From 407cd650d139e5921b17dffc090b840732b77d1f Mon Sep 17 00:00:00 2001 From: Fatih Arslan Date: Fri, 30 Oct 2015 22:51:35 +0300 Subject: [PATCH] hcl: add *ast.File with comments --- ast/ast.go | 11 +++++++++++ parser/parser.go | 15 +++++++++++---- printer/nodes.go | 7 +++++++ 3 files changed, 29 insertions(+), 4 deletions(-) diff --git a/ast/ast.go b/ast/ast.go index 62733f1..6619eef 100644 --- a/ast/ast.go +++ b/ast/ast.go @@ -10,6 +10,7 @@ type Node interface { Pos() token.Pos } +func (File) node() {} func (ObjectList) node() {} func (ObjectKey) node() {} func (ObjectItem) node() {} @@ -20,6 +21,16 @@ func (ObjectType) node() {} func (LiteralType) node() {} func (ListType) node() {} +// File represents a single HCL file +type File struct { + Node Node // usually a *ObjectList + Comments []*CommentGroup // list of all comments in the source +} + +func (f *File) Pos() token.Pos { + return f.Node.Pos() +} + // ObjectList represents a list of ObjectItems. An HCL file itself is an // ObjectList. type ObjectList struct { diff --git a/parser/parser.go b/parser/parser.go index 56b6aac..8623a83 100644 --- a/parser/parser.go +++ b/parser/parser.go @@ -34,7 +34,7 @@ func newParser(src []byte) *Parser { } // Parse returns the fully parsed source and returns the abstract syntax tree. -func Parse(src []byte) (ast.Node, error) { +func Parse(src []byte) (*ast.File, error) { p := newParser(src) return p.Parse() } @@ -42,8 +42,16 @@ func Parse(src []byte) (ast.Node, error) { var errEofToken = errors.New("EOF token found") // Parse returns the fully parsed source and returns the abstract syntax tree. -func (p *Parser) Parse() (ast.Node, error) { - return p.objectList() +func (p *Parser) Parse() (*ast.File, error) { + f := &ast.File{} + var err error + f.Node, err = p.objectList() + if err != nil { + return nil, err + } + + f.Comments = p.comments + return f, nil } func (p *Parser) objectList() (*ast.ObjectList, error) { @@ -64,7 +72,6 @@ func (p *Parser) objectList() (*ast.ObjectList, error) { node.Add(n) } - return node, nil } diff --git a/printer/nodes.go b/printer/nodes.go index 84da4e1..ec36302 100644 --- a/printer/nodes.go +++ b/printer/nodes.go @@ -18,6 +18,13 @@ func (p *printer) output(n interface{}) []byte { var buf bytes.Buffer switch t := n.(type) { + case *ast.File: + // for i, group := range t.Comments { + // for _, comment := range group.List { + // fmt.Printf("[%d] comment = %+v\n", i, comment) + // } + // } + return p.output(t.Node) case *ast.ObjectList: for i, item := range t.Items { buf.Write(p.objectItem(item))