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:
1 parent
0fe5f42a62
commit
a67f344b6b
88 files changed
+2633
-3503
No files matched your search
@@ -203,3 +203,22 @@ Analysis schema change; `schema_version` stays 2.
|
||||
* `analysis_v2_projects_addressable_formula_and_code_resources`
|
||||
* `failed_check_removes_stale_analysis`
|
||||
* `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
@@ -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
|
||||
falls back to a builtin or plugin with the same dotted spelling.
|
||||
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
|
||||
complete name `alias.f`, the site binds that export. The manifest signature
|
||||
is validated here; no library is loaded.
|
||||
@@ -207,42 +207,44 @@ is internal-only — the public wire code remains `capability.unavailable`.
|
||||
```markdown
|
||||
---
|
||||
import:
|
||||
mymath: "./math.mq.md"
|
||||
numerics: "./math.mq.md"
|
||||
---
|
||||
|
||||
## @exec main
|
||||
|
||||
`return mymath.eval(a=1)`
|
||||
`return numerics.最大公约数(甲=48, 乙=18)`
|
||||
```
|
||||
|
||||
Binds `Marqdo { function: <package instance>::math.mq.md::eval }` in both
|
||||
`check` and `run`.
|
||||
Binds `Marqdo { function: <package instance>::math.mq.md::最大公约数 }` in both
|
||||
`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
|
||||
|
||||
```markdown
|
||||
## @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
|
||||
|
||||
```markdown
|
||||
---
|
||||
import:
|
||||
math: "./math.mq.md"
|
||||
resource: "./resource.mq.md"
|
||||
---
|
||||
|
||||
## @exec main
|
||||
|
||||
`return math.eval(a=1)`
|
||||
`return resource.request("clock.now", [])`
|
||||
```
|
||||
|
||||
`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
|
||||
|
||||
|
||||
+1
-1
@@ -369,7 +369,7 @@ host boundary. Names are stable; adding one requires a spec update.
|
||||
| `resource.close` | `(handle) -> Result` | releases the host slot |
|
||||
| `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 |
|
||||
| `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 |
|
||||
| `fs.read/write` | see `spec/security.md` | capability-gated |
|
||||
|
||||
|
||||
@@ -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
|
||||
management (uv/venv) are not implemented. Python/Node are optional foreign
|
||||
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.
|
||||
@@ -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
@@ -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
|
||||
(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
|
||||
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
|
||||
ancestor heading.
|
||||
|
||||
+75
-209
@@ -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
|
||||
theorems. `math.simplify` and `math.differentiate` are **not implemented** in
|
||||
this build.
|
||||
Status: **the `math.*` builtin API was removed from the core after
|
||||
`3.0.0-beta.1`** by [ADR-0061](../docs/adr/0061-detach-domain-math-kernel-from-core.md)
|
||||
(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`,
|
||||
`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. What stays in the core
|
||||
|
||||
## 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
|
||||
operation. The frontend attributes every formula to its innermost enclosing
|
||||
heading unit (`crates/marqdo-frontend/src/resources.rs`). `ref("#heading")`
|
||||
returns a `Formula` value only when that unit contains exactly one resource;
|
||||
with two or more formulas the runtime raises `ref.ambiguous` and refuses to
|
||||
pick one (`spec/references.md` §5, ADR-0003).
|
||||
Every other math algorithm belongs to a pure `.mq.md` package (preferred) or an
|
||||
explicitly selected Plugin ABI backend for a hot path.
|
||||
|
||||
## 2. Removed builtins
|
||||
|
||||
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
|
||||
# @knowledge 数学
|
||||
# @knowledge 数学算法
|
||||
|
||||
## @knowledge 圆面积公式
|
||||
## @exec 最大公约数
|
||||
|
||||
$$
|
||||
A = \pi r^2
|
||||
$$
|
||||
`a = 甲`
|
||||
|
||||
## @exec 计算圆面积
|
||||
`b = 乙`
|
||||
|
||||
`params(r: Number)`
|
||||
`while b != 0`
|
||||
|
||||
`面积 = math.eval(ref("#圆面积公式"), {"r": r}, target="A")`
|
||||
`return 面积`
|
||||
`余数 = a % b`
|
||||
|
||||
`a = b`
|
||||
|
||||
`b = 余数`
|
||||
|
||||
`end`
|
||||
|
||||
`return a`
|
||||
```
|
||||
|
||||
Nothing is evaluated by reading or rendering the document. `math.*` must be
|
||||
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).
|
||||
Consumer:
|
||||
|
||||
## 2. Grammar
|
||||
|
||||
The parser accepts exactly this LaTeX subset (whitespace insignificant; byte
|
||||
offsets are reported for 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
|
||||
```yaml
|
||||
---
|
||||
import:
|
||||
math: "./math-library/index.mq.md"
|
||||
---
|
||||
```
|
||||
|
||||
Rules and edge cases:
|
||||
```markdown
|
||||
## @exec main
|
||||
|
||||
* `\cdot` and `\times` are accepted as synonyms for `*`.
|
||||
* 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.
|
||||
`return math.最大公约数(甲=48, 乙=18)`
|
||||
```
|
||||
|
||||
### 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:
|
||||
matrices, sums/integrals, function applications (`\sin`, `\cos`, ...),
|
||||
multi-letter commands, `\left[`/`\right]`, mismatched/missing braces,
|
||||
scientific notation, commas, arrays, subscripts, superscript commands other
|
||||
than the `^` operator, `\frac`/`\sqrt` without braced arguments, labels,
|
||||
alignment characters, line breaks. There is no `simplify`, `differentiate`,
|
||||
`integrate`, `matrix` or theorem/proof operation in this build.
|
||||
For a high-performance algorithm, add an explicitly selected Plugin ABI v1 export
|
||||
(for example `math_backend.add`) with a static signature and require
|
||||
`--trust-native-plugin` for in-process execution plus `--allow-plugin NAME` for the
|
||||
grant; without the manifest the call is `symbol.unknown`, without the grant it is
|
||||
`permission.denied`. See `examples/math-backend/`.
|
||||
|
||||
## 3. Numeric semantics
|
||||
## 4. What must not come back
|
||||
|
||||
* Exact rational arithmetic uses `num-rational::Ratio` over the
|
||||
`num-bigint::BigInt` type that also backs `Value::Int`; integers are
|
||||
arbitrary precision.
|
||||
* Decimal literals are exact rationals (`0.25` = `1/4`). `Int` bindings become
|
||||
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.
|
||||
- No new domain function may be added to `BUILTINS`, `HostOp` or
|
||||
`Host::resource_request` to emulate the removed API (ADR-0062).
|
||||
- No `Value` variant or Analysis resource kind is added for math.
|
||||
- No compatibility parser for the old `math.*` spelling.
|
||||
+6
-5
@@ -292,14 +292,15 @@ $$
|
||||
|
||||
## @exec 计算圆面积
|
||||
|
||||
`params(r: Number)`
|
||||
`面积 = ref("#圆面积公式")`
|
||||
|
||||
`面积 = math.eval(ref("#圆面积公式"), {"r": r}, target="A")`
|
||||
`return 面积`
|
||||
```
|
||||
|
||||
`ref("#圆面积公式")` resolves the single formula under that heading; the
|
||||
formula is still inert until `math.eval` consumes it.
|
||||
`ref("#圆面积公式")` resolves the single formula under that heading and returns
|
||||
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`
|
||||
|
||||
@@ -325,7 +326,7 @@ Inside a function body, `CallExpr` nodes call:
|
||||
* a local function (same module, namespace-aware resolution: current namespace
|
||||
first, then canonical name, then a unique local name);
|
||||
* 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`).
|
||||
|
||||
Static validation (`crates/marqdo-frontend/src/calls.rs`) checks arity,
|
||||
|
||||
@@ -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
|
||||
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
|
||||
|
||||
|
||||
+9
-6
@@ -263,12 +263,14 @@ CLI overrides (`run`/`call`): `--fuel`, `--stack`, `--max-output`,
|
||||
These are not configurable from the CLI in this build;
|
||||
* plugin wire: request ≤ 16 MiB, result ≤ 64 MiB, error ≤ 1 MiB, metadata
|
||||
≤ 64 KiB (see `include/marqdo_plugin_abi_v1.h`);
|
||||
* math kernel: 1 MB source, 256 parse depth, 512 AST nodes, exponent ≤ 10,000,
|
||||
exact-result ≤ 1,000,000 bits (`crates/marqdo-math`).
|
||||
* math: the core ships no math kernel (ADR-0061); a selected ABI math backend is a
|
||||
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
|
||||
foreign child processes are terminated by the host (kill on timeout/output
|
||||
overflow). In-process math and native plugins are not OS-limited.
|
||||
foreign child processes and worker plugins are terminated by the host (kill on
|
||||
timeout/output overflow). Native plugins are not OS-limited; the core no longer
|
||||
hosts an in-process math kernel.
|
||||
|
||||
## 4. Effect tracing
|
||||
|
||||
@@ -280,8 +282,9 @@ overflow). In-process math and native plugins are not OS-limited.
|
||||
"duration_micros":3,"result":"ok"}
|
||||
```
|
||||
|
||||
* `op` is the stable `HostOp::name()` (`print`, `math.eval`, `foreign.call`,
|
||||
`fs.write`, `plugin.invoke`, ...);
|
||||
* `op` is the stable `HostOp::name()` (`foreign.run`, `foreign.call`,
|
||||
`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;
|
||||
* `result` is `"ok"` or the failure code (for example
|
||||
`permission.denied`);
|
||||
|
||||
Reference in new issue
Block a user