From 498d6d1748b1e25e3965a550470fb45d8387b568 Mon Sep 17 00:00:00 2001 From: Matt Keenan <31668468+Negabinary@users.noreply.github.com> Date: Wed, 18 Nov 2026 19:18:46 -0500 Subject: [PATCH 1/2] Prover: theorems with checked proofs, and a stepper that writes them MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Adds a prover to Hazel. A theorem's proof is checked as it is written, and a stepper shows the proof as a chain of goals and writes steps for you. Theorems. `theorem t = proof in e`. The statement's outer `forall`s are introduced automatically. A theorem is proven, refuted or incomplete. The proof language: - `step`: one evaluation step at the root. Where evaluation has none, a function or `let` at the root takes its argument as it is (beta at any argument), so `from inc(2 + 3) do step end` gives `2 + 3 + 1`; - `rewrite h end` and `rewrite <- h end`: rewrite with a fact, theorem or axiom, either way round; - `algebra e end`: an algebraic rewrite, checked with Algebrite; - `from p at n do end`: run steps on the nth occurrence of a subterm (`at 1` is the default); - `forall`, `funext`, `revert`, `generalize` and `alias`; - `assume P =>` on a goal `P ==> Q`, and `have P proof =>` on any goal. Their facts are named `assume` and `have`, or `h` when written `assume h = P` or `have h = P`. `assume` on any other goal is refused; - `cases e`: a split on any expression. Each case has the case equation `e == pat`, named `case_eq`, and no inductive hypothesis. A nested split that needs the outer equation names it with `alias`; - `induction e`: each case has inductive hypotheses `ih_` and no case equation. A computed `e` is generalized first, and in each case the facts that mention the scrutinee leave scope. Nothing gives both: to carry a fact into the IH, `revert` it first. Proof words are keywords only in proof syntax. Elsewhere both parsers read them as ordinary names, so a program can still bind `from`, `at`, `have` or `induction`; only `theorem` and `forall` are reserved. The checker. `ProofCheck` records, for each proof node, its incoming and outgoing goal, its marks, its obligations and its scope (`ProofMap`). Goals are kept as written: a definition is unfolded only where a step needs to look inside it. Checking runs in the evaluation worker, as part of evaluation. Each theorem's check is cached and reused while the theorem, the theorems it can cite, their verdicts and the definitions it names are unchanged. The checker reads the statics through `ProofStatics`: the full statics map in the CLI and tests, and in the worker the `EvalInfo` sent with each request, which carries types, coverage and theorem namespaces only for a program that has theorems. A program without theorems sends and computes nothing extra. Algebra. The worker has its own Algebrite, loaded the first time a proof has an `algebra` step. A step is verified when it is Int arithmetic (`+`, `-`, `*`, powers) over literals and Int-typed variables, or Nat arithmetic (`+`, `*`, powers) over Nat-typed ones, checked as integers. Anything else, such as division, Nat's `monus` or a function call, stays an open condition. Two built-in rules state the Nat facts algebra can't check: `nat_succ_ne_zero` (`(m + 1 == 0) == false`) and `nat_add_sub` (`monus(a + k, k) == a`). Side conditions. Definedness (`x / y` needs `y != 0`) and rule premises become obligations. Facts in scope or evaluation discharge them; otherwise they stay open. Evaluating a closed condition stops at its first error. Citations. Theorems are checked in program order, each knowing the verdicts of those before it. Citing a refuted theorem is an error on that step. Citing an unfinished one is allowed: it is an assumption, not a gap. Status. A theorem reads: - proven: finished, relying on nothing unproven; - proven*: finished, but citing theorems that aren't; the star's tooltip names them; - incomplete: a hole, or an open condition other than a citation, with a quiet count of the open conditions ("incomplete · 1 open"). Clicking the count scrolls to the first one; - refuted. An exercise's score counts proven theorems only, since a student could cite an unproven lemma that states the theorem itself. Equality. `refl` needs `==` to be reflexive, so the polymorphic `==` treats two NaNs as equal. The Float-only `==.` stays IEEE. The stepper is a projection of the proof. Each line between two goals is a step, and structured steps (induction, `forall`, `have`, focus) draw as blocks. - Each side condition is a circle on its step's line. An open one is red, and its exits, "Prove here" (a `have`) and "Split on it" (a `cases`), patch the proof. - The main interaction is a write box after an unfinished proof, with three tabs: - Write: type the goal you want next, and a bounded search finds steps that reach it. An empty box offers the next step or reflexivity, which Tab takes. With part of the goal selected, the offer is the outermost step in it, and the box rewrites just that part. Typing a rule's name lists its uses. - Step: green highlights on what can step. A click writes a focused step at that node. - Strategy: one button per structured step, each writing its form with holes for the user to fill. - A block's header names the fact it introduces. What a focus works on shows as the underline in the goal above, not in the header. - Every offer is checked before it's shown. - Focus selectors are generalized with `$e`, so proofs survive edits. - Stepper edits keep the user's comments and layout. The documentation slides get a Prover section: short slides on theorems, the stepper, lemmas, induction and side conditions, and one whose proofs use every step form. Clicking a step shows its docs entry, titled by what the user types. ProverDocs checks each theorem on the slides has the status its text gives. Editor changes outside the prover: - The holes completion adds inside a tile, such as the proof of a half-typed `theorem t = 1`, keep their ids across edits, so the stepper keeps its state while the statement is typed. - Folding a selection that isn't a whole term, such as a `let ... in` header without its body, is refused. It used to crash the editor. - A toggle that is on shows the accent color. The shared toggle's on and off tracks were two shades of one hue, so an off toggle looked on. Known soundness gaps are pinned as tests in `test/evaluator/Test_ProverKnownBugs.re`. Each asserts today's wrong behaviour, so a fix shows up as a failing pin. Co-Authored-By: Claude Opus 5.5 --- docs/stlc-progress-example.hazel | 77 + hazel-programs/config/colors.hz | 6 +- .../docs/reference/prover-induction.hz | 23 + .../docs/reference/prover-lemmas.hz | 32 + .../docs/reference/prover-reference.hz | 75 + .../docs/reference/prover-side-conditions.hz | 19 + .../docs/reference/prover-stepper.hz | 24 + .../docs/reference/prover-theorems.hz | 30 + src/CLI/Cli.re | 2 +- src/CLI/Diagnostic.re | 1 + src/CLI/Run.re | 3 +- src/docslides/Slides.re | 6 + src/haz3lcore/CachedSyntax.re | 11 + .../CompositionCore/HighLevelNodeMap.re | 3 +- .../prompt_factory/HazelSyntaxNotes.re | 2 +- src/haz3lcore/Editor.re | 3 +- src/haz3lcore/EditorTransform.re | 904 +++++ src/haz3lcore/ProblemCollection.re | 43 +- src/haz3lcore/TyDi/ErrorPrint.re | 7 +- src/haz3lcore/derived/CachedStatics.re | 9 +- src/haz3lcore/derived/CanonicalCompletion.re | 65 +- src/haz3lcore/derived/Measured.re | 26 + src/haz3lcore/derived/TermData.re | 14 +- src/haz3lcore/lang/Form.re | 69 +- src/haz3lcore/lang/MakeTerm.re | 256 +- src/haz3lcore/lang/Precedence.re | 9 +- src/haz3lcore/pretty/ExpToSegment.re | 419 +- src/haz3lcore/pretty/PadIds.re | 1 - src/haz3lcore/pretty/PrettySegment.re | 237 +- src/haz3lcore/projectors/ProjectorPerform.re | 11 +- src/haz3lcore/tiles/Base.re | 3 +- src/haz3lcore/tiles/Segment.re | 141 + src/haz3lcore/tiles/Skel.re | 9 +- src/haz3lcore/tiles/Tile.re | 18 +- src/haz3lcore/zipper/action/Insert.re | 130 +- src/language/builtins/BuiltinsBase.re | 42 +- src/language/builtins/BuiltinsUtil.re | 15 +- src/language/dynamics/DHExp.re | 14 +- src/language/dynamics/Dynamics.re | 1 + src/language/dynamics/EvalInfo.re | 117 +- src/language/dynamics/Evaluator.re | 299 +- src/language/dynamics/Evaluator.rei | 35 + src/language/dynamics/IncrEval.re | 158 +- src/language/dynamics/Substitution.re | 46 +- src/language/dynamics/state/EvaluatorState.re | 12 + src/language/dynamics/state/ProofMap.re | 157 + src/language/dynamics/stepper/EvalCtx.re | 6 +- .../dynamics/stepper/EvaluatorStep.re | 27 +- .../dynamics/stepper/EvaluatorStep.rei | 9 + .../dynamics/transition/Ascriptions.re | 5 - .../dynamics/transition/Transition.re | 115 +- src/language/dynamics/transition/Unboxing.re | 3 - src/language/grammar/FormId.re | 55 +- src/language/proof/Axioms.re | 187 +- src/language/proof/Cas.re | 6 + src/language/proof/Definitions.re | 111 + src/language/proof/DomainConditions.re | 159 + src/language/proof/Induction.re | 290 ++ src/language/proof/MatchExp.re | 157 +- src/language/proof/MetaVar.re | 112 + src/language/proof/Obligation.re | 76 + src/language/proof/Occurrence.re | 307 ++ src/language/proof/ProofCheck.re | 1972 +++++++++ src/language/proof/ProofCtx.re | 117 +- src/language/proof/ProofHacks.re | 590 --- src/language/proof/ProofMark.re | 128 + src/language/proof/ProofRule.re | 435 +- src/language/proof/ProofStatics.re | 89 + src/language/proof/ProofSyntax.re | 61 + src/language/proof/SemanticCtx.re | 235 +- src/language/proof/StructuralRecursion.re | 407 ++ src/language/proof/TheoremNamespace.re | 36 + src/language/proof/Totality.re | 309 ++ .../statics/ConstructorStaticsHelpers.re | 1 - src/language/statics/Coverage.re | 32 +- src/language/statics/Ctx.re | 102 +- src/language/statics/Info.re | 25 +- src/language/statics/Mark.re | 9 +- src/language/statics/MatchedTyp.re | 1 - src/language/statics/Statics.re | 769 +++- src/language/statics/Warning.re | 12 +- src/language/term/Abbreviate.re | 42 +- src/language/term/Any.re | 4 + src/language/term/Atom.re | 17 +- src/language/term/Cls.re | 6 +- src/language/term/Equality.re | 148 +- src/language/term/Exp.re | 103 +- src/language/term/Grammar.re | 321 +- src/language/term/InvalidOperationError.re | 2 + src/language/term/Operators.re | 8 +- src/language/term/PRul.re | 25 + src/language/term/Proof.re | 211 + src/language/term/Sort.re | 4 +- src/language/term/TermBase.re | 327 +- src/language/term/Typ.re | 35 +- src/menhirParser/AST.re | 66 +- src/menhirParser/Conversion.re | 168 +- src/menhirParser/Lexer.mll | 28 +- src/menhirParser/Parser.mly | 112 +- src/util/Calc.re | 6 + src/util/FloatingElement.re | 6 +- src/util/FloatingElement.rei | 4 +- src/util/JsUtil.re | 74 +- src/util/JsUtil.rei | 16 + src/util/SampleAnchor.re | 60 +- src/web/EdgeScroll.re | 108 +- src/web/EdgeScroll.rei | 22 +- src/web/Main.re | 1 + src/web/ScrollWidth.re | 6 +- src/web/Worker.re | 1 + src/web/app/Cursor.re | 10 + src/web/app/common/ProjectorView.re | 3 +- src/web/app/common/RefractorView.re | 3 +- src/web/app/editors/EditorUtil.re | 5 +- src/web/app/editors/cell/CellEditor.re | 125 +- src/web/app/editors/code/CodeEditable.re | 535 ++- src/web/app/editors/code/CodeSelectable.re | 1 + src/web/app/editors/code/CodeViewable.re | 3 + src/web/app/editors/code/CodeWithStatics.re | 28 +- src/web/app/editors/code/ContextMenu.re | 31 +- src/web/app/editors/code/SubEditor.re | 402 ++ src/web/app/editors/decoration/Arms.re | 121 +- src/web/app/editors/decoration/CaretDec.re | 13 +- src/web/app/editors/decoration/Highlight.re | 8 +- src/web/app/editors/lines/LineNumbers.re | 3 +- src/web/app/editors/result/EvalResult.re | 407 +- src/web/app/editors/result/StepperEditor.re | 240 +- src/web/app/editors/result/Theorems.re | 774 ++-- src/web/app/editors/stepper/AlgebriteStep.re | 143 - src/web/app/editors/stepper/AssumptionBox.re | 80 - src/web/app/editors/stepper/AxiomStep.re | 174 - src/web/app/editors/stepper/AxiomsBox.re | 181 - src/web/app/editors/stepper/ForallStep.re | 209 - src/web/app/editors/stepper/InductionCase.re | 393 -- src/web/app/editors/stepper/InductionStep.re | 445 --- src/web/app/editors/stepper/MissingStep.re | 737 ---- src/web/app/editors/stepper/Obligations.re | 325 ++ src/web/app/editors/stepper/ProofMarkView.re | 171 + src/web/app/editors/stepper/RewriteChecker.re | 21 +- src/web/app/editors/stepper/SingleStep.re | 166 - src/web/app/editors/stepper/StepInterface.re | 114 - src/web/app/editors/stepper/StepSearch.re | 835 ++++ src/web/app/editors/stepper/StepperBase.re | 1134 ------ src/web/app/editors/stepper/StepperPicker.re | 887 +++++ src/web/app/editors/stepper/StepperRows.re | 504 +++ .../app/editors/stepper/StepperTargetBox.re | 70 - src/web/app/explainthis/Example.re | 23 +- src/web/app/explainthis/ExplainThis.re | 16 +- src/web/app/explainthis/ExplainThisForm.re | 52 +- src/web/app/explainthis/data/ForallExp.re | 10 +- src/web/app/explainthis/data/OpExp.re | 36 + src/web/app/explainthis/data/ProofDoc.re | 734 ++++ .../app/explainthis/data/ProofObjectExp.re | 24 - src/web/app/explainthis/data/ProofOfTyp.re | 23 - src/web/app/explainthis/data/TheoremExp.re | 40 +- src/web/app/inspector/CursorInspector.re | 218 +- src/web/app/probesystem/ProbeSidebar.re | 4 +- src/web/app/sidebar/DebugSidebar.re | 14 +- src/web/app/sidebar/ProblemSidebar.re | 3 +- src/web/app/sidebar/Sidebar.re | 2 +- src/web/app/sidebar/SidebarModel.re | 14 +- src/web/dune | 3 +- src/web/exercises/SyntaxTest.re | 12 +- src/web/init/Init.re | 6 +- src/web/util/CasJs.re | 24 + src/web/util/WorkerServer.re | 9 +- src/web/view/CodeExerciseMode.re | 29 +- src/web/view/ConfigurationMode.re | 8 +- src/web/view/ContextInspector.re | 12 + src/web/view/DerivationExerciseMode.re | 29 +- src/web/view/EvalRequest.re | 22 +- src/web/view/ScratchMode.re | 5 +- src/web/view/StepperView.re | 2711 ++++++++++++- src/web/view/TheoremExerciseMode.re | 34 +- src/web/view/TutorialMode.re | 29 +- src/web/www/dune | 10 + src/web/www/style/cell.css | 49 +- src/web/www/style/cursor-inspector.css | 31 +- src/web/www/style/dynamics.css | 13 + src/web/www/style/editor.css | 34 + src/web/www/style/nut-menu.css | 7 - src/web/www/style/settings-panel.css | 4 - src/web/www/style/sidebar.css | 19 + src/web/www/style/stepper.css | 933 ++++- src/web/www/style/theorems.css | 33 +- src/web/www/style/toggle.css | 5 +- src/web/www/style/variables.css | 38 + src/web/www/workerprelude.js | 4 + test/Test_CanonicalCompletion.re | 62 +- test/Test_CompletionScoreboard.re | 4 +- test/Test_ConfigurationMode.re | 1 + test/Test_Editing.re | 83 +- test/Test_EditorTransform.re | 1066 +++++ test/Test_Elaboration.re | 3 +- test/Test_ExpToSegment.re | 497 ++- test/Test_ExplainThis.re | 292 ++ test/Test_FastParse.re | 11 + test/Test_Grammar.re | 10 +- test/Test_InductionWildcard.re | 68 + test/Test_ListCaseStep.re | 245 ++ test/Test_MakeTerm.re | 12 + test/Test_MatchExp.re | 188 +- test/Test_Menhir.re | 280 ++ test/Test_MultiProbe.re | 2 +- test/Test_NegativeSelector.re | 151 + test/Test_PrettyPrint.re | 76 + test/Test_ProblemCollection.re | 4 +- test/Test_PromptFactory.re | 2 - test/Test_ProofContext.re | 236 ++ test/Test_ProofHacks.re | 102 - test/Test_ProofLayout.re | 1248 ++++++ test/Test_ProofRuleMentions.re | 104 + test/Test_StepperPasses.re | 72 - test/Test_SubEditor.re | 533 +++ test/Test_TermData.re | 5 +- test/Test_Undo.re | 72 + test/Test_UnusedWarnings.re | 57 +- test/Test_WorkerServer.re | 1 + test/evaluator/Test_AlgebraSteps.re | 251 ++ test/evaluator/Test_CasesInduction.re | 339 ++ test/evaluator/Test_CheckedProofs.re | 274 ++ test/evaluator/Test_ClosureLibrary.re | 644 +++ test/evaluator/Test_Definedness.re | 679 ++++ test/evaluator/Test_DefinitionNames.re | 199 + test/evaluator/Test_Equiv_Inductions.re | 584 +++ test/evaluator/Test_Evaluator.re | 24 +- test/evaluator/Test_Evaluator_Operators.re | 16 + test/evaluator/Test_Evaluator_Poly_Equal.re | 14 + test/evaluator/Test_Focus.re | 367 ++ test/evaluator/Test_FunContracts.re | 107 + test/evaluator/Test_FunctionTotality.re | 269 ++ test/evaluator/Test_Funext.re | 596 +++ test/evaluator/Test_Generalize.re | 253 ++ test/evaluator/Test_Have.re | 446 +++ test/evaluator/Test_HypothesisNaming.re | 467 +++ test/evaluator/Test_Instantiation.re | 438 ++ test/evaluator/Test_ListFoldLibrary.re | 74 + test/evaluator/Test_Milestone_STLC.re | 700 ++++ test/evaluator/Test_Obligations.re | 426 ++ test/evaluator/Test_OffDomain.re | 119 + test/evaluator/Test_ProofMap.re | 1844 +++++++++ test/evaluator/Test_ProverDocs.re | 102 + test/evaluator/Test_ProverKnownBugs.re | 60 + test/evaluator/Test_Revert.re | 224 ++ test/evaluator/Test_RootMissingRepro.re | 112 + test/evaluator/Test_StepSearch.re | 552 +++ test/evaluator/Test_StepperBase.re | 664 ---- test/evaluator/Test_StepperView.re | 3524 +++++++++++++++++ test/evaluator/Test_StructuralRecursion.re | 182 + test/evaluator/Test_SymbolicListBuiltins.re | 227 ++ test/evaluator/Test_TheoremNamespace.re | 126 + test/haz3ltest.re | 21 +- test/idb_stub.js | 8 +- test/run_node.sh | 23 + test/statics/Test_Statics.re | 3 + test/statics/Test_Statics_DynamicError.re | 62 + test/statics/Test_Statics_Noncomputable.re | 269 ++ test/statics/Test_Statics_Prelude.re | 2 +- test/statics/Test_Statics_Proof.re | 381 ++ 259 files changed, 40890 insertions(+), 7366 deletions(-) create mode 100644 docs/stlc-progress-example.hazel create mode 100644 hazel-programs/docs/reference/prover-induction.hz create mode 100644 hazel-programs/docs/reference/prover-lemmas.hz create mode 100644 hazel-programs/docs/reference/prover-reference.hz create mode 100644 hazel-programs/docs/reference/prover-side-conditions.hz create mode 100644 hazel-programs/docs/reference/prover-stepper.hz create mode 100644 hazel-programs/docs/reference/prover-theorems.hz create mode 100644 src/haz3lcore/EditorTransform.re create mode 100644 src/language/dynamics/state/ProofMap.re create mode 100644 src/language/proof/Cas.re create mode 100644 src/language/proof/Definitions.re create mode 100644 src/language/proof/DomainConditions.re create mode 100644 src/language/proof/Induction.re create mode 100644 src/language/proof/MetaVar.re create mode 100644 src/language/proof/Obligation.re create mode 100644 src/language/proof/Occurrence.re create mode 100644 src/language/proof/ProofCheck.re delete mode 100644 src/language/proof/ProofHacks.re create mode 100644 src/language/proof/ProofMark.re create mode 100644 src/language/proof/ProofStatics.re create mode 100644 src/language/proof/ProofSyntax.re create mode 100644 src/language/proof/StructuralRecursion.re create mode 100644 src/language/proof/TheoremNamespace.re create mode 100644 src/language/proof/Totality.re create mode 100644 src/language/term/PRul.re create mode 100644 src/language/term/Proof.re create mode 100644 src/web/app/editors/code/SubEditor.re delete mode 100644 src/web/app/editors/stepper/AlgebriteStep.re delete mode 100644 src/web/app/editors/stepper/AssumptionBox.re delete mode 100644 src/web/app/editors/stepper/AxiomStep.re delete mode 100644 src/web/app/editors/stepper/AxiomsBox.re delete mode 100644 src/web/app/editors/stepper/ForallStep.re delete mode 100644 src/web/app/editors/stepper/InductionCase.re delete mode 100644 src/web/app/editors/stepper/InductionStep.re delete mode 100644 src/web/app/editors/stepper/MissingStep.re create mode 100644 src/web/app/editors/stepper/Obligations.re create mode 100644 src/web/app/editors/stepper/ProofMarkView.re delete mode 100644 src/web/app/editors/stepper/SingleStep.re delete mode 100644 src/web/app/editors/stepper/StepInterface.re create mode 100644 src/web/app/editors/stepper/StepSearch.re delete mode 100644 src/web/app/editors/stepper/StepperBase.re create mode 100644 src/web/app/editors/stepper/StepperPicker.re create mode 100644 src/web/app/editors/stepper/StepperRows.re delete mode 100644 src/web/app/editors/stepper/StepperTargetBox.re create mode 100644 src/web/app/explainthis/data/ProofDoc.re delete mode 100644 src/web/app/explainthis/data/ProofObjectExp.re delete mode 100644 src/web/app/explainthis/data/ProofOfTyp.re create mode 100644 src/web/util/CasJs.re create mode 100644 src/web/www/workerprelude.js create mode 100644 test/Test_EditorTransform.re create mode 100644 test/Test_InductionWildcard.re create mode 100644 test/Test_ListCaseStep.re create mode 100644 test/Test_NegativeSelector.re create mode 100644 test/Test_ProofContext.re delete mode 100644 test/Test_ProofHacks.re create mode 100644 test/Test_ProofLayout.re create mode 100644 test/Test_ProofRuleMentions.re delete mode 100644 test/Test_StepperPasses.re create mode 100644 test/Test_SubEditor.re create mode 100644 test/evaluator/Test_AlgebraSteps.re create mode 100644 test/evaluator/Test_CasesInduction.re create mode 100644 test/evaluator/Test_CheckedProofs.re create mode 100644 test/evaluator/Test_ClosureLibrary.re create mode 100644 test/evaluator/Test_Definedness.re create mode 100644 test/evaluator/Test_DefinitionNames.re create mode 100644 test/evaluator/Test_Equiv_Inductions.re create mode 100644 test/evaluator/Test_Focus.re create mode 100644 test/evaluator/Test_FunContracts.re create mode 100644 test/evaluator/Test_FunctionTotality.re create mode 100644 test/evaluator/Test_Funext.re create mode 100644 test/evaluator/Test_Generalize.re create mode 100644 test/evaluator/Test_Have.re create mode 100644 test/evaluator/Test_HypothesisNaming.re create mode 100644 test/evaluator/Test_Instantiation.re create mode 100644 test/evaluator/Test_ListFoldLibrary.re create mode 100644 test/evaluator/Test_Milestone_STLC.re create mode 100644 test/evaluator/Test_Obligations.re create mode 100644 test/evaluator/Test_OffDomain.re create mode 100644 test/evaluator/Test_ProofMap.re create mode 100644 test/evaluator/Test_ProverDocs.re create mode 100644 test/evaluator/Test_ProverKnownBugs.re create mode 100644 test/evaluator/Test_Revert.re create mode 100644 test/evaluator/Test_RootMissingRepro.re create mode 100644 test/evaluator/Test_StepSearch.re delete mode 100644 test/evaluator/Test_StepperBase.re create mode 100644 test/evaluator/Test_StepperView.re create mode 100644 test/evaluator/Test_StructuralRecursion.re create mode 100644 test/evaluator/Test_SymbolicListBuiltins.re create mode 100644 test/evaluator/Test_TheoremNamespace.re create mode 100644 test/statics/Test_Statics_DynamicError.re create mode 100644 test/statics/Test_Statics_Noncomputable.re create mode 100644 test/statics/Test_Statics_Proof.re diff --git a/docs/stlc-progress-example.hazel b/docs/stlc-progress-example.hazel new file mode 100644 index 0000000000..f7f7784bb0 --- /dev/null +++ b/docs/stlc-progress-example.hazel @@ -0,0 +1,77 @@ +type Ty = +TB+TArr(Ty, Ty) in +type Term = +TmVar(Int)+TmLam(Ty, Term)+TmAp(Term, Term) in +type MaybeTy = +NoTy+SomeTy(Ty) in +type MaybeTm = +NoTm+SomeTm(Term) in +let ty_eq = fun p -> case p | (TB, TB) => true | (TB, TArr(x, y)) => false | (TArr(x, y), TB) => false | (TArr(x1, y1), TArr(x2, y2)) => ty_eq((x1, x2)) && ty_eq((y1, y2)) end in +let nth_ty = fun p -> case p | ([], n) => NoTy | (t :: rest, n) => if n == 0 then SomeTy(t) else nth_ty((rest, n - 1)) end in +let lam_result = fun p -> case p | (t, NoTy) => NoTy | (t, SomeTy(t2)) => SomeTy(TArr(t, t2)) end in +let ap_result = fun p -> case p | (NoTy, m) => NoTy | (SomeTy(TB), m) => NoTy | (SomeTy(TArr(ta, tb)), NoTy) => NoTy | (SomeTy(TArr(ta, tb)), SomeTy(s)) => (if ty_eq((ta, s)) then SomeTy(tb) else NoTy) end in +let infer = fun p -> case p | (ctx, TmVar(n)) => nth_ty((ctx, n)) | (ctx, TmLam(t, b)) => lam_result((t, infer((t :: ctx, b)))) | (ctx, TmAp(e1, e2)) => ap_result((infer((ctx, e1)), infer((ctx, e2)))) end in +let is_value = fun e -> case e | TmVar(n) => false | TmLam(t, b) => true | TmAp(x, y) => false end in +let is_lam = fun e -> case e | TmLam(t, b) => true | TmVar(n) => false | TmAp(x, y) => false end in +let is_some_tm = fun m -> case m | NoTm => false | SomeTm(x) => true end in +let shift = fun p -> case p | (d, c, TmVar(n)) => (if n < c then TmVar(n) else TmVar(n + d)) | (d, c, TmLam(t, b)) => TmLam(t, shift((d, c + 1, b))) | (d, c, TmAp(x, y)) => TmAp(shift((d, c, x)), shift((d, c, y))) end in +let subst = fun p -> case p | (j, v, TmVar(n)) => (if n == j then v else TmVar(n)) | (j, v, TmLam(t, b)) => TmLam(t, subst((j + 1, shift((1, 0, v)), b))) | (j, v, TmAp(x, y)) => TmAp(subst((j, v, x)), subst((j, v, y))) end in +let step = fun e -> case e | TmVar(n) => NoTm | TmLam(t, b) => NoTm | TmAp(x, y) => (if is_value(x) then (if is_value(y) then case x | TmVar(n) => NoTm | TmLam(t, b) => SomeTm(subst((0, y, b))) | TmAp(f, a) => NoTm end else case step(y) | NoTm => NoTm | SomeTm(yp) => SomeTm(TmAp(x, yp)) end) else case step(x) | NoTm => NoTm | SomeTm(xp) => SomeTm(TmAp(xp, y)) end) end in +theorem step_ap_val1 = forall u1: Term -> forall u2: Term -> is_value(u1) == false ==> step(TmAp(u1, u2)) == (case step(u1) | NoTm => NoTm | SomeTm(xp) => SomeTm(TmAp(xp, u2)) end) proof assume is_value(u1) == false => from step(TmAp(u1, u2)) do step end; from is_value(u1) do rewrite assume end end; ? in +theorem step_lam_ap2 = forall w1: Ty -> forall q1: Term -> forall u2: Term -> is_value(u2) == false ==> step(TmAp(TmLam(w1, q1), u2)) == (case step(u2) | NoTm => NoTm | SomeTm(yp) => SomeTm(TmAp(TmLam(w1, q1), yp)) end) proof assume is_value(u2) == false => from step(TmAp(TmLam(w1, q1), u2)) do step end; from is_value(TmLam(w1, q1)) do step end; from is_value(u2) do rewrite assume end end; ? in +theorem step_beta = forall w1: Ty -> forall q1: Term -> forall u2: Term -> is_value(u2) == true ==> step(TmAp(TmLam(w1, q1), u2)) == SomeTm(subst((0, u2, q1))) proof assume is_value(u2) == true => from step(TmAp(TmLam(w1, q1), u2)) do step end; from is_value(TmLam(w1, q1)) do step end; from is_value(u2) do rewrite assume end end; ? in +theorem some_tm_is_some = forall u1: Term -> is_some_tm(SomeTm(u1)) == true proof from is_some_tm(SomeTm(u1)) do step end; from true == true do rewrite refl end end in +theorem progress = forall e0: Term -> forall t0: Ty -> infer(([], e0)) == SomeTy(t0) ==> is_value(e0) || is_some_tm(step(e0)) proof generalize t0 => induction e0 +| TmVar(m0) => forall t0 => from infer(([], TmVar(m0))) do step end; from nth_ty(([], m0)) do step end; from NoTy == SomeTy(t0) do step end; from false ==> $e do step end +| TmLam(w0, q0) => forall t0 => assume infer(([], TmLam(w0, q0))) == SomeTy(t0) => from is_value(TmLam(w0, q0)) do step end; from true || $e do step end +| TmAp(x0, y0) => forall t0 => + alias ihx = ih_x0 => + alias ihy = ih_y0 => + from infer(([], TmAp(x0, y0))) do step end; cases infer(([], x0)) as tx + | NoTy => cases infer(([], y0)) as ty + | NoTy => from ap_result((NoTy, NoTy)) do step end; from NoTy == SomeTy(t0) do step end; from false ==> $e do step end + | SomeTy(s0) => from ap_result((NoTy, SomeTy(s0))) do step end; from NoTy == SomeTy(t0) do step end; from false ==> $e do step end + end + | SomeTy(tf0) => cases tf0 + | TB => cases infer(([], y0)) as ty + | NoTy => from ap_result((SomeTy(TB), NoTy)) do step end; from NoTy == SomeTy(t0) do step end; from false ==> $e do step end + | SomeTy(s0) => from ap_result((SomeTy(TB), SomeTy(s0))) do step end; from NoTy == SomeTy(t0) do step end; from false ==> $e do step end + end + | TArr(ta0, tb0) => cases infer(([], y0)) as ty + | NoTy => from ap_result((SomeTy(TArr(ta0, tb0)), NoTy)) do step end; from NoTy == SomeTy(t0) do step end; from false ==> $e do step end + | SomeTy(s0) => from ap_result((SomeTy(TArr(ta0, tb0)), SomeTy(s0))) do step end; cases ty_eq((ta0, s0)) as teq + | false => from if false then SomeTy(tb0) else NoTy do step end; from NoTy == SomeTy(t0) do step end; from false ==> $e do step end + | true => from if true then SomeTy(tb0) else NoTy do step end; assume SomeTy(tb0) == SomeTy(t0) => cases is_value(x0) as vx + | false => from is_value(TmAp(x0, y0)) do step end; from false || $e do step end; from step(TmAp(x0, y0)) do rewrite step_ap_val1 end end; cases step(x0) as sx + | NoTm => revert ihx with t0 = tf0 => + from infer(([], x0)) do rewrite tx end end; + from SomeTy(tf0) == SomeTy(tf0) do rewrite refl end end; + from true ==> is_value(x0) || is_some_tm(step(x0)) do step end; + from is_value(x0) do rewrite vx end end; + from false || is_some_tm(step(x0)) do step end; + from step(x0) do rewrite sx end end; + from is_some_tm(NoTm) do step end; + from false ==> $e do step end + | SomeTm(u0) => from is_some_tm(case SomeTm(u0) | NoTm => NoTm | SomeTm(xp) => SomeTm(TmAp(xp, y0)) end) do step end + end + | true => cases x0 + | TmVar(m0) => revert is_value(x0) == true => from x0 do rewrite case_eq end end; from is_value(TmVar(m0)) do step end; from false == true do step end; from false ==> $e do step end + | TmLam(w0, q0) => from is_value(TmAp(TmLam(w0, q0), y0)) do step end; from false || $e do step end; cases is_value(y0) as vy + | true => from step(TmAp(TmLam(w0, q0), y0)) do rewrite step_beta end end; from is_some_tm(SomeTm(subst((0, y0, q0)))) do rewrite some_tm_is_some end end + | false => from step(TmAp(TmLam(w0, q0), y0)) do rewrite step_lam_ap2 end end; cases step(y0) as sy + | NoTm => revert ihy with t0 = s0 => + from infer(([], y0)) do rewrite ty end end; + from SomeTy(s0) == SomeTy(s0) do rewrite refl end end; + from true ==> is_value(y0) || is_some_tm(step(y0)) do step end; + from is_value(y0) do rewrite vy end end; + from false || is_some_tm(step(y0)) do step end; + from step(y0) do rewrite sy end end; + from is_some_tm(NoTm) do step end; + from false ==> $e do step end + | SomeTm(u0) => from is_some_tm(case SomeTm(u0) | NoTm => NoTm | SomeTm(yp) => SomeTm(TmAp(TmLam(w0, q0), yp)) end) do step end + end + end + | TmAp(f0, a0) => revert is_value(x0) == true => from x0 do rewrite case_eq end end; from is_value(TmAp(f0, a0)) do step end; from false == true do step end; from false ==> $e do step end + end + end + end + end + end + end +end in 0 diff --git a/hazel-programs/config/colors.hz b/hazel-programs/config/colors.hz index 396c097823..2d60398d71 100644 --- a/hazel-programs/config/colors.hz +++ b/hazel-programs/config/colors.hz @@ -62,14 +62,14 @@ let theme_of(p : ColorPalette, role : ColorOverrides): ColorScheme = ^^fold(let let text_l = color_lightness(p.`ink`) in let toward(base, c, t) = color_with_lightness(c, base +. (text_l -. base) *. t) in -# at(c, t) places c on this scheme's OWN contrast axis: t = 0. is the # +# on_axis(c, t) places c on this scheme's OWN contrast axis: t = 0. is the # # page background's lightness, t = 1. the body text's. That is why one # # definition is correct in all four schemes, where a fixed lightness is # # right in light and invisible in dark. # -let at(c, t) = toward(bg_l, c, t) in +let on_axis(c, t) = toward(bg_l, c, t) in # wash scales chroma too: a fill wants a wash of its hue, an accent # # the whole thing. # -let wash(c, t, sat) = at(color_saturate(c, sat), t) in +let wash(c, t, sat) = on_axis(color_saturate(c, sat), t) in # a fill must be placed against the surface it actually sits ON, and # # not every surface is the page: table rows sit on the code background, # # ten lightness points off the page in dark. Same span, same ink. # diff --git a/hazel-programs/docs/reference/prover-induction.hz b/hazel-programs/docs/reference/prover-induction.hz new file mode 100644 index 0000000000..bd668ef96b --- /dev/null +++ b/hazel-programs/docs/reference/prover-induction.hz @@ -0,0 +1,23 @@ +# CASES AND INDUCTION # + +# A goal stuck on a variable can be split into cases, one per # +# pattern the variable can match. # +# cases e each case knows e == pattern, as the fact case_eq # +# induction e each case instead knows the statement for the # +# smaller values inside it: ih_t for a tail t # +# Use induction on a recursive type such as a list, and cases for # +# anything else, such as a Bool test. Facts about e leave scope in # +# an induction on e; revert a fact first to keep it. # + +theorem app_nil = forall xs: [Int] -> xs @ [] == xs proof + induction xs + | [] => + from [] @ [] do step end; + rewrite refl end + | x :: t => + from (x :: t) @ [] do step end; + from t @ [] do rewrite ih_t end end; + rewrite refl end + end +in +¿ diff --git a/hazel-programs/docs/reference/prover-lemmas.hz b/hazel-programs/docs/reference/prover-lemmas.hz new file mode 100644 index 0000000000..4bfa63aaeb --- /dev/null +++ b/hazel-programs/docs/reference/prover-lemmas.hz @@ -0,0 +1,32 @@ +# VARIABLES AND LEMMAS # + +# forall x: T -> P states P for every x of type T. In the proof, x # +# is an unknown value: evaluation can step around it, but not into # +# it. Goals keep definitions by name, so rev stays rev until a step # +# needs to look inside it. # + +let rev = fun xs -> case xs | [] => [] | y :: t => rev(t) @ [y] end in + +theorem rev_one = forall x: Int -> rev([x]) == [x] proof + from rev([x]) do step end; + from rev([]) do step end; + from [] @ [x] do step end; + rewrite refl end +in + +# A proven theorem is a rule. On a goal that matches the rule's left # +# side, rewrite name end replaces it with the right side; inside from # +# p do ... end, it rewrites just p. rewrite <- name end goes right to # +# left, and the builtin rule refl closes e == e. Typing a rule's name # +# in the write box lists the places it applies. # +theorem rev_two = forall x: Int -> forall y: Int -> rev([x, y]) == [y, x] proof + from rev([x, y]) do step end; + from rev([y]) do rewrite rev_one end end; + from [y] @ [x] do step end; + rewrite refl end +in + +# A proof may use a theorem that isn't finished: it then reads # +# proven*, assuming that theorem, and the star names it. Using a # +# refuted one is an error. # +¿ diff --git a/hazel-programs/docs/reference/prover-reference.hz b/hazel-programs/docs/reference/prover-reference.hz new file mode 100644 index 0000000000..0c68943169 --- /dev/null +++ b/hazel-programs/docs/reference/prover-reference.hz @@ -0,0 +1,75 @@ +# EVERY STEP # + +# Click any step in these proofs to read about it in the docs panel. # + +let sum = fun xs -> case xs | [] => 0 | y :: t => y + sum(t) end in +let sum_acc = fun (xs, a) -> case xs | [] => a | y :: t => sum_acc((t, a + y)) end in +let sign = fun n -> if n > 0 then 1 else 0 in + +theorem app_nil = forall xs: [Int] -> xs @ [] == xs proof + induction xs + | [] => from [] @ [] do step end; rewrite refl end + | x :: t => from (x :: t) @ [] do step end; from t @ [] do rewrite ih_t end end; rewrite refl end + end +in + +theorem app_nil_fun = (fun ys: [Int] -> ys @ []) == (fun ys: [Int] -> ys) proof + funext ys => + revert app_nil with xs = ys => + assume ys @ [] == ys => + from ys at 2 do rewrite <- assume end end; + rewrite refl end +in + +theorem shuffle = forall s: Int -> forall a: Int -> forall y: Int -> (y + s) + a == s + (a + y) proof + from (y + s) + a do algebra s + (a + y) end end; rewrite refl end +in + +theorem acc = forall xs: [Int] -> forall a: Int -> sum_acc((xs, a)) == sum(xs) + a proof + generalize a => + induction xs + | [] => forall a => + from sum_acc(([], a)) do step end; from sum([]) do step end; + from 0 + a do algebra a end end; rewrite refl end + | y :: t => forall a => + from sum_acc((y :: t, a)) do step end; from sum(y :: t) do step end; + from (y + sum(t)) + a do rewrite shuffle end end; + from sum(t) + (a + y) do rewrite <- ih_t with a = a + y end end; rewrite refl end + end +in + +theorem div_pos = forall z: Int -> z > 0 ==> 8 / z == 8 / z proof + assume pos = z > 0 => + have z != 0 proof rewrite nonzero_of_pos with a = z end => + rewrite refl end +in + +theorem div_neg = forall z: Int -> z < 0 ==> 8 / z == 8 / z proof + assume z < 0 => + have nz = z != 0 proof rewrite nonzero_of_neg end => + rewrite refl end +in + +theorem sum_three = forall x: Int -> forall y: Int -> x == 1 ==> y == 2 ==> x + y == 3 proof + assume x == 1 => alias hx = assume => assume y == 2 => + from x do rewrite hx end end; from y do rewrite assume end end; + from 1 + 2 do step end; step +in + +theorem sign_pos = forall n: Int -> n > 0 ==> sign(n) == 1 proof + assume n > 0 => + from sign(n) do step end; + cases n > 0 + | true => from if true then 1 else 0 do step end; step + | false => revert case_eq => from n > 0 do rewrite assume end end; from true == false do step end; rewrite false_impl end + end +in + +theorem sign_le = forall n: Int -> sign(n) <= 1 proof + from sign(n) do step end; + cases n > 0 + | true => from if true then 1 else 0 do step end; step + | false => from if false then 1 else 0 do step end; step + end +in +¿ diff --git a/hazel-programs/docs/reference/prover-side-conditions.hz b/hazel-programs/docs/reference/prover-side-conditions.hz new file mode 100644 index 0000000000..5948b75b00 --- /dev/null +++ b/hazel-programs/docs/reference/prover-side-conditions.hz @@ -0,0 +1,19 @@ +# SIDE CONDITIONS # + +# Some steps hold only under a condition: 8 / z needs z != 0. The # +# checker records each condition, and discharges it from the facts # +# in scope or by evaluation. One it can't discharge stays open: the # +# theorem reads incomplete, 1 open, and the step's row has a red # +# circle. Click the circle to see the condition and ways to add it. # +theorem div_open = forall z: Int -> 8 / z == 8 / z proof rewrite refl end in + +# For a statement P ==> Q, assume h = P => makes P a fact named h # +# for the rest of the proof. have h = P proof ... => proves a fact # +# on the way, here with the builtin rule nonzero_of_pos. Without a # +# name, the facts are called assume and have. # +theorem div_ok = forall z: Int -> z > 0 ==> 8 / z == 8 / z proof + assume pos = z > 0 => + have nz = z != 0 proof rewrite nonzero_of_pos end => + rewrite refl end +in +¿ diff --git a/hazel-programs/docs/reference/prover-stepper.hz b/hazel-programs/docs/reference/prover-stepper.hz new file mode 100644 index 0000000000..a31e2d4199 --- /dev/null +++ b/hazel-programs/docs/reference/prover-stepper.hz @@ -0,0 +1,24 @@ +# THE STEPPER # + +# A proof is a chain of goals. It starts at the statement, and each # +# step replaces the goal with one that is enough to prove it, until # +# the goal is true. The stepper draws the chain, one row per goal, # +# and underlines the part of each goal that the next step acts on. # + +# The stepper and the proof text are two views of one proof: editing # +# either changes the other. You can write a proof in the stepper and # +# only read the text it writes. # + +# An unfinished proof ends in a write box. Click the box in the # +# stepper for try_it below, then: # +# Tab takes the next evaluation step, shown in grey # +# type the goal you want next, such as 21 == 21, and press # +# Enter: a search finds the steps that get there # +# select part of the goal, such as 3 + 4, to work on just that # +# part # +# The tabs above the box offer more: Step marks each part of the # +# goal that can be evaluated, and Strategy writes the structured # +# steps of the later slides. # + +theorem try_it = (1 + 2) * (3 + 4) == 21 proof ¿ in +¿ diff --git a/hazel-programs/docs/reference/prover-theorems.hz b/hazel-programs/docs/reference/prover-theorems.hz new file mode 100644 index 0000000000..66247025e6 --- /dev/null +++ b/hazel-programs/docs/reference/prover-theorems.hz @@ -0,0 +1,30 @@ +# THEOREMS # + +# A theorem states a Bool and proves it: # +# theorem name = statement proof steps in body # +# Proofs are checked as the program runs. Below the program, a # +# stepper shows each theorem's proof, with its status in the header: # +# proven the goal reached true # +# refuted the goal reached false, so the statement is wrong # +# incomplete the proof stops before either # + +# from 2 * 3 do step end evaluates the 2 * 3 inside the goal. The # +# last step evaluates 6 == 6 to true. # +theorem six = 2 * 3 == 6 proof + from 2 * 3 do step end; + step +in + +# The same steps show that this statement is false. # +theorem seven = 2 * 3 == 7 proof + from 2 * 3 do step end; + step +in + +# An empty proof, drawn as a small circle, is one still to write. The # +# next slide fills one in. # +theorem eight = 2 * 4 == 8 proof ¿ in + +# Proofs in a theorem's body can use it by name, as the slide on # +# lemmas shows. # +¿ diff --git a/src/CLI/Cli.re b/src/CLI/Cli.re index 9f0daf8aaa..19196e8115 100644 --- a/src/CLI/Cli.re +++ b/src/CLI/Cli.re @@ -377,7 +377,7 @@ let probe_hazel = (auto: bool, many: bool, path: string): unit => { root_id, syntax.term_data, syntax.terms, - syntax.measured, + Haz3lcore.CachedSyntax.measured(syntax), info_map, ) ) { diff --git a/src/CLI/Diagnostic.re b/src/CLI/Diagnostic.re index 8326b92af7..0616c30e48 100644 --- a/src/CLI/Diagnostic.re +++ b/src/CLI/Diagnostic.re @@ -49,6 +49,7 @@ let warning_string = (item: Language.Warning.list_item): string => | TPat(NonContractive(name)) => "type " ++ name ++ " is defined as itself" | Typ(NonContractive(name)) => "recursive type rec " ++ name ++ " is defined as itself" + | Exp(ForallOutsideTheorem) => "forall outside a theorem has no value" }; /* Format a single diagnostic (error or warning) in Rust-style with source diff --git a/src/CLI/Run.re b/src/CLI/Run.re index 1978fc5dfa..09cf3c9aec 100644 --- a/src/CLI/Run.re +++ b/src/CLI/Run.re @@ -11,8 +11,9 @@ let statics_and_elab = (exp: Exp.t): (Statics.Map.t, Exp.t) => let elaborate = (exp: Exp.t): Exp.t => snd(statics_and_elab(exp)); let evaluate = (exp: Exp.t): Exp.t => { + let (statics, elab) = statics_and_elab(exp); let (result, _) = - Evaluator.evaluate(~env=Builtins.env_init, elaborate(exp)); + Evaluator.evaluate(~statics, ~env=Builtins.env_init, elab); result; }; diff --git a/src/docslides/Slides.re b/src/docslides/Slides.re index 41b2f90940..05bbb64483 100644 --- a/src/docslides/Slides.re +++ b/src/docslides/Slides.re @@ -16,6 +16,12 @@ let all_slides: list((string, Haz3lcore.PersistentZipper.t)) = ("Cards", [%blob "cards.hz"]), ("Probes", [%blob "probes.hz"]), ("Livelits / Builtins", [%blob "livelits-builtins.hz"]), + ("Prover / Theorems", [%blob "prover-theorems.hz"]), + ("Prover / The Stepper", [%blob "prover-stepper.hz"]), + ("Prover / Variables and Lemmas", [%blob "prover-lemmas.hz"]), + ("Prover / Cases and Induction", [%blob "prover-induction.hz"]), + ("Prover / Side Conditions", [%blob "prover-side-conditions.hz"]), + ("Prover / Every Step", [%blob "prover-reference.hz"]), ] |> List.map(~f=((name, text)) => (name, Haz3lcore.PersistentZipper.of_slide_text(text)) diff --git a/src/haz3lcore/CachedSyntax.re b/src/haz3lcore/CachedSyntax.re index 84c59ec1b8..5c47b62b00 100644 --- a/src/haz3lcore/CachedSyntax.re +++ b/src/haz3lcore/CachedSyntax.re @@ -1,3 +1,11 @@ +/* A segment laid out on its own: what a sub-editor renders of a region + * of the main editor's segment. */ +type splice = { + segment: Segment.t, + measured: Measured.t, + projector_list: list(Id.t), +}; + type t = { old: bool, segment: Segment.t, @@ -214,3 +222,6 @@ let calculate = (z: Zipper.t, info_map, dyn_map, ~elaborated=None, old: t) => { }; }; }; + +let measured = (syntax: t) => syntax.measured; +let segment = (syntax: t) => syntax.segment; diff --git a/src/haz3lcore/CompositionCore/HighLevelNodeMap.re b/src/haz3lcore/CompositionCore/HighLevelNodeMap.re index 27357e12f4..1195367fa2 100644 --- a/src/haz3lcore/CompositionCore/HighLevelNodeMap.re +++ b/src/haz3lcore/CompositionCore/HighLevelNodeMap.re @@ -101,8 +101,7 @@ module Utils = { | LivelitName(_) | TyAlias(_) | ExplicitNonlabel - | Theorem(_, _, _) - | ProofObject(_) + | Theorem(_, _, _, _) | Forall(_, _) | Projector(_, _) | Var(_) diff --git a/src/haz3lcore/CompositionCore/prompt_factory/HazelSyntaxNotes.re b/src/haz3lcore/CompositionCore/prompt_factory/HazelSyntaxNotes.re index 9cfb17ab67..d09c087b9e 100644 --- a/src/haz3lcore/CompositionCore/prompt_factory/HazelSyntaxNotes.re +++ b/src/haz3lcore/CompositionCore/prompt_factory/HazelSyntaxNotes.re @@ -18,7 +18,7 @@ let self = [ "10. **Comments**: `# text #`. MUST have BOTH opening AND closing `#`. Cannot span multiple lines.", "11. **No dot-accessor** on plain tuples — use destructuring: `let (a, b) = tuple in ...`. Labeled-tuple/module fields DO use `.` (see Modules).", "12. **FORBIDDEN keywords**: `rec`, `switch`, `match`, `with`, `of`. NEVER use them.", - "13. **Reserved words** — these lex as keyword forms and can NEVER be variable/function names (e.g. `eval` becomes the eval-filter keyword and misparses): `case`, `debug`, `eval`, `fix`, `forall`, `fun`, `hide`, `hint`, `if`, `in`, `let`, `module`, `pause`, `test`, `theorem`, `type`, `typfun`, `use` (also `proof_object` and the `of_*` prover forms). Common traps: `eval`, `test` — name things `evaluate`, `run_tests`, etc. `true`/`false`/`undefined`/`_` are literals/wildcard, equally unusable. `rec` and `poly` are reserved only in TYPE positions (recursive/polymorphic types — there is no let-rec). Proof-syntax delimiters (`val`, `valid`, `consistent`, `matched_*`) and trailing delimiters (`end`, `then`, `else`, `with`) DO parse as ordinary names, but avoid them for clarity.", + "13. **Reserved words** — these lex as keyword forms and can NEVER be variable/function names (e.g. `eval` becomes the eval-filter keyword and misparses): `case`, `debug`, `eval`, `fix`, `forall`, `fun`, `hide`, `hint`, `if`, `in`, `let`, `module`, `pause`, `test`, `theorem`, `type`, `typfun`, `use` (also the `of_*` prover forms). Common traps: `eval`, `test` — name things `evaluate`, `run_tests`, etc. `true`/`false`/`undefined`/`_` are literals/wildcard, equally unusable. `rec` and `poly` are reserved only in TYPE positions (recursive/polymorphic types — there is no let-rec). Proof-syntax delimiters (`val`, `valid`, `consistent`, `matched_*`) and trailing delimiters (`end`, `then`, `else`, `with`) DO parse as ordinary names, but avoid them for clarity.", "14. **No modulo operator** `%`. Use the `int_mod(a, b)` builtin instead.", "15. **Modules**: `{ let x = 1; let y = 2 }` — curly braces, semicolon-separated items. Use `module M = { ... }` for capitalized names.", "", diff --git a/src/haz3lcore/Editor.re b/src/haz3lcore/Editor.re index 2c748e5cf0..7db5a8cf25 100644 --- a/src/haz3lcore/Editor.re +++ b/src/haz3lcore/Editor.re @@ -168,7 +168,8 @@ module Update = { ); /* 2. Record target column if moving up/down */ - let state = update_col_target(~measured=syntax.measured, a, state); + let state = + update_col_target(~measured=CachedSyntax.measured(syntax), a, state); /* 3. Update the zipper */ let+ zipper = diff --git a/src/haz3lcore/EditorTransform.re b/src/haz3lcore/EditorTransform.re new file mode 100644 index 0000000000..04c0a3c0bc --- /dev/null +++ b/src/haz3lcore/EditorTransform.re @@ -0,0 +1,904 @@ +open Language; +open Util; + +/* A rewrite of one sub-term, routed through editor actions. It targets + * either an expression or a proof node (proofs sit inside `Theorem` + * expressions and have their own id space). */ +[@deriving (show({with_path: false}), sexp, yojson)] +type patch = + | ExpPatch({ + target_id: option(Id.t), + replacement: Exp.t, + /* When set, pretty-print just the replacement after splicing it in. + * Defaults on. */ + reflow: bool, + }) + | ProofPatch({ + target_id: Id.t, + replacement: Proof.t, + /* When set, lay out the new steps in the proof of the theorem the + * replacement is in (see `Reflow.proof` and `Keep`). Defaults on. */ + reflow: bool, + }) + /* Remove a proof step, with its `;`, from its enclosing `Seq`, or + * replace it with a hole when it is the whole proof. */ + | ProofRemovePatch({target_id: Id.t}); + +let mk_patch = (~target_id=?, ~reflow=true, replacement: Exp.t): patch => + ExpPatch({ + target_id, + replacement, + reflow, + }); + +let mk_proof_patch = + (~target_id: Id.t, ~reflow=true, replacement: Proof.t): patch => + ProofPatch({ + target_id, + replacement, + reflow, + }); + +let mk_proof_remove_patch = (~target_id: Id.t): patch => + ProofRemovePatch({target_id: target_id}); + +/* Replacing the sub-term with a given id. Each replacement returns the + * term it replaced and the new root, or None when no sub-term has the id + * (it may have gone since the patch was made). */ +module Rewrite = { + let replace = (~map_term, ~rep_id, ~target_id: Id.t, replacement, root) => { + let replaced = ref(None); + let root = + map_term( + (cont, node) => + if (Id.equal(rep_id(node), target_id)) { + replaced := Some(node); + replacement; + } else { + cont(node); + }, + root, + ); + Option.map(~f=old => (old, root), replaced^); + }; + + /* With no `target_id`, replaces the root. */ + let exp = + (~target_id: option(Id.t), replacement: Exp.t, root: Exp.t) + : option((Exp.t, Exp.t)) => + switch (target_id) { + | None => Some((root, replacement)) + | Some(target_id) => + replace( + ~map_term=(f_exp, e) => Exp.map_term(~f_exp, e), + ~rep_id=Exp.rep_id, + ~target_id, + replacement, + root, + ) + }; + + /* For proofs nested in program syntax. */ + let proof_in_exp = + (~target_id: Id.t, replacement: Proof.t, root: Exp.t) + : option((Proof.t, Exp.t)) => + replace( + ~map_term=(f_proof, e) => Exp.map_term(~f_proof, e), + ~rep_id=Proof.rep_id, + ~target_id, + replacement, + root, + ); + + /* The `Seq` whose direct child is `target_id`, and its other child. */ + let rec seq_parent = + (~target_id: Id.t, p: Proof.t): option((Id.t, Proof.t)) => + switch (p.term) { + | Seq(p1, p2) when Id.equal(Proof.rep_id(p1), target_id) => + Some((Proof.rep_id(p), p2)) + | Seq(p1, p2) when Id.equal(Proof.rep_id(p2), target_id) => + Some((Proof.rep_id(p), p1)) + | _ => List.find_map(~f=seq_parent(~target_id), Proof.children(p)) + }; + + /* For proofs nested in program syntax. */ + let seq_parent_in_exp = + (~target_id: Id.t, root: Exp.t): option((Id.t, Proof.t)) => { + let result = ref(None); + let _: Exp.t = + Exp.map_term( + ~f_proof= + (_cont, p) => { + switch (result^) { + | None => result := seq_parent(~target_id, p) + | Some(_) => () + }; + p; + }, + root, + ); + result^; + }; + + /* The theorem whose proof has the node `proof_id`: its id and its whole + * proof. */ + let theorem_around = + (~proof_id: Id.t, root: Exp.t): option((Id.t, Proof.t)) => { + let rec has_node = (p: Proof.t): bool => + Id.equal(Proof.rep_id(p), proof_id) + || List.exists(~f=has_node, Proof.children(p)); + let result = ref(None); + let _: Exp.t = + Exp.map_term( + ~f_exp= + (cont, e) => { + switch (e.term) { + | Theorem(_, _, proof, _) + when Option.is_none(result^) && has_node(proof) => + result := Some((Exp.rep_id(e), proof)) + | _ => () + }; + cont(e); + }, + root, + ); + result^; + }; + + /* Removing a step rewrites its enclosing `Seq` to the surviving sibling, + * so the step and its `;` leave the text together. A step that is the + * whole proof becomes a hole. Returns the id to replace and what + * replaces it. */ + let step_removal = + (~target_id: Id.t, seq_parent: option((Id.t, Proof.t))) + : (Id.t, Proof.t) => + switch (seq_parent) { + | Some(found) => found + | None => (target_id, Proof.fresh(EmptyHole)) + }; +}; + +/* Writing a replaced sub-term back into the program's segment. + * + * Re-serializing the whole program around a replaced sub-term reformats + * all of the user's code (secondary, lexemes, parens). So `local` instead + * finds the pieces the old sub-term came from in the current segment and + * replaces just that range, leaving text elsewhere exactly as it was. + * `whole_program` is the fallback. */ +module Splice = { + /* The editable writer: display settings (folded function bodies, hidden + * ascriptions) would destroy user code. It keeps literals as they were + * spelled (`007`). */ + let to_segment = (a: Any.t): Segment.t => + ExpToSegment.any_to_segment( + ~settings=ExpToSegment.Settings.editable(~inline=false), + a, + ); + + type outcome = + | NotFound /* extent not in this subtree */ + | Spliced + | Failed; /* extent found but can't be spliced safely */ + + /* The range is found by id: term ids come from the pieces they were + * parsed from, and the serializer stamps term ids back onto the pieces + * it emits, so serializing the old sub-term yields the ids of the + * pieces it occupies (plus fresh secondary ids, which match nothing). + * + * With `reflow` the replacement is pretty-printed by itself. + * + * None when the range can't be found or the splice wouldn't reparse + * faithfully. */ + let local = + (~old_node: Any.t, ~replacement: Any.t, ~reflow: bool, seg: Segment.t) + : option(Segment.t) => { + let old_ids = + old_node + |> to_segment + |> Segment.ids + |> List.map(~f=id => (id, ())) + |> Id.Map.of_list; + let raw = to_segment(replacement); + let raw_atomic = + List.length(List.filter(~f=p => !Piece.is_secondary(p), raw)) <= 1; + let is_match = (p: Piece.t) => Id.Map.mem(Piece.id(p), old_ids); + let rec go = (seg: Segment.t): (Segment.t, outcome) => { + let matched_idxs = + seg + |> List.mapi(~f=(i, p) => is_match(p) ? Some(i) : None) + |> List.filter_map(~f=Fn.id); + switch (matched_idxs) { + | [] => descend(seg) + | [first, ...rest] => + let lo = first; /* mapi indices are ascending */ + let hi = List.fold_left(~f=max, ~init=first, rest); + /* every non-secondary piece inside the range must belong to the + * old sub-term; a foreign tile wedged in means the id mapping is + * broken and splicing would eat unrelated syntax */ + let range_ok = + seg + |> List.mapi(~f=(i, p) => (i, p)) + |> List.for_all(~f=((i, p)) => + i < lo || i > hi || is_match(p) || Piece.is_secondary(p) + ); + if (!range_ok) { + (seg, Failed); + } else { + let pre = List.filteri(~f=(i, _) => i < lo, seg); + let post = List.filteri(~f=(i, _) => i > hi, seg); + /* If the old sub-term shares this level with sibling pieces + * (operators, other steps), a multi-piece replacement could + * re-associate on reparse. Expressions get a defensive Parens. + * Proofs fail here, and `apply_patch` replaces the theorem's + * whole proof instead, which has its slot to itself. */ + let partial = + List.exists(~f=p => !Piece.is_secondary(p), pre @ post); + let new_seg = + if (!partial || raw_atomic) { + Some(raw); + } else { + switch (replacement) { + | Exp(e) => Some(to_segment(Exp(Exp.fresh(Parens(e))))) + | _ => None + }; + }; + switch (new_seg) { + | None => (seg, Failed) + | Some(new_seg) => + let new_seg = reflow ? PrettySegment.prettify(new_seg) : new_seg; + (pre @ new_seg @ post, Spliced); + }; + }; + }; + } + and descend = (seg: Segment.t): (Segment.t, outcome) => { + let (rev_pieces, outcome) = + List.fold_left( + ~f= + ((acc, outcome), p: Piece.t) => + switch (outcome, p) { + | (NotFound, Tile(t)) => + let (rev_children, outcome) = + List.fold_left( + ~f= + ((cs, oc), child) => + switch (oc) { + | NotFound => + let (child', oc') = go(child); + ([child', ...cs], oc'); + | Spliced + | Failed => ([child, ...cs], oc) + }, + ~init=([], NotFound), + t.children, + ); + let tile: Piece.t = + Tile({ + ...t, + children: List.rev(rev_children), + }); + ([tile, ...acc], outcome); + | _ => ([p, ...acc], outcome) + }, + ~init=([], NotFound), + seg, + ); + (List.rev(rev_pieces), outcome); + }; + switch (go(seg)) { + | (seg', Spliced) => Some(seg') + | (_, NotFound | Failed) => None + }; + }; + + /* Re-serialize the whole program. That discards its layout, so with + * `reflow` all of it is pretty-printed. */ + let whole_program = (~reflow: bool, root: Exp.t): Segment.t => { + let seg = to_segment(Exp(root)); + reflow ? PrettySegment.prettify(seg) : seg; + }; +}; + +/* Laying out a theorem's proof again after an edit to it. */ +module Reflow = { + /* The proof is laid out as a whole and inside its theorem, because an + * edit to one step changes the lines around it: a second step turns a + * one-line proof into a block, and the block is indented from where the + * theorem sits. Only the slot of the proof is rewritten, so the + * statement and the program around the theorem keep their text, and + * `Keep.text` then puts back the proof's own text wherever the edit + * didn't change it. */ + let proof = (~theorem_id: Id.t, seg: Segment.t): Segment.t => { + /* `f` gives the new contents of a slot of steps, from the theorem's + * tile and the slot's index in it. */ + let map_steps = (f: (Tile.t, int) => Segment.t): (Segment.t => Segment.t) => + Segment.map_deep( + List.map(~f=(p: Piece.t) => + switch (p) { + | Tile(t) when Id.equal(t.id, theorem_id) => + Piece.Tile({ + ...t, + children: + List.mapi( + ~f= + (i, (sort, child)) => + Sort.equal(sort, Proof) ? f(t, i) : child, + Tile.sorted_children(t), + ), + }) + | _ => p + } + ), + ); + let laid_out = + map_steps( + (t, i) => + /* Spacing first: the spliced-in steps come from the serializer, + * which writes `| x:: t =>`, and the pretty printer keeps a + * rule's pattern as it finds it. */ + switch ( + [Piece.Tile(t)] + |> SpaceNormalize.go(~canonicalize=true) + |> PrettySegment.prettify + ) { + | [Tile(pretty)] + when List.length(pretty.children) == List.length(t.children) => + List.nth_exn(pretty.children, i) + | _ => List.nth_exn(t.children, i) + }, + seg, + ); + let levels = Indentation.level_map(laid_out); + map_steps( + (t, i) => + Indentation.fix_indentation_in_segment( + levels, + List.nth_exn(t.children, i), + ), + laid_out, + ); + }; +}; + +/* Putting the user's whitespace and comments back after an edit. + * + * The edit itself is made by printing terms, so the edited segment's + * tokens are right but its layout is the printer's. `text` keeps those + * tokens and gives each gap between two of them the text it had before + * the edit, when the tokens on either side of it are both still there. + * Only gaps next to new tokens take the printer's layout. So separators + * between surviving steps, comments and hand indentation all stay. + * + * Tokens are matched by id first: the printer stamps term ids onto the + * pieces it writes, so a carried-over sub-term's tokens keep theirs. A + * node the edit rebuilt has fresh ids, and its tokens are matched to the + * old ones by label between the id matches, so that rebuilding an + * induction to add a case keeps the layout around its other cases. */ +module Keep = { + /* A segment as its tokens (tile shards, grout, projectors), with the + * run of secondary before each one and one more for the run at the + * end. A gap's `owner` is the tile whose child it lies in, and its + * depth is how many tiles' children it lies in. */ + type flat = { + tokens: array((Id.t, string)), + gaps: array(Segment.t), + owners: array(option(Id.t)), + depths: array(int), + /* For each tile child, the indices of its first gap and its last: + * the runs just inside its delimiters. */ + children: list((int, int)), + }; + + let flatten = (seg: Segment.t): flat => { + let tokens = ref([]); + let gaps = ref([]); + let owners = ref([]); + let depths = ref([]); + let children = ref([]); + let run = ref([]); + let count = ref(0); + let token = (~owner, ~depth, tok) => { + gaps := [List.rev(run^), ...gaps^]; + owners := [owner, ...owners^]; + depths := [depth, ...depths^]; + tokens := [tok, ...tokens^]; + run := []; + count := count^ + 1; + }; + let rec level = (~owner, ~depth, seg: Segment.t) => + List.iter( + ~f= + (p: Piece.t) => + switch (p) { + | Secondary(_) => run := [p, ...run^] + | Tile(t) => + List.iteri( + ~f= + (i, shard) => { + if (i > 0) { + let first = count^; + level( + ~owner=Some(t.id), + ~depth=depth + 1, + List.nth_exn(t.children, i - 1), + ); + children := [(first, count^), ...children^]; + }; + let (owner, depth) = + i == 0 ? (owner, depth) : (Some(t.id), depth + 1); + token(~owner, ~depth, (t.id, Tile.token(t, shard))); + }, + t.shards, + ) + | Grout(g) => token(~owner, ~depth, (g.id, "")) + | Projector(pr) => token(~owner, ~depth, (pr.id, "")) + }, + seg, + ); + level(~owner=None, ~depth=0, seg); + gaps := [List.rev(run^), ...gaps^]; + owners := [None, ...owners^]; + depths := [0, ...depths^]; + { + tokens: Array.of_list(List.rev(tokens^)), + gaps: Array.of_list(List.rev(gaps^)), + owners: Array.of_list(List.rev(owners^)), + depths: Array.of_list(List.rev(depths^)), + children: children^, + }; + }; + + /* Which old token each new token is, and back. Tokens with the same id + * and label are matched first, in order; between those, a longest + * common subsequence of labels matches the tokens of rebuilt nodes. */ + let align = + (old: flat, new_: flat): (array(option(int)), array(option(int))) => { + let n_old = Array.length(old.tokens); + let n_new = Array.length(new_.tokens); + let to_new = Array.create(~len=n_old, None); + let to_old = Array.create(~len=n_new, None); + let pair = (i, j) => { + to_new[i] = Some(j); + to_old[j] = Some(i); + }; + let old_index = Stdlib.Hashtbl.create(n_old); + Array.iteri(old.tokens, ~f=(i, tok) => + Stdlib.Hashtbl.replace(old_index, tok, i) + ); + let anchors = + Array.to_list(new_.tokens) + |> List.mapi(~f=(j, tok) => + (j, Stdlib.Hashtbl.find_opt(old_index, tok)) + ) + |> List.fold_left( + ~f= + ((acc, last), (j, i)) => + switch (i) { + | Some(i) when i > last => ([(i, j), ...acc], i) + | _ => (acc, last) + }, + ~init=([], (-1)), + ) + |> fst + |> List.rev; + /* Matches labels in old[i0, i1) against new[j0, j1). Stretches are + * the insides of rebuilt nodes, so they are short; a long one is + * left unmatched rather than paying for the table. Holes have no + * label: a hole the edit filled must not match one it wrote. */ + let by_label = (i0, i1, j0, j1) => { + let (m, n) = (i1 - i0, j1 - j0); + if (m > 0 && n > 0 && m * n <= 250_000) { + let label_at = (flat, k) => snd(flat.tokens[k]); + let same = (i, j) => + !String.is_empty(label_at(old, i0 + i)) + && String.equal(label_at(old, i0 + i), label_at(new_, j0 + j)); + let table = Array.make_matrix(~dimx=m + 1, ~dimy=n + 1, 0); + for (i in m - 1 downto 0) { + for (j in n - 1 downto 0) { + table[i][j] = + same(i, j) + ? table[i + 1][j + 1] + 1 + : max(table[i + 1][j], table[i][j + 1]); + }; + }; + let rec walk = (i, j) => + if (i < m && j < n) { + if (same(i, j)) { + pair(i0 + i, j0 + j); + walk(i + 1, j + 1); + } else if (table[i + 1][j] >= table[i][j + 1]) { + walk(i + 1, j); + } else { + walk(i, j + 1); + }; + }; + walk(0, 0); + }; + }; + let last = + List.fold_left( + ~f= + ((i0, j0), (i, j)) => { + by_label(i0, i, j0, j); + pair(i, j); + (i + 1, j + 1); + }, + ~init=(0, 0), + anchors, + ); + by_label(fst(last), n_old, snd(last), n_new); + (to_new, to_old); + }; + + let is_comment = (p: Piece.t) => + Piece.is_secondary(p) && !Piece.is_whitespace(p); + + /* A gap's pieces up to its last comment, or nothing if it has none. */ + let through_last_comment = (gap: Segment.t): Segment.t => { + let rec drop = (rev: Segment.t) => + switch (rev) { + | [p, ...rest] when !is_comment(p) => drop(rest) + | _ => rev + }; + gap |> List.rev |> drop |> List.rev; + }; + + /* `after`, an edit of `before`, with `before`'s layout wherever the + * edit left it alone. */ + let text = (~before: Segment.t, ~after: Segment.t): Segment.t => { + let old = flatten(before); + let new_ = flatten(after); + let (to_new, to_old) = align(old, new_); + let (n_old, n_new) = ( + Array.length(old.tokens), + Array.length(new_.tokens), + ); + /* Indices -1 and n stand for the start and end of the program. */ + let old_of = j => + j < 0 ? Some(-1) : j >= n_new ? Some(n_old) : to_old[j]; + let new_of = i => + i < 0 ? Some(-1) : i >= n_old ? Some(n_new) : to_new[i]; + /* Tiles with a token in `after`, under their old ids. */ + let kept_tiles = Stdlib.Hashtbl.create(n_old); + Array.iteri(to_new, ~f=(i, j) => + if (Option.is_some(j)) { + Stdlib.Hashtbl.replace(kept_tiles, fst(old.tokens[i]), ()); + } + ); + let survives = (owner: option(Id.t)) => + switch (owner) { + | None => true + | Some(id) => Stdlib.Hashtbl.mem(kept_tiles, id) + }; + /* Gap j was a gap of `before` too: the tokens around it were next to + * each other there. */ + let unchanged = j => + switch (old_of(j - 1), old_of(j)) { + | (Some(x), Some(y)) => y == x + 1 + | _ => false + }; + /* The gaps just inside a child whose contents changed: when such a + * child becomes a block, its first and last lines move. */ + let at_changed_edge = Array.create(~len=n_new + 1, false); + List.iter( + ~f= + ((first, last)) => + if (! + List.for_all( + ~f=unchanged, + List.init(last - first + 1, ~f=k => first + k), + )) { + at_changed_edge[first] = true; + at_changed_edge[last] = true; + }, + new_.children, + ); + /* The old gap before each old token stays before it, unless the token + * that preceded it there now comes after it. When new tokens went in + * between those two, the gap goes where they are shallowest, latest + * among equals: before a step inserted ahead of the token, but outside + * parens opened around it. A comment that ended the earlier token's + * line stays on that line, ahead of the first new line break. */ + let old_gap_at = Array.create(~len=n_new + 1, None); + let line_ends = Array.create(~len=n_new + 1, []); + for (j in 0 to n_new) { + switch (old_of(j)) { + | Some(y) => + let gap = old.gaps[y]; + switch (new_of(y - 1)) { + | Some(x) when x >= j => () + | Some(x) when x < j - 1 => + let target = + List.init(j - x - 1, ~f=k => x + 2 + k) + |> List.fold_left( + ~f= + (best, k) => + new_.depths[k] <= new_.depths[best] ? k : best, + ~init=x + 1, + ); + let (line_end, lb, rest) = ListUtil.split(gap, Piece.is_linebreak); + let first_break = + List.init(target - x - 1, ~f=k => x + 1 + k) + |> List.find(~f=k => + List.exists(~f=Piece.is_linebreak, new_.gaps[k]) + ); + switch (lb, first_break) { + | (Some(lb), Some(k)) when List.exists(~f=is_comment, line_end) => + line_ends[k] = line_end; + old_gap_at[target] = Some([lb, ...rest]); + | _ => old_gap_at[target] = Some(gap) + }; + | _ => old_gap_at[j] = Some(gap) + }; + | None => () + }; + }; + /* The comments of the old gaps `is`, unless they were inside a + * deleted node. */ + let comments_of = (is: list(int)): Segment.t => + is + |> List.filter(~f=i => survives(old.owners[i])) + |> List.concat_map(~f=i => old.gaps[i]) + |> through_last_comment; + let breaks = (gap: Segment.t) => + List.length(List.filter(~f=Piece.is_linebreak, gap)); + /* The edited segment can hold old trivia where the edit didn't reach. + * Placing that is up to the rules here, so a printed gap loses its old + * comments, each with the whitespace before it, and gives the rest of + * its old whitespace under fresh ids. */ + let old_trivia = Stdlib.Hashtbl.create(64); + Array.iter( + ~f= + List.iter(~f=p => + Stdlib.Hashtbl.replace(old_trivia, Piece.id(p), ()) + ), + old.gaps, + ); + let printed = j => + List.fold_left( + ~f= + (acc: Segment.t, p: Piece.t) => + switch (p) { + | Secondary(s) when Stdlib.Hashtbl.mem(old_trivia, s.id) => + if (is_comment(p)) { + let rec drop_whitespace = (rev: Segment.t) => + switch (rev) { + | [q, ...rest] when Piece.is_whitespace(q) => + drop_whitespace(rest) + | _ => rev + }; + drop_whitespace(acc); + } else { + [ + Piece.Secondary({ + ...s, + id: Id.mk(), + }), + ...acc, + ]; + } + | _ => [p, ...acc] + }, + ~init=[], + new_.gaps[j], + ) + |> List.rev; + let gap = j => { + let printed = printed(j); + /* The tokens deleted right after the token at j - 1. */ + let deleted = + switch (old_of(j - 1)) { + | Some(x) => + let rec from = i => + i < n_old && Option.is_none(new_of(i)) + ? [i, ...from(i + 1)] : []; + from(x + 1); + | None => [] + }; + let kept = Option.value(~default=printed, old_gap_at[j]); + /* Text replaced by new tokens leaves its first gap before them. A + * deletion between two surviving tokens leaves one of the gaps + * around it: the one with more line breaks, so that the lines on + * either side of a deleted step stay where they were. */ + let (before, base, after) = + switch (deleted) { + | [first, ...inside] when Option.is_none(old_of(j)) => ( + [], + old.gaps[first], + comments_of(inside), + ) + | [first, ...inside] + when + Option.equal( + Int.equal, + old_of(j), + Some(first + List.length(deleted)), + ) + && breaks(old.gaps[first]) > breaks(kept) => ( + [], + old.gaps[first], + comments_of(inside) @ through_last_comment(kept), + ) + | _ => (comments_of(deleted), kept, []) + }; + let base = + switch (base) { + /* Two tokens that were never next to each other could fuse. */ + | [] when !List.is_empty(printed) && !unchanged(j) => printed + /* A block whose contents changed takes the new line breaks at its + * edges, as a one-line proof does when it gets a second step. */ + | _ + when + at_changed_edge[j] && breaks(base) == 0 && breaks(printed) > 0 => + through_last_comment(base) @ snd(Segment.split_space_run(printed)) + | _ => base + }; + let before = line_ends[j] @ before; + let space = Indentation.make_indent_spaces(1); + let before = + switch (before, base) { + | ([], _) => [] + | (_, [p, ..._]) when Piece.is_whitespace(p) => before + | _ => before @ space + }; + before @ base @ (List.is_empty(after) ? [] : after @ space); + }; + let gaps = Array.init(n_new + 1, ~f=gap); + let next = ref(0); + let take_gap = () => gaps[next^]; + let rec level = (seg: Segment.t): Segment.t => { + let pieces = + seg + |> List.filter(~f=p => !Piece.is_secondary(p)) + |> List.concat_map(~f=p => { + let g = take_gap(); + g @ [piece(p)]; + }); + pieces @ take_gap(); + } + and piece = (p: Piece.t): Piece.t => + switch (p) { + | Tile(t) => + incr(next); + let children = + List.map( + ~f= + child => { + let child = level(child); + incr(next); + child; + }, + t.children, + ); + Tile({ + ...t, + children, + }); + | Grout(_) + | Secondary(_) + | Projector(_) => + incr(next); + p; + }; + let merged = level(after); + /* An old line keeps its indentation, moved by as much as its depth in + * the program changed; a new one gets the indentation of its depth. */ + let old_levels = Indentation.level_map(before); + let new_levels = Indentation.level_map(merged); + let reindent = (seg: Segment.t): Segment.t => { + let rec go = (seg: Segment.t) => + switch (seg) { + | [lb, ...rest] when Piece.is_linebreak(lb) => + let (spaces, rest) = Segment.split_space_run(rest); + let id = Piece.id(lb); + let width = + switch ( + Id.Map.find_opt(id, old_levels), + Id.Map.find_opt(id, new_levels), + ) { + | (Some(was), Some(is)) => + max(0, List.length(spaces) + is - was) + | (None, Some(is)) => is + | (_, None) => List.length(spaces) + }; + let spaces = + List.length(spaces) == width + ? spaces : Indentation.make_indent_spaces(width); + [lb, ...spaces] @ go(rest); + | [p, ...rest] => [p, ...go(rest)] + | [] => [] + }; + go(seg); + }; + Segment.map_deep(reindent, merged); + }; +}; + +let apply_patch = (zipper: Zipper.t, patch: patch): Zipper.t => { + let root = MakeTerm.from_zip_for_sem(zipper, ~root=Exp).term; + /* A proof's replacement is written in as it is serialized, and with + * `reflow` the theorem's whole proof is then laid out. Either way, + * `Keep.text` gives the result back the user's text wherever the edit + * didn't change it. */ + let replace_proof = (~reflow, ~target_id, replacement) => + switch (Rewrite.proof_in_exp(~target_id, replacement, root)) { + | Some((old, new_root)) => + let theorem = + Rewrite.theorem_around( + ~proof_id=Proof.rep_id(replacement), + new_root, + ); + /* A replacement of several pieces can't be spliced in beside the + * old node's siblings, but its theorem's whole proof can take the + * place of the old one. */ + let whole_proofs = + switch (Rewrite.theorem_around(~proof_id=target_id, root), theorem) { + | (Some((_, before)), Some((_, after))) => [(before, after)] + | _ => [] + }; + CaretPreserving.transform( + zipper, + seg => { + let spliced = + List.find_map( + ~f= + ((before, after)) => + Splice.local( + ~old_node=Proof(before), + ~replacement=Proof(after), + ~reflow=false, + seg, + ), + [(old, replacement), ...whole_proofs], + ); + let edited = + switch (spliced) { + | Some(edited) => edited + | None => Splice.whole_program(~reflow, new_root) + }; + let edited = + switch (theorem) { + | Some((theorem_id, _)) when reflow => + Reflow.proof(~theorem_id, edited) + | _ => edited + }; + Keep.text(~before=seg, ~after=edited); + }, + ); + | None => zipper + }; + switch (patch) { + | ExpPatch({target_id, replacement, reflow}) => + switch (Rewrite.exp(~target_id, replacement, root)) { + | Some((old, new_root)) => + CaretPreserving.transform( + zipper, + seg => { + let edited = + switch ( + Splice.local( + ~old_node=Exp(old), + ~replacement=Exp(replacement), + ~reflow, + seg, + ) + ) { + | Some(edited) => edited + | None => Splice.whole_program(~reflow, new_root) + }; + Keep.text(~before=seg, ~after=edited); + }, + ) + | None => zipper + } + | ProofPatch({target_id, replacement, reflow}) => + replace_proof(~reflow, ~target_id, replacement) + | ProofRemovePatch({target_id}) => + let (target_id, replacement) = + Rewrite.step_removal( + ~target_id, + Rewrite.seq_parent_in_exp(~target_id, root), + ); + replace_proof(~reflow=true, ~target_id, replacement); + }; +}; diff --git a/src/haz3lcore/ProblemCollection.re b/src/haz3lcore/ProblemCollection.re index 278e2567ca..99b40b5dad 100644 --- a/src/haz3lcore/ProblemCollection.re +++ b/src/haz3lcore/ProblemCollection.re @@ -9,6 +9,7 @@ type problem_category = | Syntax | Hole | Static + | Runtime | Warning | Projector; @@ -33,6 +34,7 @@ type problem_context = { hole_ids: list(Grout.t), concave_holes: list(Grout.t), static_error_ids: list((Id.t, Info.t)), + runtime_error_ids: list((Id.t, Info.t)), warning_ids: list((Id.t, Info.t)), projector_errors: list((Id.t, ProjectorKind.t, ProjectorBase.error)), segment: Segment.t, @@ -102,21 +104,33 @@ let make_problem_context = own term so problems don't leak across groups. */ let id_in_this_editor = id => Option.is_some(TermData.root_piece(id, syntax.term_data)); - /* Partition error_ids into syntax and static in a single pass */ - let (syntax_error_ids, static_error_ids) = + /* Runtime problems are info entries carrying a DynamicError mark + (attached by statics to the expression inside a DynamicErrorHole). */ + let is_runtime_error = (ci: Info.t): bool => + List.exists( + ~f= + fun + | Mark.DynamicError(_) => true + | _ => false, + Info.marks_of(ci), + ); + /* Partition error_ids into runtime, syntax, and static in a single pass */ + let (runtime_error_ids, syntax_error_ids, static_error_ids) = List.fold_right( ~f= - (id, (syn, stat)) => + (id, (rt, syn, stat)) => switch (Statics.Map.lookup(id, info_map)) { | Some(ci) when Info.is_error(ci) && id_in_this_editor(id) => - if (Info.is_syntax_error(ci)) { - ([(id, ci), ...syn], stat); + if (is_runtime_error(ci)) { + ([(id, ci), ...rt], syn, stat); + } else if (Info.is_syntax_error(ci)) { + (rt, [(id, ci), ...syn], stat); } else { - (syn, [(id, ci), ...stat]); + (rt, syn, [(id, ci), ...stat]); } - | _ => (syn, stat) + | _ => (rt, syn, stat) }, - ~init=([], []), + ~init=([], [], []), statics.error_ids, ); /* Collect warning ids with their info */ @@ -156,6 +170,7 @@ let make_problem_context = hole_ids, concave_holes, static_error_ids, + runtime_error_ids, warning_ids, projector_errors, segment: syntax.segment, @@ -236,6 +251,16 @@ let collect_category = source: FromInfo(ci), } ) + | Runtime => + ctx.runtime_error_ids + |> Stdlib.List.to_seq + |> Stdlib.Seq.map(((id, ci)) => + { + id, + category: Runtime, + source: FromInfo(ci), + } + ) | Warning => ctx.warning_ids |> Stdlib.List.to_seq @@ -261,7 +286,7 @@ let collect_category = /* ---------- Convenience: all problems ---------- */ let collect_all_problems = (ctx: problem_context): list(problem) => { - [Syntax, Hole, Static, Warning, Projector] + [Syntax, Hole, Static, Runtime, Warning, Projector] |> List.concat_map(~f=cat => collect_category(ctx, cat) |> Stdlib.List.of_seq ); diff --git a/src/haz3lcore/TyDi/ErrorPrint.re b/src/haz3lcore/TyDi/ErrorPrint.re index f5e03a1e36..82341c3a3e 100644 --- a/src/haz3lcore/TyDi/ErrorPrint.re +++ b/src/haz3lcore/TyDi/ErrorPrint.re @@ -38,6 +38,7 @@ let core_mark_string = (ctx: Ctx.t, ana: Typ.t, m: Mark.t): string => { Print.typ(syn), ); switch (m) { + | DynamicError(err) => InvalidOperationError.err_msg(err) | BadLabel(_) | InvalidLabel(_, _) => "Invalid label" | DuplicateLabel(_, _) => "Duplicate label" @@ -46,9 +47,9 @@ let core_mark_string = (ctx: Ctx.t, ana: Typ.t, m: Mark.t): string => { | UnexpectedLabelSort(_) => "Unexpected label sort" | BadToken(token) => prn("\"%s\" isn't a valid token", token) | IsMulti => "Broken expression" + | FreeConstructor(_name) => prn("Constructor is not defined") | CompareFun(ty) => prn("values of type %s cannot be compared", Print.typ(ty)) - | FreeConstructor(_name) => prn("Constructor is not defined") | ExpectationMismatch({ana, syn}) => expectation(ana, syn) | NoMeet(PolyEq, tys) | NoMeet(_, tys) when ana.term == Unknown(SynSwitch) => @@ -92,7 +93,10 @@ let drv_error: DrvInfo.error => string = let exp_mark_to_string = (ctx: Ctx.t, ana: Typ.t, m: Mark.t): string => { let common_from_core = () => core_mark_string(ctx, ana, m); switch (m) { + | DynamicError(_) => common_from_core() | Free(name) => "Variable " ++ name ++ " is not bound" + | FreeHypothesis(name) => "Hypothesis " ++ name ++ " is not in scope" + | AxiomSlotNotHypothesis(_) => "Axiom slot must reference a hypothesis by name" | InexhaustiveMatch(_) => "Match is not exhaustive" | IsDeferral(InAp) => "(internal)" | IsDeferral(_) => "Unused deferral" @@ -265,6 +269,7 @@ let term_string_of: Info.t => string = | InfoMod({user_term, _}) => Print.term(Mod(user_term)) | InfoSig({user_term, _}) => Print.term(Sig(user_term)) | InfoMPat({user_term, _}) => Print.term(MPat(user_term)) + | InfoProof({user_term, _}) => Print.term(Proof(user_term)) | Secondary(_) => failwith("ChatLSP: term_string_of: Secondary"); let all = (info_map: Statics.Map.t): list(string) => { diff --git a/src/haz3lcore/derived/CachedStatics.re b/src/haz3lcore/derived/CachedStatics.re index dafd1fc48c..ff423f6ddb 100644 --- a/src/haz3lcore/derived/CachedStatics.re +++ b/src/haz3lcore/derived/CachedStatics.re @@ -112,7 +112,14 @@ let init_from_term = ctx, ); let (info_map, elaborated) = - Statics.mk(~ana?, ~probe_ids, settings, ctx_init, term); + Statics.mk( + ~ana?, + ~probe_ids, + ~in_theorem=is_dynamic_term, + settings, + ctx_init, + term, + ); let error_ids = Statics.Map.error_ids(info_map); let warning_ids = Statics.Map.warning_ids(info_map); let elaborated = diff --git a/src/haz3lcore/derived/CanonicalCompletion.re b/src/haz3lcore/derived/CanonicalCompletion.re index 25b6b648e0..50abf78d27 100644 --- a/src/haz3lcore/derived/CanonicalCompletion.re +++ b/src/haz3lcore/derived/CanonicalCompletion.re @@ -2479,7 +2479,7 @@ let derive_insertions = List.iter( ~f= (p: Piece.t) => { - Hashtbl.replace(orig_ids, Piece.id(p), ()); + Stdlib.Hashtbl.replace(orig_ids, Piece.id(p), ()); switch (p) { | Tile(t) => List.iter(~f=collect, t.children) | _ => () @@ -2491,7 +2491,7 @@ let derive_insertions = let rec_of = (tid: Id.t) => List.find(~f=(r: shard_record) => Id.equal(r.tile_id, tid), records); let originals_of = (t: Tile.t): list(int) => - Hashtbl.mem(orig_ids, t.id) + Stdlib.Hashtbl.mem(orig_ids, t.id) ? switch (rec_of(t.id)) { | Some(r) => r.original_shards | None => t.shards @@ -2528,7 +2528,7 @@ let derive_insertions = @ weave(rest, chrest); }; weave(t.shards, t.children); - | p => [(LPiece(p), Hashtbl.mem(orig_ids, Piece.id(p)))] + | p => [(LPiece(p), Stdlib.Hashtbl.mem(orig_ids, Piece.id(p)))] }, sg, ); @@ -2690,6 +2690,65 @@ let derive_insertions = }); }; +/* `completed` with each hole that completing `input` added inside a tile + given an id derived from that tile, the child it is in and its place + there. The final regrout mints a hole's id afresh on every run, so + without this an edit elsewhere in the tile, such as to a theorem's + statement, gives the hole a new id, and whatever is keyed by it, such + as the stepper rows of the theorem's unwritten proof, loses track of + it. */ +let stable_hole_ids = (~input: Segment.t, completed: Segment.t): Segment.t => { + let input_ids = Stdlib.Hashtbl.create(256); + List.iter( + ~f=id => Stdlib.Hashtbl.replace(input_ids, id, ()), + Segment.ids(input), + ); + let rec in_tile = (t: Tile.t): Tile.t => { + ...t, + children: + List.mapi( + ~f= + (k, child) => { + let added = ref(0); + List.map( + ~f= + (p: Piece.t) => + switch (p) { + | Grout(g) when !Stdlib.Hashtbl.mem(input_ids, g.id) => + let id = + Id.derive( + ~salt=sprintf("hole %d %d", k, added^), + t.id, + ); + added := added^ + 1; + Piece.Grout({ + ...g, + id, + }); + | Tile(t) => Piece.Tile(in_tile(t)) + | Grout(_) + | Secondary(_) + | Projector(_) => p + }, + child, + ); + }, + t.children, + ), + }; + List.map( + ~f= + (p: Piece.t) => + switch (p) { + | Tile(t) => Piece.Tile(in_tile(t)) + | Grout(_) + | Secondary(_) + | Projector(_) => p + }, + completed, + ); +}; + /* === Integration Points === */ let for_make_term = (seg: Segment.t): (Segment.t, list(shard_record)) => { diff --git a/src/haz3lcore/derived/Measured.re b/src/haz3lcore/derived/Measured.re index ed91479488..cd167c327b 100644 --- a/src/haz3lcore/derived/Measured.re +++ b/src/haz3lcore/derived/Measured.re @@ -180,6 +180,32 @@ let find_p = (~msg="", p: Piece.t, map): measurement => | _ => failwith("find_p: " ++ msg ++ "id: " ++ Id.to_string(p |> Piece.id)) }; +/* find_p, for a piece that may not be laid out in `map`. Raising and + * catching is slow in the browser, and callers like the stepper's + * decorations ask for many such pieces on every render. */ +let find_p_opt = (p: Piece.t, map): option(measurement) => + switch (p) { + | Secondary(w) => Id.Map.find_opt(w.id, map.secondary) + | Grout(g) => Id.Map.find_opt(g.id, map.grout) + | Projector(p) => Id.Map.find_opt(p.id, map.projectors) + | Tile(t) => + switch (Id.Map.find_opt(t.id, map.tiles)) { + | Some(shards) => + switch ( + List.Assoc.find(shards, Tile.l_shard(t), ~equal=Int.equal), + List.Assoc.find(shards, Tile.r_shard(t), ~equal=Int.equal), + ) { + | (Some(first), Some(last)) => + Some({ + origin: first.origin, + last: last.last, + }) + | _ => None + } + | None => None + } + }; + let find_by_id = (id: Id.t, map: t): option(measurement) => { switch (Id.Map.find_opt(id, map.secondary)) { | Some(m) => Some(m) diff --git a/src/haz3lcore/derived/TermData.re b/src/haz3lcore/derived/TermData.re index 1ba455e28b..324ca3636b 100644 --- a/src/haz3lcore/derived/TermData.re +++ b/src/haz3lcore/derived/TermData.re @@ -46,9 +46,9 @@ let extremes_opt = (id: Id.t, data: t) => switch (Id.Map.find_opt(id, data)) { | Some({skel, base_seg, _}) => let (l, r) = Skel.range(skel); - switch (List.nth_exn(base_seg, l), List.nth_exn(base_seg, r)) { - | exception _ => None - | (l, r) => Some((l, r)) + switch (List.nth(base_seg, l), List.nth(base_seg, r)) { + | (Some(l), Some(r)) => Some((l, r)) + | _ => None }; | None => None }; @@ -69,11 +69,11 @@ let extreme_measures = (id: Id.t, data: t, measured: Measured.t) => switch (extremes_opt(id, data)) { | Some((l, r)) => switch ( - Measured.find_p(l, measured).origin, - Measured.find_p(r, measured).last, + Measured.find_p_opt(l, measured), + Measured.find_p_opt(r, measured), ) { - | exception _ => None - | (l, r) => Some((l, r)) + | (Some(l), Some(r)) => Some((l.origin, r.last)) + | _ => None } | None => None }; diff --git a/src/haz3lcore/lang/Form.re b/src/haz3lcore/lang/Form.re index cc57713955..e63b6f5a89 100644 --- a/src/haz3lcore/lang/Form.re +++ b/src/haz3lcore/lang/Form.re @@ -100,6 +100,7 @@ let rows_of: family => list(row) = mk_infix(Exp, P.semi), mk_infix(Mod, P.mod_seq), mk_infix(Sig, P.mod_seq), + mk_infix(Proof, P.semi), ] | Plus => [ mk_infix(Exp, P.plus), @@ -200,6 +201,7 @@ let rows_of: family => list(row) = mk_parens(Drv(Exp)), mk_parens(Drv(Pat)), mk_parens(Drv(Typ)), + mk_parens(Proof), ] | ApEmpty => [ mk_post_c(LT, P.ap, Exp, []), @@ -216,8 +218,6 @@ let rows_of: family => list(row) = | ApExpTyp => [mk_post_c(L, P.ap, Exp, [Typ])] | Case => [mk_op_c(L, Exp, [Rul]), mk_op_c(L, Drv(Exp), [Drv(Exp)])] | Test => [mk_op_c(L, Exp, [Exp])] - | ProofOf => [mk_op_c(L, Typ, [Exp])] - | ProofObject => [mk_op_c(L, Exp, [Exp])] | HintedTest => [mk_op_c(L, Exp, [Exp, Exp])] | Fun => [ mk_pre_c(L, P.fun_, Exp, [Pat]), @@ -246,6 +246,7 @@ let rows_of: family => list(row) = Drv(Exp), ), ), + mk(L, Mold.mk_bin'(P.rule_sep, PRul, Exp, [Pat], Proof)), ] | Pipeline => [mk_infix(Exp, P.eqs)] // in OCaml, pipeline precedence is in same class as '=', '<', etc. | FilterHide => [mk_pre_c(L, P.let_, Exp, [Exp])] @@ -284,7 +285,7 @@ let rows_of: family => list(row) = | Valid => [mk_op_c(L, Drv(Exp), [Drv(Typ)])] | Syn => [mk(L, Mold.mk_bin'(P.ann, Drv(Exp), Drv(Exp), [], Drv(Typ)))] | And => [mk_infix(Drv(Exp), P.and_)] - | Impl => [mk_infix(Drv(Exp), P.impl)] + | Impl => [mk_infix(Drv(Exp), P.impl), mk_infix(Exp, P.impl)] | If => [ mk_pre_c(L, P.if_, Drv(Exp), [Drv(Exp), Drv(Exp)]), mk_pre_c(L, P.if_, Exp, [Exp, Exp]), @@ -293,7 +294,7 @@ let rows_of: family => list(row) = mk_pre_c(L, P.let_, Drv(Exp), [Drv(Pat), Drv(Exp)]), mk_pre_c(L, P.let_, Exp, [Pat, Exp]), ] - | Theorem => [mk_pre_c(L, P.let_, Exp, [Pat, Exp])] + | Theorem => [mk_pre_c(L, P.let_, Exp, [Pat, Exp, Proof])] | TypeAlias => [mk_pre_c(L, P.let_, Exp, [TPat, Typ])] | ModBody => [mk_op_c(LT, Exp, [Mod]), mk_op_c(LT, Typ, [Sig])] | ModLet => [mk_pre_c'(L, P.let_, Mod, [Pat], Exp)] @@ -303,7 +304,35 @@ let rows_of: family => list(row) = ] | ModuleExp => [mk_pre_c'(L, P.let_, Exp, [MPat, Exp], Exp)] | ModuleMod => [mk_pre_c'(L, P.let_, Mod, [MPat], Exp)] - | SigLet => [mk_pre_c'(L, P.let_, Sig, [], Pat)]; + | SigLet => [mk_pre_c'(L, P.let_, Sig, [], Pat)] + | ProofForall => [mk_pre_c(L, P.fun_, Proof, [Pat])] + | ProofFunext => [mk_pre_c(L, P.fun_, Proof, [Pat])] + | ProofAssume => [mk_pre_c(L, P.fun_, Proof, [Exp])] + | ProofGeneralize => [mk_pre_c(L, P.fun_, Proof, [Exp])] + | ProofRevert => [mk_pre_c(L, P.fun_, Proof, [Exp])] + | ProofAxiom => [mk_op_c(L, Proof, [Exp])] + | ProofRevertWith => [mk_pre_c(L, P.fun_, Proof, [Exp, Exp, Exp])] + | ProofAxiomWith => [mk_op_c(L, Proof, [Exp, Exp, Exp])] + /* `rewrite <- h end` applies `h` right to left. The arrow is a prefix + over the whole fact in the rewrite's slot, since the slot directly + follows `rewrite`; MakeTerm reads it back as the step's direction. + Outside a rewrite it is an error. */ + | RewriteBack => [mk_prefix(Exp, P.fun_)] + | ProofAlgebrite => [mk_op_c(L, Proof, [Exp])] + | ProofEval => [mk_op_c(L, Proof, [])] + | ProofCases + | ProofInduction => [mk_op_c(L, Proof, [PRul])] + /* `have proof => ` */ + | ProofHave => [mk_pre_c(L, P.fun_, Proof, [Exp, Proof])] + /* The named forms put the fact's name first, as `alias` does: + `have = proof ...`, `assume = => ...`. */ + | ProofHaveNamed => [mk_pre_c(L, P.fun_, Proof, [Pat, Exp, Proof])] + | ProofAssumeNamed => [mk_pre_c(L, P.fun_, Proof, [Pat, Exp])] + /* `alias = => ` */ + | ProofAlias => [mk_pre_c(L, P.fun_, Proof, [Pat, Exp])] + | ProofFocus => [mk_op_c(L, Proof, [Exp, Proof])] + /* `from at do end`, the nth occurrence. */ + | ProofFocusAt => [mk_op_c(L, Proof, [Exp, Exp, Proof])]; /* Join a family's rows with its label (FormId.label_of_family, the * label's single home). Failfast: a mold whose child count disagrees @@ -383,8 +412,13 @@ let is_annoying_delim = t => * delimiter */ let infix_delimiter_ops_prefixes: list(Token.t) = forms - |> List.filter_map(~f=((_, form: def)) => { + |> List.filter_map(~f=((fam, form: def)) => { switch ((form.mold.nibs |> snd).shape) { + /* The prover's delimiters (`at`, `do`, `with`, `proof`) would + make common short variables (`a`, `d`, `w`, `p`) mold as + operators in broken buffers outside proofs. */ + | _ when form.mold.out == Proof || form.mold.out == PRul => None + | _ when fam == Theorem => None /* Only NON-leading delimiters contribute prefixes. A non-leading delimiter (the `in` of a let) is typed in infix position, where the backup infix mold smooths entry. A @@ -492,13 +526,16 @@ let get_atomic_form: atomic_form => (Token.t => bool, list(Mold.t)) = ) | ExplicitHole => ( Token.is_explicit_hole, - [op(Exp), op(Pat), op(Typ), op(TPat), op(Drv(Typ))], + [op(Exp), op(Pat), op(Typ), op(TPat), op(Drv(Typ)), op(Proof)], ) | ImplicitHoleMarker => ( Token.is_implicit_hole_marker, - [op(Exp), op(Pat), op(Typ), op(TPat), op(Drv(Typ))], + [op(Exp), op(Pat), op(Typ), op(TPat), op(Drv(Typ)), op(Proof)], + ) + | LLMHole => ( + Token.is_llm_hole, + [op(Exp), op(Pat), op(Typ), op(TPat), op(Proof)], ) - | LLMHole => (Token.is_llm_hole, [op(Exp), op(Pat), op(Typ), op(TPat)]) | Wild => (Token.is_wild, [op(Pat), op(Drv(Exp))]) | String => (Token.is_string, [op(Exp), op(Pat)]) | QuotedLabel => (Token.is_quoted_label, [op(Exp), op(Pat), op(Typ)]) @@ -596,8 +633,8 @@ module Expansion = { /* Get expansion for a token in a specific sort context. Returns monotile if no expansion exists for this sort. - Exception: Rul context is permissive - falls back to any expansion. - This is because Rul (case rules) contains Exp/Pat operands but has no + Exception: Rul and PRul contexts are permissive - they fall back to any + expansion, because rules contain operands of other sorts but have no direct forms for things like parens. Other sorts remain strict. */ let get = (sort: Sort.t, t: Token.t): (Label.t, Direction.t) => { let matching = @@ -607,9 +644,8 @@ module Expansion = { | Some((_, _, lbl, dir)) => (lbl, dir) | None => switch (sort) { - | Rul => - /* Rul context: fall back to any expansion since rules contain - Exp/Pat operands but have no direct operand forms. */ + | Rul + | PRul => let any_match = sorted_expansions |> List.find(~f=((tok, _, _, _)) => String.equal(tok, t)); @@ -837,7 +873,7 @@ let classify_label = (sort: Sort.t, label: Label.t): (t, Sort.t) => { * segment (Segment.parenthesize). classify_label can't be used for * this: parenthesization must always produce the Parens form, and at * Drv(Exp)/Drv(Pat) classify_label finds the Ap form first (see - * same_label_rank). Sorts with no registered paren row (Rul, Mod, + * same_label_rank). Sorts with no registered paren row (Rul, PRul, Mod, * Sig, MPat, Any, remaining Drv) do fall back to classify_label: * (Parens, Any) with the op fallback mold. */ let parens_form = (sort: Sort.t): (t, Sort.t) => @@ -849,7 +885,8 @@ let parens_form = (sort: Sort.t): (t, Sort.t) => | Drv(Prop) | Drv(Exp) | Drv(Pat) - | Drv(Typ) => (Compound(Parens), sort) + | Drv(Typ) + | Proof => (Compound(Parens), sort) | _ => classify_label(sort, Token.tuple_lbl) }; diff --git a/src/haz3lcore/lang/MakeTerm.re b/src/haz3lcore/lang/MakeTerm.re index e5c8c51428..975374f2c8 100644 --- a/src/haz3lcore/lang/MakeTerm.re +++ b/src/haz3lcore/lang/MakeTerm.re @@ -203,6 +203,37 @@ let is_drv_rules = ((ts, kids): tiles): option(Aba.t(Drv.Pat.t, Drv.Exp.t)) => { |> OptUtil.sequence; Aba.mk(ps, clauses); }; +let is_proof_rules = ((ts, kids): tiles): option(Aba.t(Pat.t, Proof.t)) => { + open OptUtil.Syntax; + let+ ps = + (ts: list(tile)) + |> List.map( + ~f=fun + | (_, (F(Compound(Rule)), [Pat(p)])) => Some(p) + | _ => None: tile => option(TermBase.pat_t), + ) + |> OptUtil.sequence + /* An empty case body between two rule tiles is grout in a slot whose + nib sorts disagree (Proof before it, Exp after), so it parses as an + Exp hole. Read it as a Proof hole, or a single empty body would turn + the whole split into a MultiHole. */ + and+ bodies = + kids + |> List.map( + ~f=fun + | Proof(body) => Some(body) + | Exp({term: EmptyHole, annotation}) => + Some( + { + term: EmptyHole, + annotation, + }: TermBase.proof_t, + ) + | _ => None: TermBase.any_t => option(TermBase.proof_t), + ) + |> OptUtil.sequence; + Aba.mk(ps, bodies); +}; let ids_of_tiles = (tiles: tiles) => List.map(~f=fst, Aba.get_as(tiles)); let ids = @@ -498,9 +529,11 @@ let rec go_s = (s: Sort.t, skel: Skel.t, seg: Segment.t): Any.t => | Typ => Typ(typ(unsorted(Typ, skel, seg))) | Exp => Exp(exp(unsorted(Exp, skel, seg))) | Rul => Rul(rul(unsorted(Rul, skel, seg))) + | PRul => PRul(prul(unsorted(PRul, skel, seg))) | Mod => Mod(mod_(unsorted(Mod, skel, seg))) /* Phase 1.2: proper module parsing */ | Sig => Sig(sig_(unsorted(Sig, skel, seg))) | MPat => MPat(mpat(unsorted(MPat, skel, seg))) + | Proof => Proof(proof(unsorted(Proof, skel, seg))) | Any => let sort = Segment.sort_of(skel, seg); if (sort == Any) { @@ -872,8 +905,6 @@ and exp_term: unsorted => (Exp.term, list(Id.t)) = { | term => ret(ListLit([term])) } | (F(Compound(Test)), [Exp(test)]) => ret(Test(test)) - | (F(Compound(ProofObject)), [Exp(proof)]) => - ret(ProofObject(proof)) | (F(Compound(HintedTest)), [Exp(hint), Exp(test)]) => ret(HintedTest(test, hint)) | (F(Compound(Case)), [Rul({term, annotation: {ids, _}})]) => @@ -921,6 +952,10 @@ and exp_term: unsorted => (Exp.term, list(Id.t)) = { ret( switch (t) { | (F(Compound(UnaryMinus)), []) => UnOp(Int(Minus), r) + /* Read back by the rewrite step that holds it. */ + | (F(Compound(RewriteBack)), []) => + set_lexeme("<-"); + hole(tm); | (F(Compound(Not)), []) => UnOp(Bool(Not), r) | (F(Compound(Fun)), [Pat(pat)]) => Fun(pat, r, None, None) | (F(Compound(Forall)), [Pat(pat)]) => Forall(pat, r) @@ -929,8 +964,8 @@ and exp_term: unsorted => (Exp.term, list(Id.t)) = { | (F(Compound(Let)), [Pat(pat), Exp(def)]) => Let(pat, def, r) | (F(Compound(ModuleExp)), [MPat(mp), Exp(def)]) => ModuleExp(mp, def, r) - | (F(Compound(Theorem)), [Pat(pat), Exp(thm)]) => - Theorem(pat, thm, r) + | (F(Compound(Theorem)), [Pat(pat), Exp(thm), Proof(pf)]) => + Theorem(pat, thm, pf, r) | (F(Compound(FilterHide)), [Exp(filter)]) => Filter( Filter({ @@ -1072,6 +1107,7 @@ and exp_term: unsorted => (Exp.term, list(Id.t)) = { | F(Compound(FNotEquals)) => BinOp(Float(NotEquals), l, r) | F(Compound(LogicalAnd)) => BinOp(Bool(And), l, r) | F(Compound(LogicalOr)) => BinOp(Bool(Or), l, r) + | F(Compound(Impl)) => BinOp(Bool(Implies), l, r) | F(Compound(Cons)) => Cons(l, r) | F(Compound(CellJoin)) => Seq(l, r) | F(Compound(StringConcat)) => BinOp(String(Concat), l, r) @@ -1416,7 +1452,6 @@ and typ_term: unsorted => (Typ.term, list(Id.t)) = { | (_, (F(Tok(t)), [])) when Token.is_empty_module(t) => Sig([]) | (Some(term), _) => term | (_, (F(Tok("_")), [])) => ExplicitNonlabel - | (_, (F(Compound(ProofOf)), [Exp(exp)])) => ProofOf(exp) | (_, (F(Tok(t)), [])) when Token.is_typ_var(t) => Var(t) | (_, (F(Tok(t)), [])) when Token.is_quoted_label(t) => set_lexeme(t); @@ -1733,6 +1768,168 @@ and mpat_term: unsorted => TermBase.MPat.term = { | (Pre(_) | Post(_) | Bin(_)) as tm => ret(hole(tm)); } +and proof = unsorted => { + let (term, inner_ids) = proof_term(unsorted); + let lexeme = take_lexeme(); + /* Own tile ids first, then absorbed child ids: ExpToSegment's + split arms read them back in this order. */ + let ids = ids(unsorted) @ inner_ids; + return(p => Proof(p), ~lexeme, ids, term); +} +/* Also returns the ids absorbed from a child, as exp_term does: the + split arms absorb their PRul child's `|`/`=>` tile ids, which + nothing else records, so ExpToSegment can re-emit those tiles. */ +and proof_term: unsorted => (Proof.term, list(Id.t)) = { + let ret = (term: Proof.term) => (term, []); + let hole = unsorted => Proof.hole(kids_of_unsorted(unsorted)); + /* `rewrite <- h` parses as an unknown prefix over `h`, a one-kid + MultiHole whose lexeme is the arrow (see Form.RewriteBack). Its tile + id is absorbed, as a split absorbs its rules'. */ + let axiom = (~instantiation=?, equality: Exp.t): (Proof.term, list(Id.t)) => + switch (equality) { + | { + term: MultiHole([Exp(inner)]), + annotation: {lexeme: Some("<-"), ids, _}, + } => + adopted_ids := ids @ adopted_ids^; + ( + AxiomStep({ + equality: inner, + direction: Left, + instantiation, + }), + ids, + ); + | _ => + ret( + AxiomStep({ + equality, + direction: Right, + instantiation, + }), + ) + }; + /* Absorbs the PRul's `|`/`=>` ids, as Case does with Rules. `mk` gets + the PRul's leading term and its cases. */ + let split = (tm, prul: PRul.t, mk) => + switch (prul.term) { + | ProofRules(head, cases) => + adopted_ids := prul.annotation.ids @ adopted_ids^; + (mk(head, cases), prul.annotation.ids); + | Invalid(_) + | MultiHole(_) => ret(hole(tm)) + }; + fun + | Op(tiles) as tm => + switch (tiles) { + | ([(_id, tile)], []) => + switch (tile) { + | (F(Tok(t)), []) when is_hole_label(t) => + set_lexeme(t); + ret(hole(tm)); + | (F(Compound(Parens)), [Proof(body)]) => ret(Parens(body)) + | (F(Compound(Parens)), [kid]) => + /* Cross-sort parens (see the exp case) */ + ret(Parens(IdTagged.mk_internal([Id.mk()], Proof.hole([kid])))) + | (F(Compound(ProofAxiom)), [Exp(equality)]) => axiom(equality) + | ( + F(Compound(ProofAxiomWith)), + [Exp(equality), Exp(var), Exp(inst)], + ) => + axiom(~instantiation=(var, inst), equality) + | (F(Compound(ProofAlgebrite)), [Exp(e)]) => ret(AlgebriteStep(e)) + | (F(Compound(ProofEval)), []) => ret(EvalStep) + | (F(Compound(ProofFocus)), [Exp(selector), Proof(body)]) => + ret( + Focus({ + ordinal: None, + selector, + body, + }), + ) + /* The occurrence keeps its literal's annotation, so it prints back + with its id and whitespace, and the focus absorbs the literal's + tile id. Anything but a positive literal makes the focus a hole. */ + | ( + F(Compound(ProofFocusAt)), + [Exp(selector), Exp(at), Proof(body)], + ) => + let n = + switch (at.term) { + | Atom(Int(n)) => Bigint.to_int(n) + | _ => None + }; + switch (n) { + | Some(n) when n >= 1 => + let ids = at.annotation.ids; + adopted_ids := ids @ adopted_ids^; + ( + Focus({ + ordinal: + Some({ + term: n, + annotation: at.annotation, + }), + selector, + body, + }), + ids, + ); + | _ => ret(hole(tm)) + }; + | (F(Compound(ProofCases)), [PRul(prul)]) => + split(tm, prul, (scrut, cases) => Cases(scrut, cases)) + | (F(Compound(ProofInduction)), [PRul(prul)]) => + split(tm, prul, (scrut, cases) => Induction(scrut, cases)) + | (F(Tok(t)), []) when t != " " && !Token.is_explicit_hole(t) => + ret(Invalid(t)) + | _ => ret(hole(tm)) + } + | _ => ret(hole(tm)) + } + | Pre(tiles, Proof(body)) as tm => + switch (tiles) { + | ([(_id, (F(Compound(ProofForall)), [Pat(p)]))], []) => + ret(Forall(p, body)) + | ([(_id, (F(Compound(ProofFunext)), [Pat(p)]))], []) => + ret(Funext(p, body)) + | ([(_id, (F(Compound(ProofAssume)), [Exp(e)]))], []) => + ret(Assume(e, None, body)) + | ([(_id, (F(Compound(ProofAssumeNamed)), [Pat(x), Exp(e)]))], []) => + ret(Assume(e, Some(x), body)) + | ([(_id, (F(Compound(ProofAlias)), [Pat(x), Exp(e)]))], []) => + ret(Alias(x, e, body)) + | ([(_id, (F(Compound(ProofGeneralize)), [Exp(e)]))], []) => + ret(Generalize(e, body)) + | ([(_id, (F(Compound(ProofRevert)), [Exp(e)]))], []) => + ret(Revert(e, None, body)) + | ( + [(_id, (F(Compound(ProofRevertWith)), [Exp(e), Exp(v), Exp(i)]))], + [], + ) => + ret(Revert(e, Some((v, i)), body)) + | ([(_id, (F(Compound(ProofHave)), [Exp(e), Proof(sub)]))], []) => + ret(Have(e, None, sub, body)) + | ( + [ + ( + _id, + (F(Compound(ProofHaveNamed)), [Pat(x), Exp(e), Proof(sub)]), + ), + ], + [], + ) => + ret(Have(e, Some(x), sub, body)) + | _ => ret(hole(tm)) + } + | Bin(Proof(p1), tiles, Proof(p2)) as tm => + switch (tiles) { + | ([(_id, (F(Compound(CellJoin)), []))], []) => ret(Seq(p1, p2)) + | _ => ret(hole(tm)) + } + | (Pre(_) | Post(_) | Bin(_)) as tm => ret(hole(tm)); +} + and rul = (unsorted): Rul.t => { let e = exp(unsorted); let mk_rules = (scrut: Exp.t, rules, ids): Rul.t => { @@ -1763,6 +1960,34 @@ and rul = (unsorted): Rul.t => { }; } +/* The child of `cases` and `induction`: ` | p => | ...`, or a bare + scrutinee with no cases. Any other shape is a MultiHole, so partial + edits stay reachable. */ +and prul = (unsorted): PRul.t => { + let wrap = (pr: PRul.t): Any.t => PRul(pr); + let mk_proof_rules = (scrut: Exp.t, cases) => + return(wrap, ids(unsorted), ProofRules(scrut, cases)); + let mk_multihole = () => + return( + wrap, + ids(unsorted), + MultiHole(kids_of_unsorted(unsorted)): PRul.term, + ); + switch (unsorted) { + | Bin(Exp(scrut), tiles, Proof(last_body)) => + switch (is_proof_rules(tiles)) { + | Some((ps, leading_bodies)) => + mk_proof_rules(scrut, List.zip_exn(ps, leading_bodies @ [last_body])) + | None => mk_multihole() + } + | Op(_) + | Pre(_, Exp(_)) + | Post(Exp(_), _) + | Bin(Exp(_), _, Exp(_)) => mk_proof_rules(exp(unsorted), []) + | _ => mk_multihole() + }; +} + and unsorted = (sort: Sort.t, skel: Skel.t, seg: Segment.t): unsorted => { /* Remove projectors. We do this here as opposed to removing * them in an external call to save a whole-syntax pass. */ @@ -1819,7 +2044,14 @@ and unsorted = (sort: Sort.t, skel: Skel.t, seg: Segment.t): unsorted => { | Tile({shards, children, _} as t) => Aba.aba_triples(Aba.mk(shards, children)) |> List.map(~f=((l, kid, r)) => { - let s = l + 1 == r ? List.nth_exn(Tile.mold(t).in_, l) : Sort.Any; + /* A tile stranded at a sort where its form has no row keeps + its shards but gets the Any-fallback mold, with no child + sorts, so a missing child sort is Any too. */ + let s = + l + 1 == r + ? List.nth(Tile.mold(t).in_, l) + |> Option.value(~default=Sort.Any) + : Sort.Any; go_s(s, Segment.skel(~sort=s, kid), kid); }) }; @@ -1976,12 +2208,14 @@ let for_projection = switch (tpat(unsorted)) { | _ => Some(TPat(tpat(unsorted))) } - /* Rul case below prevents returning pseudo-terms + /* Rul/PRul cases below prevent returning pseudo-terms * consisting of case scrutinee + rule(s) */ - | Rul => None + | Rul + | PRul => None | Mod => Some(Mod(mod_(unsorted))) | Sig => Some(Sig(sig_(unsorted))) | MPat => Some(MPat(mpat(unsorted))) + | Proof => Some(Proof(proof(unsorted))) /* Default unresolved sort to Exp, matching go_s above. * Reject bare Tuple(_) for the same reason as the Exp * branch: at top level it isn't well-structured in @@ -2018,11 +2252,13 @@ let from_zip_for_sem_with_completion = (z: Zipper.t, ~root: Sort.t) => { let seg = semantic_source(z); let result = CanonicalCompletion.complete_segment_deep(~sort=Sort.Exp, seg); let masks = CanonicalCompletion.masks_of_records(result.shard_records); + let completed = + CanonicalCompletion.stable_hole_ids(~input=seg, result.completed_seg); ( - go_impl(~masks, result.completed_seg), + go_impl(~masks, completed), { source: seg, - completed: result.completed_seg, + completed, }, ); }; diff --git a/src/haz3lcore/lang/Precedence.re b/src/haz3lcore/lang/Precedence.re index 9aa06b8340..e4ae195c2e 100644 --- a/src/haz3lcore/lang/Precedence.re +++ b/src/haz3lcore/lang/Precedence.re @@ -75,11 +75,15 @@ let and_ = 32 |> right_associative; // _____ || false let or_ = 33 |> right_associative; -// Derivation Mode Only +// Material implication `==>` (also used in Derivation Mode) // A /\ B \/ C ==> D // ((A /\ B) \/ C) ==> D -let impl = 34; +// a || b ==> c || d parses as (a || b) ==> (c || d); +// a ==> b ==> c parses as a ==> (b ==> c) +let impl = 34 |> right_associative; // false || _____ +/* Shares its level with `impl`. `impl`'s right-associativity doesn't + affect grout: Skel's tie-break only tells Some(Left) from the rest. */ let concave_grout = 34; // ===== SEMICOLON (tightest structural form) ===== @@ -163,6 +167,7 @@ let of_bin_op: Language.Operators.op_bin => t = switch (op) { | And => and_ | Or => or_ + | Implies => impl } | String(op) => switch (op) { diff --git a/src/haz3lcore/pretty/ExpToSegment.re b/src/haz3lcore/pretty/ExpToSegment.re index 15f9421f81..c13d801de3 100644 --- a/src/haz3lcore/pretty/ExpToSegment.re +++ b/src/haz3lcore/pretty/ExpToSegment.re @@ -267,7 +267,6 @@ let rec external_precedence = (exp: Exp.t): Precedence.t => { | ListLit(_) | Test(_) | HintedTest(_) - | ProofObject(_) | Match(_) => Precedence.max | Asc(_) => Precedence.asc @@ -351,7 +350,6 @@ let external_precedence_typ = (tp: Typ.t) => // Same goes for forms which are already surrounded | Parens(_) | Projector(_) - | ProofOf(_) | List(_) => Precedence.max // Other forms @@ -373,9 +371,55 @@ let external_precedence_typ = (tp: Typ.t) => | Sig(_) => Precedence.min }; +/* Only the wrapping forms, whose body extends to the end of the enclosing + proof, and `;` can be broken by a following tile. Every other proof is a + leaf or closed by `end`. */ +let external_precedence_proof = (p: Proof.t) => + switch (Annotated.term_of(p)) { + | EmptyHole + | Invalid(_) + | Parens(_) + | AxiomStep(_) + | AlgebriteStep(_) + | EvalStep + | Focus(_) + | Cases(_, _) + | Induction(_, _) => Precedence.max + | Seq(_, _) => Precedence.semi + | Forall(_, _) + | Funext(_, _) + | Assume(_, _, _) + | Alias(_, _, _) + | Generalize(_, _) + | Revert(_, _, _) + | Have(_, _, _, _) => Precedence.fun_ + /* Prints as a single `?` (see proof_to_pretty) */ + | MultiHole(_) => Precedence.max + }; + /* Conditional parenthesization helpers. With Defensive: add parens based on precedence comparison (original behavior). - With Structural: never add parens here; only explicit Parens nodes in the term are emitted. */ + With Structural: never add parens here; only explicit Parens nodes in the term are emitted. + A term that is already Parens is never wrapped again, even at + Precedence.max, or every parse/print round trip would add a layer. */ +let is_parens = (exp: Exp.t): bool => + switch (Exp.term_of(exp)) { + | Parens(_) => true + | _ => false + }; + +let is_parens_pat = (pat: Pat.t): bool => + switch (Pat.term_of(pat)) { + | Parens(_) => true + | _ => false + }; + +let is_parens_typ = (typ: Typ.t): bool => + switch (Typ.term_of(typ)) { + | Parens(_) => true + | _ => false + }; + let paren_at = ( ~parenthesization: Settings.parenthesization, @@ -386,7 +430,7 @@ let paren_at = switch (parenthesization) { | Structural => exp | Defensive => - external_precedence(exp) >= internal_precedence + !is_parens(exp) && external_precedence(exp) >= internal_precedence ? Exp.fresh(Parens(exp)) : exp }; @@ -400,7 +444,7 @@ let paren_assoc_at = switch (parenthesization) { | Structural => exp | Defensive => - external_precedence(exp) > internal_precedence + !is_parens(exp) && external_precedence(exp) > internal_precedence ? Exp.fresh(Parens(exp)) : exp }; @@ -414,7 +458,8 @@ let paren_pat_at = switch (parenthesization) { | Structural => pat | Defensive => - external_precedence_pat(pat) >= internal_precedence + !is_parens_pat(pat) + && external_precedence_pat(pat) >= internal_precedence ? Pat.fresh(Parens(pat)) : pat }; @@ -428,7 +473,7 @@ let paren_pat_assoc_at = switch (parenthesization) { | Structural => pat | Defensive => - external_precedence_pat(pat) > internal_precedence + !is_parens_pat(pat) && external_precedence_pat(pat) > internal_precedence ? Pat.fresh(Parens(pat)) : pat }; @@ -442,7 +487,8 @@ let paren_typ_at = switch (parenthesization) { | Structural => typ | Defensive => - external_precedence_typ(typ) >= internal_precedence + !is_parens_typ(typ) + && external_precedence_typ(typ) >= internal_precedence ? Typ.fresh(Parens(typ)) : typ }; @@ -456,7 +502,7 @@ let paren_typ_assoc_at = switch (parenthesization) { | Structural => typ | Defensive => - external_precedence_typ(typ) > internal_precedence + !is_parens_typ(typ) && external_precedence_typ(typ) > internal_precedence ? Typ.fresh(Parens(typ)) : typ }; @@ -596,15 +642,21 @@ let rec parenthesize = parenthesize(e2) |> paren_assoc_at(Precedence.let_), ) |> rewrap - | Theorem(p, thm, e) => + | Theorem(p, thm, pf, e) => Theorem( parenthesize_pat(p) |> paren_pat_at(Precedence.min), parenthesize(thm) |> paren_at(Precedence.min), + /* Steps the stepper inserts are built, not parsed, so their + expressions have no Parens nodes and need defensive ones too. */ + parenthesize_proof( + ~parenthesization, + ~show_ascriptions, + ~show_filters, + pf, + ), parenthesize(e) |> paren_assoc_at(Precedence.let_), ) |> rewrap - | ProofObject(t) => - ProofObject(parenthesize(t) |> paren_at(Precedence.min)) |> rewrap | FixF(p, e, c) => FixF( parenthesize_pat(p) |> paren_pat_at(Precedence.min), @@ -612,16 +664,19 @@ let rec parenthesize = c // TODO: Parenthesize through closure ) |> rewrap + /* A type alone in a delimited slot is bare, whatever its precedence: + nothing there can capture it, and `type t = (+A + B) in` doesn't + define its constructors. */ | TyAlias(tp, t, e) => TyAlias( tp, - parenthesize_typ(t) |> paren_typ_at(Precedence.min), + parenthesize_typ(t), parenthesize(e) |> paren_assoc_at(Precedence.let_), ) |> rewrap | Use(t, e) => Use( - parenthesize_typ(t) |> paren_typ_at(Precedence.min), + parenthesize_typ(t), parenthesize(e) |> paren_assoc_at(Precedence.let_), ) |> rewrap @@ -642,7 +697,7 @@ let rec parenthesize = | TypAp(e, tp) => TypAp( parenthesize(e) |> paren_assoc_at(Precedence.ap), - parenthesize_typ(tp) |> paren_typ_at(Precedence.min), + parenthesize_typ(tp), ) |> rewrap | DeferredAp(e, es) => @@ -863,7 +918,6 @@ and parenthesize_typ = parenthesize_typ(~parenthesization, ~show_filters, ~show_ascriptions); let paren_typ_at = paren_typ_at(~parenthesization); let paren_typ_assoc_at = paren_typ_assoc_at(~parenthesization); - let paren_at = paren_at(~parenthesization); let should_auto_wrap_tuple = parenthesization == Defensive; let (term, rewrap) = Typ.unwrap(typ); switch (term) { @@ -877,17 +931,9 @@ and parenthesize_typ = | DrvQuoteTy(_) => typ // Other forms - | Parens(t) => - Parens( - parenthesize_typ(~already_paren=true, t) - |> paren_typ_at(Precedence.min), - ) - |> rewrap - | Projector(data, t) => - Projector(data, parenthesize_typ(t) |> paren_typ_at(Precedence.min)) - |> rewrap - | List(t) => - List(parenthesize_typ(t) |> paren_typ_at(Precedence.min)) |> rewrap + | Parens(t) => Parens(parenthesize_typ(~already_paren=true, t)) |> rewrap + | Projector(data, t) => Projector(data, parenthesize_typ(t)) |> rewrap + | List(t) => List(parenthesize_typ(t)) |> rewrap | Prod([]) => typ | Prod([t]) when @@ -947,12 +993,6 @@ and parenthesize_typ = parenthesize_typ(t) |> paren_typ_assoc_at(Precedence.type_binder), ) |> rewrap - | ProofOf(e) => - ProofOf( - parenthesize(~parenthesization, ~show_ascriptions, ~show_filters, e) - |> paren_at(Precedence.min), - ) - |> rewrap | Arrow(t1, t2) => Arrow( parenthesize_typ(t1) |> paren_typ_at(Precedence.type_arrow), @@ -1077,6 +1117,103 @@ and parenthesize_rul = }; } +/* Proof forms are keyword-delimited, but the expressions in their slots + * still need defending. Each slot is a bracketed tile child, so `min` is + * the right level, except a split's scrutinee, which shares its slot + * with the `| p => body` chain and defends at `rule_sep`. */ +and parenthesize_proof = + ( + ~parenthesization: Settings.parenthesization, + ~show_ascriptions: bool, + ~show_filters: bool, + proof: Proof.t, + ) + : Proof.t => { + let go_exp = (~level=Precedence.min, e: Exp.t): Exp.t => + parenthesize(~parenthesization, ~show_ascriptions, ~show_filters, e) + |> paren_at(~parenthesization, level); + let go_pat = (p: Pat.t): Pat.t => + parenthesize_pat(~parenthesization, ~show_ascriptions, ~show_filters, p); + let go = + parenthesize_proof(~parenthesization, ~show_ascriptions, ~show_filters); + let (term, rewrap: Proof.term => Proof.t) = IdTagged.unwrap(proof); + switch (term) { + | EmptyHole + | Invalid(_) + | MultiHole(_) => proof + | Parens(p) => Parens(go(p)) |> rewrap + /* `;` is right-associative and a wrapping form's body takes in every + step after it, so the left child needs parens when its last step is + a wrapping form: bare, `(a; assume e => b); c` would read as + `a; assume e => (b; c)`. Any other left-nested chain prints flat. */ + | Seq(p1, p2) => + let rec last_step = (p: Proof.t): Proof.t => + switch (Annotated.term_of(p)) { + | Seq(_, q) => last_step(q) + | _ => p + }; + let p1 = go(p1); + let p1 = + switch (parenthesization) { + | Defensive + when external_precedence_proof(last_step(p1)) >= Precedence.fun_ => + Proof.fresh(Parens(p1)) + | _ => p1 + }; + Seq(p1, go(p2)) |> rewrap; + | Forall(x, body) => Forall(go_pat(x), go(body)) |> rewrap + | Funext(x, body) => Funext(go_pat(x), go(body)) |> rewrap + | Assume(e, name, body) => + Assume(go_exp(e), Option.map(~f=go_pat, name), go(body)) |> rewrap + | Alias(x, e, body) => Alias(go_pat(x), go_exp(e), go(body)) |> rewrap + | Generalize(e, body) => Generalize(go_exp(e), go(body)) |> rewrap + | Revert(e, inst, body) => + Revert( + go_exp(e), + Option.map(~f=((v, i)) => (go_exp(v), go_exp(i)), inst), + go(body), + ) + |> rewrap + | Have(e, name, sub, body) => + Have(go_exp(e), Option.map(~f=go_pat, name), go(sub), go(body)) + |> rewrap + /* `<-` is a prefix at `fun_` over the fact. */ + | AxiomStep({direction, equality, instantiation}) => + AxiomStep({ + direction, + equality: + go_exp( + ~level=direction == Left ? Precedence.fun_ : Precedence.min, + equality, + ), + instantiation: + Option.map(~f=((v, i)) => (go_exp(v), go_exp(i)), instantiation), + }) + |> rewrap + | AlgebriteStep(e) => AlgebriteStep(go_exp(e)) |> rewrap + | EvalStep => proof + | Focus({ordinal, selector, body}) => + Focus({ + ordinal, + selector: go_exp(selector), + body: go(body), + }) + |> rewrap + | Cases(scrut, cases) => + Cases( + go_exp(~level=Precedence.rule_sep, scrut), + List.map(~f=((pat, body)) => (go_pat(pat), go(body)), cases), + ) + |> rewrap + | Induction(scrut, cases) => + Induction( + go_exp(~level=Precedence.rule_sep, scrut), + List.map(~f=((pat, body)) => (go_pat(pat), go(body)), cases), + ) + |> rewrap + }; +} + and parenthesize_any = ( ~parenthesization: Settings.parenthesization, @@ -1135,13 +1272,24 @@ and parenthesize_any = r, ), ) - /* Parenthesization for Drv, Mod, Sig, MPat, and Any is not yet defined. - Pretty-printing produces the term as-is; this is sound (never adds - invalid parens) but may omit disambiguating parens in nested contexts. */ + | Proof(p) => + Proof( + parenthesize_proof( + ~parenthesization, + ~show_ascriptions, + ~show_filters, + p, + ), + ) + /* Parenthesization for Drv, Mod, Sig, MPat, PRul, and Any is not yet + defined. Pretty-printing produces the term as-is; this is sound (never + adds invalid parens) but may omit disambiguating parens in nested + contexts. */ | Drv(_) => any | Mod(_) => any | Sig(_) => any | MPat(_) => any + | PRul(_) => any | Any(_) => any }; @@ -2270,18 +2418,15 @@ let rec exp_to_pretty = (~settings: Settings.t, exp: Exp.t): pretty => { and+ e2 = go(e2); let e2 = settings.inline ? e2 : [Secondary(mk_newline(Id.mk()))] @ e2; wrap(exp, [mk_form(Let, id, [p, e1])] @ e2); - | Theorem(p, thm, e) => + | Theorem(p, thm, pf, e) => // TODO: Add optional newlines let id = exp |> Exp.rep_id; let+ p = pat_to_pretty(~settings: Settings.t, p) and+ thm = go(thm) + and+ pf = proof_to_pretty(~settings: Settings.t, pf) and+ e = go(e); let e = settings.inline ? e : [Secondary(mk_newline(Id.mk()))] @ e; - wrap(exp, [mk_form(Theorem, id, [p, thm])] @ e); - | ProofObject(t) => - let id = exp |> Exp.rep_id; - let+ t = exp_to_pretty(~settings: Settings.t, t); - wrap(exp, [mk_form(ProofObject, id, [t])]); + wrap(exp, [mk_form(Theorem, id, [p, thm, pf])] @ e); | FixF(p, e, _) => // TODO: Add optional newlines let id = exp |> Exp.rep_id; @@ -3095,10 +3240,6 @@ and typ_to_pretty = (~settings: Settings.t, typ: Typ.t): pretty => { let+ tp = tpat_to_pretty(~settings: Settings.t, tp) and+ t = go(t); wrap(typ, [mk_form(Poly, id, [tp])] @ t); - | ProofOf(e) => - let id = typ |> Typ.rep_id; - let+ e = exp_to_pretty(~settings, e); - wrap(typ, [mk_form(ProofOf, id, [e])]); | Arrow(t1, t2) => let id = typ |> Typ.rep_id; let+ t1 = go(t1) @@ -3350,6 +3491,190 @@ and sig_to_pretty = (~settings: Settings.t, item: Sig.t): pretty => { and mpat_to_pretty = (~settings: Settings.t, mp: MPat.t): pretty => { p_just(mpat_to_seg(~settings, mp)); } +and proof_to_pretty = (~settings: Settings.t, p: Proof.t): pretty => { + let go = proof_to_pretty(~settings); + let wrap = wrap_with_secondary(~secondary=settings.secondary); + let (@) = concat_segment(~secondary=settings.secondary); + let mk_form = (~sort=Sort.Proof, fam, id, children) => + mk_form(~secondary=settings.secondary, ~sort, fam, id, children); + let id = p |> Proof.rep_id; + /* The PRul child is ` | p => body | ...`. */ + let split = (~family: Form.family, scrut, cases) => { + let+ s = exp_to_pretty(~settings, scrut) + and+ rendered_cases: list((Segment.t, Segment.t)) = + cases + |> List.map(~f=((pat, body)) => + (pat_to_pretty(~settings, pat), go(body)) + ) + |> all; + /* ids = [split tile, rule tiles...]: MakeTerm absorbs the rule tiles' + ids into the split's term, as with Match. */ + let rule_ids = + ( + switch (IdTagged.ids(p)) { + | [_, ...rest] => rest + | [] => [] + } + ) + |> PadIds.pad_ids( + ~forbidden=[id], + ~base=id, + List.length(rendered_cases), + ); + let cases_seg: Segment.t = + List.map2_exn( + rule_ids, rendered_cases, ~f=(rule_id, (pat_seg, body_seg)) => + [mk_form(~sort=Sort.PRul, Rule, rule_id, [pat_seg])] @ body_seg + ) + |> List.concat; + wrap(p, [mk_form(family, id, [s @ cases_seg])]); + }; + switch (p.term) { + | EmptyHole => + switch (hole_lexeme(p.annotation)) { + | Some(tok) => wrap(p, text_to_pretty(id, Sort.Proof, tok)) + | None => + wrap( + p, + [ + Grout({ + id, + shape: Convex, + }), + ], + ) + } + | Invalid(s) => wrap(p, invalid_to_pretty(id, Sort.Proof, s)) + | MultiHole(_) => wrap(p, text_to_pretty(id, Sort.Proof, "?")) + | Parens(inner) => + let+ inner = go(inner); + wrap(p, [mk_form(Parens, id, [inner])]); + | Seq(p1, p2) => + let+ s1 = go(p1) + and+ s2 = go(p2); + wrap(p, s1 @ [mk_form(CellJoin, id, [])] @ s2); + | Forall(x, body) => + let+ x = pat_to_pretty(~settings, x) + and+ b = go(body); + wrap(p, [mk_form(ProofForall, id, [x])] @ b); + | Funext(x, body) => + let+ x = pat_to_pretty(~settings, x) + and+ b = go(body); + wrap(p, [mk_form(ProofFunext, id, [x])] @ b); + | Assume(e, None, body) => + let+ e = exp_to_pretty(~settings, e) + and+ b = go(body); + wrap(p, [mk_form(ProofAssume, id, [e])] @ b); + | Assume(e, Some(x), body) => + let+ e = exp_to_pretty(~settings, e) + and+ x = pat_to_pretty(~settings, x) + and+ b = go(body); + wrap(p, [mk_form(ProofAssumeNamed, id, [x, e])] @ b); + | Alias(x, e, body) => + let+ x = pat_to_pretty(~settings, x) + and+ e = exp_to_pretty(~settings, e) + and+ b = go(body); + wrap(p, [mk_form(ProofAlias, id, [x, e])] @ b); + | Generalize(e, body) => + let+ e = exp_to_pretty(~settings, e) + and+ b = go(body); + wrap(p, [mk_form(ProofGeneralize, id, [e])] @ b); + | Revert(e, None, body) => + let+ e = exp_to_pretty(~settings, e) + and+ b = go(body); + wrap(p, [mk_form(ProofRevert, id, [e])] @ b); + | Revert(e, Some((v, inst)), body) => + let+ e = exp_to_pretty(~settings, e) + and+ v = exp_to_pretty(~settings, v) + and+ inst = exp_to_pretty(~settings, inst) + and+ b = go(body); + wrap(p, [mk_form(ProofRevertWith, id, [e, v, inst])] @ b); + | Have(e, None, sub, body) => + let+ e = exp_to_pretty(~settings, e) + and+ sub = go(sub) + and+ b = go(body); + wrap(p, [mk_form(ProofHave, id, [e, sub])] @ b); + | Have(e, Some(x), sub, body) => + let+ x = pat_to_pretty(~settings, x) + and+ e = exp_to_pretty(~settings, e) + and+ sub = go(sub) + and+ b = go(body); + wrap(p, [mk_form(ProofHaveNamed, id, [x, e, sub])] @ b); + | AxiomStep({direction, equality, instantiation}) => + let+ eq = exp_to_pretty(~settings, equality); + /* MakeTerm absorbs the arrow's tile id into the step's ids, after + the step's own. The whitespace before the arrow isn't kept, so it + is one space, with an id derived from the arrow's. */ + let eq = + switch (direction) { + | Right => eq + | Left => + let arrow_id = + switch (IdTagged.ids(p)) { + | [_, arrow_id, ..._] => arrow_id + | _ => Id.derive(~salt="rewrite-back", id) + }; + let (form, sort) = Form.classify_label(Sort.Exp, ["<-"]); + [ + Secondary(mk_space(Id.derive(~salt="space", arrow_id))), + Tile({ + id: arrow_id, + form, + sort, + shards: [0], + children: [], + }), + ] + @ eq; + }; + let inst: list(Segment.t) = + switch (instantiation) { + | None => [] + | Some((v, e)) => [ + exp_to_pretty(~settings, v), + exp_to_pretty(~settings, e), + ] + }; + let fam: Form.family = + switch (instantiation) { + | None => ProofAxiom + | Some(_) => ProofAxiomWith + }; + wrap(p, [mk_form(fam, id, [eq, ...inst])]); + | AlgebriteStep(e) => + let+ e = exp_to_pretty(~settings, e); + wrap(p, [mk_form(ProofAlgebrite, id, [e])]); + | EvalStep => p_just(wrap(p, [mk_form(ProofEval, id, [])])) + | Focus({ordinal, selector, body}) => + let+ sel = exp_to_pretty(~settings, selector) + and+ at = + switch (ordinal) { + | Some({term: n, annotation}) when n > 1 => + let at: Exp.t = { + term: Atom(Int(Bigint.of_int(n))), + annotation, + }; + Some(exp_to_pretty(~settings, at)); + | Some(_) + | None => None + } + and+ b = go(body); + /* `from` isn't a keyword to the spacing heuristics, which would glue + it to a following `(`, so the slot opens with a space unless its + stored whitespace already does. */ + let sel = + switch (sel) { + | [Secondary(_), ..._] => sel + | _ => [Secondary(mk_space(Id.mk())), ...sel] + }; + switch (at) { + | None => wrap(p, [mk_form(ProofFocus, id, [sel, b])]) + | Some(at) => wrap(p, [mk_form(ProofFocusAt, id, [sel, at, b])]) + }; + | Cases(scrut, cases) => split(~family=ProofCases, scrut, cases) + | Induction(scrut, cases) => split(~family=ProofInduction, scrut, cases) + }; +} and any_to_pretty = (~settings: Settings.t, any: Any.t): pretty => { switch (any) { | Exp(e) => exp_to_pretty(~settings: Settings.t, e) @@ -3361,6 +3686,8 @@ and any_to_pretty = (~settings: Settings.t, any: Any.t): pretty => { | Sig(s) => sig_to_pretty(~settings, s) | MPat(mp) => mpat_to_pretty(~settings, mp) | Rul(r) => rul_to_pretty(~settings, r) + | Proof(p) => proof_to_pretty(~settings, p) + | PRul(_) | Any(_) => let id = any |> Any.rep_id; p_just([ diff --git a/src/haz3lcore/pretty/PadIds.re b/src/haz3lcore/pretty/PadIds.re index 395fee8b5a..f0b4ae3b13 100644 --- a/src/haz3lcore/pretty/PadIds.re +++ b/src/haz3lcore/pretty/PadIds.re @@ -145,7 +145,6 @@ let rec pad_variant_anns = (ty: Typ.t): Typ.t => { | Label(_) | ExplicitNonlabel | Var(_) - | ProofOf(_) | Sig(_) => ty.term }; { diff --git a/src/haz3lcore/pretty/PrettySegment.re b/src/haz3lcore/pretty/PrettySegment.re index 239bb2cde3..b04039dda4 100644 --- a/src/haz3lcore/pretty/PrettySegment.re +++ b/src/haz3lcore/pretty/PrettySegment.re @@ -421,6 +421,20 @@ let is_compound_prefix = (p: Piece.t): bool => | _ => false }; +/* Is the infix operator `op` inside the body of `p`? True when `p` is a + rule or a prefix form that takes a body (fun, if, let, the proof forms + that wrap the rest of a proof) and binds looser than `op`. */ +let takes_into_body = (op: Piece.t, p: Piece.t): bool => + switch (p, infix_precedence(op)) { + | (Tile(t), Some(op_prec)) + when Tile.is_multidelimiter(t) && Tile.is_complete(t) => + switch (Tile.shapes(t)) { + | (_, Concave(prec)) => prec > op_prec + | (_, Convex) => false + } + | _ => false + }; + /* A "trailing hole" is either an implicit empty hole (Convex Grout) or an explicit hole (Tile with label `?`). When one of these appears as the sole body of a block-like form (e.g., `let x = 1 in ?`), we emit @@ -434,7 +448,7 @@ let is_trailing_hole = (p: Piece.t): bool => /* A "block form" is a compound expression whose layout naturally spans multiple lines: compound prefixes (let/fun/if/...) and compound operand - forms ending in "end" (case/end, test/end, proof_of/end, ...). We use + forms ending in "end" (case/end, test/end, ...). We use this to decide when to force a HardBreak before an expression so that block-like expressions always land on their own line. */ let is_block_form = (p: Piece.t): bool => @@ -648,8 +662,8 @@ and build_tile_doc = (s: settings, t: Tile.t, rest: list(Piece.t)): doc => { | _ => None }; - /* Attach semi and rest after a tile doc. Used by case/end, test/end, - hint/test/end, and other operand forms ending in "end". */ + /* Attach semi and rest after a tile doc. Used by the operand forms: + delimiter pairs and the forms ending in "end". */ let tile_with_rest = (tile_doc: doc): doc => switch (rest) { | [semi, ...rest2] when Piece.is_semi(semi) => @@ -666,11 +680,84 @@ and build_tile_doc = (s: settings, t: Tile.t, rest: list(Piece.t)): doc => { | _ => cats([tile_doc, Break, Group(segment_to_doc(s, rest))]) }; + /* A slot of steps is a block, bracketed by the keywords around it as + delimiters bracket their contents: the steps go on lines of their own + and `closer` starts the line after them, unless the group fits on one + line. + from e do + a; + b + end */ + let block_doc = (steps: Segment.t, closer: int): doc => + cats([ + Nest(indent_unit, cats([Break, child_doc(s, steps)])), + Break, + shard(closer), + ]); + + /* A slot of rules, ` | p => body | ...`: the scrutinee stays + on its keyword's line and every rule starts a line. */ + let rules_doc = (rules: Segment.t): doc => + switch (split_at_next_rule(strip_whitespace(rules))) { + | (_, []) => child_doc(s, rules) + | (scrut, rules) => + cats([ + Group(segment_to_doc(s, scrut)), + HardBreak, + segment_to_doc(s, rules), + ]) + }; + + /* The tile's keywords and children. A child follows its keyword on the + same line. When the tile doesn't fit on one line, each later keyword + starts a line; `closer` goes before the last one, so a Space makes it + trail instead (`fun x ->`). + + A slot of steps or rules is the tile's body. What precedes it is + grouped apart, so that the header stays on one line when the body + breaks, and the keyword closing a body always starts a line. */ + let keywords = (~closer: doc): doc => { + let rec go = (acc: doc, idx: int, slots: list((Sort.t, Segment.t))): doc => + switch (slots) { + | [] => acc + | [(sort, child), ...slots] => + let acc = + switch (sort) { + | Proof => cats([Group(acc), block_doc(child, idx)]) + | Rul + | PRul => + cats([Group(acc), Space, rules_doc(child), Break, shard(idx)]) + | Drv(_) + | Any + | Pat + | Typ + | TPat + | Exp + | Mod + | Sig + | MPat => + cats([ + acc, + Space, + Nest(indent_unit, child_doc(s, child)), + slots == [] ? closer : Break, + shard(idx), + ]) + }; + go(acc, idx + 1, slots); + }; + go(shard(0), 1, Tile.sorted_children(t)); + }; + + /* The Group keeps the tile flat when it fits (`rewrite refl end`) even + when the surrounding context breaks, e.g. a proof step before a `;`. */ + let keywords_doc = (): doc => Group(keywords(~closer=Break)); + switch (t.form) { - /* Definition forms: let/=/in, type/=/in, theorem/=/in, module/=/in */ + /* Definition forms: let/=/in, type/=/in, module/=/in, theorem/=/proof/in */ | _ when Tile.is_definition_form(t) => switch (triples) { - | [(_, pat_child, _), (_, binding_child, _)] => + | [(_, pat_child, _), (_, binding_child, _), ...steps] => let prefix = cats([ shard(0), @@ -682,7 +769,10 @@ and build_tile_doc = (s: settings, t: Tile.t, rest: list(Piece.t)): doc => { /* Hanging style: let x = (\n...\n) in Otherwise: let x =\n (...) in */ let binding_content = strip_whitespace(binding_child); - let in_suffix = cats([Space, shard(last_shard_idx)]); + /* The keyword after the binding trails it when it closes the form + (` in`). A theorem's `proof` opens the block of its steps instead, + and starts a line when the statement breaks. */ + let in_suffix = cats([steps == [] ? Space : Break, shard(2)]); /* Hanging lambda: keep `= fun ... ->` on the binding line when prefix + fun header fit the width budget (static decision — the greedy fits lookahead cannot express this preference @@ -746,7 +836,13 @@ and build_tile_doc = (s: settings, t: Tile.t, rest: list(Piece.t)): doc => { } }; let let_in_doc = Group(cats([prefix, binding_doc])); - Group(cats([let_in_doc, body_doc(true)])); + let definition = + switch (steps) { + | [] => let_in_doc + | [(_, steps, _), ..._] => + Group(cats([let_in_doc, block_doc(steps, last_shard_idx)])) + }; + Group(cats([definition, body_doc(true)])); | _ => fallback() } @@ -793,45 +889,41 @@ and build_tile_doc = (s: settings, t: Tile.t, rest: list(Piece.t)): doc => { | _ => fallback() } - /* Prefix arrow forms: fun/->, fix/->, typfun/->, poly/->, forall/->, rec/-> */ + /* Prefix arrow forms: fun/->, fix/->, typfun/->, poly/->, forall/->, + rec/->, and the forms that wrap the rest of a proof: forall/=>, + assume/as/=>, have/proof/=> */ | _ when Tile.is_prefix_arrow_form(t) => - switch (triples) { - | [(_, param_child, _)] => - let param_doc = child_doc(s, param_child); - let header = - cats([shard(0), Space, param_doc, Space, shard(last_shard_idx)]); - if (s.break_fun_params) { - cats([header, body_doc(false)]); - } else { - switch (rest) { - | [] => Group(header) - | [p] when is_trailing_hole(p) => - cats([ - Group(header), - Nest(indent_unit, cats([HardBreak, piece_doc(p)])), - ]) - | _ => - switch (split_at_comma(rest)) { - | Some(_) => cats([Group(header), body_doc(false)]) + let header = keywords(~closer=Space); + if (s.break_fun_params) { + cats([header, body_doc(false)]); + } else { + switch (rest) { + | [] => Group(header) + | [p] when is_trailing_hole(p) => + cats([ + Group(header), + Nest(indent_unit, cats([HardBreak, piece_doc(p)])), + ]) + | _ => + switch (split_at_comma(rest)) { + | Some(_) => cats([Group(header), body_doc(false)]) + | None => + switch (try_hanging_delim(rest, ())) { + | Some(hanging) => Group(cats([Group(header), Space, hanging])) | None => - switch (try_hanging_delim(rest, ())) { - | Some(hanging) => Group(cats([Group(header), Space, hanging])) - | None => - Group( - cats([ - Group(header), - Nest( - indent_unit, - cats([Break, Group(segment_to_doc(s, rest))]), - ), - ]), - ) - } + Group( + cats([ + Group(header), + Nest( + indent_unit, + cats([Break, Group(segment_to_doc(s, rest))]), + ), + ]), + ) } - }; + } }; - | _ => fallback() - } + }; /* Delimiter pairs: (...), [...], {...} */ | Form.Compound(Parens | Ap | ListLit | ModBody) => @@ -859,11 +951,10 @@ and build_tile_doc = (s: settings, t: Tile.t, rest: list(Piece.t)): doc => { ) }; switch (rest) { - | [] => delim_doc | [next, ..._] when is_paren_or_bracket(next) => /* curried application: (f)(x) stays attached */ cats([delim_doc, segment_to_doc(s, rest)]) - | _ => cats([delim_doc, Break, Group(segment_to_doc(s, rest))]) + | _ => tile_with_rest(delim_doc) }; | _ => fallback() } @@ -884,19 +975,6 @@ and build_tile_doc = (s: settings, t: Tile.t, rest: list(Piece.t)): doc => { | _ => fallback() } - /* case/end */ - | Form.Compound(Case) => - switch (triples) { - | [(_, body_child, _)] => - let inner = child_doc(s, body_child); - let tile_doc = - Group( - cats([shard(0), Space, inner, Break, shard(last_shard_idx)]), - ); - tile_with_rest(tile_doc); - | _ => fallback() - } - /* test/end: flat when it fits; otherwise break after "test" with "end" trailing the last body line */ | Form.Compound(Test) => @@ -945,19 +1023,9 @@ and build_tile_doc = (s: settings, t: Tile.t, rest: list(Piece.t)): doc => { | _ => fallback() } - /* Other operand forms ending in "end": proof_of/end, proof_object/end. - Same treatment as case/end (Space after keyword, Break before end). */ - | _ when Tile.ends_with_end(t) => - switch (triples) { - | [(_, body_child, _)] => - let inner = child_doc(s, body_child); - let tile_doc = - Group( - cats([shard(0), Space, inner, Break, shard(last_shard_idx)]), - ); - tile_with_rest(tile_doc); - | _ => fallback() - } + /* Other operand forms ending in "end": case, induction, from/do, + axiom, rewrite */ + | _ when Tile.ends_with_end(t) => tile_with_rest(keywords_doc()) /* Rule |/=> (case rule tiles with children) */ | Form.Compound(Rule) => @@ -1025,27 +1093,12 @@ and build_tile_doc = (s: settings, t: Tile.t, rest: list(Piece.t)): doc => { | _ => fallback() } - /* Generic multi-keyword tile: interleave shards and children with Break. - Children get Nest so multi-line children indent relative to keywords. */ + /* Generic multi-keyword tile */ | _ => - let rec build_rest = - (idx, triples: list((Tile.t, Segment.t, Tile.t))): doc => - switch (triples) { - | [] => Empty - | [(_, child, _), ...rest_triples] => - cats([ - Space, - Nest(indent_unit, child_doc(s, child)), - Break, - shard(idx), - build_rest(idx + 1, rest_triples), - ]) - }; - let tile_doc = cats([shard(0), build_rest(1, triples)]); switch (rest) { - | [] => tile_doc - | _ => cats([tile_doc, body_doc(false)]) - }; + | [] => keywords_doc() + | _ => cats([keywords_doc(), body_doc(false)]) + } }; } @@ -1060,14 +1113,16 @@ and semi_tail_doc = (s: settings, after: list(Piece.t)): doc => { /* Split at the first top-level semicolon, but only when the item before it has 2+ pieces (single-piece items keep their specialized - handling below) */ + handling below) and is an item of its own: in `fun x -> a; b` and + `| p => a; b` the semicolon is part of the body, which lays it out. */ and split_at_semi_multi = (ps: list(Piece.t)): option((list(Piece.t), Piece.t, list(Piece.t))) => { let rec go = (acc, ps: list(Piece.t)) => switch (ps) { | [] => None | [p, ...rest] when Piece.is_semi(p) => - List.length(acc) >= 2 ? Some((List.rev(acc), p, rest)) : None + List.length(acc) >= 2 && !List.exists(~f=takes_into_body(p), acc) + ? Some((List.rev(acc), p, rest)) : None | [p, ...rest] => go([p, ...acc], rest) }; go([], ps); diff --git a/src/haz3lcore/projectors/ProjectorPerform.re b/src/haz3lcore/projectors/ProjectorPerform.re index 9f9ce0bdbd..fc7c720a98 100644 --- a/src/haz3lcore/projectors/ProjectorPerform.re +++ b/src/haz3lcore/projectors/ProjectorPerform.re @@ -161,12 +161,15 @@ let go = }; replace_selection_and_unselect(piece, focus, z); | seg => - /* Add projector: migrate refractor from term to projector */ + /* Add projector: migrate refractor from term to projector. A + projector stands for a whole term, so a selection that isn't one, + like a `let ... in` header without its body, doesn't project: + the code around it would expect the missing part. */ + let* term_id = seg_root_id(seg); let+ piece = init(kind, seg, ~elaborated); let z = - switch (seg_root_id(seg), piece) { - | (Some(term_id), Projector(new_pr)) => - migrate_refractor(term_id, new_pr.id, z) + switch (piece) { + | Projector(new_pr) => migrate_refractor(term_id, new_pr.id, z) | _ => z }; replace_selection_and_unselect(piece, focus, z); diff --git a/src/haz3lcore/tiles/Base.re b/src/haz3lcore/tiles/Base.re index 4def3e0c22..1331315096 100644 --- a/src/haz3lcore/tiles/Base.re +++ b/src/haz3lcore/tiles/Base.re @@ -121,7 +121,7 @@ and tile_to_string = ~projector_to_segment, t: tile, ) - : string => + : string => { Aba.mk(t.shards, t.children) |> Aba.join( List.nth_exn(Form.label_of(t.form)), @@ -134,3 +134,4 @@ and tile_to_string = ), ) |> String.concat(~sep=""); +}; diff --git a/src/haz3lcore/tiles/Segment.re b/src/haz3lcore/tiles/Segment.re index 1048e02569..7d6237d4bf 100644 --- a/src/haz3lcore/tiles/Segment.re +++ b/src/haz3lcore/tiles/Segment.re @@ -183,10 +183,12 @@ let rec remold = (~shape=Nib.Shape.concave(), seg: t, s: Sort.t) => | Pat => remold_pat(shape, seg) | Exp => remold_exp(shape, seg) | Rul => remold_rul(shape, seg) + | PRul => remold_prul(shape, seg) | TPat => remold_tpat(shape, seg) | Mod => remold_mod(shape, seg) | Sig => remold_sig(shape, seg) | MPat => remold_mpat(shape, seg) + | Proof => remold_proof(shape, seg) } and remold_tile = (s: Sort.t, shape, t: Tile.t): option(Tile.t) => { open OptUtil.Syntax; @@ -569,6 +571,12 @@ and remold_exp_uni = (shape, seg: t, parent_sorts): (t, Nib.Shape.t, t) => remold_template_uni(sort, shape, tl); let (remolded_exp, shape, rest) = remold_exp_uni(shape, rest, []); ([Piece.Tile(t), ...remolded_drv] @ remolded_exp, shape, rest); + | (_, {shape, sort: Proof}) => + let (remolded_proof, shape, rest) = + remold_proof_uni(shape, tl, [Sort.Exp, ...parent_sorts]); + let (remolded_exp, shape, rest) = + remold_exp_uni(shape, rest, parent_sorts); + ([Piece.Tile(t), ...remolded_proof] @ remolded_exp, shape, rest); | _ => let (remolded, shape, rest) = remold_exp_uni(snd(Tile.shapes(t)), tl, parent_sorts); @@ -615,6 +623,52 @@ and remold_rul = (shape, seg: t): t => } } } +and remold_prul = (shape, seg: t): t => + /* Mirrors remold_rul but allows Proof on the right of a PRul-sorted tile + (i.e. ProofRule), since proof-rules bind to Proof bodies. The scrutinee + is an ordinary Exp chain that precedes the first rule tile. */ + switch (seg) { + | [] => [] + | [hd, ...tl] => + switch (hd) { + | Secondary(_) + | Grout(_) => [hd, ...remold_prul(shape, tl)] + | Projector(p) => [ + hd, + ...remold_prul(snd(ProjectorCore.shapes(p)), tl), + ] + | Tile(t) => + switch (remold_tile(PRul, shape, t)) { + | Some(t) when !Tile.has_end(Right, t) => + let (_, r) = Tile.nibs(t); + let remolded = remold(~shape=r.shape, tl, r.sort); + [Tile(t), ...remolded]; + | Some(t) => + switch (Tile.nibs(t)) { + | (_, {shape, sort: Exp}) => + let (remolded, shape, rest) = + remold_exp_uni(shape, tl, [Sort.PRul]); + [Piece.Tile(t), ...remolded] @ remold_prul(shape, rest); + | (_, {shape, sort: Pat}) => + let (remolded, shape, rest) = + remold_pat_uni(shape, tl, [Sort.PRul]); + [Piece.Tile(t), ...remolded] @ remold_prul(shape, rest); + | (_, {shape, sort: Proof}) => + let (remolded, shape, rest) = + remold_proof_uni(shape, tl, [Sort.PRul]); + [Piece.Tile(t), ...remolded] @ remold_prul(shape, rest); + | _ => failwith("remold_prul unexpected") + } + | None => + let (remolded, shape, rest) = + remold_exp_uni(shape, [hd, ...tl], []); + switch (remolded) { + | [] => [Piece.Tile(t), ...remold_prul(shape, tl)] + | [_, ..._] => remolded @ remold_prul(shape, rest) + }; + } + } + } and remold_exp = (shape, seg: t): t => switch (seg) { | [] => [] @@ -649,6 +703,10 @@ and remold_exp = (shape, seg: t): t => let (remolded, shape, rest) = remold_mod_uni(shape, tl, [Sort.Exp]); [Piece.Tile(t), ...remolded] @ remold_exp(shape, rest); + | (_, {shape, sort: Proof}) => + let (remolded, shape, rest) = + remold_proof_uni(shape, tl, [Sort.Exp]); + [Piece.Tile(t), ...remolded] @ remold_exp(shape, rest); | _ => [Tile(t), ...remold_exp(snd(Tile.shapes(t)), tl)] } } @@ -810,6 +868,89 @@ and remold_mpat = (shape, seg: t): t => } } } + } +and remold_proof_uni = (shape, seg: t, parent_sorts): (t, Nib.Shape.t, t) => + switch (seg) { + | [] => ([], shape, []) + | [hd, ...tl] => + switch (hd) { + | Secondary(_) + | Grout(_) => + let (remolded, shape, rest) = + remold_proof_uni(shape, tl, parent_sorts); + ([hd, ...remolded], shape, rest); + | Projector(p) => + let (remolded, shape, rest) = + remold_proof_uni(snd(ProjectorCore.shapes(p)), tl, parent_sorts); + ([hd, ...remolded], shape, rest); + | Tile(t) => + switch (remold_tile(Proof, shape, t)) { + | None => ([], shape, seg) + | Some(t) when !Tile.has_end(Right, t) => + let (_, r) = Tile.nibs(t); + let remolded = remold(~shape=r.shape, tl, r.sort); + let (_, shape, _) = shape_affix(Left, remolded, r.shape); + ([Tile(t), ...remolded], shape, []); + | Some(t) => + switch (Tile.nibs(t)) { + | (_, {shape, sort: Pat}) => + let (remolded_pat, shape, rest) = + remold_pat_uni(shape, tl, [Sort.Proof, ...parent_sorts]); + let (remolded_proof, shape, rest) = + remold_proof_uni(shape, rest, parent_sorts); + ([Piece.Tile(t), ...remolded_pat] @ remolded_proof, shape, rest); + | (_, {shape, sort: Exp}) => + let (remolded_exp, shape, rest) = + remold_exp_uni(shape, tl, [Sort.Proof, ...parent_sorts]); + let (remolded_proof, shape, rest) = + remold_proof_uni(shape, rest, parent_sorts); + ([Piece.Tile(t), ...remolded_exp] @ remolded_proof, shape, rest); + | (_, {shape, sort: PRul}) => ( + [Tile(t), ...remold_prul(shape, tl)], + shape, + [], + ) + | _ => + let (remolded, shape, rest) = + remold_proof_uni(snd(Tile.shapes(t)), tl, parent_sorts); + ([Tile(t), ...remolded], shape, rest); + } + } + } + } +and remold_proof = (shape, seg: t): t => + switch (seg) { + | [] => [] + | [hd, ...tl] => + switch (hd) { + | Secondary(_) + | Grout(_) => [hd, ...remold_proof(shape, tl)] + | Projector(p) => [ + hd, + ...remold_proof(snd(ProjectorCore.shapes(p)), tl), + ] + | Tile(t) => + switch (remold_tile(Proof, shape, t)) { + | None => [Tile(t), ...remold_proof(snd(Tile.shapes(t)), tl)] + | Some(t) when !Tile.has_end(Right, t) => + let (_, r) = Tile.nibs(t); + let remolded = remold(~shape=r.shape, tl, r.sort); + [Tile(t), ...remolded]; + | Some(t) => + switch (Tile.nibs(t)) { + | (_, {shape, sort: Pat}) => + let (remolded, shape, rest) = + remold_pat_uni(shape, tl, [Sort.Proof]); + [Piece.Tile(t), ...remolded] @ remold_proof(shape, rest); + | (_, {shape, sort: Exp}) => + let (remolded, shape, rest) = + remold_exp_uni(shape, tl, [Sort.Proof]); + [Piece.Tile(t), ...remolded] @ remold_proof(shape, rest); + | (_, {shape, sort: PRul}) => [Tile(t), ...remold_prul(shape, tl)] + | _ => [Tile(t), ...remold_proof(snd(Tile.shapes(t)), tl)] + } + } + } }; /* Note: This was previously memoized via Core.Memo.general(~cache_size_bound=10000, ...). diff --git a/src/haz3lcore/tiles/Skel.re b/src/haz3lcore/tiles/Skel.re index c1d2931e74..ce5c46bd49 100644 --- a/src/haz3lcore/tiles/Skel.re +++ b/src/haz3lcore/tiles/Skel.re @@ -32,8 +32,13 @@ let is_chainable = (p1: Piece.t, p2: Piece.t): bool => let both_infix = () => Mold.is_infix_op(Tile.mold(t1)) && Mold.is_infix_op(Tile.mold(t2)); switch (t1.form, t2.form) { - /* case rules chain with each other and their case header */ - | (Form.Compound(Case | Rule), Form.Compound(Rule)) => true + /* case, cases and induction rules chain with each other and their + header */ + | ( + Form.Compound(Case | ProofCases | ProofInduction | Rule), + Form.Compound(Rule), + ) => + true | (Form.Compound(Comma), Form.Compound(Comma)) => both_infix() /* semicolons chain within a module or signature body */ | (Form.Compound(CellJoin), Form.Compound(CellJoin)) => diff --git a/src/haz3lcore/tiles/Tile.re b/src/haz3lcore/tiles/Tile.re index 11851ea2ea..bb86c351b4 100644 --- a/src/haz3lcore/tiles/Tile.re +++ b/src/haz3lcore/tiles/Tile.re @@ -76,14 +76,7 @@ let ends_with_end = (t: t): bool => /* definition forms: let/type/theorem/module */ let is_definition_form = (t: t): bool => switch (label(t)) { - | [_, "=", "in"] => true - | _ => false - }; - -/* binder prefix forms: fun/fix/typfun/poly/forall/rec */ -let is_prefix_arrow_form = (t: t): bool => - switch (label(t)) { - | [_, "->"] => true + | [_, "=", ..._] => ends_with_in(t) | _ => false }; @@ -133,6 +126,15 @@ let has_concave_left_nib = (t: t): bool => | _ => false }; +/* binder prefix forms: fun/fix/typfun/poly/forall/rec, and the forms that + * wrap the rest of a proof (forall/assume/have/...). A rule also ends in + * `=>`, but has a left operand. */ +let is_prefix_arrow_form = (t: t): bool => + switch (label(t) |> List.rev) { + | ["->" | "=>", _, ..._] => !has_concave_left_nib(t) + | _ => false + }; + let to_piece = t => Tile(t); let sorted_children = (t: t) => { diff --git a/src/haz3lcore/zipper/action/Insert.re b/src/haz3lcore/zipper/action/Insert.re index 0d474c72d7..ea26af7c52 100644 --- a/src/haz3lcore/zipper/action/Insert.re +++ b/src/haz3lcore/zipper/action/Insert.re @@ -24,13 +24,40 @@ let expansion = (sort: Sort.t, t: Token.t, z: t): (Label.t, Direction.t) => { | Some(a) when Form.has_label_of(a.form, Case) => true | _ => false }; + /* `cases` and `induction` own their case rules as case does. */ + let is_induction = (f: Form.t): bool => + switch (f) { + | Form.Compound(ProofCases | ProofInduction) => true + | _ => false + }; + let before_induction_shard = (z: t): bool => + List.exists( + ~f= + (p: Piece.t) => + switch (p) { + | Tile({form, shards: [0], _}) => is_induction(form) + | _ => false + }, + z.relatives.siblings |> fst, + ); + let inside_induction = (z: t): bool => + switch (Ancestors.parent(z.relatives.ancestors)) { + | Some(a) => is_induction(a.form) + | None => false + }; switch (t) { | _ when Token.is_string_delim(t) || Token.is_quoted_label_delim(t) => /* Special case for constructing string/label literals. */ ([t ++ t], Left) - | "|" when before_case_shard(z) || inside_case(z) => - /* SPECIAL CASE: Case rule delimiter. - Inside a case, always expand | to Rule form regardless of local sort. + | "|" + when + before_case_shard(z) + || inside_case(z) + || before_induction_shard(z) + || inside_induction(z) => + /* SPECIAL CASE: Case and induction rule delimiter. + Inside a case or induction, always expand | to Rule form regardless + of local sort; remolding then picks its Rul or PRul row. Why this is needed: The Rule form's left nib is Exp (it expects an expression). But rule bodies can have type ascriptions like `expr : Type`, @@ -124,6 +151,89 @@ let insert_shard_core = }; }; +/* Proof steps with a `with`, named (`=`) or `at` variant share the plain + * step's leading token, so they expand to the plain form and the later + * `with`/`=`/`at` token switches the tile to the variant. This rewrites the + * nearest tile left of the caret that `variant` maps to a new family. The + * scan stops at any other incomplete tile, since the token belongs to it. + * The pieces between that tile and the caret are the variant's first + * child, so they take its sort: the name in `assume h =` was typed as an + * expression and is a pattern once the `=` is down. */ +let switch_variant = (variant: Tile.t => option(Form.family), z: t): t => { + let (pre, suf) = z.relatives.siblings; + let rec go = (child: Segment.t, rev_before: list(Piece.t)) => + switch (rev_before) { + | [] => None + | [Tile(t) as p, ...rest] => + switch (variant(t)) { + | Some(fam) => + let t = { + ...t, + form: Compound(fam), + sort: Proof, + }; + let child = + switch (Tile.mold(t).in_) { + | [sort, ..._] => Segment.remold(child, sort) + | [] => child + }; + Some(List.rev(rest) @ [Tile(t), ...child]); + | None when !Tile.is_complete(t) => None + | None => go([p, ...child], rest) + } + | [p, ...rest] => go([p, ...child], rest) + }; + switch (go([], List.rev(pre))) { + | Some(pre) => { + ...z, + relatives: { + ...z.relatives, + siblings: (pre, suf), + }, + } + | None => z + }; +}; + +let with_variant = (t: Tile.t): option(Form.family) => + switch (t.form, t.shards) { + | (Compound(ProofAxiom), [0]) => Some(ProofAxiomWith) + | (Compound(ProofRevert), [0]) => Some(ProofRevertWith) + | _ => None + }; + +let named_variant = (t: Tile.t): option(Form.family) => + switch (t.form, t.shards) { + | (Compound(ProofAssume), [0]) => Some(ProofAssumeNamed) + | (Compound(ProofHave), [0]) => Some(ProofHaveNamed) + | _ => None + }; + +let at_variant = (t: Tile.t): option(Form.family) => + switch (t.form, t.shards) { + | (Compound(ProofFocus), [0]) => Some(ProofFocusAt) + | _ => None + }; + +/* "=" is a prefix of "==" and "=>", so typing either passes through an + * "=" token that switches an enclosing assume/have to its named + * form, and the next keystroke removes that "=" shard again. A named form + * whose "=" shard is not down is restored to the plain form. A real + * switch is unaffected: insert_shard places the "=" in the same call. */ +let plain_of_named_variant = (t: Tile.t): option(Form.family) => + switch (t.form, t.shards) { + | (Compound(ProofAssumeNamed), [0]) => Some(ProofAssume) + | (Compound(ProofHaveNamed), [0]) => Some(ProofHave) + | _ => None + }; + +/* As for "=": "at" is a prefix of names like `atom`. */ +let plain_of_at_variant = (t: Tile.t): option(Form.family) => + switch (t.form, t.shards) { + | (Compound(ProofFocusAt), [0]) => Some(ProofFocus) + | _ => None + }; + /* Insert a new shard based on token `t` on the `d`-side of the caret */ let insert_shard = ( @@ -134,7 +244,18 @@ let insert_shard = z: t, ~root, ) - : t => + : t => { + let z = + t == "with" && Zipper.find_missing_shard(t, z) == None + ? switch_variant(with_variant, z) : z; + let z = + t == "=" && Zipper.find_missing_shard(t, z) == None + ? switch_variant(named_variant, z) + : switch_variant(plain_of_named_variant, z); + let z = + t == "at" && Zipper.find_missing_shard(t, z) == None + ? switch_variant(at_variant, z) + : switch_variant(plain_of_at_variant, z); if (Zipper.find_missing_shard(t, z) != None) { let z = destroy_selection(z); let target = Zipper.find_missing_shard(t, z) |> Option.value_exn; @@ -149,6 +270,7 @@ let insert_shard = ~root, ); }; +}; /* Replace `d`-neighbor shard with a new one based on token `t` */ let replace_shard = diff --git a/src/language/builtins/BuiltinsBase.re b/src/language/builtins/BuiltinsBase.re index 72e557c86b..da38df8acf 100644 --- a/src/language/builtins/BuiltinsBase.re +++ b/src/language/builtins/BuiltinsBase.re @@ -343,6 +343,15 @@ let numeric_fns: list(BuiltinsUtil.fn) = [ }, ]; +/* Compiling a malformed regexp throws a JS exception. The string builtins + take their patterns from user code, so they return None (stuck) instead + of letting the exception escape the evaluator. */ +let catch_malformed_regexp = (f: unit => 'a): option('a) => + switch (f()) { + | x => Some(x) + | exception _ => None + }; + let string_fns: list(BuiltinsUtil.fn) = [ { name: "string_length", @@ -493,7 +502,8 @@ let string_fns: list(BuiltinsUtil.fn) = [ binary((d1, d2) => { let-unbox regexp = (Atom(String), d1); let-unbox str = (Atom(String), d2); - Some(Exp.bool(HazelString.matches(regexp, str))); + catch_malformed_regexp(() => HazelString.matches(regexp, str)) + |> Option.map(~f=b => Exp.bool(b)); }), custom_statics: None, }, @@ -506,7 +516,8 @@ let string_fns: list(BuiltinsUtil.fn) = [ let-unbox regexp = (Atom(String), d1); let-unbox str = (Atom(String), d2); let-unbox repl = (Atom(String), d3); - Some(Exp.string(HazelString.replace(regexp, str, repl))); + catch_malformed_regexp(() => HazelString.replace(regexp, str, repl)) + |> Option.map(~f=s => Exp.string(s)); }), custom_statics: None, }, @@ -521,14 +532,25 @@ let string_fns: list(BuiltinsUtil.fn) = [ let-unbox regexp = (Atom(String), d1); let-unbox str = (Atom(String), d2); let-unbox idx = (Atom(Int), d3); - Some( - Exp.int( - switch (Bigint.to_int(idx)) { - | None => (-1) - | Some(idx) => HazelString.search(regexp, str, idx) - }, - ), - ); + switch (Bigint.to_int(idx)) { + | None => + /* An index that doesn't fit in an OCaml int is off-domain, not a + regex miss, so it errors: a -1 would be a defined result that + proofs could rely on. */ + Some( + Exp.dynamic_error_hole( + Exp.ap( + Operators.Forward, + Exp.builtin_fun("string_search"), + d1, + ), + InvalidOperationError.IndexOutOfBounds, + ), + ) + | Some(idx) => + catch_malformed_regexp(() => HazelString.search(regexp, str, idx)) + |> Option.map(~f=i => Exp.int(i)) + }; }), custom_statics: None, }, diff --git a/src/language/builtins/BuiltinsUtil.re b/src/language/builtins/BuiltinsUtil.re index f0c87c9ddd..0b684aa7d0 100644 --- a/src/language/builtins/BuiltinsUtil.re +++ b/src/language/builtins/BuiltinsUtil.re @@ -124,6 +124,17 @@ let float_op = (fn, d) => { Some(Fresh.Exp.float(fn(f))); }; +/* An off-domain atom builtin application (e.g. int_of_string("abc"), or + int_of_float(nan)) must not become an anonymous stuck term: surface the + InvalidOperationError from Atom.convert as a DynamicErrorHole attributing + the failed application, mirroring the mod builtins in BuiltinsBase. */ +let atom_builtin_error = + (name: string, d: DHExp.t, err: InvalidOperationError.t): DHExp.t => + Fresh.Exp.dynamic_error_hole( + Fresh.Exp.ap(Operators.Forward, Fresh.Exp.builtin_fun(name), d), + err, + ); + let of_atom_builtin = ((name: string, b: Atom.builtin)): builtin => { switch (b) { | OneFun(k1, k2, f) => @@ -135,7 +146,7 @@ let of_atom_builtin = ((name: string, b: Atom.builtin)): builtin => { let-unbox x = (Atom(k1), d); switch (f(x)) { | Ok(x) => Some(Atom(Atom.repack(k2, x)) |> Exp.fresh) - | Error(_) => None + | Error(err) => Some(atom_builtin_error(name, d, err)) }; }, custom_statics: None, @@ -158,7 +169,7 @@ let of_atom_builtin = ((name: string, b: Atom.builtin)): builtin => { let-unbox y = (Atom(k2), y); switch (f(x, y)) { | Ok(x) => Some(Atom(Atom.repack(k3, x)) |> Exp.fresh) - | Error(_) => None + | Error(err) => Some(atom_builtin_error(name, d, err)) }; } ), diff --git a/src/language/dynamics/DHExp.re b/src/language/dynamics/DHExp.re index fc35098077..ed30ebd716 100644 --- a/src/language/dynamics/DHExp.re +++ b/src/language/dynamics/DHExp.re @@ -90,7 +90,6 @@ let ty_subst = (s: Typ.t, tpat: TPat.t, exp: t): t => { | Seq(_) | Let(_) | Theorem(_) - | ProofObject(_) | Forall(_) | Ap(_) | BuiltinFun(_) @@ -143,7 +142,6 @@ let rec ty_comparable = (d1, d2) => { | (Var(_), _) | (Let(_), _) | (Theorem(_), _) - | (ProofObject(_), _) | (Forall(_), _) | (FixF(_), _) | (TyAlias(_), _) @@ -248,7 +246,6 @@ let rec poly_equal = (d1, d2): option(bool) => { | (Var(_), _) | (Let(_), _) | (Theorem(_), _) - | (ProofObject(_), _) | (Forall(_), _) | (FixF(_), _) | (TyAlias(_), _) @@ -294,14 +291,21 @@ let rec poly_equal = (d1, d2): option(bool) => { | (Bool(_), _) => false | (String(s1), String(s2)) => String.equal(s1, s2) | (String(_), _) => false - | (Float(f1), Float(f2)) => Float.equal(f1, f2) + /* `nan == nan`, so that `==` is reflexive as the `refl` axiom says. + * `==.` keeps IEEE equality. */ + | (Float(f1), Float(f2)) => Stdlib.Float.equal(f1, f2) | (Float(_), _) => false } ) |> Option.some | (Atom(_), _) => None | (DrvQuote(d1, _), DrvQuote(d2, _)) => - Drv.Any.eq(d1, d2, ~skip_hole=false) |> Option.some + /* Proofs trust any boolean verdict evaluation renders, so an + incomplete derivation must not get one: with ~skip_hole=false, eq + treats holes as ordinary structure, so a hole-containing derivation + would compare Some(false) against a complete one. */ + Drv.Any.contains_hole(d1) || Drv.Any.contains_hole(d2) + ? None : Drv.Any.eq(d1, d2, ~skip_hole=false) |> Option.some | (DrvQuote(_, _), _) => None | (Label(l1), Label(l2)) => String.equal(l1, l2) ? Some(true) : None | (Label(_), _) => None diff --git a/src/language/dynamics/Dynamics.re b/src/language/dynamics/Dynamics.re index ba72a5b4f3..13c0e7e2df 100644 --- a/src/language/dynamics/Dynamics.re +++ b/src/language/dynamics/Dynamics.re @@ -54,4 +54,5 @@ type t = { probe_map: Sample.Map.t, test_results: TestResults.t, theorems: list((Id.t, string, Environment.t(Exp.t), Exp.t)), + proof_map: ProofMap.t, }; diff --git a/src/language/dynamics/EvalInfo.re b/src/language/dynamics/EvalInfo.re index 356391c619..703664b247 100644 --- a/src/language/dynamics/EvalInfo.re +++ b/src/language/dynamics/EvalInfo.re @@ -22,14 +22,29 @@ type entry = { probe_targets, }; +/* What the proof checker reads, for a program with theorems. Types are + * normalized: there is no typing context to resolve an alias against + * where the evaluator runs. */ +[@deriving (show({with_path: false}), sexp, yojson)] +type proofs = { + /* Of each expression and pattern. */ + types: Id.Map.t(Typ.t), + /* What each pattern covers. */ + covers: Id.Map.t(Coverage.Constraint.t), + /* The theorems each theorem can cite, by its node's id. */ + namespaces: Id.Map.t(ProofStatics.namespace), +}; + [@deriving (show({with_path: false}), sexp, yojson)] type t = { statics: Id.Map.t(entry), + proofs: option(proofs), targets: Sample.targets /* IDs of expressions/patterns to sample */ }; let empty: t = { statics: Id.Map.empty, + proofs: None, targets: Sample.no_targets, }; @@ -56,19 +71,97 @@ let of_targets = (targets: Sample.targets): t => { let of_info_map = (~probe_all: bool, ~targets: Sample.targets, info_map: StaticsBase.Map.t) : t => { - statics: - Id.Map.filter_map( - (_id, info) => + let has_theorem = + Id.Map.exists( + (_, info) => switch (info) { - | Info.InfoExp({elab_term, co_ctx, probe_targets, _}) => - Some({ - elab_term, - co_ctx, - probe_targets: probe_all ? ProbeAll : ProbeTargets(probe_targets), - }) - | _ => None + | Info.InfoExp({elab_term: {term: Theorem(_), _}, _}) => true + | _ => false }, info_map, - ), - targets, + ); + let proofs = () => { + /* Normalizing copies every alias it expands, so equal types are made + * one value again, which the worker message then sends once. The + * copies keep the alias's ids, so they are equal as values. */ + let seen = Stdlib.Hashtbl.create(64); + let normalize = (ctx, ty) => { + let ty = Typ.normalize(ctx, ty); + switch (Stdlib.Hashtbl.find_opt(seen, ty)) { + | Some(same) => same + | None => + Stdlib.Hashtbl.add(seen, ty, ty); + ty; + }; + }; + { + types: + Id.Map.filter_map( + (_, info) => + switch (info) { + | Info.InfoExp({ctx, ty, _}) + | Info.InfoPat({ctx, ty, _}) => Some(normalize(ctx, ty)) + | _ => None + }, + info_map, + ), + covers: + Id.Map.filter_map( + (_, info) => + switch (info) { + | Info.InfoPat({constraint_, _}) => Some(constraint_) + | _ => None + }, + info_map, + ), + namespaces: + Id.Map.filter_map( + (_, info) => + switch (info) { + | Info.InfoExp({elab_term: {term: Theorem(_), _}, ctx, _}) => + Some(ProofStatics.namespace_of_ctx(ctx)) + | _ => None + }, + info_map, + ), + }; + }; + { + statics: + Id.Map.filter_map( + (_id, info) => + switch (info) { + | Info.InfoExp({elab_term, co_ctx, probe_targets, _}) => + Some({ + elab_term, + co_ctx, + probe_targets: + probe_all ? ProbeAll : ProbeTargets(probe_targets), + }) + | _ => None + }, + info_map, + ), + proofs: has_theorem ? Some(proofs()) : None, + targets, + }; }; + +/* The checker's view of the statics. None for a program without theorems, + * where there is nothing to check. */ +let proof_statics = (map: t): option(ProofStatics.t) => + Option.map( + ~f= + ({types, covers, namespaces}) => + ProofStatics.{ + typ: id => Id.Map.find_opt(id, types), + namespace: id => Id.Map.find_opt(id, namespaces), + co_ctx: id => + Option.map( + ~f=(entry: entry) => entry.co_ctx, + find_opt(id, map), + ), + pat_constraint: id => Id.Map.find_opt(id, covers), + }, + map.proofs, + ); diff --git a/src/language/dynamics/Evaluator.re b/src/language/dynamics/Evaluator.re index d4dc172849..478ea4482d 100644 --- a/src/language/dynamics/Evaluator.re +++ b/src/language/dynamics/Evaluator.re @@ -92,6 +92,181 @@ let continues_delegation = delegations, ); +/* Checking theorems' proofs. Their `step` steps reduce with the stepper + * (`EvaluatorStep`), not with this module's trampoline. */ +module Proofs = { + /* The steps a `step` proof step passes through silently. One proof + * step is one meaningful reduction, so besides the stepper's auto-hidden + * steps it also passes through `VarLookup`s. */ + let advance_hidden = (~max_steps=?, ~env, e) => { + let hidden_step = e => + switch (EvaluatorStep.get_status(~settings=CoreSettings.on, e, env)) { + | AutoStep(s) => Some(s) + | AvailableSteps([s, ..._]) + when Poly.equal(EvaluatorStep.get_step_kind(s), VarLookup) => + Some(s) + | AvailableSteps(_) => None + }; + let rec advance = (~taken, e) => + switch (hidden_step(e), max_steps) { + | (None, _) => Some(([], e)) + | (Some(_), Some(max)) when taken >= max => None + | (Some(s), _) => + switch (EvaluatorStep.take_step(s)) { + | Some(next) => + let justification = + s |> EvaluatorStep.get_step_kind |> stepper_justification; + advance(~taken=taken + 1, next) + |> Option.map(~f=((rest, outgoing)) => + ([(e, justification, next), ...rest], outgoing) + ); + | None => Some(([], e)) + } + }; + advance(~taken=0, e); + }; + + /* One `step` proof step: the silent steps, the visible step, and the + * silent steps after it. */ + let step: ProofCheck.step_fn = + (~env, ~at, e) => { + /* Unbounded, so never None. */ + let advance_hidden = e => + advance_hidden(~env, e) |> Option.value(~default=([], e)); + let (leading_auto_steps, e) = advance_hidden(e); + let visible_step = + switch (EvaluatorStep.get_status(~settings=CoreSettings.on, e, env)) { + | AvailableSteps(steps) => + switch (at) { + | Anywhere => Util.ListUtil.hd_opt(steps) + | Root => List.find(~f=EvaluatorStep.is_at_root, steps) + } + | AutoStep(_) => None + }; + switch (visible_step) { + | Some(s) => + switch (EvaluatorStep.take_step(s)) { + | Some(next) => + let (trailing_auto_steps, outgoing) = advance_hidden(next); + Some( + ProofCheck.{ + auto_incoming: + List.map( + ~f= + ((_, justification, output)) => (justification, output), + leading_auto_steps, + ), + auto_outgoing: + List.map( + ~f=((input, justification, _)) => (input, justification), + trailing_auto_steps, + ), + outgoing, + }, + ); + | None => None + } + | None => None + }; + }; + + let check_proof = + (~statics: ProofStatics.t, ~ctx: SemanticCtx.t, ~goal: Exp.t, proof) + : ProofMap.t => + ProofCheck.check(~step, ~statics, ~ctx, Some(goal), proof) |> snd; + + /* A theorem's proof checked in `scope`: the statement's outer `forall`s + * are introduced first, so their variables enter the proof's context, + * and the proof is checked against the rest, including any `==>` + * antecedents (which the proof introduces with `assume`). The + * per-theorem stepper (`Theorems.re`) seeds its goal the same way, so + * the two agree. */ + let check_theorem = + (~statics: ProofStatics.t, ~scope: SemanticCtx.t, ~statement, proof) + : ProofMap.t => { + let (ctx, goal) = ProofCheck.peel_stmt_binders(scope, statement); + check_proof(~statics, ~ctx, ~goal, proof); + }; + + /* The proofs of the theorems evaluation reached, checked in the order it + * reached them, each knowing the verdicts of the theorems before it, so + * a proof that cites one can tell whether it rests on a refuted or + * unfinished statement. Returns the proof map and the checks to cache. + * + * A check in `prev` is reused while the theorem, its scope and the + * verdicts in it, and the values it names are the same. `inputs` has + * the provenance of the values each theorem names where evaluation + * reached it. A theorem it lacks was replayed from a reused node, and + * a node is reused only when the values its theorems name are the same + * (their proofs' variables are in its co-context). */ + let check_theorems = + ( + ~statics: ProofStatics.t, + ~prev: IncrEval.t('state), + ~inputs: Id.Map.t(IncrEval.CheckedProofs.input), + ~elaborated: Exp.t, + theorems, + ) + : (ProofMap.t, Id.Map.t(IncrEval.checked_proof)) => { + let check = ((proof_map, verdicts, checks), (id, _, env, _)) => + switch (Exp.find_by_id(id, elaborated)) { + | Some({term: Theorem(p, statement, proof, _), _} as theorem) => + let namespace = + statics.namespace(id) + |> Option.value(~default=ProofStatics.empty_namespace); + let verdicts_in_scope = + List.filter_map( + ~f= + (entry: Ctx.theorem_entry) => + List.Assoc.find(verdicts, entry.id, ~equal=Id.equal) + |> Option.map(~f=v => (entry.id, v)), + namespace.theorems, + ); + let input = Id.Map.find_opt(id, inputs); + let key = + IncrEval.CheckedProofs.key( + ~namespace, + ~verdicts=verdicts_in_scope, + theorem, + ); + let checked = + switch (IncrEval.CheckedProofs.find(~prev, ~input, id, key)) { + | Some(proof_map) => proof_map + | None => + let scope = TheoremNamespace.scope(~env, ~verdicts, namespace); + check_theorem(~statics, ~scope, ~statement, proof); + }; + let checks = + switch ( + IncrEval.CheckedProofs.entry(~prev, ~input, id, key, checked) + ) { + | Some(entry) => Id.Map.add(id, entry, checks) + | None => checks + }; + let verdict: SemanticCtx.verdict = + switch (ProofMap.full_status_of_proof(checked, proof)) { + | Proven => Proven + | Refuted => Refuted + | ProvenModulo(_) + | Incomplete => Unfinished + }; + ( + ProofMap.union(proof_map, checked), + [(Pat.rep_id(p), verdict), ...verdicts], + checks, + ); + | _ => (proof_map, verdicts, checks) + }; + let (proof_map, _, checks) = + List.fold_left( + ~f=check, + ~init=(ProofMap.empty, [], Id.Map.empty), + List.rev(theorems), + ); + (proof_map, checks); + }; +}; + let rec evaluate = // Constants ( @@ -110,6 +285,9 @@ let rec evaluate = // Outputs ~parent_state: ref(EvaluatorState.t), ~outbox: option(ref(IncrEval.outbox(EvaluatorState.t))), + /* What evaluation found where it reached each theorem, for + * reusing the theorem's check (`Proofs.check_theorems`). */ + ~theorem_inputs: ref(Id.Map.t(IncrEval.CheckedProofs.input)), ~current_top_id: option(Id.t), ) : Trampoline.t(DHExp.t) => { @@ -118,8 +296,28 @@ let rec evaluate = * running. */ let evaluate = - evaluate(~prev, ~track_reuse, ~reused_ids, ~eval_info, ~outbox); + evaluate( + ~prev, + ~track_reuse, + ~reused_ids, + ~eval_info, + ~outbox, + ~theorem_inputs, + ); let expr_id = DHExp.rep_id(exp); + /* What a theorem's check depends on in the env, for reusing it once + * evaluation is done (`Proofs.check_theorems`). */ + switch (exp.term) { + | Theorem(_) => + theorem_inputs := + Id.Map.add( + expr_id, + List.is_empty(call_stack) + ? IncrEval.CheckedProofs.reached(reuse_map, exp) : InCall, + theorem_inputs^, + ) + | _ => () + }; /* Outbox publication keys only on proper program nodes * (EvalInfo.is_program_node). * Administrative/stepped intermediates never publish: doing so either @@ -508,6 +706,47 @@ let completed = (state: EvaluatorState.t): EvaluatorState.t => { }, }; +/* The statics to check proofs with: the full map when given, or else what + * `eval_info` carries. None when neither has any, and proofs aren't + * checked. */ +let proof_statics = + (~statics: Statics.Map.t, eval_info: EvalInfo.t): option(ProofStatics.t) => + Id.Map.is_empty(statics) + ? EvalInfo.proof_statics(eval_info) + : Some(ProofStatics.of_info_map(statics)); + +/* `completed`, with the proofs of the theorems evaluation reached checked, + * in the order it reached them, and their checks cached. */ +let completed_with_proofs = + ( + ~proofs: option(ProofStatics.t), + ~prev: EvaluatorState.incr_eval, + ~inputs: Id.Map.t(IncrEval.CheckedProofs.input), + elaborated: DHExp.t, + state: EvaluatorState.t, + ) + : EvaluatorState.t => + switch (proofs) { + | None => completed(state) + | Some(statics) => + let (proof_map, checks) = + Proofs.check_theorems( + ~statics, + ~prev, + ~inputs, + ~elaborated, + EvaluatorState.get_theorems(state), + ); + let state = completed(EvaluatorState.merge_proof_map(state, proof_map)); + { + ...state, + incr_eval: { + ...state.incr_eval, + proofs: checks, + }, + }; + }; + let finish = (~env, e: DHExp.t): Exp.t => e |> Substitution.in_exp(env) |> Exp.replace_all_ids; @@ -526,7 +765,11 @@ let prepare_evaluation = ~outbox, d: DHExp.t, ) - : (ref(EvaluatorState.t), Trampoline.t(DHExp.t)) => { + : ( + ref(EvaluatorState.t), + ref(Id.Map.t(IncrEval.CheckedProofs.input)), + Trampoline.t(DHExp.t), + ) => { /* The reuse map is only ever consumed by reuse_check or by incr-entry * snapshots, both of which need statics in eval_info (reuse_check also * needs a non-empty prev). When neither can fire — e.g. `hazel run`, @@ -542,6 +785,7 @@ let prepare_evaluation = ? IncrEval.clean_reuse_map_of_env(env) : IncrEval.empty_reuse_map }; let state = ref(EvaluatorState.empty); + let theorem_inputs = ref(Id.Map.empty); /* The pre-pass only yields entries via reuse_check, which needs both a * non-empty prev and statics; otherwise it is a full walk of the program * for a guaranteed-empty result. */ @@ -570,11 +814,12 @@ let prepare_evaluation = ~reused_ids, ~parent_state=state, ~outbox, + ~theorem_inputs, ~current_top_id=None, env, d, ); - (state, result); + (state, theorem_inputs, result); }; let evaluate_and_limit = @@ -582,13 +827,14 @@ let evaluate_and_limit = ~step_limit: int, ~prev: EvaluatorState.incr_eval=IncrEval.empty, ~eval_info: EvalInfo.t=EvalInfo.empty, + ~statics: Statics.Map.t=Id.Map.empty, ~env, ~reuse_map: option(IncrEval.reuse_map)=?, ~outbox: option(ref(IncrEval.outbox(EvaluatorState.t)))=?, d: DHExp.t, ) : limited_result => { - let (state, result) = + let (state, theorem_inputs, result) = prepare_evaluation(~prev, ~eval_info, ~env, ~reuse_map, ~outbox, d); switch ( Trampoline.Yielding.run_slice( @@ -597,14 +843,27 @@ let evaluate_and_limit = ) ) { | SliceDone(x, _) => - LimitedCompleted((finish(~env, x), completed(state^))) + LimitedCompleted(( + finish(~env, x), + completed_with_proofs( + ~proofs=proof_statics(~statics, eval_info), + ~prev, + ~inputs=theorem_inputs^, + d, + state^, + ), + )) | SliceYielded(_) => StepLimitExceeded }; }; type yielding_evaluation = { env: Environment.t(Exp.t), + prev: EvaluatorState.incr_eval, + eval_info: EvalInfo.t, + elaborated: DHExp.t, state: ref(EvaluatorState.t), + theorem_inputs: ref(Id.Map.t(IncrEval.CheckedProofs.input)), outbox: ref(IncrEval.outbox(EvaluatorState.t)), continuation: Trampoline.Yielding.continuation(DHExp.t), }; @@ -624,7 +883,7 @@ let start_yielding_evaluation = ) : yielding_evaluation => { let outbox = ref(IncrEval.empty_outbox); - let (state, result) = + let (state, theorem_inputs, result) = prepare_evaluation( ~prev, ~eval_info, @@ -636,7 +895,11 @@ let start_yielding_evaluation = ); { env, + prev, + eval_info, + elaborated: d, state, + theorem_inputs, outbox, continuation: Trampoline.Yielding.start(result), }; @@ -657,7 +920,13 @@ let run_yielding_slice = | SliceDone(x, _) => EvaluationCompleted(( finish(~env=evaluation.env, x), - completed(evaluation.state^), + completed_with_proofs( + ~proofs=proof_statics(~statics=Id.Map.empty, evaluation.eval_info), + ~prev=evaluation.prev, + ~inputs=evaluation.theorem_inputs^, + evaluation.elaborated, + evaluation.state^, + ), )) | SliceYielded(continuation) => EvaluationYielded({ @@ -687,7 +956,7 @@ let evaluate_counting_work = d: DHExp.t, ) : ((Exp.t, EvaluatorState.t), int) => { - let (state, result) = + let (state, _, result) = prepare_evaluation( ~prev, ~eval_info, @@ -712,11 +981,12 @@ let evaluate = ( ~prev: EvaluatorState.incr_eval=IncrEval.empty, ~eval_info: EvalInfo.t=EvalInfo.empty, + ~statics: Statics.Map.t=Id.Map.empty, ~env, d: DHExp.t, ) : (Exp.t, EvaluatorState.t) => { - let (state, result) = + let (state, theorem_inputs, result) = prepare_evaluation( ~prev, ~eval_info, @@ -728,5 +998,14 @@ let evaluate = /* Must be sequenced before reading `state`: running the trampoline is what populates it, and tuple components are evaluated right-to-left. */ let value = finish(~env, Trampoline.run(result)); - (value, completed(state^)); + ( + value, + completed_with_proofs( + ~proofs=proof_statics(~statics, eval_info), + ~prev, + ~inputs=theorem_inputs^, + d, + state^, + ), + ); }; diff --git a/src/language/dynamics/Evaluator.rei b/src/language/dynamics/Evaluator.rei index a89d3efa83..99f07c5629 100644 --- a/src/language/dynamics/Evaluator.rei +++ b/src/language/dynamics/Evaluator.rei @@ -11,10 +11,23 @@ type limited_result = | LimitedCompleted((Exp.t, EvaluatorState.t)) | StepLimitExceeded; +/* Incremental evaluator. Reuses entries from `prev` for non-deferred + * sub-expressions whose elaboration (per `eval_info`) and co-ctx + * dependencies are unchanged. The defaults for `prev` and `eval_info` + * turn reuse off. + * + * `eval_info` is a serializable projection of the statics map (see + * `EvalInfo.of_info_map`); the full map holds closures and can't cross + * postMessage. Once evaluation is done, the proofs of the theorems it + * reached are checked, in the order it reached them, with the statics + * `eval_info` carries for a program with theorems, or with `statics`, + * the full map, when it is given. Each check is cached in the state's + * `incr_eval` and reused from `prev`. */ let evaluate: ( ~prev: EvaluatorState.incr_eval=?, ~eval_info: EvalInfo.t=?, + ~statics: Statics.Map.t=?, ~env: Environment.t(Exp.t), Exp.t ) => @@ -37,6 +50,7 @@ let evaluate_and_limit: ~step_limit: int, ~prev: EvaluatorState.incr_eval=?, ~eval_info: EvalInfo.t=?, + ~statics: Statics.Map.t=?, ~env: Environment.t(Exp.t), ~reuse_map: IncrEval.reuse_map=?, ~outbox: ref(IncrEval.outbox(EvaluatorState.t))=?, @@ -62,3 +76,24 @@ let yielding_step_count: yielding_evaluation => int; let drain_streaming_outbox: yielding_evaluation => IncrEval.outbox(EvaluatorState.t); + +/* Checking theorems' proofs. */ +module Proofs: { + /* The steps a `step` proof step passes through silently from an + * expression (auto-hidden steps and `VarLookup`s), each as (input, + * justification, output), and the expression they reach. None if there + * are more than `max_steps`. */ + let advance_hidden: + (~max_steps: int=?, ~env: Environment.t(Exp.t), Exp.t) => + option((list((Exp.t, string, Exp.t)), Exp.t)); + + /* One `step` proof step: the silent steps, one visible step, and the + * silent steps after it. The checker takes its evaluation steps with + * this. */ + let step: ProofCheck.step_fn; + + /* The proof map of `proof` checked against `goal` in `ctx`. */ + let check_proof: + (~statics: ProofStatics.t, ~ctx: SemanticCtx.t, ~goal: Exp.t, Proof.t) => + ProofMap.t; +}; diff --git a/src/language/dynamics/IncrEval.re b/src/language/dynamics/IncrEval.re index 4c5fb746bc..61debee818 100644 --- a/src/language/dynamics/IncrEval.re +++ b/src/language/dynamics/IncrEval.re @@ -44,9 +44,32 @@ type entry('state) = { state: 'state, }; +/* What a theorem's check depends on besides the values its proof reads: + * the theorem, with its body dropped, the theorems it can cite and their + * verdicts. */ +[@deriving (show({with_path: false}), sexp, yojson)] +type proof_key = { + theorem: Exp.t, + namespace: ProofStatics.namespace, + verdicts: list((Id.t, SemanticCtx.verdict)), +}; + +/* A theorem's proof as checked, by the theorem's id. Unlike the theorem's + * own entry it doesn't depend on the theorem's body, which holds every + * later theorem. */ +[@deriving (show({with_path: false}), sexp, yojson)] +type checked_proof = { + key: proof_key, + /* The provenance of the variables the theorem names, when evaluation + * last reached it rather than replaying it. */ + prev_reuse_map: option(reuse_map), + proof_map: ProofMap.t, +}; + [@deriving (show({with_path: false}), sexp, yojson)] type t('state) = { entries: Id.Map.t(entry('state)), + proofs: Id.Map.t(checked_proof), /* Steps of the evaluation that produced this cache. */ steps: int, }; @@ -65,6 +88,7 @@ type outbox('state) = { let empty: t('state) = { entries: Id.Map.empty, + proofs: Id.Map.empty, steps: 0, }; @@ -78,7 +102,8 @@ let outbox_of_completed = (completed: t('state)): outbox('state) => { current: None, }; -let is_empty = (incr: t('state)): bool => Id.Map.is_empty(incr.entries); +let is_empty = (incr: t('state)): bool => + Id.Map.is_empty(incr.entries) && Id.Map.is_empty(incr.proofs); let outbox_is_empty = (outbox: outbox('state)): bool => is_empty(outbox.completed) && Option.is_none(outbox.current); @@ -114,6 +139,8 @@ let add_stream = (stream: t('state), incr: t('state)): t('state) => { incr.entries, stream.entries, ), + proofs: + Id.Map.union((_, _old, new_) => Some(new_), incr.proofs, stream.proofs), }; let merge_outbox = @@ -191,10 +218,10 @@ let equal_reuse_map = (a: reuse_map, b: reuse_map): bool => let is_runtime_dependency = (name: string): bool => !String.equal(name, "$hole"); -let restrict_to_co_ctx = (reuse_map: reuse_map, co_ctx: CoCtx.t): reuse_map => +let restrict_to_names = (reuse_map: reuse_map, names: list(Var.t)): reuse_map => List.fold_left( ~f= - (projected, (name, _)) => + (projected, name) => if (!is_runtime_dependency(name)) { projected; } else { @@ -204,9 +231,12 @@ let restrict_to_co_ctx = (reuse_map: reuse_map, co_ctx: CoCtx.t): reuse_map => }; }, ~init=empty_reuse_map, - VarMap.to_list(co_ctx), + names, ); +let restrict_to_co_ctx = (reuse_map: reuse_map, co_ctx: CoCtx.t): reuse_map => + restrict_to_names(reuse_map, List.map(~f=fst, VarMap.to_list(co_ctx))); + let reuse_map_for_co_ctx = (reuse_map: reuse_map, co_ctx: CoCtx.t): option(reuse_map) => List.fold_left( @@ -371,3 +401,123 @@ let reuse_check = Some(entry); }; + +/* Reusing a theorem's checked proof. It is reused while its key is the + * same, the theorem's ids included, since the proof map is keyed by them, + * and the values the theorem names are: where evaluation reached it, they + * have the same provenance. A theorem replayed from a reused node has + * none to compare, but the node was reused only because they are the + * same. */ +module CheckedProofs = { + /* What evaluation found where it reached a theorem: the provenance of + * the variables it names, or, inside a function call, nothing, since + * the theorem is checked afresh each time. */ + [@deriving (show({with_path: false}), sexp, yojson)] + type input = + | Reached(reuse_map) + | InCall; + + /* Every variable name in the theorem, bound or free, as names it might + * read from the env. */ + let reached = (reuse_map: reuse_map, theorem: Exp.t): input => { + let names = ref([]); + let _: Exp.t = + Exp.map_term( + ~f_exp= + (continue, e) => { + switch (Exp.term_of(e)) { + | Var(x) => names := [x, ...names^] + | _ => () + }; + continue(e); + }, + theorem, + ); + Reached(restrict_to_names(reuse_map, names^)); + }; + + let key = (~namespace, ~verdicts, theorem: Exp.t): proof_key => { + theorem: + switch (theorem.term) { + | Theorem(p, goal, proof, _) => { + ...theorem, + term: Theorem(p, goal, proof, Exp.temp(EmptyHole)), + } + | _ => theorem + }, + namespace, + verdicts, + }; + + let same_key = (a: proof_key, b: proof_key): bool => { + let ids = (e: Exp.t): list(Id.t) => { + let acc = ref([]); + let f = (continue, t: IdTagged.t(_)) => { + acc := [IdTagged.rep_id(t), ...acc^]; + continue(t); + }; + let _: Exp.t = + Exp.map_term( + ~f_exp=f, + ~f_pat=f, + ~f_typ=f, + ~f_tpat=f, + ~f_rul=f, + ~f_proof=f, + e, + ); + acc^; + }; + Exp.fast_equal_with_lexemes(a.theorem, b.theorem) + && List.equal(Id.equal, ids(a.theorem), ids(b.theorem)) + && TheoremNamespace.same(a.namespace, b.namespace) + && Poly.equal(a.verdicts, b.verdicts); + }; + + let find = + (~prev: t('state), ~input: option(input), id: Id.t, key: proof_key) + : option(ProofMap.t) => + switch (Id.Map.find_opt(id, prev.proofs), input) { + | (Some(checked), None) when same_key(checked.key, key) => + Some(checked.proof_map) + | ( + Some({prev_reuse_map: Some(prev_reuse_map), _} as checked), + Some(Reached(reuse_map)), + ) + when + same_key(checked.key, key) + && equal_reuse_map(prev_reuse_map, reuse_map) => + Some(checked.proof_map) + | (Some(_), _) + | (None, _) => None + }; + + /* The entry to cache for a theorem checked as `proof_map`. */ + let entry = + ( + ~prev: t('state), + ~input: option(input), + id: Id.t, + key: proof_key, + proof_map: ProofMap.t, + ) + : option(checked_proof) => + switch (input) { + | Some(InCall) => None + | Some(Reached(reuse_map)) => + Some({ + key, + prev_reuse_map: Some(make_clean(reuse_map)), + proof_map, + }) + | None => + Some({ + key, + prev_reuse_map: + Option.bind(Id.Map.find_opt(id, prev.proofs), ~f=checked => + checked.prev_reuse_map + ), + proof_map, + }) + }; +}; diff --git a/src/language/dynamics/Substitution.re b/src/language/dynamics/Substitution.re index ded86060b1..fa1462c10a 100644 --- a/src/language/dynamics/Substitution.re +++ b/src/language/dynamics/Substitution.re @@ -69,9 +69,9 @@ let rec in_exp = (env: Environment.t(Exp.t), exp: Exp.t) => | FixF(p, e, None) => let (env', p') = in_pat(env, env, p); FixF(p', in_exp(env', e), None) |> rewrap; - | Theorem(p, e1, e2) => + | Theorem(p, e1, pf, e2) => let (env', p') = in_pat(env, env, p); - Theorem(p', in_exp(env, e1), in_exp(env', e2)) |> rewrap; + Theorem(p', in_exp(env, e1), pf, in_exp(env', e2)) |> rewrap; | Forall(pat, e) => let (env', pat') = in_pat(env, env, pat); Forall(pat', in_exp(env', e)) |> rewrap; @@ -112,7 +112,6 @@ let rec in_exp = (env: Environment.t(Exp.t), exp: Exp.t) => | BuiltinFun(_) | Asc(_) | LivelitName(_) - | ProofObject(_) | Undefined | Module(_) | ModuleExp(_) => cont(e) @@ -124,7 +123,7 @@ let rec in_exp = (env: Environment.t(Exp.t), exp: Exp.t) => // Updates a pattern to avoid variable capture and in_pat = ( - env_outer: Environment.t(Exp.t), // The environment outside the binding form, used in ProofOfs + env_outer: Environment.t(Exp.t), // The environment outside the binding form env_acc: Environment.t(Exp.t), // The environment being built up to avoid capture p: Pat.t, ) @@ -231,10 +230,47 @@ and in_typ = (env: Environment.t(Exp.t), typ: Typ.t) => | Poly(_, _) | ProdProjection(_, _) | ProdExtension(_, _) - | ProofOf(_) | Sig(_) | DrvQuoteTy(_) => cont(t) }; }, typ, ); + +/* The environment for `in_exp` that substitutes `bindings` into `into` + * and nothing else. Every other variable free in `into` or in a bound + * value maps to itself, which is what lets `in_exp` rename a binder of + * `into` that would capture it. */ +let env_for = + (bindings: list(Environment.binding(Exp.t)), ~into: Exp.t) + : Environment.t(Exp.t) => { + let names = (e: Exp.t): list(Var.t) => { + let found = ref([]); + let _: Exp.t = + Exp.map_term( + ~f_exp= + (continue, e) => { + switch (Exp.term_of(e)) { + | Var(y) => found := [y, ...found^] + | _ => () + }; + continue(e); + }, + e, + ); + found^; + }; + let values = List.map(~f=snd, bindings); + let free = + List.dedup_and_sort( + ~compare=String.compare, + List.concat_map(~f=names, [into, ...values]), + ) + |> List.filter(~f=y => + !List.Assoc.mem(bindings, y, ~equal=String.equal) + && List.exists(~f=Exp.occurs_free_any([y]), [into, ...values]) + ); + Environment.of_bindings( + List.map(~f=y => (y, Exp.fresh(Var(y))), free) @ bindings, + ); +}; diff --git a/src/language/dynamics/state/EvaluatorState.re b/src/language/dynamics/state/EvaluatorState.re index c1912fd634..a0a3c18a7c 100644 --- a/src/language/dynamics/state/EvaluatorState.re +++ b/src/language/dynamics/state/EvaluatorState.re @@ -40,6 +40,7 @@ type t = { obs_trace: list(ObsTrace.event), step_count: int, incr_eval, + proof_map: ProofMap.t /* Incoming/outgoing expressions per proof sub-term id */ } // Note[Matt]: There are probably memory improvements to be made here by untying this knot. @@ -68,6 +69,7 @@ let empty: t = { step_count: 0, theorems: [], incr_eval: IncrEval.empty, + proof_map: ProofMap.empty, }; let empty_at = (step_count: int): t => { @@ -135,6 +137,7 @@ let append = (base: t, ext: t): t => { * carry through. */ obs_opens: base.obs_opens, obs_trace, + proof_map: ProofMap.union(base.proof_map, ext.proof_map), }; }; @@ -178,6 +181,8 @@ let get_probes = ({probes, _}) => probes; let get_theorems = ({theorems, _}) => theorems; +let get_proof_map = ({proof_map, _}) => proof_map; + let get_incr_eval = ({incr_eval, _}: t) => incr_eval; let add_incr_entry = (state: t, id: Id.t, entry: IncrEval.entry(t)): t => { @@ -185,6 +190,13 @@ let add_incr_entry = (state: t, id: Id.t, entry: IncrEval.entry(t)): t => { incr_eval: IncrEval.add_entry(id, entry, state.incr_eval), }; +let merge_proof_map = ({proof_map, _} as es, pm) => { + { + ...es, + proof_map: ProofMap.union(proof_map, pm), + }; +}; + let update = ( eval_info: EvalInfo.t, diff --git a/src/language/dynamics/state/ProofMap.re b/src/language/dynamics/state/ProofMap.re new file mode 100644 index 0000000000..9a954daa5c --- /dev/null +++ b/src/language/dynamics/state/ProofMap.re @@ -0,0 +1,157 @@ +open Util; + +/* For each proof sub-term the checker reaches, keyed by its `rep_id`: the + * goal going into the step and the goal coming out, the marks that the + * editor shows on that node, and the scope it was checked in. + * + * `None` on either side means checking broke down here: the incoming goal + * couldn't be computed because an earlier step failed, or this step's + * rule didn't apply. */ + +[@deriving (show({with_path: false}), sexp, yojson)] +type entry = { + incoming: option(Exp.t), + auto_incoming: list((string, Exp.t)), + auto_outgoing: list((Exp.t, string)), + outgoing: option(Exp.t), + marks: list(ProofMark.t), + /* Obligations incurred by this step (e.g. an `assume`'s hypothesis), + * with their discharge provenance. Empty for most steps. */ + obligations: list(Obligation.t), + /* The scope the checker checked this step in: the variables and facts + * a step written here can use. A form's body is recorded under the + * body's own id, with the scope the form opens for it. */ + ctx: SemanticCtx.t, +}; + +[@deriving (show({with_path: false}), sexp, yojson)] +type t = Id.Map.t(entry); + +let empty: t = Id.Map.empty; + +let add = (id: Id.t, entry: entry, pm: t): t => Id.Map.add(id, entry, pm); + +let lookup = (id: Id.t, pm: t): option(entry) => Id.Map.find_opt(id, pm); + +let marks_of = (id: Id.t, pm: t): list(ProofMark.t) => + switch (lookup(id, pm)) { + | Some({marks, _}) => marks + | None => [] + }; + +let error_ids = (pm: t): list(Id.t) => + Id.Map.fold( + (id, entry, acc) => List.is_empty(entry.marks) ? acc : [id, ...acc], + pm, + [], + ); + +/* Union prefers the right-hand side on overlap; used to merge a freshly- + * produced proof map into the accumulated state. */ +let union = (a: t, b: t): t => Id.Map.union((_id, _l, r) => Some(r), a, b); + +/* No entry in the proof's subtree carries a mark, a `have`'s subproof + * included. The checker passes the goal through a failed step unchanged + * (`ProofCheck.check`), so a `true` outgoing goal alone doesn't mean the + * proof holds. */ +let rec proof_is_clean = (pm: t, proof: Proof.t): bool => + List.is_empty(marks_of(Proof.rep_id(proof), pm)) + && List.for_all(~f=proof_is_clean(pm), Proof.children(proof)); + +let outgoing_is = (b: bool, pm: t, proof: Proof.t): bool => + switch (lookup(Proof.rep_id(proof), pm)) { + | Some({outgoing: Some(e), _}) => + Exp.fast_equal(e, Exp.temp(Atom(Bool(b)))) + | Some({outgoing: None, _}) + | None => false + }; + +/* Every case of a split in the subtree reaches `true`, and so does the + * body of every `assume` that steps to `true`. Both step to `true` before + * their bodies are finished: a split as soon as its cases cover the + * scrutinee, an `assume` of the goal's antecedent at once. */ +let rec cases_closed = (pm: t, proof: Proof.t): bool => + ( + switch (proof.term) { + | Cases(_, cases) + | Induction(_, cases) => + List.for_all(~f=((_, body)) => outgoing_is(true, pm, body), cases) + | Assume(_, _, body) => + !outgoing_is(true, pm, proof) || outgoing_is(true, pm, body) + | Invalid(_) + | EmptyHole + | MultiHole(_) + | Seq(_) + | Parens(_) + | AxiomStep(_) + | AlgebriteStep(_) + | EvalStep + | Focus(_) + | Forall(_) + | Funext(_) + | Alias(_) + | Generalize(_) + | Revert(_) + | Have(_) => true + } + ) + && List.for_all(~f=cases_closed(pm), Proof.children(proof)); + +/* UI status derived from a proof map for a given proof term: + * - `Some(true)` (proven) iff the proof's outgoing expression is the + * literal `true`, no step in the proof is broken and every induction + * case reaches `true`. + * - `Some(false)` (disproven) iff the proof's outgoing expression is the + * literal `false` and no step in the proof is broken. + * - `None` otherwise — incomplete proofs (holes, open induction cases), + * broken steps (marks in the subtree), or any other non-boolean + * outgoing. A + * concrete-but-incorrect proof is not a disproof. + * + * Mirrors the stepper's expression-validity convention + * (`true` / `false` / unknown). */ +let status_of_proof = (pm: t, proof: Proof.t): option(bool) => + if (!proof_is_clean(pm, proof) || !cases_closed(pm, proof)) { + None; + } else if (outgoing_is(true, pm, proof)) { + Some(true); + } else if (outgoing_is(false, pm, proof)) { + Some(false); + } else { + None; + }; + +/* All obligations recorded in the proof subtree, in proof-term order. */ +let rec obligations_of_proof = (pm: t, proof: Proof.t): list(Obligation.t) => { + let here = + switch (lookup(Proof.rep_id(proof), pm)) { + | Some({obligations, _}) => obligations + | None => [] + }; + here @ List.concat_map(~f=obligations_of_proof(pm), Proof.children(proof)); +}; + +/* The still-undischarged obligations in the proof subtree. */ +let pending_obligations = (pm: t, proof: Proof.t): list(Obligation.t) => + obligations_of_proof(pm, proof) |> List.filter(~f=Obligation.is_pending); + +/* `status_of_proof`, refined by obligations: + * - Proven / Refuted: `status_of_proof` is `true`/`false` and nothing in + * the subtree is pending; + * - ProvenModulo(obs): proven, but the obligations `obs` are pending; + * - Incomplete: everything else. */ +[@deriving (show({with_path: false}), sexp, yojson)] +type full_status = + | Proven + | Refuted + | ProvenModulo(list(Obligation.t)) + | Incomplete; + +let full_status_of_proof = (pm: t, proof: Proof.t): full_status => + switch (status_of_proof(pm, proof), pending_obligations(pm, proof)) { + | (Some(true), []) => Proven + | (Some(true), pending) => ProvenModulo(pending) + | (Some(false), []) => Refuted + | (Some(false), _) + | (None, _) => Incomplete + }; diff --git a/src/language/dynamics/stepper/EvalCtx.re b/src/language/dynamics/stepper/EvalCtx.re index 7fc3b1cacd..fd680318a2 100644 --- a/src/language/dynamics/stepper/EvalCtx.re +++ b/src/language/dynamics/stepper/EvalCtx.re @@ -8,7 +8,7 @@ type term = | Seq2(DHExp.t, t) | Let1(Pat.t, t, DHExp.t) | Let2(Pat.t, DHExp.t, t) - | Theorem(Pat.t, DHExp.t, t) + | Theorem(Pat.t, DHExp.t, Proof.t, t) | Fun(Pat.t, t, option(Typ.t), option(Var.t)) | FixF(Pat.t, t, option(Environment.t(Exp.t))) | TypAp(t, Typ.t) @@ -152,9 +152,9 @@ let rec compose = (ctx: t, d: DHExp.t): DHExp.t => { | Let2(dp, d1, ctx) => let d = compose(ctx, d); Let(dp, d1, d) |> wrap; - | Theorem(dp, d1, ctx) => + | Theorem(dp, d1, pf, ctx) => let d = compose(ctx, d); - Theorem(dp, d1, d) |> wrap; + Theorem(dp, d1, pf, d) |> wrap; | Fun(dp, ctx, typ, v) => let d = compose(ctx, d); Fun(dp, d, typ, v) |> wrap; diff --git a/src/language/dynamics/stepper/EvaluatorStep.re b/src/language/dynamics/stepper/EvaluatorStep.re index 70c68d8e9d..3543f4f83b 100644 --- a/src/language/dynamics/stepper/EvaluatorStep.re +++ b/src/language/dynamics/stepper/EvaluatorStep.re @@ -31,7 +31,9 @@ module EvalObj = { let persist = (obj: t): persistent => { let full_exp = EvalCtx.compose(obj.ctx, obj.d_loc); { - exp_idx: ProofHacks.exp_idx(obj.d_loc, full_exp), + exp_idx: + Occurrence.index(obj.d_loc, full_exp) + |> OptUtil.get_or_fail("EvaluatorStep.persist: d_loc not found"), at_exp: obj.d_loc, }; }; @@ -95,9 +97,9 @@ let rec matches = | Let2(d1, d2, ctx) => let+ ctx = matches(env, flt, ctx, exp, act, idx); Let2(d1, d2, ctx) |> rewrap; - | Theorem(dp, d1, ctx) => + | Theorem(dp, d1, pf, ctx) => let+ ctx = matches(env, flt, ctx, exp, act, idx); - Theorem(dp, d1, ctx) |> rewrap; + Theorem(dp, d1, pf, ctx) |> rewrap; | Fun(dp, ctx, ty, name) => // TODO: Should this env include the bound variables? let+ ctx = matches(env, flt, ctx, exp, act, idx); @@ -426,8 +428,25 @@ let get_status = (~settings: CoreSettings.t, exp, env) => { }; }; +let all_steps = (~settings: CoreSettings.t, exp, env) => + decompose(exp, env) + |> List.map(~f=x => + snd(should_hide_eval_obj(~settings=settings.evaluation, x)) + ); + let get_step_id = (step: step): Id.t => step.d_loc |> DHExp.rep_id; +let is_at_root = (step: step): bool => { + let rec at_root = (ctx: EvalCtx.t) => + switch (ctx) { + | Mark => true + | Term({term: Parens(ctx) | Asc(ctx, _) | Closure(_, ctx), _}) => + at_root(ctx) + | Term(_) => false + }; + at_root(step.ctx); +}; + let get_step_kind = (step: step): step_kind => step.knd; let take_step = (step: EvalObj.t) => { @@ -460,7 +479,7 @@ let refresh_step = decompose(exp, env) |> List.map(~f=should_hide_eval_obj(~settings=settings.evaluation)); // NOTE: should_hide_eval_obj actually changes the eval obj to do filter bookkeeping!!! let* desired_id = - ProofHacks.nth_exp(step.at_exp, step.exp_idx, exp) + Occurrence.nth(step.at_exp, step.exp_idx, exp) |> Option.map(~f=IdTagged.ids); let* (h, x) = List.find( diff --git a/src/language/dynamics/stepper/EvaluatorStep.rei b/src/language/dynamics/stepper/EvaluatorStep.rei index b1a7be7d4c..915b034220 100644 --- a/src/language/dynamics/stepper/EvaluatorStep.rei +++ b/src/language/dynamics/stepper/EvaluatorStep.rei @@ -16,6 +16,11 @@ type status = let get_status: (~settings: CoreSettings.t, Exp.t, Environment.t(Exp.t)) => status; +/* Every step the expression can take, including those `get_status` would + take automatically. */ +let all_steps: + (~settings: CoreSettings.t, Exp.t, Environment.t(Exp.t)) => list(step); + let refresh_step: (~settings: CoreSettings.t, Exp.t, Environment.t(Exp.t), persistent) => option((FilterAction.action, step)); @@ -27,4 +32,8 @@ let take_step: step => option(Exp.t); let get_step_id: step => Id.t; +/* Whether the step reduces the whole expression it was found in, up to + parentheses, ascriptions and closures. */ +let is_at_root: step => bool; + let get_step_kind: step => Transition.step_kind; diff --git a/src/language/dynamics/transition/Ascriptions.re b/src/language/dynamics/transition/Ascriptions.re index 12878395cb..1bce1c763d 100644 --- a/src/language/dynamics/transition/Ascriptions.re +++ b/src/language/dynamics/transition/Ascriptions.re @@ -203,10 +203,6 @@ let rec transition = (~recursive=false, d: DHExp.t): option(DHExp.t) => { | (Constructor(_, Some(Some(t))), t') when unrolled_consistent(t, t' |> Typ.temp) => Some(e) - | (ProofObject(e1), ProofOf(e2)) when Exp.fast_equal(e1, e2) => - Some( - IdTagged.fast_copy(DHExp.rep_id(e), ProofObject(e1) |> DHExp.fresh), - ) | (Test(_), Prod([])) => Some(e) // These are non-value cases we're handling to process ascriptions as early as possible | (BinOp(bin_op, _, _), _) => @@ -314,7 +310,6 @@ let rec transition = (~recursive=false, d: DHExp.t): option(DHExp.t) => { | (Test(_), _) | (HintedTest(_), _) | (Cons(_), _) - | (ProofObject(_), _) | (Constructor(_), _) | (Module(_), _) | (ModuleExp(_), _) => None diff --git a/src/language/dynamics/transition/Transition.re b/src/language/dynamics/transition/Transition.re index 02c28fa954..5342e580e6 100644 --- a/src/language/dynamics/transition/Transition.re +++ b/src/language/dynamics/transition/Transition.re @@ -562,12 +562,15 @@ module Transition = (EV: EV_MODE) => { }); }; - | Theorem({term: Var(n), _} as dp, e, d1) => + | Theorem({term: Var(n), _} as dp, e, _pf, d1) => let. _ = otherwise(env, d); let e' = Substitution.in_exp(env, e); - let env' = Environment.extend(env, (n, generated(ProofObject(e')))); + /* A theorem is a judgment, not a value, so its name binds nothing + in `env`; citations resolve through the theorem namespace in + `Ctx`. The statement is recorded as a side effect for the theorem + stepper (`Theorems.re`). */ Step({ - expr: subst_env(env', d1), + expr: subst_env(env, d1), side_effects: [ RecordTheorem(DHExp.rep_id(d), n, env, e'), RecordPatMatch({ @@ -582,21 +585,6 @@ module Transition = (EV: EV_MODE) => { | Theorem(_) => let. _ = otherwise(env, d); Indet; - | ProofObject(e) => - let. _ = otherwise(env, d); - let e' = Substitution.in_exp(env, e); - switch (mode) { - | `Substitution => Value - | `Environment => - Step({ - expr: d, - side_effects: [ - RecordTheorem(DHExp.rep_id(d), "", env, e'), - ], - kind: RecordTheorem, - is_value: true, - }) - }; // Note[Matt]: we could make this spin, but for now it's indet | Forall(_) => let. _ = otherwise(env, d); @@ -781,11 +769,7 @@ module Transition = (EV: EV_MODE) => { | DoesNotMatch => Indet | Matches(added_env) => Step({ - expr: - subst_env( - Environment.add_bindings(Environment.empty, added_env), - d3, - ), + expr: subst_env(Substitution.env_for(added_env, ~into=d3), d3), side_effects: [ RecordStackFrame(fn_name, Some(d2'), fn_def_id), RecordPatMatch({ @@ -830,7 +814,15 @@ module Transition = (EV: EV_MODE) => { RecordStackFrame(Some(ident), Some(d2'), None), ], kind: BuiltinAp(ident), - is_value: false, + /* An off-domain application (`int_of_string("abc")`) + steps to a `DynamicErrorHole` around itself. Mark that + step final, as the UnOp/BinOp error branches do, or the + builtin would be re-applied forever. */ + is_value: + switch (DHExp.term_of(expr)) { + | DynamicErrorHole(_) => true + | _ => false + }, }) | None => Indet }; @@ -940,6 +932,9 @@ module Transition = (EV: EV_MODE) => { expr, side_effects: [], kind: UnOp(op), + /* An error hole is indet, not a value, but the step must be + final: otherwise the hole's payload steps to a fresh error + hole forever. */ is_value: true, }); }; @@ -975,6 +970,24 @@ module Transition = (EV: EV_MODE) => { kind: BinOp(Bool(Or)), is_value: false, }); + /* Implication short-circuits left to right: a false antecedent gives + `true` without evaluating the consequent. */ + | BinOp(Bool(Implies), d1, d2) => + let. _ = otherwise(env, d1 => BinOp(Bool(Implies), d1, d2) |> rewrap) + and. d1' = + req_final( + req(env), + d1 => BinOp1(Bool(Implies), d1, d2) |> wrap_ctx, + d1, + ); + let.wrap_closure _ = (env, BinOp(Bool(Implies), d1', d2) |> rewrap); + let-unbox b1 = (Atom(Bool), d1'); + Step({ + expr: b1 ? asc(d2, IdTagged.FreshGrammar.Typ.bool()) : bool(true), + side_effects: [], + kind: BinOp(Bool(Implies)), + is_value: false, + }); | BinOp(op, d1, d2) => let. _ = otherwise(env, (d1, d2) => BinOp(op, d1, d2) |> rewrap) and. d1 = @@ -1028,6 +1041,9 @@ module Transition = (EV: EV_MODE) => { expr, side_effects: [], kind: BinOp(op), + /* An error hole is indet, not a value, but the step must be + final: otherwise the hole's payload steps to a fresh error + hole forever. */ is_value: true, }); }; @@ -1155,14 +1171,49 @@ module Transition = (EV: EV_MODE) => { req_final(req(env), d1 => ListConcat1(d1, d2) |> wrap_ctx, d1) and. d2' = req_final(req(env), d2 => ListConcat2(d1, d2) |> wrap_ctx, d2); - let-unbox ds1 = (ListLit, d1'); - let-unbox ds2 = (ListLit, d2'); - Step({ - expr: list_lit(ds1 @ ds2), - side_effects: [], - kind: ListConcat, - is_value: true, - }); + switch (Unboxing.unbox(ListLit, d1'), Unboxing.unbox(ListLit, d2')) { + /* Ground fast path: both sides are known-length literals, so a single + step concatenates them into one literal. */ + | (Matches(ds1), Matches(ds2)) => + Step({ + expr: list_lit(ds1 @ ds2), + side_effects: [], + kind: ListConcat, + is_value: true, + }) + /* Otherwise use the defining equations of @, which only need the + left side in constructor form: + [] @ ys --> ys + (x :: xs) @ ys --> x :: (xs @ ys) + so @ steps when the right side or the cons tail is only final, + e.g. a quantified variable in a proof. There is no right-unit + rule: `m @ []` needs induction, so it stays stuck. */ + | _ => + switch (Unboxing.unbox(ListLitn(0), d1')) { + | Matches(_) => + Step({ + expr: d2', + side_effects: [], + kind: ListConcat, + is_value: false, + }) + | DoesNotMatch + | IndetMatch => + switch (Unboxing.unbox(Cons, d1')) { + | Matches((x, xs)) => + Step({ + expr: cons(x, list_concat(xs, d2')), + side_effects: [], + kind: ListConcat, + is_value: false, + }) + /* Left side is not a list constructor (a variable or a hole): no + defining equation applies. */ + | DoesNotMatch + | IndetMatch => Indet + } + } + }; | ListLit(ds) => let. _ = otherwise(env, ds => ListLit(ds) |> rewrap) and. _ = diff --git a/src/language/dynamics/transition/Unboxing.re b/src/language/dynamics/transition/Unboxing.re index 1ef28ee267..e0da1dba0d 100644 --- a/src/language/dynamics/transition/Unboxing.re +++ b/src/language/dynamics/transition/Unboxing.re @@ -75,9 +75,6 @@ let rec unbox: type a. (unbox_request(a), DHExp.t) => unboxed(a) = | (_, Constructor(c, _)) when String.is_prefix(c, ~prefix="$") => IndetMatch - /* proofs can also have any type, but are indet */ - | (_, ProofObject(_)) => IndetMatch - /* TupLabels can be anything except for tuplabels with unmatching labels */ | (TupLabel(tuplabel), TupLabel(_, e)) => if (Option.equal( diff --git a/src/language/grammar/FormId.re b/src/language/grammar/FormId.re index 296c3c472b..9c9db9c0d1 100644 --- a/src/language/grammar/FormId.re +++ b/src/language/grammar/FormId.re @@ -94,8 +94,6 @@ type family = | ApExpTyp | Case | Test - | ProofOf - | ProofObject | HintedTest | Fun | Fix @@ -140,7 +138,30 @@ type family = | ModType | ModuleExp | ModuleMod - | SigLet; + | SigLet + /* Proof steps. Typing a leading delimiter expands to the first family + whose label starts with it, so each plain step comes before the + variants that share its leading token (`assume` before + `assume ... as`, `revert` before `revert ... with`). */ + | ProofForall + | ProofFunext + | ProofAssume + | ProofGeneralize + | ProofRevert + | ProofAxiom + | ProofRevertWith + | ProofAxiomWith + | RewriteBack + | ProofAlgebrite + | ProofEval + | ProofCases + | ProofInduction + | ProofHave + | ProofHaveNamed + | ProofAssumeNamed + | ProofAlias + | ProofFocus + | ProofFocusAt; /* A form identity, sort-free: label is derived from the form alone; * the mold is derived from (form, sort) where sort is the tile's @@ -211,8 +232,6 @@ let label_of_family: family => Label.t = | ApExpTyp => ["@<", ">"] | Case => ["case", "end"] | Test => ["test", "end"] - | ProofOf => ["proof_of", "end"] - | ProofObject => ["proof_object", "end"] | HintedTest => ["hint", "test", "end"] | Fun => ["fun", "->"] | Fix => ["fix", "->"] @@ -250,14 +269,33 @@ let label_of_family: family => Label.t = | Impl => ["==>"] | If => ["if", "then", "else"] | Let => ["let", "=", "in"] - | Theorem => ["theorem", "=", "in"] + | Theorem => ["theorem", "=", "proof", "in"] | TypeAlias => ["type", "=", "in"] | ModBody => Token.mod_lbl | ModLet => ["let", "="] | ModType => ["type", "="] | ModuleExp => ["module", "=", "in"] | ModuleMod => ["module", "="] - | SigLet => ["let"]; + | SigLet => ["let"] + | ProofForall => ["forall", "=>"] + | ProofFunext => ["funext", "=>"] + | ProofAssume => ["assume", "=>"] + | ProofGeneralize => ["generalize", "=>"] + | ProofRevert => ["revert", "=>"] + | ProofAxiom => ["rewrite", "end"] + | ProofRevertWith => ["revert", "with", "=", "=>"] + | ProofAxiomWith => ["rewrite", "with", "=", "end"] + | RewriteBack => ["<-"] + | ProofAlgebrite => ["algebra", "end"] + | ProofEval => ["step"] + | ProofCases => ["cases", "end"] + | ProofInduction => ["induction", "end"] + | ProofHave => ["have", "proof", "=>"] + | ProofHaveNamed => ["have", "=", "proof", "=>"] + | ProofAssumeNamed => ["assume", "=", "=>"] + | ProofAlias => ["alias", "=", "=>"] + | ProofFocus => ["from", "do", "end"] + | ProofFocusAt => ["from", "at", "do", "end"]; let label_of: t => Label.t = fun @@ -311,7 +349,8 @@ let float_op_family: Operators.op_bin_float => family = let bool_op_family: Operators.op_bin_bool => family = fun | And => LogicalAnd - | Or => LogicalOr; + | Or => LogicalOr + | Implies => Impl; let string_op_family: Operators.op_bin_string => family = fun diff --git a/src/language/proof/Axioms.re b/src/language/proof/Axioms.re index 4277079802..1834f12914 100644 --- a/src/language/proof/Axioms.re +++ b/src/language/proof/Axioms.re @@ -1,20 +1,169 @@ +/* Built-in axioms available to every proof, applied through the ordinary + * axiom step with no dedicated checker logic. + * + * Soundness: every equation must hold under the symmetric (strong) Kleene + * reading of the connectives over the flat domain {false, err/⊥ (= U), + * true}. So `(a && false) == false` is valid (U ∧ F = F), but excluded + * middle `(a || !a) == true` is not (U ∨ U = U) and is absent, as is + * anything else that needs definedness. + * + * Keep the name list in sync with `Statics.initial_theorems`. */ + +let var = (x: string): Exp.t => Var(x) |> Exp.fresh; +let tt: Exp.t = Atom(Bool(true)) |> Exp.fresh; +let ff: Exp.t = Atom(Bool(false)) |> Exp.fresh; +let band = (a: Exp.t, b: Exp.t): Exp.t => + BinOp(Bool(And), a, b) |> Exp.fresh; +let bor = (a: Exp.t, b: Exp.t): Exp.t => BinOp(Bool(Or), a, b) |> Exp.fresh; +let (&&&) = band; +let (|||) = bor; +let (==>>) = (a: Exp.t, b: Exp.t): Exp.t => + BinOp(Bool(Implies), a, b) |> Exp.fresh; +let neg = (a: Exp.t): Exp.t => UnOp(Bool(Not), a) |> Exp.fresh; +let eq = (a: Exp.t, b: Exp.t): Exp.t => + BinOp(Poly(Equals), a, b) |> Exp.fresh; +let forall = (x: string, body: Exp.t): Exp.t => + Forall(Var(x) |> Pat.fresh, body) |> Exp.fresh; + +/* The innermost binder is last in `xs`. */ +let foralls = (xs: list(string), body: Exp.t): Exp.t => + List.fold_right(~f=forall, xs, ~init=body); + +/* Closure-lemma builders. They use the operators user code parses to, + * so the lemmas match user goals and the conditions DomainConditions + * builds: `*`/`+`/`**`/`>`/`<`/`>=` parse to the Int class and `!=` to + * Poly(NotEquals). There are no SInt or Nat versions of the lemmas. */ +let mul = (a: Exp.t, b: Exp.t): Exp.t => + BinOp(Int(Times), a, b) |> Exp.fresh; +let add = (a: Exp.t, b: Exp.t): Exp.t => + BinOp(Int(Plus), a, b) |> Exp.fresh; +let pow = (a: Exp.t, b: Exp.t): Exp.t => + BinOp(Int(Power), a, b) |> Exp.fresh; +let neq0 = (a: Exp.t): Exp.t => + DomainConditions.neq_zero(DomainConditions.int_zero(), a); +let gt0 = (a: Exp.t): Exp.t => + BinOp(Int(GreaterThan), a, DomainConditions.int_zero()) |> Exp.fresh; +let lt0 = (a: Exp.t): Exp.t => + BinOp(Int(LessThan), a, DomainConditions.int_zero()) |> Exp.fresh; +let geq0 = DomainConditions.geq_zero_int; + +let a = var("a"); +let b = var("b"); +let c = var("c"); + +let nat = (n: int): Exp.t => Atom(Nat(Bigint.of_int(n))) |> Exp.fresh; +let nat_add = (a: Exp.t, b: Exp.t): Exp.t => + BinOp(Nat(Plus), a, b) |> Exp.fresh; +let monus = (a: Exp.t, b: Exp.t): Exp.t => + Ap(Forward, var("monus"), Tuple([a, b]) |> Exp.fresh) |> Exp.fresh; +let forall_nat = (x: string, body: Exp.t): Exp.t => + Forall( + Asc(Var(x) |> Pat.fresh, Atom(Nat) |> Typ.fresh) |> Pat.fresh, + body, + ) + |> Exp.fresh; + +let axioms: list((string, Exp.t)) = [ + /* Reflexivity of equality. */ + ("refl", forall("x", eq(eq(var("x"), var("x")), tt))), + /* Definition of implication. Kleene: ==> is *defined* as !a || b. */ + ("impl_def", foralls(["a", "b"], eq(a ==>> b, neg(a) ||| b))), + /* Commutativity / associativity: Kleene ∧/∨ are symmetric. */ + ("and_comm", foralls(["a", "b"], eq(a &&& b, b &&& a))), + ("or_comm", foralls(["a", "b"], eq(a ||| b, b ||| a))), + /* The custom infix ops inherit OCaml associativity (`&&&` is + * right-assoc, `|||` left-assoc), so the associativity laws use the + * prefix constructors to make the grouping explicit. */ + ( + "and_assoc", + foralls( + ["a", "b", "c"], + eq(band(band(a, b), c), band(a, band(b, c))), + ), + ), + ( + "or_assoc", + foralls(["a", "b", "c"], eq(bor(bor(a, b), c), bor(a, bor(b, c)))), + ), + /* De Morgan: valid in strong Kleene (¬U = U on both sides). */ + ( + "demorgan_and", + foralls(["a", "b"], eq(neg(a &&& b), neg(a) ||| neg(b))), + ), + ( + "demorgan_or", + foralls(["a", "b"], eq(neg(a ||| b), neg(a) &&& neg(b))), + ), + /* Units / annihilators. U ∧ T = U, U ∧ F = F, U ∨ T = T, U ∨ F = U. */ + ("and_true", forall("a", eq(a &&& tt, a))), + ("and_false", forall("a", eq(a &&& ff, ff))), + ("or_true", forall("a", eq(a ||| tt, tt))), + ("or_false", forall("a", eq(a ||| ff, a))), + /* Double negation: ¬¬U = U. */ + ("not_not", forall("a", eq(neg(neg(a)), a))), + /* Implication units. (U ==> T) = ¬U ∨ T = T; (T ==> a) = F ∨ a = a; + * (F ==> a) = T ∨ a = T (even for a = U). */ + ("impl_true", forall("a", eq(a ==>> tt, tt))), + ("true_impl", forall("a", eq(tt ==>> a, a))), + ("false_impl", forall("a", eq(ff ==>> a, tt))), + /* --- Closure lemmas --------------------------------------------------- + * + * Conditional rewrite rules with boolean conclusions. A cited rule + * concluding `P` reads as `P == true` (`ProofRule.BoolReading`), + * so rewriting `P` to `true` incurs the antecedents as obligations, + * which are discharged like any other (applying `nonzero_mul` incurs + * `a != 0` and `b != 0`). + * + * Soundness: a guard proven true has defined operands, so the + * conclusion's arithmetic is defined and the (in)equality holds over + * exact bigint arithmetic (`*`/`+` are total; `**` errors only on a + * negative exponent, which `b >= 0` excludes; a > 0 and b >= 0 give + * a ** b >= 1 > 0). With a guard undefined or false the obligation + * can't be discharged, so the rule can't be applied. + * + * `b >= 0 ==> a ** b >= 0` is false for negative bases + * ((-2) ** 3 == -8), hence the positive-base `pow_pos`. */ + ( + "nonzero_mul", + foralls(["a", "b"], neq0(a) ==>> (neq0(b) ==>> neq0(mul(a, b)))), + ), + ("nonzero_of_pos", forall("a", gt0(a) ==>> neq0(a))), + ("nonzero_of_neg", forall("a", lt0(a) ==>> neq0(a))), + ( + "pos_mul", + foralls(["a", "b"], gt0(a) ==>> (gt0(b) ==>> gt0(mul(a, b)))), + ), + ( + "pos_add", + foralls(["a", "b"], gt0(a) ==>> (gt0(b) ==>> gt0(add(a, b)))), + ), + ( + "pow_pos", + foralls(["a", "b"], gt0(a) ==>> (geq0(b) ==>> gt0(pow(a, b)))), + ), + /* --- Nat ------------------------------------------------------------- + * + * What `algebra` can't check about Nat. It reasons over Int, where + * `m + 1 == 0` has a solution, and `monus` truncates, so it isn't a + * polynomial. The binders range over Nats, so both sides are defined. + * They are stated with Nat operators, so they don't match Int goals, + * where the first is false. */ + ( + "nat_succ_ne_zero", + forall_nat("m", eq(eq(nat_add(var("m"), nat(1)), nat(0)), ff)), + ), + ( + "nat_add_sub", + forall_nat( + "a", + forall_nat("k", eq(monus(nat_add(a, var("k")), var("k")), a)), + ), + ), +]; + let v: ProofCtx.t = - [] - |> ProofCtx.add_exp( - "Reflexive(==)", - Forall( - Var("x") |> Pat.fresh, - BinOp( - Poly(Equals), - BinOp( - Poly(Equals), - Var("x") |> Exp.fresh, - Var("x") |> Exp.fresh, - ) - |> Exp.fresh, - Atom(Bool(true)) |> Exp.fresh, - ) - |> Exp.fresh, - ) - |> Exp.fresh, - ); + List.fold_left( + ~f=(ctx, (name, exp)) => ProofCtx.add_exp(name, exp, ctx), + ~init=[], + axioms, + ); diff --git a/src/language/proof/Cas.re b/src/language/proof/Cas.re new file mode 100644 index 0000000000..60563f4ba8 --- /dev/null +++ b/src/language/proof/Cas.re @@ -0,0 +1,6 @@ +/* The computer algebra system the checker verifies `algebra` steps with: + * Algebrite's `run`, which evaluates an Algebrite expression to its + * printed result, or None while no Algebrite is loaded. Whatever JS + * context loads Algebrite sets it (the page, the worker, the test + * runner). */ +let run: ref(string => option(string)) = ref(_ => None); diff --git a/src/language/proof/Definitions.re b/src/language/proof/Definitions.re new file mode 100644 index 0000000000..fa7c68c39e --- /dev/null +++ b/src/language/proof/Definitions.re @@ -0,0 +1,111 @@ +/* The program's definitions, as a proof sees them. + * + * Goals and facts are kept as written: they mention the program's + * definitions by name (`len(xs)`), resolved in the environment of the + * scope they are in. There a definition is bound to its value and a proof + * variable to itself. A definition's body enters a goal only where a step + * needs it: `step` looks names up as the evaluator does, and comparisons + * unfold a name where the other side has structure (`MatchExp`). */ + +let is_definition = (env: Environment.t(Exp.t), x: Var.t): bool => + switch (Environment.lookup(env, x)) { + | Some({term: Var(y), _}) => !String.equal(y, x) + | Some(_) => true + | None => false + }; + +/* The value `x` is defined as, closed and with fresh ids. */ +let unfold = (env: Environment.t(Exp.t), x: Var.t): option(Exp.t) => + is_definition(env, x) + ? Some(Substitution.in_exp(env, Exp.fresh(Var(x)))) : None; + +/* `e` with each function value that is a definition in `env` written as + * the definition's name: evaluating `len(x :: xs)` leaves the recursive + * call as `len`'s fixpoint, or that fixpoint unrolled once, and this + * gives back `1 + len(xs)`. + * + * A value is folded only where the name means that definition, so not + * under a binder of `e` with the same name. Candidates are found by the + * name the elaborator gives a function (`len+` for a recursive one), and + * must equal the definition up to alpha once both are closed and any + * fixpoint is unrolled once, since either side may hold either form. */ +let fold = (env: Environment.t(Exp.t), e: Exp.t): Exp.t => { + let unrolled = (e: Exp.t): Exp.t => { + let e = Substitution.in_exp(Environment.empty, e); + switch (Exp.term_of(e)) { + | FixF(p, body, _) => + switch (ProofSyntax.pat_to_name(p)) { + | Some(f) => + Substitution.in_exp(Environment.of_bindings([(f, e)]), body) + | None => e + } + | _ => e + }; + }; + let definitions = Stdlib.Hashtbl.create(8); + let defines = (name: Var.t, value: Exp.t): bool => { + let definition = + switch (Stdlib.Hashtbl.find_opt(definitions, name)) { + | Some(d) => d + | None => + let d = unfold(env, name) |> Option.map(~f=unrolled); + Stdlib.Hashtbl.add(definitions, name, d); + d; + }; + switch (definition) { + | Some(d) => Equality.semantic.exp(unrolled(value), d) + | None => false + }; + }; + let strip = (suffix: string, name: Var.t): Var.t => { + let n = ref(String.length(name)); + while (n^ > 0 + && String.equal(String.sub(name, ~pos=n^ - 1, ~len=1), suffix)) { + decr(n); + }; + String.sub(name, ~pos=0, ~len=n^); + }; + /* A builtin's fixpoint has no elaborated name, so its binder's is used, + * without the primes substitution adds to avoid capture. */ + let rec fn_name = (e: Exp.t): option(Var.t) => + switch (Exp.term_of(e)) { + | Closure(_, inner) + | Parens(inner) => fn_name(inner) + | FixF(p, inner, _) => + switch (fn_name(inner)) { + | Some(_) as name => name + | None => ProofSyntax.pat_to_name(p) |> Option.map(~f=strip("'")) + } + | Fun(_, _, _, Some(name)) => Some(strip("+", name)) + | _ => None + }; + let rec go = (bound: list(Var.t), e: Exp.t): Exp.t => + Exp.map_term(~f_exp=f_exp(bound), e) + and f_exp = (bound, continue, e: Exp.t): Exp.t => { + let (term, rewrap) = Exp.unwrap(e); + let under = (p: Pat.t) => go(Pat.bound_vars(p) @ bound); + switch (fn_name(e)) { + | Some(name) + when !List.mem(bound, name, ~equal=String.equal) && defines(name, e) => + Exp.fresh(Var(name)) + | _ => + switch (term) { + | Fun(p, body, t, n) => Fun(p, under(p, body), t, n) |> rewrap + | FixF(p, body, env) => FixF(p, under(p, body), env) |> rewrap + | Forall(p, body) => Forall(p, under(p, body)) |> rewrap + | Let(p, def, body) => + Let(p, go(bound, def), under(p, body)) |> rewrap + | Match(scrut, rules) => + Match( + go(bound, scrut), + List.map(~f=((p, branch)) => (p, under(p, branch)), rules), + ) + |> rewrap + /* Names in a closure's body resolve in its own environment. */ + | Closure(_) => e + | _ => continue(e) + } + }; + }; + go([], e); +}; diff --git a/src/language/proof/DomainConditions.re b/src/language/proof/DomainConditions.re new file mode 100644 index 0000000000..50a50f5fa8 --- /dev/null +++ b/src/language/proof/DomainConditions.re @@ -0,0 +1,159 @@ +open Util; + +/* The conservative domain scan. + * + * `scan` collects the boolean domain conditions of every + * partial-primitive application syntactically present in an expression: + * the conditions under which no subterm evaluates to a domain error. + * The gates in ProofCheck incur one obligation per condition. + * + * The scan is path-insensitive: in `if b == 0 then 0 else a / b` the + * guarded division still emits `b != 0`. The user repairs an over-strong + * condition by splitting on the guard and eval-stepping the conditional + * away in each branch, where the branch's `case_eq` fact discharges the + * condition by lookup. A weakest-precondition pass would avoid that; + * conservative is always sound. + * + * Coverage: + * - `a / b` (Int / SInt / Nat) → `b != 0`. Float division is total + * under IEEE: `1.0 /. 0.0` is `infinity`, so it emits nothing. + * - `int_mod` / `sint_mod` / `nat_mod` / `float_mod` → `b != 0` + * (float mod errors on 0.0, unlike float division). + * - `a ** e` (Int / SInt) → `e >= 0` (they error on NegativeExponent; + * Nat power is total). Skipped when the exponent is a non-negative + * literal. + * - `int_of_float` / `sint_of_float` / `nat_of_float` → + * `is_finite(arg)` (they error on nan and inf). + * + * The scan doesn't descend into `Fun` bodies: a lambda's body doesn't + * run until applied, and its conditions are phrased in the lambda's own + * bound variables, which mean nothing to the caller. + * + * Not covered: + * - the `int_of_string` family: the language has no boolean predicate + * for parseability. + * - `string_sub` / `string_search` index bounds. + * - `nat_of_float` negativity (`arg >= 0.0`) and `Int → SInt/Nat` + * conversion errors (IntegerTooBig / NegativeNat): only finiteness + * is emitted. + * - mod/conversion builtins applied to a computed (non-literal) + * tuple: the denominator can't be named. + * + * Identical conditions are deduplicated (Exp.fast_equal). */ + +/* Deduplicate by Exp.fast_equal, preserving order. */ +let dedup = (conditions: list(Exp.t)): list(Exp.t) => + List.fold_left( + ~f= + (acc, c) => List.exists(~f=Exp.fast_equal(c), acc) ? acc : acc @ [c], + ~init=[], + conditions, + ); + +// Building conditions + +/* Conditions use the operators user code parses to, so that a condition + * `Exp.fast_equal`s the same guard written by hand: `!=` is polymorphic + * inequality, and `>=` is the operand class's comparison. The closure + * lemmas in Axioms are stated with these builders so that they conclude + * exactly these conditions. */ +let int_zero = (): Exp.t => Exp.fresh(Atom(Int(Bigint.zero))); +let nat_zero = (): Exp.t => Exp.fresh(Atom(Nat(Bigint.zero))); +let sint_zero = (): Exp.t => Exp.fresh(Atom(SInt(0))); + +/* `b != 0`, at the class of `zero`. */ +let neq_zero = (zero: Exp.t, b: Exp.t): Exp.t => + Exp.fresh(BinOp(Poly(NotEquals), b, zero)); + +let geq_zero_int = (e: Exp.t): Exp.t => + Exp.fresh(BinOp(Int(GreaterThanOrEqual), e, int_zero())); + +/* Conditions of one builtin application, if it is a partial builtin + * the scan covers. */ +let builtin_conditions = (name: string, arg: Exp.t): list(Exp.t) => { + /* The second component of a syntactically visible pair argument (mod + * and the other two-argument builtins take a 2-tuple). */ + let pair_snd = (arg: Exp.t): option(Exp.t) => + switch (ProofSyntax.unwrap(arg) |> Exp.term_of) { + | Tuple([_, b]) => Some(b) + | _ => None + }; + /* `is_finite(arg)`, with a Var head so that it matches a user-written + * `is_finite(x)` fact, and env-substitutes to the builtin for closed + * evaluation. */ + let is_finite = (arg: Exp.t): Exp.t => + Exp.fresh(Ap(Operators.Forward, Exp.fresh(Var("is_finite")), arg)); + switch (name) { + | "int_mod" => + pair_snd(arg) |> Option.map(~f=neq_zero(int_zero())) |> Option.to_list + | "sint_mod" => + pair_snd(arg) |> Option.map(~f=neq_zero(sint_zero())) |> Option.to_list + | "nat_mod" => + pair_snd(arg) |> Option.map(~f=neq_zero(nat_zero())) |> Option.to_list + /* Float mod's condition uses IEEE float inequality `!=.`. */ + | "float_mod" => + pair_snd(arg) + |> Option.map(~f=b => + Exp.fresh( + BinOp(Float(NotEquals), b, Exp.fresh(Atom(Float(0.0)))), + ) + ) + |> Option.to_list + | "int_of_float" + | "sint_of_float" + | "nat_of_float" => [is_finite(arg)] + | _ => [] + }; +}; + +// The scan + +/* The domain conditions of every partial-primitive application in + * `exp`, in traversal (pre-)order, deduplicated. */ +let scan = (exp: Exp.t): list(Exp.t) => { + /* A manifestly non-negative exponent literal needs no condition. */ + let nonneg_literal = (e: Exp.t): bool => + switch (ProofSyntax.unwrap(e) |> Exp.term_of) { + | Atom(Int(n)) + | Atom(Nat(n)) => Bigint.(>=)(n, Bigint.zero) + | Atom(SInt(i)) => i >= 0 + | _ => false + }; + let conditions = ref([]); + let emit = (c: Exp.t) => conditions := [c, ...conditions^]; + let visit = (e: Exp.t): unit => + switch (e |> Exp.term_of) { + /* Integral division errors on 0. Float division is IEEE-total. */ + | BinOp(Int(Divide), _, b) => emit(neq_zero(int_zero(), b)) + | BinOp(SInt(Divide), _, b) => emit(neq_zero(sint_zero(), b)) + | BinOp(Nat(Divide), _, b) => emit(neq_zero(nat_zero(), b)) + /* Int/SInt power error on a negative exponent (Operators.re + * int_power/sint_power); Nat power is total. */ + | BinOp(Int(Power), _, e2) when !nonneg_literal(e2) => + emit(geq_zero_int(e2)) + | BinOp(SInt(Power), _, e2) when !nonneg_literal(e2) => + emit(Exp.fresh(BinOp(SInt(GreaterThanOrEqual), e2, sint_zero()))) + | Ap(_, fn, arg) => + switch (ProofSyntax.unwrap(fn) |> Exp.term_of) { + | Var(name) + | BuiltinFun(name) => + List.iter(~f=emit, builtin_conditions(name, arg)) + | _ => () + } + | _ => () + }; + let _: Exp.t = + Exp.map_term( + ~f_exp= + (continue, e: Exp.t) => { + visit(e); + switch (e |> Exp.term_of) { + /* Function bodies are skipped (module header). */ + | Fun(_) => e + | _ => continue(e) + }; + }, + exp, + ); + conditions^ |> List.rev |> dedup; +}; diff --git a/src/language/proof/Induction.re b/src/language/proof/Induction.re new file mode 100644 index 0000000000..e7ada68a01 --- /dev/null +++ b/src/language/proof/Induction.re @@ -0,0 +1,290 @@ +/* Building the cases of a split (`cases` or `induction`), for the checker + * and the UI stepper: the goal with the scrutinee replaced by a case's + * pattern, an induction case's inductive hypotheses, and which facts + * leave its scope. The statics use it to scope a case body as the checker + * does. */ + +/* Returns all sub-pattern of the original pattern that + 1. Have the same type as the original pattern + 2. Are not the original pattern itself. + + `t` has to be normalized, as `statics` types are: for a recursive ADT + the scrutinee's type is written with the alias (`Term`), while the + constructor payloads carry the unrolled `Rec` form. + */ + +let rec hypotheses = (statics: ProofStatics.t, t, pat) => { + switch (pat |> Pat.term_of) { + | _ when Typ.fast_equal(t, Typ.temp(Unknown(Internal))) => [] + | Invalid(_) => [] + | EmptyHole => [] + | MultiHole(_) => [] + | Wild => [] + | Atom(_) => [] + | ListLit(xs) => + List.concat(List.map(~f=hypotheses_inner(statics, t, _), xs)) + | Constructor(_) => [] + | Cons(e1, e2) => + hypotheses_inner(statics, t, e1) @ hypotheses_inner(statics, t, e2) + | Var(_) => [] + | Tuple(xs) => + List.concat(List.map(~f=hypotheses_inner(statics, t, _), xs)) + /* A wrapper's strict sub-patterns are its contents'. Through + * `hypotheses_inner` the contents would count themselves, and a case + * pattern in parens would be its own hypothesis: its goal. */ + | Parens(e) + | Projector(_, e) + | Asc(e, _) => hypotheses(statics, t, e) + | Ap(e1, e2) => + hypotheses_inner(statics, t, e1) @ hypotheses_inner(statics, t, e2) + | Label(_) => [] + | TupLabel(l, e) => + hypotheses_inner(statics, t, l) @ hypotheses_inner(statics, t, e) + | ExplicitNonlabel => [] + }; +} +and hypotheses_inner' = (statics: ProofStatics.t, t, pat) => { + let is_correct_type = + statics.typ(Pat.rep_id(pat)) + |> Option.map(~f=Typ.fast_equal(t)) + |> Option.value(~default=false); + (is_correct_type ? [pat] : []) @ hypotheses(statics, t, pat); +} +and hypotheses_inner = (statics: ProofStatics.t, t, pat) => + /* Wrappers share their inner pattern's type, so only the innermost one + counts as a hypothesis. */ + switch (pat |> Pat.term_of) { + | Parens(x) + | Projector(_, x) + | Asc(x, _) => hypotheses_inner(statics, t, x) + | Invalid(_) + | EmptyHole + | MultiHole(_) + | Wild + | ExplicitNonlabel + | Atom(_) + | ListLit(_) + | Constructor(_) + | Cons(_) + | Var(_) + | Tuple(_) + | Label(_) + | TupLabel(_) + | Ap(_) => hypotheses_inner'(statics, t, pat) + }; + +/* The name an inductive hypothesis is cited by: `ih_t` for the + sub-pattern `t`. A sub-pattern that isn't a variable, like `S(n)` in + `S(S(n))`, has no variable to name it after, so it is plain `ih`. */ +let hypothesis_name = (pat: Pat.t): string => + switch (pat |> Pat.term_of) { + | Var(x) => "ih_" ++ x + | _ => "ih" + }; + +/* Does `fact` mention `e`: free, for a variable, or as a subterm, for + a computed expression? An induction case is about a fresh value in + place of its scrutinee, so a fact that mentions the scrutinee is out of + scope there. Kept beside an inductive hypothesis that doesn't assume + it, it would prove too much. */ +let mentions = (e: Exp.t, fact: Exp.t): bool => + switch (ProofSyntax.exp_to_name(e)) { + | Some(x) => Exp.occurs_free_any([x], fact) + | None => + let found = ref(false); + let _: Exp.t = + Exp.map_term( + ~f_exp= + (continue, sub) => + if (Equality.ignoring_ascriptions.exp(sub, e)) { + found := true; + sub; + } else { + continue(sub); + }, + fact, + ); + found^; + }; + +/* Replace all occurrences of `replace` in `in_exp` with `with_exp`. + The coctx is used to prevent capture inside binders. `None` when a + binder would capture: the replacement would land under a binder for + one of `replace`'s or `with_exp`'s variables at a use of one of + `blacklist_vars`. Occurrences are found up to ascriptions, not up to + alpha-equivalence. */ +let replace = + ( + statics: ProofStatics.t, + replace, + replace_coctx, + with_exp, + with_coctx, + blacklist_vars, + in_exp, + ) + : option(Exp.t) => { + let captured = ref(false); + let is_bound = (pat: Pat.t): bool => { + let bvn = pat |> Pat.bindings |> Binding.variable_names; + CoCtx.has_any(replace_coctx, bvn) + ? true : CoCtx.has_any(with_coctx, bvn); + }; + /* At a binder the replacement stops at, `exp` must not use a + blacklisted variable. */ + let check_capture = (exp: Exp.t, blacklist_vars) => { + let coctx = + statics.co_ctx(Exp.rep_id(exp)) |> Option.value(~default=CoCtx.empty); + if (CoCtx.has_any(coctx, blacklist_vars)) { + captured := true; + }; + }; + let restrict_blacklist = (pat: Pat.t, blacklist_vars) => { + let bvn = pat |> Pat.bindings |> Binding.variable_names; + List.filter( + ~f=v => !List.mem(bvn, v, ~equal=String.equal), + blacklist_vars, + ); + }; + let rec replace_exp = (in_exp, blacklist_vars): Exp.t => + Exp.map_term( + ~f_exp= + (continue, exp) => { + let (term, rewrap) = Exp.unwrap(exp); + switch (term) { + | _ when Equality.ignoring_ascriptions.exp(exp, replace) => + with_exp |> Exp.replace_all_ids + /* Forms with binders: check if any bound variables are in the coctx, + if so, stop. */ + | Fun(p, d1, x, y) => + if (is_bound(p)) { + check_capture(exp, restrict_blacklist(p, blacklist_vars)); + exp; + } else { + Fun( + p, + replace_exp(d1, restrict_blacklist(p, blacklist_vars)), + x, + y, + ) + |> rewrap; + } + | Let(p, e1, e2) => + if (is_bound(p)) { + check_capture(exp, restrict_blacklist(p, blacklist_vars)); + Let( + p, + replace_exp(e1, restrict_blacklist(p, blacklist_vars)), + e2, + ) + |> rewrap; + } else { + continue(exp); + } + | FixF(p, e, env) => + if (is_bound(p)) { + check_capture(exp, blacklist_vars); + exp; + } else { + FixF( + p, + replace_exp(e, restrict_blacklist(p, blacklist_vars)), + env, + ) + |> rewrap; + } + | Match(e, cases) => + Match( + replace_exp(e, blacklist_vars), + List.map( + ~f= + ((p, e)) => + if (is_bound(p)) { + check_capture( + e, + restrict_blacklist(p, blacklist_vars), + ); + (p, e); + } else { + ( + p, + replace_exp( + e, + restrict_blacklist(p, blacklist_vars), + ), + ); + }, + cases, + ), + ) + |> rewrap + | Theorem(p, e1, pf, e2) => + if (is_bound(p)) { + check_capture(exp, restrict_blacklist(p, blacklist_vars)); + Theorem(p, replace_exp(e1, blacklist_vars), pf, e2) |> rewrap; + } else { + continue(exp); + } + | Forall(p, e) => + if (is_bound(p)) { + check_capture(exp, restrict_blacklist(p, blacklist_vars)); + exp; + } else { + Forall( + p, + replace_exp(e, restrict_blacklist(p, blacklist_vars)), + ) + |> rewrap; + } + /* Variables: check if in blacklist */ + | Var(x) when List.mem(blacklist_vars, x, ~equal=String.equal) => + captured := true; + exp; + | Var(_) => continue(exp) + /* Forms without binders: continue */ + | EmptyHole + | Undefined + | Invalid(_) + | MultiHole(_) + | DynamicErrorHole(_, _) + | Deferral(_) + | Atom(_) + | DrvQuote(_, _) + | ListLit(_) + | Constructor(_) + | TypFun(_) + | Tuple(_) + | TupleExtension(_) + | Label(_) + | TupLabel(_, _) + | Dot(_, _) + | LivelitName(_) + | TyAlias(_) + | Use(_, _) + | Ap(_, _, _) + | TypAp(_, _) + | DeferredAp(_, _) + | If(_, _, _) + | Seq(_, _) + | Test(_) + | HintedTest(_, _) + | Filter(_) + | Closure(_) + | Parens(_) + | Projector(_) + | Cons(_, _) + | ListConcat(_, _) + | UnOp(_, _) + | BinOp(_, _, _) + | BuiltinFun(_) + | Asc(_, _) + | ExplicitNonlabel + | Module(_) + | ModuleExp(_) => continue(exp) + }; + }, + in_exp, + ); + let replaced = replace_exp(in_exp, blacklist_vars); + captured^ ? None : Some(replaced); +}; diff --git a/src/language/proof/MatchExp.re b/src/language/proof/MatchExp.re index a481986896..eed73841c9 100644 --- a/src/language/proof/MatchExp.re +++ b/src/language/proof/MatchExp.re @@ -23,6 +23,9 @@ let rec are_alpha_equiv = (alphas: alphas, x: string, y: string): bool => let is_in_alphas_l = (alphas: alphas, x: string): bool => List.exists(~f=((x1, _)) => String.equal(x, x1), alphas); +let is_in_alphas_r = (alphas: alphas, y: string): bool => + List.exists(~f=((_, y1)) => y == y1, alphas); + /* Match exp against another pattern exp_r. - alphas: list of alpha equivalences, e.g. [("x", "y")] means x in exp_r @@ -31,18 +34,23 @@ let is_in_alphas_l = (alphas: alphas, x: string): bool => None if not matched but can be matched. - exp_r: the pattern expression to match against. - exp: the expression to match. + - defs: the definitions a free name on either side may be unfolded to, + where the other side has structure the name hides. Names are + compared as written first. */ let rec match_exp = ( - ~info_map: Statics.Map.t, + ~statics: ProofStatics.t, + ~meta: option(MetaVar.env)=None, + ~defs: Environment.t(Exp.t)=Environment.empty, alphas: alphas, ctx: match_ctx, exp_r: Exp.t, exp: Exp.t, ) : option(match_ctx) => { - let match_exp = match_exp(~info_map); + let match_exp = match_exp(~statics, ~meta, ~defs); switch (exp_r |> Exp.term_of, exp |> Exp.term_of) { /* Parens */ | (Parens(e1), _) @@ -52,16 +60,35 @@ let rec match_exp = // TODO: Better cast logic | (Asc(e1, _), _) => match_exp(alphas, ctx, e1, exp) | (_, Asc(e2, _)) => match_exp(alphas, ctx, exp_r, e2) + /* Pattern metavariables $e and $v, only when the caller supplies + * `meta`. They are non-linear: they match without recording anything, + * as the stepper's filter patterns do (Equality's `use_expr_wildcards`). + * Named metavariables ($x) are seeded into `ctx` by the caller and go + * through the ordinary match_ctx case below, which makes them linear. */ + | (Var(x), _) + when + switch (meta, MetaVar.of_name(x)) { + | (Some(_), Some(Any | Value)) => true + | _ => false + } => + MetaVar.matches( + ~env=Option.value_exn(meta), + Option.value_exn(MetaVar.of_name(x)), + exp, + ) + ? Some(ctx) : None /* Variables */ | (Var(x), _) when match_ctx_has(ctx, x) && !is_in_alphas_l(alphas, x) => let (typ, assigned_exp) = List.Assoc.find_exn(ctx, x, ~equal=String.equal); - let exp_typ = Statics.Map.ty_of(Exp.rep_id(exp), info_map); + let exp_typ = statics.typ(Exp.rep_id(exp)); + /* The binder's type is as the rule writes it, and an alias in it can't + * be resolved here, so only a type without one is compared. */ switch (exp_typ) { | Some(exp_typ) - when { - !Typ.is_consistent(Ctx.empty, exp_typ, typ); - } => + when + Typ.free_vars(typ) == [] + && !Typ.is_consistent(Ctx.empty, exp_typ, typ) => None | _ => switch (assigned_exp) { @@ -75,13 +102,24 @@ let rec match_exp = ), ) | Some(e) => - print_endline("ASSIGNED"); - print_endline("assigned exp: " ++ Exp.show(e)); - Equality.ignoring_ascriptions.exp(e, exp) ? Some(ctx) : None; + /* Bound by an earlier occurrence or by an explicit `with` + * instantiation; this occurrence must agree. */ + Equality.ignoring_ascriptions.exp(e, exp) ? Some(ctx) : None } }; | (Var(x), Var(y)) when are_alpha_equiv(alphas, x, y) => Some(ctx) + | (Var(x), _) when !is_in_alphas_l(alphas, x) => + switch (Definitions.unfold(defs, x)) { + | Some(value) => match_exp(alphas, ctx, value, exp) + | None => None + } | (Var(_), _) => None + | (_, Var(y)) + when !is_in_alphas_r(alphas, y) && Definitions.is_definition(defs, y) => + switch (Definitions.unfold(defs, y)) { + | Some(value) => match_exp(alphas, ctx, exp_r, value) + | None => None + } /* Forms with binders */ /* Forms without binders */ | (Invalid(x), Invalid(y)) when String.equal(x, y) => Some(ctx) @@ -158,13 +196,11 @@ let rec match_exp = let* ctx = match_exp(alphas, ctx, d1, d2); match_exp(alphas' @ alphas, ctx, e1, e2); | (Let(_, _, _), _) => None - | (Theorem(p1, e3, e1), Theorem(p2, e4, e2)) => + | (Theorem(p1, e3, _pf1, e1), Theorem(p2, e4, _pf2, e2)) => let* alphas' = match_pat(p1, p2); let* ctx = match_exp(alphas, ctx, e3, e4); match_exp(alphas' @ alphas, ctx, e1, e2); | (Theorem(_), _) => None - | (ProofObject(e1), ProofObject(e2)) => match_exp(alphas, ctx, e1, e2) - | (ProofObject(_), _) => None | (FixF(p1, e1, _), FixF(p2, e2, _)) => let* alphas' = match_pat(p1, p2); match_exp(alphas' @ alphas, ctx, e1, e2); @@ -388,17 +424,100 @@ let substitute_exp = (sub: match_ctx, exp: Exp.t): Exp.t => exp, ); -/* TODO[Matt]: we can probably make this faster by avoiding substituting - if we know it doesn't match */ +/* ---- Pattern matching for focus selectors --------------------------- + * + * A "pattern" here is just an Exp that may contain metavariables (see + * MetaVar). A pattern with no metavariables is a ground pattern and + * matches only expressions it is structurally equal to. + * + * Named metavariables ($x) get their linearity from `match_ctx`: we + * seed one unassigned entry per distinct name, and the existing + * `Var(x) when match_ctx_has(ctx, x)` case both records the first + * occurrence and requires later occurrences to agree with it. + */ + +/* The value notion is the stepper's, injected rather than reimplemented + * — the same predicate FilterMatcher hands to Equality. */ +let meta_env = (~env: Environment.t(Exp.t)): MetaVar.env => + MetaVar.{ + is_value: exp => ValueChecker.check_value(env, exp) != ValueChecker.Expr, + }; + +/* One unassigned match_ctx entry per distinct named metavariable. */ +let meta_ctx = (pat: Exp.t): match_ctx => + pat + |> MetaVar.named_names + |> List.map(~f=name => (name, (Unknown(Internal) |> Typ.temp, None))); + +/* Match `pat` against `exp`, returning the metavariable assignments. + * `env` is used only to decide `$v`. */ +let match_pattern = + ( + ~statics: ProofStatics.t=ProofStatics.empty, + ~env: Environment.t(Exp.t)=Environment.empty, + ~defs: Environment.t(Exp.t)=Environment.empty, + ~alphas: alphas=[], + pat: Exp.t, + exp: Exp.t, + ) + : option(match_ctx) => + match_exp( + ~statics, + ~meta=Some(meta_env(~env)), + ~defs, + alphas, + meta_ctx(pat), + pat, + exp, + ); + +let matches_pattern = + ( + ~statics=ProofStatics.empty, + ~env=Environment.empty, + ~defs=Environment.empty, + pat: Exp.t, + exp: Exp.t, + ) + : bool => + match_pattern(~statics, ~env, ~defs, pat, exp) |> Option.is_some; + let match_exp = ( - ~info_map, + ~statics, ~alphas=[], - ~exp_env: Environment.t(Exp.t), + ~defs: Environment.t(Exp.t), ~exp_r_ctx: match_ctx, exp_r: Exp.t, exp: Exp.t, - ) => { - let exp = Substitution.in_exp(exp_env, exp); - match_exp(~info_map, alphas, exp_r_ctx, exp_r, exp); + ) => + match_exp(~statics, ~defs, alphas, exp_r_ctx, exp_r, exp); + +/* Whether `a` and `b` are the same term once the definitions in `defs` + * they name are unfolded. */ +let equal_modulo = (~defs: Environment.t(Exp.t), a: Exp.t, b: Exp.t): bool => + match_exp(~statics=ProofStatics.empty, ~defs, ~exp_r_ctx=[], a, b) + |> Option.is_some; + +/* The equations `a == b` in `e` whose sides match, which reflexivity + * closes. */ +let find_refls = (~statics, ~defs, e) => { + let refls = ref([]); + let _ = + Exp.map_term( + ~f_exp= + (cont, exp) => { + switch (exp |> Exp.term_of) { + | BinOp(Poly(Equals), e1, e2) + when + match_exp(~statics, ~defs, ~exp_r_ctx=[], e1, e2) + |> Option.is_some => + refls := [exp, ...refls^]; + cont(exp); + | _ => cont(exp) + } + }, + e, + ); + refls^; }; diff --git a/src/language/proof/MetaVar.re b/src/language/proof/MetaVar.re new file mode 100644 index 0000000000..ab41366c11 --- /dev/null +++ b/src/language/proof/MetaVar.re @@ -0,0 +1,112 @@ +/* Pattern metavariables. + * + * Hazel's stepper filters already have a metavariable convention: inside + * a `pause`/`eval`/`hide` filter pattern, `$e` stands for any + * expression and `$v` for any value (see FilterMatcher.matches_exp, + * which drives Equality's `use_expr_wildcards`, and Statics' + * `is_in_filter` case that keeps them from reading as free variables). + * + * A proof focus's selector (`from do ... end`) reuses that + * convention verbatim rather than inventing a second one, so a user who + * has written a filter already knows the syntax. Nothing new needs to parse: Token.var_regexp + * already admits a `$`-prefixed name, so `$e` arrives as `Var("$e")`. + * + * This module only classifies and collects, so that the statics (to + * suppress free-variable marks) and the proof checker (to locate a + * focus) can share it without depending on each other. + * + * Whether an expression is a *value* is not a syntactic question, so, as + * Equality does with `use_expr_wildcards`, it is an injected predicate + * rather than a dependency on the evaluator. + */ + +open Util; + +[@deriving (show({with_path: false}), sexp, yojson)] +type t = + /* `$e`: any expression. Non-linear — each occurrence matches + * independently, matching filter semantics (Equality returns `true` + * unconditionally for `$e`). */ + | Any + /* `$v`: any value, per the injected predicate. Also non-linear. */ + | Value + /* `$x`, `$acc`, ...: a *named* metavariable. Unlike `$e`/`$v` these + * are linear: every occurrence of the same name must match the same + * expression. Filters have no named metavariables; MatchExp handles + * them through its match_ctx. */ + | Named(string); + +type env = {is_value: Exp.t => bool}; + +let sigil = '$'; +let any_name = "$e"; +let value_name = "$v"; + +/* A `$`-prefixed name. `$` alone is not a metavariable. */ +let is_meta_name = (name: string): bool => + String.length(name) > 1 && Char.equal(name.[0], sigil); + +let of_name = (name: string): option(t) => + if (!is_meta_name(name)) { + None; + } else if (String.equal(name, any_name)) { + Some(Any); + } else if (String.equal(name, value_name)) { + Some(Value); + } else { + Some(Named(name)); + }; + +/* Recognize a metavariable *node*. `Var` is the surface form; the + * `Constructor` case mirrors Equality's wildcard cases, which see + * metavariables in that shape on some post-elaboration filter paths. */ +let of_exp = (e: Exp.t): option(t) => + switch (e |> Exp.term_of) { + | Var(name) + | Constructor(name, _) => of_name(name) + | _ => None + }; + +/* Every metavariable occurring in a pattern, first-occurrence order. */ +let collect = (e: Exp.t): list(t) => { + let acc = ref([]); + let _ = + Exp.map_term( + ~f_exp= + (cont, e) => { + switch (of_exp(e)) { + | Some(m) when !List.mem(acc^, m, ~equal=Poly.equal) => + acc := acc^ @ [m] + | _ => () + }; + cont(e); + }, + e, + ); + acc^; +}; + +/* The names of the linear (named) metavariables in a pattern. */ +let named_names = (e: Exp.t): list(string) => + e + |> collect + |> List.filter_map( + ~f= + fun + | Named(name) => Some(name) + | Any + | Value => None, + ); + +/* The checker uses this to keep ground targets on the exact-match path + * (see Occurrence.nth_target). */ +let has_meta = (e: Exp.t): bool => !List.is_empty(collect(e)); + +/* Does a metavariable match `exp`? Only meaningful for the non-linear + * kinds; `Named` is resolved by the caller's match context. */ +let matches = (~env: env, m: t, exp: Exp.t): bool => + switch (m) { + | Any => true + | Value => env.is_value(exp) + | Named(_) => true + }; diff --git a/src/language/proof/Obligation.re b/src/language/proof/Obligation.re new file mode 100644 index 0000000000..0a973a95a2 --- /dev/null +++ b/src/language/proof/Obligation.re @@ -0,0 +1,76 @@ +open Util; + +/* The sequent-shaped proof obligations incurred by proof steps. + * + * An obligation is a sequent: a local context (the bindings visible at the + * obligation site — obligations raised inside induction cases mention + * case-local binders) plus a boolean goal. Obligations are *computed* by + * the checker on every pass and recorded in the ProofMap entry of the step + * that incurred them; they are never stored in program text. + * + * `discharge` records what discharged the obligation, if anything. */ + +[@deriving (show({with_path: false}), sexp, yojson)] +type discharge = + /* Discharged by syntactic lookup of an in-scope fact (case_eq, + * hypothesis), identified by the fact's id. */ + | Remote(Id.t) + /* The goal was closed and evaluated to `true`, so the stepper can + * replay it. */ + | Evaluated + | Pending; + +/* Why a step incurs the obligation. */ +[@deriving (show({with_path: false}), sexp, yojson)] +type kind = + /* A term the step introduces is defined: a divisor is nonzero, a + * list is nonempty (DomainConditions). */ + | Definedness + /* A cited rule's assumption, `A` of `A ==> …`, as the match + * instantiated it; or a premise of `have`'s cut rule. */ + | Premise + /* A cited theorem whose proof isn't finished: the step rests on its + * statement. */ + | Citation + /* An `algebra` step the CAS can't verify: the goal equals what it is + * rewritten to. */ + | Algebra; + +[@deriving (show({with_path: false}), sexp, yojson)] +type t = { + /* The proof step that incurred the obligation. */ + origin: Id.t, + kind, + /* The bindings visible at the obligation site. */ + bindings: list(Ctx.entry), + /* As written: it names the program's definitions. */ + goal: Exp.t, + discharge, +}; + +/* For a `Remote` discharge, the covering fact's name and statement, + * found by id among the obligation's own bindings (`Ctx.TheoremEntry`s). + * `None` for any other discharge, or if the id is not among the + * bindings. */ +let remote_fact = (ob: t): option((Var.t, Exp.t)) => + switch (ob.discharge) { + | Remote(fact_id) => + ob.bindings + |> List.find_map(~f=(e: Ctx.entry) => + switch (e) { + | TheoremEntry({id, name, prop: Some(fact)}) + when Id.compare(id, fact_id) == 0 => + Some((name, fact)) + | _ => None + } + ) + | Evaluated + | Pending => None + }; + +let is_pending = (ob: t): bool => + switch (ob.discharge) { + | Pending => true + | Remote(_) + | Evaluated => false + }; diff --git a/src/language/proof/Occurrence.re b/src/language/proof/Occurrence.re new file mode 100644 index 0000000000..e4f108f303 --- /dev/null +++ b/src/language/proof/Occurrence.re @@ -0,0 +1,307 @@ +open Util; + +/* Locating the subterm a proof focus selects. + * + * `from do` selects the nth subterm of the goal that equals + * ``, counting left to right in the source and not descending into a + * counted match. The stepper counts with `index`, which is 0-based; the checker + * reads the occurrence back with `nth_env_target`. */ + +/* Immediate expression children, in `map_term` order, including those + * inside patterns. */ +let children = (e: Exp.t): list(Exp.t) => { + let kids = ref([]); + let root_id = Exp.rep_id(e); + let _: Exp.t = + Exp.map_term( + ~f_exp= + (cont, inner) => + if (Id.equal(Exp.rep_id(inner), root_id)) { + cont(inner); + } else { + kids := [inner, ...kids^]; + inner; + }, + e, + ); + List.rev(kids^); +}; + +/* The subterms of `e` in source order, each before its own subterms, not + * descending into a subterm `stop` accepts. `map_term` can't give this + * order: OCaml evaluates constructor arguments right to left, so it + * visits `b` before `a` in `a + b`. */ +let rec in_source_order = (~stop: Exp.t => bool, e: Exp.t): list(Exp.t) => { + let in_pat = (p: Pat.t): list(Exp.t) => { + let found = ref([]); + let _: Pat.t = + Pat.map_term( + ~f_exp= + (_, e) => { + found := [e, ...found^]; + e; + }, + p, + ); + List.rev(found^); + }; + let kids = + switch (Exp.term_of(e)) { + | Invalid(_) + | EmptyHole + | Deferral(_) + | Undefined + | Atom(_) + | Constructor(_) + | Label(_) + | ExplicitNonlabel + | LivelitName(_) + | Var(_) + | BuiltinFun(_) => [] + | DynamicErrorHole(a, _) + | TypFun(_, a, _) + | TyAlias(_, _, a) + | Use(_, a) + | TypAp(a, _) + | Test(a) + | Filter(_, a) + | Closure(_, a) + | Parens(a) + | Projector(_, a) + | UnOp(_, a) + | Asc(a, _) => [a] + | TupLabel(a, b) + | Dot(a, b) + | Ap(_, a, b) + | Seq(a, b) + | HintedTest(a, b) + | Cons(a, b) + | ListConcat(a, b) + | BinOp(_, a, b) + | TupleExtension(a, b) => [a, b] + | If(a, b, c) => [a, b, c] + | ListLit(es) + | Tuple(es) => es + | DeferredAp(f, args) => [f, ...args] + | Fun(p, body, _, _) + | Forall(p, body) + | FixF(p, body, _) => in_pat(p) @ [body] + | Let(p, def, body) => in_pat(p) @ [def, body] + | Match(scrut, rules) => [ + scrut, + ...List.concat_map( + ~f=((p, branch)) => in_pat(p) @ [branch], + rules, + ), + ] + /* Rare in a goal; their children's order is `map_term`'s. */ + | MultiHole(_) + | DrvQuote(_) + | Theorem(_) + | Module(_) + | ModuleExp(_) => children(e) + }; + stop(e) + ? [e] : [e, ...List.concat_map(~f=in_source_order(~stop), kids)]; +}; + +/* How many subterms equal to `e1` come before the node with `e1`'s id in + * `e2`, not counting inside an earlier one. `None` if that id is not in + * `e2`. */ +let index = (e1: Exp.t, e2: Exp.t): option(int) => { + let is_node = e => Id.equal(Exp.rep_id(e), Exp.rep_id(e1)); + let is_equal = e => Equality.ignoring_ascriptions.exp(e, e1); + let rec count = (n, subterms) => + switch (subterms) { + | [] => None + | [e, ..._] when is_node(e) => Some(n) + | [e, ...rest] => count(is_equal(e) ? n + 1 : n, rest) + }; + count(0, in_source_order(~stop=e => !is_node(e) && is_equal(e), e2)); +}; + +/* The (n+1)th subterm of `e` that `matches`. */ +let nth_matching = (matches: Exp.t => bool, n: int, e: Exp.t): option(Exp.t) => + List.nth(in_source_order(~stop=matches, e) |> List.filter(~f=matches), n); + +/* The (n+1)th occurrence of `e1` in `e2`. */ +let nth = (e1: Exp.t, n: int, e2: Exp.t): option(Exp.t) => + nth_matching(exp => Equality.ignoring_ascriptions.exp(exp, e1), n, e2); + +/* The (n+1)th subterm of `e2` that matches `pat`, an expression that may + * contain `$e`/`$v`/`$x` metavariables (see MetaVar). A metavariable-free + * pattern matches exactly the terms it is structurally equal to, so + * indexing among matches generalizes indexing among occurrences. */ +let nth_pattern = + ( + ~statics: ProofStatics.t=ProofStatics.empty, + ~env: Environment.t(Exp.t)=Environment.empty, + pat: Exp.t, + n: int, + e2: Exp.t, + ) + : option(Exp.t) => + nth_matching(MatchExp.matches_pattern(~statics, ~env, pat), n, e2); + +/* The subterm a selector names. Pattern matching + * (MatchExp) and the equality `nth` uses (Equality) are different + * relations, so only a target that uses the pattern language goes + * through the matcher; a ground target is compared with Equality. */ +let nth_target = + ( + ~statics: ProofStatics.t=ProofStatics.empty, + ~env: Environment.t(Exp.t)=Environment.empty, + selector: Exp.t, + n: int, + e2: Exp.t, + ) + : option(Exp.t) => + MetaVar.has_meta(selector) + ? nth_pattern(~statics, ~env, selector, n, e2) : nth(selector, n, e2); + +/* `nth_target` modulo the definitions in `env`. The goal is searched as + * written first. Only if it has too few occurrences there is it searched + * again, unfolding a name where it hides structure the selector has + * (`MatchExp`'s `~defs`). + * + * Equality compares up to parens/projectors, ascriptions, + * alpha-renaming (expression and type), function names, filters and + * hole provenance, but not up to elaboration-supplied type information. + * Two same-named constructors at different types are different terms, + * and a step must not retarget across them. So both sides must be + * elaborated: an unelaborated `Constructor(c, None)` never equals its + * elaborated `Constructor(c, Some(Some(ty)))`, and the mismatch reads as + * "target not found". This is why the theorem context records + * elaborated statements (`Statics`' Theorem arm): + * `ProofCtx.of_theorem_ctx` splices a cited rule's right-hand side into + * elaborated goals. */ +let nth_env_target = + ( + ~statics: ProofStatics.t, + ~env: Environment.t(Exp.t), + selector: Exp.t, + n: int, + e2: Exp.t, + ) + : option(Exp.t) => + switch (nth_target(~statics, ~env, selector, n, e2)) { + | Some(_) as found => found + | None => + nth_matching( + MatchExp.matches_pattern(~statics, ~env, ~defs=env, selector), + n, + e2, + ) + }; + +/* `exp` with the node whose id is `id` replaced by `new_exp`, ids and + * all, so `new_exp` can be found again in the result. The caller ensures + * none of its ids occur elsewhere in `exp`. */ +let replace_by_id = (id: Id.t, exp: Exp.t, new_exp: Exp.t) => + Exp.map_term( + ~f_exp= + (cont, exp) => Id.equal(Exp.rep_id(exp), id) ? new_exp : cont(exp), + exp, + ); + +/* `selector` with as many of its subterms replaced by `$e` as keep + * `nth_env_target` resolving it to the node with id `node` in `goal`, at + * an index no greater than `index`, and the index it resolves at. Only a + * replacement that passes this check is kept, so a `selector` that misses + * the node comes back unchanged. Subterms are tried outermost first, then + * left to right, so a whole argument becomes one `$e` before its parts are + * tried. */ +let generalize = + ( + ~statics: ProofStatics.t, + ~env: Environment.t(Exp.t), + ~index: int, + selector: Exp.t, + node: Id.t, + goal: Exp.t, + ) + : (Exp.t, int) => { + let index_of = candidate => + List.init(index + 1, ~f=n => n) + |> List.find(~f=n => + Option.equal( + Id.equal, + Option.map( + ~f=Exp.rep_id, + nth_env_target(~statics, ~env, candidate, n, goal), + ), + Some(node), + ) + ); + List.fold_left( + ~f= + ((current, _) as best, sub) => + switch (Exp.find_by_id(Exp.rep_id(sub), current)) { + /* Inside a subterm already replaced. */ + | None => best + /* The `_` of `f(_, x)` is what makes it a partial application: + * written as `$e(…)` it reads back as a call. */ + | Some({term: Deferral(_), _}) => best + | Some(_) => + let candidate = + replace_by_id( + Exp.rep_id(sub), + current, + Exp.fresh(Var(MetaVar.any_name)), + ); + switch (index_of(candidate)) { + | Some(n) => (candidate, n) + | None => best + }; + }, + ~init=(selector, index), + in_source_order(~stop=_ => false, selector), + ); +}; + +/* The node of `onto` at the position the node with id `id` has in + * `from`, for two copies of one term with different ids. */ +let rec at_same_position = + (~from: Exp.t, ~onto: Exp.t, id: Id.t): option(Exp.t) => + if (Id.equal(Exp.rep_id(from), id)) { + Some(onto); + } else { + let (from_kids, onto_kids) = (children(from), children(onto)); + List.length(from_kids) == List.length(onto_kids) + ? List.zip_exn(from_kids, onto_kids) + |> List.find_map(~f=((f, o)) => + at_same_position(~from=f, ~onto=o, id) + ) + : None; + }; + +/* The patterns binding variables around the node with id `id` in `e`, + * outermost first: the parameters of the `fun`s, `fix`es and `forall`s + * it is inside, the patterns of the `let`s whose body it is in, and of + * the case arms it is in. Empty if `id` isn't in `e`. */ +let binders = (id: Id.t, e: Exp.t): list(Pat.t) => { + let rec go = (outer: list(Pat.t), e: Exp.t): option(list(Pat.t)) => + if (Id.equal(Exp.rep_id(e), id)) { + Some(List.rev(outer)); + } else { + let under = p => go([p, ...outer]); + switch (Exp.term_of(e)) { + | Fun(p, _, _, _) + | FixF(p, _, _) + | Forall(p, _) => List.find_map(~f=under(p), children(e)) + | Let(p, def, body) => + switch (go(outer, def)) { + | Some(_) as found => found + | None => under(p, body) + } + | Match(scrut, rules) => + switch (go(outer, scrut)) { + | Some(_) as found => found + | None => + List.find_map(~f=((p, branch)) => under(p, branch), rules) + } + | _ => List.find_map(~f=go(outer), children(e)) + }; + }; + go([], e) |> Option.value(~default=[]); +}; diff --git a/src/language/proof/ProofCheck.re b/src/language/proof/ProofCheck.re new file mode 100644 index 0000000000..b993f18be8 --- /dev/null +++ b/src/language/proof/ProofCheck.re @@ -0,0 +1,1972 @@ +open Util; + +/* Proof checker (big-step). + * + * Walks a proof term, threading an "incoming" goal through each sub-form + * and producing an "outgoing" goal (if the proof propagates through). + * The walk also builds a ProofMap keyed by each proof sub-term id, + * recording the (incoming, outgoing) pair seen at that node, the + * `ProofMark.t` errors of the step and the obligations it incurs. + * + * A step that fails records its mark but passes the incoming goal + * through, so later steps are still checked against the last good goal. + * Because that can carry `true`/`false` past a broken step, proven and + * disproven status also require a mark-free proof subtree + * (`ProofMap.status_of_proof`). + * + * The rewrite steps, binder peeling and funext goals are + * shared with the UI stepper, so both compute a step the same way. + * + * This module doesn't depend on the dynamics (`Transition`, + * `Evaluator`): when the checker needs to take an evaluation step, it + * calls the injected `step_fn`, which the evaluator supplies when it + * invokes the checker. + */ + +type step_result = { + auto_incoming: list((string, Exp.t)), + auto_outgoing: list((Exp.t, string)), + outgoing: Exp.t, +}; + +/* Where a `step_fn` takes its step: at the first redex in evaluation + * order, or only at the root of the expression it is given. */ +type redex_at = + | Anywhere + | Root; + +type step_fn = + (~env: Environment.t(Exp.t), ~at: redex_at, Exp.t) => option(step_result); + +let record = + ( + ~ctx: SemanticCtx.t, + ~marks: list(ProofMark.t)=[], + ~auto_incoming: list((string, Exp.t))=[], + ~auto_outgoing: list((Exp.t, string))=[], + ~obligations: list(Obligation.t)=[], + id: Id.t, + incoming: option(Exp.t), + outgoing: option(Exp.t), + m: ProofMap.t, + ) + : ProofMap.t => + ProofMap.add( + id, + { + incoming, + auto_incoming, + auto_outgoing, + outgoing, + marks, + obligations, + ctx, + }, + m, + ); + +let is_true = (goal: option(Exp.t)): bool => + switch (goal) { + | Some(e) => Exp.fast_equal(e, Exp.temp(Atom(Bool(true)))) + | None => false + }; + +/* The name a naming form (`assume h = P`) asks for, or the form's fixed + * base name when it names nothing. A hole or a compound pattern names nothing, + * so it also gets the base name rather than dropping the hypothesis. + * Base names shadow; see `SemanticCtx.add_hypothesis`. + * + * The checker runs on the elaborated proof, where a bare identifier + * pattern can arrive wrapped (`Parens`, `Asc`), so the name is read + * through `Pat.bound_vars` rather than by matching `Var`. */ +let name_or = (~default: Var.t, name: option(Pat.t)): Var.t => + switch (Option.map(~f=Pat.bound_vars, name)) { + | Some([h]) => h + | Some(_) + | None => default + }; + +/* Discharging an obligation's goal: by lookup of a fact in scope, then by + * closed evaluation, and by nothing else, so a user can always see why + * an obligation was discharged. */ +module Discharge = { + /* The only normalization in the discharge relation: `P == true` and + * `true == P` normalize to `P`, recursively. + * + * The obligations panel's split exit needs it: `cases P | true => + * ... | false => ...` installs `P == true` as the true branch's + * hypothesis, and the obligation the branch has to retire is the bare + * `P`. + * + * Sound in the flat domain: `P == true` denotes `true` only when `P` + * does (if `P` is `false` the equation is `false`; if `P` is `err` or ⊥ + * so is the equation). Being an equivalence, it can be applied to both + * sides. */ + let rec strip_eq_true = (e: Exp.t): Exp.t => + switch (Exp.term_of(e)) { + | BinOp(Poly(Equals), a, b) when is_true(Some(b)) => strip_eq_true(a) + | BinOp(Poly(Equals), a, b) when is_true(Some(a)) => strip_eq_true(b) + | Parens(e') => strip_eq_true(e') + | _ => e + }; + + /* The id of a fact in scope (`SemanticCtx.facts`) equal to `goal`, up + * to `strip_eq_true`: as written, or else once the definitions they + * name are unfolded where they differ. With `proven`, a theorem not + * proven is passed over: it can be reverted, but discharges nothing. */ + let lookup = (~proven=false, ctx: SemanticCtx.t, goal: Exp.t): option(Id.t) => { + let goal_nf = strip_eq_true(goal); + let find = same => + SemanticCtx.facts(ctx) + |> List.find_map(~f=((_name, id, fact)) => + switch (proven, SemanticCtx.verdict(ctx, id)) { + | (true, Some(Unfinished | Refuted)) => None + | _ => + same(fact, goal) || same(strip_eq_true(fact), goal_nf) + ? Some(id) : None + } + ); + switch (find(Exp.fast_equal)) { + | Some(_) as found => found + | None => find(MatchExp.equal_modulo(~defs=SemanticCtx.get_env(ctx))) + }; + }; + + let has_subterm = (matches: Exp.t => bool, e: Exp.t): bool => { + let found = ref(false); + let _: Exp.t = + Exp.map_term( + ~f_exp= + (continue, e) => + if (matches(e)) { + found := true; + e; + } else { + continue(e); + }, + e, + ); + found^; + }; + + /* Runs `step` to a fixpoint. The fuel bound is generous, since + * `step_fn` has no termination signal. + * + * It stops at the first term holding a dynamic error (`1 / 0`). Each + * `step` starts afresh, so it would redo the failed operation inside + * the error hole and wrap a new hole around it: the term grows on every + * step and never gets anywhere. Stopping only leaves a goal pending, + * since a term with an error in it isn't `true`. */ + let evaluate = (~step: step_fn, ~env, e: Exp.t): Exp.t => { + let is_error = (e: Exp.t) => + switch (Exp.term_of(e)) { + | DynamicErrorHole(_) => true + | _ => false + }; + let rec go = (fuel, e) => + switch (fuel <= 0 ? None : step(~env, ~at=Anywhere, e)) { + | Some({outgoing, _}) when has_subterm(is_error, outgoing) => outgoing + | Some({outgoing, _}) => go(fuel - 1, outgoing) + | None => e + }; + go(1000, e); + }; + + /* How `goal` is discharged: by lookup, or else by closed evaluation to + * `true`. Only a goal whose free variables are all definitions + * (`2 != 0`, `f(2) > 0`) is evaluated, and not one that calls a + * recursive function: only explicit steps (`step`) run those. Both are + * judged on a copy with the definitions substituted. */ + let find = (~step: step_fn, ~ctx: SemanticCtx.t, goal: Exp.t) => { + let substituted = + lazy(Substitution.in_exp(SemanticCtx.get_env(ctx), goal)); + /* Statics against an empty ctx leave an empty co-context exactly + * when there are no free variables. */ + let is_closed = () => { + let goal = Lazy.force(substituted); + let (statics, _) = + Statics.mk( + ~ana=Typ.temp(Atom(Bool)), + CoreSettings.on, + Ctx.empty, + goal, + ); + switch (Statics.Map.lookup_exp(Exp.rep_id(goal), statics)) { + | Some(info) => List.is_empty(Info.exp_co_ctx(info)) + | None => true + }; + }; + /* With its definitions substituted, every recursive function a goal + * can call (written in the goal, in a user's closure or in a builtin) + * is a `FixF` node in it. */ + let has_fixpoint = () => + has_subterm( + e => + switch (Exp.term_of(e)) { + | FixF(_) => true + | _ => false + }, + Lazy.force(substituted), + ); + switch (lookup(~proven=true, ctx, goal)) { + | Some(fact_id) => Obligation.Remote(fact_id) + | None when is_closed() && !has_fixpoint() => + is_true(Some(evaluate(~step, ~env=SemanticCtx.get_env(ctx), goal))) + ? Obligation.Evaluated : Obligation.Pending + | None => Obligation.Pending + }; + }; + + /* The obligation to prove `goal`, incurred at step `origin` and + * discharged if it can be. */ + let obligation = + ( + ~step: step_fn, + ~ctx: SemanticCtx.t, + ~origin: Id.t, + ~kind: Obligation.kind, + goal: Exp.t, + ) + : Obligation.t => + Obligation.{ + origin, + kind, + bindings: SemanticCtx.get_ctx(ctx).entries, + goal, + discharge: find(~step, ~ctx, goal), + }; +}; + +/* The proposition a `revert` or `alias` step cites: a + * hypothesis or theorem by name, looked up in the theorem namespace so + * that `revert h` names the same thing `rewrite h` does, or else the + * proposition as spelled out. */ +let cited_fact = (~ctx: SemanticCtx.t, e: Exp.t): Exp.t => { + let named = + Option.bind(ProofSyntax.exp_to_name(e), ~f=name => + Ctx.lookup_theorem(SemanticCtx.get_ctx(ctx), name) + ); + switch (named) { + | Some({prop: Some(prop), _}) => prop + | Some({prop: None, _}) + | None => e + }; +}; + +/* A form whose argument is still a hole, as the stepper writes + * `revert ? =>`, is unfinished rather than wrong: like a hole step, it + * passes the goal through unmarked. */ +let is_hole = (e: Exp.t): bool => + switch (Exp.term_of(e)) { + | EmptyHole => true + | _ => false + }; + +/* Definedness gates. + * + * Divergence (⊥) is never a boolean obligation: a failed + * structural-totality check refuses the step (the PossiblyDivergent* + * marks). Domain errors (err) can be stated as booleans: the domain + * scan's conditions are incurred as ordinary obligations. Eval steps + * have no gates: they preserve denotation. */ +module Gate = { + /* For the instantiations an axiom or lemma step's match bound: each + * must be structurally total; `Error(var)` names the first that is not, + * and the step is refused. Otherwise `Ok(conditions)` carries the + * domain scan of the instantiations. Common instantiations (x := y, + * x := 2, x := a + b) pass and scan to nothing. */ + let instantiations = + ( + ~statics: ProofStatics.t, + ~ctx: SemanticCtx.t, + instantiations: list((Var.t, Exp.t)), + ) + : result(list(Exp.t), Var.t) => { + let env = SemanticCtx.get_env(ctx); + /* Totality reads the bodies of the definitions an instantiation + * calls, so it checks a copy with them substituted: recursive ones + * surface their FixF spine, and quantified binders stay bare Vars. */ + let divergent = + List.find_map( + ~f= + ((n, e)) => + switch ( + Totality.check( + ~statics, + ~ctx=SemanticCtx.get_ctx(ctx), + Substitution.in_exp(env, e), + ) + ) { + | Ok () => None + | Error(_) => Some(n) + }, + instantiations, + ); + switch (divergent) { + | Some(n) => Error(n) + | None => + Ok( + instantiations + |> List.concat_map(~f=((_, e)) => DomainConditions.scan(e)) + |> DomainConditions.dedup, + ) + }; + }; + + /* For a split's scrutinee. A bare quantified variable needs nothing: + * quantifiers range over total values. A computed scrutinee has to + * denote a value: for `cases`, so its case equation is a symmetric + * equation, and for `induction`, so the goal is an instance of the + * generalized one. So a possibly-divergent scrutinee is marked and its + * domain conditions become obligations. */ + let scrutinee = + ( + ~step: step_fn, + ~statics: ProofStatics.t, + ~ctx: SemanticCtx.t, + ~origin: Id.t, + scrut: Exp.t, + ) + : (list(ProofMark.t), list(Obligation.t)) => { + let env = SemanticCtx.get_env(ctx); + switch (ProofSyntax.exp_to_name(scrut)) { + /* A scrutinee still to fill in is unfinished, not divergent. */ + | None when is_hole(scrut) => ([], []) + | Some(x) when !Definitions.is_definition(env, x) => ([], []) + | Some(_) + | None => + let marks = + switch ( + Totality.check( + ~statics, + ~ctx=SemanticCtx.get_ctx(ctx), + Substitution.in_exp(env, scrut), + ) + ) { + | Ok () => [] + | Error(_) => [ProofMark.PossiblyDivergentScrutinee] + }; + let obligations = + DomainConditions.scan(scrut) + |> List.map( + ~f=Discharge.obligation(~step, ~ctx, ~origin, ~kind=Definedness), + ); + (marks, obligations); + }; + }; +}; + +// Binders + +/* `ctx` without the facts that mention any of `names`, for a scope in + * which those names are rebound: the facts are about the old binding. + * Unlike `ProofCtx`'s capture check, this also hides them from + * `Discharge.lookup`. */ +let forget_facts_mentioning = + (names: list(Var.t), ctx: SemanticCtx.t): SemanticCtx.t => + SemanticCtx.map_ctx( + Ctx.forget_facts(fact => + ProofRule.mentions_any(ProofRule.exp_to_rule(fact), names) + ), + ctx, + ); + +/* `ctx` extended with the variables `p` binds, at type `ty`. Every proof + * binder goes through here. Names in goals and facts are resolved by + * scope, so a fact that mentions a rebound name is about what the name + * meant outside, and is dropped. That covers a binder that shadows a + * definition (`forall len ->`) as well as one that shadows an earlier + * binder. */ +let bind = (ctx: SemanticCtx.t, p: Pat.t, ty: Typ.t): SemanticCtx.t => + SemanticCtx.add_from_pattern( + forget_facts_mentioning(p |> Pat.bindings |> Binding.variable_names, ctx), + p, + ty, + ); + +/* Peel the outermost binder from a "for all pat, P" goal, for the + * `Forall` proof form: the binder, its type and the body. */ +let rec peel_binder = (goal: Exp.t): option((Pat.t, Typ.t, Exp.t)) => + switch (goal |> Exp.term_of) { + /* `EditorTransform` wraps a spliced sub-term in `Parens` whenever it + * shares a segment level with sibling pieces. */ + | Parens(inner) => peel_binder(inner) + | Fun(p, body, t, _) => + let t = OptUtil.get(() => Typ.fresh(Unknown(Internal)), t); + Some((p, t, body)); + | Forall(p, body) => Some((p, Typ.fresh(Unknown(Internal)), body)) + | _ => None + }; + +/* Introduce a theorem statement's outer binders: extend the semantic ctx + * with each binder's variables, and return the remaining core goal, + * which keeps any `==>` antecedents (those are introduced with + * `assume`). Used by the + * evaluator and the UI stepper to seed the proof goal. */ +let rec peel_stmt_binders = + (ctx: SemanticCtx.t, goal: Exp.t): (SemanticCtx.t, Exp.t) => + switch (goal |> Exp.term_of) { + /* Transparent, for the reason spelled out on `peel_binder`. */ + | Parens(inner) => peel_stmt_binders(ctx, inner) + | Forall(p, body) => + let ctx = bind(ctx, p, Typ.fresh(Unknown(Internal))); + peel_stmt_binders(ctx, body); + | _ => (ctx, goal) + }; + +// Rewrite steps + +/* A rewrite step's effect, for a step that only rewrites. */ +let rewritten = (outgoing: Exp.t): step_result => { + auto_incoming: [], + auto_outgoing: [], + outgoing, +}; + +/* `axiom end`: rewrite the goal with a rule in scope. */ +module Axiom = { + /* The rewritten goal, with the rule's assumptions instantiated by the + * match (the conditions the step incurs as obligations) and the + * metavariable instantiations the match bound (for + * `Gate.instantiations`). + * + * Every binder of the rule must be assigned, by the match or by a + * `with = ` clause (`~instantiation`), or the step is + * refused (`UnderdeterminedInstantiation`). The `with` binding is + * seeded into the match context before matching and returned with the + * matched ones, so the same gates apply to it. */ + let apply = + ( + ~statics: ProofStatics.t, + ~ctx: SemanticCtx.t, + ~direction: Direction.t, + ~equality: string, + ~instantiation: option((Var.t, Exp.t))=None, + goal: Exp.t, + ) + : result((Exp.t, list(Exp.t), list((Var.t, Exp.t))), ProofMark.t) => { + open Result.Syntax; + let env = SemanticCtx.get_env(ctx); + let proof_ctx = + ProofCtx.of_theorem_ctx( + ~builtins=Axioms.v, + ~captured=ctx.captured, + SemanticCtx.get_ctx(ctx), + ); + let* rule = + ProofCtx.lookup_rule(equality, proof_ctx) + |> Result.of_option(~error=ProofMark.UnknownEquality(equality)); + /* A cited rule with a boolean conclusion `P` reads as `P == true`. + * `~statics` settles conclusions whose shape doesn't (a plain + * variable, a Bool-typed application). */ + let rule = ProofRule.BoolReading.apply(~statics=Some(statics), rule); + let* bindings = + switch (instantiation) { + | None => Ok(None) + | Some((var, inst)) => + ProofRule.Rewrite.seed( + var, + inst, + ProofRule.Rewrite.empty_bindings(rule.bindings), + ) + |> Option.map(~f=Option.some) + |> Result.of_option( + ~error= + ProofMark.UnknownInstantiationVar({ + equality, + var, + }), + ) + }; + /* An explicit citation names the direction, so the boolean reading's + * `true |-> P` direction is offered here although rule discovery + * suppresses it. */ + let (l, r) = + ProofRule.Rewrite.matches( + ~statics, + ~env, + ~bindings?, + ~reverse=true, + rule, + goal, + ); + let rewrite = + switch (direction) { + | Direction.Left => l + | Direction.Right => r + }; + switch (rewrite) { + | None => + Error( + RuleDoesNotApply({ + equality, + direction, + }), + ) + | Some((_, mctx)) when ProofRule.Rewrite.has_unassigned(mctx) => + Error(UnderdeterminedInstantiation({equality: equality})) + | Some((w, mctx)) => + let conditions = + List.map(~f=MatchExp.substitute_exp(mctx), rule.assumptions); + let instantiations = + List.filter_map( + ~f=((n, (_, assigned))) => Option.map(~f=e => (n, e), assigned), + mctx, + ); + Ok((Exp.replace_all_ids(w), conditions, instantiations)); + }; + }; + + /* The step as written: the rule's instantiated assumptions and the + * instantiations' domain conditions are its obligations. */ + let check = + ( + ~step: step_fn, + ~statics: ProofStatics.t, + ~ctx: SemanticCtx.t, + ~origin: Id.t, + ~direction: Direction.t, + ~equality: Exp.t, + ~instantiation: option((Exp.t, Exp.t)), + goal: Exp.t, + ) + : result((step_result, list(Obligation.t)), ProofMark.t) => { + open Result.Syntax; + let* equality = + ProofSyntax.exp_to_name(equality) + |> Result.of_option(~error=ProofMark.MalformedEqualityName); + let* () = + switch (SemanticCtx.cited_verdict(ctx, equality)) { + | Some(Refuted) => Error(ProofMark.CitesRefuted(equality)) + | Some(Proven | Unfinished) + | None => Ok() + }; + /* A non-variable `with ` slot is reported like an unknown binder + * name. */ + let* instantiation = + switch (instantiation) { + | None => Ok(None) + | Some((var, inst)) => + switch (ProofSyntax.exp_to_name(var)) { + | Some(var) => Ok(Some((var, inst))) + | None => + Error( + ProofMark.UnknownInstantiationVar({ + equality, + var: "?", + }), + ) + } + }; + let* (out, conditions, instantiations) = + apply(~statics, ~ctx, ~direction, ~equality, ~instantiation, goal); + switch (Gate.instantiations(~statics, ~ctx, instantiations)) { + | Error(var) => + Error( + PossiblyDivergentInstantiation({ + equality, + var, + }), + ) + | Ok(domain_conditions) => + /* A condition that is both a premise and a domain condition is + * shown once, as the premise the rule states. */ + let premises = DomainConditions.dedup(conditions); + let domain_conditions = + DomainConditions.dedup(domain_conditions) + |> List.filter(~f=c => !List.exists(~f=Exp.fast_equal(c), premises)); + let obligations = + List.map( + ~f=Discharge.obligation(~step, ~ctx, ~origin, ~kind=Premise), + premises, + ) + @ List.map( + ~f=Discharge.obligation(~step, ~ctx, ~origin, ~kind=Definedness), + domain_conditions, + ); + let citation = + switch (Ctx.lookup_theorem(SemanticCtx.get_ctx(ctx), equality)) { + | Some({id, prop: Some(statement), _}) + when Poly.equal(SemanticCtx.verdict(ctx, id), Some(Unfinished)) => [ + Discharge.obligation( + ~step, + ~ctx, + ~origin, + ~kind=Citation, + statement, + ), + ] + | Some(_) + | None => [] + }; + Ok((rewritten(out), obligations @ citation)); + }; + }; +}; + +/* `algebra end`: replace the goal with an expression the + * CAS finds equal to it. The CAS's field laws are false for IEEE floats, + * so a Float-typed rewrite is refused. It reasons in a field, so both + * sides' domain conditions are its obligations. + * + * The CAS verifies the equation only for Int arithmetic it is right + * about: Int literals, +, −, ×, unary −, and ** with a literal exponent + * ≥ 0, over variables known to be Int. It verifies Nat literals, +, × and + * ** over variables known to be Nat the same way: such an expression has + * the value of the same polynomial over Int, and polynomials equal on + * every Nat are equal. Nat subtraction truncates, so it stays out. + * Definitions are substituted first, + * so one whose value is a literal counts as that literal, and one whose + * value is an error or a function leaves the fragment. A step the CAS + * finds wrong is refused. Any other step incurs its equation as an + * obligation. */ +module Algebrite = { + type verdict = + | Equal + | Differ + | Unverified; + + let verify = + (~statics: ProofStatics.t, ~ctx: SemanticCtx.t, goal, replacement) + : verdict => { + /* By the statics at this occurrence, or else by the checker's binder + * for it: the statics type a proof's `forall x =>` binder `Unknown`, + * where the checker binds it at the goal's type. */ + let has_cls = (cls: Atom.cls, x: Exp.t, name: Var.t): bool => { + let binder_typ = () => + Ctx.lookup_var(SemanticCtx.get_ctx(ctx), name) + |> Option.map(~f=(entry: Ctx.var_entry) => + Typ.term_of(Typ.normalize(Ctx.empty, entry.typ)) + ); + switch (Option.map(~f=Typ.term_of, statics.typ(Exp.rep_id(x)))) { + | Some(Unknown(_)) + | None => Poly.equal(binder_typ(), Some(Atom(cls))) + | Some(ty) => Poly.equal(ty, Atom(cls)) + }; + }; + /* Variables are renamed, since Algebrite reads `i` as the imaginary + * unit and `e` as Euler's number. */ + let names = ref([]); + let rename = name => + switch (List.Assoc.find(names^, name, ~equal=String.equal)) { + | Some(renamed) => renamed + | None => + let renamed = "hzv" ++ string_of_int(List.length(names^)); + names := [(name, renamed), ...names^]; + renamed; + }; + /* `cls` is Int or Nat. Every operator and operand has to be of it: a + * Nat variable under an Int `+` is ill-typed and doesn't evaluate. */ + let rec print = (cls: Atom.cls, e: Exp.t): option(string) => { + open OptUtil.Syntax; + let binary = (a, op, b) => { + let* a = print(cls, a); + let+ b = print(cls, b); + "(" ++ a ++ ")" ++ op ++ "(" ++ b ++ ")"; + }; + switch (cls, Exp.term_of(e)) { + | (Int, Atom(Int(n))) + | (Nat, Atom(Nat(n))) => Some("(" ++ Bigint.to_string(n) ++ ")") + | (_, Var(x)) when has_cls(cls, e, x) => Some(rename(x)) + | (_, Parens(e) | Asc(e, _)) => print(cls, e) + | (Int, UnOp(Int(Minus), e)) => + print(cls, e) |> Option.map(~f=e => "-(" ++ e ++ ")") + | (Int, BinOp(Int(Plus), a, b)) + | (Nat, BinOp(Nat(Plus), a, b)) => binary(a, "+", b) + | (Int, BinOp(Int(Minus), a, b)) => binary(a, "-", b) + | (Int, BinOp(Int(Times), a, b)) + | (Nat, BinOp(Nat(Times), a, b)) => binary(a, "*", b) + | (Int, BinOp(Int(Power), a, {term: Atom(Int(n)), _} as b)) + when Bigint.(>=)(n, Bigint.zero) => + binary(a, "^", b) + | (Nat, BinOp(Nat(Power), a, {term: Atom(Nat(_)), _} as b)) => + binary(a, "^", b) + | _ => None + }; + }; + let substituted = Substitution.in_exp(SemanticCtx.get_env(ctx)); + let printed = (cls: Atom.cls) => + OptUtil.zip( + print(cls, substituted(goal)), + print(cls, substituted(replacement)), + ); + let sides = + switch (printed(Int)) { + | Some(_) as sides => sides + | None => printed(Nat) + }; + switch (sides) { + | Some((l, r)) => + switch (Cas.run^("simplify((" ++ l ++ ")-(" ++ r ++ "))")) { + | Some("0") => Equal + | Some(_) => Differ + | None => Unverified + } + | _ => Unverified + }; + }; + + let check = + ( + ~step: step_fn, + ~statics: ProofStatics.t, + ~ctx: SemanticCtx.t, + ~origin: Id.t, + ~replacement: Exp.t, + goal: Exp.t, + ) + : result((step_result, list(Obligation.t)), ProofMark.t) => { + /* The statics first, with a syntactic fallback (a float literal or + * float arithmetic at the head) for expressions the statics didn't + * reach. */ + let is_float = (e: Exp.t): bool => { + let rec float_head = (e: Exp.t): bool => + switch (e |> Exp.term_of) { + | Parens(e1) + | Projector(_, e1) => float_head(e1) + | Atom(Float(_)) => true + | UnOp(Float(_), _) => true + | BinOp(Float(Plus | Minus | Times | Power | Divide), _, _) => true + | _ => false + }; + switch (statics.typ(Exp.rep_id(e))) { + | Some(ty) => + switch (Typ.term_of(ty)) { + | Atom(Float) => true + | Unknown(_) => float_head(e) + | _ => false + } + | None => float_head(e) + }; + }; + let obligation = Discharge.obligation(~step, ~ctx, ~origin); + let domain_conditions = () => + DomainConditions.dedup( + DomainConditions.scan(goal) @ DomainConditions.scan(replacement), + ) + |> List.map(~f=obligation(~kind=Definedness)); + let rewritten = rewritten(Exp.replace_all_ids(replacement)); + if (is_float(goal) || is_float(replacement)) { + Error(ProofMark.FloatAlgebrite); + } else { + switch (verify(~statics, ~ctx, goal, replacement)) { + | Equal => Ok((rewritten, domain_conditions())) + | Differ => Error(ProofMark.AlgebraDiffers) + | Unverified => + let equation = + Exp.fresh(BinOp(Poly(Equals), goal, replacement)) + |> obligation(~kind=Algebra); + Ok((rewritten, domain_conditions() @ [equation])); + }; + }; + }; +}; + +/* A redex contracts whatever its argument is: a lambda with a + * one-variable parameter, or a named function that isn't recursive, + * applied to anything, or a `let` binding one variable. A destructuring + * parameter needs its argument's shape, and a recursive function unfolds + * by evaluation. */ +module Beta = { + /* The redex at the root of `e`: its variable, body and argument. */ + let redex = + (~env: Environment.t(Exp.t), e: Exp.t): option((Var.t, Exp.t, Exp.t)) => { + open OptUtil.Syntax; + /* The statics name a recursive function `f+` (`Definitions.fold`). */ + let is_recursive = (name: option(Var.t)) => + switch (name) { + | Some(f) => + String.length(f) > 0 && Char.equal(f.[String.length(f) - 1], '+') + | None => false + }; + /* Not through a closure: its body's names mean what its environment + * says, not what the goal's scope does. */ + let rec lambda = (f: Exp.t) => + switch (Exp.term_of(f)) { + | Parens(f) + | Asc(f, _) => lambda(f) + | Fun(p, body, _, name) when !is_recursive(name) => + let+ x = ProofSyntax.pat_to_name(p); + (x, body); + | _ => None + }; + switch (Exp.term_of(ProofSyntax.unwrap(e))) { + | Ap(Forward, f, arg) => + /* A definition is unfolded, closed, only once its value shows it is + * such a lambda. */ + let* head = + switch (ProofSyntax.exp_to_name(f)) { + | Some(name) => + let* value = Environment.lookup(env, name); + let* _ = lambda(ProofSyntax.unwrap(value)); + Definitions.unfold(env, name); + | None => Some(f) + }; + let+ (x, body) = lambda(head); + (x, body, arg); + | Let(p, def, body) => + switch (Exp.term_of(ProofSyntax.unwrap(def))) { + | FixF(_) => None + | _ => + let+ x = ProofSyntax.pat_to_name(p); + (x, body, def); + } + | _ => None + }; + }; + + /* `body` with `arg` for `x`, without capturing a variable of `arg`. */ + let contract = ((x, body, arg): (Var.t, Exp.t, Exp.t)): Exp.t => + Substitution.in_exp(Substitution.env_for([(x, arg)], ~into=body), body) + |> Exp.replace_all_ids; +}; + +/* `step`: one evaluation step at the root of the goal, or, where + * evaluation takes none, the redex there contracted (`Beta`). Evaluation + * contracts a lambda or `let` itself whatever the argument, as a variable + * pattern matches anything, but not a named function whose argument isn't + * a value yet. The evaluator inlines the definitions it looks up, and the + * goals it leaves name them again (`Definitions.fold`). */ +module Eval = { + let check = + (~step: step_fn, ~env: Environment.t(Exp.t), goal: Exp.t) + : result((step_result, list(Obligation.t)), ProofMark.t) => { + let fold = Definitions.fold(env); + switch (step(~env, ~at=Root, goal)) { + | Some({auto_incoming, auto_outgoing, outgoing}) => + Ok(( + { + auto_incoming: + List.map(~f=((j, e)) => (j, fold(e)), auto_incoming), + auto_outgoing: + List.map(~f=((e, j)) => (fold(e), j), auto_outgoing), + outgoing: fold(outgoing), + }, + [], + )) + | None => + switch (Beta.redex(~env, goal)) { + | Some(redex) => Ok((rewritten(fold(Beta.contract(redex))), [])) + | None => Error(ProofMark.NothingToStep) + } + }; + }; +}; + +/* `funext x => body`: functional extensionality as an intro rule. + * + * It applies exactly when the goal is `l == r` and the two sides are + * functions: an arrow at the head of the type. `==` between two lists of + * functions is an induction, not extensionality, so `Typ.has_fun` (true + * of `[a -> b]`) is the wrong test. + * + * Evidence, in order: + * 1. Statics: the recorded type of either side is an `Arrow`. This is + * the answer whenever the statics reached the goal (the usual case + * in a theorem statement). + * 2. Syntax: either side is literally a lambda (`fun` / a `Parens` + * around one). Covers goals statics left `Unknown`, + * and gives a domain annotation when the lambda carries one. + * 3. The env: a bare variable naming a function definition. + * `inv == (fun x -> 1 / x)` has a lambda on the right, so this is + * mostly for the both-sides-named case. */ +module Funext = { + /* Follows a bare variable through the env to its definition. */ + let rec syntactic_domain = + (~env: Environment.t(Exp.t), e: Exp.t): option(Typ.t) => + switch (e |> Exp.term_of) { + | Parens(inner) => syntactic_domain(~env, inner) + | Fun(p, _, t, _) => + let rec ascribed = (p: Pat.t) => + switch (Pat.term_of(p)) { + | Parens(p) => ascribed(p) + | Asc(_, t) => Some(t) + | _ => None + }; + switch (ascribed(p), Option.map(~f=Typ.term_of, t)) { + | (Some(d), _) + | (None, Some(Arrow(d, _))) => Some(d) + | (None, _) => Some(Typ.fresh(Unknown(Internal))) + }; + /* A closure/fix wrapper around a lambda still denotes a function. */ + | Closure(_, inner) + | FixF(_, inner, _) => syntactic_domain(~env, inner) + | Var(x) => + switch (Environment.lookup(env, x)) { + /* Guard against a self-referential binding looping the lookup. */ + | Some({term: Var(y), _}) when String.equal(y, x) => None + | Some(d) => syntactic_domain(~env, d) + | None => None + } + | _ => None + }; + + /* `Some((l, r, domain))` when `goal` is `l == r` at an arrow type. The + * domain is the type to bind the funext binder at: `Unknown(Internal)` + * when the sides are known to be functions but not at what type, as + * `peel_binder` does for a `Forall` binder. */ + let rec goal = + (~statics: ProofStatics.t, ~env: Environment.t(Exp.t), g: Exp.t) + : option((Exp.t, Exp.t, Typ.t)) => + switch (g |> Exp.term_of) { + /* Parens are transparent here for the same reason they are in + * `peel_binder`: an editor splice must not hide the equality. */ + | Parens(inner) => goal(~statics, ~env, inner) + | BinOp(Poly(Equals), l, r) => + let statics_domain = (e: Exp.t): option(Typ.t) => + switch (Option.map(~f=Typ.term_of, statics.typ(Exp.rep_id(e)))) { + | Some(Arrow(d, _)) => Some(d) + | Some(_) + | None => None + }; + let domain = + switch (statics_domain(l), statics_domain(r)) { + | (Some(d), _) + | (None, Some(d)) => Some(d) + | (None, None) => + switch (syntactic_domain(~env, l)) { + | Some(d) => Some(d) + | None => syntactic_domain(~env, r) + } + }; + domain |> Option.map(~f=d => (l, r, d)); + | _ => None + }; + + /* The body's goal `l(x) == r(x)`, for the funext binder `binder` read + * as an expression. + * + * When a side is a literal lambda, the application is a beta-redex + * whose argument is a bound variable (hence a value), so contracting + * it is definitional: it renames the parameter and discovers nothing. + * Contracting here lets `(fun x -> x + 1) == (fun x -> 1 + x)` be + * proved by a pointwise `algebra` without a leading `step` on each + * side. Not contracted: + * - a named function (`inv(x)`, `f(x)`). Unfolding a definition is + * `step`'s job, and keeping the `Ap` is why `refl` closes + * `inv(x) == inv(x)` without ever applying `inv`. + * - a non-variable parameter pattern (a tuple, say): there is no + * single name to substitute for. */ + let pointwise = (~binder: Pat.t, l: Exp.t, r: Exp.t): Exp.t => { + let arg = Exp.of_pat(binder); + /* The binder's own variables map to themselves, so that substitution + * renames a lambda's inner binder that would capture them. */ + let binder_vars = + List.map(~f=x => (x, Exp.fresh(Var(x))), Pat.bound_vars(binder)); + let rec apply = (f: Exp.t): Exp.t => + switch (f |> Exp.term_of) { + | Parens(inner) => apply(inner) + | Fun(p, body, _, _) => + switch (ProofSyntax.pat_to_name(p)) { + | Some(x) => + body + |> Substitution.in_exp( + Environment.of_bindings(binder_vars @ [(x, arg)]), + ) + | None => Exp.fresh(Ap(Forward, f, arg)) + } + | _ => Exp.fresh(Ap(Forward, f, arg)) + }; + /* The goal is spliced together from trees that still carry their + * source ids, so it is freshened whole: + * - the same `arg` node is written into both sides, so one + * expression claims the binder's tiles twice, and + * `Highlight.of_tile` fails on a double-click in the inner + * stepper; + * - `l`/`r` are the incoming goal's own subtrees, so clicking one of + * their tokens parks the caret in the outer occurrence. + * This is what `StepperPicker.Terms.embed_exp` does when splicing an + * expression into proof syntax. It has to happen before the ProofMap + * records the body's incoming goal, since the inner stepper and every + * lookup on the body resolve against this tree. */ + Exp.fresh(BinOp(Poly(Equals), apply(l), apply(r))) + |> Exp.replace_all_ids; + }; +}; + +// The walk + +/* An axiom, algebrite or eval step rewrites the goal at its root. With no + * goal there is nothing to rewrite; a step that doesn't apply is marked + * and passes the goal through. */ +let check_rewrite = + ( + ~ctx: SemanticCtx.t, + ~id: Id.t, + incoming: option(Exp.t), + apply: + Exp.t => result((step_result, list(Obligation.t)), ProofMark.t), + ) + : (option(Exp.t), ProofMap.t) => + switch (incoming) { + | None => ( + None, + record( + ~ctx, + ~marks=[ProofMark.MissingIncoming], + id, + None, + None, + ProofMap.empty, + ), + ) + | Some(goal) => + switch (apply(goal)) { + | Ok(({auto_incoming, auto_outgoing, outgoing}, obligations)) => + let outgoing = Some(outgoing); + ( + outgoing, + record( + ~ctx, + ~auto_incoming, + ~auto_outgoing, + ~obligations, + id, + incoming, + outgoing, + ProofMap.empty, + ), + ); + | Error(mark) => ( + incoming, + record(~ctx, ~marks=[mark], id, incoming, incoming, ProofMap.empty), + ) + } + }; + +/* What each case of a split gets besides its pattern's bindings: for + * `cases`, the case equation `scrut == pat` as `case_eq`; for + * `induction`, the inductive hypotheses, with the facts that mention the + * scrutinee out of scope. */ +type case_facts = + | CaseEquation + | InductiveHypotheses; + +/* Threads `incoming` through the proof tree, returning the outgoing goal + * (if the proof propagates) and a proof map with an entry at every proof + * sub-term id. */ +let rec check = + ( + ~step: step_fn, + ~statics: ProofStatics.t, + ~ctx: SemanticCtx.t, + incoming: option(Exp.t), + proof: Proof.t, + ) + : (option(Exp.t), ProofMap.t) => { + let id = Proof.rep_id(proof); + switch (proof.term) { + /* A hole is an unfinished proof, not an error: it passes the goal + * through unmarked, so later steps keep working. */ + | EmptyHole => ( + incoming, + record(~ctx, id, incoming, incoming, ProofMap.empty), + ) + /* Unparseable proof text, or a multi-hole, whose children aren't proof + * terms. */ + | Invalid(_) + | MultiHole(_) => ( + incoming, + record( + ~ctx, + ~marks=[ProofMark.MalformedProofTerm], + id, + incoming, + incoming, + ProofMap.empty, + ), + ) + | Seq(p1, p2) => + let (out1, m1) = check(~step, ~statics, ~ctx, incoming, p1); + let (out2, m2) = check(~step, ~statics, ~ctx, out1, p2); + (out2, record(~ctx, id, incoming, out2, ProofMap.union(m1, m2))); + /* The parens node records the inner step's outgoing too, so the UI can + * key off either id. */ + | Parens(p) => + let (out, m) = check(~step, ~statics, ~ctx, incoming, p); + (out, record(~ctx, id, incoming, out, m)); + | AxiomStep({direction, equality, instantiation}) => + check_rewrite( + ~ctx, + ~id, + incoming, + Axiom.check( + ~step, + ~statics, + ~ctx, + ~origin=id, + ~direction, + ~equality, + ~instantiation, + ), + ) + | AlgebriteStep(replacement) => + check_rewrite( + ~ctx, + ~id, + incoming, + Algebrite.check(~step, ~statics, ~ctx, ~origin=id, ~replacement), + ) + | EvalStep => + check_rewrite( + ~ctx, + ~id, + incoming, + Eval.check(~step, ~env=SemanticCtx.get_env(ctx)), + ) + | Focus({ordinal, selector, body}) => + check_focus( + ~step, + ~statics, + ~ctx, + ~id, + incoming, + ordinal |> Option.map(~f=Annotated.term_of) |> Option.value(~default=1), + selector, + body, + ) + | Forall(pat, body) => + check_forall(~step, ~statics, ~ctx, ~id, incoming, pat, body) + | Funext(pat, body) => + check_funext(~step, ~statics, ~ctx, ~id, incoming, pat, body) + | Assume(e, name, body) => + check_assume(~step, ~statics, ~ctx, ~id, incoming, e, name, body) + /* Nothing is assumed, and the goal passes through. */ + | Have(e, _, sub, body) when is_hole(e) => + let (_, m_sub) = check(~step, ~statics, ~ctx, Some(e), sub); + let (_, m_body) = check(~step, ~statics, ~ctx, incoming, body); + ( + incoming, + record(~ctx, id, incoming, incoming, ProofMap.union(m_sub, m_body)), + ); + | Have(e, name, sub, body) => + check_have(~step, ~statics, ~ctx, ~id, incoming, e, name, sub, body) + | Generalize(e, body) => + check_generalize(~step, ~statics, ~ctx, ~id, incoming, e, body) + | Revert(e, instantiation, body) => + check_revert(~step, ~statics, ~ctx, ~id, incoming, e, instantiation, body) + | Alias(x, e, body) => + check_alias(~step, ~statics, ~ctx, ~id, incoming, x, e, body) + | Cases(scrut, cases) => + check_split( + ~step, + ~statics, + ~ctx, + ~id, + incoming, + scrut, + CaseEquation, + cases, + ) + | Induction(scrut, cases) => + check_split( + ~step, + ~statics, + ~ctx, + ~id, + incoming, + scrut, + InductiveHypotheses, + cases, + ) + }; +} + +/* A form that can't act on the goal: mark it, pass the goal through, and + * check the body against the unchanged goal so later steps stay + * meaningful. */ +and pass_through = + (~step, ~statics, ~ctx, ~id, ~marks, incoming, body) + : (option(Exp.t), ProofMap.t) => { + let (_, m) = check(~step, ~statics, ~ctx, incoming, body); + (incoming, record(~ctx, ~marks, id, incoming, incoming, m)); +} + +/* A form whose body proves a goal of its own instead of the incoming one + * (a peeled binder's body, a pointwise equation, a re-quantified or + * reverted goal). The body's partial result is about that goal, so the + * form discharges the incoming goal only when the body reaches `true`; + * otherwise the incoming goal passes through. */ +and check_subgoal = + ( + ~step, + ~statics, + ~ctx, + ~body_ctx=ctx, + ~id, + ~marks=[], + ~obligations=[], + incoming, + subgoal: option(Exp.t), + body, + ) + : (option(Exp.t), ProofMap.t) => { + let (out_body, m) = check(~step, ~statics, ~ctx=body_ctx, subgoal, body); + let outgoing = is_true(out_body) ? out_body : incoming; + (outgoing, record(~ctx, ~marks, ~obligations, id, incoming, outgoing, m)); +} + +/* `from at do end`: the body is a chain of its + * own whose incoming goal is the selected occurrence, and the focus's + * outgoing is the goal with that occurrence replaced by the body's + * outgoing. Every step of the body relates its goals by `==`, so by + * congruence the replaced goal equals the incoming one. The body's + * outgoing keeps its ids in the result; its ids are the occurrence's own + * or fresh, since every rewrite step freshens what it writes. + * + * The occurrence may sit under binders of the goal (a `fun`, a + * `forall`, a `let` body, a case arm). In the body each variable they + * bind is fresh and arbitrary, as `forall x =>` makes it: it is bound to + * itself in the env and the facts that mention its name are dropped, + * since they are about an outer variable of that name. Rewriting under + * a binder is then sound because the body's steps hold for every value + * of the variable. + * + * A selector with no such occurrence is marked, the goal passes through, + * and the body is checked with no goal. */ +and check_focus = + (~step, ~statics, ~ctx, ~id, incoming, ordinal, selector, body) + : (option(Exp.t), ProofMap.t) => { + let env = SemanticCtx.get_env(ctx); + let target = + Option.bind(incoming, ~f=goal => + Occurrence.nth_env_target(~statics, ~env, selector, ordinal - 1, goal) + |> Option.map(~f=target => (goal, target)) + ); + switch (incoming, target) { + | (None, _) => + check_subgoal( + ~step, + ~statics, + ~ctx, + ~id, + ~marks=[ProofMark.MissingIncoming], + None, + None, + body, + ) + | (Some(_), None) => + let (_, m) = check(~step, ~statics, ~ctx, None, body); + ( + incoming, + record( + ~ctx, + ~marks=[ + ProofMark.PatternNotFound({ + selector, + ordinal, + }), + ], + id, + incoming, + incoming, + m, + ), + ); + | (Some(_), Some((goal, target))) => + let binders = Occurrence.binders(Exp.rep_id(target), goal); + let body_ctx = + List.fold_left( + ~f=(ctx, p) => bind(ctx, p, Typ.fresh(Unknown(Internal))), + ~init=ctx, + binders, + ); + let (out_body, m) = + check(~step, ~statics, ~ctx=body_ctx, Some(target), body); + let outgoing = + switch (out_body) { + | Some(out) => + Some(Occurrence.replace_by_id(Exp.rep_id(target), goal, out)) + | None => incoming + }; + (outgoing, record(~ctx, id, incoming, outgoing, m)); + }; +} + +/* The binder comes from the incoming goal. A different name written in + * the proof renames it, as `funext` names its argument, unless the goal + * already uses that name. */ +and check_forall = (~step, ~statics, ~ctx, ~id, incoming, pat, body) => + switch (Option.map(~f=peel_binder, incoming)) { + | None => + check_subgoal( + ~step, + ~statics, + ~ctx, + ~id, + ~marks=[ProofMark.MissingIncoming], + None, + None, + body, + ) + | Some(Some((p, t, inner))) => + let open_body = (p, inner) => + check_subgoal( + ~step, + ~statics, + ~ctx, + ~body_ctx=bind(ctx, p, t), + ~id, + incoming, + Some(inner), + body, + ); + switch (ProofSyntax.pat_to_name(p), ProofSyntax.pat_to_name(pat)) { + | (Some(from), Some(to_)) when !String.equal(from, to_) => + if (Exp.occurs_free_any([to_], inner)) { + check_subgoal( + ~step, + ~statics, + ~ctx, + ~id, + ~marks=[ProofMark.BinderCaptures({var: to_})], + incoming, + incoming, + body, + ); + } else { + let renamed = + Pat.map_term( + ~f_pat= + (continue, q: Pat.t) => + switch (Pat.term_of(q)) { + | Var(x) when String.equal(x, from) => { + ...q, + term: Var(to_), + } + | _ => continue(q) + }, + p, + ); + /* `to_` maps to itself so that substitution renames an inner + * binder that would capture it. */ + let inner = + Substitution.in_exp( + Environment.of_bindings([ + (to_, Exp.fresh(Var(to_))), + (from, Exp.fresh(Var(to_))), + ]), + inner, + ); + open_body(renamed, inner); + } + | _ => open_body(p, inner) + }; + /* No binder to peel: mark it, but let the body keep working on the goal + * as is. */ + | Some(None) => + check_subgoal( + ~step, + ~statics, + ~ctx, + ~id, + ~marks=[ProofMark.ExpectedForallGoal], + incoming, + incoming, + body, + ) + } + +/* Functional extensionality as an intro rule rather than an axiom: as a + * rewrite equality it would have to quantify over functions at unknown + * or hole types. + * + * Incoming `f == g` at an arrow type; the body's incoming is the + * pointwise `f(x) == g(x)`, with `x` bound at the domain type. One arrow + * per `funext`: for a curried `a -> b -> c`, `f(x) == g(x)` is still at + * an arrow type, and a second `funext y =>` peels again. A binder free + * in `f` or `g` would capture that use, and is marked. On failure, as + * for `forall`: mark, and let the body keep working on the goal as + * written. */ +and check_funext = (~step, ~statics, ~ctx, ~id, incoming, pat, body) => { + let fail = mark => + check_subgoal( + ~step, + ~statics, + ~ctx, + ~id, + ~marks=[mark], + incoming, + incoming, + body, + ); + switch (incoming) { + | None => fail(ProofMark.MissingIncoming) + | Some(goal) => + switch (Funext.goal(~statics, ~env=SemanticCtx.get_env(ctx), goal)) { + | None => fail(ProofMark.ExpectedFunEqGoal) + /* The binder must be something we can actually bind, else the + * pointwise goal would mention a name nothing introduces. */ + | Some((_, _, domain)) + when Option.is_none(SemanticCtx.bind_pattern(pat, domain, Ctx.empty)) => + fail(ProofMark.MalformedFunext) + | Some((l, r, domain)) => + let captured = + List.find( + ~f= + x => + Exp.occurs_free_any([x], l) || Exp.occurs_free_any([x], r), + Pat.bound_vars(pat), + ); + switch (captured) { + | Some(var) => fail(ProofMark.BinderCaptures({var: var})) + | None => + check_subgoal( + ~step, + ~statics, + ~ctx, + ~body_ctx=bind(ctx, pat, domain), + ~id, + incoming, + Some(Funext.pointwise(~binder=pat, l, r)), + body, + ) + }; + } + }; +} + +/* Implication intro: with goal `A ==> B` where `e` is A (modulo the + * definitions in scope), hypothesize `e` and prove B. On any other goal + * the step is refused and the body keeps the goal; `have` introduces a + * fact on any goal. A hole for `e` assumes nothing yet, so the goal + * passes through unmarked, as for `have`. */ +and check_assume = (~step, ~statics, ~ctx, ~id, incoming, e, name, body) => { + let consequent = + switch (Option.bind(incoming, ~f=ProofRule.implication)) { + | Some((a, b)) + when + Exp.fast_equal(a, e) + || MatchExp.equal_modulo(~defs=SemanticCtx.get_env(ctx), a, e) => + Some(b) + | Some(_) + | None => None + }; + switch (consequent) { + | Some(b) => + /* Unnamed, the hypothesis is `assume`, which shadows any enclosing + * one; naming a nested assumption keeps the outer one citable. */ + let (body_ctx, _) = + SemanticCtx.add_hypothesis(ctx, name_or(~default="assume", name), e); + let (_, m) = check(~step, ~statics, ~ctx=body_ctx, Some(b), body); + /* Assuming the goal's antecedent proves the implication once the + * body proves its consequent, so the block steps to `true` as a split + * does, and an unfinished body is caught as an open case is + * (`ProofMap.cases_closed`). Its body's result would not equal the + * implication: in a focus it would replace it. */ + let outgoing = Some(Exp.temp(Atom(Bool(true)))); + (outgoing, record(~ctx, id, incoming, outgoing, m)); + | None => + let marks = + is_hole(e) + ? [] : [ProofMark.ExpectedImplicationGoal({assumption: e})]; + check_subgoal( + ~step, + ~statics, + ~ctx, + ~id, + ~marks, + incoming, + incoming, + body, + ); + }; +} + +/* `have proof => `, the cut rule. With incoming + * goal `G` it incurs two obligations, both recorded on the have's own + * node, as a two-condition axiom would: + * + * 1. prove `` in the enclosing scope (if the subproof could cite + * the have's own hypothesis, `have P proof => ...` would + * prove anything); + * 2. prove `G` in the scope extended with ``, named `have` unless + * the have names it. + * + * Obligation 1 is dropped when the subproof reaches `true` with a clean + * subtree, obligation 2 when the body does. An open premise is a Pending + * obligation, not a broken step, so the form has no marks. + * + * Obligation 1 can also be discharged like any other, so an + * already-known `` needs no subproof. Obligation 2 can't: its scope + * contains the new `have` hypothesis, and lookup would discharge it + * whenever `G` equals ``, trivially. + * + * The hypothesis is installed whether or not the subproof is finished, + * so obligations incurred by steps inside the body can discharge against + * it by lookup. + * + * The outgoing is the body's, so obligation 2 is Pending exactly when + * the have's own outgoing is not a clean `true`, i.e. when + * `full_status_of_proof` already reads Incomplete; a pending second + * premise never reads as ProvenModulo. The one shape this misreports is + * `Seq(Have(...), tail)` with the goal closed in the tail, which is + * outside the have's scope anyway and which the stepper never writes. */ +and check_have = (~step, ~statics, ~ctx, ~id, incoming, e, name, sub, body) => { + let proves = (out, m, p) => + is_true(out) + && ProofMap.proof_is_clean(m, p) + && ProofMap.cases_closed(m, p); + let (out_sub, m_sub) = check(~step, ~statics, ~ctx, Some(e), sub); + let sub_obligations = + proves(out_sub, m_sub, sub) + ? [] + : [Discharge.obligation(~step, ~ctx, ~origin=id, ~kind=Premise, e)]; + let (body_ctx, _) = + SemanticCtx.add_hypothesis(ctx, name_or(~default="have", name), e); + let (out_body, m_body) = + check(~step, ~statics, ~ctx=body_ctx, incoming, body); + /* In the extended scope, so the panel's local context for this row + * shows the `have` hypothesis. */ + let body_obligations = + switch (incoming) { + | Some(goal) when !proves(out_body, m_body, body) => [ + Obligation.{ + origin: id, + kind: Premise, + bindings: SemanticCtx.get_ctx(body_ctx).entries, + goal, + discharge: Pending, + }, + ] + | Some(_) + | None => [] + }; + ( + out_body, + record( + ~ctx, + ~obligations=sub_obligations @ body_obligations, + id, + incoming, + out_body, + ProofMap.union(m_sub, m_body), + ), + ); +} + +/* Re-quantify an already-peeled binder x: with incoming goal G, the + * body's incoming goal is `forall x -> G`. Soundness: `forall x -> G` + * denoting true entails G at the ambient x. + * + * Capture: inside the body, every fact whose statement mentions x + * (assume-hypotheses, case_eq, IHs) is about the + * old x, so those entries are removed from the body's scope. One filter + * over the theorem namespace covers both `Discharge.lookup` and rule + * lookup (`ProofCtx.of_theorem_ctx`); `is_captured` would cover only rule + * lookup, and only once the body re-peels the binder. The test is free + * occurrence (`ProofRule.mentions_any`), so a lemma `forall x -> ...` + * that binds its own x stays available. */ +and check_generalize = (~step, ~statics, ~ctx, ~id, incoming, e, body) => { + /* Every variable in scope, the proof's binders included, is in the env. */ + let in_scope = + ProofSyntax.exp_to_name(e) + |> OptUtil.filter(x => + Option.is_some(Environment.lookup(SemanticCtx.get_env(ctx), x)) + ); + switch (incoming, in_scope) { + | (None, _) => + pass_through( + ~step, + ~statics, + ~ctx, + ~id, + ~marks=[ProofMark.MissingIncoming], + None, + body, + ) + | (Some(_), None) when is_hole(e) => + pass_through(~step, ~statics, ~ctx, ~id, ~marks=[], incoming, body) + /* The argument isn't a bare in-scope variable. */ + | (Some(_), None) => + pass_through( + ~step, + ~statics, + ~ctx, + ~id, + ~marks=[ProofMark.MalformedGeneralize], + incoming, + body, + ) + | (Some(goal), Some(x)) => + /* The binder keeps x's type, so the body's re-peel binds x as it was + * bound, and an `algebra` step can still verify arithmetic on it. */ + let binder = + switch (Ctx.lookup_var(SemanticCtx.get_ctx(ctx), x)) { + | Some({typ: {term: Unknown(_), _}, _}) + | None => Pat.fresh(Var(x)) + | Some({typ, _}) => Pat.fresh(Asc(Pat.fresh(Var(x)), typ)) + }; + let subgoal = Exp.fresh(Forall(binder, goal)); + /* x's own binder entry stays: it is inert once no fact mentions it + * (its env binding is the identity `x ↦ Var(x)`), and the body's + * re-peel of the new binder rebinds it anyway. */ + let body_ctx = forget_facts_mentioning([x], ctx); + check_subgoal( + ~step, + ~statics, + ~ctx, + ~body_ctx, + ~id, + incoming, + Some(subgoal), + body, + ); + }; +} + +/* Move an in-scope fact back into the goal, the inverse of assume's + * implication intro. With incoming goal `G` and an in-scope fact `F` + * matching the cited argument, the body's incoming goal is `F ==> G`. + * + * No obligation: `F` holds in this scope, so under the Kleene reading + * `F ==> G` denotes exactly what `G` denotes. The step only moves a fact + * from the context into the goal, where eval and rewrite steps can + * compute with it. + * + * The fact stays in scope and citable (by lookup and, through the + * boolean reading, as a rewrite rule). That is what makes the ex falso + * idiom work: revert the contradictory fact, rewrite it with other facts + * (e.g. a `case_eq`) until the antecedent evaluates to `false`, and + * `false ==> G` evaluates to `true`. + * + * With `with x = v`, the antecedent is the fact instantiated at `v`. + * Sound for the same reason, once `v` passes the instantiation gate as a + * matched instantiation would at an axiom step: `forall x -> F(x)` holds + * in this scope, so `F(v)` does, so `F(v) ==> G` denotes what `G` + * denotes. + * + * The fact is found by `Discharge.lookup`, so the cited expression must + * name it as it stands. A failure marks the step and passes the goal + * through. */ +and check_revert = + (~step, ~statics, ~ctx, ~id, incoming, e, instantiation, body) => { + open Result.Syntax; + let fact = cited_fact(~ctx, e); + let instantiate = ((var, inst)) => { + let* x = + ProofSyntax.exp_to_name(var) + |> Result.of_option( + ~error=ProofMark.RevertFactNotQuantified({var: "?"}), + ); + let* instantiated = + ProofRule.instantiate_binder(x, inst, fact) + |> Result.of_option(~error=ProofMark.RevertFactNotQuantified({var: x})); + switch (Gate.instantiations(~statics, ~ctx, [(x, inst)])) { + | Error(var) => + Error( + ProofMark.PossiblyDivergentInstantiation({ + equality: x, + var, + }), + ) + | Ok(conditions) => + Ok(( + instantiated, + List.map( + ~f=Discharge.obligation(~step, ~ctx, ~origin=id, ~kind=Definedness), + conditions, + ), + )) + }; + }; + let fail = mark => + pass_through(~step, ~statics, ~ctx, ~id, ~marks=[mark], incoming, body); + switch (incoming, Discharge.lookup(ctx, fact)) { + | (None, _) => fail(ProofMark.MissingIncoming) + | (Some(_), None) when is_hole(e) => + pass_through(~step, ~statics, ~ctx, ~id, ~marks=[], incoming, body) + | (Some(_), None) => fail(ProofMark.UnknownFactReverted) + | (Some(goal), Some(_)) => + let antecedent = + switch (instantiation) { + | None => Ok((fact, [])) + | Some(instantiation) => instantiate(instantiation) + }; + switch (antecedent) { + | Error(mark) => fail(mark) + | Ok((antecedent, obligations)) => + check_subgoal( + ~step, + ~statics, + ~ctx, + ~id, + ~obligations, + incoming, + Some(Exp.fresh(BinOp(Bool(Implies), antecedent, goal))), + body, + ) + }; + }; +} + +/* `alias = => ` names a fact after the fact. + * Auto-installed facts have fixed names and shadow, so a nested split + * hides the enclosing one's `case_eq`; this resolves `` as `revert` + * does and installs the same proposition again under `` for the + * body's scope. + * + * Nothing new is assumed, so there is no obligation, and the outgoing is + * the body's. An unresolvable fact gets `revert`'s mark, + * `ProofMark.UnknownFactReverted`, and the body is checked against the unchanged + * goal. A hole or compound pattern in the name slot names nothing, so + * the step is then a no-op rather than a broken one. */ +and check_alias = (~step, ~statics, ~ctx, ~id, incoming, x, e, body) => { + let fact = cited_fact(~ctx, e); + switch (Discharge.lookup(ctx, fact), Pat.bound_vars(x)) { + | (None, _) => + pass_through( + ~step, + ~statics, + ~ctx, + ~id, + ~marks=[ProofMark.UnknownFactReverted], + incoming, + body, + ) + | (Some(_), names) => + let body_ctx = + switch (names) { + | [h] => SemanticCtx.add_hypothesis(ctx, h, fact) |> fst + | _ => ctx + }; + let (out_body, m) = + check(~step, ~statics, ~ctx=body_ctx, incoming, body); + (out_body, record(~ctx, id, incoming, out_body, m)); + }; +} + +/* A split on `scrut` in the incoming goal: `cases` or `induction`. + * + * Each case's body is checked against the goal with `scrut` replaced by + * the case's pattern, in a scope extended with the pattern's bindings + * and the split's `case_facts`. If the cases are exhaustive, the split's + * outgoing is `true`; an unfinished case keeps the proof incomplete. The + * split node itself is marked for empty cases, non-exhaustive cases and + * an untyped scrutinee; per-case failures are marked on the cases. + * + * `induction` on a computed `scrut` is induction on a fresh variable + * standing for it: replacing `scrut` throughout the goal is the same + * substitution, and with no case equation and no fact about `scrut` in + * scope, nothing ties a case's pattern back to `scrut`'s actual value. + * + * Exhaustiveness here is stricter than the edit-time check in the + * statics: a column whose type is `Unknown` is refused rather than + * treated as vacuously covered (`Coverage.check(~strict_unknown)`), + * because certifying a proof is not the same as marking an error. */ +and check_split = + ( + ~step, + ~statics, + ~ctx, + ~id, + incoming, + scrut: Exp.t, + case_facts: case_facts, + cases: list((Pat.t, Proof.t)), + ) + : (option(Exp.t), ProofMap.t) => { + let tyctx = SemanticCtx.get_ctx(ctx); + let (gate_marks, gate_obligations) = + Gate.scrutinee(~step, ~statics, ~ctx, ~origin=id, scrut); + let scrut_id = Exp.rep_id(scrut); + /* The statics record the scrutinee's type when elaborating the + * theorem. But they analyze a `funext` binder at `Unknown`, while the + * checker binds it at the function equality's domain, so when the + * statics leave the type unknown it is read off the checker's ctx. + * Only a variable or an ascription is read, never the cases, so an + * untyped `forall b -> | true | false` stays refused. Unknown means + * unknown at the head: `[?]` still gives coverage a list shape. */ + let scrut_ty = { + let head_unknown = ty => + switch (Typ.term_of(ty)) { + | Unknown(_) => true + | _ => false + }; + let rec ctx_ty = (e: Exp.t): option(Typ.t) => + switch (Exp.term_of(e)) { + | Parens(inner) => ctx_ty(inner) + | Asc(inner, t) => + switch (Typ.term_of(t)) { + | Unknown(_) => ctx_ty(inner) + | _ => Some(statics.typ(Exp.rep_id(e)) |> Option.value(~default=t)) + } + | Var(x) => + Ctx.lookup_var(tyctx, x) + |> Option.map(~f=(entry: Ctx.var_entry) => entry.typ) + | _ => None + }; + let statics_ty = + statics.typ(scrut_id) + |> Option.value(~default=Typ.fresh(Unknown(Internal))); + switch (ctx_ty(scrut)) { + | Some(ty) when head_unknown(statics_ty) && !head_unknown(ty) => ty + | _ => statics_ty + }; + }; + let scrut_co_ctx = + statics.co_ctx(scrut_id) |> Option.value(~default=CoCtx.empty); + let induction_ctx = + SemanticCtx.map_ctx( + _ => Ctx.forget_facts(Induction.mentions(scrut), tyctx), + ctx, + ); + /* The goal and scope of the case for `pat`. */ + let case = (pat: Pat.t) => { + let added_vars = pat |> Pat.bindings |> Binding.variable_names; + let replace_scrut = (by: Pat.t, goal: Exp.t) => + Induction.replace( + statics, + scrut, + scrut_co_ctx, + Exp.of_pat(by), + by |> Pat.bindings |> CoCtx.of_bindings, + added_vars, + goal, + ); + let case_ctx = + switch (case_facts) { + /* The case equation, absent when the pattern's variables capture + * the scrutinee. */ + | CaseEquation => + let case_ctx = bind(ctx, pat, scrut_ty); + CoCtx.has_any(scrut_co_ctx, added_vars) + ? case_ctx + : SemanticCtx.add_hypothesis( + case_ctx, + "case_eq", + Exp.fresh(BinOp(Poly(Equals), scrut, Exp.of_pat(pat))), + ) + |> fst; + | InductiveHypotheses => + let goal = incoming |> Option.value(~default=Exp.fresh(EmptyHole)); + let ihs = + Induction.hypotheses(statics, scrut_ty, pat) + |> List.filter_map(~f=h => + replace_scrut(h, goal) + |> Option.map(~f=ih => (Induction.hypothesis_name(h), ih)) + ); + List.fold_left( + ~f= + (ctx, (name, ih)) => + SemanticCtx.add_hypothesis(ctx, name, ih) |> fst, + ~init=bind(induction_ctx, pat, scrut_ty), + ihs, + ); + }; + /* `replace_scrut` gives no goal when a pattern variable would capture + * a use in the goal away from the scrutinee. */ + let case_goal = Option.bind(incoming, ~f=replace_scrut(pat)); + let captured = + switch (incoming, case_goal) { + | (Some(goal), None) => + let free_in = (e, x) => Exp.occurs_free_any([x], e); + Some( + List.find( + ~f=x => free_in(goal, x) && !free_in(scrut, x), + added_vars, + ) + |> Option.value(~default="?"), + ); + | (Some(_), Some(_)) + | (None, _) => None + }; + (case_goal, case_ctx, captured); + }; + /* `Exp.of_pat` reads a wildcard as `true`, so a wildcard case's goal + * would substitute `true` for the scrutinee. The whole split is refused + * before any case is checked. */ + let rec has_wild = (p: Pat.t): bool => + switch (Pat.term_of(p)) { + | Wild => true + | Invalid(_) + | EmptyHole + | MultiHole(_) + | ExplicitNonlabel + | Atom(_) + | Constructor(_) + | Var(_) + | Label(_) => false + | ListLit(ps) + | Tuple(ps) => List.exists(~f=has_wild, ps) + | Cons(a, b) + | TupLabel(a, b) + | Ap(a, b) => has_wild(a) || has_wild(b) + | Parens(q) + | Projector(_, q) + | Asc(q, _) => has_wild(q) + }; + let (outgoing, marks, m) = + if (List.exists(~f=((p, _)) => has_wild(p), cases)) { + (incoming, [ProofMark.InductionUnsupportedWildcard], ProofMap.empty); + } else { + let pats = List.map(~f=fst, cases); + let checked = + List.map( + ~f= + ((pat, body)) => { + let (case_goal, case_ctx, captured) = case(pat); + ( + check(~step, ~statics, ~ctx=case_ctx, case_goal, body), + captured, + ); + }, + cases, + ); + /* One mark per name, so each refused arm can say why. */ + let captures = + List.filter_map(~f=snd, checked) + |> ListUtil.dedup + |> List.map(~f=var => ProofMark.BinderCaptures({var: var})); + /* Strict mode also catches nested `Unknown`s, e.g. an ADT whose + * payload type is a hole. */ + let constraints = + List.filter_map( + ~f=pat => statics.pat_constraint(Pat.rep_id(pat)), + pats, + ); + let is_exhaustive = + Poly.equal( + Coverage.check(~strict_unknown=true, constraints, scrut_ty). + exhaustiveness, + Exhaustive, + ); + let marks = + captures + @ ( + switch (is_exhaustive, Typ.term_of(scrut_ty)) { + | (true, _) => [] + /* Covers a missing type too, which falls back to + * `Unknown(Internal)` above. */ + | (false, Unknown(_)) => [ProofMark.InductionScrutineeUntyped] + | (false, _) => [ProofMark.InductionNotExhaustive] + } + ); + /* The step's conclusion is the goal itself, so it steps to `true` + * whether or not its cases are finished; an open case keeps the + * proof incomplete (`ProofMap.status_of_proof`). A split with no + * cases is exhaustive only on a type with no values, where the + * goal holds vacuously. */ + let outgoing = + is_exhaustive ? Some(Exp.temp(Atom(Bool(true)))) : incoming; + let m = + List.fold_left( + ~f=(acc, ((_, m), _)) => ProofMap.union(acc, m), + ~init=ProofMap.empty, + checked, + ); + (outgoing, marks, m); + }; + ( + outgoing, + record( + ~ctx, + ~marks=gate_marks @ marks, + ~obligations=gate_obligations, + id, + incoming, + outgoing, + m, + ), + ); +}; diff --git a/src/language/proof/ProofCtx.re b/src/language/proof/ProofCtx.re index 589590af3a..ff158541ef 100644 --- a/src/language/proof/ProofCtx.re +++ b/src/language/proof/ProofCtx.re @@ -4,9 +4,14 @@ open Util; type entry = { name: string, rule: ProofRule.t, - typ: Typ.t, exp: Exp.t, is_captured: bool, + /* Hidden by a nearer entry of the same name. Hypothesis names are fixed + and shadow, so a scope can hold several `case_eq`s or `ih_t`s and only + the innermost is reachable by that name. A shadowed entry is kept so + the UI can show the fact, which is still in scope and still true, + while saying that its name does not reach it. */ + is_shadowed: bool, }; [@deriving (show({with_path: false}), sexp, yojson)] @@ -14,49 +19,95 @@ type t = list(entry); let add_exp = (name: string, exp: Exp.t, ctx: t) => { let rule = ProofRule.exp_to_rule(exp); - let typ = ProofRule.rule_to_typ(rule); [ { name, rule, - typ, exp, is_captured: false, + is_shadowed: false, }, ...ctx, ]; }; -let of_env = (~builtins, ~ctx: Ctx.t, env: Environment.t(Exp.t)) => { - let (_, rules) = - Environment.to_list(env) - |> List.rev - |> List.fold( - ~f= - ((seen_vars, rules), (name, exp)) => - switch (Exp.term_of(exp)) { - | Grammar.ProofObject(e) => - let rule = ProofRule.exp_to_rule(e); - let typ = ProofRule.rule_to_typ(rule); - let coctx = - ProofRule.get_coctx(ctx, Typ.temp(Atom(Bool)), rule); - let is_captured = CoCtx.has_any(coctx, seen_vars); - let entry = { - name, - rule, - typ, - exp: e, - is_captured, - }; - ([name, ...seen_vars], [entry, ...rules]); - | _ => ([name, ...seen_vars], rules) - }, - ~init=([], builtins), - ); - rules; +/* The rules citable in a scope: every fact in the scope's theorem + * namespace (`Ctx.TheoremEntry`), innermost first, then the built-in + * axioms. + * + * A fact stated in terms of a name that an inner binder has since rebound + * is about the old binding, so it is marked `is_captured` and is not + * citable. The test is a free-occurrence check (`ProofRule.mentions_any`) + * against the variable names bound strictly inside the fact's own entry, + * or the fact is among `captured`. */ +let of_theorem_ctx = (~builtins, ~captured=[], ctx: Ctx.t): t => { + /* Entries are innermost-first, so walking them in that order and + * accumulating the variable names seen so far gives, at each fact, the + * set of variables rebound strictly inside it. + * + * The result has to stay innermost-first, with the built-in axioms last. + * Hypothesis names are fixed and shadow, and `lookup_rule` takes the + * first match by name, so this order decides what a shadowed name means + * to a `rewrite` step. + * It has to agree with `revert`, which resolves through + * `Ctx.lookup_theorem`, also first-match over these entries. */ + let (_, rev_rules) = + List.fold_left( + ~f= + ((seen_vars, rules), entry) => + switch (entry) { + | Ctx.VarEntry({name, _}) => ([name, ...seen_vars], rules) + | Ctx.TheoremEntry({name, id, prop: Some(prop)}) => + let rule = ProofRule.exp_to_rule(prop); + let is_captured = + List.mem(captured, id, ~equal=Id.equal) + || ProofRule.mentions_any(rule, seen_vars); + let entry = { + name, + rule, + exp: prop, + is_captured, + /* Filled in below, once the whole list is known. */ + is_shadowed: false, + }; + (seen_vars, [entry, ...rules]); + | Ctx.TheoremEntry({prop: None, _}) + | Ctx.ConstructorEntry(_) + | Ctx.TVarEntry(_) + | Ctx.LivelitEntry(_) => (seen_vars, rules) + }, + ~init=([], []), + ctx.entries, + ); + let rules = List.rev(rev_rules) @ builtins; + /* Mark every entry a nearer one of the same name hides. The list is + innermost-first, so "nearer" is "earlier". */ + let (_, marked) = + List.fold_left( + ~f= + ((seen, acc), entry) => + ( + [entry.name, ...seen], + [ + { + ...entry, + is_shadowed: List.mem(seen, entry.name, ~equal=String.equal), + }, + ...acc, + ], + ), + ~init=([], []), + rules, + ); + List.rev(marked); }; +/* The nearest entry with this name, unless it is captured. A captured + entry still shadows the outer entries with its name, as it does for + `revert`. */ let lookup_rule = (name: string, ctx: t): option(ProofRule.t) => - ctx - |> List.find(~f=e => String.equal(e.name, name) && !e.is_captured) - |> Option.map(~f=e => e.rule); + switch (List.find(~f=e => String.equal(e.name, name), ctx)) { + | Some({is_captured: false, rule, _}) => Some(rule) + | Some({is_captured: true, _}) + | None => None + }; diff --git a/src/language/proof/ProofHacks.re b/src/language/proof/ProofHacks.re deleted file mode 100644 index a5cfe1abb5..0000000000 --- a/src/language/proof/ProofHacks.re +++ /dev/null @@ -1,590 +0,0 @@ -open Util; -open OptUtil.Syntax; - -exception Found(Exp.t); - -// Find a subexpression by id (delegates to Exp.find_by_id) -let find_exp_id = Exp.find_by_id; - -// Given an expression e1 that appears in e2, count how many -// times e1 appears with a different id before e1 in e2. -let exp_idx = (e1: Exp.t, e2: Exp.t) => { - let n = ref(0); - switch ( - Exp.map_term( - ~f_exp= - (cont, exp) => - if (Id.equal(Exp.rep_id(exp), Exp.rep_id(e1))) { - raise(Found(exp)); - } else if (Equality.ignoring_ascriptions.exp(exp, e1)) { - n := n^ + 1; - exp; - } else { - cont(exp); - }, - e2, - ) - ) { - | exception (Found(_)) => n^ - | _ => - failwith( - "exp_idx: e1 not found in e2 (found " - ++ string_of_int(n^) - ++ " matches)", - ) - }; -}; - -// Find the (n+1)th occurence of e1 in e2 -let nth_exp = (e1: Exp.t, n: int, e2: Exp.t) => { - let count = ref(0); - switch ( - Exp.map_term( - ~f_exp= - (cont, exp) => - if (Equality.ignoring_ascriptions.exp(exp, e1)) { - if (count^ == n) { - raise(Found(exp)); - } else { - count := count^ + 1; - exp; - }; - } else { - cont(exp); - }, - e2, - ) - ) { - | exception (Found(x)) => Some(x) - | _ => None - }; -}; - -let replace_exp_id = (id: Id.t, exp: Exp.t, new_exp: Exp.t) => - Exp.map_term( - ~f_exp= - (cont, exp) => - if (Id.equal(Exp.rep_id(exp), id)) { - new_exp |> Exp.replace_all_ids; - } else { - cont(exp); - }, - exp, - ); - -let rec exp_to_pat = (exp: Exp.t): Pat.t => { - let term = exp |> Exp.term_of; - let rewrap: Pat.term => Pat.t = - term => { - term, - annotation: exp.annotation, - }; - switch (term) { - | Invalid(x) => rewrap(Invalid(x)) - | EmptyHole => rewrap(EmptyHole) - | MultiHole(xs) => rewrap(MultiHole(xs)) - /* `_` in expression position parses as a deferral */ - | Deferral(_) => rewrap(Wild) - | Atom(a) => rewrap(Atom(a)) - | ListLit(xs) => rewrap(ListLit(List.map(~f=exp_to_pat, xs))) - | Constructor(c, t) => rewrap(Constructor(c, t)) - | Cons(e1, e2) => rewrap(Cons(exp_to_pat(e1), exp_to_pat(e2))) - | Var(x) => rewrap(Var(x)) - | Tuple(xs) => rewrap(Tuple(List.map(~f=exp_to_pat, xs))) - | Label(l) => rewrap(Label(l)) - | ExplicitNonlabel => rewrap(ExplicitNonlabel) - | TupLabel(l, e) => rewrap(TupLabel(exp_to_pat(l), exp_to_pat(e))) - | Parens(e) => rewrap(Parens(exp_to_pat(e))) - | Projector(data, e) => rewrap(Projector(data, exp_to_pat(e))) - | Ap(_, e1, e2) => rewrap(Ap(exp_to_pat(e1), exp_to_pat(e2))) - | Asc(e, t1) => rewrap(Asc(exp_to_pat(e), t1)) - | DynamicErrorHole(_) - | Undefined - | DrvQuote(_) - | Fun(_) - | TypFun(_) - | Dot(_) - | LivelitName(_) - | Let(_) - | Theorem(_) - | ProofObject(_) - | Forall(_) - | FixF(_) - | TyAlias(_) - | Use(_) - | TypAp(_) - | DeferredAp(_) - | If(_) - | Seq(_) - | Test(_) - | HintedTest(_) - | Filter(_) - | Closure(_) - | ListConcat(_) - | UnOp(_) - | BinOp(_) - | BuiltinFun(_) - | Match(_) - | TupleExtension(_) - | Module(_) - | ModuleExp(_) => MultiHole([Exp(exp)]) |> Pat.fresh - }; -}; - -let rec pat_to_exp = (pat: Pat.t): Exp.t => { - let term = pat |> Pat.term_of; - let rewrap: Exp.term => Exp.t = - term => { - term, - annotation: pat.annotation, - }; - switch (term) { - | Invalid(x) => rewrap(Invalid(x)) - | EmptyHole => rewrap(EmptyHole) - | MultiHole(xs) => rewrap(MultiHole(xs)) - | Wild => rewrap(Atom(Bool(true))) - | Atom(a) => rewrap(Atom(a)) - | ListLit(xs) => rewrap(ListLit(List.map(~f=pat_to_exp, xs))) - | Constructor(c, t) => rewrap(Constructor(c, t)) - | Cons(e1, e2) => rewrap(Cons(pat_to_exp(e1), pat_to_exp(e2))) - | Var(x) => rewrap(Var(x)) - | Tuple(xs) => rewrap(Tuple(List.map(~f=pat_to_exp, xs))) - | Parens(e) => rewrap(Parens(pat_to_exp(e))) - | Projector(data, e) => rewrap(Projector(data, pat_to_exp(e))) - | Ap(e1, e2) => rewrap(Ap(Forward, pat_to_exp(e1), pat_to_exp(e2))) - | Asc(e, t1) => rewrap(Asc(pat_to_exp(e), t1)) - | Label(l) => rewrap(Label(l)) - | ExplicitNonlabel => rewrap(ExplicitNonlabel) - | TupLabel(l, e) => rewrap(TupLabel(pat_to_exp(l), pat_to_exp(e))) - }; -}; - -let add_wrapping_function = (~typ=?, pat: Pat.t): Exp.t => { - Fun(pat, EmptyHole |> Exp.fresh, typ, None) |> Exp.fresh; -}; - -let rec remove_wrapping_function = (exp: Exp.t): Pat.t => { - switch (exp |> Exp.term_of) { - | Fun(p, _, _, _) => p - | Asc(e, _) => remove_wrapping_function(e) // see https://github.com/hazelgrove/hazel/issues/1586 - | _ => MultiHole([Exp(exp)]) |> Pat.fresh - }; -}; - -let dhpat_extend_ctx = (dhpat: DHPat.t, ty: Typ.t, ctx: Ctx.t): option(Ctx.t) => { - let rec dhpat_var_entry = - (dhpat: DHPat.t, ty: Typ.t): option(list(Ctx.entry)) => { - let ty' = ty; - let ty = - switch (ty.term) { - | TupLabel(_, ty) => ty - | _ => ty - }; - switch (dhpat |> Pat.term_of) { - | Var(name) => - let entry = - Ctx.VarEntry({ - name, - id: Id.invalid, - typ: ty, - custom_statics: None, - }); - Some([entry]); - | Label(name) => - Typ.equal(ty, Label(name) |> Typ.temp) ? Some([]) : None - | ExplicitNonlabel => - raise( - Failure( - "dhpat_extend_ctx ExplicitNonlabel shouldn't show up since they should only show up in in tuplabels below", - ), - ) - | TupLabel({term: ExplicitNonlabel, _}, dhpat) => - dhpat_var_entry(dhpat, ty) - | TupLabel(_, dp1) => - switch (ty'.term) { - | TupLabel(_, ty2) - when - LabeledTuple.has_same_labels( - DHPat.match_tup_label(dhpat), - Typ.match_tup_label(ty'), - ) => - dhpat_var_entry(dp1, ty2) - | TupLabel(_, _) => None - | _ => dhpat_var_entry(dp1, ty) - } - | Tuple(l1) => - let (l1, ts) = - MatchedTyp.prod(ctx, l1, Pat.match_tup_label, ty, (name, b) => - TupLabel(Label(name) |> Pat.fresh, b) |> Pat.fresh - ); - let* l = - List.map2_exn(l1, ts, ~f=(dhp, typ) => {dhpat_var_entry(dhp, typ)}) - |> OptUtil.sequence; - Some(List.concat(l)); - | Cons(dhp1, dhp2) => - let* t = MatchedTyp.list_strict(ctx, ty); - let* l1 = dhpat_var_entry(dhp1, t); - let* l2 = dhpat_var_entry(dhp2, List(t) |> Typ.temp); - Some(l1 @ l2); - | ListLit(l) => - let* t = MatchedTyp.list_strict(ctx, ty); - let* l = - List.map(~f=dhp => {dhpat_var_entry(dhp, t)}, l) |> OptUtil.sequence; - Some(List.concat(l)); - | Ap(f, dhp) => - let* name = Pat.ctr_name(f); - let* ctrs = Typ.get_sum_constructors(ctx, ty); - let* typ = ConstructorMap.get_entry(name, ctrs); - let* typ' = typ; - dhpat_var_entry(dhp, typ'); - | EmptyHole - | Wild - | Invalid(_) - | MultiHole(_) => Some([]) - | Parens(dhp) - | Projector(_, dhp) => dhpat_var_entry(dhp, ty) - | Atom(c) => - Typ.equal(ty, Atom(Atom.cls_of_t(c)) |> Typ.temp) ? Some([]) : None - | Constructor(_) => Some([]) // TODO: make this stricter - | Asc(dhp, ty1) => dhpat_var_entry(dhp, ty1) - }; - }; - let+ l = dhpat_var_entry(dhpat, ty); - List.fold_left(~f=(ctx, entry) => Ctx.extend(ctx, entry), ~init=ctx, l); -}; - -/* Returns all sub-pattern of the original pattern that - 1. Have the same type as the original pattern - 2. Are not the original pattern itself. - */ - -let rec get_inductive_hypotheses = (m, t, pat) => { - switch (pat |> Pat.term_of) { - | _ when Typ.fast_equal(t, Typ.temp(Unknown(Internal))) => [] - | Invalid(_) => [] - | EmptyHole => [] - | MultiHole(_) => [] - | Wild => [] - | Atom(_) => [] - | ListLit(xs) => - List.concat_map(~f=get_inductive_hypotheses_inner(m, t, _), xs) - | Constructor(_) => [] - | Cons(e1, e2) => - get_inductive_hypotheses_inner(m, t, e1) - @ get_inductive_hypotheses_inner(m, t, e2) - | Var(_) => [] - | Tuple(xs) => - List.concat_map(~f=get_inductive_hypotheses_inner(m, t, _), xs) - | Parens(e) - | Projector(_, e) => get_inductive_hypotheses_inner(m, t, e) - | Ap(e1, e2) => - get_inductive_hypotheses_inner(m, t, e1) - @ get_inductive_hypotheses_inner(m, t, e2) - | Asc(e, _) => get_inductive_hypotheses_inner(m, t, e) - | Label(_) => [] - | TupLabel(l, e) => - get_inductive_hypotheses_inner(m, t, l) - @ get_inductive_hypotheses_inner(m, t, e) - | ExplicitNonlabel => [] - }; -} -and get_inductive_hypotheses_inner' = (m, t, pat) => { - let is_correct_type = - Statics.Map.ty_of(Pat.rep_id(pat), m) - |> Option.map(~f=Typ.fast_equal(t)) - |> Option.value(~default=false); - (is_correct_type ? [pat] : []) @ get_inductive_hypotheses(m, t, pat); -} -and get_inductive_hypotheses_inner = (m, t, pat) => - /* Wrappers share their inner pattern's type, so only the innermost one - counts as a hypothesis. */ - switch (pat |> Pat.term_of) { - | Parens(x) - | Projector(_, x) - | Asc(x, _) => get_inductive_hypotheses_inner(m, t, x) - | Invalid(_) - | EmptyHole - | MultiHole(_) - | Wild - | ExplicitNonlabel - | Atom(_) - | ListLit(_) - | Constructor(_) - | Cons(_) - | Var(_) - | Tuple(_) - | Label(_) - | TupLabel(_) - | Ap(_) => get_inductive_hypotheses_inner'(m, t, pat) - }; - -exception BlacklistVarFound; - -/* Replace all occurrences of `replace` in `in_exp` with `with_exp`. - The coctx is used to prevent capture inside binders. */ -let rec replace_exp = - ( - info_map: Statics.Map.t, - replace, - replace_coctx, - with_exp, - with_coctx, - blacklist_vars, - in_exp, - ) => { - let is_bound = (pat: Pat.t): bool => { - let bvn = pat |> Pat.bindings |> Binding.variable_names; - CoCtx.has_any(replace_coctx, bvn) - ? true : CoCtx.has_any(with_coctx, bvn); - }; - let replace_exp = (in_exp, blacklist_vars): Exp.t => - replace_exp( - info_map, - replace, - replace_coctx, - with_exp, - with_coctx, - blacklist_vars, - in_exp, - ); - let uses_blacklist_var = (exp: Exp.t, blacklist_vars) => { - let coctx = - switch (Statics.Map.lookup_exp(Exp.rep_id(exp), info_map)) { - | Some({co_ctx, _}) => co_ctx - | None => CoCtx.empty - }; - CoCtx.has_any(coctx, blacklist_vars); - }; - let restrict_blacklist = (pat: Pat.t, blacklist_vars) => { - let bvn = pat |> Pat.bindings |> Binding.variable_names; - List.filter( - ~f=v => !List.mem(bvn, v, ~equal=String.equal), - blacklist_vars, - ); - }; - - Exp.map_term( - ~f_exp= - (continue, exp) => { - let (term, rewrap) = Exp.unwrap(exp); - switch (term) { - /* Note[Matt]: We are not currently checking alpha-equivalence here because it's unlikely - to come up, but we could. */ - | _ when Equality.ignoring_ascriptions.exp(exp, replace) => - with_exp |> Exp.replace_all_ids - /* Forms with binders: check if any bound variables are in the coctx, - if so, stop. */ - | Fun(p, d1, x, y) => - if (is_bound(p)) { - if (uses_blacklist_var( - exp, - restrict_blacklist(p, blacklist_vars), - )) { - raise(BlacklistVarFound); - }; - exp; - } else { - Fun( - p, - replace_exp(d1, restrict_blacklist(p, blacklist_vars)), - x, - y, - ) - |> rewrap; - } - | Let(p, e1, e2) => - if (is_bound(p)) { - if (uses_blacklist_var( - exp, - restrict_blacklist(p, blacklist_vars), - )) { - raise(BlacklistVarFound); - }; - Let( - p, - replace_exp(e1, restrict_blacklist(p, blacklist_vars)), - e2, - ) - |> rewrap; - } else { - continue(exp); - } - | FixF(p, e, env) => - if (is_bound(p)) { - if (uses_blacklist_var(exp, blacklist_vars)) { - raise(BlacklistVarFound); - }; - exp; - } else { - FixF( - p, - replace_exp(e, restrict_blacklist(p, blacklist_vars)), - env, - ) - |> rewrap; - } - | Match(e, cases) => - Match( - replace_exp(e, blacklist_vars), - List.map( - ~f= - ((p, e)) => - if (is_bound(p)) { - if (uses_blacklist_var( - e, - restrict_blacklist(p, blacklist_vars), - )) { - raise(BlacklistVarFound); - }; - (p, e); - } else { - ( - p, - replace_exp(e, restrict_blacklist(p, blacklist_vars)), - ); - }, - cases, - ), - ) - |> rewrap - | Theorem(p, e1, e2) => - if (is_bound(p)) { - if (uses_blacklist_var( - exp, - restrict_blacklist(p, blacklist_vars), - )) { - raise(BlacklistVarFound); - }; - Theorem(p, replace_exp(e1, blacklist_vars), e2) |> rewrap; - } else { - continue(exp); - } - | Forall(p, e) => - if (is_bound(p)) { - if (uses_blacklist_var( - exp, - restrict_blacklist(p, blacklist_vars), - )) { - raise(BlacklistVarFound); - }; - exp; - } else { - Forall(p, replace_exp(e, restrict_blacklist(p, blacklist_vars))) - |> rewrap; - } - /* Variables: check if in blacklist */ - | Var(x) when List.mem(blacklist_vars, x, ~equal=String.equal) => - raise(BlacklistVarFound) - | Var(_) => continue(exp) - /* Forms without binders: continue */ - | EmptyHole - | Undefined - | Invalid(_) - | MultiHole(_) - | DynamicErrorHole(_, _) - | Deferral(_) - | Atom(_) - | DrvQuote(_, _) - | ListLit(_) - | Constructor(_) - | TypFun(_) - | Tuple(_) - | TupleExtension(_) - | Label(_) - | TupLabel(_, _) - | Dot(_, _) - | LivelitName(_) - | TyAlias(_) - | Use(_, _) - | Ap(_, _, _) - | TypAp(_, _) - | DeferredAp(_, _) - | If(_, _, _) - | Seq(_, _) - | Test(_) - | HintedTest(_, _) - | Filter(_) - | Closure(_) - | Parens(_) - | Projector(_) - | Cons(_, _) - | ListConcat(_, _) - | UnOp(_, _) - | BinOp(_, _, _) - | BuiltinFun(_) - | ProofObject(_) - | Asc(_, _) - | ExplicitNonlabel - | Module(_) - | ModuleExp(_) => continue(exp) - }; - }, - in_exp, - ); -}; - -let replace_exp = - ( - info_map, - replace, - replace_coctx, - with_exp, - with_coctx, - blacklist_vars, - in_exp, - ) => - try( - Some( - replace_exp( - info_map, - replace, - replace_coctx, - with_exp, - with_coctx, - blacklist_vars, - in_exp, - ), - ) - ) { - | BlacklistVarFound => None - }; - -let find_refls = (~info_map, ~env, e) => { - let refls = ref([]); - let _ = - Exp.map_term( - ~f_exp= - (cont, exp) => { - switch (exp |> Exp.term_of) { - | BinOp(Poly(Equals), e1, e2) - when - MatchExp.match_exp( - ~info_map, - ~exp_env=env, - ~exp_r_ctx=[], - e1, - e2, - ) - |> Option.is_some => - refls := [exp, ...refls^]; - cont(exp); - | _ => cont(exp) - } - }, - e, - ); - refls^; -}; - -let strip_theorems = (exp: Exp.t): Exp.t => { - Exp.map_term( - ~f_exp= - (cont, exp) => { - switch (exp |> Exp.term_of) { - | Theorem(_, _, e2) => cont(e2) - | _ => cont(exp) - } - }, - exp, - ); -}; diff --git a/src/language/proof/ProofMark.re b/src/language/proof/ProofMark.re new file mode 100644 index 0000000000..4ddafcdd44 --- /dev/null +++ b/src/language/proof/ProofMark.re @@ -0,0 +1,128 @@ +open Util; + +/* The ways a proof step can go wrong during checking (ProofCheck), as + opposed to the statics' `Mark.t`. Stored in `ProofMap.entry.marks` and + rendered like statics errors. */ + +/* Declaration order is the priority order (for the cursor inspector and + error selection): earlier constructors have higher priority, as in + `Mark.re`. */ +[@deriving (show({with_path: false}), sexp, yojson, variants)] +type t = + /* Propagation break: this step can't act because the incoming goal is + * missing (an earlier step failed, or we're inside an unprovable + * forall). */ + | MissingIncoming + /* The proof term itself is malformed syntax (Invalid/MultiHole) — + * distinct from an EmptyHole, which is an intentionally-incomplete + * proof and carries no mark. */ + | MalformedProofTerm + /* Axiom: equality argument isn't a resolvable name. */ + | MalformedEqualityName + /* Axiom: the named equality rule is not in scope. */ + | UnknownEquality(string) + /* Axiom: the named theorem's proof reaches `false`, so citing it would + * prove anything. */ + | CitesRefuted(string) + /* Axiom: the rule exists but doesn't unify with the target in the + * chosen direction. */ + | RuleDoesNotApply({ + equality: string, + direction: Direction.t, + }) + /* Axiom: a rule matched, but the match and any `with` clause left some + * of its binders unassigned, so the rewrite would bring them into the + * goal free. */ + | UnderdeterminedInstantiation({equality: string}) + /* Axiom / revert: a `with = ` clause named something that + * is not a binder of the cited rule (axiom) or of the reverted fact + * (revert). The goal passes through, as with the other citation marks. + * `var` is the offending name, or "?" for a non-variable slot. */ + | UnknownInstantiationVar({ + equality: string, + var: string, + }) + /* Revert: a `with` clause was supplied but the in-scope fact has no + * `forall` to eliminate. */ + | RevertFactNotQuantified({var: string}) + /* Axiom / revert: a metavariable instantiation could not be shown + * structurally total (Totality.check). Divergence is ⊥, which no + * boolean obligation can rule out. `var` is the rule metavariable whose + * instantiation failed. */ + | PossiblyDivergentInstantiation({ + equality: string, + var: string, + }) + /* Algebrite: Float-typed rewrites are refused, because the CAS's field + * laws are false for IEEE floats. */ + | FloatAlgebrite + /* Algebrite: the CAS finds the goal and the replacement different. */ + | AlgebraDiffers + /* Focus: the goal has fewer than `ordinal` matches of `selector`. */ + | PatternNotFound({ + selector: Exp.t, + ordinal: int, + }) + /* Eval: the root of the goal isn't a redex, even after the steps the + * stepper hides (variable lookups and the like). */ + | NothingToStep + /* Forall: incoming goal isn't a `forall`/`fun`-binder. */ + | ExpectedForallGoal + /* Assume: incoming goal isn't ` ==> ...`. */ + | ExpectedImplicationGoal({assumption: Exp.t}) + /* Funext: incoming goal isn't an equality (`==`) between two things of + arrow type, so there is no pointwise goal to form. `==` on a list of + functions is not extensionality. */ + | ExpectedFunEqGoal + /* Funext: the binder is not a pattern that can be added to the semantic + context (so the pointwise goal would have a free/unbindable name). */ + | MalformedFunext + /* Funext / induction: a variable the binder or case pattern binds is + * also free in the goal it would be put around, so it would capture + * that use. */ + | BinderCaptures({var: string}) + /* Generalize: the argument isn't a bare in-scope variable (a peeled + * binder that can be re-quantified). */ + | MalformedGeneralize + /* Revert: no in-scope fact matches the reverted expression. Less + * urgent than a broken axiom citation, more urgent than the structural + * induction marks. */ + | UnknownFactReverted + /* Induction: cases don't cover the scrutinee's type. */ + | InductionNotExhaustive + /* Induction: the scrutinee's type could not be positively determined + * (no statics info, or `Unknown` after normalization — an unannotated + * quantifier binder, a type hole, an alias resolving to a hole), so + * there is no constructor set for the cases to exhaust. The case + * split's soundness argument needs to know what the scrutinee ranges + * over: `| true | false` only reduces `forall b -> P(b)` to + * `P(true) && P(false)` if `b` really is a boolean, so the checker + * doesn't guess a type from the patterns. Distinct from + * `InductionNotExhaustive` because the remedy is to annotate the + * binder, not to add a case. */ + | InductionScrutineeUntyped + /* Induction/split: a computed scrutinee (bool split) could not be + * shown structurally total, as for `PossiblyDivergentInstantiation`. + * Structural induction on a bare quantified variable never carries + * this mark. */ + | PossiblyDivergentScrutinee + /* Induction: a case pattern contains a wildcard, which has no + * expression to put in the scrutinee's place, so no case of the split + * is checked. */ + | InductionUnsupportedWildcard; + +let compare = (a: t, b: t): int => + Int.compare(Variants.to_rank(a), Variants.to_rank(b)); + +let highest = (marks: list(t)): option(t) => + switch (marks) { + | [] => None + | [h, ...tl] => + Some( + List.fold_left( + ~f=(best, cur) => compare(cur, best) < 0 ? cur : best, + ~init=h, + tl, + ), + ) + }; diff --git a/src/language/proof/ProofRule.re b/src/language/proof/ProofRule.re index b1492d5ba4..4bdc3bbaf1 100644 --- a/src/language/proof/ProofRule.re +++ b/src/language/proof/ProofRule.re @@ -1,135 +1,374 @@ open Util; +/* A theorem statement read as a rewrite rule: `forall x where g -> + * A ==> l == r` is the rule `l |-> r` (and back) over the binder `x`, + * with the assumptions `g` and `A`. */ + [@deriving (show({with_path: false}), sexp, yojson)] type conclusion = | Equality(Exp.t, Exp.t) + /* A boolean conclusion `P`, read as the equation `P == true` (see + * `BoolReading`). Not collapsed into `Equality(P, true)` because + * display states the reading rather than show an equation nobody + * wrote, and because the reverse (`true` |-> `P`) direction is gated + * separately (`Rewrite.matches`'s `~reverse`). `exp_to_rule` never + * produces this; only the reading does. */ + | BoolFact(Exp.t) | Other(Exp.t); [@deriving (show({with_path: false}), sexp, yojson)] type t = { bindings: list(Ctx.entry), - // assumptions: list(Exp.t), + /* Conditions on the rule, in source order: the peeled top-level `==>` + * antecedents (`A ==> B ==> concl` contributes [A, B]). A rule with + * assumptions is a conditional rewrite rule; applying it emits each assumption, + * instantiated by the match, as an obligation. */ + assumptions: list(Exp.t), conclusion, }; -let rec exp_to_rule = (exp: Exp.t): t => - switch (exp |> Exp.strip_wrappers |> Exp.term_of) { +/* Peel only the outer `forall` binders off a theorem statement, + * collecting the binders' ctx entries. Returns the remaining core, which + * may retain `==>` antecedents. */ +let rec peel_binders = (exp: Exp.t): (list(Ctx.entry), Exp.t) => + switch (exp |> Exp.term_of) { + /* A `Parens` from an editor splice must not hide a binder. */ + | Parens(e) => peel_binders(e) | Forall(p, e) => let bindings' = - ProofHacks.dhpat_extend_ctx(p, Typ.temp(Unknown(Internal)), Ctx.empty) + SemanticCtx.bind_pattern(p, Typ.temp(Unknown(Internal)), Ctx.empty) |> Option.map(~f=(x: Ctx.t) => x.entries) |> OptUtil.get(() => []); - let {bindings, conclusion} = exp_to_rule(e); - { - bindings: bindings' @ bindings, - conclusion, - }; - // | BinOp(Bool(Or), {term: UnOp(Bool(Not), e1), _}, e2) => - // // TODO: Negate more generally and implication - // let {bindings, assumptions, conclusion} = exp_to_rule(e2); - // { - // bindings, - // assumptions: [e1] @ assumptions, - // conclusion, - // }; - | BinOp(Poly(Equals), e1, e2) => { - bindings: [], - conclusion: Equality(e1, e2), - } - | _ => { - bindings: [], - conclusion: Other(exp), - } + let (bindings, core) = peel_binders(e); + (bindings' @ bindings, core); + | _ => ([], exp) }; -let rule_to_exp = (rule: t): Exp.t => { - let rec _wrap_assumptions = (assumptions: list(Exp.t), body: Exp.t): Exp.t => - switch (assumptions) { - | [] => body - | [a, ...rs] => - _wrap_assumptions( - rs, - Exp.fresh(BinOp(Bool(Or), Exp.fresh(UnOp(Bool(Not), a)), body)), - ) - }; - let rec wrap_foralls = (bindings: list(Ctx.entry), body: Exp.t): Exp.t => - switch (bindings) { - | [] => body - | [VarEntry({name, typ, _}), ...rs] => - wrap_foralls( - rs, - Exp.fresh( - Forall(Pat.fresh(Asc(Pat.fresh(Var(name)), typ)), body), - ), - ) - | [ConstructorEntry(_) | TVarEntry(_) | LivelitEntry(_), ...rs] => - wrap_foralls(rs, body) - }; - let body = - switch (rule.conclusion) { - | Equality(e1, e2) => Exp.fresh(BinOp(Poly(Equals), e1, e2)) - | Other(e) => e - }; - wrap_foralls( - rule.bindings, - /*wrap_assumptions(rule.assumptions,*/ body /*)*/, - ); -}; +/* `A ==> B` as `(A, B)`, through parentheses. */ +let rec implication = (exp: Exp.t): option((Exp.t, Exp.t)) => + switch (exp |> Exp.term_of) { + | Parens(inner) => implication(inner) + | BinOp(Bool(Implies), a, b) => Some((a, b)) + | _ => None + }; -let rule_to_typ = (rule: t): Typ.t => { - rule |> rule_to_exp |> (x => Typ.fresh(ProofOf(x))); +/* The rule a statement states, read as written: the boolean reading is + * applied only where a rule is used (`BoolReading`). */ +let exp_to_rule = (exp: Exp.t): t => { + /* `A ==> B ==> concl` yields ([A, B], concl). */ + let rec peel_implications = (exp: Exp.t): (list(Exp.t), Exp.t) => + switch (implication(exp)) { + | Some((e1, e2)) => + let (assumptions, core) = peel_implications(e2); + ([e1, ...assumptions], core); + | None => ([], exp) + }; + let (bindings, core) = peel_binders(exp); + let (antecedents, conclusion) = peel_implications(core); + { + bindings, + assumptions: antecedents, + conclusion: + switch (conclusion |> Exp.term_of) { + | BinOp(Poly(Equals), e1, e2) => Equality(e1, e2) + | _ => Other(conclusion) + }, + }; }; +/* The rule's conclusion as written: a `BoolFact` is the bare boolean, + * not the equation it is read as. */ let conclusion_exp = (rule: t): Exp.t => switch (rule.conclusion) { | Equality(e1, e2) => Exp.fresh(BinOp(Poly(Equals), e1, e2)) + | BoolFact(e) | Other(e) => e }; -let rec get_empty_bindings = (ctx: list(Ctx.entry)) => - switch (ctx) { - | [] => [] - | [VarEntry(var_entry), ...rs] => [ - (var_entry.name, (var_entry.typ, None)), - ...get_empty_bindings(rs), - ] - | [_, ...rs] => get_empty_bindings(rs) +// Instantiating a binder + +/* Eliminate the quantifier over `x` in a proposition by substituting + * `e` for it, the semantics of `revert with x = e`: + * + * `forall x -> B` ↦ `B[x := e]` + * + * Binders quantified outside `x` stay in place. `None` when no binder in + * the prefix is named `x`. */ +let rec instantiate_binder = (x: Var.t, e: Exp.t, prop: Exp.t): option(Exp.t) => { + let subst = (body: Exp.t) => + Substitution.in_exp(Environment.of_bindings([(x, e)]), body); + switch (prop |> Exp.term_of) { + | Parens(inner) => instantiate_binder(x, e, inner) + | Forall(pat, body) => + switch (ProofSyntax.pat_to_name(pat)) { + | Some(actual) when String.equal(actual, x) => Some(subst(body)) + | Some(_) + | None => + instantiate_binder(x, e, body) + |> Option.map(~f=b => Exp.fresh(Forall(pat, b))) + } + | _ => None }; +}; -let can_eq = - (~info_map, ~env, rule: t, exp: Exp.t): (option(Exp.t), option(Exp.t)) => { - switch (rule.conclusion) { - | Equality(a, b) => - let bindings = get_empty_bindings(rule.bindings); - ( - MatchExp.match_exp(~info_map, ~exp_env=env, ~exp_r_ctx=bindings, b, exp) - |> Option.map(~f=MatchExp.substitute_exp(_, a)), - MatchExp.match_exp(~info_map, ~exp_env=env, ~exp_r_ctx=bindings, a, exp) - |> Option.map(~f=MatchExp.substitute_exp(_, b)), - ); - | Other(_) => (None, None) +/* The boolean reading. + * + * A rule that holds says its conclusion denotes `true`, so a boolean + * conclusion `P` (a comparison, a connective, a Bool-typed application) + * can be read as the equation `P == true`, which + * makes it usable as a rewrite rule. So `... ==> (a * b != 0)` needs no + * trailing `== true`. + * + * The reading is applied where a rule is used (`ProofCheck`'s axiom + * step, the stepper's rule display and activity filter), never inside + * `exp_to_rule`: goal classification and `conclusion_exp` must see the + * proposition as written. */ +module BoolReading = { + /* A syntactic answer to "is this expression boolean-valued?". `Unclear` + * is the answer for a variable, an application, a `case` or an `if`, + * whose type only the statics knows. */ + type shape = + | Boolean + | NotBoolean + | Unclear; + + let rec shape = (e: Exp.t): shape => { + /* Spelled out rather than read off `Operators.semantics_of_bin_op` so + * that a new operator is a non-exhaustive-match warning here. */ + let bin_op_is_bool = (op: Operators.op_bin): bool => + switch (op) { + | Bool(And | Or | Implies) + | Poly(Equals | NotEquals) => true + | Int(op) + | SInt(op) + | Nat(op) => + switch (op) { + | LessThan + | LessThanOrEqual + | GreaterThan + | GreaterThanOrEqual => true + | Plus + | Minus + | Times + | Power + | Divide => false + } + | Float(op) => + switch (op) { + | LessThan + | LessThanOrEqual + | GreaterThan + | GreaterThanOrEqual + | Equals + | NotEquals => true + | Plus + | Minus + | Times + | Power + | Divide => false + } + | String(Concat) => false + }; + let un_op_is_bool = (op: Operators.op_un): bool => + switch (op) { + | Bool(Not) => true + | Int(Minus) + | Nat(Minus) + | SInt(Minus) + | Float(Minus) => false + }; + switch (e |> Exp.term_of) { + /* Transparent wrappers. `exp_to_rule` does not peel these, so a + * parenthesised equation still classifies `Other`; peeling here means + * `... ==> (P)` reads the same as `... ==> P`. */ + | Parens(e) + | Projector(_, e) + | Asc(e, _) => shape(e) + | Atom(Bool(_)) => Boolean + | Atom(Int(_) | Nat(_) | SInt(_) | Float(_) | String(_)) => NotBoolean + | UnOp(op, _) => un_op_is_bool(op) ? Boolean : NotBoolean + | BinOp(op, _, _) => bin_op_is_bool(op) ? Boolean : NotBoolean + | ListLit(_) + | Tuple(_) + | Cons(_, _) + | ListConcat(_, _) + | Fun(_, _, _, _) + | TypFun(_, _, _) => NotBoolean + | _ => Unclear + }; + }; + + /* `Other(P)` becomes `BoolFact(P)` when `P` is a boolean proposition. + * `~statics` is type evidence for an `Unclear` shape; without it, as + * in the obligations panel, the reading is purely syntactic. Anything + * it can't settle stays `Other`, which can't rewrite. */ + let apply = (~statics: option(ProofStatics.t)=None, rule: t): t => { + let is_bool_prop = (e: Exp.t): bool => + switch (shape(e), statics) { + | (Boolean, _) => true + | (NotBoolean, _) + | (Unclear, None) => false + | (Unclear, Some(statics)) => + switch (Option.map(~f=Typ.term_of, statics.typ(Exp.rep_id(e)))) { + | Some(Atom(Bool)) => true + | Some(_) + | None => false + } + }; + switch (rule.conclusion) { + | Equality(_, _) + | BoolFact(_) => rule + | Other(e) => + is_bool_prop(e) + ? { + ...rule, + conclusion: BoolFact(e), + } + : rule + }; }; + + /* The equation a `BoolFact` is read as, for display. */ + let equation = (rule: t): option(Exp.t) => + switch (rule.conclusion) { + | BoolFact(e) => + Some( + Exp.fresh(BinOp(Poly(Equals), e, Exp.fresh(Atom(Bool(true))))), + ) + | Equality(_, _) + | Other(_) => None + }; }; -let is_active = (~info_map, ~env, rule: t, exp: Exp.t): bool => - switch (can_eq(~info_map, ~env, rule, exp)) { - | (Some(_), _) - | (_, Some(_)) => true - | _ => false +/* Rewriting with a rule: matching one side of its conclusion against an + * expression (MatchExp) and instantiating the other side. */ +module Rewrite = { + /* The match context with every binder of the rule unassigned. */ + let empty_bindings = (bindings: list(Ctx.entry)): MatchExp.match_ctx => + List.filter_map( + ~f= + (entry: Ctx.entry) => + switch (entry) { + | VarEntry({name, typ, _}) => Some((name, (typ, None))) + | ConstructorEntry(_) + | TVarEntry(_) + | LivelitEntry(_) + | TheoremEntry(_) => None + }, + bindings, + ); + + /* Pre-assign one of the rule's binders in a match context, for a + * `with = ` clause. `None` when `name` is not a binder of the + * rule, which the caller reports as `UnknownInstantiationVar`. */ + let seed = + (name: Var.t, exp: Exp.t, bindings: MatchExp.match_ctx) + : option(MatchExp.match_ctx) => + MatchExp.match_ctx_has(bindings, name) + ? Some( + List.map( + ~f= + ((n, (t, e))) => + String.equal(n, name) + ? (n, (t, Some(exp))) : (n, (t, e)), + bindings, + ), + ) + : None; + + /* A rewrite from a match that left a binder unassigned would bring the + * rule's own variable into the goal free. */ + let has_unassigned = (mctx: MatchExp.match_ctx): bool => + List.exists( + ~f=((_, (_, assigned))) => Option.is_none(assigned), + mctx, + ); + + /* The rule's rewrites of `exp` in each direction, (Left, Right), i.e. + * (`rewrite <-`, `rewrite`), each with the match context that produced it, + * so callers can instantiate the rule's assumptions and detect + * unassigned binders. `~bindings` overrides the initial (all + * unassigned) match context, which is how a `with` clause is seeded. */ + let matches = + (~statics, ~env, ~bindings=?, ~reverse=false, rule: t, exp: Exp.t) + : ( + option((Exp.t, MatchExp.match_ctx)), + option((Exp.t, MatchExp.match_ctx)), + ) => { + let bindings = + switch (bindings) { + | Some(b) => b + | None => empty_bindings(rule.bindings) + }; + let via = (from, to_) => + MatchExp.match_exp(~statics, ~defs=env, ~exp_r_ctx=bindings, from, exp) + |> Option.map(~f=mctx => (MatchExp.substitute_exp(mctx, to_), mctx)); + switch (rule.conclusion) { + /* Right matches the LHS and rewrites to the RHS. */ + | Equality(a, b) => (via(b, a), via(a, b)) + /* Read as `P == true`. Forward (`rewrite`) rewrites `P` to `true`. + * + * Reverse (`rewrite <-`) rewrites a `true` in the goal to `P`. That is + * sound, but `true` occurs everywhere, so offering it during rule + * discovery would make every boolean rule "active" at every `true`. + * Only an explicit citation, which names the rule, the direction and + * the occurrence, turns it on (`~reverse`). */ + | BoolFact(p) => ( + reverse ? via(Exp.fresh(Atom(Bool(true))), p) : None, + via(p, Exp.fresh(Atom(Bool(true)))), + ) + | Other(_) => (None, None) + }; + }; + + /* The rewrites the checker accepts: those whose match assigned every + * binder. */ + let apply = + (~statics, ~env, ~reverse=false, rule: t, exp: Exp.t) + : (option(Exp.t), option(Exp.t)) => { + let (l, r) = matches(~statics, ~env, ~reverse, rule, exp); + let determined = side => + switch (side) { + | Some((w, mctx)) when !has_unassigned(mctx) => Some(w) + | Some(_) + | None => None + }; + (determined(l), determined(r)); }; -let get_coctx = (ctx: Ctx.t, ana: Typ.t, rule: t): CoCtx.t => { - let full_ctx = List.fold_left(~f=Ctx.extend, ~init=ctx, rule.bindings); - let c_exp = conclusion_exp(rule); - /* TODO[Matt]: using full statics here feels a little overblown - especially given we need to fake some settings to it, perhaps - discuss with Andrew */ - let (statics, _) = Statics.mk(~ana, CoreSettings.on, full_ctx, c_exp); - let root_id = Exp.rep_id(c_exp); - let inner_coctx = - switch (Statics.Map.lookup_exp(root_id, statics)) { - | Some(exp) => Info.exp_co_ctx(exp) - | None => [] + let is_active = (~statics, ~env, rule: t, exp: Exp.t): bool => + switch (apply(~statics, ~env, rule, exp)) { + | (Some(_), _) + | (_, Some(_)) => true + | (None, None) => false }; - CoCtx.mk(ctx, full_ctx, inner_coctx); +}; + +// Free variables + +/* Does the rule's core proposition (its assumptions as a `==>` chain + * onto its conclusion) mention any of `vs` free, modulo the rule's own + * binders? A free-variable walk, since it runs on every fact in scope at + * every binder. */ +let mentions_any = (rule: t, vs: list(Var.t)): bool => { + let core = + List.fold_right( + ~f=(a, acc) => Exp.fresh(BinOp(Bool(Implies), a, acc)), + rule.assumptions, + ~init=conclusion_exp(rule), + ); + let binders = + List.filter_map( + ~f= + (entry: Ctx.entry) => + switch (entry) { + | VarEntry({name, _}) => Some(name) + | ConstructorEntry(_) + | TVarEntry(_) + | LivelitEntry(_) + | TheoremEntry(_) => None + }, + rule.bindings, + ); + Exp.occurs_free_any(~bound=binders, vs, core); }; diff --git a/src/language/proof/ProofStatics.re b/src/language/proof/ProofStatics.re new file mode 100644 index 0000000000..87a057e91b --- /dev/null +++ b/src/language/proof/ProofStatics.re @@ -0,0 +1,89 @@ +open Util; + +/* The theorems a theorem's proof can cite: those in scope at it, innermost + * first, and which of them are captured, being about a variable the program + * has rebound since (as `ProofCtx.of_theorem_ctx` reads a scope). The + * builtin axioms are left out. */ +[@deriving (show({with_path: false}), sexp, yojson)] +type namespace = { + theorems: list(Ctx.theorem_entry), + captured: list(Id.t), +}; + +let empty_namespace = { + theorems: [], + captured: [], +}; + +/* The namespace in the typing context `ctx` of a theorem. */ +let namespace_of_ctx = (ctx: Ctx.t): namespace => { + let (_, theorems, captured) = + List.fold_left( + ~f= + ((rebound, theorems, captured), entry: Ctx.entry) => + switch (entry) { + | VarEntry({name, _}) => ([name, ...rebound], theorems, captured) + | TheoremEntry({prop: Some(prop), id, _} as theorem) => ( + rebound, + [theorem, ...theorems], + Exp.occurs_free_any(rebound, prop) + ? [id, ...captured] : captured, + ) + | TheoremEntry({prop: None, _}) + | ConstructorEntry(_) + | TVarEntry(_) + | LivelitEntry(_) => (rebound, theorems, captured) + }, + ~init=([], [], []), + ctx.entries, + ); + { + theorems: List.rev(theorems), + captured, + }; +}; + +/* What the proof checker reads from the statics of the program it checks, + * by id. The full statics map implements it, and so does the smaller map + * the evaluator gets, so the checker runs wherever the evaluator does. */ +type t = { + /* The type of an expression or pattern, normalized: the checker has no + * typing context to resolve an alias against. */ + typ: Id.t => option(Typ.t), + /* The free variables of an expression. */ + co_ctx: Id.t => option(CoCtx.t), + /* What a case pattern covers. */ + pat_constraint: Id.t => option(Coverage.Constraint.t), + /* The namespace at a theorem's node. */ + namespace: Id.t => option(namespace), +}; + +let empty: t = { + typ: _ => None, + co_ctx: _ => None, + pat_constraint: _ => None, + namespace: _ => None, +}; + +let of_info_map = (m: StaticsBase.Map.t): t => { + typ: id => + switch (StaticsBase.Map.lookup(id, m)) { + | Some(InfoExp({ty, ctx, _})) + | Some(InfoPat({ty, ctx, _})) => Some(Typ.normalize(ctx, ty)) + | Some( + InfoDrv(_) | InfoTyp(_) | InfoTPat(_) | InfoMod(_) | InfoSig(_) | + InfoMPat(_) | + InfoProof(_) | + Secondary(_), + ) + | None => None + }, + co_ctx: id => + StaticsBase.Map.lookup_exp(id, m) + |> Option.map(~f=(info: Info.exp) => info.co_ctx), + pat_constraint: id => + StaticsBase.Map.lookup_pat(id, m) |> Option.map(~f=Info.pat_constraint), + namespace: id => + StaticsBase.Map.lookup_exp(id, m) + |> Option.map(~f=(info: Info.exp) => namespace_of_ctx(info.ctx)), +}; diff --git a/src/language/proof/ProofSyntax.re b/src/language/proof/ProofSyntax.re new file mode 100644 index 0000000000..465423cf68 --- /dev/null +++ b/src/language/proof/ProofSyntax.re @@ -0,0 +1,61 @@ +/* Small readers and conversions of the syntax proofs are written in, + * shared by the checker, its definedness analyses and the UI stepper. */ + +// Reading through wrappers + +/* Looks through the wrappers that change neither what an expression + * denotes nor what it names: the editor's parens and projectors, + * ascriptions and closures. */ +let rec unwrap = (e: Exp.t): Exp.t => + switch (e |> Exp.term_of) { + | Parens(inner) + | Projector(_, inner) + | Asc(inner, _) + | Closure(_, inner) => unwrap(inner) + | _ => e + }; + +/* The name a bare variable spells: a cited rule or fact, a `with ` + * binder, a variable to generalize. */ +let exp_to_name = (e: Exp.t): option(Var.t) => + switch (unwrap(e) |> Exp.term_of) { + | Var(name) => Some(name) + | _ => None + }; + +/* The variable a simple binder pattern binds. A destructuring pattern + * binds no single name. */ +let rec pat_to_name = (p: Pat.t): option(Var.t) => + switch (p |> Pat.term_of) { + | Var(x) => Some(x) + | Parens(p1) + | Asc(p1, _) => pat_to_name(p1) + | _ => None + }; + +let add_wrapping_function = (~typ=?, pat: Pat.t): Exp.t => { + Fun(pat, EmptyHole |> Exp.fresh, typ, None) |> Exp.fresh; +}; + +let rec remove_wrapping_function = (exp: Exp.t): Pat.t => { + switch (exp |> Exp.term_of) { + | Fun(p, _, _, _) => p + | Asc(e, _) => remove_wrapping_function(e) // see https://github.com/hazelgrove/hazel/issues/1586 + | _ => MultiHole([Exp(exp)]) |> Pat.fresh + }; +}; + +// Erasing theorems + +let strip_theorems = (exp: Exp.t): Exp.t => { + Exp.map_term( + ~f_exp= + (cont, exp) => { + switch (exp |> Exp.term_of) { + | Theorem(_, _, _, e2) => cont(e2) + | _ => cont(exp) + } + }, + exp, + ); +}; diff --git a/src/language/proof/SemanticCtx.re b/src/language/proof/SemanticCtx.re index 3eca2804a2..34dcd4ac71 100644 --- a/src/language/proof/SemanticCtx.re +++ b/src/language/proof/SemanticCtx.re @@ -4,64 +4,172 @@ open Util; This module is a combination of a Ctx.t and a ClosureEnvironment.t It is used in places where we need to associate both types and values with variables, such as in the stepper. + + Hypotheses live only in the theorem namespace of `ctx` + (`Ctx.TheoremEntry`), never in `env`. Goals and facts name the + program's definitions, and `env` is what those names mean + (`Definitions`). */ +/* What checking a theorem's proof found, for the proofs that cite it. */ +[@deriving (show({with_path: false}), sexp, yojson)] +type verdict = + | Proven + /* Neither proven nor refuted, or proven only modulo open obligations: + * a proof citing it rests on its statement. */ + | Unfinished + | Refuted; + [@deriving (show({with_path: false}), sexp, yojson)] type t = { ctx: Ctx.t, env: Environment.t(Exp.t), + /* The verdicts of the theorems checked before this proof, by the id of + the name each binds. A hypothesis has none. */ + verdicts: list((Id.t, verdict)), + /* Theorems in `ctx` that are about a variable since rebound by the + * program, which `ctx` has no binder for. */ + captured: list(Id.t), }; -let free_name = (t: t, base: Var.t): Var.t => - Var.free_name( - base, - List.map(~f=(e: Ctx.var_entry) => e.name, Ctx.get_var_entries(t.ctx)), - ); +let of_ctx_and_env = (~captured=[], ctx: Ctx.t, env: Environment.t(Exp.t)): t => { + ctx, + env, + verdicts: [], + captured, +}; -let of_ctx_and_env: (Ctx.t, Environment.t(Exp.t)) => t = - (ctx, env) => { - ctx, - env, - }; +/* `t` with the types, constructors and variables of `typing` under its + * own entries, for typing an expression in its scope. The facts stay + * `t`'s. */ +let with_typing = (typing: Ctx.t, t: t): t => { + ...t, + ctx: { + ...t.ctx, + entries: + t.ctx.entries + @ List.filter( + ~f= + fun + | Ctx.TheoremEntry(_) => false + | VarEntry(_) + | ConstructorEntry(_) + | TVarEntry(_) + | LivelitEntry(_) => true, + typing.entries, + ), + }, +}; -let add_entry: (t, Id.t, Var.t, Typ.t, option(Exp.t)) => t = - ({ctx, env}, id, name, typ, value) => { - let ctx = - Ctx.extend( - ctx, +let with_verdicts = (verdicts: list((Id.t, verdict)), t: t): t => { + ...t, + verdicts, +}; + +let map_ctx = (f: Ctx.t => Ctx.t, t: t): t => { + ...t, + ctx: f(t.ctx), +}; + +/* The verdict of the theorem with this id, None for a hypothesis. */ +let verdict = (t: t, id: Id.t): option(verdict) => + List.Assoc.find(t.verdicts, id, ~equal=Id.equal); + +/* The verdict of the theorem `name` cites, None for a hypothesis or an + axiom. */ +let cited_verdict = (t: t, name: Var.t): option(verdict) => + Ctx.lookup_theorem(t.ctx, name) + |> Option.bind(_, ~f=(e: Ctx.theorem_entry) => verdict(t, e.id)); + +/* `ctx` with the variables `dhpat` binds, at their types when `dhpat` + has type `ty`. `None` when `dhpat` can't have that type. */ +let bind_pattern = (dhpat: DHPat.t, ty: Typ.t, ctx: Ctx.t): option(Ctx.t) => { + open OptUtil.Syntax; + let rec dhpat_var_entry = + (dhpat: DHPat.t, ty: Typ.t): option(list(Ctx.entry)) => { + let ty' = ty; + let ty = + switch (ty.term) { + | TupLabel(_, ty) => ty + | _ => ty + }; + switch (dhpat |> Pat.term_of) { + | Var(name) => + let entry = Ctx.VarEntry({ name, - id, - typ, + id: Id.invalid, + typ: ty, custom_statics: None, - }), - ); - let value = OptUtil.get(() => Exp.fresh(Var(name)), value); - let env = env |> Environment.extend(_, (name, value)); - { - ctx, - env, + }); + Some([entry]); + | Label(name) => + Typ.equal(ty, Label(name) |> Typ.temp) ? Some([]) : None + | ExplicitNonlabel => + raise( + Failure( + "bind_pattern ExplicitNonlabel shouldn't show up since they should only show up in in tuplabels below", + ), + ) + | TupLabel({term: ExplicitNonlabel, _}, dhpat) => + dhpat_var_entry(dhpat, ty) + | TupLabel(_, dp1) => + switch (ty'.term) { + | TupLabel(_, ty2) + when + LabeledTuple.has_same_labels( + DHPat.match_tup_label(dhpat), + Typ.match_tup_label(ty'), + ) => + dhpat_var_entry(dp1, ty2) + | TupLabel(_, _) => None + | _ => dhpat_var_entry(dp1, ty) + } + | Tuple(l1) => + let (l1, ts) = + MatchedTyp.prod(ctx, l1, Pat.match_tup_label, ty, (name, b) => + TupLabel(Label(name) |> Pat.fresh, b) |> Pat.fresh + ); + let* l = + List.map2_exn(l1, ts, ~f=(dhp, typ) => {dhpat_var_entry(dhp, typ)}) + |> OptUtil.sequence; + Some(List.concat(l)); + | Cons(dhp1, dhp2) => + let* t = MatchedTyp.list_strict(ctx, ty); + let* l1 = dhpat_var_entry(dhp1, t); + let* l2 = dhpat_var_entry(dhp2, List(t) |> Typ.temp); + Some(l1 @ l2); + | ListLit(l) => + let* t = MatchedTyp.list_strict(ctx, ty); + let* l = + List.map(~f=dhp => {dhpat_var_entry(dhp, t)}, l) |> OptUtil.sequence; + Some(List.concat(l)); + | Ap(f, dhp) => + let* name = Pat.ctr_name(f); + let* ctrs = Typ.get_sum_constructors(ctx, ty); + let* typ = ConstructorMap.get_entry(name, ctrs); + let* typ' = typ; + dhpat_var_entry(dhp, typ'); + | EmptyHole + | Wild + | Invalid(_) + | MultiHole(_) => Some([]) + | Parens(dhp) + | Projector(_, dhp) => dhpat_var_entry(dhp, ty) + | Atom(c) => + Typ.equal(ty, Atom(Atom.cls_of_t(c)) |> Typ.temp) ? Some([]) : None + | Constructor(_) => Some([]) // TODO: make this stricter + | Asc(dhp, ty1) => dhpat_var_entry(dhp, ty1) }; }; - -let add_entry_free_name = - (t: t, name: Var.t, typ: Typ.t, value: option(Exp.t)): (t, Binding.t) => { - let name = free_name(t, name); - let id = Id.mk(); - let t = add_entry(t, id, name, typ, value); - ( - t, - { - id, - name, - }, - ); + let+ l = dhpat_var_entry(dhpat, ty); + List.fold_left(~f=(ctx, entry) => Ctx.extend(ctx, entry), ~init=ctx, l); }; -let add_from_pattern = ({ctx, env}: t, pattern: Pat.t, pat_typ: Typ.t) => { +let add_from_pattern = + ({ctx, env, _} as t: t, pattern: Pat.t, pat_typ: Typ.t) => { let ctx = - ProofHacks.dhpat_extend_ctx(pattern, pat_typ, ctx) - |> Option.value(~default=ctx); + bind_pattern(pattern, pat_typ, ctx) |> Option.value(~default=ctx); let env = List.fold_left( ~f=Environment.extend, @@ -72,19 +180,56 @@ let add_from_pattern = ({ctx, env}: t, pattern: Pat.t, pat_typ: Typ.t) => { ), ); { + ...t, ctx, env, }; }; +/* A hypothesis goes only in the theorem namespace: not in the variable + namespace (no `Ctx.VarEntry`, so its name is free as far as the + statics are concerned) and not in `env` (it is not a value, so + substitution and evaluation never see it). + + The name is used as given, never freshened: an inner `case_eq` + shadows the outer one rather than becoming `case_eq'`. Citation + resolves innermost-first because `Ctx.extend` prepends and + `Ctx.lookup_theorem` takes the first match. To keep a shadowed fact + citable, name it at introduction (`assume h = e`, `have h = e`) + or re-bind it with `alias h = => ...`. */ let add_hypothesis = (t: t, name: Var.t, hyp: Exp.t): (t, Binding.t) => { - add_entry_free_name( - t, - name, - Typ.fresh(ProofOf(hyp)), - Some(Exp.fresh(ProofObject(hyp))), + let id = Id.mk(); + ( + { + ...t, + ctx: + Ctx.extend_theorem( + t.ctx, + { + name, + id, + prop: Some(hyp), + }, + ), + }, + { + id, + name, + }, ); }; +/* The facts visible in this scope, innermost first: the theorem-namespace + entries whose statement is known. Built-in axioms (`prop: None`) are + supplied separately as `Axioms.v` rule builtins. */ +let facts = (t: t): list((Var.t, Id.t, Exp.t)) => + Ctx.get_theorem_entries(t.ctx) + |> List.filter_map(~f=(e: Ctx.theorem_entry) => + switch (e.prop) { + | Some(prop) => Some((e.name, e.id, prop)) + | None => None + } + ); + let get_ctx = (t: t): Ctx.t => t.ctx; let get_env = (t: t): Environment.t(Exp.t) => t.env; diff --git a/src/language/proof/StructuralRecursion.re b/src/language/proof/StructuralRecursion.re new file mode 100644 index 0000000000..a50ee84752 --- /dev/null +++ b/src/language/proof/StructuralRecursion.re @@ -0,0 +1,407 @@ +/* Structural-recursion detection, the part of the divergence gate + * (Totality) that accepts recursive definitions. + * + * `check` conservatively decides whether a `FixF(self_pat, body, _)` is + * structurally recursive: every recursive call to the self-name inside + * the body passes, in some fixed argument position i (the same i for all + * call sites), a strict subterm of that position's parameter. "Strict + * subterm" is the classic syntactic notion: a variable bound by + * destructuring the parameter through at least one constructor layer + * (case patterns, destructuring lets, cons patterns `h :: t`, list + * literal patterns, or constructor patterns directly in a `fun` binder). + * When this holds, every recursive-call chain descends strictly in the + * well-founded subterm order on position i, so — provided everything + * else in the body terminates, which Totality.re verifies separately — + * evaluation terminates. + * + * What is tracked (per lexical scope): + * - a status map: variable -> (param index, optional tuple component, + * strict?). Parameters are seeded non-strict ("aliases"); casing on + * an alias marks the pattern's bindings strict once the walk passes + * under a constructor (`Ap`/`Cons`/`ListLit` pattern layers — depth + * is transitive: `Ap(Lam(b), a)` marks both `b` and `a` strict); + * casing on an already-strict variable marks even a bare-var + * pattern strict (subterm-of-subterm). + * - tuple parameters: `fun (a, b) -> ...` (or `case p | (a, b) => ...` + * directly on parameter p) tracks components as (i, Some j); a call + * `f((x, y))` is decreasing at (i, Some j) when component j is a + * variable strict in (i, Some j). Components of a non-strict tuple + * alias are themselves aliases, never strict (reconstructing the + * same tuple must not pass). + * - shadowing kills tracking: any rebinding of a tracked variable or + * of the self-name (fun/let/case/fix patterns) removes it from the + * maps in that scope. + * + * Refused: + * - the self-name used anywhere other than as the head of a direct + * application (passed along, rebound, returned bare); + * - a call site with no decreasing position, or call sites whose + * decreasing-position sets have empty intersection; + * - mutual recursion (`fix (f, g) -> ...`, a tuple-bound fix): the + * self pattern binds more than one name, and lexicographic or mutual + * descent is not detected; + * - a nested FixF inside the body that doesn't itself pass this check + * (it is checked standalone, then its body is still walked for calls + * to the outer self with the inner binders shadowed); + * - any expression form the walk does not positively understand. + * + * Like Totality.check, the input is expected to be environment- + * substituted (Substitution.in_exp): other definitions are inlined + * (recursive ones surfacing their own FixF spine, handled as nested + * fixes), and only the self-name refers back to this fixpoint. */ + +open Util; +open Result.Syntax; + +[@deriving (show({with_path: false}), sexp, yojson)] +type reason = string; + +/* Which parameter (and, for tuple parameters, which component) a + * tracked variable descends from. */ +type origin = { + param: int, + comp: option(int), +}; + +type status = { + origin, + strict: bool, +}; + +/* A candidate decreasing position at a call site. */ +type pos = (int, option(int)); + +type env = list((Var.t, status)); + +let shadow = (env: env, names: list(Var.t)): env => + List.filter( + ~f=((n, _)) => !List.mem(names, n, ~equal=String.equal), + env, + ); + +let var_status = (env: env, e: Exp.t): option(status) => + switch (ProofSyntax.unwrap(e) |> Exp.term_of) { + | Var(x) => List.Assoc.find(env, x, ~equal=String.equal) + | _ => None + }; + +/* Bindings introduced by matching a term of status `st` against pattern + * `p`. Constructor layers (Ap/Cons/ListLit) switch on strictness — + * transitively, so nested patterns like `Ap(Lam(b), a)` mark `b` strict + * through both layers. Tuple layers: strict components of a strict + * tuple stay strict (a component is a subterm); components of a + * non-strict parameter alias become component aliases (i, Some j) so + * tuple-passing recursion `f((b, n))` can be tracked; anything deeper + * is dropped (conservative — untracked, but still shadowed by the + * caller via Pat.bound_vars). */ +let rec pat_bind = (~origin: origin, ~strict: bool, p: Pat.t): env => + switch (p |> Pat.term_of) { + | Parens(q) + | Projector(_, q) + | Asc(q, _) + | TupLabel(_, q) => pat_bind(~origin, ~strict, q) + | Var(x) => [ + ( + x, + { + origin, + strict, + }, + ), + ] + | Ap(_, q) => pat_bind(~origin, ~strict=true, q) + | Cons(q1, q2) => + pat_bind(~origin, ~strict=true, q1) @ pat_bind(~origin, ~strict=true, q2) + | ListLit(qs) => + List.concat_map(~f=q => pat_bind(~origin, ~strict=true, q), qs) + | Tuple(qs) => + if (strict) { + List.concat_map(~f=q => pat_bind(~origin, ~strict=true, q), qs); + } else if (Option.is_none(origin.comp)) { + List.concat( + List.mapi( + ~f= + (j, q) => + pat_bind( + ~origin={ + param: origin.param, + comp: Some(j), + }, + ~strict=false, + q, + ), + qs, + ), + ); + } else { + []; + } + /* Wild, atoms, nullary constructors, labels, holes: nothing tracked. */ + | _ => [] + }; + +/* Uncurry an application spine: `f(a)(b)` -> (head f, [a, b]). */ +let uncurry = (e: Exp.t): (Exp.t, list(Exp.t)) => { + let rec go = (e: Exp.t, acc: list(Exp.t)) => { + let e = ProofSyntax.unwrap(e); + switch (e |> Exp.term_of) { + | Ap(_, fn, arg) => go(fn, [arg, ...acc]) + | _ => (e, acc) + }; + }; + go(e, []); +}; + +/* The decreasing positions witnessed by one call's argument list: + * position k is valid when its actual argument is a variable strict in + * parameter k (or, for tuple arguments, has a component j that is a + * variable strict in (k, Some j)). */ +let valid_positions = (env: env, args: list(Exp.t)): list(pos) => + List.concat( + List.mapi( + ~f= + (k, arg) => + switch (ProofSyntax.unwrap(arg) |> Exp.term_of) { + | Var(x) => + switch (List.Assoc.find(env, x, ~equal=String.equal)) { + | Some({origin: {param, comp: None}, strict: true}) + when param == k => [ + (k, None), + ] + | _ => [] + } + | Tuple(comps) => + List.concat( + List.mapi( + ~f= + (j, c) => + switch (ProofSyntax.unwrap(c) |> Exp.term_of) { + | Var(x) => + switch (List.Assoc.find(env, x, ~equal=String.equal)) { + | Some({origin: {param, comp: Some(j')}, strict: true}) + when param == k && j' == j => [ + (k, Some(j)), + ] + | _ => [] + } + | _ => [] + }, + comps, + ), + ) + | _ => [] + }, + args, + ), + ); + +/* Walk the body accumulating, per recursive call, its set of valid + * decreasing positions. Errors are conservative refusals. */ +let rec check = (fix: Exp.t): result(unit, reason) => + switch (ProofSyntax.unwrap(fix) |> Exp.term_of) { + | FixF(self_pat, body, _) => + switch (self_pat |> Pat.bound_vars) { + /* `fix () -> ...`, `fix _ -> ...`: no self-name, so nothing can + * recur. Totality walks the body itself. */ + | [] => Ok() + | [self] => + let* possets = chain(~self, ~index=0, ~env=[], body); + switch (possets) { + | [] => Ok() /* no recursive calls at all */ + | [first, ...rest] => + let fixed = + List.fold_left( + ~f= + (acc, s) => + List.filter(~f=p => List.mem(s, p, ~equal=Poly.equal), acc), + ~init=first, + rest, + ); + if (List.is_empty(fixed)) { + Error( + "recursive calls to `" + ++ self + ++ "` do not all decrease on one fixed argument position", + ); + } else { + Ok(); + }; + }; + | _ => + Error( + "the fixpoint binds several names at once (mutual recursion is not supported by structural-recursion detection)", + ) + } + | _ => Error("not a fixpoint") + } + +/* Collect the curried parameter chain `fun p0 -> fun p1 -> ...`, + * seeding each parameter's bindings as (non-strict) aliases of + * position i — through constructor layers directly in the binder they + * are already strict subterms of the actual argument. */ +and chain = + (~self: Var.t, ~index: int, ~env: env, e: Exp.t) + : result(list(list(pos)), reason) => + switch (ProofSyntax.unwrap(e) |> Exp.term_of) { + | Fun(p, body, _, _) => + let bound = Pat.bound_vars(p); + if (List.mem(bound, self, ~equal=String.equal)) { + Ok([]) /* the self-name is shadowed by its own parameter */; + } else { + let env' = + pat_bind( + ~origin={ + param: index, + comp: None, + }, + ~strict=false, + p, + ) + @ shadow(env, bound); + chain(~self, ~index=index + 1, ~env=env', body); + }; + | _ => go(~self, ~env, e) + } + +and go = + (~self: Var.t, ~env: env, e: Exp.t): result(list(list(pos)), reason) => { + let go_all = (es: list(Exp.t)): result(list(list(pos)), reason) => + List.fold_left( + ~f= + (acc, e) => { + let* xs = acc; + let* ys = go(~self, ~env, e); + Ok(xs @ ys); + }, + ~init=Ok([]), + es, + ); + /* Enter a subscope under pattern `p`, optionally seeding statuses for + * its bindings from the matched scrutinee's status. */ + let under = + (~seed: option(status), p: Pat.t, e: Exp.t) + : result(list(list(pos)), reason) => { + let bound = Pat.bound_vars(p); + if (List.mem(bound, self, ~equal=String.equal)) { + Ok([]) /* self shadowed: no recursive calls possible below */; + } else { + let seeded = + switch (seed) { + | Some({origin, strict}) => + /* Bindings under at least one constructor layer become + * strict; a bare alias of an already-strict variable is + * still strict (subterm of a subterm). */ + pat_bind(~origin, ~strict, p) + | None => [] + }; + go(~self, ~env=seeded @ shadow(env, bound), e); + }; + }; + switch (e |> Exp.term_of) { + | Var(x) when String.equal(x, self) => + Error( + "`" + ++ x + ++ "` escapes: it is used other than as the head of a direct call", + ) + | Var(_) + | Atom(_) + | Constructor(_) + | BuiltinFun(_) + | Label(_) + | ExplicitNonlabel + | LivelitName(_) + | Undefined + | DrvQuote(_) => Ok([]) + | Parens(e1) + | Projector(_, e1) + | Asc(e1, _) + | Filter(_, e1) + | Closure(_, e1) + | TyAlias(_, _, e1) + | Use(_, e1) + | TypAp(e1, _) + | Test(e1) => go(~self, ~env, e1) + | ListLit(es) + | Tuple(es) => go_all(es) + | TupLabel(e1, e2) + | Dot(e1, e2) + | TupleExtension(e1, e2) + | Cons(e1, e2) + | ListConcat(e1, e2) + | Seq(e1, e2) + | HintedTest(e1, e2) => go_all([e1, e2]) + | BinOp(_, e1, e2) => go_all([e1, e2]) + | UnOp(_, e1) => go(~self, ~env, e1) + | If(e1, e2, e3) => go_all([e1, e2, e3]) + | DeferredAp(fn, args) => go_all([fn, ...args]) + | Fun(p, body, _, _) => under(~seed=None, p, body) + | TypFun(_, body, _) => go(~self, ~env, body) + | Let(p, e1, e2) => + let* r1 = go(~self, ~env, e1); + let* r2 = under(~seed=var_status(env, e1), p, e2); + Ok(r1 @ r2); + | Match(scrut, rules) => + let* r0 = go(~self, ~env, scrut); + let seed = var_status(env, scrut); + List.fold_left( + ~f= + (acc, (p, rhs)) => { + let* xs = acc; + let* ys = under(~seed, p, rhs); + Ok(xs @ ys); + }, + ~init=Ok(r0), + rules, + ); + /* A nested fixpoint must itself be structurally recursive; its body + * is then still walked for calls to the outer self, with the inner + * binder shadowing. Totality re-checks the inner fix too, but this + * check must stand on its own. */ + | FixF(p, body, _) => + let* _ = + switch (check(e)) { + | Ok () => Ok([]) + | Error(r) => Error("nested fixpoint: " ++ r) + }; + let bound = Pat.bound_vars(p); + if (List.mem(bound, self, ~equal=String.equal)) { + Ok([]); + } else { + go(~self, ~env=shadow(env, bound), body); + }; + | Ap(_) => + let (head, args) = uncurry(e); + switch (head |> Exp.term_of) { + | Var(f) when String.equal(f, self) => + /* Arguments may themselves contain recursive calls. */ + let* inner = go_all(args); + let posset = valid_positions(env, args); + if (List.is_empty(posset)) { + Error( + "a recursive call to `" + ++ f + ++ "` passes no strict subterm of a parameter in any argument position", + ); + } else { + Ok(inner @ [posset]); + }; + | _ => + let* rh = go(~self, ~env, head); + let* ra = go_all(args); + Ok(rh @ ra); + }; + /* Holes, modules, theorems, quantifiers, invalid text, ... (Totality + * refuses them independently). */ + | EmptyHole + | Invalid(_) + | MultiHole(_) + | DynamicErrorHole(_) + | Deferral(_) + | Module(_) + | ModuleExp(_) + | Theorem(_) + | Forall(_) => + Error("contains a form structural-recursion detection does not analyze") + }; +}; diff --git a/src/language/proof/TheoremNamespace.re b/src/language/proof/TheoremNamespace.re new file mode 100644 index 0000000000..c49005fd81 --- /dev/null +++ b/src/language/proof/TheoremNamespace.re @@ -0,0 +1,36 @@ +/* The scope a theorem's proof is checked in, at the env `env` where + * evaluation reached the theorem: the theorems in its namespace, the builtin + * axioms, and the verdicts of the theorems checked before it. */ +let scope = + ( + ~env: Environment.t(Exp.t), + ~verdicts: list((Id.t, SemanticCtx.verdict)), + namespace: ProofStatics.namespace, + ) + : SemanticCtx.t => + SemanticCtx.of_ctx_and_env( + ~captured=namespace.captured, + { + ...Ctx.empty, + entries: + List.map(~f=entry => Ctx.TheoremEntry(entry), namespace.theorems) + @ List.rev_map( + ~f=entry => Ctx.TheoremEntry(entry), + Statics.initial_theorems, + ), + }, + env, + ) + |> SemanticCtx.with_verdicts(verdicts); + +/* Whether a proof cites the same theorems in either namespace. */ +let same = (a: ProofStatics.namespace, b: ProofStatics.namespace): bool => + List.equal(Id.equal, a.captured, b.captured) + && List.equal( + (x: Ctx.theorem_entry, y: Ctx.theorem_entry) => + String.equal(x.name, y.name) + && Id.equal(x.id, y.id) + && Option.equal(Exp.fast_equal_with_lexemes, x.prop, y.prop), + a.theorems, + b.theorems, + ); diff --git a/src/language/proof/Totality.re b/src/language/proof/Totality.re new file mode 100644 index 0000000000..21f4a1096e --- /dev/null +++ b/src/language/proof/Totality.re @@ -0,0 +1,309 @@ +open Util; + +/* The structural-totality check: the proof checker's divergence gate. + * + * `check` conservatively decides "evaluating this expression cannot + * diverge". Divergence is ⊥: it can't be expressed as a boolean + * condition, so unlike a domain error it can never become an obligation, + * and the caller must refuse the step when this check fails. When + * unsure, the check fails with a reason. + * + * Totality + * -------- + * "Total" means: you may evaluate it, and if it is a function you may + * apply it anywhere on its type's domain. There is no status of "total + * as a value but possibly looping as a function": a value you may not + * call is not a total value. So: + * - a quantified binder of arrow type denotes a total map. + * `forall f -> ... f(x) ...` is fine: both `f` and `f(x)` are total. + * Instantiating such a binder at a looping closure (`omega`) is what + * gets refused (ProofCheck.Gate.instantiations), not the use of the + * binder. + * - `fun x -> e` is total exactly when `e` is, with the pattern's + * bindings assumed total (as values and, if arrow-typed, as maps). + * Treating every lambda as a total value without looking at its body + * would make `fun x -> omega(x)` total. + * - a parameter of a function whose body we are walking is assumed + * total, because the arguments were checked total first. This lets + * `fold_left(xs, f, acc)` through: the builtin's body applies its + * own `f` parameter, which stood for a total map at the call site. + * + * Totality is not definedness. `1/0` and `head([])` terminate in `err`, + * which DomainConditions turns into obligations. `fun x -> 1/x` is a + * total map here. + * + * What passes: + * - literals, constructors, tuples/lists; + * - variables: after substitution these are quantified binders, + * lambda/fix parameters, or builtins, all total maps (above); + * - lambdas whose body is total under the assumption that their + * parameters are total; + * - applications of total functions to total arguments, including + * applications of abstract (quantified) functions; + * - builtin applications (every Hazel builtin terminates; their + * partiality is the domain scan's job); + * - case/if with total scrutinee and all branches total. + * + * What fails: + * - any reachable `FixF` that is not structurally recursive + * (StructuralRecursion). Recursive `let`s are elaborated to `FixF`, + * and evaluated environment values keep the `FixF` spine through + * `Substitution.in_exp`, so one syntactic check covers `fix`, + * recursive lets, and references to recursive definitions alike. + * A structurally recursive fix passes: its body is walked with the + * self-names assumed total (sound by well-founded induction on the + * subterm order, since every recursive call strictly descends), so + * the rest of the body is held to the same standard. A + * non-structural fix fails with its own reason. This is why + * `omega == omega` is refused even though `omega` is only a value + * there: a looping map is not total. + * - applying a variable that is definitely not of function type (the + * term is ill-typed or unclassifiable); + * - anything else we can't positively classify (holes, exotic forms). + * + * Quantified functions are total on their type's whole domain; there is + * no way to quantify over a function that is total only on part of it. + * + * The expression is expected to be environment-substituted + * (`Substitution.in_exp`) before calling: substitution inlines visible + * definitions (so non-recursive `let f = fun ...` applications can be + * checked through their bodies), erases closures, and leaves quantified + * binders as bare `Var`s. */ + +[@deriving (show({with_path: false}), sexp, yojson)] +type reason = string; + +let check = + (~statics: ProofStatics.t, ~ctx: Ctx.t, exp: Exp.t): result(unit, reason) => { + open Result.Syntax; + /* Could the variable `x` denote a function? Any variable that can be a + * function is assumed to be a total map, so this only rules out applying + * a name pinned to a non-function type (an ill-typed / unclassifiable + * term): by the statics at this occurrence, or else by the binder in + * `ctx`. Unknown types and names bound nowhere (lambda and fix + * parameters, whose binding site is inside the expression rather than in + * the surrounding context) are allowed. */ + let may_be_function = (x: Exp.t, name: Var.t): bool => { + let typ = + switch (statics.typ(Exp.rep_id(x))) { + | Some(_) as typ => typ + | None => + Ctx.lookup_var(ctx, name) + |> Option.map(~f=(entry: Ctx.var_entry) => entry.typ) + }; + switch (Option.map(~f=Typ.term_of, typ)) { + | None => true + /* Definitely not a function. Everything else — arrows, unknowns, + * aliases, polymorphic and recursive types, wrappers — is allowed. */ + | Some(Atom(_) | List(_) | Sum(_) | Prod(_) | Label(_) | ExplicitNonlabel) => + false + | Some(_) => true + }; + }; + /* Builtins terminate. */ + let is_builtin = (name: Var.t): bool => + Option.is_some(Environment.lookup(Builtins.env_init, name)); + /* `assumed`: names that may be treated as total, both as values and + * as maps, inside the term we are walking: + * - self-names of enclosing structurally-recursive fixpoints (sound + * by well-founded induction on the subterm order); + * - parameters of any function whose body we walk, since the + * arguments at the application site were checked total first, and + * a quantified binder standing in an argument position denotes a + * total map. + * Rebinding such a name shadows the assumption. + * + * Entering the body of a function or fixpoint, its parameters join + * `assumed`, shadowing any same-named outer assumption. */ + let bind_total = (assumed: list(Var.t), p: Pat.t): list(Var.t) => { + let bound = Pat.bound_vars(p); + bound + @ List.filter(~f=n => !List.mem(bound, n, ~equal=String.equal), assumed); + }; + /* On a reachable FixF: if it is structurally recursive, continue `k` + * into the body with the self-names assumed total; otherwise fail. */ + let fix_gate = + ( + ~assumed: list(Var.t), + fix: Exp.t, + p: Pat.t, + body: Exp.t, + k: (~assumed: list(Var.t), Exp.t) => result(unit, reason), + ) + : result(unit, reason) => + switch (StructuralRecursion.check(fix)) { + | Ok () => k(~assumed=bind_total(assumed, p), body) + | Error(r) => + Error( + "the recursive function `" + ++ ( + switch (p |> Pat.bindings |> Binding.variable_names) { + | [name, ..._] => name + | [] => "_" + } + ) + ++ "` may diverge: it is recursive and not visibly structural (" + ++ r + ++ ")", + ) + }; + let rec go = (~assumed: list(Var.t), e: Exp.t): result(unit, reason) => + switch (e |> Exp.term_of) { + /* Literals and other atomic values. */ + | Atom(_) + | Constructor(_) + | BuiltinFun(_) + | Label(_) + | ExplicitNonlabel + | ListLit([]) + | DrvQuote(_) => Ok() + /* A bare variable: after substitution these are quantified binders, + * lambda/fix parameters, or builtins, which all denote total maps + * (header). A looping closure is caught where a binder is + * instantiated (ProofCheck.Gate.instantiations). */ + | Var(_) => Ok() + /* A lambda is total exactly when its body is, with the parameters + * assumed total (header). */ + | Fun(p, body, _, _) => go(~assumed=bind_total(assumed, p), body) + | TypFun(_, body, _) => go(~assumed, body) + /* A structurally recursive fix unrolls to its body with itself (a + * total value, by the structural argument) bound, so check the body + * under that assumption. A non-structural fix is refused. */ + | FixF(p, body, _) => fix_gate(~assumed, e, p, body, go) + /* Transparent wrappers. */ + | Parens(e1) + | Projector(_, e1) + | Asc(e1, _) + | Filter(_, e1) + | Closure(_, e1) + | TyAlias(_, _, e1) + | Use(_, e1) + | Test(e1) => go(~assumed, e1) + /* Strict compound values and operators: total iff the children + * are. (`1/0` is `err`, not ⊥: the domain scan's job.) */ + | ListLit(es) + | Tuple(es) => go_all(~assumed, es) + | TupLabel(e1, e2) + | Dot(e1, e2) + | TupleExtension(e1, e2) + | Cons(e1, e2) + | ListConcat(e1, e2) + | Seq(e1, e2) + | HintedTest(e1, e2) + | BinOp(_, e1, e2) => + let* _ = go(~assumed, e1); + go(~assumed, e2); + | UnOp(_, e1) => go(~assumed, e1) + /* Non-recursive let (recursive lets carry a FixF in their definiens + * after elaboration). The let's bindings shadow any assumed + * self-names in its body, but the definiens was checked total, so + * they are themselves assumed total. */ + | Let(p, e1, e2) => + let* _ = go(~assumed, e1); + go(~assumed=bind_total(assumed, p), e2); + /* case/if: total if the scrutinee and all branches are. */ + | If(e1, e2, e3) => + let* _ = go(~assumed, e1); + let* _ = go(~assumed, e2); + go(~assumed, e3); + | Match(scrut, rules) => + let* _ = go(~assumed, scrut); + List.fold_left( + ~f= + (acc, (p, rhs)) => { + let* _ = acc; + /* Pattern bindings destructure the (total) scrutinee. */ + go(~assumed=bind_total(assumed, p), rhs); + }, + ~init=Ok(), + rules, + ); + | Ap(_, fn, arg) => + let* _ = go(~assumed, arg); + go_ap(~assumed, ~depth=1, fn); + /* Everything else (holes, invalid text, deferrals, modules, quoted + * derivations with holes, type applications, ...) is refused. */ + | EmptyHole + | Undefined + | Invalid(_) + | MultiHole(_) + | DynamicErrorHole(_) + | Deferral(_) + | LivelitName(_) + | TypAp(_) + | DeferredAp(_) + | Module(_) + | ModuleExp(_) + | Theorem(_) + | Forall(_) => Error("cannot establish that this expression terminates") + } + /* The head of an application spine. Arguments were already checked + * total, so a lambda head reduces to its body with its parameters + * assumed total (if one is a function it is a total map, so the body + * may apply it). `depth` counts the pending arguments: each lambda + * head consumes one, and an inner lambda reached with arguments still + * pending is itself applied. Without it, + * `(fun a -> fun b -> body)(x)(y)` would stop at the inner Fun as a + * value and never check `body`. */ + and go_ap = + (~assumed: list(Var.t), ~depth: int, fn: Exp.t): result(unit, reason) => + switch (fn |> Exp.term_of) { + | Parens(e1) + | Projector(_, e1) + | Asc(e1, _) + | Closure(_, e1) => go_ap(~assumed, ~depth, e1) + | Fun(p, body, _, _) => + let assumed = bind_total(assumed, p); + depth <= 1 + ? go(~assumed, body) : go_ap(~assumed, ~depth=depth - 1, body); + /* All Hazel builtins terminate (partiality is `err`, scanned by + * DomainConditions). */ + | BuiltinFun(_) => Ok() + | Constructor(_) => Ok() + /* An applied structurally recursive fix terminates on total + * arguments; keep checking its body with the self-names assumed + * total. */ + | FixF(p, body, _) => + fix_gate(~assumed, fn, p, body, (~assumed, body) => + go_ap(~assumed, ~depth, body) + ) + /* Curried application: check the inner argument, keep unwrapping. */ + | Ap(_, fn', arg') => + let* _ = go(~assumed, arg'); + go_ap(~assumed, ~depth=depth + 1, fn'); + /* Applying a variable. Every function-typed name in scope denotes a + * total map: + * - `assumed`: a recursive call of an enclosing structural fix, + * or a parameter standing for an argument already checked total; + * - a builtin, which terminates; + * - otherwise a quantified binder, total by the quantifier's + * meaning and enforced at instantiation. + * Only a name the statics have pinned to a non-function type is + * refused, as a term we can't classify. */ + | Var(x) => + if (List.mem(assumed, x, ~equal=String.equal) + || is_builtin(x) + || may_be_function(fn, x)) { + Ok(); + } else { + Error( + "`" + ++ x + ++ "` is not a function here; cannot establish this application terminates", + ); + } + | _ => Error("cannot establish that this application terminates") + } + and go_all = + (~assumed: list(Var.t), es: list(Exp.t)): result(unit, reason) => + List.fold_left( + ~f= + (acc, e) => { + let* _ = acc; + go(~assumed, e); + }, + ~init=Ok(), + es, + ); + go(~assumed=[], exp); +}; diff --git a/src/language/statics/ConstructorStaticsHelpers.re b/src/language/statics/ConstructorStaticsHelpers.re index da58e5da63..72c634eaad 100644 --- a/src/language/statics/ConstructorStaticsHelpers.re +++ b/src/language/statics/ConstructorStaticsHelpers.re @@ -48,7 +48,6 @@ let ctr_ana_typ = | Projector(_) | Rec(_) | Poly(_) - | ProofOf(_) | ProdProjection(_) | ProdExtension(_) | Sig(_) => diff --git a/src/language/statics/Coverage.re b/src/language/statics/Coverage.re index 8b0c582053..94519e4d2b 100644 --- a/src/language/statics/Coverage.re +++ b/src/language/statics/Coverage.re @@ -131,7 +131,6 @@ module Ctr = { } | Prod(elts) => Finite(Map.singleton(tuple_ctr(List.length(elts)), elts)) - | ProofOf(_) => Infinite | TupLabel(_, ty) => Finite(Map.singleton(tuple_ctr(1), [ty])) | List(elt_ty) => Finite( @@ -425,7 +424,6 @@ module UnseenPatternList: UnseenPatternList = { ) | Arrow(_) | Poly(_) - | ProofOf(_) | DrvQuoteTy(_) | Var(_) => unseen_pattern | Parens(_) @@ -564,7 +562,6 @@ module UnseenPatternList: UnseenPatternList = { cons_ctr(first_unused_str(""), col_type, unseen_pattern); | Arrow(_) | Poly(_) - | ProofOf(_) | DrvQuoteTy(_) | Var(_) => cons_wild(unseen_pattern) | Parens(_) @@ -629,7 +626,6 @@ module UnseenPatternList: UnseenPatternList = { | Atom(String) => cons_wild(unseen_pattern) | Arrow(_) | Poly(_) - | ProofOf(_) | DrvQuoteTy(_) | Var(_) => cons_wild(unseen_pattern) | Parens(_) @@ -835,7 +831,8 @@ module Submatrices = { Ctr.Map.update(ctr, add_row(idx, cols), ctrs); }; - let of_matrix = (m: Matrix.t, all_ctrs: Ctr.all_ctrs): t => { + let of_matrix = + (~strict_unknown: bool, m: Matrix.t, all_ctrs: Ctr.all_ctrs): t => { let seen_data = seen(m, all_ctrs); let { seen_ints, @@ -969,7 +966,12 @@ module Submatrices = { let first_col_exhaustive = switch (all_ctrs) { - | Unknown => true + /* A column of unknown type. At edit time it counts as covered, so + * an in-progress program doesn't flag a match whose scrutinee type + * isn't known yet. With `strict_unknown` (the prover) it is treated + * like `Infinite`: with no known constructor set, only a catch-all + * (a wildcard, a variable or a hole) covers it. */ + | Unknown => strict_unknown ? seen_truth || seen_hole : true | Infinite => seen_truth || seen_hole | Finite(_) => seen_truth || seen_hole || seen_all_ctrs }; @@ -1001,7 +1003,7 @@ module type CheckMatrix = { redundant_rows, }; - let check: (list(Constraint.t), Typ.t) => t; + let check: (~strict_unknown: bool=?, list(Constraint.t), Typ.t) => t; }; module CheckMatrix: CheckMatrix = { @@ -1084,7 +1086,8 @@ module CheckMatrix: CheckMatrix = { }; // We assume col_tys is already normalized. - let rec check_matrix = (m: Matrix.t, col_tys: list(Typ.t)): result => { + let rec check_matrix = + (~strict_unknown: bool, m: Matrix.t, col_tys: list(Typ.t)): result => { switch (col_tys) { | [] => failwith("Empty column types.") | [first_col_ty, ...rem_col_tys] => @@ -1104,7 +1107,7 @@ module CheckMatrix: CheckMatrix = { first_col_redundant_rows, seen_data, } = - Submatrices.of_matrix(m, all_ctrs); + Submatrices.of_matrix(~strict_unknown, m, all_ctrs); let (is_exhaustive, unseen_pattern, redundant_rows) = Ctr.Map.fold( @@ -1129,7 +1132,7 @@ module CheckMatrix: CheckMatrix = { unseen_pattern: submatrix_unseen_pattern, redundant_rows: submatrix_redundant_rows, } = - check_matrix(submatrix, col_tys); + check_matrix(~strict_unknown, submatrix, col_tys); let is_still_exhaustive = is_exhaustive && is_submatrix_exhaustive; @@ -1179,10 +1182,13 @@ module CheckMatrix: CheckMatrix = { }; }; - // IMPORTANT: ty should already be fully normalized. - let check = (xis: list(Constraint.t), ty: Typ.t): t => { + /* `ty` must already be fully normalized. + * + * With `strict_unknown`, a column of unknown type is not covered + * vacuously. The prover passes it; edit-time statics doesn't. */ + let check = (~strict_unknown=false, xis: list(Constraint.t), ty: Typ.t): t => { let {is_exhaustive, unseen_pattern, redundant_rows} = - check_matrix(Matrix.of_constraints(xis), [ty]); + check_matrix(~strict_unknown, Matrix.of_constraints(xis), [ty]); { exhaustiveness: is_exhaustive diff --git a/src/language/statics/Ctx.re b/src/language/statics/Ctx.re index a1830abdd6..204e955d05 100644 --- a/src/language/statics/Ctx.re +++ b/src/language/statics/Ctx.re @@ -33,12 +33,28 @@ type node_or_list = | Node(Virtual_dom.Vdom.Node.t) | List(list(Virtual_dom.Vdom.Node.t)); +/* The theorem namespace. A theorem entry names a judgment, not a value: + theorems, axioms, and the hypotheses that `assume`/`case_eq`/ + `ih_`/`have` install. Like the type namespace (`TVarEntry`), it is + separate from variables: a theorem and a variable of the same name + don't shadow each other. */ +[@deriving (show({with_path: false}), sexp, yojson)] +type theorem_entry = { + name: Var.t, + id: Id.t, + /* The proposition this entry asserts. `None` for the built-in axioms, + whose statements are rules in `Axioms.re` (see + `Statics.initial_theorems`). */ + prop: option(TermBase.exp_t), +}; + [@deriving (show({with_path: false}), sexp, yojson)] type entry = | VarEntry(var_entry) | ConstructorEntry(var_entry) | TVarEntry(tvar_entry) - | LivelitEntry(LivelitCtx.raw_livelit); + | LivelitEntry(LivelitCtx.raw_livelit) + | TheoremEntry(theorem_entry); [@deriving (show({with_path: false}), sexp, yojson)] type t = { @@ -59,6 +75,27 @@ let extend = (ctx: t, entry): t => { let extend_tvar = (ctx: t, tvar_entry: tvar_entry): t => extend(ctx, TVarEntry(tvar_entry)); +let extend_theorem = (ctx: t, thm_entry: theorem_entry): t => + extend(ctx, TheoremEntry(thm_entry)); + +/* `ctx` without the facts `about` holds of. The built-in axioms state no + proposition here, so they stay. */ +let forget_facts = (about: TermBase.exp_t => bool, ctx: t): t => { + ...ctx, + entries: + List.filter( + ~f= + fun + | TheoremEntry({prop: Some(fact), _}) => !about(fact) + | TheoremEntry({prop: None, _}) + | VarEntry(_) + | ConstructorEntry(_) + | TVarEntry(_) + | LivelitEntry(_) => true, + ctx.entries, + ), +}; + let extend_alias = (ctx: t, name: string, id: Id.t, ty: TermBase.Typ.t): t => extend_tvar( ctx, @@ -110,11 +147,30 @@ let lookup_livelit = (ctx: t, name: string): option(LivelitCtx.raw_livelit) => ctx.entries, ); +let lookup_theorem = (ctx: t, name: Var.t): option(theorem_entry) => + List.find_map( + ~f= + fun + | TheoremEntry(h) when String.equal(h.name, name) => Some(h) + | _ => None, + ctx.entries, + ); + +let get_theorem_entries = (ctx: t): list(theorem_entry) => + List.filter_map( + ~f= + fun + | TheoremEntry(h) => Some(h) + | _ => None, + ctx.entries, + ); + let get_id: entry => Id.t = fun | VarEntry({id, _}) | ConstructorEntry({id, _}) | TVarEntry({id, _}) => id + | TheoremEntry({id, _}) => id | LivelitEntry({name, _}) => Id.mk_str(name); let lookup_var = (ctx: t, name: string): option(var_entry) => @@ -263,26 +319,51 @@ let filter_shadowed = (ctx: t): t => { ctx.entries |> List.fold_left( ~f= - ((ctx, term_set, typ_set), entry) => { + ((ctx, term_set, typ_set, thm_set), entry) => { switch (entry) { | VarEntry({name, _}) | ConstructorEntry({name, _}) => VarSet.mem(name, term_set) - ? (ctx, term_set, typ_set) - : ([entry, ...ctx], VarSet.add(name, term_set), typ_set) + ? (ctx, term_set, typ_set, thm_set) + : ( + [entry, ...ctx], + VarSet.add(name, term_set), + typ_set, + thm_set, + ) | TVarEntry({name, _}) => VarSet.mem(name, typ_set) - ? (ctx, term_set, typ_set) - : ([entry, ...ctx], term_set, VarSet.add(name, typ_set)) + ? (ctx, term_set, typ_set, thm_set) + : ( + [entry, ...ctx], + term_set, + VarSet.add(name, typ_set), + thm_set, + ) | LivelitEntry({name, _}) => VarSet.mem(name, term_set) - ? (ctx, term_set, typ_set) - : ([entry, ...ctx], VarSet.add(name, term_set), typ_set) + ? (ctx, term_set, typ_set, thm_set) + : ( + [entry, ...ctx], + VarSet.add(name, term_set), + typ_set, + thm_set, + ) + | TheoremEntry({name, _}) => + /* Theorems shadow only other theorems. */ + VarSet.mem(name, thm_set) + ? (ctx, term_set, typ_set, thm_set) + : ( + [entry, ...ctx], + term_set, + typ_set, + VarSet.add(name, thm_set), + ) } }, - ~init=([], VarSet.empty, VarSet.empty), + ~init=([], VarSet.empty, VarSet.empty, VarSet.empty), ) - |> (((ctx, _, _)) => List.rev(ctx)), + |> (((ctx, _, _, _)) => List.rev(ctx)), }; let filter_stepper_filter_variables = (ctx: t): t => { @@ -296,6 +377,7 @@ let filter_stepper_filter_variables = (ctx: t): t => { | VarEntry({name, _}) | ConstructorEntry({name, _}) | LivelitEntry({name, _}) + | TheoremEntry({name, _}) | TVarEntry({name, _}) => if (String.is_prefix(name, ~prefix="$")) { ctx; diff --git a/src/language/statics/Info.re b/src/language/statics/Info.re index 54a4d0623e..86ce685867 100644 --- a/src/language/statics/Info.re +++ b/src/language/statics/Info.re @@ -126,6 +126,17 @@ type mpat = { ancestors, }; +[@deriving (show({with_path: false}), sexp, yojson)] +type proof = { + id: Id.t, + user_term: Proof.t, + cls: Cls.t, + sort: Sort.t, + ctx: Ctx.t, + ancestors, + marks: list(Mark.t) /* Statics errors on the proof node itself */, +}; + [@deriving (show({with_path: false}), sexp, yojson)] type secondary = { id: Id.t, // Id of term static info is sourced from @@ -145,6 +156,7 @@ type t = | InfoMod(mod_) | InfoSig(sig_) | InfoMPat(mpat) + | InfoProof(proof) | Secondary(secondary); /* ==================================== Getters ==================================== */ @@ -160,6 +172,7 @@ let sort_of: t => Sort.t = | InfoMod(_) => Mod | InfoSig(_) => Sig | InfoMPat(_) => MPat + | InfoProof(_) => Proof | Secondary(s) => s.sort; /* The grammar's mold system uses a single `Drv(Exp)` outer sort for all of @@ -194,6 +207,7 @@ let cls_of: t => Cls.t = | InfoMod({cls, _}) | InfoSig({cls, _}) | InfoMPat({cls, _}) + | InfoProof({cls, _}) | Secondary({cls, _}) => cls; /* Display label for a term's cls. The parser always builds numeric @@ -219,6 +233,7 @@ let any_of: t => option(Any.t) = | InfoMod({user_term, _}) => Some(Mod(user_term)) | InfoSig({user_term, _}) => Some(Sig(user_term)) | InfoMPat({user_term, _}) => Some(MPat(user_term)) + | InfoProof({user_term, _}) => Some(Proof(user_term)) | Secondary(_) => None; let ctx_of: t => Ctx.t = @@ -231,6 +246,7 @@ let ctx_of: t => Ctx.t = | InfoMod({ctx, _}) | InfoSig({ctx, _}) | InfoMPat({ctx, _}) + | InfoProof({ctx, _}) | Secondary({ctx, _}) => ctx; let ancestors_of: t => ancestors = @@ -242,7 +258,8 @@ let ancestors_of: t => ancestors = | InfoTPat({ancestors, _}) | InfoMod({ancestors, _}) | InfoSig({ancestors, _}) - | InfoMPat({ancestors, _}) => ancestors + | InfoMPat({ancestors, _}) + | InfoProof({ancestors, _}) => ancestors | Secondary(_) => []; //TODO let parent_id_of: t => option(Id.t) = @@ -257,7 +274,8 @@ let id_of: t => Id.t = | InfoTPat(i) => TPat.rep_id(i.user_term) | InfoMod({id, _}) | InfoSig({id, _}) - | InfoMPat({id, _}) => id + | InfoMPat({id, _}) + | InfoProof({id, _}) => id | Secondary(s) => s.id; let marks_of: t => list(Mark.t) = @@ -266,6 +284,7 @@ let marks_of: t => list(Mark.t) = | InfoPat({marks, _}) => marks | InfoTyp({marks, _}) | InfoTPat({marks, _}) => marks + | InfoProof({marks, _}) => marks | InfoDrv(_) /* Drv errors are tracked separately via DrvInfo.error_of. */ | InfoMod(_) | InfoSig(_) @@ -290,6 +309,7 @@ let warnings_of: t => list(Warning.list_item) = | InfoMod(_) | InfoSig(_) | InfoMPat(_) + | InfoProof(_) | Secondary(_) => []; let is_warning = (ci: t): bool => !List.is_empty(warnings_of(ci)); @@ -310,6 +330,7 @@ let is_typable_term: option(t) => bool = | Some( InfoTyp(_) | InfoTPat(_) | InfoMod(_) | InfoSig(_) | InfoMPat(_) | InfoDrv(_) | + InfoProof(_) | Secondary(_), ) => false diff --git a/src/language/statics/Mark.re b/src/language/statics/Mark.re index 8992dfefe1..5ef577175d 100644 --- a/src/language/statics/Mark.re +++ b/src/language/statics/Mark.re @@ -48,6 +48,11 @@ type tpat_var_err = Do not reorder without understanding the impact on error selection. */ [@deriving (show({with_path: false}), sexp, yojson, variants)] type t = + /* A runtime error (from a DynamicErrorHole in a result expression), + * attached by statics to the expression *inside* the hole: printing + * strips the DynamicErrorHole wrapper, so only inner ids appear in + * rendered syntax and can carry the error decoration. */ + | DynamicError(InvalidOperationError.t) | BuiltinError(error_builtin) | Free(Var.t) | IsBadPartialAp(error_partial_ap) @@ -101,7 +106,9 @@ type t = | ExpectedConstructor | IsMulti | DuplicateLabel(LabeledTuple.label, Typ.t) - | DuplicateVar(string, Typ.t); + | DuplicateVar(string, Typ.t) + | FreeHypothesis(Var.t) + | AxiomSlotNotHypothesis(Grammar.any_t(IdTagged.IdTag.t)); /* Declaration-order tag index, derived by ppx_variants_conv. */ let compare = (a: t, b: t): int => diff --git a/src/language/statics/MatchedTyp.re b/src/language/statics/MatchedTyp.re index a1f07302ae..44c20925cf 100644 --- a/src/language/statics/MatchedTyp.re +++ b/src/language/statics/MatchedTyp.re @@ -30,7 +30,6 @@ let head = (ctx: Ctx.t, ty: Typ.t): Typ.t => { | Parens(_) | Projector(_) | Poly(_) - | ProofOf(_) | ProdProjection(_) | ProdExtension(_) | Sig(_) => ty diff --git a/src/language/statics/Statics.re b/src/language/statics/Statics.re index 0a270d80bc..f7e442d68e 100644 --- a/src/language/statics/Statics.re +++ b/src/language/statics/Statics.re @@ -48,10 +48,14 @@ let rec any_to_info_map = let m = drv_to_info_map(drv, m, ~ctx, ~ancestors, ~sort=Jdmt); (CoCtx.empty, Drv(drv), m); | Rul(r) => rul_to_info_map(~ctx, ~ancestors, ~probe_ids, r, m) + | PRul(r) => prul_to_info_map(~ctx, ~ancestors, r, m) | Mod(m_term) => mod_to_info_map(~ctx, ~ancestors, ~probe_ids, m_term, m) | Sig(s_term) => sig_to_info_map(~ctx, ~ancestors, ~probe_ids, s_term, m) | MPat(mp_term) => mpat_to_info_map(~ctx, ~ancestors, ~probe_ids, mp_term, m) + | Proof(p_term) => + let (p, m) = proof_to_info_map(~ctx, ~ancestors, p_term, m); + (CoCtx.empty, Proof(p), m); | Any () => (CoCtx.empty, Any(), m) } and multi = @@ -196,6 +200,9 @@ and uexp_to_info_map = ~ctx: Ctx.t, ~ana=syn, ~is_in_filter=false, + /* True inside a theorem's proposition or proof, where forms with no + evaluation semantics (`forall`, function `==`) are legal. */ + ~in_theorem=false, ~ancestors, ~probe_ids: Id.Map.t(unit)=Id.Map.empty, uexp: Exp.t, @@ -280,6 +287,7 @@ and uexp_to_info_map = ~ctx=ctx, ~ana=syn, ~is_in_filter=is_in_filter, + ~in_theorem=in_theorem, ~ancestors=ancestors_inclusive, uexp: Exp.t, m: Map.t, @@ -289,12 +297,18 @@ and uexp_to_info_map = ~ctx, ~ana, ~is_in_filter, + ~in_theorem, ~ancestors, ~probe_ids, uexp, m, ); }; + /* `forall` is a proposition, not a value: it has no evaluation + semantics, so outside a theorem it is flagged (as a warning, since it + still types as Bool). A `let`-bound `forall` is flagged too. */ + let forall_warnings = + in_theorem ? [] : [Warning.Exp(ForallOutsideTheorem)]; let map_m_go = (m, anas, es) => { let (pairs, m) = map_m2( @@ -309,6 +323,75 @@ and uexp_to_info_map = let go_pat = upat_to_info_map(~ctx, ~ancestors=ancestors_inclusive, ~probe_ids); let go_typ = utyp_to_info_map(~ctx, ~ancestors=ancestors_inclusive); + /* A theorem's statement, a proposition, and its proof. The proof can't + cite the theorem it proves, but sees the variables bound by the + statement's outer `forall`s, so a proof of `forall x -> P` reasons + about an arbitrary `x`. */ + let theorem_to_info_map = (stmt: Exp.t, proof: Proof.t, m: Map.t) => { + let (stmt_info, stmt_elab, m) = + go(~in_theorem=true, ~ana=Atom(Bool) |> Typ.temp, stmt, m); + /* Walks the binders the `Forall` rule does, threading the map so the + binder patterns keep their info entries. */ + let rec proof_ctx_of_goal = (ctx, goal: Exp.t, m): (Ctx.t, Map.t) => + switch (goal |> Exp.term_of) { + /* Look through parens, as `ProofCheck.peel_stmt_binders` does. + Stopping at the paren would leave the inner binder free in the + proof. */ + | Parens(e1) => proof_ctx_of_goal(ctx, e1, m) + | Forall(fp, fbody) => + /* Only the binder's ctx is needed. The statement's own walk has + already recorded the binder, with the uses the statement makes; + recording it again here, with no uses, would mark it unused. */ + let (fp', _, _) = + upat_to_info_map( + ~is_synswitch=false, + ~ctx, + ~co_ctx=CoCtx.empty, + ~ancestors=ancestors_inclusive, + ~probe_ids, + fp, + m, + ); + proof_ctx_of_goal(fp'.ctx, fbody, m); + | _ => (ctx, m) + }; + let (proof_ctx, m) = proof_ctx_of_goal(ctx, stmt, m); + let (proof_elab, m) = + proof_to_info_map( + ~ctx=proof_ctx, + ~ancestors=ancestors_inclusive, + proof, + m, + ); + /* The proof's free variables: the uses of variables bound outside + it, by the binder they have at the theorem. A proof's binders and + the placeholders for the names of the facts it cites are other + binders. Evaluation reuses a node only if its free variables are + unchanged, and checking the proof reads these. */ + let proof_co_ctx = { + let uses = ref([]); + let _: Proof.t = + Proof.map_term( + ~f_exp= + (continue, e) => { + switch (e.term, Id.Map.find_opt(IdTagged.rep_id(e), m)) { + | (Var(x), Some(InfoExp(info))) => + switch (Ctx.lookup_var(info.ctx, x), Ctx.lookup_var(ctx, x)) { + | (Some(at_use), Some(at_theorem)) + when phys_equal(at_use, at_theorem) => + uses := [info.co_ctx, ...uses^] + | _ => () + } + | _ => () + }; + continue(e); + }, + proof, + ); + CoCtx.union(uses^); + }; + (stmt_info, stmt_elab, proof_elab, proof_co_ctx, m); + }; /* Analyze an expression in label position. Adds info for the label directly (like TupLabel does for its children) and returns the label name if valid. Used by CustomStatics for builtin label args. */ @@ -688,9 +771,13 @@ and uexp_to_info_map = m, ) }; - | Var(("$e" | "$v") as name) when is_in_filter => - /* Inside a filter, the meta-variables `$e` and `$v` stand for any - expression/value, so we synthesize to `?` without consulting the ctx. */ + | Var(name) when is_in_filter && MetaVar.is_meta_name(name) => + /* Inside a pattern (a stepper filter, or a proof focus's + selector), a metavariable stands for any expression/value, so + we synthesize to `?` without consulting the ctx. Returning an + empty co_ctx is what keeps it from reading as a free variable. + `MetaVar` owns the naming convention: `$e`, `$v`, and the named + `$x` used by proof-step patterns. */ add( ~elab_term=Var(name) |> rewrap, ~elab_syn_ty=Unknown(Internal) |> Typ.temp, @@ -715,6 +802,15 @@ and uexp_to_info_map = ); | DynamicErrorHole(e, err) => let (e, e_elab, m) = go(~ana, e, m); + /* Attach the error mark to the inner expression's info entry: + printing strips the DynamicErrorHole wrapper, so only inner ids + appear in the rendered syntax and can carry the error + decoration. */ + let e = { + ...e, + marks: [Mark.DynamicError(err), ...e.marks], + }; + let m = add_info(IdTagged.ids(e.user_term), InfoExp(e), m); add( ~elab_term=DynamicErrorHole(e_elab, err) |> rewrap, ~elab_syn_ty=e.elab_syn_ty, @@ -832,10 +928,13 @@ and uexp_to_info_map = m, ) | Some(ty) when Typ.has_fun_up_to_aliases(ctx, ty) => + /* Values that contain functions can't be compared by evaluation. + Inside a theorem the comparison is a proposition, proved by + funext; elsewhere it is a type error. */ add( ~elab_term=elab_poly, ~elab_syn_ty=Atom(Bool) |> Typ.fresh, - ~marks=[CompareFun(ty)], + ~marks=in_theorem ? [] : [CompareFun(ty)], ~co_ctx=co_poly, ~probe_targets=probe_targets_poly, m, @@ -1972,6 +2071,7 @@ and uexp_to_info_map = ~elab_term=Forall(p_elab, e_elab) |> rewrap, ~elab_syn_ty=Atom(Bool) |> Typ.temp, ~marks=[], + ~warnings=forall_warnings, ~co_ctx=CoCtx.mk(ctx, p.ctx, e.co_ctx), ~probe_targets= SubexpProbeTargets.union_all([p.probe_targets, e.probe_targets]), @@ -2273,18 +2373,33 @@ and uexp_to_info_map = ]), m, ); - | Theorem({term: Var(_), _} as p, e1, e2) => + | Theorem({term: Var(x), _} as p, e1, pf, e2) => let pat_typ_refs = ModuleHelpers.collect_pat_type_refs(ctx, p); - let (e1', e1_elab, m) = go(~ctx, ~ana=Atom(Bool) |> Typ.temp, e1, m); + let (e1', e1_elab, pf_elab, pf_co_ctx, m) = + theorem_to_info_map(e1, pf, m); + /* `theorem t = ...` binds `t` in the theorem namespace only. The + pattern is walked for its info, but nothing it binds reaches the + body's variable context, so `t` in expression position is free + (or names some value `t`). + + The fact records the elaborated statement: citing the theorem + splices its right-hand side into goals, which are elaborated, and + `Equality.ignoring_ascriptions` doesn't equate the unelaborated + `Constructor(c, None)` with the goal's + `Constructor(c, Some(Some(ty)))`. An `eval ... at` target written + after such a rewrite would not be found. */ let (p', _, _) = - go_pat( - ~is_synswitch=false, - ~co_ctx=CoCtx.empty, - ~ana=Typ.fresh(ProofOf(e1)), - p, - m, + go_pat(~is_synswitch=false, ~co_ctx=CoCtx.empty, ~ana=syn, p, m); + let body_ctx = + Ctx.extend_theorem( + ctx, + { + name: x, + id: IdTagged.rep_id(p), + prop: Some(e1_elab), + }, ); - let (e2, e2_elab, m) = go(~ctx=p'.ctx, ~ana, e2, m); + let (e2, e2_elab, m) = go(~ctx=body_ctx, ~ana, e2, m); let (p, p_elab, m) = go_pat( ~is_synswitch=false, @@ -2295,14 +2410,17 @@ and uexp_to_info_map = m, ); add( - ~elab_term=Theorem(p_elab, e1_elab, e2_elab) |> rewrap, + ~elab_term=Theorem(p_elab, e1_elab, pf_elab, e2_elab) |> rewrap, ~elab_syn_ty=e2.elab_syn_ty, ~marks=[], + /* No `CoCtx.mk(ctx, p.ctx, ...)`: the theorem pattern binds no + variable, so the body's uses are not closed off here. */ ~co_ctx= CoCtx.union([ p'.co_ctx, e1'.co_ctx, - CoCtx.mk(ctx, p.ctx, e2.co_ctx), + pf_co_ctx, + e2.co_ctx, pat_typ_refs, ]), ~probe_targets= @@ -2313,9 +2431,10 @@ and uexp_to_info_map = ]), m, ); - | Theorem(p, e1, e2) => + | Theorem(p, e1, pf, e2) => let pat_typ_refs = ModuleHelpers.collect_pat_type_refs(ctx, p); - let (e1', e1_elab, m) = go(~ctx, ~ana=Atom(Bool) |> Typ.temp, e1, m); + let (e1', e1_elab, pf_elab, pf_co_ctx, m) = + theorem_to_info_map(e1, pf, m); let (p', _, _) = go_pat(~is_synswitch=false, ~co_ctx=CoCtx.empty, ~ana=syn, p, m); let (e2, e2_elab, m) = go(~ctx=p'.ctx, ~ana, e2, m); @@ -2329,13 +2448,14 @@ and uexp_to_info_map = m, ); add( - ~elab_term=Theorem(p_elab, e1_elab, e2_elab) |> rewrap, + ~elab_term=Theorem(p_elab, e1_elab, pf_elab, e2_elab) |> rewrap, ~elab_syn_ty=e2.elab_syn_ty, ~marks=[BadTheorem(e2.ty)], ~co_ctx= CoCtx.union([ p'.co_ctx, e1'.co_ctx, + pf_co_ctx, CoCtx.mk(ctx, p.ctx, e2.co_ctx), pat_typ_refs, ]), @@ -2347,15 +2467,6 @@ and uexp_to_info_map = ]), m, ); - | ProofObject(e) => - let (_, e_elab, m) = go(~ctx, ~ana=Atom(Bool) |> Typ.temp, e, m); - add( - ~elab_term=ProofObject(e_elab) |> rewrap, - ~elab_syn_ty=Typ.temp(ProofOf(e)), - ~marks=[], - ~co_ctx=CoCtx.empty, - m, - ); // TODO[Matt]: do types need coctxs now? | FixF(p, e, env) => let (p', _, _) = go_pat(~is_synswitch=false, ~co_ctx=CoCtx.empty, ~ana, p, m); @@ -4061,16 +4172,6 @@ and utyp_to_info_map = let m = utpat_to_info_map(~ctx, ~ancestors=ancestors_inclusive, utpat, m) |> snd; add(m); // TODO: check with andrew - | ProofOf(e) => - let (_, _, m) = - uexp_to_info_map( - ~ctx, - ~ancestors=ancestors_inclusive, - ~ana=Atom(Bool) |> Typ.temp, - e, - m, - ); - add(m); | Rec({term: Var(name), _} as utpat, tbody) => let body_ctx = Ctx.extend_tvar( @@ -4240,6 +4341,32 @@ and rul_to_info_map = (CoCtx.union(co_ctxs), Rul(r), m); | Invalid(_) => (CoCtx.empty, Rul(r), m) } +and prul_to_info_map = + (~ctx, ~ancestors, r: PRul.t, m: Map.t): (CoCtx.t, Any.t, Map.t) => + /* Fallback handler for proof-rule tiles not absorbed into an induction; + treat the contents as a multihole for purposes of info collection. */ + switch (r.term) { + | ProofRules(scrut, cases) => + let tms = + cases + |> List.map(~f=((p, body)) => + [Grammar.Pat(p), Grammar.Proof(body)] + ) + |> List.concat; + any_to_info_map( + ~ctx, + ~ancestors, + Exp({ + term: MultiHole([Exp(scrut), ...tms]), + annotation: r.annotation, + }), + m, + ); + | MultiHole(tms) => + let (co_ctxs, _, m) = multi(~ctx, ~ancestors, m, tms); + (CoCtx.union(co_ctxs), PRul(r), m); + | Invalid(_) => (CoCtx.empty, PRul(r), m) + } and mod_to_info_map = ( ~ctx, @@ -4387,18 +4514,580 @@ and mpat_to_info_map = let (_, _, m) = any_to_info_map(~ctx, ~ancestors, Typ(typ), m); (CoCtx.empty, MPat(mp_term), add_mpat_info(m)); }; +} +and proof_to_info_map = + (~ctx, ~ancestors, p_term: Proof.t, m: Map.t): (Proof.t, Map.t) => { + let ancestors_inclusive = [IdTagged.rep_id(p_term), ...ancestors]; + /* Record this node's info, and rebuild it around its elaborated parts. + The ids and annotation are kept, so the proof map (keyed by id) and + the checker stay in sync. */ + let add = (~marks=[], term: Proof.term, m: Map.t): (Proof.t, Map.t) => { + let info = + Info.InfoProof({ + id: IdTagged.rep_id(p_term), + user_term: p_term, + cls: Cls.Proof(Proof.cls_of_term(p_term.term)), + sort: Proof, + ctx, + ancestors, + marks, + }); + ( + { + ...p_term, + term, + }, + add_info(IdTagged.ids(p_term), info, m), + ); + }; + let go = (~ctx=ctx, p: Proof.t, m: Map.t): (Proof.t, Map.t) => + proof_to_info_map(~ctx, ~ancestors=ancestors_inclusive, p, m); + /* Every expression in a proof is inside a theorem, where the + non-computable forms (`forall`, function `==`) are legal. */ + let go_exp = (~ctx=ctx, ~ana=?, ~is_in_filter=?, e: Exp.t, m: Map.t) => + uexp_to_info_map( + ~ctx, + ~ana?, + ~is_in_filter?, + ~in_theorem=true, + ~ancestors=ancestors_inclusive, + e, + m, + ); + let go_pat = (~co_ctx=CoCtx.empty, ~ana=?, p: Pat.t, m: Map.t) => + upat_to_info_map( + ~is_synswitch=false, + ~ctx, + ~co_ctx, + ~ana?, + ~ancestors=ancestors_inclusive, + p, + m, + ); + /* A proof's binders (case patterns, `forall x =>`, `funext x =>`) name + parts of the goal, which steps reach through the goal (`from $e do`) + as often as by name, so they count as used. Fact names + (`assume h = P`, `alias`) bind in the theorem namespace, not the variable one, so no + unused-variable warning applies to them either. */ + let go_binder = (~ana=?, p: Pat.t, m: Map.t) => + go_pat(~co_ctx=CoCtx.of_bindings(Pat.bindings(p)), ~ana?, p, m); + let go_prop = (e: Exp.t, m: Map.t): (Exp.t, Map.t) => { + let (_, e, m) = go_exp(~ana=Atom(Bool) |> Typ.temp, e, m); + (e, m); + }; + /* A fact's name (`assume h = P`) is walked for its info, but its ctx is + discarded: like a theorem's name, it binds in the theorem namespace, + not the variable one. */ + let go_name = (name: option(Pat.t), m: Map.t) => + switch (name) { + | None => (None, m) + | Some(x) => + let (_, x, m) = go_binder(x, m); + (Some(x), m); + }; + /* The fact name a pattern gives, read through `Pat.bound_vars` as + `ProofCheck.name_or` reads it, so a name wrapped in `Parens`/`Asc` + still resolves. */ + let fact_name = (x: Pat.t): option(Var.t) => + switch (Pat.bound_vars(x)) { + | [h] => Some(h) + | _ => None + }; + let with_fact = (~ctx=ctx, name: Var.t, ~id: Id.t, prop: Exp.t): Ctx.t => + Ctx.extend_theorem( + ctx, + { + name, + id, + prop: Some(prop), + }, + ); + /* `ctx` with `name` bound to a placeholder variable, for walking a name + that isn't a program variable without marking it `Free`. */ + let with_placeholder = (~ctx=ctx, name: Var.t): Ctx.t => + Ctx.extend( + ctx, + VarEntry({ + name, + id: Id.invalid, + typ: Unknown(Internal) |> Typ.temp, + custom_statics: None, + }), + ); + let rec unwrap_head = (e: Exp.t): Exp.t => + switch (e.term) { + | Parens(inner) + | Projector(_, inner) => unwrap_head(inner) + | _ => e + }; + /* A slot that cites a fact, when it holds a bare name `h`. The name + belongs to the theorem namespace, so it is walked as a placeholder if + a fact has it, and is marked `FreeHypothesis` if not. Returns the + cited fact. None when the slot isn't a bare name. */ + let go_fact_name = + (e: Exp.t, m: Map.t) + : option((option(Ctx.theorem_entry), Exp.t, Map.t)) => { + let head = unwrap_head(e); + switch (head.term) { + | Var(name) => + let fact = Ctx.lookup_theorem(ctx, name); + let (_, e, m) = + switch (fact) { + | Some(_) => go_exp(~ctx=with_placeholder(name), e, m) + | None => go_exp(e, m) + }; + let m = + switch (fact, Id.Map.find_opt(IdTagged.rep_id(head), m)) { + | (None, Some(InfoExp(info))) => + let marks = + List.map( + ~f= + fun + | Mark.Free(_) => Mark.FreeHypothesis(name) + | mark => mark, + info.marks, + ); + add_info( + [IdTagged.rep_id(head)], + InfoExp({ + ...info, + marks, + }), + m, + ); + | _ => m + }; + Some((fact, e, m)); + | _ => None + }; + }; + /* `with = `, where `` names a binder of the proposition + `prop` being cited, not a program variable, so it is walked as a + placeholder; the checker reports an unknown binder + (`ProofMark.UnknownInstantiationVar`). `` analyzes against the + binder's type when `prop` ascribes one, and otherwise synthesizes: a + missing ascription is not an error here, since the checker decides + whether the citation makes sense. */ + let go_binder_instantiation = + (~prop: option(Exp.t), instantiation: option((Exp.t, Exp.t)), m) => { + /* The ascribed type of the binder `x` among `prop`'s outer `forall` + binders. */ + let rec binder_typ_in_pat = (x: Var.t, pat: Pat.t): option(Typ.t) => + switch (pat.term) { + | Parens(p1) => binder_typ_in_pat(x, p1) + | Asc(p1, ty) => + switch (p1.term) { + | Var(y) when String.equal(y, x) => Some(ty) + | Parens(_) => binder_typ_in_pat(x, p1) + | _ => None + } + | _ => None + }; + let rec binder_typ_in_prop = (x: Var.t, prop: Exp.t): option(Typ.t) => + switch (prop.term) { + | Parens(e1) => binder_typ_in_prop(x, e1) + | Forall(pat, body) => + switch (binder_typ_in_pat(x, pat)) { + | Some(_) as found => found + | None => binder_typ_in_prop(x, body) + } + | _ => None + }; + switch (instantiation) { + | None => (None, m) + | Some((var, inst)) => + let binder = + switch (unwrap_head(var).term) { + | Var(name) => Some(name) + | _ => None + }; + let (_, var, m) = + switch (binder) { + | Some(name) => go_exp(~ctx=with_placeholder(name), var, m) + | None => go_exp(var, m) + }; + let ana = + switch (binder, prop) { + | (Some(x), Some(prop)) => binder_typ_in_prop(x, prop) + | _ => None + }; + let (_, inst, m) = go_exp(~ana?, inst, m); + (Some((var, inst)), m); + }; + }; + /* `cases` or `induction`. Synthesize the scrutinee's type, analyze each + pattern against it, then check each case body with the pattern's + bindings in scope. Coverage flags inexhaustive and redundant cases; + whether each body is a complete proof is the checker's job. + `case_eq_name` is the name of a `cases` split's case equation, and + `None` for `induction`. */ + let go_split = (~case_eq_name: option(Var.t), scrut, cases, m) => { + let (scrut_info, scrut, m) = go_exp(scrut, m); + let (ps, bodies) = List.unzip(cases); + let (pats, m) = + map_m( + (p, m) => { + let (info, p, m) = go_binder(~ana=scrut_info.ty, p, m); + ((info, p), m); + }, + ps, + m, + ); + /* Each case body sees the facts `ProofCheck.check_split` installs, + so a name shadows as it does there. A `cases` case gets the case + equation `scrut == pat`, absent when the pattern rebinds a variable + of the scrutinee. An `induction` case loses the facts that mention + the scrutinee and gets an `ih_` per recursive position: the + goal at the induction with that position in place of the + scrutinee. The statics don't track the goal, so an inductive + hypothesis's statement is left unknown. */ + let body_ctx = ((info: Info.pat, pat: Pat.t)) => { + let id = IdTagged.rep_id(pat); + switch (case_eq_name) { + | Some(name) => + CoCtx.has_any( + scrut_info.co_ctx, + pat |> Pat.bindings |> Binding.variable_names, + ) + ? info.ctx + : with_fact( + ~ctx=info.ctx, + name, + ~id, + Exp.fresh(BinOp(Poly(Equals), scrut, Exp.of_pat(pat))), + ) + | None => + List.fold_left( + ~f= + (case_ctx, h) => + Ctx.extend_theorem( + case_ctx, + { + name: Induction.hypothesis_name(h), + id, + prop: None, + }, + ), + ~init=Ctx.forget_facts(Induction.mentions(scrut), info.ctx), + Induction.hypotheses( + ProofStatics.of_info_map(m), + Typ.normalize(ctx, scrut_info.ty), + pat, + ), + ) + }; + }; + let (bodies, m) = + map_m2( + (ctx, body, m) => go(~ctx, body, m), + List.map(~f=body_ctx, pats), + bodies, + m, + ); + /* Unlike an expression `case`, a split must be exhaustive to be + valid, so inexhaustiveness is an error. The scrutinee is often a + bare `forall`-bound variable with no annotation (type `Unknown`), + which coverage treats as vacuously covered; so the coverage type is + refined from the case patterns (`[]` reveals `List`). A zero-case + split proves nothing and is always inexhaustive. */ + let pat_infos = List.map(~f=fst, pats); + let normalized_scrut_ty = Typ.normalize(ctx, scrut_info.ty); + let coverage_ty = + switch (Typ.term_of(normalized_scrut_ty)) { + | Unknown(_) => + pat_infos + |> List.map(~f=(pi: Info.pat) => Typ.normalize(ctx, pi.ty)) + |> List.find(~f=t => + switch (Typ.term_of(t)) { + | Unknown(_) => false + | _ => true + } + ) + |> Option.value(~default=normalized_scrut_ty) + | _ => normalized_scrut_ty + }; + let Coverage.CheckMatrix.{exhaustiveness, redundant_rows} = + Coverage.check( + List.map(~f=Info.pat_constraint, pat_infos), + coverage_ty, + ); + /* The mark goes on the split's own form, not the scrutinee. */ + let marks = + switch (cases, exhaustiveness) { + | ([], Exhaustive) => [ + Mark.InexhaustiveMatch( + scrut_info.ty, + [], + Grammar.Pat(Pat.fresh(Wild)), + ), + ] + | (_, Exhaustive) => [] + | (_, Inexhaustive(unseen_pattern)) => [ + Mark.InexhaustiveMatch(scrut_info.ty, [], unseen_pattern), + ] + }; + let m = + List.fold_left( + ~f= + (m, row) => { + let p = List.nth_exn(ps, row); + switch (Id.Map.find_opt(IdTagged.rep_id(p), m)) { + | Some(Info.InfoPat(info)) => + let info = + prepend_pat_mark(info, Mark.Redundant, ~warnings=[], ()); + add_info(IdTagged.ids(p), InfoPat(info), m); + | _ => m + }; + }, + ~init=m, + redundant_rows, + ); + (scrut, List.zip_exn(List.map(~f=snd, pats), bodies), marks, m); + }; + switch (p_term.term) { + | Invalid(_) + | EmptyHole => add(p_term.term, m) + | MultiHole(tms) => + let (_, _, m) = multi(~ctx, ~ancestors=ancestors_inclusive, m, tms); + add(p_term.term, m); + | Seq(p1, p2) => + let (p1, m) = go(p1, m); + let (p2, m) = go(p2, m); + add(Seq(p1, p2), m); + | Parens(p) => + let (p, m) = go(p, m); + add(Parens(p), m); + | AxiomStep({direction, equality, instantiation}) => + /* The equality slot names a fact; it can't be an arbitrary + expression. */ + let (cited, equality_elab, m) = + switch (go_fact_name(equality, m)) { + | Some(walked) => walked + | None => + let (info, elab, m) = go_exp(equality, m); + let info = { + ...info, + marks: [ + Mark.AxiomSlotNotHypothesis(Exp(equality)), + ...info.marks, + ], + }; + ( + None, + elab, + add_info([IdTagged.rep_id(equality)], InfoExp(info), m), + ); + }; + let (instantiation, m) = + go_binder_instantiation( + ~prop=Option.bind(cited, ~f=(fact: Ctx.theorem_entry) => fact.prop), + instantiation, + m, + ); + add( + AxiomStep({ + direction, + equality: equality_elab, + instantiation, + }), + m, + ); + | AlgebriteStep(replacement) => + let (_, replacement, m) = go_exp(replacement, m); + add(AlgebriteStep(replacement), m); + | EvalStep => add(EvalStep, m) + | Focus({ordinal, selector, body}) => + /* The selector is a pattern over the goal. Its `$e`/`$v`/`$x` + metavariables (`MetaVar`) must not read as free variables, which + `is_in_filter` gives any metavariable-bearing pattern. It may also + name variables the goal binds (`x` under a `fun x ->`), which the + ctx doesn't have, so a name the ctx lacks is walked as a + placeholder; a selector that matches nothing is the checker's to + report. The body is walked with those names too, since the checker + binds the goal's binders around the target in it. A binder the + selector doesn't name stays unknown here. */ + let names = ref([]); + let _: Exp.t = + Exp.map_term( + ~f_exp= + (continue, e) => { + switch (e.term) { + | Var(x) + when + Option.is_none(Ctx.lookup_var(ctx, x)) + && !MetaVar.is_meta_name(x) => + names := [x, ...names^] + | _ => () + }; + continue(e); + }, + selector, + ); + let selector_ctx = + List.fold_left( + ~f=(ctx, name) => with_placeholder(~ctx, name), + ~init=ctx, + names^, + ); + let (_, selector, m) = + go_exp(~ctx=selector_ctx, ~is_in_filter=true, selector, m); + let (body, m) = go(~ctx=selector_ctx, body, m); + add( + Focus({ + ordinal, + selector, + body, + }), + m, + ); + | Cases(scrut, cases) => + let (scrut, cases, marks, m) = + go_split(~case_eq_name=Some("case_eq"), scrut, cases, m); + add(~marks, Cases(scrut, cases), m); + | Induction(scrut, cases) => + let (scrut, cases, marks, m) = + go_split(~case_eq_name=None, scrut, cases, m); + add(~marks, Induction(scrut, cases), m); + | Forall(pat, body) => + /* The binders enter the variable namespace. */ + let (pat_info, pat, m) = go_binder(pat, m); + let (body, m) = go(~ctx=pat_info.ctx, body, m); + add(Forall(pat, body), m); + | Funext(pat, body) => + /* The binder names the argument of the pointwise goal `f(x) == g(x)` + the checker builds. */ + let (pat_info, pat, m) = go_binder(pat, m); + let (body, m) = go(~ctx=pat_info.ctx, body, m); + add(Funext(pat, body), m); + | Assume(e, name, body) => + let (e_elab, m) = go_prop(e, m); + let (name, m) = go_name(name, m); + /* The body can cite the assumption under the name the checker uses + (`assume` unless named). The name is fixed, so a nested `assume` + shadows the outer one. Only the theorem namespace is extended: an + assumption is not a value. */ + let fact = + Option.bind(name, ~f=fact_name) |> Option.value(~default="assume"); + let (body, m) = + go(~ctx=with_fact(fact, ~id=IdTagged.rep_id(p_term), e), body, m); + add(Assume(e_elab, name, body), m); + | Alias(x, e, body) => + /* `alias = => ` names a fact already in scope, + given by name or as a proposition (the checker matches it against + the facts in scope). The body sees the fact under , with the + statement as written, or, for a name, that fact's statement. */ + let (_, x_elab, m) = go_binder(x, m); + let (e_elab, aliased, m) = + switch (go_fact_name(e, m)) { + | Some((Some({prop: Some(prop), _}), e, m)) => (e, prop, m) + | Some((_, e, m)) => (e, e, m) + | None => + let (e, m) = go_prop(e, m); + (e, e, m); + }; + let body_ctx = + switch (fact_name(x_elab)) { + | Some(h) => with_fact(h, ~id=IdTagged.rep_id(x), aliased) + | None => ctx + }; + let (body, m) = go(~ctx=body_ctx, body, m); + add(Alias(x_elab, e_elab, body), m); + | Generalize(e, body) => + /* `generalize x => body` re-quantifies the in-scope variable `x` + (the checker rejects anything else with + `ProofMark.MalformedGeneralize`). The new quantifier rebinds `x` at + the same type, so `x` stays in the body's ctx, but the facts about + the old `x` don't, as in the checker. */ + let body_ctx = + switch (ProofSyntax.exp_to_name(e)) { + | Some(x) => Ctx.forget_facts(Exp.occurs_free_any([x]), ctx) + | None => ctx + }; + let (_, e, m) = go_exp(e, m); + let (body, m) = go(~ctx=body_ctx, body, m); + add(Generalize(e, body), m); + | Revert(e, instantiation, body) => + /* `revert F => body` moves the in-scope fact `F`, given by name or as + a proposition, back into the goal. The body is checked in the + unchanged ctx: `F` stays citable and nothing new is bound. */ + let (e_elab, m) = + switch (go_fact_name(e, m)) { + | Some((_, e, m)) => (e, m) + | None => go_prop(e, m) + }; + let (instantiation, m) = + go_binder_instantiation(~prop=Some(e), instantiation, m); + let (body, m) = go(body, m); + add(Revert(e_elab, instantiation, body), m); + | Have(e, name, sub, body) => + /* `have proof => `. The subproof proves + ``, so it is checked without it in scope; the body can cite it + under the name the checker uses (`have` unless named). */ + let (e_elab, m) = go_prop(e, m); + let (name, m) = go_name(name, m); + let fact = + Option.bind(name, ~f=fact_name) |> Option.value(~default="have"); + let (sub, m) = go(sub, m); + let (body, m) = + go(~ctx=with_fact(fact, ~id=IdTagged.rep_id(p_term), e), body, m); + add(Have(e_elab, name, sub, body), m); + }; }; +/* The built-in axioms every program can cite. Their statements are rules + in `Axioms.axioms`, hence `prop: None`. The names are copied rather than + read from there because `Axioms` depends on this module (through + `ProofCtx` and `ProofRule`); keep the two in sync. */ +let initial_theorems: list(Ctx.theorem_entry) = + [ + "refl", + "impl_def", + "and_comm", + "or_comm", + "and_assoc", + "or_assoc", + "demorgan_and", + "demorgan_or", + "and_true", + "and_false", + "or_true", + "or_false", + "not_not", + "impl_true", + "true_impl", + "false_impl", + /* Closure lemmas. */ + "nonzero_mul", + "nonzero_of_pos", + "nonzero_of_neg", + "pos_mul", + "pos_add", + "pow_pos", + /* Nat. */ + "nat_succ_ne_zero", + "nat_add_sub", + ] + |> List.map(~f=name => + Ctx.{ + name, + id: Id.mk_str(name), + prop: None, + } + ); + let mk = Core.Memo.general( ~cache_size_bound=1000, - ((ana, ctx, e, probe_ids)) => { + ((ana, ctx, e, probe_ids, in_theorem)) => { + let ctx = + List.fold_left(~f=Ctx.extend_theorem, ~init=ctx, initial_theorems); let (_, elab, m) = uexp_to_info_map( ~ana, ~ctx, ~ancestors=[], ~probe_ids, + ~in_theorem, e, Id.Map.empty, ); @@ -4426,9 +5115,11 @@ let mk = ( ~ana=Typ.temp(Unknown(SynSwitch)), ~probe_ids=Id.Map.empty, + ~in_theorem=false, core: CoreSettings.t, ctx, exp, ) => core.statics - ? mk((ana, ctx, exp, probe_ids)) : (Id.Map.empty, Exp.fresh(Tuple([]))); + ? mk((ana, ctx, exp, probe_ids, in_theorem)) + : (Id.Map.empty, Exp.fresh(Tuple([]))); diff --git a/src/language/statics/Warning.re b/src/language/statics/Warning.re index 961c199bd0..cbb6133ba4 100644 --- a/src/language/statics/Warning.re +++ b/src/language/statics/Warning.re @@ -10,11 +10,21 @@ type warning_typ = /* A type defined as itself: no value has it. */ | NonContractive(string); +/* Expression forms that have no evaluation semantics. These are legal + propositions, so they are warnings rather than marks: they only mean + "this will not run" when written outside a theorem statement or + proof. */ +[@deriving (show({with_path: false}), sexp, yojson, eq)] +type warning_exp = + /* `forall` / `forall ... where ...` used as ordinary code. */ + | ForallOutsideTheorem; + [@deriving (show({with_path: false}), sexp, yojson, eq)] type list_item = | Pat(warning_pat) | TPat(warning_typ) - | Typ(warning_typ); + | Typ(warning_typ) + | Exp(warning_exp); /* The warnings for binding type alias [name] to [def]. */ let type_binding = (name, def: Typ.alias_def): list(list_item) => diff --git a/src/language/term/Abbreviate.re b/src/language/term/Abbreviate.re index 0318b70afe..93d3853ecc 100644 --- a/src/language/term/Abbreviate.re +++ b/src/language/term/Abbreviate.re @@ -858,7 +858,7 @@ let rec abbreviate_exp = (exp: Exp.t): Exp.t => { Let(p', e1', e2'); } - | Theorem(p, e1, e2) => + | Theorem(p, e1, pf, e2) => if (available^ < 3) { available := available^ - ellipsis_cost; Invalid(flat_ellipses); @@ -875,8 +875,8 @@ let rec abbreviate_exp = (exp: Exp.t): Exp.t => { available := available^ - 11; Invalid("theorem…in…"); } else { - /* Full: "theorem " (8) + p + " = " (3) + e1 + " in " (4) + e2 */ - available := available^ - 15; + /* Full: "theorem " (8) + p + " = " (3) + e1 + " proof " (7) + pf + " in " (4) + e2 */ + available := available^ - 22; let pool = available^; let budgets = AbbrevBudget.split_evenly(~total=pool, ~parts=3); let (p', _) = @@ -894,23 +894,7 @@ let rec abbreviate_exp = (exp: Exp.t): Exp.t => { ~budget=List.nth_exn(budgets, 2), ~run=() => abbreviate_exp(e2) ); - Theorem(p', e1', e2'); - } - - | ProofObject(t) => - if (available^ < 8) { - available := available^ - ellipsis_cost; - Invalid(flat_ellipses); - } else if (available^ <= 12) { - Invalid("proof_object"); - } else if (available^ <= 13) { - Invalid("proof_object…"); - } else if (available^ <= 18) { - Invalid("proof_object…end"); - } else { - available := available^ - 16; - let t' = abbreviate_exp(t); - ProofObject(t'); + Theorem(p', e1', pf, e2'); } | Use(t1, e1) => @@ -1527,16 +1511,6 @@ and abbreviate_typ = (typ: Typ.t): Typ.t => { }; }; - let handle_unary = - (~cost: int, ~make_term: Exp.t => Typ.term, t: Exp.t): Typ.term => - if (available^ <= cost) { - available := available^ - 1; - indet_term_typ; - } else { - available := available^ - cost; - make_term(abbreviate_exp(t)); - }; - let term: Typ.term = switch (typ |> Typ.term_of) { | Unknown(prov) => Unknown(prov) @@ -1727,12 +1701,6 @@ and abbreviate_typ = (typ: Typ.t): Typ.t => { ); }; } - | ProofOf(e) => - handle_unary( - ~cost=13, // "proof_of " + " end" - ~make_term=e' => ProofOf(e'), - e, - ) | Projector(data, t) => Projector(data, abbreviate_typ(t)) | Sig(items) => if (available^ <= 2) { @@ -1804,9 +1772,11 @@ and abbreviate_any = (any: Any.t): Any.t => | TPat(tp) => TPat(abbreviate_tpat(tp)) | Rul(_) => any | Drv(_) => any + | PRul(_) => any | Mod(m) => Mod(abbreviate_mod_item(m)) | Sig(s) => Sig(abbreviate_sig_item(s)) | MPat(mp) => MPat(abbreviate_mpat(mp)) + | Proof(_) => any | Any(_) => any }; diff --git a/src/language/term/Any.re b/src/language/term/Any.re index b2c4e5aed5..93292c0825 100644 --- a/src/language/term/Any.re +++ b/src/language/term/Any.re @@ -52,9 +52,11 @@ let rec ids: TermBase.any_t => list(Id.t) = | TPat(tm) => IdTagged.ids(tm) | Rul(tm) => Rul.ids(~any_ids=ids, tm) | Drv(tm) => Drv.Any.ids(tm) + | PRul(tm) => PRul.ids(~any_ids=ids, tm) | Mod(tm) => IdTagged.ids(tm) | Sig(tm) => IdTagged.ids(tm) | MPat(tm) => IdTagged.ids(tm) + | Proof(tm) => IdTagged.ids(tm) | Any () => []; // Terms may consist of multiple tiles, eg the commas in an n-tuple, @@ -76,7 +78,9 @@ let rep_id = | TPat(tm) => TPat.rep_id(tm) | Rul(tm) => Rul.rep_id(~any_ids=ids, tm) | Drv(tm) => Drv.Any.rep_id(tm) + | PRul(tm) => PRul.rep_id(~any_ids=ids, tm) | Mod(tm) => IdTagged.rep_id(tm) | Sig(tm) => IdTagged.rep_id(tm) | MPat(tm) => IdTagged.rep_id(tm) + | Proof(tm) => IdTagged.rep_id(tm) | Any () => raise(Invalid_argument("Term.rep_id")); diff --git a/src/language/term/Atom.re b/src/language/term/Atom.re index e05e25d2c5..434d6d9024 100644 --- a/src/language/term/Atom.re +++ b/src/language/term/Atom.re @@ -159,11 +159,20 @@ let convert = | (Nat, String) => Ok(Bigint.to_string(v)) | (Float, Float) => Ok(v) - | (Float, SInt) => Ok(int_of_float(v)) - | (Float, Int) => Ok(Bigint.of_float(v)) + | (Float, SInt) => + Float.is_finite(v) + ? Ok(int_of_float(v)) : Error(InvalidOperationError.NonFiniteFloat) + | (Float, Int) => + Float.is_finite(v) + ? Ok(Bigint.of_float(v)) : Error(InvalidOperationError.NonFiniteFloat) | (Float, Nat) => - Float.(v < 0.0) - ? Error(InvalidOperationError.NegativeNat) : Ok(Bigint.of_float(v)) + if (!Float.is_finite(v)) { + Error(InvalidOperationError.NonFiniteFloat); + } else if (Float.(v < 0.0)) { + Error(InvalidOperationError.NegativeNat); + } else { + Ok(Bigint.of_float(v)); + } | (Float, Bool) => Ok(!Float.equal(v, 0.0)) | (Float, String) => Ok(string_of_float(v)) diff --git a/src/language/term/Cls.re b/src/language/term/Cls.re index 9e89596068..3c12eab87a 100644 --- a/src/language/term/Cls.re +++ b/src/language/term/Cls.re @@ -6,10 +6,12 @@ type t = | Typ(Typ.cls) | TPat(TPat.cls) | Rul(Rul.cls) + | PRul(PRul.cls) | Secondary(Secondary.cls) | Mod(Mod.cls) | Sig(Sig.cls) - | MPat(MPat.cls); + | MPat(MPat.cls) + | Proof(Proof.cls); let show = (cls: t) => switch (cls) { @@ -19,8 +21,10 @@ let show = (cls: t) => | Typ(cls) => Typ.show_cls(cls) | TPat(cls) => TPat.show_cls(cls) | Rul(cls) => Rul.show_cls(cls) + | PRul(cls) => PRul.show_cls(cls) | Secondary(cls) => Secondary.show_cls(cls) | Mod(cls) => Mod.show_cls(cls) | Sig(cls) => Sig.show_cls(cls) | MPat(cls) => MPat.show_cls(cls) + | Proof(cls) => Proof.show_cls(cls) }; diff --git a/src/language/term/Equality.re b/src/language/term/Equality.re index 239f684c52..452ba03d96 100644 --- a/src/language/term/Equality.re +++ b/src/language/term/Equality.re @@ -37,6 +37,7 @@ type equality = { mod_: (TermBase.Mod.t, TermBase.Mod.t) => bool, sig_: (TermBase.Sig.t, TermBase.Sig.t) => bool, mpat: (TermBase.MPat.t, TermBase.MPat.t) => bool, + proof: (TermBase.Proof.t, TermBase.Proof.t) => bool, any: (Any.t, Any.t) => bool, }; @@ -278,14 +279,15 @@ let equality = | None => false } | (Let(_, _, _), _) => false - | (Theorem(p1, e1, e2), Theorem(p2, e3, e4)) => + | (Theorem(p1, e1, pf1, e2), Theorem(p2, e3, pf2, e4)) => switch (pat'(p1, p2)) { | Some(alphas_exp') => exp(alphas_exp, alphas_typ, e1, e3) + && proof(alphas_exp, alphas_typ, pf1, pf2) && exp(Alphas.combine(alphas_exp', alphas_exp), alphas_typ, e2, e4) | None => false } - | (Theorem(_, _, _), _) => false + | (Theorem(_, _, _, _), _) => false // Forms with type binders | (TypFun(tp1, e1, _), TypFun(tp2, e2, _)) => @@ -420,8 +422,6 @@ let equality = | (ListConcat(e11, e12), ListConcat(e21, e22)) => exp'(e11, e21) && exp'(e12, e22) | (ListConcat(_, _), _) => false - | (ProofObject(e1), ProofObject(e2)) => exp'(e1, e2) - | (ProofObject(_), _) => false | (Module(items1), Module(items2)) => List.length(items1) == List.length(items2) && List.for_all2_exn(items1, items2, ~f=mod') @@ -627,7 +627,6 @@ let equality = (alphas_exp: Alphas.t, alphas_typ: Alphas.t, t1: Typ.t, t2: Typ.t): bool => { // This function takes alphas_exp for the theorem keyword branches which have expressions in types. let any' = any(alphas_exp, alphas_typ); - let exp' = exp(alphas_exp, alphas_typ); let typ' = typ(alphas_exp, alphas_typ); let tpat' = tpat; switch (t1 |> Annotated.term_of, t2 |> Annotated.term_of) { @@ -718,8 +717,6 @@ let equality = | (ProdExtension(t1, t2), ProdExtension(t1', t2')) => typ'(t1, t1') && typ'(t2, t2') | (ProdExtension(_), _) => false - | (ProofOf(e1), ProofOf(e2)) => exp'(e1, e2) - | (ProofOf(_), _) => false | (Sig(items1), Sig(items2)) => List.length(items1) == List.length(items2) && List.for_all2_exn(items1, items2, ~f=sig_(alphas_exp, alphas_typ)) @@ -850,6 +847,34 @@ let equality = | (MultiHole(_), _) => false }; } + and prul = + (alphas_exp: Alphas.t, alphas_typ: Alphas.t, r1: PRul.t, r2: PRul.t) + : bool => { + let pat' = pat(alphas_exp, alphas_typ); + let exp' = exp(alphas_exp, alphas_typ); + let proof' = proof(alphas_exp, alphas_typ); + switch (r1 |> Annotated.term_of, r2 |> Annotated.term_of) { + | (ProofRules(e1, rls1), ProofRules(e2, rls2)) + when List.length(rls1) == List.length(rls2) => + exp'(e1, e2) + && List.for_all2_exn(rls1, rls2, ~f=((p1, b1), (p2, b2)) => + Option.is_some(pat'(p1, p2)) && proof'(b1, b2) + ) + | (ProofRules(_, _), _) => false + + | (MultiHole(_) | Invalid(_), MultiHole(_) | Invalid(_)) + when ignore_unknown_provenance => + true + | (Invalid(s1), Invalid(s2)) => s1 == s2 + | (Invalid(_), _) => false + | (MultiHole(xs1), MultiHole(xs2)) + when + List.length(xs1) == List.length(xs2) + && List.equal((_, _) => true, xs1, xs2) => + true + | (MultiHole(_), _) => false + }; + } and filter = ( alphas_exp: Alphas.t, @@ -888,11 +913,119 @@ let equality = | (MPat(mp1), MPat(mp2)) => mpat(alphas_exp, alphas_typ, mp1, mp2) |> Option.is_some | (MPat(_), _) => false + | (Proof(p1), Proof(p2)) => proof(alphas_exp, alphas_typ, p1, p2) + | (Proof(_), _) => false + | (PRul(r1), PRul(r2)) => prul(alphas_exp, alphas_typ, r1, r2) + | (PRul(_), _) => false | (Any (), Any ()) => true | (Any (), _) => false | (Drv(d1), Drv(d2)) => d1 == d2 | (Drv(_), _) => false }; + } + and proof = + ( + alphas_exp: Alphas.t, + alphas_typ: Alphas.t, + p1: TermBase.Proof.t, + p2: TermBase.Proof.t, + ) + : bool => { + let exp' = exp(alphas_exp, alphas_typ); + let pat' = pat(alphas_exp, alphas_typ); + let any' = any(alphas_exp, alphas_typ); + /* Optional `with = ` clauses. */ + let inst' = + ( + n1: option((TermBase.Exp.t, TermBase.Exp.t)), + n2: option((TermBase.Exp.t, TermBase.Exp.t)), + ) + : bool => + switch (n1, n2) { + | (None, None) => true + | (Some((v1, i1)), Some((v2, i2))) => exp'(v1, v2) && exp'(i1, i2) + | (None, Some(_)) + | (Some(_), None) => false + }; + /* Optional fact names. */ + let name' = + (a1: option(TermBase.Pat.t), a2: option(TermBase.Pat.t)): bool => + switch (a1, a2) { + | (None, None) => true + | (Some(x1), Some(x2)) => Option.is_some(pat'(x1, x2)) + | (None, Some(_)) + | (Some(_), None) => false + }; + let rec proof' = (p1: TermBase.Proof.t, p2: TermBase.Proof.t): bool => + switch (p1 |> Annotated.term_of, p2 |> Annotated.term_of) { + // Wrappers when ignored: unwrap. These cases must come first. + | (Parens(x), _) when ignore_parens => proof'(x, p2) + | (_, Parens(x)) when ignore_parens => proof'(p1, x) + | (Parens(x), Parens(y)) => proof'(x, y) + | (Parens(_), _) => false + | (EmptyHole, EmptyHole) => true + | (EmptyHole, _) => false + | (Invalid(s1), Invalid(s2)) => s1 == s2 + | (Invalid(_), _) => false + | (MultiHole(xs1), MultiHole(xs2)) => + List.length(xs1) == List.length(xs2) + && List.for_all2_exn(xs1, xs2, ~f=any') + | (MultiHole(_), _) => false + | (Seq(a1, a2), Seq(b1, b2)) => proof'(a1, b1) && proof'(a2, b2) + | (Seq(_, _), _) => false + | ( + AxiomStep({direction: d1, equality: q1, instantiation: n1}), + AxiomStep({direction: d2, equality: q2, instantiation: n2}), + ) => + d1 == d2 && exp'(q1, q2) && inst'(n1, n2) + | (AxiomStep(_), _) => false + | (AlgebriteStep(w1), AlgebriteStep(w2)) => exp'(w1, w2) + | (AlgebriteStep(_), _) => false + | (EvalStep, EvalStep) => true + | (EvalStep, _) => false + | ( + Focus({ordinal: o1, selector: s1, body: b1}), + Focus({ordinal: o2, selector: s2, body: b2}), + ) => + Option.map(~f=Annotated.term_of, o1) + == Option.map(~f=Annotated.term_of, o2) + && exp'(s1, s2) + && proof'(b1, b2) + | (Focus(_), _) => false + | (Cases(e1, cs1), Cases(e2, cs2)) => + exp'(e1, e2) && cases'(cs1, cs2) + | (Cases(_, _), _) => false + | (Induction(e1, cs1), Induction(e2, cs2)) => + exp'(e1, e2) && cases'(cs1, cs2) + | (Induction(_, _), _) => false + | (Forall(x1, b1), Forall(x2, b2)) => + Option.is_some(pat'(x1, x2)) && proof'(b1, b2) + | (Forall(_, _), _) => false + | (Funext(x1, b1), Funext(x2, b2)) => + Option.is_some(pat'(x1, x2)) && proof'(b1, b2) + | (Funext(_, _), _) => false + | (Assume(e1, a1, b1), Assume(e2, a2, b2)) => + exp'(e1, e2) && name'(a1, a2) && proof'(b1, b2) + | (Assume(_, _, _), _) => false + | (Alias(x1, e1, b1), Alias(x2, e2, b2)) => + Option.is_some(pat'(x1, x2)) && exp'(e1, e2) && proof'(b1, b2) + | (Alias(_, _, _), _) => false + | (Generalize(e1, b1), Generalize(e2, b2)) => + exp'(e1, e2) && proof'(b1, b2) + | (Generalize(_, _), _) => false + | (Revert(e1, n1, b1), Revert(e2, n2, b2)) => + exp'(e1, e2) && inst'(n1, n2) && proof'(b1, b2) + | (Revert(_, _, _), _) => false + | (Have(e1, a1, s1, b1), Have(e2, a2, s2, b2)) => + exp'(e1, e2) && name'(a1, a2) && proof'(s1, s2) && proof'(b1, b2) + | (Have(_, _, _, _), _) => false + } + and cases' = (cs1, cs2) => + List.length(cs1) == List.length(cs2) + && List.for_all2_exn(cs1, cs2, ~f=((pa, ba), (pb, bb)) => + Option.is_some(pat'(pa, pb)) && proof'(ba, bb) + ); + proof'(p1, p2); }; { @@ -906,6 +1039,7 @@ let equality = sig_: (s1, s2) => sig_(Alphas.empty, Alphas.empty, s1, s2), mpat: (mp1, mp2) => mpat(Alphas.empty, Alphas.empty, mp1, mp2) |> Option.is_some, + proof: proof(Alphas.empty, Alphas.empty), any: any(Alphas.empty, Alphas.empty), }; }; diff --git a/src/language/term/Exp.re b/src/language/term/Exp.re index 76463ee6ef..a9ad1d017b 100644 --- a/src/language/term/Exp.re +++ b/src/language/term/Exp.re @@ -21,7 +21,6 @@ type cls = | Var | Let | Theorem - | ProofObject | Forall | FixF | TyAlias @@ -156,7 +155,6 @@ let rec strip_wrappers = (e: t): t => | Var(_) | Let(_) | Theorem(_) - | ProofObject(_) | Forall(_) | FixF(_) | TyAlias(_) @@ -205,7 +203,6 @@ let rec cls_of_term: type a. Grammar.exp_term(a) => cls = | Var(_) => Var | Let(_) => Let | Theorem(_) => Theorem - | ProofObject(_) => ProofObject | Forall(_) => Forall | FixF(_) => FixF | TyAlias(_) => TyAlias @@ -266,7 +263,6 @@ let show_cls: cls => string = | Var => "Variable reference" | Let => "Let expression" | Theorem => "Theorem expression" - | ProofObject => "Proof placeholder" | Forall => "Forall expression" | FixF => "Fixpoint operator" | TyAlias => "Type Alias definition" @@ -325,7 +321,6 @@ let rec match_tup_label: t => option((LabeledTuple.label, t)) = { | Var(_) | Let(_) | Theorem(_) - | ProofObject(_) | Forall(_) | FixF(_) | TyAlias(_) @@ -396,7 +391,6 @@ let rec is_fun = (e: t) => { | Var(_) | Let(_) | Theorem(_) - | ProofObject(_) | Forall(_) | FixF(_) | TyAlias(_) @@ -455,7 +449,6 @@ let rec is_tuple_of_functions = (e: t) => | Var(_) | Let(_) | Theorem(_) - | ProofObject(_) | Forall(_) | FixF(_) | TyAlias(_) @@ -505,7 +498,6 @@ let rec ctr_name = (e: t): option(Constructor.t) => | Var(_) | Let(_) | Theorem(_) - | ProofObject(_) | Forall(_) | FixF(_) | TyAlias(_) @@ -568,7 +560,6 @@ let rec get_num_of_functions = (e: t) => | Var(_) | Let(_) | Theorem(_) - | ProofObject(_) | Forall(_) | Filter(_) | TyAlias(_) @@ -656,7 +647,6 @@ let rec get_fn_name = (e: t) => { | Var(_) | Let(_) | Theorem(_) - | ProofObject(_) | Forall(_) | TyAlias(_) | Use(_) @@ -712,7 +702,6 @@ let rec map_fn_name = (f: option(Var.t) => option(Var.t), e: t): t => { | Var(_) | Let(_) | Theorem(_) - | ProofObject(_) | Forall(_) | TyAlias(_) | Use(_) @@ -776,3 +765,95 @@ let find_by_id = (id: Id.t, exp: t): option(t) => { let add_name = (name: option(string), exp: t): t => { map_fn_name(_ => name, exp); }; + +/* Read a pattern as an expression, so that the statics and the checker + * build a split's case equation `scrut == pat` the same way. It lives here because `Pat` can't depend on `Exp`. + * + * `Wild` has no expression counterpart; it becomes `true`, which is what + * a wildcard case's equation degenerates to. */ +let rec of_pat = (pat: Pat.t): t => { + let term = pat |> Pat.term_of; + let rewrap: term => t = + term => { + term, + annotation: pat.annotation, + }; + switch (term) { + | Invalid(x) => rewrap(Invalid(x)) + | EmptyHole => rewrap(EmptyHole) + | MultiHole(xs) => rewrap(MultiHole(xs)) + | Wild => rewrap(Atom(Bool(true))) + | Atom(a) => rewrap(Atom(a)) + | ListLit(xs) => rewrap(ListLit(List.map(~f=of_pat, xs))) + | Constructor(c, t) => rewrap(Constructor(c, t)) + | Cons(e1, e2) => rewrap(Cons(of_pat(e1), of_pat(e2))) + | Var(x) => rewrap(Var(x)) + | Tuple(xs) => rewrap(Tuple(List.map(~f=of_pat, xs))) + | Parens(e) => rewrap(Parens(of_pat(e))) + | Projector(data, e) => rewrap(Projector(data, of_pat(e))) + | Ap(e1, e2) => rewrap(Ap(Forward, of_pat(e1), of_pat(e2))) + | Asc(e, t1) => rewrap(Asc(of_pat(e), t1)) + | Label(l) => rewrap(Label(l)) + | ExplicitNonlabel => rewrap(ExplicitNonlabel) + | TupLabel(l, e) => rewrap(TupLabel(of_pat(l), of_pat(e))) + }; +}; + +/* Does any name in `vs` occur free in `e`, given `bound` already in scope? + * + * Binding structure follows `Substitution.in_exp`, except that, as in + * the statics, `Closure(env, body)` looks only at `body`: expanding `env` + * would inline the whole environment, the blow-up this walk exists to + * avoid. + * + * Non-binding forms fall through to `map_term`'s generic traversal, + * which also walks expressions nested inside patterns (`Asc`) under the + * enclosing scope, as `Substitution.in_pat` does. */ +let occurs_free_any = (~bound: list(Var.t)=[], vs: list(Var.t), e: t): bool => { + let found = ref(false); + let rec f_exp = (bound: list(Var.t), cont, e: t): t => { + if (! found^) { + let under = (bound', es) => List.iter(~f=go(bound'), es); + switch (e |> term_of) { + | Var(x) => + if (List.mem(vs, x, ~equal=String.equal) + && !List.mem(bound, x, ~equal=String.equal)) { + found := true; + } + | Fun(p, body, t, _) => + Option.iter(~f=go_typ(bound), t); + go_pat(bound, p); + under(Pat.bound_vars(p) @ bound, [body]); + | FixF(p, body, _) => + go_pat(bound, p); + under(Pat.bound_vars(p) @ bound, [body]); + | Let(p, def, body) => + go_pat(bound, p); + under(Pat.bound_vars(p) @ bound, [def, body]); + | Theorem(p, stmt, _, body) => + go_pat(bound, p); + under(Pat.bound_vars(p) @ bound, [stmt, body]); + | Forall(p, body) => + go_pat(bound, p); + under(Pat.bound_vars(p) @ bound, [body]); + | Match(scrut, cases) => + go(bound, scrut); + List.iter( + ~f= + ((p, body)) => { + go_pat(bound, p); + under(Pat.bound_vars(p) @ bound, [body]); + }, + cases, + ); + | _ => ignore(cont(e)) + }; + }; + e; + } + and go = (bound, e) => ignore(map_term(~f_exp=f_exp(bound), e)) + and go_pat = (bound, p) => ignore(Pat.map_term(~f_exp=f_exp(bound), p)) + and go_typ = (bound, t) => ignore(Typ.map_term(~f_exp=f_exp(bound), t)); + go(bound, e); + found^; +}; diff --git a/src/language/term/Grammar.re b/src/language/term/Grammar.re index 57cb4f2cdc..cf9de86601 100644 --- a/src/language/term/Grammar.re +++ b/src/language/term/Grammar.re @@ -23,6 +23,8 @@ type any_t('a) = | Mod(mod_t('a)) | Sig(sig_t('a)) | MPat(mpat_t('a)) + | Proof(proof_t('a)) + | PRul(prul_t('a)) | Any(unit) and exp_term('a) = | Invalid(string) @@ -49,8 +51,7 @@ and exp_term('a) = | LivelitName(string) | Var(Var.t) | Let(pat_t('a), exp_t('a), exp_t('a)) - | Theorem(pat_t('a), exp_t('a), exp_t('a)) - | ProofObject(exp_t('a)) + | Theorem(pat_t('a), exp_t('a), proof_t('a), exp_t('a)) | Forall(pat_t('a), exp_t('a)) | FixF(pat_t('a), exp_t('a), option(Environment.t(exp_t('a)))) | TyAlias(tpat_t('a), typ_t('a), exp_t('a)) @@ -112,7 +113,6 @@ and typ_term('a) = | Projector(projector_data, typ_t('a)) | Rec(tpat_t('a), typ_t('a)) | Poly(tpat_t('a), typ_t('a)) - | ProofOf(exp_t('a)) | ProdProjection(typ_t('a), typ_t('a)) | ProdExtension(typ_t('a), typ_t('a)) | Sig(list(sig_t('a))) @@ -128,6 +128,12 @@ and rul_term('a) = | MultiHole(list(any_t('a))) | Rules(exp_t('a), list((pat_t('a), exp_t('a)))) and rul_t('a) = Annotated.t(rul_term('a), 'a) +and prul_term('a) = + | Invalid(string) + | MultiHole(list(any_t('a))) + // Scrutinee + (pattern, proof-body) cases, as the child of `induction`. + | ProofRules(exp_t('a), list((pat_t('a), proof_t('a)))) +and prul_t('a) = Annotated.t(prul_term('a), 'a) and mod_term('a) = | Invalid(string) | EmptyHole @@ -151,6 +157,96 @@ and mpat_term('a) = | Var(Var.t) | Asc(mpat_t('a), typ_t('a)) and mpat_t('a) = Annotated.t(mpat_term('a), 'a) +and proof_term('a) = + | Invalid(string) + | EmptyHole + | MultiHole(list(any_t('a))) + | Seq(proof_t('a), proof_t('a)) + /* `( )`: grouping only, which the checker, statics and + * stepper all look through. It delimits a wrapping form like + * `funext x => ...` inside a larger proof, such as the left of a `;`. */ + | Parens(proof_t('a)) + /* The rewrite steps act at the root of the incoming goal; `Focus` + * points them at a subterm. + * + * `rewrite end` rewrites with a rule in scope, and + * `rewrite <- end` with it right to left. `instantiation` is + * the optional `with = ` clause: an explicit instantiation + * of one of the cited rule's binders, seeded into the match context + * before matching. One binding per step. */ + | AxiomStep({ + direction: Direction.t, + equality: exp_t('a), + instantiation: option((exp_t('a), exp_t('a))), + }) + /* `algebra end`: replace the goal with an expression the + * CAS finds equal to it. */ + | AlgebriteStep(exp_t('a)) + /* `step`: one evaluation step at the root, a rewrite whose replacement + * is computed. The checker takes the step function as a parameter. */ + | EvalStep + /* `from do end`, or `from at 2 do ...`: + * check against one occurrence of in the goal, and + * put its result back in place of that occurrence. The selector may use + * the `$e`/`$v`/`$x` metavariables. `ordinal` counts matches from 1, + * left to right; without one the first match is meant. It is annotated + * like a term, so its token keeps its id and whitespace. */ + | Focus({ + ordinal: option(Annotated.t(int, 'a)), + selector: exp_t('a), + body: proof_t('a), + }) + /* `cases | ... end`: case analysis. Each case gets the case + * equation ` == `, named `case_eq`, which shadows any + * enclosing one; a nested split keeps an outer equation citable with + * `alias h = case_eq =>` before it. */ + | Cases(exp_t('a), list((pat_t('a), proof_t('a)))) + /* `induction | ... end`: structural induction. Each case gets an + * inductive hypothesis `ih_` per recursive position and no case + * equation; a computed `` is first generalized to a fresh + * variable. */ + | Induction(exp_t('a), list((pat_t('a), proof_t('a)))) + | Forall(pat_t('a), proof_t('a)) + /* `funext x => `: functional extensionality as an intro rule. + * With goal `f == g` at an arrow type, the sub-proof's goal is + * `f(x) == g(x)`, with `x` bound at the domain type. A curried goal + * needs one `funext` per arrow. + * + * It isn't an axiom because axioms are rewrite equalities, and stating + * funext as one would quantify over functions at unknown types. Its + * shape is `Forall`'s: a binder wrapping a body proof. */ + | Funext(pat_t('a), proof_t('a)) + /* `assume => `, or `assume = => `: + * with goal ` ==> G`, hypothesize `` and prove `G`. The + * hypothesis is named `assume` unless named, and shadows an enclosing + * one of the same name. */ + | Assume(exp_t('a), option(pat_t('a)), proof_t('a)) + /* `alias = => `: name a fact already in scope. + * Resolves as `revert` does (by name, or by spelling out the + * proposition) and makes the same proposition citable as in the + * sub-proof. It assumes nothing new and leaves the goal alone; it lets + * a fact stay citable after a hypothesis of the same name shadows it. + * An unresolvable is marked `UnknownFactReverted`. */ + | Alias(pat_t('a), exp_t('a), proof_t('a)) + /* `generalize x => `: re-quantify the in-scope variable `x`, so + * the sub-proof's goal is `forall x -> G`. Used before `induction` to get + * quantified induction hypotheses. */ + | Generalize(exp_t('a), proof_t('a)) + /* `revert => `: move an in-scope fact back into the goal, + * the converse of `assume`. With goal `G` and in-scope fact `F`, the + * sub-proof's goal is `F ==> G`. No obligation: `F` holds here, so + * `(F ==> G) == G` under the Kleene reading. + * + * With the optional `with = ` clause, the fact must be + * quantified, and the antecedent is the fact instantiated at `exp`. */ + | Revert(exp_t('a), option((exp_t('a), exp_t('a))), proof_t('a)) + /* `have proof => `, or `have = + * proof ...`: forward reasoning, i.e. `assume` with a proof attached. + * The subproof's goal is , and can cite as `have` + * unless named. Until the subproof closes, the `have` carries the + * obligation for . */ + | Have(exp_t('a), option(pat_t('a)), proof_t('a), proof_t('a)) +and proof_t('a) = Annotated.t(proof_term('a), 'a) and stepper_filter_kind_t('a) = | Filter(filter('a)) | Residue(int, FilterAction.t) @@ -216,13 +312,13 @@ let rec map_exp_annotation: type a b. (a => b, exp_t(a)) => exp_t(b) = map_exp_annotation(f, e1), map_exp_annotation(f, e2), ) - | Theorem(p, e1, e2) => + | Theorem(p, e1, pf, e2) => Theorem( map_pat_annotation(f, p), map_exp_annotation(f, e1), + map_proof_annotation(f, pf), map_exp_annotation(f, e2), ) - | ProofObject(t) => ProofObject(map_exp_annotation(f, t)) | Forall(p, e) => Forall(map_pat_annotation(f, p), map_exp_annotation(f, e)) | FixF(p, e, _) => @@ -321,9 +417,72 @@ and map_any_annotation: 'a 'b. ('a => 'b, any_t('a)) => any_t('b) = | Mod(m) => Mod(map_mod_annotation(f, m)) | Sig(s) => Sig(map_sig_annotation(f, s)) | MPat(mp) => MPat(map_mpat_annotation(f, mp)) + | Proof(p) => Proof(map_proof_annotation(f, p)) + | PRul(r) => PRul(map_prul_annotation(f, r)) | Any(_) => Any() }; } +and map_proof_annotation: 'a 'b. ('a => 'b, proof_t('a)) => proof_t('b) = + (f, e) => { + let annotation = f(e.annotation); + let exp = map_exp_annotation(f); + let pat = map_pat_annotation(f); + let proof = map_proof_annotation(f); + let inst = Option.map(~f=((v, i)) => (exp(v), exp(i))); + { + term: + switch (e.term) { + | Invalid(s) => Invalid(s) + | EmptyHole => EmptyHole + | MultiHole(l) => MultiHole(List.map(~f=map_any_annotation(f), l)) + | Seq(p1, p2) => Seq(proof(p1), proof(p2)) + | Parens(p) => Parens(proof(p)) + | AxiomStep({direction, equality, instantiation}) => + AxiomStep({ + direction, + equality: exp(equality), + instantiation: inst(instantiation), + }) + | AlgebriteStep(e) => AlgebriteStep(exp(e)) + | EvalStep => EvalStep + | Focus({ordinal, selector, body}) => + Focus({ + ordinal: + Option.map( + ~f= + (o: Annotated.t(int, _)) => + Annotated.{ + term: o.term, + annotation: f(o.annotation), + }, + ordinal, + ), + selector: exp(selector), + body: proof(body), + }) + | Cases(e, cases) => + Cases( + exp(e), + List.map(~f=((p, body)) => (pat(p), proof(body)), cases), + ) + | Induction(e, cases) => + Induction( + exp(e), + List.map(~f=((p, body)) => (pat(p), proof(body)), cases), + ) + | Forall(x, body) => Forall(pat(x), proof(body)) + | Funext(x, body) => Funext(pat(x), proof(body)) + | Assume(e, name, body) => + Assume(exp(e), Option.map(~f=pat, name), proof(body)) + | Alias(x, e, body) => Alias(pat(x), exp(e), proof(body)) + | Generalize(e, body) => Generalize(exp(e), proof(body)) + | Revert(e, i, body) => Revert(exp(e), inst(i), proof(body)) + | Have(e, name, sub, body) => + Have(exp(e), Option.map(~f=pat, name), proof(sub), proof(body)) + }, + annotation, + }; + } and map_pat_annotation: 'a 'b. ('a => 'b, pat_t('a)) => pat_t('b) = (f, e) => { let (term, annotation) = (e.term, e.annotation); @@ -382,7 +541,6 @@ and map_typ_annotation: 'a 'b. ('a => 'b, typ_t('a)) => typ_t('b) = Rec(map_tpat_annotation(f, tp), map_typ_annotation(f, t)) | Poly(tp, t) => Poly(map_tpat_annotation(f, tp), map_typ_annotation(f, t)) - | ProofOf(e) => ProofOf(map_exp_annotation(f, e)) | Prod(l) => Prod(List.map(~f=x => map_typ_annotation(f, x), l)) | Label(l) => Label(l) | ExplicitNonlabel => ExplicitNonlabel @@ -445,6 +603,30 @@ and map_rul_annotation: 'a 'b. ('a => 'b, rul_t('a)) => rul_t('b) = annotation: new_annotation, }; } +and map_prul_annotation: 'a 'b. ('a => 'b, prul_t('a)) => prul_t('b) = + (f, e) => { + let (term, annotation) = (e.term, e.annotation); + let new_annotation = f(annotation); + { + term: + switch (term) { + | Invalid(s) => Invalid(s) + | MultiHole(l) => + MultiHole(List.map(~f=x => map_any_annotation(f, x), l)) + | ProofRules(e, l) => + ProofRules( + map_exp_annotation(f, e), + List.map( + ~f= + ((p, pr)) => + (map_pat_annotation(f, p), map_proof_annotation(f, pr)), + l, + ), + ) + }, + annotation: new_annotation, + }; + } and map_mod_annotation: 'a 'b. ('a => 'b, mod_t('a)) => mod_t('b) = (f, e) => { let (term, annotation) = (e.term, e.annotation); @@ -554,6 +736,7 @@ module Factory = (DefaultAnnotation: DefaultAnnotation) => { type tpat = tpat_t(DefaultAnnotation.t); type typ_provenance = type_provenance(DefaultAnnotation.t); type mod_ = mod_t(DefaultAnnotation.t); + type proof = proof_t(DefaultAnnotation.t); let default_annotation = ann => Option.value(~default=DefaultAnnotation.default_value(), ann); @@ -680,12 +863,8 @@ module Factory = (DefaultAnnotation: DefaultAnnotation) => { term: Let(p, e1, e2), annotation: default_annotation(ann), }; - let theorem = (~ann=?, p, e1, e2): exp_t(DefaultAnnotation.t) => { - term: Theorem(p, e1, e2), - annotation: default_annotation(ann), - }; - let proof_object = (~ann=?, t): exp_t(DefaultAnnotation.t) => { - term: ProofObject(t), + let theorem = (~ann=?, p, e1, pf, e2): exp_t(DefaultAnnotation.t) => { + term: Theorem(p, e1, pf, e2), annotation: default_annotation(ann), }; let forall = (~ann=?, p, e): exp_t(DefaultAnnotation.t) => { @@ -972,10 +1151,6 @@ module Factory = (DefaultAnnotation: DefaultAnnotation) => { term: Poly(tp, t), annotation: default_annotation(ann), }; - let proof_of = (~ann=?, e): typ_t(DefaultAnnotation.t) => { - term: ProofOf(e), - annotation: default_annotation(ann), - }; let empty_hole = (~ann=?, ()): typ_t(DefaultAnnotation.t) => { term: Unknown(Hole(EmptyHole)), annotation: default_annotation(ann), @@ -1016,6 +1191,21 @@ module Factory = (DefaultAnnotation: DefaultAnnotation) => { }; }; + module PRul = { + let prul_invalid = (~ann=?, s): prul_t(DefaultAnnotation.t) => { + term: Invalid(s), + annotation: default_annotation(ann), + }; + let prul_hole = (~ann=?, l): prul_t(DefaultAnnotation.t) => { + term: MultiHole(l), + annotation: default_annotation(ann), + }; + let prul_proof_rules = (~ann=?, e, l): prul_t(DefaultAnnotation.t) => { + term: ProofRules(e, l), + annotation: default_annotation(ann), + }; + }; + module Mod = { let invalid = (~ann=?, s): mod_t(DefaultAnnotation.t) => { term: Invalid(s), @@ -1093,6 +1283,105 @@ module Factory = (DefaultAnnotation: DefaultAnnotation) => { }; }; + module Proof = { + let invalid = (~ann=?, s): proof_t(DefaultAnnotation.t) => { + term: Invalid(s), + annotation: default_annotation(ann), + }; + let empty_hole = (~ann=?, ()): proof_t(DefaultAnnotation.t) => { + term: EmptyHole, + annotation: default_annotation(ann), + }; + let multi_hole = (~ann=?, l): proof_t(DefaultAnnotation.t) => { + term: MultiHole(l), + annotation: default_annotation(ann), + }; + let seq = (~ann=?, p1, p2): proof_t(DefaultAnnotation.t) => { + term: Seq(p1, p2), + annotation: default_annotation(ann), + }; + let parens = (~ann=?, p): proof_t(DefaultAnnotation.t) => { + term: Parens(p), + annotation: default_annotation(ann), + }; + let axiom_step = + (~ann=?, ~direction, ~equality, ~instantiation=None, ()) + : proof_t(DefaultAnnotation.t) => { + term: + AxiomStep({ + direction, + equality, + instantiation, + }), + annotation: default_annotation(ann), + }; + let algebrite_step = (~ann=?, e): proof_t(DefaultAnnotation.t) => { + term: AlgebriteStep(e), + annotation: default_annotation(ann), + }; + let eval_step = (~ann=?, ()): proof_t(DefaultAnnotation.t) => { + term: EvalStep, + annotation: default_annotation(ann), + }; + let focus = + (~ann=?, ~ordinal=None, selector, body): proof_t(DefaultAnnotation.t) => { + term: + Focus({ + ordinal: + Option.map( + ~f= + n => + Annotated.{ + term: n, + annotation: default_annotation(None), + }, + ordinal, + ), + selector, + body, + }), + annotation: default_annotation(ann), + }; + let cases = (~ann=?, e, cases): proof_t(DefaultAnnotation.t) => { + term: Cases(e, cases), + annotation: default_annotation(ann), + }; + let induction = (~ann=?, e, cases): proof_t(DefaultAnnotation.t) => { + term: Induction(e, cases), + annotation: default_annotation(ann), + }; + let forall = (~ann=?, x, body): proof_t(DefaultAnnotation.t) => { + term: Forall(x, body), + annotation: default_annotation(ann), + }; + let funext = (~ann=?, x, body): proof_t(DefaultAnnotation.t) => { + term: Funext(x, body), + annotation: default_annotation(ann), + }; + let assume = (~ann=?, ~name=None, e, body): proof_t(DefaultAnnotation.t) => { + term: Assume(e, name, body), + annotation: default_annotation(ann), + }; + let alias = (~ann=?, x, e, body): proof_t(DefaultAnnotation.t) => { + term: Alias(x, e, body), + annotation: default_annotation(ann), + }; + let generalize = (~ann=?, e, body): proof_t(DefaultAnnotation.t) => { + term: Generalize(e, body), + annotation: default_annotation(ann), + }; + let revert = + (~ann=?, ~instantiation=None, e, body): proof_t(DefaultAnnotation.t) => { + term: Revert(e, instantiation, body), + annotation: default_annotation(ann), + }; + let have = + (~ann=?, ~name=None, e, sub, body): proof_t(DefaultAnnotation.t) => { + term: Have(e, name, sub, body), + annotation: default_annotation(ann), + }; + }; + module StepperFilter = { let filter = (f): stepper_filter_kind_t(DefaultAnnotation.t) => { Filter({ diff --git a/src/language/term/InvalidOperationError.re b/src/language/term/InvalidOperationError.re index 2886b19835..6610d8eb7d 100644 --- a/src/language/term/InvalidOperationError.re +++ b/src/language/term/InvalidOperationError.re @@ -6,6 +6,7 @@ type t = | NegativeExponent | NegativeNat | IntegerTooBig + | NonFiniteFloat | Incomparable; let err_msg = (err: t): string => @@ -16,5 +17,6 @@ let err_msg = (err: t): string => | NegativeExponent => "Error: Negative Exponent in Integer Exponentiation (Consider using **.)" | NegativeNat => "Error: Cannot convert negative number to Nat" | IntegerTooBig => "Error: Integer too big" + | NonFiniteFloat => "Error: Cannot convert non-finite float (nan or infinity)" | Incomparable => "Error: Incomparable Types" }; diff --git a/src/language/term/Operators.re b/src/language/term/Operators.re index 0c1cafc437..912a6f718e 100644 --- a/src/language/term/Operators.re +++ b/src/language/term/Operators.re @@ -23,7 +23,8 @@ type op_un_num = [@deriving (show({with_path: false}), sexp, yojson, eq, enumerate)] type op_bin_bool = | And - | Or; + | Or + | Implies; [@deriving (show({with_path: false}), sexp, yojson, eq, enumerate)] type op_bin_num = @@ -224,7 +225,8 @@ let show_unop: op_un => string = let show_op_bin_bool: op_bin_bool => string = fun | And => "Boolean Conjunction" - | Or => "Boolean Disjunction"; + | Or => "Boolean Disjunction" + | Implies => "Boolean Implication"; let show_op_bin_num: op_bin_num => string = fun @@ -383,6 +385,7 @@ let semantics_of_bin_op = (op: op_bin): bin_semantics => | Bool(And) => Defined(Bool, Bool, Bool, just((&&))) // Note: booleans have extra short-cutting rules in transition | Bool(Or) => Defined(Bool, Bool, Bool, just((||))) + | Bool(Implies) => Defined(Bool, Bool, Bool, just((a, b) => !a || b)) // McCarthy short-circuit in transition, like And/Or | Poly(Equals) => DefinedPoly(Equals) | Poly(NotEquals) => DefinedPoly(NotEquals) @@ -433,6 +436,7 @@ let op_name = (op: op_bin): string => | String(Concat) => "string_concat" | Bool(And) => "bool_and" | Bool(Or) => "bool_or" + | Bool(Implies) => "bool_implies" | Poly(Equals) => "poly_eq" | Poly(NotEquals) => "poly_neq" }; diff --git a/src/language/term/PRul.re b/src/language/term/PRul.re new file mode 100644 index 0000000000..68366a4da3 --- /dev/null +++ b/src/language/term/PRul.re @@ -0,0 +1,25 @@ +include TermBase.PRul; + +[@deriving (show({with_path: false}), sexp, yojson, enumerate)] +type cls = + | ProofRule; + +/* Proof-rule sort mirroring Rul, used as the child of the `induction` tile. + As with Rul, a PRul may hold a scrutinee with no rules, so id lookup + falls back to the scrutinee's ids when the PRul has none of its own. */ +let ids = (~any_ids, {term, annotation: {ids, _}}: t) => + switch (ids) { + | [_, ..._] => ids + | [] => + switch (term) { + | MultiHole([tm, ..._]) => any_ids(tm) + | ProofRules(scrut, []) => IdTagged.ids(scrut) + | _ => [] + } + }; + +let rep_id = (~any_ids, tm) => + switch (ids(~any_ids, tm)) { + | [] => raise(Invalid_argument("PRul.rep_id")) + | [id, ..._] => id + }; diff --git a/src/language/term/Proof.re b/src/language/term/Proof.re new file mode 100644 index 0000000000..7e099e174c --- /dev/null +++ b/src/language/term/Proof.re @@ -0,0 +1,211 @@ +[@deriving (show({with_path: false}), sexp, yojson, enumerate, eq)] +type cls = + | Invalid + | EmptyHole + | MultiHole + | Seq + | AxiomStep + | AlgebriteStep + | EvalStep + | Focus + | Cases + | Induction + | Forall + | Funext + | Assume + | Generalize + | Revert + | Have + | Alias + | Parens; + +include TermBase.Proof; + +let fresh: term => t = IdTagged.fresh; + +let rep_id: t => Id.t = IdTagged.rep_id; + +let hole = (tms: list(TermBase.Any.t)): TermBase.Proof.term => + switch (tms) { + | [] => EmptyHole + | [_, ..._] => MultiHole(tms) + }; + +let rec cls_of_term: Grammar.proof_term('a) => cls = + fun + | Invalid(_) => Invalid + | EmptyHole => EmptyHole + | MultiHole(_) => MultiHole + | Seq(_, _) => Seq + /* As `Exp.cls_of_term` does, report the form inside the parens. */ + | Parens(p) => cls_of_term(p.term) + | AxiomStep(_) => AxiomStep + | AlgebriteStep(_) => AlgebriteStep + | Cases(_, _) => Cases + | Induction(_, _) => Induction + | Forall(_, _) => Forall + | Funext(_, _) => Funext + | Assume(_, _, _) => Assume + | Generalize(_, _) => Generalize + | Revert(_, _, _) => Revert + | Have(_, _, _, _) => Have + | Alias(_, _, _) => Alias + | EvalStep => EvalStep + | Focus(_) => Focus; + +/* The docs panel's title for a step: what the user types for it. */ +let show_cls: cls => string = + fun + | Invalid => "Invalid proof" + | MultiHole => "Broken proof" + | EmptyHole => "? (unfinished proof)" + | Seq => "; (one step, then the next)" + | AxiomStep => "rewrite" + | AlgebriteStep => "algebra" + | Cases => "cases" + | Induction => "induction" + | Forall => "forall" + | Funext => "funext" + | Assume => "assume" + | Generalize => "generalize" + | Revert => "revert" + | Alias => "alias" + | Have => "have" + | Parens => "Parenthesized proof" + | EvalStep => "step" + | Focus => "from"; + +/* Ignores parens and projectors, as `Exp.fast_equal` does. */ +let fast_equal = + Equality.( + equality({ + ...syntactic_settings, + ignore_parens: true, + ignore_projectors: true, + }) + ). + proof; + +/* The sub-proofs directly inside a proof, in source order. */ +let children = (p: t): list(t) => + switch (p.term) { + | EmptyHole + | Invalid(_) + | MultiHole(_) + | AxiomStep(_) + | AlgebriteStep(_) + | EvalStep => [] + | Seq(p1, p2) => [p1, p2] + | Focus({body, _}) + | Parens(body) + | Forall(_, body) + | Funext(_, body) + | Assume(_, _, body) + | Generalize(_, body) + | Alias(_, _, body) + | Revert(_, _, body) => [body] + | Have(_, _, sub, body) => [sub, body] + | Cases(_, cases) + | Induction(_, cases) => List.map(~f=snd, cases) + }; + +/* Is any step of this proof a hole? Holes in a step's arguments don't + * count; see `args_have_hole`. */ +let rec has_hole = (p: t): bool => + switch (p.term) { + | EmptyHole + | Invalid(_) + | MultiHole(_) => true + | Seq(_) + | Parens(_) + | AxiomStep(_) + | AlgebriteStep(_) + | EvalStep + | Focus(_) + | Cases(_) + | Induction(_) + | Forall(_) + | Funext(_) + | Assume(_) + | Generalize(_) + | Revert(_) + | Have(_) + | Alias(_) => List.exists(~f=has_hole, children(p)) + }; + +/* Do the step's own arguments contain a hole? Unlike `has_hole`, this + * skips nested sub-proofs: the stepper shows a hole in a case body as its + * own "…" row, but a hole in an argument (an induction pattern or + * scrutinee, a forall binder, a focus's selector, a fact's name) has no + * other indicator. */ +let rec args_have_hole = (p: t): bool => { + module M = { + exception Found_hole; + }; + let is_exp_hole = (e: Exp.t) => + switch (Exp.term_of(e)) { + | EmptyHole + | Invalid(_) + | MultiHole(_) => true + | _ => false + }; + let is_pat_hole = (p: Pat.t) => + switch (Pat.term_of(p)) { + | EmptyHole + | Invalid(_) + | MultiHole(_) => true + | _ => false + }; + let raise_on_hole = (is_hole, cont, tm) => + is_hole(tm) ? raise(M.Found_hole) : cont(tm); + let exp = (e: Exp.t): bool => + switch ( + Exp.map_term( + ~f_exp=raise_on_hole(is_exp_hole), + ~f_pat=raise_on_hole(is_pat_hole), + e, + ) + ) { + | _ => false + | exception M.Found_hole => true + }; + let pat = (p: Pat.t): bool => + switch (Pat.map_term(~f_pat=raise_on_hole(is_pat_hole), p)) { + | _ => false + | exception M.Found_hole => true + }; + let inst = (inst: option((Exp.t, Exp.t))): bool => + switch (inst) { + | None => false + | Some((v, i)) => exp(v) || exp(i) + }; + let name = (name: option(Pat.t)): bool => + switch (name) { + | None => false + | Some(x) => pat(x) + }; + switch (p.term) { + | EmptyHole + | Invalid(_) + | MultiHole(_) + | Seq(_, _) => false + | Parens(p) => args_have_hole(p) + | AxiomStep({equality, instantiation, direction: _}) => + exp(equality) || inst(instantiation) + | AlgebriteStep(e) => exp(e) + | EvalStep => false + | Focus({selector, _}) => exp(selector) + | Cases(scrut, cases) => + exp(scrut) || List.exists(~f=((case_pat, _)) => pat(case_pat), cases) + | Induction(scrut, cases) => + exp(scrut) || List.exists(~f=((case_pat, _)) => pat(case_pat), cases) + | Forall(x, _) + | Funext(x, _) => pat(x) + | Assume(e, x, _) => exp(e) || name(x) + | Alias(x, e, _) => pat(x) || exp(e) + | Generalize(e, _) => exp(e) + /* A have's subproof is a nested proof and reports its own holes. */ + | Have(e, x, _, _) => exp(e) || name(x) + | Revert(e, i, _) => exp(e) || inst(i) + }; +}; diff --git a/src/language/term/Sort.re b/src/language/term/Sort.re index fb5e120ca2..8624b8e1ac 100644 --- a/src/language/term/Sort.re +++ b/src/language/term/Sort.re @@ -9,7 +9,9 @@ type t = | Exp | Mod | Sig - | MPat; + | MPat + | Proof + | PRul; let to_string = fun diff --git a/src/language/term/TermBase.re b/src/language/term/TermBase.re index 90b2a2518f..69cf718a85 100644 --- a/src/language/term/TermBase.re +++ b/src/language/term/TermBase.re @@ -76,6 +76,14 @@ type mpat_t = Grammar.mpat_t(IdTagged.IdTag.t); [@deriving (show({with_path: false}), sexp, yojson)] type mpat_term = Grammar.mpat_term(IdTagged.IdTag.t); [@deriving (show({with_path: false}), sexp, yojson)] +type proof_t = Grammar.proof_t(IdTagged.IdTag.t); +[@deriving (show({with_path: false}), sexp, yojson)] +type proof_term = Grammar.proof_term(IdTagged.IdTag.t); +[@deriving (show({with_path: false}), sexp, yojson)] +type prul_t = Grammar.prul_t(IdTagged.IdTag.t); +[@deriving (show({with_path: false}), sexp, yojson)] +type prul_term = Grammar.prul_term(IdTagged.IdTag.t); +[@deriving (show({with_path: false}), sexp, yojson)] type stepper_filter_kind_t = Grammar.stepper_filter_kind_t(IdTagged.IdTag.t); [@deriving (show({with_path: false}), sexp, yojson)] type type_hole = Grammar.type_hole(IdTagged.IdTag.t); @@ -101,6 +109,7 @@ module rec Any: { ~f_sig: (Sig.t => Sig.t, Sig.t) => Sig.t=?, ~f_mpat: (MPat.t => MPat.t, MPat.t) => MPat.t=?, ~f_any: (Any.t => Any.t, Any.t) => Any.t=?, + ~f_proof: (Proof.t => Proof.t, Proof.t) => Proof.t=?, t ) => t; @@ -119,6 +128,7 @@ module rec Any: { ~f_sig=continue, ~f_mpat=continue, ~f_any=continue, + ~f_proof=continue, x: any_t, ) => { let rec_call = (y: any_t): any_t => @@ -135,6 +145,7 @@ module rec Any: { ~f_sig, ~f_mpat, ~f_any, + ~f_proof, x, ), ) @@ -150,6 +161,7 @@ module rec Any: { ~f_sig, ~f_mpat, ~f_any, + ~f_proof, x, ), ) @@ -165,6 +177,7 @@ module rec Any: { ~f_sig, ~f_mpat, ~f_any, + ~f_proof, x, ), ) @@ -180,6 +193,7 @@ module rec Any: { ~f_sig, ~f_mpat, ~f_any, + ~f_proof, x, ), ) @@ -195,6 +209,7 @@ module rec Any: { ~f_sig, ~f_mpat, ~f_any, + ~f_proof, x, ), ) @@ -213,6 +228,7 @@ module rec Any: { ~f_sig, ~f_mpat, ~f_any, + ~f_proof, x, ), ) @@ -228,6 +244,7 @@ module rec Any: { ~f_sig, ~f_mpat, ~f_any, + ~f_proof, x, ), ) @@ -243,6 +260,33 @@ module rec Any: { ~f_sig, ~f_mpat, ~f_any, + ~f_proof, + x, + ), + ) + | Proof(x) => + Proof( + Proof.map_term( + ~f_exp, + ~f_pat, + ~f_typ, + ~f_tpat, + ~f_rul, + ~f_any, + ~f_proof, + x, + ), + ) + | PRul(x) => + PRul( + PRul.map_term( + ~f_exp, + ~f_pat, + ~f_typ, + ~f_tpat, + ~f_rul, + ~f_any, + ~f_proof, x, ), ) @@ -269,6 +313,7 @@ and Exp: { ~f_sig: (Sig.t => Sig.t, Sig.t) => Sig.t=?, ~f_mpat: (MPat.t => MPat.t, MPat.t) => MPat.t=?, ~f_any: (Any.t => Any.t, Any.t) => Any.t=?, + ~f_proof: (Proof.t => Proof.t, Proof.t) => Proof.t=?, t ) => t; @@ -291,6 +336,7 @@ and Exp: { ~f_sig=continue, ~f_mpat=continue, ~f_any=continue, + ~f_proof=continue, x, ) => { let exp_map_term = @@ -304,6 +350,7 @@ and Exp: { ~f_sig, ~f_mpat, ~f_any, + ~f_proof, ); let pat_map_term = Pat.map_term( @@ -316,6 +363,7 @@ and Exp: { ~f_sig, ~f_mpat, ~f_any, + ~f_proof, ); let typ_map_term = Typ.map_term( @@ -328,6 +376,7 @@ and Exp: { ~f_sig, ~f_mpat, ~f_any, + ~f_proof, ); let tpat_map_term = TPat.map_term( @@ -340,6 +389,7 @@ and Exp: { ~f_sig, ~f_mpat, ~f_any, + ~f_proof, ); let any_map_term = Any.map_term( @@ -352,6 +402,7 @@ and Exp: { ~f_sig, ~f_mpat, ~f_any, + ~f_proof, ); let mpat_map_term = MPat.map_term( @@ -364,6 +415,17 @@ and Exp: { ~f_sig, ~f_mpat, ~f_any, + ~f_proof, + ); + let proof_map_term = + Proof.map_term( + ~f_exp, + ~f_pat, + ~f_typ, + ~f_tpat, + ~f_rul, + ~f_any, + ~f_proof, ); let flt_map_term = StepperFilterKind.map_term( @@ -372,7 +434,11 @@ and Exp: { ~f_typ, ~f_tpat, ~f_rul, + ~f_mod, + ~f_sig, + ~f_mpat, ~f_any, + ~f_proof, ); let rec_call = ({term, _} as exp: t) => { ...exp, @@ -408,9 +474,13 @@ and Exp: { | Dot(e1, e2) => Dot(exp_map_term(e1), exp_map_term(e2)) | Let(p, e1, e2) => Let(pat_map_term(p), exp_map_term(e1), exp_map_term(e2)) - | Theorem(p, e1, e2) => - Theorem(pat_map_term(p), exp_map_term(e1), exp_map_term(e2)) - | ProofObject(t) => ProofObject(exp_map_term(t)) + | Theorem(p, e1, pf, e2) => + Theorem( + pat_map_term(p), + exp_map_term(e1), + proof_map_term(pf), + exp_map_term(e2), + ) | Forall(p, e) => Forall(pat_map_term(p), exp_map_term(e)) | FixF(p, e, env) => FixF(pat_map_term(p), exp_map_term(e), env) | TyAlias(tp, t, e) => @@ -459,6 +529,7 @@ and Exp: { ~f_sig, ~f_mpat, ~f_any, + ~f_proof, ), items, ), @@ -491,6 +562,7 @@ and Pat: { ~f_sig: (Sig.t => Sig.t, Sig.t) => Sig.t=?, ~f_mpat: (MPat.t => MPat.t, MPat.t) => MPat.t=?, ~f_any: (Any.t => Any.t, Any.t) => Any.t=?, + ~f_proof: (Proof.t => Proof.t, Proof.t) => Proof.t=?, t ) => t; @@ -511,6 +583,7 @@ and Pat: { ~f_sig=continue, ~f_mpat=continue, ~f_any=continue, + ~f_proof=continue, x, ) => { let pat_map_term = @@ -524,6 +597,7 @@ and Pat: { ~f_sig, ~f_mpat, ~f_any, + ~f_proof, ); let typ_map_term = Typ.map_term( @@ -536,6 +610,7 @@ and Pat: { ~f_sig, ~f_mpat, ~f_any, + ~f_proof, ); let any_map_term = Any.map_term( @@ -548,6 +623,7 @@ and Pat: { ~f_sig, ~f_mpat, ~f_any, + ~f_proof, ); let rec_call = ({term, _} as exp: t) => { ...exp, @@ -595,6 +671,7 @@ and Typ: { ~f_sig: (Sig.t => Sig.t, Sig.t) => Sig.t=?, ~f_mpat: (MPat.t => MPat.t, MPat.t) => MPat.t=?, ~f_any: (Any.t => Any.t, Any.t) => Any.t=?, + ~f_proof: (Proof.t => Proof.t, Proof.t) => Proof.t=?, t ) => t; @@ -617,6 +694,7 @@ and Typ: { ~f_sig=continue, ~f_mpat=continue, ~f_any=continue, + ~f_proof=continue, x, ) => { let typ_map_term = @@ -630,6 +708,7 @@ and Typ: { ~f_sig, ~f_mpat, ~f_any, + ~f_proof, ); let any_map_term = Any.map_term( @@ -642,6 +721,7 @@ and Typ: { ~f_sig, ~f_mpat, ~f_any, + ~f_proof, ); let tpat_map_term = TPat.map_term( @@ -654,18 +734,7 @@ and Typ: { ~f_sig, ~f_mpat, ~f_any, - ); - let exp_map_term = - Exp.map_term( - ~f_exp, - ~f_pat, - ~f_typ, - ~f_tpat, - ~f_rul, - ~f_mod, - ~f_sig, - ~f_mpat, - ~f_any, + ~f_proof, ); let rec_call = ({term, _} as exp: t) => { ...exp, @@ -727,7 +796,6 @@ and Typ: { ProdExtension(typ_map_term(t1), typ_map_term(t2)) | Rec(tp, t) => Rec(tpat_map_term(tp), typ_map_term(t)) | Poly(tp, t) => Poly(tpat_map_term(tp), typ_map_term(t)) - | ProofOf(e) => ProofOf(exp_map_term(e)) | Sig(items) => Sig( List.map( @@ -742,6 +810,7 @@ and Typ: { ~f_sig, ~f_mpat, ~f_any, + ~f_proof, ), items, ), @@ -768,6 +837,7 @@ and TPat: { ~f_sig: (Sig.t => Sig.t, Sig.t) => Sig.t=?, ~f_mpat: (MPat.t => MPat.t, MPat.t) => MPat.t=?, ~f_any: (Any.t => Any.t, Any.t) => Any.t=?, + ~f_proof: (Proof.t => Proof.t, Proof.t) => Proof.t=?, t ) => t; @@ -790,6 +860,7 @@ and TPat: { ~f_sig=continue, ~f_mpat=continue, ~f_any=continue, + ~f_proof=continue, x, ) => { let any_map_term = @@ -803,6 +874,7 @@ and TPat: { ~f_sig, ~f_mpat, ~f_any, + ~f_proof, ); let rec_call = ({term, _} as exp: t) => { ...exp, @@ -840,6 +912,7 @@ and Rul: { ~f_sig: (Sig.t => Sig.t, Sig.t) => Sig.t=?, ~f_mpat: (MPat.t => MPat.t, MPat.t) => MPat.t=?, ~f_any: (Any.t => Any.t, Any.t) => Any.t=?, + ~f_proof: (Proof.t => Proof.t, Proof.t) => Proof.t=?, t ) => t; @@ -860,6 +933,7 @@ and Rul: { ~f_sig=continue, ~f_mpat=continue, ~f_any=continue, + ~f_proof=continue, x, ) => { let exp_map_term = @@ -873,6 +947,7 @@ and Rul: { ~f_sig, ~f_mpat, ~f_any, + ~f_proof, ); let pat_map_term = Pat.map_term( @@ -885,6 +960,7 @@ and Rul: { ~f_sig, ~f_mpat, ~f_any, + ~f_proof, ); let any_map_term = Any.map_term( @@ -897,6 +973,7 @@ and Rul: { ~f_sig, ~f_mpat, ~f_any, + ~f_proof, ); let rec_call = ({term, _} as exp: t) => { ...exp, @@ -917,6 +994,76 @@ and Rul: { x |> f_rul(rec_call); }; } +and PRul: { + [@deriving (show({with_path: false}), sexp, yojson)] + type term = prul_term; + [@deriving (show({with_path: false}), sexp, yojson)] + type t = prul_t; + + let map_term: + ( + ~f_exp: (Exp.t => Exp.t, Exp.t) => Exp.t=?, + ~f_pat: (Pat.t => Pat.t, Pat.t) => Pat.t=?, + ~f_typ: (Typ.t => Typ.t, Typ.t) => Typ.t=?, + ~f_tpat: (TPat.t => TPat.t, TPat.t) => TPat.t=?, + ~f_rul: (Rul.t => Rul.t, Rul.t) => Rul.t=?, + ~f_any: (Any.t => Any.t, Any.t) => Any.t=?, + ~f_proof: (Proof.t => Proof.t, Proof.t) => Proof.t=?, + t + ) => + t; +} = { + [@deriving (show({with_path: false}), sexp, yojson)] + type term = prul_term; + [@deriving (show({with_path: false}), sexp, yojson)] + type t = prul_t; + + let map_term = + ( + ~f_exp=continue, + ~f_pat=continue, + ~f_typ=continue, + ~f_tpat=continue, + ~f_rul=continue, + ~f_any=continue, + ~f_proof=continue, + x, + ) => { + let exp_map_term = + Exp.map_term(~f_exp, ~f_pat, ~f_typ, ~f_tpat, ~f_rul, ~f_any, ~f_proof); + let pat_map_term = + Pat.map_term(~f_exp, ~f_pat, ~f_typ, ~f_tpat, ~f_rul, ~f_any, ~f_proof); + let any_map_term = + Any.map_term(~f_exp, ~f_pat, ~f_typ, ~f_tpat, ~f_rul, ~f_any, ~f_proof); + let proof_map_term = + Proof.map_term( + ~f_exp, + ~f_pat, + ~f_typ, + ~f_tpat, + ~f_rul, + ~f_any, + ~f_proof, + ); + let rec_call = ({term, _} as pr: t) => { + ...pr, + term: + switch (term) { + | Invalid(_) => term + | MultiHole(things) => MultiHole(List.map(~f=any_map_term, things)) + | ProofRules(e, rls) => + ProofRules( + exp_map_term(e), + List.map( + ~f=((p, body)) => (pat_map_term(p), proof_map_term(body)), + rls, + ), + ) + }, + }; + rec_call(x); + }; +} and Mod: { [@deriving (show({with_path: false}), sexp, yojson)] type term = mod_term; @@ -934,6 +1081,7 @@ and Mod: { ~f_sig: (Sig.t => Sig.t, Sig.t) => Sig.t=?, ~f_mpat: (MPat.t => MPat.t, MPat.t) => MPat.t=?, ~f_any: (Any.t => Any.t, Any.t) => Any.t=?, + ~f_proof: (Proof.t => Proof.t, Proof.t) => Proof.t=?, t ) => t; @@ -954,6 +1102,7 @@ and Mod: { ~f_sig=continue, ~f_mpat=continue, ~f_any=continue, + ~f_proof=continue, x, ) => { let exp_map_term = @@ -967,6 +1116,7 @@ and Mod: { ~f_sig, ~f_mpat, ~f_any, + ~f_proof, ); let pat_map_term = Pat.map_term( @@ -979,6 +1129,7 @@ and Mod: { ~f_sig, ~f_mpat, ~f_any, + ~f_proof, ); let typ_map_term = Typ.map_term( @@ -991,6 +1142,7 @@ and Mod: { ~f_sig, ~f_mpat, ~f_any, + ~f_proof, ); let tpat_map_term = TPat.map_term( @@ -1003,6 +1155,7 @@ and Mod: { ~f_sig, ~f_mpat, ~f_any, + ~f_proof, ); let any_map_term = Any.map_term( @@ -1015,6 +1168,7 @@ and Mod: { ~f_sig, ~f_mpat, ~f_any, + ~f_proof, ); let mpat_map_term = MPat.map_term( @@ -1027,6 +1181,7 @@ and Mod: { ~f_sig, ~f_mpat, ~f_any, + ~f_proof, ); let rec_call = ({term, _} as m: t) => { ...m, @@ -1061,6 +1216,7 @@ and Sig: { ~f_sig: (Sig.t => Sig.t, Sig.t) => Sig.t=?, ~f_mpat: (MPat.t => MPat.t, MPat.t) => MPat.t=?, ~f_any: (Any.t => Any.t, Any.t) => Any.t=?, + ~f_proof: (Proof.t => Proof.t, Proof.t) => Proof.t=?, t ) => t; @@ -1081,6 +1237,7 @@ and Sig: { ~f_sig=continue, ~f_mpat=continue, ~f_any=continue, + ~f_proof=continue, x, ) => { let pat_map_term = @@ -1094,6 +1251,7 @@ and Sig: { ~f_sig, ~f_mpat, ~f_any, + ~f_proof, ); let typ_map_term = Typ.map_term( @@ -1106,6 +1264,7 @@ and Sig: { ~f_sig, ~f_mpat, ~f_any, + ~f_proof, ); let tpat_map_term = TPat.map_term( @@ -1118,6 +1277,7 @@ and Sig: { ~f_sig, ~f_mpat, ~f_any, + ~f_proof, ); let any_map_term = Any.map_term( @@ -1130,6 +1290,7 @@ and Sig: { ~f_sig, ~f_mpat, ~f_any, + ~f_proof, ); let rec_call = ({term, _} as s: t) => { ...s, @@ -1163,6 +1324,7 @@ and MPat: { ~f_sig: (Sig.t => Sig.t, Sig.t) => Sig.t=?, ~f_mpat: (MPat.t => MPat.t, MPat.t) => MPat.t=?, ~f_any: (Any.t => Any.t, Any.t) => Any.t=?, + ~f_proof: (Proof.t => Proof.t, Proof.t) => Proof.t=?, t ) => t; @@ -1183,6 +1345,7 @@ and MPat: { ~f_sig=continue, ~f_mpat=continue, ~f_any=continue, + ~f_proof=continue, x, ) => { let _ = (f_exp, f_pat, f_typ, f_tpat, f_rul); @@ -1197,6 +1360,7 @@ and MPat: { ~f_sig, ~f_mpat, ~f_any, + ~f_proof, ); let typ_map_term = Typ.map_term( @@ -1209,6 +1373,7 @@ and MPat: { ~f_sig, ~f_mpat, ~f_any, + ~f_proof, ); let rec rec_call = ({term, _} as mp: t) => { ...mp, @@ -1224,6 +1389,133 @@ and MPat: { x |> f_mpat(rec_call); }; } +and Proof: { + [@deriving (show({with_path: false}), sexp, yojson)] + type term = proof_term; + [@deriving (show({with_path: false}), sexp, yojson)] + type t = proof_t; + + let map_term: + ( + ~f_exp: (Exp.t => Exp.t, Exp.t) => Exp.t=?, + ~f_pat: (Pat.t => Pat.t, Pat.t) => Pat.t=?, + ~f_typ: (Typ.t => Typ.t, Typ.t) => Typ.t=?, + ~f_tpat: (TPat.t => TPat.t, TPat.t) => TPat.t=?, + ~f_rul: (Rul.t => Rul.t, Rul.t) => Rul.t=?, + ~f_any: (Any.t => Any.t, Any.t) => Any.t=?, + ~f_proof: (Proof.t => Proof.t, Proof.t) => Proof.t=?, + t + ) => + t; +} = { + [@deriving (show({with_path: false}), sexp, yojson)] + type term = proof_term; + [@deriving (show({with_path: false}), sexp, yojson)] + type t = proof_t; + + let map_term = + ( + ~f_exp=continue, + ~f_pat=continue, + ~f_typ=continue, + ~f_tpat=continue, + ~f_rul=continue, + ~f_any=continue, + ~f_proof=continue, + x, + ) => { + let exp_map_term = + Exp.map_term(~f_exp, ~f_pat, ~f_typ, ~f_tpat, ~f_rul, ~f_any, ~f_proof); + let pat_map_term = + Pat.map_term(~f_exp, ~f_pat, ~f_typ, ~f_tpat, ~f_rul, ~f_any, ~f_proof); + let any_map_term = + Any.map_term(~f_exp, ~f_pat, ~f_typ, ~f_tpat, ~f_rul, ~f_any, ~f_proof); + let proof_map_term = + Proof.map_term( + ~f_exp, + ~f_pat, + ~f_typ, + ~f_tpat, + ~f_rul, + ~f_any, + ~f_proof, + ); + let rec_call = ({term, _} as p: t) => { + ...p, + term: + switch (term) { + | EmptyHole + | Invalid(_) => term + | MultiHole(things) => MultiHole(List.map(~f=any_map_term, things)) + | Seq(p1, p2) => Seq(proof_map_term(p1), proof_map_term(p2)) + | Parens(p) => Parens(proof_map_term(p)) + | AxiomStep({direction, equality, instantiation}) => + AxiomStep({ + direction, + equality: exp_map_term(equality), + instantiation: + Option.map( + ~f=((v, i)) => (exp_map_term(v), exp_map_term(i)), + instantiation, + ), + }) + | AlgebriteStep(e) => AlgebriteStep(exp_map_term(e)) + | EvalStep => EvalStep + | Focus({ordinal, selector, body}) => + Focus({ + ordinal, + selector: exp_map_term(selector), + body: proof_map_term(body), + }) + | Cases(e, cases) => + Cases( + exp_map_term(e), + List.map( + ~f=((pt, body)) => (pat_map_term(pt), proof_map_term(body)), + cases, + ), + ) + | Induction(e, cases) => + Induction( + exp_map_term(e), + List.map( + ~f=((pt, body)) => (pat_map_term(pt), proof_map_term(body)), + cases, + ), + ) + | Forall(x, body) => Forall(pat_map_term(x), proof_map_term(body)) + | Funext(x, body) => Funext(pat_map_term(x), proof_map_term(body)) + | Assume(e, name, body) => + Assume( + exp_map_term(e), + Option.map(~f=pat_map_term, name), + proof_map_term(body), + ) + | Alias(x, e, body) => + Alias(pat_map_term(x), exp_map_term(e), proof_map_term(body)) + | Generalize(e, body) => + Generalize(exp_map_term(e), proof_map_term(body)) + | Revert(e, inst, body) => + Revert( + exp_map_term(e), + Option.map( + ~f=((v, i)) => (exp_map_term(v), exp_map_term(i)), + inst, + ), + proof_map_term(body), + ) + | Have(e, name, sub, body) => + Have( + exp_map_term(e), + Option.map(~f=pat_map_term, name), + proof_map_term(sub), + proof_map_term(body), + ) + }, + }; + x |> f_proof(rec_call); + }; +} and StepperFilterKind: { [@deriving (show({with_path: false}), sexp, yojson)] type t = stepper_filter_kind_t; @@ -1239,6 +1531,7 @@ and StepperFilterKind: { ~f_sig: (Sig.t => Sig.t, Sig.t) => Sig.t=?, ~f_mpat: (MPat.t => MPat.t, MPat.t) => MPat.t=?, ~f_any: (Any.t => Any.t, Any.t) => Any.t=?, + ~f_proof: (Proof.t => Proof.t, Proof.t) => Proof.t=?, t ) => t; @@ -1270,6 +1563,7 @@ and StepperFilterKind: { ~f_sig=continue, ~f_mpat=continue, ~f_any=continue, + ~f_proof=continue, ) => { let exp_map_term = Exp.map_term( @@ -1282,6 +1576,7 @@ and StepperFilterKind: { ~f_sig, ~f_mpat, ~f_any, + ~f_proof, ); ( fun diff --git a/src/language/term/Typ.re b/src/language/term/Typ.re index 4358ad1adc..d58350ebe1 100644 --- a/src/language/term/Typ.re +++ b/src/language/term/Typ.re @@ -23,7 +23,6 @@ type cls = | Projector | Rec | Poly - | ProofOf | ProdProjection | ProdExtension | Sig; @@ -98,7 +97,6 @@ let cls_of_term: Grammar.typ_term('a) => cls = | Sum(_) => Sum | Rec(_) => Rec | Poly(_) => Poly - | ProofOf(_) => ProofOf | ProdProjection(_) => ProdProjection | ProdExtension(_) => ProdExtension | Sig(_) => Sig; @@ -125,7 +123,6 @@ let show_cls: cls => string = | Projector => "Projector type" | Rec => "Recursive type" | Poly => "Type quantifier" - | ProofOf => "Proof type" | ProdProjection => "Tuple projection" | ProdExtension => "Tuple extension" | Sig => "Signature type"; @@ -146,7 +143,6 @@ let rec is_arrow = (typ: t) => { | Var(_) | Sum(_) | Poly(_) - | ProofOf(_) | Rec(_) | ProdProjection(_) | ProdExtension(_) @@ -161,8 +157,7 @@ let rec has_fun = (typ: t) => | TupLabel(_, typ) | ProdProjection(typ, _) => has_fun(typ) | Arrow(_) - | Poly(_) - | ProofOf(_) => true + | Poly(_) => true | Unknown(_) | Atom(_) | DrvQuoteTy(_) @@ -247,7 +242,6 @@ let rec strip_wrappers = (ty: t): t => | TupLabel(_) | Rec(_) | Poly(_) - | ProofOf(_) | ProdProjection(_) | ProdExtension(_) | Sig(_) => ty @@ -275,7 +269,6 @@ let rec match_tup_optional_label = (ty: t) => | Label(_) | Rec(_) | Poly(_) - | ProofOf(_) | ProdProjection(_) | ProdExtension(_) | Sig(_) => None @@ -307,7 +300,6 @@ let rec free_vars = (~bound=[], ty: t): list(Var.t) => | Rec(x, ty) | Poly(x, ty) => free_vars(~bound=(x |> TPat.tyvar_of_utpat |> Option.to_list) @ bound, ty) - | ProofOf(_) => [] | Sig(_) => [] }; @@ -346,7 +338,6 @@ let rec count_unknowns = (ty: t): int => | Parens(ty) | Projector(_, ty) => count_unknowns(ty) | Poly(_, ty) => count_unknowns(ty) - | ProofOf(_) => 0 | ExplicitNonlabel | Label(_) => 0 | TupLabel(_, ty) => count_unknowns(ty) @@ -419,7 +410,6 @@ let rec subst = (s: t, x: TPat.t, ty: t): t => { ProdProjection(subst(s, x, t1), subst(s, x, t2)) |> rewrap | ProdExtension(t1, t2) => ProdExtension(subst(s, x, t1), subst(s, x, t2)) |> rewrap - | ProofOf(e) => ProofOf(e) |> rewrap | Sig(_) => ty | DrvQuoteTy(_) => ty }; @@ -457,7 +447,6 @@ let non_contractive = (ty: t): option(TPat.t) => { | Label(_) | TupLabel(_) | Poly(_) - | ProofOf(_) | ProdProjection(_) | ProdExtension(_) | Sig(_) => None @@ -491,7 +480,6 @@ let rec unroll = (ty: t): option(t) => | Parens(_) | Projector(_) | Poly(_) - | ProofOf(_) | ProdProjection(_) | ProdExtension(_) | Sig(_) => Some(ty) @@ -723,7 +711,6 @@ let rec normalize = (~rec_counter=0, ~expand=_ => true, ctx: Ctx.t, ty: t): t => Rec(tpat, normalize(Ctx.extend_dummy_tvar(ctx, tpat), ty)) |> rewrap | Poly(name, ty) => Poly(name, normalize(Ctx.extend_dummy_tvar(ctx, name), ty)) |> rewrap - | ProofOf(_) => ty // Todo: should we normalize this? | Sig(items) => /* Desugar signature to labeled tuple type: { let x : Int; let y : Bool } => (x=Int, y=Bool) @@ -814,8 +801,7 @@ let rec desugar_sig = (ctx: Ctx.t, ty: t): t => { | DrvQuoteTy(_) | Var(_) | ExplicitNonlabel - | Label(_) - | ProofOf(_) => ty + | Label(_) => ty }; }; @@ -837,8 +823,7 @@ let has_fun_up_to_aliases = (ctx: Ctx.t, ty: t): bool => { | TupLabel(_, t) | ProdProjection(t, _) => go(~depth=depth + 1, ctx, t) | Arrow(_) - | Poly(_) - | ProofOf(_) => true + | Poly(_) => true | Var(x) => switch (Ctx.lookup_alias(ctx, x)) { | Some(t) => go(~depth=depth + 1, ctx, t) @@ -1118,9 +1103,6 @@ let rec meet = let+ ty = meet'(ty1, ty2); List(ty) |> temp; | (List(_), _) => None - | (ProofOf(e1), ProofOf(e2)) => - Equality.semantic.exp(e1, e2) ? Some(ty1) : None - | (ProofOf(_), _) => None // We would prefer for this to be a sort difference and never appear in a meet. // These get marked in statics but that does not remove them from the utyp's propagated on parents. | (ExplicitNonlabel, _) => None @@ -1145,7 +1127,6 @@ let rec match_synswitch = (t1: t, t2: t) => { | (ExplicitNonlabel, _) | (Var(_), _) | (Rec(_), _) - | (ProofOf(_), _) | (ProdProjection(_), _) | (ProdExtension(_), _) => t1 // These might @@ -1224,7 +1205,6 @@ let rec get_sum_constructors = (ctx: Ctx.t, ty: t): option(sum_map) => { | Projector(_) | Rec(_) | Poly(_) - | ProofOf(_) | ProdProjection(_) | ProdExtension(_) | Sig(_) => None @@ -1247,7 +1227,6 @@ let rec is_syn = (ty: t): bool => | Var(_) | Rec(_) | Poly(_) - | ProofOf(_) | List(_) | Arrow(_) | Prod(_) @@ -1271,7 +1250,6 @@ let rec is_ana_atom = (ty: t) => | Var(_) | Rec(_) | Poly(_) - | ProofOf(_) | List(_) | Arrow(_) | Prod(_) @@ -1289,7 +1267,6 @@ let rec is_syn_plus = (ty: t): bool => | Unknown(SynSwitch) => true | Arrow(t1, t2) => is_syn(t1) && is_syn_plus(t2) | Poly(_, t) => is_syn(t) - | ProofOf(_) | Unknown(_) | Atom(_) | DrvQuoteTy(_) @@ -1326,7 +1303,6 @@ let rec needs_parens = (ty: t): bool => | Label(_) | DrvQuoteTy(_) | List(_) /* is already wrapped in [] */ - | ProofOf(_) | Var(_) => false | ProdProjection(_, _) | ProdExtension(_, _) @@ -1394,7 +1370,6 @@ let rec pretty_print = (ty: t): string => "rec " ++ pretty_print_tvar(tv) ++ " -> " ++ pretty_print(t) | Poly(tv, t) => "poly " ++ pretty_print_tvar(tv) ++ " -> " ++ pretty_print(t) - | ProofOf(_e) => "yes indeed" | Sig(items) => let sig_item_str = (item: Sig.t) => switch (item.term) { @@ -1488,7 +1463,6 @@ let all_ids = (ty: t): list(Id.t) => { | Label(_) | ExplicitNonlabel | Var(_) - | ProofOf(_) | Sig(_) => () }; }; @@ -1590,9 +1564,6 @@ let rec diff = | (Poly(tp1, t1), Poly(tp2, t2)) when Equality.syntactic.tpat(tp1, tp2) => diff(~ctx?, t1, t2) | (Poly(_), _) => get_ids() - | (ProofOf(e1), ProofOf(e2)) => - Equality.syntactic.exp(e1, e2) ? [] : get_ids() - | (ProofOf(_), _) => get_ids() | (Arrow(t1a, t1b), Arrow(t2a, t2b)) => diff(~ctx?, t1a, t2a) @ diff(~ctx?, t1b, t2b) | (Arrow(_), _) => get_ids() diff --git a/src/menhirParser/AST.re b/src/menhirParser/AST.re index f81311593a..eb80489630 100644 --- a/src/menhirParser/AST.re +++ b/src/menhirParser/AST.re @@ -24,7 +24,8 @@ type op_bin_float = [@deriving (show({with_path: false}), sexp, qcheck, eq)] type op_bin_bool = | And - | Or; + | Or + | Implies; [@deriving (show({with_path: false}), sexp, qcheck, eq)] type op_bin_int = @@ -98,7 +99,6 @@ type typ = | InvalidTyp(string) | PolyType(tpat, typ) | RecType(tpat, typ) - | ProofOfType(exp) | LabelType(string) | ExplicitNonlabel | TupLabelType(typ, typ) @@ -140,8 +140,7 @@ and exp = | BinExp(exp, bin_op, exp) | UnOp(op_un, exp) | Let(pat, exp, exp) - | Theorem(pat, exp, exp) - | ProofObject(exp) + | Theorem(pat, exp, proof, exp) | Fun(pat, exp, option(string)) | ForallExp(pat, exp) | CaseExp(exp, list((pat, exp))) @@ -175,6 +174,51 @@ and exp = | Module(list(mod_item)) | ModuleExp(pat, exp, exp) +/* The proof sort (`proof_term` in Grammar.re). Like the tiles, the + `with` and named variants are separate constructors, and `AxiomStep`'s + direction is encoded by the two ProofAxiom* constructors: + `rewrite` applies its equality left-to-right (Direction.Right), + `rewrite <-` right-to-left (Direction.Left). */ +and proof = + | EmptyHoleProof + | ProofSeq(proof, proof) + | ParenProof(proof) + | ProofForall(pat, proof) + /* `funext => `: functional extensionality intro. */ + | ProofFunext(pat, proof) + | ProofAssume(exp, proof) + /* `assume = => `: names the hypothesis, which is + otherwise `assume`. */ + | ProofAssumeNamed(pat, exp, proof) + /* `alias = => `: give a known fact a second name, + so it stays citable after its own name is shadowed. */ + | ProofAlias(pat, exp, proof) + | ProofGeneralize(exp, proof) + | ProofRevert(exp, proof) + /* The extra (var, exp) pair is the `with = ` clause. */ + | ProofRevertWith(exp, exp, exp, proof) + /* `have proof => `: the asserted proposition, + its proof, and the body it is a hypothesis for. */ + | ProofHave(exp, proof, proof) + /* `have = proof => ` */ + | ProofHaveNamed(pat, exp, proof, proof) + /* `rewrite end` */ + | ProofAxiom(exp) + | ProofAxiomRev(exp) + /* (equality, var, instantiation): `rewrite with = + end`. */ + | ProofAxiomWith(exp, exp, exp) + | ProofAxiomRevWith(exp, exp, exp) + /* `algebra end` */ + | ProofAlgebrite(exp) + | ProofEval + /* `from [at ] do end` */ + | ProofFocus(option(int), exp, proof) + /* `cases | => ... end` */ + | ProofCases(exp, list((pat, proof))) + /* `induction | => ... end` */ + | ProofInduction(exp, list((pat, proof))) + and mod_item = | ModItemLet(pat, exp) | ModItemType(tpat, typ) @@ -854,7 +898,7 @@ let rec shrink_exp: QCheck.Shrink.t(exp) = let* shrunk = shrink_pat(p); return(Let(shrunk, e1, e2)); } - | Theorem(p, e1, e2) => + | Theorem(p, e1, pf, e2) => of_list([e1, e2]) <+> ( switch (pat_typ_opt(p)) { @@ -864,19 +908,16 @@ let rec shrink_exp: QCheck.Shrink.t(exp) = ) <+> { let* shrunk = shrink_exp(e1); - return(Theorem(p, shrunk, e2)); + return(Theorem(p, shrunk, pf, e2)); } <+> { let* shrunk = shrink_exp(e2); - return(Theorem(p, e1, shrunk)); + return(Theorem(p, e1, pf, shrunk)); } <+> { let* shrunk = shrink_pat(p); - return(Theorem(shrunk, e1, e2)); + return(Theorem(shrunk, e1, pf, e2)); } - | ProofObject(t) => - let* shrunk = shrink_exp(t); - return(ProofObject(shrunk)); | ForallExp(pat, e) => return(e) <+> ( @@ -1360,9 +1401,6 @@ and shrink_typ: QCheck.Shrink.t(typ) = return(RecType(tpat, shrunk)); } | ExplicitNonlabel => return(ExplicitNonlabel: typ) - | ProofOfType(e) => - let* shrunk = shrink_exp(e); - return(ProofOfType(shrunk)); | LabelType(x) => shrink_non_empty_string(x) >|= ((x: string) => LabelType(x)) | TupLabelType(t1, t2) => diff --git a/src/menhirParser/Conversion.re b/src/menhirParser/Conversion.re index 06cba493ea..9662a84344 100644 --- a/src/menhirParser/Conversion.re +++ b/src/menhirParser/Conversion.re @@ -92,6 +92,7 @@ module Operators = { switch (op_bool) { | And => And | Or => Or + | Implies => Implies }, ) | String(op_string) => @@ -167,6 +168,7 @@ module Operators = { switch (op) { | And => And | Or => Or + | Implies => Implies }; }; @@ -252,9 +254,13 @@ module rec Exp: { } | Let(p, e1, e2) => let_(Pat.of_menhir_ast(p), of_menhir_ast(e1), of_menhir_ast(e2)) - | Theorem(p, e1, e2) => - theorem(Pat.of_menhir_ast(p), of_menhir_ast(e1), of_menhir_ast(e2)) - | ProofObject(t) => proof_object(Exp.of_menhir_ast(t)) + | Theorem(p, e1, pf, e2) => + theorem( + Pat.of_menhir_ast(p), + of_menhir_ast(e1), + Proof.of_menhir_ast(pf), + of_menhir_ast(e2), + ) | ForallExp(p, e) => forall(Pat.of_menhir_ast(p), of_menhir_ast(e)) | FixF(p, e) => fix_f(Pat.of_menhir_ast(p), of_menhir_ast(e), None) | TypFun(t, e) => @@ -371,9 +377,8 @@ module rec Exp: { | Tuple(l) => TupleExp(List.map(~f=of_core, l)) | TupleExtension(e1, e2) => TupleExp([of_core(e1), of_core(e2)]) | Let(p, e1, e2) => Let(Pat.of_core(p), of_core(e1), of_core(e2)) - | Theorem(p, e1, e2) => - Theorem(Pat.of_core(p), of_core(e1), of_core(e2)) - | ProofObject(t) => ProofObject(Exp.of_core(t)) + | Theorem(p, e1, pf, e2) => + Theorem(Pat.of_core(p), of_core(e1), Proof.of_core(pf), of_core(e2)) | Forall(p, e) => ForallExp(Pat.of_core(p), Exp.of_core(e)) | FixF(p, e, _) => FixF(Pat.of_core(p), of_core(e)) | TypFun(tp, e, _) => TypFun(TPat.of_core(tp), of_core(e)) @@ -521,7 +526,6 @@ and Typ: { sum(converted_terms); | PolyType(tp, t) => poly(TPat.of_menhir_ast(tp), of_menhir_ast(t)) | RecType(tp, t) => rec_(TPat.of_menhir_ast(tp), of_menhir_ast(t)) - | ProofOfType(e) => proof_of(Exp.of_menhir_ast(e)) | Sig(items) => { annotation: false, term: Sig(List.map(~f=SigItem.of_menhir_ast, items)), @@ -556,7 +560,6 @@ and Typ: { | Unknown(p) => UnknownType(of_core_type_provenance(p)) | Poly(tp, t) => PolyType(TPat.of_core(tp), of_core(t)) | Rec(tp, t) => RecType(TPat.of_core(tp), of_core(t)) - | ProofOf(e) => ProofOfType(Exp.of_core(e)) | Parens(t) => ParenTyp(of_core(t)) | Label(s) => LabelType(s) | ExplicitNonlabel => (ExplicitNonlabel: AST.typ) @@ -608,6 +611,155 @@ and TPat: { }; }; } +and Proof: { + let of_menhir_ast: AST.proof => IndicatedG.proof; + let of_core: IndicatedG.proof => AST.proof; +} = { + open IndicatedG.Proof; + let rec of_menhir_ast = (pf: AST.proof): IndicatedG.proof => { + let inst = (v, i) => (Exp.of_menhir_ast(v), Exp.of_menhir_ast(i)); + let axiom = (direction, ~instantiation=?, eq) => + axiom_step( + ~direction, + ~equality=Exp.of_menhir_ast(eq), + ~instantiation, + (), + ); + let cases = + List.map(~f=((p, body)) => + (Pat.of_menhir_ast(p), of_menhir_ast(body)) + ); + switch (pf) { + | EmptyHoleProof => empty_hole() + | ProofSeq(p1, p2) => seq(of_menhir_ast(p1), of_menhir_ast(p2)) + | ParenProof(p) => parens(of_menhir_ast(p)) + | ProofForall(p, body) => + forall(Pat.of_menhir_ast(p), of_menhir_ast(body)) + | ProofFunext(p, body) => + funext(Pat.of_menhir_ast(p), of_menhir_ast(body)) + | ProofAssume(e, body) => + assume(Exp.of_menhir_ast(e), of_menhir_ast(body)) + | ProofAssumeNamed(x, e, body) => + assume( + ~name=Some(Pat.of_menhir_ast(x)), + Exp.of_menhir_ast(e), + of_menhir_ast(body), + ) + | ProofAlias(x, e, body) => + alias( + Pat.of_menhir_ast(x), + Exp.of_menhir_ast(e), + of_menhir_ast(body), + ) + | ProofGeneralize(e, body) => + generalize(Exp.of_menhir_ast(e), of_menhir_ast(body)) + | ProofRevert(e, body) => + revert(Exp.of_menhir_ast(e), of_menhir_ast(body)) + | ProofHave(e, sub, body) => + have(Exp.of_menhir_ast(e), of_menhir_ast(sub), of_menhir_ast(body)) + | ProofHaveNamed(x, e, sub, body) => + have( + ~name=Some(Pat.of_menhir_ast(x)), + Exp.of_menhir_ast(e), + of_menhir_ast(sub), + of_menhir_ast(body), + ) + | ProofRevertWith(e, v, i, body) => + revert( + ~instantiation=Some(inst(v, i)), + Exp.of_menhir_ast(e), + of_menhir_ast(body), + ) + | ProofAxiom(eq) => axiom(Util.Direction.Right, eq) + | ProofAxiomRev(eq) => axiom(Util.Direction.Left, eq) + | ProofAxiomWith(eq, v, i) => + axiom(Util.Direction.Right, ~instantiation=inst(v, i), eq) + | ProofAxiomRevWith(eq, v, i) => + axiom(Util.Direction.Left, ~instantiation=inst(v, i), eq) + | ProofAlgebrite(e) => algebrite_step(Exp.of_menhir_ast(e)) + | ProofEval => eval_step() + | ProofFocus(ordinal, selector, body) => + focus(~ordinal, Exp.of_menhir_ast(selector), of_menhir_ast(body)) + | ProofCases(scrut, cs) => + IndicatedG.Proof.cases(Exp.of_menhir_ast(scrut), cases(cs)) + | ProofInduction(scrut, cs) => + induction(Exp.of_menhir_ast(scrut), cases(cs)) + }; + }; + + let rec of_core = (pf: IndicatedG.proof): AST.proof => { + switch (pf.term) { + | EmptyHole => EmptyHoleProof + /* No menhir syntax for a broken proof term; the empty hole is the + closest well-formed stand-in. */ + | Invalid(_) + | MultiHole(_) => EmptyHoleProof + | Seq(p1, p2) => ProofSeq(of_core(p1), of_core(p2)) + | Parens(p) => ParenProof(of_core(p)) + | Forall(p, body) => ProofForall(Pat.of_core(p), of_core(body)) + | Funext(p, body) => ProofFunext(Pat.of_core(p), of_core(body)) + | Assume(e, None, body) => ProofAssume(Exp.of_core(e), of_core(body)) + | Assume(e, Some(x), body) => + ProofAssumeNamed(Pat.of_core(x), Exp.of_core(e), of_core(body)) + | Alias(x, e, body) => + ProofAlias(Pat.of_core(x), Exp.of_core(e), of_core(body)) + | Generalize(e, body) => ProofGeneralize(Exp.of_core(e), of_core(body)) + | Have(e, None, sub, body) => + ProofHave(Exp.of_core(e), of_core(sub), of_core(body)) + | Have(e, Some(x), sub, body) => + ProofHaveNamed( + Pat.of_core(x), + Exp.of_core(e), + of_core(sub), + of_core(body), + ) + | Revert(e, None, body) => ProofRevert(Exp.of_core(e), of_core(body)) + | Revert(e, Some((v, i)), body) => + ProofRevertWith( + Exp.of_core(e), + Exp.of_core(v), + Exp.of_core(i), + of_core(body), + ) + | AxiomStep({direction, equality, instantiation}) => + /* `rewrite` applies the equality left-to-right, `rewrite <-` + right-to-left; a `with` clause picks the -With variants. */ + let eq = Exp.of_core(equality); + switch (direction, instantiation) { + | (Right, None) => AST.ProofAxiom(eq) + | (Left, None) => AST.ProofAxiomRev(eq) + | (Right, Some((v, i))) => + AST.ProofAxiomWith(eq, Exp.of_core(v), Exp.of_core(i)) + | (Left, Some((v, i))) => + AST.ProofAxiomRevWith(eq, Exp.of_core(v), Exp.of_core(i)) + }; + | AlgebriteStep(e) => ProofAlgebrite(Exp.of_core(e)) + | EvalStep => ProofEval + | Focus({ordinal, selector, body}) => + ProofFocus( + Option.map(~f=Language.Annotated.term_of, ordinal), + Exp.of_core(selector), + of_core(body), + ) + | Cases(scrut, cases) => + ProofCases( + Exp.of_core(scrut), + List.map( + ~f=((p, body)) => (Pat.of_core(p), of_core(body)), + cases, + ), + ) + | Induction(scrut, cases) => + ProofInduction( + Exp.of_core(scrut), + List.map( + ~f=((p, body)) => (Pat.of_core(p), of_core(body)), + cases, + ), + ) + }; + }; +} and Pat: { let of_menhir_ast: AST.pat => IndicatedG.pat; let of_core: IndicatedG.pat => AST.pat; diff --git a/src/menhirParser/Lexer.mll b/src/menhirParser/Lexer.mll index 2084a43a06..86c901bc5f 100644 --- a/src/menhirParser/Lexer.mll +++ b/src/menhirParser/Lexer.mll @@ -16,6 +16,23 @@ let pop_delim () = let semi_token () = match !delim_stack with '{' :: _ -> MOD_SEMI | _ -> SEMI_COLON +(* The prover's keywords. Matching them as separate rules overflows + ocamllex's transition table, so `identifier` looks them up instead. + The parser's `name` rule accepts most of them as names too; a word added + here needs an arm there. `step` is not a keyword: the parser reads it as + a proof step from an IDENT. *) +let prover_keywords : (string, token) Stdlib.Hashtbl.t = + let t = Stdlib.Hashtbl.create 32 in + List.iter ~f:(fun (k, v) -> Stdlib.Hashtbl.replace t k v) + [ ("theorem", THEOREM); ("proof", PROOF); ("forall", FORALL); + ("funext", FUNEXT); ("assume", ASSUME); + ("generalize", GENERALIZE); ("have", HAVE); ("revert", REVERT); + ("cases", CASES); ("induction", INDUCTION); + ("alias", ALIAS); ("rewrite", REWRITE); + ("algebra", ALGEBRA); ("with", WITH); + ("from", FROM); ("at", AT); ("do", DO) ]; + t + let advance_line lexbuf = let pos = lexbuf.lex_curr_p in let pos' = { pos with @@ -94,6 +111,9 @@ let name_rest = ['a'-'z' 'A'-'Z' '0'-'9' '_'] | nonascii (* `'` continues a variable but not a constructor, as in the editor. *) let var_rest = name_rest | '\'' let identifier = name_start var_rest* +(* `$e`, `$x`: the metavariables of focus selectors, which the editor reads + as ordinary variables. Either case may follow the `$`. *) +let metavariable = '$' (name_start | ['A'-'Z']) var_rest* let constructor_ident = ['A'-'Z'] name_rest* let sexp_string = '`' [^'`']* '`' let ints = ['0'-'9']+ @@ -140,6 +160,7 @@ rule token = | "..." { TUPLE_EXTENSION } | "." { DOT } (* Poly ops*) + | "==>" { IMPLIES } | "==" { DOUBLE_EQUAL } | "!=" { NOT_EQUAL } (* Int ops*) @@ -149,6 +170,7 @@ rule token = | "/" { DIVIDE } | "**" {POWER} | "<" { LESS_THAN} + | "<-" { LEFT_ARROW } | "<=" { LESS_THAN_EQUAL } | ">" { GREATER_THAN } | ">=" { GREATER_THAN_EQUAL } @@ -214,7 +236,11 @@ rule token = | "named_fun" {NAMED_FUN} | "poly" {POLY} | "rec" {REC} - | identifier as i { IDENT(i) } + | metavariable as i { IDENT(i) } + | identifier as i + { match Stdlib.Hashtbl.find_opt prover_keywords i with + | Some t -> t + | None -> IDENT(i) } | constructor_ident as i { CONSTRUCTOR_IDENT(i)} | eof { EOF } | _ { raise (Failure ("Lex error: unknown char: '" ^ Lexing.lexeme lexbuf ^ "'")) } diff --git a/src/menhirParser/Parser.mly b/src/menhirParser/Parser.mly index 536fff0242..0c9f843d19 100644 --- a/src/menhirParser/Parser.mly +++ b/src/menhirParser/Parser.mly @@ -117,6 +117,27 @@ open AST %token SEMI_COLON +(* Prover forms *) +%token IMPLIES +%token FORALL +%token FUNEXT +%token THEOREM +%token PROOF +%token ASSUME +%token GENERALIZE +%token HAVE +%token REVERT +%token INDUCTION +%token CASES +%token ALIAS +%token REWRITE +%token LEFT_ARROW +%token ALGEBRA +%token WITH +%token FROM +%token DO +%token AT + (* Precedences *) @@ -129,6 +150,12 @@ open AST %right DASH_ARROW %nonassoc IF_EXP +/* Proof prefix forms (`forall p =>`, `assume e =>`, `revert e =>`, + `generalize e =>`) bind at Precedence.fun_, which is looser than the + proof-sequence `;` (Precedence.semi) — so `assume e => a; b` puts the + whole sequence in the body, matching the segment parser. */ +%nonassoc PROOF_PRE + /* Flat sequences - tighter than structural forms */ %right SEMI_COLON @@ -137,6 +164,11 @@ open AST ';' for Seq. This only affects the modItemExp production. */ %nonassoc MOD_ITEM_EXP +/* Material implication: right-associative, one level looser than `||` + (Precedence.impl = 34 vs Precedence.or_ = 33), so `a == b ==> c == d` + is `(a == b) ==> (c == d)` and `a ==> b ==> c` is `a ==> (b ==> c)`. */ +%right IMPLIES + %right L_OR %right L_AND @@ -207,6 +239,7 @@ program: %inline boolOp: | L_AND { BoolOp(And) } | L_OR { BoolOp(Or) } + | IMPLIES { BoolOp(Implies) } %inline stringOp: | STRING_CONCAT { StringOp(Concat) } @@ -221,8 +254,31 @@ program: binExp: | e1 = exp; b = binOp; e2 = exp { BinExp (e1, b, e2) } +(* Proof keywords are tokens so that proof syntax can see them, but anywhere + a name goes they are ordinary names, as in the editor. Each needs an arm + here and an entry in the lexer's prover_keywords. `theorem` and `forall` + stay reserved: they open expression forms, so as names they would clash + with those forms on `(`, and the editor reserves them too. *) +name: + | i = IDENT { i } + | PROOF { "proof" } + | FUNEXT { "funext" } + | ASSUME { "assume" } + | GENERALIZE { "generalize" } + | HAVE { "have" } + | REVERT { "revert" } + | CASES { "cases" } + | INDUCTION { "induction" } + | ALIAS { "alias" } + | REWRITE { "rewrite" } + | ALGEBRA { "algebra" } + | WITH { "with" } + | FROM { "from" } + | AT { "at" } + | DO { "do" } + label: - | l = IDENT { l } + | l = name { l } | l = QUOTED_LABEL { l } (* Ill-sorted labels appear in error-demo slides: (1="hello") *) | i = INT { Bigint.to_string(i) } @@ -250,7 +306,7 @@ sumTyp: typ: | c = CONSTRUCTOR_IDENT { TypVar(c) } - | c = IDENT { TypVar(c) } + | c = name { TypVar(c) } | T_TYP; s = STRING { InvalidTyp(s) } | PROJECTOR_INVOKE; OPEN_PAREN; t = typ; CLOSE_PAREN; { t } | INT_TYPE { IntType } @@ -312,7 +368,7 @@ nonAscriptingPat: | FLOAT_TYPE { ConstructorPat("Float", None) } | BOOL_TYPE { ConstructorPat("Bool", None) } | STRING_TYPE { ConstructorPat("String", None) } - | p = IDENT { VarPat(p) } + | p = name { VarPat(p) } | i = INT { AtomPat (Int i) } | f = FLOAT { AtomPat (Float f) } | s = STRING { AtomPat (String s)} @@ -394,7 +450,7 @@ ascTyp: | POLY; a = tpat; DASH_ARROW; t = ascTyp { PolyType(a, t) } | REC; c = tpat; DASH_ARROW; t = ascTyp { RecType(c, t) } | c = CONSTRUCTOR_IDENT { TypVar(c) } - | c = IDENT { TypVar(c) } + | c = name { TypVar(c) } | INT_TYPE { IntType } | SINT_TYPE { SIntType } | NAT_TYPE { NatType } @@ -413,7 +469,39 @@ ascTyp: production consumes. *) funExp: | FUN; p = funPat; DASH_ARROW; e1 = exp; { Fun (p, e1, None) } - | NAMED_FUN; name = IDENT; p = funPat; DASH_ARROW; e1 = exp { Fun (p, e1, Some(name)) } + | NAMED_FUN; n = name; p = funPat; DASH_ARROW; e1 = exp { Fun (p, e1, Some(n)) } + +forallExp: + | FORALL; p = funPat; DASH_ARROW; e = exp; { ForallExp (p, e) } + +(* Proof case: `| => `, the PRul analogue of `rul`. *) +prul: + | TURNSTILE; p = pat; EQUAL_ARROW; pf = proof; { (p, pf) } + +proof: + | QUESTION { EmptyHoleProof } + | pf1 = proof; SEMI_COLON; pf2 = proof { ProofSeq(pf1, pf2) } + | OPEN_PAREN; pf = proof; CLOSE_PAREN { ParenProof(pf) } + | FORALL; p = pat; EQUAL_ARROW; pf = proof { ProofForall(p, pf) } %prec PROOF_PRE + | FUNEXT; p = pat; EQUAL_ARROW; pf = proof { ProofFunext(p, pf) } %prec PROOF_PRE + | ASSUME; e = exp; EQUAL_ARROW; pf = proof { ProofAssume(e, pf) } %prec PROOF_PRE + | ASSUME; x = name; SINGLE_EQUAL; e = exp; EQUAL_ARROW; pf = proof { ProofAssumeNamed(VarPat(x), e, pf) } %prec PROOF_PRE + | ALIAS; x = pat; SINGLE_EQUAL; e = exp; EQUAL_ARROW; pf = proof { ProofAlias(x, e, pf) } %prec PROOF_PRE + | GENERALIZE; e = exp; EQUAL_ARROW; pf = proof { ProofGeneralize(e, pf) } %prec PROOF_PRE + | HAVE; e = exp; PROOF; sub = proof; EQUAL_ARROW; pf = proof { ProofHave(e, sub, pf) } %prec PROOF_PRE + | HAVE; x = name; SINGLE_EQUAL; e = exp; PROOF; sub = proof; EQUAL_ARROW; pf = proof { ProofHaveNamed(VarPat(x), e, sub, pf) } %prec PROOF_PRE + | REVERT; e = exp; EQUAL_ARROW; pf = proof { ProofRevert(e, pf) } %prec PROOF_PRE + | REVERT; e = exp; WITH; v = exp; SINGLE_EQUAL; i = exp; EQUAL_ARROW; pf = proof { ProofRevertWith(e, v, i, pf) } %prec PROOF_PRE + | REWRITE; eq = exp; END { ProofAxiom(eq) } + | REWRITE; LEFT_ARROW; eq = exp; END { ProofAxiomRev(eq) } + | REWRITE; eq = exp; WITH; v = exp; SINGLE_EQUAL; i = exp; END { ProofAxiomWith(eq, v, i) } + | REWRITE; LEFT_ARROW; eq = exp; WITH; v = exp; SINGLE_EQUAL; i = exp; END { ProofAxiomRevWith(eq, v, i) } + | ALGEBRA; e = exp; END { ProofAlgebrite(e) } + | x = IDENT { if String.equal x "step" then ProofEval else failwith ("Parse error: not a proof step: " ^ x) } + | FROM; sel = exp; DO; pf = proof; END { ProofFocus(None, sel, pf) } + | FROM; sel = exp; AT; n = INT; DO; pf = proof; END { ProofFocus(Some(Bigint.to_int_exn n), sel, pf) } + | CASES; e = exp; cases = list(prul); END { ProofCases(e, cases) } + | INDUCTION; e = exp; cases = list(prul); END { ProofInduction(e, cases) } %inline ifExp: @@ -429,7 +517,7 @@ tpat: | TP_TPAT; s = STRING {InvalidTPat(s)} | p = PROJECTOR_INVOKE {InvalidTPat(p)} | QUESTION {EmptyHoleTPat} - | v = IDENT {VarTPat v} + | v = name {VarTPat v} | v = CONSTRUCTOR_IDENT {VarTPat v} unExp: @@ -445,7 +533,7 @@ exp: | b = binExp { b } | i = INT { Atom (Int i) } | f = FLOAT { Atom (Float f) } - | v = IDENT { Var v } + | v = name { Var v } | l = LIVELIT_IDENT { LivelitName l } (* Base-type keywords are ordinary constructors in exp position (HTML's Int/Float/Bool/String nodes) — MakeTerm parity. *) @@ -481,13 +569,15 @@ exp: | LET; p1 = pat; COMMA; ps = separated_nonempty_list(COMMA, pat); SINGLE_EQUAL; e1 = exp; IN; e2 = exp { Let (TuplePat(p1 :: ps), e1, e2) } %prec LET_EXP | LET; i = pat; SINGLE_EQUAL; e1 = exp; COMMA; es = separated_nonempty_list(COMMA, exp); IN; e2 = exp { Let (i, TupleExp(e1 :: es), e2) } %prec LET_EXP | LET; p1 = pat; COMMA; ps = separated_nonempty_list(COMMA, pat); SINGLE_EQUAL; e1 = exp; COMMA; es = separated_nonempty_list(COMMA, exp); IN; e2 = exp { Let (TuplePat(p1 :: ps), TupleExp(e1 :: es), e2) } %prec LET_EXP - | MODULE; i = IDENT; SINGLE_EQUAL; e1 = exp; IN; e2 = exp { ModuleExp(VarPat(i), e1, e2) } %prec LET_EXP + | MODULE; i = name; SINGLE_EQUAL; e1 = exp; IN; e2 = exp { ModuleExp(VarPat(i), e1, e2) } %prec LET_EXP | MODULE; c = CONSTRUCTOR_IDENT; SINGLE_EQUAL; e1 = exp; IN; e2 = exp { ModuleExp(VarPat(c), e1, e2) } %prec LET_EXP - | MODULE; i = IDENT; COLON; t = typ; SINGLE_EQUAL; e1 = exp; IN; e2 = exp { ModuleExp(AscPat(VarPat(i), t), e1, e2) } %prec LET_EXP + | MODULE; i = name; COLON; t = typ; SINGLE_EQUAL; e1 = exp; IN; e2 = exp { ModuleExp(AscPat(VarPat(i), t), e1, e2) } %prec LET_EXP | MODULE; c = CONSTRUCTOR_IDENT; COLON; t = typ; SINGLE_EQUAL; e1 = exp; IN; e2 = exp { ModuleExp(AscPat(VarPat(c), t), e1, e2) } %prec LET_EXP | i = ifExp { i } | TRUE { Atom (Bool true) } | f = funExp {f} + | f = forallExp {f} + | THEOREM; p = pat; SINGLE_EQUAL; e1 = exp; PROOF; pf = proof; IN; e2 = exp { Theorem (p, e1, pf, e2) } %prec LET_EXP | FALSE { Atom (Bool false) } | FIX; p = funPat; DASH_ARROW; e = exp { FixF(p, e) } | TYP_FUN; t = tpat; DASH_ARROW; e = exp {TypFun(t, e)} @@ -518,9 +608,9 @@ modItemExp: modItem: | LET; i = pat; SINGLE_EQUAL; e = modItemExp { ModItemLet(i, e) } - | MODULE; i = IDENT; SINGLE_EQUAL; e = modItemExp { ModItemModule(VarPat(i), e) } + | MODULE; i = name; SINGLE_EQUAL; e = modItemExp { ModItemModule(VarPat(i), e) } | MODULE; c = CONSTRUCTOR_IDENT; SINGLE_EQUAL; e = modItemExp { ModItemModule(VarPat(c), e) } - | MODULE; i = IDENT; COLON; t = typ; SINGLE_EQUAL; e = modItemExp { ModItemModule(AscPat(VarPat(i), t), e) } + | MODULE; i = name; COLON; t = typ; SINGLE_EQUAL; e = modItemExp { ModItemModule(AscPat(VarPat(i), t), e) } | MODULE; c = CONSTRUCTOR_IDENT; COLON; t = typ; SINGLE_EQUAL; e = modItemExp { ModItemModule(AscPat(VarPat(c), t), e) } | TYP; tp = tpat; SINGLE_EQUAL; ty = typ { ModItemType(tp, ty) } | e = modItemExp { ModItemExp(e) } diff --git a/src/util/Calc.re b/src/util/Calc.re index 1f4d4ef1e0..ea2f527c2c 100644 --- a/src/util/Calc.re +++ b/src/util/Calc.re @@ -49,6 +49,12 @@ let get_value = (x: t('a)): 'a => | NewValue(x) => x }; +let map = (f: 'a => 'b, x: t('a)): t('b) => + switch (x) { + | OldValue(x) => OldValue(f(x)) + | NewValue(x) => NewValue(f(x)) + }; + let map_if_new = (f: 'a => 'a, x: t('a)): t('a) => switch (x) { | OldValue(x) => OldValue(x) diff --git a/src/util/FloatingElement.re b/src/util/FloatingElement.re index d224fe1cf6..32d8359585 100644 --- a/src/util/FloatingElement.re +++ b/src/util/FloatingElement.re @@ -168,7 +168,9 @@ let update_all = (): unit => { }; /* Setup scroll listener on #main to update floating elements. - This ensures floating elements stay positioned correctly during scroll. */ + This ensures floating elements stay positioned correctly during scroll. + Scroll events don't bubble, so the listener captures, to also hear the + scrollers inside #main (a cell's code scrolls sideways in its own box). */ let scroll_listener_attached = ref(false); let setup_scroll_listener = (): unit => @@ -183,7 +185,7 @@ let setup_scroll_listener = (): unit => update_all(); (); }); - let _ = main_coerced##addEventListener("scroll", handler); + let _ = main_coerced##addEventListener("scroll", handler, Js._true); (); }; }; diff --git a/src/util/FloatingElement.rei b/src/util/FloatingElement.rei index dc1d26310e..9e5b05b0ba 100644 --- a/src/util/FloatingElement.rei +++ b/src/util/FloatingElement.rei @@ -16,6 +16,6 @@ /* Position every `.floating-fixed` in the document. Call after each render. */ let update_all: unit => unit; -/* Keep floating elements positioned while `#main` scrolls. Call once at - startup; repeat calls are ignored. */ +/* Keep floating elements positioned while `#main`, or a scroller inside it, + scrolls. Call once at startup; repeat calls are ignored. */ let setup_scroll_listener: unit => unit; diff --git a/src/util/JsUtil.re b/src/util/JsUtil.re index 6563547a2c..09cf0eb103 100644 --- a/src/util/JsUtil.re +++ b/src/util/JsUtil.re @@ -393,6 +393,56 @@ let adjust_scroll = (container: Js.t(Dom_html.element), delta: float) => container##.scrollTop := int_of_float(target); }; +/* A cell's code scrolls sideways in a box of its own (CellEditor.View), + * with any line numbers stuck to the box's left edge. */ +module CodeScroll = { + let class_name = "code-scroll"; + + let containing = + (el: Js.t(Dom_html.element)): option(Js.t(Dom_html.element)) => + find_ancestor_with_class(el, class_name); + + /* The viewport x-range in which the scroller shows code: its box, less + * the line numbers. */ + let visible_x = (scroller: Js.t(Dom_html.element)): (float, float) => { + let rect = scroller##getBoundingClientRect; + let line_numbers = + scroller##querySelector(Js.string(".line-numbers")) |> Js.Opt.to_option; + let left = + switch (line_numbers) { + | Some(line_numbers) => line_numbers##getBoundingClientRect##.right + | None => rect##.left + }; + (left, rect##.right); + }; + + /* Float arithmetic, as scrollLeft is sub-pixel: see + * setup_focus_bar_scroll_compensation. */ + let scroll_by = (scroller: Js.t(Dom_html.element), delta: float): unit => + if (Float.(delta != 0.)) { + let current: float = Js.Unsafe.get(scroller, Js.string("scrollLeft")); + Js.Unsafe.set(scroller, Js.string("scrollLeft"), current +. delta); + }; + + /* Scroll sideways so that el is visible, with a 10% margin. Does nothing + * for an element outside a code scroller. */ + let scroll_into_view = (el: Js.t(Dom_html.element)): unit => + switch (containing(el)) { + | None => () + | Some(scroller) => + let (left, right) = visible_x(scroller); + let margin = (right -. left) *. 0.10; + let el_rect = el##getBoundingClientRect; + let left_gap = el_rect##.left -. (left +. margin); + let right_gap = el_rect##.right -. (right -. margin); + if (Float.(left_gap < 0.)) { + scroll_by(scroller, left_gap); + } else if (Float.(right_gap > 0.)) { + scroll_by(scroller, right_gap); + }; + }; +}; + /* Scroll vertically so that el_rect is visible within the container, * with a 10% margin. Only adjusts scrollTop, never scrollLeft. */ let scroll_vertically_into_view = @@ -430,9 +480,10 @@ let scroll_vertically_into_view_ancestors = go(element_to_node(el)); }; -/* Whether any of the caret shows in its scroll container, or in the - * viewport if it has none. Read before a re-render, this is what the user - * sees now, not what the coming layout will show. */ +/* Whether any of the caret shows in its scroll container (the viewport, if + * it has none) and, sideways, in its code scroller. Read before a + * re-render, this is what the user sees now, not what the coming layout + * will show. */ let caret_in_view = (): bool => switch (get_elem_by_id_opt("caret")) { | None => false @@ -445,12 +496,20 @@ let caret_in_view = (): bool => (c##.top, c##.bottom); | None => (0., Float.of_int(Dom_html.window##.innerHeight)) }; - Float.(rect##.bottom > top && rect##.top < bottom); + let in_code_scroll = + switch (CodeScroll.containing(caret)) { + | Some(scroller) => + let (left, right) = CodeScroll.visible_x(scroller); + Float.(rect##.right > left && rect##.left < right); + | None => true + }; + Float.(rect##.bottom > top && rect##.top < bottom) && in_code_scroll; }; let scroll_cursor_into_view_if_needed = () => try({ let caret_elem = get_elem_by_id("caret"); + CodeScroll.scroll_into_view(caret_elem); switch (find_scroll_container(caret_elem)) { | Some(container) => scroll_vertically_into_view(container, caret_elem) | None => @@ -534,9 +593,10 @@ let delay = (delay: float, callback: unit => unit) => { (); }; -/* Publish #main's content width as `--main-scroll-width` (read by the cell - * width rule). Two passes: reset the var first so the cell's own prior width - * doesn't inflate the measurement, force layout, then read scrollWidth. */ +/* Publish #main's content width as `--main-scroll-width` (read by the probe + * drawer's stripe, proj-probe.css). Two passes: reset the var first so the + * stripe's own prior width doesn't inflate the measurement, force layout, + * then read scrollWidth. */ let update_main_scroll_width = () => Js.Opt.iter( Dom_html.document##getElementById(Js.string("main")), diff --git a/src/util/JsUtil.rei b/src/util/JsUtil.rei index 7243acbba6..c155a6555a 100644 --- a/src/util/JsUtil.rei +++ b/src/util/JsUtil.rei @@ -41,8 +41,24 @@ let find_ancestor_with_class: option(Js_of_ocaml.Js.t(Js_of_ocaml.Dom_html.element)); let adjust_scroll: (Js_of_ocaml.Js.t(Js_of_ocaml.Dom_html.element), float) => unit; +/** The box a cell's code scrolls sideways in. */ +module CodeScroll: { + let class_name: string; + let containing: + Js_of_ocaml.Js.t(Js_of_ocaml.Dom_html.element) => + option(Js_of_ocaml.Js.t(Js_of_ocaml.Dom_html.element)); + /** The viewport x-range in which the scroller shows code. */ + let visible_x: + Js_of_ocaml.Js.t(Js_of_ocaml.Dom_html.element) => (float, float); + let scroll_by: + (Js_of_ocaml.Js.t(Js_of_ocaml.Dom_html.element), float) => unit; +}; let caret_in_view: unit => bool; let scroll_cursor_into_view_if_needed: unit => unit; +/** Scrolls the element into view in each scrolling ancestor, vertically + * only. */ +let scroll_vertically_into_view_ancestors: + Js_of_ocaml.Js.t(Js_of_ocaml.Dom_html.element) => unit; let main_scroll_top: unit => float; let set_main_scroll_top: float => unit; module Fragment: { diff --git a/src/util/SampleAnchor.re b/src/util/SampleAnchor.re index 5493224d87..51c4b680a9 100644 --- a/src/util/SampleAnchor.re +++ b/src/util/SampleAnchor.re @@ -71,42 +71,32 @@ let capture = /* Bring the indicated sample into a comfort band, minimal motion. Margin * adapts to width: small samples get a lookahead preview; one that fits is * shown fully; one wider than the viewport aligns its left edge (read from - * the start). scrollLeft set directly — smooth scrolling queues badly. */ -let scroll_horizontally = (el: Js.t(Dom_html.element)): unit => { - let doc = Dom_html.document; - Js.Opt.iter( - doc##getElementById(Js.string("main")), - main => { - let el_rect = el##getBoundingClientRect; - let main_rect = main##getBoundingClientRect; - let vp_left = main_rect##.left; - let vp_right = main_rect##.right; - let width = vp_right -. vp_left; - let pad = 16.; - let lookahead = width *. 0.10; - let el_width = el_rect##.right -. el_rect##.left; - let m = Float.max(pad, Float.min(lookahead, width -. el_width -. pad)); - let delta = - if (Float.(el_width > width -. 2. *. pad)) { - el_rect##.left -. (vp_left +. pad); - } else if (Float.(el_rect##.left < vp_left +. m)) { - el_rect##.left -. (vp_left +. m); - } else if (Float.(el_rect##.right > vp_right -. m)) { - el_rect##.right -. (vp_right -. m); - } else { - 0.; - }; - if (Float.(delta != 0.0)) { - let sl: float = Js.Unsafe.get(main, Js.string("scrollLeft")); - Js.Unsafe.set( - main, - Js.string("scrollLeft"), - Float.max(0., sl +. delta), - ); + * the start). The viewport is that of the sample's code scroller, which is + * what scrolls a sample sideways. Scrolls directly: smooth scrolling queues + * badly. */ +let scroll_horizontally = (el: Js.t(Dom_html.element)): unit => + switch (JsUtil.CodeScroll.containing(el)) { + | None => () + | Some(scroller) => + let el_rect = el##getBoundingClientRect; + let (vp_left, vp_right) = JsUtil.CodeScroll.visible_x(scroller); + let width = vp_right -. vp_left; + let pad = 16.; + let lookahead = width *. 0.10; + let el_width = el_rect##.right -. el_rect##.left; + let m = Float.max(pad, Float.min(lookahead, width -. el_width -. pad)); + let delta = + if (Float.(el_width > width -. 2. *. pad)) { + el_rect##.left -. (vp_left +. pad); + } else if (Float.(el_rect##.left < vp_left +. m)) { + el_rect##.left -. (vp_left +. m); + } else if (Float.(el_rect##.right > vp_right -. m)) { + el_rect##.right -. (vp_right -. m); + } else { + 0.; }; - }, - ); -}; + JsUtil.CodeScroll.scroll_by(scroller, delta); + }; let consume = (): unit => switch (pending^) { diff --git a/src/web/EdgeScroll.re b/src/web/EdgeScroll.re index 39de633861..527a8111b3 100644 --- a/src/web/EdgeScroll.re +++ b/src/web/EdgeScroll.re @@ -2,11 +2,12 @@ open Js_of_ocaml; open Util; open Poly; -/* Edge-scrolling during drag-select: when the pointer is near the - * top or bottom edge of the scroll container, automatically scroll - * in that direction at a speed proportional to how close the pointer - * is to the edge. A setInterval timer drives the scrolling so it - * continues even when the mouse is stationary at the edge. +/* Edge-scrolling during drag-select: when the pointer is near an edge + * of a scroll container, automatically scroll in that direction at a + * speed proportional to how close the pointer is to the edge. #main + * scrolls up and down; the code scroller the drag is in (see + * JsUtil.CodeScroll) scrolls sideways. A setInterval timer drives the + * scrolling so it continues even when the mouse is stationary at the edge. * * On each tick, after scrolling, the on_tick callback is invoked to * update the selection. This keeps the selection in sync with the @@ -17,7 +18,9 @@ let max_speed_px = 35.0; let interval_ms = 10.0; let timer_id: ref(option(Dom_html.interval_id)) = ref(None); +let last_client_x: ref(float) = ref(0.0); let last_client_y: ref(float) = ref(0.0); +let code_scroller: ref(option(Js.t(Dom_html.element))) = ref(None); let on_tick: ref(option(unit => unit)) = ref(None); let is_active = (): bool => timer_id^ != None; @@ -32,47 +35,70 @@ let clear_timer = () => let stop = () => { clear_timer(); + last_client_x := 0.0; last_client_y := 0.0; + code_scroller := None; on_tick := None; }; -let compute_delta = (client_y: float): float => +/* Pixels per tick to scroll for a pointer at `pos` between the edges `lo` + * and `hi`: negative toward lo, positive toward hi. */ +let speed = (~lo: float, ~hi: float, pos: float): float => { + let dist_from_lo = pos -. lo; + let dist_from_hi = hi -. pos; + if (dist_from_lo < 0.0) { + -. max_speed_px; + } else if (dist_from_hi < 0.0) { + max_speed_px; + } else if (dist_from_lo < margin_px) { + let ratio = 1.0 -. dist_from_lo /. margin_px; + -. max_speed_px *. ratio; + } else if (dist_from_hi < margin_px) { + let ratio = 1.0 -. dist_from_hi /. margin_px; + max_speed_px *. ratio; + } else { + 0.0; + }; +}; + +let compute_delta_y = (client_y: float): float => switch (JsUtil.get_elem_by_id_opt("main")) { | None => 0.0 | Some(container) => let rect = container##getBoundingClientRect; - let top = rect##.top; - let bottom = rect##.bottom; - let dist_from_top = client_y -. top; - let dist_from_bottom = bottom -. client_y; - if (Float.(dist_from_top < 0.0)) { - -. max_speed_px; - } else if (dist_from_bottom < 0.0) { - max_speed_px; - } else if (dist_from_top < margin_px) { - let ratio = 1.0 -. dist_from_top /. margin_px; - -. max_speed_px *. ratio; - } else if (dist_from_bottom < margin_px) { - let ratio = 1.0 -. dist_from_bottom /. margin_px; - max_speed_px *. ratio; - } else { - 0.0; - }; + speed(~lo=rect##.top, ~hi=rect##.bottom, client_y); }; -let tick = () => - switch (JsUtil.get_elem_by_id_opt("main")) { - | None => () - | Some(container) => - let delta = compute_delta(last_client_y^); - if (!Float.equal(delta, 0.0)) { - JsUtil.adjust_scroll(container, delta); - switch (on_tick^) { - | Some(f) => f() - | None => () - }; +/* Zero once the code has no further to scroll that way: most code fits + * its scroller, and a drag near its edges shouldn't keep the timer going. */ +let compute_delta_x = (client_x: float): float => + switch (code_scroller^) { + | None => 0.0 + | Some(scroller) => + let (left, right) = JsUtil.CodeScroll.visible_x(scroller); + let delta = speed(~lo=left, ~hi=right, client_x); + let scroll_left = scroller##.scrollLeft; + /* less a pixel: scrollLeft is truncated from a sub-pixel position */ + let scroll_max = scroller##.scrollWidth - scroller##.clientWidth - 1; + let can_scroll = delta < 0.0 ? scroll_left > 0 : scroll_left < scroll_max; + can_scroll ? delta : 0.0; + }; + +let tick = () => { + let delta_x = compute_delta_x(last_client_x^); + let delta_y = compute_delta_y(last_client_y^); + if (delta_x != 0.0 || delta_y != 0.0) { + Option.iter(~f=JsUtil.CodeScroll.scroll_by(_, delta_x), code_scroller^); + Option.iter( + ~f=JsUtil.adjust_scroll(_, delta_y), + JsUtil.get_elem_by_id_opt("main"), + ); + switch (on_tick^) { + | Some(f) => f() + | None => () }; }; +}; let ensure_timer = () => switch (timer_id^) { @@ -86,11 +112,19 @@ let ensure_timer = () => timer_id := Some(id); }; -let update = (~client_y: float, ~on_scroll: unit => unit) => { +/* `container` is the code container the drag is in. */ +let update = + ( + ~container: Js.t(Dom_html.element), + ~client_x: float, + ~client_y: float, + ~on_scroll: unit => unit, + ) => { + last_client_x := client_x; last_client_y := client_y; + code_scroller := JsUtil.CodeScroll.containing(container); on_tick := Some(on_scroll); - let delta = compute_delta(client_y); - if (!Float.equal(delta, 0.0)) { + if (compute_delta_x(client_x) != 0.0 || compute_delta_y(client_y) != 0.0) { ensure_timer(); } else { clear_timer(); diff --git a/src/web/EdgeScroll.rei b/src/web/EdgeScroll.rei index 0415cd8260..08a2898892 100644 --- a/src/web/EdgeScroll.rei +++ b/src/web/EdgeScroll.rei @@ -1,11 +1,21 @@ -/* Auto-scroll of #main while a drag holds the pointer near its top or bottom - edge, faster the closer it is. Scrolling continues while the pointer is - still, so whatever tracks the drag is told after each step. */ +/* Auto-scroll while a drag holds the pointer near an edge, faster the closer + it is: of #main at its top or bottom edge, and of the code scroller the + drag is in (JsUtil.CodeScroll) at its left or right. Scrolling continues + while the pointer is still, so whatever tracks the drag is told after each + step. */ let stop: unit => unit; let is_active: unit => bool; -/** Call on every pointer move of the drag. `on_scroll` runs after each - scroll step, until the pointer leaves the edge or `stop`. */ -let update: (~client_y: float, ~on_scroll: unit => unit) => unit; +/** Call on every pointer move of the drag, with the code container the drag + is in. `on_scroll` runs after each scroll step, until the pointer leaves + the edge or `stop`. */ +let update: + ( + ~container: Js_of_ocaml.Js.t(Js_of_ocaml.Dom_html.element), + ~client_x: float, + ~client_y: float, + ~on_scroll: unit => unit + ) => + unit; diff --git a/src/web/Main.re b/src/web/Main.re index f98767bad2..da60e02a62 100644 --- a/src/web/Main.re +++ b/src/web/Main.re @@ -363,6 +363,7 @@ let start = default_model => { }; CoverageExport.install(); +CasJs.install(); switch (JsUtil.Fragment.get_current()) { | Some("debug") => DebugMode.go() diff --git a/src/web/ScrollWidth.re b/src/web/ScrollWidth.re index 3879b29090..6c19bef777 100644 --- a/src/web/ScrollWidth.re +++ b/src/web/ScrollWidth.re @@ -1,7 +1,7 @@ /* Publishes #main's effective scrollWidth as the `--main-scroll-width` CSS var - * (see JsUtil.update_main_scroll_width) so the cell background stretches under - * absolutely-positioned probe overlays/drawers, which CSS intrinsic sizing - * can't see. The measure forces two whole-document layouts (cost scales with + * (see JsUtil.update_main_scroll_width) so a probe drawer's stripe spans the + * pane, which the stripe, absolutely positioned inside the code, can't size + * itself to. The measure forces two whole-document layouts (cost scales with * probe count), so we gate on `key` and re-measure only when an input changes. */ open Js_of_ocaml; diff --git a/src/web/Worker.re b/src/web/Worker.re index b6bf31af4c..73cb704b99 100644 --- a/src/web/Worker.re +++ b/src/web/Worker.re @@ -1,2 +1,3 @@ /* Web worker thread */ +CasJs.install(~script="worker-algebrite.js", ()); WorkerServer.install_message_handler(); diff --git a/src/web/app/Cursor.re b/src/web/app/Cursor.re index 0106050820..9694a624c9 100644 --- a/src/web/app/Cursor.re +++ b/src/web/app/Cursor.re @@ -17,6 +17,10 @@ type cursor('update) = { error_ids: list(Util.Id.t), /* Context-sensitive actions for command palette and keyboard shortcuts */ contextual_actions: list(ContextualAction.t), + /* Proof check results, keyed by proof sub-term id. Used by the cursor + * inspector to show incoming/outgoing expressions for proof terms. + * Defaults to empty when no evaluation has been run yet. */ + proof_map: Language.ProofMap.t, }; let map = (f: 'a => 'b, cursor) => { @@ -48,6 +52,7 @@ let empty = { redo_action: None, error_ids: [], contextual_actions: [], + proof_map: Language.ProofMap.empty, }; let with_actions = (actions: list(ContextualAction.t), cursor) => { @@ -55,4 +60,9 @@ let with_actions = (actions: list(ContextualAction.t), cursor) => { contextual_actions: cursor.contextual_actions @ actions, }; +let with_proof_map = (proof_map: Language.ProofMap.t, cursor) => { + ...cursor, + proof_map, +}; + let (let+) = (cursor, f) => map(f, cursor); diff --git a/src/web/app/common/ProjectorView.re b/src/web/app/common/ProjectorView.re index 9c96b0cd8c..37d4dadb06 100644 --- a/src/web/app/common/ProjectorView.re +++ b/src/web/app/common/ProjectorView.re @@ -198,7 +198,8 @@ module Model = { ~editor_active: bool, ~elaborated: option(Language.Exp.t), ) => { - let {projectors, measured, term_data, selection_ids, _}: CachedSyntax.t = syntax; + let {projectors, term_data, selection_ids, _}: CachedSyntax.t = syntax; + let measured = CachedSyntax.measured(syntax); List.filter_map( ~f= ((id, _)) => { diff --git a/src/web/app/common/RefractorView.re b/src/web/app/common/RefractorView.re index 60d55bc3dd..0b565e918c 100644 --- a/src/web/app/common/RefractorView.re +++ b/src/web/app/common/RefractorView.re @@ -54,7 +54,8 @@ let mk_data = (), ) : list(ProjectorView.Model.projector_data) => { - let {measured, term_data, selection_ids, _}: CachedSyntax.t = syntax; + let {term_data, selection_ids, _}: CachedSyntax.t = syntax; + let measured = CachedSyntax.measured(syntax); /* measure + cull BEFORE building per-refractor data: in All mode there are * hundreds of refractors but few on screen, so building all then discarding dominated cost */ Id.Map.bindings(refractors) diff --git a/src/web/app/editors/EditorUtil.re b/src/web/app/editors/EditorUtil.re index 972716b21f..1d21224a1e 100644 --- a/src/web/app/editors/EditorUtil.re +++ b/src/web/app/editors/EditorUtil.re @@ -53,7 +53,6 @@ let rec append_exp = (e1: Language.Exp.t, e2: Language.Exp.t): Language.Exp.t => | BinOp(_) | BuiltinFun(_) | Asc(_) - | ProofObject(_) | Module(_) | ModuleExp(_) | Match(_) => mk_fresh(Seq(e1, e2)) @@ -66,9 +65,9 @@ let rec append_exp = (e1: Language.Exp.t, e2: Language.Exp.t): Language.Exp.t => | Let(p, edef, ebody) => let ebody' = append_exp(ebody, e2); mk(Let(p, edef, ebody'), e1); - | Theorem(p, thm, ebody) => + | Theorem(p, thm, pf, ebody) => let ebody' = append_exp(ebody, e2); - mk(Theorem(p, thm, ebody'), e1); + mk(Theorem(p, thm, pf, ebody'), e1); | TyAlias(tp, tdef, ebody) => let ebody' = append_exp(ebody, e2); mk(TyAlias(tp, tdef, ebody'), e1); diff --git a/src/web/app/editors/cell/CellEditor.re b/src/web/app/editors/cell/CellEditor.re index 51e5974882..55e11bb692 100644 --- a/src/web/app/editors/cell/CellEditor.re +++ b/src/web/app/editors/cell/CellEditor.re @@ -23,26 +23,21 @@ module Model = { result: EvalResult.Model.init, }; [@deriving (show({with_path: false}), sexp, yojson)] - type persistent = { - editor: CodeEditable.Model.persistent, - result: EvalResult.Model.persistent, - }; + type persistent = {editor: CodeEditable.Model.persistent}; let persist = (model: t): persistent => { editor: model.editor |> CodeEditable.Model.persist, - result: model.result |> EvalResult.Model.persist, }; - let unpersist = (~settings as _=?, {editor, result}: persistent): t => { + let unpersist = (~settings as _=?, {editor}: persistent): t => { editor: CodeEditable.Model.unpersist(editor), - result: EvalResult.Model.unpersist(result), + result: EvalResult.Model.init, }; /* A cell holding a slide's stored source, with an un-run result. Slide sources are text-backed zippers (see PersistentZipper). */ let from_persistent_zipper = (~root, zipper: PersistentZipper.t): persistent => { editor: zipper |> Editor.Model.mk_persistent(~root), - result: EvalResult.Model.init |> EvalResult.Model.persist, }; let to_string = (model: t) => model.editor |> CodeEditable.Model.to_string; @@ -54,7 +49,15 @@ module Update = { [@deriving (show({with_path: false}), sexp, yojson)] type t = | MainEditor(CodeEditable.Update.t) - | ResultAction(EvalResult.Update.t); + | ResultAction(EvalResult.Update.t) + /* Apply a syntactic rewrite to the main editor's zipper. Emitted by + * proof-stepper views (via the `~edit_syntax` callback plumbed + * through EvalResult / Theorems / StepperView) when a step UI + * commits a structural change to the underlying `Theorem` / `Proof.t` + * tree. The patch is consumed via `EditorTransform.apply_patch`, + * which re-segments the rewritten expression and threads it back + * through `CaretPreserving.transform` so the user's caret survives. */ + | PatchMainEditor(EditorTransform.patch); let update = (~settings, action, model: Model.t) => { switch (action) { @@ -92,6 +95,22 @@ module Update = { result: updated.model, }, }; + /* A patch comes from a click elsewhere, which leaves the caret where it + * was, so the view stays where the user is rather than going back to + * the caret. */ + | PatchMainEditor(patch) => + CodeWithStatics.StaticsDebounce.force_on_next := true; // Avoid debounce because these are triggered by clicks. + let new_zipper = + EditorTransform.apply_patch(model.editor.editor.state.zipper, patch); + let new_inner_editor = Editor.Model.mk(~root=Exp, new_zipper); + { + ...model, + editor: { + ...model.editor, + editor: new_inner_editor, + }, + } + |> Updated.return(~scroll=IfCaretVisible); }; }; @@ -188,6 +207,7 @@ module Selection = { let get_cursor_info = (~inject: Update.t => Ui_effect.t(unit), ~selection, model: Model.t) : cursor(Update.t) => { + let proof_map = EvalResult.Model.proof_map(model.result); switch (selection) { | MainEditor => let+ ci = @@ -195,7 +215,8 @@ module Selection = { ~inject=a => inject(MainEditor(a)), ~selection=(), model.editor, - ); + ) + |> Cursor.with_proof_map(proof_map); Update.MainEditor(ci); | Result(selection) => let+ ci = @@ -203,7 +224,8 @@ module Selection = { ~inject=a => inject(ResultAction(a)), ~selection, model.result, - ); + ) + |> Cursor.with_proof_map(proof_map); Update.ResultAction(ci); }; }; @@ -230,6 +252,9 @@ module View = { ~lines=false, /* opt out for cells that are not the viewport-culling scope */ ~cull=true, + /* opt out for cells that are as wide as their code, which then has + nowhere to scroll */ + ~scroll_code=true, model: Model.t, ) => { let (footer, overlays) = @@ -251,6 +276,14 @@ module View = { Effect.Many([ signal(MakeActive(MainEditor)), inject(MainEditor(Perform(Move(Goal(TileId(id)))))), + ]) + | ReturnToEditor => + Effect.Many([ + signal(MakeActive(MainEditor)), + Effect.of_sync_fun( + () => Haz3lcore.FocusEffect.schedule_cell(), + (), + ), ]), ~inject=a => inject(ResultAction(a)), ~selected={ @@ -261,37 +294,57 @@ module View = { }, ~result_kind?, ~locked, + ~edit_syntax=patch => inject(PatchMainEditor(patch)), + /* Sub-editor capability: proof-stepper views render slices of + * this cell's main editor (scrutinees, case patterns) as live + * splices, and route their edits back through MainEditor — + * the same model + inject the top editor view uses below. */ + ~main_editor= + CodeEditable.Channel.{ + model: model.editor, + inject: action => inject(MainEditor(action)), + }, model.result, ); + let editor = + CodeEditable.View.view( + ~globals, + ~signal= + locked + ? _ => Ui_effect.Ignore + : fun + | MakeActive => signal(MakeActive(MainEditor)), + ~edit_mode= + locked + ? EditMode.ReadOnly + : Editable({ + inject: action => inject(MainEditor(action)), + escape: _ => Ui_effect.Ignore, + take_focus: _ => Ui_effect.Ignore, + focus: selected == Some(MainEditor) ? Some() : None, + }), + ~overlays=overlays(model.editor.editor), + ~lines, + ~cull, + ~dynamics=EvalResult.Model.dynamics(model.result), + ~predicted_reuse=EvalResult.Model.predicted_reuse(model.result), + ~pending_eval_ids=EvalResult.Model.pending_eval_ids(model.result), + ~show_active_eval=EvalResult.Model.eval_is_pending(model.result), + ~proof_map=EvalResult.Model.proof_map(model.result), + model.editor, + ); div( ~attrs=[Attr.classes(["cell", locked ? "locked" : "unlocked"])], Option.to_list(caption) @ [ - CodeEditable.View.view( - ~globals, - ~signal= - locked - ? _ => Ui_effect.Ignore - : fun - | MakeActive => signal(MakeActive(MainEditor)), - ~edit_mode= - locked - ? EditMode.ReadOnly - : Editable({ - inject: action => inject(MainEditor(action)), - escape: _ => Ui_effect.Ignore, - take_focus: _ => Ui_effect.Ignore, - focus: selected == Some(MainEditor) ? Some() : None, - }), - ~overlays=overlays(model.editor.editor), - ~lines, - ~cull, - ~dynamics=EvalResult.Model.dynamics(model.result), - ~predicted_reuse=EvalResult.Model.predicted_reuse(model.result), - ~pending_eval_ids=EvalResult.Model.pending_eval_ids(model.result), - ~show_active_eval=EvalResult.Model.eval_is_pending(model.result), - model.editor, - ), + /* The code scrolls sideways in this box (cell.css), so a long line + * widens neither the cell nor the result views in the footer. */ + scroll_code + ? div( + ~attrs=[Attr.class_(Util.JsUtil.CodeScroll.class_name)], + [editor], + ) + : editor, ] @ footer, ); diff --git a/src/web/app/editors/code/CodeEditable.re b/src/web/app/editors/code/CodeEditable.re index e715b75066..ecad3aa3af 100644 --- a/src/web/app/editors/code/CodeEditable.re +++ b/src/web/app/editors/code/CodeEditable.re @@ -13,6 +13,14 @@ module Update = { [@deriving (show({with_path: false}), sexp, yojson)] type t = | Perform(Action.t) + /* Perform, confined to the region described by the given target. + * Emitted by sub-editor views (see SubEditor.re): the action is + * vetted in `update` against the live zipper — rejected if it would + * edit outside the splice, delete the host syntax at the splice's + * edges, or move the caret out of the splice. View-level key guards + * can't enforce this: they close over the render-time zipper, which + * is stale during keystroke bursts. */ + | PerformConfined(SubEditor.Target.t, Action.t) | TAB | ContextMenu(ContextMenu.Model.action) | DebugConsole(string); @@ -91,6 +99,15 @@ module Update = { ? Animation.request([Animation.Actions.move("caret")]) : (); perform(action, model); + | PerformConfined(target, action) => + switch (SubEditor.confine_pre(~target, ~action, model.editor)) { + | None => model |> Updated.return_quiet + | Some(sub) => + let updated = perform(action, model); + Action.is_edit(action) + || SubEditor.caret_in_splice(sub, updated.model.editor.state.zipper) + ? updated : model |> Updated.return_quiet; + } | DebugConsole(key) => DebugConsole.print(~settings, model, key); model |> Updated.return_quiet; @@ -139,6 +156,17 @@ module Update = { let calculate = CodeWithStatics.Update.calculate; }; +/* A capability handle on an editor, passed down to views that render + * sub-editors (see SubEditor.re): the current model to render splices + * from, and an inject that routes editor actions back to the editor's + * update. */ +module Channel = { + type t = { + model: Model.t, + inject: Update.t => Ui_effect.t(unit), + }; +}; + module Selection = { open Cursor; @@ -258,7 +286,7 @@ module Selection = { /* Focus a probe on the current line (for end-of-line bounce) */ let focus_probe_on_row = (model: Model.t): option(Update.t) => { let z = model.editor.state.zipper; - let measured = model.editor.syntax.measured; + let measured = CachedSyntax.measured(model.editor.syntax); let caret_row = Zipper.Caret.point(measured, z).row; let refractors = z.refractors.manuals @ Id.Map.to_list(z.refractors.multis.ephemerals); @@ -448,7 +476,7 @@ module View = { ); [ CaretDec.view( - ~measured=syntax.measured, + ~measured=CachedSyntax.measured(syntax), ~font_metrics=globals.font_metrics, z, ), @@ -467,7 +495,7 @@ module View = { ? Highlight.selection_expanded(~term_data=syntax.term_data) : Highlight.selection )( - ~measured=syntax.measured, + ~measured=CachedSyntax.measured(syntax), ~shape_map=syntax.shape_map, ~font_metrics=globals.font_metrics, z, @@ -478,7 +506,7 @@ module View = { globals.color_highlights, ), VarHighlight.view( - ~measured=syntax.measured, + ~measured=CachedSyntax.measured(syntax), ~font_metrics=globals.font_metrics, ~info_map, z, @@ -498,10 +526,10 @@ module View = { d.typed_len == None ? Some(CompletionQuery.padding(z, d)) : None ), - ~measured=syntax.measured, + ~measured=CachedSyntax.measured(syntax), ~font_metrics=globals.font_metrics, ~caret_pos={ - let p = Zipper.Caret.point(syntax.measured, z); + let p = Zipper.Caret.point(CachedSyntax.measured(syntax), z); Some((p.row, p.col)); }, ~caret_form= @@ -529,6 +557,107 @@ module View = { ); }; + /* A sub-editor is an inline window onto the main editor (see + * SubEditor.re): it renders the main editor's model laid out from the + * splice, while the zipper, statics and history stay the main editor's, + * so an edit in either view edits the same segment. + * + * It has none of the main editor's buffer-wide features, which place + * things by the whole buffer's measurements: no context menu, + * refractors, projectors or edge scrolling. Edits stay in the splice: + * actions are confined there, keys that would move the caret out do + * nothing, pointer positions are translated into the main editor's + * coordinates, and triple-click selects a term, not the host line. */ + module Sub = { + let model = (sub: SubEditor.t, model: Model.t): Model.t => { + ...model, + editor: { + ...model.editor, + syntax: { + ...model.editor.syntax, + segment: sub.splice.segment, + measured: sub.splice.measured, + projector_list: sub.splice.projector_list, + }, + }, + }; + + /* Every pointer, keyboard and clipboard path emits ordinary actions; + * confining them here means none has to remember to. TAB, which + * jumps between holes anywhere in the buffer, does nothing. */ + let confine = + ( + sub: SubEditor.t, + inject: Update.t => Ui_effect.t(unit), + a: Update.t, + ) => + switch (a) { + | Perform(action) => inject(PerformConfined(sub.target, action)) + | TAB => Ui_effect.Ignore + | a => inject(a) + }; + + /* Caret and selection only, and only while the caret is in the + * splice: the splice's measurements can't place anything outside it. + * Each is guarded on its own, since both can raise on pieces just + * outside the splice and a failing selection mustn't take the caret + * with it. */ + let decos = (~globals: Globals.t, sub: SubEditor.t, model: Model.t) => { + let z = model.editor.state.zipper; + let measured = CachedSyntax.measured(model.editor.syntax); + switch ( + SubEditor.caret_in_splice(sub, z) + ? SubEditor.caret_point(sub, z) : None + ) { + | Some(origin) => + let caret = + switch ( + CaretDec.view( + ~measured, + ~font_metrics=globals.font_metrics, + ~origin, + z, + ) + ) { + | exception _ => [] + | caret => [caret] + }; + let selection = + switch ( + Highlight.selection( + ~measured, + ~shape_map=model.editor.syntax.shape_map, + ~font_metrics=globals.font_metrics, + z, + ) + ) { + | exception _ => [] + | selection => [selection] + }; + caret @ selection; + | None => [] + }; + }; + + /* Keys whose main-editor meaning would take the caret out of the + * splice: vertical and line-wise moves, and select-all. The guard is + * for the user's sake; `PerformConfined` is what enforces it. */ + let leaves_splice = (key: Key.t): bool => + switch (key) { + | { + key: + D( + "ArrowUp" | "ArrowDown" | "Home" | "End" | "PageUp" | "PageDown", + ), + _, + } + | {key: D("a" | "A"), sys: Mac, meta: Down, ctrl: Up, alt: Up, _} + | {key: D("a" | "A"), sys: PC, meta: Up, ctrl: Down, alt: Up, _} => + true + | _ => false + }; + }; + let view = ( ~globals: Globals.t, @@ -541,15 +670,31 @@ module View = { ~predicted_reuse: option(Language.EvaluatorState.incr_eval)=?, ~pending_eval_ids: list(Id.t)=[], ~show_active_eval: bool=false, + ~proof_map: Language.ProofMap.t=Language.ProofMap.empty, ~expand_selection=?, + ~sub_editor: option(SubEditor.t)=None, + /* The host's own keys, which win over the editor's. */ + ~keys: Key.t => option(Ui_effect.t(unit))=_ => None, model: Model.t, ) => { + let is_sub = Option.is_some(sub_editor); + let model = + switch (sub_editor) { + | Some(sub) => Sub.model(sub, model) + | None => model + }; + let selected = EditMode.is_active(edit_mode); - let inject = + let inject_raw = switch (edit_mode) { | ReadOnly => (_ => Ui_effect.Ignore) | Editable({inject, _}) => inject }; + let inject = + switch (sub_editor) { + | Some(sub) => Sub.confine(sub, inject_raw) + | None => inject_raw + }; let escape = switch (edit_mode) { | ReadOnly => (_ => Ui_effect.Ignore) @@ -627,71 +772,78 @@ module View = { }; /* Sync document-level listeners (click-outside + keyboard) for the * context menu. Keys are dispatched at capture phase so the editor's - * window-level handler doesn't see them while the menu is open. */ - ContextMenuListener.sync( - ~menu_open=selected && Model.context_menu_is_open(model), - ~on_close=() => inject(ContextMenu(ContextMenu.Model.Close)), - ~handle_key= - key_str => - ContextMenu.WithContext.handle_listener_key( - ~info_map=model.statics.info_map, - ~elaborated=model.statics.elaborated, - ~zipper=model.editor.state.zipper, - ~dispatch_menu=a => inject(ContextMenu(a)), - ~dispatch_action=perform_from_menu, - model.context_menu, - key_str, - ), - (), - ); + * window-level handler doesn't see them while the menu is open. The + * listener registry is a singleton, the main editor's. */ + if (!is_sub) { + ContextMenuListener.sync( + ~menu_open=selected && Model.context_menu_is_open(model), + ~on_close=() => inject(ContextMenu(ContextMenu.Model.Close)), + ~handle_key= + key_str => + ContextMenu.WithContext.handle_listener_key( + ~info_map=model.statics.info_map, + ~elaborated=model.statics.elaborated, + ~zipper=model.editor.state.zipper, + ~dispatch_menu=a => inject(ContextMenu(a)), + ~dispatch_action=perform_from_menu, + model.context_menu, + key_str, + ), + (), + ); + }; let edit_decos = - selected - ? deco( - ~expand_selection?, - ~syntax=model.editor.syntax, - ~info_map=model.statics.info_map, - ~globals, - ~on_apply= - Some(id => inject(Perform(ApplyCompletion(One(id))))), - model.editor.state.zipper, - ) - @ [ - Arms.Refractors.all( - ~font_metrics=globals.font_metrics, + switch (sub_editor) { + | Some(sub) => selected ? Sub.decos(~globals, sub, model) : [] + | None => + selected + ? deco( + ~expand_selection?, ~syntax=model.editor.syntax, - ~completion=Arms.lazy_completion(model.editor.state.zipper), + ~info_map=model.statics.info_map, + ~globals, + ~on_apply= + Some(id => inject(Perform(ApplyCompletion(One(id))))), model.editor.state.zipper, - ), - ] - @ ( - switch (model.context_menu) { - | Some(_) => [ - /* Backdrop for scroll-close. Click handling is done via - ContextMenuListener's document-level event listener. */ - Node.div( - ~attrs=[ - Attr.classes(["context-menu-backdrop"]), - Attr.on_wheel(_ => - inject(ContextMenu(ContextMenu.Model.Close)) - ), - ], - [], - ), - ContextMenu.view( - ~inject=perform_from_menu, - ~inject_menu=a => inject(ContextMenu(a)), - ~syntax=model.editor.syntax, - ~info_map=model.statics.info_map, - ~elaborated=model.statics.elaborated, - ~font_metrics=globals.font_metrics, - ~model=model.context_menu, - model.editor.state.zipper, - ), - ] - | None => [] - } - ) - : []; + ) + @ [ + Arms.Refractors.all( + ~font_metrics=globals.font_metrics, + ~syntax=model.editor.syntax, + ~completion=Arms.lazy_completion(model.editor.state.zipper), + model.editor.state.zipper, + ), + ] + @ ( + switch (model.context_menu) { + | Some(_) => [ + /* Backdrop for scroll-close. Click handling is done via + ContextMenuListener's document-level event listener. */ + Node.div( + ~attrs=[ + Attr.classes(["context-menu-backdrop"]), + Attr.on_wheel(_ => + inject(ContextMenu(ContextMenu.Model.Close)) + ), + ], + [], + ), + ContextMenu.view( + ~inject=perform_from_menu, + ~inject_menu=a => inject(ContextMenu(a)), + ~syntax=model.editor.syntax, + ~info_map=model.statics.info_map, + ~elaborated=model.statics.elaborated, + ~font_metrics=globals.font_metrics, + ~model=model.context_menu, + model.editor.state.zipper, + ), + ] + | None => [] + } + ) + : [] + }; let zipper = model.editor.state.zipper; /* never cull a cell that opted out (the range is measured on another cell), and cull only in auto-probe mode, else a stale range could hide @@ -699,57 +851,63 @@ module View = { let visible = cull && globals.settings.autoprobe_mode != Haz3lcore.AutoProbe.Off ? globals.visible_rows : None; - let refractor_data = - RefractorView.mk_data( - ~refractors= - Id.Map.union( - (_, _, b) => Some(b), - zipper.refractors.manuals |> Id.Map.of_list, - zipper.refractors.multis.ephemerals, - ), - ~syntax=model.editor.syntax, - ~indicated=Indicated.for_decoration(zipper), - ~statics=model.statics.info_map, - ~dynamics, - ~sample_focus=zipper.refractors.sample_focus, - ~editor_active=selected, - ~visible?, - ~refractor_rows=model.editor.syntax.refractor_rows, - (), - ); let refractors_model = - RefractorView.all( - x => inject(Perform(x)), - signal(MakeActive), - globals.font_metrics, - ~core_settings=globals.settings.core, - ~visible?, - ~refractor_rows=model.editor.syntax.refractor_rows, - refractor_data, - List.map(~f=fst, zipper.refractors.manuals) - @ List.map( - ~f=fst, - Id.Map.to_list(zipper.refractors.multis.ephemerals), - ), - ); + if (is_sub) { + []; + } else { + let refractor_data = + RefractorView.mk_data( + ~refractors= + Id.Map.union( + (_, _, b) => Some(b), + zipper.refractors.manuals |> Id.Map.of_list, + zipper.refractors.multis.ephemerals, + ), + ~syntax=model.editor.syntax, + ~indicated=Indicated.for_decoration(zipper), + ~statics=model.statics.info_map, + ~dynamics, + ~sample_focus=zipper.refractors.sample_focus, + ~editor_active=selected, + ~visible?, + ~refractor_rows=model.editor.syntax.refractor_rows, + (), + ); + RefractorView.all( + x => inject(Perform(x)), + signal(MakeActive), + globals.font_metrics, + ~core_settings=globals.settings.core, + ~visible?, + ~refractor_rows=model.editor.syntax.refractor_rows, + refractor_data, + List.map(~f=fst, zipper.refractors.manuals) + @ List.map( + ~f=fst, + Id.Map.to_list(zipper.refractors.multis.ephemerals), + ), + ); + }; let projectors = - ProjectorView.all( - x => inject(Perform(x)), - signal(MakeActive), - globals.font_metrics, - ~core_settings=globals.settings.core, - ~visible?, - ProjectorView.Model.mk( - ~syntax=model.editor.syntax, - ~indicated=Indicated.for_decoration(zipper), - ~statics=model.statics.info_map, - ~dynamics, - ~sample_focus=zipper.refractors.sample_focus, - ~editor_active=selected, - ~elaborated=Some(model.statics.elaborated), - ), - model.editor.syntax.projector_list, - ); + is_sub + ? [] + : ProjectorView.all( + x => inject(Perform(x)), + signal(MakeActive), + globals.font_metrics, + ~core_settings=globals.settings.core, + ~visible?, + ProjectorView.Model.mk( + ~syntax=model.editor.syntax, + ~indicated=Indicated.for_decoration(zipper), + ~statics=model.statics.info_map, + ~dynamics, + ~sample_focus=zipper.refractors.sample_focus, + ~editor_active=selected, + ~elaborated=Some(model.statics.elaborated), + ), + model.editor.syntax.projector_list, + ); ProjectorView.ViewCache.log_frame(); /* The nut-menu setting paints ReusePass predictions (frozen tint). Pending * evaluation highlights are transient progress feedback, so keep them on @@ -784,15 +942,27 @@ module View = { @ projectors @ refractors_model; let code_view = - CodeWithStatics.View.view(~globals, ~overlays, ~cull, model); - - let loc = (e: Pointer.Event.t) => - FontMetrics.get_goal( - ~font_metrics=globals.font_metrics, - container_target(e.current_target), - e.loc, + CodeWithStatics.View.view( + ~globals, + ~overlays, + ~cull, + ~proof_map, + model, ); + let loc = (e: Pointer.Event.t) => { + let raw = + FontMetrics.get_goal( + ~font_metrics=globals.font_metrics, + container_target(e.current_target), + e.loc, + ); + switch (sub_editor) { + | Some(sub) => SubEditor.translate_goal(sub, raw) + | None => raw + }; + }; + /* Pointer modifier → optional chunkiness override for * Select(Resize(Point(...))). Alt on Mac / Ctrl on PC swaps to the * non-default chunkiness (BySmart ↔ ByChar) per the "Character-level @@ -817,7 +987,7 @@ module View = { switch (z.selection.content) { | [] => false | [first, ..._] as content => - let measured = model.editor.syntax.measured; + let measured = CachedSyntax.measured(model.editor.syntax); switch ( try( Some(( @@ -902,7 +1072,7 @@ module View = { inject(Perform(Move(Point(loc(mouse), None)))), ]); | 2 => inject(Perform(Select(Smart(2)))) - | 3 => inject(Perform(Select(Smart(3)))) + | 3 => inject(Perform(Select(Smart(is_sub ? 2 : 3)))) | _ => failwith("THEN PERISH") }; | _ => Effect.Ignore @@ -950,22 +1120,26 @@ module View = { /* Snapshot at mousemove time so edge-scroll fires with the * same chunkiness mode the user had selected. */ let chunk_override = drag_chunkiness_override(pointer); - EdgeScroll.update( - ~client_y=float_of_int(pointer.loc.row), - ~on_scroll=() => { - let goal = - FontMetrics.get_goal( - ~font_metrics=globals.font_metrics, - container, - pixel_loc, + if (!is_sub) { + EdgeScroll.update( + ~container, + ~client_x=float_of_int(pointer.loc.col), + ~client_y=float_of_int(pointer.loc.row), + ~on_scroll=() => { + let goal = + FontMetrics.get_goal( + ~font_metrics=globals.font_metrics, + container, + pixel_loc, + ); + Bonsai.Effect.Expert.handle( + inject( + Perform(Select(Resize(Point(goal, chunk_override)))), + ), ); - Bonsai.Effect.Expert.handle( - inject( - Perform(Select(Resize(Point(goal, chunk_override)))), - ), - ); - }, - ); + }, + ); + }; inject( Perform(Select(Resize(Point(current_loc, chunk_override)))), ); @@ -982,9 +1156,24 @@ module View = { Attr.empty; } else { let z = model.editor.state.zipper; - /* Key.listener (not Key.handler): handler adds its own tabindex(0), - duplicating this div's tabindex — vdom warns every render */ - Key.listener(~f=key => { + /* The edges the caret escapes at: the buffer's, or the splice's. */ + let is_at_left = () => + switch (sub_editor) { + | Some(sub) => SubEditor.caret_at_left(sub, z) + | None => + z.caret == Outer + && z.relatives.ancestors == [] + && fst(Siblings.neighbors(z.relatives.siblings)) == None + }; + let is_at_right = () => + switch (sub_editor) { + | Some(sub) => SubEditor.caret_at_right(sub, z) + | None => + z.caret == Outer + && z.relatives.ancestors == [] + && snd(Siblings.neighbors(z.relatives.siblings)) == None + }; + let editor_keys = (key: Key.t) => { /* 1. Check for arrow key escape at boundaries FIRST. * Keyboard.handle_key_event always returns Some for arrows, * so boundary escape must be checked before delegation. */ @@ -997,12 +1186,7 @@ module View = { alt: Up, _, } - when - z.caret == Outer - && z.relatives.ancestors == [] - && Option.is_none( - fst(Siblings.neighbors(z.relatives.siblings)), - ) => + when is_at_left() => Effect.Many([Effect.Prevent_default, escape(Left)]) | { key: D("ArrowRight" | "ArrowDown"), @@ -1012,13 +1196,9 @@ module View = { alt: Up, _, } - when - z.caret == Outer - && z.relatives.ancestors == [] - && Option.is_none( - snd(Siblings.neighbors(z.relatives.siblings)), - ) => + when is_at_right() => Effect.Many([Effect.Prevent_default, escape(Right)]) + | _ when is_sub && Sub.leaves_splice(key) => Effect.Prevent_default /* 2. Cmd/Ctrl + C/X/V, via the clipboard helpers above. */ | { key: D("c" | "C"), @@ -1102,8 +1282,21 @@ module View = { ]) | None => Effect.Ignore } + }; + }; + /* Key.listener (not Key.handler): handler adds its own tabindex(0), + duplicating this div's tabindex — vdom warns every render */ + Key.listener(~f=key => + switch (keys(key)) { + | Some(effect) => + Effect.Many([ + Effect.Prevent_default, + Effect.Stop_propagation, + effect, + ]) + | None => editor_keys(key) } - }); + ); }; Node.div( ~attrs=[ @@ -1151,4 +1344,30 @@ module View = { : [code_view], ); }; + + /* A sub-editor onto the main editor behind `channel`. */ + let view_sub = + ( + ~globals: Globals.t, + ~channel: Channel.t, + ~take_focus: Ui_effect.t(unit), + ~focused: bool, + sub: SubEditor.t, + ) => + view( + ~globals, + ~signal= + fun + | MakeActive => take_focus, + ~edit_mode= + EditMode.Editable({ + inject: channel.inject, + escape: _ => Ui_effect.Ignore, + take_focus: _ => Ui_effect.Ignore, + focus: focused ? Some() : None, + }), + ~dynamics=Language.Dynamics.Map.empty, + ~sub_editor=Some(sub), + channel.model, + ); }; diff --git a/src/web/app/editors/code/CodeSelectable.re b/src/web/app/editors/code/CodeSelectable.re index 12ae475c25..8461033d41 100644 --- a/src/web/app/editors/code/CodeSelectable.re +++ b/src/web/app/editors/code/CodeSelectable.re @@ -47,6 +47,7 @@ module Update = { Introduce | ToggleLineComment, ) + | PerformConfined(_, _) | DebugConsole(_) | ContextMenu(_) | TAB => None; diff --git a/src/web/app/editors/code/CodeViewable.re b/src/web/app/editors/code/CodeViewable.re index 95086ed24a..16e468e414 100644 --- a/src/web/app/editors/code/CodeViewable.re +++ b/src/web/app/editors/code/CodeViewable.re @@ -51,3 +51,6 @@ let view_typ = (~globals: Globals.t, ~settings, typ: Language.Typ.t) => let view_any = (~globals: Globals.t, ~settings, any: Language.Any.t) => any |> ExpToSegment.any_to_segment(~settings) |> view_segment(~globals); + +let view_exp = (~globals: Globals.t, ~settings, exp: Language.Exp.t) => + exp |> ExpToSegment.exp_to_segment(~settings) |> view_segment(~globals); diff --git a/src/web/app/editors/code/CodeWithStatics.re b/src/web/app/editors/code/CodeWithStatics.re index bffd2ed89e..c4fa3a9382 100644 --- a/src/web/app/editors/code/CodeWithStatics.re +++ b/src/web/app/editors/code/CodeWithStatics.re @@ -82,6 +82,7 @@ module Model = { redo_action: None, error_ids: model.statics.error_ids, contextual_actions: [], + proof_map: Language.ProofMap.empty, }; [@deriving (show({with_path: false}), sexp, yojson)] @@ -258,25 +259,25 @@ module View = { type event; let view = - (~globals, ~overlays: list(Node.t)=[], ~cull=false, model: Model.t) => { + ( + ~globals, + ~overlays: list(Node.t)=[], + ~cull=false, + ~proof_map: Language.ProofMap.t=Language.ProofMap.empty, + model: Model.t, + ) => { let { editor: { syntax: - { - measured, - selection_ids, - segment, - shape_map, - refractor_rows, - term_data, - _, - }, + {selection_ids, shape_map, refractor_rows, term_data, _} as syntax, state: {zipper: z, _}, _, }, _, }: Model.t = model; + let measured = CachedSyntax.measured(syntax); + let segment = CachedSyntax.segment(syntax); let info_map = model.statics.info_map; let refine_sort = (id, mold_out) => Language.Info.refine_sort_from_mold(~info_map, ~id, mold_out); @@ -293,6 +294,11 @@ module View = { ); /* shared by the error and warning arms */ let completion = Arms.lazy_completion(z); + /* Union proof-mark ids into the red-shard overlay. Proof-check marks + * are produced at evaluation time (see src/language/proof/ProofCheck.re + * and ProofMark.t) and flow in here via CodeEditable → CellEditor, + * which reads them from the EvalResult's proof_map. */ + let proof_error_ids = Language.ProofMap.error_ids(proof_map); let error_decos = Arms.Errors.of_ids( ~refine_sort, @@ -300,7 +306,7 @@ module View = { ~font_metrics=globals.font_metrics, ~syntax=model.editor.syntax, ~completion, - model.statics.error_ids, + model.statics.error_ids @ proof_error_ids, ); let warning_ids = globals.settings.core.display_warnings ? model.statics.warning_ids : []; diff --git a/src/web/app/editors/code/ContextMenu.re b/src/web/app/editors/code/ContextMenu.re index 9f4d3a0fdf..7be34594f4 100644 --- a/src/web/app/editors/code/ContextMenu.re +++ b/src/web/app/editors/code/ContextMenu.re @@ -40,13 +40,17 @@ let caret_bottom_offset = (font_metrics: FontMetrics.t): float => { row_height +. shadow; }; -let pos_style = +/* Where the menu's corner goes, in pixels from the code container's + * origin. The menu is position: fixed (see FloatingElement): it usually + * extends past the code's top or bottom edge, where the box a cell's code + * scrolls in (cell.css) would clip it. */ +let pos_attrs = ( point: Point.t, font_metrics: FontMetrics.t, direction: Menu.open_direction, ) - : string => { + : list(Attr.t) => { let left = Float.of_int(point.col) *. font_metrics.col_width; let caret_top = Float.of_int(point.row) *. font_metrics.row_height; let caret_bottom = caret_top +. caret_bottom_offset(font_metrics); @@ -55,7 +59,15 @@ let pos_style = | `Down => caret_bottom +. caret_menu_gap | `Up => caret_top -. caret_menu_gap }; - sprintf("position: absolute; left: %fpx; top: %fpx;", left, top); + [ + Attr.create("data-float-anchor-class", "code-container"), + Attr.create("data-float-local-top", Float.to_string(top)), + Attr.create("data-float-local-left", Float.to_string(left)), + Attr.create( + "style", + "position: fixed; visibility: hidden; top: 0; left: 0;", + ), + ]; }; /* ============================================================ @@ -567,7 +579,7 @@ let view = z: Haz3lcore.Zipper.t, ) : Node.t => { - let caret_point = Zipper.Caret.point(syntax.measured, z); + let caret_point = Zipper.Caret.point(CachedSyntax.measured(syntax), z); let items = get_all_items(~info_map, ~elaborated, z); let menu_items = Menu.render( @@ -583,12 +595,15 @@ let view = } else { let direction = get_direction(caret_point, font_metrics); let dir_class = direction_class(direction); - let style = pos_style(caret_point, font_metrics, direction); - div( ~attrs=[ - Attr.classes(["context-menu", "nut-menu", dir_class]), - Attr.create("style", style), + Attr.classes([ + "context-menu", + "nut-menu", + "floating-fixed", + dir_class, + ]), + ...pos_attrs(caret_point, font_metrics, direction), ], [div_c("group", [div_c("contents", menu_items)])], ); diff --git a/src/web/app/editors/code/SubEditor.re b/src/web/app/editors/code/SubEditor.re new file mode 100644 index 0000000000..61203017cc --- /dev/null +++ b/src/web/app/editors/code/SubEditor.re @@ -0,0 +1,402 @@ +open Util; +open Haz3lcore; + +/* A sub-editor is a window onto one term of the main editor, the + * splice. Its pieces are the main editor's pieces, and the zipper, + * statics and undo history are the main editor's too, so it can't fall + * out of sync with the syntax it shows: an edit in either view edits the + * same segment. The stepper uses them to edit slices of a theorem's + * proof in place (an induction's scrutinee, a case's pattern, a form's + * argument). CodeEditable.View renders them and confines their edits. */ + +/* Where a splice is: a host tile and a path into it. A term's own id + * won't do, because term ids change as the user types (a hole becomes a + * var, a var the child of a cons) while the view lags the statics, so a + * term-id key goes stale mid-burst and drops keystrokes. The host tile's + * id survives any edit inside it. The caller knows the grammar: + * + * let scrut = + * Target.child(~anchor=induction_id, 0) + * |> Target.until(Before(NthTile(["|", "=>"], 0))); + * + * let pattern = i => + * Target.child(~anchor=induction_id, 0) + * |> Target.descend(NthTile(["|", "=>"], i), ~child=0); + */ +module Target = { + /* `NthTile(label, n)`: the n-th (0-based) direct tile piece whose label + * matches. Tiles nested inside children are ignored. */ + [@deriving (show({with_path: false}), sexp, yojson)] + type selector = + | NthTile(Label.t, int); + + /* `BeforeOrEnd` is like `Before`, but the segment end when no piece + * matches — for ranges bounded by a tile that may legitimately be absent + * (e.g. an induction scrutinee when there are no case rules yet). */ + [@deriving (show({with_path: false}), sexp, yojson)] + type bound = + | Start + | End + | Before(selector) + | BeforeOrEnd(selector) + | After(selector); + + /* `IntoChild(i)` enters the i-th mold child of the current tile; + * `IntoSelected(sel, i)` selects a tile among the current segment's + * direct pieces and enters its i-th mold child. */ + [@deriving (show({with_path: false}), sexp, yojson)] + type step = + | IntoChild(int) + | IntoSelected(selector, int); + + [@deriving (show({with_path: false}), sexp, yojson)] + type t = { + anchor: Id.t, + steps: list(step), + from: bound, + until: bound, + }; + + /* Start at the host tile's i-th child, spanning the whole child. */ + let child = (~anchor: Id.t, i: int): t => { + anchor, + steps: [IntoChild(i)], + from: Start, + until: End, + }; + + /* Narrow the end of the contiguous range in the current segment. */ + let until = (until: bound, t: t): t => { + ...t, + until, + }; + + /* Narrow the start of the contiguous range in the current segment. */ + let from = (from: bound, t: t): t => { + ...t, + from, + }; + + /* Find a tile in the current segment via `selector`, then continue + * locating from that tile's `~child`-th mold child (full span). */ + let descend = (selector: selector, ~child: int, t: t): t => { + anchor: t.anchor, + steps: t.steps @ [IntoSelected(selector, child)], + from: Start, + until: End, + }; + + let matches_selector = (sel: selector, p: Piece.t): bool => + switch (sel, p) { + | (NthTile(label, _), Tile(tile)) => + Label.equal(Tile.label(tile), label) + | (NthTile(_, _), _) => false + }; + + /* Index of the n-th direct piece matching `sel`, or None. */ + let find_selector_index = (sel: selector, seg: Segment.t): option(int) => { + let NthTile(_, n) = sel; + let rec go = (i, seen, rest) => + switch (rest) { + | [] => None + | [p, ...ps] => + if (matches_selector(sel, p)) { + seen == n ? Some(i) : go(i + 1, seen + 1, ps); + } else { + go(i + 1, seen, ps); + } + }; + go(0, 0, seg); + }; + + let find_selected_tile = (sel: selector, seg: Segment.t): option(Base.tile) => + switch (find_selector_index(sel, seg)) { + | Some(i) => + switch (List.nth(seg, i)) { + | Some(Piece.Tile(tile)) => Some(tile) + | _ => None + } + | None => None + }; + + /* Inclusive start / exclusive end index for a range bound. */ + let bound_index = (bound: bound, seg: Segment.t): option(int) => + switch (bound) { + | Start => Some(0) + | End => Some(List.length(seg)) + | Before(sel) => find_selector_index(sel, seg) + | BeforeOrEnd(sel) => + Some( + find_selector_index(sel, seg) + |> Option.value(~default=List.length(seg)), + ) + | After(sel) => + switch (find_selector_index(sel, seg)) { + | Some(i) => Some(i + 1) + | None => None + } + }; + + let slice = + (seg: Segment.t, ~from: bound, ~until: bound): option(Segment.t) => { + open OptUtil.Syntax; + let* start = bound_index(from, seg); + let* stop = bound_index(until, seg); + start <= stop && start >= 0 && stop <= List.length(seg) + ? Some(ListUtil.sublist((start, stop), seg)) : None; + }; + + type cursor = + | AtTile(Base.tile) + | AtSegment(Segment.t); + + let apply_step = (cur: cursor, step: step): option(cursor) => { + OptUtil.Syntax.( + switch (cur, step) { + | (AtTile(tile), IntoChild(i)) => + let+ child = List.nth(tile.children, i); + AtSegment(child); + | (AtSegment(seg), IntoSelected(sel, i)) => + let* tile = find_selected_tile(sel, seg); + let+ child = List.nth(tile.children, i); + AtSegment(child); + | (AtSegment(_), IntoChild(_)) + | (AtTile(_), IntoSelected(_)) => None + } + ); + }; + + /* None when the anchor, a step or the range can't be found, which + * callers take as a passing state mid-rewrite. */ + let resolve = (target: t, root: Segment.t): option(Segment.t) => { + open OptUtil.Syntax; + let rec find_tile = (seg: Segment.t): option(Base.tile) => + List.find_map( + ~f= + (p: Piece.t) => + switch (p) { + | Tile(tile) when Id.equal(tile.id, target.anchor) => Some(tile) + | Tile(tile) => List.find_map(~f=find_tile, tile.children) + | Grout(_) + | Secondary(_) + | Projector(_) => None + }, + seg, + ); + let* tile = find_tile(root); + let* cur = + List.fold_left( + ~f= + (cur, step) => { + let* cur = cur; + apply_step(cur, step); + }, + ~init=Some(AtTile(tile)), + target.steps, + ); + switch (cur) { + | AtSegment(seg) => slice(seg, ~from=target.from, ~until=target.until) + | AtTile(_) => None + }; + }; +}; + +type t = { + /* Kept so that the view's actions can be confined to the splice. */ + target: Target.t, + /* Measured from a local origin. It measures exactly the splice's + * pieces, so it also answers whether a piece is in the splice. */ + splice: CachedSyntax.splice, + /* Where the splice starts and ends in the main editor. */ + origin: Point.t, + last: Point.t, +}; + +/* Strips one separator from each end of the slot: the space the host's + * layout puts around the term, or a line break with the indentation + * beside it. Shown, it would be a stray space in the chip that the user + * could delete from the host's syntax. Any more whitespace is the user's + * own, mid-typing (`5 ` on the way to `5 + …`), and stays, or the caret + * would be stranded outside the splice after it. The caret positions + * beside a stripped separator still count as in the splice (see + * `caret_in_splice` and `caret_point`). */ +let trim_separators = (seg: Segment.t): Segment.t => { + let is_space_piece = (p: Piece.t) => + switch (p) { + | Secondary(w) => !Secondary.is_linebreak(w) && !Secondary.is_comment(w) + | Tile(_) + | Grout(_) + | Projector(_) => false + }; + let is_linebreak_piece = (p: Piece.t) => + switch (p) { + | Secondary(w) => Secondary.is_linebreak(w) + | Tile(_) + | Grout(_) + | Projector(_) => false + }; + let rec drop_spaces = + fun + | [p, ...ps] when is_space_piece(p) => drop_spaces(ps) + | ps => ps; + let leading = + fun + | [lb, ...rest] when is_linebreak_piece(lb) => + /* linebreak, then the next line's indentation */ + drop_spaces(rest) + | [ws, ...rest] when is_space_piece(ws) => rest + | seg => seg; + /* Trailing, on the reversed slot: the separator reads + * [indentation…, linebreak] there (document order: linebreak, then + * the indentation preceding the host's closing delimiter). */ + let trailing_rev = rev => + switch (drop_spaces(rev)) { + | [lb, ...rest] when is_linebreak_piece(lb) => rest + | _ => + switch (rev) { + | [ws, ...rest] when is_space_piece(ws) => rest + | rev => rev + } + }; + seg |> leading |> List.rev |> trailing_rev |> List.rev; +}; + +/* None when the target can't be resolved, the region is empty or its + * pieces aren't measured, as happens mid-rewrite; callers render + * read-only until the next pass. */ +let mk = (editor: Editor.t, ~target: Target.t): option(t) => { + open OptUtil.Syntax; + let syntax: CachedSyntax.t = editor.syntax; + let* segment = Target.resolve(target, CachedSyntax.segment(syntax)); + let segment = trim_separators(segment); + let* first = ListUtil.hd_opt(segment); + let* last_piece = ListUtil.last_opt(segment); + let* m_first = + Measured.find_by_id(Piece.id(first), CachedSyntax.measured(syntax)); + let* m_last = + Measured.find_by_id( + Piece.id(last_piece), + CachedSyntax.measured(syntax), + ); + let measured = Measured.of_segment(segment, syntax.shape_map, Id.Map.empty); + Some({ + target, + splice: { + segment, + measured, + projector_list: [], + }, + origin: m_first.origin, + last: m_last.last, + }); +}; + +/* A pointer position in the splice, in the main editor's coordinates, + * clamped to the splice so the mouse can't put the caret outside it. + * A splice over several lines is translated row by row, unclamped. */ +let translate_goal = (sub: t, p: Point.t): Point.t => + if (sub.origin.row == sub.last.row) { + Point.{ + row: sub.origin.row, + col: min(sub.origin.col + max(p.col, 0), sub.last.col), + }; + } else { + Point.{ + row: sub.origin.row + p.row, + col: p.row == 0 ? sub.origin.col + p.col : p.col, + }; + }; + +/* Whether either of the caret's neighbours is in the splice. Both count: + * at the splice's first position the left neighbour is the whitespace + * just outside it. */ +let caret_in_splice = (sub: t, z: Zipper.t): bool => { + let mem = (p: Piece.t) => + Measured.find_by_id(Piece.id(p), sub.splice.measured) |> Option.is_some; + switch (Siblings.neighbors(ZipperBase.sibs_with_sel(z))) { + | (Some(l), _) when mem(l) => true + | (_, Some(r)) when mem(r) => true + | _ => false + }; +}; + +/* The caret in splice-local coordinates. `Zipper.Caret.point` reads the + * piece left of the caret, which in the splice's first piece is the + * whitespace outside the splice; there the right neighbour's origin is + * used instead, plus the caret's offset into it. */ +let caret_point = (sub: t, z: Zipper.t): option(Point.t) => + switch (Zipper.Caret.point(sub.splice.measured, z)) { + | p => Some(p) + | exception _ => + switch (Siblings.neighbors(ZipperBase.sibs_with_sel(z))) { + | (_, Some(r)) => + Measured.find_by_id(Piece.id(r), sub.splice.measured) + |> Option.map(~f=(m: Measured.measurement) => + Point.{ + row: m.origin.row, + col: m.origin.col + Zipper.Caret.offset(z), + } + ) + | (Some(l), _) => + Measured.find_by_id(Piece.id(l), sub.splice.measured) + |> Option.map(~f=(m: Measured.measurement) => m.last) + | _ => None + } + }; + +/* At an edge of the splice, deleting outward would eat the host's syntax, + * and an arrow key escapes the sub-editor rather than leave the splice. + * The edges are on the splice's own level. Only the caret's siblings are + * compared: inside `[xyz]`, past the last sibling, the piece to the right + * is the `]` of the splice's own tile, which has that tile's id. */ +let caret_at_left = (sub: t, z: Zipper.t): bool => + Zipper.equal_caret(z.caret, Outer) + && { + open OptUtil.Syntax; + let* leftmost = ListUtil.hd_opt(sub.splice.segment); + let* right_of_caret = snd(Siblings.neighbors(z.relatives.siblings)); + Id.equal(Piece.id(leftmost), Piece.id(right_of_caret)) ? Some() : None; + } + |> Option.is_some; + +let caret_at_right = (sub: t, z: Zipper.t): bool => + Zipper.equal_caret(z.caret, Outer) + && { + open OptUtil.Syntax; + let* rightmost = ListUtil.last_opt(sub.splice.segment); + let* left_of_caret = fst(Siblings.neighbors(z.relatives.siblings)); + Id.equal(Piece.id(rightmost), Piece.id(left_of_caret)) ? Some() : None; + } + |> Option.is_some; + +/* Whether a sub-editor's action may run (CodeEditable's PerformConfined), + * judged in `update` against the live zipper: the view's key guards see + * the zipper of the last render, which is stale during a burst of keys. + * None rejects the action. Some(sub) lets it run; a move or select is + * then dropped if the caret lands outside the splice, which `sub` still + * describes exactly because a move doesn't change piece ids. */ +let confine_pre = + (~target: Target.t, ~action: Action.t, editor: Editor.t): option(t) => { + open OptUtil.Syntax; + let* sub = mk(editor, ~target); + let z = editor.state.zipper; + if (Action.is_edit(action)) { + /* A caret outside the splice would edit some other part of the + * buffer, out of sight. */ + let edge_delete = + switch (action) { + | Destruct(Local(Left, _)) => + caret_at_left(sub, z) && Selection.is_empty(z.selection) + | Destruct(Local(Right, _)) => + caret_at_right(sub, z) && Selection.is_empty(z.selection) + | _ => false + }; + caret_in_splice(sub, z) && !edge_delete ? Some(sub) : None; + } else { + /* Clicking into the splice from outside is itself a move, so moves + * are judged by where they land. */ + Some( + sub, + ); + }; +}; diff --git a/src/web/app/editors/decoration/Arms.re b/src/web/app/editors/decoration/Arms.re index 5c26b147b0..984a28cfe0 100644 --- a/src/web/app/editors/decoration/Arms.re +++ b/src/web/app/editors/decoration/Arms.re @@ -308,18 +308,25 @@ let tiles_data = Id.Map.find(id, terms) |> Language.Any.ids |> List.filter_map(~f=of_tile); }; -let term = +/* Where a term's indication goes, read off the layout, so that a caller + * can keep it and draw it again with `of_geometry`. */ +[@deriving (show({with_path: false}), sexp, yojson)] +type geometry = { + tiles: list((Id.t, Mold.t, Shards.t)), + /* The term's extent, or None for a module's `;`, which is drawn as its + * shards alone. */ + range: option((Point.t, Point.t)), +}; + +let geometry = ( - ~refine_sort: (Id.t, Sort.t) => Sort.t=(_, sort) => sort, ~term_data: TermData.t, ~terms: TermMap.t, ~measured: Measured.t, - ~font_metrics: FontMetrics.t, - ~attr: option(list(Attr.t))=?, ~clip_right: option(Point.t)=None, tile: Tile.t, ) - : list(Node.t) => { + : option(geometry) => { let id = Language.Any.rep_id(Id.Map.find(tile.id, terms)); let any_term = Id.Map.find(id, terms); @@ -342,34 +349,67 @@ let term = let msg = "Arms.term"; switch (TermData.root_tile(tile.id, term_data)) { | Some(t) => - shards( - ~refine_sort, - ~attr?, - ~font_metrics, - ~base_clss=None, - [(tile.id, Tile.mold(t), Measured.find_shards(~msg, t, measured))], - ) - | None => [] + Some({ + tiles: [ + (tile.id, Tile.mold(t), Measured.find_shards(~msg, t, measured)), + ], + range: None, + }) + | None => None }; } else { switch (TermData.extreme_measures(id, term_data, measured)) { | Some((l, r)) => - let r = apply_clip(clip_right, r); let tiles = tiles_data(~term_data, ~terms, ~measured, tile); - let tiles = is_module ? List.filter(~f=is_not_semi_tile, tiles) : tiles; - term( - ~refine_sort, - ~font_metrics, - ~rows=measured.rows, - ~tiles, - (l, r), - ~attr?, - ); - | _ => [] + Some({ + tiles: is_module ? List.filter(~f=is_not_semi_tile, tiles) : tiles, + range: Some((l, apply_clip(clip_right, r))), + }); + | None => None }; }; }; +let of_geometry = + ( + ~refine_sort: (Id.t, Sort.t) => Sort.t=(_, sort) => sort, + ~attr: option(list(Attr.t))=?, + ~font_metrics: FontMetrics.t, + ~rows: Rows.t, + {tiles, range}: geometry, + ) + : list(Node.t) => + switch (range) { + | Some(range) => + term(~refine_sort, ~font_metrics, ~rows, ~tiles, range, ~attr?) + | None => + shards(~refine_sort, ~attr?, ~font_metrics, ~base_clss=None, tiles) + }; + +let term = + ( + ~refine_sort: (Id.t, Sort.t) => Sort.t=(_, sort) => sort, + ~term_data: TermData.t, + ~terms: TermMap.t, + ~measured: Measured.t, + ~font_metrics: FontMetrics.t, + ~attr: option(list(Attr.t))=?, + ~clip_right: option(Point.t)=None, + tile: Tile.t, + ) + : list(Node.t) => + switch (geometry(~term_data, ~terms, ~measured, ~clip_right, tile)) { + | Some(geometry) => + of_geometry( + ~refine_sort, + ~attr?, + ~font_metrics, + ~rows=measured.rows, + geometry, + ) + | None => [] + }; + let term = ( ~refine_sort: (Id.t, Sort.t) => Sort.t=(_, sort) => sort, @@ -381,7 +421,7 @@ let term = ~refine_sort, ~term_data=syntax.term_data, ~terms=syntax.terms, - ~measured=syntax.measured, + ~measured=CachedSyntax.measured(syntax), ~font_metrics, ~clip_right, ); @@ -434,7 +474,12 @@ let completion_clip = switch (List.find(~f=has_shard, result.insertions)) { | None => None | Some(ins) => - switch (CanonicalCompletion.anchor_point(syntax.measured, ins)) { + switch ( + CanonicalCompletion.anchor_point( + CachedSyntax.measured(syntax), + ins, + ) + ) { | None => None | Some(p) => /* the viz anchor walks left past same-tile pieces, so it @@ -444,7 +489,7 @@ let completion_clip = Measured.find_shards( ~msg="Arms.completion_clip", t, - syntax.measured, + CachedSyntax.measured(syntax), ) |> List.map(~f=((_, sm): Shards.shard) => sm.last) |> List.fold_left( @@ -467,7 +512,11 @@ let term_range = (~syntax: CachedSyntax.t, p: Piece.t) => { | Projector(_) | Tile(_) => let id = Language.Any.rep_id(Id.Map.find(Piece.id(p), syntax.terms)); - TermData.extreme_measures(id, syntax.term_data, syntax.measured); + TermData.extreme_measures( + id, + syntax.term_data, + CachedSyntax.measured(syntax), + ); }; }; @@ -511,7 +560,9 @@ module Errors = { switch (Id.Map.find_opt(id, syntax.projectors)) { | Some(p) => /* Special case for projectors as they are not in tile map */ - switch (Id.Map.find_opt(id, syntax.measured.projectors)) { + switch ( + Id.Map.find_opt(id, CachedSyntax.measured(syntax).projectors) + ) { | Some(measurement) => [ ShardDec.simple( { @@ -539,7 +590,7 @@ module Errors = { switch (TermData.segment(id, syntax.term_data)) { | Some(seg) => Highlight.of_segment( - ~measured=syntax.measured, + ~measured=CachedSyntax.measured(syntax), ~shape_map=syntax.shape_map, ~font_metrics, ~shape_init=Some(Convex), @@ -553,7 +604,7 @@ module Errors = { | Some(range) => simple_arm( ~font_metrics, - ~rows=syntax.measured.rows, + ~rows=CachedSyntax.measured(syntax).rows, ~path_cls=[ "child-line", "simple", @@ -613,7 +664,7 @@ module Indicated = { | Grout(_) | Secondary(_) => [] | Projector(p) => - switch (Measured.find_pr_opt(p, syntax.measured)) { + switch (Measured.find_pr_opt(p, CachedSyntax.measured(syntax))) { | Some(measurement) => [ ShardDec.simple( { @@ -681,7 +732,7 @@ module Indicated = { let sort = refine_sort(rep_id, Piece.sort(root) |> fst); simple_arm( ~font_metrics, - ~rows=syntax.measured.rows, + ~rows=CachedSyntax.measured(syntax).rows, ~path_cls=["child-line", Sort.class_of(sort)], range, ); @@ -750,7 +801,7 @@ module Refractors = { let kind_cls = ProjectorCore.Kind.name(kind); simple_arm( ~font_metrics, - ~rows=syntax.measured.rows, + ~rows=CachedSyntax.measured(syntax).rows, ~path_cls=[ "child-line", cls ++ " " ++ kind_cls, @@ -802,7 +853,7 @@ module Refractors = { Haz3lcore.Indicated.index(z) == Some(id) ? [ Highlight.indicated_refractor( - ~measured=syntax.measured, + ~measured=CachedSyntax.measured(syntax), ~shape_map=syntax.shape_map, ~font_metrics, ~kind=entry.kind, diff --git a/src/web/app/editors/decoration/CaretDec.re b/src/web/app/editors/decoration/CaretDec.re index 75e76bc58e..8a14144224 100644 --- a/src/web/app/editors/decoration/CaretDec.re +++ b/src/web/app/editors/decoration/CaretDec.re @@ -59,16 +59,27 @@ let view = ( ~measured: Haz3lcore.Measured.t, ~font_metrics: FontMetrics.t, + /* Optional pre-computed caret position. Sub-editors pass this: + * their splice-local measured map can't measure the caret's + * representative piece at the splice boundary (it's the + * whitespace just outside), so they compute the point themselves + * (SubEditor.caret_point). */ + ~origin: option(Point.t)=?, z: Haz3lcore.Zipper.t, ) : Node.t => { open Haz3lcore; let side = side_of(z); + let origin = + switch (origin) { + | Some(origin) => origin + | None => Zipper.Caret.point(measured, z) + }; main( ~font_metrics, ~profile={ side, - origin: Zipper.Caret.point(measured, z), + origin, shape: Zipper.Caret.direction(z), }, ); diff --git a/src/web/app/editors/decoration/Highlight.re b/src/web/app/editors/decoration/Highlight.re index 46b56110a9..eeb31afac2 100644 --- a/src/web/app/editors/decoration/Highlight.re +++ b/src/web/app/editors/decoration/Highlight.re @@ -707,7 +707,7 @@ let color = switch (TermData.segment(id, syntax.term_data)) { | Some(segment) => of_segment( - ~measured=syntax.measured, + ~measured=CachedSyntax.measured(syntax), ~shape_map=syntax.shape_map, ~font_metrics, ~shape_init=Some(Convex), @@ -756,7 +756,11 @@ let incr_eval = |> List.dedup_and_sort(~compare=Id.compare) |> List.filter_map(~f=id => switch ( - TermData.extreme_measures(id, syntax.term_data, syntax.measured) + TermData.extreme_measures( + id, + syntax.term_data, + CachedSyntax.measured(syntax), + ) ) { | Some(range) => Some((id, range)) | None => None diff --git a/src/web/app/editors/lines/LineNumbers.re b/src/web/app/editors/lines/LineNumbers.re index 5a271fe04e..c5ab8d455b 100644 --- a/src/web/app/editors/lines/LineNumbers.re +++ b/src/web/app/editors/lines/LineNumbers.re @@ -10,7 +10,8 @@ module Model = CodeWithStatics.Model; module View = { let view = (model: Model.t, show_relative_numbers: bool, selected: bool) => { - let {editor: {syntax: {measured, _}, state: {zipper, _}, _}, _}: Model.t = model; + let {editor: {syntax, state: {zipper, _}, _}, _}: Model.t = model; + let measured = CachedSyntax.measured(syntax); let num_rows = List.length(measured.piece_rows); let empty_row = row => { let result = List.nth(List.rev(measured.piece_rows), row); diff --git a/src/web/app/editors/result/EvalResult.re b/src/web/app/editors/result/EvalResult.re index ac6e578aba..8c114d7a40 100644 --- a/src/web/app/editors/result/EvalResult.re +++ b/src/web/app/editors/result/EvalResult.re @@ -10,11 +10,110 @@ open Poly; /* This file follows conventions in [docs/ui-architecture.md] */ +/* The cell's stepper is the theorem stepper over a hidden editor holding + * `theorem cell = ? proof in ?`. Its proof is real syntax, so + * picking a step patches it, its sub-editors splice into it, and the + * checker checks it, as in a theorem. Its goal is the cell's elaborated + * program rather than the statement. */ +module CellStepper = { + [@deriving (show({with_path: false}), sexp, yojson)] + type t = { + goal: Exp.t, + editor: CodeEditable.Model.t, + /* The hidden editor changed since its proof was last checked. */ + edited: bool, + proof_map: ProofMap.t, + stepper: StepperView.Model.t, + }; + + let init = (elab: Exp.t): t => { + let zipper = + Haz3lcore.Parser.to_zipper(~root=Exp, "theorem cell = ? proof ? in ?") + |> Option.value(~default=Haz3lcore.Zipper.init()); + { + goal: + elab |> Substitution.in_exp(Builtins.env_init) |> Exp.replace_all_ids, + editor: + CodeEditable.Model.mk(Haz3lcore.Editor.Model.mk(~root=Exp, zipper)), + edited: true, + proof_map: ProofMap.empty, + stepper: StepperView.Model.init, + }; + }; + + let ctx = + SemanticCtx.of_ctx_and_env( + Builtins.ctx_init(None), + Builtins.closure_env, + ); + + let theorem_proof = (e: Exp.t): option(Proof.t) => + switch (Exp.term_of(e)) { + | Theorem(_, _, proof, _) => Some(proof) + | _ => None + }; + + /* The proof as written. */ + let proof = (cell: t): Proof.t => + CodeEditable.Model.get_statics(cell.editor).term + |> theorem_proof + |> Option.value(~default=Proof.fresh(EmptyHole)); + + let calculate = (~settings: CoreSettings.t, cell: t): t => + if (!cell.edited) { + cell; + } else { + let editor = + CodeEditable.Update.calculate( + ~settings, + ~is_edited=true, + ~stitch=x => x, + ~dynamics=Dynamics.Map.empty, + ~is_dynamic_term=false, + cell.editor, + ); + let statics = CodeEditable.Model.get_statics(editor); + /* The checker checks the elaborated proof, which keeps the written + * proof's ids. */ + let proof_map = + switch ( + Option.bind( + Exp.find_by_id(Exp.rep_id(statics.term), statics.elaborated), + ~f=theorem_proof, + ) + ) { + | Some(elaborated) => + Evaluator.Proofs.check_proof( + ~statics=ProofStatics.of_info_map(statics.info_map), + ~ctx, + ~goal=cell.goal, + elaborated, + ) + | None => ProofMap.empty + }; + let cell = { + ...cell, + editor, + edited: false, + proof_map, + }; + { + ...cell, + stepper: + StepperView.Update.calculate( + ~settings, + StepperRows.chain(~proof_map, proof(cell)), + cell.stepper, + ), + }; + }; +}; + module Model = { [@deriving (show({with_path: false}), sexp, yojson)] type display = | Evaluation(Calc.saved(option((Exp.t, CodeSelectable.Model.t)))) - | Stepper(StepperView.Model.t); + | Stepper(CellStepper.t); [@deriving (show({with_path: false}), sexp, yojson)] type t = { @@ -32,12 +131,17 @@ module Model = { pending_eval_ids: list(Id.t), display, theorems: Theorems.Model.t, - }; - - [@deriving (show({with_path: false}), sexp, yojson)] - type persistent = { - stepper: option(StepperView.Model.persistent), - theorems: Theorems.Model.persistent, + /* Bumped whenever an input of evaluation (elab, settings, targets) + * changes. Worker replies carry the generation of their request, and + * replies to an older request are refused. */ + request_gen: int, + /* The statics the latest request was built from. */ + request_statics: option(Haz3lcore.CachedStatics.t), + /* The latest completed evaluation and the statics of its request, + * which Theorems checks proofs with. While a newer request is pending, + * or after it fails, the pair stays, so a proof is never checked + * against one program's statics and another's environment. */ + checked: Calc.saved(option((Haz3lcore.CachedStatics.t, Dynamics.t))), }; let init = { @@ -53,39 +157,9 @@ module Model = { pending_eval_ids: [], display: Evaluation(Calc.Pending), theorems: Theorems.Model.init, - }; - - let persist = (model: t): persistent => { - stepper: - switch (model.display) { - | Stepper(stepper) => Some(StepperView.Model.persist(stepper)) - | _ => None - }, - theorems: Theorems.Model.persist(model.theorems), - }; - - let unpersist = (p: persistent): t => { - let theorems = Theorems.Model.unpersist(p.theorems); - switch (p.stepper) { - | Some(stepper) => { - cached_settings: Calc.Pending, - elab: Calc.Pending, - cached_targets: Calc.Pending, - result: Calc.NewValue(ProgramResult.awaiting_worker_ack), - dynamics: Calc.Pending, - incr_eval: Calc.Pending, - predicted_reuse: IncrEval.empty, - streaming_outbox: Calc.Pending, - streaming_state: Calc.Pending, - pending_eval_ids: [], - display: Stepper(StepperView.Model.unpersist(stepper)), - theorems, - } - | None => { - ...init, - theorems, - } - }; + request_gen: 0, + request_statics: None, + checked: Calc.Pending, }; let probe_results = (model: t): option(Sample.Map.t) => @@ -117,6 +191,14 @@ module Model = { let pending_eval_ids = (model: t): list(Id.t) => eval_is_pending(model) ? model.pending_eval_ids : []; + /* Proof-check results for this cell, from its last completed evaluation + * (empty until then, or if the cell contains no theorems). Consumed by + * the cursor inspector to show incoming/outgoing expressions on proof + * sub-terms. */ + let proof_map = (model: t): ProofMap.t => model.theorems.proof_map; + + let request_gen = (model: t): int => model.request_gen; + let get_elaboration = (model: t): option(Exp.t) => model.elab |> Calc.get_saved_opt; @@ -140,10 +222,15 @@ module Update = { type t = | ToggleStepper | StepperAction(StepperView.Update.t) + /* Edits to the cell stepper's hidden editor: a picked step, or typing + * in one of its sub-editors. */ + | StepperPatch(Haz3lcore.EditorTransform.patch) + | StepperEditorAction(CodeEditable.Update.t) | EvalEditorAction(CodeSelectable.Update.t) - | UpdateResult(ProgramResult.t(ProgramResult.inner)) - | UpdateStreamingEval(IncrEval.outbox(EvaluatorState.t)) - | MergeStreamingEval(IncrEval.outbox(EvaluatorState.t)) + /* Worker replies carry the generation of the request they answer. */ + | UpdateResult(int, ProgramResult.t(ProgramResult.inner)) + | UpdateStreamingEval(int, IncrEval.outbox(EvaluatorState.t)) + | MergeStreamingEval(int, IncrEval.outbox(EvaluatorState.t)) | TheoremsAction(Theorems.Update.t); /* Whether a cell the user can't edit still takes this action: evaluation @@ -156,6 +243,8 @@ module Update = { | MergeStreamingEval(_) => true | ToggleStepper | StepperAction(_) + | StepperPatch(_) + | StepperEditorAction(_) | EvalEditorAction(_) | TheoremsAction(_) => false }; @@ -163,25 +252,64 @@ module Update = { // Update is meant to make minimal changes to the model, and calculate will do the rest. let update = (~settings, action, model: Model.t): Updated.t(Model.t) => { switch (action, model) { + /* Toggling the stepper and its patches, from clicks in the stepper, + * leave the caret where it was, so they don't take the view back to + * it. */ | (ToggleStepper, {display: Stepper(_), _}) => { ...model, display: Evaluation(Calc.Pending), } - |> Updated.return + |> Updated.return(~scroll=IfCaretVisible) | (ToggleStepper, {display: Evaluation(_), _}) => + let elab = model.elab |> Calc.get_saved(Exp.fresh(EmptyHole)); { ...model, - display: Stepper(StepperView.Model.init), + display: Stepper(CellStepper.init(elab)), } - |> Updated.return - | (StepperAction(a), {display: Stepper(stepper), _}) => - let* stepper = StepperView.Update.update(~settings, a, stepper); + |> Updated.return(~scroll=IfCaretVisible); + | (StepperAction(a), {display: Stepper(cell), _}) => + let* stepper = StepperView.Update.update(~settings, a, cell.stepper); { ...model, - display: Stepper(stepper), + display: + Stepper({ + ...cell, + stepper, + }), }; - | (StepperAction(_), _) => model |> Updated.raise_invalid_action + | (StepperPatch(patch), {display: Stepper(cell), _}) => + let zipper = + Haz3lcore.EditorTransform.apply_patch( + cell.editor.editor.state.zipper, + patch, + ); + { + ...model, + display: + Stepper({ + ...cell, + editor: { + ...cell.editor, + editor: Haz3lcore.Editor.Model.mk(~root=Exp, zipper), + }, + edited: true, + }), + } + |> Updated.return(~scroll=IfCaretVisible); + | (StepperEditorAction(a), {display: Stepper(cell), _}) => + let* editor = CodeEditable.Update.update(~settings, a, cell.editor); + { + ...model, + display: + Stepper({ + ...cell, + editor, + edited: true, + }), + }; + | (StepperAction(_) | StepperPatch(_) | StepperEditorAction(_), _) => + model |> Updated.raise_invalid_action | ( EvalEditorAction(a), {display: Evaluation(Calculated(Some((exp, editor)))), _}, @@ -199,7 +327,11 @@ module Update = { ...model, theorems, }; - | (UpdateResult(result), _) => + | (UpdateResult(gen, _), _) + | (UpdateStreamingEval(gen, _), _) + | (MergeStreamingEval(gen, _), _) when gen != model.request_gen => + model |> Updated.return_quiet + | (UpdateResult(_, result), _) => { ...model, result: Calc.NewValue(result), @@ -211,7 +343,7 @@ module Update = { }, } |> Updated.return_quiet - | (UpdateStreamingEval(stream), _) => + | (UpdateStreamingEval(_, stream), _) => /* Worker ReusePlan arrives here (via on_ack). Snapshot it for the * frozen debug tint; also seed the streaming outbox / pending worklist. */ { @@ -224,7 +356,7 @@ module Update = { EvalWorklist.remove_streamed_ids(stream, model.pending_eval_ids), } |> Updated.return_quiet - | (MergeStreamingEval(stream), _) => + | (MergeStreamingEval(_, stream), _) => let current = model.streaming_outbox |> Calc.get_saved(None) @@ -260,6 +392,9 @@ module Update = { pending_eval_ids, display, theorems, + request_gen, + request_statics, + checked, }: Model.t, ) => { // Check whether settings / elab / targets have changed @@ -275,18 +410,26 @@ module Update = { cached_targets, ); + /* A new request whenever `result` below is recomputed. */ + let new_request = + Calc.is_new(elab) || Calc.is_new(settings) || Calc.is_new(targets); + let request_gen = new_request ? request_gen + 1 : request_gen; + let request_statics = new_request ? Some(statics) : request_statics; + /* Previous incremental map, if the last evaluation produced one. Pull * from the saved field so it survives intermediate pending states * (during which `result` itself is ResultPending). */ let prev_incr = incr_eval |> Calc.get_saved(IncrEval.empty); /* Project statics to the serializable slice the incremental evaluator * needs. The raw info_map can't cross postMessage because LivelitCtx - * entries contain OCaml closures. */ + * entries contain OCaml closures. Built only when it is used. */ let eval_info_map = - EvalInfo.of_info_map( - ~probe_all=Calc.get_value(settings).probe_all, - ~targets=Calc.get_value(targets), - statics.info_map, + lazy( + EvalInfo.of_info_map( + ~probe_all=Calc.get_value(settings).probe_all, + ~targets=Calc.get_value(targets), + statics.info_map, + ) ); let result = result @@ -295,6 +438,7 @@ module Update = { // TODO[Matt]: We could make this more fine-grained, we only care about one setting and.calc settings = settings and.calc _ = targets; + let eval_info_map = Lazy.force(eval_info_map); switch (queue_worker) { // Dynamics is off: | _ when !settings.dynamics => ProgramResult.awaiting_worker_ack @@ -304,6 +448,7 @@ module Update = { expr: elab, eval_info_map, prev: prev_incr, + generation: request_gen, }); ProgramResult.awaiting_worker_ack; // Using the main thread: @@ -313,6 +458,7 @@ module Update = { expr: elab, eval_info_map, prev: prev_incr, + generation: request_gen, }) ) { | Ok((exp, state)) => @@ -368,7 +514,7 @@ module Update = { | (NewValue(ProgramResult.ResultOk(_)), None) => ReusePass.reuse_pass( ~prev=prev_incr, - ~eval_info=eval_info_map, + ~eval_info=Lazy.force(eval_info_map), ~env=Builtins.env_init, Calc.get_value(elab), ) @@ -394,6 +540,7 @@ module Update = { test_results: state |> EvaluatorState.get_tests |> TestResults.mk_results, theorems: state |> EvaluatorState.get_theorems, + proof_map: state |> EvaluatorState.get_proof_map, }; let dynamics = dynamics @@ -403,7 +550,8 @@ module Update = { switch (result, streaming_state) { | (ProgramResult.ResultPending(_), Some(state)) => Some(dynamics_of_state(state)) - | (ProgramResult.ResultPending(_), None) + | (ProgramResult.ResultPending(_), None) => + dynamics |> Calc.get_saved(None) | (ProgramResult.ResultFail(_), _) => dynamics |> Calc.get_saved(None) | (ProgramResult.ResultOk({state, _}), _) => @@ -411,6 +559,14 @@ module Update = { }; }; + let checked = + switch (result, request_statics, checked) { + | (NewValue(ProgramResult.ResultOk({state, _})), Some(statics), _) => + Calc.NewValue(Some((statics, dynamics_of_state(state)))) + | (_, _, Calculated(checked)) => Calc.OldValue(checked) + | (_, _, Pending) => Calc.NewValue(None) + }; + let incr_eval = incr_eval |> { @@ -471,34 +627,29 @@ module Update = { ) |> Calc.save |> (x => Model.Evaluation(x)); - | Stepper(stepper) => + /* A new program starts its proof over. */ + | Stepper(cell) => + let cell = + Calc.is_new(elab) ? CellStepper.init(Calc.get_value(elab)) : cell; Model.Stepper( - StepperView.Update.calculate( - ~settings, - ~ctx= - OldValue( - SemanticCtx.of_ctx_and_env( - Builtins.ctx_init(None), - Builtins.closure_env, - ), - ), - elab, - stepper, - ), - ) - }; - - // HACK[Matt]: say that statics is updated iff dynamics is updated - let statics: Calc.t('a) = - switch (dynamics) { - | NewValue(_) => NewValue(statics) - | OldValue(_) => OldValue(statics) + CellStepper.calculate(~settings=Calc.get_value(settings), cell), + ); }; let theorems = Calc.get_value(settings).dynamics - ? theorems - |> Theorems.Update.calculate(~settings, ~statics, ~dynamics) + ? Theorems.Update.calculate( + ~settings, + ~statics=Calc.map(_ => statics, elab), + ~checked, + ~checking= + switch (Calc.get_value(result)) { + | ResultPending(_) => true + | ResultOk(_) + | ResultFail(_) => false + }, + theorems, + ) : theorems; ( @@ -515,6 +666,9 @@ module Update = { pending_eval_ids, display, theorems, + request_gen, + request_statics, + checked: checked |> Calc.save, }: Model.t ); }; @@ -539,12 +693,12 @@ module Selection = { editor, ); Update.EvalEditorAction(ci); - | (Stepper(focus), Stepper(s)) => + | (Stepper(focus), Stepper(cell)) => let+ ci = StepperView.Focus.get_cursor_info( ~inject=x => inject(Update.StepperAction(x)), ~focus, - s, + cell.stepper, ); Update.StepperAction(ci); | (Evaluation(_), _) => Cursor.empty @@ -566,7 +720,9 @@ module View = { type event = | MakeActive(Selection.t) - | JumpTo(Id.t); + | JumpTo(Id.t) + /* Focus leaves the result for the cell's editor. */ + | ReturnToEditor; let error_msg = (err: ProgramResult.error) => switch (err) { @@ -682,21 +838,57 @@ module View = { editor |> Calc.get_saved_exc(~print="result editor missing"), ), ] - | Stepper(s) => - StepperView.View.view( - ~globals, - ~selected= - switch (selected) { - | Some(Stepper(s)) => Some(s) - | _ => None + | Stepper(cell) => + let stepper_view = + StepperView.View.view( + ~globals, + ~selected= + switch (selected) { + | Some(Stepper(s)) => Some(s) + | _ => None + }, + ~signal= + fun + | HideStepper => inject(ToggleStepper) + | MakeActive(s) => signal(MakeActive(Stepper(s))) + | ReturnToEditor => signal(ReturnToEditor), + ~inject=x => inject(StepperAction(x)), + ~is_toplevel=true, + ~edit_syntax=patch => inject(StepperPatch(patch)), + ~backing={ + model: cell.editor, + inject: a => inject(StepperEditorAction(a)), }, - ~signal= - fun - | HideStepper => inject(ToggleStepper) - | MakeActive(s) => signal(MakeActive(Stepper(s))), - ~inject=x => inject(StepperAction(x)), - s, - ) + ~info_map=CodeEditable.Model.get_statics(cell.editor).info_map, + ~proof_map=cell.proof_map, + ~exits=_ => [], + CellStepper.proof(cell), + cell.stepper, + ); + /* The stepper renders from the last proof map / elaboration it saw, + * so on evaluation failure it silently shows stale rows; surface the + * failure above them. */ + switch (model.result |> Calc.get_value) { + | ResultFail(err) => [ + div( + ~attrs=[ + Attr.classes(["cell-item", "cell-result", "stepper-stale"]), + ], + [ + div( + ~attrs=[Attr.classes(["error-msg"])], + [text(error_msg(err))], + ), + div( + ~attrs=[Attr.classes(["stale-note"])], + [text("Steps below show the last successful evaluation.")], + ), + ], + ), + ...stepper_view, + ] + | _ => stepper_view + }; }; let test_status_icon_view = @@ -747,6 +939,10 @@ module View = { | `Custom(Node.t) ]=`EvalResults, ~locked: bool, + /* Writes a patch into the cell's program. */ + ~edit_syntax: Haz3lcore.EditorTransform.patch => Ui_effect.t(unit), + /* The cell's editor, which theorem steppers splice into. */ + ~main_editor: CodeEditable.Channel.t, model: Model.t, ) => switch (result_kind) { @@ -762,7 +958,7 @@ module View = { | Some(result) => [ test_result_layer( ~font_metrics=globals.font_metrics, - ~measured=editor.syntax.measured, + ~measured=Haz3lcore.CachedSyntax.measured(editor.syntax), result, ), ] @@ -774,12 +970,15 @@ module View = { : Theorems.View.view( ~globals, ~take_focus=f => signal(MakeActive(Theorems(f))), + ~return_to_editor=signal(ReturnToEditor), ~inject=a => inject(TheoremsAction(a)), ~selected= switch (selected) { | Some(Theorems(f)) => Some(f) | _ => None }, + ~edit_syntax, + ~main_editor, model.theorems, ); let theorems = @@ -815,7 +1014,7 @@ module View = { | Some(result) => [ test_result_layer( ~font_metrics=globals.font_metrics, - ~measured=editor.syntax.measured, + ~measured=Haz3lcore.CachedSyntax.measured(editor.syntax), result, ), ] @@ -838,7 +1037,7 @@ module View = { | Some(result) => [ test_result_layer( ~font_metrics=globals.font_metrics, - ~measured=editor.syntax.measured, + ~measured=Haz3lcore.CachedSyntax.measured(editor.syntax), result, ), ] @@ -855,7 +1054,7 @@ module View = { | Some(result) => [ test_result_layer( ~font_metrics=globals.font_metrics, - ~measured=editor.syntax.measured, + ~measured=Haz3lcore.CachedSyntax.measured(editor.syntax), result, ), ] diff --git a/src/web/app/editors/result/StepperEditor.re b/src/web/app/editors/result/StepperEditor.re index b9b965817d..11a59d46c0 100644 --- a/src/web/app/editors/result/StepperEditor.re +++ b/src/web/app/editors/result/StepperEditor.re @@ -4,15 +4,110 @@ open Poly; /* This file follows conventions in [docs/ui-architecture.md] */ +/* Where a goal editor's highlights and lines go. They are read off the + * editor's layout when the editor or what it marks changes, not on every + * render. */ +module Deco = { + [@deriving (show({with_path: false}), sexp, yojson)] + type marks = { + /* The offered steps and reflexivities, which a click takes. */ + next_steps: list(Id.t), + refls: list(Id.t), + /* The part the step below acts on. */ + acts_on: option(Id.t), + /* The selected part, which the write box writes a replacement for. */ + selected: option(Id.t), + /* The part a step the user is choosing would act on. */ + previewing: option(Id.t), + }; + + let no_marks = { + next_steps: [], + refls: [], + acts_on: None, + selected: None, + previewing: None, + }; + + [@deriving (show({with_path: false}), sexp, yojson)] + type t = { + marks, + /* The layout read. */ + [@opaque] + syntax: CachedSyntax.t, + /* In the order of their marks, so that a click on one takes it by + * index. None for a mark the editor doesn't draw. */ + next_steps: list(option(Arms.geometry)), + refls: list(option(Arms.geometry)), + /* A line under each row the part covers. */ + acts_on: list(Measured.measurement), + selected: list(Measured.measurement), + previewing: list(Measured.measurement), + }; + + let mk = (~syntax: CachedSyntax.t, marks: marks): t => { + let measured = CachedSyntax.measured(syntax); + let arm = id => + Option.bind(TermData.root_tile(id, syntax.term_data), ~f=tile => + Arms.geometry( + ~term_data=syntax.term_data, + ~terms=syntax.terms, + ~measured, + tile, + ) + ); + let line = id => + switch ( + Option.bind(id, ~f=id => + TermData.extreme_measures(id, syntax.term_data, measured) + ) + ) { + | None => [] + | Some((origin, last)) => + ListUtil.range(~lo=origin.row, last.row + 1) + |> List.map(~f=row => { + let shape = Measured.Rows.find(row, measured.rows); + Measured.{ + origin: { + row, + col: row == origin.row ? origin.col : shape.content_start, + }, + last: { + row, + col: row == last.row ? last.col : shape.content_end, + }, + }; + }) + }; + { + marks, + syntax, + next_steps: List.map(~f=arm, marks.next_steps), + refls: List.map(~f=arm, marks.refls), + acts_on: line(marks.acts_on), + selected: line(marks.selected), + previewing: line(marks.previewing), + }; + }; + + /* `deco` itself while its editor's syntax and its marks are the same, + * so that its identity says whether it changed. */ + let update = (~syntax: CachedSyntax.t, marks: marks, deco: t): t => + phys_equal(syntax, deco.syntax) && marks == deco.marks + ? deco : mk(~syntax, marks); +}; + module Model = { [@deriving (show({with_path: false}), sexp, yojson)] type t = { - // Updated editor: CodeSelectable.Model.t, - // Read-only - taken_steps: list(Id.t), - next_steps: list(Id.t), - refls: list(Id.t), + deco: Deco.t, + /* Whether the offered steps and reflexivities are highlighted. */ + hints: bool, + /* Whether the line goes under the selected part instead of where the + * step acts. */ + replacing: bool, + previewing: bool, }; }; @@ -34,88 +129,62 @@ module View = { | TakeStep(int) | Refl(int); + /* Highlights on the offered steps and reflexivities, where a click + * takes one, and lines under parts, which take no click: they mark + * where a step acts, which isn't a step to take. */ let deco = ( - ~syntax: CachedSyntax.t, ~font_metrics: FontMetrics.t, - ~inject: Update.t => Ui_effect.t(unit), - ~selected_id: option(Id.t), signal: event => Ui_effect.t(unit), model: Model.t, ) => { - open WebUtil; - - let next_steps = - (next_steps: list(Id.t), ~inject: int => Ui_effect.t(unit)) => - next_steps - |> List.filter_map(~f=TermData.root_tile(_, syntax.term_data)) - |> List.mapi(~f=(i, t: Tile.t) => - div_c( - "step-next", - Arms.term( - ~attr=[Attr.on_mousedown(_ => inject(i))], - ~font_metrics, - ~syntax, - t, - ), + let deco = model.deco; + let rows = CachedSyntax.measured(deco.syntax).rows; + let highlights = (~cls, arms, take: int => event) => + arms + |> List.mapi(~f=(i, arm) => + Option.map( + ~f= + arm => + WebUtil.div_c( + cls, + Arms.of_geometry( + ~attr=[ + WebUtil.Attr.on_mousedown(_ => signal(take(i))), + ], + ~font_metrics, + ~rows, + arm, + ), + ), + arm, ) - ); - - let taken_steps = (taken_steps: list(Id.t)) => - taken_steps - |> List.filter_map(~f=TermData.root_tile(_, syntax.term_data)) - |> List.map(~f=t => - div_c("step-taken", Arms.term(~font_metrics, ~syntax, t)) - ); - - let refl_steps = - (refl_steps: list(Id.t), ~inject: int => Ui_effect.t(unit)) => - refl_steps - |> List.filter_map(~f=TermData.root_tile(_, syntax.term_data)) - |> List.mapi(~f=(i, t: Tile.t) => - div_c( - "step-refl", - Arms.term( - ~attr=[Attr.on_mousedown(_ => inject(i))], - ~font_metrics, - ~syntax, - t, - ), - ) - ); - - taken_steps(model.taken_steps) - @ next_steps(model.next_steps, ~inject=x => - { - open OptUtil.Syntax; - let+ range = - TermData.extreme_measures( - List.nth_exn(model.next_steps, x), - model.editor.editor.syntax.term_data, - model.editor.editor.syntax.measured, - ); - Some(List.nth_exn(model.next_steps, x)) == selected_id - ? signal(TakeStep(x)) : inject(Select(PointToPoint(range))); - } - |> Option.value(~default=Ui_effect.Ignore) - ) - @ refl_steps(model.refls, ~inject=x => - { - open OptUtil.Syntax; - let+ range = - TermData.extreme_measures( - List.nth_exn(model.refls, x), - model.editor.editor.syntax.term_data, - model.editor.editor.syntax.measured, - ); - Some(List.nth_exn(model.refls, x)) == selected_id - ? signal(Refl(x)) - : { - inject(Select(PointToPoint(range))); - }; - } - |> Option.value(~default=Ui_effect.Ignore) + ) + |> List.filter_map(~f=Fn.id); + let lines = (~cls, lines) => + List.map( + ~f= + (line: Measured.measurement) => + Virtual_dom.Vdom.Node.div( + ~attrs=[ + WebUtil.Attr.classes([cls]), + DecUtil.abs_style(~font_metrics, line), + ], + [], + ), + lines, ); + ( + model.hints + ? highlights(~cls="step-next", deco.next_steps, i => TakeStep(i)) + @ highlights(~cls="step-refl", deco.refls, i => Refl(i)) + : [] + ) + @ lines( + ~cls="step-acts-on", + model.replacing ? deco.selected : deco.acts_on, + ) + @ (model.previewing ? lines(~cls="step-previewing", deco.previewing) : []); }; /* Steppers don't support probe dynamics - expressions shown are @@ -126,13 +195,14 @@ module View = { ~inject, ~signal: event => 'a, ~overlays=[], + ~keys: Util.Key.t => option(Ui_effect.t(unit))=_ => None, ~selected, - ~selected_id, ~_dynamics: Language.Dynamics.Map.t=Language.Dynamics.Map.empty, model: Model.t, ) => { CodeSelectable.View.view( ~expand_selection=true, + ~keys, ~dynamics=Language.Dynamics.Map.empty, ~signal= fun @@ -146,15 +216,7 @@ module View = { }), ~globals, ~overlays= - overlays - @ deco( - ~syntax=model.editor.editor.syntax, - ~font_metrics=globals.font_metrics, - ~inject, - ~selected_id, - signal, - model, - ), + overlays @ deco(~font_metrics=globals.font_metrics, signal, model), model.editor, ); }; diff --git a/src/web/app/editors/result/Theorems.re b/src/web/app/editors/result/Theorems.re index ac120ce96b..bee87e7b45 100644 --- a/src/web/app/editors/result/Theorems.re +++ b/src/web/app/editors/result/Theorems.re @@ -1,383 +1,551 @@ open Util; -open Calc.Syntax; open Language; open Poly; +/* The theorems of a cell, each with its stepper. The + * theorems and their proof map come from the last completed evaluation, + * checked with the statics of its request. Their proofs' syntax is read + * from the current statics, so a step just written has its row (and its + * sub-editors, which take focus) at once; it shows a goal once a check + * reaches it. */ + +/* This file follows conventions in [docs/ui-architecture.md] */ + +/* Theorem steppers always show the proof's history. */ +let with_proof_settings = (settings: CoreSettings.t): CoreSettings.t => { + ...settings, + evaluation: { + ...settings.evaluation, + enable_proof: true, + stepper_history: true, + }, +}; + module Model = { [@deriving (show({with_path: false}), sexp, yojson)] type theorem = { name: string, - ctx: Calc.saved(Ctx.t), - env: Calc.saved(Environment.t(Exp.t)), - sem_ctx: Calc.saved(SemanticCtx.t), - goal_exp: Calc.saved(Exp.t), - stepper_view: StepperView.Model.t, - }; - - [@deriving (show({with_path: false}), sexp, yojson)] - type persistent_theorem = {stepper_view: StepperView.Model.persistent}; - - let theorem_init = name => { - name, - ctx: Calc.Pending, - env: Calc.Pending, - sem_ctx: Calc.Pending, - goal_exp: Calc.Pending, - stepper_view: StepperView.Model.init, + /* The proof as written; a hole when there is none. */ + proof: Proof.t, + stepper: StepperView.Model.t, + /* While the program no longer reaches the theorem, or its proof can't + * be found, the stepper is drawn as it last was, with the proof map + * it was checked with, and keeps its state for when the theorem is + * back. */ + stale: option(ProofMap.t), }; [@deriving (show({with_path: false}), sexp, yojson)] type t = { + /* In program order. */ + thms: list(Id.t), thm_map: Id.Map.t(theorem), - thms: Calc.saved(list(Id.t)), + /* The cell's ProofMap, shared by all its theorems. */ + proof_map: ProofMap.t, + /* The statics of the proofs' syntax. */ + info_map: Statics.Map.t, }; - [@deriving (show({with_path: false}), sexp, yojson)] - type persistent = {thm_map: Id.Map.t(persistent_theorem)}; - let init = { + thms: [], thm_map: Id.Map.empty, - thms: Calc.Pending, - }; - - let persist = (model: t): persistent => { - thm_map: - Id.Map.map( - (thm: theorem) => - {stepper_view: StepperView.Model.persist(thm.stepper_view)}, - model.thm_map, - ), + proof_map: ProofMap.empty, + info_map: Statics.Map.empty, }; - let unpersist = (p: persistent): t => { - thm_map: - Id.Map.map( - (p_thm: persistent_theorem): theorem => - { - name: "?", - ctx: Calc.Pending, - env: Calc.Pending, - sem_ctx: Calc.Pending, - goal_exp: Calc.Pending, - stepper_view: StepperView.Model.unpersist(p_thm.stepper_view), - }, - p.thm_map, - ), - thms: Calc.Pending, - }; + let theorems = (model: t): list((Id.t, theorem)) => + List.filter_map( + ~f= + id => + Id.Map.find_opt(id, model.thm_map) |> Option.map(~f=t => (id, t)), + model.thms, + ); let get_score = (model: t): option((float, float)) => { - open OptUtil.Syntax; - let* thms = model.thms |> Calc.get_saved_opt; - let total = float_of_int(List.length(thms)); - let correct = - List.fold_left( + let thms = + List.filter(~f=((_, thm)) => thm.stale == None, theorems(model)); + /* Only a proof with nothing unproven scores. One relying on an + * unfinished lemma doesn't: the lemma could state the theorem itself. */ + let proven = + List.filter( ~f= - (acc, id) => - acc - +. ( - switch (Id.Map.find_opt(id, model.thm_map)) { - | Some(thm) => - StepperView.Model.get_validity(thm.stepper_view) - == Some(true) - ? 1.0 : 0.0 - | None => 0.0 - } - ), - ~init=0.0, + ((_, thm)) => + Obligations.Status.of_proof(model.proof_map, thm.proof) == Proven, thms, ); - Some((correct, total)); + Some(( + float_of_int(List.length(proven)), + float_of_int(List.length(thms)), + )); }; }; +/* The theorems drawn last, by id. A theorem whose inputs are all the same + * objects as when it was drawn gets the same node, which the virtual DOM + * then skips: a key in one theorem's write box changes no other. Kept + * outside the model, as only the view uses it. A kept node's handlers + * close over these inputs and the cell's dispatchers alone, so they act + * on the theorem as it is. */ +module Drawn = { + type inputs = { + theorem: Model.theorem, + proof_map: ProofMap.t, + info_map: Statics.Map.t, + selected: option(StepperView.Focus.t), + main_editor: CodeEditable.Model.t, + settings: Settings.t, + font_metrics: FontMetrics.t, + meta_down: bool, + color_highlights: option(ColorSteps.colorMap), + }; + + let entries: Hashtbl.t(Id.t, (inputs, Virtual_dom.Vdom.Node.t)) = + Hashtbl.create(16); + + let same = (a: inputs, b: inputs) => + phys_equal(a.theorem, b.theorem) + && phys_equal(a.proof_map, b.proof_map) + && phys_equal(a.info_map, b.info_map) + && a.selected == b.selected + /* The cell builds its editor's records again on every pass, its zipper + * included, around the same syntax and statics. A sub-editor reads the + * zipper only for its caret, so a theorem whose sub-editor has focus + * is always drawn. */ + && ( + switch (b.selected) { + | Some(Splice(_)) => false + | Some(Goal(_) | Box(_)) + | None => true + } + ) + && phys_equal(a.main_editor.editor.syntax, b.main_editor.editor.syntax) + && phys_equal( + a.main_editor.statics.info_map, + b.main_editor.statics.info_map, + ) + && phys_equal( + a.main_editor.statics.error_ids, + b.main_editor.statics.error_ids, + ) + && phys_equal( + a.main_editor.statics.warning_ids, + b.main_editor.statics.warning_ids, + ) + && phys_equal( + a.main_editor.statics.completion, + b.main_editor.statics.completion, + ) + && phys_equal(a.main_editor.dynamics, b.main_editor.dynamics) + && a.main_editor.context_menu == b.main_editor.context_menu + && phys_equal(a.settings, b.settings) + && phys_equal(a.font_metrics, b.font_metrics) + && a.meta_down == b.meta_down + && phys_equal(a.color_highlights, b.color_highlights); + + let view = (id: Id.t, inputs: inputs, draw: unit => Virtual_dom.Vdom.Node.t) => + switch (Hashtbl.find_opt(entries, id)) { + | Some((last, node)) when same(last, inputs) => node + | Some(_) + | None => + let node = draw(); + Hashtbl.replace(entries, id, (inputs, node)); + node; + }; +}; + module Update = { open Updated; [@deriving (show({with_path: false}), sexp, yojson)] type t = - | TheoremUpdate(int, StepperView.Update.t); + | TheoremUpdate(Id.t, StepperView.Update.t); - let update = (~settings, action, model: Model.t): Updated.t(Model.t) => { - let settings = - Settings.Model.{ - ...settings, - core: { - ...settings.core, - evaluation: { - ...settings.core.evaluation, - enable_proof: true, - stepper_history: true, - }, - }, - }; + let update = + (~settings: Settings.t, action, model: Model.t): Updated.t(Model.t) => { + let settings = { + ...settings, + core: with_proof_settings(settings.core), + }; switch (action) { - | TheoremUpdate(n, action) => - let id_and_thm = { - open OptUtil.Syntax; - let* id = List.nth(model.thms |> Calc.get_saved([]), n); - let* thm = Id.Map.find_opt(id, model.thm_map); - Some((id, thm)); - }; - switch (id_and_thm) { - | Some((id, thm)) => - let* stepper_view = - StepperView.Update.update(~settings, action, thm.stepper_view); - let thm_map = - Id.Map.add( - id, - { - ...thm, - stepper_view, - }, - model.thm_map, - ); - Model.{ + | TheoremUpdate(id, action) => + switch (Id.Map.find_opt(id, model.thm_map)) { + | Some(thm) => + let* stepper = + StepperView.Update.update(~settings, action, thm.stepper); + { ...model, - thm_map, + thm_map: + Id.Map.add( + id, + { + ...thm, + stepper, + }, + model.thm_map, + ), }; - | None => model |> Updated.raise_invalid_action - }; + | None => model |> raise_invalid_action + } }; }; let calculate = ( ~settings: Calc.t(CoreSettings.t), + /* The cell's current statics. */ ~statics: Calc.t(Haz3lcore.CachedStatics.t), - ~dynamics: Calc.t(option(Dynamics.t)), - {thm_map, thms}: Model.t, - ) => { - let settings' = { - ...Calc.get_value(settings), - evaluation: { - ...Calc.get_value(settings).evaluation, - enable_proof: true, - stepper_history: true, - }, - }; - let settings = - switch (settings) { - | OldValue(_) => Calc.OldValue(settings') - | NewValue(_) => Calc.NewValue(settings') + /* A completed evaluation and the statics of its request + * (EvalResult.Model.checked). */ + ~checked: Calc.t(option((Haz3lcore.CachedStatics.t, Dynamics.t))), + /* Whether a newer evaluation is running, whose check will give the + * goals of steps written since `checked`. */ + ~checking: bool, + model: Model.t, + ) + : Model.t => + switch (settings, statics, checked) { + | (OldValue(_), OldValue(_), OldValue(_)) => model + | _ => + let settings = with_proof_settings(Calc.get_value(settings)); + /* `after`, once the drawn nodes of the theorems it drops are + * forgotten. */ + let prune = (after: Model.t): Model.t => { + Id.Map.iter( + (id, thm: Model.theorem) => + if (!Id.Map.mem(id, after.thm_map)) { + Hashtbl.remove(Drawn.entries, id); + StepperView.Drawn.prune( + ~before=thm.stepper, + ~after=StepperView.Model.init, + ); + }, + model.thm_map, + ); + after; }; - let thms = - thms - |> { - let.calc dynamics = dynamics; - let theorems = - switch (dynamics) { - | None => [] - | Some(d) => d.theorems + switch (Calc.get_value(checked)) { + | None => prune(Model.init) + | Some((checked_statics, dynamics)) => + /* The evaluation checked each proof in what it has of the proof's + * scope: the theorems, and the proof's own binders. The steppers + * also type the goals, so each step's scope gets the program's + * types and variables, from the statics at its theorem. */ + let proof_map = + if (Calc.is_new(checked)) { + let with_typing = (proof_map, (id, _, _, _)) => + switch ( + Statics.Map.lookup_exp(id, checked_statics.info_map), + Exp.find_by_id(id, checked_statics.elaborated), + ) { + | (Some({ctx, _}), Some({term: Theorem(_, _, proof, _), _})) => + let rec go = (proof_map, p: Proof.t) => + List.fold_left( + ~f=go, + ~init= + switch (ProofMap.lookup(Proof.rep_id(p), proof_map)) { + | Some(entry) => + ProofMap.add( + Proof.rep_id(p), + { + ...entry, + ctx: SemanticCtx.with_typing(ctx, entry.ctx), + }, + proof_map, + ) + | None => proof_map + }, + Proof.children(p), + ); + go(proof_map, proof); + | _ => proof_map + }; + List.fold_left( + ~f=with_typing, + ~init=dynamics.proof_map, + dynamics.theorems, + ); + } else { + model.proof_map; }; - let theorems = - List.map( - ~f= - ((a, b, c, d)) => { - let d' = ProofRule.exp_to_rule(d); - (a, b, c, d'); + let info_map = Calc.get_value(statics).info_map; + let syntax = id => + switch (Statics.Map.lookup_exp(id, info_map)) { + | Some(info) => Some(info) + | None => Statics.Map.lookup_exp(id, checked_statics.info_map) + }; + let stale = (thm: Model.theorem) => { + ...thm, + stale: Some(Option.value(~default=model.proof_map, thm.stale)), + }; + /* Each theorem keeps its stepper's state from the last pass. */ + let theorem = ((id, name, _, _)) => + switch ( + syntax(id) + |> Option.map(~f=(info: Info.exp) => Exp.term_of(info.user_term)), + Id.Map.find_opt(id, model.thm_map), + ) { + | (Some(Theorem(_, _, proof, _)), last) => + let stepper = + switch (last) { + | Some(thm) => thm.stepper + | None => StepperView.Model.init + }; + let stepper = + StepperView.Update.calculate( + ~settings, + ~checking, + StepperRows.of_theorem(~proof_map, proof), + stepper, + ); + ( + id, + Model.{ + name, + proof, + stepper, + stale: None, }, - theorems, + ); + | (_, Some(thm)) => (id, stale(thm)) + | (_, None) => ( + id, + Model.{ + name, + proof: Proof.fresh(EmptyHole), + stepper: StepperView.Model.init, + stale: None, + }, + ) + }; + let reached = List.rev_map(~f=theorem, dynamics.theorems); + /* A theorem the evaluation didn't reach, after a typo above it, + * stays while it is still in the program. */ + let unreached = + List.filter_map( + ~f= + id => + switch ( + List.Assoc.mem(reached, id, ~equal=Id.equal), + Id.Map.find_opt(id, model.thm_map), + Statics.Map.lookup_exp(id, info_map), + ) { + | (false, Some(thm), Some(_)) => Some((id, stale(thm))) + | (true, _, _) + | (false, None, _) + | (false, _, None) => None + }, + model.thms, ); - List.rev_map(~f=((id, _, _, _)) => id, theorems); - } - |> Calc.old_if_same'(thms); - - // Calculate visible steppers - let thm_map = - dynamics - |> Calc.get_value - |> ( - fun - | None => [] - | Some(x) => x.theorems - ) - |> List.map(~f=((a, b, c, d)) => { - let d' = - ProofRule.exp_to_rule( - d |> Substitution.in_exp(Environment.empty), - ); - (a, b, c, d'); - }) - |> List.fold_left( - ~f= - (acc, (id, name, env', rule: ProofRule.t)) => - Id.Map.update( - id, - (opt: option(Model.theorem)) => { - let Model.{ - name: _, - ctx, - env, - sem_ctx, - goal_exp, - stepper_view, - } = - Option.value(~default=Model.theorem_init("?"), opt); - - let goal_exp = - Calc.set( - ~eq=Exp.fast_equal_with_lexemes, - rule |> ProofRule.conclusion_exp, - goal_exp, - ); - - let ctx = - ctx - |> { - let.calc statics = statics; - statics.info_map - |> Statics.Map.ctx_of(id) - |> Option.value(~default=Ctx.empty) - |> List.fold_left( - ~f=Ctx.extend, - ~init=_, - rule.bindings |> List.rev, - ); - }; - - let env = Calc.set(~eq=Environment.id_equal, env', env); - - let sem_ctx = - sem_ctx - |> { - let.calc ctx = ctx - and.calc env = env; - SemanticCtx.of_ctx_and_env(ctx, env); - }; - - let stepper_view = - StepperView.Update.calculate( - ~settings, - ~ctx=sem_ctx, - ~ana=Calc.OldValue(Typ.fresh(Atom(Bool))), - goal_exp, - stepper_view, - ); - - Some({ - name, - ctx: ctx |> Calc.save, - env: env |> Calc.save, - sem_ctx: sem_ctx |> Calc.save, - goal_exp: goal_exp |> Calc.save, - stepper_view, - }); - }, - acc, - ), - ~init=thm_map, - ); - - Model.{ - thm_map, - thms: thms |> Calc.save, + let theorems = reached @ unreached; + prune({ + thms: List.map(~f=fst, theorems), + thm_map: Id.Map.of_list(theorems), + proof_map, + info_map, + }); + }; }; - }; }; module Focus = { open Cursor; + [@deriving (show({with_path: false}), sexp, yojson)] - type t = (int, StepperView.Focus.t); + type t = (Id.t, StepperView.Focus.t); - let get_cursor_info = (~inject, ~focus: t, model: Model.t) => { - let id_and_thm = { - open OptUtil.Syntax; - let* id = List.nth(model.thms |> Calc.get_saved([]), focus |> fst); - let* thm = Id.Map.find_opt(id, model.thm_map); - Some((id, thm)); - }; - switch (id_and_thm) { - | Some((_id, thm)) => + let get_cursor_info = (~inject, ~focus as (id, focus): t, model: Model.t) => + switch (Id.Map.find_opt(id, model.thm_map)) { + | Some(thm) => let+ c = StepperView.Focus.get_cursor_info( - ~inject=x => inject(Update.TheoremUpdate(focus |> fst, x)), - ~focus=snd(focus), - thm.stepper_view, + ~inject=x => inject(Update.TheoremUpdate(id, x)), + ~focus, + thm.stepper, ); - Update.TheoremUpdate(focus |> fst, c); + Update.TheoremUpdate(id, c); | None => Cursor.empty }; - }; }; module View = { open WebUtil; + /* The steppers' settings, the same object while they are the same, so + * that a stepper's rows can tell that nothing they show changed. The + * cell builds its settings again on every render, so they are compared + * by value. */ + let last_settings: ref(option(Settings.t)) = ref(None); + let stepper_settings = (settings: Settings.t): Settings.t => { + let steppers = { + ...settings, + core: with_proof_settings(settings.core), + }; + switch (last_settings^) { + | Some(last) when last == steppers => last + | Some(_) + | None => + last_settings := Some(steppers); + steppers; + }; + }; + let view = ( ~globals: Globals.t, ~take_focus: Focus.t => Ui_effect.t(unit), + ~return_to_editor: Ui_effect.t(unit), ~inject: Update.t => Ui_effect.t(unit), ~selected: option(Focus.t), + /* Writes a patch into the cell's program. */ + ~edit_syntax: Haz3lcore.EditorTransform.patch => Ui_effect.t(unit), + /* The cell's editor, which the steppers' sub-editors splice into. */ + ~main_editor: CodeEditable.Channel.t, model: Model.t, ) => { let globals = { ...globals, - settings: { - ...globals.settings, - core: { - ...globals.settings.core, - evaluation: { - ...globals.settings.core.evaluation, - enable_proof: true, - stepper_history: true, - }, - }, - }, + settings: stepper_settings(globals.settings), }; - switch (model.thms |> Calc.get_saved([])) { - | [] => [] - | xs => - List.mapi( - ~f= - (idx, id) => { - let Model.{stepper_view, name, _} = - Id.Map.find(id, model.thm_map); - let status = - switch (StepperView.Model.get_validity(stepper_view)) { - | Some(true) => - Node.div( - ~attrs=[Attr.classes(["theorem-status", "true"])], - [Node.text("proven true")], - ) - | Some(false) - | None => - Node.div( - ~attrs=[Attr.classes(["theorem-status", "unknown"])], - [Node.text("incomplete")], - ) - }; - let header = - WebUtil.div_c( - "theorem-header", - [ - Node.strong([Node.text("Proof of theorem ")]), - Node.text(name), - status, + let theorem = ((id, {name, proof, stepper, stale}: Model.theorem)) => { + let proof_map = Option.value(~default=model.proof_map, stale); + /* A stale stepper is for reading: its proof may not be where it was + * in the program. */ + let edit_syntax = stale == None ? edit_syntax : (_ => Ui_effect.Ignore); + let status = Obligations.Status.of_proof(proof_map, proof); + let dom_id = "theorem-" ++ Id.to_string(id); + let header = + div_c( + "theorem-header", + [ + Node.strong([Node.text("Proof of theorem ")]), + Node.text(name), + switch (stale) { + | Some(_) => + Node.div( + ~attrs=[ + Attr.classes(["theorem-status", "stale"]), + Attr.title( + "The program doesn't run as far as this theorem, or its proof can't be found. This is how it was last checked.", + ), ], + [Node.text("not checked")], + ) + | None => + let to_first_gap = _ => + Ui_effect.of_sync_fun( + () => + Js_of_ocaml.( + Dom_html.document##querySelector( + Js.string( + "#" + ++ dom_id + ++ " .condition-dot.unproven:not(.citation)", + ), + ) + ) + |> Js_of_ocaml.Js.Opt.to_option + |> Option.iter( + ~f=JsUtil.scroll_vertically_into_view_ancestors, + ), + (), + ); + Node.div( + ~attrs= + [ + Attr.classes([ + "theorem-status", + Obligations.Status.class_(status), + ]), + ] + @ ( + switch (status) { + | Relying(names) => [ + Attr.title( + "Proven, assuming " + ++ String.concat(~sep=", ", names) + ++ ": cited here, but not proven yet.", + ), + ] + | Incomplete(n) when n > 0 => [ + Attr.title( + "Not proven: " + ++ (n == 1 ? "a condition is" : "conditions are") + ++ " still open. Click to find the first; its circle opens it.", + ), + Attr.on_click(to_first_gap), + ] + | Proven + | Refuted + | Incomplete(_) => [] + } + ), + [Node.text(Obligations.Status.label(status))], ); - let stepper = - StepperView.View.view( - ~globals, - ~signal= - fun - | MakeActive(f) => take_focus((idx, f)) - | HideStepper => Ui_effect.Ignore, - ~inject=a => inject(Update.TheoremUpdate(idx, a)), - ~selected= - switch (selected) { - | Some((idx', s)) when idx == idx' => Some(s) - | _ => None - }, - ~is_toplevel=false, - stepper_view, - ); - div_c("theorem", [header, ...stepper]); - }, - xs, - ) + }, + ], + ); + let stepper = + StepperView.View.view( + ~globals, + ~signal= + fun + | MakeActive(f) => take_focus((id, f)) + | HideStepper => Ui_effect.Ignore + | ReturnToEditor => return_to_editor, + ~inject=a => inject(Update.TheoremUpdate(id, a)), + ~selected= + switch (selected) { + | Some((id', f)) when id == id' => Some(f) + | _ => None + }, + ~is_toplevel=false, + ~edit_syntax, + ~backing=main_editor, + ~info_map=model.info_map, + ~proof_map, + ~exits= + Obligations.Exits.for_step( + ~ctx={ + proof, + proof_map, + info_map: model.info_map, + }, + ), + proof, + stepper, + ); + Node.div( + ~attrs=[ + Attr.id(dom_id), + Attr.classes(["theorem"] @ (stale == None ? [] : ["stale"])), + ], + [header] @ stepper, + ); }; + List.map( + ~f= + ((id, thm: Model.theorem)) => + Drawn.view( + id, + { + theorem: thm, + proof_map: model.proof_map, + info_map: model.info_map, + selected: + switch (selected) { + | Some((id', f)) when id == id' => Some(f) + | _ => None + }, + main_editor: main_editor.model, + settings: globals.settings, + font_metrics: globals.font_metrics, + meta_down: globals.meta_down, + color_highlights: globals.color_highlights, + }, + () => + theorem((id, thm)) + ), + Model.theorems(model), + ); }; }; diff --git a/src/web/app/editors/stepper/AlgebriteStep.re b/src/web/app/editors/stepper/AlgebriteStep.re deleted file mode 100644 index 8cca1d605c..0000000000 --- a/src/web/app/editors/stepper/AlgebriteStep.re +++ /dev/null @@ -1,143 +0,0 @@ -open Util; -open Language; -open StepInterface; -open OptUtil.Syntax; -open Calc.Syntax; - -/* Types are defined outside the functor to make it - easier to use them in other files. */ - -[@deriving (show({with_path: false}), sexp, yojson)] -type model'('stepper) = { - at_idx: int, - at_exp: Exp.t, - with_exp: Exp.t, - next_exp: Calc.saved(Exp.t), -}; - -[@deriving (show({with_path: false}), sexp, yojson)] -type persistent'('stepper) = { - at_idx: int, - at_exp: Exp.t, - with_exp: Exp.t, -}; - -[@deriving (show({with_path: false}), sexp, yojson)] -type action'('step) = - |; - -[@deriving (show({with_path: false}), sexp, yojson)] -type focus'('step) = - |; - -/* The methods in this file, like the other step files, are - parameterized by a Stepper module that implements the - stepper interface. This allows us to use steppers inside - steps inside steppers. The lines below can be copied as - boilerplate to other steps.*/ -module F = - (Stepper: STEPPER) - - : ( - STEP with - type model = model'(Stepper.model) and - type persistent = persistent'(Stepper.persistent) and - type action = action'(Stepper.action) and - type focus = focus'(Stepper.focus) - ) => { - [@deriving (show({with_path: false}), sexp, yojson)] - type model = model'(Stepper.model); - [@deriving (show({with_path: false}), sexp, yojson)] - type persistent = persistent'(Stepper.persistent); - [@deriving (show({with_path: false}), sexp, yojson)] - type action = action'(Stepper.action); - [@deriving (show({with_path: false}), sexp, yojson)] - type focus = focus'(Stepper.focus); - - let persist = (model: model): persistent => { - { - at_idx: model.at_idx, - at_exp: model.at_exp, - with_exp: model.with_exp, - }; - }; - - let unpersist = (p: persistent): model => { - { - at_idx: p.at_idx, - at_exp: p.at_exp, - with_exp: p.with_exp, - next_exp: Calc.Pending, - }; - }; - - let update = (~settings as _: Settings.t, action: action, _model: model) => - switch (action) { - | _ => . - }; - - let calculate = - ( - ~settings as _: Calc.t(CoreSettings.t), - ~hidden: Calc.saved(bool), - ~exp: Calc.t(Exp.t), - ~ctx as _: Calc.t(SemanticCtx.t), - ~editor as _: Calc.t(CodeSelectable.Model.t), - ~info_map as _, - ~ana as _, - model: model, - ) => { - let {at_idx, at_exp, with_exp, next_exp} = model; - let+ next_exp = - next_exp - |> Calc.map_saved(Option.some) - |> { - let.calc exp = exp; - let* e = ProofHacks.nth_exp(at_exp, at_idx, exp); - Some(ProofHacks.replace_exp_id(e |> DHExp.rep_id, exp, with_exp)); - } - |> Calc.to_option; - ( - { - at_idx, - at_exp, - with_exp, - next_exp: next_exp |> Calc.save, - }, - hidden |> Calc.set(false), - Some(next_exp), - Calc.OldValue(Some(true)), - ); - }; - - let get_cursor_info = (~inject as _, ~focus: focus, _model: model) => - switch (focus) { - | _ => . - }; - - let view_justification = - ( - ~globals as _: Globals.t, - ~focus as _: option(focus), - ~inject as _: action => Ui_effect.t(unit), - ~take_focus as _: focus => Ui_effect.t(unit), - ~hide_stepper as _: Ui_effect.t(unit), - ~undo as _: option(Ui_effect.t(unit)), - ~is_toplevel as _: bool, - _m: model, - ) => - WebUtil.Node.text("algebra"); - - let view_content = - ( - ~globals as _: Globals.t, - ~focus as _: option(focus), - ~inject as _: action => Ui_effect.t(unit), - ~take_focus as _: focus => Ui_effect.t(unit), - ~hide_stepper as _: Ui_effect.t(unit), - ~undo as _: option(Ui_effect.t(unit)), - ~is_toplevel as _: bool, - _model: model, - ) => - []; -}; diff --git a/src/web/app/editors/stepper/AssumptionBox.re b/src/web/app/editors/stepper/AssumptionBox.re deleted file mode 100644 index 737a870c17..0000000000 --- a/src/web/app/editors/stepper/AssumptionBox.re +++ /dev/null @@ -1,80 +0,0 @@ -open Util; -open Language; -open WebUtil; - -type proof_event = - | EqualityLeft(string) - | EqualityRight(string); - -module Model = { - [@deriving (show({with_path: false}), sexp, yojson)] - type t = {ctx_entry: ProofCtx.entry}; -}; - -module View = { - let view = - ( - ~globals: Globals.t, - ~info_map, - ~env: Environment.t(Exp.t), - ~active_selection: - option((Exp.t, list(Var.t), proof_event => Ui_effect.t(unit))), - model: Model.t, - ) => { - let equality_buttons = - switch (model.ctx_entry.rule.conclusion) { - | Equality(_) => - let (l, r) = - switch (active_selection) { - | _ when model.ctx_entry.is_captured => (None, None) // TODO[Matt]: tooltip explaining why disabled - | Some((exp, _vars, signal)) => - let exp = exp |> DHExp.strip_ascriptions; - let (l, r) = - ProofRule.can_eq(~info_map, ~env, model.ctx_entry.rule, exp); - ( - Option.map( - ~f=_ => signal(EqualityLeft(model.ctx_entry.name)), - l, - ), - Option.map( - ~f=_ => signal(EqualityRight(model.ctx_entry.name)), - r, - ), - ); - | None => (None, None) - }; - [ - Widgets.button_d( - // TODO[Matt]: tooltip - Node.text("<=="), - l |> Option.value(~default=Ui_effect.Ignore), - ~disabled=model.ctx_entry.is_captured || Option.is_none(l), - ), - Widgets.button_d( - // TODO[Matt]: tooltip - Node.text("==>"), - r |> Option.value(~default=Ui_effect.Ignore), - ~disabled=model.ctx_entry.is_captured || Option.is_none(r), - ), - ]; - | _ => [] - }; - div_c( - "assumption-box", - equality_buttons - @ [ - Node.text(model.ctx_entry.name ++ ": "), - CodeViewable.view_any( - ~globals, - ~settings= - Haz3lcore.ExpToSegment.Settings.of_core( - ~inline=true, - ~fold_fn_bodies=`Text, - globals.settings.core, - ), - Exp(model.ctx_entry.exp), - ), - ], - ); - }; -}; diff --git a/src/web/app/editors/stepper/AxiomStep.re b/src/web/app/editors/stepper/AxiomStep.re deleted file mode 100644 index 4955264099..0000000000 --- a/src/web/app/editors/stepper/AxiomStep.re +++ /dev/null @@ -1,174 +0,0 @@ -open Util; -open Language; -open StepInterface; -open OptUtil.Syntax; -open Calc.Syntax; - -/* Types are defined outside the functor to make it - easier to use them in other files. */ - -[@deriving (show({with_path: false}), sexp, yojson)] -type model'('stepper) = { - name: string, - at_idx: int, - at_exp: Exp.t, - direction: Direction.t, - equality: string, - next_exp: Calc.saved(Exp.t), -}; - -[@deriving (show({with_path: false}), sexp, yojson)] -type persistent'('stepper) = { - name: string, - at_idx: int, - at_exp: Exp.t, - direction: Direction.t, - equality: string, -}; - -[@deriving (show({with_path: false}), sexp, yojson)] -type action'('step) = - |; - -[@deriving (show({with_path: false}), sexp, yojson)] -type focus'('step) = - |; - -/* The methods in this file, like the other step files, are - parameterized by a Stepper module that implements the - stepper interface. This allows us to use steppers inside - steps inside steppers. The lines below can be copied as - boilerplate to other steps.*/ -module F = - (Stepper: STEPPER) - - : ( - STEP with - type model = model'(Stepper.model) and - type persistent = persistent'(Stepper.persistent) and - type action = action'(Stepper.action) and - type focus = focus'(Stepper.focus) - ) => { - [@deriving (show({with_path: false}), sexp, yojson)] - type model = model'(Stepper.model); - [@deriving (show({with_path: false}), sexp, yojson)] - type persistent = persistent'(Stepper.persistent); - [@deriving (show({with_path: false}), sexp, yojson)] - type action = action'(Stepper.action); - [@deriving (show({with_path: false}), sexp, yojson)] - type focus = focus'(Stepper.focus); - - let persist = (model: model): persistent => { - { - name: model.name, - at_idx: model.at_idx, - at_exp: model.at_exp, - direction: model.direction, - equality: model.equality, - }; - }; - - let unpersist = (p: persistent): model => { - { - name: p.name, - at_idx: p.at_idx, - at_exp: p.at_exp, - direction: p.direction, - equality: p.equality, - next_exp: Calc.Pending, - }; - }; - - let update = (~settings as _: Settings.t, action: action, _model: model) => - switch (action) { - | _ => . - }; - - let calculate = - ( - ~settings as _: Calc.t(CoreSettings.t), - ~hidden: Calc.saved(bool), - ~exp: Calc.t(Exp.t), - ~ctx: Calc.t(SemanticCtx.t), - ~editor as _: Calc.t(CodeSelectable.Model.t), - ~info_map, - ~ana as _, - model: model, - ) => { - let {name, at_idx, at_exp, direction, equality, next_exp} = model; - let+ next_exp = - next_exp - |> Calc.map_saved(Option.some) - |> { - let.calc exp = exp - and.calc ctx = ctx - and.calc info_map = info_map; - let* e = ProofHacks.nth_exp(at_exp, at_idx, exp); - let proof_ctx = - ProofCtx.of_env( - ~builtins=Axioms.v, - ~ctx=SemanticCtx.get_ctx(ctx), - SemanticCtx.get_env(ctx), - ); - let* proofrule = ProofCtx.lookup_rule(equality, proof_ctx); - let (l, r) = - ProofRule.can_eq( - ~info_map, - ~env=SemanticCtx.get_env(ctx), - proofrule, - e, - ); - let* with_exp = - switch (direction) { - | Left => l - | Right => r - }; - Some(ProofHacks.replace_exp_id(e |> DHExp.rep_id, exp, with_exp)); - } - |> Calc.to_option; - ( - { - name, - at_idx, - at_exp, - direction, - equality, - next_exp: next_exp |> Calc.save, - }, - hidden |> Calc.set(false), - Some(next_exp), - Calc.OldValue(Some(true)), - ); - }; - - let get_cursor_info = (~inject as _, ~focus: focus, _model: model) => - switch (focus) { - | _ => . - }; - - let view_justification = - ( - ~globals as _: Globals.t, - ~focus as _: option(focus), - ~inject as _: action => Ui_effect.t(unit), - ~take_focus as _: focus => Ui_effect.t(unit), - ~hide_stepper as _: Ui_effect.t(unit), - ~undo as _: option(Ui_effect.t(unit)), - ~is_toplevel as _: bool, - m: model, - ) => - WebUtil.Node.text(m.name); - - let view_content = - ( - ~globals as _: Globals.t, - ~focus as _: option(focus), - ~inject as _: action => Ui_effect.t(unit), - ~take_focus as _: focus => Ui_effect.t(unit), - ~hide_stepper as _: Ui_effect.t(unit), - ~undo as _: option(Ui_effect.t(unit)), - ~is_toplevel as _: bool, - _model: model, - ) => - []; -}; diff --git a/src/web/app/editors/stepper/AxiomsBox.re b/src/web/app/editors/stepper/AxiomsBox.re deleted file mode 100644 index 0c15a41ef3..0000000000 --- a/src/web/app/editors/stepper/AxiomsBox.re +++ /dev/null @@ -1,181 +0,0 @@ -open Util; -open WebUtil; -open Calc.Syntax; -open Language; - -module Model = { - [@deriving (show({with_path: false}), sexp, yojson)] - type t = { - filter: Calc.t(string), - all_rules: Calc.saved(ProofCtx.t), - filtered_rewrites: Calc.saved(list(AssumptionBox.Model.t)), - }; - - let init = { - filter: Calc.NewValue(""), - all_rules: Calc.Pending, - filtered_rewrites: Calc.Pending, - }; -}; - -module Update = { - [@deriving (show({with_path: false}), sexp, yojson)] - type t = - | SetFilter(string); - - let update = (~settings as _, action, model): Updated.t(Model.t) => { - switch (action) { - | SetFilter(filter) => - Model.{ - ...model, - filter: Calc.NewValue(filter), - } - |> Updated.return_quiet - }; - }; - - let calculate = - ( - ~info_map: Calc.t(Statics.Map.t), - ~ctx: Calc.t(SemanticCtx.t), - ~selected_exp: Calc.t(option(Exp.t)), - model: Model.t, - ) - : Model.t => { - let all_rules = - model.all_rules - |> { - let.calc ctx = ctx; - let env = SemanticCtx.get_env(ctx); - let ctx = SemanticCtx.get_ctx(ctx); - ProofCtx.of_env(~builtins=Axioms.v, ~ctx, env); - }; - - let filtered_rewrites = - model.filtered_rewrites - |> { - let.calc all_rules = all_rules - and.calc ctx = ctx - and.calc filter = model.filter - and.calc selected_exp = selected_exp - and.calc info_map = info_map; - - let all_assumption_boxes = - all_rules - |> ( - String.equal(filter, "") - ? x => x - : List.filter(~f=({name, _}: ProofCtx.entry) => - StringUtil.subseq_search(name, filter) - ) - ) - |> List.map(~f=ctx_entry => - AssumptionBox.Model.{ctx_entry: ctx_entry} - ) - |> ( - String.equal(filter, "") - ? List.filter(~f=(ab: AssumptionBox.Model.t) => - switch (selected_exp) { - | Some(selected_exp) => - ProofRule.is_active( - ~info_map, - ~env=SemanticCtx.get_env(ctx), - ab.ctx_entry.rule, - selected_exp |> DHExp.strip_ascriptions, - ) - | None => false - } - ) - : (x => x) - ); - - all_assumption_boxes; - }; - { - filter: model.filter |> Calc.make_old, - all_rules: all_rules |> Calc.save, - filtered_rewrites: filtered_rewrites |> Calc.save, - }; - }; -}; - -module Selection = { - open Cursor; - - [@deriving (show({with_path: false}), sexp, yojson)] - type t = unit; - - let get_cursor_info = - (~selection as (): t, _model: Model.t): cursor(Update.t) => { - empty; - }; -}; - -module View = { - let view = - ( - ~globals, - ~info_map, - ~env, - ~full_exp, - ~selected_exp, - ~inject: Update.t => Ui_effect.t(unit), - ~take_focus: Selection.t => Ui_effect.t(unit), - ~add_axiom_step: - (string, int, Exp.t, Direction.t, string) => Ui_effect.t(unit), - model: Model.t, - ) => { - let unpacked_rewrites = - model.filtered_rewrites - |> Calc.get_saved_exc(~print="view_step_rewrites"); - [ - Node.input( - ~attrs=[ - Attr.value(model.filter |> Calc.get_value), - Attr.placeholder("search assumptions..."), - Attr.on_focus(_ => take_focus()), - Attr.on_input((_, s) => inject(SetFilter(s))), - ], - (), - ), - ] - @ List.map( - ~f= - (am: AssumptionBox.Model.t) => - AssumptionBox.View.view( - ~globals, - ~info_map, - ~env, - ~active_selection= - Some(( - selected_exp, - [], - fun - | AssumptionBox.EqualityLeft(e) => { - add_axiom_step( - am.ctx_entry.name, - try(ProofHacks.exp_idx(selected_exp, full_exp)) { - | _ => 0 - }, - selected_exp, - Left, - e, - ); - } - | AssumptionBox.EqualityRight(e) => - add_axiom_step( - am.ctx_entry.name, - try(ProofHacks.exp_idx(selected_exp, full_exp)) { - | _ => 0 - }, - selected_exp, - Right, - e, - ), - )), - am, - ), - unpacked_rewrites, - ); - }; -}; diff --git a/src/web/app/editors/stepper/ForallStep.re b/src/web/app/editors/stepper/ForallStep.re deleted file mode 100644 index bfd7f8384a..0000000000 --- a/src/web/app/editors/stepper/ForallStep.re +++ /dev/null @@ -1,209 +0,0 @@ -open Util; -open Language; -open StepInterface; -open OptUtil.Syntax; -open Calc.Syntax; - -/* Types are defined outside the functor to make it - easier to use them in other files. */ - -[@deriving (show({with_path: false}), sexp, yojson)] -type model'('stepper) = { - inner_exp: Calc.saved(Exp.t), - inner_ctx: Calc.saved(SemanticCtx.t), - inner_stepper: 'stepper, - result_function: Calc.saved(Exp.t), -}; - -[@deriving (show({with_path: false}), sexp, yojson)] -type persistent'('stepper) = {inner_stepper: 'stepper}; - -[@deriving (show({with_path: false}), sexp, yojson)] -type action'('step) = - | InnerExp('step); - -[@deriving (show({with_path: false}), sexp, yojson)] -type focus'('step) = - | InnerExp('step); - -let init = init_step => { - inner_exp: Calc.Pending, - inner_ctx: Calc.Pending, - inner_stepper: init_step, - result_function: Calc.Pending, -}; - -/* The methods in this file, like the other step files, are - parameterized by a Stepper module that implements the - stepper interface. This allows us to use steppers inside - steps inside steppers. The lines below can be copied as - boilerplate to other steps.*/ -module F = - (Stepper: STEPPER) - - : ( - STEP with - type model = model'(Stepper.model) and - type persistent = persistent'(Stepper.persistent) and - type action = action'(Stepper.action) and - type focus = focus'(Stepper.focus) - ) => { - [@deriving (show({with_path: false}), sexp, yojson)] - type model = model'(Stepper.model); - [@deriving (show({with_path: false}), sexp, yojson)] - type persistent = persistent'(Stepper.persistent); - [@deriving (show({with_path: false}), sexp, yojson)] - type action = action'(Stepper.action); - [@deriving (show({with_path: false}), sexp, yojson)] - type focus = focus'(Stepper.focus); - - let persist = (model: model) => { - {inner_stepper: Stepper.persist(model.inner_stepper)}; - }; - - let unpersist = (p: persistent) => { - { - inner_exp: Calc.Pending, - inner_ctx: Calc.Pending, - inner_stepper: Stepper.unpersist(p.inner_stepper), - result_function: Calc.Pending, - }; - }; - - let update = (~settings: Settings.t, action: action, model: model) => { - Updated.( - switch (action) { - | InnerExp(a) => - let* new_inner_step = - Stepper.update(~settings, a, model.inner_stepper); - { - ...model, - inner_stepper: new_inner_step, - }; - } - ); - }; - - let calculate = - ( - ~settings: Calc.t(CoreSettings.t), - ~hidden: Calc.saved(bool), - ~exp: Calc.t(Exp.t), - ~ctx: Calc.t(SemanticCtx.t), - ~editor as _: Calc.t(CodeSelectable.Model.t), - ~info_map as _, - ~ana: Calc.t(Typ.t), - model: model, - ) => { - let {inner_exp, inner_ctx, inner_stepper, result_function} = model; - let+ (inner_ctx, inner_exp) = - (inner_ctx, inner_exp) - |> Calc.saved_pair - |> Calc.map_saved(Option.some) - |> { - let.calc exp = exp - and.calc ctx = ctx; - switch (exp |> Exp.term_of) { - | Fun(p, d1, t, _) => - let t = OptUtil.get(() => Typ.fresh(Unknown(Internal)), t); - Some((SemanticCtx.add_from_pattern(ctx, p, t), d1)); - | _ => None - }; - } - |> Calc.to_option - |> Option.map(~f=Calc.to_pair); - let (inner_stepper, last, validity) = - Stepper.calculate( - ~settings, - ~ctx=inner_ctx, - ~exp=inner_exp, - ~ana, - inner_stepper, - ); - let result_function = - result_function - |> { - let.calc last = last - and.calc exp = exp; - switch (exp |> Exp.term_of) { - | Fun(p, _, t, n) => DHExp.fresh(Fun(p, last, t, n)) - | _ => - DHExp.fresh( - Fun( - Pat.fresh(EmptyHole), - last, - Some(Typ.fresh(Unknown(Internal))), - None, - ), - ) - }; - }; - ( - { - inner_exp: inner_exp |> Calc.save, - inner_ctx: inner_ctx |> Calc.save, - inner_stepper, - result_function: result_function |> Calc.save, - }, - hidden |> Calc.set(false), - Some(result_function), - validity, - ); - }; - - let get_cursor_info = (~inject, ~focus: focus, model: model) => - Cursor.( - switch (focus) { - | InnerExp(a) => - let+ ci = - Stepper.get_cursor_info( - ~inject=a => inject(InnerExp(a): action), - ~focus=a, - model.inner_stepper, - ); - (InnerExp(ci): action); - } - ); - - let view_justification = - ( - ~globals as _: Globals.t, - ~focus as _: option(focus), - ~inject as _: action => Ui_effect.t(unit), - ~take_focus as _: focus => Ui_effect.t(unit), - ~hide_stepper as _: Ui_effect.t(unit), - ~undo as _: option(Ui_effect.t(unit)), - ~is_toplevel as _: bool, - _: model, - ) => - WebUtil.Node.text("Forall Step"); - - let view_content = - ( - ~globals: Globals.t, - ~focus: option(focus), - ~inject: action => Ui_effect.t(unit), - ~take_focus: focus => Ui_effect.t(unit), - ~hide_stepper: Ui_effect.t(unit), - ~undo as _: option(Ui_effect.t(unit)), - ~is_toplevel: bool, - model: model, - ) => { - let inner_stepper = - Stepper.view( - ~globals, - ~focus= - switch (focus) { - | Some(InnerExp(f)) => Some(f) - | None => None - }, - ~inject=x => inject(InnerExp(x)), - ~take_focus=x => take_focus(InnerExp(x)), - ~hide_stepper, - ~is_toplevel, - model.inner_stepper, - ); - - inner_stepper; - }; -}; diff --git a/src/web/app/editors/stepper/InductionCase.re b/src/web/app/editors/stepper/InductionCase.re deleted file mode 100644 index c404b66a63..0000000000 --- a/src/web/app/editors/stepper/InductionCase.re +++ /dev/null @@ -1,393 +0,0 @@ -open Util; -open Language; -open Haz3lcore; -open StepInterface; - -[@deriving (show({with_path: false}), sexp, yojson)] -type model'('stepper) = { - // Updated - pattern: CodeEditable.Model.t, - // Calculated - elab_pattern: Calc.saved(Pat.t), - inner_exp: Calc.saved(Exp.t), - step: 'stepper, - last_exp: Calc.saved(Exp.t), - inner_ctx: Calc.saved(SemanticCtx.t), - hypotheses: Calc.saved(list((Binding.t, Exp.t))), - constraint_: Calc.saved(option(Coverage.Constraint.t)), -}; - -[@deriving (show({with_path: false}), sexp, yojson)] -type persistent'('stepper) = { - pattern: CodeEditable.Model.persistent, - stepper: 'stepper, -}; - -[@deriving (show({with_path: false}), sexp, yojson)] -type action'('stepper) = - | PatternUpdate(CodeEditable.Update.t) - | StepUpdate('stepper); - -[@deriving (show({with_path: false}), sexp, yojson)] -type focus'('stepper) = - | Pattern(CodeSelectable.Selection.t) - | Stepper('stepper); - -module F = (Stepper: STEPPER) => { - type model = model'(Stepper.model); - type persistent = persistent'(Stepper.persistent); - type action = action'(Stepper.action); - type focus = focus'(Stepper.focus); - - let init = { - pattern: - CodeEditable.Model.mk(Editor.Model.mk(Zipper.init(), ~root=Exp)), - elab_pattern: Calc.Pending, - inner_exp: Calc.Pending, - step: Stepper.init, - last_exp: Calc.Pending, - inner_ctx: Calc.Pending, - hypotheses: Calc.Pending, - constraint_: Calc.Pending, - }; - - let persist = (model: model) => { - { - pattern: CodeEditable.Model.persist(model.pattern), - stepper: Stepper.persist(model.step), - }; - }; - - let unpersist = (p: persistent) => { - { - pattern: CodeEditable.Model.unpersist(p.pattern), - elab_pattern: Calc.Pending, - inner_exp: Calc.Pending, - step: Stepper.unpersist(p.stepper), - last_exp: Calc.Pending, - inner_ctx: Calc.Pending, - hypotheses: Calc.Pending, - constraint_: Calc.Pending, - }; - }; - - let update = (~settings: Settings.t, action: action, model: model) => { - Updated.( - switch (action) { - | PatternUpdate(a) => - let* new_pattern = - CodeEditable.Update.update(~settings, a, model.pattern); - { - ...model, - pattern: new_pattern, - }; - | StepUpdate(a) => - let* new_step = Stepper.update(~settings, a, model.step); - { - ...model, - step: new_step, - }; - } - ); - }; - - let calculate = - ( - ~settings: Calc.t(CoreSettings.t), - ~elab_scrut: Calc.t(Exp.t), - ~scrut_co_ctx: Calc.t(CoCtx.t), - ~scrut_ty: Calc.t(Typ.t), - ~exp: Calc.t(Exp.t), - ~ctx: Calc.t(SemanticCtx.t), - ~info_map: Calc.t(Statics.Map.t), - ~ana: Calc.t(Typ.t), - model: model, - ) => { - let pattern = - CodeEditable.Update.calculate( - ~settings=Calc.get_value(settings), - ~dynamics=Dynamics.Map.empty, - ~is_edited=true, // This editor technically edits Exps, but we want a Pat, so we put it in a function to emulate that. - ~stitch= - x => - x - |> ProofHacks.exp_to_pat - |> ProofHacks.add_wrapping_function( - ~typ=scrut_ty |> Calc.get_value, - ), - ~is_dynamic_term=true, - model.pattern, - ); - - let elab_pattern = - Calc.set( - ~eq=Pat.fast_equal, - CodeEditable.Model.get_statics(pattern).elaborated - |> ProofHacks.remove_wrapping_function, - model.elab_pattern, - ); - - let (inner_ctx, inner_exp, hypotheses) = - (model.inner_ctx, model.inner_exp, model.hypotheses) - |> Calc.saved_3 - |> { - open Calc.Syntax; - let.calc elab_pattern = elab_pattern - and.calc elab_scrut = elab_scrut - and.calc scrut_co_ctx = scrut_co_ctx - and.calc scrut_ty = scrut_ty - and.calc sem_ctx = ctx - and.calc info_map = info_map - and.calc exp = exp; - - // 1. Find what variables the pattern adds to the scope, and - // add them to the env and ctx. - let added_variables = - elab_pattern |> Pat.bindings |> Binding.variable_names; - let sem_ctx = - SemanticCtx.add_from_pattern(sem_ctx, elab_pattern, scrut_ty); - - // 2. Work out what the inner exp would be - // Note: this is an option in case some capture nonsense happens. - let inner_exp = - ProofHacks.replace_exp( - info_map, - elab_scrut, - scrut_co_ctx, - elab_pattern |> ProofHacks.pat_to_exp, - elab_pattern |> Pat.bindings |> CoCtx.of_bindings, - added_variables, - exp, - ); - - // 3. Create the case_equality assertion, and add to env and ctx if appropriate - // Note: if the LHS of case_eq is in any way captured by the added variables, then we cannot use it. - let is_case_eq_captured = - CoCtx.has_any(scrut_co_ctx, added_variables); - let case_eq = - is_case_eq_captured - ? None - : Some( - BinOp( - Poly(Equals), - elab_scrut, - elab_pattern |> ProofHacks.pat_to_exp, - ) - |> Exp.fresh - |> Substitution.in_exp(SemanticCtx.get_env(sem_ctx)), - ); - let (sem_ctx, case_eq_name) = - switch (case_eq) { - | Some(case_eq) => - SemanticCtx.add_hypothesis(sem_ctx, "case_eq", case_eq) - |> PairUtil.map_snd(Option.some) - | None => (sem_ctx, None) - }; - - // 4. Find the inductive hypotheses, and add to env and ctx - // Note: we do not add any IHs that are captured by the added variables. (This should happen iff the inner exp is captured) - let inductive_hypotheses = - ProofHacks.get_inductive_hypotheses( - CodeEditable.Model.get_statics(pattern).info_map, - scrut_ty, - elab_pattern, - ) - |> List.filter_map(~f=h => - ProofHacks.replace_exp( - info_map, - elab_scrut, - scrut_co_ctx, - h |> ProofHacks.pat_to_exp, - h |> Pat.bindings |> CoCtx.of_bindings, - added_variables, - exp, - ) - ); - let (sem_ctx, ihs) = - List.fold_left( - ~f= - ((acc, ihs), h) => - SemanticCtx.add_hypothesis(acc, "ih", h) - |> PairUtil.map_snd(x => [(x, h), ...ihs]), - ~init=(sem_ctx, []), - inductive_hypotheses, - ); - - let inner_exp = - inner_exp |> Option.value(~default=Exp.fresh(EmptyHole)); - - let case_eq_h = - switch (case_eq, case_eq_name) { - | (Some(e), Some(n)) => [(n, e)] - | _ => [] - }; - let hypotheses = case_eq_h @ ihs; - - (sem_ctx, inner_exp, hypotheses); - } - |> Calc.to_3; - - let (stepper, last_exp, validity) = - Stepper.calculate( - ~settings, // TODO: this is a little ugly - ~ctx=inner_ctx, - ~exp=inner_exp, - ~ana, - model.step, - ); - - let constraint_ = - { - open OptUtil.Syntax; - let statics = CodeWithStatics.Model.get_statics(pattern); - let* info_pat = - Statics.Map.lookup_pat( - elab_pattern |> Calc.get_value |> Pat.rep_id, - statics.info_map, - ); - Some(Info.pat_constraint(info_pat)); - } - |> Calc.set(_, model.constraint_); - - ( - { - pattern, - elab_pattern: elab_pattern |> Calc.save, - inner_exp: inner_exp |> Calc.save, - step: stepper, - last_exp: last_exp |> Calc.save, - inner_ctx: inner_ctx |> Calc.save, - hypotheses: hypotheses |> Calc.save, - constraint_: constraint_ |> Calc.save, - }, - constraint_, - validity, - ); - }; - - let get_cursor_info = (~inject, ~focus: focus, model: model) => { - Cursor.( - switch (focus) { - | Pattern(a) => - let+ ci = - CodeEditable.Selection.get_cursor_info( - ~inject=a => inject(PatternUpdate(a)), - ~selection=a, - model.pattern, - ); - PatternUpdate(ci); - | Stepper(a) => - let+ ci = - Stepper.get_cursor_info( - ~inject=a => inject(StepUpdate(a)), - ~focus=a, - model.step, - ); - StepUpdate(ci); - } - ); - }; - - let view = - ( - ~globals: Globals.t, - ~focus: option(focus), - ~inject: action => Ui_effect.t(unit), - ~take_focus: focus => Ui_effect.t(unit), - ~hide_stepper: Ui_effect.t(unit), - ~remove_case: Ui_effect.t(unit), - model: model, - ) => { - let remove_case_button = - Widgets.button( - Icons.trash, - _ => remove_case, - ~tooltip="Remove case", - ~clss=["subtle-button"], - ); - let pattern_editor = - CodeEditable.View.view( - ~globals, - ~signal= - fun - | MakeActive => take_focus(Pattern()), - ~edit_mode= - EditMode.Editable({ - inject: x => inject(PatternUpdate(x)), - escape: _ => Ui_effect.Ignore, - take_focus: _ => Ui_effect.Ignore, - focus: - switch (focus) { - | Some(Pattern ()) => Some() - | _ => None - }, - }), - ~dynamics=Dynamics.Map.empty, - model.pattern, - ); - let pattern_editor = - WebUtil.div_c("inline-editor-wrapper", [pattern_editor]); - module StepperTargetBox = StepperTargetBox.F(Stepper); - let stepper_view = - StepperTargetBox.target_box( - ~globals, - ~take_focus=s => take_focus(Stepper(s)), - ~hide_stepper, - ~inject=x => inject(StepUpdate(x)), - ~focus= - switch (focus) { - | Some(Stepper(f)) => Some(f) - | _ => None - }, - ~is_toplevel=false, - model.step, - Exp.fresh(Atom(Bool(true))), - model.last_exp |> Calc.get_saved_exc(~print="last_exp not calculated"), - ); - WebUtil.div_c( - "induction-case", - [ - WebUtil.div_c( - "induction-case-header", - [ - remove_case_button, - WebUtil.Node.text("Case "), - pattern_editor, - WebUtil.Node.text(" : "), - ], - ), - WebUtil.div_c( - "induction-case-hypotheses", - List.filter_map( - ~f= - fun - | (Binding.{name: _, id: _}, exp) => { - let rule = ProofRule.exp_to_rule(exp); - let conclusion = ProofRule.conclusion_exp(rule); - let code = - CodeViewable.view_any( - ~globals, - ~settings= - Haz3lcore.ExpToSegment.Settings.of_core( - ~inline=true, - ~fold_fn_bodies=`Text, - globals.settings.core, - ), - Exp(conclusion), - ); - Some( - WebUtil.div_c( - "induction-case-hypothesis", - [WebUtil.Node.text("assume "), code], - ), - ); - }, - model.hypotheses - |> Calc.get_saved_exc(~print="hypotheses not calculated"), - ), - ), - ] - @ stepper_view, - ); - }; -}; diff --git a/src/web/app/editors/stepper/InductionStep.re b/src/web/app/editors/stepper/InductionStep.re deleted file mode 100644 index 3c43d86d47..0000000000 --- a/src/web/app/editors/stepper/InductionStep.re +++ /dev/null @@ -1,445 +0,0 @@ -open Util; -open Language; -open Haz3lcore; -open StepInterface; -open Calc.Syntax; - -/* Types are defined outside the functor to make it - easier to use them in other files. */ - -[@deriving (show({with_path: false}), sexp, yojson)] -type model'('stepper) = { - // Updated - scrut: CodeEditable.Model.t, - cases: list(InductionCase.model'('stepper)), - // Calculated - elab_scrut_raw: Calc.saved(Exp.t), - elab_scrut_sub: Calc.saved(Exp.t), - scrut_ty: Calc.saved(Typ.t), - scrut_co_ctx: Calc.saved(CoCtx.t), - result: Calc.saved(Exp.t), - join_exp: Calc.saved(Exp.t), - is_exhaustive: Calc.saved(bool), - validity: Calc.saved(option(bool)), -}; - -[@deriving (show({with_path: false}), sexp, yojson)] -type persistent'('stepper) = { - scrut: CodeEditable.Model.persistent, - cases: list(InductionCase.persistent'('stepper)), -}; - -[@deriving (show({with_path: false}), sexp, yojson)] -type action'('step) = - | ScrutUpdate(CodeEditable.Update.t) - | CaseUpdate(int, InductionCase.action'('step)) - | AddCase - | RemoveCase(int); - -[@deriving (show({with_path: false}), sexp, yojson)] -type focus'('step) = - | Scrut(CodeEditable.Selection.t) - | Case(int, InductionCase.focus'('step)); - -let init = (~exp: option(Exp.t)=?, ()) => { - let scrut = - switch (exp) { - | Some(e) => - CodeEditable.Model.mk( - Editor.Model.mk( - Zipper.unzip( - ExpToSegment.exp_to_segment( - ~settings=ExpToSegment.Settings.editable(~inline=true), - e, - ), - ), - ~root=Exp, - ), - ) - | None => - CodeEditable.Model.mk(Editor.Model.mk(Zipper.init(), ~root=Exp)) - }; - { - scrut, - cases: [], - elab_scrut_raw: Calc.Pending, - elab_scrut_sub: Calc.Pending, - scrut_ty: Calc.Pending, - scrut_co_ctx: Calc.Pending, - result: Calc.Pending, - join_exp: Calc.Pending, - is_exhaustive: Calc.Pending, - validity: Calc.Pending, - }; -}; - -/* The methods in this file, like the other step files, are - parameterized by a Stepper module that implements the - stepper interface. This allows us to use steppers inside - steps inside steppers. The lines below can be copied as - boilerplate to other steps.*/ -module F = - (Stepper: STEPPER) - - : ( - STEP with - type model = model'(Stepper.model) and - type persistent = persistent'(Stepper.persistent) and - type action = action'(Stepper.action) and - type focus = focus'(Stepper.focus) - ) => { - module InductionCase = InductionCase.F(Stepper); - - [@deriving (show({with_path: false}), sexp, yojson)] - type model = model'(Stepper.model); - [@deriving (show({with_path: false}), sexp, yojson)] - type persistent = persistent'(Stepper.persistent); - [@deriving (show({with_path: false}), sexp, yojson)] - type action = action'(Stepper.action); - [@deriving (show({with_path: false}), sexp, yojson)] - type focus = focus'(Stepper.focus); - - let persist = (model: model) => { - { - scrut: CodeEditable.Model.persist(model.scrut), - cases: List.map(~f=InductionCase.persist, model.cases), - }; - }; - - let unpersist = (p: persistent) => { - { - scrut: CodeEditable.Model.unpersist(p.scrut), - cases: List.map(~f=InductionCase.unpersist, p.cases), - elab_scrut_raw: Calc.Pending, - elab_scrut_sub: Calc.Pending, - scrut_ty: Calc.Pending, - scrut_co_ctx: Calc.Pending, - result: Calc.Pending, - join_exp: Calc.Pending, - is_exhaustive: Calc.Pending, - validity: Calc.Pending, - }; - }; - - let update = (~settings: Settings.t, action: action, model: model) => { - Updated.( - switch (action) { - | ScrutUpdate(a) => - let* new_scrut = - CodeEditable.Update.update(~settings, a, model.scrut); - { - ...model, - scrut: new_scrut, - }; - | CaseUpdate(i, a) => - switch (List.nth(model.cases, i)) { - | Some(case) => - let* new_case = InductionCase.update(~settings, a, case); - { - ...model, - cases: ListUtil.put_nth(i, new_case, model.cases), - }; - | None => model |> raise_invalid_action - } - | AddCase => - let new_case = InductionCase.init; - { - ...model, - cases: model.cases @ [new_case], - } - |> return; - | RemoveCase(i) => - switch (ListUtil.remove_nth(i, model.cases)) { - | Some(new_cases) => - { - ...model, - cases: new_cases, - } - |> return - | None => model |> raise_invalid_action - } - } - ); - }; - - let calculate = - ( - ~settings: Calc.t(CoreSettings.t), - ~hidden: Calc.saved(bool), - ~exp: Calc.t(Exp.t), - ~ctx: Calc.t(SemanticCtx.t), - ~editor as _, - ~info_map, - ~ana: Calc.t(Typ.t), - model: model, - ) => { - let { - scrut, - cases, - elab_scrut_raw, - elab_scrut_sub, - scrut_ty, - scrut_co_ctx, - result: _, - join_exp, - is_exhaustive, - validity, - }: model = model; - let scrut = - CodeEditable.Update.calculate( - ~settings=Calc.get_value(settings), - ~ctx=Calc.get_value(ctx).ctx, - ~dynamics=Dynamics.Map.empty, - ~is_edited=true, - ~stitch=x => x, - ~is_dynamic_term=true, - scrut, - ); - let elab_scrut_raw = - Calc.set( - ~eq=Exp.fast_equal_with_lexemes, - CodeEditable.Model.get_statics(scrut).elaborated, - elab_scrut_raw, - ); - let elab_scrut_sub = - elab_scrut_sub - |> { - let.calc raw = elab_scrut_raw - and.calc sem_ctx = ctx; - let env = SemanticCtx.get_env(sem_ctx); - Substitution.in_exp(env, raw); - }; - let scrut_statics = CodeEditable.Model.get_statics(scrut); - let scrut_rep_id = Exp.rep_id(scrut_statics.elaborated); - let scrut_ty = { - let self_ty = - switch (Statics.Map.ty_of(scrut_rep_id, scrut_statics.info_map)) { - | Some(ty) => ty - | None => - raise(Failure("Missing type info for induction step scrutinee")) - }; - Calc.set(~eq=Typ.fast_equal, self_ty, scrut_ty); - }; - let scrut_co_ctx = { - let self_co_ctx = - switch (Statics.Map.lookup_exp(scrut_rep_id, scrut_statics.info_map)) { - | Some({co_ctx, _}) => co_ctx - | None => CoCtx.empty - }; - Calc.set(self_co_ctx, scrut_co_ctx); - }; - let (cases, constraints, validities) = - List.map( - ~f= - InductionCase.calculate( - ~settings, - ~scrut_ty, - ~scrut_co_ctx, - ~elab_scrut=elab_scrut_sub, - ~ctx, - ~info_map, - ~exp, - ~ana, - ), - cases, - ) - |> ListUtil.unzip3; - - let new_join_exp = - List.fold_left( - ~f= - (acc, case: InductionCase.model) => - switch (acc, case.last_exp) { - | (None, Calc.Pending) => None - | (None, Calc.Calculated(last_exp)) => Some(last_exp) - | (Some(acc), Calc.Pending) => Some(acc) - | (Some(acc), Calc.Calculated(last_exp)) - when Exp.fast_equal(acc, last_exp) => - Some(acc) - | (Some(_), Calc.Calculated(_)) => Some(Exp.fresh(EmptyHole)) - }, - ~init=None, - cases, - ); - let join_exp = - Calc.set( - ~eq=Exp.fast_equal_with_lexemes, - new_join_exp |> Option.value(~default=Exp.fresh(EmptyHole)), - join_exp, - ); - - let is_exhaustive = - is_exhaustive - |> { - let.calc constraints = Calc.combine_list(constraints) - and.calc ctx = ctx - and.calc scrut_ty = scrut_ty; - let constraints = List.filter_map(~f=Fn.id, constraints); - Poly.equal( - Coverage.check( - constraints, - Typ.normalize(SemanticCtx.get_ctx(ctx), scrut_ty), - ). - exhaustiveness, - Exhaustive, - ); - }; - - let validity = - validity - |> { - let.calc validities = Calc.combine_list(validities) - and.calc is_exhaustive = is_exhaustive; - List.fold_left( - ~f= - (v1, v2) => - switch (v1, v2) { - | (Some(true), Some(true)) => Some(true) - | (Some(false), Some(false)) => Some(false) - | (_, _) => None - }, - ~init=is_exhaustive ? Some(true) : None, - validities, - ); - }; - - let result = exp |> Calc.save; - - Some(( - { - scrut, - cases, - elab_scrut_raw: elab_scrut_raw |> Calc.save, - elab_scrut_sub: elab_scrut_sub |> Calc.save, - scrut_ty: scrut_ty |> Calc.save, - scrut_co_ctx: scrut_co_ctx |> Calc.save, - result, - join_exp: join_exp |> Calc.save, - is_exhaustive: is_exhaustive |> Calc.save, - validity: validity |> Calc.save, - }, - hidden |> Calc.set(false), - Some(Calc.OldValue(Exp.fresh(Atom(Bool(true))))), - validity, - )); - }; - - let get_cursor_info = (~inject, ~focus: focus, model: model) => - Cursor.( - switch (focus) { - | Scrut(a) => - let+ ci = - CodeEditable.Selection.get_cursor_info( - ~inject=a => inject(ScrutUpdate(a)), - ~selection=a, - model.scrut, - ); - ScrutUpdate(ci); - | Case(i, a) => - switch (List.nth(model.cases, i)) { - | Some(case) => - let+ ci = - InductionCase.get_cursor_info( - ~inject=x => inject(CaseUpdate(i, x)), - ~focus=a, - case, - ); - CaseUpdate(i, ci); - | None => Cursor.empty - } - } - ); - - let view_justification = - ( - ~globals as _: Globals.t, - ~focus as _: option(focus), - ~inject as _: action => Ui_effect.t(unit), - ~take_focus as _: focus => Ui_effect.t(unit), - ~hide_stepper as _: Ui_effect.t(unit), - ~undo as _: option(Ui_effect.t(unit)), - ~is_toplevel as _: bool, - _: model, - ) => - WebUtil.Node.text("Induction"); - - let view_content = - ( - ~globals: Globals.t, - ~focus: option(focus), - ~inject: action => Ui_effect.t(unit), - ~take_focus: focus => Ui_effect.t(unit), - ~hide_stepper: Ui_effect.t(unit), - ~undo as _: option(Ui_effect.t(unit)), - ~is_toplevel as _: bool, - model: model, - ) => { - let scrut_editor = - CodeEditable.View.view( - ~globals, - ~signal= - fun - | MakeActive => take_focus(Scrut()), - ~edit_mode= - EditMode.Editable({ - inject: x => inject(ScrutUpdate(x)), - escape: _ => Ui_effect.Ignore, - take_focus: _ => Ui_effect.Ignore, - focus: - switch (focus) { - | Some(Scrut(_)) => Some() - | Some(_) - | None => None - }, - }), - ~dynamics=Dynamics.Map.empty, - model.scrut, - ); - - let add_case_button = - Widgets.button( - WebUtil.Node.text("Case ..."), - ~tooltip="Add case", - ~clss=["subtle-button", "add-case-button"], - _ => - inject(AddCase) - ); - - let cases = - List.mapi( - ~f= - (i, case) => - InductionCase.view( - ~globals, - ~inject=x => inject(CaseUpdate(i, x)), - ~take_focus=x => take_focus(Case(i, x)), - ~remove_case=inject(RemoveCase(i)), - ~hide_stepper, - ~focus= - switch (focus) { - | Some(Case(j, s)) when i == j => Some(s) - | Some(_) - | None => None - }, - case, - ), - model.cases, - ); - - [ - WebUtil.div_c( - "induction-scrut", - [ - WebUtil.Node.text("Induction on: "), - WebUtil.div_c("inline-editor-wrapper", [scrut_editor]), - ], - ), - ] - @ cases - @ [add_case_button] - @ [ - model.is_exhaustive |> Calc.get_saved_exc(~print="exhaustive") - ? WebUtil.Node.text("exhaustive") : WebUtil.Node.text("inexhaustive"), - ]; - }; -}; diff --git a/src/web/app/editors/stepper/MissingStep.re b/src/web/app/editors/stepper/MissingStep.re deleted file mode 100644 index bd8bf1d5ce..0000000000 --- a/src/web/app/editors/stepper/MissingStep.re +++ /dev/null @@ -1,737 +0,0 @@ -open Language; -open Util; -open WebUtil; -open Calc.Syntax; -open Haz3lcore; -open Poly; - -module Model = { - [@deriving (show({with_path: false}), sexp, yojson)] - type open_box = - | AxiomsOpen(AxiomsBox.Model.t) - | RewritesOpen({ - editor: CodeEditable.Model.t, - cached_exp: Calc.saved(Exp.t), - cached_result: option(bool), - }) - | NoneOpen; - - [@deriving (show({with_path: false}), sexp, yojson)] - type assumptions = list(AssumptionBox.Model.t); - - [@deriving (show({with_path: false}), sexp, yojson)] - type t = { - next_steps: Calc.saved(EvaluatorStep.status), - refls: Calc.saved(list(Exp.t)), - selected_id: Calc.saved(option(Id.t)), - selected_exp: Calc.saved(option(Exp.t)), - full_exp: Calc.saved(Exp.t), - assumptions: Calc.saved(option(assumptions)), - open_box, - cached_env: Calc.saved(Environment.t(Exp.t)) // TODO[Matt]: remove this later, just to get env into view for now. - }; - - let init = { - next_steps: Calc.Pending, - refls: Calc.Pending, - selected_id: Calc.Pending, - selected_exp: Calc.Pending, - full_exp: Calc.Pending, - assumptions: Calc.Pending, - open_box: NoneOpen, - cached_env: Calc.Pending, - }; - [@deriving (show({with_path: false}), sexp, yojson)] - type persistent = unit; - - let persist = (_: t): persistent => (); - - let unpersist = (_: persistent): t => init; -}; - -module Update = { - open Updated; - - [@deriving (show({with_path: false}), sexp, yojson)] - type t = - | ToggleAxioms - | ProposeRewrite - | UpdateResult(bool) - | RewriteEditorAction(CodeEditable.Update.t) - | AxiomBoxAction(AxiomsBox.Update.t); - - let update = (~settings, action, model: Model.t): Updated.t(Model.t) => { - switch (action, model.open_box) { - | (ToggleAxioms, _) => - let open_box = - switch (model.open_box) { - | NoneOpen - | RewritesOpen(_) => Model.AxiomsOpen(AxiomsBox.Model.init) - | AxiomsOpen(_) => Model.NoneOpen - }; - Model.{ - ...model, - open_box, - } - |> Updated.return_quiet(~logged=true); - | (ProposeRewrite, _) => - let open_box = - switch (model.open_box) { - | NoneOpen - | AxiomsOpen(_) => - Model.RewritesOpen({ - editor: - CodeEditable.Model.mk( - Editor.Model.mk(Zipper.init(), ~root=Exp), - ), - cached_exp: Calc.Pending, - cached_result: None, - }) - | RewritesOpen(_) => Model.NoneOpen - }; - Model.{ - ...model, - open_box, - } - |> Updated.return_quiet(~recalculate=true, ~logged=true); - | (RewriteEditorAction(action), RewritesOpen({editor, _} as r)) => - let* new_editor = CodeEditable.Update.update(~settings, action, editor); - Model.{ - ...model, - open_box: - Model.RewritesOpen({ - ...r, - editor: new_editor, - }), - }; - | (RewriteEditorAction(_), _) => model |> Updated.raise_invalid_action - | (UpdateResult(result), RewritesOpen(r)) => - Model.{ - ...model, - open_box: - Model.RewritesOpen({ - ...r, - cached_result: Some(result), - }), - } - |> Updated.return_quiet(~logged=true) - | (UpdateResult(_), _) => model |> Updated.raise_invalid_action - | (AxiomBoxAction(action), AxiomsOpen(m)) => - let* updated = AxiomsBox.Update.update(~settings, action, m); - Model.{ - ...model, - open_box: Model.AxiomsOpen(updated), - }; - | (AxiomBoxAction(_), _) => model |> Updated.raise_invalid_action - }; - }; - - let calculate = - ( - ~settings, - exp, - info_map, - ctx: Calc.t(SemanticCtx.t), - new_next_steps, - { - next_steps: _, - refls, - assumptions, - selected_exp, - full_exp: _, - selected_id, - open_box, - cached_env, - }: Model.t, - editor, - ) - : Model.t => { - let selected_id = - // hacky way to get a currently-selected id - { - let editor: CodeSelectable.Model.t = editor |> Calc.get_value; - try( - { - open OptUtil.Syntax; - let zipper = editor.editor.state.zipper; - let* id = - TermData.get_root_id_using_ranges( - zipper.selection.content, - editor.editor.syntax.term_data, - editor.editor.syntax.measured, - ); - Some(id); - } - ) { - | _ => None - }; - } - |> Calc.set(_, selected_id); - let selected_exp = - selected_exp - |> { - let.calc selected_id = selected_id - and.calc exp = exp; - open OptUtil.Syntax; - let* id = selected_id; - let* exp' = ProofHacks.find_exp_id(id, exp); - Some(exp'); - }; - let assumptions = - assumptions - |> { - let.calc _exp = selected_exp - and.calc ctx = ctx; - let proof_ctx = - ctx - |> SemanticCtx.get_env - |> Environment.to_list - |> List.filter_map(~f=((name, exp)) => - switch (Exp.term_of(exp)) { - | Grammar.ProofObject(e) => Some((name, e)) - | _ => None - } - ) - |> List.fold_left( - ~f=(acc, (name, exp)) => ProofCtx.add_exp(name, exp, acc), - ~init=Axioms.v, - ) - |> List.map(~f=ctx_entry => - AssumptionBox.Model.{ctx_entry: ctx_entry} - ); - Some(proof_ctx); - }; - let refls = - refls - |> { - let.calc exp = exp - and.calc ctx = ctx - and.calc new_next_steps = new_next_steps - and.calc info_map = info_map; - let next_steps = - new_next_steps - |> ( - fun - | EvaluatorStep.AutoStep(_) => [] - | EvaluatorStep.AvailableSteps(steps) => steps - ); - ProofHacks.find_refls(~info_map, ~env=SemanticCtx.get_env(ctx), exp) - |> List.filter(~f=e => - ! - List.exists( - ~f=s => e |> Exp.rep_id == EvaluatorStep.get_step_id(s), - next_steps, - ) - ); - }; - let open_box = - switch (open_box) { - | RewritesOpen({editor, cached_exp, cached_result}) => - // Calculate syntax, holes, types, etc for the editor - let editor = - CodeEditable.Update.calculate( - ~settings, - ~is_edited=true, - ~is_dynamic_term=true, - ~dynamics=Dynamics.Map.empty, - ~stitch=x => x, - ~ctx=Calc.get_value(ctx) |> SemanticCtx.get_ctx, - editor, - ); - // Extract an exp from the editor - let cached_exp = - Calc.set( - ~eq=Exp.fast_equal_with_lexemes, - CodeEditable.Model.get_statics(editor).elaborated, - cached_exp, - ); - // Reset result if editor changes - let cached_result = - Calc.Calculated(cached_result) - |> { - let.calc _ = cached_exp; - None; - }; - Model.RewritesOpen({ - editor, - cached_exp: cached_exp |> Calc.save, - cached_result: cached_result |> Calc.get_value, - }); - | AxiomsOpen(m) => - AxiomsOpen( - AxiomsBox.Update.calculate(~info_map, ~ctx, ~selected_exp, m), - ) - | NoneOpen => NoneOpen - }; - let cached_env = - cached_env - |> { - let.calc ctx = ctx; - SemanticCtx.get_env(ctx); - }; - { - next_steps: new_next_steps |> Calc.save, - refls: refls |> Calc.save, - assumptions: assumptions |> Calc.save, - full_exp: exp |> Calc.save, - selected_exp: selected_exp |> Calc.save, - selected_id: selected_id |> Calc.save, - cached_env: cached_env |> Calc.save, - open_box, - }; - }; -}; - -module Selection = { - open Cursor; - // Selection handles focus - - [@deriving (show({with_path: false}), sexp, yojson)] - type t = - | RewriteEditor(CodeEditable.Selection.t) - | AxiomBoxSelection(AxiomsBox.Selection.t); - - let get_cursor_info = - (~inject, ~selection: t, model: Model.t): cursor(Update.t) => { - switch (selection, model.open_box) { - | (RewriteEditor(selection), RewritesOpen({editor, _})) => - let+ ci = - CodeEditable.Selection.get_cursor_info( - ~inject=a => inject(Update.RewriteEditorAction(a)), - ~selection, - editor, - ); - Update.RewriteEditorAction(ci); - | (RewriteEditor(_), _) => empty - | (AxiomBoxSelection(selection), AxiomsOpen(m)) => - let+ ci = AxiomsBox.Selection.get_cursor_info(~selection, m); - Update.AxiomBoxAction(ci); - | (AxiomBoxSelection(_), _) => empty - }; - }; -}; - -module View = { - open OptUtil.Syntax; - type event = - | AddInduction(option(Exp.t)) - | AddForall - | HideStepper - | AddAxiomStep(string, int, Exp.t, Direction.t, string) - | AddAlgebriteStep(int, Exp.t, Exp.t) - | MakeActive(Selection.t) - | TakeStep(int) - | Refl(int); - - let get_segment_bounds = (~measured: Measured.t, segment: Segment.t) => { - let* first_piece = ListUtil.hd_opt(segment); - let Point.{row: start_y, col: start_x} = - Measured.find_p(~msg="get_segment_bounds", first_piece, measured) - |> (m => m.origin); - let* last_piece = ListUtil.last_opt(segment); - let Point.{row: end_y, col: end_x} = - Measured.find_p(~msg="get_segment_bounds", last_piece, measured) - |> (m => m.last); - let rec get_left = (current_left: int, row: int, final_row: int) => - if (row > final_row) { - current_left; - } else { - get_left( - Int.min( - current_left, - Measured.Rows.find(row, measured.rows).content_start, - ), - row + 1, - final_row, - ); - }; - let left = get_left(start_x, start_y, end_y); - let rec get_right = (current_right: int, row: int, final_row: int) => - if (row == final_row) { - current_right; - } else { - get_right( - Int.max( - current_right, - Measured.Rows.find(row, measured.rows).max_col, - ), - row + 1, - final_row, - ); - }; - let right = get_right(end_x, start_y, end_y); - Some((left, right, start_y, end_y + 1)); - }; - - let view_overlay = - ( - ~globals: Globals.t, - ~signal: event => Ui_effect.t(unit), - ~inject: Update.t => Ui_effect.t(unit), - ~editor: CodeSelectable.Model.t, - ~selected: option(Selection.t), - ~info_map, - model: Model.t, - ) => - { - let+ (left, right, top, bottom) = - get_segment_bounds( - ~measured=editor.editor.syntax.measured, - editor.editor.state.zipper.selection.content, - ); - - let proof_button = (~callback: Ui_effect.t(unit), label: string) => { - Node.div( - ~attrs=[ - Attr.classes(["proof-button"]), - Attr.on_pointerdown(_ => Virtual_dom.Vdom.Effect.Stop_propagation), - Attr.on_click(_ => - Ui_effect.Many([ - callback, - Virtual_dom.Vdom.Effect.Stop_propagation, - ]) - ), - ], - [Node.text(label)], - ); - }; - - let show_step_button = - switch ( - model.selected_exp |> Calc.get_saved_exc(~print="Selected Exp") - ) { - | Some(selected_exp) => - List.findi( - model.next_steps - |> Calc.get_saved_exc(~print="next_steps") - |> ( - fun - | AutoStep(_) => [] - | AvailableSteps(steps) => steps - ) - |> List.map(~f=step => step |> EvaluatorStep.get_step_id), - ~f=(_, x) => - x == (selected_exp |> Exp.rep_id) - ) - |> Option.map(~f=fst) - | None => None - }; - - let show_refl_button = - switch ( - model.selected_exp |> Calc.get_saved_exc(~print="Selected Exp") - ) { - | Some(selected_exp) => - List.findi( - model.refls - |> Calc.get_saved_exc(~print="refls") - |> List.map(~f=refl => refl |> Exp.rep_id), - ~f=(_, x) => - x == (selected_exp |> Exp.rep_id) - ) - |> Option.map(~f=fst) - | None => None - }; - - let show_function_body_button = { - Calc.get_saved_exc(model.selected_exp) - == Some(Calc.get_saved_exc(model.full_exp)) - && Exp.is_fun(Calc.get_saved_exc(model.full_exp)); - }; - - // I want to make a bunch of buttons here: - // Evaluate [TODO], Rewrite, Axioms, Cases, - let buttons = - Node.div( - ~attrs=[Attr.classes(["proof-selection-buttons"])], - ( - switch (show_step_button) { - | None => [] - | Some(idx) => [ - proof_button( - ~callback=Ui_effect.Many([signal(TakeStep(idx))]), - "Step", - ), - ] - } - ) - @ ( - switch (show_refl_button) { - | None => [] - | Some(idx) => [ - proof_button( - ~callback= - Ui_effect.Many([ - globals.inject_global( - Set(Evaluation(ForceShowRecord)), - ), - signal(Refl(idx)), - ]), - "Reflexivity", - ), - ] - } - ) - @ ( - show_function_body_button - ? [ - proof_button( - ~callback= - Ui_effect.Many([ - globals.inject_global( - Set(Evaluation(ForceShowRecord)), - ), - signal(AddForall), - ]), - "Function Body", - ), - ] - : [] - ) - @ [ - proof_button(~callback=inject(ProposeRewrite), "Algebra ▼"), - proof_button(~callback=inject(ToggleAxioms), "Assumptions ▼"), - proof_button( - ~callback= - Ui_effect.Many([ - globals.inject_global(Set(Evaluation(ForceShowRecord))), - signal( - AddInduction( - model.selected_exp - |> Calc.get_saved_exc(~print="Selected Exp"), - ), - ), - ]), - "Cases/Induction", - ), - ], - ); - - [ - Node.div( - ~attrs=[ - Attr.classes(["missing-step-overlay-align"]), - DecUtil.position( - ~width=right - left, - ~height=bottom - top, - ~font_metrics=globals.font_metrics, - Point.{ - col: left, - row: top, - }, - ), - ], - [ - Node.div( - ~attrs=[ - Attr.class_("proof-context-box"), - Attr.on_pointerdown(_ => - Virtual_dom.Vdom.Effect.Stop_propagation - ), - ], - [buttons] - @ { - switch (model.open_box) { - | NoneOpen => [] - | AxiomsOpen(m) => [ - div_c( - "axiom-box", - AxiomsBox.View.view( - ~globals, - ~info_map, - ~env= - model.cached_env - |> Calc.get_saved_exc(~print="env not cached"), - ~inject= - (a: AxiomsBox.Update.t) => - inject(AxiomBoxAction(a)), - ~take_focus= - (s: AxiomsBox.Selection.t) => - signal(MakeActive(AxiomBoxSelection(s))), - ~add_axiom_step= - (a, b, c, d, e) => - signal(AddAxiomStep(a, b, c, d, e)), - ~full_exp= - model.full_exp - |> Calc.get_saved_exc(~print="full_exp not cached"), - ~selected_exp= - model.selected_exp - |> Calc.get_saved_exc(~print="Selected Exp") - |> Option.value(~default=EmptyHole |> Exp.fresh, _), - m, - ), - ), - ] - | RewritesOpen({editor, cached_exp, cached_result}) => - let unboxed_cached_exp = - Calc.get_saved_exc( - ~print="cached exp not calculated", - cached_exp, - ); - let unboxed_selected_exp = - Option.value( - ~default=EmptyHole |> Exp.fresh, - Calc.get_saved_exc( - ~print="selected exp not calculated", - model.selected_exp, - ), - ); - [ - // one element list with a div - // with a list containing two elements - // an Editor for user to propose their rewrite - // a button to submit the rewrite - div_c( - "rewrite-box", - [ - Node.text("Replace: "), - CodeViewable.view_any( - ~globals, - ~settings= - ExpToSegment.Settings.of_core( - ~inline=false, - ~fold_fn_bodies=`Text, - globals.settings.core, - ), - Exp(unboxed_selected_exp), - ), - Node.text("With: "), - div_c( - "inline-editor-wrapper", - [ - CodeEditable.View.view( - ~globals, - ~signal= - fun - | MakeActive => - signal(MakeActive(RewriteEditor())), - ~edit_mode= - EditMode.Editable({ - inject: x => - inject(RewriteEditorAction(x)), - escape: _ => Ui_effect.Ignore, - take_focus: _ => Ui_effect.Ignore, - focus: - switch (selected) { - | Some(RewriteEditor ()) => Some() - | _ => None - }, - }), - ~dynamics=Dynamics.Map.empty, - editor, - ), - ], - ), - ] - @ { - switch (cached_result) { - | Some(true) => [ - Node.text("Valid"), - Widgets.button( - ~clss=["proof-button"], - Node.text("Replace"), - ~tooltip="replace", - _ => - signal( - AddAlgebriteStep( - ProofHacks.exp_idx( - unboxed_selected_exp, - model.full_exp - |> Calc.get_saved_exc(~print="full_exp"), - ), - unboxed_selected_exp, - unboxed_cached_exp - |> Substitution.in_exp( - model.cached_env - |> Calc.get_saved_exc( - ~print="env not cached", - ), - ), - ), - ) - ), - ] - | Some(false) => [Node.text("Invalid")] - | None => [ - Widgets.button( - ~clss=["proof-button"], - Node.text("Check"), - _ => - inject( - UpdateResult( - RewriteChecker.check_rewrite( - unboxed_selected_exp - |> Substitution.in_exp( - model.cached_env - |> Calc.get_saved_exc( - ~print="env not cached", - ), - ), - unboxed_cached_exp - |> Substitution.in_exp( - model.cached_env - |> Calc.get_saved_exc( - ~print="env not cached", - ), - ), - ), - ), - ), - ~tooltip="check", - ), - ] - }; - }, - ), - ]; - }; - }, - ), - ], - ), - ]; - } - |> Option.value(~default=[]); - - let view_justification = - ( - ~globals: Globals.t, - ~hide_stepper: Ui_effect.t(unit), - ~undo: option(Ui_effect.t(unit)), - ~is_toplevel: bool, - _model: Model.t, - ) => { - let button_back = - Widgets.button_d( - Icons.undo, - switch (undo) { - | Some(u) => u - | None => Ui_effect.Ignore - }, - ~disabled=Option.is_none(undo), - ~tooltip="Step Backwards", - ); - let button_hide_stepper = - Widgets.toggle(~tooltip="Show Stepper", "s", true, _ => hide_stepper); - let toggle_show_history = - Widgets.toggle( - ~tooltip="Show History", - "h", - globals.settings.core.evaluation.stepper_history, - _ => - globals.inject_global(Set(Evaluation(ShowRecord))) - ); - let eval_settings = - Widgets.button(Icons.gear, _ => - globals.inject_global(Set(Evaluation(ShowSettings))) - ); - Node.div( - ~attrs=[Attr.classes(["stepper-controls"])], - [button_back] - @ ( - is_toplevel - ? [eval_settings, toggle_show_history, button_hide_stepper] : [] - ), - ); - }; -}; diff --git a/src/web/app/editors/stepper/Obligations.re b/src/web/app/editors/stepper/Obligations.re new file mode 100644 index 0000000000..2516fd3ab5 --- /dev/null +++ b/src/web/app/editors/stepper/Obligations.re @@ -0,0 +1,325 @@ +open Language; + +/* A theorem's obligations, as its header and its side-condition circles + * show them: the status they give the theorem, and the exits that + * discharge a pending one by patching the program. */ + +module Status = { + /* What a theorem's header says. A proof that cites unfinished theorems + * is proven relative to them, a deliberate assumption rather than a + * gap. Any other open condition is a gap: the proof isn't proven, and + * the header counts them, quietly, to help the user find them. */ + type t = + | Proven + /* The names of the unfinished theorems it cites. */ + | Relying(list(string)) + | Refuted + /* The open conditions, citations aside. */ + | Incomplete(int); + + let of_proof = (pm: ProofMap.t, proof: Proof.t): t => { + let (citations, gaps) = + ProofMap.pending_obligations(pm, proof) + |> List.partition_tf(~f=(ob: Obligation.t) => + Poly.equal(ob.kind, Citation) + ); + /* A citation's origin is the `rewrite` step naming the theorem. */ + let rec find = (id, p: Proof.t) => + Id.equal(Proof.rep_id(p), id) + ? Some(p) : List.find_map(~f=find(id), Proof.children(p)); + let cited = (ob: Obligation.t) => + switch (Option.map(~f=(p: Proof.t) => p.term, find(ob.origin, proof))) { + | Some(AxiomStep({equality, _})) => ProofSyntax.exp_to_name(equality) + | _ => None + }; + switch (ProofMap.full_status_of_proof(pm, proof), gaps) { + | (Proven, _) => Proven + | (Refuted, _) => Refuted + | (ProvenModulo(_), []) => + Relying(List.filter_map(~f=cited, citations) |> Util.ListUtil.dedup) + | (ProvenModulo(_) | Incomplete, _) => Incomplete(List.length(gaps)) + }; + }; + + let label = (status: t): string => + switch (status) { + | Proven => "proven" + | Relying(_) => "proven*" + | Refuted => "refuted" + | Incomplete(0) => "incomplete" + | Incomplete(n) => "incomplete · " ++ string_of_int(n) ++ " open" + }; + + /* Class suffixes are kept in sync with theorems.css. */ + let class_ = (status: t): string => + switch (status) { + | Proven => "true" + | Relying(_) => "relying" + | Refuted => "false" + | Incomplete(_) => "unknown" + }; +}; + +/* A pending obligation's exits, each a patch to the program text. + * + * For a proof step's obligation: + * 1. Prove here: wrap the proof region in `have proof ? => …`. + * The obligation is discharged at once by the have's hypothesis, and + * the `?` is proved later. + * 2. Split on it: wrap the region in `cases | true => + * | false => ? end`. The `true` case's equation covers the + * obligation; the `false` case is left open. + * Both are checked before they are offered: the wrapped proof is + * checked again, and an exit that would break a step or leave the + * obligation pending shows disabled. */ +module Exits = { + /* One exit. With no patch it shows disabled, its title saying why. */ + type t = { + label: string, + title: string, + patch: option(Haz3lcore.EditorTransform.patch), + }; + + /* The theorem a step's exits patch: they wrap a region of the proof, + * checked with the program's statics. */ + type ctx = { + proof: Proof.t, + proof_map: ProofMap.t, + info_map: Statics.Map.t, + }; + + /* Is `origin` the id of a node in this proof subtree? */ + let rec proof_contains = (~origin: Id.t, p: Proof.t): bool => + Id.equal(Proof.rep_id(p), origin) + || ( + switch (p.term) { + | EmptyHole + | Invalid(_) + | MultiHole(_) + | AxiomStep(_) + | AlgebriteStep(_) + | EvalStep => false + | Seq(a, b) => + proof_contains(~origin, a) || proof_contains(~origin, b) + | Focus({body, _}) + | Parens(body) + | Forall(_, body) + | Funext(_, body) + | Assume(_, _, body) + | Generalize(_, body) + | Alias(_, _, body) + | Revert(_, _, body) => proof_contains(~origin, body) + | Have(_, _, sub, body) => + proof_contains(~origin, sub) || proof_contains(~origin, body) + | Cases(_, cases) + | Induction(_, cases) => + List.exists(~f=((_, body)) => proof_contains(~origin, body), cases) + } + ); + + /* The goal, fit to write into the program, as in + * `StepperPicker.Terms.embed_exp`. The goal is a slice of the program + * and carries its tiles' ids: written in verbatim, one id would land on + * two tiles, which crashes the view. */ + let embed_goal = (ob: Obligation.t): Exp.t => + ob.goal |> Substitution.in_exp(Environment.empty) |> Exp.replace_all_ids; + + /* The proof region the exits wrap: the whole step chain of the + * innermost scope holding the step that incurred the obligation. It has + * to be the innermost, or a goal mentioning a case's variable would be + * wrapped outside the case that binds it. Taking the whole chain keeps + * the wrapper's body a complete `Seq` spine. */ + let region_of = (~ctx: ctx, ob: Obligation.t): option(Proof.t) => { + let origin = ob.origin; + let rec scope_body_containing = (p: Proof.t): option(Proof.t) => + switch (p.term) { + | Forall(_, body) + | Funext(_, body) + | Assume(_, _, body) + | Generalize(_, body) + | Alias(_, _, body) + | Revert(_, _, body) => + proof_contains(~origin, body) ? Some(body) : None + | Have(_, _, sub, body) => + proof_contains(~origin, body) + ? Some(body) : proof_contains(~origin, sub) ? Some(sub) : None + | Cases(_, cases) + | Induction(_, cases) => + List.find_map( + ~f= + ((_, body)) => + proof_contains(~origin, body) ? Some(body) : None, + cases, + ) + | Seq(a, b) => + switch (scope_body_containing(a)) { + | Some(_) as r => r + | None => scope_body_containing(b) + } + /* Parens are not a scope. Nor is a focus: a wrapper inside one would + have the focused subterm for its goal. */ + | Parens(inner) + | Focus({body: inner, _}) => scope_body_containing(inner) + | EmptyHole + | Invalid(_) + | MultiHole(_) + | AxiomStep(_) + | AlgebriteStep(_) + | EvalStep => None + }; + let rec region_containing = (root: Proof.t): option(Proof.t) => + if (!proof_contains(~origin, root)) { + None; + } else { + switch (scope_body_containing(root)) { + | Some(body) => region_containing(body) + | None => Some(root) + }; + }; + region_containing(ctx.proof); + }; + + /* `have proof ? => `. */ + let have = (ob: Obligation.t, region: Proof.t): Proof.t => + Proof.fresh( + Have(embed_goal(ob), None, Proof.fresh(EmptyHole), region), + ); + + /* `cases | true => | false => ? end`: an ordinary + * case split on a bool, checked like any other. */ + let split = (ob: Obligation.t, region: Proof.t): Proof.t => + Proof.fresh( + Cases( + embed_goal(ob), + [ + (Pat.fresh(Atom(Bool(true))), region), + (Pat.fresh(Atom(Bool(false))), Proof.fresh(EmptyHole)), + ], + ), + ); + + let wrap_patch = + (wrapper, ~ctx: ctx, ob: Obligation.t) + : option(Haz3lcore.EditorTransform.patch) => + region_of(~ctx, ob) + |> Option.map(~f=region => + Haz3lcore.EditorTransform.mk_proof_patch( + ~target_id=Proof.rep_id(region), + wrapper(ob, region), + ) + ); + let have_patch = wrap_patch(have); + let split_patch = wrap_patch(split); + + /* Answers of `wrap_problem` for one proof map. A long proof takes a + * while to check, and the view asks again on every redraw while the + * condition is open, so answers are kept until the proof is checked + * again. */ + let checked_wraps: + ref((ProofMap.t, list(((string, Id.t, Id.t), option(string))))) = + ref((ProofMap.empty, [])); + + /* Why `wrapper` can't wrap `ob`'s region, if it can't. The theorem's + * proof is checked again with the region wrapped, without the new + * syntax's statics, so marks on the wrapper itself (an untyped split) + * don't count: the wrap must keep every clean step clean and discharge + * `ob`. Splitting on a condition the goal mentions rewrites the goal of + * the steps below, for one. */ + let wrap_problem = + (wrapper, ~ctx: ctx, ob: Obligation.t, region: Proof.t): option(string) => + switch (ProofMap.lookup(Proof.rep_id(ctx.proof), ctx.proof_map)) { + | Some({incoming: Some(goal), ctx: scope, _}) => + let wrapped = + Proof.map_term( + ~f_proof= + (continue, p) => + Id.equal(Proof.rep_id(p), Proof.rep_id(region)) + ? wrapper(ob, region) : continue(p), + ctx.proof, + ); + let checked = + Evaluator.Proofs.check_proof( + ~statics=ProofStatics.of_info_map(ctx.info_map), + ~ctx=scope, + ~goal, + wrapped, + ); + let breaks = + Id.Map.exists( + (id, entry: ProofMap.entry) => + List.is_empty(entry.marks) + && !List.is_empty(ProofMap.marks_of(id, checked)), + ctx.proof_map, + ); + let pending = + switch (ProofMap.lookup(ob.origin, checked)) { + | Some(entry) => + List.exists( + ~f= + (o: Obligation.t) => + Obligation.is_pending(o) && Exp.fast_equal(o.goal, ob.goal), + entry.obligations, + ) + | None => false + }; + breaks + ? Some("Unavailable: it would break a step of the proof") + : pending + ? Some("Unavailable: it wouldn't discharge this condition") : None; + | Some(_) + | None => None + }; + + /* A step's exits: none once the obligation is discharged. */ + let for_step = (~ctx: ctx, ob: Obligation.t): list(t) => { + let wrap_problem = (~label, wrapper, region) => { + let (proof_map, answers) = checked_wraps^; + let answers = phys_equal(proof_map, ctx.proof_map) ? answers : []; + let key = (label, ob.origin, Exp.rep_id(ob.goal)); + switch (List.Assoc.find(answers, key, ~equal=Poly.equal)) { + | Some(answer) => answer + | None => + let answer = wrap_problem(wrapper, ~ctx, ob, region); + checked_wraps := (ctx.proof_map, [(key, answer), ...answers]); + answer; + }; + }; + let wrap = (~label, ~title, wrapper) => + switch (region_of(~ctx, ob)) { + | None => { + label, + title: "Unavailable: the step that needs this isn't in the theorem's proof", + patch: None, + } + | Some(region) => + switch (wrap_problem(~label, wrapper, region)) { + | Some(problem) => { + label, + title: problem, + patch: None, + } + | None => { + label, + title, + patch: wrap_patch(wrapper, ~ctx, ob), + } + } + }; + Obligation.is_pending(ob) + ? [ + wrap( + ~label="Prove here", + ~title= + "Wrap this part of the proof in `have proof ? => …` and prove it later", + have, + ), + wrap( + ~label="Split on it", + ~title= + "Case-split on this condition: the `true` branch gets it as a fact, the `false` branch stays open", + split, + ), + ] + : []; + }; +}; diff --git a/src/web/app/editors/stepper/ProofMarkView.re b/src/web/app/editors/stepper/ProofMarkView.re new file mode 100644 index 0000000000..3d3ef077cf --- /dev/null +++ b/src/web/app/editors/stepper/ProofMarkView.re @@ -0,0 +1,171 @@ +open Virtual_dom.Vdom; +open Node; +open Util.WebUtil; +open Util; +open Language; + +/* Proof-check marks (ProofMark.t) as messages, shared by the cursor + inspector, the stepper and the obligations panel so a failure reads the + same everywhere. */ + +/* How the prover's read-only views show expressions: inline, with the + * user's display settings. A read-only view draws no projectors, so a + * folded function shows as its name rather than as a fold, and tables + * print as code. */ +let code_view_settings = + (settings: CoreSettings.t): Haz3lcore.ExpToSegment.Settings.t => { + ... + Haz3lcore.ExpToSegment.Settings.of_core( + ~inline=true, + ~fold_fn_bodies=settings.evaluation.show_fn_bodies ? `NoFold : `Text, + settings, + ), + project_tables: false, +}; + +let view_exp = (~globals, exp: Exp.t) => + div( + ~attrs=[clss(["code-box-container"])], + [ + CodeViewable.view_exp( + ~globals, + ~settings=code_view_settings(globals.settings.core), + exp, + ), + ], + ); + +let view_any = (~globals, any: Any.t) => + div( + ~attrs=[clss(["code-box-container"])], + [ + CodeViewable.view_any( + ~globals, + ~settings=code_view_settings(globals.settings.core), + any, + ), + ], + ); + +/* The statics' inexhaustiveness message (Mark.InexhaustiveMatch), worded + * like the cursor inspector's, with a missing pattern. */ +let inexhaustive_message = (~globals, example: Any.t): list(Node.t) => [ + text("Cases are inexhaustive. An example of a missing pattern is "), + view_any(~globals, example), +]; + +let message = (~globals, m: ProofMark.t): list(Node.t) => { + let view_exp_box = view_exp(~globals); + switch (m) { + | MissingIncoming => [ + text("No incoming goal to act on (an earlier step failed)."), + ] + | MalformedProofTerm => [ + text("This step contains text that isn't a valid proof step."), + ] + | MalformedEqualityName => [ + text("Expected an equality name (a variable referring to an axiom)."), + ] + | UnknownEquality(name) => [text("Unknown equality \"" ++ name ++ "\".")] + | CitesRefuted(name) => [ + text("`" ++ name ++ "` is refuted, so it can't be cited."), + ] + | RuleDoesNotApply({equality, direction}) => [ + text( + "Equality \"" + ++ equality + ++ "\" doesn't apply in the " + ++ ( + switch ((direction: Direction.t)) { + | Left => "left" + | Right => "right" + } + ) + ++ " direction here.", + ), + ] + | UnderdeterminedInstantiation({equality}) => [ + text( + "Rule \"" + ++ equality + ++ "\" matched, but quantified variables remain undetermined; supply an explicit instantiation.", + ), + ] + | PossiblyDivergentInstantiation({equality, var}) => [ + text( + "Applying \"" + ++ equality + ++ "\" here instantiates " + ++ var + ++ " at an expression that may not terminate.", + ), + ] + | FloatAlgebrite => [ + text("Algebraic rewrites are refused on float-typed expressions."), + ] + | AlgebraDiffers => [text("Algebra finds these are not equal.")] + | PatternNotFound({selector, ordinal: 1}) => [ + text("Could not find "), + view_exp_box(selector), + text(" in the goal."), + ] + | PatternNotFound({selector, ordinal}) => [ + text("Could not find occurrence " ++ string_of_int(ordinal) ++ " of "), + view_exp_box(selector), + text(" in the goal."), + ] + | NothingToStep => [ + text( + "Nothing to evaluate at the root of the goal. Focus on a subterm with `from`.", + ), + ] + | ExpectedForallGoal => [text("Expected a `forall` goal here.")] + | ExpectedImplicationGoal({assumption}) => [ + text("`assume` needs a goal of the form "), + view_exp_box(assumption), + text(" ==> …. Use `have` to add a fact to any goal."), + ] + | ExpectedFunEqGoal => [ + text("Expected a goal of the form `f == g` between two functions."), + ] + | MalformedFunext => [ + text("`funext` needs a variable pattern to name the argument."), + ] + | BinderCaptures({var}) => [ + text( + "`" ++ var ++ "` is already used in the goal. Choose another name.", + ), + ] + | MalformedGeneralize => [ + text("`generalize` expects a bare in-scope variable."), + ] + | InductionNotExhaustive => [ + text("The cases don't cover the scrutinee's type."), + ] + | InductionScrutineeUntyped => [ + text( + "The scrutinee's type is unknown, so these cases cannot be shown to cover it. Annotate the binder.", + ), + ] + | PossiblyDivergentScrutinee => [ + text("The split scrutinee may not terminate."), + ] + | UnknownFactReverted => [text("No fact in scope matches this `revert`.")] + | UnknownInstantiationVar({equality, var}) => [ + text("`" ++ var ++ "` is not a binder of `" ++ equality ++ "`."), + ] + | RevertFactNotQuantified({var}) => [ + text("The reverted fact is not quantified over `" ++ var ++ "`."), + ] + | InductionUnsupportedWildcard => [ + span( + ~attrs=[clss(["induction-wildcard-warning"])], + [ + text( + "Wildcard case patterns are not supported in proofs yet. No case of this split is checked.", + ), + ], + ), + ] + }; +}; diff --git a/src/web/app/editors/stepper/RewriteChecker.re b/src/web/app/editors/stepper/RewriteChecker.re index 7a91ede679..7bc4c4100c 100644 --- a/src/web/app/editors/stepper/RewriteChecker.re +++ b/src/web/app/editors/stepper/RewriteChecker.re @@ -51,13 +51,19 @@ let rec print_exp_for_algebrite = (~name_other, exp: Exp.t): string => | _ => name_other(exp) }; +/* The page loads Algebrite. Where it isn't loaded, nothing is equal by + * algebra. */ let checkEquality = (expr1, expr2): bool => { let algebrite = Js.Unsafe.global##.Algebrite; - let diffExpr = sprintf("simplify((%s)-(%s))", expr1, expr2); - let algebrite_result = algebrite##run(Js.string(diffExpr)); - switch (Js.to_string(algebrite_result)) { - | "0" => true - | _ => false + if (String.equal(Js.to_string(Js.typeof(algebrite)), "undefined")) { + false; + } else { + let diffExpr = sprintf("simplify((%s)-(%s))", expr1, expr2); + let algebrite_result = algebrite##run(Js.string(diffExpr)); + switch (Js.to_string(algebrite_result)) { + | "0" => true + | _ => false + }; }; }; @@ -74,11 +80,6 @@ let check_rewrite = (from_: Exp.t, to_: Exp.t): bool => { let to_ = DHExp.strip_ascriptions(to_); let left_str = print_exp_for_algebrite(~name_other, from_); let right_str = print_exp_for_algebrite(~name_other, to_); - print_endline("Checking rewrite:"); - print_endline("From: " ++ left_str); - print_endline("To: " ++ right_str); - print_endline("e1: " ++ Exp.show(from_)); - print_endline("e2: " ++ Exp.show(to_)); if (String.equal(left_str, "Unknown") || String.equal(right_str, "Unknown")) { false; } else { diff --git a/src/web/app/editors/stepper/SingleStep.re b/src/web/app/editors/stepper/SingleStep.re deleted file mode 100644 index 227a7b7160..0000000000 --- a/src/web/app/editors/stepper/SingleStep.re +++ /dev/null @@ -1,166 +0,0 @@ -open Util; -open Language; -open StepInterface; -open OptUtil.Syntax; -open Calc.Syntax; - -/* Types are defined outside the module to make it - easier to use them in other files. */ - -[@deriving (show({with_path: false}), sexp, yojson)] -type model'('stepper) = { - // Constant - persistent_evalobj: EvaluatorStep.persistent, - // Calculated - evalobj: Calc.saved(EvaluatorStep.step), - next_exp: Calc.saved(Exp.t), -}; - -[@deriving (show({with_path: false}), sexp, yojson)] -type persistent'('stepper) = EvaluatorStep.persistent; - -[@deriving (show({with_path: false}), sexp, yojson)] -type action'('step) = - |; - -[@deriving (show({with_path: false}), sexp, yojson)] -type focus'('step) = - |; - -/* The methods in this file, like the other step files, are - parameterized by a Stepper module that implements the - stepper interface. This allows us to use steppers inside - steps inside steppers. The lines below can be copied as - boilerplate to other steps.*/ -module F = - (Stepper: STEPPER) - - : ( - STEP with - type model = model'(Stepper.model) and - type persistent = persistent'(Stepper.persistent) and - type action = action'(Stepper.action) and - type focus = focus'(Stepper.focus) - ) => { - [@deriving (show({with_path: false}), sexp, yojson)] - type model = model'(Stepper.model); - [@deriving (show({with_path: false}), sexp, yojson)] - type persistent = persistent'(Stepper.persistent); - [@deriving (show({with_path: false}), sexp, yojson)] - type action = action'(Stepper.action); - [@deriving (show({with_path: false}), sexp, yojson)] - type focus = focus'(Stepper.focus); - - let persist = (model: model) => { - model.persistent_evalobj; - }; - - let unpersist = (p: persistent) => { - { - persistent_evalobj: p, - evalobj: Calc.Pending, - next_exp: Calc.Pending, - }; - }; - - let update = (~settings as _: Settings.t, action: action, _model: model) => - switch (action) { - | _ => . - }; - - let calculate = - ( - ~settings: Calc.t(CoreSettings.t), - ~hidden: Calc.saved(bool), - ~exp: Calc.t(Exp.t), - ~ctx: Calc.t(SemanticCtx.t), - ~editor as _: Calc.t(CodeSelectable.Model.t), - ~info_map as _, - ~ana as _, - model: model, - ) => { - let {persistent_evalobj, evalobj, next_exp} = model; - let* hidden_and_eo = - Calc.saved_pair((hidden, evalobj)) - |> Calc.map_saved(Option.some) - |> { - let.calc settings = settings - and.calc exp = exp - and.calc ctx = ctx; - let+ (filter_action, eo) = - EvaluatorStep.refresh_step( - ~settings, - exp, - SemanticCtx.get_env(ctx), - persistent_evalobj, - ); - let hidden = - switch (filter_action) { - | FilterAction.Step => false - | FilterAction.Eval => true - }; - (hidden, eo); - } - |> Calc.to_option; - let (hidden, evalobj) = Calc.to_pair(hidden_and_eo); - let+ next_exp = - next_exp - |> Calc.map_saved(Option.some) - |> { - let.calc evalobj = evalobj; - EvaluatorStep.take_step(evalobj); - } - |> Calc.to_option; - ( - { - persistent_evalobj, - evalobj: evalobj |> Calc.save, - next_exp: next_exp |> Calc.save, - }, - hidden, - Some(next_exp), - Calc.OldValue(Some(true)), - ); - }; - - let get_cursor_info = - ( - ~inject as _: action => Ui_effect.t(unit), - ~focus: focus, - _model: model, - ) => - switch (focus) { - | _ => . - }; - - let view_justification = - ( - ~globals as _: Globals.t, - ~focus as _: option(focus), - ~inject as _: action => Ui_effect.t(unit), - ~take_focus as _: focus => Ui_effect.t(unit), - ~hide_stepper as _: Ui_effect.t(unit), - ~undo as _: option(Ui_effect.t(unit)), - ~is_toplevel as _: bool, - m: model, - ) => - WebUtil.Node.text( - m.evalobj - |> Calc.get_saved_exc(~print="EvaluatorStep not calculated") - |> EvaluatorStep.get_step_kind - |> Transition.stepper_justification, - ); - - let view_content = - ( - ~globals as _: Globals.t, - ~focus as _: option(focus), - ~inject as _: action => Ui_effect.t(unit), - ~take_focus as _: focus => Ui_effect.t(unit), - ~hide_stepper as _: Ui_effect.t(unit), - ~undo as _: option(Ui_effect.t(unit)), - ~is_toplevel as _: bool, - _model: model, - ) => - []; -}; diff --git a/src/web/app/editors/stepper/StepInterface.re b/src/web/app/editors/stepper/StepInterface.re deleted file mode 100644 index 27cdba75c6..0000000000 --- a/src/web/app/editors/stepper/StepInterface.re +++ /dev/null @@ -1,114 +0,0 @@ -open Util; -open Language; - -module type STEP = { - [@deriving (show({with_path: false}), sexp, yojson)] - type model; - [@deriving (show({with_path: false}), sexp, yojson)] - type persistent; - [@deriving (show({with_path: false}), sexp, yojson)] - type action; - [@deriving (show({with_path: false}), sexp, yojson)] - type focus; - - let persist: model => persistent; - - let unpersist: persistent => model; - - let update: (~settings: Settings.t, action, model) => Updated.t(model); - - let calculate: - ( - ~settings: Calc.t(CoreSettings.t), - ~hidden: Calc.saved(bool), - ~exp: Calc.t(Exp.t), - ~ctx: Calc.t(SemanticCtx.t), - ~editor: Calc.t(CodeSelectable.Model.t), - ~info_map: Calc.t(Statics.Map.t), - ~ana: Calc.t(Typ.t), - model - ) => - option( - ( - model, - Calc.t(bool), // Hidden - option(Calc.t(Exp.t)), // Next - Calc.t(option(bool)) // Truth - ), - ); - - let get_cursor_info: - (~inject: action => Ui_effect.t(unit), ~focus: focus, model) => - Cursor.cursor(action); - - let view_justification: - ( - ~globals: Globals.t, - ~focus: option(focus), - ~inject: action => Ui_effect.t(unit), - ~take_focus: focus => Ui_effect.t(unit), - ~hide_stepper: Ui_effect.t(unit), - ~undo: option(Ui_effect.t(unit)), - ~is_toplevel: bool, - model - ) => - WebUtil.Node.t; - - let view_content: - ( - ~globals: Globals.t, - ~focus: option(focus), - ~inject: action => Ui_effect.t(unit), - ~take_focus: focus => Ui_effect.t(unit), - ~hide_stepper: Ui_effect.t(unit), - ~undo: option(Ui_effect.t(unit)), - ~is_toplevel: bool, - model - ) => - list(WebUtil.Node.t); -}; - -module type STEPPER = { - [@deriving (show({with_path: false}), sexp, yojson)] - type model; - [@deriving (show({with_path: false}), sexp, yojson)] - type persistent; - [@deriving (show({with_path: false}), sexp, yojson)] - type action; - [@deriving (show({with_path: false}), sexp, yojson)] - type focus; - - let init: model; - - let persist: model => persistent; - - let unpersist: persistent => model; - - let update: (~settings: Settings.t, action, model) => Updated.t(model); - - let calculate: - ( - ~settings: Calc.t(CoreSettings.t), - ~exp: Calc.t(Exp.t), - ~ctx: Calc.t(SemanticCtx.t), - ~ana: Calc.t(Typ.t), - model - ) => - (model, Calc.t(Exp.t), Calc.t(option(bool)) /* Truth */); - - let get_cursor_info: - (~inject: action => Ui_effect.t(unit), ~focus: focus, model) => - Cursor.cursor(action); - - let view: - ( - ~globals: Globals.t, - ~take_focus: focus => Ui_effect.t(unit), - ~inject: action => Ui_effect.t(unit), - ~hide_stepper: Ui_effect.t(unit), - ~focus: option(focus), - ~is_toplevel: bool, - model - ) => - list(WebUtil.Node.t); -}; diff --git a/src/web/app/editors/stepper/StepSearch.re b/src/web/app/editors/stepper/StepSearch.re new file mode 100644 index 0000000000..78859a0d5c --- /dev/null +++ b/src/web/app/editors/stepper/StepSearch.re @@ -0,0 +1,835 @@ +open Util; +open Language; +open Poly; + +/* The write box's quick search: the steps that take a row's goal to the + * goal the user typed, found by breadth-first search, so the fewest steps + * win. + * + * Its moves are steps a user could write: `step`, at the goal's root or + * through a focus on a part that can step; reflexivity; each fact, theorem + * and axiom in either direction, at each part it rewrites; and `algebra` + * of a part with a variable in it to the typed part, when the algebra + * check says they're equal. Arithmetic with no variables is left to + * `step`. The checker verifies only Int arithmetic over Int variables, so + * an `algebra` step with a call in it leaves its equation as an + * obligation. + * Each candidate is checked by the checker against the goal it starts + * from, not by checking the theorem again, so a step found is a step the + * checker accepts. + * + * Moves act only inside the smallest part of the goal that differs from + * the typed goal: a step elsewhere would change something already right. + * A rule can rewrite most goals somehow (`rewrite <- not_not` turns any + * boolean `b` into `!!b`), so a rule's step is kept only if it shrinks + * that part; a `step`, which may unfold a definition first, is kept + * either way. + * + * The search goes `max_depth` steps deep, one more on a small goal, and + * checks at most `max_checks` candidates. It runs in slices (`run`), so a + * slow check never holds up typing for longer than one candidate takes. */ + +module Picker = StepperPicker; + +let max_depth = 3; +/* A goal of at most this many nodes is searched one step deeper. */ +let small_goal = 15; +let max_checks = 300; +/* The parts a step may act on, nearest the differing part first. */ +let max_parts = 40; + +/* A goal the search reached, the steps that reach it, in order, and the + * size of its part that differs from the typed goal. */ +[@deriving (show({with_path: false}), sexp, yojson)] +type node = { + goal: Exp.t, + steps: list(Proof.t), + differs: int, +}; + +[@deriving (show({with_path: false}), sexp, yojson)] +type move = + | Eval + | Rule; + +[@deriving (show({with_path: false}), sexp, yojson)] +type status = + | Searching + /* No steps when the typed goal is the goal already. */ + | Found(list(Proof.t)) + | NotFound; + +[@deriving (show({with_path: false}), sexp, yojson)] +type t = { + /* The typed goal, without ascriptions, as every goal is compared. */ + wanted: Exp.t, + status, + /* The node being expanded, with its candidate steps not yet checked. */ + expanding: option((node, list((move, Proof.t)))), + /* The nodes to expand at this depth, and those reached for the next. */ + frontier: list(node), + next: list(node), + /* Every goal reached, in the form `wanted` is in. */ + seen: list(Exp.t), + checks: int, + depth: int, +}; + +/* Goals compared up to ascriptions and the names of binders. */ +let same = Equality.ignoring_ascriptions.exp; + +/* A goal as it is compared: without ascriptions, and with a negated + * number read as the negative number. Evaluation gives `-3` as a number, + * while typing `-3` gives the negation of `3`. */ +let comparable = (e: Exp.t): Exp.t => + DHExp.strip_ascriptions(e) + |> Exp.map_term(~f_exp=(continue, e) => { + let (term, rewrap) = Exp.unwrap(e); + switch (term) { + | UnOp(Int(Minus), {term: Atom(Int(n)), _}) => + rewrap(Atom(Int(Bigint.neg(n)))) + | _ => continue(e) + }; + }); + +/* Whether `e` is the typed goal: as written, or else once the scope's + * definitions they name are unfolded where they differ. */ +let reaches = (goal: Picker.Goal.t, e: Exp.t, wanted: Exp.t): bool => + same(e, wanted) + || MatchExp.equal_modulo(~defs=Picker.Goal.env(goal), e, wanted); + +let rec unwrap = (e: Exp.t): Exp.t => + switch (Exp.term_of(e)) { + | Parens(inner) + | Asc(inner, _) => unwrap(inner) + | _ => e + }; + +/* The smallest part of `goal` holding every difference from `wanted`, + * with the matching part of `wanted`, or None if they are the same. A + * part in parens comes with its parens, where the checker's step on it + * starts. */ +let rec differing = (goal: Exp.t, wanted: Exp.t): option((Exp.t, Exp.t)) => { + let (g, w) = (unwrap(goal), unwrap(wanted)); + let (gs, ws) = (Occurrence.children(g), Occurrence.children(w)); + let pairs = + Exp.cls_of_term(Exp.term_of(g)) == Exp.cls_of_term(Exp.term_of(w)) + && List.length(gs) == List.length(ws) + ? Some(List.zip_exn(gs, ws)) : None; + switch ( + same(g, w), + Option.map(~f=List.filter(~f=((a, b)) => !same(a, b)), pairs), + ) { + | (true, _) => None + | (false, Some([(a, b)])) => + switch (differing(a, b)) { + | Some(_) as part => part + | None => Some((goal, wanted)) + } + | (false, _) => Some((goal, wanted)) + }; +}; + +let rec size = (e: Exp.t): int => + List.fold_left( + ~f=(n, child) => n + size(child), + ~init=1, + Occurrence.children(e), + ); + +let differs = (compared: Exp.t, wanted: Exp.t): int => + differing(compared, wanted) + |> Option.value_map(~default=0, ~f=((p, _)) => size(p)); + +let start = (goal: Picker.Goal.t, ~wanted: Exp.t): t => { + let wanted = comparable(wanted); + let here = comparable(goal.written); + { + wanted, + status: reaches(goal, here, wanted) ? Found([]) : Searching, + expanding: None, + frontier: [ + { + goal: goal.written, + steps: [], + differs: differs(here, wanted), + }, + ], + next: [], + seen: [here], + checks: 0, + depth: size(here) <= small_goal ? max_depth + 1 : max_depth, + }; +}; + +/* What can be checked as `rewrite`: arithmetic, with no booleans in it. + * The algebra check treats a call as an unknown, the same unknown for + * equal calls, so `0 + len(ys)` is `len(ys)`. */ +let rec arithmetic = (e: Exp.t): bool => + switch (Exp.term_of(e)) { + | Atom(Int(_)) + | Var(_) + | Ap(_) => true + | Parens(e) + | UnOp(Int(Minus), e) => arithmetic(e) + | BinOp(Int(Plus | Minus | Times | Divide | Power), a, b) => + arithmetic(a) && arithmetic(b) + | _ => false + }; + +/* A goal prepared for proposing steps on: as written, and without + * ascriptions, as it is compared. */ +module Prepared = { + type t = { + written: Exp.t, + compared: Exp.t, + }; + + let mk = (written: Exp.t): t => { + written, + compared: comparable(written), + }; + + /* The parts of `root` a step may act on, nearest it first, each as it + * is compared. */ + let parts = (p: t, root: Exp.t): list((Exp.t, Exp.t)) => { + let rec breadth_first = (found, n, queue) => + switch (queue) { + | [] => List.rev(found) + | _ when n >= max_parts => List.rev(found) + | [e, ...rest] => + breadth_first([e, ...found], n + 1, rest @ Occurrence.children(e)) + }; + breadth_first([], 0, [root]) + |> List.filter_map(~f=node => + Exp.find_by_id(Exp.rep_id(node), p.compared) + |> Option.map(~f=compared => (node, compared)) + ); + }; + + /* `step` at `node`: through a focus, unless `node` is the whole goal. */ + let at = (p: t, node: Exp.t, step: TermBase.Proof.term): option(Proof.t) => + Id.equal(Exp.rep_id(node), Exp.rep_id(p.written)) + ? Some(Proof.fresh(step)) + : Picker.EvalSteps.checker_idx(p.written, node) + |> Option.map(~f=index => + Proof.fresh( + Picker.Terms.focus(~selector=node, ~index, Proof.fresh(step)), + ) + ); +}; + +/* The uses of the scope's facts, theorems and axioms at `parts`, or of + * the one named `only`: each as the part, and the step rewriting it, + * kept if `keep` takes the part and what the rule rewrites it to. */ +let rule_uses = + ( + ~only: option(string)=None, + ~keep: (Exp.t, Exp.t) => bool, + goal: Picker.Goal.t, + p: Prepared.t, + parts: list((Exp.t, Exp.t)), + ) + : list((Exp.t, Proof.t)) => { + let statics = ProofStatics.of_info_map(Picker.Goal.info_map(goal)); + let (scope, axioms) = Picker.scope_and_axioms(goal.ctx); + scope + @ axioms + |> List.filter(~f=(entry: ProofCtx.entry) => + !entry.is_captured + && !entry.is_shadowed + && !Picker.Goal.cites_refuted(goal, entry.name) + && !String.equal(entry.name, "refl") + && Option.value_map(only, ~default=true, ~f=String.equal(entry.name)) + ) + |> List.concat_map(~f=(entry: ProofCtx.entry) => { + let rule = + ProofRule.BoolReading.apply(~statics=Some(statics), entry.rule); + /* A side that is just one of the rule's variables matches every + * part, as `rewrite <- and_true` rewrites any `a` to `a && true`. + * Such a step only wraps the goal, so it isn't proposed. */ + let rec is_variable = (side: Exp.t) => + switch (Exp.term_of(side)) { + | Parens(inner) + | Asc(inner, _) => is_variable(inner) + | Var(x) => + List.exists( + ~f= + (binding: Ctx.entry) => + switch (binding) { + | VarEntry({name, _}) => String.equal(name, x) + | ConstructorEntry(_) + | TVarEntry(_) + | LivelitEntry(_) + | TheoremEntry(_) => false + }, + rule.bindings, + ) + | _ => false + }; + let (forward, backward) = + switch (rule.conclusion) { + | Equality(lhs, rhs) => ( + is_variable(lhs) ? None : Some(lhs), + is_variable(rhs) ? None : Some(rhs), + ) + | BoolFact(p) => (Some(p), None) + | Other(_) => (None, None) + }; + /* A part whose head can't match is passed over before matching. */ + let applies = (side, part: Exp.t) => + switch (side) { + | Some(side) => + Exp.cls_of_term(Exp.term_of(unwrap(side))) + == Exp.cls_of_term(Exp.term_of(unwrap(part))) + | None => false + }; + /* Forward first, as a rule is read. */ + let uses = (side, direction) => + List.filter_map( + ~f= + ((node, compared)) => + applies(side, compared) + ? { + let (l, r) = + ProofRule.Rewrite.apply( + ~statics, + ~env=Picker.Goal.env(goal), + rule, + compared, + ); + switch (direction == Direction.Right ? r : l) { + | Some(result) when keep(node, result) => + Prepared.at( + p, + node, + Picker.Terms.axiom_step( + ~direction, + ~equality=entry.name, + ), + ) + |> Option.map(~f=step => (node, step)) + | Some(_) + | None => None + }; + } + : None, + parts, + ); + uses(forward, Right) @ uses(backward, Left); + }); +}; + +/* The steps to try from `from`, acting inside `part`, a part of it whose + * typed replacement is `wanted_part`. */ +let candidates = + ( + ~algebra: (Exp.t, Exp.t) => bool, + goal: Picker.Goal.t, + ~wanted: Exp.t, + from: node, + (part: Exp.t, wanted_part: Exp.t), + ) + : list((move, Proof.t)) => { + let env = Picker.Goal.env(goal); + let statics = ProofStatics.of_info_map(Picker.Goal.info_map(goal)); + let p = Prepared.mk(from.goal); + let within = Prepared.parts(p, part); + let part_compared = + switch (within) { + | [(_, compared), ..._] => compared + | [] => comparable(part) + }; + /* Whether rewriting `node` to `result` shrinks the part that differs + * from the typed goal. Only the path down to `node` is rebuilt. */ + let shrinks = (node: Exp.t, result: Exp.t) => { + let path = + Picker.self_and_ancestors(Exp.rep_id(node), from.goal) + |> Option.value(~default=[]) + |> List.map(~f=Exp.rep_id); + let rewritten = + Exp.map_term( + ~f_exp= + (cont, e) => + switch (Exp.rep_id(e)) { + | id when Id.equal(id, Exp.rep_id(node)) => result + | id when List.mem(path, id, ~equal=Id.equal) => cont(e) + | _ => e + }, + p.compared, + ); + differs(rewritten, wanted) < from.differs; + }; + let at = Prepared.at(p); + let evals = + Picker.EvalSteps.offered(~settings=goal.settings, ~env, from.goal) + |> List.filter_map(~f=({source, _}: Picker.EvalSteps.offer) => + Exp.find_by_id(source, part) + |> Option.bind(_, ~f=node => at(node, EvalStep)) + ); + let refls = + MatchExp.find_refls(~statics, ~defs=env, part_compared) + |> List.filter_map(~f=e => Exp.find_by_id(Exp.rep_id(e), part)) + |> List.filter_map(~f=node => + at( + node, + Picker.Terms.axiom_step(~direction=Right, ~equality="refl"), + ) + ); + let rec has_variable = (e: Exp.t) => + switch (Exp.term_of(e)) { + | Var(_) => true + | _ => List.exists(~f=has_variable, Occurrence.children(e)) + }; + let algebraic = + arithmetic(part) + && has_variable(part) + && arithmetic(wanted_part) + && algebra(part_compared, wanted_part) + ? Option.to_list( + at(part, Picker.Terms.algebrite_step(~replacement=wanted_part)), + ) + : []; + let rules = rule_uses(~keep=shrinks, goal, p, within) |> List.map(~f=snd); + List.map(~f=step => (Eval, step), evals) + @ List.map(~f=step => (Rule, step), refls @ algebraic @ rules); +}; + +/* Searches on until `continue_` says to stop, the search ends, or it + * reaches its bounds. `algebra` says whether two arithmetic expressions + * are equal. */ +let run = + ( + ~continue_: unit => bool, + ~algebra: (Exp.t, Exp.t) => bool, + goal: Picker.Goal.t, + search: t, + ) + : t => { + let rec loop = (t: t) => + switch (t.status, t.expanding, t.frontier) { + | (Found(_) | NotFound, _, _) => t + | (Searching, _, _) when !continue_() => t + | (Searching, _, _) when t.checks >= max_checks => { + ...t, + status: NotFound, + } + | (Searching, Some((node, [(move, step), ...rest])), _) => + let t = { + ...t, + expanding: Some((node, rest)), + checks: t.checks + 1, + }; + let reached = + Picker.outgoing(goal, node.goal, step) + |> Option.map(~f=e => (e, comparable(e))); + let steps = node.steps @ [step]; + switch (reached) { + | Some((e, compared)) when !List.exists(~f=same(compared), t.seen) => + let differs = + reaches(goal, compared, t.wanted) + ? 0 : differs(compared, t.wanted); + switch (differs, move) { + | (0, _) => + loop({ + ...t, + status: Found(steps), + }) + | (_, Rule) when differs >= node.differs => loop(t) + | (_, Eval | Rule) => + loop({ + ...t, + seen: [compared, ...t.seen], + next: [ + { + goal: e, + steps, + differs, + }, + ...t.next, + ], + }) + }; + | Some(_) + | None => loop(t) + }; + | (Searching, Some((_, [])) | None, [node, ...rest]) => + /* The differing part is found in the goal as compared, which keeps + * the ids of all but the ascriptions it drops. */ + let compared = comparable(node.goal); + let written = (part: Exp.t) => + Picker.self_and_ancestors(Exp.rep_id(part), compared) + |> Option.value(~default=[]) + |> List.find_map(~f=e => Exp.find_by_id(Exp.rep_id(e), node.goal)) + |> Option.value(~default=node.goal); + let steps = + List.length(node.steps) >= t.depth + ? [] + : differing(compared, t.wanted) + |> Option.map(~f=((part, wanted)) => (written(part), wanted)) + |> Option.value_map( + ~default=[], + ~f=candidates(~algebra, goal, ~wanted=t.wanted, node), + ); + loop({ + ...t, + expanding: Some((node, steps)), + frontier: rest, + }); + | (Searching, Some((_, [])) | None, []) => + switch (t.next) { + | [] => { + ...t, + status: NotFound, + } + | next => + loop({ + ...t, + expanding: None, + frontier: List.rev(next), + next: [], + }) + } + }; + loop(search); +}; + +/* What the box lists under itself: the goal each use of a rule would + * give. With a rule named, every use of that rule; otherwise every use of + * any rule. With part of the goal selected, only the uses inside it. Run + * in slices, as the search is. */ +module Suggestions = { + [@deriving (show({with_path: false}), sexp, yojson)] + type suggestion = { + step: Proof.t, + /* The part of the goal it acts on. */ + part: Exp.t, + /* The goal it gives. */ + result: Exp.t, + }; + + [@deriving (show({with_path: false}), sexp, yojson)] + type t = { + rule: option(string), + /* The selected part, by its id in the written goal. */ + at: option(Id.t), + /* The uses not yet checked, None until they are listed. */ + pending: option(list((Exp.t, Proof.t))), + found: list(suggestion), + }; + + let start = (~rule: option(string), ~at: option(Id.t)): t => { + rule, + at, + pending: None, + found: [], + }; + + let is_done = (t: t): bool => t.pending == Some([]); + + let run = (~continue_: unit => bool, goal: Picker.Goal.t, t: t): t => { + let rec loop = (t: t) => + switch (t.pending) { + | Some([]) => t + | _ when !continue_() => t + | None => + let p = Prepared.mk(goal.written); + loop({ + ...t, + pending: + Some( + rule_uses( + ~only=t.rule, + ~keep=(_, _) => true, + goal, + p, + Prepared.parts( + p, + Option.bind(t.at, ~f=id => Exp.find_by_id(id, goal.written)) + |> Option.value(~default=goal.written), + ), + ), + ), + }); + | Some([(part, step), ...rest]) => + let found = + switch (Picker.outgoing(goal, goal.written, step)) { + | Some(result) => + t.found + @ [ + { + step, + part, + result, + }, + ] + | None => t.found + }; + loop({ + ...t, + pending: Some(rest), + found, + }); + }; + loop(t); + }; +}; + +/* The rules the box knows by name: the scope's facts and theorems, then + * the builtin axioms. */ +let names = + (goal: Picker.Goal.t) + : list( + ( + string, + [ + | `Scope + | `Axiom + ], + ), + ) => { + let (scope, axioms) = Picker.scope_and_axioms(goal.ctx); + let named = (kind, entries) => + entries + |> List.filter(~f=(entry: ProofCtx.entry) => + !entry.is_captured + && !entry.is_shadowed + && !Picker.Goal.cites_refuted(goal, entry.name) + ) + |> List.map(~f=(entry: ProofCtx.entry) => (entry.name, kind)); + named(`Scope, scope) @ named(`Axiom, axioms); +}; + +/* What the box lists under itself. Typing the start of a name lists the + * names it completes to; a name in full, or any other text, lists the + * rules' uses. */ +[@deriving (show({with_path: false}), sexp, yojson)] +type item = + | Complete(string) + | Use(Suggestions.suggestion); + +let items = + ( + goal: Picker.Goal.t, + ~typed_name: option(string), + suggestions: option(Suggestions.t), + ) + : list(item) => { + let completions = + switch (typed_name) { + | Some(start) => + names(goal) + |> List.map(~f=fst) + |> List.filter(~f=name => + !String.equal(name, start) + && String.length(name) > String.length(start) + && String.equal( + String.sub(name, ~pos=0, ~len=String.length(start)), + start, + ) + ) + |> ListUtil.dedup_f(String.equal) + | None => [] + }; + switch (completions, suggestions) { + | ([_, ..._], _) => List.map(~f=name => Complete(name), completions) + | ([], Some(s)) => List.map(~f=use => Use(use), s.found) + | ([], None) => [] + }; +}; + +/* `steps`, taken one after another from `goal`, with each focus's + * selector generalized as the stepper's own picks are (`Picker.target`): + * as much of it replaced by `$e` as still selects the same part of the + * goal the focus starts from. */ +let generalized = (goal: Picker.Goal.t, steps: list(Proof.t)): list(Proof.t) => { + let statics = ProofStatics.of_info_map(Picker.Goal.info_map(goal)); + let env = Picker.Goal.env(goal); + let generalize = (from: Exp.t, step: Proof.t): Proof.t => + switch (step.term) { + | Focus({ordinal, selector, body}) => + let index = + ( + ordinal + |> Option.map(~f=Annotated.term_of) + |> Option.value(~default=1) + ) + - 1; + switch ( + Occurrence.nth_env_target(~statics, ~env, selector, index, from) + ) { + | Some(part) => + let (selector, index) = + Occurrence.generalize( + ~statics, + ~env, + ~index, + selector, + Exp.rep_id(part), + from, + ); + Proof.fresh(Picker.Terms.focus(~selector, ~index, body)); + | None => step + }; + | EmptyHole + | Invalid(_) + | MultiHole(_) + | Seq(_) + | Parens(_) + | EvalStep + | AxiomStep(_) + | AlgebriteStep(_) + | Forall(_) + | Funext(_) + | Assume(_) + | Have(_) + | Generalize(_) + | Revert(_) + | Alias(_) + | Cases(_) + | Induction(_) => step + }; + let (_, written) = + List.fold_left( + ~f= + ((from, written), step) => { + let step = + Option.value_map(from, ~default=step, ~f=from => + generalize(from, step) + ); + let next = + Option.bind(from, ~f=from => Picker.outgoing(goal, from, step)); + (next, written @ [step]); + }, + ~init=(Some(goal.written), []), + steps, + ); + written; +}; + +/* Writing at a hole with a step after it, as in `?; from 1 + 4 do step + * end`. A hole passes its goal through, so that step was written against + * the hole's goal, and steps written in the hole change the goal it acts + * on. The steps are written in place of the hole when the step after + * still checks once they are taken. Otherwise the search looks for steps + * back to the hole's goal: found, they are written too; not found, the + * hole stays after the written steps, marking the gap still to bridge. */ +module Bridge = { + /* The step after `hole` in its chain in `proof`. */ + let step_after = (proof: Proof.t, hole: Proof.t): option(Proof.t) => { + let rec chain = (p: Proof.t): list(Proof.t) => + switch (StepperRows.split(p)) { + | (head, Some(rest)) => [head, ...chain(rest)] + | (head, None) => [head] + }; + let found = ref(None); + let _: Proof.t = + Proof.map_term( + ~f_proof= + (continue, p) => { + switch (p.term, found^) { + | (Seq(_), None) => + let steps = chain(p); + switch ( + List.findi(steps, ~f=(_, s) => + Id.equal(Proof.rep_id(s), Proof.rep_id(hole)) + ) + |> Option.map(~f=fst) + ) { + | Some(i) => found := List.nth(steps, i + 1) + | None => () + }; + | _ => () + }; + continue(p); + }, + proof, + ); + found^; + }; + + /* Bounds the search a write runs before the write lands. */ + let max_checks = 40; + + let rec is_rewrite = (step: Proof.t) => + switch (step.term) { + | EvalStep + | AxiomStep(_) + | AlgebriteStep(_) => true + | Focus({body, _}) + | Parens(body) => is_rewrite(StepperRows.unparen(body)) + | EmptyHole + | Invalid(_) + | MultiHole(_) + | Seq(_) + | Forall(_) + | Funext(_) + | Assume(_) + | Have(_) + | Generalize(_) + | Revert(_) + | Alias(_) + | Cases(_) + | Induction(_) => false + }; + + /* What writing `steps` at `row`, whose goal is `goal`, writes: the steps + * alone, unless `row` is a hole with a step after it in `proof`. */ + let steps = + ( + ~algebra: (Exp.t, Exp.t) => bool, + ~proof: Proof.t, + goal: Picker.Goal.t, + row: StepperRows.t, + steps: list(Proof.t), + ) + : list(Proof.t) => { + let seq = steps => + switch (List.rev(steps)) { + | [] => None + | [last, ...earlier] => + Some( + List.fold_left( + ~f=(rest, step) => Proof.fresh(Seq(step, rest)), + ~init=last, + earlier, + ), + ) + }; + let after = + row.kind == Hole && List.for_all(~f=is_rewrite, steps) + ? step_after(proof, row.step) : None; + switch (after, seq(steps)) { + | (Some(next), Some(written)) => + let next_checks = + Picker.check(goal, goal.written, Proof.fresh(Seq(written, next))) + != None; + switch (Picker.outgoing(goal, goal.written, written)) { + | _ when next_checks => steps + | Some(reached) => + let from = + Picker.Goal.mk(~settings=goal.settings, ~ctx=goal.ctx, reached); + let checks = ref(0); + let search = + run( + ~continue_= + () => { + incr(checks); + checks^ <= max_checks; + }, + ~algebra, + from, + start(from, ~wanted=goal.written), + ); + switch (search.status) { + | Found(more) => steps @ more + | Searching + | NotFound => steps @ [Proof.fresh(EmptyHole)] + }; + | None => steps @ [Proof.fresh(EmptyHole)] + }; + | (None, _) + | (_, None) => steps + }; + }; +}; diff --git a/src/web/app/editors/stepper/StepperBase.re b/src/web/app/editors/stepper/StepperBase.re deleted file mode 100644 index d32e1eecd6..0000000000 --- a/src/web/app/editors/stepper/StepperBase.re +++ /dev/null @@ -1,1134 +0,0 @@ -open Util; -open Language; -open StepInterface; -open Calc.Syntax; -open OptUtil.Syntax; -open Poly; - -/* Note[Matt]: I've defined the types outside the modules here, - this is in case we ever want to parameterize the types in - the future, it'll be easier to please the OCaml compiler. */ - -[@deriving (show({with_path: false}), sexp, yojson)] -type step_kind_model = - | SingleStep(SingleStep.model'(step_model)) - | InductionStep(InductionStep.model'(step_model)) - | ForallStep(ForallStep.model'(step_model)) - | MissingStep(MissingStep.Model.t) - | AxiomStep(AxiomStep.model'(step_model)) - | AlgebriteStep(AlgebriteStep.model'(step_model)) - -and step_model = { - // Calculated - expr: Calc.saved(Exp.t), - editor: Calc.saved(CodeSelectable.Model.t), // Also Updated. - // Updated - step_kind: step_kind_model, - next_step: option(step_model), - // Calculated - hidden: Calc.saved(bool), - proof_validity: Calc.saved(option(bool)), - editor_info_map: Calc.saved(Statics.Map.t), -}; - -let init_step = { - expr: Calc.Pending, - editor: Calc.Pending, - step_kind: MissingStep(MissingStep.Model.init), - next_step: None, - hidden: Calc.Pending, - proof_validity: Calc.Pending, - editor_info_map: Calc.Pending, -}; - -[@deriving (show({with_path: false}), sexp, yojson)] -type persistent_step_kind = - | SingleStep(SingleStep.persistent'(persistent_step)) - | InductionStep(InductionStep.persistent'(persistent_step)) - | ForallStep(ForallStep.persistent'(persistent_step)) - | MissingStep(MissingStep.Model.persistent) - | AxiomStep(AxiomStep.persistent'(persistent_step)) - | AlgebriteStep(AlgebriteStep.persistent'(persistent_step)) - -and persistent_step = { - step_kind: persistent_step_kind, - next_step: option(persistent_step), -}; - -[@deriving (show({with_path: false}), sexp, yojson)] -type step_kind_action = - | SingleStep(SingleStep.action'(step_action)) - | InductionStep(InductionStep.action'(step_action)) - | ForallStep(ForallStep.action'(step_action)) - | MissingStep(MissingStep.Update.t) - | AxiomStep(AxiomStep.action'(step_action)) - | AlgebriteStep(AlgebriteStep.action'(step_action)) - -and step_action = - | StepKindAction(step_kind_action) - | EditorAction(CodeSelectable.Update.t) - | NextStep(step_action) - | RemoveStep - | StepForward(int) - | AddInduction(option(Exp.t)) - | AddForall - | AddAxiomStep(string, int, Exp.t, Direction.t, string) - | AddAlgebriteStep(int, Exp.t, Exp.t); - -[@deriving (show({with_path: false}), sexp, yojson)] -type step_kind_focus = - | SingleStep(SingleStep.focus'(step_focus)) - | InductionStep(InductionStep.focus'(step_focus)) - | ForallStep(ForallStep.focus'(step_focus)) - | MissingStep(MissingStep.Selection.t) - | AxiomStep(AxiomStep.focus'(step_focus)) - | AlgebriteStep(AlgebriteStep.focus'(step_focus)) - -and step_focus = - | StepKindFocus(step_kind_focus) - | Here(CodeSelectable.Selection.t) - | Next(step_focus); - -module rec StepKind: { - include - STEP with - type model = step_kind_model and - type persistent = persistent_step_kind and - type action = step_kind_action and - type focus = step_kind_focus; - - let is_missing_step: step_kind_model => bool; -} = { - /* The StepKind code here is almost all dispatch to the - individual step modules. */ - - module SingleStep = SingleStep.F(Stepper); - module InductionStep = InductionStep.F(Stepper); - module ForallStep = ForallStep.F(Stepper); - module MissingStep = MissingStep; // This could be functorized too. - module AxiomStep = AxiomStep.F(Stepper); - module AlgebriteStep = AlgebriteStep.F(Stepper); - - [@deriving (show({with_path: false}), sexp, yojson)] - type model = step_kind_model; - [@deriving (show({with_path: false}), sexp, yojson)] - type persistent = persistent_step_kind; - [@deriving (show({with_path: false}), sexp, yojson)] - type action = step_kind_action; - [@deriving (show({with_path: false}), sexp, yojson)] - type focus = step_kind_focus; - - let persist = (model: model): persistent => { - switch (model) { - | SingleStep(m) => SingleStep(SingleStep.persist(m)) - | InductionStep(m) => InductionStep(InductionStep.persist(m)) - | ForallStep(m) => ForallStep(ForallStep.persist(m)) - | MissingStep(m) => MissingStep(MissingStep.Model.persist(m)) - | AxiomStep(m) => AxiomStep(AxiomStep.persist(m)) - | AlgebriteStep(m) => AlgebriteStep(AlgebriteStep.persist(m)) - }; - }; - - let unpersist = (p: persistent): model => { - switch (p) { - | SingleStep(m) => SingleStep(SingleStep.unpersist(m)) - | InductionStep(m) => InductionStep(InductionStep.unpersist(m)) - | ForallStep(m) => ForallStep(ForallStep.unpersist(m)) - | MissingStep(m) => MissingStep(MissingStep.Model.unpersist(m)) - | AxiomStep(m) => AxiomStep(AxiomStep.unpersist(m)) - | AlgebriteStep(m) => AlgebriteStep(AlgebriteStep.unpersist(m)) - }; - }; - - let is_missing_step = (sk: step_kind_model): bool => { - switch (sk) { - | MissingStep(_) => true - | _ => false - }; - }; - - let update = (~settings, action: action, model: model) => { - Updated.( - switch (action, model) { - | (SingleStep(a), SingleStep(m)) => - let* s = SingleStep.update(~settings, a, m); - (SingleStep(s): model); - | (InductionStep(a), InductionStep(m)) => - let* s = InductionStep.update(~settings, a, m); - (InductionStep(s): model); - | (ForallStep(a), ForallStep(m)) => - let* s = ForallStep.update(~settings, a, m); - (ForallStep(s): model); - | (MissingStep(a), MissingStep(m)) => - let* s = MissingStep.Update.update(~settings, a, m); - (MissingStep(s): model); - | (AxiomStep(a), AxiomStep(m)) => - let* s = AxiomStep.update(~settings, a, m); - (AxiomStep(s): model); - | (AlgebriteStep(a), AlgebriteStep(m)) => - let* s = AlgebriteStep.update(~settings, a, m); - (AlgebriteStep(s): model); - | ( - SingleStep(_) | InductionStep(_) | ForallStep(_) | MissingStep(_) | - AxiomStep(_) | - AlgebriteStep(_), - _, - ) => - model |> Updated.raise_invalid_action - } - ); - }; - - let rec calculate = - ( - ~settings: Calc.t(CoreSettings.t), - ~hidden: Calc.saved(bool), - ~exp: Calc.t(Exp.t), - ~ctx: Calc.t(SemanticCtx.t), - ~editor: Calc.t(CodeSelectable.Model.t), - ~info_map: Calc.t(Statics.Map.t), - ~ana, - model: model, - ) => - switch (model) { - | SingleStep(m) => - let+ (m, h, e, v) = - SingleStep.calculate( - ~settings, - ~hidden, - ~exp, - ~ctx, - ~editor, - ~info_map, - ~ana, - m, - ); - (SingleStep(m): model, h, e, v); - | InductionStep(m) => - let+ (m, h, e, v) = - InductionStep.calculate( - ~settings, - ~hidden, - ~exp, - ~ctx, - ~editor, - ~info_map, - ~ana, - m, - ); - (InductionStep(m): model, h, e, v); - | ForallStep(m) => - let+ (m, h, e, v) = - ForallStep.calculate( - ~settings, - ~hidden, - ~exp, - ~ctx, - ~editor, - ~info_map, - ~ana, - m, - ); - (ForallStep(m): model, h, e, v); - | MissingStep(missing_step) => - let next_steps = - missing_step.next_steps - |> { - let.calc settings = settings - and.calc exp = exp - and.calc ctx = ctx; - EvaluatorStep.get_status(~settings, exp, SemanticCtx.get_env(ctx)); - }; - let next_step_to_take = - Calc.Calculated(None) - |> { - let.calc next_steps: EvaluatorStep.status = next_steps; - switch (next_steps) { - | AutoStep(next) => Some(next) - | AvailableSteps(_) => None - }; - } - |> Calc.get_value; - switch (next_step_to_take) { - | Some(evalobj) => - calculate( - ~settings, - ~info_map, - ~exp=exp |> Calc.make_new, - ~ctx=ctx |> Calc.make_new, - SingleStep({ - persistent_evalobj: evalobj |> EvaluatorStep.persist, - evalobj: Calc.Pending, - next_exp: Calc.Pending, - }): model, - ~hidden, - ~editor, - ~ana, - ) - | None => - Some(( - MissingStep( - MissingStep.Update.calculate( - ~settings=settings |> Calc.get_value, - exp, - info_map, - ctx, - next_steps, - missing_step, - editor, - ), - ), - Calc.set(false, hidden), - None, - Calc.NewValue( - // TODO: Incremental validity check - DHExp.fast_equal( - exp |> Calc.get_value, - Exp.temp(Atom(Bool(true))), - ) - ? Some(true) - : DHExp.fast_equal( - exp |> Calc.get_value, - Exp.temp(Atom(Bool(false))), - ) - ? Some(false) : None, - ), - )) - }; - | AxiomStep(m) => - let+ (m, h, e, v) = - AxiomStep.calculate( - ~settings, - ~hidden, - ~exp, - ~ctx, - ~editor, - ~info_map, - ~ana, - m, - ); - (AxiomStep(m): model, h, e, v); - | AlgebriteStep(m) => - let+ (m, h, e, v) = - AlgebriteStep.calculate( - ~settings, - ~hidden, - ~exp, - ~ctx, - ~editor, - ~info_map, - ~ana, - m, - ); - (AlgebriteStep(m): model, h, e, v); - }; - - let get_cursor_info = (~inject, ~focus: focus, model: model) => - Cursor.( - switch (focus, model) { - | (SingleStep(focus), SingleStep(model)) => - let+ focus_info = - SingleStep.get_cursor_info( - ~inject=x => inject(SingleStep(x): action), - ~focus, - model, - ); - (SingleStep(focus_info): action); - | (InductionStep(focus), InductionStep(model)) => - let+ focus_info = - InductionStep.get_cursor_info( - ~inject=x => inject(InductionStep(x): action), - ~focus, - model, - ); - (InductionStep(focus_info): action); - | (ForallStep(focus), ForallStep(model)) => - let+ focus_info = - ForallStep.get_cursor_info( - ~inject=x => inject(ForallStep(x): action), - ~focus, - model, - ); - (ForallStep(focus_info): action); - | (MissingStep(selection), MissingStep(model)) => - let+ focus_info = - MissingStep.Selection.get_cursor_info( - ~inject=x => inject(MissingStep(x): action), - ~selection, - model, - ); - (MissingStep(focus_info): action); - | (AxiomStep(focus), AxiomStep(model)) => - let+ focus_info = - AxiomStep.get_cursor_info( - ~inject=x => inject(AxiomStep(x): action), - ~focus, - model, - ); - (AxiomStep(focus_info): action); - | (AlgebriteStep(focus), AlgebriteStep(model)) => - let+ focus_info = - AlgebriteStep.get_cursor_info( - ~inject=x => inject(AlgebriteStep(x): action), - ~focus, - model, - ); - (AlgebriteStep(focus_info): action); - | ( - SingleStep(_) | InductionStep(_) | ForallStep(_) | MissingStep(_) | - AxiomStep(_) | - AlgebriteStep(_), - _, - ) => Cursor.empty - } - ); - - let view_content = - ( - ~globals: Globals.t, - ~focus: option(focus), - ~inject: action => Ui_effect.t(unit), - ~take_focus: focus => Ui_effect.t(unit), - ~hide_stepper: Ui_effect.t(unit), - ~undo: option(Ui_effect.t(unit)), - ~is_toplevel: bool, - model: model, - ) => { - let f = - switch (model) { - | SingleStep(m) => - SingleStep.view_content( - ~focus= - switch (focus) { - | Some(SingleStep(f)) => Some(f) - | _ => None - }, - ~inject=x => inject(SingleStep(x)), - ~take_focus=x => take_focus(SingleStep(x)), - m, - ) - | InductionStep(m) => - InductionStep.view_content( - ~focus= - switch (focus) { - | Some(InductionStep(f)) => Some(f) - | _ => None - }, - ~inject=x => inject(InductionStep(x)), - ~take_focus=x => take_focus(InductionStep(x)), - m, - ) - | ForallStep(m) => - ForallStep.view_content( - ~focus= - switch (focus) { - | Some(ForallStep(f)) => Some(f) - | _ => None - }, - ~inject=x => inject(ForallStep(x)), - ~take_focus=x => take_focus(ForallStep(x)), - m, - ) - | MissingStep(_) => ( - (~globals as _, ~hide_stepper as _, ~undo as _, ~is_toplevel as _) => - [] - ) - | AxiomStep(m) => - AxiomStep.view_content( - ~focus= - switch (focus) { - | Some(AxiomStep(f)) => Some(f) - | _ => None - }, - ~inject=x => inject(AxiomStep(x)), - ~take_focus=x => take_focus(AxiomStep(x)), - m, - ) - | AlgebriteStep(m) => - AlgebriteStep.view_content( - ~focus= - switch (focus) { - | Some(AlgebriteStep(f)) => Some(f) - | _ => None - }, - ~inject=x => inject(AlgebriteStep(x)), - ~take_focus=x => take_focus(AlgebriteStep(x)), - m, - ) - }; - f(~globals, ~hide_stepper, ~undo, ~is_toplevel); - }; - - let view_justification = - ( - ~globals: Globals.t, - ~focus: option(focus), - ~inject: action => Ui_effect.t(unit), - ~take_focus: focus => Ui_effect.t(unit), - ~hide_stepper: Ui_effect.t(unit), - ~undo: option(Ui_effect.t(unit)), - ~is_toplevel: bool, - model: model, - ) => - switch (model) { - | SingleStep(m) => - SingleStep.view_justification( - ~globals, - ~focus= - switch (focus) { - | Some(SingleStep(f)) => Some(f) - | _ => None - }, - ~inject=x => inject(SingleStep(x)), - ~take_focus=x => take_focus(SingleStep(x)), - ~hide_stepper, - ~undo, - ~is_toplevel, - m, - ) - | InductionStep(m) => - InductionStep.view_justification( - ~globals, - ~focus= - switch (focus) { - | Some(InductionStep(f)) => Some(f) - | Some(_) - | None => None - }, - ~inject=x => inject(InductionStep(x)), - ~take_focus=x => take_focus(InductionStep(x)), - ~hide_stepper, - ~undo, - ~is_toplevel, - m, - ) - | ForallStep(m) => - ForallStep.view_justification( - ~globals, - ~focus= - switch (focus) { - | Some(ForallStep(f)) => Some(f) - | Some(_) - | None => None - }, - ~inject=x => inject(ForallStep(x)), - ~take_focus=x => take_focus(ForallStep(x)), - ~hide_stepper, - ~undo, - ~is_toplevel, - m, - ) - | MissingStep(m) => - MissingStep.View.view_justification( - ~globals, - ~is_toplevel, - ~hide_stepper, - ~undo, - m, - ) - | AxiomStep(m) => - AxiomStep.view_justification( - ~globals, - ~focus= - switch (focus) { - | Some(AxiomStep(f)) => Some(f) - | Some(_) - | None => None - }, - ~inject=x => inject(AxiomStep(x)), - ~take_focus=x => take_focus(AxiomStep(x)), - ~hide_stepper, - ~undo, - ~is_toplevel, - m, - ) - | AlgebriteStep(m) => - AlgebriteStep.view_justification( - ~globals, - ~focus= - switch (focus) { - | Some(AlgebriteStep(f)) => Some(f) - | Some(_) - | None => None - }, - ~inject=x => inject(AlgebriteStep(x)), - ~take_focus=x => take_focus(AlgebriteStep(x)), - ~hide_stepper, - ~undo, - ~is_toplevel, - m, - ) - }; -} - -and Stepper: { - include - STEPPER with - type model = step_model and - type persistent = persistent_step and - type action = step_action and - type focus = step_focus; - let get_validity: step_model => option(bool); -} = { - [@deriving (show({with_path: false}), sexp, yojson)] - type model = step_model; - [@deriving (show({with_path: false}), sexp, yojson)] - type persistent = persistent_step; - [@deriving (show({with_path: false}), sexp, yojson)] - type action = step_action; - [@deriving (show({with_path: false}), sexp, yojson)] - type focus = step_focus; - - let init = { - expr: Calc.Pending, - editor: Calc.Pending, - step_kind: MissingStep(MissingStep.Model.init), - next_step: None, - hidden: Calc.Pending, - proof_validity: Calc.Pending, - editor_info_map: Calc.Pending, - }; - - let rec persist = (model: model): persistent => { - { - step_kind: StepKind.persist(model.step_kind), - next_step: model.next_step |> Option.map(~f=persist), - }; - }; - - let rec unpersist = (p: persistent): model => { - { - expr: Calc.Pending, - editor: Calc.Pending, - step_kind: StepKind.unpersist(p.step_kind), - next_step: p.next_step |> Option.map(~f=unpersist), - hidden: Calc.Pending, - proof_validity: Calc.Pending, - editor_info_map: Calc.Pending, - }; - }; - - let get_validity = (model: model) => - model.proof_validity - |> Calc.get_saved_exc( - ~print="get_validity called before calculate on stepper", - ); - - let rec update = - (~settings, action: step_action, model: step_model) - : Updated.t(step_model) => { - Updated.( - switch (action, model.step_kind, model.next_step) { - | (EditorAction(ea), _, _) => - switch (model.editor) { - | Calc.Pending => model |> raise_invalid_action - | Calc.Calculated(editor) => - let* new_editor = - CodeSelectable.Update.update(~settings, ea, editor); - { - ...model, - editor: Calc.Calculated(new_editor), - }; - } - | (NextStep(a), _, Some(ns)) => - let* new_next_step = update(~settings, a, ns); - { - ...model, - next_step: Some(new_next_step), - }; - | (NextStep(_), _, None) => model |> raise_invalid_action - | (RemoveStep, _, _) => - { - ...model, - step_kind: MissingStep(MissingStep.Model.init), - } - |> return - | (StepForward(idx), MissingStep(ms), _) => - let msns = - ms.next_steps - |> Calc.get_saved_exc(~print="StepForward") - |> ( - fun - | AutoStep(_) => [] - | AvailableSteps(msns) => msns - ); - switch (List.nth(msns, idx)) { - | Some(evalobj) => - { - ...model, - step_kind: - SingleStep({ - persistent_evalobj: evalobj |> EvaluatorStep.persist, - evalobj: Calc.Calculated(evalobj), - next_exp: Calc.Pending, - }), - } - |> return - | None => model |> raise_invalid_action - }; - | (StepForward(_), _, _) => model |> raise_invalid_action - | (AddInduction(exp), MissingStep(_), _) => - { - ...model, - step_kind: InductionStep(InductionStep.init(~exp?, ())), - } - |> return - | (AddInduction(_), _, _) => model |> raise_invalid_action - | (AddForall, MissingStep(_), _) => - { - ...model, - step_kind: ForallStep(ForallStep.init(init)), - } - |> return - | (AddForall, _, _) => model |> raise_invalid_action - | ( - AddAxiomStep(name, at_idx, at_exp, direction, equality), - MissingStep(_), - _, - ) => - { - ...model, - step_kind: - AxiomStep({ - name, - at_idx, - at_exp, - direction, - equality, - next_exp: Calc.Pending, - }), - } - |> return - | (AddAxiomStep(_, _, _, _, _), _, _) => model |> raise_invalid_action - | (AddAlgebriteStep(at_idx, at_exp, with_exp), MissingStep(_), _) => - { - ...model, - step_kind: - AlgebriteStep({ - at_idx, - at_exp, - with_exp, - next_exp: Calc.Pending, - }), - } - |> return - | (AddAlgebriteStep(_, _, _), _, _) => model |> raise_invalid_action - | (StepKindAction(sk_action), _, _) => - let* new_step_kind = - StepKind.update(~settings, sk_action, model.step_kind); - { - ...model, - step_kind: new_step_kind, - }; - } - ); - }; - - let rec calculate = - ( - ~settings: Calc.t(CoreSettings.t), - ~exp as expr: Calc.t(Exp.t), - ~ctx: Calc.t(SemanticCtx.t), - ~ana: Calc.t(Typ.t), - { - expr: _, - editor, - step_kind, - next_step, - hidden, - proof_validity, - editor_info_map: info_map, - }: step_model, - ) - : (step_model, Calc.t(Exp.t), Calc.t(option(bool))) => { - let editor = - editor - |> { - let.calc settings = settings - and.calc expr = expr - and.calc _ctx = ctx - and.calc _ana = ana; - expr |> CodeWithStatics.Model.mk_from_exp(~settings, ~root=Exp); - }; - let info_map = - info_map - |> { - let.calc editor: CodeSelectable.Model.t = editor; - editor.statics.info_map; - }; - let (step_kind, hidden, next_expr, inner_validity) = - StepKind.calculate( - ~settings, - ~ctx, - ~exp=expr, - ~hidden, - ~editor, - ~info_map, - ~ana, - step_kind, - ) - |> OptUtil.get(() => - MissingStep(MissingStep.Model.init) - |> StepKind.calculate( - ~settings, - ~ctx, - ~exp=expr, - ~hidden, - ~editor, - ~info_map, - ~ana, - ) - |> Option.value_exn - ); - let (next_step, last_expr, next_validity) = - switch (next_expr) { - | Some(next_expr) => - let next_step = Option.value(~default=init, next_step); - let (next_step, last_expr, next_validity) = - calculate(~settings, ~exp=next_expr, ~ctx, ~ana, next_step); - (Some(next_step), last_expr, next_validity); - | None => (None, expr, inner_validity) - }; - - let proof_validity = - proof_validity - |> { - let.calc next_validity = next_validity - and.calc inner_validity = inner_validity; - switch (next_validity, inner_validity) { - | (Some(true), Some(true)) => Some(true) - | (Some(false), Some(false)) => Some(false) - | _ => None - }; - }; - - /* re-analyze a step's editor only when it, or what it shows, changed: - every step re-analyzed on every pass made each click cost the whole - trace's statics, several times over */ - let is_edited = - Calc.is_new(editor) - || Calc.is_new(expr) - || Calc.is_new(settings) - || Calc.is_new(ctx) - || Calc.is_new(ana); - let editor = - CodeSelectable.Update.calculate( - ~is_dynamic_term=true, - ~settings=Calc.get_value(settings), - ~is_edited, - ~ctx=Calc.get_value(ctx) |> SemanticCtx.get_ctx, - ~dynamics=Dynamics.Map.empty, - ~ana=Calc.get_value(ana), - ~stitch=_ => Calc.get_value(expr), - Calc.get_value(editor), - ); - - ( - { - expr: expr |> Calc.save, - - editor: Calc.Calculated(editor), - step_kind, - next_step, - hidden: hidden |> Calc.save, - proof_validity: proof_validity |> Calc.save, - editor_info_map: info_map |> Calc.save, - }, - last_expr, - proof_validity, - ); - }; - - let rec get_cursor_info = - (~inject, ~focus: step_focus, model: step_model) - : Cursor.cursor(step_action) => { - Cursor.( - switch (focus, model.step_kind, model.next_step) { - | (StepKindFocus(sk), skm, _) => - let+ ci = - StepKind.get_cursor_info( - ~inject=x => inject(StepKindAction(x)), - ~focus=sk, - skm, - ); - StepKindAction(ci); - | (Here(a), _, _) => - let+ ci = - StepperEditor.Selection.get_cursor_info( - ~inject=x => inject(EditorAction(x)), - ~selection=a, - model.editor |> Calc.get_saved_exc(~print="Step editor selection"), - ); - EditorAction(ci); - | (Next(a), _, Some(next_step)) => - let+ ci = - get_cursor_info( - ~inject=x => inject(NextStep(x): action), - ~focus=a, - next_step, - ); - NextStep(ci); - | (Next(_), _, None) => Cursor.empty - } - ); - }; - - let rec view_step = - ( - ~globals: Globals.t, - ~take_focus: step_focus => Ui_effect.t(unit), - ~inject: step_action => Ui_effect.t(unit), - ~hide_stepper: Ui_effect.t(unit), - ~focus: option(step_focus), - ~is_toplevel: bool=false, - ~undo: option(Ui_effect.t(unit)), - model: step_model, - ) => { - let is_last_step = StepKind.is_missing_step(model.step_kind); - let is_skipped_step = model.hidden == Calc.Calculated(true); - let showing_skiped_steps = - globals.settings.core.evaluation.show_hidden_steps; - let showing_history = globals.settings.core.evaluation.stepper_history; - let this_step_shown = - is_last_step - || showing_history - && (!is_skipped_step || showing_skiped_steps); - let current_step = - if (!this_step_shown) { - []; - } else { - let taken_steps = - switch (model.step_kind) { - | SingleStep(m) => [ - m.evalobj - |> Calc.get_saved_exc(~print="SingleStep") - |> EvaluatorStep.get_step_id, - ] - | AxiomStep(m) => [m.at_exp |> Exp.rep_id] - | _ => [] - }; - let next_steps = - switch (model.step_kind) { - | MissingStep(m) => - m.next_steps - |> Calc.get_saved_exc(~print="next_steps") - |> ( - fun - | AutoStep(_) => [] - | AvailableSteps(steps) => steps - ) - |> List.map(~f=step => step |> EvaluatorStep.get_step_id) - | _ => [] - }; - let selected_exp = - switch (model.step_kind) { - | MissingStep(m) => - m.selected_exp |> Calc.get_saved_opt |> Option.join - | _ => None - }; - let refls = - switch (model.step_kind) { - | MissingStep(m) when globals.settings.core.evaluation.enable_proof => - m.refls - |> Calc.get_saved_exc(~print="refls") - |> List.map(~f=Exp.rep_id) - | _ => [] - }; - let editor = - StepperEditor.View.view( - ~globals, - ~signal= - fun - | MakeActive => take_focus(Here()) - | TakeStep(int) => inject(StepForward(int)) - | Refl(int) => { - let refl_exps = - switch (model.step_kind) { - | MissingStep(m) => - m.refls |> Calc.get_saved_exc(~print="refls") - | _ => [] - }; - let from_exp = List.nth_exn(refl_exps, int); - inject( - AddAxiomStep( - "reflexivity", - ProofHacks.exp_idx( - from_exp, - model.expr |> Calc.get_saved_exc(~print="expr"), - ), - from_exp, - Direction.Right, - "Reflexive(==)", - ), - ); - }, - ~inject=x => inject(EditorAction(x)), - ~selected= - switch (focus) { - | Some(Here(_)) => true - | _ => false - }, - ~selected_id=selected_exp |> Option.map(~f=Exp.rep_id), - ~overlays= - switch (model.step_kind) { - | MissingStep(m) - when globals.settings.core.evaluation.enable_proof => - MissingStep.View.view_overlay( - ~globals, - ~info_map= - model.editor_info_map - |> Calc.get_saved_exc(~print="info_map"), - ~inject=x => inject(StepKindAction(MissingStep(x))), - ~selected= - switch (focus) { - | Some(StepKindFocus(MissingStep(s))) => Some(s) - | _ => None - }, - ~signal= - fun - | HideStepper => hide_stepper - | MakeActive(s) => - take_focus(StepKindFocus(MissingStep(s))) - | AddForall => inject(AddForall) - | AddInduction(exp) => inject(AddInduction(exp)) - | AddAxiomStep(name, idx, e1, dir, eq) => - inject(AddAxiomStep(name, idx, e1, dir, eq)) - | AddAlgebriteStep(idx, e1, e2) => - inject(AddAlgebriteStep(idx, e1, e2)) - | TakeStep(i) => inject(StepForward(i)) - | Refl(i) => { - let refl_exps = - switch (model.step_kind) { - | MissingStep(m) => - m.refls |> Calc.get_saved_exc(~print="refls") - | _ => [] - }; - let from_exp = List.nth_exn(refl_exps, i); - inject( - AddAxiomStep( - "reflexivity", - ProofHacks.exp_idx( - from_exp, - model.expr |> Calc.get_saved_exc(~print="expr"), - ), - from_exp, - Direction.Right, - "Reflexive(==)", - ), - ); - }, - ~editor=model.editor |> Calc.get_saved_exc(~print="Editor"), - m, - ) - | _ => [] - }, - StepperEditor.Model.{ - editor: model.editor |> Calc.get_saved_exc(~print="Editor"), - taken_steps, - next_steps, - refls, - }, - ); - let justification = - StepKind.view_justification( - ~globals: Globals.t, - ~take_focus=f => take_focus(StepKindFocus(f)), - ~hide_stepper, - ~inject=a => inject(StepKindAction(a)), - ~is_toplevel, - ~focus= - switch (focus) { - | Some(StepKindFocus(sk)) => Some(sk) - | _ => None - }, - ~undo, - model.step_kind, - ); - let step_content = - StepKind.view_content( - ~globals, - ~take_focus=f => take_focus(StepKindFocus(f)), - ~hide_stepper, - ~inject=a => inject(StepKindAction(a)), - ~focus= - switch (focus) { - | Some(StepKindFocus(sk)) => Some(sk) - | _ => None - }, - ~is_toplevel, - ~undo, - model.step_kind, - ); - WebUtil.[ - Node.div( - ~attrs= - [Attr.class_("step-border")] - @ (is_skipped_step ? [Attr.class_("hidden")] : []), - [ - WebUtil.div_c( - "step-display", - [ - div_c("equiv", [Node.text("≡")]), - div_c("step-output", [editor]), - justification, - ], - ), - ] - @ step_content, - ), - ]; - }; - let next_step = - Option.map( - ~f= - view_step( - ~globals, - ~is_toplevel, - ~take_focus=f => take_focus(Next(f)), - ~hide_stepper, - ~inject=x => inject(NextStep(x)), - ~focus= - switch (focus) { - | Some(Next(s)) => Some(s) - | _ => None - }, - ~undo= - if (model.hidden |> Calc.get_saved_exc(~print="hidden")) { - undo; - } else { - Some(inject(RemoveStep)); - }, - ), - model.next_step, - ) - |> Option.value(~default=[]); - current_step @ next_step; - }; - - let view = - ( - ~globals: Globals.t, - ~take_focus: step_focus => Ui_effect.t(unit), - ~inject: step_action => Ui_effect.t(unit), - ~hide_stepper: Ui_effect.t(unit), - ~focus: option(step_focus), - ~is_toplevel: bool, - root_step, - ) => { - WebUtil.[ - Node.div( - ~attrs=[Attr.classes(["stepper", "cell-result"])], - view_step( - ~globals, - ~take_focus, - ~hide_stepper, - ~inject, - ~focus, - ~is_toplevel, - ~undo=None, - root_step, - ), - ), - ]; - }; -}; diff --git a/src/web/app/editors/stepper/StepperPicker.re b/src/web/app/editors/stepper/StepperPicker.re new file mode 100644 index 0000000000..96bd52f2a6 --- /dev/null +++ b/src/web/app/editors/stepper/StepperPicker.re @@ -0,0 +1,887 @@ +open Util; +open Language; +open Haz3lcore; +open Poly; + +/* What the write box offers and writes: the steps a row's goal can take, + * what Tab takes, the strategies, and the proof terms and patches they + * write. Everything here is a pure function of the row's goal, its scope + * and the selection, so it can be tested without the UI. */ + +// Proof Terms + +/* The proof terms the stepper writes. */ +module Terms = { + /* An expression sliced from a row's goal, made fit to write into the + * proof. Its tile ids already occur in the rendered theorem, so they + * are freshened (a duplicate id breaks `Highlight.of_tile`). It may + * hold closures the evaluator substituted in, which have no surface + * syntax, so their environments are inlined. */ + let embed_exp = (e: Exp.t): Exp.t => + e |> Substitution.in_exp(Environment.empty) |> Exp.replace_all_ids; + + let axiom_step = + (~direction: Direction.t, ~equality: string): TermBase.Proof.term => + AxiomStep({ + direction, + equality: Exp.fresh(Var(equality)), + instantiation: None, + }); + + let algebrite_step = (~replacement: Exp.t): TermBase.Proof.term => + AlgebriteStep(embed_exp(replacement)); + + /* `from do end`, selecting the match of `selector` + * with 0-based `index`. */ + let focus = + (~selector: Exp.t, ~index: int, step: Proof.t): TermBase.Proof.term => + Focus({ + ordinal: index == 0 ? None : Some(IdTagged.fresh(index + 1)), + selector: embed_exp(selector), + body: step, + }); + + /* The splits start with no cases: the user adds them in the split's + * row. */ + let cases = (~exp: Exp.t): TermBase.Proof.term => + Cases(embed_exp(exp), []); + + let induction = (~exp: Exp.t): TermBase.Proof.term => + Induction(embed_exp(exp), []); + + let forall = (): TermBase.Proof.term => + Forall(Pat.fresh(EmptyHole), Proof.fresh(EmptyHole)); + + /* The wrapping forms start with a hole for a body, so inserting one + * never discards proof text: the hole it replaces reappears inside the + * new scope. Because `;` prints flat, inserting one before a step + * reparses with that step and the rest of the chain inside the new + * scope, which is the intended reading. */ + let funext = (): TermBase.Proof.term => + Funext(Pat.fresh(EmptyHole), Proof.fresh(EmptyHole)); + + let assume = (~exp: Exp.t): TermBase.Proof.term => + Assume(embed_exp(exp), None, Proof.fresh(EmptyHole)); + + let revert = (~exp: Exp.t): TermBase.Proof.term => + Revert(embed_exp(exp), None, Proof.fresh(EmptyHole)); + + let generalize = (~exp: Exp.t): TermBase.Proof.term => + Generalize(embed_exp(exp), Proof.fresh(EmptyHole)); + + /* `have proof ? => ?`: the subproof starts as a hole too, the + * shape the obligations panel's "Prove here" writes. */ + let have = (~exp: Exp.t): TermBase.Proof.term => + Have( + embed_exp(exp), + None, + Proof.fresh(EmptyHole), + Proof.fresh(EmptyHole), + ); + + /* The id of a form's argument, child 0 of its tile. `embed_exp` + * freshens ids, so a caller can only read this back off the term. The + * printer stamps it onto the argument's pieces, so it is also where the + * caret lands to type into a freshly inserted form. */ + let rec arg_id = (t: TermBase.Proof.term): option(Id.t) => + switch (t) { + | Parens(inner) => arg_id(inner.term) + | Assume(e, _, _) + | Alias(_, e, _) + | Revert(e, _, _) + | Generalize(e, _) + | Have(e, _, _, _) => Some(Exp.rep_id(e)) + | Forall(p, _) + | Funext(p, _) => Some(Pat.rep_id(p)) + | EmptyHole + | Invalid(_) + | MultiHole(_) + | Seq(_, _) + | Cases(_, _) + | Induction(_, _) + | AxiomStep(_) + | AlgebriteStep(_) + | EvalStep + | Focus(_) => None + }; +}; + +/* Edits to the proof syntax, the only way the stepper changes a proof. */ +module Patches = { + type patch = EditorTransform.patch; + + /* Where a step picked on `row` goes: in place of a hole, before a + * step, or after the chain's last step. A hole is replaced rather than + * extended: it stands for "the proof continues here", not for a step of + * its own. */ + let write = (row: StepperRows.t, step: Proof.t): patch => + switch (row.kind) { + | Hole => + EditorTransform.mk_proof_patch(~target_id=Proof.rep_id(row.step), step) + /* `Seq(new, before)` nests left inside the enclosing chain until the + * reparse flattens it. */ + | Step(_) => + EditorTransform.mk_proof_patch( + ~target_id=Proof.rep_id(row.step), + Proof.fresh(Seq(step, row.step)), + ) + | End => + EditorTransform.mk_proof_patch( + ~target_id=Proof.rep_id(row.step), + Proof.fresh(Seq(row.step, step)), + ) + }; + + /* Splices the step out of its chain, `;` and all, or leaves a hole + * when it is the whole proof, so the text reads as if the step had + * never been written. */ + let remove = (step: Proof.t): patch => + EditorTransform.mk_proof_remove_patch(~target_id=Proof.rep_id(step)); + + /* Adds `step` to the end of a focus's steps, given its body. A body + * that is still a hole is replaced. */ + let join = (body: Proof.t, step: Proof.t): patch => + EditorTransform.mk_proof_patch( + ~target_id=Proof.rep_id(body), + switch (StepperRows.unparen(body).term) { + | EmptyHole => step + | _ => Proof.fresh(Seq(body, step)) + }, + ); + + /* The repair for an axiom step that doesn't apply: the same step in + * the other direction, when that checks from the step's goal. A + * one-step focus is drawn as its step, so it offers its step's repair. */ + let rec flip_direction = + (~info_map: Statics.Map.t, ~proof_map: ProofMap.t, step: Proof.t) + : option(patch) => + switch (step.term, StepperRows.single_step(step)) { + | (AxiomStep({direction, equality, instantiation}), _) => + let flipped: Proof.t = { + ...step, + term: + AxiomStep({ + direction: Direction.toggle(direction), + equality, + instantiation, + }), + }; + switch (ProofMap.lookup(Proof.rep_id(step), proof_map)) { + | Some({incoming: Some(goal), ctx, _}) + when + Evaluator.Proofs.check_proof( + ~statics=ProofStatics.of_info_map(info_map), + ~ctx, + ~goal, + flipped, + ) + |> ProofMap.error_ids == [] => + Some( + EditorTransform.mk_proof_patch( + ~target_id=Proof.rep_id(step), + flipped, + ), + ) + | _ => None + }; + | (_, Some(inner)) => flip_direction(~info_map, ~proof_map, inner) + | (_, None) => None + }; + + /* Adding or removing a split's case rewrites the whole node. */ + let set_cases = + (step: Proof.t, cases: list((Pat.t, Proof.t))): option(patch) => { + let rewrite = term => + Some( + EditorTransform.mk_proof_patch( + ~target_id=Proof.rep_id(step), + Proof.fresh(term), + ), + ); + switch (step.term) { + | Cases(scrut, _) => rewrite(Cases(scrut, cases)) + | Induction(scrut, _) => rewrite(Induction(scrut, cases)) + | _ => None + }; + }; + + /* A new case for a split whose cases don't yet cover its scrutinee, as + * the checker's `marks` on it say. */ + let add_case = (step: Proof.t, ~marks: list(ProofMark.t)): option(patch) => { + let uncovered = + List.mem(marks, ProofMark.InductionNotExhaustive, ~equal=Poly.equal); + let new_case = (Pat.fresh(EmptyHole), Proof.fresh(EmptyHole)); + switch (step.term) { + | Cases(_, cases) + | Induction(_, cases) when uncovered => + set_cases(step, cases @ [new_case]) + | _ => None + }; + }; +}; + +// Goals + +/* The node with `id` and the nodes enclosing it, nearest first. */ +let rec self_and_ancestors = (id, e: Exp.t): option(list(Exp.t)) => + Id.equal(Exp.rep_id(e), id) + ? Some([e]) + : Occurrence.children(e) + |> List.find_map(~f=self_and_ancestors(id)) + |> Option.map(~f=path => path @ [e]); + +/* The `step`s the stepper offers. The checker's `step` passes + * through `VarLookup`s silently (Evaluator.Proofs.advance_hidden), and + * then takes a step only at the root of its goal, so a step can't always + * be written at its own node: in `all_lists(xs) == true` the only step is + * the lookup of `all_lists`. Each step is offered as the step the checker + * takes at the nearest node around it where it takes one, here + * `all_lists(xs)`, and that node is the step's source. */ +module EvalSteps = { + /* Past this many silent steps nothing is offered, so a goal whose + * hidden steps diverge can't hang the stepper. */ + let max_silent_steps = 64; + + let checker_step = (~env, e: Exp.t): option(EvaluatorStep.step) => { + open OptUtil.Syntax; + let* (_, e) = + Evaluator.Proofs.advance_hidden(~max_steps=max_silent_steps, ~env, e); + switch (EvaluatorStep.get_status(~settings=CoreSettings.on, e, env)) { + | AvailableSteps(steps) => List.find(~f=EvaluatorStep.is_at_root, steps) + | AutoStep(_) => None + }; + }; + + /* The `n` for which the checker's `from th do` finds + * `node` itself in `goal` rather than an equal node before it. + * + * None if `node` holds a negative number. Evaluation produces those, + * but source can't spell them: written out, `-5` reads back as a + * negation, which the checker doesn't match against the number. */ + let checker_idx = (goal: Exp.t, node: Exp.t): option(int) => { + let rec has_negative_number = (e: Exp.t) => + switch (Exp.term_of(e)) { + | Atom(Int(n)) => Bigint.compare(n, Bigint.of_int(0)) < 0 + | Atom(SInt(n)) => n < 0 + | Atom(Float(f)) => f < 0.0 + | _ => List.exists(~f=has_negative_number, Occurrence.children(e)) + }; + has_negative_number(node) ? None : Occurrence.index(node, goal); + }; + + [@deriving (show({with_path: false}), sexp, yojson)] + type kind = + /* Evaluation's own step at the source, which the checker takes. */ + | Evaluation(EvaluatorStep.step) + /* A redex evaluation takes no step at, such as a named function + * applied to something that isn't a value yet, which `step` + * contracts (`ProofCheck.Beta`). */ + | Contraction; + + /* A step on offer, by its source: the node that taking it focuses on + * to write `step`. */ + [@deriving (show({with_path: false}), sexp, yojson)] + type offer = { + source: Id.t, + kind, + }; + + /* The steps to offer on `goal`. A step with no source the checker can + * find isn't offered, and steps with the same source are offered once. + * A step at the whole goal needs no selector, so it is offered even + * where `checker_idx` refuses one. */ + let offered = (~settings: CoreSettings.t, ~env, goal: Exp.t): list(offer) => { + let has_selector = (node: Exp.t) => + Id.equal(Exp.rep_id(node), Exp.rep_id(goal)) + || checker_idx(goal, node) != None; + let evaluation = (s: EvaluatorStep.step) => + self_and_ancestors(EvaluatorStep.get_step_id(s), goal) + |> Option.value(~default=[]) + |> List.find_map(~f=node => + switch (checker_step(~env, node)) { + | Some(step) when has_selector(node) => + Some({ + source: Exp.rep_id(node), + kind: Evaluation(step), + }) + | _ => None + } + ); + /* Every step, not the one the evaluator would take next: a hidden + * step it would take first, such as dropping an ascription, would hide + * the steps on every other operand. */ + let evaluations = + EvaluatorStep.all_steps(~settings, goal, env) + |> List.filter_map(~f=evaluation) + |> ListUtil.dedup_f((a, b) => Id.equal(a.source, b.source)); + let contractions = + Occurrence.in_source_order(~stop=_ => false, goal) + |> List.filter(~f=node => + ProofCheck.Beta.redex(~env, node) != None + && checker_step(~env, node) == None + && has_selector(node) + ) + |> List.map(~f=node => + { + source: Exp.rep_id(node), + kind: Contraction, + } + ); + evaluations @ contractions; + }; +}; + +/* A row's goal, prepared for stepping: its editor, which holds the + * selection, and the steps on offer. Preparing one is expensive, so the + * stepper keeps it with the goal it was made from (see `is_for`). The + * goal is shown as the checker keeps it, naming the program's + * definitions. */ +module Goal = { + [@deriving (show({with_path: false}), sexp, yojson)] + type t = { + written: Exp.t, + ctx: SemanticCtx.t, + editor: CodeSelectable.Model.t, + eval_steps: list(EvalSteps.offer), + /* Equalities in `written` that reflexivity closes. */ + refls: list(Exp.t), + /* What the goal was built with: how it prints, and which steps it + * offers. */ + settings: CoreSettings.t, + }; + + let env = (goal: t) => SemanticCtx.get_env(goal.ctx); + + let mk = (~settings: CoreSettings.t, ~ctx: SemanticCtx.t, written: Exp.t): t => { + let env = SemanticCtx.get_env(ctx); + let editor = + CodeSelectable.Model.mk_from_exp(~settings, ~root=Exp, written) + |> CodeEditable.Update.calculate( + ~settings, + ~is_edited=true, + ~is_dynamic_term=true, + ~dynamics=Dynamics.Map.empty, + ~stitch=x => x, + ~ctx=SemanticCtx.get_ctx(ctx), + ); + let eval_steps = EvalSteps.offered(~settings, ~env, written); + let step_ids = List.map(~f=(o: EvalSteps.offer) => o.source, eval_steps); + let refls = + MatchExp.find_refls( + ~statics= + ProofStatics.of_info_map( + CodeEditable.Model.get_statics(editor).info_map, + ), + ~defs=env, + written, + ) + |> List.filter(~f=e => + !List.mem(step_ids, Exp.rep_id(e), ~equal=Id.equal) + ); + { + written, + ctx, + editor, + eval_steps, + refls, + settings, + }; + }; + + /* Whether `name` cites a refuted theorem in the goal's scope, which + * the checker refuses. */ + let cites_refuted = (goal: t, name: string): bool => + SemanticCtx.cited_verdict(goal.ctx, name) == Some(Refuted); + + /* Whether `goal` is for `written` in `ctx`: the same goal, whose names + * are defined by the same text, as are the names those definitions use, + * and so on. A step on the goal can unfold any of them. */ + let is_for = (goal: t, ~ctx: SemanticCtx.t, written: Exp.t): bool => { + let rec text = (e: Exp.t): Exp.t => + switch (Exp.term_of(e)) { + | Closure(_, inner) => text(inner) + | FixF(p, body, Some(_)) => Exp.fresh(FixF(p, body, None)) + | _ => e + }; + let names = (e: Exp.t): list(Var.t) => { + let found = ref([]); + let _: Exp.t = + Exp.map_term( + ~f_exp= + (continue, e) => + switch (Exp.term_of(e)) { + | Var(x) => + found := [x, ...found^]; + e; + | _ => continue(e) + }, + e, + ); + found^; + }; + let before = env(goal); + let after = SemanticCtx.get_env(ctx); + let rec same_definitions = (seen, todo) => + switch (todo) { + | [] => true + | [x, ...todo] when List.mem(seen, x, ~equal=String.equal) => + same_definitions(seen, todo) + | [x, ...todo] => + switch (Environment.lookup(before, x), Environment.lookup(after, x)) { + | (None, None) => same_definitions([x, ...seen], todo) + | (Some(a), Some(b)) => + (phys_equal(a, b) || Exp.fast_equal(text(a), text(b))) + && same_definitions([x, ...seen], names(text(b)) @ todo) + | (Some(_), None) + | (None, Some(_)) => false + } + }; + Exp.fast_equal(goal.written, written) + && (phys_equal(before, after) || same_definitions([], names(written))); + }; + + let info_map = (goal: t): Statics.Map.t => + CodeEditable.Model.get_statics(goal.editor).info_map; + + /* The ids of the offered steps' sources, where their underlines go. */ + let step_ids = (goal: t): list(Id.t) => + List.map(~f=(o: EvalSteps.offer) => o.source, goal.eval_steps); + + /* Where the underline marking what `row`'s step acts on goes. A goal + * carried over from an earlier check prints the same as `row.goal` but + * may not share its ids, so the part is found by its position in + * `row.goal`. + * + * The editor may not draw that node. Inside a folded lambda it is in + * the editor's term but not drawn, so the underline goes on the nearest + * drawn node around it there, the fold. A hidden ascription isn't in the + * editor's term at all, so the underline goes on the first drawn node + * inside it. */ + let acts_on = (goal: t, row: StepperRows.t): option(Id.t) => { + let syntax = goal.editor.editor.syntax; + let drawn = (e: Exp.t) => + TermData.extreme_measures( + Exp.rep_id(e), + syntax.term_data, + CachedSyntax.measured(syntax), + ) + != None; + let rec inside = (e: Exp.t) => + drawn(e) + ? Some(e) + : ( + switch (Occurrence.children(e)) { + | [child] => inside(child) + | _ => None + } + ); + let editor_term = CodeEditable.Model.get_statics(goal.editor).term; + switch (row.goal, row.acts_on) { + | (Some(row_goal), Some(part)) => + Occurrence.at_same_position(~from=row_goal, ~onto=goal.written, part) + |> Option.bind(_, ~f=(node: Exp.t) => + switch (self_and_ancestors(Exp.rep_id(node), editor_term)) { + | Some(path) => List.find(~f=drawn, path) + | None => inside(node) + } + ) + |> Option.map(~f=Exp.rep_id) + | (None, _) + | (_, None) => None + }; + }; + + /* The node the user selected in the goal's editor, read off the editor + * itself so it can't lag the selection. */ + let selected = (goal: t): option(Exp.t) => { + let editor = goal.editor.editor; + TermData.get_root_id_using_ranges( + editor.state.zipper.selection.content, + editor.syntax.term_data, + CachedSyntax.measured(editor.syntax), + ) + |> Option.bind(_, ~f=id => Exp.find_by_id(id, goal.written)); + }; + + /* `goal` built again with `settings`. The node that was selected is + * selected again, or the caret goes back to the node it was at. */ + let rebuild = (~settings: CoreSettings.t, goal: t): t => { + let rebuilt = mk(~settings, ~ctx=goal.ctx, goal.written); + let zipper = goal.editor.editor.state.zipper; + let (node, restore) = + switch (selected(goal)) { + | Some(node) => ( + Some(Exp.rep_id(node)), + (id => Action.Select(Term(Id(id, zipper.selection.focus)))), + ) + | None => ( + Indicated.index(zipper), + (id => Action.Move(Goal(TileId(id)))), + ) + }; + let moved = + Option.bind(node, ~f=id => + Editor.Update.update( + ~settings, + restore(id), + rebuilt.editor.statics, + rebuilt.editor.dynamics, + rebuilt.editor.editor, + ) + |> Stdlib.Result.to_option + ); + switch (moved) { + | Some(editor) => { + ...rebuilt, + editor: { + ...rebuilt.editor, + editor, + }, + } + | None => rebuilt + }; + }; +}; + +// Picking + +/* A step to write, and where it acts: on the row's whole goal, or through + * a focus on one occurrence in it. */ +[@deriving (show({with_path: false}), sexp, yojson)] +type pick = { + at: option(target), + step: Proof.t, +} +and target = { + /* The occurrence, a node of the goal. */ + node: Exp.t, + /* What the focus writes, and which of its matches the occurrence is, + * counting from 0. */ + selector: Exp.t, + index: int, +}; + +/* Where a step picked on `node` acts: through a focus, unless `node` is + * the whole goal. The focus writes `node` with as much of it replaced by + * `$e` as still selects `node`, so the step survives edits to the parts + * of the goal it doesn't need. */ +let target = (goal: Goal.t, node: Exp.t): option(target) => + Id.equal(Exp.rep_id(node), Exp.rep_id(goal.written)) + ? None + : { + let (selector, index) = + Occurrence.generalize( + ~statics=ProofStatics.of_info_map(Goal.info_map(goal)), + ~env=Goal.env(goal), + ~index= + Occurrence.index(node, goal.written) |> Option.value(~default=0), + node, + Exp.rep_id(node), + goal.written, + ); + Some({ + node, + selector, + index, + }); + }; + +/* The proof `pick` writes on its own: its step, focused on its target. */ +let focused = (pick: pick): Proof.t => + switch (pick.at) { + | None => pick.step + | Some({selector, index, _}) => + Proof.fresh(Terms.focus(~selector, ~index, pick.step)) + }; + +/* The patch writing `pick` as a row of its own after `row`'s goal. */ +let write = (row: StepperRows.t, pick: pick): Patches.patch => + Patches.write(row, focused(pick)); + +/* The patch writing `steps` after `row`'s goal, one row each, or None + * for no steps. */ +let write_steps = + (row: StepperRows.t, steps: list(Proof.t)): option(Patches.patch) => + switch (List.rev(steps)) { + | [] => None + | [last, ...earlier] => + Some( + Patches.write( + row, + List.fold_left( + ~f=(rest, step) => Proof.fresh(Seq(step, rest)), + ~init=last, + earlier, + ), + ), + ) + }; + +/* What taking the `idx`-th offered step writes: `step`, focused on the + * step's source. */ +let take_step = (goal: Goal.t, idx: int): option(pick) => { + open OptUtil.Syntax; + let* {source, _}: EvalSteps.offer = List.nth(goal.eval_steps, idx); + let* node = Exp.find_by_id(source, goal.written); + /* A step at the root needs no selector. */ + let+ _ = + Id.equal(source, Exp.rep_id(goal.written)) + ? Some(0) : EvalSteps.checker_idx(goal.written, node); + { + at: target(goal, node), + step: Proof.fresh(EvalStep), + }; +}; + +/* Reflexivity is the `refl` axiom at the equality `node`. */ +let refl = (goal: Goal.t, node: Exp.t): pick => { + at: target(goal, node), + step: + Proof.fresh( + Terms.axiom_step(~direction=Direction.Right, ~equality="refl"), + ), +}; + +/* `proof` checked from `written` in `goal`'s scope, rather than as part + * of its theorem, or None if the checker marks any step of it. */ +let check = + (goal: Goal.t, written: Exp.t, proof: Proof.t): option(ProofMap.t) => { + let checked = + Evaluator.Proofs.check_proof( + ~statics=ProofStatics.of_info_map(Goal.info_map(goal)), + ~ctx=goal.ctx, + ~goal=written, + proof, + ); + ProofMap.error_ids(checked) == [] ? Some(checked) : None; +}; + +/* The goal a step of a checked proof leaves. */ +let outgoing_of = (checked: ProofMap.t, step: Proof.t): option(Exp.t) => + Option.bind(ProofMap.lookup(Proof.rep_id(step), checked), ~f=e => + e.outgoing + ); + +/* The goal `proof` leaves, checked as `check` does. */ +let outgoing = (goal: Goal.t, written: Exp.t, proof: Proof.t): option(Exp.t) => + Option.bind(check(goal, written, proof), ~f=checked => + outgoing_of(checked, proof) + ); + +/* A scope's citable rules: its own facts and theorems, then the builtin + * axioms, which `ProofCtx.of_theorem_ctx` lists last. */ +let scope_and_axioms = + (ctx: SemanticCtx.t): (list(ProofCtx.entry), list(ProofCtx.entry)) => { + let all = + ProofCtx.of_theorem_ctx( + ~builtins=Axioms.v, + ~captured=ctx.captured, + SemanticCtx.get_ctx(ctx), + ); + ListUtil.split_n(List.length(all) - List.length(Axioms.v), all); +}; + +// The write box + +/* What Tab takes in an empty write box: reflexivity when it closes the + * goal, or else the goal's next eval step. With part of the goal selected, + * the step is the selection's own, and the ghost is what the selection + * becomes. */ +module Ghost = { + [@deriving (show({with_path: false}), sexp, yojson)] + type t = { + /* The rule's name, shown beside the Tab key. */ + rule: string, + pick, + /* As the row would show it. */ + result: Exp.t, + }; + + let mk = (goal: Goal.t, ~selected: option(Exp.t)): option(t) => { + open OptUtil.Syntax; + /* A step on `(1 + 1)` has the parens as its source, so a selection of + * `1 + 1` takes in the parens around it. */ + let rec widen = (node, ancestors) => + switch (ancestors) { + | [parens, ...rest] => + switch (Exp.term_of(parens)) { + | Parens(_) => widen(parens, rest) + | _ => node + } + | [] => node + }; + let node = + switch (selected) { + | Some(s) => + switch (self_and_ancestors(Exp.rep_id(s), goal.written)) { + | Some([_, ...ancestors]) => widen(s, ancestors) + | Some([]) + | None => s + } + | None => goal.written + }; + let is_node = (e: Exp.t) => Id.equal(Exp.rep_id(e), Exp.rep_id(node)); + let inside = id => Exp.find_by_id(id, node) != None; + /* The step to take in `node`. On an equation, a part that also occurs + * on the other side is left alone, as stepping it only makes the sides + * differ, and the left side goes first; then the outermost part. With + * nothing selected, only evaluation's own steps count, so a redex it + * won't contract yet doesn't displace the step it takes. */ + let preferred_step = { + let sides = + switch (Exp.term_of(ProofSyntax.unwrap(node))) { + | BinOp(Poly(Equals), l, r) => Some((l, r)) + | _ => None + }; + let rank = (source: Exp.t) => { + let (shared, right) = + switch (sides) { + | Some((l, r)) => + let on_left = Exp.find_by_id(Exp.rep_id(source), l) != None; + (Occurrence.index(source, on_left ? r : l) != None, !on_left); + | None => (false, false) + }; + let depth = + self_and_ancestors(Exp.rep_id(source), node) + |> Option.value_map(~default=0, ~f=List.length); + (shared, right, depth); + }; + goal.eval_steps + |> List.mapi(~f=(idx, offer) => (idx, offer)) + |> List.filter(~f=((_, offer: EvalSteps.offer)) => + inside(offer.source) + && ( + switch (selected, offer.kind) { + | (None, Contraction) => false + | (Some(_), _) + | (None, Evaluation(_)) => true + } + ) + ) + |> List.filter_map(~f=((idx, offer: EvalSteps.offer)) => + Exp.find_by_id(offer.source, goal.written) + |> Option.map(~f=source => (rank(source), idx)) + ) + |> List.stable_sort(~compare=((a, _), (b, _)) => compare(a, b)) + |> List.map(~f=snd) + |> ListUtil.hd_opt; + }; + /* Reflexivity inside the part, as in `n == 1 ==> n == n`, only when + * no eval step is left. */ + let candidate = + switch (List.exists(~f=is_node, goal.refls), preferred_step) { + | (true, _) => Some(("refl", refl(goal, node))) + | (false, Some(idx)) => + take_step(goal, idx) |> Option.map(~f=pick => ("step", pick)) + | (false, None) => + List.find(~f=(e: Exp.t) => inside(Exp.rep_id(e)), goal.refls) + |> Option.map(~f=e => ("refl", refl(goal, e))) + }; + let* (rule, pick) = candidate; + let proof = focused(pick); + let* checked = check(goal, goal.written, proof); + /* What `node` becomes. A focus keeps the ids around the occurrence it + * replaces, so a selection wider than the step's own part is found by + * its id. */ + let+ result = + switch (pick.at) { + | Some({node: part, _}) + when !Id.equal(Exp.rep_id(part), Exp.rep_id(node)) => + outgoing_of(checked, proof) + |> Option.bind(_, ~f=Exp.find_by_id(Exp.rep_id(node))) + | Some(_) + | None => outgoing_of(checked, pick.step) + }; + { + rule, + pick, + result, + }; + }; +}; + +/* The Proof strategy tab: the goal's own introduction, then the + * strategies any goal can use. Each writes its form with holes for the + * user to fill in. */ +module Strategies = { + type strategy = { + label: string, + /* What it writes and what for. */ + tooltip: string, + writes: TermBase.Proof.term, + }; + + let intros = (goal: Goal.t): list(strategy) => { + let written = goal.written; + let hole = Exp.fresh(EmptyHole); + let forall = + ProofCheck.peel_binder(written) != None + ? [ + { + label: "Forall", + tooltip: "Writes `forall x =>`: names the argument, to prove the body for any x", + writes: Terms.forall(), + }, + ] + : []; + /* Exactly when the goal is `f == g` at an arrow type, by the checker's + * own detector, so it never writes a step that would mark. */ + let funext = + ProofCheck.Funext.goal( + ~statics=ProofStatics.of_info_map(Goal.info_map(goal)), + ~env=Goal.env(goal), + written, + ) + == None + ? [] + : [ + { + label: "Funext", + tooltip: "Writes `funext x =>`: proves the functions equal at any argument x", + writes: Terms.funext(), + }, + ]; + let assume = + ProofRule.implication(written) == None + ? [] + : [ + { + label: "Assume", + tooltip: "Writes `assume A =>`: for a goal A ==> B, adds A as a fact and proves B", + writes: Terms.assume(~exp=hole), + }, + ]; + forall @ funext @ assume; + }; + + let general = (): list(strategy) => { + let hole = Exp.fresh(EmptyHole); + [ + { + label: "Induction", + tooltip: "Writes `induction x end`: one case per form of x, each with its inductive hypotheses", + writes: Terms.induction(~exp=hole), + }, + { + label: "Cases", + tooltip: "Writes `cases e end` on any expression: one case per form of its value, each with its case equation `case_eq`", + writes: Terms.cases(~exp=hole), + }, + { + label: "Have", + tooltip: "Writes `have ? proof ? =>`: proves a stepping-stone fact first, then uses it here", + writes: Terms.have(~exp=hole), + }, + { + label: "Generalize", + tooltip: "Writes `generalize x =>`: makes x arbitrary again, a forall in the goal, e.g. before induction", + writes: Terms.generalize(~exp=hole), + }, + { + label: "Revert", + tooltip: "Writes `revert =>`: moves a fact back into the goal as fact ==> goal, e.g. before induction", + writes: Terms.revert(~exp=hole), + }, + ]; + }; +}; diff --git a/src/web/app/editors/stepper/StepperRows.re b/src/web/app/editors/stepper/StepperRows.re new file mode 100644 index 0000000000..ce715f75d0 --- /dev/null +++ b/src/web/app/editors/stepper/StepperRows.re @@ -0,0 +1,504 @@ +open Util; +open Language; +open Poly; + +/* The stepper's rows, read off the proof syntax and the checker's + * ProofMap. Nothing here is stored: the view and the state pass walk the + * proof again each time. + * + * Each step of a `;` chain is a row, showing the goal the step starts + * from. A chain that ends in a step gets one more row, the step's + * outgoing goal, where the proof continues. A form's body, an + * induction's cases, a have's two premises and a focus's steps are + * chains of their own, nested in the form's row. A focus of one step is + * drawn as that step, so it nests nothing. */ + +[@deriving (show({with_path: false}), sexp, yojson)] +type side = + | Incoming + | Outgoing; + +/* A step's own row is keyed by the step's id on the incoming side. The + * row after a chain's last step is keyed by that step's id on the + * outgoing side. */ +[@deriving (show({with_path: false}), sexp, yojson)] +type key = (Id.t, side); + +type t = { + key, + /* The step the row shows, or for an `End` row the step it follows. */ + step: Proof.t, + kind, + /* The checker's entry for `step`; None until the proof is checked. */ + entry: option(ProofMap.entry), + /* The goal the row shows, as the checker wrote it. None when there is + * none to show: nothing checked yet, or an earlier step broke. */ + goal: option(Exp.t), + /* The id in `goal` of the part the step acts on: the occurrence a focus + * selected, or all of `goal` for a step that rewrites it whole. None + * for a step that changes the goal's shape or closes it from facts + * (forall, induction, ...). */ + acts_on: option(Id.t), + /* Whether a step can be written at the row, in its write box: in place + * of a hole, or after the chain's last step where the proof goes on. */ + continues: bool, +} +and kind = + /* A written `?` or unparseable text. A step picked here replaces it. */ + | Hole + /* A step. A step picked here goes in before it. */ + | Step(nested) + /* Past the chain's last step. A step picked here extends the chain. */ + | End +and nested = + | Leaf + /* The body of forall, funext, assume, revert, generalize or alias. */ + | Body(list(t)) + | Cases(list((Pat.t, list(t)))) + | Premises({ + sub: list(t), + body: list(t), + }) + /* The steps of a focus of more than one step. */ + | Focus(list(t)); + +/* Grouping parens are transparent: `( funext x => ? )` is a funext row. */ +let rec unparen = (p: Proof.t): Proof.t => + switch (p.term) { + | Parens(inner) => unparen(inner) + | _ => p + }; + +/* The step a proof starts with, and the rest of its `;` chain. */ +let rec split = (p: Proof.t): (Proof.t, option(Proof.t)) => { + let p = unparen(p); + switch (p.term) { + | Seq(head, tail) => + switch (unparen(head)) { + /* Inserting a step before another writes `Seq(Seq(new, old), tail)` + * until a reparse flattens it, so re-associate it to keep the head a + * single step. The rebuilt node reuses the inner Seq's ids, which no + * row reads. */ + | {term: Seq(a, b), _} as inner => + split({ + ...p, + term: + Seq( + a, + { + ...inner, + term: Seq(b, tail), + }, + ), + }) + | head => (head, Some(tail)) + } + | _ => (p, None) + }; +}; + +let is_alias = (step: Proof.t) => + switch (step.term) { + | Alias(_) => true + | _ => false + }; + +/* The one step of a focus drawn as that step's line: a step with no + * nested rows of its own. */ +let single_step = (focus: Proof.t): option(Proof.t) => + switch (focus.term) { + | Focus({body, _}) => + let inner = unparen(body); + switch (inner.term) { + | AxiomStep(_) + | AlgebriteStep(_) + | EvalStep => Some(inner) + | EmptyHole + | Invalid(_) + | MultiHole(_) + | Seq(_) + | Parens(_) + | Focus(_) + | Cases(_) + | Induction(_) + | Forall(_) + | Funext(_) + | Assume(_) + | Alias(_) + | Generalize(_) + | Revert(_) + | Have(_) => None + }; + | _ => None + }; + +/* A form proving a goal of its own (forall, assume, a split, ...) passes + * its goal through until its body closes it, so the proof doesn't go on + * after it. */ +let passes_goal_through = (step: Proof.t): bool => + switch (unparen(step).term) { + | Forall(_) + | Funext(_) + | Assume(_) + | Revert(_) + | Generalize(_) + | Cases(_) + | Induction(_) => true + | EmptyHole + | Invalid(_) + | MultiHole(_) + | Seq(_) + | Parens(_) + | AxiomStep(_) + | AlgebriteStep(_) + | EvalStep + | Focus(_) + | Alias(_) + | Have(_) => false + }; + +/* The rows of the chain `proof`. With `open_end` off, a step can't be + * written after the chain's last one: the chain is a focus's steps, and + * more steps follow the focus, so a step there would go between rows. */ +let rec chain = + (~proof_map: ProofMap.t, ~open_end=true, proof: Proof.t): list(t) => { + let (step, tail) = split(proof); + let lookup = p => ProofMap.lookup(Proof.rep_id(p), proof_map); + /* A one-step focus's row is its step's: the step's marks and side + * conditions, unless the focus itself is at fault. */ + let entry = + switch (lookup(step), Option.bind(single_step(step), ~f=lookup)) { + | (Some(focus), Some(inner)) => + Some({ + ...focus, + marks: focus.marks == [] ? inner.marks : focus.marks, + obligations: focus.obligations @ inner.obligations, + }) + | (entry, _) => entry + }; + let goal = + switch (entry) { + /* After any automatic steps the checker took first. */ + | Some({incoming: Some(incoming), auto_incoming, _}) => + Some( + List.fold_left(~f=(_, (_, e)) => e, ~init=incoming, auto_incoming), + ) + | Some({incoming: None, _}) + | None => None + }; + let nested = chain(~proof_map, ~open_end=true); + /* `have` and `alias` keep their goal, so their body is the rest of this + * chain. */ + let rest = chain(~proof_map, ~open_end); + let acts_on = + switch (step.term) { + /* The checker starts a focus's body from the occurrence it selected. */ + | Focus({body, _}) => + lookup(body) + |> Option.bind(_, ~f=(e: ProofMap.entry) => e.incoming) + |> Option.map(~f=Exp.rep_id) + | AxiomStep(_) + | AlgebriteStep(_) + | EvalStep => Option.map(~f=Exp.rep_id, goal) + | EmptyHole + | Invalid(_) + | MultiHole(_) + | Seq(_) + | Parens(_) + | Forall(_) + | Funext(_) + | Assume(_) + | Revert(_) + | Generalize(_) + | Have(_) + | Alias(_) + | Cases(_) + | Induction(_) => None + }; + let row = kind => { + key: (Proof.rep_id(step), Incoming), + step, + kind, + entry, + goal, + acts_on, + continues: kind == Hole, + }; + let row = + switch (step.term) { + | EmptyHole + | Invalid(_) + | MultiHole(_) => row(Hole) + | AxiomStep(_) + | AlgebriteStep(_) + | EvalStep => row(Step(Leaf)) + | Focus({body, _}) => + row( + Step( + single_step(step) == None + ? Focus( + chain(~proof_map, ~open_end=open_end && tail == None, body), + ) + : Leaf, + ), + ) + | Forall(_, body) + | Funext(_, body) + | Assume(_, _, body) + | Revert(_, _, body) + | Generalize(_, body) => row(Step(Body(nested(body)))) + | Alias(_, _, body) => row(Step(Body(rest(body)))) + | Cases(_, cases) + | Induction(_, cases) => + row( + Step( + Cases( + List.map(~f=((pat, body)) => (pat, nested(body)), cases), + ), + ), + ) + | Have(_, _, sub, body) => + row( + Step( + Premises({ + sub: nested(sub), + body: rest(body), + }), + ), + ) + /* `split` leaves neither at the head. */ + | Parens(_) + | Seq(_, _) => row(Step(Leaf)) + }; + switch (tail, row.kind) { + | (Some(tail), _) => [row, ...chain(~proof_map, ~open_end, tail)] + /* A hole at the end already stands for "the proof continues here". */ + | (None, Hole) => [row] + /* `have` and `alias` keep their goal, so their body's own last row is + * where the proof continues. */ + | (None, Step(Premises(_))) => [row] + | (None, Step(Body(_))) when is_alias(step) => [row] + | (None, Step(_) | End) => [ + row, + { + key: (Proof.rep_id(step), Outgoing), + step, + kind: End, + entry, + goal: Option.bind(entry, ~f=(e: ProofMap.entry) => e.outgoing), + acts_on: None, + continues: open_end && !passes_goal_through(step), + }, + ] + }; +}; + +/* The rows of a theorem's proof. A proof that reads Refuted can't go on, + * as one at `true` can't, so none of its rows continues. */ +let of_theorem = (~proof_map: ProofMap.t, proof: Proof.t): list(t) => { + let rec closed = (rows: list(t)): list(t) => + List.map( + ~f= + row => + { + ...row, + continues: false, + kind: + switch (row.kind) { + | Step(Body(rows)) => Step(Body(closed(rows))) + | Step(Cases(cases)) => + Step( + Cases( + List.map( + ~f=((pat, rows)) => (pat, closed(rows)), + cases, + ), + ), + ) + | Step(Premises({sub, body})) => + Step( + Premises({ + sub: closed(sub), + body: closed(body), + }), + ) + | Step(Focus(rows)) => Step(Focus(closed(rows))) + | Step(Leaf) + | Hole + | End => row.kind + }, + }, + rows, + ); + let rows = chain(~proof_map, proof); + ProofMap.full_status_of_proof(proof_map, proof) == Refuted + ? closed(rows) : rows; +}; + +/* Whether the row shows a goal still to prove: the goal a form passes on + * after its body, until the body proves it. The last row of a focus's + * chain is the focused part rewritten, which is no goal. */ +let is_unproven = (~proof_map: ProofMap.t, row: t): bool => + row.kind == End + && passes_goal_through(row.step) + && ProofMap.status_of_proof(proof_map, row.step) != Some(true); + +/* The name a split's arm binds that the checker refused, as the goal + * already uses it: the arm's goal would capture that use, so the arm's + * steps aren't checked. */ +let refused_binding = (split: t, pat: Pat.t): option(Var.t) => { + let bound = pat |> Pat.bindings |> Binding.variable_names; + Option.value_map(split.entry, ~default=[], ~f=(e: ProofMap.entry) => + e.marks + ) + |> List.find_map(~f=(mark: ProofMark.t) => + switch (mark) { + | BinderCaptures({var}) when List.mem(bound, var, ~equal=String.equal) => + Some(var) + | _ => None + } + ); +}; + +/* Every row, nested chains included. */ +let rec all = (rows: list(t)): list(t) => + List.concat_map( + ~f= + row => + [ + row, + ...switch (row.kind) { + | Step(Body(rows)) => all(rows) + | Step(Cases(cases)) => + List.concat_map(~f=((_, c)) => all(c), cases) + | Step(Premises({sub, body})) => all(sub) @ all(body) + | Step(Focus(rows)) => all(rows) + | Step(Leaf) + | Hole + | End => [] + }, + ], + rows, + ); + +/* The goal a chain's rows reach: its last step's outgoing goal. A + * trailing hole passes its incoming goal through. */ +let reached = (rows: list(t)): option(Exp.t) => + switch (ListUtil.last_opt(rows)) { + | Some({kind: End, goal, _}) => goal + | Some({kind: Hole | Step(_), entry, _}) => + Option.bind(entry, ~f=(e: ProofMap.entry) => e.outgoing) + | None => None + }; + +/* The scope a step written at the row is checked in. */ +let ctx = (row: t): option(SemanticCtx.t) => + Option.map(~f=(e: ProofMap.entry) => e.ctx, row.entry); + +/* The side conditions a step row shows: the obligations its step + * incurs. A have's two premises are drawn as its own goals, the sub-proof + * arm and the goal continuing below it, so it shows none. */ +let side_conditions = (row: t): list(Obligation.t) => + switch (row.kind, row.entry) { + | (Step(Premises(_)), _) + | (Hole | End, _) + | (Step(_), None) => [] + | (Step(Leaf | Body(_) | Cases(_) | Focus(_)), Some(entry)) => + entry.obligations + }; + +/* The rows that carry on a step's own goal. `have` and `alias` keep the + * goal, so their body reads as the rest of the outer chain. */ +let continuation = (row: t): option(list(t)) => + switch (row.kind) { + | Step(Premises({body, _})) => Some(body) + | Step(Body(rows)) when is_alias(row.step) => Some(rows) + | Step(Leaf | Body(_) | Cases(_) | Focus(_)) + | Hole + | End => None + }; + +/* How a step is drawn between its row and the next. */ +type layout = + /* A line, with the step's lozenge on it. */ + | Line + /* The line opened into a block: the side conditions shown open, by + * index into `side_conditions`, then, with `arms`, the goals the step + * creates. */ + | Block({ + conditions: list(int), + arms: bool, + }); + +/* `expanded` is the indices of the side conditions the user opened. */ +let layout = (row: t, ~expanded: list(int)): layout => { + let count = List.length(side_conditions(row)); + let conditions = + List.dedup_and_sort(~compare=Int.compare, expanded) + |> List.filter(~f=i => i >= 0 && i < count); + let arms = + switch (row.kind, continuation(row)) { + | (Step(Body(_)), Some(_)) => false + | (Step(Body(_) | Cases(_) | Premises(_) | Focus(_)), _) => true + | (Step(Leaf) | Hole | End, _) => false + }; + conditions == [] && !arms + ? Line + : Block({ + conditions, + arms, + }); +}; + +type row = t; + +/* A row's status, from the marks the checker recorded for its step. */ +module Status = { + type t = + /* Checked, with no marks. Says nothing about whether the goal is + * proven. */ + | Clean + /* Clean, but the step's own arguments hold a hole: an induction + * case's pattern or scrutinee, a forall binder, an axiom target. + * Holes in nested proofs don't count: each has a row of its own. */ + | Incomplete + /* At fault: the highest-priority mark. */ + | Broken(ProofMark.t) + /* An earlier row is at fault, so this one has no incoming goal. */ + | Blocked + /* Not checked yet. */ + | Pending; + + let of_row = (row: row): t => + switch (row.kind, row.entry) { + /* An `End` row has no step of its own to be at fault. */ + | (End, _) => Clean + | (Hole | Step(_), None) => Pending + | (Hole | Step(_), Some({marks, _})) => + let blocked = + List.mem(marks, ProofMark.MissingIncoming, ~equal=Poly.equal); + switch (blocked, ProofMark.highest(marks), row.kind) { + | (true, _, _) => Blocked + | (false, Some(m), _) => Broken(m) + | (false, None, Step(_)) + when + Proof.args_have_hole(row.step) + || Option.value_map( + single_step(row.step), + ~default=false, + ~f=Proof.args_have_hole, + ) => + Incomplete + | (false, None, _) => Clean + }; + }; + + let broken_mark = (status: t): option(ProofMark.t) => + switch (status) { + | Broken(mark) => Some(mark) + | Clean + | Incomplete + | Blocked + | Pending => None + }; +}; diff --git a/src/web/app/editors/stepper/StepperTargetBox.re b/src/web/app/editors/stepper/StepperTargetBox.re deleted file mode 100644 index 7aa4bfa671..0000000000 --- a/src/web/app/editors/stepper/StepperTargetBox.re +++ /dev/null @@ -1,70 +0,0 @@ -open Util; -open WebUtil; - -module F = (Stepper: StepInterface.STEPPER) => { - let target_box = - ( - ~globals: Globals.t, - ~inject, - ~take_focus, - ~hide_stepper, - ~focus, - ~is_toplevel, - stepper: Stepper.model, - target: Language.Exp.t, - reached: Language.Exp.t, - ) - : list(Node.t) => { - let stepper_view = - Stepper.view( - ~globals, - ~inject, - ~take_focus, - ~hide_stepper, - ~focus, - ~is_toplevel, - stepper, - ); - let step_placeholder = () => - Node.div( - ~attrs=[ - Attr.classes(["stepper", "cell-result", "step-placeholder"]), - ], - [div_c("step-border", [Node.text("...")])], - ); - let target_editor = - CodeViewable.view_any( - ~globals, - ~settings= - Haz3lcore.ExpToSegment.Settings.of_core( - ~inline=false, - globals.settings.core, - ), - Exp(target), - ); - let target_step = () => - Node.div( - ~attrs=[Attr.classes(["stepper", "cell-result", "target-step"])], - [ - div_c( - "step-border", - [ - div_c( - "step-display", - [ - div_c("equiv", [Node.text("≡?")]), - div_c("step-output", [target_editor]), - Node.text("target"), - ], - ), - ], - ), - ], - ); - if (Language.Exp.fast_equal(target, reached)) { - stepper_view; - } else { - stepper_view @ [step_placeholder(), target_step()]; - }; - }; -}; diff --git a/src/web/app/explainthis/Example.re b/src/web/app/explainthis/Example.re index 72f06e0f1a..81126b7c39 100644 --- a/src/web/app/explainthis/Example.re +++ b/src/web/app/explainthis/Example.re @@ -34,6 +34,7 @@ let exp = v => operand(Sort.Exp, v); let pat = v => operand(Sort.Pat, v); let typ = t => operand(Sort.Typ, t); let tpat = v => operand(Sort.TPat, v); +let proof = v => operand(Sort.Proof, v); let mk_list_exp = mk_tile(ListLit, Exp); let mk_list_pat = mk_tile(ListLit, Pat); let mk_list_typ = mk_tile(ListLit, Typ); @@ -67,6 +68,7 @@ let fgte = () => mk_monotile(FGte, Exp); let sconcat = () => mk_monotile(StringConcat, Exp); let logical_and = () => mk_monotile(LogicalAnd, Exp); let logical_or = () => mk_monotile(LogicalOr, Exp); +let logical_implies = () => mk_monotile(Impl, Exp); let comma_exp = () => mk_monotile(Comma, Exp); let comma_pat = () => mk_monotile(Comma, Pat); let comma_typ = () => mk_monotile(Comma, Typ); @@ -98,7 +100,26 @@ let mk_pause = mk_tile(FilterPause, Exp); let mk_debug = mk_tile(FilterDebug, Exp); let mk_theorem = mk_tile(Theorem, Exp); let mk_forall = mk_tile(Forall, Exp); -let mk_proof_of = mk_tile(ProofOf, Typ); +let proof_seq = () => mk_monotile(CellJoin, Proof); +let mk_proof_forall = mk_tile(ProofForall, Proof); +let mk_proof_funext = mk_tile(ProofFunext, Proof); +let mk_assume = mk_tile(ProofAssume, Proof); +let mk_generalize = mk_tile(ProofGeneralize, Proof); +let mk_revert = mk_tile(ProofRevert, Proof); +let mk_revert_with = mk_tile(ProofRevertWith, Proof); +let mk_axiom = mk_tile(ProofAxiom, Proof); +let mk_axiom_with = mk_tile(ProofAxiomWith, Proof); +let mk_rewrite_back = () => mk_monotile(RewriteBack, Exp); +let mk_algebra_step = mk_tile(ProofAlgebrite, Proof); +let mk_eval_step = mk_tile(ProofEval, Proof); +let mk_focus = mk_tile(ProofFocus, Proof); +let mk_cases = mk_tile(ProofCases, Proof); +let mk_induction = mk_tile(ProofInduction, Proof); +let mk_proof_rule = mk_tile(Rule, PRul); +let mk_have = mk_tile(ProofHave, Proof); +let mk_have_named = mk_tile(ProofHaveNamed, Proof); +let mk_assume_named = mk_tile(ProofAssumeNamed, Proof); +let mk_alias = mk_tile(ProofAlias, Proof); let linebreak = () => Piece.Secondary(Secondary.mk_newline(Id.mk())); let space = () => Piece.Secondary(Secondary.mk_space(Id.mk())); diff --git a/src/web/app/explainthis/ExplainThis.re b/src/web/app/explainthis/ExplainThis.re index f6dc1c0343..bbac91b6ec 100644 --- a/src/web/app/explainthis/ExplainThis.re +++ b/src/web/app/explainthis/ExplainThis.re @@ -344,7 +344,7 @@ let expander_deco = TermData.extreme_measures( id, editor.syntax.term_data, - editor.syntax.measured, + Haz3lcore.CachedSyntax.measured(editor.syntax), ) ) { | Some((origin, _)) => origin @@ -838,6 +838,8 @@ let decide = | _ => Prose("Signature item") } | Some(InfoMPat(_)) => Prose("Module name") + | Some(InfoProof({user_term, _})) => + message_single(ProofDoc.single(user_term)) | Some(InfoExp({cls: Mod(ModLet), _})) => message_single(ModLetDecl.single) | Some(InfoExp({cls: Mod(ModType), _})) => @@ -1234,14 +1236,12 @@ let decide = | Projector(_) | Asc(_) => NoDoc // Shouldn't get hit? }; - | Theorem(pat, thm, body) => + | Theorem(pat, thm, pf, body) => let pat_id = IdTagged.rep_id(pat); let thm_id = IdTagged.rep_id(thm); + let proof_id = IdTagged.rep_id(pf); let body_id = IdTagged.rep_id(body); - get_message(TheoremExp.tests(~pat_id, ~thm_id, ~body_id)); - | ProofObject(exp) => - let typ_id = IdTagged.rep_id(exp); - get_message(ProofObjectExp.proof_of_exps(~typ_id)); + get_message(TheoremExp.tests(~pat_id, ~thm_id, ~proof_id, ~body_id)); | Forall(pat, typ) => let pat_id = IdTagged.rep_id(pat); let body_id = IdTagged.rep_id(typ); @@ -1425,6 +1425,7 @@ let decide = | Float(NotEquals) => float_not_equal | Bool(And) => bool_and | Bool(Or) => bool_or + | Bool(Implies) => bool_implies | String(Concat) => string_concat | Poly(Equals) => poly_equal | Poly(NotEquals) => poly_not_equal @@ -1556,9 +1557,6 @@ let decide = let tpat_id = IdTagged.rep_id(tpat); let tbody_id = IdTagged.rep_id(typ); get_message(RecTyp.rec_(~tpat_id, ~tbody_id)); - | ProofOf(exp) => - let body_id = IdTagged.rep_id(exp); - get_message(ProofOfTyp.proof_of(~body_id)); | Arrow(arg, result) => let arg_id = IdTagged.rep_id(arg); let result_id = IdTagged.rep_id(result); diff --git a/src/web/app/explainthis/ExplainThisForm.re b/src/web/app/explainthis/ExplainThisForm.re index d0877c3223..9c482c3554 100644 --- a/src/web/app/explainthis/ExplainThisForm.re +++ b/src/web/app/explainthis/ExplainThisForm.re @@ -101,7 +101,6 @@ type example_id = | TupleExtension3 | Let(let_examples) | Theorem - | ProofOf | Forall | Yes | UseExp1 @@ -131,6 +130,8 @@ type example_id = | AndTrue | OrFalse | OrTrue + | ImpliesFalse + | ImpliesTrue | CaseWildSimple | CaseWildTuple | CaseInt @@ -154,7 +155,28 @@ type example_id = | SigLet1 | SigType1 | ModuleKeyword1 - | ModuleKeywordDecl1; + | ModuleKeywordDecl1 + /* Prover forms */ + | ProofSeq1 + | ProofAxiom1 + | ProofAxiomWith1 + | ProofAxiomRev1 + | ProofAxiomRevWith1 + | ProofRewrite1 + | ProofEval1 + | ProofFocus1 + | ProofCases1 + | ProofInduction1 + | ProofForall1 + | ProofFunext1 + | ProofAssume1 + | ProofGeneralize1 + | ProofRevert1 + | ProofRevertWith1 + | ProofHave1 + | ProofHaveNamed1 + | ProofAssumeNamed1 + | ProofAlias1; /* No deriving: nothing serializes an `example`, `form` or `group`. Only the id enums need serializers, because `ExplainThisModel.t` is what `Store` @@ -222,7 +244,6 @@ type form_id = | LetExp(pat_sub_form_id) | FixExp(pat_sub_form_id) | TheoremExp - | ProofObjectExp | TypFunApExp | FunApExp | ConApExp @@ -283,7 +304,6 @@ type form_id = | DotTyp | Label | ForallExp - | ProofOfTyp | LabelledSumTyp | SumTypUnaryConstructorDef | SumTypNullaryConstructorDef @@ -305,7 +325,29 @@ type form_id = | SigLetDecl | SigTypeDecl | ModuleKeywordExp - | ModuleKeywordDecl; + | ModuleKeywordDecl + /* Prover forms: the Proof sort's own steps. */ + | ProofEmptyHole + | ProofMultiHole + | ProofInvalid + | ProofSeqStep + | ProofAxiomStep + | ProofAxiomRevStep + | ProofRewriteStep + | ProofEvalStep + | ProofFocusStep + | ProofCasesStep + | ProofInductionStep + | ProofForallStep + | ProofFunextStep + | ProofAssumeStep + | ProofGeneralizeStep + | ProofRevertStep + | ProofHaveStep + /* Hypothesis naming: the named forms and `alias`. */ + | ProofHaveNamedStep + | ProofAssumeNamedStep + | ProofAliasStep; type form = { id: form_id, diff --git a/src/web/app/explainthis/data/ForallExp.re b/src/web/app/explainthis/data/ForallExp.re index e8224c0a00..cda65c7593 100644 --- a/src/web/app/explainthis/data/ForallExp.re +++ b/src/web/app/explainthis/data/ForallExp.re @@ -21,11 +21,17 @@ let forall_exp = (~pat_id: Id.t, ~body_id: Id.t): form => { expandable_id: Some((Piece.id(tpat), [exp_arg])), explanation: sprintf( - "The forall expression asserts that for every value of the [*variables*](%s) the inside of the forall always returns true [*inner type*](%s). This expression does not work at runtime (it would take forever if it did!), but is useful for specifying properties of functions and data types.", + "Asserts that for every total value of the [*variable*](%s) the [*body*](%s) denotes `true`. Quantifiers range over total values only — terminating, error-free ones — which is what makes a proven `forall` an operational guarantee: every closed instance of it really evaluates to `true`. It states a property rather than computing one, so it does not run (that would take forever).", Id.to_string(pat_id), Id.to_string(body_id), ), - examples: [], + examples: [ + { + sub_id: Forall, + term: mk_example("theorem t = forall x -> x + 0 == x proof ? in 0"), + message: "The statement of `t` quantifies over every Int `x`. Proving it means proving `x + 0 == x` for an arbitrary `x`, not for any particular one.", + }, + ], }; let forall = (~pat_id: Id.t, ~body_id: Id.t): group => diff --git a/src/web/app/explainthis/data/OpExp.re b/src/web/app/explainthis/data/OpExp.re index 56637d0ed9..891e527b5a 100644 --- a/src/web/app/explainthis/data/OpExp.re +++ b/src/web/app/explainthis/data/OpExp.re @@ -197,6 +197,16 @@ let bool_and2_ex = { term: mk_example("1 < 2 && 3 < 4"), message: "The left operand evaluates to true, so evaluate the right operand. Since the right operand also evaluates to true, the whole expression evaluates to true.", }; +let bool_implies1_ex = { + sub_id: ImpliesFalse, + term: mk_example("true ==> false"), + message: "The left operand is true, so evaluate the right operand. Since the right operand is false, the whole expression evaluates to false.", +}; +let bool_implies2_ex = { + sub_id: ImpliesTrue, + term: mk_example("false ==> false"), + message: "The left operand evaluates to false, so the right operand is not evaluated. The whole expression evaluates to true.", +}; let bool_or1_ex = { sub_id: OrFalse, term: mk_example("false \\/ 2 < 1"), @@ -803,6 +813,29 @@ let bool_or_exp = (~left_id: Id.t, ~right_id: Id.t): form => { }; let exp1 = exp("e1"); let exp2 = exp("e2"); +let bool_implies_exp_coloring_ids = + (~left_id: Id.t, ~right_id: Id.t): list((Id.t, Id.t)) => + binop_exp_coloring_ids( + Piece.id(exp1), + Piece.id(exp2), + ~left_id, + ~right_id, + ); +let bool_implies_exp = (~left_id: Id.t, ~right_id: Id.t): form => { + id: BinOpExp(Bool(Implies)), + syntactic_form: [exp1, space(), logical_implies(), space(), exp2], + colorings: bool_implies_exp_coloring_ids(~left_id, ~right_id), + expandable_id: None, + explanation: + binop_explanation( + ~left_id, + ~right_id, + "Material implication. If the [*left operand*](%s) evaluates to `false`, the whole expression evaluates to `true` without evaluating the [*right operand*](%s). Otherwise, evaluates to the right operand. In a proof the connectives are read symmetrically (Kleene), so their laws — `impl_def` (`a ==> b` is `!a || b`), commutativity, associativity, De Morgan, `impl_true` — are built-in axioms you can cite. A goal `a ==> b` is also what `assume a` introduces, and what `revert` produces from a fact in scope.", + ), + examples: [bool_implies1_ex, bool_implies2_ex], +}; +let exp1 = exp("e1"); +let exp2 = exp("e2"); let str_concat_exp_coloring_ids = (~left_id: Id.t, ~right_id: Id.t): list((Id.t, Id.t)) => binop_exp_coloring_ids( @@ -897,6 +930,9 @@ let bool_and = (~left_id: Id.t, ~right_id: Id.t): group => let bool_or = (~left_id: Id.t, ~right_id: Id.t): group => singleton(bool_or_exp(~left_id, ~right_id)); +let bool_implies = (~left_id: Id.t, ~right_id: Id.t): group => + singleton(bool_implies_exp(~left_id, ~right_id)); + let string_concat = (~left_id: Id.t, ~right_id: Id.t): group => singleton(str_concat_exp(~left_id, ~right_id)); diff --git a/src/web/app/explainthis/data/ProofDoc.re b/src/web/app/explainthis/data/ProofDoc.re new file mode 100644 index 0000000000..ed4ae6a387 --- /dev/null +++ b/src/web/app/explainthis/data/ProofDoc.re @@ -0,0 +1,734 @@ +open Haz3lcore; +open Language; +open ExplainThisForm; +open Example; + +/* ExplainThis documentation for the Proof sort — the prover's step forms. + * + * House rule for this file: every message names the facts the step brings + * into scope (`assume`, `case_eq`, `ih_t`, `have`) and says whether the + * step adds a side condition, in the words the Prover slides use, because + * that is what a user sitting on the step needs to write the next one. */ + +/* A child slot, padded so the tile's shards read as delimiters. */ +let slot = (p: Piece.t): Segment.t => [space(), p, space()]; + +let proof_body = () => proof("proof"); + +// Degenerate forms + +let empty_hole: Simple.t = { + group_id: ProofEmptyHole, + form_id: ProofEmptyHole, + abstract: ([proof("?")], []), + explanation: "An unfinished proof: the goal it is handed stays open, so the theorem reads incomplete. In the stepper, the write box here offers the steps that apply to this goal.", + examples: [], +}; + +let multi_hole: Simple.t = { + group_id: ProofMultiHole, + form_id: ProofMultiHole, + abstract: ([proof("?")], []), + explanation: "These pieces don't form a proof step yet, so nothing is checked here and the goal stays open.", + examples: [], +}; + +let invalid: Simple.t = { + group_id: ProofInvalid, + form_id: ProofInvalid, + abstract: ([proof("?")], []), + explanation: "Not a proof step: this text isn't any of the step forms, so nothing is checked here and the goal stays open. In the stepper, the write box here offers the steps that apply to this goal.", + examples: [], +}; + +// Sequencing + +let seq = (~fst_id: Id.t, ~snd_id: Id.t): Simple.t => { + let (p1, p2) = (proof("step"), proof("proof")); + { + group_id: ProofSeqStep, + form_id: ProofSeqStep, + abstract: ( + [p1, space(), proof_seq(), space(), p2], + [(Piece.id(p1), fst_id), (Piece.id(p2), snd_id)], + ), + explanation: + sprintf( + "Runs the [*first step*](%s) on the goal, then gives the goal it leaves to the [*rest of the proof*](%s). A proof is a chain of steps, each replacing the goal with one that is enough to prove it, until the goal is `true`.", + fst_id |> Id.to_string, + snd_id |> Id.to_string, + ), + examples: [ + { + sub_id: ProofSeq1, + term: + mk_example( + "theorem t = 1 + 4 == 5 proof from 1 + 4 do step end; step in 0", + ), + message: "The first step evaluates `1 + 4`, leaving the goal `5 == 5`; the second evaluates that to `true`.", + }, + ], + }; +}; + +// Citation: rewrite / rewrite <-, with and without `with` + +let axiom = (~name_id: Id.t): Simple.t => { + let nm = exp("fact"); + { + group_id: ProofAxiomStep, + form_id: ProofAxiomStep, + abstract: ([mk_axiom([slot(nm)])], [(Piece.id(nm), name_id)]), + explanation: + sprintf( + "Uses the [*fact*](%s) — a theorem, a builtin rule, or a fact in scope such as `assume`, `case_eq`, `ih_t` or `have` — as a rule: on a goal that matches its left side, replaces the goal with its right side; inside a `from`, rewrites just the focused part. A fact that is a proposition `P` rather than an equation reads as `P == true`, so it rewrites `P` to `true`. A name means the nearest fact with that name; `alias` reaches one that a nearer fact hides. A rule with `==>` conditions adds them as side conditions of this step. Add `with x = e` when matching can't determine one of the rule's variables.", + name_id |> Id.to_string, + ), + examples: [ + { + sub_id: ProofAxiom1, + term: + mk_example( + "theorem t = (true && false) == (false && true) proof from true && false do rewrite and_comm end end; rewrite refl end in 0", + ), + message: "`and_comm` is a builtin rule, `a && b == b && a`. Rewriting the focused `true && false` with it makes the two sides equal, and `refl` closes the goal.", + }, + ], + }; +}; + +let axiom_with = (~name_id: Id.t, ~var_id: Id.t, ~inst_id: Id.t): Simple.t => { + let (nm, vr, it) = (exp("fact"), exp("x"), exp("e")); + { + group_id: ProofAxiomStep, + form_id: ProofAxiomStep, + abstract: ( + [mk_axiom_with([slot(nm), slot(vr), slot(it)])], + [ + (Piece.id(nm), name_id), + (Piece.id(vr), var_id), + (Piece.id(it), inst_id), + ], + ), + explanation: + sprintf( + "Uses the [*fact*](%s) as `rewrite` does, with its [*variable*](%s) set to the [*value*](%s) before matching. Write it when the variable appears only in the rule's conditions, so matching the goal can't determine it. The value must visibly terminate, and its own side conditions, such as `e != 0` for a divisor, are added to this step.", + name_id |> Id.to_string, + var_id |> Id.to_string, + inst_id |> Id.to_string, + ), + examples: [ + { + sub_id: ProofAxiomWith1, + term: + mk_example( + "let f = fun x -> x + 1 in\ntheorem lem = forall n: Int -> n == 1 ==> f(2) == 3 proof assume n == 1 => from f(2) do step end; from 2 + 1 do step end; step in\ntheorem g = f(2) == 3 proof from f(2) do rewrite lem with n = 1 end end; step in 0", + ), + message: "`lem`'s variable `n` appears only in its condition, so matching `f(2)` can't determine it, and without `with` the step is refused. `with n = 1` sets it; the condition `1 == 1` is this step's side condition, which evaluation closes.", + }, + ], + }; +}; + +let axiomrev = (~name_id: Id.t): Simple.t => { + let nm = exp("fact"); + { + group_id: ProofAxiomRevStep, + form_id: ProofAxiomRevStep, + abstract: ( + [mk_axiom([[space(), mk_rewrite_back(), ...slot(nm)]])], + [(Piece.id(nm), name_id)], + ), + explanation: + sprintf( + "`rewrite` right to left: on a goal that matches the [*fact*](%s)'s right side, replaces the goal with its left side; inside a `from`, rewrites just the focused part. On a fact that is a proposition `P`, it rewrites `true` to `P`; since `true` is everywhere, that is only done for a fact you name.", + name_id |> Id.to_string, + ), + examples: [ + { + sub_id: ProofAxiomRev1, + term: + mk_example( + "theorem t = (true && false) == (false && true) proof from false && true do rewrite <- and_comm end end; rewrite refl end in 0", + ), + message: "`and_comm` states `a && b == b && a`. Right to left on the focused `false && true`, it gives `true && false`, so the two sides are equal and `refl` closes the goal.", + }, + ], + }; +}; + +let axiomrev_with = (~name_id: Id.t, ~var_id: Id.t, ~inst_id: Id.t): Simple.t => { + let (nm, vr, it) = (exp("fact"), exp("x"), exp("e")); + { + group_id: ProofAxiomRevStep, + form_id: ProofAxiomRevStep, + abstract: ( + [ + mk_axiom_with([ + [space(), mk_rewrite_back(), ...slot(nm)], + slot(vr), + slot(it), + ]), + ], + [ + (Piece.id(nm), name_id), + (Piece.id(vr), var_id), + (Piece.id(it), inst_id), + ], + ), + explanation: + sprintf( + "`rewrite <-` with the [*fact*](%s)'s [*variable*](%s) set to the [*value*](%s) before matching. Matching a rule's right side often leaves more of its variables undetermined than matching its left, so this direction needs `with` more often. The value is checked as for `rewrite ... with`.", + name_id |> Id.to_string, + var_id |> Id.to_string, + inst_id |> Id.to_string, + ), + examples: [ + { + sub_id: ProofAxiomRevWith1, + term: + mk_example( + "let f = fun x -> x + 1 in\ntheorem lem = forall n: Int -> n == 1 ==> f(2) == 3 proof assume n == 1 => from f(2) do step end; from 2 + 1 do step end; step in\ntheorem g = 3 == f(2) proof from 3 do rewrite <- lem with n = 1 end end; rewrite refl end in 0", + ), + message: "Right to left, `lem` turns the `3` into `f(2)`, so the two sides are equal. `lem`'s `n` appears in neither side, so `with n = 1` is what lets it apply; its condition `1 == 1` is this step's side condition.", + }, + ], + }; +}; + +// Algebra / step / focus + +let algebra = (~with_id: Id.t): Simple.t => { + let wi = exp("e"); + { + group_id: ProofRewriteStep, + form_id: ProofRewriteStep, + abstract: ( + [mk_algebra_step([slot(wi)])], + [(Piece.id(wi), with_id)], + ), + explanation: + sprintf( + "Replaces the goal, or the focused part inside a `from`, with the [*replacement*](%s), and checks with computer algebra that the two are equal. The algebra treats numbers as a field, so every division or power the rewrite moves across adds a side condition (a divisor `e != 0`, an exponent `i >= 0`). On Float terms the step is refused: the field laws don't hold for floating point.", + with_id |> Id.to_string, + ), + examples: [ + { + sub_id: ProofRewrite1, + term: + mk_example( + "theorem t = 1 + 1 == 2 proof from 1 + 1 do algebra 2 end end; step in 0", + ), + message: "Rewrites the focused `1 + 1` to `2`, leaving `2 == 2`, which `step` evaluates to `true`.", + }, + ], + }; +}; + +let eval_step: Simple.t = { + group_id: ProofEvalStep, + form_id: ProofEvalStep, + abstract: ([mk_eval_step([])], []), + explanation: "Takes one evaluation step at the root of the goal, or of the focused part inside a `from`: unfolds a definition, applies a function, or takes a branch. A function or `let` there takes its argument as it is, value or not, so `(fun x -> x + 1)(2 + 3)` becomes `2 + 3 + 1`. Otherwise, if the root can't step yet, usually because its parts aren't values, the step is refused: focus on a part that can. The step adds no side condition.", + examples: [ + { + sub_id: ProofEval1, + term: + mk_example( + "theorem t = 2 + 3 == 5 proof from 2 + 3 do step end; step in 0", + ), + message: "The root `2 + 3 == 5` can't step while `2 + 3` isn't a value, so the first step focuses on `2 + 3` and evaluates it to `5`. The second evaluates `5 == 5` to `true`.", + }, + ], +}; + +let focus = (~selector_id: Id.t, ~body_id: Id.t): Simple.t => { + let (sl, bd) = (exp("selector"), proof("steps")); + { + group_id: ProofFocusStep, + form_id: ProofFocusStep, + abstract: ( + [mk_focus([slot(sl), slot(bd)])], + [(Piece.id(sl), selector_id), (Piece.id(bd), body_id)], + ), + explanation: + sprintf( + "Focuses on the first part of the goal that matches the [*selector*](%s), or the nth with `at n`, counting from 1 left to right, and runs the [*steps*](%s) on that part alone. Their result goes back into the goal in its place. In the selector, `$e` matches any expression, `$v` any value and `$x` any variable. It can match under a `fun`, a `forall`, a `let` body or a case arm; there the variables bound around it are fixed, unknown values, as under `forall x =>`, so facts about an outer variable of the same name don't apply. The steps' side conditions are their own.", + selector_id |> Id.to_string, + body_id |> Id.to_string, + ), + examples: [ + { + sub_id: ProofFocus1, + term: + mk_example( + "theorem t = (1 + 2) + (3 + 4) == 10 proof from $v + $v at 2 do step end; from $v + $v do step end; from 3 + 7 do step end; step in 0", + ), + message: "`$v + $v` matches an addition of two values. `at 2` picks the second, so the first focus evaluates `3 + 4`, leaving `(1 + 2) + 7 == 10`; the second evaluates `1 + 2`. Then `3 + 7` evaluates to `10`, and `10 == 10` to `true`.", + }, + ], + }; +}; + +// Case analysis and induction + +let cases = (~scrut_id: Id.t): Simple.t => { + let (sc, pt, bd) = (exp("e"), pat("p"), proof("proof")); + { + group_id: ProofCasesStep, + form_id: ProofCasesStep, + abstract: ( + [ + mk_cases([ + [space(), sc, space(), mk_proof_rule([slot(pt)]), space(), bd], + ]), + ], + [(Piece.id(sc), scrut_id)], + ), + explanation: + sprintf( + "Splits the goal into one case per pattern of the [*expression*](%s), which can be any expression. In each case the expression is replaced by the pattern in the goal, and the fact `case_eq` states `expression == pattern`. The patterns must cover the expression's type, its type must be known, and a computed expression must visibly terminate; a split with no cases covers only a type with no values. Cases give no `ih_` facts: for those, use `induction`. A nested split's `case_eq` hides the outer one: write `alias h = case_eq =>` at the top of a case to keep its equation available as `h` in splits nested inside.", + scrut_id |> Id.to_string, + ), + examples: [ + { + sub_id: ProofCases1, + term: + mk_example( + "let sign = fun n -> if n > 0 then 1 else 0 in\ntheorem t = forall n: Int -> sign(n) <= 1 proof from sign(n) do step end; cases n > 0\n| true => from if true then 1 else 0 do step end; step\n| false => from if false then 1 else 0 do step end; step\nend in 0", + ), + message: "Unfolding `sign(n)` leaves an `if` on `n > 0`. In the `true` case that test is `true` in the goal, so the `if` takes its first branch; in the `false` case, its second. Either way the result is at most `1`.", + }, + ], + }; +}; + +let induction = (~scrut_id: Id.t): Simple.t => { + let (sc, pt, bd) = (exp("e"), pat("p"), proof("proof")); + { + group_id: ProofInductionStep, + form_id: ProofInductionStep, + abstract: ( + [ + mk_induction([ + [space(), sc, space(), mk_proof_rule([slot(pt)]), space(), bd], + ]), + ], + [(Piece.id(sc), scrut_id)], + ), + explanation: + sprintf( + "Splits the goal into one case per pattern of the [*expression*](%s), as `cases` does, and in each case adds a fact for every variable of the expression's own type, named after it: `ih_t` for a tail `t`. That fact is the goal with the variable in place of the expression. The patterns must cover the type. A computed expression is first replaced by a fresh variable, so there is no `case_eq`, and facts that mention the expression leave scope in the cases: `revert` a fact before the induction to keep it. Write `generalize` first to get `ih_` facts that are `forall`s, which can be used at other values. An `ih_` fact hides an outer one of the same name; `alias` keeps the outer one.", + scrut_id |> Id.to_string, + ), + examples: [ + { + sub_id: ProofInduction1, + term: + mk_example( + "type Nt = +Z+S(Nt) in\nlet pos = fun e -> case e | Z => true | S(b) => true end in\ntheorem t = forall e: Nt -> pos(e) proof induction e\n| Z => from pos(Z) do step end\n| S(b) => revert pos(b) => from pos(b) do rewrite ih_b end end; from true ==> pos(S(b)) do step end; from pos(S(b)) do step end\nend in 0", + ), + message: "The two cases cover `Nt`. The base case evaluates outright; the step case uses the fact `ih_b`, which states the goal for `b`.", + }, + ], + }; +}; + +// Binder manipulation + +let forall_step = (~pat_id: Id.t, ~body_id: Id.t): Simple.t => { + let (pt, bd) = (pat("x"), proof_body()); + { + group_id: ProofForallStep, + form_id: ProofForallStep, + abstract: ( + [mk_proof_forall([slot(pt)]), space(), bd], + [(Piece.id(pt), pat_id), (Piece.id(bd), body_id)], + ), + explanation: + sprintf( + "Names the [*variable*](%s) of a `forall` goal; the [*rest of the proof*](%s) proves the body for it, an unknown value. A theorem's outer `forall`s are named for you, so this is for a `forall` a later goal starts with, such as after `assume` or `generalize`.", + pat_id |> Id.to_string, + body_id |> Id.to_string, + ), + examples: [ + { + sub_id: ProofForall1, + term: + mk_example( + "theorem t = true ==> (forall x: Int -> x == x) proof assume true => forall x => rewrite refl end in 0", + ), + message: "`assume true` leaves the goal `forall x: Int -> x == x`; `forall x` names its variable, and `refl` closes `x == x`.", + }, + ], + }; +}; + +/* `funext x => `: functional extensionality as an intro rule + rather than an axiom (an axiom is a rewrite equality, and funext as + one would quantify over functions at unknown types). */ +let funext_step = (~pat_id: Id.t, ~body_id: Id.t): Simple.t => { + let (pt, bd) = (pat("x"), proof_body()); + { + group_id: ProofFunextStep, + form_id: ProofFunextStep, + abstract: ( + [mk_proof_funext([slot(pt)]), space(), bd], + [(Piece.id(pt), pat_id), (Piece.id(bd), body_id)], + ), + explanation: + sprintf( + "Turns a goal `f == g` between two functions into the goal that they give equal results for the named [*argument*](%s), an unknown value: `fun x -> x + 1` and `fun x -> 1 + x` give `x + 1 == 1 + x`. The [*rest of the proof*](%s) proves that. One argument per `funext`: a function of two arguments needs two.", + pat_id |> Id.to_string, + body_id |> Id.to_string, + ), + examples: [ + { + sub_id: ProofFunext1, + term: + mk_example( + "theorem t = (fun x -> x + 1) == (fun x -> 1 + x) proof funext x => from x + 1 do algebra 1 + x end end; from 1 + x == 1 + x do rewrite refl end end in 0", + ), + message: "`funext x` turns the equation between functions into `x + 1 == 1 + x`, which `algebra` and `refl` close.", + }, + ], + }; +}; + +let assume = (~exp_id: Id.t, ~body_id: Id.t): Simple.t => { + let (e, bd) = (exp("e"), proof_body()); + { + group_id: ProofAssumeStep, + form_id: ProofAssumeStep, + abstract: ( + [mk_assume([slot(e)]), space(), bd], + [(Piece.id(e), exp_id), (Piece.id(bd), body_id)], + ), + explanation: + sprintf( + "On a goal `P ==> Q` whose `P` is the [*proposition*](%s), removes `P` from the goal and makes it a fact, named `assume`, for the [*rest of the proof*](%s), which proves `Q`. On any other goal the step is refused; `have` adds a fact to any goal. A nested `assume` takes the name `assume` again and hides this one: write `assume = ` to keep both available.", + exp_id |> Id.to_string, + body_id |> Id.to_string, + ), + examples: [ + { + sub_id: ProofAssume1, + term: + mk_example( + "theorem t = forall n: Int -> n == 1 ==> n == 1 proof assume n == 1 => from n do rewrite assume end end; rewrite refl end in 0", + ), + message: "The proposition is the goal's `P`, so the goal becomes `n == 1`. The fact `assume` rewrites `n` to `1`, and `refl` closes `1 == 1`.", + }, + ], + }; +}; + +let generalize = (~exp_id: Id.t, ~body_id: Id.t): Simple.t => { + let (e, bd) = (exp("x"), proof_body()); + { + group_id: ProofGeneralizeStep, + form_id: ProofGeneralizeStep, + abstract: ( + [mk_generalize([slot(e)]), space(), bd], + [(Piece.id(e), exp_id), (Piece.id(bd), body_id)], + ), + explanation: + sprintf( + "Turns the named [*variable*](%s) back into a `forall`: the [*rest of the proof*](%s) proves `forall x -> goal`. Before `induction`, this makes the `ih_` facts `forall`s, so they can be used at values other than the one in hand. Facts that mention the variable (`assume`, `case_eq`, earlier `ih_` facts) leave scope inside, since they are about the old value.", + exp_id |> Id.to_string, + body_id |> Id.to_string, + ), + examples: [ + { + sub_id: ProofGeneralize1, + term: + mk_example( + "theorem t = forall n: Int -> n + 0 == n proof generalize n => forall n => from n + 0 do algebra n end end; rewrite refl end in 0", + ), + message: "`generalize n` turns the goal back into `forall n -> n + 0 == n`, and `forall n` names the variable again.", + }, + ], + }; +}; + +// Revert + +let revert = (~exp_id: Id.t, ~body_id: Id.t): Simple.t => { + let (e, bd) = (exp("fact"), proof_body()); + { + group_id: ProofRevertStep, + form_id: ProofRevertStep, + abstract: ( + [mk_revert([slot(e)]), space(), bd], + [(Piece.id(e), exp_id), (Piece.id(bd), body_id)], + ), + explanation: + sprintf( + "Moves the [*fact*](%s), given by name or written out, back into the goal: the [*rest of the proof*](%s) proves `fact ==> goal`. It adds no side condition, and the fact stays in scope. It lets steps work on the fact: rewrite the antecedent to `true` and drop it, or to `false`, and the implication is `true`.", + exp_id |> Id.to_string, + body_id |> Id.to_string, + ), + examples: [ + { + sub_id: ProofRevert1, + term: + mk_example( + "type Nt = +Z+S(Nt) in\nlet pos = fun e -> case e | Z => true | S(b) => true end in\ntheorem t = forall e: Nt -> pos(e) proof induction e\n| Z => from pos(Z) do step end\n| S(b) => revert pos(b) => from pos(b) do rewrite ih_b end end; from true ==> pos(S(b)) do step end; from pos(S(b)) do step end\nend in 0", + ), + message: "In the step case the fact `pos(b)` goes into the goal, giving `pos(b) ==> pos(S(b))`. Rewriting it with `ih_b` makes the antecedent `true`, and evaluation drops it.", + }, + ], + }; +}; + +let revert_with = + (~exp_id: Id.t, ~var_id: Id.t, ~inst_id: Id.t, ~body_id: Id.t): Simple.t => { + let (e, vr, it, bd) = (exp("fact"), exp("x"), exp("e"), proof_body()); + { + group_id: ProofRevertStep, + form_id: ProofRevertStep, + abstract: ( + [mk_revert_with([slot(e), slot(vr), slot(it)]), space(), bd], + [ + (Piece.id(e), exp_id), + (Piece.id(vr), var_id), + (Piece.id(it), inst_id), + (Piece.id(bd), body_id), + ], + ), + explanation: + sprintf( + "Moves one instance of the [*fact*](%s) into the goal: the fact must be a `forall` over the [*variable*](%s), which is set to the [*value*](%s), and the [*rest of the proof*](%s) gets that instance as an antecedent. The value must visibly terminate, and its side conditions are added here. This is how a `forall` fact, such as an `ih_` fact after `generalize`, is used at a value other than its own.", + exp_id |> Id.to_string, + var_id |> Id.to_string, + inst_id |> Id.to_string, + body_id |> Id.to_string, + ), + examples: [ + { + sub_id: ProofRevertWith1, + term: + mk_example( + "let f = fun x -> x + 1 in\ntheorem p = forall n: Int -> n + 0 == n proof from n + 0 do algebra n end end; rewrite refl end in\ntheorem g = f(2) == 3 proof revert p with n = 5 => from 5 + 0 do step end; from 5 == 5 do step end; from true ==> f(2) == 3 do step end; from f(2) do step end; from 2 + 1 do step end; from 3 == 3 do step end in 0", + ), + message: "`revert p with n = 5` puts the instance `5 + 0 == 5`, not the `forall`, into the goal. Evaluating it to `true` lets `step` drop the implication, leaving the original goal.", + }, + ], + }; +}; + +// Have + +let have = (~exp_id: Id.t, ~sub_id: Id.t, ~body_id: Id.t): Simple.t => { + let (e, sub, bd) = (exp("e"), proof("subproof"), proof_body()); + { + group_id: ProofHaveStep, + form_id: ProofHaveStep, + abstract: ( + [mk_have([slot(e), slot(sub)]), space(), bd], + [ + (Piece.id(e), exp_id), + (Piece.id(sub), sub_id), + (Piece.id(bd), body_id), + ], + ), + explanation: + sprintf( + "Proves the [*proposition*](%s) in the [*subproof*](%s) and makes it a fact, named `have`, for the [*rest of the proof*](%s). It works on any goal. While the subproof is unfinished, the proposition is a side condition instead, and the theorem isn't proven until it is closed. Write `have = proof ...` to give the fact a name.", + exp_id |> Id.to_string, + sub_id |> Id.to_string, + body_id |> Id.to_string, + ), + examples: [ + { + sub_id: ProofHave1, + term: + mk_example( + "theorem t = forall z: Int -> z > 0 ==> z / z == 1 proof assume z > 0 => have z != 0 proof rewrite nonzero_of_pos end => from z / z do algebra 1 end end; rewrite refl end in 0", + ), + message: "The subproof derives `z != 0` from the assumption with the builtin rule `nonzero_of_pos`. That fact closes the side condition `z != 0` of `algebra 1` on `z / z`.", + }, + ], + }; +}; + +// Hypothesis naming: the named forms and `alias` + +let have_named = + (~name_id: Id.t, ~exp_id: Id.t, ~sub_id: Id.t, ~body_id: Id.t): Simple.t => { + let (nm, e, sub, bd) = ( + pat("h"), + exp("e"), + proof("subproof"), + proof_body(), + ); + { + group_id: ProofHaveNamedStep, + form_id: ProofHaveNamedStep, + abstract: ( + [mk_have_named([slot(nm), slot(e), slot(sub)]), space(), bd], + [ + (Piece.id(nm), name_id), + (Piece.id(e), exp_id), + (Piece.id(sub), sub_id), + (Piece.id(bd), body_id), + ], + ), + explanation: + sprintf( + "Proves the [*proposition*](%s) in the [*subproof*](%s) and makes it a fact for the [*rest of the proof*](%s) under the [*name*](%s) instead of `have`. Otherwise it is an unnamed `have`. A nested `have` takes the name `have` again and hides an outer one, but not this one. The name is only for the proof: it names a fact, not a value.", + exp_id |> Id.to_string, + sub_id |> Id.to_string, + body_id |> Id.to_string, + name_id |> Id.to_string, + ), + examples: [ + { + sub_id: ProofHaveNamed1, + term: + mk_example( + "theorem t = forall z: Int -> z > 0 ==> 8 / z == 8 / z proof assume z > 0 => have nz = z != 0 proof rewrite nonzero_of_pos end => from 8 / z == 8 / z do rewrite refl end end in 0", + ), + message: "The subproof derives `z != 0` from the assumption, and the rest of the proof can use it as `nz`. That fact closes the division's side condition `z != 0`.", + }, + ], + }; +}; + +let assume_named = (~name_id: Id.t, ~exp_id: Id.t, ~body_id: Id.t): Simple.t => { + let (nm, e, bd) = (pat("h"), exp("e"), proof_body()); + { + group_id: ProofAssumeNamedStep, + form_id: ProofAssumeNamedStep, + abstract: ( + [mk_assume_named([slot(nm), slot(e)]), space(), bd], + [ + (Piece.id(nm), name_id), + (Piece.id(e), exp_id), + (Piece.id(bd), body_id), + ], + ), + explanation: + sprintf( + "Makes the [*proposition*](%s) a fact for the [*rest of the proof*](%s) under the [*name*](%s) instead of `assume`. As for `assume`, the goal must be `P ==> Q` with the proposition as `P`. A nested `assume` takes the name `assume` again and hides an outer one, but not this one, so the fact stays available however deep the proof goes. The name is only for the proof: it names a fact, not a value.", + exp_id |> Id.to_string, + body_id |> Id.to_string, + name_id |> Id.to_string, + ), + examples: [ + { + sub_id: ProofAssumeNamed1, + term: + mk_example( + "theorem t = forall x: Int -> forall y: Int -> x == 1 ==> y == 2 ==> x + y == 3 proof assume x == 1 => assume hy = y == 2 => from x do rewrite assume end end; from y do rewrite hy end end; from 1 + 2 do step end; step in 0", + ), + message: "Naming the second assumption `hy` leaves the first available as `assume`. Unnamed, the second would take that name and hide the first.", + }, + ], + }; +}; + +let alias = (~name_id: Id.t, ~exp_id: Id.t, ~body_id: Id.t): Simple.t => { + let (nm, e, bd) = (pat("h"), exp("fact"), proof_body()); + { + group_id: ProofAliasStep, + form_id: ProofAliasStep, + abstract: ( + [mk_alias([slot(nm), slot(e)]), space(), bd], + [ + (Piece.id(nm), name_id), + (Piece.id(e), exp_id), + (Piece.id(bd), body_id), + ], + ), + explanation: + sprintf( + "Gives a fact in scope a second [*name*](%s) for the [*rest of the proof*](%s). The [*fact*](%s) is given as for `revert`: by name, or written out. Nothing else changes: no side condition, and the goal stays the same. Its use is to keep a fact available when a later step will hide its name: alias an outer `case_eq` at the top of a case before a nested split, or an `assume` before another `assume`. Writing the proposition out is the only way to reach a fact that is already hidden.", + name_id |> Id.to_string, + body_id |> Id.to_string, + exp_id |> Id.to_string, + ), + examples: [ + { + sub_id: ProofAlias1, + term: + mk_example( + "theorem t = forall x: Int -> forall y: Int -> x == 1 ==> y == 2 ==> x + y == 3 proof assume x == 1 => alias hx = assume => assume y == 2 => from x do rewrite hx end end; from y do rewrite assume end end; from 1 + 2 do step end; step in 0", + ), + message: "The second `assume` takes the name `assume` and hides the first. Aliasing the first as `hx` beforehand keeps it available.", + }, + ], + }; +}; + +// Dispatch + +/* Total over the Proof sort: the compiler is the completeness check that + no prover form falls back to a generic message. */ +let rec single = (p: Proof.t): Simple.t => + switch (p.term) { + | EmptyHole => empty_hole + | MultiHole(_) => multi_hole + | Invalid(_) => invalid + /* Grouping only: explain the form inside the parens. */ + | Parens(inner) => single(inner) + | Seq(p1, p2) => seq(~fst_id=Proof.rep_id(p1), ~snd_id=Proof.rep_id(p2)) + | AxiomStep({direction, equality, instantiation}) => + let name_id = Exp.rep_id(equality); + switch (direction, instantiation) { + | (Right, None) => axiom(~name_id) + | (Left, None) => axiomrev(~name_id) + | (Right, Some((v, i))) => + axiom_with(~name_id, ~var_id=Exp.rep_id(v), ~inst_id=Exp.rep_id(i)) + | (Left, Some((v, i))) => + axiomrev_with(~name_id, ~var_id=Exp.rep_id(v), ~inst_id=Exp.rep_id(i)) + }; + | AlgebriteStep(e) => algebra(~with_id=Exp.rep_id(e)) + | EvalStep => eval_step + | Focus({selector, body, _}) => + focus(~selector_id=Exp.rep_id(selector), ~body_id=Proof.rep_id(body)) + | Cases(scrut, _cases) => cases(~scrut_id=Exp.rep_id(scrut)) + | Induction(scrut, _cases) => induction(~scrut_id=Exp.rep_id(scrut)) + | Forall(pat, body) => + forall_step(~pat_id=Pat.rep_id(pat), ~body_id=Proof.rep_id(body)) + | Funext(pat, body) => + funext_step(~pat_id=Pat.rep_id(pat), ~body_id=Proof.rep_id(body)) + | Assume(e, None, body) => + assume(~exp_id=Exp.rep_id(e), ~body_id=Proof.rep_id(body)) + | Assume(e, Some(h), body) => + assume_named( + ~name_id=Pat.rep_id(h), + ~exp_id=Exp.rep_id(e), + ~body_id=Proof.rep_id(body), + ) + | Alias(h, e, body) => + alias( + ~name_id=Pat.rep_id(h), + ~exp_id=Exp.rep_id(e), + ~body_id=Proof.rep_id(body), + ) + | Generalize(e, body) => + generalize(~exp_id=Exp.rep_id(e), ~body_id=Proof.rep_id(body)) + | Revert(e, None, body) => + revert(~exp_id=Exp.rep_id(e), ~body_id=Proof.rep_id(body)) + | Revert(e, Some((v, i)), body) => + revert_with( + ~exp_id=Exp.rep_id(e), + ~var_id=Exp.rep_id(v), + ~inst_id=Exp.rep_id(i), + ~body_id=Proof.rep_id(body), + ) + | Have(e, None, sub, body) => + have( + ~exp_id=Exp.rep_id(e), + ~sub_id=Proof.rep_id(sub), + ~body_id=Proof.rep_id(body), + ) + | Have(e, Some(h), sub, body) => + have_named( + ~name_id=Pat.rep_id(h), + ~exp_id=Exp.rep_id(e), + ~sub_id=Proof.rep_id(sub), + ~body_id=Proof.rep_id(body), + ) + }; diff --git a/src/web/app/explainthis/data/ProofObjectExp.re b/src/web/app/explainthis/data/ProofObjectExp.re deleted file mode 100644 index b158ae344b..0000000000 --- a/src/web/app/explainthis/data/ProofObjectExp.re +++ /dev/null @@ -1,24 +0,0 @@ -open Haz3lcore; -open Example; -open ExplainThisForm; - -let typ = typ("t"); -let proof_of_exp_coloring_ids = (~typ_id: Id.t): list((Id.t, Id.t)) => [ - (Piece.id(typ), typ_id), -]; -let proof_of_exp_form = [mk_proof_of([[space(), typ, space()]])]; -let proof_of_exp = (~typ_id: Id.t): form => { - id: ProofObjectExp, - syntactic_form: proof_of_exp_form, - colorings: proof_of_exp_coloring_ids(~typ_id), - expandable_id: None, - explanation: - sprintf( - "A placeholder for a proof of [*goal*](%s).", - Id.to_string(typ_id), - ), - examples: [], -}; - -let proof_of_exps = (~typ_id: Id.t): group => - singleton(proof_of_exp(~typ_id)); diff --git a/src/web/app/explainthis/data/ProofOfTyp.re b/src/web/app/explainthis/data/ProofOfTyp.re deleted file mode 100644 index fb7a6994ce..0000000000 --- a/src/web/app/explainthis/data/ProofOfTyp.re +++ /dev/null @@ -1,23 +0,0 @@ -open Haz3lcore; -open Example; -open ExplainThisForm; - -let e = exp("e"); -let proof_of_typ_coloring_ids = (~body_id: Id.t): list((Id.t, Id.t)) => [ - (Piece.id(e), body_id), -]; -let proof_of_typ_form = [mk_proof_of([[space(), e, space()]])]; -let proof_of_typ = (~body_id: Id.t): form => { - id: ProofOfTyp, - syntactic_form: proof_of_typ_form, - colorings: proof_of_typ_coloring_ids(~body_id), - expandable_id: None, - explanation: - sprintf( - "This type asserts that the [*enclosed boolean*](%s) is in fact true.", - Id.to_string(body_id), - ), - examples: [], -}; - -let proof_of = (~body_id: Id.t): group => singleton(proof_of_typ(~body_id)); diff --git a/src/web/app/explainthis/data/TheoremExp.re b/src/web/app/explainthis/data/TheoremExp.re index 0f6db27327..6e4537e714 100644 --- a/src/web/app/explainthis/data/TheoremExp.re +++ b/src/web/app/explainthis/data/TheoremExp.re @@ -4,33 +4,51 @@ open ExplainThisForm; let p = pat("p"); let exp_thm = exp("h"); +let pf = proof("?"); let exp_body = exp("e"); let theorem_exp_coloring_ids = - (~body_id: Id.t, ~pat_id: Id.t, ~thm_id: Id.t): list((Id.t, Id.t)) => [ + (~body_id: Id.t, ~pat_id: Id.t, ~thm_id: Id.t, ~proof_id: Id.t) + : list((Id.t, Id.t)) => [ (Piece.id(p), pat_id), (Piece.id(exp_thm), thm_id), + (Piece.id(pf), proof_id), (Piece.id(exp_body), body_id), ]; let theorem_exp_form = [ - mk_theorem([[space(), p, space()], [space(), exp_thm, space()]]), + mk_theorem([ + [space(), p, space()], + [space(), exp_thm, space()], + [space(), pf, space()], + ]), linebreak(), exp_body, ]; -/* `body_id` is not mentioned in the explanation, but the abstract form has an - `e` placeholder for the body, so it is needed to colour it. */ -let theorem_exp = (~pat_id: Id.t, ~thm_id: Id.t, ~body_id: Id.t): form => { +let theorem_exp = + (~pat_id: Id.t, ~thm_id: Id.t, ~proof_id: Id.t, ~body_id: Id.t): form => { id: TheoremExp, syntactic_form: theorem_exp_form, - colorings: theorem_exp_coloring_ids(~body_id, ~pat_id, ~thm_id), + colorings: theorem_exp_coloring_ids(~body_id, ~pat_id, ~thm_id, ~proof_id), expandable_id: None, explanation: sprintf( - "Asserts that the [*goal*](%s) is true in the following expression, and [*names*](%s) the theorem for later reuse.", - Id.to_string(pat_id), + "Asserts that the [*statement*](%s) denotes `true`, checked by the following [*proof*](%s), and binds the [*name*](%s) in the theorem namespace, where later proofs can cite it as a rule. Theorem names are not values: they have no type, they never evaluate, and they shadow only each other. The [*body*](%s) is ordinary code, so using the theorem's name there is an unbound variable.", Id.to_string(thm_id), + Id.to_string(proof_id), + Id.to_string(pat_id), + Id.to_string(body_id), ), - examples: [], + examples: [ + { + sub_id: Theorem, + term: + mk_example( + "theorem lem = 1 + 1 == 2 proof from 1 + 1 do step end; from 2 == 2 do rewrite refl end end in 0", + ), + message: "The statement `1 + 1 == 2` is proven by evaluating the sum and closing the resulting `2 == 2` by reflexivity. `lem` is now citable in the proofs of later theorems; the body is the ordinary expression `0`.", + }, + ], }; -let tests = (~pat_id: Id.t, ~thm_id: Id.t, ~body_id: Id.t): group => - singleton(theorem_exp(~pat_id, ~thm_id, ~body_id)); +let tests = + (~pat_id: Id.t, ~thm_id: Id.t, ~proof_id: Id.t, ~body_id: Id.t): group => + singleton(theorem_exp(~pat_id, ~thm_id, ~proof_id, ~body_id)); diff --git a/src/web/app/inspector/CursorInspector.re b/src/web/app/inspector/CursorInspector.re index 5eed8ffaa9..aa74e926d3 100644 --- a/src/web/app/inspector/CursorInspector.re +++ b/src/web/app/inspector/CursorInspector.re @@ -55,7 +55,44 @@ let ctx_toggle = (~globals: Globals.t): Node.t => //[text("Γ")], ); -let term_view = (~globals: Globals.t, ~force_error=false, ci) => { +/* Whether the expression at the cursor is total, by the proof checker's + * own test, `Totality.check`. It is computed for the cursor only, since + * statics doesn't track totality. The elaborated term is checked, where + * a recursive `let` is the `FixF` the test looks for. A bare `Var` reads + * as total: the checker treats variables as quantified binders. */ +let totality_badge = (ci: Info.t): list(Node.t) => + switch (ci) { + | InfoExp(info) => + let (cls, icon, tooltip) = + switch ( + Totality.check( + ~statics=ProofStatics.empty, + ~ctx=info.ctx, + info.elab_term, + ) + ) { + | Ok () => ("total", Icons.circle_with_check, "total") + | Error(reason) => ("not-total", Icons.circle_with_no_check, reason) + }; + [div(~attrs=[clss(["totality", cls]), Attr.title(tooltip)], [icon])]; + | _ => [] + }; + +/* A proof step with checker marks is styled like a term with a type + * error. */ +let has_proof_error = (ci: Info.t, proof_map: ProofMap.t): bool => + switch (ci) { + | InfoProof(info) => ProofMap.marks_of(info.id, proof_map) != [] + | _ => false + }; + +let term_view = + ( + ~globals: Globals.t, + ~force_error=false, + ~proof_map: ProofMap.t=ProofMap.empty, + ci, + ) => { /* Drv(_) sorts have verbose type-level names like "DrvJdmt"/"DrvProp" via Sort.to_string (needed for pretty-printing `DrvQuoteTy`). For the inspector header we prefer the terse form ("Jdmt", "Prop", ...), @@ -70,20 +107,22 @@ let term_view = (~globals: Globals.t, ~force_error=false, ci) => { } ); let sort_class = Info.is_label(ci) ? "Label" : ci |> Info.class_of; + let is_err = Info.is_error(ci) || has_proof_error(ci, proof_map); div( ~attrs=[ clss( ["ci-header", sort_class] @ ( - force_error || Info.is_error(ci) + force_error || is_err ? [errc] : Info.is_warning(ci) && globals.settings.core.display_warnings ? [warnc] : [okc] ), ), ], - [ - ctx_toggle(~globals), + [ctx_toggle(~globals)] + @ totality_badge(ci) + @ [ div(~attrs=[clss(["term-tag"])], [text(sort_text)]), div(~attrs=[clss(["divider"])], [text("/")]), cls_view(ci), @@ -100,30 +139,20 @@ let elements_noun: Cls.t => string = | Exp(BinOp(Poly(_))) => "Operands" | _ => "Sub-expressions"; -let code_view_settings: Haz3lcore.ExpToSegment.Settings.t = { - secondary: AutoFormat, - parenthesization: Defensive, - label_format: QuoteWhenNecessary, - inline: true, - fold_case_clauses: false, - fold_fn_bodies: `NoFold, - hide_fixpoints: false, - show_ascriptions: true, - show_filters: false, - show_unknown_as_hole: true, - use_literal_lexemes: false, - hole_tiles: false, - project_tables: false, -}; - let view_any = (~globals, any: Any.t) => any - |> CodeViewable.view_any(~globals, ~settings=code_view_settings) + |> CodeViewable.view_any( + ~globals, + ~settings=ProofMarkView.code_view_settings(globals.settings.core), + ) |> code_box_container; let view_type = (~globals, typ: Typ.t) => typ - |> CodeViewable.view_typ(~globals, ~settings=code_view_settings) + |> CodeViewable.view_typ( + ~globals, + ~settings=ProofMarkView.code_view_settings(globals.settings.core), + ) |> code_box_container; let core_mark_err_view = @@ -177,6 +206,7 @@ let core_mark_err_view = }; ( switch (m) { + | DynamicError(err) => [text(InvalidOperationError.err_msg(err))] | BadToken(token) => switch (Haz3lcore.Token.bad_token_cls(token)) { | BadInt => [text("Integer is too large or too small")] @@ -185,6 +215,7 @@ let core_mark_err_view = | BadLabel(label) => [text("Malformed Label: "), view_any(label)] | FreeConstructor(name) => [code(name), text("not found")] + | CompareFun(ty) => [text("values cannot be compared:"), view_type(ty)] | InvalidLabel(name, expected_labels) => switch (expected_labels) { | [] => [ @@ -233,7 +264,6 @@ let core_mark_err_view = text("Duplicate Label:"), label_view(name), ] - | CompareFun(ty) => [text("values cannot be compared:"), view_type(ty)] | ExpectationMismatch({ana, syn}) => expectation_view(~ana, ~syn) | NoMeet(PolyEq, tys) | NoMeet(_, tys) when ana.term == Unknown(SynSwitch) => [ @@ -281,6 +311,13 @@ let core_mark_err_view = | TypParseFailure | TPatShadowsType(_) | TPatNotAVar(_) => [text("Type error")] + | FreeHypothesis(name) => [ + code(name), + text(" is not a hypothesis in scope"), + ] + | AxiomSlotNotHypothesis(_) => [ + text("Axiom slot must be a hypothesis name"), + ] } ) @ ( @@ -308,6 +345,11 @@ let common_warn_view = (~globals, warning: Warning.list_item): list(Node.t) => code("rec " ++ name), text("is defined as itself."), ] + | Exp(ForallOutsideTheorem) => [ + text( + "Warning: forall is a proposition, not a value; it only runs as part of a theorem statement.", + ), + ] }; /* [warnings] when there are any and warnings are displayed, else [ok]. */ @@ -632,6 +674,7 @@ let exp_mark_err_view = ), ); switch (m) { + | DynamicError(err) => div_err([text(InvalidOperationError.err_msg(err))]) | Free(name) => div_err([code(name), text("not found")]) | InexhaustiveMatch(_, inner_marks, example) => let cls_str = Cls.show(cls); @@ -790,12 +833,16 @@ let exp_mark_err_view = | ExpectationMismatch(_) | NoMeet(_) | CompareFun(_) => common_from_core() + | FreeHypothesis(name) => + div_err([code(name), text(" is not a hypothesis in scope")]) + | AxiomSlotNotHypothesis(_) => + div_err([text("Axiom slot must be a hypothesis name")]) }; }; let exp_view = ( - ~globals, + ~globals: Globals.t, ~show_type_colon=true, cls: Cls.t, message: Message.t, @@ -822,41 +869,47 @@ let exp_view = let marks = info.marks; switch (marks != []) { | false => - switch (message) { - | Exp(Default) => - div_ok( - common_ok_view( - ~globals, - ~show_type_colon, - ~lifted_ty, - ~reordered, - ~introduced_labels, - ~inferred_label, - ~label_sort=info.label_sort, - cls, - Message.Syn(info.elab_syn_ty), - ), - ) - | Exp(AnaDeferralConsistent(ana)) => - div_ok([text("Expecting type"), view_type(~globals, ana)]) - | Exp(Common(ok)) => - div_ok( - common_ok_view( - ~globals, - ~show_type_colon, - ~lifted_ty, - ~reordered, - ~introduced_labels, - ~inferred_label, - ~label_sort=info.label_sort, - cls, - ok, - ), - ) - | Pat(_) - | TypOk(_) - | TPatOk(_) => - failwith("CursorInspector.exp_view: expected Message.Exp(...)") + switch (info.warnings) { + /* Non-computable forms outside a theorem: warn instead of the ok view. */ + | [Exp(w), ..._] when globals.settings.core.display_warnings => + div_warn(common_warn_view(~globals, Exp(w))) + | _ => + switch (message) { + | Exp(Default) => + div_ok( + common_ok_view( + ~globals, + ~show_type_colon, + ~lifted_ty, + ~reordered, + ~introduced_labels, + ~inferred_label, + ~label_sort=info.label_sort, + cls, + Message.Syn(info.elab_syn_ty), + ), + ) + | Exp(AnaDeferralConsistent(ana)) => + div_ok([text("Expecting type"), view_type(~globals, ana)]) + | Exp(Common(ok)) => + div_ok( + common_ok_view( + ~globals, + ~show_type_colon, + ~lifted_ty, + ~reordered, + ~introduced_labels, + ~inferred_label, + ~label_sort=info.label_sort, + cls, + ok, + ), + ) + | Pat(_) + | TypOk(_) + | TPatOk(_) => + failwith("CursorInspector.exp_view: expected Message.Exp(...)") + } } | true => switch (Mark.highest(marks)) { @@ -1073,13 +1126,45 @@ let tpat_view = }; }; -let view_of_info = (~globals, ci): list(Node.t) => { - let wrapper = status_view => [term_view(~globals, ci), status_view]; +/* A proof step's goal coming in and going out, where an expression shows + * its type, under the highest-priority mark the checker recorded there. */ +let proof_view = (~globals, ~proof_map: ProofMap.t, info: Info.proof) => { + let view_exp_box = ProofMarkView.view_exp(~globals); + let opt_exp = (label: string, e: option(Exp.t)): list(Node.t) => + switch (e) { + | Some(e) => [text(label), view_exp_box(e)] + | None => [text(label), text("—")] + }; + switch (ProofMap.lookup(info.id, proof_map)) { + | Some({ + incoming, + auto_incoming: _, + auto_outgoing: _, + outgoing, + marks, + obligations: _, + ctx: _, + }) => + let body = opt_exp("in:", incoming) @ opt_exp("out:", outgoing); + switch (ProofMark.highest(marks)) { + | Some(m) => div_err(ProofMarkView.message(~globals, m) @ body) + | None => div_ok(body) + }; + | None => div_ok([text(info.cls |> Cls.show)]) + }; +}; + +let view_of_info = (~globals, ~proof_map: ProofMap.t, ci): list(Node.t) => { + let wrapper = status_view => [ + term_view(~globals, ~proof_map, ci), + status_view, + ]; switch (ci) { | Secondary(_) => wrapper(div([])) | InfoMod({cls, _}) => wrapper(div_ok([text(cls |> Cls.show)])) | InfoSig({cls, _}) => wrapper(div_ok([text(cls |> Cls.show)])) | InfoMPat({cls, _}) => wrapper(div_ok([text(cls |> Cls.show)])) + | InfoProof(info) => wrapper(proof_view(~globals, ~proof_map, info)) | InfoExp({cls, message, _} as ie) => wrapper(exp_view(~globals, cls, message, ie)) | InfoPat({cls, message, _} as ip) => @@ -1092,19 +1177,21 @@ let view_of_info = (~globals, ci): list(Node.t) => { }; }; -let inspector_view = (~globals: Globals.t, ci): Node.t => +let inspector_view = (~globals: Globals.t, ~proof_map, ci): Node.t => { + let is_err = Info.is_error(ci) || has_proof_error(ci, proof_map); div( ~attrs=[ Attr.id("cursor-inspector"), clss([ - Info.is_error(ci) + is_err ? errc : Info.is_warning(ci) && globals.settings.core.display_warnings ? warnc : okc, ]), ], - view_of_info(~globals, ci), + view_of_info(~globals, ~proof_map, ci), ); +}; let projector_error_inspector = ( @@ -1157,7 +1244,8 @@ let view = (~globals: Globals.t, cursor: Cursor.cursor(Editors.Update.t)) => { switch (projector_err) { | Some((_, err)) when !Info.is_error(ci) => bar_view([projector_error_inspector(~globals, ci, err)]) - | _ => bar_view([inspector_view(~globals, ci)]) + | _ => + bar_view([inspector_view(~globals, ~proof_map=cursor.proof_map, ci)]) } }; }; diff --git a/src/web/app/probesystem/ProbeSidebar.re b/src/web/app/probesystem/ProbeSidebar.re index 0586fcd083..674d476a18 100644 --- a/src/web/app/probesystem/ProbeSidebar.re +++ b/src/web/app/probesystem/ProbeSidebar.re @@ -506,7 +506,7 @@ let mode_title = (~explain_this_inject) => { }; let run_button = (~explain_this_inject, ~editor: CodeEditable.Model.t) => { - let measured = editor.editor.syntax.measured; + let measured = Haz3lcore.CachedSyntax.measured(editor.editor.syntax); div( ~attrs=[ clss(["run-button"]), @@ -541,7 +541,7 @@ let render_print_entry = (entry: print_entry): Node.t => ); let printarium_body = (~explain_this_inject, ~editor: CodeEditable.Model.t) => { - let measured = editor.editor.syntax.measured; + let measured = Haz3lcore.CachedSyntax.measured(editor.editor.syntax); /* Determine what entries to display */ let entries = switch (eval_mode_ref^) { diff --git a/src/web/app/sidebar/DebugSidebar.re b/src/web/app/sidebar/DebugSidebar.re index e2030a9866..e032bfc7b1 100644 --- a/src/web/app/sidebar/DebugSidebar.re +++ b/src/web/app/sidebar/DebugSidebar.re @@ -249,6 +249,7 @@ let ctx_entry_node = (~globals, entry: Ctx.entry): Node.t => | TVarEntry({name, kind: Abstract, _}) => ctx_row(text("type " ++ name), None) | LivelitEntry(_) => ctx_row(text("livelit"), None) + | TheoremEntry({name, _}) => ctx_row(text("theorem " ++ name), None) }; let ctx_view_rendered = (~globals, ctx: Ctx.t): Node.t => @@ -304,6 +305,7 @@ let ctx_entry_text = (entry: Ctx.entry): string => "type " ++ name ++ " = " ++ typ_to_text(~settings=code_settings, ty) | TVarEntry({name, kind: Abstract, _}) => "type " ++ name | LivelitEntry(_) => "livelit" + | TheoremEntry({name, _}) => "theorem " ++ name }; let ctx_to_text = (ctx: Ctx.t): string => @@ -562,6 +564,8 @@ let info_view = (~globals, ~raw, ci: Info.t): list(Node.t) => | InfoMPat(m) => mpat_view(~globals, ~raw, m) | Secondary(s) => secondary_view(~globals, s) | InfoDrv(d) => drv_view(~globals, d) + | InfoProof(_) => + section(~globals, "InfoProof", () => [field_str("(proof)", "—")]) }; /* ---- Syntax sections: the syntactic/zipper layer under the cursor, ---- @@ -676,7 +680,10 @@ let editor_fields = (editor: Haz3lcore.Editor.t): list(Node.t) => { [ field_str("root sort", sort_str(editor.root)), field_str("syntax stale", string_of_bool(syntax.old)), - field_str("segment pieces", string_of_int(List.length(syntax.segment))), + field_str( + "segment pieces", + string_of_int(List.length(Haz3lcore.CachedSyntax.segment(syntax))), + ), field_str( "projectors", string_of_int(List.length(syntax.projector_list)), @@ -708,7 +715,10 @@ let syntax_view = (~globals, ~cursor: Cursor.cursor(_)): list(Node.t) => { | None => [] | Some(p) => section(~globals, "Measured", () => - measured_fields(p, editor.syntax.measured) + measured_fields( + p, + Haz3lcore.CachedSyntax.measured(editor.syntax), + ) ) }; let editor_sec = diff --git a/src/web/app/sidebar/ProblemSidebar.re b/src/web/app/sidebar/ProblemSidebar.re index 5fc5b9a8a9..e73f680162 100644 --- a/src/web/app/sidebar/ProblemSidebar.re +++ b/src/web/app/sidebar/ProblemSidebar.re @@ -73,7 +73,8 @@ let problem_status_view = (~globals, ci: Language.Info.t): Node.t => ~attrs=[clss(["problem-description"])], [text(Language.Cls.show(cls))], ) - | Secondary(_) => div([]) + | Secondary(_) + | InfoProof(_) => div([]) }; let line_num_view = diff --git a/src/web/app/sidebar/Sidebar.re b/src/web/app/sidebar/Sidebar.re index 24b65ea6bc..52724c29f4 100644 --- a/src/web/app/sidebar/Sidebar.re +++ b/src/web/app/sidebar/Sidebar.re @@ -285,7 +285,7 @@ let resize_handle = (): Node.t => { let window_width = Dom_html.window##.innerWidth; let persistent_width = 38.9; let new_width = - max(400, window_width - current_x - int_of_float(persistent_width)); + max(300, window_width - current_x - int_of_float(persistent_width)); updateElementStyles(new_width); }; (); diff --git a/src/web/app/sidebar/SidebarModel.re b/src/web/app/sidebar/SidebarModel.re index 6bd7745a58..e3aa463c49 100644 --- a/src/web/app/sidebar/SidebarModel.re +++ b/src/web/app/sidebar/SidebarModel.re @@ -16,7 +16,7 @@ module Settings = { [@deriving (show({with_path: false}), sexp, yojson, enumerate)] type problem_category = Haz3lcore.ProblemCollection.problem_category = - | Syntax | Hole | Static | Warning | Projector; + | Syntax | Hole | Static | Runtime | Warning | Projector; /* Base CSS class for a category */ let category_cls = cat => @@ -24,6 +24,7 @@ module Settings = { | Syntax => "syntax" | Hole => "hole" | Static => "static" + | Runtime => "runtime" | Warning => "warning" | Projector => "projector-error" }; @@ -34,6 +35,7 @@ module Settings = { | Syntax => "Syntax Errors" | Hole => "Holes" | Static => "Static Errors" + | Runtime => "Runtime Errors" | Warning => "Warnings" | Projector => "Projector Errors" }; @@ -44,6 +46,7 @@ module Settings = { | Syntax => "Syntax" | Hole => "Hole" | Static => "Static" + | Runtime => "Runtime" | Warning => "Warning" | Projector => "Projector" }; @@ -53,7 +56,8 @@ module Settings = { let category_badge_severity = cat => switch (cat) { | Syntax - | Static => 2 + | Static + | Runtime => 2 | Projector | Warning => 1 | Hole => 0 @@ -63,7 +67,8 @@ module Settings = { let category_badge_cls = cat => switch (cat) { | Syntax - | Static => "has-errors" + | Static + | Runtime => "has-errors" | Projector | Warning => "has-warnings" | Hole => "has-holes" @@ -73,7 +78,8 @@ module Settings = { let category_badge_label = cat => switch (cat) { | Syntax - | Static => "error" + | Static + | Runtime => "error" | Projector | Warning => "warning" | Hole => "hole" diff --git a/src/web/dune b/src/web/dune index 3e814f5467..63fab7b311 100644 --- a/src/web/dune +++ b/src/web/dune @@ -24,7 +24,7 @@ (name workerServer) (flags (:standard -open Core)) - (modules WorkerServer CoverageHook) + (modules WorkerServer CoverageHook CasJs) (wrapped false) (instrumentation (backend bisect_ppx)) @@ -50,6 +50,7 @@ Worker WorkerServer CoverageHook + CasJs Migrate_exercises) (libraries core diff --git a/src/web/exercises/SyntaxTest.re b/src/web/exercises/SyntaxTest.re index 44cca236af..708d77c777 100644 --- a/src/web/exercises/SyntaxTest.re +++ b/src/web/exercises/SyntaxTest.re @@ -66,7 +66,7 @@ let rec find_fn = (name: string, uexp: Exp.t, l: list(Exp.t)): list(Exp.t) => { switch (uexp.term) { | Let(up, def, body) => l |> find_in_let(name, up, def) |> find_fn(name, body) - | Theorem(up, def, body) => + | Theorem(up, def, _, body) => l |> find_in_let(name, up, def) |> find_fn(name, body) | ListLit(ul) | Tuple(ul) => @@ -84,7 +84,6 @@ let rec find_fn = (name: string, uexp: Exp.t, l: list(Exp.t)): list(Exp.t) => { | TyAlias(_, _, u1) | Use(_, u1) | Test(u1) - | ProofObject(u1) | HintedTest(u1, _) | Closure(_, u1) | Filter(_, u1) => l |> find_fn(name, u1) @@ -231,10 +230,9 @@ let rec var_mention = (name: string, uexp: Exp.t): bool => { | Let(p, def, body) => (var_mention_upat(name, p) ? false : var_mention(name, body)) || var_mention(name, def) - | Theorem(p, thm, body) => + | Theorem(p, thm, _, body) => (var_mention_upat(name, p) ? false : var_mention(name, body)) || var_mention(name, thm) - | ProofObject(e) => var_mention(name, e) | TypFun(_, u, _) | TypAp(u, _) | Test(u) @@ -330,10 +328,9 @@ let rec var_applied = (name: string, uexp: Exp.t): bool => { | Let(p, def, body) => (var_mention_upat(name, p) ? false : var_applied(name, body)) || var_applied(name, def) - | Theorem(p, thm, body) => + | Theorem(p, thm, _, body) => (var_mention_upat(name, p) ? false : var_applied(name, body)) || var_applied(name, thm) - | ProofObject(e) => var_applied(name, e) | TypFun(_, u, _) | Test(u) | HintedTest(u, _) @@ -452,10 +449,9 @@ let rec tail_check = (name: string, uexp: Exp.t): bool => { | Let(p, def, body) => var_mention_upat(name, p) || var_mention(name, def) ? false : tail_check(name, body) - | Theorem(p, thm, body) => + | Theorem(p, thm, _, body) => var_mention_upat(name, p) || var_mention(name, thm) ? false : tail_check(name, body) - | ProofObject(_) => false | ListLit(l) | Tuple(l) => //If l has no recursive calls then true diff --git a/src/web/init/Init.re b/src/web/init/Init.re index 8033865e07..9bb2216f78 100644 --- a/src/web/init/Init.re +++ b/src/web/init/Init.re @@ -6,7 +6,6 @@ let empty_cell_editor_persistent = (~root): CellEditor.Model.persistent => { Zipper.init() |> PersistentZipper.persist |> Editor.Model.mk_persistent(~root), - result: EvalResult.Model.init |> EvalResult.Model.persist, }; let documentation_slides: list((string, PersistentZipper.t)) = @@ -27,10 +26,7 @@ let startup: Lazy.t(PersistentData.t) = |> List.map(~f=((name, content: PersistentZipper.t)) => ( name, - { - editor: content |> Editor.Model.mk_persistent(~root=Exp), - result: EvalResult.Model.init |> EvalResult.Model.persist, - }: CellEditor.Model.persistent, + {editor: content |> Editor.Model.mk_persistent(~root=Exp)}: CellEditor.Model.persistent, ) ), ), diff --git a/src/web/util/CasJs.re b/src/web/util/CasJs.re new file mode 100644 index 0000000000..712991f5cf --- /dev/null +++ b/src/web/util/CasJs.re @@ -0,0 +1,24 @@ +open Js_of_ocaml; + +/* Gives the checker the Algebrite this JS context loads as the global + * `Algebrite`. The page loads it in a module script, which runs after + * the app starts, so it is looked up at each use. Where it comes from + * `script` instead, the script is loaded at the first use, so a program + * with no `algebra` step never loads it. */ +let install = (~script: option(string)=?, ()): unit => { + let script = ref(script); + Language.Cas.run := + ( + input => { + switch (script^) { + | Some(url) => + script := None; + Js.Unsafe.global##importScripts(Js.string(url)); + | None => () + }; + let algebrite = Js.Unsafe.global##.Algebrite; + String.equal(Js.to_string(Js.typeof(algebrite)), "undefined") + ? None : Some(Js.to_string(algebrite##run(Js.string(input)))); + } + ); +}; diff --git a/src/web/util/WorkerServer.re b/src/web/util/WorkerServer.re index bf7ceb1fba..11f2cd4b32 100644 --- a/src/web/util/WorkerServer.re +++ b/src/web/util/WorkerServer.re @@ -10,6 +10,9 @@ module Request = { expr: Language.Exp.t, eval_info_map: Language.EvalInfo.t, prev: Language.EvaluatorState.incr_eval, + /* The generation of the EvalResult request this is. The worker + * ignores it; EvalRequest tags the replies with it. */ + generation: int, }; [@deriving (show, sexp, yojson)] type batch = list((key, value)); @@ -230,7 +233,7 @@ let error_response = exn => }; let evaluate_sync = (req_value: Request.value): Response.value => { - let Request.{expr, eval_info_map, prev} = req_value; + let Request.{expr, eval_info_map, prev, _} = req_value; switch ( Language.Evaluator.evaluate( ~prev, @@ -319,7 +322,7 @@ let planned_reuse: ref([]); let predict_reuse_for_request = ((key, req_value): (key, Request.value)) => { - let Request.{expr, eval_info_map, prev} = req_value; + let Request.{expr, eval_info_map, prev, _} = req_value; let stream = if (!wants_incremental(req_value)) { Language.IncrEval.empty; @@ -366,7 +369,7 @@ let timed_eval: 'a. (unit => 'a) => 'a = }; let start_evaluation = (req_value: Request.value): evaluation_start => { - let Request.{expr, eval_info_map, prev} = req_value; + let Request.{expr, eval_info_map, prev, _} = req_value; let planned = take_planned_reuse(expr); switch ( Language.Evaluator.start_yielding_evaluation( diff --git a/src/web/view/CodeExerciseMode.re b/src/web/view/CodeExerciseMode.re index e7e85ad9d7..5221783d8d 100644 --- a/src/web/view/CodeExerciseMode.re +++ b/src/web/view/CodeExerciseMode.re @@ -383,17 +383,25 @@ module Update = { }; | None => Updated.return_quiet(model) } - | Editor(pos, ResultAction(result_action) as action) + | Editor(pos, (ResultAction(_) | PatchMainEditor(_)) as action) when CodeExercise.is_editable(pos, ~instructor_mode) - || EvalResult.Update.applies_to_read_only(result_action) => + || ( + switch (action) { + | ResultAction(result_action) => + EvalResult.Update.applies_to_read_only(result_action) + | MainEditor(_) + | PatchMainEditor(_) => false + } + ) => let cell = CodeExercise.get_stitched(pos, model.cells); let* new_cell = CellEditor.Update.update(~settings, action, cell); { ...model, cells: CodeExercise.put_stitched(pos, model.cells, new_cell), }; - | Editor(_, ResultAction(_)) => Updated.raise_invalid_action(model) // TODO: I think this case should never happen + | Editor(_, ResultAction(_) | PatchMainEditor(_)) => + Updated.raise_invalid_action(model) // TODO: I think this case should never happen | RefreshStatics => CodeWithStatics.StaticsDebounce.force_on_next := true; model |> Updated.return_quiet(~recalculate=true); @@ -476,6 +484,15 @@ module Update = { model.cells, ); + /* A timeout fails every cell, tagged with the generation each had when + * this batch was enqueued, so a cell that has re-requested since + * ignores it. */ + let timeout_gens = + CodeExercise.map_stitched( + (_, cell: CellEditor.Model.t) => + EvalResult.Model.request_gen(cell.result), + cells, + ); EvalRequest.request( worker_request^, ~pos_of_key=CodeExercise.pos_of_key, @@ -486,14 +503,14 @@ module Update = { _ => ignore( CodeExercise.map_stitched( - (pos, _) => + (pos, gen) => schedule_action( Editor( pos, - ResultAction(UpdateResult(ResultFail(Timeout))), + ResultAction(UpdateResult(gen, ResultFail(Timeout))), ), ), - model.cells, + timeout_gens, ), ), ); diff --git a/src/web/view/ConfigurationMode.re b/src/web/view/ConfigurationMode.re index 1fc9e833eb..7de226a154 100644 --- a/src/web/view/ConfigurationMode.re +++ b/src/web/view/ConfigurationMode.re @@ -397,7 +397,9 @@ module Update = { switch (action) { | CellAction(a) => switch (a) { - | CellEditor.Update.ResultAction(UpdateResult(ResultOk({result, _}))) => + | CellEditor.Update.ResultAction( + UpdateResult(_, ResultOk({result, _})), + ) => let (config_type, _) = Model.get_current_config(model); perform_side_effect(~schedule_global, model, config_type, result); // Continue with normal cell update @@ -498,8 +500,8 @@ module Update = { ~pos_of_key=key => key, ~dispatch, ~on_timeout= - List.iter(~f=((key, _)) => - dispatch(key, UpdateResult(ResultFail(Timeout))) + List.iter(~f=((key, v: WorkerServer.Request.value)) => + dispatch(key, UpdateResult(v.generation, ResultFail(Timeout))) ), ); let model = { diff --git a/src/web/view/ContextInspector.re b/src/web/view/ContextInspector.re index 0bc202df39..9b3c1ed84d 100644 --- a/src/web/view/ContextInspector.re +++ b/src/web/view/ContextInspector.re @@ -66,6 +66,18 @@ let context_entry_view = (~globals, entry: Language.Ctx.entry): Node.t => { view_type(expansion_t), ], ) + | TheoremEntry({name, _}) => + div( + ~attrs=[ + Attr.on_click(_ => globals.inject_global(jump_to(entry))), + clss(["context-entry", "code", "hypothesis-entry"]), + ], + [ + div_name([text(name)]), + div(~attrs=[clss(["seperator"])], [text(":")]), + div(~attrs=[clss(["prop"])], [text("theorem")]), + ], + ) }; }; diff --git a/src/web/view/DerivationExerciseMode.re b/src/web/view/DerivationExerciseMode.re index 505a42c6be..c9323a1f42 100644 --- a/src/web/view/DerivationExerciseMode.re +++ b/src/web/view/DerivationExerciseMode.re @@ -328,7 +328,14 @@ module Update = { }; | None => Updated.return_quiet(model) } - | Editor(pos, ResultAction(UpdateResult(_)) as action) => + | Editor(pos, ResultAction(UpdateResult(_, _)) as action) => + let cell = DerivationExercise.get_stitched(pos, model.cells); + let* new_cell = CellEditor.Update.update(~settings, action, cell); + { + ...model, + cells: DerivationExercise.put_stitched(pos, model.cells, new_cell), + }; + | Editor(pos, PatchMainEditor(_) as action) => let cell = DerivationExercise.get_stitched(pos, model.cells); let* new_cell = CellEditor.Update.update(~settings, action, cell); { @@ -418,6 +425,15 @@ module Update = { stitched_elabs, ); + /* A timeout fails every cell, tagged with the generation each had when + * this batch was enqueued, so a cell that has re-requested since + * ignores it. */ + let timeout_gens = + DerivationExercise.map_stitched( + (_, cell: CellEditor.Model.t) => + EvalResult.Model.request_gen(cell.result), + cells, + ); EvalRequest.request( worker_request^, ~pos_of_key=DerivationExercise.pos_of_key, @@ -428,14 +444,14 @@ module Update = { _ => ignore( DerivationExercise.map_stitched( - (pos, _) => + (pos, gen) => schedule_action( Editor( pos, - ResultAction(UpdateResult(ResultFail(Timeout))), + ResultAction(UpdateResult(gen, ResultFail(Timeout))), ), ), - model.cells, + timeout_gens, ), ), ); @@ -1008,6 +1024,7 @@ module View = { ~caption: option(string)=?, ~subcaption: option(string)=?, ~result_kind=`NoResults, + ~scroll_code=?, this_pos: DerivationExercise.pos, cell: CellEditor.Model.t, ) => { @@ -1023,6 +1040,7 @@ module View = { }, ~inject=a => inject(Editor(this_pos, a)), ~result_kind, + ~scroll_code?, ~caption= switch (caption) { | Some(c) => CellCommon.caption(c, ~rest=?subcaption) @@ -1035,7 +1053,8 @@ module View = { let conclusion_view = (~pos, ~editor) => div( ~attrs=[Attr.class_("deduction-concl")], - [editor_view(pos, editor)], + /* a conclusion's cell is as wide as its code */ + [editor_view(~scroll_code=false, pos, editor)], ); let deduction_view = (~children_node, ~pos, ~res, ~rule, ~editor) => diff --git a/src/web/view/EvalRequest.re b/src/web/view/EvalRequest.re index 81fb6ee5dd..b72725e963 100644 --- a/src/web/view/EvalRequest.re +++ b/src/web/view/EvalRequest.re @@ -3,6 +3,7 @@ * callbacks into EvalResult actions. `dispatch` delivers one action to one * position; `on_timeout` handles a timed-out batch (exercise modes mark * every stitched cell, not just the batch items). */ + let request = ( batch: WorkerServer.Request.batch, @@ -10,7 +11,14 @@ let request = ~dispatch: ('pos, EvalResult.Update.t) => unit, ~on_timeout: WorkerServer.Request.batch => unit, ) - : unit => + : unit => { + /* Replies are tagged with the generation of the request they answer, so + * EvalResult can refuse replies to a request it has since replaced. */ + let gen_of_key = key => + switch (List.Assoc.find(batch, key, ~equal=String.equal)) { + | Some(v: WorkerServer.Request.value) => v.generation + | None => (-1) + }; WorkerClient.request( batch, ~on_result= @@ -24,7 +32,10 @@ let request = }) | Error(e) => ResultFail(e) }; - dispatch(pos_of_key(key), EvalResult.Update.UpdateResult(result)); + dispatch( + pos_of_key(key), + EvalResult.Update.UpdateResult(gen_of_key(key), result), + ); }), ~on_timeout, ~on_ack= @@ -32,10 +43,15 @@ let request = dispatch( pos_of_key(key), EvalResult.Update.UpdateStreamingEval( + gen_of_key(key), Language.IncrEval.outbox_of_completed(stream), ), ) ), ~on_stream=(key, stream) => - dispatch(pos_of_key(key), EvalResult.Update.MergeStreamingEval(stream)) + dispatch( + pos_of_key(key), + EvalResult.Update.MergeStreamingEval(gen_of_key(key), stream), + ) ); +}; diff --git a/src/web/view/ScratchMode.re b/src/web/view/ScratchMode.re index 347ce93282..8bcb78b598 100644 --- a/src/web/view/ScratchMode.re +++ b/src/web/view/ScratchMode.re @@ -558,7 +558,6 @@ let integrate_share = root: Exp, zipper: shared, }, - result: EvalResult.Model.init |> EvalResult.Model.persist, }; let new_sp = Scratchpad.mk_code( @@ -1040,8 +1039,8 @@ module Update = { ~pos_of_key=key => key, ~dispatch, ~on_timeout= - List.iter(~f=((key, _)) => - dispatch(key, UpdateResult(ResultFail(Timeout))) + List.iter(~f=((key, v: WorkerServer.Request.value)) => + dispatch(key, UpdateResult(v.generation, ResultFail(Timeout))) ), ); let new_sp = diff --git a/src/web/view/StepperView.re b/src/web/view/StepperView.re index 3fe80a2cd8..76368c5d84 100644 --- a/src/web/view/StepperView.re +++ b/src/web/view/StepperView.re @@ -1,100 +1,1923 @@ open Util; open Language; +open Poly; + +/* The stepper: a proof drawn as a chain of rows, one per step, each + * showing the goal the step starts from and the step's justification. + * Where a chain is unfinished, its last row holds the write box, where the + * user writes the next step. + * + * The rows are a projection of the proof syntax and the checker's + * ProofMap (StepperRows), walked again on every render. A row changes + * the proof only by patching its syntax (StepperPicker.Patches); the + * next check gives the next rows. The only state is each row's own UI + * state: its goal's editor, which holds the selection, and its write + * box. */ /* This file follows conventions in [docs/ui-architecture.md] */ +module Rows = StepperRows; +module Picker = StepperPicker; + module Model = { [@deriving (show({with_path: false}), sexp, yojson)] - type t = { - cached_elab_subst: Calc.saved(Exp.t), - root: StepperBase.step_model, + type tab = + | Write + | Step + | Strategy; + + /* The write box at the end of an unfinished chain. Its text stays while + * the row exists, and goes with it. */ + [@deriving (show({with_path: false}), sexp, yojson)] + type box = { + /* None until the user picks a tab: then the stepper's default. */ + tab: option(tab), + editor: CodeEditable.Model.t, + /* What Tab takes, for the goal and its selection. */ + ghost: option(Picker.Ghost.t), + /* The search for steps to the typed goal, while the box holds a + * complete expression. */ + search: option(StepSearch.t), + /* The rules' uses listed under the box, while it holds text. */ + suggestions: option(StepSearch.Suggestions.t), + /* The listed item chosen with the arrow keys. */ + chosen: option(int), + /* Counts the searches started and the slices run, so that each + * render of a running search asks for its next slice once. */ + generation: int, + /* Counts the changes to what the box searches for. */ + edits: int, + /* Whether typing has paused since the last edit. Until it has, a + * search that found nothing doesn't say so: the text is likely half + * typed. */ + paused: bool, }; - let init = { - cached_elab_subst: Calc.Pending, - root: StepperBase.init_step, + [@deriving (show({with_path: false}), sexp, yojson)] + type local = { + goal: Picker.Goal.t, + /* For a row where its chain continues. */ + box: option(box), + /* The side conditions shown open, by index into the row's + * `StepperRows.side_conditions`. */ + expanded: list(int), + /* The row's step is written but not checked yet, so `goal` is the + * goal of the row above, shown until the check gives the row its + * own. */ + checking: bool, + /* Where the goal editor's highlights and lines go. */ + deco: StepperEditor.Deco.t, }; + /* A write from a row's box, kept until the steps written are checked. */ [@deriving (show({with_path: false}), sexp, yojson)] - type persistent = {root: StepperBase.persistent_step}; + type write = { + /* The goal of the row written from, which the rows of the steps + * written show until they are checked. */ + from: Picker.Goal.t, + /* The box where the proof goes on, and the tab it opens on: the tab + * written from. That box exists only once the write is reparsed. */ + next: Rows.key, + tab: option(tab), + }; - let persist = (model: t): persistent => { - root: StepperBase.Stepper.persist(model.root), + /* Each row's state, by its key (StepperRows.key). */ + [@deriving (show({with_path: false}), sexp, yojson)] + type t = { + incoming: Id.Map.t(local), + outgoing: Id.Map.t(local), + last_write: option(write), }; - let unpersist = (p: persistent): t => { - { - cached_elab_subst: Calc.Pending, - root: StepperBase.Stepper.unpersist(p.root), + let init = { + incoming: Id.Map.empty, + outgoing: Id.Map.empty, + last_write: None, + }; + + let find = ((id, side): Rows.key, model: t): option(local) => + switch (side) { + | Incoming => Id.Map.find_opt(id, model.incoming) + | Outgoing => Id.Map.find_opt(id, model.outgoing) }; + + let add = ((id, side): Rows.key, local: local, model: t): t => + switch (side) { + | Incoming => { + ...model, + incoming: Id.Map.add(id, local, model.incoming), + } + | Outgoing => { + ...model, + outgoing: Id.Map.add(id, local, model.outgoing), + } + }; + + /* Whether the box's search or suggestions have work left. */ + let running = (box: box): bool => + switch (box.search, box.suggestions) { + | (Some({status: Searching, _}), _) => true + | (_, Some(suggestions)) => !StepSearch.Suggestions.is_done(suggestions) + | (_, None) => false + }; + + /* Whether nothing is typed in the box. */ + let is_empty = (box: box): bool => + switch (Exp.term_of(CodeEditable.Model.get_statics(box.editor).term)) { + | EmptyHole => true + | _ => false + }; +}; + +/* The goal editors drawn last, by row key. A row whose goal editor's + * inputs are all the same objects as when it was drawn gets the same node, + * which the virtual DOM then skips. Kept outside the model, as only the + * view uses it. + * + * A kept node keeps the handlers it was drawn with, so they call those of + * the latest render instead, which each render sets: a click acts on the + * proof as it is, not as it was when the node was drawn. */ +module Drawn = { + type inputs = { + editor: StepperEditor.Model.t, + focused: bool, + settings: Settings.t, + font_metrics: FontMetrics.t, + meta_down: bool, + color_highlights: option(ColorSteps.colorMap), }; - let get_validity = (m: t) => StepperBase.Stepper.get_validity(m.root); + type handlers = { + signal: StepperEditor.View.event => Ui_effect.t(unit), + inject: StepperEditor.Update.t => Ui_effect.t(unit), + keys: Key.t => option(Ui_effect.t(unit)), + }; + + type entry = { + inputs, + node: Virtual_dom.Vdom.Node.t, + current: ref(handlers), + }; + + let entries: Hashtbl.t(Rows.key, entry) = Hashtbl.create(64); + + /* Goal editors drawn again, and reused. */ + let drawn = ref(0); + let reused = ref(0); + + let same = (a: inputs, b: inputs) => + phys_equal(a.editor.editor, b.editor.editor) + && phys_equal(a.editor.deco, b.editor.deco) + && a.editor.hints == b.editor.hints + && a.editor.replacing == b.editor.replacing + && a.editor.previewing == b.editor.previewing + && a.focused == b.focused + && phys_equal(a.settings, b.settings) + && phys_equal(a.font_metrics, b.font_metrics) + && a.meta_down == b.meta_down + && phys_equal(a.color_highlights, b.color_highlights); + + let view = + ( + key: Rows.key, + inputs: inputs, + handlers: handlers, + draw: handlers => Virtual_dom.Vdom.Node.t, + ) + : Virtual_dom.Vdom.Node.t => + switch (Hashtbl.find_opt(entries, key)) { + | Some(entry) when same(entry.inputs, inputs) => + entry.current := handlers; + incr(reused); + entry.node; + | Some(_) + | None => + let current = ref(handlers); + let node = + draw({ + signal: e => current^.signal(e), + inject: a => current^.inject(a), + keys: k => current^.keys(k), + }); + Hashtbl.replace( + entries, + key, + { + inputs, + node, + current, + }, + ); + incr(drawn); + node; + }; + + /* Forgets the rows of `before` that `after` doesn't have. */ + let prune = (~before: Model.t, ~after: Model.t) => { + let forget = (side: Rows.side, kept, id, _) => + if (!Id.Map.mem(id, kept)) { + Hashtbl.remove(entries, (id, side)); + }; + Id.Map.iter(forget(Incoming, after.incoming), before.incoming); + Id.Map.iter(forget(Outgoing, after.outgoing), before.outgoing); + }; }; +/* A row's actions. The stepper's other kind of action, a patch to the + * proof, goes to whoever owns the proof text (`~edit_syntax`). */ module Update = { [@deriving (show({with_path: false}), sexp, yojson)] - type t = StepperBase.step_action; + type action = + | Goal(CodeSelectable.Update.t) + | Tab(Model.tab) + | BoxEditor(CodeEditable.Update.t) + /* Runs a slice of the box's search, if it is still the search of + * that generation. */ + | SearchSlice(int) + /* Typing has paused since the edit counted, unless another came + * after it. */ + | Paused(int) + /* An item listed under the box, by index, or none. */ + | Choose(option(int)) + /* Replaces the box's text with a name it completes to. */ + | Complete(string) + | ToggleCondition(int) + /* A step was written at the row, and the proof goes on at the box + * with this key, which keeps the row's tab. */ + | Wrote(Rows.key); + + [@deriving (show({with_path: false}), sexp, yojson)] + type t = (Rows.key, action); + + /* The box's text is an expression in the goal's scope. */ + let calculate_box = (~settings, goal: Picker.Goal.t, editor) => + CodeEditable.Update.calculate( + ~settings, + ~is_edited=true, + ~is_dynamic_term=true, + ~dynamics=Dynamics.Map.empty, + ~stitch=x => x, + ~ctx=SemanticCtx.get_ctx(goal.ctx), + editor, + ); + + let ghost = (goal: Picker.Goal.t) => + Picker.Ghost.mk(goal, ~selected=Picker.Goal.selected(goal)); + + /* The goal typed into the box, or None while it is empty or + * incomplete. */ + let wanted = (editor: CodeEditable.Model.t): option(Exp.t) => { + let statics = CodeEditable.Model.get_statics(editor); + let rec complete = (e: Exp.t) => + switch (Exp.term_of(e)) { + | EmptyHole + | MultiHole(_) + | Invalid(_) => false + | _ => List.for_all(~f=complete, Occurrence.children(e)) + }; + statics.error_ids == [] && complete(statics.term) + ? Some(statics.elaborated) : None; + }; + + /* The box's text, if it is a single name. */ + let typed_name = (editor: CodeEditable.Model.t): option(string) => + switch (Exp.term_of(CodeEditable.Model.get_statics(editor).term)) { + | Var(x) => Some(x) + | _ => None + }; - let update = (~settings, action, model: Model.t) => { - open Updated; - let* root = StepperBase.Stepper.update(~settings, action, model.root); + /* The part of the goal selected, when it is less than all of it. */ + let selected_part = (goal: Picker.Goal.t): option(Exp.t) => + switch (Picker.Goal.selected(goal)) { + | Some(part) when !Id.equal(Exp.rep_id(part), Exp.rep_id(goal.written)) => + Some(part) + | Some(_) + | None => None + }; + + /* What the box's text asks for against `goal`: a search for it as a + * goal and the uses of every rule, or, when it names a rule, that + * rule's uses alone. With part of the goal selected, the text is that + * part's replacement, and the uses are those inside it. Suggestions + * already listed for the same rules and part are kept, unless the goal + * is new. */ + let search = + (~new_goal=false, goal: Picker.Goal.t, box: Model.box): Model.box => { + let part = selected_part(goal); + let wanted = + switch (part) { + | Some(part) => + Option.map( + ~f= + typed => + Exp.map_term( + ~f_exp= + (cont, e) => + Id.equal(Exp.rep_id(e), Exp.rep_id(part)) + ? typed : cont(e), + goal.written, + ), + wanted(box.editor), + ) + | None => wanted(box.editor) + }; + let at = Option.map(~f=Exp.rep_id, part); + let rule = + switch (typed_name(box.editor)) { + | Some(name) + when + List.Assoc.mem(StepSearch.names(goal), name, ~equal=String.equal) => + Some(name) + | Some(_) + | None => None + }; { - ...model, - root, + ...box, + search: + rule == None + ? Option.map(~f=wanted => StepSearch.start(goal, ~wanted), wanted) + : None, + suggestions: + switch (box.suggestions) { + | _ when Model.is_empty(box) => None + | Some(suggestions) + when suggestions.rule == rule && suggestions.at == at && !new_goal => + Some(suggestions) + | Some(_) + | None => Some(StepSearch.Suggestions.start(~rule, ~at)) + }, + chosen: None, + generation: box.generation + 1, + edits: box.edits + 1, + /* An empty box has nothing to hold back. */ + paused: Model.is_empty(box), }; }; + /* What the box lists, at most eight, and which is highlighted: the + * one chosen with the arrows, or else the first completion, the first + * use of a rule named in full, or the use that gives the typed goal. */ + let listing = + (goal: Picker.Goal.t, box: Model.box) + : (list(StepSearch.item), option(int)) => { + let items = + StepSearch.items( + goal, + ~typed_name=typed_name(box.editor), + box.suggestions, + ) + |> ListUtil.take(8); + let gives_typed = (item: StepSearch.item) => + switch (item, box.search) { + | (Use(use), Some(search)) => + StepSearch.reaches( + goal, + StepSearch.comparable(use.result), + search.wanted, + ) + | _ => false + }; + let named = + switch (items, box.suggestions) { + | ([Complete(_), ..._], _) + | ([_, ..._], Some({rule: Some(_), _})) => Some(0) + | _ => + List.findi(items, ~f=(_, item) => gives_typed(item)) + |> Option.map(~f=fst) + }; + ( + items, + switch (box.chosen) { + | Some(i) when i < List.length(items) => Some(i) + | Some(_) + | None => named + }, + ); + }; + + /* How long a slice of the search may run before the browser gets its + * turn. A slice ends only between candidates, so it can run over by + * one check. */ + let slice_ms = 15.; + + let new_box = (~settings, ~checking, goal: Picker.Goal.t): Model.box => { + tab: None, + editor: + CodeEditable.Model.mk( + Haz3lcore.Editor.Model.mk(Haz3lcore.Zipper.init(), ~root=Exp), + ) + |> calculate_box(~settings, goal), + ghost: checking ? None : ghost(goal), + search: None, + suggestions: None, + chosen: None, + generation: 0, + edits: 0, + paused: true, + }; + + /* A box under a borrowed goal offers nothing: its offers would act on + * the wrong goal. */ + let quiet = (box: Model.box): Model.box => { + ...box, + ghost: None, + search: None, + suggestions: None, + chosen: None, + }; + + /* The goal editor's decorations, for a row whose step acts on + * `acts_on`. The row's state itself when they are the same. */ + let decorate = (~acts_on, local: Model.local): Model.local => { + let goal = local.goal; + let previewing = + switch (Option.map(~f=listing(goal), local.box)) { + | Some((items, Some(i))) => + switch (List.nth(items, i)) { + | Some(Use(use)) => Some(Exp.rep_id(use.part)) + | Some(Complete(_)) + | None => None + } + | Some((_, None)) + | None => None + }; + let deco = + StepperEditor.Deco.update( + ~syntax=goal.editor.editor.syntax, + { + next_steps: Picker.Goal.step_ids(goal), + refls: List.map(~f=Exp.rep_id, goal.refls), + acts_on, + selected: Option.map(~f=Exp.rep_id, selected_part(goal)), + previewing, + }, + local.deco, + ); + phys_equal(deco, local.deco) + ? local + : { + ...local, + deco, + }; + }; + + let update = + (~settings: Settings.t, (key, action): t, model: Model.t) + : Updated.t(Model.t) => + switch (Model.find(key, model)) { + | None => model |> Updated.raise_invalid_action + | Some(local) => + open Updated; + let set = (local: Model.local) => + Model.add( + key, + decorate( + ~acts_on=local.deco.marks.acts_on, + local.checking + ? { + ...local, + box: Option.map(~f=quiet, local.box), + } + : local, + ), + model, + ); + let set_box = (box: Model.box) => + set({ + ...local, + box: Some(box), + }); + switch (action, local.box) { + /* A changed selection changes what Tab takes, and what the box's + * text replaces. */ + | (Goal(a), _) => + let* editor = + CodeSelectable.Update.update(~settings, a, local.goal.editor); + let goal = { + ...local.goal, + editor, + }; + let part = goal => Option.map(~f=Exp.rep_id, selected_part(goal)); + set({ + ...local, + goal, + box: + Option.map( + ~f= + (box: Model.box) => { + let box = { + ...box, + ghost: ghost(goal), + }; + part(goal) == part(local.goal) ? box : search(goal, box); + }, + local.box, + ), + }); + /* Step and Proof strategy act on the whole goal, so they drop a + * selection made to write a part's replacement. */ + | (Tab(tab), Some(box)) => + let (goal, box) = + switch (tab, selected_part(local.goal)) { + | (Step | Strategy, Some(_)) => + let unselected = + CodeSelectable.Update.update( + ~settings, + Unselect(None), + local.goal.editor, + ); + let goal = { + ...local.goal, + editor: unselected.model, + }; + ( + goal, + search( + goal, + { + ...box, + ghost: ghost(goal), + }, + ), + ); + | (Write | Step | Strategy, _) => (local.goal, box) + }; + set({ + ...local, + goal, + box: + Some({ + ...box, + tab: Some(tab), + }), + }) + |> return_quiet(~logged=true); + /* A changed text is searched for afresh. The box's text isn't part of + * the program, so typing in it isn't an edit of the cell, which would + * check the whole program again. */ + | (BoxEditor(a), Some(box)) => + let* editor = { + ...CodeEditable.Update.update(~settings, a, box.editor), + is_edit: false, + }; + let editor = + calculate_box(~settings=settings.core, local.goal, editor); + let changed = + ! + Exp.fast_equal_with_lexemes( + CodeEditable.Model.get_statics(box.editor).term, + CodeEditable.Model.get_statics(editor).term, + ); + let box = { + ...box, + editor, + }; + /* An empty box showing a ghost keeps its caret before the hole, + * where the ghost starts. */ + let box = + Model.is_empty(box) && box.ghost != None + ? { + ...box, + editor: + CodeEditable.Update.update( + ~settings, + Perform(Move(Start)), + box.editor, + ). + model, + } + : box; + set_box(changed ? search(local.goal, box) : box); + /* The search first, then the suggestions. */ + | (SearchSlice(generation), Some(box)) + when generation == box.generation && Model.running(box) => + let deadline = JsUtil.precise_timestamp() +. slice_ms; + let continue_ = () => JsUtil.precise_timestamp() < deadline; + set_box({ + ...box, + search: + Option.map( + ~f= + (search: StepSearch.t) => + search.status == Searching + ? StepSearch.run( + ~continue_, + ~algebra=RewriteChecker.check_rewrite, + local.goal, + search, + ) + : search, + box.search, + ), + suggestions: + Option.map( + ~f=StepSearch.Suggestions.run(~continue_, local.goal), + box.suggestions, + ), + generation: generation + 1, + }) + |> return_quiet; + | (SearchSlice(_), _) => model |> return_quiet + | (Paused(edits), Some(box)) when edits == box.edits => + set_box({ + ...box, + paused: true, + }) + |> return_quiet + | (Paused(_), _) => model |> return_quiet + | (Choose(chosen), Some(box)) => + set_box({ + ...box, + chosen, + }) + |> return_quiet(~logged=true) + | (Complete(name), Some(box)) => + let editor = + Haz3lcore.Parser.to_zipper(~root=Exp, name) + |> Option.value(~default=Haz3lcore.Zipper.init()) + |> Haz3lcore.Editor.Model.mk(~root=Exp) + |> CodeEditable.Model.mk + |> calculate_box(~settings=settings.core, local.goal); + set_box( + search( + local.goal, + { + ...box, + editor, + }, + ), + ) + |> return(~is_edit=false, ~scroll=IfCaretVisible); + | (ToggleCondition(i), _) => + set({ + ...local, + expanded: + List.mem(local.expanded, i, ~equal=Int.equal) + ? List.filter(~f=(!=)(i), local.expanded) + : [i, ...local.expanded], + }) + |> return_quiet(~logged=true) + /* A strategy is an occasional intervention, so the box after it + * opens on the stepper's default tab. */ + | (Wrote(next), _) => + { + ...model, + last_write: + Some({ + from: local.goal, + next, + tab: + switch (local.box) { + | Some({tab: Some((Write | Step) as tab), _}) => Some(tab) + | Some({tab: Some(Strategy) | None, _}) + | None => None + }, + }), + } + |> return_quiet + | (Tab(_) | BoxEditor(_) | Choose(_) | Complete(_), None) => + model |> raise_invalid_action + }; + }; + + /* While a check runs, the rows of steps written since the last check + * have no goal. Each borrows the goal and scope of the row above it, or + * at the start of a chain those of the row written from, so that the + * chain keeps its rows, and its box, until the check lands. */ + let borrowed = + (~written_from: option((Exp.t, SemanticCtx.t)), rows: list(Rows.t)) + : list((Rows.key, (Exp.t, SemanticCtx.t))) => { + let rec chain = (above, rows: list(Rows.t)) => + List.fold_left( + ~f= + ((acc, above), row: Rows.t) => { + let (here, acc) = + switch (row.goal, Rows.ctx(row), row.entry, above) { + | (Some(goal), Some(ctx), _, _) => (Some((goal, ctx)), acc) + | (_, _, None, Some(above)) => ( + Some(above), + [(row.key, above), ...acc], + ) + | (_, _, Some(_), _) + | (_, _, None, None) => (None, acc) + }; + let nested = + switch (row.kind) { + | Step(Body(rows)) + | Step(Focus(rows)) => chain(None, rows) + | Step(Cases(cases)) => + List.concat_map(~f=((_, rows)) => chain(None, rows), cases) + | Step(Premises({sub, body})) => + chain(None, sub) @ chain(None, body) + | Step(Leaf) + | Hole + | End => [] + }; + let below = + switch (row.entry) { + | Some({outgoing: Some(outgoing), ctx, _}) => + Some((outgoing, ctx)) + | Some({outgoing: None, _}) + | None => here + }; + (nested @ acc, below); + }, + ~init=([], above == None ? written_from : above), + rows, + ) + |> fst; + chain(None, rows); + }; + + /* The state for `rows`, rebuilt from the walk: a row carries over its + * last state, preparing its goal again only if the goal or the settings + * changed, and a row the walk doesn't reach is dropped with its state. + * A row with no goal has nothing to step, so no state, unless + * `checking` says a check will give it one. */ let calculate = ( - ~settings: Calc.t(CoreSettings.t), - ~ctx: Calc.t(SemanticCtx.t), - elab: Calc.t(Exp.t), - ~ana=Calc.OldValue(Typ.fresh(Unknown(SynSwitch))), - {cached_elab_subst, root}: Model.t, + ~settings: CoreSettings.t, + ~checking=false, + rows: list(Rows.t), + model: Model.t, ) : Model.t => { - let elab_subst = - cached_elab_subst - |> { - open Calc.Syntax; - let.calc elab = elab; - elab |> Substitution.in_exp(Builtins.env_init) |> Exp.replace_all_ids; - }; - let (root, _, _) = - StepperBase.Stepper.calculate( - ~settings, - ~ctx, - ~exp=elab_subst, - ~ana, - root, - ); - { - cached_elab_subst: elab_subst |> Calc.save, - root, - }; + let borrowed = + checking + ? borrowed( + ~written_from= + Option.map( + ~f=(w: Model.write) => (w.from.written, w.from.ctx), + model.last_write, + ), + rows, + ) + : []; + List.fold_left( + ~f= + (acc, row: Rows.t) => { + let source = + switch ( + row.goal, + Rows.ctx(row), + List.Assoc.find(borrowed, row.key, ~equal=Poly.equal), + ) { + | (Some(written), Some(ctx), _) => Some((written, ctx, false)) + | (_, _, Some((written, ctx))) => Some((written, ctx, true)) + | (_, _, None) => None + }; + switch (source) { + | Some((written, ctx, checking)) => + /* A box carries its text over to its row's new goal, and + * searches again from it. */ + let with_goal = (local: Model.local, goal): Model.local => { + ...local, + goal, + checking, + box: + Option.map( + ~f= + (box: Model.box) => { + let editor = calculate_box(~settings, goal, box.editor); + checking + ? quiet({ + ...box, + editor, + }) + : search( + ~new_goal=true, + goal, + { + ...box, + editor, + ghost: ghost(goal), + }, + ); + }, + local.box, + ), + }; + let local: Model.local = + switch (Model.find(row.key, model)) { + | Some(local) + when Picker.Goal.is_for(local.goal, ~ctx, written) => + let goal = { + ...local.goal, + ctx, + }; + switch ( + CoreSettings.eq_ignoring_stepper_modals( + goal.settings, + settings, + ), + local.checking == checking, + ) { + | (true, true) when phys_equal(ctx, local.goal.ctx) => local + | (true, true) => { + ...local, + goal, + } + | (true, false) => with_goal(local, goal) + | (false, _) => + with_goal(local, Picker.Goal.rebuild(~settings, goal)) + }; + | Some(local) => + with_goal(local, Picker.Goal.mk(~settings, ~ctx, written)) + | None => + /* A borrowed goal is usually the one written from, whose + * preparation can be reused. */ + let goal: Picker.Goal.t = + switch (model.last_write) { + | Some({from, _}) + when + checking + && Picker.Goal.is_for(from, ~ctx, written) + && CoreSettings.eq_ignoring_stepper_modals( + from.settings, + settings, + ) => { + ...from, + ctx, + } + | Some(_) + | None => Picker.Goal.mk(~settings, ~ctx, written) + }; + { + goal, + box: None, + expanded: [], + checking, + deco: + StepperEditor.Deco.mk( + ~syntax=goal.editor.editor.syntax, + StepperEditor.Deco.no_marks, + ), + }; + }; + /* A row keeps its key when the steps after it change whether a + * step can be written there. */ + let local = + switch (row.continues, local.box) { + | (true, None) => + let tab = + switch (model.last_write) { + | Some({next, tab, _}) when next == row.key => tab + | Some(_) + | None => None + }; + let box = { + ...new_box(~settings, ~checking, local.goal), + tab, + }; + { + ...local, + box: Some(checking ? quiet(box) : box), + }; + | (false, Some(_)) => { + ...local, + box: None, + } + | (true, Some(_)) + | (false, None) => local + }; + Model.add( + row.key, + decorate(~acts_on=Picker.Goal.acts_on(local.goal, row), local), + acc, + ); + | None => acc + }; + }, + ~init={ + ...Model.init, + last_write: checking ? model.last_write : None, + }, + Rows.all(rows), + ) + |> ( + after => { + Drawn.prune(~before=model, ~after); + after; + } + ); }; }; module Focus = { + /* Which sub-editor of a step: a form's argument, a split's scrutinee, + * or its i-th case's pattern. */ [@deriving (show({with_path: false}), sexp, yojson)] - type t = StepperBase.step_focus; + type slot = + | Arg + | Scrut + | Pattern(int); + + [@deriving (show({with_path: false}), sexp, yojson)] + type t = + | Goal(Rows.key) + /* A row's write box. */ + | Box(Rows.key) + /* A sub-editor onto the proof text (SubEditor), by its step's id. Its + * caret is the backing editor's, so this only says which one has + * focus. */ + | Splice(Id.t, slot); + + /* The box where the proof goes on once `steps` are written in a chain: + * the first hole they leave, or the row after the last of them. The + * steps keep their ids through the write's reparse, so the key is known + * before that row exists. */ + let after_write = (steps: list(Proof.t)): option(Rows.key) => { + let rec first_hole = (p: Proof.t) => + switch (p.term) { + | EmptyHole => Some(p) + | _ => List.find_map(~f=first_hole, Proof.children(p)) + }; + switch (List.find_map(~f=first_hole, steps), ListUtil.last_opt(steps)) { + | (Some(hole), _) => Some((Proof.rep_id(hole), Incoming)) + | (None, Some(last)) => Some((Proof.rep_id(last), Outgoing)) + | (None, None) => None + }; + }; open Cursor; let get_cursor_info = - (~inject, ~focus: t, model: Model.t): cursor(Update.t) => { - let+ ci = - StepperBase.Stepper.get_cursor_info(~inject, ~focus, model.root); - ci; - }; + (~inject: Update.t => Ui_effect.t(unit), ~focus: t, model: Model.t) + : cursor(Update.t) => + switch (focus) { + | Goal(key) => + switch (Model.find(key, model)) { + | Some(local) => + let+ ci = + CodeSelectable.Selection.get_cursor_info( + ~inject=a => inject((key, Goal(a))), + ~selection=(), + local.goal.editor, + ); + (key, Update.Goal(ci)); + | None => empty + } + | Box(key) => + switch (Model.find(key, model)) { + | Some({box: Some({editor, _}), _}) => + let+ ci = + CodeEditable.Selection.get_cursor_info( + ~inject=a => inject((key, BoxEditor(a))), + ~selection=(), + editor, + ); + (key, Update.BoxEditor(ci)); + | Some({box: None, _}) + | None => empty + } + | Splice(_) => empty + }; }; module View = { - [@deriving (show({with_path: false}), sexp, yojson)] + open WebUtil; + type event = | MakeActive(Focus.t) - | HideStepper; + | HideStepper + /* Focus leaves the stepper for the editor holding the program. */ + | ReturnToEditor; + + let code = (~globals: Globals.t, any: Any.t) => + CodeViewable.view_any( + ~globals, + ~settings=ProofMarkView.code_view_settings(globals.settings.core), + any, + ); + + /* One row's chrome: the goal it starts from, then the step to the next + * row. A plain step is the line between the two rows, with its lozenge + * (the justification and a delete button) on it. A step with goals of + * its own, or with side conditions shown open, opens its line into a + * block holding them, with the lozenge on the block's top edge. + * + * The same syntax always takes the same space, so status never moves the + * proof (no scroll jumps). It shows only as a class on the row, which + * draws an indicator along the row's right edge (red broken, tan + * incomplete, dotted light red blocked), and as a popup above the + * justification, hidden until the justification is clicked, holding the + * message, any detail and the repair buttons. Both are out of the flow. */ + module Row = { + let view = + ( + ~globals: Globals.t, + ~status: Rows.Status.t, + /* Off for a row that shows the error of the step above instead + * of a goal: hidden rather than removed, so the text stays + * aligned. */ + ~show_equiv: bool, + /* The goal is what a form's body has still to prove: drawn + * faded, with `≡?`. */ + ~pending: bool=false, + /* The goal is borrowed while the step is checked: drawn faded + * if the check takes a while. */ + ~checking: bool=false, + ~delete: option(Ui_effect.t(unit)), + /* Detail for the popup, e.g. an induction's missing pattern. */ + ~popup_extra: list(Node.t)=[], + ~repair: list(Node.t)=[], + ~editor_view: Node.t, + ~justification: Node.t, + /* Collapsed side conditions, drawn left of the lozenge. */ + ~dots: list(Node.t)=[], + /* The sections of the step's block, if it has one. */ + ~block: option(list(Node.t))=None, + (), + ) => { + let (row_classes, popup_body) = + switch (status) { + | Clean => (["ok"], []) + | Pending => (["pending"], []) + | Incomplete => (["incomplete"], []) + | Broken(mark) => ( + ["broken"], + ProofMarkView.message(~globals, mark) @ popup_extra @ repair, + ) + | Blocked => ( + ["blocked"], + [Node.text("Waiting on the step above.")] @ popup_extra @ repair, + ) + }; + /* The popup sits inside the focusable wrapper, so a click on a + * repair button keeps focus within it (`:focus-within` holds) and + * lands before the popup hides. */ + let justification = + switch (popup_body) { + | [] => div_c("step-justification-wrap", [justification]) + | _ => + Node.div( + ~attrs=[ + Attr.classes(["step-justification-wrap", "has-popup"]), + Attr.create("tabindex", "0"), + ], + [div_c("step-error-popup", popup_body), justification], + ) + }; + let delete_button = + switch (delete) { + | Some(d) => [ + Widgets.button( + ~clss=["step-delete"], + ~tooltip="Delete this step", + Icons.trash, + _ => + d + ), + ] + | None => [] + }; + let transition = + div_c("step-transition", dots @ [justification] @ delete_button); + let display = transition_in_display => + div_c( + "step-display", + [ + Node.div( + ~attrs=[ + Attr.classes( + ["equiv"] @ (show_equiv ? [] : ["equiv-hidden"]), + ), + ], + [Node.text(pending ? "≡?" : "≡")], + ), + div_c("step-output", [editor_view]), + ] + @ transition_in_display, + ); + let row_classes = + row_classes + @ (pending || checking ? ["goal-pending"] : []) + @ (checking ? ["checking"] : []); + switch (block) { + | None => [ + Node.div( + ~attrs=[Attr.classes(["step-border"] @ row_classes)], + [display([transition])], + ), + ] + | Some(sections) => [ + Node.div( + ~attrs=[ + Attr.classes(["step-border", "has-block"] @ row_classes), + ], + [display([]), div_c("step-block", [transition] @ sections)], + ), + ] + }; + }; + + /* In place of the goal, when the step above broke: the checker passed + * its goal through, so printing it again would be noise. */ + let view_error_above = (~globals: Globals.t, mark: ProofMark.t) => + div_c("step-error-inline", ProofMarkView.message(~globals, mark)); + + /* A row drawn for reading only, with no step below it. */ + let quiet = (~clss, ~equiv, content) => + Node.div( + ~attrs=[Attr.classes(["step-border", clss])], + [div_c("step-display", [equiv] @ content)], + ); + + let equiv_hidden = () => + Node.div( + ~attrs=[Attr.classes(["equiv", "equiv-hidden"])], + [Node.text("≡")], + ); + + /* The `true` a chain aims at. */ + let target = (~globals) => + quiet( + ~clss="target-step", + ~equiv=div_c("equiv", [Node.text("≡?")]), + [ + div_c( + "step-output", + [code(~globals, Exp(Exp.fresh(Atom(Bool(true)))))], + ), + ], + ); + + /* The repairs a broken step offers: removing it, and, for an axiom + * that doesn't apply, trying the other direction. */ + let repairs = + ( + ~edit_syntax: Picker.Patches.patch => Ui_effect.t(unit), + ~info_map: Statics.Map.t, + ~proof_map: ProofMap.t, + status: Rows.Status.t, + step: Proof.t, + ) + : list(Node.t) => { + let button = (~tooltip, label, patch) => + Widgets.button(~clss=["proof-button"], ~tooltip, Node.text(label), _ => + edit_syntax(patch) + ); + switch (status) { + | Broken(mark) => + let flip = + switch (mark) { + | RuleDoesNotApply(_) => + Picker.Patches.flip_direction(~info_map, ~proof_map, step) + |> Option.map( + ~f= + button( + ~tooltip="Apply the equality in the other direction", + "Try other direction", + ), + ) + |> Option.to_list + | _ => [] + }; + flip + @ [ + button( + ~tooltip="Replace this step with a hole", + "Remove step", + Picker.Patches.remove(step), + ), + ]; + | Clean + | Incomplete + | Blocked + | Pending => [] + }; + }; + }; + + /* A side condition: a circle on a line, which opens into a section + * holding a read-only stepper from its goal to `true`. A closed one + * shows how the checker closed it; a pending one's `?` row holds the + * exits that discharge it. A step's circles sit on its line. */ + module Condition = { + /* The circle's icon and the section's label. */ + let kind = (kind: Obligation.kind): (string, string) => + switch (kind) { + | Definedness => ("÷", "definedness") + | Premise => ("⇒", "premise") + | Citation => ("↗", "unfinished theorem") + | Algebra => ("=", "algebra") + }; + + let dot = (~toggle: Ui_effect.t(unit), ob: Obligation.t) => { + let (icon, label) = kind(ob.kind); + let unproven = Obligation.is_pending(ob); + Node.div( + ~attrs=[ + Attr.classes( + ["condition-dot"] + @ (unproven ? ["unproven"] : []) + @ (ob.kind == Citation ? ["citation"] : []), + ), + Attr.title( + "Side condition, " + ++ label + ++ (unproven ? ", unproven" : "") + ++ ". Click to show it.", + ), + Attr.on_click(_ => toggle), + ], + [Node.text(icon)], + ); + }; + + let view = + ( + ~globals: Globals.t, + ~edit_syntax: Picker.Patches.patch => Ui_effect.t(unit), + ~exits: list(Obligations.Exits.t), + ~toggle: Ui_effect.t(unit), + ob: Obligation.t, + ) => { + let (_, label) = kind(ob.kind); + let code = code(~globals); + let goal = ob.goal; + let truth = Exp.fresh(Atom(Bool(true))); + /* Closed by evaluating it or citing a fact, so the step acts on all + * of the goal. */ + let closed = justification => + Row.view( + ~globals, + ~status=Clean, + ~show_equiv=true, + ~delete=None, + ~editor_view=div_c("step-acts-on-whole", [code(Exp(goal))]), + ~justification=Node.text(justification), + (), + ) + @ [ + Row.quiet( + ~clss="condition-closed", + ~equiv=div_c("equiv", [Node.text("≡")]), + [div_c("step-output", [code(Exp(truth))])], + ), + ]; + let exit = (e: Obligations.Exits.t) => + Node.button( + ~attrs= + ( + switch (e.patch) { + | Some(patch) => [ + Attr.classes(["condition-exit"]), + Attr.on_click(_ => edit_syntax(patch)), + ] + | None => [ + Attr.classes(["condition-exit", "disabled"]), + Attr.disabled, + ] + } + ) + @ [Attr.title(e.title)], + [Node.text(e.label)], + ); + let rows = + switch (ob.discharge, Obligation.remote_fact(ob)) { + | (Remote(_), Some((name, _))) => closed(name) + | (Remote(_), None) => closed("a fact in scope") + | (Evaluated, _) => closed("by evaluation") + /* TODO: a `?` here holds a write box once a side condition can be + * proved in place (`with by `). */ + | (Pending, _) => [ + Row.quiet( + ~clss="condition-goal", + ~equiv=div_c("equiv", [Node.text("≡")]), + [div_c("step-output", [code(Exp(goal))])], + ), + Row.quiet( + ~clss="condition-missing", + ~equiv=Row.equiv_hidden(), + [ + div_c("step-unknown", [Node.text("?")]), + switch (exits) { + | [] => + div_c("condition-hint", [Node.text("Not proven yet.")]) + | _ => div_c("condition-exits", List.map(~f=exit, exits)) + }, + ], + ), + Row.target(~globals), + ] + }; + div_c( + "step-section condition", + [ + Node.div( + ~attrs=[ + Attr.classes(["step-section-bar"]), + Attr.title("Click to collapse"), + Attr.on_click(_ => toggle), + ], + [Node.text(label)], + ), + div_c("step-slot", [div_c("stepper cell-result", rows)]), + ], + ); + }; + }; + + /* Runs the write box's search a slice at a time. Each render of a new + * generation of a running search asks for one more slice, after the + * browser has had its turn, so typing never waits on the search. A new + * search waits a moment first, in case the user is still typing. */ + module SearchSlices = { + module Spec = { + module State = Unit; + module Input = { + type t = { + generation: int, + fresh: bool, + slice: Ui_effect.t(unit), + }; + let sexp_of_t = (input: t) => + Sexplib0.Sexp.Atom(string_of_int(input.generation)); + let combine = (_, latest) => latest; + }; + let ask = (input: Input.t) => + JsUtil.delay(input.fresh ? 150. : 0., () => + Virtual_dom.Vdom.Effect.Expert.handle_non_dom_event_exn(input.slice) + ); + let init = (_, _) => (); + let on_mount = (input, (), _) => ask(input); + let update = (~old_input: Input.t, ~new_input: Input.t, (), _) => + if (old_input.generation != new_input.generation) { + ask(new_input); + }; + let destroy = (_, (), _) => (); + }; + include Virtual_dom.Vdom.Attr.Hooks.Make(Spec); + }; + + /* Tells the box when typing has paused: 500 ms after its last edit. */ + module Pause = { + module Spec = { + module State = Unit; + module Input = { + type t = { + edits: int, + paused: Ui_effect.t(unit), + }; + let sexp_of_t = (input: t) => + Sexplib0.Sexp.Atom(string_of_int(input.edits)); + let combine = (_, latest) => latest; + }; + let wait = (input: Input.t) => + JsUtil.delay(500., () => + Virtual_dom.Vdom.Effect.Expert.handle_non_dom_event_exn( + input.paused, + ) + ); + let init = (_, _) => (); + let on_mount = (input, (), _) => wait(input); + let update = (~old_input: Input.t, ~new_input: Input.t, (), _) => + if (old_input.edits != new_input.edits) { + wait(new_input); + }; + let destroy = (_, (), _) => (); + }; + include Virtual_dom.Vdom.Attr.Hooks.Make(Spec); + }; + + /* Gives the focused box DOM focus when it is drawn or starts showing its + * editor, unless DOM focus is already there. A write moves focus to a + * box drawn only after the write's reparse, under a new key, which + * nothing else would focus. */ + module DomFocus = { + module Spec = { + module State = Unit; + module Input = { + type t = { + focused: bool, + key: Rows.key, + /* Whether the box shows its editor, which takes focus from the + * box when it appears. */ + editing: bool, + }; + let sexp_of_t = (input: t) => + Sexplib0.Sexp.Atom( + Id.to_string(fst(input.key)) + ++ string_of_bool(input.focused) + ++ string_of_bool(input.editing), + ); + let combine = (_, latest) => latest; + }; + let take = (elem: Js_of_ocaml.Js.t(Js_of_ocaml.Dom_html.element)) => + JsUtil.delay( + 0., + () => { + open Js_of_ocaml; + /* The Step tab has no editor, so the box itself takes focus. */ + let target = + Js.Opt.get(elem##querySelector(Js.string(".code-editor")), () => + elem + ); + let inside = + switch (Js.Opt.to_option(Dom_html.document##.activeElement)) { + | Some(active) => + Js.to_bool( + Js.Unsafe.meth_call( + target, + "contains", + [|Js.Unsafe.inject(active)|], + ), + ) + | None => false + }; + if (!inside) { + Js.Unsafe.meth_call( + target, + "focus", + [| + Js.Unsafe.obj([| + ("preventScroll", Js.Unsafe.inject(Js._true)), + |]), + |], + ); + }; + }, + ); + let init = (_, _) => (); + let on_mount = (input: Input.t, (), elem) => + if (input.focused) { + take(elem); + }; + let update = (~old_input: Input.t, ~new_input: Input.t, (), elem) => + if (new_input.focused + && ( + !old_input.focused + || old_input.key != new_input.key + || old_input.editing != new_input.editing + )) { + take(elem); + }; + let destroy = (_, (), _) => (); + }; + include Virtual_dom.Vdom.Attr.Hooks.Make(Spec); + }; + + /* The write box, under the goal of an unfinished chain, with its tabs + * above it. */ + module Box = { + let label = (tab: Model.tab) => + switch (tab) { + | Write => "Write" + | Step => "Step" + | Strategy => "Strategy" + }; + + /* The tab the user picked, or the stepper's default, its first. */ + let current = (~tabs: list(Model.tab), box: Model.box): Model.tab => + switch (box.tab, tabs) { + | (Some(tab), _) when List.mem(tabs, tab, ~equal=Poly.equal) => tab + | (_, [first, ..._]) => first + | (_, []) => Write + }; + + /* The first and last columns of the goal's selected part, on its + * first line. */ + let columns = (goal: Picker.Goal.t): option((int, int)) => { + open OptUtil.Syntax; + let editor = goal.editor.editor; + let measured = Haz3lcore.CachedSyntax.measured(editor.syntax); + let segment = editor.state.zipper.selection.content; + let* first = ListUtil.hd_opt(segment); + let+ last = ListUtil.last_opt(segment); + let start = + Haz3lcore.Measured.find_p(~msg="Box.columns", first, measured).origin; + let end_ = + Haz3lcore.Measured.find_p(~msg="Box.columns", last, measured).last; + (start.col, end_.row == start.row ? end_.col : start.col + 1); + }; + + /* A use's step, as written: `rewrite name` or `rewrite <- name`. */ + let rule_label = (step: Proof.t) => + switch (Rows.single_step(step) |> Option.value(~default=step)) { + | {term: AxiomStep({direction, equality, _}), _} => + (direction == Left ? "rewrite <- " : "rewrite ") + ++ (ProofSyntax.exp_to_name(equality) |> Option.value(~default="")) + | _ => "" + }; + + /* What the box's search says: still looking until it has finished + * and typing has paused, so a half-typed goal never shows red. */ + let verdict = (box: Model.box): option(StepSearch.status) => + switch (box.search) { + | Some({status: NotFound, _}) when !box.paused => Some(Searching) + | Some({status, _}) => Some(status) + | None => None + }; + + let keycap = name => div_c("box-key", [Node.text(name)]); + + /* A key with no modifiers held. */ + let plain = (name, key: Key.t) => + switch (key) { + | {key: D(k), shift: Up, meta: Up, ctrl: Up, alt: Up, _} => + String.equal(k, name) + | _ => false + }; + + let view = + ( + ~globals: Globals.t, + ~key: Rows.key, + /* The first is the stepper's default. */ + ~tabs: list(Model.tab), + ~inject: Update.action => Ui_effect.t(unit), + ~write: Picker.pick => Ui_effect.t(unit), + /* Writes the steps the search found, one row each. */ + ~write_steps: list(Proof.t) => Ui_effect.t(unit), + ~take_focus: Ui_effect.t(unit), + ~focused: bool, + /* Escape takes focus out of the box. */ + ~escape: Ui_effect.t(unit), + /* The columns of the goal's selected part, when the box writes + * its replacement: the box moves right of it, with an arrow + * from it. */ + ~replacing: option((int, int)), + box: Model.box, + goal: Picker.Goal.t, + ) + : Node.t => { + let tab = current(~tabs, box); + let code = (e: Exp.t) => code(~globals, Exp(e)); + let tab_bar = + div_c( + "box-tabs", + List.map( + ~f= + t => + Node.div( + ~attrs=[ + Attr.classes(["box-tab"] @ (t == tab ? ["on"] : [])), + Attr.on_click(_ => inject(Tab(t))), + ], + [Node.text(label(t))], + ), + tabs, + ), + ); + let input = () => { + let empty = Model.is_empty(box); + let ghost = empty ? box.ghost : None; + let found = + switch (box.search) { + | Some({status: Found([_, ..._] as steps), _}) => Some(steps) + | Some({status: Found([]) | Searching | NotFound, _}) + | None => None + }; + let (items, highlighted) = Update.listing(goal, box); + let take = (item: StepSearch.item) => + switch (item) { + | Complete(name) => inject(Complete(name)) + | Use(use) => write_steps([use.step]) + }; + let highlighted_item = + Option.bind(highlighted, ~f=i => List.nth(items, i)); + let count = List.length(items); + let keys = (key: Key.t) => + switch (ghost, highlighted_item, found) { + | (Some(ghost), _, _) when plain("Tab", key) => + Some(write(ghost.pick)) + | (_, Some(Complete(name)), _) when plain("Tab", key) => + Some(inject(Complete(name))) + | (_, Some(item), _) when plain("Tab", key) => Some(take(item)) + /* Tab never leaves the box, so that pressing it again while the + * proof is rechecked doesn't walk into the page. */ + | _ when plain("Tab", key) => Some(Ui_effect.Ignore) + | _ when plain("Escape", key) => Some(escape) + /* The arrows choose among the items, and so don't move between + * the box's lines while there are any. */ + | _ when plain("ArrowDown", key) && count > 0 => + let next = + Option.value_map(highlighted, ~default=0, ~f=i => i + 1); + Some(inject(Choose(Some(min(next, count - 1))))); + | _ when plain("ArrowUp", key) && count > 0 => + Some( + inject( + Choose( + switch (highlighted) { + | Some(i) when i > 0 => Some(i - 1) + | Some(_) + | None => None + }, + ), + ), + ) + | (_, Some(item), _) when plain("Enter", key) => + Some(take(item)) + | (_, None, Some(steps)) when plain("Enter", key) => + Some(write_steps(steps)) + /* With nothing found, Enter does nothing. Shift+Enter still + * breaks the line. */ + | _ when plain("Enter", key) => Some(Ui_effect.Ignore) + | _ => None + }; + let editor = + CodeEditable.View.view( + ~globals, + ~signal= + fun + | MakeActive => take_focus, + ~edit_mode= + EditMode.Editable({ + inject: a => inject(BoxEditor(a)), + escape: _ => Ui_effect.Ignore, + take_focus: _ => Ui_effect.Ignore, + focus: focused ? Some() : None, + }), + ~dynamics=Dynamics.Map.empty, + ~keys, + box.editor, + ); + let named = + switch (Update.typed_name(box.editor)) { + | Some(name) => + List.Assoc.find( + StepSearch.names(goal), + name, + ~equal=String.equal, + ) + |> Option.map(~f=kind => + switch (kind) { + | `Scope => "a fact in scope" + | `Axiom => "an axiom" + } + ) + | None => None + }; + let (ghost, hint) = + switch (ghost, named, verdict(box)) { + | (Some(g), _, _) => ( + [div_c("box-ghost", [code(g.result)])], + [keycap("Tab"), Node.text(g.rule)], + ) + | (None, Some(kind), _) => ([], [Node.text(kind)]) + | (None, None, Some(Found([_, ..._]))) => ( + [], + [keycap("Enter")], + ) + | (None, None, Some(NotFound)) => ( + [], + [ + keycap("Enter"), + div_c( + "box-hint-none", + [Node.text("nothing proves this step")], + ), + ], + ) + | (None, None, Some(Found([]))) => ( + [], + [Node.text("the goal already")], + ) + | (None, None, Some(Searching) | None) => ([], []) + }; + let slices = + Model.running(box) + ? Attr.create_hook( + "write-box-search", + SearchSlices.create({ + generation: box.generation, + fresh: + switch (box.search) { + | Some(search) => + search.checks == 0 && search.expanding == None + | None => false + }, + slice: inject(SearchSlice(box.generation)), + }), + ) + : Attr.empty; + let item = (i, item: StepSearch.item) => + Node.div( + ~attrs=[ + Attr.classes( + ["box-item"] @ (highlighted == Some(i) ? ["on"] : []), + ), + Attr.on_click(_ => Ui_effect.Many([take_focus, take(item)])), + ], + switch (item) { + | Complete(name) => [ + code(Exp.fresh(Var(name))), + div_c( + "box-item-note", + [ + Node.text( + switch ( + List.Assoc.find( + StepSearch.names(goal), + name, + ~equal=String.equal, + ) + ) { + | Some(`Axiom) => "axiom" + | Some(`Scope) + | None => "in scope" + }, + ), + ], + ), + ] + | Use(use) => [ + code(use.result), + div_c("box-item-rule", [Node.text(rule_label(use.step))]), + ] + }, + ); + [ + Node.div( + ~attrs=[ + Attr.classes(["box-input"]), + slices, + box.paused + ? Attr.empty + : Attr.create_hook( + "write-box-pause", + Pause.create({ + edits: box.edits, + paused: inject(Paused(box.edits)), + }), + ), + ], + [ + Node.div( + ~attrs=[ + Attr.classes(["box-editor"] @ (empty ? ["empty"] : [])), + ], + [editor] @ ghost, + ), + div_c("box-hint", hint), + ], + ), + ] + @ ( + items == [] ? [] : [div_c("box-items", List.mapi(~f=item, items))] + ); + }; + let strategies = () => { + let button = (~clss=[], ~tooltip, contents, effect) => + Node.div( + ~attrs=[ + Attr.classes(["strategy-button"] @ clss), + Attr.title(tooltip), + Attr.on_click(_ => effect), + ], + contents, + ); + /* A strategy is an occasional intervention: after one, the box + * goes back to writing steps. */ + let write_whole = term => + Ui_effect.Many([ + inject(Tab(Write)), + write({ + at: None, + step: Proof.fresh(term), + }), + ]); + let strategy = (~intro, s: Picker.Strategies.strategy) => + button( + ~clss=intro ? ["intro"] : [], + ~tooltip=s.tooltip, + [Node.text(s.label)], + write_whole(s.writes), + ); + let intros = Picker.Strategies.intros(goal); + div_c( + "strategy-buttons", + List.map(~f=strategy(~intro=true), intros) + @ (intros == [] ? [] : [div_c("strategy-separator", [])]) + @ List.map(~f=strategy(~intro=false), Picker.Strategies.general()), + ); + }; + /* In pixels from the goal's first column, which the box's text + * lines up with. The arrow starts just under the goal and ends at + * the middle of the box's input, 55px further down. */ + let (shift, arrow) = + switch (replacing) { + | Some((left, right)) => + let col = c => float_of_int(c) *. globals.font_metrics.col_width; + let start = (col(left) +. col(right)) /. 2.; + let end_ = col(right) +. 10.; + let path = + sprintf( + "M %.1f 0 C %.1f 45, %.1f 55, %.1f 55 M %.1f 50 L %.1f 55 L %.1f 60", + start, + start, + start +. 10., + end_, + end_ -. 6., + end_, + end_ -. 6., + ); + ( + [Attr.create("style", sprintf("--shift: %.1fpx", end_ +. 4.))], + [ + Node.create_svg( + "svg", + ~attrs=[ + Attr.classes(["write-arrow"]), + Attr.create("width", sprintf("%.0f", end_ +. 2.)), + Attr.create("height", "62"), + ], + [ + Node.create_svg( + "path", + ~attrs=[Attr.create("d", path)], + [], + ), + ], + ), + ], + ); + | None => ([], []) + }; + /* Keys the box's editor doesn't get: one that arrives before the + * click into the box has made it the focused editor, and any on the + * Step tab, which has no editor. Typing there switches to Write. */ + let outer_keys = + focused && tab != Step + ? Attr.empty + : Key.listener(~f=key => + switch (key) { + | {key: D(text), meta: Up, ctrl: Up, alt: Up, _} + when String.length(text) == 1 => + Ui_effect.Many([ + Virtual_dom.Vdom.Effect.Prevent_default, + Virtual_dom.Vdom.Effect.Stop_propagation, + inject(Tab(Write)), + take_focus, + inject(BoxEditor(Perform(Insert(text)))), + ]) + | _ when focused && plain("Escape", key) => escape + | _ when focused && plain("Tab", key) => Virtual_dom.Vdom.Effect.Prevent_default + | _ => Ui_effect.Ignore + } + ); + Node.div( + ~attrs= + [ + Attr.classes( + ["write-box"] @ (replacing == None ? [] : ["replacing"]), + ), + outer_keys, + Attr.create_hook( + "write-box-focus", + DomFocus.create({ + focused, + key, + editing: tab == Write, + }), + ), + ...shift, + ] + @ (tab == Step ? [Attr.tabindex(-1)] : []), + arrow + @ [ + tab_bar, + div_c( + "box-body", + switch (tab) { + | Write => input() + | Step => [] + | Strategy => [strategies()] + }, + ), + ], + ); + }; + }; + + /* The row's justification: the step's keyword, or the cited equality's + * name. A one-step focus is drawn as its step. */ + let rec justification = (step: Proof.t): string => + switch (step.term) { + | AxiomStep({equality, direction, _}) => + (direction == Left ? "← " : "") + ++ (ProofSyntax.exp_to_name(equality) |> Option.value(~default="")) + | AlgebriteStep(_) => "algebra" + | EvalStep => "step" + | Focus(_) => + Rows.single_step(step) + |> Option.value_map(~default="focus", ~f=justification) + | Forall(_) => "forall" + | Funext(_) => "extensionality" + | Assume(_) => "assume" + | Revert(_) => "revert" + | Generalize(_) => "generalize" + | Have(_) => "have" + | Alias(_) => "alias" + | Cases(_) => "cases" + | Induction(_) => "induction" + | EmptyHole + | Invalid(_) + | MultiHole(_) + | Seq(_) + | Parens(_) => "" + }; let view = ( @@ -102,9 +1925,775 @@ module View = { ~signal: event => Ui_effect.t(unit), ~inject: Update.t => Ui_effect.t(unit), ~selected: option(Focus.t), - ~is_toplevel=true, + ~is_toplevel: bool, + /* Writes a patch into the proof text. */ + ~edit_syntax: Picker.Patches.patch => Ui_effect.t(unit), + /* The editor holding the proof text, which the sub-editors splice + * into. */ + ~backing: CodeEditable.Channel.t, + /* The statics of the proof text. */ + ~info_map: Statics.Map.t, + ~proof_map: ProofMap.t, + /* What a pending side condition offers to discharge it. */ + ~exits: Obligation.t => list(Obligations.Exits.t), + proof: Proof.t, model: Model.t, - ) => { + ) + : list(Node.t) => { + let take_focus = f => signal(MakeActive(f)); + /* A refuted theorem's proof can't go on, so its rows offer no write + * box (`Rows.of_theorem`) and its chains aim at nothing. */ + let refuted = + !is_toplevel + && ProofMap.full_status_of_proof(proof_map, proof) == Refuted; + let focused = f => selected == Some(f); + let code = code(~globals); + /* The steps written for `steps` at `row`: bridged to the step after a + * hole, with each focus's selector generalized. */ + let final_steps = (row: Rows.t, steps: list(Proof.t)) => + switch (Model.find(row.key, model)) { + | Some(local) => + StepSearch.Bridge.steps( + ~algebra=RewriteChecker.check_rewrite, + ~proof, + local.goal, + row, + steps, + ) + |> StepSearch.generalized(local.goal) + | None => steps + }; + /* Writes `steps` after `row`'s goal with `patch`, forcing the record + * open, or the rows just written would not be on screen. Focus goes + * to the box where the proof goes on, with the tab of the box written + * from, so that the next step is written the same way. */ + let write_patch = (row: Rows.t, steps: list(Proof.t), patch) => { + let next = Focus.after_write(steps); + let carry = + switch (next) { + | Some(next) => [inject((row.key, Wrote(next)))] + | None => [] + }; + let focus = + switch (next) { + | Some(next) => [take_focus(Box(next))] + | None => [] + }; + Ui_effect.Many( + [globals.inject_global(Set(Evaluation(ForceShowRecord)))] + @ carry + @ [edit_syntax(patch)] + @ focus, + ); + }; + /* A form with an argument to fill in takes the caret into it instead of + * the box: the backing editor's caret moves into the new argument (a + * sub-editor takes no edits, and draws no caret, while the caret is + * outside it), the new step's sub-editor takes focus, and DOM focus + * follows after the render, as the click left it on the button. */ + let write = (row: Rows.t, pick: Picker.pick) => { + let step = pick.step; + let steps = final_steps(row, [Picker.focused(pick)]); + let into = (patch, id, slot: Focus.slot) => + Ui_effect.Many([ + globals.inject_global(Set(Evaluation(ForceShowRecord))), + edit_syntax(patch), + backing.inject(Perform(Move(Goal(TileId(id))))), + take_focus(Splice(Proof.rep_id(step), slot)), + Ui_effect.of_sync_fun( + () => Haz3lcore.FocusEffect.schedule_cell(), + (), + ), + ]); + switch ( + Picker.write_steps(row, steps), + pick.at, + Picker.Terms.arg_id(step.term), + step.term, + ) { + | (None, _, _, _) => Ui_effect.Ignore + /* The bar of an `assume` or `have` has a box to type the + * proposition into only while it is a hole; once written, the bar + * names the fact. */ + | ( + Some(patch), + None, + Some(arg_id), + Assume({term: EmptyHole, _}, _, _) | + Have({term: EmptyHole, _}, _, _, _), + ) => + into(patch, arg_id, Arg) + | (Some(patch), None, Some(_), Assume(_) | Have(_)) => + write_patch(row, steps, patch) + | (Some(patch), None, Some(arg_id), _) => into(patch, arg_id, Arg) + /* A split on a scrutinee still to fill in has no case, and so no + * box, yet. */ + | ( + Some(patch), + None, + None, + Cases({term: EmptyHole, _} as scrut, []) | + Induction({term: EmptyHole, _} as scrut, []), + ) => + into(patch, Exp.rep_id(scrut), Scrut) + | (Some(patch), None, None, _) + | (Some(patch), Some(_), _, _) => write_patch(row, steps, patch) + }; + }; + let write_steps = (row: Rows.t, steps: list(Proof.t)) => { + let steps = final_steps(row, steps); + switch (Picker.write_steps(row, steps)) { + | Some(patch) => write_patch(row, steps, patch) + | None => Ui_effect.Ignore + }; + }; + /* A slice of the proof text, edited in place in the backing editor. + * Read-only while the slice can't be found there (the statics lagging + * an edit). */ + let splice = (~step: Proof.t, ~slot: Focus.slot, ~target, fallback: Any.t) => { + let focus = Focus.Splice(Proof.rep_id(step), slot); + div_c( + "inline-editor-wrapper", + [ + switch (SubEditor.mk(backing.model.editor, ~target)) { + | Some(sub) => + CodeEditable.View.view_sub( + ~globals, + ~channel=backing, + ~take_focus=take_focus(focus), + ~focused=focused(focus), + sub, + ) + | None => div_c("proof-form-arg-static", [code(fallback)]) + }, + ], + ); + }; + /* The goal's editor. With `hints`, the steps it offers are + * highlighted, and a click on one takes it. */ + /* With `into_box`, what is typed goes to the row's write box, which + * writes the selected part's replacement. */ + let goal_editor = + ( + ~hints: bool, + ~previewing: bool, + ~into_box, + row: Rows.t, + local: Model.local, + ) => { + let keys = (key: Key.t) => + switch (key) { + /* With a selection, Escape clears it. */ + | {key: D("Escape"), shift: Up, meta: Up, ctrl: Up, alt: Up, _} + when Picker.Goal.selected(local.goal) == None => + Some(signal(ReturnToEditor)) + | {key: D(text), meta: Up, ctrl: Up, alt: Up, _} + when into_box && String.length(text) == 1 => + Some( + Ui_effect.Many([ + take_focus(Box(row.key)), + inject((row.key, BoxEditor(Perform(Insert(text))))), + Ui_effect.of_sync_fun( + () => Haz3lcore.FocusEffect.schedule_cell(), + (), + ), + ]), + ) + | _ => None + }; + let goal = local.goal; + let write_opt = pick => + pick + |> Option.map(~f=write(row)) + |> Option.value(~default=Ui_effect.Ignore); + let inputs: Drawn.inputs = { + editor: { + editor: goal.editor, + deco: local.deco, + hints, + /* The selected part the box writes a replacement for is + * underlined as a focus's part is. */ + replacing: into_box, + previewing, + }, + focused: focused(Goal(row.key)), + settings: globals.settings, + font_metrics: globals.font_metrics, + meta_down: globals.meta_down, + color_highlights: globals.color_highlights, + }; + Drawn.view( + row.key, + inputs, + { + signal: + fun + | MakeActive => take_focus(Goal(row.key)) + | TakeStep(idx) => write_opt(Picker.take_step(goal, idx)) + | Refl(idx) => + write_opt( + Option.map(~f=Picker.refl(goal), List.nth(goal.refls, idx)), + ), + inject: a => inject((row.key, Goal(a))), + keys, + }, + ({signal, inject, keys}) => + StepperEditor.View.view( + ~globals, + ~signal, + ~inject, + ~selected=inputs.focused, + ~keys, + inputs.editor, + ) + ); + }; + let goal_view = + ( + ~hints, + ~previewing=false, + ~into_box=false, + ~prev_broken, + row: Rows.t, + ) => + switch (prev_broken, Model.find(row.key, model)) { + | (Some(mark), _) => Row.view_error_above(~globals, mark) + | (None, Some(local)) => + goal_editor(~hints, ~previewing, ~into_box, row, local) + | (None, None) => div_c("step-placeholder", [Node.text("—")]) + }; + let checking = (row: Rows.t) => + switch (Model.find(row.key, model)) { + | Some(local) => local.checking + | None => false + }; + let controls = (~top) => + top && is_toplevel + ? [ + Widgets.button(Icons.gear, _ => + globals.inject_global(Set(Evaluation(ShowSettings))) + ), + Widgets.toggle( + ~tooltip="Show History", + "h", + globals.settings.core.evaluation.stepper_history, + _ => + globals.inject_global(Set(Evaluation(ShowRecord))) + ), + Widgets.toggle(~tooltip="Show Stepper", "s", true, _ => + signal(HideStepper) + ), + ] + : []; + /* The cell's own stepper steps a program, so it has no Proof strategy + * tab, and starts on Step. */ + let tabs: list(Model.tab) = + is_toplevel ? [Step, Write] : [Write, Step, Strategy]; + /* A chain's rows, then, until they reach it, the `true` a proof aims + * at: a quiet row shaped like a step row, so the chain reads evenly. A + * focus's chain rewrites part of a goal, so it aims at nothing. */ + let rec chain = + (~top=false, ~target=!is_toplevel, rows: list(Rows.t)) + : list(Node.t) => [ + Node.div( + ~attrs=[Attr.classes(["stepper", "cell-result"])], + rows_view(~top, ~prev_broken=None, rows) + @ ( + target && !refuted && !ProofCheck.is_true(Rows.reached(rows)) + ? [Row.target(~globals)] : [] + ), + ), + ] + and rows_view = (~top, ~prev_broken, rows: list(Rows.t)): list(Node.t) => { + let last = + ListUtil.last_opt(rows) |> Option.map(~f=(r: Rows.t) => r.key); + let (nodes, _) = + List.fold_left( + ~f= + ((nodes, prev_broken), row: Rows.t) => { + let status = Rows.Status.of_row(row); + let node = + view_row( + ~top, + ~prev_broken, + ~status, + ~only=List.length(rows) == 1, + ~is_last=last == Some(row.key), + row, + ); + (nodes @ node, Rows.Status.broken_mark(status)); + }, + ~init=([], prev_broken), + rows, + ); + nodes; + } + and view_row = + (~top, ~prev_broken, ~status, ~only, ~is_last, row: Rows.t) + : list(Node.t) => + switch (row.kind) { + /* With history off, only the rows where the proof continues show. */ + | Step(_) when !globals.settings.core.evaluation.stepper_history => [] + | Step(nested) => + let step = row.step; + let popup_extra = + switch (Statics.Map.lookup(Proof.rep_id(step), info_map)) { + | Some(info) => + List.concat_map( + ~f= + fun + | Mark.InexhaustiveMatch(_, _, example) => + ProofMarkView.inexhaustive_message(~globals, example) + | _ => [], + Info.marks_of(info), + ) + | None => [] + }; + let conditions = Rows.side_conditions(row); + let expanded = + switch (Model.find(row.key, model)) { + | Some(local) => local.expanded + | None => [] + }; + let toggle = i => inject((row.key, ToggleCondition(i))); + let layout = Rows.layout(row, ~expanded); + let is_open = i => + switch (layout) { + | Block({conditions, _}) => + List.mem(conditions, i, ~equal=Int.equal) + | Line => false + }; + let dots = + List.concat( + List.mapi( + ~f= + (i, ob) => + is_open(i) ? [] : [Condition.dot(~toggle=toggle(i), ob)], + conditions, + ), + ); + let block = + switch (layout) { + | Line => None + | Block({conditions: open_conditions, arms: has_arms}) => + Some( + List.filter_map( + ~f= + i => + List.nth(conditions, i) + |> Option.map(~f=ob => + Condition.view( + ~globals, + ~edit_syntax, + ~exits=exits(ob), + ~toggle=toggle(i), + ob, + ) + ), + open_conditions, + ) + @ (has_arms ? arms(row, nested) : []), + ) + }; + Row.view( + ~globals, + ~status, + ~show_equiv=prev_broken == None, + ~checking=checking(row), + ~delete=Some(edit_syntax(Picker.Patches.remove(step))), + ~popup_extra, + ~repair= + Row.repairs(~edit_syntax, ~info_map, ~proof_map, status, step), + ~editor_view=goal_view(~hints=false, ~prev_broken, row), + ~justification=Node.text(justification(step)), + ~dots, + ~block, + (), + ) + @ ( + switch (Rows.continuation(row)) { + | Some(rows) => + rows_view( + ~top, + ~prev_broken=Rows.Status.broken_mark(status), + rows, + ) + | None => [] + } + ); + | Hole + | End => + /* A `?` marks a hole written mid-proof, whose box writes between + * rows. At the end, the box alone says the proof continues here. */ + let unknown = + row.kind == Hole && !is_last + ? [div_c("step-unknown", [Node.text("?")])] : []; + /* What Enter would write, previewed on the line above the box. */ + let lozenge = (clss, text) => [ + div_c("write-preview " ++ clss, [Node.text(text)]), + ]; + let preview = + switch (Model.find(row.key, model)) { + | Some({checking: true, _}) => lozenge("checking", "checking…") + | Some({box: Some(box), _}) + when row.continues && Box.current(~tabs, box) == Write => + switch (Box.verdict(box)) { + | Some(Found([_, ..._] as steps)) => + lozenge( + "", + String.concat( + ~sep=" · ", + List.map(~f=justification, steps), + ), + ) + | Some(NotFound) => lozenge("none", "no step gets here") + | Some(Searching) => lozenge("searching", "searching…") + | Some(Found([])) + | None => [] + } + | _ => [] + }; + let justification = + div_c( + "missing-step-justification", + unknown + @ preview + @ [ + Node.div( + ~attrs=[Attr.classes(["stepper-controls"])], + controls(~top), + ), + ], + ); + /* Splices the written `?`, and its `;`, out of the proof. A hole + * that is the whole chain is left alone. */ + let delete = + row.kind == Hole && !only + ? Some(edit_syntax(Picker.Patches.remove(row.step))) : None; + /* A finished chain, or one after a broken step, has nothing to + * write. */ + let box = + switch (prev_broken, Model.find(row.key, model)) { + | (None, Some({box: Some(box), goal, _})) + when row.continues && !ProofCheck.is_true(row.goal) => + Some((box, goal)) + | _ => None + }; + let hints = + switch (box) { + | Some((box, _)) => + Box.current(~tabs, box) == Step && !checking(row) + | None => false + }; + let unproven = Rows.is_unproven(~proof_map, row); + /* With part of the goal selected, the box writes its + * replacement. */ + let replacing = + switch (box) { + | Some((box, goal)) when Box.current(~tabs, box) == Write => + Update.selected_part(goal) == None ? None : Box.columns(goal) + | _ => None + }; + /* Whether to mark where the highlighted use of a rule would act. */ + let previewing = + switch (box) { + | Some((box, _)) => Box.current(~tabs, box) == Write + | None => false + }; + let box = + switch (box) { + | Some((box, goal)) => [ + Box.view( + ~globals, + ~key=row.key, + ~tabs, + ~inject=a => inject((row.key, a)), + ~write=write(row), + ~write_steps=write_steps(row), + ~take_focus=take_focus(Box(row.key)), + ~focused=focused(Box(row.key)), + ~escape= + Ui_effect.Many([ + take_focus(Goal(row.key)), + Ui_effect.of_sync_fun( + () => Haz3lcore.FocusEffect.schedule_cell(), + (), + ), + ]), + ~replacing, + box, + goal, + ), + ] + | None => [] + }; + switch (prev_broken, Model.find(row.key, model)) { + | (Some(_), _) + | (None, Some(_)) => + Row.view( + ~globals, + ~status, + ~show_equiv=prev_broken == None, + ~pending=unproven, + ~checking=checking(row), + ~delete, + ~editor_view= + goal_view( + ~hints, + ~previewing, + ~into_box=replacing != None, + ~prev_broken, + row, + ), + ~justification, + (), + ) + @ box + | (None, None) => [justification] + }; + } + /* The goals a step creates, as dark arms: a bar naming what the arm + * adds over a slot holding the arm's own stepper. */ + and arms = (row: Rows.t, nested: Rows.nested): list(Node.t) => { + let step = row.step; + let note = content => div_c("step-arm-note", content); + let arm = (bar, slot) => [ + div_c("step-arm-bar", bar), + div_c("step-slot", slot), + ]; + let dark = sections => [div_c("step-section arm", sections)]; + let form_arg = fallback => + splice( + ~step, + ~slot=Arg, + ~target=SubEditor.Target.child(~anchor=Proof.rep_id(step), 0), + fallback, + ); + /* An `assume` or `have` bar names its fact. The proposition shows + * as the goal above (an antecedent) or the block's first goal, so + * the bar offers it for editing only while it is still a hole. */ + let fact_bar = (prop: Exp.t, name: option(Pat.t), ~default, ~what) => { + let name = + name |> Option.bind(_, ~f=Pat.get_var) |> Option.value(~default); + switch (prop.term) { + | EmptyHole => [ + form_arg(Exp(prop)), + note([Node.text("as " ++ name)]), + ] + | _ => [ + div_c("step-arm-fact", [Node.text(name)]), + note([Node.text(what)]), + ] + }; + }; + switch (nested, step.term) { + | (Body(rows), Forall(p, _)) => + let typ = + switch (Pat.get_var(p), rows) { + | (Some(x), [first, ..._]) => + Rows.ctx(first) + |> Option.bind(_, ~f=ctx => + Ctx.lookup_var(SemanticCtx.get_ctx(ctx), x) + ) + |> Option.map(~f=(entry: Ctx.var_entry) => + [Node.text(", any "), code(Typ(entry.typ))] + ) + | _ => None + }; + dark( + arm( + [ + div_c("step-arm-code", [code(Pat(p))]), + note([Node.text("fixed")] @ Option.value(~default=[], typ)), + ], + chain(rows), + ), + ); + | (Body(rows), Funext(p, _)) => + dark( + arm( + [form_arg(Pat(p)), note([Node.text("any argument")])], + chain(rows), + ), + ) + | (Body(rows), Assume(e, name, _)) => + dark( + arm( + fact_bar(e, name, ~default="assume", ~what="assumed"), + chain(rows), + ), + ) + | (Body(rows), Revert(e, _, _)) => + dark( + arm( + [ + form_arg(Exp(e)), + note([Node.text("now a premise of the goal")]), + ], + chain(rows), + ), + ) + | (Body(rows), Generalize(e, _)) => + dark( + arm( + [form_arg(Exp(e)), note([Node.text("quantified again")])], + chain(rows), + ), + ) + | (Premises({sub, _}), Have(e, name, _, _)) => + dark( + arm( + fact_bar(e, name, ~default="have", ~what="proved below"), + chain(sub), + ), + ) + | (Cases(case_rows), Cases(scrut, cases)) => + split(~keyword="cases", row, scrut, cases, case_rows) + | (Cases(case_rows), Induction(scrut, cases)) => + split(~keyword="induction", row, scrut, cases, case_rows) + /* The goal above underlines what the block works on, so the bar + * doesn't repeat the selector. */ + | (Focus(rows), Focus(_)) => + dark( + arm( + [note([Node.text("rewritten in place")])], + chain(~target=false, rows), + ), + ) + | (Leaf | Body(_) | Cases(_) | Premises(_) | Focus(_), _) => [] + }; + } + and split = (~keyword, row: Rows.t, scrut: Exp.t, cases, case_rows) => { + let step = row.step; + let anchor = Proof.rep_id(step); + let set_cases = cases => + switch (Picker.Patches.set_cases(step, cases)) { + | Some(patch) => edit_syntax(patch) + | None => Ui_effect.Ignore + }; + /* The facts a case adds to the split's scope: the case equation or + * the inductive hypotheses. */ + let outer_facts = + Rows.ctx(row) + |> Option.map(~f=SemanticCtx.facts) + |> Option.value(~default=[]) + |> List.map(~f=((_, id, _)) => id); + let hypotheses = (rows: list(Rows.t)) => + switch (rows) { + | [first, ..._] => + Rows.ctx(first) + |> Option.map(~f=SemanticCtx.facts) + |> Option.value(~default=[]) + |> List.filter(~f=((_, id, _)) => + !List.mem(outer_facts, id, ~equal=Id.equal) + ) + |> List.rev_map(~f=((name, _, fact)) => + div_c( + "step-arm-fact", + [ + Node.text(name ++ ": "), + code( + Exp( + ProofRule.conclusion_exp(ProofRule.exp_to_rule(fact)), + ), + ), + ], + ) + ) + | [] => [] + }; + let case = (i, (pat: Pat.t, rows)) => { + let remove_case = + Widgets.button( + Icons.trash, + _ => + switch (ListUtil.remove_nth(i, cases)) { + | Some(cases) => set_cases(cases) + | None => Ui_effect.Ignore + }, + ~tooltip="Remove case", + ~clss=["subtle-button"], + ); + let pattern = + splice( + ~step, + ~slot=Pattern(i), + ~target= + SubEditor.Target.( + child(~anchor, 0) + |> descend(NthTile(["|", "=>"], i), ~child=0) + ), + Pat(pat), + ); + /* A refused arm's steps have no goal to act on, so the arm shows + * why in place of them. */ + let (note, slot) = + switch (Rows.refused_binding(row, pat)) { + | Some(var) => ( + div_c( + "step-arm-refusal", + ProofMarkView.message(~globals, BinderCaptures({var: var})), + ), + [], + ) + | None => ( + div_c("step-arm-note", hypotheses(rows)), + [div_c("step-slot", chain(rows))], + ) + }; + [ + div_c( + "step-arm-bar", + [Node.text("| "), pattern, note, remove_case], + ), + ] + @ slot; + }; + let add_case = + Picker.Patches.add_case( + step, + ~marks= + Option.value_map(row.entry, ~default=[], ~f=(e: ProofMap.entry) => + e.marks + ), + ) + |> Option.map(~f=patch => + Widgets.button( + Node.text("Case ..."), + ~tooltip="Add case", + ~clss=["subtle-button", "add-case-button"], + _ => + edit_syntax(patch) + ) + ) + |> Option.to_list; + /* The scrutinee is edited in place, in the bar that opens the C. */ + let scrut_bar = + div_c( + "step-arm-bar", + [ + Node.text(keyword ++ " on "), + splice( + ~step, + ~slot=Scrut, + ~target= + SubEditor.Target.( + child(~anchor, 0) + |> until(BeforeOrEnd(NthTile(["|", "=>"], 0))) + ), + Exp(scrut), + ), + ], + ); + [ + div_c( + "step-section arm", + [scrut_bar] + @ List.concat(List.mapi(~f=case, case_rows)) + @ add_case, + ), + ]; + }; let settings_modal = is_toplevel && globals.settings.core.evaluation.show_settings ? SettingsModal.view( @@ -112,15 +2701,9 @@ module View = { globals.settings.core.evaluation, ) : []; - settings_modal - @ StepperBase.Stepper.view( - ~globals, - ~take_focus=f => signal(MakeActive(f)), - ~hide_stepper=signal(HideStepper), - ~inject=u => inject(u), - ~is_toplevel, - ~focus=selected, - model.root, - ); + let rows = + is_toplevel + ? Rows.chain(~proof_map, proof) : Rows.of_theorem(~proof_map, proof); + settings_modal @ chain(~top=true, rows); }; }; diff --git a/src/web/view/TheoremExerciseMode.re b/src/web/view/TheoremExerciseMode.re index 487f77624f..235ac1ccf6 100644 --- a/src/web/view/TheoremExerciseMode.re +++ b/src/web/view/TheoremExerciseMode.re @@ -38,14 +38,10 @@ module Model = { }; [@deriving (show({with_path: false}), sexp, yojson)] - type persistent = { - lemmas: CellEditor.Model.persistent, - theorem: EvalResult.Model.persistent, - }; + type persistent = {lemmas: CellEditor.Model.persistent}; let persist = (model: t): persistent => { lemmas: model.cells.lemmas |> CellEditor.Model.persist, - theorem: model.cells.theorem.result |> EvalResult.Model.persist, }; let unpersist = @@ -60,12 +56,8 @@ module Model = { prelude: CellEditor.Model.mk(Editor.Model.mk(spec.prelude, ~root=Exp)), lemmas: persistent.lemmas |> CellEditor.Model.unpersist(~settings), - theorem: { - editor: - CellEditor.Model.mk(Editor.Model.mk(spec.theorem, ~root=Exp)). - editor, - result: persistent.theorem |> EvalResult.Model.unpersist, - }, + theorem: + CellEditor.Model.mk(Editor.Model.mk(spec.theorem, ~root=Exp)), }, editing_flags: editing_flags_false, }; @@ -273,6 +265,20 @@ module Update = { theorem: new_cell, }, }; + | Theorem(PatchMainEditor(patch)) => + let* new_cell = + CellEditor.Update.update( + ~settings, + PatchMainEditor(patch), + model.cells.theorem, + ); + { + ...model, + cells: { + ...model.cells, + theorem: new_cell, + }, + }; | Theorem(MainEditor(_)) => print_endline("Instructor-only action"); Updated.return_quiet(model); @@ -323,7 +329,7 @@ module Update = { |> EditorUtil.append_exp( _, just_prelude_term - |> Language.ProofHacks.strip_theorems + |> Language.ProofSyntax.strip_theorems |> Language.Exp.replace_all_ids, ) |> EditorUtil.append_exp(_, just_theorem_term); @@ -388,8 +394,8 @@ module Update = { ~pos_of_key=key => key, ~dispatch, ~on_timeout= - List.iter(~f=((key, _)) => - dispatch(key, UpdateResult(ResultFail(Timeout))) + List.iter(~f=((key, v: WorkerServer.Request.value)) => + dispatch(key, UpdateResult(v.generation, ResultFail(Timeout))) ), ); diff --git a/src/web/view/TutorialMode.re b/src/web/view/TutorialMode.re index 6bfc6f5af5..76bed29c1a 100644 --- a/src/web/view/TutorialMode.re +++ b/src/web/view/TutorialMode.re @@ -167,17 +167,25 @@ module Update = { }; | None => Updated.return_quiet(model) } - | Editor(pos, ResultAction(result_action) as action) + | Editor(pos, (ResultAction(_) | PatchMainEditor(_)) as action) when Tutorial.is_editable(pos, ~instructor_mode) - || EvalResult.Update.applies_to_read_only(result_action) => + || ( + switch (action) { + | ResultAction(result_action) => + EvalResult.Update.applies_to_read_only(result_action) + | MainEditor(_) + | PatchMainEditor(_) => false + } + ) => let cell = Tutorial.get_stitched(pos, model.cells); let* new_cell = CellEditor.Update.update(~settings, action, cell); { ...model, cells: Tutorial.put_stitched(pos, model.cells, new_cell), }; - | Editor(_, ResultAction(_)) => Updated.raise_invalid_action(model) // TODO: I think this case should never happen + | Editor(_, ResultAction(_) | PatchMainEditor(_)) => + Updated.raise_invalid_action(model) // TODO: I think this case should never happen | RefreshStatics => CodeWithStatics.StaticsDebounce.force_on_next := true; model |> Updated.return_quiet(~recalculate=true); @@ -257,6 +265,15 @@ module Update = { stitched_elabs, model.cells, ); + /* A timeout fails every cell, tagged with the generation each had when + * this batch was enqueued, so a cell that has re-requested since + * ignores it. */ + let timeout_gens = + Tutorial.map_stitched( + (_, cell: CellEditor.Model.t) => + EvalResult.Model.request_gen(cell.result), + cells, + ); EvalRequest.request( worker_request^, ~pos_of_key=Tutorial.pos_of_key, @@ -267,14 +284,14 @@ module Update = { _ => ignore( Tutorial.map_stitched( - (pos, _) => + (pos, gen) => schedule_action( Editor( pos, - ResultAction(UpdateResult(ResultFail(Timeout))), + ResultAction(UpdateResult(gen, ResultFail(Timeout))), ), ), - model.cells, + timeout_gens, ), ), ); diff --git a/src/web/www/dune b/src/web/www/dune index 6a7c57a033..57c3eb8de0 100644 --- a/src/web/www/dune +++ b/src/web/www/dune @@ -13,3 +13,13 @@ prebundle.js --bundle --outfile=bundled.js))) + +(rule + (targets worker-algebrite.js) + (deps workerprelude.js) + (action + (run + %{project_root}/node_modules/esbuild/bin/esbuild + workerprelude.js + --bundle + --outfile=worker-algebrite.js))) diff --git a/src/web/www/style/cell.css b/src/web/www/style/cell.css index c9122f58ad..39a0a65db4 100644 --- a/src/web/www/style/cell.css +++ b/src/web/www/style/cell.css @@ -25,7 +25,7 @@ :is(#main.Scratch, #main.Documentation, -#main.Configuration):not(.Derivations) > * > .code-editor { +#main.Configuration):not(.Derivations) > * > .code-scroll { background-color: var(--cell-active); } @@ -33,8 +33,18 @@ #main.Documentation, #main.Configuration):not(.Derivations) .cell { flex-grow: 1; - /* stretch background under probe overlays; --main-scroll-width set by ScrollWidth */ - width: var(--main-scroll-width, max-content); + /* The pane's width, whatever the cell holds: its code scrolls in + * .code-scroll, and a result too wide for the pane overflows the cell. */ + width: 100%; +} + +/* The result row (not a stepper, which is a .cell-result too) grows with a + * value that can't wrap to the pane, keeping its background under the value + * and its toggle beyond it. */ +:is(#main.Scratch, +#main.Documentation, +#main.Configuration):not(.Derivations) .cell > .cell-result:not(.stepper) { + min-width: max-content; } #main.Tutorial, @@ -87,11 +97,36 @@ flex-direction: column; } -.cell > * { +.cell > *, +.code-scroll > * { padding: 1em; padding-left: 1.2em; } +/* The cell's code scrolls sideways in this box, so that a long line widens + * neither the cell nor the views below the code. A box that scrolls one way + * clips the other, so whatever has to show past the code's top or bottom + * edge is position: fixed (see FloatingElement.re). */ +.cell > .code-scroll { + /* the editor inside takes the padding, to scroll with the code */ + padding: 0; + overflow-x: auto; + overflow-y: hidden; + /* keeps the code's width out of the cell's own max-content width */ + contain: inline-size; + scrollbar-width: thin; +} + +/* At least as wide as the box, so the whole visible row takes clicks. */ +.cell > .code-scroll > .code-editor { + width: max-content; + min-width: 100%; + /* Clipped here, vertical overflow adds no scrollable height to the box. + * With any, JsUtil.find_scroll_container would take the box for the + * code's vertical scroller. */ + overflow-y: clip; +} + .cell-item { display: flex; flex-direction: column; @@ -376,12 +411,14 @@ border-left: 1px solid transparent; } -.cell .cell-item:first-child { +.cell .cell-item:first-child, +.cell > .code-scroll:first-child { border-top-left-radius: 0.4em; border-top-right-radius: 0.4em; } -.cell .cell-item:last-child { +.cell .cell-item:last-child, +.cell > .code-scroll:last-child { border-bottom-left-radius: 0.4em; border-bottom-right-radius: 0.4em; } diff --git a/src/web/www/style/cursor-inspector.css b/src/web/www/style/cursor-inspector.css index 7aab0e6d06..f51763f13e 100644 --- a/src/web/www/style/cursor-inspector.css +++ b/src/web/www/style/cursor-inspector.css @@ -409,4 +409,33 @@ .context-inspector .context-entry .seperator { color: var(--context-inspector-colon); -} \ No newline at end of file +} +/* Totality badge — tiny icon next to Γ in the ci-header, expression + cursors only. Mirrors .gamma sizing but is non-interactive (it is a + readout, not a toggle) and slightly smaller so it stays quiet. */ + +#cursor-inspector .totality { + display: flex; + align-items: center; + height: 100%; + width: 1.4em; + cursor: default; +} + +#cursor-inspector .totality svg { + scale: 0.44; + fill: var(--cell-active); + opacity: 0.55; +} + +#cursor-inspector .totality:hover svg { + opacity: 1; +} + +#cursor-inspector .totality.not-total svg { + opacity: 0.35; +} + +#cursor-inspector .totality.not-total:hover svg { + opacity: 0.8; +} diff --git a/src/web/www/style/dynamics.css b/src/web/www/style/dynamics.css index 437318b8a5..15c720b4e0 100644 --- a/src/web/www/style/dynamics.css +++ b/src/web/www/style/dynamics.css @@ -121,6 +121,19 @@ color: var(--text-black); } +/* Evaluation-failure banner shown above an open stepper: the stepper + * renders the last successful proof map, so mark it stale. */ +.cell-item.cell-result.stepper-stale { + background-color: var(--eval-exception); +} + +.cell-item.cell-result.stepper-stale .stale-note { + padding: 0 0.25em 0.25em 0.25em; + font-style: italic; + font-size: 0.85em; + color: var(--BLACK); +} + .cell-result .icon:hover svg { animation: wobble 0.6s ease 0s 1 normal forwards; transform: scale(130%); diff --git a/src/web/www/style/editor.css b/src/web/www/style/editor.css index e72796a24f..e1561ea85c 100644 --- a/src/web/www/style/editor.css +++ b/src/web/www/style/editor.css @@ -116,6 +116,12 @@ .code .token.MPat { color: var(--token-mpat); } +.code .token.Proof { + color: var(--token-proof); +} +.code .token.PRul { + color: var(--token-prul); +} .code .token.poly, .code .token.keyword { @@ -265,6 +271,16 @@ svg.shard.indicated.Sig { svg.shard.indicated.MPat { filter: drop-shadow(var(--off-x) var(--off-y) var(--blur) var(--token-mpat)); } +svg.shard.indicated.Proof { + filter: drop-shadow( + var(--off-x) var(--off-y) var(--blur) var(--shard-lines-proof) + ); +} +svg.shard.indicated.PRul { + filter: drop-shadow( + var(--off-x) var(--off-y) var(--blur) var(--shard-lines-prul) + ); +} svg.shard.indicated.Any > path { fill: var(--shard-any); @@ -296,6 +312,12 @@ svg.shard.indicated.Sig > path { svg.shard.indicated.MPat > path { fill: var(--shard-mpat); } +svg.shard.indicated.Proof > path { + fill: var(--shard-proof); +} +svg.shard.indicated.PRul > path { + fill: var(--shard-prul); +} svg.shard.indicated.caret.Exp > path { fill: var(--shard-caret-exp); @@ -318,6 +340,12 @@ svg.shard.indicated.caret.Sig > path { svg.shard.indicated.caret.MPat > path { fill: var(--shard-caret-mpat); } +svg.shard.indicated.caret.Proof > path { + fill: var(--shard-caret-proof); +} +svg.shard.indicated.caret.PRul > path { + fill: var(--shard-caret-prul); +} svg.shard.selected { z-index: var(--select-z); @@ -554,6 +582,12 @@ svg:has(.child-line) { .child-line.MPat { stroke: var(--token-mpat); } +.child-line.Proof { + stroke: var(--shard-lines-proof); +} +.child-line.PRul { + stroke: var(--shard-lines-prul); +} /* Invisible backdrop to capture clicks outside context menu */ .context-menu-backdrop { diff --git a/src/web/www/style/nut-menu.css b/src/web/www/style/nut-menu.css index ac99e57a8c..2c41f61ebe 100644 --- a/src/web/www/style/nut-menu.css +++ b/src/web/www/style/nut-menu.css @@ -275,13 +275,6 @@ border: solid 1px var(--border-soft); } -#top-bar .nut-menu .toggle-switch.active { - background-color: var(--primary-accent); - border: solid 1px transparent; -} -#top-bar .nut-menu .toggle-switch.active .toggle-knob { - color: var(--primary-accent); -} #top-bar #editor-mode { height: 100%; diff --git a/src/web/www/style/settings-panel.css b/src/web/www/style/settings-panel.css index 415d2225dd..f4a017a4cf 100644 --- a/src/web/www/style/settings-panel.css +++ b/src/web/www/style/settings-panel.css @@ -149,10 +149,6 @@ height: 0.7em; } -#settings-panel .settings-toggle .toggle-switch.active { - background-color: var(--primary-accent); -} - #settings-panel .settings-toggle .toggle-switch.active .toggle-knob { margin-left: 0.75em; margin-right: 1px; diff --git a/src/web/www/style/sidebar.css b/src/web/www/style/sidebar.css index 7d6b72222b..e93d4ab5d5 100644 --- a/src/web/www/style/sidebar.css +++ b/src/web/www/style/sidebar.css @@ -277,6 +277,21 @@ box-shadow: inset 0 0 0 1px var(--hole-stroke); } +.problem-row.runtime { + border-left: 3px solid color-mix(in srgb, var(--RT1) 60%, transparent); + background-color: color-mix(in srgb, var(--RT0) 50%, transparent); +} + +.problem-row.runtime:hover { + background-color: var(--RT0); +} + +.problem-row.runtime.active { + border-left: 5px solid var(--RT2); + background-color: color-mix(in srgb, var(--RT0) 80%, transparent); + box-shadow: inset 0 0 0 1px var(--RT1); +} + .problem-row.warning { border-left: 3px solid color-mix(in srgb, var(--warning-hole-stroke) 60%, transparent); @@ -339,6 +354,10 @@ background-color: var(--surface-error); } +.legend-swatch.runtime { + background-color: var(--RT1); +} + .legend-swatch.warning { background-color: var(--warning-hole-stroke); } diff --git a/src/web/www/style/stepper.css b/src/web/www/style/stepper.css index e031855244..ce1c275968 100644 --- a/src/web/www/style/stepper.css +++ b/src/web/www/style/stepper.css @@ -36,48 +36,6 @@ gap: 0.5em; } -.induction-scrut { - display: flex; - flex-direction: row; - gap: 0.5em; - align-items: center; -} - -.induction-case { - display: flex; - flex-direction: column; - gap: 0.5em; - margin-left: 2em; -} - -.induction-case .stepper { - margin-left: 2em; -} -.induction-case-header { - display: flex; - flex-direction: row; - gap: 0.5em; - align-items: center; - border-top: 1px dotted var(--cell-result-border); - padding-top: 0.5em; - margin-left: -1em; -} - -.induction-case-hypothesis { - display: flex; - flex-direction: row; - gap: 0.5em; - margin-left: 3em; - align-items: center; -} - -.induction-case-patten { - display: flex; - flex-direction: row; - gap: 0.5em; - align-items: center; -} - .stepper .subtle-button { opacity: 0; cursor: pointer; @@ -89,21 +47,19 @@ transition: all 0.3s; } -.add-case-button { - margin-left: 2.5em; - color: --frame-4; -} - .stepper .subtle-button:hover { opacity: 1; } -.stepper .induction-case:hover .subtle-button { +*:hover > .subtle-button { opacity: 1; } -*:hover > .subtle-button { - opacity: 1; +/* Inline chips get their spacing from the wrapper's own padding; the + * main-editor gutter (`#main .code-editor { padding-left: 1em }`, + * reserved for when line numbers are off) doesn't apply here. */ +#main .inline-editor-wrapper .code-editor { + padding-left: 0; } /* The hexagon is drawn by ::before rather than by clipping the wrapper: @@ -136,81 +92,287 @@ /* PROVER */ -.missing-step-overlay-align { +/* A broken step's repair buttons, in its popup. */ +.proof-button { + cursor: pointer; + pointer-events: all; + background-color: var(--surface-accent-strong); + color: var(--text-sunken) !important; + padding: 0.2em 0.5em; + border-radius: 0.2em; + white-space: nowrap; +} + +/* The write box: tabs over a code box, under the goal of an unfinished + * chain. Indented to line up with the goal's text past the `≡`. */ +.write-box { + position: relative; + padding: 0.3em 1.5em 0.4em 2.6em; + margin-right: 14px; + display: flex; + flex-direction: column; + gap: 0.25em; +} + +/* Writing a selected part's replacement, the box moves right of the part, + * an arrow running to it from the part. 3.3em in is the goal's first + * column: the box's padding and its input's. */ +.write-box { + transition: padding-left 0.4s ease-in-out; +} + +/* The box keeps room for its tabs and some text, so near the right of a + * long goal it stops short of the part, the arrow running into it. */ +.write-box.replacing { + padding-left: min(calc(3.3em + var(--shift)), calc(100% - 1.5em - 22em)); +} + +.write-arrow { position: absolute; + left: 3.3em; + top: -10px; + overflow: visible; + pointer-events: none; + fill: none; + stroke: var(--cell-result-text); + stroke-width: 1.5; + stroke-dasharray: 4 3; + animation: write-arrow-in 0.6s ease-in both; +} + +@keyframes write-arrow-in { + 0%, + 50% { + opacity: 0; + } + 100% { + opacity: 1; + } +} + +.box-tabs { + display: flex; + flex-direction: row; + align-items: flex-end; + gap: 1.1em; + font-family: var(--ui-font); + font-size: 0.8em; + font-weight: 600; + color: var(--text-muted); +} + +.box-tab { + white-space: nowrap; + cursor: pointer; + padding-bottom: 2px; + border-bottom: 2px solid transparent; +} + +.box-tab:hover { + color: var(--cell-result-text); +} + +.box-tab.on { + color: var(--stepper-condition-text); + border-bottom-color: var(--stepper-condition-text); } -/* Every result row is an isolated stacking context, so a later sibling row - * (or editor layers up to --projector-overlay-z, e.g. .code-text) would paint - * over the active proof row's controls and an open assumptions/rewrite panel. - * Raise the nested row above them; only nested rows, so the outermost proof - * stays an ordinary isolated cell and the page's context menu stays on top. */ -.cell-result .cell-result:has(.missing-step-overlay-align) { +/* What a tab shows under the tabs, at least as tall as the Write tab's + * box, so switching tabs doesn't move what is below. */ +.box-body { + display: flex; + flex-direction: column; + gap: 0.25em; + min-height: 2.2em; +} + +/* Above the arrow, which near the right of a long goal ends inside the + * box. */ +.box-input { position: relative; - z-index: var(--proof-step-raised-z); + z-index: 1; + display: flex; + flex-direction: row; + align-items: center; + gap: 0.6em; + background-color: var(--light-page-color); + border: 1px solid var(--border-default); + border-radius: 6px; + padding: 0.25em 0.6em; } -.cell-result .cell-result:has(.axiom-box, .rewrite-box) { - z-index: var(--proof-step-panel-z); +.box-editor { + position: relative; + flex-grow: 1; + min-width: 4em; } -/* A context menu opened inside a proof (in a case pattern, the induction - * scrutinee or a rewrite box) shares the proof's stacking context with the - * raised rows above, so it and its backdrop have to clear them too. */ -.cell-result .context-menu-backdrop { - z-index: calc(var(--proof-step-panel-z) + 1); +#main .box-editor .code-editor { + padding-left: 0; } -.cell-result .context-menu { - z-index: calc(var(--proof-step-panel-z) + 2); +/* An empty box draws no hole: it shows what Tab takes instead. */ +.box-editor.empty .empty-hole { + visibility: hidden; } -.proof-context-box { +/* What Tab takes, faded behind an empty box. */ +.box-ghost { position: absolute; - top: calc(100% + 0.5em); - left: 2em; - z-index: var(--context-inspector-z); + inset: 0 auto auto 0; + pointer-events: none; + opacity: 0.45; +} + +.box-hint { + display: flex; + align-items: center; + gap: 0.35em; + font-family: var(--ui-font); + font-size: 0.75em; + color: var(--text-muted); + white-space: nowrap; +} + +.box-key { + font-size: 0.9em; + border: 1px solid var(--cell-result-border); + border-radius: 3px; + padding: 0 0.35em; + color: var(--cell-result-text); + background-color: var(--cell-result); +} + +.box-hint-none { + color: var(--text-error-strong); +} + +.box-hint:has(.box-hint-none) .box-key { + opacity: 0.45; +} + +/* What Enter would write, dashed: it isn't written yet. */ +.write-preview { + font-family: var(--ui-font); + font-size: 0.8em; + padding: 0 0.7em; + border: 1px dashed var(--stepper-lozenge-border); + border-radius: 999px; + background-color: var(--cell-result); + color: var(--cell-result-text); + white-space: nowrap; + /* So that the lozenge doesn't change width with each key. */ + min-width: 7em; + text-align: center; +} + +.write-preview.searching { + opacity: 0.6; +} + +.write-preview.none { + border-color: oklch(55% 0.15 30); + background-color: oklch(93% 0.04 30); + color: oklch(45% 0.15 30); +} + +/* Under the box: the goal each use of a rule gives, or the names the + * text completes to. */ +.box-items { display: flex; flex-direction: column; - gap: 0.5em; + background-color: var(--light-page-color); + border: 1px solid var(--cell-result-border); + border-radius: 6px; + overflow: hidden; } -.proof-selection-buttons { +.box-item { display: flex; flex-direction: row; - gap: 0.5em; + justify-content: space-between; + align-items: center; + gap: 1em; + padding: 0.2em 0.6em; + cursor: pointer; + border-top: 1px solid var(--cell-result); } -.proof-button { - cursor: pointer; - pointer-events: all; - background-color: var(--surface-accent-strong); - color: var(--text-sunken) !important; - padding: 0.2em 0.5em; - border-radius: 0.2em; +.box-item:first-child { + border-top: none; +} + +.box-item.on { + background-color: var(--stepper-lozenge-bkg); +} + +.box-item-rule, +.box-item-note { + font-family: var(--ui-font); + font-size: 0.75em; white-space: nowrap; + color: var(--cell-result-text); +} + +.box-item-rule { + padding: 0 0.7em; + border: 1px solid var(--stepper-lozenge-border); + border-radius: 999px; } -.axiom-box { - background-color: var(--menu-bkg); - border-radius: 0 0 0.5em 0; - outline: 0.6px solid var(--menu-outline); - box-shadow: 0px 10px 20px var(--menu-shadow); - padding: 10px; +/* The Proof strategy tab's buttons sit on the panel, not on a code + * background: they aren't code. */ +.strategy-buttons { display: flex; - flex-direction: column; - gap: 5px; + flex-direction: row; + flex-wrap: wrap; + align-items: flex-start; + gap: 0.4em; + padding: 0.15em 0; } -.rewrite-box { - background-color: var(--menu-bkg); - border-radius: 0 0 0.5em 0; - outline: 0.6px solid var(--menu-outline); - box-shadow: 0px 10px 20px var(--menu-shadow); - padding: 10px; +.strategy-button { display: flex; - flex-direction: column; - gap: 5px; + align-items: baseline; + gap: 0.4em; + cursor: pointer; + font-family: var(--ui-font); + font-size: 0.85em; + padding: 0.2em 0.7em; + border: 1px solid var(--border-default); + border-radius: 4px; + background-color: var(--cell-result); + color: var(--stepper-condition-text); + white-space: nowrap; +} + +.strategy-button:hover { + background-color: var(--stepper-lozenge-bkg); +} + +/* The goal's own introduction comes first, dark. */ +.strategy-button.intro { + background-color: var(--stepper-arm); + border-color: var(--stepper-arm); + color: var(--stepper-arm-text); +} + +.strategy-separator { + align-self: stretch; + width: 1px; + background-color: var(--cell-result-border); + margin: 0 0.2em; +} + +/* A context menu opened inside a proof (in a case pattern, the induction + * scrutinee or the write box) shares the proof's stacking context, so it + * and its backdrop are raised above the proof's step panels. */ +.cell-result .context-menu-backdrop { + z-index: calc(var(--proof-step-panel-z) + 1); +} + +.cell-result .context-menu { + z-index: calc(var(--proof-step-panel-z) + 2); } /* STEPPER (OLD) */ @@ -241,18 +403,36 @@ fill: var(--exp-ap) !important; cursor: pointer; } -.step-taken > svg.shard > path, -.step-taken > svg.shard > path *:not(.EmptyHole *, .EmptyHole) { - border: 1px var(--border-soft); - fill: var(--text-faint); + +/* What the step below acts on: a line in the color of the C a focus + opens, drawn under the text rather than as a plate, and not clickable, + so it can't be taken for an offered step. It sits above projectors, + whose boxes would otherwise hide it under a folded name. */ +.step-acts-on { + pointer-events: none; + box-sizing: border-box; + border-bottom: 2px solid var(--stepper-arm); + z-index: calc(var(--projector-hover-z) + 1); +} + +/* Where the suggestion the user is choosing would act: dashed, as it + isn't written yet. */ +.step-previewing { + pointer-events: none; + box-sizing: border-box; + border-bottom: 2px dashed var(--stepper-arm); + z-index: calc(var(--projector-hover-z) + 1); +} + +/* The same line under all of a read-only goal, which has no overlays. */ +.step-acts-on-whole .code-text { + text-decoration: underline 2px var(--stepper-arm); + text-underline-offset: 0.3em; } .step-next > svg > path.child-line { stroke: var(--border-success-muted); } -.step-taken > svg > path.child-line { - stroke: var(--border-soft); -} .step-refl > svg > path.child-line { stroke: var(--border-typ); } @@ -269,9 +449,6 @@ z-index: var(--stepper-interactive-z) !important; filter: drop-shadow(1px 1px var(--shadow-typ)) !important; } -.step-taken > svg.shard { - filter: drop-shadow(1px 1px var(--shadow-soft)) !important; -} /* In high contrast the plate cannot carry the highlight on its own. The ink sits at an extreme, so a fill far enough from the page to read as a @@ -360,14 +537,546 @@ cursor: not-allowed; } -.assumption-box { +.step-placeholder { + background-color: var(--test-panel-bkg) +} + +/* Per-row status (see StepperView.View.Row). Status must never change the + * proof's layout, so both indicators live outside the document flow: + * + * 1. An indicator line along the row's right edge, drawn by an + * absolutely-positioned ::after: solid red = broken, tan = + * incomplete, dotted lighter red = blocked (waiting on the step + * above). Ok/pending rows draw nothing. + * 2. A popup anchored above the justification, hidden until the + * justification is clicked, carrying the error message and repair + * actions. */ +.step-border { + position: relative; + /* Reserved gutter for the status indicator line. Always present — + * whether or not an indicator is drawn — so a row gaining or losing + * status never shifts layout. Because it's margin (not padding), the + * gutter sits outside the dotted separators between steps: the + * indicator floats in clear space to the right of the row. */ + margin-right: 14px; +} + +/* Lozenge-shaped line, rounded caps, centered in the gutter. Like the + * justification, the status describes the transition out of this row + * (the step), not the expression — so the lozenge is a fixed-height + * mark centered on the same between-rows boundary the justification + * sits on, rather than spanning the row. */ +.step-border.broken::after, +.step-border.incomplete::after, +.step-border.blocked::after { + content: ""; + position: absolute; + top: calc(100% - 0.75em); + height: 1.5em; + right: -9px; + width: 3px; + border-radius: 1.5px; + pointer-events: none; +} + +.step-border.broken::after { + background-color: var(--step-indicator-broken); +} + +.step-border.incomplete::after { + background-color: var(--step-indicator-incomplete); +} + +.step-border.blocked::after { + /* Round dots via a repeating radial gradient (border dots render + * square in some engines), keeping the dotted variant in the same + * rounded language as the solid lozenges. */ + background-image: radial-gradient( + circle at 50% 2px, + var(--step-indicator-blocked) 1.5px, + transparent 1.9px + ); + background-size: 3px 7px; + background-repeat: repeat-y; +} + +/* A goal not established yet: borrowed from the row above while its step + * is checked, or still to be proven by the body of the form above. */ +.step-border.goal-pending > .step-display > .step-output { + opacity: 0.5; +} + +/* A check usually lands within a moment, so a borrowed goal fades only + * if it doesn't. */ +.step-border.checking > .step-display > .step-output { + animation: checking-fade 0.3s ease-in 0.4s both; +} + +@keyframes checking-fade { + from { + opacity: 1; + } + to { + opacity: 0.5; + } +} + +.write-preview.checking { + animation: checking-show 0.3s ease-in 0.4s both; +} + +@keyframes checking-show { + from { + opacity: 0; + } + to { + opacity: 0.6; + } +} + +/* Blocked rows keep rendering (never dropped); grey the body so the + * chain visibly reads as "on hold" below the break. Opacity does not + * affect layout. */ +.step-border.blocked > .step-display { + opacity: 0.5; +} + +/* The justification wrapper anchors the popup. When the row has + * something to explain, it reads as a button and toggles the popup via + * :focus-within (the popup is inside the wrapper, so clicking a repair + * button keeps focus within it and the click lands). */ +.step-justification-wrap { + position: relative; + display: flex; + align-items: center; + border: 1px solid var(--stepper-lozenge-border); + border-radius: 0.3em; + padding: 0 0.4em; + background-color: var(--stepper-lozenge-bkg); +} + +/* A hole or a chain's end has no step to justify: its wrap holds only + * the stepper's controls, so it draws no lozenge. */ +.step-justification-wrap:has(> .missing-step-justification) { + border: none; + padding: 0; + background-color: transparent; +} + +/* ---- Transition-aligned justifications ---- + * + * A justification lives semantically between two steps: it explains how + * the expression above becomes the expression below. So it renders + * offset half a step down, sitting on the boundary line between the two + * rows. The offset is a pure transform: the wrap still occupies its + * original slot in the row's flex layout, so expression width, row + * heights, and selection geometry are untouched (and the popup anchor + * moves with it). + * + * 50% = half the band's own height (from row-center to the content's + * bottom edge), + 0.5em = the row's bottom padding, landing the band's + * center on the next row's border-top. */ +.step-display > .step-transition { + /* Into the row's right padding, so the trash can after the lozenge + * sits in a column of its own, clear of any block's C. */ + margin-right: -0.5em; display: flex; flex-direction: row; - gap : 1em; align-items: center; - margin-left: 2em; + gap: 0.3em; + transform: translateY(calc(50% + 0.5em)); + z-index: 1; + /* Sit on the separator line: an opaque background, padded on the left, + * so the line reads as interrupted by the label ("——— eval 🗑") rather + * than struck through it. */ + background-color: var(--cell-result); + padding-left: 0.4em; } -.step-placeholder { - background-color: var(--test-panel-bkg) +/* Per-row delete: rides the transition band next to the justification. + * Subtle until the row is hovered — it's a destructive affordance, not + * information. Hover is keyed to the row's own display line (not + * .step-border, which for induction/forall wraps every nested row and + * would light up all the trash cans at once). */ +.step-transition .step-delete { + opacity: 0; + transition: opacity 0.1s ease-in; + cursor: pointer; +} + +.step-display:hover .step-delete { + opacity: 0.6; +} + +.step-transition .step-delete:hover { + opacity: 1; +} + +/* Nested steppers (induction cases, forall bodies, target-box rows) sit + * inside their parent row's .step-border, which insets them on the + * right by its padding plus the indicator gutter, compounding per + * nesting level. Cancel the parent's inset, so every row's right edge + * (and with it the transition band and status lozenge gutter) lies flat + * on one column. */ +.step-border .stepper { + margin-right: calc(-0.5em - 14px); +} + +/* The trailing row's justification hangs half a step below the last + * row; give it room instead of clipping — but only when nothing follows + * (inside a target box the "⋯" row comes next, and the band should sit + * on the shared boundary, not float above it). */ +.stepper:last-child { + padding-bottom: 1.2em; +} + +.step-justification-wrap.has-popup { + cursor: pointer; + border: 1px solid var(--step-indicator-broken); + border-radius: 0.3em; + padding: 0 0.4em; + background-color: color-mix( + in srgb, + var(--step-indicator-broken) 12%, + transparent + ); +} + +.step-border.blocked .step-justification-wrap.has-popup { + border-color: var(--step-indicator-blocked); + background-color: color-mix( + in srgb, + var(--step-indicator-blocked) 12%, + transparent + ); +} + +.step-justification-wrap.has-popup:focus { + outline: none; +} + +.step-error-popup { + display: none; + position: absolute; + bottom: calc(100% + 0.4em); + right: 0; + z-index: var(--stepper-interactive-z); + flex-direction: row; + align-items: center; + flex-wrap: wrap; + gap: 0.3em; + width: max-content; + max-width: 26em; + padding: 0.5em 0.75em; + border: 1px solid var(--step-indicator-broken); + border-radius: 0.3em; + background-color: var(--test-panel-bkg); + box-shadow: 0 2px 8px var(--menu-shadow); + font-size: 0.85em; + cursor: default; +} + +.step-border.blocked .step-error-popup { + border-color: var(--step-indicator-blocked); +} + +.step-justification-wrap.has-popup:focus-within > .step-error-popup { + display: flex; +} + +/* Inline error text in a row's expression slot: when the step above is + * broken the checker passes the goal through unchanged, so rather than + * reprint the identical expression the row says what went wrong. */ +.step-error-inline { + display: flex; + flex-direction: row; + align-items: center; + flex-wrap: wrap; + gap: 0.3em; + color: var(--step-indicator-broken); + font-size: 0.85em; +} + +/* Error rows keep the ≡ slot for column alignment but don't show it — + * their content is a message, not an equivalent expression. */ +.equiv.equiv-hidden { + visibility: hidden; +} + +/* A missing step's justification: the transition out of the row is not + * yet known. */ +.missing-step-justification { + display: flex; + flex-direction: row; + align-items: center; + gap: 0.3em; +} + +.step-unknown { + opacity: 0.6; + font-weight: bold; + padding: 0 0.3em; +} + +/* Read-only fallback for a wrapping form's argument (cell-level stepper, + * or a moment when the backing segment can't be spliced). Without + * `.inline-editor-wrapper`'s chrome: an editor-looking box that + * cannot be typed into reads as broken. */ +.proof-form-arg-static { + padding: 0.2em 0; +} + +/* Prover: mark messages --------------------------------------------- + * + * The wildcard-split refusal is much longer than the other marks, so it + * may shrink and wrap inside its slot. */ +.induction-wildcard-warning { + min-width: 0; + max-width: 100%; + white-space: normal; + overflow-wrap: anywhere; +} + +/* Prover: a step's block ------------------------------------------------ + * + * A step with goals of its own (a form's body, induction's cases, have's + * sub-proof) or with side conditions shown open draws a block in place of + * the line to the next row: a C open to the right, with the step's + * lozenge on its top edge, in the column the other lozenges use. Each + * section is a C: a bar naming what it adds, over a light slot holding + * a stepper aiming at `true`. Goals the step creates are dark sections, + * side conditions mid-tone ones, before them. */ +.step-border.has-block { + padding-bottom: 0; +} + +/* The block is the step, so the row after it draws no line of its own. */ +.step-border.has-block + .step-border { + border-top-color: transparent; +} + +.step-block { + position: relative; + display: flex; + flex-direction: column; + gap: 3px; + margin: 0.6em 0 0.4em -0.7em; +} + +/* On the block's top edge, half over the block, where the step's line + * would be. The lozenge inside carries its own border and fill. */ +.step-block > .step-transition { + position: absolute; + top: 0; + right: -0.5em; + transform: translateY(-50%); + z-index: 1; + display: flex; + flex-direction: row; + align-items: center; + gap: 0.3em; +} + +.step-block > .step-transition .step-delete { + opacity: 0; +} + +.step-block > .step-transition:hover .step-delete, +.step-border.has-block > .step-display:hover + .step-block .step-delete { + opacity: 0.6; +} + +/* The status indicator marks the step, so it sits on the block's top + * edge, where the step's line would be. */ +.step-border.has-block::after { + display: none; +} + +.step-border.has-block.broken > .step-block::after, +.step-border.has-block.incomplete > .step-block::after, +.step-border.has-block.blocked > .step-block::after { + content: ""; + position: absolute; + top: -0.75em; + height: 1.5em; + right: -9px; + width: 3px; + border-radius: 1.5px; + pointer-events: none; +} + +.step-border.has-block.broken > .step-block::after { + background-color: var(--step-indicator-broken); +} + +.step-border.has-block.incomplete > .step-block::after { + background-color: var(--step-indicator-incomplete); +} + +.step-border.has-block.blocked > .step-block::after { + background-image: radial-gradient( + circle at 50% 2px, + var(--step-indicator-blocked) 1.5px, + transparent 1.9px + ); + background-size: 3px 7px; + background-repeat: repeat-y; +} + +/* A C stops short of the row's edge, leaving the trash cans' column + * clear; its slots run on to the edge, so rows nested in them keep the + * lozenge column of the rows outside. */ +.step-section { + padding: 0 0 8px 16px; + margin-right: 22px; + border-radius: 8px 0 0 8px; +} + +.step-section > .step-slot { + margin-right: -22px; +} + +.step-section.arm { + background-color: var(--stepper-arm); + color: var(--stepper-arm-text); +} + +.step-section.condition { + background-color: var(--stepper-condition); + color: var(--stepper-condition-text); +} + +.step-section-bar, +.step-arm-bar { + display: flex; + flex-direction: row; + flex-wrap: wrap; + align-items: center; + gap: 0.6em; + padding: 0.4em 0.6em 0.3em 0; +} + +.step-section-bar { + font-size: 0.8em; + font-weight: 600; + cursor: pointer; +} + +.step-arm-note { + display: flex; + flex-direction: row; + flex-wrap: wrap; + align-items: center; + gap: 0.3em 1em; + font-size: 0.8em; + opacity: 0.9; +} + +/* Why the checker refused an arm, in the arm's bar. */ +.step-arm-refusal { + display: flex; + flex-direction: row; + flex-wrap: wrap; + align-items: center; + gap: 0.3em; + font-size: 0.8em; + padding: 0.1em 0.5em; + border: 1px solid var(--step-indicator-broken); + border-radius: 0.3em; + background-color: var(--cell-result); + color: var(--step-indicator-broken); +} + +.step-arm-fact { + display: flex; + flex-direction: row; + align-items: center; + gap: 0.3em; +} + +/* Code printed in a dark bar takes the bar's light text, all tokens + * alike. Editable chips keep their own colours. */ +.step-arm-code *, +.step-arm-note * { + color: var(--stepper-arm-text) !important; +} + +.step-slot { + background-color: var(--cell-result); + color: var(--text-default); + border-radius: 7px 0 0 7px; +} + +.step-slot > .stepper:first-child > .step-border:first-child { + border-top-color: transparent; +} + +.step-section.arm .add-case-button { + color: var(--stepper-arm-text); + margin-top: 0.3em; + width: max-content; +} + +/* A side condition left collapsed: a dot on the step's line, with its + * kind's icon. Red while unproven; open, its `?` row holds the exits. */ +.condition-dot { + width: 15px; + height: 15px; + box-sizing: border-box; + border-radius: 50%; + border: 1.5px solid var(--stepper-condition-text); + background-color: var(--stepper-condition); + color: var(--stepper-condition-text); + font: 600 11px/13px var(--ui-font), sans-serif; + text-align: center; + cursor: pointer; +} + +.condition-dot.unproven { + border-color: var(--border-error-strong); + background-color: var(--border-error); + color: var(--light-page-color); +} + +.condition-exits { + display: flex; + flex-direction: row; + flex-wrap: wrap; + align-items: center; + gap: 0.3em; +} + +/* Drawn like a step's lozenge. */ +.condition-exit { + font-family: inherit; + font-size: 0.8em; + padding: 0.1em 0.5em; + border: 1px solid var(--stepper-lozenge-border); + border-radius: 0.3em; + background-color: var(--stepper-lozenge-bkg); + color: inherit; + cursor: pointer; + white-space: nowrap; +} + +.condition-exit:hover:not(.disabled) { + background-color: var(--stepper-lozenge-border); + color: var(--light-page-color); +} + +/* An exit that doesn't apply stays visible; its title says why. */ +.condition-exit.disabled { + opacity: 0.4; + cursor: not-allowed; + text-decoration: line-through; +} + +.condition-hint { + font-size: 0.8em; + opacity: 0.7; +} + +.target-step .step-output, +.condition-missing .step-unknown { + opacity: 0.5; } diff --git a/src/web/www/style/theorems.css b/src/web/www/style/theorems.css index 8547cadc8a..42e7746caa 100644 --- a/src/web/www/style/theorems.css +++ b/src/web/www/style/theorems.css @@ -36,6 +36,37 @@ animation: jello 1s ease 0s 1 normal none; } +.theorem-status.false { + background-color: var(--test-fail-active); +} + .theorem-status.unknown { color: var(--light-page-color); -} \ No newline at end of file +} + +/* Proven, relying on unfinished theorems it cites: proven's colours, + * without the `jello`, as the star says it isn't the whole story. */ +.theorem-status.relying { + background-color: var(--test-pass); + color: var(--test-percent-text); + cursor: help; +} + +/* Incomplete with conditions open: their quiet count finds the first + * when clicked. */ +.theorem-status.unknown[title] { + cursor: pointer; +} + +/* A theorem the program no longer reaches, drawn as it was last checked + * until it is back. */ +.theorem.stale > :not(.theorem-header) { + opacity: 0.5; + pointer-events: none; +} + +.theorem-status.stale { + background-color: transparent; + border: 1px dashed var(--cell-result-text); + color: var(--cell-result-text); +} diff --git a/src/web/www/style/toggle.css b/src/web/www/style/toggle.css index ee04829a4c..847b626c42 100644 --- a/src/web/www/style/toggle.css +++ b/src/web/www/style/toggle.css @@ -41,13 +41,16 @@ justify-content: center; } +/* On is the accent. The off track is a mid tone of the bar's hue, so + another shade of that hue reads as on or off depending on the scheme. */ .toggle-switch.active { - background-color: var(--surface-shard-strong); + background-color: var(--primary-accent); border: solid 1px transparent; } .toggle-switch.active .toggle-knob { margin-left: 0.9em; margin-right: 1px; + color: var(--primary-accent); } .submenu .toggle-switch { diff --git a/src/web/www/style/variables.css b/src/web/www/style/variables.css index a9b5790093..9a3feeae2a 100644 --- a/src/web/www/style/variables.css +++ b/src/web/www/style/variables.css @@ -59,4 +59,42 @@ /* HACKS */ --modal-back-z: 100; --modal-z: 101; + + /* ── Prover colors ────────────────────────────────────────────────── */ + + /* TODO: give these roles in the Colors slide (colors.hz, then + BuiltinsColorScheme.role_groups and ColorConfiguration.aliases) and + delete them here. Until then they are the light scheme's values in + every scheme. */ + + /* Runtime problems in the problems sidebar */ + --RT0: oklch(90% 0.06 350); /* row fill */ + --RT1: oklch(60% 0.25 350); /* stroke */ + --RT2: oklch(40% 0.25 350); /* active stroke */ + + /* Stepper per-row status indicator lines (right edge of a step row) */ + --step-indicator-broken: var(--border-error); + --step-indicator-incomplete: oklch(75% 0.09 80); /* tan */ + --step-indicator-blocked: oklch(75% 0.16 30); /* lighter red, dotted */ + + /* A step's block: dark sections for the goals a step creates, mid-tone + ones for its side conditions. */ + --stepper-arm: var(--ci-icon-bkg); + --stepper-arm-text: var(--light-page-color); + --stepper-condition: oklch(78% 0.045 90); + --stepper-condition-text: oklch(33% 0.04 90); + /* Every step's lozenge: the shape a step with an error already has + (`.has-popup`), in the arm colour. */ + --stepper-lozenge-border: color-mix(in srgb, var(--ci-icon-bkg) 70%, var(--cell-result)); + --stepper-lozenge-bkg: color-mix(in srgb, var(--ci-icon-bkg) 12%, var(--cell-result)); + + /* Proof sort */ + --token-proof: oklch(55% 0.17 150); + --token-prul: var(--token-proof); + --shard-caret-proof: oklch(from var(--token-proof) 95% calc(c/4) h); + --shard-proof: var(--shard-caret-proof); + --shard-lines-proof: oklch(from var(--token-proof) 80% calc(c/2) h); + --shard-prul: var(--shard-proof); + --shard-caret-prul: var(--shard-caret-proof); + --shard-lines-prul: var(--shard-lines-proof); } diff --git a/src/web/www/workerprelude.js b/src/web/www/workerprelude.js new file mode 100644 index 0000000000..625904399b --- /dev/null +++ b/src/web/www/workerprelude.js @@ -0,0 +1,4 @@ +// The worker's own Algebrite, which the proof checker verifies algebra +// steps with. Bundled into worker-algebrite.js, which the worker loads. +import Algebrite from 'algebrite'; +self.Algebrite = Algebrite; diff --git a/test/Test_CanonicalCompletion.re b/test/Test_CanonicalCompletion.re index 5bdd18e67a..d00d62c164 100644 --- a/test/Test_CanonicalCompletion.re +++ b/test/Test_CanonicalCompletion.re @@ -1893,15 +1893,16 @@ let clippable_guard_tests = { Alcotest.test_case("form-table sort coverage", `Quick, () => Alcotest.(check(string))( "coverage", - /* Pat 8 -> 9: negative literal patterns (#2419) gave `-` a - Pat mold. Re-decided, not repinned blindly: 9/88 is still - real signal, so clippable_sort stands. - Typ 14 -> 15, TPat 2 -> 4: #2448's symbolic delimiter-prefix - backup molds (Form.symbolic_delim_prefixes = `-`, `=`) reach - the InfixDelimiterPrefix atomic, which molds at all four - sorts. Re-decided: both frontiers stay far from vacuous, so - clippable_sort stands. */ - "Exp 67/88 | Pat 9/88 | Typ 15/88 | TPat 4/88 | Rul 1/88", + /* If this drifts, re-make the `clippable_sort` decision (pinned + by the next test) rather than bumping the number. An Exp + frontier is vacuous (69 of 105 labels carry an Exp mold), + while Pat, Typ and TPat stay narrow. Pat counts negative + literal patterns; Typ and TPat count the + symbolic delimiter-prefix backup molds + (Form.symbolic_delim_prefixes = `-`, `=`), which mold at all + four sorts. All four also count the proof's one-token `step`, + which as a bare word takes the atomic molds. */ + "Exp 69/105 | Pat 10/105 | Typ 15/105 | TPat 5/105 | Rul 1/105", table, ) ), @@ -1995,7 +1996,50 @@ let depth_count_tests = [ ), ]; +/* A theorem typed without its proof gets a hole for the proof from + completion. Editing the statement keeps the hole's id, which the + stepper's rows for the unwritten proof are keyed by. */ +let stable_hole_tests = [ + test_case( + "a completed theorem's proof keeps its id", + `Quick, + () => { + let proof_id = (z: Zipper.t): string => { + let found = ref("none"); + let _: Language.Exp.t = + Language.Exp.map_term( + ~f_exp= + (continue, e: Language.Exp.t) => { + switch (e.term) { + | Theorem(_, _, proof, _) => + found := Id.to_string(Language.Proof.rep_id(proof)) + | _ => () + }; + continue(e); + }, + MakeTerm.from_zip_for_sem(z, ~root=Exp).term, + ); + found^; + }; + let typed = + Test_Editing.perform( + Zipper.init(), + Test_Editing.mk("theorem t = 1¦"), + ); + let edited = Test_Editing.perform(typed, [Action.Insert("2")]); + check(Alcotest.bool, "a theorem", true, proof_id(typed) != "none"); + check( + string_testable, + "the proof's id", + proof_id(typed), + proof_id(edited), + ); + }, + ), +]; + let tests: list((string, list(Alcotest.test_case(unit)))) = [ + ("CanonicalCompletion: stable hole ids", stable_hole_tests), ( "CanonicalCompletion: depth", run_completion_tests(depth_tests) @ depth_count_tests, diff --git a/test/Test_CompletionScoreboard.re b/test/Test_CompletionScoreboard.re index a617b49354..ef2e89e424 100644 --- a/test/Test_CompletionScoreboard.re +++ b/test/Test_CompletionScoreboard.re @@ -73,7 +73,7 @@ let rec tokens = (seg: Segment.t): list(string) => /* Delimiter-shard targets: every shard of every multi-token tile, with the caret point just after its last char */ let targets = (z: Zipper.t): list((Token.t, Point.t)) => { - let measured = CachedSyntax.init(z).measured; + let measured = CachedSyntax.init(z) |> CachedSyntax.measured; let acc = ref([]); let rec walk = (sg: Segment.t) => List.iter( @@ -266,7 +266,7 @@ let run_class = (~prefix_only: bool, name: string, text: string): outcome => { result is delimiter-complete. */ let closer_targets = (z: Zipper.t): list((Token.t, Point.t)) => { - let measured = CachedSyntax.init(z).measured; + let measured = CachedSyntax.init(z) |> CachedSyntax.measured; let acc = ref([]); let rec walk = (sg: Segment.t) => List.iter( diff --git a/test/Test_ConfigurationMode.re b/test/Test_ConfigurationMode.re index 5fd8b7b0ed..cfede300a9 100644 --- a/test/Test_ConfigurationMode.re +++ b/test/Test_ConfigurationMode.re @@ -215,6 +215,7 @@ let evaluated = (result: Language.Exp.t): Web.EvalResult.Model.t => { Web.EvalResult.Update.update( ~settings=Web.Settings.Model.init, UpdateResult( + Web.EvalResult.Model.request_gen(Web.EvalResult.Model.init), ResultOk({ result, state: Language.EvaluatorState.empty, diff --git a/test/Test_Editing.re b/test/Test_Editing.re index 3e184c2001..1dbf9c07b9 100644 --- a/test/Test_Editing.re +++ b/test/Test_Editing.re @@ -74,24 +74,26 @@ let derive = (~settings: Language.CoreSettings.t, z: Zipper.t): derived => { derived; }; +let perform_one = (~settings=default_settings, a: Action.t, z: Zipper.t) => + Perform.go( + ~settings, + ~statics=Lazy.force(derive(~settings, z).statics), + ~syntax=CachedSyntax.init(z), + a, + { + zipper: z, + col_target: None, + }, + ~root=Exp, + ); + let perform = (~settings=default_settings, zip: Zipper.t, actions: list(Action.t)) - : Zipper.t => { - let perform = (a: Action.t, z: Zipper.t) => - Perform.go( - ~settings, - ~statics=Lazy.force(derive(~settings, z).statics), - ~syntax=CachedSyntax.init(z), - a, - { - zipper: z, - col_target: None, - }, - ); + : Zipper.t => List.fold_left( ~f= (z: Zipper.t, a: Action.t) => - switch (perform(a, z, ~root=Exp)) { + switch (perform_one(~settings, a, z)) { | Ok(z) => /* Term construction must be total on every reachable editor state * (statics/display consume it after every action). Checking here @@ -116,7 +118,6 @@ let perform = ~init=zip, actions, ); -}; let string_to_ltr_actions = (s: string): list(Action.t) => s |> Token.to_list |> List.map(~f=c => Action.Insert(c)); @@ -6007,7 +6008,61 @@ let delim_prefix_class_tests = [ ), ]; +let fold = Action.Project(SetIndicated(Specific(Fold))); + +let has_fold = (z: Zipper.t): bool => + List.exists( + ~f= + (p: Piece.t) => + switch (p) { + | Projector(pr) => Poly.equal(pr.kind, Fold) + | Tile(_) + | Grout(_) + | Secondary(_) => false + }, + Zipper.unselect_and_zip(z), + ); + +let fold_tests = [ + /* A projector stands for a whole term, and a header has no body for + the `in` to take. */ + test_case( + "A let header without its body doesn't fold", + `Quick, + () => { + let z = parse_zipper("let x = 1 in\n§let y = 2 in¦\nx + y"); + check( + bool, + "fold refused", + true, + switch (perform_one(fold, z)) { + | Error(Cant_project) => true + | Ok(_) + | Error(_) => false + }, + ); + }, + ), + test_case( + "A whole selected term folds", + `Quick, + () => { + let z = parse_zipper("let x = 1 in\nlet y = 2 in\n§x + y¦"); + check(bool, "folded", true, has_fold(perform(z, [fold]))); + }, + ), + test_case( + "The let at the caret folds", + `Quick, + () => { + let z = parse_zipper("let x = 1 in\n¦let y = 2 in\nx + y"); + check(bool, "folded", true, has_fold(perform(z, [fold]))); + }, + ), +]; + let tests = [ + ("Editing.Fold", fold_tests), ("Editing.PendingDelim", pending_delim_tests), ("Editing.DelimPrefixClass", delim_prefix_class_tests), ("Editing.DragToZeroWidth", drag_to_zero_width_tests), diff --git a/test/Test_EditorTransform.re b/test/Test_EditorTransform.re new file mode 100644 index 0000000000..f933097741 --- /dev/null +++ b/test/Test_EditorTransform.re @@ -0,0 +1,1066 @@ +open Alcotest; +open Language; +open Test_Evaluator_Prelude; + +let parse_zipper = (s: string): Haz3lcore.Zipper.t => + switch (Haz3lcore.Parser.to_zipper(s, ~root=Exp)) { + | Some(zipper) => zipper + | None => Alcotest.fail("Failed to parse zipper: " ++ s) + }; + +let zipper_term = (zipper: Haz3lcore.Zipper.t): Exp.t => + Haz3lcore.MakeTerm.from_zip_for_sem(zipper, ~root=Exp).term; + +/* Find the first Theorem's proof sub-term in an expression. */ +let find_theorem_proof = (e: Exp.t): option(Proof.t) => { + let found = ref(None); + let f_exp = (continue, e: Exp.t): Exp.t => + switch (e.term) { + | Theorem(_, _, proof, _) when Option.is_none(found^) => + found := Some(proof); + e; + | _ => continue(e) + }; + let _ = TermBase.Exp.map_term(~f_exp, e); + found^; +}; + +let theorem_proof = (src: string): Proof.t => + switch (find_theorem_proof(parse_exp(src))) { + | Some(p) => p + | None => Alcotest.fail("no theorem proof in: " ++ src) + }; + +/* Find all theorem proofs, in traversal order (for multi-theorem programs). */ +let find_theorem_proofs = (e: Exp.t): list(Proof.t) => { + let found = ref([]); + let f_exp = (continue, e: Exp.t): Exp.t => + switch (e.term) { + | Theorem(_, _, proof, _) => + found := found^ @ [proof]; + continue(e); + | _ => continue(e) + }; + let _ = TermBase.Exp.map_term(~f_exp, e); + found^; +}; + +/* Collect proof sub-nodes satisfying `pred`, in traversal order. */ +let rec find_proofs = (pred: Proof.t => bool, p: Proof.t): list(Proof.t) => + (pred(p) ? [p] : []) + @ List.concat_map(~f=find_proofs(pred), Proof.children(p)); + +let is_eval_step = (p: Proof.t): bool => + switch (p.term) { + | EvalStep => true + | _ => false + }; + +let is_focus_step = (p: Proof.t): bool => + switch (p.term) { + | Focus(_) => true + | _ => false + }; + +/* --- the exits' patches --------------------------------------------- + * + * `Web.Obligations.Exits` owns the pure patch builders for the exits; + * these tests drive them end to end through `apply_patch` and read the + * resulting program text. The obligations are built by hand rather than + * run through the checker on purpose: ids are per-parse, so a patch must + * target ids from the same zipper it is applied to (the checker's + * elaborated copy has its own id space — that path is covered by the + * model-level tests in Test_Obligations). */ + +module Exits = Web.Obligations.Exits; + +/* An obligation as its exits see one: only `origin` (the incurring step) + * and `goal` drive them. */ +let mk_obligation = (~origin: Id.t, ~goal: string): Obligation.t => { + origin, + kind: Premise, + bindings: [], + goal: parse_exp(goal), + discharge: Pending, +}; + +/* An obligation whose goal reuses ids from the program `z`, + the way real obligations' goals do (they are slices of the checked + program). ` != 0`, built around the program's own `var` tile. */ +let find_var = (~name: Var.t, e: Exp.t): Exp.t => { + let found = ref(None); + let f_exp = (continue, e: Exp.t): Exp.t => + switch (e.term) { + | Var(x) when String.equal(x, name) && Option.is_none(found^) => + found := Some(e); + e; + | _ => continue(e) + }; + let _ = TermBase.Exp.map_term(~f_exp, e); + switch (found^) { + | Some(e) => e + | None => Alcotest.fail("no `" ++ name ++ "` in the program") + }; +}; + +let mk_obligation_reusing = + (~origin: Id.t, ~var: Var.t, z: Haz3lcore.Zipper.t): Obligation.t => { + let goal = + Exp.fresh( + BinOp( + Poly(NotEquals), + find_var(~name=var, zipper_term(z)), + Exp.fresh(Atom(Int(Bigint.of_int(0)))), + ), + ); + { + origin, + kind: Premise, + bindings: [], + goal, + discharge: Pending, + }; +}; + +/* Every tile id in the zipper's segment, children included. A tile id + appearing twice is the shard-mismatch crash in latent form. */ +let rec tile_ids = (seg: Haz3lcore.Segment.t): list(Id.t) => + List.concat_map( + ~f= + (p: Haz3lcore.Piece.t) => + switch (p) { + | Tile(t) => [ + Haz3lcore.Piece.id(p), + ...tile_ids(List.concat(t.children)), + ] + | Grout(_) + | Secondary(_) + | Projector(_) => [] + }, + seg, + ); + +let duplicate_tile_ids = (z: Haz3lcore.Zipper.t): list(Id.t) => { + let seen = Stdlib.Hashtbl.create(64); + List.filter( + ~f= + id => + switch (Stdlib.Hashtbl.find_opt(seen, id)) { + | Some () => true + | None => + Stdlib.Hashtbl.add(seen, id, ()); + false; + }, + tile_ids(Haz3lcore.Zipper.unselect_and_zip(z)), + ); +}; + +let check_no_duplicate_tile_ids = (~msg: string, z: Haz3lcore.Zipper.t) => { + let dups = duplicate_tile_ids(z); + check( + int, + msg + ++ " — duplicated tile ids: " + ++ String.concat(~sep=", ", List.map(~f=Id.to_string, dups)) + ++ "\nin:\n" + ++ Haz3lcore.Printer.of_zipper(~holes="?", z), + 0, + List.length(dups), + ); +}; + +let exits_ctx_of = (z: Haz3lcore.Zipper.t): Exits.ctx => { + let term = zipper_term(z); + { + proof: + switch (find_theorem_proof(term)) { + | Some(p) => p + | None => Alcotest.fail("no proof") + }, + proof_map: ProofMap.empty, + info_map: Statics.Map.empty, + }; +}; + +let require_patch = + (msg: string, p: option(Haz3lcore.EditorTransform.patch)) + : Haz3lcore.EditorTransform.patch => + switch (p) { + | Some(p) => p + | None => Alcotest.fail(msg) + }; + +let serialize = (z: Haz3lcore.Zipper.t): string => + Haz3lcore.Printer.of_zipper(~holes="?", z); + +let count_newlines = (s: string): int => + String.fold(s, ~init=0, ~f=(n, c) => Char.equal(c, '\n') ? n + 1 : n); + +let contains_substring = (haystack: string, needle: string): bool => { + let hl = String.length(haystack); + let nl = String.length(needle); + let rec go = i => + i + + nl <= hl + && ( + String.equal(String.sub(haystack, ~pos=i, ~len=nl), needle) + || go(i + 1) + ); + nl == 0 || go(0); +}; + +let check_contains = (~msg: string, haystack: string, needle: string) => + check( + bool, + msg ++ " — expected to find:\n" ++ needle ++ "\nin:\n" ++ haystack, + true, + contains_substring(haystack, needle), + ); + +/* Apply a proof patch to the proof selected by `select` (out of all proof + sub-nodes of all theorems), returning the patched zipper. */ +let patch_proof_zipper = + ( + ~reflow=true, + ~select: Exp.t => option(Proof.t)=find_theorem_proof, + z: Haz3lcore.Zipper.t, + replacement: Proof.t, + ) + : Haz3lcore.Zipper.t => { + /* target_id must come from the same zipper `z` (ids are per-parse). */ + let target_id = + switch (select(zipper_term(z))) { + | Some(p) => Proof.rep_id(p) + | None => Alcotest.fail("proof selector found no target") + }; + Haz3lcore.EditorTransform.apply_patch( + z, + Haz3lcore.EditorTransform.mk_proof_patch( + ~target_id, + ~reflow, + replacement, + ), + ); +}; + +/* Apply a proof patch that replaces the (hole) proof of `target_src` with the + proof parsed from `replacement_src`, and return the serialized result. */ +let patch_proof = (~reflow=true, target_src: string, replacement_src: string) => { + let z = parse_zipper(target_src); + let replacement = theorem_proof(replacement_src); + patch_proof_zipper(~reflow, z, replacement) |> serialize; +}; + +let tests = ( + "EditorTransform", + [ + /* The step-picker inserts a wrapping form with an empty argument and + then jumps the caret into it (StepperPicker.Terms.arg_id). That jump + keys off the argument term's + rep id, so the id must survive the patch: `ExpToSegment` emits an + EmptyHole as a Grout stamped with the term's id, and the splice must + carry that Grout through unchanged. If it didn't, the inserted slot + would render but never take the caret. */ + test_case( + "proof patch preserves an empty argument's id", + `Quick, + () => { + let z = parse_zipper("theorem t = 1 == 1 proof ? in t"); + let arg = Exp.fresh(EmptyHole); + let arg_id = Exp.rep_id(arg); + let replacement = + Proof.fresh(Assume(arg, None, Proof.fresh(EmptyHole))); + let out = + patch_proof_zipper(z, ~select=find_theorem_proof, replacement); + check_contains( + ~msg="the form is written with a hole argument", + serialize(out), + "assume ?", + ); + check( + bool, + "the argument hole's id is present in the patched segment", + true, + List.mem( + Haz3lcore.Segment.ids(Haz3lcore.Zipper.unselect_and_zip(out)), + arg_id, + ~equal=Id.equal, + ), + ); + }, + ), + test_case( + "root transform rewrites the root expression", + `Quick, + () => { + let zipper = parse_zipper("1 + 2"); + let transformed = + Haz3lcore.EditorTransform.apply_patch( + zipper, + Haz3lcore.EditorTransform.mk_patch( + ~reflow=false, + parse_exp("3 * 4"), + ), + ); + check( + dhexp_typ, + "root rewrite should replace expression", + parse_exp("3 * 4"), + zipper_term(transformed), + ); + }, + ), + test_case( + "targeted transform rewrites only matching id", + `Quick, + () => { + let zipper = parse_zipper("(2 + 3) + 4"); + let root_exp = zipper_term(zipper); + let target_id = + switch (Occurrence.nth(parse_exp("2 + 3"), 0, root_exp)) { + | Some(exp) => Exp.rep_id(exp) + | None => Alcotest.fail("Could not find target exp id") + }; + let transformed = + Haz3lcore.EditorTransform.apply_patch( + zipper, + Haz3lcore.EditorTransform.mk_patch( + ~target_id, + ~reflow=false, + parse_exp("10"), + ), + ); + check( + dhexp_typ, + "only selected sub-expression changes", + parse_exp("10 + 4"), + zipper_term(transformed), + ); + }, + ), + test_case( + "missing target id is a no-op", + `Quick, + () => { + let zipper = parse_zipper("1 + 2"); + let original = zipper_term(zipper); + let transformed = + Haz3lcore.EditorTransform.apply_patch( + zipper, + Haz3lcore.EditorTransform.mk_patch( + ~target_id=Id.mk(), + ~reflow=false, + parse_exp("0"), + ), + ); + check( + dhexp_typ, + "missing id leaves expression unchanged", + original, + zipper_term(transformed), + ); + }, + ), + test_case( + "apply_patch keeps zipper semantically valid", + `Quick, + () => { + let zipper = parse_zipper("1 + 2"); + let target_id = None; + let transformed = + Haz3lcore.EditorTransform.apply_patch( + zipper, + Haz3lcore.EditorTransform.mk_patch( + ~target_id?, + parse_exp("let x = 1 in x"), + ), + ); + let term = zipper_term(transformed); + check( + dhexp_typ, + "patched zipper should still produce a term", + parse_exp("let x = 1 in x"), + term, + ); + }, + ), + test_case( + "proof patch reflows multi-step proof onto separate lines", + `Quick, + () => { + let target = "theorem t = 1 + 1 + 1 == 2 proof ? in t"; + let two_step = "theorem u = 1 == 1 proof from 1 do step end; from 1 do step end in u"; + let reflowed = patch_proof(target, two_step); + let flat = patch_proof(~reflow=false, target, two_step); + check( + bool, + "reflow=true introduces more linebreaks than reflow=false", + true, + count_newlines(reflowed) > count_newlines(flat), + ); + }, + ), + test_case( + "proof patch reflows induction cases onto separate lines", + `Quick, + () => { + let target = "theorem t = 1 == 1 proof ? in t"; + let induction = "theorem u = 1 == 1 proof induction y | a => from y do rewrite y end end | b => from z do rewrite z end end end in u"; + let reflowed = patch_proof(target, induction); + let flat = patch_proof(~reflow=false, target, induction); + check( + bool, + "reflow=true introduces more linebreaks than reflow=false", + true, + count_newlines(reflowed) > count_newlines(flat), + ); + }, + ), + /* ---- Locality: a patch must not rewrite text outside its extent ---- */ + test_case( + "proof patch preserves theorem statement byte-for-byte", + `Quick, + () => { + /* Extra parens and non-canonical spacing in the statement, which + the whole-program writer would normalize. */ + let statement = "forall x:(([Int])) -> x == x"; + let target = "theorem t = " ++ statement ++ " proof ? in t"; + let out = + patch_proof( + target, + "theorem u = 1 == 1 proof from 1 do step end; from 1 do step end in u", + ); + check_contains(~msg="statement survives untouched", out, statement); + }, + ), + test_case( + "proof patch preserves comments elsewhere in the program", + `Quick, + () => { + let target = "#keep me exactly#\ntheorem t = 1 == 1 proof ? in t"; + let out = + patch_proof( + target, + "theorem u = 1 == 1 proof from 1 do step end in u", + ); + check_contains(~msg="comment survives", out, "#keep me exactly#"); + }, + ), + test_case( + "proof patch preserves literal lexemes elsewhere", + `Quick, + () => { + /* The term records `007`'s spelling, but only as a lexeme the + printer may drop; the patch must not. */ + let target = "let k = 007 in theorem t = 1 == 1 proof ? in k"; + let out = + patch_proof( + target, + "theorem u = 1 == 1 proof from 1 do step end in u", + ); + check_contains( + ~msg="literal spelling survives", + out, + "let k = 007 in", + ); + }, + ), + test_case( + "proof patch preserves multi-line formatting of earlier bindings", + `Quick, + () => { + let binding = "let f = fun x ->\n x + 1\nin"; + let target = binding ++ "\ntheorem t = 1 == 1 proof ? in f(1)"; + let out = + patch_proof( + target, + "theorem u = 1 == 1 proof from 1 do step end in u", + ); + check_contains(~msg="binding layout survives", out, binding); + }, + ), + test_case( + "patching one theorem leaves a sibling theorem untouched", + `Quick, + () => { + let first = "theorem a = 1 == 1 proof ? in"; + let target = first ++ "\ntheorem t = 2 == 2 proof ? in t"; + let z = parse_zipper(target); + let select = (e: Exp.t) => + switch (find_theorem_proofs(e)) { + | [_, second, ..._] => Some(second) + | _ => None + }; + let replacement = + theorem_proof("theorem u = 1 == 1 proof from 1 do step end in u"); + let out = patch_proof_zipper(~select, z, replacement) |> serialize; + check_contains(~msg="first theorem survives", out, first); + check_contains(~msg="patch landed", out, "from 1 do step end"); + }, + ), + /* ---- Stability: repeated patching must not accumulate anything ---- */ + test_case( + "re-applying an equivalent proof patch is text-stable", + `Quick, + () => { + let target = "theorem t = forall x:[Int] -> x == x proof ? in t"; + let replacement_src = "theorem u = 1 == 1 proof from 1 do step end; from 1 do step end in u"; + let z1 = + patch_proof_zipper( + parse_zipper(target), + theorem_proof(replacement_src), + ); + let once = serialize(z1); + /* Patch the result again with a fresh parse of the same proof. */ + let z2 = patch_proof_zipper(z1, theorem_proof(replacement_src)); + check(string, "second patch is a fixed point", once, serialize(z2)); + }, + ), + test_case( + "adding then removing an induction case leaves the statement alone", + `Quick, + () => { + /* Re-serializing the whole program on each case add/remove would + grow parens on the forall's ascription. */ + let statement = "forall x:[Int] -> x == x"; + let one_case = + "theorem t = " + ++ statement + ++ " proof induction y | a => from y do rewrite y end end end in t"; + let two_case = + "theorem t = " + ++ statement + ++ " proof induction y | a => from y do rewrite y end end | b => from z do rewrite z end end end in t"; + let z = parse_zipper(one_case); + let z = patch_proof_zipper(z, theorem_proof(two_case)); + check_contains( + ~msg="statement intact after adding a case", + serialize(z), + statement, + ); + let z = patch_proof_zipper(z, theorem_proof(one_case)); + check_contains( + ~msg="statement intact after removing the case", + serialize(z), + statement, + ); + /* And a second add/remove cycle lands on exactly the same text. */ + let text_after_one_cycle = serialize(z); + let z = patch_proof_zipper(z, theorem_proof(two_case)); + let z = patch_proof_zipper(z, theorem_proof(one_case)); + check( + string, + "add/remove cycle is a fixed point", + text_after_one_cycle, + serialize(z), + ); + }, + ), + /* ---- Reparse safety: splices must preserve term structure ---- */ + test_case( + "exp patch into operator context keeps precedence", + `Quick, + () => { + let z = parse_zipper("2 * 3"); + let target_id = + switch (Occurrence.nth(parse_exp("3"), 0, zipper_term(z))) { + | Some(exp) => Exp.rep_id(exp) + | None => Alcotest.fail("Could not find target exp id") + }; + let transformed = + Haz3lcore.EditorTransform.apply_patch( + z, + Haz3lcore.EditorTransform.mk_patch( + ~target_id, + parse_exp("5 + 6"), + ), + ); + check( + dhexp_typ, + "splice must not re-associate as (2 * 5) + 6", + parse_exp("2 * (5 + 6)"), + zipper_term(transformed), + ); + }, + ), + test_case( + "atomic exp patch splices without disturbing surroundings", + `Quick, + () => { + let z = parse_zipper("2 * 3"); + let target_id = + switch (Occurrence.nth(parse_exp("3"), 0, zipper_term(z))) { + | Some(exp) => Exp.rep_id(exp) + | None => Alcotest.fail("Could not find target exp id") + }; + let out = + Haz3lcore.EditorTransform.apply_patch( + z, + Haz3lcore.EditorTransform.mk_patch(~target_id, parse_exp("7")), + ) + |> serialize; + check(string, "only the operand changes", "2 * 7", out); + }, + ), + test_case( + "multi-step proof replacing one step of a seq keeps all steps", + `Quick, + () => { + /* A multi-piece proof can't be spliced in beside the step's + siblings, so the theorem's whole proof is replaced; the steps + must still all be there. */ + let target = "theorem t = 1 == 1 proof from y do rewrite y end end; from z do rewrite z end end in t"; + let z = parse_zipper(target); + let select = (e: Exp.t) => + switch (find_theorem_proof(e)) { + | Some(p) => + switch (find_proofs(is_focus_step, p)) { + | [first, ..._] => Some(first) + | [] => None + } + | None => None + }; + let replacement = + theorem_proof( + "theorem u = 1 == 1 proof from 1 do step end; from 2 do step end in u", + ); + let out = patch_proof_zipper(~select, z, replacement); + let expected = "theorem t = 1 == 1 proof from 1 do step end; from 2 do step end; from z do rewrite z end end in t"; + check( + dhexp_typ, + "all three steps present in order", + parse_exp(expected), + zipper_term(out), + ); + }, + ), + test_case( + "patching a case body keeps the statement and the other case", + `Quick, + () => { + let statement = "1 == 1"; + let target = + "theorem t = " + ++ statement + ++ " proof induction y | a => from y do rewrite y end end | b => from z do rewrite z end end end in t"; + let z = parse_zipper(target); + let select = (e: Exp.t) => + switch (find_theorem_proof(e)) { + | Some(p) => + switch (find_proofs(is_focus_step, p)) { + | [first, ..._] => Some(first) + | [] => None + } + | None => None + }; + let replacement = + theorem_proof("theorem u = 1 == 1 proof from 9 do step end in u"); + let out = patch_proof_zipper(~select, z, replacement); + let text = serialize(out); + check_contains(~msg="statement intact", text, statement); + check_contains( + ~msg="patched case body landed", + text, + "from 9 do step end", + ); + /* The untouched case is still present with its tokens intact. */ + check_contains( + ~msg="sibling case intact", + text, + "from z do rewrite z end end", + ); + }, + ), + test_case( + "patched output reparses to the patched term", + `Quick, + () => { + let target = "theorem t = forall x:[Int] -> x == x proof ? in t"; + let replacement_src = "theorem u = 1 == 1 proof induction y | a => from y do rewrite y end end | b => from z do rewrite z end end end in u"; + let z = + patch_proof_zipper( + parse_zipper(target), + theorem_proof(replacement_src), + ); + /* Serialize and reparse: the text must parse and mean the same. */ + let reparsed = parse_zipper(serialize(z)); + check( + dhexp_typ, + "text roundtrips through reparse", + zipper_term(z), + zipper_term(reparsed), + ); + }, + ), + test_case( + "missing target id leaves the program text untouched", + `Quick, + () => { + /* Non-canonical formatting everywhere: a no-op patch must not + reformat anything. */ + let target = "let k = 007 in\ntheorem t = 1 == 1 proof ? in k"; + let z = parse_zipper(target); + let before = serialize(z); + let out = + Haz3lcore.EditorTransform.apply_patch( + z, + Haz3lcore.EditorTransform.mk_proof_patch( + ~target_id=Id.mk(), + theorem_proof( + "theorem u = 1 == 1 proof from 1 do step end in u", + ), + ), + ); + check(string, "no-op patch changes nothing", before, serialize(out)); + }, + ), + test_case( + "extending an eval-step chain splices the second step", + `Quick, + () => { + /* Mirrors the stepper UI's ExtendProof patch: taking a second + step replaces the previous step's leaf with Seq(leaf, new). */ + let target = "theorem thm = 1 + 4 == 5 proof \nfrom 1 + 4 do step end\n in"; + let z = parse_zipper(target); + let prev = + switch (find_theorem_proof(zipper_term(z))) { + | Some(p) => + switch (find_proofs(is_focus_step, p)) { + | [step, ..._] => step + | [] => Alcotest.fail("no focus step found") + } + | None => Alcotest.fail("no theorem proof") + }; + let head = + theorem_proof( + "theorem u = 1 == 1 proof from 5 == 5 do step end in u", + ); + let replacement = Proof.fresh(Seq(prev, head)); + let out = + Haz3lcore.EditorTransform.apply_patch( + z, + Haz3lcore.EditorTransform.mk_proof_patch( + ~target_id=Proof.rep_id(prev), + replacement, + ), + ); + /* The first step's odd hand layout stays; only the new step's + line is laid out. */ + check( + string, + "second step chains onto the first", + "theorem thm = 1 + 4 == 5 proof \n" + ++ "from 1 + 4 do step end;\n" + ++ " from 5 == 5 do step end\n" + ++ " in?", + serialize(out), + ); + }, + ), + test_case( + "reflow=false proof patch still splices locally", + `Quick, + () => { + let statement = "forall x:(([Int])) -> x == x"; + let target = "theorem t = " ++ statement ++ " proof ? in t"; + let out = + patch_proof( + ~reflow=false, + target, + "theorem u = 1 == 1 proof from 1 do step end in u", + ); + check_contains(~msg="statement intact", out, statement); + check_contains(~msg="patch landed", out, "from 1 do step end"); + }, + ), + test_case( + "remove patch splices a mid-chain step and its semicolon", + `Quick, + () => { + let src = "theorem t = 1 + 4 == 5 proof from 1 + 4 do step end; from 1 + 3 do step end; from 5 == 5 do step end in t"; + let z = parse_zipper(src); + let target_id = + switch (find_theorem_proof(zipper_term(z))) { + | Some(p) => + switch (find_proofs(is_focus_step, p)) { + | [_, second, _] => Proof.rep_id(second) + | _ => Alcotest.fail("expected three focus steps") + } + | None => Alcotest.fail("no proof") + }; + let out = + Haz3lcore.EditorTransform.apply_patch( + z, + Haz3lcore.EditorTransform.mk_proof_remove_patch(~target_id), + ) + |> serialize; + check( + bool, + "removed step is gone — got:\n" ++ out, + false, + contains_substring(out, "1 + 3"), + ); + check_contains(~msg="first step kept", out, "from 1 + 4 do step end"); + check_contains( + ~msg="third step kept", + out, + "from 5 == 5 do step end", + ); + /* The `;` went with the step: the result reparses to a two-step + * chain with no hole where the step was. */ + let reparsed = + switch (find_theorem_proof(parse_exp(out))) { + | Some(p) => p + | None => Alcotest.fail("no proof after removal: " ++ out) + }; + check( + int, + "two steps remain", + 2, + List.length(find_proofs(is_focus_step, reparsed)), + ); + check( + bool, + "no hole left behind — got:\n" ++ out, + false, + Proof.has_hole(reparsed), + ); + }, + ), + test_case( + "remove patch on the sole step leaves a hole proof", + `Quick, + () => { + let src = "theorem t = 1 + 4 == 5 proof from 1 + 4 do step end in t"; + let z = parse_zipper(src); + let target_id = + switch (find_theorem_proof(zipper_term(z))) { + | Some(p) => Proof.rep_id(p) + | None => Alcotest.fail("no proof") + }; + let out = + Haz3lcore.EditorTransform.apply_patch( + z, + Haz3lcore.EditorTransform.mk_proof_remove_patch(~target_id), + ) + |> serialize; + check( + bool, + "step is gone — got:\n" ++ out, + false, + contains_substring(out, "step"), + ); + let reparsed = + switch (find_theorem_proof(parse_exp(out))) { + | Some(p) => p + | None => Alcotest.fail("no proof after removal: " ++ out) + }; + check( + bool, + "an empty proof (hole) remains", + true, + Proof.has_hole(reparsed), + ); + }, + ), + /* --- exit 1: prove here, via a `have` ----------------------------- */ + test_case( + "have patch wraps the enclosing proof region", + `Quick, + () => { + let z = + parse_zipper( + "theorem t = 1 + 4 == 5 proof from 1 + 4 do step end; from 5 == 5 do step end in t", + ); + let ctx = exits_ctx_of(z); + /* Incurred by the first step; the region is the whole chain. */ + let origin = + switch (find_proofs(is_eval_step, ctx.proof)) { + | [first, ..._] => Proof.rep_id(first) + | _ => Alcotest.fail("no eval steps") + }; + let patch = + require_patch( + "have action should be available", + Exits.have_patch(~ctx, mk_obligation(~origin, ~goal="2 != 0")), + ); + let out = + Haz3lcore.EditorTransform.apply_patch(z, patch) |> serialize; + check_contains(~msg="the have keyword landed", out, "have"); + check_contains(~msg="its proposition is the goal", out, "2 != 0"); + check_contains(~msg="subproof slot is a hole", out, "proof"); + check_contains( + ~msg="first step preserved", + out, + "from 1 + 4 do step end", + ); + check_contains( + ~msg="second step preserved", + out, + "from 5 == 5 do step end", + ); + /* Reparse: a Have whose body still holds both steps. */ + switch (find_theorem_proof(parse_exp(out))) { + | Some({term: Have(_, _, sub, body), _}) => + check( + bool, + "subproof is a hole", + true, + switch (sub.term) { + | EmptyHole => true + | _ => false + }, + ); + check( + int, + "both steps live in the have's body", + 2, + List.length(find_proofs(is_eval_step, body)), + ); + | Some(other) => + Alcotest.fail( + "expected a Have proof, got: " + ++ Proof.show_cls(Proof.cls_of_term(other.term)) + ++ "\nin:\n" + ++ out, + ) + | None => Alcotest.fail("no proof after patch: " ++ out) + }; + }, + ), + /* --- exit 2: split on the obligation ----------------------------- */ + test_case( + "split patch wraps the region in a true/false induction", + `Quick, + () => { + let z = + parse_zipper( + "theorem t = 1 + 4 == 5 proof from 1 + 4 do step end; from 5 == 5 do step end in t", + ); + let ctx = exits_ctx_of(z); + let origin = + switch (find_proofs(is_eval_step, ctx.proof)) { + | [first, ..._] => Proof.rep_id(first) + | _ => Alcotest.fail("no eval steps") + }; + let patch = + require_patch( + "split action should be available", + Exits.split_patch(~ctx, mk_obligation(~origin, ~goal="2 != 0")), + ); + let out = + Haz3lcore.EditorTransform.apply_patch(z, patch) |> serialize; + check_contains(~msg="a case split landed", out, "cases"); + check_contains(~msg="on the obligation goal", out, "2 != 0"); + check_contains(~msg="true case", out, "true"); + check_contains(~msg="false case", out, "false"); + check_contains(~msg="steps preserved", out, "from 1 + 4 do step end"); + switch (find_theorem_proof(parse_exp(out))) { + | Some({term: Cases(_, cases), _}) => + check(int, "two cases", 2, List.length(cases)); + switch (cases) { + | [(_, true_body), (_, false_body)] => + check( + int, + "the original chain is the true branch", + 2, + List.length(find_proofs(is_eval_step, true_body)), + ); + check( + bool, + "the false branch is open", + true, + Proof.has_hole(false_body), + ); + | _ => () + }; + | Some(other) => + Alcotest.fail( + "expected an Induction proof, got: " + ++ Proof.show_cls(Proof.cls_of_term(other.term)) + ++ "\nin:\n" + ++ out, + ) + | None => Alcotest.fail("no proof after patch: " ++ out) + }; + }, + ), + /* --- id hygiene: patched syntax must not duplicate tile ids ------ + * + * In the browser the obligation's goal is a slice of the + * checked program, so its exps carry the ids the program's tiles were + * parsed from. Embedding that slice verbatim puts one id on two + * tiles; `Measured.find_shards` then returns both occurrences' shards + * for a single tile and `Highlight.of_tile` dies with + * "shard mismatch: ... label = [\"z\"] ... tile_Shards:2". + * The view isn't testable headlessly, but the duplicate is. */ + test_case( + "have patch on a program-sourced goal mints fresh tile ids", + `Quick, + () => { + let z = + parse_zipper( + "theorem t = forall n: Int -> 8 / n == 8 / n proof from 8 / n do step end in t", + ); + let ctx = exits_ctx_of(z); + let origin = + switch (find_proofs(is_eval_step, ctx.proof)) { + | [first, ..._] => Proof.rep_id(first) + | _ => Alcotest.fail("no eval steps") + }; + let patch = + require_patch( + "have action available", + Exits.have_patch( + ~ctx, + mk_obligation_reusing(~origin, ~var="n", z), + ), + ); + let patched = Haz3lcore.EditorTransform.apply_patch(z, patch); + check_no_duplicate_tile_ids( + ~msg="have patch reused the goal's program ids", + patched, + ); + check_contains( + ~msg="the have still landed", + serialize(patched), + "have", + ); + }, + ), + test_case( + "split patch on a program-sourced goal mints fresh tile ids", + `Quick, + () => { + let z = + parse_zipper( + "theorem t = forall n: Int -> 8 / n == 8 / n proof from 8 / n do step end in t", + ); + let ctx = exits_ctx_of(z); + let origin = + switch (find_proofs(is_eval_step, ctx.proof)) { + | [first, ..._] => Proof.rep_id(first) + | _ => Alcotest.fail("no eval steps") + }; + let patch = + require_patch( + "split action available", + Exits.split_patch( + ~ctx, + mk_obligation_reusing(~origin, ~var="n", z), + ), + ); + let patched = Haz3lcore.EditorTransform.apply_patch(z, patch); + check_no_duplicate_tile_ids( + ~msg="split patch reused the goal's program ids", + patched, + ); + check_contains( + ~msg="the case split still landed", + serialize(patched), + "cases", + ); + }, + ), + ], +); diff --git a/test/Test_Elaboration.re b/test/Test_Elaboration.re index 97c8ad5bfc..910327997d 100644 --- a/test/Test_Elaboration.re +++ b/test/Test_Elaboration.re @@ -69,7 +69,7 @@ let adt_node_ids = exp => { go(body); | Let(_, def, body) | Seq(def, body) - | Theorem(_, def, body) => + | Theorem(_, def, _, body) => go(def); go(body); | If(c, t, f) => @@ -87,7 +87,6 @@ let adt_node_ids = exp => { | Projector(_, e) | Asc(e, _) | Use(_, e) - | ProofObject(e) | Closure(_, e) => go(e) | Deferral(_) => () | Fun(_, body, _, _) diff --git a/test/Test_ExpToSegment.re b/test/Test_ExpToSegment.re index ff4389a3f0..43638c1dd3 100644 --- a/test/Test_ExpToSegment.re +++ b/test/Test_ExpToSegment.re @@ -858,6 +858,19 @@ in f(42)|}, {|Ids stable: let/fun/case|}, {|let f = fun x -> case x | A => 1 end in f(2)|}, ), + /* The ids of an induction's `|`/`=>` rule tiles. These tiles live in + the induction's `PRul` child, so `MakeTerm` absorbs their ids onto + the `Induction` term for `ExpToSegment` to re-emit. Losing them + passes the id-ignoring `segments` check and fails only + `equiv (strict mod grout)`. `cases` keeps its rules the same way. */ + roundtrip_ids_test( + {|Ids stable: proof induction rules|}, + {|theorem x = 1 proof induction y | a => from y do rewrite y end end | b => ? end in x|}, + ), + roundtrip_ids_test( + {|Ids stable: proof cases rules|}, + {|theorem x = 1 proof cases y | a => from y do rewrite case_eq end end | b => ? end in x|}, + ), roundtrip_test({|Sum type: spaced|}, {|type T = + A + B in T|}), roundtrip_test({|Sum type: compact|}, {|type T = +A+B in T|}), /* Bare sums: the parse's id count distinguishes `A + B` from @@ -938,21 +951,178 @@ end|}), roundtrip_test({|Forall: simple|}, {|forall a -> 1|}), roundtrip_test({|Forall: with spaces|}, {|forall a -> 1|}), roundtrip_test({|Forall: compact|}, {|forall a->1|}), + /* material implication */ + roundtrip_test({|Implies: simple|}, {|true ==> false|}), + roundtrip_test({|Implies: with equalities|}, {|a == b ==> c == d|}), + roundtrip_test({|Implies: chained|}, {|a ==> b ==> c|}), + roundtrip_test({|Implies: left-parenthesized|}, {|(a ==> b) ==> c|}), /* Use expressions (use ... in) */ roundtrip_test({|Use: simple|}, {|use Nat in 1|}), roundtrip_test({|Use: spaced|}, {|use Nat in 1|}), roundtrip_test({|Use: compact|}, {|use Nat in 1|}), - /* ProofOf (proof_of ... end) - type-level */ - roundtrip_test({|ProofOf: simple|}, {|1 : proof_of 1 end|}), - roundtrip_test({|ProofOf: spaced|}, {|1 : proof_of 1 end|}), - /* ProofObject (proof_object ... end) - expression-level */ - roundtrip_test({|ProofObject: simple|}, {|proof_object 1 end|}), - roundtrip_test({|ProofObject: spaced|}, {|proof_object 1 end|}), - roundtrip_test({|ProofObject: with expr|}, {|proof_object 1 + 2 end|}), - /* Theorem expressions (theorem ... = ... in) */ - roundtrip_test({|Theorem: simple|}, {|theorem x = 1 in x|}), - roundtrip_test({|Theorem: spaced|}, {|theorem x = 1 in x|}), - roundtrip_test({|Theorem: compact|}, {|theorem x=1 in x|}), + /* Theorem expressions (theorem ... = ... proof ... in ...) */ + roundtrip_test( + {|Theorem: simple|}, + {|theorem x = 1 proof from y do rewrite y end end in x|}, + ), + /* Grouping parens at Proof sort. Without them, `(` in a proof slot + would remold as an Exp paren and the wrapping form inside it would + become a MultiHole. */ + roundtrip_test( + {|Theorem: parenthesized proof|}, + {|theorem x = 1 proof ( from y do rewrite y end end ) in x|}, + ), + /* Control: an unwritten hole body prints back as a `?` monotile, with + and without the parens, as grout does elsewhere. */ + roundtrip_test( + {|Theorem: funext with an unwritten hole body|}, + {|theorem x = 1 proof funext y =>? in x|}, + ), + roundtrip_test( + {|Theorem: parenthesized funext with an unwritten hole body|}, + {|theorem x = 1 proof ( funext y =>? ) in x|}, + ), + roundtrip_test( + {|Theorem: parenthesized funext with a hole body|}, + {|theorem x = 1 proof ( funext y => ? ) in x|}, + ), + roundtrip_test( + {|Theorem: parenthesized proof as the left arm of a `;`|}, + {|theorem x = 1 proof ( funext y => ? ); from y do rewrite y end end in x|}, + ), + roundtrip_test( + {|Theorem: spaced|}, + {|theorem x = 1 proof from y do rewrite y end end in x|}, + ), + roundtrip_test( + {|Theorem: compact|}, + {|theorem x=1 proof from y do rewrite y end end in x|}, + ), + /* Proof: induction (single case, case-like syntax — no `with` keyword) */ + roundtrip_test( + {|Induction: single-case|}, + {|theorem x = 1 proof induction y | a => from y do rewrite y end end end in x|}, + ), + /* Proof: induction (multi-case) */ + roundtrip_test( + {|Induction: multi-case|}, + {|theorem x = 1 proof induction y | a => from y do rewrite y end end | b => from z do rewrite z end end end in x|}, + ), + /* Proof: forall (quantified variable) */ + roundtrip_test( + {|Forall: simple|}, + {|theorem x = 1 proof forall y => from y do rewrite y end end in x|}, + ), + /* Proof: assume (hypothesized proposition) */ + roundtrip_test( + {|Assume: simple|}, + {|theorem x = 1 proof assume 2 == 2 => from y do rewrite y end end in x|}, + ), + roundtrip_test( + {|Assume: nested|}, + {|theorem x = 1 proof assume 2 == 2 => assume 3 == 3 => from y do rewrite y end end in x|}, + ), + /* Proof: a focus. The occurrence after `at` keeps its whitespace. */ + roundtrip_test( + {|Focus: at|}, + {|theorem x = 1 proof from y + 1 at 2 do step end in x|}, + ), + roundtrip_test( + {|Focus: at, spaced|}, + {|theorem x = 1 proof from y + 1 at 2 do step end in x|}, + ), + /* "at" is a prefix of `atom`, which switches the focus to its `at` + form while it is typed (see `Insert.plain_of_at_variant`). */ + roundtrip_test( + {|Focus: a selector starting with at|}, + {|theorem x = 1 proof from atom do step end in x|}, + ), + roundtrip_test( + {|Focus: at, after a selector starting with at|}, + {|theorem x = 1 proof from atom at 2 do step end in x|}, + ), + roundtrip_test( + {|Focus: nested, several steps|}, + {|theorem x = 1 proof from y at 11 do from z do step; step end end in x|}, + ), + /* Proof: explicit instantiation (`with = ` on a citation + step). Each with-variant is a distinct compound form beside its + plain form, so both spellings must round-trip. */ + roundtrip_test( + {|AxiomWith: simple|}, + {|theorem x = 1 proof from y do rewrite y with n = 2 end end in x|}, + ), + roundtrip_test( + {|AxiomWith: spaced|}, + {|theorem x = 1 proof from y do rewrite y with n = 2 end end in x|}, + ), + /* The step keeps no annotation for its `<-`, so the space before it + prints with a new id. */ + roundtrip_test( + ~known_equiv_gap=true, + {|AxiomRevWith: simple|}, + {|theorem x = 1 proof from y do rewrite <- y with n = 2 end end in x|}, + ), + roundtrip_test( + {|RevertWith: simple|}, + {|theorem x = 1 proof revert y with n = 2 => from y do rewrite y end end in x|}, + ), + roundtrip_test( + {|RevertWith: compound instantiation|}, + {|theorem x = 1 proof revert y with n = 2 + 3 => from y do rewrite y end end in x|}, + ), + /* The plain forms must keep round-tripping unchanged: `with` is only + absorbed by a citation step that is still missing its own shards. */ + roundtrip_test( + {|Revert: plain still round-trips|}, + {|theorem x = 1 proof revert y => from y do rewrite y end end in x|}, + ), + roundtrip_test( + {|Algebrite: `with` still belongs to algebra|}, + {|theorem x = 1 proof from y do algebra z end end in x|}, + ), + /* Hypothesis naming. The named forms share their leading token with + the plain forms, and "=" is a prefix of "==" and "=>", so these pin + that the named forms survive a round trip and that the plain ones + do too (see `Insert.plain_of_named_variant`). */ + roundtrip_test( + {|AssumeNamed: names the hypothesis|}, + {|theorem x = 1 proof assume h = y == 1 => from y do rewrite h end end in x|}, + ), + roundtrip_test( + {|Cases: plain|}, + {|theorem x = 1 proof cases y | true => ? | false => ? end in x|}, + ), + roundtrip_test( + {|HaveNamed: names the fact|}, + {|theorem x = 1 proof have h = y == 1 proof ? => from y do rewrite h end end in x|}, + ), + roundtrip_test( + {|Have: plain, with an equality in its proposition|}, + {|theorem x = 1 proof have y == 1 proof ? => ? in x|}, + ), + roundtrip_test( + {|Assume: plain, with an equality in its proposition|}, + {|theorem x = 1 proof assume y == 1 => ? in x|}, + ), + roundtrip_test( + {|Alias: retroactive naming|}, + {|theorem x = 1 proof alias h = assume => from y do rewrite h end end in x|}, + ), + roundtrip_test( + {|Alias: fact spelled out as a proposition|}, + {|theorem x = 1 proof alias h = y == 1 => from y do rewrite h end end in x|}, + ), + /* An `assume` in a case body must not turn its split into the named + form: its `==` and `=>` pass through "=" on the way. */ + roundtrip_test( + {|Cases: plain survives an assume in a case body|}, + {|theorem x = 1 proof cases y | true => assume y == 1 => ? | false => ? end in x|}, + ), + roundtrip_test( + {|Induction: plain survives an assume in a case body|}, + {|theorem x = 1 proof induction y | true => assume y == 1 => ? | false => ? end in x|}, + ), /* Module expressions: empty module roundtrip */ roundtrip_test({|Module: empty|}, {|{}|}), /* Module text round-trip tests */ @@ -1056,6 +1226,135 @@ let roundtrip_defensive_paren_tests = ( ], ); +/* Defensive printing must be idempotent: parse → print → parse → print + reaches a fixed point after the first print. Otherwise every editor + round-trip (e.g. EditorTransform patches on proof edits) adds a layer + of parens, e.g. on an ascription that is already parenthesized + (`forall x:(([Int]))` after two induction-case edits). Settings mirror + EditorTransform.Splice.to_segment. */ +let editable_print = (exp: Exp.t): string => + print_seg( + ExpToSegment.exp_to_segment( + exp, + ~settings={ + ...ExpToSegment.Settings.editable(~inline=true), + use_literal_lexemes: false, + }, + ), + ); + +let defensive_idempotence_test = (name: string, input: string) => + test_case(name, `Quick, () => { + switch (Parser.to_term(input, ~root=Exp)) { + | Some(term) => + let once = editable_print(term); + switch (Parser.to_term(once, ~root=Exp)) { + | Some(term') => + let twice = editable_print(term'); + check(string, {|Defensive print fixed point|}, once, twice); + | None => Alcotest.fail({|Failed to re-parse printed text: |} ++ once) + }; + | None => Alcotest.fail({|Failed to parse|}) + } + }); + +let defensive_idempotence_tests = ( + "Defensive Print Idempotence", + [ + defensive_idempotence_test( + {|Forall with list-type ascription|}, + {|forall x:[Int] -> x == x|}, + ), + defensive_idempotence_test( + {|Forall with atomic-type ascription|}, + {|forall x:Int -> x == x|}, + ), + defensive_idempotence_test( + {|Forall with pre-parenthesized ascription|}, + {|forall x:([Int]) -> x == x|}, + ), + defensive_idempotence_test( + {|Forall with arrow-type ascription|}, + {|forall f:(Int -> Int) -> f == f|}, + ), + /* The stepper builds left-nested chains. */ + test_case( + {|Left-nested proof chain ending in an assume keeps its scope|}, + `Quick, + () => { + let flatten_left = (p: Proof.t): Proof.t => + switch (p.term) { + | Seq({term: Parens(inner), _}, rest) => { + ...p, + term: Seq(inner, rest), + } + | _ => p + }; + let grouped = + Test_Evaluator_Prelude.parse_exp( + {|theorem t = 1 == 1 proof (step; assume 1 == 1 => ?); step in t|}, + ); + let left_nested = + grouped + |> Exp.map_term(~f_exp=(continue, e) => + switch (e.term) { + | Theorem(p, stmt, proof, body) => { + ...e, + term: Theorem(p, stmt, flatten_left(proof), body), + } + | _ => continue(e) + } + ); + let reread = + Test_Evaluator_Prelude.parse_exp(editable_print(left_nested)); + check( + bool, + "reads back with parens around the chain", + true, + Equality.( + equality({ + ...syntactic_settings, + ignore_parens: false, + }). + exp + )( + reread, + grouped, + ), + ); + }, + ), + defensive_idempotence_test( + {|Fun with ascribed pattern|}, + {|fun (x : Int) -> x|}, + ), + defensive_idempotence_test( + {|Let with ascribed pattern|}, + {|let x : [Int] = [1] in x|}, + ), + defensive_idempotence_test( + {|Sum type definition|}, + {|type T = +A + B(T) in A|}, + ), + defensive_idempotence_test( + {|Parenthesized sum type|}, + {|let x : [(+A + B)] = [] in x|}, + ), + /* A parenthesized sum doesn't define its constructors, so a program + printed with one doesn't read back as the program it was. */ + test_case({|Sum type definition is printed bare|}, `Quick, () => + check( + string, + "no parentheses around the sum", + {|type T = + A + B(T) in A|}, + editable_print( + Test_Evaluator_Prelude.parse_exp({|type T = +A + B(T) in A|}), + ), + ) + ), + ], +); + /* Larger program round-trip tests with comments, formatting, and multi-line structure. These verify that secondary-in-terms handles complex nested expressions correctly. */ let roundtrip_larger_programs = ( @@ -1771,12 +2070,188 @@ let pad_ids_tests = ( ], ); +/* Expressions embedded in proof steps get the same defensive parens as + any other expression. Steps inserted by the stepper UI are built, not + parsed, so they carry no explicit Parens node: `parenthesize` has to + descend through the proof to add them, otherwise a `fun` + in application-head position reparses as the argument being applied + inside the body (`(fun x -> 100 / x)(y)` printing as + `fun x -> 100 / x(y)`). */ +let built_fun_ap = (): Exp.t => { + let body = Test_Evaluator_Prelude.parse_exp({|100 / x|}); + let pat = Pat.fresh(Var("x")); + let f = Exp.fresh(Fun(pat, body, None, None)); + Exp.fresh(Ap(Forward, f, Test_Evaluator_Prelude.parse_exp({|y|}))); +}; + +let theorem_around = (pf: TermBase.Proof.term): Exp.t => + Exp.fresh( + Theorem( + Pat.fresh(Var("t")), + Test_Evaluator_Prelude.parse_exp({|1 == 1|}), + Proof.fresh(pf), + Exp.fresh(Var("t")), + ), + ); + +let proof_paren_test = + (name: string, pf: TermBase.Proof.term, expected: string) => + test_case( + name, + `Quick, + () => { + let printed = editable_print(theorem_around(pf)); + check(string, "printed with defensive parens", expected, printed); + /* and it reparses to the same text */ + switch (Parser.to_term(printed, ~root=Exp)) { + | Some(t) => + check(string, "reparse fixed point", printed, editable_print(t)) + | None => Alcotest.fail("failed to reparse: " ++ printed) + }; + }, + ); + +let proof_embedded_paren_tests = { + let focus = (selector, step: TermBase.Proof.term): TermBase.Proof.term => + Focus({ + ordinal: None, + selector, + body: Proof.fresh(step), + }); + let refl: TermBase.Proof.term = + AxiomStep({ + direction: Util.Direction.Right, + equality: Exp.fresh(Var("refl")), + instantiation: None, + }); + ( + "Defensive Parens: Proof-Embedded Expressions", + [ + proof_paren_test( + {|focus selector: plain fun in application head|}, + focus(built_fun_ap(), refl), + {|theorem t = 1 == 1 proof from (fun x -> 100 / x)(y) do rewrite refl end end in t|}, + ), + proof_paren_test( + {|assume hypothesis: fun in application head|}, + Assume(built_fun_ap(), None, Proof.fresh(EmptyHole)), + {|theorem t = 1 == 1 proof assume(fun x -> 100 / x)(y) => ? in t|}, + ), + /* A built `Seq` whose left arm is a wrapping form: the wrapping + form's body slot extends rightward (P.fun_ is looser than P.semi), + so without grouping parens `funext y => ?; step` reparses as + `Funext(y, Seq(?, eval))`. */ + proof_paren_test( + {|Seq left arm: a wrapping form is parenthesized|}, + Seq( + Proof.fresh( + Funext(Pat.fresh(Var("y")), Proof.fresh(EmptyHole)), + ), + Proof.fresh(EvalStep), + ), + {|theorem t = 1 == 1 proof(funext y => ?); step in t|}, + ), + /* Control: `;` is associative and right-associative, so a + left-nested Seq still prints flat — no parens churn. */ + proof_paren_test( + {|Seq left arm: a nested Seq still prints flat|}, + Seq( + Proof.fresh( + Seq( + Proof.fresh(focus(Exp.fresh(Var("a")), EvalStep)), + Proof.fresh(focus(Exp.fresh(Var("b")), EvalStep)), + ), + ), + Proof.fresh(focus(Exp.fresh(Var("c")), EvalStep)), + ), + {|theorem t = 1 == 1 proof from a do step end; from b do step end; from c do step end in t|}, + ), + ], + ); +}; + +/* A focus's selector reads back as the same term from its `from … do` + slot, whatever form it is: the slot is delimited, so the selector needs + no parentheses. Checked with both parsers, and with the linebreaks the + printer puts in. */ +let selector_roundtrip_test = (~ordinal=?, selector: string) => + test_case( + selector, + `Quick, + () => { + let exp = + theorem_around( + Focus({ + ordinal: Option.map(~f=IdTagged.fresh, ordinal), + selector: Test_Evaluator_Prelude.parse_exp(selector), + body: Proof.fresh(EvalStep), + }), + ); + List.iter( + ~f= + inline => { + let printed = + print_seg( + ExpToSegment.exp_to_segment( + exp, + ~settings=ExpToSegment.Settings.editable(~inline), + ), + ); + let reads_back = (parser: string, reparsed: option(Exp.t)) => + switch (reparsed) { + | Some(reparsed) => + check( + Test_Evaluator_Prelude.dhexp_typ, + parser ++ ": " ++ printed, + exp, + reparsed, + ) + | None => + Alcotest.fail(parser ++ " failed to reparse: " ++ printed) + }; + reads_back("typing parser", Parser.to_term(printed, ~root=Exp)); + reads_back( + "fast parser", + PersistentZipper.parse_text(~source="test", ~root=Exp, printed) + |> Option.map(~f=z => + MakeTerm.from_zip_for_sem(z, ~root=Exp).term + ), + ); + }, + [true, false], + ); + }, + ); + +let selector_roundtrip_tests = ( + "Round-Trip: Focus Selectors", + [ + selector_roundtrip_test("x"), + selector_roundtrip_test("f(x) + 1"), + selector_roundtrip_test("a == b"), + selector_roundtrip_test("a == b && c == d"), + selector_roundtrip_test("if a then b else c"), + selector_roundtrip_test("if $e then $e else $e"), + selector_roundtrip_test("case x | 0 => 1 | _ => 2 end"), + selector_roundtrip_test("fun x -> x + 1"), + selector_roundtrip_test("let y = 1 in y + 1"), + selector_roundtrip_test("a; b"), + selector_roundtrip_test("1 + (if a then b else c)"), + selector_roundtrip_test(~ordinal=2, "x + 1"), + selector_roundtrip_test(~ordinal=2, "if a then b else c"), + selector_roundtrip_test(~ordinal=2, "let y = 1 in y + 1"), + ], +); + let all = [ tests, pad_ids_tests, + proof_embedded_paren_tests, + selector_roundtrip_tests, roundtrip_tests, roundtrip_incomplete_tests, roundtrip_defensive_paren_tests, + defensive_idempotence_tests, roundtrip_larger_programs, roundtrip_grout_string_tests, roundtrip_projector_tests, diff --git a/test/Test_ExplainThis.re b/test/Test_ExplainThis.re index 67d045c38e..4a0e7752cd 100644 --- a/test/Test_ExplainThis.re +++ b/test/Test_ExplainThis.re @@ -761,6 +761,288 @@ let golden_case = ((name, src)) => }, ); +/* --- prover-form documentation completeness ------------------------------ */ + +/* Every form of the Proof sort must map to a real message, not a generic + "Proof term" fallback. `ProofDoc.single` is total over `Proof.term`, so + the compiler already guarantees an arm exists; what this test guarantees + is that each arm carries prose, that the prose references every child it + colors (a coloring whose id never appears in the message paints + nothing), that no `%s` placeholder was left unfilled, and that each + example's source really parses. */ + +let contains = (hay: string, needle: string): bool => { + let (nh, nn) = (String.length(hay), String.length(needle)); + let rec go = (i: int) => + i + nn > nh + ? false + : String.equal(String.sub(hay, ~pos=i, ~len=nn), needle) || go(i + 1); + go(0); +}; + +let hole_proof = () => Proof.fresh(EmptyHole); +let some_exp = (): Exp.t => Exp.fresh(EmptyHole); +let some_pat = (): Pat.t => Pat.fresh(EmptyHole); +let inst = () => Some((some_exp(), some_exp())); + +/* Representative terms, one per constructor (and one per shape of the + optional `with` clause, which selects a different message). Exhaustive + by construction: a new proof form fails to compile here. */ +let representatives = (cls: Proof.cls): list(Proof.t) => + switch (cls) { + | Invalid => [Proof.fresh(Invalid("~"))] + | EmptyHole => [Proof.fresh(EmptyHole)] + | MultiHole => [Proof.fresh(MultiHole([]))] + | Seq => [Proof.fresh(Seq(hole_proof(), hole_proof()))] + | AxiomStep => + [Util.Direction.Right, Util.Direction.Left] + |> List.concat_map(~f=direction => + [None, inst()] + |> List.map(~f=instantiation => + Proof.fresh( + AxiomStep({ + direction, + equality: some_exp(), + instantiation, + }), + ) + ) + ) + | AlgebriteStep => [Proof.fresh(AlgebriteStep(some_exp()))] + | EvalStep => [Proof.fresh(EvalStep)] + | Focus => [ + Proof.fresh( + Focus({ + ordinal: None, + selector: some_exp(), + body: hole_proof(), + }), + ), + ] + | Cases => [ + Proof.fresh(Cases(some_exp(), [(some_pat(), hole_proof())])), + ] + | Induction => [ + Proof.fresh(Induction(some_exp(), [(some_pat(), hole_proof())])), + ] + | Forall => [Proof.fresh(Forall(some_pat(), hole_proof()))] + | Funext => [Proof.fresh(Funext(some_pat(), hole_proof()))] + | Assume => [ + Proof.fresh(Assume(some_exp(), None, hole_proof())), + Proof.fresh(Assume(some_exp(), Some(some_pat()), hole_proof())), + ] + | Alias => [Proof.fresh(Alias(some_pat(), some_exp(), hole_proof()))] + | Generalize => [Proof.fresh(Generalize(some_exp(), hole_proof()))] + | Revert => [ + Proof.fresh(Revert(some_exp(), None, hole_proof())), + Proof.fresh(Revert(some_exp(), inst(), hole_proof())), + ] + | Have => [ + Proof.fresh(Have(some_exp(), None, hole_proof(), hole_proof())), + Proof.fresh( + Have(some_exp(), Some(some_pat()), hole_proof(), hole_proof()), + ), + ] + /* Parens are transparent: their doc is the inner form's, so the + representative wraps a form that has a worked example. */ + | Parens => [ + Proof.fresh(Parens(Proof.fresh(Funext(some_pat(), hole_proof())))), + ] + }; + +/* The degenerate forms carry a message but no worked example. */ +let example_free = (cls: Proof.cls): bool => + switch (cls) { + | Invalid + | EmptyHole + | MultiHole => true + | Seq + | AxiomStep + | AlgebriteStep + | EvalStep + | Focus + | Cases + | Induction + | Forall + | Funext + | Assume + | Generalize + | Revert + | Have + | Alias + | Parens => false + }; + +let check_doc = + (~what: string, ~needs_example: bool, doc: Web.ExplainThisForm.Simple.t) => { + let msg = doc.explanation; + Alcotest.check( + Alcotest.bool, + what ++ ": message is real prose", + true, + String.length(msg) > 80, + ); + Alcotest.check( + Alcotest.bool, + what ++ ": message is not the generic fallback", + false, + contains(msg, "Proof term"), + ); + Alcotest.check( + Alcotest.bool, + what ++ ": no unfilled format placeholder", + false, + contains(msg, "%s"), + ); + /* Every colored child must be referenced by the message. */ + let (_, colorings) = doc.abstract; + List.iter( + ~f= + ((_, id)) => + Alcotest.check( + Alcotest.bool, + what + ++ ": message references its colored child " + ++ Id.to_string(id), + true, + contains(msg, Id.to_string(id)), + ), + colorings, + ); + if (needs_example) { + Alcotest.check( + Alcotest.bool, + what ++ ": has at least one example", + true, + !List.is_empty(doc.examples), + ); + }; + /* An example whose source failed to parse comes back as an empty + segment, so this checks the example programs are real syntax. */ + List.iter( + ~f= + (ex: Web.ExplainThisForm.example) => + Alcotest.check( + Alcotest.bool, + what ++ ": example parses", + true, + !List.is_empty(Lazy.force(ex.term)), + ), + doc.examples, + ); +}; + +let test_proof_forms_documented = () => + List.iter( + ~f= + (cls: Proof.cls) => + List.iter( + ~f= + p => + check_doc( + ~what=Proof.show_cls(cls), + ~needs_example=!example_free(cls), + Web.ProofDoc.single(p), + ), + representatives(cls), + ), + Proof.all_of_cls, + ); + +/* End-to-end: the cursor inspector's own path. `color_map_of` gives an + empty color map for plain prose and a populated one for a form whose + message references its children, so a non-empty map on every InfoProof + in these programs asserts that the dispatch reaches ProofDoc rather than + a stub. Between them the sources cover every step form that takes + children. */ +let proof_sources = [ + "theorem t = 1 + 4 == 5 proof from 1 + 4 do step end; from 5 == 5 do step end in 0", + "theorem t = 1 + 1 == 2 proof from 1 + 1 do algebra 2 end end in 0", + "theorem t = (true && false) == (false && true) proof from true && false do rewrite and_comm end end in 0", + "theorem t = (true && false) == (false && true) proof from false && true do rewrite <- and_comm end end in 0", + "theorem t = forall x -> x == x proof forall x => from x == x do rewrite refl end end in 0", + "theorem t = forall n: Int -> n == 1 ==> n == 1 proof assume n == 1 => from n == 1 do rewrite assume end end in 0", + "theorem t = forall x -> x == 1 proof have 1 == 1 proof from 1 == 1 do rewrite refl end end => ? in 0", + "theorem t = forall x -> x == 1 proof have h = 1 == 1 proof from 1 == 1 do rewrite refl end end => ? in 0", + "theorem inv = forall w -> w / w == 1 proof ? in theorem t = forall n -> n / n == 1 proof generalize n => forall n => from n / n do rewrite inv end end in 0", + "let f = fun x -> x + 1 in theorem lem = forall n: Int -> n == 1 ==> f(2) == 3 proof ? in theorem g = f(2) == 3 proof from f(2) do rewrite lem with n = 1 end end in 0", + "let f = fun x -> x + 1 in theorem p = forall n: Int -> n + 0 == n proof ? in theorem g = f(2) == 3 proof revert p with n = 5 => ? in 0", + "theorem t = forall n: Int -> forall m: Int -> n == n proof cases n > 0 | true => alias hn = case_eq => cases m > 0 | true => revert hn => ? | false => ? end | false => ? end in 0", + "theorem t = forall n: Int -> n > 0 ==> n != 0 proof assume n > 0 => cases n > 0 | true => revert case_eq => ? | false => ? end in 0", + "theorem t = forall x: Int -> forall y: Int -> x == 1 ==> y == 2 ==> x == x proof assume x == 1 => assume hy = y == 2 => revert hy => ? in 0", + "theorem t = forall n: Int -> n == 1 ==> n == n proof assume n == 1 => alias hn = assume => from n == n do rewrite refl end end in 0", + "type Nt = +Z+S(Nt) in let pos = fun e -> case e | Z => true | S(b) => true end in theorem t = forall e: Nt -> pos(e) proof induction e | Z => from pos(Z) do step end | S(b) => revert pos(b) => from pos(b) do rewrite ih_b end end end in 0", +]; + +let parse_exp = (s: string) => + switch (Haz3lcore.Parser.to_term(s, ~root=Exp)) { + | Some(e) => e + | None => Alcotest.fail("Failed to parse: " ++ s) + }; + +let test_cursor_on_proof_step_explains = () => { + let seen = ref(0); + /* Assert the sources really parse into the naming forms rather than + degrading to holes, which the loop below would skip in silence. */ + let named = ref([]); + List.iter( + ~f= + src => { + let info_map = statics(parse_exp(src)); + Id.Map.iter( + (_id, info: Info.t) => + switch (info) { + | InfoProof({user_term, _}) => + switch (user_term.term) { + /* The degenerate forms and `step` have no children to color. */ + | EmptyHole + | MultiHole(_) + | Invalid(_) + | EvalStep => () + | _ => + incr(seen); + switch (user_term.term) { + | Assume(_, Some(_), _) => named := ["assume", ...named^] + | Have(_, Some(_), _, _) => named := ["have", ...named^] + | Alias(_) => named := ["alias", ...named^] + | _ => () + }; + let (color_map, _) = + ET.color_map_of(~globals, ET.decide(~docs, Some(info))); + Alcotest.check( + Alcotest.bool, + Proof.show_cls(Proof.cls_of_term(user_term.term)) + ++ ": cursor gets a message referencing its children", + false, + Id.Map.is_empty(color_map), + ); + } + | _ => () + }, + info_map, + ); + }, + proof_sources, + ); + Alcotest.check( + Alcotest.bool, + "the sources really contain proof steps", + true, + seen^ >= 20, + ); + List.iter( + ~f= + shape => + Alcotest.check( + Alcotest.bool, + shape ++ ": source parsed into the named form", + true, + List.mem(named^, shape, ~equal=String.equal), + ), + ["assume", "have", "alias"], + ); +}; + let tests = ( "ExplainThis", [ @@ -770,6 +1052,16 @@ let tests = ( ), coverage_case, pairing_case, + Alcotest.test_case( + "every prover form has a real message", + `Quick, + test_proof_forms_documented, + ), + Alcotest.test_case( + "cursor on a proof step gets a real message", + `Quick, + test_cursor_on_proof_step_explains, + ), ...List.map(~f=golden_case, corpus), ], ); diff --git a/test/Test_FastParse.re b/test/Test_FastParse.re index 82130a095d..bb7f2932b5 100644 --- a/test/Test_FastParse.re +++ b/test/Test_FastParse.re @@ -99,6 +99,15 @@ let rejected = (name, txt) => ) }); +/* The stepper writes `$e` metavariables into focus selectors. */ +let metavariable_selector = {|let rev = fun xs -> case xs | [] => [] | x :: t => rev(t) @ [x] end in + +theorem rev_nil = rev([]) == [] proof + from $e([]) do step end; + rewrite refl end +in +rev_nil|}; + let tests = ( "FastParse", [ @@ -189,6 +198,8 @@ let tests = ( ), semantic("module with members", "let m = { let a = 1; let b = 2 } in m"), semantic("case with ctor pats", "case a | Down(x, y) => x | Up => 0 end"), + verbatim("focus selector with a metavariable", metavariable_selector), + semantic("focus selector with a metavariable", metavariable_selector), rejected("unbalanced brace", "let m = { let a = 1 in m"), test_case("projector trigger materializes", `Quick, () => { switch ( diff --git a/test/Test_Grammar.re b/test/Test_Grammar.re index 6f719fbde5..4f46b54bb0 100644 --- a/test/Test_Grammar.re +++ b/test/Test_Grammar.re @@ -58,8 +58,13 @@ let sample_expression = (cls_exp: Exp.cls): Grammar.UnitGrammar.exp => { | LivelitAp => livelit_ap(Forward, livelit_name("^slider"), int(1)) | Var => var("x") | Let => let_(Pat.empty_hole(), empty_hole(), empty_hole()) - | Theorem => theorem(Pat.empty_hole(), empty_hole(), empty_hole()) - | ProofObject => proof_object(Exp.empty_hole()) + | Theorem => + theorem( + Pat.empty_hole(), + empty_hole(), + Proof.empty_hole(), + empty_hole(), + ) | Forall => forall(Pat.empty_hole(), empty_hole()) | FixF => fix_f(Pat.empty_hole(), empty_hole(), None) | TyAlias => @@ -162,7 +167,6 @@ let sample_type = (cls_typ: Typ.cls): Grammar.UnitGrammar.typ => { | Parens => parens(unknown(Hole(EmptyHole))) | Rec => rec_(TPat.var("x"), unknown(Hole(EmptyHole))) | Poly => poly(TPat.var("x"), unknown(Hole(EmptyHole))) - | ProofOf => proof_of(Exp.var("x")) | EmptyHole => unknown(Hole(EmptyHole)) | SynSwitch => unknown(SynSwitch) | Internal => unknown(Internal) diff --git a/test/Test_InductionWildcard.re b/test/Test_InductionWildcard.re new file mode 100644 index 0000000000..4167c270db --- /dev/null +++ b/test/Test_InductionWildcard.re @@ -0,0 +1,68 @@ +open Alcotest; +open Language; +open Test_Evaluator_Prelude; +open Poly; + +/* A wildcard anywhere in a case pattern refuses the whole split before + * any case is checked. */ +let check_refused = (src: string, ()) => { + let (state, _, elab) = src |> parse_exp |> Test_ProofMap.eval_with_proof; + let pm = EvaluatorState.get_proof_map(state); + let entry = Test_ProofMap.proof_entry(state, elab); + check( + bool, + "only the wildcard mark", + true, + entry.marks == [ProofMark.InductionUnsupportedWildcard], + ); + check(bool, "goal passes through", true, entry.incoming == entry.outgoing); + check( + bool, + "not proven", + true, + ProofMap.full_status_of_proof(pm, Test_ProofMap.proof_of(elab)) + == ProofMap.Incomplete, + ); + check(int, "no case is checked", 1, Id.Map.cardinal(pm)); +}; + +let tests = ( + "InductionWildcard", + [ + test_case( + "after a case that checks", + `Quick, + check_refused( + {|theorem w = forall b: Bool -> b == true proof induction b | true => from true == true do rewrite refl end end | _ => from true == true do rewrite refl end end end in true|}, + ), + ), + test_case( + "in a cons head", + `Quick, + check_refused( + {|let first = fun xs -> case xs | [] => true | h :: t => h end in theorem w = forall xs: [Bool] -> first(xs) == true proof induction xs | [] => from first([]) do step end; from true == true do rewrite refl end end | _ :: t => from first(true :: t) do step end; from true == true do rewrite refl end end end in true|}, + ), + ), + test_case( + "nested in a cons head", + `Quick, + check_refused( + {|let first = fun xs -> case xs | [] => true | [] :: rest => true | (h :: t) :: rest => h end in theorem w = forall xs: [[Bool]] -> first(xs) == true proof induction xs | [] => from first([]) do step end; from true == true do rewrite refl end end | [] :: rest => from first([] :: rest) do step end; from true == true do rewrite refl end end | (_ :: t) :: rest => from first((true :: t) :: rest) do step end; from true == true do rewrite refl end end end in true|}, + ), + ), + test_case( + "in a constructor payload", + `Quick, + check_refused( + {|type N = +Z + S((Bool, Bool)) in let first = fun n -> case n | Z => true | S((a, y)) => a end in theorem w = forall n: N -> first(n) == true proof induction n | Z => from first(Z) do step end; from true == true do rewrite refl end end | S((_, _)) => from first(S((true, true))) do step end; from true == true do rewrite refl end end end in true|}, + ), + ), + test_case( + "in an ascribed tuple", + `Quick, + check_refused( + {|theorem w = forall p: (Bool, Bool) -> p == (true, true) proof induction p | ((_, _) : (Bool, Bool)) => from (true, true) == (true, true) do rewrite refl end end end in true|}, + ), + ), + ], +); diff --git a/test/Test_ListCaseStep.re b/test/Test_ListCaseStep.re new file mode 100644 index 0000000000..5a255ad13c --- /dev/null +++ b/test/Test_ListCaseStep.re @@ -0,0 +1,245 @@ +open Alcotest; +open Language; +open Poly; + +/* In `all_lists(xs) == true` the stepper's only step is the lookup of + * `all_lists`, which the checker's `step` passes through silently. The + * stepper offers the step the checker takes at `all_lists(xs)` instead, + * and taking it writes a `step` step that checks. */ + +module Rows = Web.StepperRows; +module Picker = Web.StepperPicker; +module Fixture = Test_StepperView.Fixture; + +let all_lists = {|let all_lists = fun (xs : [Int]) -> + case xs + | [] => true + | _ :: t => all_lists(t) + end +in +|}; + +let every = + all_lists + ++ "theorem every = forall (xs : [Int]) -> all_lists(xs) == true proof ? in 0"; + +let every_by_cases = + all_lists + ++ "theorem every = forall (xs : [Int]) -> all_lists(xs) == true " + ++ "proof induction xs | [] => ? | x :: t => ? end in 0"; + +let both_nil = + all_lists ++ "theorem both = all_lists([]) == all_lists([]) proof ? in 0"; + +/* The goal of a theorem's first row. */ +let first_goal = (f: Fixture.t): Picker.Goal.t => + Fixture.goal(f, Test_StepperView.first(f.rows)); + +/* The first row of induction case `i`. */ +let case_row = (f: Fixture.t, i): Rows.t => + switch ( + List.nth(Test_StepperView.cases(Test_StepperView.first(f.rows)), i) + ) { + | Some(rows) => Test_StepperView.first(rows) + | None => Alcotest.fail("no case " ++ string_of_int(i)) + }; + +let offered = (goal: Picker.Goal.t): list(EvaluatorStep.step) => + List.filter_map( + ~f= + (offer: Picker.EvalSteps.offer) => + switch (offer.kind) { + | Evaluation(step) => Some(step) + | Contraction => None + }, + goal.eval_steps, + ); + +/* What taking the `n`-th offered step writes, checking that it is `step` + * focused on `exp`: the focus's selector, printed, and the 0-based index + * of its match. */ +let written_focus = (goal: Picker.Goal.t, n, ~exp: string): (string, int) => + switch (Picker.take_step(goal, n)) { + | Some({at: Some({node, selector, index}), step: {term: EvalStep, _}}) => + check(string, "focuses on", exp, Test_ProofMap.print_exp(node)); + (Test_ProofMap.print_exp(selector), index); + | Some(_) => Alcotest.fail("taking the step writes something else") + | None => Alcotest.fail("taking the step writes nothing") + }; + +/* `from at do step end`, for the match with 0-based `idx`. */ +let focused_eval = (~exp, ~idx) => + "from " + ++ exp + ++ (idx == 0 ? "" : " at " ++ string_of_int(idx + 1)) + ++ " do step end"; + +let replace_once = (~sub, ~by, s) => + switch (Str.search_forward(Str.regexp_string(sub), s, 0)) { + | i => + String.sub(s, ~pos=0, ~len=i) + ++ by + ++ String.sub( + s, + ~pos=i + String.length(sub), + ~len=String.length(s) - i - String.length(sub), + ) + | exception Stdlib.Not_found => Alcotest.fail("no " ++ sub) + }; + +let check_entry = (entry: ProofMap.entry, ~outgoing: option(string)) => { + check( + list(string), + "the written step checks", + [], + List.map(~f=ProofMark.show, entry.marks), + ); + Option.iter( + ~f= + expected => + check( + string, + "outgoing goal", + expected, + Test_ProofMap.print_exp( + Test_ProofMap.require_exp("no outgoing goal", entry.outgoing), + ), + ), + outgoing, + ); +}; + +/* Writes `step` focused on the `idx`-th `exp` as the theorem's proof and + * checks it. */ +let check_written_proof = (src, ~exp, ~idx, ~outgoing) => { + let src = + replace_once( + ~sub="proof ?", + ~by="proof " ++ focused_eval(~exp, ~idx), + src, + ); + let (state, _, elab) = + Test_ProofMap.eval_with_proof(Test_Evaluator_Prelude.parse_exp(src)); + check_entry(Test_ProofMap.proof_entry(state, elab), ~outgoing); +}; + +let test_offers_the_checker_step = () => { + let goal = first_goal(Fixture.mk(~name="every", every)); + let steps = offered(goal); + check( + bool, + "offers a step other than a lookup", + true, + List.exists( + ~f=s => EvaluatorStep.get_step_kind(s) != Transition.VarLookup, + steps, + ), + ); + let highlighted = id => + Haz3lcore.TermData.root_tile(id, goal.editor.editor.syntax.term_data) + != None; + check( + bool, + "every offered step highlights a tile of the row", + true, + steps != [] && List.for_all(~f=highlighted, Picker.Goal.step_ids(goal)), + ); +}; + +let test_taking_it_writes_a_checked_step = () => { + let goal = first_goal(Fixture.mk(~name="every", every)); + switch (offered(goal)) { + | [_] => + let (selector, idx) = written_focus(goal, 0, ~exp="all_lists(xs)"); + check(int, "at index", 0, idx); + check_written_proof(every, ~exp=selector, ~idx, ~outgoing=None); + | steps => + Alcotest.fail(string_of_int(List.length(steps)) ++ " steps offered") + }; +}; + +/* Takes the first offered step in induction case `i`, writes it into the + * case's hole, and checks the written step. */ +let take_in_case = (i, ~hole, ~exp, ~outgoing) => { + let f = Fixture.mk(~name="every", every_by_cases); + let goal = Fixture.goal(f, case_row(f, i)); + let (selector, idx) = + switch (offered(goal)) { + | [_, ..._] => written_focus(goal, 0, ~exp) + | [] => Alcotest.fail("no step offered") + }; + let src = + replace_once( + ~sub=hole ++ " => ?", + ~by=hole ++ " => " ++ focused_eval(~exp=selector, ~idx), + every_by_cases, + ); + switch (case_row(Fixture.mk(~name="every", src), i)) { + | {kind: Step(_), step: {term: Focus(_), _}, entry: Some(entry), _} => + check_entry(entry, ~outgoing) + | _ => Alcotest.fail("the case is not a checked eval step") + }; +}; + +/* One step per side, each highlighting its side and writing the index + * under which the checker reduces that side. */ +let test_each_occurrence_writes_its_index = () => { + let goal = first_goal(Fixture.mk(~name="both", both_nil)); + check(int, "one step per side", 2, List.length(offered(goal))); + let (left, right) = + switch (Exp.term_of(goal.written)) { + | BinOp(Poly(Equals), l, r) => (l, r) + | _ => Alcotest.fail("not an == goal") + }; + let check_side = (side: Exp.t, ~outgoing) => + switch ( + List.findi(Picker.Goal.step_ids(goal), ~f=(_, id) => + Id.equal(id, Exp.rep_id(side)) + ) + |> Option.map(~f=fst) + ) { + | Some(n) => + let (selector, idx) = written_focus(goal, n, ~exp="all_lists([])"); + check_written_proof( + both_nil, + ~exp=selector, + ~idx, + ~outgoing=Some(outgoing), + ); + | None => Alcotest.fail("no step highlights " ++ Exp.show(side)) + }; + check_side(left, ~outgoing="true == all_lists([])"); + check_side(right, ~outgoing="all_lists([]) == true"); +}; + +let tests = ( + "ListCaseStep", + [ + test_case( + "a goal applying a let-bound function offers the checker's step", + `Quick, + test_offers_the_checker_step, + ), + test_case( + "taking it writes an eval step that checks", + `Quick, + test_taking_it_writes_a_checked_step, + ), + test_case("in the [] case body", `Quick, () => + take_in_case( + 0, + ~hole="[]", + ~exp="all_lists([])", + ~outgoing=Some("true == true"), + ) + ), + test_case("in the x :: t case body", `Quick, () => + take_in_case(1, ~hole="x :: t", ~exp="all_lists(x:: t)", ~outgoing=None) + ), + test_case( + "equal occurrences each write their own index", + `Quick, + test_each_occurrence_writes_its_index, + ), + ], +); diff --git a/test/Test_MakeTerm.re b/test/Test_MakeTerm.re index 8e402e77e1..5da22a61c4 100644 --- a/test/Test_MakeTerm.re +++ b/test/Test_MakeTerm.re @@ -406,5 +406,17 @@ let tests = (); }, ), + /* Malformed proof text makes a hole term, never an exception. */ + test_case( + "Malformed proof: have with two proof clauses in an induction case", + `Quick, + () => { + let _ = + parse_exp( + "theorem fill = true proof induction x | h => have p proof y proof induction a | [] => ? in 0", + ); + (); + }, + ), ], ); diff --git a/test/Test_MatchExp.re b/test/Test_MatchExp.re index e3c80d6b00..50d852ea9d 100644 --- a/test/Test_MatchExp.re +++ b/test/Test_MatchExp.re @@ -9,7 +9,7 @@ let parse_exp = (s: string) => { let match_check = ( - ~info_map=Language.Statics.Map.empty, + ~statics=Language.ProofStatics.empty, ~alphas=[], ~ctx_in=[], exp_r, @@ -39,9 +39,9 @@ let match_check = exp_r ++ " against " ++ exp, expected, Language.MatchExp.match_exp( - ~info_map, + ~statics, ~alphas, - ~exp_env=Language.Environment.empty, + ~defs=Language.Environment.empty, ~exp_r_ctx=ctx_in, exp_r', exp', @@ -196,3 +196,185 @@ let tests = [ ], ), ]; + +/* ---- Pattern metavariables in target slots (MetaVar / match_pattern) --- + * + * `$e` matches any expression, `$v` any value, and both are non-linear + * (occurrences are independent), exactly as in stepper filters. Named + * metavariables `$x` are linear: every occurrence must agree. + */ + +let pattern_check = (~env=Language.Environment.empty, pat, exp, expected, ()) => + check( + Alcotest.bool, + pat ++ " matches " ++ exp, + expected, + Language.MatchExp.matches_pattern(~env, parse_exp(pat), parse_exp(exp)), + ); + +/* `Occurrence.nth_pattern` indexes among pattern matches. Returns the + * matched subterm rendered back to a string for easy comparison. */ +let nth_pat_check = (pat, n, target, expected: option(string), ()) => { + let matched = + Language.Occurrence.nth_pattern(parse_exp(pat), n, parse_exp(target)); + switch (expected, matched) { + | (None, None) => + check( + Alcotest.bool, + pat ++ " has no match #" ++ string_of_int(n), + true, + true, + ) + | (Some(exp), Some(got)) => + if (!Language.Exp.fast_equal(got, parse_exp(exp))) { + Alcotest.fail( + pat + ++ " match #" + ++ string_of_int(n) + ++ ": expected " + ++ exp + ++ " but got " + ++ Language.Exp.show(got), + ); + } + | (Some(exp), None) => + Alcotest.fail("expected match " ++ exp ++ " for " ++ pat) + | (None, Some(_)) => Alcotest.fail("expected no match for " ++ pat) + }; +}; + +/* For a metavariable-free target, the dispatcher the checker uses has to + * agree with the exact-match `Occurrence.nth` lookup. */ +let ground_regression_check = (target, n, goal, ()) => { + let target' = parse_exp(target); + let goal' = parse_exp(goal); + let old = Language.Occurrence.nth(target', n, goal'); + let new_ = Language.Occurrence.nth_target(target', n, goal'); + check( + Alcotest.bool, + "ground target `" ++ target ++ "` #" ++ string_of_int(n) ++ " unchanged", + true, + Option.equal(Language.Exp.fast_equal, old, new_), + ); +}; + +let pattern_tests = [ + ( + "MetaVar patterns", + [ + /* $e: any expression, and non-linear. */ + test_case( + "$e matches a literal", + `Quick, + pattern_check("$e", "1", true), + ), + test_case( + "$e matches a compound expression", + `Quick, + pattern_check("$e", "1 + 2", true), + ), + test_case( + "$e == $e matches a reflexive equation", + `Quick, + pattern_check("$e == $e", "1 == 1", true), + ), + test_case( + "$e is non-linear: sides need not agree", + `Quick, + pattern_check("$e == $e", "1 == 2", true), + ), + test_case( + "$e still respects the surrounding structure", + `Quick, + pattern_check("$e == $e", "1 + 2", false), + ), + /* $v: any value. */ + test_case( + "$v matches a value", + `Quick, + pattern_check("$v + $v", "1 + 2", true), + ), + test_case( + "$v rejects a non-value operand", + `Quick, + pattern_check("$v + $v", "(1 + 2) + 4", false), + ), + test_case( + "$e accepts where $v rejects", + `Quick, + pattern_check("$e + $e", "(1 + 2) + 4", true), + ), + /* Named metavariables are linear. */ + test_case( + "$x == $x requires both sides to agree", + `Quick, + pattern_check("$x == $x", "1 == 1", true), + ), + test_case( + "$x == $x rejects differing sides", + `Quick, + pattern_check("$x == $x", "1 == 2", false), + ), + /* Ground patterns are the degenerate case. */ + test_case( + "a ground pattern matches only itself", + `Quick, + pattern_check("1 + 2", "1 + 2", true), + ), + test_case( + "a ground pattern rejects a different term", + `Quick, + pattern_check("1 + 2", "1 + 3", false), + ), + /* A focus's `at n` indexes among pattern matches. + * 1. The match is the parenthesized node: pattern matching + * ignores parens, so the outermost matching node is `(1 + 2)` + * itself, which is also the node the exact-match lookup + * returns. + * 2. Matches count left to right in the source. `nth_pattern` uses + * the same traversal as `Occurrence.nth`, so `at n` counts + * pattern matches in the order it counts exact occurrences. */ + test_case( + "nth_exp_pat: first $v + $v match", + `Quick, + nth_pat_check("$v + $v", 0, "(1 + 2) + (3 + 4)", Some("(1 + 2)")), + ), + test_case( + "nth_exp_pat: second $v + $v match", + `Quick, + nth_pat_check("$v + $v", 1, "(1 + 2) + (3 + 4)", Some("(3 + 4)")), + ), + test_case( + "nth_exp_pat: no third match", + `Quick, + nth_pat_check("$v + $v", 2, "(1 + 2) + (3 + 4)", None), + ), + test_case( + "nth_exp_pat: $e + $e takes the outermost sum first", + `Quick, + nth_pat_check( + "$e + $e", + 0, + "(1 + 2) + (3 + 4)", + Some("(1 + 2) + (3 + 4)"), + ), + ), + /* Ground targets against the exact-match lookup. */ + test_case( + "ground regression: occurrence 0", + `Quick, + ground_regression_check("1 + 2", 0, "(1 + 2) + (1 + 2) == 6"), + ), + test_case( + "ground regression: occurrence 1", + `Quick, + ground_regression_check("1 + 2", 1, "(1 + 2) + (1 + 2) == 6"), + ), + test_case( + "ground regression: missing occurrence", + `Quick, + ground_regression_check("9 + 9", 0, "(1 + 2) + (1 + 2) == 6"), + ), + ], + ), +]; diff --git a/test/Test_Menhir.re b/test/Test_Menhir.re index d4a17ca4c0..1bbf0c9811 100644 --- a/test/Test_Menhir.re +++ b/test/Test_Menhir.re @@ -111,6 +111,30 @@ let menhir_roundtrip_test = (name: string, source: string) => }, ); +/* Compares menhir ASTs directly. Used to check `Conversion.Exp.of_core`, + the core -> menhir-AST direction, which `menhir_matches` never + exercises. */ +let ast_check = + (testable(Fmt.using(AST.show_exp, Fmt.string)))(AST.equal_exp) + |> Alcotest.check; + +/* Round-trip through the other direction: take the segment parser's core + term for `src`, render it back to a menhir AST with `of_core`, and + require it to equal what menhir parses from the same text. */ +let of_core_renders_test = (name: string, src: string) => + test_case( + name, + `Quick, + () => { + let core = make_term_parse(src); + ast_check( + "of_core(MakeTerm parse) matches menhir parse", + Interface.parse_program(src), + Conversion.Exp.of_core(Grammar.map_exp_annotation(_ => false, core)), + ); + }, + ); + let menhir_maketerm_equivalent_test = (~speed_level=`Quick, name: string, actual: string) => test_case(name, speed_level, () => { @@ -282,6 +306,25 @@ let qcheck_menhir_serialized_equivalent_test = }, ); +/* Proof keywords that are ordinary names outside proof syntax. */ +let soft_proof_keywords = [ + "proof", + "funext", + "assume", + "generalize", + "have", + "revert", + "cases", + "induction", + "alias", + "rewrite", + "algebra", + "with", + "from", + "at", + "do", +]; + let tests = Fresh.( "MenhirParser", @@ -1081,7 +1124,244 @@ let ex5 = list_of_mylist(x) in Fresh.Exp.(dot(var("m"), label("X"))), {|m.X|}, ), + /* =================================================================== + Prover syntax + =================================================================== */ + /* --- `==>` : right-associative, one level looser than `||` ------- */ + full_parser_test( + "Implies", + bin_op(Bool(Implies), var("a"), var("b")), + "a ==> b", + ), + full_parser_test( + "Implies is right associative", + bin_op( + Bool(Implies), + var("a"), + bin_op(Bool(Implies), var("b"), var("c")), + ), + "a ==> b ==> c", + ), + full_parser_test( + "Implies binds looser than equality", + bin_op( + Bool(Implies), + bin_op(Poly(Equals), var("a"), var("b")), + bin_op(Poly(Equals), var("c"), var("d")), + ), + "a == b ==> c == d", + ), + full_parser_test( + "Implies binds looser than disjunction", + bin_op( + Bool(Implies), + bin_op(Bool(Or), var("a"), var("b")), + bin_op(Bool(Or), var("c"), var("d")), + ), + "a || b ==> c || d", + ), + full_parser_test( + "Conjunction binds tighter than implies", + bin_op( + Bool(Implies), + bin_op(Bool(And), var("a"), var("b")), + var("c"), + ), + "a && b ==> c", + ), + /* --- `forall` ---------------------------------------------------- */ + full_parser_test( + "Forall", + forall(Pat.var("x"), bin_op(Poly(Equals), var("x"), var("x"))), + "forall x -> x == x", + ), + full_parser_test( + "Forall with ascribed binder", + forall( + Pat.asc(Pat.var("n"), Typ.int()), + bin_op(Poly(Equals), var("n"), int(0)), + ), + "forall n : Int -> n == 0", + ), + /* The body extends across `==>`: fun_ (37) is looser than impl (34). */ + full_parser_test( + "Forall body swallows implications", + forall( + Pat.asc(Pat.var("n"), Typ.int()), + bin_op( + Bool(Implies), + bin_op(Poly(Equals), var("n"), int(0)), + bin_op(Poly(Equals), var("n"), int(1)), + ), + ), + "forall n : Int -> n == 0 ==> n == 1", + ), + /* --- proof prefix forms ------------------------------------------ */ + menhir_maketerm_equivalent_test( + "Theorem with an empty-hole proof", + "theorem t = forall x -> x == x proof ? in t", + ), + menhir_maketerm_equivalent_test( + "Proof assume", + "theorem t = forall n : Int -> n == 0 ==> n == 0 proof assume n == 0 => ? in t", + ), + menhir_maketerm_equivalent_test( + "Proof revert", + "theorem t = forall n : Int -> n == 0 ==> 1 == 1 proof assume n == 0 => revert n == 0 => ? in t", + ), + menhir_maketerm_equivalent_test( + "Proof generalize", + "theorem t = forall n : Int -> n == n proof forall n => generalize n => ? in t", + ), + /* `assume e => a; b` puts the whole sequence in the body: the prefix + forms sit at fun_ (37), looser than the proof `;` at semi (35). */ + menhir_maketerm_equivalent_test( + "Proof prefix binds looser than proof sequencing", + "theorem t = forall x -> x == x proof assume x == x => ?; ? in t", + ), + menhir_maketerm_equivalent_test( + "Proof rewrite step", + "theorem t = forall x -> x == x proof from x == x do rewrite refl end end in t", + ), + menhir_maketerm_equivalent_test( + "Proof rewrite <- step", + "theorem t = forall x -> x == x proof from x == x do rewrite <- refl end end in t", + ), + menhir_maketerm_equivalent_test( + "Proof eval step", + "theorem t = 1 + 1 == 2 proof from 1 + 1 do step end in t", + ), + menhir_maketerm_equivalent_test( + "Proof algebra step", + "theorem t = 1 + 1 == 2 proof from 1 + 1 do algebra 2 end end in t", + ), + menhir_maketerm_equivalent_test( + "Proof step at the root", + "theorem t = 2 == 2 proof step in t", + ), + /* `step` is a proof step only where a step goes. */ + menhir_maketerm_equivalent_test( + "A function named step, focused on and stepped", + "let step = fun x -> x in theorem t = step(1) == 1 proof from step(1) do step end; step in t", + ), + menhir_maketerm_equivalent_test( + "Proof focus at an occurrence, with two steps", + "theorem t = (1 + 1) * (1 + 1) == 4 proof from 1 + 1 at 2 do step; algebra 2 end end in t", + ), + menhir_maketerm_equivalent_test( + "Proof induction", + "theorem t = forall n : Int -> n == n proof induction n | 0 => ? | m => ? end in t", + ), + menhir_maketerm_equivalent_test( + "Parenthesized proof", + "theorem t = 1 == 1 proof (step) in t", + ), + menhir_maketerm_equivalent_test( + "Parenthesized chain as the left of a `;`", + "theorem t = 1 == 1 proof (step; assume 1 == 1 => ?); step in t", + ), + menhir_maketerm_equivalent_test( + "Focus selector with a metavariable", + "let rev = fun xs -> xs in theorem t = rev([]) == [] proof from $e([]) do step end; rewrite refl end in t", + ), + /* --- full prover programs (from test/evaluator) ------------------ */ + /* Test_Revert.ex_falso_src */ + menhir_maketerm_equivalent_test( + "Full program: ex falso via assume/revert", + "theorem t = forall n: Int -> n == 0 ==> n == 1 ==> false proof assume n == 0 => assume n == 1 => revert n == 1 => from n do rewrite assume end end; from 0 == 1 do step end; from false ==> false do step end in t", + ), + /* Test_Revert.adt_ih_src: ADT induction with a reverted IH. */ + menhir_maketerm_equivalent_test( + "Full program: ADT induction with a reverted IH", + "type Nt = +Z+S(Nt) in let pos = fun e -> case e | Z => true | S(b) => true end in theorem t = forall e: Nt -> pos(e) proof induction e | Z => from pos(Z) do step end | S(b) => revert pos(b) => from pos(b) do rewrite ih_b end end; from true ==> pos(S(b)) do step end; from pos(S(b)) do step end end in t", + ), + /* --- hypothesis naming ------------------------------------------- + The menhir grammar's naming productions must agree with the + tile-level forms, so these compare the two parsers directly. */ + menhir_maketerm_equivalent_test( + "assume = ...", + "theorem t = forall n: Int -> n == 1 ==> n == n proof assume h = n == 1 => from n do rewrite h end end; ? in t", + ), + menhir_maketerm_equivalent_test( + "cases", + "theorem t = forall n: Int -> n == n proof cases n > 0 | true => from n > 0 do rewrite case_eq end end | false => ? end in t", + ), + menhir_maketerm_equivalent_test( + "alias = ", + "theorem t = forall n: Int -> n == 1 ==> n == n proof assume n == 1 => alias h = assume => from n do rewrite h end end; ? in t", + ), + menhir_maketerm_equivalent_test( + "alias with a spelled-out proposition", + "theorem t = forall n: Int -> n == 1 ==> n == n proof assume n == 1 => alias h = n == 1 => from n do rewrite h end end; ? in t", + ), + menhir_maketerm_equivalent_test( + "have = ...", + "theorem t = 1 == 1 proof have h = 1 == 1 proof ? => rewrite h end in t", + ), + menhir_maketerm_equivalent_test( + "Citing a have by its default name", + "theorem t = 1 == 1 proof have 1 == 1 proof ? => rewrite have end in t", + ), + /* The plain forms keep parsing identically: `cases` and `assume` + share their leading token with their named variants. */ + menhir_maketerm_equivalent_test( + "plain cases with an assume in a case body", + "theorem t = forall n: Int -> n == n proof cases n > 0 | true => assume n == 1 => ? | false => ? end in t", + ), + /* --- core -> menhir AST (Conversion.of_core) ---------------------- */ + of_core_renders_test("of_core: implies", "a ==> b ==> c"), + of_core_renders_test( + "of_core: theorem with assume/revert", + "theorem t = forall n : Int -> n == 0 ==> 1 == 1 proof assume n == 0 => revert n == 0 => ? in t", + ), + of_core_renders_test( + "of_core: proof steps", + "theorem t = 1 + 1 == 2 proof from 1 + 1 do step end; from 1 + 1 do algebra 2 end end; from 2 == 2 do rewrite refl end end in t", + ), + of_core_renders_test( + "of_core: parenthesized proof", + "theorem t = 1 == 1 proof (step; assume 1 == 1 => ?); step in t", + ), + of_core_renders_test( + "of_core: named assume and have", + "theorem t = forall n : Int -> n == 1 ==> n == n proof assume h = n == 1 => have k = n == 1 proof ? => ? in t", + ), + of_core_renders_test( + "of_core: proof induction and generalize", + "theorem t = forall n : Int -> n == n proof forall n => generalize n => induction n | 0 => ? | m => ? end in t", + ), QCheck_alcotest.to_alcotest(qcheck_menhir_maketerm_equivalent_test), QCheck_alcotest.to_alcotest(qcheck_menhir_serialized_equivalent_test), + ...List.concat_map( + ~f= + w => + [ + menhir_only_test( + "Proof keyword as a variable: " ++ w, + let_( + Pat.var(w), + int(1), + ap( + Forward, + fn(Pat.var(w), var(w), None, None), + var(w), + ), + ), + sprintf("let %s = 1 in (fun %s -> %s)(%s)", w, w, w, w), + ), + menhir_maketerm_equivalent_test( + "Proof keyword as a name, label and tuple binder: " ++ w, + sprintf( + "let %s = 1 in (fun (%s, x) -> (%s = %s, x))(%s, 2)", + w, + w, + w, + w, + w, + ), + ), + ], + soft_proof_keywords, + ), ], ); diff --git a/test/Test_MultiProbe.re b/test/Test_MultiProbe.re index d8bc6eb82c..bf7f2b665f 100644 --- a/test/Test_MultiProbe.re +++ b/test/Test_MultiProbe.re @@ -125,7 +125,7 @@ let test_probe_placement = (~name: string, ~code: string): test_case(_) => { target_id, syntax.term_data, syntax.terms, - syntax.measured, + Haz3lcore.CachedSyntax.measured(syntax), info_map, ) ) { diff --git a/test/Test_NegativeSelector.re b/test/Test_NegativeSelector.re new file mode 100644 index 0000000000..87c599f424 --- /dev/null +++ b/test/Test_NegativeSelector.re @@ -0,0 +1,151 @@ +open Alcotest; +open Language; +open Poly; + +/* Evaluation produces negative numbers that source can't spell: `-5` + * written out reads back as a negation. So the stepper doesn't offer, or + * write, a `step` step whose selector holds one; the checker could never + * find it. Each program's first step produces a negative number, and the + * hole after it is the row under test. */ + +module Picker = Web.StepperPicker; + +/* The goal of the hole after the program's first step. */ +let hole_goal = (src: string): Picker.Goal.t => { + let f = Test_StepperView.Fixture.mk(src); + switch ( + List.find( + ~f=(row: Web.StepperRows.t) => row.kind == Hole, + Test_StepperView.Fixture.all(f), + ) + ) { + | Some(row) => Test_StepperView.Fixture.goal(f, row) + | None => Alcotest.fail("no hole row") + }; +}; + +/* What each offered step writes. */ +let written_targets = (goal: Picker.Goal.t): list((Exp.t, int)) => + List.mapi(~f=(n, _) => Picker.take_step(goal, n), goal.eval_steps) + |> List.filter_map( + ~f= + fun + | Some( + {at: Some({selector, index, _}), step: {term: EvalStep, _}}: Picker.pick, + ) => + Some((selector, index)) + | _ => None, + ); + +/* The checker's entry for `step` focused on the `idx`-th `selector`, + * written in the hole. */ +let check_written = (src, ~selector, ~idx): ProofMap.entry => { + let src = + Test_ListCaseStep.replace_once( + ~sub="; ? in 0", + ~by= + "; " ++ Test_ListCaseStep.focused_eval(~exp=selector, ~idx) ++ " in 0", + src, + ); + let (state, _, elab) = + Test_ProofMap.eval_with_proof(Test_Evaluator_Prelude.parse_exp(src)); + switch (Test_ProofMap.proof_of(elab).term) { + | Seq(_, second) => + switch ( + ProofMap.lookup( + Proof.rep_id(second), + EvaluatorState.get_proof_map(state), + ) + ) { + | Some(entry) => entry + | None => Alcotest.fail("no entry for the written step") + } + | _ => Alcotest.fail("the proof is not two steps") + }; +}; + +/* Only the side without a negative number is offered, and what it writes + * checks. */ +let offers_only = (src, ~spellable) => { + switch (written_targets(hole_goal(src))) { + | [(selector, idx)] => + check( + string, + "the offered selector", + spellable, + Test_ProofMap.print_exp(selector), + ); + check( + list(string), + "the written step checks", + [], + List.map( + ~f=ProofMark.show, + check_written(src, ~selector=spellable, ~idx).marks, + ), + ); + | targets => + Alcotest.fail( + "offered: " + ++ String.concat( + ~sep=", ", + List.map(~f=((e, _)) => Test_ProofMap.print_exp(e), targets), + ), + ) + }; +}; + +let negative_int = {|theorem t = (0 - 5) * 2 == 0 - 10 proof from 0 - 5 do step end; ? in 0|}; + +let negative_float = {|theorem t = (0.0 -. 2.5) *. 2.0 ==. 0.0 -. 5.0 proof from 0.0 -. 2.5 do step end; ? in 0|}; + +let test_stale_offer = () => { + let goal = hole_goal(negative_int); + let written = goal.written; + let env = Picker.Goal.env(goal); + let negative_side = + switch (Exp.term_of(written)) { + | BinOp(_, l, _) => l + | _ => Alcotest.fail("not an == goal") + }; + let step = + switch (EvaluatorStep.get_status(~settings=CoreSettings.on, written, env)) { + | AvailableSteps(steps) => + List.find_exn(steps, ~f=s => + Id.equal(EvaluatorStep.get_step_id(s), Exp.rep_id(negative_side)) + ) + | AutoStep(_) => Alcotest.fail("the goal has a hidden step") + }; + let stale = { + ...goal, + eval_steps: [ + { + source: Exp.rep_id(negative_side), + kind: Evaluation(step), + }, + ], + }; + check( + bool, + "taking it writes nothing", + true, + Picker.take_step(stale, 0) == None, + ); +}; + +let tests = ( + "NegativeSelector", + [ + test_case("a negative Int isn't quoted", `Quick, () => + offers_only(negative_int, ~spellable="$e - $e") + ), + test_case("a negative Float isn't quoted", `Quick, () => + offers_only(negative_float, ~spellable="$e -. $e") + ), + test_case( + "a stale offer quoting a negative number writes nothing", + `Quick, + test_stale_offer, + ), + ], +); diff --git a/test/Test_PrettyPrint.re b/test/Test_PrettyPrint.re index ab9f1d970e..e06c112826 100644 --- a/test/Test_PrettyPrint.re +++ b/test/Test_PrettyPrint.re @@ -1224,6 +1224,80 @@ else 3|}, ), ]; +/* === Sequences === + `;` binds tighter than a rule and than the prefix forms that take a body + (fun, if, let), so a sequence that follows one is its body. */ + +let sequence_tests = [ + test_format_seg( + ~name="A sequence after an arrow is the function's body", + ~input="fun x -> a; b", + ~expected={|fun x -> + a; + b|}, + (), + ), + test_format_seg( + ~name="A sequence in a case rule goes below the rule", + ~input="case s | a => x; y | b => z end", + ~expected={|case s +| a => + x; + y +| b => z +end|}, + (), + ), + test_format_seg( + ~name="A sequence after else is in the else branch", + ~input="if c then a else b; d", + ~expected={|if c +then a +else b; +d|}, + (), + ), + test_format_seg( + ~name="A let in a sequence keeps the lines after it", + ~input="a; let x = 1 in b; c", + ~expected={|a; +let x = 1 in +b; +c|}, + (), + ), + test_format_seg( + ~name="A semicolon stays with the parentheses before it", + ~input="(a); b", + ~expected={|(a); +b|}, + (), + ), +]; + +/* === Case scrutinees === */ + +let scrutinee_tests = [ + test_format_seg( + ~name="An application scrutinee still breaks the rules", + ~input="case f(x) | 0 => 1 end", + ~expected={|case f(x) +| 0 => 1 +end|}, + (), + ), + test_format_seg( + ~name="An operator in the scrutinee breaks apart from those in the rules", + ~width=30, + ~input="case alpha + beta | 0 => gamma + delta | _ => e end", + ~expected={|case alpha + beta +| 0 => gamma + delta +| _ => e +end|}, + (), + ), +]; + /* === SpaceNormalize canonicalize (Format(Spacing) backend) === */ let respace = (input: string): string => @@ -1333,6 +1407,8 @@ let tests = [ ("PrettyPrint.Breaking", breaking_tests), ("PrettyPrint.Delimiters", delimiter_tests), ("PrettyPrint.Case", case_tests), + ("PrettyPrint.Scrutinees", scrutinee_tests), + ("PrettyPrint.Sequences", sequence_tests), ("PrettyPrint.Complex", complex_tests), ("PrettyPrint.CommaCompound", comma_compound_tests), ("PrettyPrint.Realworld", realworld_tests), diff --git a/test/Test_ProblemCollection.re b/test/Test_ProblemCollection.re index 5014852503..c8045fef75 100644 --- a/test/Test_ProblemCollection.re +++ b/test/Test_ProblemCollection.re @@ -200,7 +200,7 @@ let nearest_measured_id_invalid = () => { let nearest_measured_id_inside_fold = () => { /* Walk an Exp tree and return the id of the first Int literal matching - `n`. Mirrors ProofHacks.find_exp_id. */ + `n`. Mirrors Exp.find_by_id. */ module M = { exception Found(Language.Exp.t); }; @@ -270,7 +270,7 @@ let nearest_measured_id_inside_fold = () => { /* Look the resolved id up in the Exp tree and assert the node there is a Fold projector. */ let resolved_exp = - switch (Language.ProofHacks.find_exp_id(resolved, exp)) { + switch (Language.Exp.find_by_id(resolved, exp)) { | Some(e) => e | None => fail("resolved id not found in Exp tree") }; diff --git a/test/Test_PromptFactory.re b/test/Test_PromptFactory.re index 64bdd712c8..c310652ce9 100644 --- a/test/Test_PromptFactory.re +++ b/test/Test_PromptFactory.re @@ -85,7 +85,6 @@ let reserved = [ "type", "typfun", "use", - "proof_object", "of_jdmt", "of_ctx", "of_prop", @@ -109,7 +108,6 @@ let soft_reserved = [ "matched_prod", "matched_sum", "poly", - "proof_of", "rec", "then", "val", diff --git a/test/Test_ProofContext.re b/test/Test_ProofContext.re new file mode 100644 index 0000000000..952f558b11 --- /dev/null +++ b/test/Test_ProofContext.re @@ -0,0 +1,236 @@ +open Alcotest; +open Haz3lcore; +open Web; +open Language; +open Poly; + +/* Evaluation checks proofs with the statics its request carries, and + * EvalResult ignores replies to requests it has since replaced. The + * reference is the evaluator checking the same program with its full + * statics. */ + +let settings = CoreSettings.on; + +let cached_statics = (term: Exp.t): CachedStatics.t => + CachedStatics.init_from_term(~settings, ~is_dynamic_term=false, term); + +let native_map = (cs: CachedStatics.t): ProofMap.t => + Evaluator.evaluate( + ~eval_info= + EvalInfo.of_info_map( + ~probe_all=settings.probe_all, + ~targets=cs.targets, + cs.info_map, + ), + ~statics=cs.info_map, + ~env=Builtins.env_init, + cs.elaborated, + ) + |> snd + |> EvaluatorState.get_proof_map; + +/* Each entry's marks and goals, as the user sees them. */ +let summary = (pm: ProofMap.t): list(string) => { + let exp = e => + Option.value_map(e, ~default="-", ~f=Test_ProofMap.print_exp); + Id.Map.bindings(pm) + |> List.map(~f=((id, entry: ProofMap.entry)) => + Id.to_string(id) + ++ " [" + ++ String.concat(~sep="; ", List.map(~f=ProofMark.show, entry.marks)) + ++ "] " + ++ exp(entry.incoming) + ++ " => " + ++ exp(entry.outgoing) + ); +}; + +let check_map = (msg, ~expected: ProofMap.t, m: EvalResult.Model.t) => + check( + list(string), + msg, + summary(expected), + summary(EvalResult.Model.proof_map(m)), + ); + +let test_checked_with_statics = () => { + /* Without the type of `b`, the checker can't tell `false` is missing. */ + let cs = + cached_statics( + Test_Evaluator_Prelude.parse_exp( + {|theorem t = forall (b : Bool) -> b || true proof + induction b + | true => from true || true do step end + end +in 0|}, + ), + ); + let m = + EvalResult.Update.calculate( + ~settings, + ~queue_worker=None, + ~is_edited=true, + cs, + EvalResult.Model.init, + ); + check_map("checked with the statics", ~expected=native_map(cs), m); +}; + +/* The edit changes `k`'s type, which only the statics know, and `j`'s + * value, which only the evaluation's env knows, so checking the edited + * program's statics against the old env matches neither program. The edit + * keeps every id, as edits in the editor do. */ +let before_edit = + Test_Evaluator_Prelude.parse_exp( + {|let (k, j) : (Bool, Int) = (true, 40 + 1) in theorem t = k || j == 41 proof + induction k + | true => from true || j == 41 do step end + | false => from false || j == 41 do step end + end +in 0|}, + ); + +let after_edit = { + let unknown_typ = ref(None); + let _ = + TermBase.Exp.map_term( + ~f_typ= + (continue, t: Typ.t) => { + switch (t.term) { + | Unknown(_) => unknown_typ := Some(t.term) + | _ => () + }; + continue(t); + }, + Test_Evaluator_Prelude.parse_exp("let x : ? = 1 in 0"), + ); + let f_typ = (continue, t: Typ.t): Typ.t => + switch (t.term, unknown_typ^) { + | (Atom(Bool), Some(unknown)) => { + ...t, + term: unknown, + } + | _ => continue(t) + }; + Test_Evaluator_Incremental.replace_int_lit( + ~from=40, + ~to_=41, + TermBase.Exp.map_term(~f_typ, before_edit), + ); +}; + +/* EvalResult with a worker whose requests are collected. */ +let queued = ref([]); + +let calculate = (~is_edited, cs, m) => + EvalResult.Update.calculate( + ~settings, + ~queue_worker=Some(r => queued := [r, ...queued^]), + ~is_edited, + cs, + m, + ); + +let update = (action, m) => + EvalResult.Update.update(~settings=Settings.Model.init, action, m).model; + +let latest_request = (): WorkerServer.Request.value => + switch (queued^) { + | [r, ..._] => r + | [] => Alcotest.fail("no request queued") + }; + +let reply = (req: WorkerServer.Request.value) => + switch (WorkerServer.evaluate_sync(req)) { + | Ok((result, state)) => + ProgramResult.ResultOk( + ProgramResult.{ + result, + state, + }, + ) + | Error(e) => ProgramResult.ResultFail(e) + }; + +let ack = (req: WorkerServer.Request.value): EvalResult.Update.t => + UpdateStreamingEval(req.generation, IncrEval.empty_outbox); + +/* Evaluates `cs` on the worker through to its result. */ +let evaluate = (cs, m) => { + let m = calculate(~is_edited=true, cs, m); + let req = latest_request(); + let m = calculate(~is_edited=false, cs, update(ack(req), m)); + let m = update(UpdateResult(req.generation, reply(req)), m); + calculate(~is_edited=false, cs, m); +}; + +let test_pending_keeps_previous_check = () => { + queued := []; + let before = cached_statics(before_edit); + let after = cached_statics(after_edit); + let native_before = native_map(before); + let native_after = native_map(after); + check( + bool, + "the edit changes the proof map", + false, + summary(native_before) == summary(native_after), + ); + let m = evaluate(before, EvalResult.Model.init); + check_map("before the edit", ~expected=native_before, m); + let m = calculate(~is_edited=true, after, m); + let req = latest_request(); + check_map("edit pending", ~expected=native_before, m); + let m = calculate(~is_edited=false, after, update(ack(req), m)); + check_map("edit acknowledged", ~expected=native_before, m); + let m = update(UpdateResult(req.generation, reply(req)), m); + let m = calculate(~is_edited=false, after, m); + check_map("edit evaluated", ~expected=native_after, m); +}; + +let test_replaced_request_ignored = () => { + queued := []; + let before = cached_statics(before_edit); + let after = cached_statics(after_edit); + let m = evaluate(before, EvalResult.Model.init); + let m = calculate(~is_edited=true, after, m); + let replaced = latest_request(); + /* Undoing the edit replaces its request. */ + let undone = cached_statics(before_edit); + let m = calculate(~is_edited=true, undone, m); + let current = latest_request(); + let m = update(ack(replaced), m); + let m = update(UpdateResult(replaced.generation, reply(replaced)), m); + let m = + update( + UpdateResult(replaced.generation, ResultFail(ProgramResult.Timeout)), + m, + ); + let m = calculate(~is_edited=false, undone, m); + check(bool, "still pending", true, EvalResult.Model.eval_is_pending(m)); + check_map("its result is ignored", ~expected=native_map(before), m); + let m = update(UpdateResult(current.generation, reply(current)), m); + let m = calculate(~is_edited=false, undone, m); + check_map("the current result", ~expected=native_map(undone), m); +}; + +let tests = ( + "ProofContext", + [ + test_case( + "proofs are checked with the cell's statics", + `Quick, + test_checked_with_statics, + ), + test_case( + "while an edit is evaluated, proofs stay checked against the program before it", + `Quick, + test_pending_keeps_previous_check, + ), + test_case( + "replies to a replaced request are ignored", + `Quick, + test_replaced_request_ignored, + ), + ], +); diff --git a/test/Test_ProofHacks.re b/test/Test_ProofHacks.re deleted file mode 100644 index 72e913ad07..0000000000 --- a/test/Test_ProofHacks.re +++ /dev/null @@ -1,102 +0,0 @@ -/* Tests for the proof helpers in ProofRule and ProofHacks that look through - Parens and Projector wrappers. */ - -open Alcotest; - -let parse_exp = (s: string) => { - switch (Haz3lcore.Parser.to_term(s, ~root=Exp)) { - | Some(e) => e - | None => Alcotest.fail("Failed to parse expression: " ++ s) - }; -}; - -let tests = ( - "ProofHacks", - [ - test_case("Parenthesized forall body is an equality rule", `Quick, () => - List.iter( - ~f= - src => - check( - Alcotest.bool, - src, - true, - switch (Language.ProofRule.exp_to_rule(parse_exp(src))) { - | {conclusion: Equality(_), _} => true - | {conclusion: Other(_), _} => false - }, - ), - [ - "forall n -> n + 0 == n", - "forall n -> (n + 0 == n)", - "(forall n -> (n + 0 == n))", - "^^fold(forall n -> ^^fold(n + 0 == n))", - ], - ) - ), - test_case("exp_to_pat keeps every pattern-like form", `Quick, () => - List.iter( - ~f= - src => { - /* The same text read as a pattern: the parameter of a lambda */ - let pat = - switch (parse_exp("fun " ++ src ++ " -> ?").term) { - | Fun(p, _, _, _) => p - | _ => fail("expected a lambda for: " ++ src) - }; - let converted = Language.ProofHacks.exp_to_pat(parse_exp(src)); - check( - Alcotest.bool, - src - ++ " gives " - ++ Language.Pat.show(converted) - ++ " not " - ++ Language.Pat.show(pat), - true, - Language.Pat.fast_equal(converted, pat), - ); - }, - ["_", "(a=x, _)", "^^fold(x)", "Some((x, _))"], - ) - ), - test_case("Folded sub-pattern yields one inductive hypothesis", `Quick, () => - List.iter( - ~f= - pat_src => { - let src = - "case (? : (rec t -> +Z+S(t))) | " - ++ pat_src - ++ " => 0 | _ => 1 end"; - let exp = parse_exp(src); - let (m, _) = - Language.Statics.mk( - Language.CoreSettings.on, - Language.Builtins.ctx_init(Some(Int)), - exp, - ); - let pat = - switch (exp.term) { - | Match(_, [(p, _), ..._]) => p - | _ => fail("expected a case expression: " ++ src) - }; - let t = - switch ( - Language.Statics.Map.ty_of(Language.Pat.rep_id(pat), m) - ) { - | Some(t) => t - | None => fail("no type for pattern: " ++ src) - }; - check( - Alcotest.int, - pat_src, - 1, - List.length( - Language.ProofHacks.get_inductive_hypotheses(m, t, pat), - ), - ); - }, - ["S(n)", "S((n))", "S(^^fold(n))"], - ) - ), - ], -); diff --git a/test/Test_ProofLayout.re b/test/Test_ProofLayout.re new file mode 100644 index 0000000000..1959c50e2e --- /dev/null +++ b/test/Test_ProofLayout.re @@ -0,0 +1,1248 @@ +open Alcotest; +open Language; +open Test_Evaluator_Prelude; +open Poly; + +/* How theorems and their proofs are laid out: by the pretty printer over a + whole program, and after an edit to a proof, which lays out only that + theorem's proof. */ + +let layout = Test_PrettyPrint.test_format_seg; + +let form_tests = [ + layout( + ~name="a short proof stays on the theorem's line", + ~input="theorem t = 1 == 1 proof step in t", + ~expected={|theorem t = 1 == 1 proof step in +t|}, + (), + ), + layout( + ~name="an unwritten proof stays on the theorem's line", + ~input="theorem t = 1 == 1 proof ? in t", + ~expected={|theorem t = 1 == 1 proof ? in +t|}, + (), + ), + layout( + ~name="several steps go one per line, between `proof` and `in`", + ~input="theorem t = 1 == 1 proof from 1 do step end; step in t", + ~expected={|theorem t = 1 == 1 proof + from 1 do step end; + step +in +t|}, + (), + ), + layout( + ~name="one step too long for the theorem's line goes below it", + ~width=40, + ~input= + "theorem t = f(1) + g(2) == 3 proof from f(1) + g(2) do step end in t", + ~expected= + {|theorem t = f(1) + g(2) == 3 proof + from f(1) + g(2) do step end +in +t|}, + (), + ), + layout( + ~name="a statement too long for its line breaks as a let's would", + ~width=40, + ~input= + "theorem t = some_function(1) + another(2) == the_result(3) proof step in t", + ~expected= + {|theorem t = + some_function(1) + another(2) + == the_result(3) +proof + step +in +t|}, + (), + ), + layout( + ~name= + "a quantified statement keeps its first binder on the theorem's line", + ~width=50, + ~input= + "theorem t = forall x: Int -> forall y: Int -> x + y == y + x proof step in t", + ~expected= + {|theorem t = forall x : Int -> + forall y : Int -> x + y == y + x +proof + step +in +t|}, + (), + ), + layout( + ~name="a focus with several steps is a block", + ~input= + "theorem t = 1 == 1 proof from (2 + 3) * 2 do from 2 + 3 do step end; step end; step in t", + ~expected= + {|theorem t = 1 == 1 proof + from (2 + 3) * 2 do + from 2 + 3 do step end; + step + end; + step +in +t|}, + (), + ), + layout( + ~name="a focus on a metavariable selector", + ~input= + "theorem t = 1 == 1 proof from $e([]) at 2 do step end; from $e(a, h) do step; step end in t", + ~expected= + {|theorem t = 1 == 1 proof + from $e([]) at 2 do step end; + from $e(a, h) do + step; + step + end +in +t|}, + (), + ), + layout( + ~name="a focus with one step too long for its line is a block", + ~width=50, + ~input= + "theorem t = 1 == 1 proof from a_long_function(x, y + 1) do rewrite a_long_lemma with n = f(1, 2) end end in t", + ~expected= + {|theorem t = 1 == 1 proof + from a_long_function(x, y + 1) do + rewrite a_long_lemma with n = f(1, 2) end + end +in +t|}, + (), + ), + layout( + ~name="a wrapping form with a short body stays on one line", + ~input= + "theorem t = forall n: Int -> n == n proof forall n => rewrite refl end in t", + ~expected= + {|theorem t = forall n : Int -> n == n proof forall n => rewrite refl end in +t|}, + (), + ), + layout( + ~name="a wrapping form's steps are indented below it, as a fun's body is", + ~input= + "theorem t = 1 == 1 proof forall n => from n + 0 do algebra n end end; rewrite refl end in t", + ~expected= + {|theorem t = 1 == 1 proof + forall n => + from n + 0 do algebra n end end; + rewrite refl end +in +t|}, + (), + ), + layout( + ~name="a wrapping form after other steps takes the steps after it", + ~input="theorem t = 1 == 1 proof step; forall x => step; step in t", + ~expected= + {|theorem t = 1 == 1 proof + step; + forall x => + step; + step +in +t|}, + (), + ), + layout( + ~name="a wrapping form with an unwritten body leaves it a line", + ~input="theorem t = 1 == 1 proof forall n => ? in t", + ~expected={|theorem t = 1 == 1 proof + forall n => + ? +in +t|}, + (), + ), + layout( + ~name="a have's proof is a block, closed by `=>`", + ~input= + "theorem t = 1 == 1 proof assume h = p => have q proof from q do rewrite h end end; step => rewrite refl end in t", + ~expected= + {|theorem t = 1 == 1 proof + assume h = p => + have q proof + from q do rewrite h end end; + step + => + rewrite refl end +in +t|}, + (), + ), + layout( + ~name="a have with a one-step proof keeps it on its line", + ~input= + "theorem t = 1 == 1 proof have q proof step => step; rewrite refl end in t", + ~expected= + {|theorem t = 1 == 1 proof + have q proof step => + step; + rewrite refl end +in +t|}, + (), + ), + layout( + ~name="induction is laid out as case is", + ~input= + "theorem t = 1 == 1 proof induction xs | [] => step | y :: t => from rev(y :: t) do rewrite rev_cons end end; rewrite refl end end in t", + ~expected= + {|theorem t = 1 == 1 proof + induction xs + | [] => step + | y :: t => + from rev(y :: t) do rewrite rev_cons end end; + rewrite refl end + end +in +t|}, + (), + ), + layout( + ~name="cases with one short case still gives it a line", + ~input="theorem t = 1 == 1 proof cases f(b) | true => step end in t", + ~expected= + {|theorem t = 1 == 1 proof + cases f(b) + | true => step + end +in +t|}, + (), + ), + layout( + ~name="an induction inside a case of another", + ~input= + "theorem t = 1 == 1 proof induction xs | [] => induction ys | [] => step | z :: zs => step; step end | y :: t => step end in t", + ~expected= + {|theorem t = 1 == 1 proof + induction xs + | [] => + induction ys + | [] => step + | z :: zs => + step; + step + end + | y :: t => step + end +in +t|}, + (), + ), + layout( + ~name="a wrapped induction, its cases wrapped in turn", + ~input= + "theorem t = 1 == 1 proof generalize acc => induction xs | [] => forall acc => step; step | y :: t => forall acc => step end in t", + ~expected= + {|theorem t = 1 == 1 proof + generalize acc => + induction xs + | [] => + forall acc => + step; + step + | y :: t => forall acc => step + end +in +t|}, + (), + ), + layout( + ~name="a citation too long for its line breaks before its keywords", + ~width=30, + ~input= + "theorem t = 1 == 1 proof rewrite a_long_lemma_name with n = some_function(1, 2) end in t", + ~expected= + {|theorem t = 1 == 1 proof + rewrite a_long_lemma_name + with n + = some_function(1, 2) + end +in +t|}, + (), + ), + layout( + ~name="a parenthesized proof keeps its `;`", + ~input="theorem t = 1 == 1 proof (forall x => step); step in t", + ~expected={|theorem t = 1 == 1 proof + (forall x => step); + step +in +t|}, + (), + ), + layout( + ~name="a theorem in an indented position", + ~input= + "let f = fun x -> theorem t = 1 == 1 proof from 1 do step end; step in t in f", + ~expected= + {|let f = fun x -> + theorem t = 1 == 1 proof + from 1 do step end; + step + in + t in +f|}, + (), + ), +]; + +/* A hand-formatted program of theorems about lists. It has no `$e` + selectors: the fast parser doesn't read them, and the typing parser + takes seconds on a program this long. */ +let examples = {|let rev = fun xs -> case xs | [] => [] | x :: t => rev(t) @ [x] end in +let total = fun prices -> case prices | [] => 0 | p :: rest => p + total(rest) end in +let add = fun (acc, p) -> acc + p in + +# Warm-ups # +theorem occurrences = (1 + 1) * (1 + 1) == 4 proof + from 1 + 1 at 2 do step end; + from 1 + 1 do step end; + from 2 * 2 do step end; + step +in +theorem nested = (2 + 3) * 2 == 10 proof + from (2 + 3) * 2 do + from 2 + 3 do step end; + step + end; + step +in +theorem algebra = 4 / 2 == 2 proof + from 4 / 2 do algebra 2 end end; + step +in +# Under a binder x is a fixed, arbitrary Int. # +theorem under_fun = (fun x: Int -> x + 0) == (fun x: Int -> x) proof + from x + 0 do algebra x end end; + rewrite refl end +in + +# Lists # +theorem rev_nil = rev([]) == [] proof + from rev([]) do step end; + rewrite refl end +in +theorem rev_cons = forall x: Int -> forall t: [Int] -> rev(x :: t) == rev(t) @ [x] proof + from rev(x :: t) do step end; + rewrite refl end +in +theorem app_cons = forall y: Int -> forall l: [Int] -> forall m: [Int] -> (y :: l) @ m == y :: (l @ m) proof + from (y :: l) @ m do step end; + rewrite refl end +in +theorem snoc = forall xs: [Int] -> forall x: Int -> rev(xs @ [x]) == x :: rev(xs) proof + induction xs + | [] => + from rev([]) do rewrite rev_nil end end; + from rev([] @ [x]) do + from [] @ [x] do step end; + step; + from rev([]) do step end; + step + end; + from x :: [] do step end; + rewrite refl end + | y :: t => + from (y :: t) @ [x] do rewrite app_cons end end; + from rev(y :: (t @ [x])) do rewrite rev_cons end end; + from rev(t @ [x]) do rewrite ih_t end end; + from (x :: rev(t)) @ [y] do rewrite app_cons end end; + from rev(y :: t) do rewrite rev_cons end end; + rewrite refl end + end +in +theorem invol = forall xs: [Int] -> rev(rev(xs)) == xs proof + induction xs + | [] => + from rev([]) do rewrite rev_nil end end; + from rev([]) do rewrite rev_nil end end; + rewrite refl end + | x :: t => + from rev(x :: t) do rewrite rev_cons end end; + from rev(rev(t) @ [x]) do rewrite snoc end end; + from rev(rev(t)) do rewrite ih_t end end; + rewrite refl end + end +in + +# A simple total and a fold-based fast total agree # +theorem total_nil = total([]) == 0 proof + from total([]) do step end; + rewrite refl end +in +theorem total_cons = forall p: Int -> forall rest: [Int] -> total(p :: rest) == p + total(rest) proof + from total(p :: rest) do step end; + rewrite refl end +in +theorem fold_nil = forall a: Int -> fold_left([], add, a) == a proof + from fold_left([], add, a) do step end; + rewrite refl end +in +theorem fold_cons = forall h: Int -> forall t: [Int] -> forall a: Int -> fold_left(h :: t, add, a) == fold_left(t, add, a + h) proof + from fold_left(h :: t, add, a) do step; from add(a, h) do step end; step end; + from fold_left(t, add, a + h) do step end; + rewrite refl end +in +theorem shuffle = forall a: Int -> forall b: Int -> forall c: Int -> a + (b + c) == (a + b) + c proof + from a + (b + c) do algebra (a + b) + c end end; + rewrite refl end +in +theorem total_acc = forall prices: [Int] -> forall acc: Int -> acc + total(prices) == fold_left(prices, add, acc) proof + generalize acc => induction prices + | [] => forall acc => + from total([]) do rewrite total_nil end end; + from fold_left([], add, acc) do rewrite fold_nil end end; + from acc + 0 do algebra acc end end; + rewrite refl end + | p :: rest => forall acc => + from total(p :: rest) do rewrite total_cons end end; + from fold_left(p :: rest, add, acc) do rewrite fold_cons end end; + from acc + (p + total(rest)) do rewrite shuffle end end; + from fold_left(rest, add, acc + p) do rewrite <- ih_rest end end; + rewrite refl end + end +in +theorem totals_agree = forall prices: [Int] -> total(prices) == fold_left(prices, add, 0) proof + from fold_left(prices, add, 0) do rewrite <- total_acc end end; + from 0 + total(prices) do algebra total(prices) end end; + rewrite refl end +in + +# To try: # +theorem app_assoc = forall xs: [Int] -> forall ys: [Int] -> forall zs: [Int] -> (xs @ ys) @ zs == xs @ (ys @ zs) proof + induction xs + | [] => ? + | x :: t => ? + end +in +0|}; + +/* The theorems of `examples` whose proofs are written as the pretty printer + lays them out. */ +let canonical_theorems = [ + "occurrences", + "nested", + "algebra", + "under_fun", + "rev_nil", + "rev_cons", + "app_cons", + "snoc", + "invol", + "total_nil", + "total_cons", + "fold_nil", + "shuffle", + "totals_agree", + "app_assoc", +]; + +let fold_cons_proof = {|proof + from fold_left(h :: t, add, a) do + step; + from add(a, h) do step end; + step + end; + from fold_left(t, add, a + h) do step end; + rewrite refl end +in|}; + +let total_acc_proof = {|proof + generalize acc => + induction prices + | [] => + forall acc => + from total([]) do rewrite total_nil end end; + from fold_left([], add, acc) do rewrite fold_nil end end; + from acc + 0 do algebra acc end end; + rewrite refl end + | p :: rest => + forall acc => + from total(p :: rest) do rewrite total_cons end end; + from fold_left(p :: rest, add, acc) do rewrite fold_cons end end; + from acc + (p + total(rest)) do rewrite shuffle end end; + from fold_left(rest, add, acc + p) do rewrite <- ih_rest end end; + rewrite refl end + end +in|}; + +let check_contains = Test_EditorTransform.check_contains; + +/* Parses as the editor does when it loads text, which takes a fraction of + the time that typing the examples in does. */ +let parse_zipper = (text: string): Haz3lcore.Zipper.t => + switch ( + Haz3lcore.PersistentZipper.parse_text(~source="test", ~root=Exp, text) + ) { + | Some(z) => z + | None => Alcotest.fail("Failed to parse: " ++ text) + }; + +let examples_zipper = lazy(parse_zipper(examples)); + +let format = (z: Haz3lcore.Zipper.t): string => + Haz3lcore.Zipper.unselect_and_zip(z) + |> Haz3lcore.PrettySegment.prettify + |> Haz3lcore.Printer.of_segment(~holes="?"); + +let formatted_examples = lazy(format(Lazy.force(examples_zipper))); + +let examples_tests = [ + test_case( + "formatting the examples twice changes nothing", + `Quick, + () => { + let once = Lazy.force(formatted_examples); + check(string, "idempotent", once, format(parse_zipper(once))); + }, + ), + test_case("the formatted examples parse to the same program", `Quick, () => + check( + dhexp_typ, + "same term", + Test_EditorTransform.zipper_term(Lazy.force(examples_zipper)), + Test_EditorTransform.zipper_term( + parse_zipper(Lazy.force(formatted_examples)), + ), + ) + ), + test_case( + "the examples' proofs, formatted", + `Quick, + () => { + let formatted = Lazy.force(formatted_examples); + /* A statement that fits its line leaves the proof as it was written. */ + check_contains( + ~msg="nested", + formatted, + {|theorem nested = (2 + 3) * 2 == 10 proof + from (2 + 3) * 2 do + from 2 + 3 do step end; + step + end; + step +in|}, + ); + check_contains( + ~msg="snoc", + formatted, + {|theorem snoc = forall xs : [Int] -> + forall x : Int -> rev(xs @ [x]) == x :: rev(xs) +proof + induction xs + | [] => + from rev([]) do rewrite rev_nil end end; + from rev([] @ [x]) do + from [] @ [x] do step end; + step; + from rev([]) do step end; + step + end; + from x :: [] do step end; + rewrite refl end + | y :: t => + from (y :: t) @ [x] do rewrite app_cons end end; + from rev(y :: (t @ [x])) do rewrite rev_cons end end; + from rev(t @ [x]) do rewrite ih_t end end; + from (x :: rev(t)) @ [y] do rewrite app_cons end end; + from rev(y :: t) do rewrite rev_cons end end; + rewrite refl end + end +in|}, + ); + check_contains(~msg="fold_cons", formatted, fold_cons_proof); + check_contains(~msg="total_acc", formatted, total_acc_proof); + check_contains( + ~msg="app_assoc", + formatted, + {|proof + induction xs + | [] => ? + | x :: t => ? + end +in +0|}, + ); + }, + ), +]; + +// Edits + +module Edit = { + let zipper_term = Test_EditorTransform.zipper_term; + let serialize = Test_EditorTransform.serialize; + + /* The proof of the theorem named `name`. */ + let proof_of = (name: string, e: Exp.t): Proof.t => { + let found = ref(None); + let f_exp = (continue, e: Exp.t): Exp.t => { + switch (e.term) { + | Theorem({term: Var(x), _}, _, proof, _) when x == name => + found := Some(proof) + | _ => () + }; + continue(e); + }; + let _ = TermBase.Exp.map_term(~f_exp, e); + switch (found^) { + | Some(proof) => proof + | None => Alcotest.fail("no theorem named " ++ name) + }; + }; + + let rec last_step = (p: Proof.t): Proof.t => + switch (p.term) { + | Seq(_, rest) => last_step(rest) + | _ => p + }; + + /* The last step of the `i`th case of a split. */ + let last_of_case = (i: int, p: Proof.t): Proof.t => + switch (p.term) { + | Cases(_, cases) + | Induction(_, cases) => last_step(snd(List.nth_exn(cases, i))) + | _ => Alcotest.fail("not a split") + }; + + /* Replaces the node `target` picks from the proof of `name`. */ + let patch = + ( + ~target: Proof.t => Proof.t=p => p, + ~replacement: Proof.t => Proof.t, + name: string, + z: Haz3lcore.Zipper.t, + ) + : Haz3lcore.Zipper.t => { + let target = target(proof_of(name, zipper_term(z))); + Haz3lcore.EditorTransform.apply_patch( + z, + Haz3lcore.EditorTransform.mk_proof_patch( + ~target_id=Proof.rep_id(target), + replacement(target), + ), + ); + }; + + /* What the stepper does to take a step at the end of a proof. */ + let add_step = (step: Proof.t) => + patch(~target=last_step, ~replacement=last => + Proof.fresh(Seq(last, step)) + ); + + let eval_step = () => Proof.fresh(EvalStep); + + /* `text` with the first `before` replaced by `after`. */ + let replace_first = (~before: string, ~after: string, text: string) => + Str.replace_first(Str.regexp_string(before), after, text); + + let tests = [ + test_case( + "laying out a proof that is already laid out changes nothing", + `Quick, + () => { + let z = Lazy.force(examples_zipper); + List.iter( + ~f= + name => + check( + string, + name, + serialize(z), + serialize(patch(~replacement=p => p, name, z)), + ), + canonical_theorems, + ); + }, + ), + test_case( + "an edit that changes nothing keeps the proof's hand layout", + `Quick, + () => { + /* The examples write fold_cons's first focus on one line, where + the printer would make it a block. */ + let z = Lazy.force(examples_zipper); + check( + string, + "fold_cons", + serialize(z), + serialize(patch(~replacement=p => p, "fold_cons", z)), + ); + }, + ), + test_case( + "a step added to a proof of several adds one line", + `Quick, + () => { + let z = Lazy.force(examples_zipper); + check( + string, + "occurrences", + replace_first( + ~before=" from 2 * 2 do step end;\n step\nin", + ~after=" from 2 * 2 do step end;\n step;\n step\nin", + serialize(z), + ), + serialize(add_step(eval_step(), "occurrences", z)), + ); + }, + ), + test_case( + "a step added inside an induction's case adds one line", + `Quick, + () => { + let z = Lazy.force(examples_zipper); + check( + string, + "invol", + replace_first( + ~before=" rewrite refl end\n | x :: t =>", + ~after=" rewrite refl end;\n step\n | x :: t =>", + serialize(z), + ), + serialize( + patch( + ~target=last_of_case(0), + ~replacement=last => Proof.fresh(Seq(last, eval_step())), + "invol", + z, + ), + ), + ); + }, + ), + test_case( + "a removed step takes its line with it", + `Quick, + () => { + let z = Lazy.force(examples_zipper); + let step = last_of_case(1, proof_of("snoc", zipper_term(z))); + check( + string, + "snoc", + replace_first( + ~before= + " from rev(y :: t) do rewrite rev_cons end end;\n rewrite refl end\n end", + ~after=" from rev(y :: t) do rewrite rev_cons end end\n end", + serialize(z), + ), + serialize( + Haz3lcore.EditorTransform.apply_patch( + z, + Haz3lcore.EditorTransform.mk_proof_remove_patch( + ~target_id=Proof.rep_id(step), + ), + ), + ), + ); + }, + ), + test_case( + "a first step stays on the theorem's line, a second makes a block", + `Quick, + () => { + let z = parse_zipper("theorem t = 1 == 1 proof ? in t"); + let z = patch(~replacement=_ => eval_step(), "t", z); + check( + string, + "one step", + "theorem t = 1 == 1 proof step in t", + serialize(z), + ); + let z = add_step(eval_step(), "t", z); + check( + string, + "two steps", + "theorem t = 1 == 1 proof\n step;\n step\nin t", + serialize(z), + ); + }, + ), + test_case( + "a proof is indented from where its theorem sits", + `Quick, + () => { + let z = + parse_zipper( + "let f = fun x ->\n theorem t = 1 == 1 proof step in\n t\nin f", + ); + check( + string, + "nested theorem", + "let f = fun x ->\n theorem t = 1 == 1 proof\n step;\n step\n in\n t\nin f", + serialize(add_step(eval_step(), "t", z)), + ); + }, + ), + ]; +}; + +/* What each stepper write leaves of the text the user wrote: comments + and hand layout around and inside the edited steps stay, and only the + new text is laid out. Each test checks the whole text after the write, + that every comment survives, and that the text parses to the program + the write makes. */ +module KeepText = { + module Patches = Web.StepperPicker.Patches; + module Terms = Web.StepperPicker.Terms; + module Exits = Web.Obligations.Exits; + module Rewrite = Haz3lcore.EditorTransform.Rewrite; + let serialize = Edit.serialize; + let zipper_term = Edit.zipper_term; + + let program = {|# about t # +theorem t = forall xs: [Int] -> rev(rev(xs)) == xs proof + # first # + induction xs # scrut # + | [] => + from rev([]) do rewrite rev_nil end end; # base one # + from rev([]) do rewrite rev_nil end end; rewrite refl end + | x :: t => + # step # + from rev(x :: t) do rewrite rev_cons end end; + from rev(rev(t)) do + rewrite ih_t end; # in focus # + step + end; + rewrite refl end # last # + end +in t|}; + + let rec steps = (p: Proof.t): list(Proof.t) => + switch (p.term) { + | Seq(a, b) => steps(a) @ steps(b) + | _ => [p] + }; + + let induction = (z): Proof.t => Edit.proof_of("t", zipper_term(z)); + + /* The steps of the induction's `i`th case. */ + let case = (i: int, z): list(Proof.t) => + switch (induction(z).term) { + | Cases(_, cases) + | Induction(_, cases) => steps(snd(List.nth_exn(cases, i))) + | _ => Alcotest.fail("not a split") + }; + + let row = (kind: Web.StepperRows.kind, step: Proof.t): Web.StepperRows.t => { + key: (Proof.rep_id(step), kind == End ? Outgoing : Incoming), + step, + kind, + entry: None, + goal: None, + acts_on: None, + continues: true, + }; + + let comments = (text: string): list(string) => { + let rec from = pos => + switch (Stdlib.String.index_from_opt(text, pos, '#')) { + | None => [] + | Some(start) => + switch (Stdlib.String.index_from_opt(text, start + 1, '#')) { + | None => [] + | Some(stop) => [ + String.sub(text, ~pos=start, ~len=stop - start + 1), + ...from(stop + 1), + ] + } + }; + from(0) |> List.sort(~compare); + }; + + /* The program the patch makes, printed fresh and parsed back. */ + let patched = (z, patch: Haz3lcore.EditorTransform.patch): Exp.t => { + let root = zipper_term(z); + let proof = (target_id, replacement) => + Rewrite.proof_in_exp(~target_id, replacement, root); + let new_root = + switch (patch) { + | ExpPatch({target_id, replacement, _}) => + Rewrite.exp(~target_id, replacement, root) |> Option.map(~f=snd) + | ProofPatch({target_id, replacement, _}) => + proof(target_id, replacement) |> Option.map(~f=snd) + | ProofRemovePatch({target_id}) => + let (target_id, replacement) = + Rewrite.step_removal( + ~target_id, + Rewrite.seq_parent_in_exp(~target_id, root), + ); + proof(target_id, replacement) |> Option.map(~f=snd); + }; + switch (new_root) { + | Some(e) => + e + |> Haz3lcore.ExpToSegment.exp_to_segment( + ~settings=Haz3lcore.ExpToSegment.Settings.editable(~inline=true), + ) + |> Haz3lcore.Printer.of_segment(~holes="?", ~refractors=[]) + |> parse_exp + | None => Alcotest.fail("the patch's target isn't in the program") + }; + }; + + let check_write = + ( + ~src=program, + ~lost: list(string)=[], + ~expected: string, + patch: Haz3lcore.Zipper.t => Haz3lcore.EditorTransform.patch, + ) => { + let z = parse_zipper(src); + let patch = patch(z); + let out = serialize(Haz3lcore.EditorTransform.apply_patch(z, patch)); + check(string, "text", expected, out); + check( + list(string), + "comments", + List.filter( + ~f=c => !List.mem(lost, c, ~equal=String.equal), + comments(src), + ), + comments(out), + ); + check( + bool, + "parses to the patched program", + true, + Exp.fast_equal(patched(z, patch), parse_exp(out)), + ); + }; + + let eval = () => Proof.fresh(EvalStep); + + let tests = [ + test_case("Enter after a case's last step adds one line", `Quick, () => + check_write( + ~expected= + Edit.replace_first( + ~before=" rewrite refl end\n", + ~after=" rewrite refl end;\n step\n", + program, + ), + z => + Patches.write(row(End, Util.ListUtil.last(case(0, z))), eval()) + ) + ), + test_case( + "Enter after a line ending in a comment leaves the comment there", + `Quick, + () => + check_write( + ~expected= + Edit.replace_first( + ~before="rewrite refl end # last #\n", + ~after="rewrite refl end; # last #\n step\n", + program, + ), + z => + Patches.write(row(End, Util.ListUtil.last(case(1, z))), eval()) + ) + ), + test_case("Tab before a step adds one line above it", `Quick, () => + check_write( + ~expected= + Edit.replace_first( + ~before=" from rev(rev(t)) do\n", + ~after=" step;\n from rev(rev(t)) do\n", + program, + ), + z => + Patches.write( + row(Step(Leaf), List.nth_exn(case(1, z), 1)), + eval(), + ) + ) + ), + test_case("a step joined to a focus's steps adds one line", `Quick, () => + check_write( + ~expected= + Edit.replace_first( + ~before=" step\n end;", + ~after=" step;\n step\n end;", + program, + ), + z => + switch (List.nth_exn(case(1, z), 1).term) { + | Focus({body, _}) => Patches.join(body, eval()) + | _ => Alcotest.fail("not a focus") + } + ) + ), + test_case( + "a strategy's wrapping form goes in above the step and its comment", + `Quick, + () => + check_write( + ~expected= + Edit.replace_first( + ~before=" | x :: t =>\n", + ~after= + " | x :: t =>\n (\n generalize t =>\n ?\n );\n", + program, + ), + z => + Patches.write( + row(Step(Leaf), List.hd_exn(case(1, z))), + Proof.fresh(Terms.generalize(~exp=Exp.fresh(Var("t")))), + ) + ) + ), + test_case("removing a step removes it and its `;` only", `Quick, () => + check_write( + ~expected= + Edit.replace_first( + ~before= + "\n from rev([]) do rewrite rev_nil end end; rewrite", + ~after="\n rewrite", + program, + ), + z => + Patches.remove(List.nth_exn(case(0, z), 1)) + ) + ), + test_case("removing a chain's last step removes its `;`", `Quick, () => + check_write( + ~expected= + Edit.replace_first( + ~before=" end;\n rewrite refl end # last #\n", + ~after=" end # last #\n", + program, + ), + z => + Patches.remove(Util.ListUtil.last(case(1, z))) + ) + ), + test_case("Case adds a case and keeps the others as written", `Quick, () => + check_write( + ~expected= + Edit.replace_first( + ~before=" # last #\n end", + ~after=" # last #\n | ? => ?\n end", + program, + ), + z => + switch ( + Patches.add_case( + induction(z), + ~marks=[Language.ProofMark.InductionNotExhaustive], + ) + ) { + | Some(patch) => patch + | None => Alcotest.fail("no case to add") + } + ) + ), + test_case( + "a strategy written in place of a hole keeps the text around it", + `Quick, + () => + check_write( + ~src="theorem t = 1 == 1 proof # todo #\n ?\nin t", + ~expected= + "theorem t = 1 == 1 proof # todo #\n induction ? end\nin t", + z => + Patches.write( + row(Hole, Edit.proof_of("t", zipper_term(z))), + Proof.fresh(Terms.induction(~exp=Exp.fresh(EmptyHole))), + ) + ) + ), + test_case("a second step turns a one-line proof into a block", `Quick, () => + check_write( + ~src="theorem t = 1 == 1 proof step # done # in t", + ~expected="theorem t = 1 == 1 proof\n step;\n step # done #\nin t", + z => + Patches.write(row(End, Edit.proof_of("t", zipper_term(z))), eval()) + ) + ), + test_case("Tab keeps steps the user put on one line", `Quick, () => + check_write( + ~src= + "theorem t = (1 + 1) * (1 + 1) == 4 proof\n from 1 + 1 at 2 do step end; from 1 + 1 do step end;\n step\nin t", + ~expected= + "theorem t = (1 + 1) * (1 + 1) == 4 proof\n from 1 + 1 at 2 do step end; from 1 + 1 do step end;\n step;\n step\nin t", + z => + Patches.write( + row(End, Edit.last_step(Edit.proof_of("t", zipper_term(z)))), + eval(), + ) + ) + ), + test_case( + "flipping an axiom's direction rewrites only its keyword", `Quick, () => + check_write( + ~src="theorem t = 1 == 1 proof\n rewrite # which # refl end\nin t", + ~expected= + "theorem t = 1 == 1 proof\n rewrite <- # which # refl end\nin t", + z => { + let step = Edit.proof_of("t", zipper_term(z)); + switch (step.term) { + | AxiomStep(a) => + Haz3lcore.EditorTransform.mk_proof_patch( + ~target_id=Proof.rep_id(step), + { + ...step, + term: + AxiomStep({ + ...a, + direction: Util.Direction.toggle(a.direction), + }), + }, + ) + | _ => Alcotest.fail("not an axiom step") + }; + }, + ) + ), + test_case("a rebuilt node keeps its steps' literal spellings", `Quick, () => + check_write( + ~src= + "theorem t = forall b: Bool -> 1 == 1 proof\n induction b\n | true => from 007 + 1 do step end\n end\nin t", + ~expected= + "theorem t = forall b: Bool -> 1 == 1 proof\n induction b\n | true => from 007 + 1 do step end\n | ? => ?\n end\nin t", + z => + switch ( + Patches.add_case( + Edit.proof_of("t", zipper_term(z)), + ~marks=[Language.ProofMark.InductionNotExhaustive], + ) + ) { + | Some(patch) => patch + | None => Alcotest.fail("no case to add") + } + ) + ), + test_case( + "the caret stays by the text it was at", + `Quick, + () => { + let with_caret = (z: Haz3lcore.Zipper.t) => + Haz3lcore.Printer.of_zipper(~holes="?", ~caret="¦", z); + let at = (step: Proof.t, z) => + switch ( + Haz3lcore.Move.jump_to_side_of_id(Left, z, Proof.rep_id(step)) + ) { + | Some(z) => z + | None => Alcotest.fail("can't put the caret at the step") + }; + let write = z => + Haz3lcore.EditorTransform.apply_patch( + z, + Patches.write( + row(End, Util.ListUtil.last(case(0, z))), + eval(), + ), + ); + let z = parse_zipper(program); + let edited = Util.ListUtil.last(case(0, z)); + let later = List.nth_exn(case(1, z), 1); + List.iter( + ~f= + ((name, step, before)) => + check_contains( + ~msg=name, + with_caret(write(at(step, z))), + "¦" ++ before, + ), + [ + ( + "at the step written after", + edited, + "rewrite refl end;\n step", + ), + ("at a later step", later, "from rev(rev(t)) do"), + ], + ); + }, + ), + ]; + + // Side-condition exits + + module ET = Test_EditorTransform; + + let exits_program = {|let f = fun n -> + # the body # + 8 / n +in +theorem t = forall n: Int -> # any n # + 8 / n == 8 / n proof + # first # + from 8 / n do step end; # one # + step +in t|}; + + let first_eval_origin = z => + switch (ET.find_proofs(ET.is_eval_step, ET.exits_ctx_of(z).proof)) { + | [first, ..._] => Proof.rep_id(first) + | [] => Alcotest.fail("no eval steps") + }; + + let exit_tests = [ + test_case("the have exit wraps the steps and keeps their text", `Quick, () => + check_write( + ~src=exits_program, + ~expected= + Edit.replace_first( + ~before= + "proof\n # first #\n from 8 / n do step end; # one #\n step\n", + ~after= + "proof\n have n != 0 proof ? =>\n # first #\n from 8 / n do step end; # one #\n step\n", + exits_program, + ), + z => + ET.require_patch( + "have", + Exits.have_patch( + ~ctx=ET.exits_ctx_of(z), + ET.mk_obligation(~origin=first_eval_origin(z), ~goal="n != 0"), + ), + ) + ) + ), + test_case( + "the split exit wraps the steps and keeps their text", `Quick, () => + check_write( + ~src=exits_program, + ~expected= + Edit.replace_first( + ~before=" from 8 / n do step end; # one #\n step\n", + ~after= + " cases n != 0\n | true =>\n from 8 / n do step end; # one #\n step\n | false => ?\n end\n", + exits_program, + ), + z => + ET.require_patch( + "split", + Exits.split_patch( + ~ctx=ET.exits_ctx_of(z), + ET.mk_obligation(~origin=first_eval_origin(z), ~goal="n != 0"), + ), + ) + ) + ), + ]; +}; + +let tests = [ + ("ProofLayout.Forms", form_tests), + ("ProofLayout.Examples", examples_tests), + ("ProofLayout.Edits", Edit.tests), + ("ProofLayout.KeepText", KeepText.tests @ KeepText.exit_tests), +]; diff --git a/test/Test_ProofRuleMentions.re b/test/Test_ProofRuleMentions.re new file mode 100644 index 0000000000..04e95f58a3 --- /dev/null +++ b/test/Test_ProofRuleMentions.re @@ -0,0 +1,104 @@ +open Alcotest; + +/* `ProofRule.mentions_any` answers "does this fact mention x free?" for the + * prover's capture tests (`ProofCtx.of_theorem_ctx`'s `is_captured`, + * `ProofCheck`'s generalize). It walks the rule directly rather than + * running statics on it, which overflows a browser worker's stack on + * docs/stlc-progress-example.hazel (see `test/run_node.sh` for why the + * suite doesn't see stack limits). + * + * These pin occurrence, shadowing by every binding form the walk + * special-cases, and the reach into assumptions and into expressions + * nested under types. */ + +let parse_exp = (s: string) => + switch (Haz3lcore.Parser.to_term(s, ~root=Exp)) { + | Some(e) => e + | None => Alcotest.fail("Failed to parse expression: " ++ s) + }; + +let mentions = (name: string, src: string): bool => + Language.ProofRule.mentions_any( + Language.ProofRule.exp_to_rule(parse_exp(src)), + [name], + ); + +let check_mentions = (~expected: bool, name, src, ()) => + check( + bool, + (expected ? "mentions " : "does not mention ") ++ name ++ ": " ++ src, + expected, + mentions(name, src), + ); + +let tests = [ + ( + "ProofRule.mentions_any", + [ + test_case( + "free occurrence in the conclusion", + `Quick, + check_mentions(~expected=true, "x", "x == 1"), + ), + test_case( + "absent name", + `Quick, + check_mentions(~expected=false, "y", "x == 1"), + ), + test_case( + "free occurrence in an assumption", + `Quick, + check_mentions(~expected=true, "x", "x == 1 ==> 2 == 2"), + ), + test_case( + "the rule's own forall binder is not a mention", + `Quick, + check_mentions(~expected=false, "x", "forall x: Int -> x == 1"), + ), + test_case( + "a rule binder shadows only itself", + `Quick, + check_mentions(~expected=true, "y", "forall x: Int -> x == y"), + ), + test_case( + "shadowed by an inner fun binder", + `Quick, + check_mentions(~expected=false, "x", "(fun x -> x)(1) == 1"), + ), + test_case( + "free under an inner fun binder", + `Quick, + check_mentions(~expected=true, "x", "(fun y -> x)(1) == 1"), + ), + test_case( + "shadowed by an inner let binder", + `Quick, + check_mentions(~expected=false, "x", "(let x = 1 in x) == 1"), + ), + test_case( + "free in an inner let's body", + `Quick, + check_mentions(~expected=true, "x", "(let y = 1 in x) == 1"), + ), + test_case( + "shadowed by a case branch's pattern", + `Quick, + check_mentions(~expected=false, "x", "(case 1 | x => x end) == 1"), + ), + test_case( + "free in a case scrutinee that a branch shadows", + `Quick, + check_mentions(~expected=true, "x", "(case x | x => x end) == 1"), + ), + test_case( + "shadowed by an inner forall", + `Quick, + check_mentions( + ~expected=false, + "x", + "(forall x: Int -> x == 1) == true", + ), + ), + ], + ), +]; diff --git a/test/Test_StepperPasses.re b/test/Test_StepperPasses.re deleted file mode 100644 index 04741cb1b2..0000000000 --- a/test/Test_StepperPasses.re +++ /dev/null @@ -1,72 +0,0 @@ -open Alcotest; -open Haz3lcore; - -/* A pass over a stepper (every click makes one) re-analyzes only the steps - that changed: the first step's analysis survives a second step and a - selection */ - -let elab = (s: string): Language.Exp.t => - switch (Parser.to_term(s, ~root=Language.Sort.Exp)) { - | Some(u) => - let (_, elab) = - Language.Statics.mk( - Language.CoreSettings.on, - Language.Builtins.ctx_init(Some(Int)), - u, - ); - elab; - | None => Alcotest.fail("could not parse: " ++ s) - }; - -let ctx = - Language.SemanticCtx.of_ctx_and_env( - Language.Builtins.ctx_init(None), - Language.Builtins.closure_env, - ); - -/* the analysis itself: a pass rebuilds the record around it (targets) */ -let first_info_map = (m: Web.StepperView.Model.t) => - Util.Calc.get_saved_exc(~print="first step", m.root.editor).statics. - info_map; - -let passes = () => { - let e = elab("(1 + 2) + (3 + 4)"); - let calc = (exp, m) => - Web.StepperView.Update.calculate( - ~settings=Util.Calc.OldValue(Language.CoreSettings.on), - ~ctx=Util.Calc.OldValue(ctx), - exp, - m, - ); - let step = (a, m) => - calc( - Util.Calc.OldValue(e), - Web.StepperView.Update.update(~settings=Web.Settings.Model.init, a, m). - model, - ); - /* the first steps are taken automatically (hidden), so a click lands at - the end of the trace */ - let take = (m: Web.StepperView.Model.t) => { - let rec at_end = - (s: Web.StepperBase.step_model): Web.StepperBase.step_action => - switch (s.next_step) { - | Some(n) => NextStep(at_end(n)) - | None => StepForward(0) - }; - step(at_end(m.root), m); - }; - let one = take(calc(Util.Calc.NewValue(e), Web.StepperView.Model.init)); - let before = first_info_map(one); - let again = step(EditorAction(Select(All)), take(one)); - check( - bool, - "the first step's analysis kept", - true, - phys_equal(before, first_info_map(again)), - ); -}; - -let tests = ( - "StepperPasses", - [test_case("passes are incremental", `Quick, passes)], -); diff --git a/test/Test_SubEditor.re b/test/Test_SubEditor.re new file mode 100644 index 0000000000..d30664b7fe --- /dev/null +++ b/test/Test_SubEditor.re @@ -0,0 +1,533 @@ +/** + * Tests for SubEditor.Target resolution, separator trimming, and + * update-time confinement. Locators are structural (host tile id + + * path) so they survive inner term-id churn. + */ +open Alcotest; +open Haz3lcore; +open Language; +open Action; +open Poly; + +module SubEditor = Web.SubEditor; +module Target = SubEditor.Target; + +let seg_string = (seg: Segment.t): string => + Segment.to_string( + seg, + ~projector_to_segment=_ => [], + ~refractor_seg_to_seg=(r, s) => (r, s), + ); + +let check_seg = (msg, expected: string, actual: option(Segment.t)) => + switch (actual) { + | None => fail(msg ++ ": resolve returned None") + | Some(seg) => check(string, msg, expected, seg_string(seg)) + }; + +let mk_tile = + (~id=Id.mk(), label: Label.t, children: list(Segment.t)): Base.tile => { + let (form, sort) = Form.classify_label(Sort.Exp, label); + { + id, + form, + sort, + shards: List.init(List.length(label), ~f=i => i), + children, + }; +}; + +let tile = (~id=?, label, children): Piece.t => + Piece.Tile(mk_tile(~id?, label, children)); + +let atom = (~id=?, name: string): Piece.t => tile(~id?, [name], []); + +let space = (): Piece.t => + Piece.Secondary(Haz3lcore.Secondary.mk_space(Id.mk())); + +let linebreak = (): Piece.t => + Piece.Secondary(Haz3lcore.Secondary.mk_newline(Id.mk())); + +/* Synthetic host shaped like `case x | A => 1 | B => 2 end`. + * Rule tiles only contain the pattern child; the body is a sibling + * (mirrors Form.Rule). A parenthesized nested `| =>` must not affect + * direct selectors. */ +let mk_host = () => { + let host_id = Id.mk(); + let scrut_id = Id.mk(); + let nested_rule = tile(["|", "=>"], [[atom("nested")]]); + let child = [ + atom(~id=scrut_id, "x"), + space(), + tile(["(", ")"], [[nested_rule, atom("0")]]), + space(), + tile(["|", "=>"], [[atom("A")]]), + atom("1"), + space(), + tile(["|", "=>"], [[atom("B")]]), + atom("2"), + ]; + let host = mk_tile(~id=host_id, ["case", "end"], [child]); + (host_id, scrut_id, [Piece.Tile(host)]); +}; + +let rule = ["|", "=>"]; + +let scrut_target = (anchor: Id.t): Target.t => + Target.child(~anchor, 0) + |> Target.until(Target.Before(Target.NthTile(rule, 0))); + +let pattern_target = (anchor: Id.t, i: int): Target.t => + Target.child(~anchor, 0) + |> Target.descend(Target.NthTile(rule, i), ~child=0); + +let between_rules_target = (anchor: Id.t): Target.t => + Target.child(~anchor, 0) + |> Target.from(Target.After(Target.NthTile(rule, 0))) + |> Target.until(Target.Before(Target.NthTile(rule, 1))); + +/* --- Resolve --- */ + +let test_whole_child = () => { + let (host_id, _, root) = mk_host(); + let target = Target.child(~anchor=host_id, 0); + check_seg( + "whole child", + "x (|nested=>0) |A=>1 |B=>2", + Target.resolve(target, root), + ); +}; + +let test_prefix_until_first_rule = () => { + let (host_id, _, root) = mk_host(); + check_seg( + "scrut prefix", + "x (|nested=>0) ", + Target.resolve(scrut_target(host_id), root), + ); +}; + +let test_nth_rule_pattern = () => { + let (host_id, _, root) = mk_host(); + check_seg( + "first rule pattern", + "A", + Target.resolve(pattern_target(host_id, 0), root), + ); + check_seg( + "second rule pattern", + "B", + Target.resolve(pattern_target(host_id, 1), root), + ); +}; + +let test_between_bounds = () => { + let (host_id, _, root) = mk_host(); + check_seg( + "between rules", + "1 ", + Target.resolve(between_rules_target(host_id), root), + ); +}; + +let test_nested_label_ignored = () => { + /* Direct NthTile(rule, 0) must pick the outer `|A=>`, not the nested + * `|nested=>` inside parentheses. */ + let (host_id, _, root) = mk_host(); + check_seg( + "direct first rule pattern", + "A", + Target.resolve(pattern_target(host_id, 0), root), + ); +}; + +let test_missing_returns_none = () => { + let (host_id, _, root) = mk_host(); + check( + bool, + "bad anchor", + true, + Target.resolve(Target.child(~anchor=Id.mk(), 0), root) == None, + ); + check( + bool, + "bad child index", + true, + Target.resolve(Target.child(~anchor=host_id, 9), root) == None, + ); + check( + bool, + "missing selector", + true, + Target.resolve( + Target.child(~anchor=host_id, 0) + |> Target.until(Target.Before(Target.NthTile(rule, 9))), + root, + ) + == None, + ); + check( + bool, + "reversed bounds", + true, + Target.resolve( + Target.child(~anchor=host_id, 0) + |> Target.from(Target.Before(Target.NthTile(rule, 1))) + |> Target.until(Target.Before(Target.NthTile(rule, 0))), + root, + ) + == None, + ); +}; + +let test_before_or_end_falls_back = () => { + /* BeforeOrEnd bounds a scrut-style prefix even when no rule tile + * exists yet (induction with zero cases): it falls back to the + * segment end instead of failing to resolve. */ + let scrut_target' = (anchor: Id.t): Target.t => + Target.child(~anchor, 0) + |> Target.until(Target.BeforeOrEnd(Target.NthTile(rule, 0))); + /* With rules present: identical to Before. */ + let (host_id, _, root) = mk_host(); + check_seg( + "with rules, same as Before", + "x (|nested=>0) ", + Target.resolve(scrut_target'(host_id), root), + ); + /* With no rules: spans the whole child. */ + let host_id = Id.mk(); + let root = [ + Piece.Tile( + mk_tile( + ~id=host_id, + ["induction", "end"], + [[space(), atom("x"), space()]], + ), + ), + ]; + check_seg( + "no rules, whole child", + " x ", + Target.resolve(scrut_target'(host_id), root), + ); + check( + bool, + "plain Before still fails with no rules", + true, + Target.resolve(scrut_target(host_id), root) == None, + ); +}; + +let test_stable_under_inner_id_churn = () => { + let (host_id, scrut_id, root) = mk_host(); + let target = scrut_target(host_id); + let before = Target.resolve(target, root); + /* Replace the scrutinee tile's id (and content) while keeping the host. */ + let root' = + switch (root) { + | [Piece.Tile(host)] => + let child = + switch (host.children) { + | [seg] => + List.map( + ~f= + (p: Piece.t) => + switch (p) { + | Piece.Tile(t) when t.id == scrut_id => + atom(~id=Id.mk(), "yz") + | p => p + }, + seg, + ) + | _ => fail("expected one child") + }; + [ + Piece.Tile({ + ...host, + children: [child], + }), + ]; + | _ => fail("expected host tile") + }; + check_seg("before churn", "x (|nested=>0) ", before); + check_seg( + "after churn, same target", + "yz (|nested=>0) ", + Target.resolve(target, root'), + ); +}; + +/* --- Trim --- */ + +let test_trim_one_space_each_end = () => { + let seg = [space(), atom("x"), space(), atom("y"), space()]; + let trimmed = SubEditor.trim_separators(seg); + check(string, "trim spaces", "x y", seg_string(trimmed)); +}; + +let test_trim_linebreak_and_indent = () => { + /* Leading: linebreak + indent. Trailing: linebreak (no spaces between + * content and the trailing linebreak — those would be kept as user + * whitespace). */ + let seg = [linebreak(), space(), space(), atom("x"), linebreak()]; + let trimmed = SubEditor.trim_separators(seg); + check(string, "trim linebreak+indent", "x", seg_string(trimmed)); +}; + +let test_trim_keeps_user_mid_whitespace = () => { + /* Two spaces after x: first is host separator (stripped), second is + * the user's mid-typing space and must remain. */ + let seg = [space(), atom("x"), space(), space()]; + let trimmed = SubEditor.trim_separators(seg); + check(string, "keep mid-typing space", "x ", seg_string(trimmed)); +}; + +/* --- Confinement via real editor --- */ + +let caret_char = "¦"; + +let string_to_ltr_actions = (s: string): list(Action.t) => + s |> Token.to_list |> List.map(~f=c => Action.Insert(c)); + +let mv_l = (n: int): list(Action.t) => + List.init(n, ~f=_ => Action.Move(Local(Left, ByChar))); + +let perform_zip = (zip: Zipper.t, actions: list(Action.t)): Zipper.t => { + let go = (a: Action.t, z: Zipper.t) => + Perform.go( + ~settings=CoreSettings.off, + ~statics=CachedStatics.empty, + ~syntax=CachedSyntax.init(z), + ~root=Exp, + a, + { + zipper: z, + col_target: None, + }, + ); + List.fold_left( + ~f= + (z, a) => + switch (go(a, z)) { + | Ok(z) => z + | Error(err) => + fail("Failed on action: " ++ Action.Failure.show(err)) + }, + ~init=zip, + actions, + ); +}; + +let zipper_with_caret = (init: string): Zipper.t => { + let rec split = (before, rest) => + switch (rest) { + | [] => fail("No caret in: " ++ init) + | [hd, ...tl] => + hd == caret_char + ? (List.rev(before), tl) : split([hd, ...before], tl) + }; + let (before, after) = split([], Token.to_list(init)); + let s = Token.of_list(before @ after); + perform_zip( + Zipper.init(), + string_to_ltr_actions(s) @ mv_l(List.length(after)), + ); +}; + +let find_tile_by_label = (label: Label.t, seg: Segment.t): option(Base.tile) => { + let rec go = (seg: Segment.t): option(Base.tile) => + List.fold_left( + ~f= + (found, p: Piece.t) => + switch (found) { + | Some(_) => found + | None => + switch (p) { + | Piece.Tile(t) => + Tile.label(t) == label + ? Some(t) + : List.fold_left( + ~f=(found, child) => found == None ? go(child) : found, + ~init=None, + t.children, + ) + | _ => None + } + }, + ~init=None, + seg, + ); + go(seg); +}; + +let case_editor = (with_caret: string): (Editor.Model.t, Id.t) => { + let z = zipper_with_caret(with_caret); + let ed = Editor.Model.mk(z, ~root=Exp); + switch ( + find_tile_by_label(["case", "end"], CachedSyntax.segment(ed.syntax)) + ) { + | None => fail("no case tile") + | Some(t) => (ed, t.id) + }; +}; + +let test_mk_scrut_from_case = () => { + let (ed, case_id) = case_editor("case x | A => 1 end¦"); + let target = scrut_target(case_id); + switch (SubEditor.mk(ed, ~target)) { + | None => fail("mk returned None") + | Some(sub) => + check(string, "mk scrut segment", "x", seg_string(sub.splice.segment)) + }; +}; + +let test_confine_rejects_edge_delete = () => { + let (ed, case_id) = case_editor("case ¦x | A => 1 end"); + let target = scrut_target(case_id); + check( + bool, + "Destruct(Left) at left edge rejected", + true, + SubEditor.confine_pre( + ~target, + ~action=Destruct(Local(Left, ByChar)), + ed, + ) + == None, + ); + let (ed_r, case_id_r) = case_editor("case x¦ | A => 1 end"); + let target_r = scrut_target(case_id_r); + check( + bool, + "Destruct(Right) at right edge rejected", + true, + SubEditor.confine_pre( + ~target=target_r, + ~action=Destruct(Local(Right, ByChar)), + ed_r, + ) + == None, + ); +}; + +/* Inside a splice that is one bracketed tile, the caret beside a bracket + * is not at the splice's edge, though the bracket has the splice's id. */ +let test_confine_allows_delete_beside_inner_bracket = () => { + let (ed, case_id) = case_editor("case [xyz¦] | A => 1 end"); + check( + bool, + "Destruct(Left) before `]` allowed", + true, + SubEditor.confine_pre( + ~target=scrut_target(case_id), + ~action=Destruct(Local(Left, ByChar)), + ed, + ) + |> Option.is_some, + ); + let (ed_r, case_id_r) = case_editor("case [¦xyz] | A => 1 end"); + check( + bool, + "Destruct(Right) after `[` allowed", + true, + SubEditor.confine_pre( + ~target=scrut_target(case_id_r), + ~action=Destruct(Local(Right, ByChar)), + ed_r, + ) + |> Option.is_some, + ); +}; + +let test_confine_rejects_edit_outside = () => { + /* Caret on the rule separator — outside the scrut splice. */ + let (ed, case_id) = case_editor("case x ¦| A => 1 end"); + let target = scrut_target(case_id); + check( + bool, + "Insert outside splice rejected", + true, + SubEditor.confine_pre(~target, ~action=Insert("z"), ed) == None, + ); +}; + +let test_confine_allows_edit_inside = () => { + let (ed, case_id) = case_editor("case ¦x | A => 1 end"); + let target = scrut_target(case_id); + check( + bool, + "Insert inside splice allowed", + true, + Option.is_some(SubEditor.confine_pre(~target, ~action=Insert("z"), ed)), + ); +}; + +let tests = ( + "SubEditor", + [ + test_case("resolve whole child", `Quick, test_whole_child), + test_case( + "resolve prefix until first rule", + `Quick, + test_prefix_until_first_rule, + ), + test_case("resolve nth rule pattern", `Quick, test_nth_rule_pattern), + test_case("resolve between bounds", `Quick, test_between_bounds), + test_case( + "nested matching labels ignored", + `Quick, + test_nested_label_ignored, + ), + test_case( + "malformed targets return None", + `Quick, + test_missing_returns_none, + ), + test_case( + "BeforeOrEnd falls back to end", + `Quick, + test_before_or_end_falls_back, + ), + test_case( + "stable under inner id churn", + `Quick, + test_stable_under_inner_id_churn, + ), + test_case( + "trim one space each end", + `Quick, + test_trim_one_space_each_end, + ), + test_case( + "trim linebreak and indent", + `Quick, + test_trim_linebreak_and_indent, + ), + test_case( + "trim keeps user mid whitespace", + `Quick, + test_trim_keeps_user_mid_whitespace, + ), + test_case("mk scrut from case", `Quick, test_mk_scrut_from_case), + test_case( + "confine rejects edge delete", + `Quick, + test_confine_rejects_edge_delete, + ), + test_case( + "confine allows delete beside a bracket inside the splice", + `Quick, + test_confine_allows_delete_beside_inner_bracket, + ), + test_case( + "confine rejects edit outside", + `Quick, + test_confine_rejects_edit_outside, + ), + test_case( + "confine allows edit inside", + `Quick, + test_confine_allows_edit_inside, + ), + ], +); diff --git a/test/Test_TermData.re b/test/Test_TermData.re index 72be48bd97..a1470805e3 100644 --- a/test/Test_TermData.re +++ b/test/Test_TermData.re @@ -13,7 +13,8 @@ let syntax_from_string = (s: string): Haz3lcore.CachedSyntax.t => let root_piece_finds_grout = () => { let syntax = syntax_from_string("1 +"); - let holes = Haz3lcore.Segment.holes(syntax.segment); + let holes = + Haz3lcore.Segment.holes(Haz3lcore.CachedSyntax.segment(syntax)); check(bool, "parse produced at least one hole/grout", true, holes != []); List.iter( ~f= @@ -45,7 +46,7 @@ let root_piece_finds_tile = () => { | Tile(t) => Some(t.id) | _ => None }, - syntax.segment, + Haz3lcore.CachedSyntax.segment(syntax), ); check(bool, "found tiles", true, tile_ids != []); List.iter( diff --git a/test/Test_Undo.re b/test/Test_Undo.re index 9fa8fe1c26..71bcf80c89 100644 --- a/test/Test_Undo.re +++ b/test/Test_Undo.re @@ -306,5 +306,77 @@ let tests = ( ); }, ), + test_case( + "undo puts back a step deleted from the stepper, with the steps inside it", + `Quick, + () => { + let z = + Test_EditorTransform.parse_zipper( + "theorem t = forall (b : Bool) -> b || false == b proof induction b | true => from true || false do step end | false => from false || false do step end end; ? in t", + ); + let induction = + switch (Test_EditorTransform.(find_theorem_proof(zipper_term(z)))) { + | Some({term: Seq(induction, _), _}) => induction + | _ => fail("no induction chained before a hole") + }; + let m0 = mk_model(); + let scratch = + switch (m0.current.editors) { + | Scratch(s) => s + | _ => fail("not in scratch mode") + }; + let scratchpad = List.nth_exn(scratch.scratchpads, scratch.current); + let agent = + switch (scratchpad.kind) { + | Code({agent, _}) => agent + | Drv(_) => fail("not a code slide") + }; + let scratchpad = { + ...scratchpad, + kind: + Code({ + editor: + CellEditor.Model.mk(Haz3lcore.Editor.Model.mk(~root=Exp, z)), + agent, + }), + }; + let m0 = { + ...m0, + current: { + ...m0.current, + editors: + Scratch({ + ...scratch, + scratchpads: + Util.ListUtil.put_nth( + scratch.current, + scratchpad, + scratch.scratchpads, + ), + }), + }, + }; + let t0 = text_of(m0); + let m1 = + apply( + m0, + Editors( + Scratch( + CellAction( + PatchMainEditor(StepperPicker.Patches.remove(induction)), + ), + ), + ), + ); + check( + string, + "the delete took the induction and its `;`", + "theorem t = forall (b : Bool) -> b || false == b proof ? in t", + text_of(m1), + ); + let m2 = apply(m1, undo); + check(string, "undo restores the text", t0, text_of(m2)); + }, + ), ], ); diff --git a/test/Test_UnusedWarnings.re b/test/Test_UnusedWarnings.re index 9ba18cf74e..b8435960fe 100644 --- a/test/Test_UnusedWarnings.re +++ b/test/Test_UnusedWarnings.re @@ -104,22 +104,6 @@ let tests = ( ); }, ), - test_case( - "theorem: binder's info has the proof type", - `Quick, - () => { - let t = theorem_binder("theorem t = true in t", "t"); - check( - bool, - "t : ProofOf(...)", - true, - switch (Typ.term_of(t.ty)) { - | ProofOf(_) => true - | _ => false - }, - ); - }, - ), check_unused("forall: used binder", "forall (x : Int) -> x == x", []), check_unused("forall: unused binder", "forall (x : Int) -> true", ["x"]), check_unused( @@ -374,5 +358,46 @@ let tests = ( "let x = (a=1, b=2) in let y = 3 in x ... (a=y)", [], ), + /* Funext binders name the arbitrary argument of the pointwise goal; + the proof need not mention them. */ + check_unused( + "funext: binder not flagged unused in a hole body", + "theorem t = (fun x -> x) == (fun x -> x) proof funext y => ? in t", + [], + ), + check_unused( + "theorem with a proof: a statement binder the statement uses", + "theorem t = forall x : [Int] -> x == x @ [] proof ? in t", + [], + ), + check_unused( + "theorem with a proof: an unused statement binder still warns", + "theorem t = forall (x : Int) -> true proof ? in t", + ["x"], + ), + check_unused( + "proof: induction case binders", + {|theorem t = forall x : [Int] -> x == x @ [] proof +induction x +| [] => from [] @ [] do step end; from $e do step end +| u :: us => from u :: us @ [] do step end +end in t|}, + [], + ), + check_unused( + "proof: forall and funext binders", + "theorem t = forall (x : Int) -> (fun a -> a + x) == (fun b -> x + b) proof forall x => funext z => ? in t", + [], + ), + check_unused( + "proof: fact names", + "theorem t = forall (x : Int) -> x == 1 ==> x == 1 proof forall x => assume h = x == 1 => alias k = h => ? in t", + [], + ), + check_unused( + "proof: an ordinary binding still warns", + "let y = 1 in theorem t = forall (x : Int) -> x == x proof forall x => ? in t", + ["y"], + ), ], ); diff --git a/test/Test_WorkerServer.re b/test/Test_WorkerServer.re index 030a666caa..418f45deb0 100644 --- a/test/Test_WorkerServer.re +++ b/test/Test_WorkerServer.re @@ -164,6 +164,7 @@ let request = eval_info_map: Test_Evaluator_Incremental.eval_info_of_statics(info_map), prev, + generation: 0, }, ); }; diff --git a/test/evaluator/Test_AlgebraSteps.re b/test/evaluator/Test_AlgebraSteps.re new file mode 100644 index 0000000000..bff9b89ec9 --- /dev/null +++ b/test/evaluator/Test_AlgebraSteps.re @@ -0,0 +1,251 @@ +open Alcotest; +open Language; +open Test_ProofMap.Harness; + +/* `algebra` steps, verified by Algebrite. It verifies Int arithmetic + * (literals, +, −, ×, unary −, ** with a literal exponent) over variables + * known to be Int, and Nat arithmetic (literals, +, ×, **) over variables + * known to be Nat, and refuses a step it finds wrong. Any other step's + * equation is left as an obligation, so the proof can't read plain + * Proven. */ + +let status = (name, src) => { + let (pm, proof) = run_named(name, src); + switch (ProofMap.full_status_of_proof(pm, proof)) { + | Proven => "Proven" + | ProvenModulo(obs) => + "ProvenModulo " + ++ String.concat( + ~sep=", ", + List.map( + ~f=(ob: Obligation.t) => Obligation.show_kind(ob.kind), + obs, + ), + ) + | Refuted => "Refuted" + | Incomplete => "Incomplete" + }; +}; + +let differs = (name, src) => { + let (pm, proof) = run_named(name, src); + has_mark_kind( + pm, + proof, + fun + | ProofMark.AlgebraDiffers => true + | _ => false, + ); +}; + +let tests = ( + "AlgebraSteps", + [ + test_case( + "a polynomial identity over Int variables is verified", `Quick, () => + check( + string, + "Proven", + "Proven", + status( + "t", + "theorem t = forall a: Int -> forall b: Int -> (a + b) * (a + b) == a * a + 2 * a * b + b ** 2 proof from (a + b) * (a + b) do algebra a * a + 2 * a * b + b ** 2 end end; from $e == $e do rewrite refl end end in t", + ), + ) + ), + test_case( + "a polynomial identity over Nat variables is verified", `Quick, () => + check( + string, + "Proven", + "Proven", + status( + "t", + "use Nat in theorem t = forall a: Nat -> forall b: Nat -> (a + b) * (a + b) == a * a + 2 * a * b + b ** 2 proof from (a + b) * (a + b) do algebra a * a + 2 * a * b + b ** 2 end end; from $e == $e do rewrite refl end end in t", + ), + ) + ), + test_case("a wrong Nat step is refused", `Quick, () => + check( + bool, + "marked", + true, + differs( + "t", + "use Nat in theorem t = forall x: Nat -> x + x == 3 * x proof from x + x do algebra 3 * x end end in t", + ), + ) + ), + /* True, but `monus` truncates, so it isn't a polynomial and the step + stays an obligation. */ + test_case("Nat subtraction is unverified", `Quick, () => + check( + string, + "ProvenModulo", + "ProvenModulo Algebra", + status( + "t", + "use Nat in theorem t = forall x: Nat -> monus(x + 1, 1) == x proof from monus(x + 1, 1) do algebra x end end; rewrite refl end in t", + ), + ) + ), + test_case("a wrong step is refused", `Quick, () => + check( + bool, + "marked", + true, + differs( + "t", + "theorem t = forall x: Int -> x + x == 3 * x proof from x + x do algebra 3 * x end end in t", + ), + ) + ), + test_case("`i` is a variable, not the imaginary unit", `Quick, () => + check( + bool, + "marked", + true, + differs( + "t", + "theorem t = forall i: Int -> i * i + 1 == 0 proof from i * i do algebra 0 - 1 end end in t", + ), + ) + ), + test_case("a definition with a literal value counts as it", `Quick, () => + check( + string, + "Proven", + "Proven", + status( + "t", + "let n = 3 in theorem t = n + n == 6 proof from n + n do algebra 6 end end; from 6 == 6 do rewrite refl end end in t", + ), + ) + ), + test_case( + "a definition whose value is an error leaves the step unverified", + `Quick, + () => + check( + string, + "ProvenModulo", + "ProvenModulo Algebra", + status( + "t", + "let x : Int = 1 / 0 in theorem t = 0 * x == 0 proof from 0 * x do algebra 0 end end; from 0 == 0 do rewrite refl end end in t", + ), + ) + ), + test_case("a variable not known to be Int is unverified", `Quick, () => + check( + string, + "ProvenModulo", + "ProvenModulo Algebra", + status( + "t", + "theorem t = forall x -> x + 0 == x proof from x + 0 do algebra x end end; from x == x do rewrite refl end end in t", + ), + ) + ), + test_case("a step outside Int arithmetic doesn't prove", `Quick, () => + check( + string, + "ProvenModulo", + "ProvenModulo Algebra", + status("bad", "theorem bad = 1 == 2 proof algebra true end in bad"), + ) + ), + /* False at n = 1: Int division rounds. */ + test_case("Int division is not exact", `Quick, () => + check( + string, + "ProvenModulo", + "ProvenModulo Algebra", + status( + "half", + "theorem half = forall n: Int -> n / 2 * 2 == n proof from n / 2 * 2 do algebra n end end; rewrite refl end in half", + ), + ) + ), + test_case("Nat division is not exact", `Quick, () => + check( + string, + "ProvenModulo", + "ProvenModulo Algebra", + status( + "half", + "use Nat in theorem half = forall n: Nat -> n / 2 * 2 == n proof from n / 2 * 2 do algebra n end end; rewrite refl end in half", + ), + ) + ), + test_case("nat_succ_ne_zero decides a Nat test against 0", `Quick, () => + check( + string, + "Proven", + "Proven", + status( + "t", + "use Nat in theorem t = forall m: Nat -> (if m + 1 == 0 then 0 else 5) == 5 proof from m + 1 == 0 do rewrite nat_succ_ne_zero end end; from if false then 0 else 5 do step end; rewrite refl end in t", + ), + ) + ), + /* `m + 1 == 0` is true at m = -1. */ + test_case("nat_succ_ne_zero doesn't apply to an Int", `Quick, () => + check( + bool, + "refused", + true, + { + let (pm, proof) = + run_named( + "t", + "theorem t = forall m: Int -> (m + 1 == 0) == false proof from m + 1 == 0 do rewrite nat_succ_ne_zero end end; rewrite refl end in t", + ); + has_mark_kind( + pm, + proof, + fun + | ProofMark.RuleDoesNotApply(_) => true + | _ => false, + ); + }, + ) + ), + test_case("nat_add_sub takes off what was added", `Quick, () => + check( + string, + "Proven", + "Proven", + status( + "t", + "use Nat in theorem t = forall m: Nat -> monus(m + 3, 3) == m proof from monus(m + 3, 3) do rewrite nat_add_sub end end; rewrite refl end in t", + ), + ) + ), + /* Both rules apply, so the sum unfolds. It recurses through `monus`, + which the totality check doesn't follow, so `refl` at a goal that + mentions it is refused: the first mark is on that last step. */ + test_case("a sum written with if unfolds at m + 1", `Quick, () => + check( + bool, + "only refl is refused", + true, + { + let (pm, proof) = + run_named( + "t", + "use Nat in let sum = fun (n : Nat) -> if n == 0 then 0 else n + sum(monus(n, 1)) in theorem t = forall m: Nat -> sum(m + 1) == m + 1 + sum(m) proof from sum(m + 1) do step end; from m + 1 == 0 do rewrite nat_succ_ne_zero end end; from if false then 0 else m + 1 + sum(monus(m + 1, 1)) do step end; from monus(m + 1, 1) do rewrite nat_add_sub end end; rewrite refl end in t", + ); + has_mark_kind( + pm, + proof, + fun + | ProofMark.PossiblyDivergentInstantiation({equality: "refl", _}) => + true + | _ => false, + ); + }, + ) + ), + ], +); diff --git a/test/evaluator/Test_CasesInduction.re b/test/evaluator/Test_CasesInduction.re new file mode 100644 index 0000000000..caaa12393c --- /dev/null +++ b/test/evaluator/Test_CasesInduction.re @@ -0,0 +1,339 @@ +open Alcotest; +open Language; +open Test_ProofMap.Harness; +open Poly; + +/* The two splits. `cases e` gives each case the case equation + * `e == pat` and no inductive hypothesis. `induction e` gives each case + * its inductive hypotheses and no case equation, a computed `e` is first + * generalized, and the facts that mention `e` are out of scope in its + * cases. Nothing gives both: an inductive hypothesis kept beside a fact + * tying the case to the scrutinee's actual value would prove too much. */ + +let tl = "let tl = fun xs -> case xs | [] => [] | _ :: t => t end in "; + +/* The bodies of the root split's cases. */ +let case_bodies = (proof: Proof.t): list(Proof.t) => { + let rec split = (p: Proof.t) => + switch (p.term) { + | Cases(_, cases) + | Induction(_, cases) => List.map(~f=snd, cases) + | Assume(_, _, body) => split(body) + | _ => Alcotest.fail("no split at the root") + }; + split(proof); +}; + +/* Printed without spaces, which the printer places loosely. */ +let printed = (e: Exp.t): string => + print_exp(e) |> String.split(~on=' ') |> String.concat(~sep=""); + +/* The facts in scope in a case body, by name, with their statements. */ +let facts = (pm: ProofMap.t, body: Proof.t): list((string, string)) => + switch (ProofMap.lookup(Proof.rep_id(body), pm)) { + | Some({ctx, _}) => + SemanticCtx.facts(ctx) + |> List.map(~f=((name, _, fact)) => (name, printed(fact))) + | None => Alcotest.fail("no scope recorded for the case") + }; + +let check_goal = (msg, expected, pm, body) => + check(string, msg, expected, printed(incoming_of(pm, body))); + +let check_fact = (msg, ~name, expected, pm, body) => + check( + option(string), + msg, + expected, + List.Assoc.find(facts(pm, body), name, ~equal=String.equal), + ); + +let both_cases = (src: string): (ProofMap.t, Proof.t, Proof.t) => { + let (pm, proof) = run(src); + switch (case_bodies(proof)) { + | [nil, cons] => (pm, nil, cons) + | _ => Alcotest.fail("expected two cases") + }; +}; + +let test_induction_has_no_case_equation = () => { + let (pm, nil, cons) = + both_cases( + "theorem t = forall xs: [Int] -> xs == xs proof induction xs | [] => ? | y :: rest => ? end in t", + ); + check_fact("no case equation for []", ~name="case_eq", None, pm, nil); + check_fact("no case equation for ::", ~name="case_eq", None, pm, cons); + check_fact( + "the inductive hypothesis", + ~name="ih_rest", + Some("rest==rest"), + pm, + cons, + ); +}; + +let test_cases_has_no_inductive_hypothesis = () => { + let (pm, _, cons) = + both_cases( + "theorem t = forall xs: [Int] -> xs == xs proof cases xs | [] => ? | y :: rest => ? end in t", + ); + check_fact( + "the case equation", + ~name="case_eq", + Some("xs==y::rest"), + pm, + cons, + ); + check_fact("no inductive hypothesis", ~name="ih_rest", None, pm, cons); +}; + +/* With `xs == [1]` in scope beside the unconditional `ih_rest`, the cons + * case could prove anything about `xs`. */ +let test_induction_hides_facts_about_a_variable = () => { + let src = "theorem t = forall xs: [Int] -> forall n: Int -> n == 1 ==> xs == [1] ==> xs == xs proof assume hn = n == 1 => assume xs == [1] => induction xs | [] => ? | y :: rest => ? end in t"; + let (pm, nil, cons) = both_cases(src); + check_fact( + "the fact about xs is out of scope", + ~name="assume", + None, + pm, + nil, + ); + check_fact( + "the fact about xs is out of scope", + ~name="assume", + None, + pm, + cons, + ); + check_fact( + "a fact that doesn't mention xs stays", + ~name="hn", + Some("n==1"), + pm, + cons, + ); +}; + +let test_cases_keeps_facts_about_a_variable = () => { + let (pm, _, cons) = + both_cases( + "theorem t = forall xs: [Int] -> xs == [1] ==> xs == xs proof assume xs == [1] => cases xs | [] => ? | y :: rest => ? end in t", + ); + check_fact( + "the fact about xs stays", + ~name="assume", + Some("xs==[1]"), + pm, + cons, + ); +}; + +/* Induction on a computed value is induction on a fresh variable in its + * place. The cases' goals and hypotheses have the pattern in place of + * `tl(xs)`, and nothing in scope says what `tl(xs)` is. */ +let test_induction_generalizes_a_computed_scrutinee = () => { + let (pm, nil, cons) = + both_cases( + tl + ++ "theorem t = forall xs: [Int] -> tl(xs) == [] ==> tl(xs) == tl(xs) proof assume tl(xs) == [] => induction tl(xs) | [] => ? | y :: rest => ? end in t", + ); + check_goal("the [] case's goal", "[]==[]", pm, nil); + check_goal("the :: case's goal", "y::rest==y::rest", pm, cons); + check_fact( + "the inductive hypothesis", + ~name="ih_rest", + Some("rest==rest"), + pm, + cons, + ); + check_fact("no case equation", ~name="case_eq", None, pm, nil); + check_fact( + "the fact about tl(xs) is out of scope", + ~name="assume", + None, + pm, + nil, + ); +}; + +let test_cases_on_a_computed_scrutinee = () => { + let (pm, _, cons) = + both_cases( + tl + ++ "theorem t = forall xs: [Int] -> tl(xs) == [] ==> tl(xs) == tl(xs) proof assume tl(xs) == [] => cases tl(xs) | [] => ? | y :: rest => ? end in t", + ); + check_fact( + "the case equation", + ~name="case_eq", + Some("tl(xs)==y::rest"), + pm, + cons, + ); + check_fact("no inductive hypothesis", ~name="ih_rest", None, pm, cons); + check_fact( + "the fact about tl(xs) stays", + ~name="assume", + Some("tl(xs)==[]"), + pm, + cons, + ); +}; + +/* Induction on `[1]` gives the `::` case `ih_t: false`, the goal itself. + * Sound only because the `[]` case has no case equation `[1] == []` to + * close it with, so it stays open. */ +let test_induction_on_a_literal_proves_nothing = () => { + let (pm, proof) = + run_named( + "bad", + "theorem bad = false proof induction [1] | [] => rewrite case_eq end | h :: t => rewrite ih_t end end in bad", + ); + check( + bool, + "the [] case can't cite a case equation", + true, + has_mark_kind( + pm, + proof, + fun + | ProofMark.UnknownEquality("case_eq") => true + | _ => false, + ), + ); + check( + bool, + "not proven", + false, + ProofMap.full_status_of_proof(pm, proof) == ProofMap.Proven, + ); +}; + +/* A split's cases have to cover its scrutinee's type, so a split with + * none is not exhaustive, unless the type has no values, where it proves + * its goal. */ +let empty_split = (src: string) => { + let (pm, proof) = run(src); + ( + ProofMap.marks_of(Proof.rep_id(proof), pm), + ProofMap.full_status_of_proof(pm, proof), + ); +}; + +let test_empty_split_is_not_exhaustive = () => + List.iter( + ~f= + src => + check( + bool, + src, + true, + switch (empty_split(src)) { + | ([ProofMark.InductionNotExhaustive], _) => true + | _ => false + }, + ), + [ + "theorem t = forall b: Bool -> b == b proof cases b end in t", + "theorem t = forall xs: [Int] -> xs == xs proof induction xs end in t", + ], + ); + +let test_empty_split_on_void_proves = () => { + let (marks, status) = + empty_split("theorem t = forall v: Void -> false proof cases v end in t"); + check(bool, "no marks", true, marks == []); + check(bool, "proven", true, status == ProofMap.Proven); +}; + +/* A case pattern in parens or with an ascription is the scrutinee in + * the case, not a strict part of it, so it is not one of its own + * inductive hypotheses: that hypothesis would be the case's goal. */ +let wrapped_case = (pat: string) => { + let src = + "theorem t = forall xs: [Int] -> xs == [] proof induction xs | [] => rewrite refl end | " + ++ pat + ++ " => from y :: t do rewrite ih end end; rewrite refl end end in t"; + let (pm, proof) = run(src); + let hypotheses = + switch (case_bodies(proof)) { + | [_, cons] => + facts(pm, cons) + |> List.map(~f=fst) + |> List.filter(~f=name => String.is_prefix(name, ~prefix="ih")) + | _ => Alcotest.fail("expected two cases") + }; + (ProofMap.full_status_of_proof(pm, proof), hypotheses); +}; + +let test_wrapped_case_is_not_its_own_hypothesis = (pat, ()) => { + let (status, hypotheses) = wrapped_case(pat); + check(bool, "not proven", false, status == ProofMap.Proven); + check(list(string), "the hypotheses", ["ih_t"], hypotheses); +}; + +let tests = ( + "CasesInduction", + [ + test_case( + "a split with no cases is not exhaustive", + `Quick, + test_empty_split_is_not_exhaustive, + ), + test_case( + "a split with no cases on Void proves its goal", + `Quick, + test_empty_split_on_void_proves, + ), + test_case( + "an induction case has no case equation", + `Quick, + test_induction_has_no_case_equation, + ), + test_case( + "a cases case has no inductive hypothesis", + `Quick, + test_cases_has_no_inductive_hypothesis, + ), + test_case( + "an induction case doesn't see facts about its scrutinee", + `Quick, + test_induction_hides_facts_about_a_variable, + ), + test_case( + "a cases case keeps facts about its scrutinee", + `Quick, + test_cases_keeps_facts_about_a_variable, + ), + test_case( + "induction generalizes a computed scrutinee", + `Quick, + test_induction_generalizes_a_computed_scrutinee, + ), + test_case( + "cases on a computed scrutinee", + `Quick, + test_cases_on_a_computed_scrutinee, + ), + test_case( + "induction on a literal proves nothing", + `Quick, + test_induction_on_a_literal_proves_nothing, + ), + test_case( + "a case pattern in parens is not its own hypothesis", + `Quick, + test_wrapped_case_is_not_its_own_hypothesis("(y :: t)"), + ), + test_case( + "an ascribed case pattern is not its own hypothesis", + `Quick, + test_wrapped_case_is_not_its_own_hypothesis("(y :: t : [Int])"), + ), + test_case( + "a case pattern in two wrappers keeps its inner hypotheses", + `Quick, + test_wrapped_case_is_not_its_own_hypothesis("((y :: t))"), + ), + ], +); diff --git a/test/evaluator/Test_CheckedProofs.re b/test/evaluator/Test_CheckedProofs.re new file mode 100644 index 0000000000..fe4164387d --- /dev/null +++ b/test/evaluator/Test_CheckedProofs.re @@ -0,0 +1,274 @@ +open Alcotest; +open Language; +open Test_Evaluator_Prelude; +open Test_ProofMap.Harness; +open Poly; + +/* Reusing a checked proof across evaluations. A theorem's proof is + * reused unless the theorem, the provenance of a variable it names, or the + * theorems in scope change; a change to its body, which holds every later + * theorem, doesn't recheck it. + * + * Edits keep ids, as the editor's do, so the second evaluation finds the + * first's entries (see Test_Evaluator_Incremental). */ + +let eval = (~prev=IncrEval.empty, exp: Exp.t) => { + let (info_map, elab) = statics_and_elab(exp); + let eval_info = + EvalInfo.of_info_map( + ~probe_all=CoreSettings.on.probe_all, + ~targets=Id.Map.empty, + info_map, + ); + let (_, state) = + Evaluator.evaluate(~prev, ~eval_info, ~env=Builtins.env_init, elab); + (state, elab); +}; + +/* `exp` with the int literal `from` replaced by `to_` in theorem `name`'s + * statement and proof only, keeping every id. */ +let edit_theorem = (name: string, ~from: int, ~to_: int, exp: Exp.t): Exp.t => { + let replace_int = + Exp.map_term(~f_exp=(continue, e: Exp.t) => + switch (e.term) { + | Atom(Int(n)) when Bigint.to_string(n) == string_of_int(from) => { + ...e, + term: Atom(Int(Bigint.of_int(to_))), + } + | _ => continue(e) + } + ); + Exp.map_term( + ~f_exp= + (continue, e: Exp.t) => + switch (e.term) { + | Theorem({term: Var(x), _} as p, goal, proof, body) when x == name => + let edited = + replace_int({ + ...e, + term: Theorem(p, goal, proof, Exp.temp(EmptyHole)), + }); + switch (edited.term) { + | Theorem(p, goal, proof, _) => { + ...e, + term: Theorem(p, goal, proof, continue(body)), + } + | _ => continue(e) + }; + | _ => continue(e) + }, + exp, + ); +}; + +/* The proof map entry of theorem `name`'s proof. */ +let root = (name, (state, elab)) => + switch ( + ProofMap.lookup( + Proof.rep_id(proof_of_named(name, elab)), + EvaluatorState.get_proof_map(state), + ) + ) { + | Some(entry) => entry + | None => fail("no proof map entry for " ++ name) + }; + +let reused = (name, ~before, ~after) => + phys_equal(root(name, before), root(name, after)); + +/* How many steps of theorem `name`'s proof are marked. */ +let marks = (name, (state, elab)) => { + let pm = EvaluatorState.get_proof_map(state); + let rec count = (p: Proof.t) => + (ProofMap.marks_of(Proof.rep_id(p), pm) == [] ? 0 : 1) + + List.fold_left(~f=(n, c) => n + count(c), ~init=0, Proof.children(p)); + count(proof_of_named(name, elab)); +}; + +let test_unchanged_is_reused = () => { + let exp = + parse_exp( + "theorem a = 1 + 1 == 2 proof step in theorem b = 2 + 2 == 4 proof step in 0", + ); + let before = eval(exp); + let after = eval(~prev=fst(before).incr_eval, exp); + check(bool, "a is reused", true, reused("a", ~before, ~after)); + check(bool, "b is reused", true, reused("b", ~before, ~after)); +}; + +let test_body_change_keeps_earlier_theorem = () => { + let exp = + parse_exp( + "theorem a = 1 + 1 == 2 proof step in theorem b = 2 + 2 == 4 proof step in 0", + ); + let before = eval(exp); + let after = + eval( + ~prev=fst(before).incr_eval, + edit_theorem("b", ~from=4, ~to_=5, exp), + ); + check( + bool, + "a, whose body changed, is reused", + true, + reused("a", ~before, ~after), + ); + check(bool, "b is checked again", false, reused("b", ~before, ~after)); +}; + +let discharges = (name, (state, elab)) => + ProofMap.obligations_of_proof( + EvaluatorState.get_proof_map(state), + proof_of_named(name, elab), + ) + |> List.map(~f=(ob: Obligation.t) => + Obligation.show_discharge(ob.discharge) + ); + +/* `k` is named only in the proof. */ +let test_definition_named_in_proof = () => { + let exp = + parse_exp( + "let k = 3 in theorem a = 2 == 2 proof have k == 1 proof ? => ? in 0", + ); + let discharge = discharges("a"); + let before = eval(exp); + check( + list(string), + "k == 1 doesn't hold", + ["Pending", "Pending"], + discharge(before), + ); + let after = + eval( + ~prev=fst(before).incr_eval, + Test_Evaluator_Incremental.replace_int_lit(~from=3, ~to_=1, exp), + ); + check( + list(string), + "k == 1 holds", + ["Evaluated", "Pending"], + discharge(after), + ); +}; + +/* `b` is inside `a`'s node, which evaluation reuses if nothing it depends + * on changed, `b`'s proof included. */ +let test_definition_named_in_nested_proof = () => { + let exp = + parse_exp( + "let k = 3 in theorem a = 2 == 2 proof ? in theorem b = 2 == 2 proof have k == 1 proof ? => ? in 0", + ); + let before = eval(exp); + check( + list(string), + "k == 1 doesn't hold", + ["Pending", "Pending"], + discharges("b", before), + ); + let after = + eval( + ~prev=fst(before).incr_eval, + Test_Evaluator_Incremental.replace_int_lit(~from=3, ~to_=1, exp), + ); + check( + list(string), + "k == 1 holds", + ["Evaluated", "Pending"], + discharges("b", after), + ); +}; + +/* `b` cites `a`, which isn't a variable, so no co-ctx has it. */ +let test_cited_theorem_changes = () => { + let exp = + parse_exp( + "theorem a = 40 + 2 == 42 proof ? in theorem b = 40 + 2 == 42 proof from 40 + 2 do rewrite a end end in 0", + ); + let before = eval(exp); + check(int, "b's rewrite applies", 0, marks("b", before)); + let after = + eval( + ~prev=fst(before).incr_eval, + edit_theorem("a", ~from=2, ~to_=3, exp), + ); + check(int, "b's rewrite no longer applies", 1, marks("b", after)); +}; + +/* `exp` with theorem `name`'s proof a hole, keeping every id. */ +let drop_proof = (name: string, exp: Exp.t): Exp.t => + Exp.map_term( + ~f_exp= + (continue, e: Exp.t) => + switch (e.term) { + | Theorem({term: Var(x), _} as p, goal, proof, body) when x == name => { + ...e, + term: + Theorem( + p, + goal, + { + ...proof, + term: EmptyHole, + }, + continue(body), + ), + } + | _ => continue(e) + }, + exp, + ); + +/* Citing an unfinished theorem incurs its statement as an obligation, so a + * proof is checked again when the verdict of a theorem it cites changes. */ +let test_cited_verdict_changes = () => { + let exp = + parse_exp( + "theorem a = 1 == 1 proof rewrite refl end in theorem b = 1 == 1 proof from 1 do rewrite a end end; rewrite refl end in 0", + ); + let before = eval(exp); + check(list(string), "a is proven", [], discharges("b", before)); + let after = eval(~prev=fst(before).incr_eval, drop_proof("a", exp)); + check( + list(string), + "a is unfinished, so citing it incurs its statement", + ["Evaluated"], + discharges("b", after), + ); +}; + +let tests = ( + "CheckedProofs", + [ + test_case( + "an unchanged theorem's proof is reused", + `Quick, + test_unchanged_is_reused, + ), + test_case( + "a change in a theorem's body doesn't recheck it", + `Quick, + test_body_change_keeps_earlier_theorem, + ), + test_case( + "a proof is rechecked when a definition only it names changes", + `Quick, + test_definition_named_in_proof, + ), + test_case( + "a proof inside a reused node is rechecked when a definition only it names changes", + `Quick, + test_definition_named_in_nested_proof, + ), + test_case( + "a proof is rechecked when a theorem it cites changes", + `Quick, + test_cited_theorem_changes, + ), + test_case( + "a proof is rechecked when the verdict of a theorem it cites changes", + `Quick, + test_cited_verdict_changes, + ), + ], +); diff --git a/test/evaluator/Test_ClosureLibrary.re b/test/evaluator/Test_ClosureLibrary.re new file mode 100644 index 0000000000..d4f54a2186 --- /dev/null +++ b/test/evaluator/Test_ClosureLibrary.re @@ -0,0 +1,644 @@ +open Alcotest; +open Language; +open Test_ProofMap.Harness; + +/* How far the six arithmetic closure lemmas of + * `src/language/proof/Axioms.re` can be proved in Hazel itself, rather + * than trusted as axioms. + * + * None of the six can be, and all for the same reason. Rewriting can only + * relate two predicates when some cited equation mentions both, and no + * built-in axiom mentions two different arithmetic comparisons: the + * Kleene axioms are purely boolean (`and_comm`, `impl_def`, ...), + * `refl` is reflexivity, and the only equations relating `>` to `!=`, + * or `a > 0`/`b > 0` to `a * b > 0`, are the six closure lemmas + * themselves, which would be circular. Evaluation can't bridge the gap + * either: on a symbolic operand a comparison is stuck (`NothingToStep`, + * `test_pin_symbolic_comparison_is_stuck`). Proving them needs + * monotonicity reasoning over ordered arithmetic, and + * `pow_pos` also needs induction on the exponent, which no Hazel numeric + * type provides (`test_pin_no_numeric_induction_hypothesis`). + * + * Nor can one lemma be proved from another: no two share a pair of + * comparisons. (`pos_mul` + `nonzero_of_pos` give `nonzero_mul` only for + * positive arguments.) + * + * So the file pins, as Test_Milestone_STLC does, each lemma's longest + * mark-free partial proof, its status, its obligations, and a `FRICTION:` + * note naming what is missing. Also: + * - each lemma's true branch is closed (the bool split substitutes in + * the goal, leaving the literal `true`), so half of each proof is + * real; + * - `nonzero_of_pos`'s a1 == 0 sub-case closes by the revert-based ex + * falso idiom (`test_zero_case_closes_by_ex_falso`); + * - every lemma's closed instances are fully proven by evaluation + * (section D). */ + +let has_mark_kind = Test_ProofMap.has_mark_kind; + +let is_remote = (ob: Obligation.t): bool => + switch (ob.discharge) { + | Remote(_) => true + | _ => false + }; + +let is_evaluated = (ob: Obligation.t): bool => + Poly.equal(ob.discharge, Evaluated); + +/* --- Section A: the six statements ------------------------------------- */ + +/* Each is the corresponding `Axioms.re` entry transcribed into surface + * syntax, identical up to binder names (a/b -> a1/b1). The Axioms.re + * builder is quoted above each one so the correspondence is checkable by + * eye. `==>` is right-associative, and the nested antecedent is written + * without parentheses, the shape `Axioms.foralls` builds. + * + * The conclusions are bare booleans, read as `P == true` + * (`ProofRule.BoolReading`). */ + +/* forall("a", gt0(a) ==>> neq0(a)) */ +let stmt_nonzero_of_pos = "forall a1 -> a1 > 0 ==> a1 != 0"; + +/* forall("a", lt0(a) ==>> neq0(a)) */ +let stmt_nonzero_of_neg = "forall a1 -> a1 < 0 ==> a1 != 0"; + +/* foralls(["a","b"], neq0(a) ==>> (neq0(b) ==>> neq0(mul(a,b)))) */ +let stmt_nonzero_mul = "forall a1 -> forall b1 -> a1 != 0 ==> b1 != 0 ==> a1 * b1 != 0"; + +/* foralls(["a","b"], gt0(a) ==>> (gt0(b) ==>> gt0(mul(a,b)))) */ +let stmt_pos_mul = "forall a1 -> forall b1 -> a1 > 0 ==> b1 > 0 ==> a1 * b1 > 0"; + +/* foralls(["a","b"], gt0(a) ==>> (gt0(b) ==>> gt0(add(a,b)))) */ +let stmt_pos_add = "forall a1 -> forall b1 -> a1 > 0 ==> b1 > 0 ==> a1 + b1 > 0"; + +/* foralls(["a","b"], gt0(a) ==>> (geq0(b) ==>> gt0(pow(a,b)))) */ +let stmt_pow_pos = "forall a1 -> forall b1 -> a1 > 0 ==> b1 >= 0 ==> a1 ** b1 > 0"; + +let theorem = (name: string, stmt: string, proof: string): string => + "theorem " ++ name ++ " = " ++ stmt ++ " proof " ++ proof ++ " in " ++ name; + +/* --- Section B: the six partial proofs ---------------------------------- */ + +/* The shared proof skeleton. The goal core of every closure lemma is + * the bare predicate `P`, so: + * 1. assume-intro each antecedent (no obligation); + * 2. bool-split on P itself. The split substitutes in the goal here + * (P is written exactly as it appears, with no env inlining, + * unlike Test_Milestone_STLC's computed scrutinees), so the + * branches come out as the literals `true` and `false`; + * 3. the true branch's goal is then `true`, and the hole passes it + * through; + * 4. the false branch is where the arithmetic content is, and where + * the proof gets stuck. + * + * FRICTION (all six): in the false branch the goal is `false` with the + * split's `case_eq` (`P == false`) and the intro'd antecedents in scope. + * Closing it means deriving a contradiction between two different + * arithmetic comparisons over a symbolic Int (e.g. `a1 > 0` against + * `(a1 != 0) == false`). Every available move fails: + * - Rewriting needs an equation mentioning both comparisons. The only + * such equations in scope are the six closure lemmas themselves + * (circular). + * - Evaluation is stuck: `a1 > 0` on a symbolic `a1` yields + * `NothingToStep`, so reverting the antecedent into the goal gives + * `a1 > 0 ==> false`, which can't be falsified. Ex falso works only + * once `a1` is a literal (`test_zero_case_closes_by_ex_falso`). + * - Splitting further doesn't help: Int/Nat case analysis is + * `| 0 => | n =>` (a literal and a catch-all, + * `test_pin_no_numeric_induction_hypothesis`), so the catch-all + * branch reproduces the original goal with no inductive hypothesis. + * - Algebrite doesn't close it: a boolean comparison isn't arithmetic + * the CAS verifies, so the step's equation is left open + * (`test_algebrite_leaves_the_lemma_open`). */ +let partial_proof = (antecedents: list(string), predicate: string): string => + List.fold_right( + ~f=(a, rest) => "assume " ++ a ++ " => " ++ rest, + antecedents, + ~init="cases " ++ predicate ++ " | true => ? | false => ? end", + ); + +let src_nonzero_of_pos = + theorem( + "nonzero_of_pos_proved", + stmt_nonzero_of_pos, + partial_proof(["a1 > 0"], "a1 != 0"), + ); + +let src_nonzero_of_neg = + theorem( + "nonzero_of_neg_proved", + stmt_nonzero_of_neg, + partial_proof(["a1 < 0"], "a1 != 0"), + ); + +let src_nonzero_mul = + theorem( + "nonzero_mul_proved", + stmt_nonzero_mul, + partial_proof(["a1 != 0", "b1 != 0"], "a1 * b1 != 0"), + ); + +let src_pos_mul = + theorem( + "pos_mul_proved", + stmt_pos_mul, + partial_proof(["a1 > 0", "b1 > 0"], "a1 * b1 > 0"), + ); + +let src_pos_add = + theorem( + "pos_add_proved", + stmt_pos_add, + partial_proof(["a1 > 0", "b1 > 0"], "a1 + b1 > 0"), + ); + +let src_pow_pos = + theorem( + "pow_pos_proved", + stmt_pow_pos, + partial_proof(["a1 > 0", "b1 >= 0"], "a1 ** b1 > 0"), + ); + +/* Every partial proof pins identically: mark-free (every retained step + * goes through), no pending obligations, and `Incomplete`, with one + * hole per lemma. The true branch really is proven; only the + * false branch is open. */ +let check_partial = (name: string, src: string, expected_obs: int): unit => { + let (pm, proof) = run_named(name, src); + check_mark_free(name, pm, proof); + check_obligation_count( + name ++ ": obligation count", + expected_obs, + pm, + proof, + ); + if (List.exists( + ~f=Obligation.is_pending, + ProofMap.obligations_of_proof(pm, proof), + )) { + Alcotest.fail( + name ++ ": no obligation should be Pending\n" ++ dump(pm, proof), + ); + }; + check_status( + name ++ " pins as Incomplete (one documented false-branch hole)", + ProofMap.Incomplete, + pm, + proof, + ); +}; + +let test_nonzero_of_pos_partial = () => + check_partial("nonzero_of_pos_proved", src_nonzero_of_pos, 0); +let test_nonzero_of_neg_partial = () => + check_partial("nonzero_of_neg_proved", src_nonzero_of_neg, 0); +let test_nonzero_mul_partial = () => + check_partial("nonzero_mul_proved", src_nonzero_mul, 0); +let test_pos_mul_partial = () => + check_partial("pos_mul_proved", src_pos_mul, 0); +let test_pos_add_partial = () => + check_partial("pos_add_proved", src_pos_add, 0); + +/* pow_pos is the only one of the six that incurs an obligation: the bool + * split's domain scan sees `a1 ** b1` and emits `b1 >= 0`, which + * discharges Remote against the intro'd second antecedent. */ +let test_pow_pos_partial = () => { + check_partial("pow_pos_proved", src_pow_pos, 1); + let (pm, proof) = run_named("pow_pos_proved", src_pow_pos); + switch (ProofMap.obligations_of_proof(pm, proof)) { + | [ob] => + Test_ProofMap.check_exp( + "pow_pos's split emits the ** domain condition", + "b1 >= 0", + ob.goal, + ); + Alcotest.check( + Alcotest.bool, + "discharged Remote against the intro'd antecedent", + true, + is_remote(ob), + ); + | obs => + Alcotest.fail( + "expected exactly one obligation, got " + ++ string_of_int(List.length(obs)), + ) + }; +}; + +/* The half that is proven: the true branch of each split reaches + * `true`, so "Incomplete" above is one open branch rather than a proof + * that never started. The split closes the branch: its goal is already + * `true`. + * + * The false branch's goal is the literal `false`, and + * `ProofMap.status_of_proof` reads a `false` outgoing as refuted, so the + * open branch of a partially proven boolean lemma reports `Some(false)`, + * not `None`. That is sound, and the theorem's own status is still + * Incomplete (`check_partial`): the branch has been driven to `false`, + * and what remains is to contradict it against the split's `case_eq`. + * But the stepper shows such a branch as disproven rather than + * unknown. */ +let test_true_branch_is_really_closed = () => { + let (pm, proof) = run_named("nonzero_of_pos_proved", src_nonzero_of_pos); + let rec find_split = (p: Proof.t): option(Proof.t) => + switch (p.term) { + | Cases(_, _) => Some(p) + | Assume(_, _, b) + | Forall(_, b) + | Generalize(_, b) + | Revert(_, _, b) => find_split(b) + | Seq(a, b) => + switch (find_split(a)) { + | Some(x) => Some(x) + | None => find_split(b) + } + | _ => None + }; + switch (find_split(proof)) { + | Some({term: Cases(_, [(_, true_body), (_, false_body)]), _}) => + Alcotest.check( + Alcotest.option(bool), + "the true branch proves (outgoing is literal true)", + Some(true), + ProofMap.status_of_proof(pm, true_body), + ); + Alcotest.check( + Alcotest.option(bool), + "the false branch is the open one, driven to the literal `false`", + Some(false), + ProofMap.status_of_proof(pm, false_body), + ); + | _ => Alcotest.fail("expected a two-case bool split\n" ++ dump(pm, proof)) + }; +}; + +/* --- Section C: friction pins ------------------------------------------- + * + * The checker facts the header's conclusion rests on. Each fails if the + * limitation goes away, which is the signal to revisit this file. */ + +/* (C1) A comparison on a symbolic operand doesn't step, so closed + * evaluation can't decide it and ex falso has nothing to compute + * with. */ +let test_pin_symbolic_comparison_is_stuck = () => { + let (pm, proof) = + run_named( + "t", + theorem( + "t", + stmt_nonzero_of_pos, + "assume a1 > 0 => from a1 != 0 do step end; ?", + ), + ); + if (! + has_mark_kind( + pm, + proof, + fun + | ProofMark.NothingToStep => true + | _ => false, + )) { + Alcotest.fail( + "a symbolic `a1 != 0` unexpectedly stepped -- evaluation gained " + ++ "symbolic arithmetic; revisit the closure-library verdict!\n" + ++ dump(pm, proof), + ); + }; +}; + +/* (C2) No numeric induction. `induction` on an Int or Nat binder is + * accepted, but the only patterns available are a literal and a + * catch-all variable: there is no successor pattern, hence no inductive + * hypothesis (`ih_n` is not even in scope). This is what blocks `pow_pos`: + * its proof wants induction on the exponent with a quantified IH, and + * `generalize` can supply the quantification but there is no induction + * principle to hand it to. + * + * Making the exponent a `Nat` doesn't help: Nat is an atom type, not an + * inductive one (the probe below is over Nat and still has no `ih_n`), and + * `**` parses to the Int operator class, so a Nat-typed variant would be + * a lemma about a different operator. */ +let test_pin_no_numeric_induction_hypothesis = () => { + let (pm, proof) = + run_named( + "t", + "theorem t = forall a1: Nat -> a1 != 0 proof induction a1 " + ++ "| 0 => ? | n => from n != 0 do rewrite ih_n end end end in t", + ); + if (! + has_mark_kind( + pm, + proof, + fun + | ProofMark.UnknownEquality("ih_n") => true + | _ => false, + )) { + Alcotest.fail( + "a numeric induction produced an `ih_n` -- an induction principle " + ++ "for Nat/Int landed; pow_pos may now be provable!\n" + ++ dump(pm, proof), + ); + }; +}; + +/* (C3) Algebrite can't prove a closure lemma. `algebra true` on + * `a1 != 0` is a boolean comparison, not Int arithmetic the CAS + * verifies, so its equation is left open and the lemma isn't plain + * Proven. */ +let test_algebrite_leaves_the_lemma_open = () => { + let (pm, proof) = + run_named( + "t", + theorem( + "t", + stmt_nonzero_of_pos, + "assume a1 > 0 => from a1 != 0 do algebra true end end", + ), + ); + Alcotest.check( + Alcotest.bool, + "an unverified Algebrite rewrite leaves the lemma open", + true, + switch (ProofMap.full_status_of_proof(pm, proof)) { + | ProvenModulo([{kind: Algebra, _}]) => true + | _ => false + }, + ); +}; + +/* (C4) A nested antecedent in parentheses, as `Axioms.re`'s `==>>` + * reads, is introduced as the bare one is. */ +let test_parens_nested_antecedent_introduced = () => { + let parenthesised = "forall a1 -> forall b1 -> a1 != 0 ==> (b1 != 0 ==> a1 * b1 != 0)"; + let (pm, proof) = + run_named( + "t", + theorem( + "t", + parenthesised, + partial_proof(["a1 != 0", "b1 != 0"], "a1 * b1 != 0"), + ), + ); + check_obligation_count( + "the parenthesised nested antecedent is introduced", + 0, + pm, + proof, + ); +}; + +/* (C5) The false branch's a1 == 0 sub-case does close, by the + * revert-based ex falso idiom. Split the symbolic `a1` into the literal + * `0` and a catch-all; in the `0` branch the split's `case_eq` is + * `a1 == 0`, which rewrites `a1` to `0` inside the reverted antecedent, + * evaluation falsifies `0 > 0`, and `==>` collapses the goal to `true`. + * Only the catch-all branch (an arbitrary Int) stays open: the missing + * induction principle of (C2). The obstacle is symbolic operands, not + * the idiom. */ +let ex_falso_src = + theorem( + "t", + stmt_nonzero_of_pos, + "assume a1 > 0 => cases a1 != 0 " + ++ "| true => ? " + ++ "| false => cases a1 " + /* Inside the inner `a1` split, `case_eq` denotes that split's + * equation, which shadows the enclosing `a1 != 0` one. */ + ++ "| 0 => revert a1 > 0 => from a1 do rewrite case_eq end end; " + ++ "from 0 > 0 do step end; from false ==> false do step end " + ++ "| n => ? end end", + ); + +let test_zero_case_closes_by_ex_falso = () => { + let (pm, proof) = run_named("t", ex_falso_src); + check_mark_free("ex falso probe", pm, proof); + let rec find_revert = (p: Proof.t): option(Proof.t) => + switch (p.term) { + | Revert(_, _, _) => Some(p) + | Assume(_, _, b) + | Forall(_, b) + | Generalize(_, b) => find_revert(b) + | Seq(a, b) => + switch (find_revert(a)) { + | Some(x) => Some(x) + | None => find_revert(b) + } + | Cases(_, cases) + | Induction(_, cases) => + List.fold_left( + ~f= + (acc, (_, body)) => + switch (acc) { + | Some(_) => acc + | None => find_revert(body) + }, + ~init=None, + cases, + ) + | _ => None + }; + switch (find_revert(proof)) { + | Some(revert_node) => + Alcotest.check( + Alcotest.option(bool), + "the a1 == 0 sub-case closes outright (ex falso)", + Some(true), + ProofMap.status_of_proof(pm, revert_node), + ) + | None => Alcotest.fail("no revert node found\n" ++ dump(pm, proof)) + }; + check_status( + "the lemma is still Incomplete (the catch-all branch is open)", + ProofMap.Incomplete, + pm, + proof, + ); +}; + +/* --- Section D: closed instances -------------------------------------- + * + * The lemmas can't be proved in general, but every closed instance of + * each (the whole `==>` statement instantiated at literals) is decided + * by evaluation, so a `have` of one with no subproof discharges as + * `Evaluated`. That spot-checks that every closed instance of a theorem + * evaluates to true. + * + * Two instances per lemma, including boundary cases: a negative factor + * for `nonzero_mul`, `b1 == 0` for `pow_pos` (5 ** 0 == 1 > 0, the case + * the `b >= 0` guard exists to admit while excluding negatives). */ + +let closed_instance = (name: string, fact: string): string => + theorem( + name, + "1 == 1", + "have " ++ fact ++ " proof ? => from 1 == 1 do rewrite refl end end", + ); + +let instances: list((string, string)) = [ + ("nonzero_of_pos_at_7", "7 > 0 ==> 7 != 0"), + ("nonzero_of_pos_at_1", "1 > 0 ==> 1 != 0"), + ("nonzero_of_neg_at_neg3", "-3 < 0 ==> -3 != 0"), + ("nonzero_of_neg_at_neg1", "-1 < 0 ==> -1 != 0"), + ("nonzero_mul_at_2_3", "2 != 0 ==> 3 != 0 ==> 2 * 3 != 0"), + ("nonzero_mul_at_neg2_5", "-2 != 0 ==> 5 != 0 ==> -2 * 5 != 0"), + ("pos_mul_at_2_3", "2 > 0 ==> 3 > 0 ==> 2 * 3 > 0"), + ("pos_mul_at_1_1", "1 > 0 ==> 1 > 0 ==> 1 * 1 > 0"), + ("pos_add_at_2_3", "2 > 0 ==> 3 > 0 ==> 2 + 3 > 0"), + ("pos_add_at_1_7", "1 > 0 ==> 7 > 0 ==> 1 + 7 > 0"), + ("pow_pos_at_2_3", "2 > 0 ==> 3 >= 0 ==> 2 ** 3 > 0"), + ("pow_pos_at_5_0", "5 > 0 ==> 0 >= 0 ==> 5 ** 0 > 0"), +]; + +let check_instance = ((name, fact)): unit => { + let src = closed_instance(name, fact); + let (pm, proof) = run_named(name, src); + check_mark_free(name, pm, proof); + switch (ProofMap.obligations_of_proof(pm, proof)) { + | [ob] when is_evaluated(ob) => () + | obs => + Alcotest.fail( + name + ++ ": expected exactly one Evaluated obligation, got " + ++ String.concat(~sep=", ", List.map(~f=show_obligation, obs)) + ++ "\n" + ++ dump(pm, proof), + ) + }; + check_status(name ++ " is fully Proven", ProofMap.Proven, pm, proof); +}; + +let test_instances = () => List.iter(~f=check_instance, instances); + +/* --- How the obligations are discharged ------------------------------- + * + * Every obligation the file incurs, by how it was discharged: all 13 by + * lookup or closed evaluation. That says nothing about proof + * completeness: the six open false branches incur no obligation. */ + +let all_workload: list((string, string)) = + [ + ("nonzero_of_pos_proved", src_nonzero_of_pos), + ("nonzero_of_neg_proved", src_nonzero_of_neg), + ("nonzero_mul_proved", src_nonzero_mul), + ("pos_mul_proved", src_pos_mul), + ("pos_add_proved", src_pos_add), + ("pow_pos_proved", src_pow_pos), + ] + @ List.map( + ~f=((name, fact)) => (name, closed_instance(name, fact)), + instances, + ); + +let test_channel_distribution = () => { + let (remote, evaluated, pending) = + List.fold_left( + ~f= + ((r, e, p), (name, src)) => { + let (pm, proof) = run_named(name, src); + List.fold_left( + ~f= + ((r, e, p), ob: Obligation.t) => + switch (ob.discharge) { + | Remote(_) => (r + 1, e, p) + | Evaluated => (r, e + 1, p) + | Pending => (r, e, p + 1) + }, + ~init=(r, e, p), + ProofMap.obligations_of_proof(pm, proof), + ); + }, + ~init=(0, 0, 0), + all_workload, + ); + + Alcotest.check( + Alcotest.int, + "lookup: pow_pos's ** domain condition", + 1, + remote, + ); + Alcotest.check( + Alcotest.int, + "closed evaluation: the 12 closed instances", + 12, + evaluated, + ); + Alcotest.check(Alcotest.int, "nothing pending", 0, pending); +}; + +let tests = ( + "Evaluator.ClosureLibrary", + [ + test_case( + "nonzero_of_pos: partial, blocked on symbolic order reasoning", + `Quick, + test_nonzero_of_pos_partial, + ), + test_case( + "nonzero_of_neg: partial, blocked on symbolic order reasoning", + `Quick, + test_nonzero_of_neg_partial, + ), + test_case( + "nonzero_mul: partial, blocked on symbolic product reasoning", + `Quick, + test_nonzero_mul_partial, + ), + test_case( + "pos_mul: partial, blocked on sign monotonicity of *", + `Quick, + test_pos_mul_partial, + ), + test_case( + "pos_add: partial, blocked on monotonicity of +", + `Quick, + test_pos_add_partial, + ), + test_case( + "pow_pos: partial; its ** domain condition discharges Remote", + `Quick, + test_pow_pos_partial, + ), + test_case( + "the split's true branch is genuinely closed", + `Quick, + test_true_branch_is_really_closed, + ), + test_case( + "pin: a symbolic comparison does not step", + `Quick, + test_pin_symbolic_comparison_is_stuck, + ), + test_case( + "pin: numeric induction generates no inductive hypothesis", + `Quick, + test_pin_no_numeric_induction_hypothesis, + ), + test_case( + "an unverified Algebrite rewrite leaves the lemma open", + `Quick, + test_algebrite_leaves_the_lemma_open, + ), + test_case( + "a nested antecedent in parentheses is introduced", + `Quick, + test_parens_nested_antecedent_introduced, + ), + test_case( + "the a1 == 0 sub-case closes by ex falso", + `Quick, + test_zero_case_closes_by_ex_falso, + ), + test_case( + "closed instances are fully proven, guards by evaluation", + `Quick, + test_instances, + ), + test_case( + "every obligation discharges by lookup or evaluation", + `Quick, + test_channel_distribution, + ), + ], +); diff --git a/test/evaluator/Test_Definedness.re b/test/evaluator/Test_Definedness.re new file mode 100644 index 0000000000..923bf55acd --- /dev/null +++ b/test/evaluator/Test_Definedness.re @@ -0,0 +1,679 @@ +open Alcotest; +open Language; +open Test_Evaluator_Prelude; +open Test_ProofMap.Harness; +open Poly; + +/* Definedness gates. + * + * Structural totality (Totality.re) refuses possibly-divergent + * instantiations/scrutinees with marks; the domain scan + * (DomainConditions.re) turns partial-primitive applications into + * ordinary boolean obligations. */ + +let check_count = (msg, expected, obs) => + Alcotest.check(Alcotest.int, msg, expected, List.length(obs)); + +let is_divergent_scrutinee: ProofMark.t => bool = + fun + | ProofMark.PossiblyDivergentScrutinee => true + | _ => false; + +let is_float_algebrite: ProofMark.t => bool = + fun + | ProofMark.FloatAlgebrite => true + | _ => false; + +/* An open instantiation containing division: `x := y / z` scans to the + * denominator condition `z != 0`, which stays Pending (open goals are + * never evaluated). */ +let test_open_division_instantiation_pending = () => { + let src = {|theorem u = forall y -> forall z -> y / z == y / z proof from y / z == y / z do rewrite refl end end in u|}; + let (pm, proof, obs) = obligations(src); + check_count("one scanned obligation", 1, obs); + switch (obs) { + | [ob] => + check_exp("the obligation is the denominator", "z != 0", ob.goal); + Alcotest.check( + Alcotest.bool, + "the obligation is pending", + true, + Obligation.is_pending(ob), + ); + | _ => () + }; + switch (ProofMap.full_status_of_proof(pm, proof)) { + | ProvenModulo([_]) => () + | other => + Alcotest.fail( + "expected ProvenModulo with one obligation, got: " + ++ ProofMap.show_full_status(other), + ) + }; +}; + +/* A parenthesized inner binder. `EditorTransform` wraps a spliced + * sub-term in `Parens` whenever it shares a segment level with + * siblings. Binder peeling must look through the parens, or the inner + * binder is never peeled. */ +let test_parenthesized_binder_still_peels = () => { + let src = {|theorem t = forall y -> (forall z -> y + z == y + z) proof from y + z == y + z do rewrite refl end end in t|}; + let (pm, proof, _) = obligations(src); + switch (ProofMap.full_status_of_proof(pm, proof)) { + | ProofMap.Proven => () + | other => + Alcotest.fail( + "expected fully Proven, got: " ++ ProofMap.show_full_status(other), + ) + }; +}; + +/* --- Instantiations that need nothing ------------------------------- */ + +/* The common instantiations, a quantified variable or a sum of them, + * emit no marks and no obligations. */ +let test_instantiation_exemption_var = () => { + let src = {|theorem t = forall x -> x == x proof from x == x do rewrite refl end end in t|}; + let (pm, proof, obs) = obligations(src); + check_count("x := x emits zero obligations", 0, obs); + Alcotest.check( + Alcotest.bool, + "no divergence mark", + false, + has_mark_kind(pm, proof, is_divergent_instantiation), + ); + Alcotest.check( + Alcotest.bool, + "fully Proven", + true, + ProofMap.full_status_of_proof(pm, proof) == ProofMap.Proven, + ); +}; + +let test_instantiation_exemption_total_ops = () => { + let src = {|theorem t = forall a -> forall b -> a + b == a + b proof from a + b == a + b do rewrite refl end end in t|}; + let (pm, proof, obs) = obligations(src); + check_count("x := a + b emits zero obligations", 0, obs); + Alcotest.check( + Alcotest.bool, + "fully Proven", + true, + ProofMap.full_status_of_proof(pm, proof) == ProofMap.Proven, + ); +}; + +/* --- Totality refusal -------------------------------------------------- */ + +/* Instantiating at a call of a general-recursive function is refused: + * divergence is never an obligation. */ +let test_divergent_instantiation_refused = () => { + let src = {|let f = fun n -> if n > 0 then f(n - 1) else 0 in theorem t = f(1) == f(1) proof from f(1) == f(1) do rewrite refl end end in t|}; + let (pm, proof, obs) = obligations(src); + Alcotest.check( + Alcotest.bool, + "PossiblyDivergentInstantiation mark is emitted", + true, + has_mark_kind(pm, proof, is_divergent_instantiation), + ); + check_count("a refused step incurs no obligations", 0, obs); + Alcotest.check( + Alcotest.option(bool), + "the refused proof is not proven", + None, + ProofMap.status_of_proof(pm, proof), + ); +}; + +/* The same recursive call inside an eval step is fine: eval steps + * preserve denotation and have no gates. */ +let test_recursive_call_in_eval_step_ungated = () => { + let src = {|let f = fun n -> if n > 0 then f(n - 1) else 0 in theorem t = f(1) == 0 proof from f(1) do step end in t|}; + let (pm, proof, obs) = obligations(src); + check_count("eval step incurs no obligations", 0, obs); + Alcotest.check( + Alcotest.bool, + "no divergence mark on an eval step", + false, + has_mark_kind(pm, proof, is_divergent_instantiation), + ); +}; + +/* --- Split / induction gate -------------------------------------------- */ + +/* Structural induction on a bare quantified variable emits nothing. The + * binder is annotated so this tests the divergence gate alone: an + * unannotated binder is refused separately, for having an unknown + * scrutinee type (tests below). */ +let test_induction_bare_variable_no_gate = () => { + let src = {|theorem t = forall b: Bool -> b == b proof induction b | true => from true == true do rewrite refl end end | false => from false == false do rewrite refl end end end in t|}; + let (pm, proof, obs) = obligations(src); + check_count("bare-variable induction emits zero obligations", 0, obs); + Alcotest.check( + Alcotest.bool, + "no PossiblyDivergentScrutinee mark", + false, + has_mark_kind(pm, proof, is_divergent_scrutinee), + ); +}; + +/* A computed bool scrutinee (split) is domain-scanned: splitting on + * `x / y == 1` emits `y != 0` on the induction node, path-insensitively, + * before any branch is entered. */ +let test_split_computed_scrutinee_emits_condition = () => { + let src = {|theorem t = forall x -> forall y -> x / y == x / y proof induction x / y == 1 | true => ? | false => ? end in t|}; + let (pm, proof, obs) = obligations(src); + check_count("split emits the denominator condition", 1, obs); + switch (obs) { + | [ob] => + check_exp("the condition is y != 0", "y != 0", ob.goal); + Alcotest.check( + Alcotest.bool, + "the condition is pending", + true, + Obligation.is_pending(ob), + ); + | _ => () + }; + Alcotest.check( + Alcotest.bool, + "a total computed scrutinee is not refused", + false, + has_mark_kind(pm, proof, is_divergent_scrutinee), + ); +}; + +/* A computed scrutinee that calls a recursive function is refused. */ +let test_split_divergent_scrutinee_refused = () => { + let src = {|let f = fun n -> if n > 0 then f(n - 1) else 0 in theorem t = forall x -> x == x proof induction f(1) == 0 | true => ? | false => ? end in t|}; + let (pm, proof, _obs) = obligations(src); + Alcotest.check( + Alcotest.bool, + "PossiblyDivergentScrutinee mark is emitted", + true, + has_mark_kind(pm, proof, is_divergent_scrutinee), + ); +}; + +/* --- Induction exhaustiveness: the scrutinee's type must be known ----- */ + +/* A case split reduces `forall x -> P(x)` to one obligation per case, + * which is only valid if the cases exhaust what `x` ranges over, so the + * check needs to know the scrutinee's type. When it is `Unknown` the + * induction is refused (`InductionScrutineeUntyped`) rather than counted + * as vacuously covered, as the edit-time statics do with the same + * `Coverage.check`. */ + +let is_induction_untyped: ProofMark.t => bool = + fun + | ProofMark.InductionScrutineeUntyped => true + | _ => false; + +let is_induction_not_exhaustive: ProofMark.t => bool = + fun + | ProofMark.InductionNotExhaustive => true + | _ => false; + +let status_of = (src: string): ProofMap.full_status => { + let (state, _, elab) = src |> parse_exp |> eval_with_proof; + let pm = EvaluatorState.get_proof_map(state); + ProofMap.full_status_of_proof(pm, proof_of_named("t", elab)); +}; + +let check_not_proven = (msg, src) => + Alcotest.check( + Alcotest.bool, + msg, + true, + switch (status_of(src)) { + | Incomplete => true + | Proven + | Refuted + | ProvenModulo(_) => false + }, + ); + +let check_mark = (msg, src, pred) => { + let (state, _, elab) = src |> parse_exp |> eval_with_proof; + let pm = EvaluatorState.get_proof_map(state); + Alcotest.check( + Alcotest.bool, + msg, + true, + has_mark_kind(pm, proof_of_named("t", elab), pred), + ); +}; + +/* (1) The scrutinee `z != 0` is a comparison, so it is `Bool`-typed even + * though `z` is an unannotated binder: an ordinary missing-`false`-case + * failure. */ +let user_repro = {|let f = fun x -> 100 / x in +let g = fun w -> 100 / w in +theorem t = forall y -> forall z -> f(y) + 4 / 2 + 8 / z == f(y) + 4 / 2 + 8 / z +proof induction z != 0 | true => from f(y) + 4 / 2 + 8 / z == f(y) + 4 / 2 + 8 / z do rewrite refl end end end +in 0|}; + +let test_user_repro_not_proven = () => { + check_not_proven("the reported repro does not certify", user_repro); + check_mark( + "and it is flagged inexhaustive (Bool scrutinee, `false` case missing)", + user_repro, + is_induction_not_exhaustive, + ); +}; + +/* An untyped scrutinee, a bare unannotated `forall` binder. Non-strict + * `Coverage.check` reports a single-case split on an `Unknown` column as + * exhaustive, which would certify these false theorems; each must be + * refused with `InductionScrutineeUntyped`. */ +let untyped_witnesses = [ + ( + "forall b -> b == true", + {|theorem t = forall b -> b == true proof induction b | true => from true == true do rewrite refl end end end in t|}, + ), + ( + "forall n -> n == 0", + {|theorem t = forall n -> n == 0 proof induction n | 0 => from 0 == 0 do rewrite refl end end end in t|}, + ), + ( + "forall xs -> xs == []", + {|theorem t = forall xs -> xs == [] proof induction xs | [] => from [] == [] do rewrite refl end end end in t|}, + ), +]; + +let test_untyped_scrutinee_witnesses_refused = () => + untyped_witnesses + |> List.iter(~f=((name, src)) => { + check_not_proven("false theorem does not certify: " ++ name, src); + check_mark( + "InductionScrutineeUntyped on: " ++ name, + src, + is_induction_untyped, + ); + }); + +/* (2) Annotated scrutinee, `true` case only: refused by the ordinary + * exhaustiveness path (the type is known, a case is missing). The control + * confirming the bool-split constraints reach Coverage. */ +let test_annotated_true_only_not_proven = () => { + let src = {|theorem t = forall b: Bool -> b == b proof induction b | true => from true == true do rewrite refl end end end in t|}; + check_not_proven("annotated Bool, `true` only, does not certify", src); + check_mark( + "flagged InductionNotExhaustive, not Untyped", + src, + is_induction_not_exhaustive, + ); +}; + +/* An unannotated `funext` binder is bound at the function equality's + * domain, so `induction` on it knows its type even though the statics + * leave the binder `Unknown`. A missing case is then an ordinary + * inexhaustive split, not an untyped scrutinee. */ +let check_funext_binder_typed = (src: string, ()) => + check_mark("inexhaustive, not untyped", src, is_induction_not_exhaustive); + +let funext_ascribed_definition = {|let sum: [Int] -> Int = fun xs -> case xs +| [] => 0 +| x::xs => x + sum(xs) +end +in +theorem t = sum == sum proof funext xs => induction xs | [] => ? end in t|}; + +let funext_annotated_lambdas = {|theorem t = (fun xs:[Int] -> 0) == (fun xs:[Int] -> 0) proof funext ys => induction ys | [] => ? end in t|}; + +/* (3) An annotated scrutinee with both cases certifies. */ +let test_annotated_both_cases_proven = () => { + let src = {|theorem t = forall b: Bool -> b == b proof induction b | true => from true == true do rewrite refl end end | false => from false == false do rewrite refl end end end in t|}; + Alcotest.check( + Alcotest.bool, + "annotated Bool with both cases is Proven", + true, + status_of(src) == ProofMap.Proven, + ); +}; + +/* (4) An untyped scrutinee with both bool cases is refused too. + * `| true | false` only reduces `forall b -> P(b)` to + * `P(true) && P(false)` if `b` really is a boolean; with the type + * unknown, `b` may range over `Int`. The checker doesn't infer `Bool` + * from the case patterns. */ +let test_untyped_both_cases_still_refused = () => { + let src = {|theorem t = forall b -> b == b proof induction b | true => from true == true do rewrite refl end end | false => from false == false do rewrite refl end end end in t|}; + check_not_proven("untyped scrutinee with both bool cases is refused", src); + check_mark("with the untyped mark", src, is_induction_untyped); +}; + +/* Over-refusal guards. Refusing `Unknown` columns must not refuse these. */ + +/* A single wildcard/variable case is a genuine catch-all: it covers any + * type, known or not, so it certifies even on an untyped scrutinee. */ +let test_untyped_wildcard_case_still_proven = () => { + let src = {|theorem t = forall b -> b == b proof induction b | x => from x == x do rewrite refl end end end in t|}; + Alcotest.check( + Alcotest.bool, + "catch-all case on an untyped scrutinee is Proven", + true, + status_of(src) == ProofMap.Proven, + ); +}; + +/* `Unknown` in a position coverage never consults is fine: splitting a + * `[?]` scrutinizes the list spine, not the element type. */ +let test_unknown_element_type_still_proven = () => { + let src = {|theorem t = forall xs: [?] -> xs == xs proof induction xs | [] => from [] == [] do rewrite refl end end | y :: ys => from y :: ys == y :: ys do rewrite refl end end end in t|}; + Alcotest.check( + Alcotest.bool, + "list-of-unknown-element split is Proven", + true, + status_of(src) == ProofMap.Proven, + ); +}; + +/* --- Algebrite gate ----------------------------------------------------- */ + +/* A rewrite whose sides contain division emits the denominator + * obligation (deduplicated across the two sides). Division is outside + * what the CAS verifies, so the step's equation is an obligation too. */ +let test_algebrite_division_obligation = () => { + let src = {|theorem t = forall a -> forall b -> a / b == a / b proof from a / b do algebra a / b end end in t|}; + let (pm, proof, obs) = obligations(src); + let obs = + List.filter(~f=(ob: Obligation.t) => ob.kind == Definedness, obs); + check_count("one deduplicated denominator obligation", 1, obs); + switch (obs) { + | [ob] => check_exp("the condition is b != 0", "b != 0", ob.goal) + | _ => () + }; + Alcotest.check( + Alcotest.bool, + "integer rewrite is not refused as float", + false, + has_mark_kind(pm, proof, is_float_algebrite), + ); +}; + +/* Float-typed Algebrite rewrites are refused: CAS field laws are false + * for IEEE floats. */ +let test_algebrite_float_refused = () => { + let src = {|theorem t = forall x -> x +. 1. ==. x +. 1. proof from x +. 1. do algebra 1. +. x end end in t|}; + let (pm, proof, obs) = obligations(src); + Alcotest.check( + Alcotest.bool, + "FloatAlgebrite mark is emitted", + true, + has_mark_kind(pm, proof, is_float_algebrite), + ); + check_count("a refused rewrite incurs no obligations", 0, obs); +}; + +/* --- Float division is total ----------------------------------------- */ + +/* Float division is IEEE-total: `1. /. 0.` is the value infinity. + * Instantiating at it emits no obligation and no refusal. */ +let test_float_division_is_total = () => { + let src = {|theorem t = 1. /. 0. == 1. /. 0. proof from 1. /. 0. == 1. /. 0. do rewrite refl end end in t|}; + let (pm, proof, obs) = obligations(src); + check_count("float division emits zero obligations", 0, obs); + Alcotest.check( + Alcotest.bool, + "no divergence mark", + false, + has_mark_kind(pm, proof, is_divergent_instantiation), + ); + Alcotest.check( + Alcotest.bool, + "fully Proven", + true, + ProofMap.full_status_of_proof(pm, proof) == ProofMap.Proven, + ); +}; + +/* --- Eval steps stay free --------------------------------------------- */ + +let test_eval_step_division_no_gate = () => { + let src = {|theorem t = 4 / 2 == 2 proof from 4 / 2 do step end; from 2 == 2 do step end in t|}; + let (pm, proof, obs) = obligations(src); + check_count("eval steps over division incur nothing", 0, obs); + Alcotest.check( + Alcotest.bool, + "fully Proven", + true, + ProofMap.full_status_of_proof(pm, proof) == ProofMap.Proven, + ); +}; + +/* --- Scan coverage: builtins ------------------------------------------- */ + +/* `int_mod(a, b)` emits `b != 0`. */ +let test_mod_builtin_condition = () => { + let src = {|theorem t = forall a -> forall b -> int_mod(a, b) == int_mod(a, b) proof from int_mod(a, b) == int_mod(a, b) do rewrite refl end end in t|}; + let (_pm, _proof, obs) = obligations(src); + check_count("one mod obligation", 1, obs); + switch (obs) { + | [ob] => check_exp("the condition is b != 0", "b != 0", ob.goal) + | _ => () + }; +}; + +/* Int power with a variable exponent emits `y >= 0` (NegativeExponent + * is the error; Nat power would be total). */ +let test_power_exponent_condition = () => { + let src = {|theorem t = forall x -> forall y -> x ** y == x ** y proof from x ** y == x ** y do rewrite refl end end in t|}; + let (_pm, _proof, obs) = obligations(src); + check_count("one exponent obligation", 1, obs); + switch (obs) { + | [ob] => check_exp("the condition is y >= 0", "y >= 0", ob.goal) + | _ => () + }; +}; + +/* `int_of_float` at a closed finite float: the `is_finite` condition is + * emitted and discharges by closed evaluation. */ +let test_of_float_is_finite_condition = () => { + let src = {|theorem t = int_of_float(2.5) == int_of_float(2.5) proof from int_of_float(2.5) == int_of_float(2.5) do rewrite refl end end in t|}; + let (pm, proof, obs) = obligations(src); + check_count("one is_finite obligation", 1, obs); + Alcotest.check( + Alcotest.bool, + "discharged by closed evaluation", + true, + switch (obs) { + | [ob] => ob.discharge == Obligation.Evaluated + | _ => false + }, + ); + Alcotest.check( + Alcotest.bool, + "fully Proven", + true, + ProofMap.full_status_of_proof(pm, proof) == ProofMap.Proven, + ); +}; + +/* Closed evaluation of a goal that hits a dynamic error ends at the + * error, not at `true`; a goal with no error reaches its value. The step + * count is capped, so that a loop that doesn't stop at the error fails at + * once instead of running its fuel out. */ +let test_closed_evaluation_stops_at_an_error = () => { + let cap = 20; + let evaluate = (src: string): (string, int) => { + let steps = ref(0); + let step: ProofCheck.step_fn = + (~env, ~at, e) => { + incr(steps); + steps^ > cap ? None : Evaluator.Proofs.step(~env, ~at, e); + }; + let result = + ProofCheck.Discharge.evaluate( + ~step, + ~env=Builtins.env_init, + elaborate(parse_exp(src)), + ); + (print_exp(result), steps^); + }; + List.iter( + ~f= + src => { + let (result, steps) = evaluate(src); + Alcotest.check( + Alcotest.bool, + src ++ " isn't true", + false, + result == "true", + ); + Alcotest.check( + Alcotest.bool, + src ++ " stops at the error", + true, + steps <= 5, + ); + }, + [ + "1 / 0 == 1", + "(fun (x : Int) -> true)(1 / 0)", + {|int_of_string("abc") == 1|}, + ], + ); + List.iter( + ~f= + ((src, expected)) => + Alcotest.check(Alcotest.string, src, expected, fst(evaluate(src))), + [ + ("if false then 1 / 0 == 1 else true", "true"), + ("2 * 3 == 6", "true"), + ("6 / 2 == 3", "true"), + ("2 * 3 == 7", "false"), + ], + ); +}; + +let tests = ( + "Evaluator.Definedness", + [ + test_case( + "closed evaluation stops at a dynamic error", + `Quick, + test_closed_evaluation_stops_at_an_error, + ), + test_case( + "open instantiation with division stays Pending", + `Quick, + test_open_division_instantiation_pending, + ), + test_case( + "instantiation at a quantified variable emits nothing", + `Quick, + test_instantiation_exemption_var, + ), + test_case( + "instantiation at a total-op composition emits nothing", + `Quick, + test_instantiation_exemption_total_ops, + ), + test_case( + "recursive-call instantiation is refused", + `Quick, + test_divergent_instantiation_refused, + ), + test_case( + "recursive call inside an eval step is ungated", + `Quick, + test_recursive_call_in_eval_step_ungated, + ), + test_case( + "bare-variable induction emits no gate traffic", + `Quick, + test_induction_bare_variable_no_gate, + ), + test_case( + "bool split on a computed scrutinee emits its domain condition", + `Quick, + test_split_computed_scrutinee_emits_condition, + ), + test_case( + "bool split on a divergent scrutinee is refused", + `Quick, + test_split_divergent_scrutinee_refused, + ), + test_case( + "induction on a comparison missing the false case does not certify", + `Quick, + test_user_repro_not_proven, + ), + test_case( + "untyped scrutinee cannot certify a false theorem", + `Quick, + test_untyped_scrutinee_witnesses_refused, + ), + test_case( + "annotated scrutinee, true case only, is inexhaustive", + `Quick, + test_annotated_true_only_not_proven, + ), + test_case( + "an ascribed definition types a funext binder", + `Quick, + check_funext_binder_typed(funext_ascribed_definition), + ), + test_case( + "annotated lambdas type a funext binder", + `Quick, + check_funext_binder_typed(funext_annotated_lambdas), + ), + test_case( + "annotated scrutinee with both cases is proven", + `Quick, + test_annotated_both_cases_proven, + ), + test_case( + "untyped scrutinee with both bool cases is still refused", + `Quick, + test_untyped_both_cases_still_refused, + ), + test_case( + "catch-all case on an untyped scrutinee still certifies", + `Quick, + test_untyped_wildcard_case_still_proven, + ), + test_case( + "unknown element type does not block a list split", + `Quick, + test_unknown_element_type_still_proven, + ), + test_case( + "algebrite rewrite emits denominator obligations", + `Quick, + test_algebrite_division_obligation, + ), + test_case( + "float-typed algebrite rewrite is refused", + `Quick, + test_algebrite_float_refused, + ), + test_case( + "float division is IEEE-total: no obligation, no refusal", + `Quick, + test_float_division_is_total, + ), + test_case( + "eval steps over division stay free", + `Quick, + test_eval_step_division_no_gate, + ), + test_case("mod builtin emits b != 0", `Quick, test_mod_builtin_condition), + test_case( + "int power emits exponent >= 0", + `Quick, + test_power_exponent_condition, + ), + test_case( + "int_of_float emits is_finite, closed-evaluated", + `Quick, + test_of_float_is_finite_condition, + ), + test_case( + "a parenthesized binder still peels", + `Quick, + test_parenthesized_binder_still_peels, + ), + ], +); diff --git a/test/evaluator/Test_DefinitionNames.re b/test/evaluator/Test_DefinitionNames.re new file mode 100644 index 0000000000..b99904574a --- /dev/null +++ b/test/evaluator/Test_DefinitionNames.re @@ -0,0 +1,199 @@ +open Language; +open Test_ProofMap.Harness; + +/* Goals and facts name the program's definitions as written, and names + * are resolved by scope. A proof binder that rebinds a name hides the + * facts that mention it, and one that would capture a name the goal + * still uses is marked. One case per kind of binder. */ + +let status_of = (name, src): string => { + let (pm, proof) = run_named(name, src); + switch (ProofMap.full_status_of_proof(pm, proof)) { + | Proven => "Proven" + | ProvenModulo(_) => "ProvenModulo" + | Refuted => "Refuted" + | Incomplete => "Incomplete" + }; +}; + +let check_status = (~theorem="t", expected, src) => { + let (pm, proof) = run_named(theorem, src); + Alcotest.check( + Alcotest.string, + "status\n" ++ dump(pm, proof), + expected, + status_of(theorem, src), + ); +}; + +let check_marked = (~theorem="t", what, pred, src) => { + let (pm, proof) = run_named(theorem, src); + Alcotest.check( + Alcotest.bool, + what ++ "\n" ++ dump(pm, proof), + true, + has_mark_kind(pm, proof, pred), + ); +}; + +let captures: ProofMark.t => bool = + fun + | BinderCaptures(_) => true + | _ => false; + +let len = "let len = fun xs -> case xs | [] => 0 | x :: t => 1 + len(t) end in "; + +let tests = ( + "DefinitionNames", + [ + Alcotest.test_case( + "eval leaves a recursive call named by its definition", + `Quick, + () => { + let (pm, proof) = + run_named( + "t", + len + ++ "theorem t = forall y: Int -> forall ys: [Int] -> len(y :: ys) == 1 + len(ys) proof from len(y :: ys) do step end; ? in t", + ); + let d = dump(pm, proof); + Alcotest.check( + Alcotest.bool, + "the goal after eval names len\n" ++ d, + true, + contains(d, "out: 1 + len(ys) == 1 + len(ys)"), + ); + }, + ), + Alcotest.test_case( + "eval leaves a builtin's recursive call named", + `Quick, + () => { + let (pm, proof) = + run_named( + "t", + "let add = fun (acc, x) -> acc + x in theorem t = forall h: Int -> forall l: [Int] -> forall a: Int -> fold_left(h :: l, add, a) == fold_left(l, add, a + h) proof from fold_left(h :: l, add, a) do step end; ? in t", + ); + let d = dump(pm, proof); + Alcotest.check( + Alcotest.bool, + "the goal after eval names fold_left\n" ++ d, + true, + contains(d, "out: fold_left(l, add, add(a, h))"), + ); + }, + ), + Alcotest.test_case( + "forall: a binder named like a definition hides lemmas about it", + `Quick, + () => + check_marked( + "the lemma about the program's len doesn't apply to the binder", + fun + | RuleDoesNotApply(_) + | UnknownEquality(_) => true + | _ => false, + len + ++ "theorem len_nil = len([]) == 0 proof from len([]) do step end; step in " + ++ "theorem t = forall len: ([Int] -> Int) -> len([]) == 0 proof rewrite len_nil end in t", + ) + ), + Alcotest.test_case( + "forall: eval doesn't unfold a binder named like a definition", + `Quick, + () => + check_marked( + "nothing to step", + fun + | NothingToStep => true + | _ => false, + len + ++ "theorem t = forall len: ([Int] -> Int) -> len([]) == 0 proof from len([]) do step end in t", + ) + ), + Alcotest.test_case( + "funext: a binder free in the functions is marked", `Quick, () => + check_marked( + "captures", + captures, + "let k = 5 in theorem t = (fun z: Int -> k) == (fun z: Int -> 5) proof funext k => rewrite refl end in t", + ) + ), + Alcotest.test_case( + "funext: a binder free in the functions is captured", `Quick, () => + check_status( + ~theorem="bad", + "Incomplete", + "theorem bad = forall y: Int -> (fun z: Int -> y) == (fun z: Int -> z) proof funext y => rewrite refl end in bad", + ) + ), + Alcotest.test_case( + "generalize: facts about the generalized variable are hidden", `Quick, () => + check_status( + ~theorem="bad", + "Incomplete", + "theorem bad = forall x: Int -> x == 0 ==> x == 0 proof assume x == 0 => generalize x => forall x => rewrite assume end in bad", + ) + ), + Alcotest.test_case( + "case pattern: a variable the goal uses outside the scrutinee is marked", + `Quick, + () => + check_marked( + "captures", + captures, + "let k = 0 in theorem t = forall xs: [Int] -> xs == [] || k == 0 proof induction xs | [] => ? | k :: rest => ? end in t", + ) + ), + Alcotest.test_case( + "case pattern: facts about a rebound name are hidden", `Quick, () => + check_status( + ~theorem="bad", + "Incomplete", + "let hd0 = fun l -> case l | [] => true | y :: _ => y == 0 end in " + ++ "theorem bad = forall x: Int -> forall xs: [Int] -> x == 0 ==> hd0(xs) proof assume x == 0 => induction xs | [] => ? | x :: t => step; rewrite assume end in bad", + ) + ), + Alcotest.test_case( + "focus: under a lambda, lemmas about a definition it shadows are hidden", + `Quick, + () => + check_status( + ~theorem="bad", + "Incomplete", + "let k = 0 in theorem k0 = k == 0 proof from k do step end; step in " + ++ "theorem bad = (fun k: Int -> k) == (fun k: Int -> 0) proof from k do rewrite k0 end end; rewrite refl in bad", + ) + ), + Alcotest.test_case( + "have: the hypothesis is hidden under a binder that rebinds its names", + `Quick, + () => + check_status( + ~theorem="bad", + "Incomplete", + "let k = 0 in theorem bad = true ==> (forall k: Int -> k == 0) proof have k == 0 proof step => assume true => forall k => rewrite have end in bad", + ) + ), + Alcotest.test_case( + "assume: the hypothesis is hidden under a binder that rebinds its names", + `Quick, + () => + check_status( + ~theorem="bad", + "Incomplete", + "theorem bad = forall x: Int -> x == 0 ==> (forall x: Int -> x == 0) proof assume x == 0 => forall x => rewrite assume end in bad", + ) + ), + Alcotest.test_case( + "have: an inner fact about a rebound name stays an obligation", + `Quick, + () => + check_status( + ~theorem="bad", + "ProvenModulo", + "theorem bad = forall x: Int -> x == 0 ==> (forall x: Int -> x == 0) proof assume x == 0 => forall x => have h = x == 0 proof ? => from x do rewrite h end end; step in bad", + ) + ), + ], +); diff --git a/test/evaluator/Test_Equiv_Inductions.re b/test/evaluator/Test_Equiv_Inductions.re new file mode 100644 index 0000000000..3876e24780 --- /dev/null +++ b/test/evaluator/Test_Equiv_Inductions.re @@ -0,0 +1,584 @@ +open Alcotest; +open Language; +open Test_ProofMap.Harness; + +/* Harder equivalence proofs: generalize + induction + + * eval/axiom/rewrite. + * + * Three families: + * A. the accumulator pattern, `acc + len(xs) == (xs, acc)`. + * The unaccumulated statement can't close (the IH is at + * accumulator 0 while the residual fold is at 1); `generalize acc` + * fixes that. + * B. reverse involution, `rev(rev(xs)) == xs`, which needs a snoc + * helper that is itself an induction. + * C. a round trip `of_int(to_int(n)) == n` over a recursive ADT. + * + * Families A and B have no hole lemmas. Every + * "Incomplete"/"ProvenModulo" expectation pins a limitation, documented + * at the test: (i) the unaccumulated statement, which shows the wrong + * accumulator rather than a checker limit; (ii) family C's `of_s` + * positivity obligation, not discharged; (iii) the two rewrite/`Nat` + * pins in C. */ + +let has_mark_kind = Test_ProofMap.has_mark_kind; + +let check_incomplete = (msg, pm, proof) => + check_status(msg, ProofMap.Incomplete, pm, proof); + +let has_pattern_not_found = (pm, proof) => + has_mark_kind( + pm, + proof, + fun + | ProofMark.PatternNotFound(_) => true + | _ => false, + ); + +let has_nothing_to_step = (pm, proof) => + has_mark_kind( + pm, + proof, + fun + | ProofMark.NothingToStep => true + | _ => false, + ); + +let has_possibly_divergent = (pm, proof) => + has_mark_kind( + pm, + proof, + fun + | ProofMark.PossiblyDivergentInstantiation(_) => true + | _ => false, + ); + +let has_unknown_equality = (pm, proof) => + has_mark_kind( + pm, + proof, + fun + | ProofMark.UnknownEquality(_) => true + | _ => false, + ); + +/* --- A. len vs a fold: the accumulator pattern ------------------------- */ + +let prelude_a = {|let len = fun xs -> case xs | [] => 0 | _ :: t => 1 + len(t) end in let add1 = fun (acc, _) -> acc + 1 in |}; + +/* Defining equations that close by one `step` + `refl`: `len` is + * an ordinary structural recursion, and `fold_left`/`add1` at the empty + * list reduce to the accumulator. */ +let len_nil = {|theorem len_nil = len([]) == 0 proof from len([]) do step end; from 0 == 0 do rewrite refl end end in |}; +let len_cons = {|theorem len_cons = forall h: Int -> forall t: [Int] -> len(h :: t) == 1 + len(t) proof from len(h :: t) do step end; from 1 + len(t) == 1 + len(t) do rewrite refl end end in |}; +let fold_nil = {|theorem fold_nil = forall a: Int -> fold_left([], add1, a) == a proof from fold_left([], add1, a) do step end; from a == a do rewrite refl end end in |}; +let add1_step = {|theorem add1_step = forall a: Int -> forall b: Int -> add1((a, b)) == a + 1 proof from add1((a, b)) do step end; from a + 1 == a + 1 do rewrite refl end end in |}; + +/* `shuffle` is pure arithmetic and closes by the Algebrite rewrite. */ +let shuffle = {|theorem shuffle = forall a: Int -> forall b: Int -> a + (1 + b) == (a + 1) + b proof from a + (1 + b) do algebra (a + 1) + b end end; from (a + 1) + b == (a + 1) + b do rewrite refl end end in |}; + +/* `fold_cons` closes because: + * (1) the closing `refl` lands on an expression containing + * `fold_left`, which applies its quantified function parameter, + * and a quantified `f` is a total map, so the instantiation gate + * lets it through; + * (2) enough `step` steps make both sides converge to the same `case` + * on `t`, which `refl` matches up to alpha-renaming. + * The left side takes three steps (step the cons, which leaves + * `fold_left(t, add1, add1(a, h))`, apply `add1`, unfold on `t`) and the + * right side one. See test_fold_cons_proves_by_eval. */ +let fold_cons = {|theorem fold_cons = forall h: Int -> forall t: [Int] -> forall a: Int -> fold_left(h :: t, add1, a) == fold_left(t, add1, a + 1) proof from fold_left(h :: t, add1, a) do step; from $e(a, h) do step end; step end; from fold_left(t, add1, a + 1) do step end; rewrite refl end in |}; + +let lemmas_a = + len_nil ++ len_cons ++ fold_nil ++ add1_step ++ shuffle ++ fold_cons; + +let test_a_defining_equations_prove = () => { + let cases = [ + ("len_nil", len_nil), + ("len_cons", len_cons), + ("fold_nil", fold_nil), + ("add1_step", add1_step), + ("shuffle", shuffle), + ]; + List.iter( + ~f= + ((name, lemma)) => { + let (pm, proof) = run_named(name, prelude_a ++ lemma ++ name); + check_proven( + "defining equation " ++ name ++ " closes by eval/rewrite + refl", + pm, + proof, + ); + }, + cases, + ); +}; + +/* The main theorem: `forall xs -> forall acc -> acc + len(xs) == + * fold_left(xs, add1, acc)`. + * + * `generalize acc` makes the IH forall-quantified over the accumulator, + * so the cons case can cite it at `acc + 1`. This version applies the IH + * in the reverse direction (`rewrite <-`), rewriting the fold side back + * into `(acc + 1) + len(xs')`, so the final `refl` lands on a + * `len`-only expression. thm_a_fwd below closes the other way round. */ +let thm_a = {|theorem lenfold = forall xs: [Int] -> forall acc: Int -> acc + len(xs) == fold_left(xs, add1, acc) proof generalize acc => induction xs | [] => forall acc => from len([]) do rewrite len_nil end end; from fold_left([], add1, acc) do rewrite fold_nil end end; from acc + 0 do algebra acc end end; from acc == acc do rewrite refl end end | x :: xs' => forall acc => from len(x :: xs') do rewrite len_cons end end; from fold_left(x :: xs', add1, acc) do rewrite fold_cons end end; from acc + (1 + len(xs')) do rewrite shuffle end end; from fold_left(xs', add1, acc + 1) do rewrite <- ih_xs' end end; from $e == $e do rewrite refl end end end in |}; + +let test_generalized_accumulator_proves = () => { + let (pm, proof) = + run_named("lenfold", prelude_a ++ lemmas_a ++ thm_a ++ "lenfold"); + check_mark_free("the generalized len/fold proof is mark-free", pm, proof); + check_obligation_count("no obligations", 0, pm, proof); + check_proven( + "acc + len(xs) == fold_left(xs, add1, acc) is Proven", + pm, + proof, + ); +}; + +/* The same theorem closing the other way. Here the IH is cited forward, + * rewriting `(acc + 1) + len(xs')` into `fold_left(xs', add1, acc + 1)`, + * so the residual goal is + * `fold_left(xs', add1, acc + 1) == fold_left(xs', add1, acc + 1)` and + * the closing move is a plain `rewrite refl`. That passes the + * instantiation gate although `fold_left` applies its abstract function + * parameter, because a quantified `f` is a total map. */ +let thm_a_fwd = {|theorem lenfoldf = forall xs: [Int] -> forall acc: Int -> acc + len(xs) == fold_left(xs, add1, acc) proof generalize acc => induction xs | [] => forall acc => from len([]) do rewrite len_nil end end; from fold_left([], add1, acc) do rewrite fold_nil end end; from acc + 0 do algebra acc end end; from acc == acc do rewrite refl end end | x :: xs' => forall acc => from len(x :: xs') do rewrite len_cons end end; from fold_left(x :: xs', add1, acc) do rewrite fold_cons end end; from acc + (1 + len(xs')) do rewrite shuffle end end; from (acc + 1) + len(xs') do rewrite ih_xs' end end; from $e == $e do rewrite refl end end end in |}; + +let test_forward_ih_accumulator_proves = () => { + let (pm, proof) = + run_named("lenfoldf", prelude_a ++ lemmas_a ++ thm_a_fwd ++ "lenfoldf"); + check_mark_free("the forward-IH len/fold proof is mark-free", pm, proof); + Alcotest.check( + Alcotest.bool, + "closing refl on a residual fold_left == fold_left is not refused", + false, + has_possibly_divergent(pm, proof), + ); + check_obligation_count("no obligations", 0, pm, proof); + check_proven( + "forward-IH version closes on refl at fold_left == fold_left", + pm, + proof, + ); +}; + +/* `fold_cons` proves by eval alone. One step short, the sides don't + * match yet. */ +let test_fold_cons_proves_by_eval = () => { + let fc = proof => + prelude_a + ++ {|theorem fc = forall h: Int -> forall t: [Int] -> forall a: Int -> fold_left(h :: t, add1, a) == fold_left(t, add1, a + 1) proof |} + ++ proof + ++ {| in fc|}; + let (pm, proof) = + run_named( + "fc", + fc( + {|from fold_left(h :: t, add1, a) do step; from $e(a, h) do step end; step end; from fold_left(t, add1, a + 1) do step end; rewrite refl end|}, + ), + ); + Alcotest.check( + Alcotest.bool, + "eval DOES step fold_left on a cons -- this was never a stuck-step pin", + false, + has_nothing_to_step(pm, proof), + ); + Alcotest.check( + Alcotest.bool, + "and the closing refl is not refused as divergent", + false, + has_possibly_divergent(pm, proof), + ); + check_mark_free("fold_cons by eval is mark-free", pm, proof); + check_proven( + "fold_left(h :: t, add1, a) == fold_left(t, add1, a + 1) by eval + refl", + pm, + proof, + ); + let (pm, proof) = + run_named( + "fc", + fc( + {|from fold_left(h :: t, add1, a) do step; from $e(a, h) do step end end; from fold_left(t, add1, a + 1) do step end; rewrite refl end|}, + ), + ); + check_incomplete( + "fold_cons does not close with the left side one step short", + pm, + proof, + ); +}; + +/* Negative control: without the accumulator generalization the theorem + * is `len(xs) == fold_left(xs, add1, 0)`. In the cons case `fold_cons` + * moves the fold to accumulator `0 + 1`, but the IH only speaks about + * accumulator `0` -- the cited fold does not occur in the goal, hence + * PatternNotFound. This is the accumulator mismatch, concretely. */ +let test_naive_accumulator_is_incomplete = () => { + let src = + prelude_a + ++ lemmas_a + ++ {|theorem naive = forall xs: [Int] -> len(xs) == fold_left(xs, add1, 0) proof induction xs | [] => from len([]) do rewrite len_nil end end; from fold_left([], add1, 0) do rewrite fold_nil end end; from 0 == 0 do rewrite refl end end | x :: xs' => from len(x :: xs') do rewrite len_cons end end; from fold_left(x :: xs', add1, 0) do rewrite fold_cons end end; from fold_left(xs', add1, 0) do rewrite <- ih_xs' end end; from $e == $e do rewrite refl end end end in naive|}; + let (pm, proof) = run_named("naive", src); + Alcotest.check( + Alcotest.bool, + "the IH at accumulator 0 does not occur in the residual goal", + true, + has_pattern_not_found(pm, proof), + ); + check_incomplete("the naive induction does not close", pm, proof); +}; + +/* `refl` is `forall x -> (x == x) == true`, and the instantiation + * gate refuses any instantiation Totality.check can't show total. The + * `fold_left` fix applies its function parameter `f`, an abstract + * variable, but a quantified function parameter is a total map, so + * `fold_left(t, add1, 0) == fold_left(t, add1, 0)` is Proven, like the + * `len` control. (A divergent instantiation such as `omega == omega` is + * still refused; see Test_FunctionTotality.) */ +let test_refl_eq_proves_on_fold_left_expression = () => { + let src = + prelude_a + ++ {|theorem w = forall t: [Int] -> fold_left(t, add1, 0) == fold_left(t, add1, 0) proof from fold_left(t, add1, 0) == fold_left(t, add1, 0) do rewrite refl end end in w|}; + let (pm, proof) = run_named("w", src); + Alcotest.check( + Alcotest.bool, + "refl at a fold_left expression is not refused as divergent", + false, + has_possibly_divergent(pm, proof), + ); + check_mark_free("and it leaves no marks", pm, proof); + check_proven("so X == X over fold_left closes", pm, proof); + /* Control: the same shape over `len` is Proven. */ + let control = + prelude_a + ++ {|theorem w2 = forall t: [Int] -> len(t) == len(t) proof from len(t) == len(t) do rewrite refl end end in w2|}; + let (pm', proof') = run_named("w2", control); + check_proven("control: refl over `len` closes", pm', proof'); +}; + +/* Currying is not a barrier, but the left side's first redex is not its + * root: `fadd(h :: t)(a)` applies `fadd(h :: t)`, which has to step + * first. Focused there, one step applies the outer argument; then the + * left side's root steps to the right side's shape and `refl` + * closes. */ +let test_curried_accumulator_equation_closes_by_focus = () => { + let fadd_cons = proof => + {|let fadd = fun xs -> fun acc -> case xs | [] => acc | _ :: t => fadd(t)(acc + 1) end in theorem fadd_cons = forall h: Int -> forall t: [Int] -> forall a: Int -> fadd(h :: t)(a) == fadd(t)(a + 1) proof |} + ++ proof + ++ {| in fadd_cons|}; + let (pm, proof) = + run_named( + "fadd_cons", + fadd_cons( + {|from fadd(h :: t)(a) do from fadd(h :: t) do step end; step end; rewrite refl end|}, + ), + ); + check_mark_free("the curried cons equation is mark-free", pm, proof); + check_proven("the curried accumulator's cons equation closes", pm, proof); + let (pm, proof) = + run_named( + "fadd_cons", + fadd_cons({|from fadd(h :: t)(a) do step end; rewrite refl end|}), + ); + Alcotest.check( + Alcotest.bool, + "the root of `fadd(h :: t)(a)` is not a redex", + true, + has_nothing_to_step(pm, proof), + ); +}; + +/* Uncurrying the accumulator avoids the counting: the tupled + * `fa((xs, acc))` reduces beta + case in a single `step` step, like + * `len`. */ +let prelude_fu = {|let len = fun xs -> case xs | [] => 0 | _ :: t => 1 + len(t) end in let fa = fun (xs, acc) -> case xs | [] => acc | _ :: t => fa((t, acc + 1)) end in |}; +let lemmas_fu = + len_nil + ++ len_cons + ++ {|theorem fa_nil = forall a: Int -> fa(([], a)) == a proof from fa(([], a)) do step end; from a == a do rewrite refl end end in theorem fa_cons = forall h: Int -> forall t: [Int] -> forall a: Int -> fa((h :: t, a)) == fa((t, a + 1)) proof from fa((h :: t, a)) do step end; from $e == $e do rewrite refl end end in |} + ++ shuffle; +let thm_fu = {|theorem lenfa = forall xs: [Int] -> forall acc: Int -> acc + len(xs) == fa((xs, acc)) proof generalize acc => induction xs | [] => forall acc => from len([]) do rewrite len_nil end end; from fa(([], acc)) do rewrite fa_nil end end; from acc + 0 do algebra acc end end; from acc == acc do rewrite refl end end | x :: xs' => forall acc => from len(x :: xs') do rewrite len_cons end end; from fa((x :: xs', acc)) do rewrite fa_cons end end; from acc + (1 + len(xs')) do rewrite shuffle end end; from fa((xs', acc + 1)) do rewrite <- ih_xs' end end; from $e == $e do rewrite refl end end end in |}; + +let test_uncurried_accumulator_hole_free = () => { + let (pm, proof) = + run_named("lenfa", prelude_fu ++ lemmas_fu ++ thm_fu ++ "lenfa"); + check_mark_free("hole-free accumulator proof is mark-free", pm, proof); + check_obligation_count("no obligations", 0, pm, proof); + check_proven( + "acc + len(xs) == fa((xs, acc)) is Proven with no hole lemmas", + pm, + proof, + ); +}; + +/* --- B. reverse involution -------------------------------------------- */ + +let prelude_b = {|let rev = fun xs -> case xs | [] => [] | x :: t => rev(t) @ [x] end in |}; + +let rev_nil = {|theorem rev_nil = rev([]) == [] proof from rev([]) do step end; from ([]: [Int]) == ([]: [Int]) do rewrite refl end end in |}; +let rev_cons = {|theorem rev_cons = forall x: Int -> forall t: [Int] -> rev(x :: t) == rev(t) @ [x] proof from rev(x :: t) do step end; from rev(t) @ [x] == rev(t) @ [x] do rewrite refl end end in |}; + +/* The append equations. `@` steps on constructor form, so `[] @ m` and + * `(y :: l) @ m` each take one `step` step with `l`/`m` still + * quantified, and `refl` closes (test_append_equations_prove_by_eval). */ +let app_lemmas = {|theorem app_nil_l = forall m: [Int] -> [] @ m == m proof from [] @ m do step end; from m == m do rewrite refl end end in theorem app_cons = forall y: Int -> forall l: [Int] -> forall m: [Int] -> (y :: l) @ m == y :: (l @ m) proof from (y :: l) @ m do step end; from y :: (l @ m) == y :: (l @ m) do rewrite refl end end in |}; + +let lemmas_b = rev_nil ++ rev_cons ++ app_lemmas; + +/* The helper that reverse involution needs, itself an induction over xs + * (with the outer `x` held fixed, so no `generalize` is needed). The nil + * case is pure computation: a focus on `rev([] @ [x])` evaluates it down + * to `[x]`, which `x :: []` also steps to. The cons case is the + * interesting one and closes with app_cons / rev_cons / IH / app_cons / + * rev_cons. */ +let snoc = {|theorem snoc = forall xs: [Int] -> forall x: Int -> rev(xs @ [x]) == x :: rev(xs) proof induction xs | [] => from rev([]) do rewrite rev_nil end end; from rev([] @ [x]) do from [] @ [x] do step end; step; from $e([]) do step end; step end; from x :: [] do step end; rewrite refl end | y :: t => from (y :: t) @ [x] do rewrite app_cons end end; from rev(y :: (t @ [x])) do rewrite rev_cons end end; from rev(t @ [x]) do rewrite ih_t end end; from (x :: rev(t)) @ [y] do rewrite app_cons end end; from rev(y :: t) do rewrite rev_cons end end; from $e == $e do rewrite refl end end end in |}; + +let invol = {|theorem invol = forall xs: [Int] -> rev(rev(xs)) == xs proof induction xs | [] => from rev([]) do rewrite rev_nil end end; from rev([]) do rewrite rev_nil end end; from $e == $e do rewrite refl end end | x :: t => from rev(x :: t) do rewrite rev_cons end end; from rev(rev(t) @ [x]) do rewrite snoc end end; from rev(rev(t)) do rewrite ih_t end end; from $e == $e do rewrite refl end end end in |}; + +let test_rev_defining_equations_prove = () => { + List.iter( + ~f= + ((name, lemma)) => { + let (pm, proof) = run_named(name, prelude_b ++ lemma ++ name); + check_proven("rev equation " ++ name ++ " closes by eval", pm, proof); + }, + [("rev_nil", rev_nil), ("rev_cons", rev_cons)], + ); +}; + +/* `[] @ m` and `(y :: l) @ m` step although `m` is quantified, because + * `@` steps on constructor form: each closes by one `step` + `refl`, + * with no marks. */ +let test_append_equations_prove_by_eval = () => { + let nil_l = {|theorem app_nil_l = forall m: [Int] -> [] @ m == m proof from [] @ m do step end; from m == m do rewrite refl end end in app_nil_l|}; + let (pm, proof) = run_named("app_nil_l", nil_l); + Alcotest.check( + Alcotest.bool, + "`[] @ m` is not stuck", + false, + has_nothing_to_step(pm, proof), + ); + check_mark_free("the `[] @ m` proof is mark-free", pm, proof); + check_proven("`[] @ m == m` is Proven for quantified m", pm, proof); + let cons = {|theorem app_cons = forall y: Int -> forall l: [Int] -> forall m: [Int] -> (y :: l) @ m == y :: (l @ m) proof from (y :: l) @ m do step end; from y :: (l @ m) == y :: (l @ m) do rewrite refl end end in app_cons|}; + let (pm', proof') = run_named("app_cons", cons); + check_mark_free("the `(y :: l) @ m` proof is mark-free", pm', proof'); + check_proven( + "`(y :: l) @ m == y :: (l @ m)` is Proven for quantified l, m", + pm', + proof', + ); +}; + +/* The snoc helper: an induction in its own right, on top of the two + * append lemmas. */ +let test_snoc_proves = () => { + let (pm, proof) = + run_named("snoc", prelude_b ++ lemmas_b ++ snoc ++ "snoc"); + check_mark_free("the snoc induction is mark-free", pm, proof); + check_proven( + "rev(xs @ [x]) == x :: rev(xs) is Proven (induction on xs)", + pm, + proof, + ); +}; + +/* ...and with snoc in hand the involution is a short induction. */ +let test_reverse_involution_proves = () => { + let (pm, proof) = + run_named("invol", prelude_b ++ lemmas_b ++ snoc ++ invol ++ "invol"); + check_mark_free("the involution proof is mark-free", pm, proof); + check_obligation_count("no obligations", 0, pm, proof); + check_proven("rev(rev(xs)) == xs is Proven", pm, proof); +}; + +/* --- C. Nat round trip ------------------------------------------------- */ + +/* The ADT isn't called `Nat`, which is a reserved Hazel type name + * (Token.re / Ctx.re / MakeTerm's `["Nat"] => Atom(Nat)`): + * `type Nat = +Z + S(Nat)` doesn't introduce a recursive ADT, and + * `induction n` over it generates no inductive hypotheses + * (test_nat_is_a_reserved_type_name). */ +let prelude_c = {|type Nt = +Z + S(Nt) in let to_int = fun n -> case n | Z => 0 | S(m) => 1 + to_int(m) end in let of_int = fun k -> if k <= 0 then Z else S(of_int(k - 1)) in |}; + +/* `to_int`'s equations are one-step evals. `of_int(0)` needs three eval + * steps (unfold, decide `0 <= 0`, select the branch). Hazel's `if` has + * no `end` delimiter, and writing one produces a hole-riddled + * elaboration in which of_int looks stuck. */ +let lemmas_c = {|theorem to_z = to_int(Z) == 0 proof from to_int(Z) do step end; from 0 == 0 do rewrite refl end end in theorem to_s = forall m: Nt -> to_int(S(m)) == 1 + to_int(m) proof from to_int(S(m)) do step end; from 1 + to_int(m) == 1 + to_int(m) do rewrite refl end end in theorem of_z = of_int(0) == Z proof from of_int(0) do step end; from $e do step end; from $e do step end; from $e == $e do rewrite refl end end in theorem of_s = forall k: Int -> k > 0 ==> of_int(k) == S(of_int(k - 1)) proof ? in theorem minus_one = forall j: Int -> 1 + j - 1 == j proof from 1 + j - 1 do algebra j end end; from j == j do rewrite refl end end in |}; + +let round = {|theorem round = forall n: Nt -> of_int(to_int(n)) == n proof induction n | Z => from to_int(Z) do rewrite to_z end end; from of_int(0) do rewrite of_z end end; from $e == $e do rewrite refl end end | S(m) => from to_int(S(m)) do rewrite to_s end end; from of_int(1 + to_int(m)) do rewrite of_s end end; from 1 + to_int(m) - 1 do rewrite minus_one end end; from of_int(to_int(m)) do rewrite ih_m end end; from $e == $e do rewrite refl end end end in |}; + +let test_to_int_and_of_int_equations = () => { + let to_z = {|theorem to_z = to_int(Z) == 0 proof from to_int(Z) do step end; from 0 == 0 do rewrite refl end end in to_z|}; + let (pm, proof) = run_named("to_z", prelude_c ++ to_z); + check_proven("to_int(Z) == 0 closes by eval", pm, proof); + let to_s = {|theorem to_s = forall m: Nt -> to_int(S(m)) == 1 + to_int(m) proof from to_int(S(m)) do step end; from 1 + to_int(m) == 1 + to_int(m) do rewrite refl end end in to_s|}; + let (pm, proof) = run_named("to_s", prelude_c ++ to_s); + check_proven("to_int(S(m)) == 1 + to_int(m) closes by eval", pm, proof); + /* of_int isn't stuck: it needs three steps through the `if`. */ + let of_z = {|theorem of_z = of_int(0) == Z proof from of_int(0) do step; from 0 <= 0 do step end; step end; rewrite refl end in of_z|}; + let (pm, proof) = run_named("of_z", prelude_c ++ of_z); + check_proven("of_int(0) == Z closes in three eval steps", pm, proof); +}; + +/* The Algebrite `rewrite` step locates its target up to the environment, + * like axiom steps, so it finds `1 + to_int(m) - 1` after an earlier axiom + * step has left the environment-substituted `to_int` in the goal. */ +let test_rewrite_matches_through_the_environment = () => { + let src = + prelude_c + ++ lemmas_c + ++ {|theorem r = forall n: Nt -> of_int(to_int(n)) == n proof induction n | Z => ? | S(m) => from to_int(S(m)) do rewrite to_s end end; from of_int(1 + to_int(m)) do rewrite of_s end end; from 1 + to_int(m) - 1 do algebra to_int(m) end end end in r|}; + let (pm, proof) = run_named("r", src); + Alcotest.check( + Alcotest.bool, + "the written `1 + to_int(m) - 1` is found by the rewrite step", + false, + has_pattern_not_found(pm, proof), + ); +}; + +/* PIN: shadowing the reserved `Nat` type name yields an induction with + * no IHs (citing `ih_m` is UnknownEquality); the identical program under a + * non-reserved name has the IH available (it doesn't rewrite the goal, + * so the citation is refused for that, not for an unknown name). */ +let test_nat_is_a_reserved_type_name = () => { + let bad = {|type Nat = +Z + S(Nat) in let to_int = fun n -> case n | Z => 0 | S(m) => 1 + to_int(m) end in theorem t = forall n: Nat -> to_int(n) == 0 proof induction n | Z => ? | S(m) => rewrite ih_m end end in t|}; + let (pm, proof) = run_named("t", bad); + Alcotest.check( + Alcotest.bool, + "induction over a `Nat`-named ADT generates no IH", + true, + has_unknown_equality(pm, proof), + ); + let good = {|type Nt = +Z + S(Nt) in let to_int = fun n -> case n | Z => 0 | S(m) => 1 + to_int(m) end in theorem t = forall n: Nt -> to_int(n) == 0 proof induction n | Z => ? | S(m) => rewrite ih_m end end in t|}; + let (pm', proof') = run_named("t", good); + Alcotest.check( + Alcotest.bool, + "under a non-reserved name the IH exists", + false, + has_unknown_equality(pm', proof'), + ); +}; + +/* The round trip: mark-free and ProvenModulo. The single pending + * obligation is `of_s`'s guard instantiated at the cons case, + * `1 + to_int(m) > 0`; discharging it needs `to_int(m) >= 0`, another + * induction over Nt, not supplied here. */ +let test_nat_round_trip_proven_modulo = () => { + let (pm, proof) = + run_named("round", prelude_c ++ lemmas_c ++ round ++ "round"); + check_mark_free("the round-trip proof is mark-free", pm, proof); + let obs = without_citations(ProofMap.obligations_of_proof(pm, proof)); + Alcotest.check( + Alcotest.int, + "exactly one obligation (of_s's positivity guard)", + 1, + List.length(obs), + ); + Alcotest.check( + Alcotest.bool, + "and it is pending", + true, + List.for_all(~f=Obligation.is_pending, obs), + ); + switch (ProofMap.full_status_of_proof(pm, proof)) { + | ProofMap.ProvenModulo(_) => () + | other => + Alcotest.fail( + "expected ProvenModulo, got " + ++ ProofMap.show_full_status(other) + ++ "\n--- proof dump ---\n" + ++ dump(pm, proof), + ) + }; +}; + +let tests = ( + "Equivalence inductions", + [ + test_case( + "A: len/fold/add1 defining equations close by eval", + `Quick, + test_a_defining_equations_prove, + ), + test_case( + "A: generalize acc + induction proves acc + len(xs) == fold_left(xs, add1, acc)", + `Quick, + test_generalized_accumulator_proves, + ), + test_case( + "A: the same theorem closes with the IH cited forward", + `Quick, + test_forward_ih_accumulator_proves, + ), + test_case( + "A: fold_cons closes by eval + refl", + `Quick, + test_fold_cons_proves_by_eval, + ), + test_case( + "A: control -- the naive unaccumulated statement cannot close", + `Quick, + test_naive_accumulator_is_incomplete, + ), + test_case( + "A: refl proves an equation between fold_left expressions", + `Quick, + test_refl_eq_proves_on_fold_left_expression, + ), + test_case( + "A: a curried accumulator's cons equation closes by focusing on its head", + `Quick, + test_curried_accumulator_equation_closes_by_focus, + ), + test_case( + "A: the uncurried accumulator theorem proves with no hole lemmas", + `Quick, + test_uncurried_accumulator_hole_free, + ), + test_case( + "B: rev defining equations close by eval", + `Quick, + test_rev_defining_equations_prove, + ), + test_case( + "B: append equations prove by eval + refl (no holes)", + `Quick, + test_append_equations_prove_by_eval, + ), + test_case( + "B: the snoc helper is itself an induction, and it proves", + `Quick, + test_snoc_proves, + ), + test_case( + "B: reverse involution proves given snoc", + `Quick, + test_reverse_involution_proves, + ), + test_case( + "C: to_int and of_int defining equations close by eval", + `Quick, + test_to_int_and_of_int_equations, + ), + test_case( + "C: rewrite matches through the environment", + `Quick, + test_rewrite_matches_through_the_environment, + ), + test_case( + "C: pin -- `Nat` is reserved, so its induction has no IH", + `Quick, + test_nat_is_a_reserved_type_name, + ), + test_case( + "C: of_int(to_int(n)) == n is ProvenModulo the positivity guard", + `Quick, + test_nat_round_trip_proven_modulo, + ), + ], +); diff --git a/test/evaluator/Test_Evaluator.re b/test/evaluator/Test_Evaluator.re index def4133dfe..4177d62e77 100644 --- a/test/evaluator/Test_Evaluator.re +++ b/test/evaluator/Test_Evaluator.re @@ -15,6 +15,7 @@ let tests = Test_Evaluator_Function.tests, Test_Evaluator_Fixpoint.tests, Test_Evaluator_List.tests, + Test_SymbolicListBuiltins.tests, Test_Evaluator_Atom.tests, Test_Evaluator_Let.tests, Test_Evaluator_Operators.tests, @@ -23,10 +24,31 @@ let tests = Test_Evaluator_BuiltinsTupleOperations.tests, Test_Evaluator_TypAp.tests, Test_Stepper.tests, - Test_StepperBase.tests, + Test_StepperView.tests, + Test_StepSearch.tests, Test_Evaluator_Properties.tests, Test_Evaluator_Performance.tests, Test_Evaluator_Modules.tests, Test_Evaluator_Incremental.tests, Test_Evaluator_IncrCorpus.tests, + Test_OffDomain.tests, + Test_ProofMap.tests, + Test_Definedness.tests, + Test_StructuralRecursion.tests, + Test_FunContracts.tests, + Test_Obligations.tests, + Test_Generalize.tests, + Test_Revert.tests, + Test_CasesInduction.tests, + Test_Instantiation.tests, + Test_Milestone_STLC.tests, + Test_RootMissingRepro.tests, + Test_ClosureLibrary.tests, + Test_Have.tests, + Test_HypothesisNaming.tests, + Test_Funext.tests, + Test_FunctionTotality.tests, + Test_Equiv_Inductions.tests, + Test_ListFoldLibrary.tests, + Test_Focus.tests, ]; diff --git a/test/evaluator/Test_Evaluator_Operators.re b/test/evaluator/Test_Evaluator_Operators.re index 27d64cde79..55d54aa81b 100644 --- a/test/evaluator/Test_Evaluator_Operators.re +++ b/test/evaluator/Test_Evaluator_Operators.re @@ -102,6 +102,22 @@ let tests = ( parse_and_evaluate_test("s1 /. s2", "(s1 /. s2) : Float"); parse_and_evaluate_test("b1 && b2", "(b1 && b2) : Bool"); parse_and_evaluate_test("b1 || b2", "(b1 || b2) : Bool"); + parse_and_evaluate_test("b1 ==> b2", "(b1 ==> b2) : Bool"); + }, + ), + test_case( + "Material implication evaluates McCarthy left-to-right", + `Quick, + () => { + /* A false antecedent short-circuits to true without evaluating + the consequent — even past a domain error. */ + parse_and_evaluate_test("true", "false ==> 1 / 0 == 1"); + parse_and_evaluate_test("false", "true ==> false"); + parse_and_evaluate_test("true", "true ==> true"); + parse_and_evaluate_test("true", "false ==> false"); + /* Nested with other bool ops at the documented precedences: + (a || b) ==> (c && d). */ + parse_and_evaluate_test("false", "false || true ==> true && false"); }, ), ], diff --git a/test/evaluator/Test_Evaluator_Poly_Equal.re b/test/evaluator/Test_Evaluator_Poly_Equal.re index ac4570b7dc..4c60eaef1c 100644 --- a/test/evaluator/Test_Evaluator_Poly_Equal.re +++ b/test/evaluator/Test_Evaluator_Poly_Equal.re @@ -96,6 +96,20 @@ let tests = ( ); }, ), + test_case( + "== is reflexive at nan, ==. is IEEE", + `Quick, + () => { + let evaluates_to = (expected, src) => + evaluation_test(src, bool(expected), elaborate(parse_exp(src))); + evaluates_to(true, "nan == nan"); + evaluates_to(true, "(nan, 1) == (nan, 1)"); + evaluates_to(true, "[nan] == [nan]"); + evaluates_to(false, "nan != nan"); + evaluates_to(true, "0.0 == -0.0"); + evaluates_to(false, "nan ==. nan"); + }, + ), test_case( "Polymorphic Equality Type Inconsistency Dynamics", `Quick, diff --git a/test/evaluator/Test_Focus.re b/test/evaluator/Test_Focus.re new file mode 100644 index 0000000000..bcb85a5246 --- /dev/null +++ b/test/evaluator/Test_Focus.re @@ -0,0 +1,367 @@ +open Alcotest; +open Language; +open Test_ProofMap.Harness; + +/* `from at do end`: the steps act on one + * occurrence of the selector, and their result is put back in the goal. + * The rewrite steps themselves act only at the root of their goal. */ + +let outgoing = (pm: ProofMap.t, p: Proof.t): string => + switch (ProofMap.lookup(Proof.rep_id(p), pm)) { + | Some({outgoing: Some(e), _}) => print_exp(e) + | _ => Alcotest.fail("no outgoing goal recorded\n" ++ dump(pm, p)) + }; + +/* The first step of a chain. */ +let head = (p: Proof.t): Proof.t => + switch (p.term) { + | Seq(first, _) => first + | _ => p + }; + +let focus_body = (p: Proof.t): Proof.t => + switch (p.term) { + | Focus({body, _}) => body + | _ => Alcotest.fail("not a focus: " ++ Proof.show(p)) + }; + +let has = (pred, pm, proof) => has_mark_kind(pm, proof, pred); + +let nothing_to_step: ProofMark.t => bool = + fun + | NothingToStep => true + | _ => false; + +let test_at_selects_the_nth_match = () => { + let (pm, proof) = + run_named( + "t", + "theorem t = (1 + 1) * (1 + 1) == 4 proof from 1 + 1 at 2 do step end; ? in t", + ); + check( + string, + "the second `1 + 1` is evaluated in place", + "(1 + 1) * 2 == 4", + outgoing(pm, head(proof)), + ); +}; + +let test_missing_occurrence_is_marked = () => { + let (pm, proof) = + run_named( + "t", + "theorem t = (1 + 1) * (1 + 1) == 4 proof from 1 + 1 at 3 do step end in t", + ); + check( + bool, + "there is no third `1 + 1`", + true, + has( + fun + | PatternNotFound({ordinal: 3, _}) => true + | _ => false, + pm, + proof, + ), + ); +}; + +let test_steps_chain_inside_a_focus = () => { + let (pm, proof) = + run_named( + "t", + "theorem t = (2 + 3) * 2 == 10 proof from (2 + 3) * 2 do from 2 + 3 do step end; step end; step in t", + ); + check_mark_free("a focus of two steps", pm, proof); + check_proven("its result is lifted into the goal", pm, proof); +}; + +let test_eval_refuses_a_root_that_is_not_a_redex = () => { + let (pm, proof) = run_named("t", "theorem t = 1 + 2 == 3 proof step in t"); + check( + bool, + "`1 + 2 == 3` can't step at its root", + true, + has(nothing_to_step, pm, proof), + ); +}; + +let test_obligations_belong_to_the_inner_step = () => { + let (pm, proof) = + run_named( + "t", + "theorem t = 4 / 2 == 2 proof from 4 / 2 do algebra 2 end end; ? in t", + ); + let focus = head(proof); + let obligations = p => + switch (ProofMap.lookup(Proof.rep_id(p), pm)) { + | Some(entry) => List.length(entry.obligations) + | None => Alcotest.fail("no entry") + }; + check(int, "the focus incurs none", 0, obligations(focus)); + check( + bool, + "the rewrite incurs the divisor's", + true, + obligations(focus_body(focus)) > 0, + ); +}; + +/* Under a binder the variable is fresh: closed parts still evaluate, an + * open part can't, and an outer fact about a same-named variable isn't + * available. */ +let test_eval_under_a_binder = () => { + let (pm, proof) = + run_named( + "t", + "theorem t = (fun x: Int -> 1 + 2) == (fun x: Int -> 3) proof from 1 + 2 do step end; rewrite refl end in t", + ); + check_mark_free("a closed subterm of a lambda body steps", pm, proof); + check_proven("and the lambdas are then equal", pm, proof); +}; + +let test_open_term_does_not_step = () => { + let (pm, proof) = + run_named( + "t", + "theorem t = (fun x: Int -> x + 0) == (fun x: Int -> x) proof from x + 0 do step end in t", + ); + check( + bool, + "`x + 0` with `x` bound by the lambda can't step", + true, + has(nothing_to_step, pm, proof), + ); +}; + +/* Anything but a positive literal after `at` makes the focus a hole. */ +let test_occurrence_is_a_positive_literal = () => + List.iter( + ~f= + at => { + let (_, proof) = + run_named( + "t", + "theorem t = 1 + 1 == 2 proof from 1 + 1 at " + ++ at + ++ " do step end in t", + ); + check( + bool, + "`at " ++ at ++ "` is not a focus", + false, + switch (proof.term) { + | Focus(_) => true + | _ => false + }, + ); + }, + ["0", "x", "?"], + ); + +/* A selector that is just a definition's name finds it in the goal. */ +let test_selector_naming_a_definition = () => { + let (pm, proof) = + run_named( + "t", + "let rev = fun xs -> case xs | [] => [] | x :: t => rev(t) @ [x] end in theorem t = rev([]) == [] proof from rev do step end; ? in t", + ); + check( + bool, + "found\n" ++ dump(pm, proof), + false, + has( + fun + | ProofMark.PatternNotFound(_) => true + | _ => false, + pm, + proof, + ), + ); +}; + +/* `step` on a focused redex contracts it whatever its argument is. */ +let first_outgoing = (src: string): string => { + let (pm, proof) = run_named("t", src); + outgoing(pm, head(proof)); +}; + +let refused = (src: string): bool => { + let (pm, proof) = run_named("t", src); + has(nothing_to_step, pm, proof); +}; + +let test_redexes_contract_at_any_argument = () => { + check( + string, + "a lambda applied to a sum", + "2 + 3 + 1 == 6", + first_outgoing( + "theorem t = (fun x -> x + 1)(2 + 3) == 6 proof from (fun x -> x + 1)(2 + 3) do step end; ? in t", + ), + ); + check( + string, + "a let", + "2 + 3 + 1 == 6", + first_outgoing( + "theorem t = (let x = 2 + 3 in x + 1) == 6 proof from (let x = 2 + 3 in x + 1) do step end; ? in t", + ), + ); + check( + string, + "a named function", + "2 + 3 + 1 == 6", + first_outgoing( + "let inc = fun x -> x + 1 in theorem t = inc(2 + 3) == 6 proof from inc(2 + 3) do step end; ? in t", + ), + ); + check( + string, + "a value argument", + "5 + 1 == 6", + first_outgoing( + "theorem t = (fun x -> x + 1)(5) == 6 proof from (fun x -> x + 1)(5) do step end; ? in t", + ), + ); +}; + +let test_some_redexes_wait_for_a_value = () => { + check( + bool, + "a destructuring parameter needs its argument's shape", + true, + refused( + "theorem t = (fun (a, b) -> a + b)(if true then (1, 2) else (3, 4)) == 3 proof from (fun (a, b) -> a + b)(if true then (1, 2) else (3, 4)) do step end; ? in t", + ), + ); + check( + bool, + "a recursive function unfolds by evaluation", + true, + refused( + "let count = fun n -> if n <= 0 then 0 else count(n - 1) in theorem t = count(1 + 1) == 0 proof from count(1 + 1) do step end; ? in t", + ), + ); + check( + bool, + "a root that isn't a redex, with an operand that isn't a value", + true, + refused("theorem t = 2 + 3 == 5 proof step; ? in t"), + ); +}; + +/* A goal's variables are free, so the argument's must not be captured + * by a binder in the body. */ +let test_contraction_avoids_capture = () => { + check( + string, + "a variable argument", + "(fun y' -> y) == (fun z -> y)", + first_outgoing( + "theorem t = forall y: Int -> (fun x -> fun y -> x)(y) == (fun z -> y) proof from (fun x -> fun y -> x)(y) do step end; ? in t", + ), + ); + check( + string, + "an argument that isn't a value", + "(fun y' -> y + (1 + 1)) == (fun z -> y)", + first_outgoing( + "theorem t = forall y: Int -> (fun x -> fun y -> x)(y + (1 + 1)) == (fun z -> y) proof from (fun x -> fun y -> x)(y + (1 + 1)) do step end; ? in t", + ), + ); + let (pm, proof) = + run_named( + "t", + "theorem t = forall y: Int -> (fun x -> fun y -> x)(y)(0) == 0 proof from (fun x -> fun y -> x)(y) do step end; step; ? in t", + ); + check( + bool, + "so a false statement isn't proved", + false, + Poly.equal(ProofMap.full_status_of_proof(pm, proof), ProofMap.Proven), + ); +}; + +/* The argument has no value, but beta at any argument doesn't ask for + * one, so this is provable. */ +let test_contraction_drops_an_argument_with_no_value = () => { + let (pm, proof) = + run_named( + "t", + "theorem t = (fun x -> 0)(1 / 0) == 0 proof from (fun x -> 0)(1 / 0) do step end; step in t", + ); + check( + bool, + "proven", + true, + Poly.equal(ProofMap.full_status_of_proof(pm, proof), ProofMap.Proven), + ); +}; + +let tests = ( + "Evaluator.Focus", + [ + test_case( + "step contracts a focused redex whatever its argument", + `Quick, + test_redexes_contract_at_any_argument, + ), + test_case( + "destructuring, recursion and other roots wait for a value", + `Quick, + test_some_redexes_wait_for_a_value, + ), + test_case( + "a contraction avoids capture", + `Quick, + test_contraction_avoids_capture, + ), + test_case( + "a contraction can drop an argument with no value", + `Quick, + test_contraction_drops_an_argument_with_no_value, + ), + test_case( + "an occurrence is a positive literal", + `Quick, + test_occurrence_is_a_positive_literal, + ), + test_case( + "at n selects the nth match", + `Quick, + test_at_selects_the_nth_match, + ), + test_case( + "a missing occurrence is marked", + `Quick, + test_missing_occurrence_is_marked, + ), + test_case( + "steps chain inside a focus and the result is lifted", + `Quick, + test_steps_chain_inside_a_focus, + ), + test_case( + "eval refuses a root that is not a redex", + `Quick, + test_eval_refuses_a_root_that_is_not_a_redex, + ), + test_case( + "obligations belong to the inner step", + `Quick, + test_obligations_belong_to_the_inner_step, + ), + test_case("eval under a binder", `Quick, test_eval_under_a_binder), + test_case( + "an open term does not step", + `Quick, + test_open_term_does_not_step, + ), + test_case( + "a selector naming a definition finds it", + `Quick, + test_selector_naming_a_definition, + ), + ], +); diff --git a/test/evaluator/Test_FunContracts.re b/test/evaluator/Test_FunContracts.re new file mode 100644 index 0000000000..66bf098ae8 --- /dev/null +++ b/test/evaluator/Test_FunContracts.re @@ -0,0 +1,107 @@ +open Alcotest; +open Language; +open Test_ProofMap.Harness; +open Poly; + +/* The closure lemmas of Axioms.re, guarded axioms used as ordinary + * conditional rewrite rules. */ + +let check_count = (msg, expected, obs) => + Alcotest.check(Alcotest.int, msg, expected, List.length(obs)); + +let is_remote: Obligation.discharge => bool = + fun + | Obligation.Remote(_) => true + | _ => false; + +/* --- Closure lemmas -------------------------------------------------- */ + +/* Nothing covers the antecedents: ProvenModulo with the two Pending. */ +let test_nonzero_mul_pending_without_binders = () => { + let src = {|theorem t = forall a -> forall b -> a * b != 0 proof from a * b != 0 do rewrite nonzero_mul end end in t|}; + let (pm, proof, obs) = obligations(src); + check_count("the two antecedent obligations", 2, obs); + Alcotest.check( + Alcotest.bool, + "both are Pending", + true, + List.for_all(~f=Obligation.is_pending, obs), + ); + switch (ProofMap.full_status_of_proof(pm, proof)) { + | ProvenModulo([_, _]) => () + | other => + Alcotest.fail( + "expected ProvenModulo with two pending, got: " + ++ ProofMap.show_full_status(other), + ) + }; +}; + +/* Bridging lemma: `nonzero_of_pos` turns a `> 0` fact into the `!= 0` + * an obligation needs, here as an axiom step rewriting the goal + * itself. */ +let test_nonzero_of_pos_bridge = () => { + let src = {|theorem t = forall a -> a > 0 ==> a != 0 proof assume a > 0 => from a != 0 do rewrite nonzero_of_pos end end in t|}; + let (pm, proof, obs) = obligations(src); + check_count("one antecedent obligation", 1, obs); + switch (obs) { + | [ob] => + check_exp("the antecedent is a > 0", "a > 0", ob.goal); + Alcotest.check( + Alcotest.bool, + "discharged Remote against the assumption", + true, + is_remote(ob.discharge), + ); + | _ => () + }; + Alcotest.check( + Alcotest.bool, + "fully Proven", + true, + ProofMap.full_status_of_proof(pm, proof) == ProofMap.Proven, + ); +}; + +/* Closed antecedents just run: `pos_mul` at literals. */ +let test_pos_mul_closed_evaluated = () => { + let src = {|theorem t = 2 * 3 > 0 proof from 2 * 3 > 0 do rewrite pos_mul end end in t|}; + let (pm, proof, obs) = obligations(src); + check_count("the two antecedent obligations", 2, obs); + Alcotest.check( + Alcotest.bool, + "both discharged by closed evaluation", + true, + List.for_all( + ~f=(ob: Obligation.t) => ob.discharge == Obligation.Evaluated, + obs, + ), + ); + Alcotest.check( + Alcotest.bool, + "fully Proven", + true, + ProofMap.full_status_of_proof(pm, proof) == ProofMap.Proven, + ); +}; + +let tests = ( + "Evaluator.FunContracts", + [ + test_case( + "nonzero_mul pending without binders (ProvenModulo)", + `Quick, + test_nonzero_mul_pending_without_binders, + ), + test_case( + "nonzero_of_pos bridges > 0 to != 0", + `Quick, + test_nonzero_of_pos_bridge, + ), + test_case( + "pos_mul closed antecedents evaluate", + `Quick, + test_pos_mul_closed_evaluated, + ), + ], +); diff --git a/test/evaluator/Test_FunctionTotality.re b/test/evaluator/Test_FunctionTotality.re new file mode 100644 index 0000000000..ad18886eb7 --- /dev/null +++ b/test/evaluator/Test_FunctionTotality.re @@ -0,0 +1,269 @@ +open Alcotest; +open Language; +open Test_Evaluator_Prelude; +open Test_ProofMap.Harness; + +/* Totality of functions (see the Totality.re header). + * + * "Total" means one thing: you may evaluate it, and if it is a function + * you may apply it on its type's domain. There is no "total as a value + * but possibly looping as a function". + * + * So a quantified binder of arrow type is a total map: `forall f -> ...` + * licenses `f(x)` and `fold_left(xs, f, acc)`. What is refused is + * instantiating such a binder at a looping closure, and any term that + * reaches a non-structural fixpoint at all, including a bare `omega`, + * since a looping map is not a total value. + * + * Totality is not definedness: `1/0` and `head([])` terminate (in + * `err`), so they stay DomainConditions obligations. `inv = fun x -> + * 1/x` is a total map here. */ + +let marks_of = (pm: ProofMap.t, proof: Proof.t): string => + switch (find_marked_sub(pm, proof)) { + | Some((_, marks)) => + String.concat(~sep="; ", List.map(~f=ProofMark.show, marks)) + | None => "" + }; + +/* Passes the gate silently: no divergence mark, no obligations, and the + * theorem is fully Proven. */ +let expect_pass = (src: string): unit => { + let (pm, proof, obs) = obligations(src); + Alcotest.check( + Alcotest.bool, + "no PossiblyDivergentInstantiation mark, got: " ++ marks_of(pm, proof), + false, + has_mark_kind(pm, proof, is_divergent_instantiation), + ); + Alcotest.check(Alcotest.int, "zero obligations", 0, List.length(obs)); + switch (ProofMap.full_status_of_proof(pm, proof)) { + | ProofMap.Proven => () + | other => + Alcotest.fail( + "expected fully Proven, got: " + ++ ProofMap.show_full_status(other) + ++ "\nmarks: " + ++ marks_of(pm, proof), + ) + }; +}; + +/* Refused: divergence mark, no obligations (divergence is never an + * obligation), not proven. */ +let expect_refused = (src: string): unit => { + let (pm, proof, obs) = obligations(src); + Alcotest.check( + Alcotest.bool, + "PossiblyDivergentInstantiation mark is emitted, marks: " + ++ marks_of(pm, proof), + true, + has_mark_kind(pm, proof, is_divergent_instantiation), + ); + Alcotest.check( + Alcotest.int, + "a refused step incurs no obligations", + 0, + List.length(obs), + ); + Alcotest.check( + Alcotest.option(bool), + "the refused proof is not proven", + None, + ProofMap.status_of_proof(pm, proof), + ); +}; + +/* --- An abstract function is applicable ------------------------------ */ + +/* `forall f -> forall x -> f(x) == f(x)`: neither the arrow-typed `f` + * nor `f(x)`, which has no visible definition, is refused. Both binders + * are annotated so this tests the divergence gate alone (an unannotated + * induction scrutinee is gated separately). */ +let test_abstract_function_applied = () => + expect_pass( + {|theorem t = forall f: (Int -> Int) -> forall x: Int -> f(x) == f(x) proof from f(x) == f(x) do rewrite refl end end in t|}, + ); + +/* --- Higher-order builtins -------------------------------------------- */ + +/* A concrete function through `fold_left`. `fold_left` is itself a + * (structural) Hazel fixpoint whose body applies its own `f` + * parameter, so this exercises the "parameters of a walked body are + * assumed total" rule even with no abstract function in sight. */ +let test_fold_left_concrete_function = () => + expect_pass( + {|let add1 = fun (acc, _) -> acc + 1 in theorem t = forall xs: [Int] -> forall acc: Int -> fold_left(xs, add1, acc) == fold_left(xs, add1, acc) proof from fold_left(xs, add1, acc) == fold_left(xs, add1, acc) do rewrite refl end end in t|}, + ); + +/* An abstract `f` through `fold_left`. Walking + * `fold_left`'s body reaches `f(acc, x)` where `f` is the builtin's own + * parameter, standing for the quantified `f` we passed in — a total map, + * so the application is licensed. */ +/* TODO: the defining equation + * `fold_left(x :: xs, f, acc) == fold_left(xs, f, f(acc, x))` is not + * derivable: `eval fold_left(x :: xs, f, acc) at 0` inlines the + * builtin's fixpoint body but doesn't step the `case` on a symbolic + * `x :: xs`, so the step lands on an unreduced beta-redex and the + * following `refl` reports `PatternNotFound`. That is a limit of + * `step`, not of totality, so this file tests `E == E` instead. */ +let test_fold_left_abstract_function = () => + expect_pass( + {|theorem t = forall f: ((Int, Int) -> Int) -> forall x: Int -> forall xs: [Int] -> forall acc: Int -> fold_left(x :: xs, f, acc) == fold_left(x :: xs, f, acc) proof from fold_left(x :: xs, f, acc) == fold_left(x :: xs, f, acc) do rewrite refl end end in t|}, + ); + +/* --- Totality is not definedness -------------------------------------- */ + +/* `inv` divides. Division terminates (in `err` at 0), so `inv` is a + * total map and `inv == inv` needs no funext and no divergence mark. + * The `y != 0` side of it is DomainConditions' business, and there is + * no division to scan in `inv == inv` itself. */ +let test_inv_refl_no_divergence = () => + expect_pass( + {|let inv = fun x -> 1 / x in theorem t = inv == inv proof from inv == inv do rewrite refl end end in t|}, + ); + +/* The plainest first-order instantiation passes. */ +let test_first_order_var_refl = () => + expect_pass( + {|theorem t = forall x -> x == x proof from x == x do rewrite refl end end in t|}, + ); + +/* --- Refusals --------------------------------------------------------- */ + +/* Non-structural (arithmetic) recursion: `n - 1` is not a subterm. */ +let test_nonstructural_recursion_refused = () => + expect_refused( + {|let f = fun n -> if n > 0 then f(n - 1) else 0 in theorem t = f(1) == f(1) proof from f(1) == f(1) do rewrite refl end end in t|}, + ); + +/* `omega` as a value: a looping map is not total, so `omega == omega` + * is refused even though nothing is applied. */ +let test_omega_as_value_refused = () => + expect_refused( + {|let omega = fun x -> omega(x) in theorem t = omega == omega proof from omega == omega do rewrite refl end end in t|}, + ); + +/* A lambda whose body loops is not a total value either: Totality + * looks at lambda bodies. */ +let test_lambda_with_divergent_body_refused = () => + expect_refused( + {|let omega = fun x -> omega(x) in theorem t = (fun y -> omega(y)) == (fun y -> omega(y)) proof from (fun y -> omega(y)) == (fun y -> omega(y)) do rewrite refl end end in t|}, + ); + +/* --- Instantiating a quantified function at a diverging function ------ */ + +/* The quantifier ranges over total maps, so the obligation to be total + * lands here: `lem`'s `f` may not be instantiated at `omega`. */ +let omega_lem = + "let omega = fun x -> omega(x) in " + /* A theorem statement's outer binders are auto-introduced + * (ProofCheck.peel_stmt_binders), so no explicit `forall f =>` step. */ + ++ "theorem lem = forall f: (Int -> Int) -> f(0) == f(0) proof from f(0) == f(0) do rewrite refl end end in "; + +let test_lemma_is_proven = () => { + let (state, _, elab) = omega_lem ++ "lem" |> parse_exp |> eval_with_proof; + let pm = EvaluatorState.get_proof_map(state); + let proof = proof_of_named("lem", elab); + switch (ProofMap.full_status_of_proof(pm, proof)) { + | ProofMap.Proven => () + | other => + Alcotest.fail( + "the quantified-function lemma should be Proven, got: " + ++ ProofMap.show_full_status(other) + ++ "\nmarks: " + ++ marks_of(pm, proof), + ) + }; +}; + +/* Mirrors Test_Instantiation's `with n = bad(1)` fixture, with the + * instantiated binder function-typed: `h` appears only in the + * antecedent, so the target `inc(2)` leaves it underdetermined and + * `with h = omega` is what supplies it — straight into the gate. + * (The lemma itself is a hole here; the Proven quantified-function + * lemma is covered by `test_lemma_is_proven` above.) */ +let test_instantiation_at_omega_refused = () => { + let src = + "let omega = fun x -> omega(x) in " + ++ "let inc = fun x -> x + 1 in " + ++ "theorem lem = forall h: (Int -> Int) -> h(1) == 1 ==> inc(2) == 3 proof ? in " + ++ "theorem g = inc(2) == 3 proof from inc(2) do rewrite lem with h = omega end end in g"; + let (state, _, elab) = src |> parse_exp |> eval_with_proof; + let pm = EvaluatorState.get_proof_map(state); + let proof = proof_of_named("g", elab); + if (!has_mark_kind(pm, proof, is_divergent_instantiation)) { + Alcotest.fail( + "instantiating a quantified function at `omega` should be refused\n" + ++ dump(pm, proof), + ); + }; +}; + +/* The same with no annotations: this doesn't depend on the statics + having resolved the binder's type. */ +let test_abstract_function_applied_unannotated = () => + expect_pass( + {|theorem t = forall f -> forall x -> f(x) == f(x) proof from f(x) == f(x) do rewrite refl end end in t|}, + ); + +let tests = ( + "Evaluator.FunctionTotality", + [ + test_case( + "an abstract quantified function is applicable", + `Quick, + test_abstract_function_applied, + ), + test_case( + "an unannotated abstract function is applicable", + `Quick, + test_abstract_function_applied_unannotated, + ), + test_case( + "fold_left with a concrete function passes", + `Quick, + test_fold_left_concrete_function, + ), + test_case( + "fold_left with an abstract function passes", + `Quick, + test_fold_left_abstract_function, + ), + test_case( + "inv == inv needs no divergence mark", + `Quick, + test_inv_refl_no_divergence, + ), + test_case( + "first-order forall x -> x == x still passes", + `Quick, + test_first_order_var_refl, + ), + test_case( + "non-structural recursion is still refused", + `Quick, + test_nonstructural_recursion_refused, + ), + test_case( + "omega as a value is refused", + `Quick, + test_omega_as_value_refused, + ), + test_case( + "a lambda with a divergent body is refused", + `Quick, + test_lambda_with_divergent_body_refused, + ), + test_case( + "the quantified-function lemma is Proven", + `Quick, + test_lemma_is_proven, + ), + test_case( + "instantiating at omega is refused", + `Quick, + test_instantiation_at_omega_refused, + ), + ], +); diff --git a/test/evaluator/Test_Funext.re b/test/evaluator/Test_Funext.re new file mode 100644 index 0000000000..58637120ea --- /dev/null +++ b/test/evaluator/Test_Funext.re @@ -0,0 +1,596 @@ +open Alcotest; +open Language; +open Test_Evaluator_Prelude; +open Test_ProofMap.Harness; +open Poly; + +/* `funext x => `: functional extensionality as a proof form, not + * an axiom. An axiom is a rewrite equality; stating funext as one would + * have to quantify over functions at unknown/hole types. Funext is an + * intro rule, like `forall x =>` and `assume`. + * + * Rule: with incoming goal `f == g` at an arrow type, the body's incoming + * goal is the pointwise `f(x) == g(x)` and `x` is bound at the domain + * type. Outgoing is `true` when the body closes that; otherwise the outer + * `f == g` passes through (same convention as Forall). */ + +let full_status = (src: string): ProofMap.full_status => { + let (pm, proof) = run(src); + ProofMap.full_status_of_proof(pm, proof); +}; + +let check_status = (msg: string, expected: ProofMap.full_status, src: string) => { + let actual = full_status(src); + Alcotest.check( + Alcotest.bool, + msg ++ " (got: " ++ ProofMap.show_full_status(actual) ++ ")", + true, + actual == expected, + ); +}; + +/* The immediate body of a `funext` node — the sub-proof that sees the + * pointwise goal. */ +let funext_body = (p: Proof.t): Proof.t => + switch (p.term) { + | Funext(_, body) => body + | _ => Alcotest.fail("expected the proof to be a funext node") + }; + +/* --- 1. Happy path ---------------------------------------------------- */ + +/* The commuting pointwise-as-functions theorem. `funext x` turns the + * function equality into `(fun x -> x + 1)(x) == (fun x -> 1 + x)(x)`, + * the rewrite commutes the left body, and refl closes it. Fully Proven. */ +let test_happy_path_proven = () => + check_status( + "pointwise commute proves as a function equality", + ProofMap.Proven, + {|theorem t = (fun x: Int -> x + 1) == (fun x: Int -> 1 + x) proof funext x => from x + 1 do algebra 1 + x end end; from 1 + x == 1 + x do rewrite refl end end in t|}, + ); + +/* The body's incoming goal is the pointwise one. When a side is a + * literal lambda, the application is a beta-redex whose contraction is + * definitional, so the goal the body sees is the contracted `x + 1 == 1 + x` + * — which is what makes a plain pointwise `rewrite` reach it. */ +let test_body_goal_is_pointwise = () => { + let src = {|theorem t = (fun x -> x + 1) == (fun x -> 1 + x) proof funext x => ? in t|}; + let (pm, proof) = run(src); + let goal = incoming_of(pm, funext_body(proof)); + check_exp( + "the body sees the contracted pointwise goal (got: " + ++ print_exp(goal) + ++ ")", + "x + 1 == 1 + x", + goal, + ); +}; + +/* A named function stays an application: unfolding a definition is + * `step`'s job, not funext's. This keeps + * `refl` on `inv(x) == inv(x)` a claim about `inv` applied to an + * arbitrary argument rather than a claim about `inv`'s body. */ +let test_named_function_stays_applied = () => { + let src = {|let inv = fun x -> 1 / x in theorem t = inv == inv proof funext x => ? in t|}; + let (pm, proof) = run(src); + let goal = incoming_of(pm, funext_body(proof)); + let is_ap = (e: Exp.t) => + switch (e |> Exp.term_of) { + | Ap(_, _, _) => true + | _ => false + }; + switch (goal |> Exp.term_of) { + | BinOp(Poly(Equals), l, r) => + Alcotest.check( + Alcotest.bool, + "both sides stay applications for a named function (got: " + ++ print_exp(goal) + ++ ")", + true, + is_ap(l) && is_ap(r), + ) + | _ => + Alcotest.fail("expected an `==` body goal, got: " ++ print_exp(goal)) + }; +}; + +/* And that pointwise goal closes by reflexivity without ever applying + * `inv`, which is a different claim from `inv == (fun x -> 1 / x)` (see + * the partiality test below). */ +let test_named_function_refl_proves = () => + check_status( + "`inv == inv` closes pointwise by refl without applying inv", + ProofMap.Proven, + {|let inv = fun x -> 1 / x in theorem t = inv == inv proof funext x => from inv(x) == inv(x) do rewrite refl end end in t|}, + ); + +/* --- 2. Control: refl at identical functions, without funext ---------- */ + +/* `f == f` between two syntactically identical lambdas closes by + * reflexivity with no funext. */ +let test_refl_identical_functions_no_funext = () => + check_status( + "refl closes identical function literals without funext", + ProofMap.Proven, + {|theorem t = (fun x -> x + 1) == (fun x -> x + 1) proof from (fun x -> x + 1) == (fun x -> x + 1) do rewrite refl end end in t|}, + ); + +/* --- 3. Malformed: funext on a non-function equality ------------------ */ + +/* `1 == 1` is an equality, but not at an arrow type: there is no + * pointwise goal to form. Mark and pass the goal through, the same + * recovery `forall` uses for `ExpectedForallGoal`. */ +let test_non_arrow_equality_marked = () => { + let src = {|theorem t = 1 == 1 proof funext x => ? in t|}; + let (pm, proof) = run(src); + Alcotest.check( + Alcotest.bool, + "ExpectedFunEqGoal is emitted on a non-arrow `==`", + true, + has_mark_kind( + pm, + proof, + fun + | ProofMark.ExpectedFunEqGoal => true + | _ => false, + ), + ); + Alcotest.check( + Alcotest.bool, + "a marked funext does not prove the theorem", + false, + ProofMap.full_status_of_proof(pm, proof) == ProofMap.Proven, + ); +}; + +/* --- 4. Control: the hole, with no funext ----------------------------- */ + +/* A bare hole against a function equality is Incomplete. If this flips + * to Proven, function `==` has started to compute, which would be + * wrong. */ +let test_hole_without_funext_incomplete = () => + check_status( + "a hole against a function equality stays Incomplete", + ProofMap.Incomplete, + {|theorem t = (fun x -> x + 1) == (fun x -> 1 + x) proof ? in t|}, + ); + +/* A `funext` whose body is still a hole is Incomplete too: the form + * itself proves nothing. */ +let test_funext_hole_body_incomplete = () => + check_status( + "funext with a hole body is Incomplete", + ProofMap.Incomplete, + {|theorem t = (fun x -> x + 1) == (fun x -> 1 + x) proof funext x => ? in t|}, + ); + +/* --- 5. Currying: one arrow per funext -------------------------------- */ + +/* `a -> b -> c` peels once to `f(x) == g(x)`, which is still an arrow; a + * second `funext y =>` peels again. */ +let test_two_arrow_nested_funext = () => { + let src = {|theorem t = (fun x: Int -> fun y: Int -> x + y) == (fun x: Int -> fun y: Int -> y + x) proof funext x => funext y => from x + y do algebra y + x end end; from y + x == y + x do rewrite refl end end in t|}; + let (pm, proof) = run(src); + let status = ProofMap.full_status_of_proof(pm, proof); + Alcotest.check( + Alcotest.bool, + "two nested funext close the curried commute (got: " + ++ ProofMap.show_full_status(status) + ++ ")", + true, + status == ProofMap.Proven, + ); +}; + +/* The inner funext's goal is the twice-applied pointwise equality. */ +let test_two_arrow_inner_goal = () => { + let src = {|theorem t = (fun x -> fun y -> x + y) == (fun x -> fun y -> y + x) proof funext x => funext y => ? in t|}; + let (pm, proof) = run(src); + let inner = funext_body(proof); + let inner_goal = incoming_of(pm, funext_body(inner)); + Alcotest.check( + Alcotest.bool, + "the inner body goal is an equality (got: " + ++ print_exp(inner_goal) + ++ ")", + true, + switch (inner_goal |> Exp.term_of) { + | BinOp(Poly(Equals), _, _) => true + | _ => false + }, + ); +}; + +/* --- 6. Partiality: no automatic restriction on the body goal ---------- */ + +/* Funext doesn't wrap the body goal in a domain restriction: partiality + * shows up when a later step applies `f(x)`. So proving + * `inv == (fun x -> 1 / x)` by evaluating the application is not a + * clean Proven. */ +let test_partial_function_not_cleanly_proven = () => { + let src = {|let inv = fun x -> 1 / x in theorem t = inv == (fun x -> 1 / x) proof funext x => from inv(x) == inv(x) do rewrite refl end end in t|}; + let (pm, proof) = run(src); + let status = ProofMap.full_status_of_proof(pm, proof); + Alcotest.check( + Alcotest.bool, + "a partial function equality is not a clean Proven (got: " + ++ ProofMap.show_full_status(status) + ++ ")", + false, + status == ProofMap.Proven, + ); +}; + +/* --- 7. Contraction keeps let-bound names ----------------------------- */ + +/* A literal lambda whose body mentions a let-bound name: + * + * let f : Int -> Int = fun x -> 1 / x in + * theorem t = (fun x -> f(f(x))) == (fun x : Int -> x) proof + * funext y => from f do step end in t + * + * Contracting the redex substitutes only `x |-> y`, so the pointwise goal + * names `f` as the lambda did, and later steps find it by name. */ + +let funext_repro = (body: string): string => + "let f : Int -> Int = fun x -> 1 / x in theorem t = (fun x -> f(f(x))) == (fun x : Int -> x) proof " + ++ body + ++ " in t"; + +let test_letbound_name_is_kept = () => { + let (pm, proof) = run(funext_repro("funext y => ?")); + Alcotest.check( + Alcotest.string, + "the pointwise goal", + "f(f(y)) == y", + print_exp(incoming_of(pm, funext_body(proof))), + ); +}; + +/* And so `eval f at 0` inside the funext body must not be a + * PatternNotFound. Whether that eval then has anything to step is a + * separate question (`f`'s definition is already a + * value); the assertion here is only that the pattern is found. */ +let test_eval_in_funext_body_finds_pattern = () => { + let src = funext_repro("funext y => from f do step end"); + let (pm, proof) = run(src); + Alcotest.check( + Alcotest.bool, + "`eval f` inside funext finds its pattern (status: " + ++ ProofMap.show_full_status(ProofMap.full_status_of_proof(pm, proof)) + ++ ")", + false, + has_mark_kind( + pm, + proof, + fun + | ProofMark.PatternNotFound(_) => true + | _ => false, + ), + ); +}; + +/* Same, for an eval of the application rather than the bare name, the + * form that has a redex to reduce. */ +let test_eval_application_in_funext_body_finds_pattern = () => { + let src = funext_repro("funext y => from f(f(y)) do step end"); + let (pm, proof) = run(src); + Alcotest.check( + Alcotest.bool, + "`eval f(f(y))` inside funext finds its pattern (status: " + ++ ProofMap.show_full_status(ProofMap.full_status_of_proof(pm, proof)) + ++ ")", + false, + has_mark_kind( + pm, + proof, + fun + | ProofMark.PatternNotFound(_) => true + | _ => false, + ), + ); +}; + +/* --- id uniqueness of the synthesized pointwise goal ------------------ */ + +/* The body's incoming goal is synthesized: `f(x) == g(x)` is assembled + * from the incoming goal's own two sides plus one argument tree lifted + * out of the funext binder, each carrying its ids from the source + * program, and the argument is written into both sides. Without + * freshening, the goal claims the binder's tiles twice and re-claims + * tiles still live in the funext row and the main editor. Duplicate ids + * in one expression make `Highlight.of_tile` fail on a shard-count + * mismatch (double-click in the inner stepper), and ids shared with the + * outside park the caret in the wrong place on a single click. + * + * Mirrors `Test_EditorTransform.duplicate_tile_ids`: collect, count, + * assert zero repeats. */ +let all_ids = (e: Exp.t): list(Id.t) => { + let acc = ref([]); + let f: + 'a. + (IdTagged.t('a) => IdTagged.t('a), IdTagged.t('a)) => IdTagged.t('a) + = + (continue, x) => { + acc := x.annotation.ids @ acc^; + continue(x); + }; + let _: Exp.t = + e |> Exp.map_term(~f_exp=f, ~f_pat=f, ~f_typ=f, ~f_tpat=f, ~f_rul=f); + acc^ |> List.filter(~f=id => id != Id.invalid); +}; + +let duplicates = (ids: list(Id.t)): list(Id.t) => { + let seen = Stdlib.Hashtbl.create(64); + List.filter( + ~f= + id => + switch (Stdlib.Hashtbl.find_opt(seen, id)) { + | Some () => true + | None => + Stdlib.Hashtbl.add(seen, id, ()); + false; + }, + ids, + ); +}; + +let check_no_duplicate_ids = (msg: string, e: Exp.t) => { + let dups = duplicates(all_ids(e)); + Alcotest.check( + Alcotest.int, + msg + ++ " — duplicated ids: " + ++ String.concat(~sep=", ", List.map(~f=Id.to_string, dups)) + ++ "\nin: " + ++ print_exp(e), + 0, + List.length(dups), + ); +}; + +/* The minimal shape: one binder, written into both sides. */ +let test_body_goal_ids_unique_minimal = () => { + let src = {|theorem t = (fun x -> x) == (fun x -> x) proof funext x => ? in t|}; + let (pm, proof) = run(src); + check_no_duplicate_ids( + "the pointwise body goal has no duplicate ids", + incoming_of(pm, funext_body(proof)), + ); +}; + +/* Named functions on both sides, so neither application contracts and + * the shared `xs` argument appears in the goal twice. */ +let matt_repro = {|let plus = fun (x,y) -> x + y in +let sum(xs) = case xs +| [] => 0 +| x::xs => x + sum(xs) +end +in + +theorem t = + sum == fold_left(_, sum, 0) +proof + funext xs => ? +in t|}; + +let test_body_goal_ids_unique_named = () => { + let (pm, proof) = run(matt_repro); + check_no_duplicate_ids( + "the pointwise goal of a named-function funext has no duplicate ids", + incoming_of(pm, funext_body(proof)), + ); +}; + +/* And the goal must not reuse the outer `f == g`'s ids either: those + * tiles belong to the theorem's own editor, and sharing them makes a + * click inside the inner stepper jump out to the parent row. */ +let test_body_goal_ids_disjoint_from_outer = () => { + let src = {|theorem t = (fun x -> x) == (fun x -> x) proof funext x => ? in t|}; + let (pm, proof) = run(src); + let outer = all_ids(incoming_of(pm, proof)); + let body = all_ids(incoming_of(pm, funext_body(proof))); + let seen = Stdlib.Hashtbl.create(64); + List.iter(~f=id => Stdlib.Hashtbl.replace(seen, id, ()), outer); + let shared = List.filter(~f=id => Stdlib.Hashtbl.mem(seen, id), body); + Alcotest.check( + Alcotest.int, + "the pointwise goal shares no ids with the outer function equality " + ++ "— shared: " + ++ String.concat(~sep=", ", List.map(~f=Id.to_string, shared)), + 0, + List.length(shared), + ); +}; + +/* --- Grouping parens around a proof ----------------------------------- */ + +/* `( funext x => ... )` is a ParensProof tile: a Proof-sorted paren whose + * child is the wrapping form, rather than an Exp paren around a + * sort-mismatched `funext`. */ +let test_parens_parse_shape = () => { + let src = {|theorem t = (fun x -> x) == (fun x -> x) proof ( funext x => ) in t|}; + let proof = find_theorem_proof(parse_exp(src)); + switch (proof) { + | Some({term: Parens({term: Funext(_, {term: EmptyHole, _}), _}), _}) => + () + | Some(p) => + Alcotest.fail( + "expected Parens(Funext(_, EmptyHole)), got " ++ Proof.show(p), + ) + | None => Alcotest.fail("no theorem found") + }; +}; + +/* A program that needs ParensProof. Checked as a parse test only: whether `sum == fold_left(_, sum, 0)` type-checks is + * a separate question from whether `( funext xs =>)` groups. */ +let test_parens_motivating_program = () => { + let src = {|let plus = fun (x,y) -> x + y in +let sum(xs) = case xs +| [] => 0 +| x::xs => x + sum(xs) +end +in + +theorem t = + sum == fold_left(_, sum, 0) +proof + ( funext xs =>) +in +|}; + switch (find_theorem_proof(parse_exp(src))) { + | Some({term: Parens({term: Funext(_, _), _}), _}) => () + | Some(p) => + Alcotest.fail( + "expected the proof to be Parens(Funext(...)), got " ++ Proof.show(p), + ) + | None => Alcotest.fail("no theorem found") + }; +}; + +/* The checker sees straight through the parens: a parenthesized proof + * that would prove the theorem still proves it. */ +let test_parens_transparent_to_checker = () => + check_status( + "a parenthesized funext proof still proves", + ProofMap.Proven, + {|theorem t = (fun x: Int -> x + 1) == (fun x: Int -> 1 + x) proof ( funext x => from x + 1 do algebra 1 + x end end; from 1 + x == 1 + x do rewrite refl end end ) in t|}, + ); + +/* The stepper sees through them too: the parens are unwrapped before + * looking for a `;` chain, so the row is the funext's, with its body. */ +let test_parens_transparent_to_stepper = () => { + let inner = + Proof.fresh(Funext(Pat.fresh(Var("x")), Proof.fresh(EmptyHole))); + let (head, tail) = Web.StepperRows.split(Proof.fresh(Parens(inner))); + Alcotest.check( + Alcotest.bool, + "a parenthesized leaf step has no tail", + true, + tail == None, + ); + switch (head.term) { + | Funext(_, _) => () + | _ => Alcotest.fail("the parens were not unwrapped to the funext") + }; + switch ( + Web.StepperRows.chain( + ~proof_map=ProofMap.empty, + Proof.fresh(Parens(inner)), + ) + ) { + | [{kind: Step(Body(_)), step: {term: Funext(_), _}, _}, _] => () + | _ => Alcotest.fail("a parenthesized funext is not a funext row") + }; +}; + +let tests = ( + "Funext", + [ + test_case( + "grouping parens: `( funext x => )` parses as Parens(Funext(...))", + `Quick, + test_parens_parse_shape, + ), + test_case( + "grouping parens: the motivating program parses", + `Quick, + test_parens_motivating_program, + ), + test_case( + "grouping parens: the checker sees through them", + `Quick, + test_parens_transparent_to_checker, + ), + test_case( + "grouping parens: the stepper's proof splitting sees through them", + `Quick, + test_parens_transparent_to_stepper, + ), + test_case( + "happy path: pointwise commute proves as `f == g`", + `Quick, + test_happy_path_proven, + ), + test_case( + "the body's goal is the contracted pointwise equality", + `Quick, + test_body_goal_is_pointwise, + ), + test_case( + "a named function stays applied in the pointwise goal", + `Quick, + test_named_function_stays_applied, + ), + test_case( + "`inv == inv` closes pointwise by refl, without applying inv", + `Quick, + test_named_function_refl_proves, + ), + test_case( + "control: refl still closes identical functions without funext", + `Quick, + test_refl_identical_functions_no_funext, + ), + test_case( + "funext on a non-arrow `==` is marked ExpectedFunEqGoal", + `Quick, + test_non_arrow_equality_marked, + ), + test_case( + "control: a hole against a function equality stays Incomplete", + `Quick, + test_hole_without_funext_incomplete, + ), + test_case( + "funext with a hole body is Incomplete", + `Quick, + test_funext_hole_body_incomplete, + ), + test_case( + "currying: two nested funext peel two arrows", + `Quick, + test_two_arrow_nested_funext, + ), + test_case( + "currying: the inner body goal is an equality", + `Quick, + test_two_arrow_inner_goal, + ), + test_case( + "partiality: no automatic restriction, so `inv == ...` is not clean", + `Quick, + test_partial_function_not_cleanly_proven, + ), + test_case( + "a let-bound name is kept when funext contracts the redex", + `Quick, + test_letbound_name_is_kept, + ), + test_case( + "`eval f` inside a funext body is not a PatternNotFound", + `Quick, + test_eval_in_funext_body_finds_pattern, + ), + test_case( + "`eval f(f(y))` inside a funext body is not a PatternNotFound", + `Quick, + test_eval_application_in_funext_body_finds_pattern, + ), + test_case( + "ids: the pointwise body goal has no duplicate ids", + `Quick, + test_body_goal_ids_unique_minimal, + ), + test_case( + "ids: a named-function pointwise goal has no duplicate ids", + `Quick, + test_body_goal_ids_unique_named, + ), + test_case( + "ids: the pointwise goal is disjoint from the outer goal", + `Quick, + test_body_goal_ids_disjoint_from_outer, + ), + ], +); diff --git a/test/evaluator/Test_Generalize.re b/test/evaluator/Test_Generalize.re new file mode 100644 index 0000000000..e224187046 --- /dev/null +++ b/test/evaluator/Test_Generalize.re @@ -0,0 +1,253 @@ +open Alcotest; +open Language; +open Test_ProofMap.Harness; + +/* The `generalize` proof step. + * + * `generalize x => body` re-quantifies an already-peeled binder: the + * body's incoming goal is `forall x -> G`, every fact mentioning the old x + * is removed from the body's scope (capture soundness), and the node's + * outgoing is `true` only when the body proves the re-quantified goal. + * The payoff is forall-quantified inductive hypotheses. */ + +/* The immediate body of a `generalize` node (the sub-proof that sees the + * re-quantified goal). */ +let generalize_body = (p: Proof.t): Proof.t => + switch (p.term) { + | Generalize(_, body) => body + | _ => Alcotest.fail("expected the proof to be a generalize node") + }; + +let is_forall = (e: Exp.t): bool => + switch (e |> Exp.term_of) { + | Forall(_, _) => true + | _ => false + }; + +/* --- 1. Mechanics ------------------------------------------------------ */ + +/* Inside `generalize y` the goal is the re-quantified + * `forall y -> x + y == y + x`; re-peel it and close by rewrite + refl. + * The theorem is fully Proven. */ +let test_mechanics_requantified_goal = () => { + let src = {|theorem t = forall x -> forall y -> x + y == y + x proof generalize y => forall y => from x + y do algebra y + x end end; from y + x == y + x do rewrite refl end end in t|}; + let (pm, proof) = run(src); + let body = generalize_body(proof); + let body_goal = incoming_of(pm, body); + Alcotest.check( + Alcotest.bool, + "the body's incoming goal is a plain forall", + true, + is_forall(body_goal), + ); + check_exp( + "the body's incoming goal re-quantifies y", + "forall y -> x + y == y + x", + body_goal, + ); + check_status("theorem is fully Proven", ProofMap.Proven, pm, proof); +}; + +/* --- 2. Capture -------------------------------------------------------- */ + +/* A hypothesis about x must become unavailable inside `generalize x`: + * citing it fails with the ordinary unknown-equality behavior. */ +let test_captured_hypothesis_not_citable = () => { + let src = {|theorem t = forall x -> x == 1 ==> x == 1 proof assume x == 1 => generalize x => forall x => from x do rewrite assume end end in t|}; + let (pm, proof) = run(src); + Alcotest.check( + Alcotest.bool, + "citing the captured assume-fact is UnknownEquality", + true, + has_mark_kind( + pm, + proof, + fun + | ProofMark.UnknownEquality(_) => true + | _ => false, + ), + ); + Alcotest.check( + Alcotest.option(bool), + "the theorem is not proven", + None, + ProofMap.status_of_proof(pm, proof), + ); +}; + +/* An obligation identical to the captured fact must stay Pending inside + * the generalize, since lookup can't see the removed fact; the same + * program without `generalize` discharges it Remote. */ +let test_captured_fact_does_not_discharge = () => { + let src = {|theorem t = forall x -> x != 0 ==> x == x proof assume x != 0 => generalize x => forall x => have x != 0 proof ? => from x == x do rewrite refl end end in t|}; + let (pm, proof) = run(src); + let obs = ProofMap.obligations_of_proof(pm, proof); + Alcotest.check(Alcotest.int, "the have's obligation", 1, List.length(obs)); + Alcotest.check( + Alcotest.bool, + "it is Pending (no remote discharge across generalize)", + true, + List.for_all(~f=Obligation.is_pending, obs), + ); + /* Control: without the generalize, the have's obligation discharges + * against the assumption by lookup (Remote). */ + let control = {|theorem t = forall x -> x != 0 ==> x == x proof assume x != 0 => have x != 0 proof ? => from x == x do rewrite refl end end in t|}; + let (pm', proof') = run(control); + let obs' = ProofMap.obligations_of_proof(pm', proof'); + Alcotest.check( + Alcotest.bool, + "control: the inner obligation discharges Remote", + true, + List.exists( + ~f= + (ob: Obligation.t) => + switch (ob.discharge) { + | Obligation.Remote(_) => true + | _ => false + }, + obs', + ), + ); +}; + +/* --- 3. Quantified IH end to end -------------------------------------- */ + +/* rev_append-style length theorem: the cons case needs the IH at + * `x :: ys`, a different instantiation from the peeled ys, which the + * unquantified IH can't give and `generalize ys` does. Helper equations are supplied as hole-proof lemmas (the test + * targets the generalize/IH machinery, not list algebra). */ +let quantified_ih_src = {|let ra = fun xs -> fun ys -> case xs | [] => ys | h :: t => ra(t)(h :: ys) end in let len = fun l -> case l | [] => 0 | h :: t => 1 + len(t) end in theorem ra_nil = forall zs -> ra([])(zs) == zs proof ? in theorem ra_cons = forall h -> forall t -> forall zs -> ra(h :: t)(zs) == ra(t)(h :: zs) proof ? in theorem len_nil = len([]) == 0 proof ? in theorem len_cons = forall h -> forall t -> len(h :: t) == 1 + len(t) proof ? in theorem shuffle = forall a -> forall b -> a + (1 + b) == (1 + a) + b proof ? in theorem zero_add = forall n -> 0 + n == n proof ? in theorem u = forall xs: [Int] -> forall ys -> len(ra(xs)(ys)) == len(xs) + len(ys) proof generalize ys => induction xs | [] => forall ys => from ra([])(ys) do rewrite ra_nil end end; from len([]) do rewrite len_nil end end; from 0 + len(ys) do rewrite zero_add end end; from len(ys) == len(ys) do rewrite refl end end | x :: xs' => forall ys => from ra(x :: xs')(ys) do rewrite ra_cons end end; from len(ra(xs')(x :: ys)) do rewrite ih_xs' end end; from len(x :: ys) do rewrite len_cons end end; from len(x :: xs') do rewrite len_cons end end; from len(xs') + (1 + len(ys)) do rewrite shuffle end end; from (1 + len(xs')) + len(ys) == (1 + len(xs')) + len(ys) do rewrite refl end end end in u|}; + +let test_quantified_ih_proves = () => { + let (pm, proof) = run_named("u", quantified_ih_src); + /* The induction operates on the re-quantified goal, so its generated + * IHs are forall-quantified over ys. */ + let body = generalize_body(proof); + Alcotest.check( + Alcotest.bool, + "the induction's incoming goal is forall-quantified", + true, + is_forall(incoming_of(pm, body)), + ); + let obs = without_citations(ProofMap.obligations_of_proof(pm, proof)); + Alcotest.check(Alcotest.int, "no obligations", 0, List.length(obs)); + check_proven_given_lemmas( + "theorem u is fully Proven (IH cited at x :: ys)", + pm, + proof, + ); +}; + +/* Negative control: without generalize, the IH is the unquantified + * equation at the peeled ys, and citing it at `x :: ys` fails + * (RuleDoesNotApply). */ +let test_unquantified_ih_too_weak = () => { + let src = {|let ra = fun xs -> fun ys -> case xs | [] => ys | h :: t => ra(t)(h :: ys) end in let len = fun l -> case l | [] => 0 | h :: t => 1 + len(t) end in theorem ra_cons = forall h -> forall t -> forall zs -> ra(h :: t)(zs) == ra(t)(h :: zs) proof ? in theorem u = forall xs: [Int] -> forall ys -> len(ra(xs)(ys)) == len(xs) + len(ys) proof induction xs | [] => ? | x :: xs' => from ra(x :: xs')(ys) do rewrite ra_cons end end; from len(ra(xs')(x :: ys)) do rewrite ih_xs' end end end in u|}; + let (pm, proof) = run_named("u", src); + Alcotest.check( + Alcotest.bool, + "citing the naive IH at x :: ys does not apply", + true, + has_mark_kind( + pm, + proof, + fun + | ProofMark.RuleDoesNotApply(_) => true + | _ => false, + ), + ); + Alcotest.check( + Alcotest.option(bool), + "the naive proof is not proven", + None, + ProofMap.status_of_proof(pm, proof), + ); +}; + +/* --- 4. Malformed ------------------------------------------------------- */ + +let has_malformed_generalize = (pm, proof) => + has_mark_kind( + pm, + proof, + fun + | ProofMark.MalformedGeneralize => true + | _ => false, + ); + +/* `generalize 5`: not a variable, so marked; the goal passes through. */ +let test_generalize_literal_marked = () => { + let src = {|theorem t = forall x -> x == x proof generalize 5 => from x == x do rewrite refl end end in t|}; + let (pm, proof) = run(src); + Alcotest.check( + Alcotest.bool, + "MalformedGeneralize mark is emitted", + true, + has_malformed_generalize(pm, proof), + ); + Alcotest.check( + Alcotest.option(bool), + "the theorem is not proven", + None, + ProofMap.status_of_proof(pm, proof), + ); +}; + +/* `generalize z` with z not in scope: same mark. */ +let test_generalize_out_of_scope_marked = () => { + let src = {|theorem t = forall x -> x == x proof generalize z => from x == x do rewrite refl end end in t|}; + let (pm, proof) = run(src); + Alcotest.check( + Alcotest.bool, + "MalformedGeneralize mark is emitted", + true, + has_malformed_generalize(pm, proof), + ); + Alcotest.check( + Alcotest.option(bool), + "the theorem is not proven", + None, + ProofMap.status_of_proof(pm, proof), + ); +}; + +let tests = ( + "Evaluator.Generalize", + [ + test_case( + "generalize re-quantifies the goal and the theorem proves", + `Quick, + test_mechanics_requantified_goal, + ), + test_case( + "a captured hypothesis is not citable inside generalize", + `Quick, + test_captured_hypothesis_not_citable, + ), + test_case( + "a captured fact does not discharge obligations", + `Quick, + test_captured_fact_does_not_discharge, + ), + test_case( + "quantified IH end-to-end: generalize + induction proves", + `Quick, + test_quantified_ih_proves, + ), + test_case( + "control: the unquantified IH is too weak", + `Quick, + test_unquantified_ih_too_weak, + ), + test_case( + "generalize of a literal is marked malformed", + `Quick, + test_generalize_literal_marked, + ), + test_case( + "generalize of an out-of-scope name is marked malformed", + `Quick, + test_generalize_out_of_scope_marked, + ), + ], +); diff --git a/test/evaluator/Test_Have.re b/test/evaluator/Test_Have.re new file mode 100644 index 0000000000..499d81ba71 --- /dev/null +++ b/test/evaluator/Test_Have.re @@ -0,0 +1,446 @@ +open Alcotest; +open Language; +open Test_Evaluator_Prelude; +open Test_ProofMap.Harness; +open Poly; + +/* The `have` proof form, `have proof => `: the + * cut rule, and the obligations panel's "prove here" exit. + * + * Semantics under test (`ProofCheck.check_have`). Have is a two-premise + * rule: with incoming goal G it incurs two obligations on its own node, + * one per premise, each retired by its own attached proof. + * - premise 1's goal is , checked in the enclosing scope (it + * can't cite the have's own hypothesis). Dropped when the subproof + * closes it (`true`, clean subtree); otherwise it is discharged if it + * can be, so an already-known goes Remote/Evaluated with no + * subproof written; + * - premise 2's goal is G, in the scope extended with under the + * name "have". Dropped when the body closes it; otherwise Pending, + * never discharged by lookup, which would trivially succeed against + * the new `have` whenever G equals ; + * - that hypothesis is installed whether or not the subproof is done, + * so an obligation incurred by a step inside the body discharges + * Remote by lookup as soon as the wrapper is written; + * - outgoing is the body's, and mark-free: an open premise is an + * incomplete proof, not a broken step. */ + +let int_check = (msg, expected, actual) => + Alcotest.check(Alcotest.int, msg, expected, actual); + +let bool_check = (msg, expected, actual) => + Alcotest.check(Alcotest.bool, msg, expected, actual); + +let dump_obligations = (obs: list(Obligation.t)): string => + obs + |> List.map(~f=(ob: Obligation.t) => + " " + ++ String.map(~f=c => c == '\n' ? ' ' : c, print_exp(ob.goal)) + ++ " -> " + ++ Obligation.show_discharge(ob.discharge) + ) + |> String.concat(~sep="\n"); + +/* The shared shape: a theorem whose statement leaves `x` unrestricted, so + * a `have` about `x` has an open goal, which closed evaluation can't + * discharge. That is what makes the difference between a + * proven and an unproven subproof visible in the obligation list. */ +let with_have = (subproof: string): string => + "theorem t = forall x: Int -> x == x proof have x == x proof " + ++ subproof + ++ " => from x == x do rewrite refl end end in t"; + +/* --- 1. a proven subproof discharges the have's obligation ----------- */ + +let test_proven_subproof_discharges = () => { + let (pm, proof) = run(with_have("from x == x do rewrite refl end end")); + let obs = ProofMap.obligations_of_proof(pm, proof); + if (obs != []) { + Alcotest.fail( + "a proven `have` subproof should leave NO obligation, got:\n" + ++ dump_obligations(obs), + ); + }; + check_mark_free("have with a proven subproof", pm, proof); + bool_check( + "the theorem is plain Proven", + true, + ProofMap.full_status_of_proof(pm, proof) == ProofMap.Proven, + ); +}; + +/* --- 2. an incomplete subproof leaves the obligation pending --------- */ + +let test_incomplete_subproof_pending = () => { + let (pm, proof) = run(with_have("?")); + let obs = ProofMap.obligations_of_proof(pm, proof); + int_check( + "exactly one obligation — the have's own:\n" ++ dump_obligations(obs), + 1, + List.length(obs), + ); + bool_check( + "and it is pending:\n" ++ dump_obligations(obs), + true, + List.for_all(~f=Obligation.is_pending, obs), + ); + /* Mark-free: an unfinished subproof is an incomplete proof, not a + * broken step. */ + check_mark_free("have with a hole subproof", pm, proof); + /* The goal reached `true` granted the pending obligation. */ + bool_check( + "status is ProvenModulo", + true, + switch (ProofMap.full_status_of_proof(pm, proof)) { + | ProvenModulo(_) => true + | Proven + | Refuted + | Incomplete => false + }, + ); +}; + +/* --- 3. the hypothesis is citable from the body ---------------------- */ + +/* The point of the "prove here" action: an obligation incurred inside the + * body discharges against the have's hypothesis by lookup even while + * the subproof is still a hole. `8 / z` in the goal makes the axiom step + * incur `z != 0`, and nothing else in scope covers it. */ +let citable_src = {|theorem t = forall z: Int -> 8 / z == 8 / z +proof have z != 0 proof ? => from 8 / z == 8 / z do rewrite refl end end +in t|}; + +let test_hypothesis_citable_in_body = () => { + let (pm, proof) = run(citable_src); + let obs = ProofMap.obligations_of_proof(pm, proof); + let dump = dump_obligations(obs); + /* Two obligations: the body's `z != 0` (Remote, against the have) and + * the have's own `z != 0` (Pending, until the subproof is written). */ + int_check("two obligations:\n" ++ dump, 2, List.length(obs)); + let remotes = + List.filter( + ~f= + (ob: Obligation.t) => + switch (ob.discharge) { + | Remote(_) => true + | _ => false + }, + obs, + ); + int_check( + "the body's obligation is discharged Remote:\n" ++ dump, + 1, + List.length(remotes), + ); + /* The receipt names the hypothesis the checker installed. */ + switch (remotes) { + | [ob] => + switch (Obligation.remote_fact(ob)) { + | Some((name, _)) => + bool_check( + "receipt names a `have` hypothesis, got " ++ name, + true, + String.length(name) >= 4 + && String.sub(name, ~pos=0, ~len=4) == "have", + ) + | None => Alcotest.fail("Remote discharge with no recoverable receipt") + } + | _ => () + }; + int_check( + "the have itself still carries one pending obligation:\n" ++ dump, + 1, + List.length(List.filter(~f=Obligation.is_pending, obs)), + ); + check_mark_free("have citable in body", pm, proof); +}; + +/* --- 4. the subproof may not cite the have's own hypothesis ---------- */ + +/* Soundness guard: were the subproof checked in the extended scope, `have + * P proof => ...` would prove anything. The subproof is checked + * in the enclosing scope, so citing `have` there is an unknown fact. */ +let self_cite_src = {|theorem t = forall x: Int -> x == x +proof have x == 1 proof from x do rewrite have end end => from x == x do rewrite refl end end +in t|}; + +let test_subproof_cannot_self_cite = () => { + let (pm, proof) = run(self_cite_src); + bool_check( + "citing the have's own hypothesis inside its subproof does not prove it", + false, + ProofMap.full_status_of_proof(pm, proof) == ProofMap.Proven, + ); + let obs = ProofMap.obligations_of_proof(pm, proof); + bool_check( + "the have's obligation is still pending:\n" ++ dump_obligations(obs), + true, + List.exists(~f=Obligation.is_pending, obs), + ); +}; + +/* --- 5. round-trip: the form survives print/parse -------------------- */ + +let test_form_roundtrips = () => { + let src = with_have("?"); + let printed = print_exp(parse_exp(src)); + bool_check( + "printed program still contains the have form: " ++ printed, + true, + contains(printed, "have"), + ); + /* Re-parsing the printed text yields the same proof term. */ + let p1 = proof_of(parse_exp(src)); + let p2 = proof_of(parse_exp(printed)); + bool_check( + "reparse is proof-equal:\n" ++ printed, + true, + Proof.fast_equal(p1, p2), + ); +}; + +let split_probe_src = {|theorem t = forall z: Int -> 8 / z == 8 / z +proof cases z != 0 | true => from 8 / z == 8 / z do rewrite refl end end | false => ? end +in t|}; + +/* The obligations panel's split exit, end to end: in the `true` branch + * the case equation `(z != 0) == true` covers the branch's `z != 0` + * obligation by lookup (modulo `ProofCheck.Discharge.strip_eq_true`). The `false` + * branch is left to the user, so the theorem is Incomplete. */ +let test_split_discharges_in_true_branch = () => { + let (pm, proof) = run(split_probe_src); + let obs = ProofMap.obligations_of_proof(pm, proof); + let dump = dump_obligations(obs); + int_check("one obligation:\n" ++ dump, 1, List.length(obs)); + bool_check( + "discharged against the case equation:\n" ++ dump, + true, + List.for_all( + ~f= + (ob: Obligation.t) => + switch (ob.discharge) { + | Remote(_) => true + | Evaluated + | Pending => false + }, + obs, + ), + ); + switch (obs) { + | [ob] => + switch (Obligation.remote_fact(ob)) { + | Some((name, _)) => + bool_check( + "the receipt names the case equation, got " ++ name, + true, + String.length(name) >= 7 + && String.sub(name, ~pos=0, ~len=7) == "case_eq", + ) + | None => Alcotest.fail("Remote discharge with no recoverable receipt") + } + | _ => () + }; +}; + +/* The (first) `have` node in a proof term. The theorem's proof root is + * not necessarily the have itself (binder peeling, `;` chains), and the + * obligation's `origin` is the have's own rep_id. */ +let rec find_have = (p: Proof.t): option(Proof.t) => + switch (p.term) { + | Have(_, _, _, _) => Some(p) + | Seq(a, b) => + switch (find_have(a)) { + | Some(_) as r => r + | None => find_have(b) + } + | Forall(_, b) + | Funext(_, b) + | Assume(_, _, b) + | Alias(_, _, b) + | Generalize(_, b) + | Revert(_, _, b) + | Parens(b) => find_have(b) + | Cases(_, cases) + | Induction(_, cases) => + List.fold_left( + ~f= + (acc, (_, b)) => + switch (acc) { + | Some(_) => acc + | None => find_have(b) + }, + ~init=None, + cases, + ) + | EmptyHole + | Invalid(_) + | MultiHole(_) + | AxiomStep(_) + | AlgebriteStep(_) + | EvalStep => None + | Focus({body, _}) => find_have(body) + }; + +/* --- 6. both premises open: two obligations on the have node --------- */ + +/* Have is a two-premise rule, so `have P proof ? => ?` on goal G carries + * both premises as obligations of the have step itself, not only as + * nested proof incompleteness. `P` here is `x == 2`, which is neither in + * the theorem's context nor closed, so neither lookup nor closed + * evaluation can discharge premise 1. */ +let two_holes_src = {|theorem t = forall x: Int -> x == x +proof have x == 2 proof ? => ? +in t|}; + +let test_two_open_premises = () => { + let (pm, proof) = run(two_holes_src); + let obs = ProofMap.obligations_of_proof(pm, proof); + let dump = dump_obligations(obs); + int_check( + "two obligations, one per premise:\n" ++ dump, + 2, + List.length(obs), + ); + /* Both are recorded on the have node, so the obligations panel groups + * them under this step, as it does a two-condition axiom's. */ + let have_id = + switch (find_have(proof)) { + | Some(h) => Proof.rep_id(h) + | None => Alcotest.fail("no `have` node in the proof term") + }; + bool_check( + "both obligations originate at the have step:\n" ++ dump, + true, + List.for_all( + ~f=(ob: Obligation.t) => Id.compare(ob.origin, have_id) == 0, + obs, + ), + ); + bool_check( + "both are pending:\n" ++ dump, + true, + List.for_all(~f=Obligation.is_pending, obs), + ); + /* Premise 1 is ``; premise 2 is the outer goal. */ + bool_check( + "one obligation is the proposition:\n" ++ dump, + true, + List.exists( + ~f= + (ob: Obligation.t) => + Exp.fast_equal(ob.goal, elaborated_exp("x == 2")), + obs, + ), + ); + bool_check( + "the other is the incoming goal:\n" ++ dump, + true, + List.exists( + ~f= + (ob: Obligation.t) => + Exp.fast_equal(ob.goal, elaborated_exp("x == x")), + obs, + ), + ); + /* Premise 2's local context is the extended one: the panel must show + * the `have` hypothesis the premise is allowed to use. */ + switch ( + List.find( + ~f= + (ob: Obligation.t) => + Exp.fast_equal(ob.goal, elaborated_exp("x == x")), + obs, + ) + ) { + | Some(ob) => + bool_check( + "the body premise's bindings carry the `have` hypothesis", + true, + List.exists( + ~f= + (e: Ctx.entry) => + switch (e) { + | TheoremEntry({name, _}) => name == "have" + | _ => false + }, + ob.bindings, + ), + ) + | None => () + }; + check_mark_free("have with two hole premises", pm, proof); + /* Not ProvenModulo: with the body open the goal never reaches `true`, + * so a pending second premise cannot masquerade as "proven modulo". */ + bool_check( + "status is Incomplete", + true, + ProofMap.full_status_of_proof(pm, proof) == ProofMap.Incomplete, + ); +}; + +/* An open body premise with a closed subproof still leaves premise 2. */ +let test_body_premise_alone = () => { + let (pm, proof) = + run( + {|theorem t = forall x: Int -> x == x +proof have 1 == 1 proof from 1 == 1 do rewrite refl end end => ? +in t|}, + ); + let obs = ProofMap.obligations_of_proof(pm, proof); + let dump = dump_obligations(obs); + int_check("only the body premise remains:\n" ++ dump, 1, List.length(obs)); + bool_check( + "and it is the incoming goal:\n" ++ dump, + true, + switch (obs) { + | [ob] => Exp.fast_equal(ob.goal, elaborated_exp("x == x")) + | _ => false + }, + ); +}; + +let tests = ( + "Evaluator.Have", + [ + test_case( + "proven subproof discharges the obligation", + `Quick, + test_proven_subproof_discharges, + ), + test_case( + "two open premises are two obligations on the have", + `Quick, + test_two_open_premises, + ), + test_case( + "a closed subproof still leaves the body premise", + `Quick, + test_body_premise_alone, + ), + test_case( + "incomplete subproof leaves it pending", + `Quick, + test_incomplete_subproof_pending, + ), + test_case( + "hypothesis is citable in the body", + `Quick, + test_hypothesis_citable_in_body, + ), + test_case( + "subproof cannot cite the have itself", + `Quick, + test_subproof_cannot_self_cite, + ), + test_case( + "form round-trips through the printer", + `Quick, + test_form_roundtrips, + ), + test_case( + "split discharges the obligation in the true branch", + `Quick, + test_split_discharges_in_true_branch, + ), + ], +); diff --git a/test/evaluator/Test_HypothesisNaming.re b/test/evaluator/Test_HypothesisNaming.re new file mode 100644 index 0000000000..04eed09fcd --- /dev/null +++ b/test/evaluator/Test_HypothesisNaming.re @@ -0,0 +1,467 @@ +open Alcotest; +open Language; +open Test_ProofMap.Harness; + +/* Hypothesis naming: fixed names and shadowing, named forms, `alias`. + * + * The rules under test: + * + * 1. Every auto-installed fact takes its base name (`case_eq`, + * `ih_`, `assume`, `have`) with no freshening, so a second + * introduction in an inner scope shadows the first + * (`SemanticCtx.add_hypothesis`). + * 2. Citation resolves innermost first, because `Ctx.extend` prepends + * and `Ctx.lookup_theorem` takes the first match. Citing a shadowed + * name is not an error: it denotes the nearest enclosing + * introduction. + * 3. `cases as ` names the split's case equation in every + * case, and `assume as ` names the assumption, so a deep + * leaf can still cite an outer introduction. + * 4. `alias = => ...` binds an already-known fact to a + * second name: the way to reach a fact that has already been + * shadowed. */ + +let marks_of = (pm, proof): list(ProofMark.t) => + switch (find_marked_sub(pm, proof)) { + | None => [] + | Some((_, marks)) => marks + }; + +let check_has_unknown_equality = (msg, name, pm, proof) => + if (! + has_mark_kind( + pm, + proof, + fun + | ProofMark.UnknownEquality(n) => String.equal(n, name) + | _ => false, + )) { + Alcotest.fail( + msg + ++ ": expected UnknownEquality(\"" + ++ name + ++ "\"), got " + ++ String.concat( + ~sep="; ", + List.map(~f=ProofMark.show, marks_of(pm, proof)), + ), + ); + }; + +/* Which fact did a name resolve to? + * + * `revert => ?` resolves the name through `cited_fact` and moves + * that proposition into the body's goal as an antecedent (`F ==> G`), so + * the body's goal shows what the name denoted. That is sharper than + * checking for marks, since an unrelated rewrite failure is a mark too. */ +let rec find_revert = (p: Proof.t): option(Proof.t) => + switch (p.term) { + | Revert(_, _, _) => Some(p) + | Seq(a, b) => + switch (find_revert(a)) { + | Some(_) as r => r + | None => find_revert(b) + } + | Parens(b) + | Forall(_, b) + | Funext(_, b) + | Assume(_, _, b) + | Alias(_, _, b) + | Generalize(_, b) => find_revert(b) + | Have(_, _, sub, b) => + switch (find_revert(sub)) { + | Some(_) as r => r + | None => find_revert(b) + } + | Cases(_, cases) + | Induction(_, cases) => + List.find_map(~f=((_, b)) => find_revert(b), cases) + | EmptyHole + | Invalid(_) + | MultiHole(_) + | AxiomStep(_) + | AlgebriteStep(_) + | EvalStep => None + | Focus({body, _}) => find_revert(body) + }; + +/* The antecedent a `revert ` moved into the goal, as printed text, + read off the body's incoming goal `F ==> G`. (The revert node's own + outgoing is its body's, which for a `?` body is the goal passed + through.) */ +let reverted_antecedent = (pm: ProofMap.t, proof: Proof.t): string => + switch (find_revert(proof)) { + | None => Alcotest.fail("no revert node in the proof") + | Some({term: Revert(_, _, body), _}) => + switch (ProofMap.lookup(Proof.rep_id(body), pm)) { + | Some({incoming: Some(g), _}) => print_exp(g) + | _ => Alcotest.fail("the revert's body has no incoming goal") + } + | Some(_) => Alcotest.fail("find_revert returned a non-revert node") + }; + +let check_resolves_to = (msg, ~name_denotes: string, pm, proof) => { + let got = reverted_antecedent(pm, proof); + if (!contains(got, name_denotes)) { + Alcotest.fail( + msg + ++ ": expected the cited name to denote `" + ++ name_denotes + ++ "`, but the reverted goal is: " + ++ got, + ); + }; +}; + +/* --- 1. innermost wins (`Ctx.lookup_theorem`) ------------------------- */ + +/* Two nested `assume`s, both named `assume`. Reverting the name shows + * that it denotes the inner one. */ +let nested_assume_src = + "theorem t = forall x: Int -> forall y: Int -> x == 1 ==> y == 2 ==> x == x proof " + ++ "assume x == 1 => assume y == 2 => revert assume => ? in t"; + +let test_shadowed_name_resolves_innermost = () => { + let (pm, proof) = run(nested_assume_src); + check_resolves_to( + "the bare name `assume` must resolve to the INNER assumption", + ~name_denotes="y == 2", + pm, + proof, + ); +}; + +/* The same claim on the other lookup path. `revert` resolves a name + * through `SemanticCtx`/`Ctx.lookup_theorem`; an axiom step resolves it + * through `ProofCtx.lookup_rule` over `ProofCtx.of_theorem_ctx`. Both + * have to agree, or a name would mean one thing to `revert` and another + * to `rewrite`. Here the two candidate facts have different left-hand + * sides, so only the innermost reading can rewrite the target `m`. */ +let test_axiom_step_also_resolves_innermost = () => { + let (pm, proof) = + run( + "theorem t = forall n: Int -> forall m: Int -> n == 1 ==> m == 2 ==> m == m proof " + ++ "assume n == 1 => assume m == 2 => from m do rewrite assume end end; ? in t", + ); + check_mark_free( + "an axiom step citing a shadowed name must resolve to the INNER fact, " + ++ "exactly as revert does", + pm, + proof, + ); +}; + +/* --- 2. `assume ... as `: naming at introduction ------------------ */ + +/* With the inner assumption named, `assume` still denotes the outer one, + * and the inner one is reachable under its own name. */ +let test_named_assume_leaves_outer_citable = () => { + let (pm, proof) = + run( + "theorem t = forall x: Int -> forall y: Int -> x == 1 ==> y == 2 ==> x == x proof " + ++ "assume x == 1 => assume hy = y == 2 => revert assume => ? in t", + ); + check_resolves_to( + "naming the inner assumption leaves the outer one as `assume`", + ~name_denotes="x == 1", + pm, + proof, + ); +}; + +let test_assume_name_denotes_its_own_fact = () => { + let (pm, proof) = + run( + "theorem t = forall x: Int -> forall y: Int -> x == 1 ==> y == 2 ==> x == x proof " + ++ "assume x == 1 => assume hy = y == 2 => revert hy => ? in t", + ); + check_resolves_to( + "an assume's name denotes the assumption it was attached to", + ~name_denotes="y == 2", + pm, + proof, + ); +}; + +/* --- 3. an aliased `case_eq` cited from a deep leaf ---------------- */ + +/* Two nested splits, each `true` case starting with the steps it is + * given. Unaliased, the inner split's `case_eq` shadows the outer one, so + * at depth the name denotes the inner equation. */ +let two_splits = (outer: string, inner: string, cite: string): string => + "theorem t = forall n: Int -> forall m: Int -> n == n proof " + ++ "cases n > 0 | true => " + ++ outer + ++ "cases m > 0 | true => " + ++ inner + ++ "revert " + ++ cite + ++ " => ? | false => ? end | false => ? end in t"; + +let test_bare_case_eq_at_depth_is_the_inner_one = () => { + let (pm, proof) = run(two_splits("", "", "case_eq")); + check_resolves_to( + "at depth the bare `case_eq` is the INNER split's equation", + ~name_denotes="m > 0", + pm, + proof, + ); +}; + +/* Aliased, the outer split's equation is citable from the deep leaf, as + * in Test_Milestone_STLC's `progress`. */ +let test_aliased_split_cited_from_deep_leaf = () => { + let (pm, proof) = run(two_splits("alias hn = case_eq => ", "", "hn")); + check_resolves_to( + "an aliased outer equation is citable inside a nested split", + ~name_denotes="n > 0", + pm, + proof, + ); + check_mark_free("citing an aliased outer equation is mark-free", pm, proof); +}; + +/* --- 4. duplicate names shadow too --------------------------------- */ + +/* Naming is not a uniqueness constraint. Two aliases may take the same + * name; the inner one shadows the outer, exactly as the fixed names do. */ +let test_duplicate_name_shadows = () => { + let (pm, proof) = + run(two_splits("alias h = case_eq => ", "alias h = case_eq => ", "h")); + check_resolves_to( + "a duplicate name shadows: it denotes the inner split", + ~name_denotes="m > 0", + pm, + proof, + ); +}; + +/* --- 5. `alias`: naming a fact past a shadow ------------------------- */ + +/* The outer split is unnamed, so inside the inner split its `case_eq` is + * shadowed. An `alias` taken in the outer scope, where the name still + * resolves to it, carries it in under a name the inner split doesn't + * take. */ +let test_alias_keeps_outer_fact_past_a_shadow = () => { + let (pm, proof) = + run( + "theorem t = forall n: Int -> forall m: Int -> n == n proof " + ++ "cases n > 0 | true => alias hn = case_eq => " + ++ "cases m > 0 | true => revert hn => ? " + ++ "| false => ? end | false => ? end in t", + ); + check_resolves_to( + "an alias taken before the shadowing split keeps the outer fact", + ~name_denotes="n > 0", + pm, + proof, + ); + check_mark_free("alias is mark-free", pm, proof); +}; + +/* An alias resolves its fact the way `revert` does, so it also accepts + * the proposition spelled out. That is the only way to reach a fact that + * is already shadowed where the alias is written. */ +let test_alias_by_spelled_out_proposition = () => { + let (pm, proof) = + run( + "theorem t = forall x: Int -> forall y: Int -> x == 1 ==> y == 2 ==> x == x proof " + ++ "assume x == 1 => assume y == 2 => alias hx = x == 1 => " + ++ "revert hx => ? in t", + ); + check_resolves_to( + "alias resolves a spelled-out proposition, reaching a shadowed fact", + ~name_denotes="x == 1", + pm, + proof, + ); +}; + +/* Aliasing something that is not in scope gets revert's mark, and the + * body is checked against the unchanged goal. */ +let test_alias_unknown_fact_marks = () => { + let (pm, proof) = + run( + "theorem t = forall n: Int -> n == n proof " + ++ "alias hn = n == 99 => from n == n do rewrite refl end end in t", + ); + if (! + has_mark_kind( + pm, + proof, + fun + | ProofMark.UnknownFactReverted => true + | _ => false, + )) { + Alcotest.fail( + "aliasing a fact that is not in scope should mark " + ++ "UnknownFactReverted, got " + ++ String.concat( + ~sep="; ", + List.map(~f=ProofMark.show, marks_of(pm, proof)), + ), + ); + }; +}; + +/* An alias asserts nothing new, so it is obligation-free and + * goal-preserving: a proof that closes without it closes with it. */ +let test_alias_incurs_no_obligation = () => { + let (pm, proof) = + run( + "theorem t = forall n: Int -> n == 1 ==> n == n proof " + ++ "assume n == 1 => alias hn = assume => " + ++ "from n == n do rewrite refl end end in t", + ); + check_mark_free("alias is mark-free and goal-preserving", pm, proof); + /* Zero, not "one fewer": the `assume` here is an implication intro + (the goal's antecedent is exactly what it assumes), which is + obligation-free, and the alias adds nothing. */ + Alcotest.check( + Alcotest.int, + "alias incurs no obligation of its own", + 0, + List.length(ProofMap.obligations_of_proof(pm, proof)), + ); +}; + +/* --- 6. names that were never introduced ---------------------------- */ + +let test_unknown_name_is_unknown_equality = () => { + let (pm, proof) = + run( + "theorem t = forall n: Int -> n == n proof " + ++ "cases n > 0 | true => rewrite hzz end; ? " + ++ "| false => ? end in t", + ); + check_has_unknown_equality( + "citing a name that was never introduced", + "hzz", + pm, + proof, + ); +}; + +/* A fact's name is scoped to the form that introduced it. */ +/* A sub-pattern in parens or a projector is the same hypothesis as the + * bare one, so it is named for its variable. */ +let test_wrapped_sub_pattern_is_named_for_its_variable = () => + List.iter( + ~f= + pat_src => { + let exp = + Test_Evaluator_Prelude.parse_exp( + "case (? : (rec t -> +Z+S(t))) | " + ++ pat_src + ++ " => 0 | _ => 1 end", + ); + let statics = ProofStatics.of_info_map(fst(statics_and_elab(exp))); + let pat = + switch (exp.term) { + | Match(_, [(p, _), ..._]) => p + | _ => fail("expected a case expression: " ++ pat_src) + }; + let t = + switch (statics.typ(Pat.rep_id(pat))) { + | Some(t) => t + | None => fail("no type for pattern: " ++ pat_src) + }; + check( + list(string), + pat_src, + ["ih_n"], + List.map( + ~f=Induction.hypothesis_name, + Induction.hypotheses(statics, t, pat), + ), + ); + }, + ["S(n)", "S((n))", "S(^^fold(n))"], + ); + +let test_name_is_scoped_to_its_form = () => { + let (pm, proof) = + run( + "theorem t = forall n: Int -> n == n proof " + ++ "cases n > 0 | true => alias hn = case_eq => ? | false => ? end; " + ++ "rewrite hn end in t", + ); + check_has_unknown_equality( + "a fact's name does not escape its form", + "hn", + pm, + proof, + ); +}; + +let tests = ( + "HypothesisNaming", + [ + test_case( + "shadowed bare name resolves innermost", + `Quick, + test_shadowed_name_resolves_innermost, + ), + test_case( + "rewrite steps resolve innermost too", + `Quick, + test_axiom_step_also_resolves_innermost, + ), + test_case( + "assume-as leaves the outer assume citable", + `Quick, + test_named_assume_leaves_outer_citable, + ), + test_case( + "a fact's name denotes its own fact", + `Quick, + test_assume_name_denotes_its_own_fact, + ), + test_case( + "bare case_eq at depth is the inner split's", + `Quick, + test_bare_case_eq_at_depth_is_the_inner_one, + ), + test_case( + "aliased split cited from a deep leaf", + `Quick, + test_aliased_split_cited_from_deep_leaf, + ), + test_case("duplicate names shadow", `Quick, test_duplicate_name_shadows), + test_case( + "alias keeps an outer fact past a shadow", + `Quick, + test_alias_keeps_outer_fact_past_a_shadow, + ), + test_case( + "alias resolves a spelled-out proposition", + `Quick, + test_alias_by_spelled_out_proposition, + ), + test_case( + "alias of an unknown fact marks", + `Quick, + test_alias_unknown_fact_marks, + ), + test_case( + "alias incurs no obligation", + `Quick, + test_alias_incurs_no_obligation, + ), + test_case( + "a name never introduced is UnknownEquality", + `Quick, + test_unknown_name_is_unknown_equality, + ), + test_case( + "a fact's name does not escape its form", + `Quick, + test_name_is_scoped_to_its_form, + ), + test_case( + "a wrapped sub-pattern is named for its variable", + `Quick, + test_wrapped_sub_pattern_is_named_for_its_variable, + ), + ], +); diff --git a/test/evaluator/Test_Instantiation.re b/test/evaluator/Test_Instantiation.re new file mode 100644 index 0000000000..c7fe30a920 --- /dev/null +++ b/test/evaluator/Test_Instantiation.re @@ -0,0 +1,438 @@ +open Alcotest; +open Language; +open Test_Evaluator_Prelude; +open Test_ProofMap.Harness; +open Poly; + +/* Explicit instantiation at the citation site: + * + * `rewrite with = end` + * `rewrite <- with = end` + * `revert with = => ` + * + * For the axiom step the binding is seeded into `MatchExp`'s match + * context before matching, so `UnderdeterminedInstantiation` only fires + * on metavariables still unresolved after seeding. For `revert` the + * named binder of the (quantified) in-scope fact is eliminated and the + * instantiated fact is what moves into the goal. + * + * The instantiation gate applies to the supplied expression as it does + * to a matched one: possible divergence is refused, domain conditions + * become obligations. */ + +let one_line = (s: string): string => + String.map(~f=c => c == '\n' ? ' ' : c, s); + +let obligation_goals = (pm, proof): list(string) => + ProofMap.obligations_of_proof(pm, proof) + |> List.map(~f=(ob: Obligation.t) => one_line(print_exp(ob.goal))); + +let check_has_obligation = (msg, needle: string, pm, proof) => { + let goals = obligation_goals(pm, proof); + if (!List.exists(~f=g => g == needle, goals)) { + Alcotest.fail( + msg + ++ ": expected an obligation `" + ++ needle + ++ "`, got [" + ++ String.concat(~sep=", ", goals) + ++ "]", + ); + }; +}; + +/* --- Fixture ------------------------------------------------------------- + + `lem` is a conditional rule whose binder `n` appears in the antecedent + but not in the conclusion, so matching the conclusion can never + resolve it. (The quantified inductive hypotheses of + Test_Milestone_STLC have this shape.) Its own proof is a hole: a + cited fact need not be proven to be cited. */ + +let prelude = "let f = fun x -> x + 1 in "; + +/* A general-recursive function the totality checker cannot accept: the + recursive call's argument is arithmetic, not a strict subterm. */ +let diverger = "let bad = fun x -> bad(x + 1) in "; + +let lem = "theorem lem = forall n: Int -> n == 1 ==> f(2) == 3 proof ? in "; + +let src = (rest: string): string => prelude ++ lem ++ rest; + +/* --- axiom + with -------------------------------------------------------- */ + +/* The control: without a `with` clause the citation is refused. */ +let test_axiom_underdetermined_without_with = () => { + let (pm, proof) = + run_named( + "g", + src( + "theorem g = f(2) == 3 proof from f(2) do rewrite lem end end in g", + ), + ); + if (! + has_mark_kind( + pm, + proof, + fun + | ProofMark.UnderdeterminedInstantiation(_) => true + | _ => false, + )) { + Alcotest.fail( + "citing `lem` without `with` should be underdetermined\n" + ++ dump(pm, proof), + ); + }; +}; + +/* Seeding `n` resolves the rule, the rewrite goes through, and the + instantiated antecedent `1 == 1` is incurred as an obligation, + discharged by closed evaluation, so the theorem is fully Proven. */ +let test_axiom_with_resolves = () => { + let (pm, proof) = + run_named( + "g", + src( + "theorem g = f(2) == 3 proof from f(2) do rewrite lem with n = 1 end end; from 3 == 3 do step end in g", + ), + ); + check_mark_free("axiom+with", pm, proof); + check_has_obligation( + "axiom+with incurs its antecedent", + "1 == 1", + pm, + proof, + ); + check_proven_given_lemmas("axiom+with closes the goal", pm, proof); +}; + +/* `rewrite <-` takes the clause too (right-to-left application). */ +let test_axiomrev_with_resolves = () => { + let (pm, proof) = + run_named( + "g", + src( + "theorem g = 3 == 3 proof from 3 do rewrite <- lem with n = 1 end end in g", + ), + ); + check_mark_free("rewrite <-+with", pm, proof); +}; + +/* A `with` clause naming something that is not a binder of the cited + rule is marked and passes the goal through. */ +let test_axiom_with_unknown_var = () => { + let (pm, proof) = + run_named( + "g", + src( + "theorem g = f(2) == 3 proof from f(2) do rewrite lem with m = 1 end end in g", + ), + ); + if (! + has_mark_kind( + pm, + proof, + fun + | ProofMark.UnknownInstantiationVar(_) => true + | _ => false, + )) { + Alcotest.fail( + "`with m = ...` should be an unknown instantiation variable\n" + ++ dump(pm, proof), + ); + }; +}; + +/* --- The gates apply to the supplied expression ------------------------- */ + +/* Divergence is refused, never an obligation: a supplied expression + whose call graph reaches a non-structural fix can't be used to + instantiate. */ +let test_axiom_with_divergent_is_refused = () => { + let (pm, proof) = + run_named( + "g", + prelude + ++ diverger + ++ lem + ++ "theorem g = f(2) == 3 proof from f(2) do rewrite lem with n = bad(1) end end in g", + ); + if (! + has_mark_kind( + pm, + proof, + fun + | ProofMark.PossiblyDivergentInstantiation(_) => true + | _ => false, + )) { + Alcotest.fail( + "a divergent supplied instantiation should be refused\n" + ++ dump(pm, proof), + ); + }; +}; + +/* A domain error is an obligation: instantiating at `6 / d` incurs + `d != 0` through the ordinary scan. */ +let test_axiom_with_domain_condition = () => { + let (pm, proof) = + run_named( + "g", + src( + "theorem g = forall d: Int -> f(2) == 3 proof forall d => from f(2) do rewrite lem with n = 6 / d end end; from 3 == 3 do step end in g", + ), + ); + check_has_obligation( + "instantiating at `6 / d` scans for the denominator", + "d != 0", + pm, + proof, + ); +}; + +/* --- revert + with ------------------------------------------------------- */ + +/* `p` is a quantified fact in scope. `revert p with n = 5` moves the + instance `5 + 0 == 5` into the goal, not the quantified statement. */ +let quantified = "theorem p = forall n: Int -> n + 0 == n proof ? in "; + +let test_revert_with_instantiates = () => { + let (pm, proof) = + run_named( + "g", + prelude + ++ quantified + ++ "theorem g = f(2) == 3 proof revert p with n = 5 => from 5 + 0 do step end; from 5 == 5 do step end; from true ==> f(2) == 3 do step end; from f(2) do step end; from 2 + 1 do step end; from 3 == 3 do step end in g", + ); + check_mark_free("revert+with", pm, proof); + check_status("revert+with closes the goal", ProofMap.Proven, pm, proof); +}; + +/* A quantified inductive hypothesis, cited by name and instantiated, as + in Test_Milestone_STLC. It covers two things the spelled-out form + doesn't: by-name resolution of a fact, and identification of a binder + whose installed name carries substitution-renaming primes the source + never shows. */ +let ih_src = (cite: string): string => + "type L = +Nil+Cons(L) in " + ++ "let sz = fun l -> case l | Nil => 0 | Cons(r) => sz(r) + 1 end in " + ++ "theorem ihp = forall l0: L -> forall k0: Int -> sz(l0) == k0 ==> sz(l0) >= 0 proof generalize k0 => induction l0 " + ++ "| Nil => ? | Cons(r0) => forall k0 => " + ++ cite + ++ " end in ihp"; + +let test_revert_ih_by_name = () => { + let (pm, proof) = run_named("ihp", ih_src("revert ih_r0 => ?")); + if (has_mark_kind( + pm, + proof, + fun + | ProofMark.UnknownFactReverted => true + | _ => false, + )) { + Alcotest.fail( + "a quantified IH should be revertible BY NAME\n" ++ dump(pm, proof), + ); + }; +}; + +let test_revert_ih_with_instantiation = () => { + let (pm, proof) = + run_named("ihp", ih_src("revert ih_r0 with k0 = 7 => ?")); + check_mark_free("revert ih_r0 with k0 = 7", pm, proof); + /* The antecedent moved into the goal is the instance at 7: the + quantifier is gone and `7` has replaced the binder. */ + let d = dump(pm, proof); + if (!contains(d, "== 7 ==>")) { + Alcotest.fail( + "expected the instantiated antecedent `... == 7 ==> ...` in the " + ++ "goal:\n" + ++ d, + ); + }; +}; + +/* Naming a binder the fact does not quantify over is marked. */ +let test_revert_with_unknown_binder = () => { + let (pm, proof) = + run_named( + "g", + prelude + ++ quantified + ++ "theorem g = f(2) == 3 proof revert p with q = 5 => ? in g", + ); + if (! + has_mark_kind( + pm, + proof, + fun + | ProofMark.RevertFactNotQuantified(_) => true + | _ => false, + )) { + Alcotest.fail( + "`revert p with q = ...` should report a non-quantified binder\n" + ++ dump(pm, proof), + ); + }; +}; + +/* The gates apply here too. */ +let test_revert_with_divergent_is_refused = () => { + let (pm, proof) = + run_named( + "g", + prelude + ++ diverger + ++ quantified + ++ "theorem g = f(2) == 3 proof revert p with n = bad(1) => ? in g", + ); + if (! + has_mark_kind( + pm, + proof, + fun + | ProofMark.PossiblyDivergentInstantiation(_) => true + | _ => false, + )) { + Alcotest.fail( + "a divergent `revert ... with` instantiation should be refused\n" + ++ dump(pm, proof), + ); + }; +}; + +/* --- Every binder assigned ---------------------------------------------- + + `z`'s binder `n` occurs only on its right-hand side, so citing it at a + bare `0` leaves `n` unassigned, though no assumption mentions it. */ + +let zero_mul = "theorem z = forall n: Int -> 0 == n * 0 proof ? in "; + +let check_underdetermined_passes_through = (src: string) => { + let (pm, proof) = run_named("g", zero_mul ++ src); + /* The citation, inside the focus on `0`. */ + let step = + switch (proof.term) { + | Focus({body, _}) => body + | _ => proof + }; + switch (ProofMap.lookup(Proof.rep_id(step), pm)) { + | Some({ + marks: [UnderdeterminedInstantiation({equality: "z"})], + incoming, + outgoing, + _, + }) + when incoming == outgoing => + () + | _ => + Alcotest.fail( + "expected the citation refused and the goal unchanged\n" + ++ dump(pm, proof), + ) + }; +}; + +let test_unassigned_binder_in_conclusion = () => + check_underdetermined_passes_through( + "theorem g = 0 == 0 proof from 0 do rewrite z end end in g", + ); + +/* The proof's own `n` doesn't count as an assignment of the rule's. */ +let test_unassigned_binder_shadowed = () => + check_underdetermined_passes_through( + "theorem g = forall n: Int -> 0 == 0 proof from 0 do rewrite z end end in g", + ); + +let test_discovery_skips_unassigned_binder = () => { + let rule = ProofRule.exp_to_rule(parse_exp("forall n: Int -> 0 == n * 0")); + let target = parse_exp("0"); + let (info_map, _) = statics_and_elab(target); + Alcotest.check( + Alcotest.bool, + "not offered at a bare `0`", + false, + ProofRule.Rewrite.is_active( + ~statics=ProofStatics.of_info_map(info_map), + ~env=Environment.empty, + rule, + target, + ), + ); +}; + +let tests = ( + "Evaluator.Instantiation", + [ + test_case( + "control: no `with` is still underdetermined", + `Quick, + test_axiom_underdetermined_without_with, + ), + test_case( + "axiom+with resolves an underdetermined rule", + `Quick, + test_axiom_with_resolves, + ), + test_case( + "rewrite <-+with resolves too", + `Quick, + test_axiomrev_with_resolves, + ), + test_case( + "axiom+with: unknown binder name is marked", + `Quick, + test_axiom_with_unknown_var, + ), + test_case( + "gate: divergent instantiation is refused", + `Quick, + test_axiom_with_divergent_is_refused, + ), + test_case( + "gate: domain condition becomes an obligation", + `Quick, + test_axiom_with_domain_condition, + ), + test_case( + "revert+with cashes in the instance", + `Quick, + test_revert_with_instantiates, + ), + test_case( + "revert: a quantified IH is citable by name", + `Quick, + test_revert_ih_by_name, + ), + test_case( + "revert+with: an IH instantiates by name", + `Quick, + test_revert_ih_with_instantiation, + ), + test_case( + "revert+with: non-quantified binder is marked", + `Quick, + test_revert_with_unknown_binder, + ), + test_case( + "revert+with: divergent instantiation is refused", + `Quick, + test_revert_with_divergent_is_refused, + ), + test_case( + "a binder only in the conclusion must be assigned", + `Quick, + test_unassigned_binder_in_conclusion, + ), + test_case( + "a shadowing proof variable doesn't assign a binder", + `Quick, + test_unassigned_binder_shadowed, + ), + test_case( + "discovery doesn't offer an unassigned binder", + `Quick, + test_discovery_skips_unassigned_binder, + ), + ], +); diff --git a/test/evaluator/Test_ListFoldLibrary.re b/test/evaluator/Test_ListFoldLibrary.re new file mode 100644 index 0000000000..f7f9cc5ae3 --- /dev/null +++ b/test/evaluator/Test_ListFoldLibrary.re @@ -0,0 +1,74 @@ +open Alcotest; +open Test_ProofMap.Harness; + +/* A small proof library: a Bool fold and its accumulator laws, where each + * later lemma cites the earlier ones. */ + +let library = {|let foldl = fun (xs : [Bool], f, acc : Bool) -> + case xs | [] => acc | x :: rest => foldl(rest, f, f(acc, x)) end in +let conj = fun (acc : Bool, x : Bool) -> acc && x in +theorem true_and = forall (p : Bool) -> (true && p) == p proof + induction p + | true => from true && true do step end; + from true == true do step end + | false => from true && false do step end; + from false == false do step end + end +in +theorem fold_conj_false = forall (xs : [Bool]) -> foldl(xs, conj, false) == false proof + induction xs + | [] => from foldl([], conj, false) do step end; + from false == false do step end + | h :: t => from foldl(h :: t, conj, false) do step end; + from conj(false, h) do step end; + from false && h do step end; + from foldl(t, conj, false) do rewrite ih_t end end; + from false == false do step end + end +in +theorem fold_conj_acc = forall (b : Bool) -> forall (xs : [Bool]) -> + foldl(xs, conj, b) == (b && foldl(xs, conj, true)) proof + induction b + | true => from true && foldl(xs, conj, true) do rewrite true_and end end; + from foldl(xs, conj, true) == foldl(xs, conj, true) do rewrite refl end end + | false => from foldl(xs, conj, false) do rewrite fold_conj_false end end; + from false && foldl(xs, conj, true) do step end; + from false == false do step end + end +in +theorem fold_conj_cons = forall (h : Bool) -> forall (t : [Bool]) -> + foldl(h :: t, conj, true) == (h && foldl(t, conj, true)) proof + from foldl(h :: t, conj, true) do step end; + from conj(true, h) do step end; + from true && h do step end; + from foldl(t, conj, h) do rewrite fold_conj_acc end end; + induction h + | true => from true && foldl(t, conj, true) do rewrite true_and end end; + from true && foldl(t, conj, true) do rewrite true_and end end; + from foldl(t, conj, true) == foldl(t, conj, true) do rewrite refl end end + | false => from false && foldl(t, conj, true) do step end; + from false && foldl(t, conj, true) do step end; + from false == false do step end + end +in +0|}; + +let proven = (name: string) => + test_case( + name ++ " is proven", + `Quick, + () => { + let (pm, proof) = run_named(name, library); + check_proven(name, pm, proof); + }, + ); + +let tests = ( + "ProofLibrary.ListFold", + [ + proven("true_and"), + proven("fold_conj_false"), + proven("fold_conj_acc"), + proven("fold_conj_cons"), + ], +); diff --git a/test/evaluator/Test_Milestone_STLC.re b/test/evaluator/Test_Milestone_STLC.re new file mode 100644 index 0000000000..be4b7403c8 --- /dev/null +++ b/test/evaluator/Test_Milestone_STLC.re @@ -0,0 +1,700 @@ +open Alcotest; +open Language; +open Test_Evaluator_Prelude; +open Test_ProofMap.Harness; + +/* A minimal simply-typed lambda calculus (de Bruijn) encoded as Hazel + * ADTs, with structurally recursive decision procedures (ty_eq / nth_ty / + * infer / step / subst / shift), and a proof of progress. + * + * Fully proven theorems assert Proven with nothing pending; partial + * proofs carry `?` holes with `FRICTION:` comments and assert their exact + * intermediate status, so the file pins what the prover can't yet do. */ + +let has_mark_kind = Test_ProofMap.has_mark_kind; + +/* --- The encoding ------------------------------------------------------- */ + +/* Types: TB (base) | TArr(Ty, Ty). Terms, de Bruijn: TmVar(Int) | + * TmLam(Ty, Term) | TmAp(Term, Term). Option types are hand-rolled ADTs + * (MaybeTy / MaybeTm) — the builtin Option is not used, to keep + * constructor coverage/pattern behavior under our control. + * + * All decision procedures take a tuple and are structurally recursive in + * one argument position; nth_ty recurses on the list (index decremented + * alongside), not on the Int. + * + * `step` implements CBV: congruence-1 (head not a value), congruence-2 + * (head value, argument not), beta (both values, head a lambda). Beta is + * `subst((0, y, b))` — the outer down-shift of the classical de Bruijn + * beta is omitted (progress is insensitive to it and negative literals + * would be the only use of them here); `shift` is still exercised + * under binders inside `subst`. */ + +let prelude = + "type Ty = +TB+TArr(Ty, Ty) in " + ++ "type Term = +TmVar(Int)+TmLam(Ty, Term)+TmAp(Term, Term) in " + ++ "type MaybeTy = +NoTy+SomeTy(Ty) in " + ++ "type MaybeTm = +NoTm+SomeTm(Term) in " + ++ "let ty_eq = fun p -> case p | (TB, TB) => true | (TB, TArr(x, y)) => false | (TArr(x, y), TB) => false | (TArr(x1, y1), TArr(x2, y2)) => ty_eq((x1, x2)) && ty_eq((y1, y2)) end in " + ++ "let nth_ty = fun p -> case p | ([], n) => NoTy | (t :: rest, n) => if n == 0 then SomeTy(t) else nth_ty((rest, n - 1)) end in " + ++ "let lam_result = fun p -> case p | (t, NoTy) => NoTy | (t, SomeTy(t2)) => SomeTy(TArr(t, t2)) end in " + ++ "let ap_result = fun p -> case p | (NoTy, m) => NoTy | (SomeTy(TB), m) => NoTy | (SomeTy(TArr(ta, tb)), NoTy) => NoTy | (SomeTy(TArr(ta, tb)), SomeTy(s)) => (if ty_eq((ta, s)) then SomeTy(tb) else NoTy) end in " + ++ "let infer = fun p -> case p | (ctx, TmVar(n)) => nth_ty((ctx, n)) | (ctx, TmLam(t, b)) => lam_result((t, infer((t :: ctx, b)))) | (ctx, TmAp(e1, e2)) => ap_result((infer((ctx, e1)), infer((ctx, e2)))) end in " + ++ "let is_value = fun e -> case e | TmVar(n) => false | TmLam(t, b) => true | TmAp(x, y) => false end in " + /* is_lam's branch order differs from is_value's on purpose. With the + * same order the two definitions are alpha-equal, and a selector + * `is_value(TmVar(n))` with no occurrence as written would match an + * `is_lam(TmVar(n))` once both are unfolded. */ + ++ "let is_lam = fun e -> case e | TmLam(t, b) => true | TmVar(n) => false | TmAp(x, y) => false end in " + ++ "let is_some_tm = fun m -> case m | NoTm => false | SomeTm(x) => true end in " + ++ "let shift = fun p -> case p | (d, c, TmVar(n)) => (if n < c then TmVar(n) else TmVar(n + d)) | (d, c, TmLam(t, b)) => TmLam(t, shift((d, c + 1, b))) | (d, c, TmAp(x, y)) => TmAp(shift((d, c, x)), shift((d, c, y))) end in " + ++ "let subst = fun p -> case p | (j, v, TmVar(n)) => (if n == j then v else TmVar(n)) | (j, v, TmLam(t, b)) => TmLam(t, subst((j + 1, shift((1, 0, v)), b))) | (j, v, TmAp(x, y)) => TmAp(subst((j, v, x)), subst((j, v, y))) end in " + ++ "let step = fun e -> case e | TmVar(n) => NoTm | TmLam(t, b) => NoTm | TmAp(x, y) => (if is_value(x) then (if is_value(y) then case x | TmVar(n) => NoTm | TmLam(t, b) => SomeTm(subst((0, y, b))) | TmAp(f, a) => NoTm end else case step(y) | NoTm => NoTm | SomeTm(yp) => SomeTm(TmAp(x, yp)) end) else case step(x) | NoTm => NoTm | SomeTm(xp) => SomeTm(TmAp(xp, y)) end) end in "; + +let program = (rest: string): string => prelude ++ rest; + +/* --- (a) Smoke: every decision procedure passes the totality gate ------ */ + +/* A refl instantiation at `f(x)` runs the instantiation gate on the + * substituted `f` (its FixF spine must be detected structurally + * recursive). Proven with no obligations means the gate passed. */ +let smoke = (fn_app: string): unit => { + let src = + program( + "theorem t = forall v: Term -> forall w: Ty -> forall ts: [Ty] -> forall i: Int -> forall m: MaybeTm -> " + ++ fn_app + ++ " == " + ++ fn_app + ++ " proof rewrite refl end in t", + ); + let (pm, proof) = run_named("t", src); + check_obligation_count( + "smoke: no obligations for " ++ fn_app, + 0, + pm, + proof, + ); + check_proven("smoke: " ++ fn_app ++ " refl is Proven", pm, proof); +}; + +let test_smoke_ty_eq = () => smoke("ty_eq((w, w))"); +let test_smoke_nth_ty = () => smoke("nth_ty((ts, i))"); +let test_smoke_infer = () => smoke("infer((ts, v))"); +let test_smoke_is_value = () => smoke("is_value(v)"); +let test_smoke_step = () => smoke("step(v)"); +let test_smoke_subst = () => smoke("subst((i, v, v))"); +let test_smoke_shift = () => smoke("shift((i, i, v))"); +let test_smoke_is_some_tm = () => smoke("is_some_tm(m)"); + +/* --- Dynamics sanity --------------------------------------------------- + * + * Each closed equation evaluates to `true`, which checks the encoding's + * dynamics. They run in the evaluator, not as `assume`d facts, because + * discharge by closed evaluation never runs a recursive function. */ + +let closed_fact = (fact: string): unit => + Alcotest.check( + Alcotest.bool, + fact, + true, + Exp.fast_equal( + parse_and_evaluate(program(fact)), + Exp.temp(Atom(Bool(true))), + ), + ); + +/* infer types the identity function. */ +let test_dyn_infer_id = () => + closed_fact("infer(([], TmLam(TB, TmVar(0)))) == SomeTy(TArr(TB, TB))"); + +/* infer rejects an unbound variable and a self-application shape. */ +let test_dyn_infer_unbound = () => + closed_fact("infer(([], TmVar(0))) == NoTy"); + +/* A well-typed application: (\\x:TB. x) applied under a lambda. */ +let test_dyn_infer_ap = () => + closed_fact( + "infer(([], TmAp(TmLam(TB, TmVar(0)), TmLam(TB, TmVar(0))))) == NoTy", + ); + +/* step: beta fires on value-value application. */ +let test_dyn_step_beta = () => + closed_fact( + "step(TmAp(TmLam(TB, TmVar(0)), TmLam(TB, TmVar(0)))) == SomeTm(TmLam(TB, TmVar(0)))", + ); + +/* step: congruence-1 steps the head of a nested application. */ +let test_dyn_step_cong = () => + closed_fact( + "step(TmAp(TmAp(TmLam(TB, TmVar(0)), TmLam(TB, TmVar(0))), TmVar(3))) == SomeTm(TmAp(TmLam(TB, TmVar(0)), TmVar(3)))", + ); + +/* step: values and stuck terms do not step. */ +let test_dyn_step_stuck = () => closed_fact("step(TmVar(0)) == NoTm"); + +/* --- (b) Canonical forms ------------------------------------------------ */ + +/* The ==>-chain phrasing is fully provable: every case is closed by + * evaluation alone (the McCarthy dynamics of `==>` turn a false + * antecedent into `true` without touching the consequent). */ +let canonical_impl_src = + program( + "theorem canonical = forall e: Term -> forall t1: Ty -> forall t2: Ty -> is_value(e) ==> infer(([], e)) == SomeTy(TArr(t1, t2)) ==> is_lam(e) proof induction e " + ++ "| TmVar(n) => from is_value(TmVar(n)) do step end; from false ==> infer(([], TmVar(n))) == SomeTy(TArr(t1, t2)) ==> is_lam(TmVar(n)) do step end " + /* FRICTION: evaluating the antecedent to `true` and stripping + * `true ==> _` by eval doesn't work: the eval step's leading + * auto-steps fire hidden FixUnwrap transitions inside the untouched + * middle antecedent, leaving it fix-unrolled and unmatchable for the + * later assume-intro (fast_equal). Introducing both antecedents by + * assume avoids evaluating near them. */ + ++ "| TmLam(t, b) => assume is_value(TmLam(t, b)) => assume infer(([], TmLam(t, b))) == SomeTy(TArr(t1, t2)) => from is_lam(TmLam(t, b)) do step end " + ++ "| TmAp(x, y) => from is_value(TmAp(x, y)) do step end; from false ==> infer(([], TmAp(x, y))) == SomeTy(TArr(t1, t2)) ==> is_lam(TmAp(x, y)) do step end " + ++ "end in canonical", + ); + +let test_canonical_impl_proven = () => { + let (pm, proof) = run_named("canonical", canonical_impl_src); + check_obligation_count( + "canonical (==> form): no obligations", + 0, + pm, + proof, + ); + check_proven("canonical (==> form) is fully Proven", pm, proof); +}; + +/* A small genuine theorem exercising the full TmVar eval chain of + * progress (an unbound variable types as nothing, so anything follows): + * 4 eval steps unfold infer/nth_ty, falsify the antecedent, and + * McCarthy-collapse the implication. */ +let var_never_types_src = + program( + "theorem var_never_types = forall n: Int -> forall t: Ty -> infer(([], TmVar(n))) == SomeTy(t) ==> false proof " + ++ "from infer(([], TmVar(n))) do step end; from nth_ty(([], n)) do step end; from NoTy == SomeTy(t) do step end; from false ==> false do step end in var_never_types", + ); + +let test_var_never_types = () => { + let (pm, proof) = run_named("var_never_types", var_never_types_src); + check_obligation_count("var_never_types: no obligations", 0, pm, proof); + check_proven("var_never_types is fully Proven", pm, proof); +}; + +/* --- Step-unfolding helper lemmas (equality conclusions) ---------------- + * + * `step` on an application unfolds to a three-way conditional blob; to + * reason under it the blob must be quoted verbatim as an eval target. + * These lemmas pay that cost once each and export small guarded + * equations whose antecedents discharge by lookup against split case_eq + * facts at the use sites. */ + +let cong1_case = (hd: string, arg: string): string => + "case step(" + ++ hd + ++ ") | NoTm => NoTm | SomeTm(xp) => SomeTm(TmAp(xp, " + ++ arg + ++ ")) end"; + +let cong2_case = (hd: string, arg: string): string => + "case step(" + ++ arg + ++ ") | NoTm => NoTm | SomeTm(yp) => SomeTm(TmAp(" + ++ hd + ++ ", yp)) end"; + +/* Congruence-1: a non-value head means the application steps iff the + * head does. */ +let lemma_step_ap_val1 = + "theorem step_ap_val1 = forall u1: Term -> forall u2: Term -> is_value(u1) == false ==> step(TmAp(u1, u2)) == (" + ++ cong1_case("u1", "u2") + /* TODO: finish the proof by collapsing the conditional the eval + * leaves. `progress` cites the lemma as stated. */ + ++ ") proof assume is_value(u1) == false => from step(TmAp(u1, u2)) do step end; from is_value(u1) do rewrite assume end end; ? in "; + +/* Congruence-2 at a lambda head: the head's value-ness is computed by + * evaluation inside the lemma, so no is_value(head) antecedent is + * needed. */ +let lemma_step_lam_ap2 = + "theorem step_lam_ap2 = forall w1: Ty -> forall q1: Term -> forall u2: Term -> is_value(u2) == false ==> step(TmAp(TmLam(w1, q1), u2)) == (" + ++ cong2_case("TmLam(w1, q1)", "u2") + /* TODO: finish, as for step_ap_val1. */ + ++ ") proof assume is_value(u2) == false => from step(TmAp(TmLam(w1, q1), u2)) do step end; from is_value(TmLam(w1, q1)) do step end; from is_value(u2) do rewrite assume end end; ? in "; + +/* Beta: both sides values, lambda head. */ +let lemma_step_beta = "theorem step_beta = forall w1: Ty -> forall q1: Term -> forall u2: Term -> is_value(u2) == true ==> step(TmAp(TmLam(w1, q1), u2)) == SomeTm(subst((0, u2, q1))) proof assume is_value(u2) == true => from step(TmAp(TmLam(w1, q1), u2)) do step end; from is_value(TmLam(w1, q1)) do step end; from is_value(u2) do rewrite assume end end; ? in "; + +/* is_some_tm(SomeTm(v)) == true — needed because evaluating + * `is_some_tm(SomeTm(subst(...)))` directly would first unfold the + * CBV-forced `subst` application into an unquotable blob. */ +let lemma_some_tm_is_some = "theorem some_tm_is_some = forall u1: Term -> is_some_tm(SomeTm(u1)) == true proof from is_some_tm(SomeTm(u1)) do step end; from true == true do rewrite refl end end in "; + +/* The step-unfolding lemmas' proofs are partial (see the FRICTION notes + * in each source): every retained step is mark-free, no obligations are + * incurred (assume is intro), and the proof pins as Incomplete. Their + * statements still act as conditional rewrite rules at the progress use + * sites: a rule comes from its statement, not its proof. */ +let lemma_partial_test = (name: string, lemma: string): unit => { + let (pm, proof) = run_named(name, program(lemma ++ name)); + if (Option.is_some(Test_ProofMap.find_marked_sub(pm, proof))) { + Alcotest.fail( + "lemma " ++ name ++ " should be mark-free\n" ++ dump(pm, proof), + ); + }; + check_obligation_count( + "lemma " ++ name ++ ": no obligations", + 0, + pm, + proof, + ); + check_status( + "lemma " ++ name ++ " pins as Incomplete", + ProofMap.Incomplete, + pm, + proof, + ); +}; + +let lemma_test = (name: string, lemma: string): unit => { + let (pm, proof) = run_named(name, program(lemma ++ name)); + check_proven("lemma " ++ name ++ " is fully Proven", pm, proof); + check_obligation_count( + "lemma " ++ name ++ ": no obligations", + 0, + pm, + proof, + ); +}; + +let test_lemma_step_ap_val1 = () => + lemma_partial_test("step_ap_val1", lemma_step_ap_val1); +let test_lemma_step_lam_ap2 = () => + lemma_partial_test("step_lam_ap2", lemma_step_lam_ap2); +let test_lemma_step_beta = () => + lemma_partial_test("step_beta", lemma_step_beta); +let test_lemma_some_tm_is_some = () => + lemma_test("some_tm_is_some", lemma_some_tm_is_some); + +/* --- (c) Progress ------------------------------------------------------- + * + * forall e -> forall t -> infer([], e) == SomeTy(t) ==> + * is_value(e) || is_some_tm(step(e)) + * + * by generalize t => induction e. TmVar and TmLam close outright. The + * TmAp case is driven by ADT/bool splits on the computed scrutinees of + * infer's unfolding, closing every branch the vocabulary can close: + * - all branches where infer computes NoTy: antecedent evaluates to + * false, McCarthy `==>` collapses the goal to true; + * - head-not-value + step(x0) = SomeTm(_): congruence lemma; + * - lambda head + value argument: beta lemma; + * - lambda head + non-value argument + step(y0) = SomeTm(_): + * congruence lemma; + * - value head that is a TmVar or a TmAp: vacuous by canonical forms, + * closed by ex falso (`revert` the value-ness case_eq into the goal, + * rewrite x0 there by the shape case_eq, and let evaluation falsify + * the antecedent); + * - value head that steps to NoTm, and lambda head + non-value + * argument stepping to NoTm: vacuous by the inductive hypothesis at + * the type the enclosing split produced. `revert` the IH + * instantiated there (`revert ih_x0 with t0 = tf0`), rewrite its + * antecedent away with the case_eqs in scope, and the same ex falso + * collapse finishes it. + * `progress` is fully Proven (test_progress_proven). */ + +let progress_consequent = "is_value(TmAp(x0, y0)) || is_some_tm(step(TmAp(x0, y0)))"; + +/* One antecedent-falsified leaf: collapse ap_result by evaluation, + * falsify, McCarthy-collapse. The splits on `infer` calls have already + * replaced them in the goal. */ +let noty_leaf = (pair: string): string => + "from ap_result((" + ++ pair + ++ ")) do step end; from NoTy == SomeTy(t0) do step end; from false ==> " + ++ progress_consequent + ++ " do step end"; + +let progress_src = + program( + lemma_step_ap_val1 + ++ lemma_step_lam_ap2 + ++ lemma_step_beta + ++ lemma_some_tm_is_some + ++ "theorem progress = forall e0: Term -> forall t0: Ty -> infer(([], e0)) == SomeTy(t0) ==> is_value(e0) || is_some_tm(step(e0)) proof generalize t0 => induction e0 " + ++ "| TmVar(m0) => forall t0 => from infer(([], TmVar(m0))) do step end; from nth_ty(([], m0)) do step end; from NoTy == SomeTy(t0) do step end; from false ==> is_value(TmVar(m0)) || is_some_tm(step(TmVar(m0))) do step end " + ++ "| TmLam(w0, q0) => forall t0 => assume infer(([], TmLam(w0, q0))) == SomeTy(t0) => from is_value(TmLam(w0, q0)) do step end; from true || is_some_tm(step(TmLam(w0, q0))) do step end " + ++ "| TmAp(x0, y0) => forall t0 => " + /* This case gets two inductive hypotheses, `ih_x0` and `ih_y0`, + * which the two leaves below cite as `ihx` / `ihy`. */ + ++ "alias ihx = ih_x0 => " + ++ "alias ihy = ih_y0 => " + ++ "from infer(([], TmAp(x0, y0))) do step end; " + /* `alias tx = case_eq` at the top of a case names this split's case + * equation, so the deep IH leaves below can still cite it: as + * `case_eq` it would be shadowed by the splits nested inside. */ + ++ "cases infer(([], x0)) " + ++ "| NoTy => " + ++ "cases infer(([], y0)) " + ++ "| NoTy => " + ++ noty_leaf("NoTy, NoTy") + ++ " | SomeTy(s0) => " + ++ noty_leaf("NoTy, SomeTy(s0)") + ++ " end " + ++ "| SomeTy(tf0) => alias tx = case_eq => " + ++ "cases tf0 " + ++ "| TB => cases infer(([], y0)) " + ++ "| NoTy => " + ++ noty_leaf("SomeTy(TB), NoTy") + ++ " | SomeTy(s0) => " + ++ noty_leaf("SomeTy(TB), SomeTy(s0)") + ++ " end " + ++ "| TArr(ta0, tb0) => cases infer(([], y0)) " + ++ "| NoTy => " + ++ noty_leaf("SomeTy(TArr(ta0, tb0)), NoTy") + ++ " | SomeTy(s0) => alias ty = case_eq => from ap_result((SomeTy(TArr(ta0, tb0)), SomeTy(s0))) do step end; " + ++ "cases ty_eq((ta0, s0)) " + ++ "| false => from if false then SomeTy(tb0) else NoTy do step end; from NoTy == SomeTy(t0) do step end; from false ==> " + ++ progress_consequent + ++ " do step end " + ++ "| true => from if true then SomeTy(tb0) else NoTy do step end; " + ++ "assume SomeTy(tb0) == SomeTy(t0) => " + /* The `is_value(x0)` split comes before the two goal-evaluating + * steps, so the ex falso leaves below get the goal as written and the + * evaluation happens only in the branch that wants it. */ + ++ "cases is_value(x0) " + /* Congruence-1: the head steps, so the application steps. */ + ++ "| false => alias vx = case_eq => from is_value(TmAp(x0, y0)) do step end; " + ++ "from false || is_some_tm(step(TmAp(x0, y0))) do step end; " + ++ "from step(TmAp(x0, y0)) do rewrite step_ap_val1 end end; " + ++ "cases step(x0) " + /* Vacuous by the inductive hypothesis. IH(x0) at t0 := tf0, with + * case_eq infer(([], x0)) == SomeTy(tf0) and is_value(x0) == false, + * forces step(x0) == SomeTm(_), which contradicts case_eq + * step(x0) == NoTm. The IH is quantified (`forall t0 -> A(t0) ==> D`) + * and D doesn't mention t0, so matching can't fix the binder: the + * citation has to say what t0 is. `revert ihx with t0 = tf0` moves the + * instance into the goal; then the case_eqs in scope rewrite A to + * `SomeTy(tf0) == SomeTy(tf0)` (refl: true) and D to `false`, + * leaving `false ==> G`, which McCarthy-collapses to true. */ + ++ "| NoTm => alias sx = case_eq => revert ihx with t0 = tf0 => " + ++ "from infer(([], x0)) do rewrite tx end end; " + ++ "from SomeTy(tf0) == SomeTy(tf0) do rewrite refl end end; " + ++ "from true ==> is_value(x0) || is_some_tm(step(x0)) do step end; " + ++ "from is_value(x0) do rewrite vx end end; " + ++ "from false || is_some_tm(step(x0)) do step end; " + ++ "from step(x0) do rewrite sx end end; " + ++ "from is_some_tm(NoTm) do step end; " + ++ "from false ==> is_some_tm(case NoTm | NoTm => NoTm | SomeTm(xp) => SomeTm(TmAp(xp, y0)) end) do step end " + ++ "| SomeTm(u0) => from is_some_tm(case SomeTm(u0) | NoTm => NoTm | SomeTm(xp) => SomeTm(TmAp(xp, y0)) end) do step end " + ++ "end " + ++ "| true => cases x0 " + /* Vacuous by canonical forms: is_value(x0) == true and + * x0 == TmVar(m0) are contradictory. Reverting the value-ness fact + * and rewriting x0 by the split's own case_eq gives + * `is_value(TmVar(m0)) == true`, which evaluates to `false`. */ + ++ "| TmVar(m0) => alias hx0 = case_eq => revert is_value(x0) == true => from x0 do rewrite hx0 end end; from is_value(TmVar(m0)) do step end; from false == true do step end; from false ==> (is_value(TmAp(TmVar(m0), y0)) || is_some_tm(step(TmAp(TmVar(m0), y0)))) do step end " + ++ "| TmLam(w0, q0) => from is_value(TmAp(TmLam(w0, q0), y0)) do step end; " + ++ "from false || is_some_tm(step(TmAp(TmLam(w0, q0), y0))) do step end; " + ++ "cases is_value(y0) " + /* Beta: the canonical-forms leaf. */ + ++ "| true => from step(TmAp(TmLam(w0, q0), y0)) do rewrite step_beta end end; from is_some_tm(SomeTm(subst((0, y0, q0)))) do rewrite some_tm_is_some end end " + /* Congruence-2 at a lambda head. */ + ++ "| false => alias vy = case_eq => from step(TmAp(TmLam(w0, q0), y0)) do rewrite step_lam_ap2 end end; " + ++ "cases step(y0) " + /* The same IH leaf as above, at IH(y0) and t0 := s0, cited through + * the `ihy` alias. */ + ++ "| NoTm => alias sy = case_eq => revert ihy with t0 = s0 => " + ++ "from infer(([], y0)) do rewrite ty end end; " + ++ "from SomeTy(s0) == SomeTy(s0) do rewrite refl end end; " + ++ "from true ==> is_value(y0) || is_some_tm(step(y0)) do step end; " + ++ "from is_value(y0) do rewrite vy end end; " + ++ "from false || is_some_tm(step(y0)) do step end; " + ++ "from step(y0) do rewrite sy end end; " + ++ "from is_some_tm(NoTm) do step end; " + ++ "from false ==> is_some_tm(case NoTm | NoTm => NoTm | SomeTm(yp) => SomeTm(TmAp(TmLam(w0, q0), yp)) end) do step end " + ++ "| SomeTm(u0) => from is_some_tm(case SomeTm(u0) | NoTm => NoTm | SomeTm(yp) => SomeTm(TmAp(TmLam(w0, q0), yp)) end) do step end " + ++ "end " + ++ "end " + /* Same ex falso as the TmVar leaf: is_value(x0) == true with + * x0 == TmAp(f0, a0). */ + ++ "| TmAp(f0, a0) => alias hx0 = case_eq => revert is_value(x0) == true => from x0 do rewrite hx0 end end; from is_value(TmAp(f0, a0)) do step end; from false == true do step end; from false ==> (is_value(TmAp(TmAp(f0, a0), y0)) || is_some_tm(step(TmAp(TmAp(f0, a0), y0)))) do step end " + ++ "end " + ++ "end " + ++ "end " + ++ "end " + ++ "end " + ++ "end in progress", + ); + +let test_progress_proven = () => { + let (pm, proof) = run_named("progress", progress_src); + /* Mark-free, with no holes. */ + if (Option.is_some(Test_ProofMap.find_marked_sub(pm, proof))) { + Alcotest.fail( + "progress should be mark-free\n--- proof dump ---\n" ++ dump(pm, proof), + ); + }; + /* The three step-lemma applications each incur exactly their + * instantiated antecedent, all discharged Remote against split case_eq + * facts. Nothing is Pending. */ + let obs = without_citations(ProofMap.obligations_of_proof(pm, proof)); + check_obligation_count( + "progress: exactly the 3 lemma antecedents", + 3, + pm, + proof, + ); + if (! + List.for_all( + ~f= + (ob: Obligation.t) => + switch (ob.discharge) { + | Obligation.Remote(_) => true + | _ => false + }, + obs, + )) { + Alcotest.fail( + "all progress obligations should discharge Remote (channel 1):\n" + ++ String.concat(~sep="\n", List.map(~f=show_obligation, obs)), + ); + }; + /* Every leaf closes: `progress` for STLC is proven in Hazel itself. The + * two vacuous leaves need the quantified inductive hypothesis at a type + * the split produced (`revert ihx with t0 = tf0` and + * `revert ihy with t0 = s0`), each naming its IH through an `alias`. */ + check_proven_given_lemmas("progress is fully Proven", pm, proof); +}; + +/* --- Addressing occurrences in an unfolded body ------------------------ + + After `eval step(TmAp(u1, u2))` unfolds step's body into the goal, the + calls in it name their functions, so written selectors find them: one + to another definition (`is_value(u2)`) and a recursive one + (`step(u1)`). */ + +let unroll_probe = (piece: string): (ProofMap.t, Proof.t) => { + let src = + program( + "theorem bp = forall u1: Term -> forall u2: Term -> is_value(u1) == false ==> step(TmAp(u1, u2)) == NoTm proof assume is_value(u1) == false => from step(TmAp(u1, u2)) do step end; from is_value(u1) do rewrite assume end end; from " + ++ piece + ++ " do step end; ? in bp", + ); + run_named("bp", src); +}; + +let test_unfolded_call_addressable = (piece: string, ()) => { + let (pm, proof) = unroll_probe(piece); + if (has_mark_kind( + pm, + proof, + fun + | ProofMark.PatternNotFound(_) => true + | _ => false, + )) { + Alcotest.fail(piece ++ " should be addressable\n" ++ dump(pm, proof)); + }; +}; + +/* --- Pins: inductive hypotheses --------------------------------------- */ + +/* Structural induction over a user ADT generates inductive hypotheses, + * although recursive-ADT constructor payloads carry the unrolled `rec` + * form while the scrutinee carries the alias form (see + * `Induction.hypotheses`). + * + * `revert` matches an in-scope fact by `Exp.fast_equal`, so a mark-free + * revert of the spelled-out statement pins the IH exactly: the goal at + * the sub-term x0, still quantified over t0 because of the + * `generalize`. */ +let ih_probe_src = (cite: string): string => + program( + "theorem ihprobe = forall e0: Term -> forall t0: Ty -> infer(([], e0)) == SomeTy(t0) ==> is_value(e0) || is_some_tm(step(e0)) proof generalize t0 => induction e0 " + ++ "| TmVar(m0) => ? | TmLam(w0, q0) => ? " + ++ "| TmAp(x0, y0) => forall t0 => " + ++ cite + ++ " end in ihprobe", + ); + +/* The IH exists, quantified over t0, at the sub-term x0. */ +let test_ih_exists_quantified = () => { + let (pm, proof) = + run_named( + "ihprobe", + ih_probe_src( + "revert forall t0 -> infer(([], x0)) == SomeTy(t0) ==> is_value(x0) || is_some_tm(step(x0)) => ?", + ), + ); + if (has_mark_kind( + pm, + proof, + fun + | ProofMark.UnknownFactReverted => true + | _ => false, + )) { + Alcotest.fail( + "the quantified IH at x0 should be an in-scope fact\n" + ++ dump(pm, proof), + ); + }; +}; + +/* Negative control: the IH is at the sub-term, not at the scrutinee. */ +let test_ih_not_at_scrutinee = () => { + let (pm, proof) = + run_named( + "ihprobe", + ih_probe_src( + "revert forall t0 -> infer(([], TmAp(x0, y0))) == SomeTy(t0) ==> is_value(TmAp(x0, y0)) || is_some_tm(step(TmAp(x0, y0))) => ?", + ), + ); + if (! + has_mark_kind( + pm, + proof, + fun + | ProofMark.UnknownFactReverted => true + | _ => false, + )) { + Alcotest.fail("the goal at the scrutinee is not an IH"); + }; +}; + +/* Without a `with` clause, citing the quantified IH is refused: its + conclusion doesn't mention `t0`, so matching it leaves the binder + unresolved while the antecedent mentions it, an underdetermined + instantiation. */ +let test_ih_citation_underdetermined_without_with = () => { + let (pm, proof) = + run_named( + "ihprobe", + ih_probe_src( + /* This case installs two inductive hypotheses, one per sub-term; + the `alias` names x0's. */ + "alias ihx = ih_x0 => revert ihx => from is_value(x0) || is_some_tm(step(x0)) do rewrite ihx end end", + ), + ); + if (! + has_mark_kind( + pm, + proof, + fun + | ProofMark.UnderdeterminedInstantiation(_) => true + | _ => false, + )) { + Alcotest.fail( + "citing the quantified IH with no instantiation should still be " + ++ "refused as underdetermined\n" + ++ dump(pm, proof), + ); + }; +}; + +/* ...and with one it goes through: `revert ih_y0 with t0 = ` moves the + instance of the IH into the goal, as the vacuous `progress` leaves do + (test_progress_proven). The IH is cited by name. */ +let test_ih_instantiated_with_clause = () => { + let (pm, proof) = + run_named("ihprobe", ih_probe_src("revert ih_y0 with t0 = t0 => ?")); + if (Option.is_some(Test_ProofMap.find_marked_sub(pm, proof))) { + Alcotest.fail( + "instantiating the quantified IH should be mark-free\n" + ++ dump(pm, proof), + ); + }; +}; + +/* The binder must actually be one the IH quantifies. */ +let test_ih_instantiation_unknown_binder = () => { + let (pm, proof) = + run_named("ihprobe", ih_probe_src("revert ih_y0 with zz = t0 => ?")); + if (! + has_mark_kind( + pm, + proof, + fun + | ProofMark.RevertFactNotQuantified(_) => true + | _ => false, + )) { + Alcotest.fail( + "`with zz = ...` names no binder of the IH and should be marked\n" + ++ dump(pm, proof), + ); + }; +}; + +let tests = ( + "Evaluator.MilestoneSTLC", + [ + test_case("smoke: ty_eq passes the gate", `Quick, test_smoke_ty_eq), + test_case("smoke: nth_ty passes the gate", `Quick, test_smoke_nth_ty), + test_case("smoke: infer passes the gate", `Quick, test_smoke_infer), + test_case("smoke: is_value passes the gate", `Quick, test_smoke_is_value), + test_case("smoke: step passes the gate", `Quick, test_smoke_step), + test_case("smoke: subst passes the gate", `Quick, test_smoke_subst), + test_case("smoke: shift passes the gate", `Quick, test_smoke_shift), + test_case( + "smoke: is_some_tm passes the gate", + `Quick, + test_smoke_is_some_tm, + ), + test_case("dynamics: infer types identity", `Quick, test_dyn_infer_id), + test_case( + "dynamics: infer rejects unbound var", + `Quick, + test_dyn_infer_unbound, + ), + test_case( + "dynamics: infer on an ill-typed application", + `Quick, + test_dyn_infer_ap, + ), + test_case("dynamics: beta step", `Quick, test_dyn_step_beta), + test_case("dynamics: congruence step", `Quick, test_dyn_step_cong), + test_case("dynamics: stuck term", `Quick, test_dyn_step_stuck), + test_case( + "canonical forms (==> form) fully proven", + `Quick, + test_canonical_impl_proven, + ), + test_case("var_never_types fully proven", `Quick, test_var_never_types), + test_case("lemma step_ap_val1", `Quick, test_lemma_step_ap_val1), + test_case("lemma step_lam_ap2", `Quick, test_lemma_step_lam_ap2), + test_case("lemma step_beta", `Quick, test_lemma_step_beta), + test_case("lemma some_tm_is_some", `Quick, test_lemma_some_tm_is_some), + test_case("progress is fully proven", `Quick, test_progress_proven), + test_case( + "ADT induction generates a quantified IH", + `Quick, + test_ih_exists_quantified, + ), + test_case( + "the IH is at the sub-term, not the scrutinee", + `Quick, + test_ih_not_at_scrutinee, + ), + test_case( + "quantified IH citation is underdetermined without `with`", + `Quick, + test_ih_citation_underdetermined_without_with, + ), + test_case( + "quantified IH instantiates with a `with` clause", + `Quick, + test_ih_instantiated_with_clause, + ), + test_case( + "`with` must name a binder the IH quantifies", + `Quick, + test_ih_instantiation_unknown_binder, + ), + test_case( + "a call to another definition in an unfolded body is addressable", + `Quick, + test_unfolded_call_addressable("is_value(u2)"), + ), + test_case( + "a recursive call in an unfolded body is addressable", + `Quick, + test_unfolded_call_addressable("step(u1)"), + ), + ], +); diff --git a/test/evaluator/Test_Obligations.re b/test/evaluator/Test_Obligations.re new file mode 100644 index 0000000000..c0ee4aaedc --- /dev/null +++ b/test/evaluator/Test_Obligations.re @@ -0,0 +1,426 @@ +open Alcotest; +open Language; +open Test_Evaluator_Prelude; +open Poly; + +module Status = Web.Obligations.Status; +module Exits = Web.Obligations.Exits; + +/* A theorem's obligations as its header and side-condition circles show + * them: the status, with its count of open conditions, the exits that + * discharge a pending one, and the goals as written. + * + * Reuses the Test_ProofMap harness like Test_Definedness. */ + +let eval_with_proof = Test_ProofMap.eval_with_proof; +let proof_of = Test_ProofMap.proof_of; +let check_exp = Test_ProofMap.check_exp; + +let run = (src: string): (ProofMap.t, Proof.t) => { + let (state, _, elab) = src |> parse_exp |> eval_with_proof; + (EvaluatorState.get_proof_map(state), proof_of(elab)); +}; + +let bool_check = (msg, expected, actual) => + Alcotest.check(Alcotest.bool, msg, expected, actual); + +let int_check = (msg, expected, actual) => + Alcotest.check(Alcotest.int, msg, expected, actual); + +let contains_substring = (haystack: string, needle: string): bool => { + let hl = String.length(haystack); + let nl = String.length(needle); + let rec go = i => + i + + nl <= hl + && (String.sub(haystack, ~pos=i, ~len=nl) == needle || go(i + 1)); + nl == 0 || go(0); +}; + +let str_check = (msg, expected, actual) => + Alcotest.check(Alcotest.string, msg, expected, actual); + +/* A sample program with two obligations in its proof: + * + * z != 0 Pending (open; nothing in scope covers it) + * 2 != 0 Evaluated (ground; closed evaluation, channel 2) + */ +let repro = {|let f = fun x -> 100 / x in +theorem t = forall y -> forall z -> f(y) + 4 / 2 + 8 / z == f(y) + 4 / 2 + 8 / z +proof from f(y) + 4 / 2 + 8 / z == f(y) + 4 / 2 + 8 / z do rewrite refl end end +in t|}; + +/* --- status mapping ----------------------------------------------- */ + +/* The header's status: proven; proven relying on the unfinished theorems + * a proof cites, which aren't counted as gaps; or incomplete, with a + * count of its open conditions. Only proven scores. */ +let test_status = () => { + let status = src => { + let (pm, proof) = Test_ProofMap.Harness.run_named("t", src); + Status.(label(of_proof(pm, proof))); + }; + str_check( + "proven", + "proven", + status( + {|theorem t = 1 == 1 proof from 1 == 1 do rewrite refl end end in t|}, + ), + ); + str_check( + "relying", + "proven*", + status( + {|theorem lemma = forall n: Int -> n + 0 == n proof ? in theorem t = 2 + 0 == 2 proof from 2 + 0 do rewrite lemma end end; rewrite refl end in t|}, + ), + ); + let (pm, proof) = + Test_ProofMap.Harness.run_named( + "t", + {|theorem lemma = forall n: Int -> n + 0 == n proof ? in theorem t = 2 + 0 == 2 proof from 2 + 0 do rewrite lemma end end; rewrite refl end in t|}, + ); + bool_check( + "relying names what it assumes", + true, + Status.of_proof(pm, proof) == Status.Relying(["lemma"]), + ); + str_check( + "an open condition", + "incomplete · 1 open", + status( + {|theorem t = forall z: Int -> 8 / z == 8 / z proof rewrite refl end in t|}, + ), + ); + str_check( + "a hole", + "incomplete", + status({|theorem t = 1 + 1 == 2 proof ? in t|}), + ); + str_check( + "refuted", + "refuted", + status( + {|theorem t = 1 + 1 == 3 proof from 1 + 1 do step end; step in t|}, + ), + ); + let score = src => + Web.Theorems.Model.get_score( + Test_StepperView.Fixture.mk(src).cell.theorems, + ); + let score_t = Alcotest.(option(pair(float(0.), float(0.)))); + Alcotest.check( + score_t, + "an open condition scores 0", + Some((0., 1.)), + score(repro), + ); + /* Both theorems count; neither is proven outright. */ + Alcotest.check( + score_t, + "relying on an unfinished lemma scores 0", + Some((0., 2.)), + score( + {|theorem lemma = forall n: Int -> n + 0 == n proof ? in theorem t = 2 + 0 == 2 proof from 2 + 0 do rewrite lemma end end; rewrite refl end in t|}, + ), + ); +}; + +/* End to end: the repro theorem's goal reaches `true` but one obligation + * is pending, so the chip is the ProvenModulo one, while the bool status + * stays `Some(true)`. */ +let test_repro_status_is_proven_modulo = () => { + let (pm, proof) = run(repro); + switch (ProofMap.full_status_of_proof(pm, proof)) { + | ProvenModulo(obs) => + int_check("exactly one pending", 1, List.length(obs)) + | Proven => Alcotest.fail("expected ProvenModulo, got Proven") + | Refuted => Alcotest.fail("expected ProvenModulo, got Refuted") + | Incomplete => Alcotest.fail("expected ProvenModulo, got Incomplete") + }; + Alcotest.check( + Alcotest.option(bool), + "bool status is untouched", + Some(true), + ProofMap.status_of_proof(pm, proof), + ); +}; + +/* A proof with no obligations at all is plain Proven; a hole is + * Incomplete. */ +let test_status_proven_and_incomplete = () => { + let (pm, proof) = + run( + {|theorem t = 1 == 1 proof from 1 == 1 do rewrite refl end end in t|}, + ); + bool_check( + "obligation-free proof is Proven", + true, + ProofMap.full_status_of_proof(pm, proof) == ProofMap.Proven, + ); + let (pm, proof) = run({|theorem t = 1 + 1 == 2 proof ? in t|}); + bool_check( + "hole proof is Incomplete", + true, + ProofMap.full_status_of_proof(pm, proof) == ProofMap.Incomplete, + ); +}; + +/* --- covering facts ------------------------------------------------- */ + +/* A Remote discharge recovers its covering fact from the obligation's own + * recorded bindings: an open closed circle's justification names it. */ +let test_remote_fact_is_the_covering_fact = () => { + let (pm, proof) = + run( + {|theorem t = forall y -> y != 0 ==> 8 / y == 8 / y proof assume y != 0 => from 8 / y == 8 / y do rewrite refl end end in t|}, + ); + let obs = ProofMap.obligations_of_proof(pm, proof); + List.iter( + ~f= + (ob: Obligation.t) => + switch (ob.discharge, Obligation.remote_fact(ob)) { + | (Remote(_), Some((name, fact))) => + str_check("the hypothesis that covers it", "assume", name); + check_exp("the fact's statement", "y != 0", fact); + | (Remote(_), None) => + Alcotest.fail("no covering fact recovered for a Remote discharge") + | (Evaluated | Pending, fact) => + bool_check("only a Remote discharge has a fact", true, fact == None) + }, + obs, + ); + bool_check( + "the program has a Remote discharge", + true, + List.exists( + ~f=(ob: Obligation.t) => Obligation.remote_fact(ob) != None, + obs, + ), + ); +}; + +/* --- readable goals ------------------------------------------------ */ + +/* An obligation's goal is kept as written, naming the function rather + * than carrying its body. */ +let test_goal_is_as_written = () => { + let src = {|let d = fun q -> q + 1 in +theorem t = forall y -> 1 == 1 +proof have d(y) != 0 proof ? => from 1 == 1 do rewrite refl end end +in t|}; + let (pm, proof) = run(src); + let obs = ProofMap.obligations_of_proof(pm, proof); + int_check("one premise obligation", 1, List.length(obs)); + switch (obs) { + | [ob] => check_exp("the goal is what was written", "d(y) != 0", ob.goal) + | _ => () + }; +}; + +/* --- a step's exits ------------------------------------------------- */ + +/* Availability is computed from the obligation's own data plus the + * theorem's syntax, so these tests run the real checker. (The + * patch/round-trip side is Test_EditorTransform's: ids are per-parse, so + * patches must be applied to the zipper they were built from.) */ + +let run_with_ctx = (src: string): (ProofMap.t, Proof.t, Exits.ctx) => { + let (state, info_map, elab) = src |> parse_exp |> eval_with_proof; + let proof = proof_of(elab); + let proof_map = EvaluatorState.get_proof_map(state); + ( + proof_map, + proof, + { + proof, + proof_map, + info_map, + }, + ); +}; + +let pending_of = (pm, proof): list(Obligation.t) => + ProofMap.obligations_of_proof(pm, proof) + |> List.filter(~f=Obligation.is_pending); + +let one_pending = (msg, pm, proof): Obligation.t => + switch (pending_of(pm, proof)) { + | [ob] => ob + | obs => + Alcotest.fail( + msg + ++ ": expected exactly one pending obligation, got " + ++ string_of_int(List.length(obs)), + ) + }; + +/* The obligation arises inside an induction case and mentions that + * case's own binder. */ +let case_scoped_src = {|theorem t = forall n: Int -> 8 / n == 8 / n +proof induction n | 0 => ? | m => from 8 / m == 8 / m do rewrite refl end end end +in t|}; + +let test_exits_at_case_binder = () => { + let (pm, proof, ctx) = run_with_ctx(case_scoped_src); + let obs = pending_of(pm, proof); + let ob = + switch ( + List.find( + ~f=(ob: Obligation.t) => Exp.occurs_free_any(["m"], ob.goal), + obs, + ) + ) { + | Some(ob) => ob + | None => + Alcotest.fail( + "expected a pending obligation mentioning the case binder `m`, got " + ++ string_of_int(List.length(obs)), + ) + }; + switch (Exits.for_step(~ctx, ob)) { + | [prove, split] => + bool_check("prove here is available", true, prove.patch != None); + bool_check("split is available", true, split.patch != None); + | actions => + Alcotest.fail( + "expected two actions, got " ++ string_of_int(List.length(actions)), + ) + }; + /* And the wrapping region is inside the case, so the emitted `have`'s + * proposition can mention `m` at all. */ + switch (Exits.region_of(~ctx, ob)) { + | Some(region) => + bool_check( + "the region is the case body, not the whole proof", + false, + Id.compare(Proof.rep_id(region), Proof.rep_id(proof)) == 0, + ); + bool_check( + "and it contains the incurring step", + true, + Exits.proof_contains(~origin=ob.origin, region), + ); + | None => Alcotest.fail("no wrapping region found for a case obligation") + }; +}; + +/* A discharged obligation has no exits. */ +let test_no_exits_when_discharged = () => { + let (pm, proof, ctx) = run_with_ctx(repro); + let discharged = + ProofMap.obligations_of_proof(pm, proof) + |> List.filter(~f=ob => !Obligation.is_pending(ob)); + bool_check( + "the repro has discharged obligations to check", + true, + List.length(discharged) > 0, + ); + List.iter( + ~f= + ob => + int_check( + "no exits on a discharged obligation", + 0, + List.length(Exits.for_step(~ctx, ob)), + ), + discharged, + ); +}; + +/* Against a theorem whose proof doesn't hold the incurring step, the + * exits are disabled, with a reason, rather than misdirected. */ +let test_exits_disabled_outside_the_theorem = () => { + let (pm, proof, _) = run_with_ctx(repro); + let ob = one_pending("repro", pm, proof); + let ctx: Exits.ctx = { + proof: Proof.fresh(EmptyHole), + proof_map: ProofMap.empty, + info_map: Statics.Map.empty, + }; + switch (Exits.for_step(~ctx, ob)) { + | [prove, split] => + bool_check("prove here disabled", true, prove.patch == None); + bool_check("split disabled", true, split.patch == None); + bool_check( + "and says why", + true, + contains_substring(prove.title, "Unavailable"), + ); + | actions => + Alcotest.fail( + "expected two actions, got " ++ string_of_int(List.length(actions)), + ) + }; +}; + +/* An exit that would break the proof shows disabled. Splitting on a + * condition the goal mentions rewrites the goal of the steps below it. */ +let test_split_disabled_when_it_breaks_a_step = () => { + let (pm, proof, ctx) = + run_with_ctx( + "theorem t = forall x: Int -> x == 1 proof have x == 1 proof ? => from x do rewrite have end end; from 1 == 1 do rewrite refl end end in t", + ); + let ob = one_pending("split", pm, proof); + switch (Exits.for_step(~ctx, ob)) { + | [prove, split] => + bool_check("prove here enabled", true, prove.patch != None); + bool_check("split disabled", true, split.patch == None); + str_check( + "and says why", + "Unavailable: it would break a step of the proof", + split.title, + ); + | exits => Alcotest.fail(string_of_int(List.length(exits)) ++ " exits") + }; +}; + +let tests = ( + "Obligations", + [ + test_case( + "an exit that would break a step is disabled, with a reason", + `Quick, + test_split_disabled_when_it_breaks_a_step, + ), + test_case( + "the exits at an induction case wrap the case's body", + `Quick, + test_exits_at_case_binder, + ), + test_case( + "a discharged obligation has no exits", + `Quick, + test_no_exits_when_discharged, + ), + test_case( + "exits outside the theorem are disabled, with a reason", + `Quick, + test_exits_disabled_outside_the_theorem, + ), + test_case( + "the header reads proven, proven* or incomplete with a count", + `Quick, + test_status, + ), + test_case( + "one pending obligation makes a proven theorem ProvenModulo", + `Quick, + test_repro_status_is_proven_modulo, + ), + test_case( + "obligation-free and hole proofs are Proven / Incomplete", + `Quick, + test_status_proven_and_incomplete, + ), + test_case( + "a Remote discharge has its covering fact", + `Quick, + test_remote_fact_is_the_covering_fact, + ), + test_case( + "an obligation's goal is as written", + `Quick, + test_goal_is_as_written, + ), + ], +); diff --git a/test/evaluator/Test_OffDomain.re b/test/evaluator/Test_OffDomain.re new file mode 100644 index 0000000000..0e27d1e83f --- /dev/null +++ b/test/evaluator/Test_OffDomain.re @@ -0,0 +1,119 @@ +open Alcotest; +open Test_Evaluator_Prelude; +open Language; + +/* Off-domain primitive evaluation never yields a boolean verdict; it + produces an error or indet result that says where it came from. Floats + are IEEE-total, which is pinned here too. */ + +/* Strip evaluation wrappers to get at the result's head term. */ +let rec unwrap = (d: Exp.t): Exp.t => + switch (DHExp.term_of(d)) { + | Closure(_, d1) + | Parens(d1) + | Asc(d1, _) => unwrap(d1) + | _ => d + }; + +let head_error = (d: Exp.t): option(InvalidOperationError.t) => + switch (DHExp.term_of(unwrap(d))) { + | DynamicErrorHole(_, err) => Some(err) + | _ => None + }; + +let is_bool_lit = (d: Exp.t): bool => + switch (DHExp.term_of(unwrap(d))) { + | Atom(Bool(_)) => true + | _ => false + }; + +let error_testable: testable(InvalidOperationError.t) = + testable( + Fmt.using(InvalidOperationError.show, Fmt.string), + InvalidOperationError.equal, + ); + +let check_error = + (msg: string, expected: InvalidOperationError.t, program: string) => + check( + option(error_testable), + msg, + Some(expected), + head_error(parse_and_evaluate(program)), + ); + +let check_no_verdict = (msg: string, program: string) => { + let result = parse_and_evaluate(program); + check(bool, msg ++ " (no boolean verdict)", false, is_bool_lit(result)); + check(bool, msg ++ " (not a value)", false, ValueChecker.is_value(result)); +}; + +let tests = ( + "Evaluator.OffDomain", + [ + test_case( + "Division by zero is an error, not a value", + `Quick, + () => { + check_error( + "1 / 0 is a DivideByZero error hole", + DivideByZero, + "1 / 0", + ); + check_no_verdict("1 / 0", "1 / 0"); + }, + ), + test_case( + "Equality on errors renders no verdict", + `Quick, + () => { + check_no_verdict("1 / 0 == 1 / 0", "1 / 0 == 1 / 0"); + check_no_verdict("1 / 0 == 1", "1 / 0 == 1"); + }, + ), + test_case( + "Failed string conversion attributes its error", + `Quick, + () => { + check_error( + "int_of_string(\"abc\") is an InvalidOfString error hole", + InvalidOfString, + "int_of_string(\"abc\")", + ); + check_no_verdict("int_of_string(\"abc\")", "int_of_string(\"abc\")"); + }, + ), + test_case( + "Float to integer conversion is off-domain on nan/inf", + `Quick, + () => { + check_error( + "int_of_float(nan) is a NonFiniteFloat error hole", + NonFiniteFloat, + "int_of_float(nan)", + ); + check_error( + "int_of_float(infinity) is a NonFiniteFloat error hole", + NonFiniteFloat, + "int_of_float(1. /. 0.)", + ); + check_error( + "sint_of_float(nan) is a NonFiniteFloat error hole", + NonFiniteFloat, + "sint_of_float(0. /. 0.)", + ); + check_no_verdict("int_of_float(nan)", "int_of_float(nan)"); + }, + ), + test_case("IEEE floats are total by design", `Quick, () => { + /* 1.0 /. 0.0 is the value infinity, not an error: float + arithmetic is deliberately total (section 1.5), so equality + on it renders a genuine verdict. */ + evaluation_test( + "1. /. 0. == 1. /. 0. evaluates to true", + IdTagged.FreshGrammar.Exp.bool(true), + elaborate(parse_exp("1. /. 0. == 1. /. 0.")), + ) + }), + ], +); diff --git a/test/evaluator/Test_ProofMap.re b/test/evaluator/Test_ProofMap.re new file mode 100644 index 0000000000..f7b10ebca0 --- /dev/null +++ b/test/evaluator/Test_ProofMap.re @@ -0,0 +1,1844 @@ +open Alcotest; +open Language; +open Test_Evaluator_Prelude; +open Poly; + +/* Tests for the big-step proof checking phase. Each test parses a + * program containing a theorem, evaluates it through the big-step + * evaluator, and inspects the resulting EvaluatorState.proof_map for + * the mark we expect on the proof term just inside the theorem. */ + +/* The harness the proof tests share: run a program, find a theorem's + * proof, and check the proof map, printing every proof node's goals and + * marks on failure. */ +module Harness = { + let statics_and_elab = (exp: Exp.t): (Statics.Map.t, Exp.t) => + Statics.mk( + CoreSettings.on, + Builtins.ctx_init(Some(Operators.default_mode)), + exp, + ); + + let eval_with_proof = + (exp: Exp.t): (EvaluatorState.t, Statics.Map.t, Exp.t) => { + let (statics, elab) = statics_and_elab(exp); + let (_, state) = + Evaluator.evaluate(~statics, ~env=Builtins.env_init, elab); + (state, statics, elab); + }; + + /* Find a Theorem's proof sub-term in the elaborated expression. We use + * map_term's stash side-channel to capture the first Theorem proof we + * encounter; test programs only contain one. */ + let find_theorem_proof = (e: Exp.t): option(Proof.t) => { + let found = ref(None); + let f_exp = (continue, e: Exp.t): Exp.t => { + switch (e.term) { + | Theorem(_, _, proof, _) when found^ == None => + found := Some(proof); + e; + | _ => continue(e) + }; + }; + let _ = TermBase.Exp.map_term(~f_exp, e); + found^; + }; + + let proof_of = (elab: Exp.t): Proof.t => + switch (find_theorem_proof(elab)) { + | Some(p) => p + | None => Alcotest.fail("no theorem found in elaborated expression") + }; + + let proof_entry = (state: EvaluatorState.t, elab: Exp.t): ProofMap.entry => + switch ( + ProofMap.lookup( + Proof.rep_id(proof_of(elab)), + EvaluatorState.get_proof_map(state), + ) + ) { + | Some(entry) => entry + | None => Alcotest.fail("no proof-map entry for theorem proof") + }; + + let elaborated_exp = (src: string): Exp.t => { + let (_, elab) = statics_and_elab(parse_exp(src)); + elab; + }; + + let check_exp = (msg: string, expected: string, actual: Exp.t) => + Alcotest.check( + Alcotest.bool, + msg, + true, + Exp.fast_equal(elaborated_exp(expected), actual), + ); + + let require_exp = (msg: string, exp: option(Exp.t)): Exp.t => + switch (exp) { + | Some(exp) => exp + | None => Alcotest.fail(msg) + }; + + /* Find the proof of the theorem bound to `name`, for programs with + * several theorems (e.g. a guarded lemma and its use site). */ + let rec pat_var_name = (p: Pat.t): option(string) => + switch (p.term) { + | Var(x) => Some(x) + | Parens(p) + | Projector(_, p) + | Asc(p, _) => pat_var_name(p) + | _ => None + }; + + let find_theorem_proof_named = (name: string, e: Exp.t): option(Proof.t) => { + let found = ref(None); + let f_exp = (continue, e: Exp.t): Exp.t => { + switch (e.term) { + | Theorem(p, _, proof, _) when pat_var_name(p) == Some(name) => + if (found^ == None) { + found := Some(proof); + }; + continue(e); + | _ => continue(e) + }; + }; + let _ = TermBase.Exp.map_term(~f_exp, e); + found^; + }; + + let proof_of_named = (name: string, elab: Exp.t): Proof.t => + switch (find_theorem_proof_named(name, elab)) { + | Some(p) => p + | None => Alcotest.fail("no theorem named " ++ name) + }; + + let print_exp = (e: Exp.t): string => + e + |> Haz3lcore.ExpToSegment.exp_to_segment( + ~settings=Haz3lcore.ExpToSegment.Settings.editable(~inline=true), + ) + |> Haz3lcore.Printer.of_segment(~holes="?", ~refractors=[]); + + /* Walk the inner proof recursively and collect the first proof sub-term + * whose mark list is non-empty. Used to locate whichever sub-step the + * checker reported a mark against. */ + let rec find_marked_sub = + (pm: ProofMap.t, proof: Proof.t) + : option((Id.t, list(ProofMark.t))) => { + let id = Proof.rep_id(proof); + let marks = ProofMap.marks_of(id, pm); + if (marks != []) { + Some((id, marks)); + } else { + switch (proof.term) { + | Seq(p1, p2) => + switch (find_marked_sub(pm, p1)) { + | Some(_) as s => s + | None => find_marked_sub(pm, p2) + } + | Parens(body) + | Forall(_, body) + | Funext(_, body) + | Assume(_, _, body) + | Alias(_, _, body) + | Generalize(_, body) + | Revert(_, _, body) => find_marked_sub(pm, body) + | Have(_, _, sub, body) => + switch (find_marked_sub(pm, sub)) { + | Some(_) as s => s + | None => find_marked_sub(pm, body) + } + | Cases(_, cases) + | Induction(_, cases) => + let rec scan = ( + fun + | [] => None + | [(_p, body), ...rest] => + switch (find_marked_sub(pm, body)) { + | Some(_) as s => s + | None => scan(rest) + } + ); + scan(cases); + | EmptyHole + | Invalid(_) + | MultiHole(_) + | AxiomStep(_) + | AlgebriteStep(_) + | EvalStep => None + | Focus({body, _}) => find_marked_sub(pm, body) + }; + }; + }; + + let has_mark_kind = + (pm: ProofMap.t, proof: Proof.t, pred: ProofMark.t => bool): bool => + switch (find_marked_sub(pm, proof)) { + | Some((_, marks)) => List.exists(~f=pred, marks) + | None => false + }; + + let is_divergent_instantiation: ProofMark.t => bool = + fun + | ProofMark.PossiblyDivergentInstantiation(_) => true + | _ => false; + + /* Runs `src`, returning the proof map and its first theorem's proof. */ + let run = (src: string): (ProofMap.t, Proof.t) => { + let (state, _, elab) = src |> parse_exp |> eval_with_proof; + (EvaluatorState.get_proof_map(state), proof_of(elab)); + }; + + let run_named = (name: string, src: string): (ProofMap.t, Proof.t) => { + let (state, _, elab) = src |> parse_exp |> eval_with_proof; + (EvaluatorState.get_proof_map(state), proof_of_named(name, elab)); + }; + + /* `run`, with the obligations recorded in the proof. */ + let obligations = (src: string): (ProofMap.t, Proof.t, list(Obligation.t)) => { + let (pm, proof) = run(src); + (pm, proof, ProofMap.obligations_of_proof(pm, proof)); + }; + + let incoming_of = (pm: ProofMap.t, p: Proof.t): Exp.t => + switch (ProofMap.lookup(Proof.rep_id(p), pm)) { + | Some({incoming: Some(e), _}) => e + | _ => Alcotest.fail("no incoming goal recorded for the proof node") + }; + + let contains = (haystack: string, needle: string): bool => { + let hl = String.length(haystack); + let nl = String.length(needle); + let rec go = i => + i + + nl <= hl + && (String.sub(haystack, ~pos=i, ~len=nl) == needle || go(i + 1)); + nl == 0 || go(0); + }; + + /* On one line, and cut short when long. */ + let trunc = (s: string): string => { + let s = String.map(~f=c => c == '\n' ? ' ' : c, s); + String.length(s) > 2000 ? String.sub(s, ~pos=0, ~len=2000) ++ " ..." : s; + }; + + let show_obligation = (ob: Obligation.t): string => + trunc(print_exp(ob.goal)) + ++ " [" + ++ Obligation.show_discharge(ob.discharge) + ++ "]"; + + /* Each step of `proof` with its incoming and outgoing goals, marks and + * obligations, indented by nesting, for failure messages. */ + let dump = (pm: ProofMap.t, proof: Proof.t): string => { + let exp_str = (e: option(Exp.t)): string => + switch (e) { + | Some(e) => trunc(print_exp(e)) + | None => "" + }; + let rec go = (indent: string, p: Proof.t): string => { + let (inc, out, marks, obs) = + switch (ProofMap.lookup(Proof.rep_id(p), pm)) { + | Some({incoming, outgoing, marks, obligations, _}) => ( + exp_str(incoming), + exp_str(outgoing), + marks + |> List.map(~f=m => trunc(ProofMark.show(m))) + |> String.concat(~sep="; "), + obligations + |> List.map(~f=show_obligation) + |> String.concat(~sep="; "), + ) + | None => ("", "", "", "") + }; + let here = + indent + ++ Proof.show_cls(Proof.cls_of_term(p.term)) + ++ "\n" + ++ indent + ++ " in: " + ++ inc + ++ "\n" + ++ indent + ++ " out: " + ++ out + ++ (marks == "" ? "" : "\n" ++ indent ++ " marks: " ++ marks) + ++ (obs == "" ? "" : "\n" ++ indent ++ " obs: " ++ obs); + /* A sequence's steps line up; anything else nests. */ + let inner = + switch (p.term) { + | Seq(_) => indent + | _ => indent ++ " " + }; + String.concat( + ~sep="\n", + [here, ...List.map(~f=go(inner), Proof.children(p))], + ); + }; + go("", proof); + }; + + let check_mark_free = (msg, pm, proof) => + switch (find_marked_sub(pm, proof)) { + | None => () + | Some((_, marks)) => + Alcotest.fail( + msg + ++ ": expected no marks, got " + ++ String.concat(~sep="; ", List.map(~f=ProofMark.show, marks)) + ++ "\n--- proof dump ---\n" + ++ dump(pm, proof), + ) + }; + + let check_status = (msg, expected: ProofMap.full_status, pm, proof) => { + let actual = ProofMap.full_status_of_proof(pm, proof); + if (actual != expected) { + Alcotest.fail( + msg + ++ "\nexpected: " + ++ ProofMap.show_full_status(expected) + ++ "\ngot: " + ++ ProofMap.show_full_status(actual) + ++ "\n--- proof dump ---\n" + ++ dump(pm, proof), + ); + }; + }; + + let check_proven = (msg, pm, proof) => + check_status(msg, ProofMap.Proven, pm, proof); + + /* Tests leave lemmas unfinished (`proof ?`) to use them as axioms, and + * citing one rests on it: an obligation of its own. These helpers set + * those citations aside. */ + let without_citations = (obs: list(Obligation.t)) => + List.filter(~f=(ob: Obligation.t) => ob.kind != Citation, obs); + + /* Proven, or proven given the unfinished lemmas it cites. */ + let check_proven_given_lemmas = (msg, pm, proof) => + switch (ProofMap.full_status_of_proof(pm, proof)) { + | ProvenModulo(obs) when without_citations(obs) == [] => () + | _ => check_proven(msg, pm, proof) + }; + + let check_obligation_count = (msg, expected: int, pm, proof) => { + let count = + List.length( + without_citations(ProofMap.obligations_of_proof(pm, proof)), + ); + if (count != expected) { + Alcotest.fail( + msg + ++ "\nexpected " + ++ string_of_int(expected) + ++ " obligations, got " + ++ string_of_int(count) + ++ "\n--- proof dump ---\n" + ++ dump(pm, proof), + ); + }; + }; +}; +include Harness; + +let proof_id_of = (elab: Exp.t): Id.t => + switch (find_theorem_proof(elab)) { + | Some(p) => Proof.rep_id(p) + | None => Alcotest.fail("no theorem found in elaborated expression") + }; + +/* The entry of the step a theorem's proof focuses on. */ +let focused_entry = (state: EvaluatorState.t, elab: Exp.t): ProofMap.entry => + switch (proof_of(elab).term) { + | Focus({body, _}) => + switch ( + ProofMap.lookup( + Proof.rep_id(body), + EvaluatorState.get_proof_map(state), + ) + ) { + | Some(entry) => entry + | None => Alcotest.fail("no proof-map entry for the focused step") + } + | _ => Alcotest.fail("the proof is not a focus") + }; + +/* A parenthesized redex has one hidden transition before the visible + * arithmetic step. auto_incoming stores (justification, resulting_exp): + * the expression is therefore the result of removing parentheses, not + * the input that still contains them. */ +let test_leading_auto_step_trace = () => { + let src = {|theorem t = (1 + 2) == 3 proof from (1 + 2) do step end in t|}; + let (state, _, elab) = src |> parse_exp |> eval_with_proof; + let entry = focused_entry(state, elab); + check_exp( + "incoming precedes hidden step", + "(1 + 2)", + require_exp("expected incoming", entry.incoming), + ); + switch (entry.auto_incoming) { + | [("remove parentheses", resulting_exp)] => + check_exp( + "auto_incoming expression follows hidden step", + "1 + 2", + resulting_exp, + ) + | _ => Alcotest.fail("expected one leading remove-parentheses transition") + }; + Alcotest.check( + Alcotest.int, + "no hidden transitions follow visible arithmetic", + 0, + List.length(entry.auto_outgoing), + ); + check_exp( + "outgoing follows visible arithmetic", + "3", + require_exp("expected outgoing", entry.outgoing), + ); +}; + +/* Selecting the conditional branch is the visible step; removing the + * selected branch's parentheses is hidden afterward. auto_outgoing stores + * (input_exp, justification), so it must retain the still-parenthesized + * input rather than the result of the hidden transition. */ +let test_trailing_auto_step_trace = () => { + let src = {|theorem t = (if true then (3) else 4) == 3 proof from (if true then (3) else 4) do step end in t|}; + let (state, _, elab) = src |> parse_exp |> eval_with_proof; + let entry = focused_entry(state, elab); + switch (entry.auto_outgoing) { + | [(input_exp, "remove parentheses")] => + check_exp( + "auto_outgoing expression precedes hidden step", + "(3)", + input_exp, + ) + | _ => + Alcotest.fail( + "expected one trailing remove-parentheses transition: " + ++ ProofMap.show_entry(entry), + ) + }; + check_exp( + "outgoing follows trailing lookup", + "3", + require_exp("expected outgoing", entry.outgoing), + ); +}; + +/* Reflexivity axiom on a closed equality: outgoing of the top-level + * proof should be `true`, giving a checkmark. */ +let test_refl_checkmark = () => { + let src = {|theorem t = 1 == 1 proof from 1 == 1 do rewrite refl end end in t|}; + let uexp = parse_exp(src); + let (state, _, elab) = eval_with_proof(uexp); + let pm = EvaluatorState.get_proof_map(state); + Alcotest.check( + Alcotest.option(bool), + "refl proof should be checkmark", + Some(true), + ProofMap.status_of_proof(pm, proof_of(elab)), + ); +}; + +/* A theorem with outer universal quantifiers: the foralls are + * auto-introduced, so a bare reflexivity proof on the conclusion proves + * the theorem (outgoing `true`) without needing an explicit `forall` + * proof step. */ +let test_refl_forall_checkmark = () => { + let src = {|theorem t = forall x -> x == x proof from x == x do rewrite refl end end in t|}; + let uexp = parse_exp(src); + let (state, _, elab) = eval_with_proof(uexp); + let pm = EvaluatorState.get_proof_map(state); + Alcotest.check( + Alcotest.option(bool), + "forall reflexivity proof should be checkmark", + Some(true), + ProofMap.status_of_proof(pm, proof_of(elab)), + ); +}; + +/* An empty-hole proof acts as the identity (recovery): the goal passes + * through unchanged, so an unreduced goal stays unproven. */ +let test_empty_hole_nothing = () => { + let src = {|theorem t = 1 + 1 == 2 proof ? in t|}; + let uexp = parse_exp(src); + let (state, _, elab) = eval_with_proof(uexp); + let pm = EvaluatorState.get_proof_map(state); + let proof = proof_of(elab); + Alcotest.check( + Alcotest.option(bool), + "empty-hole proof should be nothing", + None, + ProofMap.status_of_proof(pm, proof), + ); + /* The hole passes the goal through rather than going dark. */ + let outgoing = + switch (ProofMap.lookup(Proof.rep_id(proof), pm)) { + | Some({outgoing, _}) => outgoing + | None => None + }; + Alcotest.check( + Alcotest.bool, + "empty-hole proof passes the goal through", + true, + outgoing != None, + ); +}; + +/* A hole-free but unsuccessful proof of a false statement: the axiom + * doesn't apply, so outgoing is None. That is not a disproof + * (`Some(false)` requires outgoing `false`), and it must not be marked + * proven either — status stays `None`. */ +let test_false_goal_not_checkmark = () => { + let src = {|theorem t = 1 == 2 proof from 1 == 2 do rewrite refl end end in t|}; + let uexp = parse_exp(src); + let (state, _, elab) = eval_with_proof(uexp); + let pm = EvaluatorState.get_proof_map(state); + let proof = proof_of(elab); + Alcotest.check( + Alcotest.bool, + "proof has no EmptyHole/Invalid/MultiHole", + false, + Proof.has_hole(proof), + ); + Alcotest.check( + Alcotest.option(bool), + "failed proof is neither proven nor disproven", + None, + ProofMap.status_of_proof(pm, proof), + ); +}; + +/* A state-merge round-trip: append a freshly-evaluated state (carrying a + * proof-map entry) onto an empty base and check the entry survives the + * merge. */ +let test_append_proof_map = () => { + let src = {|theorem t = 1 == 1 proof from 1 == 1 do rewrite refl end end in t|}; + let uexp = parse_exp(src); + let (state, _, elab) = eval_with_proof(uexp); + let pid = proof_id_of(elab); + let pm = EvaluatorState.get_proof_map(state); + /* Merge the evaluated state onto a fresh empty base; the proof_map + * should be carried through the append. */ + let merged = EvaluatorState.append(EvaluatorState.empty, state); + let pm_merged = EvaluatorState.get_proof_map(merged); + Alcotest.check( + Alcotest.bool, + "merged proof map has entry for proof id", + ProofMap.lookup(pid, pm_merged) != None, + ProofMap.lookup(pid, pm) != None, + ); +}; + +/* --- Proof-mark tests --------------------------------------------- + * + * Each test exercises a specific `ProofMark.t` variant by constructing + * a theorem whose inner proof step should fail in the expected way, + * then asserts that the proof-map marks at the inner step's id include + * the right mark kind. `proof-mark error_ids` must also surface that id. */ + +/* The proof-map error_ids list must include the id of any marked sub-term + * — this drives the red shard overlay in the code view. */ +let marked_id_is_surfaced = (pm: ProofMap.t, proof: Proof.t): bool => + switch (find_marked_sub(pm, proof)) { + | Some((id, _)) => List.mem(ProofMap.error_ids(pm), id, ~equal=Id.equal) + | None => false + }; + +/* UnknownEquality: an axiom that names a rule not in scope. */ +let test_unknown_equality_mark = () => { + let src = {|theorem t = 1 == 1 proof from 1 == 1 do rewrite bogus end end in t|}; + let uexp = parse_exp(src); + let (state, _, elab) = eval_with_proof(uexp); + let pm = EvaluatorState.get_proof_map(state); + let proof = proof_of(elab); + Alcotest.check( + Alcotest.bool, + "UnknownEquality mark is emitted", + true, + has_mark_kind( + pm, + proof, + fun + | ProofMark.UnknownEquality(_) => true + | _ => false, + ), + ); + Alcotest.check( + Alcotest.bool, + "marked id appears in ProofMap.error_ids", + true, + marked_id_is_surfaced(pm, proof), + ); +}; + +/* PatternNotFound: axiom's at_exp pattern isn't present at the + * requested occurrence in the incoming goal. */ +let test_pattern_not_found_mark = () => { + let src = {|theorem t = 1 == 1 proof from 5 == 5 do rewrite refl end end in t|}; + let uexp = parse_exp(src); + let (state, _, elab) = eval_with_proof(uexp); + let pm = EvaluatorState.get_proof_map(state); + let proof = proof_of(elab); + Alcotest.check( + Alcotest.bool, + "PatternNotFound mark is emitted", + true, + has_mark_kind( + pm, + proof, + fun + | ProofMark.PatternNotFound(_) => true + | _ => false, + ), + ); +}; + +/* Rewrite (AlgebriteStep) should locate the `at_exp` pattern in the + * incoming goal. Here `x + x` is literally the left-hand side of the + * goal `x + x == 2 * x`, so occurrence 0 must be found and no + * PatternNotFound mark should be emitted. */ +let test_rewrite_finds_pattern = () => { + let src = {|theorem t = forall x -> x + x == 2 * x proof from x + x do algebra 2 * x end end in t|}; + let uexp = parse_exp(src); + let (state, _, elab) = eval_with_proof(uexp); + let pm = EvaluatorState.get_proof_map(state); + let proof = proof_of(elab); + Alcotest.check( + Alcotest.bool, + "algebra must find `x + x` (no PatternNotFound mark)", + false, + has_mark_kind( + pm, + proof, + fun + | ProofMark.PatternNotFound(_) => true + | _ => false, + ), + ); +}; + +/* A focus ordinal counts occurrences in the goal as written: the goal + * `sum == fold_left(_, sum, 0)` has one `0`, though `sum`'s body has + * more. */ +let rewrite_zero_src = {|let plus = fun (x,y) -> x + y in +let sum(xs) = case xs +| [] => 0 +| x::xs => x + sum(xs) +end +in + +theorem t = + sum == fold_left(_, sum, 0) +proof + from 0 do algebra 0 + 0 end end +in t|}; + +let test_rewrite_zero_as_written = () => { + let (state, _, elab) = rewrite_zero_src |> parse_exp |> eval_with_proof; + let pm = EvaluatorState.get_proof_map(state); + let proof = proof_of(elab); + let entry = + switch (ProofMap.lookup(Proof.rep_id(proof), pm)) { + | Some(entry) => entry + | None => Alcotest.fail("no proof-map entry for the rewrite") + }; + check_exp( + "the goal's own `0` is the one rewritten", + "sum == fold_left(_, sum, 0 + 0)", + require_exp("expected outgoing", entry.outgoing), + ); +}; + +/* Same as above but under `use Nat`, which sets the numeric operator + * mode to Nat, so both the goal's `x + x` and the rewrite's `at_exp` + * must elaborate to Nat(Plus) and still match. This needs the proof + * term's expressions to be elaborated too. */ +let test_rewrite_finds_pattern_nat = () => { + let src = {|use Nat in theorem t = forall x -> x + x == 2 * x proof from x + x do algebra 2 * x end end in t|}; + let uexp = parse_exp(src); + let (state, _, elab) = eval_with_proof(uexp); + let pm = EvaluatorState.get_proof_map(state); + let proof = proof_of(elab); + Alcotest.check( + Alcotest.bool, + "algebra under `use Nat` must find `x + x` (no PatternNotFound mark)", + false, + has_mark_kind( + pm, + proof, + fun + | ProofMark.PatternNotFound(_) => true + | _ => false, + ), + ); +}; + +/* NothingToStep: an eval step on a fully-normalised subterm. The literal + * `1` has no reducible step under the evaluator. */ +let test_nothing_to_step_mark = () => { + let src = {|theorem t = 1 == 1 proof from 1 do step end in t|}; + let uexp = parse_exp(src); + let (state, _, elab) = eval_with_proof(uexp); + let pm = EvaluatorState.get_proof_map(state); + let proof = proof_of(elab); + Alcotest.check( + Alcotest.bool, + "NothingToStep mark is emitted", + true, + has_mark_kind( + pm, + proof, + fun + | ProofMark.NothingToStep => true + | _ => false, + ), + ); +}; + +/* ExpectedForallGoal: a `forall` proof when the goal isn't a forall. */ +let test_expected_forall_goal_mark = () => { + let src = {|theorem t = 1 == 1 proof forall x => from 1 == 1 do rewrite refl end end in t|}; + let uexp = parse_exp(src); + let (state, _, elab) = eval_with_proof(uexp); + let pm = EvaluatorState.get_proof_map(state); + let proof = proof_of(elab); + Alcotest.check( + Alcotest.bool, + "ExpectedForallGoal mark is emitted", + true, + has_mark_kind( + pm, + proof, + fun + | ProofMark.ExpectedForallGoal => true + | _ => false, + ), + ); +}; + +/* MissingIncoming: once a step breaks propagation, the next step in a + * sequence should record MissingIncoming against its own id. */ +let test_missing_incoming_mark = () => { + /* The first axiom is bogus: it records a mark but passes the goal + * through, so the second axiom still acts on `1 == 1` and succeeds. + * The proof reaches `true`, but the broken step keeps it from counting + * as proven. */ + let src = {|theorem t = 1 == 1 proof from 1 == 1 do rewrite bogus end end; from 1 == 1 do rewrite refl end end in t|}; + let uexp = parse_exp(src); + let (state, _, elab) = eval_with_proof(uexp); + let pm = EvaluatorState.get_proof_map(state); + let proof = proof_of(elab); + /* No step goes dark: nothing carries MissingIncoming. */ + let rec scan = (p: Proof.t): bool => { + let here = + List.exists( + ~f= + fun + | ProofMark.MissingIncoming => true + | _ => false, + ProofMap.marks_of(Proof.rep_id(p), pm), + ); + here + || ( + switch (p.term) { + | Seq(a, b) => scan(a) || scan(b) + | _ => false + } + ); + }; + Alcotest.check( + Alcotest.bool, + "broken step recovers instead of blocking the second step", + false, + scan(proof), + ); + /* The second step ran against the passed-through goal and reduced it + * to `true`... */ + let outgoing = + switch (ProofMap.lookup(Proof.rep_id(proof), pm)) { + | Some({outgoing: Some(e), _}) => Some(e) + | _ => None + }; + Alcotest.check( + Alcotest.bool, + "later step still ran on the recovered goal", + true, + switch (outgoing) { + | Some(e) => Exp.fast_equal(e, Exp.temp(Atom(Bool(true)))) + | None => false + }, + ); + /* ...but a proof with a broken step in it is not proven. */ + Alcotest.check( + Alcotest.option(bool), + "broken-but-recovered proof is not marked proven", + None, + ProofMap.status_of_proof(pm, proof), + ); +}; + +/* Chained eval steps: each step's outgoing feeds the next. */ +let test_one_eval_step_outgoing = () => { + let src = {|theorem thm = 1 + 4 == 5 proof from 1 + 4 do step end in thm|}; + let (state, _, elab) = src |> parse_exp |> eval_with_proof; + let entry = proof_entry(state, elab); + check_exp( + "one-step outgoing", + "5 == 5", + require_exp("expected outgoing", entry.outgoing), + ); +}; + +let test_two_eval_steps_outgoing = () => { + let src = {|theorem thm = 1 + 4 == 5 proof from 1 + 4 do step end; from 5 == 5 do step end in thm|}; + let (state, _, elab) = src |> parse_exp |> eval_with_proof; + let entry = proof_entry(state, elab); + check_exp( + "two-step outgoing", + "true", + require_exp("expected outgoing", entry.outgoing), + ); +}; + +/* A theorem mid-edit (body after `in` still empty) must still get its + proof checked into the proof map. */ +let test_empty_body_still_checked = () => { + let src = "theorem thm = 1 + 4 == 5 proof \nfrom 1 + 4 do step end\n in"; + let (state, _, elab) = src |> parse_exp |> eval_with_proof; + let entry = proof_entry(state, elab); + check_exp( + "empty-body one-step outgoing", + "5 == 5", + require_exp("expected outgoing (empty body)", entry.outgoing), + ); +}; + +/* MalformedProofTerm: unparseable text in proof position is an error, + * unlike an EmptyHole (an intentionally-incomplete proof, unmarked). */ +let test_malformed_proof_term_mark = () => { + let src = {|theorem t = 1 == 1 proof 1 + 1 in t|}; + let uexp = parse_exp(src); + let (state, _, elab) = eval_with_proof(uexp); + let pm = EvaluatorState.get_proof_map(state); + let proof = proof_of(elab); + Alcotest.check( + Alcotest.bool, + "MalformedProofTerm mark is emitted", + true, + has_mark_kind( + pm, + proof, + fun + | ProofMark.MalformedProofTerm => true + | _ => false, + ), + ); +}; + +let test_empty_hole_proof_unmarked = () => { + let src = {|theorem t = 1 == 1 proof ? in t|}; + let uexp = parse_exp(src); + let (state, _, elab) = eval_with_proof(uexp); + let pm = EvaluatorState.get_proof_map(state); + let proof = proof_of(elab); + Alcotest.check( + Alcotest.bool, + "an empty-hole proof carries no mark", + true, + find_marked_sub(pm, proof) == None, + ); +}; + +/* Direction survives the axiom surface syntax: `rewrite <-` parses to a + * Left-direction step, and printing + reparsing preserves it. */ +let axiom_direction_of = (p: Proof.t): option(Util.Direction.t) => { + let rec go = (p: Proof.t): option(Util.Direction.t) => + switch (p.term) { + | AxiomStep({direction, _}) => Some(direction) + | Seq(p1, p2) => + switch (go(p1)) { + | Some(_) as d => d + | None => go(p2) + } + | Forall(_, body) => go(body) + | _ => None + }; + go(p); +}; + +let test_axiom_direction_roundtrip = () => { + let src = {|theorem t = 1 == 1 proof rewrite <- refl end in t|}; + let direction_of = (e: Exp.t): option(Util.Direction.t) => + switch (find_theorem_proof(e)) { + | Some(p) => axiom_direction_of(p) + | None => None + }; + let uexp = parse_exp(src); + Alcotest.check( + Alcotest.bool, + "rewrite <- parses to a Left-direction step", + true, + direction_of(uexp) == Some(Util.Direction.Left), + ); + let reparsed = parse_exp(print_exp(uexp)); + Alcotest.check( + Alcotest.bool, + "direction survives print + reparse", + true, + direction_of(reparsed) == Some(Util.Direction.Left), + ); +}; + +/* --- Assume / obligation tests ------------------------------------- + * + * `assume => ` hypothesizes for the sub-proof and + * incurs a sequent obligation, recorded on the assume node's proof-map + * entry with discharge provenance. `full_status_of_proof` refines + * `status_of_proof` with the obligation-aware `ProvenModulo`. */ + +/* (a) An unused, undischargeable assumption: the proof still reaches + * `true` (`status_of_proof` is unaffected), but full status is + * ProvenModulo with exactly one pending obligation `1 == 2`. (The + * assumption is closed but evaluates to `false`, so closed evaluation + * doesn't discharge it; a closed `true` assumption would discharge as + * `Evaluated`, see the next test.) */ +/* (a') Closed evaluation: a closed assumption that evaluates to `true` + * discharges as `Evaluated`, so the theorem is fully Proven despite the + * assumption. */ +/* Closed evaluation never runs a recursive function, whether the goal + * calls it directly, through a non-recursive closure or as a builtin. */ +let check_assume_stays_pending = (prefix: string, fact: string, ()) => { + let src = + prefix + ++ "theorem t = 1 == 1 proof have " + ++ fact + ++ " proof ? => from 1 == 1 do rewrite refl end end in t"; + let (state, _, elab) = src |> parse_exp |> eval_with_proof; + let pm = EvaluatorState.get_proof_map(state); + Alcotest.check( + Alcotest.bool, + "the obligation stays Pending", + true, + switch (ProofMap.obligations_of_proof(pm, proof_of(elab))) { + | [ob] => ob.discharge == Obligation.Pending + | _ => false + }, + ); +}; + +let countdown = "let r = fun (n : Int) -> if n == 0 then 0 else r(n - 1) in "; + +/* (b) The assumed equation is used: citing the hypothesis name `assume` + * rewrites the goal with the assumed equation, so the theorem is + * ProvenModulo its single pending obligation. */ +let test_assume_hypothesis_used = () => { + let src = {|theorem t = forall x -> x == 1 ==> x == 1 proof assume x == 1 => from x do rewrite assume end end; from 1 == 1 do rewrite refl end end in t|}; + let (state, _, elab) = src |> parse_exp |> eval_with_proof; + let pm = EvaluatorState.get_proof_map(state); + let proof = proof_of(elab); + Alcotest.check( + Alcotest.string, + "proven by citing the hypothesis", + "Proven", + ProofMap.show_full_status(ProofMap.full_status_of_proof(pm, proof)), + ); +}; + +/* (c) A nested assume of an identical proposition: the inner obligation + * discharges Remote against the outer hypothesis by lookup, so two + * obligations are recorded but only one is pending. (`1 == 2` evaluates + * to `false`, so the outer one stays pending.) */ +/* (d) An assume-free proof has no obligations and full status + * Proven. */ +let test_no_assume_full_status_proven = () => { + let src = {|theorem t = 1 == 1 proof from 1 == 1 do rewrite refl end end in t|}; + let (state, _, elab) = src |> parse_exp |> eval_with_proof; + let pm = EvaluatorState.get_proof_map(state); + let proof = proof_of(elab); + Alcotest.check( + Alcotest.int, + "no obligations recorded", + 0, + List.length(ProofMap.obligations_of_proof(pm, proof)), + ); + Alcotest.check( + Alcotest.bool, + "full status is Proven", + true, + ProofMap.full_status_of_proof(pm, proof) == ProofMap.Proven, + ); +}; + +/* --- Implication ---------------------------------------------------- */ + +/* `==>` parses right-associative, just below `||`, and round-trips + * through printing. */ +let test_implies_parse_and_roundtrip = () => { + let same = (msg, a, b) => + Alcotest.check( + Alcotest.bool, + msg, + true, + Exp.fast_equal(parse_exp(a), parse_exp(b)), + ); + let diff = (msg, a, b) => + Alcotest.check( + Alcotest.bool, + msg, + false, + Exp.fast_equal(parse_exp(a), parse_exp(b)), + ); + same( + "==> binds looser than ==", + "a == b ==> c == d", + "(a == b) ==> (c == d)", + ); + same("==> is right-associative", "a ==> b ==> c", "a ==> (b ==> c)"); + diff("==> is not left-associative", "a ==> b ==> c", "(a ==> b) ==> c"); + same( + "==> binds looser than ||", + "a || b ==> c || d", + "(a || b) ==> (c || d)", + ); + let roundtrip = src => { + let e = parse_exp(src); + Alcotest.check( + Alcotest.bool, + "round-trip: " ++ src, + true, + Exp.fast_equal(e, parse_exp(print_exp(e))), + ); + }; + roundtrip("a == b ==> c == d"); + roundtrip("a ==> b ==> c"); + roundtrip("(a ==> b) ==> c"); +}; + +/* Implication intro via assume: when the assumed exp is the antecedent of + * the incoming `A ==> B` goal, the checker strips it (the body's incoming + * is B) and no obligation is incurred. A complete proof goes through with + * full status Proven and zero obligations. */ +let test_impl_intro_via_assume = () => { + let src = {|theorem t = forall x -> x == 2 ==> x + 1 == 3 proof assume x == 2 => from x do rewrite assume end end; from 2 + 1 do step end; from 3 == 3 do rewrite refl end end in t|}; + let (state, _, elab) = src |> parse_exp |> eval_with_proof; + let pm = EvaluatorState.get_proof_map(state); + let proof = proof_of(elab); + Alcotest.check( + Alcotest.int, + "intro incurs ZERO obligations", + 0, + List.length(ProofMap.obligations_of_proof(pm, proof)), + ); + Alcotest.check( + Alcotest.bool, + "full status is Proven", + true, + ProofMap.full_status_of_proof(pm, proof) == ProofMap.Proven, + ); +}; + +/* A non-matching assume against an implication goal is not an intro: + * the goal keeps its antecedent, so the proof can't strip it, and the + * assume incurs its obligation. */ +/* `assume` is implication introduction only: on a goal that isn't + * `P ==> Q` with P the written proposition it is refused, and incurs + * nothing. A hole for P assumes nothing yet and isn't refused. */ +let test_assume_needs_an_implication = () => { + let assume_marks = src => { + let (pm, proof) = run(src); + ( + ProofMap.marks_of(Proof.rep_id(proof), pm), + ProofMap.obligations_of_proof(pm, proof), + ); + }; + let refused = src => + switch (assume_marks(src)) { + | ([ProofMark.ExpectedImplicationGoal(_)], []) => true + | _ => false + }; + Alcotest.check( + Alcotest.bool, + "refused when P isn't the antecedent", + true, + refused( + {|theorem t = forall x -> x == 2 ==> x + 1 == 3 proof assume x == 5 => ? in t|}, + ), + ); + Alcotest.check( + Alcotest.bool, + "refused when the goal isn't an implication", + true, + refused({|theorem t = 1 == 1 proof assume 1 == 2 => ? in t|}), + ); + Alcotest.check( + Alcotest.bool, + "a hole isn't refused", + true, + assume_marks({|theorem t = 1 == 1 proof assume ? => ? in t|}) == ([], []), + ); +}; + +/* Conditional rule via `==>`: a use site with a closed + * instantiation incurs the instantiated antecedent, which closed evaluation + * discharges (`Evaluated`), so full status is Proven. */ +let test_conditional_rule_closed_discharges = () => { + let src = {|theorem inv = forall x -> x != 0 ==> x == x proof assume x != 0 => from x == x do rewrite refl end end in theorem u = 2 == 2 proof from 2 do rewrite inv end end; from 2 == 2 do rewrite refl end end in u|}; + let (state, _, elab) = src |> parse_exp |> eval_with_proof; + let pm = EvaluatorState.get_proof_map(state); + let use_proof = proof_of_named("u", elab); + let obs = ProofMap.obligations_of_proof(pm, use_proof); + Alcotest.check( + Alcotest.int, + "the use site incurs one obligation", + 1, + List.length(obs), + ); + switch (obs) { + | [ob] => + check_exp("the obligation is the instantiated guard", "2 != 0", ob.goal); + Alcotest.check( + Alcotest.bool, + "discharged by closed evaluation", + true, + ob.discharge == Obligation.Evaluated, + ); + | _ => () + }; + Alcotest.check( + Alcotest.bool, + "use is fully Proven", + true, + ProofMap.full_status_of_proof(pm, use_proof) == ProofMap.Proven, + ); +}; + +/* Same rule with an open instantiation: the instantiated guard can't be + * evaluated (open goals never are) and nothing in scope covers it, so it + * is Pending and the use is ProvenModulo. */ +let test_conditional_rule_open_pending = () => { + let src = {|theorem inv = forall x -> x != 0 ==> x == x proof assume x != 0 => from x == x do rewrite refl end end in theorem u = forall y -> y == y proof from y do rewrite inv end end; from y == y do rewrite refl end end in u|}; + let (state, _, elab) = src |> parse_exp |> eval_with_proof; + let pm = EvaluatorState.get_proof_map(state); + let use_proof = proof_of_named("u", elab); + switch (ProofMap.full_status_of_proof(pm, use_proof)) { + | ProvenModulo([ob]) => + check_exp("pending obligation is the open guard", "y != 0", ob.goal) + | other => + Alcotest.fail( + "expected ProvenModulo with one pending obligation, got: " + ++ ProofMap.show_full_status(other), + ) + }; +}; + +/* Underdetermined instantiation: a conditional rule whose assumption + * mentions a metavariable (`k`) the conclusion match cannot fix is + * refused with UnderdeterminedInstantiation. */ +let test_underdetermined_instantiation = () => { + let src = {|theorem r = forall x -> forall k -> k != 0 ==> x == x proof ? in theorem u = 2 == 2 proof from 2 do rewrite r end end in u|}; + let (state, _, elab) = src |> parse_exp |> eval_with_proof; + let pm = EvaluatorState.get_proof_map(state); + let use_proof = proof_of_named("u", elab); + Alcotest.check( + Alcotest.bool, + "UnderdeterminedInstantiation mark is emitted", + true, + has_mark_kind( + pm, + use_proof, + fun + | ProofMark.UnderdeterminedInstantiation(_) => true + | _ => false, + ), + ); +}; + +/* Built-in Kleene axioms are usable as ordinary axiom steps. */ +let test_kleene_axiom_and_comm = () => { + let src = {|theorem t = (true && false) == (false && true) proof from true && false do rewrite and_comm end end; from (false && true) == (false && true) do rewrite refl end end in t|}; + let (state, _, elab) = src |> parse_exp |> eval_with_proof; + let pm = EvaluatorState.get_proof_map(state); + Alcotest.check( + Alcotest.bool, + "and_comm proof is Proven", + true, + ProofMap.full_status_of_proof(pm, proof_of(elab)) == ProofMap.Proven, + ); +}; + +let test_kleene_axiom_impl_def = () => { + let src = {|theorem t = forall p -> forall q -> (p ==> q) == (!p || q) proof from p ==> q do rewrite impl_def end end; from (!p || q) == (!p || q) do rewrite refl end end in t|}; + let (state, _, elab) = src |> parse_exp |> eval_with_proof; + let pm = EvaluatorState.get_proof_map(state); + Alcotest.check( + Alcotest.bool, + "impl_def proof is Proven", + true, + ProofMap.full_status_of_proof(pm, proof_of(elab)) == ProofMap.Proven, + ); +}; + +/* ---- Pattern targets in `on`/`at` slots ---------------------------- + * + * The target slot of a proof step accepts a pattern with `$e`/`$v`/`$x` + * metavariables (MetaVar), reusing the stepper filter convention. The + * matched *concrete* subterm is what gets rewritten or evaluated, so + * these tests assert the same outcomes as their ground-quote + * neighbours above. + */ + +/* `rewrite refl at 0 on $e == $e` in place of the exact quote: the + * pattern locates the equation, and the axiom still applies to the + * concrete `1 == 1` it matched. Compare test_refl_checkmark. */ +let test_pattern_refl_checkmark = () => { + let src = {|theorem t = 1 == 1 proof from $e == $e do rewrite refl end end in t|}; + let (state, _, elab) = src |> parse_exp |> eval_with_proof; + let pm = EvaluatorState.get_proof_map(state); + Alcotest.check( + Alcotest.option(bool), + "pattern-target refl proof should be checkmark", + Some(true), + ProofMap.status_of_proof(pm, proof_of(elab)), + ); +}; + +/* The same under a binder: the pattern doesn't have to name `x`, so + * renaming the statement's variable doesn't break the proof. Compare + * test_refl_forall_checkmark. */ +let test_pattern_refl_forall_checkmark = () => { + let src = {|theorem t = forall x -> x == x proof from $e == $e do rewrite refl end end in t|}; + let (state, _, elab) = src |> parse_exp |> eval_with_proof; + let pm = EvaluatorState.get_proof_map(state); + Alcotest.check( + Alcotest.option(bool), + "pattern-target forall refl proof should be checkmark", + Some(true), + ProofMap.status_of_proof(pm, proof_of(elab)), + ); +}; + +/* An eval step whose target is a pattern: `$e + $e` locates `1 + 2` + * and the concrete subterm is what steps. Compare + * test_leading_auto_step_trace, which quotes `(1 + 2)` exactly. */ +let test_pattern_eval_step_outgoing = () => { + let src = {|theorem t = (1 + 2) == 3 proof from $e + $e do step end in t|}; + let (state, _, elab) = src |> parse_exp |> eval_with_proof; + let entry = proof_entry(state, elab); + check_exp( + "pattern-target eval step reaches the same outgoing", + "3 == 3", + require_exp("expected outgoing", entry.outgoing), + ); +}; + +/* `$v` is value-restricted, so it discriminates where `$e` would not: + * in `(1 + 2) + (3 + 4)` the outer sum has non-value operands, so it is + * not a `$v + $v` match and only the two inner sums are. This also + * exercises `at n` among *pattern* matches, which count left to + * right, so `at 2` is the right sum. */ +let test_pattern_value_metavar_indexing = () => { + let src = {|theorem t = (1 + 2) + (3 + 4) == 10 proof from $v + $v at 2 do step end in t|}; + let (state, _, elab) = src |> parse_exp |> eval_with_proof; + let entry = proof_entry(state, elab); + check_exp( + "second $v + $v match is the right-hand sum", + "(1 + 2) + 7 == 10", + require_exp("expected outgoing", entry.outgoing), + ); +}; + +/* A pattern that matches nothing is reported exactly like a missing + * exact quote. Compare the PatternNotFound test for `5 == 5`. */ +let test_pattern_not_found = () => { + let src = {|theorem t = 1 == 1 proof from $e + $e do rewrite refl end end in t|}; + let (state, _, elab) = src |> parse_exp |> eval_with_proof; + let pm = EvaluatorState.get_proof_map(state); + Alcotest.check( + Alcotest.bool, + "unmatched pattern target is a PatternNotFound", + true, + has_mark_kind( + pm, + proof_of(elab), + fun + | ProofMark.PatternNotFound(_) => true + | _ => false, + ), + ); +}; + +/* Metavariables in a target slot must not read as free variables: the + * statics case that covers stepper filters covers these slots too, so + * the program has no free-variable mark. */ +let test_pattern_metavar_not_free = () => { + let src = {|theorem t = 1 == 1 proof from $e == $e do rewrite refl end end in t|}; + let (statics, _) = statics_and_elab(parse_exp(src)); + let free = + Id.Map.exists( + (_, info) => + switch (info) { + | Info.InfoExp({marks, _}) => + List.exists( + ~f= + fun + | Mark.Free(name) => MetaVar.is_meta_name(name) + | _ => false, + marks, + ) + | _ => false + }, + statics, + ); + Alcotest.check( + Alcotest.bool, + "no metavariable is marked free", + false, + free, + ); +}; + +/* --- Proofs are not values ------------------------------------------ + * + * Theorems and hypotheses live in their own context namespace, not as + * values. The statics side is tested in Test_Statics_Proof; these two + * test the checker, which reads the same `Ctx.TheoremEntry` entries. + */ + +/* A `let` of the same name after the theorem doesn't hide the theorem + * from a citation: `rewrite lem` resolves in the theorem namespace, which + * the value binding can't shadow. */ +let test_citation_survives_value_shadowing = () => { + /* `lem` states `1 + 1 == 2`, so citing it rewrites `1 + 1` to `2`; + `g`'s goal then evaluates to `true`. The `let lem = 5` in between + rebinds the name in the value namespace only. */ + let src = {|theorem lem = 1 + 1 == 2 proof from 1 + 1 do step end; from 2 == 2 do rewrite refl end end in let lem = 5 in theorem g = (1 + 1) + 1 == 3 proof from 1 + 1 do rewrite lem end end; from 2 + 1 do step end; from 3 == 3 do rewrite refl end end in lem|}; + let (state, _, elab) = src |> parse_exp |> eval_with_proof; + let pm = EvaluatorState.get_proof_map(state); + let proof = proof_of_named("g", elab); + /* The citation resolves. */ + Alcotest.check( + Alcotest.bool, + "`rewrite lem` is not an unknown equality with `lem` rebound", + false, + has_mark_kind( + pm, + proof, + fun + | ProofMark.UnknownEquality(_) => true + | _ => false, + ), + ); + Alcotest.check( + Alcotest.option(bool), + "`rewrite lem` still applies with `lem` rebound to a value", + Some(true), + ProofMap.status_of_proof(pm, proof), + ); +}; + +/* A theorem name is not a value, so in `theorem t = ... in t` the body + * is an ordinary expression (with `t` free), and the theorem is still + * checked: the proof map is populated. */ +let test_theorem_body_is_ordinary_code = () => { + let src = {|theorem t = 1 == 1 proof from 1 == 1 do rewrite refl end end in 7|}; + let (state, _, elab) = src |> parse_exp |> eval_with_proof; + let pm = EvaluatorState.get_proof_map(state); + let proof = proof_of_named("t", elab); + Alcotest.check( + Alcotest.option(bool), + "the theorem is still checked when the body ignores its name", + Some(true), + ProofMap.status_of_proof(pm, proof), + ); +}; + +/* Each step records the scope it was checked in: a form's own node has + * the enclosing scope, its body the scope the form opens. */ +let test_entries_record_scope = () => { + let src = {|theorem t = forall (x : Int) -> x == 1 ==> x == x proof assume x == 1 => ? in t|}; + let (pm, proof) = run(src); + let hole = + switch (proof.term) { + | Assume(_, _, body) => body + | _ => Alcotest.fail("not assume _ => ?") + }; + let ctx_of = (p: Proof.t) => + switch (ProofMap.lookup(Proof.rep_id(p), pm)) { + | Some(entry) => entry.ctx + | None => Alcotest.fail("no entry") + }; + let fact_names = p => + SemanticCtx.facts(ctx_of(p)) |> List.map(~f=((name, _, _)) => name); + check( + bool, + "the statement's binder is in scope", + true, + Ctx.lookup_var(SemanticCtx.get_ctx(ctx_of(proof)), "x") != None, + ); + check( + bool, + "the assume is checked without its hypothesis", + false, + List.mem(fact_names(proof), "assume", ~equal=String.equal), + ); + check( + bool, + "the assume's body has the hypothesis", + true, + List.mem(fact_names(hole), "assume", ~equal=String.equal), + ); +}; + +/* An induction steps to its conclusion, `true`, once its cases cover the + * scrutinee, so the row after it never repeats the goal; a case still + * open keeps the proof incomplete. */ +let test_unfinished_induction_steps_to_true = () => { + let (pm, proof) = + run( + {|theorem t = forall xs : [Int] -> xs == xs proof induction xs | [] => from [] == [] do rewrite refl end end | y :: ys => ? end in t|}, + ); + let outgoing = + switch (ProofMap.lookup(Proof.rep_id(proof), pm)) { + | Some({outgoing: Some(e), _}) => print_exp(e) + | _ => "" + }; + Alcotest.check(Alcotest.string, "outgoing", "true", outgoing); + check_status("an open case", ProofMap.Incomplete, pm, proof); +}; + +/* Assuming a goal's antecedent steps to `true`, as a split does, so the + * assume's body result never stands in for the implication; an + * unfinished body keeps the proof incomplete. */ +let test_assume_of_antecedent_steps_to_true = () => { + let (pm, proof) = + run({|theorem t = 1 == 2 ==> false proof assume 1 == 2 => ? in t|}); + check_status("an unfinished body", ProofMap.Incomplete, pm, proof); + let (pm, proof) = + run( + {|theorem t = forall x: Int -> x == 1 ==> 2 == 2 proof assume x == 1 => step in t|}, + ); + check_status("a finished body", ProofMap.Proven, pm, proof); + /* In a focus, the body's result would replace the implication. */ + let (pm, proof) = + run_named( + "bad", + {|theorem bad = forall x: Int -> (!(x == 0) || x == 1) == false proof from !(x == 0) || x == 1 do rewrite <- impl_def end; assume h = x == 0 => from x do rewrite h end end; step end; step in bad|}, + ); + check_status("in a focus", ProofMap.Incomplete, pm, proof); +}; + +/* A `have`'s premise is proven only when its subproof's splits and + * assumes are finished too. */ +let test_have_premise_needs_closed_cases = () => { + let pending = src => { + let (_, _, obs) = obligations(src); + List.length(List.filter(~f=Obligation.is_pending, obs)); + }; + Alcotest.check( + Alcotest.int, + "an open induction case", + 1, + pending( + {|theorem t = 1 == 1 proof have 1 == 2 proof induction [1] | [] => ? | h :: rest => ? end => step in t|}, + ), + ); + Alcotest.check( + Alcotest.int, + "an unfinished assume", + 1, + pending( + {|theorem t = forall x: Int -> 1 == 1 proof have x == 2 ==> x == 3 proof assume x == 2 => ? => step in t|}, + ), + ); +}; + +/* Citing a theorem whose proof isn't finished rests on its statement, an + * obligation; citing a refuted one is an error on the step. */ +let test_citation_follows_the_cited_verdict = () => { + let cite = lemma => + run_named( + "t", + "theorem lemma = 1 == 2 proof " + ++ lemma + ++ " in theorem t = 1 == 2 proof from 1 do rewrite lemma end end; step in t", + ); + let (pm, proof) = cite("?"); + switch (ProofMap.full_status_of_proof(pm, proof)) { + | ProvenModulo([{kind: Citation, _}]) => () + | status => + Alcotest.fail( + "unfinished: expected ProvenModulo on the citation, got " + ++ ProofMap.show_full_status(status), + ) + }; + let (pm, proof) = cite("step"); + check_status("refuted", ProofMap.Incomplete, pm, proof); + Alcotest.check( + Alcotest.bool, + "the citing step is marked", + true, + List.mem( + List.concat_map( + ~f=((_, entry: ProofMap.entry)) => entry.marks, + Id.Map.bindings(pm), + ), + ProofMark.CitesRefuted("lemma"), + ~equal=Poly.equal, + ), + ); + let (pm, proof) = + run_named( + "t", + {|theorem lemma = 1 + 1 == 2 proof step in theorem t = 1 + 1 == 2 proof from 1 + 1 do rewrite lemma end end; step in t|}, + ); + check_status("proven", ProofMap.Proven, pm, proof); +}; + +/* A `forall` step names the goal's binder: a different name renames it, + * unless the goal already uses that name. */ +let test_forall_renames_the_binder = () => { + let (pm, proof) = + run( + {|theorem t = forall a: Int -> a == a proof generalize a => forall b => from b == b do rewrite refl end end in t|}, + ); + check_status("renamed", ProofMap.Proven, pm, proof); + let (pm, _) = + run( + {|theorem t = forall a: Int -> forall b: Int -> a + b == a + b proof generalize a => forall b => ? in t|}, + ); + Alcotest.check( + Alcotest.bool, + "a name the goal uses is refused", + true, + List.mem( + List.concat_map( + ~f=((_, entry: ProofMap.entry)) => entry.marks, + Id.Map.bindings(pm), + ), + ProofMark.BinderCaptures({var: "b"}), + ~equal=Poly.equal, + ), + ); +}; + +/* An implication in parentheses is still one: `assume` introduces its + * antecedent, and a lemma stated with one is a conditional rule. */ +let test_implication_through_parens = () => { + let (pm, proof) = + run( + {|theorem t = forall x: Int -> x == x ==> (forall y: Int -> (y == x ==> y == x)) proof assume x == x => forall y => assume y == x => ? in t|}, + ); + Alcotest.check( + Alcotest.int, + "assume: no pending obligation", + 0, + List.length( + List.filter( + ~f=Obligation.is_pending, + ProofMap.obligations_of_proof(pm, proof), + ), + ), + ); + let (pm, proof) = + run_named( + "u", + {|theorem inv = forall x -> (x != 0 ==> x == x) proof assume x != 0 => from x == x do rewrite refl end end in theorem u = forall y -> y == y proof from y do rewrite inv end end; from y == y do rewrite refl end end in u|}, + ); + switch (ProofMap.full_status_of_proof(pm, proof)) { + | ProvenModulo([ob]) => + check_exp("a cited lemma's antecedent", "y != 0", ob.goal) + | other => + Alcotest.fail( + "expected the antecedent pending, got " + ++ ProofMap.show_full_status(other), + ) + }; +}; + +/* `==` is reflexive at `nan`, so `refl` instantiated there proves only + * what is true. */ +let test_refl_at_nan = () => { + let (pm, proof) = + run_named( + "bad", + {|theorem refl_f = forall x: Float -> x == x proof rewrite refl end in theorem bad = false proof revert refl_f with x = nan => from $e == $e do step end; step in bad|}, + ); + check_status("false stays false", ProofMap.Refuted, pm, proof); +}; + +/* A split whose scrutinee is still a hole, as the Strategy tab writes + * it, is unfinished, not marked as possibly divergent. */ +let test_hole_scrutinee_unmarked = () => + List.iter( + ~f= + split => { + let (pm, _) = + run( + "theorem t = forall xs: [Int] -> xs == xs proof " + ++ split + ++ " ? end in t", + ); + Alcotest.check( + Alcotest.bool, + split ++ " ?", + false, + List.mem( + List.concat_map( + ~f=((_, entry: ProofMap.entry)) => entry.marks, + Id.Map.bindings(pm), + ), + ProofMark.PossiblyDivergentScrutinee, + ~equal=Poly.equal, + ), + ); + }, + ["induction", "cases"], + ); + +let tests = ( + "Evaluator.ProofMap", + [ + test_case( + "a split on a hole isn't possibly divergent", + `Quick, + test_hole_scrutinee_unmarked, + ), + test_case( + "a forall step renames the goal's binder", + `Quick, + test_forall_renames_the_binder, + ), + test_case( + "an implication in parentheses is an implication", + `Quick, + test_implication_through_parens, + ), + test_case("refl at nan proves nothing false", `Quick, test_refl_at_nan), + test_case( + "assuming a goal's antecedent steps to true", + `Quick, + test_assume_of_antecedent_steps_to_true, + ), + test_case( + "a have's premise needs its subproof's cases closed", + `Quick, + test_have_premise_needs_closed_cases, + ), + test_case( + "a citation follows the cited theorem's verdict", + `Quick, + test_citation_follows_the_cited_verdict, + ), + test_case( + "each step records the scope it was checked in", + `Quick, + test_entries_record_scope, + ), + test_case( + "one eval step's outgoing feeds the goal", + `Quick, + test_one_eval_step_outgoing, + ), + test_case( + "two chained eval steps discharge the goal", + `Quick, + test_two_eval_steps_outgoing, + ), + test_case( + "empty theorem body still checks the proof", + `Quick, + test_empty_body_still_checked, + ), + test_case( + "eval trace records leading hidden transition", + `Quick, + test_leading_auto_step_trace, + ), + test_case( + "eval trace records trailing hidden transition", + `Quick, + test_trailing_auto_step_trace, + ), + test_case("refl produces checkmark", `Quick, test_refl_checkmark), + test_case( + "forall refl produces checkmark", + `Quick, + test_refl_forall_checkmark, + ), + test_case("empty hole produces nothing", `Quick, test_empty_hole_nothing), + test_case( + "false goal is not marked as proven", + `Quick, + test_false_goal_not_checkmark, + ), + test_case("append carries proof_map", `Quick, test_append_proof_map), + test_case( + "unknown equality emits mark", + `Quick, + test_unknown_equality_mark, + ), + test_case( + "pattern-not-found emits mark", + `Quick, + test_pattern_not_found_mark, + ), + test_case("algebra finds pattern", `Quick, test_rewrite_finds_pattern), + test_case( + "a focus ordinal counts occurrences as written", + `Quick, + test_rewrite_zero_as_written, + ), + test_case( + "algebra finds pattern under use Nat", + `Quick, + test_rewrite_finds_pattern_nat, + ), + test_case( + "nothing-to-step emits mark", + `Quick, + test_nothing_to_step_mark, + ), + test_case( + "expected forall goal emits mark", + `Quick, + test_expected_forall_goal_mark, + ), + test_case( + "missing-incoming propagates to later step", + `Quick, + test_missing_incoming_mark, + ), + test_case( + "malformed proof term emits mark", + `Quick, + test_malformed_proof_term_mark, + ), + test_case( + "empty-hole proof stays unmarked", + `Quick, + test_empty_hole_proof_unmarked, + ), + test_case( + "rewrite direction survives round trip", + `Quick, + test_axiom_direction_roundtrip, + ), + test_case( + "assumed hypothesis is citable and rewrites the goal", + `Quick, + test_assume_hypothesis_used, + ), + test_case( + "assume-free proof is Proven with no obligations", + `Quick, + test_no_assume_full_status_proven, + ), + test_case( + "closed evaluation doesn't run a recursive function", + `Quick, + check_assume_stays_pending(countdown, "r(3) == 0"), + ), + test_case( + "closed evaluation doesn't run a closure that recurses", + `Quick, + check_assume_stays_pending( + countdown ++ "let h = fun (n : Int) -> r(n) in ", + "h(3) == 0", + ), + ), + test_case( + "closed evaluation doesn't run a recursive builtin", + `Quick, + check_assume_stays_pending("", "length([1, 2]) == 2"), + ), + test_case( + "==> parses and round-trips", + `Quick, + test_implies_parse_and_roundtrip, + ), + test_case( + "implication intro via assume (no obligation)", + `Quick, + test_impl_intro_via_assume, + ), + test_case( + "assume needs a goal P ==> Q", + `Quick, + test_assume_needs_an_implication, + ), + test_case( + "conditional rule: closed instantiation discharges Evaluated", + `Quick, + test_conditional_rule_closed_discharges, + ), + test_case( + "conditional rule: open instantiation stays Pending", + `Quick, + test_conditional_rule_open_pending, + ), + test_case( + "underdetermined instantiation is refused", + `Quick, + test_underdetermined_instantiation, + ), + test_case( + "Kleene axiom and_comm is usable", + `Quick, + test_kleene_axiom_and_comm, + ), + test_case( + "Kleene axiom impl_def is usable", + `Quick, + test_kleene_axiom_impl_def, + ), + test_case( + "pattern target: $e == $e proves reflexivity", + `Quick, + test_pattern_refl_checkmark, + ), + test_case( + "pattern target: $e == $e under a binder", + `Quick, + test_pattern_refl_forall_checkmark, + ), + test_case( + "pattern target: eval $e + $e reaches the same outgoing", + `Quick, + test_pattern_eval_step_outgoing, + ), + test_case( + "pattern target: $v is value-restricted and `at` indexes matches", + `Quick, + test_pattern_value_metavar_indexing, + ), + test_case( + "pattern target: an unmatched pattern is PatternNotFound", + `Quick, + test_pattern_not_found, + ), + test_case( + "pattern target: metavariables are not free variables", + `Quick, + test_pattern_metavar_not_free, + ), + test_case( + "namespace separation: citation survives value shadowing", + `Quick, + test_citation_survives_value_shadowing, + ), + test_case( + "namespace separation: theorem body is ordinary code", + `Quick, + test_theorem_body_is_ordinary_code, + ), + test_case( + "an unfinished induction steps to true and stays incomplete", + `Quick, + test_unfinished_induction_steps_to_true, + ), + ], +); diff --git a/test/evaluator/Test_ProverDocs.re b/test/evaluator/Test_ProverDocs.re new file mode 100644 index 0000000000..8d418e45d4 --- /dev/null +++ b/test/evaluator/Test_ProverDocs.re @@ -0,0 +1,102 @@ +open Alcotest; +open Language; +open Test_Evaluator_Prelude; +open Test_ProofMap.Harness; + +/* The prover's documentation slides tell the reader what each theorem + * on them shows. These tests hold the checker to what the slides say. */ + +let read_slide = (file: string): string => { + let path = Filename.concat("hazel-programs/docs/reference", file); + let path = + List.find( + ~f=Stdlib.Sys.file_exists, + [path, Filename.concat("../../..", path)], + ) + |> Option.value(~default=path); + let ic = Stdlib.open_in_bin(path); + let text = Stdlib.really_input_string(ic, Stdlib.in_channel_length(ic)); + Stdlib.close_in(ic); + text; +}; + +let status = (pm: ProofMap.t, proof: Proof.t): string => + Web.Obligations.Status.(label(of_proof(pm, proof))); + +let theorem_names = (e: Exp.t): list(string) => { + let names = ref([]); + let f_exp = (continue, e: Exp.t) => { + switch (e.term) { + | Theorem(p, _, _, _) => + names := Option.to_list(pat_var_name(p)) @ names^ + | _ => () + }; + continue(e); + }; + let _ = TermBase.Exp.map_term(~f_exp, e); + List.rev(names^); +}; + +/* Every theorem on the slide, in order, with the status the slide's + * text gives it. */ +let slide = (file, expected: list((string, string))) => + test_case( + file, + `Quick, + () => { + let (state, _, elab) = + read_slide(file) |> parse_exp |> eval_with_proof; + let pm = EvaluatorState.get_proof_map(state); + check( + list(string), + "the theorems", + List.map(~f=fst, expected), + theorem_names(elab), + ); + List.iter( + ~f= + ((name, want)) => + check( + string, + name, + want, + status(pm, proof_of_named(name, elab)), + ), + expected, + ); + }, + ); + +let tests = ( + "ProverDocs", + [ + slide( + "prover-theorems.hz", + [("six", "proven"), ("seven", "refuted"), ("eight", "incomplete")], + ), + slide("prover-stepper.hz", [("try_it", "incomplete")]), + slide( + "prover-lemmas.hz", + [("rev_one", "proven"), ("rev_two", "proven")], + ), + slide("prover-induction.hz", [("app_nil", "proven")]), + slide( + "prover-side-conditions.hz", + [("div_open", "incomplete · 1 open"), ("div_ok", "proven")], + ), + slide( + "prover-reference.hz", + [ + ("app_nil", "proven"), + ("app_nil_fun", "proven"), + ("shuffle", "proven"), + ("acc", "proven"), + ("div_pos", "proven"), + ("div_neg", "proven"), + ("sum_three", "proven"), + ("sign_pos", "proven"), + ("sign_le", "proven"), + ], + ), + ], +); diff --git a/test/evaluator/Test_ProverKnownBugs.re b/test/evaluator/Test_ProverKnownBugs.re new file mode 100644 index 0000000000..44605e4aae --- /dev/null +++ b/test/evaluator/Test_ProverKnownBugs.re @@ -0,0 +1,60 @@ +open Language; +open Test_ProofMap.Harness; + +/* Each case pins a bug as it behaves today, named by its id in the + * prover's bug list. When a fix changes the behaviour the case fails: + * move its program to the regression tests of the area it belongs to, + * asserting the right verdict, and mark the bug fixed. */ + +let status_of = (name, src): string => { + let (pm, proof) = run_named(name, src); + switch (ProofMap.full_status_of_proof(pm, proof)) { + | Proven => "Proven" + | ProvenModulo(_) => "ProvenModulo" + | Refuted => "Refuted" + | Incomplete => "Incomplete" + }; +}; + +let pinned = (id, what, ~theorem="bad", ~now, src) => + Alcotest.test_case(id ++ ": " ++ what, `Quick, () => + Alcotest.check( + Alcotest.string, + id ++ " still behaves as filed", + now, + status_of(theorem, src), + ) + ); + +let parse_exp = Test_Evaluator_Prelude.parse_exp; + +let statics_marks = (src): list(Mark.t) => { + let (_, statics, _) = src |> parse_exp |> eval_with_proof; + Id.Map.fold((_, info, acc) => Info.marks_of(info) @ acc, statics, []); +}; + +let tests = ( + "ProverKnownBugs", + [ + Alcotest.test_case( + "PROVER-STATICS-FOCUS-BINDERS: a focus body can't name a goal binder its selector doesn't", + `Quick, + () => { + let src = "theorem t = (fun x: Int -> x + 0) == (fun x: Int -> x + (x - x)) proof from 0 do algebra x - x end end in t"; + let (pm, proof) = run_named("t", src); + Alcotest.check( + Alcotest.bool, + "the checker binds `x` in the body", + true, + Option.is_none(find_marked_sub(pm, proof)), + ); + Alcotest.check( + Alcotest.bool, + "PROVER-STATICS-FOCUS-BINDERS still behaves as filed", + true, + List.mem(statics_marks(src), Mark.Free("x"), ~equal=Poly.equal), + ); + }, + ), + ], +); diff --git a/test/evaluator/Test_Revert.re b/test/evaluator/Test_Revert.re new file mode 100644 index 0000000000..650c8fbbc3 --- /dev/null +++ b/test/evaluator/Test_Revert.re @@ -0,0 +1,224 @@ +open Alcotest; +open Language; +open Test_ProofMap.Harness; + +/* The `revert` proof step and the boolean reading of facts. + * + * `revert F => body` moves an in-scope fact back into the goal: the + * body's incoming goal is `F ==> G`. It is the inverse of assume's + * implication intro, sound and complete (F holds here, so + * `(F ==> G) == G`), hence obligation-free, and it lets eval and rewrite + * steps, which work only on the goal, compute with a hypothesis. + * + * Also covered: inductive hypotheses for recursive ADTs. */ + +/* --- Ex falso: revert a fact, contradict it in the goal, eval ---------- */ + +/* Two assumed equations that cannot both hold. Reverting the second puts + * it in the goal, where the first (still in scope, as a rewrite rule) + * turns it into `0 == 1`; evaluation then falsifies the antecedent and + * McCarthy-collapses the implication. This is the ex-falso idiom the step + * exists for: no absurdity rule, just "move it into the goal and + * compute". */ +/* The proof needs `as h0` on the outer assumption: both assumptions + are named `assume`, and the inner one shadows the outer, so `assume` + here would rewrite `n` to `1` rather than to `0`. */ +let ex_falso_src = "theorem t = forall n: Int -> n == 0 ==> n == 1 ==> false proof assume h0 = n == 0 => assume n == 1 => revert n == 1 => from n do rewrite h0 end end; from 0 == 1 do step end; from false ==> false do step end in t"; + +let test_ex_falso = () => { + let (pm, proof) = run_named("t", ex_falso_src); + check_mark_free("revert ex falso", pm, proof); + /* revert itself incurs nothing; the two assumes are intros. */ + check_obligation_count("revert ex falso", 0, pm, proof); + check_proven("revert ex falso is Proven", pm, proof); +}; + +/* --- The reverted fact stays in scope ---------------------------------- */ + +/* Reverting doesn't consume the fact: it is still citable as a rewrite + * rule inside the body, and still discharges obligations by lookup. */ +let stays_in_scope_src = "theorem t = forall n: Int -> n == 0 ==> 1 == 1 proof assume n == 0 => revert n == 0 => from n do rewrite assume end end; from 0 == 0 do step end; step; step in t"; + +let test_revert_keeps_fact = () => { + let (pm, proof) = run_named("t", stays_in_scope_src); + check_mark_free("revert keeps the fact in scope", pm, proof); + check_proven("revert keeps the fact in scope: Proven", pm, proof); +}; + +/* --- No matching fact: mark and pass through -------------------------- */ + +let unknown_src = "theorem t = forall n: Int -> n == 0 ==> 1 == 1 proof assume n == 0 => revert n == 7 => ? in t"; + +let test_revert_unknown = () => { + let (pm, proof) = run_named("t", unknown_src); + if (! + has_mark_kind( + pm, + proof, + fun + | ProofMark.UnknownFactReverted => true + | _ => false, + )) { + Alcotest.fail("reverting a fact that is not in scope should mark"); + }; + check_obligation_count( + "revert of an unknown fact incurs nothing", + 0, + pm, + proof, + ); +}; + +/* --- Bare-boolean theorem conclusions used as rules ------------------- */ + +/* The reading is uniform: it applies to every rule, not just to + * hypotheses. A theorem whose statement concludes in a bare boolean is + * therefore usable as a rewrite rule by a later theorem, with no + * `== true` anywhere in the source. `lem`'s own proof is a hole — a + * rule's usability does not depend on its proof being finished, which is + * what lets these tests be about the rule mechanism alone. */ +let lem_bare = "theorem lem = forall x: Int -> x * 0 != 1 proof ? in "; + +/* The same lemma with the reading spelled out as an Equality. Every + * assertion below is made against both, and they must agree. */ +let lem_eq = "theorem lem = forall x: Int -> (x * 0 != 1) == true proof ? in "; + +/* Forward (`rewrite`): the conclusion instance rewrites to `true`. */ +let fwd_src = "theorem t = 7 * 0 != 1 proof from 7 * 0 != 1 do rewrite lem end end in t"; + +/* Reverse (`rewrite <-`): a `true` in the goal rewrites to the conclusion + * instance. Enabled for explicit citations only; rule discovery + * suppresses it, since `true` occurs everywhere + * (`ProofRule.Rewrite.matches`). The `with` clause supplies the + * instantiation that matching on a bare `true` can't recover, and + * evaluation then brings the instance back to `true`. */ +let rev_src = "theorem t = true proof from true do rewrite <- lem with x = 3 end end; from 3 * 0 do step end; from 0 != 1 do step end in t"; + +let check_rule_use = (label: string, prelude: string, body: string) => { + let (pm, proof) = run_named("t", prelude ++ body); + check_mark_free(label, pm, proof); + check_obligation_count( + label ++ ": unconditional rule incurs nothing", + 0, + pm, + proof, + ); + check_proven_given_lemmas(label ++ ": Proven", pm, proof); +}; + +let test_bare_bool_theorem_as_rule_forward = () => { + check_rule_use( + "bare-boolean theorem as a rule, forward", + lem_bare, + fwd_src, + ); + /* An Equality-concluding rule behaves identically. */ + check_rule_use("the `== true` spelling, forward", lem_eq, fwd_src); +}; + +let test_bare_bool_theorem_as_rule_reverse = () => { + check_rule_use( + "bare-boolean theorem as a rule, reverse", + lem_bare, + rev_src, + ); + check_rule_use("the `== true` spelling, reverse", lem_eq, rev_src); +}; + +/* Negative control: the reading is gated. A conclusion that is not a + * boolean proposition stays `Other`, which can't rewrite, so citing such + * a rule marks rather than rewriting the term to `true`. */ +let non_bool_src = + "theorem lem = forall x: Int -> x * 0 proof ? in " + ++ "theorem t = 7 * 0 != 1 proof from 7 * 0 do rewrite lem end end in t"; + +let test_non_bool_conclusion_stays_inert = () => { + let (pm, proof) = run_named("t", non_bool_src); + if (! + has_mark_kind( + pm, + proof, + fun + | ProofMark.RuleDoesNotApply(_) => true + | _ => false, + )) { + Alcotest.fail( + "a non-boolean conclusion gained a rewrite reading\n" ++ dump(pm, proof), + ); + }; +}; + +/* --- Recursive-ADT inductive hypotheses ------------------------------- */ + +/* `induction e` on a recursive ADT installs an IH per recursive + * sub-pattern, although the sub-pattern's type (the unrolled `rec` form) + * is not `Typ.fast_equal` to the scrutinee's (the alias). Reverting the + * IH by its exact statement pins its shape. */ +let adt_prelude = "type Nt = +Z+S(Nt) in let pos = fun e -> case e | Z => true | S(b) => true end in "; + +let adt_ih_src = + adt_prelude + ++ "theorem t = forall e: Nt -> pos(e) proof induction e " + ++ "| Z => from pos(Z) do step end " + ++ "| S(b) => revert pos(b) => from pos(b) do rewrite ih_b end end; from true ==> pos(S(b)) do step end; from pos(S(b)) do step end " + ++ "end in t"; + +let test_adt_ih = () => { + let (pm, proof) = run_named("t", adt_ih_src); + check_mark_free("ADT induction installs an IH", pm, proof); + check_obligation_count("ADT IH citation incurs nothing", 0, pm, proof); + check_proven("ADT induction with a cited IH is Proven", pm, proof); +}; + +/* Negative control: a statement that is not an installed fact marks, so + * the test above is not vacuous. */ +let adt_ih_neg_src = + adt_prelude + ++ "theorem t = forall e: Nt -> pos(e) proof induction e " + ++ "| Z => ? " + ++ "| S(b) => revert pos(e) => ? " + ++ "end in t"; + +let test_adt_ih_negative = () => { + let (pm, proof) = run_named("t", adt_ih_neg_src); + if (! + has_mark_kind( + pm, + proof, + fun + | ProofMark.UnknownFactReverted => true + | _ => false, + )) { + Alcotest.fail("reverting a non-fact should still mark"); + }; +}; + +let tests = ( + "Evaluator.Revert", + [ + test_case("revert + eval ex falso", `Quick, test_ex_falso), + test_case( + "revert keeps the fact in scope", + `Quick, + test_revert_keeps_fact, + ), + test_case("revert of an unknown fact marks", `Quick, test_revert_unknown), + test_case( + "bare-boolean theorem as a rule (forward), vs the == true spelling", + `Quick, + test_bare_bool_theorem_as_rule_forward, + ), + test_case( + "bare-boolean theorem as a rule (reverse), vs the == true spelling", + `Quick, + test_bare_bool_theorem_as_rule_reverse, + ), + test_case( + "a non-boolean conclusion stays inert", + `Quick, + test_non_bool_conclusion_stays_inert, + ), + test_case("recursive-ADT induction installs IHs", `Quick, test_adt_ih), + test_case("IH revert negative control", `Quick, test_adt_ih_negative), + ], +); diff --git a/test/evaluator/Test_RootMissingRepro.re b/test/evaluator/Test_RootMissingRepro.re new file mode 100644 index 0000000000..080e965272 --- /dev/null +++ b/test/evaluator/Test_RootMissingRepro.re @@ -0,0 +1,112 @@ +open Alcotest; +open Poly; + +/* User-reported program: STLC progress development with `?` holes left in + * the two step(_)==NoTm branches and trailing lemma holes. */ +let user_src = {prog|type Ty = +TB+TArr(Ty, Ty) in +type Term = +TmVar(Int)+TmLam(Ty, Term)+TmAp(Term, Term) in +type MaybeTy = +NoTy+SomeTy(Ty) in +type MaybeTm = +NoTm+SomeTm(Term) in +let ty_eq = fun p -> case p | (TB, TB) => true | (TB, TArr(x, y)) => false | (TArr(x, y), TB) => false | (TArr(x1, y1), TArr(x2, y2)) => ty_eq((x1, x2)) && ty_eq((y1, y2)) end in +let nth_ty = fun p -> case p | ([], n) => NoTy | (t :: rest, n) => if n == 0 then SomeTy(t) else nth_ty((rest, n - 1)) end in +let lam_result = fun p -> case p | (t, NoTy) => NoTy | (t, SomeTy(t2)) => SomeTy(TArr(t, t2)) end in +let ap_result = fun p -> case p | (NoTy, m) => NoTy | (SomeTy(TB), m) => NoTy | (SomeTy(TArr(ta, tb)), NoTy) => NoTy | (SomeTy(TArr(ta, tb)), SomeTy(s)) => (if ty_eq((ta, s)) then SomeTy(tb) else NoTy) end in +let infer = fun p -> case p | (ctx, TmVar(n)) => nth_ty((ctx, n)) | (ctx, TmLam(t, b)) => lam_result((t, infer((t :: ctx, b)))) | (ctx, TmAp(e1, e2)) => ap_result((infer((ctx, e1)), infer((ctx, e2)))) end in +let is_value = fun e -> case e | TmVar(n) => false | TmLam(t, b) => true | TmAp(x, y) => false end in +let is_lam = fun e -> case e | TmLam(t, b) => true | TmVar(n) => false | TmAp(x, y) => false end in +let is_some_tm = fun m -> case m | NoTm => false | SomeTm(x) => true end in +let shift = fun p -> case p | (d, c, TmVar(n)) => (if n < c then TmVar(n) else TmVar(n + d)) | (d, c, TmLam(t, b)) => TmLam(t, shift((d, c + 1, b))) | (d, c, TmAp(x, y)) => TmAp(shift((d, c, x)), shift((d, c, y))) end in +let subst = fun p -> case p | (j, v, TmVar(n)) => (if n == j then v else TmVar(n)) | (j, v, TmLam(t, b)) => TmLam(t, subst((j + 1, shift((1, 0, v)), b))) | (j, v, TmAp(x, y)) => TmAp(subst((j, v, x)), subst((j, v, y))) end in +let step = fun e -> case e | TmVar(n) => NoTm | TmLam(t, b) => NoTm | TmAp(x, y) => (if is_value(x) then (if is_value(y) then case x | TmVar(n) => NoTm | TmLam(t, b) => SomeTm(subst((0, y, b))) | TmAp(f, a) => NoTm end else case step(y) | NoTm => NoTm | SomeTm(yp) => SomeTm(TmAp(x, yp)) end) else case step(x) | NoTm => NoTm | SomeTm(xp) => SomeTm(TmAp(xp, y)) end) end in +theorem step_ap_val1 = forall u1: Term -> forall u2: Term -> is_value(u1) == false ==> step(TmAp(u1, u2)) == (case step(u1) | NoTm => NoTm | SomeTm(xp) => SomeTm(TmAp(xp, u2)) end) proof assume is_value(u1) == false => from step(TmAp(u1, u2)) do step end; from is_value(u1) do rewrite assume end end; ? in +theorem step_lam_ap2 = forall w1: Ty -> forall q1: Term -> forall u2: Term -> is_value(u2) == false ==> step(TmAp(TmLam(w1, q1), u2)) == (case step(u2) | NoTm => NoTm | SomeTm(yp) => SomeTm(TmAp(TmLam(w1, q1), yp)) end) proof assume is_value(u2) == false => from step(TmAp(TmLam(w1, q1), u2)) do step end; from is_value(TmLam(w1, q1)) do step end; from is_value(u2) do rewrite assume end end; ? in +theorem step_beta = forall w1: Ty -> forall q1: Term -> forall u2: Term -> is_value(u2) == true ==> step(TmAp(TmLam(w1, q1), u2)) == SomeTm(subst((0, u2, q1))) proof assume is_value(u2) == true => from step(TmAp(TmLam(w1, q1), u2)) do step end; from is_value(TmLam(w1, q1)) do step end; from is_value(u2) do rewrite assume end end; ? in +theorem some_tm_is_some = forall u1: Term -> is_some_tm(SomeTm(u1)) == true proof from is_some_tm(SomeTm(u1)) do step end; from true == true do rewrite refl end end in +theorem progress = forall e0: Term -> forall t0: Ty -> infer(([], e0)) == SomeTy(t0) ==> is_value(e0) || is_some_tm(step(e0)) proof generalize t0 => induction e0 +| TmVar(m0) => forall t0 => from infer(([], TmVar(m0))) do step end; from nth_ty(([], m0)) do step end; from NoTy == SomeTy(t0) do step end; from false ==> is_value(TmVar(m0)) || is_some_tm(step(TmVar(m0))) do step end +| TmLam(w0, q0) => forall t0 => assume infer(([], TmLam(w0, q0))) == SomeTy(t0) => from is_value(TmLam(w0, q0)) do step end; from true || is_some_tm(step(TmLam(w0, q0))) do step end +| TmAp(x0, y0) => forall t0 => from infer(([], TmAp(x0, y0))) do step end; cases infer(([], x0)) +| NoTy => alias tx = case_eq => from infer(([], x0)) do rewrite tx end end; cases infer(([], y0)) +| NoTy => alias ty = case_eq => from infer(([], y0)) do rewrite ty end end; from ap_result((NoTy, NoTy)) do step end; from NoTy == SomeTy(t0) do step end; from false ==> is_value(TmAp(x0, y0)) || is_some_tm(step(TmAp(x0, y0))) do step end +| SomeTy(s0) => alias ty = case_eq => from infer(([], y0)) do rewrite ty end end; from ap_result((NoTy, SomeTy(s0))) do step end; from NoTy == SomeTy(t0) do step end; from false ==> is_value(TmAp(x0, y0)) || is_some_tm(step(TmAp(x0, y0))) do step end +end +| SomeTy(tf0) => alias tx = case_eq => from infer(([], x0)) do rewrite tx end end; cases tf0 +| TB => cases infer(([], y0)) +| NoTy => alias ty = case_eq => from infer(([], y0)) do rewrite ty end end; from ap_result((SomeTy(TB), NoTy)) do step end; from NoTy == SomeTy(t0) do step end; from false ==> is_value(TmAp(x0, y0)) || is_some_tm(step(TmAp(x0, y0))) do step end +| SomeTy(s0) => alias ty = case_eq => from infer(([], y0)) do rewrite ty end end; from ap_result((SomeTy(TB), SomeTy(s0))) do step end; from NoTy == SomeTy(t0) do step end; from false ==> is_value(TmAp(x0, y0)) || is_some_tm(step(TmAp(x0, y0))) do step end +end +| TArr(ta0, tb0) => cases infer(([], y0)) +| NoTy => alias ty = case_eq => from infer(([], y0)) do rewrite ty end end; from ap_result((SomeTy(TArr(ta0, tb0)), NoTy)) do step end; from NoTy == SomeTy(t0) do step end; from false ==> is_value(TmAp(x0, y0)) || is_some_tm(step(TmAp(x0, y0))) do step end +| SomeTy(s0) => alias ty = case_eq => from infer(([], y0)) do rewrite ty end end; from ap_result((SomeTy(TArr(ta0, tb0)), SomeTy(s0))) do step end; cases ty_eq((ta0, s0)) +| false => alias teq = case_eq => from ty_eq((ta0, s0)) do rewrite teq end end; from if false then SomeTy(tb0) else NoTy do step end; from NoTy == SomeTy(t0) do step end; from false ==> is_value(TmAp(x0, y0)) || is_some_tm(step(TmAp(x0, y0))) do step end +| true => alias teq = case_eq => from ty_eq((ta0, s0)) do rewrite teq end end; from if true then SomeTy(tb0) else NoTy do step end; assume SomeTy(tb0) == SomeTy(t0) => cases is_value(x0) +| false => from is_value(TmAp(x0, y0)) do step end; from false || is_some_tm(step(TmAp(x0, y0))) do step end; from step(TmAp(x0, y0)) do rewrite step_ap_val1 end end; cases step(x0) +| NoTm => ? +| SomeTm(u0) => alias sx = case_eq => from step(x0) do rewrite sx end end; from is_some_tm(case SomeTm(u0) | NoTm => NoTm | SomeTm(xp) => SomeTm(TmAp(xp, y0)) end) do step end +end +| true => cases x0 +| TmVar(m0) => alias hx0 = case_eq => revert is_value(x0) == true => from x0 do rewrite hx0 end end; from is_value(TmVar(m0)) == true do step end; from false == true do step end; from false ==> (is_value(TmAp(TmVar(m0), y0)) || is_some_tm(step(TmAp(TmVar(m0), y0)))) do step end +| TmLam(w0, q0) => from is_value(TmAp(TmLam(w0, q0), y0)) do step end; from false || is_some_tm(step(TmAp(TmLam(w0, q0), y0))) do step end; cases is_value(y0) +| true => from step(TmAp(TmLam(w0, q0), y0)) do rewrite step_beta end end; from is_some_tm(SomeTm(subst((0, y0, q0)))) do rewrite some_tm_is_some end end +| false => from step(TmAp(TmLam(w0, q0), y0)) do rewrite step_lam_ap2 end end; cases step(y0) +| NoTm => ? +| SomeTm(u0) => alias sy = case_eq => from step(y0) do rewrite sy end end; from is_some_tm(case SomeTm(u0) | NoTm => NoTm | SomeTm(yp) => SomeTm(TmAp(TmLam(w0, q0), yp)) end) do step end +end +end +| TmAp(f0, a0) => alias hx0 = case_eq => revert is_value(x0) == true => from x0 do rewrite hx0 end end; from is_value(TmAp(f0, a0)) == true do step end; from false == true do step end; from false ==> (is_value(TmAp(TmAp(f0, a0), y0)) || is_some_tm(step(TmAp(TmAp(f0, a0), y0)))) do step end +end +end +end +end +end +end +end in progress|prog}; + +/* Every row the walk reaches has the checker's entry, and every row with + * a goal has its state, in each theorem of a large development. */ +let test_rows_are_checked = () => { + let statics = Test_StepperView.Fixture.statics(user_src); + let cell = + Test_StepperView.Fixture.calculate( + ~is_edited=true, + statics, + Web.EvalResult.Model.init, + ); + let names = + Web.Theorems.Model.theorems(cell.theorems) + |> List.map(~f=((_, thm: Web.Theorems.Model.theorem)) => thm.name); + check(int, "the program has 5 theorems", 5, List.length(names)); + let violations = name => { + let f = Test_StepperView.Fixture.of_cell(~name, statics, cell); + Test_StepperView.Fixture.all(f) + |> List.concat_map(~f=(row: Web.StepperRows.t) => + ( + row.entry == None + ? [name ++ ": a row the checker didn't reach"] : [] + ) + @ ( + row.goal != None + && Web.StepperView.Model.find(row.key, f.theorem.stepper) == None + ? [name ++ ": a row with a goal but no state"] : [] + ) + ); + }; + check( + list(string), + "violations", + [], + List.concat_map(~f=violations, names), + ); +}; + +let tests = ( + "Evaluator.RootMissingRepro", + [ + /* Slow: this development takes minutes to check. */ + test_case( + "user STLC progress program: every row is checked", + `Slow, + test_rows_are_checked, + ), + ], +); diff --git a/test/evaluator/Test_StepSearch.re b/test/evaluator/Test_StepSearch.re new file mode 100644 index 0000000000..07f40901c3 --- /dev/null +++ b/test/evaluator/Test_StepSearch.re @@ -0,0 +1,552 @@ +open Alcotest; +open Language; +open Haz3lcore; +open Poly; + +module Fixture = Test_StepperView.Fixture; +module Picker = Web.StepperPicker; +module Search = Web.StepSearch; + +let first = Test_StepperView.first; +let body = Test_StepperView.body; +let written = Test_StepperView.written; + +/* The goal of the theorem's first row, or of its first row inside the + * first row's body. */ +let goal = (~inside=false, src) => { + let f = Fixture.mk(src); + let row = first(f.rows); + Fixture.goal(f, inside ? first(body(row)) : row); +}; + +/* `text` typed into the row's write box: elaborated in the goal's scope, + * as the box does. */ +let typed = (goal: Picker.Goal.t, text: string): Exp.t => + switch (Parser.to_zipper(~root=Exp, text)) { + | Some(z) => + Web.CodeEditable.Model.mk(Editor.Model.mk(z, ~root=Exp)) + |> Web.StepperView.Update.calculate_box( + ~settings=Test_StepperView.settings, + goal, + ) + |> Web.CodeEditable.Model.get_statics + |> (statics => statics.elaborated) + | None => Alcotest.fail("can't parse " ++ text) + }; + +let no_algebra = (_, _) => false; + +let search = (~algebra=no_algebra, goal, text) => + Search.run( + ~continue_=() => true, + ~algebra, + goal, + Search.start(goal, ~wanted=typed(goal, text)), + ); + +/* The steps found, each as written, or None if there are none. */ +let found = (s: Search.t): option(list(string)) => + switch (s.status) { + | Found(steps) => Some(List.map(~f=written, steps)) + | NotFound => None + | Searching => Alcotest.fail("still searching") + }; + +let steps = option(list(string)); + +let arithmetic = "theorem t = (1 + 1) * 2 == 4 proof ? in t"; + +let tests = ( + "StepSearch", + [ + test_case( + "a step on either operand is found", + `Quick, + () => { + let g = goal("theorem t = (1 + 2) * (3 + 4) == 21 proof ? in t"); + check( + steps, + "left", + Some(["from (1 + 2) do step end"]), + found(search(g, "3 * (3 + 4) == 21")), + ); + check( + steps, + "right", + Some(["from (3 + 4) do step end"]), + found(search(g, "(1 + 2) * 7 == 21")), + ); + }, + ), + test_case( + "a refuted theorem isn't offered as a rule, an unfinished one is", + `Quick, + () => { + let g = + goal( + "theorem refuted = 1 + 1 == 3 proof from 1 + 1 do step end; step in " + ++ "theorem unfinished = 2 * 2 == 5 proof ? in " + ++ "theorem t = (1 + 1) * (2 * 2) == 4 proof ? in t", + ); + let names = List.map(~f=fst, Search.names(g)); + check( + bool, + "refuted named", + false, + List.mem(names, "refuted", ~equal=String.equal), + ); + check( + bool, + "unfinished named", + true, + List.mem(names, "unfinished", ~equal=String.equal), + ); + check( + steps, + "refuted used", + None, + found(search(g, "3 * (2 * 2) == 4")), + ); + check( + bool, + "unfinished used", + true, + found(search(g, "(1 + 1) * 5 == 4")) != None, + ); + }, + ), + test_case("a typed negative number is the number a step gives", `Quick, () => + check( + steps, + "steps", + Some(["from 0 - 5 do step end"]), + found( + search( + goal("theorem t = 0 - 5 + 2 == 0 - 3 proof ? in t"), + "-5 + 2 == 0 - 3", + ), + ), + ) + ), + test_case( + "the steps found are written with their selectors generalized", + `Quick, + () => { + let g = goal(arithmetic); + switch (search(g, "4 == 4").status) { + | Found(steps) => + check( + list(string), + "steps", + ["from ($e + $e) do step end", "from $e * $e do step end"], + List.map(~f=written, Search.generalized(g, steps)), + ) + | Searching + | NotFound => Alcotest.fail("no steps found") + }; + }, + ), + test_case( + "at a hole with a step after it, a write keeps the hole unless that step still checks", + `Quick, + () => { + /* `from 1 + 4 do step end`, written in the hole. */ + let step = + Proof.fresh( + Picker.Terms.focus( + ~selector=Test_Evaluator_Prelude.parse_exp("1 + 4"), + ~index=0, + Proof.fresh(EvalStep), + ), + ); + let bridged = src => { + let f = Fixture.mk(src); + let row = first(f.rows); + Search.Bridge.steps( + ~algebra=no_algebra, + ~proof=f.theorem.proof, + Fixture.goal(f, row), + row, + [step], + ) + |> List.map(~f=written); + }; + check( + list(string), + "the step after still checks", + ["from 1 + 4 do step end"], + bridged("theorem t = 1 + 4 == 5 proof ?; step in t"), + ); + check( + list(string), + "it doesn't, and nothing leads back", + ["from 1 + 4 do step end", "?"], + bridged( + "theorem t = 1 + 4 == 5 proof ?; from 1 + 4 do step end in t", + ), + ); + }, + ), + test_case("the algebra check takes a call as an unknown", `Quick, () => + check( + bool, + "a part with a call is arithmetic", + true, + Search.arithmetic(Test_Evaluator_Prelude.parse_exp("0 + len(ys)")), + ) + ), + test_case( + "one eval step reaches the typed goal, written where the checker takes it", + `Quick, + () => { + let g = goal(arithmetic); + check( + steps, + "steps", + Some(["from (1 + 1) do step end"]), + found(search(g, "2 * 2 == 4")), + ); + }, + ), + test_case( + "the fewest steps reaching it, one row each", + `Quick, + () => { + let g = goal(arithmetic); + check( + steps, + "two", + Some(["from (1 + 1) do step end", "from 2 * 2 do step end"]), + found(search(g, "4 == 4")), + ); + check( + steps, + "to true", + Some([ + "from (1 + 1) do step end", + "from 2 * 2 do step end", + "step", + ]), + found(search(g, "true")), + ); + }, + ), + test_case( + "a goal no step reaches is not found, and the goal itself takes no steps", + `Quick, + () => { + let g = goal(arithmetic); + check(steps, "unreachable", None, found(search(g, "5 == 5"))); + check( + steps, + "itself", + Some([]), + found(search(g, "(1 + 1) * 2 == 4")), + ); + }, + ), + test_case( + "a fact rewrites where it applies, in either direction", + `Quick, + () => { + let g = + goal( + ~inside=true, + "theorem t = forall x -> x == 1 ==> x + 0 == 1 proof assume x == 1 => ? in t", + ); + check( + steps, + "forward", + Some(["from x do rewrite assume end end"]), + found(search(g, "1 + 0 == 1")), + ); + check( + steps, + "backward", + Some(["from 1 do rewrite <- assume end end"]), + found(search(g, "x + 0 == x")), + ); + }, + ), + test_case( + "a rule that only wraps a part, as `rewrite <- not_not` turns b into !!b, isn't tried", + `Quick, + () => + check( + steps, + "steps", + None, + found(search(goal(arithmetic), "!!((1 + 1) * 2 == 4)")), + ) + ), + test_case( + "a theorem in scope rewrites to the typed goal, whose definitions inline with binders renamed", + `Quick, + () => { + let f = + Fixture.mk( + "let rev = fun xs -> case xs | [] => [] | y :: ys => rev(ys) @ [y] end in theorem rev_app = forall (xs : [Int]) -> forall (ys : [Int]) -> rev(xs @ ys) == rev(ys) @ rev(xs) proof ? in theorem t = forall (xs : [Int]) -> forall (ys : [Int]) -> rev(xs @ ys) == rev(ys) @ rev(xs) proof ? in t", + ); + check( + steps, + "steps", + Some(["from rev(xs @ ys) do rewrite rev_app end end"]), + found( + search( + Fixture.goal(f, first(f.rows)), + "rev(ys) @ rev(xs) == rev(ys) @ rev(xs)", + ), + ), + ); + }, + ), + test_case( + "reflexivity closes an equation of equals", + `Quick, + () => { + let g = + goal( + "let f = fun x -> x in theorem t = forall (xs : [Int]) -> f(xs) == f(xs) proof ? in t", + ); + check( + steps, + "steps", + Some(["rewrite refl end"]), + found(search(g, "true")), + ); + }, + ), + test_case( + "an arithmetic part the algebra check equates is rewritten to what was typed", + `Quick, + () => { + let g = + goal("theorem t = forall (x : Int) -> x + x == 2 * x proof ? in t"); + let algebra = (a, b) => + Test_ProofMap.print_exp(a) == "x + x" + && Test_ProofMap.print_exp(b) == "2 * x"; + check( + steps, + "steps", + Some(["from x + x do algebra 2 * x end end"]), + found(search(~algebra, g, "2 * x == 2 * x")), + ); + check( + steps, + "not without it", + None, + found(search(g, "2 * x == 2 * x")), + ); + }, + ), + test_case( + "typing into a row's box starts a search, its slices find the steps, and they are written one row each", + `Quick, + () => { + let f = Fixture.mk(arithmetic); + let row = first(f.rows); + let f = + Fixture.act(f, (row.key, BoxEditor(Perform(Paste("4 == 4"))))); + let box = (f: Fixture.t) => + switch (Fixture.local(f, row).box) { + | Some(box) => box + | None => Alcotest.fail("no box") + }; + let rec slices = (n, f: Fixture.t) => + switch (box(f).search) { + | Some({status: Searching, _}) when n < 100 => + slices( + n + 1, + Fixture.act(f, (row.key, SearchSlice(box(f).generation))), + ) + | Some(search) => search + | None => Alcotest.fail("no search started") + }; + let search = slices(0, f); + check( + steps, + "found", + Some(["from (1 + 1) do step end", "from 2 * 2 do step end"]), + found(search), + ); + switch (search.status) { + | Found(found) => + switch (Picker.write_steps(row, found)) { + | Some(ProofPatch({replacement, _})) => + check( + string, + "in place of the hole", + "from (1 + 1) do step end; from 2 * 2 do step end", + written(replacement), + ) + | _ => Alcotest.fail("not a proof patch") + } + | Searching + | NotFound => () + }; + }, + ), + test_case( + "a rule named in full lists each of its uses, in each direction, with the goal it gives", + `Quick, + () => { + let g = + goal( + ~inside=true, + "theorem t = forall x -> x == 1 ==> x + 0 == 1 proof assume x == 1 => ? in t", + ); + let suggestions = + Search.Suggestions.run( + ~continue_=() => true, + g, + Search.Suggestions.start(~rule=Some("assume"), ~at=None), + ); + check( + list(pair(string, string)), + "uses", + [ + ("from x do rewrite assume end end", "1 + 0 == 1"), + ("from 1 do rewrite <- assume end end", "x + 0 == x"), + ], + List.map( + ~f= + (use: Search.Suggestions.suggestion) => + (written(use.step), Test_ProofMap.print_exp(use.result)), + suggestions.found, + ), + ); + check( + bool, + "listed", + true, + List.length( + Search.items(g, ~typed_name=Some("assume"), Some(suggestions)), + ) + == 2, + ); + }, + ), + test_case( + "typing the start of a name lists the names in scope it completes to", + `Quick, + () => { + let g = + goal( + ~inside=true, + "theorem t = forall x -> x == 1 ==> x + 0 == 1 proof assume x == 1 => ? in t", + ); + let completions = start => + Search.items(g, ~typed_name=Some(start), None) + |> List.filter_map(~f=(item: Search.item) => + switch (item) { + | Complete(name) => Some(name) + | Use(_) => None + } + ); + check(list(string), "ass", ["assume"], completions("ass")); + check( + list(string), + "the axioms too", + ["nonzero_of_neg", "nonzero_of_pos", "nonzero_mul", "not_not"], + completions("no"), + ); + }, + ), + test_case( + "with part of the goal selected, the box's text is that part's replacement, and the uses listed are inside it", + `Quick, + () => { + let f = Fixture.mk("theorem t = 2 * (1 + 1) == 4 proof ? in t"); + let row = first(f.rows); + let part = + Test_StepperView.Picking.node(Fixture.goal(f, row), "(1 + 1)"); + let f = + Fixture.act( + f, + (row.key, Goal(Select(Term(Id(Exp.rep_id(part), Right))))), + ); + let f = Fixture.act(f, (row.key, BoxEditor(Perform(Paste("2"))))); + let box = (f: Fixture.t) => + switch (Fixture.local(f, row).box) { + | Some(box) => box + | None => Alcotest.fail("no box") + }; + let rec slices = (n, f: Fixture.t) => + Web.StepperView.Model.running(box(f)) && n < 100 + ? slices( + n + 1, + Fixture.act(f, (row.key, SearchSlice(box(f).generation))), + ) + : box(f); + let box = slices(0, f); + check( + steps, + "found", + Some(["from (1 + 1) do step end"]), + Option.bind(box.search, ~f=s => found(s)), + ); + check( + bool, + "the uses are looked for inside the part", + true, + Option.bind(box.suggestions, ~f=(s: Search.Suggestions.t) => s.at) + != None, + ); + }, + ), + test_case( + "run in slices, the search finds what it finds in one go", + `Quick, + () => { + let g = goal(arithmetic); + let wanted = typed(g, "true"); + /* One candidate per slice. */ + let rec slices = (n, s: Search.t) => + switch (s.status) { + | Searching => + let budget = ref(1); + slices( + n + 1, + Search.run( + ~continue_= + () => { + budget := budget^ - 1; + budget^ >= 0; + }, + ~algebra=no_algebra, + g, + s, + ), + ); + | Found(_) + | NotFound => (n, s) + }; + let (n, s) = slices(0, Search.start(g, ~wanted)); + check(bool, "several slices", true, n > 1); + check(steps, "steps", found(search(g, "true")), found(s)); + }, + ), + test_case( + "typing nat_ completes to the Nat rules", + `Quick, + () => { + let g = + goal( + "use Nat in theorem t = forall (m : Nat) -> (m + 1 == 0) == false proof ? in t", + ); + check( + list(string), + "completions", + ["nat_add_sub", "nat_succ_ne_zero"], + Search.items(g, ~typed_name=Some("nat_"), None) + |> List.filter_map(~f=(item: Search.item) => + switch (item) { + | Complete(name) => Some(name) + | Use(_) => None + } + ), + ); + }, + ), + ], +); diff --git a/test/evaluator/Test_StepperBase.re b/test/evaluator/Test_StepperBase.re deleted file mode 100644 index 693db4f6da..0000000000 --- a/test/evaluator/Test_StepperBase.re +++ /dev/null @@ -1,664 +0,0 @@ -open Alcotest; -open Language; -open Test_Evaluator_Prelude; -open Util; -open Haz3lcore; - -// Import StepperBase types from web module -module StepperBase = Web.StepperBase; - -// Helper constructors for step_kind_model -module StepKindHelpers = { - // Create a SingleStep that will automatically take the next available step - let mk_auto_single_step = (exp: Exp.t): StepperBase.step_kind_model => { - let status = - EvaluatorStep.get_status( - ~settings=CoreSettings.on, - exp, - Environment.empty, - ); - switch (status) { - | AutoStep(step) - | AvailableSteps([step, ..._]) => - StepperBase.SingleStep({ - persistent_evalobj: EvaluatorStep.persist(step), - evalobj: Calc.Pending, - next_exp: Calc.Pending, - }) - | AvailableSteps([]) => failwith("No step available for expression") - }; - }; - - // Create an AxiomStep at a specific subexpression - let mk_axiom_step = - ( - ~name="reflexivity", - ~at_idx=0, - ~direction=Direction.Right, - ~equality="Reflexive(==)", - at_exp, - ) // Required parameter at the end - : StepperBase.step_kind_model => { - StepperBase.AxiomStep({ - name, - at_idx, - at_exp, - direction, - equality, - next_exp: Calc.Pending, - }); - }; - - // Create a MissingStep (for testing validation) - let mk_missing_step = (): StepperBase.step_kind_model => - StepperBase.MissingStep(Web.MissingStep.Model.init); - - // Create an InductionStep with a scrutinee expression - let mk_induction_step = - (~exp: option(Exp.t)=?, ()): StepperBase.step_kind_model => - StepperBase.InductionStep(Web.InductionStep.init(~exp?, ())); -}; - -// Helper to create a minimal step model for testing -let mk_test_step = - (~step_kind: StepperBase.step_kind_model, ~next_step=None, ()) - : StepperBase.step_model => { - expr: Calc.Pending, - editor: Calc.Pending, - step_kind, - next_step, - hidden: Calc.Pending, - proof_validity: Calc.Pending, - editor_info_map: Calc.Pending, -}; - -// Helper constructors for InductionCase -module InductionCaseHelpers = { - let mk_pattern_editor = (pattern_str: string): Web.CodeWithStatics.Model.t => { - let pattern_exp = parse_exp(pattern_str); - let editor = - Editor.Model.mk( - ~root=Exp, - Zipper.unzip( - ExpToSegment.exp_to_segment( - ~settings=ExpToSegment.Settings.editable(~inline=true), - pattern_exp, - ), - ), - ); - Web.CodeWithStatics.Model.mk(editor); - }; - - // Create an InductionCase from a pattern string - let mk_case = - ( - ~pattern_str: string, - ~inner_exp: option(Exp.t)=?, - ~last_exp: option(Exp.t)=?, - ~step: option(StepperBase.step_model)=?, - (), - ) - : Web.InductionCase.model'(StepperBase.step_model) => { - { - pattern: mk_pattern_editor(pattern_str), - elab_pattern: Calc.Pending, - inner_exp: - inner_exp - |> Option.map(~f=exp => Calc.Calculated(exp)) - |> Option.value(~default=Calc.Pending), - step: step |> Option.value(~default=StepperBase.init_step), - last_exp: - last_exp - |> Option.map(~f=exp => Calc.Calculated(exp)) - |> Option.value(~default=Calc.Pending), - inner_ctx: Calc.Pending, - hypotheses: Calc.Pending, - constraint_: Calc.Pending, - }; - }; - - // Build a step chain by linking step_kinds into next_step fields - let rec build_step_chain = - (step_kinds: list(StepperBase.step_kind_model)) - : option(StepperBase.step_model) => - switch (step_kinds) { - | [] => None - | [kind] => Some(mk_test_step(~step_kind=kind, ())) - | [kind, ...rest] => - Some( - mk_test_step(~step_kind=kind, ~next_step=build_step_chain(rest), ()), - ) - }; - - // Create an induction case from a pattern, goal, and list of step_kinds - let mk_case_with_steps = - ( - ~pattern_str: string, - ~goal_str: string, - step_kinds: list(StepperBase.step_kind_model), - ) - : Web.InductionCase.model'(StepperBase.step_model) => { - let goal_exp = parse_exp(goal_str); - let step = - switch (build_step_chain(step_kinds)) { - | Some(s) => s - | None => StepperBase.init_step - }; - mk_case(~pattern_str, ~inner_exp=goal_exp, ~step, ()); - }; - - // Create an InductionStep with scrutinee and cases - let mk_induction_with_cases = - ( - ~scrut_str: string, - ~cases: list(Web.InductionCase.model'(StepperBase.step_model)), - ) - : StepperBase.step_kind_model => { - // Create a complete InductionStep model directly by matching the structure - // Since we can't easily access the base fields, we create everything from scratch - let scrut_editor = mk_pattern_editor(scrut_str); - - let ind_model: Web.InductionStep.model'(StepperBase.step_model) = { - scrut: scrut_editor, - cases, - elab_scrut_raw: Calc.Pending, - elab_scrut_sub: Calc.Pending, - scrut_ty: Calc.Pending, - scrut_co_ctx: Calc.Pending, - result: Calc.Pending, - join_exp: Calc.Pending, - is_exhaustive: Calc.Pending, - validity: Calc.Pending, - }; - - (StepperBase.InductionStep(ind_model): StepperBase.step_kind_model); - }; -}; - -// Helper to run calculate with minimal dependencies -let test_calculate = - ( - ~exp: Exp.t, - ~ctx=Builtins.ctx_init(Some(Int)), - ~ana=IdTagged.FreshGrammar.Typ.int(), // Use a fresh type for ana - step: StepperBase.step_model, - ) - : (StepperBase.step_model, Calc.t(Exp.t), Calc.t(option(bool))) => { - let settings = Calc.NewValue(CoreSettings.on); - let exp_calc = Calc.NewValue(exp); - let ctx_calc = - Calc.NewValue(SemanticCtx.of_ctx_and_env(ctx, Builtins.env_init)); - let ana_calc = Calc.NewValue(ana); - - StepperBase.Stepper.calculate( - ~settings, - ~exp=exp_calc, - ~ctx=ctx_calc, - ~ana=ana_calc, - step, - ); -}; - -// Run a single step and return the result expression -let run_single_step = (~exp, ~step_kind) => { - let step = mk_test_step(~step_kind, ()); - let (_, final_exp, _) = test_calculate(~exp, step); - Calc.get_value(final_exp); -}; - -// Run a step chain and return the final result -let run_step_chain = - ( - ~initial_exp, - ~step_kinds: list(StepperBase.step_kind_model), - ~ctx=?, - (), - ) => { - switch (InductionCaseHelpers.build_step_chain(step_kinds)) { - | Some(root_step) => - let (model, final_exp, validity) = - test_calculate(~exp=initial_exp, ~ctx?, root_step); - (model, Calc.get_value(final_exp), Calc.get_value(validity)); - | None => failwith("Empty step chain") - }; -}; - -let tests = ( - "StepperBase", - [ - // ============================================================ - // Basic calculation tests - // ============================================================ - test_case( - "calculate empty missing step", - `Quick, - () => { - let exp = parse_exp("1 + 2"); - let step = - mk_test_step(~step_kind=StepKindHelpers.mk_missing_step(), ()); - let (_, final_exp, _) = test_calculate(~exp, step); - check( - dhexp_typ, - "expression unchanged", - exp, - Calc.get_value(final_exp), - ); - }, - ), - // ============================================================ - // SingleStep tests - // ============================================================ - test_case( - "single step: simple arithmetic", - `Quick, - () => { - let exp = parse_exp("1 + 2"); - let result = - run_single_step( - ~exp, - ~step_kind=StepKindHelpers.mk_auto_single_step(exp), - ); - check(dhexp_typ, "1 + 2 -> 3", parse_exp("3"), result); - }, - ), - test_case( - "single step: beta reduction", - `Quick, - () => { - let exp = - Exp.fresh( - Ap( - Forward, - Exp.fresh( - Fun( - Pat.fresh(Var("x")), - Exp.fresh( - BinOp( - Int(Plus), - Exp.fresh(Var("x")), - Exp.fresh(Atom(Int(Bigint.of_int(1)))), - ), - ), - None, - None, - ), - ), - Exp.fresh(Atom(Int(Bigint.of_int(5)))), - ), - ); - let elab = elaborate(exp); - let result = - run_single_step( - ~exp=elab, - ~step_kind=StepKindHelpers.mk_auto_single_step(elab), - ); - // After beta reduction, should have 5 + 1 - let expected_pattern = parse_exp("5 + 1"); - check( - dhexp_typ, - "(fun x -> x + 1)(5) reduces", - expected_pattern, - result, - ); - }, - ), - test_case( - "single step: let binding", - `Quick, - () => { - let exp = parse_exp("let x = 5 in x + 1"); - let elab = elaborate(exp); - let result = - run_single_step( - ~exp=elab, - ~step_kind=StepKindHelpers.mk_auto_single_step(elab), - ); - // After one step, should substitute x - let expected = parse_exp("5 + 1"); - check(dhexp_typ, "let x = 5 in x + 1 -> 5 + 1", expected, result); - }, - ), - // ============================================================ - // Validity tests - // ============================================================ - test_case( - "validity: true expression", - `Quick, - () => { - let exp = parse_exp("true"); - let step = - mk_test_step(~step_kind=StepKindHelpers.mk_missing_step(), ()); - let (_, _, validity) = test_calculate(~exp, step); - check( - option(bool), - "true is valid", - Some(true), - Calc.get_value(validity), - ); - }, - ), - test_case( - "validity: false expression", - `Quick, - () => { - let exp = parse_exp("false"); - let step = - mk_test_step(~step_kind=StepKindHelpers.mk_missing_step(), ()); - let (_, _, validity) = test_calculate(~exp, step); - check( - option(bool), - "false is refutable", - Some(false), - Calc.get_value(validity), - ); - }, - ), - test_case( - "validity: unknown expression", - `Quick, - () => { - let exp = parse_exp("42"); - let step = - mk_test_step(~step_kind=StepKindHelpers.mk_missing_step(), ()); - let (_, _, validity) = test_calculate(~exp, step); - check( - option(bool), - "42 is not a boolean", - None, - Calc.get_value(validity), - ); - }, - ), - test_case( - "validity: single step to true", - `Quick, - () => { - let exp = parse_exp("1 == 1"); - let elab = elaborate(exp); - let step_kind = StepKindHelpers.mk_auto_single_step(elab); - let step = mk_test_step(~step_kind, ()); - let (_, final_exp, validity) = test_calculate(~exp=elab, step); - // After evaluation, 1 == 1 should become true - check( - dhexp_typ, - "1 == 1 evaluates to true", - parse_exp("true"), - Calc.get_value(final_exp), - ); - // But validity on a SingleStep checks the *next* expression - // So we need to check the model's proof_validity field - check( - option(bool), - "validity is Some(true)", - Some(true), - Calc.get_value(validity), - ); - }, - ), - // ============================================================ - // Step Chain tests - // ============================================================ - test_case( - "step chain: two arithmetic steps", - `Quick, - () => { - let exp = parse_exp("1 + 2 + 3"); - let elab = elaborate(exp); - // First step: 1 + 2 -> 3 - // Second step: 3 + 3 -> 6 - let step1 = StepKindHelpers.mk_auto_single_step(elab); - let after_first = run_single_step(~exp=elab, ~step_kind=step1); - let step2 = StepKindHelpers.mk_auto_single_step(after_first); - - let (_, final_exp, _) = - run_step_chain(~initial_exp=elab, ~step_kinds=[step1, step2], ()); - check(dhexp_typ, "1 + 2 + 3 -> 6", parse_exp("6"), final_exp); - }, - ), - test_case( - "step chain: validity propagation true", - `Quick, - () => { - // Chain that ends in true should have validity Some(true) - // Use a simpler expression that requires fewer steps - let exp = parse_exp("1 == 1"); - let elab = elaborate(exp); - - // Take one step: 1 == 1 -> true - let step1 = StepKindHelpers.mk_auto_single_step(elab); - - let (_, final_exp, validity) = - run_step_chain(~initial_exp=elab, ~step_kinds=[step1], ()); - - check(dhexp_typ, "reduces to true", parse_exp("true"), final_exp); - check(option(bool), "chain validity is true", Some(true), validity); - }, - ), - // ============================================================ - // Equality tests - // ============================================================ - test_case( - "equality: expression with same structure", - `Quick, - () => { - // Test that two expressions with same structure but different IDs - // are considered equal for validity purposes - let exp1 = parse_exp("true"); - let exp2 = parse_exp("true"); - // They should be equal according to DHExp.fast_equal - check( - bool, - "structurally equal", - true, - DHExp.fast_equal(exp1, exp2), - ); - }, - ), - // ============================================================ - // InductionStep tests - // ============================================================ - test_case( - "induction step: create with scrutinee", - `Quick, - () => { - // Test that we can create an InductionStep with a scrutinee - let scrut_exp = parse_exp("n"); - let step_kind = StepKindHelpers.mk_induction_step(~exp=scrut_exp, ()); - let step = mk_test_step(~step_kind, ()); - - // Just verify it calculates without crashing - let (_, _, _) = test_calculate(~exp=parse_exp("true"), step); - // If we get here, the test passed - check(bool, "induction step created", true, true); - }, - ), - test_case( - "induction step: exhaustiveness check empty", - `Quick, - () => { - // An InductionStep with no cases should not be exhaustive - let scrut_exp = parse_exp("true"); - let elab = elaborate(scrut_exp); - let step_kind = StepKindHelpers.mk_induction_step(~exp=elab, ()); - let step = mk_test_step(~step_kind, ()); - - let (model, _, _) = test_calculate(~exp=parse_exp("true"), step); - - // Extract the InductionStep from the model to check exhaustiveness - switch (model.step_kind) { - | StepperBase.InductionStep(ind_model) => - let is_exhaustive = - ind_model.is_exhaustive - |> Calc.get_saved_exc(~print="is_exhaustive not calculated"); - check(bool, "empty induction not exhaustive", false, is_exhaustive); - | _ => failwith("Expected InductionStep") - }; - }, - ), - test_case( - "induction step: validity with no cases on concrete type", - `Quick, - () => { - // An InductionStep with no cases on a concrete type (like Int) should be None (not valid) - // because it's not exhaustive - let scrut_exp = parse_exp("42"); // Int type - concrete - let elab = elaborate(scrut_exp); - let step_kind = StepKindHelpers.mk_induction_step(~exp=elab, ()); - let step = mk_test_step(~step_kind, ()); - - let (model, _, _) = test_calculate(~exp=parse_exp("true"), step); - - // Check that validity is None - concrete type with no cases is not valid - switch (model.step_kind) { - | StepperBase.InductionStep(ind_model) => - let ind_validity = - ind_model.validity - |> Calc.get_saved_exc(~print="validity not calculated"); - check( - option(bool), - "no cases on concrete type is not valid", - None, - ind_validity, - ); - | _ => failwith("Expected InductionStep") - }; - }, - ), - test_case( - "induction step: calculate result expression", - `Quick, - () => { - // An InductionStep should calculate a result expression (join_exp) - let scrut_exp = parse_exp("n"); - let step_kind = StepKindHelpers.mk_induction_step(~exp=scrut_exp, ()); - let step = mk_test_step(~step_kind, ()); - - let (model, _, _) = test_calculate(~exp=parse_exp("true"), step); - - // Check that result and join_exp are calculated - switch (model.step_kind) { - | StepperBase.InductionStep(ind_model) => - let result = ind_model.result |> Calc.get_saved_opt; - let join_exp = ind_model.join_exp |> Calc.get_saved_opt; - // Both should be calculated (even if the result might be an error) - check(bool, "result is calculated", true, Option.is_some(result)); - check( - bool, - "join_exp is calculated", - true, - Option.is_some(join_exp), - ); - | _ => failwith("Expected InductionStep") - }; - }, - ), - // Complete proof of xs == xs by induction with proof steps - test_case( - "induction step: complete proof xs == xs", - `Quick, - () => { - // Build induction proof: for all xs, xs == xs - // The inductive case generates an inductive hypothesis "ih: tl == tl" - // by substituting xs->tl in the goal "xs == xs". - // Base case: [] == [] (by reflexivity) - // Inductive case: hd::tl == hd::tl (using reflexivity, with IH available) - // Note: The IH exists and could be used in a more complex proof - let step = - mk_test_step( - ~step_kind= - InductionCaseHelpers.mk_induction_with_cases( - ~scrut_str="xs", - ~cases=[ - InductionCaseHelpers.mk_case_with_steps( - ~pattern_str="[]", - ~goal_str="[] == []", - [ - StepKindHelpers.mk_axiom_step( - ~name="Reflexive(==)", - ~equality="Reflexive(==)", - parse_exp("[] == []"), - ), - ], - ), - InductionCaseHelpers.mk_case_with_steps( - ~pattern_str="hd::tl", - ~goal_str="hd::tl == hd::tl", - [ - StepKindHelpers.mk_axiom_step( - ~name="ih", - ~equality="ih", - parse_exp("tl"), - ), - StepKindHelpers.mk_axiom_step( - ~name="Reflexive(==)", - ~equality="Reflexive(==)", - parse_exp("hd::tl == hd::tl"), - ), - ], - ), - ], - ), - (), - ); - - // Run calculate on the entire proof structure - // Need to add xs to context with List type for IH generation to work - let xs_entry: Ctx.entry = - VarEntry({ - name: "xs", - id: Id.invalid, - typ: List(Atom(Int) |> Typ.temp) |> Typ.temp, - custom_statics: None, - }); - let ctx_with_xs = - Ctx.extend(Builtins.ctx_init(Some(Int)), xs_entry); - let (model, _, _) = - test_calculate(~exp=parse_exp("xs == xs"), ~ctx=ctx_with_xs, step); - - // Verify the proof - switch (model.step_kind) { - | InductionStep({cases, is_exhaustive, validity, _}) => - check(int, "should have 2 cases", 2, List.length(cases)); - check( - bool, - "should be exhaustive", - true, - is_exhaustive - |> Calc.get_saved_opt - |> Option.value(~default=false), - ); - - // Verify inductive hypothesis IS generated - let inductive_case = List.nth_exn(cases, 1); - let hypotheses = - inductive_case.Web.InductionCase.hypotheses - |> Calc.get_saved_opt - |> Option.value(~default=[]); - - check( - int, - "inductive case should have 2 hypotheses (case_eq and ih)", - 2, - List.length(hypotheses), - ); - - let has_ih = - List.exists( - ~f=((binding, _)) => String.equal(binding.Binding.name, "ih"), - hypotheses, - ); - check(bool, "should have 'ih' hypothesis", true, has_ih); - - // Proof should be valid with reflexivity steps - check( - option(option(bool)), - "proof should be valid", - Some(Some(true)), - validity |> Calc.get_saved_opt, - ); - | _ => Alcotest.fail("Expected InductionStep") - }; - }, - ), - ], -); diff --git a/test/evaluator/Test_StepperView.re b/test/evaluator/Test_StepperView.re new file mode 100644 index 0000000000..be471898f6 --- /dev/null +++ b/test/evaluator/Test_StepperView.re @@ -0,0 +1,3524 @@ +open Alcotest; +open Language; +open Util; +open Haz3lcore; +open Poly; + +module Rows = Web.StepperRows; +module Picker = Web.StepperPicker; +module Stepper = Web.StepperView; + +let parse_exp = Test_Evaluator_Prelude.parse_exp; +let print = Test_ProofMap.print_exp; + +let settings = CoreSettings.on; + +/* A cell evaluated and checked as the editor does it. */ +module Fixture = { + type t = { + statics: CachedStatics.t, + cell: Web.EvalResult.Model.t, + id: Id.t, + theorem: Web.Theorems.Model.theorem, + rows: list(Rows.t), + }; + + let statics_of_term = (term: Exp.t): CachedStatics.t => + CachedStatics.init_from_term(~settings, ~is_dynamic_term=false, term); + + let statics = (src: string): CachedStatics.t => + statics_of_term(parse_exp(src)); + + /* Evaluates on the main thread, or, with `pending`, sends the request to + * a worker that never answers. */ + let calculate = (~pending=false, ~is_edited, statics, cell) => + Web.EvalResult.Update.calculate( + ~settings, + ~queue_worker=pending ? Some(_ => ()) : None, + ~is_edited, + statics, + cell, + ); + + let of_cell = (~name, statics, cell: Web.EvalResult.Model.t): t => { + let theorems = cell.theorems; + switch ( + Web.Theorems.Model.theorems(theorems) + |> List.find(~f=((_, thm: Web.Theorems.Model.theorem)) => + thm.name == name + ) + ) { + | Some((id, theorem)) => { + statics, + cell, + id, + theorem, + rows: Rows.of_theorem(~proof_map=theorems.proof_map, theorem.proof), + } + | None => Alcotest.fail("no theorem " ++ name) + }; + }; + + let mk = (~name="t", src: string): t => { + let statics = statics(src); + of_cell( + ~name, + statics, + calculate(~is_edited=true, statics, Web.EvalResult.Model.init), + ); + }; + + /* Sends a stepper action through the cell, and recalculates, as the + * page does after an action. */ + let act = (f: t, action: Stepper.Update.t): t => { + let updated = + Web.EvalResult.Update.update( + ~settings=Web.Settings.Model.init, + TheoremsAction(TheoremUpdate(f.id, action)), + f.cell, + ); + of_cell( + ~name=f.theorem.name, + f.statics, + calculate(~is_edited=false, f.statics, updated.model), + ); + }; + + let all = (f: t) => Rows.all(f.rows); + + let local = (f: t, row: Rows.t): Stepper.Model.local => + switch (Stepper.Model.find(row.key, f.theorem.stepper)) { + | Some(local) => local + | None => Alcotest.fail("the row has no state") + }; + + let goal = (f: t, row: Rows.t): Picker.Goal.t => local(f, row).goal; +}; + +let goal = (row: Rows.t): string => + switch (row.goal) { + | Some(g) => print(g) + | None => Alcotest.fail("the row has no goal") + }; + +let kind = (row: Rows.t): string => + switch (row.kind) { + | Hole => "hole" + | End => "end" + | Step(_) => Web.StepperView.View.justification(row.step) + }; + +let kinds = (rows: list(Rows.t)) => List.map(~f=kind, rows); + +let body = (row: Rows.t): list(Rows.t) => + switch (row.kind) { + | Step(Body(rows)) => rows + | _ => Alcotest.fail("not a form with a body: " ++ kind(row)) + }; + +let premises = (row: Rows.t): (list(Rows.t), list(Rows.t)) => + switch (row.kind) { + | Step(Premises({sub, body})) => (sub, body) + | _ => Alcotest.fail("not a have: " ++ kind(row)) + }; + +let cases = (row: Rows.t): list(list(Rows.t)) => + switch (row.kind) { + | Step(Cases(cases)) => List.map(~f=snd, cases) + | _ => Alcotest.fail("not an induction: " ++ kind(row)) + }; + +let first = (rows: list(Rows.t)): Rows.t => + switch (rows) { + | [row, ..._] => row + | [] => Alcotest.fail("no rows") + }; + +let last = (rows: list(Rows.t)): Rows.t => + switch (ListUtil.last_opt(rows)) { + | Some(row) => row + | None => Alcotest.fail("no rows") + }; + +/* The facts in scope at a row, by name. */ +let facts = (row: Rows.t): list((string, string)) => + switch (Rows.ctx(row)) { + | Some(ctx) => + SemanticCtx.facts(ctx) + |> List.map(~f=((name, _, e)) => (name, print(e))) + | None => Alcotest.fail("the row has no scope") + }; + +/* The offered eval steps' displayed nodes, printed. */ +let offered = (goal: Picker.Goal.t): list(string) => + Picker.Goal.step_ids(goal) + |> List.filter_map(~f=id => Exp.find_by_id(id, goal.written)) + |> List.map(~f=print); + +let written = (p: Proof.t): string => + Proof(p) + |> ExpToSegment.any_to_segment( + ~settings=ExpToSegment.Settings.editable(~inline=true), + ) + |> Printer.of_segment(~holes="?", ~refractors=[]); + +/* Every tile id in a segment, children and folded projector interiors + * included. A repeated id makes `Highlight.of_tile` raise a shard + * mismatch. */ +let rec segment_tile_ids = (seg: Segment.t): list(Id.t) => + List.concat_map( + ~f= + (p: Piece.t) => + switch (p) { + | Tile(t) => [ + Piece.id(p), + ...segment_tile_ids(List.concat(t.children)), + ] + | Projector(pr) => segment_tile_ids([pr.syntax]) + | Grout(_) + | Secondary(_) => [] + }, + seg, + ); + +let duplicated = (ids: list(Id.t)): list(Id.t) => { + let seen = Stdlib.Hashtbl.create(64); + List.filter( + ~f= + id => + switch (Stdlib.Hashtbl.find_opt(seen, id)) { + | Some () => true + | None => + Stdlib.Hashtbl.add(seen, id, ()); + false; + }, + ids, + ); +}; + +/* Which rows a proof becomes. */ +module Walk = { + let tests = [ + test_case( + "a hole proof is one hole row", + `Quick, + () => { + let f = Fixture.mk("theorem t = 1 + 2 == 3 proof ? in t"); + check(list(string), "rows", ["hole"], kinds(f.rows)); + check( + string, + "its goal is the statement", + "1 + 2 == 3", + goal(first(f.rows)), + ); + }, + ), + test_case( + "a chain ending in a step gets an end row with the step's outgoing goal", + `Quick, + () => { + let f = + Fixture.mk( + "theorem t = 1 + 4 == 5 proof from 1 + 4 do step end in t", + ); + check(list(string), "rows", ["step", "end"], kinds(f.rows)); + let (step, end_) = (first(f.rows), last(f.rows)); + check( + bool, + "the end row is keyed by the step, on the outgoing side", + true, + end_.key == (Proof.rep_id(step.step), Outgoing), + ); + check(string, "its goal", "5 == 5", goal(end_)); + check( + list(string), + "it offers the next redex", + ["5 == 5"], + offered(Fixture.goal(f, end_)), + ); + }, + ), + test_case( + "a chain ending in a hole gets no end row", + `Quick, + () => { + let f = + Fixture.mk( + "theorem t = 1 + 4 == 5 proof from 1 + 4 do step end; ? in t", + ); + check(list(string), "rows", ["step", "hole"], kinds(f.rows)); + check(string, "the hole's goal", "5 == 5", goal(last(f.rows))); + }, + ), + test_case( + "a hole mid-chain passes its goal on", + `Quick, + () => { + let f = + Fixture.mk( + "theorem t = 1 + 4 == 5 proof ?; from 1 + 4 do step end in t", + ); + check( + list(string), + "rows", + ["hole", "step", "end"], + kinds(f.rows), + ); + check( + string, + "the step's goal", + "1 + 4 == 5", + goal(List.nth_exn(f.rows, 1)), + ); + }, + ), + test_case( + "a step inserted before another heads the chain before the reparse", + `Quick, + () => { + let step = s => Proof.fresh(AlgebriteStep(parse_exp(s))); + let (a, b, c) = (step("1"), step("2"), step("3")); + let (head, tail) = + Rows.split(Proof.fresh(Seq(Proof.fresh(Seq(a, b)), c))); + check( + bool, + "the head is the inserted step", + true, + phys_equal(head, a), + ); + switch (tail) { + | Some({term: Seq(b', c'), _}) => + check( + bool, + "then the old chain", + true, + phys_equal(b', b) && phys_equal(c', c), + ) + | _ => Alcotest.fail("the tail is not the rest of the chain") + }; + }, + ), + test_case( + "an axiom row is justified by the cited equality", + `Quick, + () => { + let f = + Fixture.mk( + "theorem t = 1 == 1 proof from 1 == 1 do rewrite refl end end in t", + ); + check(list(string), "rows", ["refl", "end"], kinds(f.rows)); + check(string, "it proves the goal", "true", goal(last(f.rows))); + }, + ), + test_case( + "a cases row nests each case's rows", + `Quick, + () => { + let f = + Fixture.mk( + "theorem t = forall (b : Bool) -> b || false == b proof cases b | true => ? | false => ? end in t", + ); + let cases = cases(first(f.rows)); + check(int, "two cases", 2, List.length(cases)); + check( + list(string), + "each case's goal has its pattern for the scrutinee", + ["true || false == true", "false || false == false"], + List.map(~f=rows => goal(first(rows)), cases), + ); + check( + bool, + "each case's scope has its case equation", + true, + List.for_all( + ~f= + rows => + List.Assoc.mem( + facts(first(rows)), + "case_eq", + ~equal=String.equal, + ), + cases, + ), + ); + }, + ), + test_case( + "an induction case's scope has its inductive hypotheses and no case equation", + `Quick, + () => { + let f = + Fixture.mk( + "theorem t = forall (xs : [Int]) -> xs == xs proof induction xs | [] => ? | y :: rest => ? end in t", + ); + switch (cases(first(f.rows))) { + | [nil, cons] => + check( + list(string), + "the cons case's new facts", + ["ih_rest"], + List.map(~f=fst, facts(first(cons))) + |> List.filter(~f=name => + ! + List.Assoc.mem( + facts(first(nil)), + name, + ~equal=String.equal, + ) + ), + ); + check( + bool, + "no case has a case equation", + false, + List.Assoc.mem( + facts(first(nil)), + "case_eq", + ~equal=String.equal, + ) + || List.Assoc.mem( + facts(first(cons)), + "case_eq", + ~equal=String.equal, + ), + ); + | _ => Alcotest.fail("expected two cases") + }; + }, + ), + test_case( + "a step that doesn't apply is broken, and offers its repairs", + `Quick, + () => { + let f = + Fixture.mk( + "theorem t = forall x: Int -> x == 1 ==> 1 + 1 == 2 proof assume x == 1 => from 1 do rewrite assume end end in t", + ); + let row = first(body(first(f.rows))); + switch (Rows.Status.of_row(row)) { + | Broken(RuleDoesNotApply(_)) => () + | status => + Alcotest.fail( + "status: " + ++ ( + Rows.Status.broken_mark(status) + |> Option.value_map(~default="not broken", ~f=ProofMark.show) + ), + ) + }; + let flips = (f: Fixture.t, row: Rows.t) => + Picker.Patches.flip_direction( + ~info_map=f.statics.info_map, + ~proof_map=f.cell.theorems.proof_map, + row.step, + ) + != None; + check(bool, "it can be flipped", true, flips(f, row)); + let f = + Fixture.mk( + "theorem t = 1 + 4 == 5 proof from 1 + 4 == 5 do rewrite refl end end in t", + ); + check( + bool, + "reflexivity, the same both ways, can't", + false, + flips(f, first(f.rows)), + ); + }, + ), + test_case( + "an induction offers another case only while its cases don't cover its scrutinee", + `Quick, + () => { + let adds_case = src => { + let f = Fixture.mk(src); + let row = first(f.rows); + Picker.Patches.add_case( + row.step, + ~marks= + Option.value_map(row.entry, ~default=[], ~f=(e: ProofMap.entry) => + e.marks + ), + ) + != None; + }; + check( + bool, + "one case of two", + true, + adds_case( + "theorem t = forall b: Bool -> b || !b proof induction b | true => ? end in t", + ), + ); + check( + bool, + "both", + false, + adds_case( + "theorem t = forall b: Bool -> b || !b proof induction b | true => ? | false => ? end in t", + ), + ); + }, + ), + ]; +}; + +/* A form's body, and a have's premises, are chains of their own, with + * the goal and scope the checker gave them. */ +module Scopes = { + let assume_src = {|theorem t = forall x -> x == 1 ==> x == 1 proof assume x == 1 => from x do rewrite assume end end; from 1 == 1 do rewrite refl end end in t|}; + let have_src = {|theorem t = forall x -> x == 1 proof have 1 == 1 proof ? => ? in t|}; + + let tests = [ + test_case( + "assume: the body renders as nested rows", + `Quick, + () => { + let f = Fixture.mk(assume_src); + check( + list(string), + "outer rows", + ["assume", "end"], + kinds(f.rows), + ); + check( + list(string), + "body rows", + ["assume", "refl", "end"], + kinds(body(first(f.rows))), + ); + }, + ), + test_case( + "assume: the body's scope has the `assume` hypothesis", + `Quick, + () => { + let f = Fixture.mk(assume_src); + check( + option(string), + "the hypothesis", + Some("x == 1"), + List.Assoc.find( + facts(first(body(first(f.rows)))), + "assume", + ~equal=String.equal, + ), + ); + check( + bool, + "and the assume itself is checked without it", + false, + List.Assoc.mem( + facts(first(f.rows)), + "assume", + ~equal=String.equal, + ), + ); + }, + ), + test_case( + "assume: implication intro strips the antecedent from the body's goal", + `Quick, + () => { + let f = + Fixture.mk( + "theorem t = forall x -> x == 2 ==> x + 1 == 3 proof assume x == 2 => ? in t", + ); + check( + string, + "the body's goal", + "x + 1 == 3", + goal(first(body(first(f.rows)))), + ); + }, + ), + test_case( + "revert: the body's goal is the fact implying the old goal", + `Quick, + () => { + let f = + Fixture.mk( + "theorem t = forall x -> x == 1 ==> x == 1 proof assume x == 1 => revert x == 1 => ? in t", + ); + let revert = first(body(first(f.rows))); + check(string, "the row", "revert", kind(revert)); + let hole = first(body(revert)); + check(string, "the body's goal", "x == 1 ==> x == 1", goal(hole)); + check( + bool, + "the reverted fact is still citable", + true, + List.Assoc.mem(facts(hole), "assume", ~equal=String.equal), + ); + }, + ), + test_case( + "generalize: the body's goal is re-quantified, without facts about the variable", + `Quick, + () => { + let f = + Fixture.mk( + "theorem t = forall x -> x == 1 ==> x == x proof assume x == 1 => generalize x => ? in t", + ); + let generalize = first(body(first(f.rows))); + check( + bool, + "the hypothesis is in scope before the generalize", + true, + List.Assoc.mem(facts(generalize), "assume", ~equal=String.equal), + ); + let hole = first(body(generalize)); + switch (hole.goal |> Option.map(~f=Exp.term_of)) { + | Some(Forall(_)) => () + | _ => Alcotest.fail("the body's goal is not re-quantified") + }; + check( + bool, + "and gone inside it", + false, + List.Assoc.mem(facts(hole), "assume", ~equal=String.equal), + ); + }, + ), + test_case( + "have: the subproof is a chain rooted at the proposition", + `Quick, + () => { + let f = Fixture.mk(have_src); + let (sub, _) = premises(first(f.rows)); + check(list(string), "the subproof's rows", ["hole"], kinds(sub)); + check(string, "its goal", "1 == 1", goal(first(sub))); + check( + bool, + "a row to write in: it has state", + true, + Stepper.Model.find(first(sub).key, f.theorem.stepper) != None, + ); + }, + ), + test_case( + "have: a completed subproof renders its rows and reaches true", + `Quick, + () => { + let f = + Fixture.mk( + {|theorem t = forall x -> x == 1 proof have 1 == 1 proof from 1 == 1 do rewrite refl end end => ? in t|}, + ); + let (sub, _) = premises(first(f.rows)); + check( + list(string), + "the subproof's rows", + ["refl", "end"], + kinds(sub), + ); + check( + option(string), + "it reaches true", + Some("true"), + Rows.reached(sub) |> Option.map(~f=print), + ); + }, + ), + test_case( + "have: the body continues the outer goal, with `have` in scope", + `Quick, + () => { + let f = Fixture.mk(have_src); + let (_, body) = premises(first(f.rows)); + check(list(string), "the body's rows", ["hole"], kinds(body)); + check(string, "its goal", "x == 1", goal(first(body))); + check( + option(string), + "the hypothesis", + Some("1 == 1"), + List.Assoc.find(facts(first(body)), "have", ~equal=String.equal), + ); + }, + ), + test_case( + "have: the subproof is checked in the enclosing scope", + `Quick, + () => { + let f = + Fixture.mk( + {|theorem t = forall x -> x == 1 proof have 1 == 1 proof have 2 == 2 proof ? => ? => ? in t|}, + ); + let (sub, _) = premises(first(f.rows)); + let (_, inner_body) = premises(first(sub)); + let haves = + facts(first(inner_body)) + |> List.filter(~f=((name, _)) => name == "have") + |> List.map(~f=snd); + check( + list(string), + "only the inner have's hypothesis", + ["2 == 2"], + haves, + ); + }, + ), + test_case( + "have: the obligation panel's Prove-here shape has both premises' rows", + `Quick, + () => { + let f = + Fixture.mk( + "let f = fun x -> 100 / x in theorem t = forall y -> f(y) == f(y) proof have y != 0 proof ? => ? in t", + ); + let (sub, body) = premises(first(f.rows)); + check(string, "the subproof's goal", "y != 0", goal(first(sub))); + check(string, "the body's goal", "f(y) == f(y)", goal(first(body))); + check( + list(string), + "both are holes", + ["hole", "hole"], + kinds([first(sub), first(body)]), + ); + }, + ), + ]; +}; + +/* The stored state: one entry per row, kept while the row lasts. */ +/* A goal holding a lambda, which the display folds unless function + * bodies are shown. */ +module Settings_change = { + let src = "let twice = fun f -> fun x -> f(f(x)) in theorem t = twice(fun y -> y + 1)(3) == 5 proof ? in t"; + + /* The goal's `twice(fun y -> y + 1)` and its `3`. */ + let lhs = (goal: Picker.Goal.t): (Exp.t, Exp.t) => + switch (Exp.term_of(goal.written)) { + | BinOp(_, lhs, _) => + switch (Exp.term_of(lhs)) { + | Ap(_, applied, three) => (applied, three) + | _ => Alcotest.fail("not an application") + } + | _ => Alcotest.fail("not an equation") + }; + let applied = goal => fst(lhs(goal)); + let three = goal => snd(lhs(goal)); + + let show_fn_bodies = (settings: CoreSettings.t): CoreSettings.t => { + ...settings, + evaluation: { + ...settings.evaluation, + show_fn_bodies: true, + }, + }; + + let text = (goal: Picker.Goal.t): string => + Printer.of_zipper(~holes="?", goal.editor.editor.state.zipper); +}; + +module State = { + let tab = (local: Stepper.Model.local) => + Option.bind(local.box, ~f=(box: Stepper.Model.box) => box.tab); + + let tests = [ + test_case( + "the row where a chain continues has a write box, and a step row none", + `Quick, + () => { + let f = + Fixture.mk( + "theorem t = (1 + 1) * 2 == 4 proof from 1 + 1 do step end in t", + ); + check( + list(bool), + "has a box", + [false, true], + List.map(~f=row => Fixture.local(f, row).box != None, f.rows), + ); + let row = last(f.rows); + check( + bool, + "no tab picked", + true, + tab(Fixture.local(f, row)) == None, + ); + let f = Fixture.act(f, (row.key, Tab(Step))); + check( + bool, + "the tab picked", + true, + tab(Fixture.local(f, row)) == Some(Step), + ); + }, + ), + test_case( + "every hole has a write box, in the middle of a proof too", + `Quick, + () => { + let f = + Fixture.mk( + "theorem t = (1 + 1) * 2 == 4 proof ?; from 1 + 1 do step end in t", + ); + check( + list(pair(string, bool)), + "rows and boxes", + [("hole", true), ("step", false), ("end", true)], + List.map( + ~f=row => (kind(row), Fixture.local(f, row).box != None), + f.rows, + ), + ); + }, + ), + test_case( + "a focus's steps end in a write box only when the focus ends its chain", + `Quick, + () => { + let inner_end = src => { + let f = Fixture.mk(src); + switch (first(f.rows).kind) { + | Step(Focus(rows)) => + let row = last(rows); + (row.continues, Fixture.local(f, row).box != None); + | _ => Alcotest.fail("not a C") + }; + }; + check( + pair(bool, bool), + "last in its chain", + (true, true), + inner_end( + "theorem t = (1 + 1) * 2 == 4 proof from (1 + 1) * 2 do from 1 + 1 do step end; step end in t", + ), + ); + check( + pair(bool, bool), + "with a step after it", + (false, false), + inner_end( + "theorem t = (1 + 1) * 2 == 4 proof from (1 + 1) * 2 do from 1 + 1 do step end; step end; step in t", + ), + ); + }, + ), + test_case( + "an empty box showing a ghost keeps its caret before the hole", + `Quick, + () => { + let f = Fixture.mk("theorem t = (1 + 1) * 2 == 4 proof ? in t"); + let row = first(f.rows); + let at_start = (f: Fixture.t) => + switch (Fixture.local(f, row).box) { + | Some(box) => + let z = box.editor.editor.state.zipper; + fst(Siblings.neighbors(z.relatives.siblings)) == None + && z.relatives.ancestors == []; + | None => Alcotest.fail("no box") + }; + List.iter( + ~f= + ((label, move)) => + check( + bool, + label, + true, + at_start( + Fixture.act( + f, + (row.key, BoxEditor(Perform(Move(move)))), + ), + ), + ), + [("End", Action.End), ("Right", Local(Right, ByChar))], + ); + }, + ), + test_case( + "a recalculation keeps each row's editor while its goal is unchanged", + `Quick, + () => { + let f = + Fixture.mk( + {|theorem t = forall x -> x == 1 proof have 1 == 1 proof ? => from 1 + 1 do step end in t|}, + ); + let f = Fixture.act(f, (first(f.rows).key, Goal(Move(Start)))); + let again = + Stepper.Update.calculate( + ~settings=Web.Theorems.with_proof_settings(settings), + f.rows, + f.theorem.stepper, + ); + List.iter( + ~f= + (row: Rows.t) => + switch ( + Stepper.Model.find(row.key, f.theorem.stepper), + Stepper.Model.find(row.key, again), + ) { + | (Some(before), Some(after)) => + check( + bool, + kind(row) ++ ": the same editor", + true, + phys_equal(before.goal.editor, after.goal.editor), + ) + | (None, None) => () + | _ => Alcotest.fail(kind(row) ++ ": state came or went") + }, + Fixture.all(f), + ); + }, + ), + test_case( + "a changed goal is prepared again, keeping the row's box", + `Quick, + () => { + let f = Fixture.mk("theorem t = 1 + 2 == 3 proof ? in t"); + let row = first(f.rows); + let f = Fixture.act(f, (row.key, Tab(Strategy))); + let changed = { + ...row, + goal: Some(parse_exp("2 + 2 == 4")), + }; + let model = + Stepper.Update.calculate(~settings, [changed], f.theorem.stepper); + switch (Stepper.Model.find(row.key, model)) { + | Some(local) => + check( + string, + "the new goal", + "2 + 2 == 4", + print(local.goal.written), + ); + check( + bool, + "the box keeps its tab", + true, + tab(local) == Some(Strategy), + ); + | None => Alcotest.fail("the row lost its state") + }; + }, + ), + test_case( + "a settings change prepares a goal again, keeping its selection and box", + `Quick, + () => { + let f = Fixture.mk(Settings_change.src); + let row = first(f.rows); + let applied = Settings_change.applied(Fixture.goal(f, row)); + let f = Fixture.act(f, (row.key, Tab(Strategy))); + let f = + Fixture.act( + f, + ( + row.key, + Goal(Select(Term(Id(Exp.rep_id(applied), Right)))), + ), + ); + let before = Fixture.local(f, row); + let shown = Settings_change.show_fn_bodies(before.goal.settings); + let model = + Stepper.Update.calculate( + ~settings=shown, + f.rows, + f.theorem.stepper, + ); + switch (Stepper.Model.find(row.key, model)) { + | Some(local) => + check( + bool, + "built with the new settings", + true, + local.goal.settings == shown, + ); + check( + string, + "printed with function bodies", + "twice(fun y -> y + 1)(3) == 5", + Settings_change.text(local.goal), + ); + check( + option(string), + "the same node selected", + Some(print(Settings_change.applied(local.goal))), + Option.map(~f=print, Picker.Goal.selected(local.goal)), + ); + check( + bool, + "the box keeps its tab", + true, + tab(local) == Some(Strategy), + ); + | None => Alcotest.fail("the row lost its state") + }; + }, + ), + test_case( + "a settings change keeps the caret by the same node", + `Quick, + () => { + let f = Fixture.mk(Settings_change.src); + let row = first(f.rows); + let three = Settings_change.three(Fixture.goal(f, row)); + let f = + Fixture.act( + f, + (row.key, Goal(Move(Goal(TileId(Exp.rep_id(three)))))), + ); + let before = Fixture.local(f, row); + let model = + Stepper.Update.calculate( + ~settings=Settings_change.show_fn_bodies(before.goal.settings), + f.rows, + f.theorem.stepper, + ); + switch (Stepper.Model.find(row.key, model)) { + | Some(local) => + check( + option(string), + "the caret at the 3", + Some("3"), + Indicated.index(local.goal.editor.editor.state.zipper) + |> Option.map(~f=id => + switch (Exp.find_by_id(id, local.goal.written)) { + | Some(e) => print(e) + | None => "not in the goal" + } + ), + ) + | None => Alcotest.fail("the row lost its state") + }; + }, + ), + test_case( + "opening the history doesn't prepare goals again", + `Quick, + () => { + let f = Fixture.mk(Settings_change.src); + let row = first(f.rows); + let before = Fixture.local(f, row); + let settings = before.goal.settings; + let model = + Stepper.Update.calculate( + ~settings={ + ...settings, + evaluation: { + ...settings.evaluation, + stepper_history: !settings.evaluation.stepper_history, + }, + }, + f.rows, + f.theorem.stepper, + ); + switch (Stepper.Model.find(row.key, model)) { + | Some(local) => + check( + bool, + "the same editor", + true, + phys_equal(local.goal.editor, before.goal.editor), + ) + | None => Alcotest.fail("the row lost its state") + }; + }, + ), + test_case( + "a row's state goes when its step does", + `Quick, + () => { + let f = + Fixture.mk( + "theorem t = 1 + 4 == 5 proof from 1 + 4 do step end in t", + ); + let other = Fixture.mk("theorem t = 1 + 4 == 5 proof ? in t"); + let model = + Stepper.Update.calculate(~settings, other.rows, f.theorem.stepper); + check( + bool, + "none of the old rows has state", + true, + List.for_all( + ~f=(row: Rows.t) => Stepper.Model.find(row.key, model) == None, + f.rows, + ), + ); + check( + bool, + "the new row has", + true, + Stepper.Model.find(first(other.rows).key, model) != None, + ); + }, + ), + test_case( + "a row with no goal has no state", + `Quick, + () => { + let f = Fixture.mk("theorem t = 1 == 1 proof ? in t"); + let row = { + ...first(f.rows), + goal: None, + }; + check( + bool, + "no state", + true, + Stepper.Model.find( + row.key, + Stepper.Update.calculate(~settings, [row], Stepper.Model.init), + ) + == None, + ); + }, + ), + test_case( + "a step just written has its row before the next check", + `Quick, + () => { + /* Its argument's sub-editor has to be there to take focus. */ + let term = parse_exp("theorem t = 1 + 4 == 5 proof ? in t"); + let statics = Fixture.statics_of_term(term); + let cell = + Fixture.calculate( + ~is_edited=true, + statics, + Web.EvalResult.Model.init, + ); + let edited = + Exp.map_term( + ~f_proof= + (cont, p: Proof.t) => + switch (p.term) { + | EmptyHole => + Proof.fresh( + Picker.Terms.assume(~exp=Exp.fresh(EmptyHole)), + ) + | _ => cont(p) + }, + term, + ); + let statics = Fixture.statics_of_term(edited); + let f = + Fixture.of_cell( + ~name="t", + statics, + Fixture.calculate(~pending=true, ~is_edited=true, statics, cell), + ); + check(list(string), "rows", ["assume", "end"], kinds(f.rows)); + check(bool, "not checked yet", true, first(f.rows).goal == None); + }, + ), + test_case( + "a folded theorem keeps its stepper", + `Quick, + () => { + let names = src => + Fixture.statics(src) + |> Fixture.calculate(~is_edited=true, _, Web.EvalResult.Model.init) + |> (cell => Web.Theorems.Model.theorems(cell.theorems)) + |> List.map(~f=((_, thm: Web.Theorems.Model.theorem)) => thm.name); + let t = "theorem t = 1 == 1 proof ? in "; + let u = "theorem u = 2 == 2 proof ? in "; + check( + list(string), + "whole program", + ["t", "u"], + names("^^fold(" ++ t ++ u ++ "t)"), + ); + check( + list(string), + "the rest of the program", + ["t", "u"], + names(t ++ "^^fold(" ++ u ++ "t)"), + ); + check( + list(string), + "statement", + ["t"], + names("theorem t = ^^fold(1 == 1) proof ? in t"), + ); + check( + list(string), + "under a let", + ["u"], + names("let x = ^^fold(" ++ u ++ "1) in x"), + ); + }, + ), + test_case( + "a theorem's stepper goes when the theorem does", + `Quick, + () => { + let f = + Fixture.mk( + "theorem t = 1 == 1 proof ? in theorem u = 2 == 2 proof ? in t", + ); + check( + int, + "two theorems", + 2, + List.length(Web.Theorems.Model.theorems(f.cell.theorems)), + ); + let statics = Fixture.statics("theorem t = 1 == 1 proof ? in t"); + let cell = Fixture.calculate(~is_edited=true, statics, f.cell); + check( + list(string), + "only t is left", + ["t"], + Id.Map.bindings(cell.theorems.thm_map) + |> List.map(~f=((_, thm: Web.Theorems.Model.theorem)) => thm.name), + ); + }, + ), + ]; +}; + +/* What the write box offers, as a function of the goal and the + * selection. */ +module Picking = { + let root_goal = src => { + let f = Fixture.mk(src); + Fixture.goal(f, first(f.rows)); + }; + + let node = (goal: Picker.Goal.t, printed: string): Exp.t => { + let found = ref(None); + let _: Exp.t = + Exp.map_term( + ~f_exp= + (cont, e) => { + if (found^ == None && print(e) == printed) { + found := Some(e); + }; + cont(e); + }, + goal.written, + ); + switch (found^) { + | Some(e) => e + | None => Alcotest.fail("no " ++ printed ++ " in the goal") + }; + }; + + /* The ghost's rule, the step Tab writes, and what the ghost shows. */ + let ghost = (~selected=None, goal) => + Picker.Ghost.mk(goal, ~selected) + |> Option.map(~f=(g: Picker.Ghost.t) => + (g.rule, written(Picker.focused(g.pick)), print(g.result)) + ); + + let ghost_t = option(triple(string, string, string)); + + let labels = (strategies: list(Picker.Strategies.strategy)) => + List.map(~f=(s: Picker.Strategies.strategy) => s.label, strategies); + + /* What the strategy labelled `label` writes. */ + let writes = (strategies: list(Picker.Strategies.strategy), label) => + switch ( + List.find( + ~f=(s: Picker.Strategies.strategy) => s.label == label, + strategies, + ) + ) { + | Some(s) => written(Proof.fresh(s.writes)) + | None => Alcotest.fail("no " ++ label ++ " strategy") + }; + + let equation = "theorem t = 1 + 2 + 3 == 6 proof ? in t"; + let implication = "theorem t = forall x -> x == 2 ==> x + 1 == 3 proof ? in t"; + + let tests = [ + test_case( + "an empty box's ghost is the goal's next eval step, written where the checker takes it", + `Quick, + () => + check( + ghost_t, + "ghost", + Some(("step", "from $e + 2 do step end", "3 + 3 == 6")), + ghost(root_goal(equation)), + ) + ), + test_case("a goal reflexivity closes has the ghost `true`", `Quick, () => + check( + ghost_t, + "ghost", + Some(("refl", "rewrite refl end", "true")), + ghost( + root_goal("theorem t = forall (x : Int) -> x == x proof ? in t"), + ), + ) + ), + test_case( + "with part of the goal selected, the ghost is that part's own step and what the part becomes", + `Quick, + () => { + let goal = root_goal("theorem t = 2 * (1 + 1) == 4 proof ? in t"); + check( + ghost_t, + "ghost", + Some(("step", "from ($e + $e) do step end", "2")), + ghost(~selected=Some(node(goal, "1 + 1")), goal), + ); + check( + ghost_t, + "a part with no step has none", + None, + ghost(~selected=Some(node(goal, "4")), goal), + ); + }, + ), + test_case( + "a selected call of a named function contracts; with nothing selected, Tab steps as before", + `Quick, + () => { + let goal = + root_goal( + "let inc = fun x -> x + 1 in theorem t = inc(2 + 3) == 6 proof ? in t", + ); + let call = node(goal, "inc(2 + 3)"); + check( + bool, + "the Step tab marks the call", + true, + List.mem( + Picker.Goal.step_ids(goal), + Exp.rep_id(call), + ~equal=Id.equal, + ), + ); + check( + ghost_t, + "selected", + Some(("step", "from $e($e) do step end", "2 + 3 + 1")), + ghost(~selected=Some(call), goal), + ); + check( + ghost_t, + "nothing selected", + Some(("step", "from $e + $e do step end", "inc(5) == 6")), + ghost(goal), + ); + }, + ), + test_case( + "the goal's own introduction comes first: Assume for an implication", + `Quick, + () => { + let goal = root_goal(implication); + let intros = Picker.Strategies.intros(goal); + check(list(string), "intros", ["Assume"], labels(intros)); + check( + string, + "a hole to assume", + "assume ? => ?", + writes(intros, "Assume"), + ); + check( + list(string), + "an equation has none", + [], + labels(Picker.Strategies.intros(root_goal(equation))), + ); + check( + list(string), + "an implication in parentheses", + ["Assume"], + labels( + Picker.Strategies.intros( + root_goal( + "theorem t = forall x -> (x == 2 ==> x + 1 == 3) proof ? in t", + ), + ), + ), + ); + }, + ), + test_case( + "a function equality's introduction is Funext, with a hole for its argument", + `Quick, + () => { + let goal = + root_goal( + "theorem t = (fun x -> x + 1) == (fun x -> 1 + x) proof ? in t", + ); + check( + string, + "funext", + "funext ? => ?", + writes(Picker.Strategies.intros(goal), "Funext"), + ); + }, + ), + test_case( + "then the strategies any goal can use, each saying what it writes", + `Quick, + () => { + let general = Picker.Strategies.general(); + check( + list(string), + "strategies", + ["Induction", "Cases", "Have", "Generalize", "Revert"], + labels(general), + ); + check( + list(string), + "without a tooltip", + [], + general + @ Picker.Strategies.intros(root_goal(implication)) + |> List.filter(~f=(s: Picker.Strategies.strategy) => + s.tooltip == "" + ) + |> labels, + ); + }, + ), + test_case( + "every strategy writes its form with holes to fill in", + `Quick, + () => { + let general = Picker.Strategies.general(); + check( + list(string), + "writes", + [ + "induction ? end", + "cases ? end", + "have ? proof ? => ?", + "generalize ? => ?", + "revert ? => ?", + ], + List.map(~f=writes(general), labels(general)), + ); + }, + ), + test_case( + "Forall is offered on a forall goal", + `Quick, + () => { + let f = + Fixture.mk( + "theorem t = forall x: Int -> x > 0 ==> (forall y: Int -> y == y) proof assume x > 0 => ? in t", + ); + let goal = Fixture.goal(f, first(body(first(f.rows)))); + check( + bool, + "Forall", + true, + List.mem( + labels(Picker.Strategies.intros(goal)), + "Forall", + ~equal=String.equal, + ), + ); + }, + ), + test_case( + "with no eval step left, the ghost is reflexivity inside the goal", + `Quick, + () => { + let goal = + root_goal( + "theorem t = forall n: Int -> n == 1 ==> n == n proof ? in t", + ); + switch (Picker.Ghost.mk(goal, ~selected=None)) { + | Some(g) => + check(string, "the rule", "refl", g.rule); + check( + string, + "what the goal becomes", + "n == 1 ==> true", + print(g.result), + ); + | None => Alcotest.fail("no ghost") + }; + }, + ), + test_case( + "on an equation, the ghost steps a part only one side has, the left first", + `Quick, + () => { + let goal = + root_goal( + "let len = fun xs -> case xs | [] => 0 | _ :: t => 1 + len(t) end in theorem t = forall ys: [Int] -> len([] @ ys) == len([]) + len(ys) proof ? in t", + ); + check( + ghost_t, + "ghost", + Some(( + "step", + "from $e @ $e do step end", + "len(ys) == len([]) + len(ys)", + )), + ghost(goal), + ); + }, + ), + ]; +}; + +/* Taking an offered step writes it, and the cell stepper advances. */ +module Regressions = { + /* What writing `pick` at `row` puts into the proof. */ + let written_at = (row: Rows.t, pick: Picker.pick): string => + switch (Picker.write(row, pick)) { + | ProofPatch({replacement, _}) => written(replacement) + | _ => Alcotest.fail("not a proof patch") + }; + + /* The cell stepper's goals for `src` after taking the only step the + * last row offers `steps` times. */ + let cell_walk = (src: string, ~steps: int): list(string) => { + let statics = Fixture.statics(src); + let cell = + Fixture.calculate(~is_edited=true, statics, Web.EvalResult.Model.init); + let update = (action, cell) => { + let updated = + Web.EvalResult.Update.update( + ~settings=Web.Settings.Model.init, + action, + cell, + ); + Fixture.calculate(~is_edited=false, statics, updated.model); + }; + let stepper = (cell: Web.EvalResult.Model.t) => + switch (cell.display) { + | Stepper(s) => s + | Evaluation(_) => Alcotest.fail("the stepper is off") + }; + let rows = cell => + Rows.chain( + ~proof_map=stepper(cell).proof_map, + Web.EvalResult.CellStepper.proof(stepper(cell)), + ); + let step = cell => { + let row = last(rows(cell)); + let goal = + switch (Stepper.Model.find(row.key, stepper(cell).stepper)) { + | Some(local) => local.goal + | None => Alcotest.fail("the last row has no state") + }; + switch (Picker.take_step(goal, 0)) { + | Some(pick) => update(StepperPatch(Picker.write(row, pick)), cell) + | None => Alcotest.fail("no step offered at " ++ print(goal.written)) + }; + }; + let cell = + List.fold_left( + ~f=(cell, _) => step(cell), + ~init=update(ToggleStepper, cell), + List.init(steps, ~f=Fn.id), + ); + List.map(~f=goal, rows(cell)); + }; + + let tests = [ + test_case( + "Step and Proof strategy drop a selection of part of the goal, and Write keeps it", + `Quick, + () => { + let f = Fixture.mk("theorem t = 2 * (1 + 1) == 4 proof ? in t"); + let row = first(f.rows); + let part = Picking.node(Fixture.goal(f, row), "(1 + 1)"); + let f = + Fixture.act( + f, + (row.key, Goal(Select(Term(Id(Exp.rep_id(part), Right))))), + ); + let selected = (f: Fixture.t) => + Option.map(~f=print, Picker.Goal.selected(Fixture.goal(f, row))); + let f = Fixture.act(f, (row.key, Tab(Write))); + check(option(string), "Write", Some("(1 + 1)"), selected(f)); + let f = Fixture.act(f, (row.key, Tab(Strategy))); + check(option(string), "Proof strategy", None, selected(f)); + }, + ), + test_case( + "a step inside a call's argument is offered at the argument, not at the call", + `Quick, + () => { + let f = + Fixture.mk( + "let len = fun xs -> case xs | [] => 0 | _ :: t => 1 + len(t) end in theorem t = forall xs: [Int] -> len(xs @ []) == len(xs) proof induction xs | [] => ? | y :: ys => ? end in t", + ); + let row = first(List.hd_exn(cases(first(f.rows)))); + let goal = Fixture.goal(f, row); + check( + list(string), + "offered", + ["len([])", "[] @ []"], + offered(goal), + ); + List.iteri( + ~f= + (n, _) => + switch (Picker.take_step(goal, n)) { + | Some(pick) => + check( + bool, + written(Picker.focused(pick)) ++ " checks", + true, + Picker.outgoing(goal, goal.written, Picker.focused(pick)) + != None, + ) + | None => Alcotest.fail("an offered step writes nothing") + }, + goal.eval_steps, + ); + }, + ), + test_case( + "a strategy's `?` argument leaves its step unfinished, not wrong", + `Quick, + () => + List.iter( + ~f= + step => { + let f = + Fixture.mk( + "theorem t = forall n: Int -> n > 5 ==> n > 3 proof assume n > 5 => " + ++ step + ++ " in t", + ); + check( + list(string), + step ++ ": marks", + [], + List.concat_map( + ~f= + (row: Rows.t) => + switch (row.entry) { + | Some(entry) => List.map(~f=ProofMark.show, entry.marks) + | None => [] + }, + Fixture.all(f), + ), + ); + check( + string, + step ++ ": status", + "incomplete", + Web.Obligations.Status.( + label(of_proof(f.cell.theorems.proof_map, f.theorem.proof)) + ), + ); + }, + ["revert ? => ?", "generalize ? => ?", "have ? proof ? => ?"], + ) + ), + test_case( + "theorem stepper: taking an offered step writes the checker's eval step in place of the hole", + `Quick, + () => { + let f = Fixture.mk("theorem t = 1 + 2 + 3 == 6 proof ? in t"); + let row = first(f.rows); + let goal = Fixture.goal(f, row); + check(list(string), "offered", ["1 + 2"], offered(goal)); + switch (Picker.take_step(goal, 0)) { + | Some(pick) => + check( + string, + "written", + "from $e + 2 do step end", + written_at(row, pick), + ) + | None => Alcotest.fail("no step offered") + }; + }, + ), + test_case( + "cell stepper: taking a step advances to the next goal", `Quick, () => + check( + list(string), + "the goals", + ["1 + 2 + 3", "3 + 3", "6"], + cell_walk("1 + 2 + 3", ~steps=2), + ) + ), + test_case( + "cell stepper: a goal holding a negative number still steps at its root", + `Quick, + () => + check( + list(string), + "the goals", + ["0 - 5 + 2", "-5 + 2", "-3"], + cell_walk("0 - 5 + 2", ~steps=2), + ) + ), + ]; +}; + +/* What the stepper writes into the proof text, and that it reads back. A + * form with nothing to search goes in with a hole argument, and the + * caret jumps into that argument, so the hole has to be a caret target. */ +module Insertion = { + let parse_zipper = (s: string): Zipper.t => + switch (Parser.to_zipper(s, ~root=Exp)) { + | Some(z) => z + | None => Alcotest.fail("failed to parse zipper: " ++ s) + }; + + let theorem_proof = (z: Zipper.t): Proof.t => + switch ( + Test_ProofMap.find_theorem_proof( + MakeTerm.from_zip_for_sem(z, ~root=Exp).term, + ) + ) { + | Some(p) => p + | None => Alcotest.fail("no theorem proof") + }; + + /* Writes `term` over the theorem's (hole) proof, as picking on its hole + * row does. */ + let insert_zipper = (~src: string, term: TermBase.Proof.term): Zipper.t => { + let z = parse_zipper(src); + EditorTransform.apply_patch( + z, + EditorTransform.mk_proof_patch( + ~target_id=Proof.rep_id(theorem_proof(z)), + Proof.fresh(term), + ), + ); + }; + + let insert = (~src: string, term: TermBase.Proof.term): string => + insert_zipper(~src, term) |> Printer.of_zipper(~holes="?"); + + let reparsed = (out: string): Proof.t => + switch (Test_ProofMap.find_theorem_proof(parse_exp(out))) { + | Some(p) => p + | None => Alcotest.fail("no theorem proof after insertion") + }; + + let contains = (haystack: string, needle: string): bool => { + let hl = String.length(haystack); + let nl = String.length(needle); + let rec go = i => + i + + nl <= hl + && (String.sub(haystack, ~pos=i, ~len=nl) == needle || go(i + 1)); + nl == 0 || go(0); + }; + + let check_contains = (~msg: string, haystack: string, needle: string) => + check( + bool, + msg ++ ": expected to find\n" ++ needle ++ "\nin:\n" ++ haystack, + true, + contains(haystack, needle), + ); + + let hole = () => Exp.fresh(EmptyHole); + let implication = "theorem t = forall x -> x == 2 ==> x == 2 proof ? in t"; + + let tests = [ + test_case( + "Assume with no argument writes `assume ? =>`", + `Quick, + () => { + let out = insert(~src=implication, Picker.Terms.assume(~exp=hole())); + check_contains(~msg="the step", out, "assume ? =>"); + check_contains( + ~msg="the statement survives", + out, + "forall x -> x == 2 ==> x == 2", + ); + }, + ), + test_case( + "Generalize with no argument writes `generalize ? =>`", `Quick, () => + check_contains( + ~msg="the step", + insert( + ~src="theorem t = forall x -> x == x proof ? in t", + Picker.Terms.generalize(~exp=hole()), + ), + "generalize ?", + ) + ), + test_case( + "an empty-argument form reparses with a hole argument", `Quick, () => + switch ( + reparsed(insert(~src=implication, Picker.Terms.assume(~exp=hole()))) + ) { + | {term: Assume({term: EmptyHole, _}, None, {term: EmptyHole, _}), _} => + () + | p => Alcotest.fail("reparsed as " ++ Proof.show(p)) + } + ), + test_case( + "a new form's argument hole is a caret target, and the form keeps its id", + `Quick, + () => + List.iter( + ~f= + ((label, src, term)) => { + let arg_id = + switch (Picker.Terms.arg_id(term)) { + | Some(id) => id + | None => Alcotest.fail(label ++ ": no argument id") + }; + let step = Proof.fresh(term); + let z = parse_zipper(src); + let z = + EditorTransform.apply_patch( + z, + EditorTransform.mk_proof_patch( + ~target_id=Proof.rep_id(theorem_proof(z)), + step, + ), + ); + check( + bool, + label ++ ": the caret can jump to the argument", + true, + Move.jump_to_id_indicated(z, arg_id) != None, + ); + /* The view focuses the new step's argument by the step's id. */ + check( + bool, + label ++ ": the step keeps its id", + true, + Proof.rep_id(theorem_proof(z)) == Proof.rep_id(step), + ); + }, + [ + ("assume", implication, Picker.Terms.assume(~exp=hole())), + ("generalize", implication, Picker.Terms.generalize(~exp=hole())), + /* Revert is picked, not typed, but focused the same way so the + * pick can be adjusted. */ + ( + "revert", + implication, + Picker.Terms.revert(~exp=parse_exp("x == 2")), + ), + ( + "have", + "theorem t = forall x -> x == 1 proof ? in t", + Picker.Terms.have(~exp=hole()), + ), + ], + ) + ), + test_case("a step with no argument has no argument id", `Quick, () => + check( + bool, + "none", + true, + Picker.Terms.arg_id(Proof.fresh(EmptyHole).term) == None, + ) + ), + test_case("a picked Assume argument writes `assume => ?`", `Quick, () => + check_contains( + ~msg="the step", + insert( + ~src=implication, + Picker.Terms.assume(~exp=parse_exp("x == 2")), + ), + "assume x == 2 =>", + ) + ), + test_case("a picked Revert fact writes `revert => ?`", `Quick, () => + check_contains( + ~msg="the step", + insert( + ~src="theorem t = forall x -> x == 1 proof ? in t", + Picker.Terms.revert(~exp=parse_exp("x == 1")), + ), + "revert x == 1 =>", + ) + ), + test_case( + "a picked Generalize argument writes `generalize => ?`", `Quick, () => + check_contains( + ~msg="the step", + insert( + ~src="theorem t = forall x -> x == x proof ? in t", + Picker.Terms.generalize(~exp=parse_exp("x")), + ), + "generalize x =>", + ) + ), + test_case( + "Have with no argument writes `have ? proof ? =>`", + `Quick, + () => { + let out = + insert( + ~src="theorem t = forall x -> x == 1 proof ? in t", + Picker.Terms.have(~exp=hole()), + ); + check_contains(~msg="the proposition", out, "have ?"); + check_contains(~msg="an open subproof", out, "proof ?"); + check_contains(~msg="the arrow", out, "=>"); + }, + ), + test_case("an empty-argument have reparses with three holes", `Quick, () => + switch ( + reparsed( + insert( + ~src="theorem t = forall x -> x == 1 proof ? in t", + Picker.Terms.have(~exp=hole()), + ), + ) + ) { + | { + term: + Have( + {term: EmptyHole, _}, + None, + {term: EmptyHole, _}, + {term: EmptyHole, _}, + ), + _, + } => + () + | p => Alcotest.fail("reparsed as " ++ Proof.show(p)) + } + ), + test_case( + "a picked Have proposition writes `have proof ? => ?`", `Quick, () => + check_contains( + ~msg="the step", + insert( + ~src="theorem t = forall x -> x == 1 proof ? in t", + Picker.Terms.have(~exp=parse_exp("1 == 1")), + ), + "have 1 == 1 proof ?", + ) + ), + test_case("an inserted form reparses as that form", `Quick, () => + switch ( + reparsed( + insert( + ~src=implication, + Picker.Terms.assume(~exp=parse_exp("x == 2")), + ), + ) + ) { + | {term: Assume(e, None, {term: EmptyHole, _}), _} => + check(string, "the argument", "x == 2", print(e)) + | p => Alcotest.fail("reparsed as " ++ Proof.show(p)) + } + ), + test_case( + "a step picked on a hole replaces it, on a step goes before it, on an end row extends the chain", + `Quick, + () => { + let src = "theorem t = 1 + 4 == 5 proof ?; from 1 + 4 do step end in t"; + let z = parse_zipper(src); + let proof_map = Fixture.mk(src).cell.theorems.proof_map; + let rows = Rows.chain(~proof_map, theorem_proof(z)); + check(list(string), "rows", ["hole", "step", "end"], kinds(rows)); + /* The chain after picking `from 2 + 2 do step end` on `row`: each + * row's hole or focus selector. */ + let pick = row => { + let term = + Picker.Terms.focus( + ~selector=parse_exp("2 + 2"), + ~index=0, + Proof.fresh(EvalStep), + ); + EditorTransform.apply_patch( + z, + Picker.Patches.write(row, Proof.fresh(term)), + ) + |> theorem_proof + |> Rows.chain(~proof_map=ProofMap.empty) + |> List.filter_map(~f=(row: Rows.t) => + switch (row.kind, row.step.term) { + | (Hole, _) => Some("?") + | (Step(_), Focus({selector, _})) => Some(print(selector)) + | _ => None + } + ); + }; + check( + list(string), + "on the hole", + ["2 + 2", "1 + 4"], + pick(List.nth_exn(rows, 0)), + ); + check( + list(string), + "on the step", + ["?", "2 + 2", "1 + 4"], + pick(List.nth_exn(rows, 1)), + ); + check( + list(string), + "on the end row", + ["?", "1 + 4", "2 + 2"], + pick(List.nth_exn(rows, 2)), + ); + }, + ), + ]; +}; + +/* Goals as rows show them: as written, naming the program's + * definitions. */ +module Display = { + let sum = {|let sum(xs) = case xs +| [] => 0 +| x::xs => x + sum(xs) +end +in +|}; + + let rec has = (pred, e: Exp.t): bool => + pred(e) || List.exists(~f=has(pred), Occurrence.children(e)); + + let is_fun = (e: Exp.t) => + switch (e.term) { + | Fun(_) + | FixF(_) + | Closure(_) => true + | _ => false + }; + + let tests = [ + test_case( + "the Step tab offers a step on each operand", + `Quick, + () => { + let f = + Fixture.mk("theorem t = (1 + 2) * (3 + 4) == 21 proof ? in t"); + let g = Fixture.goal(f, first(f.rows)); + check( + list(string), + "offered", + ["(1 + 2)", "(3 + 4)"], + Picker.Goal.step_ids(g) + |> List.filter_map(~f=id => Exp.find_by_id(id, g.written)) + |> List.map(~f=print) + |> List.sort(~compare), + ); + }, + ), + test_case( + "a refuted theorem offers no write box, an unfinished one does", + `Quick, + () => { + let box_at_end = src => { + let f = Fixture.mk(src); + switch (List.rev(f.rows)) { + | [last, ..._] => Fixture.local(f, last).box != None + | [] => Alcotest.fail("no rows") + }; + }; + check( + bool, + "refuted", + false, + box_at_end( + "theorem t = 1 + 1 == 3 proof from 1 + 1 do step end; step in t", + ), + ); + check( + bool, + "unfinished", + true, + box_at_end( + "theorem t = 1 + 1 == 2 proof from 1 + 1 do step end in t", + ), + ); + }, + ), + test_case( + "the last row of a focus is no goal still to prove", + `Quick, + () => { + let unproven = src => { + let f = Fixture.mk(src); + Fixture.all(f) + |> List.filter( + ~f=Rows.is_unproven(~proof_map=f.cell.theorems.proof_map), + ) + |> kinds; + }; + check( + list(string), + "in a focus", + [], + unproven( + "theorem t = (2 + 3) * 2 == 10 proof from (2 + 3) * 2 do from 2 + 3 do step end; step end; step in t", + ), + ); + check( + list(string), + "after an unfinished assume", + ["end"], + unproven( + "theorem t = forall x: Int -> x == 1 ==> x + 0 == 1 proof assume x == 1 => ? in t", + ), + ); + }, + ), + test_case( + "an arm whose pattern binds a name the goal uses is refused", + `Quick, + () => { + let f = + Fixture.mk( + "theorem t = forall xs: [Int] -> forall x: Int -> forall z: Int -> (xs @ [x]) @ [z] == xs @ [x, z] proof induction xs | [] => ? | [x] => ? | z :: rest => ? end in t", + ); + let row = first(f.rows); + switch (row.kind) { + | Step(Cases(cases)) => + check( + list(option(string)), + "refused", + [None, Some("x"), Some("z")], + List.map( + ~f=((pat, _)) => Rows.refused_binding(row, pat), + cases, + ), + ) + | _ => Alcotest.fail("the first row is not a split") + }; + }, + ), + test_case( + "a focus ordinal counts occurrences in the goal as shown", + `Quick, + () => { + let f = + Fixture.mk( + sum + ++ "theorem t = sum == fold_left(_, sum, 0) proof from 0 do algebra 0 + 0 end end in t", + ); + check(list(string), "rows", ["algebra", "end"], kinds(f.rows)); + check( + string, + "the end row", + "sum == fold_left(_, sum, 0 + 0)", + goal(last(f.rows)), + ); + }, + ), + test_case( + "a row shows its goal naming the definitions", + `Quick, + () => { + let f = + Fixture.mk( + "let f = fun x -> 100 / x in theorem t = forall y -> f(y) == f(y) proof ? in t", + ); + let goal = Fixture.goal(f, first(f.rows)); + check(string, "as written", "f(y) == f(y)", print(goal.written)); + check(bool, "no function inlined", false, has(is_fun, goal.written)); + }, + ), + test_case( + "an end row shows the outgoing goal naming the definitions", + `Quick, + () => { + let f = + Fixture.mk( + "let f = fun x -> x in theorem t = f == f proof funext x => ? in t", + ); + check( + list(string), + "rows", + ["extensionality", "end"], + kinds(f.rows), + ); + let goal = Fixture.goal(f, last(f.rows)); + check(bool, "no function inlined", false, has(is_fun, goal.written)); + }, + ), + test_case( + "applications of a recursive function offer eval steps", + `Quick, + () => { + let f = + Fixture.mk( + sum + ++ "theorem t = sum([]) == fold_left(_, sum, 0)([]) proof ? in t", + ); + check( + bool, + "steps offered", + true, + offered(Fixture.goal(f, first(f.rows))) != [], + ); + }, + ), + test_case( + "an end row's tile ids, underlined ones included, are unique", + `Quick, + () => { + /* A duplicate makes `Highlight.of_tile` raise a shard mismatch. */ + let f = + Fixture.mk( + sum + ++ "theorem t = sum([]) == fold_left(_, sum, 0)([]) proof from fold_left(_, sum, 0)([]) do step end in t", + ); + let goal = Fixture.goal(f, last(f.rows)); + let ids = + goal.editor.editor.state.zipper + |> Zipper.unselect_and_zip + |> segment_tile_ids; + check( + list(string), + "duplicated ids", + [], + duplicated(ids) |> List.map(~f=Id.to_string), + ); + check( + list(string), + "underlined ids that are not unique", + [], + Picker.Goal.step_ids(goal) + |> List.filter(~f=id => + List.length(List.filter(~f=Id.equal(id), ids)) > 1 + ) + |> List.map(~f=Id.to_string), + ); + }, + ), + test_case( + "a funext body offers eval of an applied recursive function", + `Quick, + () => { + let f = + Fixture.mk( + sum + ++ "theorem t = sum == fold_left(_, sum, 0) proof funext xs => ? in t", + ); + let goal = Fixture.goal(f, first(body(first(f.rows)))); + check( + string, + "the pointwise goal", + "sum(xs) == fold_left(_, sum, 0)(xs)", + print(goal.written), + ); + check(bool, "steps offered", true, offered(goal) != []); + }, + ), + ]; +}; + +/* How a step draws below its row: a line, or a block of side conditions + * and the goals it creates. */ +module Structure = { + let inv = {|theorem inv = forall x -> x != 0 ==> x / x == 1 proof ? in theorem t = forall x -> forall y -> x / x + y / y == 2 proof from x / x do rewrite inv end end; from y / y do rewrite inv end end in t|}; + + let layout = + Alcotest.testable( + (fmt, l: Rows.layout) => + switch (l) { + | Line => Format.fprintf(fmt, "Line") + | Block({conditions, arms}) => + Format.fprintf( + fmt, + "Block([%s], arms: %b)", + String.concat(~sep=", ", List.map(~f=string_of_int, conditions)), + arms, + ) + }, + (==), + ); + + let kinds_of = (row: Rows.t) => + Rows.side_conditions(row) + |> List.map(~f=(ob: Obligation.t) => Obligation.show_kind(ob.kind)); + + let tests = [ + test_case( + "a step's side conditions are dots on its line until opened", + `Quick, + () => { + let f = Fixture.mk(inv); + let (x, y) = + switch (f.rows) { + | [x, y, ..._] => (x, y) + | _ => Alcotest.fail("two steps expected") + }; + /* `inv` is unfinished, so citing it rests on its statement. */ + check( + list(string), + "a premise and the citation each", + ["Premise", "Citation"], + kinds_of(x), + ); + check( + list(bool), + "all open", + [true, true, true, true], + List.map( + ~f=Obligation.is_pending, + Rows.side_conditions(x) @ Rows.side_conditions(y), + ), + ); + check(layout, "collapsed", Line, Rows.layout(x, ~expanded=[])); + check( + layout, + "opened", + Block({ + conditions: [0], + arms: false, + }), + Rows.layout(x, ~expanded=[0]), + ); + check( + layout, + "an index past the conditions opens nothing", + Line, + Rows.layout(x, ~expanded=[3]), + ); + }, + ), + test_case( + "opening a condition is kept across passes, with its row", + `Quick, + () => { + let f = Fixture.mk(inv); + let row = first(f.rows); + let f = Fixture.act(f, (row.key, ToggleCondition(0))); + check(list(int), "open", [0], Fixture.local(f, row).expanded); + let model = + Stepper.Update.calculate(~settings, f.rows, f.theorem.stepper); + check( + list(int), + "after another pass", + [0], + switch (Stepper.Model.find(row.key, model)) { + | Some(local) => local.expanded + | None => Alcotest.fail("the row lost its state") + }, + ); + let f = Fixture.act(f, (row.key, ToggleCondition(0))); + check( + list(int), + "closed again", + [], + Fixture.local(f, row).expanded, + ); + }, + ), + test_case( + "a form's body and an induction's cases are arms", + `Quick, + () => { + let forall = + Fixture.mk( + "theorem t = true ==> forall x : Int -> x == x proof assume true => forall x => from x == x do rewrite refl end end in t", + ); + let assume = first(forall.rows); + check( + layout, + "assume", + Block({ + conditions: [], + arms: true, + }), + Rows.layout(assume, ~expanded=[]), + ); + check( + layout, + "forall", + Block({ + conditions: [], + arms: true, + }), + Rows.layout(first(body(assume)), ~expanded=[]), + ); + let induction = + Fixture.mk( + "theorem t = forall xs : [Int] -> xs == xs proof induction xs | [] => ? | y :: ys => ? end in t", + ); + check( + layout, + "induction", + Block({ + conditions: [], + arms: true, + }), + Rows.layout(first(induction.rows), ~expanded=[]), + ); + }, + ), + test_case( + "have and alias keep their goal: the body continues the chain", + `Quick, + () => { + let have = + Fixture.mk( + "theorem t = forall z -> 8 / z == 8 / z proof have z != 0 proof ? => from 8 / z == 8 / z do rewrite refl end end in t", + ); + let row = first(have.rows); + check( + list(string), + "no end row after the have", + ["have"], + kinds(have.rows), + ); + check(list(string), "its premises are its arms", [], kinds_of(row)); + check( + layout, + "a block with the sub-proof", + Block({ + conditions: [], + arms: true, + }), + Rows.layout(row, ~expanded=[]), + ); + check( + option(list(string)), + "continued by its body", + Some(["refl", "end"]), + Rows.continuation(row) |> Option.map(~f=kinds), + ); + let alias = + Fixture.mk( + "theorem t = forall x -> x == 1 ==> x == 1 proof assume x == 1 => alias h = x == 1 => ? in t", + ); + let row = first(body(first(alias.rows))); + check( + layout, + "alias is a line", + Line, + Rows.layout(row, ~expanded=[]), + ); + check( + option(list(string)), + "continued by its body", + Some(["hole"]), + Rows.continuation(row) |> Option.map(~f=kinds), + ); + }, + ), + test_case( + "obligations are tagged with their kind", + `Quick, + () => { + let kinds_at = (src, pick) => kinds_of(pick(Fixture.mk(src).rows)); + check( + list(string), + "a division the instantiation brings in", + ["Definedness"], + kinds_at( + "theorem t = forall z -> 8 / z == 8 / z proof from 8 / z == 8 / z do rewrite refl end end in t", + first, + ), + ); + }, + ), + ]; +}; + +/* A focus of one step is drawn as that step; a focus of several opens a + * C of its own steps; and a step picked inside what a focus just rewrote + * joins the focus. What a focus selects is underlined in the goal above + * it. */ +module Focusing = { + /* The node of `goal`'s display underlined for `row`'s focus, printed, + * and which of the display's occurrences of it it is, counting from 0. */ + let underlined = (goal: Picker.Goal.t, row: Rows.t): (string, int) => + switch ( + Option.bind(Picker.Goal.acts_on(goal, row), ~f=id => + Exp.find_by_id(id, goal.written) + ) + ) { + | Some(node) => ( + print(node), + Occurrence.index(node, goal.written) |> Option.value(~default=-1), + ) + | None => Alcotest.fail("nothing underlined") + }; + let underline = pair(string, int); + + /* What picking `step` on `node`, a node of `goal`, writes at `row`. */ + let eval_written = (row: Rows.t, goal: Picker.Goal.t, node: Exp.t): string => + switch ( + Picker.write( + row, + { + at: Picker.target(goal, node), + step: Proof.fresh(EvalStep), + }, + ) + ) { + | ProofPatch({replacement, _}) => written(replacement) + | _ => Alcotest.fail("not a proof patch") + }; + + /* The goal `src`'s proof ends on, failing if the checker marks a step. */ + let ends_on = (src: string): string => { + let f = Fixture.mk(src); + List.iter( + ~f= + (row: Rows.t) => + switch (row.entry) { + | Some({marks: [_, ..._] as marks, _}) => + Alcotest.fail( + "marked: " + ++ String.concat(~sep=", ", List.map(~f=ProofMark.show, marks)), + ) + | Some(_) + | None => () + }, + Fixture.all(f), + ); + goal(last(f.rows)); + }; + + /* Each case picks `step` on a node of the hole's goal, checks what the + * picker writes, then checks that what it wrote selects that node. */ + let generalizing_tests = [ + test_case( + "a focus writes `$e` for each part of its selection that its match doesn't need", + `Quick, + () => { + let f = Fixture.mk("theorem t = 1 + 2 + 3 == 6 proof ? in t"); + let row = first(f.rows); + let goal = Fixture.goal(f, row); + check( + string, + "`$e + $e` would select `1 + 2 + 3`", + "from $e + 2 do step end", + eval_written(row, goal, Picking.node(goal, "1 + 2")), + ); + check( + string, + "it selects the `1 + 2`", + "3 + 3 == 6", + ends_on( + "theorem t = 1 + 2 + 3 == 6 proof from $e + 2 do step end in t", + ), + ); + }, + ), + test_case( + "a focus keeps its ordinal, generalizing only what keeps it", + `Quick, + () => { + let f = Fixture.mk("theorem t = (1 + 1) * (1 + 1) == 4 proof ? in t"); + let row = first(f.rows); + let goal = Fixture.goal(f, row); + let second = + switch (Occurrence.nth(parse_exp("1 + 1"), 1, goal.written)) { + | Some(node) => node + | None => Alcotest.fail("no second 1 + 1") + }; + check( + string, + "the second `1 + 1`", + "from ($e + $e) at 2 do step end", + eval_written(row, goal, second), + ); + check( + string, + "it selects the second `1 + 1`", + "(1 + 1) * 2 == 4", + ends_on( + "theorem t = (1 + 1) * (1 + 1) == 4 proof from ($e + $e) at 2 do step end in t", + ), + ); + }, + ), + test_case( + "a focus keeps the `_` of a partial application, and reads back", + `Quick, + () => { + let src = "let add = fun (a, b) -> a + b in let g = fun x -> x + 1 in theorem t = g(3) == add(_, 1)(3) proof %% in t"; + let fill = proof => + Str.global_replace(Str.regexp_string("%%"), proof, src); + let f = Fixture.mk(fill("?")); + let row = first(f.rows); + let goal = Fixture.goal(f, row); + let step = + eval_written(row, goal, Picking.node(goal, "add(_, 1)(3)")); + check( + bool, + step ++ " keeps the `_`", + true, + String.contains(step, '_'), + ); + ends_on(fill(step)) |> ignore; + }, + ), + test_case( + "a focus on a call writes `$e` for the function and its argument", + `Quick, + () => { + let f = + Fixture.mk( + "let k = fun x -> x + 1 in theorem t = 7 + k(2) == 10 proof ? in t", + ); + let row = first(f.rows); + let goal = Fixture.goal(f, row); + check( + string, + "the call", + "from $e($e) do step end", + eval_written(row, goal, Picking.node(goal, "k(2)")), + ); + check( + string, + "it selects `k(2)`", + "7 + (2 + 1) == 10", + ends_on( + "let k = fun x -> x + 1 in theorem t = 7 + k(2) == 10 proof from $e($e) do step end in t", + ), + ); + }, + ), + ]; + + let tests = [ + test_case( + "a one-step focus is a line named for its step", + `Quick, + () => { + let f = + Fixture.mk( + "theorem t = 1 + 4 == 5 proof from 1 + 4 do step end in t", + ); + switch (first(f.rows)) { + | {kind: Step(Leaf), _} as row => + check(string, "named for its step", "step", kind(row)) + | row => Alcotest.fail("not a line: " ++ kind(row)) + }; + }, + ), + test_case( + "a focus of several steps nests them, and the next row is the lifted goal", + `Quick, + () => { + let f = + Fixture.mk( + "theorem t = (2 + 3) * 2 == 10 proof from (2 + 3) * 2 do from 2 + 3 do step end; step end; step in t", + ); + check( + list(string), + "outer rows", + ["focus", "step", "end"], + kinds(f.rows), + ); + switch (first(f.rows).kind) { + | Step(Focus(rows)) => + check( + list(string), + "its steps", + ["step", "step", "end"], + kinds(rows), + ); + check( + string, + "they start from the selected subterm", + "(2 + 3) * 2", + goal(first(rows)), + ); + | _ => Alcotest.fail("not a C") + }; + check( + string, + "the row after it", + "10 == 10", + goal(List.nth_exn(f.rows, 1)), + ); + }, + ), + test_case( + "a step taken inside what a focus rewrote is a row of its own", + `Quick, + () => { + let f = + Fixture.mk( + "theorem t = (2 + 3) * 2 == 10 proof from 2 + 3 do step end in t", + ); + let row = last(f.rows); + let goal = Fixture.goal(f, row); + let pick: Picker.pick = { + at: Picker.target(goal, Picking.node(goal, "5 * 2")), + step: Proof.fresh(EvalStep), + }; + switch (Picker.write(row, pick)) { + | ProofPatch({replacement, _}) => + check( + string, + "after the focus", + "from 2 + 3 do step end; from $e * $e do step end", + written(replacement), + ) + | _ => Alcotest.fail("not a proof patch") + }; + }, + ), + test_case( + "a one-step focus underlines the occurrence its ordinal picks", + `Quick, + () => { + let f = + Fixture.mk( + "theorem t = (1 + 1) * (1 + 1) == 4 proof from 1 + 1 at 2 do step end; step in t", + ); + let row = first(f.rows); + check( + underline, + "the second 1 + 1", + ("(1 + 1)", 1), + underlined(Fixture.goal(f, row), row), + ); + let next = List.nth_exn(f.rows, 1); + check( + underline, + "the `step` after it, all of its goal", + ("(1 + 1) * 2 == 4", 0), + underlined(Fixture.goal(f, next), next), + ); + }, + ), + test_case( + "a focus of several steps underlines its occurrence above the C, and a focus inside it underlines within the C's goal", + `Quick, + () => { + let f = + Fixture.mk( + "theorem t = (2 + 3) * 2 + (2 + 3) * 2 == 20 proof from (2 + 3) * 2 at 2 do from 2 + 3 do step end; step end; step in t", + ); + let row = first(f.rows); + check( + underline, + "above the C", + ("(2 + 3) * 2", 1), + underlined(Fixture.goal(f, row), row), + ); + switch (row.kind) { + | Step(Focus(rows)) => + let inner = first(rows); + check( + underline, + "inside the C", + ("(2 + 3)", 0), + underlined(Fixture.goal(f, inner), inner), + ); + | _ => Alcotest.fail("not a C") + }; + }, + ), + test_case( + "the underline lands on a call to a definition", + `Quick, + () => { + let f = + Fixture.mk( + "let k = fun x -> x + 1 in theorem t = 7 + k(2) == 10 proof from k(2) do step end; step in t", + ); + let row = first(f.rows); + check( + underline, + "the call", + ("k(2)", 0), + underlined(Fixture.goal(f, row), row), + ); + }, + ), + test_case( + "the underline is found in a goal with ids of its own", + `Quick, + () => { + let f = + Fixture.mk( + "theorem t = (1 + 1) * (1 + 1) == 4 proof from 1 + 1 at 2 do step end; step in t", + ); + let row = first(f.rows); + let goal = + switch (row.goal, Rows.ctx(row)) { + | (Some(written), Some(ctx)) => + Picker.Goal.mk(~settings, ~ctx, Exp.replace_all_ids(written)) + | _ => Alcotest.fail("the row has no goal") + }; + check( + underline, + "the second 1 + 1", + ("(1 + 1)", 1), + underlined(goal, row), + ); + }, + ), + test_case( + "a step on the whole goal underlines all of it: eval, axiom, rewrite", + `Quick, + () => { + let whole = (src, named) => { + let f = Fixture.mk(src); + let row = + switch (List.find(~f=r => kind(r) == named, Fixture.all(f))) { + | Some(row) => row + | None => Alcotest.fail("no " ++ named ++ " row") + }; + check( + underline, + named, + (goal(row), 0), + underlined(Fixture.goal(f, row), row), + ); + }; + whole("theorem t = 4 == 4 proof step in t", "step"); + whole( + "theorem t = forall x: Int -> x == x proof forall x => rewrite refl end in t", + "refl", + ); + whole( + "theorem t = 4 / 2 == 2 proof algebra 2 == 2 end; step in t", + "algebra", + ); + }, + ), + test_case( + "a step that changes the goal's shape underlines nothing", + `Quick, + () => { + let f = + Fixture.mk( + "theorem t = forall x: Int -> x == x proof forall x => rewrite refl end in t", + ); + let row = first(f.rows); + check(string, "a forall", "forall", kind(row)); + check( + bool, + "nothing underlined", + true, + Picker.Goal.acts_on(Fixture.goal(f, row), row) == None, + ); + }, + ), + test_case( + "an occurrence with a hidden ascription underlines what it ascribes", + `Quick, + () => { + /* The checker's goal reads `x :: rev([]) : [Int]`, and the + * selector matches the ascription first. */ + let f = + Fixture.mk( + "let rev = fun xs -> case xs | [] => [] | x :: t => rev(t) @ [x] end in theorem t = forall x: Int -> [x] == x :: rev([]) proof forall x => from rev([]) do step end; ? in t", + ); + let row = + switch ( + List.find( + ~f= + (r: Rows.t) => + switch (r.step.term) { + | Focus(_) => true + | _ => false + }, + Fixture.all(f), + ) + ) { + | Some(row) => row + | None => Alcotest.fail("no focus row") + }; + let goal = Fixture.goal(f, row); + check( + bool, + "the checker selected the ascription", + true, + switch (row.goal, row.acts_on) { + | (Some(written), Some(part)) => + switch (Exp.find_by_id(part, written)) { + | Some({term: Asc(_), _}) => true + | _ => false + } + | _ => false + }, + ); + check( + option(string), + "the application, not its ascription", + Some("application"), + Picker.Goal.acts_on(goal, row) + |> Option.bind(_, ~f=id => Exp.find_by_id(id, goal.written)) + |> Option.map(~f=(e: Exp.t) => + switch (Exp.term_of(e)) { + | Ap(_) => "application" + | _ => print(e) + } + ), + ); + }, + ), + test_case( + "an occurrence inside a folded function underlines the fold", + `Quick, + () => { + let f = + Fixture.mk( + "theorem t = (fun x: Int -> x + 0) == (fun x: Int -> x) proof from x + 0 do algebra x end end; rewrite refl end in t", + ); + let row = first(f.rows); + let goal = Fixture.goal(f, row); + let term = Web.CodeEditable.Model.get_statics(goal.editor).term; + check( + option(string), + "a fold", + Some("fold"), + Picker.Goal.acts_on(goal, row) + |> Option.bind(_, ~f=id => Exp.find_by_id(id, term)) + |> Option.map(~f=(e: Exp.t) => + switch (Exp.term_of(e)) { + | Projector(_) => "fold" + | _ => print(e) + } + ), + ); + }, + ), + ]; +}; + +/* The page scrolls to the focused editor's caret after an update that + * asks it to. A click in the stepper leaves that caret where it was, so + * its updates mustn't ask, or the page jumps to a caret the user has + * scrolled away from. */ +/* What a write leaves for the next one: focus on the box where the proof + * goes on, open on the same tab. */ +module Writing = { + /* A theorem's cell, and the zipper of its program, which patches are + * written into. */ + type t = { + zipper: Zipper.t, + f: Fixture.t, + }; + + let check_zipper = + (~pending=false, ~name="t", zipper: Zipper.t, cell): Fixture.t => { + let statics = + Fixture.statics_of_term( + MakeTerm.from_zip_for_sem(zipper, ~root=Exp).term, + ); + Fixture.of_cell( + ~name, + statics, + Fixture.calculate(~pending, ~is_edited=true, statics, cell), + ); + }; + + let mk = (src: string): t => { + let zipper = Insertion.parse_zipper(src); + { + zipper, + f: check_zipper(zipper, Web.EvalResult.Model.init), + }; + }; + + /* Writes `patch` and checks the program again, keeping the steppers' + * state, as the page does. */ + let write = (~pending=false, w: t, patch): t => { + let zipper = EditorTransform.apply_patch(w.zipper, patch); + { + zipper, + f: check_zipper(~pending, zipper, w.f.cell), + }; + }; + + /* The row holding a box, the one a write from the box goes on at. */ + let box_row = (f: Fixture.t): Rows.t => + switch ( + List.filter( + ~f= + (row: Rows.t) => + switch (Stepper.Model.find(row.key, f.theorem.stepper)) { + | Some({box: Some(_), _}) => true + | _ => false + }, + Fixture.all(f), + ) + ) { + | [row] => row + | rows => + Alcotest.fail(string_of_int(List.length(rows)) ++ " rows with a box") + }; + + /* Takes the ghost at the box, as Tab does, giving the program after and + * the key focus moves to. */ + let tab = (w: t): (t, Rows.key) => { + let row = box_row(w.f); + switch (Stepper.Update.ghost(Fixture.goal(w.f, row))) { + | Some(ghost) => + let written = Picker.focused(ghost.pick); + let next = + switch (Stepper.Focus.after_write([written])) { + | Some(next) => next + | None => Alcotest.fail("no box to go on at") + }; + let w = { + ...w, + f: Fixture.act(w.f, (row.key, Wrote(next))), + }; + (write(w, Picker.Patches.write(row, written)), next); + | None => Alcotest.fail("no ghost") + }; + }; + + let box = (f: Fixture.t): Stepper.Model.box => + switch (Fixture.local(f, box_row(f)).box) { + | Some(box) => box + | None => Alcotest.fail("no box") + }; + + /* Types `text` into the box and runs its search to the end. */ + let type_ = (f: Fixture.t, text: string): Fixture.t => { + let key = box_row(f).key; + let rec run = (f, slices) => + slices > 1000 || !Stepper.Model.running(box(f)) + ? f + : run( + Fixture.act(f, (key, SearchSlice(box(f).generation))), + slices + 1, + ); + run(Fixture.act(f, (key, BoxEditor(Perform(Insert(text))))), 0); + }; + + let tests = [ + test_case( + "a search that finds nothing says so only once typing has paused", + `Quick, + () => { + let f = mk("theorem t = (1 + 1) * (2 + 0) == 4 proof ? in t").f; + let key = box_row(f).key; + let verdict = f => Stepper.View.Box.verdict(box(f)); + let f = type_(f, "2"); + check( + bool, + "the search found nothing", + true, + Option.map(~f=(s: Web.StepSearch.t) => s.status, box(f).search) + == Some(Web.StepSearch.NotFound), + ); + check( + bool, + "while typing", + true, + verdict(f) == Some(Web.StepSearch.Searching), + ); + let edits = box(f).edits; + let f = type_(f, "2"); + let f = Fixture.act(f, (key, Paused(edits))); + check( + bool, + "a pause after an earlier edit", + true, + verdict(f) == Some(Web.StepSearch.Searching), + ); + let f = Fixture.act(f, (key, Paused(box(f).edits))); + check( + bool, + "once paused", + true, + verdict(f) == Some(Web.StepSearch.NotFound), + ); + }, + ), + test_case( + "a typo above a theorem keeps its stepper and its state until it is fixed", + `Quick, + () => { + let w = mk("theorem t = (1 + 1) * (2 + 0) == 4 proof ? in t"); + let w = { + ...w, + f: type_(w.f, "4"), + }; + let edit = (actions, w: t) => { + let zipper = Test_Editing.perform(w.zipper, actions); + { + zipper, + f: check_zipper(zipper, w.f.cell), + }; + }; + let typo = [ + Action.Move(Start), + ...List.map( + ~f=c => Action.Insert(c), + ["e", "t", " ", "z", " ", "=", " ", "1", " ", "i", "n", " "], + ), + ]; + let broken = edit(typo, w); + check(bool, "stale", true, broken.f.theorem.stale != None); + check( + string, + "the box keeps its text", + "4", + Printer.of_zipper( + ~holes="?", + box(broken.f).editor.editor.state.zipper, + ), + ); + let fixed = + edit( + List.init(12, ~f=_ => Action.Destruct(Local(Left, ByChar))), + broken, + ); + check(bool, "not stale", true, fixed.f.theorem.stale == None); + check( + string, + "the box still has its text", + "4", + Printer.of_zipper( + ~holes="?", + box(fixed.f).editor.editor.state.zipper, + ), + ); + }, + ), + test_case( + "after each Tab, focus goes to the box where the proof goes on", + `Quick, + () => { + let w = mk("theorem t = (1 + 1) * (2 + 0) == 4 proof ? in t"); + let (w, next) = tab(w); + check(bool, "the first Tab's box", true, box_row(w.f).key == next); + let (w, next) = tab(w); + check(bool, "the second Tab's box", true, box_row(w.f).key == next); + check(string, "its goal", "2 * 2 == 4", goal(box_row(w.f))); + }, + ), + test_case( + "while a write is checked, its rows show the goal above and the box stays", + `Quick, + () => { + let w = mk("theorem t = (1 + 1) * (2 + 0) == 4 proof ? in t"); + let row = box_row(w.f); + let goal_before = goal(row); + let written = + switch (Stepper.Update.ghost(Fixture.goal(w.f, row))) { + | Some(ghost) => Picker.focused(ghost.pick) + | None => Alcotest.fail("no ghost") + }; + let patch = Picker.Patches.write(row, written); + let w = { + ...w, + f: + Fixture.act( + w.f, + ( + row.key, + Wrote( + Option.value_exn(Stepper.Focus.after_write([written])), + ), + ), + ), + }; + let checking = write(~pending=true, w, patch); + let row = box_row(checking.f); + let local = Fixture.local(checking.f, row); + check(bool, "checking", true, local.checking); + check( + string, + "the goal above", + goal_before, + print(local.goal.written), + ); + check( + bool, + "the box offers nothing", + true, + Option.bind(local.box, ~f=(box: Stepper.Model.box) => box.ghost) + == None, + ); + let checked = write(w, patch); + let local = Fixture.local(checked.f, box_row(checked.f)); + check(bool, "checked", false, local.checking); + check( + string, + "its own goal", + "(1 + 1) * 2 == 4", + goal(box_row(checked.f)), + ); + check( + bool, + "the box offers a step", + true, + Option.bind(local.box, ~f=(box: Stepper.Model.box) => box.ghost) + != None, + ); + }, + ), + test_case( + "a box written from on the Step tab is followed by one on the Step tab", + `Quick, + () => { + let w = mk("theorem t = (1 + 1) * (2 + 0) == 4 proof ? in t"); + let w = { + ...w, + f: Fixture.act(w.f, (box_row(w.f).key, Tab(Step))), + }; + let (w, _) = tab(w); + switch (Fixture.local(w.f, box_row(w.f)).box) { + | Some(box) => + check(bool, "on Step", true, box.tab == Some(Stepper.Model.Step)) + | None => Alcotest.fail("no box") + }; + }, + ), + test_case( + "a write that leaves holes goes on at the first of them", + `Quick, + () => { + let w = mk("theorem t = forall n : Int -> n == n proof ? in t"); + let row = box_row(w.f); + let written = + Proof.fresh( + Forall(Pat.fresh(Var("n")), Proof.fresh(EmptyHole)), + ); + let next = Stepper.Focus.after_write([written]); + let w = write(w, Picker.Patches.write(row, written)); + check(bool, "the body's box", true, Some(box_row(w.f).key) == next); + }, + ), + ]; +}; + +module Scrolling = { + let not_always = (updated: Web.Updated.t(_)) => + switch (updated.scroll) { + | Always => false + | IfCaretVisible + | Never => true + }; + + let tests = [ + test_case( + "the stepper's patch to the cell's program doesn't scroll to its caret", + `Quick, + () => { + let src = "theorem t = 1 + 1 == 2 proof ? in t"; + let z = Insertion.parse_zipper(src); + let patch = + EditorTransform.mk_proof_patch( + ~target_id=Proof.rep_id(Insertion.theorem_proof(z)), + Proof.fresh(EvalStep), + ); + check( + bool, + "PatchMainEditor", + true, + not_always( + Web.CellEditor.Update.update( + ~settings=Web.Settings.Model.init, + PatchMainEditor(patch), + Web.CellEditor.Model.mk(Editor.Model.mk(~root=Exp, z)), + ), + ), + ); + }, + ), + test_case( + "the cell stepper's toggle and patches don't scroll to a caret", + `Quick, + () => { + let statics = Fixture.statics("1 + 2 + 3"); + let cell = + Fixture.calculate( + ~is_edited=true, + statics, + Web.EvalResult.Model.init, + ); + let update = (action, cell) => + Web.EvalResult.Update.update( + ~settings=Web.Settings.Model.init, + action, + cell, + ); + let toggled = update(ToggleStepper, cell); + check(bool, "ToggleStepper", true, not_always(toggled)); + let cell = + Fixture.calculate(~is_edited=false, statics, toggled.model); + let stepper = + switch (cell.display) { + | Stepper(s) => s + | Evaluation(_) => Alcotest.fail("the stepper is off") + }; + let row = + last( + Rows.chain( + ~proof_map=stepper.proof_map, + Web.EvalResult.CellStepper.proof(stepper), + ), + ); + check( + bool, + "StepperPatch", + true, + not_always( + update( + StepperPatch( + Picker.Patches.write(row, Proof.fresh(EvalStep)), + ), + cell, + ), + ), + ); + }, + ), + test_case( + "the write box's tabs and list don't scroll to a caret", + `Quick, + () => { + let f = Fixture.mk("theorem t = 1 + 1 == 2 proof ? in t"); + let row = first(f.rows); + let update = action => + Stepper.Update.update( + ~settings=Web.Settings.Model.init, + (row.key, action), + f.theorem.stepper, + ); + List.iter( + ~f= + ((label, action)) => + check(bool, label, true, not_always(update(action))), + [ + ("Tab", Stepper.Update.Tab(Strategy)), + ("Choose", Choose(Some(0))), + ("SearchSlice", SearchSlice(0)), + ("Complete", Complete("refl")), + ], + ); + }, + ), + ]; +}; + +/* An offer writes a step that survives being printed into the program, + * read back and checked again, and names definitions as the goal does. */ +module Round_trip = { + let len = "let len = fun xs -> case xs | [] => 0 | x :: t => 1 + len(t) end in "; + + let has_fun = (text: string): bool => + Test_ProofMap.contains(text, "fun ") + || Test_ProofMap.contains(text, "fix "); + + /* `template` with its `%%` filled. */ + let fill = (template: string, text: string): string => + switch (String.split(template, ~on='%')) { + | [before, "", after] => before ++ text ++ after + | _ => Alcotest.fail("the template needs one %%") + }; + + /* The program with `step` written at `%%`, after checking that it + * names no function bodies. */ + let write = (template: string, step: Proof.t): string => { + let text = written(step); + check(bool, "written without bodies: " ++ text, false, has_fun(text)); + fill(template, text); + }; + + let check_clean = (src: string) => { + let (pm, proof) = Test_ProofMap.run_named("t", src); + check( + option(string), + "reread and rechecked\n" ++ src ++ "\n" ++ Test_ProofMap.dump(pm, proof), + None, + Test_ProofMap.find_marked_sub(pm, proof) + |> Option.map(~f=((_, marks)) => + marks |> List.map(~f=ProofMark.show) |> String.concat(~sep="; ") + ), + ); + (pm, proof); + }; + + let tests = [ + test_case( + "Tab's steps, written in turn, prove the theorem", + `Quick, + () => { + let template = + len + ++ "theorem t = forall y: Int -> forall ys: [Int] -> len(y :: ys) == 1 + len(ys) proof %% in t"; + let rec go = (steps, rounds) => { + let src = fill(template, String.concat(~sep="; ", steps @ ["?"])); + let f = Fixture.mk(src); + let goal = Fixture.goal(f, last(f.rows)); + switch (Picker.Ghost.mk(goal, ~selected=None)) { + | Some(ghost) when rounds > 0 => + let text = written(Picker.focused(ghost.pick)); + check( + bool, + "written without bodies: " ++ text, + false, + has_fun(text), + ); + go(steps @ [text], rounds - 1); + | _ => steps + }; + }; + let steps = go([], 4); + let src = fill(template, String.concat(~sep="; ", steps)); + let (pm, proof) = check_clean(src); + check( + string, + "proven by " ++ String.concat(~sep="; ", steps), + "Proven", + ProofMap.show_full_status( + ProofMap.full_status_of_proof(pm, proof), + ), + ); + }, + ), + ]; +}; + +/* Rows drawn again only when what they show changes. */ +module Redrawing = { + /* A row's goal editor drawn through Stepper.Drawn, as the stepper draws + * it, keeping the handlers its node was drawn with. */ + let draw = (~focused=false, row: Rows.t, local: Stepper.Model.local, signal) => { + let globals = Web.Globals.Model.init(); + let drawn_with = ref(None); + let _: Virtual_dom.Vdom.Node.t = + Stepper.Drawn.view( + row.key, + { + editor: { + editor: local.goal.editor, + deco: local.deco, + hints: true, + replacing: false, + previewing: false, + }, + focused, + settings: globals.settings, + font_metrics: globals.font_metrics, + meta_down: false, + color_highlights: None, + }, + { + signal, + inject: _ => Ui_effect.Ignore, + keys: _ => None, + }, + handlers => { + drawn_with := Some(handlers); + Virtual_dom.Vdom.Node.none; + }, + ); + drawn_with^; + }; + + let tests = [ + test_case( + "a row's goal is prepared again when a function its definitions call changes", + `Quick, + () => { + let src = g => + "let g = fun x -> " + ++ g + ++ " in let f = fun x -> g(x) in theorem t = f(1) == 2 proof ? in t"; + /* Whether the goal checked with `g` defined as `before` is kept + * when it is checked again with `g` defined as `after`. */ + let kept = (before, after) => { + let row = first(Fixture.mk(src(after)).rows); + switch (row.goal, Rows.ctx(row)) { + | (Some(written), Some(ctx)) => + let f = Fixture.mk(src(before)); + Picker.Goal.is_for( + Fixture.goal(f, first(f.rows)), + ~ctx, + written, + ); + | _ => Alcotest.fail("the row has no goal") + }; + }; + check(bool, "g the same", true, kept("x + 1", "x + 1")); + check(bool, "g changed", false, kept("x + 1", "x + 2")); + }, + ), + test_case( + "rows rebuilt from the same check keep their state's records", + `Quick, + () => { + let f = + Fixture.mk( + "theorem t = (1 + 1) * 2 == 4 proof from 1 + 1 do eval end in t", + ); + let again = + Stepper.Update.calculate( + ~settings=Web.Theorems.with_proof_settings(settings), + f.rows, + f.theorem.stepper, + ); + check( + list(bool), + "the same record", + List.map(~f=_ => true, Fixture.all(f)), + List.map( + ~f= + (row: Rows.t) => + switch ( + Stepper.Model.find(row.key, f.theorem.stepper), + Stepper.Model.find(row.key, again), + ) { + | (Some(before), Some(after)) => phys_equal(before, after) + | _ => false + }, + Fixture.all(f), + ), + ); + }, + ), + test_case( + "a click on a row's reused node acts through the latest render", + `Quick, + () => { + let f = Fixture.mk("theorem t = (1 + 1) * (2 + 0) == 4 proof ? in t"); + let row = last(f.rows); + let local = Fixture.local(f, row); + let taken = ref([]); + let take = (render, event: Web.StepperEditor.View.event) => + switch (event) { + | TakeStep(i) => + Ui_effect.of_sync_fun( + () => taken := [(render, i), ...taken^], + (), + ) + | MakeActive + | Refl(_) => Ui_effect.Ignore + }; + let first = + switch (draw(row, local, take("first"))) { + | Some(handlers) => handlers + | None => Alcotest.fail("the row wasn't drawn") + }; + check( + bool, + "the second render reuses the node", + true, + Option.is_none(draw(row, local, take("second"))), + ); + Virtual_dom.Vdom.Effect.Expert.handle_non_dom_event_exn( + first.signal(TakeStep(0)), + ); + check( + list(pair(string, int)), + "taken by", + [("second", 0)], + taken^, + ); + check( + bool, + "a change of focus draws the row again", + true, + Option.is_some(draw(~focused=true, row, local, take("third"))), + ); + }, + ), + ]; +}; + +let tests = ( + "StepperView", + Walk.tests + @ Scopes.tests + @ State.tests + @ Picking.tests + @ Regressions.tests + @ Display.tests + @ Round_trip.tests + @ Insertion.tests + @ Structure.tests + @ Focusing.tests + @ Focusing.generalizing_tests + @ Writing.tests + @ Scrolling.tests + @ Redrawing.tests, +); diff --git a/test/evaluator/Test_StructuralRecursion.re b/test/evaluator/Test_StructuralRecursion.re new file mode 100644 index 0000000000..4b1a4dbfbe --- /dev/null +++ b/test/evaluator/Test_StructuralRecursion.re @@ -0,0 +1,182 @@ +open Alcotest; +open Language; +open Test_ProofMap.Harness; + +/* Structural-recursion detection. + * + * StructuralRecursion.re recognizes fixpoints whose every recursive + * call passes, in one fixed argument position, a strict subterm of + * that position's parameter; Totality.re then lets such fixpoints (and + * their applications to total arguments) through the instantiation + * gate. Non-structural recursion must still be refused. */ + +/* The instantiation passes the gate silently: no divergence mark, no + * obligations, fully Proven. */ +let expect_pass = (src: string): unit => { + let (pm, proof, obs) = obligations(src); + Alcotest.check( + Alcotest.bool, + "no PossiblyDivergentInstantiation mark", + false, + has_mark_kind(pm, proof, is_divergent_instantiation), + ); + Alcotest.check(Alcotest.int, "zero obligations", 0, List.length(obs)); + Alcotest.check( + Alcotest.bool, + "fully Proven", + true, + Poly.equal(ProofMap.full_status_of_proof(pm, proof), ProofMap.Proven), + ); +}; + +/* The instantiation is refused: divergence mark, no obligations, not + * proven. */ +let expect_refused = (src: string): unit => { + let (pm, proof, obs) = obligations(src); + Alcotest.check( + Alcotest.bool, + "PossiblyDivergentInstantiation mark is emitted", + true, + has_mark_kind(pm, proof, is_divergent_instantiation), + ); + Alcotest.check( + Alcotest.int, + "a refused step incurs no obligations", + 0, + List.length(obs), + ); + Alcotest.check( + Alcotest.option(bool), + "the refused proof is not proven", + None, + ProofMap.status_of_proof(pm, proof), + ); +}; + +/* --- A Term-ADT decision procedure ------------------------------------ */ + +/* `size` recurses on constructor payloads, the classic metatheory + * shape. */ +let test_term_adt_size_passes = () => + expect_pass( + {|type Term = +Var(Int)+Lam(Term)+Ap(Term, Term) in let size = fun e -> case e | Var(n) => 1 | Lam(b) => 1 + size(b) | Ap(e1, e2) => 1 + size(e1) + size(e2) end in theorem t = forall x -> size(x) == size(x) proof from size(x) == size(x) do rewrite refl end end in t|}, + ); + +/* The same procedure written with surface `fix` (recursive `let`s + * elaborate to the same FixF; both spellings must pass). */ +let test_explicit_fix_passes = () => + expect_pass( + {|type Term = +Var(Int)+Lam(Term)+Ap(Term, Term) in let size = fix f -> fun e -> case e | Var(n) => 1 | Lam(b) => 1 + f(b) | Ap(e1, e2) => 1 + f(e1) + f(e2) end in theorem t = forall x -> size(x) == size(x) proof from size(x) == size(x) do rewrite refl end end in t|}, + ); + +/* --- List recursion (the Ex_ReverseReverse shapes) ---------------------- */ + +/* `snoc` recurses on the tail through `h :: t`; `rev` calls `snoc` + * (a nested, itself-structural fix after substitution) around its own + * structural call. */ +let test_snoc_rev_pass = () => + expect_pass( + {|let snoc = fun xs -> fun y -> case xs | [] => [y] | h :: t => h :: snoc(t)(y) end in let rev = fun l -> case l | [] => [] | h :: t => snoc(rev(t))(h) end in theorem t = forall x -> rev(x) == rev(x) proof from rev(x) == rev(x) do rewrite refl end end in t|}, + ); + +/* --- Depth: strict subterms through nested pattern layers -------------- */ + +/* `Ap(Lam(b), a)` binds `b` two constructor layers down; tracking is + * transitive, so `h(b)` passes. */ +let test_nested_pattern_depth_passes = () => + expect_pass( + {|type Term = +Var(Int)+Lam(Term)+Ap(Term, Term) in let h = fun e -> case e | Ap(Lam(b), a) => h(b) | Ap(e1, e2) => 0 | Lam(b) => 0 | Var(n) => 0 end in theorem t = forall x -> h(x) == h(x) proof from h(x) == h(x) do rewrite refl end end in t|}, + ); + +/* Casing on an already-strict variable: bindings stay strict + * (subterm-of-subterm), one case at a time. */ +let test_two_step_case_passes = () => + expect_pass( + {|type Term = +Var(Int)+Lam(Term)+Ap(Term, Term) in let h = fun e -> case e | Ap(l, a) => case l | Lam(b) => h(b) | Var(n) => 0 | Ap(e1, e2) => h(e1) end | Lam(b) => 0 | Var(n) => 0 end in theorem t = forall x -> h(x) == h(x) proof from h(x) == h(x) do rewrite refl end end in t|}, + ); + +/* --- Non-structural recursion is refused ----------------------------- */ + +/* `n - 1` is arithmetic, not a subterm. */ +let test_arithmetic_recursion_refused = () => + expect_refused( + {|let f = fun n -> if n > 0 then f(n - 1) else 0 in theorem t = f(1) == f(1) proof from f(1) == f(1) do rewrite refl end end in t|}, + ); + +/* `f(e)` passes the parameter itself, which is not strict. */ +let test_self_argument_refused = () => + expect_refused( + {|let f = fun e -> f(e) in theorem t = f(1) == f(1) proof from f(1) == f(1) do rewrite refl end end in t|}, + ); + +/* A reconstructed argument (`Ap(e1, e1)` builds a new term of the + * same size) is not a subterm. */ +let test_reconstructed_argument_refused = () => + expect_refused( + {|type Term = +Var(Int)+Lam(Term)+Ap(Term, Term) in let f = fun e -> case e | Var(n) => 0 | Lam(b) => f(b) | Ap(e1, e2) => f(Ap(e1, e1)) end in theorem t = f(Var(1)) == f(Var(1)) proof from f(Var(1)) == f(Var(1)) do rewrite refl end end in t|}, + ); + +/* Each call decreases somewhere, but not in one fixed position. */ +let test_inconsistent_positions_refused = () => + expect_refused( + {|let g = fun a -> fun b -> case a | [] => 0 | h :: t => case b | [] => g(t)(b) | j :: u => g(a)(u) end end in theorem t = g([1])([2]) == g([1])([2]) proof from g([1])([2]) == g([1])([2]) do rewrite refl end end in t|}, + ); + +/* Shadowing kills the strict-subterm status: `t` is rebound before + * the call. */ +let test_shadowed_subterm_refused = () => + expect_refused( + {|let s = fun l -> case l | [] => 0 | h :: t => let t = [] in s(t) end in theorem t = s([1]) == s([1]) proof from s([1]) == s([1]) do rewrite refl end end in t|}, + ); + +let tests = ( + "Evaluator.StructuralRecursion", + [ + test_case( + "Term-ADT size passes the instantiation gate", + `Quick, + test_term_adt_size_passes, + ), + test_case( + "explicit fix spelling passes", + `Quick, + test_explicit_fix_passes, + ), + test_case("snoc/rev list recursion passes", `Quick, test_snoc_rev_pass), + test_case( + "strict subterm through nested pattern layers passes", + `Quick, + test_nested_pattern_depth_passes, + ), + test_case( + "casing on an already-strict variable stays strict", + `Quick, + test_two_step_case_passes, + ), + test_case( + "arithmetic recursion is refused", + `Quick, + test_arithmetic_recursion_refused, + ), + test_case( + "passing the parameter itself is refused", + `Quick, + test_self_argument_refused, + ), + test_case( + "passing a re-constructed term is refused", + `Quick, + test_reconstructed_argument_refused, + ), + test_case( + "inconsistent decreasing positions are refused", + `Quick, + test_inconsistent_positions_refused, + ), + test_case( + "rebinding the subterm variable defeats the call", + `Quick, + test_shadowed_subterm_refused, + ), + ], +); diff --git a/test/evaluator/Test_SymbolicListBuiltins.re b/test/evaluator/Test_SymbolicListBuiltins.re new file mode 100644 index 0000000000..08cf99e2ba --- /dev/null +++ b/test/evaluator/Test_SymbolicListBuiltins.re @@ -0,0 +1,227 @@ +open Alcotest; +open Language; +open Test_Evaluator_Prelude; + +/* Symbolic list operators: `@` steps when its left side is in constructor + * form. + * + * A quantified `m: [Int]` is a `Var`, which never unboxes as a list + * literal, so if `@` needed both sides to be literals, `[] @ m` and + * `(y :: l) @ m` would be stuck inside a proof `step`. Instead `@` has + * defining equations, like the `case` a user-defined `append` would use: + * + * [] @ ys == ys + * (x :: xs) @ ys == x :: (xs @ ys) + * + * They fire whenever the left side is in constructor form and the right + * side is final. There is no rule for + * - the right unit `xs @ [] == xs`, which needs induction; or + * - a left side that is a bare variable or hole. + * + * Reuses the Test_ProofMap harness. */ + +let eval_with_proof = Test_ProofMap.eval_with_proof; +let proof_of = Test_ProofMap.proof_of; +let has_mark_kind = Test_ProofMap.has_mark_kind; + +let run = (src: string): (ProofMap.t, Proof.t) => { + let (state, _, elab) = src |> parse_exp |> eval_with_proof; + let pm = EvaluatorState.get_proof_map(state); + (pm, proof_of(elab)); +}; + +let full_status = (src: string): ProofMap.full_status => { + let (pm, proof) = run(src); + ProofMap.full_status_of_proof(pm, proof); +}; + +let check_status = (msg: string, expected: ProofMap.full_status, src: string) => { + let actual = full_status(src); + Alcotest.check( + Alcotest.bool, + msg ++ " (got: " ++ ProofMap.show_full_status(actual) ++ ")", + true, + Poly.equal(actual, expected), + ); +}; + +let nothing_to_step = (src: string): bool => { + let (pm, proof) = run(src); + has_mark_kind( + pm, + proof, + fun + | ProofMark.NothingToStep => true + | _ => false, + ); +}; + +/* --- 1. The two defining equations of `@` ----------------------------- */ + +/* `[] @ m == m` with `m` quantified: the right side is a variable that + * will never become a literal. */ +let test_append_nil_left = () => + check_status( + "`[] @ m` steps to `m` with m quantified", + ProofMap.Proven, + {|theorem t = forall m: [Int] -> [] @ m == m proof from [] @ m do step end; from m == m do rewrite refl end end in t|}, + ); + +/* `(y :: l) @ m == y :: (l @ m)`: both the cons tail and the right side are + * quantified variables, so nothing here can flatten to a literal. One step + * peels the cons. */ +let test_append_cons_left = () => + check_status( + "`(y :: l) @ m` peels to `y :: (l @ m)` with l, m quantified", + ProofMap.Proven, + {|theorem t = forall y: Int -> forall l: [Int] -> forall m: [Int] -> (y :: l) @ m == y :: (l @ m) proof from (y :: l) @ m do step end; from y :: (l @ m) == y :: (l @ m) do rewrite refl end end in t|}, + ); + +/* --- 2. The ground fast path ----------------------------------------- */ + +/* When both sides are literals, `@` concatenates in a single step to one + * literal rather than peeling one cons at a time. Eval and stepper tests + * depend on this shape. */ +let test_ground_concat_still_one_step = () => + check_status( + "`[1, 2] @ [3]` concatenates to a literal", + ProofMap.Proven, + {|theorem t = [1, 2] @ [3] == [1, 2, 3] proof from [1, 2] @ [3] do step end; from [1, 2, 3] == [1, 2, 3] do rewrite refl end end in t|}, + ); + +/* --- 3. What stays stuck --------------------------------------------- */ + +/* A bare variable on the left matches neither defining equation, so + * `m @ n` is stuck. (Closing `m @ n == m @ n` by reflexivity is a + * separate question, about totality.) */ +let test_var_left_is_stuck = () => + Alcotest.check( + Alcotest.bool, + "`m @ n` with both sides variables does not step", + true, + nothing_to_step( + {|theorem t = forall m: [Int] -> forall n: [Int] -> m @ n == m @ n proof from m @ n do step end; ? in t|}, + ), + ); + +/* The right unit is not a primitive step: `m @ []` needs induction on + * `m`. If this steps, `@` has a rule the small-step semantics can't + * justify. */ +let test_right_unit_is_stuck = () => + Alcotest.check( + Alcotest.bool, + "`m @ []` does not step (the right unit needs induction)", + true, + nothing_to_step( + {|theorem t = forall m: [Int] -> m @ [] == m proof from m @ [] do step end; ? in t|}, + ), + ); + +/* --- 4. `case`-defined list operations, for comparison ---------------- */ + +/* A user-defined `case` on a cons matches constructor form: the + * behaviour `@` shares. */ +let test_length_cons_proves = () => + check_status( + "a `case`-defined length proves its cons equation", + ProofMap.Proven, + {|let len = fun l -> case l | [] => 0 | h :: t => 1 + len(t) end in theorem t = forall h: Int -> forall t: [Int] -> len(h :: t) == 1 + len(t) proof from len(h :: t) do step end; from 1 + len(t) == 1 + len(t) do rewrite refl end end in t|}, + ); + +/* --- 5. The `append` builtin ----------------------------------------- + * + * `append` is `fun (xs, ys) -> xs @ ys` (BuiltinsList.re), so it needs one + * extra `step` to unfold the builtin and then uses the same equations. */ + +let test_append_nil_inherits = () => + check_status( + "`append([], m)` unfolds to `[] @ m` and then to `m`", + ProofMap.Proven, + {|theorem t = forall m: [Int] -> append([], m) == m proof from append([], m) do step; step end; rewrite refl end in t|}, + ); + +let test_append_cons_inherits = () => + check_status( + "`append(y :: l, m)` unfolds and peels to `y :: (l @ m)`", + ProofMap.Proven, + {|theorem t = forall y: Int -> forall l: [Int] -> forall m: [Int] -> append(y :: l, m) == y :: (l @ m) proof from append(y :: l, m) do step; step end; rewrite refl end in t|}, + ); + +/* --- 6. `fold_left`: steps, and names its recursive call --------------- + * + * `fold_left` is a HazelFn `case`, so a `step` on a cons steps, leaving + * the recursive call as `fold_left(t, f, f(a, h))`. With the function + * applied, the defining equation closes by reflexivity. */ + +let fold_left_cons_src = {|theorem t = forall h: Int -> forall t: [Int] -> forall a: Int -> fold_left(h :: t, fun (acc, x) -> acc + x, a) == fold_left(t, fun (acc, x) -> acc + x, a + h) proof from fold_left(h :: t, fun (acc, x) -> acc + x, a) do step end; from (fun (acc, x) -> acc + x)((a, h)) do step end; rewrite refl in t|}; + +let test_fold_left_cons_steps = () => + Alcotest.check( + Alcotest.bool, + "`fold_left` on a cons steps (it is a `case`, not a ListLit unbox)", + false, + nothing_to_step(fold_left_cons_src), + ); + +let test_fold_left_cons_closes = () => + check_status( + "fold_left's cons equation closes", + ProofMap.Proven, + fold_left_cons_src, + ); + +let tests = ( + "Evaluator.SymbolicListBuiltins", + [ + test_case( + "`[] @ m == m` proves for quantified m", + `Quick, + test_append_nil_left, + ), + test_case( + "`(y :: l) @ m == y :: (l @ m)` proves for quantified l, m", + `Quick, + test_append_cons_left, + ), + test_case( + "ground `[1, 2] @ [3]` concatenates to a literal in one step", + `Quick, + test_ground_concat_still_one_step, + ), + test_case( + "pin: `m @ n` with a variable on the left does not step", + `Quick, + test_var_left_is_stuck, + ), + test_case( + "pin: the right unit `m @ []` does not step", + `Quick, + test_right_unit_is_stuck, + ), + test_case( + "reference: a `case`-defined length proves its cons equation", + `Quick, + test_length_cons_proves, + ), + test_case( + "the `append` builtin steps too: `append([], m) == m`", + `Quick, + test_append_nil_inherits, + ), + test_case( + "the `append` builtin steps too: `append(y :: l, m) == y :: (l @ m)`", + `Quick, + test_append_cons_inherits, + ), + test_case( + "`fold_left` on a cons does step", + `Quick, + test_fold_left_cons_steps, + ), + test_case( + "fold_left's cons equation closes by eval and reflexivity", + `Quick, + test_fold_left_cons_closes, + ), + ], +); diff --git a/test/evaluator/Test_TheoremNamespace.re b/test/evaluator/Test_TheoremNamespace.re new file mode 100644 index 0000000000..06c6cc4892 --- /dev/null +++ b/test/evaluator/Test_TheoremNamespace.re @@ -0,0 +1,126 @@ +open Alcotest; +open Language; +open Test_Evaluator_Prelude; +open Test_ProofMap.Harness; + +/* The theorem namespace a proof is checked in is built during evaluation. + * Theorem scoping is lexical, so at each theorem it has to be the + * namespace the statics give the proof: the same theorems, shadowed and + * captured the same way. */ + +/* Each theorem's proof root, with the citable facts in its scope as + * (name, captured, shadowed): as the checker scoped it, and as the + * statics did. The builtin axioms are left out. */ +let scopes = (src: string) => { + let (state, statics, elab) = src |> parse_exp |> eval_with_proof; + let proof_map = EvaluatorState.get_proof_map(state); + let facts = (~captured=[], ctx) => + ProofCtx.of_theorem_ctx(~builtins=[], ~captured, ctx) + |> List.map(~f=(e: ProofCtx.entry) => + (e.name, e.is_captured, e.is_shadowed) + ); + let proofs = ref([]); + let _: Exp.t = + Exp.map_term( + ~f_exp= + (continue, e) => { + switch (Exp.term_of(e)) { + | Theorem({term: Var(name), _}, _, proof, _) => + proofs := [(name, Proof.rep_id(proof)), ...proofs^] + | _ => () + }; + continue(e); + }, + elab, + ); + List.rev_map( + ~f= + ((name, id)) => { + let checked = + ProofMap.lookup(id, proof_map) + |> Option.map(~f=(entry: ProofMap.entry) => + facts( + ~captured=entry.ctx.captured, + SemanticCtx.get_ctx(entry.ctx), + ) + ); + let static = + Statics.Map.lookup(id, statics) + |> Option.map(~f=info => facts(Info.ctx_of(info))); + (name, checked, static); + }, + proofs^, + ); +}; + +let fact = triple(string, bool, bool); + +let check_scopes = + (src, ~expected: list((string, list((string, bool, bool))))) => { + let sorted = l => List.sort(~compare=Poly.compare, l); + let scopes = scopes(src); + let as_scoped_by = side => + List.map( + ~f=((name, checked, static)) => (name, side(checked, static)), + scopes, + ) + |> sorted; + let expected = + List.map(~f=((name, facts)) => (name, Some(facts)), expected) + |> sorted; + let scope = list(pair(string, option(list(fact)))); + check( + scope, + "as the statics scope them", + expected, + as_scoped_by((_, static) => static), + ); + check( + scope, + "as the checker scopes them", + expected, + as_scoped_by((checked, _) => checked), + ); +}; + +let tests = ( + "TheoremNamespace", + [ + test_case("later theorems see earlier ones, innermost first", `Quick, () => + check_scopes( + "let x = 1 in theorem a = x == 1 proof ? in theorem b = x + 0 == 1 proof ? in theorem c = true proof ? in 0", + ~expected=[ + ("a", []), + ("b", [("a", false, false)]), + ("c", [("b", false, false), ("a", false, false)]), + ], + ) + ), + test_case("a theorem in a definition is out of scope after it", `Quick, () => + check_scopes( + "let y = (theorem a = 1 == 1 proof ? in 5) in theorem b = true proof ? in y", + ~expected=[("a", []), ("b", [])], + ) + ), + test_case("a theorem of the same name shadows", `Quick, () => + check_scopes( + "theorem a = 1 == 1 proof ? in theorem a = 2 == 2 proof ? in theorem c = true proof ? in 0", + ~expected=[ + ("a", []), + ("a", [("a", false, false)]), + ("c", [("a", false, false), ("a", false, true)]), + ], + ) + ), + test_case("rebinding a variable a theorem names captures it", `Quick, () => + check_scopes( + "let x = 1 in let z = 0 in theorem a = x == 1 proof ? in let z = 3 in theorem b = true proof ? in let x = 2 in theorem c = true proof ? in 0", + ~expected=[ + ("a", []), + ("b", [("a", false, false)]), + ("c", [("b", false, false), ("a", true, false)]), + ], + ) + ), + ], +); diff --git a/test/haz3ltest.re b/test/haz3ltest.re index 8f160bee03..bd483c90f3 100644 --- a/test/haz3ltest.re +++ b/test/haz3ltest.re @@ -1,5 +1,7 @@ open Junit_alcotest; +CasJs.install(); + Stdlib.Printexc.register_printer(exn => { switch (exn) { | Language.EvaluatorError.Exception(msg) => @@ -58,6 +60,7 @@ let (suite, exit_with_test_status) = @ Test_Evaluator.tests @ Test_Editing.tests @ Test_TypToSegment.tests + @ [Test_EditorTransform.tests] @ Test_Reassociate.tests @ Test_MultiProbe.tests @ [Test_SampleSelection.tests] @@ -80,15 +83,17 @@ let (suite, exit_with_test_status) = @ Test_RoundtripFuzz.tests @ Test_LocalReformat.tests @ Test_MatchExp.tests - @ [Test_ProofHacks.tests] + @ Test_MatchExp.pattern_tests + @ Test_ProofRuleMentions.tests + @ [Test_InductionWildcard.tests] @ Test_RefractorSerialization.tests @ [ Test_TableCore.tests, - Test_StepperPasses.tests, Test_TableTransforms.tests, Test_RichProbeRegistry.tests, ] @ Test_PrettyPrint.tests + @ Test_ProofLayout.tests @ Test_TyDi.tests @ [Test_Move.tests] @ [Test_UnusedWarnings.tests] @@ -120,7 +125,17 @@ let (suite, exit_with_test_status) = @ [Test_SettingsPanel.tests] @ Test_ShortcutAction.tests @ Test_Color.tests - @ [Test_ExplainThis.tests], + @ [Test_ExplainThis.tests] + @ [Test_SubEditor.tests] + @ [Test_ListCaseStep.tests] + @ [Test_ProofContext.tests] + @ [Test_NegativeSelector.tests] + @ [Test_DefinitionNames.tests] + @ [Test_ProverKnownBugs.tests] + @ [Test_ProverDocs.tests] + @ [Test_TheoremNamespace.tests] + @ [Test_CheckedProofs.tests] + @ [Test_AlgebraSteps.tests], ); Junit.to_file(Junit.make([suite]), "junit_tests.xml"); Bisect.Runtime.write_coverage_data(); diff --git a/test/idb_stub.js b/test/idb_stub.js index 41e3cf8402..7d4ffb2f20 100644 --- a/test/idb_stub.js +++ b/test/idb_stub.js @@ -1,5 +1,6 @@ -// Minimal stubs for browser globals needed by Ezjs_idb module initialization. -// The test suite runs in Node.js which lacks these browser APIs. +// The browser globals the test suite needs, which Node.js lacks: minimal +// stubs for Ezjs_idb's module initialization, and the Algebrite the page +// and the worker load, which the proof checker verifies algebra with. if (typeof window === "undefined") { globalThis.window = globalThis; } @@ -14,3 +15,6 @@ if (typeof IDBKeyRange === "undefined") { if (typeof indexedDB === "undefined") { globalThis.indexedDB = {open: () => ({result: null})}; } +if (typeof Algebrite === "undefined") { + globalThis.Algebrite = require("algebrite"); +} diff --git a/test/run_node.sh b/test/run_node.sh index f836926536..628e2e690f 100755 --- a/test/run_node.sh +++ b/test/run_node.sh @@ -15,6 +15,29 @@ export QCHECK_SEED="${QCHECK_SEED:-42}" # (e.g., Pattern Coverage Checker) # --require idb_stub.js: provide minimal IndexedDB globals for Node.js # (Ezjs_idb captures IDBKeyRange at module init time) +# +# What --stack-size hides +# +# A browser gives the page about 1MB of JS stack, and a Web Worker (where +# the evaluator runs, see src/web/util/WorkerServer.re) less; neither is +# adjustable. So 8MB here hides any recursion that fits in 8MB but +# overflows in the editor. +# +# It can't be lowered to browser size: alcotest walks the test list with +# a non-tail-recursive bind, so the runner itself overflows below about +# 2048 (it fails at 1536), whatever NAME_REGEX you pass. Pattern Coverage +# passes at 2048, so 2048 is the lowest this could go, but that leaves no +# headroom for new tests; trying it needs a full suite run. +# +# To check browser-stack behaviour, use the CLI, which runs the same +# parse -> statics -> elaborate -> evaluate pipeline without alcotest: +# +# dune build src/CLI/cli.bc.js --profile dev +# node --stack-size=984 --require src/CLI/polyfill.js \ +# _build/default/src/CLI/cli.bc.js run docs/stlc-progress-example.hazel +# +# Walk --stack-size down to find the headroom; node prints the top frames +# of the RangeError, which name the recursion. if [ -z "$IDB_STUB" ] || [ -z "$TEST_JS" ]; then BUILD_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/../_build/default/test" && pwd)" diff --git a/test/statics/Test_Statics.re b/test/statics/Test_Statics.re index 770241e54f..a206376730 100644 --- a/test/statics/Test_Statics.re +++ b/test/statics/Test_Statics.re @@ -16,4 +16,7 @@ let tests = Test_Statics_Fixpoint.tests, Test_Statics_Properties.tests, Test_Statics_Parens.tests, + Test_Statics_Proof.tests, + Test_Statics_DynamicError.tests, + Test_Statics_Noncomputable.tests, ]; diff --git a/test/statics/Test_Statics_DynamicError.re b/test/statics/Test_Statics_DynamicError.re new file mode 100644 index 0000000000..2f96c728f0 --- /dev/null +++ b/test/statics/Test_Statics_DynamicError.re @@ -0,0 +1,62 @@ +open Alcotest; +open Test_Statics_Prelude; +open Language; + +/* Statics attaches a `Mark.DynamicError` for a `DynamicErrorHole` to the + *inner* expression's info entry: printing strips the DynamicErrorHole + wrapper, so only inner ids appear in rendered syntax and can carry the + error decoration (shards, cursor inspector, problem sidebar). */ + +let is_dynamic_error = + fun + | Mark.DynamicError(_) => true + | _ => false; + +let test_mark_attaches_to_inner_expression = () => { + let inner = parse_exp("1 + 1"); + let e = Exp.fresh(DynamicErrorHole(inner, DivideByZero)); + let map = statics(e); + let inner_marks = + switch (Statics.Map.lookup(Exp.rep_id(inner), map)) { + | Some(info) => Info.marks_of(info) + | None => Alcotest.fail("no info entry for the inner expression") + }; + Alcotest.check( + bool, + "inner expression carries the DynamicError mark", + true, + List.exists(~f=is_dynamic_error, inner_marks), + ); +}; + +let test_no_mark_without_error_hole = () => { + let e = parse_exp("1 + 1"); + let map = statics(e); + Alcotest.check( + bool, + "plain expression carries no DynamicError mark", + true, + ! + Id.Map.exists( + (_, info: Info.t) => + List.exists(~f=is_dynamic_error, Info.marks_of(info)), + map, + ), + ); +}; + +let tests = ( + "Statics_DynamicError", + [ + test_case( + "DynamicErrorHole marks its inner expression", + `Quick, + test_mark_attaches_to_inner_expression, + ), + test_case( + "no DynamicError mark on plain expressions", + `Quick, + test_no_mark_without_error_hole, + ), + ], +); diff --git a/test/statics/Test_Statics_Noncomputable.re b/test/statics/Test_Statics_Noncomputable.re new file mode 100644 index 0000000000..8fb623eff2 --- /dev/null +++ b/test/statics/Test_Statics_Noncomputable.re @@ -0,0 +1,269 @@ +open Alcotest; +open Test_Statics_Prelude; +open Language; + +/* Non-computable forms: `forall` is a proposition, and `==` / `!=` at a + type containing a function has no evaluation semantics. Inside a theorem's statement or proof they are + legal; outside they are warnings, not marks. */ + +let warnings = (map: Statics.Map.t): list(Warning.list_item) => + Id.Map.fold( + (_, info: Info.t, acc) => Info.warnings_of(info) @ acc, + map, + [], + ); + +let is_forall_warning = + fun + | Warning.Exp(ForallOutsideTheorem) => true + | _ => false; + +let compare_fun_errors = (map: Statics.Map.t): int => + errors(map) + |> List.concat_map(~f=snd) + |> List.filter( + ~f= + fun + | Mark.CompareFun(_) => true + | _ => false, + ) + |> List.length; + +let count = (pred, map) => + List.length(List.filter(~f=pred, warnings(map))); + +let expects_warning = + (name: string, source: string, pred: Warning.list_item => bool) => + test_case( + name, + `Quick, + () => { + let s = statics(parse_exp(source)); + Alcotest.check(bool, name, true, count(pred, s) > 0); + }, + ); + +let expects_no_warning = + (name: string, source: string, pred: Warning.list_item => bool) => + test_case( + name, + `Quick, + () => { + let s = statics(parse_exp(source)); + Alcotest.check(int, name, 0, count(pred, s)); + }, + ); + +/* --- stepper path ------------------------------------------------- + A stepper / eval-result editor re-runs statics on an already-evaluated + term, which may have come out of a theorem's statement or proof. Those + editors pass `is_dynamic_term=true`, which threads through to + `Statics.mk(~in_theorem=true, ...)`, so the non-computable warnings must + stay quiet there. The cell editor (`is_dynamic_term=false`) keeps warning. */ + +let statics_stepper = term => + fst( + Statics.mk( + ~in_theorem=true, + CoreSettings.on, + Builtins.ctx_init(Some(Int)), + term, + ), + ); + +let statics_cached_stepper = term => { + let s = + Haz3lcore.CachedStatics.init_from_term( + ~settings=CoreSettings.on, + ~is_dynamic_term=true, + term, + ); + s.info_map; +}; + +let expects_no_warning_via = + ( + statics_of: Exp.t => Statics.Map.t, + name: string, + source: string, + pred: Warning.list_item => bool, + ) => + test_case( + name, + `Quick, + () => { + let s = statics_of(parse_exp(source)); + Alcotest.check(int, name, 0, count(pred, s)); + }, + ); + +/* Whether comparing functions is reported as a type error. */ +let expects_compare_fun_via = + ( + statics_of: Exp.t => Statics.Map.t, + name: string, + source: string, + expected: bool, + ) => + test_case( + name, + `Quick, + () => { + let s = statics_of(parse_exp(source)); + Alcotest.check(bool, name, expected, compare_fun_errors(s) > 0); + }, + ); + +/* No expression anywhere in the program carries a mark. */ +let expects_no_errors = (name: string, source: string) => + test_case( + name, + `Quick, + () => { + let s = statics(parse_exp(source)); + let marks = List.map(~f=snd, errors(s)); + Alcotest.check( + list(testable_issue), + name, + [], + List.map(~f=ms => Marks(ms), marks), + ); + }, + ); + +let tests = ( + "Statics.Noncomputable", + [ + /* --- `forall` outside a theorem ---------------------------------- */ + expects_warning( + "bare forall warns", + {|forall x -> x == x|}, + is_forall_warning, + ), + /* Int `==` is computable: no function-comparison error. */ + expects_compare_fun_via( + statics, + "bare forall over Int == is not a function comparison", + {|forall x -> x == x|}, + false, + ), + expects_no_errors("bare forall is not an error", {|forall x -> x == x|}), + expects_warning( + "forall in a let body warns", + {|let p = forall x -> x == x in p|}, + is_forall_warning, + ), + /* --- `forall` inside a theorem ------------------------------------ */ + expects_no_warning( + "forall in a theorem statement is quiet", + {|theorem t = forall x -> x == x proof from x == x do rewrite refl end end in 0|}, + is_forall_warning, + ), + expects_no_errors( + "forall in a theorem statement is not an error", + {|theorem t = forall x -> x == x proof from x == x do rewrite refl end end in 0|}, + ), + /* The continuation after `in` is ordinary code, so a `forall` there + still warns even though it sits inside a `theorem` term. */ + expects_warning( + "forall in the theorem continuation warns", + {|theorem t = true proof ? in forall x -> true|}, + is_forall_warning, + ), + /* --- function equality outside a theorem -------------------------- */ + expects_compare_fun_via( + statics, + "function == outside a theorem is a type error", + {|(fun x -> x) == (fun x -> x)|}, + true, + ), + /* `!=` shares the DefinedPoly path with `==`. */ + expects_compare_fun_via( + statics, + "function != outside a theorem is a type error", + {|(fun x -> x) != (fun x -> x)|}, + true, + ), + /* --- function equality inside a theorem (the funext pin) ---------- */ + expects_no_errors( + "function == in a theorem statement is not an error", + {|theorem t = (fun x -> x + 1) == (fun x -> 1 + x) proof ? in 0|}, + ), + /* --- nesting ------------------------------------------------------- */ + /* The inner theorem's own statement is quiet; the program-level + `forall` in the outer let-binding still warns. Exactly one warning. */ + test_case( + "nested theorem: only the outer forall warns", + `Quick, + () => { + let src = {|let p = forall x -> x == x in theorem t = forall y -> y == y proof ? in 0|}; + let s = statics(parse_exp(src)); + Alcotest.check(int, src, 1, count(is_forall_warning, s)); + }, + ), + /* A `forall` in a proof (here, an `on` target inside an axiom step) is + inside the theorem block and must not warn. */ + expects_no_warning( + "forall inside a proof is quiet", + {|theorem t = true proof from (forall x -> x == x) do rewrite refl end end in 0|}, + is_forall_warning, + ), + /* --- stepper editors count as inside a theorem -------------------- */ + expects_no_warning_via( + statics_stepper, + "stepper: bare forall is quiet", + {|forall x -> x == x|}, + is_forall_warning, + ), + expects_compare_fun_via( + statics_stepper, + "stepper: function == is not an error", + {|(fun x -> x) == (fun x -> x)|}, + false, + ), + expects_compare_fun_via( + statics_stepper, + "stepper: function != is not an error", + {|(fun x -> x) != (fun x -> x)|}, + false, + ), + /* Same, through the editor-facing entry point the stepper actually + uses (`CachedStatics.init_from_term(~is_dynamic_term=true)`). */ + expects_no_warning_via( + statics_cached_stepper, + "stepper (cached): bare forall is quiet", + {|forall x -> x == x|}, + is_forall_warning, + ), + expects_compare_fun_via( + statics_cached_stepper, + "stepper (cached): function == is not an error", + {|(fun x -> x) == (fun x -> x)|}, + false, + ), + /* The memo cache key includes `in_theorem`, so a stepper result must + not silence the cell editor for the same term (or vice versa). */ + test_case( + "cell path still warns after the stepper path is cached", + `Quick, + () => { + let src = {|forall x -> x == x|}; + let e = parse_exp(src); + let quiet = statics_stepper(e); + Alcotest.check( + int, + "stepper quiet", + 0, + count(is_forall_warning, quiet), + ); + let loud = statics(e); + Alcotest.check( + bool, + "cell warns", + true, + count(is_forall_warning, loud) > 0, + ); + }, + ), + ], +); diff --git a/test/statics/Test_Statics_Prelude.re b/test/statics/Test_Statics_Prelude.re index aa25eb7269..8cb2052498 100644 --- a/test/statics/Test_Statics_Prelude.re +++ b/test/statics/Test_Statics_Prelude.re @@ -46,7 +46,6 @@ let rec equal_mark: (Mark.t, Mark.t) => bool = j1 == j2 && List.equal(source_equal, s1, s2) | (DuplicateLabel(l1, t1), DuplicateLabel(l2, t2)) => String.equal(l1, l2) && Typ.fast_equal(t1, t2) - | (CompareFun(t1), CompareFun(t2)) => Typ.fast_equal(t1, t2) | (DuplicateVar(n1, t1), DuplicateVar(n2, t2)) => String.equal(n1, n2) && Typ.fast_equal(t1, t2) | (BadToken(s1), BadToken(s2)) => String.equal(s1, s2) @@ -74,6 +73,7 @@ let rec equal_mark: (Mark.t, Mark.t) => bool = && i1 == i2 && Typ.fast_equal(t1, t2) | (IsMulti, IsMulti) => true + | (CompareFun(t1), CompareFun(t2)) => Typ.fast_equal(t1, t2) | (FreeConstructor(c1), FreeConstructor(c2)) => Constructor.equal(c1, c2) | (ExplicitNonlabel, ExplicitNonlabel) => true | ( diff --git a/test/statics/Test_Statics_Proof.re b/test/statics/Test_Statics_Proof.re new file mode 100644 index 0000000000..93dab66a7f --- /dev/null +++ b/test/statics/Test_Statics_Proof.re @@ -0,0 +1,381 @@ +open Alcotest; +open Test_Statics_Prelude; +open Language; + +/* Helpers to check that the statics result for a given program + contains a mark matching a supplied predicate, or that it contains + no errors of interest. */ +let has_mark = (pred: Mark.t => bool, map: Statics.Map.t): bool => + Id.Map.exists( + (_, info: Info.t) => List.exists(~f=pred, Info.marks_of(info)), + map, + ); + +let no_mark = (pred: Mark.t => bool, map: Statics.Map.t): bool => + !has_mark(pred, map); + +let expects_mark = (name: string, source: string, pred: Mark.t => bool) => + test_case( + name, + `Quick, + () => { + let exp = parse_exp(source); + let s = statics(exp); + Alcotest.check(bool, name, true, has_mark(pred, s)); + }, + ); + +let expects_no_mark = (name: string, source: string, pred: Mark.t => bool) => + test_case( + name, + `Quick, + () => { + let exp = parse_exp(source); + let s = statics(exp); + Alcotest.check(bool, name, true, no_mark(pred, s)); + }, + ); + +let is_free_hyp = + fun + | Mark.FreeHypothesis(_) => true + | _ => false; + +let is_axiom_slot_error = + fun + | Mark.AxiomSlotNotHypothesis(_) => true + | _ => false; + +let is_free_var = + fun + | Mark.Free(_) => true + | _ => false; + +let is_expectation_mismatch = + fun + | Mark.ExpectationMismatch(_) => true + | _ => false; + +let is_redundant = + fun + | Mark.Redundant => true + | _ => false; + +let is_inexhaustive = + fun + | Mark.InexhaustiveMatch(_) => true + | _ => false; + +/* Hovering `name` in the program: its info has no marks and + its scope has `name` as a fact. */ +let cites_fact_in_scope = (name: string, source: string) => + test_case( + "hovering `" ++ name ++ "` resolves it as a fact in scope", + `Quick, + () => { + let m = statics(parse_exp(source)); + let hovered = + Id.Map.fold( + (_, info: Info.t, found) => + switch (found, info) { + | (None, InfoExp({user_term: {term: Var(x), _}, _} as e)) + when String.equal(x, name) => + Some(e) + | _ => found + }, + m, + None, + ); + switch (hovered) { + | None => Alcotest.fail("no `" ++ name ++ "` in the program") + | Some(e) => + Alcotest.(check(list(string)))( + "no marks", + [], + List.map(~f=Mark.show, e.marks), + ); + Alcotest.check( + bool, + "a fact in scope", + true, + Option.is_some(Ctx.lookup_theorem(e.ctx, name)), + ); + }; + }, + ); + +/* A list split, `induction` or `cases`, whose cons case cites `fact`. */ +let snoc_citing = (~split="induction", fact) => + {|theorem t = forall xs: [Int] -> forall x: Int -> xs @ [x] == xs @ [x] proof |} + ++ split + ++ {| xs | [] => ? | y :: rest => from rest @ [x] do rewrite |} + ++ fact + ++ {| end end end in t|}; + +let tests = ( + "Statics.Proof", + [ + /* Built-in axiom `refl` is a hypothesis, so an axiom step + referring to it should not produce a FreeHypothesis mark. */ + expects_no_mark( + "rewrite refl is a known hypothesis", + {|theorem t = true proof from 1 do rewrite refl end end in t|}, + is_free_hyp, + ), + /* A completely unknown name in the axiom equality slot should + trigger FreeHypothesis. */ + expects_mark( + "rewrite bogus is a free hypothesis", + {|theorem t = true proof from 1 do rewrite bogus end end in t|}, + is_free_hyp, + ), + /* `forall x => ...`: `x` should be visible as a variable, + not as a hypothesis. */ + expects_no_mark( + "forall binds a variable visible in body", + {|theorem t = true proof forall x => from x do rewrite refl end end in 0|}, + is_free_var, + ), + /* The theorem introduces the goal's outer `forall`-bound variables + into the proof scope, so referencing `x` in the proof of + `forall x -> x == x` is not a free variable. */ + expects_no_mark( + "theorem goal forall var is visible in proof", + {|theorem t = forall x -> x == x proof from x == x do rewrite refl end end in 0|}, + is_free_var, + ), + /* Proof induction must be exhaustive: a list induction with only the + empty-list case is inexhaustive, even when the scrutinee is an + unannotated forall variable (type Unknown refined from the patterns). */ + expects_mark( + "induction on unannotated forall var flags inexhaustive", + {|theorem t = forall xs -> xs == xs proof induction xs | [] => ? end in t|}, + is_inexhaustive, + ), + /* Covering both list constructors is exhaustive (no mark). */ + expects_no_mark( + "induction covering [] and :: is exhaustive", + {|theorem t = forall xs -> xs == xs proof induction xs | [] => ? | y :: ys => ? end in t|}, + is_inexhaustive, + ), + /* A proof induction with no cases proves nothing -> inexhaustive. */ + expects_mark( + "induction with no cases flags inexhaustive", + {|theorem t = forall xs -> xs == xs proof induction xs end in t|}, + is_inexhaustive, + ), + /* Induction with two identical patterns should flag redundancy. */ + expects_mark( + "induction flags redundant rows", + {|theorem t = true proof induction 1 | 1 => ? | 1 => ? end in t|}, + is_redundant, + ), + /* Induction with a non-exhaustive match should flag inexhaustiveness. */ + expects_mark( + "induction flags inexhaustive match", + {|theorem t = true proof induction 1 | 0 => ? end in t|}, + is_inexhaustive, + ), + expects_mark( + "cases flags inexhaustive match", + {|theorem t = true proof cases 1 | 0 => ? end in t|}, + is_inexhaustive, + ), + /* `assume` introduces a hypothesis citable in its body: an axiom step + naming the generated hypothesis (`assume`) is not a free + hypothesis. */ + expects_no_mark( + "assume body sees the hypothesis", + {|theorem t = 1 == 1 proof assume 2 == 2 => from 2 do rewrite assume end end in t|}, + is_free_hyp, + ), + /* The assumption analyzes against Bool: a non-bool assumption is a + static type error. */ + expects_mark( + "non-bool assumption flags a type error", + {|theorem t = 1 == 1 proof assume 5 => ? in t|}, + is_expectation_mismatch, + ), + /* ...and a boolean assumption is not. */ + expects_no_mark( + "bool assumption has no type error", + {|theorem t = 1 == 1 proof assume 2 == 2 => ? in t|}, + is_expectation_mismatch, + ), + /* --- Implication ------------------------------------------------- */ + /* `==>` types Bool × Bool → Bool: boolean operands are fine... */ + expects_no_mark( + "==> accepts boolean operands", + {|theorem t = true ==> true proof ? in t|}, + is_expectation_mismatch, + ), + /* ...non-boolean ones are a type error. */ + expects_mark( + "==> rejects non-boolean operands", + {|theorem t = 5 ==> true proof ? in t|}, + is_expectation_mismatch, + ), + /* --- Proofs are not values --------------------------------------- + Theorems, axioms and hypotheses live in their own context + namespace, like type aliases. */ + /* (a) A theorem name is not a value, so naming it in expression + position is a free variable. */ + expects_mark( + "a theorem name in expression position is free", + {|theorem t = true proof ? in t|}, + is_free_var, + ), + /* (b) ...so a `let` and a `theorem` of the same name don't collide: + `t` in the body is the value 5, not the theorem. */ + expects_no_mark( + "let-bound name and theorem name do not collide", + {|let t = 5 in theorem t = true proof ? in t|}, + is_free_var, + ), + /* (c) ...and a later `let` of the same name doesn't hide the theorem + from a `rewrite` slot, which looks the name up in the theorem + namespace. */ + expects_no_mark( + "citation finds a theorem shadowed by a later value binding", + {|theorem lem = 1 == 1 proof ? in let lem = 5 in theorem g = true proof from 1 do rewrite lem end end in lem|}, + is_free_hyp, + ), + /* (d) Hypotheses are invisible to expressions for the same reason: + the auto-named `assume` hypothesis is citable in a proof but is + not a variable of the program. */ + expects_mark( + "an assume hypothesis is not an expression variable", + {|theorem t = 1 == 1 proof assume 2 == 2 => ? in assume|}, + is_free_var, + ), + /* --- Hypothesis naming, at edit time ------------------------------ + The statics installs a fact's name in the theorem namespace, so a + citation of it resolves while the user types, not only when the + checker runs. */ + expects_no_mark( + "an assume's name is a known hypothesis at edit time", + {|theorem t = forall n -> n == n proof assume h = n == 1 => from n do rewrite h end end in t|}, + is_free_hyp, + ), + /* A fact's name binds only in the theorem namespace: like the + auto-named ones, it is not a variable of the program. */ + expects_mark( + "a fact's name is not an expression variable", + {|theorem t = 1 == 1 proof assume h = 2 == 2 => ? in h|}, + is_free_var, + ), + /* `alias` re-binds an in-scope fact under a second name, and the + body sees it. */ + expects_no_mark( + "an alias name is a known hypothesis at edit time", + {|theorem t = forall n -> n == n proof assume n == 1 => alias h = assume => from n do rewrite h end end in t|}, + is_free_hyp, + ), + /* The alias's fact slot is a fact reference, not a program variable: + a bare name there must not read as free. (The body is `0`, not + `t`: a theorem's own name is free in expression position, as + tested above, and would mask this.) */ + expects_no_mark( + "an alias's fact slot resolves a hypothesis name", + {|theorem t = forall n -> n == n proof assume n == 1 => alias h = assume => ? in 0|}, + is_free_var, + ), + /* ...and aliasing a name that is not a fact does mark. */ + expects_mark( + "aliasing an unknown name marks at edit time", + {|theorem t = forall n -> n == n proof alias h = nosuchfact => ? in t|}, + is_free_hyp, + ), + /* --- The facts a split's case installs --------------------------- + A case body sees what `ProofCheck.check_split` gives it: in an + `induction`, an `ih_` per recursive position, and in a + `cases`, the case equation. */ + expects_no_mark( + "`ih_rest` is in scope in a recursive case", + snoc_citing("ih_rest"), + is_free_hyp, + ), + cites_fact_in_scope("ih_rest", snoc_citing("ih_rest")), + expects_mark( + "`ih_rest` is not in scope in a base case", + {|theorem t = forall xs: [Int] -> xs == xs proof induction xs | [] => from xs do rewrite ih_rest end end | y :: rest => ? end in t|}, + is_free_hyp, + ), + expects_no_mark( + "`case_eq` is in scope in a `cases` case", + snoc_citing(~split="cases", "case_eq"), + is_free_hyp, + ), + cites_fact_in_scope("case_eq", snoc_citing(~split="cases", "case_eq")), + expects_mark( + "`case_eq` is not in scope in an `induction` case", + snoc_citing("case_eq"), + is_free_hyp, + ), + expects_mark( + "`ih_rest` is not in scope in a `cases` case", + snoc_citing(~split="cases", "ih_rest"), + is_free_hyp, + ), + /* An induction case is about a fresh value in the scrutinee's place, + so a fact about the scrutinee is out of scope there. */ + expects_mark( + "an `induction` case can't cite a fact about the scrutinee", + {|theorem t = forall xs: [Int] -> xs == [] ==> xs == xs proof assume xs == [] => induction xs | [] => from xs do rewrite assume end end | y :: rest => ? end in t|}, + is_free_hyp, + ), + expects_no_mark( + "a `cases` case can cite a fact about the scrutinee", + {|theorem t = forall xs: [Int] -> xs == [] ==> xs == xs proof assume xs == [] => cases xs | [] => from xs do rewrite assume end end | y :: rest => ? end in t|}, + is_free_hyp, + ), + expects_no_mark( + "an `induction` case can cite a fact that doesn't mention the scrutinee", + {|theorem t = forall xs: [Int] -> forall n: Int -> n == 1 ==> xs == xs proof assume n == 1 => induction xs | [] => from n do rewrite assume end end | y :: rest => ? end in t|}, + is_free_hyp, + ), + /* The case equation `xs == y :: xs` would mention the pattern's own + `xs`, not the scrutinee, so the checker doesn't install it. */ + expects_mark( + "no `case_eq` when the pattern rebinds the scrutinee", + {|theorem t = forall xs: [Int] -> xs == xs proof cases xs | [] => ? | y :: xs => from xs do rewrite case_eq end end end in t|}, + is_free_hyp, + ), + /* `generalize x` makes `x` arbitrary again, so the facts about the + old `x` leave scope, as in the checker. */ + expects_mark( + "generalize hides the facts about its variable", + {|theorem t = forall x: Int -> x > 0 ==> x + 0 == x proof assume x > 0 => generalize x => revert assume => ? in t|}, + is_free_hyp, + ), + expects_mark( + "an unknown name in a case still errors", + snoc_citing("nosuchfact"), + is_free_hyp, + ), + /* --- Other forms that extend a body's scope ---------------------- */ + expects_no_mark( + "a `have` body sees the hypothesis", + {|theorem t = 1 == 1 proof have 2 == 2 proof ? => from 1 do rewrite have end end in t|}, + is_free_hyp, + ), + /* The subproof proves the `have`; it can't cite it. */ + expects_mark( + "a `have` subproof doesn't see the hypothesis", + {|theorem t = 1 == 1 proof have 2 == 2 proof from 2 do rewrite have end end => ? in t|}, + is_free_hyp, + ), + /* `x` is bound by the goal's `fun x ->` around the focused `x + 0`, + which the checker brings into the focus body's scope. */ + expects_no_mark( + "a focus body sees a binder its selector names", + {|theorem t = (fun x -> x + 0) == (fun x -> x) proof from x + 0 do algebra x end end; ? in 0|}, + is_free_var, + ), + expects_mark( + "a focus body's binder names don't escape it", + {|theorem t = (fun x -> x + 0) == (fun x -> x) proof from x + 0 do algebra x end end; algebra x in 0|}, + is_free_var, + ), + ], +); From b990e344d61f3c8a6eaf31350a945eeb7d8a8d2c Mon Sep 17 00:00:00 2001 From: Matt Keenan <31668468+Negabinary@users.noreply.github.com> Date: Fri, 20 Nov 2026 10:21:21 -0500 Subject: [PATCH 2/2] Stepper: a setting to write out every step For teaching: a student learns the rules of reduction by writing each step out, so in this mode the stepper helps with none of it. A "Write out steps" setting, in the stepper settings beside "Proof steps" and in the stepper's gear menu, turns the mode on. Theorem exercises carry the same flag, toggled by an instructor; it turns the mode on and can't turn the setting off. Saved settings and exercises without the field load with it off. In the mode, nothing in the theorem or cell stepper offers a step: there is no Step tab or its goal marks, no ghost for Tab to take, no list of a rule's uses, no "Try other direction" repair, and writing at a hole doesn't bridge back to the step after it. No completion is offered either: the write box completes no name, and its editor suggests no type-directed completion, so Tab inserts nothing. The box writes only a goal one step reaches, and says when the typed goal is further away. The Write and Strategy tabs, side condition exits, deleting a step and undo stay. Co-Authored-By: Claude Opus 5.5 --- src/language/CoreSettings.re | 6 + src/web/Migrate_exercises.re | 1 + src/web/Settings.re | 6 + src/web/app/editors/SettingsModal.re | 6 + src/web/app/editors/stepper/StepSearch.re | 23 +- src/web/exercises/TheoremExercise.re | 7 + .../exercises/examples/Ex_ReverseReverse.ml | 1 + src/web/view/NutMenu.re | 6 + src/web/view/StepperView.re | 78 ++++-- src/web/view/TheoremExerciseMode.re | 63 ++++- test/Test_SettingsPanel.re | 43 +++- test/Test_TheoremExercise.re | 155 ++++++++++++ test/evaluator/Test_StepSearch.re | 25 +- test/evaluator/Test_StepperView.re | 223 +++++++++++++++++- test/haz3ltest.re | 1 + 15 files changed, 605 insertions(+), 39 deletions(-) create mode 100644 test/Test_TheoremExercise.re diff --git a/src/language/CoreSettings.re b/src/language/CoreSettings.re index 202964b218..843c7a1bc5 100644 --- a/src/language/CoreSettings.re +++ b/src/language/CoreSettings.re @@ -16,6 +16,11 @@ module Evaluation = { show_settings: bool, show_hidden_steps: bool, enable_proof: bool, + /* The stepper offers no step and completes nothing: each step is + * typed into its write box, which writes only a step that reaches the + * typed goal at once. */ + [@sexp.default false] [@yojson.default false] + write_out_steps: bool, project_tables: bool, }; @@ -32,6 +37,7 @@ module Evaluation = { show_settings: false, show_hidden_steps: false, enable_proof: false, + write_out_steps: false, project_tables: true, }; }; diff --git a/src/web/Migrate_exercises.re b/src/web/Migrate_exercises.re index d299f36086..814091a787 100644 --- a/src/web/Migrate_exercises.re +++ b/src/web/Migrate_exercises.re @@ -155,6 +155,7 @@ let emit_item = (item: item): string => prelude: persist_zipper(spec.prelude), lemmas: persist_zipper(spec.lemmas), theorem: persist_zipper(spec.theorem), + write_out_steps: spec.write_out_steps, }; "let " ++ name diff --git a/src/web/Settings.re b/src/web/Settings.re index 9876bcbf9f..ce877136b3 100644 --- a/src/web/Settings.re +++ b/src/web/Settings.re @@ -68,6 +68,7 @@ module Model = { show_settings: false, show_hidden_steps: false, enable_proof: false, + write_out_steps: false, project_tables: false, }, }, @@ -137,6 +138,7 @@ module Update = { | ShowRecord | ForceShowRecord | EnableProof + | WriteOutSteps | ShowCaseClauses | ShowFnBodies | ShowAscriptionSteps @@ -280,6 +282,10 @@ module Update = { ...evaluation, enable_proof: !evaluation.enable_proof, } + | WriteOutSteps => { + ...evaluation, + write_out_steps: !evaluation.write_out_steps, + } | ProjectTables => { ...evaluation, project_tables: !evaluation.project_tables, diff --git a/src/web/app/editors/SettingsModal.re b/src/web/app/editors/SettingsModal.re index 7de7965980..9fd099cbb4 100644 --- a/src/web/app/editors/SettingsModal.re +++ b/src/web/app/editors/SettingsModal.re @@ -35,6 +35,12 @@ let view = settings.enable_proof, Evaluation(EnableProof), ), + setting( + "✍", + "write out steps", + settings.write_out_steps, + Evaluation(WriteOutSteps), + ), setting( "|", "show case clauses", diff --git a/src/web/app/editors/stepper/StepSearch.re b/src/web/app/editors/stepper/StepSearch.re index 78859a0d5c..b3750d311a 100644 --- a/src/web/app/editors/stepper/StepSearch.re +++ b/src/web/app/editors/stepper/StepSearch.re @@ -26,8 +26,10 @@ open Poly; * either way. * * The search goes `max_depth` steps deep, one more on a small goal, and - * checks at most `max_checks` candidates. It runs in slices (`run`), so a - * slow check never holds up typing for longer than one candidate takes. */ + * checks at most `max_checks` candidates. Writing out steps, it goes one + * step deep: the box writes no step the user didn't type. It runs in + * slices (`run`), so a slow check never holds up typing for longer than + * one candidate takes. */ module Picker = StepperPicker; @@ -158,7 +160,9 @@ let start = (goal: Picker.Goal.t, ~wanted: Exp.t): t => { next: [], seen: [here], checks: 0, - depth: size(here) <= small_goal ? max_depth + 1 : max_depth, + depth: + goal.settings.evaluation.write_out_steps + ? 1 : size(here) <= small_goal ? max_depth + 1 : max_depth, }; }; @@ -601,8 +605,8 @@ let names = }; /* What the box lists under itself. Typing the start of a name lists the - * names it completes to; a name in full, or any other text, lists the - * rules' uses. */ + * names it completes to, unless steps are written out; a name in full, or + * any other text, lists the rules' uses. */ [@deriving (show({with_path: false}), sexp, yojson)] type item = | Complete(string) @@ -617,6 +621,7 @@ let items = : list(item) => { let completions = switch (typed_name) { + | Some(_) when goal.settings.evaluation.write_out_steps => [] | Some(start) => names(goal) |> List.map(~f=fst) @@ -712,8 +717,9 @@ let generalized = (goal: Picker.Goal.t, steps: list(Proof.t)): list(Proof.t) => * the hole's goal, and steps written in the hole change the goal it acts * on. The steps are written in place of the hole when the step after * still checks once they are taken. Otherwise the search looks for steps - * back to the hole's goal: found, they are written too; not found, the - * hole stays after the written steps, marking the gap still to bridge. */ + * back to the hole's goal, unless steps are written out: found, they are + * written too; not found, the hole stays after the written steps, + * marking the gap still to bridge. */ module Bridge = { /* The step after `hole` in its chain in `proof`. */ let step_after = (proof: Proof.t, hole: Proof.t): option(Proof.t) => { @@ -806,6 +812,9 @@ module Bridge = { != None; switch (Picker.outgoing(goal, goal.written, written)) { | _ when next_checks => steps + /* The steps back are the user's to write. */ + | Some(_) when goal.settings.evaluation.write_out_steps => + steps @ [Proof.fresh(EmptyHole)] | Some(reached) => let from = Picker.Goal.mk(~settings=goal.settings, ~ctx=goal.ctx, reached); diff --git a/src/web/exercises/TheoremExercise.re b/src/web/exercises/TheoremExercise.re index f29bd3f708..e8fefdeeae 100644 --- a/src/web/exercises/TheoremExercise.re +++ b/src/web/exercises/TheoremExercise.re @@ -10,6 +10,9 @@ type spec = { prelude: Haz3lcore.Zipper.t, lemmas: Haz3lcore.Zipper.t, theorem: Haz3lcore.Zipper.t, + /* Turns the stepper's write-out mode on for this exercise. */ + [@sexp.default false] [@yojson.default false] + write_out_steps: bool, }; /* Persistent counterpart of [spec] (see CodeExercise.persistent_spec): @@ -25,6 +28,8 @@ type persistent_spec = { prelude: Haz3lcore.PersistentZipper.t, lemmas: Haz3lcore.PersistentZipper.t, theorem: Haz3lcore.PersistentZipper.t, + [@sexp.default false] [@yojson.default false] + write_out_steps: bool, }; let of_persistent = (t: persistent_spec): spec => { @@ -39,6 +44,7 @@ let of_persistent = (t: persistent_spec): spec => { prelude: unpersist(t.prelude), lemmas: unpersist(t.lemmas), theorem: unpersist(t.theorem), + write_out_steps: t.write_out_steps, }; }; @@ -51,4 +57,5 @@ let blank_spec = (~title, ~module_name): spec => { prelude: Haz3lcore.Zipper.init(), lemmas: Haz3lcore.Zipper.init(), theorem: Haz3lcore.Zipper.init(), + write_out_steps: false, }; diff --git a/src/web/exercises/examples/Ex_ReverseReverse.ml b/src/web/exercises/examples/Ex_ReverseReverse.ml index 7281f18cf5..1f0639d24b 100644 --- a/src/web/exercises/examples/Ex_ReverseReverse.ml +++ b/src/web/exercises/examples/Ex_ReverseReverse.ml @@ -9,6 +9,7 @@ let exercise : Exercise.t = "Show that this implementation of list reverse is its own inverse \ (i.e. that `rev` is *involutive*)."; max_points = 10; + write_out_steps = false; prelude = { zipper = diff --git a/src/web/view/NutMenu.re b/src/web/view/NutMenu.re index 1b33a3c579..98403156d7 100644 --- a/src/web/view/NutMenu.re +++ b/src/web/view/NutMenu.re @@ -194,6 +194,12 @@ let stepper = (~globals: Globals.t): section => { Evaluation(EnableProof), "Enable proof-based stepping mode (experimental)", ), + toggle( + "Write out steps", + s.write_out_steps, + Evaluation(WriteOutSteps), + "Type every step: the stepper offers none", + ), ], }; }; diff --git a/src/web/view/StepperView.re b/src/web/view/StepperView.re index 76368c5d84..77667e2964 100644 --- a/src/web/view/StepperView.re +++ b/src/web/view/StepperView.re @@ -121,6 +121,17 @@ module Model = { | (_, None) => false }; + /* The box's tabs, its default first. A cell's stepper steps a program, + * so it has no Strategy tab, and starts on Step. Writing out steps, + * there is no Step tab, whose marks hand over the next step. */ + let tabs = (~settings: CoreSettings.t, ~cell: bool): list(tab) => + switch (settings.evaluation.write_out_steps, cell) { + | (false, true) => [Step, Write] + | (false, false) => [Write, Step, Strategy] + | (true, true) => [Write] + | (true, false) => [Write, Strategy] + }; + /* Whether nothing is typed in the box. */ let is_empty = (box: box): bool => switch (Exp.term_of(CodeEditable.Model.get_statics(box.editor).term)) { @@ -250,9 +261,18 @@ module Update = { type t = (Rows.key, action); /* The box's text is an expression in the goal's scope. */ + /* Writing out steps, the box's editor completes nothing either. */ + let box_settings = (goal: Picker.Goal.t, settings: CoreSettings.t) => + goal.settings.evaluation.write_out_steps + ? { + ...settings, + assist: false, + } + : settings; + let calculate_box = (~settings, goal: Picker.Goal.t, editor) => CodeEditable.Update.calculate( - ~settings, + ~settings=box_settings(goal, settings), ~is_edited=true, ~is_dynamic_term=true, ~dynamics=Dynamics.Map.empty, @@ -262,7 +282,8 @@ module Update = { ); let ghost = (goal: Picker.Goal.t) => - Picker.Ghost.mk(goal, ~selected=Picker.Goal.selected(goal)); + goal.settings.evaluation.write_out_steps + ? None : Picker.Ghost.mk(goal, ~selected=Picker.Goal.selected(goal)); /* The goal typed into the box, or None while it is empty or * incomplete. */ @@ -340,6 +361,9 @@ module Update = { suggestions: switch (box.suggestions) { | _ when Model.is_empty(box) => None + /* Each use listed gives its goal, so the list would hand over + * the next step. */ + | _ when goal.settings.evaluation.write_out_steps => None | Some(suggestions) when suggestions.rule == rule && suggestions.at == at && !new_goal => Some(suggestions) @@ -441,12 +465,13 @@ module Update = { | Some((_, None)) | None => None }; + let offers = !goal.settings.evaluation.write_out_steps; let deco = StepperEditor.Deco.update( ~syntax=goal.editor.editor.syntax, { - next_steps: Picker.Goal.step_ids(goal), - refls: List.map(~f=Exp.rep_id, goal.refls), + next_steps: offers ? Picker.Goal.step_ids(goal) : [], + refls: offers ? List.map(~f=Exp.rep_id, goal.refls) : [], acts_on, selected: Option.map(~f=Exp.rep_id, selected_part(goal)), previewing, @@ -557,7 +582,15 @@ module Update = { * check the whole program again. */ | (BoxEditor(a), Some(box)) => let* editor = { - ...CodeEditable.Update.update(~settings, a, box.editor), + ... + CodeEditable.Update.update( + ~settings={ + ...settings, + core: box_settings(local.goal, settings.core), + }, + a, + box.editor, + ), is_edit: false, }; let editor = @@ -1143,9 +1176,11 @@ module View = { ); /* The repairs a broken step offers: removing it, and, for an axiom - * that doesn't apply, trying the other direction. */ + * that doesn't apply, trying the other direction, unless steps are + * written out, as that is a step to take. */ let repairs = ( + ~settings: CoreSettings.t, ~edit_syntax: Picker.Patches.patch => Ui_effect.t(unit), ~info_map: Statics.Map.t, ~proof_map: ProofMap.t, @@ -1161,7 +1196,7 @@ module View = { | Broken(mark) => let flip = switch (mark) { - | RuleDoesNotApply(_) => + | RuleDoesNotApply(_) when !settings.evaluation.write_out_steps => Picker.Patches.flip_direction(~info_map, ~proof_map, step) |> Option.map( ~f= @@ -1666,7 +1701,13 @@ module View = { keycap("Enter"), div_c( "box-hint-none", - [Node.text("nothing proves this step")], + [ + Node.text( + globals.settings.core.evaluation.write_out_steps + ? "not one step away: write the step between" + : "nothing proves this step", + ), + ], ), ], ) @@ -2185,10 +2226,7 @@ module View = { ), ] : []; - /* The cell's own stepper steps a program, so it has no Proof strategy - * tab, and starts on Step. */ - let tabs: list(Model.tab) = - is_toplevel ? [Step, Write] : [Write, Step, Strategy]; + let tabs = Model.tabs(~settings=globals.settings.core, ~cell=is_toplevel); /* A chain's rows, then, until they reach it, the `true` a proof aims * at: a quiet row shaped like a step row, so the chain reads evenly. A * focus's chain rewrites part of a goal, so it aims at nothing. */ @@ -2303,7 +2341,14 @@ module View = { ~delete=Some(edit_syntax(Picker.Patches.remove(step))), ~popup_extra, ~repair= - Row.repairs(~edit_syntax, ~info_map, ~proof_map, status, step), + Row.repairs( + ~settings=globals.settings.core, + ~edit_syntax, + ~info_map, + ~proof_map, + status, + step, + ), ~editor_view=goal_view(~hints=false, ~prev_broken, row), ~justification=Node.text(justification(step)), ~dots, @@ -2346,7 +2391,12 @@ module View = { List.map(~f=justification, steps), ), ) - | Some(NotFound) => lozenge("none", "no step gets here") + | Some(NotFound) => + lozenge( + "none", + globals.settings.core.evaluation.write_out_steps + ? "not one step away" : "no step gets here", + ) | Some(Searching) => lozenge("searching", "searching…") | Some(Found([])) | None => [] diff --git a/src/web/view/TheoremExerciseMode.re b/src/web/view/TheoremExerciseMode.re index 235ac1ccf6..f86a27d712 100644 --- a/src/web/view/TheoremExerciseMode.re +++ b/src/web/view/TheoremExerciseMode.re @@ -35,6 +35,7 @@ module Model = { max_points: int, cells, editing_flags, + write_out_steps: bool, }; [@deriving (show({with_path: false}), sexp, yojson)] @@ -60,6 +61,7 @@ module Model = { CellEditor.Model.mk(Editor.Model.mk(spec.theorem, ~root=Exp)), }, editing_flags: editing_flags_false, + write_out_steps: spec.write_out_steps, }; }; @@ -78,6 +80,7 @@ module Model = { CellEditor.Model.mk(Editor.Model.mk(spec.theorem, ~root=Exp)), }, editing_flags: editing_flags_false, + write_out_steps: spec.write_out_steps, }; }; @@ -91,9 +94,27 @@ module Model = { prelude: model.cells.prelude.editor.editor.state.zipper, lemmas: model.cells.lemmas.editor.editor.state.zipper, theorem: model.cells.theorem.editor.editor.state.zipper, + write_out_steps: model.write_out_steps, }; }; + /* The exercise's flag turns the write-out mode on, but can't turn the + * setting off. */ + let core_settings_for = + (model: t, settings: Language.CoreSettings.t): Language.CoreSettings.t => { + ...settings, + evaluation: { + ...settings.evaluation, + write_out_steps: + settings.evaluation.write_out_steps || model.write_out_steps, + }, + }; + + let settings_for = (model: t, settings: Settings.t): Settings.t => { + ...settings, + core: core_settings_for(model, settings.core), + }; + let export_module = (model: t): string => { let prefix = "let exercise : Exercise.t = Theorem\n"; let spec = spec_of_t(model); @@ -121,7 +142,8 @@ module Update = { | EditingPrompt | UpdateTitle(string) | UpdateModuleName(string) - | UpdatePrompt(string); + | UpdatePrompt(string) + | ToggleWriteOutSteps; [@deriving (show({with_path: false}), sexp, yojson)] type t = @@ -173,6 +195,11 @@ module Update = { ...model, prompt, }) + | ToggleWriteOutSteps => + Updated.return({ + ...model, + write_out_steps: !model.write_out_steps, + }) }; }; @@ -186,6 +213,7 @@ module Update = { }; let update = (~settings: Settings.t, action: t, model: Model.t) => { + let settings = Model.settings_for(model, settings); switch (action) { | Instructor(action) => instructor_update(~settings, action, model) | Prelude(action) when settings.instructor_mode => @@ -297,6 +325,7 @@ module Update = { model: Model.t, ) : Model.t => { + let settings = Model.core_settings_for(model, settings); let statics_mode = CodeWithStatics.StaticsDebounce.consume(~is_edited, ~schedule_refresh=() => schedule_action(RefreshStatics) @@ -501,6 +530,10 @@ module View = { ~selection: option(Selection.t), model: Model.t, ) => { + let globals = { + ...globals, + settings: Model.settings_for(model, globals.settings), + }; let editing_flags = model.editing_flags; let on_focus_textbox = _ => take_focus(TextBox); @@ -536,6 +569,22 @@ module View = { ~update_prompt=p => inject(Instructor(UpdatePrompt(p))), ); + let write_out_steps_view = + globals.settings.instructor_mode + ? [ + CellCommon.simple_cell_view([ + Widgets.toggle_named( + ~name="Write out steps", + ~tooltip="Students type every step: the stepper offers none", + "✍", + model.write_out_steps, + _ => + inject(Instructor(ToggleWriteOutSteps)) + ), + ]), + ] + : []; + let prelude_view = CellEditor.View.view( ~globals, @@ -593,14 +642,8 @@ module View = { |> Option.value(~default=(Float.nan, Float.nan)), ); - [ - score_view, - title_view, - module_name_view, - prompt_view, - prelude_view, - lemmas_view, - theorem_view, - ]; + [score_view, title_view, module_name_view] + @ write_out_steps_view + @ [prompt_view, prelude_view, lemmas_view, theorem_view]; }; }; diff --git a/test/Test_SettingsPanel.re b/test/Test_SettingsPanel.re index 771c659966..ad8a0bd30f 100644 --- a/test/Test_SettingsPanel.re +++ b/test/Test_SettingsPanel.re @@ -42,7 +42,48 @@ let old_blob = () => { ); }; +let without_write_out = () => { + let rec drop = (s: Sexplib.Sexp.t): Sexplib.Sexp.t => + switch (s) { + | List(items) => + List( + List.filter_map( + ~f= + (item: Sexplib.Sexp.t) => + switch (item) { + | List([Atom("write_out_steps"), ..._]) => None + | other => Some(drop(other)) + }, + items, + ), + ) + | atom => atom + }; + let on = { + ...Settings.Model.init, + core: { + ...Settings.Model.init.core, + evaluation: { + ...Settings.Model.init.core.evaluation, + write_out_steps: true, + }, + }, + }; + let loaded = + Settings.Model.persistent_of_sexp( + drop(Settings.Model.sexp_of_persistent(on)), + ); + check(bool, "off", false, loaded.core.evaluation.write_out_steps); +}; + let tests = ( "SettingsPanel", - [test_case("settings saved before the panel load", `Quick, old_blob)], + [ + test_case("settings saved before the panel load", `Quick, old_blob), + test_case( + "settings saved without writing out steps load with it off", + `Quick, + without_write_out, + ), + ], ); diff --git a/test/Test_TheoremExercise.re b/test/Test_TheoremExercise.re new file mode 100644 index 0000000000..58725295a0 --- /dev/null +++ b/test/Test_TheoremExercise.re @@ -0,0 +1,155 @@ +open Alcotest; +open Web; + +module Mode = TheoremExerciseMode; + +let model = (~write_out_steps) => + Mode.Model.of_spec({ + ...TheoremExercise.blank_spec(~title="t", ~module_name="T"), + write_out_steps, + }); + +let settings = (~instructor_mode=false, write_out_steps): Settings.t => { + let init = Settings.Model.init; + { + ...init, + instructor_mode, + core: { + ...init.core, + evaluation: { + ...init.core.evaluation, + write_out_steps, + }, + }, + }; +}; + +let writes_out = (model, settings) => + Mode.Model.settings_for(model, settings).core.evaluation.write_out_steps; + +let flag_turns_mode_on = () => { + check( + bool, + "the flag on", + true, + writes_out(model(~write_out_steps=true), settings(false)), + ); + check( + bool, + "the flag off, the setting on", + true, + writes_out(model(~write_out_steps=false), settings(true)), + ); + check( + bool, + "both off", + false, + writes_out(model(~write_out_steps=false), settings(false)), + ); +}; + +let only_instructor_toggles = () => { + let toggled = (~instructor_mode) => + Mode.Update.update( + ~settings=settings(~instructor_mode, false), + Instructor(ToggleWriteOutSteps), + model(~write_out_steps=false), + ). + model. + write_out_steps; + check(bool, "a student", false, toggled(~instructor_mode=false)); + check(bool, "an instructor", true, toggled(~instructor_mode=true)); +}; + +/* A saved exercise, as sexp and as JSON, with the flag or without the + * field. */ +let round_trip = () => { + let empty = Haz3lcore.PersistentZipper.persist(Haz3lcore.Zipper.init()); + let saved: TheoremExercise.persistent_spec = { + id: Haz3lcore.Id.mk(), + title: "t", + module_name: "T", + prompt: "", + max_points: 10, + prelude: empty, + lemmas: empty, + theorem: empty, + write_out_steps: true, + }; + let sexp = TheoremExercise.sexp_of_persistent_spec(saved); + let json = TheoremExercise.yojson_of_persistent_spec(saved); + let loaded = (spec: TheoremExercise.persistent_spec) => + TheoremExercise.of_persistent(spec).write_out_steps; + check( + bool, + "sexp", + true, + loaded(TheoremExercise.persistent_spec_of_sexp(sexp)), + ); + check( + bool, + "JSON", + true, + loaded(TheoremExercise.persistent_spec_of_yojson(json)), + ); + let without_sexp = + switch (sexp) { + | List(fields) => + Sexplib.Sexp.List( + List.filter( + ~f= + (field: Sexplib.Sexp.t) => + switch (field) { + | List([Atom("write_out_steps"), ..._]) => false + | _ => true + }, + fields, + ), + ) + | Atom(_) => Alcotest.fail("not a record") + }; + let without_json = + switch (json) { + | `Assoc(fields) => + `Assoc( + List.filter( + ~f=((name, _)) => !String.equal(name, "write_out_steps"), + fields, + ), + ) + | _ => Alcotest.fail("not a record") + }; + check( + bool, + "sexp without the field", + false, + loaded(TheoremExercise.persistent_spec_of_sexp(without_sexp)), + ); + check( + bool, + "JSON without the field", + false, + loaded(TheoremExercise.persistent_spec_of_yojson(without_json)), + ); +}; + +let tests = ( + "TheoremExercise", + [ + test_case( + "the exercise's flag turns writing out steps on, and can't turn it off", + `Quick, + flag_turns_mode_on, + ), + test_case( + "only an instructor toggles writing out steps", + `Quick, + only_instructor_toggles, + ), + test_case( + "an exercise loads with and without its write-out flag", + `Quick, + round_trip, + ), + ], +); diff --git a/test/evaluator/Test_StepSearch.re b/test/evaluator/Test_StepSearch.re index 07f40901c3..f67b8e4a30 100644 --- a/test/evaluator/Test_StepSearch.re +++ b/test/evaluator/Test_StepSearch.re @@ -13,8 +13,8 @@ let written = Test_StepperView.written; /* The goal of the theorem's first row, or of its first row inside the * first row's body. */ -let goal = (~inside=false, src) => { - let f = Fixture.mk(src); +let goal = (~settings=Test_StepperView.settings, ~inside=false, src) => { + let f = Fixture.mk(~settings, src); let row = first(f.rows); Fixture.goal(f, inside ? first(body(row)) : row); }; @@ -59,6 +59,27 @@ let arithmetic = "theorem t = (1 + 1) * 2 == 4 proof ? in t"; let tests = ( "StepSearch", [ + test_case( + "writing out steps, a goal one step away is found and two steps away isn't", + `Quick, + () => { + let src = "theorem t = 1 + 2 + 3 == 6 proof ? in t"; + let g = goal(~settings=Test_StepperView.Writing_out.write_out, src); + check( + steps, + "one step", + Some(["from 1 + 2 do step end"]), + found(search(g, "3 + 3 == 6")), + ); + check(steps, "two steps", None, found(search(g, "6 == 6"))); + check( + steps, + "two steps, not writing out", + Some(["from 1 + 2 do step end", "from 3 + 3 do step end"]), + found(search(goal(src), "6 == 6")), + ); + }, + ), test_case( "a step on either operand is found", `Quick, diff --git a/test/evaluator/Test_StepperView.re b/test/evaluator/Test_StepperView.re index be471898f6..099e52c897 100644 --- a/test/evaluator/Test_StepperView.re +++ b/test/evaluator/Test_StepperView.re @@ -16,6 +16,7 @@ let settings = CoreSettings.on; /* A cell evaluated and checked as the editor does it. */ module Fixture = { type t = { + settings: CoreSettings.t, statics: CachedStatics.t, cell: Web.EvalResult.Model.t, id: Id.t, @@ -31,7 +32,8 @@ module Fixture = { /* Evaluates on the main thread, or, with `pending`, sends the request to * a worker that never answers. */ - let calculate = (~pending=false, ~is_edited, statics, cell) => + let calculate = + (~settings=settings, ~pending=false, ~is_edited, statics, cell) => Web.EvalResult.Update.calculate( ~settings, ~queue_worker=pending ? Some(_ => ()) : None, @@ -40,7 +42,8 @@ module Fixture = { cell, ); - let of_cell = (~name, statics, cell: Web.EvalResult.Model.t): t => { + let of_cell = + (~settings=settings, ~name, statics, cell: Web.EvalResult.Model.t): t => { let theorems = cell.theorems; switch ( Web.Theorems.Model.theorems(theorems) @@ -49,6 +52,7 @@ module Fixture = { ) ) { | Some((id, theorem)) => { + settings, statics, cell, id, @@ -59,12 +63,18 @@ module Fixture = { }; }; - let mk = (~name="t", src: string): t => { + let mk = (~settings=settings, ~name="t", src: string): t => { let statics = statics(src); of_cell( + ~settings, ~name, statics, - calculate(~is_edited=true, statics, Web.EvalResult.Model.init), + calculate( + ~settings, + ~is_edited=true, + statics, + Web.EvalResult.Model.init, + ), ); }; @@ -78,9 +88,15 @@ module Fixture = { f.cell, ); of_cell( + ~settings=f.settings, ~name=f.theorem.name, f.statics, - calculate(~is_edited=false, f.statics, updated.model), + calculate( + ~settings=f.settings, + ~is_edited=false, + f.statics, + updated.model, + ), ); }; @@ -3505,6 +3521,202 @@ module Redrawing = { ]; }; +/* With steps written out, nothing offers a step: each is typed into the + * box, which writes only a step that reaches the typed goal at once. */ +module Writing_out = { + let write_out = { + ...settings, + evaluation: { + ...settings.evaluation, + write_out_steps: true, + }, + }; + + /* Types `text` into the box a character at a time. */ + let type_ = (f: Fixture.t, text: string): Fixture.t => + String.fold(text, ~init=f, ~f=(f, c) => + Writing.type_(f, String.of_char(c)) + ); + + /* The box's search's steps, each as written, or None if it found + * none. */ + let found = (box: Stepper.Model.box): option(list(string)) => + switch (box.search) { + | Some({status: Found(steps), _}) => Some(List.map(~f=written, steps)) + | Some({status: NotFound, _}) => None + | Some({status: Searching, _}) + | None => Alcotest.fail("no finished search") + }; + + /* What the stepper offers at the first row: the ghost, the eval steps + * and reflexivities marked on the goal, and the uses of rules listed + * once something is typed. */ + let offers = (~settings, src) => { + let f = Fixture.mk(~settings, src); + let row = first(f.rows); + let local = Fixture.local(f, row); + let typed = type_(f, "3"); + ( + Option.is_some(Writing.box(f).ghost), + !List.is_empty(local.deco.marks.next_steps) + || !List.is_empty(local.deco.marks.refls), + Option.is_some(Writing.box(typed).suggestions), + ); + }; + + /* A cell's stepper, with `text` typed into its last row's box. */ + let cell = (src: string, text: string) => { + let statics = Fixture.statics(src); + let calculate = (~is_edited, cell) => + Fixture.calculate(~settings=write_out, ~is_edited, statics, cell); + let update = (action, cell) => + calculate( + ~is_edited=false, + Web.EvalResult.Update.update( + ~settings=Web.Settings.Model.init, + action, + cell, + ). + model, + ); + let stepper = (cell: Web.EvalResult.Model.t) => + switch (cell.display) { + | Stepper(s) => s + | Evaluation(_) => Alcotest.fail("the stepper is off") + }; + let rows = cell => + Rows.chain( + ~proof_map=stepper(cell).proof_map, + Web.EvalResult.CellStepper.proof(stepper(cell)), + ); + let box = cell => + switch ( + Stepper.Model.find(last(rows(cell)).key, stepper(cell).stepper) + ) { + | Some({box: Some(box), _}) => box + | Some({box: None, _}) + | None => Alcotest.fail("the last row has no box") + }; + let act = (action, cell) => + update(StepperAction((last(rows(cell)).key, action)), cell); + let rec run = (cell, slices) => + slices > 1000 || !Stepper.Model.running(box(cell)) + ? cell + : run(act(SearchSlice(box(cell).generation), cell), slices + 1); + let cell = + String.fold( + text, + ~init= + update( + ToggleStepper, + calculate(~is_edited=true, Web.EvalResult.Model.init), + ), + ~f=(cell, c) => + run(act(BoxEditor(Perform(Insert(String.of_char(c)))), cell), 0) + ); + let write = cell => + switch (box(cell).search) { + | Some({status: Found(steps), _}) => + switch (Picker.write_steps(last(rows(cell)), steps)) { + | Some(patch) => update(StepperPatch(patch), cell) + | None => Alcotest.fail("the steps found write nothing") + } + | _ => Alcotest.fail("nothing found") + }; + (box(cell), () => List.map(~f=goal, rows(write(cell)))); + }; + + let tests = [ + test_case( + "there is no Step tab", + `Quick, + () => { + let tabs = (~cell) => + List.map( + ~f=Stepper.Model.show_tab, + Stepper.Model.tabs(~settings=write_out, ~cell), + ); + check( + list(string), + "a theorem", + ["Write", "Strategy"], + tabs(~cell=false), + ); + check(list(string), "a cell", ["Write"], tabs(~cell=true)); + }, + ), + test_case( + "the stepper offers no ghost, marks or listed uses of rules", + `Quick, + () => { + let src = "theorem t = 1 + 2 + 3 == 6 proof ? in t"; + let offered = triple(bool, bool, bool); + check(offered, "off", (true, true, true), offers(~settings, src)); + check( + offered, + "on", + (false, false, false), + offers(~settings=write_out, src), + ); + }, + ), + test_case( + "the box completes no name, so Tab has nothing to take", + `Quick, + () => { + let completes = settings => { + let f = + Fixture.mk(~settings, "theorem t = 1 + 2 + 3 == 6 proof ? in t"); + let f = type_(f, "and_"); + let box = Writing.box(f); + let goal = Fixture.goal(f, Writing.box_row(f)); + Option.is_some(box.ghost) + || !List.is_empty(fst(Stepper.Update.listing(goal, box))); + }; + check(bool, "off", true, completes(settings)); + check(bool, "on", false, completes(write_out)); + }, + ), + test_case( + "the box's editor suggests no completion", + `Quick, + () => { + let suggests = settings => { + let f = + Fixture.mk(~settings, "theorem t = 1 + 2 + 3 == 6 proof ? in t"); + let selection = + Writing.box(type_(f, "tr")).editor.editor.state.zipper.selection; + Selection.is_buffer(selection) && !List.is_empty(selection.content); + }; + check(bool, "off", true, suggests(settings)); + check(bool, "on", false, suggests(write_out)); + }, + ), + test_case( + "in a cell, typing the next goal writes its step", + `Quick, + () => { + let (box, written) = cell("1 + 2 + 3", "3 + 3"); + check( + option(list(string)), + "found", + Some(["from 1 + 2 do step end"]), + found(box), + ); + check(list(string), "the goals", ["1 + 2 + 3", "3 + 3"], written()); + }, + ), + test_case( + "in a cell, a goal two steps away isn't found", + `Quick, + () => { + let (box, _) = cell("1 + 2 + 3", "6"); + check(option(list(string)), "found", None, found(box)); + }, + ), + ]; +}; + let tests = ( "StepperView", Walk.tests @@ -3519,6 +3731,7 @@ let tests = ( @ Focusing.tests @ Focusing.generalizing_tests @ Writing.tests + @ Writing_out.tests @ Scrolling.tests @ Redrawing.tests, ); diff --git a/test/haz3ltest.re b/test/haz3ltest.re index bd483c90f3..df7a255a3a 100644 --- a/test/haz3ltest.re +++ b/test/haz3ltest.re @@ -123,6 +123,7 @@ let (suite, exit_with_test_status) = @ Test_ColorConfiguration.tests @ Test_ConfigurationMode.tests @ [Test_SettingsPanel.tests] + @ [Test_TheoremExercise.tests] @ Test_ShortcutAction.tests @ Test_Color.tests @ [Test_ExplainThis.tests]