Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Implement unreferenced variable validation #1357

Merged
merged 15 commits into from
Aug 18, 2023
14 changes: 11 additions & 3 deletions internal/decoder/validations/unreferenced_origin.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@ package validations

import (
"context"
"fmt"
"log"

"github.com/hashicorp/hcl-lang/decoder"
"github.com/hashicorp/hcl-lang/lang"
Expand All @@ -23,24 +25,30 @@ func UnReferencedOrigin(ctx context.Context) lang.DiagnosticsMap {
for _, origin := range pathCtx.ReferenceOrigins {
matchableOrigin, ok := origin.(reference.MatchableOrigin)
if !ok {
// TODO: add a diag here
continue
}

foo := matchableOrigin.Address()[0]
if foo.String() != "var" {
continue
}

log.Printf("MatchableOrigin: %s", matchableOrigin.Address())

_, ok = pathCtx.ReferenceTargets.Match(matchableOrigin)
if !ok {
// target not found
diagsMap[origin.OriginRange().Filename] = hcl.Diagnostics{
&hcl.Diagnostic{
Severity: hcl.DiagError,
Summary: "No reference found", // TODO: Is there more we can state here?
Summary: fmt.Sprintf("No declaration found for %q", matchableOrigin.Address()),
Subject: origin.OriginRange().Ptr(),
},
}
continue
}

}

log.Printf("Length: %d Diags produced: %+v", len(pathCtx.ReferenceOrigins) , diagsMap)
return diagsMap
}
28 changes: 23 additions & 5 deletions internal/decoder/validations/unreferenced_origin_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,35 +8,53 @@ import (
"reflect"
"testing"

"github.com/hashicorp/hcl-lang/decoder"
"github.com/hashicorp/hcl-lang/lang"
"github.com/hashicorp/hcl-lang/reference"
"github.com/hashicorp/hcl/v2"
)

func TestUnReferencedOrigin(t *testing.T) {
ctx := context.Background()
// build pathdecoder
// set pathctx
// ctx = withPathContext(ctx, d.pathCtx)

pathCtx := &decoder.PathContext{
ReferenceOrigins: reference.Origins{
reference.LocalOrigin{
Range: hcl.Range{
Filename: "test.tf",
Start: hcl.Pos{},
End: hcl.Pos{},
},
Addr: lang.Address{
lang.RootStep{Name: "var"},
lang.AttrStep{Name: "foo"},
},
},
},
}

ctx = decoder.WithPathContext(ctx, pathCtx)

tests := []struct {
name string
ctx context.Context
want lang.DiagnosticsMap
}{
{
name: "unreferenced variable",
name: "undeclared variable",
ctx: ctx,
want: lang.DiagnosticsMap{
"test.tf": hcl.Diagnostics{
&hcl.Diagnostic{
Severity: hcl.DiagError,
Summary: "No reference found",
Summary: "No declaration found for \"var.foo\"",
Subject: &hcl.Range{},
},
},
},
},
}

for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := UnReferencedOrigin(tt.ctx); !reflect.DeepEqual(got, tt.want) {
Expand Down