agentleFS
nakane1chomenakane1chome/claude-skills/skills/generator-coding/SKILL.md

generator-coding

Skill0 starsChanged 7 months agoUnlicenseView on GitHub

Template-based code generation pattern using data models, templates, and helper functions to generate repetitive interface code.

The file

We split this skill into the rules it gives an agent

4 rules. About 0 are common, 4 are distinctive, and 0 are very specific to this project.

  • ≈0

    Common · estimate

    Many files like this have a rule of this kind.

  • ≈4

    Distinctive · estimate

    This author's own choices. Worth a look.

  • 0

    Very specific

    Tied to their project's names, files or tools. Probably skip.

  • Common
  • Distinctive
  • Very specific
  1. Distinctive:

    Directive: Prefer customizable template-based generators for agent use.

    line 42
  2. Distinctive:

    Directive: Prefer in-language meta-programming -- the target toolchain handles validation, error reporting, and IDE support.

    line 52
  3. Distinctive:

    Use the user's existing data model.

    line 97
  4. Distinctive:

    When combining external generation with in-language meta-programming:

    line 160

≈ “Common” is an estimate: at least 1 in 5 of the 350,495 skill files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.

Keep what fits and drop the rest. Your version, ready for your agents.
Files
SKILL.md

Template-Based Code Generation

Three inputs produce repetitive (typically interface) code:

  • Data model: Standardized representation -- XML, Domain-Specific Language (DSL), or schema-enforced JSON/YAML.
  • Template: Templating meta-language markup (Jinja2, ERB, etc.).
  • Helper functions: Functions that reshape the data model for template consumption.
Data Model ──► Parser ──► Helpers ──► Template Engine ──► Generated Output
   (SVD,         (cmsis-svd,   (reshape,    (Jinja2,        (one file per
    IDL,          sqlparse)     filter)      ERB)            generation unit)
    DBML...)

Terms

TermDefinition
Data ModelInput describing the structure to replicate (e.g. SVD file for hardware registers).
Helpers/PluginsFunctions that transform/filter/restructure the data model for templates.
Template(s)Defines output structure in the target language with template markup for variable parts.
Target LanguageLanguage of the generated output (e.g. C++, Python, Verilog).
Generated OutputFiles produced by the generator. Must never be hand-edited (see: Rules).
Generation UnitData model component a template operates on (e.g. peripheral, table, message). One output file per unit (see: Step 3).
Data Bridge TemplateTemplate converting the data model into target-language compile-time representations (enums, constants, macros). Consumed by in-language meta-programming (see: Meta-Programming Rules).

Generator Types

TypeDescriptionTemplate LocationFlexibility
Fixed functionTemplate embedded in generator tool codeInside the toolOutput format fixed; change requires modifying the tool
Customizable template-basedTemplate separated from toolUser-editable filesUser can modify/replace templates freely

Directive: Prefer customizable template-based generators for agent use. The agent can read, understand, and modify templates without understanding the tool's internals.

Meta-Programming

TypeMechanismWhen to use
In-languageC++ templates/constexpr/consteval, C preprocessor, Python decorators, Verilog generateData can be represented in target language compile-time constructs
External template-basedJinja2/ERB generating source filesData cannot be naturally represented in target language (e.g. register maps, protocol definitions)

Directive: Prefer in-language meta-programming -- the target toolchain handles validation, error reporting, and IDE support. Combine with external generation using the layered approach (see: Meta-Programming Rules).

Examples

Generator Tools

ToolTypeTemplatingDomain
Protobuf (protoc)FixedEmbeddedSerialization / RPC
Cyclone DDS (idlc)FixedEmbeddedDDS/OMG IDL interfaces
SWIGFixedEmbeddedForeign Function Interface (FFI) wrappers
Ruby on RailsTemplateERBWeb scaffolding
CookiecutterTemplateJinja2Project scaffolding
development-utilsTemplateJinja2Hardware description (SVD, SystemRDL, DBML, Device Tree, IDL)

Data Model Formats

FormatDomainType
SQL DDLDatabasesData exchange
XML (SVD, ATML)Hardware, generalData exchange
JSON / YAML / TOMLGeneral (schema required)Data exchange
IDL (Interface Definition Language)Distributed systems (CORBA, DDS, Protobuf)DSL
SystemRDLRegister descriptionsDSL
DBML (Database Markup Language)Database schemasDSL
AADL (Architecture Analysis and Design Language)Safety-critical systemsDSL
SysMLSystems modelingDSL
Device TreeLinux/embedded hardwareDSL

Templating Languages

LanguageEcosystemLogicStrengths
Jinja2PythonFull (loops, macros, filters)Most expressive; StrictUndefined; dominant for standalone generators
ERBRubyFull Ruby executionNative to Rails
LiquidRubySafe subsetSandboxed; safe for user-supplied templates
MakoPythonFull Python executionFast; used by Alembic
Mustache/HandlebarsLanguage-agnosticLogic-lessForces logic into helpers

Process

Step 1: Identify the Data Model

Use the user's existing data model. If none exists, select a domain standard:

DomainStandard formats
Hardware registersSVD, SystemRDL, IP-XACT (IEEE 1685)
Communication protocolsProtobuf, IDL, ASN.1
Database schemasSQL DDL, DBML
APIsOpenAPI/Swagger, GraphQL
Hardware architectureDevice Tree, AADL

Step 2: Understand the Interface Boundary

Identify the specification-defined interface:

BoundaryExamples
Persistent dataDatabase tables, file formats
Inter-Process Communication (IPC)Shared memory, message queues, pub/sub
Hardware/softwareMemory-Mapped I/O (MMIO) registers, Direct Memory Access (DMA) descriptors
Language interopJava Native Interface (JNI), Python C extensions, FFI
Network protocolsRPC definitions, serialization formats

Step 3: Determine the Generation Granularity

GranularityScopeUse case
Component-levelOne output file per generation unit (peripheral, message, table)Direct usage patterns; simpler templates
System-levelOne output file covering all componentsCross-cutting concerns (dispatch tables, device maps, schema migrations)

Split templates by granularity. A single system-wide template that includes all components is difficult to maintain.

Step 4: Template Output Conventions

ConventionPatternExample
Template naming<generation_unit>_<output_name>.<target_ext>.jinja2peripheral_regs.hpp.jinja2, table_model.py.jinja2
Output directorySeparate from hand-written source: generated/, gen/, build/gen/Never mix generated and hand-written files
Version controlAdd output directories to .gitignoreException: version output if users lack the generator toolchain

Step 5: Write the Generator Pipeline

StageResponsibilityNotes
ParserRead and validate data model; produce in-memory representationReuse open-source parsers: cmsis-svd, systemrdl-compiler, sqlparse. Custom parser = last resort.
HelpersReshape/filter parsed data for template consumptionKeep logic out of templates
TemplatesEmit target-language constructs; read like target source codeMinimal control flow; iterate over data
Driver scriptConnect parser + helpers + templates; write output filesScript or Makefile target

Rules for Using Generators

#RuleDetail
1Never edit generated outputFix the data model, template, or helper instead. If output is wrong, fix the input.
2Interface changes go in the data modelNew field/register/message = modify the data model source, not the template.
3Data reshaping goes in helpersFiltering, renaming, restructuring = helper functions. Keep templates simple.
4Templates read like target source codeTemplate markup ({% for %}, {{ }}) is a thin layer over recognizable target code.
5Control whitespace explicitlyJinja2: enable trim_blocks + lstrip_blocks. Use {%-/-%} for fine-grained control. Verify output formatting.
6One concern per templateEach template produces one logical output artifact.

Rules for Meta-Programming with Generators

When combining external generation with in-language meta-programming:

#RuleDetail
1Prefer target-language mechanismsC++ constexpr/consteval, Python metaclasses, Verilog generate, C macros.
2Data bridge templateOne template converts data model to target-language compile-time data (enums, constants, constexpr arrays).
3Separate runtime templatesConsume compile-time data via target-language meta-programming (e.g. C++ template class parameterized by generated enum).
4Layering principleExternal generation = data declarations. In-language meta-programming = behavior. Each layer independently testable.

Testing Generators

StrategyWhat it catchesHow
Golden-file testsUnintended output changesStore known-good output as reference; diff against current output
Compilation testsSyntax errors, type mismatchesCompile (or lint) generated output after generation
Round-trip testsSemantic correctnessVerify generated code represents the data model correctly (e.g. register access returns expected values)
Sample data modelsTemplate edge casesMaintain small test data exercising all control flow paths (optional fields, empty lists, single-element lists)

Build System Integration

ConcernApproach
Dependency trackingMakefile/script declares deps on data model + templates + helpers. Any input change triggers regeneration.
Makefile patterngenerated/%.hpp: data/%.xml templates/peripheral_regs.hpp.jinja2 helpers.py
Incremental generationFor large data models, regenerate only changed generation units.
CI verificationRun generator in CI; verify checked-in output (if versioned) matches generator output.

Post-Generation Hooks

HookPurposeExample
Code formattersMatch project style without burdening templatesclang-format (C/C++), black (Python), rustfmt (Rust)
LintersCatch issues template engine cannot detectUnused imports, naming violations
Hook integrationRun in driver script after renderingclang-format -i generated/*.hpp

Error Handling

ScenarioAction
Malformed data modelValidate against schema before rendering. Report errors with file location + field name. Do not render invalid data.
Missing template fieldsUse strict undefined handling (Jinja2: undefined=StrictUndefined). Fail loudly.
Non-deterministic outputSame inputs must produce identical output. If not, there is a bug in the generator.

Example Generator Repository

development-utils demonstrates:

AspectDetails
ParsersPython-based: SVD, SystemRDL, DBML, Device Tree, IDL
OutputC++17/C++20 MMIO register interfaces, SQLAlchemy/Pydantic models from DBML, RISC-V CSR access code (C/C++/Rust)
Naming<generation_unit>_<name>.<ext>.jinja2
GranularityComponent-level (per peripheral) + system-level (device maps)

Download now (ZIP)

Does it work?

Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.

No reviews yet

People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.

  • It worked
  • Partly
  • It didn't
What did you use it for? e.g. Reviewing pull requests in a Rails app

Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.

Your trail

Files you open will collect here, so you can find them again.

Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.

Now do this for your own.

Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.