Debian Codegraph @

parser.go

raw symbols SCIP
1 // Copyright (c) 2017 Ernest Micklei
2 //
3 // MIT License
4 //
5 // Permission is hereby granted, free of charge, to any person obtaining
6 // a copy of this software and associated documentation files (the
7 // "Software"), to deal in the Software without restriction, including
8 // without limitation the rights to use, copy, modify, merge, publish,
9 // distribute, sublicense, and/or sell copies of the Software, and to
10 // permit persons to whom the Software is furnished to do so, subject to
11 // the following conditions:
12 //
13 // The above copyright notice and this permission notice shall be
14 // included in all copies or substantial portions of the Software.
15 //
16 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
17 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
18 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
19 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
20 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
21 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
22 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
23
24 package proto
25
26 import (
27 "bytes"
28 "errors"
29 "fmt"
30 "io"
31 "runtime"
32 "strconv"
33 "strings"
34 "text/scanner"
35 )
36
37 // Parser represents a parser.
38 type Parser struct {
39 debug bool
40 scanner *scanner.Scanner
41 buf *nextValues
42 scannerErrors []error
43 }
44
45 // nextValues is to capture the result of next()
46 type nextValues struct {
47 pos scanner.Position
48 tok token
49 lit string
50 }
51
52 // NewParser returns a new instance of Parser.
53 func NewParser(r io.Reader) *Parser {
54 s := new(scanner.Scanner)
55 s.Init(r)
56 s.Mode = scanner.ScanIdents | scanner.ScanFloats | scanner.ScanStrings | scanner.ScanRawStrings | scanner.ScanComments
57 p := &Parser{scanner: s}
58 s.Error = p.handleScanError
59 return p
60 }
61
62 // handleScanError is called from the underlying Scanner
63 func (p *Parser) handleScanError(s *scanner.Scanner, msg string) {
64 p.scannerErrors = append(p.scannerErrors,
65 fmt.Errorf("go scanner error at %v = %v", s.Position, msg))
66 }
67
68 // ignoreIllegalEscapesWhile is called for scanning constants of an option.
69 // Such content can have a syntax that is not acceptable by the Go scanner.
70 // This temporary installs a handler that ignores only one type of error: illegal char escape
71 func (p *Parser) ignoreIllegalEscapesWhile(block func()) {
72 // during block call change error handler
73 p.scanner.Error = func(s *scanner.Scanner, msg string) {
74 // this catches both "illegal char escape" <= go1.12 and "invalid char escape" go1.13
75 if strings.Contains(msg, "char escape") { // too bad there is no constant for this in scanner pkg
76 return
77 }
78 p.handleScanError(s, msg)
79 }
80 block()
81 // restore
82 p.scanner.Error = p.handleScanError
83 }
84
85 // Parse parses a proto definition. May return a parse or scanner error.
86 func (p *Parser) Parse() (*Proto, error) {
87 proto := new(Proto)
88 if p.scanner.Filename != "" {
89 proto.Filename = p.scanner.Filename
90 }
91 parseError := proto.parse(p)
92 // see if it was a scanner error
93 if len(p.scannerErrors) > 0 {
94 buf := new(bytes.Buffer)
95 for _, each := range p.scannerErrors {
96 fmt.Fprintln(buf, each)
97 }
98 return proto, errors.New(buf.String())
99 }
100 return proto, parseError
101 }
102
103 // Filename is for reporting. Optional.
104 func (p *Parser) Filename(f string) {
105 p.scanner.Filename = f
106 }
107
108 const stringWithSingleQuote = "'"
109
110 // next returns the next token using the scanner or drain the buffer.
111 func (p *Parser) next() (pos scanner.Position, tok token, lit string) {
112 if p.buf != nil {
113 // consume buf
114 vals := *p.buf
115 p.buf = nil
116 return vals.pos, vals.tok, vals.lit
117 }
118 ch := p.scanner.Scan()
119 if ch == scanner.EOF {
120 return p.scanner.Position, tEOF, ""
121 }
122 lit = p.scanner.TokenText()
123 // single quote needs additional scanning
124 if stringWithSingleQuote == lit {
125 return p.nextSingleQuotedString()
126 }
127 return p.scanner.Position, asToken(lit), lit
128 }
129
130 // pre: first single quote has been read
131 func (p *Parser) nextSingleQuotedString() (pos scanner.Position, tok token, lit string) {
132 // Save current scanner mode and temporarily disable comment scanning
133 // to prevent // inside single quotes from being treated as comments
134 savedMode := p.scanner.Mode
135 p.scanner.Mode = scanner.ScanIdents | scanner.ScanFloats | scanner.ScanStrings | scanner.ScanRawStrings
136 defer func() { p.scanner.Mode = savedMode }()
137
138 var ch rune
139 p.ignoreErrorsWhile(func() { ch = p.scanner.Scan() })
140 if ch == scanner.EOF {
141 return p.scanner.Position, tEOF, ""
142 }
143 // string inside single quote
144 lit = p.scanner.TokenText()
145 if stringWithSingleQuote == lit {
146 // empty single quoted string
147 return p.scanner.Position, tIDENT, "''"
148 }
149
150 // scan for partial tokens until actual closing single-quote(') token
151 for {
152 p.ignoreErrorsWhile(func() { ch = p.scanner.Scan() })
153
154 if ch == scanner.EOF {
155 return p.scanner.Position, tEOF, ""
156 }
157
158 partial := p.scanner.TokenText()
159 if partial == "'" {
160 break
161 }
162 lit += partial
163 }
164 // end quote expected
165 if stringWithSingleQuote != p.scanner.TokenText() {
166 p.unexpected(lit, "'", p)
167 }
168 return p.scanner.Position, tIDENT, fmt.Sprintf("'%s'", lit)
169 }
170
171 func (p *Parser) ignoreErrorsWhile(block func()) {
172 // during block call change error handler which ignores it all
173 p.scanner.Error = func(s *scanner.Scanner, msg string) { return }
174 block()
175 // restore
176 p.scanner.Error = p.handleScanError
177 }
178
179 // nextPut sets the buffer
180 func (p *Parser) nextPut(pos scanner.Position, tok token, lit string) {
181 p.buf = &nextValues{pos, tok, lit}
182 }
183
184 func (p *Parser) unexpected(found, expected string, obj interface{}) error {
185 debug := ""
186 if p.debug {
187 _, file, line, _ := runtime.Caller(1)
188 debug = fmt.Sprintf(" at %s:%d (with %#v)", file, line, obj)
189 }
190 return fmt.Errorf("%v: found %q but expected [%s]%s", p.scanner.Position, found, expected, debug)
191 }
192
193 func (p *Parser) nextInteger() (i int, err error) {
194 _, tok, lit := p.next()
195 if "-" == lit {
196 i, err = p.nextInteger()
197 return i * -1, err
198 }
199 if tok != tNUMBER {
200 return 0, errors.New("non integer")
201 }
202 if strings.HasPrefix(lit, "0x") || strings.HasPrefix(lit, "0X") {
203 // hex decode
204 i64, err := strconv.ParseInt(lit, 0, 64)
205 return int(i64), err
206 }
207 i, err = strconv.Atoi(lit)
208 return
209 }
210
211 // nextIdentifier consumes tokens which may have one or more dot separators (namespaced idents).
212 func (p *Parser) nextIdentifier() (pos scanner.Position, tok token, lit string) {
213 pos, tok, lit = p.nextIdent(false)
214 if tDOT == tok {
215 // leading dot allowed
216 pos, tok, lit = p.nextIdent(false)
217 lit = "." + lit
218 }
219 return
220 }
221
222 func (p *Parser) nextMessageLiteralFieldName() (pos scanner.Position, tok token, lit string) {
223 pos, tok, lit = p.nextIdent(true)
224 if tok == tLEFTSQUARE {
225 pos, tok, lit = p.nextIdent(true)
226 _, _, _ = p.next() // consume right square
227 }
228 return
229 }
230
231 // nextTypeName implements the Packages and Name Resolution for finding the name of the type.
232 // Valid examples:
233 // .google.protobuf.Empty
234 // stream T must return tSTREAM
235 // optional int32 must return tOPTIONAL
236 // Bogus must return Bogus
237 func (p *Parser) nextTypeName() (pos scanner.Position, tok token, lit string) {
238 pos, tok, lit = p.next()
239 startPos := pos
240 fullLit := lit
241 // leading dot allowed
242 if tDOT == tok {
243 pos, tok, lit = p.next()
244 fullLit = fmt.Sprintf(".%s", lit)
245 }
246 // type can be namespaced more
247 for {
248 r := p.peekNonWhitespace()
249 if '.' != r {
250 break
251 }
252 p.next() // consume dot
253 pos, tok, lit = p.next()
254 fullLit = fmt.Sprintf("%s.%s", fullLit, lit)
255 tok = tIDENT
256 }
257 return startPos, tok, fullLit
258 }
259
260 func (p *Parser) nextIdent(keywordStartAllowed bool) (pos scanner.Position, tok token, lit string) {
261 pos, tok, lit = p.next()
262 if tIDENT != tok {
263 // can be keyword
264 if !(isKeyword(tok) && keywordStartAllowed) {
265 return
266 }
267 // proceed with keyword as first literal
268 }
269 startPos := pos
270 fullLit := lit
271 // see if identifier is namespaced
272 for {
273 r := p.peekNonWhitespace()
274 if r != '.' {
275 break
276 }
277 p.next() // consume dot
278 fullLit += "."
279 pos, tok, lit := p.next()
280 if tIDENT != tok && !isKeyword(tok) {
281 p.nextPut(pos, tok, lit)
282 break
283 }
284 fullLit += lit
285 }
286 return startPos, tIDENT, fullLit
287 }
288
289 func (p *Parser) peekNonWhitespace() rune {
290 r := p.scanner.Peek()
291 if r == scanner.EOF {
292 return r
293 }
294 if isWhitespace(r) {
295 // consume it
296 p.scanner.Next()
297 return p.peekNonWhitespace()
298 }
299 return r
300 }
301
302 // https://protobuf.dev/reference/protobuf/proto3-spec/
303 func (p *Parser) nextFullIdent(keywordStartAllowed bool) (pos scanner.Position, tok token, lit string) {
304 pos, tok, lit = p.next()
305 if tIDENT != tok {
306 // can be keyword
307 if !(isKeyword(tok) && keywordStartAllowed) {
308 return
309 }
310 // proceed with keyword as first literal
311 }
312 fullIdent := lit
313 for {
314 r := p.peekNonWhitespace()
315 if r != '.' {
316 break
317 }
318 p.next() // consume dot
319 pos, tok, lit = p.nextFullIdent(true)
320 if tok != tIDENT {
321 p.nextPut(pos, tok, lit)
322 break
323 }
324 fullIdent = fmt.Sprintf("%s.%s", fullIdent, lit)
325 }
326 return pos, tIDENT, fullIdent
327 }