-
-
Notifications
You must be signed in to change notification settings - Fork 65
/
parser.go
293 lines (269 loc) · 7.87 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
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
// Copyright (c) 2017 Ernest Micklei
//
// MIT License
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
package proto
import (
"bytes"
"errors"
"fmt"
"io"
"runtime"
"strconv"
"strings"
"text/scanner"
)
// Parser represents a parser.
type Parser struct {
debug bool
scanner *scanner.Scanner
buf *nextValues
scannerErrors []error
}
// nextValues is to capture the result of next()
type nextValues struct {
pos scanner.Position
tok token
lit string
}
// NewParser returns a new instance of Parser.
func NewParser(r io.Reader) *Parser {
s := new(scanner.Scanner)
s.Init(r)
s.Mode = scanner.ScanIdents | scanner.ScanFloats | scanner.ScanStrings | scanner.ScanRawStrings | scanner.ScanComments
p := &Parser{scanner: s}
s.Error = p.handleScanError
return p
}
// handleScanError is called from the underlying Scanner
func (p *Parser) handleScanError(s *scanner.Scanner, msg string) {
p.scannerErrors = append(p.scannerErrors,
fmt.Errorf("go scanner error at %v = %v", s.Position, msg))
}
// ignoreIllegalEscapesWhile is called for scanning constants of an option.
// Such content can have a syntax that is not acceptable by the Go scanner.
// This temporary installs a handler that ignores only one type of error: illegal char escape
func (p *Parser) ignoreIllegalEscapesWhile(block func()) {
// during block call change error handler
p.scanner.Error = func(s *scanner.Scanner, msg string) {
// this catches both "illegal char escape" <= go1.12 and "invalid char escape" go1.13
if strings.Contains(msg, "char escape") { // too bad there is no constant for this in scanner pkg
return
}
p.handleScanError(s, msg)
}
block()
// restore
p.scanner.Error = p.handleScanError
}
// Parse parses a proto definition. May return a parse or scanner error.
func (p *Parser) Parse() (*Proto, error) {
proto := new(Proto)
if p.scanner.Filename != "" {
proto.Filename = p.scanner.Filename
}
parseError := proto.parse(p)
// see if it was a scanner error
if len(p.scannerErrors) > 0 {
buf := new(bytes.Buffer)
for _, each := range p.scannerErrors {
fmt.Fprintln(buf, each)
}
return proto, errors.New(buf.String())
}
return proto, parseError
}
// Filename is for reporting. Optional.
func (p *Parser) Filename(f string) {
p.scanner.Filename = f
}
const stringWithSingleQuote = "'"
// next returns the next token using the scanner or drain the buffer.
func (p *Parser) next() (pos scanner.Position, tok token, lit string) {
if p.buf != nil {
// consume buf
vals := *p.buf
p.buf = nil
return vals.pos, vals.tok, vals.lit
}
ch := p.scanner.Scan()
if ch == scanner.EOF {
return p.scanner.Position, tEOF, ""
}
lit = p.scanner.TokenText()
// single quote needs additional scanning
if stringWithSingleQuote == lit {
return p.nextSingleQuotedString()
}
return p.scanner.Position, asToken(lit), lit
}
// pre: first single quote has been read
func (p *Parser) nextSingleQuotedString() (pos scanner.Position, tok token, lit string) {
var ch rune
p.ignoreErrorsWhile(func() { ch = p.scanner.Scan() })
if ch == scanner.EOF {
return p.scanner.Position, tEOF, ""
}
// string inside single quote
lit = p.scanner.TokenText()
if stringWithSingleQuote == lit {
// empty single quoted string
return p.scanner.Position, tIDENT, "''"
}
// scan for partial tokens until actual closing single-quote(') token
for {
p.ignoreErrorsWhile(func() { ch = p.scanner.Scan() })
if ch == scanner.EOF {
return p.scanner.Position, tEOF, ""
}
partial := p.scanner.TokenText()
if partial == "'" {
break
}
lit += partial
}
// end quote expected
if stringWithSingleQuote != p.scanner.TokenText() {
p.unexpected(lit, "'", p)
}
return p.scanner.Position, tIDENT, fmt.Sprintf("'%s'", lit)
}
func (p *Parser) ignoreErrorsWhile(block func()) {
// during block call change error handler which ignores it all
p.scanner.Error = func(s *scanner.Scanner, msg string) { return }
block()
// restore
p.scanner.Error = p.handleScanError
}
// nextPut sets the buffer
func (p *Parser) nextPut(pos scanner.Position, tok token, lit string) {
p.buf = &nextValues{pos, tok, lit}
}
func (p *Parser) unexpected(found, expected string, obj interface{}) error {
debug := ""
if p.debug {
_, file, line, _ := runtime.Caller(1)
debug = fmt.Sprintf(" at %s:%d (with %#v)", file, line, obj)
}
return fmt.Errorf("%v: found %q but expected [%s]%s", p.scanner.Position, found, expected, debug)
}
func (p *Parser) nextInteger() (i int, err error) {
_, tok, lit := p.next()
if "-" == lit {
i, err = p.nextInteger()
return i * -1, err
}
if tok != tNUMBER {
return 0, errors.New("non integer")
}
if strings.HasPrefix(lit, "0x") || strings.HasPrefix(lit, "0X") {
// hex decode
i64, err := strconv.ParseInt(lit, 0, 64)
return int(i64), err
}
i, err = strconv.Atoi(lit)
return
}
// nextIdentifier consumes tokens which may have one or more dot separators (namespaced idents).
func (p *Parser) nextIdentifier() (pos scanner.Position, tok token, lit string) {
pos, tok, lit = p.nextIdent(false)
if tDOT == tok {
// leading dot allowed
pos, tok, lit = p.nextIdent(false)
lit = "." + lit
}
return
}
func (p *Parser) nextMessageLiteralFieldName() (pos scanner.Position, tok token, lit string) {
pos, tok, lit = p.nextIdent(true)
if tok == tLEFTSQUARE {
pos, tok, lit = p.nextIdent(true)
_, _, _ = p.next() // consume right square
}
return
}
// nextTypeName implements the Packages and Name Resolution for finding the name of the type.
// Valid examples:
// .google.protobuf.Empty
// stream T must return tSTREAM
// optional int32 must return tOPTIONAL
// Bogus must return Bogus
func (p *Parser) nextTypeName() (pos scanner.Position, tok token, lit string) {
pos, tok, lit = p.next()
startPos := pos
fullLit := lit
// leading dot allowed
if tDOT == tok {
pos, tok, lit = p.next()
fullLit = fmt.Sprintf(".%s", lit)
}
// type can be namespaced more
for {
r := p.peekNonWhitespace()
if '.' != r {
break
}
p.next() // consume dot
pos, tok, lit = p.next()
fullLit = fmt.Sprintf("%s.%s", fullLit, lit)
tok = tIDENT
}
return startPos, tok, fullLit
}
func (p *Parser) nextIdent(keywordStartAllowed bool) (pos scanner.Position, tok token, lit string) {
pos, tok, lit = p.next()
if tIDENT != tok {
// can be keyword
if !(isKeyword(tok) && keywordStartAllowed) {
return
}
// proceed with keyword as first literal
}
startPos := pos
fullLit := lit
// see if identifier is namespaced
for {
r := p.peekNonWhitespace()
if '.' != r {
break
}
p.next() // consume dot
pos, tok, lit := p.next()
if tIDENT != tok && !isKeyword(tok) {
p.nextPut(pos, tok, lit)
break
}
fullLit = fmt.Sprintf("%s.%s", fullLit, lit)
}
return startPos, tIDENT, fullLit
}
func (p *Parser) peekNonWhitespace() rune {
r := p.scanner.Peek()
if r == scanner.EOF {
return r
}
if isWhitespace(r) {
// consume it
p.scanner.Next()
return p.peekNonWhitespace()
}
return r
}