-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathparser.go
135 lines (114 loc) · 2.24 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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
package make
import (
"go/scanner"
"io"
"github.com/unmango/go-make/ast"
"github.com/unmango/go-make/token"
)
type Parser struct {
s *Scanner
file *token.File
errors scanner.ErrorList
pos token.Pos
tok token.Token // one token look-ahead
lit string // token literal
}
func NewParser(r io.Reader) *Parser {
s := NewScanner(r)
s.Scan() // TODO: Cleaner priming
return &Parser{
s: s,
file: &token.File{},
tok: s.Token(),
lit: s.Literal(),
}
}
func (p *Parser) ParseFile() (*ast.File, error) {
f := p.parseFile()
if p.errors.Len() > 0 {
p.errors.Sort()
return nil, p.errors.Err()
} else {
return f, nil
}
}
func (p *Parser) expect(tok token.Token) token.Pos {
pos := p.pos
if p.tok != tok {
p.error(pos, "expected '"+tok.String()+"'")
}
p.next()
return pos
}
func (p *Parser) error(pos token.Pos, msg string) {
epos := p.file.Position(pos)
p.errors.Add(epos, msg)
}
func (p *Parser) next() {
if p.s.Scan() {
// TODO: p.pos
p.tok, p.lit = p.s.Token(), p.s.Literal()
} else {
p.tok = token.EOF
}
}
func (p *Parser) parseFile() *ast.File {
if p.errors.Len() > 0 {
return nil
}
var rules []*ast.Rule
for p.tok != token.EOF {
rules = append(rules, p.parseRule())
}
return &ast.File{
Comments: []*ast.CommentGroup{},
Rules: rules,
FileStart: token.Pos(p.file.Base()),
FileEnd: token.Pos(p.file.Base() + p.file.Size()),
}
}
func (p *Parser) parseRule() *ast.Rule {
if p.tok != token.IDENT {
p.expect(token.IDENT)
return nil
}
var targets []ast.FileName
for p.tok != token.COLON && p.tok != token.EOF {
targets = append(targets, p.parseFileName())
}
var colon token.Pos
if p.tok == token.COLON {
colon = p.pos
p.next()
} else {
p.expect(token.COLON)
}
return &ast.Rule{
Targets: &ast.TargetList{
List: targets,
},
Colon: colon,
Pipe: token.NoPos,
Semi: token.NoPos,
PreReqs: &ast.PreReqList{},
Recipes: []*ast.Recipe{},
}
}
func (p *Parser) parseFileName() ast.FileName {
return &ast.LiteralFileName{
Name: p.parseIdent(),
}
}
func (p *Parser) parseIdent() *ast.Ident {
pos, name := p.pos, "_"
if p.tok == token.IDENT {
name = p.lit
p.next()
} else {
p.expect(token.IDENT)
}
return &ast.Ident{
NamePos: pos,
Name: name,
}
}