php8: resolve enums in NamespaceResolver

This commit is contained in:
Tyler Christensen 2023-04-24 12:23:01 -06:00 committed by Laytan Laats
parent 33d9423421
commit 6d1eee5a79
3 changed files with 50 additions and 3 deletions

View File

@ -111,7 +111,7 @@ php-parser [flags] <path> ...
Namespace resolver
------------------
Namespace resolver is a visitor that resolves nodes fully qualified name and saves into `map[node.Node]string` structure
Namespace resolver is a visitor that resolves nodes fully qualified name and saves into `map[ast.Vertex]string` structure
- For `Class`, `Interface`, `Trait`, `Function`, `Constant` nodes it saves name with current namespace.
- For `Class`, `Interface`, `Trait`, `Enum`, `Function`, `Constant` nodes it saves name with current namespace.
- For `Name`, `Relative`, `FullyQualified` nodes it resolves `use` aliases and saves a fully qualified name.

View File

@ -89,6 +89,22 @@ func (nsr *NamespaceResolver) StmtClass(n *ast.StmtClass) {
}
}
func (nsr *NamespaceResolver) StmtEnum(n *ast.StmtEnum) {
if n.Type != nil {
nsr.ResolveName(n.Type, "")
}
if n.Implements != nil {
for _, interfaceName := range n.Implements {
nsr.ResolveName(interfaceName, "")
}
}
if n.Name != nil {
nsr.AddNamespacedName(n, string(n.Name.(*ast.Identifier).Value))
}
}
func (nsr *NamespaceResolver) StmtInterface(n *ast.StmtInterface) {
if n.Extends != nil {
for _, interfaceName := range n.Extends {

View File

@ -1,9 +1,10 @@
package nsresolver_test
import (
"testing"
"github.com/laytan/php-parser/pkg/visitor/nsresolver"
"github.com/laytan/php-parser/pkg/visitor/traverser"
"testing"
"gotest.tools/assert"
@ -463,6 +464,36 @@ func TestResolveTraitName(t *testing.T) {
assert.DeepEqual(t, expected, nsResolver.ResolvedNames)
}
func TestResolveEnumName(t *testing.T) {
nameAB := &ast.Name{Parts: []ast.Vertex{&ast.NamePart{Value: []byte("A")}, &ast.NamePart{Value: []byte("B")}}}
nameBC := &ast.Name{Parts: []ast.Vertex{&ast.NamePart{Value: []byte("B")}, &ast.NamePart{Value: []byte("C")}}}
enum := &ast.StmtEnum{
Name: &ast.Identifier{Value: []byte("A")},
Type: nameAB,
Implements: []ast.Vertex{
nameBC,
},
}
stxTree := &ast.StmtStmtList{
Stmts: []ast.Vertex{
enum,
},
}
expected := map[ast.Vertex]string{
enum: "A",
nameAB: "A\\B",
nameBC: "B\\C",
}
nsResolver := nsresolver.NewNamespaceResolver()
traverser.NewTraverser(nsResolver).Traverse(stxTree)
assert.DeepEqual(t, expected, nsResolver.ResolvedNames)
}
func TestResolveFunctionName(t *testing.T) {
nameAB := &ast.Name{Parts: []ast.Vertex{&ast.NamePart{Value: []byte("A")}, &ast.NamePart{Value: []byte("B")}}}
nameBC := &ast.Name{Parts: []ast.Vertex{&ast.NamePart{Value: []byte("B")}, &ast.NamePart{Value: []byte("C")}}}