- 
                Notifications
    You must be signed in to change notification settings 
- Fork 17
Description
Follow up of terraform-linters/tflint-ruleset-terraform#196
Naked identifier map keys are typically not valid references, but can still be successfully evaluated. Despite this, it fails to evaluate in the TFLint plugin SDK. This is exactly the same problem that occurs in terraform-linters/tflint-ruleset-terraform#196, where the test runner doesn't throw an error, but the actual runner does.
The cause of this is in the serialization of expressions. In the actual runner, in order to send an expression via gRPC, it is converted into a byte sequence of the expression's source code and then parsed again as an expression:
tflint-plugin-sdk/plugin/internal/toproto/toproto.go
Lines 117 to 120 in 63caa05
| out := &proto.Expression{ | |
| Bytes: expr.Range().SliceBytes(source), | |
| Range: Range(expr.Range()), | |
| } | 
| parsed, diags := hclext.ParseExpression(expr.Bytes, expr.Range.Filename, Pos(expr.Range.Start)) | 
However, expressions such as map keys are context-sensitive and when parsed in this manner the result is a different expression type.
package main
import (
        "fmt"
        "github.com/hashicorp/hcl/v2"
        "github.com/hashicorp/hcl/v2/hclsyntax"
)
func main() {
        source := []byte(`{ keys = "value" }`)
        expr, diags := hclsyntax.ParseExpression(source, "main.tf", hcl.InitialPos)
        if diags.HasErrors() {
                panic(diags)
        }
        pairs, diags := hcl.ExprMap(expr)
        if diags.HasErrors() {
                panic(diags)
        }
        originalExpr := pairs[0].Key
        fmt.Printf("original_expr=%T\n", originalExpr)
        keySource := originalExpr.Range().SliceBytes(source)
        parsedExpr, diags := hclsyntax.ParseExpression(keySource, "main.tf", originalExpr.Range().Start)
        if diags.HasErrors() {
                panic(diags)
        }
        fmt.Printf("parsed_expr=%T\n", parsedExpr)
}$ go run main.go
original_expr=*hclsyntax.ObjectConsKeyExpr
parsed_expr=*hclsyntax.ScopeTraversalExprThe ObjectConsKeyExpr is a wrapper expression that allows a naked identifier to be evaluated without error.
https://github.com/hashicorp/hcl/blob/v2.21.0/hclsyntax/expression.go#L1286-L1292
To fix this in the SDK, we would need to include the fact that the expression was a map key in proto.Expression and restore it on the host side.