forked from extrame/goyymmdd
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathparser.go
70 lines (63 loc) · 1.38 KB
/
parser.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
package yymmdd
// Parse creates a new parser with the recommended
// parameters.
func Parse(tokens []LexToken) Formatter {
p := &parser{
tokens: tokens,
pos: -1,
}
p.initState = initialParserState
return p.run()
}
// run starts the statemachine
func (p *parser) run() Formatter {
var f Formatter
for state := p.initState; state != nil; {
state = state(p, &f)
}
return f
}
// parserState represents the state of the scanner
// as a function that returns the next state.
type parserState func(*parser, *Formatter) parserState
// nest returns what the next token AND
// advances p.pos.
func (p *parser) next() *LexToken {
if p.pos >= len(p.tokens)-1 {
return nil
}
p.pos += 1
return &p.tokens[p.pos]
}
// the parser type
type parser struct {
tokens []LexToken
pos int
serial int
initState parserState
}
// the starting state for parsing
func initialParserState(p *parser, f *Formatter) parserState {
var t *LexToken
for t = p.next(); t[0] != T_EOF; t = p.next() {
var item ItemFormatter
switch t[0] {
case T_YEAR_MARK:
item = new(YearFormatter)
case T_MONTH_MARK:
item = new(MonthFormatter)
case T_DAY_MARK:
item = new(DayFormatter)
case T_RAW_MARK:
item = new(basicFormatter)
}
item.setOriginal(t[1])
f.Items = append(f.Items, item)
}
if len(t[1]) > 0 {
r := new(basicFormatter)
r.origin = t[1]
f.Items = append(f.Items, r)
}
return nil
}