Skip to content

Commit e18e2e3

Browse files
authored
Add name-to-string, reserved-type, attribute-resolution and doc-comment helpers (#1)
1 parent 20be31d commit e18e2e3

6 files changed

Lines changed: 298 additions & 0 deletions

File tree

‎pkg/ast/name.go‎

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
package ast
2+
3+
import "strings"
4+
5+
// ToString returns the source text of a name node - a Name, NameFullyQualified,
6+
// or NameRelative joined by "\", a NamePart or Identifier value, or "" for any
7+
// other node. The leading separator of a fully qualified name is not included.
8+
func ToString(node Vertex) string {
9+
switch n := node.(type) {
10+
case *Name:
11+
return partsToString(n.Parts)
12+
case *NameFullyQualified:
13+
return partsToString(n.Parts)
14+
case *NameRelative:
15+
return partsToString(n.Parts)
16+
case *NamePart:
17+
return string(n.Value)
18+
case *Identifier:
19+
return string(n.Value)
20+
default:
21+
return ""
22+
}
23+
}
24+
25+
func partsToString(parts []Vertex) string {
26+
segments := make([]string, 0, len(parts))
27+
for _, part := range parts {
28+
if namePart, ok := part.(*NamePart); ok {
29+
segments = append(segments, string(namePart.Value))
30+
}
31+
}
32+
return strings.Join(segments, "\\")
33+
}
34+
35+
// reservedTypes are the PHP reserved type keywords that are not class names.
36+
var reservedTypes = map[string]bool{
37+
"int": true, "float": true, "string": true, "bool": true, "void": true,
38+
"array": true, "iterable": true, "callable": true, "object": true,
39+
"mixed": true, "never": true, "null": true, "false": true, "true": true,
40+
"self": true, "static": true, "parent": true,
41+
}
42+
43+
// IsReservedType reports whether name is a PHP reserved type keyword (a scalar,
44+
// array, callable, void, never, mixed, or a self/static/parent relative type),
45+
// matched case-insensitively. Such a name is a builtin type, not a class
46+
// reference, even though the parser produces a Name node for it.
47+
func IsReservedType(name string) bool {
48+
return reservedTypes[strings.ToLower(name)]
49+
}

‎pkg/ast/name_test.go‎

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
package ast_test
2+
3+
import (
4+
"testing"
5+
6+
"gotest.tools/assert"
7+
8+
"github.com/rectorphp/php-parser-in-go/pkg/ast"
9+
)
10+
11+
func TestToString(test *testing.T) {
12+
name := &ast.Name{Parts: []ast.Vertex{
13+
&ast.NamePart{Value: []byte("App")},
14+
&ast.NamePart{Value: []byte("Entity")},
15+
&ast.NamePart{Value: []byte("User")},
16+
}}
17+
assert.Equal(test, "App\\Entity\\User", ast.ToString(name))
18+
19+
fullyQualified := &ast.NameFullyQualified{Parts: []ast.Vertex{
20+
&ast.NamePart{Value: []byte("App")},
21+
&ast.NamePart{Value: []byte("User")},
22+
}}
23+
assert.Equal(test, "App\\User", ast.ToString(fullyQualified))
24+
25+
assert.Equal(test, "User", ast.ToString(&ast.NamePart{Value: []byte("User")}))
26+
assert.Equal(test, "string", ast.ToString(&ast.Identifier{Value: []byte("string")}))
27+
assert.Equal(test, "", ast.ToString(&ast.Root{}))
28+
}
29+
30+
func TestIsReservedType(test *testing.T) {
31+
for _, reserved := range []string{"int", "STRING", "Bool", "void", "iterable", "self", "static", "mixed", "never"} {
32+
assert.Assert(test, ast.IsReservedType(reserved), "expected %q reserved", reserved)
33+
}
34+
for _, className := range []string{"App\\User", "Closure", "Iterator", "Stringable"} {
35+
assert.Assert(test, !ast.IsReservedType(className), "expected %q not reserved", className)
36+
}
37+
}

‎pkg/visitor/doccomment.go‎

Lines changed: 85 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,85 @@
1+
package visitor
2+
3+
import (
4+
"github.com/rectorphp/php-parser-in-go/pkg/ast"
5+
"github.com/rectorphp/php-parser-in-go/pkg/token"
6+
)
7+
8+
// GetDocComment returns the /** */ doc comment immediately preceding a
9+
// declaration node, or nil when there is none. It is supported for the nodes
10+
// that carry a doc block: class, interface, trait and enum declarations,
11+
// functions and methods, and property and class-constant lists. For any other
12+
// node it returns nil.
13+
//
14+
// The comment is read from the free-floating tokens that precede the node's
15+
// first significant token (an attribute group, a modifier, or the declaration
16+
// keyword). When several doc comments precede the node, the closest one is
17+
// returned.
18+
func GetDocComment(node ast.Vertex) *token.Token {
19+
return lastDocComment(leadingTokens(node))
20+
}
21+
22+
// GetDocCommentText is GetDocComment returning the comment text, or "" when
23+
// there is no doc comment.
24+
func GetDocCommentText(node ast.Vertex) string {
25+
if doc := GetDocComment(node); doc != nil {
26+
return string(doc.Value)
27+
}
28+
return ""
29+
}
30+
31+
func leadingTokens(node ast.Vertex) []*token.Token {
32+
switch n := node.(type) {
33+
case *ast.StmtClass:
34+
return collectLeading(n.AttrGroups, n.Modifiers, n.ClassTkn)
35+
case *ast.StmtInterface:
36+
return collectLeading(n.AttrGroups, nil, n.InterfaceTkn)
37+
case *ast.StmtTrait:
38+
return collectLeading(n.AttrGroups, nil, n.TraitTkn)
39+
case *ast.StmtEnum:
40+
return collectLeading(n.AttrGroups, nil, n.EnumTkn)
41+
case *ast.StmtFunction:
42+
return collectLeading(n.AttrGroups, nil, n.FunctionTkn)
43+
case *ast.StmtClassMethod:
44+
return collectLeading(n.AttrGroups, n.Modifiers, n.FunctionTkn)
45+
case *ast.StmtPropertyList:
46+
return collectLeading(n.AttrGroups, n.Modifiers, nil)
47+
case *ast.StmtClassConstList:
48+
return collectLeading(n.AttrGroups, n.Modifiers, n.ConstTkn)
49+
default:
50+
return nil
51+
}
52+
}
53+
54+
func collectLeading(attrGroups, modifiers []ast.Vertex, keyword *token.Token) []*token.Token {
55+
var tokens []*token.Token
56+
for _, group := range attrGroups {
57+
if attributeGroup, ok := group.(*ast.AttributeGroup); ok {
58+
tokens = append(tokens, attributeGroup.OpenAttributeTkn)
59+
}
60+
}
61+
for _, modifier := range modifiers {
62+
if identifier, ok := modifier.(*ast.Identifier); ok {
63+
tokens = append(tokens, identifier.IdentifierTkn)
64+
}
65+
}
66+
if keyword != nil {
67+
tokens = append(tokens, keyword)
68+
}
69+
return tokens
70+
}
71+
72+
func lastDocComment(tokens []*token.Token) *token.Token {
73+
var found *token.Token
74+
for _, tkn := range tokens {
75+
if tkn == nil {
76+
continue
77+
}
78+
for _, free := range tkn.FreeFloating {
79+
if free.ID == token.T_DOC_COMMENT {
80+
found = free
81+
}
82+
}
83+
}
84+
return found
85+
}

‎pkg/visitor/doccomment_test.go‎

Lines changed: 74 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,74 @@
1+
package visitor_test
2+
3+
import (
4+
"strings"
5+
"testing"
6+
7+
"gotest.tools/assert"
8+
9+
"github.com/rectorphp/php-parser-in-go/pkg/ast"
10+
"github.com/rectorphp/php-parser-in-go/pkg/conf"
11+
"github.com/rectorphp/php-parser-in-go/pkg/parser"
12+
"github.com/rectorphp/php-parser-in-go/pkg/version"
13+
"github.com/rectorphp/php-parser-in-go/pkg/visitor"
14+
)
15+
16+
func firstClass(test *testing.T, src string) *ast.StmtClass {
17+
phpVersion, _ := version.New("8.4")
18+
root, err := parser.Parse([]byte(src), conf.Config{Version: phpVersion})
19+
assert.NilError(test, err)
20+
21+
for _, stmt := range root.(*ast.Root).Stmts {
22+
if class, ok := stmt.(*ast.StmtClass); ok {
23+
return class
24+
}
25+
if namespace, ok := stmt.(*ast.StmtNamespace); ok {
26+
for _, inner := range namespace.Stmts {
27+
if class, ok := inner.(*ast.StmtClass); ok {
28+
return class
29+
}
30+
}
31+
}
32+
}
33+
test.Fatal("no class found")
34+
return nil
35+
}
36+
37+
func TestGetDocComment(test *testing.T) {
38+
class := firstClass(test, `<?php
39+
/**
40+
* @api
41+
*/
42+
final class Foo
43+
{
44+
}
45+
`)
46+
47+
doc := visitor.GetDocComment(class)
48+
assert.Assert(test, doc != nil)
49+
assert.Assert(test, strings.Contains(string(doc.Value), "@api"))
50+
assert.Assert(test, strings.Contains(visitor.GetDocCommentText(class), "@api"))
51+
}
52+
53+
func TestGetDocCommentWithAttribute(test *testing.T) {
54+
class := firstClass(test, `<?php
55+
/** @deprecated */
56+
#[SomeAttribute]
57+
final class Bar
58+
{
59+
}
60+
`)
61+
62+
assert.Assert(test, strings.Contains(visitor.GetDocCommentText(class), "@deprecated"))
63+
}
64+
65+
func TestGetDocCommentNone(test *testing.T) {
66+
class := firstClass(test, `<?php
67+
final class Baz
68+
{
69+
}
70+
`)
71+
72+
assert.Assert(test, visitor.GetDocComment(class) == nil)
73+
assert.Equal(test, "", visitor.GetDocCommentText(class))
74+
}
Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
package nsresolver_test
2+
3+
import (
4+
"testing"
5+
6+
"gotest.tools/assert"
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"
13+
"github.com/rectorphp/php-parser-in-go/pkg/visitor/nsresolver"
14+
"github.com/rectorphp/php-parser-in-go/pkg/visitor/traverser"
15+
)
16+
17+
type attributeCollector struct {
18+
visitor.Null
19+
nodes []*ast.Attribute
20+
}
21+
22+
func (collector *attributeCollector) Attribute(node *ast.Attribute) {
23+
collector.nodes = append(collector.nodes, node)
24+
}
25+
26+
func TestResolveAttributeName(test *testing.T) {
27+
src := []byte(`<?php
28+
namespace App;
29+
use App\Attribute\AsThing;
30+
#[AsThing]
31+
final class Controller
32+
{
33+
}
34+
`)
35+
36+
phpVersion, _ := version.New("8.4")
37+
root, err := parser.Parse(src, conf.Config{Version: phpVersion})
38+
assert.NilError(test, err)
39+
40+
resolver := nsresolver.NewNamespaceResolver()
41+
traverser.NewTraverser(resolver).Traverse(root)
42+
43+
collector := &attributeCollector{}
44+
traverser.NewTraverser(collector).Traverse(root)
45+
assert.Equal(test, 1, len(collector.nodes))
46+
47+
resolved := resolver.ResolvedNames[collector.nodes[0].Name]
48+
assert.Equal(test, "App\\Attribute\\AsThing", resolved)
49+
}

‎pkg/visitor/nsresolver/namespace_resolver.go‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -196,6 +196,10 @@ func (namespaceResolver *NamespaceResolver) ExprConstFetch(node *ast.ExprConstFe
196196
namespaceResolver.ResolveName(node.Const, "const")
197197
}
198198

199+
func (namespaceResolver *NamespaceResolver) Attribute(node *ast.Attribute) {
200+
namespaceResolver.ResolveName(node.Name, "")
201+
}
202+
199203
func (namespaceResolver *NamespaceResolver) StmtTraitUse(node *ast.StmtTraitUse) {
200204
for _, trait := range node.Traits {
201205
namespaceResolver.ResolveName(trait, "")

0 commit comments

Comments
 (0)