Browse Source

Don't allow binding to an unbound variable

master
Dylan Baker 5 years ago
parent
commit
21bf43c0e0
3 changed files with 18 additions and 1 deletions
  1. 2
    0
      lib/chervil/ast/definition.rb
  2. 5
    1
      lib/chervil/interpreter.rb
  3. 11
    0
      spec/ast/definition_spec.rb

+ 2
- 0
lib/chervil/ast/definition.rb View File

@@ -13,6 +13,8 @@ module Chervil::AST
13 13
     end
14 14
 
15 15
     def evaluate(env)
16
+      @value = value.evaluate(env) if value.is_a?(Identifier)
17
+      return @value if @value.is_a?(::Chervil::Error)
16 18
       env.set(@name.name, @value)
17 19
       nil
18 20
     end

+ 5
- 1
lib/chervil/interpreter.rb View File

@@ -6,7 +6,11 @@ module Chervil
6 6
     end
7 7
 
8 8
     def interpret
9
-      @tree.map { |node| node.evaluate(@env) }
9
+      @tree.map do |node|
10
+        result = node.evaluate(@env)
11
+        return [result] if result.is_a?(Error)
12
+        result
13
+      end
10 14
     end
11 15
   end
12 16
 end

+ 11
- 0
spec/ast/definition_spec.rb View File

@@ -8,5 +8,16 @@ module Chervil
8 8
       ).evaluate(env)
9 9
       expect(env.get("x")).to eq(AST::Number.new(5.0))
10 10
     end
11
+
12
+    it 'throws an error if bound to an unbound variable' do
13
+      env = Env.new
14
+      result = AST::Definition.new(
15
+        AST::Identifier.new("x"),
16
+        AST::Identifier.new("y"),
17
+      ).evaluate(env)
18
+      expect(result).to eq(
19
+        ::Chervil::Error.new("unbound variable y")
20
+      )
21
+    end
11 22
   end
12 23
 end

Loading…
Cancel
Save