From 88a4b9f10d24e613332ab8cfcd271b762246236f Mon Sep 17 00:00:00 2001
From: Ary Borenszweig <aborenszweig@manas.com.ar>
Date: Mon, 28 Jul 2014 16:12:06 -0300
Subject: [PATCH] Fixed some issues with consts

---
 spec/compiler/codegen/const_spec.cr        | 14 ++++++++++++++
 spec/compiler/type_inference/const_spec.cr | 20 ++++++++++++++++++++
 src/compiler/crystal/type_inference.cr     | 12 +++++++-----
 3 files changed, 41 insertions(+), 5 deletions(-)

diff --git a/spec/compiler/codegen/const_spec.cr b/spec/compiler/codegen/const_spec.cr
index 4dec644edf..d9288c2d06 100644
--- a/spec/compiler/codegen/const_spec.cr
+++ b/spec/compiler/codegen/const_spec.cr
@@ -186,4 +186,18 @@ describe "Codegen: const" do
       Bar.new.bar
       ").to_i.should eq(1)
   end
+
+  it "codegens two consts with same variable name" do
+    run("
+      A = begin
+            a = 1
+          end
+
+      B = begin
+            a = 2.3
+          end
+
+      (A + B).to_i
+      ").to_i.should eq(3)
+  end
 end
diff --git a/spec/compiler/type_inference/const_spec.cr b/spec/compiler/type_inference/const_spec.cr
index 4779cb4711..df73e59f7f 100755
--- a/spec/compiler/type_inference/const_spec.cr
+++ b/spec/compiler/type_inference/const_spec.cr
@@ -115,4 +115,24 @@ describe "Type inference: const" do
       foo 1
       ") { char }
   end
+
+  it "doesn't crash with const used in initialize (bug)" do
+    assert_type("
+      COCO = init_coco
+
+      def init_coco
+        1
+      end
+
+      class Foo
+        def initialize
+          COCO
+        end
+      end
+
+      Foo.new
+
+      COCO
+      ") { int32 }
+  end
 end
diff --git a/src/compiler/crystal/type_inference.cr b/src/compiler/crystal/type_inference.cr
index 5af6a7b0e8..6b92249b1d 100644
--- a/src/compiler/crystal/type_inference.cr
+++ b/src/compiler/crystal/type_inference.cr
@@ -1485,11 +1485,13 @@ module Crystal
       case type
       when Const
         unless type.value.type?
-          old_types, old_scope, old_vars, old_meta_vars, old_type_lookup = @types, @scope, @vars, @meta_vars, @type_lookup
-          @types, @scope, @vars, @meta_vars, @type_lookup = type.scope_types, type.scope, MetaVars.new, MetaVars.new, nil
-          type.value.accept self
-          type.vars = @meta_vars
-          @types, @scope, @vars, @meta_vars, @type_lookup = old_types, old_scope, old_vars, old_meta_vars, old_type_lookup
+          meta_vars = MetaVars.new
+          dummy_def = Def.new("const", [] of Arg)
+          type_visitor = TypeVisitor.new(@mod, meta_vars, dummy_def)
+          type_visitor.types = type.scope_types
+          type_visitor.scope = type.scope
+          type.value.accept type_visitor
+          type.vars = meta_vars
         end
         node.target_const = type
         node.bind_to type.value
-- 
GitLab