Compare commits
19
Commits
rfc-gpl-0004
...
master
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
652ea76360 | ||
|
|
9149ee40a4 | ||
|
|
51d4c6568d | ||
|
|
af1e07f3d7 | ||
|
|
58fccae303 | ||
|
|
e903575d91 | ||
|
|
b1314328e6 | ||
|
|
1dc088b602 | ||
|
|
71d29261a8 | ||
|
|
69c5dc8d20 | ||
|
|
095eef1370 | ||
|
|
c582451a5f | ||
|
|
f7a5a7b016 | ||
|
|
22b7757420 | ||
|
|
dd69919b48 | ||
|
|
1390f0081b | ||
|
|
e4c4a852d0 | ||
|
|
6e9b5af88d | ||
|
|
b702b31c76 |
No files matched your search
+41
-69
@@ -114,6 +114,19 @@ jobs:
|
||||
python3 tests/consumers/analysis_consumer.py /tmp/analysis-v2.json
|
||||
python3 tests/consumers/trace_consumer.py \
|
||||
/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:
|
||||
name: runtime contract (${{ matrix.os }})
|
||||
@@ -185,7 +198,7 @@ jobs:
|
||||
|
||||
frozen-extensions:
|
||||
name: frozen Linux archive and external extensions
|
||||
runs-on: ubuntu-latest
|
||||
runs-on: ubuntu-24.04
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
with:
|
||||
@@ -200,6 +213,7 @@ jobs:
|
||||
version="$(cargo metadata --no-deps --format-version 1 --offline \
|
||||
| python3 -c 'import json,sys; print(next(p["version"] for p in json.load(sys.stdin)["packages"] if p["name"]=="marqdo-cli"))')"
|
||||
python3 tools/release/package.py --source-sha "$GITHUB_SHA" --version "$version"
|
||||
python3 tools/release/smoke.py --archive dist/marqdo-*.tar.gz
|
||||
tools/ci/run_frozen_extensions.sh dist/marqdo-*.tar.gz "$GITHUB_SHA" dist/frozen-extension-evidence.json
|
||||
- uses: actions/upload-artifact@v4
|
||||
with:
|
||||
@@ -207,6 +221,13 @@ jobs:
|
||||
path: dist/frozen-extension-evidence.json
|
||||
if-no-files-found: error
|
||||
|
||||
- uses: actions/upload-artifact@v4
|
||||
if: startsWith(github.ref, 'refs/tags/v') || github.event_name == 'workflow_dispatch'
|
||||
with:
|
||||
name: frozen-linux-archive-${{ github.sha }}
|
||||
path: dist/marqdo-*.tar.gz*
|
||||
if-no-files-found: error
|
||||
|
||||
release-evidence:
|
||||
name: release evidence manifest
|
||||
needs: [test, schema, cross-platform, frozen-extensions]
|
||||
@@ -222,7 +243,6 @@ jobs:
|
||||
LINUX_RESULT: ${{ needs.test.result }}
|
||||
SCHEMA_RESULT: ${{ needs.schema.result }}
|
||||
EXTENSIONS_RESULT: ${{ needs.frozen-extensions.result }}
|
||||
PORTABLE_RESULT: ${{ needs.cross-platform.result }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
state() {
|
||||
@@ -233,11 +253,18 @@ jobs:
|
||||
esac
|
||||
}
|
||||
linux="$(state "$LINUX_RESULT")"
|
||||
portable="$(state "$PORTABLE_RESULT")"
|
||||
if [ "$(state "$SCHEMA_RESULT")" != "PASS" ] || [ "$(state "$EXTENSIONS_RESULT")" != "PASS" ]; then
|
||||
linux="FAIL"
|
||||
fi
|
||||
python3 tools/ci/release_evidence.py --target-sha "$TARGET_SHA" --out "docs/evidence/ci/$TARGET_SHA/manifest.json" --gate "linux=$linux:$TARGET_SHA:$RUN_URL" --gate "windows=$portable:$TARGET_SHA:$RUN_URL" --gate "macos=$portable:$TARGET_SHA:$RUN_URL" --gate "strict_vm=UNVERIFIED::${{ github.server_url }}/${{ github.repository }}/actions/workflows/security-linux.yml" --gate "performance=UNVERIFIED::"
|
||||
python3 tools/ci/release_evidence.py --profile rc --target-sha "$TARGET_SHA" \
|
||||
--out "docs/evidence/ci/$TARGET_SHA/manifest.json" \
|
||||
--gate "linux=$linux:$TARGET_SHA:$RUN_URL" \
|
||||
--gate "windows=UNSUPPORTED:$TARGET_SHA:linux-only-rc-scope" \
|
||||
--gate "macos=UNSUPPORTED:$TARGET_SHA:linux-only-rc-scope" \
|
||||
--gate "extension=$(state "$EXTENSIONS_RESULT"):$TARGET_SHA:$RUN_URL" \
|
||||
--gate "strict_vm=UNVERIFIED::$RUN_URL" \
|
||||
--gate "performance=UNVERIFIED::$RUN_URL"
|
||||
|
||||
- name: Validate external-extension evidence when committed
|
||||
shell: bash
|
||||
env:
|
||||
@@ -249,7 +276,7 @@ jobs:
|
||||
python3 tools/ci/verify_extension_contracts.py --validate "$manifest"
|
||||
else
|
||||
echo "UNVERIFIED: no external-extension manifest for $TARGET_SHA."
|
||||
echo "Release requires tools/ci/verify_extension_contracts.py on the tagged SHA (docs/releasing.md §7)."
|
||||
echo "Release requires tools/ci/verify_extension_contracts.py on the tagged SHA (docs/releasing.md §8)."
|
||||
fi
|
||||
- name: Upload release manifest
|
||||
uses: actions/upload-artifact@v4
|
||||
@@ -259,72 +286,17 @@ jobs:
|
||||
if-no-files-found: error
|
||||
|
||||
release-candidate:
|
||||
name: release candidate artifact (${{ matrix.os }})
|
||||
name: archive-only Linux candidate smoke
|
||||
needs: [test, schema, cross-platform, frozen-extensions]
|
||||
if: startsWith(github.ref, 'refs/tags/v') || github.event_name == 'workflow_dispatch'
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
include:
|
||||
- os: ubuntu-latest
|
||||
target: x86_64-unknown-linux-gnu
|
||||
- os: macos-latest
|
||||
target: aarch64-apple-darwin
|
||||
runs-on: ${{ matrix.os }}
|
||||
runs-on: ubuntu-24.04
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: dtolnay/rust-toolchain@stable
|
||||
- uses: Swatinem/rust-cache@v2
|
||||
- name: Build release binaries
|
||||
run: |
|
||||
cargo build --release --locked -p marqdo-cli -p marqdo-provider-worker
|
||||
test -x target/release/marqdo-provider-worker
|
||||
- name: Package and checksum
|
||||
shell: bash
|
||||
run: |
|
||||
set -euo pipefail
|
||||
version="$(cargo metadata --no-deps --format-version 1 | python3 -c 'import json,sys; print(json.load(sys.stdin)["packages"][0]["version"])')"
|
||||
stage="dist/marqdo-${version}-${{ matrix.target }}"
|
||||
mkdir -p "$stage"
|
||||
install -m 0755 target/release/marqdo "$stage/"
|
||||
# The provider worker is required for provider.json v2 and must be a
|
||||
# sibling of the marqdo executable (no PATH fallback).
|
||||
install -m 0755 target/release/marqdo-provider-worker "$stage/"
|
||||
cp LICENSE-MIT LICENSE-APACHE CHANGELOG.md COMPATIBILITY.md README.md "$stage/"
|
||||
cp -r spec examples "$stage/"
|
||||
mkdir -p "$stage/tests"
|
||||
cp -r tests/consumers "$stage/tests/"
|
||||
printf 'source_sha=%s\nversion=%s\ntarget=%s\n' "$GITHUB_SHA" "$version" "${{ matrix.target }}" > "$stage/SOURCE_SHA"
|
||||
rustc -vV > "$stage/rustc-vV.txt"
|
||||
tar -C dist -czf "dist/marqdo-${version}-${{ matrix.target }}.tar.gz" "$(basename "$stage")"
|
||||
cd dist
|
||||
if command -v sha256sum >/dev/null 2>&1; then
|
||||
sha256sum "marqdo-${version}-${{ matrix.target }}.tar.gz" > "marqdo-${version}-${{ matrix.target }}.tar.gz.sha256"
|
||||
else
|
||||
shasum -a 256 "marqdo-${version}-${{ matrix.target }}.tar.gz" > "marqdo-${version}-${{ matrix.target }}.tar.gz.sha256"
|
||||
fi
|
||||
cat "marqdo-${version}-${{ matrix.target }}.tar.gz.sha256"
|
||||
- name: Clean-install smoke
|
||||
shell: bash
|
||||
run: |
|
||||
set -euo pipefail
|
||||
tmp="$(mktemp -d)"
|
||||
cp dist/marqdo-*.tar.gz* "$tmp/"
|
||||
cd "$tmp"
|
||||
sha256sum -c marqdo-*.tar.gz.sha256 2>/dev/null || shasum -a 256 -c marqdo-*.tar.gz.sha256
|
||||
tar -xzf marqdo-*.tar.gz
|
||||
cd marqdo-*
|
||||
./marqdo --version
|
||||
./marqdo --help >/dev/null
|
||||
test -x ./marqdo-provider-worker
|
||||
./marqdo check examples/multi-module/index.mq.md --refs --emit analysis.json
|
||||
./marqdo run examples/hello.mq.md
|
||||
./marqdo run examples/multi-module/index.mq.md --trace-file trace.json
|
||||
python3 tests/consumers/analysis_consumer.py analysis.json
|
||||
python3 tests/consumers/trace_consumer.py analysis.json trace.json
|
||||
python3 tests/consumers/validate_protocols.py analysis.json trace.json examples/tool-unknown-name/tool.json
|
||||
- uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: marqdo-${{ matrix.target }}
|
||||
path: dist/marqdo-*.tar.gz*
|
||||
if-no-files-found: error
|
||||
persist-credentials: false
|
||||
- uses: actions/download-artifact@v4
|
||||
with:
|
||||
name: frozen-linux-archive-${{ github.sha }}
|
||||
path: dist
|
||||
- name: Cold install the checked archive
|
||||
run: bash tools/release/cold-install.sh dist/marqdo-*.tar.gz "$GITHUB_SHA"
|
||||
+17
-4
@@ -23,6 +23,12 @@ steps:
|
||||
# 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
|
||||
- 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 architecture_boundaries
|
||||
- python3 -m unittest discover -s tools/ci -p "test_*.py"
|
||||
@@ -32,12 +38,19 @@ steps:
|
||||
- rustup target add x86_64-pc-windows-gnu
|
||||
- cargo check --workspace --all-targets --target x86_64-pc-windows-gnu
|
||||
|
||||
build:
|
||||
image: rust:1.100-bookworm
|
||||
depends_on: [test]
|
||||
minimum-rust:
|
||||
image: rust:1.89-bookworm
|
||||
commands:
|
||||
- apt-get update
|
||||
- apt-get install -y --no-install-recommends ca-certificates git openssl python3 build-essential
|
||||
- apt-get install -y --no-install-recommends build-essential ca-certificates
|
||||
- cargo check --locked --workspace --all-targets
|
||||
|
||||
build:
|
||||
image: rust:1.100-bookworm
|
||||
depends_on: [test, minimum-rust]
|
||||
commands:
|
||||
- apt-get update
|
||||
- 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
|
||||
# only supported transport and resolution is a sibling-of-CLI lookup.
|
||||
- cargo build --release --locked -p marqdo-cli -p marqdo-provider-worker
|
||||
|
||||
+30
-14
@@ -1,32 +1,45 @@
|
||||
# G4 fixed performance node.
|
||||
#
|
||||
# Manual only: this workflow never runs on push or pull_request and therefore
|
||||
# never executes untrusted PR code on the designated performance agent. The
|
||||
# repository currently has one Woodpecker agent (agent_id 1), so it is the
|
||||
# fixed node; the CPU affinity and hardware/toolchain manifest are recorded in
|
||||
# every report. Do not compare its timings with another machine or with
|
||||
# QEMU/TCG.
|
||||
# Manual performance comparison on the shared Woodpecker runner.
|
||||
# Shared-node measurements may support an explicitly approved RC WARN.
|
||||
when:
|
||||
event: [manual]
|
||||
branch: [master]
|
||||
branch: [master, "release/*"]
|
||||
|
||||
steps:
|
||||
measure:
|
||||
image: rust:1.100-bookworm
|
||||
commands:
|
||||
- apt-get update
|
||||
- apt-get install -y --no-install-recommends python3 util-linux ca-certificates
|
||||
- cargo build --release --locked -p marqdo-cli
|
||||
- apt-get install -y --no-install-recommends python3 util-linux ca-certificates git openssl build-essential
|
||||
- cargo build --release --locked -p marqdo-cli -p marqdo-provider-worker
|
||||
- |
|
||||
set -eu
|
||||
baseline_sha=2c7c4f31e7a388d3fcfa717a77067e696ed13854
|
||||
git fetch --no-tags origin refs/tags/v3.0.0-beta.1
|
||||
test "$(git rev-parse 'FETCH_HEAD^{commit}')" = "$baseline_sha"
|
||||
perf_dir="$(mktemp -d)"
|
||||
git worktree add --detach "$perf_dir/beta" "$baseline_sha"
|
||||
trap 'git worktree remove --force "$perf_dir/beta"; rm -rf "$perf_dir"' EXIT
|
||||
(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)"
|
||||
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_CPU $(awk -F: '/model name/ {print $2; exit}' /proc/cpuinfo | xargs)"
|
||||
echo "G4_GOVERNOR $(cat /sys/devices/system/cpu/cpu0/cpufreq/scaling_governor 2>/dev/null || echo unavailable)"
|
||||
python3 tools/perf/runner.py --no-build --warmups 5 --samples 20 \
|
||||
--approved-node --platform-id woodpecker-agent-1 \
|
||||
--cpu-list "$cpu_list" --out perf.json
|
||||
(cd "$perf_dir/beta" && python3 tools/perf/runner.py --no-build \
|
||||
--warmups 5 --samples 20 --platform-id woodpecker-agent-1 \
|
||||
--cpu-list "$cpu_list" --out "$perf_dir/beta.json" > /dev/null)
|
||||
python3 tools/perf/runner.py --no-build --binary "$candidate/marqdo" --warmups 5 --samples 20 \
|
||||
--platform-id woodpecker-agent-1 --cpu-list "$cpu_list" \
|
||||
--baseline "$perf_dir/beta.json" --out perf.json > /dev/null
|
||||
python3 - <<'PY'
|
||||
import json
|
||||
|
||||
@@ -47,6 +60,9 @@ steps:
|
||||
f"rss={workload.get('max_rss_kb_median')}"
|
||||
)
|
||||
PY
|
||||
echo "G4_BASELINE_REPORT_BEGIN"
|
||||
cat "$perf_dir/beta.json"
|
||||
echo "G4_BASELINE_REPORT_END"
|
||||
echo "G4_REPORT_BEGIN"
|
||||
cat perf.json
|
||||
echo "G4_REPORT_END"
|
||||
+20
-4
@@ -10,7 +10,23 @@ Foreign wire v1, Provider manifest v2, lock v4) and independent package
|
||||
versions (including the bundled stdlib `0.1.0`) are versioned separately and
|
||||
do not follow the product version. Dates use ISO 8601.
|
||||
|
||||
## Unreleased (post `3.0.0-beta.1`)
|
||||
## 3.0.0-rc.2 (candidate)
|
||||
|
||||
- The Rust workspace, CLI version output and protocol producers report
|
||||
`3.0.0-rc.2`. The locked workspace requires Rust 1.89.
|
||||
- The candidate targets Linux x86_64 with glibc. See
|
||||
[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)
|
||||
|
||||
@@ -63,7 +79,7 @@ detach), ADR-0062 (resource-operation ownership/core kinds), ADR-0063
|
||||
metadata-only `@namespace.identifier` annotation layer is specified as
|
||||
**Proposed** with target `3.1.x`. The current parser still rejects any other
|
||||
leading `@foo` with `sem.invalid_mode_marker`; no `annotation.unknown` code,
|
||||
manifest loader, Analysis v3 or sidecar exists in this build. Contracts:
|
||||
manifest loader or heading annotations projection exists in this build. Contracts:
|
||||
ADR-0060 and [`spec/heading-annotations-v1.md`](spec/heading-annotations-v1.md).
|
||||
- **Foreign F-B removal is deferred (H-02).** The permission-gated one-shot
|
||||
`foreign.run`/`foreign.call` + `KernelRegistry` stay as the controlled
|
||||
@@ -93,8 +109,8 @@ detach), ADR-0062 (resource-operation ownership/core kinds), ADR-0063
|
||||
- New public contract
|
||||
[`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),
|
||||
with fixtures and an independent Python consumer. Analysis v2 and Trace v2
|
||||
schemas/versions are unchanged.
|
||||
with fixtures and an independent Python consumer. Trace v2 retains its
|
||||
public event envelope.
|
||||
- Limitations: memory metadata events (OBS-06/P2), a bidirectional debug
|
||||
protocol and SSE/HTTP remain out of scope; strict mode refuses event mode
|
||||
explicitly.
|
||||
|
||||
+25
-4
@@ -8,6 +8,11 @@ this beta. Executed status and same-SHA evidence are in
|
||||
[`docs/STATUS.md`](docs/STATUS.md), and SHA-bound external evidence is under
|
||||
[`docs/evidence/extension/`](docs/evidence/extension/README.md).
|
||||
|
||||
The `3.0.0-rc.2` candidate targets Linux x86_64 on glibc 2.39 and
|
||||
includes the post-beta changes below. See the
|
||||
[RC acceptance procedure](docs/releasing.md). The platform evidence table
|
||||
records the beta and subsequent development verification.
|
||||
|
||||
## Language source syntax (breaking change)
|
||||
|
||||
**The `.mq.md` source language is a breaking change.** The current contract is
|
||||
@@ -46,7 +51,7 @@ Consequences for compatibility:
|
||||
|
||||
## Post-`3.0.0-beta.1` boundary changes (RFC-EXT-0003)
|
||||
|
||||
These land after the beta tag and **before any next beta/stable tag**; they are
|
||||
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
|
||||
evidence: [`docs/evidence/2026-11-22-rfc-ext-0003-core-hardcoding.md`](docs/evidence/2026-11-22-rfc-ext-0003-core-hardcoding.md).
|
||||
|
||||
@@ -57,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. |
|
||||
| Core resource kinds enforced on every registration path (H-04) | Provider name or declared kind equal to `stdio/file/tcp/tls/udp/tcp-listener` is rejected with `ext.manifest_invalid` (CLI) / `ResourceUnsupported` (host) before registration. No provider may shadow a core kind. |
|
||||
| `resource_request` operation ownership (H-03) | New domain/business operations are forbidden in the core: ship a pure `.mq.md` package, ABI export or Provider. The exact reviewed allowlist is pinned by `architecture_boundaries.rs`; see `docs/architecture/resource-operations.md`. |
|
||||
| Heading Annotations v1 (H-05/H-07) | **Proposed, not implemented.** This build still rejects unknown `@foo` with `sem.invalid_mode_marker`; no annotation manifest, `annotation.unknown`, Analysis v3 or sidecar exists yet. Target `3.1.x`; ADR-0060 and `spec/heading-annotations-v1.md`. |
|
||||
| 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. |
|
||||
|
||||
## 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
|
||||
|
||||
| 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. |
|
||||
| Language / CLI | `3.0.0-beta.1` (prerelease) | 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). |
|
||||
| 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. |
|
||||
| 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. |
|
||||
|
||||
Generated
+15
-15
@@ -412,7 +412,7 @@ checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53"
|
||||
|
||||
[[package]]
|
||||
name = "marqdo-cli"
|
||||
version = "3.0.0-beta.1"
|
||||
version = "3.0.0-rc.2"
|
||||
dependencies = [
|
||||
"clap",
|
||||
"hex",
|
||||
@@ -438,7 +438,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "marqdo-expression"
|
||||
version = "3.0.0-beta.1"
|
||||
version = "3.0.0-rc.2"
|
||||
dependencies = [
|
||||
"marqdo-span",
|
||||
"num-bigint",
|
||||
@@ -449,7 +449,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "marqdo-foreign"
|
||||
version = "3.0.0-beta.1"
|
||||
version = "3.0.0-rc.2"
|
||||
dependencies = [
|
||||
"hex",
|
||||
"libc",
|
||||
@@ -465,7 +465,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "marqdo-frontend"
|
||||
version = "3.0.0-beta.1"
|
||||
version = "3.0.0-rc.2"
|
||||
dependencies = [
|
||||
"marqdo-expression",
|
||||
"marqdo-ir",
|
||||
@@ -480,7 +480,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "marqdo-host"
|
||||
version = "3.0.0-beta.1"
|
||||
version = "3.0.0-rc.2"
|
||||
dependencies = [
|
||||
"flate2",
|
||||
"getrandom 0.4.3",
|
||||
@@ -504,7 +504,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "marqdo-ir"
|
||||
version = "3.0.0-beta.1"
|
||||
version = "3.0.0-rc.2"
|
||||
dependencies = [
|
||||
"marqdo-expression",
|
||||
"marqdo-span",
|
||||
@@ -514,7 +514,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "marqdo-markdown"
|
||||
version = "3.0.0-beta.1"
|
||||
version = "3.0.0-rc.2"
|
||||
dependencies = [
|
||||
"comrak",
|
||||
"marqdo-span",
|
||||
@@ -525,7 +525,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "marqdo-package"
|
||||
version = "3.0.0-beta.1"
|
||||
version = "3.0.0-rc.2"
|
||||
dependencies = [
|
||||
"hex",
|
||||
"semver",
|
||||
@@ -539,7 +539,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "marqdo-plugin-abi"
|
||||
version = "3.0.0-beta.1"
|
||||
version = "3.0.0-rc.2"
|
||||
dependencies = [
|
||||
"hex",
|
||||
"libloading",
|
||||
@@ -554,7 +554,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "marqdo-plugin-sdk"
|
||||
version = "3.0.0-beta.1"
|
||||
version = "3.0.0-rc.2"
|
||||
dependencies = [
|
||||
"marqdo-plugin-abi",
|
||||
"serde",
|
||||
@@ -563,7 +563,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "marqdo-provider-worker"
|
||||
version = "3.0.0-beta.1"
|
||||
version = "3.0.0-rc.2"
|
||||
dependencies = [
|
||||
"libloading",
|
||||
"marqdo-host",
|
||||
@@ -575,7 +575,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "marqdo-runtime"
|
||||
version = "3.0.0-beta.1"
|
||||
version = "3.0.0-rc.2"
|
||||
dependencies = [
|
||||
"marqdo-expression",
|
||||
"marqdo-frontend",
|
||||
@@ -594,7 +594,7 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "marqdo-sandbox"
|
||||
version = "3.0.0-beta.1"
|
||||
version = "3.0.0-rc.2"
|
||||
dependencies = [
|
||||
"libc",
|
||||
"serde",
|
||||
@@ -602,14 +602,14 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "marqdo-span"
|
||||
version = "3.0.0-beta.1"
|
||||
version = "3.0.0-rc.2"
|
||||
dependencies = [
|
||||
"serde",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "marqdo-value"
|
||||
version = "3.0.0-beta.1"
|
||||
version = "3.0.0-rc.2"
|
||||
dependencies = [
|
||||
"marqdo-span",
|
||||
"num-bigint",
|
||||
|
||||
+3
-3
@@ -19,10 +19,10 @@ members = [
|
||||
]
|
||||
|
||||
[workspace.package]
|
||||
version = "3.0.0-beta.1"
|
||||
version = "3.0.0-rc.2"
|
||||
edition = "2021"
|
||||
rust-version = "1.82"
|
||||
license = "MIT OR Apache-2.0"
|
||||
rust-version = "1.89"
|
||||
license = "Apache-2.0"
|
||||
repository = "https://github.com/cflmy/marqdo-cli"
|
||||
authors = ["Marqdo contributors"]
|
||||
|
||||
|
||||
-21
@@ -1,21 +0,0 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2026 Marqdo contributors
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
@@ -10,7 +10,7 @@ The official implementation is a Rust workspace; Python/Node are optional
|
||||
foreign kernels, never the compiler target.
|
||||
|
||||
This repository is the new, independent Marqdo toolchain, now at product
|
||||
version **`3.0.0-beta.1`**. 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
|
||||
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
|
||||
@@ -27,7 +27,7 @@ release policy.
|
||||
> [`docs/STATUS.md`](docs/STATUS.md) and
|
||||
> [`docs/migration/README.md`](docs/migration/README.md).
|
||||
|
||||
> **Status: `3.0.0-beta.1` prerelease** —
|
||||
> **Published baseline: `3.0.0-beta.1` prerelease** —
|
||||
> [release](https://git.cflmy.cn/cflmy/marqdo-cli/releases/tag/v3.0.0-beta.1),
|
||||
> source `2c7c4f31e7a388d3fcfa717a77067e696ed13854`. The public beta target is **Linux x86_64 (glibc)**; macOS and Windows are experimental and not claimed, and the
|
||||
> C ABI plugin/provider paths are Linux-only in this beta. The language
|
||||
@@ -53,7 +53,7 @@ mirror is not used as the authoritative lane for this beta.
|
||||
|
||||
## Build
|
||||
|
||||
Requires Rust 1.82+.
|
||||
Requires Rust 1.89 or newer for the locked workspace.
|
||||
|
||||
```bash
|
||||
cargo build -p marqdo-cli
|
||||
@@ -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**`,
|
||||
`*x = 1*` and `` `x = 1` `` are the same assignment. Prefer inline code spans
|
||||
for expressions containing `*` or `**`.
|
||||
* **Statements are explicit.** `if <Bool>`, `else`, `while <Bool>`, `end`,
|
||||
`return <expr>`, `params(n: Int)`, assignment, or an expression call. Each
|
||||
carrier holds exactly one statement; every `if`/`while` is closed by `end`
|
||||
inside the same heading body.
|
||||
* **Statements are explicit.** An `if` may have multiple `else if` arms and
|
||||
a final `else`. `while` repeats while its condition is true. `break` exits the
|
||||
nearest loop and `continue` rechecks its condition. Each carrier holds one
|
||||
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
|
||||
document. `> print(1)` is prose; `> **print(1)**` contains a call.
|
||||
* **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
|
||||
transports, brokered `fs.read`, and explicitly trusted in-process calls
|
||||
(`--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,
|
||||
SemVer negotiation and whole-bundle digest verification; **Execution Events
|
||||
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
|
||||
marqdo run examples/hello.mq.md
|
||||
marqdo call examples/control-flow.mq.md main
|
||||
marqdo call examples/factorial.mq.md 数学.阶乘 --arg n=5
|
||||
marqdo run examples/multi-module/index.mq.md
|
||||
marqdo run examples/python-foreign.mq.md --allow-foreign # needs python3 or node
|
||||
|
||||
@@ -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
|
||||
//! kinds are the public contract, while internal Rust types may change. The
|
||||
@@ -17,13 +17,24 @@ use crate::loader::LoadedProject;
|
||||
|
||||
/// Schema name and version.
|
||||
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.
|
||||
pub fn build(project: &LoadedProject) -> Value {
|
||||
let mut modules = Vec::new();
|
||||
let mut version = BASE_VERSION;
|
||||
for (module_id, file) in &project.files {
|
||||
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!({
|
||||
"id": module_id.to_string(),
|
||||
"package_instance_id": module_id.instance,
|
||||
@@ -49,7 +60,7 @@ pub fn build(project: &LoadedProject) -> Value {
|
||||
});
|
||||
json!({
|
||||
"schema": SCHEMA,
|
||||
"schema_version": SCHEMA_VERSION,
|
||||
"schema_version": version,
|
||||
"producer": {
|
||||
"name": "marqdo",
|
||||
"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`.
|
||||
fn encode(project: &LoadedProject) -> Result<Vec<u8>, String> {
|
||||
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<_>>(),
|
||||
"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!({
|
||||
"kind": "return",
|
||||
"value": expr_json(value),
|
||||
@@ -523,6 +545,7 @@ fn collect_calls(
|
||||
expr_calls(project, module, function, condition, calls);
|
||||
collect_calls(project, module, function, body, calls);
|
||||
}
|
||||
Stmt::Break { .. } | Stmt::Continue { .. } => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -351,6 +351,19 @@ fn observation_payload(event: ObservationEvent<'_>) -> (&'static str, 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 {
|
||||
operation,
|
||||
result_code,
|
||||
|
||||
@@ -648,6 +648,7 @@ fn collect_identifiers_stmts(stmts: &[Stmt], names: &mut std::collections::BTree
|
||||
collect_identifiers_expr(condition, names);
|
||||
collect_identifiers_stmts(body, names);
|
||||
}
|
||||
Stmt::Break { .. } | Stmt::Continue { .. } => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -314,7 +314,7 @@ struct CheckArgs {
|
||||
/// Declare a plugin manifest for static export-signature checking.
|
||||
#[arg(long = "plugin", value_name = "PATH")]
|
||||
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")]
|
||||
emit: Option<PathBuf>,
|
||||
/// Machine readable JSON output.
|
||||
|
||||
+21
-10
@@ -31,7 +31,10 @@ struct SupportedProtocols {
|
||||
|
||||
const SUPPORTED: SupportedProtocols = SupportedProtocols {
|
||||
tool: PROTOCOL_VERSION,
|
||||
analysis: &[2],
|
||||
analysis: &[
|
||||
crate::analysis::BASE_VERSION,
|
||||
crate::analysis::LOOP_CONTROL_VERSION,
|
||||
],
|
||||
trace: &[2],
|
||||
};
|
||||
|
||||
@@ -297,7 +300,7 @@ fn negotiate_protocol(
|
||||
let Some(requested) = requested else {
|
||||
return Ok(());
|
||||
};
|
||||
if requested.is_empty() || !requested.iter().any(|version| supported.contains(version)) {
|
||||
if shared_version(requested, supported).is_none() {
|
||||
return Err(format!(
|
||||
"tool.protocol_incompatible: tool requires {name} version(s) {requested:?}, this core supports {supported:?}"
|
||||
));
|
||||
@@ -305,6 +308,14 @@ fn negotiate_protocol(
|
||||
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 {
|
||||
let mut bytes = command.bytes();
|
||||
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_TOOL_PROTOCOL", "1");
|
||||
if record
|
||||
if let Some(version) = record
|
||||
.compatibility
|
||||
.analysis
|
||||
.as_ref()
|
||||
.is_some_and(|versions| versions.contains(&2))
|
||||
.as_deref()
|
||||
.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
|
||||
.trace
|
||||
.as_ref()
|
||||
.is_some_and(|versions| versions.contains(&2))
|
||||
.as_deref()
|
||||
.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() {
|
||||
Ok(status) => status.code().unwrap_or(1),
|
||||
|
||||
@@ -393,3 +393,146 @@ fn trace_records_calls_effects_and_status_without_secrets() {
|
||||
serde_json::from_slice(&std::fs::read(&error_trace).unwrap()).unwrap();
|
||||
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());
|
||||
}
|
||||
@@ -765,3 +765,109 @@ fn broken_pipe_makes_the_run_fail_instead_of_running_forever() {
|
||||
"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);
|
||||
}
|
||||
}
|
||||
@@ -436,30 +436,37 @@ fn tampered_path_dependency_content_is_rejected_by_locked_sync() {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn incompatible_project_marqdo_range_fails_closed_before_program_load() {
|
||||
fn project_marqdo_range_applies_to_the_running_core() {
|
||||
let dir = TempDir::new("runtime-range");
|
||||
let root = dir.path();
|
||||
write(
|
||||
&root.join("marqdo.yaml"),
|
||||
"project:\n name: stale\n version: 0.1.0\n marqdo: \">=0.1,<1\"\n",
|
||||
);
|
||||
let core = env!("CARGO_PKG_VERSION");
|
||||
write(&root.join("index.mq.md"), "## @exec main\n\n`return 1`\n");
|
||||
for command in [["check", "index.mq.md"], ["run", "index.mq.md"]] {
|
||||
let output = cli(root, &command);
|
||||
assert!(
|
||||
!output.status.success(),
|
||||
"{} must fail closed: {}",
|
||||
command[0],
|
||||
String::from_utf8_lossy(&output.stderr)
|
||||
);
|
||||
let stderr = String::from_utf8_lossy(&output.stderr);
|
||||
assert!(
|
||||
stderr.contains("package.marqdo_incompatible"),
|
||||
"unexpected stderr: {stderr}"
|
||||
);
|
||||
assert!(
|
||||
stderr.contains(env!("CARGO_PKG_VERSION")),
|
||||
"diagnostic must name the running core: {stderr}"
|
||||
|
||||
for (range, compatible) in [
|
||||
(">=3.0.0-beta.1,<4.0.0".to_string(), true),
|
||||
(format!("={core}"), true),
|
||||
(">=3.0.0,<4.0.0".to_string(), !core.contains('-')),
|
||||
(">=0.1,<1".to_string(), false),
|
||||
] {
|
||||
write(
|
||||
&root.join("marqdo.yaml"),
|
||||
&format!("project:\n name: runtime-range\n version: 0.1.0\n marqdo: \"{range}\"\n"),
|
||||
);
|
||||
for command in ["check", "run"] {
|
||||
let output = cli(root, &[command, "index.mq.md"]);
|
||||
let stderr = String::from_utf8_lossy(&output.stderr);
|
||||
assert_eq!(
|
||||
output.status.success(),
|
||||
compatible,
|
||||
"{command}: {range} on {core}: {stderr}"
|
||||
);
|
||||
if !compatible {
|
||||
assert!(stderr.contains("package.marqdo_incompatible"), "{stderr}");
|
||||
assert!(
|
||||
stderr.contains(core),
|
||||
"diagnostic must name the running core: {stderr}"
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -429,3 +429,35 @@ fn narration_removal_preserves_execution() {
|
||||
);
|
||||
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)
|
||||
);
|
||||
}
|
||||
@@ -376,6 +376,17 @@ fn protocol_negotiation_accepts_declared_versions_and_rejects_disjoint_ones() {
|
||||
assert!(text.contains("analysis=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 [
|
||||
("\"analysis\":[99]", "analysis-disjoint"),
|
||||
("\"analysis\":[]", "analysis-empty"),
|
||||
@@ -451,35 +462,39 @@ fn a_root_record_json_in_the_source_package_is_rejected() {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn beta_core_requires_an_explicit_prerelease_compatible_range() {
|
||||
fn prerelease_core_requires_an_explicit_prerelease_compatible_range() {
|
||||
let dir = TempDir::new("prerelease-range");
|
||||
let home = dir.path().join("home");
|
||||
let core = env!("CARGO_PKG_VERSION");
|
||||
|
||||
// The shipped example range opt-in must install on this real core.
|
||||
let manifest = write_tool(dir.path(), "prerelease", "#!/bin/sh\nexit 0\n");
|
||||
let install = cli(&home, &["tool", "install", manifest.to_str().unwrap()]);
|
||||
assert_eq!(install.status.code(), Some(0), "{}", stderr(&install));
|
||||
|
||||
if core.contains('-') {
|
||||
// SemVer: a stable-only requirement must not silently accept a
|
||||
// prerelease core. The operator has to opt in with a prerelease range.
|
||||
let manifest = write_tool(dir.path(), "stableonly", "#!/bin/sh\nexit 0\n");
|
||||
for (range, compatible) in [
|
||||
(">=3.0.0-beta.1,<4.0.0".to_string(), true),
|
||||
(format!("={core}"), true),
|
||||
(">=3.0.0,<4.0.0".to_string(), !core.contains('-')),
|
||||
(">=0.1,<1".to_string(), false),
|
||||
] {
|
||||
let manifest = write_tool(dir.path(), "prerelease", "#!/bin/sh\nexit 0\n");
|
||||
let text = std::fs::read_to_string(&manifest)
|
||||
.unwrap()
|
||||
.replace(">=3.0.0-beta.1,<4.0.0", ">=3.0.0,<4.0.0");
|
||||
.replace(">=3.0.0-beta.1,<4.0.0", &range);
|
||||
std::fs::write(&manifest, text).unwrap();
|
||||
let output = cli(&home, &["tool", "install", manifest.to_str().unwrap()]);
|
||||
assert_eq!(
|
||||
output.status.code(),
|
||||
Some(1),
|
||||
"a stable-only range must reject prerelease core {core}: {}",
|
||||
stderr(&output)
|
||||
);
|
||||
assert!(
|
||||
stderr(&output).contains("requires marqdo"),
|
||||
"{}",
|
||||
output.status.success(),
|
||||
compatible,
|
||||
"{range} on {core}: {}",
|
||||
stderr(&output)
|
||||
);
|
||||
if compatible {
|
||||
assert!(cli(&home, &["tool", "remove", "prerelease"])
|
||||
.status
|
||||
.success());
|
||||
} else {
|
||||
assert!(
|
||||
stderr(&output).contains("requires marqdo"),
|
||||
"{}",
|
||||
stderr(&output)
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -2,7 +2,7 @@
|
||||
//!
|
||||
//! One Markdown carrier holds exactly one payload. This module is the only
|
||||
//! 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
|
||||
//! words into blocks; this module owns their lexical recognition and the
|
||||
//! expression grammar they embed.
|
||||
@@ -22,10 +22,16 @@ use marqdo_span::Span;
|
||||
pub enum PayloadStatement {
|
||||
/// `if <expr>`
|
||||
If(Expr),
|
||||
/// `else if <expr>`
|
||||
ElseIf(Expr),
|
||||
/// `else` (no expression)
|
||||
Else,
|
||||
/// `while <expr>`
|
||||
While(Expr),
|
||||
/// Exit the closest enclosing loop.
|
||||
Break,
|
||||
/// Recheck the closest enclosing loop condition.
|
||||
Continue,
|
||||
/// `end` (no expression)
|
||||
End,
|
||||
/// `return <expr>`
|
||||
@@ -65,7 +71,12 @@ pub fn parse_payload_statement(source: &str) -> Result<PayloadStatement, ParseEr
|
||||
|
||||
let tokens = lexer::tokenize(trimmed)?;
|
||||
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 => {
|
||||
let expr = control_expression(trimmed, first.span, "if")?;
|
||||
Ok(PayloadStatement::If(expr))
|
||||
@@ -79,6 +90,11 @@ pub fn parse_payload_statement(source: &str) -> Result<PayloadStatement, ParseEr
|
||||
Ok(PayloadStatement::Return(expr))
|
||||
}
|
||||
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")?;
|
||||
Ok(PayloadStatement::Else)
|
||||
}
|
||||
@@ -128,6 +144,7 @@ mod tests {
|
||||
fn expr_of(source: &str) -> Expr {
|
||||
match parse_payload_statement(source).expect("valid payload") {
|
||||
PayloadStatement::If(expr)
|
||||
| PayloadStatement::ElseIf(expr)
|
||||
| PayloadStatement::While(expr)
|
||||
| PayloadStatement::Return(expr) => expr,
|
||||
other => panic!("unexpected payload: {other:?}"),
|
||||
@@ -136,7 +153,7 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
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 expr = expr_of(&source);
|
||||
assert_eq!(expr.span().start, keyword.len() + 1);
|
||||
@@ -159,7 +176,16 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
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!(
|
||||
parse_payload_statement(source).is_err(),
|
||||
"{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]
|
||||
fn control_expressions_must_consume_the_payload() {
|
||||
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());
|
||||
}
|
||||
|
||||
|
||||
@@ -213,7 +213,10 @@ fn collect_assigned(stmts: &[Stmt], out: &mut BTreeSet<String>) {
|
||||
}
|
||||
}
|
||||
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.stmts(body);
|
||||
}
|
||||
Stmt::Break { .. } | Stmt::Continue { .. } => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
+151
-102
@@ -3,16 +3,12 @@
|
||||
//! Parameters come only from free reads of executable expressions. Prose,
|
||||
//! headings, inert code spans and natural language never introduce parameters.
|
||||
//!
|
||||
//! The analysis tracks, for every program point:
|
||||
//! * `must` – variables definitely assigned on every path from entry;
|
||||
//! * `may` – variables assigned on at least one 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.
|
||||
//! Each reachable path tracks definite and possible assignments. Sequences
|
||||
//! merge fallthrough, break and continue separately, so a transfer never
|
||||
//! contributes bindings from the statements it skips. A return ends the path.
|
||||
//!
|
||||
//! Loop bodies get special treatment: their first iteration starts from the
|
||||
//! pre-loop state, so a read of an entry variable inside a loop is a parameter
|
||||
//! candidate even though the body also assigns it (the classic counter case).
|
||||
//! The first iteration starts from the pre-loop state. A first read before a
|
||||
//! body assignment can therefore still be a parameter (the counter case).
|
||||
|
||||
use std::collections::{BTreeMap, BTreeSet};
|
||||
|
||||
@@ -45,7 +41,6 @@ pub struct ParamCandidate {
|
||||
struct State {
|
||||
must: BTreeSet<String>,
|
||||
may: BTreeSet<String>,
|
||||
ambiguous: BTreeSet<String>,
|
||||
}
|
||||
|
||||
impl State {
|
||||
@@ -53,18 +48,46 @@ impl State {
|
||||
State {
|
||||
must: self.must.intersection(&other.must).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> {
|
||||
/// Names that are parameters/locals/builtins/imports and therefore never
|
||||
/// reported as unknown; used for explicit signatures.
|
||||
known: Option<&'a BTreeSet<String>>,
|
||||
reads: BTreeMap<String, Span>,
|
||||
diagnostics: Vec<Diagnostic>,
|
||||
ambiguous_reported: BTreeSet<String>,
|
||||
ambiguous_reads: BTreeMap<String, Span>,
|
||||
unknown_reported: BTreeSet<String>,
|
||||
}
|
||||
|
||||
@@ -74,7 +97,7 @@ impl<'a> Analyzer<'a> {
|
||||
known,
|
||||
reads: BTreeMap::new(),
|
||||
diagnostics: Vec::new(),
|
||||
ambiguous_reported: BTreeSet::new(),
|
||||
ambiguous_reads: BTreeMap::new(),
|
||||
unknown_reported: BTreeSet::new(),
|
||||
}
|
||||
}
|
||||
@@ -83,20 +106,8 @@ impl<'a> Analyzer<'a> {
|
||||
if state.must.contains(name) {
|
||||
return;
|
||||
}
|
||||
if state.ambiguous.contains(name) {
|
||||
if !self.ambiguous_reported.contains(name) {
|
||||
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",
|
||||
),
|
||||
);
|
||||
}
|
||||
if state.may.contains(name) {
|
||||
self.ambiguous_reads.entry(name.to_string()).or_insert(span);
|
||||
return;
|
||||
}
|
||||
if let Some(known) = self.known {
|
||||
@@ -169,107 +180,104 @@ impl<'a> Analyzer<'a> {
|
||||
}
|
||||
}
|
||||
|
||||
fn assign(&self, name: &str, state: &mut State) {
|
||||
state.must.insert(name.to_string());
|
||||
state.may.insert(name.to_string());
|
||||
state.ambiguous.insert(name.to_string());
|
||||
}
|
||||
|
||||
fn analyze_stmts(&mut self, stmts: &[Stmt], mut state: State) -> State {
|
||||
fn analyze_stmts(&mut self, stmts: &[Stmt], state: State) -> Flow {
|
||||
let mut flow = Flow {
|
||||
next: Some(state),
|
||||
..Flow::default()
|
||||
};
|
||||
for stmt in stmts {
|
||||
state = match stmt {
|
||||
let Some(mut state) = flow.next.take() else {
|
||||
break;
|
||||
};
|
||||
flow.next = match stmt {
|
||||
Stmt::Assign { target, value, .. } => {
|
||||
match target {
|
||||
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.assign(name, &mut state);
|
||||
state.must.insert(name.clone());
|
||||
state.may.insert(name.clone());
|
||||
}
|
||||
PlaceTarget::Index { base, index, .. } => {
|
||||
// Runtime order for an index place is base, index,
|
||||
// RHS; reads in the place are free reads like any
|
||||
// other.
|
||||
// Keep the runtime's evaluation order.
|
||||
self.read_expr(base, &state);
|
||||
self.read_expr(index, &state);
|
||||
self.read_expr(value, &state);
|
||||
}
|
||||
}
|
||||
state
|
||||
Some(state)
|
||||
}
|
||||
Stmt::Eval { expr, .. } => {
|
||||
self.read_expr(expr, &state);
|
||||
state
|
||||
Some(state)
|
||||
}
|
||||
Stmt::Return { value, .. } => {
|
||||
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 {
|
||||
condition, body, ..
|
||||
} => {
|
||||
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<_>>(),
|
||||
}
|
||||
}
|
||||
} => self.analyze_loop(condition, body, state),
|
||||
};
|
||||
}
|
||||
state
|
||||
flow
|
||||
}
|
||||
|
||||
fn analyze_branch(&mut self, arms: &[BranchArm], state: State) -> State {
|
||||
// Conditions are evaluated in order against the incoming state.
|
||||
fn analyze_branch(&mut self, arms: &[BranchArm], state: State) -> Flow {
|
||||
let mut flow = Flow::default();
|
||||
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);
|
||||
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
|
||||
// state; variables assigned only inside an arm stay "may assigned".
|
||||
let mut joined: Option<State> = Some(State {
|
||||
must: state.must.clone(),
|
||||
may: state.may.clone(),
|
||||
ambiguous: state.ambiguous.clone(),
|
||||
});
|
||||
for arm in arms {
|
||||
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),
|
||||
});
|
||||
merge_paths(&mut flow.next, Some(state));
|
||||
flow
|
||||
}
|
||||
|
||||
fn analyze_loop(&mut self, condition: &Expr, body: &[Stmt], state: State) -> Option<State> {
|
||||
self.read_expr(condition, &state);
|
||||
if *condition == Expr::Bool(false) {
|
||||
return Some(state);
|
||||
}
|
||||
match joined {
|
||||
Some(joined) => joined,
|
||||
None => state,
|
||||
|
||||
let Flow {
|
||||
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
|
||||
});
|
||||
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
|
||||
.reads
|
||||
.iter()
|
||||
@@ -391,7 +426,14 @@ mod tests {
|
||||
},
|
||||
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]
|
||||
@@ -399,7 +441,7 @@ mod tests {
|
||||
let stmts = vec![
|
||||
Stmt::Branch {
|
||||
arms: vec![BranchArm {
|
||||
condition: parse_expression("true").unwrap(),
|
||||
condition: parse_expression("flag").unwrap(),
|
||||
condition_span: Span::new(0, 0),
|
||||
body: vec![assign("x", "1")],
|
||||
span: Span::new(0, 0),
|
||||
@@ -409,7 +451,14 @@ mod tests {
|
||||
ret("x"),
|
||||
];
|
||||
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
|
||||
.diagnostics
|
||||
.iter()
|
||||
|
||||
@@ -8,7 +8,7 @@
|
||||
use marqdo_expression::{
|
||||
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_span::Span;
|
||||
use marqdo_value::{codes, Diagnostic};
|
||||
@@ -100,10 +100,10 @@ struct Mapper {
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
enum Stop {
|
||||
End,
|
||||
Else,
|
||||
Eof,
|
||||
enum ArmContext {
|
||||
Outside,
|
||||
Conditional,
|
||||
Default,
|
||||
}
|
||||
|
||||
struct RawPayload {
|
||||
@@ -139,14 +139,12 @@ impl Mapper {
|
||||
self.extract(block, &mut raw, true);
|
||||
}
|
||||
let mut position = 0;
|
||||
let (stmts, stop) = self.sequence(&raw, &mut position, false, false);
|
||||
if stop != Stop::Eof {
|
||||
// `sequence` leaves `position` on the stray `end` payload, so the
|
||||
// diagnostic points at the keyword instead of the previous
|
||||
// statement. A control frame may never close across a heading.
|
||||
let stmts = self.sequence(&raw, &mut position, ArmContext::Outside, false);
|
||||
if let Some(node) = raw.get(position) {
|
||||
// The only delimiter that can stop the segment is a stray `end`.
|
||||
self.error(
|
||||
codes::SEM_UNMATCHED_END,
|
||||
raw.get(position).map(|node| node.span),
|
||||
Some(node.span),
|
||||
"`end` has no open `if`/`while` in this heading segment",
|
||||
);
|
||||
}
|
||||
@@ -215,7 +213,11 @@ impl Mapper {
|
||||
return;
|
||||
}
|
||||
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);
|
||||
}
|
||||
out.push(RawPayload {
|
||||
@@ -243,102 +245,78 @@ impl Mapper {
|
||||
}
|
||||
}
|
||||
|
||||
/// Read a body up to its next delimiter without consuming that delimiter.
|
||||
fn sequence(
|
||||
&mut self,
|
||||
nodes: &[RawPayload],
|
||||
position: &mut usize,
|
||||
stop_on_else: bool,
|
||||
in_else_body: bool,
|
||||
) -> (Vec<Stmt>, Stop) {
|
||||
arm: ArmContext,
|
||||
in_loop: bool,
|
||||
) -> Vec<Stmt> {
|
||||
let mut out = Vec::new();
|
||||
while *position < nodes.len() {
|
||||
let raw = &nodes[*position];
|
||||
while let Some(raw) = nodes.get(*position) {
|
||||
match &raw.payload {
|
||||
Payload::Else => {
|
||||
if stop_on_else {
|
||||
return (out, Stop::Else);
|
||||
Payload::Else | Payload::ElseIf(_) => {
|
||||
if arm == ArmContext::Conditional {
|
||||
break;
|
||||
}
|
||||
self.error(
|
||||
if in_else_body {
|
||||
codes::SEM_DUPLICATE_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
|
||||
let (code, message) = match (&raw.payload, arm) {
|
||||
(Payload::Else, ArmContext::Default) => {
|
||||
(codes::SEM_DUPLICATE_ELSE, "`if` has more than one `else`")
|
||||
}
|
||||
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(
|
||||
codes::SEM_UNCLOSED_CONTROL,
|
||||
Some(span),
|
||||
"`if` is not closed by `end`",
|
||||
);
|
||||
} else {
|
||||
*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 });
|
||||
self.error(code, Some(raw.span), message);
|
||||
*position += 1;
|
||||
}
|
||||
Payload::End => break,
|
||||
Payload::If(_) => {
|
||||
self.executed = true;
|
||||
out.push(self.branch(nodes, position, in_loop));
|
||||
}
|
||||
Payload::While(condition) => {
|
||||
self.executed = true;
|
||||
let condition = condition.clone();
|
||||
let span = raw.span;
|
||||
*position += 1;
|
||||
let (body, stop) = self.sequence(nodes, position, false, false);
|
||||
if stop != Stop::End {
|
||||
self.error(
|
||||
codes::SEM_UNCLOSED_CONTROL,
|
||||
Some(span),
|
||||
"`while` is not closed by `end`",
|
||||
);
|
||||
} else {
|
||||
*position += 1;
|
||||
}
|
||||
let body = self.sequence(nodes, position, ArmContext::Outside, true);
|
||||
self.close_block(nodes, position, raw.span, "while");
|
||||
out.push(Stmt::Loop {
|
||||
condition,
|
||||
condition_span: span,
|
||||
condition: condition.clone(),
|
||||
condition_span: raw.span,
|
||||
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) => {
|
||||
self.executed = true;
|
||||
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`"),
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -620,7 +620,7 @@ fn validate_handler_name(name: &str) -> Result<(), PluginError> {
|
||||
pub struct Capabilities {
|
||||
/// Write to program standard output (`打印`).
|
||||
pub console: bool,
|
||||
/// Use the native math kernel.
|
||||
/// Grant ceiling for the `math.compute` plugin capability.
|
||||
pub math: bool,
|
||||
/// Readable project-relative path patterns.
|
||||
pub fs_read: Vec<String>,
|
||||
|
||||
@@ -1047,6 +1047,25 @@ impl Host for StdHost {
|
||||
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 {
|
||||
frame_id,
|
||||
name,
|
||||
|
||||
@@ -30,7 +30,7 @@ pub use handles::{contains_plugin_handle, PluginHandleTable};
|
||||
pub use host::{arity, expect_text, Host, HostOp, StdHost};
|
||||
pub use marqdo_sandbox::{PlatformCapabilities, SandboxMode, StrictIsolation};
|
||||
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,
|
||||
ValueState, DEFAULT_MAX_OBSERVATION_BYTES, DEFAULT_MAX_OBSERVATION_EVENTS,
|
||||
DEFAULT_MAX_VALUE_BYTES, MAX_STREAM_CHUNK_BYTES,
|
||||
|
||||
@@ -193,6 +193,13 @@ pub enum ObservationEvent<'a> {
|
||||
module_id: &'a str,
|
||||
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.
|
||||
Effect {
|
||||
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`].
|
||||
///
|
||||
/// Every variant carries an `Option<FrameId>`; observation of values and
|
||||
@@ -257,6 +283,13 @@ pub enum RuntimeObservation<'a> {
|
||||
module_id: &'a str,
|
||||
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.
|
||||
VariableAssigned {
|
||||
frame_id: Option<FrameId>,
|
||||
@@ -498,6 +531,7 @@ pub fn estimate_event_bytes(event: &ObservationEvent<'_>) -> u64 {
|
||||
}
|
||||
ObservationEvent::BranchEval { module_id, .. }
|
||||
| ObservationEvent::LoopIteration { module_id, .. }
|
||||
| ObservationEvent::LoopTransfer { module_id, .. }
|
||||
| ObservationEvent::Effect { module_id, .. } => {
|
||||
add_text(module_id);
|
||||
if let ObservationEvent::LoopIteration { decision, .. } = event {
|
||||
|
||||
@@ -58,6 +58,10 @@ enum Recorded {
|
||||
state: ValueState,
|
||||
value: Option<serde_json::Value>,
|
||||
},
|
||||
LoopTransfer {
|
||||
frame: FrameId,
|
||||
kind: &'static str,
|
||||
},
|
||||
Effect {
|
||||
operation: String,
|
||||
result_code: String,
|
||||
@@ -110,6 +114,12 @@ impl From<ObservationEvent<'_>> for Recorded {
|
||||
frame: frame_id,
|
||||
decision: decision.to_string(),
|
||||
},
|
||||
ObservationEvent::LoopTransfer {
|
||||
frame_id, transfer, ..
|
||||
} => Recorded::LoopTransfer {
|
||||
frame: frame_id,
|
||||
kind: transfer.event_kind(),
|
||||
},
|
||||
ObservationEvent::Effect {
|
||||
operation,
|
||||
result_code,
|
||||
|
||||
@@ -285,11 +285,11 @@ pub enum Stmt {
|
||||
/// Span of the whole statement.
|
||||
span: Span,
|
||||
},
|
||||
/// `if`/`else` group: the first true arm wins.
|
||||
/// `if`/`else if`/`else` group: the first true arm wins.
|
||||
Branch {
|
||||
/// Arms in AST order.
|
||||
arms: Vec<BranchArm>,
|
||||
/// Span of the list node.
|
||||
/// Span of the opening `if` carrier.
|
||||
span: Span,
|
||||
},
|
||||
/// `while`/`end` group.
|
||||
@@ -303,6 +303,16 @@ pub enum Stmt {
|
||||
/// Span of the whole `while` statement.
|
||||
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 {
|
||||
/// Returned expression.
|
||||
@@ -320,12 +330,14 @@ impl Stmt {
|
||||
| Stmt::Eval { span, .. }
|
||||
| Stmt::Branch { span, .. }
|
||||
| Stmt::Loop { span, .. }
|
||||
| Stmt::Break { span }
|
||||
| Stmt::Continue { 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)]
|
||||
pub struct BranchArm {
|
||||
/// Boolean condition expression.
|
||||
@@ -334,7 +346,7 @@ pub struct BranchArm {
|
||||
pub condition_span: Span,
|
||||
/// Statements executed when the condition is true.
|
||||
pub body: Vec<Stmt>,
|
||||
/// Span of the whole list item.
|
||||
/// Span of the branch carrier.
|
||||
pub span: Span,
|
||||
}
|
||||
|
||||
|
||||
@@ -4,7 +4,8 @@ use std::collections::BTreeMap;
|
||||
|
||||
use marqdo_expression::{BinaryOp, Expr, RecordEntry};
|
||||
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_span::Span;
|
||||
@@ -71,6 +72,8 @@ struct BoundArgs {
|
||||
enum Flow {
|
||||
Next,
|
||||
Return(Value),
|
||||
Break(Span),
|
||||
Continue(Span),
|
||||
}
|
||||
|
||||
/// Marqdo tree-walk interpreter.
|
||||
@@ -225,11 +228,21 @@ impl<'a> Interpreter<'a> {
|
||||
id: frame_id,
|
||||
};
|
||||
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;
|
||||
let status = match &result {
|
||||
Ok(Flow::Next) => "ok",
|
||||
Ok(Flow::Return(_)) => "return",
|
||||
Ok(None) => "ok",
|
||||
Ok(Some(_)) => "return",
|
||||
Err(error) => error.code(),
|
||||
};
|
||||
self.host.record_semantic(
|
||||
@@ -246,8 +259,7 @@ impl<'a> Interpreter<'a> {
|
||||
close?;
|
||||
}
|
||||
match result {
|
||||
Ok(Flow::Next) => Ok(Value::Unit),
|
||||
Ok(Flow::Return(value)) => Ok(value),
|
||||
Ok(value) => Ok(value.unwrap_or(Value::Unit)),
|
||||
Err(mut error) => {
|
||||
error.attribute_module(function.id.module.canonical());
|
||||
error.push_frame(
|
||||
@@ -409,6 +421,31 @@ impl<'a> Interpreter<'a> {
|
||||
Stmt::Eval { expr, .. } => {
|
||||
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 } => {
|
||||
let value = self.eval_expr(value, frame)?;
|
||||
let module = frame.function.module.canonical();
|
||||
@@ -461,7 +498,7 @@ impl<'a> Interpreter<'a> {
|
||||
if condition {
|
||||
match self.exec_stmts(program, &arm.body, frame)? {
|
||||
Flow::Next => break,
|
||||
Flow::Return(value) => return Ok(Flow::Return(value)),
|
||||
flow => return Ok(flow),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -502,8 +539,9 @@ impl<'a> Interpreter<'a> {
|
||||
break;
|
||||
}
|
||||
match self.exec_stmts(program, body, frame)? {
|
||||
Flow::Next => {}
|
||||
Flow::Return(value) => return Ok(Flow::Return(value)),
|
||||
Flow::Next | Flow::Continue(_) => {}
|
||||
Flow::Break(_) => break,
|
||||
flow @ Flow::Return(_) => return Ok(flow),
|
||||
}
|
||||
},
|
||||
}
|
||||
|
||||
@@ -249,3 +249,46 @@ fn memory_budget_is_enforced_without_changing_the_region() {
|
||||
.unwrap_err();
|
||||
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,
|
||||
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 {
|
||||
frame_id,
|
||||
name,
|
||||
|
||||
@@ -31,6 +31,14 @@ pub mod codes {
|
||||
pub const SEM_SYNTAX: &str = "sem.syntax";
|
||||
/// `else` does not bind an open `if`.
|
||||
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`.
|
||||
pub const SEM_DUPLICATE_ELSE: &str = "sem.duplicate_else";
|
||||
/// `end` closes no open frame.
|
||||
|
||||
@@ -24,6 +24,14 @@ command, log or source path is a defect, not a state. Historical snapshots
|
||||
[`history/`](history/README.md) and [`evidence/`](evidence/) and must not be read
|
||||
as current status.
|
||||
|
||||
## RC candidate
|
||||
|
||||
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
|
||||
[release procedure](releasing.md) requires a green manifest bound to the
|
||||
candidate SHA before publication. The release record below refers to the
|
||||
published beta.
|
||||
|
||||
## 0. Beta release record — `3.0.0-beta.1`
|
||||
|
||||
### 0.1 Product, version axes and scope
|
||||
@@ -256,6 +264,22 @@ digests. The external lane ran from a temporary fixture checkout with Cargo
|
||||
absent from PATH. Archive SHA-256 is
|
||||
`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
|
||||
|
||||
> **Historical record.** Everything in §1 onward was executed before the
|
||||
|
||||
@@ -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
@@ -64,4 +64,5 @@ Files: `0001`–`0050`, plus:
|
||||
* [0065](0065-resource-control-vnext.md) — proposed manifest-driven stateful
|
||||
operations and child resources;
|
||||
* [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.
|
||||
@@ -55,6 +55,13 @@ replace `spec/` or a recorded test log.
|
||||
> [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).
|
||||
|
||||
> **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
|
||||
|
||||
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` |
|
||||
| `else if` | `else if <Bool expression>` | 添加同一分支组的条件臂 | 否,复用 `Branch` |
|
||||
| `else` | `else` | 切换至当前 if 的否则分支 | 否 |
|
||||
| `while` | `while <Bool expression>` | 开始循环 | 否,映射已有 `Loop` |
|
||||
| `break` | `break` | 退出最近一层循环 | 否,结构化控制转移 |
|
||||
| `continue` | `continue` | 重新检查最近一层循环的条件 | 否,结构化控制转移 |
|
||||
| `end` | `end` | 结束最近未关闭的 if/while | 否,仅用于编译期配对 |
|
||||
| `return` | `return <expression>` | 返回当前 H2 函数,终止后续执行 | 否,映射已有 `Return` |
|
||||
| `params` | `params(name: Type, ...)` | H2 Exec 函数的可选参数声明 | 否,编译期元数据 |
|
||||
@@ -604,7 +607,7 @@ import:
|
||||
`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` 专用写法(本期)**:若需要多路判断,可在 `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 的循环
|
||||
|
||||
@@ -720,9 +725,10 @@ import:
|
||||
|
||||
严格规则:
|
||||
|
||||
- 每一个 `if` 恰有一个匹配的 `end`;`else` 可选且最多一个。
|
||||
- 每一个 `if` 恰有一个匹配的 `end`。可有多个 `else if` 和一个末尾 `else`。
|
||||
- 每一个 `while` 恰有一个匹配的 `end`。
|
||||
- `else` 不能独立出现;不能对应 `while`;一个 `if` 不能有两个 `else`。
|
||||
- `else if` 和 `else` 只能配对栈顶的 `if`。
|
||||
- 独占载荷的 `break` 结束同一标题执行段中的最近循环,`continue` 跳至该循环的下一次条件检查。
|
||||
- `end` 不能独立出现;语义片段末尾若仍有未闭合控制块则报错。
|
||||
- 不允许控制块跨越**标题边界**(见第 6 章),也不能跨 H2 函数、不同 `@exec` 章节或知识区域。
|
||||
- `if x > 0:` 带尾冒号首版不合法;规范语句不使用冒号,因为 Markdown 控制不由缩进决定。
|
||||
@@ -755,7 +761,7 @@ V2 推荐显式声明:
|
||||
| `return`(无表达式) | 语法错误 | `return None`(如果确实要返回 None) |
|
||||
| `end if` | 语法错误 | `end` |
|
||||
| `for x in xs` | 未纳入首版语法 | 标准库算法或 `while` |
|
||||
| `break`、`continue`、`try` | 未纳入首版语法 | 首版不承诺 |
|
||||
| `try` | 不属于当前语法 | — |
|
||||
| `a.b = 1` | 保留现有赋值能力限制 | 使用相应数据操作 API |
|
||||
| `x = 1; return x` 单个载荷 | 语法错误 | 两个独立闭合载荷 |
|
||||
| 直接写 `> print(x)` | 文档引用,不执行 | `> **print(x)**` |
|
||||
@@ -784,7 +790,10 @@ V2 推荐显式声明:
|
||||
```ebnf
|
||||
(* 每一个独立 Markdown 载荷对应且只对应一条 statement。 *)
|
||||
carrier_statement = "if", required_space, expr, EOF
|
||||
| "else", whitespace, "if", whitespace, Expr, EOF
|
||||
| "else", EOF
|
||||
| "break", EOF
|
||||
| "continue", EOF
|
||||
| "while", required_space, expr, EOF
|
||||
| "end", 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 均应对关键字使用同一套保留字定义。
|
||||
|
||||
- `if`、`while` 后必须为可完整消费的表达式;表达式运行结果必须 Bool。现有条件纯度限制仍适用。
|
||||
- `else`、`end` 后不允许额外词元,`end if`、`else x` 均硬错误。
|
||||
- `else if` 后必须有条件;独立的 `else` 和 `end` 后无额外词元。
|
||||
- `return` 后必须是表达式;其作用范围是当前 H2 函数,不是当前段落/列表项。
|
||||
- `params` 仅允许声明位置;作为普通表达式调用不得偷偷生效。
|
||||
- 首版**没有**冒号、缩进结束、自动括号、换行分号语法糖。
|
||||
@@ -817,14 +826,23 @@ TokenStream = [StatementToken(payload, span, carrier_kind, owner_unit), ...]
|
||||
|
||||
```text
|
||||
open_if(condition):
|
||||
push IfFrame(cond, then=[], else=None)
|
||||
push IfFrame(arms=[(condition, [])], has_else=false)
|
||||
|
||||
on_statement(stmt):
|
||||
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:
|
||||
require stack.top == IfFrame and frame.else is None
|
||||
switch frame active branch from then to else
|
||||
require stack.top == IfFrame and not frame.has_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):
|
||||
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,没有匹配结构时报错。
|
||||
- `return` 属于正在打开的 body,但运行时终止整个 H2 函数;降为现有 `Stmt::Return` IR。
|
||||
- `else` 不会成为单独一条 Runtime 指令;它只是 IR `Branch` 的分支边界。
|
||||
- `else if` 和 `else` 是 `Branch` 的臂边界。解释器将 `break` 和 `continue` 传递到最近的循环。
|
||||
- 相同载荷序列应产生相同的**归一化可执行 IR**,不因列表编号、引用层数、加粗/斜体/行内代码形态改变运算类别。
|
||||
|
||||
**一个实现注意点**:现有 `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` |
|
||||
| `**if x >**` | 语法错误,不降级文档 | `sem.syntax` |
|
||||
| `**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` |
|
||||
| `**end**`(无 if/while) | 不能独立结束 | `sem.unmatched_end` |
|
||||
| `**if true**` 到片段结束无 end | 未闭合控制 | `sem.unclosed_control` |
|
||||
|
||||
@@ -49,6 +49,7 @@ marqdo-cli/
|
||||
│ ├── foreign.md Python/Node kernel protocol
|
||||
│ ├── tool-v1.md generic external Tool Protocol v1
|
||||
│ ├── 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-v1.md public Trace v1 event stream
|
||||
├── crates/
|
||||
|
||||
@@ -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
|
||||
require a core commit.
|
||||
|
||||
Product version for these docs: **`3.0.0-beta.1`** (Linux x86_64 beta).
|
||||
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,
|
||||
Tool v1, Plugin ABI v1, Foreign wire v1, Provider manifest v2, lock v4,
|
||||
markdown profile `marqdo.md.v1`.
|
||||
|
||||
@@ -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,
|
||||
never link Marqdo's Rust internals or depend on `inspect --ir`.
|
||||
|
||||
## Analysis v2 (static)
|
||||
## Analysis v2 and v3 (static)
|
||||
|
||||
```bash
|
||||
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
|
||||
target is removed. Do not generate a consumer artifact with
|
||||
`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,
|
||||
`markdown_profile`), `project`, `modules`, `diagnostics`.
|
||||
- `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.
|
||||
- `check` does not load plugin libraries, start kernels/providers or execute the
|
||||
program.
|
||||
- Schemas: `spec/schemas/analysis-v2.schema.json`; contract:
|
||||
`spec/analysis-v2.md`; consumers: `tests/consumers/analysis_consumer.py`,
|
||||
`tests/consumers/validate_protocols.py`.
|
||||
- Contracts: [Analysis v2](../../spec/analysis-v2.md) and
|
||||
[Analysis v3](../../spec/analysis-v3.md). Each links to its schema.
|
||||
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
|
||||
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
|
||||
Analysis itself.
|
||||
- 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.
|
||||
- Defaults are 100,000 events / 32 MiB; `--trace-max-events` and
|
||||
`--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`
|
||||
(SIGKILL/crash/broken pipe); never synthesize success.
|
||||
- `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.
|
||||
- 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.
|
||||
- Values are off by default (`value_state: not_requested`).
|
||||
`--observe-variable NAME` and `--observe-parameter NAME` are exact-name
|
||||
|
||||
@@ -6,9 +6,9 @@ This page summarizes the public support policy. The authoritative matrix is
|
||||
|
||||
## Version axes (do not conflate)
|
||||
|
||||
| Axis | `3.0.0-beta.1` value | Change rule |
|
||||
| Axis | `3.0.0-rc.2` value | Change rule |
|
||||
|---|---|---|
|
||||
| Product / CLI | `3.0.0-beta.1` | SemVer prerelease; breaking changes inside the 3.0 beta line are allowed and appear in `CHANGELOG.md`. |
|
||||
| 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. |
|
||||
| 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. |
|
||||
@@ -22,14 +22,14 @@ This page summarizes the public support policy. The authoritative matrix is
|
||||
| Plugin/tool/example packages | their own | Independent SemVer. |
|
||||
|
||||
`project.marqdo` and a tool's `compatibility.marqdo` are **enforced product
|
||||
ranges**. Beta cores require a prerelease range such as
|
||||
`>=3.0.0-beta.1,<4.0.0`; `>=3.0.0,<4.0.0` does not match a beta core.
|
||||
ranges**. Prerelease cores require a prerelease range such as
|
||||
`>=3.0.0-beta.1,<4.0.0`; `>=3.0.0,<4.0.0` does not match the RC.
|
||||
|
||||
## Platform support (`3.0.0-beta.1`)
|
||||
## Candidate platform scope
|
||||
|
||||
| Platform | Release status | Notes |
|
||||
|---|---|---|
|
||||
| Linux x86_64 (glibc) | **Supported** | Only release archive: CLI + provider worker, same target triple. |
|
||||
| Linux x86_64 (glibc 2.39 baseline) | **RC target** | Only release archive: CLI + provider worker, same target triple. |
|
||||
| Linux aarch64 | Not built | No artifact; source may build. |
|
||||
| macOS arm64/x86_64 | Experimental, not claimed | Core may run; no macOS provider worker, no plugin ABI claim, no archive. |
|
||||
| Windows x86_64 | Experimental, not claimed | Compile gate only; C ABI/plugin/provider/worker not claimed/fail-closed. |
|
||||
@@ -42,7 +42,7 @@ grant, values are off by default, and `--mode strict` currently refuses
|
||||
|
||||
## Language compatibility
|
||||
|
||||
`3.0.0-beta.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 /
|
||||
block-quote call / first code-span signature) is **not executable**; there is no
|
||||
`--legacy`, syntax switch or downgrade path. Migration is a rewrite task
|
||||
@@ -52,15 +52,8 @@ The earlier `cflmy/marqdo` product line is a different architecture; its source
|
||||
syntax, package format and plugin ABI v2 are not compatible and no hidden
|
||||
compatibility layer is provided.
|
||||
|
||||
## Beta policy
|
||||
## RC policy
|
||||
|
||||
- Beta may break behavior with a changelog note; protocols are versioned
|
||||
separately and only change with a new major.
|
||||
- No LTS is announced. LTS is a later, evidence-based decision (see the
|
||||
prerelease plan §3.2/§5), not a calendar promise.
|
||||
- Known non-security gaps are listed in [release-limits.md](release-limits.md)
|
||||
and in the release notes; unsupported requests must fail closed.
|
||||
- G4 performance is a Beta-only `WARN` on the fixed Woodpecker agent for this
|
||||
release; it is not a general performance guarantee.
|
||||
- Every archive is checksummed and records its source SHA and toolchain.
|
||||
Checksums prove integrity only, not publisher identity.
|
||||
- See [release gates](../releasing.md) for the Linux RC acceptance procedure.
|
||||
- [Known limitations](release-limits.md) ship with the archive.
|
||||
- Every archive records its checksum, source SHA and toolchain.
|
||||
@@ -1,15 +1,15 @@
|
||||
# Quickstart: install and run
|
||||
|
||||
Product: `3.0.0-beta.1` (Linux x86_64 beta). 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.
|
||||
|
||||
## 1. Install the archive
|
||||
|
||||
```bash
|
||||
sha256sum -c marqdo-3.0.0-beta.1-x86_64-unknown-linux-gnu.tar.gz.sha256
|
||||
tar -xzf marqdo-3.0.0-beta.1-x86_64-unknown-linux-gnu.tar.gz
|
||||
cd marqdo-3.0.0-beta.1-x86_64-unknown-linux-gnu
|
||||
./marqdo --version # marqdo 3.0.0-beta.1
|
||||
sha256sum -c marqdo-3.0.0-rc.2-x86_64-unknown-linux-gnu.tar.gz.sha256
|
||||
tar -xzf marqdo-3.0.0-rc.2-x86_64-unknown-linux-gnu.tar.gz
|
||||
cd marqdo-3.0.0-rc.2-x86_64-unknown-linux-gnu
|
||||
./marqdo --version # marqdo 3.0.0-rc.2
|
||||
./marqdo --help
|
||||
```
|
||||
|
||||
@@ -58,9 +58,15 @@ stdout and diagnostics.
|
||||
documentation. Unmarked headings inherit the nearest ancestor mode.
|
||||
- `**strong**`, `*emph*` and inline `` `code` `` are interchangeable carriers of
|
||||
one statement each.
|
||||
- Control flow uses keywords: `if`/`else`/`while`/`end`, plus `params(...)` and
|
||||
`return`.
|
||||
- Lists, block quotes and paragraphs are presentation only.
|
||||
- A branch has an `if`, any number of `else if` arms and an optional
|
||||
final `else`, followed by one `end`. Each condition is evaluated in order.
|
||||
- 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
|
||||
[`../architecture/RFC-LANG-0002-unified-semantics.md`](../architecture/RFC-LANG-0002-unified-semantics.md),
|
||||
[`../../spec/mapping.md`](../../spec/mapping.md) and
|
||||
|
||||
@@ -1,14 +1,14 @@
|
||||
# Marqdo 3.0.0-beta.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
|
||||
the release record: the beta support claim is exactly what is written here.
|
||||
the release record: it defines the platform and feature scope for the release candidate.
|
||||
Items marked **unsupported** must fail closed, not be silently emulated.
|
||||
|
||||
## Platform support
|
||||
|
||||
| Platform | Beta status | Notes |
|
||||
| Platform | RC scope | Notes |
|
||||
|---|---|---|
|
||||
| Linux x86_64 (glibc) | **Supported release platform** | The archived `marqdo` and `marqdo-provider-worker` binaries target `x86_64-unknown-linux-gnu` and are the only binaries this release claims. |
|
||||
| Linux x86_64 (glibc 2.39 baseline) | **Supported release platform** | The archived `marqdo` and `marqdo-provider-worker` binaries target `x86_64-unknown-linux-gnu` and are the only binaries this release claims. |
|
||||
| Linux aarch64 | Not built | No release artifact; source may build. |
|
||||
| macOS (arm64/x86_64) | Experimental, not claimed | Core CLI may work, but no macOS provider worker, no native plugin ABI claim and no macOS release artifact. |
|
||||
| Windows x86_64 | Experimental, not claimed | Core CLI may compile/run; the plugin/provider C ABI and provider worker are not claimed. |
|
||||
@@ -19,14 +19,13 @@ user and is not a security boundary against hostile code.
|
||||
|
||||
## `strict` isolation
|
||||
|
||||
`strict` is Linux-only and probe-gated. The beta release claims it only when the
|
||||
same-SHA G3 evidence recorded in `docs/evidence/` is present; otherwise this file
|
||||
and the release notes must say **strict: unsupported** and the runtime must fail
|
||||
closed (no project code executes).
|
||||
`strict` is Linux-only and probe-gated. The RC release requires same-SHA
|
||||
G3 evidence from a non-root disposable VM. The CLI fails closed when the
|
||||
runtime probe is unavailable.
|
||||
|
||||
Even when available:
|
||||
|
||||
* strict L1 covers the pure language plus native Math;
|
||||
* strict L1 covers the interpreter, console and read-only bundled stdlib;
|
||||
* strict L2 (Worker/Foreign/Provider inside strict) is **unsupported** and every
|
||||
such flag is refused with exit 2;
|
||||
* rlimits are used for resource limits, not cgroup-v2 accounting;
|
||||
@@ -58,18 +57,14 @@ Even when available:
|
||||
|
||||
## Compatibility and versioning
|
||||
|
||||
* `3.0.0-beta.1` is a **prerelease**, not stable and not LTS. Breaking changes
|
||||
inside the 3.0 beta series are allowed and announced in the changelog.
|
||||
* `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
|
||||
v2, Execution Events v1, Tool v1, Plugin ABI v1, Foreign wire v1, Provider
|
||||
manifest v2 and lock v4 keep their own major numbers. Do not infer them from
|
||||
`3.0.0-beta.1`. Execution Events v1 is a post-beta addition and is not in the
|
||||
tagged beta archive.
|
||||
manifest v2 and lock v4 keep their own major numbers.
|
||||
* The official bundled stdlib keeps its independent package version `0.1.0`.
|
||||
A plugin `.mq.md` package version such as `0.1.0` is also independent.
|
||||
* `project.marqdo` in `marqdo.yaml` is enforced in this release. SemVer
|
||||
prerelease rules apply: `>=3.0.0,<4.0.0` does **not** accept a beta core;
|
||||
beta users must declare a prerelease range such as
|
||||
prerelease rules apply: `>=3.0.0,<4.0.0` does **not** accept a prerelease core. Packages and Tools can use a prerelease range such as
|
||||
`>=3.0.0-beta.1,<4.0.0`.
|
||||
* Old `cflmy/marqdo` source syntax, package format and plugin ABI v2 are not
|
||||
compatible. There is no `--legacy` or downgrade path; migration is a separate
|
||||
@@ -82,7 +77,7 @@ Archives are accompanied by SHA256 checksums and `RELEASE_INFO.json`
|
||||
integrity only; they are **not** a publisher signature. A digest obtained from
|
||||
an untrusted Git URL does not make the code trustworthy.
|
||||
|
||||
## Execution Events v1 (post-beta addition)
|
||||
## Execution Events v1
|
||||
|
||||
* Implemented: live stdout/stderr chunks, lifecycle/terminal events, call
|
||||
instance ids, branch/loop/effect events, explicit bounded value observation.
|
||||
@@ -92,7 +87,7 @@ an untrusted Git URL does not make the code trustworthy.
|
||||
* `--mode strict` currently rejects `--event-stream` explicitly; there is no
|
||||
silent fallback to `project`.
|
||||
* The live lane is tested on Linux x86_64; macOS/Windows are unverified for
|
||||
this option like the rest of the beta CLI.
|
||||
this option for this candidate.
|
||||
* In-process native plugins are rejected in event mode
|
||||
(`ext.event_stream_unsupported_native_plugin`) because they share the process
|
||||
and can write the protocol fd directly; worker plugins remain usable.
|
||||
@@ -106,3 +101,10 @@ environment creation, a distributed package registry, JIT execution, built-in
|
||||
Knowledge/Proof/View commands, a mature async/concurrency model, and platform
|
||||
installers. The planned direction is external Tool repositories consuming the
|
||||
public protocols, not new core commands.
|
||||
|
||||
## Beta migration
|
||||
|
||||
The former core `math.*` calls fail static validation with `symbol.unknown`.
|
||||
Use a pure `.mq.md` library or an explicitly selected ABI backend. See
|
||||
[the math library migration](libraries.md).
|
||||
Task/Channel and Resource Control are outside this RC's protocol scope.
|
||||
@@ -20,7 +20,7 @@ marqdo-view/
|
||||
examples/
|
||||
```
|
||||
|
||||
`tool.json` for the `3.0.0-beta.1` product line:
|
||||
`tool.json` for the `3.0.0-rc.2` candidate:
|
||||
|
||||
```json
|
||||
{
|
||||
@@ -44,7 +44,8 @@ marqdo-view/
|
||||
rejects a mismatched range at install and dispatch time with a
|
||||
`requires marqdo …` diagnostic.
|
||||
- `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 (`init`, `run`, `call`, `check`, `inspect`, `fmt`, `plugin`, `add`,
|
||||
`remove`, `lock`, `sync`, `tool`, `help`).
|
||||
@@ -72,7 +73,7 @@ The tool receives:
|
||||
|---|---|
|
||||
| `MARQDO_BIN` | absolute path of the running `marqdo` executable |
|
||||
| `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 |
|
||||
|
||||
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.
|
||||
@@ -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.
|
||||
+46
-20
@@ -4,12 +4,17 @@ This document is the release-candidate procedure. It does **not** grant
|
||||
permission to tag or publish: a tag requires the gates below to be green on the
|
||||
exact commit and an explicit maintainer sign-off recorded in the release notes.
|
||||
|
||||
Two profiles are deliberately separate (see
|
||||
Three profiles apply (see
|
||||
[`MARQDO_3_0_PRERELEASE_PLAN.md`](MARQDO_3_0_PRERELEASE_PLAN.md) §3):
|
||||
|
||||
* **beta** — a prerelease (`-beta.N`) on the platform(s) the project can really
|
||||
test and fix. Known non-security gaps are allowed only when explicitly
|
||||
recorded. `3.0.0-beta.1` claims **Linux x86_64 (glibc)** only.
|
||||
* **rc** — `-rc.N`. The current target is Linux x86_64 (glibc).
|
||||
Record Windows and macOS as UNSUPPORTED for this scope. Require same-SHA
|
||||
Linux CI, frozen extensions, clean install, version compatibility, strict
|
||||
VM PASS. Performance requires fixed-node PASS or the specific shared-node
|
||||
exception documented below.
|
||||
* **stable** — `3.0.0`/LTS. Not covered by beta exceptions; see
|
||||
[`STABLE_RELEASE_IMPLEMENTATION.md`](STABLE_RELEASE_IMPLEMENTATION.md)
|
||||
(historical roadmap input) and the public support matrix.
|
||||
@@ -64,6 +69,29 @@ JIT and built-in Knowledge/Proof/View are **not** beta gates; they are listed as
|
||||
unsupported/experimental in
|
||||
[`developers/release-limits.md`](developers/release-limits.md).
|
||||
|
||||
### Linux RC preconditions
|
||||
|
||||
Use the frozen-SHA build and archive checks above. Additionally:
|
||||
|
||||
- Strict L1 requires a same-SHA PASS on a disposable VM as a non-root user.
|
||||
Record the strict evidence and verify the archived binary on that guest.
|
||||
- Measure the packaged CLI on a dedicated fixed node with 5 warmups and
|
||||
20 samples or more for each of the nine workloads. Compare against a
|
||||
correctness-verified baseline on the same node, CPU affinity, governor,
|
||||
kernel and toolchain. Record investigation and resolution for any p50
|
||||
increase of at least 15% or median peak RSS increase of at least 20%.
|
||||
A dedicated node is the default. For a prerelease approved by the
|
||||
maintainer to use a shared node, take at least three paired beta/RC runs
|
||||
under the same measured conditions and keep all reports. Verify all nine
|
||||
workloads and investigate threshold breaches or unstable samples before
|
||||
accepting a `WARN`. Record the approval, runner environment and limits in
|
||||
the release notes. This exception applies to the named RC only.
|
||||
- Version compatibility covers the locked Rust minimum, CLI and Analysis
|
||||
product identity, Tool/project prerelease ranges, and beta migration.
|
||||
- Use Ubuntu 24.04 (glibc 2.39) for the independent archive-only runtime
|
||||
check. Task/Channel, Resource Control and native macOS/Windows remain
|
||||
outside this candidate's support scope.
|
||||
|
||||
## 2. Build and local gate
|
||||
|
||||
```bash
|
||||
@@ -92,7 +120,7 @@ python3 tools/release/package.py --version "$version" --source-sha "$sha"
|
||||
|
||||
Contents: `marqdo` **and** `marqdo-provider-worker` in the same directory,
|
||||
the **complete verified `stdlib/` bundle** (`stdlib.json`, every `.mq.md` module
|
||||
and self-test), `LICENSE-*`, `README.md`, `CHANGELOG.md`, `COMPATIBILITY.md`,
|
||||
and self-test), `LICENSE-APACHE`, `README.md`, `CHANGELOG.md`, `COMPATIBILITY.md`,
|
||||
`RELEASE_INFO.json`, `SOURCE_SHA`, `KNOWN_LIMITATIONS.md`, `spec/`,
|
||||
`docs/developers/`, `examples/` (with host-built plugin/provider/math-backend
|
||||
artifacts so the examples run without a compiler) and `tests/consumers/`.
|
||||
@@ -100,7 +128,10 @@ artifacts so the examples run without a compiler) and `tests/consumers/`.
|
||||
`RELEASE_INFO.json` records the stdlib `name`, `version`, `tree_digest`,
|
||||
`aliases_digest`, `file_count` and `files`. `package.py` recomputes both digests
|
||||
with the same canonical algorithm as the runtime and refuses to package a mismatch
|
||||
with `stdlib/stdlib.json` (RFC-EXT-0003 H-08 / T-PKG-04). The bundled stdlib is a
|
||||
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
|
||||
fall back to the compile-time source path.
|
||||
|
||||
@@ -119,7 +150,7 @@ python3 tools/release/smoke.py \
|
||||
|
||||
It verifies the `.sha256`, `RELEASE_INFO.json`/`SOURCE_SHA`, both stdlib
|
||||
digests against `stdlib/stdlib.json` and the staged tree, offline
|
||||
`--version`/`--help`, `check`/`run`/`call`, lock/sync, Analysis v2 and Trace v2
|
||||
`--version`/`--help`, `check`/`run`/`call`, lock/sync, Analysis v2/v3 and Trace v2
|
||||
consumers, Tool install/dispatch, native + worker plugin transports, a foreign
|
||||
kernel, Resource Provider v2 through the shipped worker (positive,
|
||||
unauthorized and missing-helper fail-closed), the pure math package and optional
|
||||
@@ -136,18 +167,7 @@ The cold-install gate must run in a container that receives **only the archive
|
||||
bytes** — no source directory, no `/build`, no Cargo — and extracts them itself:
|
||||
|
||||
```bash
|
||||
docker run --rm -v "$PWD/dist:/dist:ro" ubuntu:24.04 sh -c '
|
||||
set -eu
|
||||
mkdir -p /opt/marqdo
|
||||
tar -xzf /dist/marqdo-<version>-x86_64-unknown-linux-gnu.tar.gz -C /opt/marqdo
|
||||
cd /opt/marqdo/marqdo-<version>-x86_64-unknown-linux-gnu
|
||||
./marqdo --version
|
||||
./marqdo --help >/dev/null
|
||||
./marqdo run examples/hello.mq.md
|
||||
./marqdo check examples/multi-module/index.mq.md --emit /tmp/analysis.json
|
||||
./marqdo call examples/math-library-demo.mq.md main
|
||||
./marqdo call examples/factorial.mq.md 阶乘 --arg n=5
|
||||
'
|
||||
bash tools/release/cold-install.sh dist/marqdo-*.tar.gz "$(git rev-parse HEAD)"
|
||||
```
|
||||
|
||||
Run this on the same Linux x86_64 glibc baseline as the release support
|
||||
@@ -172,8 +192,14 @@ python3 tools/ci/release_evidence.py --profile beta --target-sha "$sha" \
|
||||
|
||||
`BETA_RELEASE_CANDIDATE` is the only acceptable decision for a beta tag. A
|
||||
missing, skipped, failed or SHA-mismatched gate is `DO_NOT_RELEASE`; never
|
||||
hand-edit a manifest to PASS. Stable releases use the default `--profile
|
||||
stable` and additionally require Windows/macOS PASS and a strict PASS.
|
||||
hand-edit a manifest to PASS. For a Linux RC, use
|
||||
`--profile rc --require-release` and declare both excluded platforms. If
|
||||
the shared-node exception applies, pass
|
||||
`--rc-shared-performance-approval <release-notes-reference>` and supply
|
||||
`performance=WARN:<candidate-sha>:<comparison-evidence>`. Use the generated
|
||||
`RC_RELEASE_CANDIDATE` decision before running the tagging commands.
|
||||
Stable releases use `--profile stable --require-release` and require native
|
||||
Windows and macOS PASS in addition to the Linux and contract gates.
|
||||
|
||||
## 6. Tagging and publication (owner approval required)
|
||||
|
||||
@@ -189,10 +215,10 @@ git push origin "v${version}"
|
||||
Then create the Gitea release for the tag with `prerelease: true`, attach the
|
||||
tarball and its `.sha256`, and include the release notes. The notes must state:
|
||||
|
||||
* beta / non-LTS status and the Linux x86_64-only support claim;
|
||||
* prerelease status, support lifetime and the Linux x86_64 platform scope;
|
||||
* the breaking RFC-LANG-0002 language change and no legacy path;
|
||||
* the strict policy (same-SHA evidence, or `strict: unsupported` fail-closed);
|
||||
* the G4 Beta-only WARN environment and limits when applicable;
|
||||
* the G4 result and its comparison, including any approved shared-node exception;
|
||||
* independently versioned protocols and stdlib/package versions;
|
||||
* the checksum-integrity-not-signature caveat and the known-limitations file;
|
||||
* the exact source SHA and links to the evidence manifest.
|
||||
|
||||
@@ -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 合计`
|
||||
@@ -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[]`.
|
||||
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.
|
||||
|
||||
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.
|
||||
@@ -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
@@ -84,12 +84,14 @@ implicit string↔number conversions; conversion builtins must be called.
|
||||
* `Return` — written as the `return <expr>` statement in an executable payload
|
||||
— unwinds through any number of branch/loop bodies to the enclosing H2
|
||||
function frame. A function that falls off the end still returns `Unit`.
|
||||
* `Branch` comes from an `if`/`else`/`end` group: the condition is evaluated
|
||||
once, must be `Bool`, and exactly one arm executes (the `else` arm when
|
||||
present and the condition is false, otherwise the then arm). `Loop` comes
|
||||
from a `while`/`end` group and re-evaluates its `Bool` condition before each
|
||||
iteration. The control stack is compile-time only (`spec/mapping.md` §5);
|
||||
neither `end` nor `else` is a runtime instruction.
|
||||
* `Branch` evaluates `if` and `else if` conditions in order. Each reached
|
||||
condition is evaluated once and must be `Bool`. At most one arm executes.
|
||||
When all conditions are false, the optional `else` arm executes.
|
||||
* A `while` loop evaluates its `Bool` condition before each iteration.
|
||||
`Break` exits the nearest loop. `Continue` immediately returns to the
|
||||
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
|
||||
have no initialization side effects and their `main` is never started.
|
||||
* 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)
|
||||
|
||||
Parameters are discovered by definite-assignment data-flow analysis over the
|
||||
function's control-flow graph, never from prose:
|
||||
Definite-assignment analysis uses the function's structured control flow.
|
||||
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
|
||||
edges. Loop bodies may execute zero times.
|
||||
2. Compute the set of variables *definitely assigned* on every path from the
|
||||
function entry.
|
||||
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).
|
||||
An unconditional transfer stops the current sequence. A branch joins only
|
||||
the arms that reach its next statement. A loop may skip the body if its
|
||||
condition can be false. Its normal and `continue` backedges lead to the
|
||||
condition check and its `break` paths join the loop exit.
|
||||
|
||||
Consequences: `**结果 = n * 阶乘(n=n-1)**` infers `n`; `**n = 3**` followed by
|
||||
reads makes `n` a local. Inferred parameters are named arguments only; an
|
||||
|
||||
@@ -118,7 +118,7 @@ Required payload fields: `entry`, `mode`, `source`; optional
|
||||
```
|
||||
|
||||
`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
|
||||
changes, existing events become stale; consumers must not render them onto the
|
||||
new source.
|
||||
@@ -152,6 +152,7 @@ Required payload fields:
|
||||
| `return` | `frame_id`, `value_type`, `module_id`, `span` |
|
||||
| `branch.eval` | `frame_id`, `result`, `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` |
|
||||
|
||||
* `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
|
||||
`continue` (body will execute) or `exit` (condition was false). The event is
|
||||
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
|
||||
stable error code). It never carries effect arguments or file contents.
|
||||
* `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
|
||||
protocol preserves bytes and does not promise automatic redaction of program
|
||||
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.
|
||||
* 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
|
||||
@@ -303,11 +308,11 @@ authorization are unchanged.
|
||||
* Tests use synthetic sentinel values and assert that unselected values never
|
||||
appear in the stream, Trace or `--json`.
|
||||
|
||||
## 6. Relation to Analysis v2 and Trace v2
|
||||
## 6. Relation to Analysis and Trace v2
|
||||
|
||||
| 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. |
|
||||
| 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. |
|
||||
|
||||
+18
-18
@@ -7,17 +7,18 @@
|
||||
it lives; this grammar decides what that payload means. No second parser
|
||||
and no per-file syntax selector exists.
|
||||
|
||||
Implementation state: the Rust expression parser still implements the
|
||||
previous, control-free grammar; this file is the target contract. See
|
||||
docs/STATUS.md.
|
||||
See docs/STATUS.md for implementation and release status.
|
||||
*)
|
||||
|
||||
(* One payload is exactly one statement and must consume the whole payload. *)
|
||||
payload = statement , EOF ;
|
||||
|
||||
statement = if_stmt
|
||||
| else_if_stmt
|
||||
| else_stmt
|
||||
| while_stmt
|
||||
| break_stmt
|
||||
| continue_stmt
|
||||
| end_stmt
|
||||
| return_stmt
|
||||
| params_stmt
|
||||
@@ -25,28 +26,27 @@ statement = if_stmt
|
||||
| expression ;
|
||||
|
||||
if_stmt = "if" , space_required , expression ;
|
||||
else_if_stmt = "else" , space_required , "if" , space_required , expression ;
|
||||
else_stmt = "else" ;
|
||||
while_stmt = "while" , space_required , expression ;
|
||||
break_stmt = "break" ;
|
||||
continue_stmt = "continue" ;
|
||||
end_stmt = "end" ;
|
||||
return_stmt = "return" , space_required , expression ;
|
||||
params_stmt = "params" , "(" , [ parameter_list ] , ")" ;
|
||||
|
||||
(* `if`, `else`, `while`, `end`, `return` and `params` are reserved statement
|
||||
words only when they are the complete first token of a payload.
|
||||
`ifdef(x)` and `returning(x)` are ordinary identifiers; a bare `if` used as
|
||||
an identifier is a reserved-word error. `else`/`end` take no additional
|
||||
tokens: `else x` and `end if` are syntax errors. No trailing colon:
|
||||
`if x > 0:` is a syntax error. No `elif`, `for`, `break`, `continue`,
|
||||
`try`, empty `return`, `end if`, or semicolon-separated multi-statement
|
||||
payload exists in this revision.
|
||||
(* `if`, `else`, `while`, `end`, `return` and `params` are reserved words.
|
||||
`break` and `continue` are contextual: a complete payload of exactly that
|
||||
identifier takes precedence over the ordinary expression production.
|
||||
Calls, assignments and uses inside expressions retain their identifier
|
||||
meaning. Neither loop-control statement takes operands or a label.
|
||||
No trailing colon, `elif`, `for`, `try`, empty `return`, `end if`, or
|
||||
semicolon-separated multi-statement payload is supported.
|
||||
|
||||
Control pairing is not part of this grammar; it is a separate compile-time
|
||||
stack in the frontend:
|
||||
- every `if` has exactly one closing `end`;
|
||||
- `else` is optional and at most one per `if`;
|
||||
- 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.
|
||||
The frontend pairs statements inside each heading execution segment.
|
||||
Each `if` takes zero or more `else if` arms and at most one final `else`.
|
||||
Each `if` and `while` takes one closing `end`. A loop control statement
|
||||
requires an open `while` in the same segment. See mapping.md.
|
||||
*)
|
||||
|
||||
(* Function parameter declaration. It is legal only as the first direct
|
||||
|
||||
+42
-37
@@ -23,8 +23,8 @@ Markdown→program mapping changes.
|
||||
3. **Closed carriers carry one statement each.** In an Exec scope, `Strong`,
|
||||
`Emph` and inline `Code` are interchangeable carriers of one payload. They
|
||||
no longer mean execute/return/lazy respectively.
|
||||
4. **Keywords inside the payload decide the operation.** `if`, `else`, `while`,
|
||||
`end`, `return`, `params(...)`, assignment and expression statements. Lists,
|
||||
4. **Keywords inside the payload decide the operation.** `if`, `else if`, `else`, `while`, `break`,
|
||||
`continue`, `end`, `return`, `params(...)`, assignment and expression statements. Lists,
|
||||
block quotes and paragraphs are document containers only.
|
||||
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.
|
||||
@@ -217,8 +217,9 @@ Each extracted payload is exactly one statement, defined by
|
||||
`spec/expression.ebnf`:
|
||||
|
||||
```text
|
||||
if <expr> else while <expr> end
|
||||
return <expr> params(...) assignment expression
|
||||
if <expr> else if <expr> else end
|
||||
while <expr> break continue
|
||||
return <expr> params(...) assignment expression
|
||||
```
|
||||
|
||||
Lexical details:
|
||||
@@ -226,13 +227,16 @@ Lexical details:
|
||||
* Keywords are recognized only as complete first tokens: `ifdef(...)` and
|
||||
`returning` are ordinary identifiers; a bare `if`/`else` used as an
|
||||
identifier is a reserved-keyword error.
|
||||
* `if`, `while` and `return` require a non-empty expression that consumes the
|
||||
whole payload (to EOF). Trailing characters are errors.
|
||||
* `else` and `end` accept no additional tokens; `else x` and `end if` are
|
||||
`sem.syntax`.
|
||||
* No trailing colon: `if x > 0:` is `sem.syntax`. No `elif`, `for`, `break`,
|
||||
`continue`, `try`, `end if` or semicolon-separated statements in this
|
||||
version.
|
||||
* `if`, `else if`, `while` and `return` require whitespace followed by an
|
||||
expression that consumes the whole payload. Trailing colons are
|
||||
`sem.syntax`. `else` and `end` take no arguments.
|
||||
* `break` and `continue` are loop control only when the complete payload is
|
||||
the single identifier. `break 2` and `continue label` are syntax errors.
|
||||
`break(1)`, `continue = 1` and `return break` retain their ordinary call,
|
||||
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
|
||||
still returns `Unit`. Explicit `return None` is available when `None` is the
|
||||
intended value.
|
||||
@@ -244,33 +248,30 @@ Lexical details:
|
||||
|
||||
## 5. Control-stack lowering
|
||||
|
||||
Within one execution segment, payloads form a token stream. Lower it with one
|
||||
explicit stack:
|
||||
Within one execution segment, payloads form an ordered statement stream.
|
||||
The innermost open control block owns its body.
|
||||
|
||||
```text
|
||||
open_if(cond) -> push IfFrame(cond, then=[], else=None)
|
||||
statement -> append to the innermost active body
|
||||
else -> require top is IfFrame with else=None; switch to else body
|
||||
open_while(cond)-> push WhileFrame(cond, body=[])
|
||||
end -> require a non-empty stack; pop the top frame and lower it
|
||||
at_segment_end -> require the stack to be empty
|
||||
```
|
||||
|
||||
Rules:
|
||||
|
||||
* `else` pairs with the top-of-stack `IfFrame` only. It may not skip an open
|
||||
`while` or an inner `if`.
|
||||
* At most one `else` per `if`; `else` with no open `if` is
|
||||
`sem.unmatched_else`; a second `else` is `sem.duplicate_else`.
|
||||
* `end` closes exactly the most recent open `if`/`while`; no match is
|
||||
`sem.unmatched_end`.
|
||||
* Reaching a segment boundary with an open frame is `sem.unclosed_control`,
|
||||
with a related span on the opener. The compiler must not synthesize an `end`.
|
||||
* `if` lower to the existing `Branch` IR; the optional `else` may lower to a
|
||||
final unconditional arm while preserving left-to-right short-circuit
|
||||
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.
|
||||
* `if` opens a branch with zero or more subsequent `else if` arms and one
|
||||
optional final `else`. Each arm starts in its own carrier. Two carriers
|
||||
containing `else` and `if` still open a nested branch and require separate
|
||||
closing `end` statements. An empty arm is legal.
|
||||
* `else if` and `else` must bind the innermost open block, which must be an
|
||||
`if`. A second `else` or an `else if` after `else` is a hard error.
|
||||
* `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
|
||||
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.
|
||||
Each conditional arm has its own source span.
|
||||
* `while` lowers to `Loop`. `break` exits the nearest open loop and
|
||||
`continue` skips the rest of its body and rechecks its condition. Both
|
||||
require a loop in the same function and heading execution segment.
|
||||
`return` exits the whole function, including from inside a loop.
|
||||
* Definite-assignment inference merges reachable fallthrough paths. Loop
|
||||
exits include condition-failure and `break` paths. `continue` and
|
||||
ordinary body fallthrough lead back to the condition. An abrupt transfer
|
||||
stops inference from its remaining sequence. A reachable free read of an
|
||||
inferred parameter establishes its entry binding before any reassignment.
|
||||
|
||||
## 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.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_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.unmatched_end` | `end` with no open control frame |
|
||||
| `sem.unclosed_control` | an open `if`/`while` at a heading/function/file boundary |
|
||||
|
||||
@@ -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"]}}},
|
||||
"then": {
|
||||
|
||||
+4
-6
@@ -1,7 +1,6 @@
|
||||
# Marqdo Security Model (implemented status)
|
||||
|
||||
Status: **describes the `3.0.0-beta.1` implementation, including honest gaps.** This is
|
||||
not a security audit; it documents what the code actually enforces.
|
||||
Status: describes enforcement in the `3.0.0-rc.2` candidate.
|
||||
|
||||
Normative implementation:
|
||||
|
||||
@@ -14,7 +13,7 @@ Normative implementation:
|
||||
| Project-rooted filesystem | `crates/marqdo-host/src/fs.rs` |
|
||||
| Budgets | `crates/marqdo-host/src/budget.rs` |
|
||||
| Effect tracing | `crates/marqdo-host/src/trace.rs` |
|
||||
| Math/foreign adapters | `crates/marqdo-host/src/kernels.rs` |
|
||||
| Foreign adapter | `crates/marqdo-host/src/kernels.rs` |
|
||||
| Foreign child processes | `crates/marqdo-foreign/src/lib.rs` |
|
||||
| Plugin loading / in-process plugin calls | `crates/marqdo-host/src/host.rs` (`load_plugin`, `op_plugin_invoke`), `crates/marqdo-plugin-abi/src/loader.rs` |
|
||||
| CLI flags and capability construction | `crates/cli/src/main.rs`, `crates/cli/src/commands.rs` |
|
||||
@@ -29,7 +28,7 @@ Normative implementation:
|
||||
|---|---|---|
|
||||
| `pure` | No external I/O; memory computation and budgets only. | **Enforced.** `Capabilities::pure()` = `console`, `math` only; every FS/foreign/plugin grant flag makes the CLI exit 2 with "pure mode prohibits external I/O grants". |
|
||||
| `project` | Operator-approved project resources under `CapabilityHost` + bounded resources. | **Enforced for the implemented operations.** Defaults equal `pure`; `--allow-read`, `--allow-write`, `--allow-net`, `--allow-env`, `--allow-process`, `--allow-random`, `--allow-foreign`, `--allow-plugin` add grants. `resource.open` supports stdin read, separate stdout/stderr write, granted project-file read/write (ADR-0025/0026/0040), granted in-process provider kinds (ADR-0033) and granted TCP/UDP/listener/TLS streams, including DNS names after an exact host grant (ADR-0034/0047/0048); process/device remain unsupported. Sandboxing is cooperative (in-process checks), not OS isolation; in-process providers are trusted, not sandboxed. |
|
||||
| `strict` | Untrusted documents under real OS isolation. | **Linux: enforced when the runtime probe passes (ADR-0021).** `resource.open` is **refused** in strict except for the existing `stdio/stdout` console channel (console grant); stdin/stderr, file/TCP/provider/process resources remain refused until a provider passes the isolation lane (CM-A11, ADR-0030/0034/0040). `PlatformCapabilities::detect()` runs a real Bubblewrap smoke test; success reports `Available { mechanism }`, failure reports `Unavailable { reason }`. Strict L1 supports the interpreter, console, native Math and the read-only bundled stdlib (published at `/run/marqdo-stdlib` for the Compat-C print chain); `--allow-read/--allow-write/--allow-net/--allow-env/--allow-process/--allow-random/--allow-foreign/--allow-plugin/--plugin/--trust-native-plugin/--kernel/--trace-file` are rejected with exit 2. macOS/Windows and Linux hosts without the mechanisms remain `Unavailable`; there is **no fallback** to an unrestricted process. |
|
||||
| `strict` | Untrusted documents under real OS isolation. | **Linux: enforced when the runtime probe passes (ADR-0021).** `resource.open` is **refused** in strict except for the existing `stdio/stdout` console channel (console grant); stdin/stderr, file/TCP/provider/process resources remain refused until a provider passes the isolation lane (CM-A11, ADR-0030/0034/0040). `PlatformCapabilities::detect()` runs a real Bubblewrap smoke test; success reports `Available { mechanism }`, failure reports `Unavailable { reason }`. Strict L1 supports the interpreter, console and the read-only bundled stdlib (published at `/run/marqdo-stdlib` for the Compat-C print chain); `--allow-read/--allow-write/--allow-net/--allow-env/--allow-process/--allow-random/--allow-foreign/--allow-plugin/--plugin/--trust-native-plugin/--kernel/--trace-file` are rejected with exit 2. macOS/Windows and Linux hosts without the mechanisms remain `Unavailable`; there is **no fallback** to an unrestricted process. |
|
||||
|
||||
`marqdo inspect <file> --platform` prints the detection report, for example:
|
||||
|
||||
@@ -92,7 +91,7 @@ set for one run:
|
||||
| Field | Default (`pure`/`project`) | Used by |
|
||||
|---|---|---|
|
||||
| `console: bool` | `true` | `resource.open("stdio","stdin",["read"])`, `resource.open("stdio","stdout"/"stderr",["write"])` and the stdlib console chain; a missing grant is `permission.denied` and stdout/stderr are also bounded by the output budget |
|
||||
| `math: bool` | `true` | `math.*` host ops |
|
||||
| `math: bool` | `true` | Grant ceiling for the `math.compute` plugin capability, subject to package, policy and installed handler checks |
|
||||
| `fs_read: Vec<String>` | empty | `fs.read` and project `resource.open("file", path, ["read"])` |
|
||||
| `fs_write: Vec<String>` | empty | `fs.write` and project `resource.open("file", path, ["write"])` |
|
||||
| `net_hosts: Vec<String>` | empty | exact host/IP grants for `resource.open("tcp"|"udp"|"tcp-listener"|"tls", "host:port", ...)`; DNS is resolved only after the host grant; TLS still validates certificates; `--allow-net <HOST>` adds a grant (ADR-0034/0047/0048) |
|
||||
@@ -171,7 +170,6 @@ before reading. Full symlink/race hardening is an open P4 item.
|
||||
* `resource.request("random.bytes")` → `capabilities.check_random` before
|
||||
`getrandom::fill`;
|
||||
* `fs.write` → `check_write` then `ProjectFs::write`;
|
||||
* math ops → `capabilities.math` (in `crates/marqdo-host/src/kernels.rs`);
|
||||
* foreign ops → `capabilities.check_foreign` (requires `foreign && process`);
|
||||
* plugin invoke → the **complete export name** must be registered, then
|
||||
`capabilities.check_plugin(package)` on **every call**; loading also checks
|
||||
|
||||
+5
-4
@@ -1,6 +1,6 @@
|
||||
# Marqdo CLI Tool Protocol v1 — 通用外部工具协议
|
||||
|
||||
> 状态:**Implemented / frozen protocol v1**(产品 `3.0.0-beta.1`)。核心根命令同样优先;任何官方/第三方工具一视同仁;该协议**不是** C ABI 插件协议。安装、校验、分发与协议协商均已实现并由 `crates/cli/tests/tool_protocol.rs` 覆盖。
|
||||
> 状态:**Implemented / frozen protocol v1**(独立于产品版本)。核心根命令同样优先;任何官方/第三方工具一视同仁;该协议**不是** C ABI 插件协议。安装、校验、分发与协议协商均已实现并由 `crates/cli/tests/tool_protocol.rs` 覆盖。
|
||||
|
||||
## 1. 范围与不变量
|
||||
|
||||
@@ -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 不兼容应显式失败。
|
||||
|
||||
@@ -47,7 +47,8 @@
|
||||
|
||||
工具负责自己的命令层级与帮助,如 `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. 三个独立安全域
|
||||
|
||||
@@ -57,7 +58,7 @@
|
||||
|
||||
## 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、迁移期诊断和工具冲突统计,不能静默覆盖已有已注册工具。
|
||||
|
||||
|
||||
+10
-3
@@ -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;
|
||||
`check`, `inspect` and `tool list` never execute a document.
|
||||
* 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.
|
||||
* No argument values, secrets, handles or file contents are recorded.
|
||||
* 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
|
||||
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>`).
|
||||
`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.
|
||||
|
||||
`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 |
|
||||
| `branch.eval` | `true` / `false` | 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` |
|
||||
| `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
|
||||
additive; consumers must ignore unknown kinds. `effect.operation` names the
|
||||
`HostOp` (`print`, `fs.read`, ...).
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
## @exec 符号
|
||||
|
||||
Regression fixture for separate else and if carriers forming nested branches.
|
||||
|
||||
`if n < 0`
|
||||
|
||||
`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 合计`
|
||||
@@ -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()
|
||||
@@ -13,7 +13,7 @@ analysis = json.loads(analysis_bytes)
|
||||
with open(sys.argv[2], encoding="utf-8") as 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")
|
||||
if trace.get("schema") != "marqdo.trace" or trace.get("schema_version") != 2:
|
||||
raise SystemExit("unsupported trace")
|
||||
|
||||
@@ -48,22 +48,28 @@ def main():
|
||||
trace = json.loads(trace_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("tool-v1.schema.json", tool, "tool")
|
||||
|
||||
# Negative mutations: structure, version and traversal must fail closed.
|
||||
bad = copy.deepcopy(analysis)
|
||||
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.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["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["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`
|
||||
Loaded 100 of 128 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user