From 0e668f87b2bf9be60e3919a5ed6caf7230792afb Mon Sep 17 00:00:00 2001 From: Fatih Arslan Date: Mon, 12 Oct 2015 02:49:07 +0300 Subject: [PATCH] parser: working assignstatement is finished --- parser/ast.go | 2 +- parser/parser.go | 29 ++++++++++++++--------------- parser/parser_test.go | 14 ++++++++------ 3 files changed, 23 insertions(+), 22 deletions(-) diff --git a/parser/ast.go b/parser/ast.go index a8ec9c3..e54a5ba 100644 --- a/parser/ast.go +++ b/parser/ast.go @@ -48,7 +48,7 @@ func (s *Source) String() string { func (s *Source) Pos() scanner.Pos { // always returns the uninitiliazed position - return scanner.Pos{} + return s.nodes[0].Pos() } // IdentStatement represents an identifier. diff --git a/parser/parser.go b/parser/parser.go index 84b5dff..96f8a61 100644 --- a/parser/parser.go +++ b/parser/parser.go @@ -29,14 +29,14 @@ func (p *Parser) Parse() Node { node := &Source{} for { + if n := p.parseStatement(); n != nil { + node.add(n) + } + // break if we hit the end if p.tok.Type == scanner.EOF { break } - - if n := p.parseStatement(); n != nil { - node.add(n) - } } return node @@ -48,20 +48,16 @@ func (p *Parser) parseStatement() Node { tok := p.scan() if tok.Type.IsLiteral() { - // found an object if p.prevTok.Type.IsLiteral() { return p.parseObject() } - return p.parseIdent() - } - switch tok.Type { - case scanner.LBRACE: - return p.parseObject() - case scanner.LBRACK: - return p.parseList() - case scanner.ASSIGN: - return p.parseAssignment() + if tok := p.scan(); tok.Type == scanner.ASSIGN { + return p.parseAssignment() + } + + p.unscan() + return p.parseIdent() } return nil @@ -113,7 +109,10 @@ func (p *Parser) scan() scanner.Token { } // unscan pushes the previously read token back onto the buffer. -func (p *Parser) unscan() { p.n = 1 } +func (p *Parser) unscan() { + p.n = 1 + p.tok = p.prevTok +} // ---------------------------------------------------------------------------- // Parsing support diff --git a/parser/parser_test.go b/parser/parser_test.go index e8f07eb..c1bf5fe 100644 --- a/parser/parser_test.go +++ b/parser/parser_test.go @@ -1,17 +1,19 @@ package parser -import ( - "fmt" - "testing" -) +import "testing" func TestAssignStatment(t *testing.T) { src := `ami = "${var.foo}"` - p := New([]byte(src)) p.enableTrace = true n := p.Parse() - fmt.Println(n) + if n.String() != src { + t.Errorf("AssignStatement is not parsed correctly\n\twant: '%s'\n\tgot : '%s'", src, n.String()) + } + + if n.Pos().Line != 1 { + t.Errorf("AssignStatement position is wrong\n\twant: '%d'\n\tgot : '%d'", 1, n.Pos().Line) + } }