1
0
mirror of https://github.com/danog/liquid.git synced 2024-12-02 16:57:50 +01:00
liquid/scanner.rl

92 lines
1.6 KiB
Plaintext
Raw Normal View History

2017-06-25 22:21:31 +02:00
// Adapted from https://github.com/mhamrah/thermostat
2017-06-25 18:36:28 +02:00
package main
2017-06-25 22:21:31 +02:00
import "fmt"
2017-06-25 18:36:28 +02:00
import "strconv"
2017-06-25 22:21:31 +02:00
%%{
machine expression;
write data;
access lex.;
variable p lex.p;
variable pe lex.pe;
}%%
2017-06-25 18:36:28 +02:00
2017-06-25 22:21:31 +02:00
type lexer struct {
data []byte
p, pe, cs int
ts, te, act int
val func(Context) interface{}
}
2017-06-26 04:00:36 +02:00
func (l* lexer) token() string {
return string(l.data[l.ts:l.te])
}
2017-06-25 22:21:31 +02:00
func newLexer(data []byte) *lexer {
lex := &lexer{
data: data,
pe: len(data),
}
%% write init;
return lex
}
func (lex *lexer) Lex(out *yySymType) int {
eof := lex.pe
tok := 0
2017-06-25 18:36:28 +02:00
%%{
2017-06-26 02:20:58 +02:00
action Bool {
tok = LITERAL
2017-06-26 04:00:36 +02:00
out.val = lex.token() == "true"
fbreak;
2017-06-26 02:20:58 +02:00
}
2017-06-25 22:21:31 +02:00
action Ident {
tok = IDENTIFIER
2017-06-26 04:00:36 +02:00
out.name = lex.token()
2017-06-25 22:21:31 +02:00
fbreak;
}
2017-06-26 13:50:53 +02:00
action Int {
tok = LITERAL
n, err := strconv.ParseInt(lex.token(), 10, 64)
if err != nil {
panic(err)
}
out.val = int(n)
2017-06-26 13:50:53 +02:00
fbreak;
}
action Float {
2017-06-26 02:20:58 +02:00
tok = LITERAL
2017-06-26 04:00:36 +02:00
n, err := strconv.ParseFloat(lex.token(), 64)
2017-06-25 22:21:31 +02:00
if err != nil {
panic(err)
}
out.val = n
2017-06-25 22:21:31 +02:00
fbreak;
}
2017-06-26 04:00:36 +02:00
action Relation { tok = RELATION; out.name = lex.token(); fbreak; }
2017-06-25 22:21:31 +02:00
ident = (alpha | '_') . (alnum | '_')* ;
2017-06-26 13:50:53 +02:00
float = '-'? (digit+ '.' digit* | '.' digit+);
2017-06-25 22:21:31 +02:00
main := |*
2017-06-26 13:50:53 +02:00
'-'? digit+ => Int;
float => Float;
[.;] | '[' | ']' => { tok = int(lex.data[lex.ts]); fbreak; };
2017-06-26 02:20:58 +02:00
("true" | "false") => Bool;
2017-06-25 22:21:31 +02:00
("==" | "!=" | ">" | ">" | ">=" | "<=") => Relation;
("and" | "or" | "contains") => Relation;
2017-06-26 02:20:58 +02:00
ident => Ident;
2017-06-25 22:21:31 +02:00
space+;
*|;
2017-06-25 18:36:28 +02:00
write exec;
2017-06-25 22:21:31 +02:00
}%%
2017-06-25 18:36:28 +02:00
2017-06-25 22:21:31 +02:00
return tok
2017-06-25 18:36:28 +02:00
}
2017-06-25 22:21:31 +02:00
func (lex *lexer) Error(e string) {
fmt.Println("error:", e)
}