Skip to content

Commit 79b086f

Browse files
dansloTomasVotruba
andauthored
Keep heredoc labels and nowdocs, and end the closing label's line (#27)
Co-authored-by: Tomas Votruba <tomas.vot@gmail.com>
1 parent 5b102e6 commit 79b086f

3 files changed

Lines changed: 147 additions & 2 deletions

File tree

‎pkg/visitor/formatter/formatter.go‎

Lines changed: 75 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ import (
44
"bytes"
55
"github.com/rectorphp/php-parser-in-go/pkg/ast"
66
"github.com/rectorphp/php-parser-in-go/pkg/token"
7+
"strconv"
78
)
89

910
type formatterState int
@@ -19,6 +20,9 @@ type formatter struct {
1920
freeFloating []*token.Token
2021

2122
lastSemiColon *token.Token
23+
// heredocClosed is set after a heredoc's closing label: before PHP 7.3
24+
// nothing but a semicolon may follow it on its line.
25+
heredocClosed bool
2226
}
2327

2428
func NewFormatter() *formatter {
@@ -79,6 +83,13 @@ func (formatter *formatter) getFreeFloating() []*token.Token {
7983
}
8084

8185
func (formatter *formatter) newToken(tokenID token.ID, value []byte) *token.Token {
86+
if formatter.heredocClosed {
87+
formatter.heredocClosed = false
88+
if tokenID != ';' {
89+
formatter.freeFloating = append([]*token.Token{{ID: token.T_WHITESPACE, Value: []byte("\n")}}, formatter.freeFloating...)
90+
}
91+
}
92+
8293
return &token.Token{
8394
ID: tokenID,
8495
Value: value,
@@ -2345,12 +2356,74 @@ func (formatter *formatter) ScalarEncapsedStringBrackets(node *ast.ScalarEncapse
23452356
node.CloseCurlyBracketTkn = formatter.newToken('}', []byte("}"))
23462357
}
23472358

2359+
// ScalarHeredoc keeps the label a heredoc was written with, and whether it
2360+
// is a nowdoc, whose body is not interpolated: a label the body holds at
2361+
// the start of a line would end it there.
23482362
func (formatter *formatter) ScalarHeredoc(node *ast.ScalarHeredoc) {
2349-
node.OpenHeredocTkn = formatter.newToken(token.T_START_HEREDOC, []byte("<<<EOT\n"))
2363+
label, nowdoc := heredocLabel(node.OpenHeredocTkn)
2364+
label = freeLabel(label, node.Parts)
2365+
open := "<<<" + label + "\n"
2366+
if nowdoc {
2367+
open = "<<<'" + label + "'\n"
2368+
}
2369+
node.OpenHeredocTkn = formatter.newToken(token.T_START_HEREDOC, []byte(open))
23502370
for _, part := range node.Parts {
23512371
part.Accept(formatter)
23522372
}
2353-
node.CloseHeredocTkn = formatter.newToken(token.T_START_HEREDOC, []byte("EOT"))
2373+
node.CloseHeredocTkn = formatter.newToken(token.T_END_HEREDOC, []byte(label))
2374+
formatter.heredocClosed = true
2375+
}
2376+
2377+
// heredocLabel returns the label an opening <<<LABEL, <<<"LABEL" or
2378+
// <<<'LABEL' token names, and whether it opens a nowdoc: EOT without one.
2379+
func heredocLabel(open *token.Token) (string, bool) {
2380+
if open == nil {
2381+
return "EOT", false
2382+
}
2383+
value := bytes.TrimLeft(bytes.TrimPrefix(open.Value, []byte("<<<")), " \t")
2384+
value = bytes.TrimRight(value, "\r\n")
2385+
nowdoc := bytes.HasPrefix(value, []byte("'"))
2386+
value = bytes.Trim(value, "'\"")
2387+
if len(value) == 0 {
2388+
return "EOT", false
2389+
}
2390+
return string(value), nowdoc
2391+
}
2392+
2393+
// freeLabel returns label, or one made from it, that starts no line of the
2394+
// heredoc's body as a whole word.
2395+
func freeLabel(label string, parts []ast.Vertex) string {
2396+
var body []byte
2397+
for _, part := range parts {
2398+
if text, ok := part.(*ast.ScalarEncapsedStringPart); ok {
2399+
body = append(body, text.Value...)
2400+
}
2401+
}
2402+
candidate := label
2403+
for i := 1; endsHeredoc(body, candidate); i++ {
2404+
candidate = label + strconv.Itoa(i)
2405+
}
2406+
return candidate
2407+
}
2408+
2409+
// endsHeredoc reports whether a line of body would end a heredoc labelled
2410+
// label: it starts, after indentation, with the label as a whole word.
2411+
func endsHeredoc(body []byte, label string) bool {
2412+
for line := range bytes.SplitSeq(body, []byte("\n")) {
2413+
line = bytes.TrimLeft(line, " \t")
2414+
rest, ok := bytes.CutPrefix(line, []byte(label))
2415+
if !ok {
2416+
continue
2417+
}
2418+
if len(rest) == 0 {
2419+
return true
2420+
}
2421+
next := rest[0]
2422+
if next != '_' && (next < '0' || next > '9') && (next < 'a' || next > 'z') && (next < 'A' || next > 'Z') && next < 0x80 {
2423+
return true
2424+
}
2425+
}
2426+
return false
23542427
}
23552428

23562429
func (formatter *formatter) ScalarLnumber(node *ast.ScalarLnumber) {
Lines changed: 61 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,61 @@
1+
package formatter_test
2+
3+
import (
4+
"bytes"
5+
"strings"
6+
"testing"
7+
8+
"github.com/rectorphp/php-parser-in-go/pkg/ast"
9+
"github.com/rectorphp/php-parser-in-go/pkg/conf"
10+
"github.com/rectorphp/php-parser-in-go/pkg/parser"
11+
"github.com/rectorphp/php-parser-in-go/pkg/version"
12+
"github.com/rectorphp/php-parser-in-go/pkg/visitor/formatter"
13+
"github.com/rectorphp/php-parser-in-go/pkg/visitor/printer"
14+
)
15+
16+
// formatHeredoc parses src, lays it out from scratch and prints it,
17+
// without the open tag the formatter writes.
18+
func formatHeredoc(test *testing.T, src string) string {
19+
test.Helper()
20+
ver, err := version.New("8.4")
21+
if err != nil {
22+
test.Fatal(err)
23+
}
24+
root, err := parser.Parse([]byte(src), conf.Config{Version: ver})
25+
if err != nil {
26+
test.Fatal(err)
27+
}
28+
root.Accept(formatter.NewFormatter())
29+
var buffer bytes.Buffer
30+
root.(*ast.Root).Accept(printer.NewPrinter(&buffer))
31+
return strings.TrimLeft(strings.TrimPrefix(buffer.String(), "<?php"), " \n")
32+
}
33+
34+
// A nowdoc stays one: as a heredoc, PHP would interpolate its body.
35+
func TestFormatter_KeepsNowdoc(test *testing.T) {
36+
actual := formatHeredoc(test, "<?php $a = <<<'TXT'\nval $x \\t end\nTXT;\n")
37+
expected := "$a = <<<'TXT'\nval $x \\t end\nTXT;\n"
38+
if actual != expected {
39+
test.Errorf("\nexpected: %q\nactual: %q\n", expected, actual)
40+
}
41+
}
42+
43+
// A heredoc keeps its label, and takes another where its body holds a line
44+
// that would end it: here EOT.
45+
func TestFormatter_KeepsHeredocLabel(test *testing.T) {
46+
actual := formatHeredoc(test, "<?php $a = <<<TXT\nEOT; x\nTXT;\n$b = <<<TXT\nTXT1\nTXT;\n")
47+
expected := "$a = <<<TXT\nEOT; x\nTXT;\n$b = <<<TXT\nTXT1\nTXT;\n"
48+
if actual != expected {
49+
test.Errorf("\nexpected: %q\nactual: %q\n", expected, actual)
50+
}
51+
}
52+
53+
// Before PHP 7.3 nothing but a semicolon may follow a heredoc's closing
54+
// label on its line.
55+
func TestFormatter_HeredocArgumentEndsLine(test *testing.T) {
56+
actual := formatHeredoc(test, "<?php echo strtoupper(<<<EOT\nabc\nEOT\n), 1;")
57+
expected := "echo strtoupper(<<<EOT\nabc\nEOT\n), 1;"
58+
if actual != expected {
59+
test.Errorf("\nexpected: %q\nactual: %q\n", expected, actual)
60+
}
61+
}

‎pkg/visitor/printer/printer_php8_test.go‎

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -313,6 +313,17 @@ EAP;
313313
}
314314
}
315315

316+
// A flexible heredoc closed mid-line prints back byte for byte.
317+
func TestParseAndPrintPHP8InlineHeredoc(test *testing.T) {
318+
src := "<?php\nfoo(<<<EOT\n x\n EOT, 1);\nfoo(<<<EOT\n x\n EOT)->bar();\n"
319+
320+
actual := printPHP8(parsePHP8(src))
321+
322+
if src != actual {
323+
test.Errorf("\nexpected: %q\ngot: %q\n", src, actual)
324+
}
325+
}
326+
316327
// test assign
317328

318329
func TestParseAndPrintPHP8Assign(test *testing.T) {

0 commit comments

Comments
 (0)