Debian Codegraph @

parser/parser.go

raw symbols SCIP
1 package parser
2
3 import (
4 "fmt"
5 "os"
6 "strings"
7
8 "github.com/goccy/go-yaml/ast"
9 "github.com/goccy/go-yaml/internal/errors"
10 "github.com/goccy/go-yaml/lexer"
11 "github.com/goccy/go-yaml/token"
12 )
13
14 type Mode uint
15
16 const (
17 ParseComments Mode = 1 << iota // parse comments and add them to AST
18 )
19
20 // ParseBytes parse from byte slice, and returns ast.File
21 func ParseBytes(bytes []byte, mode Mode, opts ...Option) (*ast.File, error) {
22 tokens := lexer.Tokenize(string(bytes))
23 f, err := Parse(tokens, mode, opts...)
24 if err != nil {
25 return nil, err
26 }
27 return f, nil
28 }
29
30 // Parse parse from token instances, and returns ast.File
31 func Parse(tokens token.Tokens, mode Mode, opts ...Option) (*ast.File, error) {
32 if tk := tokens.InvalidToken(); tk != nil {
33 return nil, errors.ErrSyntax(tk.Error, tk)
34 }
35 p, err := newParser(tokens, mode, opts)
36 if err != nil {
37 return nil, err
38 }
39 f, err := p.parse(newContext())
40 if err != nil {
41 return nil, err
42 }
43 return f, nil
44 }
45
46 // Parse parse from filename, and returns ast.File
47 func ParseFile(filename string, mode Mode, opts ...Option) (*ast.File, error) {
48 file, err := os.ReadFile(filename)
49 if err != nil {
50 return nil, err
51 }
52 f, err := ParseBytes(file, mode, opts...)
53 if err != nil {
54 return nil, err
55 }
56 f.Name = filename
57 return f, nil
58 }
59
60 type YAMLVersion string
61
62 const (
63 YAML10 YAMLVersion = "1.0"
64 YAML11 YAMLVersion = "1.1"
65 YAML12 YAMLVersion = "1.2"
66 YAML13 YAMLVersion = "1.3"
67 )
68
69 var yamlVersionMap = map[string]YAMLVersion{
70 "1.0": YAML10,
71 "1.1": YAML11,
72 "1.2": YAML12,
73 "1.3": YAML13,
74 }
75
76 type parser struct {
77 tokens []*Token
78 pathMap map[string]ast.Node
79 yamlVersion YAMLVersion
80 allowDuplicateMapKey bool
81 secondaryTagDirective *ast.DirectiveNode
82 }
83
84 func newParser(tokens token.Tokens, mode Mode, opts []Option) (*parser, error) {
85 filteredTokens := []*token.Token{}
86 if mode&ParseComments != 0 {
87 filteredTokens = tokens
88 } else {
89 for _, tk := range tokens {
90 if tk.Type == token.CommentType {
91 continue
92 }
93 // keep prev/next reference between tokens containing comments
94 // https://github.com/goccy/go-yaml/issues/254
95 filteredTokens = append(filteredTokens, tk)
96 }
97 }
98 tks, err := CreateGroupedTokens(token.Tokens(filteredTokens))
99 if err != nil {
100 return nil, err
101 }
102 p := &parser{
103 tokens: tks,
104 pathMap: make(map[string]ast.Node),
105 }
106 for _, opt := range opts {
107 opt(p)
108 }
109 return p, nil
110 }
111
112 func (p *parser) parse(ctx *context) (*ast.File, error) {
113 file := &ast.File{Docs: []*ast.DocumentNode{}}
114 for _, token := range p.tokens {
115 doc, err := p.parseDocument(ctx, token.Group)
116 if err != nil {
117 return nil, err
118 }
119 file.Docs = append(file.Docs, doc)
120 }
121 return file, nil
122 }
123
124 func (p *parser) parseDocument(ctx *context, docGroup *TokenGroup) (*ast.DocumentNode, error) {
125 if len(docGroup.Tokens) == 0 {
126 return ast.Document(docGroup.RawToken(), nil), nil
127 }
128
129 p.pathMap = make(map[string]ast.Node)
130
131 var (
132 tokens = docGroup.Tokens
133 start *token.Token
134 end *token.Token
135 )
136 if docGroup.First().Type() == token.DocumentHeaderType {
137 start = docGroup.First().RawToken()
138 tokens = tokens[1:]
139 }
140 if docGroup.Last().Type() == token.DocumentEndType {
141 end = docGroup.Last().RawToken()
142 tokens = tokens[:len(tokens)-1]
143 defer func() {
144 // clear yaml version value if DocumentEnd token (...) is specified.
145 p.yamlVersion = ""
146 }()
147 }
148
149 if len(tokens) == 0 {
150 return ast.Document(docGroup.RawToken(), nil), nil
151 }
152
153 body, err := p.parseDocumentBody(ctx.withGroup(&TokenGroup{
154 Type: TokenGroupDocumentBody,
155 Tokens: tokens,
156 }))
157 if err != nil {
158 return nil, err
159 }
160 node := ast.Document(start, body)
161 node.End = end
162 return node, nil
163 }
164
165 func (p *parser) parseDocumentBody(ctx *context) (ast.Node, error) {
166 node, err := p.parseToken(ctx, ctx.currentToken())
167 if err != nil {
168 return nil, err
169 }
170 if ctx.next() {
171 return nil, errors.ErrSyntax("value is not allowed in this context", ctx.currentToken().RawToken())
172 }
173 return node, nil
174 }
175
176 func (p *parser) parseToken(ctx *context, tk *Token) (ast.Node, error) {
177 switch tk.GroupType() {
178 case TokenGroupMapKey, TokenGroupMapKeyValue:
179 return p.parseMap(ctx)
180 case TokenGroupDirective:
181 node, err := p.parseDirective(ctx.withGroup(tk.Group), tk.Group)
182 if err != nil {
183 return nil, err
184 }
185 ctx.goNext()
186 return node, nil
187 case TokenGroupDirectiveName:
188 node, err := p.parseDirectiveName(ctx.withGroup(tk.Group))
189 if err != nil {
190 return nil, err
191 }
192 ctx.goNext()
193 return node, nil
194 case TokenGroupAnchor:
195 node, err := p.parseAnchor(ctx.withGroup(tk.Group), tk.Group)
196 if err != nil {
197 return nil, err
198 }
199 ctx.goNext()
200 return node, nil
201 case TokenGroupAnchorName:
202 anchor, err := p.parseAnchorName(ctx.withGroup(tk.Group))
203 if err != nil {
204 return nil, err
205 }
206 ctx.goNext()
207 if ctx.isTokenNotFound() {
208 return nil, errors.ErrSyntax("could not find anchor value", tk.RawToken())
209 }
210 value, err := p.parseToken(ctx, ctx.currentToken())
211 if err != nil {
212 return nil, err
213 }
214 if _, ok := value.(*ast.AnchorNode); ok {
215 return nil, errors.ErrSyntax("anchors cannot be used consecutively", value.GetToken())
216 }
217 anchor.Value = value
218 return anchor, nil
219 case TokenGroupAlias:
220 node, err := p.parseAlias(ctx.withGroup(tk.Group))
221 if err != nil {
222 return nil, err
223 }
224 ctx.goNext()
225 return node, nil
226 case TokenGroupLiteral, TokenGroupFolded:
227 node, err := p.parseLiteral(ctx.withGroup(tk.Group))
228 if err != nil {
229 return nil, err
230 }
231 ctx.goNext()
232 return node, nil
233 case TokenGroupScalarTag:
234 node, err := p.parseTag(ctx.withGroup(tk.Group))
235 if err != nil {
236 return nil, err
237 }
238 ctx.goNext()
239 return node, nil
240 }
241 switch tk.Type() {
242 case token.CommentType:
243 return p.parseComment(ctx)
244 case token.TagType:
245 return p.parseTag(ctx)
246 case token.MappingStartType:
247 return p.parseFlowMap(ctx.withFlow(true))
248 case token.SequenceStartType:
249 return p.parseFlowSequence(ctx.withFlow(true))
250 case token.SequenceEntryType:
251 return p.parseSequence(ctx)
252 case token.SequenceEndType:
253 // SequenceEndType is always validated in parseFlowSequence.
254 // Therefore, if this is found in other cases, it is treated as a syntax error.
255 return nil, errors.ErrSyntax("could not find '[' character corresponding to ']'", tk.RawToken())
256 case token.MappingEndType:
257 // MappingEndType is always validated in parseFlowMap.
258 // Therefore, if this is found in other cases, it is treated as a syntax error.
259 return nil, errors.ErrSyntax("could not find '{' character corresponding to '}'", tk.RawToken())
260 case token.MappingValueType:
261 return nil, errors.ErrSyntax("found an invalid key for this map", tk.RawToken())
262 }
263 node, err := p.parseScalarValue(ctx, tk)
264 if err != nil {
265 return nil, err
266 }
267 ctx.goNext()
268 return node, nil
269 }
270
271 func (p *parser) parseScalarValue(ctx *context, tk *Token) (ast.ScalarNode, error) {
272 if tk.Group != nil {
273 switch tk.GroupType() {
274 case TokenGroupAnchor:
275 return p.parseAnchor(ctx.withGroup(tk.Group), tk.Group)
276 case TokenGroupAnchorName:
277 anchor, err := p.parseAnchorName(ctx.withGroup(tk.Group))
278 if err != nil {
279 return nil, err
280 }
281 ctx.goNext()
282 if ctx.isTokenNotFound() {
283 return nil, errors.ErrSyntax("could not find anchor value", tk.RawToken())
284 }
285 value, err := p.parseToken(ctx, ctx.currentToken())
286 if err != nil {
287 return nil, err
288 }
289 if _, ok := value.(*ast.AnchorNode); ok {
290 return nil, errors.ErrSyntax("anchors cannot be used consecutively", value.GetToken())
291 }
292 anchor.Value = value
293 return anchor, nil
294 case TokenGroupAlias:
295 return p.parseAlias(ctx.withGroup(tk.Group))
296 case TokenGroupLiteral, TokenGroupFolded:
297 return p.parseLiteral(ctx.withGroup(tk.Group))
298 case TokenGroupScalarTag:
299 return p.parseTag(ctx.withGroup(tk.Group))
300 default:
301 return nil, errors.ErrSyntax("unexpected scalar value", tk.RawToken())
302 }
303 }
304 switch tk.Type() {
305 case token.MergeKeyType:
306 return newMergeKeyNode(ctx, tk)
307 case token.NullType, token.ImplicitNullType:
308 return newNullNode(ctx, tk)
309 case token.BoolType:
310 return newBoolNode(ctx, tk)
311 case token.IntegerType, token.BinaryIntegerType, token.OctetIntegerType, token.HexIntegerType:
312 return newIntegerNode(ctx, tk)
313 case token.FloatType:
314 return newFloatNode(ctx, tk)
315 case token.InfinityType:
316 return newInfinityNode(ctx, tk)
317 case token.NanType:
318 return newNanNode(ctx, tk)
319 case token.StringType, token.SingleQuoteType, token.DoubleQuoteType:
320 return newStringNode(ctx, tk)
321 case token.TagType:
322 // this case applies when it is a scalar tag and its value does not exist.
323 // Examples of cases where the value does not exist include cases like `key: !!str,` or `!!str : value`.
324 return p.parseScalarTag(ctx)
325 }
326 return nil, errors.ErrSyntax("unexpected scalar value type", tk.RawToken())
327 }
328
329 func (p *parser) parseFlowMap(ctx *context) (*ast.MappingNode, error) {
330 node, err := newMappingNode(ctx, ctx.currentToken(), true)
331 if err != nil {
332 return nil, err
333 }
334 ctx.goNext() // skip MappingStart token
335
336 isFirst := true
337 for ctx.next() {
338 tk := ctx.currentToken()
339 if tk.Type() == token.MappingEndType {
340 node.End = tk.RawToken()
341 break
342 }
343
344 var entryTk *Token
345 if tk.Type() == token.CollectEntryType {
346 entryTk = tk
347 ctx.goNext()
348 } else if !isFirst {
349 return nil, errors.ErrSyntax("',' or '}' must be specified", tk.RawToken())
350 }
351
352 if tk := ctx.currentToken(); tk.Type() == token.MappingEndType {
353 // this case is here: "{ elem, }".
354 // In this case, ignore the last element and break mapping parsing.
355 node.End = tk.RawToken()
356 break
357 }
358
359 mapKeyTk := ctx.currentToken()
360 switch mapKeyTk.GroupType() {
361 case TokenGroupMapKeyValue:
362 value, err := p.parseMapKeyValue(ctx.withGroup(mapKeyTk.Group), mapKeyTk.Group, entryTk)
363 if err != nil {
364 return nil, err
365 }
366 node.Values = append(node.Values, value)
367 ctx.goNext()
368 case TokenGroupMapKey:
369 key, err := p.parseMapKey(ctx.withGroup(mapKeyTk.Group), mapKeyTk.Group)
370 if err != nil {
371 return nil, err
372 }
373 ctx := ctx.withChild(p.mapKeyText(key))
374 colonTk := mapKeyTk.Group.Last()
375 if p.isFlowMapDelim(ctx.nextToken()) {
376 value, err := newNullNode(ctx, ctx.insertNullToken(colonTk))
377 if err != nil {
378 return nil, err
379 }
380 mapValue, err := newMappingValueNode(ctx, colonTk, entryTk, key, value)
381 if err != nil {
382 return nil, err
383 }
384 node.Values = append(node.Values, mapValue)
385 ctx.goNext()
386 } else {
387 ctx.goNext()
388 if ctx.isTokenNotFound() {
389 return nil, errors.ErrSyntax("could not find map value", colonTk.RawToken())
390 }
391 value, err := p.parseToken(ctx, ctx.currentToken())
392 if err != nil {
393 return nil, err
394 }
395 mapValue, err := newMappingValueNode(ctx, colonTk, entryTk, key, value)
396 if err != nil {
397 return nil, err
398 }
399 node.Values = append(node.Values, mapValue)
400 }
401 default:
402 if !p.isFlowMapDelim(ctx.nextToken()) {
403 errTk := mapKeyTk
404 if errTk == nil {
405 errTk = tk
406 }
407 return nil, errors.ErrSyntax("could not find flow map content", errTk.RawToken())
408 }
409 key, err := p.parseScalarValue(ctx, mapKeyTk)
410 if err != nil {
411 return nil, err
412 }
413 value, err := newNullNode(ctx, ctx.insertNullToken(mapKeyTk))
414 if err != nil {
415 return nil, err
416 }
417 mapValue, err := newMappingValueNode(ctx, mapKeyTk, entryTk, key, value)
418 if err != nil {
419 return nil, err
420 }
421 node.Values = append(node.Values, mapValue)
422 ctx.goNext()
423 }
424 isFirst = false
425 }
426 if node.End == nil {
427 return nil, errors.ErrSyntax("could not find flow mapping end token '}'", node.Start)
428 }
429 ctx.goNext() // skip mapping end token.
430 return node, nil
431 }
432
433 func (p *parser) isFlowMapDelim(tk *Token) bool {
434 return tk.Type() == token.MappingEndType || tk.Type() == token.CollectEntryType
435 }
436
437 func (p *parser) parseMap(ctx *context) (*ast.MappingNode, error) {
438 keyTk := ctx.currentToken()
439 if keyTk.Group == nil {
440 return nil, errors.ErrSyntax("unexpected map key", keyTk.RawToken())
441 }
442 var keyValueNode *ast.MappingValueNode
443 if keyTk.GroupType() == TokenGroupMapKeyValue {
444 node, err := p.parseMapKeyValue(ctx.withGroup(keyTk.Group), keyTk.Group, nil)
445 if err != nil {
446 return nil, err
447 }
448 keyValueNode = node
449 ctx.goNext()
450 if err := p.validateMapKeyValueNextToken(ctx, keyTk, ctx.currentToken()); err != nil {
451 return nil, err
452 }
453 } else {
454 key, err := p.parseMapKey(ctx.withGroup(keyTk.Group), keyTk.Group)
455 if err != nil {
456 return nil, err
457 }
458 ctx.goNext()
459
460 valueTk := ctx.currentToken()
461 if keyTk.Line() == valueTk.Line() && valueTk.Type() == token.SequenceEntryType {
462 return nil, errors.ErrSyntax("block sequence entries are not allowed in this context", valueTk.RawToken())
463 }
464 ctx := ctx.withChild(p.mapKeyText(key))
465 value, err := p.parseMapValue(ctx, key, keyTk.Group.Last())
466 if err != nil {
467 return nil, err
468 }
469 node, err := newMappingValueNode(ctx, keyTk.Group.Last(), nil, key, value)
470 if err != nil {
471 return nil, err
472 }
473 keyValueNode = node
474 }
475 mapNode, err := newMappingNode(ctx, &Token{Token: keyValueNode.GetToken()}, false, keyValueNode)
476 if err != nil {
477 return nil, err
478 }
479 var tk *Token
480 if ctx.isComment() {
481 tk = ctx.nextNotCommentToken()
482 } else {
483 tk = ctx.currentToken()
484 }
485 for tk.Column() == keyTk.Column() {
486 typ := tk.Type()
487 if ctx.isFlow && typ == token.SequenceEndType {
488 // [
489 // key: value
490 // ] <=
491 break
492 }
493 if !p.isMapToken(tk) {
494 return nil, errors.ErrSyntax("non-map value is specified", tk.RawToken())
495 }
496 cm := p.parseHeadComment(ctx)
497 if typ == token.MappingEndType {
498 // a: {
499 // b: c
500 // } <=
501 ctx.goNext()
502 break
503 }
504 node, err := p.parseMap(ctx)
505 if err != nil {
506 return nil, err
507 }
508 if len(node.Values) != 0 {
509 if err := setHeadComment(cm, node.Values[0]); err != nil {
510 return nil, err
511 }
512 }
513 mapNode.Values = append(mapNode.Values, node.Values...)
514 if node.FootComment != nil {
515 mapNode.Values[len(mapNode.Values)-1].FootComment = node.FootComment
516 }
517 tk = ctx.currentToken()
518 }
519 if ctx.isComment() {
520 if keyTk.Column() <= ctx.currentToken().Column() {
521 // If the comment is in the same or deeper column as the last element column in map value,
522 // treat it as a footer comment for the last element.
523 if len(mapNode.Values) == 1 {
524 mapNode.Values[0].FootComment = p.parseFootComment(ctx, keyTk.Column())
525 mapNode.Values[0].FootComment.SetPath(mapNode.Values[0].Key.GetPath())
526 } else {
527 mapNode.FootComment = p.parseFootComment(ctx, keyTk.Column())
528 mapNode.FootComment.SetPath(mapNode.GetPath())
529 }
530 }
531 }
532 return mapNode, nil
533 }
534
535 func (p *parser) validateMapKeyValueNextToken(ctx *context, keyTk, tk *Token) error {
536 if tk == nil {
537 return nil
538 }
539 if tk.Column() <= keyTk.Column() {
540 return nil
541 }
542 if ctx.isComment() {
543 return nil
544 }
545 if ctx.isFlow && (tk.Type() == token.CollectEntryType || tk.Type() == token.SequenceEndType) {
546 return nil
547 }
548 // a: b
549 // c <= this token is invalid.
550 return errors.ErrSyntax("value is not allowed in this context. map key-value is pre-defined", tk.RawToken())
551 }
552
553 func (p *parser) isMapToken(tk *Token) bool {
554 if tk.Group == nil {
555 return tk.Type() == token.MappingStartType || tk.Type() == token.MappingEndType
556 }
557 g := tk.Group
558 return g.Type == TokenGroupMapKey || g.Type == TokenGroupMapKeyValue
559 }
560
561 func (p *parser) parseMapKeyValue(ctx *context, g *TokenGroup, entryTk *Token) (*ast.MappingValueNode, error) {
562 if g.Type != TokenGroupMapKeyValue {
563 return nil, errors.ErrSyntax("unexpected map key-value pair", g.RawToken())
564 }
565 if g.First().Group == nil {
566 return nil, errors.ErrSyntax("unexpected map key", g.RawToken())
567 }
568 keyGroup := g.First().Group
569 key, err := p.parseMapKey(ctx.withGroup(keyGroup), keyGroup)
570 if err != nil {
571 return nil, err
572 }
573
574 c := ctx.withChild(p.mapKeyText(key))
575 value, err := p.parseToken(c, g.Last())
576 if err != nil {
577 return nil, err
578 }
579 return newMappingValueNode(c, keyGroup.Last(), entryTk, key, value)
580 }
581
582 func (p *parser) parseMapKey(ctx *context, g *TokenGroup) (ast.MapKeyNode, error) {
583 if g.Type != TokenGroupMapKey {
584 return nil, errors.ErrSyntax("unexpected map key", g.RawToken())
585 }
586 if g.First().Type() == token.MappingKeyType {
587 mapKeyTk := g.First()
588 if mapKeyTk.Group != nil {
589 ctx = ctx.withGroup(mapKeyTk.Group)
590 }
591 key, err := newMappingKeyNode(ctx, mapKeyTk)
592 if err != nil {
593 return nil, err
594 }
595 ctx.goNext() // skip mapping key token
596 if ctx.isTokenNotFound() {
597 return nil, errors.ErrSyntax("could not find value for mapping key", mapKeyTk.RawToken())
598 }
599
600 scalar, err := p.parseScalarValue(ctx, ctx.currentToken())
601 if err != nil {
602 return nil, err
603 }
604 key.Value = scalar
605 keyText := p.mapKeyText(scalar)
606 keyPath := ctx.withChild(keyText).path
607 key.SetPath(keyPath)
608 if err := p.validateMapKey(ctx, key.GetToken(), keyPath, g.Last()); err != nil {
609 return nil, err
610 }
611 p.pathMap[keyPath] = key
612 return key, nil
613 }
614 if g.Last().Type() != token.MappingValueType {
615 return nil, errors.ErrSyntax("expected map key-value delimiter ':'", g.Last().RawToken())
616 }
617
618 scalar, err := p.parseScalarValue(ctx, g.First())
619 if err != nil {
620 return nil, err
621 }
622 key, ok := scalar.(ast.MapKeyNode)
623 if !ok {
624 return nil, errors.ErrSyntax("cannot take map-key node", scalar.GetToken())
625 }
626 keyText := p.mapKeyText(key)
627 keyPath := ctx.withChild(keyText).path
628 key.SetPath(keyPath)
629 if err := p.validateMapKey(ctx, key.GetToken(), keyPath, g.Last()); err != nil {
630 return nil, err
631 }
632 p.pathMap[keyPath] = key
633 return key, nil
634 }
635
636 func (p *parser) validateMapKey(ctx *context, tk *token.Token, keyPath string, colonTk *Token) error {
637 if !p.allowDuplicateMapKey {
638 if n, exists := p.pathMap[keyPath]; exists {
639 pos := n.GetToken().Position
640 return errors.ErrSyntax(
641 fmt.Sprintf("mapping key %q already defined at [%d:%d]", tk.Value, pos.Line, pos.Column),
642 tk,
643 )
644 }
645 }
646 origin := p.removeLeftWhiteSpace(tk.Origin)
647 if ctx.isFlow {
648 if tk.Type == token.StringType {
649 origin = p.removeRightWhiteSpace(origin)
650 if tk.Position.Line+p.newLineCharacterNum(origin) != colonTk.Line() {
651 return errors.ErrSyntax("map key definition includes an implicit line break", tk)
652 }
653 }
654 return nil
655 }
656 if tk.Type != token.StringType && tk.Type != token.SingleQuoteType && tk.Type != token.DoubleQuoteType {
657 return nil
658 }
659 if p.existsNewLineCharacter(origin) {
660 return errors.ErrSyntax("unexpected key name", tk)
661 }
662 return nil
663 }
664
665 func (p *parser) removeLeftWhiteSpace(src string) string {
666 // CR or LF or CRLF
667 return strings.TrimLeftFunc(src, func(r rune) bool {
668 return r == ' ' || r == '\r' || r == '\n'
669 })
670 }
671
672 func (p *parser) removeRightWhiteSpace(src string) string {
673 // CR or LF or CRLF
674 return strings.TrimRightFunc(src, func(r rune) bool {
675 return r == ' ' || r == '\r' || r == '\n'
676 })
677 }
678
679 func (p *parser) existsNewLineCharacter(src string) bool {
680 return p.newLineCharacterNum(src) > 0
681 }
682
683 func (p *parser) newLineCharacterNum(src string) int {
684 var num int
685 for i := 0; i < len(src); i++ {
686 switch src[i] {
687 case '\r':
688 if len(src) > i+1 && src[i+1] == '\n' {
689 i++
690 }
691 num++
692 case '\n':
693 num++
694 }
695 }
696 return num
697 }
698
699 func (p *parser) mapKeyText(n ast.Node) string {
700 if n == nil {
701 return ""
702 }
703 switch nn := n.(type) {
704 case *ast.MappingKeyNode:
705 return p.mapKeyText(nn.Value)
706 case *ast.TagNode:
707 return p.mapKeyText(nn.Value)
708 case *ast.AnchorNode:
709 return p.mapKeyText(nn.Value)
710 case *ast.AliasNode:
711 return ""
712 }
713 return n.GetToken().Value
714 }
715
716 func (p *parser) parseMapValue(ctx *context, key ast.MapKeyNode, colonTk *Token) (ast.Node, error) {
717 tk := ctx.currentToken()
718 if tk == nil {
719 return newNullNode(ctx, ctx.addNullValueToken(colonTk))
720 }
721
722 if ctx.isComment() {
723 tk = ctx.nextNotCommentToken()
724 }
725 keyCol := key.GetToken().Position.Column
726 keyLine := key.GetToken().Position.Line
727
728 if tk.Column() != keyCol && tk.Line() == keyLine && (tk.GroupType() == TokenGroupMapKey || tk.GroupType() == TokenGroupMapKeyValue) {
729 // a: b:
730 // ^
731 //
732 // a: b: c
733 // ^
734 return nil, errors.ErrSyntax("mapping value is not allowed in this context", tk.RawToken())
735 }
736
737 if tk.Column() == keyCol && p.isMapToken(tk) {
738 // in this case,
739 // ----
740 // key: <value does not defined>
741 // next
742 return newNullNode(ctx, ctx.insertNullToken(colonTk))
743 }
744
745 if tk.Line() == keyLine && tk.GroupType() == TokenGroupAnchorName &&
746 ctx.nextToken().Column() == keyCol && p.isMapToken(ctx.nextToken()) {
747 // in this case,
748 // ----
749 // key: &anchor
750 // next
751 group := &TokenGroup{
752 Type: TokenGroupAnchor,
753 Tokens: []*Token{tk, ctx.createImplicitNullToken(tk)},
754 }
755 anchor, err := p.parseAnchor(ctx.withGroup(group), group)
756 if err != nil {
757 return nil, err
758 }
759 ctx.goNext()
760 return anchor, nil
761 }
762
763 if tk.Column() <= keyCol && tk.GroupType() == TokenGroupAnchorName {
764 // key: <value does not defined>
765 // &anchor
766 return nil, errors.ErrSyntax("anchor is not allowed in this context", tk.RawToken())
767 }
768 if tk.Column() <= keyCol && tk.Type() == token.TagType {
769 // key: <value does not defined>
770 // !!tag
771 return nil, errors.ErrSyntax("tag is not allowed in this context", tk.RawToken())
772 }
773
774 if tk.Column() < keyCol {
775 // in this case,
776 // ----
777 // key: <value does not defined>
778 // next
779 return newNullNode(ctx, ctx.insertNullToken(colonTk))
780 }
781
782 if tk.Line() == keyLine && tk.GroupType() == TokenGroupAnchorName &&
783 ctx.nextToken().Column() < keyCol {
784 // in this case,
785 // ----
786 // key: &anchor
787 // next
788 group := &TokenGroup{
789 Type: TokenGroupAnchor,
790 Tokens: []*Token{tk, ctx.createImplicitNullToken(tk)},
791 }
792 anchor, err := p.parseAnchor(ctx.withGroup(group), group)
793 if err != nil {
794 return nil, err
795 }
796 ctx.goNext()
797 return anchor, nil
798 }
799
800 value, err := p.parseToken(ctx, ctx.currentToken())
801 if err != nil {
802 return nil, err
803 }
804 if err := p.validateAnchorValueInMapOrSeq(value, keyCol); err != nil {
805 return nil, err
806 }
807 return value, nil
808 }
809
810 func (p *parser) validateAnchorValueInMapOrSeq(value ast.Node, col int) error {
811 anchor, ok := value.(*ast.AnchorNode)
812 if !ok {
813 return nil
814 }
815 tag, ok := anchor.Value.(*ast.TagNode)
816 if !ok {
817 return nil
818 }
819 anchorTk := anchor.GetToken()
820 tagTk := tag.GetToken()
821
822 if anchorTk.Position.Line == tagTk.Position.Line {
823 // key:
824 // &anchor !!tag
825 //
826 // - &anchor !!tag
827 return nil
828 }
829
830 if tagTk.Position.Column <= col {
831 // key: &anchor
832 // !!tag
833 //
834 // - &anchor
835 // !!tag
836 return errors.ErrSyntax("tag is not allowed in this context", tagTk)
837 }
838 return nil
839 }
840
841 func (p *parser) parseAnchor(ctx *context, g *TokenGroup) (*ast.AnchorNode, error) {
842 anchorNameGroup := g.First().Group
843 anchor, err := p.parseAnchorName(ctx.withGroup(anchorNameGroup))
844 if err != nil {
845 return nil, err
846 }
847 ctx.goNext()
848 if ctx.isTokenNotFound() {
849 return nil, errors.ErrSyntax("could not find anchor value", anchor.GetToken())
850 }
851
852 value, err := p.parseToken(ctx, ctx.currentToken())
853 if err != nil {
854 return nil, err
855 }
856 if _, ok := value.(*ast.AnchorNode); ok {
857 return nil, errors.ErrSyntax("anchors cannot be used consecutively", value.GetToken())
858 }
859 anchor.Value = value
860 return anchor, nil
861 }
862
863 func (p *parser) parseAnchorName(ctx *context) (*ast.AnchorNode, error) {
864 anchor, err := newAnchorNode(ctx, ctx.currentToken())
865 if err != nil {
866 return nil, err
867 }
868 ctx.goNext()
869 if ctx.isTokenNotFound() {
870 return nil, errors.ErrSyntax("could not find anchor value", anchor.GetToken())
871 }
872
873 anchorName, err := p.parseScalarValue(ctx, ctx.currentToken())
874 if err != nil {
875 return nil, err
876 }
877 if anchorName == nil {
878 return nil, errors.ErrSyntax("unexpected anchor. anchor name is not scalar value", ctx.currentToken().RawToken())
879 }
880 anchor.Name = anchorName
881 return anchor, nil
882 }
883
884 func (p *parser) parseAlias(ctx *context) (*ast.AliasNode, error) {
885 alias, err := newAliasNode(ctx, ctx.currentToken())
886 if err != nil {
887 return nil, err
888 }
889 ctx.goNext()
890 if ctx.isTokenNotFound() {
891 return nil, errors.ErrSyntax("could not find alias value", alias.GetToken())
892 }
893
894 aliasName, err := p.parseScalarValue(ctx, ctx.currentToken())
895 if err != nil {
896 return nil, err
897 }
898 if aliasName == nil {
899 return nil, errors.ErrSyntax("unexpected alias. alias name is not scalar value", ctx.currentToken().RawToken())
900 }
901 alias.Value = aliasName
902 return alias, nil
903 }
904
905 func (p *parser) parseLiteral(ctx *context) (*ast.LiteralNode, error) {
906 node, err := newLiteralNode(ctx, ctx.currentToken())
907 if err != nil {
908 return nil, err
909 }
910 ctx.goNext() // skip literal/folded token
911
912 tk := ctx.currentToken()
913 if tk == nil {
914 value, err := newStringNode(ctx, &Token{Token: token.New("", "", node.Start.Position)})
915 if err != nil {
916 return nil, err
917 }
918 node.Value = value
919 return node, nil
920 }
921 value, err := p.parseToken(ctx, tk)
922 if err != nil {
923 return nil, err
924 }
925 str, ok := value.(*ast.StringNode)
926 if !ok {
927 return nil, errors.ErrSyntax("unexpected token. required string token", value.GetToken())
928 }
929 node.Value = str
930 return node, nil
931 }
932
933 func (p *parser) parseScalarTag(ctx *context) (*ast.TagNode, error) {
934 tag, err := p.parseTag(ctx)
935 if err != nil {
936 return nil, err
937 }
938 if tag.Value == nil {
939 return nil, errors.ErrSyntax("specified not scalar tag", tag.GetToken())
940 }
941 if _, ok := tag.Value.(ast.ScalarNode); !ok {
942 return nil, errors.ErrSyntax("specified not scalar tag", tag.GetToken())
943 }
944 return tag, nil
945 }
946
947 func (p *parser) parseTag(ctx *context) (*ast.TagNode, error) {
948 tagTk := ctx.currentToken()
949 tagRawTk := tagTk.RawToken()
950 node, err := newTagNode(ctx, tagTk)
951 if err != nil {
952 return nil, err
953 }
954 ctx.goNext()
955
956 comment := p.parseHeadComment(ctx)
957
958 var tagValue ast.Node
959 if p.secondaryTagDirective != nil {
960 value, err := newStringNode(ctx, ctx.currentToken())
961 if err != nil {
962 return nil, err
963 }
964 tagValue = value
965 node.Directive = p.secondaryTagDirective
966 } else {
967 value, err := p.parseTagValue(ctx, tagRawTk, ctx.currentToken())
968 if err != nil {
969 return nil, err
970 }
971 tagValue = value
972 }
973 if err := setHeadComment(comment, tagValue); err != nil {
974 return nil, err
975 }
976 node.Value = tagValue
977 return node, nil
978 }
979
980 func (p *parser) parseTagValue(ctx *context, tagRawTk *token.Token, tk *Token) (ast.Node, error) {
981 if tk == nil {
982 return newNullNode(ctx, ctx.createImplicitNullToken(&Token{Token: tagRawTk}))
983 }
984 switch token.ReservedTagKeyword(tagRawTk.Value) {
985 case token.MappingTag, token.SetTag:
986 if !p.isMapToken(tk) {
987 return nil, errors.ErrSyntax("could not find map", tk.RawToken())
988 }
989 if tk.Type() == token.MappingStartType {
990 return p.parseFlowMap(ctx.withFlow(true))
991 }
992 return p.parseMap(ctx)
993 case token.IntegerTag, token.FloatTag, token.StringTag, token.BinaryTag, token.TimestampTag, token.BooleanTag, token.NullTag:
994 if tk.GroupType() == TokenGroupLiteral || tk.GroupType() == TokenGroupFolded {
995 return p.parseLiteral(ctx.withGroup(tk.Group))
996 } else if tk.Type() == token.CollectEntryType || tk.Type() == token.MappingValueType {
997 return newTagDefaultScalarValueNode(ctx, tagRawTk)
998 }
999 scalar, err := p.parseScalarValue(ctx, tk)
1000 if err != nil {
1001 return nil, err
1002 }
1003 ctx.goNext()
1004 return scalar, nil
1005 case token.SequenceTag, token.OrderedMapTag:
1006 if tk.Type() == token.SequenceStartType {
1007 return p.parseFlowSequence(ctx.withFlow(true))
1008 }
1009 return p.parseSequence(ctx)
1010 }
1011 return p.parseToken(ctx, tk)
1012 }
1013
1014 func (p *parser) parseFlowSequence(ctx *context) (*ast.SequenceNode, error) {
1015 node, err := newSequenceNode(ctx, ctx.currentToken(), true)
1016 if err != nil {
1017 return nil, err
1018 }
1019 ctx.goNext() // skip SequenceStart token
1020
1021 isFirst := true
1022 for ctx.next() {
1023 tk := ctx.currentToken()
1024 if tk.Type() == token.SequenceEndType {
1025 node.End = tk.RawToken()
1026 break
1027 }
1028
1029 var entryTk *Token
1030 if tk.Type() == token.CollectEntryType {
1031 if isFirst {
1032 return nil, errors.ErrSyntax("expected sequence element, but found ','", tk.RawToken())
1033 }
1034 entryTk = tk
1035 ctx.goNext()
1036 } else if !isFirst {
1037 return nil, errors.ErrSyntax("',' or ']' must be specified", tk.RawToken())
1038 }
1039
1040 if tk := ctx.currentToken(); tk.Type() == token.SequenceEndType {
1041 // this case is here: "[ elem, ]".
1042 // In this case, ignore the last element and break sequence parsing.
1043 node.End = tk.RawToken()
1044 break
1045 }
1046
1047 if ctx.isTokenNotFound() {
1048 break
1049 }
1050
1051 ctx := ctx.withIndex(uint(len(node.Values)))
1052 value, err := p.parseToken(ctx, ctx.currentToken())
1053 if err != nil {
1054 return nil, err
1055 }
1056 node.Values = append(node.Values, value)
1057 seqEntry := ast.SequenceEntry(entryTk.RawToken(), value, nil)
1058 if err := setLineComment(ctx, seqEntry, entryTk); err != nil {
1059 return nil, err
1060 }
1061 seqEntry.SetPath(ctx.path)
1062 node.Entries = append(node.Entries, seqEntry)
1063
1064 isFirst = false
1065 }
1066 if node.End == nil {
1067 return nil, errors.ErrSyntax("sequence end token ']' not found", node.Start)
1068 }
1069 ctx.goNext() // skip sequence end token.
1070 return node, nil
1071 }
1072
1073 func (p *parser) parseSequence(ctx *context) (*ast.SequenceNode, error) {
1074 seqTk := ctx.currentToken()
1075 seqNode, err := newSequenceNode(ctx, seqTk, false)
1076 if err != nil {
1077 return nil, err
1078 }
1079
1080 tk := seqTk
1081 for tk.Type() == token.SequenceEntryType && tk.Column() == seqTk.Column() {
1082 seqTk := tk
1083 headComment := p.parseHeadComment(ctx)
1084 ctx.goNext() // skip sequence entry token
1085
1086 ctx := ctx.withIndex(uint(len(seqNode.Values)))
1087 value, err := p.parseSequenceValue(ctx, seqTk)
1088 if err != nil {
1089 return nil, err
1090 }
1091 seqEntry := ast.SequenceEntry(seqTk.RawToken(), value, headComment)
1092 if err := setLineComment(ctx, seqEntry, seqTk); err != nil {
1093 return nil, err
1094 }
1095 seqEntry.SetPath(ctx.path)
1096 seqNode.ValueHeadComments = append(seqNode.ValueHeadComments, headComment)
1097 seqNode.Values = append(seqNode.Values, value)
1098 seqNode.Entries = append(seqNode.Entries, seqEntry)
1099
1100 if ctx.isComment() {
1101 tk = ctx.nextNotCommentToken()
1102 } else {
1103 tk = ctx.currentToken()
1104 }
1105 }
1106 if ctx.isComment() {
1107 if seqTk.Column() <= ctx.currentToken().Column() {
1108 // If the comment is in the same or deeper column as the last element column in sequence value,
1109 // treat it as a footer comment for the last element.
1110 seqNode.FootComment = p.parseFootComment(ctx, seqTk.Column())
1111 if len(seqNode.Values) != 0 {
1112 seqNode.FootComment.SetPath(seqNode.Values[len(seqNode.Values)-1].GetPath())
1113 }
1114 }
1115 }
1116 return seqNode, nil
1117 }
1118
1119 func (p *parser) parseSequenceValue(ctx *context, seqTk *Token) (ast.Node, error) {
1120 tk := ctx.currentToken()
1121 if tk == nil {
1122 return newNullNode(ctx, ctx.addNullValueToken(seqTk))
1123 }
1124
1125 if ctx.isComment() {
1126 tk = ctx.nextNotCommentToken()
1127 }
1128 seqCol := seqTk.Column()
1129 seqLine := seqTk.Line()
1130
1131 if tk.Column() == seqCol && tk.Type() == token.SequenceEntryType {
1132 // in this case,
1133 // ----
1134 // - <value does not defined>
1135 // -
1136 return newNullNode(ctx, ctx.insertNullToken(seqTk))
1137 }
1138
1139 if tk.Line() == seqLine && tk.GroupType() == TokenGroupAnchorName &&
1140 ctx.nextToken().Column() == seqCol && ctx.nextToken().Type() == token.SequenceEntryType {
1141 // in this case,
1142 // ----
1143 // - &anchor
1144 // -
1145 group := &TokenGroup{
1146 Type: TokenGroupAnchor,
1147 Tokens: []*Token{tk, ctx.createImplicitNullToken(tk)},
1148 }
1149 anchor, err := p.parseAnchor(ctx.withGroup(group), group)
1150 if err != nil {
1151 return nil, err
1152 }
1153 ctx.goNext()
1154 return anchor, nil
1155 }
1156
1157 if tk.Column() <= seqCol && tk.GroupType() == TokenGroupAnchorName {
1158 // - <value does not defined>
1159 // &anchor
1160 return nil, errors.ErrSyntax("anchor is not allowed in this sequence context", tk.RawToken())
1161 }
1162 if tk.Column() <= seqCol && tk.Type() == token.TagType {
1163 // - <value does not defined>
1164 // !!tag
1165 return nil, errors.ErrSyntax("tag is not allowed in this sequence context", tk.RawToken())
1166 }
1167
1168 if tk.Column() < seqCol {
1169 // in this case,
1170 // ----
1171 // - <value does not defined>
1172 // next
1173 return newNullNode(ctx, ctx.insertNullToken(seqTk))
1174 }
1175
1176 if tk.Line() == seqLine && tk.GroupType() == TokenGroupAnchorName &&
1177 ctx.nextToken().Column() < seqCol {
1178 // in this case,
1179 // ----
1180 // - &anchor
1181 // next
1182 group := &TokenGroup{
1183 Type: TokenGroupAnchor,
1184 Tokens: []*Token{tk, ctx.createImplicitNullToken(tk)},
1185 }
1186 anchor, err := p.parseAnchor(ctx.withGroup(group), group)
1187 if err != nil {
1188 return nil, err
1189 }
1190 ctx.goNext()
1191 return anchor, nil
1192 }
1193
1194 value, err := p.parseToken(ctx, ctx.currentToken())
1195 if err != nil {
1196 return nil, err
1197 }
1198 if err := p.validateAnchorValueInMapOrSeq(value, seqCol); err != nil {
1199 return nil, err
1200 }
1201 return value, nil
1202 }
1203
1204 func (p *parser) parseDirective(ctx *context, g *TokenGroup) (*ast.DirectiveNode, error) {
1205 directiveNameGroup := g.First().Group
1206 directive, err := p.parseDirectiveName(ctx.withGroup(directiveNameGroup))
1207 if err != nil {
1208 return nil, err
1209 }
1210
1211 switch directive.Name.String() {
1212 case "YAML":
1213 if len(g.Tokens) != 2 {
1214 return nil, errors.ErrSyntax("unexpected format YAML directive", g.First().RawToken())
1215 }
1216 valueTk := g.Tokens[1]
1217 valueRawTk := valueTk.RawToken()
1218 value := valueRawTk.Value
1219 ver, exists := yamlVersionMap[value]
1220 if !exists {
1221 return nil, errors.ErrSyntax(fmt.Sprintf("unknown YAML version %q", value), valueRawTk)
1222 }
1223 if p.yamlVersion != "" {
1224 return nil, errors.ErrSyntax("YAML version has already been specified", valueRawTk)
1225 }
1226 p.yamlVersion = ver
1227 versionNode, err := newStringNode(ctx, valueTk)
1228 if err != nil {
1229 return nil, err
1230 }
1231 directive.Values = append(directive.Values, versionNode)
1232 case "TAG":
1233 if len(g.Tokens) != 3 {
1234 return nil, errors.ErrSyntax("unexpected format TAG directive", g.First().RawToken())
1235 }
1236 tagKey, err := newStringNode(ctx, g.Tokens[1])
1237 if err != nil {
1238 return nil, err
1239 }
1240 if tagKey.Value == "!!" {
1241 p.secondaryTagDirective = directive
1242 }
1243 tagValue, err := newStringNode(ctx, g.Tokens[2])
1244 if err != nil {
1245 return nil, err
1246 }
1247 directive.Values = append(directive.Values, tagKey, tagValue)
1248 default:
1249 if len(g.Tokens) > 1 {
1250 for _, tk := range g.Tokens[1:] {
1251 value, err := newStringNode(ctx, tk)
1252 if err != nil {
1253 return nil, err
1254 }
1255 directive.Values = append(directive.Values, value)
1256 }
1257 }
1258 }
1259 return directive, nil
1260 }
1261
1262 func (p *parser) parseDirectiveName(ctx *context) (*ast.DirectiveNode, error) {
1263 directive, err := newDirectiveNode(ctx, ctx.currentToken())
1264 if err != nil {
1265 return nil, err
1266 }
1267 ctx.goNext()
1268 if ctx.isTokenNotFound() {
1269 return nil, errors.ErrSyntax("could not find directive value", directive.GetToken())
1270 }
1271
1272 directiveName, err := p.parseScalarValue(ctx, ctx.currentToken())
1273 if err != nil {
1274 return nil, err
1275 }
1276 if directiveName == nil {
1277 return nil, errors.ErrSyntax("unexpected directive. directive name is not scalar value", ctx.currentToken().RawToken())
1278 }
1279 directive.Name = directiveName
1280 return directive, nil
1281 }
1282
1283 func (p *parser) parseComment(ctx *context) (ast.Node, error) {
1284 cm := p.parseHeadComment(ctx)
1285 if ctx.isTokenNotFound() {
1286 return cm, nil
1287 }
1288 node, err := p.parseToken(ctx, ctx.currentToken())
1289 if err != nil {
1290 return nil, err
1291 }
1292 if err := setHeadComment(cm, node); err != nil {
1293 return nil, err
1294 }
1295 return node, nil
1296 }
1297
1298 func (p *parser) parseHeadComment(ctx *context) *ast.CommentGroupNode {
1299 tks := []*token.Token{}
1300 for ctx.isComment() {
1301 tks = append(tks, ctx.currentToken().RawToken())
1302 ctx.goNext()
1303 }
1304 if len(tks) == 0 {
1305 return nil
1306 }
1307 return ast.CommentGroup(tks)
1308 }
1309
1310 func (p *parser) parseFootComment(ctx *context, col int) *ast.CommentGroupNode {
1311 tks := []*token.Token{}
1312 for ctx.isComment() && col <= ctx.currentToken().Column() {
1313 tks = append(tks, ctx.currentToken().RawToken())
1314 ctx.goNext()
1315 }
1316 if len(tks) == 0 {
1317 return nil
1318 }
1319 return ast.CommentGroup(tks)
1320 }