From 845ac944148263d65491f9e09ee46e83b7c906fc Mon Sep 17 00:00:00 2001 From: z7zmey Date: Thu, 29 Mar 2018 00:04:09 +0300 Subject: [PATCH] pretty printer: print Do, Default --- printer/printer.go | 29 ++++++++++++++++++++++ printer/printer_test.go | 55 +++++++++++++++++++++++++++++++++++++++++ 2 files changed, 84 insertions(+) diff --git a/printer/printer.go b/printer/printer.go index a7fd1fa..bd1d738 100644 --- a/printer/printer.go +++ b/printer/printer.go @@ -317,6 +317,10 @@ func getPrintFuncByNode(n node.Node) func(o io.Writer, n node.Node) { return printStmtContinue case *stmt.Declare: return printStmtDeclare + case *stmt.Default: + return printStmtDefault + case *stmt.Do: + return printStmtDo case *stmt.StmtList: return printStmtStmtList @@ -1458,6 +1462,31 @@ func printStmtDeclare(o io.Writer, n node.Node) { printStmt(o, nn.Stmt) } +func printStmtDefault(o io.Writer, n node.Node) { + nn := n.(*stmt.Default) + io.WriteString(o, "default:\n") + printNodes(o, nn.Stmts) +} + +func printStmtDo(o io.Writer, n node.Node) { + nn := n.(*stmt.Do) + io.WriteString(o, "do") + + switch s := nn.Stmt.(type) { + case *stmt.StmtList: + io.WriteString(o, " {\n") + printNodes(o, s.Stmts) + io.WriteString(o, "} ") + default: + io.WriteString(o, "\n") + Print(o, s) + } + + io.WriteString(o, "while (") + Print(o, nn.Cond) + io.WriteString(o, ");\n") +} + func printStmtStmtList(o io.Writer, n node.Node) { nn := n.(*stmt.StmtList) diff --git a/printer/printer_test.go b/printer/printer_test.go index a47c6f6..13949a9 100644 --- a/printer/printer_test.go +++ b/printer/printer_test.go @@ -2326,6 +2326,61 @@ func TestPrintStmtDeclareNop(t *testing.T) { } } +func TestPrintStmtDefalut(t *testing.T) { + o := bytes.NewBufferString("") + + printer.Print(o, &stmt.Default{ + Stmts: []node.Node{ + &stmt.Expression{Expr: &expr.Variable{VarName: &node.Identifier{Value: "a"}}}, + }, + }) + + expected := "default:\n$a;\n" + actual := o.String() + + if expected != actual { + t.Errorf("\nexpected: %s\ngot: %s\n", expected, actual) + } +} + +func TestPrintStmtDo_Expression(t *testing.T) { + o := bytes.NewBufferString("") + + printer.Print(o, &stmt.Do{ + Cond: &scalar.Lnumber{Value: "1"}, + Stmt: &stmt.Expression{ + Expr: &expr.Variable{VarName: &node.Identifier{Value: "a"}}, + }, + }) + + expected := "do\n$a;\nwhile (1);\n" + actual := o.String() + + if expected != actual { + t.Errorf("\nexpected: %s\ngot: %s\n", expected, actual) + } +} + +func TestPrintStmtDo_StmtList(t *testing.T) { + o := bytes.NewBufferString("") + + printer.Print(o, &stmt.Do{ + Cond: &scalar.Lnumber{Value: "1"}, + Stmt: &stmt.StmtList{ + Stmts: []node.Node{ + &stmt.Expression{Expr: &expr.Variable{VarName: &node.Identifier{Value: "a"}}}, + }, + }, + }) + + expected := "do {\n$a;\n} while (1);\n" + actual := o.String() + + if expected != actual { + t.Errorf("\nexpected: %s\ngot: %s\n", expected, actual) + } +} + func TestPrintStmtList(t *testing.T) { o := bytes.NewBufferString("")