-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathschema.go
More file actions
1754 lines (1516 loc) · 51.4 KB
/
schema.go
File metadata and controls
1754 lines (1516 loc) · 51.4 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
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
// SPDX-FileCopyrightText: Copyright 2015-2025 go-swagger maintainers
// SPDX-License-Identifier: Apache-2.0
package codescan
import (
"encoding/json"
"fmt"
"go/ast"
"go/importer"
"go/token"
"go/types"
"log"
"reflect"
"strconv"
"strings"
"golang.org/x/tools/go/ast/astutil"
"golang.org/x/tools/go/packages"
"github.com/go-openapi/spec"
)
func addExtension(ve *spec.VendorExtensible, key string, value any, skip bool) {
if skip {
return
}
ve.AddExtension(key, value)
}
type schemaTypable struct {
schema *spec.Schema
level int
skipExt bool
}
func (st schemaTypable) In() string { return "body" }
func (st schemaTypable) Typed(tpe, format string) {
st.schema.Typed(tpe, format)
}
func (st schemaTypable) SetRef(ref spec.Ref) {
st.schema.Ref = ref
}
func (st schemaTypable) Schema() *spec.Schema {
return st.schema
}
func (st schemaTypable) Items() swaggerTypable { //nolint:ireturn // polymorphic by design
if st.schema.Items == nil {
st.schema.Items = new(spec.SchemaOrArray)
}
if st.schema.Items.Schema == nil {
st.schema.Items.Schema = new(spec.Schema)
}
st.schema.Typed("array", "")
return schemaTypable{st.schema.Items.Schema, st.level + 1, st.skipExt}
}
func (st schemaTypable) AdditionalProperties() swaggerTypable { //nolint:ireturn // polymorphic by design
if st.schema.AdditionalProperties == nil {
st.schema.AdditionalProperties = new(spec.SchemaOrBool)
}
if st.schema.AdditionalProperties.Schema == nil {
st.schema.AdditionalProperties.Schema = new(spec.Schema)
}
st.schema.Typed("object", "")
return schemaTypable{st.schema.AdditionalProperties.Schema, st.level + 1, st.skipExt}
}
func (st schemaTypable) Level() int { return st.level }
func (st schemaTypable) AddExtension(key string, value any) {
addExtension(&st.schema.VendorExtensible, key, value, st.skipExt)
}
func (st schemaTypable) WithEnum(values ...any) {
st.schema.WithEnum(values...)
}
func (st schemaTypable) WithEnumDescription(desc string) {
if desc == "" {
return
}
st.AddExtension(extEnumDesc, desc)
}
type schemaValidations struct {
current *spec.Schema
}
func (sv schemaValidations) SetMaximum(val float64, exclusive bool) {
sv.current.Maximum = &val
sv.current.ExclusiveMaximum = exclusive
}
func (sv schemaValidations) SetMinimum(val float64, exclusive bool) {
sv.current.Minimum = &val
sv.current.ExclusiveMinimum = exclusive
}
func (sv schemaValidations) SetMultipleOf(val float64) { sv.current.MultipleOf = &val }
func (sv schemaValidations) SetMinItems(val int64) { sv.current.MinItems = &val }
func (sv schemaValidations) SetMaxItems(val int64) { sv.current.MaxItems = &val }
func (sv schemaValidations) SetMinLength(val int64) { sv.current.MinLength = &val }
func (sv schemaValidations) SetMaxLength(val int64) { sv.current.MaxLength = &val }
func (sv schemaValidations) SetPattern(val string) { sv.current.Pattern = val }
func (sv schemaValidations) SetUnique(val bool) { sv.current.UniqueItems = val }
func (sv schemaValidations) SetDefault(val any) { sv.current.Default = val }
func (sv schemaValidations) SetExample(val any) { sv.current.Example = val }
func (sv schemaValidations) SetEnum(val string) {
var typ string
if len(sv.current.Type) > 0 {
typ = sv.current.Type[0]
}
sv.current.Enum = parseEnum(val, &spec.SimpleSchema{Format: sv.current.Format, Type: typ})
}
type schemaBuilder struct {
ctx *scanCtx
decl *entityDecl
GoName string
Name string
annotated bool
discovered []*entityDecl
postDecls []*entityDecl
}
func (s *schemaBuilder) Build(definitions map[string]spec.Schema) error {
s.inferNames()
schema := definitions[s.Name]
err := s.buildFromDecl(s.decl, &schema)
if err != nil {
return err
}
definitions[s.Name] = schema
return nil
}
func (s *schemaBuilder) inferNames() {
if s.GoName != "" {
return
}
goName := s.decl.Ident.Name
name := goName
defer func() {
s.GoName = goName
s.Name = name
}()
if s.decl.Comments == nil {
return
}
DECLS:
for _, cmt := range s.decl.Comments.List {
for ln := range strings.SplitSeq(cmt.Text, "\n") {
matches := rxModelOverride.FindStringSubmatch(ln)
if len(matches) > 0 {
s.annotated = true
}
if len(matches) > 1 && len(matches[1]) > 0 {
name = matches[1]
break DECLS
}
}
}
}
func (s *schemaBuilder) buildFromDecl(_ *entityDecl, schema *spec.Schema) error {
// analyze doc comment for the model
// This includes parsing "example", "default" and other validation at the top-level declaration.
sp := s.createParser("", schema, schema, nil)
sp.setTitle = func(lines []string) { schema.Title = joinDropLast(lines) }
sp.setDescription = func(lines []string) {
schema.Description = joinDropLast(lines)
enumDesc := getEnumDesc(schema.Extensions)
if enumDesc != "" {
schema.Description += "\n" + enumDesc
}
}
if err := sp.Parse(s.decl.Comments); err != nil {
return err
}
// if the type is marked to ignore, just return
if sp.ignored {
return nil
}
defer func() {
if schema.Ref.String() == "" {
// unless this is a $ref, we add traceability of the origin of this schema in source
if s.Name != s.GoName {
addExtension(&schema.VendorExtensible, "x-go-name", s.GoName, s.ctx.opts.SkipExtensions)
}
addExtension(&schema.VendorExtensible, "x-go-package", s.decl.Obj().Pkg().Path(), s.ctx.opts.SkipExtensions)
}
}()
switch tpe := s.decl.ObjType().(type) {
// TODO(fredbi): we may safely remove all the cases here that are not Named or Alias
case *types.Basic:
debugLogf(s.ctx.debug, "basic: %v", tpe.Name())
return nil
case *types.Struct:
return s.buildFromStruct(s.decl, tpe, schema, make(map[string]string))
case *types.Interface:
return s.buildFromInterface(s.decl, tpe, schema, make(map[string]string))
case *types.Array:
debugLogf(s.ctx.debug, "array: %v -> %v", s.decl.Ident.Name, tpe.Elem().String())
return nil
case *types.Slice:
debugLogf(s.ctx.debug, "slice: %v -> %v", s.decl.Ident.Name, tpe.Elem().String())
return nil
case *types.Map:
debugLogf(s.ctx.debug, "map: %v -> [%v]%v", s.decl.Ident.Name, tpe.Key().String(), tpe.Elem().String())
return nil
case *types.Named:
debugLogf(s.ctx.debug, "named: %v", tpe)
return s.buildDeclNamed(tpe, schema)
case *types.Alias:
debugLogf(s.ctx.debug, "alias: %v -> %v", tpe, tpe.Rhs())
tgt := schemaTypable{schema, 0, s.ctx.opts.SkipExtensions}
return s.buildDeclAlias(tpe, tgt)
case *types.TypeParam:
log.Printf("WARNING: generic type parameters are not supported yet %[1]v (%[1]T). Skipped", tpe)
return nil
case *types.Chan:
log.Printf("WARNING: channels are not supported %[1]v (%[1]T). Skipped", tpe)
return nil
case *types.Signature:
log.Printf("WARNING: functions are not supported %[1]v (%[1]T). Skipped", tpe)
return nil
default:
log.Printf("WARNING: missing parser for type %T, skipping model: %s\n", tpe, s.Name)
return nil
}
}
func (s *schemaBuilder) buildDeclNamed(tpe *types.Named, schema *spec.Schema) error {
if unsupportedBuiltin(tpe) {
log.Printf("WARNING: skipped unsupported builtin type: %v", tpe)
return nil
}
o := tpe.Obj()
mustNotBeABuiltinType(o)
debugLogf(s.ctx.debug, "got the named type object: %s.%s | isAlias: %t | exported: %t", o.Pkg().Path(), o.Name(), o.IsAlias(), o.Exported())
if isStdTime(o) {
schema.Typed("string", "date-time")
return nil
}
ps := schemaTypable{schema, 0, s.ctx.opts.SkipExtensions}
ti := s.decl.Pkg.TypesInfo.Types[s.decl.Spec.Type]
if !ti.IsType() {
return fmt.Errorf("declaration is not a type: %v: %w", o, ErrCodeScan)
}
return s.buildFromType(ti.Type, ps)
}
// buildFromTextMarshal renders a type that marshals as text as a string.
func (s *schemaBuilder) buildFromTextMarshal(tpe types.Type, tgt swaggerTypable) error {
if typePtr, ok := tpe.(*types.Pointer); ok {
return s.buildFromTextMarshal(typePtr.Elem(), tgt)
}
typeNamed, ok := tpe.(*types.Named)
if !ok {
tgt.Typed("string", "")
return nil
}
tio := typeNamed.Obj()
if isStdError(tio) {
tgt.AddExtension("x-go-type", tio.Name())
return swaggerSchemaForType(tio.Name(), tgt)
}
debugLogf(s.ctx.debug, "named refined type %s.%s", tio.Pkg().Path(), tio.Name())
pkg, found := s.ctx.PkgForType(tpe)
if strings.ToLower(tio.Name()) == "uuid" {
tgt.Typed("string", "uuid")
return nil
}
if !found {
// this must be a builtin
debugLogf(s.ctx.debug, "skipping because package is nil: %v", tpe)
return nil
}
if isStdTime(tio) {
tgt.Typed("string", "date-time")
return nil
}
if isStdJSONRawMessage(tio) {
tgt.Typed("object", "") // TODO: this should actually be any type
return nil
}
cmt, hasComments := s.ctx.FindComments(pkg, tio.Name())
if !hasComments {
cmt = new(ast.CommentGroup)
}
if sfnm, isf := strfmtName(cmt); isf {
tgt.Typed("string", sfnm)
return nil
}
tgt.Typed("string", "")
tgt.AddExtension("x-go-type", tio.Pkg().Path()+"."+tio.Name())
return nil
}
func (s *schemaBuilder) buildFromType(tpe types.Type, tgt swaggerTypable) error {
// check if the type implements encoding.TextMarshaler interface
// if so, the type is rendered as a string.
debugLogf(s.ctx.debug, "schema buildFromType %v (%T)", tpe, tpe)
if isTextMarshaler(tpe) {
return s.buildFromTextMarshal(tpe, tgt)
}
switch titpe := tpe.(type) {
case *types.Basic:
if unsupportedBuiltinType(titpe) {
log.Printf("WARNING: skipped unsupported builtin type: %v", tpe)
return nil
}
return swaggerSchemaForType(titpe.String(), tgt)
case *types.Pointer:
return s.buildFromType(titpe.Elem(), tgt)
case *types.Struct:
return s.buildFromStruct(s.decl, titpe, tgt.Schema(), make(map[string]string))
case *types.Interface:
return s.buildFromInterface(s.decl, titpe, tgt.Schema(), make(map[string]string))
case *types.Slice:
// anonymous slice
return s.buildFromType(titpe.Elem(), tgt.Items())
case *types.Array:
// anonymous array
return s.buildFromType(titpe.Elem(), tgt.Items())
case *types.Map:
return s.buildFromMap(titpe, tgt)
case *types.Named:
// a named type, e.g. type X struct {}
return s.buildNamedType(titpe, tgt)
case *types.Alias:
// a named alias, e.g. type X = {RHS type}.
debugLogf(s.ctx.debug, "alias(schema.buildFromType): got alias %v to %v", titpe, titpe.Rhs())
return s.buildAlias(titpe, tgt)
case *types.TypeParam:
log.Printf("WARNING: generic type parameters are not supported yet %[1]v (%[1]T). Skipped", titpe)
return nil
case *types.Chan:
log.Printf("WARNING: channels are not supported %[1]v (%[1]T). Skipped", tpe)
return nil
case *types.Signature:
log.Printf("WARNING: functions are not supported %[1]v (%[1]T). Skipped", tpe)
return nil
default:
panic(fmt.Errorf("ERROR: can't determine refined type %[1]v (%[1]T): %w", titpe, errInternal))
}
}
func (s *schemaBuilder) buildNamedType(titpe *types.Named, tgt swaggerTypable) error {
tio := titpe.Obj()
if unsupportedBuiltin(titpe) {
log.Printf("WARNING: skipped unsupported builtin type: %v", titpe)
return nil
}
if isAny(tio) {
// e.g type X any or type X interface{}
_ = tgt.Schema()
return nil
}
// special case of the "error" interface.
if isStdError(tio) {
tgt.AddExtension("x-go-type", tio.Name())
return swaggerSchemaForType(tio.Name(), tgt)
}
// special case of the "time.Time" type
if isStdTime(tio) {
tgt.Typed("string", "date-time")
return nil
}
// special case of the "json.RawMessage" type
if isStdJSONRawMessage(tio) {
tgt.Typed("object", "") // TODO: this should actually be any type
return nil
}
pkg, found := s.ctx.PkgForType(titpe)
debugLogf(s.ctx.debug, "named refined type %s.%s", pkg, tio.Name())
if !found {
// this must be a builtin
//
// This could happen for example when using unsupported types such as complex64, complex128, uintptr,
// or type constraints such as comparable.
debugLogf(s.ctx.debug, "skipping because package is nil (builtin type): %v", tio)
return nil
}
cmt, hasComments := s.ctx.FindComments(pkg, tio.Name())
if !hasComments {
cmt = new(ast.CommentGroup)
}
if tn, ok := typeName(cmt); ok {
if err := swaggerSchemaForType(tn, tgt); err == nil {
return nil
}
// For unsupported swagger:type values (e.g., "array"), fall through
// to underlying type resolution so the full schema (including items
// for slices) is properly built. Build directly from the underlying
// type to bypass the named-type $ref creation.
return s.buildFromType(titpe.Underlying(), tgt)
}
if s.decl.Spec.Assign.IsValid() {
debugLogf(s.ctx.debug, "found assignment: %s.%s", tio.Pkg().Path(), tio.Name())
return s.buildFromType(titpe.Underlying(), tgt)
}
if titpe.TypeArgs() != nil && titpe.TypeArgs().Len() > 0 {
return s.buildFromType(titpe.Underlying(), tgt)
}
// invariant: the Underlying cannot be an alias or named type
switch utitpe := titpe.Underlying().(type) {
case *types.Struct:
return s.buildNamedStruct(tio, cmt, tgt)
case *types.Interface:
debugLogf(s.ctx.debug, "found interface: %s.%s", tio.Pkg().Path(), tio.Name())
decl, found := s.ctx.FindModel(tio.Pkg().Path(), tio.Name())
if !found {
return fmt.Errorf("can't find source file for type: %v: %w", utitpe, ErrCodeScan)
}
return s.makeRef(decl, tgt)
case *types.Basic:
return s.buildNamedBasic(tio, pkg, cmt, utitpe, tgt)
case *types.Array:
return s.buildNamedArray(tio, cmt, utitpe.Elem(), tgt)
case *types.Slice:
return s.buildNamedSlice(tio, cmt, utitpe.Elem(), tgt)
case *types.Map:
debugLogf(s.ctx.debug, "found map type: %s.%s", tio.Pkg().Path(), tio.Name())
if decl, ok := s.ctx.FindModel(tio.Pkg().Path(), tio.Name()); ok {
return s.makeRef(decl, tgt)
}
return nil
case *types.TypeParam:
log.Printf("WARNING: generic type parameters are not supported yet %[1]v (%[1]T). Skipped", utitpe)
return nil
case *types.Chan:
log.Printf("WARNING: channels are not supported %[1]v (%[1]T). Skipped", utitpe)
return nil
case *types.Signature:
log.Printf("WARNING: functions are not supported %[1]v (%[1]T). Skipped", utitpe)
return nil
default:
log.Printf(
"WARNING: can't figure out object type for named type (%T): %v [alias: %t]",
titpe.Underlying(), titpe.Underlying(), titpe.Obj().IsAlias(),
)
return nil
}
}
func (s *schemaBuilder) buildNamedBasic(tio *types.TypeName, pkg *packages.Package, cmt *ast.CommentGroup, utitpe *types.Basic, tgt swaggerTypable) error {
if unsupportedBuiltinType(utitpe) {
log.Printf("WARNING: skipped unsupported builtin type: %v", utitpe)
return nil
}
debugLogf(s.ctx.debug, "found primitive type: %s.%s", tio.Pkg().Path(), tio.Name())
if sfnm, isf := strfmtName(cmt); isf {
tgt.Typed("string", sfnm)
return nil
}
if enumName, ok := enumName(cmt); ok {
enumValues, enumDesces, _ := s.ctx.FindEnumValues(pkg, enumName)
if len(enumValues) > 0 {
tgt.WithEnum(enumValues...)
enumTypeName := reflect.TypeOf(enumValues[0]).String()
_ = swaggerSchemaForType(enumTypeName, tgt)
}
if len(enumDesces) > 0 {
tgt.WithEnumDescription(strings.Join(enumDesces, "\n"))
}
return nil
}
if defaultName, ok := defaultName(cmt); ok {
debugLogf(s.ctx.debug, "default name: %s", defaultName)
return nil
}
if typeName, ok := typeName(cmt); ok {
_ = swaggerSchemaForType(typeName, tgt)
return nil
}
if isAliasParam(tgt) || aliasParam(cmt) {
err := swaggerSchemaForType(utitpe.Name(), tgt)
if err == nil {
return nil
}
}
if decl, ok := s.ctx.FindModel(tio.Pkg().Path(), tio.Name()); ok {
return s.makeRef(decl, tgt)
}
return swaggerSchemaForType(utitpe.String(), tgt)
}
func (s *schemaBuilder) buildNamedStruct(tio *types.TypeName, cmt *ast.CommentGroup, tgt swaggerTypable) error {
debugLogf(s.ctx.debug, "found struct: %s.%s", tio.Pkg().Path(), tio.Name())
decl, ok := s.ctx.FindModel(tio.Pkg().Path(), tio.Name())
if !ok {
debugLogf(s.ctx.debug, "could not find model in index: %s.%s", tio.Pkg().Path(), tio.Name())
return nil
}
o := decl.Obj()
if isStdTime(o) {
tgt.Typed("string", "date-time")
return nil
}
if sfnm, isf := strfmtName(cmt); isf {
tgt.Typed("string", sfnm)
return nil
}
if tn, ok := typeName(cmt); ok {
if err := swaggerSchemaForType(tn, tgt); err == nil {
return nil
}
// For unsupported swagger:type values, fall through to makeRef
// rather than silently returning an empty schema.
}
return s.makeRef(decl, tgt)
}
func (s *schemaBuilder) buildNamedArray(tio *types.TypeName, cmt *ast.CommentGroup, elem types.Type, tgt swaggerTypable) error {
debugLogf(s.ctx.debug, "found array type: %s.%s", tio.Pkg().Path(), tio.Name())
if sfnm, isf := strfmtName(cmt); isf {
if sfnm == goTypeByte {
tgt.Typed("string", sfnm)
return nil
}
if sfnm == "bsonobjectid" {
tgt.Typed("string", sfnm)
return nil
}
tgt.Items().Typed("string", sfnm)
return nil
}
// When swagger:type is set to an unsupported value (e.g., "array"),
// skip the $ref and inline the array schema with proper items type.
if tn, ok := typeName(cmt); ok {
if err := swaggerSchemaForType(tn, tgt); err != nil {
return s.buildFromType(elem, tgt.Items())
}
return nil
}
if decl, ok := s.ctx.FindModel(tio.Pkg().Path(), tio.Name()); ok {
return s.makeRef(decl, tgt)
}
return s.buildFromType(elem, tgt.Items())
}
func (s *schemaBuilder) buildNamedSlice(tio *types.TypeName, cmt *ast.CommentGroup, elem types.Type, tgt swaggerTypable) error {
debugLogf(s.ctx.debug, "found slice type: %s.%s", tio.Pkg().Path(), tio.Name())
if sfnm, isf := strfmtName(cmt); isf {
if sfnm == goTypeByte {
tgt.Typed("string", sfnm)
return nil
}
tgt.Items().Typed("string", sfnm)
return nil
}
// When swagger:type is set to an unsupported value (e.g., "array"),
// skip the $ref and inline the slice schema with proper items type.
// This preserves the field's description that would be lost with $ref.
if tn, ok := typeName(cmt); ok {
if err := swaggerSchemaForType(tn, tgt); err != nil {
// Unsupported type name (e.g., "array") — build inline from element type.
return s.buildFromType(elem, tgt.Items())
}
return nil
}
if decl, ok := s.ctx.FindModel(tio.Pkg().Path(), tio.Name()); ok {
return s.makeRef(decl, tgt)
}
return s.buildFromType(elem, tgt.Items())
}
// buildDeclAlias builds a top-level alias declaration.
func (s *schemaBuilder) buildDeclAlias(tpe *types.Alias, tgt swaggerTypable) error {
if unsupportedBuiltinType(tpe) {
log.Printf("WARNING: skipped unsupported builtin type: %v", tpe)
return nil
}
o := tpe.Obj()
if isAny(o) {
_ = tgt.Schema() // this is mutating tgt to create an empty schema
return nil
}
if isStdError(o) {
tgt.AddExtension("x-go-type", o.Name())
return swaggerSchemaForType(o.Name(), tgt)
}
mustNotBeABuiltinType(o)
if isStdTime(o) {
tgt.Typed("string", "date-time")
return nil
}
mustHaveRightHandSide(tpe)
rhs := tpe.Rhs()
// If transparent aliases are enabled, use the underlying type directly without creating a definition
if s.ctx.app.transparentAliases {
return s.buildFromType(rhs, tgt)
}
decl, ok := s.ctx.FindModel(o.Pkg().Path(), o.Name())
if !ok {
return fmt.Errorf("can't find source file for aliased type: %v -> %v: %w", tpe, rhs, ErrCodeScan)
}
s.postDecls = append(s.postDecls, decl) // mark the left-hand side as discovered
if !s.ctx.app.refAliases {
// expand alias
return s.buildFromType(tpe.Underlying(), tgt)
}
// resolve alias to named type as $ref
switch rtpe := rhs.(type) {
// named declarations: we construct a $ref to the right-hand side target of the alias
case *types.Named:
ro := rtpe.Obj()
rdecl, found := s.ctx.FindModel(ro.Pkg().Path(), ro.Name())
if !found {
return fmt.Errorf("can't find source file for target type of alias: %v -> %v: %w", tpe, rtpe, ErrCodeScan)
}
return s.makeRef(rdecl, tgt)
case *types.Alias:
ro := rtpe.Obj()
if unsupportedBuiltin(rtpe) {
log.Printf("WARNING: skipped unsupported builtin type: %v", rtpe)
return nil
}
if isAny(ro) {
// e.g. type X = any
_ = tgt.Schema() // this is mutating tgt to create an empty schema
return nil
}
if isStdError(ro) {
// e.g. type X = error
tgt.AddExtension("x-go-type", o.Name())
return swaggerSchemaForType(o.Name(), tgt)
}
mustNotBeABuiltinType(ro) // TODO(fred): there are a few other cases
rdecl, found := s.ctx.FindModel(ro.Pkg().Path(), ro.Name())
if !found {
return fmt.Errorf("can't find source file for target type of alias: %v -> %v: %w", tpe, rtpe, ErrCodeScan)
}
return s.makeRef(rdecl, tgt)
}
// alias to anonymous type
return s.buildFromType(rhs, tgt)
}
func (s *schemaBuilder) buildAnonymousInterface(it *types.Interface, tgt swaggerTypable, decl *entityDecl) error {
tgt.Typed("object", "")
for fld := range it.ExplicitMethods() {
if err := s.processAnonInterfaceMethod(fld, it, decl, tgt.Schema()); err != nil {
return err
}
}
return nil
}
func (s *schemaBuilder) processAnonInterfaceMethod(fld *types.Func, it *types.Interface, decl *entityDecl, schema *spec.Schema) error {
if !fld.Exported() {
return nil
}
sig, isSignature := fld.Type().(*types.Signature)
if !isSignature {
return nil
}
if sig.Params().Len() > 0 {
return nil
}
if sig.Results() == nil || sig.Results().Len() != 1 {
return nil
}
afld := findASTField(decl.File, fld.Pos())
if afld == nil {
debugLogf(s.ctx.debug, "can't find source associated with %s for %s", fld.String(), it.String())
return nil
}
if ignored(afld.Doc) {
return nil
}
name := nameOverride(fld.Name(), afld.Doc)
if schema.Properties == nil {
schema.Properties = make(map[string]spec.Schema)
}
ps := schema.Properties[name]
if err := s.buildFromType(sig.Results().At(0).Type(), schemaTypable{&ps, 0, s.ctx.opts.SkipExtensions}); err != nil {
return err
}
if sfName, isStrfmt := strfmtName(afld.Doc); isStrfmt {
ps.Typed("string", sfName)
ps.Ref = spec.Ref{}
ps.Items = nil
}
if err := s.createParser(name, schema, &ps, afld).Parse(afld.Doc); err != nil {
return err
}
if ps.Ref.String() == "" && name != fld.Name() {
ps.AddExtension("x-go-name", fld.Name())
}
if s.ctx.app.setXNullableForPointers {
_, isPointer := fld.Type().(*types.Signature).Results().At(0).Type().(*types.Pointer)
noNullableExt := ps.Extensions == nil ||
(ps.Extensions["x-nullable"] == nil && ps.Extensions["x-isnullable"] == nil)
if isPointer && noNullableExt {
ps.AddExtension("x-nullable", true)
}
}
schema.Properties[name] = ps
return nil
}
// buildAlias builds a reference to an alias from another type.
func (s *schemaBuilder) buildAlias(tpe *types.Alias, tgt swaggerTypable) error {
if unsupportedBuiltinType(tpe) {
log.Printf("WARNING: skipped unsupported builtin type: %v", tpe)
return nil
}
o := tpe.Obj()
if isAny(o) {
_ = tgt.Schema()
return nil
}
mustNotBeABuiltinType(o)
// If transparent aliases are enabled, use the underlying type directly
if s.ctx.app.transparentAliases {
return s.buildFromType(tpe.Rhs(), tgt)
}
decl, ok := s.ctx.FindModel(o.Pkg().Path(), o.Name())
if !ok {
return fmt.Errorf("can't find source file for aliased type: %v: %w", tpe, ErrCodeScan)
}
return s.makeRef(decl, tgt)
}
func (s *schemaBuilder) buildFromMap(titpe *types.Map, tgt swaggerTypable) error {
// check if key is a string type, or knows how to marshall to text.
// If not, print a message and skip the map property.
//
// Only maps with string keys can go into additional properties
sch := tgt.Schema()
if sch == nil {
return fmt.Errorf("items doesn't support maps: %w", ErrCodeScan)
}
eleProp := schemaTypable{sch, tgt.Level(), s.ctx.opts.SkipExtensions}
key := titpe.Key()
if key.Underlying().String() == "string" || isTextMarshaler(key) {
return s.buildFromType(titpe.Elem(), eleProp.AdditionalProperties())
}
return nil
}
func (s *schemaBuilder) buildFromInterface(decl *entityDecl, it *types.Interface, schema *spec.Schema, seen map[string]string) error {
if it.Empty() {
// return an empty schema for empty interfaces
return nil
}
var (
tgt *spec.Schema
hasAllOf bool
)
var flist []*ast.Field
if specType, ok := decl.Spec.Type.(*ast.InterfaceType); ok {
flist = make([]*ast.Field, it.NumEmbeddeds()+it.NumExplicitMethods())
copy(flist, specType.Methods.List)
}
// First collect the embedded interfaces
// create refs when:
//
// 1. the embedded interface is decorated with an allOf annotation
// 2. the embedded interface is an alias
for fld := range it.EmbeddedTypes() {
if tgt == nil {
tgt = &spec.Schema{}
}
fieldHasAllOf, err := s.processEmbeddedType(fld, flist, decl, schema, seen)
if err != nil {
return err
}
hasAllOf = hasAllOf || fieldHasAllOf
}
if tgt == nil {
tgt = schema
}
// We can finally build the actual schema for the struct
if tgt.Properties == nil {
tgt.Properties = make(map[string]spec.Schema)
}
tgt.Typed("object", "")
for fld := range it.ExplicitMethods() {
if err := s.processInterfaceMethod(fld, it, decl, tgt, seen); err != nil {
return err
}
}
if tgt == nil {
return nil
}
if hasAllOf && len(tgt.Properties) > 0 {
schema.AllOf = append(schema.AllOf, *tgt)
}
for k := range tgt.Properties {
if _, ok := seen[k]; !ok {
delete(tgt.Properties, k)
}
}
return nil
}
func (s *schemaBuilder) processEmbeddedType(fld types.Type, flist []*ast.Field, decl *entityDecl, schema *spec.Schema, seen map[string]string) (fieldHasAllOf bool, err error) {
debugLogf(s.ctx.debug, "inspecting embedded type in interface: %v", fld)
switch ftpe := fld.(type) {
case *types.Named:
debugLogf(s.ctx.debug, "embedded named type (buildInterface): %v", ftpe)
o := ftpe.Obj()
if isAny(o) || isStdError(o) {
return false, nil
}
return s.buildNamedInterface(ftpe, flist, decl, schema, seen)
case *types.Interface:
debugLogf(s.ctx.debug, "embedded anonymous interface type (buildInterface): %v", ftpe)
var aliasedSchema spec.Schema
ps := schemaTypable{schema: &aliasedSchema, skipExt: s.ctx.opts.SkipExtensions}
if err = s.buildAnonymousInterface(ftpe, ps, decl); err != nil {
return false, err
}
if aliasedSchema.Ref.String() != "" || len(aliasedSchema.Properties) > 0 || len(aliasedSchema.AllOf) > 0 {
fieldHasAllOf = true
schema.AddToAllOf(aliasedSchema)
}
case *types.Alias:
debugLogf(s.ctx.debug, "embedded alias (buildInterface): %v -> %v", ftpe, ftpe.Rhs())
var aliasedSchema spec.Schema
ps := schemaTypable{schema: &aliasedSchema, skipExt: s.ctx.opts.SkipExtensions}
if err = s.buildAlias(ftpe, ps); err != nil {
return false, err
}
if aliasedSchema.Ref.String() != "" || len(aliasedSchema.Properties) > 0 || len(aliasedSchema.AllOf) > 0 {
fieldHasAllOf = true
schema.AddToAllOf(aliasedSchema)
}
case *types.Union:
log.Printf("WARNING: union type constraints are not supported yet %[1]v (%[1]T). Skipped", ftpe)
case *types.TypeParam:
log.Printf("WARNING: generic type parameters are not supported yet %[1]v (%[1]T). Skipped", ftpe)
case *types.Chan:
log.Printf("WARNING: channels are not supported %[1]v (%[1]T). Skipped", ftpe)
case *types.Signature:
log.Printf("WARNING: functions are not supported %[1]v (%[1]T). Skipped", ftpe)
default:
log.Printf(
"WARNING: can't figure out object type for allOf named type (%T): %v",
ftpe, ftpe.Underlying(),
)
}
debugLogf(s.ctx.debug, "got embedded interface: %v {%T}, fieldHasAllOf: %t", fld, fld, fieldHasAllOf)
return fieldHasAllOf, nil
}
func findASTField(file *ast.File, pos token.Pos) *ast.Field {
ans, _ := astutil.PathEnclosingInterval(file, pos, pos)
for _, an := range ans {
if at, valid := an.(*ast.Field); valid {
return at
}
}
return nil
}
func nameOverride(defaultName string, doc *ast.CommentGroup) string {
name := defaultName
if doc != nil {
for _, cmt := range doc.List {
for ln := range strings.SplitSeq(cmt.Text, "\n") {
matches := rxName.FindStringSubmatch(ln)
if ml := len(matches); ml > 1 {
name = matches[ml-1]
}
}
}
}
return name
}
func (s *schemaBuilder) processInterfaceMethod(fld *types.Func, it *types.Interface, decl *entityDecl, tgt *spec.Schema, seen map[string]string) error {
if !fld.Exported() {
return nil
}
sig, isSignature := fld.Type().(*types.Signature)
if !isSignature {
return nil
}
if sig.Params().Len() > 0 {
return nil
}
if sig.Results() == nil || sig.Results().Len() != 1 {
return nil
}
afld := findASTField(decl.File, fld.Pos())
if afld == nil {
debugLogf(s.ctx.debug, "can't find source associated with %s for %s", fld.String(), it.String())