diff --git a/README.md b/README.md index a8cbb2c..b88acf6 100644 --- a/README.md +++ b/README.md @@ -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 diff --git a/fixtures/0001.php b/fixtures/0001.php index 568f738..0971029 100644 --- a/fixtures/0001.php +++ b/fixtures/0001.php @@ -14,6 +14,7 @@ class Bar { } function scalarThrower() { + // Comment throw "str"; } } diff --git a/fixtures/0002-loops.php b/fixtures/0002-loops.php index 998acea..6588216 100644 --- a/fixtures/0002-loops.php +++ b/fixtures/0002-loops.php @@ -9,7 +9,7 @@ for($i = 0; $i < 3; ++$i) { foreach($foo2 as $v2) { } - while(true) { + while(true /* infinite. */) { } do { diff --git a/main.go b/main.go index 61c5d6a..034654e 100644 --- a/main.go +++ b/main.go @@ -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()) diff --git a/node.go b/node.go index 43dba3d..6db7e2a 100644 --- a/node.go +++ b/node.go @@ -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