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

decoder: Add support for LiteralValue as Constraint #187

Merged
merged 3 commits into from
Mar 30, 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
30 changes: 15 additions & 15 deletions decoder/expr_literal_value.go
Original file line number Diff line number Diff line change
@@ -1,29 +1,29 @@
package decoder

import (
"context"
"fmt"
"strconv"

"github.com/hashicorp/hcl-lang/lang"
"github.com/hashicorp/hcl-lang/schema"
"github.com/hashicorp/hcl/v2"
"github.com/zclconf/go-cty/cty"
)

type LiteralValue struct {
expr hcl.Expression
cons schema.LiteralValue
expr hcl.Expression
cons schema.LiteralValue
pathCtx *PathContext
}

func (lv LiteralValue) CompletionAtPos(ctx context.Context, pos hcl.Pos) []lang.Candidate {
// TODO
return nil
}
func formatNumberVal(val cty.Value) string {
bf := val.AsBigFloat()

func (lv LiteralValue) HoverAtPos(ctx context.Context, pos hcl.Pos) *lang.HoverData {
// TODO
return nil
}
if bf.IsInt() {
intNum, _ := bf.Int64()
return fmt.Sprintf("%d", intNum)
}

fNum, _ := bf.Float64()
return strconv.FormatFloat(fNum, 'f', -1, 64)

func (lv LiteralValue) SemanticTokens(ctx context.Context) []lang.SemanticToken {
// TODO
return nil
}
98 changes: 98 additions & 0 deletions decoder/expr_literal_value_completion.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,98 @@
package decoder

import (
"context"

"github.com/hashicorp/hcl-lang/lang"
"github.com/hashicorp/hcl-lang/schema"
"github.com/hashicorp/hcl/v2"
"github.com/hashicorp/hcl/v2/hclsyntax"
"github.com/zclconf/go-cty/cty"
)

func (lv LiteralValue) CompletionAtPos(ctx context.Context, pos hcl.Pos) []lang.Candidate {
typ := lv.cons.Value.Type()

if isEmptyExpression(lv.expr) {
editRange := hcl.Range{
Filename: lv.expr.Range().Filename,
Start: pos,
End: pos,
}

// We expect values to be always fully populated
ctx = schema.WithPrefillRequiredFields(ctx, true)

cd := lv.cons.EmptyCompletionData(ctx, 1, 0)

return []lang.Candidate{
{
Label: labelForLiteralValue(lv.cons.Value, false),
Detail: typ.FriendlyName(),
Kind: candidateKindForType(typ),
TextEdit: lang.TextEdit{
Range: editRange,
NewText: cd.NewText,
Snippet: cd.Snippet,
},
TriggerSuggest: cd.TriggerSuggest,
},
}
}

if typ == cty.Bool {
return lv.completeBoolAtPos(ctx, pos)
}

editRange := lv.expr.Range()
if editRange.End.Line != pos.Line {
// account for quotes or brackets that are not closed
editRange.End = pos
}
Comment on lines +48 to +51
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nitpick: This would not account for completion inside a (valid) multi-line expression, which is one of the reasons we use slightly more sophisticated solution for such an edge case, e.g. in Map

// check any incomplete configuration up to a terminating character
fileBytes := m.pathCtx.Files[eType.Range().Filename].Bytes
recoveredBytes := recoverLeftBytes(fileBytes, pos, func(offset int, r rune) bool {
return isObjectItemTerminatingRune(r) && offset > recoveryPos.Byte
})
trimmedBytes := bytes.TrimRight(recoveredBytes, " \t")

Given that we only get to deal with primitive types here (which are mostly single-line), it should be fine to ignore. Multiline strings do exist (HEREDOC syntax) but we don't really use them in Terraform as constraint anywhere.

Implementing a perfect solution would be unnecessarily costly as we'd have to be looking for different terminating character or even a sequence of characters, depending on what type we can "guess".

TL;DR it's fine as is.


Side note - I am surprised that config such as this

attr = "foo

is parsed by HCL at all and returns expression with range that we can take advantage of here, because a lot of other invalid configuration variations end up missing from the AST entirely (including the attribute), which is also what motivated that recovery logic linked above. 😅


if !editRange.ContainsPos(pos) {
// account for trailing character(s) which doesn't appear in AST
// such as dot, opening bracket etc.
editRange.End = pos
}

cd := lv.cons.EmptyCompletionData(ctx, 1, 0)
return []lang.Candidate{
{
Label: labelForLiteralValue(lv.cons.Value, false),
Detail: typ.FriendlyName(),
Kind: candidateKindForType(typ),
TextEdit: lang.TextEdit{
Range: editRange,
NewText: cd.NewText,
Snippet: cd.Snippet,
},
TriggerSuggest: cd.TriggerSuggest,
},
}

// Avoid partial completion inside complex types for now
}

func (lt LiteralValue) completeBoolAtPos(ctx context.Context, pos hcl.Pos) []lang.Candidate {
switch eType := lt.expr.(type) {

case *hclsyntax.ScopeTraversalExpr:
prefixLen := pos.Byte - eType.Range().Start.Byte
prefix := eType.Traversal.RootName()[0:prefixLen]
return boolLiteralCandidates(prefix, eType.Range())

case *hclsyntax.LiteralValueExpr:
if eType.Val.Type() == cty.Bool {
value := "false"
if eType.Val.True() {
value = "true"
}
prefixLen := pos.Byte - eType.Range().Start.Byte
prefix := value[0:prefixLen]
return boolLiteralCandidates(prefix, eType.Range())
}
}

return []lang.Candidate{}
}
Loading