xgo/parser/parser.go

1202 lines
22 KiB
Go
Raw Normal View History

package parser
2019-01-09 10:17:42 +03:00
import (
"fmt"
"io"
2019-12-20 22:40:38 +03:00
"sort"
2019-01-09 10:17:42 +03:00
"strconv"
2019-12-30 00:38:51 +03:00
"github.com/d5/tengo/v2/token"
2019-01-09 10:17:42 +03:00
)
type bailout struct{}
2019-12-20 22:40:38 +03:00
var stmtStart = map[token.Token]bool{
token.Break: true,
token.Continue: true,
token.For: true,
token.If: true,
token.Return: true,
token.Export: true,
}
// Error represents a parser error.
type Error struct {
2019-12-20 22:40:38 +03:00
Pos SourceFilePos
Msg string
}
func (e Error) Error() string {
2019-12-20 22:40:38 +03:00
if e.Pos.Filename != "" || e.Pos.IsValid() {
return fmt.Sprintf("Parse Error: %s\n\tat %s", e.Msg, e.Pos)
}
return fmt.Sprintf("Parse Error: %s", e.Msg)
}
// ErrorList is a collection of parser errors.
type ErrorList []*Error
2019-12-20 22:40:38 +03:00
// Add adds a new parser error to the collection.
func (p *ErrorList) Add(pos SourceFilePos, msg string) {
*p = append(*p, &Error{pos, msg})
2019-12-20 22:40:38 +03:00
}
// Len returns the number of elements in the collection.
func (p ErrorList) Len() int {
2019-12-20 22:40:38 +03:00
return len(p)
}
func (p ErrorList) Swap(i, j int) {
2019-12-20 22:40:38 +03:00
p[i], p[j] = p[j], p[i]
}
func (p ErrorList) Less(i, j int) bool {
2019-12-20 22:40:38 +03:00
e := &p[i].Pos
f := &p[j].Pos
if e.Filename != f.Filename {
return e.Filename < f.Filename
}
if e.Line != f.Line {
return e.Line < f.Line
}
if e.Column != f.Column {
return e.Column < f.Column
}
return p[i].Msg < p[j].Msg
}
// Sort sorts the collection.
func (p ErrorList) Sort() {
2019-12-20 22:40:38 +03:00
sort.Sort(p)
}
func (p ErrorList) Error() string {
2019-12-20 22:40:38 +03:00
switch len(p) {
case 0:
return "no errors"
case 1:
return p[0].Error()
}
return fmt.Sprintf("%s (and %d more errors)", p[0], len(p)-1)
}
// Err returns an error.
func (p ErrorList) Err() error {
2019-12-20 22:40:38 +03:00
if len(p) == 0 {
return nil
}
return p
}
// Parser parses the Tengo source files. It's based on Go's parser
// implementation.
2019-01-09 10:17:42 +03:00
type Parser struct {
2019-12-20 22:40:38 +03:00
file *SourceFile
errors ErrorList
2019-12-20 22:40:38 +03:00
scanner *Scanner
pos Pos
2019-01-09 10:17:42 +03:00
token token.Token
tokenLit string
2019-12-20 22:40:38 +03:00
exprLevel int // < 0: in control clause, >= 0: in expression
syncPos Pos // last sync position
syncCount int // number of advance calls without progress
2019-01-09 10:17:42 +03:00
trace bool
indent int
traceOut io.Writer
}
// NewParser creates a Parser.
2019-12-20 22:40:38 +03:00
func NewParser(file *SourceFile, src []byte, trace io.Writer) *Parser {
2019-01-09 10:17:42 +03:00
p := &Parser{
file: file,
trace: trace != nil,
traceOut: trace,
}
2019-12-20 22:40:38 +03:00
p.scanner = NewScanner(p.file, src,
func(pos SourceFilePos, msg string) {
p.errors.Add(pos, msg)
}, 0)
2019-01-09 10:17:42 +03:00
p.next()
return p
}
// ParseFile parses the source and returns an AST file unit.
2019-12-20 22:40:38 +03:00
func (p *Parser) ParseFile() (file *File, err error) {
defer func() {
if e := recover(); e != nil {
if _, ok := e.(bailout); !ok {
panic(e)
}
}
p.errors.Sort()
err = p.errors.Err()
}()
2019-01-09 10:17:42 +03:00
if p.trace {
2019-12-20 22:40:38 +03:00
defer untracep(tracep(p, "File"))
2019-01-09 10:17:42 +03:00
}
if p.errors.Len() > 0 {
return nil, p.errors.Err()
}
stmts := p.parseStmtList()
if p.errors.Len() > 0 {
return nil, p.errors.Err()
}
2019-12-20 22:40:38 +03:00
file = &File{
2019-01-09 10:17:42 +03:00
InputFile: p.file,
Stmts: stmts,
}
return
2019-01-09 10:17:42 +03:00
}
2019-12-20 22:40:38 +03:00
func (p *Parser) parseExpr() Expr {
2019-01-09 10:17:42 +03:00
if p.trace {
2019-12-20 22:40:38 +03:00
defer untracep(tracep(p, "Expression"))
2019-01-09 10:17:42 +03:00
}
expr := p.parseBinaryExpr(token.LowestPrec + 1)
// ternary conditional expression
if p.token == token.Question {
return p.parseCondExpr(expr)
}
return expr
2019-01-09 10:17:42 +03:00
}
2019-12-20 22:40:38 +03:00
func (p *Parser) parseBinaryExpr(prec1 int) Expr {
2019-01-09 10:17:42 +03:00
if p.trace {
2019-12-20 22:40:38 +03:00
defer untracep(tracep(p, "BinaryExpression"))
2019-01-09 10:17:42 +03:00
}
x := p.parseUnaryExpr()
for {
op, prec := p.token, p.token.Precedence()
if prec < prec1 {
return x
}
pos := p.expect(op)
y := p.parseBinaryExpr(prec + 1)
2019-12-20 22:40:38 +03:00
x = &BinaryExpr{
LHS: x,
RHS: y,
2019-01-09 10:17:42 +03:00
Token: op,
TokenPos: pos,
}
}
}
2019-12-20 22:40:38 +03:00
func (p *Parser) parseCondExpr(cond Expr) Expr {
questionPos := p.expect(token.Question)
trueExpr := p.parseExpr()
colonPos := p.expect(token.Colon)
falseExpr := p.parseExpr()
2019-12-20 22:40:38 +03:00
return &CondExpr{
Cond: cond,
True: trueExpr,
False: falseExpr,
QuestionPos: questionPos,
ColonPos: colonPos,
}
}
2019-12-20 22:40:38 +03:00
func (p *Parser) parseUnaryExpr() Expr {
2019-01-09 10:17:42 +03:00
if p.trace {
2019-12-20 22:40:38 +03:00
defer untracep(tracep(p, "UnaryExpression"))
2019-01-09 10:17:42 +03:00
}
switch p.token {
case token.Add, token.Sub, token.Not, token.Xor:
pos, op := p.pos, p.token
p.next()
x := p.parseUnaryExpr()
2019-12-20 22:40:38 +03:00
return &UnaryExpr{
2019-01-09 10:17:42 +03:00
Token: op,
TokenPos: pos,
Expr: x,
}
}
return p.parsePrimaryExpr()
}
2019-12-20 22:40:38 +03:00
func (p *Parser) parsePrimaryExpr() Expr {
2019-01-09 10:17:42 +03:00
if p.trace {
2019-12-20 22:40:38 +03:00
defer untracep(tracep(p, "PrimaryExpression"))
2019-01-09 10:17:42 +03:00
}
x := p.parseOperand()
L:
for {
switch p.token {
case token.Period:
p.next()
switch p.token {
case token.Ident:
x = p.parseSelector(x)
default:
pos := p.pos
p.errorExpected(pos, "selector")
2019-01-09 10:17:42 +03:00
p.advance(stmtStart)
2019-12-20 22:40:38 +03:00
return &BadExpr{From: pos, To: p.pos}
2019-01-09 10:17:42 +03:00
}
case token.LBrack:
x = p.parseIndexOrSlice(x)
case token.LParen:
x = p.parseCall(x)
default:
break L
}
}
return x
}
2019-12-20 22:40:38 +03:00
func (p *Parser) parseCall(x Expr) *CallExpr {
2019-01-09 10:17:42 +03:00
if p.trace {
2019-12-20 22:40:38 +03:00
defer untracep(tracep(p, "Call"))
2019-01-09 10:17:42 +03:00
}
lparen := p.expect(token.LParen)
p.exprLevel++
2019-12-20 22:40:38 +03:00
var list []Expr
2020-06-08 19:54:24 +03:00
var ellipsis Pos
for p.token != token.RParen && p.token != token.EOF && !ellipsis.IsValid() {
2019-01-09 10:17:42 +03:00
list = append(list, p.parseExpr())
2020-06-08 19:54:24 +03:00
if p.token == token.Ellipsis {
ellipsis = p.pos
p.next()
}
2019-01-09 10:17:42 +03:00
if !p.expectComma(token.RParen, "call argument") {
break
}
}
p.exprLevel--
rparen := p.expect(token.RParen)
2019-12-20 22:40:38 +03:00
return &CallExpr{
2020-06-08 19:54:24 +03:00
Func: x,
LParen: lparen,
RParen: rparen,
Ellipsis: ellipsis,
Args: list,
2019-01-09 10:17:42 +03:00
}
}
func (p *Parser) expectComma(closing token.Token, want string) bool {
if p.token == token.Comma {
p.next()
if p.token == closing {
p.errorExpected(p.pos, want)
return false
}
return true
}
if p.token == token.Semicolon && p.tokenLit == "\n" {
p.next()
}
return false
}
2019-12-20 22:40:38 +03:00
func (p *Parser) parseIndexOrSlice(x Expr) Expr {
2019-01-09 10:17:42 +03:00
if p.trace {
2019-12-20 22:40:38 +03:00
defer untracep(tracep(p, "IndexOrSlice"))
2019-01-09 10:17:42 +03:00
}
lbrack := p.expect(token.LBrack)
p.exprLevel++
2019-12-20 22:40:38 +03:00
var index [2]Expr
2019-01-09 10:17:42 +03:00
if p.token != token.Colon {
index[0] = p.parseExpr()
}
numColons := 0
if p.token == token.Colon {
numColons++
p.next()
if p.token != token.RBrack && p.token != token.EOF {
index[1] = p.parseExpr()
}
}
p.exprLevel--
rbrack := p.expect(token.RBrack)
if numColons > 0 {
// slice expression
2019-12-20 22:40:38 +03:00
return &SliceExpr{
2019-01-09 10:17:42 +03:00
Expr: x,
LBrack: lbrack,
RBrack: rbrack,
Low: index[0],
High: index[1],
}
}
2019-12-20 22:40:38 +03:00
return &IndexExpr{
2019-01-09 10:17:42 +03:00
Expr: x,
LBrack: lbrack,
RBrack: rbrack,
Index: index[0],
}
}
2019-12-20 22:40:38 +03:00
func (p *Parser) parseSelector(x Expr) Expr {
2019-01-09 10:17:42 +03:00
if p.trace {
2019-12-20 22:40:38 +03:00
defer untracep(tracep(p, "Selector"))
2019-01-09 10:17:42 +03:00
}
sel := p.parseIdent()
2019-12-20 22:40:38 +03:00
return &SelectorExpr{Expr: x, Sel: &StringLit{
2019-01-09 10:17:42 +03:00
Value: sel.Name,
ValuePos: sel.NamePos,
Literal: sel.Name,
}}
}
2019-12-20 22:40:38 +03:00
func (p *Parser) parseOperand() Expr {
2019-01-09 10:17:42 +03:00
if p.trace {
2019-12-20 22:40:38 +03:00
defer untracep(tracep(p, "Operand"))
2019-01-09 10:17:42 +03:00
}
switch p.token {
case token.Ident:
return p.parseIdent()
case token.Int:
v, _ := strconv.ParseInt(p.tokenLit, 10, 64)
2019-12-20 22:40:38 +03:00
x := &IntLit{
2019-01-09 10:17:42 +03:00
Value: v,
ValuePos: p.pos,
Literal: p.tokenLit,
}
p.next()
return x
case token.Float:
v, _ := strconv.ParseFloat(p.tokenLit, 64)
2019-12-20 22:40:38 +03:00
x := &FloatLit{
2019-01-09 10:17:42 +03:00
Value: v,
ValuePos: p.pos,
Literal: p.tokenLit,
}
p.next()
return x
case token.Char:
2019-01-10 13:45:20 +03:00
return p.parseCharLit()
case token.String:
2019-01-09 10:17:42 +03:00
v, _ := strconv.Unquote(p.tokenLit)
2019-12-20 22:40:38 +03:00
x := &StringLit{
2019-01-09 10:17:42 +03:00
Value: v,
ValuePos: p.pos,
Literal: p.tokenLit,
}
p.next()
return x
case token.True:
2019-12-20 22:40:38 +03:00
x := &BoolLit{
2019-01-09 10:17:42 +03:00
Value: true,
ValuePos: p.pos,
Literal: p.tokenLit,
}
p.next()
return x
case token.False:
2019-12-20 22:40:38 +03:00
x := &BoolLit{
2019-01-09 10:17:42 +03:00
Value: false,
ValuePos: p.pos,
Literal: p.tokenLit,
}
p.next()
return x
case token.Undefined:
2019-12-20 22:40:38 +03:00
x := &UndefinedLit{TokenPos: p.pos}
p.next()
return x
2019-01-17 12:56:05 +03:00
case token.Import:
return p.parseImportExpr()
2019-01-09 10:17:42 +03:00
case token.LParen:
lparen := p.pos
p.next()
p.exprLevel++
x := p.parseExpr()
p.exprLevel--
rparen := p.expect(token.RParen)
2019-12-20 22:40:38 +03:00
return &ParenExpr{
2019-01-09 10:17:42 +03:00
LParen: lparen,
Expr: x,
RParen: rparen,
}
case token.LBrack: // array literal
return p.parseArrayLit()
case token.LBrace: // map literal
return p.parseMapLit()
case token.Func: // function literal
return p.parseFuncLit()
case token.Error: // error expression
return p.parseErrorExpr()
2019-01-25 06:31:17 +03:00
case token.Immutable: // immutable expression
return p.parseImmutableExpr()
2019-01-09 10:17:42 +03:00
}
pos := p.pos
p.errorExpected(pos, "operand")
p.advance(stmtStart)
2019-12-20 22:40:38 +03:00
return &BadExpr{From: pos, To: p.pos}
2019-01-09 10:17:42 +03:00
}
2019-12-20 22:40:38 +03:00
func (p *Parser) parseImportExpr() Expr {
2019-01-17 12:56:05 +03:00
pos := p.pos
p.next()
p.expect(token.LParen)
if p.token != token.String {
p.errorExpected(p.pos, "module name")
p.advance(stmtStart)
2019-12-20 22:40:38 +03:00
return &BadExpr{From: pos, To: p.pos}
2019-01-17 12:56:05 +03:00
}
// module name
moduleName, _ := strconv.Unquote(p.tokenLit)
2019-12-20 22:40:38 +03:00
expr := &ImportExpr{
2019-01-17 12:56:05 +03:00
ModuleName: moduleName,
Token: token.Import,
TokenPos: pos,
}
p.next()
p.expect(token.RParen)
return expr
}
2019-12-20 22:40:38 +03:00
func (p *Parser) parseCharLit() Expr {
2019-01-10 13:45:20 +03:00
if n := len(p.tokenLit); n >= 3 {
2019-12-20 22:40:38 +03:00
code, _, _, err := strconv.UnquoteChar(p.tokenLit[1:n-1], '\'')
if err == nil {
x := &CharLit{
Value: code,
2019-01-10 13:45:20 +03:00
ValuePos: p.pos,
Literal: p.tokenLit,
}
p.next()
return x
}
}
pos := p.pos
p.error(pos, "illegal char literal")
p.next()
2019-12-20 22:40:38 +03:00
return &BadExpr{
2019-01-10 13:45:20 +03:00
From: pos,
To: p.pos,
}
}
2019-12-20 22:40:38 +03:00
func (p *Parser) parseFuncLit() Expr {
2019-01-09 10:17:42 +03:00
if p.trace {
2019-12-20 22:40:38 +03:00
defer untracep(tracep(p, "FuncLit"))
2019-01-09 10:17:42 +03:00
}
typ := p.parseFuncType()
p.exprLevel++
body := p.parseBody()
p.exprLevel--
2019-12-20 22:40:38 +03:00
return &FuncLit{
2019-01-09 10:17:42 +03:00
Type: typ,
Body: body,
}
}
2019-12-20 22:40:38 +03:00
func (p *Parser) parseArrayLit() Expr {
2019-01-09 10:17:42 +03:00
if p.trace {
2019-12-20 22:40:38 +03:00
defer untracep(tracep(p, "ArrayLit"))
2019-01-09 10:17:42 +03:00
}
lbrack := p.expect(token.LBrack)
p.exprLevel++
2019-12-20 22:40:38 +03:00
var elements []Expr
2019-01-09 10:17:42 +03:00
for p.token != token.RBrack && p.token != token.EOF {
2019-01-17 12:56:05 +03:00
elements = append(elements, p.parseExpr())
2019-01-09 10:17:42 +03:00
if !p.expectComma(token.RBrack, "array element") {
break
}
}
p.exprLevel--
rbrack := p.expect(token.RBrack)
2019-12-20 22:40:38 +03:00
return &ArrayLit{
2019-01-17 12:56:05 +03:00
Elements: elements,
2019-01-09 10:17:42 +03:00
LBrack: lbrack,
RBrack: rbrack,
}
}
2019-12-20 22:40:38 +03:00
func (p *Parser) parseErrorExpr() Expr {
pos := p.pos
p.next()
lparen := p.expect(token.LParen)
value := p.parseExpr()
rparen := p.expect(token.RParen)
2019-12-20 22:40:38 +03:00
return &ErrorExpr{
ErrorPos: pos,
Expr: value,
LParen: lparen,
RParen: rparen,
}
2019-01-09 10:17:42 +03:00
}
2019-12-20 22:40:38 +03:00
func (p *Parser) parseImmutableExpr() Expr {
2019-01-25 06:31:17 +03:00
pos := p.pos
p.next()
lparen := p.expect(token.LParen)
value := p.parseExpr()
rparen := p.expect(token.RParen)
2019-12-20 22:40:38 +03:00
return &ImmutableExpr{
2019-01-25 06:31:17 +03:00
ErrorPos: pos,
Expr: value,
LParen: lparen,
RParen: rparen,
}
}
2019-12-20 22:40:38 +03:00
func (p *Parser) parseFuncType() *FuncType {
2019-01-09 10:17:42 +03:00
if p.trace {
2019-12-20 22:40:38 +03:00
defer untracep(tracep(p, "FuncType"))
2019-01-09 10:17:42 +03:00
}
pos := p.expect(token.Func)
params := p.parseIdentList()
2019-12-20 22:40:38 +03:00
return &FuncType{
2019-01-09 10:17:42 +03:00
FuncPos: pos,
Params: params,
}
}
2019-12-20 22:40:38 +03:00
func (p *Parser) parseBody() *BlockStmt {
2019-01-09 10:17:42 +03:00
if p.trace {
2019-12-20 22:40:38 +03:00
defer untracep(tracep(p, "Body"))
2019-01-09 10:17:42 +03:00
}
lbrace := p.expect(token.LBrace)
list := p.parseStmtList()
rbrace := p.expect(token.RBrace)
2019-12-20 22:40:38 +03:00
return &BlockStmt{
2019-01-09 10:17:42 +03:00
LBrace: lbrace,
RBrace: rbrace,
Stmts: list,
}
}
2019-12-20 22:40:38 +03:00
func (p *Parser) parseStmtList() (list []Stmt) {
2019-01-09 10:17:42 +03:00
if p.trace {
2019-12-20 22:40:38 +03:00
defer untracep(tracep(p, "StatementList"))
2019-01-09 10:17:42 +03:00
}
for p.token != token.RBrace && p.token != token.EOF {
2019-01-09 10:17:42 +03:00
list = append(list, p.parseStmt())
}
return
}
2019-12-20 22:40:38 +03:00
func (p *Parser) parseIdent() *Ident {
2019-01-09 10:17:42 +03:00
pos := p.pos
name := "_"
if p.token == token.Ident {
name = p.tokenLit
p.next()
} else {
p.expect(token.Ident)
}
2019-12-20 22:40:38 +03:00
return &Ident{
2019-01-09 10:17:42 +03:00
NamePos: pos,
Name: name,
}
}
2019-12-20 22:40:38 +03:00
func (p *Parser) parseIdentList() *IdentList {
2019-01-09 10:17:42 +03:00
if p.trace {
2019-12-20 22:40:38 +03:00
defer untracep(tracep(p, "IdentList"))
2019-01-09 10:17:42 +03:00
}
2019-12-20 22:40:38 +03:00
var params []*Ident
2019-01-09 10:17:42 +03:00
lparen := p.expect(token.LParen)
isVarArgs := false
2019-01-09 10:17:42 +03:00
if p.token != token.RParen {
if p.token == token.Ellipsis {
isVarArgs = true
p.next()
}
2019-01-09 10:17:42 +03:00
params = append(params, p.parseIdent())
for !isVarArgs && p.token == token.Comma {
2019-01-09 10:17:42 +03:00
p.next()
if p.token == token.Ellipsis {
isVarArgs = true
p.next()
}
2019-01-09 10:17:42 +03:00
params = append(params, p.parseIdent())
}
}
2019-01-09 10:17:42 +03:00
rparen := p.expect(token.RParen)
2019-12-20 22:40:38 +03:00
return &IdentList{
LParen: lparen,
RParen: rparen,
VarArgs: isVarArgs,
List: params,
2019-01-09 10:17:42 +03:00
}
}
2019-12-20 22:40:38 +03:00
func (p *Parser) parseStmt() (stmt Stmt) {
2019-01-09 10:17:42 +03:00
if p.trace {
2019-12-20 22:40:38 +03:00
defer untracep(tracep(p, "Statement"))
2019-01-09 10:17:42 +03:00
}
switch p.token {
case // simple statements
2019-12-20 22:40:38 +03:00
token.Func, token.Error, token.Immutable, token.Ident, token.Int,
token.Float, token.Char, token.String, token.True, token.False,
token.Undefined, token.Import, token.LParen, token.LBrace,
token.LBrack, token.Add, token.Sub, token.Mul, token.And, token.Xor,
token.Not:
2019-01-09 10:17:42 +03:00
s := p.parseSimpleStmt(false)
p.expectSemi()
return s
case token.Return:
return p.parseReturnStmt()
2019-02-02 10:27:29 +03:00
case token.Export:
return p.parseExportStmt()
2019-01-09 10:17:42 +03:00
case token.If:
return p.parseIfStmt()
case token.For:
return p.parseForStmt()
case token.Break, token.Continue:
return p.parseBranchStmt(p.token)
case token.Semicolon:
2019-12-20 22:40:38 +03:00
s := &EmptyStmt{Semicolon: p.pos, Implicit: p.tokenLit == "\n"}
2019-01-09 10:17:42 +03:00
p.next()
return s
case token.RBrace:
// semicolon may be omitted before a closing "}"
2019-12-20 22:40:38 +03:00
return &EmptyStmt{Semicolon: p.pos, Implicit: true}
2019-01-09 10:17:42 +03:00
default:
pos := p.pos
p.errorExpected(pos, "statement")
p.advance(stmtStart)
2019-12-20 22:40:38 +03:00
return &BadStmt{From: pos, To: p.pos}
2019-01-09 10:17:42 +03:00
}
}
2019-12-20 22:40:38 +03:00
func (p *Parser) parseForStmt() Stmt {
2019-01-09 10:17:42 +03:00
if p.trace {
2019-12-20 22:40:38 +03:00
defer untracep(tracep(p, "ForStmt"))
2019-01-09 10:17:42 +03:00
}
pos := p.expect(token.For)
// for {}
if p.token == token.LBrace {
body := p.parseBlockStmt()
p.expectSemi()
2019-12-20 22:40:38 +03:00
return &ForStmt{
2019-01-09 10:17:42 +03:00
ForPos: pos,
Body: body,
}
}
prevLevel := p.exprLevel
p.exprLevel = -1
2019-12-20 22:40:38 +03:00
var s1 Stmt
2019-01-09 10:17:42 +03:00
if p.token != token.Semicolon { // skipping init
s1 = p.parseSimpleStmt(true)
}
// for _ in seq {} or
// for value in seq {} or
// for key, value in seq {}
2019-12-20 22:40:38 +03:00
if forInStmt, isForIn := s1.(*ForInStmt); isForIn {
2019-01-09 10:17:42 +03:00
forInStmt.ForPos = pos
p.exprLevel = prevLevel
forInStmt.Body = p.parseBlockStmt()
p.expectSemi()
return forInStmt
}
// for init; cond; post {}
2019-12-20 22:40:38 +03:00
var s2, s3 Stmt
2019-01-09 10:17:42 +03:00
if p.token == token.Semicolon {
p.next()
if p.token != token.Semicolon {
s2 = p.parseSimpleStmt(false) // cond
}
p.expect(token.Semicolon)
if p.token != token.LBrace {
s3 = p.parseSimpleStmt(false) // post
}
} else {
// for cond {}
s2 = s1
s1 = nil
}
// body
p.exprLevel = prevLevel
body := p.parseBlockStmt()
p.expectSemi()
cond := p.makeExpr(s2, "condition expression")
2019-12-20 22:40:38 +03:00
return &ForStmt{
2019-01-09 10:17:42 +03:00
ForPos: pos,
Init: s1,
Cond: cond,
Post: s3,
Body: body,
}
}
2019-12-20 22:40:38 +03:00
func (p *Parser) parseBranchStmt(tok token.Token) Stmt {
2019-01-09 10:17:42 +03:00
if p.trace {
2019-12-20 22:40:38 +03:00
defer untracep(tracep(p, "BranchStmt"))
2019-01-09 10:17:42 +03:00
}
pos := p.expect(tok)
2019-12-20 22:40:38 +03:00
var label *Ident
2019-01-09 10:17:42 +03:00
if p.token == token.Ident {
label = p.parseIdent()
}
p.expectSemi()
2019-12-20 22:40:38 +03:00
return &BranchStmt{
2019-01-09 10:17:42 +03:00
Token: tok,
TokenPos: pos,
Label: label,
}
}
2019-12-20 22:40:38 +03:00
func (p *Parser) parseIfStmt() Stmt {
2019-01-09 10:17:42 +03:00
if p.trace {
2019-12-20 22:40:38 +03:00
defer untracep(tracep(p, "IfStmt"))
2019-01-09 10:17:42 +03:00
}
pos := p.expect(token.If)
init, cond := p.parseIfHeader()
body := p.parseBlockStmt()
2019-12-20 22:40:38 +03:00
var elseStmt Stmt
2019-01-09 10:17:42 +03:00
if p.token == token.Else {
p.next()
switch p.token {
case token.If:
elseStmt = p.parseIfStmt()
case token.LBrace:
elseStmt = p.parseBlockStmt()
p.expectSemi()
default:
p.errorExpected(p.pos, "if or {")
2019-12-20 22:40:38 +03:00
elseStmt = &BadStmt{From: p.pos, To: p.pos}
2019-01-09 10:17:42 +03:00
}
} else {
p.expectSemi()
}
2019-12-20 22:40:38 +03:00
return &IfStmt{
2019-01-09 10:17:42 +03:00
IfPos: pos,
Init: init,
Cond: cond,
Body: body,
Else: elseStmt,
}
}
2019-12-20 22:40:38 +03:00
func (p *Parser) parseBlockStmt() *BlockStmt {
2019-01-09 10:17:42 +03:00
if p.trace {
2019-12-20 22:40:38 +03:00
defer untracep(tracep(p, "BlockStmt"))
2019-01-09 10:17:42 +03:00
}
lbrace := p.expect(token.LBrace)
list := p.parseStmtList()
rbrace := p.expect(token.RBrace)
2019-12-20 22:40:38 +03:00
return &BlockStmt{
2019-01-09 10:17:42 +03:00
LBrace: lbrace,
RBrace: rbrace,
Stmts: list,
}
}
2019-12-20 22:40:38 +03:00
func (p *Parser) parseIfHeader() (init Stmt, cond Expr) {
2019-01-09 10:17:42 +03:00
if p.token == token.LBrace {
p.error(p.pos, "missing condition in if statement")
2019-12-20 22:40:38 +03:00
cond = &BadExpr{From: p.pos, To: p.pos}
2019-01-09 10:17:42 +03:00
return
}
outer := p.exprLevel
p.exprLevel = -1
if p.token == token.Semicolon {
p.error(p.pos, "missing init in if statement")
return
}
init = p.parseSimpleStmt(false)
2019-12-20 22:40:38 +03:00
var condStmt Stmt
2019-01-09 10:17:42 +03:00
if p.token == token.LBrace {
condStmt = init
init = nil
} else if p.token == token.Semicolon {
p.next()
condStmt = p.parseSimpleStmt(false)
} else {
p.error(p.pos, "missing condition in if statement")
}
if condStmt != nil {
cond = p.makeExpr(condStmt, "boolean expression")
}
if cond == nil {
2019-12-20 22:40:38 +03:00
cond = &BadExpr{From: p.pos, To: p.pos}
2019-01-09 10:17:42 +03:00
}
p.exprLevel = outer
return
}
2019-12-20 22:40:38 +03:00
func (p *Parser) makeExpr(s Stmt, want string) Expr {
2019-01-09 10:17:42 +03:00
if s == nil {
return nil
}
2019-12-20 22:40:38 +03:00
if es, isExpr := s.(*ExprStmt); isExpr {
2019-01-09 10:17:42 +03:00
return es.Expr
}
found := "simple statement"
2019-12-20 22:40:38 +03:00
if _, isAss := s.(*AssignStmt); isAss {
2019-01-09 10:17:42 +03:00
found = "assignment"
}
p.error(s.Pos(), fmt.Sprintf("expected %s, found %s", want, found))
2019-12-20 22:40:38 +03:00
return &BadExpr{From: s.Pos(), To: p.safePos(s.End())}
2019-01-09 10:17:42 +03:00
}
2019-12-20 22:40:38 +03:00
func (p *Parser) parseReturnStmt() Stmt {
2019-01-09 10:17:42 +03:00
if p.trace {
2019-12-20 22:40:38 +03:00
defer untracep(tracep(p, "ReturnStmt"))
2019-01-09 10:17:42 +03:00
}
pos := p.pos
p.expect(token.Return)
2019-12-20 22:40:38 +03:00
var x Expr
2019-01-09 10:17:42 +03:00
if p.token != token.Semicolon && p.token != token.RBrace {
x = p.parseExpr()
2019-01-09 10:17:42 +03:00
}
p.expectSemi()
2019-12-20 22:40:38 +03:00
return &ReturnStmt{
2019-01-09 10:17:42 +03:00
ReturnPos: pos,
Result: x,
2019-01-09 10:17:42 +03:00
}
}
2019-12-20 22:40:38 +03:00
func (p *Parser) parseExportStmt() Stmt {
2019-02-02 10:27:29 +03:00
if p.trace {
2019-12-20 22:40:38 +03:00
defer untracep(tracep(p, "ExportStmt"))
2019-02-02 10:27:29 +03:00
}
pos := p.pos
p.expect(token.Export)
x := p.parseExpr()
p.expectSemi()
2019-12-20 22:40:38 +03:00
return &ExportStmt{
2019-02-02 10:27:29 +03:00
ExportPos: pos,
Result: x,
}
}
2019-12-20 22:40:38 +03:00
func (p *Parser) parseSimpleStmt(forIn bool) Stmt {
2019-01-09 10:17:42 +03:00
if p.trace {
2019-12-20 22:40:38 +03:00
defer untracep(tracep(p, "SimpleStmt"))
2019-01-09 10:17:42 +03:00
}
x := p.parseExprList()
switch p.token {
case token.Assign, token.Define: // assignment statement
pos, tok := p.pos, p.token
p.next()
y := p.parseExprList()
2019-12-20 22:40:38 +03:00
return &AssignStmt{
LHS: x,
RHS: y,
2019-01-09 10:17:42 +03:00
Token: tok,
TokenPos: pos,
}
case token.In:
if forIn {
p.next()
y := p.parseExpr()
2019-12-20 22:40:38 +03:00
var key, value *Ident
2019-01-09 10:17:42 +03:00
var ok bool
switch len(x) {
case 1:
2019-12-20 22:40:38 +03:00
key = &Ident{Name: "_", NamePos: x[0].Pos()}
2019-01-09 10:17:42 +03:00
2019-12-20 22:40:38 +03:00
value, ok = x[0].(*Ident)
2019-01-09 10:17:42 +03:00
if !ok {
p.errorExpected(x[0].Pos(), "identifier")
2019-12-20 22:40:38 +03:00
value = &Ident{Name: "_", NamePos: x[0].Pos()}
2019-01-09 10:17:42 +03:00
}
case 2:
2019-12-20 22:40:38 +03:00
key, ok = x[0].(*Ident)
2019-01-09 10:17:42 +03:00
if !ok {
p.errorExpected(x[0].Pos(), "identifier")
2019-12-20 22:40:38 +03:00
key = &Ident{Name: "_", NamePos: x[0].Pos()}
2019-01-09 10:17:42 +03:00
}
2019-12-20 22:40:38 +03:00
value, ok = x[1].(*Ident)
2019-01-09 10:17:42 +03:00
if !ok {
p.errorExpected(x[1].Pos(), "identifier")
2019-12-20 22:40:38 +03:00
value = &Ident{Name: "_", NamePos: x[1].Pos()}
2019-01-09 10:17:42 +03:00
}
}
2019-12-20 22:40:38 +03:00
return &ForInStmt{
2019-01-09 10:17:42 +03:00
Key: key,
Value: value,
Iterable: y,
}
}
}
if len(x) > 1 {
p.errorExpected(x[0].Pos(), "1 expression")
// continue with first expression
}
switch p.token {
case token.Define,
2019-12-20 22:40:38 +03:00
token.AddAssign, token.SubAssign, token.MulAssign, token.QuoAssign,
token.RemAssign, token.AndAssign, token.OrAssign, token.XorAssign,
token.ShlAssign, token.ShrAssign, token.AndNotAssign:
2019-01-09 10:17:42 +03:00
pos, tok := p.pos, p.token
p.next()
y := p.parseExpr()
2019-12-20 22:40:38 +03:00
return &AssignStmt{
LHS: []Expr{x[0]},
RHS: []Expr{y},
2019-01-09 10:17:42 +03:00
Token: tok,
TokenPos: pos,
}
case token.Inc, token.Dec:
// increment or decrement statement
2019-12-20 22:40:38 +03:00
s := &IncDecStmt{Expr: x[0], Token: p.token, TokenPos: p.pos}
2019-01-09 10:17:42 +03:00
p.next()
return s
}
2019-12-20 22:40:38 +03:00
return &ExprStmt{Expr: x[0]}
2019-01-09 10:17:42 +03:00
}
2019-12-20 22:40:38 +03:00
func (p *Parser) parseExprList() (list []Expr) {
2019-01-09 10:17:42 +03:00
if p.trace {
2019-12-20 22:40:38 +03:00
defer untracep(tracep(p, "ExpressionList"))
2019-01-09 10:17:42 +03:00
}
list = append(list, p.parseExpr())
for p.token == token.Comma {
p.next()
list = append(list, p.parseExpr())
}
return
}
2019-12-20 22:40:38 +03:00
func (p *Parser) parseMapElementLit() *MapElementLit {
2019-01-09 10:17:42 +03:00
if p.trace {
2019-12-20 22:40:38 +03:00
defer untracep(tracep(p, "MapElementLit"))
2019-01-09 10:17:42 +03:00
}
pos := p.pos
name := "_"
if p.token == token.Ident {
name = p.tokenLit
} else if p.token == token.String {
v, _ := strconv.Unquote(p.tokenLit)
name = v
} else {
p.errorExpected(pos, "map key")
}
p.next()
colonPos := p.expect(token.Colon)
2019-01-09 10:17:42 +03:00
valueExpr := p.parseExpr()
2019-12-20 22:40:38 +03:00
return &MapElementLit{
Key: name,
KeyPos: pos,
2019-01-09 10:17:42 +03:00
ColonPos: colonPos,
Value: valueExpr,
}
}
2019-12-20 22:40:38 +03:00
func (p *Parser) parseMapLit() *MapLit {
2019-01-09 10:17:42 +03:00
if p.trace {
2019-12-20 22:40:38 +03:00
defer untracep(tracep(p, "MapLit"))
2019-01-09 10:17:42 +03:00
}
lbrace := p.expect(token.LBrace)
p.exprLevel++
2019-12-20 22:40:38 +03:00
var elements []*MapElementLit
2019-01-09 10:17:42 +03:00
for p.token != token.RBrace && p.token != token.EOF {
2019-01-17 12:56:05 +03:00
elements = append(elements, p.parseMapElementLit())
2019-01-09 10:17:42 +03:00
if !p.expectComma(token.RBrace, "map element") {
break
}
}
p.exprLevel--
rbrace := p.expect(token.RBrace)
2019-12-20 22:40:38 +03:00
return &MapLit{
2019-01-09 10:17:42 +03:00
LBrace: lbrace,
RBrace: rbrace,
2019-01-17 12:56:05 +03:00
Elements: elements,
2019-01-09 10:17:42 +03:00
}
}
2019-12-20 22:40:38 +03:00
func (p *Parser) expect(token token.Token) Pos {
2019-01-09 10:17:42 +03:00
pos := p.pos
if p.token != token {
p.errorExpected(pos, "'"+token.String()+"'")
}
p.next()
return pos
}
func (p *Parser) expectSemi() {
switch p.token {
case token.RParen, token.RBrace:
// semicolon is optional before a closing ')' or '}'
case token.Comma:
// permit a ',' instead of a ';' but complain
p.errorExpected(p.pos, "';'")
fallthrough
case token.Semicolon:
p.next()
default:
p.errorExpected(p.pos, "';'")
p.advance(stmtStart)
}
}
func (p *Parser) advance(to map[token.Token]bool) {
for ; p.token != token.EOF; p.next() {
if to[p.token] {
if p.pos == p.syncPos && p.syncCount < 10 {
p.syncCount++
return
}
if p.pos > p.syncPos {
p.syncPos = p.pos
p.syncCount = 0
return
}
}
}
}
2019-12-20 22:40:38 +03:00
func (p *Parser) error(pos Pos, msg string) {
2019-01-09 10:17:42 +03:00
filePos := p.file.Position(pos)
n := len(p.errors)
if n > 0 && p.errors[n-1].Pos.Line == filePos.Line {
// discard errors reported on the same line
return
}
if n > 10 {
// too many errors; terminate early
panic(bailout{})
}
p.errors.Add(filePos, msg)
}
2019-12-20 22:40:38 +03:00
func (p *Parser) errorExpected(pos Pos, msg string) {
2019-01-09 10:17:42 +03:00
msg = "expected " + msg
if pos == p.pos {
// error happened at the current position: provide more specific
switch {
case p.token == token.Semicolon && p.tokenLit == "\n":
msg += ", found newline"
case p.token.IsLiteral():
msg += ", found " + p.tokenLit
default:
msg += ", found '" + p.token.String() + "'"
}
}
p.error(pos, msg)
}
func (p *Parser) next() {
if p.trace && p.pos.IsValid() {
s := p.token.String()
switch {
case p.token.IsLiteral():
p.printTrace(s, p.tokenLit)
case p.token.IsOperator(), p.token.IsKeyword():
p.printTrace(`"` + s + `"`)
default:
p.printTrace(s)
}
}
p.token, p.tokenLit, p.pos = p.scanner.Scan()
}
func (p *Parser) printTrace(a ...interface{}) {
const (
2019-12-20 22:40:38 +03:00
dots = ". . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . "
2019-01-09 10:17:42 +03:00
n = len(dots)
)
filePos := p.file.Position(p.pos)
2019-12-20 22:40:38 +03:00
_, _ = fmt.Fprintf(p.traceOut, "%5d: %5d:%3d: ", p.pos, filePos.Line,
filePos.Column)
2019-01-09 10:17:42 +03:00
i := 2 * p.indent
for i > n {
_, _ = fmt.Fprint(p.traceOut, dots)
i -= n
}
_, _ = fmt.Fprint(p.traceOut, dots[0:i])
_, _ = fmt.Fprintln(p.traceOut, a...)
}
2019-12-20 22:40:38 +03:00
func (p *Parser) safePos(pos Pos) Pos {
fileBase := p.file.Base
fileSize := p.file.Size
2019-01-09 10:17:42 +03:00
if int(pos) < fileBase || int(pos) > fileBase+fileSize {
2019-12-20 22:40:38 +03:00
return Pos(fileBase + fileSize)
2019-01-09 10:17:42 +03:00
}
return pos
}
2019-12-20 22:40:38 +03:00
func tracep(p *Parser, msg string) *Parser {
2019-01-09 10:17:42 +03:00
p.printTrace(msg, "(")
p.indent++
return p
}
2019-12-20 22:40:38 +03:00
func untracep(p *Parser) {
2019-01-09 10:17:42 +03:00
p.indent--
p.printTrace(")")
}