11 Commits
Author SHA1 Message Date
Codex 9149ee40a4 Prepare Marqdo CLI 3.0.0-rc.2 with structured control flow
ci/woodpecker/push/main Pipeline was successful
ci/woodpecker/manual/performance Pipeline was successful
2026-11-23 22:40:06 +08:00
Codex 51d4c6568d Record control-flow RC verification and the pending performance decision 2026-11-23 22:35:23 +08:00
Codex af1e07f3d7 Benchmark the verified archive on release staging branches
ci/woodpecker/push/main Pipeline was successful
ci/woodpecker/manual/performance Pipeline was successful
2026-11-23 22:19:57 +08:00
Codex 58fccae303 Verify both Analysis versions in the shipped RC archive
ci/woodpecker/push/main Pipeline was canceled
2026-11-23 22:15:28 +08:00
Codex e903575d91 Record SHA-bound control-flow verification and consumer compatibility 2026-11-23 19:56:45 +08:00
Codex b1314328e6 Cover short-circuiting and transfers in nested branch arms 2026-11-23 19:53:40 +08:00
Codex 1dc088b602 Verify control-flow invariants and document the development contract 2026-11-23 19:51:12 +08:00
Codex 71d29261a8 Expose loop transfers through versioned public observations 2026-11-23 19:47:24 +08:00
Codex 69c5dc8d20 Implement nearest-loop transfers and reachable binding analysis 2026-11-23 19:41:01 +08:00
Codex 095eef1370 Lower else-if chains to ordered branch arms 2026-11-23 19:36:29 +08:00
Codex c582451a5f Specify structured control flow for RFC-CTRL-0005 2026-11-23 19:32:42 +08:00
123 changed files with 2485 additions and 458 deletions

No files matched your search

+13
View File
@@ -114,6 +114,19 @@ jobs:
python3 tests/consumers/analysis_consumer.py /tmp/analysis-v2.json python3 tests/consumers/analysis_consumer.py /tmp/analysis-v2.json
python3 tests/consumers/trace_consumer.py \ python3 tests/consumers/trace_consumer.py \
/tmp/analysis-v2.json /tmp/trace-v2.json /tmp/analysis-v2.json /tmp/trace-v2.json
./target/debug/marqdo check tests/conformance/semantics/85-nested-loop-control.mq.md \
--emit /tmp/analysis-v3.json
./target/debug/marqdo run tests/conformance/semantics/85-nested-loop-control.mq.md \
--event-stream jsonl --trace-file /tmp/control-trace-v2.json > /tmp/control-events.jsonl
python3 tests/consumers/validate_protocols.py \
/tmp/analysis-v3.json /tmp/control-trace-v2.json examples/tool-unknown-name/tool.json
python3 tests/consumers/analysis_v3_consumer.py /tmp/analysis-v3.json
if python3 tests/consumers/analysis_consumer.py /tmp/analysis-v3.json; then
echo "Analysis v2 consumer accepted a v3 document" >&2
exit 1
fi
python3 tests/consumers/trace_consumer.py /tmp/analysis-v3.json /tmp/control-trace-v2.json
python3 tests/consumers/execution_events_consumer.py /tmp/control-events.jsonl
cross-platform: cross-platform:
name: runtime contract (${{ matrix.os }}) name: runtime contract (${{ matrix.os }})
+7 -1
View File
@@ -23,6 +23,12 @@ steps:
# validated by the independent Python consumer and the public schema. # validated by the independent Python consumer and the public schema.
- cargo run --quiet --locked -p marqdo-cli -- run tests/consumers/fixtures/execution-events/basic.mq.md --event-stream jsonl > /tmp/execution-events.jsonl - cargo run --quiet --locked -p marqdo-cli -- run tests/consumers/fixtures/execution-events/basic.mq.md --event-stream jsonl > /tmp/execution-events.jsonl
- python3 tests/consumers/execution_events_consumer.py /tmp/execution-events.jsonl - python3 tests/consumers/execution_events_consumer.py /tmp/execution-events.jsonl
- ./target/debug/marqdo check examples/control-flow.mq.md --emit /tmp/control-analysis.json
- ./target/debug/marqdo run examples/control-flow.mq.md --event-stream jsonl --trace-file /tmp/control-trace.json > /tmp/control-events.jsonl
- python3 tests/consumers/analysis_v3_consumer.py /tmp/control-analysis.json
- python3 tests/consumers/validate_protocols.py /tmp/control-analysis.json /tmp/control-trace.json examples/tool-unknown-name/tool.json
- python3 tests/consumers/trace_consumer.py /tmp/control-analysis.json /tmp/control-trace.json
- python3 tests/consumers/execution_events_consumer.py /tmp/control-events.jsonl
- cargo test -p marqdo-cli --test docs_consistency - cargo test -p marqdo-cli --test docs_consistency
- cargo test -p marqdo-cli --test architecture_boundaries - cargo test -p marqdo-cli --test architecture_boundaries
- python3 -m unittest discover -s tools/ci -p "test_*.py" - python3 -m unittest discover -s tools/ci -p "test_*.py"
@@ -44,7 +50,7 @@ steps:
depends_on: [test, minimum-rust] depends_on: [test, minimum-rust]
commands: commands:
- apt-get update - apt-get update
- apt-get install -y --no-install-recommends ca-certificates git openssl python3 build-essential - apt-get install -y --no-install-recommends ca-certificates git openssl python3 python3-jsonschema build-essential
# Release archives must ship both binaries: the provider worker is the # Release archives must ship both binaries: the provider worker is the
# only supported transport and resolution is a sibling-of-CLI lookup. # only supported transport and resolution is a sibling-of-CLI lookup.
- cargo build --release --locked -p marqdo-cli -p marqdo-provider-worker - cargo build --release --locked -p marqdo-cli -p marqdo-provider-worker
+12 -4
View File
@@ -2,15 +2,15 @@
# Shared-node measurements may support an explicitly approved RC WARN. # Shared-node measurements may support an explicitly approved RC WARN.
when: when:
event: [manual] event: [manual]
branch: [master] branch: [master, "release/*"]
steps: steps:
measure: measure:
image: rust:1.100-bookworm image: rust:1.100-bookworm
commands: commands:
- apt-get update - apt-get update
- apt-get install -y --no-install-recommends python3 util-linux ca-certificates git build-essential - apt-get install -y --no-install-recommends python3 util-linux ca-certificates git openssl build-essential
- cargo build --release --locked -p marqdo-cli - cargo build --release --locked -p marqdo-cli -p marqdo-provider-worker
- | - |
set -eu set -eu
baseline_sha=2c7c4f31e7a388d3fcfa717a77067e696ed13854 baseline_sha=2c7c4f31e7a388d3fcfa717a77067e696ed13854
@@ -21,6 +21,14 @@ steps:
trap 'git worktree remove --force "$perf_dir/beta"; rm -rf "$perf_dir"' EXIT trap 'git worktree remove --force "$perf_dir/beta"; rm -rf "$perf_dir"' EXIT
(cd "$perf_dir/beta" && cargo build --release --locked -p marqdo-cli) (cd "$perf_dir/beta" && cargo build --release --locked -p marqdo-cli)
version="$(target/release/marqdo --version | cut -d ' ' -f 2)"
python3 tools/release/package.py --version "$version" --source-sha "$CI_COMMIT_SHA" --out-dir "$perf_dir"
archive="$perf_dir/marqdo-$version-x86_64-unknown-linux-gnu.tar.gz"
(cd "$perf_dir" && sha256sum -c "$(basename "$archive.sha256")")
tar -xzf "$archive" -C "$perf_dir"
candidate="$perf_dir/marqdo-$version-x86_64-unknown-linux-gnu"
test "$(cat "$candidate/SOURCE_SHA")" = "$CI_COMMIT_SHA"
allowed="$(awk '/^Cpus_allowed_list:/ {print $2}' /proc/self/status)" allowed="$(awk '/^Cpus_allowed_list:/ {print $2}' /proc/self/status)"
cpu_list="${MARQDO_PERF_CPU_LIST:-$(printf '%s' "$allowed" | cut -d, -f1 | cut -d- -f1)}" cpu_list="${MARQDO_PERF_CPU_LIST:-$(printf '%s' "$allowed" | cut -d, -f1 | cut -d- -f1)}"
echo "G4_NODE host=$(uname -n) kernel=$(uname -r) arch=$(uname -m) allowed_cpus=$allowed pin=$cpu_list" echo "G4_NODE host=$(uname -n) kernel=$(uname -r) arch=$(uname -m) allowed_cpus=$allowed pin=$cpu_list"
@@ -29,7 +37,7 @@ steps:
(cd "$perf_dir/beta" && python3 tools/perf/runner.py --no-build \ (cd "$perf_dir/beta" && python3 tools/perf/runner.py --no-build \
--warmups 5 --samples 20 --platform-id woodpecker-agent-1 \ --warmups 5 --samples 20 --platform-id woodpecker-agent-1 \
--cpu-list "$cpu_list" --out "$perf_dir/beta.json" > /dev/null) --cpu-list "$cpu_list" --out "$perf_dir/beta.json" > /dev/null)
python3 tools/perf/runner.py --no-build --warmups 5 --samples 20 \ python3 tools/perf/runner.py --no-build --binary "$candidate/marqdo" --warmups 5 --samples 20 \
--platform-id woodpecker-agent-1 --cpu-list "$cpu_list" \ --platform-id woodpecker-agent-1 --cpu-list "$cpu_list" \
--baseline "$perf_dir/beta.json" --out perf.json > /dev/null --baseline "$perf_dir/beta.json" --out perf.json > /dev/null
python3 - <<'PY' python3 - <<'PY'
+16 -5
View File
@@ -10,13 +10,24 @@ Foreign wire v1, Provider manifest v2, lock v4) and independent package
versions (including the bundled stdlib `0.1.0`) are versioned separately and versions (including the bundled stdlib `0.1.0`) are versioned separately and
do not follow the product version. Dates use ISO 8601. do not follow the product version. Dates use ISO 8601.
## 3.0.0-rc.1 (candidate) ## 3.0.0-rc.2 (candidate)
- The Rust workspace, CLI version output and protocol producers report - The Rust workspace, CLI version output and protocol producers report
`3.0.0-rc.1`. The locked workspace requires Rust 1.89. `3.0.0-rc.2`. The locked workspace requires Rust 1.89.
- The candidate targets Linux x86_64 with glibc. See - The candidate targets Linux x86_64 with glibc. See
[release gates](docs/releasing.md) for the evidence required for publication. [release gates](docs/releasing.md) for the evidence required for publication.
### Structured control flow (RFC-CTRL-0005)
- Added ordered `else if` arms and nearest-loop `break` and `continue`.
Bare keyword carriers take the control meaning. Calls, bindings and
identifiers within expressions retain their existing syntax.
- Inferred signatures now use reachable reads and merge assignments on
reachable control exits. A parameter inferred only from unreachable
statements may disappear.
- Analysis v3 represents loop transfers. Projects without transfers still emit
v2. Trace v2 and Execution Events v1 report the two explicit control events.
### Core/extension boundary — RFC-EXT-0003 (issue #3) ### 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). Executed evidence: [`docs/evidence/2026-11-22-rfc-ext-0003-core-hardcoding.md`](docs/evidence/2026-11-22-rfc-ext-0003-core-hardcoding.md).
@@ -68,7 +79,7 @@ detach), ADR-0062 (resource-operation ownership/core kinds), ADR-0063
metadata-only `@namespace.identifier` annotation layer is specified as metadata-only `@namespace.identifier` annotation layer is specified as
**Proposed** with target `3.1.x`. The current parser still rejects any other **Proposed** with target `3.1.x`. The current parser still rejects any other
leading `@foo` with `sem.invalid_mode_marker`; no `annotation.unknown` code, leading `@foo` with `sem.invalid_mode_marker`; no `annotation.unknown` code,
manifest loader, Analysis v3 or sidecar exists in this build. Contracts: manifest loader or heading annotations projection exists in this build. Contracts:
ADR-0060 and [`spec/heading-annotations-v1.md`](spec/heading-annotations-v1.md). 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 F-B removal is deferred (H-02).** The permission-gated one-shot
`foreign.run`/`foreign.call` + `KernelRegistry` stay as the controlled `foreign.run`/`foreign.call` + `KernelRegistry` stay as the controlled
@@ -98,8 +109,8 @@ detach), ADR-0062 (resource-operation ownership/core kinds), ADR-0063
- New public contract - New public contract
[`spec/execution-events-v1.md`](spec/execution-events-v1.md) and [`spec/execution-events-v1.md`](spec/execution-events-v1.md) and
[`spec/schemas/execution-events-v1.schema.json`](spec/schemas/execution-events-v1.schema.json), [`spec/schemas/execution-events-v1.schema.json`](spec/schemas/execution-events-v1.schema.json),
with fixtures and an independent Python consumer. Analysis v2 and Trace v2 with fixtures and an independent Python consumer. Trace v2 retains its
schemas/versions are unchanged. public event envelope.
- Limitations: memory metadata events (OBS-06/P2), a bidirectional debug - Limitations: memory metadata events (OBS-06/P2), a bidirectional debug
protocol and SSE/HTTP remain out of scope; strict mode refuses event mode protocol and SSE/HTTP remain out of scope; strict mode refuses event mode
explicitly. explicitly.
+21 -5
View File
@@ -8,7 +8,7 @@ this beta. Executed status and same-SHA evidence are in
[`docs/STATUS.md`](docs/STATUS.md), and SHA-bound external evidence is under [`docs/STATUS.md`](docs/STATUS.md), and SHA-bound external evidence is under
[`docs/evidence/extension/`](docs/evidence/extension/README.md). [`docs/evidence/extension/`](docs/evidence/extension/README.md).
The `3.0.0-rc.1` candidate targets Linux x86_64 on glibc 2.39 and The `3.0.0-rc.2` candidate targets Linux x86_64 on glibc 2.39 and
includes the post-beta changes below. See the includes the post-beta changes below. See the
[RC acceptance procedure](docs/releasing.md). The platform evidence table [RC acceptance procedure](docs/releasing.md). The platform evidence table
records the beta and subsequent development verification. records the beta and subsequent development verification.
@@ -51,7 +51,7 @@ Consequences for compatibility:
## Post-`3.0.0-beta.1` boundary changes (RFC-EXT-0003) ## Post-`3.0.0-beta.1` boundary changes (RFC-EXT-0003)
These landed after the beta tag and **are included in the `3.0.0-rc.1` candidate**; they are These landed after the beta tag and **are included in the `3.0.0-rc.2` candidate**; they are
intentional beta-line incompatibilities. Frozen decisions: ADR-0060..0063; executed 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). evidence: [`docs/evidence/2026-11-22-rfc-ext-0003-core-hardcoding.md`](docs/evidence/2026-11-22-rfc-ext-0003-core-hardcoding.md).
@@ -62,17 +62,33 @@ evidence: [`docs/evidence/2026-11-22-rfc-ext-0003-core-hardcoding.md`](docs/evid
| 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. | | 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. | | 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`. | | `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`. | | 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` or heading annotations projection 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. | | 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. |
## Structured control flow (RFC-CTRL-0005, RC.2)
The RC.2 candidate reserves `break` and `continue` only as complete
payloads. An existing standalone identifier read can be written as
`(break)` or `(continue)`. Calls, bindings, fields and identifiers within
expressions retain their meaning. Two separate carriers containing `else` and
`if` still require two closing `end` statements.
Parameter inference ignores reads after a definite transfer. When upgrading
a caller that passed an argument inferred solely from unreachable code,
remove the argument or keep it through an explicit `params(...)` declaration.
`marqdo-lint 0.1.0` reads legacy Analysis v2 documents. Its control layout
alignment for `else if` and its Analysis v3 support require an update in
that tool.
## Public protocol versions ## Public protocol versions
| Surface | Version | Compatibility rule | | Surface | Version | Compatibility rule |
|---|---|---| |---|---|---|
| Markdown profile | `marqdo.md.v1` | Frozen parser/options. The RFC-LANG-0002 mapping rewrite keeps this profile; the source-language break is tracked above, not by a new profile id. | | Markdown profile | `marqdo.md.v1` | Frozen parser/options. The RFC-LANG-0002 mapping rewrite keeps this profile; the source-language break is tracked above, not by a new profile id. |
| Language / CLI | `3.0.0-rc.1` (candidate) | SemVer prerelease: breaking changes inside the 3.0 beta line are allowed and announced in the changelog. The `.mq.md` source language changed incompatibly (RFC-LANG-0002); there is no old-syntax execution path or downgrade. CLI flags may change with a changelog note; `strict` refusal is contractual. | | Language / CLI | `3.0.0-rc.2` (candidate) | SemVer prerelease: breaking changes inside the 3.0 beta line are allowed and announced in the changelog. The `.mq.md` source language changed incompatibly (RFC-LANG-0002); there is no old-syntax execution path or downgrade. CLI flags may change with a changelog note; `strict` refusal is contractual. |
| `marqdo.lock` | v4 | v3 is rejected with an explicit `marqdo lock` migration error; v1/v2 are rejected with a relock instruction; `run`/`call`/`check` never rewrite or fetch the lock. `extensions:` records manifest/artifact identity (integrity, not publisher auth). | | `marqdo.lock` | v4 | v3 is rejected with an explicit `marqdo lock` migration error; v1/v2 are rejected with a relock instruction; `run`/`call`/`check` never rewrite or fetch the lock. `extensions:` records manifest/artifact identity (integrity, not publisher auth). |
| Analysis | v2 | Consumers reject unknown majors; incompatible field changes require v3. | | Analysis | v2/v3 | Projects with loop transfers emit v3. Other projects emit v2. Consumers reject unknown majors. |
| Trace | v2 | Binds to the exact Analysis bytes; unknown majors rejected. | | Trace | v2 | Binds to the exact Analysis bytes; unknown majors rejected. |
| 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. |
Generated
+15 -15
View File
@@ -412,7 +412,7 @@ checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53"
[[package]] [[package]]
name = "marqdo-cli" name = "marqdo-cli"
version = "3.0.0-rc.1" version = "3.0.0-rc.2"
dependencies = [ dependencies = [
"clap", "clap",
"hex", "hex",
@@ -438,7 +438,7 @@ dependencies = [
[[package]] [[package]]
name = "marqdo-expression" name = "marqdo-expression"
version = "3.0.0-rc.1" version = "3.0.0-rc.2"
dependencies = [ dependencies = [
"marqdo-span", "marqdo-span",
"num-bigint", "num-bigint",
@@ -449,7 +449,7 @@ dependencies = [
[[package]] [[package]]
name = "marqdo-foreign" name = "marqdo-foreign"
version = "3.0.0-rc.1" version = "3.0.0-rc.2"
dependencies = [ dependencies = [
"hex", "hex",
"libc", "libc",
@@ -465,7 +465,7 @@ dependencies = [
[[package]] [[package]]
name = "marqdo-frontend" name = "marqdo-frontend"
version = "3.0.0-rc.1" version = "3.0.0-rc.2"
dependencies = [ dependencies = [
"marqdo-expression", "marqdo-expression",
"marqdo-ir", "marqdo-ir",
@@ -480,7 +480,7 @@ dependencies = [
[[package]] [[package]]
name = "marqdo-host" name = "marqdo-host"
version = "3.0.0-rc.1" version = "3.0.0-rc.2"
dependencies = [ dependencies = [
"flate2", "flate2",
"getrandom 0.4.3", "getrandom 0.4.3",
@@ -504,7 +504,7 @@ dependencies = [
[[package]] [[package]]
name = "marqdo-ir" name = "marqdo-ir"
version = "3.0.0-rc.1" version = "3.0.0-rc.2"
dependencies = [ dependencies = [
"marqdo-expression", "marqdo-expression",
"marqdo-span", "marqdo-span",
@@ -514,7 +514,7 @@ dependencies = [
[[package]] [[package]]
name = "marqdo-markdown" name = "marqdo-markdown"
version = "3.0.0-rc.1" version = "3.0.0-rc.2"
dependencies = [ dependencies = [
"comrak", "comrak",
"marqdo-span", "marqdo-span",
@@ -525,7 +525,7 @@ dependencies = [
[[package]] [[package]]
name = "marqdo-package" name = "marqdo-package"
version = "3.0.0-rc.1" version = "3.0.0-rc.2"
dependencies = [ dependencies = [
"hex", "hex",
"semver", "semver",
@@ -539,7 +539,7 @@ dependencies = [
[[package]] [[package]]
name = "marqdo-plugin-abi" name = "marqdo-plugin-abi"
version = "3.0.0-rc.1" version = "3.0.0-rc.2"
dependencies = [ dependencies = [
"hex", "hex",
"libloading", "libloading",
@@ -554,7 +554,7 @@ dependencies = [
[[package]] [[package]]
name = "marqdo-plugin-sdk" name = "marqdo-plugin-sdk"
version = "3.0.0-rc.1" version = "3.0.0-rc.2"
dependencies = [ dependencies = [
"marqdo-plugin-abi", "marqdo-plugin-abi",
"serde", "serde",
@@ -563,7 +563,7 @@ dependencies = [
[[package]] [[package]]
name = "marqdo-provider-worker" name = "marqdo-provider-worker"
version = "3.0.0-rc.1" version = "3.0.0-rc.2"
dependencies = [ dependencies = [
"libloading", "libloading",
"marqdo-host", "marqdo-host",
@@ -575,7 +575,7 @@ dependencies = [
[[package]] [[package]]
name = "marqdo-runtime" name = "marqdo-runtime"
version = "3.0.0-rc.1" version = "3.0.0-rc.2"
dependencies = [ dependencies = [
"marqdo-expression", "marqdo-expression",
"marqdo-frontend", "marqdo-frontend",
@@ -594,7 +594,7 @@ dependencies = [
[[package]] [[package]]
name = "marqdo-sandbox" name = "marqdo-sandbox"
version = "3.0.0-rc.1" version = "3.0.0-rc.2"
dependencies = [ dependencies = [
"libc", "libc",
"serde", "serde",
@@ -602,14 +602,14 @@ dependencies = [
[[package]] [[package]]
name = "marqdo-span" name = "marqdo-span"
version = "3.0.0-rc.1" version = "3.0.0-rc.2"
dependencies = [ dependencies = [
"serde", "serde",
] ]
[[package]] [[package]]
name = "marqdo-value" name = "marqdo-value"
version = "3.0.0-rc.1" version = "3.0.0-rc.2"
dependencies = [ dependencies = [
"marqdo-span", "marqdo-span",
"num-bigint", "num-bigint",
+1 -1
View File
@@ -19,7 +19,7 @@ members = [
] ]
[workspace.package] [workspace.package]
version = "3.0.0-rc.1" version = "3.0.0-rc.2"
edition = "2021" edition = "2021"
rust-version = "1.89" rust-version = "1.89"
license = "MIT OR Apache-2.0" license = "MIT OR Apache-2.0"
+8 -6
View File
@@ -10,7 +10,7 @@ The official implementation is a Rust workspace; Python/Node are optional
foreign kernels, never the compiler target. foreign kernels, never the compiler target.
This repository is the new, independent Marqdo toolchain, now at product This repository is the new, independent Marqdo toolchain, now at product
version **`3.0.0-rc.1`** in this checkout. It is **not** a compatibility rewrite of version **`3.0.0-rc.2`** in this checkout. It is **not** a compatibility rewrite of
`cflmy/marqdo`; the old syntax, package format and plugin ABI v2 are not `cflmy/marqdo`; the old syntax, package format and plugin ABI v2 are not
claimed to work here. See [docs/developers/](docs/developers/README.md) for the claimed to work here. See [docs/developers/](docs/developers/README.md) for the
third-party entry point and `docs/MARQDO_3_0_PRERELEASE_PLAN.md` for the beta third-party entry point and `docs/MARQDO_3_0_PRERELEASE_PLAN.md` for the beta
@@ -114,10 +114,11 @@ executes anything. The Markdown profile is unchanged by the semantic rewrite.
* **Closed carriers are interchangeable.** In an Exec section, `**x = 1**`, * **Closed carriers are interchangeable.** In an Exec section, `**x = 1**`,
`*x = 1*` and `` `x = 1` `` are the same assignment. Prefer inline code spans `*x = 1*` and `` `x = 1` `` are the same assignment. Prefer inline code spans
for expressions containing `*` or `**`. for expressions containing `*` or `**`.
* **Statements are explicit.** `if <Bool>`, `else`, `while <Bool>`, `end`, * **Statements are explicit.** An `if` may have multiple `else if` arms and
`return <expr>`, `params(n: Int)`, assignment, or an expression call. Each a final `else`. `while` repeats while its condition is true. `break` exits the
carrier holds exactly one statement; every `if`/`while` is closed by `end` nearest loop and `continue` rechecks its condition. Each carrier holds one
inside the same heading body. statement and every `if` or `while` closes with `end` in the same heading
body. See the [control-flow example](examples/control-flow.mq.md).
* **Containers do not compute.** `1.`, `-`, `>` and emphasis only organize the * **Containers do not compute.** `1.`, `-`, `>` and emphasis only organize the
document. `> print(1)` is prose; `> **print(1)**` contains a call. document. `> print(1)` is prose; `> **print(1)**` contains a call.
* **Knowledge is inert.** Nothing in a `@knowledge` section executes, so it is * **Knowledge is inert.** Nothing in a `@knowledge` section executes, so it is
@@ -231,7 +232,7 @@ rules are [`RFC-LANG-0002`](docs/architecture/RFC-LANG-0002-unified-semantics.md
target-triple + sha256 artifact verification, native and isolated worker target-triple + sha256 artifact verification, native and isolated worker
transports, brokered `fs.read`, and explicitly trusted in-process calls transports, brokered `fs.read`, and explicitly trusted in-process calls
(`--plugin --trust-native-plugin --allow-plugin`). A C ABI is not a sandbox. (`--plugin --trust-native-plugin --allow-plugin`). A C ABI is not a sandbox.
* **Public protocols** — Analysis v2 and Trace v2 with JSON Schemas and * **Public protocols** — Analysis [v2](spec/analysis-v2.md)/[v3](spec/analysis-v3.md) and Trace v2 with JSON Schemas and
independent Python consumers; Tool Protocol v1 with arbitrary command names, independent Python consumers; Tool Protocol v1 with arbitrary command names,
SemVer negotiation and whole-bundle digest verification; **Execution Events SemVer negotiation and whole-bundle digest verification; **Execution Events
v1** (`run/call --event-stream jsonl`) for live stdout/stderr, call frames and v1** (`run/call --event-stream jsonl`) for live stdout/stderr, call frames and
@@ -373,6 +374,7 @@ tests/ conformance/negative corpus (see tests/README.md)
```bash ```bash
marqdo run examples/hello.mq.md marqdo run examples/hello.mq.md
marqdo call examples/control-flow.mq.md main
marqdo call examples/factorial.mq.md 数学.阶乘 --arg n=5 marqdo call examples/factorial.mq.md 数学.阶乘 --arg n=5
marqdo run examples/multi-module/index.mq.md marqdo run examples/multi-module/index.mq.md
marqdo run examples/python-foreign.mq.md --allow-foreign # needs python3 or node marqdo run examples/python-foreign.mq.md --allow-foreign # needs python3 or node
+26 -3
View File
@@ -1,4 +1,4 @@
//! Public Analysis v2 projection (spec/analysis-v2.md). //! Public Analysis projection (spec/analysis-v2.md and spec/analysis-v3.md).
//! //!
//! This is deliberately not a serde dump of `marqdo-ir`: the schema and node //! This is deliberately not a serde dump of `marqdo-ir`: the schema and node
//! kinds are the public contract, while internal Rust types may change. The //! kinds are the public contract, while internal Rust types may change. The
@@ -17,13 +17,24 @@ use crate::loader::LoadedProject;
/// Schema name and version. /// Schema name and version.
pub const SCHEMA: &str = "marqdo.analysis"; pub const SCHEMA: &str = "marqdo.analysis";
pub const SCHEMA_VERSION: u32 = 2; pub const BASE_VERSION: u32 = 2;
/// First schema version with structured loop transfers.
pub const LOOP_CONTROL_VERSION: u32 = 3;
/// Build the deterministic public projection. /// Build the deterministic public projection.
pub fn build(project: &LoadedProject) -> Value { pub fn build(project: &LoadedProject) -> Value {
let mut modules = Vec::new(); let mut modules = Vec::new();
let mut version = BASE_VERSION;
for (module_id, file) in &project.files { for (module_id, file) in &project.files {
let module = &file.analysis.module; let module = &file.analysis.module;
if version == BASE_VERSION
&& module
.functions
.iter()
.any(|function| has_loop_control(&function.body))
{
version = LOOP_CONTROL_VERSION;
}
modules.push(json!({ modules.push(json!({
"id": module_id.to_string(), "id": module_id.to_string(),
"package_instance_id": module_id.instance, "package_instance_id": module_id.instance,
@@ -49,7 +60,7 @@ pub fn build(project: &LoadedProject) -> Value {
}); });
json!({ json!({
"schema": SCHEMA, "schema": SCHEMA,
"schema_version": SCHEMA_VERSION, "schema_version": version,
"producer": { "producer": {
"name": "marqdo", "name": "marqdo",
"version": env!("CARGO_PKG_VERSION"), "version": env!("CARGO_PKG_VERSION"),
@@ -70,6 +81,15 @@ pub fn build(project: &LoadedProject) -> Value {
}) })
} }
fn has_loop_control(body: &[Stmt]) -> bool {
body.iter().any(|stmt| match stmt {
Stmt::Break { .. } | Stmt::Continue { .. } => true,
Stmt::Branch { arms, .. } => arms.iter().any(|arm| has_loop_control(&arm.body)),
Stmt::Loop { body, .. } => has_loop_control(body),
Stmt::Assign { .. } | Stmt::Eval { .. } | Stmt::Return { .. } => false,
})
}
/// Encode exactly the bytes written by `check --emit`. /// Encode exactly the bytes written by `check --emit`.
fn encode(project: &LoadedProject) -> Result<Vec<u8>, String> { fn encode(project: &LoadedProject) -> Result<Vec<u8>, String> {
serde_json::to_vec_pretty(&build(project)) serde_json::to_vec_pretty(&build(project))
@@ -293,6 +313,8 @@ fn stmt_json(stmt: &Stmt) -> Value {
"body": body.iter().map(stmt_json).collect::<Vec<_>>(), "body": body.iter().map(stmt_json).collect::<Vec<_>>(),
"span": span_json(*span), "span": span_json(*span),
}), }),
Stmt::Break { span } => json!({"kind": "break", "span": span_json(*span)}),
Stmt::Continue { span } => json!({"kind": "continue", "span": span_json(*span)}),
Stmt::Return { value, span } => json!({ Stmt::Return { value, span } => json!({
"kind": "return", "kind": "return",
"value": expr_json(value), "value": expr_json(value),
@@ -523,6 +545,7 @@ fn collect_calls(
expr_calls(project, module, function, condition, calls); expr_calls(project, module, function, condition, calls);
collect_calls(project, module, function, body, calls); collect_calls(project, module, function, body, calls);
} }
Stmt::Break { .. } | Stmt::Continue { .. } => {}
} }
} }
} }
+13
View File
@@ -351,6 +351,19 @@ fn observation_payload(event: ObservationEvent<'_>) -> (&'static str, Json) {
"span": span.map(span_json), "span": span.map(span_json),
}), }),
), ),
ObservationEvent::LoopTransfer {
frame_id,
transfer,
module_id,
span,
} => (
transfer.event_kind(),
json!({
"frame_id": frame_id.as_wire(),
"module_id": module_id,
"span": span_json(span),
}),
),
ObservationEvent::Effect { ObservationEvent::Effect {
operation, operation,
result_code, result_code,
+1
View File
@@ -648,6 +648,7 @@ fn collect_identifiers_stmts(stmts: &[Stmt], names: &mut std::collections::BTree
collect_identifiers_expr(condition, names); collect_identifiers_expr(condition, names);
collect_identifiers_stmts(body, names); collect_identifiers_stmts(body, names);
} }
Stmt::Break { .. } | Stmt::Continue { .. } => {}
} }
} }
} }
+1 -1
View File
@@ -314,7 +314,7 @@ struct CheckArgs {
/// Declare a plugin manifest for static export-signature checking. /// Declare a plugin manifest for static export-signature checking.
#[arg(long = "plugin", value_name = "PATH")] #[arg(long = "plugin", value_name = "PATH")]
plugin: Vec<PathBuf>, plugin: Vec<PathBuf>,
/// Write the public Analysis v2 projection (only on successful check). /// Write public Analysis JSON, using v3 for projects with loop transfers.
#[arg(long, value_name = "PATH")] #[arg(long, value_name = "PATH")]
emit: Option<PathBuf>, emit: Option<PathBuf>,
/// Machine readable JSON output. /// Machine readable JSON output.
+21 -10
View File
@@ -31,7 +31,10 @@ struct SupportedProtocols {
const SUPPORTED: SupportedProtocols = SupportedProtocols { const SUPPORTED: SupportedProtocols = SupportedProtocols {
tool: PROTOCOL_VERSION, tool: PROTOCOL_VERSION,
analysis: &[2], analysis: &[
crate::analysis::BASE_VERSION,
crate::analysis::LOOP_CONTROL_VERSION,
],
trace: &[2], trace: &[2],
}; };
@@ -297,7 +300,7 @@ fn negotiate_protocol(
let Some(requested) = requested else { let Some(requested) = requested else {
return Ok(()); return Ok(());
}; };
if requested.is_empty() || !requested.iter().any(|version| supported.contains(version)) { if shared_version(requested, supported).is_none() {
return Err(format!( return Err(format!(
"tool.protocol_incompatible: tool requires {name} version(s) {requested:?}, this core supports {supported:?}" "tool.protocol_incompatible: tool requires {name} version(s) {requested:?}, this core supports {supported:?}"
)); ));
@@ -305,6 +308,14 @@ fn negotiate_protocol(
Ok(()) Ok(())
} }
fn shared_version(requested: &[u32], supported: &[u32]) -> Option<u32> {
requested
.iter()
.copied()
.filter(|version| supported.contains(version))
.max()
}
fn is_valid_command(command: &str) -> bool { fn is_valid_command(command: &str) -> bool {
let mut bytes = command.bytes(); let mut bytes = command.bytes();
matches!(bytes.next(), Some(byte) if byte.is_ascii_lowercase()) matches!(bytes.next(), Some(byte) if byte.is_ascii_lowercase())
@@ -623,21 +634,21 @@ pub fn dispatch(args: &[OsString]) -> i32 {
process.env("MARQDO_BIN", bin); process.env("MARQDO_BIN", bin);
} }
process.env("MARQDO_TOOL_PROTOCOL", "1"); process.env("MARQDO_TOOL_PROTOCOL", "1");
if record if let Some(version) = record
.compatibility .compatibility
.analysis .analysis
.as_ref() .as_deref()
.is_some_and(|versions| versions.contains(&2)) .and_then(|versions| shared_version(versions, SUPPORTED.analysis))
{ {
process.env("MARQDO_PROTOCOL_ANALYSIS", "2"); process.env("MARQDO_PROTOCOL_ANALYSIS", version.to_string());
} }
if record if let Some(version) = record
.compatibility .compatibility
.trace .trace
.as_ref() .as_deref()
.is_some_and(|versions| versions.contains(&2)) .and_then(|versions| shared_version(versions, SUPPORTED.trace))
{ {
process.env("MARQDO_PROTOCOL_TRACE", "2"); process.env("MARQDO_PROTOCOL_TRACE", version.to_string());
} }
match process.status() { match process.status() {
Ok(status) => status.code().unwrap_or(1), Ok(status) => status.code().unwrap_or(1),
+143
View File
@@ -393,3 +393,146 @@ fn trace_records_calls_effects_and_status_without_secrets() {
serde_json::from_slice(&std::fs::read(&error_trace).unwrap()).unwrap(); serde_json::from_slice(&std::fs::read(&error_trace).unwrap()).unwrap();
assert_eq!(trace["run"]["status"], "runtime.division_by_zero"); assert_eq!(trace["run"]["status"], "runtime.division_by_zero");
} }
#[test]
fn multi_arm_branch_preserves_analysis_v2_and_carrier_positions() {
let dir = TempDir::new("else-if");
let source = r#"## @exec 分类
`params(数值: Int)`
1. `if 数值 < 0`
`return -1`
2. **else if 数值 == 0**
`return 0`
> *else if 数值 == 1*
>
> `return 1`
`else`
`return 2`
`end`
"#;
write(dir.path(), "index.mq.md", source);
let output = cli(
dir.path(),
&["check", "index.mq.md", "--emit", "analysis.json"],
);
assert!(output.status.success(), "{output:?}");
let analysis: serde_json::Value =
serde_json::from_slice(&std::fs::read(dir.path().join("analysis.json")).unwrap()).unwrap();
assert_eq!(analysis["schema_version"], 2);
assert_eq!(analysis["producer"]["markdown_profile"], "marqdo.md.v1");
let branch = &analysis["modules"][0]["functions"][0]["body"][0];
assert_eq!(branch["kind"], "branch");
let arms = branch["arms"].as_array().unwrap();
assert_eq!(arms.len(), 4);
for (arm, carrier) in arms.iter().zip([
"`if 数值 < 0`",
"**else if 数值 == 0**",
"*else if 数值 == 1*",
"`else`",
]) {
let start = source.find(carrier).unwrap();
let expected = serde_json::json!({"start": start, "end": start + carrier.len()});
assert_eq!(arm["span"], expected);
assert_eq!(arm["condition_span"], expected);
}
for (input, expected) in [("-3", "-1"), ("0", "0"), ("1", "1"), ("9", "2")] {
let output = cli(
dir.path(),
&[
"call",
"index.mq.md",
"分类",
"--arg",
&format!("数值={input}"),
"--json",
],
);
assert!(output.status.success(), "{output:?}");
let result: serde_json::Value = serde_json::from_slice(&output.stdout).unwrap();
assert_eq!(result["value"]["decimal"], expected);
}
}
#[test]
fn an_imported_loop_transfer_selects_v3_and_keeps_the_else_if_call_edge() {
let dir = TempDir::new("imported-loop");
write(
dir.path(),
"gate.mq.md",
"## @exec enabled\n\n`while true`\n\n`break`\n\n`end`\n\n`return true`\n",
);
write(
dir.path(),
"index.mq.md",
r#"---
import:
gate: "./gate.mq.md"
---
## @exec main
`if false`
`return 0`
`else if gate.enabled()`
`return 1`
`end`
"#,
);
let result = cli(
dir.path(),
&["check", "index.mq.md", "--emit", "analysis.json"],
);
assert!(result.status.success(), "{result:?}");
let analysis: serde_json::Value =
serde_json::from_slice(&std::fs::read(dir.path().join("analysis.json")).unwrap()).unwrap();
assert_eq!(analysis["schema_version"], 3);
let root = analysis["modules"]
.as_array()
.unwrap()
.iter()
.find(|module| module["relative_path"] == "index.mq.md")
.unwrap();
let calls = root["calls"].as_array().unwrap();
assert_eq!(calls.len(), 1);
assert_eq!(calls[0]["state"], "function");
assert!(calls[0]["target"]
.as_str()
.unwrap()
.ends_with("::gate.mq.md::enabled"));
}
#[test]
fn invalid_loop_control_rejects_check_and_does_not_execute_the_function() {
let dir = TempDir::new("invalid-loop");
write(
dir.path(),
"index.mq.md",
"## @exec main\n\n`打印(\"unreachable output\")`\n\n`break`\n",
);
write(dir.path(), "stale.json", "previous output");
let checked = cli(
dir.path(),
&["check", "index.mq.md", "--emit", "stale.json", "--json"],
);
assert_eq!(checked.status.code(), Some(1), "{checked:?}");
assert!(String::from_utf8_lossy(&checked.stdout).contains("sem.break_outside_loop"));
assert!(!String::from_utf8_lossy(&checked.stdout).contains("unreachable output"));
assert!(!dir.path().join("stale.json").exists());
let run = cli(dir.path(), &["run", "index.mq.md"]);
assert_eq!(run.status.code(), Some(1), "{run:?}");
assert!(run.stdout.is_empty());
}
+106
View File
@@ -765,3 +765,109 @@ fn broken_pipe_makes_the_run_fail_instead_of_running_forever() {
"expected a transport diagnostic on stderr: {stderr}" "expected a transport diagnostic on stderr: {stderr}"
); );
} }
#[test]
fn loop_transfers_are_ordered_structural_events_with_source_spans() {
use sha2::{Digest, Sha256};
let dir = TempDir::new("loop-transfers");
let source = r#"## @exec main
`索引 = 0`
`while true`
`索引 = 索引 + 1`
`if 索引 == 1`
`continue`
`else if 索引 == 2`
`break`
`end`
`end`
`return 索引`
"#;
dir.write("index.mq.md", source);
let checked = cli(
dir.path(),
&["check", "index.mq.md", "--emit", "analysis.json"],
);
assert!(checked.status.success(), "{checked:?}");
let analysis_bytes = fs::read(dir.path().join("analysis.json")).unwrap();
let analysis: Value = serde_json::from_slice(&analysis_bytes).unwrap();
assert_eq!(analysis["schema_version"], 3);
let module = &analysis["modules"][0];
let branch = &module["functions"][0]["body"][1]["body"][1];
let output = cli(
dir.path(),
&[
"run",
"index.mq.md",
"--mode",
"pure",
"--event-stream",
"jsonl",
"--trace-file",
"trace.json",
],
);
assert!(output.status.success(), "{output:?}");
let events = parse_events(&output.stdout);
assert_envelope(&events);
assert_eq!(events.last().unwrap()["kind"], "run.completed");
let trace: Value =
serde_json::from_slice(&fs::read(dir.path().join("trace.json")).unwrap()).unwrap();
assert_eq!(trace["schema_version"], 2);
assert_eq!(
trace["source"]["analysis_digest"],
format!("sha256:{:x}", Sha256::digest(analysis_bytes))
);
let kinds = |events: &[Value]| {
events
.iter()
.filter_map(|event| match event["kind"].as_str() {
Some("loop.iteration") => Some("loop.iteration"),
Some("control.continue") => Some("control.continue"),
Some("control.break") => Some("control.break"),
Some("return") => Some("return"),
_ => None,
})
.collect::<Vec<_>>()
};
let expected = [
"loop.iteration",
"control.continue",
"loop.iteration",
"control.break",
"return",
];
assert_eq!(kinds(&events), expected);
let trace_events = trace["events"].as_array().unwrap();
assert_eq!(kinds(trace_events), expected);
let frame = &events_of(&events, "call.enter")[0]["payload"]["frame_id"];
for (index, keyword) in ["continue", "break"].iter().enumerate() {
let kind = format!("control.{keyword}");
let carrier = format!("`{keyword}`");
let start = source.find(&carrier).unwrap();
let span = serde_json::json!({"start": start, "end": start + carrier.len()});
let payload = &events_of(&events, &kind)[0]["payload"];
assert_eq!(payload["frame_id"], *frame);
assert_eq!(payload["module_id"], module["id"]);
assert_eq!(payload["span"], span);
assert_eq!(payload.as_object().unwrap().len(), 3);
let event = &events_of(trace_events, &kind)[0];
assert_eq!(event["module_id"], module["id"]);
assert_eq!(event["span"], span);
assert!(event["detail"].is_null());
let statement = &branch["arms"][index]["body"][0];
assert_eq!(statement["kind"], *keyword);
assert_eq!(statement["span"], span);
}
}
+32
View File
@@ -429,3 +429,35 @@ fn narration_removal_preserves_execution() {
); );
assert_eq!(values[0], marqdo_value::Value::int(120)); assert_eq!(values[0], marqdo_value::Value::int(120));
} }
#[test]
fn control_flow_ir_is_independent_of_lists_quotes_and_prose() {
let statements = [
"`i = 0`",
"`while true`",
"`i = i + 1`",
"`if i == 1`",
"`continue`",
"`else if i == 2`",
"`break`",
"`end`",
"`end`",
"`return i`",
];
let plain = format!("## @exec main\n\n{}\n", statements.join("\n\n"));
let adorned = statements
.iter()
.enumerate()
.map(|(index, statement)| match index % 3 {
0 => format!("1. {statement} Ordinary prose follows the carrier."),
1 => format!("> {statement}"),
_ => format!("- {statement}"),
})
.collect::<Vec<_>>()
.join("\n\n");
let decorated = format!("## @exec main\n\n{adorned}\n");
assert_eq!(
executable_projection(&plain),
executable_projection(&decorated)
);
}
+11
View File
@@ -376,6 +376,17 @@ fn protocol_negotiation_accepts_declared_versions_and_rejects_disjoint_ones() {
assert!(text.contains("analysis=2"), "{text}"); assert!(text.contains("analysis=2"), "{text}");
assert!(text.contains("trace=2"), "{text}"); assert!(text.contains("trace=2"), "{text}");
let manifest = write_tool(dir.path(), "proto-v3", "");
let mut declared: serde_json::Value =
serde_json::from_slice(&std::fs::read(&manifest).unwrap()).unwrap();
declared["compatibility"]["analysis"] = serde_json::json!([2, 3]);
std::fs::write(&manifest, declared.to_string()).unwrap();
let install = cli(&home, &["tool", "install", manifest.to_str().unwrap()]);
assert_eq!(install.status.code(), Some(0), "{}", stderr(&install));
let output = cli(&home, &["proto-v3"]);
assert_eq!(output.status.code(), Some(7), "{}", stderr(&output));
assert!(stdout(&output).contains("analysis=3"));
for (compat, tag) in [ for (compat, tag) in [
("\"analysis\":[99]", "analysis-disjoint"), ("\"analysis\":[99]", "analysis-disjoint"),
("\"analysis\":[]", "analysis-empty"), ("\"analysis\":[]", "analysis-empty"),
+58 -4
View File
@@ -2,7 +2,7 @@
//! //!
//! One Markdown carrier holds exactly one payload. This module is the only //! One Markdown carrier holds exactly one payload. This module is the only
//! place that decides whether that payload is a control statement //! place that decides whether that payload is a control statement
//! (`if`/`else`/`while`/`end`/`return`), a `params(...)` declaration, or an //! (`if`/`else if`/`else`/`while`/`break`/`continue`/`end`/`return`), a `params(...)` declaration, or an
//! ordinary assignment/expression. The frontend still owns pairing the control //! ordinary assignment/expression. The frontend still owns pairing the control
//! words into blocks; this module owns their lexical recognition and the //! words into blocks; this module owns their lexical recognition and the
//! expression grammar they embed. //! expression grammar they embed.
@@ -22,10 +22,16 @@ use marqdo_span::Span;
pub enum PayloadStatement { pub enum PayloadStatement {
/// `if <expr>` /// `if <expr>`
If(Expr), If(Expr),
/// `else if <expr>`
ElseIf(Expr),
/// `else` (no expression) /// `else` (no expression)
Else, Else,
/// `while <expr>` /// `while <expr>`
While(Expr), While(Expr),
/// Exit the closest enclosing loop.
Break,
/// Recheck the closest enclosing loop condition.
Continue,
/// `end` (no expression) /// `end` (no expression)
End, End,
/// `return <expr>` /// `return <expr>`
@@ -65,7 +71,12 @@ pub fn parse_payload_statement(source: &str) -> Result<PayloadStatement, ParseEr
let tokens = lexer::tokenize(trimmed)?; let tokens = lexer::tokenize(trimmed)?;
let first = tokens.first().expect("tokenize always returns EOF"); let first = tokens.first().expect("tokenize always returns EOF");
match first.kind { match &first.kind {
TokenKind::Ident(name) if matches!(tokens[1].kind, TokenKind::Eof) => match name.as_str() {
"break" => Ok(PayloadStatement::Break),
"continue" => Ok(PayloadStatement::Continue),
_ => parse_statement(trimmed).map(PayloadStatement::Ordinary),
},
TokenKind::If => { TokenKind::If => {
let expr = control_expression(trimmed, first.span, "if")?; let expr = control_expression(trimmed, first.span, "if")?;
Ok(PayloadStatement::If(expr)) Ok(PayloadStatement::If(expr))
@@ -79,6 +90,11 @@ pub fn parse_payload_statement(source: &str) -> Result<PayloadStatement, ParseEr
Ok(PayloadStatement::Return(expr)) Ok(PayloadStatement::Return(expr))
} }
TokenKind::Else => { TokenKind::Else => {
if matches!(tokens[1].kind, TokenKind::If) {
let keyword = Span::new(first.span.start, tokens[1].span.end);
let expr = control_expression(trimmed, keyword, "else if")?;
return Ok(PayloadStatement::ElseIf(expr));
}
require_only_keyword(&tokens, "else")?; require_only_keyword(&tokens, "else")?;
Ok(PayloadStatement::Else) Ok(PayloadStatement::Else)
} }
@@ -128,6 +144,7 @@ mod tests {
fn expr_of(source: &str) -> Expr { fn expr_of(source: &str) -> Expr {
match parse_payload_statement(source).expect("valid payload") { match parse_payload_statement(source).expect("valid payload") {
PayloadStatement::If(expr) PayloadStatement::If(expr)
| PayloadStatement::ElseIf(expr)
| PayloadStatement::While(expr) | PayloadStatement::While(expr)
| PayloadStatement::Return(expr) => expr, | PayloadStatement::Return(expr) => expr,
other => panic!("unexpected payload: {other:?}"), other => panic!("unexpected payload: {other:?}"),
@@ -136,7 +153,7 @@ mod tests {
#[test] #[test]
fn parses_control_statements_with_payload_relative_spans() { fn parses_control_statements_with_payload_relative_spans() {
for keyword in ["if", "while", "return"] { for keyword in ["if", "else if", "while", "return"] {
let source = format!("{keyword} x > 0"); let source = format!("{keyword} x > 0");
let expr = expr_of(&source); let expr = expr_of(&source);
assert_eq!(expr.span().start, keyword.len() + 1); assert_eq!(expr.span().start, keyword.len() + 1);
@@ -159,7 +176,16 @@ mod tests {
#[test] #[test]
fn keywords_require_whitespace_and_an_expression() { fn keywords_require_whitespace_and_an_expression() {
for source in ["if", "while", "return", "if(x)", "while(1)", "return(x)"] { for source in [
"if",
"else if",
"while",
"return",
"if(x)",
"else if(x)",
"while(1)",
"return(x)",
] {
assert!( assert!(
parse_payload_statement(source).is_err(), parse_payload_statement(source).is_err(),
"{source} must be rejected" "{source} must be rejected"
@@ -167,9 +193,37 @@ mod tests {
} }
} }
#[test]
fn loop_control_keywords_are_contextual() {
assert_eq!(
parse_payload_statement("break").unwrap(),
PayloadStatement::Break
);
assert_eq!(
parse_payload_statement("continue").unwrap(),
PayloadStatement::Continue
);
for source in [
"break(1)",
"continue = 1",
"(break)",
"break + continue",
"continue_work()",
] {
assert!(matches!(
parse_payload_statement(source).unwrap(),
PayloadStatement::Ordinary(_)
));
}
for source in ["break 2", "continue outer", "break if true"] {
assert!(parse_payload_statement(source).is_err(), "{source}");
}
}
#[test] #[test]
fn control_expressions_must_consume_the_payload() { fn control_expressions_must_consume_the_payload() {
assert!(parse_payload_statement("if x > 0:").is_err()); assert!(parse_payload_statement("if x > 0:").is_err());
assert!(parse_payload_statement("else if x > 0:").is_err());
assert!(parse_payload_statement("if x y").is_err()); assert!(parse_payload_statement("if x y").is_err());
} }
+5 -1
View File
@@ -213,7 +213,10 @@ fn collect_assigned(stmts: &[Stmt], out: &mut BTreeSet<String>) {
} }
} }
Stmt::Loop { body, .. } => collect_assigned(body, out), Stmt::Loop { body, .. } => collect_assigned(body, out),
Stmt::Eval { .. } | Stmt::Return { .. } => {} Stmt::Eval { .. }
| Stmt::Return { .. }
| Stmt::Break { .. }
| Stmt::Continue { .. } => {}
} }
} }
} }
@@ -257,6 +260,7 @@ impl<'a> Binder<'a> {
self.expr(condition); self.expr(condition);
self.stmts(body); self.stmts(body);
} }
Stmt::Break { .. } | Stmt::Continue { .. } => {}
} }
} }
} }
+151 -102
View File
@@ -3,16 +3,12 @@
//! Parameters come only from free reads of executable expressions. Prose, //! Parameters come only from free reads of executable expressions. Prose,
//! headings, inert code spans and natural language never introduce parameters. //! headings, inert code spans and natural language never introduce parameters.
//! //!
//! The analysis tracks, for every program point: //! Each reachable path tracks definite and possible assignments. Sequences
//! * `must` – variables definitely assigned on every path from entry; //! merge fallthrough, break and continue separately, so a transfer never
//! * `may` – variables assigned on at least one path; //! contributes bindings from the statements it skips. A return ends the path.
//! * `ambiguous` – variables that may have been assigned before the read on
//! some path but not on all paths, which makes the variable's identity
//! ambiguous (blueprint S-04) rather than silently inventing a parameter.
//! //!
//! Loop bodies get special treatment: their first iteration starts from the //! The first iteration starts from the pre-loop state. A first read before a
//! pre-loop state, so a read of an entry variable inside a loop is a parameter //! body assignment can therefore still be a parameter (the counter case).
//! candidate even though the body also assigns it (the classic counter case).
use std::collections::{BTreeMap, BTreeSet}; use std::collections::{BTreeMap, BTreeSet};
@@ -45,7 +41,6 @@ pub struct ParamCandidate {
struct State { struct State {
must: BTreeSet<String>, must: BTreeSet<String>,
may: BTreeSet<String>, may: BTreeSet<String>,
ambiguous: BTreeSet<String>,
} }
impl State { impl State {
@@ -53,18 +48,46 @@ impl State {
State { State {
must: self.must.intersection(&other.must).cloned().collect(), must: self.must.intersection(&other.must).cloned().collect(),
may: self.may.union(&other.may).cloned().collect(), may: self.may.union(&other.may).cloned().collect(),
ambiguous: self.ambiguous.union(&other.ambiguous).cloned().collect(),
} }
} }
} }
/// Join only reachable paths. An absent path contributes no assignments.
fn merge_paths(left: &mut Option<State>, right: Option<State>) {
if let Some(right) = right {
*left = Some(match left.take() {
Some(left) => left.join(&right),
None => right,
});
}
}
#[derive(Default)]
struct Flow {
next: Option<State>,
breaks: Option<State>,
continues: Option<State>,
}
impl Flow {
fn merge(&mut self, other: Self) {
merge_paths(&mut self.next, other.next);
self.merge_loop_transfers(other.breaks, other.continues);
}
fn merge_loop_transfers(&mut self, breaks: Option<State>, continues: Option<State>) {
merge_paths(&mut self.breaks, breaks);
merge_paths(&mut self.continues, continues);
}
}
struct Analyzer<'a> { struct Analyzer<'a> {
/// Names that are parameters/locals/builtins/imports and therefore never /// Names that are parameters/locals/builtins/imports and therefore never
/// reported as unknown; used for explicit signatures. /// reported as unknown; used for explicit signatures.
known: Option<&'a BTreeSet<String>>, known: Option<&'a BTreeSet<String>>,
reads: BTreeMap<String, Span>, reads: BTreeMap<String, Span>,
diagnostics: Vec<Diagnostic>, diagnostics: Vec<Diagnostic>,
ambiguous_reported: BTreeSet<String>, ambiguous_reads: BTreeMap<String, Span>,
unknown_reported: BTreeSet<String>, unknown_reported: BTreeSet<String>,
} }
@@ -74,7 +97,7 @@ impl<'a> Analyzer<'a> {
known, known,
reads: BTreeMap::new(), reads: BTreeMap::new(),
diagnostics: Vec::new(), diagnostics: Vec::new(),
ambiguous_reported: BTreeSet::new(), ambiguous_reads: BTreeMap::new(),
unknown_reported: BTreeSet::new(), unknown_reported: BTreeSet::new(),
} }
} }
@@ -83,20 +106,8 @@ impl<'a> Analyzer<'a> {
if state.must.contains(name) { if state.must.contains(name) {
return; return;
} }
if state.ambiguous.contains(name) { if state.may.contains(name) {
if !self.ambiguous_reported.contains(name) { self.ambiguous_reads.entry(name.to_string()).or_insert(span);
self.ambiguous_reported.insert(name.to_string());
self.diagnostics.push(
Diagnostic::error(
codes::SYMBOL_UNINITIALIZED,
Some(span),
format!("`{name}` may be read before it is assigned"),
)
.with_hint(
"assign it on every path before this read, or pass it in as a parameter",
),
);
}
return; return;
} }
if let Some(known) = self.known { if let Some(known) = self.known {
@@ -169,107 +180,104 @@ impl<'a> Analyzer<'a> {
} }
} }
fn assign(&self, name: &str, state: &mut State) { fn analyze_stmts(&mut self, stmts: &[Stmt], state: State) -> Flow {
state.must.insert(name.to_string()); let mut flow = Flow {
state.may.insert(name.to_string()); next: Some(state),
state.ambiguous.insert(name.to_string()); ..Flow::default()
} };
fn analyze_stmts(&mut self, stmts: &[Stmt], mut state: State) -> State {
for stmt in stmts { for stmt in stmts {
state = match stmt { let Some(mut state) = flow.next.take() else {
break;
};
flow.next = match stmt {
Stmt::Assign { target, value, .. } => { Stmt::Assign { target, value, .. } => {
match target { match target {
PlaceTarget::Local { name, .. } => { PlaceTarget::Local { name, .. } => {
// Preserve v1 order: the RHS is read before the
// local rebinding makes the name definitely
// assigned.
self.read_expr(value, &state); self.read_expr(value, &state);
self.assign(name, &mut state); state.must.insert(name.clone());
state.may.insert(name.clone());
} }
PlaceTarget::Index { base, index, .. } => { PlaceTarget::Index { base, index, .. } => {
// Runtime order for an index place is base, index, // Keep the runtime's evaluation order.
// RHS; reads in the place are free reads like any
// other.
self.read_expr(base, &state); self.read_expr(base, &state);
self.read_expr(index, &state); self.read_expr(index, &state);
self.read_expr(value, &state); self.read_expr(value, &state);
} }
} }
state Some(state)
} }
Stmt::Eval { expr, .. } => { Stmt::Eval { expr, .. } => {
self.read_expr(expr, &state); self.read_expr(expr, &state);
state Some(state)
} }
Stmt::Return { value, .. } => { Stmt::Return { value, .. } => {
self.read_expr(value, &state); self.read_expr(value, &state);
state None
}
Stmt::Break { .. } => {
merge_paths(&mut flow.breaks, Some(state));
None
}
Stmt::Continue { .. } => {
merge_paths(&mut flow.continues, Some(state));
None
}
Stmt::Branch { arms, .. } => {
let branch = self.analyze_branch(arms, state);
flow.merge_loop_transfers(branch.breaks, branch.continues);
branch.next
} }
Stmt::Branch { arms, .. } => self.analyze_branch(arms, state),
Stmt::Loop { Stmt::Loop {
condition, body, .. condition, body, ..
} => { } => self.analyze_loop(condition, body, state),
self.read_expr(condition, &state);
// First iteration starts from the pre-loop state: body
// assignments must not flag pre-loop reads as ambiguous.
let body_out = self.analyze_stmts(
body,
State {
must: state.must.clone(),
may: state.may.clone(),
ambiguous: state.ambiguous.clone(),
},
);
State {
must: state.must.clone(),
may: body_out
.may
.union(&state.may)
.cloned()
.collect::<BTreeSet<_>>(),
ambiguous: body_out
.ambiguous
.union(&state.ambiguous)
.cloned()
.collect::<BTreeSet<_>>(),
}
}
}; };
} }
state flow
} }
fn analyze_branch(&mut self, arms: &[BranchArm], state: State) -> State { fn analyze_branch(&mut self, arms: &[BranchArm], state: State) -> Flow {
// Conditions are evaluated in order against the incoming state. let mut flow = Flow::default();
for arm in arms { for arm in arms {
// Only earlier false conditions lead to this arm. Conditions do
// not change the assignment state of the current frame.
self.read_expr(&arm.condition, &state); self.read_expr(&arm.condition, &state);
if arm.condition != Expr::Bool(false) {
flow.merge(self.analyze_stmts(&arm.body, state.clone()));
}
if arm.condition == Expr::Bool(true) {
return flow;
}
} }
// The branch may match no arm, so the incoming state joins every arm's merge_paths(&mut flow.next, Some(state));
// state; variables assigned only inside an arm stay "may assigned". flow
let mut joined: Option<State> = Some(State { }
must: state.must.clone(),
may: state.may.clone(), fn analyze_loop(&mut self, condition: &Expr, body: &[Stmt], state: State) -> Option<State> {
ambiguous: state.ambiguous.clone(), self.read_expr(condition, &state);
}); if *condition == Expr::Bool(false) {
for arm in arms { return Some(state);
let arm_out = self.analyze_stmts(
&arm.body,
State {
must: state.must.clone(),
may: state.may.clone(),
ambiguous: state.ambiguous.clone(),
},
);
joined = Some(match joined {
None => arm_out,
Some(previous) => previous.join(&arm_out),
});
} }
match joined {
Some(joined) => joined, let Flow {
None => state, mut next,
mut breaks,
continues,
} = self.analyze_stmts(body, state.clone());
merge_paths(&mut next, continues);
// A later break can inherit assignments from an earlier iteration.
// It can also occur on the first, so only "may" gains those bindings.
if let (Some(breaks), Some(backedge)) = (&mut breaks, &next) {
breaks.may.extend(backedge.may.iter().cloned());
} }
if *condition == Expr::Bool(true) {
return breaks;
}
// A false condition may be seen before any iteration or after a
// backedge. A break exits directly and a return never reaches here.
merge_paths(&mut next, Some(state));
merge_paths(&mut next, breaks);
next
} }
} }
@@ -294,7 +302,34 @@ pub fn infer(
names names
}); });
let mut analyzer = Analyzer::new(known.as_ref()); let mut analyzer = Analyzer::new(known.as_ref());
analyzer.analyze_stmts(stmts, State::default()); let initial = signature.map_or_else(State::default, |signature| {
let bound: BTreeSet<_> = signature
.params
.iter()
.map(|param| param.name.clone())
.collect();
State {
must: bound.clone(),
may: bound,
}
});
analyzer.analyze_stmts(stmts, initial);
for (name, span) in analyzer.ambiguous_reads {
// A reachable free read makes the name an entry parameter throughout
// an inferred function, including before or after a local rebinding.
if !analyzer.reads.contains_key(&name) {
analyzer.diagnostics.push(
Diagnostic::error(
codes::SYMBOL_UNINITIALIZED,
Some(span),
format!("`{name}` may be read before it is assigned"),
)
.with_hint(
"assign it on every path before this read, or pass it in as a parameter",
),
);
}
}
let mut params: Vec<ParamCandidate> = analyzer let mut params: Vec<ParamCandidate> = analyzer
.reads .reads
.iter() .iter()
@@ -391,7 +426,14 @@ mod tests {
}, },
ret("n"), ret("n"),
]; ];
assert_eq!(params(&stmts), vec!["n".to_string()]); let inference = infer(&stmts, None, &BTreeSet::new());
assert_eq!(inference.params[0].name, "n");
assert_eq!(inference.params.len(), 1);
assert!(
inference.diagnostics.is_empty(),
"{:?}",
inference.diagnostics
);
} }
#[test] #[test]
@@ -399,7 +441,7 @@ mod tests {
let stmts = vec![ let stmts = vec![
Stmt::Branch { Stmt::Branch {
arms: vec![BranchArm { arms: vec![BranchArm {
condition: parse_expression("true").unwrap(), condition: parse_expression("flag").unwrap(),
condition_span: Span::new(0, 0), condition_span: Span::new(0, 0),
body: vec![assign("x", "1")], body: vec![assign("x", "1")],
span: Span::new(0, 0), span: Span::new(0, 0),
@@ -409,7 +451,14 @@ mod tests {
ret("x"), ret("x"),
]; ];
let inference = infer(&stmts, None, &BTreeSet::new()); let inference = infer(&stmts, None, &BTreeSet::new());
assert!(inference.params.is_empty()); assert_eq!(
inference
.params
.iter()
.map(|param| param.name.as_str())
.collect::<Vec<_>>(),
["flag"]
);
assert!(inference assert!(inference
.diagnostics .diagnostics
.iter() .iter()
+128 -92
View File
@@ -8,7 +8,7 @@
use marqdo_expression::{ use marqdo_expression::{
parse_payload_statement, AssignTarget, Expr, PayloadStatement as Payload, StatementKind, parse_payload_statement, AssignTarget, Expr, PayloadStatement as Payload, StatementKind,
}; };
use marqdo_ir::{PlaceTarget, Stmt}; use marqdo_ir::{BranchArm, PlaceTarget, Stmt};
use marqdo_markdown::{MarkdownDocument, MdKind, MdNode}; use marqdo_markdown::{MarkdownDocument, MdKind, MdNode};
use marqdo_span::Span; use marqdo_span::Span;
use marqdo_value::{codes, Diagnostic}; use marqdo_value::{codes, Diagnostic};
@@ -100,10 +100,10 @@ struct Mapper {
} }
#[derive(Debug, Clone, Copy, PartialEq, Eq)] #[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Stop { enum ArmContext {
End, Outside,
Else, Conditional,
Eof, Default,
} }
struct RawPayload { struct RawPayload {
@@ -139,14 +139,12 @@ impl Mapper {
self.extract(block, &mut raw, true); self.extract(block, &mut raw, true);
} }
let mut position = 0; let mut position = 0;
let (stmts, stop) = self.sequence(&raw, &mut position, false, false); let stmts = self.sequence(&raw, &mut position, ArmContext::Outside, false);
if stop != Stop::Eof { if let Some(node) = raw.get(position) {
// `sequence` leaves `position` on the stray `end` payload, so the // The only delimiter that can stop the segment is a stray `end`.
// diagnostic points at the keyword instead of the previous
// statement. A control frame may never close across a heading.
self.error( self.error(
codes::SEM_UNMATCHED_END, codes::SEM_UNMATCHED_END,
raw.get(position).map(|node| node.span), Some(node.span),
"`end` has no open `if`/`while` in this heading segment", "`end` has no open `if`/`while` in this heading segment",
); );
} }
@@ -215,7 +213,11 @@ impl Mapper {
return; return;
} }
if let Some(mut payload) = self.parse_payload(&text, &segments) { if let Some(mut payload) = self.parse_payload(&text, &segments) {
if let Payload::If(expr) | Payload::While(expr) | Payload::Return(expr) = &mut payload { if let Payload::If(expr)
| Payload::ElseIf(expr)
| Payload::While(expr)
| Payload::Return(expr) = &mut payload
{
segments.rewrite_expr(expr); segments.rewrite_expr(expr);
} }
out.push(RawPayload { out.push(RawPayload {
@@ -243,102 +245,78 @@ impl Mapper {
} }
} }
/// Read a body up to its next delimiter without consuming that delimiter.
fn sequence( fn sequence(
&mut self, &mut self,
nodes: &[RawPayload], nodes: &[RawPayload],
position: &mut usize, position: &mut usize,
stop_on_else: bool, arm: ArmContext,
in_else_body: bool, in_loop: bool,
) -> (Vec<Stmt>, Stop) { ) -> Vec<Stmt> {
let mut out = Vec::new(); let mut out = Vec::new();
while *position < nodes.len() { while let Some(raw) = nodes.get(*position) {
let raw = &nodes[*position];
match &raw.payload { match &raw.payload {
Payload::Else => { Payload::Else | Payload::ElseIf(_) => {
if stop_on_else { if arm == ArmContext::Conditional {
return (out, Stop::Else); break;
} }
self.error( let (code, message) = match (&raw.payload, arm) {
if in_else_body { (Payload::Else, ArmContext::Default) => {
codes::SEM_DUPLICATE_ELSE (codes::SEM_DUPLICATE_ELSE, "`if` has more than one `else`")
} else {
codes::SEM_UNMATCHED_ELSE
},
Some(raw.span),
if in_else_body {
"`if` has more than one `else`"
} else {
"`else` has no open `if`"
},
);
*position += 1;
}
Payload::End => {
return (out, Stop::End);
}
Payload::If(condition) => {
self.executed = true;
let condition = condition.clone();
let span = raw.span;
*position += 1;
let (then_body, stop) = self.sequence(nodes, position, true, false);
let mut else_body = Vec::new();
let finish = match stop {
Stop::Else => {
*position += 1;
let (body, stop) = self.sequence(nodes, position, false, true);
else_body = body;
stop
} }
other => other, (Payload::Else, _) => {
(codes::SEM_UNMATCHED_ELSE, "`else` has no open `if`")
}
(_, ArmContext::Default) => (
codes::SEM_ELSE_IF_AFTER_ELSE,
"`else if` cannot follow the final `else`",
),
(_, _) => (codes::SEM_UNMATCHED_ELSE_IF, "`else if` has no open `if`"),
}; };
if finish != Stop::End { self.error(code, Some(raw.span), message);
self.error( *position += 1;
codes::SEM_UNCLOSED_CONTROL, }
Some(span), Payload::End => break,
"`if` is not closed by `end`", Payload::If(_) => {
); self.executed = true;
} else { out.push(self.branch(nodes, position, in_loop));
*position += 1;
}
let mut arms = vec![marqdo_ir::BranchArm {
condition,
condition_span: span,
body: then_body,
span,
}];
if !else_body.is_empty() {
arms.push(marqdo_ir::BranchArm {
condition: Expr::Bool(true),
condition_span: span,
body: else_body,
span,
});
}
out.push(Stmt::Branch { arms, span });
} }
Payload::While(condition) => { Payload::While(condition) => {
self.executed = true; self.executed = true;
let condition = condition.clone();
let span = raw.span;
*position += 1; *position += 1;
let (body, stop) = self.sequence(nodes, position, false, false); let body = self.sequence(nodes, position, ArmContext::Outside, true);
if stop != Stop::End { self.close_block(nodes, position, raw.span, "while");
self.error(
codes::SEM_UNCLOSED_CONTROL,
Some(span),
"`while` is not closed by `end`",
);
} else {
*position += 1;
}
out.push(Stmt::Loop { out.push(Stmt::Loop {
condition, condition: condition.clone(),
condition_span: span, condition_span: raw.span,
body, body,
span, span: raw.span,
}); });
} }
Payload::Break | Payload::Continue => {
self.executed = true;
let span = raw.span;
let (statement, code, keyword) = match raw.payload {
Payload::Break => {
(Stmt::Break { span }, codes::SEM_BREAK_OUTSIDE_LOOP, "break")
}
_ => (
Stmt::Continue { span },
codes::SEM_CONTINUE_OUTSIDE_LOOP,
"continue",
),
};
if in_loop {
out.push(statement);
} else {
self.error(
code,
Some(span),
format!("`{keyword}` requires an open loop in this heading segment"),
);
}
*position += 1;
}
Payload::Return(value) => { Payload::Return(value) => {
self.executed = true; self.executed = true;
out.push(Stmt::Return { out.push(Stmt::Return {
@@ -406,6 +384,64 @@ impl Mapper {
} }
} }
} }
(out, Stop::Eof) out
}
fn branch(&mut self, nodes: &[RawPayload], position: &mut usize, in_loop: bool) -> Stmt {
let span = nodes[*position].span;
let mut arms = Vec::new();
while let Some(raw) = nodes.get(*position) {
let condition = match &raw.payload {
Payload::If(condition) | Payload::ElseIf(condition) => condition,
_ => break,
};
*position += 1;
let body = self.sequence(nodes, position, ArmContext::Conditional, in_loop);
arms.push(BranchArm {
condition: condition.clone(),
condition_span: raw.span,
body,
span: raw.span,
});
}
if let Some(raw) = nodes
.get(*position)
.filter(|raw| matches!(raw.payload, Payload::Else))
{
*position += 1;
let body = self.sequence(nodes, position, ArmContext::Default, in_loop);
// An empty fallback is ordinary fallthrough.
if !body.is_empty() {
arms.push(BranchArm {
condition: Expr::Bool(true),
condition_span: raw.span,
body,
span: raw.span,
});
}
}
self.close_block(nodes, position, span, "if");
Stmt::Branch { arms, span }
}
fn close_block(
&mut self,
nodes: &[RawPayload],
position: &mut usize,
opener: Span,
keyword: &str,
) {
if matches!(
nodes.get(*position).map(|raw| &raw.payload),
Some(Payload::End)
) {
*position += 1;
} else {
self.error(
codes::SEM_UNCLOSED_CONTROL,
Some(opener),
format!("`{keyword}` is not closed by `end`"),
);
}
} }
} }
+19
View File
@@ -1047,6 +1047,25 @@ impl Host for StdHost {
false, false,
) )
} }
RuntimeObservation::LoopTransfer {
frame_id,
transfer,
module_id,
span,
} => {
let Some(frame_id) = frame_id else {
return Ok(());
};
self.emit_observation(
ObservationEvent::LoopTransfer {
frame_id,
transfer,
module_id,
span,
},
false,
)
}
RuntimeObservation::VariableAssigned { RuntimeObservation::VariableAssigned {
frame_id, frame_id,
name, name,
+1 -1
View File
@@ -30,7 +30,7 @@ pub use handles::{contains_plugin_handle, PluginHandleTable};
pub use host::{arity, expect_text, Host, HostOp, StdHost}; pub use host::{arity, expect_text, Host, HostOp, StdHost};
pub use marqdo_sandbox::{PlatformCapabilities, SandboxMode, StrictIsolation}; pub use marqdo_sandbox::{PlatformCapabilities, SandboxMode, StrictIsolation};
pub use observe::{ pub use observe::{
encode_value, estimate_event_bytes, FrameId, ObservationConfig, ObservationError, encode_value, estimate_event_bytes, FrameId, LoopTransfer, ObservationConfig, ObservationError,
ObservationEvent, ObservationSink, ObservedValue, ParameterSource, RuntimeObservation, ObservationEvent, ObservationSink, ObservedValue, ParameterSource, RuntimeObservation,
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,
+34
View File
@@ -193,6 +193,13 @@ pub enum ObservationEvent<'a> {
module_id: &'a str, module_id: &'a str,
span: Option<Span>, span: Option<Span>,
}, },
/// An explicit loop control statement executed.
LoopTransfer {
frame_id: FrameId,
transfer: LoopTransfer,
module_id: &'a str,
span: Span,
},
/// The host completed a controlled effect attempt. /// The host completed a controlled effect attempt.
Effect { Effect {
operation: &'a str, operation: &'a str,
@@ -230,6 +237,25 @@ pub enum ObservationEvent<'a> {
}, },
} }
/// The action carried by a structured loop transfer observation.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum LoopTransfer {
/// Exit the enclosing loop.
Break,
/// Proceed to the enclosing loop's next condition check.
Continue,
}
impl LoopTransfer {
/// The event kind in Trace and Execution Events.
pub fn event_kind(self) -> &'static str {
match self {
Self::Break => "control.break",
Self::Continue => "control.continue",
}
}
}
/// Borrowed runtime notification accepted by [`crate::Host::observe_runtime`]. /// Borrowed runtime notification accepted by [`crate::Host::observe_runtime`].
/// ///
/// Every variant carries an `Option<FrameId>`; observation of values and /// Every variant carries an `Option<FrameId>`; observation of values and
@@ -257,6 +283,13 @@ pub enum RuntimeObservation<'a> {
module_id: &'a str, module_id: &'a str,
span: Option<Span>, span: Option<Span>,
}, },
/// An explicit loop control statement executed.
LoopTransfer {
frame_id: Option<FrameId>,
transfer: LoopTransfer,
module_id: &'a str,
span: Span,
},
/// A local variable assignment committed. /// A local variable assignment committed.
VariableAssigned { VariableAssigned {
frame_id: Option<FrameId>, frame_id: Option<FrameId>,
@@ -498,6 +531,7 @@ pub fn estimate_event_bytes(event: &ObservationEvent<'_>) -> u64 {
} }
ObservationEvent::BranchEval { module_id, .. } ObservationEvent::BranchEval { module_id, .. }
| ObservationEvent::LoopIteration { module_id, .. } | ObservationEvent::LoopIteration { module_id, .. }
| ObservationEvent::LoopTransfer { module_id, .. }
| ObservationEvent::Effect { module_id, .. } => { | ObservationEvent::Effect { module_id, .. } => {
add_text(module_id); add_text(module_id);
if let ObservationEvent::LoopIteration { decision, .. } = event { if let ObservationEvent::LoopIteration { decision, .. } = event {
+10
View File
@@ -58,6 +58,10 @@ enum Recorded {
state: ValueState, state: ValueState,
value: Option<serde_json::Value>, value: Option<serde_json::Value>,
}, },
LoopTransfer {
frame: FrameId,
kind: &'static str,
},
Effect { Effect {
operation: String, operation: String,
result_code: String, result_code: String,
@@ -110,6 +114,12 @@ impl From<ObservationEvent<'_>> for Recorded {
frame: frame_id, frame: frame_id,
decision: decision.to_string(), decision: decision.to_string(),
}, },
ObservationEvent::LoopTransfer {
frame_id, transfer, ..
} => Recorded::LoopTransfer {
frame: frame_id,
kind: transfer.event_kind(),
},
ObservationEvent::Effect { ObservationEvent::Effect {
operation, operation,
result_code, result_code,
+16 -4
View File
@@ -285,11 +285,11 @@ pub enum Stmt {
/// Span of the whole statement. /// Span of the whole statement.
span: Span, span: Span,
}, },
/// `if`/`else` group: the first true arm wins. /// `if`/`else if`/`else` group: the first true arm wins.
Branch { Branch {
/// Arms in AST order. /// Arms in AST order.
arms: Vec<BranchArm>, arms: Vec<BranchArm>,
/// Span of the list node. /// Span of the opening `if` carrier.
span: Span, span: Span,
}, },
/// `while`/`end` group. /// `while`/`end` group.
@@ -303,6 +303,16 @@ pub enum Stmt {
/// Span of the whole `while` statement. /// Span of the whole `while` statement.
span: Span, span: Span,
}, },
/// Exit the nearest loop in the enclosing function.
Break {
/// Span of the carrier.
span: Span,
},
/// Resume at the nearest loop condition in the enclosing function.
Continue {
/// Span of the carrier.
span: Span,
},
/// Return from the enclosing function (`return` statement). /// Return from the enclosing function (`return` statement).
Return { Return {
/// Returned expression. /// Returned expression.
@@ -320,12 +330,14 @@ impl Stmt {
| Stmt::Eval { span, .. } | Stmt::Eval { span, .. }
| Stmt::Branch { span, .. } | Stmt::Branch { span, .. }
| Stmt::Loop { span, .. } | Stmt::Loop { span, .. }
| Stmt::Break { span }
| Stmt::Continue { span }
| Stmt::Return { span, .. } => *span, | Stmt::Return { span, .. } => *span,
} }
} }
} }
/// One arm of an `if`/`else` group. /// One arm of an `if`/`else if`/`else` group.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct BranchArm { pub struct BranchArm {
/// Boolean condition expression. /// Boolean condition expression.
@@ -334,7 +346,7 @@ pub struct BranchArm {
pub condition_span: Span, pub condition_span: Span,
/// Statements executed when the condition is true. /// Statements executed when the condition is true.
pub body: Vec<Stmt>, pub body: Vec<Stmt>,
/// Span of the whole list item. /// Span of the branch carrier.
pub span: Span, pub span: Span,
} }
+47 -9
View File
@@ -4,7 +4,8 @@ use std::collections::BTreeMap;
use marqdo_expression::{BinaryOp, Expr, RecordEntry}; use marqdo_expression::{BinaryOp, Expr, RecordEntry};
use marqdo_host::{ use marqdo_host::{
ExecutionContext, FrameId, Host, HostOp, ParameterSource, ResourceRead, RuntimeObservation, ExecutionContext, FrameId, Host, HostOp, LoopTransfer, ParameterSource, ResourceRead,
RuntimeObservation,
}; };
use marqdo_ir::{builtins, Function, FunctionId, ModuleId, PlaceTarget, Program, Stmt}; use marqdo_ir::{builtins, Function, FunctionId, ModuleId, PlaceTarget, Program, Stmt};
use marqdo_span::Span; use marqdo_span::Span;
@@ -71,6 +72,8 @@ struct BoundArgs {
enum Flow { enum Flow {
Next, Next,
Return(Value), Return(Value),
Break(Span),
Continue(Span),
} }
/// Marqdo tree-walk interpreter. /// Marqdo tree-walk interpreter.
@@ -225,11 +228,21 @@ impl<'a> Interpreter<'a> {
id: frame_id, id: frame_id,
}; };
self.depth += 1; self.depth += 1;
let result = self.exec_stmts(program, &function.body, &mut frame); let result = self
.exec_stmts(program, &function.body, &mut frame)
.and_then(|flow| match flow {
Flow::Next => Ok(None),
Flow::Return(value) => Ok(Some(value)),
Flow::Break(span) | Flow::Continue(span) => Err(RuntimeError::new(
ErrorCategory::Internal,
Some(span),
"loop control escaped its enclosing function",
)),
});
self.depth -= 1; self.depth -= 1;
let status = match &result { let status = match &result {
Ok(Flow::Next) => "ok", Ok(None) => "ok",
Ok(Flow::Return(_)) => "return", Ok(Some(_)) => "return",
Err(error) => error.code(), Err(error) => error.code(),
}; };
self.host.record_semantic( self.host.record_semantic(
@@ -246,8 +259,7 @@ impl<'a> Interpreter<'a> {
close?; close?;
} }
match result { match result {
Ok(Flow::Next) => Ok(Value::Unit), Ok(value) => Ok(value.unwrap_or(Value::Unit)),
Ok(Flow::Return(value)) => Ok(value),
Err(mut error) => { Err(mut error) => {
error.attribute_module(function.id.module.canonical()); error.attribute_module(function.id.module.canonical());
error.push_frame( error.push_frame(
@@ -409,6 +421,31 @@ impl<'a> Interpreter<'a> {
Stmt::Eval { expr, .. } => { Stmt::Eval { expr, .. } => {
self.eval_expr(expr, frame)?; self.eval_expr(expr, frame)?;
} }
Stmt::Break { span } | Stmt::Continue { span } => {
let (flow, transfer) = if matches!(stmt, Stmt::Break { .. }) {
(Flow::Break(*span), LoopTransfer::Break)
} else {
(Flow::Continue(*span), LoopTransfer::Continue)
};
let module = frame.function.module.canonical();
self.host.record_semantic(
transfer.event_kind(),
Some(&frame.function.to_string()),
Some(&module),
Some(*span),
None,
);
if self.observe {
self.host
.observe_runtime(RuntimeObservation::LoopTransfer {
frame_id: frame.id,
transfer,
module_id: &module,
span: *span,
})?;
}
return Ok(flow);
}
Stmt::Return { value, span } => { Stmt::Return { value, span } => {
let value = self.eval_expr(value, frame)?; let value = self.eval_expr(value, frame)?;
let module = frame.function.module.canonical(); let module = frame.function.module.canonical();
@@ -461,7 +498,7 @@ impl<'a> Interpreter<'a> {
if condition { if condition {
match self.exec_stmts(program, &arm.body, frame)? { match self.exec_stmts(program, &arm.body, frame)? {
Flow::Next => break, Flow::Next => break,
Flow::Return(value) => return Ok(Flow::Return(value)), flow => return Ok(flow),
} }
} }
} }
@@ -502,8 +539,9 @@ impl<'a> Interpreter<'a> {
break; break;
} }
match self.exec_stmts(program, body, frame)? { match self.exec_stmts(program, body, frame)? {
Flow::Next => {} Flow::Next | Flow::Continue(_) => {}
Flow::Return(value) => return Ok(Flow::Return(value)), Flow::Break(_) => break,
flow @ Flow::Return(_) => return Ok(flow),
} }
}, },
} }
@@ -249,3 +249,46 @@ fn memory_budget_is_enforced_without_changing_the_region() {
.unwrap_err(); .unwrap_err();
assert_eq!(error.code(), "resource.exhausted"); assert_eq!(error.code(), "resource.exhausted");
} }
#[test]
fn continue_obeys_fuel_and_wall_clock_budgets() {
use std::time::{Duration, Instant};
let source = "## @exec main\n\n`while true`\n\n`continue`\n\n`end`\n";
let program = build(source);
let module = ModuleId::from("index.mq.md");
let mut fuel_host = host();
fuel_host.budget.fuel = 20;
let fuel = run(&program, &mut fuel_host, &module, "main", Vec::new()).unwrap_err();
assert_eq!(fuel.code(), "resource.exhausted");
assert!(fuel.message.contains("fuel exhausted"));
let mut deadline_host = host();
deadline_host.budget.fuel = u64::MAX;
deadline_host.budget.deadline = Some(Instant::now() + Duration::from_millis(25));
let timeout = run(&program, &mut deadline_host, &module, "main", Vec::new()).unwrap_err();
assert_eq!(timeout.code(), "resource.exhausted");
assert!(timeout.message.contains("wall-clock time limit"));
}
#[test]
fn malformed_ir_cannot_transfer_into_the_callers_loop() {
let source =
"## @exec child\n\n`return 1`\n\n## @exec main\n\n`while true`\n\n`child()`\n\n`end`\n";
let mut program = build(source);
let module = ModuleId::from("index.mq.md");
let child = program
.modules
.get_mut(&module)
.unwrap()
.functions
.iter_mut()
.find(|function| function.id.name == "child")
.unwrap();
let span = child.body[0].span();
child.body[0] = marqdo_ir::Stmt::Break { span };
let error = run(&program, &mut host(), &module, "main", Vec::new()).unwrap_err();
assert_eq!(error.category, marqdo_value::ErrorCategory::Internal);
assert_eq!(error.span, Some(span));
}
@@ -93,6 +93,18 @@ impl ObservationSink for Recorder {
source: None, source: None,
decision: decision.to_string(), decision: decision.to_string(),
}, },
ObservationEvent::LoopTransfer {
frame_id, transfer, ..
} => Seen {
kind: transfer.event_kind(),
frame: Some(frame_id.0),
name: String::new(),
value_type: String::new(),
state: None,
wire: None,
source: None,
decision: String::new(),
},
ObservationEvent::VariableAssigned { ObservationEvent::VariableAssigned {
frame_id, frame_id,
name, name,
+8
View File
@@ -31,6 +31,14 @@ pub mod codes {
pub const SEM_SYNTAX: &str = "sem.syntax"; pub const SEM_SYNTAX: &str = "sem.syntax";
/// `else` does not bind an open `if`. /// `else` does not bind an open `if`.
pub const SEM_UNMATCHED_ELSE: &str = "sem.unmatched_else"; pub const SEM_UNMATCHED_ELSE: &str = "sem.unmatched_else";
/// `else if` has no matching open `if`.
pub const SEM_UNMATCHED_ELSE_IF: &str = "sem.unmatched_else_if";
/// `else if` follows the final `else`.
pub const SEM_ELSE_IF_AFTER_ELSE: &str = "sem.else_if_after_else";
/// A `break` appears outside a loop in its heading segment.
pub const SEM_BREAK_OUTSIDE_LOOP: &str = "sem.break_outside_loop";
/// A `continue` appears outside a loop in its heading segment.
pub const SEM_CONTINUE_OUTSIDE_LOOP: &str = "sem.continue_outside_loop";
/// A second `else` appears for one `if`. /// A second `else` appears for one `if`.
pub const SEM_DUPLICATE_ELSE: &str = "sem.duplicate_else"; pub const SEM_DUPLICATE_ELSE: &str = "sem.duplicate_else";
/// `end` closes no open frame. /// `end` closes no open frame.
+17 -1
View File
@@ -26,7 +26,7 @@ as current status.
## RC candidate ## RC candidate
The workspace reports `3.0.0-rc.1` and declares Rust 1.89 as its locked The workspace reports `3.0.0-rc.2` and declares Rust 1.89 as its locked
minimum. Linux x86_64 on glibc 2.39 is the candidate platform. The minimum. Linux x86_64 on glibc 2.39 is the candidate platform. The
[release procedure](releasing.md) requires a green manifest bound to the [release procedure](releasing.md) requires a green manifest bound to the
candidate SHA before publication. The release record below refers to the candidate SHA before publication. The release record below refers to the
@@ -264,6 +264,22 @@ digests. The external lane ran from a temporary fixture checkout with Cargo
absent from PATH. Archive SHA-256 is absent from PATH. Archive SHA-256 is
`8934bfc25c7b5526071eae6f24143ca3805ad3d7cc484626a4345b1deed430b2`. `8934bfc25c7b5526071eae6f24143ca3805ad3d7cc484626a4345b1deed430b2`.
## 0.8 Structured control flow — RFC-CTRL-0005 (RC.2 candidate)
[ADR-0067](adr/0067-structured-control-flow.md) covers the phase A implementation.
An `else if` carrier adds a condition arm to the existing branch IR.
`break` and `continue` transfer to the nearest loop in the same heading
execution segment. Binding inference joins only reachable control exits.
The [runnable example](../examples/control-flow.mq.md) uses ordinary Markdown
list containers.
[Analysis v3](../spec/analysis-v3.md) represents the loop transfer statements.
Other documents continue to emit v2. Trace v2 and Execution Events v1 expose
the new control events. The published beta evidence applies to its original
SHA. The maintainer selected phase A for RC.2. List iteration
is a follow-up design. The [pre-candidate local verification record](evidence/2026-11-23-rfc-ctrl-0005.md)
identifies the tested commit, commands, archive digest and consumer results.
## 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
+42
View File
@@ -0,0 +1,42 @@
# ADR-0067 — Multi-arm branches and nearest-loop control
Status: Accepted for development. Release inclusion requires a maintainer
decision and the applicable same-SHA release gates.
Implements stage A of [RFC-CTRL-0005](https://git.cflmy.cn/cflmy/marqdo-cli/issues/7)
as an amendment to [RFC-LANG-0002](../architecture/RFC-LANG-0002-unified-semantics.md)
and the existing [mapping](../../spec/mapping.md) and
[grammar](../../spec/expression.ebnf). Follow the frontend → IR → interpreter
boundary in the [development blueprint](../DEVELOPMENT_BLUEPRINT.md#7-rust-独立解释器ir值系统与执行内核).
## Language and execution
An `else if` carrier adds an arm to the existing Branch IR. Condition
evaluation is ordered and short-circuited. A separate `else` carrier followed
by `if` keeps its nested meaning. The frontend owns pairing, heading
boundaries, and diagnostics. The Markdown profile and carrier mapping stay
the same.
A complete `break` or `continue` payload is contextual loop control. Existing
names in functions, parameters, fields, calls and expressions stay valid.
The ambiguous case is a standalone identifier read, which can be written
with parentheses. The runtime propagates a structured result to the nearest
loop, with the usual statement and iteration budgets. The loop consumes that
result within the current function. Static binding analysis only merges
reachable exits and keeps the function's initial loop-entry binding rules.
## Public projections
Branch arms fit Analysis v2. A project containing a loop transfer requires
Analysis v3, which preserves the envelope and adds the statement kinds
`break` and `continue`. The writer selects the required version from the
project. A v2 reader can keep reading existing output and rejects v3 at the
envelope. Trace v2 adds `control.break` and `control.continue` to its open
event vocabulary. Execution Events v1 adds the corresponding events, carrying
only the existing frame/module/span fields. The Trace digest binds to the
automatically selected Analysis document. Markdown, ABI and Host operation
versions are independent of this change.
Stage B List iteration requires a separate decision on snapshot and binding
semantics. Release approval and ecosystem adoption are tracked outside this
implementation.
+2 -1
View File
@@ -64,4 +64,5 @@ Files: `0001`–`0050`, plus:
* [0065](0065-resource-control-vnext.md) — proposed manifest-driven stateful * [0065](0065-resource-control-vnext.md) — proposed manifest-driven stateful
operations and child resources; operations and child resources;
* [0066](0066-structured-tasks-v1.md) — proposed task isolation, bounded * [0066](0066-structured-tasks-v1.md) — proposed task isolation, bounded
communication and cancellation. communication and cancellation;
* [0067](0067-structured-control-flow.md) — multi-arm branches and nearest-loop transfers.
+7
View File
@@ -55,6 +55,13 @@ replace `spec/` or a recorded test log.
> [Task v1](../adr/0066-structured-tasks-v1.md) designs are Proposed. > [Task v1](../adr/0066-structured-tasks-v1.md) designs are Proposed.
> See [STATUS §0.7](../STATUS.md#07-post-beta-stable-core-review--rfc-gpl-0004-unreleased). > See [STATUS §0.7](../STATUS.md#07-post-beta-stable-core-review--rfc-gpl-0004-unreleased).
> **Structured control flow (RFC-CTRL-0005).**
> [ADR-0067](../adr/0067-structured-control-flow.md) extends the payload parser
> and branch mapper, adds nearest-loop execution transfers and makes binding
> inference path-sensitive. Analysis chooses v2 or v3 according to the
> statements it emits. The interpreter owns the transfers and reports them
> through the existing observation facade.
## 1. Four state dimensions ## 1. Four state dimensions
A claim is stated in exactly one of these dimensions. "Exists in the tree" is not A claim is stated in exactly one of these dimensions. "Exists in the tree" is not
@@ -526,8 +526,11 @@ import:
| 关键字 | 语法 | 含义 | 是否新增计算原语 | | 关键字 | 语法 | 含义 | 是否新增计算原语 |
|---|---|---|---| |---|---|---|---|
| `if` | `if <Bool expression>` | 开始条件分支 | 否,映射已有 `Branch` | | `if` | `if <Bool expression>` | 开始条件分支 | 否,映射已有 `Branch` |
| `else if` | `else if <Bool expression>` | 添加同一分支组的条件臂 | 否,复用 `Branch` |
| `else` | `else` | 切换至当前 if 的否则分支 | 否 | | `else` | `else` | 切换至当前 if 的否则分支 | 否 |
| `while` | `while <Bool expression>` | 开始循环 | 否,映射已有 `Loop` | | `while` | `while <Bool expression>` | 开始循环 | 否,映射已有 `Loop` |
| `break` | `break` | 退出最近一层循环 | 否,结构化控制转移 |
| `continue` | `continue` | 重新检查最近一层循环的条件 | 否,结构化控制转移 |
| `end` | `end` | 结束最近未关闭的 if/while | 否,仅用于编译期配对 | | `end` | `end` | 结束最近未关闭的 if/while | 否,仅用于编译期配对 |
| `return` | `return <expression>` | 返回当前 H2 函数,终止后续执行 | 否,映射已有 `Return` | | `return` | `return <expression>` | 返回当前 H2 函数,终止后续执行 | 否,映射已有 `Return` |
| `params` | `params(name: Type, ...)` | H2 Exec 函数的可选参数声明 | 否,编译期元数据 | | `params` | `params(name: Type, ...)` | H2 Exec 函数的可选参数声明 | 否,编译期元数据 |
@@ -604,7 +607,7 @@ import:
`return x` `return x`
```` ````
规范语义:条件计算一次,必须是 Bool;为真执行 `if` 和 `else` 之间的载荷,否则执行 `else` 和 `end` 之间的载荷。**不能两个分支都执行。** `else` 可以省略;但 `end` 不能省略。 各条件必须返回 Bool,每个条件在轮到该臂时求值一次。执行第一个为真的臂,或在所有条件为假时执行末尾的 `else`。没有匹配臂也没有 `else` 时直接继续。每组需要一个 `end`。
**将它排成有序列表也完全合法**: **将它排成有序列表也完全合法**:
@@ -675,7 +678,9 @@ import:
匹配规则:每个 `else` 只作用于**栈顶尚未结束的 `if`**;每个 `end` 关闭最近的 `if` 或 `while`。这是一套确定的编译期配对规则,不靠缩进/列表种类/解释器猜测。 匹配规则:每个 `else` 只作用于**栈顶尚未结束的 `if`**;每个 `end` 关闭最近的 `if` 或 `while`。这是一套确定的编译期配对规则,不靠缩进/列表种类/解释器猜测。
**不支持 `else if` 专用写法(本期)**:若需要多路判断,可在 `else` 内另写一个嵌套 `if ... end`,按上述栈规则执行。若未来证明有显著可读性需求,再独立讨论 `elif`,不能开发者自行在 Parser 中宽容接受。 多臂条件采用同一载荷内的 `else if <expr>`,允许零至多个条件臂和一个末尾
`else`。整组由一个 `end` 闭合,各条件从左到右按需求值。两个独立载荷
`else` 与 `if` 仍表示嵌套分支。详见 [RFC-CTRL-0005 的采纳记录](../adr/0067-structured-control-flow.md)。
## 4.5 `while` / `end`:不依赖 bullet List 的循环 ## 4.5 `while` / `end`:不依赖 bullet List 的循环
@@ -720,9 +725,10 @@ import:
严格规则: 严格规则:
- 每一个 `if` 恰有一个匹配的 `end`;`else` 可选且最多一个。 - 每一个 `if` 恰有一个匹配的 `end`。可有多个 `else if` 和一个末尾 `else`。
- 每一个 `while` 恰有一个匹配的 `end`。 - 每一个 `while` 恰有一个匹配的 `end`。
- `else` 不能独立出现;不能对应 `while`;一个 `if` 不能有两个 `else`。 - `else if` 和 `else` 只能配对栈顶的 `if`。
- 独占载荷的 `break` 结束同一标题执行段中的最近循环,`continue` 跳至该循环的下一次条件检查。
- `end` 不能独立出现;语义片段末尾若仍有未闭合控制块则报错。 - `end` 不能独立出现;语义片段末尾若仍有未闭合控制块则报错。
- 不允许控制块跨越**标题边界**(见第 6 章),也不能跨 H2 函数、不同 `@exec` 章节或知识区域。 - 不允许控制块跨越**标题边界**(见第 6 章),也不能跨 H2 函数、不同 `@exec` 章节或知识区域。
- `if x > 0:` 带尾冒号首版不合法;规范语句不使用冒号,因为 Markdown 控制不由缩进决定。 - `if x > 0:` 带尾冒号首版不合法;规范语句不使用冒号,因为 Markdown 控制不由缩进决定。
@@ -755,7 +761,7 @@ V2 推荐显式声明:
| `return`(无表达式) | 语法错误 | `return None`(如果确实要返回 None) | | `return`(无表达式) | 语法错误 | `return None`(如果确实要返回 None) |
| `end if` | 语法错误 | `end` | | `end if` | 语法错误 | `end` |
| `for x in xs` | 未纳入首版语法 | 标准库算法或 `while` | | `for x in xs` | 未纳入首版语法 | 标准库算法或 `while` |
| `break`、`continue`、`try` | 未纳入首版语法 | 首版不承诺 | | `try` | 不属于当前语法 | — |
| `a.b = 1` | 保留现有赋值能力限制 | 使用相应数据操作 API | | `a.b = 1` | 保留现有赋值能力限制 | 使用相应数据操作 API |
| `x = 1; return x` 单个载荷 | 语法错误 | 两个独立闭合载荷 | | `x = 1; return x` 单个载荷 | 语法错误 | 两个独立闭合载荷 |
| 直接写 `> print(x)` | 文档引用,不执行 | `> **print(x)**` | | 直接写 `> print(x)` | 文档引用,不执行 | `> **print(x)**` |
@@ -784,7 +790,10 @@ V2 推荐显式声明:
```ebnf ```ebnf
(* 每一个独立 Markdown 载荷对应且只对应一条 statement。 *) (* 每一个独立 Markdown 载荷对应且只对应一条 statement。 *)
carrier_statement = "if", required_space, expr, EOF carrier_statement = "if", required_space, expr, EOF
| "else", whitespace, "if", whitespace, Expr, EOF
| "else", EOF | "else", EOF
| "break", EOF
| "continue", EOF
| "while", required_space, expr, EOF | "while", required_space, expr, EOF
| "end", EOF | "end", EOF
| "return", required_space, expr, EOF | "return", required_space, expr, EOF
@@ -799,7 +808,7 @@ carrier_statement = "if", required_space, expr, EOF
**词法必须考虑完整单词边界**:`ifdef()`、`returning()` 不是 `if`、`return` 控制语句;反之,单独的 `if`、`else` 等当作标识符使用应明确报保留字错误。为了避免自相矛盾,Tokeniser 和 Parser 均应对关键字使用同一套保留字定义。 **词法必须考虑完整单词边界**:`ifdef()`、`returning()` 不是 `if`、`return` 控制语句;反之,单独的 `if`、`else` 等当作标识符使用应明确报保留字错误。为了避免自相矛盾,Tokeniser 和 Parser 均应对关键字使用同一套保留字定义。
- `if`、`while` 后必须为可完整消费的表达式;表达式运行结果必须 Bool。现有条件纯度限制仍适用。 - `if`、`while` 后必须为可完整消费的表达式;表达式运行结果必须 Bool。现有条件纯度限制仍适用。
- `else`、`end` 后不允许额外词元,`end if`、`else x` 均硬错误。 - `else if` 后必须有条件;独立的 `else` 和 `end` 后无额外词元。
- `return` 后必须是表达式;其作用范围是当前 H2 函数,不是当前段落/列表项。 - `return` 后必须是表达式;其作用范围是当前 H2 函数,不是当前段落/列表项。
- `params` 仅允许声明位置;作为普通表达式调用不得偷偷生效。 - `params` 仅允许声明位置;作为普通表达式调用不得偷偷生效。
- 首版**没有**冒号、缩进结束、自动括号、换行分号语法糖。 - 首版**没有**冒号、缩进结束、自动括号、换行分号语法糖。
@@ -817,14 +826,23 @@ TokenStream = [StatementToken(payload, span, carrier_kind, owner_unit), ...]
```text ```text
open_if(condition): open_if(condition):
push IfFrame(cond, then=[], else=None) push IfFrame(arms=[(condition, [])], has_else=false)
on_statement(stmt): on_statement(stmt):
append stmt to the current innermost active body append stmt to the current innermost active body
on_else_if(condition):
require stack.top == IfFrame and not frame.has_else
append and activate a new conditional arm
on_else: on_else:
require stack.top == IfFrame and frame.else is None require stack.top == IfFrame and not frame.has_else
switch frame active branch from then to else append and activate the final arm
set frame.has_else
on_break_or_continue:
require an open WhileFrame in the current segment
append the transfer to the current innermost active body
open_while(condition): open_while(condition):
push WhileFrame(cond, body=[]) push WhileFrame(cond, body=[])
@@ -842,10 +860,10 @@ at_segment_end:
该算法可以保证: 该算法可以保证:
- `else` 配对最近尚未结束、且位于栈顶的 `if`;不得跳过未关闭的 `while` 寻找更外层 `if`。 - `else if` 和 `else` 配对栈顶的 `if`,且只能出现在末尾 `else` 之前;不得跳过未关闭的 `while` 寻找更外层 `if`。
- `end` 只关闭栈顶最近的一层 if/while,没有匹配结构时报错。 - `end` 只关闭栈顶最近的一层 if/while,没有匹配结构时报错。
- `return` 属于正在打开的 body,但运行时终止整个 H2 函数;降为现有 `Stmt::Return` IR。 - `return` 属于正在打开的 body,但运行时终止整个 H2 函数;降为现有 `Stmt::Return` IR。
- `else` 不会成为单独一条 Runtime 指令;它只是 IR `Branch` 的分支边界。 - `else if` 和 `else` 是 `Branch` 的臂边界。解释器将 `break` 和 `continue` 传递到最近的循环。
- 相同载荷序列应产生相同的**归一化可执行 IR**,不因列表编号、引用层数、加粗/斜体/行内代码形态改变运算类别。 - 相同载荷序列应产生相同的**归一化可执行 IR**,不因列表编号、引用层数、加粗/斜体/行内代码形态改变运算类别。
**一个实现注意点**:现有 `Branch` IR 的每个 arm 带 `condition`,没有专用可选 else;首版可以将兜底 else 降为最后一个 `true` arm,并明确保持既有“从左到右找第一匹配”的短路求值。如果未来 IR 引入更明确的 `else_body`,必须同步更改 IR schema、Trace 规范和**全部下游消费者及测试**;不能在本轮暗改行为。 **一个实现注意点**:现有 `Branch` IR 的每个 arm 带 `condition`,没有专用可选 else;首版可以将兜底 else 降为最后一个 `true` arm,并明确保持既有“从左到右找第一匹配”的短路求值。如果未来 IR 引入更明确的 `else_body`,必须同步更改 IR schema、Trace 规范和**全部下游消费者及测试**;不能在本轮暗改行为。
@@ -969,6 +987,10 @@ R(IR, imports) = ExecutableProgram or Diagnostics
| `## @exec` | 缺少标题名称 | `sem.empty_unit_name` | | `## @exec` | 缺少标题名称 | `sem.empty_unit_name` |
| `**if x >**` | 语法错误,不降级文档 | `sem.syntax` | | `**if x >**` | 语法错误,不降级文档 | `sem.syntax` |
| `**else**`(无 if) | 无匹配分支 | `sem.unmatched_else` | | `**else**`(无 if) | 无匹配分支 | `sem.unmatched_else` |
| `**else if true**`(无 if) | 无匹配分支 | `sem.unmatched_else_if` |
| `**else if true**`(位于末尾 else 后) | 条件臂位置非法 | `sem.else_if_after_else` |
| `**break**`(循环外) | 无匹配循环 | `sem.break_outside_loop` |
| `**continue**`(循环外) | 无匹配循环 | `sem.continue_outside_loop` |
| `**else**`(重复 else) | 重复,否则分支只允许一个 | `sem.duplicate_else` | | `**else**`(重复 else) | 重复,否则分支只允许一个 | `sem.duplicate_else` |
| `**end**`(无 if/while) | 不能独立结束 | `sem.unmatched_end` | | `**end**`(无 if/while) | 不能独立结束 | `sem.unmatched_end` |
| `**if true**` 到片段结束无 end | 未闭合控制 | `sem.unclosed_control` | | `**if true**` 到片段结束无 end | 未闭合控制 | `sem.unclosed_control` |
+1
View File
@@ -49,6 +49,7 @@ marqdo-cli/
│ ├── 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)
│ ├── analysis-v3.md projection for projects with loop transfers
│ ├── trace-v2.md public Trace v2 projection (v1 historical) │ ├── trace-v2.md public Trace v2 projection (v1 historical)
│ └── trace-v1.md public Trace v1 event stream │ └── trace-v1.md public Trace v1 event stream
├── crates/ ├── crates/
+1 -1
View File
@@ -6,7 +6,7 @@ Rust structures, `marqdo-ir` internals, `inspect --ir`, relative paths into the
core checkout, or host memory layout. Adding a new domain function must not core checkout, or host memory layout. Adding a new domain function must not
require a core commit. require a core commit.
Product version for these docs: **`3.0.0-rc.1`** (Linux x86_64 candidate). Product version for these docs: **`3.0.0-rc.2`** (Linux x86_64 candidate).
Protocol versions are independent: Analysis v2, Trace v2, Execution Events v1, Protocol versions are independent: Analysis v2, Trace v2, Execution Events v1,
Tool v1, Plugin ABI v1, Foreign wire v1, Provider manifest v2, lock v4, Tool v1, Plugin ABI v1, Foreign wire v1, Provider manifest v2, lock v4,
markdown profile `marqdo.md.v1`. markdown profile `marqdo.md.v1`.
+15 -9
View File
@@ -1,9 +1,9 @@
# Analysis v2 and Trace v2 consumers # Analysis and Trace v2 consumers
Both are public, versioned JSON artifacts. A consumer must read them as files, Both are public, versioned JSON artifacts. A consumer must read them as files,
never link Marqdo's Rust internals or depend on `inspect --ir`. never link Marqdo's Rust internals or depend on `inspect --ir`.
## Analysis v2 (static) ## Analysis v2 and v3 (static)
```bash ```bash
marqdo check index.mq.md --emit ./analysis.json marqdo check index.mq.md --emit ./analysis.json
@@ -13,7 +13,10 @@ marqdo check index.mq.md --emit ./analysis.json
independent Markdown-link check and can make `check` fail; on failure the emit independent Markdown-link check and can make `check` fail; on failure the emit
target is removed. Do not generate a consumer artifact with target is removed. Do not generate a consumer artifact with
`check --refs --emit` without checking the exit code. `check --refs --emit` without checking the exit code.
- `schema: "marqdo.analysis"`, `schema_version: 2`. - `schema: "marqdo.analysis"`. The writer emits `schema_version: 2` for
projects without loop transfers and `3` when a function body contains
`break` or `continue`. Check the version before walking function bodies.
Both versions encode `else if` in the ordered `branch.arms` array.
- Top level: `producer` (`name`, `version` = product version, - Top level: `producer` (`name`, `version` = product version,
`markdown_profile`), `project`, `modules`, `diagnostics`. `markdown_profile`), `project`, `modules`, `diagnostics`.
- `project`: `root_id` (`root:<name>@<version>` for manifest projects), - `project`: `root_id` (`root:<name>@<version>` for manifest projects),
@@ -26,9 +29,10 @@ marqdo check index.mq.md --emit ./analysis.json
instance ids, never absolute paths. instance ids, never absolute paths.
- `check` does not load plugin libraries, start kernels/providers or execute the - `check` does not load plugin libraries, start kernels/providers or execute the
program. program.
- Schemas: `spec/schemas/analysis-v2.schema.json`; contract: - Contracts: [Analysis v2](../../spec/analysis-v2.md) and
`spec/analysis-v2.md`; consumers: `tests/consumers/analysis_consumer.py`, [Analysis v3](../../spec/analysis-v3.md). Each links to its schema.
`tests/consumers/validate_protocols.py`. The independent consumers in `tests/consumers/` check the version and
decode the public nodes.
View must render the **original Markdown** and use Analysis only to correlate View must render the **original Markdown** and use Analysis only to correlate
source offsets/heading units/callable mapping. Knowledge must use heading source offsets/heading units/callable mapping. Knowledge must use heading
@@ -50,7 +54,8 @@ marqdo run index.mq.md --trace-file ./trace.json
stale; do not bind it to the new source. `run --trace-file` does not emit stale; do not bind it to the new source. `run --trace-file` does not emit
Analysis itself. Analysis itself.
- Event kinds: `call.enter`, `call.exit`, `branch.eval`, `loop.iteration`, - Event kinds: `call.enter`, `call.exit`, `branch.eval`, `loop.iteration`,
`return`, `effect`, and possibly `trace.truncated`. Sourced events carry a `control.break`, `control.continue`, `return`, `effect` and possibly
`trace.truncated`. Sourced events carry a
module id and a UTF-8 span. module id and a UTF-8 span.
- Defaults are 100,000 events / 32 MiB; `--trace-max-events` and - Defaults are 100,000 events / 32 MiB; `--trace-max-events` and
`--trace-max-bytes` adjust them (`0` = unlimited). A consumer must tolerate `--trace-max-bytes` adjust them (`0` = unlimited). A consumer must tolerate
@@ -80,10 +85,11 @@ marqdo run index.mq.md --event-stream jsonl --trace-file ./trace.json
a complete stream. An EOF without a terminal event is `incomplete` a complete stream. An EOF without a terminal event is `incomplete`
(SIGKILL/crash/broken pipe); never synthesize success. (SIGKILL/crash/broken pipe); never synthesize success.
- `run.started.source` contains `root_id` and the `sha256:` digest of the exact - `run.started.source` contains `root_id` and the `sha256:` digest of the exact
Analysis v2 bytes. `--trace-file` may be combined; both writers share one Analysis bytes. `--trace-file` may be combined; both writers share one
opaque run id, and Trace v2 remains atomic and value-free. opaque run id, and Trace v2 remains atomic and value-free.
- Structural events: `call.enter`/`call.exit` (`frame_id`, `parent_frame_id`), - Structural events: `call.enter`/`call.exit` (`frame_id`, `parent_frame_id`),
`return`, `branch.eval`, `loop.iteration`, `effect`. Frames identify call `return`, `branch.eval`, `loop.iteration`, `control.break`,
`control.continue` and `effect`. Frames identify call
instances, not functions; a failed argument binding creates no frame. instances, not functions; a failed argument binding creates no frame.
- Values are off by default (`value_state: not_requested`). - Values are off by default (`value_state: not_requested`).
`--observe-variable NAME` and `--observe-parameter NAME` are exact-name `--observe-variable NAME` and `--observe-parameter NAME` are exact-name
+3 -3
View File
@@ -6,9 +6,9 @@ This page summarizes the public support policy. The authoritative matrix is
## Version axes (do not conflate) ## Version axes (do not conflate)
| Axis | `3.0.0-rc.1` value | Change rule | | Axis | `3.0.0-rc.2` value | Change rule |
|---|---|---| |---|---|---|
| Product / CLI | `3.0.0-rc.1` | SemVer prerelease. See `CHANGELOG.md` for changes from the beta. | | Product / CLI | `3.0.0-rc.2` | SemVer prerelease. See `CHANGELOG.md` for changes from the beta. |
| Analysis | v2 | New major for incompatible changes; consumers reject unknown majors. | | Analysis | v2 | New major for incompatible changes; consumers reject unknown majors. |
| Trace | v2 | New major for incompatible changes; binds to exact Analysis bytes. | | Trace | v2 | New major for incompatible changes; binds to exact Analysis bytes. |
| Execution Events | v1 | One-line NDJSON stream; new major for incompatible required-field/ordering/redaction changes. Consumers reject unknown majors. | | Execution Events | v1 | One-line NDJSON stream; new major for incompatible required-field/ordering/redaction changes. Consumers reject unknown majors. |
@@ -42,7 +42,7 @@ grant, values are off by default, and `--mode strict` currently refuses
## Language compatibility ## Language compatibility
`3.0.0-rc.1` implements RFC-LANG-0002 only. Pre-RFC `.mq.md` source `3.0.0-rc.2` implements RFC-LANG-0002 only. Pre-RFC `.mq.md` source
(Strong-execute / Emph-return / ordered-list branch / bullet-list loop / (Strong-execute / Emph-return / ordered-list branch / bullet-list loop /
block-quote call / first code-span signature) is **not executable**; there is no block-quote call / first code-span signature) is **not executable**; there is no
`--legacy`, syntax switch or downgrade path. Migration is a rewrite task `--legacy`, syntax switch or downgrade path. Migration is a rewrite task
+14 -8
View File
@@ -1,15 +1,15 @@
# Quickstart: install and run # Quickstart: install and run
Product: `3.0.0-rc.1` (Linux x86_64 candidate). Install a **release archive**, not Product: `3.0.0-rc.2` (Linux x86_64 candidate). Install a **release archive**, not
a source checkout, when you only consume Marqdo. a source checkout, when you only consume Marqdo.
## 1. Install the archive ## 1. Install the archive
```bash ```bash
sha256sum -c marqdo-3.0.0-rc.1-x86_64-unknown-linux-gnu.tar.gz.sha256 sha256sum -c marqdo-3.0.0-rc.2-x86_64-unknown-linux-gnu.tar.gz.sha256
tar -xzf marqdo-3.0.0-rc.1-x86_64-unknown-linux-gnu.tar.gz tar -xzf marqdo-3.0.0-rc.2-x86_64-unknown-linux-gnu.tar.gz
cd marqdo-3.0.0-rc.1-x86_64-unknown-linux-gnu cd marqdo-3.0.0-rc.2-x86_64-unknown-linux-gnu
./marqdo --version # marqdo 3.0.0-rc.1 ./marqdo --version # marqdo 3.0.0-rc.2
./marqdo --help ./marqdo --help
``` ```
@@ -58,9 +58,15 @@ stdout and diagnostics.
documentation. Unmarked headings inherit the nearest ancestor mode. documentation. Unmarked headings inherit the nearest ancestor mode.
- `**strong**`, `*emph*` and inline `` `code` `` are interchangeable carriers of - `**strong**`, `*emph*` and inline `` `code` `` are interchangeable carriers of
one statement each. one statement each.
- Control flow uses keywords: `if`/`else`/`while`/`end`, plus `params(...)` and - A branch has an `if`, any number of `else if` arms and an optional
`return`. final `else`, followed by one `end`. Each condition is evaluated in order.
- Lists, block quotes and paragraphs are presentation only. - A `while` loop ends at `end`. Inside its body, `break` exits the nearest
loop and `continue` skips to its next condition check. `return` exits
the function. See the [runnable example](../../examples/control-flow.mq.md).
- Lists, block quotes and paragraphs organize the source view. For review or
linting, put each branch head at the start of an ordered list item and
place the loop head at the start of a bullet item. Nest the body visually
and close each group with its own `end` carrier.
- The normative contract is - The normative contract is
[`../architecture/RFC-LANG-0002-unified-semantics.md`](../architecture/RFC-LANG-0002-unified-semantics.md), [`../architecture/RFC-LANG-0002-unified-semantics.md`](../architecture/RFC-LANG-0002-unified-semantics.md),
[`../../spec/mapping.md`](../../spec/mapping.md) and [`../../spec/mapping.md`](../../spec/mapping.md) and
+2 -2
View File
@@ -1,4 +1,4 @@
# Marqdo 3.0.0-rc.1 — known limitations # Marqdo 3.0.0-rc.2 — known limitations
This file ships in the release archive as `KNOWN_LIMITATIONS.md`. It is part of This file ships in the release archive as `KNOWN_LIMITATIONS.md`. It is part of
the release record: it defines the platform and feature scope for the release candidate. the release record: it defines the platform and feature scope for the release candidate.
@@ -57,7 +57,7 @@ Even when available:
## Compatibility and versioning ## Compatibility and versioning
* `3.0.0-rc.1` is a **prerelease**. The changelog lists changes from the beta. * `3.0.0-rc.2` is a **prerelease**. The changelog lists changes from the beta.
* The product version is independent of protocol versions: Analysis v2, Trace * The product version is independent of protocol versions: Analysis v2, Trace
v2, Execution Events v1, Tool v1, Plugin ABI v1, Foreign wire v1, Provider v2, Execution Events v1, Tool v1, Plugin ABI v1, Foreign wire v1, Provider
manifest v2 and lock v4 keep their own major numbers. manifest v2 and lock v4 keep their own major numbers.
+4 -3
View File
@@ -20,7 +20,7 @@ marqdo-view/
examples/ examples/
``` ```
`tool.json` for the `3.0.0-rc.1` candidate: `tool.json` for the `3.0.0-rc.2` candidate:
```json ```json
{ {
@@ -44,7 +44,8 @@ marqdo-view/
rejects a mismatched range at install and dispatch time with a rejects a mismatched range at install and dispatch time with a
`requires marqdo …` diagnostic. `requires marqdo …` diagnostic.
- `analysis`/`trace` are declared only if the tool consumes them; the current - `analysis`/`trace` are declared only if the tool consumes them; the current
core provides Analysis v2 and Trace v2. development branch provides Analysis v2/v3 and Trace v2. Declare
`analysis: [2, 3]` when the reader handles both versions.
- `command` must match `^[a-z][a-z0-9-]*$` and must not collide with a built-in - `command` must match `^[a-z][a-z0-9-]*$` and must not collide with a built-in
command (`init`, `run`, `call`, `check`, `inspect`, `fmt`, `plugin`, `add`, command (`init`, `run`, `call`, `check`, `inspect`, `fmt`, `plugin`, `add`,
`remove`, `lock`, `sync`, `tool`, `help`). `remove`, `lock`, `sync`, `tool`, `help`).
@@ -72,7 +73,7 @@ The tool receives:
|---|---| |---|---|
| `MARQDO_BIN` | absolute path of the running `marqdo` executable | | `MARQDO_BIN` | absolute path of the running `marqdo` executable |
| `MARQDO_TOOL_PROTOCOL` | `1` | | `MARQDO_TOOL_PROTOCOL` | `1` |
| `MARQDO_PROTOCOL_ANALYSIS` | `2` when Analysis v2 was negotiated | | `MARQDO_PROTOCOL_ANALYSIS` | Highest shared Analysis version. Read the artifact envelope for its actual version. |
| `MARQDO_PROTOCOL_TRACE` | `2` when Trace v2 was negotiated | | `MARQDO_PROTOCOL_TRACE` | `2` when Trace v2 was negotiated |
Call `$MARQDO_BIN` with an argv array; do not assume `marqdo` is on `PATH`. Call `$MARQDO_BIN` with an argv array; do not assume `marqdo` is on `PATH`.
@@ -0,0 +1,63 @@
# Linux RC1 assessment for RFC-CTRL-0005
Candidate `af1e07f3d772a7f641c37ef9c2d435783f93141d` was tested on
`release/3.0.0-rc.1-control-flow`. This is a separate verification branch
from the existing `release/3.0.0-rc.1` freeze at `f7a5a7b`.
[Woodpecker #56](https://ci.cflmy.cn/repos/1/pipeline/56) passed all steps,
including format, Clippy, workspace tests, Windows cross-compilation, the
Rust 1.89 locked check, release build, protocol smoke, and independent extension
conformance. Windows and macOS are outside this Linux candidate's scope.
## Archive
The locally rebuilt archive passes its checksum, smoke tests and installed-only
cold check in Ubuntu 24.04 with glibc 2.39. Its seven frozen extension contract
groups and six reference applications passed. Its executable digests match
the two digests stamped by Woodpecker #56.
| File | SHA-256 |
|---|---|
| Linux archive | `7d04070dfea78c71a4223b85156ec18b18476410d3a28db4b4fe24ab2dd7f5cf` |
| `marqdo` | `adaea5d34f914878b3ee67f8ea852741a6021d07e42e4e0d7e10510ee4559c8a` |
| `marqdo-provider-worker` | `71f145e75d0f69b7a292d7a48da0bf1f850d6f57efb417f59877c8acdeb195d3` |
The archive declares Analysis v2 and v3. Its smoke test exercises both majors
against independent readers and checks the Trace v2 digest. The old Lint
consumer limitation is recorded in the
[control-flow development verification](2026-11-23-rfc-ctrl-0005.md).
## Strict L1
The strict security lane passed for this SHA in a disposable Ubuntu 26.04 VM
as uid 1000, with Bubblewrap 0.11.1 and kernel 7.0.0-43-generic. The base image
digest was verified against Canonical's dated release checksum. The same guest
also verified the archive checksum and ran the installed example in strict
mode, returning 5 with the CLI digest shown above.
## Performance
Each paired run compared the beta tag with the extracted candidate archive.
All nine workload results were correctness-verified on Woodpecker agent 1,
pinned to logical CPU 0, kernel 7.0.0-31-generic, on an Intel i7-12700H with the
`powersave` governor. Each run used five warmups and twenty samples per
workload. All three candidate executable digests match the archive above.
The complete beta and candidate reports are retained in the linked logs.
| Paired run | HTTP parser p50 change | HTTP parser beta and candidate p95 |
|---|---:|---:|
| [#57](https://ci.cflmy.cn/repos/1/pipeline/57) | +21.58% | 5.5765 / 5.6545 ms |
| [#58](https://ci.cflmy.cn/repos/1/pipeline/58) | +0.05% | 5.7052 / 5.6888 ms |
| [#59](https://ci.cflmy.cn/repos/1/pipeline/59) | +0.15% | 5.7086 / 5.6371 ms |
The first pair crossed the 15% p50 threshold. Its beta p50 was 4.5126 ms,
compared with 5.5761 and 5.5602 ms in the next two pairs. The candidate p50
stayed within 5.4865–5.5789 ms across the three. The p95 and CPU samples
overlapped. The threshold breach was not reproduced and is recorded with the
shared-node variability. The largest RSS increase was 1.16%. No other
comparison crossed the investigation thresholds.
The three reports are shared-node SMOKE. The aggregate RC gate records
`DO_NOT_RELEASE` until the maintainer explicitly accepts the named shared-node
WARN or the dedicated-node performance gate passes. The candidate SHA remains
frozen while that decision is pending.
+58
View File
@@ -0,0 +1,58 @@
# RFC-CTRL-0005 development verification
The stage A implementation and tests were verified at
`b1314328e6128cf1066cedaee06a8aa84cf1a405` against the
[issue baseline](https://git.cflmy.cn/cflmy/marqdo-cli/issues/7)
`f7a5a7b0163bf5229ed09adfffd892f9899e6667`.
## Linux results
The local run used Rust 1.98.1 on Linux x86_64 and the locked dependency
graph. A clean checkout under a path that Bubblewrap could mount was used
for workspace testing and packaging.
| Check | Result |
|---|---|
| Baseline workspace tests | 587 passed, 2 ignored |
| Workspace format and Clippy with warnings denied | Passed |
| Workspace tests | 595 passed, 2 ignored |
| CLI tests | 220 passed |
| Python CI tooling tests | 32 passed |
| Release archive smoke | Passed, including strict execution |
| Frozen extension lane with fixtures at `cf92e1ae7d22cb4bd1f5609c5fa8daa11e8980ec` | 7 contract groups and 6 reference applications passed |
| Archive-only control-flow example | Returned 5 in pure, project and strict modes |
| Archive-only independent protocol consumers | Analysis v2/v3, Trace v2 digest verification and Execution Events v1 passed. The legacy Analysis consumer rejected v3. |
The archive was built by `tools/release/package.py` and verified by
`tools/release/smoke.py` and `tools/ci/run_frozen_extensions.sh`.
Archive SHA-256 is
`00c486642c524ea699e3c83f151875b1048e9b4affc89565c79a3d29af4af9b7`.
The Rust commands were `cargo fmt --all -- --check`,
`cargo clippy --workspace --all-targets --locked --offline -- -D warnings`,
`cargo test --workspace --locked --offline --no-fail-fast -- --test-threads=1`
and `cargo test -p marqdo-cli --locked --offline -- --test-threads=1`.
GitHub and Woodpecker both contain independent schema and consumer checks.
## Coverage and consumer compatibility
- Semantic fixtures 80–88 cover ordered arms, short-circuiting, fallthrough,
empty arms, nested loops and branch bodies, contextual identifiers and
inert prose. Fixture 34 still exercises separately carried nested branches.
- The negative corpus covers unmatched and out-of-order arms, malformed
transfers, missing closure, function and heading bounds, and possibly
uninitialized reads on loop exit. Runtime tests cover non-boolean
conditions, fuel, deadlines and transfer containment at function boundaries.
- CLI tests compare Analysis, Trace and Execution Events source spans in UTF-8,
bind Trace to the emitted Analysis digest, verify the call graph and prove
that invalid input stops before execution. A property test compares
span-independent IR across Markdown list, quote and paragraph containers.
- The separately built `marqdo-lint 0.1.0` binary at repository commit
`58cea75` read the existing `hello.mq.md` Analysis v2 output. Its current
alignment logic reports `analysis_incomplete` for native `else if`,
and it rejects Analysis v3 because it supports only v2. Adoption of the
new nodes requires an update in the Lint repository.
These results record local implementation and archive verification.
Release inclusion and platform evidence remain subject to the maintainer's
release process.
+5 -2
View File
@@ -128,7 +128,10 @@ artifacts so the examples run without a compiler) and `tests/consumers/`.
`RELEASE_INFO.json` records the stdlib `name`, `version`, `tree_digest`, `RELEASE_INFO.json` records the stdlib `name`, `version`, `tree_digest`,
`aliases_digest`, `file_count` and `files`. `package.py` recomputes both digests `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 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 with `stdlib/stdlib.json` (RFC-EXT-0003 H-08 / T-PKG-04).
The `protocols.analysis` field identifies the default Analysis major.
`protocols.analysis_versions` lists all majors the archive can emit.
The archive smoke exercises a published example and a consumer for each major. The bundled stdlib is a
runtime requirement, not a build-machine side effect: a release binary must never runtime requirement, not a build-machine side effect: a release binary must never
fall back to the compile-time source path. fall back to the compile-time source path.
@@ -147,7 +150,7 @@ python3 tools/release/smoke.py \
It verifies the `.sha256`, `RELEASE_INFO.json`/`SOURCE_SHA`, both stdlib It verifies the `.sha256`, `RELEASE_INFO.json`/`SOURCE_SHA`, both stdlib
digests against `stdlib/stdlib.json` and the staged tree, offline 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/v3 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), the pure math package and optional unauthorized and missing-helper fail-closed), the pure math package and optional
+35
View File
@@ -0,0 +1,35 @@
# @knowledge 筛选读数
跳过无效读数,遇到停止标记时结束扫描,返回已接收读数的总和。
## @exec main
`读数 = [2, -1, 3, 0, 9]`
`位置 = 0`
`合计 = 0`
- `while 位置 < 长度(读数)`:逐项读取。
`当前 = 读数[位置]`
`位置 = 位置 + 1`
1. `if 当前 < 0`:跳过无效读数。
`continue`
2. `else if 当前 == 0`:遇到停止标记。
`break`
3. `else`:累计有效读数。
`合计 = 合计 + 当前`
`end`
`end`
`return 合计`
+4
View File
@@ -222,3 +222,7 @@ When that work ships (target `3.1.x`), it must use a new protocol version
source digest and the exact Analysis bytes digest; it must not rewrite v2 `units[]`. 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, 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. and must reject an unknown sidecar/v3 version rather than silently ignoring it.
Projects containing structured loop transfers use [Analysis v3](analysis-v3.md).
A v2 projection never contains those transfer statements. Multiple conditional
arms use the existing ordered `branch.arms` array.
+27
View File
@@ -0,0 +1,27 @@
# Marqdo Analysis v3
Analysis v3 extends the public [Analysis v2](analysis-v2.md) contract with
structured loop control. Its envelope keeps `schema: "marqdo.analysis"` and
sets `schema_version: 3`. The writer emits v3 if any emitted function body
contains either new statement, including inside a nested body or an imported
module. Other projects still emit v2. Multi-arm branches fit both versions.
## Statement additions
```json
{"kind": "break", "span": {"start": 30, "end": 37}}
{"kind": "continue", "span": {"start": 39, "end": 49}}
```
Both spans are half-open UTF-8 byte ranges covering the carrier in the
containing module. Walk the enclosing statement bodies to find the nearest
loop. `break` transfers to the statement after that loop. `continue`
transfers to its condition. There are no operands, labels or call edges.
Call and resource projections retain their v2 shapes.
Consumers check the major version before traversing any function body. A v2
reader rejects v3, while a reader that accepts both versions can share its
v2 decoding and add two statement kinds. Trace v2 binds to the version
automatically emitted for the same input via `source.analysis_digest`.
JSON Schema: [analysis-v3.schema.json](schemas/analysis-v3.schema.json).
+19 -21
View File
@@ -84,12 +84,14 @@ implicit string↔number conversions; conversion builtins must be called.
* `Return` — written as the `return <expr>` statement in an executable payload * `Return` — written as the `return <expr>` statement in an executable payload
— unwinds through any number of branch/loop bodies to the enclosing H2 — unwinds through any number of branch/loop bodies to the enclosing H2
function frame. A function that falls off the end still returns `Unit`. function frame. A function that falls off the end still returns `Unit`.
* `Branch` comes from an `if`/`else`/`end` group: the condition is evaluated * `Branch` evaluates `if` and `else if` conditions in order. Each reached
once, must be `Bool`, and exactly one arm executes (the `else` arm when condition is evaluated once and must be `Bool`. At most one arm executes.
present and the condition is false, otherwise the then arm). `Loop` comes When all conditions are false, the optional `else` arm executes.
from a `while`/`end` group and re-evaluates its `Bool` condition before each * A `while` loop evaluates its `Bool` condition before each iteration.
iteration. The control stack is compile-time only (`spec/mapping.md` §5); `Break` exits the nearest loop. `Continue` immediately returns to the
neither `end` nor `else` is a runtime instruction. nearest loop's condition check. Both are charged as statements and
preserve the loop's budget checks. Pairing and legality are checked
within each heading execution segment (see [mapping](mapping.md)).
* Imported modules only register definitions for the importing document; they * Imported modules only register definitions for the importing document; they
have no initialization side effects and their `main` is never started. have no initialization side effects and their `main` is never started.
* Function calls recurse; recursion depth is bounded by the stack budget. * Function calls recurse; recursion depth is bounded by the stack budget.
@@ -293,22 +295,18 @@ and `resource.exhausted` (region or run budget).
## 5. Parameter inference (static, name based) ## 5. Parameter inference (static, name based)
Parameters are discovered by definite-assignment data-flow analysis over the Definite-assignment analysis uses the function's structured control flow.
function's control-flow graph, never from prose: First-entry arguments are bound before the body executes. A read on a
reachable path with no possible prior assignment can establish an inferred
parameter. A partially assigned name without an entry binding is ambiguous
and raises `symbol.uninitialized`. With an explicit signature, unresolved
names raise `symbol.unknown`. Builtins and imported aliases are excluded
from parameter inference.
1. Build the CFG of the function body in AST order, with branch and loop An unconditional transfer stops the current sequence. A branch joins only
edges. Loop bodies may execute zero times. the arms that reach its next statement. A loop may skip the body if its
2. Compute the set of variables *definitely assigned* on every path from the condition can be false. Its normal and `continue` backedges lead to the
function entry. condition check and its `break` paths join the loop exit.
3. Every read of a variable that is not definitely assigned at that point and
that has no assignment anywhere in the function is a **candidate
parameter** (sorted by canonical name).
4. If a variable is assigned on some paths but read before that assignment on
others, its identity is ambiguous: emit `symbol.uninitialized` (S-04)
instead of inventing a parameter.
5. Exclude builtins, imported aliases and reserved names from inference.
6. A read that is not explained by a parameter, a local, a builtin or an
import is `symbol.unknown` with a hint (typo protection).
Consequences: `**结果 = n * 阶乘(n=n-1)**` infers `n`; `**n = 3**` followed by Consequences: `**结果 = n * 阶乘(n=n-1)**` infers `n`; `**n = 3**` followed by
reads makes `n` a local. Inferred parameters are named arguments only; an reads makes `n` a local. Inferred parameters are named arguments only; an
+9 -4
View File
@@ -118,7 +118,7 @@ Required payload fields: `entry`, `mode`, `source`; optional
``` ```
`source.analysis_digest` is `sha256:` plus the SHA-256 of the **exact bytes** `source.analysis_digest` is `sha256:` plus the SHA-256 of the **exact bytes**
of the Analysis v2 file produced for the same project and projection of the [Analysis file](analysis-v3.md) produced for the same project and projection
configuration (not a re-serialization of the in-memory IR). If the source configuration (not a re-serialization of the in-memory IR). If the source
changes, existing events become stale; consumers must not render them onto the changes, existing events become stale; consumers must not render them onto the
new source. new source.
@@ -152,6 +152,7 @@ Required payload fields:
| `return` | `frame_id`, `value_type`, `module_id`, `span` | | `return` | `frame_id`, `value_type`, `module_id`, `span` |
| `branch.eval` | `frame_id`, `result`, `module_id`, `span` | | `branch.eval` | `frame_id`, `result`, `module_id`, `span` |
| `loop.iteration` | `frame_id`, `decision`, `module_id`, `span` | | `loop.iteration` | `frame_id`, `decision`, `module_id`, `span` |
| `control.break`, `control.continue` | `frame_id`, `module_id`, non-null `span` |
| `effect` | `operation`, `result_code`, `module_id`, `span` | | `effect` | `operation`, `result_code`, `module_id`, `span` |
* `frame_id` is an opaque run-unique string (`f1`, `f2`, ...). It identifies * `frame_id` is an opaque run-unique string (`f1`, `f2`, ...). It identifies
@@ -166,6 +167,10 @@ Required payload fields:
* `branch.eval.result` is a JSON boolean. `loop.iteration.decision` is * `branch.eval.result` is a JSON boolean. `loop.iteration.decision` is
`continue` (body will execute) or `exit` (condition was false). The event is `continue` (body will execute) or `exit` (condition was false). The event is
emitted once per condition evaluation; iteration indices are not part of v1. emitted once per condition evaluation; iteration indices are not part of v1.
* `control.break` and `control.continue` report an executed transfer at
its carrier span. The frame stays active. A continue precedes the next
condition check, and a break skips further checks of the loop it exits.
The structural event budget applies to both events.
* `effect.result_code` is a non-sensitive result summary (for example `ok` or a * `effect.result_code` is a non-sensitive result summary (for example `ok` or a
stable error code). It never carries effect arguments or file contents. stable error code). It never carries effect arguments or file contents.
* `module_id` is a logical package module id; `span` is * `module_id` is a logical package module id; `span` is
@@ -291,7 +296,7 @@ authorization are unchanged.
* Program stdout/stderr may contain secrets by the program's own intent; the * Program stdout/stderr may contain secrets by the program's own intent; the
protocol preserves bytes and does not promise automatic redaction of program protocol preserves bytes and does not promise automatic redaction of program
output. output.
* Trace v2 and Analysis v2 never gain argument/local values, handles, memory * Trace v2 and Analysis never gain argument/local values, handles, memory
bytes or new secret-bearing fields through this protocol. bytes or new secret-bearing fields through this protocol.
* A third-party extension's raw OS stdout/stderr must not pollute the JSONL * A third-party extension's raw OS stdout/stderr must not pollute the JSONL
channel. Such output remains external process data: it is either captured by channel. Such output remains external process data: it is either captured by
@@ -303,11 +308,11 @@ authorization are unchanged.
* Tests use synthetic sentinel values and assert that unselected values never * Tests use synthetic sentinel values and assert that unselected values never
appear in the stream, Trace or `--json`. appear in the stream, Trace or `--json`.
## 6. Relation to Analysis v2 and Trace v2 ## 6. Relation to Analysis and Trace v2
| Artifact | Relation | | Artifact | Relation |
|---|---| |---|---|
| Analysis v2 | Static only. `run.started.source` binds to its exact bytes via `analysis_digest`. Events never replace it. | | Analysis v2/v3 | Static only. `run.started.source` binds to its exact bytes via `analysis_digest`. Events never replace it. |
| Trace v2 | Unchanged schema/version and privacy promise. In a combined run both writers share the CLI-generated `run_id`; Trace v2 gains no frame/value fields and is still published atomically after the run. | | Trace v2 | Unchanged schema/version and privacy promise. In a combined run both writers share the CLI-generated `run_id`; Trace v2 gains no frame/value fields and is still published atomically after the run. |
| Tool Protocol v1 | Unchanged. A consumer invokes the released binary via `MARQDO_BIN` and negotiates by reading `stream.opened`; `tool.json` does not implicitly advertise an `events` field. | | Tool Protocol v1 | Unchanged. A consumer invokes the released binary via `MARQDO_BIN` and negotiates by reading `stream.opened`; `tool.json` does not implicitly advertise an `events` field. |
| View SSE | Implemented by the View repository by adapting this JSONL stream. The CLI implements no HTTP/SSE. | | View SSE | Implemented by the View repository by adapting this JSONL stream. The CLI implements no HTTP/SSE. |
+18 -18
View File
@@ -7,17 +7,18 @@
it lives; this grammar decides what that payload means. No second parser it lives; this grammar decides what that payload means. No second parser
and no per-file syntax selector exists. and no per-file syntax selector exists.
Implementation state: the Rust expression parser still implements the See docs/STATUS.md for implementation and release status.
previous, control-free grammar; this file is the target contract. See
docs/STATUS.md.
*) *)
(* One payload is exactly one statement and must consume the whole payload. *) (* One payload is exactly one statement and must consume the whole payload. *)
payload = statement , EOF ; payload = statement , EOF ;
statement = if_stmt statement = if_stmt
| else_if_stmt
| else_stmt | else_stmt
| while_stmt | while_stmt
| break_stmt
| continue_stmt
| end_stmt | end_stmt
| return_stmt | return_stmt
| params_stmt | params_stmt
@@ -25,28 +26,27 @@ statement = if_stmt
| expression ; | expression ;
if_stmt = "if" , space_required , expression ; if_stmt = "if" , space_required , expression ;
else_if_stmt = "else" , space_required , "if" , space_required , expression ;
else_stmt = "else" ; else_stmt = "else" ;
while_stmt = "while" , space_required , expression ; while_stmt = "while" , space_required , expression ;
break_stmt = "break" ;
continue_stmt = "continue" ;
end_stmt = "end" ; end_stmt = "end" ;
return_stmt = "return" , space_required , expression ; return_stmt = "return" , space_required , expression ;
params_stmt = "params" , "(" , [ parameter_list ] , ")" ; params_stmt = "params" , "(" , [ parameter_list ] , ")" ;
(* `if`, `else`, `while`, `end`, `return` and `params` are reserved statement (* `if`, `else`, `while`, `end`, `return` and `params` are reserved words.
words only when they are the complete first token of a payload. `break` and `continue` are contextual: a complete payload of exactly that
`ifdef(x)` and `returning(x)` are ordinary identifiers; a bare `if` used as identifier takes precedence over the ordinary expression production.
an identifier is a reserved-word error. `else`/`end` take no additional Calls, assignments and uses inside expressions retain their identifier
tokens: `else x` and `end if` are syntax errors. No trailing colon: meaning. Neither loop-control statement takes operands or a label.
`if x > 0:` is a syntax error. No `elif`, `for`, `break`, `continue`, No trailing colon, `elif`, `for`, `try`, empty `return`, `end if`, or
`try`, empty `return`, `end if`, or semicolon-separated multi-statement semicolon-separated multi-statement payload is supported.
payload exists in this revision.
Control pairing is not part of this grammar; it is a separate compile-time The frontend pairs statements inside each heading execution segment.
stack in the frontend: Each `if` takes zero or more `else if` arms and at most one final `else`.
- every `if` has exactly one closing `end`; Each `if` and `while` takes one closing `end`. A loop control statement
- `else` is optional and at most one per `if`; requires an open `while` in the same segment. See mapping.md.
- every `while` has exactly one closing `end`;
- `else` must bind the top-of-stack `if`; `end` closes the top frame;
- a frame must close inside the same heading's direct body.
*) *)
(* Function parameter declaration. It is legal only as the first direct (* Function parameter declaration. It is legal only as the first direct
+42 -37
View File
@@ -23,8 +23,8 @@ Markdown→program mapping changes.
3. **Closed carriers carry one statement each.** In an Exec scope, `Strong`, 3. **Closed carriers carry one statement each.** In an Exec scope, `Strong`,
`Emph` and inline `Code` are interchangeable carriers of one payload. They `Emph` and inline `Code` are interchangeable carriers of one payload. They
no longer mean execute/return/lazy respectively. no longer mean execute/return/lazy respectively.
4. **Keywords inside the payload decide the operation.** `if`, `else`, `while`, 4. **Keywords inside the payload decide the operation.** `if`, `else if`, `else`, `while`, `break`,
`end`, `return`, `params(...)`, assignment and expression statements. Lists, `continue`, `end`, `return`, `params(...)`, assignment and expression statements. Lists,
block quotes and paragraphs are document containers only. block quotes and paragraphs are document containers only.
5. **Errors never fall back to prose.** Once a payload is extracted from an 5. **Errors never fall back to prose.** Once a payload is extracted from an
Exec scope it must parse fully; a failure is a diagnostic. Exec scope it must parse fully; a failure is a diagnostic.
@@ -217,8 +217,9 @@ Each extracted payload is exactly one statement, defined by
`spec/expression.ebnf`: `spec/expression.ebnf`:
```text ```text
if <expr> else while <expr> end if <expr> else if <expr> else end
return <expr> params(...) assignment expression while <expr> break continue
return <expr> params(...) assignment expression
``` ```
Lexical details: Lexical details:
@@ -226,13 +227,16 @@ Lexical details:
* Keywords are recognized only as complete first tokens: `ifdef(...)` and * Keywords are recognized only as complete first tokens: `ifdef(...)` and
`returning` are ordinary identifiers; a bare `if`/`else` used as an `returning` are ordinary identifiers; a bare `if`/`else` used as an
identifier is a reserved-keyword error. identifier is a reserved-keyword error.
* `if`, `while` and `return` require a non-empty expression that consumes the * `if`, `else if`, `while` and `return` require whitespace followed by an
whole payload (to EOF). Trailing characters are errors. expression that consumes the whole payload. Trailing colons are
* `else` and `end` accept no additional tokens; `else x` and `end if` are `sem.syntax`. `else` and `end` take no arguments.
`sem.syntax`. * `break` and `continue` are loop control only when the complete payload is
* No trailing colon: `if x > 0:` is `sem.syntax`. No `elif`, `for`, `break`, the single identifier. `break 2` and `continue label` are syntax errors.
`continue`, `try`, `end if` or semicolon-separated statements in this `break(1)`, `continue = 1` and `return break` retain their ordinary call,
version. assignment and expression meanings. To read a variable named `break` or
`continue` as an expression statement, parenthesize the identifier.
* `elif`, `for`, `try` and semicolon-separated statements are outside this
grammar.
* `return` always requires an expression; falling off the end of a function * `return` always requires an expression; falling off the end of a function
still returns `Unit`. Explicit `return None` is available when `None` is the still returns `Unit`. Explicit `return None` is available when `None` is the
intended value. intended value.
@@ -244,33 +248,30 @@ Lexical details:
## 5. Control-stack lowering ## 5. Control-stack lowering
Within one execution segment, payloads form a token stream. Lower it with one Within one execution segment, payloads form an ordered statement stream.
explicit stack: The innermost open control block owns its body.
```text * `if` opens a branch with zero or more subsequent `else if` arms and one
open_if(cond) -> push IfFrame(cond, then=[], else=None) optional final `else`. Each arm starts in its own carrier. Two carriers
statement -> append to the innermost active body containing `else` and `if` still open a nested branch and require separate
else -> require top is IfFrame with else=None; switch to else body closing `end` statements. An empty arm is legal.
open_while(cond)-> push WhileFrame(cond, body=[]) * `else if` and `else` must bind the innermost open block, which must be an
end -> require a non-empty stack; pop the top frame and lower it `if`. A second `else` or an `else if` after `else` is a hard error.
at_segment_end -> require the stack to be empty * `end` closes the innermost open `if` or `while`. Reaching a segment
``` boundary with an open block is a hard error on the opener.
* All conditional arms lower to one ordered `Branch`. Evaluate conditions
Rules: left to right and execute only the first matching arm. If all are false,
execute the optional `else` body or proceed to the next statement.
* `else` pairs with the top-of-stack `IfFrame` only. It may not skip an open Each conditional arm has its own source span.
`while` or an inner `if`. * `while` lowers to `Loop`. `break` exits the nearest open loop and
* At most one `else` per `if`; `else` with no open `if` is `continue` skips the rest of its body and rechecks its condition. Both
`sem.unmatched_else`; a second `else` is `sem.duplicate_else`. require a loop in the same function and heading execution segment.
* `end` closes exactly the most recent open `if`/`while`; no match is `return` exits the whole function, including from inside a loop.
`sem.unmatched_end`. * Definite-assignment inference merges reachable fallthrough paths. Loop
* Reaching a segment boundary with an open frame is `sem.unclosed_control`, exits include condition-failure and `break` paths. `continue` and
with a related span on the opener. The compiler must not synthesize an `end`. ordinary body fallthrough lead back to the condition. An abrupt transfer
* `if` lower to the existing `Branch` IR; the optional `else` may lower to a stops inference from its remaining sequence. A reachable free read of an
final unconditional arm while preserving left-to-right short-circuit inferred parameter establishes its entry binding before any reassignment.
evaluation and executing at most one arm. `while` lowers to `Loop`; `return`
lowers to `Return` and unwinds the whole H2 function. `else`/`end` generate no
runtime instruction of their own.
## 6. Functions, signatures and calls ## 6. Functions, signatures and calls
@@ -333,6 +334,10 @@ Stable machine-readable codes (the human `message`/`hint` text may change):
| `sem.empty_payload` | an empty carrier in an Exec scope | | `sem.empty_payload` | an empty carrier in an Exec scope |
| `sem.syntax` | malformed statement, missing condition/value, trailing tokens, colon, unsupported keyword | | `sem.syntax` | malformed statement, missing condition/value, trailing tokens, colon, unsupported keyword |
| `sem.unmatched_else` | `else` with no open `if` at the top of the stack | | `sem.unmatched_else` | `else` with no open `if` at the top of the stack |
| `sem.unmatched_else_if` | `else if` with no open `if` at the top of the stack |
| `sem.else_if_after_else` | `else if` after the final `else` of the same `if` |
| `sem.break_outside_loop` | `break` with no open loop in this heading segment |
| `sem.continue_outside_loop` | `continue` with no open loop in this heading segment |
| `sem.duplicate_else` | a second `else` for the same `if` | | `sem.duplicate_else` | a second `else` for the same `if` |
| `sem.unmatched_end` | `end` with no open control frame | | `sem.unmatched_end` | `end` with no open control frame |
| `sem.unclosed_control` | an open `if`/`while` at a heading/function/file boundary | | `sem.unclosed_control` | an open `if`/`while` at a heading/function/file boundary |
+376
View File
@@ -0,0 +1,376 @@
{
"$schema": "https://json-schema.org/draft/2020-12/schema",
"$id": "https://marqdo.dev/schemas/analysis-v3.schema.json",
"title": "Marqdo Analysis v3",
"type": "object",
"required": [
"schema",
"schema_version",
"producer",
"project",
"modules",
"diagnostics"
],
"properties": {
"schema": {
"const": "marqdo.analysis"
},
"schema_version": {
"const": 3
},
"producer": {
"type": "object",
"required": [
"name",
"version",
"markdown_profile"
],
"properties": {
"name": {
"type": "string"
},
"version": {
"type": "string"
},
"markdown_profile": {
"const": "marqdo.md.v1"
}
},
"additionalProperties": true
},
"project": {
"type": "object",
"required": [
"root_id",
"identity_kind",
"lock_digest"
],
"properties": {
"root_id": {
"type": "string",
"minLength": 1,
"pattern": "^(root:|sha256:[0-9a-f]{64}$)"
},
"identity_kind": {
"enum": [
"manifest",
"workspace_snapshot"
]
},
"lock_digest": {
"type": "string",
"pattern": "^(sha256:[0-9a-f]{64})?$"
}
},
"additionalProperties": true
},
"modules": {
"type": "array",
"items": {
"type": "object",
"required": [
"id",
"package_instance_id",
"relative_path",
"source_digest",
"units",
"functions",
"imports",
"references",
"calls",
"resources"
],
"properties": {
"id": {
"type": "string",
"pattern": "::"
},
"package_instance_id": {
"type": "string",
"minLength": 1
},
"relative_path": {
"type": "string",
"minLength": 1,
"pattern": "^(?!/)(?!.*\\.\\.)"
},
"source_digest": {
"type": "string",
"pattern": "^[0-9a-f]{64}$"
},
"units": {
"type": "array"
},
"functions": {
"type": "array",
"items": {
"type": "object",
"required": [
"body"
],
"properties": {
"body": {
"$ref": "#/$defs/body"
}
}
}
},
"imports": {
"type": "array"
},
"references": {
"type": "array"
},
"calls": {
"type": "array"
},
"resources": {
"type": "array",
"items": {
"type": "object",
"required": [
"id",
"module_id",
"unit_id",
"kind",
"span",
"content_digest"
],
"properties": {
"id": {
"type": "string",
"pattern": "#resource:(formula|code)-[0-9]+$"
},
"module_id": {
"type": "string",
"pattern": "::"
},
"unit_id": {
"type": "string",
"minLength": 1
},
"kind": {
"enum": [
"formula",
"code"
]
},
"span": {
"type": "object",
"required": [
"start",
"end"
],
"properties": {
"start": {
"type": "integer",
"minimum": 0
},
"end": {
"type": "integer",
"minimum": 0
}
},
"additionalProperties": true
},
"content_digest": {
"type": "string",
"pattern": "^[0-9a-f]{64}$"
},
"language": {
"type": [
"string",
"null"
]
},
"display": {
"type": "boolean"
}
},
"additionalProperties": true
}
}
},
"additionalProperties": true
}
},
"diagnostics": {
"type": "array",
"items": {
"type": "object",
"required": [
"module",
"relative_path",
"severity",
"code",
"message"
],
"properties": {
"module": {
"type": "string",
"pattern": "::"
},
"relative_path": {
"type": "string",
"minLength": 1
},
"span": {
"type": [
"object",
"null"
],
"required": [
"start",
"end"
],
"properties": {
"start": {
"type": "integer",
"minimum": 0
},
"end": {
"type": "integer",
"minimum": 0
}
}
},
"line": {
"type": [
"integer",
"null"
],
"minimum": 1
},
"column": {
"type": [
"integer",
"null"
],
"minimum": 1
},
"severity": {
"enum": [
"error",
"warning"
]
},
"code": {
"type": "string",
"minLength": 1
},
"message": {
"type": "string",
"minLength": 1
},
"hints": {
"type": "array",
"items": {
"type": "string"
}
}
},
"additionalProperties": true
}
}
},
"additionalProperties": true,
"$defs": {
"body": {
"type": "array",
"items": {
"$ref": "#/$defs/statement"
}
},
"span": {
"type": "object",
"required": [
"start",
"end"
],
"properties": {
"start": {
"type": "integer",
"minimum": 0
},
"end": {
"type": "integer",
"minimum": 0
}
}
},
"statement": {
"type": "object",
"required": [
"kind",
"span"
],
"properties": {
"kind": {
"enum": [
"assign",
"expression",
"branch",
"loop",
"return",
"break",
"continue"
]
},
"span": {
"$ref": "#/$defs/span"
}
},
"allOf": [
{
"if": {
"properties": {
"kind": {
"const": "loop"
}
}
},
"then": {
"required": [
"body"
],
"properties": {
"body": {
"$ref": "#/$defs/body"
}
}
}
},
{
"if": {
"properties": {
"kind": {
"const": "branch"
}
}
},
"then": {
"required": [
"arms"
],
"properties": {
"arms": {
"type": "array",
"items": {
"type": "object",
"required": [
"body"
],
"properties": {
"body": {
"$ref": "#/$defs/body"
}
}
}
}
}
}
}
]
}
}
}
@@ -154,6 +154,23 @@
} }
} }
}, },
{
"if": {"required": ["kind"], "properties": {"kind": {"enum": ["control.break", "control.continue"]}}},
"then": {
"properties": {
"payload": {
"type": "object",
"required": ["frame_id", "module_id", "span"],
"properties": {
"frame_id": {"type": "string", "pattern": "^f[0-9]+$"},
"module_id": {"type": "string", "minLength": 1},
"span": {"type": "object", "$ref": "#/$defs/span"}
},
"additionalProperties": true
}
}
}
},
{ {
"if": {"required": ["kind"], "properties": {"kind": {"enum": ["variable.assigned", "parameter.observed"]}}}, "if": {"required": ["kind"], "properties": {"kind": {"enum": ["variable.assigned", "parameter.observed"]}}},
"then": { "then": {
+1 -1
View File
@@ -1,6 +1,6 @@
# Marqdo Security Model (implemented status) # Marqdo Security Model (implemented status)
Status: describes enforcement in the `3.0.0-rc.1` candidate. Status: describes enforcement in the `3.0.0-rc.2` candidate.
Normative implementation: Normative implementation:
+4 -3
View File
@@ -29,7 +29,7 @@
} }
``` ```
类型:`schema` 固定字符串,`schema_version` 正整数(首版仅 1),`name`/`version`/`command`/`entrypoint` 非空字符串,`version` 必须是合法 SemVer,`compatibility.marqdo` 必须是可解析的 SemVer 范围,`analysis`、`trace` 为可选的非空正整数数组;仅当工具使用该数据协议时声明。当前核心提供 Analysis v2 与 Trace v2,因此声明 `[1]`(或与 `[2]` 无交集)会在安装/分发时被拒绝。未来可以增加可选字段,但不得改变现有字段含义。 类型:`schema` 固定字符串,`schema_version` 正整数(首版仅 1),`name`/`version`/`command`/`entrypoint` 非空字符串,`version` 必须是合法 SemVer,`compatibility.marqdo` 必须是可解析的 SemVer 范围,`analysis`、`trace` 为可选的非空正整数数组;仅当工具使用该数据协议时声明。当前开发分支提供 Analysis v2/v3 与 Trace v2。声明与对应版本集合无交集时,安装和分发会拒绝。未来可以增加可选字段,但不得改变现有字段含义。
`command`:建议 `^[a-z][a-z0-9-]*$`,不得与任何内置命令或保留参数冲突;同一注册表中命令唯一,名字冲突拒绝且不覆盖。`entrypoint`:包内受控相对路径,不能是绝对路径、`.`/`..` 跳出根目录、符号链接逃逸或可直接解释的任意 shell 片段。真实文件应可执行并与目标平台匹配;若扩展名或平台格式与 OS 不兼容应显式失败。 `command`:建议 `^[a-z][a-z0-9-]*$`,不得与任何内置命令或保留参数冲突;同一注册表中命令唯一,名字冲突拒绝且不覆盖。`entrypoint`:包内受控相对路径,不能是绝对路径、`.`/`..` 跳出根目录、符号链接逃逸或可直接解释的任意 shell 片段。真实文件应可执行并与目标平台匹配;若扩展名或平台格式与 OS 不兼容应显式失败。
@@ -47,7 +47,8 @@
工具负责自己的命令层级与帮助,如 `marqdo benchmark run .`、`marqdo benchmark --help`。CLI 不读取或修改工具业务选项。Rust `clap` 可通过单一 `external_subcommand` 捕获未知子命令,但必须保留 `OsString` 原样传参;不能让工具要求 CLI 添加 `Command::View` 等专门枚举项。不要求工具在处理 `--help` 时调用核心。未知命令时报错;即使 PATH 中存在 `marqdo-<first>`,**没有显式注册也不能执行它**。 工具负责自己的命令层级与帮助,如 `marqdo benchmark run .`、`marqdo benchmark --help`。CLI 不读取或修改工具业务选项。Rust `clap` 可通过单一 `external_subcommand` 捕获未知子命令,但必须保留 `OsString` 原样传参;不能让工具要求 CLI 添加 `Command::View` 等专门枚举项。不要求工具在处理 `--help` 时调用核心。未知命令时报错;即使 PATH 中存在 `marqdo-<first>`,**没有显式注册也不能执行它**。
可选辅助环境:`MARQDO_BIN`(当前核心 CLI 的绝对路径),`MARQDO_TOOL_PROTOCOL=1`;仅当工具声明并协商了对应协议时,额外设置 `MARQDO_PROTOCOL_ANALYSIS=2` 与/或 `MARQDO_PROTOCOL_TRACE=2`。工具通过此路径运行 `marqdo check ... --emit ...` 和 `marqdo run ... --trace-file ...`,不拥有额外宿主内部 API。不得自动将密钥、项目能力授予记录、ABI 插件加载句柄或用户外联会话传给工具。 可选辅助环境:`MARQDO_BIN`(当前核心 CLI 的绝对路径),`MARQDO_TOOL_PROTOCOL=1`;仅当工具声明并协商了对应协议时,额外设置 `MARQDO_PROTOCOL_ANALYSIS` 与/或 `MARQDO_PROTOCOL_TRACE`,值是双方支持的最高版本。
Analysis 写入器按项目内容选择版本。工具应先检查输出的 `schema_version`,支持两版的工具声明 `analysis: [2, 3]`。工具通过此路径运行 `marqdo check ... --emit ...` 和 `marqdo run ... --trace-file ...`,不拥有额外宿主内部 API。不得自动将密钥、项目能力授予记录、ABI 插件加载句柄或用户外联会话传给工具。
## 5. 三个独立安全域 ## 5. 三个独立安全域
@@ -57,7 +58,7 @@
## 6. 向后兼容 ## 6. 向后兼容
`schema_version` 不支持、`marqdo` 范围不匹配、工具版本不是合法 SemVer,或声明的 Analysis/Trace 列表与核心支持集(当前 `analysis: [2]`、`trace: [2]`)无交集时,安装与分发都必须以稳定错误拒绝;错误信息包含 `tool.protocol_incompatible`。可忽略的未知扩展字段允许透传,但不能被视为隐含授权。没有声明数据协议的工具不受该检查约束,也不会收到协议环境变量。 `schema_version` 不支持、`marqdo` 范围不匹配、工具版本不是合法 SemVer,或声明的 Analysis/Trace 列表与核心支持集(当前 `analysis: [2, 3]`、`trace: [2]`)无交集时,安装与分发都必须以稳定错误拒绝;错误信息包含 `tool.protocol_incompatible`。可忽略的未知扩展字段允许透传,但不能被视为隐含授权。没有声明数据协议的工具不受该检查约束,也不会收到协议环境变量。
原生命令集合是保留命名空间;未来新增与社区工具冲突的新核心顶层命令属于破坏性变化,必须经过 ADR、迁移期诊断和工具冲突统计,不能静默覆盖已有已注册工具。 原生命令集合是保留命名空间;未来新增与社区工具冲突的新核心顶层命令属于破坏性变化,必须经过 ADR、迁移期诊断和工具冲突统计,不能静默覆盖已有已注册工具。
+10 -3
View File
@@ -8,7 +8,7 @@ Supersedes Trace v1; v1 was never released and is kept as history.
* Tracing is observation, not execution. Only `run`/`call` produce a trace; * Tracing is observation, not execution. Only `run`/`call` produce a trace;
`check`, `inspect` and `tool list` never execute a document. `check`, `inspect` and `tool list` never execute a document.
* Events come from the interpreter (`call.*`, `branch.eval`, * Events come from the interpreter (`call.*`, `branch.eval`,
`loop.iteration`, `return`) and the host (`effect`). Both share one sequence. `loop.iteration`, `control.break`, `control.continue`, `return`) and the host (`effect`). Both share one sequence.
* The writer is atomic; an error run still records its terminal status. * The writer is atomic; an error run still records its terminal status.
* No argument values, secrets, handles or file contents are recorded. * No argument values, secrets, handles or file contents are recorded.
* Trace capacity is a bounded observation budget. Reaching it truncates the * Trace capacity is a bounded observation budget. Reaching it truncates the
@@ -41,10 +41,11 @@ code. Every span-bearing event has a `module_id`; the span is a UTF-8 byte
offset range in that module. `source` only carries project identity and the offset range in that module. `source` only carries project identity and the
Analysis digest; it does not identify the span owner. Analysis digest; it does not identify the span owner.
`source.root_id` is the Analysis v2 `project.root_id` `source.root_id` is the emitted Analysis `project.root_id`
(`root:<name>@<version>` or `sha256:<workspace snapshot>`). (`root:<name>@<version>` or `sha256:<workspace snapshot>`).
`source.analysis_digest` is `sha256:` plus the SHA-256 of the exact Analysis `source.analysis_digest` is `sha256:` plus the SHA-256 of the exact Analysis
v2 bytes produced for the same project with the same projection configuration. bytes produced for the same project with the same projection configuration.
The [Analysis writer](analysis-v3.md) selects v2 or v3 from the project.
A consumer verifies it by hashing the Analysis file. A consumer verifies it by hashing the Analysis file.
`truncated` is `null` or: `truncated` is `null` or:
@@ -66,9 +67,15 @@ event is `{"kind":"trace.truncated","detail":<reason>,"module_id":null,
| `return` | value type name | current function’s module | | `return` | value type name | current function’s module |
| `branch.eval` | `true` / `false` | current function’s module | | `branch.eval` | `true` / `false` | current function’s module |
| `loop.iteration` | `continue` / `exit` | current function’s module | | `loop.iteration` | `continue` / `exit` | current function’s module |
| `control.break` | null | current function’s module |
| `control.continue` | null | current function’s module |
| `effect` | result summary | module from `ExecutionContext` | | `effect` | result summary | module from `ExecutionContext` |
| `trace.truncated` | `event_budget` / `byte_budget` | null | | `trace.truncated` | `event_budget` / `byte_budget` | null |
The explicit transfer events carry the keyword carrier span. `control.continue`
precedes the next evaluation of the enclosing loop condition. `control.break`
leaves that loop without a further condition evaluation.
`function_id` is always the canonical callee function id. Future kinds are `function_id` is always the canonical callee function id. Future kinds are
additive; consumers must ignore unknown kinds. `effect.operation` names the additive; consumers must ignore unknown kinds. `effect.operation` names the
`HostOp` (`print`, `fs.read`, ...). `HostOp` (`print`, `fs.read`, ...).
@@ -1,5 +1,7 @@
## @exec 符号 ## @exec 符号
Regression fixture for separate else and if carriers forming nested branches.
`if n < 0` `if n < 0`
`return -1` `return -1`
@@ -0,0 +1,14 @@
{
"args": {
"数值": {
"decimal": "2",
"type": "int"
}
},
"function": "分类",
"stdout": "",
"value": {
"decimal": "2",
"type": "int"
}
}
@@ -0,0 +1,21 @@
## @exec 分类
`params(数值: Int)`
1. `if 数值 < 0`
`return -1`
2. **else if 数值 == 2**
`return 2`
3. *else if 1 / 0 > 0*
`return 3`
4. `else`
`return 4`
`end`
@@ -0,0 +1,9 @@
{
"args": {},
"function": "main",
"stdout": "",
"value": {
"decimal": "7",
"type": "int"
}
}
@@ -0,0 +1,9 @@
## @exec main
`if false`
`else if false`
`end`
`return 7`
@@ -0,0 +1,9 @@
{
"args": {},
"function": "main",
"stdout": "",
"value": {
"decimal": "5",
"type": "int"
}
}
@@ -0,0 +1,15 @@
## @exec main
`if false`
`else if true`
This selected arm contains prose only.
`else`
`return 9`
`end`
`return 5`
@@ -0,0 +1,9 @@
{
"args": {},
"function": "main",
"stdout": "",
"value": {
"decimal": "7",
"type": "int"
}
}
@@ -0,0 +1,13 @@
## @exec main
- `while true`
**结果 = 6**
`break`
`结果 = 未到达`
`end`
`return 结果 + 1`
@@ -0,0 +1,9 @@
{
"args": {},
"function": "main",
"stdout": "",
"value": {
"decimal": "3",
"type": "int"
}
}
@@ -0,0 +1,15 @@
## @exec main
`位置 = 0`
`while 位置 < 3`
`位置 = 位置 + 1`
`continue`
`return 未到达`
`end`
`return 位置`
@@ -0,0 +1,9 @@
{
"args": {},
"function": "main",
"stdout": "",
"value": {
"decimal": "26",
"type": "int"
}
}
@@ -0,0 +1,41 @@
## @exec main
`外 = 0`
`合计 = 0`
`while 外 < 3`
`外 = 外 + 1`
`内 = 0`
`while 内 < 4`
`内 = 内 + 1`
`if 内 == 1`
`continue`
`else if 内 == 3`
`break`
`end`
`合计 = 合计 + 外`
`end`
`if 外 == 2`
`continue`
`end`
`合计 = 合计 + 10`
`end`
`return 合计`
@@ -0,0 +1,9 @@
{
"args": {},
"function": "main",
"stdout": "",
"value": {
"decimal": "42",
"type": "int"
}
}
@@ -0,0 +1,25 @@
## @exec main
The words continue and break in this sentence are ordinary prose.
`while true`
`if false`
`break`
`else if true`
`return 42`
`end`
`continue`
`end`
`return 未到达`
### @knowledge Control vocabulary
`break` and **continue** and *else if* are examples of inert text here.
@@ -0,0 +1,9 @@
{
"args": {},
"function": "main",
"stdout": "",
"value": {
"decimal": "5",
"type": "int"
}
}
@@ -0,0 +1,11 @@
## @exec break
`params(continue: Int)`
`return continue + 1`
## @exec main
`continue = break(4)`
`return continue`
@@ -0,0 +1,9 @@
{
"args": {},
"function": "main",
"stdout": "",
"value": {
"decimal": "4",
"type": "int"
}
}
@@ -0,0 +1,41 @@
## @exec main
`轮次 = 0`
`合计 = 0`
`while 轮次 < 4`
`轮次 = 轮次 + 1`
`if 轮次 == 1`
`合计 = 合计 + 1`
`else if 1 / (轮次 - 1) > 0`
`if 轮次 == 2`
`continue`
`else`
`合计 = 合计 + 3`
`break`
`end`
`else if 1 / 0 > 0`
`return -1`
`else`
`return -2`
`end`
`end`
`return 合计`
+45
View File
@@ -0,0 +1,45 @@
#!/usr/bin/env python3
"""Read loop transfers from public Analysis JSON using only Python."""
import json
import pathlib
import sys
def visit(body, loop_span=None):
for statement in body:
kind = statement["kind"]
if kind == "loop":
yield from visit(statement["body"], statement["span"])
elif kind == "branch":
for arm in statement["arms"]:
yield from visit(arm["body"], loop_span)
elif kind in ("break", "continue"):
if loop_span is None:
raise SystemExit(f"{kind} outside a projected loop")
span = statement["span"]
if not 0 <= loop_span["start"] < span["start"] < span["end"]:
raise SystemExit(f"invalid {kind} carrier span")
yield kind, loop_span["start"]
elif kind not in ("assign", "expression", "return"):
raise SystemExit(f"unsupported statement kind {kind}")
def main():
if len(sys.argv) != 2:
raise SystemExit("usage: analysis_v3_consumer.py ANALYSIS.json")
analysis = json.loads(pathlib.Path(sys.argv[1]).read_text(encoding="utf-8"))
if analysis.get("schema") != "marqdo.analysis" or analysis.get("schema_version") != 3:
raise SystemExit("unsupported Analysis schema version")
transfers = [
transfer
for module in analysis["modules"]
for function in module["functions"]
for transfer in visit(function["body"])
]
if not transfers:
raise SystemExit("missing loop transfers")
print(f"transfers={len(transfers)} nearest_loops={len({target for _, target in transfers})}")
if __name__ == "__main__":
main()
+1 -1
View File
@@ -13,7 +13,7 @@ analysis = json.loads(analysis_bytes)
with open(sys.argv[2], encoding="utf-8") as handle: with open(sys.argv[2], encoding="utf-8") as handle:
trace = json.load(handle) trace = json.load(handle)
if analysis.get("schema") != "marqdo.analysis" or analysis.get("schema_version") != 2: if analysis.get("schema") != "marqdo.analysis" or analysis.get("schema_version") not in (2, 3):
raise SystemExit("unsupported analysis") raise SystemExit("unsupported analysis")
if trace.get("schema") != "marqdo.trace" or trace.get("schema_version") != 2: if trace.get("schema") != "marqdo.trace" or trace.get("schema_version") != 2:
raise SystemExit("unsupported trace") raise SystemExit("unsupported trace")
+10 -4
View File
@@ -48,22 +48,28 @@ def main():
trace = json.loads(trace_path.read_text(encoding="utf-8")) trace = json.loads(trace_path.read_text(encoding="utf-8"))
tool = json.loads(tool_path.read_text(encoding="utf-8")) tool = json.loads(tool_path.read_text(encoding="utf-8"))
require_valid("analysis-v2.schema.json", analysis, "analysis") version = analysis.get("schema_version")
if version not in (2, 3):
raise SystemExit("unsupported Analysis schema version")
analysis_schema = f"analysis-v{version}.schema.json"
require_valid(analysis_schema, analysis, "analysis")
if version == 3:
require_invalid("analysis-v2.schema.json", analysis, "legacy schema rejects v3")
require_valid("trace-v2.schema.json", trace, "trace") require_valid("trace-v2.schema.json", trace, "trace")
require_valid("tool-v1.schema.json", tool, "tool") require_valid("tool-v1.schema.json", tool, "tool")
# Negative mutations: structure, version and traversal must fail closed. # Negative mutations: structure, version and traversal must fail closed.
bad = copy.deepcopy(analysis) bad = copy.deepcopy(analysis)
bad["schema_version"] = 999 bad["schema_version"] = 999
require_invalid("analysis-v2.schema.json", bad, "analysis unsupported version") require_invalid(analysis_schema, bad, "analysis unsupported version")
bad = copy.deepcopy(analysis) bad = copy.deepcopy(analysis)
bad.pop("modules", None) bad.pop("modules", None)
require_invalid("analysis-v2.schema.json", bad, "analysis missing modules") require_invalid(analysis_schema, bad, "analysis missing modules")
bad = copy.deepcopy(analysis) bad = copy.deepcopy(analysis)
bad["modules"][0]["resources"] = 3 bad["modules"][0]["resources"] = 3
require_invalid("analysis-v2.schema.json", bad, "analysis resources integer") require_invalid(analysis_schema, bad, "analysis resources integer")
bad = copy.deepcopy(trace) bad = copy.deepcopy(trace)
bad["events"][0]["seq"] = "zero" bad["events"][0]["seq"] = "zero"
@@ -0,0 +1,5 @@
{
"codes": [
"sem.break_outside_loop"
]
}
@@ -0,0 +1,11 @@
## @exec main
`while true`
`子函数()`
`end`
## @exec 子函数
`break`
@@ -0,0 +1,5 @@
{
"codes": [
"sem.syntax"
]
}
@@ -0,0 +1,7 @@
## @exec main
`while true`
`break 2`
`end`
@@ -0,0 +1,5 @@
{
"codes": [
"sem.break_outside_loop"
]
}
@@ -0,0 +1,7 @@
## @exec main
`if true`
`break`
`end`
@@ -0,0 +1,5 @@
{
"codes": [
"symbol.uninitialized"
]
}
@@ -0,0 +1,19 @@
## @exec main
`params(标志: Bool)`
`while true`
`if 标志`
`break`
`end`
`结果 = 1`
`break`
`end`
`return 结果`
@@ -0,0 +1,5 @@
{
"codes": [
"symbol.uninitialized"
]
}
@@ -0,0 +1,21 @@
## @exec main
`params(位置: Int)`
`while true`
`if 位置 > 0`
`break`
`end`
`结果 = 1`
`位置 = 位置 + 1`
`continue`
`end`
`return 结果`
@@ -0,0 +1,5 @@
{
"codes": [
"sem.syntax"
]
}
@@ -0,0 +1,7 @@
## @exec main
`while true`
`continue outer`
`end`
@@ -0,0 +1,5 @@
{
"codes": [
"sem.continue_outside_loop"
]
}
@@ -0,0 +1,3 @@
## @exec main
`continue`
@@ -0,0 +1,5 @@
{
"codes": [
"sem.duplicate_else"
]
}
@@ -0,0 +1,9 @@
## @exec main
`if false`
`else`
`else`
`end`
@@ -0,0 +1,5 @@
{
"codes": [
"sem.else_if_after_else"
]
}
@@ -0,0 +1,9 @@
## @exec main
`if false`
`else`
`else if true`
`end`
@@ -0,0 +1,5 @@
{
"codes": [
"sem.unmatched_end"
]
}
@@ -0,0 +1,9 @@
## @exec main
`if false`
`else if true`
`end`
`end`
@@ -0,0 +1,5 @@
{
"codes": [
"sem.syntax"
]
}
Loaded 100 of 123 files, more files were not shown because too many files have changed in this diff. Show more