浏览代码

Parse strings

master
Dylan Baker 6 年前
父节点
当前提交
5a23b3dee7
共有 4 个文件被更改,包括 23 次插入3 次删除
  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 查看文件

@@ -2,4 +2,5 @@ module Chervil::AST
2 2
   require "chervil/ast/application"
3 3
   require "chervil/ast/identifier"
4 4
   require "chervil/ast/number"
5
+  require "chervil/ast/string"
5 6
 end

+ 13
- 0
lib/chervil/ast/string.rb 查看文件

@@ -0,0 +1,13 @@
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 查看文件

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

+ 4
- 0
spec/parser_spec.rb 查看文件

@@ -10,6 +10,10 @@ module Chervil
10 10
       expect(parse('1').first).to eq(AST::Number.new(1.0))
11 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 17
     it 'parses an identifier' do
14 18
       expect(parse('+').first).to eq(AST::Identifier.new('+'))
15 19
     end

正在加载...
取消
保存