Skip to content

Commit b02b0cf

Browse files
committed
Add else if support
1 parent cf53913 commit b02b0cf

File tree

4 files changed

+30
-3
lines changed

4 files changed

+30
-3
lines changed

ast/print_test.go

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -84,6 +84,7 @@ func TestPrint(t *testing.T) {
8484
{`(3 + 5) / (5 % 3)`, `(3 + 5) / (5 % 3)`},
8585
{`(-(1+1)) == 2`, `-(1 + 1) == 2`},
8686
{`if true { 1 } else { 2 }`, `true ? 1 : 2`},
87+
{`if true { 1 } else if false { 2 } else { 3 }`, `true ? 1 : (false ? 2 : 3)`},
8788
}
8889

8990
for _, tt := range tests {

expr_test.go

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1390,6 +1390,10 @@ func TestExpr(t *testing.T) {
13901390
`if "a" < "b" {let x = "a"; x} else {"abc"}`,
13911391
"a",
13921392
},
1393+
{
1394+
`if 1 == 2 { "no" } else if 1 == 1 { "yes" } else { "maybe" }`,
1395+
"yes",
1396+
},
13931397
{
13941398
`1; 2; 3`,
13951399
3,

parser/parser.go

Lines changed: 9 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -334,9 +334,15 @@ func (p *Parser) parseConditionalIf() Node {
334334
expr1 := p.parseSequenceExpression()
335335
p.expect(Bracket, "}")
336336
p.expect(Operator, "else")
337-
p.expect(Bracket, "{")
338-
expr2 := p.parseSequenceExpression()
339-
p.expect(Bracket, "}")
337+
338+
var expr2 Node
339+
if p.current.Is(Operator, "if") {
340+
expr2 = p.parseConditionalIf()
341+
} else {
342+
p.expect(Bracket, "{")
343+
expr2 = p.parseSequenceExpression()
344+
p.expect(Bracket, "}")
345+
}
340346

341347
return &ConditionalNode{
342348
Cond: nodeCondition,

parser/parser_test.go

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -659,6 +659,16 @@ world`},
659659
Exp1: &BoolNode{Value: true},
660660
Exp2: &IdentifierNode{Value: "x"}},
661661
},
662+
{
663+
"if a { 1 } else if b { 2 } else { 3 }",
664+
&ConditionalNode{
665+
Cond: &IdentifierNode{Value: "a"},
666+
Exp1: &IntegerNode{Value: 1},
667+
Exp2: &ConditionalNode{
668+
Cond: &IdentifierNode{Value: "b"},
669+
Exp1: &IntegerNode{Value: 2},
670+
Exp2: &IntegerNode{Value: 3}}},
671+
},
662672
{
663673
"1; 2; 3",
664674
&SequenceNode{
@@ -1019,6 +1029,12 @@ func TestParse_error(t *testing.T) {
10191029
`unexpected token Operator("if") (1:5)
10201030
| 1 + if true { 2 } else { 3 }
10211031
| ....^`,
1032+
},
1033+
{
1034+
`if a { 1 } else b`,
1035+
`unexpected token Identifier("b") (1:17)
1036+
| if a { 1 } else b
1037+
| ................^`,
10221038
},
10231039
{
10241040
`list | all(#,,)`,

0 commit comments

Comments
 (0)