Debian Codegraph @

caddyconfig/caddyfile/lexer.go

raw symbols SCIP
1 // Copyright 2015 Matthew Holt and The Caddy Authors
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // http://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15 package caddyfile
16
17 import (
18 "bufio"
19 "bytes"
20 "fmt"
21 "io"
22 "regexp"
23 "strings"
24 "unicode"
25 )
26
27 type (
28 // lexer is a utility which can get values, token by
29 // token, from a Reader. A token is a word, and tokens
30 // are separated by whitespace. A word can be enclosed
31 // in quotes if it contains whitespace.
32 lexer struct {
33 reader *bufio.Reader
34 token Token
35 line int
36 skippedLines int
37 }
38
39 // Token represents a single parsable unit.
40 Token struct {
41 File string
42 imports []string
43 Line int
44 Text string
45 wasQuoted rune // enclosing quote character, if any
46 heredocMarker string
47 snippetName string
48 }
49 )
50
51 // Tokenize takes bytes as input and lexes it into
52 // a list of tokens that can be parsed as a Caddyfile.
53 // Also takes a filename to fill the token's File as
54 // the source of the tokens, which is important to
55 // determine relative paths for `import` directives.
56 func Tokenize(input []byte, filename string) ([]Token, error) {
57 l := lexer{}
58 if err := l.load(bytes.NewReader(input)); err != nil {
59 return nil, err
60 }
61 var tokens []Token
62 for {
63 found, err := l.next()
64 if err != nil {
65 return nil, err
66 }
67 if !found {
68 break
69 }
70 l.token.File = filename
71 tokens = append(tokens, l.token)
72 }
73 return tokens, nil
74 }
75
76 // load prepares the lexer to scan an input for tokens.
77 // It discards any leading byte order mark.
78 func (l *lexer) load(input io.Reader) error {
79 l.reader = bufio.NewReader(input)
80 l.line = 1
81
82 // discard byte order mark, if present
83 firstCh, _, err := l.reader.ReadRune()
84 if err != nil {
85 return err
86 }
87 if firstCh != 0xFEFF {
88 err := l.reader.UnreadRune()
89 if err != nil {
90 return err
91 }
92 }
93
94 return nil
95 }
96
97 // next loads the next token into the lexer.
98 // A token is delimited by whitespace, unless
99 // the token starts with a quotes character (")
100 // in which case the token goes until the closing
101 // quotes (the enclosing quotes are not included).
102 // Inside quoted strings, quotes may be escaped
103 // with a preceding \ character. No other chars
104 // may be escaped. The rest of the line is skipped
105 // if a "#" character is read in. Returns true if
106 // a token was loaded; false otherwise.
107 func (l *lexer) next() (bool, error) {
108 var val []rune
109 var comment, quoted, btQuoted, inHeredoc, heredocEscaped, escaped bool
110 var heredocMarker string
111
112 makeToken := func(quoted rune) bool {
113 l.token.Text = string(val)
114 l.token.wasQuoted = quoted
115 l.token.heredocMarker = heredocMarker
116 return true
117 }
118
119 for {
120 // Read a character in; if err then if we had
121 // read some characters, make a token. If we
122 // reached EOF, then no more tokens to read.
123 // If no EOF, then we had a problem.
124 ch, _, err := l.reader.ReadRune()
125 if err != nil {
126 if len(val) > 0 {
127 if inHeredoc {
128 return false, fmt.Errorf("incomplete heredoc <<%s on line #%d, expected ending marker %s", heredocMarker, l.line+l.skippedLines, heredocMarker)
129 }
130
131 return makeToken(0), nil
132 }
133 if err == io.EOF {
134 return false, nil
135 }
136 return false, err
137 }
138
139 // detect whether we have the start of a heredoc
140 if (!quoted && !btQuoted) && (!inHeredoc && !heredocEscaped) &&
141 len(val) > 1 && string(val[:2]) == "<<" {
142 // a space means it's just a regular token and not a heredoc
143 if ch == ' ' {
144 return makeToken(0), nil
145 }
146
147 // skip CR, we only care about LF
148 if ch == '\r' {
149 continue
150 }
151
152 // after hitting a newline, we know that the heredoc marker
153 // is the characters after the two << and the newline.
154 // we reset the val because the heredoc is syntax we don't
155 // want to keep.
156 if ch == '\n' {
157 if len(val) == 2 {
158 return false, fmt.Errorf("missing opening heredoc marker on line #%d; must contain only alphanumeric characters, dashes and underscores; got empty string", l.line)
159 }
160
161 // check if there's too many <
162 if string(val[:3]) == "<<<" {
163 return false, fmt.Errorf("too many '<' for heredoc on line #%d; only use two, for example <<END", l.line)
164 }
165
166 heredocMarker = string(val[2:])
167 if !heredocMarkerRegexp.Match([]byte(heredocMarker)) {
168 return false, fmt.Errorf("heredoc marker on line #%d must contain only alphanumeric characters, dashes and underscores; got '%s'", l.line, heredocMarker)
169 }
170
171 inHeredoc = true
172 l.skippedLines++
173 val = nil
174 continue
175 }
176 val = append(val, ch)
177 continue
178 }
179
180 // if we're in a heredoc, all characters are read as-is
181 if inHeredoc {
182 val = append(val, ch)
183
184 if ch == '\n' {
185 l.skippedLines++
186 }
187
188 // check if we're done, i.e. that the last few characters are the marker
189 if len(val) >= len(heredocMarker) && heredocMarker == string(val[len(val)-len(heredocMarker):]) {
190 // set the final value
191 val, err = l.finalizeHeredoc(val, heredocMarker)
192 if err != nil {
193 return false, err
194 }
195
196 // set the line counter, and make the token
197 l.line += l.skippedLines
198 l.skippedLines = 0
199 return makeToken('<'), nil
200 }
201
202 // stay in the heredoc until we find the ending marker
203 continue
204 }
205
206 // track whether we found an escape '\' for the next
207 // iteration to be contextually aware
208 if !escaped && !btQuoted && ch == '\\' {
209 escaped = true
210 continue
211 }
212
213 if quoted || btQuoted {
214 if quoted && escaped {
215 // all is literal in quoted area,
216 // so only escape quotes
217 if ch != '"' {
218 val = append(val, '\\')
219 }
220 escaped = false
221 } else {
222 if (quoted && ch == '"') || (btQuoted && ch == '`') {
223 return makeToken(ch), nil
224 }
225 }
226 // allow quoted text to wrap continue on multiple lines
227 if ch == '\n' {
228 l.line += 1 + l.skippedLines
229 l.skippedLines = 0
230 }
231 // collect this character as part of the quoted token
232 val = append(val, ch)
233 continue
234 }
235
236 if unicode.IsSpace(ch) {
237 // ignore CR altogether, we only actually care about LF (\n)
238 if ch == '\r' {
239 continue
240 }
241 // end of the line
242 if ch == '\n' {
243 // newlines can be escaped to chain arguments
244 // onto multiple lines; else, increment the line count
245 if escaped {
246 l.skippedLines++
247 escaped = false
248 } else {
249 l.line += 1 + l.skippedLines
250 l.skippedLines = 0
251 }
252 // comments (#) are single-line only
253 comment = false
254 }
255 // any kind of space means we're at the end of this token
256 if len(val) > 0 {
257 return makeToken(0), nil
258 }
259 continue
260 }
261
262 // comments must be at the start of a token,
263 // in other words, preceded by space or newline
264 if ch == '#' && len(val) == 0 {
265 comment = true
266 }
267 if comment {
268 continue
269 }
270
271 if len(val) == 0 {
272 l.token = Token{Line: l.line}
273 if ch == '"' {
274 quoted = true
275 continue
276 }
277 if ch == '`' {
278 btQuoted = true
279 continue
280 }
281 }
282
283 if escaped {
284 // allow escaping the first < to skip the heredoc syntax
285 if ch == '<' {
286 heredocEscaped = true
287 } else {
288 val = append(val, '\\')
289 }
290 escaped = false
291 }
292
293 val = append(val, ch)
294 }
295 }
296
297 // finalizeHeredoc takes the runes read as the heredoc text and the marker,
298 // and processes the text to strip leading whitespace, returning the final
299 // value without the leading whitespace.
300 func (l *lexer) finalizeHeredoc(val []rune, marker string) ([]rune, error) {
301 stringVal := string(val)
302
303 // find the last newline of the heredoc, which is where the contents end
304 lastNewline := strings.LastIndex(stringVal, "\n")
305
306 // collapse the content, then split into separate lines
307 lines := strings.Split(stringVal[:lastNewline+1], "\n")
308
309 // figure out how much whitespace we need to strip from the front of every line
310 // by getting the string that precedes the marker, on the last line
311 paddingToStrip := stringVal[lastNewline+1 : len(stringVal)-len(marker)]
312
313 // iterate over each line and strip the whitespace from the front
314 var out string
315 for lineNum, lineText := range lines[:len(lines)-1] {
316 if lineText == "" || lineText == "\r" {
317 out += "\n"
318 continue
319 }
320
321 // find an exact match for the padding
322 index := strings.Index(lineText, paddingToStrip)
323
324 // if the padding doesn't match exactly at the start then we can't safely strip
325 if index != 0 {
326 cleanLineText := strings.TrimRight(lineText, "\r\n")
327 return nil, fmt.Errorf("mismatched leading whitespace in heredoc <<%s on line #%d [%s], expected whitespace [%s] to match the closing marker", marker, l.line+lineNum+1, cleanLineText, paddingToStrip)
328 }
329
330 // strip, then append the line, with the newline, to the output.
331 // also removes all "\r" because Windows.
332 out += strings.ReplaceAll(lineText[len(paddingToStrip):]+"\n", "\r", "")
333 }
334
335 // Remove the trailing newline from the loop
336 if len(out) > 0 && out[len(out)-1] == '\n' {
337 out = out[:len(out)-1]
338 }
339
340 // return the final value
341 return []rune(out), nil
342 }
343
344 // Quoted returns true if the token was enclosed in quotes
345 // (i.e. double quotes, backticks, or heredoc).
346 func (t Token) Quoted() bool {
347 return t.wasQuoted > 0
348 }
349
350 // NumLineBreaks counts how many line breaks are in the token text.
351 func (t Token) NumLineBreaks() int {
352 lineBreaks := strings.Count(t.Text, "\n")
353 if t.wasQuoted == '<' {
354 // heredocs have an extra linebreak because the opening
355 // delimiter is on its own line and is not included in the
356 // token Text itself, and the trailing newline is removed.
357 lineBreaks += 2
358 }
359 return lineBreaks
360 }
361
362 // Clone returns a deep copy of the token.
363 func (t Token) Clone() Token {
364 return Token{
365 File: t.File,
366 imports: append([]string{}, t.imports...),
367 Line: t.Line,
368 Text: t.Text,
369 wasQuoted: t.wasQuoted,
370 heredocMarker: t.heredocMarker,
371 snippetName: t.snippetName,
372 }
373 }
374
375 var heredocMarkerRegexp = regexp.MustCompile("^[A-Za-z0-9_-]+$")
376
377 // isNextOnNewLine tests whether t2 is on a different line from t1
378 func isNextOnNewLine(t1, t2 Token) bool {
379 // If the second token is from a different file,
380 // we can assume it's from a different line
381 if t1.File != t2.File {
382 return true
383 }
384
385 // If the second token is from a different import chain,
386 // we can assume it's from a different line
387 if len(t1.imports) != len(t2.imports) {
388 return true
389 }
390 for i, im := range t1.imports {
391 if im != t2.imports[i] {
392 return true
393 }
394 }
395
396 // If the first token (incl line breaks) ends
397 // on a line earlier than the next token,
398 // then the second token is on a new line
399 return t1.Line+t1.NumLineBreaks() < t2.Line
400 }