69. Pure and impure functions: computed purity, @pure assertions, and @impure interface boundaries¶
Date: 2026-11-25
Status: Accepted (2026-11-25)
Context¶
Issue #375 showed that when an ordinary function returning a record — such as Pia.Time.civil_from_days — is named more than once in a contract, the verifier encoded each mention as an unrelated fresh value. The interface conformance check substitutes result with a call at every mention, so ensures days_from_civil result.year result.month result.day = z became three separate calls whose fields were never tied together.
Inside a single module, the verifier can walk a function's body and call graph to decide whether it is deterministic. Across a module boundary, it cannot. Today a .piai interface (ADR 0039) carries no purity information:
Pia.Sys.Posix.open,close,lseekanderrnotake nooutorinoutparameters, yet wrapexternC syscalls with observable side effects (file descriptors, globalerrno, OS state).Pia.Time.civil_from_daysis genuinely pure, yet an importer sees the same kind of signature asPosix.open.- Existing
contractOnlyinsrc/verify/Verifier.cppencodes every single-scalar imported function as one uninterpreted function, which is unsound for impure scalar FFI wrappers such asPosix.closeorPosix.errnowhen called more than once.
At the same time, programmers have no way to assert that a function is pure and have the compiler reject an accidental side effect, nor to see from an interface whether an exported function has hidden effects.
Decision¶
1. Three levels of purity, computed by the compiler¶
Every function in Pia has a purity level computed by the compiler from its signature, its body and its transitive call graph:
- Strongly pure (total, no effects). Takes no
out,inout,mutable,atomicordynparameters; performs no hidden effects (section 2); and is proved to terminate (everywhileloop and recursive cycle has adecreasesmeasure, matching ADR 0043 and ADR 0044). Local mutation (let mutablelocals, non-escaping local buffers fromwith_arena, and calling weakly-pure functions on local buffers) and returning fixed arrays[T; N]are allowed: repeated calls on equal arguments always return equal values and change no observable state outside the call. - Weakly pure (parameter mutation only, total). Takes one or more
out,inoutormutableparameters, performs no hidden effects, and is proved to terminate. Examples includeAlgo.Sort.sortandVec.push. Its effects are completely visible in its parameter modifiers, so it needs no@impureattribute and may be called on local buffers inside a strongly-pure function. It cannot be called directly in contracts. - Impure (
@impure). Performs or transitively calls any hidden, concurrent, or potentially non-terminating effect: - any foreign
= extern "..."declaration (always impure; see section 3), - any
unsafecall orunsafe view, - any pointer-address operation (
AddressOp/AtAddressOp), - any atomic operation or
atomicparameter (ADR 0052), - any
whileloop or recursion without a proveddecreasesmeasure, - any call to an impure function (including imported
@impurefunctions).
Calls to let spec functions and let lemma proofs never make a function impure.
2. @pure and @impure attributes¶
(* Private functions infer purity automatically; no attribute is needed. *)
let civil_from_days (z : int{-365962028..364523337}) : ymd = ...
(* Optional @pure asserts strong purity + totality; violation is an error. *)
let civil_from_days (z : int{-365962028..364523337}) : ymd @pure = ...
(* Exported impure functions must declare @impure in their interface. *)
interface Posix = sig
let open : (path : [u8]) -> (flags : i32) -> i32 @impure @variadic(2)
requires len path >= 1 && path.[len path - 1] = 0
ensures result >= -1
let close : (fd : i32) -> i32 @impure
ensures result >= -1 && result <= 0
end
- Private functions: purity and impurity are computed automatically, so private helpers and atomic primitives (such as
tests/verify/atomics.pia) need no annotation. @pure: an explicit, compiler-checked assertion of strong purity and totality. Placing@pureon a function that takesout/inout/mutableoratomicparameters, performs a hidden effect, calls an impure function, or lacks proved termination is a compile-time error.@impure: explicitly declares hidden, concurrent or non-terminating effects.- Lint (ADR 0037): a lint (
impure_interface) recommends adding@impureon definitions and interface rows whose computed purity is impure when they are part of a module's interface, so the annotation stays visible at the definition as well as the interface.
3. Foreign (= extern "...") functions are always @impure¶
Every = extern "..." declaration is unconditionally @impure. Marking a foreign declaration @pure is a compile-time error, even inside a @trusted module: pure functions are proved in Pia (or modelled as a library theory, ADR 0036), never trusted through C FFI. Purity therefore adds zero unverified trust surface to --trust-report.
4. Interfaces, .piai export and conformance¶
Matches ADR 0004 ("the strongest guarantee is always the default; every weakening is visible in the source and, where it affects callers, in the interface"):
- Unmarked interface rows default to non-impure (strongly pure when there are no
out/inout/mutableparameters; weakly pure when there are). An implementation whose computed purity is impure fails interface conformance unless the interface row carries@impure. - Subtyping: a strongly-pure (or weakly-pure) implementation satisfies an
@impureinterface row (stronger meets weaker, matching weakerrequiresand strongerensures). An impure implementation cannot satisfy an unmarked or@pureinterface row. - Always exported in
.piai: the compiler always writes the computed purity property into.piaiinterface artifacts and includes it in the interface hash (ADR 0024). Importers always know statically whether an imported function is strongly pure, weakly pure or@impure.
5. Contracts and verifier encoding¶
- No impure calls in contracts: calling an
@impurefunction (or a weakly-pure mutating function) insiderequires,ensures,invariant,assert,let specorlet lemmais a compile-time error — generalising ADR 0044 section 6's ban on effectful lambdas in contracts. - Interface conformance for
@impurefunctions: an@impurefunction may still carryrequiresandensuresabout its ownresultand parameters (such asPosix.open'sensures result >= -1). Its conformance check usesqueueContractCall(calling the function once as the body and checkingensuresonresult) rather than substituting calls intoensures. - Verifier uninterpreted-function encoding (#375): strongly-pure functions — both module-local and imported — are encoded lazily as one uninterpreted SMT function per scalarized result field whenever called more than once or demanded in a contract or quantifier, so repeated calls (such as
civil_from_days zinCalendar.civil_from_days.contract) agree.@impureimported functions (such asPosix.close,Posix.lseekandPosix.errno) are never encoded as uninterpreted functions, closing thecontractOnlysoundness gap.
6. Higher-order functions and purity polymorphism¶
Higher-order functions such as map, fold and find are generic over their callback's Function instance (ADR 0044) and monomorphised per callback:
- Purity polymorphism: an arrow parameter
(f : a -> b)accepts either a pure or an@impurecallback unless annotated@pure(or called in the higher-order function's contracts, which requiresfto be strongly pure). Each monomorphised instance computes its purity from its body and the concrete callbackf:map xs fis pure whenfis pure and@impurewhenfis@impure. - Generic proofs (ADR 0043): a generic proved once whose contracts apply
frequiresfto be strongly pure and total; one whose contracts do not applyfholds for impure callbacks too.
7. Code generation¶
Once purity is checked by the compiler, LLVM lowering can attach memory(none) / willreturn attributes to strongly-pure functions where sound. Codegen remains unchanged in the initial steps.
Dean's answers (2026-11-25)¶
- Default polarity: pure by default (when no
out/inout/mutableoratomicparameters), with@impurefor hidden effects and optional@pureas an explicit checked assertion. - Purity boundary: externally pure and total — local mutation (
let mutable, local buffers /with_arena) and fixed-array[T; N]returns are allowed, and purity requires proved termination (decreasesonwhileand recursion). - Foreign (
extern) functions: always@impure; no@pureon C FFI, even in@trustedmodules. Pure code is written in Pia or modelled as a theory. - Parameter mutation vs hidden effects: D-style weak vs strong purity. Functions whose only effect is mutating
out/inout/mutableparameters (likesort) need no@impureand may be called on local buffers inside pure functions;@impuremarks hidden effects, and@pureasserts neither mutable parameters nor@impure. - Computed purity,
.piaiexport and lint: purity/impurity is computed automatically by the compiler (including for atomics) and always exported in.piaiinterfaces; unmarked interface rows default to pure (hard conformance error if the implementation is impure), and a lint recommends writing@impureon exported impure functions. - Higher-order functions: include purity polymorphism (e.g.
mapinherits the purity of its callback). - Rollout: fold this ADR into the same PR as the
#375verifier fix, then build the compiler checks in follow-up steps.
Build order¶
- Verifier encoding for repeated pure calls (#375, this PR): lazy uninterpreted-function encoding per scalarized result field for module-local pure functions, with
tests/verify/pure_contract_calls.pia. - Computed purity,
@pure/@impureattributes, and contract checks: compute strong/weak/impure purity (including termination) in IRGen/Verifier, accept@pureand@impureingenAttributes, reject@pureonexternand impure calls in contracts/specs/lemmas, and route@impureinterface conformance checks throughqueueContractCall. - Interfaces,
.piai,Pia.Sys.Posix, andcontractOnlyfix: export computed purity in.piaiand include it in the interface hash; enforce unmarked interface rows as non-impure; annotatelib/Pia/Sys/Posix.pia(andtools/bindings/gen.py) with@impure; restrict imported uninterpreted-function encoding inVerifier.cppto strongly-pure imports. - Lint and skills: add the
impure_interfacelint insrc/syntax/Lint.cpp(withtests/lint/), and document@pureand@impureindocs/design.md,docs/idioms.md, andskills/pia-language/SKILL.md. - Purity polymorphism: propagate callback purity through monomorphised higher-order functions and ADR 0043/0044 checks, with tests in
tests/verify/. - Codegen (optional follow-up): emit LLVM
memory(none)/willreturnattributes for proved strongly-pure functions.
Consequences¶
- Purity becomes a compiler-computed, interface-visible property rather than a verifier-internal heuristic.
- Imported strongly-pure functions returning records (such as
Pia.Time.civil_from_days) work in contracts across module boundaries, while impure FFI wrappers (Pia.Sys.Posix) cannot be falsely equated by the solver. - Private functions and weakly-pure mutating algorithms (
Algo.Sort,Vec, codecs) require no new annotations; only exported functions with hidden, concurrent, or non-terminating effects carry@impurein their interfaces. - No unverified trust surface is added:
= extern "..."is always@impure.
Prior art¶
| Source | What Pia takes |
|---|---|
D pure |
Weak vs strong purity: local mutation and calling mutating helpers on local state inside strongly-pure functions |
F* Tot / Pure vs ML / Dv |
Pure and total by default, with explicit effectful boundaries |
Dafny function vs method |
Only pure total functions appear in contracts and act as SMT functions |
| Koka / Flix effect systems | Purity polymorphism for higher-order functions |