MTL Code Generation

Complete Code Generator

Build a complete Swift code generator from the Company metamodel, applying all MTL concepts together.

In this tutorial, you’ll create a production-quality generator that produces Swift structs with properties, initialisers, and utility methods.

60 mins Estimated Time

Section 1

Designing the Generator

A complete generator combines multiple templates, queries, and macros to produce well-structured code. Plan your template architecture before coding.

Separate concerns: use helper templates for repeated patterns, queries for logic, and macros for formatting.

Step 1

Create the main generation template.

The main template orchestrates file generation, calling helper templates for each model element.

SwiftGenerator.mtl
1[module SwiftGenerator('http://www.example.org/company')]
2
3[template main(pkg : EPackage)]
4[file (pkg.name + '.swift', 'overwrite', 'UTF-8')]
5// Generated from [pkg.name/]
6
7[for (cls : EClass | pkg.eClassifiers->filter(EClass))]
8[generateClass(cls)/]
9[/for]
10[/file]
11[/template]
12
13[template generateClass(cls : EClass)]
14struct [cls.name/] {
15 // TODO: Add properties
16}
17[/template]

Step 2

Add helper templates for classes.

Helper templates focus on generating specific parts. This one generates a Swift struct from an EClass.

SwiftGenerator.mtl
1[module SwiftGenerator('http://www.example.org/company')]
2
3[template main(pkg : EPackage)]
4[file (pkg.name + '.swift', 'overwrite', 'UTF-8')]
5// Generated from [pkg.name/]
6
7[for (cls : EClass | pkg.eClassifiers->filter(EClass))]
8[generateClass(cls)/]
9[/for]
10[/file]
11[/template]
12
13[template generateClass(cls : EClass)]
14struct [cls.name/] {
15[for (attr : EAttribute | cls.eStructuralFeatures->filter(EAttribute))]
16 var [attr.name/]: String
17[/for]
18}
19[/template]

Step 3

Generate the complete project.

Run the complete generator against your Company model to produce a full Swift module.

Terminal
1swift-mtl generate SwiftGenerator.mtl --model Company.ecore --output generated/

Check Your Understanding

Question 1 of 1

Why use helper templates instead of putting everything in main?

AQL Basics

Learn the fundamentals of the Acceleo Query Language (AQL) for navigating and querying models.