Skip to content

Commit c22ad7a

Browse files
hcldec: Improved context for expression diagnostics
The two cases where we decode attribute values should include the expression and EvalContext in any diagnostics they generate so that the calling application can give hints about the types and values of variables that are used within the expression. This also includes some adjustments to the returned source ranges so that both cases are consistent with one another and so that both indicate the entire expression as the Subject and include the attribute name in the Context. Including the whole expression in the range ensures that when there's a problem inside a tuple or object constructor, for example, we'll show the line containing the problem and not just the opening [ or { symbol.
1 parent fc57429 commit c22ad7a

File tree

1 file changed

+11
-6
lines changed

1 file changed

+11
-6
lines changed

hcldec/spec.go

Lines changed: 11 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -204,8 +204,10 @@ func (s *AttrSpec) decode(content *hcl.BodyContent, blockLabels []blockLabel, ct
204204
"Inappropriate value for attribute %q: %s.",
205205
s.Name, err.Error(),
206206
),
207-
Subject: attr.Expr.StartRange().Ptr(),
208-
Context: hcl.RangeBetween(attr.NameRange, attr.Expr.StartRange()).Ptr(),
207+
Subject: attr.Expr.Range().Ptr(),
208+
Context: hcl.RangeBetween(attr.NameRange, attr.Expr.Range()).Ptr(),
209+
Expression: attr.Expr,
210+
EvalContext: ctx,
209211
})
210212
// We'll return an unknown value of the _correct_ type so that the
211213
// incomplete result can still be used for some analysis use-cases.
@@ -1227,10 +1229,13 @@ func (s *BlockAttrsSpec) decode(content *hcl.BodyContent, blockLabels []blockLab
12271229
attrVal, err := convert.Convert(attrVal, s.ElementType)
12281230
if err != nil {
12291231
diags = append(diags, &hcl.Diagnostic{
1230-
Severity: hcl.DiagError,
1231-
Summary: "Invalid attribute value",
1232-
Detail: fmt.Sprintf("Invalid value for attribute of %q block: %s.", s.TypeName, err),
1233-
Subject: attr.Expr.Range().Ptr(),
1232+
Severity: hcl.DiagError,
1233+
Summary: "Invalid attribute value",
1234+
Detail: fmt.Sprintf("Invalid value for attribute of %q block: %s.", s.TypeName, err),
1235+
Subject: attr.Expr.Range().Ptr(),
1236+
Context: hcl.RangeBetween(attr.NameRange, attr.Expr.Range()).Ptr(),
1237+
Expression: attr.Expr,
1238+
EvalContext: ctx,
12341239
})
12351240
attrVal = cty.UnknownVal(s.ElementType)
12361241
}

0 commit comments

Comments
 (0)