[{"data":1,"prerenderedAt":4},["ShallowReactive",2],{"HtwOMPhfGZ":3},"# StrataPython\n\nPython language support for Strata. This package translates Python programs into Strata's intermediate representations (Core, Laurel) for formal verification.\n\n## Building\n\n```bash\nlake build\n```\n\nThis builds the default targets, among them the `StrataPython` library and the `StrataPythonSem`\nlibrary (the Python semantics and its proofs, which `StrataPython` doesn't import). The\ncompile-time tests need `lake build StrataPythonTest StrataDynTest`.\n\n## Package Purpose\n\nStrataPython provides:\n\n- **Python AST** - Types generated from the Python dialect DDM definition\n- **Python-to-Laurel translation** - Translation through the Laurel IR (higher-level, supports dispatch and overloads).\n- **Python-to-Core translation** - *Deprecated.* Direct translation from Python to Core IR, kept for `pyInterpret` and `pyAnalyzeToGoto`; new features should target the Laurel path\n- **PySpec pipeline** - Reads Python type specifications (`.pyspec.st.ion`) and generates Laurel declarations for verification\n- **Regex support** - Translates Python regular expressions to Core SMT assertions\n- **Overload resolution** - Identifies and resolves dispatch-based service overloads\n\n## Modeled postconditions: `@ensures` vs `@admit`\n\nPySpec declarations model external APIs; they do not contain implementations\nthat Strata can execute and verify. An `@ensures` contract claims a property\nthat should be *verified* against an implementation, so Strata currently\nrejects modeled `@ensures` contracts with a fatal `unsupportedPostcondition`\ndiagnostic rather than silently assuming an unverified predicate at call\nsites.\n\nVerification of real code still depends on assumptions about code that will\nnot or cannot be verified (e.g. standard library models). Those assumptions\nare supported — they just have to be acknowledged explicitly with `@admit`:\n\n```python\n@admit(lambda result: result >= 0)\ndef modeled_value() -> int:\n    ...\n```\n\nAn `@admit` postcondition becomes a free (assume-only) postcondition of the\ngenerated bodiless procedure: an unverified modeling assumption the\nverification depends on, like the trusted return-type assumption.\n\nBecause the `@ensures` diagnostic is fatal, loading any PySpec module that\ncontains a modeled `@ensures` aborts the analysis, even when the analyzed code\nnever calls the affected procedure. This loud failure prevents Strata from\nsilently weakening a user-authored contract; switching the contract to\n`@admit` restores the assumption while making its unverified status explicit.\n\nThe split is by whether there is a body to verify: `@ensures` is a claim to\n*verify* against an implementation, `@admit` is the acknowledged, unverified\nassumption for bodyless declarations. PySpec declarations are bodyless models,\nso `@ensures` is rejected there and `@admit` is the supported form — the same\ndivision as Dafny's verified `ensures` versus `{:extern}` declarations, whose\npostconditions must be acknowledged with `{:axiom}`.\n\n## Rejection over silent mistranslation\n\nSpec constructs the dictionary map model cannot express are rejected with\nfatal diagnostics rather than lowered approximately: dict quantifiers over\nnon-string keys (\"dict quantifier requires str keys\") and `**kwargs` without\n`Unpack[TypedDict]` (`kwargsExpansionError`, which would otherwise silently\ndrop any `@requires` mentioning it). On the Laurel path, a return\nannotation's dict schema is likewise never assumed at call sites, only the\ncoarse type tag is; schema claims require `@admit`, same as `@ensures`. The\nDyn path assumes the schema of a PySpec model's return type at call sites,\nwithout an `@admit`. This is a trusted assumption, which `docs/PythonToDyn.md`\n§12.9 (*Return schemas*) states.\n\nDiagnostic strings are not a stable interface; consumers classify runs by\nexit code and the `RESULT:`/`DETAIL:` lines. Known completeness limitation\n(not a soundness risk): a fully-havoced `Any` hitting a caller-side map\nschema quantifier can verify as UNKNOWN.\n\n## Dependencies\n\n- `Strata` (parent package) - Core IR, Laurel IR, verification infrastructure, SMT backend\n- `StrataDDM` (transitive via Strata) - Dialect Definition Mechanism, Ion format\n\n## File Structure\n\nThe package is the repository root:\n\n```\n.\n├── StrataPython.lean              # Public API (readPythonIon, pySpecsDir, pyTranslateLaurel, etc.)\n├── StrataPython/\n│   ├── Cli.lean                   # Shared CLI helpers for the Scripts/ executables\n│   ├── PythonDialect.lean         # DDM dialect definition + generated types (expr, stmt, etc.)\n│   ├── PythonIdent.lean           # Module-qualified Python identifiers\n│   ├── ReadPython.lean            # Read Python AST from Ion format\n│   ├── PythonToCore.lean          # Direct Python → Core translation\n│   ├── PythonToLaurel.lean        # Python → Laurel translation (main pipeline)\n│   ├── PySpecPipeline.lean        # PySpec reading, overload resolution, Laurel construction\n│   ├── PyFactory.lean             # Core expression factory with regex support\n│   ├── CorePrelude.lean           # Python Core runtime prelude\n│   ├── PythonLaurelCorePrelude.lean  # Laurel-translated runtime prelude\n│   ├── PythonRuntimeLaurelPart.lean  # Runtime support as Laurel declarations\n│   ├── PythonLaurelTypedExpr.lean    # Type-tagged Laurel expression builders\n│   ├── FunctionSignatures.lean    # Function signature types for Core translation\n│   ├── OverloadTable.lean         # Overload dispatch table\n│   ├── Specs.lean                 # PySpec file reading, module discovery, translation\n│   ├── Specs/\n│   │   ├── DDM.lean               # PySpec DDM dialect and serialization\n│   │   ├── Decls.lean             # PySpec type declarations (SpecType, FunctionDecl, etc.)\n│   │   ├── IdentifyOverloads.lean # AST walker for overload resolution\n│   │   ├── MessageKind.lean       # Pipeline message classification\n│   │   └── ToLaurel.lean          # PySpec → Laurel translation\n│   ├── Regex/\n│   │   ├── ReParser.lean          # Python regex parser\n│   │   └── ReToCore.lean          # Regex → Core SMT translation\n│   ├── Dyn/                       # Python on Dyn: environment, builder, scopes, translator\n│   └── Pipeline/\n│       └── PyAnalyzeLaurel.lean   # Full analysis pipeline (Python → Laurel → Core → SMT)\n├── StrataDyn/                     # Dyn, a typed SSA IR (independent of StrataPython)\n├── StrataDynTest/                 # Dyn core tests\n├── Scripts/                       # Executable entry points (pyInterpret, pyAnalyzeLaurel, etc.)\n├── Python/\n│   ├── pyhard/                    # pyhard.py: the loop-invariant markers that programs import\n│   └── strata-python/             # Python tooling package (Ion reader, dialect generator)\n├── StrataPythonTest/              # Compile-time tests (built with lake build)\n├── StrataPythonTestExtra/         # Runtime tests (run with lake test, require Python)\n├── StrataPythonFrontEndTestMain.lean # Test driver (`lake test`) for StrataPythonTestExtra\n├── docs/                          # Dyn reference, Python-to-Dyn spec, Dyn guide (dyn/)\n├── AGENTS.md                      # Guide for AI agents working in this package\n├── lakefile.toml\n├── lean-toolchain\n└── lake-manifest.json\n```\n\n## Dyn\n\nDyn is a typed SSA intermediate representation in Lean, whose types and instructions are\ndeclared by a layered environment. It is split across two directories:\n\n| Directory | Contents | Tests |\n|---|---|---|\n| `StrataDyn/` | The core IR, builder, environment DSL, well-formedness checker, the printer and reader of its text form, and in `StrataDyn/Core/` the translation of Dyn types to Core types (namespace `Strata.Dyn`). Imports nothing from StrataPython | `StrataDynTest/`; `StrataPythonTestExtra/DynReadTest.lean` reads every translator golden back and puts it in canonical form, and `DynRefToRegTest.lean` runs ref-to-reg on each |\n| `StrataPython/Dyn/` | Python on Dyn: the Python environment (`Env.lean`), the emission helpers (`Build.lean`), name resolution (`Scope.lean`), the declared shapes of classes (`Shape.lean`), the shape check of comprehensions (`CompShape.lean`), the size lemmas and tactic that the termination proofs of name resolution and the translator share (`Termination.lean`), the translator (`Translate.lean`) and properties of it (`TranslateProps.lean`), Python's canonical form (`Canonical.lean`) and the `pydyn` commands (`Cli.lean`) | `StrataPythonTest/Dyn/`; `StrataPythonTestExtra/DynTranslateTest.lean` and `PyScopeTest.lean` run the translator and the scope pass over the programs in `StrataPythonTest/Dyn/dyn_tests/`, listed in `StrataPythonTest/Dyn/dyn_tests.txt`; `DynCanonicalTest.lean` checks the canonical form of the six example programs `g01` to `g06`, each of which exercises some properties of the canonical form |\n| `StrataPython/Dyn/Sem/` | The Python semantics, the library `StrataPythonSem`: a rule for each `py.*` operation (`Rules/`, over the protocols of `Proto/`), the world they run on, and the proofs that each rule stays within its effect and keeps its certificate; `docs/PythonToDyn.md` §13 describes it | `StrataPythonTest/Dyn/Sem/`; `StrataPythonTestExtra/SemDiffTest.lean` compares `pydyn run` with CPython 3.12 on the corpus and the test programs, and `SemScaleTest.lean` and `SemLoopsTest.lean` check how its cost grows |\n\n[`docs/Dyn.md`](./docs/Dyn.md) is the Dyn reference, and\n[`docs/PythonToDyn.md`](./docs/PythonToDyn.md) specifies how Python lowers to it.\n[`docs/dyn/`](./docs/dyn/README.md) is \"Introduction to Dyn\", a guide for anyone\nwriting a new front end, built as its own Verso project.\n\n`lake exe pydyn dyn FILE` prints the diagnostics and the Dyn module for `FILE`, a\n`.py` file (parsed with `python -m strata_python.gen`; `PYTHON` selects the interpreter) or a\nPython Ion file. `lake exe pydyn canonical FILE` prints the same, with every function put in\ncanonical form (see \"Canonical form\" in `docs/Dyn.md`). If a function cannot be put in that\nform, the command prints a comment that says why, and then the module as translated.\n`lake exe pydyn read FILE` reads a printed Dyn module, such as a translator golden, and\nprints it again. All three print constants folded into their uses, or with `--full` each on its\nown line. `lake exe pydyn features FILE` prints the Python features a Python Ion file uses.\n`lake exe pydyn run FILE` runs a `.py` file with the Python semantics and prints its trace: its\noutput, its outcome and its globals, or the gap where the semantics stops (`docs/PythonToDyn.md`\n§13.1). `pydyn --help` lists the subcommands.\n\n## Spec quantifiers\n\nWithin a PySpec function body, each supported `assert P` contributes the formula\n`P` to the function's generated preconditions; the imperative `assert` itself is\nnot part of the logical expression. PySpec expressions may quantify over lists\nand dictionaries using `all()` and `any()`:\n\n- **Universal** — `all(P(x) for x in xs)` lowers to `∀`.\n- **Existential** — `any(P(x) for x in xs)` lowers to `∃`.\n\nSupported collection forms (the iterable's static type determines the domain):\n\n| Syntax | Domain |\n|--------|--------|\n| `for x in xs` | List elements |\n| `for k in d` or `for k in d.keys()` | Dict string keys |\n| `for v in d.values()` | Dict values (via `d[k]` lookup) |\n| `for k, v in d.items()` | Dict key-value pairs |\n\nStatement-form universal quantifiers (`for ...: assert ...`) remain supported\nfor compatibility with generated PySpecs; `assert all(...)` is preferred for\nnew specifications. List domains currently bind only the element, not its index,\nso a quantified assertion message cannot identify the failing index.\n\nAn optional `if` guard filters the quantification:\n`assert all(len(k) >= 1 for k in Keys if k != sentinel)` lowers to\n`∀ k. membership(k) ⟹ (k ≠ sentinel ⟹ len(k) ≥ 1)`.\n\n**Caveat: an `any(...)` (∃) precondition can be refuted but never proven.**\nThe encoding uses collection membership as the SMT trigger. In goal position\ntriggers do not synthesize a witness, so a *genuinely satisfied* existential\nverifies as `unknown` — not `✔️` — while a *false* one is refuted. An `any(...)`\nprecondition therefore only flags the case where no element can satisfy it; it\nis a bug-finding signal, not a guarantee the verifier can discharge. Do not\nwrite an `any(...)` precondition expecting callers that satisfy it to verify\ngreen.\n\nIf you need a guarantee callers can discharge, state it universally or\nstructurally instead. For non-emptiness, require `len(xs) >= 1`. Where the\nwitness matters, take it as a parameter and assert a property of it directly —\n`assert Needle in Keys` is a membership check the solver can prove, unlike\n`assert any(k == Needle for k in Keys)`, which expresses the same requirement\nexistentially and therefore cannot be.\n\n## Signature order: module ghosts are emitted first\n\nModule-scope `ghost(...)` declarations are always emitted before all other\nsignatures, regardless of source position, so a contract can forward-reference\na ghost declared later in the file. Consumers should bucket signatures by kind\nrather than rely on array order.\n\n## Testing\n\n### Compile-time tests (no Python required)\n\n```bash\nlake build StrataPythonTest\n```\n\n### Runtime tests (require the `strata` Python packages installed)\n\n```bash\nPYTHON=python lake test\n```\n\nThe runtime tests require both the `strata-base` package (from the parent\nStrata repository) and the in-repo `strata-python` package:\n\n```bash\npip install \u003CStrataDDM-repo>/Python/strata\npip install ./Python/strata-python\n```\n\n### Regex differential tests\n\n`StrataPythonTestExtra/RegexDiffTest.lean` compares Strata's SMT regex backend\nagainst Python's `re` on the corpus in `StrataPythonTest/Regex/corpus.tsv`. It is\none of the runtime tests above and has the same requirements. To run only it:\n\n```bash\nPYTHON=python lake test -- RegexDiffTest\n```\n\n## Key Namespaces\n\n| Namespace | Contents |\n|-----------|----------|\n| `StrataPython` | Public API, generated AST types (expr, stmt, etc.), Core translation |\n| `StrataPython.ToLaurel` | Python-to-Laurel translation internals |\n| `StrataPython.Specs` | PySpec reading, translation, module discovery |\n| `StrataPython.Specs.ToLaurel` | PySpec-to-Laurel declaration generation |\n| `StrataPython.Specs.IdentifyOverloads` | Overload resolution AST walker |\n| `StrataPython.Laurel` | Type-tagged Laurel expression builders |\n| `StrataPython.Pipeline` | Full pyAnalyzeLaurel pipeline |\n| `Strata.Dyn` | The Dyn IR (`StrataDyn/`) |\n| `StrataPython.Dyn` | Python on Dyn (`PyScope`, `PyBuild`, `PyTranslate`) |\n| `StrataPython.Dyn.Sem` | The Python semantics (`StrataPython/Dyn/Sem/`) |\n",1795981083803]