Skip to content

Commit 19ab95f

Browse files
committed
Parse expressions with parentheses
1 parent 2a5de46 commit 19ab95f

File tree

2 files changed

+29
-0
lines changed

2 files changed

+29
-0
lines changed

lib/expression_parser.rb

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,15 @@ def parse
3838
identifier = tokenizer.identifier
3939

4040
Variable.new(identifier)
41+
when Tokenizer::SYMBOL
42+
fail 'Not an opening parenthesis' unless tokenizer.symbol == '('
43+
tokenizer.advance
44+
45+
node = parse
46+
47+
fail 'Not a closing parenthesis' unless tokenizer.token_type == Tokenizer::SYMBOL && tokenizer.symbol == ')'
48+
49+
node
4150
end
4251

4352
return left_node unless tokenizer.has_more_tokens?

spec/unit/expression_parser_spec.rb

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -76,6 +76,26 @@
7676
push constant 2
7777
push constant 3
7878
add
79+
add
80+
VM
81+
end
82+
83+
it 'emits VM code for compound binary expressions with parentheses' do
84+
tokenizer = Tokenizer.new('(1 + 2) + 3')
85+
tokenizer.advance
86+
87+
symbol_table = SymbolTable.new
88+
89+
result = ExpressionParser.new(tokenizer).parse
90+
output = StringIO.new
91+
vm_writer = VMWriter.new(output)
92+
result.emit(vm_writer, symbol_table)
93+
94+
expect(output.string).to eq(<<-VM)
95+
push constant 1
96+
push constant 2
97+
add
98+
push constant 3
7999
add
80100
VM
81101
end

0 commit comments

Comments
 (0)