Browse Source

Parse strings

master
Dylan Baker 6 years ago
parent
commit
5a23b3dee7
4 changed files with 23 additions and 3 deletions
  1. 1
    0
      lib/chervil/ast.rb
  2. 13
    0
      lib/chervil/ast/string.rb
  3. 5
    3
      lib/chervil/parser.rb
  4. 4
    0
      spec/parser_spec.rb

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

2
   require "chervil/ast/application"
2
   require "chervil/ast/application"
3
   require "chervil/ast/identifier"
3
   require "chervil/ast/identifier"
4
   require "chervil/ast/number"
4
   require "chervil/ast/number"
5
+  require "chervil/ast/string"
5
 end
6
 end

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

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

+ 5
- 3
lib/chervil/parser.rb View File

1
 module Chervil
1
 module Chervil
2
-  class Parser
3
-    def initialize(lexer)
2
+  class Parser def initialize(lexer)
4
       @lexer = lexer
3
       @lexer = lexer
5
       @tree = Array.new
4
       @tree = Array.new
6
       @current_token = @lexer.get_next_token
5
       @current_token = @lexer.get_next_token
14
     end
13
     end
15
 
14
 
16
     def expr
15
     def expr
17
-      if @current_token.type == :number
16
+      if [:string, :number].include?(@current_token.type)
18
         constant
17
         constant
19
       elsif @current_token.type == :identifier
18
       elsif @current_token.type == :identifier
20
         identifier
19
         identifier
47
       when :number
46
       when :number
48
         token = eat(:number)
47
         token = eat(:number)
49
         AST::Number.new(token.value.to_f)
48
         AST::Number.new(token.value.to_f)
49
+      when :string
50
+        token = eat(:string)
51
+        AST::String.new(token.value)
50
       end
52
       end
51
     end
53
     end
52
 
54
 

+ 4
- 0
spec/parser_spec.rb View File

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
11
     end
12
 
12
 
13
+    it 'parses a string' do
14
+      expect(parse('"hello world"').first).to eq(AST::String.new('hello world'))
15
+    end
16
+
13
     it 'parses an identifier' do
17
     it 'parses an identifier' do
14
       expect(parse('+').first).to eq(AST::Identifier.new('+'))
18
       expect(parse('+').first).to eq(AST::Identifier.new('+'))
15
     end
19
     end

Loading…
Cancel
Save