Better lexer

This commit is contained in:
Tristan Hume
2013-07-24 15:19:14 -04:00
parent 76272a1afa
commit b20a594f25
+41 -13
View File
@@ -25,7 +25,7 @@ module Liquid
} }
def initialize(input) def initialize(input)
@input = input.chars.to_a @input = input
end end
def tokenize def tokenize
@@ -33,18 +33,26 @@ module Liquid
@output = [] @output = []
loop do loop do
consume_whitespace tok = next_token
c = @input[@p] return @output unless tok
@output << tok
end
end
# are we out of input? def next_token
return @output unless c consume_whitespace
c = @input[@p]
return nil unless c
if identifier?(c) if identifier?(c)
@output << consume_identifier identifier
elsif s = SPECIALS[c] elsif c == '"' || c == '\''
@output << Token[s] string_literal
@p += 1 elsif s = SPECIALS[c]
end @p += 1
Token[s]
else
raise SyntaxError, "Unexpected character #{c}."
end end
end end
@@ -56,19 +64,39 @@ module Liquid
c =~ /^\s$/ c =~ /^\s$/
end end
def consume
c = @input[@p]
@p += 1
c
end
def consume_whitespace def consume_whitespace
while whitespace?(@input[@p]) while whitespace?(@input[@p])
@p += 1 @p += 1
end end
end end
def consume_identifier def identifier
str = "" str = ""
while identifier?(@input[@p]) while identifier?(@input[@p])
str << @input[@p] str << @input[@p]
@p += 1 @p += 1
end end
Token[:identifier, str] Token[:id, str]
end end
def string_literal
quote = consume()
start = @p
while @input[@p] != quote
@p += 1
end
@p += 1 # closing quote
Token[:string, @input[start..(@p-2)]]
end
def number_literal
end end
end end