This example demonstrates how to parse a TOML document and preserving comments. Comments are stored in the AST as Comment nodes. This example displays the structure of the full AST generated by the parser using the following structure: 1. Each root-level expression is separated by three dashes. 2.
()
| 769 | // 3. Siblings have the same indentation. |
| 770 | // 4. Children of a node are indented one level. |
| 771 | func ExampleParser_comments() { |
| 772 | doc := `# Top of the document comment. |
| 773 | # Optional, any amount of lines. |
| 774 | |
| 775 | # Above table. |
| 776 | [table] # Next to table. |
| 777 | # Above simple value. |
| 778 | key = "value" # Next to simple value. |
| 779 | # Below simple value. |
| 780 | |
| 781 | # Some comment alone. |
| 782 | |
| 783 | # Multiple comments, on multiple lines. |
| 784 | |
| 785 | # Above inline table. |
| 786 | name = { first = "Tom", last = "Preston-Werner" } # Next to inline table. |
| 787 | # Below inline table. |
| 788 | |
| 789 | # Above array. |
| 790 | array = [ 1, 2, 3 ] # Next to one-line array. |
| 791 | # Below array. |
| 792 | |
| 793 | # Above multi-line array. |
| 794 | key5 = [ # Next to start of inline array. |
| 795 | # Second line before array content. |
| 796 | 1, # Next to first element. |
| 797 | # After first element. |
| 798 | # Before second element. |
| 799 | 2, |
| 800 | 3, # Next to last element |
| 801 | # After last element. |
| 802 | ] # Next to end of array. |
| 803 | # Below multi-line array. |
| 804 | |
| 805 | # Before array table. |
| 806 | [[products]] # Next to array table. |
| 807 | # After array table. |
| 808 | ` |
| 809 | |
| 810 | var printGeneric func(*Parser, int, *Node) |
| 811 | printGeneric = func(p *Parser, indent int, e *Node) { |
| 812 | if e == nil { |
| 813 | return |
| 814 | } |
| 815 | s := p.Shape(e.Raw) |
| 816 | x := fmt.Sprintf("%d:%d->%d:%d (%d->%d)", s.Start.Line, s.Start.Column, s.End.Line, s.End.Column, s.Start.Offset, s.End.Offset) |
| 817 | fmt.Printf("%-25s | %s%s [%s]\n", x, strings.Repeat(" ", indent), e.Kind, e.Data) |
| 818 | printGeneric(p, indent+1, e.Child()) |
| 819 | printGeneric(p, indent, e.Next()) |
| 820 | } |
| 821 | |
| 822 | printTree := func(p *Parser) { |
| 823 | for p.NextExpression() { |
| 824 | e := p.Expression() |
| 825 | fmt.Println("---") |
| 826 | printGeneric(p, 0, e) |
| 827 | } |
| 828 | if err := p.Error(); err != nil { |
nothing calls this directly
no test coverage detected
searching dependent graphs…