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
     end
13
     end
14
 
14
 
15
     def evaluate(env)
15
     def evaluate(env)
16
+      @value = value.evaluate(env) if value.is_a?(Identifier)
17
+      return @value if @value.is_a?(::Chervil::Error)
16
       env.set(@name.name, @value)
18
       env.set(@name.name, @value)
17
       nil
19
       nil
18
     end
20
     end

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

6
     end
6
     end
7
 
7
 
8
     def interpret
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
     end
14
     end
11
   end
15
   end
12
 end
16
 end

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

8
       ).evaluate(env)
8
       ).evaluate(env)
9
       expect(env.get("x")).to eq(AST::Number.new(5.0))
9
       expect(env.get("x")).to eq(AST::Number.new(5.0))
10
     end
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
   end
22
   end
12
 end
23
 end

Loading…
Cancel
Save