Skip to content

Commit 72ec3dd

Browse files
committed
fix: handle nil expr for reference targets
1 parent 4671301 commit 72ec3dd

File tree

2 files changed

+32
-0
lines changed

2 files changed

+32
-0
lines changed

decoder/reference_targets.go

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -275,6 +275,11 @@ func (d *PathDecoder) decodeReferenceTargetsForAttribute(attr *hcl.Attribute, at
275275

276276
ctx := context.Background()
277277

278+
// Early return as we don't attempt to recover reference targets for invalid expressions
279+
if attr.Expr == nil {
280+
return refs
281+
}
282+
278283
expr := d.newExpression(attr.Expr, attrSchema.Constraint)
279284
if eType, ok := expr.(ReferenceTargetsExpression); ok {
280285
var targetCtx *TargetContext

decoder/reference_targets_test.go

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,9 @@ import (
1212
"github.com/google/go-cmp/cmp"
1313
"github.com/hashicorp/hcl-lang/lang"
1414
"github.com/hashicorp/hcl-lang/reference"
15+
"github.com/hashicorp/hcl-lang/schema"
1516
"github.com/hashicorp/hcl/v2"
17+
"github.com/hashicorp/hcl/v2/hclsyntax"
1618
"github.com/zclconf/go-cty-debug/ctydebug"
1719
"github.com/zclconf/go-cty/cty"
1820
)
@@ -352,3 +354,28 @@ func TestReferenceTargetForOriginAtPos(t *testing.T) {
352354
})
353355
}
354356
}
357+
358+
func TestCollectReferenceTargets_nil_expr(t *testing.T) {
359+
// provider:: is not a traversal expression, so hcl will return a nil expression which needs to be
360+
// handled gracefully
361+
f, _ := hclsyntax.ParseConfig([]byte(`attr = provider::`), "test.tf", hcl.InitialPos)
362+
363+
d := testPathDecoder(t, &PathContext{
364+
Schema: &schema.BodySchema{
365+
Attributes: map[string]*schema.AttributeSchema{
366+
"attr": {Constraint: schema.AnyExpression{OfType: cty.DynamicPseudoType}},
367+
},
368+
},
369+
Files: map[string]*hcl.File{
370+
"test.tf": f,
371+
},
372+
})
373+
targets, err := d.CollectReferenceTargets()
374+
if err != nil {
375+
t.Fatal("unexpected error when collecting reference targets while there was no expr in one of them")
376+
}
377+
378+
if len(targets) != 0 {
379+
t.Fatalf("expected no targets, got %d", len(targets))
380+
}
381+
}

0 commit comments

Comments
 (0)