Replace the Strong/Emph/List/Quote mapping in place with the single @exec/@knowledge heading-mode model, unified payload carriers and keyword control flow. - add the authoritative RFC, ADR-0052 and a historical ADR index - rewrite spec/mapping.md and spec/expression.ebnf as the normative mapping/statement grammar; update evaluation, references, math, foreign, package-format, plugin-abi, security and schema notes - rewrite README, AGENTS, COMPATIBILITY and CHANGELOG for the breaking language change; update the architecture index/overview and active docs - mark superseded planning docs, compute RFCs, evidence and syntax-role ADRs as historical/superseded without rewriting their decisions - add migration guide, per-file inventory and dev-only audit scripts The frontend/stdlib migration is completed in the following commits; this commit contains documentation only.
10 KiB
Marqdo Math v1
Status: frozen subset for M0.5. The kernel computes numbers; it never proves
theorems. math.simplify and math.differentiate are not implemented in
this build.
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. From Markdown to a value
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).
# @knowledge 数学
## @knowledge 圆面积公式
$$
A = \pi r^2
$$
## @exec 计算圆面积
`params(r: Number)`
`面积 = math.eval(ref("#圆面积公式"), {"r": r}, target="A")`
`return 面积`
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).
2. Grammar
The parser accepts exactly this LaTeX subset (whitespace insignificant; byte offsets are reported for parse errors):
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:
\cdotand\timesare accepted as synonyms for*.- Implicit multiplication between adjacent factors:
2x,\pi r^2,(a)(b),m a. Concatenated letters form one identifier (mais the variablema; writem aorm * afor 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 sosin(x)is not silently read as a product. - Underscores are ordinary identifier characters:
x_1is the variablex_1, not a subscript. - A single top-level
=creates anEquation { 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.5is an exact rational computation, not binary floating point.\sqrt{x}is real-valued: a negative radicand is aTypeerror.- Decimal literals have no exponent form (
1e3is rejected);2eis2 * e(number times the constant), while2e3is rejected rather than reinterpreted.
2.1 Unsupported constructs
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.
3. Numeric semantics
- Exact rational arithmetic uses
num-rational::Ratioover thenum-bigint::BigInttype that also backsValue::Int; integers are arbitrary precision. - Decimal literals are exact rationals (
0.25=1/4).Intbindings become exact integers.Floatbindings are interpreted as the exact binary rational value of thef64; non-finiteFloatbindings are aTypeerror. + - * / ^are exact when both operands are exact. Division keeps a rational, so\frac{1}{3} * 3is exactly1.- The final value is a Marqdo
Intexactly when the exact result is an integer, and aFloatotherwise (crates/marqdo-math/src/eval.rs, theNumericenum). Examples:1.5 + 2.5→Int(4);1 / 2→Float(0.5);100 / 4→Int(25). \pi,\eand a\sqrtof a non-perfect square introduce anf64approximation. Anything derived from them is aFloat. Precision follows IEEE-754 binary64 (about 15–17 significant decimal digits); approximate results are never presented as exact.\sqrtof a perfect square of an exact rational stays exact (\sqrt{4}→Int(2));\sqrt{1/4}isFloat(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 byMAX_EXPONENT. Negative integer exponents are exact reciprocals (the result is therefore aFloatunless it is integral).0 ^ 0is aTypeerror. - Exact intermediate/result numerators and denominators are bounded by
MAX_RESULT_BITS; exceeding the bound returns a structuredUnsupportederror rather than hanging or exhausting memory. - Division by zero is a
Typeerror inside the kernel. The host maps allMathErrorKind::Typetoruntime.type; it does not produce the interpreter'sruntime.division_by_zerocode for a formula. This is a known divergence from the module doc comment incrates/marqdo-math/src/lib.rsand should be fixed or documented in an ADR. - Constants are reserved: a binding named
piorenever overrides the constant, and they cannot be solve targets (useE,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,
targetmust beNone; supplying one isUnsupported("a target variable is only meaningful for an equation"); - for an equation,
targetis required (Unsupportedotherwise); an empty target isUnsupported; - the target must occur exactly once and the equation must be affine in
the target. Other variables are substituted from
bindingsfirst; a missing binding isUndefinedVariable.
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(withybound);F = m asolved forF,mora.
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
Formulavalue orText; anything else isruntime.type; bindingsmust be aMapwhose values areIntorFloat; any other value type isruntime.typewith a message naming the binding;targetmust beTextorNone; other types areruntime.type;- builtin arity/parameter-name mistakes are catchable statically
(
call.arity, seespec/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 ais 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
latextext of amathnode. - Not error-free in the floating-point sense: approximation precision is documented, not guaranteed beyond binary64.