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

Early validation #1368

Merged
merged 15 commits into from
Sep 28, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 25 additions & 2 deletions internal/context/context.go
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,7 @@ var (
ctxExperimentalFeatures = &contextKey{"experimental features"}
ctxRPCContext = &contextKey{"rpc context"}
ctxLanguageId = &contextKey{"language ID"}
ctxValidationOptions = &contextKey{"validation options"}
)

func missingContextErr(ctxKey *contextKey) *MissingContextErr {
Expand Down Expand Up @@ -188,6 +189,10 @@ func RPCContext(ctx context.Context) RPCContextData {
return ctx.Value(ctxRPCContext).(RPCContextData)
}

func (ctxData RPCContextData) IsDidChangeRequest() bool {
return ctxData.Method == "textDocument/didChange"
}

func WithLanguageId(ctx context.Context, languageId string) context.Context {
return context.WithValue(ctx, ctxLanguageId, languageId)
}
Expand All @@ -200,6 +205,24 @@ func IsLanguageId(ctx context.Context, expectedLangId string) bool {
return langId == expectedLangId
}

func (ctxData RPCContextData) IsDidChangeRequest() bool {
return ctxData.Method == "textDocument/didChange"
func WithValidationOptions(ctx context.Context, validationOptions *settings.ValidationOptions) context.Context {
return context.WithValue(ctx, ctxValidationOptions, validationOptions)
}

func SetValidationOptions(ctx context.Context, validationOptions settings.ValidationOptions) error {
e, ok := ctx.Value(ctxValidationOptions).(*settings.ValidationOptions)
if !ok {
return missingContextErr(ctxValidationOptions)
}

*e = validationOptions
return nil
}

func ValidationOptions(ctx context.Context) (settings.ValidationOptions, error) {
validationOptions, ok := ctx.Value(ctxValidationOptions).(*settings.ValidationOptions)
if !ok {
return settings.ValidationOptions{}, missingContextErr(ctxValidationOptions)
}
return *validationOptions, nil
}
2 changes: 2 additions & 0 deletions internal/decoder/decoder.go
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ func modulePathContext(mod *state.Module, schemaReader state.SchemaReader, modRe
ReferenceTargets: make(reference.Targets, 0),
Files: make(map[string]*hcl.File, 0),
Functions: coreFunctions(mod),
Validators: moduleValidators,
}

for _, origin := range mod.RefOrigins {
Expand Down Expand Up @@ -63,6 +64,7 @@ func varsPathContext(mod *state.Module) (*decoder.PathContext, error) {
ReferenceOrigins: make(reference.Origins, 0),
ReferenceTargets: make(reference.Targets, 0),
Files: make(map[string]*hcl.File),
Validators: varsValidators,
}

for _, origin := range mod.VarsRefOrigins {
Expand Down
74 changes: 74 additions & 0 deletions internal/decoder/validations/unreferenced_origin.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
// Copyright (c) HashiCorp, Inc.
// SPDX-License-Identifier: MPL-2.0

package validations

import (
"context"
"fmt"
"slices"

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

func UnreferencedOrigins(ctx context.Context, pathCtx *decoder.PathContext) lang.DiagnosticsMap {
diagsMap := make(lang.DiagnosticsMap)

for _, origin := range pathCtx.ReferenceOrigins {
localOrigin, ok := origin.(reference.LocalOrigin)
if !ok {
// We avoid reporting on other origin types.
//
// DirectOrigin is represented as module's source
// and we already validate existence of the local module
// and avoiding linking to a non-existent module in terraform-schema
// https://github.com/hashicorp/terraform-schema/blob/b39f3de0/schema/module_schema.go#L212-L232
//
// PathOrigin is represented as module inputs
// and we can validate module inputs more meaningfully
// as attributes in body (module block), e.g. raise that
// an input is required or unknown, rather than "reference"
// lacking a corresponding target.
continue
}

address := localOrigin.Address()

if len(address) > 2 {
// We temporarily ignore references with more than 2 segments
// as these indicate references to complex types
// which we do not fully support yet.
// TODO: revisit as part of https://github.com/hashicorp/terraform-ls/issues/653
continue
}

// we only initially validate variables & local values
// resources and data sources can have unknown schema
// and will be researched at a later point
supported := []string{"var", "local"}
firstStep := address[0].String()
if !slices.Contains(supported, firstStep) {
continue
}

_, ok = pathCtx.ReferenceTargets.Match(localOrigin)
if !ok {
// target not found
fileName := origin.OriginRange().Filename
d := &hcl.Diagnostic{
Severity: hcl.DiagError,
Summary: fmt.Sprintf("No declaration found for %q", address),
Subject: origin.OriginRange().Ptr(),
}
diagsMap[fileName] = diagsMap[fileName].Append(d)

continue
}

}

return diagsMap
}
187 changes: 187 additions & 0 deletions internal/decoder/validations/unreferenced_origin_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,187 @@
// Copyright (c) HashiCorp, Inc.
// SPDX-License-Identifier: MPL-2.0

package validations

import (
"context"
"fmt"
"testing"

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

func TestUnreferencedOrigins(t *testing.T) {
tests := []struct {
name string
origins reference.Origins
want lang.DiagnosticsMap
}{
{
name: "undeclared variable",
origins: 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"},
},
},
},
want: lang.DiagnosticsMap{
"test.tf": hcl.Diagnostics{
&hcl.Diagnostic{
Severity: hcl.DiagError,
Summary: "No declaration found for \"var.foo\"",
Subject: &hcl.Range{
Filename: "test.tf",
Start: hcl.Pos{},
End: hcl.Pos{},
},
},
},
},
},
{
name: "undeclared local value",
origins: reference.Origins{
reference.LocalOrigin{
Range: hcl.Range{
Filename: "test.tf",
Start: hcl.Pos{},
End: hcl.Pos{},
},
Addr: lang.Address{
lang.RootStep{Name: "local"},
lang.AttrStep{Name: "foo"},
},
},
},
want: lang.DiagnosticsMap{
"test.tf": hcl.Diagnostics{
&hcl.Diagnostic{
Severity: hcl.DiagError,
Summary: "No declaration found for \"local.foo\"",
Subject: &hcl.Range{
Filename: "test.tf",
Start: hcl.Pos{},
End: hcl.Pos{},
},
},
},
},
},
{
name: "unsupported variable of complex type",
origins: 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: "obj"},
lang.AttrStep{Name: "field"},
},
},
},
want: lang.DiagnosticsMap{},
},
{
name: "unsupported path origins (module input)",
origins: reference.Origins{
reference.PathOrigin{
Range: hcl.Range{
Filename: "test.tf",
Start: hcl.Pos{},
End: hcl.Pos{},
},
TargetAddr: lang.Address{
lang.RootStep{Name: "var"},
lang.AttrStep{Name: "foo"},
},
TargetPath: lang.Path{
Path: "./submodule",
LanguageID: "terraform",
},
Constraints: reference.OriginConstraints{},
},
},
want: lang.DiagnosticsMap{},
},
{
name: "many undeclared variables",
origins: reference.Origins{
reference.LocalOrigin{
Range: hcl.Range{
Filename: "test.tf",
Start: hcl.Pos{Line: 1, Column: 1, Byte: 0},
End: hcl.Pos{Line: 1, Column: 10, Byte: 10},
},
Addr: lang.Address{
lang.RootStep{Name: "var"},
lang.AttrStep{Name: "foo"},
},
},
reference.LocalOrigin{
Range: hcl.Range{
Filename: "test.tf",
Start: hcl.Pos{Line: 2, Column: 1, Byte: 0},
End: hcl.Pos{Line: 2, Column: 10, Byte: 10},
},
Addr: lang.Address{
lang.RootStep{Name: "var"},
lang.AttrStep{Name: "wakka"},
},
},
},
want: lang.DiagnosticsMap{
"test.tf": hcl.Diagnostics{
&hcl.Diagnostic{
Severity: hcl.DiagError,
Summary: "No declaration found for \"var.foo\"",
Subject: &hcl.Range{
Filename: "test.tf",
Start: hcl.Pos{Line: 1, Column: 1, Byte: 0},
End: hcl.Pos{Line: 1, Column: 10, Byte: 10},
},
},
&hcl.Diagnostic{
Severity: hcl.DiagError,
Summary: "No declaration found for \"var.wakka\"",
Subject: &hcl.Range{
Filename: "test.tf",
Start: hcl.Pos{Line: 2, Column: 1, Byte: 0},
End: hcl.Pos{Line: 2, Column: 10, Byte: 10},
},
},
},
},
},
}

for i, tt := range tests {
t.Run(fmt.Sprintf("%2d-%s", i, tt.name), func(t *testing.T) {
ctx := context.Background()

pathCtx := &decoder.PathContext{
ReferenceOrigins: tt.origins,
}

diags := UnreferencedOrigins(ctx, pathCtx)
if diff := cmp.Diff(tt.want["test.tf"], diags["test.tf"]); diff != "" {
t.Fatalf("unexpected diagnostics: %s", diff)
}
})
}
}
24 changes: 24 additions & 0 deletions internal/decoder/validators.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
// Copyright (c) HashiCorp, Inc.
// SPDX-License-Identifier: MPL-2.0

package decoder

import (
"github.com/hashicorp/hcl-lang/validator"
)

var moduleValidators = []validator.Validator{
validator.BlockLabelsLength{},
validator.DeprecatedAttribute{},
validator.DeprecatedBlock{},
validator.MaxBlocks{},
validator.MinBlocks{},
validator.MissingRequiredAttribute{},
validator.UnexpectedAttribute{},
validator.UnexpectedBlock{},
}

var varsValidators = []validator.Validator{
validator.UnexpectedAttribute{},
validator.UnexpectedBlock{},
}
Loading