Debian Codegraph @

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

raw
1 package ast
2
3 import (
4 "errors"
5 "fmt"
6 "io"
7 "math"
8 "strconv"
9 "strings"
10
11 "github.com/goccy/go-yaml/token"
12 )
13
14 var (
15 ErrInvalidTokenType = errors.New("invalid token type")
16 ErrInvalidAnchorName = errors.New("invalid anchor name")
17 ErrInvalidAliasName = errors.New("invalid alias name")
18 )
19
20 // NodeType type identifier of node
21 type NodeType int
22
23 const (
24 // UnknownNodeType type identifier for default
25 UnknownNodeType NodeType = iota
26 // DocumentType type identifier for document node
27 DocumentType
28 // NullType type identifier for null node
29 NullType
30 // BoolType type identifier for boolean node
31 BoolType
32 // IntegerType type identifier for integer node
33 IntegerType
34 // FloatType type identifier for float node
35 FloatType
36 // InfinityType type identifier for infinity node
37 InfinityType
38 // NanType type identifier for nan node
39 NanType
40 // StringType type identifier for string node
41 StringType
42 // MergeKeyType type identifier for merge key node
43 MergeKeyType
44 // LiteralType type identifier for literal node
45 LiteralType
46 // MappingType type identifier for mapping node
47 MappingType
48 // MappingKeyType type identifier for mapping key node
49 MappingKeyType
50 // MappingValueType type identifier for mapping value node
51 MappingValueType
52 // SequenceType type identifier for sequence node
53 SequenceType
54 // AnchorType type identifier for anchor node
55 AnchorType
56 // AliasType type identifier for alias node
57 AliasType
58 // DirectiveType type identifier for directive node
59 DirectiveType
60 // TagType type identifier for tag node
61 TagType
62 // CommentType type identifier for comment node
63 CommentType
64 // CommentGroupType type identifier for comment group node
65 CommentGroupType
66 )
67
68 // String node type identifier to text
69 func (t NodeType) String() string {
70 switch t {
71 case UnknownNodeType:
72 return "UnknownNode"
73 case DocumentType:
74 return "Document"
75 case NullType:
76 return "Null"
77 case BoolType:
78 return "Bool"
79 case IntegerType:
80 return "Integer"
81 case FloatType:
82 return "Float"
83 case InfinityType:
84 return "Infinity"
85 case NanType:
86 return "Nan"
87 case StringType:
88 return "String"
89 case MergeKeyType:
90 return "MergeKey"
91 case LiteralType:
92 return "Literal"
93 case MappingType:
94 return "Mapping"
95 case MappingKeyType:
96 return "MappingKey"
97 case MappingValueType:
98 return "MappingValue"
99 case SequenceType:
100 return "Sequence"
101 case AnchorType:
102 return "Anchor"
103 case AliasType:
104 return "Alias"
105 case DirectiveType:
106 return "Directive"
107 case TagType:
108 return "Tag"
109 case CommentType:
110 return "Comment"
111 case CommentGroupType:
112 return "CommentGroup"
113 }
114 return ""
115 }
116
117 // String node type identifier to YAML Structure name
118 // based on https://yaml.org/spec/1.2/spec.html
119 func (t NodeType) YAMLName() string {
120 switch t {
121 case UnknownNodeType:
122 return "unknown"
123 case DocumentType:
124 return "document"
125 case NullType:
126 return "null"
127 case BoolType:
128 return "boolean"
129 case IntegerType:
130 return "int"
131 case FloatType:
132 return "float"
133 case InfinityType:
134 return "inf"
135 case NanType:
136 return "nan"
137 case StringType:
138 return "string"
139 case MergeKeyType:
140 return "merge key"
141 case LiteralType:
142 return "scalar"
143 case MappingType:
144 return "mapping"
145 case MappingKeyType:
146 return "key"
147 case MappingValueType:
148 return "value"
149 case SequenceType:
150 return "sequence"
151 case AnchorType:
152 return "anchor"
153 case AliasType:
154 return "alias"
155 case DirectiveType:
156 return "directive"
157 case TagType:
158 return "tag"
159 case CommentType:
160 return "comment"
161 case CommentGroupType:
162 return "comment"
163 }
164 return ""
165 }
166
167 // Node type of node
168 type Node interface {
169 io.Reader
170 // String node to text
171 String() string
172 // GetToken returns token instance
173 GetToken() *token.Token
174 // Type returns type of node
175 Type() NodeType
176 // AddColumn add column number to child nodes recursively
177 AddColumn(int)
178 // SetComment set comment token to node
179 SetComment(*CommentGroupNode) error
180 // Comment returns comment token instance
181 GetComment() *CommentGroupNode
182 // GetPath returns YAMLPath for the current node
183 GetPath() string
184 // SetPath set YAMLPath for the current node
185 SetPath(string)
186 // MarshalYAML
187 MarshalYAML() ([]byte, error)
188 // already read length
189 readLen() int
190 // append read length
191 addReadLen(int)
192 // clean read length
193 clearLen()
194 }
195
196 // MapKeyNode type for map key node
197 type MapKeyNode interface {
198 Node
199 // String node to text without comment
200 stringWithoutComment() string
201 }
202
203 // ScalarNode type for scalar node
204 type ScalarNode interface {
205 MapKeyNode
206 GetValue() interface{}
207 }
208
209 type BaseNode struct {
210 Path string
211 Comment *CommentGroupNode
212 read int
213 }
214
215 func addCommentString(base string, node *CommentGroupNode) string {
216 return fmt.Sprintf("%s %s", base, node.String())
217 }
218
219 func (n *BaseNode) readLen() int {
220 return n.read
221 }
222
223 func (n *BaseNode) clearLen() {
224 n.read = 0
225 }
226
227 func (n *BaseNode) addReadLen(len int) {
228 n.read += len
229 }
230
231 // GetPath returns YAMLPath for the current node.
232 func (n *BaseNode) GetPath() string {
233 if n == nil {
234 return ""
235 }
236 return n.Path
237 }
238
239 // SetPath set YAMLPath for the current node.
240 func (n *BaseNode) SetPath(path string) {
241 if n == nil {
242 return
243 }
244 n.Path = path
245 }
246
247 // GetComment returns comment token instance
248 func (n *BaseNode) GetComment() *CommentGroupNode {
249 return n.Comment
250 }
251
252 // SetComment set comment token
253 func (n *BaseNode) SetComment(node *CommentGroupNode) error {
254 n.Comment = node
255 return nil
256 }
257
258 func min(a, b int) int {
259 if a < b {
260 return a
261 }
262 return b
263 }
264
265 func readNode(p []byte, node Node) (int, error) {
266 s := node.String()
267 readLen := node.readLen()
268 remain := len(s) - readLen
269 if remain == 0 {
270 node.clearLen()
271 return 0, io.EOF
272 }
273 size := min(remain, len(p))
274 for idx, b := range []byte(s[readLen : readLen+size]) {
275 p[idx] = byte(b)
276 }
277 node.addReadLen(size)
278 return size, nil
279 }
280
281 // Null create node for null value
282 func Null(tk *token.Token) *NullNode {
283 return &NullNode{
284 BaseNode: &BaseNode{},
285 Token: tk,
286 }
287 }
288
289 // Bool create node for boolean value
290 func Bool(tk *token.Token) *BoolNode {
291 b, _ := strconv.ParseBool(tk.Value)
292 return &BoolNode{
293 BaseNode: &BaseNode{},
294 Token: tk,
295 Value: b,
296 }
297 }
298
299 // Integer create node for integer value
300 func Integer(tk *token.Token) *IntegerNode {
301 value := removeUnderScoreFromNumber(tk.Value)
302 switch tk.Type {
303 case token.BinaryIntegerType:
304 // skip two characters because binary token starts with '0b'
305 skipCharacterNum := 2
306 negativePrefix := ""
307 if value[0] == '-' {
308 skipCharacterNum++
309 negativePrefix = "-"
310 }
311 if len(negativePrefix) > 0 {
312 i, _ := strconv.ParseInt(negativePrefix+value[skipCharacterNum:], 2, 64)
313 return &IntegerNode{
314 BaseNode: &BaseNode{},
315 Token: tk,
316 Value: i,
317 }
318 }
319 i, _ := strconv.ParseUint(negativePrefix+value[skipCharacterNum:], 2, 64)
320 return &IntegerNode{
321 BaseNode: &BaseNode{},
322 Token: tk,
323 Value: i,
324 }
325 case token.OctetIntegerType:
326 // octet token starts with '0o' or '-0o' or '0' or '-0'
327 skipCharacterNum := 1
328 negativePrefix := ""
329 if value[0] == '-' {
330 skipCharacterNum++
331 if len(value) > 2 && value[2] == 'o' {
332 skipCharacterNum++
333 }
334 negativePrefix = "-"
335 } else {
336 if value[1] == 'o' {
337 skipCharacterNum++
338 }
339 }
340 if len(negativePrefix) > 0 {
341 i, _ := strconv.ParseInt(negativePrefix+value[skipCharacterNum:], 8, 64)
342 return &IntegerNode{
343 BaseNode: &BaseNode{},
344 Token: tk,
345 Value: i,
346 }
347 }
348 i, _ := strconv.ParseUint(value[skipCharacterNum:], 8, 64)
349 return &IntegerNode{
350 BaseNode: &BaseNode{},
351 Token: tk,
352 Value: i,
353 }
354 case token.HexIntegerType:
355 // hex token starts with '0x' or '-0x'
356 skipCharacterNum := 2
357 negativePrefix := ""
358 if value[0] == '-' {
359 skipCharacterNum++
360 negativePrefix = "-"
361 }
362 if len(negativePrefix) > 0 {
363 i, _ := strconv.ParseInt(negativePrefix+value[skipCharacterNum:], 16, 64)
364 return &IntegerNode{
365 BaseNode: &BaseNode{},
366 Token: tk,
367 Value: i,
368 }
369 }
370 i, _ := strconv.ParseUint(value[skipCharacterNum:], 16, 64)
371 return &IntegerNode{
372 BaseNode: &BaseNode{},
373 Token: tk,
374 Value: i,
375 }
376 }
377 if value[0] == '-' || value[0] == '+' {
378 i, _ := strconv.ParseInt(value, 10, 64)
379 return &IntegerNode{
380 BaseNode: &BaseNode{},
381 Token: tk,
382 Value: i,
383 }
384 }
385 i, _ := strconv.ParseUint(value, 10, 64)
386 return &IntegerNode{
387 BaseNode: &BaseNode{},
388 Token: tk,
389 Value: i,
390 }
391 }
392
393 // Float create node for float value
394 func Float(tk *token.Token) *FloatNode {
395 f, _ := strconv.ParseFloat(removeUnderScoreFromNumber(tk.Value), 64)
396 return &FloatNode{
397 BaseNode: &BaseNode{},
398 Token: tk,
399 Value: f,
400 }
401 }
402
403 // Infinity create node for .inf or -.inf value
404 func Infinity(tk *token.Token) *InfinityNode {
405 node := &InfinityNode{
406 BaseNode: &BaseNode{},
407 Token: tk,
408 }
409 switch tk.Value {
410 case ".inf", ".Inf", ".INF":
411 node.Value = math.Inf(0)
412 case "-.inf", "-.Inf", "-.INF":
413 node.Value = math.Inf(-1)
414 }
415 return node
416 }
417
418 // Nan create node for .nan value
419 func Nan(tk *token.Token) *NanNode {
420 return &NanNode{
421 BaseNode: &BaseNode{},
422 Token: tk,
423 }
424 }
425
426 // String create node for string value
427 func String(tk *token.Token) *StringNode {
428 return &StringNode{
429 BaseNode: &BaseNode{},
430 Token: tk,
431 Value: tk.Value,
432 }
433 }
434
435 // Comment create node for comment
436 func Comment(tk *token.Token) *CommentNode {
437 return &CommentNode{
438 BaseNode: &BaseNode{},
439 Token: tk,
440 }
441 }
442
443 func CommentGroup(comments []*token.Token) *CommentGroupNode {
444 nodes := []*CommentNode{}
445 for _, comment := range comments {
446 nodes = append(nodes, Comment(comment))
447 }
448 return &CommentGroupNode{
449 BaseNode: &BaseNode{},
450 Comments: nodes,
451 }
452 }
453
454 // MergeKey create node for merge key ( << )
455 func MergeKey(tk *token.Token) *MergeKeyNode {
456 return &MergeKeyNode{
457 BaseNode: &BaseNode{},
458 Token: tk,
459 }
460 }
461
462 // Mapping create node for map
463 func Mapping(tk *token.Token, isFlowStyle bool, values ...*MappingValueNode) *MappingNode {
464 node := &MappingNode{
465 BaseNode: &BaseNode{},
466 Start: tk,
467 IsFlowStyle: isFlowStyle,
468 Values: []*MappingValueNode{},
469 }
470 node.Values = append(node.Values, values...)
471 return node
472 }
473
474 // MappingValue create node for mapping value
475 func MappingValue(tk *token.Token, key MapKeyNode, value Node) *MappingValueNode {
476 return &MappingValueNode{
477 BaseNode: &BaseNode{},
478 Start: tk,
479 Key: key,
480 Value: value,
481 }
482 }
483
484 // MappingKey create node for map key ( '?' ).
485 func MappingKey(tk *token.Token) *MappingKeyNode {
486 return &MappingKeyNode{
487 BaseNode: &BaseNode{},
488 Start: tk,
489 }
490 }
491
492 // Sequence create node for sequence
493 func Sequence(tk *token.Token, isFlowStyle bool) *SequenceNode {
494 return &SequenceNode{
495 BaseNode: &BaseNode{},
496 Start: tk,
497 IsFlowStyle: isFlowStyle,
498 Values: []Node{},
499 }
500 }
501
502 func Anchor(tk *token.Token) *AnchorNode {
503 return &AnchorNode{
504 BaseNode: &BaseNode{},
505 Start: tk,
506 }
507 }
508
509 func Alias(tk *token.Token) *AliasNode {
510 return &AliasNode{
511 BaseNode: &BaseNode{},
512 Start: tk,
513 }
514 }
515
516 func Document(tk *token.Token, body Node) *DocumentNode {
517 return &DocumentNode{
518 BaseNode: &BaseNode{},
519 Start: tk,
520 Body: body,
521 }
522 }
523
524 func Directive(tk *token.Token) *DirectiveNode {
525 return &DirectiveNode{
526 BaseNode: &BaseNode{},
527 Start: tk,
528 }
529 }
530
531 func Literal(tk *token.Token) *LiteralNode {
532 return &LiteralNode{
533 BaseNode: &BaseNode{},
534 Start: tk,
535 }
536 }
537
538 func Tag(tk *token.Token) *TagNode {
539 return &TagNode{
540 BaseNode: &BaseNode{},
541 Start: tk,
542 }
543 }
544
545 // File contains all documents in YAML file
546 type File struct {
547 Name string
548 Docs []*DocumentNode
549 }
550
551 // Read implements (io.Reader).Read
552 func (f *File) Read(p []byte) (int, error) {
553 for _, doc := range f.Docs {
554 n, err := doc.Read(p)
555 if err == io.EOF {
556 continue
557 }
558 return n, nil
559 }
560 return 0, io.EOF
561 }
562
563 // String all documents to text
564 func (f *File) String() string {
565 docs := []string{}
566 for _, doc := range f.Docs {
567 docs = append(docs, doc.String())
568 }
569 if len(docs) > 0 {
570 return strings.Join(docs, "\n") + "\n"
571 } else {
572 return ""
573 }
574 }
575
576 // DocumentNode type of Document
577 type DocumentNode struct {
578 *BaseNode
579 Start *token.Token // position of DocumentHeader ( `---` )
580 End *token.Token // position of DocumentEnd ( `...` )
581 Body Node
582 }
583
584 // Read implements (io.Reader).Read
585 func (d *DocumentNode) Read(p []byte) (int, error) {
586 return readNode(p, d)
587 }
588
589 // Type returns DocumentNodeType
590 func (d *DocumentNode) Type() NodeType { return DocumentType }
591
592 // GetToken returns token instance
593 func (d *DocumentNode) GetToken() *token.Token {
594 return d.Body.GetToken()
595 }
596
597 // AddColumn add column number to child nodes recursively
598 func (d *DocumentNode) AddColumn(col int) {
599 if d.Body != nil {
600 d.Body.AddColumn(col)
601 }
602 }
603
604 // String document to text
605 func (d *DocumentNode) String() string {
606 doc := []string{}
607 if d.Start != nil {
608 doc = append(doc, d.Start.Value)
609 }
610 doc = append(doc, d.Body.String())
611 if d.End != nil {
612 doc = append(doc, d.End.Value)
613 }
614 return strings.Join(doc, "\n")
615 }
616
617 // MarshalYAML encodes to a YAML text
618 func (d *DocumentNode) MarshalYAML() ([]byte, error) {
619 return []byte(d.String()), nil
620 }
621
622 func removeUnderScoreFromNumber(num string) string {
623 return strings.ReplaceAll(num, "_", "")
624 }
625
626 // NullNode type of null node
627 type NullNode struct {
628 *BaseNode
629 Token *token.Token
630 }
631
632 // Read implements (io.Reader).Read
633 func (n *NullNode) Read(p []byte) (int, error) {
634 return readNode(p, n)
635 }
636
637 // Type returns NullType
638 func (n *NullNode) Type() NodeType { return NullType }
639
640 // GetToken returns token instance
641 func (n *NullNode) GetToken() *token.Token {
642 return n.Token
643 }
644
645 // AddColumn add column number to child nodes recursively
646 func (n *NullNode) AddColumn(col int) {
647 n.Token.AddColumn(col)
648 }
649
650 // GetValue returns nil value
651 func (n *NullNode) GetValue() interface{} {
652 return nil
653 }
654
655 // String returns `null` text
656 func (n *NullNode) String() string {
657 if n.Comment != nil {
658 return addCommentString("null", n.Comment)
659 }
660 return n.stringWithoutComment()
661 }
662
663 func (n *NullNode) stringWithoutComment() string {
664 return "null"
665 }
666
667 // MarshalYAML encodes to a YAML text
668 func (n *NullNode) MarshalYAML() ([]byte, error) {
669 return []byte(n.String()), nil
670 }
671
672 // IntegerNode type of integer node
673 type IntegerNode struct {
674 *BaseNode
675 Token *token.Token
676 Value interface{} // int64 or uint64 value
677 }
678
679 // Read implements (io.Reader).Read
680 func (n *IntegerNode) Read(p []byte) (int, error) {
681 return readNode(p, n)
682 }
683
684 // Type returns IntegerType
685 func (n *IntegerNode) Type() NodeType { return IntegerType }
686
687 // GetToken returns token instance
688 func (n *IntegerNode) GetToken() *token.Token {
689 return n.Token
690 }
691
692 // AddColumn add column number to child nodes recursively
693 func (n *IntegerNode) AddColumn(col int) {
694 n.Token.AddColumn(col)
695 }
696
697 // GetValue returns int64 value
698 func (n *IntegerNode) GetValue() interface{} {
699 return n.Value
700 }
701
702 // String int64 to text
703 func (n *IntegerNode) String() string {
704 if n.Comment != nil {
705 return addCommentString(n.Token.Value, n.Comment)
706 }
707 return n.stringWithoutComment()
708 }
709
710 func (n *IntegerNode) stringWithoutComment() string {
711 return n.Token.Value
712 }
713
714 // MarshalYAML encodes to a YAML text
715 func (n *IntegerNode) MarshalYAML() ([]byte, error) {
716 return []byte(n.String()), nil
717 }
718
719 // FloatNode type of float node
720 type FloatNode struct {
721 *BaseNode
722 Token *token.Token
723 Precision int
724 Value float64
725 }
726
727 // Read implements (io.Reader).Read
728 func (n *FloatNode) Read(p []byte) (int, error) {
729 return readNode(p, n)
730 }
731
732 // Type returns FloatType
733 func (n *FloatNode) Type() NodeType { return FloatType }
734
735 // GetToken returns token instance
736 func (n *FloatNode) GetToken() *token.Token {
737 return n.Token
738 }
739
740 // AddColumn add column number to child nodes recursively
741 func (n *FloatNode) AddColumn(col int) {
742 n.Token.AddColumn(col)
743 }
744
745 // GetValue returns float64 value
746 func (n *FloatNode) GetValue() interface{} {
747 return n.Value
748 }
749
750 // String float64 to text
751 func (n *FloatNode) String() string {
752 if n.Comment != nil {
753 return addCommentString(n.Token.Value, n.Comment)
754 }
755 return n.stringWithoutComment()
756 }
757
758 func (n *FloatNode) stringWithoutComment() string {
759 return n.Token.Value
760 }
761
762 // MarshalYAML encodes to a YAML text
763 func (n *FloatNode) MarshalYAML() ([]byte, error) {
764 return []byte(n.String()), nil
765 }
766
767 // StringNode type of string node
768 type StringNode struct {
769 *BaseNode
770 Token *token.Token
771 Value string
772 }
773
774 // Read implements (io.Reader).Read
775 func (n *StringNode) Read(p []byte) (int, error) {
776 return readNode(p, n)
777 }
778
779 // Type returns StringType
780 func (n *StringNode) Type() NodeType { return StringType }
781
782 // GetToken returns token instance
783 func (n *StringNode) GetToken() *token.Token {
784 return n.Token
785 }
786
787 // AddColumn add column number to child nodes recursively
788 func (n *StringNode) AddColumn(col int) {
789 n.Token.AddColumn(col)
790 }
791
792 // GetValue returns string value
793 func (n *StringNode) GetValue() interface{} {
794 return n.Value
795 }
796
797 // escapeSingleQuote escapes s to a single quoted scalar.
798 // https://yaml.org/spec/1.2.2/#732-single-quoted-style
799 func escapeSingleQuote(s string) string {
800 var sb strings.Builder
801 growLen := len(s) + // s includes also one ' from the doubled pair
802 2 + // opening and closing '
803 strings.Count(s, "'") // ' added by ReplaceAll
804 sb.Grow(growLen)
805 sb.WriteString("'")
806 sb.WriteString(strings.ReplaceAll(s, "'", "''"))
807 sb.WriteString("'")
808 return sb.String()
809 }
810
811 // String string value to text with quote or literal header if required
812 func (n *StringNode) String() string {
813 switch n.Token.Type {
814 case token.SingleQuoteType:
815 quoted := escapeSingleQuote(n.Value)
816 if n.Comment != nil {
817 return addCommentString(quoted, n.Comment)
818 }
819 return quoted
820 case token.DoubleQuoteType:
821 quoted := strconv.Quote(n.Value)
822 if n.Comment != nil {
823 return addCommentString(quoted, n.Comment)
824 }
825 return quoted
826 }
827
828 lbc := token.DetectLineBreakCharacter(n.Value)
829 if strings.Contains(n.Value, lbc) {
830 // This block assumes that the line breaks in this inside scalar content and the Outside scalar content are the same.
831 // It works mostly, but inconsistencies occur if line break characters are mixed.
832 header := token.LiteralBlockHeader(n.Value)
833 space := strings.Repeat(" ", n.Token.Position.Column-1)
834 values := []string{}
835 for _, v := range strings.Split(n.Value, lbc) {
836 values = append(values, fmt.Sprintf("%s %s", space, v))
837 }
838 block := strings.TrimSuffix(strings.TrimSuffix(strings.Join(values, lbc), fmt.Sprintf("%s %s", lbc, space)), fmt.Sprintf(" %s", space))
839 return fmt.Sprintf("%s%s%s", header, lbc, block)
840 } else if len(n.Value) > 0 && (n.Value[0] == '{' || n.Value[0] == '[') {
841 return fmt.Sprintf(`'%s'`, n.Value)
842 }
843 if n.Comment != nil {
844 return addCommentString(n.Value, n.Comment)
845 }
846 return n.Value
847 }
848
849 func (n *StringNode) stringWithoutComment() string {
850 switch n.Token.Type {
851 case token.SingleQuoteType:
852 quoted := fmt.Sprintf(`'%s'`, n.Value)
853 return quoted
854 case token.DoubleQuoteType:
855 quoted := strconv.Quote(n.Value)
856 return quoted
857 }
858
859 lbc := token.DetectLineBreakCharacter(n.Value)
860 if strings.Contains(n.Value, lbc) {
861 // This block assumes that the line breaks in this inside scalar content and the Outside scalar content are the same.
862 // It works mostly, but inconsistencies occur if line break characters are mixed.
863 header := token.LiteralBlockHeader(n.Value)
864 space := strings.Repeat(" ", n.Token.Position.Column-1)
865 values := []string{}
866 for _, v := range strings.Split(n.Value, lbc) {
867 values = append(values, fmt.Sprintf("%s %s", space, v))
868 }
869 block := strings.TrimSuffix(strings.TrimSuffix(strings.Join(values, lbc), fmt.Sprintf("%s %s", lbc, space)), fmt.Sprintf(" %s", space))
870 return fmt.Sprintf("%s%s%s", header, lbc, block)
871 } else if len(n.Value) > 0 && (n.Value[0] == '{' || n.Value[0] == '[') {
872 return fmt.Sprintf(`'%s'`, n.Value)
873 }
874 return n.Value
875 }
876
877 // MarshalYAML encodes to a YAML text
878 func (n *StringNode) MarshalYAML() ([]byte, error) {
879 return []byte(n.String()), nil
880 }
881
882 // LiteralNode type of literal node
883 type LiteralNode struct {
884 *BaseNode
885 Start *token.Token
886 Value *StringNode
887 }
888
889 // Read implements (io.Reader).Read
890 func (n *LiteralNode) Read(p []byte) (int, error) {
891 return readNode(p, n)
892 }
893
894 // Type returns LiteralType
895 func (n *LiteralNode) Type() NodeType { return LiteralType }
896
897 // GetToken returns token instance
898 func (n *LiteralNode) GetToken() *token.Token {
899 return n.Start
900 }
901
902 // AddColumn add column number to child nodes recursively
903 func (n *LiteralNode) AddColumn(col int) {
904 n.Start.AddColumn(col)
905 if n.Value != nil {
906 n.Value.AddColumn(col)
907 }
908 }
909
910 // GetValue returns string value
911 func (n *LiteralNode) GetValue() interface{} {
912 return n.String()
913 }
914
915 // String literal to text
916 func (n *LiteralNode) String() string {
917 origin := n.Value.GetToken().Origin
918 lit := strings.TrimRight(strings.TrimRight(origin, " "), "\n")
919 if n.Comment != nil {
920 return fmt.Sprintf("%s %s\n%s", n.Start.Value, n.Comment.String(), lit)
921 }
922 return fmt.Sprintf("%s\n%s", n.Start.Value, lit)
923 }
924
925 func (n *LiteralNode) stringWithoutComment() string {
926 return n.String()
927 }
928
929 // MarshalYAML encodes to a YAML text
930 func (n *LiteralNode) MarshalYAML() ([]byte, error) {
931 return []byte(n.String()), nil
932 }
933
934 // MergeKeyNode type of merge key node
935 type MergeKeyNode struct {
936 *BaseNode
937 Token *token.Token
938 }
939
940 // Read implements (io.Reader).Read
941 func (n *MergeKeyNode) Read(p []byte) (int, error) {
942 return readNode(p, n)
943 }
944
945 // Type returns MergeKeyType
946 func (n *MergeKeyNode) Type() NodeType { return MergeKeyType }
947
948 // GetToken returns token instance
949 func (n *MergeKeyNode) GetToken() *token.Token {
950 return n.Token
951 }
952
953 // GetValue returns '<<' value
954 func (n *MergeKeyNode) GetValue() interface{} {
955 return n.Token.Value
956 }
957
958 // String returns '<<' value
959 func (n *MergeKeyNode) String() string {
960 return n.stringWithoutComment()
961 }
962
963 func (n *MergeKeyNode) stringWithoutComment() string {
964 return n.Token.Value
965 }
966
967 // AddColumn add column number to child nodes recursively
968 func (n *MergeKeyNode) AddColumn(col int) {
969 n.Token.AddColumn(col)
970 }
971
972 // MarshalYAML encodes to a YAML text
973 func (n *MergeKeyNode) MarshalYAML() ([]byte, error) {
974 return []byte(n.String()), nil
975 }
976
977 // BoolNode type of boolean node
978 type BoolNode struct {
979 *BaseNode
980 Token *token.Token
981 Value bool
982 }
983
984 // Read implements (io.Reader).Read
985 func (n *BoolNode) Read(p []byte) (int, error) {
986 return readNode(p, n)
987 }
988
989 // Type returns BoolType
990 func (n *BoolNode) Type() NodeType { return BoolType }
991
992 // GetToken returns token instance
993 func (n *BoolNode) GetToken() *token.Token {
994 return n.Token
995 }
996
997 // AddColumn add column number to child nodes recursively
998 func (n *BoolNode) AddColumn(col int) {
999 n.Token.AddColumn(col)
1000 }
1001
1002 // GetValue returns boolean value
1003 func (n *BoolNode) GetValue() interface{} {
1004 return n.Value
1005 }
1006
1007 // String boolean to text
1008 func (n *BoolNode) String() string {
1009 if n.Comment != nil {
1010 return addCommentString(n.Token.Value, n.Comment)
1011 }
1012 return n.stringWithoutComment()
1013 }
1014
1015 func (n *BoolNode) stringWithoutComment() string {
1016 return n.Token.Value
1017 }
1018
1019 // MarshalYAML encodes to a YAML text
1020 func (n *BoolNode) MarshalYAML() ([]byte, error) {
1021 return []byte(n.String()), nil
1022 }
1023
1024 // InfinityNode type of infinity node
1025 type InfinityNode struct {
1026 *BaseNode
1027 Token *token.Token
1028 Value float64
1029 }
1030
1031 // Read implements (io.Reader).Read
1032 func (n *InfinityNode) Read(p []byte) (int, error) {
1033 return readNode(p, n)
1034 }
1035
1036 // Type returns InfinityType
1037 func (n *InfinityNode) Type() NodeType { return InfinityType }
1038
1039 // GetToken returns token instance
1040 func (n *InfinityNode) GetToken() *token.Token {
1041 return n.Token
1042 }
1043
1044 // AddColumn add column number to child nodes recursively
1045 func (n *InfinityNode) AddColumn(col int) {
1046 n.Token.AddColumn(col)
1047 }
1048
1049 // GetValue returns math.Inf(0) or math.Inf(-1)
1050 func (n *InfinityNode) GetValue() interface{} {
1051 return n.Value
1052 }
1053
1054 // String infinity to text
1055 func (n *InfinityNode) String() string {
1056 if n.Comment != nil {
1057 return addCommentString(n.Token.Value, n.Comment)
1058 }
1059 return n.stringWithoutComment()
1060 }
1061
1062 func (n *InfinityNode) stringWithoutComment() string {
1063 return n.Token.Value
1064 }
1065
1066 // MarshalYAML encodes to a YAML text
1067 func (n *InfinityNode) MarshalYAML() ([]byte, error) {
1068 return []byte(n.String()), nil
1069 }
1070
1071 // NanNode type of nan node
1072 type NanNode struct {
1073 *BaseNode
1074 Token *token.Token
1075 }
1076
1077 // Read implements (io.Reader).Read
1078 func (n *NanNode) Read(p []byte) (int, error) {
1079 return readNode(p, n)
1080 }
1081
1082 // Type returns NanType
1083 func (n *NanNode) Type() NodeType { return NanType }
1084
1085 // GetToken returns token instance
1086 func (n *NanNode) GetToken() *token.Token {
1087 return n.Token
1088 }
1089
1090 // AddColumn add column number to child nodes recursively
1091 func (n *NanNode) AddColumn(col int) {
1092 n.Token.AddColumn(col)
1093 }
1094
1095 // GetValue returns math.NaN()
1096 func (n *NanNode) GetValue() interface{} {
1097 return math.NaN()
1098 }
1099
1100 // String returns .nan
1101 func (n *NanNode) String() string {
1102 if n.Comment != nil {
1103 return addCommentString(n.Token.Value, n.Comment)
1104 }
1105 return n.stringWithoutComment()
1106 }
1107
1108 func (n *NanNode) stringWithoutComment() string {
1109 return n.Token.Value
1110 }
1111
1112 // MarshalYAML encodes to a YAML text
1113 func (n *NanNode) MarshalYAML() ([]byte, error) {
1114 return []byte(n.String()), nil
1115 }
1116
1117 // MapNode interface of MappingValueNode / MappingNode
1118 type MapNode interface {
1119 MapRange() *MapNodeIter
1120 }
1121
1122 // MapNodeIter is an iterator for ranging over a MapNode
1123 type MapNodeIter struct {
1124 values []*MappingValueNode
1125 idx int
1126 }
1127
1128 const (
1129 startRangeIndex = -1
1130 )
1131
1132 // Next advances the map iterator and reports whether there is another entry.
1133 // It returns false when the iterator is exhausted.
1134 func (m *MapNodeIter) Next() bool {
1135 m.idx++
1136 next := m.idx < len(m.values)
1137 return next
1138 }
1139
1140 // Key returns the key of the iterator's current map node entry.
1141 func (m *MapNodeIter) Key() MapKeyNode {
1142 return m.values[m.idx].Key
1143 }
1144
1145 // Value returns the value of the iterator's current map node entry.
1146 func (m *MapNodeIter) Value() Node {
1147 return m.values[m.idx].Value
1148 }
1149
1150 // MappingNode type of mapping node
1151 type MappingNode struct {
1152 *BaseNode
1153 Start *token.Token
1154 End *token.Token
1155 IsFlowStyle bool
1156 Values []*MappingValueNode
1157 FootComment *CommentGroupNode
1158 }
1159
1160 func (n *MappingNode) startPos() *token.Position {
1161 if len(n.Values) == 0 {
1162 return n.Start.Position
1163 }
1164 return n.Values[0].Key.GetToken().Position
1165 }
1166
1167 // Merge merge key/value of map.
1168 func (n *MappingNode) Merge(target *MappingNode) {
1169 keyToMapValueMap := map[string]*MappingValueNode{}
1170 for _, value := range n.Values {
1171 key := value.Key.String()
1172 keyToMapValueMap[key] = value
1173 }
1174 column := n.startPos().Column - target.startPos().Column
1175 target.AddColumn(column)
1176 for _, value := range target.Values {
1177 mapValue, exists := keyToMapValueMap[value.Key.String()]
1178 if exists {
1179 mapValue.Value = value.Value
1180 } else {
1181 n.Values = append(n.Values, value)
1182 }
1183 }
1184 }
1185
1186 // SetIsFlowStyle set value to IsFlowStyle field recursively.
1187 func (n *MappingNode) SetIsFlowStyle(isFlow bool) {
1188 n.IsFlowStyle = isFlow
1189 for _, value := range n.Values {
1190 value.SetIsFlowStyle(isFlow)
1191 }
1192 }
1193
1194 // Read implements (io.Reader).Read
1195 func (n *MappingNode) Read(p []byte) (int, error) {
1196 return readNode(p, n)
1197 }
1198
1199 // Type returns MappingType
1200 func (n *MappingNode) Type() NodeType { return MappingType }
1201
1202 // GetToken returns token instance
1203 func (n *MappingNode) GetToken() *token.Token {
1204 return n.Start
1205 }
1206
1207 // AddColumn add column number to child nodes recursively
1208 func (n *MappingNode) AddColumn(col int) {
1209 n.Start.AddColumn(col)
1210 n.End.AddColumn(col)
1211 for _, value := range n.Values {
1212 value.AddColumn(col)
1213 }
1214 }
1215
1216 func (n *MappingNode) flowStyleString(commentMode bool) string {
1217 values := []string{}
1218 for _, value := range n.Values {
1219 values = append(values, strings.TrimLeft(value.String(), " "))
1220 }
1221 mapText := fmt.Sprintf("{%s}", strings.Join(values, ", "))
1222 if commentMode && n.Comment != nil {
1223 return addCommentString(mapText, n.Comment)
1224 }
1225 return mapText
1226 }
1227
1228 func (n *MappingNode) blockStyleString(commentMode bool) string {
1229 values := []string{}
1230 for _, value := range n.Values {
1231 values = append(values, value.String())
1232 }
1233 mapText := strings.Join(values, "\n")
1234 if commentMode && n.Comment != nil {
1235 value := values[0]
1236 var spaceNum int
1237 for i := 0; i < len(value); i++ {
1238 if value[i] != ' ' {
1239 break
1240 }
1241 spaceNum++
1242 }
1243 comment := n.Comment.StringWithSpace(spaceNum)
1244 return fmt.Sprintf("%s\n%s", comment, mapText)
1245 }
1246 return mapText
1247 }
1248
1249 // String mapping values to text
1250 func (n *MappingNode) String() string {
1251 if len(n.Values) == 0 {
1252 if n.Comment != nil {
1253 return addCommentString("{}", n.Comment)
1254 }
1255 return "{}"
1256 }
1257
1258 commentMode := true
1259 if n.IsFlowStyle || len(n.Values) == 0 {
1260 return n.flowStyleString(commentMode)
1261 }
1262 return n.blockStyleString(commentMode)
1263 }
1264
1265 // MapRange implements MapNode protocol
1266 func (n *MappingNode) MapRange() *MapNodeIter {
1267 return &MapNodeIter{
1268 idx: startRangeIndex,
1269 values: n.Values,
1270 }
1271 }
1272
1273 // MarshalYAML encodes to a YAML text
1274 func (n *MappingNode) MarshalYAML() ([]byte, error) {
1275 return []byte(n.String()), nil
1276 }
1277
1278 // MappingKeyNode type of tag node
1279 type MappingKeyNode struct {
1280 *BaseNode
1281 Start *token.Token
1282 Value Node
1283 }
1284
1285 // Read implements (io.Reader).Read
1286 func (n *MappingKeyNode) Read(p []byte) (int, error) {
1287 return readNode(p, n)
1288 }
1289
1290 // Type returns MappingKeyType
1291 func (n *MappingKeyNode) Type() NodeType { return MappingKeyType }
1292
1293 // GetToken returns token instance
1294 func (n *MappingKeyNode) GetToken() *token.Token {
1295 return n.Start
1296 }
1297
1298 // AddColumn add column number to child nodes recursively
1299 func (n *MappingKeyNode) AddColumn(col int) {
1300 n.Start.AddColumn(col)
1301 if n.Value != nil {
1302 n.Value.AddColumn(col)
1303 }
1304 }
1305
1306 // String tag to text
1307 func (n *MappingKeyNode) String() string {
1308 return n.stringWithoutComment()
1309 }
1310
1311 func (n *MappingKeyNode) stringWithoutComment() string {
1312 return fmt.Sprintf("%s %s", n.Start.Value, n.Value.String())
1313 }
1314
1315 // MarshalYAML encodes to a YAML text
1316 func (n *MappingKeyNode) MarshalYAML() ([]byte, error) {
1317 return []byte(n.String()), nil
1318 }
1319
1320 // MappingValueNode type of mapping value
1321 type MappingValueNode struct {
1322 *BaseNode
1323 Start *token.Token
1324 Key MapKeyNode
1325 Value Node
1326 FootComment *CommentGroupNode
1327 }
1328
1329 // Replace replace value node.
1330 func (n *MappingValueNode) Replace(value Node) error {
1331 column := n.Value.GetToken().Position.Column - value.GetToken().Position.Column
1332 value.AddColumn(column)
1333 n.Value = value
1334 return nil
1335 }
1336
1337 // Read implements (io.Reader).Read
1338 func (n *MappingValueNode) Read(p []byte) (int, error) {
1339 return readNode(p, n)
1340 }
1341
1342 // Type returns MappingValueType
1343 func (n *MappingValueNode) Type() NodeType { return MappingValueType }
1344
1345 // GetToken returns token instance
1346 func (n *MappingValueNode) GetToken() *token.Token {
1347 return n.Start
1348 }
1349
1350 // AddColumn add column number to child nodes recursively
1351 func (n *MappingValueNode) AddColumn(col int) {
1352 n.Start.AddColumn(col)
1353 if n.Key != nil {
1354 n.Key.AddColumn(col)
1355 }
1356 if n.Value != nil {
1357 n.Value.AddColumn(col)
1358 }
1359 }
1360
1361 // SetIsFlowStyle set value to IsFlowStyle field recursively.
1362 func (n *MappingValueNode) SetIsFlowStyle(isFlow bool) {
1363 switch value := n.Value.(type) {
1364 case *MappingNode:
1365 value.SetIsFlowStyle(isFlow)
1366 case *MappingValueNode:
1367 value.SetIsFlowStyle(isFlow)
1368 case *SequenceNode:
1369 value.SetIsFlowStyle(isFlow)
1370 }
1371 }
1372
1373 // String mapping value to text
1374 func (n *MappingValueNode) String() string {
1375 var text string
1376 if n.Comment != nil {
1377 text = fmt.Sprintf(
1378 "%s\n%s",
1379 n.Comment.StringWithSpace(n.Key.GetToken().Position.Column-1),
1380 n.toString(),
1381 )
1382 } else {
1383 text = n.toString()
1384 }
1385 if n.FootComment != nil {
1386 text += fmt.Sprintf("\n%s", n.FootComment.StringWithSpace(n.Key.GetToken().Position.Column-1))
1387 }
1388 return text
1389 }
1390
1391 func (n *MappingValueNode) toString() string {
1392 space := strings.Repeat(" ", n.Key.GetToken().Position.Column-1)
1393 keyIndentLevel := n.Key.GetToken().Position.IndentLevel
1394 valueIndentLevel := n.Value.GetToken().Position.IndentLevel
1395 keyComment := n.Key.GetComment()
1396 if _, ok := n.Value.(ScalarNode); ok {
1397 return fmt.Sprintf("%s%s: %s", space, n.Key.String(), n.Value.String())
1398 } else if keyIndentLevel < valueIndentLevel {
1399 if keyComment != nil {
1400 return fmt.Sprintf(
1401 "%s%s: %s\n%s",
1402 space,
1403 n.Key.stringWithoutComment(),
1404 keyComment.String(),
1405 n.Value.String(),
1406 )
1407 }
1408 return fmt.Sprintf("%s%s:\n%s", space, n.Key.String(), n.Value.String())
1409 } else if m, ok := n.Value.(*MappingNode); ok && (m.IsFlowStyle || len(m.Values) == 0) {
1410 return fmt.Sprintf("%s%s: %s", space, n.Key.String(), n.Value.String())
1411 } else if s, ok := n.Value.(*SequenceNode); ok && (s.IsFlowStyle || len(s.Values) == 0) {
1412 return fmt.Sprintf("%s%s: %s", space, n.Key.String(), n.Value.String())
1413 } else if _, ok := n.Value.(*AnchorNode); ok {
1414 return fmt.Sprintf("%s%s: %s", space, n.Key.String(), n.Value.String())
1415 } else if _, ok := n.Value.(*AliasNode); ok {
1416 return fmt.Sprintf("%s%s: %s", space, n.Key.String(), n.Value.String())
1417 }
1418 if keyComment != nil {
1419 return fmt.Sprintf(
1420 "%s%s: %s\n%s",
1421 space,
1422 n.Key.stringWithoutComment(),
1423 keyComment.String(),
1424 n.Value.String(),
1425 )
1426 }
1427 if m, ok := n.Value.(*MappingNode); ok && m.Comment != nil {
1428 return fmt.Sprintf(
1429 "%s%s: %s",
1430 space,
1431 n.Key.String(),
1432 strings.TrimLeft(n.Value.String(), " "),
1433 )
1434 }
1435 return fmt.Sprintf("%s%s:\n%s", space, n.Key.String(), n.Value.String())
1436 }
1437
1438 // MapRange implements MapNode protocol
1439 func (n *MappingValueNode) MapRange() *MapNodeIter {
1440 return &MapNodeIter{
1441 idx: startRangeIndex,
1442 values: []*MappingValueNode{n},
1443 }
1444 }
1445
1446 // MarshalYAML encodes to a YAML text
1447 func (n *MappingValueNode) MarshalYAML() ([]byte, error) {
1448 return []byte(n.String()), nil
1449 }
1450
1451 // ArrayNode interface of SequenceNode
1452 type ArrayNode interface {
1453 ArrayRange() *ArrayNodeIter
1454 }
1455
1456 // ArrayNodeIter is an iterator for ranging over a ArrayNode
1457 type ArrayNodeIter struct {
1458 values []Node
1459 idx int
1460 }
1461
1462 // Next advances the array iterator and reports whether there is another entry.
1463 // It returns false when the iterator is exhausted.
1464 func (m *ArrayNodeIter) Next() bool {
1465 m.idx++
1466 next := m.idx < len(m.values)
1467 return next
1468 }
1469
1470 // Value returns the value of the iterator's current array entry.
1471 func (m *ArrayNodeIter) Value() Node {
1472 return m.values[m.idx]
1473 }
1474
1475 // Len returns length of array
1476 func (m *ArrayNodeIter) Len() int {
1477 return len(m.values)
1478 }
1479
1480 // SequenceNode type of sequence node
1481 type SequenceNode struct {
1482 *BaseNode
1483 Start *token.Token
1484 End *token.Token
1485 IsFlowStyle bool
1486 Values []Node
1487 ValueHeadComments []*CommentGroupNode
1488 FootComment *CommentGroupNode
1489 }
1490
1491 // Replace replace value node.
1492 func (n *SequenceNode) Replace(idx int, value Node) error {
1493 if len(n.Values) <= idx {
1494 return fmt.Errorf(
1495 "invalid index for sequence: sequence length is %d, but specified %d index",
1496 len(n.Values), idx,
1497 )
1498 }
1499 column := n.Values[idx].GetToken().Position.Column - value.GetToken().Position.Column
1500 value.AddColumn(column)
1501 n.Values[idx] = value
1502 return nil
1503 }
1504
1505 // Merge merge sequence value.
1506 func (n *SequenceNode) Merge(target *SequenceNode) {
1507 column := n.Start.Position.Column - target.Start.Position.Column
1508 target.AddColumn(column)
1509 n.Values = append(n.Values, target.Values...)
1510 }
1511
1512 // SetIsFlowStyle set value to IsFlowStyle field recursively.
1513 func (n *SequenceNode) SetIsFlowStyle(isFlow bool) {
1514 n.IsFlowStyle = isFlow
1515 for _, value := range n.Values {
1516 switch value := value.(type) {
1517 case *MappingNode:
1518 value.SetIsFlowStyle(isFlow)
1519 case *MappingValueNode:
1520 value.SetIsFlowStyle(isFlow)
1521 case *SequenceNode:
1522 value.SetIsFlowStyle(isFlow)
1523 }
1524 }
1525 }
1526
1527 // Read implements (io.Reader).Read
1528 func (n *SequenceNode) Read(p []byte) (int, error) {
1529 return readNode(p, n)
1530 }
1531
1532 // Type returns SequenceType
1533 func (n *SequenceNode) Type() NodeType { return SequenceType }
1534
1535 // GetToken returns token instance
1536 func (n *SequenceNode) GetToken() *token.Token {
1537 return n.Start
1538 }
1539
1540 // AddColumn add column number to child nodes recursively
1541 func (n *SequenceNode) AddColumn(col int) {
1542 n.Start.AddColumn(col)
1543 n.End.AddColumn(col)
1544 for _, value := range n.Values {
1545 value.AddColumn(col)
1546 }
1547 }
1548
1549 func (n *SequenceNode) flowStyleString() string {
1550 values := []string{}
1551 for _, value := range n.Values {
1552 values = append(values, value.String())
1553 }
1554 return fmt.Sprintf("[%s]", strings.Join(values, ", "))
1555 }
1556
1557 func (n *SequenceNode) blockStyleString() string {
1558 space := strings.Repeat(" ", n.Start.Position.Column-1)
1559 values := []string{}
1560 if n.Comment != nil {
1561 values = append(values, n.Comment.StringWithSpace(n.Start.Position.Column-1))
1562 }
1563
1564 for idx, value := range n.Values {
1565 valueStr := value.String()
1566 splittedValues := strings.Split(valueStr, "\n")
1567 trimmedFirstValue := strings.TrimLeft(splittedValues[0], " ")
1568 diffLength := len(splittedValues[0]) - len(trimmedFirstValue)
1569 if len(splittedValues) > 1 && value.Type() == StringType || value.Type() == LiteralType {
1570 // If multi-line string, the space characters for indent have already been added, so delete them.
1571 prefix := space + " "
1572 for i := 1; i < len(splittedValues); i++ {
1573 splittedValues[i] = strings.TrimPrefix(splittedValues[i], prefix)
1574 }
1575 }
1576 newValues := []string{trimmedFirstValue}
1577 for i := 1; i < len(splittedValues); i++ {
1578 if len(splittedValues[i]) <= diffLength {
1579 // this line is \n or white space only
1580 newValues = append(newValues, "")
1581 continue
1582 }
1583 trimmed := splittedValues[i][diffLength:]
1584 newValues = append(newValues, fmt.Sprintf("%s %s", space, trimmed))
1585 }
1586 newValue := strings.Join(newValues, "\n")
1587 if len(n.ValueHeadComments) == len(n.Values) && n.ValueHeadComments[idx] != nil {
1588 values = append(values, n.ValueHeadComments[idx].StringWithSpace(n.Start.Position.Column-1))
1589 }
1590 values = append(values, fmt.Sprintf("%s- %s", space, newValue))
1591 }
1592 if n.FootComment != nil {
1593 values = append(values, n.FootComment.StringWithSpace(n.Start.Position.Column-1))
1594 }
1595 return strings.Join(values, "\n")
1596 }
1597
1598 // String sequence to text
1599 func (n *SequenceNode) String() string {
1600 if n.IsFlowStyle || len(n.Values) == 0 {
1601 return n.flowStyleString()
1602 }
1603 return n.blockStyleString()
1604 }
1605
1606 // ArrayRange implements ArrayNode protocol
1607 func (n *SequenceNode) ArrayRange() *ArrayNodeIter {
1608 return &ArrayNodeIter{
1609 idx: startRangeIndex,
1610 values: n.Values,
1611 }
1612 }
1613
1614 // MarshalYAML encodes to a YAML text
1615 func (n *SequenceNode) MarshalYAML() ([]byte, error) {
1616 return []byte(n.String()), nil
1617 }
1618
1619 // AnchorNode type of anchor node
1620 type AnchorNode struct {
1621 *BaseNode
1622 Start *token.Token
1623 Name Node
1624 Value Node
1625 }
1626
1627 func (n *AnchorNode) SetName(name string) error {
1628 if n.Name == nil {
1629 return ErrInvalidAnchorName
1630 }
1631 s, ok := n.Name.(*StringNode)
1632 if !ok {
1633 return ErrInvalidAnchorName
1634 }
1635 s.Value = name
1636 return nil
1637 }
1638
1639 // Read implements (io.Reader).Read
1640 func (n *AnchorNode) Read(p []byte) (int, error) {
1641 return readNode(p, n)
1642 }
1643
1644 // Type returns AnchorType
1645 func (n *AnchorNode) Type() NodeType { return AnchorType }
1646
1647 // GetToken returns token instance
1648 func (n *AnchorNode) GetToken() *token.Token {
1649 return n.Start
1650 }
1651
1652 // AddColumn add column number to child nodes recursively
1653 func (n *AnchorNode) AddColumn(col int) {
1654 n.Start.AddColumn(col)
1655 if n.Name != nil {
1656 n.Name.AddColumn(col)
1657 }
1658 if n.Value != nil {
1659 n.Value.AddColumn(col)
1660 }
1661 }
1662
1663 // String anchor to text
1664 func (n *AnchorNode) String() string {
1665 value := n.Value.String()
1666 if len(strings.Split(value, "\n")) > 1 {
1667 return fmt.Sprintf("&%s\n%s", n.Name.String(), value)
1668 } else if s, ok := n.Value.(*SequenceNode); ok && !s.IsFlowStyle {
1669 return fmt.Sprintf("&%s\n%s", n.Name.String(), value)
1670 } else if m, ok := n.Value.(*MappingNode); ok && !m.IsFlowStyle {
1671 return fmt.Sprintf("&%s\n%s", n.Name.String(), value)
1672 }
1673 return fmt.Sprintf("&%s %s", n.Name.String(), value)
1674 }
1675
1676 // MarshalYAML encodes to a YAML text
1677 func (n *AnchorNode) MarshalYAML() ([]byte, error) {
1678 return []byte(n.String()), nil
1679 }
1680
1681 // AliasNode type of alias node
1682 type AliasNode struct {
1683 *BaseNode
1684 Start *token.Token
1685 Value Node
1686 }
1687
1688 func (n *AliasNode) SetName(name string) error {
1689 if n.Value == nil {
1690 return ErrInvalidAliasName
1691 }
1692 s, ok := n.Value.(*StringNode)
1693 if !ok {
1694 return ErrInvalidAliasName
1695 }
1696 s.Value = name
1697 return nil
1698 }
1699
1700 // Read implements (io.Reader).Read
1701 func (n *AliasNode) Read(p []byte) (int, error) {
1702 return readNode(p, n)
1703 }
1704
1705 // Type returns AliasType
1706 func (n *AliasNode) Type() NodeType { return AliasType }
1707
1708 // GetToken returns token instance
1709 func (n *AliasNode) GetToken() *token.Token {
1710 return n.Start
1711 }
1712
1713 // AddColumn add column number to child nodes recursively
1714 func (n *AliasNode) AddColumn(col int) {
1715 n.Start.AddColumn(col)
1716 if n.Value != nil {
1717 n.Value.AddColumn(col)
1718 }
1719 }
1720
1721 // String alias to text
1722 func (n *AliasNode) String() string {
1723 return fmt.Sprintf("*%s", n.Value.String())
1724 }
1725
1726 // MarshalYAML encodes to a YAML text
1727 func (n *AliasNode) MarshalYAML() ([]byte, error) {
1728 return []byte(n.String()), nil
1729 }
1730
1731 // DirectiveNode type of directive node
1732 type DirectiveNode struct {
1733 *BaseNode
1734 Start *token.Token
1735 Value Node
1736 }
1737
1738 // Read implements (io.Reader).Read
1739 func (n *DirectiveNode) Read(p []byte) (int, error) {
1740 return readNode(p, n)
1741 }
1742
1743 // Type returns DirectiveType
1744 func (n *DirectiveNode) Type() NodeType { return DirectiveType }
1745
1746 // GetToken returns token instance
1747 func (n *DirectiveNode) GetToken() *token.Token {
1748 return n.Start
1749 }
1750
1751 // AddColumn add column number to child nodes recursively
1752 func (n *DirectiveNode) AddColumn(col int) {
1753 if n.Value != nil {
1754 n.Value.AddColumn(col)
1755 }
1756 }
1757
1758 // String directive to text
1759 func (n *DirectiveNode) String() string {
1760 return fmt.Sprintf("%s%s", n.Start.Value, n.Value.String())
1761 }
1762
1763 // MarshalYAML encodes to a YAML text
1764 func (n *DirectiveNode) MarshalYAML() ([]byte, error) {
1765 return []byte(n.String()), nil
1766 }
1767
1768 // TagNode type of tag node
1769 type TagNode struct {
1770 *BaseNode
1771 Start *token.Token
1772 Value Node
1773 }
1774
1775 // Read implements (io.Reader).Read
1776 func (n *TagNode) Read(p []byte) (int, error) {
1777 return readNode(p, n)
1778 }
1779
1780 // Type returns TagType
1781 func (n *TagNode) Type() NodeType { return TagType }
1782
1783 // GetToken returns token instance
1784 func (n *TagNode) GetToken() *token.Token {
1785 return n.Start
1786 }
1787
1788 // AddColumn add column number to child nodes recursively
1789 func (n *TagNode) AddColumn(col int) {
1790 n.Start.AddColumn(col)
1791 if n.Value != nil {
1792 n.Value.AddColumn(col)
1793 }
1794 }
1795
1796 // String tag to text
1797 func (n *TagNode) String() string {
1798 return fmt.Sprintf("%s %s", n.Start.Value, n.Value.String())
1799 }
1800
1801 // MarshalYAML encodes to a YAML text
1802 func (n *TagNode) MarshalYAML() ([]byte, error) {
1803 return []byte(n.String()), nil
1804 }
1805
1806 // CommentNode type of comment node
1807 type CommentNode struct {
1808 *BaseNode
1809 Token *token.Token
1810 }
1811
1812 // Read implements (io.Reader).Read
1813 func (n *CommentNode) Read(p []byte) (int, error) {
1814 return readNode(p, n)
1815 }
1816
1817 // Type returns TagType
1818 func (n *CommentNode) Type() NodeType { return CommentType }
1819
1820 // GetToken returns token instance
1821 func (n *CommentNode) GetToken() *token.Token { return n.Token }
1822
1823 // AddColumn add column number to child nodes recursively
1824 func (n *CommentNode) AddColumn(col int) {
1825 if n.Token == nil {
1826 return
1827 }
1828 n.Token.AddColumn(col)
1829 }
1830
1831 // String comment to text
1832 func (n *CommentNode) String() string {
1833 return fmt.Sprintf("#%s", n.Token.Value)
1834 }
1835
1836 // MarshalYAML encodes to a YAML text
1837 func (n *CommentNode) MarshalYAML() ([]byte, error) {
1838 return []byte(n.String()), nil
1839 }
1840
1841 // CommentGroupNode type of comment node
1842 type CommentGroupNode struct {
1843 *BaseNode
1844 Comments []*CommentNode
1845 }
1846
1847 // Read implements (io.Reader).Read
1848 func (n *CommentGroupNode) Read(p []byte) (int, error) {
1849 return readNode(p, n)
1850 }
1851
1852 // Type returns TagType
1853 func (n *CommentGroupNode) Type() NodeType { return CommentType }
1854
1855 // GetToken returns token instance
1856 func (n *CommentGroupNode) GetToken() *token.Token {
1857 if len(n.Comments) > 0 {
1858 return n.Comments[0].Token
1859 }
1860 return nil
1861 }
1862
1863 // AddColumn add column number to child nodes recursively
1864 func (n *CommentGroupNode) AddColumn(col int) {
1865 for _, comment := range n.Comments {
1866 comment.AddColumn(col)
1867 }
1868 }
1869
1870 // String comment to text
1871 func (n *CommentGroupNode) String() string {
1872 values := []string{}
1873 for _, comment := range n.Comments {
1874 values = append(values, comment.String())
1875 }
1876 return strings.Join(values, "\n")
1877 }
1878
1879 func (n *CommentGroupNode) StringWithSpace(col int) string {
1880 values := []string{}
1881 space := strings.Repeat(" ", col)
1882 for _, comment := range n.Comments {
1883 values = append(values, space+comment.String())
1884 }
1885 return strings.Join(values, "\n")
1886
1887 }
1888
1889 // MarshalYAML encodes to a YAML text
1890 func (n *CommentGroupNode) MarshalYAML() ([]byte, error) {
1891 return []byte(n.String()), nil
1892 }
1893
1894 // Visitor has Visit method that is invokded for each node encountered by Walk.
1895 // If the result visitor w is not nil, Walk visits each of the children of node with the visitor w,
1896 // followed by a call of w.Visit(nil).
1897 type Visitor interface {
1898 Visit(Node) Visitor
1899 }
1900
1901 // Walk traverses an AST in depth-first order: It starts by calling v.Visit(node); node must not be nil.
1902 // If the visitor w returned by v.Visit(node) is not nil,
1903 // Walk is invoked recursively with visitor w for each of the non-nil children of node,
1904 // followed by a call of w.Visit(nil).
1905 func Walk(v Visitor, node Node) {
1906 if v = v.Visit(node); v == nil {
1907 return
1908 }
1909
1910 switch n := node.(type) {
1911 case *CommentNode:
1912 case *NullNode:
1913 walkComment(v, n.BaseNode)
1914 case *IntegerNode:
1915 walkComment(v, n.BaseNode)
1916 case *FloatNode:
1917 walkComment(v, n.BaseNode)
1918 case *StringNode:
1919 walkComment(v, n.BaseNode)
1920 case *MergeKeyNode:
1921 walkComment(v, n.BaseNode)
1922 case *BoolNode:
1923 walkComment(v, n.BaseNode)
1924 case *InfinityNode:
1925 walkComment(v, n.BaseNode)
1926 case *NanNode:
1927 walkComment(v, n.BaseNode)
1928 case *LiteralNode:
1929 walkComment(v, n.BaseNode)
1930 Walk(v, n.Value)
1931 case *DirectiveNode:
1932 walkComment(v, n.BaseNode)
1933 Walk(v, n.Value)
1934 case *TagNode:
1935 walkComment(v, n.BaseNode)
1936 Walk(v, n.Value)
1937 case *DocumentNode:
1938 walkComment(v, n.BaseNode)
1939 Walk(v, n.Body)
1940 case *MappingNode:
1941 walkComment(v, n.BaseNode)
1942 for _, value := range n.Values {
1943 Walk(v, value)
1944 }
1945 case *MappingKeyNode:
1946 walkComment(v, n.BaseNode)
1947 Walk(v, n.Value)
1948 case *MappingValueNode:
1949 walkComment(v, n.BaseNode)
1950 Walk(v, n.Key)
1951 Walk(v, n.Value)
1952 case *SequenceNode:
1953 walkComment(v, n.BaseNode)
1954 for _, value := range n.Values {
1955 Walk(v, value)
1956 }
1957 case *AnchorNode:
1958 walkComment(v, n.BaseNode)
1959 Walk(v, n.Name)
1960 Walk(v, n.Value)
1961 case *AliasNode:
1962 walkComment(v, n.BaseNode)
1963 Walk(v, n.Value)
1964 }
1965 }
1966
1967 func walkComment(v Visitor, base *BaseNode) {
1968 if base == nil {
1969 return
1970 }
1971 if base.Comment == nil {
1972 return
1973 }
1974 Walk(v, base.Comment)
1975 }
1976
1977 type filterWalker struct {
1978 typ NodeType
1979 results []Node
1980 }
1981
1982 func (v *filterWalker) Visit(n Node) Visitor {
1983 if v.typ == n.Type() {
1984 v.results = append(v.results, n)
1985 }
1986 return v
1987 }
1988
1989 type parentFinder struct {
1990 target Node
1991 }
1992
1993 func (f *parentFinder) walk(parent, node Node) Node {
1994 if f.target == node {
1995 return parent
1996 }
1997 switch n := node.(type) {
1998 case *CommentNode:
1999 return nil
2000 case *NullNode:
2001 return nil
2002 case *IntegerNode:
2003 return nil
2004 case *FloatNode:
2005 return nil
2006 case *StringNode:
2007 return nil
2008 case *MergeKeyNode:
2009 return nil
2010 case *BoolNode:
2011 return nil
2012 case *InfinityNode:
2013 return nil
2014 case *NanNode:
2015 return nil
2016 case *LiteralNode:
2017 return f.walk(node, n.Value)
2018 case *DirectiveNode:
2019 return f.walk(node, n.Value)
2020 case *TagNode:
2021 return f.walk(node, n.Value)
2022 case *DocumentNode:
2023 return f.walk(node, n.Body)
2024 case *MappingNode:
2025 for _, value := range n.Values {
2026 if found := f.walk(node, value); found != nil {
2027 return found
2028 }
2029 }
2030 case *MappingKeyNode:
2031 return f.walk(node, n.Value)
2032 case *MappingValueNode:
2033 if found := f.walk(node, n.Key); found != nil {
2034 return found
2035 }
2036 return f.walk(node, n.Value)
2037 case *SequenceNode:
2038 for _, value := range n.Values {
2039 if found := f.walk(node, value); found != nil {
2040 return found
2041 }
2042 }
2043 case *AnchorNode:
2044 if found := f.walk(node, n.Name); found != nil {
2045 return found
2046 }
2047 return f.walk(node, n.Value)
2048 case *AliasNode:
2049 return f.walk(node, n.Value)
2050 }
2051 return nil
2052 }
2053
2054 // Parent get parent node from child node.
2055 func Parent(root, child Node) Node {
2056 finder := &parentFinder{target: child}
2057 return finder.walk(root, root)
2058 }
2059
2060 // Filter returns a list of nodes that match the given type.
2061 func Filter(typ NodeType, node Node) []Node {
2062 walker := &filterWalker{typ: typ}
2063 Walk(walker, node)
2064 return walker.results
2065 }
2066
2067 // FilterFile returns a list of nodes that match the given type.
2068 func FilterFile(typ NodeType, file *File) []Node {
2069 results := []Node{}
2070 for _, doc := range file.Docs {
2071 walker := &filterWalker{typ: typ}
2072 Walk(walker, doc)
2073 results = append(results, walker.results...)
2074 }
2075 return results
2076 }
2077
2078 type ErrInvalidMergeType struct {
2079 dst Node
2080 src Node
2081 }
2082
2083 func (e *ErrInvalidMergeType) Error() string {
2084 return fmt.Sprintf("cannot merge %s into %s", e.src.Type(), e.dst.Type())
2085 }
2086
2087 // Merge merge document, map, sequence node.
2088 func Merge(dst Node, src Node) error {
2089 if doc, ok := src.(*DocumentNode); ok {
2090 src = doc.Body
2091 }
2092 err := &ErrInvalidMergeType{dst: dst, src: src}
2093 switch dst.Type() {
2094 case DocumentType:
2095 node, _ := dst.(*DocumentNode)
2096 return Merge(node.Body, src)
2097 case MappingType:
2098 node, _ := dst.(*MappingNode)
2099 target, ok := src.(*MappingNode)
2100 if !ok {
2101 return err
2102 }
2103 node.Merge(target)
2104 return nil
2105 case SequenceType:
2106 node, _ := dst.(*SequenceNode)
2107 target, ok := src.(*SequenceNode)
2108 if !ok {
2109 return err
2110 }
2111 node.Merge(target)
2112 return nil
2113 }
2114 return err
2115 }