node/try-catch: group err vars; simplify names; treat Exception as base case

This commit is contained in:
mappu 2020-04-07 23:26:44 +12:00
parent e9aa553216
commit c52acb7249
1 changed files with 37 additions and 16 deletions

29
node.go
View File

@ -654,7 +654,7 @@ func (this *conversionState) convertNoFreeFloating(n_ node.Node) (string, error)
handler = "// suppress error" handler = "// suppress error"
} else { } else {
catchVars := "" catchVars := []string{}
catchIfs := []string{} catchIfs := []string{}
for _, catch_ := range n.Catches { for _, catch_ := range n.Catches {
@ -676,12 +676,26 @@ func (this *conversionState) convertNoFreeFloating(n_ node.Node) (string, error)
return "", parseErr{catch_, err} return "", parseErr{catch_, err}
} }
if typename == `Exception` {
// PHP base type - catches all exceptions
catchStmt := catchBody
catchIfs = append(catchIfs, catchStmt)
} else {
tempCatchVar := catchVar tempCatchVar := catchVar
if len(catch.Types) > 1 { if len(catch.Types) > 1 {
tempCatchVar += "_" + typename tempCatchVar += "" + typename
} }
catchVars += "var " + tempCatchVar + "*" + typename + "\n" // It's common for PHP types to have 'Exception' in the suffix
// We are probably free to elide that (stylistically)
if strings.HasSuffix(tempCatchVar, `Exception`) {
tempCatchVar = tempCatchVar[0 : len(tempCatchVar)-9]
}
catchVars = append(catchVars, tempCatchVar+"*"+typename)
catchStmt := "if errors.As(err, &" + tempCatchVar + ") {\n" catchStmt := "if errors.As(err, &" + tempCatchVar + ") {\n"
if len(catch.Types) > 1 { if len(catch.Types) > 1 {
@ -693,8 +707,15 @@ func (this *conversionState) convertNoFreeFloating(n_ node.Node) (string, error)
catchIfs = append(catchIfs, catchStmt) catchIfs = append(catchIfs, catchStmt)
} }
} }
}
handler = catchVars + strings.Join(catchIfs, "else") + "\n" handler = ""
if len(catchVars) == 1 {
handler += "var " + catchVars[0] + "\n"
} else {
handler += "var (\n" + strings.Join(catchVars, "\n") + "\n)\n"
}
handler += strings.Join(catchIfs, " else ") + "\n"
} }
// Store the handler to be used going forwards // Store the handler to be used going forwards