Debian Codegraph @

dependencies/pkg/mod/github.com/goccy/[email protected]/scanner/scanner.go

raw
1 package scanner
2
3 import (
4 "errors"
5 "io"
6 "strings"
7
8 "github.com/goccy/go-yaml/token"
9 )
10
11 // IndentState state for indent
12 type IndentState int
13
14 const (
15 // IndentStateEqual equals previous indent
16 IndentStateEqual IndentState = iota
17 // IndentStateUp more indent than previous
18 IndentStateUp
19 // IndentStateDown less indent than previous
20 IndentStateDown
21 // IndentStateKeep uses not indent token
22 IndentStateKeep
23 )
24
25 // Scanner holds the scanner's internal state while processing a given text.
26 // It can be allocated as part of another data structure but must be initialized via Init before use.
27 type Scanner struct {
28 source []rune
29 sourcePos int
30 sourceSize int
31 // line number. This number starts from 1.
32 line int
33 // column number. This number starts from 1.
34 column int
35 // offset represents the offset from the beginning of the source.
36 offset int
37 // lastDelimColumn is the last column needed to compare indent is retained.
38 lastDelimColumn int
39 // indentNum indicates the number of spaces used for indentation.
40 indentNum int
41 // prevLineIndentNum indicates the number of spaces used for indentation at previous line.
42 prevLineIndentNum int
43 // indentLevel indicates the level of indent depth. This value does not match the column value.
44 indentLevel int
45 docStartColumn int
46 isFirstCharAtLine bool
47 isAnchor bool
48 startedFlowSequenceNum int
49 startedFlowMapNum int
50 indentState IndentState
51 savedPos *token.Position
52 }
53
54 func (s *Scanner) pos() *token.Position {
55 return &token.Position{
56 Line: s.line,
57 Column: s.column,
58 Offset: s.offset,
59 IndentNum: s.indentNum,
60 IndentLevel: s.indentLevel,
61 }
62 }
63
64 func (s *Scanner) bufferedToken(ctx *Context) *token.Token {
65 if s.savedPos != nil {
66 tk := ctx.bufferedToken(s.savedPos)
67 s.savedPos = nil
68 return tk
69 }
70 line := s.line
71 column := s.column - len(ctx.buf)
72 level := s.indentLevel
73 if ctx.isSaveIndentMode() {
74 line -= s.newLineCount(ctx.buf)
75 column = strings.Index(string(ctx.obuf), string(ctx.buf)) + 1
76 // Since we are in a literal, folded or raw folded
77 // we can use the indent level from the last token.
78 last := ctx.lastToken()
79 if last != nil { // The last token should never be nil here.
80 level = last.Position.IndentLevel + 1
81 }
82 }
83 return ctx.bufferedToken(&token.Position{
84 Line: line,
85 Column: column,
86 Offset: s.offset - len(ctx.buf),
87 IndentNum: s.indentNum,
88 IndentLevel: level,
89 })
90 }
91
92 func (s *Scanner) progressColumn(ctx *Context, num int) {
93 s.column += num
94 s.offset += num
95 ctx.progress(num)
96 }
97
98 func (s *Scanner) progressLine(ctx *Context) {
99 s.prevLineIndentNum = s.indentNum
100 s.column = 1
101 s.line++
102 s.offset++
103 s.indentNum = 0
104 s.isFirstCharAtLine = true
105 s.isAnchor = false
106 ctx.progress(1)
107 }
108
109 func (s *Scanner) isNewLineChar(c rune) bool {
110 if c == '\n' {
111 return true
112 }
113 if c == '\r' {
114 return true
115 }
116 return false
117 }
118
119 func (s *Scanner) newLineCount(src []rune) int {
120 size := len(src)
121 cnt := 0
122 for i := 0; i < size; i++ {
123 c := src[i]
124 switch c {
125 case '\r':
126 if i+1 < size && src[i+1] == '\n' {
127 i++
128 }
129 cnt++
130 case '\n':
131 cnt++
132 }
133 }
134 return cnt
135 }
136
137 func (s *Scanner) updateIndentLevel() {
138 if s.prevLineIndentNum < s.indentNum {
139 s.indentLevel++
140 } else if s.prevLineIndentNum > s.indentNum {
141 if s.indentLevel > 0 {
142 s.indentLevel--
143 }
144 }
145 }
146
147 func (s *Scanner) updateIndentState(ctx *Context) {
148 if s.lastDelimColumn > 0 {
149 if s.lastDelimColumn < s.column {
150 s.indentState = IndentStateUp
151 } else {
152 // If lastDelimColumn and s.column are the same,
153 // treat as Down state since it is the same column as delimiter.
154 s.indentState = IndentStateDown
155 }
156 } else {
157 s.indentState = s.indentStateFromIndentNumDifference()
158 }
159 }
160
161 func (s *Scanner) indentStateFromIndentNumDifference() IndentState {
162 switch {
163 case s.prevLineIndentNum < s.indentNum:
164 return IndentStateUp
165 case s.prevLineIndentNum == s.indentNum:
166 return IndentStateEqual
167 default:
168 return IndentStateDown
169 }
170 }
171
172 func (s *Scanner) updateIndent(ctx *Context, c rune) {
173 if s.isFirstCharAtLine && s.isNewLineChar(c) && ctx.isDocument() {
174 return
175 }
176 if s.isFirstCharAtLine && c == ' ' {
177 s.indentNum++
178 return
179 }
180 if !s.isFirstCharAtLine {
181 s.indentState = IndentStateKeep
182 return
183 }
184 s.updateIndentLevel()
185 s.updateIndentState(ctx)
186 s.isFirstCharAtLine = false
187 }
188
189 func (s *Scanner) isChangedToIndentStateDown() bool {
190 return s.indentState == IndentStateDown
191 }
192
193 func (s *Scanner) isChangedToIndentStateUp() bool {
194 return s.indentState == IndentStateUp
195 }
196
197 func (s *Scanner) addBufferedTokenIfExists(ctx *Context) {
198 ctx.addToken(s.bufferedToken(ctx))
199 }
200
201 func (s *Scanner) breakLiteral(ctx *Context) {
202 s.docStartColumn = 0
203 ctx.breakLiteral()
204 }
205
206 func (s *Scanner) scanSingleQuote(ctx *Context) (tk *token.Token, pos int) {
207 ctx.addOriginBuf('\'')
208 srcpos := s.pos()
209 startIndex := ctx.idx + 1
210 src := ctx.src
211 size := len(src)
212 value := []rune{}
213 isFirstLineChar := false
214 isNewLine := false
215 for idx := startIndex; idx < size; idx++ {
216 if !isNewLine {
217 s.progressColumn(ctx, 1)
218 } else {
219 isNewLine = false
220 }
221 c := src[idx]
222 pos = idx + 1
223 ctx.addOriginBuf(c)
224 if s.isNewLineChar(c) {
225 value = append(value, ' ')
226 isFirstLineChar = true
227 isNewLine = true
228 s.progressLine(ctx)
229 continue
230 } else if c == ' ' && isFirstLineChar {
231 continue
232 } else if c != '\'' {
233 value = append(value, c)
234 isFirstLineChar = false
235 continue
236 }
237 if idx+1 < len(ctx.src) && ctx.src[idx+1] == '\'' {
238 // '' handle as ' character
239 value = append(value, c)
240 ctx.addOriginBuf(c)
241 idx++
242 continue
243 }
244 s.progressColumn(ctx, 1)
245 tk = token.SingleQuote(string(value), string(ctx.obuf), srcpos)
246 pos = idx - startIndex + 1
247 return
248 }
249 return
250 }
251
252 func hexToInt(b rune) int {
253 if b >= 'A' && b <= 'F' {
254 return int(b) - 'A' + 10
255 }
256 if b >= 'a' && b <= 'f' {
257 return int(b) - 'a' + 10
258 }
259 return int(b) - '0'
260 }
261
262 func hexRunesToInt(b []rune) int {
263 sum := 0
264 for i := 0; i < len(b); i++ {
265 sum += hexToInt(b[i]) << (uint(len(b)-i-1) * 4)
266 }
267 return sum
268 }
269
270 func (s *Scanner) scanDoubleQuote(ctx *Context) (tk *token.Token, pos int) {
271 ctx.addOriginBuf('"')
272 srcpos := s.pos()
273 startIndex := ctx.idx + 1
274 src := ctx.src
275 size := len(src)
276 value := []rune{}
277 isFirstLineChar := false
278 isNewLine := false
279 for idx := startIndex; idx < size; idx++ {
280 if !isNewLine {
281 s.progressColumn(ctx, 1)
282 } else {
283 isNewLine = false
284 }
285 c := src[idx]
286 pos = idx + 1
287 ctx.addOriginBuf(c)
288 if s.isNewLineChar(c) {
289 value = append(value, ' ')
290 isFirstLineChar = true
291 isNewLine = true
292 s.progressLine(ctx)
293 continue
294 } else if c == ' ' && isFirstLineChar {
295 continue
296 } else if c == '\\' {
297 isFirstLineChar = false
298 if idx+1 >= size {
299 value = append(value, c)
300 continue
301 }
302 nextChar := src[idx+1]
303 progress := 0
304 switch nextChar {
305 case 'b':
306 progress = 1
307 ctx.addOriginBuf(nextChar)
308 value = append(value, '\b')
309 case 'e':
310 progress = 1
311 ctx.addOriginBuf(nextChar)
312 value = append(value, '\x1B')
313 case 'f':
314 progress = 1
315 ctx.addOriginBuf(nextChar)
316 value = append(value, '\f')
317 case 'n':
318 progress = 1
319 ctx.addOriginBuf(nextChar)
320 value = append(value, '\n')
321 case 'r':
322 progress = 1
323 ctx.addOriginBuf(nextChar)
324 value = append(value, '\r')
325 case 'v':
326 progress = 1
327 ctx.addOriginBuf(nextChar)
328 value = append(value, '\v')
329 case 'L': // LS (#x2028)
330 progress = 1
331 ctx.addOriginBuf(nextChar)
332 value = append(value, []rune{'\xE2', '\x80', '\xA8'}...)
333 case 'N': // NEL (#x85)
334 progress = 1
335 ctx.addOriginBuf(nextChar)
336 value = append(value, []rune{'\xC2', '\x85'}...)
337 case 'P': // PS (#x2029)
338 progress = 1
339 ctx.addOriginBuf(nextChar)
340 value = append(value, []rune{'\xE2', '\x80', '\xA9'}...)
341 case '_': // #xA0
342 progress = 1
343 ctx.addOriginBuf(nextChar)
344 value = append(value, []rune{'\xC2', '\xA0'}...)
345 case '"':
346 progress = 1
347 ctx.addOriginBuf(nextChar)
348 value = append(value, nextChar)
349 case 'x':
350 progress = 3
351 if idx+progress >= size {
352 // TODO: need to return error
353 //err = errors.New("invalid escape character \\x")
354 return
355 }
356 codeNum := hexRunesToInt(src[idx+2 : idx+progress+1])
357 value = append(value, rune(codeNum))
358 case 'u':
359 progress = 5
360 if idx+progress >= size {
361 // TODO: need to return error
362 //err = errors.New("invalid escape character \\u")
363 return
364 }
365 codeNum := hexRunesToInt(src[idx+2 : idx+progress+1])
366 value = append(value, rune(codeNum))
367 case 'U':
368 progress = 9
369 if idx+progress >= size {
370 // TODO: need to return error
371 //err = errors.New("invalid escape character \\U")
372 return
373 }
374 codeNum := hexRunesToInt(src[idx+2 : idx+progress+1])
375 value = append(value, rune(codeNum))
376 case '\\':
377 progress = 1
378 ctx.addOriginBuf(nextChar)
379 value = append(value, c)
380 default:
381 value = append(value, c)
382 }
383 idx += progress
384 s.progressColumn(ctx, progress)
385 continue
386 } else if c != '"' {
387 value = append(value, c)
388 isFirstLineChar = false
389 continue
390 }
391 s.progressColumn(ctx, 1)
392 tk = token.DoubleQuote(string(value), string(ctx.obuf), srcpos)
393 pos = idx - startIndex + 1
394 return
395 }
396 return
397 }
398
399 func (s *Scanner) scanQuote(ctx *Context, ch rune) (tk *token.Token, pos int) {
400 if ch == '\'' {
401 return s.scanSingleQuote(ctx)
402 }
403 return s.scanDoubleQuote(ctx)
404 }
405
406 func (s *Scanner) isMergeKey(ctx *Context) bool {
407 if ctx.repeatNum('<') != 2 {
408 return false
409 }
410 src := ctx.src
411 size := len(src)
412 for idx := ctx.idx + 2; idx < size; idx++ {
413 c := src[idx]
414 if c == ' ' {
415 continue
416 }
417 if c != ':' {
418 return false
419 }
420 if idx+1 < size {
421 nc := src[idx+1]
422 if nc == ' ' || s.isNewLineChar(nc) {
423 return true
424 }
425 }
426 }
427 return false
428 }
429
430 func (s *Scanner) scanTag(ctx *Context) (tk *token.Token, pos int) {
431 ctx.addOriginBuf('!')
432 ctx.progress(1) // skip '!' character
433 for idx, c := range ctx.src[ctx.idx:] {
434 pos = idx + 1
435 ctx.addOriginBuf(c)
436 switch c {
437 case ' ', '\n', '\r':
438 value := ctx.source(ctx.idx-1, ctx.idx+idx)
439 tk = token.Tag(value, string(ctx.obuf), s.pos())
440 pos = len([]rune(value))
441 return
442 }
443 }
444 return
445 }
446
447 func (s *Scanner) scanComment(ctx *Context) (tk *token.Token, pos int) {
448 ctx.addOriginBuf('#')
449 ctx.progress(1) // skip '#' character
450 for idx, c := range ctx.src[ctx.idx:] {
451 ctx.addOriginBuf(c)
452 switch c {
453 case '\n', '\r':
454 if ctx.previousChar() == '\\' {
455 continue
456 }
457 value := ctx.source(ctx.idx, ctx.idx+idx)
458 tk = token.Comment(value, string(ctx.obuf), s.pos())
459 pos = len([]rune(value)) + 1
460 return
461 }
462 }
463 // document ends with comment.
464 value := string(ctx.src[ctx.idx:])
465 tk = token.Comment(value, string(ctx.obuf), s.pos())
466 pos = len([]rune(value)) + 1
467 return
468 }
469
470 func trimCommentFromLiteralOpt(text string) (string, error) {
471 idx := strings.Index(text, "#")
472 if idx < 0 {
473 return text, nil
474 }
475 if idx == 0 {
476 return "", errors.New("invalid literal header")
477 }
478 return text[:idx-1], nil
479 }
480
481 func (s *Scanner) scanLiteral(ctx *Context, c rune) {
482 ctx.addOriginBuf(c)
483 if ctx.isEOS() {
484 if ctx.isLiteral {
485 ctx.addBuf(c)
486 }
487 value := ctx.bufferedSrc()
488 ctx.addToken(token.String(string(value), string(ctx.obuf), s.pos()))
489 ctx.resetBuffer()
490 s.progressColumn(ctx, 1)
491 } else if s.isNewLineChar(c) {
492 if ctx.isLiteral {
493 ctx.addBuf(c)
494 } else {
495 ctx.addBuf(' ')
496 }
497 s.progressLine(ctx)
498 } else if s.isFirstCharAtLine && c == ' ' {
499 if 0 < s.docStartColumn && s.docStartColumn <= s.column {
500 ctx.addBuf(c)
501 }
502 s.progressColumn(ctx, 1)
503 } else {
504 if s.docStartColumn == 0 {
505 s.docStartColumn = s.column
506 }
507 ctx.addBuf(c)
508 s.progressColumn(ctx, 1)
509 }
510 }
511
512 func (s *Scanner) scanNewLine(ctx *Context, c rune) {
513 if len(ctx.buf) > 0 && s.savedPos == nil {
514 s.savedPos = s.pos()
515 s.savedPos.Column -= len(ctx.bufferedSrc())
516 }
517
518 // if the following case, origin buffer has unnecessary two spaces.
519 // So, `removeRightSpaceFromOriginBuf` remove them, also fix column number too.
520 // ---
521 // a:[space][space]
522 // b: c
523 removedNum := ctx.removeRightSpaceFromBuf()
524 if removedNum > 0 {
525 s.column -= removedNum
526 s.offset -= removedNum
527 if s.savedPos != nil {
528 s.savedPos.Column -= removedNum
529 }
530 }
531
532 // There is no problem that we ignore CR which followed by LF and normalize it to LF, because of following YAML1.2 spec.
533 // > Line breaks inside scalar content must be normalized by the YAML processor. Each such line break must be parsed into a single line feed character.
534 // > Outside scalar content, YAML allows any line break to be used to terminate lines.
535 // > -- https://yaml.org/spec/1.2/spec.html
536 if c == '\r' && ctx.nextChar() == '\n' {
537 ctx.addOriginBuf('\r')
538 ctx.progress(1)
539 c = '\n'
540 }
541
542 if ctx.isEOS() {
543 s.addBufferedTokenIfExists(ctx)
544 } else if s.isAnchor {
545 s.addBufferedTokenIfExists(ctx)
546 }
547 ctx.addBuf(' ')
548 ctx.addOriginBuf(c)
549 ctx.isSingleLine = false
550 s.progressLine(ctx)
551 }
552
553 func (s *Scanner) scanFlowMapStart(ctx *Context) bool {
554 if ctx.existsBuffer() {
555 return false
556 }
557
558 ctx.addOriginBuf('{')
559 ctx.addToken(token.MappingStart(string(ctx.obuf), s.pos()))
560 s.startedFlowMapNum++
561 s.progressColumn(ctx, 1)
562 return true
563 }
564
565 func (s *Scanner) scanFlowMapEnd(ctx *Context) bool {
566 if s.startedFlowMapNum <= 0 {
567 return false
568 }
569
570 s.addBufferedTokenIfExists(ctx)
571 ctx.addOriginBuf('}')
572 ctx.addToken(token.MappingEnd(string(ctx.obuf), s.pos()))
573 s.startedFlowMapNum--
574 s.progressColumn(ctx, 1)
575 return true
576 }
577
578 func (s *Scanner) scanFlowArrayStart(ctx *Context) bool {
579 if ctx.existsBuffer() {
580 return false
581 }
582
583 ctx.addOriginBuf('[')
584 ctx.addToken(token.SequenceStart(string(ctx.obuf), s.pos()))
585 s.startedFlowSequenceNum++
586 s.progressColumn(ctx, 1)
587 return true
588 }
589
590 func (s *Scanner) scanFlowArrayEnd(ctx *Context) bool {
591 if s.startedFlowSequenceNum <= 0 {
592 return false
593 }
594
595 s.addBufferedTokenIfExists(ctx)
596 ctx.addOriginBuf(']')
597 ctx.addToken(token.SequenceEnd(string(ctx.obuf), s.pos()))
598 s.startedFlowSequenceNum--
599 s.progressColumn(ctx, 1)
600 return true
601 }
602
603 func (s *Scanner) scanFlowEntry(ctx *Context, c rune) bool {
604 if s.startedFlowSequenceNum <= 0 && s.startedFlowMapNum <= 0 {
605 return false
606 }
607
608 s.addBufferedTokenIfExists(ctx)
609 ctx.addOriginBuf(c)
610 ctx.addToken(token.CollectEntry(string(ctx.obuf), s.pos()))
611 s.progressColumn(ctx, 1)
612 return true
613 }
614
615 func (s *Scanner) scanMapDelim(ctx *Context) bool {
616 nc := ctx.nextChar()
617 if s.startedFlowMapNum <= 0 && nc != ' ' && !s.isNewLineChar(nc) && !ctx.isNextEOS() {
618 return false
619 }
620
621 // mapping value
622 tk := s.bufferedToken(ctx)
623 if tk != nil {
624 s.lastDelimColumn = tk.Position.Column
625 ctx.addToken(tk)
626 } else if tk := ctx.lastToken(); tk != nil {
627 // If the map key is quote, the buffer does not exist because it has already been cut into tokens.
628 // Therefore, we need to check the last token.
629 if tk.Indicator == token.QuotedScalarIndicator {
630 s.lastDelimColumn = tk.Position.Column
631 }
632 }
633 ctx.addToken(token.MappingValue(s.pos()))
634 s.progressColumn(ctx, 1)
635 return true
636 }
637
638 func (s *Scanner) scanDocumentStart(ctx *Context) bool {
639 if s.indentNum != 0 {
640 return false
641 }
642 if s.column != 1 {
643 return false
644 }
645 if ctx.repeatNum('-') != 3 {
646 return false
647 }
648
649 s.addBufferedTokenIfExists(ctx)
650 ctx.addToken(token.DocumentHeader(string(ctx.obuf)+"---", s.pos()))
651 s.progressColumn(ctx, 3)
652 return true
653 }
654
655 func (s *Scanner) scanDocumentEnd(ctx *Context) bool {
656 if s.indentNum != 0 {
657 return false
658 }
659 if s.column != 1 {
660 return false
661 }
662 if ctx.repeatNum('.') != 3 {
663 return false
664 }
665
666 ctx.addToken(token.DocumentEnd(string(ctx.obuf)+"...", s.pos()))
667 s.progressColumn(ctx, 3)
668 return true
669 }
670
671 func (s *Scanner) scanMergeKey(ctx *Context) bool {
672 if !s.isMergeKey(ctx) {
673 return false
674 }
675
676 s.lastDelimColumn = s.column
677 ctx.addToken(token.MergeKey(string(ctx.obuf)+"<<", s.pos()))
678 s.progressColumn(ctx, 1)
679 return true
680 }
681
682 func (s *Scanner) scanRawFoldedChar(ctx *Context) bool {
683 if !ctx.existsBuffer() {
684 return false
685 }
686 if !s.isChangedToIndentStateUp() {
687 return false
688 }
689
690 ctx.isRawFolded = true
691 ctx.addBuf('-')
692 ctx.addOriginBuf('-')
693 s.progressColumn(ctx, 1)
694 return true
695 }
696
697 func (s *Scanner) scanSequence(ctx *Context) bool {
698 if ctx.existsBuffer() {
699 return false
700 }
701
702 nc := ctx.nextChar()
703 if nc != ' ' && !s.isNewLineChar(nc) {
704 return false
705 }
706
707 s.addBufferedTokenIfExists(ctx)
708 ctx.addOriginBuf('-')
709 tk := token.SequenceEntry(string(ctx.obuf), s.pos())
710 s.lastDelimColumn = tk.Position.Column
711 ctx.addToken(tk)
712 s.progressColumn(ctx, 1)
713 return true
714 }
715
716 func (s *Scanner) scanLiteralHeader(ctx *Context) (bool, error) {
717 if ctx.existsBuffer() {
718 return false, nil
719 }
720
721 progress, err := s.scanLiteralHeaderOption(ctx)
722 if err != nil {
723 return false, err
724 }
725 s.progressColumn(ctx, progress)
726 s.progressLine(ctx)
727 return true, nil
728 }
729
730 func (s *Scanner) scanLiteralHeaderOption(ctx *Context) (pos int, err error) {
731 header := ctx.currentChar()
732 ctx.addOriginBuf(header)
733 ctx.progress(1) // skip '|' or '>' character
734 for idx, c := range ctx.src[ctx.idx:] {
735 pos = idx
736 ctx.addOriginBuf(c)
737 switch c {
738 case '\n', '\r':
739 value := ctx.source(ctx.idx, ctx.idx+idx)
740 opt := strings.TrimRight(value, " ")
741 orgOptLen := len(opt)
742 opt, err = trimCommentFromLiteralOpt(opt)
743 if err != nil {
744 return
745 }
746 switch opt {
747 case "", "+", "-",
748 "0", "1", "2", "3", "4", "5", "6", "7", "8", "9":
749 hasComment := len(opt) < orgOptLen
750 if header == '|' {
751 if hasComment {
752 commentLen := orgOptLen - len(opt)
753 headerPos := strings.Index(string(ctx.obuf), "|")
754 litBuf := ctx.obuf[:len(ctx.obuf)-commentLen-headerPos]
755 commentBuf := ctx.obuf[len(litBuf):]
756 ctx.addToken(token.Literal("|"+opt, string(litBuf), s.pos()))
757 s.column += len(litBuf)
758 s.offset += len(litBuf)
759 commentHeader := strings.Index(value, "#")
760 ctx.addToken(token.Comment(string(value[commentHeader+1:]), string(commentBuf), s.pos()))
761 } else {
762 ctx.addToken(token.Literal("|"+opt, string(ctx.obuf), s.pos()))
763 }
764 ctx.isLiteral = true
765 } else if header == '>' {
766 if hasComment {
767 commentLen := orgOptLen - len(opt)
768 headerPos := strings.Index(string(ctx.obuf), ">")
769 foldedBuf := ctx.obuf[:len(ctx.obuf)-commentLen-headerPos]
770 commentBuf := ctx.obuf[len(foldedBuf):]
771 ctx.addToken(token.Folded(">"+opt, string(foldedBuf), s.pos()))
772 s.column += len(foldedBuf)
773 s.offset += len(foldedBuf)
774 commentHeader := strings.Index(value, "#")
775 ctx.addToken(token.Comment(string(value[commentHeader+1:]), string(commentBuf), s.pos()))
776 } else {
777 ctx.addToken(token.Folded(">"+opt, string(ctx.obuf), s.pos()))
778 }
779 ctx.isFolded = true
780 }
781 s.indentState = IndentStateKeep
782 ctx.resetBuffer()
783 ctx.literalOpt = opt
784 return
785 }
786 }
787 }
788 err = errors.New("invalid literal header")
789 return
790 }
791
792 func (s *Scanner) scanMapKey(ctx *Context) bool {
793 if ctx.existsBuffer() {
794 return false
795 }
796
797 nc := ctx.nextChar()
798 if nc != ' ' {
799 return false
800 }
801
802 ctx.addToken(token.MappingKey(s.pos()))
803 s.progressColumn(ctx, 1)
804 return true
805 }
806
807 func (s *Scanner) scanDirective(ctx *Context) bool {
808 if ctx.existsBuffer() {
809 return false
810 }
811 if s.indentNum != 0 {
812 return false
813 }
814
815 ctx.addToken(token.Directive(string(ctx.obuf)+"%", s.pos()))
816 s.progressColumn(ctx, 1)
817 return true
818 }
819
820 func (s *Scanner) scanAnchor(ctx *Context) bool {
821 if ctx.existsBuffer() {
822 return false
823 }
824
825 s.addBufferedTokenIfExists(ctx)
826 ctx.addOriginBuf('&')
827 ctx.addToken(token.Anchor(string(ctx.obuf), s.pos()))
828 s.progressColumn(ctx, 1)
829 s.isAnchor = true
830 return true
831 }
832
833 func (s *Scanner) scanAlias(ctx *Context) bool {
834 if ctx.existsBuffer() {
835 return false
836 }
837
838 s.addBufferedTokenIfExists(ctx)
839 ctx.addOriginBuf('*')
840 ctx.addToken(token.Alias(string(ctx.obuf), s.pos()))
841 s.progressColumn(ctx, 1)
842 return true
843 }
844
845 func (s *Scanner) scan(ctx *Context) (pos int) {
846 for ctx.next() {
847 pos = ctx.nextPos()
848 c := ctx.currentChar()
849
850 // First, change the IndentState.
851 // If the target character is the first character in a line, IndentState is Up/Down/Equal state.
852 // The second and subsequent letters are Keep.
853 s.updateIndent(ctx, c)
854
855 // If IndentState is down, tokens are split, so the buffer accumulated until that point needs to be cutted as a token.
856 if s.isChangedToIndentStateDown() {
857 s.addBufferedTokenIfExists(ctx)
858 }
859 if ctx.isDocument() {
860 if s.isChangedToIndentStateDown() {
861 s.breakLiteral(ctx)
862 } else {
863 s.scanLiteral(ctx, c)
864 continue
865 }
866 }
867 switch c {
868 case '{':
869 if s.scanFlowMapStart(ctx) {
870 return
871 }
872 case '}':
873 if s.scanFlowMapEnd(ctx) {
874 return
875 }
876 case '.':
877 if s.scanDocumentEnd(ctx) {
878 pos += 2
879 return
880 }
881 case '<':
882 if s.scanMergeKey(ctx) {
883 pos++
884 return
885 }
886 case '-':
887 if s.scanDocumentStart(ctx) {
888 pos += 2
889 return
890 }
891 if s.scanRawFoldedChar(ctx) {
892 continue
893 }
894 if s.scanSequence(ctx) {
895 return
896 }
897 if ctx.existsBuffer() {
898 // '-' is literal
899 ctx.addBuf(c)
900 ctx.addOriginBuf(c)
901 s.progressColumn(ctx, 1)
902 continue
903 }
904 case '[':
905 if s.scanFlowArrayStart(ctx) {
906 return
907 }
908 case ']':
909 if s.scanFlowArrayEnd(ctx) {
910 return
911 }
912 case ',':
913 if s.scanFlowEntry(ctx, c) {
914 return
915 }
916 case ':':
917 if s.scanMapDelim(ctx) {
918 return
919 }
920 case '|', '>':
921 scanned, err := s.scanLiteralHeader(ctx)
922 if err != nil {
923 // TODO: returns syntax error object
924 return
925 }
926 if scanned {
927 continue
928 }
929 case '!':
930 if !ctx.existsBuffer() {
931 token, progress := s.scanTag(ctx)
932 ctx.addToken(token)
933 s.progressColumn(ctx, progress)
934 if c := ctx.previousChar(); s.isNewLineChar(c) {
935 s.progressLine(ctx)
936 }
937 pos += progress
938 return
939 }
940 case '%':
941 if s.scanDirective(ctx) {
942 return
943 }
944 case '?':
945 if s.scanMapKey(ctx) {
946 return
947 }
948 case '&':
949 if s.scanAnchor(ctx) {
950 return
951 }
952 case '*':
953 if s.scanAlias(ctx) {
954 return
955 }
956 case '#':
957 if !ctx.existsBuffer() || ctx.previousChar() == ' ' {
958 s.addBufferedTokenIfExists(ctx)
959 token, progress := s.scanComment(ctx)
960 ctx.addToken(token)
961 s.progressColumn(ctx, progress)
962 s.progressLine(ctx)
963 pos += progress
964 return
965 }
966 case '\'', '"':
967 if !ctx.existsBuffer() {
968 token, progress := s.scanQuote(ctx, c)
969 ctx.addToken(token)
970 pos += progress
971 // If the non-whitespace character immediately following the quote is ':', the quote should be treated as a map key.
972 // Therefore, do not return and continue processing as a normal map key.
973 if ctx.currentCharWithSkipWhitespace() == ':' {
974 continue
975 }
976 return
977 }
978 case '\r', '\n':
979 s.scanNewLine(ctx, c)
980 continue
981 case ' ':
982 if ctx.isSaveIndentMode() || (!s.isAnchor && !s.isFirstCharAtLine) {
983 ctx.addBuf(c)
984 ctx.addOriginBuf(c)
985 s.progressColumn(ctx, 1)
986 continue
987 }
988 if s.isFirstCharAtLine {
989 s.progressColumn(ctx, 1)
990 ctx.addOriginBuf(c)
991 continue
992 }
993 s.addBufferedTokenIfExists(ctx)
994 pos-- // to rescan white space at next scanning for adding white space to next buffer.
995 s.isAnchor = false
996 return
997 }
998 ctx.addBuf(c)
999 ctx.addOriginBuf(c)
1000 s.progressColumn(ctx, 1)
1001 }
1002 s.addBufferedTokenIfExists(ctx)
1003 return
1004 }
1005
1006 // Init prepares the scanner s to tokenize the text src by setting the scanner at the beginning of src.
1007 func (s *Scanner) Init(text string) {
1008 src := []rune(text)
1009 s.source = src
1010 s.sourcePos = 0
1011 s.sourceSize = len(src)
1012 s.line = 1
1013 s.column = 1
1014 s.offset = 1
1015 s.prevLineIndentNum = 0
1016 s.lastDelimColumn = 0
1017 s.indentLevel = 0
1018 s.indentNum = 0
1019 s.isFirstCharAtLine = true
1020 }
1021
1022 // Scan scans the next token and returns the token collection. The source end is indicated by io.EOF.
1023 func (s *Scanner) Scan() (token.Tokens, error) {
1024 if s.sourcePos >= s.sourceSize {
1025 return nil, io.EOF
1026 }
1027 ctx := newContext(s.source[s.sourcePos:])
1028 defer ctx.release()
1029 progress := s.scan(ctx)
1030 s.sourcePos += progress
1031 var tokens token.Tokens
1032 tokens = append(tokens, ctx.tokens...)
1033 return tokens, nil
1034 }