node: preserve comments

This commit is contained in:
mappu 2020-04-07 18:27:20 +12:00
parent 2568412a50
commit 49241e7a8c
5 changed files with 51 additions and 3 deletions

View File

@ -76,7 +76,7 @@ The goal is to produce idiomatic, maintainable Go code as part of a one-off conv
- [ ] PHPUnit -> Go Test
- [ ] Replace Composer/PSR-4 autoloading with Go imports
[X] Variadic function parameters
[ ] Preserve comments
[X] Preserve comments
[ ] Preserve rough line spacing
[ ] Convert wordpress / mediawiki / symfony
- [ ] Option to convert with preset=cli, preset=web, webroot path

View File

@ -14,6 +14,7 @@ class Bar {
}
function scalarThrower() {
// Comment
throw "str";
}
}

View File

@ -9,7 +9,7 @@ for($i = 0; $i < 3; ++$i) {
foreach($foo2 as $v2) {
}
while(true) {
while(true /* infinite. */) {
}
do {

View File

@ -28,6 +28,9 @@ func ConvertFile(filename string) (string, error) {
panic(err)
}
// Enable comments extraction
p.WithFreeFloating()
p.Parse()
for _, err := range p.GetErrors() {
return "", errors.New(err.String())

46
node.go
View File

@ -8,6 +8,7 @@ import (
//"strconv"
"strings"
"github.com/z7zmey/php-parser/freefloating"
"github.com/z7zmey/php-parser/node"
"github.com/z7zmey/php-parser/node/expr"
"github.com/z7zmey/php-parser/node/expr/assign"
@ -43,7 +44,50 @@ type conversionState struct {
//
func (this *conversionState) convert(n_ node.Node) (string, error) {
func (this *conversionState) convert(n node.Node) (string, error) {
// Get any whitespace/comments attached to this node
freePrefix := ""
freeSuffix := ""
if ff := n.GetFreeFloating(); ff != nil && !ff.IsEmpty() {
for positionType, elements := range *ff {
element:
for _, element := range elements {
if element.StringType == freefloating.TokenType {
// Skip <?php
continue element
}
if element.StringType == freefloating.WhiteSpaceType {
// We can't insert arbitrary whitespace
// TODO the number of newlines would be fine ONLY IF this is a *stmt
continue element
}
switch positionType {
default:
fallthrough
case freefloating.Start:
freePrefix += element.Value
case freefloating.End, freefloating.AltEnd:
freeSuffix += element.Value
}
}
}
}
// Convert the node itself
ret, err := this.convertNoFreeFloating(n)
if err != nil {
return "", err
}
return freePrefix + ret + freeSuffix, nil
}
func (this *conversionState) convertNoFreeFloating(n_ node.Node) (string, error) {
switch n := n_.(type) {
//