Skip to content

Commit

Permalink
Nested ternary expressions are illegal
Browse files Browse the repository at this point in the history
  • Loading branch information
skx committed Dec 18, 2019
1 parent f7224ad commit 16d23a7
Showing 1 changed file with 16 additions and 0 deletions.
16 changes: 16 additions & 0 deletions parser/parser.go
Original file line number Diff line number Diff line change
Expand Up @@ -97,6 +97,11 @@ type Parser struct {
// postfixParseFns holds a map of parsing methods for
// postfix-based syntax.
postfixParseFns map[token.Type]postfixParseFn

// are we inside a ternary expression?
//
// Nested ternary expressions are illegal :)
tern bool
}

// New returns our new parser-object.
Expand Down Expand Up @@ -387,6 +392,16 @@ func (p *Parser) parseInfixExpression(left ast.Expression) ast.Expression {

// parseTernaryExpression parses a ternary expression
func (p *Parser) parseTernaryExpression(condition ast.Expression) ast.Expression {

if p.tern {
msg := fmt.Sprintf("nested ternary expressions are illegal, around line %d", p.l.GetLine())
p.errors = append(p.errors, msg)
return nil
}

p.tern = true
defer func() { p.tern = false }()

expression := &ast.TernaryExpression{
Token: p.curToken,
Condition: condition,
Expand All @@ -403,6 +418,7 @@ func (p *Parser) parseTernaryExpression(condition ast.Expression) ast.Expression
p.nextToken()
expression.IfFalse = p.parseExpression(precedence)

p.tern = false
return expression
}

Expand Down

0 comments on commit 16d23a7

Please sign in to comment.