Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 9 additions & 2 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,7 @@ jobs:
echo "backends=$backends" >> "$GITHUB_OUTPUT"

check:
name: make check (${{ matrix.dir }})
name: make check (${{ matrix.dir }}${{ matrix.suffix }})
needs: changes
runs-on: ubuntu-latest
timeout-minutes: 60
Expand All @@ -55,6 +55,11 @@ jobs:
- dir: TypeScript
- dir: Clojure
maven: true
target: check-core
- dir: Clojure
maven: true
suffix: ', verification'
target: check-verify
- dir: PHP
nix-shells: php php85
- dir: Go
Expand Down Expand Up @@ -91,8 +96,10 @@ jobs:
~/.gitlibs
key: maven-${{ runner.os }}-${{ hashFiles('langs/Clojure/**/deps.edn') }}
restore-keys: maven-${{ runner.os }}-
- if: env.RUN_BACKEND == 'true'
- if: env.RUN_BACKEND == 'true' && !matrix.target
run: make check BACKENDS=${{ matrix.dir }}
- if: env.RUN_BACKEND == 'true' && matrix.target
run: nix develop .#clojure -c make -C langs/Clojure ${{ matrix.target }}
check-compiler:
name: leanfran (all languages, ${{ matrix.os }})
runs-on: ${{ matrix.os }}
Expand Down
2 changes: 2 additions & 0 deletions CONTRIBUTING.md
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,8 @@ The Rust and PHP environments contain store paths that cache.nixos.org lacks: Ae

Pull requests run the checks for affected backends, including cross-backend test inputs listed in `maint/ci-backends.sh`. Shared or unrecognized paths trigger all checks. A new commit cancels the previous CI run for that pull request. Runs on `master` and release tags still check every backend.

`maint/test-all-languages.sh .lake/build/bin/leanfran` runs `sync`, `check`, and `status` in one project with all seven backends and compares the manifest and lock byte for byte across command orders. Run it in the default development shell after building the compiler and preparing the Python environment, TypeScript distribution, and PHP dependencies. `maint/test-property-parity.sh .lake/build/bin/leanfran <language>` uses the same counterexample and boolean inputs in each backend's development shell. It prints the first failing run and the shrunk input so their values can be compared across languages.

## Packaging

[LICENSE](LICENSE) applies to all backends. Cargo inherits its path from the Rust workspace. Hatch includes it in Python wheels and source distributions. The TypeScript `make pack` target copies it into `dist/LICENSE`, and the Clojure JAR builder includes it as `META-INF/LICENSE`. The PHP runtime declares the repository's Apache-2.0 license in its Composer manifest.
Expand Down
2 changes: 1 addition & 1 deletion docs/php-guide.md
Original file line number Diff line number Diff line change
Expand Up @@ -381,7 +381,7 @@ A proved `refines` without `requires` replaces the specification. The generated

### Random tests

`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. Pass `[Calc::class, 'clamp']` to test just that method. Call either entry point from PHPUnit or a standalone PHP script. The [clamp sample](../langs/PHP/samples/verified-clamp/main.php) calls `checkClass` before printing its result.
`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](../langs/PHP/samples/verified-clamp/main.php) 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.

Expand Down
2 changes: 1 addition & 1 deletion docs/python-guide.md
Original file line number Diff line number Diff line change
Expand Up @@ -531,7 +531,7 @@ in the generated module: the attribute `spec` of a public function (`spec.sumTo.
### Random tests

- `check_model(f)` / `check_module(m)` generate arguments from the annotations (pydantic constraints
included), skip those failing `requires`, and compare with `refines` and `ensures`. A `float` can be a NaN, an infinity or `-0.0`, and a
included), skip those failing `requires`, and compare with `refines` and `ensures`. `check_module(m)` reports failures from all modeled functions together. A `float` can be a NaN, an infinity or `-0.0`, and a
list can have an element twice. An `int` with a lower and an upper bound (`Int64`) takes the bounds and the numbers around
powers of two such as 2⁵³; without both bounds it is between -1000 and 1000, and about one of three
is around ±2³¹, ±2⁵³, ±2⁶³ or ±2⁶⁴ when the function is fast for them: it has no loop, comprehension or recursion, calls only
Expand Down
2 changes: 1 addition & 1 deletion docs/typescript-guide.md
Original file line number Diff line number Diff line change
Expand Up @@ -511,7 +511,7 @@ theorem clamp.proof.refines : clamp.obligation.refines := by
types from the source of the `model(...)` call, discards arguments that fail
`requires` and results that are integers but not safe ones, and throws `PropertyFailure` with
the smallest failing arguments it found: integers near 0, short arrays and strings, each field of an object. `LEANFRAN_RUNS` (1 to 2147483647, 200 by default) is the number of
the other arguments and `LEANFRAN_SEED` (0 to 9223372036854775807, 1 by default) the seed. `checkModule(m)` runs it for every model function of a module.
the other arguments and `LEANFRAN_SEED` (0 to 9223372036854775807, 1 by default) the seed. `checkModule(m)` runs it for every model function of a module and reports failures together.
`arbitrary(schema, fc)` of `leanfran/schema` generates the values of a descriptor.

A specification runs the Lean definitions of its block, also when the generated code calls a proved TypeScript function
Expand Down
1 change: 1 addition & 0 deletions langs/C/Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,7 @@ check-verify: build
../../maint/test-theorems.sh ../../.lake/build/bin/leanfran c
../../maint/test-isolation.sh ../../.lake/build/bin/leanfran c
../../maint/test-freshness.sh ../../.lake/build/bin/leanfran c
../../maint/test-property-parity.sh ../../.lake/build/bin/leanfran c

check-random: build
../../maint/C/test-random.sh
Expand Down
6 changes: 5 additions & 1 deletion langs/Clojure/Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ check-verify: build
../../maint/test-theorems.sh ../../.lake/build/bin/leanfran clojure
../../maint/test-isolation.sh ../../.lake/build/bin/leanfran clojure
../../maint/test-freshness.sh ../../.lake/build/bin/leanfran clojure
../../maint/test-property-parity.sh ../../.lake/build/bin/leanfran clojure
../../maint/test-csimp.sh ../../.lake/build/bin/leanfran clojure

.PHONY: check-samples
Expand All @@ -60,7 +61,10 @@ test-generate: build
../../maint/test-generate.sh ../../.lake/build/bin/leanfran clojure

.PHONY: check
check: format-check lint test check-verify test-generate check-samples check-cli
check: check-core check-verify

.PHONY: check-core
check-core: format-check lint test test-generate check-samples check-cli

.PHONY: jar
jar:
Expand Down
19 changes: 14 additions & 5 deletions langs/Clojure/src/leanfran/runtime.clj
Original file line number Diff line number Diff line change
Expand Up @@ -1329,6 +1329,13 @@
(declare to-clj from-clj)


(defn- required-field
[m k]
(if (and (map? m) (contains? m k))
(get m k)
(throw (IllegalArgumentException. (str "leanfran: missing field " k)))))


(defn- struct->map
[{:keys [fields]} v]
(into {}
Expand All @@ -1340,7 +1347,7 @@
[{:keys [tag size ssize fields]} m]
(let [c (ctor tag size ssize)]
(doseq [[k [where i] d] fields]
(let [x (from-clj d (get m k))]
(let [x (from-clj d (required-field m k))]
(if (= where :obj) (set-obj! c i x) (sset! c i x))))
c))

Expand All @@ -1362,7 +1369,7 @@
tag
(let [c (ctor tag size ssize)]
(doseq [[k [where i] d] fields]
(let [x (from-clj d (get m k))]
(let [x (from-clj d (required-field m k))]
(if (= where :obj) (set-obj! c i x) (sset! c i x))))
c))))

Expand Down Expand Up @@ -1408,8 +1415,10 @@
(when (neg? n) (throw (IllegalArgumentException. (str "leanfran: " n " is not a natural number"))))
n)
:int (norm (bigint v))
:bool (if v 1 0)
:string v
:bool (case v true 1 false 0
(throw (IllegalArgumentException. "leanfran: expected a boolean")))
:string (if (string? v) v
(throw (IllegalArgumentException. "leanfran: expected a string")))
:char (cond
(char? v) (long (int v))
(string? v) (long (.codePointAt ^String v 0))
Expand All @@ -1423,7 +1432,7 @@
:array (mapv #(from-clj (second d) %) v)
:option (if (nil? v) 0 (ctor 1 1 0 (from-clj (second d) v)))
:prod (ctor 0 2 0 (from-clj (nth d 1) (nth v 0)) (from-clj (nth d 2) (nth v 1)))
:field1 (from-clj (nth d 2) (get v (nth d 1)))
:field1 (from-clj (nth d 2) (required-field v (nth d 1)))
:map (reduce (fn [acc [k x]] (ctor 1 2 0 (ctor 0 2 0 (from-clj (nth d 1) k) (from-clj (nth d 2) x)) acc)) 0 (reverse (seq v)))
:set (reduce (fn [acc x] (ctor 1 2 0 (from-clj (second d) x) acc)) 0 (reverse (seq v)))
:ref (let [t (get @types (second d))]
Expand Down
8 changes: 8 additions & 0 deletions langs/Clojure/test/leanfran/core_test.clj
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,14 @@
(t/is (= :spades (flip :hearts))))


(t/deftest deflean-rejects-invalid-public-inputs
(t/is (thrown-with-msg? IllegalArgumentException #"not a natural number" (double -1)))
(t/is (thrown-with-msg? IllegalArgumentException #"missing field :frozen"
(deposit {:owner "ann" :balance 10} 5)))
(t/is (thrown-with-msg? IllegalArgumentException #"expected a string"
(deposit {:owner 1 :balance 10 :frozen false} 5))))


(t/deftest deflean-mixes-forms-and-lean-source
(t/is (= [["a" 2] ["b" 1]] (vec (histogram ["b" "a" "a"]))))
(t/is (= 3 (safe-div 7 2)))
Expand Down
1 change: 1 addition & 0 deletions langs/Go/make/verify.mk
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ check-verify: build
bash ../../maint/test-theorems.sh ../../.lake/build/bin/leanfran go
bash ../../maint/test-isolation.sh ../../.lake/build/bin/leanfran go
bash ../../maint/test-freshness.sh ../../.lake/build/bin/leanfran go
bash ../../maint/test-property-parity.sh ../../.lake/build/bin/leanfran go

check-samples: test-verify-samples

Expand Down
1 change: 1 addition & 0 deletions langs/PHP/make/verify.mk
Original file line number Diff line number Diff line change
Expand Up @@ -12,4 +12,5 @@ check-verify: test-verify-pbt
bash ../../maint/test-theorems.sh ../../.lake/build/bin/leanfran php
bash ../../maint/test-isolation.sh ../../.lake/build/bin/leanfran php
bash ../../maint/test-freshness.sh ../../.lake/build/bin/leanfran php
bash ../../maint/test-property-parity.sh ../../.lake/build/bin/leanfran php
bash ../../maint/test-csimp.sh ../../.lake/build/bin/leanfran php
15 changes: 13 additions & 2 deletions langs/PHP/src/Embed/Bridge.php
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
use Conao3\Leanfran\Runtime as L;
use Conao3\Leanfran\Schema\Desc;
use Conao3\Leanfran\ValidationError;
use ReflectionMethod;

/** Calls the PHP functions that replace Lean specifications in the generated PHP. */
final class Bridge
Expand Down Expand Up @@ -41,10 +42,20 @@ public static function call(string $function, array $arguments, Desc $result): m
private static function find(string $function): ?callable
{
[$class, $method] = [...explode('::', $function), ''];
if ($method !== '' && (!class_exists($class) || !method_exists($class, $method))) {
if ($method === '') {
return is_callable($function) ? $function : null;
}
if (!class_exists($class) || !method_exists($class, $method)) {
return null;
}
$reflection = new ReflectionMethod($class, $method);
if (!$reflection->isStatic()) {
return null;
}
return is_callable($function) ? $function : null;
if ($reflection->isPublic() && is_callable($function)) {
return $function;
}
return $reflection->getClosure();
}

private static function native(mixed $value): bool
Expand Down
18 changes: 17 additions & 1 deletion langs/PHP/src/Verify.php
Original file line number Diff line number Diff line change
Expand Up @@ -76,6 +76,7 @@ public static function checkClass(string $class): void
throw new \InvalidArgumentException("Unknown model class $class");
}
$reflection = new ReflectionClass($class);
$failures = [];
foreach ($reflection->getMethods() as $method) {
if (
$method->getDeclaringClass()->name !== $reflection->name
Expand All @@ -86,7 +87,22 @@ public static function checkClass(string $class): void
if (!$method->isStatic()) {
throw new \InvalidArgumentException("$class::{$method->name}: expected a static model method");
}
self::checkModel($method->getClosure());
try {
self::checkModel($method->getClosure());
} catch (LeanBlockStale $error) {
throw $error;
} catch (RuntimeException $error) {
$failures[] = $error;
}
}
if (count($failures) === 1) {
throw $failures[0];
}
if ($failures !== []) {
throw new RuntimeException(implode("\n", array_map(
static fn(RuntimeException $error) => $error->getMessage(),
$failures,
)));
}
}

Expand Down
8 changes: 4 additions & 4 deletions langs/PHP/src/Verify/Check.php
Original file line number Diff line number Diff line change
Expand Up @@ -145,10 +145,10 @@ private function csimp(string $key): array
) {
return [];
}
$private = $model->node instanceof Stmt\ClassMethod && !$model->node->isPublic();
if ($private && $model->class !== $model->block->name) {
return [];
}
$private =
$model->node instanceof Stmt\ClassMethod
&& !$model->node->isPublic()
&& $model->class === $model->block->name;
return [[
'label' => 'refines',
'spec' => Translate::leanName("{$model->block->module}.$model->refines"),
Expand Down
8 changes: 7 additions & 1 deletion langs/PHP/src/Verify/Inputs.php
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@

use Conao3\Leanfran\Marshal;
use Conao3\Leanfran\Schema\Desc;
use Conao3\Leanfran\ValidationError;
use Exception;
use Random\Engine\Mt19937;
use Random\Randomizer;

Expand Down Expand Up @@ -265,7 +267,11 @@ private function constructObject(Type $type, array $draft): object
foreach ($this->objects->fields($type) as $key => $field) {
$values[$key] = $this->construct($field, $draft[$key]);
}
return new $class(...$values);
try {
return new $class(...$values);
} catch (Exception $error) {
throw new ValidationError([['path' => [], 'message' => $error->getMessage()]]);
}
}

/**
Expand Down
17 changes: 15 additions & 2 deletions langs/PHP/tests/Differential/Complexity.php
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,19 @@
require 'vendor/autoload.php';
require 'test-out/Complexity.php';

function cpuTimeMicros(): int
{
$usage = getrusage();
if ($usage === false) {
throw new RuntimeException('Unable to read process CPU time.');
}
return (
(1_000_000 * ($usage['ru_utime.tv_sec'] + $usage['ru_stime.tv_sec']))
+ $usage['ru_utime.tv_usec']
+ $usage['ru_stime.tv_usec']
);
}

$suffix = new LString('é猫');
Conao3\Leanfran\Runtime\lean_mark_persistent($suffix);

Expand Down Expand Up @@ -54,9 +67,9 @@
for ($i = 0; $i < 3; ++$i) {
foreach ([$n, 4 * $n] as $size) {
$startValue = $input($size);
$start = hrtime(true);
$start = cpuTimeMicros();
$result = $run($size, $startValue);
$times[$size][] = (hrtime(true) - $start) / 1e6;
$times[$size][] = (cpuTimeMicros() - $start) / 1000;
if (!$check($result, $size)) {
throw new RuntimeException("$name returned incorrect contents for $size updates.");
}
Expand Down
1 change: 1 addition & 0 deletions langs/PHP/tests/fixtures/replaced/expected.txt
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,7 @@ Spec::sameTwice [7] = 7 <- same same
Spec::otherTwice [8] = 8 <- other other
Spec::namedTwice [9] = 9 <- App\named App\named
Spec::lostTwice [5] = 5 <- lost lost
Spec::floatTwice [0.5] = 0.5 <- keep_float keep_float
Spec::ofOptionTwice [1] = 4
Spec::ofOptionTwice [null] = 6
Spec::nestedTwice [1] = [1, null]
Expand Down
2 changes: 2 additions & 0 deletions langs/PHP/tests/fixtures/replaced/lean/Proofs/Replaced.lean
Original file line number Diff line number Diff line change
Expand Up @@ -105,6 +105,8 @@ theorem Lost.lost.proof.refines : Lost.lost.obligation.refines := by
intro n
simp [Lost.lost, LeanPhpEmbed.App.Spec.lost]

theorem Lost.keep_float.proof.refines : Lost.keep_float.obligation.refines := fun _ => rfl

theorem named.proof.refines : named.obligation.refines := by
intro n
simp [named, LeanPhpEmbed.App.Spec.named]
Expand Down
4 changes: 4 additions & 0 deletions langs/PHP/tests/fixtures/replaced/main.php
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,9 @@ function text(mixed $value): string
}

$big = gmp_pow(2, 70);
if (class_exists(Lost::class) && Lost::direct(5) !== 5) {
throw new \RuntimeException('The direct call of Lost changed the argument.');
}

show('sumTo', 10);
show('twice', 10);
Expand Down Expand Up @@ -70,6 +73,7 @@ function text(mixed $value): string
show('Spec::otherTwice', 8);
show('Spec::namedTwice', 9);
show('Spec::lostTwice', 5);
show('Spec::floatTwice', 0.5);
show('Spec::ofOptionTwice', 1);
show('Spec::ofOptionTwice', null);
show('Spec::nestedTwice', 1);
Expand Down
19 changes: 18 additions & 1 deletion langs/PHP/tests/fixtures/replaced/src/Lost.php
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,25 @@
final class Lost
{
#[Model(refines: 'lost', spec: Spec::class)]
public static function lost(int $n): int
private static function lost(int $n): int
{
return $n;
}

public static function direct(int $n): int
{
return self::lost($n);
}

/** @param array<mixed> $arguments */
public static function __callStatic(string $name, array $arguments): never
{
throw new \LogicException("Unexpected magic call: $name");
}

#[Model(refines: 'keepFloat', spec: Spec::class)]
protected static function keep_float(float $x): float
{
return $x;
}
}
2 changes: 2 additions & 0 deletions langs/PHP/tests/fixtures/replaced/src/Spec.php
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@
@[noinline] def other (n : Int) : Int := if n = 8 then 8 else n
@[noinline] def named (n : Int) : Int := if n = 9 then 9 else n
@[noinline] def lost (n : Int) : Int := if n = 5 then 5 else n
@[noinline] def keepFloat (x : Float) : Float := x
@[noinline] def ofOption (n : Option Int) : Int := n.getD 3
@[noinline] def nested (n : Option (Option Int)) : Option Int := n.getD none
@[noinline] def positiveOr (n : Int) : Int := max n 1
Expand All @@ -31,6 +32,7 @@
def otherTwice (n : Int) : Int := other (other n)
def namedTwice (n : Int) : Int := named (named n)
def lostTwice (n : Int) : Int := lost (lost n)
def floatTwice (x : Float) : Float := keepFloat (keepFloat x)
def ofOptionTwice (n : Option Int) : Int := ofOption n + ofOption none
def nestedTwice (n : Int) : Option Int × Option Int := (nested (some (some n)), nested none)
def positiveOrTwice (n : Int) : Int := positiveOr (positiveOr n)
Expand Down
Loading
Loading