6 "github.com/apparentlymart/go-textseg/textseg"
7 "github.com/hashicorp/hcl2/hcl"
10 //go:generate stringer -type tokenType scanner.go
14 tokenBraceO tokenType = '{'
15 tokenBraceC tokenType = '}'
16 tokenBrackO tokenType = '['
17 tokenBrackC tokenType = ']'
18 tokenComma tokenType = ','
19 tokenColon tokenType = ':'
20 tokenKeyword tokenType = 'K'
21 tokenString tokenType = 'S'
22 tokenNumber tokenType = 'N'
23 tokenEOF tokenType = '␄'
24 tokenInvalid tokenType = 0
25 tokenEquals tokenType = '=' // used only for reminding the user of JSON syntax
34 // scan returns the primary tokens for the given JSON buffer in sequence.
36 // The responsibility of this pass is to just mark the slices of the buffer
37 // as being of various types. It is lax in how it interprets the multi-byte
38 // token types keyword, string and number, preferring to capture erroneous
39 // extra bytes that we presume the user intended to be part of the token
40 // so that we can generate more helpful diagnostics in the parser.
41 func scan(buf []byte, start pos) []token {
46 tokens = append(tokens, token{
49 Range: posRange(p, p),
54 buf, p = skipWhitespace(buf, p)
57 tokens = append(tokens, token{
60 Range: posRange(p, p),
69 case first == '{' || first == '}' || first == '[' || first == ']' || first == ',' || first == ':' || first == '=':
72 tokens = append(tokens, token{
73 Type: tokenType(first),
75 Range: posRange(start, p),
80 tokBuf, buf, p = scanString(buf, p)
81 tokens = append(tokens, token{
84 Range: posRange(start, p),
86 case byteCanStartNumber(first):
88 tokBuf, buf, p = scanNumber(buf, p)
89 tokens = append(tokens, token{
92 Range: posRange(start, p),
94 case byteCanStartKeyword(first):
96 tokBuf, buf, p = scanKeyword(buf, p)
97 tokens = append(tokens, token{
100 Range: posRange(start, p),
103 tokens = append(tokens, token{
106 Range: start.Range(1, 1),
108 // If we've encountered an invalid then we might as well stop
109 // scanning since the parser won't proceed beyond this point.
115 func byteCanStartNumber(b byte) bool {
117 // We are slightly more tolerant than JSON requires here since we
118 // expect the parser will make a stricter interpretation of the
119 // number bytes, but we specifically don't allow 'e' or 'E' here
120 // since we want the scanner to treat that as the start of an
121 // invalid keyword instead, to produce more intelligible error messages.
122 case '-', '+', '.', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9':
129 func scanNumber(buf []byte, start pos) ([]byte, []byte, pos) {
130 // The scanner doesn't check that the sequence of digit-ish bytes is
131 // in a valid order. The parser must do this when decoding a number
136 for i = 0; i < len(buf); i++ {
138 case '-', '+', '.', 'e', 'E', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9':
145 return buf[:i], buf[i:], p
148 func byteCanStartKeyword(b byte) bool {
150 // We allow any sequence of alphabetical characters here, even though
151 // JSON is more constrained, so that we can collect what we presume
152 // the user intended to be a single keyword and then check its validity
153 // in the parser, where we can generate better diagnostics.
154 // So e.g. we want to be able to say:
155 // unrecognized keyword "True". Did you mean "true"?
156 case isAlphabetical(b):
163 func scanKeyword(buf []byte, start pos) ([]byte, []byte, pos) {
167 for i = 0; i < len(buf); i++ {
170 case isAlphabetical(b) || b == '_':
177 return buf[:i], buf[i:], p
180 func scanString(buf []byte, start pos) ([]byte, []byte, pos) {
181 // The scanner doesn't validate correct use of escapes, etc. It pays
182 // attention to escapes only for the purpose of identifying the closing
183 // quote character. It's the parser's responsibility to do proper
186 // The scanner also doesn't specifically detect unterminated string
187 // literals, though they can be identified in the parser by checking if
188 // the final byte in a string token is the double-quote character.
190 // Skip the opening quote symbol
217 // Advance by one grapheme cluster, so that we consider each
218 // grapheme to be a "column".
219 // Ignoring error because this scanner cannot produce errors.
220 advance, _, _ := textseg.ScanGraphemeClusters(buf[i:], true)
222 p.Pos.Byte += advance
229 return buf[:i], buf[i:], p
232 func skipWhitespace(buf []byte, start pos) ([]byte, pos) {
236 for i = 0; i < len(buf); i++ {
246 // For the purpose of line/column counting we consider a
247 // carriage return to take up no space, assuming that it will
248 // be paired up with a newline (on Windows, for example) that
249 // will account for both of them.
252 // We arbitrarily count a tab as if it were two spaces, because
253 // we need to choose _some_ number here. This means any system
254 // that renders code on-screen with markers must itself treat
255 // tabs as a pair of spaces for rendering purposes, or instead
256 // use the byte offset and back into its own column position.
271 func (p *pos) Range(byteLen, charLen int) hcl.Range {
275 end.Column += charLen
277 Filename: p.Filename,
283 func posRange(start, end pos) hcl.Range {
285 Filename: start.Filename,
291 func (t token) GoString() string {
292 return fmt.Sprintf("json.token{json.%s, []byte(%q), %#v}", t.Type, t.Bytes, t.Range)
295 func isAlphabetical(b byte) bool {
296 return (b >= 'a' && b <= 'z') || (b >= 'A' && b <= 'Z')