Conao3 Notes

leanfran for PHP: call Lean 4 functions from PHP, and prove PHP functions in Lean

I built the PHP version of leanfran, which lets you call functions written and proved in Lean 4 from PHP classes. Lean structures and inductive types become PHP classes that check Lean's conditions when you create a value, and in the other direction you can translate functions written in PHP into Lean and prove their properties in Lean.

The repository is langs/PHP/ in conao3/lean-leanfran, under the Apache-2.0 license. The package is on Packagist as conao3/leanfran, and this post is based on running version 0.7.0.

leanfran turns the intermediate representation of the Lean compiler into PHP source, and the generated PHP runs with only the Composer package, so you don't need Lean at run time.

The post that introduced leanfran covers the other four languages, Rust, Python, TypeScript, and Clojure, and PHP ships from the same repository at the same version.

Three ways to use it

There are three ways to use leanfran from PHP.

img

  1. Write Lean functions and theorems in a PHP class with #[Lean(...)], and call the methods that vendor/bin/leanfran sync generates from PHP.
  2. Pass Lean structures and inductive types around as PHP classes that come with checks and JSON conversion.
  3. Add #[Model(...)] to a function written in PHP to translate it into Lean, and check the proofs of its properties with vendor/bin/leanfran check.

1 and 2 go from Lean to PHP, and 3 goes from PHP to Lean.

Writing Lean in a PHP class

Install leanfran-php, the CLI that converts Lean code, with nix, and add the Composer package to your application.

$ nix profile install github:conao3/lean-leanfran/v0.7.0#php
$ composer require conao3/leanfran

The package runs on 64-bit PHP 8.4 or later with the GMP and Tokenizer extensions. Generating code and checking proofs also need lean and lake from Lean 4.35.0 on your PATH.

In autoload.psr-4 of composer.json, map the App namespace to src/, and write the following class in src/Pricing.php.

<?php

declare(strict_types=1);

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;
}

The #[Lean(...)] attribute holds the Lean source as a nowdoc, and the class uses the generated trait Pricing\Functions. The ok field of Range holds a proof of lo ≤ hi, and width_le is a theorem that the width is at most the upper bound.

The caller, main.php, creates a Range from the generated class and passes it to Pricing::width.

<?php

declare(strict_types=1);

use App\Pricing;
use App\Pricing\Range;

require __DIR__ . '/vendor/autoload.php';

echo Pricing::width(new Range(lo: 2, hi: 5)), PHP_EOL;

vendor/bin/leanfran sync has Lean check the theorem and then generates the PHP, so after that you can run the code with PHP alone.

$ vendor/bin/leanfran sync
leanfran: 1 block checked and generated
$ php main.php
3

The generated files go to src/Pricing/, next to the class.

$ find src -type f | sort
src/Pricing/Functions.php
src/Pricing/Internal/LeanPricing.php
src/Pricing/leanfran.json
src/Pricing.php
src/Pricing/Range.php

Functions.php is the trait with the width method, Range.php is the class for the type, and Internal/LeanPricing.php is the body generated from Lean's intermediate representation. leanfran.json records the hash of the block and the generated files.

If you commit the generated files to the repository, CI can check with vendor/bin/leanfran status that they are up to date without installing Lean.

If you change the theorem to width r ≤ r.lo, the proof fails and generation stops there.

$ vendor/bin/leanfran sync
src/Pricing.php:19:7: error: (lean block App\Pricing, Lean 10:2) omega could not prove the goal:
a possible counterexample may satisfy the constraints
  b ≥ 0
  a ≥ 0
  a - b ≤ 0
  2*a - b ≤ -1
where
 a := ↑r.lo
 b := ↑r.hi
lake build failed

The error starts with the line and column in the PHP file, followed by the line and column of the Lean code inside the block. If generation fails, the previously generated PHP stays in place, so php main.php still prints 3 after this.

Lean types become PHP classes

Range becomes a final readonly class, lo and hi become public properties, and the proof field ok becomes a check in the constructor. The following range.php creates a value from JSON, passes input that breaks the condition to the constructor, and then prints the JSON Schema.

<?php

declare(strict_types=1);

use App\Pricing\Range;
use Conao3\Leanfran\ValidationError;

require __DIR__ . '/vendor/autoload.php';

$r = Range::fromJson('{"lo":1,"hi":4}');
echo $r->hi, PHP_EOL;

try {
    new Range(lo: 5, hi: 2);
} catch (ValidationError $e) {
    echo $e->getMessage(), PHP_EOL;
}

echo json_encode(Range::jsonSchema(), JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES), PHP_EOL;
$ php range.php
4
Range.ok: lo ≤ hi
{
    "$schema": "https://json-schema.org/draft/2020-12/schema",
    "type": "object",
    "properties": {
        "lo": {
            "type": "integer",
            "minimum": 0
        },
        "hi": {
            "type": "integer",
            "minimum": 0
        }
    },
    "required": [
        "lo",
        "hi"
    ],
    "additionalProperties": false
}

The constructor runs the lo ≤ hi check with code compiled from Lean, so a value whose lo is greater than hi raises a ValidationError.

JSON Schema cannot express lo ≤ hi, which spans two fields, so the schema only shows the lower bound of Nat. The constructor checks this condition, and the same check runs when you create a value from an array or pass a generated class to the Valinor mapper.

If you pass a readonly class written in PHP to models in #[Lean(...)], it comes into Lean as a structure, and ranges such as int<0, 100> in the class's PHPDoc become proof fields.

Proving PHP functions in Lean

For the other direction, write clamp, which keeps a value within a range, in PHP, and tie it to a Lean specification with #[Model(...)].

<?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;
    }
}

refines names a Lean function that returns the same value as the implementation, requires the precondition on the input, and ensures the conditions the return value meets. In this example, the proof obligations are that clamp returns the same value as clampSpec when lo ≤ hi, and that the return value is at least lo and at most hi.

vendor/bin/leanfran check reads the PHP syntax tree, translates the function into a Lean function in do notation, and creates the obligation propositions with names such as clamp.obligation.refines. The proofs go in lean/Proofs/ next to composer.json, and here I use the proof from the verified-clamp sample as is.

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

theorem clamp.proof.in_range : clamp.obligation.in_range := by
  intro x lo hi h
  simp only [ordered, decide_eq_true_eq] at h
  simp only [clamp, inRange]
  split <;> (try split) <;> simp_all <;> omega

end LeanPhpModel.App.Calc

leanfran reads the PHP syntax tree with nikic/php-parser, so add it as a development dependency and then run check.

$ composer require -q --dev --no-interaction 'nikic/php-parser:^5.9'
$ vendor/bin/leanfran check --require proved
leanfran: 2 blocks checked and generated
App\Calc\clamp refines: proved
App\Calc\clamp in_range: proved
leanfran: all blocks up to date

With --require proved, the exit code is 1 if any obligation is not proved. proved means that the type of the theorem matches the obligation and the proof relies on neither sorry nor any axiom outside the three standard ones.

You can also compare the PHP implementation with the Lean specification in a random test that doesn't use Lean.

<?php

declare(strict_types=1);

use App\Calc;
use Conao3\Leanfran\Verify;
use Conao3\Leanfran\Verify\PropertyFailure;

require __DIR__ . '/vendor/autoload.php';

try {
    Verify::checkClass(Calc::class);
    echo 'ok', PHP_EOL;
} catch (PropertyFailure $e) {
    echo $e->getMessage(), PHP_EOL;
}
$ php verify.php
ok

Verify::checkClass builds inputs from boundary values such as 0 and the integer limits and from random numbers with a fixed seed, and collects 200 inputs that meet requires. For each input, it compares the return value of the PHP clamp with the value of the generated clampSpec.

Now change the second if of the implementation so that it returns $hi - 1 when $x is greater than or equal to $hi.

if ($x >= $hi) {
    return $hi - 1;
}

check can no longer pass the two proofs, so it prints Lean's errors to standard error and marks each obligation failed.

$ vendor/bin/leanfran check --require proved 2>/dev/null
leanfran: 2 blocks checked and generated
App\Calc\clamp refines: failed
App\Calc\clamp in_range: failed
leanfran: all blocks up to date

The random test also finds a counterexample, an input where all three arguments are 0.

$ php verify.php
App\Calc\clamp [refines] failed (seed=1, input=[0, 0, 0]): implementation returned -1; spec expected 0

What the proofs guarantee

The Lean theorems guarantee properties of the functions written in Lean and of the Lean models translated from PHP. For those properties to hold when the generated PHP or the original PHP runs, the converter, the runtime, and the model of PHP's operations must be correct, and I check these parts with tests.

leanfran checks integer operations in PHP within the 64-bit range, and a calculation that overflows into a float fails in the model too. In a function with #[Model(...)], ranges such as int<0, 100> in the PHPDoc of the arguments are not assumptions for the proof, so write the conditions the proof uses in requires.

leanfran can translate a subset of PHP: it handles foreach, match, list indexing, readonly classes, and enum, but not pass-by-reference, ??, or functions that do input and output. The full list of supported syntax is in the PHP guide.

For the generated PHP, tests compare its results with those of Lean's C backend.

At the time of writing, the results of 1,707,520 numeric operations built from boundary values and random numbers match the C backend byte for byte on both PHP 8.4 and 8.5. 65 cases, such as Float32 transcendental functions, differ by no more than one step of the smallest floating-point increment.

Wrapping up

Besides the examples in this post, the PHP samples include verified-cart, which proves a loop that computes a total, assuming upper bounds on prices and quantities, and embed-orders, which shares types between two blocks. There is also greet-cli, which runs a Lean IO function as a PHP command.

The setup steps are in the PHP README, and the details of the type mapping and the CLI are in the PHP guide.