diff --git a/docs/adr/0069-public-analysis-boundary.md b/docs/adr/0069-public-analysis-boundary.md new file mode 100644 index 0000000..315d746 --- /dev/null +++ b/docs/adr/0069-public-analysis-boundary.md @@ -0,0 +1,80 @@ +# ADR-0069 — One public Analysis boundary for independent static tools + +Status: Accepted for implementation on the pre-stable 3.0 line (2026-11-25). + +## Context + +Issue [#10](https://git.cflmy.cn/cflmy/marqdo-cli/issues/10) audited the +public Analysis contract at `master@e6066e6`. The CLI already restricts +View/Lint-style consumers to installed Tools, but the emitted +`marqdo.analysis` document only exposed program IR. It omitted the Markdown +document AST, the exact source text, the entry/context snapshot, heading +scopes and anchors, complete section ranges, and reference resolution states. +Independent tools therefore had to re-parse Markdown, guess section ends or run +a second non-public analysis path. Two implementations of Markdown-link +resolution existed (`analysis.rs` and `commands.rs`), the Analysis `unresolved` +state could not distinguish "not loaded" from "missing", and `analysis.rs` +re-read `marqdo.lock` after preparation. + +## Decision + +`marqdo check ENTRY --emit PATH` remains the only public static-analysis +producer. Before the first stable release, replace `marqdo.analysis` revision 3 +in place under ADR-0068. There is one shape, one producer and one validation +path; retired fields are not read. + +The projection is built by one typed encoder from the same +`project_prepare::prepare` facts consumed by `check`, `inspect`, `run` and +`call`: + +* `project.entry_module_id`, `manifest_digest`, the captured `lock_digest`, + stdlib identity and the static extension identities that actually took part + in preparation; +* each loaded module's exact UTF-8 `source` and its `source_digest`, plus the + public Markdown AST (`document`) in the shape already described by + `spec/markdown-profile.md`; +* one heading index: canonical path, parent, effective mode, mode origin and + source unit, heading span, complete section span and the function created by + an Exec H2; +* the anchor map, functions, explicit imports, resources, static call bindings + and diagnostics; +* every Markdown link through one scoped `document_refs` resolver that + distinguishes `resolved`, `not_loaded`, `missing`, `ambiguous`, `external`, + `outside_scope` and `invalid`. + +The resolver is a pure function over an explicit catalog. Ordinary Analysis +uses the loaded-module catalog and never opens a link target. `check --refs` +and `inspect --refs` build a separate, explicitly limited catalog for direct +link targets and append diagnostics; they do not change the ordinary Analysis +module set and never execute or import a target. + +Identity strings stay the current presentation for names that do not contain +the structural separators. Unit paths are now also exposed as the structured +`path` array, and identity display escapes `/`, `#` and `%` inside a path +segment so `#/` cannot collide with a segment containing +`/`. `Function.local_name` and `namespace` remain structured fields; consumers +must not split display ids. + +The public source field is an explicit local artifact. It is written with +owner-only permissions where the platform supports them, is never copied into +Observation, is never printed by default, and its digestion is the exact +UTF-8 bytes (SHA-256). Observation continues to bind to the SHA-256 of the +exact bytes emitted by `check --emit` with the same static options. + +## Security and verification + +The boundary remains non-executing: no plugin shared library, worker, foreign +kernel, network request or implicit module load. `--emit` publishes atomically +through an owner-only exclusive temporary file and rename, refuses to overwrite +a loaded source, manifest, lock file, symlink to one, or a hard link to one, +and only removes a previous artifact at a caller-specified output path under +the same guard. + +Production checks local typed invariants and the canonical encoder; an +independent Python consumer validates the emitted bytes against the published +JSON Schema and semantic invariants, and mutation fixtures prove that missing +required fields, stale same-revision artifacts, tampered digests/spans, +duplicate ids, wrong ownership and invalid reference states are rejected. +`docs/STATUS.md` records exactly what was executed on which SHA; the +pre-stable line makes no compatibility promise for consumers linked to the +retired shape. diff --git a/spec/analysis.md b/spec/analysis.md index 0b5fbbd..e36be52 100644 --- a/spec/analysis.md +++ b/spec/analysis.md @@ -1,20 +1,43 @@ # Marqdo Analysis Current public contract for `marqdo check --emit PATH`. Every project emits -`marqdo.analysis` with `schema_version: 3`. +`marqdo.analysis` with `schema_version: 3`. The contract is implemented by +[ADR-0069](../docs/adr/0069-public-analysis-boundary.md); it replaces the +program-only Analysis shape in place. Retired artifacts with the same revision +are rejected because every field below is required. ## 1. Invariants `check --emit`: -* never executes the document, loads a plugin shared library, starts a foreign - kernel or imports a module implicitly; -* validates the loaded program first; on a compile error it writes no artifact - and removes an existing artifact at the target path; -* writes atomically through a temporary file and rename; -* contains no absolute machine paths, timestamps, PIDs or other environmental - data, so the same logical project emits byte-identical Analysis from - different checkout directories and is safe to compare across machines. +* never executes the document, opens a plugin shared library, starts a worker + or foreign kernel, accesses the network, or imports a module implicitly; +* validates the prepared program first; on a compile or load error it writes + no artifact and only removes a previous artifact at the caller-specified + output path when that path is a safe output (see §8); +* writes through an owner-only exclusive temporary file in the target directory + and renames it into place atomically; +* contains no absolute machine paths, timestamps, PIDs, random ids or other + environmental data, so the same logical project emits byte-identical + Analysis from different checkout directories; +* exposes only facts that one of `check`, `inspect`, `run` or `call` already + consumes through `project_prepare::prepare`. There is no second parser, + second call-binding pass or tool-specific branching. + +`source` is present because it is the one artifact that lets a reader slice +every span without knowing package-cache or stdlib layouts. It contains only +modules that the loader already read statically; no extra file, asset or +binary is read. Treat an emitted Analysis as sensitive local source data: +`--help` and this specification say so, and the CLI neither uploads nor logs +it. + +`AnalysisDigest` is the lowercase hex SHA-256 of the exact UTF-8 bytes written +by `check --emit` (pretty JSON), represented in Observation as +`sha256:<64 hex>`. Diagnostics and every static option that changes the +projection are part of those bytes. `run`/`call` bind to the same projection +with the same static options; a `--refs` invocation adds diagnostics and +therefore has a different digest, and must not be substituted for the ordinary +artifact. ## 2. Top-level shape @@ -24,59 +47,82 @@ Current public contract for `marqdo check --emit PATH`. Every project emits "schema_version": 3, "producer": { "name": "marqdo", - "version": "", + "version": "", "markdown_profile": "marqdo.md.v1" }, "project": { - "root_id": "root:quantum@0.1.0", + "root_id": "root:demo@0.1.0", "identity_kind": "manifest", + "entry_module_id": "root:demo@0.1.0::index.mq.md", "lock_digest": "sha256:<64 hex>", - "stdlib": { - "version": "0.1.0", - "digest": "sha256:<64 hex>", - "instance_id": "std:marqdo-stdlib@0.1.0#<64 hex>" - } + "manifest_digest": "sha256:<64 hex>", + "stdlib": null, + "extensions": [] }, "modules": [], "diagnostics": [] } ``` -`project.identity_kind` is: +### 2.1 Project identity and snapshot -| Kind | `root_id` | Meaning | -|---|---|---| -| `manifest` | `root:@` | Logical identity of a project with `marqdo.yaml`. Moving the checkout or a Git clone does not change it. | -| `workspace_snapshot` | `sha256:<64 hex>` | No manifest. Digest of sorted `(module_id, source_digest)` pairs; identifies content, not a persistent project. | +| Field | Meaning | +|---|---| +| `root_id` | `root:@` for a project with `marqdo.yaml`; `sha256:<64 hex>` content snapshot without one. A snapshot is not a persistent project identity. | +| `identity_kind` | `manifest` or `workspace_snapshot`. | +| `entry_module_id` | The canonical id of the module loaded from `ENTRY`; it must occur exactly once in `modules`. A second entry of the same project produces its own Analysis and is never merged by basename. | +| `lock_digest` | `sha256:` + SHA-256 of the exact `marqdo.lock` bytes captured during preparation; `""` only when no lock file exists. A read failure is a load error, never an empty digest. | +| `manifest_digest` | `sha256:` + SHA-256 of the exact `marqdo.yaml` bytes captured during preparation; `""` when there is no manifest. This distinguishes equal name/version projects with different static configuration. | +| `stdlib` | `null`, or the verified bundle `{version, digest, instance_id}` actually used by this load. | +| `extensions` | Static extension identities that participated in preparation, sorted by `(kind, name, logical_owner, manifest_digest)`. See §2.2. | -`project.lock_digest` is the SHA-256 of the exact `marqdo.lock` bytes prefixed -with `sha256:`, or `""` when there is no lock. It is not a logical identity. +Manifest and lock bytes are read once while loading. Analysis never re-reads +them; a concurrent edit cannot make the artifact claim bytes other than the +snapshot that determined the program. -`project.stdlib` records the verified bundled standard library identity used by -this load: declared version, content digest and package instance id. It is -`null` when no bundle was available. A digest mismatch is a hard load error, so -an Analysis artifact can only name a bundle whose bytes matched the manifest. - -`AnalysisDigest` is the lowercase hex SHA-256 of the exact UTF-8 bytes written -by `check --emit` (pretty JSON). This is what Observation binds to -`source.analysis_digest`; an independent consumer can verify it by hashing the -file. Diagnostics and any configuration options that change the projection are -part of that digest. - -Module ids are `::` (ADR-0008) and are -scoped by `project.root_id`. A module id alone is not a cross-project symbol. - -## 3. Modules - -The module object is unchanged from Analysis v1 except for `resources`: +### 2.2 Extension identity ```json { - "id": "root:res@0.1.0::index.mq.md", - "package_instance_id": "root:res@0.1.0", + "kind": "plugin", + "name": "example.echo", + "version": "0.1.0", + "logical_owner": "root:demo@0.1.0", + "source": "./plugin", + "manifest_digest": "sha256:<64 hex>", + "artifact_digest": "sha256:<64 hex>", + "selected_target": "x86_64-unknown-linux-gnu" +} +``` + +`kind` is `plugin`, `kernel` or `provider`. Declared extensions use the lock v4 +identity that was validated during preparation; explicit `--plugin` descriptors +are included with their verified manifest identity, `source: "--plugin"` and +`logical_owner: "cli"`. No secret, physical path, handle, signature or grant is +projected. Two exports of the same package are one identity; equal export names +in different packages remain distinct. + +### 2.3 Module paths and ordering + +Modules are sorted by canonical `id`. `id` is +`::` and is scoped by +`project.root_id`. `relative_path` must be non-empty UTF-8 with `/` +separators, contain no empty, `.` or `..` segment and no OS absolute, drive or +UNC prefix. Valid names such as `foo..bar.mq.md` are accepted; a file name that +cannot be represented losslessly is rejected rather than silently rewritten. + +## 3. Module shape + +```json +{ + "id": "root:demo@0.1.0::index.mq.md", + "package_instance_id": "root:demo@0.1.0", "relative_path": "index.mq.md", - "source_digest": "<64 hex of exact source bytes>", + "source_digest": "<64 hex SHA-256 of source bytes>", + "source": "", + "document": {"kind": "document", "span": {"start": 0, "end": 0}, "children": []}, "units": [], + "anchors": [], "functions": [], "imports": [], "references": [], @@ -85,119 +131,343 @@ The module object is unchanged from Analysis v1 except for `resources`: } ``` -Modules are sorted by `id`; functions, units and calls keep document order and -the v1 semantic node shapes (`assign`, `expression`, `branch`, `loop`, -`return`; literals, variables, lists, records, unary/binary, member, index, -call). The v1 `call_site` node was retired with RFC-LANG-0002: calls are -`call` expressions inside an `assign`/`expression`/`return`/condition body, not -a separate statement. `imports`, `references` and `calls` remain static facts; a -Markdown reference is not a call. `effects` remains `["unknown"]` (a -conservative summary, not a purity proof). +`source_digest` is the lowercase hex SHA-256 of the decoded UTF-8 bytes of +`source`. BOM, CRLF, missing trailing newline and NUL bytes are preserved in +`source`; JSON escaping changes the encoding only, not the decoded bytes. +Every `span` in the module indexes `source`. -`calls[]` is projected from the single prepared call binding -(`spec/callable-resolution.md` §6): `state` remains -`function`/`builtin`/`plugin`/`unresolved`, and official stdlib aliases such as -`打印` are reported as `function` targets because that is the implementation -that runs. The private `CallBindingTable` is not serialized; Analysis's -schema and version are unchanged. +### 3.1 Document AST -An `assign` node keeps the v1 string `target` for a local rebinding. Addressable -memory adds one additive target form (ADR-0022); consumers that only understand -local assignments can ignore an object target: +`document` is the public shape already defined by +`spec/markdown-profile.md` §5, emitted by an explicit projector and shared with +`inspect --ast`. Every node has `kind`, `span` and `children` (leaves use `[]`). +Leaves carry `literal` where the profile defines one. Attribute rules: -```json -{"kind":"assign", - "target":{"kind":"index", - "base":{"kind":"variable","name":"内存","span":{"start":23,"end":26}}, - "index":{"kind":"literal","type":"int","value":"0","span":{"start":27,"end":28}}, - "span":{"start":23,"end":29}}, - "value":{"kind":"literal","type":"int","value":"7","span":{"start":32,"end":33}}, - "span":{"start":18,"end":35}} -``` +| Kind | Attributes | +|---|---| +| `document`, `block_quote`, `paragraph`, `strong`, `emph`, `strikethrough`, `table_cell` | none | +| `front_matter` | `literal` | +| `list` | `ordered`, `start` (`null` for bullet), `tight` | +| `item` | `task` (`null`, `true`, `false`) | +| `heading` | `level` (1-6), `setext` | +| `text`, `math_block`, `html_block`, `html_inline` | `literal` | +| `code` | `ticks` (delimiter length), `literal` | +| `code_block` | `fenced`, `info`, `literal` | +| `math` | `display`, `literal` | +| `link`, `image` | `url`, `title` | +| `table` | `alignments` (`none`, `left`, `center`, `right`) | +| `table_row` | `header` | +| `thematic_break`, `soft_break`, `line_break` | none | +| `other` | `tag`, optional `literal`, children preserved | -`target.kind` is `"index"`; `base` and `index` use the same expression node -shapes as every other expression. Analysis is static: it records the place but -never allocates a region or executes the write. +The root `document` span covers the whole source including a BOM. All node +spans are half-open UTF-8 byte offsets, `start <= end <= source.len()` and on +UTF-8 boundaries. Container spans follow the parser source map, including its +documented empty/synthetic exceptions; semantic validation checks the +invariants that hold and does not pretend `literal` is byte-identical to the +span (entities, escapes and code whitespace may be normalised). HTML, links and +code blocks are inert data. -## 4. Resources +### 3.2 Units and heading scopes -`resources` is an array, not a count. The projection includes exactly the -resource kinds represented by `marqdo-ir::Resource`; it does not invent table, -HTML or link resources. +`units` is in document order with the root first: ```json { - "id": "root:res@0.1.0::index.mq.md#resource:formula-1", - "module_id": "root:res@0.1.0::index.mq.md", - "unit_id": "root:res@0.1.0::index.mq.md#calc", - "kind": "formula", - "span": {"start": 30, "end": 44}, - "content_digest": "<64 hex>", - "language": null, - "display": true + "id": "root:demo@0.1.0::index.mq.md#力学/计算力", + "path": ["力学", "计算力"], + "parent_id": "root:demo@0.1.0::index.mq.md#力学", + "kind": "function", + "name": "计算力", + "level": 2, + "mode": "exec", + "mode_origin": "explicit", + "mode_source_unit_id": "root:demo@0.1.0::index.mq.md#力学/计算力", + "heading_span": {"start": 10, "end": 30}, + "span": {"start": 10, "end": 90}, + "function": "root:demo@0.1.0::index.mq.md::力学.计算力" } ``` -| Field | Semantics | +| Field | Requirement | |---|---| -| `id` | `#resource:-`; `n` is the 1-based ordinal among resources of that kind in the module, in document order | -| `module_id` | redundant with the enclosing module, present for flattened consumers | -| `unit_id` | innermost owning unit | -| `kind` | `formula` or `code`; future kinds are additive and unknown kinds must be ignored | -| `span` | Markdown node byte span, including math delimiters/fence, relative to that module's source | -| `content_digest` | SHA-256 of the payload: formula LaTeX bytes without delimiters; exact code fence source bytes | -| `language` | code fence info string (may be `""`); `null` for formulas | -| `display` | formula only: block vs inline math | +| `id` | Canonical unit id. Display escapes `/`, `#` and `%` inside each path segment as `%2F`, `%23`, `%25`; `path` is the authoritative structure and consumers must not split `id`. | +| `path` | Canonical NFC/whitespace-normalised heading path, including this heading; `[]` for the root. | +| `parent_id` | Root: `null`. Non-root: nearest real ancestor unit, `null` only for the root; not the Markdown DOM parent. | +| `kind` | `root`, `namespace` (H1), `function` (Exec H2), `knowledge` (Knowledge H2), `section` (H3-H6). | +| `name` | Normalised heading name; `""` for the root. | +| `level` | 0 for the root, otherwise 1-6. | +| `mode` | Effective `exec` or `knowledge`; the root is `knowledge`. | +| `mode_origin` | Root: `default`. Non-root: `explicit` when the ATX heading declares `@exec`/`@knowledge`; otherwise `inherited`. Setext headings never declare. | +| `mode_source_unit_id` | The unit that provides the effective mode: the root, or the nearest explicit ancestor (possibly the unit itself). Must be the unit or one of its ancestors. | +| `heading_span` | Root: `null`. Otherwise the original heading AST span. | +| `span` | Root: whole source including BOM. Otherwise the complete section range: from the heading start to the next heading of the same or higher level, or EOF; it includes all child headings and excludes the next sibling. | +| `function` | Canonical owning `FunctionId` for an Exec section; `null` for Knowledge/namespace/root. Only an Exec H2 creates a callable; nested sections point at it. | -Resource ids are Analysis-local ordinals, not persistent symbols and not `ref` -anchors. Content identity is `(module_id, content_digest)`; location identity is -`(module_id, span)`. Inserting an earlier resource renumbers later ordinals, but -the content digest and span still let a consumer detect the change. Payloads -are not copied into Analysis: consumers read the module source (via -`relative_path`) and slice `span` or verify `content_digest`. +Mode declarations are only the ATX first-Text-child `@exec`/`@knowledge` +tokens; any other `@word` is `sem.invalid_mode_marker`. Mode inheritance pops +same-or-higher-level ancestors first, so a sibling never supplies a mode. +Headings inside lists, block quotes or fences do not create language units. -## 5. Diagnostics +### 3.3 Anchors -Diagnostics no longer embed absolute physical paths: +```json +{"anchor": "计算力", "unit_id": "root:demo@0.1.0::index.mq.md#力学/计算力"} +``` + +`anchors` projects the single `UnitIndex.anchors` map, sorted by `anchor`. +Anchors are navigation names, not identities; slug collisions use the current +numbered algorithm. A display title, semantic name, anchor and unit id are +different concepts; the display title comes from the AST. + +### 3.4 Functions ```json { - "module": "root:res@0.1.0::index.mq.md", + "id": "root:demo@0.1.0::index.mq.md::力学.计算力", + "unit_id": "root:demo@0.1.0::index.mq.md#力学/计算力", + "local_name": "计算力", + "namespace": "力学", + "span": {"start": 10, "end": 90}, + "heading_span": {"start": 10, "end": 30}, + "signature": { + "kind": "explicit", + "params": [{"name": "n", "required": true, "type": "Int", "default": null, + "span": {"start": 31, "end": 41}}] + }, + "effects": ["unknown"], + "body": [] +} +``` + +Every function corresponds one-to-one to an Exec H2 and to its `function` unit. +`namespace` is `null` outside an H1 namespace. Parameters keep declaration order +for explicit signatures and the canonical order for inferred ones; spans are +projected as written. `effects` is the honest conservative default +`["unknown"]`, never a purity proof. + +`body` supports every current public statement: `assign` (string local target or +`{"kind":"index",...}`), `expression`, `branch` (ordered arms), `loop`, +`return`, `break` and `continue`, with the expression variants `literal`, +`variable`, `list`, `record`, `unary`, `binary`, `member`, `index`, `call`. +Arbitrary-precision integers are decimal strings; a float is a finite JSON +number. An unknown required kind is rejected by schema/semantic validation, not +silently dropped. + +### 3.5 Imports + +`imports` keeps `{alias, target, span, resolved}` in document order. +`resolved` is the canonical target module id from the single prepared import +resolution, or `null` for a diagnostic import. Imports are explicit; a link is +never an import. + +### 3.6 References + +See §5. + +### 3.7 Calls + +```json +{ + "function": "root:demo@0.1.0::index.mq.md::main", + "span": {"start": 40, "end": 52}, + "callee": {"kind": "ident", "name": "计算力"}, + "state": "function", + "target": "root:demo@0.1.0::index.mq.md::力学.计算力", + "target_kind": "function", + "target_owner": null, + "reason": null +} +``` + +Calls are projected from the single prepared `CallBindingTable`, one record per +call expression occurrence, in source order. `state`: + +| State | `target` | `target_kind` | +|---|---|---| +| `function` | existing canonical `FunctionId` | `function` | +| `builtin` | canonical builtin name | `builtin` | +| `plugin` | full dotted export name | `plugin` | +| `unresolved` | `null` | `null` | + +For `plugin`, `target_owner` is +`{"kind":"plugin","package":"","digest":"sha256:<64 hex>"}` from the +static descriptor; no plugin function node is fabricated. `reason` is +`dynamic` for a value call and `unbound` when preparation could not bind a +statically known callee, otherwise `null`. Legal dynamic calls do not +invalidate Analysis; genuine compile errors do. + +### 3.8 Resources + +`resources` projects exactly the inert `marqdo-ir::Resource` kinds `formula` and +`code`: `id` (module-local ordinal), `module_id`, `unit_id`, `kind`, `span`, +`content_digest`, `language` (`null` for formula), `display` (`true|false` for +formula, `null` for code). The payload lives in `source`, not in the artifact. +Ordinals are snapshot-local, never persistent symbols. + +## 4. Diagnostics + +```json +{ + "module": "root:demo@0.1.0::index.mq.md", "relative_path": "index.mq.md", "span": {"start": 10, "end": 20}, "line": 2, "column": 3, - "severity": "warning", - "code": "sem.inferred_signature", + "severity": "error", + "code": "sem.invalid_mode_marker", "message": "...", "hints": [] } ``` -`span` is the primary coordinate; `line`/`column` are presentation-derived from -the owning module. `span`, `line` or `column` may be `null` when no precise -location exists. +`span` is primary; `line`/`column` are 1-based presentation derived from the +owning module and may be `null`. A successful Analysis contains no `error` +diagnostic. Diagnostics are deterministic: source position, then code. -The `code` value is an open, stable string: the current language revision adds -the `sem.*` family (`spec/mapping.md` §8) and removes the old -`markdown.inert_executable` warning. Diagnostic codes may be added without changing the structure. +## 5. Reference resolution -## 6. Loop transfers +One pure resolver (`crates/cli/src/document_refs.rs`) handles every Markdown +link. It takes the source module, source span, raw URL and an explicit catalog +of documents with anchors and exact names. It performs no load, call binding, +import, network access or caller-entry fallback. -Conditional arms appear in source order. Both `break` and `continue` are -statements with a `kind` and the half-open UTF-8 `span` of their carrier. -They have no operands or call edges. Walk the enclosing bodies to find -the nearest loop. `break` transfers past that loop and `continue` transfers -to its condition. +### 5.1 Catalog scope -## 7. Validation +* Ordinary Analysis uses only the modules already loaded for this program. + A local target outside that set is `not_loaded`; the artifact states that the + current scope did not verify it, never that it is absent. +* `check --refs` and `inspect --refs` build an explicit extension catalog: + direct local `.mq.md` targets are read once and parsed with the same heading + index; plain files are checked for existence only. They are not added to + `modules`, imports, call bindings or the program, and are never executed. + Budget/IO failures produce errors, never a silent downgrade. +* Given the same catalog, Analysis, `check` and `inspect` must produce the same + state for the same link. -Require exactly `schema: "marqdo.analysis"` and `schema_version: 3` before -traversing the document. The [JSON Schema](schemas/analysis.schema.json) -validates record shapes. Check source digests, spans, ownership and -reference targets separately. Its full branch and loop structure applies -equally to simple projects and imported modules. +### 5.2 Reference record -Source digests cover the original bytes. Preserve UTF-8 byte offsets for -BOM, CRLF, CJK and emoji. Observation binds to the SHA-256 of the exact -emitted Analysis JSON bytes. +```json +{ + "source": "root:demo@0.1.0::index.mq.md", + "source_unit": "root:demo@0.1.0::index.mq.md#力学", + "url": "./theory.mq.md#formula", + "span": {"start": 20, "end": 50}, + "state": "not_loaded", + "target_kind": null, + "target_module": null, + "target_unit": null, + "candidate_package_instance_id": "root:demo@0.1.0", + "candidate_path": "theory.mq.md", + "fragment": "formula", + "candidates": [] +} +``` + +`source_unit` is the innermost unit whose complete `span` contains the link. +`candidate_path` is the normalised package-relative logical candidate; no OS +path is emitted. `fragment` is the once-decoded fragment or `null`; the raw +`url` is always preserved. `candidates` contains exact unit ids only for an +ambiguous canonical-name fallback. + +| State | Meaning | Constraints | +|---|---|---| +| `resolved` | exact target in this catalog, or an explicitly verified local file | `target_kind: module` requires `target_module`; no fragment means `target_unit: null`; a verified plain file uses `target_kind: file` and needs no module | +| `not_loaded` | local candidate is outside this catalog; existence unverified | `target_unit: null`; never reported as missing | +| `missing` | catalog module has no such fragment, or explicit verification proved the file absent | keep the known `target_module` when available | +| `ambiguous` | canonical-name fallback has two or more exact candidates | `target_unit: null`; `candidates` lists all | +| `external` | URI has an external scheme (`http`, `https`, `mailto`, ...) | no network access; target fields `null`; not an error | +| `outside_scope` | local target escapes the allowed package root, or uses an absolute/file/drive/UNC path | target unread; no physical path emitted | +| `invalid` | malformed URI/percent encoding or unsupported address | no guessed repair | + +Exact anchor lookup comes first; the existing canonical-name fallback (if +retained) collects all exact name candidates: 0 `missing`, 1 `resolved`, 2+ +`ambiguous`. No `.find()`, case folding, edit distance or fuzzy binding. An +empty fragment is the document root. The fragment is percent-decoded exactly +once; invalid sequences are `invalid`. + +Consumers may not reinterpret a non-`.mq.md` target as a Marqdo module. A +regular Markdown fragment is not verified against a foreign document profile: +the state is `not_loaded` with a diagnostic that coverage was insufficient, not +`missing`. + +### 5.3 Security + +Paths are normalised segment-by-segment after one percent decode. `file:` +URIs, OS absolute paths, drive/UNC paths, NUL, symlink escape and encoded +traversal are rejected or `outside_scope`. A legal `../` is allowed only while +the normalised candidate stays inside the package module root. The ordinary +Analysis opens no candidate. `--refs` opens only allowed local files, with +size/count limits, conservative symlink rejection and canonical root checking. + +## 6. Validation + +There are two steps on one boundary: + +1. the [JSON Schema](schemas/analysis.schema.json) validates closed record + shapes, required fields, enums, types and array element shapes; +2. a semantic validator checks cross-record invariants that JSON Schema cannot + express. + +The required semantic invariants are: + +1. schema/revision/profile/entry/root/package/module identities agree; ids are + unique; paths do not escape their package; text is valid UTF-8. +2. every `source_digest` matches its `source`; every span belongs to that + module's source, has `start <= end <= source.len()` and lies on UTF-8 + boundaries; functions, statements, resources and references never point at + another module. +3. there is exactly one root unit; parent edges form a tree (no cycle); each + `path` equals its parent's path plus its name; full spans nest with their + parent; heading AST, unit, function and anchor links exist and are + unambiguous; mode source units are self-or-ancestor. +4. functions are unique and correspond to Exec H2 units; each `function` field + points at the real definition; resolved call targets exist; builtin/plugin + targets never pretend to be Marqdo functions; imports resolve to catalog + modules. +5. reference state/nullability/candidates are consistent; `resolved` targets + exist in the catalog; ordinary Analysis has no fabricated external module; + resources refer to real units and their digests match the AST payload. +6. diagnostic owner/severity/code/span/line/column are valid; a successful + Analysis has no error; all arrays and modules are deterministically sorted. + +The producer runs typed local checks before encoding; the independent +`tests/consumers/analysis_consumer.py` and `validate_protocols.py` validate the +serialized bytes. Production validation never replaces consumer validation of +untrusted input. + +## 7. Failure and exit semantics + +`check` keeps its CLI contract: success `0`; static diagnostic errors `1`; +argument, load/IO or output failures `2`. `--json` is a check diagnostic +summary, not a second Analysis writer. `--emit` is the only full Analysis +writer. + +A failed check publishes no success artifact. It may remove a previous artifact +at the caller-specified output path only when that path is not an input source, +manifest, lock/dependency file, directory, symlink or hard link to one, and only +when that previous artifact is the one the caller named. Partial/unsuccessful +Analysis documents do not exist. + +## 8. Output safety + +`--emit PATH`: + +* refuses a path equal to any loaded source, the manifest or the lock file, + including through a hard link or symlink; +* refuses a directory, a symlink at the destination, or an output whose parent + cannot be created safely; +* creates the temporary file exclusively with owner-only permissions on Unix, + writes and flushes it, then renames it over the destination; +* on failure removes only its own temporary file and leaves inputs untouched; +* uses the same canonical encoder for the file and for the Observation digest. + No second pretty writer is allowed. + +## 9. Observation binding + +`run`/`call` compute `source.analysis_digest` by encoding the same +`PreparedProgram` with the same encoder and hashing the exact bytes. +Observation never copies `source`, document AST or link targets into runtime +events. A run with different static options (for example `--refs`, `--plugin` +or a different entry) binds a different artifact; consumers must re-check +digests against the disk version they rely on. diff --git a/spec/markdown-profile.md b/spec/markdown-profile.md index bbea330..8cc8de7 100644 --- a/spec/markdown-profile.md +++ b/spec/markdown-profile.md @@ -80,7 +80,11 @@ parses it exactly once with `serde_yaml`. Supported semantics: ## 5. AST view -`marqdo inspect --ast --json` prints this tree: +`marqdo inspect --ast --json` prints this tree, and `marqdo check --emit` +projects the identical `modules[].document` shape with the same projector +(`spec/analysis.md` §3.1). Neither is a second parser or a second long-lived +AST. The root `document` span covers the whole source including a BOM; every +span is a half-open UTF-8 byte offset into `modules[].source`. ```json { diff --git a/spec/observation.md b/spec/observation.md index 0ca64a0..056fd34 100644 --- a/spec/observation.md +++ b/spec/observation.md @@ -39,6 +39,10 @@ fields. Reject other format identifiers, unknown kinds and invalid payloads. SHA-256 over the file bytes, including formatting. Before highlighting a source span, validate the binding, module source digest and original UTF-8 half-open byte range. A changed source or Analysis invalidates attribution. + The static options that change the projection include the entry, `--plugin`, + load/extension selection and diagnostics; a `--refs` check adds diagnostics + and therefore emits different bytes. Run/call never copy `source`, the + document AST or link targets into runtime events; they only bind the digest. - `call.enter` identifies the call instance and its parent. `call.exit` closes that same instance. Call carriers belong to the caller module. Parameter spans identify declarations in the called module. diff --git a/spec/references.md b/spec/references.md index be3a3f0..f863ee7 100644 --- a/spec/references.md +++ b/spec/references.md @@ -16,7 +16,7 @@ Normative implementation: | Resource collection and attribution | `crates/marqdo-frontend/src/resources.rs` | | Executable payload → statement mapping | `crates/marqdo-frontend/src/map.rs` | | `ref(...)` runtime resolution | `crates/marqdo-runtime/src/builtins_impl.rs` | -| Static link graph (`inspect --refs`) | `crates/cli/src/commands.rs` | +| Static link graph (Analysis `references`, `check --refs`, `inspect --refs`) | `crates/cli/src/document_refs.rs` | | Cross-module call validation | `crates/marqdo-frontend/src/calls.rs` | This file complements [`mapping.md`](mapping.md) (AST roles) and @@ -89,7 +89,10 @@ pub struct UnitId { pub module: ModuleId, pub path: Vec } normalization. `## @exec main` has the semantic name `main`; the declaration is never part of a `UnitId`, `FunctionId` or anchor. * `Display` renders `#`; the root unit renders as - `#`. + `#`. A path segment escapes `%`, `/` and `#` as `%25`, `%2F` and + `%23`, so a single segment named `a/b` cannot collide with the two-level path + `a` -> `b`. Consumers must use the structured `UnitId.path` exposed by + Analysis and must never split a display id to recover hierarchy. * `UnitKind` is `root`, `namespace` (`#`), `function` (`##` Exec) or `section` (`###`+). A Knowledge H2 is an addressable knowledge unit, not a `function`. Sections are addressable but not callable. @@ -125,6 +128,15 @@ to units (`crates/marqdo-frontend/src/units.rs::github_slug`): Internal ids stay canonical, so a heading rename is a link-breaking change but never changes the canonical unit path. +## 2.5 One document-link resolver + +Analysis `references`, `check --refs` and `inspect --refs` use one pure +resolver over an explicit catalog (`spec/analysis.md` §5). It never loads a +module, binds a call or accesses the network. Ordinary Analysis uses only the +loaded modules; the `--refs` checks may add directly referenced local files to +a separate catalog for existence/anchor verification. The retired +`commands.rs::resolve_link` algorithm does not exist. + ## 3. Front matter imports Imports exist only as an explicit YAML mapping in the document's front matter diff --git a/spec/schemas/analysis.schema.json b/spec/schemas/analysis.schema.json index 18b4fdf..2619c8d 100644 --- a/spec/schemas/analysis.schema.json +++ b/spec/schemas/analysis.schema.json @@ -3,6 +3,7 @@ "$id": "https://marqdo.dev/schemas/analysis.schema.json", "title": "Marqdo Analysis", "type": "object", + "additionalProperties": false, "required": [ "schema", "schema_version", @@ -12,365 +13,703 @@ "diagnostics" ], "properties": { - "schema": { - "const": "marqdo.analysis" + "schema": {"const": "marqdo.analysis"}, + "schema_version": {"const": 3}, + "producer": {"$ref": "#/$defs/producer"}, + "project": {"$ref": "#/$defs/project"}, + "modules": { + "type": "array", + "items": {"$ref": "#/$defs/module"} }, - "schema_version": { - "const": 3 + "diagnostics": { + "type": "array", + "items": {"$ref": "#/$defs/diagnostic"} + } + }, + "$defs": { + "span": { + "type": "object", + "additionalProperties": false, + "required": ["start", "end"], + "properties": { + "start": {"type": "integer", "minimum": 0}, + "end": {"type": "integer", "minimum": 0} + } }, "producer": { "type": "object", - "required": [ - "name", - "version", - "markdown_profile" - ], + "additionalProperties": false, + "required": ["name", "version", "markdown_profile"], "properties": { - "name": { - "type": "string" - }, - "version": { - "type": "string" - }, - "markdown_profile": { - "const": "marqdo.md.v1" - } - }, - "additionalProperties": true + "name": {"const": "marqdo"}, + "version": {"type": "string", "minLength": 1}, + "markdown_profile": {"const": "marqdo.md.v1"} + } }, "project": { "type": "object", + "additionalProperties": false, "required": [ "root_id", "identity_kind", - "lock_digest" + "entry_module_id", + "lock_digest", + "manifest_digest", + "stdlib", + "extensions" ], "properties": { "root_id": { "type": "string", - "minLength": 1, - "pattern": "^(root:|sha256:[0-9a-f]{64}$)" - }, - "identity_kind": { - "enum": [ - "manifest", - "workspace_snapshot" - ] + "pattern": "^(root:[A-Za-z0-9_.@+/-]+|sha256:[0-9a-f]{64})$" }, + "identity_kind": {"enum": ["manifest", "workspace_snapshot"]}, + "entry_module_id": {"type": "string", "minLength": 1}, "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 - } + }, + "manifest_digest": { + "type": "string", + "pattern": "^(sha256:[0-9a-f]{64})?$" + }, + "stdlib": { + "type": ["object", "null"], + "additionalProperties": false, + "required": ["version", "digest", "instance_id"], + "properties": { + "version": {"type": "string", "minLength": 1}, + "digest": {"type": "string", "pattern": "^sha256:[0-9a-f]{64}$"}, + "instance_id": {"type": "string", "minLength": 1} } }, - "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 + "extensions": { + "type": "array", + "items": {"$ref": "#/$defs/extension"} } } }, - "statement": { + "extension": { "type": "object", + "additionalProperties": false, "required": [ "kind", - "span" + "name", + "version", + "logical_owner", + "source", + "manifest_digest", + "artifact_digest", + "selected_target" ], + "properties": { + "kind": {"enum": ["plugin", "kernel", "provider"]}, + "name": {"type": "string", "minLength": 1}, + "version": {"type": "string", "minLength": 1}, + "logical_owner": {"type": "string", "minLength": 1}, + "source": {"type": "string", "minLength": 1}, + "manifest_digest": {"type": "string", "pattern": "^sha256:[0-9a-f]{64}$"}, + "artifact_digest": {"type": "string", "pattern": "^sha256:[0-9a-f]{64}$"}, + "selected_target": {"type": "string", "minLength": 1} + } + }, + "module": { + "type": "object", + "additionalProperties": false, + "required": [ + "id", + "package_instance_id", + "relative_path", + "source_digest", + "source", + "document", + "units", + "anchors", + "functions", + "imports", + "references", + "calls", + "resources" + ], + "properties": { + "id": {"type": "string", "pattern": "::"}, + "package_instance_id": {"type": "string", "minLength": 1}, + "relative_path": { + "type": "string", + "minLength": 1, + "pattern": "^(?!/)(?!.*::)(?!.*(^|/)\\.\\.?(/|$))(?![A-Za-z]:)(?!.*\\\\)(?!.*//).*$" + }, + "source_digest": {"type": "string", "pattern": "^[0-9a-f]{64}$"}, + "source": {"type": "string"}, + "document": {"$ref": "#/$defs/node"}, + "units": {"type": "array", "items": {"$ref": "#/$defs/unit"}}, + "anchors": {"type": "array", "items": {"$ref": "#/$defs/anchor"}}, + "functions": {"type": "array", "items": {"$ref": "#/$defs/function"}}, + "imports": {"type": "array", "items": {"$ref": "#/$defs/import"}}, + "references": {"type": "array", "items": {"$ref": "#/$defs/reference"}}, + "calls": {"type": "array", "items": {"$ref": "#/$defs/call"}}, + "resources": {"type": "array", "items": {"$ref": "#/$defs/resource"}} + } + }, + "node": { + "type": "object", + "additionalProperties": false, + "required": ["kind", "span", "children"], "properties": { "kind": { "enum": [ - "assign", - "expression", - "branch", - "loop", - "return", - "break", - "continue" + "document", "front_matter", "block_quote", "list", "item", + "heading", "paragraph", "text", "strong", "emph", "strikethrough", + "code", "code_block", "math", "math_block", "link", "image", + "table", "table_row", "table_cell", "thematic_break", + "soft_break", "line_break", "html_block", "html_inline", "other" ] }, - "span": { - "$ref": "#/$defs/span" - } + "span": {"$ref": "#/$defs/span"}, + "children": {"type": "array", "items": {"$ref": "#/$defs/node"}}, + "literal": {"type": "string"}, + "tag": {"type": "string", "minLength": 1}, + "level": {"type": "integer", "minimum": 1, "maximum": 6}, + "setext": {"type": "boolean"}, + "ordered": {"type": "boolean"}, + "start": {"type": ["integer", "null"], "minimum": 0}, + "tight": {"type": "boolean"}, + "task": {"type": ["boolean", "null"]}, + "ticks": {"type": "integer", "minimum": 1}, + "fenced": {"type": "boolean"}, + "info": {"type": "string"}, + "display": {"type": "boolean"}, + "url": {"type": "string"}, + "title": {"type": "string"}, + "alignments": { + "type": "array", + "items": {"enum": ["none", "left", "center", "right"]} + }, + "header": {"type": "boolean"} }, "allOf": [ - { - "if": { + {"if": {"properties": {"kind": {"const": "front_matter"}}}, + "then": {"required": ["literal"], "properties": {"children": {"maxItems": 0}}}}, + {"if": {"properties": {"kind": {"const": "text"}}}, + "then": {"required": ["literal"], "properties": {"children": {"maxItems": 0}}}}, + {"if": {"properties": {"kind": {"const": "code"}}}, + "then": {"required": ["literal", "ticks"], "properties": {"children": {"maxItems": 0}}}}, + {"if": {"properties": {"kind": {"const": "code_block"}}}, + "then": {"required": ["literal", "fenced", "info"], "properties": {"children": {"maxItems": 0}}}}, + {"if": {"properties": {"kind": {"const": "math"}}}, + "then": {"required": ["literal", "display"], "properties": {"children": {"maxItems": 0}}}}, + {"if": {"properties": {"kind": {"const": "math_block"}}}, + "then": {"required": ["literal"], "properties": {"children": {"maxItems": 0}}}}, + {"if": {"properties": {"kind": {"const": "html_block"}}}, + "then": {"required": ["literal"], "properties": {"children": {"maxItems": 0}}}}, + {"if": {"properties": {"kind": {"const": "html_inline"}}}, + "then": {"required": ["literal"], "properties": {"children": {"maxItems": 0}}}}, + {"if": {"properties": {"kind": {"const": "thematic_break"}}}, + "then": {"properties": {"children": {"maxItems": 0}}}}, + {"if": {"properties": {"kind": {"const": "soft_break"}}}, + "then": {"properties": {"children": {"maxItems": 0}}}}, + {"if": {"properties": {"kind": {"const": "line_break"}}}, + "then": {"properties": {"children": {"maxItems": 0}}}}, + {"if": {"properties": {"kind": {"const": "heading"}}}, + "then": {"required": ["level", "setext"]}}, + {"if": {"properties": {"kind": {"const": "list"}}}, + "then": {"required": ["ordered", "start", "tight"]}}, + {"if": {"properties": {"kind": {"const": "item"}}}, + "then": {"required": ["task"]}}, + {"if": {"properties": {"kind": {"const": "link"}}}, + "then": {"required": ["url", "title"]}}, + {"if": {"properties": {"kind": {"const": "image"}}}, + "then": {"required": ["url", "title"]}}, + {"if": {"properties": {"kind": {"const": "table"}}}, + "then": {"required": ["alignments"]}}, + {"if": {"properties": {"kind": {"const": "table_row"}}}, + "then": {"required": ["header"]}}, + {"if": {"properties": {"kind": {"const": "other"}}}, + "then": {"required": ["tag"]}} + ] + }, + "unit": { + "type": "object", + "additionalProperties": false, + "required": [ + "id", "path", "parent_id", "kind", "name", "level", "mode", + "mode_origin", "mode_source_unit_id", "heading_span", "span", "function" + ], + "properties": { + "id": {"type": "string", "minLength": 1}, + "path": { + "type": "array", + "items": {"type": "string", "minLength": 1} + }, + "parent_id": {"type": ["string", "null"]}, + "kind": {"enum": ["root", "namespace", "function", "knowledge", "section"]}, + "name": {"type": "string"}, + "level": {"type": "integer", "minimum": 0, "maximum": 6}, + "mode": {"enum": ["exec", "knowledge"]}, + "mode_origin": {"enum": ["default", "explicit", "inherited"]}, + "mode_source_unit_id": {"type": "string", "minLength": 1}, + "heading_span": {"oneOf": [{"$ref": "#/$defs/span"}, {"type": "null"}]}, + "span": {"$ref": "#/$defs/span"}, + "function": {"type": ["string", "null"]} + } + }, + "anchor": { + "type": "object", + "additionalProperties": false, + "required": ["anchor", "unit_id"], + "properties": { + "anchor": {"type": "string", "minLength": 1}, + "unit_id": {"type": "string", "minLength": 1} + } + }, + "function": { + "type": "object", + "additionalProperties": false, + "required": [ + "id", "unit_id", "local_name", "namespace", "span", "heading_span", + "signature", "effects", "body" + ], + "properties": { + "id": {"type": "string", "minLength": 1}, + "unit_id": {"type": "string", "minLength": 1}, + "local_name": {"type": "string", "minLength": 1}, + "namespace": {"type": ["string", "null"]}, + "span": {"$ref": "#/$defs/span"}, + "heading_span": {"$ref": "#/$defs/span"}, + "signature": { + "type": "object", + "additionalProperties": false, + "required": ["kind", "params"], + "properties": { + "kind": {"enum": ["explicit", "inferred"]}, + "params": {"type": "array", "items": {"$ref": "#/$defs/param"}} + } + }, + "effects": { + "type": "array", + "items": {"enum": ["unknown"]} + }, + "body": {"type": "array", "items": {"$ref": "#/$defs/statement"}} + } + }, + "param": { + "type": "object", + "additionalProperties": false, + "required": ["name", "required", "type", "default", "span"], + "properties": { + "name": {"type": "string", "minLength": 1}, + "required": {"type": "boolean"}, + "type": {"type": ["string", "null"]}, + "default": { + "oneOf": [{"$ref": "#/$defs/expression"}, {"type": "null"}] + }, + "span": {"$ref": "#/$defs/span"} + } + }, + "statement": { + "oneOf": [ + {"$ref": "#/$defs/stmt_assign"}, + {"$ref": "#/$defs/stmt_expression"}, + {"$ref": "#/$defs/stmt_branch"}, + {"$ref": "#/$defs/stmt_loop"}, + {"$ref": "#/$defs/stmt_return"}, + {"$ref": "#/$defs/stmt_break"}, + {"$ref": "#/$defs/stmt_continue"} + ] + }, + "stmt_assign": { + "type": "object", + "additionalProperties": false, + "required": ["kind", "target", "value", "span"], + "properties": { + "kind": {"const": "assign"}, + "target": {"$ref": "#/$defs/place"}, + "value": {"$ref": "#/$defs/expression"}, + "span": {"$ref": "#/$defs/span"} + } + }, + "stmt_expression": { + "type": "object", + "additionalProperties": false, + "required": ["kind", "value", "span"], + "properties": { + "kind": {"const": "expression"}, + "value": {"$ref": "#/$defs/expression"}, + "span": {"$ref": "#/$defs/span"} + } + }, + "stmt_branch": { + "type": "object", + "additionalProperties": false, + "required": ["kind", "arms", "span"], + "properties": { + "kind": {"const": "branch"}, + "arms": { + "type": "array", + "minItems": 1, + "items": { + "type": "object", + "additionalProperties": false, + "required": ["condition", "condition_span", "body", "span"], "properties": { - "kind": { - "const": "loop" - } - } - }, - "then": { - "required": [ - "body" - ], - "properties": { - "body": { - "$ref": "#/$defs/body" - } + "condition": {"$ref": "#/$defs/expression"}, + "condition_span": {"$ref": "#/$defs/span"}, + "body": {"type": "array", "items": {"$ref": "#/$defs/statement"}}, + "span": {"$ref": "#/$defs/span"} } } }, + "span": {"$ref": "#/$defs/span"} + } + }, + "stmt_loop": { + "type": "object", + "additionalProperties": false, + "required": ["kind", "condition", "condition_span", "body", "span"], + "properties": { + "kind": {"const": "loop"}, + "condition": {"$ref": "#/$defs/expression"}, + "condition_span": {"$ref": "#/$defs/span"}, + "body": {"type": "array", "items": {"$ref": "#/$defs/statement"}}, + "span": {"$ref": "#/$defs/span"} + } + }, + "stmt_return": { + "type": "object", + "additionalProperties": false, + "required": ["kind", "value", "span"], + "properties": { + "kind": {"const": "return"}, + "value": {"$ref": "#/$defs/expression"}, + "span": {"$ref": "#/$defs/span"} + } + }, + "stmt_break": { + "type": "object", + "additionalProperties": false, + "required": ["kind", "span"], + "properties": { + "kind": {"const": "break"}, + "span": {"$ref": "#/$defs/span"} + } + }, + "stmt_continue": { + "type": "object", + "additionalProperties": false, + "required": ["kind", "span"], + "properties": { + "kind": {"const": "continue"}, + "span": {"$ref": "#/$defs/span"} + } + }, + "place": { + "oneOf": [ + {"type": "string", "minLength": 1}, { - "if": { - "properties": { - "kind": { - "const": "branch" - } - } - }, - "then": { - "required": [ - "arms" - ], - "properties": { - "arms": { - "type": "array", - "items": { - "type": "object", - "required": [ - "body" - ], - "properties": { - "body": { - "$ref": "#/$defs/body" - } - } - } - } - } + "type": "object", + "additionalProperties": false, + "required": ["kind", "base", "index", "span"], + "properties": { + "kind": {"const": "index"}, + "base": {"$ref": "#/$defs/expression"}, + "index": {"$ref": "#/$defs/expression"}, + "span": {"$ref": "#/$defs/span"} } } ] + }, + "expression": { + "oneOf": [ + {"$ref": "#/$defs/expr_literal"}, + {"$ref": "#/$defs/expr_variable"}, + {"$ref": "#/$defs/expr_list"}, + {"$ref": "#/$defs/expr_record"}, + {"$ref": "#/$defs/expr_unary"}, + {"$ref": "#/$defs/expr_binary"}, + {"$ref": "#/$defs/expr_member"}, + {"$ref": "#/$defs/expr_index"}, + {"$ref": "#/$defs/expr_call"} + ] + }, + "expr_literal": { + "type": "object", + "additionalProperties": false, + "required": ["kind", "type", "span"], + "properties": { + "kind": {"const": "literal"}, + "type": {"enum": ["int", "float", "text", "bool", "none"]}, + "value": {"type": ["string", "number", "boolean"]}, + "span": {"$ref": "#/$defs/span"} + }, + "allOf": [ + {"if": {"properties": {"type": {"const": "int"}}}, + "then": {"required": ["value"], "properties": {"value": {"type": "string", "pattern": "^-?[0-9]+$"}}}}, + {"if": {"properties": {"type": {"const": "float"}}}, + "then": {"required": ["value"], "properties": {"value": {"type": "number"}}}}, + {"if": {"properties": {"type": {"const": "text"}}}, + "then": {"required": ["value"], "properties": {"value": {"type": "string"}}}}, + {"if": {"properties": {"type": {"const": "bool"}}}, + "then": {"required": ["value"], "properties": {"value": {"type": "boolean"}}}}, + {"if": {"properties": {"type": {"const": "none"}}}, + "then": {"not": {"required": ["value"]}}} + ] + }, + "expr_variable": { + "type": "object", + "additionalProperties": false, + "required": ["kind", "name", "span"], + "properties": { + "kind": {"const": "variable"}, + "name": {"type": "string", "minLength": 1}, + "span": {"$ref": "#/$defs/span"} + } + }, + "expr_list": { + "type": "object", + "additionalProperties": false, + "required": ["kind", "items", "span"], + "properties": { + "kind": {"const": "list"}, + "items": {"type": "array", "items": {"$ref": "#/$defs/expression"}}, + "span": {"$ref": "#/$defs/span"} + } + }, + "expr_record": { + "type": "object", + "additionalProperties": false, + "required": ["kind", "entries", "span"], + "properties": { + "kind": {"const": "record"}, + "entries": { + "type": "array", + "items": { + "type": "object", + "additionalProperties": false, + "required": ["key", "key_span", "value"], + "properties": { + "key": {"type": "string", "minLength": 1}, + "key_span": {"$ref": "#/$defs/span"}, + "value": {"$ref": "#/$defs/expression"} + } + } + }, + "span": {"$ref": "#/$defs/span"} + } + }, + "expr_unary": { + "type": "object", + "additionalProperties": false, + "required": ["kind", "op", "operand", "span"], + "properties": { + "kind": {"const": "unary"}, + "op": {"enum": ["not", "neg", "pos"]}, + "operand": {"$ref": "#/$defs/expression"}, + "span": {"$ref": "#/$defs/span"} + } + }, + "expr_binary": { + "type": "object", + "additionalProperties": false, + "required": ["kind", "op", "left", "right", "span"], + "properties": { + "kind": {"const": "binary"}, + "op": { + "enum": [ + "or", "and", "eq", "ne", "lt", "le", "gt", "ge", + "add", "sub", "mul", "div", "floor_div", "mod", "pow" + ] + }, + "left": {"$ref": "#/$defs/expression"}, + "right": {"$ref": "#/$defs/expression"}, + "span": {"$ref": "#/$defs/span"} + } + }, + "expr_member": { + "type": "object", + "additionalProperties": false, + "required": ["kind", "base", "field", "span"], + "properties": { + "kind": {"const": "member"}, + "base": {"$ref": "#/$defs/expression"}, + "field": {"type": "string", "minLength": 1}, + "span": {"$ref": "#/$defs/span"} + } + }, + "expr_index": { + "type": "object", + "additionalProperties": false, + "required": ["kind", "base", "index", "span"], + "properties": { + "kind": {"const": "index"}, + "base": {"$ref": "#/$defs/expression"}, + "index": {"$ref": "#/$defs/expression"}, + "span": {"$ref": "#/$defs/span"} + } + }, + "expr_call": { + "type": "object", + "additionalProperties": false, + "required": ["kind", "callee", "args", "span"], + "properties": { + "kind": {"const": "call"}, + "callee": {"$ref": "#/$defs/expression"}, + "args": {"type": "array", "items": {"$ref": "#/$defs/arg"}}, + "span": {"$ref": "#/$defs/span"} + } + }, + "arg": { + "type": "object", + "additionalProperties": false, + "required": ["name", "value", "span"], + "properties": { + "name": {"type": ["string", "null"]}, + "value": {"$ref": "#/$defs/expression"}, + "span": {"$ref": "#/$defs/span"} + } + }, + "import": { + "type": "object", + "additionalProperties": false, + "required": ["alias", "target", "span", "resolved"], + "properties": { + "alias": {"type": "string", "minLength": 1}, + "target": {"type": "string", "minLength": 1}, + "span": {"$ref": "#/$defs/span"}, + "resolved": {"type": ["string", "null"]} + } + }, + "reference": { + "type": "object", + "additionalProperties": false, + "required": [ + "source", "source_unit", "url", "span", "state", "target_kind", + "target_module", "target_unit", "candidate_package_instance_id", + "candidate_path", "fragment", "candidates" + ], + "properties": { + "source": {"type": "string", "minLength": 1}, + "source_unit": {"type": "string", "minLength": 1}, + "url": {"type": "string"}, + "span": {"$ref": "#/$defs/span"}, + "state": { + "enum": [ + "resolved", "not_loaded", "missing", "ambiguous", + "external", "outside_scope", "invalid" + ] + }, + "target_kind": {"enum": ["module", "file", null]}, + "target_module": {"type": ["string", "null"]}, + "target_unit": {"type": ["string", "null"]}, + "candidate_package_instance_id": {"type": ["string", "null"]}, + "candidate_path": {"type": ["string", "null"]}, + "fragment": {"type": ["string", "null"]}, + "candidates": { + "type": "array", + "items": {"type": "string", "minLength": 1} + } + } + }, + "callee": { + "oneOf": [ + { + "type": "object", + "additionalProperties": false, + "required": ["kind", "name"], + "properties": { + "kind": {"const": "ident"}, + "name": {"type": "string", "minLength": 1} + } + }, + { + "type": "object", + "additionalProperties": false, + "required": ["kind", "base", "field"], + "properties": { + "kind": {"const": "member"}, + "base": {"$ref": "#/$defs/callee"}, + "field": {"type": "string", "minLength": 1} + } + }, + { + "type": "object", + "additionalProperties": false, + "required": ["kind", "span"], + "properties": { + "kind": {"const": "expression"}, + "span": {"$ref": "#/$defs/span"} + } + } + ] + }, + "target_owner": { + "oneOf": [ + { + "type": "object", + "additionalProperties": false, + "required": ["kind", "package", "digest"], + "properties": { + "kind": {"const": "plugin"}, + "package": {"type": "string", "minLength": 1}, + "digest": {"type": "string", "pattern": "^sha256:[0-9a-f]{64}$"} + } + }, + {"type": "null"} + ] + }, + "call": { + "type": "object", + "additionalProperties": false, + "required": [ + "function", "span", "callee", "state", "target", "target_kind", + "target_owner", "reason" + ], + "properties": { + "function": {"type": "string", "minLength": 1}, + "span": {"$ref": "#/$defs/span"}, + "callee": {"$ref": "#/$defs/callee"}, + "state": {"enum": ["function", "builtin", "plugin", "unresolved"]}, + "target": {"type": ["string", "null"]}, + "target_kind": {"enum": ["function", "builtin", "plugin", null]}, + "target_owner": {"$ref": "#/$defs/target_owner"}, + "reason": {"enum": ["dynamic", "unbound", null]} + } + }, + "resource": { + "type": "object", + "additionalProperties": false, + "required": [ + "id", "module_id", "unit_id", "kind", "span", "content_digest", + "language", "display" + ], + "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": {"$ref": "#/$defs/span"}, + "content_digest": {"type": "string", "pattern": "^[0-9a-f]{64}$"}, + "language": {"type": ["string", "null"]}, + "display": {"type": ["boolean", "null"]} + } + }, + "diagnostic": { + "type": "object", + "additionalProperties": false, + "required": [ + "module", "relative_path", "span", "line", "column", + "severity", "code", "message", "hints" + ], + "properties": { + "module": {"type": "string", "pattern": "::"}, + "relative_path": {"type": "string", "minLength": 1}, + "span": {"oneOf": [{"$ref": "#/$defs/span"}, {"type": "null"}]}, + "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"}} + } } } }