Browse Source

Test scoping

master
Dylan Baker 5 years ago
parent
commit
da7881db9f
2 changed files with 42 additions and 0 deletions
  1. 1
    0
      lib/ahem/ast/function_call.rb
  2. 41
    0
      spec/ast/function_call_spec.rb

+ 1
- 0
lib/ahem/ast/function_call.rb View File

12
   end
12
   end
13
 
13
 
14
   def execute(env)
14
   def execute(env)
15
+    env = Environment.new(env)
15
     function = env.get(@function.name)
16
     function = env.get(@function.name)
16
 
17
 
17
     if function.is_a?(AST::FunctionDefinition)
18
     if function.is_a?(AST::FunctionDefinition)

+ 41
- 0
spec/ast/function_call_spec.rb View File

86
       ).execute(env)
86
       ).execute(env)
87
     ).to eq(120.0)
87
     ).to eq(120.0)
88
   end
88
   end
89
+
90
+  # This is equivalent to the program
91
+  #
92
+  # function add_one(n) {
93
+  #   n + 1;
94
+  # }
95
+  # add_one(5);
96
+  # print(n);
97
+  #
98
+  # This test is ensuring that `n` is not still defined outside the scope of
99
+  # add_one after the function finishes executing
100
+  it 'destroys variables when they go out of scope' do
101
+    env = Environment.new
102
+    AST::FunctionDefinition.new(
103
+      AST::Identifier.new('add_one'),
104
+      [AST::Identifier.new('n')],
105
+      AST::Block.new([
106
+        AST::Binary.new(
107
+          AST::Operators::ADD,
108
+          AST::Identifier.new('n'),
109
+          AST::Number.new(1.0)
110
+        )
111
+      ])
112
+    ).execute(env)
113
+
114
+    AST::FunctionCall.new(
115
+      AST::Identifier.new('add_one'),
116
+      [
117
+        AST::Number.new(5)
118
+      ]
119
+    ).execute(env)
120
+
121
+    expect do
122
+      AST::FunctionCall.new(
123
+        AST::Identifier.new('print'),
124
+        [
125
+          AST::Identifier.new('n')
126
+        ]
127
+      ).execute(env)
128
+    end.to raise_error('Undefined variable n')
129
+  end
89
 end
130
 end

Loading…
Cancel
Save