Browse Source

Allow grouping expressions with parentheses

master
Dylan Baker 5 years ago
parent
commit
0d7aa28346
2 changed files with 21 additions and 0 deletions
  1. 5
    0
      lib/ahem/parser.rb
  2. 16
    0
      spec/parser_spec.rb

+ 5
- 0
lib/ahem/parser.rb View File

237
       array
237
       array
238
     when TokenKinds::LBRACE
238
     when TokenKinds::LBRACE
239
       hash
239
       hash
240
+    when TokenKinds::LPAREN
241
+      eat(TokenKinds::LPAREN)
242
+      e = expression
243
+      eat(TokenKinds::RPAREN)
244
+      e
240
     else
245
     else
241
       raise "Unexpected token #{token.type}"
246
       raise "Unexpected token #{token.type}"
242
     end
247
     end

+ 16
- 0
spec/parser_spec.rb View File

360
     expect(parse('-1;')).to eq([AST::Unary.new(:-, AST::Number.new(1.0))])
360
     expect(parse('-1;')).to eq([AST::Unary.new(:-, AST::Number.new(1.0))])
361
     expect(parse('!true;')).to eq([AST::Unary.new(:!, AST::Boolean.new(true))])
361
     expect(parse('!true;')).to eq([AST::Unary.new(:!, AST::Boolean.new(true))])
362
   end
362
   end
363
+
364
+  it 'gives parenthetical expressions higher precedence' do
365
+    expect(parse('(1 + 2) * 3;')).to eq(
366
+      [
367
+        AST::Binary.new(
368
+          AST::Operators::MULTIPLY,
369
+          AST::Binary.new(
370
+            AST::Operators::ADD,
371
+            AST::Number.new(1.0),
372
+            AST::Number.new(2.0)
373
+          ),
374
+          AST::Number.new(3.0),
375
+        )
376
+      ]
377
+    )
378
+  end
363
 end
379
 end

Loading…
Cancel
Save