MCPcopy
hub / github.com/hashicorp/hcl / Index

Function Index

ops.go:26–252  ·  ops.go::Index

Index is a helper function that performs the same operation as the index operator in the HCL expression language. That is, the result is the same as it would be for collection[key] in a configuration expression. This is exported so that applications can perform indexing in a manner consistent with

(collection, key cty.Value, srcRange *Range)

Source from the content-addressed store, hash-verified

24// though nil can be provided if the calling application is going to
25// ignore the subject of the returned diagnostics anyway.
26func Index(collection, key cty.Value, srcRange *Range) (cty.Value, Diagnostics) {
27 const invalidIndex = "Invalid index"
28
29 if collection.IsNull() {
30 return cty.DynamicVal, Diagnostics{
31 {
32 Severity: DiagError,
33 Summary: "Attempt to index null value",
34 Detail: "This value is null, so it does not have any indices.",
35 Subject: srcRange,
36 },
37 }
38 }
39 if key.IsNull() {
40 return cty.DynamicVal, Diagnostics{
41 {
42 Severity: DiagError,
43 Summary: invalidIndex,
44 Detail: "Can't use a null value as an indexing key.",
45 Subject: srcRange,
46 },
47 }
48 }
49 ty := collection.Type()
50 kty := key.Type()
51 if kty == cty.DynamicPseudoType || ty == cty.DynamicPseudoType {
52 return cty.DynamicVal.WithSameMarks(collection), nil
53 }
54
55 switch {
56
57 case ty.IsListType() || ty.IsTupleType() || ty.IsMapType():
58 var wantType cty.Type
59 switch {
60 case ty.IsListType() || ty.IsTupleType():
61 wantType = cty.Number
62 case ty.IsMapType():
63 wantType = cty.String
64 default:
65 // should never happen
66 panic("don't know what key type we want")
67 }
68
69 key, keyErr := convert.Convert(key, wantType)
70 if keyErr != nil {
71 return cty.DynamicVal, Diagnostics{
72 {
73 Severity: DiagError,
74 Summary: invalidIndex,
75 Detail: fmt.Sprintf(
76 "The given key does not identify an element in this collection value: %s.",
77 keyErr.Error(),
78 ),
79 Subject: srcRange,
80 },
81 }
82 }
83

Callers 3

TraversalStepMethod · 0.85
ApplyPathFunction · 0.85
TestIndexFunction · 0.85

Calls 2

TypeMethod · 0.45
ErrorMethod · 0.45

Tested by 1

TestIndexFunction · 0.68