Skip to content

Commit 81793b1

Browse files
committed
Use exception to handle exit instead of exiting the process directly
1 parent 9d6b05b commit 81793b1

File tree

4 files changed

+23
-9
lines changed

4 files changed

+23
-9
lines changed

spec/spec_helper.cr

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -24,12 +24,16 @@ def run_lit_in_process(*args)
2424
end
2525

2626
def run_lit(file)
27-
result = nil
27+
status = Process::Status.new(0)
2828
full_output = output_of {
29-
result, _ = Lit::Lit.run(File.read(file))
29+
begin
30+
result = Lit::Lit.run_file(file)
31+
status = Process::Status.new(result.ok? ? 0 : 1)
32+
rescue e : Lit::Interpreter::Exit
33+
status = Process::Status.new(e.status.to_i)
34+
end
3035
}
3136

32-
status = Process::Status.new(result ? 0 : 1)
3337
{status, full_output}
3438
end
3539

src/lit.cr

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -26,10 +26,14 @@ module Lit
2626
end
2727
end
2828

29-
if opts.first?
30-
exit(Lit.run_file(opts.first).to_i)
31-
else
32-
Lit.run_repl
29+
begin
30+
if opts.first?
31+
exit(Lit.run_file(opts.first).to_i)
32+
else
33+
Lit.run_repl
34+
end
35+
rescue e : ::Lit::Interpreter::Exit
36+
exit(e.status.to_i)
3337
end
3438
end
3539
end

src/lit/interpreter.cr

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,12 @@ module Lit
3232
def initialize(@value); end
3333
end
3434

35+
class Exit < Exception
36+
getter status : Int64
37+
38+
def initialize(@status); end
39+
end
40+
3541
class Next < Exception; end
3642

3743
getter environment # current environment

src/lit/stdlib/native.cr

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -70,9 +70,9 @@ module Lit
7070
}),
7171
::Lit::Native::Fn.new("exit", 0..1, ->(interpreter : Interpreter, arguments : ::Array(Value), token : Token) : Value {
7272
if arguments.empty?
73-
exit
73+
raise Interpreter::Exit.new(0)
7474
elsif arguments[0].is_a?(Int64)
75-
exit(arguments[0].as(Int64).to_i32)
75+
raise Interpreter::Exit.new(arguments[0].as(Int64).to_i32)
7676
else
7777
raise RuntimeError.new(token, "Expected number as the first argument, got #{interpreter.type_of(arguments[0])}.")
7878
end

0 commit comments

Comments
 (0)