Skip to content

Commit 525e0b1

Browse files
Copilotjakebailey
andcommitted
Fix GetElementOrPropertyAccessName to handle ElementAccessExpression correctly
Co-authored-by: jakebailey <[email protected]>
1 parent 18a1872 commit 525e0b1

File tree

2 files changed

+43
-1
lines changed

2 files changed

+43
-1
lines changed

internal/ast/elementaccess_test.go

Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
package ast
2+
3+
import (
4+
"testing"
5+
)
6+
7+
func TestGetElementOrPropertyAccessName(t *testing.T) {
8+
factory := NewNodeFactory(NodeFactoryHooks{})
9+
10+
// Test with a string literal argument
11+
stringLiteral := factory.NewStringLiteral("key")
12+
expression := factory.NewIdentifier("obj")
13+
elementAccess := factory.NewElementAccessExpression(expression, nil, stringLiteral, 0)
14+
15+
name := GetElementOrPropertyAccessName(elementAccess)
16+
if name != "key" {
17+
t.Errorf("Expected GetElementOrPropertyAccessName to return 'key', got '%s'", name)
18+
}
19+
20+
// Test with a numeric literal argument
21+
numericLiteral := factory.NewNumericLiteral("123")
22+
elementAccess = factory.NewElementAccessExpression(expression, nil, numericLiteral, 0)
23+
24+
name = GetElementOrPropertyAccessName(elementAccess)
25+
if name != "123" {
26+
t.Errorf("Expected GetElementOrPropertyAccessName to return '123', got '%s'", name)
27+
}
28+
29+
// Test with a non-literal argument
30+
nonLiteralArg := factory.NewIdentifier("nonLiteralKey")
31+
elementAccess = factory.NewElementAccessExpression(expression, nil, nonLiteralArg, 0)
32+
33+
name = GetElementOrPropertyAccessName(elementAccess)
34+
if name != "" {
35+
t.Errorf("Expected GetElementOrPropertyAccessName to return '', got '%s'", name)
36+
}
37+
}

internal/ast/utilities.go

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1301,7 +1301,7 @@ func GetElementOrPropertyAccessArgumentExpressionOrName(node *Node) *Node {
13011301
if IsStringOrNumericLiteralLike(arg) {
13021302
return arg
13031303
}
1304-
return nil
1304+
return node
13051305
}
13061306
panic("Unhandled case in GetElementOrPropertyAccessArgumentExpressionOrName")
13071307
}
@@ -1311,6 +1311,11 @@ func GetElementOrPropertyAccessName(node *Node) string {
13111311
if name == nil {
13121312
return ""
13131313
}
1314+
// If we get back the original node and it's an ElementAccessExpression,
1315+
// it means it had a non-literal argument, so return empty string
1316+
if name == node && node.Kind == KindElementAccessExpression {
1317+
return ""
1318+
}
13141319
return name.Text()
13151320
}
13161321

0 commit comments

Comments
 (0)