Debian Codegraph @

parser/pageparser/pagelexer.go

raw
1 // Copyright 2018 The Hugo Authors. All rights reserved.
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 // http://www.apache.org/licenses/LICENSE-2.0
7 //
8 // Unless required by applicable law or agreed to in writing, software
9 // distributed under the License is distributed on an "AS IS" BASIS,
10 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11 // See the License for the specific language governing permissions and
12 // limitations under the License.
13
14 package pageparser
15
16 import (
17 "bytes"
18 "fmt"
19 "unicode"
20 "unicode/utf8"
21 "unique"
22 )
23
24 const eof = -1
25
26 // returns the next state in scanner.
27 type stateFunc func(*pageLexer) stateFunc
28
29 type pageLexer struct {
30 input []byte
31 stateStart stateFunc
32 state stateFunc
33 pos int // input position
34 start int // item start position
35 width int // width of last element
36
37 // Contains lexers for shortcodes and other main section
38 // elements.
39 sectionHandlers *sectionHandlers
40
41 cfg Config
42
43 // The summary divider to look for.
44 summaryDivider []byte
45 // Set when we have parsed any summary divider
46 summaryDividerChecked bool
47
48 lexerShortcodeState
49
50 // items delivered to client
51 items Items
52
53 // error delivered to the client
54 err error
55 }
56
57 // Implement the Result interface
58 func (l *pageLexer) Iterator() *Iterator {
59 return NewIterator(l.items)
60 }
61
62 func (l *pageLexer) Input() []byte {
63 return l.input
64 }
65
66 type Config struct {
67 NoFrontMatter bool
68 NoSummaryDivider bool
69 }
70
71 // note: the input position here is normally 0 (start), but
72 // can be set if position of first shortcode is known
73 func newPageLexer(input []byte, stateStart stateFunc, cfg Config) *pageLexer {
74 lexer := &pageLexer{
75 input: input,
76 stateStart: stateStart,
77 summaryDivider: summaryDivider,
78 cfg: cfg,
79 lexerShortcodeState: lexerShortcodeState{
80 currLeftDelimItem: tLeftDelimScNoMarkup,
81 currRightDelimItem: tRightDelimScNoMarkup,
82 openShortcodes: make(map[unique.Handle[string]]bool),
83 },
84 items: make([]Item, 0, 5),
85 }
86
87 lexer.sectionHandlers = createSectionHandlers(lexer)
88
89 return lexer
90 }
91
92 // main loop
93 func (l *pageLexer) run() *pageLexer {
94 for l.state = l.stateStart; l.state != nil; {
95 l.state = l.state(l)
96 }
97 return l
98 }
99
100 // Page syntax
101 var (
102 byteOrderMark = '\ufeff'
103 summaryDivider = []byte("<!--more-->")
104 summaryDividerOrg = []byte("# more")
105 delimTOML = []byte("+++")
106 delimYAML = []byte("---")
107 delimOrg = []byte("#+")
108 )
109
110 func (l *pageLexer) next() rune {
111 if l.pos >= len(l.input) {
112 l.width = 0
113 return eof
114 }
115
116 runeValue, runeWidth := utf8.DecodeRune(l.input[l.pos:])
117 l.width = runeWidth
118 l.pos += l.width
119
120 return runeValue
121 }
122
123 // peek, but no consume
124 func (l *pageLexer) peek() rune {
125 r := l.next()
126 l.backup()
127 return r
128 }
129
130 // steps back one
131 func (l *pageLexer) backup() {
132 l.pos -= l.width
133 }
134
135 func (l *pageLexer) append(item Item) {
136 if item.Pos() < len(l.input) {
137 item.firstByte = l.input[item.Pos()]
138 }
139 l.items = append(l.items, item)
140 }
141
142 // sends an item back to the client.
143 func (l *pageLexer) emit(t ItemType) {
144 defer func() {
145 l.start = l.pos
146 }()
147
148 if t == tText {
149 // Identify any trailing whitespace/intendation.
150 // We currently only care about the last one.
151 for i := l.pos - 1; i >= l.start; i-- {
152 b := l.input[i]
153 if b != ' ' && b != '\t' && b != '\r' && b != '\n' {
154 break
155 }
156 if i == l.start && b != '\n' {
157 l.append(Item{Type: tIndentation, low: l.start, high: l.pos})
158 return
159 } else if b == '\n' && i < l.pos-1 {
160 l.append(Item{Type: t, low: l.start, high: i + 1})
161 l.append(Item{Type: tIndentation, low: i + 1, high: l.pos})
162 return
163 } else if b == '\n' && i == l.pos-1 {
164 break
165 }
166
167 }
168 }
169
170 l.append(Item{Type: t, low: l.start, high: l.pos})
171 }
172
173 // sends a string item back to the client.
174 func (l *pageLexer) emitString(t ItemType) {
175 l.append(Item{Type: t, low: l.start, high: l.pos, isString: true})
176 l.start = l.pos
177 }
178
179 func (l *pageLexer) isEOF() bool {
180 return l.pos >= len(l.input)
181 }
182
183 // special case, do not send '\\' back to client
184 func (l *pageLexer) ignoreEscapesAndEmit(t ItemType, isString bool) {
185 i := l.start
186 k := i
187
188 var segments []lowHigh
189
190 for i < l.pos {
191 r, w := utf8.DecodeRune(l.input[i:l.pos])
192 if r == '\\' {
193 if i > k {
194 segments = append(segments, lowHigh{k, i})
195 }
196 // See issue #10236.
197 // We don't send the backslash back to the client,
198 // which makes the end parsing simpler.
199 // This means that we cannot render the AST back to be
200 // exactly the same as the input,
201 // but that was also the situation before we introduced the issue in #10236.
202 k = i + w
203 }
204 i += w
205 }
206
207 if k < l.pos {
208 segments = append(segments, lowHigh{k, l.pos})
209 }
210
211 if len(segments) > 0 {
212 l.append(Item{Type: t, segments: segments})
213 }
214
215 l.start = l.pos
216 }
217
218 // gets the current value (for debugging and error handling)
219 func (l *pageLexer) current() []byte {
220 return l.input[l.start:l.pos]
221 }
222
223 // ignore current element
224 func (l *pageLexer) ignore() {
225 l.start = l.pos
226 }
227
228 var lf = []byte("\n")
229
230 // nil terminates the parser
231 func (l *pageLexer) errorf(format string, args ...any) stateFunc {
232 l.append(Item{Type: tError, Err: fmt.Errorf(format, args...), low: l.start, high: l.pos})
233 return nil
234 }
235
236 func (l *pageLexer) consumeCRLF() bool {
237 var consumed bool
238 for _, r := range crLf {
239 if l.next() != r {
240 l.backup()
241 } else {
242 consumed = true
243 }
244 }
245 return consumed
246 }
247
248 func (l *pageLexer) consumeToSpace() {
249 for {
250 r := l.next()
251 if r == eof || isASCIISpace(r) {
252 l.backup()
253 return
254 }
255 }
256 }
257
258 func (l *pageLexer) consumeSpace() {
259 for {
260 r := l.next()
261 if r == eof || !isASCIISpace(r) {
262 l.backup()
263 return
264 }
265 }
266 }
267
268 type sectionHandlers struct {
269 l *pageLexer
270
271 // Set when none of the sections are found so we
272 // can safely stop looking and skip to the end.
273 skipAll bool
274
275 handlers []*sectionHandler
276 skipIndexes []int
277 }
278
279 func (s *sectionHandlers) skip() int {
280 if s.skipAll {
281 return -1
282 }
283
284 s.skipIndexes = s.skipIndexes[:0]
285 var shouldSkip bool
286 for _, skipper := range s.handlers {
287 idx := skipper.skip()
288 if idx != -1 {
289 shouldSkip = true
290 s.skipIndexes = append(s.skipIndexes, idx)
291 }
292 }
293
294 if !shouldSkip {
295 s.skipAll = true
296 return -1
297 }
298
299 return minIndex(s.skipIndexes...)
300 }
301
302 func createSectionHandlers(l *pageLexer) *sectionHandlers {
303 handlers := make([]*sectionHandler, 0, 2)
304
305 shortCodeHandler := &sectionHandler{
306 l: l,
307 skipFunc: func(l *pageLexer) int {
308 return l.index(leftDelimSc)
309 },
310 lexFunc: func(origin stateFunc, l *pageLexer) (stateFunc, bool) {
311 if !l.isShortCodeStart() {
312 return origin, false
313 }
314
315 if l.isInline {
316 // If we're inside an inline shortcode, the only valid shortcode markup is
317 // the markup which closes it.
318 b := l.input[l.pos+3:]
319 end := indexNonWhiteSpace(b, '/')
320 if end != len(l.input)-1 {
321 b = bytes.TrimSpace(b[end+1:])
322 if end == -1 || !bytes.HasPrefix(b, []byte(l.currShortcodeName+" ")) {
323 return l.errorf("inline shortcodes do not support nesting"), true
324 }
325 }
326 }
327
328 if l.hasPrefix(leftDelimScWithMarkup) {
329 l.currLeftDelimItem = tLeftDelimScWithMarkup
330 l.currRightDelimItem = tRightDelimScWithMarkup
331 } else {
332 l.currLeftDelimItem = tLeftDelimScNoMarkup
333 l.currRightDelimItem = tRightDelimScNoMarkup
334 }
335
336 return lexShortcodeLeftDelim, true
337 },
338 }
339
340 handlers = append(handlers, shortCodeHandler)
341
342 if !l.cfg.NoSummaryDivider {
343 summaryDividerHandler := &sectionHandler{
344 l: l,
345 skipFunc: func(l *pageLexer) int {
346 if l.summaryDividerChecked {
347 return -1
348 }
349 return l.index(l.summaryDivider)
350 },
351 lexFunc: func(origin stateFunc, l *pageLexer) (stateFunc, bool) {
352 if !l.hasPrefix(l.summaryDivider) {
353 return origin, false
354 }
355
356 l.summaryDividerChecked = true
357 l.pos += len(l.summaryDivider)
358 // This makes it a little easier to reason about later.
359 l.consumeSpace()
360 l.emit(TypeLeadSummaryDivider)
361
362 return origin, true
363 },
364 }
365
366 handlers = append(handlers, summaryDividerHandler)
367
368 }
369
370 return &sectionHandlers{
371 l: l,
372 handlers: handlers,
373 skipIndexes: make([]int, len(handlers)),
374 }
375 }
376
377 func (s *sectionHandlers) lex(origin stateFunc) stateFunc {
378 if s.skipAll {
379 return nil
380 }
381
382 if s.l.pos > s.l.start {
383 s.l.emit(tText)
384 }
385
386 for _, handler := range s.handlers {
387 if handler.skipAll {
388 continue
389 }
390
391 next, handled := handler.lexFunc(origin, handler.l)
392 if next == nil || handled {
393 return next
394 }
395 }
396
397 // Not handled by the above.
398 s.l.pos++
399
400 return origin
401 }
402
403 type sectionHandler struct {
404 l *pageLexer
405
406 // No more sections of this type.
407 skipAll bool
408
409 // Returns the index of the next match, -1 if none found.
410 skipFunc func(l *pageLexer) int
411
412 // Lex lexes the current section and returns the next state func and
413 // a bool telling if this section was handled.
414 // Note that returning nil as the next state will terminate the
415 // lexer.
416 lexFunc func(origin stateFunc, l *pageLexer) (stateFunc, bool)
417 }
418
419 func (s *sectionHandler) skip() int {
420 if s.skipAll {
421 return -1
422 }
423
424 idx := s.skipFunc(s.l)
425 if idx == -1 {
426 s.skipAll = true
427 }
428 return idx
429 }
430
431 func lexMainSection(l *pageLexer) stateFunc {
432 if l.isEOF() {
433 return lexDone
434 }
435
436 // Fast forward as far as possible.
437 skip := l.sectionHandlers.skip()
438
439 if skip == -1 {
440 l.pos = len(l.input)
441 return lexDone
442 } else if skip > 0 {
443 l.pos += skip
444 }
445
446 next := l.sectionHandlers.lex(lexMainSection)
447 if next != nil {
448 return next
449 }
450
451 l.pos = len(l.input)
452 return lexDone
453 }
454
455 func lexDone(l *pageLexer) stateFunc {
456 // Done!
457 if l.pos > l.start {
458 l.emit(tText)
459 }
460 l.emit(tEOF)
461 return nil
462 }
463
464 //lint:ignore U1000 useful for debugging
465 func (l *pageLexer) printCurrentInput() {
466 fmt.Printf("input[%d:]: %q", l.pos, string(l.input[l.pos:]))
467 }
468
469 // state helpers
470
471 func (l *pageLexer) index(sep []byte) int {
472 return bytes.Index(l.input[l.pos:], sep)
473 }
474
475 func (l *pageLexer) hasPrefix(prefix []byte) bool {
476 return bytes.HasPrefix(l.input[l.pos:], prefix)
477 }
478
479 // helper functions
480
481 // returns the min index >= 0
482 func minIndex(indices ...int) int {
483 min := -1
484
485 for _, j := range indices {
486 if j < 0 {
487 continue
488 }
489 if min == -1 {
490 min = j
491 } else if j < min {
492 min = j
493 }
494 }
495 return min
496 }
497
498 func indexNonWhiteSpace(s []byte, in rune) int {
499 idx := bytes.IndexFunc(s, func(r rune) bool {
500 return !isASCIISpace(r)
501 })
502
503 if idx == -1 {
504 return -1
505 }
506
507 r, _ := utf8.DecodeRune(s[idx:])
508 if r == in {
509 return idx
510 }
511 return -1
512 }
513
514 func isASCIISpace(r rune) bool {
515 switch r {
516 case '\t', '\n', '\v', '\f', '\r', ' ':
517 return true
518 }
519 return false
520 }
521
522 func isAlphaNumericOrHyphen(r rune) bool {
523 // let unquoted YouTube ids as positional params slip through (they contain hyphens)
524 return isAlphaNumeric(r) || r == '-'
525 }
526
527 var crLf = []rune{'\r', '\n'}
528
529 func isEndOfLine(r rune) bool {
530 return r == '\r' || r == '\n'
531 }
532
533 func isAlphaNumeric(r rune) bool {
534 return r == '_' || unicode.IsLetter(r) || unicode.IsDigit(r)
535 }