Debian Codegraph @

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

raw
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 parser struct{}
15
16 func (p *parser) parseMapping(ctx *context) (*ast.MappingNode, error) {
17 mapTk := ctx.currentToken()
18 node := ast.Mapping(mapTk, true)
19 node.SetPath(ctx.path)
20 ctx.progress(1) // skip MappingStart token
21 for ctx.next() {
22 tk := ctx.currentToken()
23 if tk.Type == token.MappingEndType {
24 node.End = tk
25 return node, nil
26 } else if tk.Type == token.CollectEntryType {
27 ctx.progress(1)
28 continue
29 }
30
31 value, err := p.parseMappingValue(ctx)
32 if err != nil {
33 return nil, err
34 }
35 mvnode, ok := value.(*ast.MappingValueNode)
36 if !ok {
37 return nil, errors.ErrSyntax("failed to parse flow mapping node", value.GetToken())
38 }
39 node.Values = append(node.Values, mvnode)
40 ctx.progress(1)
41 }
42 return nil, errors.ErrSyntax("unterminated flow mapping", node.GetToken())
43 }
44
45 func (p *parser) parseSequence(ctx *context) (*ast.SequenceNode, error) {
46 node := ast.Sequence(ctx.currentToken(), true)
47 node.SetPath(ctx.path)
48 ctx.progress(1) // skip SequenceStart token
49 for ctx.next() {
50 tk := ctx.currentToken()
51 if tk.Type == token.SequenceEndType {
52 node.End = tk
53 break
54 } else if tk.Type == token.CollectEntryType {
55 ctx.progress(1)
56 continue
57 }
58
59 value, err := p.parseToken(ctx.withIndex(uint(len(node.Values))), tk)
60 if err != nil {
61 return nil, err
62 }
63 node.Values = append(node.Values, value)
64 ctx.progress(1)
65 }
66 return node, nil
67 }
68
69 func (p *parser) parseTag(ctx *context) (*ast.TagNode, error) {
70 tagToken := ctx.currentToken()
71 node := ast.Tag(tagToken)
72 node.SetPath(ctx.path)
73 ctx.progress(1) // skip tag token
74 var (
75 value ast.Node
76 err error
77 )
78 switch token.ReservedTagKeyword(tagToken.Value) {
79 case token.MappingTag,
80 token.OrderedMapTag:
81 value, err = p.parseMapping(ctx)
82 case token.IntegerTag,
83 token.FloatTag,
84 token.StringTag,
85 token.BinaryTag,
86 token.TimestampTag,
87 token.NullTag:
88 typ := ctx.currentToken().Type
89 if typ == token.LiteralType || typ == token.FoldedType {
90 value, err = p.parseLiteral(ctx)
91 } else {
92 value = p.parseScalarValue(ctx.currentToken())
93 }
94 case token.SequenceTag,
95 token.SetTag:
96 err = errors.ErrSyntax(fmt.Sprintf("sorry, currently not supported %s tag", tagToken.Value), tagToken)
97 default:
98 // custom tag
99 value, err = p.parseToken(ctx, ctx.currentToken())
100 }
101 if err != nil {
102 return nil, err
103 }
104 node.Value = value
105 return node, nil
106 }
107
108 func (p *parser) removeLeftSideNewLineCharacter(src string) string {
109 // CR or LF or CRLF
110 return strings.TrimLeft(strings.TrimLeft(strings.TrimLeft(src, "\r"), "\n"), "\r\n")
111 }
112
113 func (p *parser) existsNewLineCharacter(src string) bool {
114 if strings.Index(src, "\n") > 0 {
115 return true
116 }
117 if strings.Index(src, "\r") > 0 {
118 return true
119 }
120 return false
121 }
122
123 func (p *parser) validateMapKey(tk *token.Token) error {
124 if tk.Type != token.StringType {
125 return nil
126 }
127 origin := p.removeLeftSideNewLineCharacter(tk.Origin)
128 if p.existsNewLineCharacter(origin) {
129 return errors.ErrSyntax("unexpected key name", tk)
130 }
131 return nil
132 }
133
134 func (p *parser) createNullToken(base *token.Token) *token.Token {
135 pos := *(base.Position)
136 pos.Column++
137 return token.New("null", "null", &pos)
138 }
139
140 func (p *parser) parseMapValue(ctx *context, key ast.MapKeyNode, colonToken *token.Token) (ast.Node, error) {
141 node, err := p.createMapValueNode(ctx, key, colonToken)
142 if err != nil {
143 return nil, err
144 }
145 if node != nil && node.GetPath() == "" {
146 node.SetPath(ctx.path)
147 }
148 return node, nil
149 }
150
151 func (p *parser) createMapValueNode(ctx *context, key ast.MapKeyNode, colonToken *token.Token) (ast.Node, error) {
152 tk := ctx.currentToken()
153 if tk == nil {
154 nullToken := p.createNullToken(colonToken)
155 ctx.insertToken(ctx.idx, nullToken)
156 return ast.Null(nullToken), nil
157 }
158 var comment *ast.CommentGroupNode
159 if tk.Type == token.CommentType {
160 comment = p.parseCommentOnly(ctx)
161 if comment != nil {
162 comment.SetPath(ctx.withChild(key.GetToken().Value).path)
163 }
164 tk = ctx.currentToken()
165 }
166 if tk.Position.Column == key.GetToken().Position.Column && tk.Type == token.StringType {
167 // in this case,
168 // ----
169 // key: <value does not defined>
170 // next
171
172 nullToken := p.createNullToken(colonToken)
173 ctx.insertToken(ctx.idx, nullToken)
174 nullNode := ast.Null(nullToken)
175
176 if comment != nil {
177 _ = nullNode.SetComment(comment)
178 } else {
179 // If there is a comment, it is already bound to the key node,
180 // so remove the comment from the key to bind it to the null value.
181 keyComment := key.GetComment()
182 if keyComment != nil {
183 if err := key.SetComment(nil); err != nil {
184 return nil, err
185 }
186 _ = nullNode.SetComment(keyComment)
187 }
188 }
189 return nullNode, nil
190 }
191
192 if tk.Position.Column < key.GetToken().Position.Column {
193 // in this case,
194 // ----
195 // key: <value does not defined>
196 // next
197 nullToken := p.createNullToken(colonToken)
198 ctx.insertToken(ctx.idx, nullToken)
199 nullNode := ast.Null(nullToken)
200 if comment != nil {
201 _ = nullNode.SetComment(comment)
202 }
203 return nullNode, nil
204 }
205
206 value, err := p.parseToken(ctx, ctx.currentToken())
207 if err != nil {
208 return nil, err
209 }
210 if comment != nil {
211 _ = value.SetComment(comment)
212 }
213 return value, nil
214 }
215
216 func (p *parser) validateMapValue(ctx *context, key, value ast.Node) error {
217 keyColumn := key.GetToken().Position.Column
218 valueColumn := value.GetToken().Position.Column
219 if keyColumn != valueColumn {
220 return nil
221 }
222 if value.Type() != ast.StringType {
223 return nil
224 }
225 ntk := ctx.nextToken()
226 if ntk == nil || (ntk.Type != token.MappingValueType && ntk.Type != token.SequenceEntryType) {
227 return errors.ErrSyntax("could not found expected ':' token", value.GetToken())
228 }
229 return nil
230 }
231
232 func (p *parser) parseMappingValue(ctx *context) (ast.Node, error) {
233 key, err := p.parseMapKey(ctx)
234 if err != nil {
235 return nil, err
236 }
237 keyText := key.GetToken().Value
238 key.SetPath(ctx.withChild(keyText).path)
239 if err := p.validateMapKey(key.GetToken()); err != nil {
240 return nil, err
241 }
242 ctx.progress(1) // progress to mapping value token
243 tk := ctx.currentToken() // get mapping value token
244 if tk == nil {
245 return nil, errors.ErrSyntax("unexpected map", key.GetToken())
246 }
247 ctx.progress(1) // progress to value token
248 if err := p.setSameLineCommentIfExists(ctx.withChild(keyText), key); err != nil {
249 return nil, err
250 }
251 if key.GetComment() != nil {
252 // if current token is comment, GetComment() is not nil.
253 // then progress to value token
254 ctx.progressIgnoreComment(1)
255 }
256
257 value, err := p.parseMapValue(ctx.withChild(keyText), key, tk)
258 if err != nil {
259 return nil, err
260 }
261 if err := p.validateMapValue(ctx, key, value); err != nil {
262 return nil, err
263 }
264
265 mvnode := ast.MappingValue(tk, key, value)
266 mvnode.SetPath(ctx.withChild(keyText).path)
267 node := ast.Mapping(tk, false, mvnode)
268 node.SetPath(ctx.withChild(keyText).path)
269
270 ntk := ctx.nextNotCommentToken()
271 antk := ctx.afterNextNotCommentToken()
272 for antk != nil && antk.Type == token.MappingValueType &&
273 ntk.Position.Column == key.GetToken().Position.Column {
274 ctx.progressIgnoreComment(1)
275 value, err := p.parseToken(ctx, ctx.currentToken())
276 if err != nil {
277 return nil, err
278 }
279 switch value.Type() {
280 case ast.MappingType:
281 c, _ := value.(*ast.MappingNode)
282 comment := c.GetComment()
283 for idx, v := range c.Values {
284 if idx == 0 && comment != nil {
285 if err := v.SetComment(comment); err != nil {
286 return nil, err
287 }
288 }
289 node.Values = append(node.Values, v)
290 }
291 case ast.MappingValueType:
292 node.Values = append(node.Values, value.(*ast.MappingValueNode))
293 default:
294 return nil, fmt.Errorf("failed to parse mapping value node node is %s", value.Type())
295 }
296 ntk = ctx.nextNotCommentToken()
297 antk = ctx.afterNextNotCommentToken()
298 }
299 if len(node.Values) == 1 {
300 mapKeyCol := mvnode.Key.GetToken().Position.Column
301 commentTk := ctx.nextToken()
302 if commentTk != nil && commentTk.Type == token.CommentType && mapKeyCol <= commentTk.Position.Column {
303 // If the comment is in the same or deeper column as the last element column in map value,
304 // treat it as a footer comment for the last element.
305 comment := p.parseFootComment(ctx, mapKeyCol)
306 mvnode.FootComment = comment
307 }
308 return mvnode, nil
309 }
310 mapCol := node.GetToken().Position.Column
311 commentTk := ctx.nextToken()
312 if commentTk != nil && commentTk.Type == token.CommentType && mapCol <= commentTk.Position.Column {
313 // If the comment is in the same or deeper column as the last element column in map value,
314 // treat it as a footer comment for the last element.
315 comment := p.parseFootComment(ctx, mapCol)
316 node.FootComment = comment
317 }
318 return node, nil
319 }
320
321 func (p *parser) parseSequenceEntry(ctx *context) (*ast.SequenceNode, error) {
322 tk := ctx.currentToken()
323 sequenceNode := ast.Sequence(tk, false)
324 sequenceNode.SetPath(ctx.path)
325 curColumn := tk.Position.Column
326 for tk.Type == token.SequenceEntryType {
327 ctx.progress(1) // skip sequence token
328 tk = ctx.currentToken()
329 if tk == nil {
330 return nil, errors.ErrSyntax("empty sequence entry", ctx.previousToken())
331 }
332 var comment *ast.CommentGroupNode
333 if tk.Type == token.CommentType {
334 comment = p.parseCommentOnly(ctx)
335 tk = ctx.currentToken()
336 if tk.Type == token.SequenceEntryType {
337 ctx.progress(1) // skip sequence token
338 }
339 }
340 value, err := p.parseToken(ctx.withIndex(uint(len(sequenceNode.Values))), ctx.currentToken())
341 if err != nil {
342 return nil, err
343 }
344 if comment != nil {
345 comment.SetPath(ctx.withIndex(uint(len(sequenceNode.Values))).path)
346 sequenceNode.ValueHeadComments = append(sequenceNode.ValueHeadComments, comment)
347 } else {
348 sequenceNode.ValueHeadComments = append(sequenceNode.ValueHeadComments, nil)
349 }
350 sequenceNode.Values = append(sequenceNode.Values, value)
351 tk = ctx.nextNotCommentToken()
352 if tk == nil {
353 break
354 }
355 if tk.Type != token.SequenceEntryType {
356 break
357 }
358 if tk.Position.Column != curColumn {
359 break
360 }
361 ctx.progressIgnoreComment(1)
362 }
363 commentTk := ctx.nextToken()
364 if commentTk != nil && commentTk.Type == token.CommentType && curColumn <= commentTk.Position.Column {
365 // If the comment is in the same or deeper column as the last element column in sequence value,
366 // treat it as a footer comment for the last element.
367 comment := p.parseFootComment(ctx, curColumn)
368 sequenceNode.FootComment = comment
369 }
370 return sequenceNode, nil
371 }
372
373 func (p *parser) parseAnchor(ctx *context) (*ast.AnchorNode, error) {
374 tk := ctx.currentToken()
375 anchor := ast.Anchor(tk)
376 anchor.SetPath(ctx.path)
377 ntk := ctx.nextToken()
378 if ntk == nil {
379 return nil, errors.ErrSyntax("unexpected anchor. anchor name is undefined", tk)
380 }
381 ctx.progress(1) // skip anchor token
382 name, err := p.parseToken(ctx, ctx.currentToken())
383 if err != nil {
384 return nil, err
385 }
386 anchor.Name = name
387 ntk = ctx.nextToken()
388 if ntk == nil {
389 return nil, errors.ErrSyntax("unexpected anchor. anchor value is undefined", ctx.currentToken())
390 }
391 ctx.progress(1)
392 value, err := p.parseToken(ctx, ctx.currentToken())
393 if err != nil {
394 return nil, err
395 }
396 anchor.Value = value
397 return anchor, nil
398 }
399
400 func (p *parser) parseAlias(ctx *context) (*ast.AliasNode, error) {
401 tk := ctx.currentToken()
402 alias := ast.Alias(tk)
403 alias.SetPath(ctx.path)
404 ntk := ctx.nextToken()
405 if ntk == nil {
406 return nil, errors.ErrSyntax("unexpected alias. alias name is undefined", tk)
407 }
408 ctx.progress(1) // skip alias token
409 name, err := p.parseToken(ctx, ctx.currentToken())
410 if err != nil {
411 return nil, err
412 }
413 alias.Value = name
414 return alias, nil
415 }
416
417 func (p *parser) parseMapKey(ctx *context) (ast.MapKeyNode, error) {
418 tk := ctx.currentToken()
419 if value := p.parseScalarValue(tk); value != nil {
420 return value, nil
421 }
422 switch tk.Type {
423 case token.MergeKeyType:
424 return ast.MergeKey(tk), nil
425 case token.MappingKeyType:
426 return p.parseMappingKey(ctx)
427 }
428 return nil, errors.ErrSyntax("unexpected mapping key", tk)
429 }
430
431 func (p *parser) parseStringValue(tk *token.Token) *ast.StringNode {
432 switch tk.Type {
433 case token.StringType,
434 token.SingleQuoteType,
435 token.DoubleQuoteType:
436 return ast.String(tk)
437 }
438 return nil
439 }
440
441 func (p *parser) parseScalarValueWithComment(ctx *context, tk *token.Token) (ast.ScalarNode, error) {
442 node := p.parseScalarValue(tk)
443 if node == nil {
444 return nil, nil
445 }
446 node.SetPath(ctx.path)
447 if p.isSameLineComment(ctx.nextToken(), node) {
448 ctx.progress(1)
449 if err := p.setSameLineCommentIfExists(ctx, node); err != nil {
450 return nil, err
451 }
452 }
453 return node, nil
454 }
455
456 func (p *parser) parseScalarValue(tk *token.Token) ast.ScalarNode {
457 if node := p.parseStringValue(tk); node != nil {
458 return node
459 }
460 switch tk.Type {
461 case token.NullType:
462 return ast.Null(tk)
463 case token.BoolType:
464 return ast.Bool(tk)
465 case token.IntegerType,
466 token.BinaryIntegerType,
467 token.OctetIntegerType,
468 token.HexIntegerType:
469 return ast.Integer(tk)
470 case token.FloatType:
471 return ast.Float(tk)
472 case token.InfinityType:
473 return ast.Infinity(tk)
474 case token.NanType:
475 return ast.Nan(tk)
476 }
477 return nil
478 }
479
480 func (p *parser) parseDirective(ctx *context) (*ast.DirectiveNode, error) {
481 node := ast.Directive(ctx.currentToken())
482 ctx.progress(1) // skip directive token
483 value, err := p.parseToken(ctx, ctx.currentToken())
484 if err != nil {
485 return nil, err
486 }
487 node.Value = value
488 ctx.progress(1)
489 tk := ctx.currentToken()
490 if tk == nil {
491 // Since current token is nil, use the previous token to specify
492 // the syntax error location.
493 return nil, errors.ErrSyntax("unexpected directive value. document not started", ctx.previousToken())
494 }
495 if tk.Type != token.DocumentHeaderType {
496 return nil, errors.ErrSyntax("unexpected directive value. document not started", ctx.currentToken())
497 }
498 return node, nil
499 }
500
501 func (p *parser) parseLiteral(ctx *context) (*ast.LiteralNode, error) {
502 node := ast.Literal(ctx.currentToken())
503 ctx.progress(1) // skip literal/folded token
504
505 tk := ctx.currentToken()
506 var comment *ast.CommentGroupNode
507 if tk.Type == token.CommentType {
508 comment = p.parseCommentOnly(ctx)
509 comment.SetPath(ctx.path)
510 if err := node.SetComment(comment); err != nil {
511 return nil, err
512 }
513 tk = ctx.currentToken()
514 }
515 value, err := p.parseToken(ctx, tk)
516 if err != nil {
517 return nil, err
518 }
519 snode, ok := value.(*ast.StringNode)
520 if !ok {
521 return nil, errors.ErrSyntax("unexpected token. required string token", value.GetToken())
522 }
523 node.Value = snode
524 return node, nil
525 }
526
527 func (p *parser) isSameLineComment(tk *token.Token, node ast.Node) bool {
528 if tk == nil {
529 return false
530 }
531 if tk.Type != token.CommentType {
532 return false
533 }
534 return tk.Position.Line == node.GetToken().Position.Line
535 }
536
537 func (p *parser) setSameLineCommentIfExists(ctx *context, node ast.Node) error {
538 tk := ctx.currentToken()
539 if !p.isSameLineComment(tk, node) {
540 return nil
541 }
542 comment := ast.CommentGroup([]*token.Token{tk})
543 comment.SetPath(ctx.path)
544 if err := node.SetComment(comment); err != nil {
545 return err
546 }
547 return nil
548 }
549
550 func (p *parser) parseDocument(ctx *context) (*ast.DocumentNode, error) {
551 startTk := ctx.currentToken()
552 ctx.progress(1) // skip document header token
553 body, err := p.parseToken(ctx, ctx.currentToken())
554 if err != nil {
555 return nil, err
556 }
557 node := ast.Document(startTk, body)
558 if ntk := ctx.nextToken(); ntk != nil && ntk.Type == token.DocumentEndType {
559 node.End = ntk
560 ctx.progress(1)
561 }
562 return node, nil
563 }
564
565 func (p *parser) parseCommentOnly(ctx *context) *ast.CommentGroupNode {
566 commentTokens := []*token.Token{}
567 for {
568 tk := ctx.currentToken()
569 if tk == nil {
570 break
571 }
572 if tk.Type != token.CommentType {
573 break
574 }
575 commentTokens = append(commentTokens, tk)
576 ctx.progressIgnoreComment(1) // skip comment token
577 }
578 return ast.CommentGroup(commentTokens)
579 }
580
581 func (p *parser) parseFootComment(ctx *context, col int) *ast.CommentGroupNode {
582 commentTokens := []*token.Token{}
583 for {
584 ctx.progressIgnoreComment(1)
585 commentTokens = append(commentTokens, ctx.currentToken())
586
587 nextTk := ctx.nextToken()
588 if nextTk == nil {
589 break
590 }
591 if nextTk.Type != token.CommentType {
592 break
593 }
594 if col > nextTk.Position.Column {
595 break
596 }
597 }
598 return ast.CommentGroup(commentTokens)
599 }
600
601 func (p *parser) parseComment(ctx *context) (ast.Node, error) {
602 group := p.parseCommentOnly(ctx)
603 node, err := p.parseToken(ctx, ctx.currentToken())
604 if err != nil {
605 return nil, err
606 }
607 if node == nil {
608 return group, nil
609 }
610 group.SetPath(node.GetPath())
611 if err := node.SetComment(group); err != nil {
612 return nil, err
613 }
614 return node, nil
615 }
616
617 func (p *parser) parseMappingKey(ctx *context) (*ast.MappingKeyNode, error) {
618 keyTk := ctx.currentToken()
619 node := ast.MappingKey(keyTk)
620 node.SetPath(ctx.path)
621 ctx.progress(1) // skip mapping key token
622 value, err := p.parseToken(ctx.withChild(keyTk.Value), ctx.currentToken())
623 if err != nil {
624 return nil, err
625 }
626 node.Value = value
627 return node, nil
628 }
629
630 func (p *parser) parseToken(ctx *context, tk *token.Token) (ast.Node, error) {
631 node, err := p.createNodeFromToken(ctx, tk)
632 if err != nil {
633 return nil, err
634 }
635 if node != nil && node.GetPath() == "" {
636 node.SetPath(ctx.path)
637 }
638 return node, nil
639 }
640
641 func (p *parser) createNodeFromToken(ctx *context, tk *token.Token) (ast.Node, error) {
642 if tk == nil {
643 return nil, nil
644 }
645 if tk.NextType() == token.MappingValueType {
646 node, err := p.parseMappingValue(ctx)
647 return node, err
648 }
649 node, err := p.parseScalarValueWithComment(ctx, tk)
650 if err != nil {
651 return nil, err
652 }
653 if node != nil {
654 return node, nil
655 }
656 switch tk.Type {
657 case token.CommentType:
658 return p.parseComment(ctx)
659 case token.MappingKeyType:
660 return p.parseMappingKey(ctx)
661 case token.DocumentHeaderType:
662 return p.parseDocument(ctx)
663 case token.MappingStartType:
664 return p.parseMapping(ctx)
665 case token.SequenceStartType:
666 return p.parseSequence(ctx)
667 case token.SequenceEntryType:
668 return p.parseSequenceEntry(ctx)
669 case token.AnchorType:
670 return p.parseAnchor(ctx)
671 case token.AliasType:
672 return p.parseAlias(ctx)
673 case token.DirectiveType:
674 return p.parseDirective(ctx)
675 case token.TagType:
676 return p.parseTag(ctx)
677 case token.LiteralType, token.FoldedType:
678 return p.parseLiteral(ctx)
679 }
680 return nil, nil
681 }
682
683 func (p *parser) parse(tokens token.Tokens, mode Mode) (*ast.File, error) {
684 ctx := newContext(tokens, mode)
685 file := &ast.File{Docs: []*ast.DocumentNode{}}
686 for ctx.next() {
687 node, err := p.parseToken(ctx, ctx.currentToken())
688 if err != nil {
689 return nil, err
690 }
691 ctx.progressIgnoreComment(1)
692 if node == nil {
693 continue
694 }
695 if doc, ok := node.(*ast.DocumentNode); ok {
696 file.Docs = append(file.Docs, doc)
697 } else {
698 file.Docs = append(file.Docs, ast.Document(nil, node))
699 }
700 }
701 return file, nil
702 }
703
704 type Mode uint
705
706 const (
707 ParseComments Mode = 1 << iota // parse comments and add them to AST
708 )
709
710 // ParseBytes parse from byte slice, and returns ast.File
711 func ParseBytes(bytes []byte, mode Mode) (*ast.File, error) {
712 tokens := lexer.Tokenize(string(bytes))
713 f, err := Parse(tokens, mode)
714 if err != nil {
715 return nil, err
716 }
717 return f, nil
718 }
719
720 // Parse parse from token instances, and returns ast.File
721 func Parse(tokens token.Tokens, mode Mode) (*ast.File, error) {
722 var p parser
723 f, err := p.parse(tokens, mode)
724 if err != nil {
725 return nil, err
726 }
727 return f, nil
728 }
729
730 // Parse parse from filename, and returns ast.File
731 func ParseFile(filename string, mode Mode) (*ast.File, error) {
732 file, err := os.ReadFile(filename)
733 if err != nil {
734 return nil, err
735 }
736 f, err := ParseBytes(file, mode)
737 if err != nil {
738 return nil, err
739 }
740 f.Name = filename
741 return f, nil
742 }