Browse Source

Evaluate definition/indentifier

master
Dylan Baker 5 years ago
parent
commit
fa2699e483

+ 1
- 0
lib/chervil.rb View File

@@ -1,4 +1,5 @@
1 1
 require 'chervil/ast'
2
+require 'chervil/env'
2 3
 require 'chervil/interpreter'
3 4
 require 'chervil/lexer'
4 5
 require 'chervil/parser'

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

@@ -11,5 +11,9 @@ module Chervil::AST
11 11
     def ==(other)
12 12
       @name == other.name && @value == other.value
13 13
     end
14
+
15
+    def evaluate(env)
16
+      env.set(@name.name, @value)
17
+    end
14 18
   end
15 19
 end

+ 4
- 0
lib/chervil/ast/identifier.rb View File

@@ -9,5 +9,9 @@ module Chervil::AST
9 9
     def ==(other)
10 10
       @name == other.name
11 11
     end
12
+
13
+    def evaluate(env)
14
+      env.get(@name)
15
+    end
12 16
   end
13 17
 end

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

@@ -5,7 +5,8 @@ module Chervil
5 5
     end
6 6
 
7 7
     def interpret
8
-      @tree.map(&:evaluate)
8
+      env = Env.new
9
+      @tree.map { |node| node.evaluate(env) }
9 10
     end
10 11
   end
11 12
 end

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

@@ -0,0 +1,12 @@
1
+module Chervil
2
+  RSpec.describe AST::Definition do
3
+    it 'evaluates' do
4
+      env = Env.new
5
+      AST::Definition.new(
6
+        AST::Identifier.new("x"),
7
+        AST::Number.new(5.0)
8
+      ).evaluate(env)
9
+      expect(env.get("x")).to eq(AST::Number.new(5.0))
10
+    end
11
+  end
12
+end

+ 12
- 0
spec/ast/identifier_spec.rb View File

@@ -0,0 +1,12 @@
1
+module Chervil
2
+  RSpec.describe AST::Identifier do
3
+    it 'evaluates' do
4
+      env = Env.new
5
+      identifier = AST::Identifier.new("x")
6
+      value = AST::Number.new(5.0)
7
+      definition = AST::Definition.new(identifier, value)
8
+      definition.evaluate(env)
9
+      expect(identifier.evaluate(env)).to eq(value)
10
+    end
11
+  end
12
+end

Loading…
Cancel
Save