API Reference

Most functions below are runtime builtins: Julia versions of MetaModelica's builtin functions for code translated from MetaModelica. Pattern matching needs only the macros; see Pattern matching.

MetaModelica.globalRoots — Constant

Sets the index of the root variable with index 1..1024 This is a global mutable value and should be used sparingly. You are recommended not to use "missing" the runtime system treats this values as uninitialized and fail getGlobalRoot later on.

source
MetaModelica.SOME — Type
SOME(x)

An optional value that is present: Julia's Some (SOME === Some, the value is x.value). With nothing it forms Option. Base converts a Some{S} to an Option{T} for S <: T.

source
MetaModelica._exprReadsWrittenFields — Method

Return true when expr syntactically reads a field of sym that has already been written in the pending batch. A bare sym reference (e.g. foo(sym)) is treated as a read of every field, since the call may read anything, so it triggers a flush whenever any write is pending. Field accesses sym.f are matched against writtenFields by top-level field name. quote ... end and QuoteNode contents are skipped.

source
MetaModelica._topFieldAccessOf — Method

If expr has the form sym.f, sym.f.g, sym.f.g.h, ..., return the top-level field (the segment immediately under sym). Otherwise return nothing. The "top" is the deepest segment in the chain whose base is sym, since getproperty(getproperty(sym, :f), :g) reads sym.f first.

source
MetaModelica._withLine — Method

Wrap inner in a :block Expr prefixed with ln so Julia attaches the source location to the synthesized code. Falls back to inner if ln is nothing.

source
MetaModelica.arrayAppend — Method

Appends arr2 to arr1. O(length(arr1) + length(arr2)). Note that this operation is not destructive, i.e. a new array is created.

source
MetaModelica.arrayElemType — Method
arrayElemType(T)

The element type of an array made from values of type T: T, except that a list (Cons or Nil) gives List. An array<list<T>> starts from {} or a first list and later holds nil and other lists; typed after its seed (Nil{Any}, Cons{Int}) it could not store them.

source
MetaModelica.assignBlockFunc — Method

Block form of @assign. Walks blockExpr.args, groups consecutive field-assignments by their root variable, and folds each group into a single Accessors.setproperties call so the root struct is reallocated exactly once per group. Plain name = rhs assignments and other statements are emitted verbatim and act as group separators. Each synthesized call carries the source line of the last assignment that contributed to it, so stack traces point to user code.

source
MetaModelica.assignFunc — Method

Helper function for the assignmacro, see @assign We have one case where we assign a immutable structure to an immutable structure or something to a primitive variable. If it is not a primitive we assign to a subcomponent of that structure. We then clone the structure with that particular field changed.

source
MetaModelica.buildPatchExpr — Method

Build a NamedTuple-literal Expr representing the patch for a (sub)object. readExpr is an already-escaped Expr that reads the (sub)object the patch is applied to; it is used to construct readExpr.fieldName for nested sub-objects so that recursive setproperties calls share the same root read.

updates is a vector of (path::Vector{Symbol}, rhs, line) whose first path segment selects the field within this NamedTuple. The line carries the LineNumberNode of the originating assignment and is attached to any synthesized intermediate code so stack traces point to user source. A direct overwrite of a field (empty remaining path) supersedes any nested updates that came before it; nested updates that follow the direct overwrite are applied on top of the overwritten value via a let binding so the RHS is evaluated once.

source
MetaModelica.compacted_tag_info — Method
compacted_tag_info(ctor) -> (StructType, tagfield::Symbol, tagvalue, fieldorder::NTuple{N,Symbol}) | nothing

Extension point for combined/tagged-union types: several conceptually distinct record types folded into ONE concrete struct with a tag field (needed for self- or mutually-recursive uniontype clusters, where every variant sharing one concrete type means @match's normal isa-based struct-pattern dispatch does not apply). A generator targeting this representation implements one method per variant CONSTRUCTOR FUNCTION (the value a pattern head like ADD evaluates to) returning (StructType, tagfield, tagvalue, fieldorder); @match/@matchcontinue then compile a ADD(a, b) => ... pattern into a getfield(obj, tagfield) === tagvalue comparison plus getfield-based destructuring of fieldorder, instead of value isa ADD. Default nothing (ordinary struct-type patterns are unaffected).

source
MetaModelica.decomposeAssign — Method

Decompose an assignment of the form name.f1.f2... = rhs into (name::Symbol, [:f1, :f2, ...], rhs). Returns an empty path for the bare name = rhs. Returns nothing when the LHS is anything else (indexing, destructuring, ...) so the caller can fall through to the verbatim form.

source
MetaModelica.genShouldFail — Method

This function implements the @shouldFail macro. @shouldFail(arg) succeeds if arg fails, where arg is a local match-equation/statement.

source
MetaModelica.handleSugar — Method

Handle syntactic sugar for MetaModelica mode. Mostly lists but also for the optional type. Parenthesis for these expressions are skipped

source
MetaModelica.handle_fast_match — Function

Helper function for @fastmatch.

Strategy. For each case T(p1, p2, ...) => rhs, generate a Julia method <value>Func(<value>::T) that destructures <value> into the named bindings and evaluates rhs. Dispatch among the cases happens via Julia's multiple-dispatch on the runtime type of <value>.

Supported pattern shapes inside the struct call:

  • positional Symbol bindings, e.g. T(x, y) binds x = obj.field1, y = obj.field2 using fieldnames(T) order.
  • _ and __ placeholders skip the corresponding field.
  • keyword bindings field=name bind name = obj.field.

Unsupported shapes raise at macro-expansion time (literal patterns, nested patterns, where guards). Two cases dispatched on the same struct type overwrite the same generated method.

source
MetaModelica.handle_match_case — Method

Handles match cases both for the matchcontinue and regular match case calls handledestruct. See handledestruct for more details. subject: the matched variable of a @match whose value is a plain variable, narrowed in each case's body (subjectNarrowing); nothing otherwise. swallowHook: a function called as swallowHook(caseNumber, exception, caseText) when a @matchcontinue case swallows an exception (MM_Debug passes its logger); nothing adds no code.

source
MetaModelica.isPresent — Method

TODO: I am far from sure that this will fly.. in Julia. The code generated from the transpiler is correct however

source
MetaModelica.isvariant — Method
isvariant(value, variant) -> Bool

value isa variant that also works for compacted uniontypes. variant is either a type (an ordinary @Record) or a constructor function registered through compacted_tag_info (@CUniontype, @T_Uniontype or hand-written). For a constructor the check is a tag comparison and constant-folds.

source
MetaModelica.mm_throw — Method
mm_throw(e)

Throw e; without recording a backtrace inside a with_cheap_throws scope, when the exception being handled there is a control-flow value.

source
MetaModelica.reportUnexpectedInMatch — Method
reportUnexpectedInMatch(e, backtrace) -> Nothing

Prints an exception that a matchcontinue case does not retry on (not a MetaModelica or ImmutableList failure) before the case rethrows it. The expanded matches call it through invokelatest: a direct call compiled the backtrace printer (Base.show_backtrace) into every function with a matchcontinue, and a package adding a method that the printer calls (ColorVectorSpace's reduce_first) invalidated all of them, and their callers, at each load (OMFrontend: 973 compiled methods, 2026-11-16).

source
MetaModelica.stringDelimitList — Method

O(str) Takes a list of strings and a string delimiter and appends all list elements with the string delimiter inserted between elements. Example: stringDelimitList({"x","y","z"}, ", ") => "x, y, z"

source
MetaModelica.stringInt — Method

Fails unless the whole string is a base-10 integer (omc's stringInt). A MetaModelica failure, so a matchcontinue tries its next case.

source
MetaModelica.stringReal — Method

This function fails unless the whole string can be consumed by strtod without setting errno. For more details, see man 3 strtod

source
MetaModelica.subjectNarrowing — Method
subjectNarrowing(subject::Symbol, pattern, calling_module) -> Union{Expr, Nothing}

subject isa T for the type T that a case's top-level pattern proves the matched value has: a struct pattern T(...), a compacted variant's struct, _::T, the pattern of a guard. nothing for the other patterns (wildcards, bindings, constants, tuples, lists, disjunctions).

A @match case adds it to its condition. The case tests a copy of the subject (value), and Julia narrows only the variable it tests, so reads through the subject in the case's body (iterator.current in @match iterator begin RANGE(__) => iterator.current end) were Any: dynamic calls that a package adding a method invalidates, with their callers, at each load (OMFrontend 2026-11-16). For @match the test gives the pattern's answer, since nothing assigns the subject between the copy and the case. @matchcontinue gets none: a failed case's body may have assigned the subject before a later case is tested.

source
MetaModelica.valueConstructor — Method

The return-value is compiler-dependent on the runtime implementation of boxed values. The number of bits reserved for the constructor is generally between 6 and 8 bits.

source
MetaModelica.valueSlots — Method

The number of slots a boxed value has. This is dependent on sizeof(void*) on the architecture in question.

source
MetaModelica.variantof — Method
variantof(value)

The variant of value: its type for an ordinary record, its constructor function for a compacted uniontype value. variantof(x) === CREF is the compacted counterpart of typeof(x) === CREF.

source
MetaModelica.with_cheap_throws — Method
with_cheap_throws(f)

Call f() in a scope where mm_throw (and so fail() and the match macros' failures) throws without recording a backtrace. A nested scope is the outer one. Opening a scope costs one ordinary throw (~0.1 ms on macOS): open it around a large computation, not per small task.

source
MetaModelica.@CUniontype — Macro
@CUniontype Name begin
  VARIANT1(field1::Type1, field2::Type2, ...)
  VARIANT2(...)
  ...
end

Declarative shorthand for the "compacted tagged struct" pattern: one concrete NameData <: Name struct with a tag @enum, instead of abstract type + N records, for self/mutually-recursive uniontype clusters. Expands to the struct, the tag enum, one constructor function per variant (positional and keyword forms), and the matching compacted_tag_info registration for each, so @match/@matchcontinue dispatch on VARIANT(...) patterns exactly as they would on ordinary struct-per-variant records. A field typed as Name (the uniontype's own name) becomes NameData, so the recursive spine is concrete. Nullary variants return a shared singleton.

Field layout is computed automatically: fields are collected across variants in first-seen order, and each variant's OWN field set must equal the first K entries of that shared order for some K (the #undef-via-partial-new() trick used to omit fields a variant doesn't need only works when the omitted fields are a common trailing suffix, not an arbitrary subset). This holds naturally for variants that form a chain of increasing detail (e.g. EMPTY(), WILD(), then CREF(name, subscripts, rest)); it does not hold for variants with genuinely disjoint fields, which errors at macro-expansion time rather than silently degrading. Use @T_Uniontype for those.

source
MetaModelica.@ExtendedFunction — Macro
@ExtendedFunction new old(arg = value, ...)

Define new: the positional arguments of old, with new defaults for the named ones, passed on to old. The Julia version of MetaModelica's function new = old(arg = value);, for the MetaModelica-to-Julia translator. old must be defined before the macro, and its defaults must be literals or constants.

source
MetaModelica.@T_Uniontype — Macro
@T_Uniontype [mutable] Name begin
  VARIANT1(field1::Type1, field2::Type2 = default, ...)
  VARIANT2()
  ...
end

Compacted uniontype for variants with DISJOINT fields (where @CUniontype's prefix rule does not hold). Expands to one concrete NameImpl <: Name struct (mutable struct with the mutable flag) holding a tag::NameTag plus the union of all variant fields in first-seen order, and per variant a constructor function, a compacted_tag_info registration (so @match patterns VARIANT(...) work), plus valueConstructor and variantof. Name is declared as an abstract type unless it already exists (for example through @UniontypeDecl Name).

Fields a variant does not have are filled with the field's default when some variant declares one (var::Int8 = Int8(0)), otherwise with nothing; only such a field (missing from some variant, no default) is typed Union{Nothing, Type}. A field typed with the uniontype's own name is typed as NameImpl.

Constructors: positional with all fields (VARIANT(a, b, c)), positional with trailing defaults left out, and keyword (VARIANT(; a, c)) where every defaulted field may be left out. Nullary variants of an immutable uniontype return a shared singleton.

source
MetaModelica.@assign — Macro

This macro reimplements the MetaModelica assignment semantics using setfield to assign to variables. For assignments using primitives, the regular Julia assignment is generated. For cases where deeply nested immutable structures are manipulated we use setfield E.g.: a.b.c = 5 Where a is a nested immutable struct

A begin ... end block form is also supported. Consecutive assignments to the same root variable are folded into a single setproperties call, reallocating the struct once instead of once per field.

julia @assign begin obj.a = 1 obj.b = 2 obj.c.x = 5 obj.c.y = 6 end

expands to one allocation for obj and one for obj.c. When a later assignment's RHS reads a field that an earlier assignment in the batch wrote (e.g. obj.b = obj.a after obj.a = 1), the macro flushes the pending writes first so the read sees the updated value. Reads of other fields of the same root (e.g. obj.b = obj.c while only obj.a has been written) do not cause a flush, so chains where every line reads and writes disjoint fields still collapse to a single setproperties call. The same flush happens before a non-field statement (x = obj.a) or any other expression in the block, so sequential read/write semantics are preserved across the entire block.

source
MetaModelica.@fastmatch — Macro

Patterns:

  • FOO(a,b)

  • BAR()

When using @fastmatch we limit the usage and only allow match on structs.

Here, the use variables that are not bound to the structs will result in errors, therefore, use this match option carefully.

source
MetaModelica.@fastmatch — Macro

Similar to match but more limited. Instead of handling everything within one function we generate a new function for each case. Hence, we limit the possible objects we can match on to structs.

Here we generate a function for each type with <function_name> Example:

@fastmatch <type-we-match-on> begin
             FOO(v) => v
             BAR(l, r) => l + r
             FOOO() => v
           end

This will result in the generation of the following functions:

function <type-we-match-on>Func(case::FOO)
  Foo.v
end

function <type-we-match-on>Func(case::BAR)
  l + r
end

function <type-we-match-on>Func(case::FOOO)
   v
end
source
MetaModelica.@instanceName — Macro
@instanceName

Macro form of getInstanceName that captures the enclosing function name at macro-expansion time. Embeds the name as a literal string so there is no runtime cost. Falls back to the file:line if the enclosing function is not statically resolvable. Use this in error-message construction where you previously typed getInstanceName().

source
MetaModelica.@match — Macro

Patterns:

* `_` matches anything

* `foo` matches anything, binds value to `foo`

* `foo(__)` wildcard match on all subfields of foo, binds value to `foo`

* `Foo(x,y,z)` matches structs of type `Foo` with fields matching `x,y,z`

* `Foo(x=y)` matches structs of type `Foo` with a field named `x` matching `y`

* `[x,y,z]` matches `AbstractArray`s with 3 entries matching `x,y,z`

* `(x,y,z)` matches `Tuple`s with 3 entries matching `x,y,z`

* `[x,y...,z]` matches `AbstractArray`s where `x` matches the first entry, `z` matches the last entry and `y` matches the remaining entries.

* `[x,y...]` matches `AbstractArray`s , where `x` matches the first entry, and `y` matches the remaining entries.

* `(x,y...,z)` matches `Tuple`s with at least 2 entries, where `x` matches the first entry, `z` matches the last entry and `y` matches the remaining entries.

* `_::T` matches any subtype (`isa`) of T

* `x || y` matches values which match either `x` or `y` (only variables which exist in both branches will be bound)

* `x && y` matches values which match both `x` and `y`

* `x where condition` matches only if `condition` is true (`condition` may use any variables that occur earlier in the pattern eg `(x, y, z where x + y > z)`)

* `x <| y` is syntactic sugar for `cons(x,y)` (See the ImmutableList package)

* Anything else is treated as a constant and tested for equality

Patterns can be nested arbitrarily.

Repeated variables only match if they are == eg (x,x) matches (1,1) but not (1,2).

source
MetaModelica.@match — Macro
  @match value begin
      pattern1 => result1
      pattern2 => result2
      ...
  end

Return result for the first matching pattern. If there are no matches, throw MatchFailure

source
MetaModelica.@match — Macro

@match pattern = value If value matches pattern, bind variables and return value. Otherwise, throw MatchFailure.

source
MetaModelica.@matchcontinue — Macro

Patterns:

* `_` matches anything

* `foo` matches anything, binds value to `foo`

* `foo(__)` wildcard match on all subfields of foo, binds value to `foo`

* `Foo(x,y,z)` matches structs of type `Foo` with fields matching `x,y,z`

* `Foo(x=y)` matches structs of type `Foo` with a field named `x` matching `y`

* `[x,y,z]` matches `AbstractArray`s with 3 entries matching `x,y,z`

* `(x,y,z)` matches `Tuple`s with 3 entries matching `x,y,z`

* `[x,y...,z]` matches `AbstractArray`s where `x` matches the first entry, `z` matches the last entry and `y` matches the remaining entries.

* `[x,y...]` matches `AbstractArray`s , where `x` matches the first entry, and `y` matches the remaining entries.

* `(x,y...,z)` matches `Tuple`s with at least 2 entries, where `x` matches the first entry, `z` matches the last entry and `y` matches the remaining entries.

* `_::T` matches any subtype (`isa`) of T

* `x || y` matches values which match either `x` or `y` (only variables which exist in both branches will be bound)

* `x && y` matches values which match both `x` and `y`

* `x where condition` matches only if `condition` is true (`condition` may use any variables that occur earlier in the pattern eg `(x, y, z where x + y > z)`)

* `x <| y` is syntactic sugar for `cons(x,y)` (See the ImmutableList package)

* Anything else is treated as a constant and tested for equality

Patterns can be nested arbitrarily.

Repeated variables only match if they are == eg (x,x) matches (1,1) but not (1,2).

source
MetaModelica.@matchcontinue — Macro
  @matchcontinue value begin
      pattern1 => result1
      pattern2 => result2
      ...
  end

Return result for the first matching pattern. If there are no matches, throw MatchFailure.

source
MetaModelica.@nospecialized — Macro
@nospecialized function name(a, b, ...; k = ..., ...)::R where {T, ...}
    ...
end

Rewrites a function definition so every positional and keyword argument is wrapped in @nospecialize, and the whole definition is wrapped in Base.@nospecializeinfer. The short form name(args...) = body, return-type annotations, where clauses, and keyword arguments are all supported.

Equivalent rewrite for a long-form definition:

@nospecializeinfer function name(@nospecialize(a), @nospecialize(b), ...; @nospecialize(k = ...))::R where {T, ...}
    ...
end
source
MetaModelica.@registerVariants — Macro
@registerVariants T begin
  VARIANT_A(field1, field2)
  VARIANT_B()
  ...
end

Register the variants of a hand-written tagged struct T for @match, isvariant and variantof.

@T_Uniontype and @CUniontype generate a struct, its tag @enum and its constructors from a variant list. This macro is for a struct written out in plain Julia instead (fields and constructors documented where they are defined); it generates only the registration, which is the same for every such struct.

What T must have:

  • a field tag holding a value of an @enum with one value per variant, named <VARIANT>_TAG (VARIANT_A_TAG), declared in the order the variants are listed here (the first is 0);
  • per variant a function VARIANT_A(...) returning a T with that tag, defined before this macro (the registration dispatches on typeof(VARIANT_A)).

Each variant is listed with its own fields, in the order of its positional arguments: the fields a pattern binds (VARIANT_A(x, y) binds field1 and field2; VARIANT_A(field2 = y) names one).

It expands to:

  • per variant MetaModelica.compacted_tag_info(::typeof(VARIANT_A)) = (T, :tag, VARIANT_A_TAG, (:field1, :field2)), what @match and isvariant read;
  • MetaModelica.valueConstructor(v::T) = Int(v.tag) and MetaModelica.variantof(v::T) = (VARIANT_A, VARIANT_B, ...)[Int(v.tag) + 1];
  • a check at load that Int(VARIANT_A_TAG) is the variant's position: an enum in another order is an error instead of a wrong match.

T is a type name; an alias of a concrete type (const Modifier = ModifierImpl{Tree}) works.

Example

@enum ShapeTag::UInt8 CIRCLE_TAG RECT_TAG

"""A shape: `CIRCLE(r)` or `RECT(w, h)`."""
struct Shape
  tag::ShapeTag
  r::Float64
  w::Float64
  h::Float64
end
CIRCLE(r) = Shape(CIRCLE_TAG, r, 0.0, 0.0)
RECT(w, h) = Shape(RECT_TAG, 0.0, w, h)

@registerVariants Shape begin
  CIRCLE(r)
  RECT(w, h)
end

area(s::Shape) = @match s begin
  CIRCLE(r = r) => pi * r^2
  RECT(w, h) => w * h
end
source
MetaModelica.@splice — Macro
@splice(iterator, body)

Utility macro given a body on the format @splice <tuple> in <collection> <body> Generates:

Expr(:..., :(($(esc(body)) for $(esc(iterator.args[2])) in $(esc(iterator.args[3])))))

Example:

bound = [:x, :y, :z]
julia> quote $(MetaModelica.@splice variable in bound :(
            $(esc(variable)) = $(Symbol("variable_$variable"))
          )) end

quote
    $(Expr(:escape, :x)) = variable_x
    $(Expr(:escape, :y)) = variable_y
    $(Expr(:escape, :z)) = variable_z
end
source
MetaModelica.@unsafematch — Macro
  @unsafematch value begin
      pattern1 => result1
      pattern2 => result2
      ...
  end

Return result for the first matching pattern. If there are no matches, returns value.

source
MetaModelica.UniontypeDef.@Uniontype — Macro

Creates a uniontype consisting of 0...N records.

Two call forms:

  • @Uniontype Name body — abstract type + records, no docstring.
  • @Uniontype "text" Name body — as above, plus attach "text" as the docstring on the abstract type.

The docstring-first form exists because the plain macro expands to a multi-form block (one abstract type plus N structs), which Julia's docstring machinery rejects as a prefix-string target. The leading-string form works around that by registering the docstring post-hoc via @doc str name once the binding exists.

source
MetaModelica.UniontypeDef.@UniontypeDecl — Macro
@UniontypeDecl Name

Declare the abstract type Name of a uniontype before its definition, so that uniontypes defined earlier can have fields of type Name (mutually recursive uniontypes). The later @Uniontype Name or @T_Uniontype Name uses this declaration.

source
MetaModelica.Dangerous.arrayCreateNoInit — Method

Creates a new array where the elements are not initialized!. Any attempt to access an uninitialized elements may cause segmentation faults if you're lucky, and pretty much anything else if you're not. Do not use unless you will immediately fill the whole array with data. The dummy variable is used to fix the type of the array.

source
MetaModelica.MM_Debug — Module
MM_Debug

@matchcontinue that logs every exception a case swallows. The same macro name as MetaModelica.@matchcontinue, built by the same code (handle_match_cases with a swallowHook), so a debug run swaps one import:

using MetaModelica.MM_Debug: @matchcontinue

An explicit import wins over the implicit using MetaModelica. Remove the line to return to the plain macro. The log is MM_Debug.LOG; clear!() before a run, summarize() or print_log() after.

source