Skip to content

Commit d735c16

Browse files
committed
parser: properly parse {% switch v.(type) %}
Updates #77
1 parent 5597812 commit d735c16

File tree

2 files changed

+10
-5
lines changed

2 files changed

+10
-5
lines changed

parser/parser.go

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -291,14 +291,14 @@ func (p *parser) parseDefault() error {
291291
return fmt.Errorf("cannot find end of %q at %s", stmtStr, s.Context())
292292
}
293293

294-
func (p *parser) parseCase() error {
294+
func (p *parser) parseCase(switchValue string) error {
295295
s := p.s
296296
t, err := expectTagContents(s)
297297
if err != nil {
298298
return err
299299
}
300300
caseStr := "case " + string(t.Value)
301-
if err = validateCaseStmt(t.Value); err != nil {
301+
if err = validateCaseStmt(switchValue, t.Value); err != nil {
302302
return fmt.Errorf("invalid statement %q at %s: %s", caseStr, s.Context(), err)
303303
}
304304
p.Printf("case %s:", t.Value)
@@ -358,6 +358,7 @@ func (p *parser) parseSwitch() error {
358358
return fmt.Errorf("invalid statement %q at %s: %s", switchStr, s.Context(), err)
359359
}
360360
p.Printf("switch %s {", t.Value)
361+
switchValue := string(t.Value)
361362
caseNum := 0
362363
defaultFound := false
363364
p.switchDepth++
@@ -387,7 +388,7 @@ func (p *parser) parseSwitch() error {
387388
return nil
388389
case "case":
389390
caseNum++
390-
if err = p.parseCase(); err != nil {
391+
if err = p.parseCase(switchValue); err != nil {
391392
return err
392393
}
393394
case "default":
@@ -872,8 +873,8 @@ func validateSwitchStmt(stmt []byte) error {
872873
return err
873874
}
874875

875-
func validateCaseStmt(stmt []byte) error {
876-
exprStr := fmt.Sprintf("func () { switch {case %s:} }", stmt)
876+
func validateCaseStmt(switchValue string, stmt []byte) error {
877+
exprStr := fmt.Sprintf("func () { switch %s {case %s:} }", switchValue, stmt)
877878
_, err := goparser.ParseExpr(exprStr)
878879
return err
879880
}

parser/parser_test.go

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -173,6 +173,10 @@ func TestParseSwitchCaseSuccess(t *testing.T) {
173173
// switch with break
174174
testParseSuccess(t, "{%func a()%}{%switch n%}{%case 1%}aaa{%break%}ignore{%endswitch%}{%endfunc%}")
175175

176+
// switch on a type
177+
// See https://github.com/valyala/quicktemplate/issues/77
178+
testParseSuccess(t, "{%func a()%}{%switch a.(type) %}{% case []string %}aaa{%case int%}bbb{%endswitch%}{%endfunc%}")
179+
176180
// complex switch
177181
testParseSuccess(t, `{%func f()%}{% for %}
178182
{%switch foo() %}

0 commit comments

Comments
 (0)