Browse Source

Allow arbitrary chaining of () and []

master
Dylan Baker 4 years ago
parent
commit
9a77ac219b
2 changed files with 38 additions and 11 deletions
  1. 11
    10
      lib/ahem/parser.rb
  2. 27
    1
      spec/parser_spec.rb

+ 11
- 10
lib/ahem/parser.rb View File

@@ -284,16 +284,17 @@ class Parser
284 284
         raise "Unexpected token #{token.type}"
285 285
       end
286 286
 
287
-    while @current_token.type == TokenKinds::LPAREN
288
-      args = arguments
289
-      expr = AST::FunctionCall.new(expr, args)
290
-    end
291
-
292
-    while @current_token.type == TokenKinds::LBRACKET
293
-      eat(TokenKinds::LBRACKET)
294
-      key = expression
295
-      eat(TokenKinds::RBRACKET)
296
-      expr = AST::Index.new(expr, key)
287
+    while [TokenKinds::LPAREN, TokenKinds::LBRACKET].include?(@current_token.type)
288
+      case @current_token.type
289
+      when TokenKinds::LPAREN
290
+        args = arguments
291
+        expr = AST::FunctionCall.new(expr, args)
292
+      when TokenKinds::LBRACKET
293
+        eat(TokenKinds::LBRACKET)
294
+        key = expression
295
+        eat(TokenKinds::RBRACKET)
296
+        expr = AST::Index.new(expr, key)
297
+      end
297 298
     end
298 299
 
299 300
     expr

+ 27
- 1
spec/parser_spec.rb View File

@@ -464,7 +464,33 @@ RSpec.describe Parser do
464 464
             [],
465 465
           ),
466 466
           []
467
-        )        
467
+        )
468
+      ]
469
+    )
470
+  end
471
+
472
+  it 'allows arbitrarily chaining function calls and indexes' do
473
+    expect(parse('func()[0]()[1][2]();')).to eq(
474
+      [
475
+        AST::FunctionCall.new(
476
+          AST::Index.new(
477
+            AST::Index.new(
478
+              AST::FunctionCall.new(
479
+                AST::Index.new(
480
+                  AST::FunctionCall.new(
481
+                    AST::Identifier.new('func'),
482
+                    []
483
+                  ),
484
+                  AST::Number.new(0.0)
485
+                ),
486
+                []
487
+              ),
488
+              AST::Number.new(1.0)
489
+            ),
490
+            AST::Number.new(2.0)
491
+          ),
492
+          []
493
+        )
468 494
       ]
469 495
     )
470 496
   end

Loading…
Cancel
Save