Browse Source

Parse identifiers

master
Dylan Baker 6 years ago
parent
commit
7b554d0095
5 changed files with 27 additions and 2 deletions
  1. 1
    0
      lib/chervil/ast.rb
  2. 13
    0
      lib/chervil/ast/identifier.rb
  3. 1
    1
      lib/chervil/lexer.rb
  4. 7
    0
      lib/chervil/parser.rb
  5. 5
    1
      spec/parser_spec.rb

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

@@ -1,3 +1,4 @@
1 1
 module Chervil::AST
2
+  require "chervil/ast/identifier"
2 3
   require "chervil/ast/number"
3 4
 end

+ 13
- 0
lib/chervil/ast/identifier.rb View File

@@ -0,0 +1,13 @@
1
+module Chervil::AST
2
+  class Identifier
3
+    attr_reader :name
4
+
5
+    def initialize(name)
6
+      @name = name
7
+    end
8
+
9
+    def ==(other)
10
+      @name == other.name
11
+    end
12
+  end
13
+end

+ 1
- 1
lib/chervil/lexer.rb View File

@@ -31,7 +31,7 @@ module Chervil
31 31
         if match = source.match(/^[0-9]+(\.[0-9]+)?/)
32 32
           advance(match[0].size)
33 33
           Token.new(:number, match[0])
34
-        elsif match = source.match(/^[a-z!$%&*\/:<=>?~_^][a-z0-9@!$%&*\/:<=>?~_^,+\-]*/)
34
+        elsif match = source.match(/^[a-z!$%&*\/:<=>?~_^+][a-z0-9@!$%&*\/:<=>?~_^,\-]*/)
35 35
           advance(match[0].size)
36 36
           Token.new(:identifier, match[0])
37 37
         end

+ 7
- 0
lib/chervil/parser.rb View File

@@ -16,9 +16,16 @@ module Chervil
16 16
     def expr
17 17
       if @current_token.type == :number
18 18
         constant
19
+      elsif @current_token.type == :identifier
20
+        identifier
19 21
       end
20 22
     end
21 23
 
24
+    def identifier
25
+      identifier = eat(:identifier)
26
+      AST::Identifier.new(identifier.value)
27
+    end
28
+
22 29
     def constant
23 30
       case @current_token.type
24 31
       when :number

+ 5
- 1
spec/parser_spec.rb View File

@@ -7,7 +7,11 @@ module Chervil
7 7
     end
8 8
 
9 9
     it 'parses a number' do
10
-      expect(parse("1").first).to eq(AST::Number.new(1.0))
10
+      expect(parse('1').first).to eq(AST::Number.new(1.0))
11
+    end
12
+
13
+    it 'parses an identifier' do
14
+      expect(parse('+').first).to eq(AST::Identifier.new('+'))
11 15
     end
12 16
   end
13 17
 end

Loading…
Cancel
Save