Skip to content

Commit

Permalink
compiler/parser: fix panic on invalid default left expression
Browse files Browse the repository at this point in the history
If the left expression of a 'default' expression is not an identifier,
call, or rendering expression, the compiler panics instead of returning
an error.

Fixes #942
  • Loading branch information
gazerro authored Sep 23, 2022
1 parent ed8d8e4 commit ce873df
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 1 deletion.
7 changes: 6 additions & 1 deletion internal/compiler/parser_expressions.go
Original file line number Diff line number Diff line change
Expand Up @@ -434,11 +434,16 @@ func (p *parsing) parseExpr(tok token, canBeSwitchGuard, canElideType, mustBeTyp
pos := tok.pos
pos.Start = operand.Pos().Start
node := ast.NewDefault(pos, operand, nil)
if _, ok := operand.(*ast.Render); ok {
switch operand.(type) {
case *ast.Identifier:
case *ast.Call:
case *ast.Render:
// Replace the Render node with the Default node in the unexpanded
// slice because, when the tree is expanded, the parser needs to know
// if the render expression is used in a default expression.
p.unexpanded[len(p.unexpanded)-1] = node
default:
panic(syntaxError(operand.Pos(), "unexpected %s, expecting identifier, call or render", operand))
}
node.Expr2, tok = p.parseExpr(p.next(), false, false, false, nextIsBlockBrace)
if node.Expr2 == nil {
Expand Down
7 changes: 7 additions & 0 deletions test/misc/templates_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2720,6 +2720,13 @@ var templateMultiFileCases = map[string]struct {
expectedBuildErr: `const initializer render "partial.html" is not a constant`,
},

"Default with invalid left expression": {
sources: fstest.Files{
"index.txt": `{% if sortBy := sortBy.(html) default ""; sortBy %}{% end if %}`,
},
expectedBuildErr: `unexpected sortBy.(html), expecting identifier, call or render`,
},

"Removed special render assignment form": {
sources: fstest.Files{
"index.html": `{% var s string %}{% var ok bool %}{% s, ok = render "partial.html" %}`,
Expand Down

0 comments on commit ce873df

Please sign in to comment.