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