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

53
node.go
View File

@ -654,7 +654,7 @@ func (this *conversionState) convertNoFreeFloating(n_ node.Node) (string, error)
handler = "// suppress error"
} else {
catchVars := ""
catchVars := []string{}
catchIfs := []string{}
for _, catch_ := range n.Catches {
@ -676,25 +676,46 @@ func (this *conversionState) convertNoFreeFloating(n_ node.Node) (string, error)
return "", parseErr{catch_, err}
}
tempCatchVar := catchVar
if len(catch.Types) > 1 {
tempCatchVar += "_" + typename
if typename == `Exception` {
// PHP base type - catches all exceptions
catchStmt := catchBody
catchIfs = append(catchIfs, catchStmt)
} else {
tempCatchVar := catchVar
if len(catch.Types) > 1 {
tempCatchVar += "" + typename
}
// 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"
if len(catch.Types) > 1 {
catchStmt += catchVar + " := " + tempCatchVar + " // rename\n"
}
catchStmt += catchBody // contains its own {}
catchStmt += "}" // but without trailing NL
catchIfs = append(catchIfs, catchStmt)
}
catchVars += "var " + tempCatchVar + "*" + typename + "\n"
catchStmt := "if errors.As(err, &" + tempCatchVar + ") {\n"
if len(catch.Types) > 1 {
catchStmt += catchVar + " := " + tempCatchVar + " // rename\n"
}
catchStmt += catchBody // contains its own {}
catchStmt += "} " // but without trailing NL
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