hclwrite: handle legacy dot access of numeric indexes

This commit is contained in:
Ben Drucker 2020-04-28 20:38:45 -07:00
parent 7098edec61
commit 8e04c38ebf
2 changed files with 86 additions and 0 deletions

View File

@ -88,6 +88,16 @@ func (it inputTokens) PartitionType(ty hclsyntax.TokenType) (before, within, aft
panic(fmt.Sprintf("didn't find any token of type %s", ty)) panic(fmt.Sprintf("didn't find any token of type %s", ty))
} }
func (it inputTokens) PartitionTypeOk(ty hclsyntax.TokenType) (before, within, after inputTokens, ok bool) {
for i, t := range it.writerTokens {
if t.Type == ty {
return it.Slice(0, i), it.Slice(i, i+1), it.Slice(i+1, len(it.nativeTokens)), true
}
}
return inputTokens{}, inputTokens{}, inputTokens{}, false
}
func (it inputTokens) PartitionTypeSingle(ty hclsyntax.TokenType) (before inputTokens, found *Token, after inputTokens) { func (it inputTokens) PartitionTypeSingle(ty hclsyntax.TokenType) (before inputTokens, found *Token, after inputTokens) {
before, within, after := it.PartitionType(ty) before, within, after := it.PartitionType(ty)
if within.Len() != 1 { if within.Len() != 1 {
@ -404,6 +414,19 @@ func parseTraversalStep(nativeStep hcl.Traverser, from inputTokens) (before inpu
children = step.inTree.children children = step.inTree.children
before, from, after = from.Partition(nativeStep.SourceRange()) before, from, after = from.Partition(nativeStep.SourceRange())
if inBefore, dot, from, ok := from.PartitionTypeOk(hclsyntax.TokenDot); ok {
children.AppendUnstructuredTokens(inBefore.Tokens())
children.AppendUnstructuredTokens(dot.Tokens())
valBefore, valToken, valAfter := from.PartitionTypeSingle(hclsyntax.TokenNumberLit)
children.AppendUnstructuredTokens(valBefore.Tokens())
key := newNumber(valToken)
step.key = children.Append(key)
children.AppendUnstructuredTokens(valAfter.Tokens())
return before, newNode(step), after
}
var inBefore, oBrack, keyTokens, cBrack inputTokens var inBefore, oBrack, keyTokens, cBrack inputTokens
inBefore, oBrack, from = from.PartitionType(hclsyntax.TokenOBrack) inBefore, oBrack, from = from.PartitionType(hclsyntax.TokenOBrack)
children.AppendUnstructuredTokens(inBefore.Tokens()) children.AppendUnstructuredTokens(inBefore.Tokens())

View File

@ -555,6 +555,69 @@ func TestParse(t *testing.T) {
}, },
}, },
}, },
{
"a = foo.0\n",
TestTreeNode{
Type: "Body",
Children: []TestTreeNode{
{
Type: "Attribute",
Children: []TestTreeNode{
{
Type: "comments",
},
{
Type: "identifier",
Val: "a",
},
{
Type: "Tokens",
Val: " =",
},
{
Type: "Expression",
Children: []TestTreeNode{
{
Type: "Traversal",
Children: []TestTreeNode{
{
Type: "TraverseName",
Children: []TestTreeNode{
{
Type: "identifier",
Val: " foo",
},
},
},
{
Type: "TraverseIndex",
Children: []TestTreeNode{
{
Type: "Tokens",
Val: ".",
},
{
Type: "number",
Val: "0",
},
},
},
},
},
},
},
{
Type: "comments",
},
{
Type: "Tokens",
Val: "\n",
},
},
},
},
},
},
{ {
"a = foo[bar]\n", "a = foo[bar]\n",
TestTreeNode{ TestTreeNode{