-
Notifications
You must be signed in to change notification settings - Fork 24
/
expr_function.go
299 lines (255 loc) · 7.83 KB
/
expr_function.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
// Copyright (c) HashiCorp, Inc.
// SPDX-License-Identifier: MPL-2.0
package decoder
import (
"bytes"
"context"
"fmt"
"sort"
"strings"
"github.com/hashicorp/hcl-lang/lang"
"github.com/hashicorp/hcl-lang/reference"
"github.com/hashicorp/hcl-lang/schema"
"github.com/hashicorp/hcl/v2"
"github.com/hashicorp/hcl/v2/hclsyntax"
"github.com/zclconf/go-cty/cty"
"github.com/zclconf/go-cty/cty/convert"
"github.com/zclconf/go-cty/cty/function"
)
type functionExpr struct {
expr hcl.Expression
returnType cty.Type
pathCtx *PathContext
}
func (fe functionExpr) CompletionAtPos(ctx context.Context, pos hcl.Pos) []lang.Candidate {
if isEmptyExpression(fe.expr) {
editRange := hcl.Range{
Filename: fe.expr.Range().Filename,
Start: pos,
End: pos,
}
return fe.matchingFunctions("", editRange)
}
switch eType := fe.expr.(type) {
case *hclsyntax.ScopeTraversalExpr:
if len(eType.Traversal) > 1 {
// We assume that function names cannot contain dots
return []lang.Candidate{}
}
prefixLen := pos.Byte - eType.Traversal.SourceRange().Start.Byte
rootName := eType.Traversal.RootName()
// There can be a single segment with trailing dot which cannot
// be a function anymore as functions cannot contain dots.
if prefixLen > len(rootName) {
return []lang.Candidate{}
}
prefix := rootName[0:prefixLen]
return fe.matchingFunctions(prefix, eType.Range())
case *hclsyntax.FunctionCallExpr:
if eType.NameRange.ContainsPos(pos) {
prefixLen := pos.Byte - eType.NameRange.Start.Byte
prefix := eType.Name[0:prefixLen]
editRange := eType.Range()
return fe.matchingFunctions(prefix, editRange)
}
f, ok := fe.pathCtx.Functions[eType.Name]
if !ok {
return []lang.Candidate{} // Unknown function
}
parensRange := hcl.RangeBetween(eType.OpenParenRange, eType.CloseParenRange)
if !parensRange.ContainsPos(pos) {
return []lang.Candidate{} // Not inside parenthesis
}
paramsLen := len(f.Params)
if paramsLen == 0 && f.VarParam == nil {
return []lang.Candidate{} // Function accepts no parameters
}
var lastArgExpr hcl.Expression
lastArgEndPos := eType.OpenParenRange.Start
lastArgIdx := 0
for i, arg := range eType.Args {
// We overshot the argument and stop
if arg.Range().Start.Byte > pos.Byte {
break
}
if arg.Range().ContainsPos(pos) || arg.Range().End.Byte == pos.Byte {
var param function.Parameter
if i < paramsLen {
param = f.Params[i]
} else if f.VarParam != nil {
param = *f.VarParam
} else {
// Too many arguments passed to the function
return []lang.Candidate{}
}
cons := newExpression(fe.pathCtx, arg, schema.AnyExpression{OfType: param.Type})
return cons.CompletionAtPos(ctx, pos)
}
lastArgExpr = arg
lastArgEndPos = arg.Range().End
lastArgIdx = i
}
fileBytes := fe.pathCtx.Files[eType.Range().Filename].Bytes
recoveredBytes := recoverLeftBytes(fileBytes, pos, func(byteOffset int, r rune) bool {
return (r == ',' || r == '(') && byteOffset > lastArgEndPos.Byte
})
trimmedBytes := bytes.TrimRight(recoveredBytes, " \t\n")
activePar := lastArgIdx // default to last seen parameter
elemExpr := newEmptyExpressionAtPos(fe.expr.Range().Filename, pos)
if string(trimmedBytes) == "," {
activePar = lastArgIdx + 1
} else if len(recoveredBytes) == 0 && lastArgExpr != nil {
// We were unable to recover any bytes, which suggests
// we're still (partially) completing the last argument.
// A common case is trailing dot in func_call(var.foo.)
elemExpr = lastArgExpr
}
var param function.Parameter
if activePar < paramsLen {
param = f.Params[activePar]
} else if f.VarParam != nil {
param = *f.VarParam
} else {
// Too many arguments passed to the function
return []lang.Candidate{}
}
cons := newExpression(fe.pathCtx, elemExpr, schema.AnyExpression{OfType: param.Type})
return cons.CompletionAtPos(ctx, pos)
}
return []lang.Candidate{}
}
func (fe functionExpr) HoverAtPos(ctx context.Context, pos hcl.Pos) *lang.HoverData {
funcExpr, ok := fe.expr.(*hclsyntax.FunctionCallExpr)
if !ok {
return nil
}
funcSig, ok := fe.pathCtx.Functions[funcExpr.Name]
if !ok {
return nil
}
if funcExpr.NameRange.ContainsPos(pos) {
return &lang.HoverData{
Content: lang.Markdown(fmt.Sprintf("```terraform\n%s(%s) %s\n```\n\n%s",
funcExpr.Name, parameterNamesAsString(funcSig), funcSig.ReturnType.FriendlyName(), funcSig.Description)),
Range: fe.expr.Range(),
}
}
paramsLen := len(funcSig.Params)
if paramsLen == 0 && funcSig.VarParam == nil {
return nil // Function accepts no parameters
}
for i, arg := range funcExpr.Args {
var param function.Parameter
if i < paramsLen {
param = funcSig.Params[i]
} else if funcSig.VarParam != nil {
param = *funcSig.VarParam
} else {
// Too many arguments passed to the function
return nil
}
if arg.Range().ContainsPos(pos) {
return newExpression(fe.pathCtx, arg, schema.AnyExpression{
OfType: param.Type,
}).HoverAtPos(ctx, pos)
}
}
return nil
}
func (fe functionExpr) SemanticTokens(ctx context.Context) []lang.SemanticToken {
funcExpr, ok := fe.expr.(*hclsyntax.FunctionCallExpr)
if !ok {
return []lang.SemanticToken{}
}
funcSig, ok := fe.pathCtx.Functions[funcExpr.Name]
if !ok {
return []lang.SemanticToken{}
}
tokens := make([]lang.SemanticToken, 0)
tokens = append(tokens, lang.SemanticToken{
Type: lang.TokenFunctionName,
Modifiers: []lang.SemanticTokenModifier{},
Range: funcExpr.NameRange,
})
paramsLen := len(funcSig.Params)
if paramsLen == 0 && funcSig.VarParam == nil {
return tokens // Function accepts no parameters
}
for i, arg := range funcExpr.Args {
var param function.Parameter
if i < paramsLen {
param = funcSig.Params[i]
} else if funcSig.VarParam != nil {
param = *funcSig.VarParam
} else {
// Too many arguments passed to the function
break
}
tokens = append(tokens, newExpression(fe.pathCtx, arg, schema.AnyExpression{
OfType: param.Type,
}).SemanticTokens(ctx)...)
}
return tokens
}
func (fe functionExpr) ReferenceOrigins(ctx context.Context, allowSelfRefs bool) reference.Origins {
funcExpr, diags := hcl.ExprCall(fe.expr)
if diags.HasErrors() {
return reference.Origins{}
}
funcSig, ok := fe.pathCtx.Functions[funcExpr.Name]
if !ok {
return nil
}
paramsLen := len(funcSig.Params)
if paramsLen == 0 && funcSig.VarParam == nil {
return nil // Function accepts no parameters
}
origins := make(reference.Origins, 0)
for i, arg := range funcExpr.Arguments {
var param function.Parameter
if i < paramsLen {
param = funcSig.Params[i]
} else if funcSig.VarParam != nil {
param = *funcSig.VarParam
} else {
// Too many arguments passed to the function
break
}
expr := Any{
pathCtx: fe.pathCtx,
expr: arg,
cons: schema.AnyExpression{
OfType: param.Type,
},
}
origins = append(origins, expr.ReferenceOrigins(ctx, allowSelfRefs)...)
}
return origins
}
func (fe functionExpr) matchingFunctions(prefix string, editRange hcl.Range) []lang.Candidate {
candidates := make([]lang.Candidate, 0)
for name, f := range fe.pathCtx.Functions {
if !strings.HasPrefix(name, prefix) {
continue
}
// Reject functions that have a non-convertible return type
if _, err := convert.Convert(cty.UnknownVal(f.ReturnType), fe.returnType); err != nil {
continue
}
candidates = append(candidates, lang.Candidate{
Label: name,
Detail: fmt.Sprintf("%s(%s) %s", name, parameterNamesAsString(f), f.ReturnType.FriendlyName()),
Kind: lang.FunctionCandidateKind,
Description: lang.Markdown(f.Description),
TextEdit: lang.TextEdit{
NewText: fmt.Sprintf("%s()", name),
Snippet: fmt.Sprintf("%s(${0})", name),
Range: editRange,
},
})
}
sort.SliceStable(candidates, func(i, j int) bool {
return candidates[i].Label < candidates[j].Label
})
return candidates
}