Anvil: use profile bindings
A profile binding is a compile-time object that stands for a profile, a stereotype, a tag or an enumeration in a model. A plugin applies a stereotype, reads a tagged value or finds every element carrying a stereotype through that object, and the compiler checks the metaclass, the tag name and the tag's type before the tool ever opens a project.
The profile.runtime package carries the API. The profile-binding
contract explains why it resolves the way it does.
Get the bindings
Forge's generateProfileBindings task reads a profile's .mdzip during a consuming project's build
and emits Kotlin into that project's own profile package. Anvil publishes the API the emitted code
sits on; the Forge guide to generating profile bindings
states how a consumer configures the task.
The emitted shape is one object per profile, one nested object per stereotype, and one val per
tag:
@Generated
public object OrganizationProfile : ProfileReference(
name = "Organization Profile",
uri = "https://example.test/spec/organization/profile",
) {
@Generated
public object Building : StereotypeReference<Class>(OrganizationProfile, "Building", Class::class) {
public val floors: SingleValueTagReference<Int> = singleValueTag("floors")
public val leased: SingleValueTagReference<Boolean> = singleValueTag("leased")
public val securityTier: SingleValueTagReference<EnumerationLiteral> = singleValueTag("securityTier")
}
}A stereotype's type parameter is the metaclass it extends, so Building accepts a Class and
rejects a Package at compile time. A profile with no .mdzip to generate from is bound by hand
against the same API — see Hand-write a binding.
Test and apply a stereotype
if (!OrganizationProfile.Building.isAppliedTo(element)) {
OrganizationProfile.Building.applyTo(element)
}isAppliedTo counts specialisations by default, so an element carrying a stereotype that extends
Building answers true. Pass includeDerived = false for the exact stereotype alone.
applyTo and every other write require an open session. A model write outside a session fails
silently and leaves no undo entry, so the binding asserts the session and throws instead:
val sessions = SessionManager.getInstance()
sessions.createSession(project, "apply Building")
var completed = false
try {
OrganizationProfile.Building.applyTo(element)
completed = true
} finally {
if (completed) sessions.closeSession(project) else sessions.cancelSession(project)
}Exactly one of closeSession or cancelSession runs, on success and on failure alike, including an
Error that a catch on RuntimeException would not reach.
applyTo seeds tagged values after applying the stereotype, and TagDefaults decides how many:
TagDefaults | Creates |
|---|---|
REQUIRED (default) | The values the model requires |
ALL | Every value carrying a default |
NONE | No tagged values |
removeFrom(element) takes the stereotype off again and cascades to its tagged values.
Read and write tags
A tag reference reads without a session and writes inside one:
val floors: Int? = OrganizationProfile.Building.floors.get(element)
OrganizationProfile.Building.floors.set(element, 12)
OrganizationProfile.Building.floors.set(element, null) // clears the valueA multi-valued tag adds one value, removes one occurrence, replaces the whole list, or clears it:
val occupied: List<Class> = OrganizationProfile.BusinessUnit.occupies.get(element)
OrganizationProfile.BusinessUnit.occupies.add(element, building)
OrganizationProfile.BusinessUnit.occupies.remove(element, building)
OrganizationProfile.BusinessUnit.occupies.set(element, listOf(building))
OrganizationProfile.BusinessUnit.occupies.clear(element)remove drops a single occurrence, mirroring add. Removing every occurrence of a value takes a
loop or clear.
Every write keeps both ends of a bidirectional association consistent, so dropping a value from one end unlinks the far end as well.
Convert an enumerated tag
An enumerated tag is typed EnumerationLiteral on the stereotype, and the generated enum crosses the
boundary in both directions:
val tier: SecurityTier? = SecurityTier.from(OrganizationProfile.Building.securityTier.get(element))
OrganizationProfile.Building.securityTier.set(element, SecurityTier._3.literal(project))from matches on XMI id first and on the literal's name second, so a literal renamed in the profile
still resolves. literal(project) answers null when the profile is absent from the project or the
literal has been deleted from it.
Work through a view
The generator also emits one view per stereotype: a value class over an element of the right metaclass, exposing that stereotype's tags as properties.
val building = BuildingView(element)
building.floors = 12
val leased = building.leasedA view carries no state beyond the element it wraps, so it costs nothing over the tag-reference calls it delegates to. Its setters write, so the same session rule applies.
Find every element carrying a stereotype
OrganizationProfile.Building.findAll(project).forEach { building -> … }findAll answers a Sequence, filtered to the stereotype's own metaclass, and counts specialisations
unless includeDerived = false is passed.
Hand-write a binding
A profile with no .mdzip available is bound against the same API. Extend ProfileReference and
StereotypeReference, and declare tags through the two protected helpers:
object AcmeProfile : ProfileReference("ACME", "https://example.test/spec/acme/profile") {
object Concept : StereotypeReference<Class>(AcmeProfile, "Concept", Class::class) {
val code = singleValueTag<String>("code")
val aliases = multiValueTag<String>("aliases")
}
}A hand-written binding carries no @Generated, so it stays in the coverage report — it is the
author's code, and the author's tests are what the report measures.
What fails, and what it means
Every failure is an exception naming the reference and the reason, rather than a silent no-op.
| Message names | Cause |
|---|---|
profile … is not loaded in project | The project does not carry the profile the URI names |
stereotype … is not defined in profile | The profile is loaded, and the stereotype is absent from it |
Model mutation requires an open session | A write outside a session |
element is not registered in project | The element has been disposed |
element is read-only | The element cannot take a write; the Open API does not block one |
element is a proxy into an unloaded module | The owning module is not loaded |
stereotype does not fit the element's metaclass | applyTo against a metaclass the stereotype does not extend |
The profile URI is what a project is matched on, and the profile's name is carried for diagnostics alone, so a URI that has drifted from the model produces the first message above rather than a mismatch nobody notices.
Related
- The profile-binding contract — why nothing is cached, and what guards the API against a breaking change.
- Anvil: write an auto-stereotype rule — a rule's
conditionsandapplyStereotypeare written against these bindings.