Skip to content

Commit

Permalink
Support closured vars inside Const initializer (#10478)
Browse files Browse the repository at this point in the history
* Support Const initializer typed Nil

* Support closured vars inside Const initializer

* fixup! Support Const initializer typed Nil

* fixup! Support Const initializer typed Nil
  • Loading branch information
RX14 authored Mar 16, 2021
1 parent 17f153e commit e572b56
Show file tree
Hide file tree
Showing 4 changed files with 42 additions and 5 deletions.
35 changes: 35 additions & 0 deletions spec/compiler/codegen/const_spec.cr
Original file line number Diff line number Diff line change
Expand Up @@ -533,4 +533,39 @@ describe "Codegen: const" do
a &+ Foo.x
)).to_i.should eq(6)
end

it "supports closured vars inside initializers (#10474)" do
run(%(
class Foo
def bar
3
end
end
def func(&block : -> Int32)
block.call
end
CONST = begin
foo = Foo.new
func do
foo.bar
end
end
CONST
)).to_i.should eq(3)
end

it "supports storing function returning nil" do
run(%(
def foo
"foo"
nil
end
CONST = foo
CONST.nil?
)).to_b.should eq(true)
end
end
8 changes: 5 additions & 3 deletions src/compiler/crystal/codegen/const.cr
Original file line number Diff line number Diff line change
Expand Up @@ -100,7 +100,7 @@ class Crystal::CodeGenVisitor
# Start with fresh variables
context.vars = LLVMVars.new

alloca_vars const.vars
alloca_vars const.fake_def.try(&.vars), const.fake_def
request_value do
accept const.value
end
Expand Down Expand Up @@ -153,7 +153,7 @@ class Crystal::CodeGenVisitor
# Start with fresh variables
context.vars = LLVMVars.new

alloca_vars const.vars
alloca_vars const.fake_def.try(&.vars), const.fake_def

request_value do
accept const.value
Expand All @@ -173,7 +173,9 @@ class Crystal::CodeGenVisitor
end
else
global.initializer = llvm_type(const.value.type).null
store @last, global
unless const.value.type.nil_type? || const.value.type.void?
store @last, global
end
end

ret
Expand Down
2 changes: 1 addition & 1 deletion src/compiler/crystal/semantic/main_visitor.cr
Original file line number Diff line number Diff line change
Expand Up @@ -189,7 +189,7 @@ module Crystal
type_visitor.inside_constant = true
type.value.accept type_visitor

type.vars = const_def.vars
type.fake_def = const_def
type.visitor = self
type.used = true

Expand Down
2 changes: 1 addition & 1 deletion src/compiler/crystal/types.cr
Original file line number Diff line number Diff line change
Expand Up @@ -3155,7 +3155,7 @@ module Crystal
# saved under a type types like any other type.
class Const < NamedType
property value : ASTNode
property vars : MetaVars?
property fake_def : Def?
property? used = false
property? visited = false

Expand Down

0 comments on commit e572b56

Please sign in to comment.