Kaynağa Gözat

Test scoping

master
Dylan Baker 5 yıl önce
ebeveyn
işleme
da7881db9f
2 değiştirilmiş dosya ile 42 ekleme ve 0 silme
  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 Dosyayı Görüntüle

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

+ 41
- 0
spec/ast/function_call_spec.rb Dosyayı Görüntüle

@@ -86,4 +86,45 @@ RSpec.describe AST::FunctionCall do
86 86
       ).execute(env)
87 87
     ).to eq(120.0)
88 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 130
 end

Loading…
İptal
Kaydet