Skip to content

Commit fe484f8

Browse files
radeksimkodbanck
andauthored
reference: Fix panic when trying to shorten origin address (#158)
Co-authored-by: Daniel Banck <[email protected]>
1 parent e68e5f2 commit fe484f8

File tree

2 files changed

+39
-6
lines changed

2 files changed

+39
-6
lines changed

reference/target.go

Lines changed: 12 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -150,10 +150,6 @@ func (ref Target) ConformsToType(typ cty.Type) bool {
150150
}
151151

152152
func (target Target) Matches(origin MatchableOrigin) bool {
153-
if len(target.LocalAddr) > len(origin.Address()) && len(target.Addr) > len(origin.Address()) {
154-
return false
155-
}
156-
157153
originAddr, localOriginAddr := origin.Address(), origin.Address()
158154

159155
matchesCons := false
@@ -173,8 +169,18 @@ func (target Target) Matches(origin MatchableOrigin) bool {
173169
}
174170

175171
if target.Type == cty.DynamicPseudoType {
176-
originAddr = origin.Address().FirstSteps(uint(len(target.Addr)))
177-
localOriginAddr = origin.Address().FirstSteps(uint(len(target.LocalAddr)))
172+
// Account for the case where the origin address points to a nested
173+
// segment, which the target address doesn't explicitly contain
174+
// but implies.
175+
// e.g. If self.foo target is of "any type" (cty.DynamicPseudoType),
176+
// then we assume it is a match for self.foo.anything
177+
// by ignoring the last "anything" segment.
178+
if len(target.Addr) < len(origin.Address()) {
179+
originAddr = origin.Address().FirstSteps(uint(len(target.Addr)))
180+
}
181+
if len(target.LocalAddr) < len(origin.Address()) {
182+
localOriginAddr = origin.Address().FirstSteps(uint(len(target.LocalAddr)))
183+
}
178184
matchesCons = true
179185
continue
180186
}

reference/targets_test.go

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -379,6 +379,33 @@ func TestTargets_Match_localRefs(t *testing.T) {
379379
},
380380
true,
381381
},
382+
{
383+
"local origin and global target",
384+
Targets{
385+
{
386+
Addr: lang.Address{
387+
lang.RootStep{Name: "module"},
388+
lang.AttrStep{Name: "localmodd"},
389+
lang.AttrStep{Name: "someattribute"},
390+
},
391+
Type: cty.DynamicPseudoType,
392+
},
393+
},
394+
LocalOrigin{
395+
Addr: lang.Address{
396+
lang.RootStep{Name: "self"},
397+
lang.AttrStep{Name: "attribute"},
398+
},
399+
Constraints: OriginConstraints{
400+
{
401+
OfScopeId: "",
402+
OfType: cty.String,
403+
},
404+
},
405+
},
406+
Targets{},
407+
false,
408+
},
382409
}
383410
for i, tc := range testCases {
384411
t.Run(fmt.Sprintf("%d-%s", i, tc.name), func(t *testing.T) {

0 commit comments

Comments
 (0)