77c0b55a59
The original prototype of hclwrite tried to track both the tokens and the AST as two parallel data structures. This quickly exploded in complexity, leading to lots of messy code to manage keeping those two structures in sync. This new approach melds the two structures together, creating first a physical token tree (made of "node" objects, and hidden from the caller) and then attaching the AST nodes to that token tree as additional sidecar data. The result is much easier to work with, leading to less code in the parser and considerably less complex data structures in the parser's tests. This commit is enough to reach feature parity with the previous prototype, but it remains a prototype. With a more usable foundation, we'll evolve this into a more complete implementation in subsequent commits.
48 lines
1015 B
Go
48 lines
1015 B
Go
package hclwrite
|
|
|
|
import (
|
|
"fmt"
|
|
"strings"
|
|
)
|
|
|
|
type TestTreeNode struct {
|
|
Type string
|
|
Val string
|
|
|
|
Children []TestTreeNode
|
|
}
|
|
|
|
func makeTestTree(n *node) (root TestTreeNode) {
|
|
const us = "hclwrite."
|
|
const usPtr = "*hclwrite."
|
|
root.Type = fmt.Sprintf("%T", n.content)
|
|
if strings.HasPrefix(root.Type, us) {
|
|
root.Type = root.Type[len(us):]
|
|
} else if strings.HasPrefix(root.Type, usPtr) {
|
|
root.Type = root.Type[len(usPtr):]
|
|
}
|
|
|
|
type WithVal interface {
|
|
testValue() string
|
|
}
|
|
hasTestVal := false
|
|
if withVal, ok := n.content.(WithVal); ok {
|
|
root.Val = withVal.testValue()
|
|
hasTestVal = true
|
|
}
|
|
|
|
n.content.walkChildNodes(func(n *node) {
|
|
root.Children = append(root.Children, makeTestTree(n))
|
|
})
|
|
|
|
// If we didn't end up with any children then this is probably a leaf
|
|
// node, so we'll set its content value to it raw bytes if we didn't
|
|
// already set a test value.
|
|
if !hasTestVal && len(root.Children) == 0 {
|
|
toks := n.content.BuildTokens(nil)
|
|
root.Val = toks.testValue()
|
|
}
|
|
|
|
return root
|
|
}
|