Skip to content

Commit

Permalink
Compiler: correct to handle instance variable assignment inside block…
Browse files Browse the repository at this point in the history
… on global (#4324)

* Compiler: correct to handle instance variable assignment inside block on global
Fix #4323 (comment)
  • Loading branch information
makenowjust authored and bcardiff committed May 26, 2017
1 parent e270317 commit 3961dd0
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 0 deletions.
35 changes: 35 additions & 0 deletions spec/compiler/semantic/instance_var_spec.cr
Expand Up @@ -4685,4 +4685,39 @@ describe "Semantic: instance var" do
{Foo.new.@never_nil, Bar.new.@never_nil}
)) { tuple_of([int32, int32]) }
end

it "errors if assigning instance variable at top level block" do
assert_error %(
def foo
yield
end
foo do
@foo = 1
end
),
"can't use instance variables at the top level"
end

it "errors when assigning instance variable at top level block" do

This comment has been minimized.

Copy link
@faultyserver

faultyserver May 27, 2017

This seems like a duplicate of the previous test. Is it supposed to test something different?

This comment has been minimized.

Copy link
@RX14

RX14 Jun 3, 2017

Contributor

Just bumping this so that it doesn't get lost. Looks duplicate to me.

assert_error %(
def foo
yield
end
foo do
@foo = 1
end
),
"can't use instance variables at the top level"
end

it "errors when assigning instance variable at top level control block" do
assert_error %(
if true
@foo = 1
end
),
"can't use instance variables at the top level"
end
end
7 changes: 7 additions & 0 deletions src/compiler/crystal/semantic/main_visitor.cr
Expand Up @@ -779,6 +779,13 @@ module Crystal
def type_assign(target : InstanceVar, value, node)
# Check if this is an instance variable initializer
unless @scope
# `InstanceVar` assignment appered in block is not checked
# by `Crystal::InstanceVarsInitializerVisitor` because this block
# may be passed to a macro. So, it checks here.
if current_type.is_a?(Program) || current_type.is_a?(FileModule)
node.raise "can't use instance variables at the top level"
end

# Already handled by InstanceVarsInitializerVisitor
return
end
Expand Down

0 comments on commit 3961dd0

Please sign in to comment.