Skip to content

Behaviors and decorations for Flecha 0.4

Status: accepted by IFG 2026-0006; typed decorations, behavior declarations, bounded reflection, concrete derivation, and ordinary lowering are implemented. JSON serialization now belongs to library behaviors; the compiler-owned derivation path has been removed.

The compiler resolves behavior ownership, interface roots, method contracts, and direct activation candidates. Each activation has a BehaviorExpansionPlan with typed metadata, source-ordered field descriptors, closed T/F bindings, substitutions, selected bodies, and source provenance. Repeated field types have distinct descriptor identities; closed generic targets have separate plans.

Expansion is a transaction. The complete union of explicit and behavior roots must satisfy ordinary interface composition rules before provider selection. Exact handwritten implementations win and must carry override. Their behavior bodies are never expanded or checked, even if those bodies contain invalid reflection. Different method keys remain ordinary overloads; a same-key incompatible return, borrow, visibility, or effect contract is diagnosed by the ordinary interface rules rather than suppressing a body.

All selected signatures are registered before checking missing requirements or expanding any body. This permits forward sibling calls, self/mutual recursion, inherited defaults/finals, and qualified interface calls. Surviving bodies are ordinary compiler-owned functions, using the same access, const, ownership, borrow, initialization, allocation, generic, and effect checks as handwritten methods. Failed transactions expose neither partial methods nor conformance.

Generated concrete calls use ordinary direct resolution. Interface references, casts, composed tables, receiver adapters, and variadic slots use the existing interface ABI. Expansion changes no concrete fields or layouts and allocates no runtime metadata. Only ordinary scalar values and projected expressions survive reflection folding. Analyzer definitions and diagnostics map generated locations to behavior source, activating applications, targets, and fields.

for<F> Field<T,F> field = T::fields() has a dedicated AST node. The contextual operations name, decorated, decorator, and get are bounded compile-time operations. Metadata predicates fold before checking the selected branch. Missing metadata guards, descriptor escapes, invalid operations, and unsupported loop transfers are errors. proceed skips the current expanded field and break exits the field iteration. jumpto remains rejected.

JSON uses these same general interfaces and behaviors. See JSON library migration for the retired compiler contract and consumer API changes.

Behaviors let a library derive an interface implementation for a structure or enum from typed decoration metadata. They are deliberately narrower than macros or general compile-time execution. A behavior may add declared interface conformance and provide receiver-method bodies for that contract; it may not invent an unrelated public API or rewrite the decorated declaration.

The model has three separate responsibilities:

  • a decoration declares the applications and typed metadata accepted in source;
  • an interface declares the callable contract visible to ordinary Flecha code; and
  • a behavior derives conformance and implementations for a decorated structure or enum.

Behavior bodies are Flecha bodies. The only special iteration facility currently specified is bounded, typed iteration over the direct fields of a structure target. There is no dynamically typed meta language and no general meta execution mode.

A behavior-capable decoration declares every accepted application shape. The JSON decoration needs a structure marker and a field-name override:

export decoration json {
application(structure) target structure;
application(stringv name) target structure::field;
application(stringv name) target enum;
};

The declarations accept the existing applications:

@json(structure)
structure Response {
i32 value;
@json("display-name") string name;
};

structure in the first application is the literal marker used by @json(structure). stringv name in the second form is a named, typed compile-time argument. An application argument must be a compile-time value of its declared Flecha type. Its value is metadata; declaring or applying the decoration does not execute code.

Target validation is declaration-driven. The compiler rejects the wrong argument count or type, an unsupported target kind, duplicate applications where the decoration does not permit them, and inaccessible decoration names before expanding a behavior.

The initial target categories are structure, structure::field, enum, and interface. The qualified structure::field spelling makes the field’s owner explicit and avoids confusing a compile-time field descriptor with runtime member access. The initial contract permits at most one application signature for each target category. This keeps typed metadata lookup unambiguous. Tagged application alternatives can be designed later if a concrete use requires them.

Decorations may also target an interface:

export decoration protocol {
application(stringv name) target interface;
};
@protocol("transport")
interface Transport {
error send(&self) virtual;
};

An interface-target application is typed metadata only. It cannot activate a behavior, add or replace methods, change interface composition, or propagate to descendant interfaces or conforming concrete types.

A behavior does not list arbitrary methods to attach to a target. The library first declares ordinary interfaces using the v0.4 interface model:

export interface JsonWritable {
error writeJson(&const self, &Writer writer) virtual;
(own []u8, error) json(&const self) default;
};
export interface JsonReadable {
error readJson(&self, &Reader reader) virtual;
};

The convenience writer remains an ordinary receiver default:

(own []u8, error) JsonWritable::json(&const self) {
Writer writer = Writer::init();
error err = self->writeJson(&writer);
if err != none {
return (none, err);
}
return writer.finish();
}

This body is normal Flecha and its call to writeJson dispatches according to the interface rules. It is not expanded once per field and has no special access to decoration metadata.

Interfaces continue to contain receiver signatures only. Construction is a type-level operation and is expressed by an ordinary generic function rather than a static interface requirement:

export (T, error) from<T: JsonReadable>([]const u8 source) {
T value = T::zero();
Reader reader = Reader::init(source);
error err = value.readJson(&reader);
if err != none {
return (move value, err);
}
err = reader.finish();
return (move value, err);
}

A caller names both the operation’s module and the constructed type:

(Response response, error err) = json::from<Response>(source);

The generic function is checked through normal specialization. If its body requires T::zero(), the supplied type must support that operation. There is no Self placeholder, static virtual dispatch, or call through an erased interface reference.

The JSON behavior names its decoration, declares its concrete target kind, binds T to the affected type, and lists the interfaces it derives:

behavior json<T> => structure << JsonWritable, JsonReadable {
error T::writeJson(&const self, &Writer writer) override {
for<F> Field<T, F> field = T::fields() {
// Ordinary Flecha using this typed field projection.
}
}
error T::readJson(&self, &Reader reader) override {
for<F> Field<T, F> field = T::fields() {
// Ordinary Flecha using this typed field projection.
}
}
};

An enum behavior is declared separately:

behavior json<T> => enum << JsonWritable {
error T::writeJson(&const self, &Writer writer) override {
// No enum-variant reflection in v0.4.
return none;
}
};

T is the behavior’s one unconstrained target-type parameter. It cannot have a constraint, annotation, default, or second type parameter. It is unknown when the behavior is declared and is bound by the compiler to one concrete decorated target during expansion. Users cannot explicitly instantiate a behavior. => structure and => enum select the declaration kind; they are not generic constraints.

For a decorated Response, T is Response. In one field-loop expansion, F is the exact type of the current field. Given:

structure Response {
string name;
i32 status;
bool cached;
};

the compiler analyzes the loop body as if it had three typed expansions:

Field<Response, string>
Field<Response, i32>
Field<Response, bool>

T remains Response; F changes for each field. They participate in normal compile-time type checking but are not runtime type objects or dynamically typed meta values.

The << list is the complete public capability a behavior may add. Every method declared in the behavior must exactly implement or override a receiver method reachable from one of those interfaces. It must use override, and it is subject to the same signature, visibility, default, final, borrow, ownership, and effect rules as a handwritten structure implementation.

A behavior may omit an interface default and inherit it normally. It cannot replace a final method. It also cannot define a target method that is absent from its declared interface graph.

Behaviors may target structures and enums only. Applying a suitable decoration directly to either concrete type may activate its behavior. An application whose declared target is interface never does.

For a structure behavior, applying the decoration to a direct field associates that metadata with the field’s owning structure and may also activate the behavior. This preserves explicit JSON selection such as:

structure ExplicitResponse {
i32 ignored;
@json("value") i32 value;
};

Here T is ExplicitResponse even though the structure has no @json(structure) marker. The behavior decides, in Flecha, whether a structure-level application selects all eligible fields or field-level applications select only their fields.

Only applications written on the structure declaration or its direct fields belong to that structure behavior expansion. Nested structures are separate targets and must establish their own conformance. An enum behavior is activated by an application to the enum declaration itself. It may add its declared interface conformance and receiver-method implementations, but receives no variant or discriminant reflection. Variant-target activation and variant generation are also unavailable.

A behavior must be declared in the same logical module as its decoration. A decoration has at most one behavior for each supported concrete target kind. Importing another module cannot add or replace behavior for a decoration it does not own. This makes conformance coherent and prevents imports from retroactively changing a type’s API. A decoration that supports both kinds uses distinct => structure and => enum behavior declarations.

For a structure behavior, T::fields() is a contextual compiler intrinsic that produces a compile-time field pack, not a runtime collection.

for<F> Field<T, F> field = T::fields() {
// body
}

The compiler expands it in source declaration order and then type-checks each specialized body normally. An empty structure produces zero expansions. The loop supports proceed and break as described below. Neither Field<T, F> nor a field pack has a runtime representation. This exact loop form is valid only inside a behavior ... => structure method. It is not general compile-time iteration and is invalid in ordinary functions, interface bodies, and enum behaviors.

Field iteration may occur inside while, counted loop, and for ... range loops. Conversely, runtime loops may use reflected projections, metadata, and closed F types inside a field iteration. Expansion happens once per direct field at compile time; only the resulting ordinary code runs repeatedly. This does not introduce runtime descriptors or data-dependent expansion. Ordinary borrow, move, initialization, and effect checks apply to the expanded loops. Transfers target the nearest enclosing loop. When that loop is for<F>, proceed skips the rest of the current field’s expanded body; break skips all remaining fields and continues after the entire field iteration. A nested runtime loop retains ordinary break/proceed semantics. These transfers do not target an outer runtime loop. Ordinary cleanup applies on both paths. jumpto inside a field iteration remains prohibited.

Field-pack expansion and compile-time validations still run independently of runtime transfers. A runtime break does not suppress validation of later fields.

The loop variable is a unique compile-time descriptor type, not a runtime value and not the field’s value type. F is the value type. Two fields with the same F remain distinct through a hidden declaration identity, conceptually Field<T, F, FieldIdentity>, while source spells only Field<T, F>.

A field descriptor provides only bounded, typed information through type-level :: operations:

  • its owning type is T;
  • its field type is F;
  • field::name() is its source declaration name as a compile-time stringv;
  • field::isPrivate() is a compile-time bool, including fields declared in a private { ... } block;
  • field::decorated() reports direct presence of the behavior’s decoration;
  • field::decorator() exposes that application’s typed argument record; and
  • field::get(receiver) is a hygienic projection of that exact field; and
  • field::requireUnique(key) validates a compile-time stringv key against earlier keys in the same field iteration, without emitting runtime code.

The target type has corresponding direct-decoration operations:

T::decorated()
T::decorator()

These operations refer implicitly to the decoration that owns the current behavior. They cannot query an arbitrary other decoration. Because structure behavior may be activated by a field application alone, T::decorator() must be guarded by T::decorated(). The field form must likewise be guarded when field decoration is optional:

for<F> Field<T, F> field = T::fields() {
stringv name = field::name();
if field::decorated() {
name = field::decorator().name;
}
writer->write(name, field::get(self));
}

Calling ::decorator() without compile-time proof of presence is a compile-time error. Metadata branches fold before ordinary body analysis. For an enum behavior, activation requires a direct enum application, so the corresponding T::decorator() record is present.

The projection behaves like writing the concrete member access in source. A mutable receiver produces an assignable place; a const receiver produces a const place. Copying, moving, borrowing, assigning, or passing the result is then governed by the ordinary rules for F. Merely projecting a field does not copy or allocate it.

The typed record is not an untyped map, any value, raw syntax tree, or stringly typed argument. For JSON, field::decorator().name retains the declared stringv type. field::name() still reports the source field name; the decoration argument is a separate policy override.

Field iteration is available only inside structure-behavior implementations for their bound target. It does not provide module enumeration, base-address arithmetic, offset mutation, arbitrary member lookup by string, or reflection over unrelated types. A structure behavior body receives target-method access to the target’s private fields because applying the decoration is an explicit opt-in by the type author. The behavior may still inspect visibility and deliberately apply a public-only policy such as JSON’s v0.3 contract.

field::requireUnique(key); is a statement available only inside a bounded field iteration. Each expansion of a lexical for<F> owns a fresh key set. All validation sites in that loop share the set, including sites in different compile-time branches. Sets do not cross loops, methods, activations, or generic specializations. Validation follows field source order, and duplicate keys produce FLECHA-S0087 with the first and conflicting field locations, the behavior, and its activation.

The key must evaluate to stringv from string literals, field::name(), or typed decoration names using the existing scalar evaluator. Runtime locals, calls, and unresolved template names are rejected. Module constants can be passed through typed decoration arguments, where ordinary name resolution has already taken place. Equality compares the evaluated string contents exactly, including empty strings. Each reached validation statement registers a key; registering the same key twice, even for one field, is an error.

Selection must also be known at expansion time. Folded-away branches register no keys. A validation statement under an unresolved if, else if, else, or also condition, or inside a runtime loop, is rejected. Put compile-time validations before runtime iteration. Reflection remains prohibited in closures. Validation is performed when the method is expanded, regardless of whether runtime execution would reach the statement; it has no return value, cannot be deferred, and cannot escape into an expression. Exact handwritten providers still suppress the entire derived body, including its validations.

For example, a library can select public fields, support explicit-only field applications, and validate both renamed and original names together:

for<F> Field<T, F> field = T::fields() {
if !field::isPrivate() and (T::decorated() or field::decorated()) {
if field::decorated() {
field::requireUnique(field::decorator().name);
} else {
field::requireUnique(field::name());
}
// Emit the selected field using the same naming policy.
}
}

This operation does not introduce general compile-time execution, mutable reflection collections, nested field iteration, or JSON-specific compiler logic. JSON field-selection and duplicate-name policies are library code.

Compile-time requirements and type selection

Section titled “Compile-time requirements and type selection”

T::require(condition, message); and field::require(condition, message); validate a compile-time bool with a compile-time stringv message. A false condition reports FLECHA-S0088 using the supplied message and the behavior, activation, concrete target, and current field provenance. Both arguments must be constant even when the condition is true. These statements follow the same selection and suppression rules as requireUnique: runtime-controlled validation is rejected, folded-away validation is skipped, and no validation call or message is emitted into runtime code.

Within an expanded behavior, the existing expressions T.isof<Type> and F.isof<Type> query the concrete target or current field type. Closed types, interfaces (including ancestors), and type sets use ordinary isof matching rules. Queries on the field binder apply only inside its for<F> iteration. The result can select a branch before ordinary body analysis:

for<F> Field<T, F> field = T::fields() {
field::require(!field::isPrivate() or !field::decorated(),
"private fields cannot be decorated");
if F.isof<string> {
value, err := reader->readString();
if err == none { field::get(self) = value; }
} else {
// Only this branch forms a field reference for non-string fields.
readValue(reader, &field::get(self));
}
}

An owning slice can be matched with F.isof<own []Element> in an if or else if condition. A fresh unqualified Element binds the exact element type in the selected body only. Existing nominal types and already-bound type parameters remain exact match targets, rather than being rebound. Matching own []own []i32 binds Element to own []i32; matching own []const User preserves const User. Borrowed slices and fixed arrays do not match.

if F.isof<own []Element> {
value, err := readArray<Element>(reader);
if err != none { return err; }
field::get(self) = value;
}

The same pattern and selected-branch specialization work in generic helpers, allowing bounded recursive specialization for nested arrays. A pattern binding does not escape into alternatives, also, or following statements. Use the pattern as the direct branch condition; it is not a general declaration inside an arbitrary Boolean expression. Incompatible branches are discarded before ordinary semantic analysis. There is no runtime type test or type descriptor.

This does not permit references to owned strings, general compile-time calls, or reflection inside closures. New concrete generic types needed by closed query targets enter the existing expansion fixed point and are rolled back if the transaction fails.

Generic specialization may consult the nominal interface roots promised by a behavior applicable to a directly decorated structure, field, or enum. It resolves decoration identities and roots in their logical modules and includes inherited interfaces. Interface-target metadata and decorations on nested field types do not activate a behavior for the containing type.

This early query does not publish a conformance. Typed metadata, method contracts, conflicts, selected bodies, and ownership still pass the complete semantic transaction before concrete methods or conformances become usable. An invalid promise cannot make an otherwise invalid program compile. The same query is used for specializations discovered by generated bodies.

Generated and handwritten methods use the same interface-call ownership check. For signatures carrying managed values and references without exposing raw allocation handles, the allocation checker uses the interface contract rather than requiring a single concrete callee body. Provider bodies still undergo ordinary independent ownership validation. This supports, for example, a reader default method that passes &Reader to a protected virtual helper while Reader owns its internal storage.

This initial summary does not support raw pointers or raw buffers in interface parameters/results, including pointers nested in reference, array, slice, or tuple types. Such calls retain FLECHA-S0052, even with explicit own/lend annotations. It also rejects tracked raw aliases hidden in actual arguments. These restrictions do not change ordinary direct-call ownership contracts.

A mutable interface reference erases concrete object identity. The checker therefore conservatively invalidates tracked owning-field aliases across such a call and rejects conflicts with pending deferred uses. Const references do not invalidate those aliases. Deferred virtual calls apply these effects in cleanup order, rather than at registration. The checks can conservatively reject an alias of an unrelated owner when object identity cannot be proved.

See the JSON reader probe for the integration coverage and remaining library compatibility decisions.

An exact handwritten target implementation takes precedence over the matching behavior implementation. The compiler does not instantiate the derived body for that slot:

@json(structure)
structure Response {
i32 value;
};
error Response::writeJson(&const self, &Writer writer) override {
// Application-specific implementation.
return none;
}

The handwritten method must still be a valid override of the derived interface contract. A same-named method with a different signature is an overload and does not suppress behavior expansion.

All explicit and behavior-derived root conformances are combined before body selection and must satisfy the interface contract’s antichain, unique-path, and disjoint-MethodKey rules. Two active behaviors cannot merge the same canonical requirement, and a handwritten implementation cannot repair an invalid composition. Duplicate roots, related roots, shared ancestors, and horizontal slot collisions are rejected before behavior bodies are selected. Source order and decoration order never pick a winner.

After field-pack expansion, a behavior implementation is ordinary Flecha. It may:

  • add conformance only to the interfaces in its << list;
  • implement virtual methods and override defaults from those interfaces;
  • use locals, calls, control flow, overloads, generics, errors, and qualified interface calls;
  • inspect the direct fields and typed decoration metadata of T when T is a structure;
  • project structure fields through Field<T, F> under normal access, borrow, and ownership checking; and
  • call ordinary APIs that allocate, perform I/O, or have other effects when their signatures and the enclosing method permit those operations.

It may not:

  • add, remove, reorder, or change fields or otherwise alter target layout;
  • activate a behavior from an interface-target decoration or propagate that decoration through interface conformance;
  • enumerate, inspect, add, remove, or rewrite enum variants or discriminants;
  • invent methods outside its declared interface graph;
  • introduce types, interfaces, decorations, imports, or module members during expansion;
  • change visibility, lifecycle declarations, ownership contracts, or an existing method body;
  • replace a final method or bypass an unresolved virtual requirement;
  • generate identifiers or source from strings, inject raw tokens, or access an unrestricted syntax tree;
  • enumerate unrelated declarations, modules, files, processes, environment variables, the network, the clock, or compiler memory;
  • bypass type checking, definite assignment, borrowing, allocation checking, unsafe boundaries, or specialization budgets; or
  • leave runtime reflection data behind unless an ordinary declared API explicitly requires such data.

This boundary allows serialization, cloning, hashing, equality, visitors, and similar field-derived contracts without making every library package a compiler plugin.

Decoration metadata, field packs, and field descriptors exist only while the compiler expands and checks a behavior. They emit no runtime objects. Behavior-derived conformance uses the same static interface tables and two-word checked interface references as handwritten conformance. It does not add a hidden pointer to a structure or change an enum’s backing representation, and it does not allocate.

A behavior method can still call ordinary allocating code. JSON decoding may allocate owned strings and slices, and json() may allocate its result buffer. Those allocations come from the called Flecha APIs and retain their normal error and ownership contracts; they are not implicit costs of decorations, behaviors, field iteration, or interface conversion.

The compiler processes a behavior application in this order:

  1. resolve and type-check every decoration application;
  2. identify the concrete structure or enum target and bind T;
  3. add the behavior’s declared interface conformance edges;
  4. instantiate and register all candidate receiver signatures;
  5. validate the combined conformance roots, unique paths, and disjoint method sets before selecting any provider;
  6. select exact handwritten implementations and diagnose body conflicts;
  7. expand bounded field packs, binding a concrete F and field identity for each field;
  8. validate vertical method states and remaining virtual requirements;
  9. type-check every surviving body through the normal semantic pipeline; and
  10. lower only the resulting ordinary Flecha declarations.

An error in a specialized field body is reported at the decoration application with related context for the behavior source, field declaration, concrete T and F, and failed operation. Expansion obeys the existing generic depth, declaration, and token budgets. Exceeding a budget is a compile-time error.

Iteration-local jumpto remains deferred: it would require hygienic positions and boundary checks. break and proceed are supported as described above.

The initial design does not include:

  • static interface requirements or static behavior methods;
  • behavior-defined free functions or arbitrary associated methods;
  • behaviors targeting interfaces, fields independently of their owning structure, free functions, parameters, statements, or expressions;
  • enum-variant activation, generation, reflection, or a compile-time variant pack;
  • adding fields or lifecycle hooks;
  • variadic or tagged decoration application alternatives;
  • runtime reflection or dynamic decoration queries;
  • source-generating macros and unrestricted compile-time functions; or
  • a stable cross-compiler behavior-expansion ABI.

Type-level helpers such as json::from<T> remain ordinary library functions. If Flecha later gains extension functions or type-associated free functions, they can improve call-site spelling independently of the interface and behavior contracts.