ALF for C C++ Code Generation

This section describes the subset of ALF (Action Language for Foundational UML) supported by the code generators targeting C and C++. It is intended for end users writing code inside UML opaque behaviors, while still keeping the references required for implementation and validation.

This page discusses:

Introduction

Scope

The code generator accepts ALF expressions and statements written inside UML opaque behavior bodies and produces equivalent C or C++ code. The supported subset includes:

  • Literal, unary, binary, and navigation expressions
  • Assignment expressions (simple, compound, array)
  • Control-flow statements (if, while, for, break, return)
  • Operation invocations (virtual dispatch, receptions, global functions)

Out of scope: class declarations, package definitions, sequence/activity flow, and concurrency constructs.

Reference

For readers who need the formal background, the corresponding sections of the OMG ALF standard are indicated through references such as §8.x and §9.x:

Note:

OMG Action Language for Foundational UML (ALF), formal/17-07-04
Object Management Group, July 2017

UML Model Overview

ALF code is written inside UML Opaque Behaviors (operation bodies, state-machine effects, etc.). The code generator resolves names and types against the UML model.

Primitive Types

The following built-in types are available in ALF without any import:

ALF Primitive Description C Type C++ Type
Integer Whole numbers int int
Boolean True/false values int (0/1) bool
Real Decimal numbers double double
String Text values char* char*

Example Model

The examples used throughout this document rely on the following classes:

Alf Example MyClass

Expressions

Literal Expressions

Reference: OMG ALF §8.3 — LiteralExpression

Literal values are translated directly. The main difference between C and C++ is how booleans and null are represented.

ALF C C++
true 1 true
false 0 false
42 42 42
0 0 0
3.14 3.14 3.14
0.0 0.0 0.0
"hello world" "hello world" "hello world"
"" "" ""
"Say \"Hello\"" "Say \"Hello\"" "Say \"Hello\""
null NULL nullptr

Supported literal types: Boolean, Natural (integer), Real (decimal), String, Null.

Name Expressions

Reference: OMG ALF §8.4 — NameExpression

A bare name is resolved in the following order:

  1. Local variable — emitted as-is.
  2. Class property (implicit this) — prefixed with self-> (C) or this-> (C++).
  3. Enumeration literal — qualified name Enum.Literal is emitted as the unqualified literal name.
ALF C C++ Resolution
local local local Local variable
property self->property this->property Implicit this property
State.On On On Enumeration literal

This Expression

Reference: OMG ALF §8.5 — ThisExpression

The this keyword references the current object instance.

ALF C C++
this.value self->value this->value

In C, this is translated to self (the pointer parameter passed to C functions implementing class operations).

Property Access Expression

Reference: OMG ALF §8.6 — PropertyAccessExpression

Property access depends on the target language, the class layout, and whether the property is read-only or inherited.

Standard Layout (vtable)

ALF C C++
this.attr self->attr this->attr

Const Vtable Layout

When using the const_vtable class layout, read-only properties are stored in a constant part:

ALF C (const_vtable) Description
this.attr (read-only) self->constPart->attr Read-only property in const part
this.attr (mutable) self->attr Mutable property, direct access
this.attr (class-typed, read-only) self->constPart->attr Class-typed read-only property

Superclass Properties

You can access properties inherited from a superclass through the extension structure:

ALF C (const_vtable) Description
this.attr (from SuperClass, mutable) self->extended_class_SuperClass->attr Inherited mutable property
this.attr (from SuperClass, read-only) self->extended_class_SuperClass->constPart->attr Inherited const property

Array Property Access

ALF C C++
customer.address[i] customer->address[i] customer->address[i]

Invocation Expressions

Reference: OMG ALF §8.7 — InvocationExpression, FeatureInvocationTarget

Operation Calls (Virtual Dispatch)

Operations are dispatched through the vtable. The self/this pointer is passed as the first argument in C.

Note:

Model context: MyClass owns operation computeValue(p: Integer): void.

ALF C (vtable) C++
this.computeValue(42) self->vtable->computeValue(self, 42) this->computeValue(42)

With const_vtable layout:

ALF C (const_vtable)
this.computeValue(42) self->constPart->vtable->computeValue(self, 42)

Subclass operations resolve through the same vtable mechanism — the vtable pointer is shared.

Reception Calls (Signal/Event Sending)

Receptions (UML signals) are translated to event structures sent through the Target Abstraction Layer (TAL).

Note:

Model context: Light owns receptions On(), Off() backed by state machine Light; MyClass has association light: Light.

ALF:

evPushPressedAndReleased();

C:

Tal_Event_evPushPressedAndReleased evt;
evt.super.size = sizeof(evt);
evt.super.eventId = CONTROLLER_CLS_EVENT_T_evPushPressedAndReleased;
evt.super.type = Tal_Event_Type_SignalEvent;
tal_sendEvent(&self->controller_cls_stm_inputEvents, (Tal_Event*)&evt);

C++:

Tal_Event_evPushPressedAndReleased evt;
evt.super.size = sizeof(evt);
evt.super.eventId = CONTROLLER_CLS_EVENT_T_evPushPressedAndReleased;
evt.super.type = Tal_Event_Type_SignalEvent;
tal_sendEvent(&this->controller_cls_stm_inputEvents, (Tal_Event*)&evt);

Receptions on other objects use the target’s state machine input event queue:

ALF: light.On()
C: tal_sendEvent(&self->light->Light_Light_inputEvents, (Tal_Event*)&evt);

Global Function: WriteLine

The ALF global function WriteLine is translated to tal_printf with format string construction:

ALF C / C++
WriteLine("Hello") tal_printf("Hello\n")
WriteLine("Hello " + who + " " + IntegerFunctions::ToString(i)) tal_printf("Hello %s %d\n", self->who, self->i) (C)

Type-specific ToString calls are replaced by format specifiers: %s (string), %d (integer, Boolean), %f (Real).

Unary Expressions

Numeric Unary (Reference: OMG ALF §8.8 — NumericUnaryExpression)

ALF C C++
+1234 +1234 +1234
-42 -42 -42

Boolean Unary (Reference: OMG ALF §8.8 — BooleanUnaryExpression)

ALF C C++
!value !value !value

Increment / Decrement (Reference: OMG ALF §8.9 — IncrementOrDecrementExpression)

ALF C C++
++value ++value ++value
value++ value++ value++
--value --value --value
value-- value-- value--

Arithmetic Expressions

Reference: OMG ALF §8.10 — UnaryOrMultiplicativeExpression

All arithmetic operators translate directly:

ALF C C++
amount * interestRate amount * interestRate amount * interestRate
duration / timeStep duration / timeStep duration / timeStep
length % unit length % unit length % unit
initialPosition + positionChange initialPosition + positionChange initialPosition + positionChange
basePrice - discount basePrice - discount basePrice - discount

Operator precedence: *, /, % bind tighter than +, - (standard C/C++ precedence).

Relational Expressions

Reference: OMG ALF §8.11 — RelationalOrClassificationExpression

ALF C C++
sensorReading > threshold sensorReading > threshold sensorReading > threshold
size < maxSize size < maxSize size < maxSize
size >= minSize size >= minSize size >= minSize
count <= limit count <= limit count <= limit

Equality Expressions

Reference: OMG ALF §8.12 — ClassificationOrEqualityExpression

ALF C C++
errorCount == 0 errorCount == 0 errorCount == 0
nextRecord != endRecord nextRecord != endRecord nextRecord != endRecord
list.next == null list->next == NULL list->next == nullptr

Logical Expressions

Reference: OMG ALF §8.13 — InclusiveOrOrConditionalAndExpression

Both && and || use short-circuit evaluation, as in C/C++.

ALF C C++
index > 0 && value[index] < limit index > 0 && self->value[index] < limit index > 0 && this->value[index] < limit
index == 0 \|\| value[index] >= limit index == 0 \|\| self->value[index] >= limit index == 0 \|\| this->value[index] >= limit

Assignment Expressions

Reference: OMG ALF §8.14 — AssignmentExpression

Simple Assignment

ALF C C++ Context
result = 42 result = 42 result = 42 Local variable
name = "John" self->name = "John" this->name = "John" Class property

Array Element Assignment

ALF C C++
customer.address[i] = newAddress customer->address[i] = newAddress customer->address[i] = newAddress

Compound Assignment

ALF C C++
x += 4 x += 4 x += 4

Supported compound operators: +=, -=, *=, /=, %=.

Parenthesized Expressions

Reference: OMG ALF §8.3 — ParenthesizedExpression

Parentheses are preserved to maintain operator precedence:

ALF C C++
((5 + 2) * 3) / 2 ((5 + 2) * 3) / 2 ((5 + 2) * 3) / 2

Statements

Empty Statement

Reference: OMG ALF §9.5 — EmptyStatement

An empty input produces no output.

Expression Statement

Reference: OMG ALF §9.7 — ExpressionStatement

Any expression followed by ; is a valid statement:

ALF C C++
this.value; self->value; this->value;

Block Statement

Reference: OMG ALF §9.4 — Block

Blocks are enclosed in braces with consistent four-space indentation.

Empty block:

ALF C / C++
{} { }

Single statement:

ALF C
{ x = 42; } { self->x = 42; }

Multiple statements:

ALF C C++
{ x = 42; y = "hello"; z = true; } { self->x = 42; self->y = "hello"; self->z = 1; } { this->x = 42; this->y = "hello"; this->z = true; }

Nested blocks are supported with incremental indentation.

If Statement

Reference: OMG ALF §9.8 — IfStatement

Simple If

ALF:

if (x > 0) {
    y = 1;
}

C / C++:

if (x > 0) {
    y = 1;
}

If / Else

ALF:

if (x > 0) {
    y = 1;
} else {
    y = -1;
}

C / C++:

if (x > 0) {
    y = 1;
} else {
    y = -1;
}

If / Else-If Chain

ALF:

if (x > 0) {
    y = 1;
} else if (x < 0) {
    y = -1;
} else {
    y = 0;
}

C / C++:

if (x > 0) {
    y = 1;
} else if (x < 0) {
    y = -1;
} else {
    y = 0;
}

Nested if statements are supported with incremental indentation.

While Statement

Reference: OMG ALF §9.10 — WhileStatement

ALF:

while (x > 0) {
    x--;
}

C / C++:

while (x > 0) {
    x--;
}

ALF:

while (true) {
    if (done) {
        break;
    }
}

C:

while (1) {
    if (done) {
        break;
    }
}

C++:

while (true) {
    if (done) {
        break;
    }
}

Note: true in a while condition maps to 1 in C and true in C++.

Do Statement

Reference: OMG ALF §9.11 — DoStatement

The body of a do statement runs before its condition is evaluated, so it always executes at least once. The trailing semicolon is part of the statement.

ALF:

do {
    x--;
} while (x > 0);

C / C++:

do {
    x--;
} while (x > 0);

ALF:

do {
    if (done) {
        break;
    }
} while (running);

C / C++:

do {
    if (done) {
        break;
    }
} while (running);

A local name declared in the body is still in scope in the condition, which is why the condition is generated after the block. Nested do loops are supported with incremental indentation.

For Statement

Reference: OMG ALF §9.12 — ForStatement

Range-Based for (i in 1..N)

The range expression is translated into a standard for loop in both languages:

ALF C C++
for (i in 1..5) { total = total + i; } for (int i = 1; i <= 5; i++) { total = total + i; } for (int i = 1; i <= 5; i++) { total = total + i; }

Collection-Based for (item in collection)

Collection iteration differs between C and C++.

Note:

Model context: MyClass owns property items: Integer [0..10] (array of up to 10 integers).

ALF:

for (item in items) {
    total = total + item;
}

C — index-based loop with element extraction:

for (int i = 0; i < 10; i++) {
    int item = self->items[i];
    total = total + item;
}

C++ — range-based for:

for (int item : this->items) {
    total = total + item;
}

Break Statement

Reference: OMG ALF §9.13 — BreakStatement

break; translates directly to break; in both C and C++. Supported inside while and for loops.

Return Statement

Reference: OMG ALF §9.14 — ReturnStatement

ALF C C++
return; return; return;
return 42; return 42; return 42;

Early return patterns (return inside if) are supported:

ALF:

if (x) {
    return 0;
}
return 42;

C / C++:

if (x) {
    return 0;
}
return 42;

C-specific Generation Rules

In-line Statement

An in-line statement embeds native code, written for one target language, directly in an opaque behavior body (Reference: OMG ALF §9.3 — InLineStatement). The opening /*@ is reserved by the ALF lexical rules: it is not a comment. The header names the language (C, or 'C++' quoted as in the specification; Cpp is accepted too) and may carry a trailing // comment; a line terminator must follow the header. Everything up to the closing */ is the native code, kept verbatim.

The generator of the named language emits the code as it is, at the current indentation; the generator of the other language leaves a one-line trace comment instead, so a body can carry a C section and a C++ section side by side. The simulation ignores in-line code for a language it does not execute. Unlike the legacy SOP_Start/SOP_End tags, an in-line statement is a statement among the others: the ALF around it is still generated.

ALF:

this.time = this.time + 1;
/*@inline(C)
Timer_reset(&self->t);
*/
/*@inline('C++')
this->t.reset();
*/

C:

self->time = self->time + 1;
Timer_reset(&self->t);
// @inline(C++) omitted for this target

C++:

this->time = this->time + 1;
// @inline(C) omitted for this target
this->t.reset();

Generation-off Region

A generation-off region marks ALF that exists for the CATIA Magic simulation only: the region opens with a comment holding only @generation(off) — //@generation(off), // @generation(off) or /* @generation(off) */, alone on its line — and closes the same way with @generation(on), or with the end of the body. The generator never parses the region — it is skipped as raw text, so it may use any ALF construct the simulator accepts, beyond the subset supported here — and renders it as documentation comments in the generated code, one comment line per ALF line under a header naming the marker. The type checker does not look at it either; CATIA Magic validates it.

An in-line statement inside the region is an island: it is parsed and emitted as code, and the region resumes after it, until the closing marker. Together, @generation(off) and @inline express simulated one way, generated another: the simulation runs the ALF, the target runs the native code. A (on) marker without a preceding (off), and an (off) marker inside an open region, are reported as errors.

ALF:

x = x + 1;
//@generation(off)
this.display.show(x);
let msg = "tick " + x;
//@generation(on)
/*@inline(C)
DISPLAY_show(self->x);
*/

C:

self->x = self->x + 1;
// @generation(off): ALF simulated by CATIA Magic, not generated
//   this.display.show(x);
//   let msg = "tick " + x;
// @generation(on)
DISPLAY_show(self->x);

Self Pointer

In C, the current instance is accessed via self, a pointer parameter passed to all class operation functions. ALF this maps to self.

Virtual Dispatch

Operations are dispatched through a vtable pointer stored in the instance structure:

  • vtable layout: self->vtable->operation(self, args)
  • const_vtable layout: self->constPart->vtable->operation(self, args)

Object Allocation Modes

Two object allocation strategies are supported:

  • dynamic: Standard heap allocation with pointer-based member access.
  • static: Stack or statically allocated objects; class-typed properties are stored in a constPart segment.

Boolean Representation

ALF true → 1, ALF false → 0.

Null Representation

ALF null → NULL.

Superclass Access

Inherited properties are accessed through an extension pointer: self->extended_class_<SuperClassName>->property.

For read-only inherited properties with const_vtable layout: self->extended_class_<SuperClassName>->constPart->property.

Reception → TAL Event Structure

Each reception call generates a Tal_Event_<SignalName> structure, sets the event metadata (size, eventId, type), and sends it via tal_sendEvent.

WriteLine → tal_printf

The WriteLine function is translated to tal_printf with automatic format string construction based on argument types.

C++-specific Generation Rules

This Pointer

ALF this maps to C++ this directly.

Member Access

All member access uses -> (pointer to member), matching the C++ object model where instances are pointer-based.

Native Boolean

ALF true/false map to C++ true/false.

Null Representation

ALF null → nullptr.

Range-Based for Loops

Collection iteration uses C++ range-based for: for (Type item : this->collection).

Range iteration (i in 1..N) still uses a standard index-based for loop.

Reception → TAL Event Structure

Same structure as C, but using this-> instead of self-> for member access.

Appendix

ALF Operator Precedence

Precedence Operators Associativity Description
8 (highest) !, +, - (unary), ++, -- Right Unary operators
7 *, /, % Left Multiplicative
6 +, - (binary) Left Additive
5 <, <=, >, >= Left Relational
4 ==, != Left Equality
3 && Left Logical AND
2 \|\| Left Logical OR
1 (lowest) =, +=, -=, *=, /=, %= Right Assignment

Parentheses () override precedence at any level.

Reference Mapping

Each ALF concept documented here is mapped to the corresponding section of OMG ALF formal/17-07-04 and verified by JUnit tests using @Tag("covers:<ConceptName>") annotations.

Documented concept ALF reference section C tests C++ tests
LiteralExpression §8.3 11 11
NameExpression §8.4 3 3
ThisExpression §8.5 9 4
ParenthesizedExpression §8.3 1 1
PropertyAccessExpression §8.6 6 1
InvocationExpression §8.7 7 7
FeatureInvocationTarget §8.7 3 3
NumericUnaryExpression §8.8 2 2
BooleanUnaryExpression §8.8 1 1
IncrementOrDecrementExpression §8.9 4 4
UnaryOrMultiplicativeExpression §8.10 5 5
RelationalOrClassificationExpression §8.11 4 4
ClassificationOrEqualityExpression §8.12 3 3
InclusiveOrOrConditionalAndExpression §8.13 2 2
AssignmentExpression §8.14 4 4
EmptyStatement §9.5 1 1
ExpressionStatement §9.7 1 1
Block §9.4 5 5
IfStatement §9.8 7 7
WhileStatement §9.10 5 5
DoStatement §9.11 5 4
ForStatement §9.12 3 3
BreakStatement §9.13 6 6
ReturnStatement §9.14 4 4

Detailed Test Logs

The complete ALF → C and ALF → C++ translation tables, auto-generated from the JUnit tests, are available in:

  • ALF for C code generation examples
  • ALF for C++ code generation examples