Skip to content

Commit

Permalink
Error if using return inside a constant's value (#6347)
Browse files Browse the repository at this point in the history
  • Loading branch information
asterite authored and sdogruyol committed Jul 7, 2018
1 parent 13edef6 commit fa8a586
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 0 deletions.
13 changes: 13 additions & 0 deletions spec/compiler/semantic/const_spec.cr
Original file line number Diff line number Diff line change
Expand Up @@ -360,4 +360,17 @@ describe "Semantic: const" do
),
"A is not a type, it's a constant"
end

it "errors if using return inside constant value (#5391)" do
assert_error %(
class Foo
A = begin
return if 1 == 2
end
end
Foo::A
),
"can't return from constant"
end
end
6 changes: 6 additions & 0 deletions src/compiler/crystal/semantic/main_visitor.cr
Original file line number Diff line number Diff line change
Expand Up @@ -86,6 +86,7 @@ module Crystal
# ```
property last_block_kind : Symbol?
property? inside_ensure : Bool = false
property? inside_constant = false

@unreachable = false
@is_initialize = false
Expand Down Expand Up @@ -193,6 +194,7 @@ module Crystal
const_def = Def.new("const", [] of Arg)
type_visitor = MainVisitor.new(@program, meta_vars, const_def)
type_visitor.current_type = type.namespace
type_visitor.inside_constant = true
type.value.accept type_visitor

type.vars = const_def.vars
Expand Down Expand Up @@ -1727,6 +1729,10 @@ module Crystal
node.raise "can't return from ensure"
end

if inside_constant?
node.raise "can't return from constant"
end

typed_def = @typed_def || node.raise("can't return from top level")

if typed_def.captured_block?
Expand Down

0 comments on commit fa8a586

Please sign in to comment.