go/tools/asthelpergen/design.md
The asthelpergen package is a code generation tool that automatically creates helper methods for Abstract Syntax Tree (AST) implementations. Given a root interface, it generates various AST manipulation utilities including cloning, equality comparison, visiting, and rewriting functions.
astHelperGen)namedIface: The root interface for which helpers are generatedgens: Collection of specialized generators (clone, equals, visit, rewrite, etc.)todo: Queue of types discovered during generation that need processing_scope: Type scope for finding implementationsThe system uses a plugin-like architecture with two key interfaces:
generatorSPI (Service Provider Interface):
addType(): Adds newly discovered types to the processing queuefindImplementations(): Discovers all types implementing a given interfacescope(): Access to the type system scopegenerator Interface:
cloneGen)ast_clone.goequalsGen)ast_equals.goComparator structvisitGen)ast_visit.goVisitable interface with custom visit logicrewriteGen)ast_rewrite.gopathGen)ast_path.gocowGen)ast_copy_on_rewrite.gogo/packagesastHelperGen instancetodo queueThe generator uses Go's type system to:
Each generator implements methods for different type categories:
interfaceMethod: Handles interface types with type switchingstructMethod: Handles struct types with field iterationptrToStructMethod: Handles pointer-to-struct typessliceMethod: Handles slice types with element processingbasicMethod: Handles basic types (int, string, etc.)Exclude: List of type patterns to exclude from cloningAllowCustom: List of types that can have custom comparatorsPackages: Go packages to analyzeRootInterface: Fully qualified name of the root interfacemain/main.go)spf13/pflag for command-line argument parsingintegration/ package provide real-world examplesMultiple generators implement the same interface, allowing easy extension with new generator types.
The generation process is driven by Go's type system, ensuring type safety and correctness.
Types are discovered incrementally as generators process fields and references, ensuring complete coverage.
Uses dave/jennifer for programmatic Go code generation instead of text templates, providing better type safety and refactoring support.
alreadyDone mapThe architecture supports easy addition of new generators:
generator interfaceGenerateASTHelpers()This design provides a robust, extensible foundation for AST helper code generation while maintaining type safety and performance.