Anvil: write an auto-stereotype rule
A modeller draws ordinary UML, and a rule applies the stereotype the model already implies. The
autostereotype package carries the engine, the rule contract and the Project Options switch each
rule is read from; events carries the tracer that explains what a rule saw, standalone of the
engine. A resource extends this part of Anvil rather than calling it.
1. Declare the rule set
A resource declares one AutoStereotypeRuleSet, which carries the identity every registration
derives from:
object AcmeRules : AutoStereotypeRuleSet(
groupId = "ACME_GROUP",
groupLabel = "ACME",
profileUri = AcmeProfile.uri,
log = ResourceLog.of("ACME"),
) {
override val rules: List<AutoStereotypeRule<*>> = listOf(AttributeRule, StepActionRule)
}| Property | Decides |
|---|---|
groupId | The Project Options group identifier, persisted in every model that has been asked. Keep it stable across renames. |
groupLabel | What the Project Options dialog shows. Name it after the resource, so a later setting joins the same group. |
profileUri | Which projects carry the group, and which projects the rules run in at all. A project without the resource's profile can hold none of its stereotypes. |
log | The category the engine and the tracer write under. See Anvil: log from a resource. |
rules | Every rule the resource ships. |
defaultEnabled | What a rule does in a project that has never been asked. Defaults to enabled. |
The rules list is the one place a rule is named. The engine reads it to evaluate every rule against
every committed transaction, and the Project Options configurator reads the same list to declare one
switch per rule. A rule therefore cannot reach a model without a switch, and a switch cannot exist
without a rule.
2. Hold one engine in the plugin
class Main : Plugin() {
companion object {
val engine = AutoStereotypeEngine(AcmeRules)
}
override fun init() = engine.install()
override fun close(): Boolean {
engine.uninstall()
return true
}
override fun isSupported(): Boolean = true
}install() declares the options group, installs the tracer, and attaches a rule listener to every
project as it opens. uninstall() undoes each registration in reverse. Both calls are idempotent.
The engine holds the field for you, so nothing else in the plugin registers a listener, a
configurator or a provider of its own. Holding it in the companion object, rather than an instance
field, is what lets another class in the plugin reach it — Suspend the rules around an
automation is where an action does.
3. Write the rule
A rule extends AutoStereotypeRule<U>, where U is the metaclass its stereotype lands on, and
declares four members:
private object AttributeRule : AutoStereotypeRule<Property>(
"Attribute",
"ACME_ATTRIBUTE",
"Auto-apply Attribute",
"Applies «Attribute» to a Property owned by a «Concept» and typed by a «Concept»",
) {
override fun candidatesOf(event: PropertyChangeEvent) = listOfNotNull(event.source as? Property)
override fun conditions(usage: Property) =
listOf(
condition("owner", usage.owner) { ConceptStereotype.isAppliedTo(it) },
condition("type", usage.type) { ConceptStereotype.isAppliedTo(it) },
)
override fun alreadyApplied(usage: Property) = AttributeStereotype.isAppliedTo(usage)
override fun applyStereotype(usage: Property) = AttributeStereotype.applyTo(usage)
}| Member | Answers |
|---|---|
candidatesOf | The elements a committed PropertyChangeEvent may have brought into or out of scope |
conditions | One labelled Condition per half of the trigger, evaluated against a candidate |
alreadyApplied | Whether the candidate already carries the stereotype, including through a specialisation |
applyStereotype | The call that writes it, run inside an open session |
The four constructor arguments name the stereotype for log lines and declare the rule's Project
Options switch. optionId is persisted in every model that has been asked, so it stays stable across
renames of the rule.
A rule that notifies runs once per candidate, so a rule notifying per element puts a balloon in front of the modeller on every edit — summarise a completed batch instead, per Notify a modeller.
4. Establish candidatesOf from a recorded event trace
Read what the model reports, rather than the UML metamodel. The example above is deliberately minimal, and a real rule answers more than the event's source. What the model reports contradicts a reading of the metamodel often enough that guessing does not work:
- Ownership of a
Propertyarrives asUMLClass, and of aCallBehaviorActionasactivity.PropertyNames.OWNERfires for neither. - Applying a stereotype to a definition reports no event at all on the usages that refer to it,
which is why a rule sweeps back from the definition when
appliedStereotypechanges on it.
Raise the resource's category to debug, reproduce the modelling action in the tool, and read what
fires. An installed engine traces every committed transaction under the rule set's own category, and
appends each rule's verdict for every candidate the event brings into scope:
── trace #7 [commit] project "Demo" — 3 events (addTransactionCommitListener)
[1] type | src=Property "speed" (…41088_3224) | old=null | new=Class "Concept B" «Concept» (…9163_3258) | owner=Class "Holder" «Concept» | rule=Attribute MATCH(apply) ✓owner:Class "Holder" «Concept» ✓type:Class "Concept B" «Concept»The verdict is computed from the rule's candidates rather than from the event's source, so a sweep-back from a definition is visible in the trace.
Anvil: trace model events covers the block format, the three channels and their levels, and how to install a trace in a plugin that has no engine yet — which is what a rule author does before the first rule exists.
5. Label the conditions
Conditions are declared as a list rather than folded into one boolean, because two readers need them. The engine reads the list as a conjunction and applies the stereotype once every condition holds. The tracer reads the identical list and prints which label failed and what it found, so a trace can never describe a rule differently from the way the engine evaluates it.
The condition(label, value) { … } helper guards the probe and handles a missing value. A null value
never satisfies a condition and renders as unset, which separates a Property carrying no type from
one typed by something the rule rejects.
Two safeguards live in AutoStereotypeRule rather than in any one rule, and both exist so that a
rule which cannot be evaluated never writes. A rule declaring no conditions has stated no reason to
apply and matches nothing. A rule whose own code throws while evaluating a candidate yields no match,
rather than letting an exception reach the transaction that is committing.
What the engine guarantees around the rule
Four guarantees hold for every rule, so a rule states its own decision and nothing else:
- One undo step. The engine plans while the transaction commits and writes from the
Runnablethe listener returns, so its writes join the committing session. - A rule that cannot be evaluated never writes. A rule declaring no conditions matches nothing, and any failure while evaluating a candidate yields no match.
- A doomed candidate is dropped. An element the same transaction deletes is never stereotyped.
- One element fails alone. A read-only element is reported against itself and the batch continues, so the rest of an edit is still stereotyped.
Each rule's switch appears in Project Options as one entry in the group named by groupLabel,
present only in a project that carries the resource's profile. The switch is read fresh on every
transaction, so a modeller who flips it mid-session is obeyed from the next edit.
A profileUri that does not match the profile in the model silences every rule of the set, in
every project. The engine skips a project whose used profiles do not include that URI, before it
reads a single switch, and it says so at debug once per committed transaction:
"Demo" carries no ACME profile — 3 events ignoredThe line names groupLabel rather than the URI, so it reads as a project that lacks the profile even
when the project has it and the URI is the typo. Compare the URI against the one the profile carries
in the model — the same string the generated bindings expose as AcmeProfile.uri — rather than
against the profile's name.
How auto-stereotyping works explains why the engine is built this way, including the channel it registers on and the session it writes in.
Suspend the rules around an automation
An automation that edits the model commits a transaction like any other edit. The rules read that transaction and stereotype what it produced, which is rarely what an automation wants. Wrap it:
class GenerateStructure : DefaultBrowserAction("GENERATE", "Generate structure", null, null) {
override fun actionPerformed(event: ActionEvent) {
Main.engine.withRulesSuspended {
project.commit("generate structure") { generate(project) }
}
}
}commit closes the session when generate returns and cancels it when generate throws, including
an Error; Anvil: commit a model change states the rest of its
contract.
Close the session inside the block. The commit listener runs inside closeSession, on the thread
that closes the session, so an edit whose session closes after the block returns — deferred to
invokeLater, or handed to a background task — commits with no suspension in force and the rules
fire. Suspension is scoped to the calling thread for the same reason, which is what leaves a
modeller's own edit during a background automation still stereotyped.
An automation with no single lambda to wrap — one spanning a wizard's pages, or two menu actions —
calls suspendRules() and resumeRules() instead and owns the finally itself. Both forms nest, so
a helper that suspends inside an automation that already suspended returns to a suspended state.
Both calls must run on the same thread, and the finally that pairs them is mandatory, not
advisory. A suspendRules() whose resumeRules() never runs leaves that thread suspended for the
life of the application — on the thread that closes model edits, every later transaction goes
unstereotyped, visible only as a debug line per commit. A resumeRules() that runs on a different
thread does not repair this: it logs a warning that reads as a spurious call, while the thread that
actually suspended stays suspended. Prefer withRulesSuspended for exactly this reason, and reach
for the pair only when no single lambda spans the automation.
Suspension, the profile the rule set names and the Project Options switch are three gates, and all
three must pass before a rule writes. A project that does not use the profile profileUri names is
skipped before any switch is read. Suspending turns nothing on: a rule the modeller switched off
stays off. See Three gates, in
order.
A suspended region silences the planning, not the event tracer. A trace read at debug (§4) still
prints MATCH(apply) for a candidate a suspended region then drops, because the tracer watches every
event regardless of the gate. The auto-stereotyping is suspended line the listener writes at the
same level is what resolves the apparent contradiction: it names the transaction the trace's
MATCH(apply) did not, in fact, apply.
When the engine changes
A rule's trigger set comes from a recorded trace, so a change to the engine that alters which events
reach candidatesOf invalidates every rule already written against it. Re-record the traces for the
affected rules rather than reasoning about the difference.
Related
- How auto-stereotyping works — the engine behind this contract, and why each part of it is shaped that way.
- Anvil: trace model events — reading the trace §4 depends on, with or without an engine.
- Anvil: log from a resource — the category the engine and tracer write under, and how to raise it.
- Anvil: use profile bindings — the bindings a rule's
conditionsandapplyStereotypeare written against. - Open API: add a project option — the tool's own API for the Project Options switch each rule is read from.