1 // Package parser implements a parser for HCL (HashiCorp Configuration
11 "github.com/hashicorp/hcl/hcl/ast"
12 "github.com/hashicorp/hcl/hcl/scanner"
13 "github.com/hashicorp/hcl/hcl/token"
23 comments []*ast.CommentGroup
24 leadComment *ast.CommentGroup // last lead comment
25 lineComment *ast.CommentGroup // last line comment
29 n int // buffer size (max = 1)
32 func newParser(src []byte) *Parser {
38 // Parse returns the fully parsed source and returns the abstract syntax tree.
39 func Parse(src []byte) (*ast.File, error) {
40 // normalize all line endings
41 // since the scanner and output only work with "\n" line endings, we may
42 // end up with dangling "\r" characters in the parsed data.
43 src = bytes.Replace(src, []byte("\r\n"), []byte("\n"), -1)
49 var errEofToken = errors.New("EOF token found")
51 // Parse returns the fully parsed source and returns the abstract syntax tree.
52 func (p *Parser) Parse() (*ast.File, error) {
55 p.sc.Error = func(pos token.Pos, msg string) {
56 scerr = &PosError{Pos: pos, Err: errors.New(msg)}
59 f.Node, err = p.objectList(false)
67 f.Comments = p.comments
71 // objectList parses a list of items within an object (generally k/v pairs).
72 // The parameter" obj" tells this whether to we are within an object (braces:
73 // '{', '}') or just at the top level. If we're within an object, we end
75 func (p *Parser) objectList(obj bool) (*ast.ObjectList, error) {
76 defer un(trace(p, "ParseObjectList"))
77 node := &ast.ObjectList{}
83 if tok.Type == token.RBRACE {
88 n, err := p.objectItem()
89 if err == errEofToken {
90 break // we are finished
93 // we don't return a nil node, because might want to use already
101 // object lists can be optionally comma-delimited e.g. when a list of maps
102 // is being expressed, so a comma is allowed here - it's simply consumed
104 if tok.Type != token.COMMA {
111 func (p *Parser) consumeComment() (comment *ast.Comment, endline int) {
112 endline = p.tok.Pos.Line
114 // count the endline if it's multiline comment, ie starting with /*
115 if len(p.tok.Text) > 1 && p.tok.Text[1] == '*' {
116 // don't use range here - no need to decode Unicode code points
117 for i := 0; i < len(p.tok.Text); i++ {
118 if p.tok.Text[i] == '\n' {
124 comment = &ast.Comment{Start: p.tok.Pos, Text: p.tok.Text}
129 func (p *Parser) consumeCommentGroup(n int) (comments *ast.CommentGroup, endline int) {
130 var list []*ast.Comment
131 endline = p.tok.Pos.Line
133 for p.tok.Type == token.COMMENT && p.tok.Pos.Line <= endline+n {
134 var comment *ast.Comment
135 comment, endline = p.consumeComment()
136 list = append(list, comment)
139 // add comment group to the comments list
140 comments = &ast.CommentGroup{List: list}
141 p.comments = append(p.comments, comments)
146 // objectItem parses a single object item
147 func (p *Parser) objectItem() (*ast.ObjectItem, error) {
148 defer un(trace(p, "ParseObjectItem"))
150 keys, err := p.objectKey()
151 if len(keys) > 0 && err == errEofToken {
152 // We ignore eof token here since it is an error if we didn't
153 // receive a value (but we did receive a key) for the item.
156 if len(keys) > 0 && err != nil && p.tok.Type == token.RBRACE {
157 // This is a strange boolean statement, but what it means is:
158 // We have keys with no value, and we're likely in an object
159 // (since RBrace ends an object). For this, we set err to nil so
160 // we continue and get the error below of having the wrong value
164 // Reset the token type so we don't think it completed fine. See
165 // objectType which uses p.tok.Type to check if we're done with
167 p.tok.Type = token.EOF
173 o := &ast.ObjectItem{
177 if p.leadComment != nil {
178 o.LeadComment = p.leadComment
185 o.Val, err = p.object()
190 o.Val, err = p.objectType()
195 keyStr := make([]string, 0, len(keys))
196 for _, k := range keys {
197 keyStr = append(keyStr, k.Token.Text)
200 return nil, fmt.Errorf(
201 "key '%s' expected start of object ('{') or assignment ('=')",
202 strings.Join(keyStr, " "))
205 // do a look-ahead for line comment
207 if len(keys) > 0 && o.Val.Pos().Line == keys[0].Pos().Line && p.lineComment != nil {
208 o.LineComment = p.lineComment
215 // objectKey parses an object key and returns a ObjectKey AST
216 func (p *Parser) objectKey() ([]*ast.ObjectKey, error) {
218 keys := make([]*ast.ObjectKey, 0)
224 // It is very important to also return the keys here as well as
225 // the error. This is because we need to be able to tell if we
226 // did parse keys prior to finding the EOF, or if we just found
228 return keys, errEofToken
230 // assignment or object only, but not nested objects. this is not
231 // allowed: `foo bar = {}`
233 return nil, &PosError{
235 Err: fmt.Errorf("nested object expected: LBRACE got: %s", p.tok.Type),
240 return nil, &PosError{
242 Err: errors.New("no object keys found!"),
250 // If we have no keys, then it is a syntax error. i.e. {{}} is not
255 Err: fmt.Errorf("expected: IDENT | STRING got: %s", p.tok.Type),
261 case token.IDENT, token.STRING:
263 keys = append(keys, &ast.ObjectKey{Token: p.tok})
265 return keys, &PosError{
267 Err: fmt.Errorf("illegal character"),
270 return keys, &PosError{
272 Err: fmt.Errorf("expected: IDENT | STRING | ASSIGN | LBRACE got: %s", p.tok.Type),
278 // object parses any type of object, such as number, bool, string, object or
280 func (p *Parser) object() (ast.Node, error) {
281 defer un(trace(p, "ParseType"))
285 case token.NUMBER, token.FLOAT, token.BOOL, token.STRING, token.HEREDOC:
286 return p.literalType()
288 return p.objectType()
294 return nil, errEofToken
297 return nil, &PosError{
299 Err: fmt.Errorf("Unknown token: %+v", tok),
303 // objectType parses an object type and returns a ObjectType AST
304 func (p *Parser) objectType() (*ast.ObjectType, error) {
305 defer un(trace(p, "ParseObjectType"))
307 // we assume that the currently scanned token is a LBRACE
308 o := &ast.ObjectType{
312 l, err := p.objectList(true)
314 // if we hit RBRACE, we are good to go (means we parsed all Items), if it's
315 // not a RBRACE, it's an syntax error and we just return it.
316 if err != nil && p.tok.Type != token.RBRACE {
320 // No error, scan and expect the ending to be a brace
321 if tok := p.scan(); tok.Type != token.RBRACE {
322 return nil, fmt.Errorf("object expected closing RBRACE got: %s", tok.Type)
326 o.Rbrace = p.tok.Pos // advanced via parseObjectList
330 // listType parses a list type and returns a ListType AST
331 func (p *Parser) listType() (*ast.ListType, error) {
332 defer un(trace(p, "ParseListType"))
334 // we assume that the currently scanned token is a LBRACK
344 case token.COMMA, token.RBRACK:
346 return nil, &PosError{
349 "error parsing list, expected comma or list end, got: %s",
355 case token.BOOL, token.NUMBER, token.FLOAT, token.STRING, token.HEREDOC:
356 node, err := p.literalType()
361 // If there is a lead comment, apply it
362 if p.leadComment != nil {
363 node.LeadComment = p.leadComment
370 // get next list item or we are at the end
371 // do a look-ahead for line comment
373 if p.lineComment != nil && len(l.List) > 0 {
374 lit, ok := l.List[len(l.List)-1].(*ast.LiteralType)
376 lit.LineComment = p.lineComment
377 l.List[len(l.List)-1] = lit
386 // Looks like a nested object, so parse it out
387 node, err := p.objectType()
389 return nil, &PosError{
392 "error while trying to parse object within list: %s", err),
398 node, err := p.listType()
400 return nil, &PosError{
403 "error while trying to parse list within list: %s", err),
412 return nil, &PosError{
414 Err: fmt.Errorf("unexpected token while parsing list: %s", tok.Type),
420 // literalType parses a literal type and returns a LiteralType AST
421 func (p *Parser) literalType() (*ast.LiteralType, error) {
422 defer un(trace(p, "ParseLiteral"))
424 return &ast.LiteralType{
429 // scan returns the next token from the underlying scanner. If a token has
430 // been unscanned then read that instead. In the process, it collects any
431 // comment groups encountered, and remembers the last lead and line comments.
432 func (p *Parser) scan() token.Token {
433 // If we have a token on the buffer, then return it.
439 // Otherwise read the next token from the scanner and Save it to the buffer
440 // in case we unscan later.
444 if p.tok.Type == token.COMMENT {
445 var comment *ast.CommentGroup
448 // fmt.Printf("p.tok.Pos.Line = %+v prev: %d endline %d \n",
449 // p.tok.Pos.Line, prev.Pos.Line, endline)
450 if p.tok.Pos.Line == prev.Pos.Line {
451 // The comment is on same line as the previous token; it
452 // cannot be a lead comment but may be a line comment.
453 comment, endline = p.consumeCommentGroup(0)
454 if p.tok.Pos.Line != endline {
455 // The next token is on a different line, thus
456 // the last comment group is a line comment.
457 p.lineComment = comment
461 // consume successor comments, if any
463 for p.tok.Type == token.COMMENT {
464 comment, endline = p.consumeCommentGroup(1)
467 if endline+1 == p.tok.Pos.Line && p.tok.Type != token.RBRACE {
469 case token.RBRACE, token.RBRACK:
470 // Do not count for these cases
472 // The next token is following on the line immediately after the
473 // comment group, thus the last comment group is a lead comment.
474 p.leadComment = comment
483 // unscan pushes the previously read token back onto the buffer.
484 func (p *Parser) unscan() {
488 // ----------------------------------------------------------------------------
491 func (p *Parser) printTrace(a ...interface{}) {
496 const dots = ". . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . "
498 fmt.Printf("%5d:%3d: ", p.tok.Pos.Line, p.tok.Pos.Column)
510 func trace(p *Parser, msg string) *Parser {
511 p.printTrace(msg, "(")
516 // Usage pattern: defer un(trace(p, "..."))