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