[{"data":1,"prerenderedAt":4},["ShallowReactive",2],{"0KkBBVXbX0":3},"# Formalizing Shape Expressions in Lean 4\n\nThis repository is a Lean 4 formalization of\n[ShEx (Shape Expressions)](https://shex.io/). ShEx is a schema language\nthat validates RDF graphs.\n\nThe repository formalizes **two** papers:\n\n> Iovka Boneva, Jose Emilio Labra Gayo, Eric Prud'hommeaux,\n> *\"Semantics and Validation of Shapes Schemas for RDF\"*, ISWC 2017.\n\n> Iovka Boneva, Jose Emilio Labra Gayo, Eric Prud'hommeaux, Katherine\n> Thornton, Andra Waagmeester, *\"Shape Expressions with Inheritance\"*,\n> arXiv:2503.24299, 2025.\n\nIt also contains some experiments about RDF and ShEx.\n\nThe 2025 paper adds an inheritance mechanism (`extends` and `abstract`) to\nShEx 2.1. It is not a strict extension of the 2017 formalism: the node\nconstraints, `closed`/`extra` and the extension hierarchy are all\ndifferent. Thus, the two papers are separate developments. They share\nonly the RDF and typing vocabulary, which does not depend on a paper.\n\nThe goal is a machine-checked model of each paper. The model contains RDF\ngraphs, the syntax of shape expressions and the satisfaction relations.\nFor the 2017 paper, it also contains a full proof of soundness and\ncompleteness for two validation algorithms. The goal is not a production\nShEx validator.\n\nA third directory, `ShexLean/Shex2026InheritanceDisjunction/`, is an\n**exploration**. It is not a third paper. §6 (\"Design Choices\") of the\n2025 paper explicitly does *not* allow `extends` on a disjunction of\nshapes, because of an ambiguity with multiple inheritance. The exploration\nasks if we can remove this restriction and keep the same correctness\nresults. The directory is a copy of `Shex2025Inheritance/` with that one\nrestriction removed, and with a fix for the ambiguity that is designed and\nproved sound. Refer to \"What is implemented (2026 exploration)\" below.\n\n## Repository structure\n\n```\nShexLean/\n  Common/                          -- vocabulary that the two papers share (RDF, Typing, ...)\n  InductiveRDF/                    -- a different representation of RDF graphs. We examined it\n                                      as a possible route to decidability (refer to\n                                      \"Decidability\" below). It is proved correct, but no\n                                      other part uses it.\n  Shex2017Schemas/                 -- 2017 paper: syntax, semantics, algorithms, decidability\n    examples/                      -- worked examples from the paper\n  InheritanceCore/                 -- the parts of the 2025 formalism that do not depend on the\n                                      payload of `extends` (triple expressions, shapes, Table 1,\n                                      rule 17), shared by the 2025 and 2026 directories\n  Shex2025Inheritance/             -- 2025 paper: syntax, semantics, algorithm, decidability\n    examples/                      -- worked examples from the paper\n  Shex2026InheritanceDisjunction/  -- exploration: \"extends on a disjunction\" (§6 of 2025).\n                                      Same structure as Shex2025Inheritance/ (from the syntax\n                                      to decidability and rendering)\n    examples/                      -- worked example for the exploration\nexamples/                          -- infrastructure of the shex_lean CLI (does not depend on a paper)\nSTYLE.md                           -- writing rules for comments and documentation\n```\n\n`ShexLean.lean` imports each file that is not an example. Thus,\n`lake build ShexLean` type-checks the full formalization. The `Examples`\nlibrary and the `shex_lean` executable build the worked examples\nseparately (refer to \"Running\" below). `examples/Registry.lean` imports\neach example file. Thus, `lake build` type-checks all of them.\n\n## Decidability\n\nIn the two papers, the satisfaction relations are `Prop`s with quantifiers\nover infinite types. Thus, as written, you cannot execute them.\n\nEach paper has a `Decidable.lean` file. This file shows that you can bound\neach such quantifier to the finite graph, typing or schema. This gives\nreal `Decidable` instances, which `decide` and `native_decide` can use.\n\nThe 2025 side needs one restriction. `subjectOf` uses `Classical.choice`.\nThus, `.constraint` is decided only at the node level (`ShapeExpr.MOk`\nand `FOk`). No worked example uses the excluded case.\n\nThe 2026 exploration needs one more bound. Rule 18 has a new existential\nwitness, `pick : Label → ℕ`. `ShapeExpr.extTeAt_mod` shows that only the\nindex modulo the number of disjuncts is important. Thus, `Decidable.lean`\nsearches only over the finite set `ShapeExpr.pickBound S x` for each\nancestor `x`.\n\nThe `Render.lean` file of each paper pretty-prints real `Schema`, `Graph`\nand `Typing` values. It computes the `true` and `false` claims with these\ninstances.\n\n## What is implemented (2017 paper)\n\n- `Common/RDF.lean`, `Common/Typing.lean`: RDF graphs and typings (§1,\n  §3.1).\n- `Shex2017Schemas/Syntax.lean`, `Semantics.lean`: the grammar and the\n  satisfaction relations (Fig. 1, Fig. 2).\n- `Shex2017Schemas/Stratification.lean`: stratified negation (§3.2).\n- `Shex2017Schemas/MaximalTyping.lean`, `Proposition1.lean`: the\n  construction of the maximal correct typing, Lemma 1 and Proposition 1\n  (§3.3).\n- `Shex2017Schemas/Lemma2.lean`: the maximal typing does not depend on the\n  stratification. The paper gives only a proof sketch for this result.\n- `Shex2017Schemas/CombStrat.lean`: a lexicographic combination of two\n  stratifications. The proof of Lemma 2 does not need it, but it is a\n  useful fact.\n- `Shex2017Schemas/ShapesSem.lean`: Definitions 5 and 6, `SHAPES_SEM`.\n- `Shex2017Schemas/Algorithm1.lean`: Algorithm 1 (§4.1). It is proved\n  equal to the semantics.\n- `Shex2017Schemas/Algorithm2.lean`: Algorithm 2 (§4.2), the recursive\n  validation procedure that detects cycles. It is proved sound and\n  complete. (The proof sketch of the paper covers only termination.)\n- `Shex2017Schemas/examples/`: each numbered example from the paper, one\n  file for each example. Each file has proofs, and its rendered output is\n  generated from real `Schema`, `Graph` and `Typing` values. Nobody copied\n  the output by hand.\n\n## What is implemented (2025 paper: Shape Expressions with Inheritance)\n\nThis part is in the namespace `ShexLean.Inheritance`. It uses\n`Common/RDF.lean` and `Common/Typing.lean` with no change, and the shared\ndefinitions of `InheritanceCore/` (refer to the next list).\n\n- `Shex2025Inheritance/Syntax.lean`: the grammar of shape expressions\n  (Definition 1) and `Schema = (Y, X, def, A)` (Definition 2).\n- `Shex2025Inheritance/Stratification.lean`: the walk `depsAux` of\n  Definition 5.\n- `Shex2025Inheritance/Semantics.lean`: the three satisfaction relations\n  (Tables 1-3). Table 1 and Table 2 are structural. Table 3 has a fuel\n  parameter only for the evaluation of `restr(x)` in rule 18, because that\n  call is not on a subterm.\n- `Shex2025Inheritance/Termination.lean`: Lemma 1. A sufficiently large\n  fuel makes the relations independent of fuel. The proof is complete. It\n  needs only `ExtAcyclic`.\n- `Shex2025Inheritance/Proposition1.lean`: the agreement and monotonicity\n  lemmas of `Satisfies`, which use the rules of Table 3. With them, this\n  file gives the instance of `InheritanceSemantics` and Proposition 1.\n- `Shex2025Inheritance/Lemma2.lean`, `Algorithm1.lean`: Lemma 2 and the\n  correctness of the algorithm of §5, for this development.\n- `Shex2025Inheritance/Locality.lean`, `Algorithm2.lean`: the recursive\n  validation algorithm of §5 (\"a recursive algorithm that computes only a\n  portion of τmax\"), proved correct for this development.\n  `Locality.lean` proves that `n ⊨ s` uses the typing only at the\n  neighbours of `n`.\n- `Shex2025Inheritance/Decidable.lean`, `Render.lean`: refer to\n  \"Decidability\".\n- `Shex2025Inheritance/Complexity/`: Proposition 2 (\"validation is\n  NP-complete\"), checked in Lean.\n  - `Hardness.lean`: two reductions from Exact Cover, with linear size.\n    Validation is NP-hard (`validation_NP_hard`). With `not`, it is also\n    coNP-hard (`validation_coNP_hard`). Thus, with `not`, validation is\n    not in NP unless NP = coNP, and Proposition 2 needs a restriction.\n  - `Hardness2017.lean`: the same two reductions for the schemas of the\n    2017 paper, which have `NOT` and no `extends`\n    (`validation2017_NP_hard`, `validation2017_coNP_hard`). Thus, the\n    coNP-hardness does not come from `extends`. The 2017 paper makes no\n    claim about the complexity of validation.\n  - `Certificate.lean`: in the fragment with no `not` and no\n    `restr(x)`, validation is in NP (`validation_in_NP`). A computable\n    `check` verifies certificates of size at most `8 · (N + 1)^7`. The\n    NP-hardness reduction stays in this fragment (`posSchema_fragment`).\n  - `Cost.lean`: in an explicit cost model, `check` costs a polynomial in\n    `N` (`costCheck_poly`), and the reductions cost `(|I| + 1)²`.\n  - `Oracle.lean`: in general, Algorithm 1 decides validation with at most\n    `(2 · N²)²` local checks (`validation_oracle_calls`).\n  - The NP-completeness of Exact Cover is not proved in Lean. Mathlib has\n    no NP class. The cost model is a model: it does not measure the\n    compiled code.\n- `Shex2025Inheritance/examples/`: each numbered example from the paper,\n  with the same structure as the 2017 side.\n\nThe proofs of Proposition 1, Lemma 2 and Algorithm 1 do not depend on the\nrules of Table 3. They are in `InheritanceCore/` and apply to each\ndevelopment that gives an instance of `InheritanceSemantics`:\n\n- `InheritanceCore/Syntax.lean`, `TripleMatch.lean`, `Decidable.lean`,\n  `Render.lean`: triple expressions, shapes, Table 1 and rule 17.\n- `InheritanceCore/Schema.lean`: schemas for any type of shape\n  expressions (the class `ShapeSyntax`), the extension hierarchy `H_S`\n  (Definition 3), the dependency graph `D_S` (Definitions 5-6),\n  stratifications (Definition 7) and the restrictions of a schema.\n- `InheritanceCore/MaxTyping.lean`: the class `InheritanceSemantics`,\n  correct typings (Definition 4), the maximal typing (Definition 8) and\n  Proposition 1.\n- `InheritanceCore/Lemma2.lean`: the maximal typing does not depend on the\n  stratification (§4.3). The proof is complete. The paper gives only a\n  sketch.\n- `InheritanceCore/Algorithm1.lean`: the validation algorithm of §5,\n  proved correct.\n- `InheritanceCore/Locality.lean`, `InheritanceCore/Algorithm2.lean`: the\n  recursive validation algorithm of §5, proved correct\n  (`prove_correct`). The paper says only that the 2017 algorithm \"also\n  works for ShEx with inheritance\". It gives no algorithm and no proof.\n  The adaptation has two changes. The dependency set of `(n, z)` has the\n  labels that `z` reaches in `D_S`, so it includes the ancestors (rule 18)\n  and the descendants (abstract labels). The local check is the one of\n  Definition 4, as in Algorithm 1. The proof needs one more fact about the\n  semantics, the class `LocalSemantics`: `n ⊨ s` uses the typing only at\n  the objects of `neigh_G(n)`.\n- `InheritanceCore/SchemaDecidable.lean`: computable ancestor sets.\n- `InheritanceCore/MaxFixedPoint.lean`: `τ_max` is a fixed point of the\n  local check (`mem_Typing8_iff`).\n- `InheritanceCore/OracleCalls.lean`: Algorithm 1 calls the local check at\n  most `(|Nodes(G)| · |Y ∪ X|)²` times (`oracleCalls_le`).\n\n## What is implemented (2026 exploration: disjunctive `extends`)\n\n§6 (\"Design Choices\") of the 2025 paper restricts `extends X h [and u]`.\n`h` must be one plain shape, not a general shape expression. Thus, it\ncannot be a disjunction `s1 or s2`.\n\nThe paper tells why. Let a node inherit from the same disjunctive ancestor\nalong two different paths. The example of the paper is a hypothetical\n`Figure → ⟨coord@Cartesian⟩ or ⟨coord@Polar⟩`, which `ColouredCircle`\nreaches through `ColouredFigure` and through `Circle`. Then the two paths\ncan select different disjuncts, and one node can satisfy the two. The\npaper says that this is undesirable. It says that a correct fix needs\n\"(1) recording which disjunct... has been satisfied by each subtype, and\n(2) checking whether all the subtypes satisfy the same disjunct.\"\n\nThe paper does not give that fix. This directory gives it, and checks if\nProposition 1 and Lemma 2 are still true with the fix. **They are true.\nThere is no `sorry` in the directory.**\n\n- `Shex2026InheritanceDisjunction/Syntax.lean`: the payload of\n  `ShapeExpr.extends` is now a *nonempty `List Shape`* (`hs`), not one\n  `Shape`. A singleton list gives exactly the grammar of the original\n  paper. Thus, the original formalism is the special case\n  `hs.length = 1` of this one.\n  - `ShapeExpr.extTeAt i` resolves `ext-te(x)` at a selected disjunct\n    index.\n  - `extTeAt_one` and `extTeAt_two` connect it to concrete triple\n    expressions for the singleton case and the pair case.\n  - `extTeAt_mod` shows that `extTeAt` depends only on its index modulo\n    the number of disjuncts. This fact makes the new existential\n    decidable.\n- `Shex2026InheritanceDisjunction/Semantics.lean`: the same as\n  `Shex2025Inheritance/Semantics.lean`, except rule 18 (the `.extends` case\n  of `SatisfiesMAt`). Rule 18 has one more existential witness,\n  `pick : ShapeLabel → ℕ`. Each `.extends` occurrence selects `pick` one\n  time, and all the ancestors that this occurrence reaches share it. This\n  is the fix:\n  - `S.ancSet` already puts each ancestor that one `.extends` clause can\n    reach into one `Finset`, with no duplicates. (Multiple inheritance is\n    written as many labels in one `xs`, not as many separate `.extends`\n    nodes. `WellFormedX` makes the definition of each `x ∈ X` one\n    `extends` clause at the top level. An `extends` nested in a\n    restriction `u` is a separate occurrence, with its own `pick`.)\n  - Thus, two inheritance paths that go to the same disjunctive ancestor\n    must use the *same* shared `pick` and `Mx` witness.\n  - This is exactly \"(1) record the choice, (2) check that the subtypes\n    agree\". The fix needs no global parameter for the schema or the\n    typing.\n- `Shex2026InheritanceDisjunction/Stratification.lean`, `Termination.lean`:\n  the dependency graph and Lemma 1 (independence from fuel), done again\n  for `hs` and `pick`. `Shape.listDepInfo` is the union of the dependency\n  information of all the disjuncts. `pick` can select any of them, so a\n  sound stratification analysis must count them all. The proof of Lemma 1\n  is the same as in 2025, and needs only `ExtAcyclic`.\n- The results of `InheritanceCore/MaxTyping.lean`, `Lemma2.lean` and\n  `Algorithm1.lean` apply with no change, through the instance of\n  `InheritanceSemantics` in `Proposition1.lean`.\n- `Shex2026InheritanceDisjunction/Proposition1.lean`: Proposition 1 of\n  the paper, done again and **proved** for the relaxed semantics. The\n  agreement and monotonicity lemmas `SatisfiesMAt_transfer` and\n  `SatisfiesMAt_stratMono` are the lemmas that dereference `.extends`.\n  Each of them gets the same `pick` existential as rule 18, at the\n  location where the `Mx` witness already was. The other cases (`or`,\n  `and`, `not`, `.ofShape`) do not change.\n- `Shex2026InheritanceDisjunction/Lemma2.lean`, `Algorithm1.lean`: Lemma 2\n  and the correctness of Algorithm 1, for this development (the generic\n  proofs of `InheritanceCore/`).\n- `Shex2026InheritanceDisjunction/Locality.lean`, `Algorithm2.lean`: the\n  recursive validation algorithm, proved correct for this development.\n- `Shex2026InheritanceDisjunction/Decidable.lean`, `Render.lean`:\n  decidability and rendering for the relaxed semantics. Refer to\n  \"Decidability\" above for the new bound on `pick`.\n- `Shex2026InheritanceDisjunction/examples/Example1_coloured_circle.lean`:\n  a formalized version of the hypothetical case of §6 of the paper.\n  - The body of `Figure` is relaxed to\n    `[⟨coord@CartesianCoord⟩, ⟨coord@PolarCoord⟩]`.\n  - `Circle` and `ColouredFigure` both extend `Figure`.\n  - `ColouredCircle` inherits from the two (the motivating schema of §2,\n    with `Attribute`, `Colour` and `Radius` removed, because they are not\n    related to the coordinate question).\n\n  There are three claims. Each claim is a theorem\n  (`f1_satisfies_ColouredCircle`, `f2_satisfies_ColouredCircle` and\n  `f3_not_satisfies_ColouredCircle`). The command-line tool also computes\n  them with `renderDecide`:\n  - A node with *consistent* Cartesian coordinates is a `ColouredCircle`.\n  - A node with *consistent* polar coordinates is a `ColouredCircle`.\n    (The paper says that this legitimate use is the reason to want the\n    relaxation.)\n  - A node whose coordinate data matches *neither* disjunct is not a\n    `ColouredCircle`. This is true for each possible witness, not only for\n    the witnesses that we tried. `f3_not_satisfies_ColouredCircle` is a\n    real proof of non-existence, not an omission.\n\n## CLI infrastructure (`examples/`)\n\n- `Example.lean`, `Registry.lean`: a record for each worked example (name,\n  summary, and the schema, graph and typing as text), and the registry\n  from which the executable lists and selects the examples.\n- `Proof.lean`, `ProofRegistry.lean`: a record that points to the `.lean`\n  file that contains a theorem. Thus, the executable shows each proof from\n  its real source, not from text that a person selected.\n\n## Requirements\n\n- [`elan`](https://github.com/leanprover/elan), with the Lean toolchain\n  that `lean-toolchain` specifies. (The first build installs it\n  automatically.)\n- Internet access on the first build, so that `lake` can get Mathlib.\n\n## Running\n\nBuild the library and the executable:\n\n```\nlake build\n```\n\nList the worked examples and the proofs (this is also the default when\nthere are no arguments):\n\n```\n$ lake exe shex_lean list\n...\nExamples:\n  2017 — Semantics and Validation of Shapes Schemas for RDF:\n    schemas2017-example1-introduction — §1 Introductory Example: users, programmers, clients, issues.\n    schemas2017-example2-issue-tracker — Recursive \u003CIssueSh> schema, two issues reporting on each other.\n    ...\n  2025 — Shape Expressions with Inheritance:\n    inheritance2025-example1-figures — Fig. 1/2's full ColouredCircle schema: f1 is both a Circle and a ColouredFigure.\n    ...\n\nProofs:\n  2017 — Semantics and Validation of Shapes Schemas for RDF:\n    schemas2017-lemma1 — A schema with no negation has a maximal correct typing (§3.3).\n    ...\n  2025 — Shape Expressions with Inheritance:\n    inheritance2025-lemma1 — Evaluation of n,τ⊨def(z) always terminates (§4.2).\n    ...\n```\n\nPrint the schema, the graph and the typing of one example:\n\n```\n$ lake exe shex_lean run schemas2017-example2-issue-tracker\nschemas2017-example2-issue-tracker — Recursive \u003CIssueSh> schema, two issues reporting on each other.\n\nSchema:\n\u003CIssueSh> → ({is:reportedBy} @\u003CStr> ; {is:relatedTo} @\u003CIssueSh> [0;*])\n\u003CStr> → {\"Bob\", \"Ren\"}\n\nGraph:\n\u003Ci1> is:relatedTo \u003Ci2> .\n\u003Ci1> is:reportedBy \"Ren\" .\n\u003Ci2> is:relatedTo \u003Ci1> .\n\u003Ci2> is:reportedBy \"Bob\" .\n\nTyping:\n{(\"Bob\",\u003CStr>), (\"Ren\",\u003CStr>), (\u003Ci1>,\u003CIssueSh>), (\u003Ci2>,\u003CIssueSh>)}   (correct = true)\n```\n\nThe executable pretty-prints the schema, graph and typing text from the\nreal Lean values. `correct = true` is a `renderDecide` computation: the\nCLI runs the compiled code of the `Decidable` instance. It is independent\nof the theorem that `lake build` checks, and the kernel does not check it.\n\nPrint the Lean source of a proof. Run this command from the project root,\nbecause it reads the `.lean` file directly:\n\n```\nlake exe shex_lean run schemas2017-lemma1\n```\n\nTo step through the definitions and proofs interactively, open the\nproject in an editor with Lean support (for example, VS Code with the\nLean 4 extension).\n\n## Tests\n\n`tests/` contains a test suite that uses the validation tests of the ShEx\ntest suite (\u003Chttps://github.com/shexSpec/shexTest>). It checks the 2025\nformalism with the structural tests and with the inheritance tests\n(`extends` and `abstract`). Run it with:\n\n```\nlake test\n```\n\nThe test suite is separate from the formalization. `lake build` does not\nbuild it. Refer to [`tests/README.md`](tests/README.md).\n\n## Writing style\n\nThe comments, docstrings and this README use a style based on\nSimplified Technical English (ASD-STE100). Refer to [`STYLE.md`](STYLE.md)\nfor the rules.\n",1795981098468]