Skip to content

Commit

Permalink
fix: handle nil expr for reference targets
Browse files Browse the repository at this point in the history
  • Loading branch information
ansgarm committed Feb 20, 2024
1 parent 4671301 commit 72ec3dd
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 0 deletions.
5 changes: 5 additions & 0 deletions decoder/reference_targets.go
Original file line number Diff line number Diff line change
Expand Up @@ -275,6 +275,11 @@ func (d *PathDecoder) decodeReferenceTargetsForAttribute(attr *hcl.Attribute, at

ctx := context.Background()

// Early return as we don't attempt to recover reference targets for invalid expressions
if attr.Expr == nil {
return refs
}

expr := d.newExpression(attr.Expr, attrSchema.Constraint)
if eType, ok := expr.(ReferenceTargetsExpression); ok {
var targetCtx *TargetContext
Expand Down
27 changes: 27 additions & 0 deletions decoder/reference_targets_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,9 @@ import (
"github.com/google/go-cmp/cmp"
"github.com/hashicorp/hcl-lang/lang"
"github.com/hashicorp/hcl-lang/reference"
"github.com/hashicorp/hcl-lang/schema"
"github.com/hashicorp/hcl/v2"
"github.com/hashicorp/hcl/v2/hclsyntax"
"github.com/zclconf/go-cty-debug/ctydebug"
"github.com/zclconf/go-cty/cty"
)
Expand Down Expand Up @@ -352,3 +354,28 @@ func TestReferenceTargetForOriginAtPos(t *testing.T) {
})
}
}

func TestCollectReferenceTargets_nil_expr(t *testing.T) {
// provider:: is not a traversal expression, so hcl will return a nil expression which needs to be
// handled gracefully
f, _ := hclsyntax.ParseConfig([]byte(`attr = provider::`), "test.tf", hcl.InitialPos)

d := testPathDecoder(t, &PathContext{
Schema: &schema.BodySchema{
Attributes: map[string]*schema.AttributeSchema{
"attr": {Constraint: schema.AnyExpression{OfType: cty.DynamicPseudoType}},
},
},
Files: map[string]*hcl.File{
"test.tf": f,
},
})
targets, err := d.CollectReferenceTargets()
if err != nil {
t.Fatal("unexpected error when collecting reference targets while there was no expr in one of them")
}

if len(targets) != 0 {
t.Fatalf("expected no targets, got %d", len(targets))
}
}

0 comments on commit 72ec3dd

Please sign in to comment.