This repository was archived by the owner on Aug 13, 2026. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathplan.go
More file actions
850 lines (785 loc) · 23 KB
/
Copy pathplan.go
File metadata and controls
850 lines (785 loc) · 23 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
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
package plan
import (
"fmt"
"go/token"
"go/types"
"strings"
"unicode"
"github.com/mickamy/injector/internal/diag"
"github.com/mickamy/injector/internal/ir"
)
// Options carries CLI-level defaults that may be overridden per container by
// a //injector:container directive.
type Options struct {
// Must is the default value applied to containers whose directive does
// not explicitly specify must.
Must bool
}
// Plan is the resolved sequence of operations needed to construct a single
// container, plus metadata used by the emit layer.
//
// ReturnType is the *declared* return type of the constructor. The emitter
// always produces &<StructName>{...} as the return expression and relies on
// Go's assignability rules to fit ReturnType — so when ReturnType differs
// from *<StructName> (e.g. via inject:"returns" or //injector:container
// returns=...), *<StructName> must implement (or be identical to)
// ReturnType. This is also why RoleReturnsOnly fields contribute no Step:
// their type is recorded for the signature but the value is supplied by
// the container struct literal itself.
type Plan struct {
Container ir.Container
ConstructorName string
ReturnType types.Type
EmitMust bool
ReturnsError bool
// Inputs are constructor parameters in container-field order.
Inputs []Input
// Steps are resolution operations in execution order (deps first).
Steps []Step
// Outputs map RoleOut field names to the step that produces their value.
Outputs []Output
}
// StepKind classifies a step in a Plan.
type StepKind int
const (
// StepKindProvider invokes a provider function with the given args.
StepKindProvider StepKind = iota
// StepKindInput refers to a constructor input parameter.
StepKindInput
// StepKindEmbedField refers to an exported field of an inject:"embed"
// input, accessed as <input>.<FieldName>.
StepKindEmbedField
)
// Step is a single resolution operation.
type Step struct {
Kind StepKind
VarName string
OutType types.Type
// For StepKindProvider:
Provider *ir.Provider
ArgSteps []int
// For StepKindInput and StepKindEmbedField:
InputIndex int
// For StepKindEmbedField:
EmbedFieldName string
}
// Input is a constructor parameter (declared via inject:"arg" or
// inject:"embed").
type Input struct {
Name string
Type types.Type
}
// Output is a RoleOut field assignment: which step's value goes into which
// container field.
type Output struct {
FieldName string
StepIndex int
}
// Build resolves dependencies for one container against the given provider
// index and CLI defaults, returning a Plan that the emit layer can consume.
func Build(c ir.Container, idx *Index, opts Options) (Plan, []diag.Diag) {
var diags []diag.Diag
constructorName := constructorNameFor(c)
returnType, retDiag := resolveReturnType(c)
if retDiag != nil {
diags = append(diags, *retDiag)
}
emitMust := mergeMust(c.Directive.Must, opts.Must)
inputs, inDiags := buildInputs(c)
diags = append(diags, inDiags...)
overrides, ovDiags := buildOverrides(c, idx)
diags = append(diags, ovDiags...)
embeds, emDiags := buildEmbeds(c, inputs)
diags = append(diags, emDiags...)
r := &resolver{
idx: idx,
inputs: inputs,
overrides: overrides,
embeds: embeds,
stepByKey: map[string]int{},
active: map[string]bool{},
selfPkgPath: c.PkgPath,
selfFuncName: constructorName,
}
var outputs []Output
for _, f := range c.Fields {
switch f.Role {
case ir.RoleOut:
stepIdx, ds := r.resolveField(f)
diags = append(diags, ds...)
if stepIdx < 0 {
continue
}
outputs = append(outputs, Output{FieldName: f.Name, StepIndex: stepIdx})
case ir.RoleArg:
if f.Name == "_" {
continue
}
stepIdx, ds := r.resolveByType(f.Type, f.Pos, "field "+f.Name)
diags = append(diags, ds...)
if stepIdx < 0 {
continue
}
outputs = append(outputs, Output{FieldName: f.Name, StepIndex: stepIdx})
case ir.RoleOverride, ir.RoleReturnsOnly, ir.RoleEmbed:
// Handled in buildOverrides / resolveReturnType / buildEmbeds.
}
}
renameOutputSteps(r.steps, outputs)
returnsErr := false
for _, s := range r.steps {
if s.Kind == StepKindProvider && s.Provider != nil && s.Provider.ReturnsError {
returnsErr = true
break
}
}
return Plan{
Container: c,
ConstructorName: constructorName,
ReturnType: returnType,
EmitMust: emitMust,
ReturnsError: returnsErr,
Inputs: inputs,
Steps: r.steps,
Outputs: outputs,
}, diags
}
// resolver holds mutable state during resolution.
type resolver struct {
idx *Index
inputs []Input
overrides map[string]*ir.Provider // typeKey → provider
embeds map[string]embedSource // typeKey → embed source
steps []Step
stepByKey map[string]int
active map[string]bool
// selfPkgPath and selfFuncName identify this container's own
// generated constructor. They are used to filter the by-type lookup
// so a container whose `inject:"returns"` declares an interface that
// matches an unrelated provider does not see its own previously
// emitted constructor as a candidate (a self-loop that would also
// produce a spurious "multiple providers" error).
selfPkgPath string
selfFuncName string
}
// embedSource describes one exported field of an inject:"embed" input that
// is exposed as a resolution source.
type embedSource struct {
InputIndex int
FieldName string
FieldType types.Type
}
func (r *resolver) resolveField(f ir.Field) (int, []diag.Diag) {
if f.ProviderRef.HasRef() {
return r.resolveByRef(f.Type, f.ProviderRef.Raw, f.Pos)
}
return r.resolveByType(f.Type, f.Pos, "field "+f.Name)
}
// excludeSelfProvider drops the container's own previously generated
// constructor from the candidate list so a `inject:"returns"` field does
// not pick itself up via type lookup. Callers that name a provider
// explicitly via inject:"with=..." are not affected.
//
// The common case is that the self-provider is not in the candidate
// list at all (most fields request types unrelated to the container's
// own return type), so the function returns the original slice without
// allocating when there is nothing to exclude.
func (r *resolver) excludeSelfProvider(candidates []*ir.Provider) []*ir.Provider {
if r.selfFuncName == "" {
return candidates
}
selfIdx := -1
for i, c := range candidates {
if c.PkgPath == r.selfPkgPath && c.FuncName == r.selfFuncName {
selfIdx = i
break
}
}
if selfIdx < 0 {
return candidates
}
// Boundary cases — the self-provider sits at one end of the slice,
// so a sub-slice is enough and no allocation is needed. This covers
// the very common case of a single matching candidate.
if selfIdx == 0 {
return candidates[1:]
}
if selfIdx == len(candidates)-1 {
return candidates[:selfIdx]
}
kept := make([]*ir.Provider, 0, len(candidates)-1)
kept = append(kept, candidates[:selfIdx]...)
kept = append(kept, candidates[selfIdx+1:]...)
return kept
}
func (r *resolver) resolveByType(want types.Type, pos token.Position, parent string) (int, []diag.Diag) {
tk := TypeKey(want)
for i, in := range r.inputs {
if TypeKey(in.Type) == tk {
return r.useInput(i), nil
}
}
if p, ok := r.overrides[tk]; ok {
return r.resolveProvider(p, pos)
}
if es, ok := r.embeds[tk]; ok {
return r.useEmbed(es), nil
}
candidates := r.idx.LookupByType(want)
candidates = r.excludeSelfProvider(candidates)
if len(candidates) == 0 {
return -1, []diag.Diag{
diag.Errorf(pos, "no provider for %s (required by %s)", TypeString(want), parent),
}
}
if len(candidates) > 1 {
return -1, []diag.Diag{
diag.Errorf(pos, "multiple providers for %s (required by %s)", TypeString(want), parent).
WithHints(FormatCandidates(candidates)...),
}
}
return r.resolveProvider(candidates[0], pos)
}
func (r *resolver) resolveByRef(want types.Type, ref string, pos token.Position) (int, []diag.Diag) {
candidates := r.idx.LookupByRef(ref)
if len(candidates) == 0 {
return -1, []diag.Diag{
diag.Errorf(pos, "no provider matches %q", ref),
}
}
var matched []*ir.Provider
for _, p := range candidates {
if p.Result != nil && types.Identical(p.Result, want) {
matched = append(matched, p)
}
}
if len(matched) == 0 {
return -1, []diag.Diag{
diag.Errorf(pos, "provider %q does not produce %s", ref, TypeString(want)).
WithHints(FormatCandidates(candidates)...),
}
}
if len(matched) > 1 {
return -1, []diag.Diag{
diag.Errorf(pos, "reference %q is ambiguous", ref).
WithHints(FormatCandidates(matched)...),
}
}
return r.resolveProvider(matched[0], pos)
}
func (r *resolver) useInput(idx int) int {
key := fmt.Sprintf("input:%d", idx)
if id, ok := r.stepByKey[key]; ok {
return id
}
in := r.inputs[idx]
r.steps = append(r.steps, Step{
Kind: StepKindInput,
VarName: in.Name,
OutType: in.Type,
InputIndex: idx,
})
id := len(r.steps) - 1
r.stepByKey[key] = id
return id
}
func (r *resolver) useEmbed(es embedSource) int {
key := fmt.Sprintf("embed:%d:%s", es.InputIndex, es.FieldName)
if id, ok := r.stepByKey[key]; ok {
return id
}
r.steps = append(r.steps, Step{
Kind: StepKindEmbedField,
VarName: varNameForEmbed(es, r.steps),
OutType: es.FieldType,
InputIndex: es.InputIndex,
EmbedFieldName: es.FieldName,
})
id := len(r.steps) - 1
r.stepByKey[key] = id
return id
}
func (r *resolver) resolveProvider(p *ir.Provider, pos token.Position) (int, []diag.Diag) {
key := "provider:" + ProviderName(p)
if id, ok := r.stepByKey[key]; ok {
return id, nil
}
if r.active[key] {
return -1, []diag.Diag{
diag.Errorf(pos, "circular dependency at %s", ProviderName(p)),
}
}
r.active[key] = true
defer delete(r.active, key)
var argIDs []int
var diags []diag.Diag
for _, pt := range p.Params {
argID, ds := r.resolveByType(pt, pos, ProviderName(p))
diags = append(diags, ds...)
if argID < 0 {
return -1, diags
}
argIDs = append(argIDs, argID)
}
r.steps = append(r.steps, Step{
Kind: StepKindProvider,
VarName: varNameForProvider(p, r.steps),
OutType: p.Result,
Provider: p,
ArgSteps: argIDs,
})
id := len(r.steps) - 1
r.stepByKey[key] = id
return id, diags
}
func constructorNameFor(c ir.Container) string {
if c.Directive.Name != "" {
return c.Directive.Name
}
return "New" + upperFirst(c.StructName)
}
func resolveReturnType(c ir.Container) (types.Type, *diag.Diag) {
var taggedReturns *ir.Field
for i := range c.Fields {
f := &c.Fields[i]
if !f.IsReturns {
continue
}
if taggedReturns != nil {
d := diag.Errorf(f.Pos,
`multiple inject:"returns" fields (also at %s)`, taggedReturns.Pos)
return nil, &d
}
taggedReturns = f
}
if c.Directive.ReturnType != nil {
if taggedReturns != nil {
d := diag.Errorf(c.Pos,
`directive returns= conflicts with inject:"returns" on field %s`,
taggedReturns.Name)
return nil, &d
}
return c.Directive.ReturnType, nil
}
if taggedReturns != nil {
return taggedReturns.Type, nil
}
if c.StructType != nil {
return types.NewPointer(c.StructType), nil
}
return nil, nil
}
func mergeMust(d ir.MustMode, cliMust bool) bool {
switch d {
case ir.MustOn:
return true
case ir.MustOff:
return false
case ir.MustUnset:
fallthrough
default:
return cliMust
}
}
func buildInputs(c ir.Container) ([]Input, []diag.Diag) {
var inputs []Input
var diags []diag.Diag
seenTypes := map[string]token.Position{}
seenNames := map[string]token.Position{}
for _, f := range c.Fields {
if f.Role != ir.RoleArg && f.Role != ir.RoleEmbed {
continue
}
name := f.ArgName
if name == "" {
name = deriveInputName(f.Type)
}
tk := TypeKey(f.Type)
if prev, ok := seenTypes[tk]; ok {
diags = append(diags, diag.Errorf(f.Pos,
"duplicate input type %s (first declared at %s)", TypeString(f.Type), prev))
continue
}
if prev, ok := seenNames[name]; ok {
diags = append(diags, diag.Errorf(f.Pos,
`duplicate input name %q (first declared at %s); use inject:"arg=..." to disambiguate`,
name, prev))
continue
}
seenTypes[tk] = f.Pos
seenNames[name] = f.Pos
inputs = append(inputs, Input{Name: name, Type: f.Type})
}
return inputs, diags
}
// buildEmbeds walks the container's RoleEmbed fields and returns a TypeKey
// → embedSource map of exported sub-fields available as resolution sources.
// Each embed input must be a struct (or pointer to a struct); other shapes
// produce diagnostics. Promoted fields reached through anonymous embeds
// are also exposed; shallower fields shadow deeper ones inside a single
// embed (matching Go's selector semantics), while equal-depth duplicates
// within one embed and same-type sources across two embeds are both
// reported as errors.
func buildEmbeds(c ir.Container, inputs []Input) (map[string]embedSource, []diag.Diag) {
out := map[string]embedSource{}
var diags []diag.Diag
indexByType := make(map[string]int, len(inputs))
for i, in := range inputs {
indexByType[TypeKey(in.Type)] = i
}
for _, f := range c.Fields {
if f.Role != ir.RoleEmbed {
continue
}
idx, ok := indexByType[TypeKey(f.Type)]
if !ok {
// The corresponding input was rejected (duplicate type/name).
continue
}
st, ok := structOf(f.Type)
if !ok {
diags = append(diags, diag.Errorf(f.Pos,
`inject:"embed" requires a struct or pointer to struct, got %s`,
TypeString(f.Type)))
continue
}
sources, srcDiags := embedSourcesOf(f.Type, st, idx, f.Pos, inputs)
diags = append(diags, srcDiags...)
for tk, src := range sources {
if existing, dup := out[tk]; dup {
diags = append(diags, diag.Errorf(f.Pos,
"embed: multiple sources for %s (also %s.%s)",
TypeString(src.FieldType),
inputs[existing.InputIndex].Name, existing.FieldName))
continue
}
out[tk] = src
}
}
return out, diags
}
// embedSourcesOf walks a single embed input breadth-first, recording each
// exported field (direct or promoted through anonymous embeds) keyed by
// TypeKey. The traversal mirrors Go's selector promotion: a shallower
// field wins over deeper ones of the same type, while same-depth
// duplicates are reported as ambiguity diagnostics and skipped.
func embedSourcesOf(
rootType types.Type,
rootSt *types.Struct,
inputIdx int,
fPos token.Position,
inputs []Input,
) (map[string]embedSource, []diag.Diag) {
out := map[string]embedSource{}
claimed := map[string]bool{}
var diags []diag.Diag
type frame struct {
st *types.Struct
prefix string
}
visited := map[string]bool{TypeKey(rootType): true}
level := []frame{{rootSt, ""}}
for len(level) > 0 {
var next []frame
levelCands := map[string][]embedSource{}
for _, fr := range level {
for sf := range fr.st.Fields() {
if !sf.Exported() {
continue
}
name := sf.Name()
if fr.prefix != "" {
name = fr.prefix + "." + name
}
tk := TypeKey(sf.Type())
if !claimed[tk] {
levelCands[tk] = append(levelCands[tk], embedSource{
InputIndex: inputIdx,
FieldName: name,
FieldType: sf.Type(),
})
}
if sf.Anonymous() && !visited[tk] {
visited[tk] = true
if subst, ok := structOf(sf.Type()); ok {
next = append(next, frame{subst, name})
}
}
}
}
for tk, cands := range levelCands {
if len(cands) > 1 {
names := make([]string, 0, len(cands))
for _, c := range cands {
names = append(names, inputs[c.InputIndex].Name+"."+c.FieldName)
}
diags = append(diags, diag.Errorf(fPos,
"embed: ambiguous source for %s at the same depth (%s)",
TypeString(cands[0].FieldType), strings.Join(names, ", ")))
claimed[tk] = true
continue
}
out[tk] = cands[0]
claimed[tk] = true
}
level = next
}
return out, diags
}
// structOf returns the underlying *types.Struct of t (unwrapping a leading
// pointer and resolving type aliases) and reports whether t had a struct
// shape at all.
func structOf(t types.Type) (*types.Struct, bool) {
t = types.Unalias(t)
if ptr, ok := t.(*types.Pointer); ok {
t = types.Unalias(ptr.Elem())
}
if named, ok := t.(*types.Named); ok {
if st, ok := named.Underlying().(*types.Struct); ok {
return st, true
}
return nil, false
}
if st, ok := t.(*types.Struct); ok {
return st, true
}
return nil, false
}
// buildOverrides walks fields whose inject tag names a specific provider
// (`inject:"with=..."`) and indexes them by their declared type. The
// resolver consults this map ahead of provider-by-type lookup, so that any
// transitive dependency inside the same container resolves to the same
// provider the user picked for the field.
//
// Both blank (RoleOverride) and non-blank (RoleOut with a ref) fields
// contribute. The non-blank case lets a stored field double as a
// container-wide override; users no longer need a redundant blank twin to
// disambiguate sibling resolutions.
func buildOverrides(c ir.Container, idx *Index) (map[string]*ir.Provider, []diag.Diag) {
out := map[string]*ir.Provider{}
posByType := map[string]token.Position{}
var diags []diag.Diag
for _, f := range c.Fields {
if f.Role != ir.RoleOverride && f.Role != ir.RoleOut {
continue
}
if !f.ProviderRef.HasRef() {
continue
}
candidates := idx.LookupByRef(f.ProviderRef.Raw)
if len(candidates) == 0 {
diags = append(diags, diag.Errorf(f.Pos,
"no provider matches %q", f.ProviderRef.Raw))
continue
}
var matched []*ir.Provider
for _, p := range candidates {
if p.Result != nil && types.Identical(p.Result, f.Type) {
matched = append(matched, p)
}
}
switch len(matched) {
case 0:
diags = append(diags, diag.Errorf(f.Pos,
"provider %q does not produce %s", f.ProviderRef.Raw, TypeString(f.Type)).
WithHints(FormatCandidates(candidates)...))
case 1:
tk := TypeKey(f.Type)
if existing, dup := out[tk]; dup && existing != matched[0] {
diags = append(diags, diag.Errorf(f.Pos,
"conflicting providers selected for %s: %s vs %s (also at %s)",
TypeString(f.Type),
ProviderName(existing), ProviderName(matched[0]),
posByType[tk]))
continue
}
out[tk] = matched[0]
posByType[tk] = f.Pos
default:
diags = append(diags, diag.Errorf(f.Pos,
"reference %q is ambiguous", f.ProviderRef.Raw).
WithHints(FormatCandidates(matched)...))
}
}
return out, diags
}
func deriveInputName(t types.Type) string {
if t == nil {
return "arg"
}
// Resolve Go 1.22+ type aliases (`type Client = valkey.Client`) so
// the alias's own name flows through instead of falling out to the
// "arg" sentinel.
t = types.Unalias(t)
if ptr, ok := t.(*types.Pointer); ok {
return deriveInputName(ptr.Elem())
}
if named, ok := t.(*types.Named); ok {
if obj := named.Obj(); obj != nil && obj.Name() != "" {
return lowerFirst(obj.Name())
}
}
return "arg"
}
// renameOutputSteps renames non-input steps that produce a container
// output to lowerFirst(field name). This puts the field's own identifier
// at the call site (`tx := tx.New(...)` for a `Tx` field, suffixed if it
// would shadow an existing step name). Steps that are not bound to any
// output keep the type-derived name picked at resolution time.
//
// Renaming runs in two passes so that an output whose desired base name
// is currently held by another step that is also about to be renamed can
// claim the now-vacated name without unnecessarily suffixing. Without
// this, a hypothetical swap (step A holds "foo" and wants "db", step B
// holds "db" and wants "foo") would land on `foo2`/`db` instead of the
// clean `foo`/`db`.
func renameOutputSteps(steps []Step, outputs []Output) {
used := make(map[string]bool, len(steps))
for _, st := range steps {
used[st.VarName] = true
}
type pendingRename struct {
stepIdx int
base string
}
var renames []pendingRename
// A shared step (bound to more than one container field, e.g. when two
// fields request the same dependency) appears multiple times in
// outputs. Decide the rename for each step at the first valid output
// and skip any later occurrences so we don't queue the same step
// twice, which would leak the dropped candidate name into `used` and
// force unrelated steps onto a suffix.
decided := make(map[int]bool, len(outputs))
for _, o := range outputs {
if o.StepIndex < 0 || o.StepIndex >= len(steps) {
continue
}
if decided[o.StepIndex] {
continue
}
s := &steps[o.StepIndex]
if s.Kind == StepKindInput {
decided[o.StepIndex] = true
continue
}
base := lowerFirst(o.FieldName)
if base == "" {
continue
}
if base == s.VarName {
// Existing name already lines up with this field; no rename
// needed even if later outputs would have picked a different
// base.
decided[o.StepIndex] = true
continue
}
delete(used, s.VarName)
renames = append(renames, pendingRename{stepIdx: o.StepIndex, base: base})
decided[o.StepIndex] = true
}
for _, r := range renames {
pick := r.base
if used[pick] {
for i := 2; ; i++ {
try := fmt.Sprintf("%s%d", r.base, i)
if !used[try] {
pick = try
break
}
}
}
steps[r.stepIdx].VarName = pick
used[pick] = true
}
}
func varNameForEmbed(es embedSource, existing []Step) string {
// FieldName may be a dotted selector (e.g. "CommonInfra.DB") when the
// source comes from a promoted field; only the leaf segment is a valid
// identifier base.
leaf := es.FieldName
if i := strings.LastIndex(leaf, "."); i >= 0 {
leaf = leaf[i+1:]
}
base := lowerFirst(leaf)
if base == "" {
base = "v"
}
used := map[string]struct{}{}
for _, s := range existing {
used[s.VarName] = struct{}{}
}
if _, ok := used[base]; !ok {
return base
}
for i := 2; ; i++ {
try := fmt.Sprintf("%s%d", base, i)
if _, ok := used[try]; !ok {
return try
}
}
}
func varNameForProvider(p *ir.Provider, existing []Step) string {
// Name the variable after what the call produces, not after the
// constructor function. `db.Open(...) *sql.DB` reads more naturally
// as `db := db.Open(...)` than `open := db.Open(...)`, and
// container-field-bound steps later get renamed once more to the
// destination field name.
base := deriveInputName(p.Result)
if base == "arg" {
// Anonymous or unnamed result type — fall back to the function
// name for a less generic label than "arg".
base = p.FuncName
if strings.HasPrefix(base, "New") && len(base) > 3 {
base = base[3:]
}
base = lowerFirst(base)
}
if base == "" {
base = "v"
}
used := map[string]struct{}{}
for _, s := range existing {
used[s.VarName] = struct{}{}
}
if _, ok := used[base]; !ok {
return base
}
for i := 2; ; i++ {
try := fmt.Sprintf("%s%d", base, i)
if _, ok := used[try]; !ok {
return try
}
}
}
func upperFirst(s string) string {
if s == "" {
return ""
}
r := []rune(s)
r[0] = unicode.ToUpper(r[0])
return string(r)
}
// lowerFirst lowercases the leading run of uppercase letters of s, following
// the Go convention that "URL" → "url" and "URLPath" → "urlPath" (the last
// cap of a leading run is preserved when followed by a lowercase letter).
func lowerFirst(s string) string {
if s == "" {
return ""
}
runes := []rune(s)
n := len(runes)
i := 0
for i < n && unicode.IsUpper(runes[i]) {
i++
}
if i == 0 {
return s
}
if i < n && i > 1 {
i--
}
for j := range i {
runes[j] = unicode.ToLower(runes[j])
}
return string(runes)
}