Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 22 additions & 0 deletions pkg/visitor/formatter/formatter.go
Original file line number Diff line number Diff line change
Expand Up @@ -145,6 +145,28 @@ func (formatter *formatter) Root(node *ast.Root) {
formatter.addIndent()

formatter.formatStmts(&node.Stmts)
formatter.dropTrailingOpenTag(node)
}

// dropTrailingOpenTag drops an open tag the end token holds, which follows
// a closing tag the formatter made a semicolon: '?>\n<?php // c' would
// print inside PHP code.
func (formatter *formatter) dropTrailingOpenTag(node *ast.Root) {
if node.EndTkn == nil {
return
}
if len(node.Stmts) > 0 {
if _, html := node.Stmts[len(node.Stmts)-1].(*ast.StmtInlineHtml); html {
return
}
}
var kept []*token.Token
for _, t := range node.EndTkn.FreeFloating {
if t.ID != token.T_OPEN_TAG {
kept = append(kept, t)
}
}
node.EndTkn.FreeFloating = kept
}

func (formatter *formatter) Nullable(node *ast.Nullable) {
Expand Down
31 changes: 31 additions & 0 deletions pkg/visitor/formatter/formatter_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,37 @@ func TestFormatter_Root(test *testing.T) {
}
}

func TestFormatter_Root_TrailingOpenTag(test *testing.T) {
buffer := bytes.NewBufferString("")

node := &ast.Root{
Stmts: []ast.Vertex{
&ast.StmtNop{},
},
EndTkn: &token.Token{
FreeFloating: []*token.Token{
{ID: token.T_OPEN_TAG, Value: []byte("<?php\n")},
{ID: token.T_COMMENT, Value: []byte("// trailing")},
},
},
}

formatterValue := formatter.NewFormatter()
node.Accept(formatterValue)

printerValue := printer.NewPrinter(buffer)
node.Accept(printerValue)

expected := `<?php

;// trailing`
actual := buffer.String()

if expected != actual {
test.Errorf("\nexpected: %s\ngot: %s\n", expected, actual)
}
}

func TestFormatter_Nullable(test *testing.T) {
buffer := bytes.NewBufferString("")

Expand Down