leanfran | PHP quick start | Samples
Generation uses Lean 4.35.0 and the leanfran compiler. Install the compiler with nix profile install 'github:conao3/lean-leanfran/v<version>#leanfran', where <version> is the release of the Composer package, and follow the quick start to install the Composer runtime. Running the generated code requires 64-bit PHP 8.4 or later, ext-gmp, and ext-tokenizer.
Put a Lean block on a PHP class:
namespace App;
use Conao3\Leanfran\Lean;
#[Lean(<<<'LEAN'
structure Range where
lo : Nat
hi : Nat
ok : lo ≤ hi
def width (r : Range) : Nat := r.hi - r.lo
theorem width_le (r : Range) : width r ≤ r.hi := by
unfold width
omega
LEAN)]
final class Pricing
{
use Pricing\Functions;
}Run leanfran --lang php sync in the directory of composer.json. App\Pricing::width(new App\Pricing\Range(lo: 2, hi: 5)) then returns 3. The PHP quick start has the Composer setup.
You can also generate PHP directly from a compiled Lean module. From the application directory, build the standalone pricing sample and generate its PHP API.
(cd ../lean-leanfran/langs/PHP/samples/pricing/lean && lake build)
leanfran --lang php module generate --module-name Pricing \
--search-path ../lean-leanfran/langs/PHP/samples/pricing/lean/.lake/build/lib/lean \
--output-dir generated --php-namespace 'App\Lean\Pricing'samples/ holds embedded blocks, verified functions, and programs generated from Lean modules.
Put #[Conao3\Leanfran\Lean(...)] on a PHP class. Its fully qualified name identifies the block. The attribute takes four arguments.
| Argument | Purpose |
|---|---|
source |
Lean source in a nowdoc or a single-quoted PHP string literal. |
imports |
Lean modules to import, such as ['Std.Data.HashMap']. |
uses |
Block classes whose Lean definitions are in scope, such as [Orders::class]. Their generated public PHP types are shared. |
models |
PHP classes to import as Lean structures or enum types, such as [LineItem::class]. |
The last three arguments are optional literal arrays. Class names can be written as fully qualified strings or ClassName::class literals. See embed-range for a complete block and embed-orders for two blocks that share an Order type.
A Lean error in a block has the form <file>:<line>:<column>: error: (lean block <class>, Lean <line>:<column>) <message>. It gives the block's fully qualified PHP class name and the Lean line and column within its source string. When a block fails to build, the previous generated PHP stays in place. Proofs of #[Model] functions run after sync has installed the generated files.
A model is a final class whose instance data consists of promoted public readonly properties on its public constructor, or a backed enum. Composer must be able to autoload model classes and any classes used by their properties. Block discovery reads PHP tokens, and model discovery loads the model classes for Reflection, including during status. Referenced models are imported transitively, and their references must be acyclic.
Reflection supplies native types. The CLI resolves PHPDoc class names in the namespace and imports of the constructor declaration. It reads constructor @param types and promoted property @var types, with @var taking precedence when both are present. A native array needs a list or pair annotation. An unsupported type produces a diagnostic with the class and property.
| PHP or PHPDoc type | Lean representation |
|---|---|
int |
Int |
int<a, b> |
Nat if the lower bound is nonnegative, otherwise Int, with inclusive bounds as applicable. Use min or max for an unbounded endpoint. |
positive-int, non-negative-int |
Nat, with a lower-bound proof for positive-int. |
negative-int |
Int with an upper-bound proof at −1. |
float, bool, string |
Float, Bool, String respectively. |
non-empty-string |
String with a minimum length of 1. |
list<T>, non-empty-list<T> |
List T, with a minimum length of 1 for non-empty-list<T>. |
array{0: A, 1: B} |
A × B |
?T or T|null |
Option T |
| Model class | A structure under LeanPhpModels with the PHP namespace and class name. |
| Backed enum | An inductive type with a nullary constructor for each PHP case name. |
Bounds and minimum lengths become Lean proof fields such as percent_le, quantity_ge, and items_min_items. The generated PHP accepts the original class and validates its properties before constructing the Lean value. For example, passing 101 in a field annotated int<0, 100> raises Conao3\Leanfran\ValidationError with the argument and property in the issue path. The generated code reconstructs returned models by calling the original constructor with named arguments. A change to a model's Lean representation makes its block and dependent blocks stale.
Generate the public API with --output-dir and --php-namespace, and map that namespace to the output directory in Composer's PSR-4 autoload configuration. The facade exposes Lean functions as typed static methods. A generation job writes the public types and facade at the root of the output directory and writes the implementation under Internal/. The summary lists generated files and skipped definitions with their reasons. The class under Internal/ lists the files of the job, and a run removes the listed files that it no longer generates. Other files stay, among them those of --output-file and of other modules.
--facade sets the facade name. --type-module MyApp.Common=App\Lean\Common refers to types already generated under App\Lean\Common with the Lean namespace prefix MyApp.Common stripped. Configure Composer to load both output directories. Generated code depends on conao3/leanfran.
| Lean | Public PHP type | JSON |
|---|---|---|
Nat, Int |
int|\GMP. Values within PHP's integer range use int. |
Number |
UInt8, UInt16, UInt32, Int8 through Int64, ISize |
int with PHPDoc bounds such as int<0, 255> |
Number |
UInt64, USize |
Nonnegative int|\GMP |
Decimal string |
Fin n |
int if n ≤ 2^63, otherwise int|\GMP |
Number |
Float, Float32 |
float |
Number or a nonfinite value's string |
Bool |
bool |
Boolean |
String, Char |
UTF-8 string. A Char has one Unicode scalar. |
String |
Unit, PUnit |
null |
{} |
Option α |
The type for α or null |
A value or null. A field named x? uses key x and omits it for none. |
List α, Array α |
list<T> |
Array |
α × β |
array{0: A, 1: B} |
Two-element array |
Except ε α |
Conao3\Leanfran\Except<E, A> implemented by Ok and Err |
{"ok": v} or {"error": e} |
| Structure | Final readonly class with public properties, including flattened parent fields | Object |
| Inductive with only nullary constructors | String-backed enum | Constructor name as a string |
| Other inductives | Interface and one final readonly class per constructor | Externally tagged value |
| Named subtype | Final readonly class with a val property |
JSON representation of val |
| Anonymous subtype | Base PHP type with runtime validation | Base JSON representation |
Function returning IO α |
Returns the public type for α and throws Conao3\Leanfran\LeanIOError on IO errors |
Result type's representation |
Parameterized types are generated for each concrete instance used in public signatures. Type names capitalize the first character, join Lean name components with underscores, and append concrete type arguments, as in PairNatBool. Facade methods convert each Lean name component to camel case and join the components with underscores. Both naming rules apply after stripping --namespace. Constructor classes append the capitalized constructor name, as in DiscountPercent. Enum case names capitalize the constructor name. Reserved PHP names gain a trailing underscore, as in List_. Case-insensitive collisions gain suffixes such as _2 and _3.
Constructors accept decimal strings for Nat, Int, UInt64, and USize, and normalize them to int or \GMP. Generated constructors validate field types and run the compiled Lean decisions for proof fields and subtype predicates. Proof fields participate in validation and are erased from public properties. Simple bounds also narrow PHPDoc types, for example to non-empty-string or non-empty-list<T>.
Invalid values raise Conao3\Leanfran\ValidationError. Its issues contain a message and a path of field names and array indices for each violation. getMessage() formats the first issue as a dotted path and a message, such as rest.0.Range.ok: lo ≤ hi. Facade argument issues start with the parameter name.
Generated value types provide fromArray, fromJson, toArray, and toJson. Externally tagged inductive values use a bare string for nullary constructors and a single-key object for constructors with data. Named parameters produce an object payload, as in {"percent":{"p":10}}. Positional parameters use properties such as a0 in PHP and a single value or an array in JSON, as in {"positional":6} and {"pair":[7,"♥"]}. Ordinary option fields emit null for none.
For finite Float values, JSON follows Lean's six-place decimal rounding, so 1 / 3 becomes 0.333333 and negative zero becomes 0. Float32 uses the same formatting after rounding the value to binary32. The nonfinite values use "NaN", "Infinity", and "-Infinity".
fromJson() preserves out-of-range integer literals as \GMP. toJson() writes large Nat and Int values as exact number literals, and UInt64 and USize as decimal strings. PHP's json_encode() calls jsonSerialize(), which emits \GMP values as decimal strings. Use toJson() for Lean's numeric wire representation.
Call Range::jsonSchema() to get a schema array for the Lean wire format. Pass 'draft-07' or 'openapi-3.0' to choose another target. The default is 'draft-2020-12'. Other target strings raise InvalidArgumentException. Each generated constructor class for an inductive returns the schema for the whole inductive.
The generator follows the TypeScript backend. Recursive definitions use $defs in draft 2020-12 and definitions in the other targets. Simple bounds become schema keywords such as maximum and minLength. A bound that neither an int nor a float holds exactly, and a literal that wraps in its type such as 300 for UInt8, become no keyword. The generated schema describes the wire shape and expressible bounds. Constructor validation checks relational predicates such as lo ≤ hi. Float schemas use type: number. The three nonfinite strings are supported by the JSON codec.
The openapi-3.0 target preserves the TypeScript converter’s tuple and recursion formats. It uses an array of schemas for tuple items and local definitions for recursion. OpenAPI 3.0 Schema Objects require an object for items and specify a fixed set of supported keywords. OpenAPI 3.0.4 Schema Object
In your application, run composer require cuyz/valinor:^2.8 to map data directly into the generated constructor signatures. The configured mapper turns a ValidationError into a MappingError message. Iterate $error->messages() to read the mapper's input path and the text of the Lean issue.
$mapper = \Conao3\Leanfran\Valinor::configure(new \CuyZ\Valinor\MapperBuilder())->mapper();
$range = $mapper->map(\App\Lean\Pricing\Range::class, ['lo' => 1, 'hi' => 3]);For an inductive, pass the constructor class to the mapper. Use fromJson() or fromArray() on a constructor class for externally tagged data. A mapper built without configure() propagates Lean's constructor validation exceptions directly.
| Lean | PHP runtime representation |
|---|---|
Nat, Int |
int|\GMP. Values within the signed 64-bit range use int. |
UInt8, UInt16, UInt32 |
Nonnegative int with arithmetic reduced to the corresponding bit width. |
UInt64, USize |
An int carrying the same 64-bit pattern, including patterns that appear negative in PHP. |
Int8 through Int64, ISize |
An int carrying the same bits as the corresponding unsigned type. |
Bool, Char |
int for a Boolean tag or Unicode scalar. |
Float |
A PHP float (binary64). |
Float32 |
A PHP float rounded to binary32. Integer conversions round once at binary32 precision. Transcendental results are within 1 ULP of the native oracle. |
String |
LString holding validated UTF-8. Positions are byte offsets. Length counts Unicode scalars. |
Array α |
LArray holding a zero-based PHP array of Lean runtime values. |
ByteArray, FloatArray |
LByteArray holding a byte string and LFloatArray holding PHP floats. |
For App\Pricing in src/Pricing.php, leanfran writes the App\Pricing\Functions trait and public types such as App\Pricing\Range to src/Pricing/. The implementation lives under src/Pricing/Internal/. The php section of leanfran.manifest.json at the project root records the block hash and the generated files. In the block class, add use Pricing\Functions; so callers can use App\Pricing::width(). Map App\ to src/ in the Composer PSR-4 autoloader.
A generated PHP file starts with <?php and the line
// Code generated by leanfran --lang php (generator 8) from LeanPhpEmbed.B4170705c50726963696e67. DO NOT EDIT.The module name holds the class name in hexadecimal.
The first call of a generated trait method in a process compares the #[Lean] arguments of the class, and of the classes in uses, with the key that sync wrote in the trait. If they differ, or if the generated trait is missing, the call throws Conao3\Leanfran\LeanBlockStale. PHP reports a missing trait as a fatal error with the same message.
leanfran: the Lean block App\Pricing is out of date; run 'leanfran --lang php sync'
The comparison covers the block, the names in models, and the generator version. leanfran --lang php status and Verify::checkModel also compare the definitions of the models. With LEANFRAN_AUTO_SYNC=1 the call runs leanfran --lang php sync in the project, with the compiler of LEANFRAN_CLI or leanfran on PATH, and continues with the PHP that was generated before. The new PHP takes effect when the program starts again. A missing trait is generated and loaded at once.
Commit the generated PHP, leanfran.manifest.json and leanfran.lock. In CI, install Composer dependencies and run leanfran --lang php status to verify that the checkout is up to date. Run check in jobs that also verify Lean proofs and regenerate the PHP. The CLI keeps its Lake workspace in .leanfran/php/ and takes the lock file .leanfran/lock; .leanfran/.gitignore lists both. sync keeps files in an output directory that leanfran did not generate, and refuses with exit 254 to overwrite such a file.
A job using --internal-only emits one PSR-4-compatible PHP file with a final class. By default, the class lives in Leanfran\Generated. The class name prefixes the module name with Lean and joins its components with underscores. Arith becomes LeanArith, and Data.List becomes LeanData_List. Module names that need escaping use Lean's identifier mangling.
Roots and reachable definitions, including definitions from imports, are exposed as public static methods. The emitter applies Lean's Name.mangle with the prefix l_. When two method names would match under case folding, each receives a suffix __c<hex>. The suffix encodes which characters in the mangled name are ASCII uppercase. Generation fails with 254 if the final names still collide.
Method signatures follow Lean IR. Boxed and erased values use mixed, fixed-width integer scalars use int, and floating-point scalars use float. Erased and void parameters are omitted. The runtime functions live in Conao3\Leanfran\Runtime and Composer loads them automatically.
--main emits runMain and runs it when PHP executes the generated file directly. Module initializers run in declaration order before the entry point. A failure in initialization stops execution. The runtime writes uncaught IO errors to stderr as uncaught exception: … and exits with status 1.
The runtime supports stdin, stdout, stderr, file and directory operations, clocks, environment variables, and child processes. It drains both output pipes when reading from a child with piped stdout and stderr. Monotonic time comes from hrtime in nanoseconds or whole milliseconds. Wall-clock time has microsecond precision and is returned in seconds and nanoseconds. File access and modification timestamps have one-second precision. On Unix, process spawning with setsid requires the PHP posix and pcntl extensions. PHP's exit implements IO.Process.forceExit, so PHP shutdown handlers still run.
Tasks started with spawn, map, bind, or IO.asTask run synchronously and return a completed task. Priority and cancellation have no effect. Waiting on an unresolved IO.Promise panics.
Self tail calls use jumps. Mutual tail calls and tail calls through closures use a trampoline. The depth tests run one million steps under memory_limit=128M. For non-tail recursion, the practical limit depends on PHP's memory_limit and, with Xdebug enabled, xdebug.max_nesting_level.
OPcache and JIT are optional runtime settings. If Zend OPcache is loaded, set opcache.enable_cli=1 to enable it for CLI processes. Set opcache.jit=tracing and a nonzero opcache.jit_buffer_size to enable tracing JIT. Run the quick-start application with these settings.
php -d opcache.enable_cli=1 -d opcache.jit=tracing -d opcache.jit_buffer_size=64M main.phpSet LEANFRAN_CLI to select the compiler executable used by host tools (default: leanfran on
PATH). Set LAKE to select the Lake executable used by the compiler (default: lake on PATH).
Run the leanfran executable with --lang php from the application directory. Pass --dir <dir> to select another directory. The project root is the nearest directory at or above it with a leanfran.toml, or else with a composer.json.
| Command | Effect |
|---|---|
leanfran --lang php sync |
Scans the package, builds the blocks in .leanfran/php/workspace, and installs their generated PHP and leanfran.manifest.json after every block succeeds. |
leanfran --lang php status |
Prints <class>: stale, <class>: missing <path> and <class>: removed for blocks, and <id> [<label>]: <state> for saved proof states. It runs without Lean and exits 1 if outputs or proof results are stale. |
leanfran --lang php check |
Runs sync, translates the #[Model] functions, and checks their Lean proofs. Accepts --require proved to enforce a proof policy. |
The executable reads the package with php vendor/conao3/leanfran/bin/leanfran scan and, during check, translate. These two commands print JSON and write no file; the executable builds the Lean workspace, generates the PHP and installs it. If the project root has no vendor/conao3/leanfran, the executable prints how to install the package and exits 255. The Composer package installs no leanfran command. The release version, generator version and Lean version of the executable must match the installed Composer package, and lean and lake on PATH must have the executable's Lean version, Lean 4.35.0. A lean-toolchain at the project root must name the same version. A mismatch exits 255. The executable reads Lean::VERSION of vendor/conao3/leanfran before it runs the package and, for another release, exits 255 with composer require conao3/leanfran:<version> for its own release. The package exits 255 and names the compiler release to install when an older executable passes it sync, check or status.
You can run leanfran --lang php status in a job with PHP, sha256sum or shasum and the leanfran executable but no Lean toolchain to check freshness of committed outputs and proof results. Run check after editing proof files to refresh their results and enforce the proved policy.
Use leanfran generate to generate PHP from the modules listed in your project's leanfran.toml. A PHP table maps its output directory to a Composer PSR-4 namespace and shares types between its modules.
leanfran --lang php module generate reads a compiled Lean module and emits PHP source. Run leanfran --lang php --help to list the commands and leanfran --lang php <command> --help to list the options of a command. --version prints the compiler's release version and its Lean version. --generator-version prints the emitted-code version.
| Option | Effect |
|---|---|
--module-name <Name> |
Selects the compiled Lean module. Required for a single job. |
--roots <Name> ... |
Selects the definitions to generate. Defaults to public definitions in the selected module. |
--import <Name> ... |
Imports additional Lean modules, whose @[csimp] lemmas apply. |
--search-path <dir> ... |
Adds directories to the search path for .olean files. |
--output-dir <dir> |
Writes PSR-4 public types, a facade, and an internal class. |
--php-namespace <NS> |
Sets the PHP namespace. Required with --output-dir. |
--facade <Name> |
Names the public facade. Defaults to the last component of the module name. |
--facade-kind class|trait |
Emits a facade class or trait. The default is class. |
--type-module <N=NS> ... |
Reuses types from Lean namespace N that were generated into PHP namespace NS. The option takes several values. |
--class <NS\Name> |
Sets the PHP class name for single-file output. |
--main <Name> |
Generates a CLI entry point for a Lean IO definition in single-file output. |
--output-file <path> |
Writes the PHP source to the given file. Defaults to stdout. |
--output json|text |
Sets the summary format. Defaults to JSON. The summary goes to stderr when source goes to stdout. |
--internal-only |
Selects the runtime-facing class, also the default without --output-dir. |
--namespace <Name> |
Removes a Lean namespace prefix from public names. Defaults to the module name. |
--batch <file> |
Reads a JSON array of jobs. Each job has module, either output_file or output_dir, and optionally roots and namespace. A job with output_file also takes class and main. A job with output_dir requires path, the PHP namespace, and also takes facade, facade_kind, type_modules (objects with namespace and target), models, and type_group (a string shared by the jobs that share types). Unknown keys and values of another type are errors. |
The JSON summary is an array with one object per job: module, files, functions (lean and name of every generated function), externs (the runtime functions that the code calls), skipped (name and reason), error (code and message) for a failed job, and data. data has the generated class and, for --output-dir, public with the facade methods. The exit code of a batch is the highest code of its jobs.
Use --output-dir together with --php-namespace. Options for single-file output (--output-file, --internal-only, --class, and --main) are incompatible with --output-dir. The facade and shared-type options apply to directory output. leanfran --lang php obligations check --modules … --obligations file returns JSON states for the supplied obligations. Its exit status indicates whether the command ran successfully. Use leanfran --lang php check --require proved to enforce their states.
sync, check, and status exit 0 on success. They exit 1 when status prints a stale, missing, or removed output or a stale or removed function, when check or status reports an unextracted or failed obligation, or when an obligation is not proved under --require proved. They exit 252 for an argument they cannot read, 254 for an error in the package (a Lean diagnostic, a scan error, a file leanfran did not generate at a path that sync writes) and 255 for an error in the environment (a missing package or tool such as sha256sum, shasum on macOS, a version mismatch).
The other commands of leanfran --lang php use these codes.
| Exit code | Meaning |
|---|---|
| 0 | Success |
| 1 | Out-of-date output or unmet obligations (status, check) |
| 252 | Invalid arguments or batch jobs, including an invalid class name |
| 254 | Input that cannot be converted, such as a module without an .olean in the search path or a call to an extern outside the runtime's inventory |
| 255 | Other errors, such as failure to write the output file |
The project file leanfran.toml is optional. The settings of sync, check and status describe the project root, [check], [[require]] and projects with several languages.
[embed.php]
paths = ["src"]paths of [embed.php] lists the directories to scan, relative to the project root. Without it, the commands scan the autoload.psr-4 directories of the composer.json in the project root, and exit 254 without that file. A directory that does not exist is skipped. The Composer package runs from vendor in the project root. When composer.json is in a directory below leanfran.toml, set Composer's config.vendor-dir to the vendor of the project root.
extra.leanfran in a composer.json is an error with exit code 254 that names the [embed.php] table. Composer scripts can run the executable, for example "lean:sync": "leanfran --lang php sync".
| Variable | Effect |
|---|---|
LEANFRAN_RUNS, LEANFRAN_SEED |
The number of inputs and the seed of the random tests. |
LEANFRAN_AUTO_SYNC=1 |
A Lean block that is out of date runs leanfran --lang php sync --dir <root> instead of throwing LeanBlockStale. |
Attach #[Conao3\Leanfran\Model(...)] to a typed static method or a named function. The attribute binds the function to executable Lean specifications in a #[Lean] block. The cart sample proves a summation loop correct when every price and the list length are bounded.
Start in the application directory from the PHP quick start. Save this as src/Calc.php. The #[Model] attribute links the PHP implementation to an executable Lean specification, an input condition, and a property of the result.
<?php
declare(strict_types=1);
namespace App;
use Conao3\Leanfran\Lean;
use Conao3\Leanfran\Model;
#[Lean(<<<'LEAN'
def clampSpec (x lo hi : Int) : Int := max lo (min hi x)
def ordered (_x lo hi : Int) : Bool := lo ≤ hi
def inRange (_x lo hi : Int) (r : Int) : Bool := lo ≤ r && r ≤ hi
LEAN)]
final class Calc
{
use Calc\Functions;
#[Model(refines: 'clampSpec', requires: 'ordered', ensures: ['in_range' => 'inRange'])]
public static function clamp(int $x, int $lo, int $hi): int
{
if ($x < $lo) {
return $lo;
}
if ($x > $hi) {
return $hi;
}
return $x;
}
}Copy the proofs into lean/Proofs/ next to composer.json. Install the PHP parser as a development dependency.
mkdir -p lean/Proofs
cp ../lean-leanfran/langs/PHP/samples/verified-clamp/lean/Proofs/Calc.lean lean/Proofs/
composer require --dev --no-interaction 'nikic/php-parser:^5.9'
leanfran --lang php check --require provedThe proof check reports both obligations as proved and writes leanfran.lock. Commit it with the manifest.
App\Calc\clamp [in_range]: proved
App\Calc\clamp [refines]: proved
Run the random test and call the implementation.
php -r 'require "vendor/autoload.php"; Conao3\Leanfran\Verify::checkClass(App\Calc::class); echo App\Calc::clamp(12, 0, 10), PHP_EOL;'10
| Argument | Purpose |
|---|---|
refines |
Lean function that takes the PHP arguments in the same order and returns the specification's result. The proof establishes equality with that result. |
requires |
Lean function that takes the arguments and returns Bool. Every obligation assumes it returns true. |
ensures |
Literal map from obligation labels to Lean functions taking the arguments followed by the result and returning Bool. A label matches [a-z][a-z0-9_]*, and refines is reserved. |
spec |
Class containing the #[Lean] block, written as a fully qualified string or a ClassName::class literal. Defaults to the declaring class for a method. Specify it on a namespace function. |
Use names relative to the selected block. A dotted name can select a Lean declaration in a namespace within the block. Each option is optional when the block can be inferred. A random test needs at least one refines or ensures oracle. Install nikic/php-parser as a development dependency in the application that declares the models. Run the following from its Composer directory.
composer require --dev --no-interaction 'nikic/php-parser:^5.9'The translator expects by-value parameters and return values, locals with consistent types, and a return or throw on every path. A call to another modeled function must resolve statically within the same project, pass all arguments positionally, and avoid recursive cycles. In a namespace, an unqualified call to a built-in or an unqualified PHP_INT_MAX or PHP_INT_MIN names the global one when neither a PHP file of the project outside vendor nor a file that the Composer autoloader loads defines that name in the namespace; write \max or \PHP_INT_MAX otherwise.
| Area | Supported forms |
|---|---|
| Parameters and results | int → Int, bool → Bool, string → String, float → Float, and native ?T → Option. Use PHPDoc list<T> or array{0: A, 1: B} on native array for a Lean list or pair. |
| Value types | Backed enums and final classes with promoted public readonly properties and no destructor. Supported generated public value types are enums and structures with representable fields, and with the name of their Lean type. Construction in the translated body requires a structural constructor. A generated constructor's supported invariant checks translate to failure branches. |
| Statements | Local assignment and reassignment, two-element tuple destructuring, +=, -=, *=, .=, and integer increment and decrement as statements. Also if/elseif/else, early return, foreach over lists with or without the index, for, while, single-level break/continue, throw new X(...), and append to a list created in the function. |
| Expressions | Integer +, -, *, %, unary minus, and intdiv. Float +, -, *, /, and unary minus. Same-type <, <=, >, and >= for numbers and booleans. Strict equality and inequality on same-type scalars and enum cases, or when comparing a nullable value with null. An int becomes a float where PHP converts it: in a return, an argument of a modeled function, and an argument of a constructor. Boolean &&, ||, and !, ternaries, match, list indices, constant tuple indices, property reads, enum cases, list and pair literals, and structural new. |
| Built-ins | count for a list or pair, abs for a number, two-argument min and max on integers, strlen for the byte length of a string, and . for string concatenation. |
Outside this subset are missing parameter or return types, mixed, general unions, unannotated arrays, associative arrays, integer /, loose comparisons (==, !=, <=>), and object, list, or tuple operands to === or !==. PHP object comparisons use identity. min and max on floats are outside it because their results on NaN and −0.0 depend on OPcache. So are an int in a local variable, list, or tuple of floats, where PHP keeps the int, and float literals in another notation than decimal. The subset also excludes parameters with the default null and a type without ?, self in a trait, calls to non-public methods of another class, invalid UTF-8 strings, interpolation, string indexing, ??, references, variadic parameters, PHP globals and static locals, property writes, dynamic calls, generators, I/O, and exception handlers. Unsupported syntax produces a source location and an unextracted state.
Lean models the body using do notation. An infallible body uses Id.run. A body with a modeled failure, a for or while loop, or a call to a fallible function uses Php.M α, an alias for Except Php.Exc α. The rules are implemented in LeanPhpLib.Php.
| PHP operation | Lean behavior |
|---|---|
Integer addition, subtraction, multiplication, negation and abs |
Arithmetic on Int, checked against the signed 64-bit range. When PHP promotes the result to a float, the model returns overflow. |
intdiv |
Division truncating toward zero. A zero divisor gives divisionByZero. Dividing PHP_INT_MIN by −1 gives arithmeticError. |
% |
Remainder with the dividend's sign. A zero divisor gives divisionByZero. |
| Float division | A zero divisor gives divisionByZero. |
| List indexing | Negative or out-of-range indices give undefinedIndex, corresponding to PHP's warning and null result. |
| Integer fields of generated classes | PHP holds them as int|\GMP. They are passed on, compared with <, <=, >, and >=, and passed to min and max as they are. Every other use takes their int, and gives overflow outside the signed 64-bit range. |
match |
A match with no matching arm or default gives unhandledMatch. |
throw new X(...) |
A failure carrying the exception class name. |
The proof describes the translated function under its input contract. PHP strings must contain valid UTF-8, arrays must have the list or pair shape in their PHPDoc, and numbers must follow the PHP types at the boundary. String equality compares byte sequences and strlen counts UTF-8 bytes. They rely on the translator and its model of PHP operations. After an overflow or an undefinedIndex PHP continues with a float, a GMP, or null, which the model does not have, so no obligation holds for an input that reaches one. A proved refinement of a fallible translation establishes that it returns Except.ok on inputs satisfying the precondition. A proved postcondition establishes that the function returns a value with the postcondition or throws an exception. Both establish that the loops of the function end.
The logical assumptions are the requires predicate and the invariants of supported generated public types that their constructors validate. PHPDoc supplies the shape of a list or pair. PHPDoc bounds such as int<0, 100> and length refinements supply no assumptions. Put those conditions in requires if the proof needs them. A verified function cannot use an imported PHP value type whose Lean representation assumes stronger PHPDoc constraints. A standalone PHP value type is translated using just its shape.
The translated name is LeanPhpModel.<namespace>.<class>.<method> for a method, with the class component omitted for a namespace function. The translator writes an abbrev <function>.obligation.<label> : Prop for each refinement and postcondition. Each obligation universally quantifies the arguments and includes the precondition when present. A refinement equates the result with the spec, wrapped in Except.ok for a fallible body. A postcondition says the predicate on the arguments and result is true. For a fallible body it is Php.Ensures <call> fun result => <predicate>: the predicate holds for a result returned via Except.ok, and the call has neither overflow nor undefinedIndex.
Place Lean modules under lean/Proofs/ at the project root. Import the generated model module and prove <function>.proof.<label> with the corresponding obligation as its type. Open the block's LeanPhpEmbed.<namespace>.<class> aliases to refer to the specifications. The following theorem appears in the clamp proof file.
import LeanPhpModel.App.Calc
open LeanPhpEmbed.App.Calc
namespace LeanPhpModel.App.Calc
theorem clamp.proof.refines : clamp.obligation.refines := by
intro x lo hi h
simp only [ordered, decide_eq_true_eq] at h
simp only [clamp, clampSpec]
split <;> (try split) <;> simp_all <;> omega
end LeanPhpModel.App.Calcleanfran --lang php check syncs the blocks, translates the modeled functions, builds their Lean definitions and proofs, and writes proof results and input hashes to leanfran.lock. It prints a state per obligation.
| State | Meaning |
|---|---|
proved |
The theorem's type is definitionally equal to the obligation, the kernel accepts the theorem and every declaration outside the Lean toolchain that it or the obligation uses, and its axioms are limited to propext, Quot.sound, and Classical.choice. |
sorry |
The proof depends on sorryAx. |
axioms |
The proof depends on an axiom outside the allowed set. |
failed |
The proof or a declaration it uses has an error, or the kernel rejects one of them. |
missing |
The expected theorem is absent from the built proof modules. |
mismatch |
The theorem's type differs from the obligation. |
unextracted |
The translator or Lean could not produce the obligation, or the translated definition uses an instance on standard types from another module. |
check and status print <id> [<label>]: <state> lines, where <id> is the namespaced function or method name such as App\Calc\clamp. An unextracted function also prints <file>:<line>:<column>: error: unextracted <id>: <reason> to standard error. Functions that a tool rejects lists the reasons. check exits 1 if any obligation is unextracted or failed, and with --require proved if any obligation has a state other than proved. status runs without Lean, parses the model source using the same PHP parser, and compares the lock with the current model bodies, the Lean blocks, the translator sources and the proof files. It reports a function as stale when its saved result is missing, or when its source, the block of its specs, a class or enum that it names, a function it calls, or one of the other inputs has changed, and a locked function without #[Model] as <id>: removed. Stale outputs, stale proof results and saved unextracted or failed states produce exit 1. The other fresh saved states give a successful status, unless --require proved is given.
Leanfran replaces a specification only when status reports a proved refines without
requires, the generated code can call the implementation, and its values can round-trip.
The model must not use a specification that is a candidate for replacement. If several
functions qualify for one specification, the first by function id wins.
The obligation must cover all of the specification's arguments in the same order, and the model
and specification types must match after unfolding reducible definitions such as abbrev.
The sole result exception is an Int model result for a Nat specification; that proof
guarantees a nonnegative result. Arguments coerced or supplied by elaboration do not qualify.
check writes the lock and applies the replacement. The next sync drops it if the function,
its dependencies, the proofs, or other inputs changed so that status no longer reports it as
proved. Until that sync, generated calls may still reach the changed implementation.
Random tests always compare the host function against the Lean body with no replacements.
Generated code resolves a named function or static method through Composer autoloading
(autoload.files for a function) and calls the Lean body if the target is unavailable or an
argument contains an integer outside the native 64-bit range. The unreplaced methods used by
the random tests remain in the generated class under Internal/. Exceptions reach the caller.
Instance methods and parameters of classes whose constructors can reject converted values
are not eligible. A bounded integer implementation that needs requires for its proof is
not substituted. Calls already inlined by Lean keep the Lean body; use @[noinline] to keep
a callable definition.
Each accepted input calls the implementation once. The test checks refines first, then
ensures in the written order, and reports the first failure for that function. run is the
zero-based index of the original failure among accepted inputs; input shows the counterexample
after shrinking. If the host call fails, the value is failed: <reason>. If a specification
fails, the report says the spec failed and shows error: <reason>.
Conao3\Leanfran\Verify::checkModel(callable $f, ?int $runs = null, ?int $seed = null): void runs one model, with LEANFRAN_RUNS (1 to 2147483647, 200 by default) accepted inputs and the seed LEANFRAN_SEED (0 to 9223372036854775807, 1 by default) for the arguments it lacks. Verify::checkClass(string $class): void runs the annotated methods declared by that class with the defaults and reports failures together. Pass [Calc::class, 'clamp'] to test just that method. Call either entry point from PHPUnit or a standalone PHP script. The clamp sample calls checkClass before printing its result.
The tester runs the selected block's generated PHP wrappers, with the Lean bodies of the specifications that a function replaces. Run sync or check first and keep the generated files, leanfran.manifest.json, and the PHP parser available. It does not read leanfran.toml: it finds the blocks through the source entries of the manifest, and checks the compiler version, the hash, and the generated files of the block it uses. A block that is out of date throws LeanBlockStale before the first input, or, with LEANFRAN_AUTO_SYNC=1, after it ran sync: the next start of the test uses the new PHP. Only leanfran --lang php status reports a change of [[require]] or paths. Preserve the generated methods’ PHPDoc when using OPcache. The tests themselves run without Lean. Boundary cases include 0, ±1, the integer limits, ±(2^53 + 1), NaN, the infinities, −0.0, the smallest subnormal float, empty lists and strings, and single ASCII and non-ASCII characters. The tester then uses a local seeded Mt19937 engine. Random strings have up to eight Unicode scalars, lists have up to eight elements with repeated ones, and nested list and nullable values are depth-limited. Integer fields of generated classes include values outside the signed 64-bit range.
Inputs that fail a generated value check or whose requires predicate returns false are discarded. Repeated cases count as accepted inputs. The test fails with only <n> of <runs> inputs satisfied requires when it discards more than 100 candidates per requested run. It compares results with refines and evaluates each ensures on the PHP result. refines compares arrays and public object fields structurally, with exact integer comparison for GMP results. Scalars of different PHP types compare unequal, as do 0.0 and −0.0. NaN equals NaN.
A counterexample throws Conao3\Leanfran\Verify\PropertyFailure, whose message gives the function, the label, the seed, and the number of the run (from 0, of the accepted inputs). The test below has a function that is wrong for x > 100, and its requires accepts even numbers.
App\Properties\refinesWrong [refines]: mismatch (seed 1, run 2)
input: x=102
expected: 103, got: 102
The input is the smallest that the tester finds for the same label: integers and floats closer to 0, shorter lists and strings, null, false, the first enum case, and objects with such fields. The run is that of the first failure. Shrinking ends after 1,000 calls of the function.
For a failed postcondition, the first line says <name in the block> does not hold, and the last line is result: <value>. A function that throws shows failed: <exception> as its value. A specification that throws shows the spec failed and error: <exception>. A Lean panic in a specification shows error: panic: <message>. The properties of the exception hold these values, such as input, actual, expected, run, and specFailed.
If the PHP function throws on an accepted input, the test fails and preserves the throwable, including a TypeError from returning an overflowed float through an int signature. With only postconditions, this uses the first label and expects a successful return. A float returned to an integer specification also fails the result comparison. Reuse the seed and run count to reproduce the sequence.
For a Lean-enabled CI job, install Composer development dependencies, put the leanfran compiler and the selected Lean toolchain on PATH, and run the proof and property checks. For the clamp sample, run the following from its Composer directory.
leanfran --lang php check --require proved
php main.phpThe public API skips private definitions, polymorphic functions, indexed inductives, type classes, propositions, higher-order signatures, constructors with type-valued fields, and proof fields without a Decidable instance. It also skips types with ambiguous nullability such as Option (Option α), library types under Std, Lean, IO, and System outside the supported mappings, and runtime-only types such as ByteArray, Thunk, and Task. Read skipped in the generation summary for the reason on each definition.