MCPcopy Index your code
hub / github.com/coder/guts / buildStruct

Method buildStruct

convert.go:808–963  ·  view source on GitHub ↗

buildStruct just prints the typescript def for a type. Generic type parameters are inferred from the type and inferred.

(obj types.Object, st *types.Struct)

Source from the content-addressed store, hash-verified

806// buildStruct just prints the typescript def for a type.
807// Generic type parameters are inferred from the type and inferred.
808func (ts *Typescript) buildStruct(obj types.Object, st *types.Struct) (*bindings.Interface, error) {
809 tsi := &bindings.Interface{
810 Name: ts.parsed.Identifier(obj),
811 Modifiers: []bindings.Modifier{},
812 Fields: []*bindings.PropertySignature{},
813 Parameters: []*bindings.TypeParameter{}, // Generics
814 Heritage: []*bindings.HeritageClause{}, // Extends
815 Source: ts.location(obj),
816 }
817
818 // Handle named embedded structs in the codersdk package via extension.
819 // This is inheritance.
820 // TODO: Maybe this could be done inline in the main for loop?
821 var extends []parsedType
822 for i := 0; i < st.NumFields(); i++ {
823 field := st.Field(i)
824 tag := reflect.StructTag(st.Tag(i))
825 // Adding a json struct tag causes the json package to consider
826 // the field unembedded.
827 if field.Embedded() && tag.Get("json") == "" {
828 // TODO: This prevents an inheritance clause from having a ` | null` in the
829 // expression. Typescript does not support `null` in the extends clause.
830 // This is not a perfect solution, and exists as a workaround.
831 // See https://github.com/coder/guts/issues/40
832 fieldType := field.Type()
833 for i := 0; i < 10; i++ { // Can there be an infinite loop here?
834 if ptrType, ok := fieldType.(*types.Pointer); ok {
835 fieldType = ptrType.Elem()
836 continue
837 }
838 break
839 }
840
841 // TODO: Generic args
842 heritage, err := ts.typescriptType(fieldType)
843 if err != nil {
844 return tsi, xerrors.Errorf("heritage type: %w", err)
845 }
846 extends = append(extends, heritage)
847 }
848 }
849
850 if len(extends) > 0 {
851 var heritages []bindings.ExpressionType
852 for _, heritage := range extends {
853 heritages = append(heritages, heritage.Value)
854 }
855 tsi.Heritage = append(tsi.Heritage, bindings.HeritageClauseExtends(heritages...))
856 }
857
858 if _, ok := obj.(*types.TypeName); ok {
859 var typeParamed interface{ TypeParams() *types.TypeParamList }
860 switch typedObj := obj.Type().(type) {
861 case *types.Named:
862 typeParamed = typedObj
863 case *types.Alias:
864 typeParamed = typedObj
865 default:

Callers 1

parseMethod · 0.95

Calls 10

locationMethod · 0.95
typescriptTypeMethod · 0.95
HeritageClauseExtendsFunction · 0.92
SimplifyFunction · 0.92
LeadingCommentMethod · 0.80
CommentForObjectMethod · 0.80
AppendCommentsMethod · 0.80
IdentifierMethod · 0.45
StringMethod · 0.45

Tested by

no test coverage detected