From c52acb72490141a2e8a94f92c3a70f33bf9a3e33 Mon Sep 17 00:00:00 2001 From: mappu Date: Tue, 7 Apr 2020 23:26:44 +1200 Subject: [PATCH] node/try-catch: group err vars; simplify names; treat Exception as base case --- node.go | 53 +++++++++++++++++++++++++++++++++++++---------------- 1 file changed, 37 insertions(+), 16 deletions(-) diff --git a/node.go b/node.go index 96df5b4..4fc76b1 100644 --- a/node.go +++ b/node.go @@ -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