Browse Source

Parse property access/method calls

master
Dylan Baker 5 years ago
parent
commit
bbfd7cc4d7
4 changed files with 43 additions and 1 deletions
  1. 1
    0
      lib/ahem/ast.rb
  2. 12
    0
      lib/ahem/ast/property.rb
  3. 5
    1
      lib/ahem/parser.rb
  4. 25
    0
      spec/parser_spec.rb

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

@@ -18,6 +18,7 @@ module AST
18 18
   require 'ahem/ast/number'
19 19
   require 'ahem/ast/operators'
20 20
   require 'ahem/ast/property_declaration'
21
+  require 'ahem/ast/property'
21 22
   require 'ahem/ast/string'
22 23
   require 'ahem/ast/unary'
23 24
   require 'ahem/ast/variable_declaration'

+ 12
- 0
lib/ahem/ast/property.rb View File

@@ -0,0 +1,12 @@
1
+class AST::Property
2
+  attr_reader :object, :name
3
+
4
+  def initialize(object, name)
5
+    @object = object
6
+    @name = name
7
+  end
8
+
9
+  def ==(other)
10
+    other.is_a?(AST::Property) && other.object == @object && other.name == @name
11
+  end
12
+end

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

@@ -284,7 +284,7 @@ class Parser
284 284
         raise "Unexpected token #{token.type}"
285 285
       end
286 286
 
287
-    while [TokenKinds::LPAREN, TokenKinds::LBRACKET].include?(@current_token.type)
287
+    while [TokenKinds::LPAREN, TokenKinds::LBRACKET, TokenKinds::HASH].include?(@current_token.type)
288 288
       case @current_token.type
289 289
       when TokenKinds::LPAREN
290 290
         args = arguments
@@ -294,6 +294,10 @@ class Parser
294 294
         key = expression
295 295
         eat(TokenKinds::RBRACKET)
296 296
         expr = AST::Index.new(expr, key)
297
+      when TokenKinds::HASH
298
+        eat(TokenKinds::HASH)
299
+        property = identifier
300
+        expr = AST::Property.new(expr, property)
297 301
       end
298 302
     end
299 303
 

+ 25
- 0
spec/parser_spec.rb View File

@@ -494,4 +494,29 @@ RSpec.describe Parser do
494 494
       ]
495 495
     )
496 496
   end
497
+
498
+  it 'parses property access' do
499
+    expect(parse('hello#world;')).to eq(
500
+      [
501
+        AST::Property.new(
502
+          AST::Identifier.new('hello'),
503
+          AST::Identifier.new('world'),
504
+        ),
505
+      ]
506
+    )
507
+  end
508
+
509
+  it 'parses allows calling properties (methods)' do
510
+    expect(parse('hello#world();')).to eq(
511
+      [
512
+        AST::FunctionCall.new(
513
+          AST::Property.new(
514
+            AST::Identifier.new('hello'),
515
+            AST::Identifier.new('world'),
516
+          ),
517
+          []          
518
+        )
519
+      ]
520
+    )
521
+  end
497 522
 end

Loading…
Cancel
Save