Repository navigation
Expand file tree
/
Copy pathconvert.go
More file actions
671 lines (574 loc) · 25.1 KB
/
Copy pathconvert.go
File metadata and controls
671 lines (574 loc) · 25.1 KB
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
// SPDX-License-Identifier: Apache-2.0
// Copyright Noble Factor. All rights reserved.
package op
import (
"encoding"
"fmt"
"reflect"
"strings"
)
var (
// resourceInterfaceType is the [reflect.Type] of [Resource], cached for [Convert]'s registered-Resource step.
resourceInterfaceType = reflect.TypeFor[Resource]()
// sourceConverterType is the cached [reflect.Type] of [SourceConverter].
//
// Used by [typesAreInterconvertible] to test whether a candidate source type opts into the source-side
// conversion contract.
sourceConverterType = reflect.TypeFor[SourceConverter]()
// targetConverterType is the cached [reflect.Type] of [TargetConverter].
//
// Used by [typesAreInterconvertible] to test whether a candidate target type opts into the target-side
// conversion contract.
targetConverterType = reflect.TypeFor[TargetConverter]()
)
// Convert projects a Go value into the target type via the type-matching cascade.
//
// Convert is the single source of truth for Go↔Go projection in the framework. Every starlark-bridge entry point
// (wrapper extraction, plan-mode slot fill, immediate-mode dispatch) and method-dispatch site ([Method.Invoke]) routes
// through here so type-matching semantics stay in one place.
//
// The cascade:
//
// 1. Identity — value's type is the target type. Return as-is.
// 2. Assignability — value's underlying type is assignable to target ([reflect.Type.AssignableTo]).
// 3. Slice element conversion — both source and target are slices; recurse element-wise.
// 4. Map element conversion — both source and target are maps; recurse key-and-value-wise.
// 5. Source-side opt-in — value implements [SourceConverter] and advertises the target type.
// 6. Registered Resource construction — target implements [Resource], and a constructor is registered in
// [RuntimeEnvironment.ReceiverRegistry]; the constructor is run with (runtimeEnvironment, value).
// 7. Target-side opt-in — fresh target probe implements [TargetConverter] and advertises the source type.
// 8. Text unmarshal — string source into a target (or its pointer) implementing [encoding.TextUnmarshaler], e.g.
// [time.Time]; the target reconstructs itself from the text bytes.
// 9. Struct hydration — map source into a struct target; each exported field is filled from the map by its
// `json`/`yaml` tag (or field name), recursing through Convert.
// 10. Error — no path through the cascade succeeds.
//
// Parameters:
// - `runtimeEnvironment`: the ambient [RuntimeEnvironment]. Step 6 uses its [Registry] for registered
// Resource construction.
// - `value`: the source value to project. `nil` yields the zero value of `target`.
// - `target`: the [`reflect.Type`] of the desired result.
//
// Returns:
// - `any`: the projected value, ready to assign to a target of type `target`.
// - `error`: non-nil if no path through the cascade succeeds.
func Convert(runtimeEnvironment *RuntimeEnvironment, value any, target reflect.Type) (any, error) {
// Step 0: nil → zero of target.
if value == nil {
return reflect.Zero(target).Interface(), nil
}
// Steps 1-2: identity, the `any` target, and (pointer-dereferenced) assignability/convertibility —
// see [convertDirect].
if converted, ok := convertDirect(value, target); ok {
return converted, nil
}
elem := reflect.ValueOf(value)
for elem.Kind() == reflect.Pointer {
elem = elem.Elem()
}
// Step 3: slice element conversion.
if v, ok, err := tryConvertSlice(runtimeEnvironment, elem, target); ok {
return v, err
}
// Step 4: map element conversion.
if v, ok, err := tryConvertMap(runtimeEnvironment, elem, target); ok {
return v, err
}
// Step 5: source-side opt-in.
if c, ok := value.(SourceConverter); ok && c.CanConvertTo(target) {
return c.ConvertTo(target)
}
// Step 6: registered Resource construction.
if v, ok, err := tryConstructResource(runtimeEnvironment, value, target); ok {
return v, err
}
// Step 7: target-side opt-in.
if v, ok, err := tryTargetConverter(value, target); ok {
return v, err
}
// Step 8: text unmarshal (string -> encoding.TextUnmarshaler target, e.g. time.Time).
if v, ok, err := tryTextUnmarshaler(value, target); ok {
return v, err
}
// Step 9: struct hydration (map -> struct).
if v, ok, err := tryHydrateStruct(runtimeEnvironment, elem, target); ok {
return v, err
}
// Step 10: not convertible.
return nil, fmt.Errorf("%T value is neither assignable nor convertible to %s", value, target)
}
// convertDirect handles [Convert]'s direct paths — steps 1 through 2.
//
// Step 1: identity. Pointer-equal reflect.Type means the same underlying `*rtype`, so `==` is a single pointer
// comparison and subsumes the assignability identity case without paying for reflect.ValueOf, the deref walk,
// or the Interface() round-trip. Hot path for slot-fill from Parameter.Default (already at p.Type) and for any
// caller-supplied value whose dynamic type already matches target exactly.
//
// Step 1.5: empty interface (`any`) target. Any non-nil value satisfies `any` — return as-is. Crucially,
// SKIP the pointer-deref of step 2: a *T value passed to an `any`-typed target must preserve its pointer
// shape, because callers downstream (e.g., a method whose signature is `[]*T`) need the pointer back. The
// bridge's early-projection path uses this when goReceiver.Project(reflect.TypeFor[any]()) asks for the
// natural Go form of a wrapped instance — *op.Invocation must come back as *op.Invocation, not op.Invocation.
//
// Step 2: assignability with pointer-deref. Dereference pointers so a *T value reaches a T target through the
// underlying assignability rule.
//
// Parameters:
// - `value`: the non-nil value under conversion.
// - `target`: the destination type.
//
// Returns:
// - `any`: the converted value when a direct path applied.
// - `bool`: true when a direct path applied.
func convertDirect(value any, target reflect.Type) (any, bool) {
if reflect.TypeOf(value) == target {
return value, true
}
if target.Kind() == reflect.Interface && target.NumMethod() == 0 {
return value, true
}
elem := reflect.ValueOf(value)
for elem.Kind() == reflect.Pointer {
elem = elem.Elem()
}
if elem.IsValid() {
if elem.Type().AssignableTo(target) {
return elem.Interface(), true
}
if elem.Type().ConvertibleTo(target) {
return elem.Convert(target).Interface(), true
}
}
if reflect.TypeOf(value).AssignableTo(target) {
return value, true
}
return nil, false
}
// tryConvertSlice handles [Convert]'s step 3: slice → slice element-wise recursion.
//
// Heterogeneous-shaped sources ([]any from starlark lists) cannot satisfy AssignableTo against typed Go slices
// ([]string, []*file.Resource). Each element is recursed through the full [Convert] cascade so element-level
// conversions compose. Returns (nil, false, nil) when either input is not a slice.
//
// Parameters:
// - `runtimeEnvironment`: forwarded to the recursive [Convert] calls for env-sensitive steps.
// - `elem`: the source value as a [reflect.Value] (already pointer-dereferenced by Convert step 2).
// - `target`: the desired slice target type.
//
// Returns:
// - `any`: the constructed slice when applicable; nil otherwise.
// - `bool`: true when this step applied (regardless of error); false when neither input is a slice.
// - `error`: non-nil when an element conversion failed.
func tryConvertSlice(
runtimeEnvironment *RuntimeEnvironment,
elem reflect.Value,
target reflect.Type,
) (converted any, applied bool, err error) {
if elem.Kind() != reflect.Slice || target.Kind() != reflect.Slice {
return nil, false, nil
}
n := elem.Len()
out := reflect.MakeSlice(target, n, n)
for i := range n {
converted, err := Convert(runtimeEnvironment, elem.Index(i).Interface(), target.Elem())
if err != nil {
return nil, true, fmt.Errorf("slice index %d: %w", i, err)
}
out.Index(i).Set(reflect.ValueOf(converted))
}
return out.Interface(), true, nil
}
// tryConvertMap handles [Convert]'s step 4: map → map key-and-value recursion.
//
// Heterogeneous-shaped sources (map[any]any, map[string]any from starlark dictionaries) cannot satisfy AssignableTo
// against typed Go maps. Keys and values are recursed through the full [Convert] cascade so map-element conversions
// compose. Returns (nil, false, nil) when either input is not a map.
//
// Parameters:
// - `runtimeEnvironment`: forwarded to the recursive [Convert] calls for env-sensitive steps.
// - `elem`: the source value as a [reflect.Value] (already pointer-dereferenced by Convert step 2).
// - `target`: the desired map target type.
//
// Returns:
// - `any`: the constructed map when applicable; nil otherwise.
// - `bool`: true when this step applied (regardless of error); false when neither input is a map.
// - `error`: non-nil when a key or value conversion failed.
func tryConvertMap(
runtimeEnvironment *RuntimeEnvironment,
elem reflect.Value,
target reflect.Type,
) (converted any, applied bool, err error) {
if elem.Kind() != reflect.Map || target.Kind() != reflect.Map {
return nil, false, nil
}
out := reflect.MakeMapWithSize(target, elem.Len())
iter := elem.MapRange()
for iter.Next() {
convertedKey, err := Convert(runtimeEnvironment, iter.Key().Interface(), target.Key())
if err != nil {
return nil, true, fmt.Errorf("map key %v: %w", iter.Key().Interface(), err)
}
convertedValue, err := Convert(runtimeEnvironment, iter.Value().Interface(), target.Elem())
if err != nil {
return nil, true, fmt.Errorf("map value for %v: %w", iter.Key().Interface(), err)
}
out.SetMapIndex(reflect.ValueOf(convertedKey), reflect.ValueOf(convertedValue))
}
return out.Interface(), true, nil
}
// tryConstructResource handles [Convert]'s step 6: registered Resource construction.
//
// A value that is the URI of a resource already held by [RuntimeEnvironment.ResourceCatalog] resolves to that restored
// generation first — this is how a reloaded producer result (a resource's tag-URI string) retypes to the live Resource
// after resume, since the registered constructor would reject the tag URI (it expects a bare file:// scheme). A path
// string or unknown URI misses the catalog and constructs fresh.
//
// Tried before [TargetConverter] (step 7) so Resources with both a registered constructor and a [TargetConverter]
// opt-in use the env-aware canonical path at dispatch: the registered constructor receives the full
// [RuntimeEnvironment] (catalog, root, registry, etc.) and can produce a fully-canonicalized Resource.
// [TargetConverter] (step 7) is reached only when no registered constructor applies — env-less library callers, tests,
// or non-Resource target types — and serves as the framework's plan-time convertibility probe via
// [typesAreInterconvertible]. Resources without a registered constructor still get the [TargetConverter] path;
// Resources with one always prefer the canonical.
//
// Returns (nil, false, nil) when `target` is not a Resource type or no [RuntimeEnvironment.ReceiverRegistry] is
// available.
//
// Parameters:
// - `runtimeEnvironment`: provides [RuntimeEnvironment.ReceiverRegistry] for type lookup and is passed to the
// registered constructor.
// - `value`: the source value to project.
// - `target`: the Resource target type.
//
// Returns:
// - `any`: the constructed Resource when applicable; nil otherwise.
// - `bool`: true when this step applied (regardless of error).
// - `error`: non-nil when registry lookup, type assertion, or constructor execution fails.
func tryConstructResource(
runtimeEnvironment *RuntimeEnvironment,
value any,
target reflect.Type,
) (constructed any, applied bool, err error) {
if !target.Implements(resourceInterfaceType) || runtimeEnvironment == nil {
return nil, false, nil
}
// A reloaded producer result is the resource's tag-URI string: a promise resolved after resume hands the consumer
// that string, not the live Resource. If the rehydrated catalog already holds that resource, return the full
// restored generation rather than reconstructing a fresh, state-less one — and the file constructor would anyway
// reject the tag URI, expecting a bare file:// scheme. Path strings and unknown URIs miss the catalog and fall
// through to construction below.
if uri, isString := value.(string); isString && runtimeEnvironment.ResourceCatalog != nil {
if id := runtimeEnvironment.ResourceCatalog.Current(uri); id != "" {
resource, ok := runtimeEnvironment.ResourceCatalog.Lookup(id)
if ok && reflect.TypeOf(resource).AssignableTo(target) {
return resource, true, nil
}
}
}
// Resources are typically announced under the value type (file.Resource), but the parameter type is the pointer
// (*file.Resource). Try the pointer-or-element fallback the registry's other lookups use.
rt, ok := ReceiverRegistry().TypeByReflection(target)
if !ok && target.Kind() == reflect.Pointer {
rt, ok = ReceiverRegistry().TypeByReflection(target.Elem())
}
if !ok && target.Kind() != reflect.Pointer {
rt, ok = ReceiverRegistry().TypeByReflection(reflect.PointerTo(target))
}
if !ok {
return nil, true, fmt.Errorf("resource type %s not registered — must be announced via op.AnnounceResource", target)
}
rrt, isResourceReceiverType := rt.(ResourceReceiverType)
if !isResourceReceiverType {
return nil, true, fmt.Errorf("type %s registered as %T, not as ResourceReceiverType", target, rt)
}
v, err := rrt.Construct()(runtimeEnvironment, value)
if err != nil {
return nil, true, fmt.Errorf("construct %s from %T: %w", target, value, err)
}
return v, true, nil
}
// tryTargetConverter handles [Convert]'s step 7: target-side opt-in.
//
// Probe must be a *target or target-as-already-pointer, since converter methods conventionally sit on the pointer
// receiver. Reached after step 6, so registered-Resource canonicalization always wins at dispatch when env is
// available; step 7 fires for RuntimeEnvironment-les callers, non-Resource target types, and Resources whose registry
// entry is missing.
//
// Returns (nil, false, nil) when the target probe does not implement [TargetConverter] or declines to
// absorb `value`'s type via [TargetConverter.CanConvertFrom].
//
// Parameters:
// - `value`: the source value to project.
// - `target`: the desired target type.
//
// Returns:
// - `any`: the constructed value when applicable; nil otherwise.
// - `bool`: true when this step applied; false when the target does not opt into [TargetConverter] for
// `value`'s type.
// - `error`: non-nil when [TargetConverter.ConvertFrom] fails.
func tryTargetConverter(value any, target reflect.Type) (converted any, applied bool, err error) {
var probe any
if target.Kind() == reflect.Pointer {
probe = reflect.New(target.Elem()).Interface()
} else {
probe = reflect.New(target).Interface()
}
t, ok := probe.(TargetConverter)
if !ok || !t.CanConvertFrom(reflect.TypeOf(value)) {
return nil, false, nil
}
v, err := t.ConvertFrom(value)
return v, true, err
}
// tryTextUnmarshaler handles [Convert]'s step 8: a string source into a text-absorbing target.
//
// A value serialized through [encoding.TextMarshaler] (e.g. [time.Time] → RFC 3339) reloads as a plain string; a target
// — or its pointer — implementing [encoding.TextUnmarshaler] reconstructs itself from those bytes. Returns
// (nil, false, nil) when the source is not a string or the target does not absorb text.
//
// Parameters:
// - `value`: the source value; only a string applies.
// - `target`: the desired target type.
//
// Returns:
// - `any`: the unmarshaled value (target kind, or its pointer when the target is a pointer); nil otherwise.
// - `bool`: true when this step applied (regardless of error); false when it does not apply.
// - `error`: non-nil when [encoding.TextUnmarshaler.UnmarshalText] fails.
func tryTextUnmarshaler(value any, target reflect.Type) (unmarshaled any, applied bool, err error) {
text, isString := value.(string)
if !isString {
return nil, false, nil
}
concrete := target
if concrete.Kind() == reflect.Pointer {
concrete = concrete.Elem()
}
pointer := reflect.New(concrete)
unmarshaler, ok := pointer.Interface().(encoding.TextUnmarshaler)
if !ok {
return nil, false, nil
}
if err := unmarshaler.UnmarshalText([]byte(text)); err != nil {
return nil, true, fmt.Errorf("unmarshal text into %s: %w", target, err)
}
if target.Kind() == reflect.Pointer {
return pointer.Interface(), true, nil
}
return pointer.Elem().Interface(), true, nil
}
// tryHydrateStruct handles [Convert]'s step 9: a map source into a struct target.
//
// A struct serializes to an object and reloads as `map[string]any` — the codec drops the Go type. Given the target
// struct type (on restore, the source's produced type id; otherwise the consumer's slot), this rebuilds it: each
// exported field is filled from the map by its `json`/`yaml` tag (or field name), recursing every field value through
// [Convert] so nested structs, resources, slices, and maps compose. Returns (nil, false, nil) when the source is not a
// string-keyed map or the target (after one pointer deref) is not a struct.
//
// Parameters:
// - `runtimeEnvironment`: forwarded to the recursive [Convert] calls for env-sensitive field types (resources).
// - `elem`: the source value as a [reflect.Value] (pointer-dereferenced by [Convert] step 2).
// - `target`: the desired struct or *struct target type.
//
// Returns:
// - `any`: the populated struct (or its pointer when the target is a pointer); nil otherwise.
// - `bool`: true when this step applied (regardless of error); false when it does not apply.
// - `error`: non-nil when a field conversion fails.
func tryHydrateStruct(
runtimeEnvironment *RuntimeEnvironment, elem reflect.Value, target reflect.Type,
) (hydrated any, applied bool, err error) {
concrete := target
if concrete.Kind() == reflect.Pointer {
concrete = concrete.Elem()
}
if elem.Kind() != reflect.Map || elem.Type().Key().Kind() != reflect.String || concrete.Kind() != reflect.Struct {
return nil, false, nil
}
out := reflect.New(concrete).Elem()
for i := range concrete.NumField() {
field := concrete.Field(i)
if !field.IsExported() {
continue
}
fieldValue, ok := structFieldFromMap(elem, field)
if !ok {
continue
}
converted, err := Convert(runtimeEnvironment, fieldValue.Interface(), field.Type)
if err != nil {
return nil, true, fmt.Errorf("field %s: %w", field.Name, err)
}
convertedValue := reflect.ValueOf(converted)
if !convertedValue.IsValid() {
continue
}
out.Field(i).Set(convertedValue)
}
if target.Kind() == reflect.Pointer {
pointer := reflect.New(concrete)
pointer.Elem().Set(out)
return pointer.Interface(), true, nil
}
return out.Interface(), true, nil
}
// structFieldFromMap finds a struct field's value in a decoded object map, trying the field's `json` tag, `yaml` tag,
// then its Go name — whichever key the codec wrote.
//
// Parameters:
// - `elem`: the source map (string-keyed).
// - `field`: the struct field being filled.
//
// Returns:
// - `reflect.Value`: the matching map value; the zero Value when no candidate key is present.
// - `bool`: true when a candidate key matched.
func structFieldFromMap(elem reflect.Value, field reflect.StructField) (reflect.Value, bool) {
for _, key := range fieldKeys(field) {
if value := elem.MapIndex(reflect.ValueOf(key)); value.IsValid() {
return value, true
}
}
return reflect.Value{}, false
}
// fieldKeys returns the candidate object keys for a struct field: its `json` and `yaml` tag names (the part before the
// first comma) and its Go field name.
//
// Parameters:
// - `field`: the struct field.
//
// Returns:
// - `[]string`: the candidate keys, tag names first.
func fieldKeys(field reflect.StructField) []string {
keys := make([]string, 0, 3)
for _, tag := range []string{"json", "yaml"} {
if name, _, _ := strings.Cut(field.Tag.Get(tag), ","); name != "" && name != "-" {
keys = append(keys, name)
}
}
return append(keys, field.Name)
}
// typesAreInterconvertible reports whether a value of type `a` can fill a slot typed `b` or vice versa.
//
// Symmetrically tests both directions via any of the purely reflective paths of the [Convert] cascade.
//
// Used by [Subgraph.mergeBubbled] (the bubble-up parameter-consistency check), so the same-named-variable-across-
// differently-typed-slots case is not treated as a hard collision when a registered conversion bridges the two
// types. Slot-fill is *defined* as the conversion site; the plan-time check honors the same contract the dispatch-
// time cascade does.
//
// Paths probed (mirroring [Convert] steps 1, 2, 5, 6):
//
// 1. Identity — `a == b`.
// 2. Assignability — `a.AssignableTo(b)` or `b.AssignableTo(a)`.
// 3. Source-side opt-in — a zero-value of `a` implements [SourceConverter] and `CanConvertTo(b)` returns true,
// or symmetrically for `b → a`.
// 4. Target-side opt-in — a fresh probe of `b` implements [TargetConverter] and `CanConvertFrom(a)` returns true,
// or symmetrically for `b ← a`.
//
// Paths NOT probed: slice / map element-wise recursion (require a concrete value) and registered-Resource construction
// (requires a [RuntimeEnvironment] handle). Providers whose Resource types want plan-time type-compatibility honored
// for non-Resource sources opt in by implementing [TargetConverter] on the Resource type — the framework then wires
// both the plan-time consistency check (via this function) and the dispatch-time slot-fill (via [Convert] step 6)
// uniformly.
//
// Both [SourceConverter.CanConvertTo] and [TargetConverter.CanConvertFrom] are part of the cheap-probe contract:
// callers MUST be safe on a zero-value receiver (no field dereference), because this function calls them against nil
// pointers and zero structs to determine the existence of a conversion path without producing a value.
//
// Parameters:
// - `a`: one of the two types to test.
// - `b`: the other type.
//
// Returns:
// - `bool`: true if at least one of the probed paths reports interconvertibility in either direction.
func typesAreInterconvertible(a, b reflect.Type) bool {
if a == nil || b == nil {
return false
}
if a == b {
return true
}
if a.AssignableTo(b) || b.AssignableTo(a) {
return true
}
if sourceSideAdvertises(a, b) || sourceSideAdvertises(b, a) {
return true
}
if targetSideAdvertises(b, a) || targetSideAdvertises(a, b) {
return true
}
return false
}
// sourceSideAdvertises reports whether `source` opts into [SourceConverter] for `target`.
//
// Probes both the value form of `source` (when methods sit on a value receiver) and the pointer form (when methods sit
// on `*source`, the conventional Go choice). When the type implements [SourceConverter], [SourceConverter.CanConvertTo]
// is called on the probe to confirm `target` is an advertised destination.
//
// Pointer-type sources allocate a fresh zero-value via [reflect.New](source.Elem()) — never a nil pointer — so methods
// promoted through embedded structs (e.g., [op.ResourceBase] on a Resource type) can access the embedded field without
// dereferencing nil.
//
// Parameters:
// - `source`: the candidate source type whose [SourceConverter] opt-in is being probed.
// - `target`: the destination type the source must advertise convertibility to.
//
// Returns:
// - `bool`: true when a probe of `source` (or its pointer form) implements [SourceConverter] and reports
// `CanConvertTo(target)`; false otherwise.
func sourceSideAdvertises(source, target reflect.Type) bool {
if source.Implements(sourceConverterType) {
var probe any
if source.Kind() == reflect.Pointer {
probe = reflect.New(source.Elem()).Interface()
} else {
probe = reflect.Zero(source).Interface()
}
if c, ok := probe.(SourceConverter); ok {
return c.CanConvertTo(target)
}
}
if source.Kind() != reflect.Pointer {
ptrSource := reflect.PointerTo(source)
if ptrSource.Implements(sourceConverterType) {
probe := reflect.New(source).Interface()
if c, ok := probe.(SourceConverter); ok {
return c.CanConvertTo(target)
}
}
}
return false
}
// targetSideAdvertises reports whether `target` opts into [TargetConverter] for `source`.
//
// Mirrors [Convert] step 6's probe construction: when `target` is `*T`, the probe is `*T`; when `target` is a
// non-pointer `T`, the probe is `*T` (TargetConverter methods conventionally sit on the pointer receiver).
// [TargetConverter.CanConvertFrom] is then called on the probe to confirm `source` is an absorbable type.
//
// Parameters:
// - `source`: the candidate source type the target must advertise convertibility from.
// - `target`: the destination type whose [TargetConverter] opt-in is being probed.
//
// Returns:
// - `bool`: true when a fresh probe of `target` (or its pointer form) implements [TargetConverter] and
// reports `CanConvertFrom(source)`; false otherwise.
func targetSideAdvertises(source, target reflect.Type) bool {
var probeType reflect.Type
if target.Kind() == reflect.Pointer {
probeType = target
} else {
probeType = reflect.PointerTo(target)
}
if !probeType.Implements(targetConverterType) {
return false
}
var probe any
if target.Kind() == reflect.Pointer {
probe = reflect.New(target.Elem()).Interface()
} else {
probe = reflect.New(target).Interface()
}
t, ok := probe.(TargetConverter)
if !ok {
return false
}
return t.CanConvertFrom(source)
}