$ show dart-lang/source_gen
source_gen is a Dart library that provides a framework for writing source code generators that integrate with the `package:build` build system. It defines abstract `Generator` and `GeneratorForAnnotation` classes, and provides concrete `Builder` implementations (`PartBuilder`, `SharedPartBuilder`, `LibraryBuilder`) that wrap generators into build-compatible builders. The library also includes utilities for type checking (`TypeChecker`), reading constant annotation values (`ConstantReader`), reviving constant expressions (`Revivable`), and navigating library elements (`LibraryReader`). A `CombiningBuilder` merges multiple generated part files into a single `.g.dart` output. The codebase is well-structured, thoroughly tested, and actively maintained by the Dart team. It is not a standalone application but a framework dependency for packages that need to generate Dart code at build time.
The LLM identified 3 files worth highlighting for reuse:
Implements the `TypeChecker` abstraction for compile-time type matching without using mirrors. Provides multiple implementations (`_NameTypeChecker`, `_LiteralNameTypeChecker`, `_UriTypeChecker`, `_LibraryTypeChecker`, `_AnyChecker`) that can check type assignability, exact match, and supertype relationships. Handles edge cases like null libraries, function types, and unresolved annotations with detailed error reporting. This component is self-contained and could be extracted into a standalone package for any Dart code generation tool that needs to match types at build time.
Provides `ConstantReader`, a high-level wrapper around the analyzer's `DartObject` for reading constant annotation values. Offers type-safe accessors for bool, int, double, String, Symbol, Type, List, Set, Map, and literal values. Handles null objects gracefully with a `_NullConstant` implementation, and supports recursive field access through superclasses via `getFieldRecursive`. The `peek` method allows safe optional field reading. This component is reusable for any code generator that needs to parse annotation arguments.
Implements `reviveInstance` and `Revivable` to reconstruct constant expressions from analyzer `DartObject` instances. Handles constructors (default, named, private), static fields, top-level variables, enum values, and function references. Tries to return public accessors first, falling back to private ones. The `Revivable` class captures the source URI, accessor, and arguments needed to recreate the constant in generated code. This is a non-trivial piece of logic that demonstrates deep understanding of the analyzer's constant model and is reusable for any code generator that needs to emit constant references.