MCPcopy Create free account
hub / github.com/apache/fory / generateCode

Function generateCode

go/fory/codegen/generator.go:541–614  ·  view source on GitHub ↗

generateCode generates code with package-based naming (legacy mode)

(pkg *packages.Package, structs []*StructInfo)

Source from the content-addressed store, hash-verified

539
540// generateCode generates code with package-based naming (legacy mode)
541func generateCode(pkg *packages.Package, structs []*StructInfo) error {
542 var buf bytes.Buffer
543
544 // Generate file header
545 fmt.Fprintf(&buf, "// Code generated by forygen. DO NOT EDIT.\n")
546 fmt.Fprintf(&buf, "// source: %s\n", pkg.PkgPath)
547 fmt.Fprintf(&buf, "// generated at: %s\n\n", time.Now().Format(time.RFC3339))
548 fmt.Fprintf(&buf, "package %s\n\n", pkg.Name)
549
550 // Determine which imports are needed
551 needsTime := false
552 needsReflect := false
553 needsOptional := false
554
555 for _, s := range structs {
556 for _, field := range s.Fields {
557 typeStr := field.Type.String()
558 if typeStr == "time.Time" || typeStr == "github.com/apache/fory/go/fory.Date" {
559 needsTime = true
560 }
561 if field.IsOptional {
562 needsOptional = true
563 }
564 // We need reflect for the interface compatibility methods
565 needsReflect = true
566 }
567 }
568
569 // Generate imports
570 // Note: "fmt" is not imported by default. Add it only if the generated code uses fmt.
571 fmt.Fprintf(&buf, "import (\n")
572 if needsReflect {
573 fmt.Fprintf(&buf, "\t\"reflect\"\n")
574 }
575 if needsTime {
576 fmt.Fprintf(&buf, "\t\"time\"\n")
577 }
578 fmt.Fprintf(&buf, "\t\"github.com/apache/fory/go/fory\"\n")
579 if needsOptional {
580 fmt.Fprintf(&buf, "\t\"github.com/apache/fory/go/fory/optional\"\n")
581 }
582 fmt.Fprintf(&buf, ")\n\n")
583
584 // Generate init function to register serializer factories
585 fmt.Fprintf(&buf, "func init() {\n")
586 for _, s := range structs {
587 fmt.Fprintf(&buf, "\tfory.RegisterSerializerFactory((*%s)(nil), NewSerializerFor_%s)\n", s.Name, s.Name)
588 }
589 fmt.Fprintf(&buf, "}\n\n")
590
591 // Generate serializers for each struct
592 for _, s := range structs {
593 if err := generateStructSerializer(&buf, s); err != nil {
594 return fmt.Errorf("generating serializer for %s: %w", s.Name, err)
595 }
596 }
597
598 // Generate compile-time guards to ensure struct definitions haven't changed

Callers 1

processPackageFunction · 0.85

Calls 6

generateStructSerializerFunction · 0.85
convertStructInfosFunction · 0.85
generateCompileGuardFunction · 0.85
BytesMethod · 0.80
StringMethod · 0.45
WriteStringMethod · 0.45

Tested by

no test coverage detected