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
 module Chervil::AST
1
 module Chervil::AST
2
+  require "chervil/ast/identifier"
2
   require "chervil/ast/number"
3
   require "chervil/ast/number"
3
 end
4
 end

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

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
         if match = source.match(/^[0-9]+(\.[0-9]+)?/)
31
         if match = source.match(/^[0-9]+(\.[0-9]+)?/)
32
           advance(match[0].size)
32
           advance(match[0].size)
33
           Token.new(:number, match[0])
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
           advance(match[0].size)
35
           advance(match[0].size)
36
           Token.new(:identifier, match[0])
36
           Token.new(:identifier, match[0])
37
         end
37
         end

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

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

+ 5
- 1
spec/parser_spec.rb View File

7
     end
7
     end
8
 
8
 
9
     it 'parses a number' do
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
     end
15
     end
12
   end
16
   end
13
 end
17
 end

Loading…
Cancel
Save