forked from hashicorp/hcl
-
Notifications
You must be signed in to change notification settings - Fork 0
/
expression.go
1890 lines (1685 loc) · 55.1 KB
/
expression.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
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright (c) HashiCorp, Inc.
// SPDX-License-Identifier: MPL-2.0
package hclsyntax
import (
"fmt"
"sort"
"sync"
"github.com/hashicorp/hcl/v2"
"github.com/hashicorp/hcl/v2/ext/customdecode"
"github.com/zclconf/go-cty/cty"
"github.com/zclconf/go-cty/cty/convert"
"github.com/zclconf/go-cty/cty/function"
)
// Expression is the abstract type for nodes that behave as HCL expressions.
type Expression interface {
Node
// The hcl.Expression methods are duplicated here, rather than simply
// embedded, because both Node and hcl.Expression have a Range method
// and so they conflict.
Value(ctx *hcl.EvalContext) (cty.Value, hcl.Diagnostics)
Variables() []hcl.Traversal
StartRange() hcl.Range
}
// Assert that Expression implements hcl.Expression
var _ hcl.Expression = Expression(nil)
// ParenthesesExpr represents an expression written in grouping
// parentheses.
//
// The parser takes care of the precedence effect of the parentheses, so the
// only purpose of this separate expression node is to capture the source range
// of the parentheses themselves, rather than the source range of the
// expression within. All of the other expression operations just pass through
// to the underlying expression.
type ParenthesesExpr struct {
Expression
SrcRange hcl.Range
}
var _ hcl.Expression = (*ParenthesesExpr)(nil)
func (e *ParenthesesExpr) Range() hcl.Range {
return e.SrcRange
}
func (e *ParenthesesExpr) walkChildNodes(w internalWalkFunc) {
// We override the walkChildNodes from the embedded Expression to
// ensure that both the parentheses _and_ the content are visible
// in a walk.
w(e.Expression)
}
// LiteralValueExpr is an expression that just always returns a given value.
type LiteralValueExpr struct {
Val cty.Value
SrcRange hcl.Range
}
func (e *LiteralValueExpr) walkChildNodes(w internalWalkFunc) {
// Literal values have no child nodes
}
func (e *LiteralValueExpr) Value(ctx *hcl.EvalContext) (cty.Value, hcl.Diagnostics) {
return e.Val, nil
}
func (e *LiteralValueExpr) Range() hcl.Range {
return e.SrcRange
}
func (e *LiteralValueExpr) StartRange() hcl.Range {
return e.SrcRange
}
// Implementation for hcl.AbsTraversalForExpr.
func (e *LiteralValueExpr) AsTraversal() hcl.Traversal {
// This one's a little weird: the contract for AsTraversal is to interpret
// an expression as if it were traversal syntax, and traversal syntax
// doesn't have the special keywords "null", "true", and "false" so these
// are expected to be treated like variables in that case.
// Since our parser already turned them into LiteralValueExpr by the time
// we get here, we need to undo this and infer the name that would've
// originally led to our value.
// We don't do anything for any other values, since they don't overlap
// with traversal roots.
if e.Val.IsNull() {
// In practice the parser only generates null values of the dynamic
// pseudo-type for literals, so we can safely assume that any null
// was orignally the keyword "null".
return hcl.Traversal{
hcl.TraverseRoot{
Name: "null",
SrcRange: e.SrcRange,
},
}
}
switch e.Val {
case cty.True:
return hcl.Traversal{
hcl.TraverseRoot{
Name: "true",
SrcRange: e.SrcRange,
},
}
case cty.False:
return hcl.Traversal{
hcl.TraverseRoot{
Name: "false",
SrcRange: e.SrcRange,
},
}
default:
// No traversal is possible for any other value.
return nil
}
}
// ScopeTraversalExpr is an Expression that retrieves a value from the scope
// using a traversal.
type ScopeTraversalExpr struct {
Traversal hcl.Traversal
SrcRange hcl.Range
}
func (e *ScopeTraversalExpr) walkChildNodes(w internalWalkFunc) {
// Scope traversals have no child nodes
}
func (e *ScopeTraversalExpr) Value(ctx *hcl.EvalContext) (cty.Value, hcl.Diagnostics) {
val, diags := e.Traversal.TraverseAbs(ctx)
setDiagEvalContext(diags, e, ctx)
return val, diags
}
func (e *ScopeTraversalExpr) Range() hcl.Range {
return e.SrcRange
}
func (e *ScopeTraversalExpr) StartRange() hcl.Range {
return e.SrcRange
}
// Implementation for hcl.AbsTraversalForExpr.
func (e *ScopeTraversalExpr) AsTraversal() hcl.Traversal {
return e.Traversal
}
// RelativeTraversalExpr is an Expression that retrieves a value from another
// value using a _relative_ traversal.
type RelativeTraversalExpr struct {
Source Expression
Traversal hcl.Traversal
SrcRange hcl.Range
}
func (e *RelativeTraversalExpr) walkChildNodes(w internalWalkFunc) {
w(e.Source)
}
func (e *RelativeTraversalExpr) Value(ctx *hcl.EvalContext) (cty.Value, hcl.Diagnostics) {
src, diags := e.Source.Value(ctx)
ret, travDiags := e.Traversal.TraverseRel(src)
setDiagEvalContext(travDiags, e, ctx)
diags = append(diags, travDiags...)
return ret, diags
}
func (e *RelativeTraversalExpr) Range() hcl.Range {
return e.SrcRange
}
func (e *RelativeTraversalExpr) StartRange() hcl.Range {
return e.SrcRange
}
// Implementation for hcl.AbsTraversalForExpr.
func (e *RelativeTraversalExpr) AsTraversal() hcl.Traversal {
// We can produce a traversal only if our source can.
st, diags := hcl.AbsTraversalForExpr(e.Source)
if diags.HasErrors() {
return nil
}
ret := make(hcl.Traversal, len(st)+len(e.Traversal))
copy(ret, st)
copy(ret[len(st):], e.Traversal)
return ret
}
// FunctionCallExpr is an Expression that calls a function from the EvalContext
// and returns its result.
type FunctionCallExpr struct {
Name string
Args []Expression
// If true, the final argument should be a tuple, list or set which will
// expand to be one argument per element.
ExpandFinal bool
NameRange hcl.Range
OpenParenRange hcl.Range
CloseParenRange hcl.Range
}
func (e *FunctionCallExpr) walkChildNodes(w internalWalkFunc) {
for _, arg := range e.Args {
w(arg)
}
}
func (e *FunctionCallExpr) Value(ctx *hcl.EvalContext) (cty.Value, hcl.Diagnostics) {
var diags hcl.Diagnostics
var f function.Function
exists := false
hasNonNilMap := false
thisCtx := ctx
for thisCtx != nil {
if thisCtx.Functions == nil {
thisCtx = thisCtx.Parent()
continue
}
hasNonNilMap = true
f, exists = thisCtx.Functions[e.Name]
if exists {
break
}
thisCtx = thisCtx.Parent()
}
if !exists {
if !hasNonNilMap {
return cty.DynamicVal, hcl.Diagnostics{
{
Severity: hcl.DiagError,
Summary: "Function calls not allowed",
Detail: "Functions may not be called here.",
Subject: e.Range().Ptr(),
Expression: e,
EvalContext: ctx,
},
}
}
avail := make([]string, 0, len(ctx.Functions))
for name := range ctx.Functions {
avail = append(avail, name)
}
suggestion := nameSuggestion(e.Name, avail)
if suggestion != "" {
suggestion = fmt.Sprintf(" Did you mean %q?", suggestion)
}
return cty.DynamicVal, hcl.Diagnostics{
{
Severity: hcl.DiagError,
Summary: "Call to unknown function",
Detail: fmt.Sprintf("There is no function named %q.%s", e.Name, suggestion),
Subject: &e.NameRange,
Context: e.Range().Ptr(),
Expression: e,
EvalContext: ctx,
},
}
}
diagExtra := functionCallDiagExtra{
calledFunctionName: e.Name,
}
params := f.Params()
varParam := f.VarParam()
args := e.Args
if e.ExpandFinal {
if len(args) < 1 {
// should never happen if the parser is behaving
panic("ExpandFinal set on function call with no arguments")
}
expandExpr := args[len(args)-1]
expandVal, expandDiags := expandExpr.Value(ctx)
diags = append(diags, expandDiags...)
if expandDiags.HasErrors() {
return cty.DynamicVal, diags
}
switch {
case expandVal.Type().Equals(cty.DynamicPseudoType):
if expandVal.IsNull() {
diags = append(diags, &hcl.Diagnostic{
Severity: hcl.DiagError,
Summary: "Invalid expanding argument value",
Detail: "The expanding argument (indicated by ...) must not be null.",
Subject: expandExpr.Range().Ptr(),
Context: e.Range().Ptr(),
Expression: expandExpr,
EvalContext: ctx,
Extra: &diagExtra,
})
return cty.DynamicVal, diags
}
return cty.DynamicVal, diags
case expandVal.Type().IsTupleType() || expandVal.Type().IsListType() || expandVal.Type().IsSetType():
if expandVal.IsNull() {
diags = append(diags, &hcl.Diagnostic{
Severity: hcl.DiagError,
Summary: "Invalid expanding argument value",
Detail: "The expanding argument (indicated by ...) must not be null.",
Subject: expandExpr.Range().Ptr(),
Context: e.Range().Ptr(),
Expression: expandExpr,
EvalContext: ctx,
Extra: &diagExtra,
})
return cty.DynamicVal, diags
}
if !expandVal.IsKnown() {
return cty.DynamicVal, diags
}
// When expanding arguments from a collection, we must first unmark
// the collection itself, and apply any marks directly to the
// elements. This ensures that marks propagate correctly.
expandVal, marks := expandVal.Unmark()
newArgs := make([]Expression, 0, (len(args)-1)+expandVal.LengthInt())
newArgs = append(newArgs, args[:len(args)-1]...)
it := expandVal.ElementIterator()
for it.Next() {
_, val := it.Element()
newArgs = append(newArgs, &LiteralValueExpr{
Val: val.WithMarks(marks),
SrcRange: expandExpr.Range(),
})
}
args = newArgs
default:
diags = append(diags, &hcl.Diagnostic{
Severity: hcl.DiagError,
Summary: "Invalid expanding argument value",
Detail: "The expanding argument (indicated by ...) must be of a tuple, list, or set type.",
Subject: expandExpr.Range().Ptr(),
Context: e.Range().Ptr(),
Expression: expandExpr,
EvalContext: ctx,
Extra: &diagExtra,
})
return cty.DynamicVal, diags
}
}
if len(args) < len(params) {
missing := params[len(args)]
qual := ""
if varParam != nil {
qual = " at least"
}
return cty.DynamicVal, hcl.Diagnostics{
{
Severity: hcl.DiagError,
Summary: "Not enough function arguments",
Detail: fmt.Sprintf(
"Function %q expects%s %d argument(s). Missing value for %q.",
e.Name, qual, len(params), missing.Name,
),
Subject: &e.CloseParenRange,
Context: e.Range().Ptr(),
Expression: e,
EvalContext: ctx,
Extra: &diagExtra,
},
}
}
if varParam == nil && len(args) > len(params) {
return cty.DynamicVal, hcl.Diagnostics{
{
Severity: hcl.DiagError,
Summary: "Too many function arguments",
Detail: fmt.Sprintf(
"Function %q expects only %d argument(s).",
e.Name, len(params),
),
Subject: args[len(params)].StartRange().Ptr(),
Context: e.Range().Ptr(),
Expression: e,
EvalContext: ctx,
Extra: &diagExtra,
},
}
}
argVals := make([]cty.Value, len(args))
for i, argExpr := range args {
var param *function.Parameter
if i < len(params) {
param = ¶ms[i]
} else {
param = varParam
}
var val cty.Value
if decodeFn := customdecode.CustomExpressionDecoderForType(param.Type); decodeFn != nil {
var argDiags hcl.Diagnostics
val, argDiags = decodeFn(argExpr, ctx)
diags = append(diags, argDiags...)
if val == cty.NilVal {
val = cty.UnknownVal(param.Type)
}
} else {
var argDiags hcl.Diagnostics
val, argDiags = argExpr.Value(ctx)
if len(argDiags) > 0 {
diags = append(diags, argDiags...)
}
// Try to convert our value to the parameter type
var err error
val, err = convert.Convert(val, param.Type)
if err != nil {
diags = append(diags, &hcl.Diagnostic{
Severity: hcl.DiagError,
Summary: "Invalid function argument",
Detail: fmt.Sprintf(
"Invalid value for %q parameter: %s.",
param.Name, err,
),
Subject: argExpr.StartRange().Ptr(),
Context: e.Range().Ptr(),
Expression: argExpr,
EvalContext: ctx,
Extra: &diagExtra,
})
}
}
argVals[i] = val
}
if diags.HasErrors() {
// Don't try to execute the function if we already have errors with
// the arguments, because the result will probably be a confusing
// error message.
return cty.DynamicVal, diags
}
resultVal, err := f.Call(argVals)
if err != nil {
// For errors in the underlying call itself we also return the raw
// call error via an extra method on our "diagnostic extra" value.
diagExtra.functionCallError = err
switch terr := err.(type) {
case function.ArgError:
i := terr.Index
var param *function.Parameter
if i < len(params) {
param = ¶ms[i]
} else {
param = varParam
}
if param == nil || i > len(args)-1 {
// Getting here means that the function we called has a bug:
// it returned an arg error that refers to an argument index
// that wasn't present in the call. For that situation
// we'll degrade to a less specific error just to give
// some sort of answer, but best to still fix the buggy
// function so that it only returns argument indices that
// are in range.
switch {
case param != nil:
// In this case we'll assume that the function was trying
// to talk about a final variadic parameter but the caller
// didn't actually provide any arguments for it. That means
// we can at least still name the parameter in the
// error message, but our source range will be the call
// as a whole because we don't have an argument expression
// to highlight specifically.
diags = append(diags, &hcl.Diagnostic{
Severity: hcl.DiagError,
Summary: "Invalid function argument",
Detail: fmt.Sprintf(
"Invalid value for %q parameter: %s.",
param.Name, err,
),
Subject: e.Range().Ptr(),
Expression: e,
EvalContext: ctx,
Extra: &diagExtra,
})
default:
// This is the most degenerate case of all, where the
// index is out of range even for the declared parameters,
// and so we can't tell which parameter the function is
// trying to report an error for. Just a generic error
// report in that case.
diags = append(diags, &hcl.Diagnostic{
Severity: hcl.DiagError,
Summary: "Error in function call",
Detail: fmt.Sprintf(
"Call to function %q failed: %s.",
e.Name, err,
),
Subject: e.StartRange().Ptr(),
Context: e.Range().Ptr(),
Expression: e,
EvalContext: ctx,
Extra: &diagExtra,
})
}
} else {
argExpr := args[i]
// TODO: we should also unpick a PathError here and show the
// path to the deep value where the error was detected.
diags = append(diags, &hcl.Diagnostic{
Severity: hcl.DiagError,
Summary: "Invalid function argument",
Detail: fmt.Sprintf(
"Invalid value for %q parameter: %s.",
param.Name, err,
),
Subject: argExpr.StartRange().Ptr(),
Context: e.Range().Ptr(),
Expression: argExpr,
EvalContext: ctx,
Extra: &diagExtra,
})
}
default:
diags = append(diags, &hcl.Diagnostic{
Severity: hcl.DiagError,
Summary: "Error in function call",
Detail: fmt.Sprintf(
"Call to function %q failed: %s.",
e.Name, err,
),
Subject: e.StartRange().Ptr(),
Context: e.Range().Ptr(),
Expression: e,
EvalContext: ctx,
Extra: &diagExtra,
})
}
return cty.DynamicVal, diags
}
return resultVal, diags
}
func (e *FunctionCallExpr) Range() hcl.Range {
return hcl.RangeBetween(e.NameRange, e.CloseParenRange)
}
func (e *FunctionCallExpr) StartRange() hcl.Range {
return hcl.RangeBetween(e.NameRange, e.OpenParenRange)
}
// Implementation for hcl.ExprCall.
func (e *FunctionCallExpr) ExprCall() *hcl.StaticCall {
ret := &hcl.StaticCall{
Name: e.Name,
NameRange: e.NameRange,
Arguments: make([]hcl.Expression, len(e.Args)),
ArgsRange: hcl.RangeBetween(e.OpenParenRange, e.CloseParenRange),
}
// Need to convert our own Expression objects into hcl.Expression.
for i, arg := range e.Args {
ret.Arguments[i] = arg
}
return ret
}
// FunctionCallDiagExtra is an interface implemented by the value in the "Extra"
// field of some diagnostics returned by FunctionCallExpr.Value, giving
// cooperating callers access to some machine-readable information about the
// call that a diagnostic relates to.
type FunctionCallDiagExtra interface {
// CalledFunctionName returns the name of the function being called at
// the time the diagnostic was generated, if any. Returns an empty string
// if there is no known called function.
CalledFunctionName() string
// FunctionCallError returns the error value returned by the implementation
// of the function being called, if any. Returns nil if the diagnostic was
// not returned in response to a call error.
//
// Some errors related to calling functions are generated by HCL itself
// rather than by the underlying function, in which case this method
// will return nil.
FunctionCallError() error
}
type functionCallDiagExtra struct {
calledFunctionName string
functionCallError error
}
func (e *functionCallDiagExtra) CalledFunctionName() string {
return e.calledFunctionName
}
func (e *functionCallDiagExtra) FunctionCallError() error {
return e.functionCallError
}
type ConditionalExpr struct {
Condition Expression
TrueResult Expression
FalseResult Expression
SrcRange hcl.Range
}
func (e *ConditionalExpr) walkChildNodes(w internalWalkFunc) {
w(e.Condition)
w(e.TrueResult)
w(e.FalseResult)
}
func (e *ConditionalExpr) Value(ctx *hcl.EvalContext) (cty.Value, hcl.Diagnostics) {
trueResult, trueDiags := e.TrueResult.Value(ctx)
falseResult, falseDiags := e.FalseResult.Value(ctx)
var diags hcl.Diagnostics
resultType := cty.DynamicPseudoType
convs := make([]convert.Conversion, 2)
switch {
// If either case is a dynamic null value (which would result from a
// literal null in the config), we know that it can convert to the expected
// type of the opposite case, and we don't need to speculatively reduce the
// final result type to DynamicPseudoType.
// If we know that either Type is a DynamicPseudoType, we can be certain
// that the other value can convert since it's a pass-through, and we don't
// need to unify the types. If the final evaluation results in the dynamic
// value being returned, there's no conversion we can do, so we return the
// value directly.
case trueResult.RawEquals(cty.NullVal(cty.DynamicPseudoType)):
resultType = falseResult.Type()
convs[0] = convert.GetConversionUnsafe(cty.DynamicPseudoType, resultType)
case falseResult.RawEquals(cty.NullVal(cty.DynamicPseudoType)):
resultType = trueResult.Type()
convs[1] = convert.GetConversionUnsafe(cty.DynamicPseudoType, resultType)
case trueResult.Type() == cty.DynamicPseudoType, falseResult.Type() == cty.DynamicPseudoType:
// the final resultType type is still unknown
// we don't need to get the conversion, because both are a noop.
default:
// Try to find a type that both results can be converted to.
resultType, convs = convert.UnifyUnsafe([]cty.Type{trueResult.Type(), falseResult.Type()})
}
if resultType == cty.NilType {
return cty.DynamicVal, hcl.Diagnostics{
{
Severity: hcl.DiagError,
Summary: "Inconsistent conditional result types",
Detail: fmt.Sprintf(
"The true and false result expressions must have consistent types. %s.",
describeConditionalTypeMismatch(trueResult.Type(), falseResult.Type()),
),
Subject: hcl.RangeBetween(e.TrueResult.Range(), e.FalseResult.Range()).Ptr(),
Context: &e.SrcRange,
Expression: e,
EvalContext: ctx,
},
}
}
condResult, condDiags := e.Condition.Value(ctx)
diags = append(diags, condDiags...)
if condResult.IsNull() {
diags = append(diags, &hcl.Diagnostic{
Severity: hcl.DiagError,
Summary: "Null condition",
Detail: "The condition value is null. Conditions must either be true or false.",
Subject: e.Condition.Range().Ptr(),
Context: &e.SrcRange,
Expression: e.Condition,
EvalContext: ctx,
})
return cty.UnknownVal(resultType), diags
}
if !condResult.IsKnown() {
// We might be able to offer a refined range for the result based on
// the two possible outcomes.
if trueResult.Type() == cty.Number && falseResult.Type() == cty.Number {
// This case deals with the common case of (predicate ? 1 : 0) and
// significantly decreases the range of the result in that case.
if !(trueResult.IsNull() || falseResult.IsNull()) {
if gt := trueResult.GreaterThan(falseResult); gt.IsKnown() {
b := cty.UnknownVal(cty.Number).Refine()
if gt.True() {
b = b.
NumberRangeLowerBound(falseResult, true).
NumberRangeUpperBound(trueResult, true)
} else {
b = b.
NumberRangeLowerBound(trueResult, true).
NumberRangeUpperBound(falseResult, true)
}
b = b.NotNull() // If neither of the results is null then the result can't be either
return b.NewValue().WithSameMarks(condResult).WithSameMarks(trueResult).WithSameMarks(falseResult), diags
}
}
}
if trueResult.Type().IsCollectionType() && falseResult.Type().IsCollectionType() {
if trueResult.Type().Equals(falseResult.Type()) {
if !(trueResult.IsNull() || falseResult.IsNull()) {
trueLen := trueResult.Length()
falseLen := falseResult.Length()
if gt := trueLen.GreaterThan(falseLen); gt.IsKnown() {
b := cty.UnknownVal(resultType).Refine()
trueLen, _ := trueLen.AsBigFloat().Int64()
falseLen, _ := falseLen.AsBigFloat().Int64()
if gt.True() {
b = b.
CollectionLengthLowerBound(int(falseLen)).
CollectionLengthUpperBound(int(trueLen))
} else {
b = b.
CollectionLengthLowerBound(int(trueLen)).
CollectionLengthUpperBound(int(falseLen))
}
b = b.NotNull() // If neither of the results is null then the result can't be either
return b.NewValue().WithSameMarks(condResult).WithSameMarks(trueResult).WithSameMarks(falseResult), diags
}
}
}
}
_, condResultMarks := condResult.Unmark()
trueResult, trueResultMarks := trueResult.Unmark()
falseResult, falseResultMarks := falseResult.Unmark()
trueRng := trueResult.Range()
falseRng := falseResult.Range()
ret := cty.UnknownVal(resultType)
if trueRng.DefinitelyNotNull() && falseRng.DefinitelyNotNull() {
ret = ret.RefineNotNull()
}
return ret.WithMarks(condResultMarks, trueResultMarks, falseResultMarks), diags
}
condResult, err := convert.Convert(condResult, cty.Bool)
if err != nil {
diags = append(diags, &hcl.Diagnostic{
Severity: hcl.DiagError,
Summary: "Incorrect condition type",
Detail: "The condition expression must be of type bool.",
Subject: e.Condition.Range().Ptr(),
Context: &e.SrcRange,
Expression: e.Condition,
EvalContext: ctx,
})
return cty.UnknownVal(resultType), diags
}
// Unmark result before testing for truthiness
condResult, _ = condResult.UnmarkDeep()
if condResult.True() {
diags = append(diags, trueDiags...)
if convs[0] != nil {
var err error
trueResult, err = convs[0](trueResult)
if err != nil {
// Unsafe conversion failed with the concrete result value
diags = append(diags, &hcl.Diagnostic{
Severity: hcl.DiagError,
Summary: "Inconsistent conditional result types",
Detail: fmt.Sprintf(
"The true result value has the wrong type: %s.",
err.Error(),
),
Subject: e.TrueResult.Range().Ptr(),
Context: &e.SrcRange,
Expression: e.TrueResult,
EvalContext: ctx,
})
trueResult = cty.UnknownVal(resultType)
}
}
return trueResult, diags
} else {
diags = append(diags, falseDiags...)
if convs[1] != nil {
var err error
falseResult, err = convs[1](falseResult)
if err != nil {
// Unsafe conversion failed with the concrete result value
diags = append(diags, &hcl.Diagnostic{
Severity: hcl.DiagError,
Summary: "Inconsistent conditional result types",
Detail: fmt.Sprintf(
"The false result value has the wrong type: %s.",
err.Error(),
),
Subject: e.FalseResult.Range().Ptr(),
Context: &e.SrcRange,
Expression: e.FalseResult,
EvalContext: ctx,
})
falseResult = cty.UnknownVal(resultType)
}
}
return falseResult, diags
}
}
// describeConditionalTypeMismatch makes a best effort to describe the
// difference between types in the true and false arms of a conditional
// expression in a way that would be useful to someone trying to understand
// why their conditional expression isn't valid.
//
// NOTE: This function is only designed to deal with situations
// where trueTy and falseTy are different. Calling it with two equal
// types will produce a nonsense result. This function also only really
// deals with situations that type unification can't resolve, so we should
// call this function only after trying type unification first.
func describeConditionalTypeMismatch(trueTy, falseTy cty.Type) string {
// The main tricky cases here are when both trueTy and falseTy are
// of the same structural type kind, such as both being object types
// or both being tuple types. In that case the "FriendlyName" method
// returns only "object" or "tuple" and so we need to do some more
// work to describe what's different inside them.
switch {
case trueTy.IsObjectType() && falseTy.IsObjectType():
// We'll first gather up the attribute names and sort them. In the
// event that there are multiple attributes that disagree across
// the two types, we'll prefer to report the one that sorts lexically
// least just so that our error message is consistent between
// evaluations.
var trueAttrs, falseAttrs []string
for name := range trueTy.AttributeTypes() {
trueAttrs = append(trueAttrs, name)
}
sort.Strings(trueAttrs)
for name := range falseTy.AttributeTypes() {
falseAttrs = append(falseAttrs, name)
}
sort.Strings(falseAttrs)
for _, name := range trueAttrs {
if !falseTy.HasAttribute(name) {
return fmt.Sprintf("The 'true' value includes object attribute %q, which is absent in the 'false' value", name)
}
trueAty := trueTy.AttributeType(name)
falseAty := falseTy.AttributeType(name)
if !trueAty.Equals(falseAty) {
// For deeply-nested differences this will likely get very
// clunky quickly by nesting these messages inside one another,
// but we'll accept that for now in the interests of producing
// _some_ useful feedback, even if it isn't as concise as
// we'd prefer it to be. Deeply-nested structures in
// conditionals are thankfully not super common.
return fmt.Sprintf(
"Type mismatch for object attribute %q: %s",
name, describeConditionalTypeMismatch(trueAty, falseAty),
)
}
}
for _, name := range falseAttrs {
if !trueTy.HasAttribute(name) {
return fmt.Sprintf("The 'false' value includes object attribute %q, which is absent in the 'true' value", name)
}
// NOTE: We don't need to check the attribute types again, because
// any attribute that both types have in common would already have
// been checked in the previous loop.
}
case trueTy.IsTupleType() && falseTy.IsTupleType():
trueEtys := trueTy.TupleElementTypes()
falseEtys := falseTy.TupleElementTypes()
if trueCount, falseCount := len(trueEtys), len(falseEtys); trueCount != falseCount {
return fmt.Sprintf("The 'true' tuple has length %d, but the 'false' tuple has length %d", trueCount, falseCount)
}
// NOTE: Thanks to the condition above, we know that both tuples are
// of the same length and so they must have some differing types
// instead.
for i := range trueEtys {
trueEty := trueEtys[i]
falseEty := falseEtys[i]
if !trueEty.Equals(falseEty) {
// For deeply-nested differences this will likely get very
// clunky quickly by nesting these messages inside one another,
// but we'll accept that for now in the interests of producing
// _some_ useful feedback, even if it isn't as concise as
// we'd prefer it to be. Deeply-nested structures in
// conditionals are thankfully not super common.
return fmt.Sprintf(
"Type mismatch for tuple element %d: %s",
i, describeConditionalTypeMismatch(trueEty, falseEty),
)
}
}
case trueTy.IsCollectionType() && falseTy.IsCollectionType():
// For this case we're specifically interested in the situation where:
// - both collections are of the same kind, AND
// - the element types of both are either object or tuple types.
// This is just to avoid writing a useless statement like
// "The 'true' value is list of object, but the 'false' value is list of object".
// This still doesn't account for more awkward cases like collections
// of collections of structural types, but we won't let perfect be
// the enemy of the good.
trueEty := trueTy.ElementType()
falseEty := falseTy.ElementType()
if (trueTy.IsListType() && falseTy.IsListType()) || (trueTy.IsMapType() && falseTy.IsMapType()) || (trueTy.IsSetType() && falseTy.IsSetType()) {
if (trueEty.IsObjectType() && falseEty.IsObjectType()) || (trueEty.IsTupleType() && falseEty.IsTupleType()) {
noun := "collection"
switch { // NOTE: We now know that trueTy and falseTy have the same collection kind
case trueTy.IsListType():
noun = "list"
case trueTy.IsSetType():
noun = "set"
case trueTy.IsMapType():
noun = "map"
}
return fmt.Sprintf(
"Mismatched %s element types: %s",
noun, describeConditionalTypeMismatch(trueEty, falseEty),
)
}
}
}
// If we don't manage any more specialized message, we'll just report
// what the two types are.
trueName := trueTy.FriendlyName()
falseName := falseTy.FriendlyName()
if trueName == falseName {
// Absolute last resort for when we have no special rule above but
// we have two types with the same friendly name anyway. This is
// the most vague of all possible messages but is reserved for
// particularly awkward cases, like lists of lists of differing tuple
// types.
return "At least one deeply-nested attribute or element is not compatible across both the 'true' and the 'false' value"
}
return fmt.Sprintf(
"The 'true' value is %s, but the 'false' value is %s",
trueTy.FriendlyName(), falseTy.FriendlyName(),
)
}
func (e *ConditionalExpr) Range() hcl.Range {
return e.SrcRange
}
func (e *ConditionalExpr) StartRange() hcl.Range {
return e.Condition.StartRange()
}
type IndexExpr struct {
Collection Expression
Key Expression
SrcRange hcl.Range
OpenRange hcl.Range
BracketRange hcl.Range
}
func (e *IndexExpr) walkChildNodes(w internalWalkFunc) {
w(e.Collection)
w(e.Key)
}
func (e *IndexExpr) Value(ctx *hcl.EvalContext) (cty.Value, hcl.Diagnostics) {
var diags hcl.Diagnostics
coll, collDiags := e.Collection.Value(ctx)
key, keyDiags := e.Key.Value(ctx)
diags = append(diags, collDiags...)
diags = append(diags, keyDiags...)
val, indexDiags := hcl.Index(coll, key, &e.BracketRange)
setDiagEvalContext(indexDiags, e, ctx)
diags = append(diags, indexDiags...)
return val, diags
}
func (e *IndexExpr) Range() hcl.Range {
return e.SrcRange
}
func (e *IndexExpr) StartRange() hcl.Range {
return e.OpenRange