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.MATCHCONTINUE_FILE — Constant
The file of the match macros; line numbers from it are replaced by the call site's.
MetaModelica.Option — Type
Option{T}MetaModelica's Option<T>: Union{Some{T}, Nothing}.
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.
MetaModelica.CheapThrowScope — Type
The exception a with_cheap_throws scope handles while its body runs; not an error.
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.
MetaModelica.NONE — Function
The absent value of an Option: nothing.
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.
MetaModelica._shortPattern — Method
The pattern of a case as text of at most 60 characters, for the log of MM_Debug.
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.
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.
MetaModelica.anyString — Method
Returns the string representation of any value. Rather slow; only use this for debugging!
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.
MetaModelica.arrayCopy — Method
O(n)
MetaModelica.arrayCreate — Method
O(size)
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.
MetaModelica.arrayEmpty — Method
O(1)
MetaModelica.arrayGet — Method
O(1)
MetaModelica.arrayLength — Method
O(1) ?
MetaModelica.arrayList — Method
O(N)
MetaModelica.arrayUpdate — Method
O(1)
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.
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.
MetaModelica.boolAnd — Method
Logically combine two Booleans with 'and' operator
MetaModelica.boolEq — Method
Compares two Booleans
MetaModelica.boolNot — Method
Logically invert Boolean value using 'not' operator
MetaModelica.boolOr — Method
Logically combine two Booleans with 'or' operator
MetaModelica.boolString — Method
Returns \"true\" or \"false\" string
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.
MetaModelica.clock — Method
Use the diff to compare two time samples to each other. Not very accurate.
MetaModelica.compacted_tag_info — Method
compacted_tag_info(ctor) -> (StructType, tagfield::Symbol, tagvalue, fieldorder::NTuple{N,Symbol}) | nothingExtension 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).
MetaModelica.debug_print — Method
For RML compatibility
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.
MetaModelica.evaluated_fieldcount — Method
Statically get the fieldcount of a type. Useful to avoid runtime calls to fieldcount.
MetaModelica.evaluated_fieldnames — Method
Statically get the fieldnames of a type. Useful to avoid runtime calls to fieldnames (which includes many allocations).
MetaModelica.evaluated_fieldtypes — Method
Experimental
MetaModelica.genShouldFail — Method
This function implements the @shouldFail macro. @shouldFail(arg) succeeds if arg fails, where arg is a local match-equation/statement.
MetaModelica.handleSugar — Method
Handle syntactic sugar for MetaModelica mode. Mostly lists but also for the optional type. Parenthesis for these expressions are skipped
MetaModelica.handle_destruct — Method
Top level utility function. Handles deconstruction of patterns together with the value symbol.
MetaModelica.handle_destruct_fields — Method
Handles the deconstruction of fields
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)bindsx = obj.field1,y = obj.field2usingfieldnames(T)order. _and__placeholders skip the corresponding field.- keyword bindings
field=namebindname = 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.
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.
MetaModelica.handle_match_cases — Method
Top level function for all match macros except for the match equation macro.
MetaModelica.handle_match_eq — Method
Handles match equations such as @match x = 4
MetaModelica.intAbs — Method
Returns the absolute value of Integer i
MetaModelica.intAdd — Method
Adds two Integer values
MetaModelica.intBitAnd — Method
Returns bitwise 'and' of Integers i1 and i2
MetaModelica.intBitLShift — Method
Returns bitwise left shift of Integer i by s bits
MetaModelica.intBitNot — Method
Returns bitwise inverted Integer number of i
MetaModelica.intBitOr — Method
Returns bitwise 'or' of Integers i1 and i2
MetaModelica.intBitRShift — Method
Returns bitwise right shift of Integer i by s bits
MetaModelica.intBitXor — Method
Returns bitwise 'xor' of Integers i1 and i2
MetaModelica.intDiv — Method
Divides two Integer values
MetaModelica.intEq — Method
Returns whether Integer i1 is equal to Integer i2
MetaModelica.intGe — Method
Returns whether Integer i1 is greater than or equal to Integer i2
MetaModelica.intGt — Method
Returns whether Integer i1 is greater than Integer i2
MetaModelica.intLe — Method
Returns whether Integer i1 is smaller than or equal to Integer i2
MetaModelica.intLt — Method
Returns whether Integer i1 is smaller than Integer i2
MetaModelica.intMax — Method
Returns the bigger one of two Integer values
MetaModelica.intMin — Method
Returns the smaller one of two Integer values
MetaModelica.intMod — Method
Calculates remainder of Integer division i1/i2
MetaModelica.intMul — Method
Multiplies two Integer values
MetaModelica.intNe — Method
Returns whether Integer i1 is not equal to Integer i2
MetaModelica.intNeg — Method
Returns negative value of Integer i
MetaModelica.intReal — Method
Converts Integer to Real
MetaModelica.intString — Method
Converts Integer to String
MetaModelica.intSub — Method
Subtracts two Integer values
MetaModelica.isNone — Method
Returns true if the input is NONE()
MetaModelica.isPresent — Method
TODO: I am far from sure that this will fly.. in Julia. The code generated from the transpiler is correct however
MetaModelica.isSome — Method
Returns true if the input is SOME()
MetaModelica.is_match_macrocall — Method
Check if pattern is a nested @match or @matchcontinue macrocall. Returns true if it is, false otherwise.
MetaModelica.isvariant — Method
isvariant(value, variant) -> Boolvalue 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.
MetaModelica.listArray — Method
Same as listArray but with a dummy argument to specify the type.
MetaModelica.listArray — Method
O(1)
MetaModelica.listArray — Method
O(n)
MetaModelica.listArray — Method
O(n)
Same as listArray but with a dummy argument to specify the type.
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.
MetaModelica.printAny — Method
print(anyString(a)), but to stderr
MetaModelica.referenceEq — Method
This is a very fast comparison of two values which only checks if the pointers are equal.
MetaModelica.referencePointerString — Method
Returns the pointer address of a reference as a hexadecimal string that can be used for debugging.
MetaModelica.reportUnexpectedInMatch — Method
reportUnexpectedInMatch(e, backtrace) -> NothingPrints 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).
MetaModelica.resolve_pattern_head — Method
Resolve a pattern head (CTOR or a qualified A.B.CTOR) to its value in mod at macro-expansion time. Returns nothing when it does not resolve.
MetaModelica.setStackOverflowSignal — Method
Sets the stack overflow signal to the given value and returns the old one
MetaModelica.stringAppend — Method
O(s1+s2)
MetaModelica.stringAppendList — Method
O(str)
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"
MetaModelica.stringEmpty — Method
O(1)
MetaModelica.stringEq — Method
O(N)
MetaModelica.stringEqual — Method
O(N)
MetaModelica.stringGet — Method
O(1)
MetaModelica.stringGetStringChar — Method
O(1)
MetaModelica.stringHashDjb2 — Method
Standard djb2 hash over UTF-8 code units.
MetaModelica.stringHashDjb2Mod — Method
Does hashing+modulo without intermediate results.
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.
MetaModelica.stringLength — Method
O(1)
MetaModelica.stringListStringChar — Method
O(str)
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
MetaModelica.stringUpdateStringChar — Method
O(n)
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.
MetaModelica.unsafe_handle_match_eq — Method
Handles match equations such as @unsafematch x = 4
MetaModelica.valueCompare — Method
a1 > a2?
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.
MetaModelica.valueEq — Method
Structural equality
MetaModelica.valueSlots — Method
The number of slots a boxed value has. This is dependent on sizeof(void*) on the architecture in question.
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.
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.
MetaModelica.@CUniontype — Macro
@CUniontype Name begin
VARIANT1(field1::Type1, field2::Type2, ...)
VARIANT2(...)
...
endDeclarative 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.
MetaModelica.@ExtendedAnonFunction — Macro
@ExtendedAnonFunction old(arg = value, ...)An anonymous function: old with new defaults for the named arguments, as @ExtendedFunction. The Julia version of MetaModelica's function old(arg = value) passed as an argument.
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.
MetaModelica.@T_Uniontype — Macro
@T_Uniontype [mutable] Name begin
VARIANT1(field1::Type1, field2::Type2 = default, ...)
VARIANT2()
...
endCompacted 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.
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.
MetaModelica.@cheap_throws — Macro
@cheap_throws exprwith_cheap_throws(() -> expr).
MetaModelica.@closure — Macro
Wraps the @closure macro of FastClosures. See the FastClosure package for more information.
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.
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
endThis 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
endMetaModelica.@instanceName — Macro
@instanceNameMacro 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().
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 equalityPatterns can be nested arbitrarily.
Repeated variables only match if they are == eg (x,x) matches (1,1) but not (1,2).
MetaModelica.@match — Macro
@match value begin
pattern1 => result1
pattern2 => result2
...
endReturn result for the first matching pattern. If there are no matches, throw MatchFailure
MetaModelica.@match — Macro
@match pattern = value If value matches pattern, bind variables and return value. Otherwise, throw MatchFailure.
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 equalityPatterns can be nested arbitrarily.
Repeated variables only match if they are == eg (x,x) matches (1,1) but not (1,2).
MetaModelica.@matchcontinue — Macro
@matchcontinue value begin
pattern1 => result1
pattern2 => result2
...
endReturn result for the first matching pattern. If there are no matches, throw MatchFailure.
MetaModelica.@nospecialized — Macro
@nospecialized function name(a, b, ...; k = ..., ...)::R where {T, ...}
...
endRewrites 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, ...}
...
endMetaModelica.@registerVariants — Macro
@registerVariants T begin
VARIANT_A(field1, field2)
VARIANT_B()
...
endRegister 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
tagholding a value of an@enumwith 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 aTwith that tag, defined before this macro (the registration dispatches ontypeof(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@matchandisvariantread; MetaModelica.valueConstructor(v::T) = Int(v.tag)andMetaModelica.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
endMetaModelica.@shouldFail — Macro
@shouldFail(arg) succeeds if arg fails, where arg is a local match-equation/statement.
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
endMetaModelica.@unsafematch — Macro
@unsafematch value begin
pattern1 => result1
pattern2 => result2
...
endReturn result for the first matching pattern. If there are no matches, returns value.
MetaModelica.@unsafematch — Macro
@match pattern = value If value matches pattern, bind variables and return value.
MetaModelica.UniontypeDef.@Mutable_Uniontype — Macro
Creates a mutable uniontype consisting of 0...N records. Same call forms as @Uniontype: optional leading String becomes the docstring.
MetaModelica.UniontypeDef.@Record — Macro
@Record NAME begin
field1::Type1
field2::Type2
end
@Record NAME field1::Type1 field2::Type2A record of a @Uniontype or @Mutable_Uniontype, written inside its block: a struct NAME with these fields, a subtype of the uniontype. A record may have no fields (@Record NAME).
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.
MetaModelica.UniontypeDef.@UniontypeDecl — Macro
@UniontypeDecl NameDeclare 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.
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.
MetaModelica.Dangerous.arrayGetNoBoundsChecking — Method
O(1)
MetaModelica.Dangerous.arrayUpdateNoBoundsChecking — Method
O(1)
MetaModelica.Dangerous.stringGetNoBoundsChecking — Method
O(1)
MetaModelica.Dangerous.unsafe_pointer_from_objref — Method
Unsafe function to get pointers from immutable struct. Use with !care!
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: @matchcontinueAn 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.
MetaModelica.MM_Debug.LOG — Constant
Swallowed exceptions. Fields: case_num (1-based; 0 when all cases failed), exception_type, message, source.
MetaModelica.MM_Debug.MAX_LOG — Constant
Entries kept in LOG; later ones are dropped (batch runs).
MetaModelica.MM_Debug.clear! — Method
Empty LOG.
MetaModelica.MM_Debug.log_swallowed — Method
The hook of the @matchcontinue expansion: record one swallowed exception.
MetaModelica.MM_Debug.print_log — Method
Print the last last_n entries of LOG.
MetaModelica.MM_Debug.summarize — Method
Print the number of swallowed exceptions per exception type.
MetaModelica.MM_Debug.@matchcontinue — Macro
@matchcontinue value begin
pattern1 => result1
pattern2 => result2
...
endMetaModelica.@matchcontinue plus a log entry in LOG for every swallowed exception.