diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 6e62d807..4fdf7836 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -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 @@ -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 @@ -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 }} diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 4dd0482a..1885fa27 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -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 ` 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. diff --git a/docs/php-guide.md b/docs/php-guide.md index b04220c7..879b25b8 100644 --- a/docs/php-guide.md +++ b/docs/php-guide.md @@ -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. diff --git a/docs/python-guide.md b/docs/python-guide.md index 80403703..52e67402 100644 --- a/docs/python-guide.md +++ b/docs/python-guide.md @@ -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 diff --git a/docs/typescript-guide.md b/docs/typescript-guide.md index d360ed0e..be20f8ac 100644 --- a/docs/typescript-guide.md +++ b/docs/typescript-guide.md @@ -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 diff --git a/langs/C/Makefile b/langs/C/Makefile index 12d92a0c..0cd2d262 100644 --- a/langs/C/Makefile +++ b/langs/C/Makefile @@ -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 diff --git a/langs/Clojure/Makefile b/langs/Clojure/Makefile index faa84cb4..5e5de056 100644 --- a/langs/Clojure/Makefile +++ b/langs/Clojure/Makefile @@ -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 @@ -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: diff --git a/langs/Clojure/src/leanfran/runtime.clj b/langs/Clojure/src/leanfran/runtime.clj index 77335581..e4378c68 100644 --- a/langs/Clojure/src/leanfran/runtime.clj +++ b/langs/Clojure/src/leanfran/runtime.clj @@ -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 {} @@ -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)) @@ -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)))) @@ -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)) @@ -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))] diff --git a/langs/Clojure/test/leanfran/core_test.clj b/langs/Clojure/test/leanfran/core_test.clj index 673871d1..e0a9b06d 100644 --- a/langs/Clojure/test/leanfran/core_test.clj +++ b/langs/Clojure/test/leanfran/core_test.clj @@ -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))) diff --git a/langs/Go/make/verify.mk b/langs/Go/make/verify.mk index 8d3e60e5..4fc091b2 100644 --- a/langs/Go/make/verify.mk +++ b/langs/Go/make/verify.mk @@ -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 diff --git a/langs/PHP/make/verify.mk b/langs/PHP/make/verify.mk index 8b7aa7c8..0d3ee15d 100644 --- a/langs/PHP/make/verify.mk +++ b/langs/PHP/make/verify.mk @@ -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 diff --git a/langs/PHP/src/Embed/Bridge.php b/langs/PHP/src/Embed/Bridge.php index eb07e9e8..a55b507f 100644 --- a/langs/PHP/src/Embed/Bridge.php +++ b/langs/PHP/src/Embed/Bridge.php @@ -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 @@ -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 diff --git a/langs/PHP/src/Verify.php b/langs/PHP/src/Verify.php index 21c7e52d..2ee4a7c7 100644 --- a/langs/PHP/src/Verify.php +++ b/langs/PHP/src/Verify.php @@ -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 @@ -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, + ))); } } diff --git a/langs/PHP/src/Verify/Check.php b/langs/PHP/src/Verify/Check.php index e4145d4b..345c7442 100644 --- a/langs/PHP/src/Verify/Check.php +++ b/langs/PHP/src/Verify/Check.php @@ -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"), diff --git a/langs/PHP/src/Verify/Inputs.php b/langs/PHP/src/Verify/Inputs.php index d427a98b..ff5b86ba 100644 --- a/langs/PHP/src/Verify/Inputs.php +++ b/langs/PHP/src/Verify/Inputs.php @@ -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; @@ -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()]]); + } } /** diff --git a/langs/PHP/tests/Differential/Complexity.php b/langs/PHP/tests/Differential/Complexity.php index e37412d6..0dcbb995 100644 --- a/langs/PHP/tests/Differential/Complexity.php +++ b/langs/PHP/tests/Differential/Complexity.php @@ -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); @@ -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."); } diff --git a/langs/PHP/tests/fixtures/replaced/expected.txt b/langs/PHP/tests/fixtures/replaced/expected.txt index 0afab89d..fe0ece35 100644 --- a/langs/PHP/tests/fixtures/replaced/expected.txt +++ b/langs/PHP/tests/fixtures/replaced/expected.txt @@ -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] diff --git a/langs/PHP/tests/fixtures/replaced/lean/Proofs/Replaced.lean b/langs/PHP/tests/fixtures/replaced/lean/Proofs/Replaced.lean index 87f699b5..853f214a 100644 --- a/langs/PHP/tests/fixtures/replaced/lean/Proofs/Replaced.lean +++ b/langs/PHP/tests/fixtures/replaced/lean/Proofs/Replaced.lean @@ -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] diff --git a/langs/PHP/tests/fixtures/replaced/main.php b/langs/PHP/tests/fixtures/replaced/main.php index e2a76602..4e6a9a9b 100644 --- a/langs/PHP/tests/fixtures/replaced/main.php +++ b/langs/PHP/tests/fixtures/replaced/main.php @@ -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); @@ -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); diff --git a/langs/PHP/tests/fixtures/replaced/src/Lost.php b/langs/PHP/tests/fixtures/replaced/src/Lost.php index f8d1cc0b..7f386e4b 100644 --- a/langs/PHP/tests/fixtures/replaced/src/Lost.php +++ b/langs/PHP/tests/fixtures/replaced/src/Lost.php @@ -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 $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; + } } diff --git a/langs/PHP/tests/fixtures/replaced/src/Spec.php b/langs/PHP/tests/fixtures/replaced/src/Spec.php index 1f11867a..2f323357 100644 --- a/langs/PHP/tests/fixtures/replaced/src/Spec.php +++ b/langs/PHP/tests/fixtures/replaced/src/Spec.php @@ -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 @@ -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) diff --git a/langs/PHP/tests/fixtures/verify/pbt/PropertiesTest.php b/langs/PHP/tests/fixtures/verify/pbt/PropertiesTest.php index 25a039ea..020268b8 100644 --- a/langs/PHP/tests/fixtures/verify/pbt/PropertiesTest.php +++ b/langs/PHP/tests/fixtures/verify/pbt/PropertiesTest.php @@ -5,7 +5,11 @@ use App\Calc; use App\Color; use App\Properties; +use Conao3\Leanfran\Embed\Project; +use Conao3\Leanfran\ValidationError; use Conao3\Leanfran\Verify; +use Conao3\Leanfran\Verify\Inputs; +use Conao3\Leanfran\Verify\Objects; use Conao3\Leanfran\Verify\PropertyFailure; use PHPUnit\Framework\Attributes\DataProvider; use PHPUnit\Framework\TestCase; @@ -43,6 +47,34 @@ public function testOffByOneReportsTheCounterexample(): void } } + public function testClassReportsMultipleCounterexamples(): void + { + try { + Verify::checkClass(Properties::class); + self::fail('Expected the modeled methods to fail'); + } catch (RuntimeException $error) { + self::assertStringContainsString('Properties\\offByOne [refines]: mismatch', $error->getMessage()); + self::assertStringContainsString('Properties\\throwsAbove [refines]: mismatch', $error->getMessage()); + } + } + + public function testConstructorProgrammingErrorsAreNotRejectedInputs(): void + { + $objects = new Objects(Project::load(dirname(__DIR__), new stdClass())); + $type = $objects->type(RejectsInput::class); + $inputs = new Inputs($objects, 1); + try { + $inputs->build([$type], [['value' => 0]]); + self::fail('Expected a rejected input'); + } catch (ValidationError $error) { + self::assertStringContainsString('value rejected', $error->getMessage()); + } + + $this->expectException(TypeError::class); + $this->expectExceptionMessage('constructor bug'); + $inputs->build([$type], [['value' => 1]]); + } + public function testEnvironmentSetsTheDefaultsOfRunsAndSeed(): void { try { @@ -377,3 +409,17 @@ public function testThrowingWithOnlyAnEnsuresClauseIsACounterexample(): void } } } + +final readonly class RejectsInput +{ + public function __construct( + public int $value, + ) { + if ($value === 0) { + throw new DomainException('value rejected'); + } + if ($value === 1) { + throw new TypeError('constructor bug'); + } + } +} diff --git a/langs/Python/Makefile b/langs/Python/Makefile index 84b1c4b2..30455275 100644 --- a/langs/Python/Makefile +++ b/langs/Python/Makefile @@ -20,6 +20,7 @@ check-verify: build ../../maint/test-theorems.sh ../../.lake/build/bin/leanfran python ../../maint/test-isolation.sh ../../.lake/build/bin/leanfran python ../../maint/test-freshness.sh ../../.lake/build/bin/leanfran python + ../../maint/test-property-parity.sh ../../.lake/build/bin/leanfran python ../../maint/test-csimp.sh ../../.lake/build/bin/leanfran python test-generate: build diff --git a/langs/Python/src/leanfran/runtime.py b/langs/Python/src/leanfran/runtime.py index 4c331421..75cb1658 100644 --- a/langs/Python/src/leanfran/runtime.py +++ b/langs/Python/src/leanfran/runtime.py @@ -17,8 +17,11 @@ import importlib import math +import re import struct import sys +from contextlib import contextmanager +from contextvars import ContextVar PERSISTENT = 1 << 62 @@ -216,7 +219,25 @@ def _eprint(msg): sys.stderr.flush() +class LeanPanic(RuntimeError): + pass + + +_raise_panics = ContextVar("leanfran_raise_panics", default=False) + + +@contextmanager +def raising_panics(): + token = _raise_panics.set(True) + try: + yield + finally: + _raise_panics.reset(token) + + def _panic(msg): + if _raise_panics.get(): + raise LeanPanic(re.sub(r"\APANIC at .*?:\d+:\d+: ", "", msg, flags=re.DOTALL)) _eprint(msg) @@ -226,12 +247,14 @@ def lean_panic_fn(default, msg): def lean_panic_fn_borrowed(default, msg): - lean_inc(default) _panic(_s(msg)) + lean_inc(default) return default def lean_internal_panic(msg): + if _raise_panics.get(): + raise LeanPanic(msg) _eprint(f"INTERNAL PANIC: {msg}") sys.exit(1) diff --git a/langs/Python/src/leanfran/verify.py b/langs/Python/src/leanfran/verify.py index 0e3a46ee..5cdf1625 100644 --- a/langs/Python/src/leanfran/verify.py +++ b/langs/Python/src/leanfran/verify.py @@ -23,6 +23,8 @@ import types import typing +from .runtime import LeanPanic, raising_panics + REGISTRY = [] @@ -379,6 +381,13 @@ class PropertyFailure(AssertionError): pass +class _SampleFailure(PropertyFailure): + def __init__(self, inputs, failure): + self.inputs = inputs + self.failure = failure + super().__init__(*failure) + + MAX_RUNS = 2**31 - 1 MAX_SEED = 2**63 - 1 @@ -408,6 +417,8 @@ def spec_name(spec): def _error(e): text = str(e) + if isinstance(e, LeanPanic): + return f"panic: {text}" return f"{type(e).__name__}: {text}" if text else type(e).__name__ @@ -421,11 +432,44 @@ def _call(label, f, *args, limited=False): """Calls the function or the specification; a generated specification runs its Lean body.""" f = getattr(f, "__lean_spec__", f) try: - return _limited(f, *args) if limited else f(*args) + if label is None: + return f(*args) + with raising_panics(): + return _limited(f, *args) if limited else f(*args) except Exception as e: raise _Raised(label, e) from e +def _smaller_integer(value): + yield 0 + magnitude = abs(value) + sign = -1 if value < 0 else 1 + for i in range(magnitude.bit_length() - 1, -1, -1): + step = 1 << i + if step < magnitude: + yield sign * (magnitude - step) + + +def _shrink_wide_integers(inputs, failure, hints, test): + remaining = 1000 + for i, hint in enumerate(hints): + if hint is not int or type(inputs[i]) is not int: + continue + while inputs[i] and remaining: + for value in _smaller_integer(inputs[i]): + candidate = (*inputs[:i], value, *inputs[i + 1 :]) + remaining -= 1 + _, next_failure = test(candidate, force_limit=True) + if next_failure is not None and next_failure[:2] == failure[:2]: + inputs, failure = candidate, next_failure + break + if not remaining: + break + else: + break + return inputs, failure + + def check_model(fn, max_examples=None, seed=None): """Runs the function against its specifications on generated arguments; raises on a counterexample. @@ -451,9 +495,8 @@ def check_model(fn, max_examples=None, seed=None): skipped = 0 failed_run = None - def compare(args): + def compare(args, limited): """The label (or None), what failed and the line after the input, or None.""" - limited = wide and _large(args) try: result = _call(None, fn, *copy.deepcopy(args)) except _Raised as e: @@ -475,19 +518,25 @@ def compare(args): return label, f"{spec_name(predicate)} does not hold", f"result: {result!r}" return None - def property_(args): - nonlocal accepted, rejected, skipped, failed_run + def test(args, *, force_limit=False): try: - limited = wide and _large(args) + limited = force_limit or (wide and _large(args)) if spec.requires is not None and not _call("requires", spec.requires, *args, limited=limited): - if failed_run is None: - rejected += 1 - hypothesis.reject() - failure = compare(args) + return False, None + return True, compare(args, limited) except _Raised as e: - failure = e.label, "the spec failed", f"error: {_error(e.cause)}" + return True, (e.label, "the spec failed", f"error: {_error(e.cause)}") except _TooLong: - skipped += 1 + return None, None + + def property_(args): + nonlocal accepted, rejected, skipped, failed_run + allowed, failure = test(args) + if not allowed: + if allowed is None: + skipped += 1 + elif failed_run is None: + rejected += 1 hypothesis.reject() if failure is None: if failed_run is None: @@ -495,12 +544,7 @@ def property_(args): return if failed_run is None: failed_run = accepted - label, what, detail = failure - where = spec.qualname if label is None else f"{spec.qualname} [{label}]" - shown = ", ".join(f"{p}={a!r}" for p, a in zip(params, args, strict=True)) - raise PropertyFailure( - f"{where}: {what} (seed {seed}, run {failed_run})\n input: {shown}\n {detail}" - ) from None + raise _SampleFailure(args, failure) # Hypothesis also ends when it discards too many inputs; the next round draws the inputs that remain. rounds = 0 @@ -515,6 +559,16 @@ def property_(args): )(hypothesis.seed(seed + rounds * (MAX_SEED + 1))(hypothesis.given(strategies)(property_))) try: run() + except _SampleFailure as error: + inputs, failure = error.inputs, error.failure + if wide and _large(inputs): + inputs, failure = _shrink_wide_integers(inputs, failure, [hints[p] for p in params], test) + label, what, detail = failure + where = spec.qualname if label is None else f"{spec.qualname} [{label}]" + shown = ", ".join(f"{p}={a!r}" for p, a in zip(params, inputs, strict=True)) + raise PropertyFailure( + f"{where}: {what} (seed {seed}, run {failed_run})\n input: {shown}\n {detail}" + ) from None except hypothesis.errors.Unsatisfiable: if (accepted, rejected, skipped) == before: raise @@ -527,5 +581,13 @@ def property_(args): def check_module(module, max_examples=None, seed=None): """``check_model`` for every ``@model`` function of the module.""" + failures = [] for spec in models_of(module): - check_model(spec.fn, max_examples, seed) + try: + check_model(spec.fn, max_examples, seed) + except PropertyFailure as error: + failures.append(error) + if len(failures) == 1: + raise failures[0] + if failures: + raise PropertyFailure("\n".join(map(str, failures))) diff --git a/langs/Python/tests/test_verify.py b/langs/Python/tests/test_verify.py index 6bf73a9a..cf95f39b 100644 --- a/langs/Python/tests/test_verify.py +++ b/langs/Python/tests/test_verify.py @@ -11,9 +11,35 @@ import pytest from conftest import CLI, ROOT +from leanfran import verify from leanfran.verify import check_model, model +def test_wide_shrink_limits_spec_on_intermediate_inputs(monkeypatch): + from hypothesis import strategies as st + + wide = verify.EDGES[0] + monkeypatch.setattr(verify, "_fast", lambda _: True) + monkeypatch.setattr(verify, "strategy", lambda *_: st.just(wide)) + monkeypatch.setattr(verify, "STEPS", 100) + visits = [] + + def spec(x): + if 0 < x < wide: + visits.append(x) + for _ in range(1000): + pass + return 0 + + @model(refines=spec) + def wrong(x: int) -> int: + return int(x != 0) + + with pytest.raises(verify.PropertyFailure, match=rf"input: x={wide}\n"): + check_model(wrong, max_examples=1) + assert visits + + def execute(cmd, cwd): env = {**os.environ, "LEANFRAN_CLI": str(CLI), "PYTHONPATH": str(cwd)} return subprocess.run(cmd, cwd=cwd, env=env, capture_output=True, text=True, check=False) @@ -392,6 +418,22 @@ def test_property_checks(project): assert (r.returncode, r.stdout) == (0, ""), r.stderr +def test_module_reports_multiple_counterexamples(project): + r = python( + project, + """ +from types import SimpleNamespace +try: + check_module(SimpleNamespace(bad_clamp=bad_clamp, first=first)) +except PropertyFailure as error: + print(error) +""", + ) + assert r.returncode == 0, r.stderr + assert "bad_clamp [refines]: mismatch (seed 1, run " in r.stdout + assert "first [refines]: mismatch (seed 1, run " in r.stdout + + @pytest.mark.parametrize( ("function", "label", "message", "detail"), [ diff --git a/langs/Rust/Makefile b/langs/Rust/Makefile index 288de0c4..1ad7b6cc 100644 --- a/langs/Rust/Makefile +++ b/langs/Rust/Makefile @@ -25,6 +25,7 @@ test: leanfran tests/project/test.sh ../../maint/test-theorems.sh "$(LEANFRAN_CLI)" rust ../../maint/test-freshness.sh "$(LEANFRAN_CLI)" rust + ../../maint/test-property-parity.sh "$(LEANFRAN_CLI)" rust test-generate: leanfran ../../maint/test-generate.sh "$(LEANFRAN_CLI)" rust diff --git a/langs/Rust/crates/leanfran-build/src/lib.rs b/langs/Rust/crates/leanfran-build/src/lib.rs index 1e627721..edebc2f9 100644 --- a/langs/Rust/crates/leanfran-build/src/lib.rs +++ b/langs/Rust/crates/leanfran-build/src/lib.rs @@ -226,6 +226,18 @@ impl Builder { /// Copies the Rust modules of the `lean!` blocks and of the models of the /// `#[leanfran::opaque]` functions from the cache to `OUT_DIR`. pub fn compile(&self) -> Result<(), Error> { + std::thread::scope(|scope| { + let worker = std::thread::Builder::new() + .stack_size(32 << 20) + .spawn_scoped(scope, || self.compile_on_worker())?; + match worker.join() { + Ok(result) => result, + Err(panic) => std::panic::resume_unwind(panic), + } + }) + } + + fn compile_on_worker(&self) -> Result<(), Error> { println!("cargo:rerun-if-env-changed={EXTRACTING}"); let mut items = model::CrateItems::default(); let (blocks, files) = self.scan_blocks(Some(&mut items))?; diff --git a/langs/Rust/crates/leanfran-build/tests/build.rs b/langs/Rust/crates/leanfran-build/tests/build.rs index 0a70d3dd..f9f1a583 100644 --- a/langs/Rust/crates/leanfran-build/tests/build.rs +++ b/langs/Rust/crates/leanfran-build/tests/build.rs @@ -52,6 +52,15 @@ fn crate_dir(name: &str, source: &str) -> PathBuf { dir } +#[test] +fn a_build_scans_a_long_expression() { + let source = format!("pub fn sum(x: u32) -> u32 {{ {}x }}", "x + ".repeat(2999)); + let dir = crate_dir("long-expression", &source); + Builder::with_dirs(&dir, dir.join("out"), "long-expression") + .compile() + .unwrap(); +} + #[test] fn a_build_copies_the_cache_and_stops_without_an_entry() { let dir = crate_dir( diff --git a/langs/TypeScript/Makefile b/langs/TypeScript/Makefile index 0fe2c8e1..75203b94 100644 --- a/langs/TypeScript/Makefile +++ b/langs/TypeScript/Makefile @@ -73,6 +73,7 @@ check-verify: build pack ../../maint/test-theorems.sh ../../.lake/build/bin/leanfran typescript ../../maint/test-isolation.sh ../../.lake/build/bin/leanfran typescript ../../maint/test-freshness.sh ../../.lake/build/bin/leanfran typescript + ../../maint/test-property-parity.sh ../../.lake/build/bin/leanfran typescript ../../maint/test-csimp.sh ../../.lake/build/bin/leanfran typescript check-samples: build pack diff --git a/langs/TypeScript/src/runtime/io.ts b/langs/TypeScript/src/runtime/io.ts index 28b798fc..2c99aa8c 100644 --- a/langs/TypeScript/src/runtime/io.ts +++ b/langs/TypeScript/src/runtime/io.ts @@ -85,6 +85,23 @@ export function getPlatform(): Platform { // mirror the C globals. let panicMessages = true let exitOnPanic = false +let raisePanics = false + +export function withLeanPanics(run: () => T): T { + const saved = raisePanics + raisePanics = true + try { + return run() + } finally { + raisePanics = saved + } +} + +function leanPanic(message: string): Error { + const error = new Error(message.replace(/^PANIC at .*?:\d+:\d+: /su, "")) + error.name = "panic" + return error +} export function lean_set_panic_messages(b: number): void { panicMessages = b !== 0 @@ -95,6 +112,7 @@ export function lean_set_exit_on_panic(b: number): void { } export function lean_panic_fn(defaultVal: T, msg: Obj): T { + if (raisePanics) throw leanPanic(asString(msg)) if (panicMessages) platform.writeStderr(asString(msg) + "\n") if (exitOnPanic) platform.exit(1) return defaultVal @@ -107,6 +125,7 @@ export function lean_panic_fn_borrowed(defaultVal: T, msg: Obj): T { // FnBody.unreachable -> lean_internal_panic_unreachable: FATAL. Dead match arms // are never meant to run; print and terminate (never fall through). export function lean_internal_panic(msg: string): never { + if (raisePanics) throw leanPanic(msg) platform.writeStderr("INTERNAL PANIC: " + msg + "\n") return platform.exit(1) } diff --git a/langs/TypeScript/src/verify/index.ts b/langs/TypeScript/src/verify/index.ts index 17f8b091..f4a092c3 100644 --- a/langs/TypeScript/src/verify/index.ts +++ b/langs/TypeScript/src/verify/index.ts @@ -2,6 +2,7 @@ import { dirname } from "node:path" import { pathToFileURL } from "node:url" import type * as FastCheck from "fast-check" import { type BlockEntry, blockRegistry, leanNameOf, leanSpecOf } from "../runtime/block.ts" +import { withLeanPanics } from "../runtime/io.ts" import { checkValue, standardValidate, type TypeDesc } from "../runtime/marshal.ts" import { callerFile, leanModel, projectRoot, requireCurrent } from "../embed.ts" import { isRecord, moduleParts, scannedFnv } from "../project.ts" @@ -478,7 +479,7 @@ export async function checkModel(fn: Spec, options: CheckOptions = {}): Promise< ]) const callSpec = (label: string, spec: Spec, args: unknown[]): unknown => { try { - return Reflect.apply(leanSpecOf(spec), undefined, args) + return withLeanPanics(() => Reflect.apply(leanSpecOf(spec), undefined, args)) } catch (e) { throw new Counterexample({ label, @@ -578,5 +579,16 @@ export async function checkModule( const values = new Set(Object.values(module)) const entries = [...modelRegistry().values()].filter((e) => values.has(e.fn)) if (entries.length === 0) throw new TypeError("leanfran: the module has no model(...) functions") - for (const entry of entries) await checkModel(entry.fn, options) + const failures: PropertyFailure[] = [] + for (const entry of entries) { + try { + await checkModel(entry.fn, options) + } catch (error) { + if (!(error instanceof PropertyFailure)) throw error + failures.push(error) + } + } + if (failures.length === 1) throw failures[0] + if (failures.length > 1) + throw new PropertyFailure(failures.map((error) => error.message).join("\n")) } diff --git a/langs/TypeScript/test/verify.test.ts b/langs/TypeScript/test/verify.test.ts index 7d18f7c0..b1e18bfa 100644 --- a/langs/TypeScript/test/verify.test.ts +++ b/langs/TypeScript/test/verify.test.ts @@ -160,6 +160,12 @@ describe("checkModel", () => { await checkModule(orders, { range: { min: -2000n, max: 2000n }, numRuns: 100 }) }) + test("checkModule reports multiple counterexamples", async () => { + await expect(checkModule({ overEven, throwsEven })).rejects.toThrow( + /overEven \[refines\]: mismatch[^]*throwsEven \[refines\]: mismatch/u, + ) + }) + test("a wrong implementation fails with a counterexample", async () => { const err: unknown = await checkModel(badClamp).catch((e: unknown) => e) expect(err).toBeInstanceOf(PropertyFailure) diff --git a/langs/TypeScript/vite.config.ts b/langs/TypeScript/vite.config.ts index 955822cc..d8886bed 100644 --- a/langs/TypeScript/vite.config.ts +++ b/langs/TypeScript/vite.config.ts @@ -22,6 +22,7 @@ const config: ViteUserConfig = defineConfig({ test: { include: ["test/**/*.test.ts"], exclude: ["test/embed/**", "test/verify/app/**", "node_modules/**"], + testTimeout: 30_000, }, pack: [ { diff --git a/maint/PHP/test-replaced.sh b/maint/PHP/test-replaced.sh index 12afb984..228fe506 100644 --- a/maint/PHP/test-replaced.sh +++ b/maint/PHP/test-replaced.sh @@ -63,8 +63,10 @@ check='require "vendor/autoload.php"; foreach ([[App\Calc::class], [App\Spec::class], [App\Lost::class], [App\Impl::class, "other"], "App\\named"] as $f) { try { is_array($f) && count($f) === 1 ? Verify::checkClass($f[0]) : Verify::checkModel($f); - } catch (Conao3\Leanfran\Verify\PropertyFailure $e) { - echo strtok($e->getMessage(), "("), "\n"; + } catch (RuntimeException $e) { + preg_match_all("/^[^ ].* \\[refines\\]: mismatch(?= \\(seed)/m", $e->getMessage(), $rows); + if ($rows[0] === []) throw $e; + echo implode("\n", $rows[0]), "\n"; } }' diff -u /dev/null <(php -r "$check") @@ -73,11 +75,13 @@ diff -u /dev/null <(php -r "$check") sed -i 's/return intdiv(\$n \* (\$n + 1), 2);/return intdiv($n * ($n + 1), 2) + ($n > 100 ? 1 : 0);/' src/Calc.php sed -i '/function same(/,/}/ s/return \$n;/return $n + 1;/; s/return min(/return 1 + min(/' src/Spec.php sed -i 's/return \$n;/return -$n;/' src/Impl.php src/functions.php src/Lost.php -expected='App\Calc\sum_to [refines]: mismatch -App\Spec\cap_private [refines]: mismatch -App\Lost\lost [refines]: mismatch -App\Impl\other [refines]: mismatch -App\named [refines]: mismatch ' +expected='App\Calc\sum_to [refines]: mismatch +App\Calc\double_sum [refines]: mismatch +App\Spec\cap_private [refines]: mismatch +App\Spec\same [refines]: mismatch +App\Lost\lost [refines]: mismatch +App\Impl\other [refines]: mismatch +App\named [refines]: mismatch' diff -u <(printf '%s\n' "$expected") <(php -r "$check") mismatch() { php -r 'require "vendor/autoload.php"; @@ -120,7 +124,7 @@ diff -u expected.txt <(php main.php) # Without the functions the generated PHP runs the Lean bodies. mv src/Lost.php Lost.php sed -i '/#\[Model/,$ d' src/functions.php -diff -u <(sed 's/ <- App.named.*//; s/ <- lost.*//' expected.txt) <(php main.php) +diff -u <(sed 's/ <- App.named.*//; s/ <- lost.*//; s/ <- keep_float.*//' expected.txt) <(php main.php) mv Lost.php src/Lost.php # An exception of a function reaches the caller. diff --git a/maint/block-project.sh b/maint/block-project.sh index 0b17ee41..316ccc28 100644 --- a/maint/block-project.sh +++ b/maint/block-project.sh @@ -35,7 +35,7 @@ case $lang in export PATH="$root/langs/Rust/target/debug:$PATH" depend "$root/langs/Rust" printf 'fn main() {\n leanfran_build::Builder::new().compile().unwrap();\n}\n' >build.rs - mkdir src + mkdir -p src printf 'mod facts;\n\nfn main() {\n println!("{}", facts::facts::twice(3));\n let n = std::env::args().nth(1).unwrap().parse().unwrap();\n facts::facts::unwritten(n);\n}\n' >src/main.rs file=src/facts.rs block=app::facts::facts before=$'leanfran::lean! {\n pub mod facts;\n r#"' after=$'\n"#\n}' @@ -52,7 +52,7 @@ case $lang in ;; typescript) printf '{"name": "app", "type": "module", "dependencies": {"leanfran": "*"}}\n' >package.json - mkdir src + mkdir -p src depend "$root/langs/TypeScript" file=src/facts.ts block=src/facts.ts:facts before=$'import { lean, type LeanBlock } from "leanfran"\n\nexport const block: LeanBlock = lean(\n "facts",\n String.raw`' after=$'\n`,\n)' @@ -65,7 +65,7 @@ case $lang in ;; php) printf '{"name": "app/app", "autoload": {"psr-4": {"App\\\\": "src/"}}}\n' >composer.json - mkdir src + mkdir -p src depend "$root/langs/PHP" file=src/Facts.php block='App\Facts' before=$'>leanfran.toml file=src/facts.c block=facts before='/* leanfran:lean facts' after=$'\n*/' @@ -111,7 +111,7 @@ call() { out=$(find . -name leanfran.pc -exec dirname {} \; | head -1) printf 'include %s/leanfran.mk\nbuild:\n\t@true\n' "$out" >build.mk make -s -f build.mk build || return - eval 'cc -std=c11 main.c -o main '"$(PKG_CONFIG_PATH=$out pkg-config --cflags --libs leanfran)" + eval 'cc -std=c11 main.c -o main '"$(PKG_CONFIG_PATH=$out pkg-config --cflags --libs leanfran)" || return ./main ;; esac diff --git a/maint/test-all-languages.sh b/maint/test-all-languages.sh new file mode 100755 index 00000000..3a73580e --- /dev/null +++ b/maint/test-all-languages.sh @@ -0,0 +1,104 @@ +#!/usr/bin/env bash +set -euo pipefail + +usage='usage: maint/test-all-languages.sh (in the default Nix shell, with the language packages built)' +leanfran=$(realpath "${1:?$usage}") +root=$(cd "$(dirname "$0")/.." && pwd) +work=$(mktemp -d) +trap 'chmod -R u+w "$work"; rm -rf "$work"' EXIT + +languages=(rust python typescript clojure php go c) +reverse=(c go php clojure typescript python rust) +export LEANFRAN_CLI=$leanfran +export PATH="$root/langs/Rust/target/debug:$PATH" +export PYTHONPATH="$root/langs/Python/src:src" +unset LEANFRAN_AUTO_SYNC + +text='def twice (n : UInt32) : UInt32 := n + n +theorem twice_two : twice 2 = 4 := by decide +theorem unfinished : twice 3 = 6 := sorry +axiom cheat : 1 = 2 +theorem assumed : twice 1 = 3 := absurd cheat (by decide)' + +mkdir "$work/source" +cd "$work/source" +for lang in "${languages[@]}"; do + ( + if [[ $lang == go ]]; then + mkdir go-project + cd go-project + fi + . "$root/maint/block-project.sh" + write "$text" + printf '%s [assumed]: axioms\n%s [unfinished]: sorry\n' "$block" "$block" + if [[ $lang == go ]]; then printf 'paths = ["go-project"]\n' >>leanfran.toml; fi + mv leanfran.toml "$work/$lang.toml" + ) >>"$work/rows" +done +for lang in "${languages[@]}"; do + cat "$work/$lang.toml" + printf '\n' +done >leanfran.toml +LC_ALL=C sort -o "$work/rows" "$work/rows" + +expect() { + local expected=$1 status=0 + shift + uv run --no-sync --project "$root/langs/Python" "$leanfran" "$@" || status=$? + if [[ $status != "$expected" ]]; then + printf 'test-all-languages.sh: %s: expected exit %s, got %s\n' "$*" "$expected" "$status" >&2 + exit 1 + fi +} + +cp -a "$work/source" "$work/project" +cd "$work/project" +expect 0 sync +expect 0 check >"$work/check" +expect 0 status >"$work/status" +expect 1 status --require proved >"$work/required" +for command in check status required; do + LC_ALL=C sort "$work/$command" | diff -u "$work/rows" - +done +expect 0 status --output json >"$work/status.json" + +files=(leanfran.manifest.json leanfran.lock) +node --input-type=module -e ' + import assert from "node:assert/strict"; + import { readFileSync } from "node:fs"; + const [statusPath, manifestPath, lockPath, ...languages] = process.argv.slice(1); + const read = (path) => JSON.parse(readFileSync(path, "utf8")); + const status = read(statusPath); + const manifest = read(manifestPath).languages; + const lock = read(lockPath).languages; + for (const data of [status, manifest, lock]) { + assert.deepEqual(Object.keys(data).sort(), languages.toSorted()); + } + for (const lang of languages) { + assert.equal(manifest[lang].blocks.length, 1, lang); + assert.deepEqual(status[lang].blocks, [], lang); + assert.deepEqual(status[lang].functions, [], lang); + assert.equal(lock[lang].theorems.length, 2, lang); + } +' "$work/status.json" "${files[@]}" "${languages[@]}" +cp "${files[@]}" "$work/" + +check_order() { + cd "$work" + chmod -R u+w project + rm -rf project + cp -a source project + cd project + local lang file + for lang; do expect 0 --lang "$lang" sync; done + for lang; do expect 0 --lang "$lang" check; done >"$work/check-ordered" + for lang; do expect 0 --lang "$lang" status; done >"$work/status-ordered" + LC_ALL=C sort "$work/check-ordered" | diff -u "$work/rows" - + LC_ALL=C sort "$work/status-ordered" | diff -u "$work/rows" - + for file in "${files[@]}"; do diff -u "$work/$file" "$file"; done + expect 0 status --output json | diff -u "$work/status.json" - +} + +check_order "${languages[@]}" +check_order "${reverse[@]}" +printf 'test-all-languages.sh: 7 languages passed in one root\n' diff --git a/maint/test-csimp.sh b/maint/test-csimp.sh index aba36454..e36e5b96 100755 --- a/maint/test-csimp.sh +++ b/maint/test-csimp.sh @@ -1038,8 +1038,6 @@ CLJ CLJ clojure -M models.clj } - # A generated function does not check its arguments: the spec compares the number with the text. - held_failure='holds does not hold' typed_failures='app.types/wrapped-of-int [refines]: mismatch app.types/unwrapped-of-int [refines]: the spec failed app.types/nested-of-option [refines]: the spec failed' @@ -2216,6 +2214,27 @@ expect 0 check --require proved run "$base" 'after a check' mismatches '' 'after a check' stale 0 '' 'after a check' +if [[ $lang == go ]]; then + mkdir standalone + for prefix in l_ L_; do + options=() + if [[ $prefix == L_ ]]; then options=(--internal-only); fi + "$leanfran" --lang go module generate --module-name "$namespace" \ + --search-path .leanfran/go/workspace/.lake/build/lib/lean --import "LeanGoCsimp.$namespace" \ + --roots "$namespace.succTwice" --go-package standalone --output-file standalone/generated.go \ + "${options[@]}" >out 2>err || fail 'module generate --output-file with a Go replacement' + cat >standalone/generated_test.go <out 2>err || fail 'the stand-alone Go file must run the Lean body' + done +fi expect 0 check --require proved [[ $(grep -c 'blocks checked and generated' err) == 1 ]] || fail 'a second check generated the blocks again' diff --git a/maint/test-embed.sh b/maint/test-embed.sh index 7c45237e..77e6ad5e 100755 --- a/maint/test-embed.sh +++ b/maint/test-embed.sh @@ -1245,6 +1245,25 @@ for name in num late; do calls "$name" ''; done expect 0 --lang fake-byte check --require proved calls num "$called" +coerced=$(spec_block coerced Coerced c1 '' '' 'def coerced.spec (x : Int) : Int := x +def coerced.call (x : Int) : Int := coerced.spec x + 1 +') +csimp_scan ", $coerced" ", $(spec_fn cast c1)" +csimp_translate ", $(model_module FakeModel.Cast 'import FakeShared.Embed.Coerced + +def FakeModel.cast (x : Nat) : Int := x +def FakeModel.cast.obligation.refines : Prop := ∀ x, FakeModel.cast x = coerced.spec (x : Int) +' '"fake.cast"')" ", $(csimp_fn cast coerced.spec)" ' +import FakeModel.Cast' +rm lean/Proofs/Down.lean +printf 'import FakeModel.Cast\n\ntheorem FakeModel.cast.proof.refines : FakeModel.cast.obligation.refines := fun _ => rfl\n' \ + >lean/Proofs/Cast.lean +expect 0 --lang fake-byte check --require proved +line out 'fake.cast [refines]: proved' +calls coerced '' +lacks csimp/leanfran.lock 'fake:src#cast' +expect 0 --lang fake-byte status --require proved + tool=sha256sum [[ $(uname) == Darwin ]] && tool=shasum nosha="$work/nosha" diff --git a/maint/test-freshness.sh b/maint/test-freshness.sh index 79ce83da..5bcaa0db 100755 --- a/maint/test-freshness.sh +++ b/maint/test-freshness.sh @@ -34,7 +34,7 @@ def unwritten (n : UInt32) : UInt32 := n' runs() { call 0 >out 2>err || fail "the program failed, $1" - [[ $(head -1 out) == 6 ]] || fail "twice 3, $1" + [[ $(head -1 out) == "${2:-6}" ]] || fail "twice 3, $1" } # A copy of the package with another generator version, in files where a sed script changes it: other