From 5ccd90ef52e1e632236f7326478d4faa74f99438 Mon Sep 17 00:00:00 2001 From: Sergey Kamardin Date: Fri, 9 Feb 2018 00:06:56 +0300 Subject: [PATCH] syntax/ast: pretty printing --- syntax/ast/ast.go | 50 +++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 50 insertions(+) diff --git a/syntax/ast/ast.go b/syntax/ast/ast.go index a903a20..3220a69 100644 --- a/syntax/ast/ast.go +++ b/syntax/ast/ast.go @@ -1,5 +1,10 @@ package ast +import ( + "bytes" + "fmt" +) + type Node struct { Parent *Node Children []*Node @@ -36,6 +41,26 @@ func (a *Node) Equal(b *Node) bool { return true } +func (a *Node) String() string { + var buf bytes.Buffer + buf.WriteString(a.Kind.String()) + if a.Value != nil { + buf.WriteString(" =") + buf.WriteString(fmt.Sprintf("%v", a.Value)) + } + if len(a.Children) > 0 { + buf.WriteString(" [") + for i, c := range a.Children { + if i > 0 { + buf.WriteString(", ") + } + buf.WriteString(c.String()) + } + buf.WriteString("]") + } + return buf.String() +} + func Insert(parent *Node, children ...*Node) { parent.Children = append(parent.Children, children...) for _, ch := range children { @@ -70,3 +95,28 @@ const ( KindSingle KindAnyOf ) + +func (k Kind) String() string { + switch k { + case KindNothing: + return "Nothing" + case KindPattern: + return "Pattern" + case KindList: + return "List" + case KindRange: + return "Range" + case KindText: + return "Text" + case KindAny: + return "Any" + case KindSuper: + return "Super" + case KindSingle: + return "Single" + case KindAnyOf: + return "AnyOf" + default: + return "" + } +}