Model APIs
The model guide introduces binding and block placement. The composition guide covers reusable submodels, and the functions guide covers deterministic functions and probability families.
Model construction
StanBlocks.@slic Macro
@slic [data] body
@slic name(args...) = bodyDefine a probabilistic model using Julia syntax. Bind data with the optional leading argument or call the resulting model with keyword inputs. A named definition creates a callable submodel whose positional arguments bind by name.
The defining module is captured automatically via __module__, so that @deffun functions defined in the same module (e.g. a package extension) are found during symbol resolution.
A leading string literal inside the begin ... end block is captured as the model docstring and rendered as a // ... comment header in the generated Stan code. A Julia docstring before a named definition, "doc" @slic f(args...) = body, documents that method of f instead.
StanBlocks.@plate Macro
@plate for i in 1:N
x[i] ~ dist(…) # a model-scope array, one element per cell
t ~ dist(…) # a per-cell local (hoisted, hygienic name)
y[i] ~ dist(x[i], t) # an observation on data `y`
endThe annotated independent-cell loop of a @slic model body: sugar for the plate(...) do … end primitive (the tracer inlines both; neither is a HOF). Arrays indexed by the loop variable are model-scope arrays visible after the loop; bare fresh names are per-iteration locals; writes to names bound outside the loop are rejected — SB models never mutate. Cells are independent: a read at any other index than the loop variable's is an error (use @scan). for i in 1:N, j in 1:M gives an N-D outer shape; for di in doses iterates the values of a container (a RaggedVector group per cell).
Only meaningful inside a @slic model body, where it is a reserved form.
StanBlocks.@scan Macro
@scan begin
x[1] ~ dist0(…) # setup: the initial state(s)
for i in 2:T
x[i] ~ dist(x[i-1], …) # the recurrence: lag reads `x[i-k]`
end
endThe annotated sequential loop of a @slic model body (a sampled-states recurrence; decision 17cilkc): one block whose trailing for is the recurrence and whose preceding statements are the setup. Arrays indexed by the loop variable are model-scope arrays; inside the loop they may be read at the current index or at a fixed lag x[i - k] (k ≥ 1), never ahead. Every element is assigned exactly once across setup + loop (the setup fills x[1:m] and the loop starts at m+1). Per-iteration locals and observations behave as in @plate. Lowers to a plain Stan for loop; a prior-only or cross-validated model re-draws the whole block in generated quantities in step order.
Only meaningful inside a @slic model body, where it is a reserved form.
StanBlocks.compile_slic_bundle Function
compile_slic_bundle(data, definitions, body;
udf_definitions=(), anonymous_submodels=(), name=nothing)Compile an ordered collection of @deffun UDF definitions, named SLIC sub-model definitions, anonymous sub-model dependencies, and one parent SLIC model body. Each udf_definitions value is either an expression accepted by @deffun or a named tuple with a required definition expression plus optional markers and assertions. definitions contains expressions shaped like f(args...) = begin ... end (without an outer @slic macro call); anonymous_submodels contains name => body_or_value pairs, where name is the Symbol used by the parent and the value is either an anonymous SLIC body expression (without an outer @slic) or an existing SlicModel; and body is the parent model expression. UDFs are installed first in their supplied order, then named SLIC definitions, then anonymous dependencies, in a fresh module. The parent is traced exactly once in that same module.
Structured UDF metadata is the macro-free spelling of trusted compiler-owned annotations. markers accepts one Symbol or a tuple/vector drawn from :stanonly, :juliacompat, :lhs, :lpxf, and :inline; :inline cannot be combined with :lhs or :lpxf. assertions is a tuple/vector of named tuples with a condition AST and optional string message. Assertions are prepended to one bodyful definition with the semantics of @stan_assert. Unknown fields, markers, duplicates, and malformed assertions fail before evaluation.
Each UDF or SLIC definition, and the parent body, may be written as either a bare expression or source_part => expression, where source_part is a Symbol or string. Labeled parts preserve that identity in diagnostic results. Bare expressions retain the legacy source-location behavior, with slic_bundle used when the expression has no source file.
Each anonymous dependency is either name => body_or_value or source_part => (name => body_or_value). A body expression is expanded by @slic inside the owned workspace, so it sees the bundle's earlier definitions without caller-side Core.eval. An existing SlicModel keeps its original defining module. In both forms the parent refers to the dependency by name, and repeated calls keep ordinary anonymous-submodel kwarg binding and hygienic LHS namespaces.
The result is a named tuple with:
model: the tracedStanModel, ready for cheap data rebinding;descriptor: itsModelDescriptor, withnameforwarded tostan_descriptor;code: the generated Stan source.
This is an integration boundary for already-parsed, trusted SLIC expressions. It does not parse or sandbox source, and it deliberately preserves @slic's macro-expansion semantics: macros inside a supplied expression can execute Julia code during expansion. Validate untrusted source before calling this function and isolate its execution when it comes from an anonymous user.
Function definitions
StanBlocks.@deffun Macro
@deffun function_definitionDefine a Stan-compatible function with type inference and Stan code generation.
Parses a Julia-style function definition (with type-annotated arguments and return type), generates the corresponding Stan function, and registers type-inference signatures so the transpiler can propagate types through calls to this function. Definitions are Stan-only by default. Add @juliacompat to an eligible bodyful bare-symbol definition to install one callable Julia method from the original user-facing definition as well. Signature-only/type- token glue, qualified or pre-existing function extensions, and definitions whose own name is in the probability/RNG/ODE/reduce_sum family (*_lpdf, *_lpmf, *_lcdf, *_lccdf, *_cdf, *_rng, the elementwise *_lpdfs/*_lpmfs/… companions, and ode_*) remain Stan-only even when annotated.
The opt-in Julia target is a bounded deterministic compatibility layer: supported signatures, symbolic dimension checks, typed locals, control flow/mutation, nested deterministic calls, higher-order arguments, and varargs. In a @juliacompat definition, a direct probability/RNG/ODE/reduce_sum primitive call errors at expansion time. Remove the annotation when the definition is intentionally Stan-only. A probability-family definition is outside the layer by construction and gets no Julia method.
For functions ending in _lpdf/_lpmf/_lcdf/_lccdf, the return type is automatically set to real and companion _lpdfs/_rng stubs are generated for use in generated_quantities.
UDF bodies must not contain ~ sampling statements or target += increments — UDFs cannot introduce parameters or directly manipulate the log density. The macro errors at expansion time if either is found.
Standard Julia macros inside the body are expanded against the calling module before tracing, so @views, @., @inbounds, and user-defined macros work transparently.
Inlining
Annotating with @inline (or giving the function a Julia-convention trailing ! in its name) expands each call at its call site.
Inline UDFs do not appear in Stan's functions {} block. Multi-statement bodies, vararg parameters, and higher-order function arguments are all supported. Locals are renamed per call site, and pre-statements hoist into the enclosing block.
@inline cannot be combined with @lhs / @lpxf.
StanBlocks.@defsig Macro
@defsig signatureRegister type-inference signatures for existing Stan functions. Prefer @deffun when defining a function body. This lower-level registration is primarily for extending the set of functions the tracer recognizes.
StanBlocks.@juliacompat Macro
@juliacompat definitionOpt an eligible bodyful @deffun definition into the bounded deterministic Julia compatibility target while retaining the same SLIC/Stan lowering.
It may wrap one definition or a begin ... end group inside @deffun. Signature-only/type-token glue, qualified or pre-existing function extensions, and probability/RNG/ODE/reduce_sum-family definitions remain Stan-only. Within a @juliacompat begin ... end group, a nested @stanonly definition explicitly opts that member back out.
StanBlocks.@stanonly Macro
@stanonly definitionExplicitly mark a @deffun definition as Stan-only. This is the default, so the annotation is normally optional; it remains useful as documentation and to opt one member out of a surrounding @juliacompat begin ... end group.
It may wrap one definition or a begin ... end group inside @deffun.
StanBlocks.@stan_assert Macro
@stan_assert cond
@stan_assert cond messageStan-compatible runtime assertion. Expands to if !cond; reject(msg); end, where Stan's reject aborts the current MCMC proposal with the message. Without an explicit message, a default "assertion failed: <cond>" is used.
Use inside @deffun bodies (control flow is not allowed in @slic model bodies — wrap the check in a helper if needed at the model level).
StanBlocks.return_type_of Function
return_type_of(f, args...) -> StanTypeInfer the Stan return type and shape of a SLIC-callable function for the given representative Julia arguments. The result is the same StanType used by the transpiler and prints as Stan syntax, for example real, vector[3], or matrix[2, 4].
Inside an @deffun body, return_type_of(f, args...) is a transpile-time type token and may be used in a computed type annotation.
The query is intentionally bounded to non-inline @deffun functions and @defsig-registered SLIC callables whose result is a scalar or sized Stan container. Inline functions, closures, sub-models, arbitrary Julia functions, and tuple/user-defined-type results require a full call-site trace and are not queryable through this API. Inside a UDF, spell symbolic output dimensions explicitly (return_type_of(f, x)[n]) when they are already bound by the surrounding signature.
StanBlocks.slic_eval Function
slic_eval(mod::Module, expression)Evaluate trusted SLIC definitions in mod as one exclusive publication phase. Use a fresh module and put a complete runtime-generated family (all @deffun companions and extension methods such as autokwargs) in one expression before sharing its bindings. compile_slic_bundle already uses this protocol.
Individual SLIC definition macros synchronize their generated methods. This outer boundary also covers macro expansion and families spanning several macros or ordinary Julia extension methods. stan_model observes completed definitions in the newest method world, including from previously created tasks; independent traces remain parallel. Direct Julia calls to newly defined functions still need Julia's usual Base.invokelatest boundary.
This is not a sandbox or a rollback facility: discard a fresh module if evaluation fails. Do not spawn and wait for other definition/tracing tasks inside this boundary. Published inputs must stay read-only and tracing hooks must be pure; uncoordinated Core.eval of ordinary extension methods is outside this protocol.
Probability families
StanBlocks.@lpxf Macro
@lpxf foo_lpdf
@lpxf begin foo_lpdf; bar_lpmf endRegister the three SLIC dispatch hooks (lpxf_expr, rng_expr, likelihood_expr) for one or more user-defined log-probability functions.
The argument(s) must be bare symbols ending in _lpdf, _lpmf, _lcdf, or _lccdf. For each name, it associates the base family with the density, random-number generator and pointwise log-density companions.
The companion foo_rng and foo_lpdfs (resp. _lpmfs/_lcdfs/_lccdfs) names must already exist when the registrations execute. This macro does not parse function bodies and does not wrap @deffun.
StanBlocks.@lhs Macro
@lhs foo_lpdf(y::T, args...) = bodyInside a @deffun block, opt this method into base-level LHS inference. Without @lhs, only the _lpdf-keyed tracetype is registered (so the method dispatches when called explicitly), but lhs ~ foo(args...) cannot trace because the base foo has no tracetype keyed on its argument signature. @lhs registers tracetype_by_head(::typeof(foo), ::CanonicalExpr{<:typeof(foo), <:Tuple{lhs_type[2:end]...}}) so the sampling form works.
Compose with @lpxf (any order — @lhs @lpxf … or @lpxf @lhs …) to also register the dispatch hooks for foo/foo_rng/foo_lpdfs.
Standalone @lhs (outside @deffun) is not supported and errors immediately.
StanBlocks.ValueFamily Type
ValueFamily(label::Symbol, kind::Symbol, density_defs, pointwise_defs, rng_defs, mod::Module; support=(;), lcdf=nothing, lccdf=nothing)A value-based sampling distribution: the _lpdf/_lpmf + pointwise + _rng triad as DATA, usable in y ~ family(…) with no Core.eval, no Julia methods, and no module bindings. kind is :lpdf or :lpmf. Each *_defs is one @deffun-shaped sig = body expression or a vector of them (scalar AND whole-vector overloads, as usual); companion labels derive from label exactly like @lpxf derives them (<label>_<kind>, <label>_<kind>s, <label>_rng). support is the intrinsic-support NamedTuple (the autokwargs contract — scalars, vectors, adjoint/transpose wrappers — kept on ONE native parameter declaration). mod is the defining module (actual identity, not a printed name): companion bodies trace in its context.
lcdf/lccdf optionally supply the log-CDF and log-CCDF companions, defs shaped like the triad's and labelled <label>_lcdf/<label>_lccdf (the names @deffun families use). The family then stands in the family slot of the distribution HOFs — weighted, truncated, censored, interval_censored, token form (censored(family, args…; lower=lo)) or call form (censored(family(args…); lower=lo)) — exactly like an @lpxf family; left censoring needs a log-CDF, right censoring a log-CCDF, and interval censoring or truncation the relevant tail probabilities. Weighting needs no additional companion.
Companion bodies spell sibling labels bare (density calling pointwise, RNG recursing across overloads, a CCDF calling the CDF, …) exactly as in @deffun source; the constructor links them to the companion values, so @deffun-shaped ASTs migrate by swapping the Core.eval for this constructor. Splice the family into a generated body (Expr(:call, family, args…)) or bind it in a module and reference it by name.
Unsupported operations: explicit user bounds at a value ~ site (put bounds in support=, or write truncated(family, …)), companion selectors (density(family, …)) and @deffun function-argument positions, data-dict carriage, ragged observations.
StanBlocks.ValueUDF Type
ValueUDF(label::Symbol, def, mod::Module)
ValueUDF(label::Symbol, defs::AbstractVector, mod::Module)A value-based Stan function: one label with one or more @deffun-shaped sig = body overloads, traced in mod's context. No Julia function, method, or module binding is created — the value splices directly into generated Exprs as a call head, or binds in a module and resolves by name.
Each def mirrors one @deffun-block definition (name(args...)::ret = body, args... trailing vararg allowed, sized-token leading formals allowed). v1 rejects kwarg formals, positional defaults, signature stubs, :void returns, and every marker except the vacuous @stanonly (@lhs/@lpxf claim a family density role a bare UDF does not have; @inline/@juliacompat have no value meaning — companions always lift like non-@inline @deffuns). Bodies may reference the companion's own label (overload recursion).
StanBlocks.family_support Function
family_support(f, args...) -> NamedTupleInspect the registered observation type and intrinsic support of an ordinary @lpxf family, builtin family, or ValueFamily for a typed signature. Pass symbolic declarations such as :(mu::real), :(sigma::real), or :(mu::vector[n]). Undeclared size symbols are symbolic data integers. Numeric literals are also accepted; they remain literals, not representative values substituted for symbolic arguments.
The result has fields kind (:continuous or :discrete), type (the Stan center-type symbol), size (a tuple of dimension expressions), and support (a named tuple of intrinsic lower/upper bounds). Bounds and dimensions retain symbolic expressions; compound expressions are Stan source strings. For example, family_support(StanBlocks.stan.uniform, :(lo::real), :(hi::real)) reports support = (lower = :lo, upper = :hi). Literal lower=-Inf and upper=Inf are omitted, as they impose no restriction.
A whole-real scalar family has kind === :continuous, type === :real, isempty(size) and isempty(support). This inspects SLIC's registration, including typed autokwargs hooks; it does not prove support from a density's mathematical body. Extension authors must register nontrivial support. Unknown families, unsupported signatures and untyped arguments raise errors; they never become an empty-support result. This query does not test companion implementations or add call-site truncation bounds.