Do not override Stmts in printNodeRoot()

This commit is contained in:
Ryan Liu 2020-07-10 15:50:09 +08:00
parent ee48d84609
commit b1266584ac
2 changed files with 27 additions and 22 deletions

View File

@ -4,8 +4,6 @@ import (
"io"
"strings"
"github.com/z7zmey/php-parser/node/stmt"
"github.com/z7zmey/php-parser/node"
"github.com/z7zmey/php-parser/node/expr"
"github.com/z7zmey/php-parser/node/expr/assign"
@ -13,6 +11,7 @@ import (
"github.com/z7zmey/php-parser/node/expr/cast"
"github.com/z7zmey/php-parser/node/name"
"github.com/z7zmey/php-parser/node/scalar"
"github.com/z7zmey/php-parser/node/stmt"
)
type PrettyPrinter struct {
@ -415,11 +414,12 @@ func (p *PrettyPrinter) printNode(n node.Node) {
// node
func (p *PrettyPrinter) printNodeRoot(n node.Node) {
var stmts []node.Node
v := n.(*node.Root)
if len(v.Stmts) > 0 {
firstStmt := v.Stmts[0]
v.Stmts = v.Stmts[1:]
stmts = v.Stmts[1:]
switch fs := firstStmt.(type) {
case *stmt.InlineHtml:
@ -433,7 +433,7 @@ func (p *PrettyPrinter) printNodeRoot(n node.Node) {
}
}
p.indentDepth--
p.printNodes(v.Stmts)
p.printNodes(stmts)
io.WriteString(p.w, "\n")
}

View File

@ -16,10 +16,17 @@ import (
)
func TestPrintFile(t *testing.T) {
o := bytes.NewBufferString("")
p := printer.NewPrettyPrinter(o, "\t")
p.Print(&node.Root{
expected := `<?php
namespace Foo;
abstract class Bar extends Baz
{
public function greet()
{
echo 'Hello world';
}
}
`
rootNode := &node.Root{
Stmts: []node.Node{
&stmt.Namespace{
NamespaceName: &name.Name{
@ -59,22 +66,20 @@ func TestPrintFile(t *testing.T) {
},
},
},
})
expected := `<?php
namespace Foo;
abstract class Bar extends Baz
{
public function greet()
{
echo 'Hello world';
}
}
`
actual := o.String()
if expected != actual {
t.Errorf("\nexpected: %s\ngot: %s\n", expected, actual)
o1 := bytes.NewBufferString("")
p1 := printer.NewPrettyPrinter(o1, "\t")
p1.Print(rootNode)
if actual := o1.String(); expected != actual {
t.Errorf("\nPrint the 1st time\nexpected: %s\ngot: %s\n", expected, actual)
}
o2 := bytes.NewBufferString("")
p2 := printer.NewPrettyPrinter(o2, "\t")
p2.Print(rootNode)
if actual := o2.String(); expected != actual {
t.Errorf("\nPrint the 2nd time\nexpected: %s\ngot: %s\n", expected, actual)
}
}