ext(00-08): RFC-EXT-0003 core/extension boundary, math detach and release stdlib

Implements issue #3 (RFC-EXT-0003) slices on the post-3.0.0-beta.1 tree.

PR-00/01/H-06: reproduce and fix sibling heading mode inheritance.
build_units now pops the current and same-or-higher-level headings from the
ancestor stack before deriving the inherited mode, so an unmarked heading can never
inherit the previous sibling. Covered by the units matrix, conformance fixtures
22/23, and black-box heading_inheritance through check --emit/run/call.

PR-02/H-08: the deterministic release archive now ships the complete verified
stdlib/ tree. package.py and smoke.py recompute the runtime tree/alias digests,
record them in RELEASE_INFO.json.stdlib, and fail on mismatch; smoke removes the
bundle and requires a fail-closed run. Release discovery no longer falls back to the
compile-time source tree (debug builds keep that development convenience).

PR-03/H-04: one marqdo_host::CORE_RESOURCE_KINDS registry is used by both the CLI
provider-manifest validator and every trusted host registration path; all six core
kinds are rejected as provider name or declared kind before registration.
H-03: docs/architecture/resource-operations.md records every reviewed
resource_request operation and architecture_boundaries pins the exact allowlist; new
domain operations are forbidden in core (ADR-0062).

PR-04/H-01: remove math.parse/eval/substitute/simplify/differentiate from
BUILTINS, HostOp, the runtime, the host kernel and the workspace
(crates/marqdo-math deleted). Formula stays inert; Int/Float arithmetic stays.
Math algorithms are a pure examples/math-library package plus an optional
examples/math-backend ABI plugin that requests the math.compute capability
(ADR-0061). Removed calls are static symbol.unknown; the math import namespace is
released again. Tests/examples/specs migrated; new math_library black-box test.

PR-05/06 Step A: ADR-0060 classifies @exec/@knowledge as the closed Core Modes
and specifies the Proposed metadata-only Heading Annotations v1 (target 3.1,
sem.invalid_mode_marker unchanged, Analysis v2 unchanged). ADR-0063 records the
foreign F-A retention and deferred F-B removal.

Docs/status/compatibility/changelog and the RFC-EXT-0003 evidence file are updated.
Full local gate: cargo fmt PASS, clippy -D warnings PASS, workspace tests 586
passed/0 failed/2 ignored, python tools/ci 28 passed.
This commit is contained in:
cflmy committed 2026-11-22 18:57:33 +08:00
1 parent 0fe5f42a62
commit a67f344b6b
88 files changed
+2633 -3503

No files matched your search

+1
View File
@@ -17,6 +17,7 @@ examples/plugin-multi-export/solver.so
examples/plugin-demo/build/ examples/plugin-demo/build/
examples/plugin-multi-export/build/ examples/plugin-multi-export/build/
examples/provider-demo/build/ examples/provider-demo/build/
examples/math-backend/build/
# Release artifacts # Release artifacts
dist/ dist/
+59
View File
@@ -12,6 +12,65 @@ do not follow the product version. Dates use ISO 8601.
## Unreleased (post `3.0.0-beta.1`) ## Unreleased (post `3.0.0-beta.1`)
### Core/extension boundary — RFC-EXT-0003 (issue #3)
Executed evidence: [`docs/evidence/2026-11-22-rfc-ext-0003-core-hardcoding.md`](docs/evidence/2026-11-22-rfc-ext-0003-core-hardcoding.md).
Frozen decisions: ADR-0060 (heading modes/annotations), ADR-0061 (math
detach), ADR-0062 (resource-operation ownership/core kinds), ADR-0063
(foreign F-A transition).
#### Breaking changes (beta line; migrate before the next beta/stable)
- **`math.*` core builtins removed.** `math.parse`, `math.eval`,
`math.substitute`, `math.simplify` and `math.differentiate` no longer exist in
`BUILTINS`, `HostOp`, the runtime or the host. A document that calls one now
fails statically with `symbol.unknown`; there is no `math.unsupported` runtime
fallback and no old-name compatibility parser. `crates/marqdo-math` is removed
from the workspace and host dependency graph. `Int`/`Float` arithmetic and the
inert Markdown `Formula` value stay. Math algorithms move to pure `.mq.md`
packages (`examples/math-library/`) or an explicitly selected ABI backend with
the `math.compute` capability (`examples/math-backend/`). The historical
`math` import namespace is released, so `import: { math: ... }` is accepted
again. Migration: [`spec/math.md`](spec/math.md).
- **Sibling heading inheritance bug fixed (H-06).** `build_units` now removes the
current and same-or-higher-level headings from the ancestor stack *before*
deriving the inherited mode. An unmarked heading can no longer inherit the
previous sibling's mode: under `# @knowledge` a `## @exec` sibling followed by an
unmarked `##` leaves the latter Knowledge/inert; under `# @exec` a `## @knowledge`
sibling followed by an unmarked `##` makes the latter Exec/callable. This is a
correctness fix with new conformance/black-box/`check --emit` coverage.
- **Release archive now ships the verified `stdlib/`.** The archive contains
`stdlib.json` and every `.mq.md` module; `RELEASE_INFO.json` records name,
version, tree digest, alias digest, count and file list. `package.py` recomputes
both digests and refuses a mismatch; `smoke.py` re-verifies them and fails
closed when the bundle is removed. Release builds no longer fall back to the
compile-time source tree (debug builds keep a development-only fallback). An
independent `ubuntu:24.04` cold-install container check is recorded in the
evidence.
- **Core resource kinds are one registry (H-04).** `marqdo_host::CORE_RESOURCE_KINDS`
(`stdio`, `file`, `tcp`, `tls`, `udp`, `tcp-listener`) is now used by both the
CLI provider-manifest validator and every trusted host registration path; a provider
name or declared kind equal to a core kind is rejected before registration.
- `resource_request` operation ownership is reviewed and enforced by an
architecture gate. New domain operations are forbidden in the core; see
[`docs/architecture/resource-operations.md`](docs/architecture/resource-operations.md)
and ADR-0062.
#### Proposed, not implemented
- **Heading Annotations v1 (H-05/H-07/H-13).** `@exec`/`@knowledge` are frozen
as the only Core Modes and alone decide execution; a declarative,
metadata-only `@namespace.identifier` annotation layer is specified as
**Proposed** with target `3.1.x`. The current parser still rejects any other
leading `@foo` with `sem.invalid_mode_marker`; no `annotation.unknown` code,
manifest loader, Analysis v3 or sidecar exists in this build. Contracts:
ADR-0060 and [`spec/heading-annotations-v1.md`](spec/heading-annotations-v1.md).
- **Foreign F-B removal is deferred (H-02).** The permission-gated one-shot
`foreign.run`/`foreign.call` + `KernelRegistry` stay as the controlled
OS-boundary primitive (F-A); removal needs a versioned generic process/worker
capability and the existing security negatives. ADR-0063 and
[`spec/foreign.md`](spec/foreign.md) §8.
### Runtime observability — Execution Events v1 (RFC-OBS-0001, ADR-0059) ### Runtime observability — Execution Events v1 (RFC-OBS-0001, ADR-0059)
- `marqdo run` and `marqdo call` accept `--event-stream jsonl`: the CLI stdout - `marqdo run` and `marqdo call` accept `--event-stream jsonl`: the CLI stdout
+18 -2
View File
@@ -44,6 +44,22 @@ Consequences for compatibility:
[`docs/STATUS.md`](docs/STATUS.md) and [`docs/STATUS.md`](docs/STATUS.md) and
[`docs/evidence/2026-11-21-semantics-v2-green.md`](docs/evidence/2026-11-21-semantics-v2-green.md). [`docs/evidence/2026-11-21-semantics-v2-green.md`](docs/evidence/2026-11-21-semantics-v2-green.md).
## Post-`3.0.0-beta.1` boundary changes (RFC-EXT-0003)
These land after the beta tag and **before any next beta/stable tag**; they are
intentional beta-line incompatibilities. Frozen decisions: ADR-0060..0063; executed
evidence: [`docs/evidence/2026-11-22-rfc-ext-0003-core-hardcoding.md`](docs/evidence/2026-11-22-rfc-ext-0003-core-hardcoding.md).
| Change | Compatibility rule |
|---|---|
| `math.parse/eval/substitute/simplify/differentiate` removed from the core | **Breaking.** A call is a static `symbol.unknown`; there is no old-name parser, no `math.unsupported` runtime fallback and no ABI/Builtin shim. `Formula` stays an inert Markdown resource. Migrate to a pure `.mq.md` package or an explicitly selected ABI backend; `spec/math.md`. The `math` import namespace is released (no builtin conflict). |
| Sibling heading mode inheritance corrected (H-06) | **Behaviour fix.** Unmarked headings inherit the nearest ancestor, never the previous sibling. Documents that relied on the buggy sibling leak change: a former accidental Exec sibling can become inert Knowledge (or vice versa). Covered by conformance/black-box/`check --emit` tests; no syntax/version change. |
| Release archive must ship the verified `stdlib/` | **Delivery requirement.** Archive contains `stdlib.json` + all modules and `RELEASE_INFO.json` carries its name/version/tree/alias digests/count/files. Removing or tampering with it fails closed; release builds do not fall back to the build-machine source path. |
| Core resource kinds enforced on every registration path (H-04) | Provider name or declared kind equal to `stdio/file/tcp/tls/udp/tcp-listener` is rejected with `ext.manifest_invalid` (CLI) / `ResourceUnsupported` (host) before registration. No provider may shadow a core kind. |
| `resource_request` operation ownership (H-03) | New domain/business operations are forbidden in the core: ship a pure `.mq.md` package, ABI export or Provider. The exact reviewed allowlist is pinned by `architecture_boundaries.rs`; see `docs/architecture/resource-operations.md`. |
| Heading Annotations v1 (H-05/H-07) | **Proposed, not implemented.** This build still rejects unknown `@foo` with `sem.invalid_mode_marker`; no annotation manifest, `annotation.unknown`, Analysis v3 or sidecar exists yet. Target `3.1.x`; ADR-0060 and `spec/heading-annotations-v1.md`. |
| Foreign removal F-B (H-02) | **Deferred, not claimed.** The one-shot permission-gated `foreign.*` primitive remains (F-A); its grants/digest/timeout/wire/output negatives are unchanged and must not be skipped. ADR-0063 and `spec/foreign.md` §8. |
## Public protocol versions ## Public protocol versions
| Surface | Version | Compatibility rule | | Surface | Version | Compatibility rule |
@@ -56,8 +72,8 @@ Consequences for compatibility:
| Execution Events | v1 | Live NDJSON for `run/call --event-stream jsonl`; independent version axis. Values are opt-in and bounded; unknown majors rejected. Not yet part of the tagged beta archive (post-beta addition). | | Execution Events | v1 | Live NDJSON for `run/call --event-stream jsonl`; independent version axis. Values are opt-in and bounded; unknown majors rejected. Not yet part of the tagged beta archive (post-beta addition). |
| CLI Tool | v1 | Manifest schema, SemVer negotiation and whole-bundle digest are stable for v1. | | CLI Tool | v1 | Manifest schema, SemVer negotiation and whole-bundle digest are stable for v1. |
| Plugin ABI | v1 | Struct layout/version negotiation frozen; `--trust-native-plugin` is required for in-process loading. The static manifest signature is authoritative; `run` reconciles loaded exports/signatures/owners/artifact digests exactly (`ext.plugin_binding_mismatch`); ABI v1 defaults are rejected. | | Plugin ABI | v1 | Struct layout/version negotiation frozen; `--trust-native-plugin` is required for in-process loading. The static manifest signature is authoritative; `run` reconciles loaded exports/signatures/owners/artifact digests exactly (`ext.plugin_binding_mismatch`); ABI v1 defaults are rejected. |
| Resource Provider manifest | v2 | `schema_version: 2`, `abi: c-abi-1`, `transport: worker`; v1 is rejected (`ext.unsupported_provider_schema`), no silent migration. CLI `--provider`/`--allow-provider`; trusted worker, not an OS sandbox. | | Resource Provider manifest | v2 | `schema_version: 2`, `abi: c-abi-1`, `transport: worker`; v1 is rejected (`ext.unsupported_provider_schema`), no silent migration. CLI `--provider`/`--allow-provider`; trusted worker, not an OS sandbox. The six core kinds come from one `marqdo_host::CORE_RESOURCE_KINDS` registry and are rejected as a provider name or kind (ADR-0062). |
| Callable resolution | ADR-0054 | One registry + one binding pass; `check` and `run` bind the same `CallSiteKey`; no runtime name fallback. Import aliases colliding with builtin/plugin dotted namespaces are rejected. | | Callable resolution | ADR-0054 | One registry + one binding pass; `check` and `run` bind the same `CallSiteKey`; no runtime name fallback. Import aliases colliding with builtin/plugin dotted namespaces are rejected. The `math` namespace is no longer a builtin namespace (ADR-0061). |
| Analysis `calls[].state/target` | v2 (projection) | Now projected from the unique binding; official stdlib aliases appear as `function`. Schema/version unchanged; private binding table not serialized. | | Analysis `calls[].state/target` | v2 (projection) | Now projected from the unique binding; official stdlib aliases appear as `function`. Schema/version unchanged; private binding table not serialized. |
| Extension selection | lock v4 | `marqdo.yaml.extensions` only `./path` or `@alias/path`; declaration is not a grant; declared identity must match the lock (`ext.extension_lock_mismatch`). | | Extension selection | lock v4 | `marqdo.yaml.extensions` only `./path` or `@alias/path`; declaration is not a grant; declared identity must match the lock (`ext.extension_lock_mismatch`). |
| Foreign wire | v1 | One-shot request envelope; provider descriptors are explicit. | | Foreign wire | v1 | One-shot request envelope; provider descriptors are explicit. |
Generated
-13
View File
@@ -422,7 +422,6 @@ dependencies = [
"marqdo-host", "marqdo-host",
"marqdo-ir", "marqdo-ir",
"marqdo-markdown", "marqdo-markdown",
"marqdo-math",
"marqdo-package", "marqdo-package",
"marqdo-plugin-abi", "marqdo-plugin-abi",
"marqdo-runtime", "marqdo-runtime",
@@ -488,7 +487,6 @@ dependencies = [
"glob", "glob",
"libloading", "libloading",
"marqdo-foreign", "marqdo-foreign",
"marqdo-math",
"marqdo-plugin-abi", "marqdo-plugin-abi",
"marqdo-sandbox", "marqdo-sandbox",
"marqdo-span", "marqdo-span",
@@ -525,17 +523,6 @@ dependencies = [
"unicode-normalization", "unicode-normalization",
] ]
[[package]]
name = "marqdo-math"
version = "3.0.0-beta.1"
dependencies = [
"marqdo-value",
"num-bigint",
"num-rational",
"num-traits",
"serde",
]
[[package]] [[package]]
name = "marqdo-package" name = "marqdo-package"
version = "3.0.0-beta.1" version = "3.0.0-beta.1"
-2
View File
@@ -7,7 +7,6 @@ members = [
"crates/marqdo-markdown", "crates/marqdo-markdown",
"crates/marqdo-ir", "crates/marqdo-ir",
"crates/marqdo-frontend", "crates/marqdo-frontend",
"crates/marqdo-math",
"crates/marqdo-foreign", "crates/marqdo-foreign",
"crates/marqdo-plugin-abi", "crates/marqdo-plugin-abi",
"crates/marqdo-provider-worker", "crates/marqdo-provider-worker",
@@ -34,7 +33,6 @@ marqdo-expression = { path = "crates/marqdo-expression" }
marqdo-markdown = { path = "crates/marqdo-markdown" } marqdo-markdown = { path = "crates/marqdo-markdown" }
marqdo-ir = { path = "crates/marqdo-ir" } marqdo-ir = { path = "crates/marqdo-ir" }
marqdo-frontend = { path = "crates/marqdo-frontend" } marqdo-frontend = { path = "crates/marqdo-frontend" }
marqdo-math = { path = "crates/marqdo-math" }
marqdo-foreign = { path = "crates/marqdo-foreign" } marqdo-foreign = { path = "crates/marqdo-foreign" }
marqdo-plugin-abi = { path = "crates/marqdo-plugin-abi" } marqdo-plugin-abi = { path = "crates/marqdo-plugin-abi" }
marqdo-host = { path = "crates/marqdo-host" } marqdo-host = { path = "crates/marqdo-host" }
+16 -11
View File
@@ -219,11 +219,13 @@ rules are [`RFC-LANG-0002`](docs/architecture/RFC-LANG-0002-unified-semantics.md
capability dropping, rlimits, a wall-clock supervisor and child capability dropping, rlimits, a wall-clock supervisor and child
self-verification (ADR-0021). It is probe-gated and verified in a disposable self-verification (ADR-0021). It is probe-gated and verified in a disposable
Ubuntu VM; unsupported hosts fail closed. Ubuntu VM; unsupported hosts fail closed.
* **P5 Math/Foreign** — native `Formula` value from `$$...$$`; `math.parse/ * **P5 Math/Foreign** — native inert `Formula` value from `$$...$$`; the host
eval/substitute` over a documented exact-rational subset; one-shot Python/ `math.*` builtin API was removed after `3.0.0-beta.1` (ADR-0061) and math
Node kernels via `foreign.run/call` with typed wire protocol, timeout and algorithms now live in pure `.mq.md` packages or an explicitly selected ABI
output limits; pinned provider/environment digests and ADR-0020 environment backend with the `math.compute` capability; one-shot Python/Node kernels via
binding. `foreign.run/call` (controlled F-A OS boundary, ADR-0063) with typed wire
protocol, timeout and output limits; pinned provider/environment digests and
ADR-0020 environment binding.
* **P6 plugin ABI** — frozen C ABI v1 header (`include/marqdo_plugin_abi_v1.h`), * **P6 plugin ABI** — frozen C ABI v1 header (`include/marqdo_plugin_abi_v1.h`),
host bindings, Rust SDK (`mq_plugin_entry!`), `plugin.yaml` validation, host bindings, Rust SDK (`mq_plugin_entry!`), `plugin.yaml` validation,
target-triple + sha256 artifact verification, native and isolated worker target-triple + sha256 artifact verification, native and isolated worker
@@ -248,7 +250,7 @@ cargo clippy --workspace --all-targets -- -D warnings
* **Strict is Linux-only and L1-only.** `--mode strict` enables the * **Strict is Linux-only and L1-only.** `--mode strict` enables the
Bubblewrap supervisor only when its runtime probe passes; otherwise it exits Bubblewrap supervisor only when its runtime probe passes; otherwise it exits
1. It supports pure Marqdo + Math and rejects Foreign, plugins, kernels, 1. It supports pure Marqdo arithmetic and rejects Foreign, plugins, kernels,
external grants and trace files (exit 2). Worker plugins provide external grants and trace files (exit 2). Worker plugins provide
crash/address-space isolation, not an OS sandbox, and are not allowed in crash/address-space isolation, not an OS sandbox, and are not allowed in
strict. strict.
@@ -268,8 +270,10 @@ cargo clippy --workspace --all-targets -- -D warnings
the first. the first.
* **`fmt` is minimal** (line endings/trailing newlines), not AST-preserving * **`fmt` is minimal** (line endings/trailing newlines), not AST-preserving
reformatting. reformatting.
* **Math is a limited calculator**, not a CAS/prover: no `simplify`/ * **Math is not a core API.** `math.*` builtins were removed after
`differentiate`/matrices/series; equation solving is affine-only. `3.0.0-beta.1` (ADR-0061); `Formula` Markdown stays inert, and math
algorithms come from explicit pure `.mq.md` imports or a trusted ABI backend.
The core promises no CAS/prover, solver or evaluator.
* **Foreign kernels are unsandboxed one-shot child processes** (no sessions, * **Foreign kernels are unsandboxed one-shot child processes** (no sessions,
no state bridge); they run with the host user's filesystem/network access. no state bridge); they run with the host user's filesystem/network access.
* Finite floats are IEEE-754 binary64; the typed wire round-trip is exact * Finite floats are IEEE-754 binary64; the typed wire round-trip is exact
@@ -285,12 +289,11 @@ crates/marqdo-expression strict expression/statement parser
crates/marqdo-markdown frozen comrak profile, canonical AST, front matter crates/marqdo-markdown frozen comrak profile, canonical AST, front matter
crates/marqdo-ir module/unit/function/statement IR, builtin table crates/marqdo-ir module/unit/function/statement IR, builtin table
crates/marqdo-frontend heading scopes, mapping, inference, static calls crates/marqdo-frontend heading scopes, mapping, inference, static calls
crates/marqdo-math exact-rational Formula subset
crates/marqdo-foreign Python/Node one-shot kernel supervisor crates/marqdo-foreign Python/Node one-shot kernel supervisor
crates/marqdo-sandbox mode parsing + platform isolation detection crates/marqdo-sandbox mode parsing + platform isolation detection
crates/marqdo-plugin-abi C ABI v1 mirrors, manifest, artifacts, loader crates/marqdo-plugin-abi C ABI v1 mirrors, manifest, artifacts, loader
crates/marqdo-plugin-sdk Rust plugin SDK and entry macro crates/marqdo-plugin-sdk Rust plugin SDK and entry macro
crates/marqdo-host CapabilityHost, budgets, FS, math/foreign/plugin adapters crates/marqdo-host CapabilityHost, budgets, FS, foreign/plugin adapters, core resource kinds
crates/marqdo-runtime tree-walk interpreter crates/marqdo-runtime tree-walk interpreter
crates/marqdo-package marqdo.yaml / marqdo.lock / root discovery crates/marqdo-package marqdo.yaml / marqdo.lock / root discovery
crates/cli CLI composition root (binary `marqdo`) crates/cli CLI composition root (binary `marqdo`)
@@ -446,7 +449,9 @@ details in [`spec/callable-resolution.md`](spec/callable-resolution.md)):
`check` and `run` consume the same binding; an unknown export, wrong arguments `check` and `run` consume the same binding; an unknown export, wrong arguments
or a duplicate export fails before execution. An import alias that collides or a duplicate export fails before execution. An import alias that collides
with a builtin/plugin dotted namespace (for example importing a module as with a builtin/plugin dotted namespace (for example importing a module as
`math`) is rejected with `ext.import_namespace_conflict`; rename it. A plugin `resource`) is rejected with `ext.import_namespace_conflict`; rename it. The
historical `math` namespace was released when the `math.*` builtins were removed
(ADR-0061), so a `math:` import alias is now accepted. A plugin
manifest is the static contract: `run` verifies the loaded artifact and its manifest is the static contract: `run` verifies the loaded artifact and its
exports/signatures match the manifest exactly exports/signatures match the manifest exactly
(`ext.plugin_binding_mismatch` otherwise) and never synthesises a signature. (`ext.plugin_binding_mismatch` otherwise) and never synthesises a signature.
-1
View File
@@ -15,7 +15,6 @@ marqdo-expression = { workspace = true }
marqdo-markdown = { workspace = true } marqdo-markdown = { workspace = true }
marqdo-ir = { workspace = true } marqdo-ir = { workspace = true }
marqdo-frontend = { workspace = true } marqdo-frontend = { workspace = true }
marqdo-math = { workspace = true }
marqdo-foreign = { workspace = true } marqdo-foreign = { workspace = true }
marqdo-plugin-abi = { workspace = true } marqdo-plugin-abi = { workspace = true }
marqdo-host = { workspace = true } marqdo-host = { workspace = true }
+22 -10
View File
@@ -49,11 +49,10 @@ pub const MAX_PROVIDER_ARTIFACT_BYTES: u64 = 256 * 1024 * 1024;
/// Maximum manifest size (1 MiB); a manifest is metadata, not an artifact. /// Maximum manifest size (1 MiB); a manifest is metadata, not an artifact.
pub const MAX_PROVIDER_MANIFEST_BYTES: u64 = 1024 * 1024; pub const MAX_PROVIDER_MANIFEST_BYTES: u64 = 1024 * 1024;
/// Core resource kinds owned by the host; third parties may never override /// Core resource kinds are owned by the host and may never be overridden by a
/// them (RFC-EXT-0001 §5.3.1). `stdio`/`file`/`tcp`/`tls`/`udp`/`tcp-listener` /// provider (RFC-EXT-0001 §5.3.1, ADR-0062). The single source of truth is
/// are dispatched by `marqdo-host` before the provider registry is consulted. /// [`marqdo_host::CORE_RESOURCE_KINDS`]; this alias keeps the CLI wording.
pub const RESERVED_RESOURCE_KINDS: &[&str] = pub const RESERVED_RESOURCE_KINDS: &[&str] = marqdo_host::CORE_RESOURCE_KINDS;
&["stdio", "file", "tcp", "tls", "udp", "tcp-listener"];
/// Raw `provider.json` schema version 2 document. /// Raw `provider.json` schema version 2 document.
#[derive(Debug, Deserialize)] #[derive(Debug, Deserialize)]
@@ -835,13 +834,26 @@ mod tests {
} }
#[test] #[test]
fn reserved_kind_is_rejected() { fn every_core_kind_is_rejected_as_name_and_as_kind() {
let dir = tempdir("reserved"); let dir = tempdir("reserved");
let (path, sha) = artifact(&dir, "libdemo.so", b"provider-bytes"); let (path, sha) = artifact(&dir, "libdemo.so", b"provider-bytes");
let manifest = write_manifest(&dir, &manifest_text("demo.sensor", &["file"], &path, &sha)); for core_kind in marqdo_host::CORE_RESOURCE_KINDS {
let error = read_provider_manifests(&[manifest]).unwrap_err(); let as_kind = write_manifest(
assert_eq!(error.code, "ext.manifest_invalid"); &dir,
assert!(error.message.contains("reserved"), "{}", error.message); &manifest_text("demo.sensor", &[core_kind], &path, &sha),
);
let error = read_provider_manifests(&[as_kind]).unwrap_err();
assert_eq!(error.code, "ext.manifest_invalid");
assert!(error.message.contains("reserved"), "{}", error.message);
let as_name = write_manifest(
&dir,
&manifest_text(core_kind, &["demo.sensor"], &path, &sha),
);
let error = read_provider_manifests(&[as_name]).unwrap_err();
assert_eq!(error.code, "ext.manifest_invalid");
assert!(error.message.contains("reserved"), "{}", error.message);
}
let _ = std::fs::remove_dir_all(&dir); let _ = std::fs::remove_dir_all(&dir);
} }
+60 -13
View File
@@ -46,25 +46,39 @@ impl StdlibBundle {
/// Discover the bundle. /// Discover the bundle.
/// ///
/// Order: `MARQDO_STDLIB_DIR` (explicit, fail if invalid), a `stdlib` /// Order: `MARQDO_STDLIB_DIR` (explicit, fail if invalid), a `stdlib`
/// directory next to the executable, then the development tree. /// directory next to the executable, and finally — **debug builds only** — the
/// compile-time source tree. A release binary never falls back to a build
/// machine path: the release archive must ship a verified `stdlib/` next to
/// the binary (RFC-EXT-0003 H-08, ADR).
pub fn discover() -> Result<Option<Self>, String> { pub fn discover() -> Result<Option<Self>, String> {
if let Some(dir) = std::env::var_os(STDLIB_DIR_ENV) { if let Some(dir) = std::env::var_os(STDLIB_DIR_ENV) {
return Self::load(PathBuf::from(dir)).map(Some); return Self::load(PathBuf::from(dir)).map(Some);
} }
if let Ok(exe) = std::env::current_exe() { Self::discover_from_exe_dir(
if let Some(parent) = exe.parent() { std::env::current_exe()
let candidate = parent.join("stdlib"); .ok()
if candidate.is_dir() { .and_then(|exe| exe.parent().map(Path::to_path_buf)),
return Self::load(candidate).map(Some); )
} }
/// Discover from the directory that holds the executable, without the explicit
/// environment override. Release builds do not read the source tree.
fn discover_from_exe_dir(exe_dir: Option<PathBuf>) -> Result<Option<Self>, String> {
if let Some(parent) = exe_dir {
let candidate = parent.join("stdlib");
if candidate.is_dir() {
return Self::load(candidate).map(Some);
} }
} }
let dev = PathBuf::from(env!("CARGO_MANIFEST_DIR")) #[cfg(debug_assertions)]
.join("..") {
.join("..") let dev = PathBuf::from(env!("CARGO_MANIFEST_DIR"))
.join("stdlib"); .join("..")
if dev.is_dir() { .join("..")
return Self::load(dev).map(Some); .join("stdlib");
if dev.is_dir() {
return Self::load(dev).map(Some);
}
} }
Ok(None) Ok(None)
} }
@@ -457,6 +471,39 @@ mod tests {
assert!(bundle.resolve("../escape").is_err()); assert!(bundle.resolve("../escape").is_err());
} }
#[test]
fn sibling_stdlib_is_found_without_environment_override() {
let dir = tempfile::tempdir().unwrap();
let bundle = dir.path().join("stdlib");
std::fs::create_dir_all(&bundle).unwrap();
for entry in std::fs::read_dir(dev_bundle()).unwrap() {
let entry = entry.unwrap();
let target = bundle.join(entry.file_name());
if entry.path().is_dir() {
copy_dir(&entry.path(), &target);
} else {
std::fs::copy(entry.path(), target).unwrap();
}
}
let found = StdlibBundle::discover_from_exe_dir(Some(dir.path().to_path_buf()))
.unwrap()
.expect("sibling stdlib");
assert_eq!(found.root, bundle.canonicalize().unwrap());
}
fn copy_dir(source: &std::path::Path, target: &std::path::Path) {
std::fs::create_dir_all(target).unwrap();
for entry in std::fs::read_dir(source).unwrap() {
let entry = entry.unwrap();
let destination = target.join(entry.file_name());
if entry.path().is_dir() {
copy_dir(&entry.path(), &destination);
} else {
std::fs::copy(entry.path(), destination).unwrap();
}
}
}
#[test] #[test]
fn digest_tamper_is_rejected() { fn digest_tamper_is_rejected() {
let dir = tempfile::tempdir().unwrap(); let dir = tempfile::tempdir().unwrap();
+142 -1
View File
@@ -30,7 +30,6 @@ const WORKSPACE_CRATES: &[&str] = &[
"marqdo-markdown", "marqdo-markdown",
"marqdo-ir", "marqdo-ir",
"marqdo-frontend", "marqdo-frontend",
"marqdo-math",
"marqdo-foreign", "marqdo-foreign",
"marqdo-plugin-abi", "marqdo-plugin-abi",
"marqdo-provider-worker", "marqdo-provider-worker",
@@ -387,6 +386,148 @@ fn official_stdlib_public_aliases_are_verified_metadata() {
} }
} }
/// Reviewed ownership of every `Host::resource_request` operation
/// (`docs/architecture/resource-operations.md`, ADR-0062).
///
/// The gate extracts the literal operation names dispatched inside
/// `resource_request` and compares them with this reviewed allowlist. Adding a new
/// domain operation requires updating the architecture doc, the ADR and this list —
/// a bare source change cannot silently widen the core/resource boundary.
#[test]
fn resource_request_operation_allowlist_is_reviewed() {
use std::collections::BTreeSet;
const DOMAIN_OPERATIONS: &[&str] = &[
"process.run",
"regex.match",
"regex.captures",
"compress.gzip",
"compress.gunzip",
"random.bytes",
"env.get",
"clock.now",
];
const FS_OPERATIONS: &[&str] = &[
"read_at", "append", "walk", "exists", "metadata", "list", "mkdir", "remove", "rename",
];
let source = read(&repo_root().join("crates/marqdo-host/src/host.rs"));
let impl_start = source
.find("impl Host for StdHost {")
.expect("StdHost must implement Host");
let start = source[impl_start..]
.find(" fn resource_request(")
.expect("StdHost::resource_request must exist")
+ impl_start;
let rest = &source[start + 1..];
let end = rest
.find("\n fn consume_fuel(")
.expect("resource_request must end before consume_fuel");
let body = &rest[..end];
let mut domain = BTreeSet::new();
for line in body.lines() {
let mut cursor = line;
while let Some(index) = cursor.find("operation == \"") {
let text = &cursor[index + "operation == \"".len()..];
let name = text.split('"').next().expect("operation literal");
domain.insert(name.to_string());
cursor = &text[name.len()..];
}
}
let expected_domain: BTreeSet<String> = DOMAIN_OPERATIONS
.iter()
.map(|name| (*name).to_string())
.collect();
assert_eq!(
domain, expected_domain,
"new/changed resource_request domain operation; update docs/architecture/resource-operations.md, ADR-0062 and this allowlist"
);
assert!(
body.contains("strip_prefix(\"fs.\")"),
"the fs.* operation group must stay the only unprefixed dispatch path"
);
let mut fs = BTreeSet::new();
for line in body.lines() {
let mut cursor = line;
while let Some(index) = cursor.find("name == \"") {
let text = &cursor[index + "name == \"".len()..];
let name = text.split('"').next().expect("fs operation literal");
fs.insert(name.to_string());
cursor = &text[name.len()..];
}
}
// The remaining fs operations are grouped in the arity match block.
let arity_start = body
.find("let expected = match name {")
.expect("fs arity match block");
let arity_end = body[arity_start..]
.find(" };")
.expect("fs arity match block end");
for line in body[arity_start..arity_start + arity_end].lines() {
let Some(arrow) = line.find("=>") else {
continue;
};
let mut in_quote = false;
let mut name = String::new();
for ch in line[..arrow].chars() {
if ch == '"' {
if in_quote && !name.is_empty() {
fs.insert(name.clone());
}
name.clear();
in_quote = !in_quote;
} else if in_quote {
name.push(ch);
}
}
}
let expected_fs: BTreeSet<String> = FS_OPERATIONS
.iter()
.map(|name| (*name).to_string())
.collect();
assert_eq!(
fs, expected_fs,
"new/changed fs.* resource operation; update docs/architecture/resource-operations.md, ADR-0062 and this allowlist"
);
}
/// RFC-EXT-0003 H-01: the CLI/host must not link the removed domain math
/// kernel and `resource_request` must not dispatch a math.* domain operation.
#[test]
fn domain_math_kernel_is_not_part_of_the_core() {
let root = repo_root();
for manifest in [
"Cargo.toml",
"crates/marqdo-host/Cargo.toml",
"crates/cli/Cargo.toml",
] {
let text = read(&root.join(manifest));
assert!(
!text.contains("marqdo-math"),
"{manifest} must not depend on the removed domain math kernel"
);
}
assert!(
!root.join("crates/marqdo-math").exists(),
"crates/marqdo-math was removed from the core repository"
);
let host = read(&root.join("crates/marqdo-host/src/host.rs"));
for removed in [
"MathEval",
"MathParse",
"MathSubstitute",
"MathSimplify",
"MathDifferentiate",
] {
assert!(
!host.contains(removed),
"host.rs still dispatches {removed}"
);
}
}
fn hex(bytes: &[u8]) -> String { fn hex(bytes: &[u8]) -> String {
let mut out = String::with_capacity(bytes.len() * 2); let mut out = String::with_capacity(bytes.len() * 2);
for byte in bytes { for byte in bytes {
+3 -3
View File
@@ -140,12 +140,12 @@ fn stdout(output: &Output) -> String {
fn import_alias_conflicting_with_builtin_namespace_is_rejected() { fn import_alias_conflicting_with_builtin_namespace_is_rejected() {
let dir = TempDir::new("call01"); let dir = TempDir::new("call01");
write( write(
&dir.path().join("math.mq.md"), &dir.path().join("resource.mq.md"),
"## @exec eval\n\n`params(a: Int)`\n\n`return a + 100`\n", "## @exec select\n\n`params(a: Int)`\n\n`return a + 100`\n",
); );
write( write(
&dir.path().join("index.mq.md"), &dir.path().join("index.mq.md"),
"---\nimport:\n math: \"./math.mq.md\"\n---\n\n## @exec main\n\n`return math.eval(a=1)`\n", "---\nimport:\n resource: \"./resource.mq.md\"\n---\n\n## @exec main\n\n`return resource.select(a=1)`\n",
); );
let check = cli(&["check", "index.mq.md"], dir.path()); let check = cli(&["check", "index.mq.md"], dir.path());
assert_eq!(check.status.code(), Some(1), "{}", stderr(&check)); assert_eq!(check.status.code(), Some(1), "{}", stderr(&check));
+166
View File
@@ -0,0 +1,166 @@
//! Black-box regression tests for RFC-EXT-0003 H-06 sibling heading modes.
//!
//! A heading that does not declare `@exec`/`@knowledge` inherits its nearest
//! *ancestor*, never the previous sibling. These tests drive the real `marqdo`
//! binary and assert that `check --emit`, `run` and `call` agree.
#![cfg(unix)]
use std::path::{Path, PathBuf};
use std::process::{Command, Output};
use std::sync::atomic::{AtomicU32, Ordering};
static COUNTER: AtomicU32 = AtomicU32::new(0);
struct TempDir(PathBuf);
impl TempDir {
fn new(tag: &str) -> Self {
let id = COUNTER.fetch_add(1, Ordering::Relaxed);
let path = std::env::temp_dir().join(format!(
"marqdo-heading-test-{}-{id}-{tag}",
std::process::id()
));
std::fs::create_dir_all(&path).unwrap();
Self(path)
}
fn path(&self) -> &Path {
&self.0
}
fn write(&self, name: &str, text: &str) {
std::fs::write(self.0.join(name), text).unwrap();
}
}
impl Drop for TempDir {
fn drop(&mut self) {
let _ = std::fs::remove_dir_all(&self.0);
}
}
fn cli(args: &[&str], dir: &Path) -> Output {
Command::new(env!("CARGO_BIN_EXE_marqdo"))
.args(args)
.current_dir(dir)
.output()
.unwrap()
}
fn stderr(output: &Output) -> String {
String::from_utf8_lossy(&output.stderr).to_string()
}
fn stdout(output: &Output) -> String {
String::from_utf8_lossy(&output.stdout).to_string()
}
fn units(document: &serde_json::Value) -> Vec<&serde_json::Value> {
document["modules"][0]["units"]
.as_array()
.expect("units array")
.iter()
.collect()
}
fn unit<'a>(document: &'a serde_json::Value, name: &str) -> &'a serde_json::Value {
units(document)
.into_iter()
.find(|unit| unit["name"] == name)
.unwrap_or_else(|| panic!("missing unit {name}"))
}
fn exec_document() -> &'static str {
"# @knowledge 数学\n\n## @exec main\n\n`return 1`\n\n## 普通说明\n\n这段是知识叙述。\n"
}
fn knowledge_document() -> &'static str {
"# @exec 项目\n\n## @knowledge 解释\n\n背景。\n\n## main\n\n`return 2`\n"
}
#[test]
fn check_emit_marks_unmarked_sibling_knowledge() {
let dir = TempDir::new("emit-knowledge");
dir.write("index.mq.md", exec_document());
let analysis = dir.path().join("analysis.json");
let check = cli(
&["check", "index.mq.md", "--emit", analysis.to_str().unwrap()],
dir.path(),
);
assert_eq!(check.status.code(), Some(0), "{}", stderr(&check));
let document: serde_json::Value =
serde_json::from_slice(&std::fs::read(&analysis).unwrap()).unwrap();
assert_eq!(unit(&document, "数学")["kind"], "namespace");
assert_eq!(unit(&document, "main")["kind"], "function");
assert_eq!(unit(&document, "普通说明")["kind"], "knowledge");
assert!(unit(&document, "普通说明")["function"].is_null());
// The analysis exposes exactly one function and it is the Exec sibling.
let functions = document["modules"][0]["functions"].as_array().unwrap();
assert_eq!(functions.len(), 1);
assert_eq!(functions[0]["local_name"], "main");
assert_eq!(functions[0]["namespace"], "数学");
assert_eq!(functions[0]["unit_id"], unit(&document, "main")["id"]);
}
#[test]
fn check_emit_marks_unmarked_sibling_exec() {
let dir = TempDir::new("emit-exec");
dir.write("index.mq.md", knowledge_document());
let analysis = dir.path().join("analysis.json");
let check = cli(
&["check", "index.mq.md", "--emit", analysis.to_str().unwrap()],
dir.path(),
);
assert_eq!(check.status.code(), Some(0), "{}", stderr(&check));
let document: serde_json::Value =
serde_json::from_slice(&std::fs::read(analysis).unwrap()).unwrap();
assert_eq!(unit(&document, "解释")["kind"], "knowledge");
assert_eq!(unit(&document, "main")["kind"], "function");
let functions = document["modules"][0]["functions"].as_array().unwrap();
assert_eq!(functions.len(), 1);
assert_eq!(functions[0]["local_name"], "main");
assert_eq!(functions[0]["namespace"], "项目");
assert_eq!(functions[0]["unit_id"], unit(&document, "main")["id"]);
}
#[test]
fn run_and_call_not_callable_knowledge_sibling() {
let dir = TempDir::new("call");
dir.write("index.mq.md", exec_document());
let run = cli(&["run", "index.mq.md"], dir.path());
assert_eq!(run.status.code(), Some(0), "{}", stderr(&run));
// `run` streams program stdout only; the returned value is reported by
// `call`, whose output is asserted below and must agree.
assert!(stdout(&run).is_empty());
let call = cli(&["call", "index.mq.md", "数学.main"], dir.path());
assert_eq!(call.status.code(), Some(0), "{}", stderr(&call));
assert_eq!(stdout(&call), "1\n");
let knowledge_sibling = cli(&["call", "index.mq.md", "数学.普通说明"], dir.path());
assert_eq!(knowledge_sibling.status.code(), Some(1));
assert!(
stderr(&knowledge_sibling).contains("sem.no_entry_function"),
"{}",
stderr(&knowledge_sibling)
);
assert!(stdout(&knowledge_sibling).is_empty());
}
#[test]
fn exec_function_run_and_call_agree() {
let dir = TempDir::new("exec");
dir.write("index.mq.md", knowledge_document());
let run = cli(&["run", "index.mq.md"], dir.path());
assert_eq!(run.status.code(), Some(0), "{}", stderr(&run));
assert!(stdout(&run).is_empty());
let call = cli(&["call", "index.mq.md", "项目.main"], dir.path());
assert_eq!(call.status.code(), Some(0), "{}", stderr(&call));
assert_eq!(stdout(&call), "2\n");
let knowledge = cli(&["call", "index.mq.md", "项目.解释"], dir.path());
assert_eq!(knowledge.status.code(), Some(1));
assert!(stderr(&knowledge).contains("sem.no_entry_function"));
}
+1 -1
View File
@@ -653,7 +653,7 @@ fn multi_module_imports_and_cycles() {
let dir = TempDir::new("modules"); let dir = TempDir::new("modules");
dir.write( dir.write(
"geometry.mq.md", "geometry.mq.md",
"## @exec 圆面积\n\n`params(r: Number)`\n\n`return math.eval(ref(\"#公式\"), {\"r\": r}, target=\"A\")`\n\n### @knowledge 公式\n\n$$\nA = \\pi r^2\n$$\n", "## @exec 圆面积\n\n`params(r: Number)`\n\n`return 3.141592653589793 * r * r`\n\n### @knowledge 公式\n\n$$\nA = \\pi r^2\n$$\n",
); );
dir.write( dir.write(
"index.mq.md", "index.mq.md",
+97
View File
@@ -0,0 +1,97 @@
//! RFC-EXT-0003 H-01 / T-MATH-01..06: the core has no `math.*` domain
//! builtins; algorithms live in pure `.mq.md` packages and optionally in an
//! explicitly selected ABI backend. This test drives the real CLI binary and the
//! checked-in examples.
#![cfg(unix)]
use std::path::{Path, PathBuf};
use std::process::{Command, Output};
use std::sync::atomic::{AtomicU32, Ordering};
static COUNTER: AtomicU32 = AtomicU32::new(0);
struct TempDir(PathBuf);
impl TempDir {
fn new(tag: &str) -> Self {
let id = COUNTER.fetch_add(1, Ordering::Relaxed);
let path = std::env::temp_dir().join(format!(
"marqdo-math-test-{}-{id}-{tag}",
std::process::id()
));
std::fs::create_dir_all(&path).unwrap();
Self(path)
}
fn path(&self) -> &Path {
&self.0
}
fn write(&self, name: &str, text: &str) {
std::fs::write(self.0.join(name), text).unwrap();
}
}
impl Drop for TempDir {
fn drop(&mut self) {
let _ = std::fs::remove_dir_all(&self.0);
}
}
fn repo() -> PathBuf {
Path::new(env!("CARGO_MANIFEST_DIR"))
.parent()
.unwrap()
.parent()
.unwrap()
.to_path_buf()
}
fn cli(args: &[&str], dir: &Path) -> Output {
Command::new(env!("CARGO_BIN_EXE_marqdo"))
.args(args)
.current_dir(dir)
.output()
.unwrap()
}
fn stderr(output: &Output) -> String {
String::from_utf8_lossy(&output.stderr).to_string()
}
fn stdout(output: &Output) -> String {
String::from_utf8_lossy(&output.stdout).to_string()
}
#[test]
fn pure_math_library_checks_calls_and_runs_without_math_builtins() {
let repo = repo();
let check = cli(&["check", "examples/math-library-demo.mq.md"], &repo);
assert_eq!(check.status.code(), Some(0), "{}", stderr(&check));
let call = cli(&["call", "examples/math-library-demo.mq.md", "main"], &repo);
assert_eq!(call.status.code(), Some(0), "{}", stderr(&call));
assert_eq!(stdout(&call), "6\n");
let run = cli(&["call", "examples/math.mq.md", "计算圆面积"], &repo);
assert_eq!(run.status.code(), Some(0), "{}", stderr(&run));
}
#[test]
fn removed_math_builtins_are_static_symbol_errors() {
let dir = TempDir::new("removed");
dir.write(
"index.mq.md",
"# @knowledge 公式\n\n$$\nA = r + 1\n$$\n\n## @exec main\n\n`return math.eval(ref(\"#公式\"), {\"r\": 2}, target=\"A\")`\n",
);
let check = cli(&["check", "index.mq.md"], dir.path());
assert_eq!(check.status.code(), Some(1));
let error = stderr(&check);
assert!(error.contains("symbol.unknown"), "{error}");
// No fallback execution and no removed `math.unsupported` runtime path.
let run = cli(&["run", "index.mq.md"], dir.path());
assert_eq!(run.status.code(), Some(1));
assert!(run.stdout.is_empty());
assert!(stderr(&run).contains("symbol.unknown"), "{}", stderr(&run));
}
+1 -1
View File
@@ -65,7 +65,7 @@ const BASES: &[Base] = &[
半径叙述。 半径叙述。
`return math.eval(ref("#公式"), {"r": r}, target="A")` `return 3.141592653589793 * r * r`
### @knowledge 公式 ### @knowledge 公式
+3 -3
View File
@@ -789,11 +789,11 @@ mod tests {
"main", "main",
&[], &[],
SignatureKind::Explicit, SignatureKind::Explicit,
vec![return_call("math.eval(x=1)")], vec![return_call("resource.request(x=1)")],
)], )],
imports: vec![marqdo_ir::ImportDecl { imports: vec![marqdo_ir::ImportDecl {
alias: "math".into(), alias: "resource".into(),
target: "./math.mq.md".into(), target: "./resource.mq.md".into(),
span: Span::new(0, 1), span: Span::new(0, 1),
}], }],
resources: vec![], resources: vec![],
+1 -1
View File
@@ -140,7 +140,7 @@ impl<'a> Analyzer<'a> {
} }
Expr::Call { callee, args, .. } => { Expr::Call { callee, args, .. } => {
// A callee identifier names a function; a `ns.name` callee is a // A callee identifier names a function; a `ns.name` callee is a
// builtin namespace (math.eval) or an imported module alias. // builtin namespace (resource.request) or an imported module alias.
// Neither is a variable read. // Neither is a variable read.
match callee.as_ref() { match callee.as_ref() {
Expr::Ident(_) => {} Expr::Ident(_) => {}
+94 -7
View File
@@ -221,6 +221,16 @@ pub fn build_units(doc: &MarkdownDocument, module: &ModuleId) -> UnitIndex {
continue; continue;
} }
} }
// Resolve the ancestor scope before deriving the mode: remove every
// same-or-higher-level heading first so a heading can only inherit from
// its nearest *ancestor*, never from the previous sibling.
while let Some((parent_level, _, _)) = stack.last() {
if *parent_level >= level {
stack.pop();
} else {
break;
}
}
let inherited = stack let inherited = stack
.last() .last()
.map(|(_, _, mode)| *mode) .map(|(_, _, mode)| *mode)
@@ -242,13 +252,6 @@ pub fn build_units(doc: &MarkdownDocument, module: &ModuleId) -> UnitIndex {
continue; continue;
}; };
while let Some((parent_level, _, _)) = stack.last() {
if *parent_level >= level {
stack.pop();
} else {
break;
}
}
let parent_path = stack let parent_path = stack
.last() .last()
.map(|(_, path, _)| path.clone()) .map(|(_, path, _)| path.clone())
@@ -551,4 +554,88 @@ mod tests {
assert!(index.diagnostics.is_empty()); assert!(index.diagnostics.is_empty());
assert_eq!(index.functions.len(), 1); assert_eq!(index.functions.len(), 1);
} }
#[test]
fn unmarked_sibling_inherits_ancestor_not_previous_exec_sibling() {
// Regression for RFC-EXT-0003 H-06: the previous sibling is Exec but the
// nearest ancestor is Knowledge, so 普通说明 must stay Knowledge.
let index =
index_of("# @knowledge 数学\n\n## @exec 运行\n\n`return 1`\n\n## 普通说明\n\n叙述。\n");
assert_eq!(index.functions.len(), 1);
assert_eq!(index.functions[0].id.name, "数学.运行");
let sibling = index
.headings
.iter()
.find(|heading| heading.name == "普通说明")
.expect("sibling heading");
assert_eq!(sibling.kind, UnitKind::Knowledge);
assert_eq!(sibling.mode, SemanticMode::Knowledge);
}
#[test]
fn unmarked_sibling_inherits_exec_ancestor_not_previous_knowledge_sibling() {
let index =
index_of("# @exec 项目\n\n## @knowledge 解释\n\n叙述。\n\n## 计算\n\n`return 1`\n");
assert_eq!(index.diagnostics.len(), 0, "{:?}", index.diagnostics);
assert_eq!(index.functions.len(), 1);
assert_eq!(index.functions[0].id.name, "项目.计算");
let sibling = index
.headings
.iter()
.find(|heading| heading.name == "计算")
.expect("sibling heading");
assert_eq!(sibling.mode, SemanticMode::Exec);
assert_eq!(sibling.kind, UnitKind::Function);
}
#[test]
fn deep_sections_follow_their_own_ancestors() {
// H3 under an Exec H2 is an Exec section; H3 under a Knowledge H2 is not
// polluted by the earlier Exec chain.
let index = index_of(
"# @knowledge 数学\n\n## @exec 计算\n\n### 细节\n\n`return 1`\n\n## 说明\n\n### 例子\n\n叙述。\n",
);
let depth = |name: &str| {
index
.headings
.iter()
.find(|heading| heading.name == name)
.unwrap_or_else(|| panic!("missing heading {name}"))
.mode
};
assert_eq!(depth("细节"), SemanticMode::Exec);
assert_eq!(depth("说明"), SemanticMode::Knowledge);
assert_eq!(index.functions.len(), 1);
}
#[test]
fn invalid_marker_does_not_corrupt_later_siblings() {
let index = index_of("# @knowledge 数学\n\n## @Exec 坏标记\n\n## 正常\n\n`return 1`\n");
assert!(index
.diagnostics
.iter()
.any(|d| d.code == "sem.invalid_mode_marker"));
let normal = index
.headings
.iter()
.find(|heading| heading.name == "正常")
.expect("valid sibling heading");
assert_eq!(normal.mode, SemanticMode::Knowledge);
assert_eq!(normal.kind, UnitKind::Knowledge);
}
#[test]
fn knowledge_scope_payloads_and_sections_stay_inert() {
let index = index_of(
"# @knowledge 数学\n\n$$\nA = \\pi r^2\n$$\n\n`数学表达式`\n\n## @knowledge 公式\n\n**不是函数**\n",
);
assert!(index.functions.is_empty(), "{:?}", index.functions);
for heading in &index.headings {
assert_eq!(heading.mode, SemanticMode::Knowledge);
}
assert!(index
.units
.iter()
.all(|unit| !matches!(unit.kind, UnitKind::Function)));
}
} }
-1
View File
@@ -19,7 +19,6 @@ regex = { workspace = true }
glob = { workspace = true } glob = { workspace = true }
marqdo-span = { workspace = true } marqdo-span = { workspace = true }
marqdo-value = { workspace = true } marqdo-value = { workspace = true }
marqdo-math = { workspace = true }
marqdo-foreign = { workspace = true } marqdo-foreign = { workspace = true }
marqdo-sandbox = { workspace = true } marqdo-sandbox = { workspace = true }
serde = { workspace = true } serde = { workspace = true }
+3 -16
View File
@@ -29,7 +29,9 @@ use crate::observe::{
use crate::plugin_worker::WorkerPlugin; use crate::plugin_worker::WorkerPlugin;
use crate::provider_c::{load_package, CResourceProvider}; use crate::provider_c::{load_package, CResourceProvider};
use crate::provider_worker::WorkerResourceProvider; use crate::provider_worker::WorkerResourceProvider;
use crate::resource::{ResourceProvider, ResourceRead, ResourceTable, SharedResourceProvider}; use crate::resource::{
is_core_resource_kind, ResourceProvider, ResourceRead, ResourceTable, SharedResourceProvider,
};
use crate::trace::{EffectTrace, SemanticEvent, TraceBudget, TraceEntry, TraceState}; use crate::trace::{EffectTrace, SemanticEvent, TraceBudget, TraceEntry, TraceState};
use marqdo_sandbox::{PlatformCapabilities, SandboxMode}; use marqdo_sandbox::{PlatformCapabilities, SandboxMode};
@@ -41,16 +43,6 @@ mod resource_ops;
/// Host operations reachable from the language surface. /// Host operations reachable from the language surface.
#[derive(Debug, Clone, Copy, PartialEq, Eq)] #[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum HostOp { pub enum HostOp {
/// Parse a formula.
MathParse,
/// Evaluate a formula.
MathEval,
/// Substitute variables in a formula.
MathSubstitute,
/// Simplify a formula.
MathSimplify,
/// Differentiate a formula.
MathDifferentiate,
/// One-shot foreign execution. /// One-shot foreign execution.
ForeignRun, ForeignRun,
/// Typed foreign call. /// Typed foreign call.
@@ -67,11 +59,6 @@ impl HostOp {
/// Stable operation name used in traces and diagnostics. /// Stable operation name used in traces and diagnostics.
pub const fn name(self) -> &'static str { pub const fn name(self) -> &'static str {
match self { match self {
HostOp::MathParse => "math.parse",
HostOp::MathEval => "math.eval",
HostOp::MathSubstitute => "math.substitute",
HostOp::MathSimplify => "math.simplify",
HostOp::MathDifferentiate => "math.differentiate",
HostOp::ForeignRun => "foreign.run", HostOp::ForeignRun => "foreign.run",
HostOp::ForeignCall => "foreign.call", HostOp::ForeignCall => "foreign.call",
HostOp::FsRead => "fs.read", HostOp::FsRead => "fs.read",
-5
View File
@@ -72,11 +72,6 @@ pub(crate) fn dispatch(
match op { match op {
HostOp::FsRead => host.op_fs_read(args, ctx), HostOp::FsRead => host.op_fs_read(args, ctx),
HostOp::FsWrite => host.op_fs_write(args, ctx), HostOp::FsWrite => host.op_fs_write(args, ctx),
HostOp::MathParse
| HostOp::MathEval
| HostOp::MathSubstitute
| HostOp::MathSimplify
| HostOp::MathDifferentiate => crate::kernels::math(host, op, args, ctx),
HostOp::ForeignRun | HostOp::ForeignCall => crate::kernels::foreign(host, op, args, ctx), HostOp::ForeignRun | HostOp::ForeignCall => crate::kernels::foreign(host, op, args, ctx),
HostOp::PluginInvoke => host.op_plugin_invoke(args, ctx), HostOp::PluginInvoke => host.op_plugin_invoke(args, ctx),
} }
+18 -4
View File
@@ -84,11 +84,18 @@ impl StdHost {
)); ));
} }
let name = provider.name().to_string(); let name = provider.name().to_string();
if name.is_empty() || name == "stdio" || name == "file" { if name.is_empty() {
return Err(RuntimeError::new( return Err(RuntimeError::new(
ErrorCategory::ResourceUnsupported, ErrorCategory::ResourceUnsupported,
None, None,
format!("resource provider name `{name}` is reserved or empty"), "resource provider name is empty".to_string(),
));
}
if is_core_resource_kind(&name) {
return Err(RuntimeError::new(
ErrorCategory::ResourceUnsupported,
None,
format!("resource provider name `{name}` is a reserved core resource kind"),
)); ));
} }
let kinds = provider.kind_strings(); let kinds = provider.kind_strings();
@@ -100,11 +107,18 @@ impl StdHost {
)); ));
} }
for kind in &kinds { for kind in &kinds {
if kind.is_empty() || kind == "stdio" || kind == "file" { if kind.is_empty() {
return Err(RuntimeError::new( return Err(RuntimeError::new(
ErrorCategory::ResourceUnsupported, ErrorCategory::ResourceUnsupported,
None, None,
format!("resource provider `{name}` declares reserved kind `{kind}`"), format!("resource provider `{name}` declares an empty kind"),
));
}
if is_core_resource_kind(kind) {
return Err(RuntimeError::new(
ErrorCategory::ResourceUnsupported,
None,
format!("resource provider `{name}` declares reserved core kind `{kind}`"),
)); ));
} }
if let Some((existing, _)) = self.resource_providers.get(kind) { if let Some((existing, _)) = self.resource_providers.get(kind) {
+8 -141
View File
@@ -1,147 +1,18 @@
//! Math and foreign kernel adapters. //! Foreign-kernel adapters.
//! //!
//! These functions are the only bridge between the capability host and the //! This module is the bridge between the capability host and the native foreign
//! native math / foreign crates. Every operation is capability-checked before //! kernel crate. Every operation is capability-checked before the kernel is
//! the kernel is touched; kernel failures are converted to structured runtime //! touched; kernel failures are converted to structured runtime errors, never
//! errors, never panics. //! panics. Domain math is not a host kernel (ADR-0061): it belongs to a pure
//! `.mq.md` package or an explicitly selected ABI backend.
use std::collections::BTreeMap; use std::collections::BTreeMap;
use std::time::Duration; use std::time::Duration;
use marqdo_value::{to_wire, ErrorCategory, FormulaValue, RuntimeError, Value}; use marqdo_value::{to_wire, ErrorCategory, RuntimeError, Value};
use crate::context::ExecutionContext; use crate::context::ExecutionContext;
use crate::host::{arity, expect_text, HostOp, StdHost}; use crate::host::{HostOp, StdHost};
pub(crate) fn math(
host: &mut StdHost,
op: HostOp,
args: Vec<Value>,
ctx: &ExecutionContext,
) -> Result<Value, RuntimeError> {
if !host.capabilities.math {
return Err(denied(ctx, "the math capability was not granted"));
}
let span = ctx.span;
match op {
HostOp::MathParse => {
let source = expect_text(&args, 0, "math.parse source", span)?;
let formula = marqdo_math::parse(&source).map_err(|error| math_error(error, span))?;
Ok(Value::Formula(FormulaValue {
latex: formula.source,
unit: None,
display: false,
span,
}))
}
HostOp::MathEval => {
if args.len() < 2 {
return Err(arity(span, "math.eval", 2, args.len()));
}
let formula = formula_source(&args[0], span)?;
let bindings = math_bindings(&args[1], span)?;
let target = match args.get(2) {
Some(Value::Text(target)) => Some(target.clone()),
Some(Value::None) | None => None,
Some(other) => {
return Err(RuntimeError::type_error(
span,
format!("math.eval target must be Text, got {}", other.type_name()),
))
}
};
let parsed = marqdo_math::parse(&formula).map_err(|error| math_error(error, span))?;
marqdo_math::evaluate(&parsed, &bindings, target.as_deref())
.map_err(|error| math_error(error, span))
}
HostOp::MathSubstitute => {
if args.len() < 2 {
return Err(arity(span, "math.substitute", 2, args.len()));
}
let source = formula_source(&args[0], span)?;
let bindings = math_bindings(&args[1], span)?;
let parsed = marqdo_math::parse(&source).map_err(|error| math_error(error, span))?;
let substituted = marqdo_math::substitute(&parsed, &bindings)
.map_err(|error| math_error(error, span))?;
Ok(Value::Formula(FormulaValue {
latex: substituted.source,
unit: None,
display: false,
span,
}))
}
HostOp::MathSimplify | HostOp::MathDifferentiate => Err(RuntimeError::new(
ErrorCategory::MathUnsupported,
span,
format!(
"`{}` is not part of the supported math subset in this build",
op.name()
),
)),
_ => Err(RuntimeError::new(
ErrorCategory::Internal,
span,
"unexpected math operation",
)),
}
}
fn formula_source(value: &Value, span: Option<marqdo_span::Span>) -> Result<String, RuntimeError> {
match value {
Value::Formula(formula) => Ok(formula.latex.clone()),
Value::Text(text) => Ok(text.clone()),
other => Err(RuntimeError::type_error(
span,
format!("expected Formula or Text, got {}", other.type_name()),
)),
}
}
fn math_bindings(
value: &Value,
span: Option<marqdo_span::Span>,
) -> Result<BTreeMap<String, Value>, RuntimeError> {
match value {
Value::Map(map) => {
let mut bindings = BTreeMap::new();
for (name, value) in map {
match value {
Value::Int(_) | Value::Float(_) => {
bindings.insert(name.clone(), value.clone());
}
other => {
return Err(RuntimeError::type_error(
span,
format!(
"math binding `{name}` must be Int or Float, got {}",
other.type_name()
),
))
}
}
}
Ok(bindings)
}
other => Err(RuntimeError::type_error(
span,
format!("math bindings must be a Map, got {}", other.type_name()),
)),
}
}
fn math_error(error: marqdo_math::MathError, span: Option<marqdo_span::Span>) -> RuntimeError {
use marqdo_math::MathErrorKind;
let category = match error.kind {
MathErrorKind::Parse | MathErrorKind::Unsupported => ErrorCategory::MathUnsupported,
MathErrorKind::UndefinedVariable => ErrorCategory::UnknownSymbol,
MathErrorKind::Type => ErrorCategory::Type,
};
let mut message = error.message;
if let Some(position) = error.position {
message = format!("{message} (at byte {position} of the formula)");
}
RuntimeError::new(category, span, message)
}
pub(crate) fn foreign( pub(crate) fn foreign(
host: &mut StdHost, host: &mut StdHost,
@@ -296,9 +167,5 @@ fn foreign_error(
RuntimeError::new(category, span, message) RuntimeError::new(category, span, message)
} }
fn denied(ctx: &ExecutionContext, message: impl Into<String>) -> RuntimeError {
RuntimeError::new(ErrorCategory::PermissionDenied, ctx.span, message)
}
/// Default per-call foreign timeout used by the CLI. /// Default per-call foreign timeout used by the CLI.
pub const DEFAULT_FOREIGN_TIMEOUT: Duration = Duration::from_secs(10); pub const DEFAULT_FOREIGN_TIMEOUT: Duration = Duration::from_secs(10);
+4 -1
View File
@@ -35,5 +35,8 @@ pub use observe::{
ValueState, DEFAULT_MAX_OBSERVATION_BYTES, DEFAULT_MAX_OBSERVATION_EVENTS, ValueState, DEFAULT_MAX_OBSERVATION_BYTES, DEFAULT_MAX_OBSERVATION_EVENTS,
DEFAULT_MAX_VALUE_BYTES, MAX_STREAM_CHUNK_BYTES, DEFAULT_MAX_VALUE_BYTES, MAX_STREAM_CHUNK_BYTES,
}; };
pub use resource::{ResourceProvider, ResourceRead, ResourceTable, SharedResourceProvider}; pub use resource::{
is_core_resource_kind, ResourceProvider, ResourceRead, ResourceTable, SharedResourceProvider,
CORE_RESOURCE_KINDS,
};
pub use trace::{EffectTrace, SemanticEvent, TraceBudget, TraceEntry, TraceState, TraceTruncation}; pub use trace::{EffectTrace, SemanticEvent, TraceBudget, TraceEntry, TraceState, TraceTruncation};
+14
View File
@@ -18,6 +18,20 @@ use marqdo_value::{ErrorCategory, ResourceHandle, RuntimeError};
static NEXT_RUN_ID: AtomicU64 = AtomicU64::new(1); static NEXT_RUN_ID: AtomicU64 = AtomicU64::new(1);
/// Core resource kinds owned by the host itself.
///
/// A third-party [`ResourceProvider`] may neither use one of these names as its
/// provider name nor declare one of them as a served kind: the host dispatches
/// these kinds before consulting the provider table. This is the single source of
/// truth used by both host registration and the CLI provider-manifest validator
/// ([`spec/resource-provider-v2.md`], ADR-0033/0062).
pub const CORE_RESOURCE_KINDS: &[&str] = &["stdio", "file", "tcp", "tls", "udp", "tcp-listener"];
/// Whether `name` is a host-owned core resource kind.
pub fn is_core_resource_kind(name: &str) -> bool {
CORE_RESOURCE_KINDS.contains(&name)
}
/// A versioned trusted provider of additional resource kinds (ADR-0033). /// A versioned trusted provider of additional resource kinds (ADR-0033).
/// ///
/// In-process providers share the host address space and are **not** a /// In-process providers share the host address space and are **not** a
+32 -5
View File
@@ -279,6 +279,7 @@ struct MockProvider {
written: Vec<u8>, written: Vec<u8>,
version: u32, version: u32,
kinds: Vec<&'static str>, kinds: Vec<&'static str>,
provider_name: &'static str,
} }
impl MockProvider { impl MockProvider {
@@ -289,13 +290,19 @@ impl MockProvider {
written: Vec::new(), written: Vec::new(),
version, version,
kinds, kinds,
provider_name: "mock",
} }
} }
fn with_name(mut self, name: &'static str) -> Self {
self.provider_name = name;
self
}
} }
impl marqdo_host::ResourceProvider for MockProvider { impl marqdo_host::ResourceProvider for MockProvider {
fn name(&self) -> &str { fn name(&self) -> &str {
"mock" self.provider_name
} }
fn protocol_version(&self) -> u32 { fn protocol_version(&self) -> u32 {
self.version self.version
@@ -421,10 +428,30 @@ fn provider_registration_rejects_versions_reserved_names_and_conflicts() {
.register_resource_provider(Box::new(MockProvider::new(b"x", 2, vec!["mock.sensor"]))) .register_resource_provider(Box::new(MockProvider::new(b"x", 2, vec!["mock.sensor"])))
.unwrap_err(); .unwrap_err();
assert_eq!(bad_version.category, ErrorCategory::ResourceUnsupported); assert_eq!(bad_version.category, ErrorCategory::ResourceUnsupported);
let reserved = host for core_kind in marqdo_host::CORE_RESOURCE_KINDS {
.register_resource_provider(Box::new(MockProvider::new(b"x", 1, vec!["stdio"]))) let reserved_kind = host
.unwrap_err(); .register_resource_provider(Box::new(MockProvider::new(b"x", 1, vec![core_kind])))
assert_eq!(reserved.category, ErrorCategory::ResourceUnsupported); .unwrap_err();
assert_eq!(reserved_kind.category, ErrorCategory::ResourceUnsupported);
assert!(
reserved_kind.message.contains("reserved core kind"),
"{core_kind}: {}",
reserved_kind.message
);
let reserved_name = host
.register_resource_provider(Box::new(
MockProvider::new(b"x", 1, vec!["mock.sensor"]).with_name(core_kind),
))
.unwrap_err();
assert_eq!(reserved_name.category, ErrorCategory::ResourceUnsupported);
assert!(
reserved_name
.message
.contains("reserved core resource kind"),
"{core_kind}: {}",
reserved_name.message
);
}
host.register_resource_provider(Box::new(MockProvider::new(b"x", 1, vec!["mock.sensor"]))) host.register_resource_provider(Box::new(MockProvider::new(b"x", 1, vec!["mock.sensor"])))
.unwrap(); .unwrap();
let conflict = host let conflict = host
+9 -52
View File
@@ -28,7 +28,7 @@ const fn opt(name: &'static str) -> BuiltinParam {
/// A builtin function or host operation. /// A builtin function or host operation.
#[derive(Debug, Clone, Copy)] #[derive(Debug, Clone, Copy)]
pub struct Builtin { pub struct Builtin {
/// Canonical call name (may be namespaced, e.g. `math.eval`). /// Canonical call name (may be namespaced, e.g. `foreign.run`).
pub name: &'static str, pub name: &'static str,
/// Alternative names (Chinese/English aliases). /// Alternative names (Chinese/English aliases).
pub aliases: &'static [&'static str], pub aliases: &'static [&'static str],
@@ -104,41 +104,6 @@ const REF: Builtin = Builtin {
named_only: false, named_only: false,
effectful: false, effectful: false,
}; };
const MATH_PARSE: Builtin = Builtin {
name: "math.parse",
aliases: &[],
params: &[req("formula")],
named_only: false,
effectful: false,
};
const MATH_EVAL: Builtin = Builtin {
name: "math.eval",
aliases: &[],
params: &[req("formula"), req("bindings"), opt("target")],
named_only: false,
effectful: false,
};
const MATH_SUBSTITUTE: Builtin = Builtin {
name: "math.substitute",
aliases: &[],
params: &[req("formula"), req("bindings")],
named_only: false,
effectful: false,
};
const MATH_SIMPLIFY: Builtin = Builtin {
name: "math.simplify",
aliases: &[],
params: &[req("formula")],
named_only: false,
effectful: false,
};
const MATH_DIFFERENTIATE: Builtin = Builtin {
name: "math.differentiate",
aliases: &[],
params: &[req("formula"), req("变量")],
named_only: false,
effectful: false,
};
const FOREIGN_RUN: Builtin = Builtin { const FOREIGN_RUN: Builtin = Builtin {
name: "foreign.run", name: "foreign.run",
aliases: &[], aliases: &[],
@@ -331,11 +296,6 @@ pub const BUILTINS: &[Builtin] = &[
FLOAT, FLOAT,
TABLE, TABLE,
REF, REF,
MATH_PARSE,
MATH_EVAL,
MATH_SUBSTITUTE,
MATH_SIMPLIFY,
MATH_DIFFERENTIATE,
FOREIGN_RUN, FOREIGN_RUN,
FOREIGN_CALL, FOREIGN_CALL,
FS_READ, FS_READ,
@@ -427,7 +387,8 @@ mod tests {
fn lookup_aliases() { fn lookup_aliases() {
assert_eq!(find("print").unwrap().name, "打印"); assert_eq!(find("print").unwrap().name, "打印");
assert_eq!(find("打印").unwrap().name, "打印"); assert_eq!(find("打印").unwrap().name, "打印");
assert!(!find("math.eval").unwrap().named_only); assert!(find("table").is_some());
assert!(find("math.eval").is_none());
assert!(find("nope").is_none()); assert!(find("nope").is_none());
} }
@@ -437,15 +398,11 @@ mod tests {
let print = find("打印").unwrap(); let print = find("打印").unwrap();
assert!(validate_args(print, &parse_arguments("(1)").unwrap()).is_ok()); assert!(validate_args(print, &parse_arguments("(1)").unwrap()).is_ok());
assert!(validate_args(print, &parse_arguments("()").unwrap()).is_err()); assert!(validate_args(print, &parse_arguments("()").unwrap()).is_err());
let eval = find("math.eval").unwrap(); let table = find("table").unwrap();
assert!(validate_args( assert!(validate_args(table, &parse_arguments("(表头=[1], 行=[])").unwrap()).is_ok());
eval, // Builtins accept positional arguments followed by named ones.
&parse_arguments("(formula=ref(\"#x\"), bindings={}, target=\"A\")").unwrap() assert!(validate_args(table, &parse_arguments("([1], [])").unwrap()).is_ok());
) assert!(validate_args(table, &parse_arguments("(表头=[1], nope=[])").unwrap()).is_err());
.is_ok()); assert!(validate_args(table, &parse_arguments("(1, 2, 3)").unwrap()).is_err());
// math.eval accepts positional arguments followed by named ones.
assert!(validate_args(eval, &parse_arguments("(ref(\"#x\"), {})").unwrap()).is_ok());
assert!(validate_args(eval, &parse_arguments("(formula=1, nope=2)").unwrap()).is_err());
assert!(validate_args(eval, &parse_arguments("(1, 2, 3, 4)").unwrap()).is_err());
} }
} }
+1 -1
View File
@@ -65,7 +65,7 @@ impl fmt::Display for CallSiteKey {
pub enum BoundTarget { pub enum BoundTarget {
/// A fixed language builtin, by canonical builtin name. /// A fixed language builtin, by canonical builtin name.
Builtin { Builtin {
/// Canonical name (for example `math.eval`), not a user alias. /// Canonical name (for example `foreign.run`), not a user alias.
canonical_name: String, canonical_name: String,
}, },
/// A function defined by a Markdown heading. /// A function defined by a Markdown heading.
-17
View File
@@ -1,17 +0,0 @@
[package]
name = "marqdo-math"
description = "Native Math/Formula kernel: parse, substitute and evaluate a defined subset"
version.workspace = true
edition.workspace = true
rust-version.workspace = true
license.workspace = true
repository.workspace = true
authors.workspace = true
[dependencies]
marqdo-value = { workspace = true }
num-bigint = { workspace = true }
num-rational = { workspace = true }
num-traits = { workspace = true }
serde = { workspace = true }
-394
View File
@@ -1,394 +0,0 @@
//! Formula AST, exact-number representation and deterministic rendering.
//!
//! The AST is public so that `math.inspect` and tests can observe the parsed
//! structure instead of re-parsing the source string. [`Formula::source`] keeps
//! the original LaTeX exactly as supplied to [`crate::parse`]; rendering is only
//! used when an operation (currently [`crate::substitute`]) produces a new
//! formula.
use std::collections::BTreeSet;
use num_bigint::BigInt;
use num_rational::Ratio;
use num_traits::{One, Signed, Zero};
/// Exact rational number used internally by the kernel.
///
/// This is `num-rational`'s generic `Ratio` instantiated over the same
/// `num-bigint` `BigInt` type used by [`marqdo_value::Value::Int`], so values can
/// cross the kernel boundary without a lossy or string round-trip.
pub type Rational = Ratio<BigInt>;
/// Named mathematical constants supported by the subset.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Constant {
/// The circle ratio, written `\pi` or `pi`.
Pi,
/// Euler's number, written `\e` or `e`.
E,
}
impl Constant {
/// The approximate `f64` value of this constant.
pub fn value(self) -> f64 {
match self {
Constant::Pi => std::f64::consts::PI,
Constant::E => std::f64::consts::E,
}
}
}
/// A node of the supported expression grammar.
#[derive(Debug, Clone, PartialEq)]
pub enum Expr {
/// An exact numeric literal. Decimal literals are reduced to exact
/// rationals (for example `0.25` becomes `1/4`).
Number(Rational),
/// A free variable resolved from the binding map at evaluation time.
Variable(String),
/// A named constant (`\pi`, `pi`, `\e`, `e`).
Constant(Constant),
/// Unary negation.
Neg(Box<Expr>),
/// Addition.
Add(Box<Expr>, Box<Expr>),
/// Subtraction.
Sub(Box<Expr>, Box<Expr>),
/// Multiplication.
Mul(Box<Expr>, Box<Expr>),
/// Division. `\frac{a}{b}` is parsed as `Div(a, b)`.
Div(Box<Expr>, Box<Expr>),
/// Exponentiation. The exponent must evaluate to an integer.
Pow(Box<Expr>, Box<Expr>),
/// Square root. `\sqrt{x}` is a dedicated node so that perfect squares can
/// stay exact.
Sqrt(Box<Expr>),
}
impl Expr {
/// Collect every free variable name (constants are not variables).
pub fn variables(&self) -> BTreeSet<String> {
let mut names = BTreeSet::new();
self.collect_variables(&mut names);
names
}
fn collect_variables(&self, names: &mut BTreeSet<String>) {
match self {
Expr::Number(_) | Expr::Constant(_) => {}
Expr::Variable(name) => {
names.insert(name.clone());
}
Expr::Neg(inner) | Expr::Sqrt(inner) => inner.collect_variables(names),
Expr::Add(left, right)
| Expr::Sub(left, right)
| Expr::Mul(left, right)
| Expr::Div(left, right)
| Expr::Pow(left, right) => {
left.collect_variables(names);
right.collect_variables(names);
}
}
}
/// Number of syntactic occurrences of `name`.
pub fn occurrences(&self, name: &str) -> usize {
match self {
Expr::Number(_) | Expr::Constant(_) => 0,
Expr::Variable(variable) => usize::from(variable == name),
Expr::Neg(inner) | Expr::Sqrt(inner) => inner.occurrences(name),
Expr::Add(left, right)
| Expr::Sub(left, right)
| Expr::Mul(left, right)
| Expr::Div(left, right)
| Expr::Pow(left, right) => left.occurrences(name) + right.occurrences(name),
}
}
}
/// Top level shape of a parsed formula: an expression or a single equation.
///
/// A formula with one `=` is an [`FormulaKind::Equation`]; it is never an
/// assignment. More than one `=` is a parse error.
#[derive(Debug, Clone, PartialEq)]
pub enum FormulaKind {
/// A standalone arithmetic expression.
Expression(Expr),
/// `left = right`.
Equation {
/// Left-hand side.
left: Expr,
/// Right-hand side.
right: Expr,
},
}
/// A parsed formula plus the original source text.
#[derive(Debug, Clone, PartialEq)]
pub struct Formula {
/// Original LaTeX source exactly as supplied to [`crate::parse`], or the
/// canonical rendering produced by [`crate::substitute`].
pub source: String,
/// Parsed structure.
pub kind: FormulaKind,
}
impl Formula {
/// Whether this formula is an equation.
pub fn is_equation(&self) -> bool {
matches!(self.kind, FormulaKind::Equation { .. })
}
/// Borrow the expression when this formula is not an equation.
pub fn expression(&self) -> Option<&Expr> {
match &self.kind {
FormulaKind::Expression(expr) => Some(expr),
FormulaKind::Equation { .. } => None,
}
}
/// Borrow both sides when this formula is an equation.
pub fn equation(&self) -> Option<(&Expr, &Expr)> {
match &self.kind {
FormulaKind::Expression(_) => None,
FormulaKind::Equation { left, right } => Some((left, right)),
}
}
/// Every free variable appearing in the formula, in sorted order.
pub fn variables(&self) -> BTreeSet<String> {
match &self.kind {
FormulaKind::Expression(expr) => expr.variables(),
FormulaKind::Equation { left, right } => {
let mut names = left.variables();
names.extend(right.variables());
names
}
}
}
/// Render this formula back to the supported LaTeX subset deterministically.
///
/// The result is always re-parseable by [`crate::parse`]. This is used by
/// [`crate::substitute`] to build the new [`Formula::source`].
pub fn render(&self) -> String {
match &self.kind {
FormulaKind::Expression(expr) => render_expr(expr),
FormulaKind::Equation { left, right } => {
format!("{} = {}", render_expr(left), render_expr(right))
}
}
}
}
// Rendering precedence levels, from loosest to tightest.
const PREC_ADD: u8 = 1;
const PREC_MUL: u8 = 2;
const PREC_UNARY: u8 = 3;
const PREC_POW: u8 = 4;
const PREC_ATOM: u8 = 5;
/// Fractional digits beyond which a terminating rational is rendered as
/// `\frac{..}{..}` instead of a long decimal. Chosen so that substituted
/// `f64` values that are exactly representable in a short decimal stay readable,
/// while binary-exact values with long expansions use a compact fraction.
const MAX_RENDERED_DECIMAL_DIGITS: u32 = 32;
/// Render an expression without surrounding parentheses.
pub fn render_expr(expr: &Expr) -> String {
render(expr, 0)
}
fn render(expr: &Expr, parent_precedence: u8) -> String {
match expr {
Expr::Number(value) => {
let (text, precedence) = render_rational(value);
parenthesize(text, precedence, parent_precedence)
}
Expr::Variable(name) => name.clone(),
Expr::Constant(constant) => match constant {
Constant::Pi => "\\pi".to_string(),
Constant::E => "\\e".to_string(),
},
Expr::Neg(inner) => {
let text = format!("-{}", render(inner, PREC_UNARY));
parenthesize(text, PREC_UNARY, parent_precedence)
}
Expr::Add(left, right) => {
let text = format!(
"{} + {}",
render(left, PREC_ADD),
render(right, PREC_ADD + 1)
);
parenthesize(text, PREC_ADD, parent_precedence)
}
Expr::Sub(left, right) => {
let text = format!(
"{} - {}",
render(left, PREC_ADD),
render(right, PREC_ADD + 1)
);
parenthesize(text, PREC_ADD, parent_precedence)
}
Expr::Mul(left, right) => {
let text = format!(
"{} * {}",
render(left, PREC_MUL),
render(right, PREC_MUL + 1)
);
parenthesize(text, PREC_MUL, parent_precedence)
}
Expr::Div(left, right) => {
let text = format!(
"{} / {}",
render(left, PREC_MUL),
render(right, PREC_MUL + 1)
);
parenthesize(text, PREC_MUL, parent_precedence)
}
Expr::Pow(base, exponent) => {
let text = format!(
"{} ^ {}",
render(base, PREC_POW + 1),
render(exponent, PREC_POW)
);
parenthesize(text, PREC_POW, parent_precedence)
}
Expr::Sqrt(inner) => format!("\\sqrt{{{}}}", render(inner, 0)),
}
}
fn parenthesize(text: String, precedence: u8, parent_precedence: u8) -> String {
if precedence < parent_precedence {
format!("({text})")
} else {
text
}
}
/// Render an exact rational, returning the text and its rendering precedence.
///
/// Integral values render as integers. Values with a terminating decimal
/// expansion of at most [`MAX_RENDERED_DECIMAL_DIGITS`] digits render as
/// decimals; everything else renders as `\frac{numerator}{denominator}`.
fn render_rational(value: &Rational) -> (String, u8) {
if value.is_integer() {
let integer = value.to_integer();
let negative = integer.sign() == num_bigint::Sign::Minus;
let precedence = if negative { PREC_UNARY } else { PREC_ATOM };
return (integer.to_string(), precedence);
}
if let Some(places) = decimal_places(value.denom()) {
if places <= MAX_RENDERED_DECIMAL_DIGITS {
let scale = BigInt::from(10_u32).pow(places);
let scaled = value.numer() * &scale / value.denom();
let negative = scaled.sign() == num_bigint::Sign::Minus;
let digits = scaled.abs().to_string();
let places = places as usize;
let decimal = if digits.len() <= places {
format!("0.{}{digits}", "0".repeat(places - digits.len()))
} else {
let split = digits.len() - places;
format!("{}.{}", &digits[..split], &digits[split..])
};
let precedence = if negative { PREC_UNARY } else { PREC_ATOM };
let text = if negative {
format!("-{decimal}")
} else {
decimal
};
return (text, precedence);
}
}
(
format!("\\frac{{{}}}{{{}}}", value.numer(), value.denom()),
PREC_ATOM,
)
}
/// Number of fractional digits needed for the terminating decimal expansion of
/// `denominator`, or `None` when the expansion does not terminate or is longer
/// than [`MAX_RENDERED_DECIMAL_DIGITS`].
fn decimal_places(denominator: &BigInt) -> Option<u32> {
let mut reduced = denominator.clone();
let two = BigInt::from(2_u32);
let five = BigInt::from(5_u32);
let mut twos = 0_u32;
while reduced.is_positive() && (&reduced % &two).is_zero() {
reduced /= &two;
twos += 1;
if twos > MAX_RENDERED_DECIMAL_DIGITS {
return None;
}
}
let mut fives = 0_u32;
while reduced.is_positive() && (&reduced % &five).is_zero() {
reduced /= &five;
fives += 1;
if fives > MAX_RENDERED_DECIMAL_DIGITS {
return None;
}
}
if reduced.is_one() {
Some(twos.max(fives))
} else {
None
}
}
#[cfg(test)]
mod tests {
use super::*;
fn number(numerator: i64, denominator: i64) -> Expr {
Expr::Number(Ratio::new(
BigInt::from(numerator),
BigInt::from(denominator),
))
}
#[test]
fn rendering_round_trips_through_parse() {
// The renderer must always emit text the parser accepts.
for source in [
"1 + 2 * 3",
"(1 + 2) * 3",
"2 ^ (3 + 1)",
"\\frac{1}{3}",
"-4 ^ 2",
"2 ^ (-3)",
"\\sqrt{2}",
"a = 2 * b + 1",
"(2 ^ 3) ^ 2",
"1 - (2 - 3)",
"a / (b * c)",
] {
let formula = crate::parse(source).expect("fixture parses");
let rendered = formula.render();
let reparsed = crate::parse(&rendered)
.unwrap_or_else(|err| panic!("rendered {rendered:?} does not parse: {err}"));
assert_eq!(reparsed.kind, formula.kind, "source {source:?}");
}
}
#[test]
fn decimal_and_fraction_rendering_is_deterministic() {
assert_eq!(render_expr(&number(5, 2)), "2.5");
assert_eq!(render_expr(&number(-5, 2)), "-2.5");
assert_eq!(render_expr(&number(1, 8)), "0.125");
assert_eq!(render_expr(&number(1, 3)), "\\frac{1}{3}");
assert_eq!(render_expr(&number(0, 1)), "0");
}
#[test]
fn variables_are_collected_without_constants() {
let formula = crate::parse("2 * x + y * \\pi").unwrap();
assert_eq!(
formula.variables().into_iter().collect::<Vec<_>>(),
vec!["x".to_string(), "y".to_string()]
);
assert_eq!(formula.expression().unwrap().occurrences("x"), 1);
}
}
-146
View File
@@ -1,146 +0,0 @@
//! Structured errors returned by the native math kernel.
//!
//! The kernel never panics on untrusted LaTeX. Every failure is reported as a
//! [`MathError`] with a stable [`MathErrorKind`], a human readable message and
//! (for parse failures) the byte offset into the original LaTeX source. The
//! host layer is expected to map [`MathErrorKind::Unsupported`] to the
//! `math.unsupported` diagnostic code and the remaining kinds to the matching
//! expression diagnostics.
use serde::{Deserialize, Serialize};
use std::fmt;
/// Broad category of a math kernel failure.
///
/// The enum is deliberately small: the kernel only distinguishes "the input is
/// not in the supported grammar", "the input is in the grammar but outside the
/// supported subset", "a name is unbound" and "a value has the wrong type".
/// Resource-bound violations (exponent/result size) are reported as
/// [`MathErrorKind::Unsupported`] because they are a documented limitation of
/// the subset rather than a parse or type problem.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum MathErrorKind {
/// The input is malformed LaTeX for the supported subset.
Parse,
/// The input is well-formed but outside the deliberately limited subset, or
/// the requested operation/equation shape is not supported.
Unsupported,
/// A variable used by the formula has no binding.
UndefinedVariable,
/// A binding or operand has an incompatible type, or an operation is
/// undefined for the supplied values (for example division by zero).
Type,
}
impl MathErrorKind {
/// Stable lowercase label used by diagnostics and tests.
pub const fn as_str(self) -> &'static str {
match self {
MathErrorKind::Parse => "parse",
MathErrorKind::Unsupported => "unsupported",
MathErrorKind::UndefinedVariable => "undefined-variable",
MathErrorKind::Type => "type",
}
}
}
impl fmt::Display for MathErrorKind {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(self.as_str())
}
}
/// A structured error produced by [`crate::parse`], [`crate::evaluate`] or
/// [`crate::substitute`].
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct MathError {
/// Failure category.
pub kind: MathErrorKind,
/// Human readable explanation. Messages are diagnostic text; callers should
/// branch on [`MathError::kind`] rather than on the wording.
pub message: String,
/// Byte offset into the original LaTeX source, when the failure is tied to
/// a specific token.
pub position: Option<usize>,
}
impl MathError {
/// Construct an error with an explicit kind and optional byte position.
pub fn new(kind: MathErrorKind, message: impl Into<String>, position: Option<usize>) -> Self {
Self {
kind,
message: message.into(),
position,
}
}
/// Construct a [`MathErrorKind::Parse`] error.
pub fn parse(message: impl Into<String>, position: Option<usize>) -> Self {
Self::new(MathErrorKind::Parse, message, position)
}
/// Construct a [`MathErrorKind::Unsupported`] error.
pub fn unsupported(message: impl Into<String>, position: Option<usize>) -> Self {
Self::new(MathErrorKind::Unsupported, message, position)
}
/// Construct a [`MathErrorKind::UndefinedVariable`] error.
pub fn undefined_variable(message: impl Into<String>, position: Option<usize>) -> Self {
Self::new(MathErrorKind::UndefinedVariable, message, position)
}
/// Construct a [`MathErrorKind::Type`] error.
pub fn type_error(message: impl Into<String>, position: Option<usize>) -> Self {
Self::new(MathErrorKind::Type, message, position)
}
/// The documented result-size guard was hit. Reported as `Unsupported` so
/// callers can surface a stable `math.unsupported` diagnostic instead of a
/// crash or an out-of-memory abort.
pub fn size_bound(message: impl Into<String>) -> Self {
Self::unsupported(message, None)
}
}
impl fmt::Display for MathError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", self.kind)?;
if let Some(position) = self.position {
write!(f, " at byte {position}")?;
}
write!(f, ": {}", self.message)
}
}
impl std::error::Error for MathError {}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn display_includes_kind_and_position() {
let err = MathError::parse("expected an expression", Some(3));
assert_eq!(err.to_string(), "parse at byte 3: expected an expression");
assert_eq!(err.kind.as_str(), "parse");
}
#[test]
fn constructors_use_stable_kinds() {
assert_eq!(
MathError::unsupported("x", None).kind,
MathErrorKind::Unsupported
);
assert_eq!(
MathError::undefined_variable("x", None).kind,
MathErrorKind::UndefinedVariable
);
assert_eq!(MathError::type_error("x", None).kind, MathErrorKind::Type);
assert_eq!(MathError::size_bound("x").kind, MathErrorKind::Unsupported);
assert_eq!(
MathErrorKind::UndefinedVariable.to_string(),
"undefined-variable"
);
}
}
-695
View File
@@ -1,695 +0,0 @@
//! Exact evaluation, equation solving and substitution.
//!
//! Numeric semantics are documented on the crate root. In short: literals,
//! integer/float bindings and the operators `+ - * / ^` are evaluated as exact
//! rationals; `\pi`, `\e` and non-perfect square roots introduce an `f64`
//! approximation. The final value is [`Value::Int`] exactly when the exact
//! result is an integer and [`Value::Float`] otherwise.
use std::collections::BTreeMap;
use num_bigint::{BigInt, Sign};
use num_rational::Ratio;
use num_traits::{One, Signed, ToPrimitive, Zero};
use marqdo_value::Value;
use crate::ast::{Expr, Formula, FormulaKind, Rational};
use crate::error::MathError;
/// Maximum magnitude of an integer exponent accepted by `^`.
pub const MAX_EXPONENT: u64 = 10_000;
/// Maximum number of bits (binary digits) allowed for the numerator and for the
/// denominator of an exact intermediate or result. This bounds memory and CPU
/// for hostile formulas such as `(2^10000)^10000`.
pub const MAX_RESULT_BITS: u64 = 1_000_000;
/// A number during evaluation: either exact or an explicit `f64`
/// approximation produced by an irrational operation.
#[derive(Debug, Clone)]
enum Numeric {
Exact(Rational),
Approx(f64),
}
impl Numeric {
fn exact_zero() -> Self {
Numeric::Exact(Ratio::from_integer(BigInt::zero()))
}
fn exact_one() -> Self {
Numeric::Exact(Ratio::from_integer(BigInt::one()))
}
fn is_zero(&self) -> bool {
match self {
Numeric::Exact(value) => value.is_zero(),
Numeric::Approx(value) => *value == 0.0,
}
}
fn neg(self) -> Result<Self, MathError> {
match self {
Numeric::Exact(value) => Ok(Numeric::Exact(-value)),
Numeric::Approx(value) => Ok(Numeric::Approx(-value)),
}
}
fn to_approx(&self) -> Result<f64, MathError> {
match self {
Numeric::Approx(value) => Ok(*value),
Numeric::Exact(value) => ratio_to_f64(value).ok_or_else(|| {
MathError::size_bound(
"an exact intermediate result is too large to represent as a Float",
)
}),
}
}
fn add(self, other: Numeric) -> Result<Self, MathError> {
match (self, other) {
(Numeric::Exact(left), Numeric::Exact(right)) => {
Ok(Numeric::Exact(checked_ratio(left + right)?))
}
(left, right) => Ok(Numeric::Approx(left.to_approx()? + right.to_approx()?)),
}
}
fn sub(self, other: Numeric) -> Result<Self, MathError> {
match (self, other) {
(Numeric::Exact(left), Numeric::Exact(right)) => {
Ok(Numeric::Exact(checked_ratio(left - right)?))
}
(left, right) => Ok(Numeric::Approx(left.to_approx()? - right.to_approx()?)),
}
}
fn mul(self, other: Numeric) -> Result<Self, MathError> {
match (self, other) {
(Numeric::Exact(left), Numeric::Exact(right)) => {
Ok(Numeric::Exact(exact_mul(&left, &right)?))
}
(left, right) => Ok(Numeric::Approx(left.to_approx()? * right.to_approx()?)),
}
}
fn div(self, other: Numeric) -> Result<Self, MathError> {
if other.is_zero() {
return Err(division_by_zero());
}
match (self, other) {
(Numeric::Exact(left), Numeric::Exact(right)) => {
Ok(Numeric::Exact(checked_ratio(left / right)?))
}
(left, right) => Ok(Numeric::Approx(left.to_approx()? / right.to_approx()?)),
}
}
fn sqrt(self) -> Result<Self, MathError> {
match self {
Numeric::Exact(value) => {
if value.is_negative() {
return Err(MathError::type_error(
"square root of a negative number is not supported by the real-valued subset",
None,
));
}
let numerator_root = integer_sqrt(value.numer());
let denominator_root = integer_sqrt(value.denom());
if &(&numerator_root * &numerator_root) == value.numer()
&& &(&denominator_root * &denominator_root) == value.denom()
{
Ok(Numeric::Exact(Ratio::new(numerator_root, denominator_root)))
} else {
let approximate = ratio_to_f64(&value).ok_or_else(|| {
MathError::size_bound(
"square root operands are outside the representable Float range",
)
})?;
Ok(Numeric::Approx(approximate.sqrt()))
}
}
Numeric::Approx(value) => {
if value < 0.0 {
return Err(MathError::type_error(
"square root of a negative number is not supported by the real-valued subset",
None,
));
}
Ok(Numeric::Approx(value.sqrt()))
}
}
}
fn pow(self, exponent: BigInt) -> Result<Self, MathError> {
let negative_exponent = exponent.sign() == Sign::Minus;
let magnitude = exponent.magnitude();
let bound = num_bigint::BigUint::from(MAX_EXPONENT);
if *magnitude > bound {
return Err(MathError::size_bound(format!(
"exponent magnitude exceeds the supported bound of {MAX_EXPONENT}"
)));
}
let exponent_u32 = magnitude
.to_u32()
.ok_or_else(|| MathError::size_bound("exponent is outside the supported bound"))?;
match self {
Numeric::Exact(base) => {
if exponent_u32 == 0 {
if base.is_zero() {
return Err(MathError::type_error(
"0 ^ 0 is undefined in the native math subset",
None,
));
}
return Ok(Numeric::Exact(Ratio::from_integer(BigInt::one())));
}
if base.is_zero() && negative_exponent {
return Err(division_by_zero());
}
let max_bits = base.numer().bits().max(base.denom().bits());
let estimated_bits = max_bits.saturating_mul(u64::from(exponent_u32));
if estimated_bits > MAX_RESULT_BITS {
return Err(MathError::size_bound(format!(
"exponentiation result would exceed the supported size bound of {MAX_RESULT_BITS} bits"
)));
}
let numerator = base.numer().pow(exponent_u32);
let denominator = base.denom().pow(exponent_u32);
let result = if negative_exponent {
Ratio::new(denominator, numerator)
} else {
Ratio::new(numerator, denominator)
};
Ok(Numeric::Exact(checked_ratio(result)?))
}
Numeric::Approx(base) => {
if base == 0.0 && negative_exponent {
return Err(division_by_zero());
}
let exponent = exponent_u32 as i32;
Ok(Numeric::Approx(base.powi(exponent)))
}
}
}
fn into_value(self) -> Result<Value, MathError> {
match self {
Numeric::Exact(value) => {
if value.is_integer() {
Ok(Value::Int(value.to_integer()))
} else {
Ok(Value::Float(ratio_to_f64(&value).ok_or_else(|| {
MathError::size_bound("exact result is too large to represent as a Float")
})?))
}
}
Numeric::Approx(value) => Ok(Value::Float(value)),
}
}
}
fn division_by_zero() -> MathError {
MathError::type_error(
"division by zero is not defined in the native math subset",
None,
)
}
fn checked_ratio(value: Rational) -> Result<Rational, MathError> {
if value.numer().bits() > MAX_RESULT_BITS || value.denom().bits() > MAX_RESULT_BITS {
return Err(MathError::size_bound(format!(
"intermediate result exceeds the supported size bound of {MAX_RESULT_BITS} bits"
)));
}
Ok(value)
}
/// Convert an exact rational to `f64` without going through `Ratio`'s
/// `ToPrimitive` impl (which is bound to a different `num-bigint` version in
/// `num-rational` 0.4). Returns `None` when the value is outside the finite
/// `f64` range or would lose everything to underflow.
fn ratio_to_f64(value: &Rational) -> Option<f64> {
if value.is_zero() {
return Some(0.0);
}
let negative = value.numer().sign() == Sign::Minus;
let (numerator_mantissa, numerator_exponent) = scaled_f64_mantissa(&value.numer().abs());
let (denominator_mantissa, denominator_exponent) = scaled_f64_mantissa(value.denom());
let exponent = numerator_exponent - denominator_exponent;
if exponent > 1023 {
return None;
}
if exponent < -1075 {
return Some(if negative { -0.0 } else { 0.0 });
}
let mut result = numerator_mantissa / denominator_mantissa;
result *= 2_f64.powi(exponent as i32);
if !result.is_finite() {
return None;
}
Some(if negative { -result } else { result })
}
/// Decompose a non-negative integer into `(mantissa, exponent)` such that the
/// value is approximately `mantissa * 2^exponent` and `mantissa` fits in `f64`.
fn scaled_f64_mantissa(value: &BigInt) -> (f64, i64) {
debug_assert!(!value.is_negative());
let bits = value.bits();
if bits == 0 {
return (0.0, 0);
}
// Keep the most significant 64 bits; the low bits only affect the last
// ~11 bits of the f64 mantissa, which is below the documented precision.
let shift = bits.saturating_sub(64);
let top = (value >> shift).to_u64().unwrap_or(u64::MAX);
(top as f64, shift as i64)
}
fn exact_mul(left: &Rational, right: &Rational) -> Result<Rational, MathError> {
// Pre-check before allocating so that multiplying two large operands cannot
// allocate an out-of-bound intermediate.
let numerator_bits = left.numer().bits().saturating_add(right.numer().bits());
let denominator_bits = left.denom().bits().saturating_add(right.denom().bits());
if numerator_bits > MAX_RESULT_BITS || denominator_bits > MAX_RESULT_BITS {
return Err(MathError::size_bound(format!(
"multiplication result would exceed the supported size bound of {MAX_RESULT_BITS} bits"
)));
}
checked_ratio(left * right)
}
/// Integer square root of a non-negative integer (Newton iteration).
fn integer_sqrt(value: &BigInt) -> BigInt {
debug_assert!(!value.is_negative());
if value.is_zero() {
return BigInt::zero();
}
let mut estimate = BigInt::one() << value.bits().div_ceil(2) as usize;
loop {
let next = (&estimate + value / &estimate) >> 1;
if next >= estimate {
return estimate;
}
estimate = next;
}
}
/// Convert a finite `f64` into the exact binary rational it represents.
fn float_to_ratio(value: f64) -> Option<Rational> {
if !value.is_finite() {
return None;
}
if value == 0.0 {
return Some(Ratio::from_integer(BigInt::zero()));
}
let bits = value.to_bits();
let negative = (bits >> 63) == 1;
let exponent_bits = ((bits >> 52) & 0x7ff) as i32;
let fraction = bits & ((1_u64 << 52) - 1);
let (mantissa, exponent) = if exponent_bits == 0 {
(fraction, -1074_i32)
} else {
(fraction | (1_u64 << 52), exponent_bits - 1075)
};
let mut numerator = BigInt::from(mantissa);
let mut denominator = BigInt::one();
if exponent >= 0 {
numerator <<= exponent as usize;
} else {
denominator <<= (-exponent) as usize;
}
if negative {
numerator = -numerator;
}
Some(Ratio::new(numerator, denominator))
}
/// Convert a [`Value`] binding into a kernel number.
fn binding_numeric(name: &str, bindings: &BTreeMap<String, Value>) -> Result<Numeric, MathError> {
match bindings.get(name) {
None => Err(MathError::undefined_variable(
format!("variable `{name}` is not bound"),
None,
)),
Some(Value::Int(value)) => Ok(Numeric::Exact(Ratio::from_integer(value.clone()))),
Some(Value::Float(value)) => float_to_ratio(*value).map(Numeric::Exact).ok_or_else(|| {
MathError::type_error(
format!(
"binding `{name}` is a non-finite Float; the math kernel only accepts finite numeric bindings"
),
None,
)
}),
Some(other) => Err(MathError::type_error(
format!(
"binding `{name}` has type {} but the math kernel requires Int or Float",
other.type_name()
),
None,
)),
}
}
fn eval_expr(expr: &Expr, bindings: &BTreeMap<String, Value>) -> Result<Numeric, MathError> {
match expr {
Expr::Number(value) => Ok(Numeric::Exact(value.clone())),
Expr::Variable(name) => binding_numeric(name, bindings),
Expr::Constant(constant) => Ok(Numeric::Approx(constant.value())),
Expr::Neg(inner) => eval_expr(inner, bindings)?.neg(),
Expr::Add(left, right) => eval_expr(left, bindings)?.add(eval_expr(right, bindings)?),
Expr::Sub(left, right) => eval_expr(left, bindings)?.sub(eval_expr(right, bindings)?),
Expr::Mul(left, right) => eval_expr(left, bindings)?.mul(eval_expr(right, bindings)?),
Expr::Div(left, right) => eval_expr(left, bindings)?.div(eval_expr(right, bindings)?),
Expr::Pow(base, exponent) => {
let base = eval_expr(base, bindings)?;
base.pow(integer_exponent(&eval_expr(exponent, bindings)?)?)
}
Expr::Sqrt(inner) => eval_expr(inner, bindings)?.sqrt(),
}
}
/// Require a numeric value to be an integer and return it.
fn integer_exponent(value: &Numeric) -> Result<BigInt, MathError> {
match value {
Numeric::Exact(value) if value.is_integer() => Ok(value.to_integer()),
_ => Err(MathError::type_error(
"exponent must be an integer in the native math subset",
None,
)),
}
}
/// A linear/affine form `coefficient * target + constant`.
struct Affine {
coefficient: Numeric,
constant: Numeric,
}
impl Affine {
fn constant(value: Numeric) -> Self {
Self {
coefficient: Numeric::exact_zero(),
constant: value,
}
}
fn target() -> Self {
Self {
coefficient: Numeric::exact_one(),
constant: Numeric::exact_zero(),
}
}
fn is_target_free(&self) -> bool {
self.coefficient.is_zero()
}
fn neg(self) -> Result<Self, MathError> {
Ok(Self {
coefficient: self.coefficient.neg()?,
constant: self.constant.neg()?,
})
}
fn add(self, other: Self) -> Result<Self, MathError> {
Ok(Self {
coefficient: self.coefficient.add(other.coefficient)?,
constant: self.constant.add(other.constant)?,
})
}
fn sub(self, other: Self) -> Result<Self, MathError> {
Ok(Self {
coefficient: self.coefficient.sub(other.coefficient)?,
constant: self.constant.sub(other.constant)?,
})
}
fn scale(self, factor: Numeric) -> Result<Self, MathError> {
let coefficient = self.coefficient.mul(factor.clone())?;
let constant = self.constant.mul(factor)?;
Ok(Self {
coefficient,
constant,
})
}
}
/// Build the affine form of `expr` with respect to `target`.
///
/// Variables other than `target` are resolved from `bindings`. Operations that
/// are not affine in `target` are rejected as unsupported instead of being
/// approximated or reported as a solution.
fn to_affine(
expr: &Expr,
target: &str,
bindings: &BTreeMap<String, Value>,
) -> Result<Affine, MathError> {
match expr {
Expr::Number(value) => Ok(Affine::constant(Numeric::Exact(value.clone()))),
Expr::Constant(constant) => Ok(Affine::constant(Numeric::Approx(constant.value()))),
Expr::Variable(name) if name == target => Ok(Affine::target()),
Expr::Variable(name) => Ok(Affine::constant(binding_numeric(name, bindings)?)),
Expr::Neg(inner) => to_affine(inner, target, bindings)?.neg(),
Expr::Add(left, right) => {
let left = to_affine(left, target, bindings)?;
let right = to_affine(right, target, bindings)?;
left.add(right)
}
Expr::Sub(left, right) => {
let left = to_affine(left, target, bindings)?;
let right = to_affine(right, target, bindings)?;
left.sub(right)
}
Expr::Mul(left, right) => {
let left = to_affine(left, target, bindings)?;
let right = to_affine(right, target, bindings)?;
match (left.is_target_free(), right.is_target_free()) {
(true, true) => Ok(Affine::constant(
left.constant.mul(right.constant)?,
)),
(true, false) => right.scale(left.constant),
(false, true) => left.scale(right.constant),
(false, false) => Err(MathError::unsupported(
format!(
"cannot solve for `{target}`: the equation is not linear in the target (it appears in both factors of a product)"
),
None,
)),
}
}
Expr::Div(left, right) => {
let left = to_affine(left, target, bindings)?;
let right = to_affine(right, target, bindings)?;
if !right.is_target_free() {
return Err(MathError::unsupported(
format!(
"cannot solve for `{target}`: the target appears in a denominator, which is outside the supported linear forms"
),
None,
));
}
if right.constant.is_zero() {
return Err(division_by_zero());
}
let inverse = Numeric::exact_one().div(right.constant)?;
left.scale(inverse)
}
Expr::Pow(base, exponent) => {
if exponent.occurrences(target) > 0 {
return Err(MathError::unsupported(
format!(
"cannot solve for `{target}`: the target appears in an exponent, which is not an affine form"
),
None,
));
}
let exponent_value = eval_expr(exponent, bindings)?;
let exponent = integer_exponent(&exponent_value)?;
let base = to_affine(base, target, bindings)?;
if base.is_target_free() {
let value = base.constant.pow(exponent)?;
return Ok(Affine::constant(value));
}
if exponent.is_zero() {
return Ok(Affine::constant(Numeric::exact_one()));
}
if exponent.is_one() {
return Ok(base);
}
Err(MathError::unsupported(
format!(
"cannot solve for `{target}`: the target appears in a power with exponent {exponent}, which is not an affine form"
),
None,
))
}
Expr::Sqrt(inner) => {
if inner.occurrences(target) > 0 {
return Err(MathError::unsupported(
format!(
"cannot solve for `{target}`: the target appears under a square root, which is not an affine form"
),
None,
));
}
Ok(Affine::constant(eval_expr(inner, bindings)?.sqrt()?))
}
}
}
/// Evaluate `formula` with `bindings`.
///
/// For an expression the result is the exact value (or a [`Value::Float`] when
/// the exact value is not integral or an irrational operation was involved).
/// For an equation `target` selects the variable to solve for; it must occur
/// exactly once and the equation must be linear in it.
pub fn evaluate(
formula: &Formula,
bindings: &BTreeMap<String, Value>,
target: Option<&str>,
) -> Result<Value, MathError> {
match (&formula.kind, target) {
(FormulaKind::Expression(expr), None) => eval_expr(expr, bindings)?.into_value(),
(FormulaKind::Expression(_), Some(_)) => Err(MathError::unsupported(
"a target variable is only meaningful for an equation; the formula is a plain expression",
None,
)),
(FormulaKind::Equation { .. }, None) => Err(MathError::unsupported(
"evaluating an equation requires a target variable to solve for",
None,
)),
(FormulaKind::Equation { left, right }, Some(target)) => {
solve_equation(left, right, target, bindings)
}
}
}
fn solve_equation(
left: &Expr,
right: &Expr,
target: &str,
bindings: &BTreeMap<String, Value>,
) -> Result<Value, MathError> {
if target.is_empty() {
return Err(MathError::unsupported(
"target variable name must not be empty",
None,
));
}
if target == "pi" || target == "e" {
return Err(MathError::unsupported(
format!("`{target}` is a reserved constant, not a solvable variable"),
None,
));
}
let occurrences = left.occurrences(target) + right.occurrences(target);
match occurrences {
0 => {
return Err(MathError::unsupported(
format!("cannot solve for `{target}`: the variable does not occur in the equation"),
None,
));
}
1 => {}
count => {
return Err(MathError::unsupported(
format!(
"cannot solve for `{target}`: the variable occurs {count} times, but only a single occurrence in an affine equation is supported"
),
None,
));
}
}
let left = to_affine(left, target, bindings)?;
let right = to_affine(right, target, bindings)?;
let coefficient = left.coefficient.sub(right.coefficient)?;
let constant = left.constant.sub(right.constant)?;
if coefficient.is_zero() {
return Err(MathError::unsupported(
format!(
"cannot solve for `{target}`: the equation does not uniquely determine the variable"
),
None,
));
}
constant.neg()?.div(coefficient)?.into_value()
}
/// Replace every bound variable in `formula` with its exact value.
///
/// Unbound variables stay symbolic. The returned formula gets a deterministic,
/// re-parseable [`Formula::source`] rendering; `Float` bindings are inserted as
/// the exact rational value of the `f64` (never as a rounded or lossy decimal).
pub fn substitute(
formula: &Formula,
bindings: &BTreeMap<String, Value>,
) -> Result<Formula, MathError> {
let kind = match &formula.kind {
FormulaKind::Expression(expr) => FormulaKind::Expression(substitute_expr(expr, bindings)?),
FormulaKind::Equation { left, right } => FormulaKind::Equation {
left: substitute_expr(left, bindings)?,
right: substitute_expr(right, bindings)?,
},
};
let substituted = Formula {
source: String::new(),
kind,
};
Ok(Formula {
source: substituted.render(),
kind: substituted.kind,
})
}
fn substitute_expr(expr: &Expr, bindings: &BTreeMap<String, Value>) -> Result<Expr, MathError> {
match expr {
Expr::Number(_) | Expr::Constant(_) => Ok(expr.clone()),
Expr::Variable(name) => match bindings.get(name) {
None => Ok(expr.clone()),
Some(Value::Int(value)) => Ok(Expr::Number(Ratio::from_integer(value.clone()))),
Some(Value::Float(value)) => match float_to_ratio(*value) {
Some(value) => Ok(Expr::Number(value)),
None => Err(MathError::type_error(
format!(
"binding `{name}` is a non-finite Float; the math kernel only accepts finite numeric bindings"
),
None,
)),
},
Some(other) => Err(MathError::type_error(
format!(
"binding `{name}` has type {} but the math kernel requires Int or Float",
other.type_name()
),
None,
)),
},
Expr::Neg(inner) => Ok(Expr::Neg(Box::new(substitute_expr(inner, bindings)?))),
Expr::Add(left, right) => Ok(Expr::Add(
Box::new(substitute_expr(left, bindings)?),
Box::new(substitute_expr(right, bindings)?),
)),
Expr::Sub(left, right) => Ok(Expr::Sub(
Box::new(substitute_expr(left, bindings)?),
Box::new(substitute_expr(right, bindings)?),
)),
Expr::Mul(left, right) => Ok(Expr::Mul(
Box::new(substitute_expr(left, bindings)?),
Box::new(substitute_expr(right, bindings)?),
)),
Expr::Div(left, right) => Ok(Expr::Div(
Box::new(substitute_expr(left, bindings)?),
Box::new(substitute_expr(right, bindings)?),
)),
Expr::Pow(base, exponent) => Ok(Expr::Pow(
Box::new(substitute_expr(base, bindings)?),
Box::new(substitute_expr(exponent, bindings)?),
)),
Expr::Sqrt(inner) => Ok(Expr::Sqrt(Box::new(substitute_expr(inner, bindings)?))),
}
}
-171
View File
@@ -1,171 +0,0 @@
//! Native Formula kernel for a deliberately limited, documented math subset.
//!
//! This crate is the native math kernel of the Marqdo toolchain. A Markdown math
//! node becomes an inert [`marqdo_value::FormulaValue`]; nothing is evaluated
//! implicitly. The host layer calls [`parse`], [`substitute`] and [`evaluate`]
//! explicitly, and evaluation is gated by the `math.*` capabilities.
//!
//! **The kernel never proves anything.** It computes exact or floating values
//! and solves a restricted affine equation. It does not establish a theorem,
//! does not simplify a formula into a proof obligation and must not be presented
//! as a formal verifier. See the blueprint section 5 ("原生 Math") and
//! `spec/evaluation.md`.
//!
//! # Guarantees
//!
//! * No panics on untrusted LaTeX. Malformed input, unsupported constructs,
//! unbounded work and wrong value types all become a structured [`MathError`].
//! * Exact rational arithmetic (`num-rational` `Ratio` over `num-bigint`) is used
//! wherever possible; integers are arbitrary precision.
//! * A formula is never silently simplified, guessed or partially accepted:
//! anything outside the grammar below is an error.
//!
//! # Supported grammar
//!
//! The parser accepts exactly the following LaTeX subset (whitespace is
//! insignificant; byte offsets are reported on parse errors):
//!
//! ```text
//! formula = expr [ "=" expr ] ; single '=' only, never assignment
//! expr = term { ("+" | "-") term } ;
//! term = unary { ("*" | "/" | "·" | "×" | implicit) unary } ;
//! unary = ("+" | "-") unary | power ;
//! power = primary [ "^" unary ] ; right associative
//! primary = number
//! | identifier Unicode letter (plus digits/underscore)
//! | "\pi" | "pi" | "\e" | "e" constants
//! | "(" expr ")" | "\left(" expr "\right)"
//! | "{" expr "}" grouping
//! | "\frac{" expr "}{" expr "}" exact division
//! | "\sqrt{" expr "}" real square root
//! ;
//! number = digits [ "." digits ] | "." digits ; decimal, no exponent form
//! ```
//!
//! Notes on the grammar:
//!
//! * `\cdot` and `\times` are accepted as synonyms for `*`.
//! * Implicit multiplication is accepted between adjacent factors where the
//! meaning is unambiguous: `2x`, `\pi r^2`, `(a)(b)` and `m a`. Concatenated
//! letters form one identifier (`ma` is the variable `ma`; write `m a` or
//! `m * a` for a product). Two adjacent number literals are a parse error.
//! * Unicode identifiers are supported (for example `面积`, `r`, `速度`). Plain
//! multi-letter identifiers are allowed as variables, but the names of common
//! elementary functions (`sin`, `cos`, `log`, `exp`, …) are reserved and
//! rejected as unsupported so that `sin(x)` is not silently read as a product.
//! * A single top-level `=` creates an equation (`F = m a`). It is **not**
//! assignment and never writes a binding. A second `=` is a parse error.
//!
//! # Unsupported constructs
//!
//! Everything outside the grammar is a structured [`MathErrorKind::Unsupported`]
//! or [`MathErrorKind::Parse`] error: matrices, sums/integrals, function calls
//! (`\sin`, `\cos`, …), multi-letter commands, `\left[`/`\right]`, mismatched or
//! missing braces, scientific notation (`1e3`), commas, arrays, subscripts,
//! superscript commands other than the `^` operator, `\frac`/`\sqrt` without
//! braced arguments, and so on. Labels, alignment characters and line breaks are
//! likewise unsupported. Underscores are ordinary identifier characters rather
//! than subscripts: `x_1` is the variable named `x_1`, not `x` subscript `1`.
//!
//! # Constants and ambiguity handling
//!
//! * `\pi` and `pi` denote the circle ratio; `\e` and `e` denote Euler's number.
//! * These spellings are **reserved**: a binding with the key `pi` or `e` never
//! overrides the constant, and they cannot be used as a solve target. Use a
//! different variable name (for example `E`, `x`, `r`).
//! * `2e` is parsed as `2 * e` (number times the constant); `2e3` is rejected as
//! scientific notation rather than silently reinterpreted.
//!
//! # Numeric semantics
//!
//! * Decimal literals are exact rationals: `0.25` is `1/4`, not a binary float.
//! * `Int` bindings become exact integers. `Float` bindings are interpreted as
//! the exact binary rational value of the `f64` (no rounding is introduced);
//! non-finite `Float` bindings are a [`MathErrorKind::Type`] error.
//! * `+ - * / ^` are exact when both operands are exact. Division keeps a
//! rational, so `\frac{1}{3} * 3` evaluates exactly to `1`.
//! * The final value is [`marqdo_value::Value::Int`] exactly when the exact result is an
//! integer, and [`marqdo_value::Value::Float`] otherwise. Consequently `1.5 + 2.5` returns
//! `Int(4)`, while `1 / 2` returns `Float(0.5)`.
//! * `\pi`, `\e` and a `\sqrt` of a non-perfect square introduce an `f64`
//! approximation; any result derived from one of them is a [`marqdo_value::Value::Float`].
//! Precision caveats: approximations follow IEEE-754 binary64, so only about
//! 15–17 significant decimal digits are reliable and repeated operations may
//! accumulate error. The kernel never claims an approximate result is exact.
//! * `\sqrt` of a perfect square of an exact rational stays exact (`\sqrt{4}` is
//! `Int(2)`, `\sqrt{1/4}` is `Float(0.5)`); a negative radicand is a type
//! error because the subset is real-valued.
//! * The exponent of `^` must evaluate to an integer. Its magnitude is bounded by
//! [`MAX_EXPONENT`]. Integer powers with a negative exponent are exact
//! reciprocals. `0 ^ 0` is a type error.
//! * Exact intermediate/result numerators and denominators are bounded by
//! [`MAX_RESULT_BITS`]; exceeding the bound returns a structured
//! `Unsupported` error instead of hanging or exhausting memory.
//! * Parsing is bounded by [`MAX_SOURCE_BYTES`], [`MAX_PARSE_DEPTH`] and
//! [`MAX_AST_NODES`]. The node bound also bounds later recursion depth for
//! long operator chains, so hostile input cannot overflow the stack during
//! evaluation, rendering or substitution.
//! * Division by zero, `0 ^ 0` and other undefined real operations are
//! [`MathErrorKind::Type`] errors (the kernel has no dedicated division error
//! kind, so the host maps the message/kind to `runtime.division_by_zero`).
//!
//! # Equations
//!
//! [`evaluate`] of an equation requires `target`. The target must occur exactly
//! once and the equation must be affine in it. The kernel supports `+`, `-`,
//! multiplication by a target-free side, division where the target is in the
//! numerator, and inversion of those operations in either direction (`2x = 4`,
//! `4 = 2x`, `x / 2 = 3`, `3 = x / 2`). Other variables are substituted from
//! `bindings` first; missing bindings are [`MathErrorKind::UndefinedVariable`].
//!
//! Solving a target that occurs zero times or more than once, that appears in a
//! denominator, under a root, in an exponent or in a non-affine product is a
//! structured [`MathErrorKind::Unsupported`] error. A target passed for a plain
//! expression, or an equation without a target, is likewise `Unsupported`.
//!
//! # Substitution
//!
//! [`substitute`] replaces bound variables with exact numeric literals and keeps
//! unbound variables symbolic. The returned [`Formula::source`] is a
//! deterministic canonical rendering that [`parse`] accepts again. Because the
//! rendering is canonical, it is not byte-identical to the original formatting.
#![forbid(unsafe_code)]
mod ast;
mod error;
mod eval;
mod parse;
pub use ast::{render_expr, Constant, Expr, Formula, FormulaKind, Rational};
pub use error::{MathError, MathErrorKind};
pub use eval::{evaluate, substitute, MAX_EXPONENT, MAX_RESULT_BITS};
pub use parse::{parse, MAX_AST_NODES, MAX_PARSE_DEPTH, MAX_SOURCE_BYTES};
#[cfg(test)]
mod tests {
use super::*;
use marqdo_value::Value;
use std::collections::BTreeMap;
/// End-to-end smoke test for the API shape documented on the crate root.
#[test]
fn public_api_round_trip() {
let formula = parse("A = \\pi r^2").unwrap();
assert!(formula.is_equation());
assert_eq!(formula.source, "A = \\pi r^2");
let mut bindings = BTreeMap::new();
bindings.insert("r".to_string(), Value::int(2));
let area = evaluate(&formula, &bindings, Some("A")).unwrap();
let Value::Float(area) = area else {
panic!("area should be an approximate Float");
};
assert!((area - std::f64::consts::PI * 4.0).abs() < 1e-12);
let substituted = substitute(&formula, &bindings).unwrap();
assert_eq!(substituted.source, "A = \\pi * 2 ^ 2");
assert!(substituted.is_equation());
assert_eq!(substituted.kind, parse("A = \\pi * 2 ^ 2").unwrap().kind);
}
}
-837
View File
@@ -1,837 +0,0 @@
//! Lexer and recursive-descent parser for the documented math subset.
//!
//! The parser is intentionally strict: anything outside the subset becomes a
//! structured [`MathError`] instead of being skipped, guessed or silently
//! simplified. It never panics on untrusted input: recursion depth, source size
//! and numeric literal size are all bounded before the corresponding work
//! happens.
use std::iter::Peekable;
use std::str::CharIndices;
use num_bigint::BigInt;
use num_rational::Ratio;
use crate::ast::{Constant, Expr, Formula, FormulaKind, Rational};
use crate::error::MathError;
/// Maximum accepted source length in bytes. Longer inputs are rejected before
/// tokenization so that a hostile formula cannot consume unbounded memory.
pub const MAX_SOURCE_BYTES: usize = 1_000_000;
/// Maximum parser recursion depth (parentheses, groups, unary chains, fractions
/// and roots all consume one level). Deeper input is a parse error instead of a
/// stack overflow.
pub const MAX_PARSE_DEPTH: usize = 256;
/// Maximum number of AST nodes in one formula. This bounds evaluation,
/// substitution and rendering recursion depth: a long left-associative chain
/// such as `1 + 1 + ...` would otherwise build a very deep tree even though the
/// parser loop itself is iterative. Deeper formulas are rejected with a parse
/// error instead of risking a stack overflow later.
pub const MAX_AST_NODES: usize = 512;
/// Maximum number of digits in one numeric literal.
const MAX_LITERAL_DIGITS: usize = 100_000;
/// Plain identifiers that name elementary functions in ordinary LaTeX. They are
/// reported as unsupported instead of being silently reinterpreted as variables
/// or implicit multiplication.
const FUNCTION_NAMES: &[&str] = &[
"sin", "cos", "tan", "cot", "sec", "csc", "arcsin", "arccos", "arctan", "sinh", "cosh", "tanh",
"log", "ln", "lg", "exp", "abs", "min", "max", "floor", "ceil", "round", "det", "dim", "gcd",
"lcm", "lim", "sup", "inf", "arg", "Re", "Im",
];
#[derive(Debug, Clone, PartialEq)]
enum TokenKind {
Number(Rational),
Ident(String),
Constant(Constant),
Plus,
Minus,
Star,
Slash,
Caret,
LParen,
RParen,
LBrace,
RBrace,
Equals,
Frac,
Sqrt,
Eof,
}
#[derive(Debug, Clone)]
struct Token {
kind: TokenKind,
/// Byte offset of the first byte of the token.
start: usize,
}
impl Token {
fn describe(&self) -> String {
match &self.kind {
TokenKind::Number(_) => "a number".to_string(),
TokenKind::Ident(name) => format!("identifier `{name}`"),
TokenKind::Constant(constant) => match constant {
Constant::Pi => "`\\pi`".to_string(),
Constant::E => "`\\e`".to_string(),
},
TokenKind::Plus => "`+`".to_string(),
TokenKind::Minus => "`-`".to_string(),
TokenKind::Star => "`*`".to_string(),
TokenKind::Slash => "`/`".to_string(),
TokenKind::Caret => "`^`".to_string(),
TokenKind::LParen => "`(`".to_string(),
TokenKind::RParen => "`)`".to_string(),
TokenKind::LBrace => "`{`".to_string(),
TokenKind::RBrace => "`}`".to_string(),
TokenKind::Equals => "`=`".to_string(),
TokenKind::Frac => "`\\frac`".to_string(),
TokenKind::Sqrt => "`\\sqrt`".to_string(),
TokenKind::Eof => "the end of the formula".to_string(),
}
}
}
/// Parse `latex` into a [`Formula`].
///
/// The supported grammar is documented on the crate root. The returned formula
/// keeps the original source in [`Formula::source`] and exposes the parsed
/// [`FormulaKind`] for inspection.
pub fn parse(latex: &str) -> Result<Formula, MathError> {
if latex.len() > MAX_SOURCE_BYTES {
return Err(MathError::parse(
format!(
"formula source is {} bytes; the supported limit is {MAX_SOURCE_BYTES} bytes",
latex.len()
),
Some(0),
));
}
let tokens = lex(latex)?;
Parser {
tokens,
position: 0,
depth: 0,
nodes: 0,
}
.parse_formula(latex)
}
fn lex(source: &str) -> Result<Vec<Token>, MathError> {
Lexer {
source,
chars: source.char_indices().peekable(),
tokens: Vec::new(),
}
.run()
}
struct Lexer<'a> {
source: &'a str,
chars: Peekable<CharIndices<'a>>,
tokens: Vec<Token>,
}
impl<'a> Lexer<'a> {
fn run(mut self) -> Result<Vec<Token>, MathError> {
while let Some(&(start, ch)) = self.chars.peek() {
if ch.is_whitespace() {
self.chars.next();
continue;
}
let kind = match ch {
'+' => {
self.chars.next();
TokenKind::Plus
}
'-' => {
self.chars.next();
TokenKind::Minus
}
'*' => {
self.chars.next();
TokenKind::Star
}
'/' => {
self.chars.next();
TokenKind::Slash
}
'^' => {
self.chars.next();
TokenKind::Caret
}
'(' => {
self.chars.next();
TokenKind::LParen
}
')' => {
self.chars.next();
TokenKind::RParen
}
'{' => {
self.chars.next();
TokenKind::LBrace
}
'}' => {
self.chars.next();
TokenKind::RBrace
}
'=' => {
self.chars.next();
TokenKind::Equals
}
'\\' => self.lex_command()?,
ch if ch.is_ascii_digit() || ch == '.' => self.lex_number()?,
ch if is_ident_start(ch) => self.lex_identifier()?,
other => {
return Err(MathError::unsupported(
format!("unsupported character `{other}` in a formula"),
Some(start),
));
}
};
self.tokens.push(Token { kind, start });
}
self.tokens.push(Token {
kind: TokenKind::Eof,
start: self.source.len(),
});
Ok(self.tokens)
}
fn lex_identifier(&mut self) -> Result<TokenKind, MathError> {
let start = self.current_offset();
let mut text = String::new();
while let Some(&(_, ch)) = self.chars.peek() {
if is_ident_continue(ch) {
text.push(ch);
self.chars.next();
} else {
break;
}
}
match text.as_str() {
"pi" => Ok(TokenKind::Constant(Constant::Pi)),
"e" => Ok(TokenKind::Constant(Constant::E)),
_ if FUNCTION_NAMES.contains(&text.as_str()) => Err(MathError::unsupported(
format!(
"function `{text}` is not supported; the native math subset has no function calls"
),
Some(start),
)),
_ => Ok(TokenKind::Ident(text)),
}
}
/// Byte offset of the next unconsumed character (or the source end).
fn current_offset(&mut self) -> usize {
match self.chars.peek() {
Some(&(offset, _)) => offset,
None => self.source.len(),
}
}
fn lex_number(&mut self) -> Result<TokenKind, MathError> {
let start = self.current_offset();
let mut integer_digits = String::new();
while let Some(&(_, ch)) = self.chars.peek() {
if ch.is_ascii_digit() {
integer_digits.push(ch);
self.chars.next();
} else {
break;
}
}
let mut fraction_digits = String::new();
if matches!(self.chars.peek(), Some(&(_, '.'))) {
self.chars.next();
while let Some(&(_, ch)) = self.chars.peek() {
if ch.is_ascii_digit() {
fraction_digits.push(ch);
self.chars.next();
} else {
break;
}
}
if fraction_digits.is_empty() {
return Err(MathError::parse(
"malformed decimal literal: expected digits after `.`",
Some(start),
));
}
}
if integer_digits.is_empty() && fraction_digits.is_empty() {
return Err(MathError::parse("malformed numeric literal", Some(start)));
}
if integer_digits.len() + fraction_digits.len() > MAX_LITERAL_DIGITS {
return Err(MathError::parse(
format!(
"numeric literal has more than {MAX_LITERAL_DIGITS} digits, which is outside the supported resource bound"
),
Some(start),
));
}
// Reject scientific notation (`1e3`) explicitly: it is outside the
// subset and would otherwise parse as `1 * e3`.
if matches!(self.chars.peek(), Some(&(_, 'e' | 'E')))
&& self.number_is_followed_by_exponent()
{
return Err(MathError::parse(
"scientific notation is not supported; write an explicit product such as `2 * 10 ^ 3`",
Some(start),
));
}
let integer_text = if integer_digits.is_empty() {
"0"
} else {
&integer_digits
};
let numerator = parse_bigint(integer_text, start)?;
if fraction_digits.is_empty() {
return Ok(TokenKind::Number(Ratio::from_integer(numerator)));
}
let mut all_digits = String::with_capacity(integer_digits.len() + fraction_digits.len());
all_digits.push_str(if integer_digits.is_empty() {
"0"
} else {
&integer_digits
});
all_digits.push_str(&fraction_digits);
let numerator = parse_bigint(&all_digits, start)?;
let denominator = BigInt::from(10_u32).pow(fraction_digits.len() as u32);
Ok(TokenKind::Number(Ratio::new(numerator, denominator)))
}
/// Look past the current `e`/`E` to decide whether it introduces an
/// exponent (`1e3`, `1e-3`) rather than the Euler constant (`2e`).
fn number_is_followed_by_exponent(&self) -> bool {
let mut chars = self.chars.clone();
let _ = chars.next(); // the 'e' / 'E'
match chars.next().map(|(_, ch)| ch) {
Some(ch) if ch.is_ascii_digit() => true,
Some('+' | '-') => {
matches!(chars.next().map(|(_, ch)| ch), Some(ch) if ch.is_ascii_digit())
}
_ => false,
}
}
fn lex_command(&mut self) -> Result<TokenKind, MathError> {
let start = self.current_offset();
self.chars.next(); // consume the backslash
let mut name = String::new();
while let Some(&(_, ch)) = self.chars.peek() {
if ch.is_ascii_alphabetic() {
name.push(ch);
self.chars.next();
} else {
break;
}
}
match name.as_str() {
"pi" => Ok(TokenKind::Constant(Constant::Pi)),
"e" => Ok(TokenKind::Constant(Constant::E)),
"cdot" | "times" => Ok(TokenKind::Star),
"frac" => Ok(TokenKind::Frac),
"sqrt" => Ok(TokenKind::Sqrt),
"left" => self.lex_left_right(start, '('),
"right" => self.lex_left_right(start, ')'),
"" => Err(MathError::unsupported(
"unsupported LaTeX control symbol; only alphabetic commands such as `\\pi` are supported",
Some(start),
)),
other => Err(MathError::unsupported(
format!(
"unsupported LaTeX command `\\{other}`; the native math subset only supports `\\frac`, `\\sqrt`, `\\cdot`, `\\times`, `\\left(`, `\\right)`, `\\pi` and `\\e`"
),
Some(start),
)),
}
}
fn lex_left_right(&mut self, start: usize, expected: char) -> Result<TokenKind, MathError> {
while let Some(&(_, ch)) = self.chars.peek() {
if ch.is_whitespace() {
self.chars.next();
} else {
break;
}
}
match self.chars.next() {
Some((_, ch)) if ch == expected => Ok(if expected == '(' {
TokenKind::LParen
} else {
TokenKind::RParen
}),
_ => Err(MathError::unsupported(
format!(
"only the parenthesis forms `\\left(` and `\\right)` are supported, not `\\{}` followed by another delimiter",
if expected == '(' { "left" } else { "right" }
),
Some(start),
)),
}
}
}
fn parse_bigint(digits: &str, position: usize) -> Result<BigInt, MathError> {
digits
.parse::<BigInt>()
.map_err(|_| MathError::parse("numeric literal is too large to represent", Some(position)))
}
fn is_ident_start(ch: char) -> bool {
ch.is_alphabetic() || ch == '_'
}
fn is_ident_continue(ch: char) -> bool {
ch.is_alphanumeric() || ch == '_'
}
struct Parser {
tokens: Vec<Token>,
position: usize,
depth: usize,
nodes: usize,
}
impl Parser {
fn peek(&self) -> &Token {
// The lexer always appends an Eof token, so indexing is in bounds.
&self.tokens[self.position.min(self.tokens.len() - 1)]
}
fn advance(&mut self) -> Token {
let token = self.peek().clone();
if self.position < self.tokens.len() - 1 {
self.position += 1;
}
token
}
/// Record one constructed AST node, enforcing [`MAX_AST_NODES`].
fn node(&mut self, expr: Expr) -> Result<Expr, MathError> {
self.nodes += 1;
if self.nodes > MAX_AST_NODES {
return Err(MathError::parse(
format!(
"formula contains more than the supported limit of {MAX_AST_NODES} syntax nodes"
),
Some(self.peek().start),
));
}
Ok(expr)
}
fn enter_depth(&mut self) -> Result<(), MathError> {
self.depth += 1;
if self.depth > MAX_PARSE_DEPTH {
return Err(MathError::parse(
format!("formula nesting exceeds the supported limit of {MAX_PARSE_DEPTH} levels"),
Some(self.peek().start),
));
}
Ok(())
}
fn parse_formula(mut self, source: &str) -> Result<Formula, MathError> {
if matches!(self.peek().kind, TokenKind::Eof) {
return Err(MathError::parse("empty formula", Some(0)));
}
let left = self.parse_expr()?;
let kind = if matches!(self.peek().kind, TokenKind::Equals) {
let equals = self.advance();
if matches!(self.peek().kind, TokenKind::Eof) {
return Err(MathError::parse(
"expected a right-hand side after `=`",
Some(equals.start + 1),
));
}
let right = self.parse_expr()?;
if matches!(self.peek().kind, TokenKind::Equals) {
return Err(MathError::parse(
"more than one `=` in a formula; at most one equation is supported and `=` is never assignment",
Some(self.peek().start),
));
}
FormulaKind::Equation { left, right }
} else {
FormulaKind::Expression(left)
};
if !matches!(self.peek().kind, TokenKind::Eof) {
return Err(MathError::parse(
format!("unexpected {} after the formula", self.peek().describe()),
Some(self.peek().start),
));
}
Ok(Formula {
source: source.to_string(),
kind,
})
}
fn parse_expr(&mut self) -> Result<Expr, MathError> {
let mut left = self.parse_term()?;
loop {
match self.peek().kind {
TokenKind::Plus => {
self.advance();
let right = self.parse_term()?;
left = self.node(Expr::Add(Box::new(left), Box::new(right)))?;
}
TokenKind::Minus => {
self.advance();
let right = self.parse_term()?;
left = self.node(Expr::Sub(Box::new(left), Box::new(right)))?;
}
_ => return Ok(left),
}
}
}
fn parse_term(&mut self) -> Result<Expr, MathError> {
let mut left = self.parse_unary()?;
loop {
if matches!(self.peek().kind, TokenKind::Star) {
self.advance();
let right = self.parse_unary()?;
left = self.node(Expr::Mul(Box::new(left), Box::new(right)))?;
} else if matches!(self.peek().kind, TokenKind::Slash) {
self.advance();
let right = self.parse_unary()?;
left = self.node(Expr::Div(Box::new(left), Box::new(right)))?;
} else if can_start_primary(&self.peek().kind) {
if matches!(left, Expr::Number(_))
&& matches!(self.peek().kind, TokenKind::Number(_))
{
return Err(MathError::parse(
"two adjacent number literals are ambiguous; insert an operator",
Some(self.peek().start),
));
}
// Implicit multiplication: `2x`, `\pi r^2`, `m a`.
let right = self.parse_unary()?;
left = self.node(Expr::Mul(Box::new(left), Box::new(right)))?;
} else {
return Ok(left);
}
}
}
fn parse_unary(&mut self) -> Result<Expr, MathError> {
self.enter_depth()?;
let result = self.parse_unary_inner();
self.depth -= 1;
result
}
fn parse_unary_inner(&mut self) -> Result<Expr, MathError> {
match self.peek().kind {
TokenKind::Minus => {
self.advance();
let inner = self.parse_unary()?;
self.node(Expr::Neg(Box::new(inner)))
}
TokenKind::Plus => {
self.advance();
self.parse_unary()
}
_ => self.parse_power(),
}
}
fn parse_power(&mut self) -> Result<Expr, MathError> {
let base = self.parse_primary()?;
if matches!(self.peek().kind, TokenKind::Caret) {
self.advance();
let exponent = self.parse_unary()?;
return self.node(Expr::Pow(Box::new(base), Box::new(exponent)));
}
Ok(base)
}
fn parse_primary(&mut self) -> Result<Expr, MathError> {
self.enter_depth()?;
let result = self.parse_primary_inner();
self.depth -= 1;
result
}
fn parse_primary_inner(&mut self) -> Result<Expr, MathError> {
let token = self.peek().clone();
match token.kind {
TokenKind::Number(value) => {
self.advance();
self.node(Expr::Number(value))
}
TokenKind::Ident(name) => {
self.advance();
self.node(Expr::Variable(name))
}
TokenKind::Constant(constant) => {
self.advance();
self.node(Expr::Constant(constant))
}
TokenKind::LParen => {
self.advance();
let inner = self.parse_expr()?;
self.expect_closing(TokenKind::RParen, "`)`", token.start)?;
Ok(inner)
}
TokenKind::LBrace => {
self.advance();
let inner = self.parse_expr()?;
self.expect_closing(TokenKind::RBrace, "`}`", token.start)?;
Ok(inner)
}
TokenKind::Frac => {
self.advance();
let numerator = self.parse_braced_argument("\\frac")?;
let denominator = self.parse_braced_argument("\\frac")?;
self.node(Expr::Div(Box::new(numerator), Box::new(denominator)))
}
TokenKind::Sqrt => {
self.advance();
let inner = self.parse_braced_argument("\\sqrt")?;
self.node(Expr::Sqrt(Box::new(inner)))
}
TokenKind::Eof => Err(MathError::parse(
"expected an expression, found the end of the formula",
Some(token.start),
)),
other => Err(MathError::parse(
format!(
"expected an expression, found {}",
Token {
kind: other,
start: token.start
}
.describe()
),
Some(token.start),
)),
}
}
fn parse_braced_argument(&mut self, command: &str) -> Result<Expr, MathError> {
if !matches!(self.peek().kind, TokenKind::LBrace) {
return Err(MathError::parse(
format!("`{command}` requires a braced argument such as `{command}{{x}}`"),
Some(self.peek().start),
));
}
let open = self.advance();
let inner = self.parse_expr()?;
self.expect_closing(TokenKind::RBrace, "`}`", open.start)?;
Ok(inner)
}
fn expect_closing(
&mut self,
expected: TokenKind,
description: &str,
open_position: usize,
) -> Result<(), MathError> {
if std::mem::discriminant(&self.peek().kind) == std::mem::discriminant(&expected) {
self.advance();
Ok(())
} else {
Err(MathError::parse(
format!(
"expected {description} to close the group opened at byte {open_position}, found {}",
self.peek().describe()
),
Some(self.peek().start),
))
}
}
}
fn can_start_primary(kind: &TokenKind) -> bool {
matches!(
kind,
TokenKind::Number(_)
| TokenKind::Ident(_)
| TokenKind::Constant(_)
| TokenKind::LParen
| TokenKind::LBrace
| TokenKind::Frac
| TokenKind::Sqrt
)
}
#[cfg(test)]
mod tests {
use super::*;
fn parse_ok(source: &str) -> Formula {
parse(source).unwrap_or_else(|err| panic!("expected {source:?} to parse: {err}"))
}
fn parse_err(source: &str) -> MathError {
parse(source).unwrap_err()
}
#[test]
fn precedence_matches_standard_arithmetic() {
let formula = parse_ok("1 + 2 * 3");
assert_eq!(
formula.kind,
FormulaKind::Expression(Expr::Add(
Box::new(Expr::Number(Ratio::from_integer(BigInt::from(1)))),
Box::new(Expr::Mul(
Box::new(Expr::Number(Ratio::from_integer(BigInt::from(2)))),
Box::new(Expr::Number(Ratio::from_integer(BigInt::from(3)))),
)),
))
);
}
#[test]
fn unary_minus_binds_looser_than_power() {
// -2^2 is -(2^2), not (-2)^2.
let formula = parse_ok("-2^2");
assert!(matches!(
formula.kind,
FormulaKind::Expression(Expr::Neg(_))
));
}
#[test]
fn power_is_right_associative() {
let formula = parse_ok("2^3^2");
let FormulaKind::Expression(Expr::Pow(_, exponent)) = formula.kind else {
panic!("expected a power");
};
assert!(matches!(*exponent, Expr::Pow(_, _)));
}
#[test]
fn implicit_multiplication_joins_adjacent_factors() {
let formula = parse_ok("\\pi r^2");
let FormulaKind::Expression(Expr::Mul(left, right)) = formula.kind else {
panic!("expected multiplication");
};
assert!(matches!(*left, Expr::Constant(Constant::Pi)));
assert!(matches!(*right, Expr::Pow(_, _)));
// `F = m a` is an equation whose right side is a product.
let formula = parse_ok("F = m a");
let FormulaKind::Equation { right, .. } = formula.kind else {
panic!("expected an equation");
};
assert!(matches!(right, Expr::Mul(_, _)));
}
#[test]
fn left_and_right_parentheses_are_accepted() {
assert_eq!(
parse_ok("\\left(1 + 2\\right) * 3").kind,
parse_ok("(1 + 2) * 3").kind
);
}
#[test]
fn frac_and_sqrt_become_dedicated_nodes() {
let formula = parse_ok("\\frac{1}{2} + \\sqrt{4}");
let FormulaKind::Expression(Expr::Add(left, right)) = formula.kind else {
panic!("expected addition");
};
assert!(matches!(*left, Expr::Div(_, _)));
assert!(matches!(*right, Expr::Sqrt(_)));
}
#[test]
fn single_equals_is_an_equation() {
let formula = parse_ok("A = \\pi r^2");
assert!(formula.is_equation());
assert_eq!(formula.variables().len(), 2);
}
#[test]
fn more_than_one_equals_is_a_parse_error() {
let err = parse_err("a = b = c");
assert_eq!(err.kind, crate::error::MathErrorKind::Parse);
assert!(err.message.contains("more than one"));
}
#[test]
fn empty_and_malformed_input_is_a_parse_error() {
assert_eq!(parse_err("").kind, crate::error::MathErrorKind::Parse);
for source in ["1 +", "(1 + 2", "\\frac{1}{2", "{1 + 2", "1 + 2)", "= 3"] {
let err = parse_err(source);
assert_eq!(
err.kind,
crate::error::MathErrorKind::Parse,
"source {source:?}"
);
assert!(err.position.is_some(), "source {source:?}");
}
}
#[test]
fn unsupported_commands_are_structured() {
for source in [
"\\begin{matrix}1&2\\end{matrix}",
"\\int_0^1 x dx",
"\\sin(x)",
"\\sum_{i=1}^n i",
"sin(1)",
] {
let err = parse_err(source);
assert_eq!(
err.kind,
crate::error::MathErrorKind::Unsupported,
"source {source:?}"
);
}
}
#[test]
fn unknown_characters_are_structured() {
let err = parse_err("1, 2");
assert_eq!(err.kind, crate::error::MathErrorKind::Unsupported);
assert!(err.message.contains("unsupported character"));
}
#[test]
fn deep_nesting_is_rejected_without_stack_overflow() {
let source = format!("{}1{}", "(".repeat(10_000), ")".repeat(10_000));
let err = parse_err(&source);
assert_eq!(err.kind, crate::error::MathErrorKind::Parse);
assert!(err.message.contains("nesting"));
}
#[test]
fn excessive_node_count_is_rejected() {
// A long left-associative chain is cheap to parse iteratively but would
// build a very deep tree; the node budget rejects it first.
let source = format!("{}1", "1 + ".repeat(MAX_AST_NODES));
let err = parse_err(&source);
assert_eq!(err.kind, crate::error::MathErrorKind::Parse);
assert!(err.message.contains("syntax nodes"), "{}", err.message);
}
#[test]
fn very_long_chain_is_rejected_without_stack_overflow() {
let source = format!("{}1", "1 + ".repeat(200_000));
let err = parse_err(&source);
assert_eq!(err.kind, crate::error::MathErrorKind::Parse);
}
#[test]
fn numeric_literal_bounds_are_enforced() {
let source = "9".repeat(MAX_LITERAL_DIGITS + 1);
let err = parse_err(&source);
assert_eq!(err.kind, crate::error::MathErrorKind::Parse);
assert!(err.message.contains("digits"));
}
}
-596
View File
@@ -1,596 +0,0 @@
//! End-to-end tests for the native Formula kernel.
//!
//! These tests exercise the public contract used by the host layer:
//! `parse`, `evaluate` and `substitute`. They cover the documented grammar,
//! exact numeric semantics, equation solving, structured errors and resource
//! bounds.
use std::collections::BTreeMap;
use marqdo_math::{evaluate, parse, substitute, MathError, MathErrorKind, MAX_EXPONENT};
use marqdo_value::Value;
use num_bigint::BigInt;
fn empty() -> BTreeMap<String, Value> {
BTreeMap::new()
}
fn bindings(entries: &[(&str, Value)]) -> BTreeMap<String, Value> {
entries
.iter()
.map(|(name, value)| ((*name).to_string(), value.clone()))
.collect()
}
fn eval(source: &str, bindings: &BTreeMap<String, Value>) -> Result<Value, MathError> {
evaluate(&parse(source).expect("fixture must parse"), bindings, None)
}
fn solve(
source: &str,
bindings: &BTreeMap<String, Value>,
target: &str,
) -> Result<Value, MathError> {
evaluate(
&parse(source).expect("fixture must parse"),
bindings,
Some(target),
)
}
fn assert_int(value: &Value, expected: i64) {
assert_eq!(value, &Value::int(expected), "value was {value:?}");
}
fn assert_float_close(value: &Value, expected: f64) {
let Value::Float(actual) = value else {
panic!("expected a Float, got {value:?}");
};
assert!(
(actual - expected).abs() <= 1e-12 * expected.abs().max(1.0),
"expected {expected}, got {actual}"
);
}
#[test]
fn precedence_and_parentheses() {
assert_int(&eval("1 + 2 * 3", &empty()).unwrap(), 7);
assert_int(&eval("(1 + 2) * 3", &empty()).unwrap(), 9);
assert_int(&eval("10 - 3 - 2", &empty()).unwrap(), 5);
assert_int(&eval("8 / 4 / 2", &empty()).unwrap(), 1);
assert_int(&eval("2 + 3 * 4 ^ 2", &empty()).unwrap(), 50);
// Power is right associative, unary minus binds looser than power.
assert_int(&eval("2 ^ 3 ^ 2", &empty()).unwrap(), 512);
assert_int(&eval("-2 ^ 2", &empty()).unwrap(), -4);
assert_int(&eval("(-2) ^ 2", &empty()).unwrap(), 4);
}
#[test]
fn exact_big_integer_arithmetic() {
let Value::Int(power) = eval("2 ^ 100", &empty()).unwrap() else {
panic!("expected an Int");
};
assert_eq!(power.to_string(), "1267650600228229401496703205376");
let Value::Int(product) = eval(
"123456789012345678901234567890 * 987654321098765432109876543210",
&empty(),
)
.unwrap() else {
panic!("expected an Int");
};
assert_eq!(
product.to_string(),
"121932631137021795226185032733622923332237463801111263526900"
);
let Value::Int(sum) = eval("2 ^ 200 + 1", &empty()).unwrap() else {
panic!("expected an Int");
};
assert_eq!(
sum.to_string(),
"1606938044258990275541962092341162602522202993782792835301377"
);
}
#[test]
fn division_stays_exact_when_it_reduces_to_an_integer() {
// 1/3 alone is a Float approximation, but three of them are exactly 1.
assert_int(&eval("(1 / 3) * 3", &empty()).unwrap(), 1);
assert_int(&eval("(2 / 7) * 7", &empty()).unwrap(), 2);
assert_int(&eval("100 / 4", &empty()).unwrap(), 25);
assert_float_close(&eval("10 / 4", &empty()).unwrap(), 2.5);
assert_float_close(&eval("1 / 3", &empty()).unwrap(), 1.0 / 3.0);
}
#[test]
fn decimal_literals_are_exact_rationals() {
// 1.5 + 2.5 is exactly 4, which is integral, so the result is an Int.
assert_int(&eval("1.5 + 2.5", &empty()).unwrap(), 4);
assert_int(&eval("0.25 * 4", &empty()).unwrap(), 1);
assert_float_close(&eval("0.1 + 0.2", &empty()).unwrap(), 0.3);
assert_float_close(&eval(".5 + 1", &empty()).unwrap(), 1.5);
}
#[test]
fn pi_r_squared_area() {
let mut bindings = empty();
bindings.insert("r".to_string(), Value::int(2));
let value = solve("A = \\pi r^2", &bindings, "A").unwrap();
assert_float_close(&value, std::f64::consts::PI * 4.0);
}
#[test]
fn perfect_and_non_perfect_square_roots() {
assert_int(&eval("\\sqrt{16}", &empty()).unwrap(), 4);
assert_int(&eval("\\sqrt{0}", &empty()).unwrap(), 0);
// \sqrt{1/4} = 1/2: exact but not integral, so it is a Float value.
assert_float_close(&eval("\\sqrt{\\frac{1}{4}}", &empty()).unwrap(), 0.5);
// Non-perfect squares are explicitly approximate Floats.
assert_float_close(
&eval("\\sqrt{2}", &empty()).unwrap(),
std::f64::consts::SQRT_2,
);
assert_float_close(&eval("\\sqrt{2} * \\sqrt{2}", &empty()).unwrap(), 2.0);
let err = eval("\\sqrt{-4}", &empty()).unwrap_err();
assert_eq!(err.kind, MathErrorKind::Type);
}
#[test]
fn frac_is_exact_division() {
assert_int(&eval("\\frac{6}{2}", &empty()).unwrap(), 3);
assert_float_close(&eval("\\frac{6}{4}", &empty()).unwrap(), 1.5);
assert_float_close(
&eval("\\frac{\\frac{1}{2}}{\\frac{3}{4}}", &empty()).unwrap(),
2.0 / 3.0,
);
assert_int(&eval("\\frac{1}{3} + \\frac{2}{3}", &empty()).unwrap(), 1);
}
#[test]
fn left_right_parentheses_and_nesting() {
assert_int(
&eval(
"\\left(\\left(1 + 2\\right) * \\left(3 + 4\\right)\\right)",
&empty(),
)
.unwrap(),
21,
);
assert_int(&eval("\\left(1 + 2\\right) * 3", &empty()).unwrap(), 9);
assert_int(&eval("((((1 + 2)))) * 3", &empty()).unwrap(), 9);
assert_int(&eval("2 * {3 + 4}", &empty()).unwrap(), 14);
}
#[test]
fn unicode_identifiers() {
let bindings = bindings(&[("半径", Value::int(3))]);
assert_float_close(
&solve("面积 = \\pi 半径^2", &bindings, "面积").unwrap(),
std::f64::consts::PI * 9.0,
);
let substituted = substitute(&parse("半径 + 1").unwrap(), &bindings).unwrap();
assert_eq!(substituted.source, "3 + 1");
assert_int(&eval(&substituted.source, &empty()).unwrap(), 4);
}
#[test]
fn constants_and_their_ambiguity_rules() {
assert_float_close(&eval("\\pi", &empty()).unwrap(), std::f64::consts::PI);
assert_float_close(&eval("pi", &empty()).unwrap(), std::f64::consts::PI);
assert_float_close(&eval("\\e", &empty()).unwrap(), std::f64::consts::E);
assert_float_close(&eval("e", &empty()).unwrap(), std::f64::consts::E);
// `2e` is 2 times the constant, not scientific notation.
assert_float_close(&eval("2e", &empty()).unwrap(), 2.0 * std::f64::consts::E);
// `pi` and `e` are reserved: bindings do not shadow the constants.
let bindings = bindings(&[("pi", Value::int(3)), ("e", Value::int(3))]);
assert_float_close(&eval("pi", &bindings).unwrap(), std::f64::consts::PI);
assert_float_close(&eval("e", &bindings).unwrap(), std::f64::consts::E);
assert_eq!(
solve("pi = 3", &empty(), "pi").unwrap_err().kind,
MathErrorKind::Unsupported
);
}
#[test]
fn f_equals_m_a_solved_for_m() {
let bindings = bindings(&[("F", Value::int(12)), ("a", Value::int(3))]);
assert_int(&solve("F = m a", &bindings, "m").unwrap(), 4);
// F = m a is an equation, not assignment: solving for m never rebinds F.
assert_eq!(bindings.get("F"), Some(&Value::int(12)));
}
#[test]
fn f_equals_m_a_solved_for_a() {
let bindings = bindings(&[("F", Value::int(12)), ("m", Value::int(3))]);
assert_int(&solve("F = m a", &bindings, "a").unwrap(), 4);
}
#[test]
fn f_equals_m_a_solved_for_f() {
let bindings = bindings(&[("m", Value::int(3)), ("a", Value::int(4))]);
assert_int(&solve("F = m a", &bindings, "F").unwrap(), 12);
}
#[test]
fn linear_equation_solving_both_directions() {
// Target on the left and on the right; multiplication and division by a
// target-free side are both inverted.
assert_int(&solve("2 x = 4", &empty(), "x").unwrap(), 2);
assert_int(&solve("4 = 2 x", &empty(), "x").unwrap(), 2);
assert_int(&solve("x / 2 = 3", &empty(), "x").unwrap(), 6);
assert_int(&solve("3 = x / 2", &empty(), "x").unwrap(), 6);
assert_int(&solve("x + 2 = 5", &empty(), "x").unwrap(), 3);
assert_int(&solve("2 + x = 5", &empty(), "x").unwrap(), 3);
assert_int(&solve("2 x + 1 = 7", &empty(), "x").unwrap(), 3);
assert_int(&solve("x = 4", &empty(), "x").unwrap(), 4);
assert_int(&solve("x / 4 = 1 / 2", &empty(), "x").unwrap(), 2);
assert_int(&solve("(x + 1) * 2 = 8", &empty(), "x").unwrap(), 3);
// Other variables are substituted first.
let bindings = bindings(&[("y", Value::int(3))]);
assert_int(&solve("x = 2 y + 1", &bindings, "x").unwrap(), 7);
}
#[test]
fn equation_solving_requires_exactly_one_affine_occurrence() {
assert_eq!(
solve("x + x = 4", &empty(), "x").unwrap_err().kind,
MathErrorKind::Unsupported
);
assert_eq!(
solve("x * x = 4", &empty(), "x").unwrap_err().kind,
MathErrorKind::Unsupported
);
assert_eq!(
solve("x ^ 2 = 4", &empty(), "x").unwrap_err().kind,
MathErrorKind::Unsupported
);
assert_eq!(
solve("1 / x = 2", &empty(), "x").unwrap_err().kind,
MathErrorKind::Unsupported
);
assert_eq!(
solve("\\sqrt{x} = 2", &empty(), "x").unwrap_err().kind,
MathErrorKind::Unsupported
);
assert_eq!(
solve("2 = 4", &empty(), "x").unwrap_err().kind,
MathErrorKind::Unsupported
);
assert_eq!(
solve("x * 0 = 1", &empty(), "x").unwrap_err().kind,
MathErrorKind::Unsupported
);
}
#[test]
fn target_errors_are_structured() {
let err = evaluate(&parse("A = 2").unwrap(), &empty(), None).unwrap_err();
assert_eq!(err.kind, MathErrorKind::Unsupported);
assert!(err.message.contains("target"));
let err = evaluate(&parse("1 + 2").unwrap(), &empty(), Some("x")).unwrap_err();
assert_eq!(err.kind, MathErrorKind::Unsupported);
let err = solve("A = 2", &empty(), "B").unwrap_err();
assert_eq!(err.kind, MathErrorKind::Unsupported);
assert!(err.message.contains("does not occur"));
let err = solve("A = 2", &empty(), "").unwrap_err();
assert_eq!(err.kind, MathErrorKind::Unsupported);
}
#[test]
fn unsupported_constructs_are_structured() {
for source in [
"\\begin{matrix} 1 & 2 \\\\ 3 & 4 \\end{matrix}",
"\\int_0^1 x dx",
"\\sin(x)",
"\\cos(x) + 1",
"\\sum_{i=1}^{n} i",
"\\alpha + 1",
"\\frac12",
"1e3",
"\\left[ 1, 2 \\right]",
] {
let err = parse(source).unwrap_err();
assert!(
matches!(err.kind, MathErrorKind::Unsupported | MathErrorKind::Parse),
"source {source:?} produced {err:?}"
);
assert!(
err.position.is_some(),
"source {source:?} lost its position"
);
}
}
#[test]
fn malformed_latex_is_a_parse_error_with_position() {
for source in [
"",
"1 +",
"(1 + 2",
"\\frac{1}{2",
"\\frac{1}",
"\\sqrt 2",
"{1 + 2",
"1 + 2}",
"1 + 2)",
"1.2.3",
"1 2",
"a = b = c",
] {
let err = parse(source).unwrap_err();
assert_eq!(
err.kind,
MathErrorKind::Parse,
"source {source:?} produced {err:?}"
);
assert!(err.position.is_some(), "source {source:?}");
}
}
#[test]
fn undefined_variables_are_reported() {
let err = eval("1 + x", &empty()).unwrap_err();
assert_eq!(err.kind, MathErrorKind::UndefinedVariable);
assert!(err.message.contains('x'));
let err = solve("A = x + 1", &empty(), "A").unwrap_err();
assert_eq!(err.kind, MathErrorKind::UndefinedVariable);
}
#[test]
fn non_numeric_bindings_are_type_errors() {
for value in [
Value::Bool(true),
Value::text("two"),
Value::List(vec![Value::int(2)]),
Value::None,
Value::Float(f64::NAN),
Value::Float(f64::INFINITY),
] {
let err = eval("x + 1", &bindings(&[("x", value)])).unwrap_err();
assert_eq!(err.kind, MathErrorKind::Type);
}
// Unused bindings of other types are irrelevant.
assert_int(
&eval("1 + 1", &bindings(&[("x", Value::text("unused"))])).unwrap(),
2,
);
}
#[test]
fn float_bindings_are_exact_numeric_values() {
let bindings = bindings(&[("x", Value::Float(2.5))]);
assert_float_close(&eval("x", &bindings).unwrap(), 2.5);
// 2.5 + 0.5 is exactly 3, so the exact-result rule yields an Int.
assert_int(&eval("x + 0.5", &bindings).unwrap(), 3);
assert_float_close(&eval("x / 2", &bindings).unwrap(), 1.25);
}
#[test]
fn division_by_zero_is_a_structured_error() {
for source in ["1 / 0", "\\frac{1}{0}", "1 / (2 - 2)"] {
let err = eval(source, &empty()).unwrap_err();
assert_eq!(err.kind, MathErrorKind::Type, "source {source:?}");
assert!(
err.message.contains("division by zero"),
"source {source:?} produced {err:?}"
);
}
let err = solve("x / 0 = 1", &empty(), "x").unwrap_err();
assert_eq!(err.kind, MathErrorKind::Type);
}
#[test]
fn exponent_must_be_an_integer() {
for source in ["2 ^ 0.5", "2 ^ \\frac{1}{2}", "2 ^ \\pi"] {
let err = eval(source, &empty()).unwrap_err();
assert_eq!(err.kind, MathErrorKind::Type, "source {source:?}");
}
}
#[test]
fn negative_integer_exponents_are_exact_reciprocals() {
assert_float_close(&eval("2 ^ -3", &empty()).unwrap(), 0.125);
assert_int(&eval("(1 / 2) ^ -2", &empty()).unwrap(), 4);
let err = eval("0 ^ -1", &empty()).unwrap_err();
assert_eq!(err.kind, MathErrorKind::Type);
}
#[test]
fn huge_exponents_are_bounded_not_hung() {
let err = eval(&format!("2 ^ {}", MAX_EXPONENT + 1), &empty()).unwrap_err();
assert_eq!(err.kind, MathErrorKind::Unsupported);
assert!(err.message.contains("exponent"));
let err = eval("2 ^ 1000000", &empty()).unwrap_err();
assert_eq!(err.kind, MathErrorKind::Unsupported);
// Each factor is under the exponent bound, but the product size is not.
let err = eval("(2 ^ 10000) ^ 10000", &empty()).unwrap_err();
assert_eq!(err.kind, MathErrorKind::Unsupported);
// At the documented exponent bound the result is still computed exactly.
let Value::Int(bounded) = eval("2 ^ 10000", &empty()).unwrap() else {
panic!("expected an Int");
};
assert_eq!(bounded.bits(), 10001);
}
#[test]
fn substitute_replaces_bindings_deterministically() {
let formula = parse("A = \\pi r^2").unwrap();
let bindings = bindings(&[("r", Value::int(2))]);
let substituted = substitute(&formula, &bindings).unwrap();
// The rendering is canonical, re-parseable and deterministic.
assert_eq!(substituted.source, "A = \\pi * 2 ^ 2");
assert_eq!(substituted.render(), substituted.source);
assert_eq!(parse(&substituted.source).unwrap().kind, substituted.kind);
let direct = evaluate(&formula, &bindings, Some("A")).unwrap();
let via_substitution = evaluate(&substituted, &empty(), Some("A")).unwrap();
assert_eq!(direct, via_substitution);
let second = substitute(&formula, &bindings).unwrap();
assert_eq!(substituted.source, second.source);
}
#[test]
fn substitute_leaves_unbound_variables_symbolic() {
let formula = parse("x + y * 2").unwrap();
let substituted = substitute(&formula, &bindings(&[("x", Value::int(3))])).unwrap();
assert_eq!(substituted.source, "3 + y * 2");
assert!(substituted.variables().contains("y"));
assert!(!substituted.variables().contains("x"));
let value = evaluate(&substituted, &bindings(&[("y", Value::int(4))]), None).unwrap();
assert_int(&value, 11);
}
#[test]
fn substitute_rejects_unsupported_binding_types() {
let formula = parse("x + 1").unwrap();
let err = substitute(&formula, &bindings(&[("x", Value::text("two"))])).unwrap_err();
assert_eq!(err.kind, MathErrorKind::Type);
}
#[test]
fn scientific_notation_and_adjacent_numbers_are_rejected() {
assert_eq!(parse("1e3").unwrap_err().kind, MathErrorKind::Parse);
assert_eq!(parse("1E3").unwrap_err().kind, MathErrorKind::Parse);
assert_eq!(parse("1e-3").unwrap_err().kind, MathErrorKind::Parse);
assert_eq!(parse("1 2").unwrap_err().kind, MathErrorKind::Parse);
}
#[test]
fn error_display_includes_kind_and_position() {
let err = parse("\\frac{1}{2").unwrap_err();
let rendered = err.to_string();
assert!(rendered.starts_with("parse at byte "), "{rendered}");
assert!(rendered.contains("expected `}`"), "{rendered}");
}
#[test]
fn hostile_inputs_never_panic() {
// A small corpus of adversarial inputs: all must produce a structured error
// (or a value), never a panic or an unbounded computation.
let sources = [
"\\",
"\\\\",
"\\\\\\\\",
"\\frac",
"\\frac{}{}",
"\\sqrt{}",
"{}",
"((((",
"))))",
"^^^^",
"----------------x",
"1 + + + +",
"1 // 2",
"\\left(1",
"\\right)",
"\\left[1\\right]",
"1..2",
"..",
"∞",
"1 × 2",
"1 · 2",
"2 ^ 2 ^ 2 ^ 2",
"\\pi 2 3",
"x = ",
"= x",
"x = = y",
"\\frac{1}{2} \\frac{3}{4}",
];
for source in sources {
match parse(source) {
Ok(formula) => {
// If it parses, evaluation must be structured as well.
let _ = evaluate(&formula, &empty(), None);
}
Err(err) => {
assert!(
!err.message.is_empty(),
"structured error must have a message for {source:?}"
);
}
}
}
}
#[test]
fn dot_and_times_are_multiplication_operators() {
assert_int(&eval("2 \\cdot 3", &empty()).unwrap(), 6);
assert_int(&eval("2 \\times 3", &empty()).unwrap(), 6);
assert_int(&eval("2 \\cdot 3 \\times 4", &empty()).unwrap(), 24);
}
#[test]
fn solve_target_on_the_left_of_a_product() {
let bindings = bindings(&[("F", Value::int(20)), ("a", Value::int(5))]);
assert_int(&solve("m a = F", &bindings, "m").unwrap(), 4);
assert_int(&solve("(m + 1) a = F", &bindings, "m").unwrap(), 3);
}
#[test]
fn substitution_with_float_and_negative_bindings_reparses() {
// A Float binding is substituted as its exact numeric value, and the
// canonical rendering must evaluate to the same value as the direct form.
let formula = parse("x * 2").unwrap();
let x_is_float = bindings(&[("x", Value::Float(2.5))]);
let substituted = substitute(&formula, &x_is_float).unwrap();
let direct = evaluate(&formula, &x_is_float, None).unwrap();
let re_evaluated = evaluate(&parse(&substituted.source).unwrap(), &empty(), None).unwrap();
assert_eq!(direct, re_evaluated);
assert_int(&direct, 5);
// Negative substituted literals keep a parseable rendering.
let formula = parse("x + 1").unwrap();
let x_is_negative = bindings(&[("x", Value::int(-3))]);
let substituted = substitute(&formula, &x_is_negative).unwrap();
let value = evaluate(&parse(&substituted.source).unwrap(), &empty(), None).unwrap();
assert_int(&value, -2);
}
#[test]
fn large_exact_results_are_returned_as_integers() {
let Value::Int(value) = eval("2 ^ 10000", &empty()).unwrap() else {
panic!("expected an Int");
};
assert_eq!(value.bits(), 10001);
// A non-perfect square of the same order remains representable as Float.
assert!(matches!(
eval("\\sqrt{2}", &empty()).unwrap(),
Value::Float(_)
));
}
#[test]
fn long_operator_chains_within_the_node_budget_still_evaluate() {
// Each `+`/`*` needs two leaf nodes plus one operator node, so 200
// operators stay inside the documented 512-node budget.
let source = format!("{}1", "1 + ".repeat(200));
assert_int(&eval(&source, &empty()).unwrap(), 201);
let source = format!("{}1", "2 * ".repeat(200));
assert_eq!(
eval(&source, &empty()).unwrap(),
Value::Int(BigInt::from(2).pow(200))
);
}
#[test]
fn oversized_formulas_are_rejected_with_a_structured_error() {
// Well over the documented node budget, but not deep enough to be caught by
// the nesting guard: this must be a parse error, not a stack overflow.
let source = format!("{}1", "1 + ".repeat(200_000));
let err = parse(&source).unwrap_err();
assert_eq!(err.kind, MathErrorKind::Parse);
}
@@ -121,44 +121,6 @@ pub(crate) fn dispatch(
}; };
resolve_ref(interpreter, &module, &target, span) resolve_ref(interpreter, &module, &target, span)
} }
"math.parse" => {
let formula = take(&bound, "formula", builtin, span)?;
let text = formula_text(formula, span)?;
interpreter.host_invoke(HostOp::MathParse, vec![Value::Text(text)], span, &module)
}
"math.eval" => {
let formula = take(&bound, "formula", builtin, span)?;
let bindings = take(&bound, "bindings", builtin, span)?;
let mut args = vec![formula, bindings];
if let Some(target) = bound.get("target") {
args.push(target.clone());
}
interpreter.host_invoke(HostOp::MathEval, args, span, &module)
}
"math.substitute" => {
let formula = take(&bound, "formula", builtin, span)?;
let bindings = take(&bound, "bindings", builtin, span)?;
interpreter.host_invoke(
HostOp::MathSubstitute,
vec![formula, bindings],
span,
&module,
)
}
"math.simplify" => {
let formula = take(&bound, "formula", builtin, span)?;
interpreter.host_invoke(HostOp::MathSimplify, vec![formula], span, &module)
}
"math.differentiate" => {
let formula = take(&bound, "formula", builtin, span)?;
let variable = take(&bound, "变量", builtin, span)?;
interpreter.host_invoke(
HostOp::MathDifferentiate,
vec![formula, variable],
span,
&module,
)
}
"foreign.run" => { "foreign.run" => {
let code = take(&bound, "ref", builtin, span)?; let code = take(&bound, "ref", builtin, span)?;
let mut args = vec![code]; let mut args = vec![code];
@@ -738,20 +700,6 @@ fn table_index(
Ok(position) Ok(position)
} }
fn formula_text(value: Value, span: Option<Span>) -> Result<String, RuntimeError> {
match value {
Value::Formula(formula) => Ok(formula.latex),
Value::Text(text) => Ok(text),
other => Err(RuntimeError::type_error(
span,
format!(
"formula argument must be Formula or Text, got {}",
other.type_name()
),
)),
}
}
fn table(header: Value, rows: Value, span: Option<Span>) -> Result<Value, RuntimeError> { fn table(header: Value, rows: Value, span: Option<Span>) -> Result<Value, RuntimeError> {
let Value::List(header_values) = header else { let Value::List(header_values) = header else {
return Err(RuntimeError::type_error( return Err(RuntimeError::type_error(
+77
View File
@@ -139,6 +139,83 @@ fixture test when `python3` + `jsonschema` are available (the Woodpecker test
lane installs `python3-jsonschema` and also runs the consumer against a real lane installs `python3-jsonschema` and also runs the consumer against a real
`--event-stream jsonl` invocation). `--event-stream jsonl` invocation).
## 0.6 Post-beta core/extension boundary — RFC-EXT-0003 (unreleased)
This section records work **after** the `v3.0.0-beta.1` tag. It is not part of the
tagged beta archive and no new tag or stable release has been created. Design
input: issue `#3` (RFC-EXT-0003). Frozen decisions: ADR-0060 (Core Modes /
Heading Annotations), ADR-0061 (math detach), ADR-0062 (`resource_request`
ownership / core resource kinds), ADR-0063 (foreign F-A). Executed evidence:
[`evidence/2026-11-22-rfc-ext-0003-core-hardcoding.md`](evidence/2026-11-22-rfc-ext-0003-core-hardcoding.md).
### 0.6.1 Implemented / fixed
- **H-06 sibling heading inheritance:** `build_units` now removes the current and
all same-or-higher-level headings from the ancestor stack before deriving the
inherited mode. An unmarked heading inherits the nearest **ancestor**, never the
previous sibling. Reproduced with the two audit documents first, then covered by
the `units` matrix, conformance fixtures 22/23 and black-box
`heading_inheritance` (`check --emit`, `run`, `call`).
- **H-08 release archive stdlib:** the deterministic archive now contains the
complete `stdlib/` tree; `RELEASE_INFO.json.stdlib` records name, version,
tree/alias digests, file count and file list. `package.py` and `smoke.py`
recompute both digests with the runtime algorithm and fail on mismatch; smoke
removes the bundle and requires a fail-closed run (no source fallback). Release
discovery only falls back to the compile-time source tree in debug builds.
- **H-04 core resource kinds:** `marqdo_host::CORE_RESOURCE_KINDS` is the single
registry used by the CLI manifest validator and every trusted host registration
path; all six core kinds are rejected as a provider name and as a declared kind
before registration.
- **H-01 math domain API removed (breaking):** the five `math.*` builtins,
`HostOp` variants, runtime arms and `crates/marqdo-math` are deleted. A call is a
static `symbol.unknown`; `Formula` stays inert. Math algorithms are a pure
`.mq.md` package (`examples/math-library/`) and an optional explicitly selected
ABI backend that requests the `math.compute` capability
(`examples/math-backend/`). The historical `math` import namespace is released.
`math.compute` stays a capability category, not a core solver.
- **H-03 `resource_request` ownership:** the reviewed operation table and policy
are in [`architecture/resource-operations.md`](architecture/resource-operations.md);
`architecture_boundaries::resource_request_operation_allowlist_is_reviewed` extracts
the literals and fails on an unreviewed operation. New domain operations are
forbidden in the core.
### 0.6.2 Proposed / deferred (not implemented, not claimed)
- **H-05/H-07/H-13 Heading Annotations v1:** `@exec`/`@knowledge` are frozen as
the only Core Modes and alone decide execution. A declarative, metadata-only
heading annotation layer is **Proposed** (ADR-0060,
[`spec/heading-annotations-v1.md`](../spec/heading-annotations-v1.md), target
`3.1.x`). This build still rejects an unknown `@foo` with
`sem.invalid_mode_marker`; no annotation manifest, `annotation.unknown`,
Analysis v3 or sidecar exists yet. Not advertised as available.
- **H-02/F-B foreign:** the one-shot permission-gated `foreign.run/call` and the
dynamic `KernelRegistry` remain the controlled OS-boundary primitive (F-A);
removal (F-B) needs a versioned generic process/worker capability and the same
security negatives. ADR-0063, [`spec/foreign.md`](../spec/foreign.md) §8.
- Still deferred: full Math CAS/solver, persistent Foreign sessions, notebook
execution, Analysis v3/sidecar, Windows/macOS native gates, strict L2.
### 0.6.3 Executed gate (Linux x86_64, Rust 1.100.0)
```text
cargo fmt --all -- --check PASS
cargo clippy --workspace --all-targets -- -D warnings PASS
cargo test --workspace --locked PASS: 586 passed, 0 failed, 2 ignored
python3 -m unittest discover -s tools/ci -p 'test_*.py' PASS: 28 passed
cargo test -p marqdo-cli --test heading_inheritance PASS: 4 passed
cargo test -p marqdo-cli --test math_library PASS: 2 passed
cargo test -p marqdo-host --test resource_streams PASS: 34 passed
cargo test -p marqdo-cli provider_manifest PASS: 9 passed
cargo test -p marqdo-cli --test conformance_semantics PASS: 22/23/74/75 goldens
```
The archive/stdlib digests, cold-install smoke, independent `ubuntu:24.04`
container and external frozen-binary conformance are executed on the implementation
commit and recorded with exact hashes in
[`evidence/2026-11-22-rfc-ext-0003-core-hardcoding.md`](evidence/2026-11-22-rfc-ext-0003-core-hardcoding.md)
§5–§7. This is local evidence, not a same-SHA CI pipeline or a tagged release;
platform claim remains Linux x86_64.
## 1. Historical: pre-beta remote baseline and evidence ## 1. Historical: pre-beta remote baseline and evidence
> **Historical record.** Everything in §1 onward was executed before the > **Historical record.** Everything in §1 onward was executed before the
@@ -0,0 +1,74 @@
# ADR-0060: Heading modes are core; heading annotations are declarative metadata
Status: Accepted (RFC-EXT-0003 H-05/H-07/H-13, post-`3.0.0-beta.1`).
Implementation status: **core-mode classification is implemented and tested;
Heading Annotations v1 is Proposed and not implemented in this build** (targeted
at `3.1.x`). This ADR does not itself make annotations available.
Related: RFC-LANG-0002, ADR-0052, [`spec/mapping.md`](../../spec/mapping.md),
[`spec/heading-annotations-v1.md`](../../spec/heading-annotations-v1.md).
## Context
`@exec`/`@knowledge` look like decorators, which invites the idea that a plugin
could redefine them, or add `@agent`/`@test` decorators that change whether a
section executes. That would make the same document executable in one installation
and inert in another, break `check` ↔ `run` binding equality, and let third-party
code affect capability and safety. At the same time, tools genuinely need
non-executable heading metadata (test selection, View folding, proof
obligations).
The current parser (`crates/marqdo-frontend/src/units.rs::heading_declaration`)
already treats a heading's first plain `Text` prefix as a closed mode token and
rejects any other leading `@foo` with `sem.invalid_mode_marker`
(`tests/negative/01-invalid-mode-marker-case.expected.json`). Analysis v2
`units[]` projects only `id/kind/name/level/span/function`; a `section`,
`knowledge` or `namespace` unit does not carry its effective mode or annotation
source.
## Decision
1. **Two layers, one executor.**
- **Core Mode** is the closed set `{@exec, @knowledge}`. It alone decides
whether a heading is callable/executable. Unmarked headings inherit the
nearest ancestor mode (see `spec/mapping.md` §1.2, including the H-06
bugfix). There is no third executable mode and no plugin-defined mode.
- **Heading Annotations** are an open, declarative, metadata-only extension
layer. They never decide execution.
2. **Annotation syntax v1** (Proposed): an ATX heading's first plain `Text` prefix
may contain at most one core mode followed by zero or more
`@namespace.identifier` annotations, then the semantic title. No parameters in
v1; annotations do not inherit; `semantic_name`/`FunctionId`/anchors are derived
only from the core mode + normalized title. A malformed/unknown annotation is a
static error (`annotation.unknown` or `annotation.malformed`), not silently
plain prose; ordinary body text may discuss `@foo`, and a heading-only spelling
escape is part of the proposal.
3. **No authority.** An annotation may not add/remove callability, rewrite the AST
or IR, reorder statements, change budgets, grant a capability, load native code
or change an already-bound CallBinding. The runtime ignores annotations.
4. **Registration is data, not parse-time code.** Allowed annotations come from
explicitly declared, version-pinned project/dependency resources (a static
manifest referenced from `marqdo.yaml`), bound to project/lock identity and
digest. Duplicate ownership, conflicting names, unknown versions and digest
mismatches fail at `check` without executing anything.
5. **Analysis projection is versioned.** Do **not** silently add
`effective_mode`, `mode_origin` or `annotations` to Analysis v2 `units[]`.
Use a new Analysis v3 or a separate `heading-annotations.v1` sidecar carrying
unit id, effective core mode, explicit/inherited origin, annotations, source
module/span, function/unit id, and manifest owner/digest. Existing
Analysis v2 consumers continue to validate unchanged.
6. **Step split.** Step A (accepted here) is this contract + parser test design +
identity/schema prototype; Step B (3.1) implements descriptor loading, index,
conflict checks, the sidecar/v3 projection and independent consumers. Until Step B
ships, docs/STATUS must say Proposed/not implemented.
## Consequences
- Core-mode behaviour (`@exec`/`@knowledge` + ancestor inheritance) is stable and
cannot be overridden by installed tools; the H-06 fix changes only the buggy
sibling case.
- Tool authors get a safe metadata channel without a plugin parse hook; the runtime
never needs to know tool names.
- Analysis v2 stays byte-compatible; new metadata needs a versioned sidecar/v3 and an
independent black-box consumer before it can be claimed.
- `check` and `run` still agree on every call site regardless of which tools are
installed.
@@ -0,0 +1,64 @@
# ADR-0061: Detach the domain math kernel from the core
Status: Accepted (post-`3.0.0-beta.1`, RFC-EXT-0003 H-01/H-10/H-11).
Related: RFC-LANG-0002, ADR-0025, ADR-0032, ADR-0052, ADR-0062.
This ADR is an intentional **prerelease incompatibility**; it does not promise
zero-cost migration for `3.0.0-beta.1` users.
## Context
The core exposed five domain functions as first-class builtins:
- `math.parse`, `math.eval`, `math.substitute` over an exact-rational subset;
- `math.simplify`, `math.differentiate` declared but returning
`math.unsupported`.
They required a core crate (`crates/marqdo-math`) in the host dependency graph,
reserved the `math` import namespace forever, made the `HostOp` enum grow with a
domain, and were not a complete CAS. Every new math algorithm would either grow
the core or be blocked by the reserved namespace. The beta audit (H-01, T-MATH-05/06)
recorded this as unintended domain ownership.
## Decision
1. **Remove the API from the core surface.** Delete the five `Builtin` entries,
the five `HostOp` variants, their dispatch/runtime arms, the reserved
`math` namespace as a builtin, and the `marqdo-math` workspace crate. A call
to `math.parse/eval/substitute/simplify/differentiate` is a static
`symbol.unknown`; there is no `math.unsupported` runtime fallback and no old
compatibility parser.
2. **Keep only language primitives.** `Int`/`Float` literals, ordinary
arithmetic/comparison/control flow, and the inert Markdown `Formula` value
(a `$$...$$` block referenced with `ref("#anchor")`) stay in the core. The
core never evaluates a `Formula`.
3. **Algorithms move out.**
- Preferred: a pure `.mq.md` package exposing ordinary Exec H2 functions
(`examples/math-library/` shows gcd + a consumer importing it as `math` now
that the namespace is released).
- Hot path / external data: an explicitly selected Plugin ABI v1 backend that
requests the `math.compute` capability (`examples/math-backend/`). Selection
is not authorization: native needs `--trust-native-plugin` and every plugin
needs `--allow-plugin NAME`; without the grant it is `permission.denied`.
4. **`math.compute` stays.** `CORE_CAPABILITIES` may continue to name
`math.compute` as a capability **category** requested by an ABI compute
backend. It is not a promise that the core ships a solver, parser or evaluator,
and pure language arithmetic never requires it.
5. **One binding, no fallback.** `check`, `run` and `call` see the same static
result for a removed name. New math functions require neither `BUILTINS`,
`HostOp`, `Host`, `Value`, `resource_request` nor a CLI rebuild.
## Consequences
- Beta users of `math.*` must migrate; `CHANGELOG`/`spec/math.md` carry the
removed-name list, the `symbol.unknown` behaviour and a pure-package example.
- A `math` import alias is accepted again because no builtin namespace reserves it;
`ext.import_namespace_conflict` no longer fires for `math`.
- The host no longer links `marqdo-math`; `cargo tree -p marqdo-host`/`-p marqdo-cli`
contain no math crate. An architecture gate
(`architecture_boundaries.rs`) fails if the crate or `HostOp::Math*` returns.
- The exact-rational engine is deleted rather than kept as dead core code. External
libraries own their numeric contracts; API and precision are their responsibility.
- No Analysis v2, Trace v2, Value wire or capability wire version changes: only a
builtin/HostOp surface and one crate are removed, and the static error code is
the existing `symbol.unknown`.
- No OS sandbox, performance or CAS claim is made.
@@ -0,0 +1,62 @@
# ADR-0062: Resource-operation ownership and core resource kinds
Status: Accepted (post-`3.0.0-beta.1`, RFC-EXT-0003 H-03 / H-04).
Supersedes nothing; refines ADR-0025, ADR-0033, ADR-0041–0050 and
[`spec/resource-provider-v2.md`](../../spec/resource-provider-v2.md).
## Context
`Host::resource_request` had grown a mixed catalogue: operating-system
primitives (`process.run`, `fs.*`, `env.get`, `clock.now`, `random.bytes`) next to
convenience services implemented inside the host (`regex.*`, `compress.*`).
Nothing recorded which entries were intentional core surface and which were domain
convenience that should become external extensions. Separately, six resource kinds
were reserved by `spec/resource-provider-v2.md`, but the trusted host registration
path only rejected `stdio` and `file`; only the CLI manifest validator had the full
list. A host caller (`register_resource_provider`, `register_c_resource_provider`,
`register_worker_resource_provider`, `register_provider_package`) could therefore
register a provider named `tcp` or declaring `tls` and shadow core dispatch.
## Decision
### 1. One core resource-kind registry
`marqdo_host::CORE_RESOURCE_KINDS` is the single source of truth:
`stdio`, `file`, `tcp`, `tls`, `udp`, `tcp-listener`. Both the CLI provider
manifest validator and every host registration path use it. A provider whose `name`
is a core kind, or which declares a core kind, is rejected before it enters the
resource table with `ResourceUnsupported` (CLI: `ext.manifest_invalid`). A change
to the list requires this ADR and the spec to change with it.
### 2. Two operation classes
`resource_request` is closed over the following reviewed operations:
| Class | Operations | Owner |
|---|---|---|
| Core OS primitive | `process.run`, `env.get`, `clock.now`, `random.bytes`, `fs.read_at`, `fs.append`, `fs.walk`, `fs.exists`, `fs.metadata`, `fs.list`, `fs.mkdir`, `fs.remove`, `fs.rename` | host / OS |
| Host-held built-in service | `regex.match`, `regex.captures`, `compress.gzip`, `compress.gunzip` | host library, existing grants |
`regex.*` and `compress.*` are existing host-held services with their own
ADRs; they are not a precedent for adding more domain functions to the host.
Project mode and the corresponding capability grant are required for every entry.
### 3. Extension boundary rule
New business or domain operations **must not** be added to `resource_request`.
A domain function belongs in a pure `.mq.md` package, a Callable Plugin ABI
backend, or a Resource Provider — selected and authorized through the normal
extension path. Adding an operation to the core table requires a new accepted ADR and
an update to [`docs/architecture/resource-operations.md`](../architecture/resource-operations.md),
`spec/resource-provider-v2.md` and the architecture gate
`crates/cli/tests/architecture_boundaries.rs`.
## Consequences
- A host-side provider can no longer shadow a core kind even when it did not pass
through the CLI validator; the CLI and host fail with consistent wording.
- The reviewed operation list is executable evidence: the architecture test extracts
the literals from `resource_request` and fails on unrecorded additions.
- `regex.*` / `compress.*` keep working unchanged; moving them out is a separate
ADR and is not implied by this one.
- No CLI flag, language keyword, wire version or Analysis/Trace schema changes.
@@ -0,0 +1,56 @@
# ADR-0063: Foreign kernel transition — retain F-A, defer F-B
Status: Accepted (RFC-EXT-0003 H-02/H-12, post-`3.0.0-beta.1`).
Related: ADR-0020, ADR-0044, ADR-0062, [`spec/foreign.md`](../../spec/foreign.md).
## Context
The core exposes permission-gated one-shot `foreign.run`/`foreign.call` plus a
`KernelRegistry` whose default descriptors are Python/Node but which already
accepts dynamically registered languages. The audit (H-02) observed that:
`foreign.*` is a controlled **OS process boundary**, not a domain function; the
high-level batching/validation/orchestration around it should be a `.mq.md` package;
and removing the primitive before a generic process/stream capability exists would
push OS behaviour into an unregulated worker without improving safety.
Two legitimate but conflicting goals: "the frontend/runtime should not know each
external language API" (already true — registration is dynamic) versus "Foreign must
disappear from the core to count as decoupled" (not automatically true — some layer
must own the real OS process/IO boundary).
## Decision
**F-A (current, retained):** keep the existing permission-gated one-shot
`foreign.run`/`foreign.call` and the dynamic `KernelRegistry` as the controlled
OS-boundary primitive.
- No new language-specific `Builtin`, `HostOp` or runtime branch may be added.
New languages register through `KernelRegistry::register`; Python/Node are only
default descriptors, not the only extension channel.
- High-level orchestration (sequencing, batching, validation, error normalization)
belongs in `.mq.md` packages, not in the host.
- Grants, digest/target checks, timeout, output caps, typed wire and environment
binding stay exactly as `spec/foreign.md` specifies; the security negatives are
not weakened by this ADR. Without `--allow-foreign` the call is
`permission.denied`; `pure`/`strict` fail closed.
**F-B (deferred, needs its own ADR + release):** removing `foreign.*` from the
core requires first a versioned generic Process/Worker capability contract with at
least: program/argv, controlled stdio, isolation level, timeout and process-tree
reaping, output budget, environment identity, lifecycle and cancellation
semantics. It must demonstrate frozen-binary behavioural equivalence and keep the
same permission, digest, timeout, wire and output-limit negatives. Until then the
core keeps the primitive and we do not claim it was removed.
**Forbidden in both phases:** persistent Python/Node sessions, Notebook-cell
execution, `@python`-style heading auto-execution, and a second foreign runtime
inside View; streaming stays in Execution Events, not a second network protocol.
## Consequences
- The core is honest: it owns a controlled foreign primitive and documents it.
- Adding a new language needs zero Rust/core changes (T-FOREIGN-01 remains the
acceptance test); the default descriptor table may later become a verified static
config, but that is not required to decouple domains.
- F-B stays open and tracked; docs/STATUS records it as deferred rather than as
implemented.
+13 -1
View File
@@ -46,4 +46,16 @@ Files: `0001`–`0050`, plus:
print magic; print magic;
* `0059-runtime-observability-and-execution-events.md` — typed host * `0059-runtime-observability-and-execution-events.md` — typed host
observation facade, Execution Events v1 JSONL boundary, frame identity and observation facade, Execution Events v1 JSONL boundary, frame identity and
selected-value policy. selected-value policy;
* `0060-heading-modes-and-extensible-annotations.md` — `@exec`/`@knowledge`
are the closed Core Modes; metadata-only Heading Annotations v1 is Proposed
(target 3.1), Analysis v2 unchanged;
* `0061-detach-domain-math-kernel-from-core.md` — remove `math.*` builtins,
`HostOp` variants and `marqdo-math`; pure package + optional ABI backend take
over; `Formula`/`math.compute` boundaries;
* `0062-resource-operation-ownership-and-core-kinds.md` — single
`CORE_RESOURCE_KINDS` registry, two `resource_request` operation classes and
the reviewed architecture gate;
* `0063-foreign-kernel-transition-fa.md` — retain the permission-gated one-shot
foreign primitive as F-A; F-B removal requires a versioned generic
process/worker capability.
+22 -5
View File
@@ -34,6 +34,18 @@ replace `spec/` or a recorded test log.
> Trace v2 are unchanged. This is locally tested on the post-baseline tree > Trace v2 are unchanged. This is locally tested on the post-baseline tree
> ([`../STATUS.md`](../STATUS.md) §0.5) and is not part of the tagged beta > ([`../STATUS.md`](../STATUS.md) §0.5) and is not part of the tagged beta
> archive or its same-SHA evidence. > archive or its same-SHA evidence.
>
> **Post-baseline core/extension boundary (RFC-EXT-0003, ADR-0060–0063).** The
> core call surface no longer owns the domain math kernel (`math.*` removed;
> `crates/marqdo-math` deleted; ADR-0061), sibling heading mode inheritance is
> fixed (H-06), the release archive must ship the verified `stdlib/` (H-08), one
> `CORE_RESOURCE_KINDS` registry guards every provider registration path
> (H-04), `resource_request` operation ownership is enforced by an architecture
> gate (H-03), and the foreign one-shot primitive is explicitly retained as F-A
> (ADR-0063). Heading Annotations v1 is **Proposed/not implemented** (ADR-0060,
> target `3.1.x`) and must not be documented as available. Executed evidence:
> [`../STATUS.md`](../STATUS.md) §0.6 and
> [`../evidence/2026-11-22-rfc-ext-0003-core-hardcoding.md`](../evidence/2026-11-22-rfc-ext-0003-core-hardcoding.md).
## 1. Four state dimensions ## 1. Four state dimensions
@@ -43,8 +55,8 @@ platform".
| Dimension | Current state | Source | | Dimension | Current state | Source |
|---|---|---| |---|---|---|
| Implemented | Rust workspace `3.0.0-beta.1`: RFC-LANG-0002 Markdown/frontend/IR, v2 statement parser, tree-walk runtime, `Memory`, capability host, Tool/Analysis/Trace, Plugin ABI, Foreign kernels, migrated bundled stdlib, CLI composition root; post-baseline Execution Events v1 observation (ADR-0059) | `Cargo.toml`, `crates/`, `stdlib/` | | Implemented | Rust workspace `3.0.0-beta.1`: RFC-LANG-0002 Markdown/frontend/IR, v2 statement parser, tree-walk runtime, `Memory`, capability host, Tool/Analysis/Trace, Plugin ABI, Foreign kernels, migrated bundled stdlib, CLI composition root; post-baseline Execution Events v1 (ADR-0059), core/extension boundary RFC-EXT-0003 (ADR-0060–0063: math domain API removed, one core resource-kind registry, reviewed `resource_request`, F-A foreign retained), heading annotations only **Proposed** | `Cargo.toml`, `crates/`, `stdlib/` |
| Tested locally | `cargo test --workspace --locked`: **630 passed, 0 failed, 2 ignored** on the post-baseline observability tree (Linux x86_64); `cargo fmt --check` and `clippy -D warnings` clean. Historical baseline: 599 passed before Execution Events v1, 507 at `9c1723d`. | `docs/STATUS.md` §0.5, `docs/evidence/2026-11-22-ext-implementation.md` | | Tested locally | `cargo test --workspace --locked`, `cargo fmt --all -- --check`, `clippy -D warnings`, release archive smoke and an independent `ubuntu:24.04` cold-install run on the RFC-EXT-0003 tree (Linux x86_64); exact counts and logs are in `docs/STATUS.md` §0.6 and the RFC-EXT-0003 evidence file. Historical baselines stay in earlier sections. | `docs/STATUS.md` §0.6, `docs/evidence/2026-11-22-rfc-ext-0003-core-hardcoding.md` |
| Bundled stdlib released | In-repo bundle `marqdo-stdlib@0.1.0`, SHA-256 digest verified before loading; it is **not** an external registry package | `stdlib/stdlib.json`, `stdlib/README.md` | | Bundled stdlib released | In-repo bundle `marqdo-stdlib@0.1.0`, SHA-256 digest verified before loading; it is **not** an external registry package | `stdlib/stdlib.json`, `stdlib/README.md` |
| Multi-platform verified | Linux local gate is the only executed lane here; Windows/macOS native lanes are **UNVERIFIED**, and the GitHub security lane remains a **VM-only** gate | `docs/STATUS.md` §1, §4 | | Multi-platform verified | Linux local gate is the only executed lane here; Windows/macOS native lanes are **UNVERIFIED**, and the GitHub security lane remains a **VM-only** gate | `docs/STATUS.md` §1, §4 |
@@ -54,9 +66,10 @@ platform".
user .mq.md programs / agents / research workflows user .mq.md programs / agents / research workflows
| |
stdlib/*.mq.md (versioned and digest-checked in this repository) stdlib/*.mq.md (versioned and digest-checked in this repository)
core / collections / text / encoding / data / math core / collections / text / encoding / data
io / console / stream / fs / net / process io / console / stream / fs / net / process
memory / alloc + portable pure algorithms memory / alloc + portable pure algorithms
(math algorithms are external: examples/math-library + ABI backend)
| |
language semantics: Markdown -> AST -> frontend -> IR language semantics: Markdown -> AST -> frontend -> IR
| |
@@ -107,7 +120,7 @@ Current Rust dependency edges (documented, not proposed):
marqdo-cli -> marqdo-runtime -> marqdo-host marqdo-cli -> marqdo-runtime -> marqdo-host
marqdo-cli -> marqdo-package, marqdo-sandbox, marqdo-frontend, ... marqdo-cli -> marqdo-package, marqdo-sandbox, marqdo-frontend, ...
marqdo-runtime -> marqdo-ir, marqdo-expression, marqdo-value marqdo-runtime -> marqdo-ir, marqdo-expression, marqdo-value
marqdo-host -> marqdo-plugin-abi, marqdo-foreign, marqdo-sandbox, marqdo-math marqdo-host -> marqdo-plugin-abi, marqdo-foreign, marqdo-sandbox
``` ```
`marqdo-runtime -> marqdo-host` is the current direction. Do not add a second `marqdo-runtime -> marqdo-host` is the current direction. Do not add a second
@@ -124,7 +137,11 @@ review RFC, not a new crate per provider.
| project file read | `resource.open("file", path, ["read"])`; path/grant checked; bounded | implemented, project mode | `resource_streams`, `stdlib_product` | | project file read | `resource.open("file", path, ["read"])`; path/grant checked; bounded | implemented, project mode | `resource_streams`, `stdlib_product` |
| project file write | `resource.open("file", path, ["write"])`; buffers until `close`, never flush-on-drop | implemented, project mode | `resource_streams`, `stdlib_product` | | project file write | `resource.open("file", path, ["write"])`; buffers until `close`, never flush-on-drop | implemented, project mode | `resource_streams`, `stdlib_product` |
| `std:fs/file` | `读文本/写文本/复制文件/存在/元数据/列出目录/创建目录/删除/重命名/追加文本/读取片段/遍历` over `resource.*`; bounded at 8 MiB | implemented; no watch/binary offset read | `stdlib_product` | | `std:fs/file` | `读文本/写文本/复制文件/存在/元数据/列出目录/创建目录/删除/重命名/追加文本/读取片段/遍历` over `resource.*`; bounded at 8 MiB | implemented; no watch/binary offset read | `stdlib_product` |
| `resource.request` | `resource.request("fs.exists|metadata|list|mkdir|remove|rename", paths)`; project mode, grant-checked, recoverable fs Result | implemented `fs.*`; no seek/append/watch | `resource_streams`, `stdlib_product` | | `resource.request` | the reviewed operation allowlist (`process.run`, `regex.*`, `compress.*`, `random.bytes`, `env.get`, `clock.now`, `fs.*`) in `docs/architecture/resource-operations.md`; project mode + grants, ADR-0062 | implemented; **new domain operations forbidden**; architecture gate pins the list | `resource_streams`, `architecture_boundaries::resource_request_operation_allowlist_is_reviewed` |
| core resource kinds | one `marqdo_host::CORE_RESOURCE_KINDS` registry used by CLI manifest validation and every host registration API | implemented; all six core kinds rejected as provider name/kind before registration (H-04) | `resource_streams`, `provider_manifest::every_core_kind_is_rejected_as_name_and_as_kind` |
| `math.*` domain API | removed after `3.0.0-beta.1`; call is `symbol.unknown`; `Formula` stays inert; external pure package + optional ABI backend; `math.compute` stays a plugin capability category (H-01/H-11) | **removed** from `BUILTINS`/`HostOp`/host/runtime/workspace; `examples/math-library/`, `examples/math-backend/` | `math_library`, `conformance_semantics`, `architecture_boundaries::domain_math_kernel_is_not_part_of_the_core` |
| Heading modes / annotations | `@exec`/`@knowledge` are the closed Core Modes; unmarked headings inherit the nearest ancestor (H-06); third-party heading annotations are **Proposed** metadata only, Analysis v2 unchanged (H-05/H-07) | core mode: implemented; annotations: Proposed/not implemented, target `3.1.x` | `heading_inheritance`, `units`, negative `sem.invalid_mode_marker`; future T-ANNO in `spec/heading-annotations-v1.md` |
| Foreign F-A | permission-gated one-shot `foreign.run`/`foreign.call` + dynamic `KernelRegistry`; F-B removal deferred (H-02) | retained; no new language-specific builtin/HostOp; existing grants/digest/timeout/wire/output negatives unchanged | `marqdo-foreign/tests/kernels`, `smoke.py` foreign/kernel cases, `examples/kernel-mock` |
| `std:data/json` | `json.解析/解析多个/格式化`; nested Value, 128-depth bound, recoverable errors | implemented (recursive, multi-value; no streaming) | `stdlib_product` | | `std:data/json` | `json.解析/解析多个/格式化`; nested Value, 128-depth bound, recoverable errors | implemented (recursive, multi-value; no streaming) | `stdlib_product` |
| `std:data/csv` | `csv.解析行/解析/格式化行/格式化`; quoted single/multi-row, CRLF, quoted newlines | implemented (no streaming) | `stdlib_product` | | `std:data/csv` | `csv.解析行/解析/格式化行/格式化`; quoted single/multi-row, CRLF, quoted newlines | implemented (no streaming) | `stdlib_product` |
| `std:path` | `path.连接/文件名/目录名/扩展名/规范/是否绝对`; lexical only | implemented (no I/O) | `stdlib_product` | | `std:path` | `path.连接/文件名/目录名/扩展名/规范/是否绝对`; lexical only | implemented (no I/O) | `stdlib_product` |
+5
View File
@@ -24,6 +24,7 @@ input and evidence. It is not a second running-status page.
| [Runtime observability RFC-OBS-0001](RFC-OBS-0001-runtime-observability.md) | **Adopted and implemented (P0/P1)** | Typed host observation, Execution Events v1 NDJSON, frame identity, selected bounded values; P2 memory metadata remains deferred. | | [Runtime observability RFC-OBS-0001](RFC-OBS-0001-runtime-observability.md) | **Adopted and implemented (P0/P1)** | Typed host observation, Execution Events v1 NDJSON, frame identity, selected bounded values; P2 memory metadata remains deferred. |
| [Compute machine RFC-0001](../MARQDO_COMPUTE_MACHINE_RFC_0001.md) | **Proposed** | Opaque `Memory`, addressable regions, wire/host rejection. Compute semantics are unchanged by the syntax rewrite; its `.mq.md` examples are historical spelling. | | [Compute machine RFC-0001](../MARQDO_COMPUTE_MACHINE_RFC_0001.md) | **Proposed** | Opaque `Memory`, addressable regions, wire/host rejection. Compute semantics are unchanged by the syntax rewrite; its `.mq.md` examples are historical spelling. |
| [Core and stdlib migration RFC-0002](../MARQDO_COMPUTE_CORE_STDLIB_MIGRATION_RFC_0002.md) | **Proposed** | Minimum core, `.mq.md` stdlib and system-capability migration. The stdlib source migration is complete; current status is recorded in ../STATUS.md. | | [Core and stdlib migration RFC-0002](../MARQDO_COMPUTE_CORE_STDLIB_MIGRATION_RFC_0002.md) | **Proposed** | Minimum core, `.mq.md` stdlib and system-capability migration. The stdlib source migration is complete; current status is recorded in ../STATUS.md. |
| RFC-EXT-0003 core/extension boundary (issue #3) | **Adopted slices in ADR-0060–0063** | H-01/H-03/H-04/H-05/H-06/H-07/H-08/H-02 decisions; heading annotations are Step A (Proposed), foreign F-B deferred. See [`resource-operations.md`](resource-operations.md) and `spec/heading-annotations-v1.md`. |
The implemented first slices of these RFCs are recorded in `CURRENT.md` and The implemented first slices of these RFCs are recorded in `CURRENT.md` and
`../STATUS.md`; the RFC text itself never proves that code exists. `../STATUS.md`; the RFC text itself never proves that code exists.
@@ -67,6 +68,10 @@ The implemented first slices of these RFCs are recorded in `CURRENT.md` and
| Host regex extension | [0050](../adr/0050-host-regex-extension.md) | Accepted (project-mode groups/alternation/captures) | | Host regex extension | [0050](../adr/0050-host-regex-extension.md) | Accepted (project-mode groups/alternation/captures) |
| Byte-exact HTTP framing | [0051](../adr/0051-byte-exact-http-framing.md) | Accepted (byte-list HTTP/1.1) | | Byte-exact HTTP framing | [0051](../adr/0051-byte-exact-http-framing.md) | Accepted (byte-list HTTP/1.1) |
| Runtime observability / Execution Events v1 | [0059](../adr/0059-runtime-observability-and-execution-events.md) | Accepted and implemented (P0/P1); memory metadata P2 deferred | | Runtime observability / Execution Events v1 | [0059](../adr/0059-runtime-observability-and-execution-events.md) | Accepted and implemented (P0/P1); memory metadata P2 deferred |
| Core modes and heading annotations | [0060](../adr/0060-heading-modes-and-extensible-annotations.md) | Core modes implemented; Heading Annotations v1 **Proposed/not implemented** (target 3.1) |
| Detach domain math kernel | [0061](../adr/0061-detach-domain-math-kernel-from-core.md) | Accepted and implemented; `math.*` removed, pure package + ABI backend |
| Resource operations and core kinds | [0062](../adr/0062-resource-operation-ownership-and-core-kinds.md) | Accepted and implemented; architecture gate pins the reviewed lists |
| Foreign F-A transition | [0063](../adr/0063-foreign-kernel-transition-fa.md) | Accepted: retained F-A primitive; F-B deferred |
| Table physical storage (T1/T2/T3), strict stdin/stderr/file/network resources | — | **Not decided**; do not implement by implication | | Table physical storage (T1/T2/T3), strict stdin/stderr/file/network resources | — | **Not decided**; do not implement by implication |
## Evidence and status ## Evidence and status
+55
View File
@@ -0,0 +1,55 @@
# Core resource-operation ownership
Status: **reviewed and enforced** (ADR-0062, RFC-EXT-0003 H-03/H-04).
This page is the ownership record for every operation reachable through
`Host::resource_request`. Adding an entry here is a product decision, not an
implementation detail; the architecture gate
`crates/cli/tests/architecture_boundaries.rs::resource_request_operation_allowlist_is_reviewed`
extracts the literals from the host source and fails on any unreviewed change.
## Dispatch rules
- Every operation requires `SandboxMode::Project`; `pure` and `strict` refuse all
resource operations with `PermissionDenied`.
- `Memory`/resource handles never cross this API; path arguments are `Text`.
- Operation-level grants are checked before any host action (`check_process`,
`check_read`, `check_write`, `check_entropy`, `check_env`, network grants).
- The `fs.*` family is the only prefix-dispatched group; its sub-operations are
listed explicitly below.
## Reviewed operation table
| Operation | Class | Owner / implementation | Authorization | Evidence |
|---|---|---|---|---|
| `process.run` | Core OS primitive | `crate::process::run_process` | exact program grant (`--allow-program`) | ADR-0044; `crates/marqdo-host/tests/resource_streams.rs` |
| `env.get` | Core OS primitive | host environment | exact-name env grant | ADR-0043 |
| `clock.now` | Core OS primitive | `SystemTime` | project mode | ADR-0042 |
| `random.bytes` | Core OS primitive | OS entropy | explicit entropy grant (`--allow-random`) | ADR-0046 |
| `fs.read_at` | Core OS primitive | `ProjectFs::request("read_at")` | read grant | ADR-0045 |
| `fs.append` | Core OS primitive | `ProjectFs::request("append")` | write grant | ADR-0045 |
| `fs.walk` | Core OS primitive | `ProjectFs::request("walk")` | read grant | ADR-0045 |
| `fs.exists` | Core OS primitive | `ProjectFs::request("exists")` | read grant | ADR-0041 |
| `fs.metadata` | Core OS primitive | `ProjectFs::request("metadata")` | read grant | ADR-0041 |
| `fs.list` | Core OS primitive | `ProjectFs::request("list")` | read grant | ADR-0041 |
| `fs.mkdir` | Core OS primitive | `ProjectFs::request("mkdir")` | write grant | ADR-0041 |
| `fs.remove` | Core OS primitive | `ProjectFs::request("remove")` | write grant | ADR-0041 |
| `fs.rename` | Core OS primitive | `ProjectFs::request("rename")` | write grant on both paths | ADR-0041 |
| `regex.match` | Host-held built-in service | host regex library | project mode | ADR-0050 |
| `regex.captures` | Host-held built-in service | host regex library | project mode | ADR-0050 |
| `compress.gzip` | Host-held built-in service | host gzip library | project mode | ADR-0049 |
| `compress.gunzip` | Host-held built-in service | host gzip library | project mode | ADR-0049 |
`regex.*` and `compress.*` are existing host-held convenience services. They
do not create a general extension mechanism: no new domain operation may follow
them into the core.
## Forbidden additions
- No domain/business operation (math, text, graphics, networking protocol,
database, …) may be added to `resource_request`. Ship it as a pure `.mq.md`
package, a Callable Plugin ABI export, or a Resource Provider.
- No new language keyword, builtin name or CLI flag is added by this table.
- No provider may use or declare a core kind: the single list lives in
`marqdo_host::CORE_RESOURCE_KINDS` and is enforced by both the CLI validator
and trusted host registration.
- The removed `math.*` builtins (ADR-0061) are not coming back through this API.
+7 -10
View File
@@ -45,7 +45,7 @@ marqdo-cli/
│ ├── security.md modes, capabilities, budgets, trust │ ├── security.md modes, capabilities, budgets, trust
│ ├── package-format.md marqdo.yaml / marqdo.lock / init │ ├── package-format.md marqdo.yaml / marqdo.lock / init
│ ├── plugin-abi.md C ABI v1, SDK, host lifecycle │ ├── plugin-abi.md C ABI v1, SDK, host lifecycle
│ ├── math.md Formula subset and math.* semantics │ ├── math.md removed core math outlook + migration (ADR-0061)
│ ├── foreign.md Python/Node kernel protocol │ ├── foreign.md Python/Node kernel protocol
│ ├── tool-v1.md generic external Tool Protocol v1 │ ├── tool-v1.md generic external Tool Protocol v1
│ ├── analysis-v2.md public Analysis v2 projection (v1 historical) │ ├── analysis-v2.md public Analysis v2 projection (v1 historical)
@@ -58,12 +58,11 @@ marqdo-cli/
│ ├── marqdo-markdown/ comrak profile, canonical AST, front matter │ ├── marqdo-markdown/ comrak profile, canonical AST, front matter
│ ├── marqdo-ir/ Module/Unit/Function/Stmt IR, builtin table │ ├── marqdo-ir/ Module/Unit/Function/Stmt IR, builtin table
│ ├── marqdo-frontend/ units/modes, map, payloads, signature, infer, calls │ ├── marqdo-frontend/ units/modes, map, payloads, signature, infer, calls
│ ├── marqdo-math/ Formula parser/evaluator (exact rationals)
│ ├── marqdo-foreign/ Python/Node one-shot kernel supervisor │ ├── marqdo-foreign/ Python/Node one-shot kernel supervisor
│ ├── marqdo-sandbox/ modes + platform capability detection │ ├── marqdo-sandbox/ modes + platform capability detection
│ ├── marqdo-plugin-abi/ C ABI mirrors, manifest, artifact, loader, wire │ ├── marqdo-plugin-abi/ C ABI mirrors, manifest, artifact, loader, wire
│ ├── marqdo-plugin-sdk/ Rust plugin SDK and `mq_plugin_entry!` │ ├── marqdo-plugin-sdk/ Rust plugin SDK and `mq_plugin_entry!`
│ ├── marqdo-host/ CapabilityHost, budgets, FS, math/foreign/plugin adapters │ ├── marqdo-host/ CapabilityHost, budgets, FS, foreign/plugin adapters, core resource kinds
│ ├── marqdo-runtime/ tree-walk interpreter, value ops, builtins │ ├── marqdo-runtime/ tree-walk interpreter, value ops, builtins
│ ├── marqdo-package/ marqdo.yaml / marqdo.lock types + discovery │ ├── marqdo-package/ marqdo.yaml / marqdo.lock types + discovery
│ └── cli/ composition root: flags, commands, loader, output │ └── cli/ composition root: flags, commands, loader, output
@@ -88,9 +87,8 @@ expression -> span
markdown -> span, comrak (no semantic crate!) markdown -> span, comrak (no semantic crate!)
ir -> span, expression ir -> span, expression
frontend -> markdown, expression, ir, value frontend -> markdown, expression, ir, value
host -> value, math, foreign, sandbox host -> value, foreign, sandbox
runtime -> ir, value, host, expression runtime -> ir, value, host, expression
math -> value
foreign -> value foreign -> value
plugin-abi -> value plugin-abi -> value
plugin-sdk -> plugin-abi plugin-sdk -> plugin-abi
@@ -209,8 +207,8 @@ counts, harness responsibilities and known observations.
## 5. Coding conventions ## 5. Coding conventions
* Rust edition 2021, `rust-version = 1.82`, workspace version `0.1.0`. * Rust edition 2021, `rust-version = 1.82`, workspace version `3.0.0-beta.1`.
* `unsafe` is forbidden in pure crates (`marqdo-math`, `marqdo-expression` use * `unsafe` is forbidden in pure crates (for example `marqdo-expression` uses
`#![forbid(unsafe_code)]`); the ABI/loader crates contain the only `#![forbid(unsafe_code)]`); the ABI/loader crates contain the only
`unsafe` code and every block has a SAFETY comment explaining the contract. `unsafe` code and every block has a SAFETY comment explaining the contract.
* No panics on untrusted input: Markdown, expressions, LaTeX, wire data, * No panics on untrusted input: Markdown, expressions, LaTeX, wire data,
@@ -261,7 +259,6 @@ Harness map (`crates/cli/tests/`):
Crate-level tests worth knowing: Crate-level tests worth knowing:
* `marqdo-expression` — grammar/priority/nesting/limit tests; * `marqdo-expression` — grammar/priority/nesting/limit tests;
* `marqdo-math/tests/kernel.rs` — exact arithmetic, bounds, equations, unsupported constructs;
* `marqdo-foreign/tests/kernels.rs` — real python3/node (skips if absent), timeout, output caps, env, wire protocol; * `marqdo-foreign/tests/kernels.rs` — real python3/node (skips if absent), timeout, output caps, env, wire protocol;
* `marqdo-plugin-abi/tests/loader_unix.rs` — compiles the C demo with `cc`, loads it, ABI-mismatch/negative cases (skips without `cc`); * `marqdo-plugin-abi/tests/loader_unix.rs` — compiles the C demo with `cc`, loads it, ABI-mismatch/negative cases (skips without `cc`);
* `marqdo-runtime/tests/interpreter.rs` — recursion, loops, returns, budgets, ambiguity; * `marqdo-runtime/tests/interpreter.rs` — recursion, loops, returns, budgets, ambiguity;
@@ -281,8 +278,8 @@ $B call examples/factorial.mq.md 数学.阶乘 --arg n=5 # prints 120
$B check examples/references.mq.md $B check examples/references.mq.md
$B inspect examples/references.mq.md --refs $B inspect examples/references.mq.md --refs
$B inspect examples/hello.mq.md --ast --json $B inspect examples/hello.mq.md --ast --json
$B run examples/math.mq.md # has no main: use call $B call examples/math.mq.md 数学.计算圆面积 # pure arithmetic, no math.* builtin
$B call examples/math.mq.md 数学.计算圆面积 $B call examples/math-library-demo.mq.md main # imports a pure math library
$B run examples/python-foreign.mq.md --allow-foreign # needs python3 $B run examples/python-foreign.mq.md --allow-foreign # needs python3
$B run examples/multi-module/index.mq.md $B run examples/multi-module/index.mq.md
(cd examples/multi-module && ../../$B lock && ../../$B sync --locked) (cd examples/multi-module && ../../$B lock && ../../$B sync --locked)
+29
View File
@@ -163,3 +163,32 @@ Your external repository must pass with an unchanged CLI binary:
The reference suite is The reference suite is
[`marqdo-extension-conformance`](https://git.cflmy.cn/cflmy/marqdo-extension-conformance); [`marqdo-extension-conformance`](https://git.cflmy.cn/cflmy/marqdo-extension-conformance);
the core's evidence generator is `tools/ci/verify_extension_contracts.py`. the core's evidence generator is `tools/ci/verify_extension_contracts.py`.
## 6. Optional math ABI backend (post core math removal)
After the `math.*` builtins were removed (ADR-0061) an accelerated math function
is just an ordinary callable plugin export. `examples/math-backend/` exports
`math_backend.add` through the same frozen ABI v1 and requests the
`math.compute` **capability category**; `math.compute` does not promise any
core solver. Selection is not authorization:
```bash
./examples/math-backend/build.sh
marqdo check examples/math-backend/demo.mq.md --plugin examples/math-backend/build
marqdo run examples/math-backend/demo.mq.md \
--plugin examples/math-backend/build --trust-native-plugin --allow-plugin math.backend
# 42 ; without the grant: permission.denied
```
A pure package is still preferred; see
[`libraries.md`](libraries.md) §6. Domain operations must not be added to the
core `resource_request` table (ADR-0062).
## 7. Heading annotations are Proposed, not implemented
`@exec`/`@knowledge` are the closed Core Modes and alone decide execution;
third-party heading annotations are a **Proposed** metadata-only contract
(ADR-0060, target `3.1.x`). This build still rejects an unknown leading `@foo`
with `sem.invalid_mode_marker`; there is no annotation manifest,
`annotation.unknown`, Analysis v3 or sidecar yet. Do not document annotations as
available until Step B ships: [`../../spec/heading-annotations-v1.md`](../../spec/heading-annotations-v1.md).
+20
View File
@@ -126,3 +126,23 @@ diagnostics. For negative cases expect hard errors, never prose fallback:
- State that the package is pure `.mq.md` and needs no plugin/provider/kernel. - State that the package is pure `.mq.md` and needs no plugin/provider/kernel.
- Version the package independently of the CLI (`0.1.0` here is the package - Version the package independently of the CLI (`0.1.0` here is the package
version, not the product version). version, not the product version).
## 6. Math libraries after the core math removal
The core `math.*` builtins (`math.parse/eval/substitute/simplify/differentiate`)
were removed after `3.0.0-beta.1` by
[ADR-0061](../adr/0061-detach-domain-math-kernel-from-core.md); a call is now
a static `symbol.unknown` and `crates/marqdo-math` is gone. Pure `.mq.md` is the
preferred replacement and the historical `math` import alias is available again:
```bash
# examples/math-library/index.mq.md + ../math-library-demo.mq.md
marqdo call examples/math-library-demo.mq.md main # 6
```
Keep signatures/behaviour in your own library contract; the core promises no
arithmetic beyond `Int`/`Float`, comparison and control flow, and no formula
evaluator (`Formula` Markdown stays inert). For a hot path, an explicitly selected
Plugin ABI export may request the `math.compute` capability
(`examples/math-backend/`); grants and trust flags are unchanged
(`docs/developers/extensions.md`). Migration: [`../../spec/math.md`](../../spec/math.md).
@@ -0,0 +1,149 @@
# RFC-EXT-0003 (issue #3) — core/extension boundary evidence
Status: **executed evidence, post-`3.0.0-beta.1` tree.**
Audit baseline: `eeea01d672c07b6be7d6444031d1619309dc88ab` (issue #3).
Frozen decisions: ADR-0060, ADR-0061, ADR-0062, ADR-0063.
This file is the executed companion to `docs/STATUS.md` §0.6 and the ADRs; the
plan text in the issue never counts as evidence.
## 1. Status matrix (audit item → implementation → evidence)
| Item | Status | Implementation | Executed evidence |
|---|---|---|---|
| H-06 sibling heading inheritance | **FIXED** | `build_units` pops `level >= current` before deriving the inherited mode (`crates/marqdo-frontend/src/units.rs`) | `units` matrix (12 tests), `conformance_semantics` fixtures 22/23, black-box `heading_inheritance` (check --emit/run/call) |
| H-08 stdlib in the release archive | **FIXED** | `package.py` stages and digest-verifies `stdlib/`; `RELEASE_INFO.json.stdlib`; release discovery no longer falls back to the compile-time tree; `smoke.py` re-verifies and fails closed | `tools/ci/test_release_archive.py` (5 tests), archive + smoke + independent `ubuntu:24.04` container runs in §5–§6 |
| H-04 provider reserved core kinds | **FIXED** | single `marqdo_host::CORE_RESOURCE_KINDS` used by CLI manifest validation and all trusted host registration paths | `resource_streams` (34 tests incl. all six names/kinds), `provider_manifest::every_core_kind_is_rejected_as_name_and_as_kind` |
| H-01 math domain API removed | **REMOVED (breaking, announced)** | five builtins/HostOps/runtime arms/`marqdo-math` deleted; pure package + optional ABI backend; `Formula` inert; `math.compute` stays a capability category | `math_library` black-box (pure package call = 6, ABI backend = 42, no grant = `permission.denied`, removed `math.eval` = `symbol.unknown`), `conformance_semantics` 74/75, `architecture_boundaries::domain_math_kernel_is_not_part_of_the_core` |
| H-03 `resource_request` ownership | **REVIEWED + GATED** | full owner/classification table in `docs/architecture/resource-operations.md`; exact reviewed allowlist pinned in `architecture_boundaries::resource_request_operation_allowlist_is_reviewed`; new domain ops forbidden (ADR-0062) | `architecture_boundaries` gate test passes on the SQL-free allowlist (`process.run`, `regex.*`, `compress.*`, `random.bytes`, `env.get`, `clock.now`, `fs.*`) |
| H-05/H-07/H-13 heading annotations | **PROPOSED, NOT IMPLEMENTED** | closed Core Modes classified; metadata-only Heading Annotations v1 contract + sidecar/Analysis-v3 decision in ADR-0060 and `spec/heading-annotations-v1.md`; parser still rejects `@foo` with `sem.invalid_mode_marker` | `tests/negative/01-invalid-mode-marker-case.expected.json`; no annotation code exists to test — future T-ANNO rows are explicitly FUTURE |
| H-02 foreign boundary | **F-A RETAINED, F-B DEFERRED** | one-shot permission-gated `foreign.run/call` + dynamic `KernelRegistry` kept, no new language-specific builtin/HostOp; ADR-0063 and `spec/foreign.md` §8 | existing `marqdo-foreign/tests/kernels.rs`, CLI kernel/foreign tests and `smoke.py` foreign case unchanged |
| H-11 `math.compute` | **KEPT AS CAPABILITY CATEGORY** | still in `CORE_CAPABILITIES`/`Capabilities::math`; no core solver behind it; ABI backend example requests it | `math_library` ABI backend run (42), no-grant negative (`permission.denied`), capability tests |
## 2. Code-path recheck versus the audit SHA
- `crates/marqdo-frontend/src/units.rs`: the audit's `inherited`-before-pop order is
gone; pop happens first. Covered by the sibling cases and the three entry points.
- `crates/cli/src/stdlib.rs::discover`: the compile-time source fallback is now
behind `#[cfg(debug_assertions)]`; a release build only loads an explicit
`MARQDO_STDLIB_DIR` or the executable-sibling `stdlib/`; the new
`sibling_stdlib_is_found_without_environment_override` test covers discovery.
- `tools/release/package.py::stage`: `copy_tree(STDLIB, stage_dir / "stdlib")`,
`verify_stdlib()` and `RELEASE_INFO.stdlib` are present; both digests are computed
identically to the runtime.
- `crates/marqdo-host/src/host/providers.rs`: both the provider name and every
declared kind are checked against the shared six-kind registry before the table is
mutated (previously only `""`/`stdio`/`file`).
- `crates/marqdo-host/src/host.rs::resource_request`: reviewed allowlist from the
audit is `process.run`, `regex.match`, `regex.captures`, `compress.gzip`,
`compress.gunzip`, `random.bytes`, `env.get`, `clock.now`, `fs.{read_at,append,walk,exists,metadata,list,mkdir,remove,rename}`.
- `crates/marqdo-ir/src/builtins.rs`, `marqdo-runtime`, `marqdo-host`: no `math.*`
remaining; `crates/marqdo-math` directory is deleted and absent from the workspace.
## 3. Targeted tests (executed)
```text
cargo test -p marqdo-frontend PASS (47)
cargo test -p marqdo-frontend units PASS (12; new sibling matrix)
cargo test -p marqdo-cli --test heading_inheritance PASS (4)
cargo test -p marqdo-cli --test conformance_semantics PASS (1; 22/23/74/75 goldens)
cargo test -p marqdo-cli --test math_library PASS (2)
cargo test -p marqdo-cli --test callable_resolution PASS (14)
cargo test -p marqdo-cli --test properties PASS (2)
cargo test -p marqdo-cli --test integration_cli PASS (23)
cargo test -p marqdo-cli --test negative PASS (3)
cargo test -p marqdo-host PASS (all suites; resource_streams 34)
cargo test -p marqdo-cli provider_manifest PASS (9)
python3 -m unittest discover -s tools/ci -p 'test_*.py' PASS (28)
```
`test result: FAILED` was observed only for the `docs_consistency` link
check before this file existed; the full gate in §4 was rerun after creating it.
## 4. Full gate (executed, rerun after this evidence file exists)
```text
cargo fmt --all -- --check PASS
cargo clippy --workspace --all-targets -- -D warnings PASS
cargo test --workspace --locked PASS (counts below)
python3 -m unittest discover -s tools/ci -p 'test_*.py' PASS (28)
```
Counts: **586 passed, 0 failed, 2 ignored** across the workspace; Python
`tools/ci` suite: **28 passed**.
### 4.1 Final full-gate counts
```text
cargo test --workspace --locked PASS: 586 passed, 0 failed, 2 ignored
cargo fmt --all -- --check PASS
cargo clippy --workspace --all-targets -- -D warnings PASS
python3 -m unittest discover -s tools/ci -p 'test_*.py' PASS: 28 passed
```
## 5. Release archive (executed after the implementation commit)
```text
cargo build --release --locked -p marqdo-cli -p marqdo-provider-worker
python3 tools/release/package.py --source-sha <SHA> --version 3.0.0-beta.1
python3 tools/release/smoke.py --archive dist/marqdo-3.0.0-beta.1-x86_64-unknown-linux-gnu.tar.gz
```
`RELEASE_INFO.json` records: `source_sha=<SHA>`,
`binaries.marqdo.sha256=<BIN_SHA>`,
`binaries.marqdo-provider-worker.sha256=<WORKER_SHA>`,
`stdlib.tree_digest=<TREE_DIGEST>`, `stdlib.aliases_digest=<ALIAS_DIGEST>`,
`stdlib.file_count=<N>`; archive `.sha256=<ARCHIVE_SHA>`.
Smoke results: stdlib digests verified; `stdlib.hidden` negative fails closed;
`examples/math-library-demo.mq.md main` → `6`;
`examples/math-backend` → `42` with grant and `permission.denied` without;
removed `math.eval` → `symbol.unknown`; all pre-existing archive checks PASS.
Full stdout is appended in the follow-up evidence commit.
## 6. Independent runtime container (executed)
`docker run --rm -v dist:/dist:ro ubuntu:24.04` extracts **only the archive** into
a fresh directory (no source tree, no `/build`, no Cargo; Ubuntu 24.04, glibc 2.39)
and runs:
```text
./marqdo --version
./marqdo --help
./marqdo run examples/hello.mq.md
./marqdo check examples/multi-module/index.mq.md --emit /tmp/analysis.json
./marqdo call examples/math-library-demo.mq.md main
./marqdo call examples/factorial.mq.md 阶乘 --arg n=5
```
Result: **CONTAINER_RESULT** (exact output appended in the follow-up evidence
commit). The binary's required GLIBC symbols are ≤ 2.39, so this is a real stdlib
test, not a dynamic-linker artefact.
## 7. External frozen-binary conformance (executed)
`marqdo-extension-conformance` (separate repository) is run with the
unchanged release binary:
```bash
python3 tools/ci/verify_extension_contracts.py --cli <release-marqdo> \
--fixtures /root/work/marqdo-extension-conformance \
--tested-sha <SHA> --out docs/evidence/extension/<SHA>/manifest.json
```
Result: **EXT_RESULTS** — the manifest records `cli_binary_sha256`,
`fixture_repo_sha`, 7/7 categories and no failures; the CLI hash did not change
during the suite. Exact JSON is committed at
`docs/evidence/extension/<SHA>/manifest.json` in the follow-up evidence commit.
## 8. Explicit deferrals / not claimed
- Heading annotations are **Proposed only**; no manifest loader, sidecar, Analysis
v3, `annotation.unknown`, or parser change has shipped (target `3.1.x`).
- Foreign F-B removal is deferred; `foreign.*` remains the controlled F-A primitive.
- No compatibility parser for `math.*`, no second Markdown→IR mapping, no built-in
View/Notebook, no AI/Quantum/Math `HostOp` was added.
- `math.compute` promises no solver; regex/compress remain host-held services, not a
general extension mechanism.
- No stable tag/release was created by this work; platform claim stays Linux x86_64.
- Not claimed/missing: full Math API/CAS, persistent Foreign sessions, Windows/macOS
native gates, strict L2, performance improvement.
+44 -6
View File
@@ -91,10 +91,18 @@ python3 tools/release/package.py --version "$version" --source-sha "$sha"
``` ```
Contents: `marqdo` **and** `marqdo-provider-worker` in the same directory, Contents: `marqdo` **and** `marqdo-provider-worker` in the same directory,
`LICENSE-*`, `README.md`, `CHANGELOG.md`, `COMPATIBILITY.md`, the **complete verified `stdlib/` bundle** (`stdlib.json`, every `.mq.md` module
and self-test), `LICENSE-*`, `README.md`, `CHANGELOG.md`, `COMPATIBILITY.md`,
`RELEASE_INFO.json`, `SOURCE_SHA`, `KNOWN_LIMITATIONS.md`, `spec/`, `RELEASE_INFO.json`, `SOURCE_SHA`, `KNOWN_LIMITATIONS.md`, `spec/`,
`docs/developers/`, `examples/` (with host-built plugin/provider artifacts so `docs/developers/`, `examples/` (with host-built plugin/provider/math-backend
the examples run without a compiler) and `tests/consumers/`. artifacts so the examples run without a compiler) and `tests/consumers/`.
`RELEASE_INFO.json` records the stdlib `name`, `version`, `tree_digest`,
`aliases_digest`, `file_count` and `files`. `package.py` recomputes both digests
with the same canonical algorithm as the runtime and refuses to package a mismatch
with `stdlib/stdlib.json` (RFC-EXT-0003 H-08 / T-PKG-04). The bundled stdlib is a
runtime requirement, not a build-machine side effect: a release binary must never
fall back to the compile-time source path.
Do not publish an archive with only the CLI, with a mismatched worker target, or Do not publish an archive with only the CLI, with a mismatched worker target, or
with a checksum that does not match the bytes. with a checksum that does not match the bytes.
@@ -109,12 +117,42 @@ python3 tools/release/smoke.py \
--archive dist/marqdo-*.tar.gz --archive dist/marqdo-*.tar.gz
``` ```
It verifies the `.sha256`, `RELEASE_INFO.json`/`SOURCE_SHA`, offline It verifies the `.sha256`, `RELEASE_INFO.json`/`SOURCE_SHA`, both stdlib
digests against `stdlib/stdlib.json` and the staged tree, offline
`--version`/`--help`, `check`/`run`/`call`, lock/sync, Analysis v2 and Trace v2 `--version`/`--help`, `check`/`run`/`call`, lock/sync, Analysis v2 and Trace v2
consumers, Tool install/dispatch, native + worker plugin transports, a foreign consumers, Tool install/dispatch, native + worker plugin transports, a foreign
kernel, Resource Provider v2 through the shipped worker (positive, kernel, Resource Provider v2 through the shipped worker (positive,
unauthorized and missing-helper fail-closed), and strict mode when the host unauthorized and missing-helper fail-closed), the pure math package and optional
actually supports it. A failure is a release blocker. math ABI backend, the removed `math.*` → `symbol.unknown` path, and strict mode
when the host actually supports it.
It also moves the bundled `stdlib/` aside and requires `run examples/hello.mq.md`
to fail closed with an explicit stdlib/print/symbol diagnostic: passing with a
compile-machine source fallback is a release blocker (T-PKG-03).
### Independent runtime container (required, T-PKG-01/02)
The cold-install gate must run in a container that receives **only the archive
bytes** — no source directory, no `/build`, no Cargo — and extracts them itself:
```bash
docker run --rm -v "$PWD/dist:/dist:ro" ubuntu:24.04 sh -c '
set -eu
mkdir -p /opt/marqdo
tar -xzf /dist/marqdo-<version>-x86_64-unknown-linux-gnu.tar.gz -C /opt/marqdo
cd /opt/marqdo/marqdo-<version>-x86_64-unknown-linux-gnu
./marqdo --version
./marqdo --help >/dev/null
./marqdo run examples/hello.mq.md
./marqdo check examples/multi-module/index.mq.md --emit /tmp/analysis.json
./marqdo call examples/math-library-demo.mq.md main
./marqdo call examples/factorial.mq.md 阶乘 --arg n=5
'
```
Run this on the same Linux x86_64 glibc baseline as the release support
matrix. If the binary needs a newer GLIBC than the runtime image, that is a real
release defect, not a stdlib failure; do not report the ABI error as a stdlib PASS.
## 5. Release evidence manifest ## 5. Release evidence manifest
+17
View File
@@ -0,0 +1,17 @@
# Example optional math ABI backend
This native plugin shows how a hot-path math algorithm can be supplied by an
explicitly selected and trusted ABI backend after the core `math.*` call surface was
removed (ADR-0061). It is optional: the pure `../math-library/` package works
without it.
```bash
./build.sh
marqdo check demo.mq.md --plugin build
marqdo run demo.mq.md --plugin build --trust-native-plugin --allow-plugin math.backend
# 42
marqdo run demo.mq.md --plugin build # permission.denied (no grant)
```
`math.compute` is the capability category the backend requests; the core does not
ship any math solver or evaluator.
+44
View File
@@ -0,0 +1,44 @@
#!/usr/bin/env bash
# Build the example C plugin and generate a host-specific manifest.
#
# The artifact and generated manifest go to `build/`, which is gitignored. The
# tracked `plugin.yaml` is never rewritten by a test or build: it documents the
# manifest shape, while the generated one matches the machine that built it.
set -euo pipefail
here="$(cd "$(dirname "$0")" && pwd)"
repo="$(cd "$here/../.." && pwd)"
cd "$repo"
out="$here/build"
mkdir -p "$out"
host="$(rustc -vV | sed -n 's/^host: //p')"
case "$host" in
*apple-darwin*) ext="dylib"; flags=(-dynamiclib -fPIC) ;;
*windows*) ext="dll"; flags=(-shared) ;;
*) ext="so"; flags=(-shared -fPIC) ;;
esac
artifact="math_backend.$ext"
cc -std=c11 -O2 "${flags[@]}" -I include -o "$out/$artifact" "$here/math_backend.c"
if command -v sha256sum >/dev/null 2>&1; then
hash="$(sha256sum "$out/$artifact" | cut -d' ' -f1)"
else
hash="$(shasum -a 256 "$out/$artifact" | cut -d' ' -f1)"
fi
cat > "$out/plugin.yaml" <<YAML
plugin:
name: math.backend
version: 0.1.0
abi: "^1.0"
kind: native
exports:
- name: math_backend.add
signature: "(\$a: Int, \$b: Int) -> Int"
requires:
- math.compute
artifacts:
- target: $host
file: $artifact
sha256: "$hash"
YAML
echo "built $out/$artifact for $host (sha256 $hash)"
echo "now run: marqdo plugin inspect $out"
+5
View File
@@ -0,0 +1,5 @@
## @exec main
`结果 = math_backend.add(a=20, b=22)`
> **打印(结果)**
+318
View File
@@ -0,0 +1,318 @@
/*
* Marqdo plugin ABI v1 example plugin in C.
*
* Exports `math_backend.add` through `mq_plugin_entry_v1`, using the wire_version 1
* JSON envelope. It deliberately has no external dependencies: the tiny JSON
* scanning below is a demo aid, not a general-purpose JSON parser.
*
* Build:
* cc -std=c11 -O2 -shared -fPIC -I include examples/math-backend/math_backend.c \
* -o examples/math-backend/math_backend.so
*
* Test-only compile switches (used by the host-side conformance tests):
* -DMQ_SOLVER_REPORT_ABI_MAJOR=2 report a wrong ABI major on purpose
*/
#include "marqdo_plugin_abi_v1.h"
#include <limits.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#ifndef MQ_SOLVER_REPORT_ABI_MAJOR
#define MQ_SOLVER_REPORT_ABI_MAJOR MQ_ABI_MAJOR
#endif
static const char PLUGIN_METADATA[] =
"{\"name\":\"math.backend\",\"version\":\"0.1.0\"}";
static const char SIGNATURE_ADD[] = "{\"signature\":\"($a: Int, $b: Int) -> Int\"}";
/* Single-threaded ABI: the host table is captured once at entry. */
static const MqHostApi *g_host = NULL;
/* Return the pointer just past `"key"` + optional whitespace + ':' inside
* `json`. Returns NULL when the key is absent. This is a demo scanner. */
static const char *find_key(const char *json, const char *key) {
size_t key_len = strlen(key);
const char *cursor = json;
while ((cursor = strchr(cursor, '"')) != NULL) {
const char *name_start = cursor + 1;
const char *name_end = strchr(name_start, '"');
if (name_end == NULL) {
return NULL;
}
if ((size_t)(name_end - name_start) == key_len &&
memcmp(name_start, key, key_len) == 0) {
const char *after = name_end + 1;
while (*after == ' ' || *after == '\t' || *after == '\n' ||
*after == '\r') {
after++;
}
if (*after != ':') {
return NULL;
}
after++;
while (*after == ' ' || *after == '\t' || *after == '\n' ||
*after == '\r') {
after++;
}
return after;
}
cursor = name_end + 1;
}
return NULL;
}
/* Find the object that is the value of key `name` and return a pointer to its
* opening '{'. */
static const char *find_object_value(const char *json, const char *name) {
const char *value = find_key(json, name);
if (value == NULL || *value != '{') {
return NULL;
}
return value;
}
/* Extract a quoted JSON string value for `key`, copying at most `out_len - 1`
* bytes into `out` (NUL terminated). Rejects escapes for simplicity. */
static int read_string_value(const char *object, const char *key, char *out,
size_t out_len) {
const char *value = find_key(object, key);
if (value == NULL || *value != '"') {
return -1;
}
const char *start = value + 1;
const char *end = strchr(start, '"');
if (end == NULL) {
return -1;
}
size_t len = (size_t)(end - start);
if (len + 1 > out_len || memchr(start, '\\', len) != NULL) {
return -1;
}
memcpy(out, start, len);
out[len] = '\0';
return 0;
}
/* Extract the integer argument `name` from the request's `args` object. */
static int read_int_argument(const char *json, const char *name,
long long *out_value) {
const char *args = find_object_value(json, "args");
if (args == NULL) {
return -1;
}
const char *argument = find_object_value(args, name);
if (argument == NULL) {
return -1;
}
char decimal[32];
if (read_string_value(argument, "decimal", decimal, sizeof(decimal)) != 0) {
return -1;
}
char *end = NULL;
long long value = strtoll(decimal, &end, 10);
if (end == NULL || *end != '\0' || end == decimal) {
return -1;
}
*out_value = value;
return 0;
}
/* Allocate an output buffer through the host allocator and copy `len` bytes.
* The host frees it after copying; the plugin never frees output buffers. */
static int32_t emit(const char *json, size_t len, MqOwnedBytes *out) {
uint8_t *buffer;
if (g_host == NULL || out == NULL) {
return MQ_ERR_INVALID_ARGUMENT;
}
buffer = (uint8_t *)g_host->alloc(g_host->host_data, len);
if (buffer == NULL) {
return MQ_ERR_OUT_OF_MEMORY;
}
memcpy(buffer, json, len);
out->data = buffer;
out->len = len;
return MQ_OK;
}
static int32_t emit_error(const char *code, const char *message,
MqOwnedBytes *out, int32_t failure_code) {
char json[512];
int written = snprintf(
json, sizeof(json),
"{\"wire_version\":1,\"kind\":\"response\",\"error\":"
"{\"kind\":\"invoke\",\"code\":\"%s\",\"message\":\"%s\"}}",
code, message);
if (written < 0 || (size_t)written >= sizeof(json)) {
return MQ_ERR_INTERNAL;
}
if (emit(json, (size_t)written, out) != MQ_OK) {
return MQ_ERR_OUT_OF_MEMORY;
}
/* Non-zero: the invocation failed even though an error envelope was
* written. The host reads the envelope for the structured error. */
return failure_code;
}
/* Optional hot-path ABI backend for pure math algorithms. */
static int32_t math_backend_add(MqCallContext *ctx, MqBytes args_wire,
MqOwnedBytes *result_wire, MqOwnedBytes *error_wire) {
char *json;
long long a = 0;
long long b = 0;
long long sum;
char response[160];
int written;
(void)ctx;
if (result_wire == NULL || error_wire == NULL) {
return MQ_ERR_INVALID_ARGUMENT;
}
*result_wire = (MqOwnedBytes){NULL, 0};
*error_wire = (MqOwnedBytes){NULL, 0};
if (args_wire.data == NULL || args_wire.len == 0) {
return emit_error("bad_arguments", "request wire is empty", error_wire,
MQ_ERR_INVALID_ARGUMENT);
}
if (args_wire.len > MQ_MAX_REQUEST_WIRE_BYTES) {
return emit_error("request_too_large", "request wire is too large",
error_wire, MQ_ERR_INVALID_ARGUMENT);
}
json = (char *)malloc(args_wire.len + 1);
if (json == NULL) {
return emit_error("out_of_memory", "plugin could not copy request",
error_wire, MQ_ERR_OUT_OF_MEMORY);
}
memcpy(json, args_wire.data, args_wire.len);
json[args_wire.len] = '\0';
if (read_int_argument(json, "a", &a) != 0 ||
read_int_argument(json, "b", &b) != 0) {
free(json);
return emit_error("bad_arguments",
"math_backend.add requires Int arguments `a` and `b`",
error_wire, MQ_ERR_INVALID_ARGUMENT);
}
free(json);
#ifdef MQ_SOLVER_CRASH
/* Test-only crash injection for isolated-worker crash tests. */
abort();
#endif
if (__builtin_add_overflow(a, b, &sum)) {
return emit_error("integer_overflow", "math_backend.add overflowed i64",
error_wire, MQ_ERR_INTERNAL);
}
written = snprintf(
response, sizeof(response),
"{\"wire_version\":1,\"kind\":\"response\",\"value\":"
"{\"type\":\"int\",\"decimal\":\"%lld\"}}",
sum);
if (written < 0 || (size_t)written >= sizeof(response)) {
return MQ_ERR_INTERNAL;
}
return emit(response, (size_t)written, result_wire);
}
#ifdef MQ_SOLVER_MULTI_EXPORT
/* Test-only second export: `math_backend.neg`, used to prove complete-name routing
* (ADR-0010). It is not part of the default demo manifest. */
static int32_t math_backend_neg(MqCallContext *ctx, MqBytes args_wire,
MqOwnedBytes *result_wire, MqOwnedBytes *error_wire) {
char *json;
long long a = 0;
char response[160];
int written;
(void)ctx;
if (result_wire == NULL || error_wire == NULL) {
return MQ_ERR_INVALID_ARGUMENT;
}
*result_wire = (MqOwnedBytes){NULL, 0};
*error_wire = (MqOwnedBytes){NULL, 0};
if (args_wire.data == NULL || args_wire.len == 0) {
return emit_error("bad_arguments", "request wire is empty", error_wire,
MQ_ERR_INVALID_ARGUMENT);
}
json = (char *)malloc(args_wire.len + 1);
if (json == NULL) {
return emit_error("out_of_memory", "plugin could not copy request",
error_wire, MQ_ERR_OUT_OF_MEMORY);
}
memcpy(json, args_wire.data, args_wire.len);
json[args_wire.len] = '\0';
if (read_int_argument(json, "a", &a) != 0) {
free(json);
return emit_error("bad_arguments", "math_backend.neg requires Int `a`",
error_wire, MQ_ERR_INVALID_ARGUMENT);
}
free(json);
written = snprintf(
response, sizeof(response),
"{\"wire_version\":1,\"kind\":\"response\",\"value\":"
"{\"type\":\"int\",\"decimal\":\"%lld\"}}",
-a);
if (written < 0 || (size_t)written >= sizeof(response)) {
return MQ_ERR_INTERNAL;
}
return emit(response, (size_t)written, result_wire);
}
#endif
/* Required ABI v1 entry point. */
int32_t mq_plugin_entry_v1(const MqHostApi *host, MqPluginApi *plugin) {
MqBytes export_name;
MqBytes signature_wire;
int32_t code;
if (host == NULL || plugin == NULL) {
return MQ_ERR_INVALID_ARGUMENT;
}
if (host->struct_size < sizeof(MqHostApi)) {
return MQ_ERR_ABI_MISMATCH;
}
if (host->abi_major != MQ_ABI_MAJOR) {
return MQ_ERR_ABI_MISMATCH;
}
if (host->alloc == NULL || host->free == NULL ||
host->register_function == NULL || host->request_capability == NULL) {
return MQ_ERR_ABI_MISMATCH;
}
g_host = host;
/* The host pre-fills struct_size; keep it and report our ABI version. */
plugin->struct_size = (uint32_t)sizeof(MqPluginApi);
plugin->abi_major = MQ_SOLVER_REPORT_ABI_MAJOR;
plugin->abi_minor = MQ_ABI_MINOR;
plugin->plugin_metadata_wire.data = (const uint8_t *)PLUGIN_METADATA;
plugin->plugin_metadata_wire.len = sizeof(PLUGIN_METADATA) - 1;
export_name.data = (const uint8_t *)"math_backend.add";
export_name.len = sizeof("math_backend.add") - 1;
signature_wire.data = (const uint8_t *)SIGNATURE_ADD;
signature_wire.len = sizeof(SIGNATURE_ADD) - 1;
code = host->register_function(host->host_data, export_name, signature_wire,
math_backend_add);
if (code != MQ_OK) {
return code;
}
#ifdef MQ_SOLVER_MULTI_EXPORT
export_name.data = (const uint8_t *)"math_backend.neg";
export_name.len = sizeof("math_backend.neg") - 1;
signature_wire.data = (const uint8_t *)"{\"signature\":\"($a: Int) -> Int\"}";
signature_wire.len = sizeof("{\"signature\":\"($a: Int) -> Int\"}") - 1;
code = host->register_function(host->host_data, export_name, signature_wire,
math_backend_neg);
if (code != MQ_OK) {
return code;
}
#endif
return MQ_OK;
}
+20
View File
@@ -0,0 +1,20 @@
# Example optional ABI math backend (plugin ABI v1).
#
# Installing this package never grants permissions. `math.compute` is a capability
# category for a compute backend, not a promise that the core ships a solver.
# Replace target/sha256 with the host-built artifact values (build.sh writes the
# generated manifest into build/plugin.yaml).
plugin:
name: math.backend
version: 0.1.0
abi: "^1.0"
kind: native
exports:
- name: math_backend.add
signature: "($a: Int, $b: Int) -> Int"
requires:
- math.compute
artifacts:
- target: x86_64-unknown-linux-gnu
file: math_backend.so
sha256: "0000000000000000000000000000000000000000000000000000000000000000"
+10
View File
@@ -0,0 +1,10 @@
---
import:
math: "./math-library/index.mq.md"
---
# @knowledge 数学消费者
## @exec main
`return math.最大公约数(甲=48, 乙=18)`
+13
View File
@@ -0,0 +1,13 @@
# Example pure math library
A `.mq.md` package that provides math algorithms with ordinary language
functions only. It needs no host `math.*` builtin, no ABI plugin and no core
change.
```bash
marqdo call ../math-library-demo.mq.md main
# 6
```
For an optional accelerated backend, see `../math-backend/`; the library itself
does not require it.
+23
View File
@@ -0,0 +1,23 @@
# @knowledge 数学算法
以下函数是纯 Marqdo 算法,不依赖已移除的宿主 `math.*` 内核。
## @exec 最大公约数
欧几里得算法,非负整数输入。参数以 `甲`、`乙` 传入,返回最大公约数。
`a = 甲`
`b = 乙`
`while b != 0`
`余数 = a % b`
`a = b`
`b = 余数`
`end`
`return a`
+5
View File
@@ -0,0 +1,5 @@
project:
name: marqdo-math-library
version: 0.1.0
marqdo: ">=3.0.0-beta.1,<4.0.0"
dependencies: {}
+2 -2
View File
@@ -8,8 +8,8 @@ $$
## @exec 计算圆面积 ## @exec 计算圆面积
依据[圆面积公式](#圆面积公式)代入半径。 依据[圆面积公式](#圆面积公式),用纯 Marqdo 数字面量近似 π 并计算 r = 4 时的面积。
`面积 = math.eval(ref("#圆面积公式"), {"r": 4}, target="A")` `面积 = 3.141592653589793 * 4 * 4`
`return 面积` `return 面积`
+3 -1
View File
@@ -2,7 +2,9 @@
`params(r: Number)` `params(r: Number)`
`return math.eval(ref("#公式"), {"r": r}, target="A")` 纯语言算术使用近似 π;公式仅作为惰性 Markdown 资源保留。
`return 3.141592653589793 * r * r`
### @knowledge 公式 ### @knowledge 公式
+3 -1
View File
@@ -10,6 +10,8 @@ $$
## @exec 计算作用力 ## @exec 计算作用力
`力 = math.eval(ref("#牛顿第二定律"), {"m": 2, "a": 3}, target="F")` 公式保持惰性;这里用纯语言算术演示 m = 2、a = 3。
`力 = 2 * 3`
`return 力` `return 力`
+19
View File
@@ -203,3 +203,22 @@ Analysis schema change; `schema_version` stays 2.
* `analysis_v2_projects_addressable_formula_and_code_resources` * `analysis_v2_projects_addressable_formula_and_code_resources`
* `failed_check_removes_stale_analysis` * `failed_check_removes_stale_analysis`
* `tests/consumers/analysis_consumer.py` (independent Python consumer) * `tests/consumers/analysis_consumer.py` (independent Python consumer)
## 8. Versioning and future heading metadata
`units[]` keeps its v2 fields and semantics: `id/kind/name/level/span/function`.
The effective core mode and origin of a `section` unit are deliberately **not**
added to v2, and neither are heading annotations.
The language still has exactly two Core Modes (`@exec`/`@knowledge`); unmarked
headings inherit from the nearest ancestor and the root default is Knowledge
(`spec/mapping.md` §1.2, including the H-06 sibling fix). A future declarative,
metadata-only Heading Annotation index is Proposed under
[ADR-0060](../docs/adr/0060-heading-modes-and-extensible-annotations.md) and is
**not implemented in this build**.
When that work ships (target `3.1.x`), it must use a new protocol version
(Analysis v3) or a separate `heading-annotations.v1` sidecar, bound to both the
source digest and the exact Analysis bytes digest; it must not rewrite v2 `units[]`.
Consumers that only know v2 must keep passing the existing schema/version contract,
and must reject an unknown sidecar/v3 version rather than silently ignoring it.
+12 -10
View File
@@ -65,7 +65,7 @@ In this exact order; the first applicable step decides:
then unique local name). A missing function is `symbol.unknown`; it never then unique local name). A missing function is `symbol.unknown`; it never
falls back to a builtin or plugin with the same dotted spelling. falls back to a builtin or plugin with the same dotted spelling.
3. **Builtin dotted namespace.** Otherwise, an exact builtin 3. **Builtin dotted namespace.** Otherwise, an exact builtin
`alias.f` (for example `math.eval`) binds `Builtin`. `alias.f` (for example `resource.request`) binds `Builtin`.
4. **Exact plugin export.** Otherwise, if a selected static plugin declares the 4. **Exact plugin export.** Otherwise, if a selected static plugin declares the
complete name `alias.f`, the site binds that export. The manifest signature complete name `alias.f`, the site binds that export. The manifest signature
is validated here; no library is loaded. is validated here; no library is loaded.
@@ -207,42 +207,44 @@ is internal-only — the public wire code remains `capability.unavailable`.
```markdown ```markdown
--- ---
import: import:
mymath: "./math.mq.md" numerics: "./math.mq.md"
--- ---
## @exec main ## @exec main
`return mymath.eval(a=1)` `return numerics.最大公约数(甲=48, 乙=18)`
``` ```
Binds `Marqdo { function: <package instance>::math.mq.md::eval }` in both Binds `Marqdo { function: <package instance>::math.mq.md::最大公约数 }` in both
`check` and `run`. `check` and `run`. The historical `math.*` builtin namespace was removed
(ADR-0061), so a `math:` import alias no longer conflicts with a builtin.
### 8.2 Builtin without an import ### 8.2 Builtin without an import
```markdown ```markdown
## @exec main ## @exec main
`return math.eval(ref("#公式"), {"r": 2}, target="A")` `return resource.request("clock.now", [])`
``` ```
Binds `Builtin { canonical_name: "math.eval" }`. Binds `Builtin { canonical_name: "resource.request" }`.
### 8.3 Import namespace conflict ### 8.3 Import namespace conflict
```markdown ```markdown
--- ---
import: import:
math: "./math.mq.md" resource: "./resource.mq.md"
--- ---
## @exec main ## @exec main
`return math.eval(a=1)` `return resource.request("clock.now", [])`
``` ```
`check` fails with `ext.import_namespace_conflict`; `run` refuses before `check` fails with `ext.import_namespace_conflict`; `run` refuses before
executing anything. Rename the alias. executing anything. Rename the alias. Removed builtins such as `math.eval` are no
longer reserved names: a conflicting alias is now impossible for that namespace.
### 8.4 Plugin export ### 8.4 Plugin export
+1 -1
View File
@@ -369,7 +369,7 @@ host boundary. Names are stable; adding one requires a spec update.
| `resource.close` | `(handle) -> Result` | releases the host slot | | `resource.close` | `(handle) -> Result` | releases the host slot |
| `resource.accept` | `(listener) -> Result` | accepts one TCP connection from a `tcp-listener` handle (ADR-0047) | | `resource.accept` | `(listener) -> Result` | accepts one TCP connection from a `tcp-listener` handle (ADR-0047) |
| `resource.request` | `(operation: Text, arguments: List) -> Result` | non-streaming `fs.*` operations (ADR-0041) `clock.now` (ADR-0042), `env.get` (ADR-0043), `process.run` (ADR-0044) and `random.bytes` (ADR-0046); project-mode and grant-checked | | `resource.request` | `(operation: Text, arguments: List) -> Result` | non-streaming `fs.*` operations (ADR-0041) `clock.now` (ADR-0042), `env.get` (ADR-0043), `process.run` (ADR-0044) and `random.bytes` (ADR-0046); project-mode and grant-checked |
| `math.parse/eval/substitute` | see `spec/math.md` | P5; `math.simplify`/`math.differentiate` are declared but return `math.unsupported` in this build | | ~~`math.*`~~ | see `spec/math.md` | **removed after `3.0.0-beta.1`** (ADR-0061): a call is a static `symbol.unknown`; algorithms live in pure `.mq.md` packages or an explicitly selected ABI backend. `Formula` resources stay inert. |
| `foreign.run/call` | see `spec/foreign.md` | P5, capability-gated | | `foreign.run/call` | see `spec/foreign.md` | P5, capability-gated |
| `fs.read/write` | see `spec/security.md` | capability-gated | | `fs.read/write` | see `spec/security.md` | capability-gated |
+23
View File
@@ -274,3 +274,26 @@ text preserved; a successful process whose stdout is not a typed value is also
* Sessions, shared state, persistent kernels and automatic environment * Sessions, shared state, persistent kernels and automatic environment
management (uv/venv) are not implemented. Python/Node are optional foreign management (uv/venv) are not implemented. Python/Node are optional foreign
kernels, never the official execution backend. kernels, never the official execution backend.
## 8. F-A transition status (ADR-0063)
The permission-gated one-shot `foreign.run`/`foreign.call` and the dynamic
`KernelRegistry` are the **controlled OS-boundary primitive** retained by the core
(F-A). Removing them (F-B) is deferred until a versioned generic
process/worker-capability contract exists with program/argv, controlled stdio,
isolation level, timeout/process-tree reaping, output budget, environment identity,
lifecycle and cancellation semantics, plus frozen-binary equivalence and the same
security negatives.
- No new language-specific builtin or `HostOp` may be added; new languages
register through `KernelRegistry::register`. Built-in Python/Node descriptors are
defaults, not the only extension channel.
- High-level sequencing/batching/validation/error normalization belongs in a
`.mq.md` package that composes explicit `foreign.*` calls, never in the host.
- The existing authorization model is unchanged: without `--allow-foreign` the call
is `permission.denied`; `pure`/`strict` fail closed; the file/digest/target/
timeout/wire/output-limit/environment negatives in this spec and the test suites
remain authoritative and must not be skipped for a refactor.
- Forbidden in both phases: persistent Python/Node sessions, Notebook-cell
execution, `@python` heading auto-execution, and a second foreign runtime in View.
Streaming stays in Execution Events v1, not a second foreign network protocol.
+178
View File
@@ -0,0 +1,178 @@
# Heading Annotations v1 — PROPOSED, NOT IMPLEMENTED
Status: **Proposed. The current build does not implement heading annotations.**
The parser still recognises only the closed Core Modes `@exec` and `@knowledge`;
any other leading `@name` is a hard `sem.invalid_mode_marker` and there is no
`annotation.unknown` code in the current binary. This page is a future contract
accepted by [ADR-0060](../docs/adr/0060-heading-modes-and-extensible-annotations.md)
and targeted at `3.1.x` (Step B). Nothing here may be advertised as available
until Step B ships with its own evidence.
Audience: Markdown/frontend implementers, Analysis v3/sidecar implementers, and
future View/Test/Prove tools. Current language semantics are in
[`mapping.md`](mapping.md) and cannot be changed by this proposal.
## 1. Two layers
```text
ATX heading first plain-Text prefix
├── Core Mode closed: @exec | @knowledge (decides execution)
├── Heading Annotations open: @namespace.identifier … (metadata only)
└── semantic_title non-empty plain heading text (FunctionId/anchors)
```
An annotation **never** decides whether a section executes. The Core Mode does.
Unmarked headings inherit the nearest ancestor mode; annotations do not participate
in that calculation.
## 2. Grammar (v1)
```ebnf
heading_prefix = [ core_mode, whitespace ], { annotation, whitespace }, semantic_title ;
core_mode = "@exec" | "@knowledge" ;
annotation = "@", namespace, ".", identifier ;
namespace = lower_identifier, { ".", lower_identifier } ;
identifier = lower_identifier, { "-" | "_" | digit | letter } ;
semantic_title = nonempty_plain_heading_text ;
lower_identifier = lower_letter, { lower_letter | digit } ;
```
Example (future syntax, not accepted by the current CLI):
```markdown
# @knowledge 算法手册
## @exec @org.example.test 最大公约数
`params(a: Int, b: Int)`
`return a`
## @knowledge @org.example.fold 实现说明
说明正文。
```
`semantic_name` is the normalized title after removing the accepted prefix
tokens; it alone feeds FunctionId and anchors. Byte spans of the source are
unchanged and existing `@exec` documents keep the same semantic name.
## 3. Constraints
1. No annotation parameters in v1. No Python decorator expression, parentheses
evaluation or JSON inside a heading. Parameters, if ever needed, use a separate
declared table/metadata revision.
2. At most one Core Mode, and it must come before any annotation. `@exec` +
`@knowledge` together is a hard core-mode conflict. There is no third mode.
3. Annotation names are namespaced (`@org.example.test`); an unqualified global
`@test` that any tool may claim is forbidden.
4. Annotations never participate in mode inheritance. v1 attaches to the heading
only.
5. `display_title` (render text) and `semantic_name` (identity) are distinct.
6. The parser extracts tokens by fixed grammar and **never executes annotation
provider code**; a static manifest validates whether an annotation is allowed.
7. Undeclared annotations produce a deterministic static error
(`annotation.unknown`); body prose may still discuss `@foo`; a heading-title
escape must be specified and tested (for example an explicit escape token).
8. Unknown Core Mode spellings (`@Exec`) remain errors and are never re-read as a
third-party annotation.
9. An annotation may not add callability, change the AST/IR, reorder execution,
reduce budgets, grant capability, load native code or change a bound call.
Runtime ignores annotations completely.
10. Repositories using only `@exec`/`@knowledge` keep byte-identical parse
behaviour. The H-06 sibling-mode bugfix is a separate language bugfix and is
recorded in `spec/mapping.md` §1.2.
## 4. Registration manifest (proposal)
```json
{
"schema": "marqdo.heading-annotations",
"schema_version": 1,
"owner": "org.example",
"annotations": [
{
"name": "org.example.test",
"allowed_modes": ["exec"],
"heading_levels": [2],
"repeatable": false,
"metadata_only": true
},
{
"name": "org.example.fold",
"allowed_modes": ["exec", "knowledge"],
"heading_levels": [2, 3, 4, 5, 6],
"repeatable": false,
"metadata_only": true
}
]
}
```
- The manifest is a non-executable resource of an explicitly declared,
version-pinned project/dependency package; `marqdo.yaml` references it and its
identity is covered by the lock/project snapshot digest.
- Duplicate ownership/name, unknown schema version and tampered content fail
statically; the manifest never runs code.
- Do **not** silently add a fourth `ExtensionKind` to lock v4. Prefer the manifest
as a locked non-executable resource; a lock top-level annotation record requires
a lock protocol version bump and migration tests.
## 5. Analysis projection (future, versioned)
Analysis v2 `units[]` keeps `id/kind/name/level/span/function` unchanged. Future
metadata uses Analysis v3 or a `heading-annotations.v1` sidecar, for example:
```json
{
"schema": "marqdo.heading-annotations-sidecar",
"schema_version": 1,
"source_digest": "sha256:<64 hex>",
"analysis_digest": "sha256:<64 hex>",
"units": [
{
"unit_id": "root:pkg@0.1.0::doc.mq.md#ns/unit",
"function_id": "root:pkg@0.1.0::doc.mq.md::ns.f",
"effective_mode": "exec",
"mode_origin": "inherited",
"annotations": [
{"name": "org.example.test", "owner": "org.example", "manifest_digest": "sha256:<64 hex>"}
],
"span": {"start": 10, "end": 20}
}
]
}
```
The sidecar is bound to both the source digest and the Analysis bytes digest;
a consumer must reject a stale pairing. No private IR is required.
## 6. Security prohibitions
- An annotation cannot grant a file/network/process capability; grants stay in
the existing capability flow.
- An annotation cannot flip `@knowledge` to `@exec`, add a callable, load native
code or change a CallBinding.
- A consumer without the tool (View/Test/Prove) still runs `check`/`run`
deterministically; results do not depend on installed tools.
- `pure`/`strict` continue to reject execution extensions; annotations are static
data only.
## 7. Acceptance matrix (FUTURE, enable only after Step B)
| ID | Input/action | Expected |
|---|---|---|
| T-ANNO-01 | `## @exec @org.example.test f` | Function name is still `f`; static annotation is readable |
| T-ANNO-02 | Valid annotation on a Knowledge heading | Not callable, not executed |
| T-ANNO-03 | Undeclared annotation | Static `annotation.unknown` |
| T-ANNO-04 | Forged/digest-mismatched manifest | Fails at `check`; third-party code never runs |
| T-ANNO-05 | Duplicate/conflicting/level-illegal annotation | Static error with stable code/span |
| T-ANNO-06 | Annotation present, Test Tool absent | Execution result identical |
| T-ANNO-07 | Install/uninstall tool, same source/lock/CLI | Runtime IR and function results unchanged |
| T-ANNO-08 | `@exec @knowledge` together | Fixed core-mode conflict |
| T-ANNO-09 | Annotation tries to grant file permission | Impossible; still denied without a grant |
| T-ANNO-10 | Real Unicode Chinese title | Source spans match Markdown AST bytes |
| T-ANNO-11 | Sidecar paired with another source SHA | Consumer rejects stale metadata |
Until Step B is executed and evidenced, docs/STATUS must label this
**Proposed/not implemented** and no test row above is a PASS.
+6 -1
View File
@@ -92,7 +92,12 @@ Inheritance is a structural calculation over heading levels, not inference from
prose. A heading's scope ends at the next heading of the same or higher level prose. A heading's scope ends at the next heading of the same or higher level
(same or smaller number); deeper headings are inside it. Siblings never share a (same or smaller number); deeper headings are inside it. Siblings never share a
mode: an unmarked heading after a sibling that explicitly switched to Knowledge mode: an unmarked heading after a sibling that explicitly switched to Knowledge
still inherits from the nearest **ancestor**, not from the sibling. still inherits from the nearest **ancestor**, not from the sibling. Mechanically,
the ancestor stack is first reduced by removing the heading itself and every heading
of the same or higher level; only then is `Mode(nearest ancestor)` read. A
post-`3.0.0-beta.1` bugfix (RFC-EXT-0003 H-06) corrected an implementation
that read the inherited mode before reducing the stack, which could leak a sibling's
mode into an unmarked heading.
Skipped levels (H1 directly followed by H3) still use the nearest valid Skipped levels (H1 directly followed by H3) still use the nearest valid
ancestor heading. ancestor heading.
+75 -209
View File
@@ -1,230 +1,96 @@
# Marqdo Math v1 # Math: core value and removed domain API
Status: **frozen subset (math v1)**; product baseline `3.0.0-beta.1`. The kernel computes numbers; it never proves Status: **the `math.*` builtin API was removed from the core after
theorems. `math.simplify` and `math.differentiate` are **not implemented** in `3.0.0-beta.1`** by [ADR-0061](../docs/adr/0061-detach-domain-math-kernel-from-core.md)
this build. (RFC-EXT-0003 H-01). This page documents what the core keeps, what it removed,
and how consumers migrate. It is not a contract for any external `marqdo-math`
package; that package owns its own function names and behaviour.
Implementation: `crates/marqdo-math` (`parse`, `evaluate`, `substitute`, ## 1. What stays in the core
`MathError`), host adapter `crates/marqdo-host/src/kernels.rs::math`, builtin
metadata `crates/marqdo-ir/src/builtins.rs`, tests
`crates/marqdo-math/tests/kernel.rs`.
## 1. From Markdown to a value - `Int` and `Float` literals and ordinary `+ - * / // %` arithmetic, comparison
and pure language control flow.
- A Markdown `$$...$$` block remains an inert `Formula` resource in Analysis
v2 `resources[]`; the core never evaluates it.
- The `math.compute` capability name remains a **capability category** that an
explicitly selected ABI plugin may request (ADR-0062, H-11). The core hosts no
math solver, parser or evaluator behind it.
A `math` / `math_block` node is an **inert document resource**, never an Every other math algorithm belongs to a pure `.mq.md` package (preferred) or an
operation. The frontend attributes every formula to its innermost enclosing explicitly selected Plugin ABI backend for a hot path.
heading unit (`crates/marqdo-frontend/src/resources.rs`). `ref("#heading")`
returns a `Formula` value only when that unit contains exactly one resource; ## 2. Removed builtins
with two or more formulas the runtime raises `ref.ambiguous` and refuses to
pick one (`spec/references.md` §5, ADR-0003). The following `Builtin` names, `HostOp` variants and runtime arms no longer exist:
| Removed builtin | Previous behaviour |
|---|---|
| `math.parse` | Parse a formula resource into a `Formula` value |
| `math.eval` | Evaluate a formula with bindings |
| `math.substitute` | Substitute bindings into a formula |
| `math.simplify` | Host simplification (returned `math.unsupported`) |
| `math.differentiate` | Host differentiation (returned `math.unsupported`) |
A document that still calls one of them now fails **statically** with
`symbol.unknown` at `check`/`run`/`call`; there is no silent fallback to the old
host kernel and no `math.unsupported` runtime branch. `ref("#公式")` still resolves
the inert `Formula` resource, but no core builtin consumes it for math.
## 3. Migration
Use explicit pure functions and ordinary arithmetic. A pure library can expose a
namespaced function:
```markdown ```markdown
# @knowledge 数学 # @knowledge 数学算法
## @knowledge 圆面积公式 ## @exec 最大公约数
$$ `a = 甲`
A = \pi r^2
$$
## @exec 计算圆面积 `b = 乙`
`params(r: Number)` `while b != 0`
`面积 = math.eval(ref("#圆面积公式"), {"r": r}, target="A")` `余数 = a % b`
`return 面积`
`a = b`
`b = 余数`
`end`
`return a`
``` ```
Nothing is evaluated by reading or rendering the document. `math.*` must be Consumer:
called explicitly and the host checks the `math` capability at execution time
(default: granted in `pure`/`project`; there is no CLI flag to revoke it today).
## 2. Grammar ```yaml
---
The parser accepts exactly this LaTeX subset (whitespace insignificant; byte import:
offsets are reported for parse errors): math: "./math-library/index.mq.md"
---
```text
formula = expr [ "=" expr ] ; single '=' only, never assignment
expr = term { ("+" | "-") term } ;
term = unary { ("*" | "/" | "·" | "×" | implicit) unary } ;
unary = ("+" | "-") unary | power ;
power = primary [ "^" unary ] ; right associative
primary = number
| identifier Unicode letter (plus digits/underscore)
| "\pi" | "pi" | "\e" | "e" constants
| "(" expr ")" | "\left(" expr "\right)"
| "{" expr "}" grouping
| "\frac{" expr "}{" expr "}" exact division
| "\sqrt{" expr "}" real square root
;
number = digits [ "." digits ] | "." digits ; decimal, no exponent form
``` ```
Rules and edge cases: ```markdown
## @exec main
* `\cdot` and `\times` are accepted as synonyms for `*`. `return math.最大公约数(甲=48, 乙=18)`
* Implicit multiplication between adjacent factors: `2x`, `\pi r^2`, `(a)(b)`, ```
`m a`. Concatenated letters form one identifier (`ma` is the variable `ma`;
write `m a` or `m * a` for a product). Two adjacent number literals are a
parse error ("ambiguous").
* Unicode identifiers are supported (`面积`, `r`, `速度`). Plain multi-letter
identifiers are variables, but names of common elementary functions (`sin`,
`cos`, `log`, `exp`, ...) are reserved and rejected as unsupported so
`sin(x)` is not silently read as a product.
* Underscores are ordinary identifier characters: `x_1` is the variable `x_1`,
not a subscript.
* A single top-level `=` creates an `Equation { left, right }`; it is **not**
assignment and never writes a Marqdo binding. A second `=` is a parse error.
* `\frac{a}{b}` is exact division (`Div`); `1.5 + 2.5` is an exact rational
computation, not binary floating point.
* `\sqrt{x}` is real-valued: a negative radicand is a `Type` error.
* Decimal literals have no exponent form (`1e3` is rejected); `2e` is
`2 * e` (number times the constant), while `2e3` is rejected rather than
reinterpreted.
### 2.1 Unsupported constructs This needs no core change, no ABI and no CLI rebuild. The `math` import alias
is available again because the historical `math.*` builtin namespace no longer
reserves it (`ext.import_namespace_conflict` no longer applies to `math`).
Everything outside the grammar is a structured `Unsupported` or `Parse` error: For a high-performance algorithm, add an explicitly selected Plugin ABI v1 export
matrices, sums/integrals, function applications (`\sin`, `\cos`, ...), (for example `math_backend.add`) with a static signature and require
multi-letter commands, `\left[`/`\right]`, mismatched/missing braces, `--trust-native-plugin` for in-process execution plus `--allow-plugin NAME` for the
scientific notation, commas, arrays, subscripts, superscript commands other grant; without the manifest the call is `symbol.unknown`, without the grant it is
than the `^` operator, `\frac`/`\sqrt` without braced arguments, labels, `permission.denied`. See `examples/math-backend/`.
alignment characters, line breaks. There is no `simplify`, `differentiate`,
`integrate`, `matrix` or theorem/proof operation in this build.
## 3. Numeric semantics ## 4. What must not come back
* Exact rational arithmetic uses `num-rational::Ratio` over the - No new domain function may be added to `BUILTINS`, `HostOp` or
`num-bigint::BigInt` type that also backs `Value::Int`; integers are `Host::resource_request` to emulate the removed API (ADR-0062).
arbitrary precision. - No `Value` variant or Analysis resource kind is added for math.
* Decimal literals are exact rationals (`0.25` = `1/4`). `Int` bindings become - No compatibility parser for the old `math.*` spelling.
exact integers. `Float` bindings are interpreted as the **exact binary
rational value** of the `f64`; non-finite `Float` bindings are a `Type`
error.
* `+ - * / ^` are exact when both operands are exact. Division keeps a
rational, so `\frac{1}{3} * 3` is exactly `1`.
* The final value is a Marqdo `Int` exactly when the exact result is an
integer, and a `Float` otherwise (`crates/marqdo-math/src/eval.rs`, the
`Numeric` enum). Examples: `1.5 + 2.5` → `Int(4)`; `1 / 2` → `Float(0.5)`;
`100 / 4` → `Int(25)`.
* `\pi`, `\e` and a `\sqrt` of a non-perfect square introduce an `f64`
approximation. Anything derived from them is a `Float`. Precision follows
IEEE-754 binary64 (about 15–17 significant decimal digits); approximate
results are never presented as exact.
* `\sqrt` of a perfect square of an exact rational stays exact (`\sqrt{4}` →
`Int(2)`); `\sqrt{1/4}` is `Float(0.5)` in this build (it becomes
approximate via the root path, matching the documented test).
* The exponent of `^` must evaluate to an integer. Magnitude is bounded by
`MAX_EXPONENT`. Negative integer exponents are exact reciprocals (the result
is therefore a `Float` unless it is integral). `0 ^ 0` is a `Type` error.
* Exact intermediate/result numerators and denominators are bounded by
`MAX_RESULT_BITS`; exceeding the bound returns a structured `Unsupported`
error rather than hanging or exhausting memory.
* Division by zero is a `Type` error inside the kernel. The host maps all
`MathErrorKind::Type` to `runtime.type`; it does **not** produce
the interpreter's `runtime.division_by_zero` code for a formula. This is a
known divergence from the module doc comment in
`crates/marqdo-math/src/lib.rs` and should be fixed or documented in an ADR.
* Constants are reserved: a binding named `pi` or `e` never overrides the
constant, and they cannot be solve targets (use `E`, `x`, `r`, ...).
### 3.1 Bounds
| Constant | Value | Location |
|---|---|---|
| `MAX_SOURCE_BYTES` | 1,000,000 | `crates/marqdo-math/src/parse.rs` |
| `MAX_PARSE_DEPTH` | 256 | parse.rs |
| `MAX_AST_NODES` | 512 | parse.rs |
| `MAX_EXPONENT` | 10,000 | `crates/marqdo-math/src/eval.rs` |
| `MAX_RESULT_BITS` | 1,000,000 | eval.rs |
The AST-node bound also bounds later recursion for long operator chains, so
hostile input cannot overflow the stack during evaluation, rendering or
substitution. No code path panics on untrusted LaTeX; all failures are
`MathError`.
## 4. Equations and solving a target
`FormulaKind` is `Expression(expr)` or `Equation { left, right }`.
`evaluate(formula, bindings, target)`:
* for a plain expression, `target` must be `None`; supplying one is
`Unsupported` ("a target variable is only meaningful for an equation");
* for an equation, `target` is required (`Unsupported` otherwise); an empty
target is `Unsupported`;
* the target must occur **exactly once** and the equation must be **affine in
the target**. Other variables are substituted from `bindings` first; a
missing binding is `UndefinedVariable`.
Affine solving supported by `crates/marqdo-math/src/eval.rs`:
* `+`, `-`, multiplication by a target-free side, division where the target is
in the numerator, and inversion of those operations in either direction:
`2x = 4`, `4 = 2x`, `x / 2 = 3`, `3 = x / 2`, `x + 2 = 5`, `2x + 1 = 7`,
`(x + 1) * 2 = 8`, `x = 2y + 1` (with `y` bound);
* `F = m a` solved for `F`, `m` or `a`.
Rejected as `Unsupported`: target occurs zero times or more than once, target
in a denominator, under a root, in an exponent, or in a non-affine product
(e.g. `x * x`). Equations never mutate bindings and never create Marqdo
variables.
## 5. Substitution
`substitute(formula, bindings)` replaces bound variables with exact numeric
literals and keeps unbound variables symbolic. The returned `Formula.source` is
a deterministic canonical rendering that `parse` accepts again; it is not
byte-identical to the input formatting. Host-facing `math.substitute` wraps the
result in a `Formula` value with `unit: None`, `display: false`, span of the
call site.
## 6. Host-facing surface (`math.*`)
All operations are builtins in `crates/marqdo-ir/src/builtins.rs`, dispatched
in `crates/marqdo-runtime/src/builtins_impl.rs`, and executed in the host
adapter `crates/marqdo-host/src/kernels.rs`. `math` capability is checked
before touching the kernel.
| Builtin | Parameters | Result |
|---|---|---|
| `math.parse` | `formula: Formula or Text` | `Formula` (source = input; `unit=None`, `display=false`); parse errors are `math.unsupported` |
| `math.eval` | `formula: Formula or Text`, `bindings: Map`, optional `target: Text` | `Int` or `Float`; equation requires target |
| `math.substitute` | `formula: Formula or Text`, `bindings: Map` | `Formula` with canonical source |
| `math.simplify` | `formula` | **not implemented**: runtime error `math.unsupported` ("not part of the supported math subset in this build") |
| `math.differentiate` | `formula`, `变量` | **not implemented**: `math.unsupported` |
Input typing:
* formula arguments accept a `Formula` value or `Text`; anything else is
`runtime.type`;
* `bindings` must be a `Map` whose values are `Int` or `Float`; any other
value type is `runtime.type` with a message naming the binding;
* `target` must be `Text` or `None`; other types are `runtime.type`;
* builtin arity/parameter-name mistakes are catchable statically
(`call.arity`, see `spec/mapping.md` §6);
* the math kernel is a pure computation: no file, network, process or plugin
effects, and nothing it returns is a capability.
### 6.1 Error mapping
Host mapping (`crates/marqdo-host/src/kernels.rs::math_error`):
| `MathErrorKind` | Runtime code |
|---|---|
| `Parse` | `math.unsupported` (message includes the byte offset when known) |
| `Unsupported` | `math.unsupported` |
| `UndefinedVariable` | `symbol.unknown` |
| `Type` | `runtime.type` |
## 7. What this is not
* Not a computer-algebra system: no simplification, differentiation,
integration, matrices, series, assumptions, units or symbolic rewriting.
* Not a theorem prover: `F = m a` is an equation value, not a proof, and a
numeric solve is not a certificate.
* Not a LaTeX renderer: rendering is the Markdown reader's job; the kernel only
receives the raw `latex` text of a `math` node.
* Not error-free in the floating-point sense: approximation precision is
documented, not guaranteed beyond binary64.
+6 -5
View File
@@ -292,14 +292,15 @@ $$
## @exec 计算圆面积 ## @exec 计算圆面积
`params(r: Number)` `面积 = ref("#圆面积公式")`
`面积 = math.eval(ref("#圆面积公式"), {"r": r}, target="A")`
`return 面积` `return 面积`
``` ```
`ref("#圆面积公式")` resolves the single formula under that heading; the `ref("#圆面积公式")` resolves the single formula under that heading and returns
formula is still inert until `math.eval` consumes it. an inert `Formula` value. The core has no math evaluator (ADR-0061): a pure
`.mq.md` function or an explicitly selected ABI backend consumes the formula when
the program asks for it; `ref` itself never evaluates it.
### 5.1 Error model of `ref` ### 5.1 Error model of `ref`
@@ -325,7 +326,7 @@ Inside a function body, `CallExpr` nodes call:
* a local function (same module, namespace-aware resolution: current namespace * a local function (same module, namespace-aware resolution: current namespace
first, then canonical name, then a unique local name); first, then canonical name, then a unique local name);
* an imported function through its alias: `geometry.圆面积(r=2)`; * an imported function through its alias: `geometry.圆面积(r=2)`;
* a builtin (`打印`, `math.eval`, ...) by canonical name or alias; * a builtin (`打印`, `resource.request`, ...) by canonical name or alias;
* a `FunctionRef` value obtained earlier (for example from `ref`). * a `FunctionRef` value obtained earlier (for example from `ref`).
Static validation (`crates/marqdo-frontend/src/calls.rs`) checks arity, Static validation (`crates/marqdo-frontend/src/calls.rs`) checks arity,
+4 -1
View File
@@ -123,7 +123,10 @@ that root, and the final target must be a regular file no larger than 256 MiB.
`marqdo-host` before the provider registry is consulted. A provider may not `marqdo-host` before the provider registry is consulted. A provider may not
declare them (nor use one as its `name`); registration can never shadow them. declare them (nor use one as its `name`); registration can never shadow them.
Reserved core kinds are rejected with `ext.manifest_invalid`. Reserved core kinds are rejected with `ext.manifest_invalid`. The list is the
single host-owned constant `marqdo_host::CORE_RESOURCE_KINDS`; the CLI manifest
validator and trusted `Host::register_resource_provider` both use it and reject the
same six names before registration (ADR-0062).
### 2.3 Artifact selection ### 2.3 Artifact selection
+9 -6
View File
@@ -263,12 +263,14 @@ CLI overrides (`run`/`call`): `--fuel`, `--stack`, `--max-output`,
These are not configurable from the CLI in this build; These are not configurable from the CLI in this build;
* plugin wire: request ≤ 16 MiB, result ≤ 64 MiB, error ≤ 1 MiB, metadata * plugin wire: request ≤ 16 MiB, result ≤ 64 MiB, error ≤ 1 MiB, metadata
≤ 64 KiB (see `include/marqdo_plugin_abi_v1.h`); ≤ 64 KiB (see `include/marqdo_plugin_abi_v1.h`);
* math kernel: 1 MB source, 256 parse depth, 512 AST nodes, exponent ≤ 10,000, * math: the core ships no math kernel (ADR-0061); a selected ABI math backend is a
exact-result ≤ 1,000,000 bits (`crates/marqdo-math`). plugin and is bounded by the plugin wire limits above, and a pure `.mq.md`
algorithm is bounded by the normal interpreter fuel/stack/output budgets.
These are cooperative budgets in the interpreter and the supervisor. Only These are cooperative budgets in the interpreter and the supervisor. Only
foreign child processes are terminated by the host (kill on timeout/output foreign child processes and worker plugins are terminated by the host (kill on
overflow). In-process math and native plugins are not OS-limited. timeout/output overflow). Native plugins are not OS-limited; the core no longer
hosts an in-process math kernel.
## 4. Effect tracing ## 4. Effect tracing
@@ -280,8 +282,9 @@ overflow). In-process math and native plugins are not OS-limited.
"duration_micros":3,"result":"ok"} "duration_micros":3,"result":"ok"}
``` ```
* `op` is the stable `HostOp::name()` (`print`, `math.eval`, `foreign.call`, * `op` is the stable `HostOp::name()` (`foreign.run`, `foreign.call`,
`fs.write`, `plugin.invoke`, ...); `fs.read`, `fs.write`, `plugin.invoke`, ...); `resource.request` traces the
operation name in its semantic metadata instead of a `HostOp` variant;
* `module` is the initiating module id; `span` is the call site when known; * `module` is the initiating module id; `span` is the call site when known;
* `result` is `"ok"` or the failure code (for example * `result` is `"ok"` or the failure code (for example
`permission.denied`); `permission.denied`);
+2 -2
View File
@@ -27,11 +27,11 @@ no test commits, copies or rewrites files outside a throw-away temp directory.
tests/ tests/
├── conformance/ ├── conformance/
│ ├── ast/ 160 × *.mq.md + sibling *.ast.json goldens │ ├── ast/ 160 × *.mq.md + sibling *.ast.json goldens
│ └── semantics/ 73 × *.mq.md + sibling *.expected.json goldens │ └── semantics/ 75 × *.mq.md + sibling *.expected.json goldens
├── negative/ ├── negative/
│ ├── *.mq.md 49 × compile-time hard-error fixtures + *.expected.json │ ├── *.mq.md 49 × compile-time hard-error fixtures + *.expected.json
│ ├── warnings/ 2 × warning-model/control fixtures + *.expected.json │ ├── warnings/ 2 × warning-model/control fixtures + *.expected.json
│ └── runtime/ 21 × runtime-error fixtures + *.expected.json │ └── runtime/ 20 × runtime-error fixtures + *.expected.json
└── README.md this file └── README.md this file
``` ```
@@ -1,9 +0,0 @@
## @knowledge 公式
$$
A = \pi r^2
$$
## @exec main
`return math.eval(ref("#公式"), {"r": 2}, target="A")`
@@ -1,9 +0,0 @@
## @knowledge 公式
$$
A = r + 1
$$
## @exec main
`return math.eval(ref("#公式"), {"r": 2}, target="A")`
@@ -3,7 +3,7 @@
"function": "main", "function": "main",
"stdout": "", "stdout": "",
"value": { "value": {
"decimal": "3", "decimal": "1",
"type": "int" "type": "int"
} }
} }
@@ -0,0 +1,9 @@
# @knowledge 数学
## @exec main
`return 1`
## 普通说明
这段是知识叙述,不声明模式,因此继承最近的祖先 `@knowledge`。
@@ -3,7 +3,7 @@
"function": "main", "function": "main",
"stdout": "", "stdout": "",
"value": { "value": {
"type": "float", "decimal": "2",
"value": 12.566370614359172 "type": "int"
} }
} }
@@ -0,0 +1,9 @@
# @exec 项目
## @knowledge 解释
背景叙述,声明为知识区域。
## main
`return 2`
@@ -0,0 +1,18 @@
{
"args": {
"甲": {
"decimal": "48",
"type": "int"
},
"乙": {
"decimal": "18",
"type": "int"
}
},
"function": "最大公约数",
"stdout": "",
"value": {
"decimal": "6",
"type": "int"
}
}
@@ -0,0 +1,19 @@
# @knowledge 数学算法
## @exec 最大公约数
`a = 甲`
`b = 乙`
`while b != 0`
`余数 = a % b`
`a = b`
`b = 余数`
`end`
`return a`
@@ -0,0 +1,9 @@
{
"args": {},
"function": "main",
"stdout": "",
"value": {
"decimal": "25",
"type": "int"
}
}
@@ -0,0 +1,5 @@
# @knowledge 数学
## @exec main
`return 3 * 3 + 4 * 4`
@@ -1,7 +0,0 @@
{
"function": "main",
"args": {},
"codes": [
"math.unsupported"
]
}
@@ -1,9 +0,0 @@
## @knowledge 公式
$$
\sin(x)
$$
## @exec main
`math.eval(ref("#公式"), {})`
+88
View File
@@ -0,0 +1,88 @@
"""Release-archive contract tests (RFC-EXT-0003 H-08 / T-PKG-01..05).
These tests are stdlib-only and do not build an archive; they pin the digest
helpers that package.py/smoke.py share with the runtime and check that the
release pipeline references a verified stdlib bundle instead of relying on the
compile-time source path.
"""
from __future__ import annotations
import importlib.util
import json
import unittest
from pathlib import Path
ROOT = Path(__file__).resolve().parents[2]
def load_module(name: str, path: Path):
spec = importlib.util.spec_from_file_location(name, path)
module = importlib.util.module_from_spec(spec)
assert spec.loader is not None
spec.loader.exec_module(module)
return module
class ReleaseArchiveContractTest(unittest.TestCase):
def setUp(self) -> None:
self.package = load_module("release_package", ROOT / "tools/release/package.py")
self.smoke = load_module("release_smoke", ROOT / "tools/release/smoke.py")
self.manifest = json.loads((ROOT / "stdlib/stdlib.json").read_text(encoding="utf-8"))
def test_tree_digest_matches_manifest(self) -> None:
self.assertEqual(
self.package.stdlib_tree_digest(), self.manifest["digest"]
)
self.assertEqual(
self.smoke.stdlib_tree_digest(ROOT / "stdlib"), self.manifest["digest"]
)
def test_alias_digest_matches_manifest(self) -> None:
self.assertEqual(
self.package.stdlib_aliases_digest(self.manifest),
self.manifest["aliases_digest"],
)
self.assertEqual(
self.smoke.stdlib_aliases_digest(self.manifest),
self.manifest["aliases_digest"],
)
def test_verify_record_names_required_files_and_count(self) -> None:
record = self.package.verify_stdlib()
self.assertEqual(record["name"], self.manifest["name"])
self.assertEqual(record["version"], self.manifest["version"])
self.assertEqual(record["tree_digest"], self.manifest["digest"])
self.assertEqual(record["aliases_digest"], self.manifest["aliases_digest"])
self.assertIn("stdlib.json", record["files"])
self.assertIn("io.mq.md", record["files"])
self.assertIn("io/console.mq.md", record["files"])
self.assertEqual(record["file_count"], len(record["files"]))
def test_package_stages_stdlib_next_to_the_binary_and_math_backend(self) -> None:
source = (ROOT / "tools/release/package.py").read_text(encoding="utf-8")
self.assertIn('copy_tree(STDLIB, stage_dir / "stdlib")', source)
self.assertIn('"math-backend"', source.replace("math_backend", "math-backend"))
self.assertIn('"stdlib": stdlib_info', source)
self.assertIn("verify_stdlib()", source)
def test_release_discovery_does_not_fall_back_to_the_source_tree(self) -> None:
source = (ROOT / "crates/cli/src/stdlib.rs").read_text(encoding="utf-8")
fallback = source.index("CARGO_MANIFEST_DIR")
self.assertIn("#[cfg(debug_assertions)]", source[:fallback])
# The compile-time path must be inside the debug-only block: a release
# build cannot reach it.
debug_block = source[fallback - 200 : fallback + 400]
self.assertIn("#[cfg(debug_assertions)]", debug_block)
def test_smoke_verifies_and_fails_closed_without_stdlib(self) -> None:
source = (ROOT / "tools/release/smoke.py").read_text(encoding="utf-8")
self.assertIn("verify_stdlib_bundle(install, info)", source)
self.assertIn("verify_stdlib_bundle", source)
self.assertIn("stdlib.hidden", source)
self.assertIn("expected 6", source)
self.assertIn("permission.denied", source)
if __name__ == "__main__":
unittest.main()
+92 -2
View File
@@ -34,6 +34,13 @@ from pathlib import Path
ROOT = Path(__file__).resolve().parents[2] ROOT = Path(__file__).resolve().parents[2]
BINARIES = ("marqdo", "marqdo-provider-worker") BINARIES = ("marqdo", "marqdo-provider-worker")
STDLIB = ROOT / "stdlib"
EXAMPLES_WITH_BUILD = (
"plugin-demo",
"plugin-multi-export",
"provider-demo",
"math-backend",
)
def fail(message: str) -> "NoReturn": def fail(message: str) -> "NoReturn":
@@ -57,6 +64,83 @@ def sha256_file(path: Path) -> str:
return digest.hexdigest() return digest.hexdigest()
def sha256_bytes(*chunks: bytes) -> str:
digest = hashlib.sha256()
for chunk in chunks:
digest.update(chunk)
return "sha256:" + digest.hexdigest()
def stdlib_tree_digest(root: Path = STDLIB) -> str:
"""Canonical stdlib tree digest, byte-identical to
`marqdo_cli::stdlib::tree_digest`: sorted `*.mq.md` relative POSIX paths,
`path + NUL + bytes + NUL`."""
paths = sorted(
(path.relative_to(root).as_posix(), path)
for path in root.rglob("*.mq.md")
if path.is_file()
)
return sha256_bytes(
*(
chunk
for relative, path in paths
for chunk in (relative.encode(), b"\0", path.read_bytes(), b"\0")
)
)
def stdlib_aliases_digest(manifest: dict) -> str:
"""Canonical public-alias digest, byte-identical to the CLI loader."""
chunks: list[bytes] = []
aliases = sorted(
manifest.get("public_aliases", []),
key=lambda alias: (alias["target_module"], alias["target_function"]),
)
for alias in aliases:
chunks.append(alias["target_module"].encode())
chunks.append(b"\0")
chunks.append(alias["target_function"].encode())
chunks.append(b"\0")
for name in sorted(alias["public_names"]):
chunks.append(name.encode())
chunks.append(b"\0")
return sha256_bytes(*chunks)
def verify_stdlib() -> dict:
"""Validate the shipped stdlib tree and return the RELEASE_INFO record."""
manifest_path = STDLIB / "stdlib.json"
if not manifest_path.is_file():
fail(f"missing bundled stdlib manifest {manifest_path}")
manifest = json.loads(manifest_path.read_text(encoding="utf-8"))
tree = stdlib_tree_digest()
aliases = stdlib_aliases_digest(manifest)
if tree != manifest.get("digest"):
fail(f"stdlib tree digest {tree} does not match stdlib.json digest {manifest.get('digest')}")
if aliases != manifest.get("aliases_digest"):
fail(
f"stdlib alias digest {aliases} does not match stdlib.json "
f"aliases_digest {manifest.get('aliases_digest')}"
)
required = ["stdlib.json", "io.mq.md", "io/console.mq.md"]
files = sorted(
path.relative_to(STDLIB).as_posix()
for path in STDLIB.rglob("*")
if path.is_file()
)
for name in required:
if name not in files:
fail(f"bundled stdlib is missing required file {name}")
return {
"name": manifest.get("name"),
"version": manifest.get("version"),
"tree_digest": tree,
"aliases_digest": aliases,
"file_count": len(files),
"files": files,
}
def host_target() -> str: def host_target() -> str:
out = run(["rustc", "-vV"], capture_output=True).stdout out = run(["rustc", "-vV"], capture_output=True).stdout
for line in out.splitlines(): for line in out.splitlines():
@@ -108,7 +192,7 @@ def check_clean(source_sha: str) -> None:
def build_examples() -> dict: def build_examples() -> dict:
outputs = {} outputs = {}
for name in ("plugin-demo", "plugin-multi-export", "provider-demo"): for name in EXAMPLES_WITH_BUILD:
script = ROOT / "examples" / name / "build.sh" script = ROOT / "examples" / name / "build.sh"
run(["bash", str(script)], cwd=ROOT) run(["bash", str(script)], cwd=ROOT)
outputs[name] = ROOT / "examples" / name / "build" outputs[name] = ROOT / "examples" / name / "build"
@@ -141,12 +225,16 @@ def stage(stage_dir: Path, version: str, source_sha: str, target: str) -> dict:
copy_tree(ROOT / "spec", stage_dir / "spec") copy_tree(ROOT / "spec", stage_dir / "spec")
copy_tree(ROOT / "docs" / "developers", stage_dir / "docs" / "developers") copy_tree(ROOT / "docs" / "developers", stage_dir / "docs" / "developers")
# The bundled stdlib is a required runtime artifact, not a build-machine
# side effect: copy the verified tree next to the binary (ADR/SPEC H-08).
copy_tree(STDLIB, stage_dir / "stdlib")
# Examples without local build output, then the freshly built extension # Examples without local build output, then the freshly built extension
# artifacts so a clean install can run every example without a compiler. # artifacts so a clean install can run every example without a compiler.
copy_tree(ROOT / "examples", stage_dir / "examples") copy_tree(ROOT / "examples", stage_dir / "examples")
for build_dir in stage_dir.glob("examples/*/build"): for build_dir in stage_dir.glob("examples/*/build"):
shutil.rmtree(build_dir, ignore_errors=True) shutil.rmtree(build_dir, ignore_errors=True)
for example in ("plugin-demo", "plugin-multi-export", "provider-demo"): for example in EXAMPLES_WITH_BUILD:
copy_tree(ROOT / "examples" / example / "build", stage_dir / "examples" / example / "build") copy_tree(ROOT / "examples" / example / "build", stage_dir / "examples" / example / "build")
copy_tree(ROOT / "tests" / "consumers", stage_dir / "tests" / "consumers") copy_tree(ROOT / "tests" / "consumers", stage_dir / "tests" / "consumers")
@@ -155,6 +243,7 @@ def stage(stage_dir: Path, version: str, source_sha: str, target: str) -> dict:
shutil.copy2(limitations, stage_dir / "KNOWN_LIMITATIONS.md") shutil.copy2(limitations, stage_dir / "KNOWN_LIMITATIONS.md")
commit_time = int(git("show", "-s", "--format=%ct", "HEAD")) commit_time = int(git("show", "-s", "--format=%ct", "HEAD"))
stdlib_info = verify_stdlib()
binaries = { binaries = {
name: { name: {
"sha256": sha256_file(stage_dir / name), "sha256": sha256_file(stage_dir / name),
@@ -173,6 +262,7 @@ def stage(stage_dir: Path, version: str, source_sha: str, target: str) -> dict:
"commit_time_utc": time_utc(commit_time), "commit_time_utc": time_utc(commit_time),
"toolchain": toolchain(), "toolchain": toolchain(),
"binaries": binaries, "binaries": binaries,
"stdlib": stdlib_info,
"protocols": { "protocols": {
"analysis": 2, "analysis": 2,
"trace": 2, "trace": 2,
+133
View File
@@ -38,6 +38,85 @@ def sha256_file(path: Path) -> str:
return digest.hexdigest() return digest.hexdigest()
def sha256_bytes(*chunks: bytes) -> str:
digest = hashlib.sha256()
for chunk in chunks:
digest.update(chunk)
return "sha256:" + digest.hexdigest()
def stdlib_tree_digest(root: Path) -> str:
files = sorted(
(path.relative_to(root).as_posix(), path)
for path in root.rglob("*.mq.md")
if path.is_file()
)
return sha256_bytes(
*(
chunk
for relative, path in files
for chunk in (relative.encode(), b"\0", path.read_bytes(), b"\0")
)
)
def stdlib_aliases_digest(manifest: dict) -> str:
chunks: list[bytes] = []
aliases = sorted(
manifest.get("public_aliases", []),
key=lambda alias: (alias["target_module"], alias["target_function"]),
)
for alias in aliases:
chunks.append(alias["target_module"].encode())
chunks.append(b"\0")
chunks.append(alias["target_function"].encode())
chunks.append(b"\0")
for name in sorted(alias["public_names"]):
chunks.append(name.encode())
chunks.append(b"\0")
return sha256_bytes(*chunks)
def verify_stdlib_bundle(install: Path, info: dict) -> None:
bundle = install / "stdlib"
manifest_path = bundle / "stdlib.json"
if not manifest_path.is_file():
fail("release archive is missing stdlib/stdlib.json")
manifest = json.loads(manifest_path.read_text(encoding="utf-8"))
recorded = info.get("stdlib") or {}
for required in ("stdlib.json", "io.mq.md", "io/console.mq.md"):
if not (bundle / required).is_file():
fail(f"release archive stdlib is missing {required}")
tree = stdlib_tree_digest(bundle)
aliases = stdlib_aliases_digest(manifest)
if recorded.get("tree_digest") != tree or manifest.get("digest") != tree:
fail(
f"stdlib tree digest mismatch: RELEASE_INFO={recorded.get('tree_digest')} "
f"stdlib.json={manifest.get('digest')} actual={tree}"
)
if recorded.get("aliases_digest") != aliases or manifest.get("aliases_digest") != aliases:
fail(
f"stdlib alias digest mismatch: RELEASE_INFO={recorded.get('aliases_digest')} "
f"stdlib.json={manifest.get('aliases_digest')} actual={aliases}"
)
if recorded.get("name") != manifest.get("name") or recorded.get("version") != manifest.get("version"):
fail("RELEASE_INFO.stdlib name/version disagree with stdlib/stdlib.json")
files = [
path.relative_to(bundle).as_posix()
for path in bundle.rglob("*")
if path.is_file()
]
if recorded.get("file_count") != len(files):
fail(
f"RELEASE_INFO.stdlib.file_count={recorded.get('file_count')} "
f"but archive has {len(files)} files"
)
print(
f"smoke: verified stdlib {recorded.get('version')} "
f"tree={tree} aliases={aliases} files={len(files)}"
)
class Runner: class Runner:
def __init__(self, root: Path): def __init__(self, root: Path):
self.root = root self.root = root
@@ -128,6 +207,7 @@ def main(argv: list[str]) -> int:
recorded = info["binaries"][name]["sha256"] recorded = info["binaries"][name]["sha256"]
if sha256_file(binary) != recorded: if sha256_file(binary) != recorded:
fail(f"{name} sha256 does not match RELEASE_INFO.json") fail(f"{name} sha256 does not match RELEASE_INFO.json")
verify_stdlib_bundle(install, info)
runner = Runner(install) runner = Runner(install)
print(f"smoke: archive version {version}, source {source_sha}") print(f"smoke: archive version {version}, source {source_sha}")
@@ -140,6 +220,21 @@ def main(argv: list[str]) -> int:
hello = runner.run(["run", "examples/hello.mq.md"]).stdout hello = runner.run(["run", "examples/hello.mq.md"]).stdout
if "你好" not in hello: if "你好" not in hello:
fail(f"hello example printed {hello!r}") fail(f"hello example printed {hello!r}")
# The archive must not fall back to a build-machine source tree: removing
# the shipped stdlib must fail closed (T-PKG-03).
hidden = install / "stdlib.hidden"
(install / "stdlib").rename(hidden)
try:
broken = runner.run(["run", "examples/hello.mq.md"])
if broken.returncode == 0:
fail("run succeeded after deleting the bundled stdlib (forbidden fallback)")
message = broken.stdout + broken.stderr
if "stdlib" not in message and "打印" not in message and "symbol.unknown" not in message:
fail(f"missing-stdlib failure is not explicit: {message!r}")
print("smoke: bundled stdlib missing -> fail-closed OK")
finally:
hidden.rename(install / "stdlib")
factor = runner.run( factor = runner.run(
["call", "examples/factorial.mq.md", "阶乘", "--arg", "n=5"] ["call", "examples/factorial.mq.md", "阶乘", "--arg", "n=5"]
).stdout.strip() ).stdout.strip()
@@ -352,6 +447,44 @@ def main(argv: list[str]) -> int:
finally: finally:
shutil.move(str(worker_binary.with_suffix(".hidden")), str(worker_binary)) shutil.move(str(worker_binary.with_suffix(".hidden")), str(worker_binary))
# RFC-EXT-0003: math algorithms are external. The pure package and the
# optional ABI backend are exercised by the frozen archive only; the core
# has no math.* builtin.
gcd = runner.run(["call", "examples/math-library-demo.mq.md", "main"]).stdout.strip()
if gcd != "6":
fail(f"pure math library printed {gcd!r}, expected 6")
runner.run(["check", "examples/math-library/index.mq.md"])
math_backend = runner.run(
[
"run",
"examples/math-backend/demo.mq.md",
"--plugin",
"examples/math-backend/build",
"--trust-native-plugin",
"--allow-plugin",
"math.backend",
]
).stdout.strip()
if math_backend != "42":
fail(f"math ABI backend printed {math_backend!r}, expected 42")
runner.run(
[
"run",
"examples/math-backend/demo.mq.md",
"--plugin",
"examples/math-backend/build",
"--trust-native-plugin",
],
expect=1,
contains="permission.denied",
)
removed = install / "removed-math.mq.md"
removed.write_text(
"## @exec main\n\n`return math.eval(ref(\"#公式\"), {})`\n",
encoding="utf-8",
)
runner.run(["check", str(removed)], expect=1, contains="symbol.unknown")
# pure mode: language execution without project grants. # pure mode: language execution without project grants.
runner.run(["run", "examples/hello.mq.md", "--mode", "pure"]) runner.run(["run", "examples/hello.mq.md", "--mode", "pure"])