Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
aaec78fcc9 | ||
|
|
71cadfa0cd | ||
|
|
b9a31bb848 | ||
|
|
8f0d96ca63 | ||
|
|
a578ac98a0 | ||
|
|
eeb1069cfc | ||
|
|
754a9b4b7c | ||
|
|
0fc0826435 | ||
|
|
10d7f3340d | ||
|
|
75bc285386 | ||
|
|
ded72c2339 | ||
|
|
1b1c3e3abb | ||
|
|
90fae14818 | ||
|
|
1f8283236f | ||
|
|
f1d79df497 | ||
|
|
bed5b0e832 | ||
|
|
a2a28f8d23 | ||
|
|
472fe7a433 | ||
|
|
6de3b53103 | ||
|
|
b2c970b467 | ||
|
|
021bdc5a92 | ||
|
|
6216cff4cf | ||
|
|
9ff6e7cf7a | ||
|
|
2c515cf3bd | ||
|
|
e8a18a7cf9 | ||
|
|
02b9d5ce4c | ||
|
|
112e0d910b | ||
|
|
bff8014c1f | ||
|
|
df3f4072dd | ||
|
|
1513aa2794 | ||
|
|
3174e24eea | ||
|
|
847b1caa7e | ||
|
|
cdebb49d89 | ||
|
|
b96ff3935a | ||
|
|
7d14bd0dd1 | ||
|
|
dc0f2e12f3 | ||
|
|
bc311bc076 | ||
|
|
a34558d3be | ||
|
|
2cc4d115d0 | ||
|
|
1516949567 | ||
|
|
c4e1580bb0 | ||
|
|
c6d296a7e2 | ||
|
|
80cf197be6 | ||
|
|
865cd55e21 | ||
|
|
6d2b9619e3 | ||
|
|
65a1fef17c | ||
|
|
ef1a4478c5 | ||
|
|
632c8feb36 | ||
|
|
aa40345281 | ||
|
|
8547b85825 | ||
|
|
4ecad78433 | ||
|
|
eb5161b207 | ||
|
|
aed40d7464 | ||
|
|
b6b76efc0d | ||
|
|
01bb52a76d | ||
|
|
1797516f46 | ||
|
|
e2ecfea69b | ||
|
|
4b6b5fc197 | ||
|
|
2b2d2bc18b | ||
|
|
c091f80e6e | ||
|
|
14b8e187ea | ||
|
|
00ac6eb86c | ||
|
|
843635ed26 | ||
|
|
2c0f93839f | ||
|
|
09b7ebddc4 | ||
|
|
cf04ff1442 | ||
|
|
1a68ae0795 | ||
|
|
0e47384532 | ||
|
|
28ebbbbc4c | ||
|
|
4f5906b0ff | ||
|
|
f08507a789 | ||
|
|
691ef26a01 | ||
|
|
5930f91ed6 | ||
|
|
1b80671dd0 | ||
|
|
49a2446f85 | ||
|
|
67ed8e09be | ||
|
|
1086e54ecc |
@@ -12,3 +12,38 @@
|
||||
*.png binary
|
||||
*.jpg binary
|
||||
*.zip binary
|
||||
|
||||
# Exact source/recovery oracles and archived ledgers retain their measured bytes.
|
||||
# Keep ordinary text diffs; only disable checkout/check-in newline conversion.
|
||||
PROJECT_GOAL.md -text whitespace=cr-at-eol
|
||||
harness/fixtures/release1-native/** -text
|
||||
harness/fixtures/interface-operation-probe/** -text
|
||||
harness/history/2026-09-06-ledgers-before-consolidation/** -text
|
||||
harness/history/2026-09-10-ledgers-before-continuation-refresh/** -text
|
||||
harness/history/2026-09-10-ledgers-before-second-consolidation/** -text whitespace=blank-at-eol,blank-at-eof,space-before-tab,cr-at-eol
|
||||
harness/experiments/textual-authoring-20260911-local/** -text whitespace=blank-at-eol,blank-at-eof,space-before-tab,cr-at-eol
|
||||
crates/oa-desktop/src/recovery/fixtures/*.json -text
|
||||
crates/oa-core/src/analysis_numeric/fixtures/** -text whitespace=cr-at-eol
|
||||
harness/fixtures/source7-native/** -text
|
||||
harness/fixtures/basic-editing/** -text
|
||||
harness/fixtures/scenario-authoring/base/** -text whitespace=cr-at-eol
|
||||
harness/experiments/textual-authoring-20260911/** -text whitespace=cr-at-eol
|
||||
harness/experiments/textual-authoring-20260911/observed/split-entry.arcadia whitespace=-blank-at-eol,cr-at-eol
|
||||
harness/experiments/analysis-context-20260911/** -text whitespace=cr-at-eol
|
||||
harness/experiments/analysis-baseline-20260911/** -text whitespace=cr-at-eol
|
||||
harness/experiments/library-compatibility-20260911/** -text whitespace=cr-at-eol
|
||||
harness/experiments/refined-contracts-review-20260911/** -text whitespace=cr-at-eol
|
||||
harness/behavior-creation-contract.rs -text whitespace=cr-at-eol
|
||||
harness/experiments/source-cli-independent-20260911/** -text whitespace=cr-at-eol
|
||||
|
||||
# Preserve checksum-bound font notices verbatim through Git round trips.
|
||||
scripts/windows-notices/GNOME-Cantarell-61362600e104-COPYING -text
|
||||
scripts/windows-notices/Fira-OFL.txt -text
|
||||
scripts/windows-notices/FiraSans-Regular-NOTICE.txt -text
|
||||
harness/experiments/behavior-creation-native-20260911/** -text whitespace=cr-at-eol
|
||||
harness/experiments/constructor-defaults-20260911/** -text whitespace=cr-at-eol
|
||||
harness/experiments/constructor-defaults-20260911/results/*.arcadia whitespace=-blank-at-eol,cr-at-eol
|
||||
harness/release-scenario-native-9e8r6t-20260911.md -text whitespace=cr-at-eol
|
||||
|
||||
# Preserve the independently reviewed codec handoff bytes.
|
||||
harness/release-analysis-codec-implementation-20260911.md -text whitespace=-blank-at-eof,cr-at-eol
|
||||
|
||||
@@ -11,3 +11,4 @@
|
||||
/model-store/
|
||||
/.local/
|
||||
.arcadia-save-*/
|
||||
__pycache__/
|
||||
|
||||
@@ -0,0 +1,73 @@
|
||||
# Agent working agreement
|
||||
|
||||
## Working method
|
||||
|
||||
- Follow `PROJECT_GOAL.md` and the user's current instructions. Work autonomously within scope. Resolve discoverable questions yourself; record, test, and revise reversible assumptions. Ask only when a consequential decision needs information or authorization not already available. Continue independent useful work while blocked elsewhere.
|
||||
- Map unfamiliar domains through primary sources, comparable systems, and real user workflows. Identify underlying needs, valuable concepts, and avoidable friction; evaluate improvements rather than merely reproducing features. Synthesize findings into decisions or experiments, and stop research when another action offers greater value.
|
||||
- Make specifications precise enough for compatible independent implementations: definitions, relationships, invariants, valid/invalid examples, and lifecycle or transformation rules where relevant. Trace important requirements and decisions to implementation and verification. Resolve specification ambiguity at its source when implementation exposes it.
|
||||
- For consequential uncertain choices, compare materially different candidates against explicit user-derived criteria. Ask independent critics to challenge assumptions and attempt to falsify proposals; refine or replace candidates as evidence warrants. Record the choice, evidence, tradeoffs, rejected approaches, and reasons to revisit it. Use proportionate effort for reversible local choices.
|
||||
- Plan milestones that resolve uncertainty or deliver useful capability, with explicit dependencies. Test foundational assumptions before substantial downstream work. At checkpoints, assess progress toward the actual objective and replan when evidence invalidates the strategy or progress stalls.
|
||||
- Define observable success and suitable evaluators before repeated improvement: invariants, examples, round trips, transformations, performance checks, realistic user tasks, or explicit review rubrics. Ensure the evaluator measures the intended outcome. For experiments, record the question, expectations, method, result, and implications; isolate exploratory prototypes from production architecture.
|
||||
- Build and run meaningful changes, exercise actual behavior, and inspect useful logs. Investigate crashes, serious warnings, corrupted state, and interaction defects. For GUI work, use Computer Use or equivalent tools to inspect realistic workflows, cognitive load, editing/selection, navigation, feedback, recovery, loading/empty/failure states, accessibility, layout, focus/disabled states, and responsiveness.
|
||||
- Match independent reviews to the artifact and risks. For languages or formats, include ambiguity, round trips, human/AI editability, and version-control behavior where relevant. Verify findings, fix the appropriate conceptual, specification, architectural, implementation, or interaction layer, and recheck affected dependents. Reuse valid evidence; repeat checks for concrete risks, changes, findings, or required gates. Compilation, screenshots, and worker reports alone do not establish correctness or usability.
|
||||
- Favor the simplest maintainable design satisfying known requirements and justified extensibility. Avoid speculative abstraction, unrelated refactoring, and repeating approaches already invalidated by evidence.
|
||||
|
||||
## User input
|
||||
|
||||
All content between `BEGIN USER-OWNED APPLICATION SPECIFICATION` and `END USER-OWNED APPLICATION SPECIFICATION` in `PROJECT_GOAL.md` belongs to the user. Its headings and structure are unrestricted. Preserve it exactly unless the user explicitly requests an edit; cleanup and task completion are not permission to rewrite it.
|
||||
|
||||
Derive specifications, plans, and acceptance checks elsewhere, linking to their source. Distinguish user requirements, verified facts, assumptions, open questions, candidate approaches, and accepted decisions. Interpretations must not silently replace the user's intent. When input changes, reconcile affected work. Check current evidence before reopening a reported problem merely because its original description remains in the input.
|
||||
|
||||
## Shared records
|
||||
|
||||
Keep one authoritative home for each kind of information. Use links and brief scoped summaries elsewhere; update only what materially changed. Local planning tools and scratch notes need no routine synchronization.
|
||||
|
||||
| Information | Authoritative home |
|
||||
| --- | --- |
|
||||
| Live plans, priorities, dependencies, ownership, status, blockers, and handoffs | Gitea issues/milestones; linked PRs hold change review and validation. |
|
||||
| Specifications, architecture, interfaces, and build/run documentation | Established version-controlled project documents. |
|
||||
| Durable decisions and reusable evidence | `harness/DECISIONS.md` and relevant topic notes, or existing equivalents. |
|
||||
| Navigation and integrated-state checkpoint | `harness/STATE.md`: links, verified code commit/release, capabilities, and material limitations. No live task ledger. |
|
||||
| Shared entrypoint | Gitea Wiki: overview and links, without duplicating versioned documentation. |
|
||||
| Published deliverables | Gitea releases, tied to source commits and verification. |
|
||||
|
||||
Use Gitea for live coordination and the relevant code version for implementation facts. Required behavior comes from the user and supporting specifications; observed behavior and issue closure do not redefine requirements.
|
||||
|
||||
## Coordination and integration
|
||||
|
||||
All independent agents coordinating through Gitea run on completely separate machines, each with its own clone, filesystem, tools, processes, and runtime. Gitea and pushed Git history are the shared communication and delivery channels. Local files (including `harness`), unpushed commits, worktrees, test results, and localhost services are not accessible to peers. Matching branch names or paths do not imply synchronized contents.
|
||||
|
||||
1. On starting or resuming, including after compaction, inspect the working branch, local changes, applicable instructions, relevant shared records, and existing implementation. Recover context from authoritative records. Check for newer shared instructions on the actual remote default branch without overwriting local work. Read what is relevant; avoid repeated full-history scans and constant polling.
|
||||
2. Search before creating tasks. Claim a meaningful outcome in its Gitea issue with a stable session identity, scope, remote repository/branch, and acceptance criteria. Keep small steps within that task. Recheck after claiming; comments are not atomic locks. Respect existing ownership and resolve overlapping claims before overlapping work.
|
||||
3. Independent sessions are peers. Each owns its contribution and delegated work on its own machine. Record one integration/release owner when a milestone needs shared coordination. Use distinct remote work branches, partition files/interfaces, and coordinate changes to shared specifications and documents. Worktrees provide local isolation only; they do not share work between machines.
|
||||
4. At meaningful checkpoints or handoffs, record changed results, commit/PR links, verification commands and environment, blockers, and next actions. Identify the tested code version and label uncommitted or unpublished work as local-only. Before asking peers to consume results, push the required code and versioned documentation, including relevant `harness` updates; publish other required artifacts in Gitea and link them. Use repository-relative paths with commit references, reproducible commands, and necessary environment details; local paths and localhost URLs alone are not handoffs. Do not assume another agent is running or has read a message; silence alone does not establish abandonment. Record evidence and preserve existing work when reassigning a task.
|
||||
5. Follow project review and merge conventions. Fetch the relevant remote branches and inspect the identified commits before reviewing or integrating another machine's work. Resolve conflicts while preserving others' edits, and verify the combined result locally; report material environment differences. Local instruction-file edits reach peers only after publication and retrieval. Do not overwrite others' work or force-push shared history to resolve coordination problems.
|
||||
6. Close work when its acceptance criteria are met and the result is integrated or delivered as appropriate. Mark duplicates and superseded tasks explicitly with replacement links. Then choose further useful unowned work while the requested objective remains incomplete.
|
||||
|
||||
Use Gitea MCP for shared coordination. If unavailable, report the failure, buffer necessary handoff information locally, and continue already-owned or clearly non-overlapping work. Reconcile with current Gitea state when access returns; do not claim an ownership update, review, or publication succeeded without confirmation.
|
||||
|
||||
## Delegation and reasoning
|
||||
|
||||
Use GPT-6 Astra exclusively. Gitea peers are independent remote sessions, not subagents controlled by this session. Spawned subagents use the execution environment actually provided by the agent tools; do not assume they share files, and publish their results before Gitea peers need them. Delegate bounded independent research, design, implementation, or review when it improves progress, judgment, or preserves the parent's context. Give subagents the relevant context, ownership boundaries, result format, and evidence requirements. Use fresh critics when practical. The parent owns synthesis and integration and normally consolidates results into Gitea. Choose concurrency according to useful independent work and available resources, including other sessions; there is no agent-count quota.
|
||||
|
||||
Optimize reasoning effort for verified outcomes per cost, including review, retries, and repair:
|
||||
|
||||
- Main agent: default to high for planning, synthesis, integration, and acceptance decisions; medium for dispatching a settled plan and routine coordination.
|
||||
- Subagents: default to medium for bounded implementation and targeted research; low for straightforward retrieval, mechanical edits, and running established checks; high for complex debugging, correctness review, adversarial analysis, or ambiguous design.
|
||||
- Use extra-high selectively for difficult foundational semantic, methodological, formal, or cross-domain decisions. Reserve max for exceptional unresolved problems where additional reasoning is likely to justify its cost. Retain higher settings when evidence supports their value.
|
||||
|
||||
Allocate by task difficulty and consequences, not role or length alone. Start higher when a clearly difficult decision has expensive downstream consequences. Escalate for concrete reasoning difficulties; resolve missing evidence or unclear requirements at their source. Set subagent effort explicitly through supported controls to avoid unintended inheritance. Do not claim an unapplied change or alter global configuration merely to enforce these preferences.
|
||||
|
||||
## Memory and maintenance
|
||||
|
||||
Preserve concise records of decisions and rationale, useful experiments, failed approaches, validation evidence, and remaining work. Link substantial evidence rather than copying logs into indexes. Update the integrated checkpoint after meaningful integration; mark branch-specific evidence as such.
|
||||
|
||||
Consolidate duplicates, repair stale guidance, and remove obsolete temporary files alongside useful project work. Before removing material, check references, active ownership, and ongoing use; preserve unique knowledge and update affected links. Prefer closing, superseding, or archiving history over deletion. User input is excluded from autonomous cleanup.
|
||||
|
||||
If legacy local task ledgers or plans duplicate Gitea, migrate their live content once into existing or appropriately scoped issues, preserve useful decisions/evidence, and mark the old records superseded. Record the migration so later sessions do not repeat it. Do not create empty documents or maintain records for ceremony.
|
||||
|
||||
## Delivery
|
||||
|
||||
Publish versioned Gitea releases at meaningful working milestones; mark unfinished versions as prereleases. Check existing releases/tags and coordinate one owner and version before publishing. Build from an identified integrated commit and verify the packaged result and launch steps.
|
||||
|
||||
Include runnable builds or appropriate artifacts, concise release notes, build/run/deployment instructions as applicable, known limitations, tested platforms, and verification evidence. Confirm publication and artifact availability. Use existing authorized API access or project tooling when MCP lacks a needed release/upload operation. Do not silently replace published versions with different contents.
|
||||
Generated
+80
@@ -65,6 +65,15 @@ dependencies = [
|
||||
"libc",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "ar_archive_writer"
|
||||
version = "0.5.3"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "73cd58deff2140a0a8eae87e417bd01db68a33e148aa93d1e8cd837e55e312b6"
|
||||
dependencies = [
|
||||
"object",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "arrayref"
|
||||
version = "0.3.9"
|
||||
@@ -2107,6 +2116,25 @@ dependencies = [
|
||||
"jni-sys 0.3.1",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "num-bigint"
|
||||
version = "0.5.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "93e7820bc0a80a0238e650327316f929ba18d5be054b647490a3a6a339f3e7c0"
|
||||
dependencies = [
|
||||
"num-integer",
|
||||
"num-traits",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "num-integer"
|
||||
version = "0.1.47"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "7ce2d95d4b3734dc35aa2f45e1aa22cd416814592a4f9d9205e11affd5b8e10b"
|
||||
dependencies = [
|
||||
"num-traits",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "num-traits"
|
||||
version = "0.2.19"
|
||||
@@ -2139,13 +2167,27 @@ dependencies = [
|
||||
"syn 2.0.119",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "oa-cli"
|
||||
version = "0.2.0"
|
||||
dependencies = [
|
||||
"oa-core",
|
||||
"serde",
|
||||
"serde_json",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "oa-core"
|
||||
version = "0.2.0"
|
||||
dependencies = [
|
||||
"libc",
|
||||
"num-bigint",
|
||||
"num-integer",
|
||||
"num-traits",
|
||||
"same-file",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"stacker",
|
||||
"tempfile",
|
||||
"thiserror 2.0.20",
|
||||
"uuid",
|
||||
@@ -2155,10 +2197,16 @@ dependencies = [
|
||||
name = "oa-desktop"
|
||||
version = "0.2.0"
|
||||
dependencies = [
|
||||
"axum",
|
||||
"iced",
|
||||
"iced_runtime",
|
||||
"oa-core",
|
||||
"oa-server",
|
||||
"reqwest",
|
||||
"rfd",
|
||||
"serde",
|
||||
"serde_json",
|
||||
"tempfile",
|
||||
"tokio",
|
||||
]
|
||||
|
||||
@@ -2470,6 +2518,15 @@ dependencies = [
|
||||
"objc2-foundation 0.2.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "object"
|
||||
version = "0.39.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "2e5a6c098c7a3b6547378093f5cc30bc54fd361ce711e05293a5cc589562739b"
|
||||
dependencies = [
|
||||
"memchr",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "once_cell"
|
||||
version = "1.21.4"
|
||||
@@ -2693,6 +2750,16 @@ version = "1.0.18"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "3d595e54a326bc53c1c197b32d295e14b169e3cfeaa8dc82b529f947fba6bcf5"
|
||||
|
||||
[[package]]
|
||||
name = "psm"
|
||||
version = "0.1.32"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "4dcd034599e63b970727f70d79e02d62390a4a84f7c6b827c27c46d5ac3fa622"
|
||||
dependencies = [
|
||||
"ar_archive_writer",
|
||||
"cc",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "quick-xml"
|
||||
version = "0.41.0"
|
||||
@@ -3413,6 +3480,19 @@ version = "1.2.1"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596"
|
||||
|
||||
[[package]]
|
||||
name = "stacker"
|
||||
version = "0.1.25"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "707f49d46706bacf8a2b00d51dace3f9de527c13eec3778f570c411f89e69967"
|
||||
dependencies = [
|
||||
"cc",
|
||||
"cfg-if",
|
||||
"libc",
|
||||
"psm",
|
||||
"windows-sys 0.61.2",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "static_assertions"
|
||||
version = "1.1.0"
|
||||
|
||||
+1
-1
@@ -1,5 +1,5 @@
|
||||
[workspace]
|
||||
members = ["crates/oa-core", "crates/oa-desktop", "crates/oa-server"]
|
||||
members = ["crates/oa-core", "crates/oa-desktop", "crates/oa-server", "crates/oa-cli"]
|
||||
resolver = "2"
|
||||
|
||||
[workspace.package]
|
||||
|
||||
@@ -0,0 +1,74 @@
|
||||
# ARCADIA Studio — development-run summary
|
||||
|
||||
Latest correction: your review identified a misplaced priority in this run. Advanced counterpart review received attention while basic diagram editing remained awkward. The first attempted fix added large creation buttons; you rejected that too. Actual use of the installed Capella 7.1 has now informed a redesign around a compact contextual palette, in-place naming and renaming, relevant existing elements, explicit activity allocation and clear counterpart destinations. Implementation and native verification remain in progress; the downloadable preview described below predates these corrections. [Observed Capella behavior and design decisions](harness/release-capella-basic-editing-20260907.md).
|
||||
|
||||
Updated 7 September 2026. This summarizes the whole continuation run: work integrated from earlier branches, new engineering features, defects found through actual use, and verification on this machine. **The product has advanced substantially, but the complete Windows/Linux release has not yet been accepted.** The latest Windows preview is built, packaged and available for your inspection below.
|
||||
|
||||
## Objective and starting point
|
||||
|
||||
The objective is a usable Operational Analysis (OA) and System Analysis (SA) engineering application, with equivalent graphical, textual and REST workflows, maintained traceability, offline guidance, and working Windows/Linux distributions. The run treated domain semantics, interaction design, recovery, examples and verification as part of the product—not merely as supporting documentation.
|
||||
|
||||
The initial checkout lagged behind other branches. An ancestry, patch-equivalence and code audit found that direct process/scenario/state editing, data contracts, hosted integration and earlier semantic review were already combined in `codex/data-contract-integration`. Work continued from that baseline on `codex/release1-continuation`; duplicate preliminary changes were preserved rather than overwriting integrated work. Source6 work and its evidence were subsequently committed at `4b6b5fc`; source7 and later improvements remain a separately reviewed continuation. No remote publication is implied. [Branch integration](harness/release-branch-integration-20260906.md)
|
||||
|
||||
## Engineering features and editing workflows
|
||||
|
||||
The integrated foundation includes architecture views and ports; typed data, interfaces and values; direct scenario/process gestures; and persisted state-machine views with regions, pseudostates, transitions and maintained action references. The run extended and tested those workflows rather than replacing their shared model.
|
||||
|
||||
Source6 added first-class OA **Communication Means** between participants, with allocated interactions and explicit direction. OA→SA transition requires reviewed component-port choices; it does not silently invent responsibility or substitute a participant for a port. Scenario endpoint resolution handles reverse communication on unoriented channels and correlated Call/Reply behavior. Native testing also corrected transitions that left users on the wrong layer or diagram despite producing the right model.
|
||||
|
||||
Saved views gained exchange categories, hidden-edge choices, relation-kind selection, behavior coverage/context filters and exchange-name/item labels. Filters preserve semantic identities and stable port geometry. Traceability views explicitly support both layers. Advisory checks now locate incomplete behavior coverage, non-leaf work exchanges and mission/capability gaps without turning legitimate unfinished engineering work into structural corruption. [Coverage and implementation map](harness/release-current-coverage-20260906.md)
|
||||
|
||||
Semantic reconciliation became an editable, atomic **multi-source review**. Engineers can review scalar values, constructors, keyed collections, ordered members, child ownership, incident relationships and artifact lifecycle changes. Included rows compose through the shared planner; excluded invalid rows retain their raw input. Conflicting intentions are checked against the actual destination field. Artifact creation, movement, deletion and all seven metadata fields preserve distinctions such as absent versus empty text. Native tests exercised complete Apply/Save/Undo/Redo cycles, not just individual controls. [Artifact evidence](harness/release-artifacts-native-20260906.md), [attachment evidence](harness/release-attachments-native-20260906.md)
|
||||
|
||||
The optional hosted workflow continues to use the same core model and REST service, with conditional ETags, explicit publish/save, conflict handling and retained local drafts. Connection credentials remain in memory. Typed commands, modular source, diagnostics and OpenAPI were kept aligned as representations evolved. Existing hosted acceptance is recorded separately from still-required current-platform transport cases. [Hosted workflow](harness/release-hosted-desktop.md)
|
||||
|
||||
## Source, history, recovery and onboarding
|
||||
|
||||
Home now offers New/Open, examples, the guide, recent local models and recoverable sessions. Missing recent files remain visible with a recovery route. The searchable offline engineering guide has related topics and guarded workspace actions; navigation and scroll behavior were corrected through minimum-window testing.
|
||||
|
||||
Periodic user-local checkpoints preserve the accepted source bundle and raw source, property, behavior, workflow and semantic-review drafts. They do not silently save model files or restore an executable command plan. Recovery creates an unsaved copy, rebuilds previews and requires explicit saving. Write preflight preserves the last good checkpoint if a new snapshot is invalid; close/write races and stale save receipts were covered with regressions.
|
||||
|
||||
Frozen, nonempty old5/old6 fixtures support bounded migration to source7. Accepted headers are upgraded while comments, includes and raw invalid edits are retained. Unsupported newer intent hidden in old structural fields or constructor caches is rejected without destroying the checkpoint; ordinary prose containing those words remains valid raw text. Native old5, old6 and current7 recovery cases compared full bundles, model exports and draft DTOs. [Recovery contract](harness/release-source7-recovery-20260906.md)
|
||||
|
||||
A real Save As defect was fixed: changing the entry filename had created an extra Undo transaction and cleared Redo. Save As now adopts file identity across retained history without an artificial model edit, with conservative filename-collision preflight before disk writes. Journal publication was hardened against Windows scanner/share races and accidental takeover of another writer; Linux uses no-replace publication with fail-closed unsupported behavior. These safeguards do not claim model-file compare-and-swap or universal power-loss guarantees. [Save As](harness/release-save-as-runtime-packaging.md), [journal review](harness/release-journal-publication-review-20260906.md)
|
||||
|
||||
A coherent water-pressure restoration lesson now connects OA responsibilities and communication to explicit SA ports, interfaces, processes, scenarios, state behavior, saved views and evidence. It contains 94 elements, 62 relations, five views, 68 traces and 30 source files, plus deterministic replay inputs and one deliberate warning. Home and the guide open it. Copy the **whole example folder**, including its evidence, before editing. [Walkthrough](examples/release1/README.md)
|
||||
|
||||
## Source7: two substantive semantic gaps closed
|
||||
|
||||
Independent probes established two gaps that existing constructs could not faithfully represent:
|
||||
|
||||
* **Caller-specific process assembly:** ContextualLink addresses include the caller and complete reference-occurrence path. The same leaf reused through two references remains two distinct contributions. Precedence, exchange assembly and common-work purposes have separate meanings; common work does not imply execution fusion. Deletion removes dependent links rather than silently shortening their addresses.
|
||||
* **Exact interface-operation identity:** Messages can retain unresolved operation intent or select a specific InterfaceItemAllocation. Selection requires proof through actual compatible component ports. Reply derives its operation from the exact Call while validating its own channel and correlation; parameterless operations remain distinguishable. Removing an allocation never silently selects another equivalent-looking allocation, and ordinary channel validity still applies.
|
||||
|
||||
Both landed under one source/schema7 contract across core, parser/updater, REST, graphical forms, semantic review and recovery. Old versions reject new fields even when explicitly null. Reference/path admission and bounded contextual analysis are deterministic and independent of cache size; exhausted analysis reports incompleteness rather than fabricated reachability. [Ratified contract](harness/release-source7-integration-decision-20260906.md)
|
||||
|
||||
Native inspection then exposed obscured contextual routes, endpoint hit-priority conflicts, and a separate process Fit problem. Routing and qualified selection were corrected and independently checked. The latest Fit change measures the actual remaining viewport, adds bounded tools/details disclosures and keeps pending-form actions reachable. Its first six tests caught two real failures: Iced discarded zero-size slots and reset the canvas tree. A narrow slot-preserving fix passed all six unchanged expectations, the existing pending-scroll and branch-fit regressions, and the full desktop suite. [Fit review](harness/release-process-fit-independent-review-20260907.md)
|
||||
|
||||
## What has actually been verified
|
||||
|
||||
Windows checkpoints include core **433 passed/1 ignored**, corrected full server **56/56**, and now full desktop **570/570** after the Fit fix. The latest locked workspace binaries build, formatting and strict workspace/all-target Clippy all passed. Native checks used separately hashed binaries and independent complete-model/source oracles for artifacts, batch review, communication, teaching edits, source7 operation choices, nested links and crash recovery—including Save, Undo, Redo and reopening. These are scoped results, not one blanket final-release pass. [Current evidence ledger](harness/STATE.md), [source7 native report](harness/release-source7-native-acceptance-20260907.md)
|
||||
|
||||
Linux verification ran in a real Ubuntu guest under QEMU using Rust1.90, ext4 and immutable source snapshots. Current core completed **436 passed/2 ignored**. Server compilation passed; unit **2/2** and HTTP **50/51** passed. One timing-dependent test returned the legitimate 30-second deadline response504 instead of412, including an isolated rerun. Its replacement uses a private test-only preparation gate to prove real HTTP overlap and retain exact conflict/model/disk assertions; that correction passed on Windows and still needs Linux execution. [Linux gate](harness/release-source7-linux-gate-20260907.md)
|
||||
|
||||
WSL installation was authorized, but importing the isolated distro remains pending a Windows restart. QEMU resources, shutdown budgets and caches were preserved. A cross-built probe actually executed on Linux. After VMware clock adjustments interrupted one watchdog and another run paused for your Windows build, the **full Linux desktop cross-build passed** with Rust1.90 on a fresh snapshot containing the Fit fix. Its final cached build took2m20s; the ELF dependencies, glibc2.28 link baseline and all37 teaching files were checked. Actual Linux GUI execution remains unverified. The built snapshot precedes the subsequent guide-label wording update. [Cross-build status](harness/release-source7-linux-gui-cross-build-20260907.md)
|
||||
|
||||
The next Linux test session failed during kernel startup on three bounded attempts, before any corrected server tests ran. We preserved the failures and extracted the exact verified Ubuntu boot assets for a temporary timer-check workaround. Automatic approval review rejected its preparation/launch command as “blocked by policy,” so that experiment did not run. All task VM processes are stopped. [Boot evidence and pending gate](harness/release-source7-linux-server-corrected-gate-20260907.md)
|
||||
|
||||
## Latest preview and remaining release work
|
||||
|
||||
**Run the latest Windows preview:** open [arcadia-studio.exe](dist/ArcadiaStudio-preview-source7-20260907-x86_64-pc-windows-gnullvm/arcadia-studio.exe). Keep its folder intact, including `libunwind.dll`; no compiler installation or PATH change is needed. To move it elsewhere, extract the whole [preview ZIP](dist/ArcadiaStudio-preview-source7-20260907-x86_64-pc-windows-gnullvm.zip). Home opens the guide and examples. This is a development-profile preview, not the final optimized release.
|
||||
|
||||
Or run this in PowerShell:
|
||||
|
||||
```powershell
|
||||
& 'C:\Users\User\Documents\Git\ARCADIA-Studio\dist\ArcadiaStudio-preview-source7-20260907-x86_64-pc-windows-gnullvm\arcadia-studio.exe'
|
||||
```
|
||||
|
||||
The package contains 565 files, including all 37 teaching files; independent integrity verification and source/build provenance are recorded alongside the ZIP. The packaged executable's SHA-256 begins `DC50C887`; the ZIP's is `1fac10b30daf2f8e1dac29e9469485e4bea142e77ff5a13e4c9d1e41ff03abb2`. [Provenance](dist/ArcadiaStudio-preview-source7-20260907-x86_64-pc-windows-gnullvm.zip.provenance.json)
|
||||
|
||||
The packaged app launched with a clean PATH. At **1444×932**, the accepted OA caller graph fitted at **68%** with all four cards visible. A **1102×932** width was also observed; this does **not** establish the 700-pixel minimum-height case. Your Escape stopped Computer Use before the final UI checks; no clean close is claimed. A subsequent read-only oracle confirmed the saved model and both source files were unchanged; this does not establish unobserved in-memory state. Broader native acceptance remains open.
|
||||
|
||||
The subsequent guide update names the actual Tools, Selection details, Restore panels and Reply operation controls. Formatting, independent label review and a fresh Windows workspace-binary build passed; the downloadable preview above retains its original, already-tested bytes.
|
||||
|
||||
Remaining work is to finish native Fit checks, complete outstanding engineering/hosted workflows, execute the corrected Linux server gate, verify actual Linux GUI behavior, and produce optimized, independently reviewed final packages including the updated guide. Export is explicitly **Architecture SVG**; faithful process/scenario/state SVG is deferred. Logical/physical architecture layers and simulation are outside this OA/SA release. The applicable Windows/Linux acceptance obligations remain open. [Release plan](harness/PLAN.md)
|
||||
+111
@@ -0,0 +1,111 @@
|
||||
# Project goal
|
||||
|
||||
## Objective
|
||||
|
||||
Take the existing project to the complete, coherent, usable, and verified outcome defined by the user input below. Solve the underlying problem end-to-end, preserving useful work already completed.
|
||||
|
||||
Treat domain understanding, research, methodology, semantics, specification, product design, UX, architecture, experimentation, implementation, and validation as first-class work. Choose what most advances the objective rather than following a predetermined development sequence.
|
||||
|
||||
Follow `AGENTS.md` for execution, coordination, record ownership, and delivery. Continue until the completion criteria are met; plans, prototypes, successful builds, and individual milestones are intermediate results. Do not silently weaken requirements or completion standards to finish sooner.
|
||||
|
||||
## Completion criteria
|
||||
|
||||
Apply these criteria to the scope requested by the user:
|
||||
|
||||
- Required capabilities address the intended problem and support realistic user workflows.
|
||||
- Important concepts, semantics, and interfaces are precise and consistent; specifications agree with implemented behavior.
|
||||
- Consequential decisions have evidence and rationale. Major assumptions have been validated, explicitly accepted, or isolated without compromising required behavior.
|
||||
- The result builds, runs, and operates on the required platforms. Relevant tests and evaluators pass; integrations, edge cases, and failure states have been exercised against the actual result.
|
||||
- User-facing behavior and usability have been exercised directly, using representative data and workflows.
|
||||
- A fresh independent review covers requirements, domain/semantic consistency, usability, architecture, correctness, regressions, runtime behavior, documentation, and remaining risks. Valid material findings are addressed, blocking and high-impact issues resolved, and affected behavior reverified; no known blocker or high-severity defect remains.
|
||||
- Deliverables are maintainable, appropriately extensible, documented, and published as required by `AGENTS.md`. Obsolete scaffolding is removed; documentation and shared state accurately describe the result. Another engineer or agent can reproduce the verification and continue the work.
|
||||
|
||||
If required work or verification is blocked, record the specific gap and continue independent useful work without claiming completion.
|
||||
|
||||
## Final handoff
|
||||
|
||||
Link the delivered result and summarize capabilities, discoveries, architecture and decisions, relevant rejected approaches, verification and independent review, remaining limitations, and exact build/run/deployment/verification instructions. Refer to authoritative records instead of repeating the project history.
|
||||
|
||||
## USER-OWNED APPLICATION SPECIFICATION
|
||||
|
||||
The block below accepts all project-specific requirements, context, priorities, and feedback, with any headings or organization the user chooses.
|
||||
|
||||
<!-- BEGIN USER-OWNED APPLICATION SPECIFICATION -->
|
||||
## Application specification
|
||||
|
||||
### General description
|
||||
|
||||
Create a modern clone of ARCADIA Capella using Rust Iced framework. It should be cross platform (supporting Windows and Linux at least). Use Rust exclusively (wherever possible & practical).
|
||||
|
||||
Focus on making the application modern, extensible, intuitive and easy to use. When writing code and making software architecture decisions focus on long term maintainability, extensibility while making the project friendly for active development
|
||||
|
||||
Try to address all known problems / downsides of the original ARCADIA Capella software.
|
||||
|
||||
Version 1 MVP in the form of working Operational Analysis layer is done.
|
||||
Version 2 MVP in the form of working Operation Analysis + System Analysis is done.
|
||||
You should make the 1st release version of the project with fully feature complete Operation Analysis + System Architecture, according to this application specification.
|
||||
Remaining ARCADIA layers will be added in future releases.
|
||||
|
||||
Transitioning of model elements between layers (in both directions) should be easy and intuitive.
|
||||
|
||||
Keep in mind that the target audience for the application are system engineers. And you should satisfy their needs and use cases
|
||||
|
||||
The application should be a general systems modeling tool, like ARCADIA Capella or SysML v2
|
||||
|
||||
You should implement most of the ARCADIA semantics, while adressing original ARCADIA Capella problems / downsides
|
||||
|
||||
The original ARCADIA Capella UI is very bloated, clunky, unintuitive and hard to use. In addition, it lacks a number of quality of life features. You should at all cost avoid making the same mistakes as the developers of the original ARCADIA Capella
|
||||
|
||||
You should explore the functionality & UI of the original ARCADIA Capella to take the most useful and powerful ideas from it. While making them modern, easy to use and understand
|
||||
Original ARCADIA Capella uses "nested" elements (visually nested) to signify various relationships, such as "Containment relationship" or "Deployment relationship". Instead of using visually noisy arrows / graph edges. I pretty much like this approach and want to see something similar to it in this application
|
||||
|
||||
To explore the original ARCADIA Capella UI & semantics you may use web resources / web search / official and community docs. Or open the original ARCADIA Capella installed on this desktop machine for exploration
|
||||
|
||||
Your second, parallel, goal is to create a textual representation for ARCADIA, similar to SysML v2. So a user can either edit a system model using UI (graphical representation) or text. Both graphical and textual representations should be fully equivalent and have full parity. You may take inspiration from SysML v2. Both graphical and textual representations should have one overarching, concrete, unambiguous spec in reST format, similar to SysML v2 strictness
|
||||
The application should support both forms of editing
|
||||
The textual representation should be easily editable and understandble for both humans and AI
|
||||
The textual representation should be easily handled by version control tools such as Git
|
||||
The underlying semantics of the textual / graphical representation should support traceability of various development artifacts (for example - code, CAD files, electrical schematics, Docx files and anything in between)
|
||||
The textual representation editor should have syntax highlighting and linting
|
||||
|
||||
The project should also have a backend server / service that you can deploy. The backend server purpose is to give programmatic access to stored system models. So, there also should be a clear REST API for querying, editing and working with models. The purpose of the REST API is to allow automation, scripting and AI-driven workflows
|
||||
An example could be - writing custom plugins for various domain specific software (version control software, CAD software etc...) to establish traceability between development artifacts and a system model
|
||||
|
||||
The desktop application should contain built-in guide / help / tutorial with clear and concise info on modeling concepts, underlying semantics, common modeling scenarios and application features / how to use the app. It should be easy to navigate and explore
|
||||
|
||||
@Computer
|
||||
|
||||
### Semantic model / metamodel
|
||||
|
||||
Requirements:
|
||||
- Textual notation.
|
||||
- Graphical notation.
|
||||
- Constraints and calculations.
|
||||
- Quantities and units.
|
||||
- State and behavior modeling.
|
||||
- Reusable model libraries.
|
||||
- Strong, standardized specification.
|
||||
- Strong, standardized API.
|
||||
|
||||
#### Textual notation
|
||||
|
||||
Requirements:
|
||||
- Should not have visual noise and clutter.
|
||||
- Should have means to reduce cognitive load when developing system models.
|
||||
- Should be easily editable by humans. And AI agents.
|
||||
- System engineers should be able to easily develop system models (both big and small) using textual notation only.
|
||||
|
||||
### UI
|
||||
|
||||
The focus should be on reducing system engineer's cognitive load when creating / working with a system model. Regardless of the model size (big or small).
|
||||
|
||||
Long, homogeneous lists in the UI that require user to scroll far or search for a desired option for too long - is a bad design.
|
||||
|
||||
## Active issues / current guidance
|
||||
|
||||
Right now, the behavior & scenarios UI is hard to use. It contains static / uneditable diagrams, which is highly dubious. In addition, user workflow with the behavior & scenarios UI differ significantly from the other UIs - you can't edit diagrams and instead suppose to click on menus for model development
|
||||
|
||||
---
|
||||
|
||||
The current project state is nowhere near the usability of the original ARCADIA Capella (despite its downfalls) or its functionality / semantics. You should focus on that by studying original ARCADIA Capella very closely and implementing its features in a modern, ergonomic and easy to use way
|
||||
<!-- END USER-OWNED APPLICATION SPECIFICATION -->
|
||||
@@ -2,14 +2,14 @@
|
||||
|
||||
Arcadia Studio is a native Rust/Iced modeling workbench for system engineers. V2 covers Operational Analysis (OA) and System Analysis (SA), with graphical and textual editing of one typed model and a deployable Rust REST service. It is an independent implementation inspired by Arcadia and Eclipse Capella, not a complete Capella or SysML implementation.
|
||||
|
||||
The normative [language and editing contract](docs/language.rst) defines supported semantics, both representations, validation and migration. [Scope](docs/scope.md) states the boundaries. The [acceptance](docs/acceptance.md), [validation](docs/validation.md) and [current state](harness/STATE.md) records document V2 tests and native Windows/Linux Computer Use verification.
|
||||
The normative [language and editing contract](docs/language.rst) defines supported semantics, both representations, validation and migration. [Scope](docs/scope.md) states the boundaries. The [acceptance](docs/acceptance.md) and [validation](docs/validation.md) records document the earlier V2 baseline. [Current state](harness/STATE.md) and the [2026-09-06 coverage audit](harness/release-current-coverage-20260906.md) track subsequent implementation and outstanding release gates; the current first release is not yet accepted.
|
||||
|
||||
## Build and run
|
||||
|
||||
Install stable Rust and your platform's native compiler. The workspace declares Rust 1.90; the recorded development builds use Rust 1.98.1. Windows requires Visual Studio Build Tools with **Desktop development with C++**. Ubuntu/Debian development dependencies are:
|
||||
Install stable Rust and your platform's native compiler. The workspace declares Rust 1.90; the recorded development builds use Rust 1.98.1. The standard Windows MSVC path uses Visual Studio Build Tools with **Desktop development with C++**. Ubuntu/Debian development dependencies are:
|
||||
|
||||
```sh
|
||||
sudo apt-get install build-essential pkg-config libxkbcommon-dev libwayland-dev libvulkan-dev libx11-dev libxrandr-dev libxi-dev
|
||||
sudo apt-get install build-essential pkg-config libxkbcommon-dev libxkbcommon-x11-0 libwayland-dev libvulkan-dev libx11-dev libxrandr-dev libxi-dev
|
||||
```
|
||||
|
||||
From the repository root:
|
||||
@@ -18,14 +18,26 @@ From the repository root:
|
||||
cargo run --locked -p oa-desktop --bin arcadia-studio
|
||||
```
|
||||
|
||||
Build both desktop and server release executables:
|
||||
Build the desktop, server and source CLI release executables:
|
||||
|
||||
```sh
|
||||
cargo build --release --workspace --locked
|
||||
```
|
||||
|
||||
Stage the complete teaching examples beside these executables so **Home → Open water-pressure walkthrough** works in an optimized source build. From the repository root, use `Copy-Item -Recurse -Force examples target/release/` in PowerShell or `cp -R examples target/release/` on Linux. If you set a different Cargo target directory or pass `--target`, use that build's executable directory instead of `target/release`. The packaging scripts include these examples automatically.
|
||||
|
||||
Run `target/release/arcadia-studio.exe` on Windows or `./target/release/arcadia-studio` on Linux. No task-specific cache directory is required. A graphical desktop and compatible graphics driver are required; the application uses Iced 0.14 with WGPU and X11/Wayland support. It does not require Java, Eclipse, a browser, an account or a running server.
|
||||
|
||||
An optional Windows path uses the `stable-x86_64-pc-windows-gnullvm` Rust toolchain with LLVM-MinGW. Put LLVM-MinGW's `bin` directory on `PATH`, including `clang.exe` and `llvm-windres.exe`, then run:
|
||||
|
||||
```powershell
|
||||
rustup toolchain install stable-x86_64-pc-windows-gnullvm
|
||||
$env:CARGO_TARGET_X86_64_PC_WINDOWS_GNULLVM_LINKER = 'clang.exe'
|
||||
cargo +stable-x86_64-pc-windows-gnullvm build --release --workspace --locked
|
||||
```
|
||||
|
||||
GNU/gnullvm builds require a resource compiler to embed the normal-user (`asInvoker`) manifest in executables and tests. The build selects `llvm-windres` for gnullvm or `windres` for GNU; set `RC` to its executable path if it is not on `PATH`. This avoids Windows treating installer-like test filenames as elevation requests. The current machine uses user-local Rust 1.98.1 and LLVM-MinGW 20260826 UCRT; compilation and test progress are recorded in [current state](harness/STATE.md). That evidence is separate from native workflow and release-package acceptance.
|
||||
|
||||
On the tested Ubuntu 24.04/WSLg environment, Mesa's Vulkan software adapter is required:
|
||||
|
||||
```sh
|
||||
@@ -35,20 +47,39 @@ WGPU_BACKEND=vulkan VK_DRIVER_FILES=/usr/share/vulkan/icd.d/lvp_icd.x86_64.json
|
||||
|
||||
A compatible native Linux graphics adapter can use the ordinary command. This software-adapter workaround requires the indicated driver file. See the [platform verification record](docs/validation.md) for tested environments.
|
||||
|
||||
V2 release bundles are `dist/ArcadiaStudio-Windows.zip` and `dist/ArcadiaStudio-Linux.tar.gz`, with archive checksums in `dist/SHA256SUMS.txt`. Extract the bundle and run its `arcadia-studio.exe` or `./arcadia-studio`; Rust is not needed to run a packaged executable. Both bundles include the headless server, examples, specifications and deployment instructions. Linux bundles target the documented Ubuntu 24.04 runtime. Packaged executable and archive evidence is recorded in [package verification](harness/verification-v2-packages.md).
|
||||
The earlier V2 package record describes `dist/ArcadiaStudio-Windows.zip` and `dist/ArcadiaStudio-Linux.tar.gz`, with archive checksums in `dist/SHA256SUMS.txt`. Extract a verified bundle and run its `arcadia-studio.exe` or `./arcadia-studio`; Rust is not needed to run a packaged executable. Those bundles include the headless server, examples, specifications and deployment instructions; Linux targets the documented Ubuntu 24.04 runtime. [Package verification](harness/verification-v2-packages.md) applies to that recorded revision. Current changes still require fresh packages, checksums and acceptance.
|
||||
|
||||
The current [Windows packaging instructions](docs/windows-packaging.md) stage both executables, verify their runtime DLL dependencies, and produce an archive with checksums and provenance. Native acceptance fixtures and independent expected results are retained in [the release fixture directory](harness/fixtures/release1-native/README.md).
|
||||
|
||||
## Work with source files from the command line
|
||||
|
||||
The `arcadia` CLI checks an explicit `.arcadia` entry file and its includes without
|
||||
starting the desktop or server:
|
||||
|
||||
```sh
|
||||
cargo run --locked -p oa-cli --bin arcadia -- check examples/text-first/project.arcadia
|
||||
```
|
||||
|
||||
`stabilize ROOT` previews the identities needed for persistent editing;
|
||||
`rename-alias ROOT OLD NEW` previews an alias change and its references. Add
|
||||
`--write` to save that invocation's candidate, or `--json` for structured
|
||||
diagnostics and changed-file text/diffs. Preview leaves files untouched.
|
||||
See [source CLI commands](docs/source-cli.md) for examples and exit codes.
|
||||
|
||||
## Model operational needs and system responsibilities
|
||||
|
||||
The coastal rescue example combines people, an organization, a System of Interest, information and physical exchange items, normal/degraded behavior and code/CAD evidence. Choose **New** to start an empty project.
|
||||
The desktop starts at **Home**, where you can create a model, open a local project, continue recent files or recover retained work. Missing recent files stay visible with **Locate**; **Remove** only forgets their history entry. Choose **Explore rescue example** for a model combining people, an organization, a System of Interest, information and physical exchange items, normal/degraded behavior and code/CAD evidence.
|
||||
|
||||
The example opens in an architecture view with work nested inside its performers. Each layer also has dedicated functional dataflow and mission/capability views. Regenerate both example formats with matching identities using `cargo run --locked -p oa-core --example generate_demo`; the command verifies both saved models. Historical migration fixtures remain separate.
|
||||
|
||||
1. In **Operational Analysis**, create entities, actors, activities and capabilities. Use **In selected** for semantic decomposition and **Allocated** for new leaf work performed by a participant. Activities can decompose independently of their performer; roles capture shared operational responsibility.
|
||||
The architecture diagram has a compact side palette; expand it to see tool names. Choose an element tool, click its position, enter its name in place and press **Enter**. **Escape** cancels the draft. Select a card and press **F2** to rename it. Right-click a participant and choose **Add activity** or **Add function** to create work with its performer allocation in one undoable edit. Ordinary palette creation leaves work unallocated. **Add existing** places a compatible model element in the current view; **Include already shown** offers **Locate** for existing placements.
|
||||
|
||||
1. In **Operational Analysis**, create entities, actors, activities and capabilities. Use **In selected** for semantic decomposition and **Allocated** for new leaf work performed by a participant. Activities can decompose independently of their performer; roles capture shared operational responsibility. **Communication means** connects operational Entities or Actors directly, with direction and carried items; **Exchange allocation** associates the Interactions it carries. Operational communication requires no system ports.
|
||||
2. Switch to **System Analysis**. Define one System of Interest and external Actors, then functions, missions, capabilities and functional chains. The system boundary has no internal LA/PA components in this version.
|
||||
3. Select a System or System Actor and choose **Add port** in the browser or Properties. Choose Standard or Flow, then **Create port**. Use **Boundary exchange** in the diagram palette, or **Draw boundary exchange** on a selected visible source port, to connect compatible component ports directly. Create the other participant's matching port first if none exists. Functions expose separate input/output port actions; the **Functional exchange** palette tool connects them. **Actions** exposes other engineering relationships and off-diagram configuration; **Data & interfaces** holds reusable payloads and contracts.
|
||||
4. Create focused views. **Containment** nests semantic children; **Architecture · allocated work** nests work within performers; **Functional dataflow** shows work decomposition and exchanges; **Missions & capabilities** shows objectives and participation. Dashed, italic parent work denotes an allocation summary inferred from its leaves. Ports appear on their owner's boundary. Placement dragging changes geometry. **Hide** removes a placement; **Delete from model** removes semantics and dependent references. Use **Placement** and **View properties** for exact values.
|
||||
5. In **Behavior & scenarios**, author processes/chains, scenario lifelines and ordered occurrences, including repeated uses of the same exchange and explicit fragments/branches. Select a State machine and choose **Create diagram** to place its existing regions and states/modes in a saved view. State machines also support availability and state-action links. Conditions are descriptive, not executable simulation code. Behavior and Data authoring preserve your other diagram layouts.
|
||||
6. Select an OA or SA element and choose **Create / update counterpart**. Review dependency scope and counterpart choices, then apply one undoable transaction. Existing counterparts retain their structural choices; reviewed updates compare names/descriptions. Manual traces link other engineering correspondences. **Traceability** also edits artifact URI, revision and fragment metadata.
|
||||
4. Create focused views. **Containment** nests semantic children; **Architecture · allocated work** nests work within performers; **Functional dataflow** shows work decomposition and exchanges; **Missions & capabilities** shows objectives and participation. Dashed, italic parent work denotes an allocation summary inferred from its leaves. Ports appear on their owner's boundary. **View properties** stages saved line-kind, category, behavior-coverage, context, label and individual-hide choices. Right-click empty diagram space for **Duplicate view**, retaining the same semantic records in an independent presentation. Placement **Hide** removes a placement; line hiding retains its relationship; **Delete from model** removes semantics and dependent references.
|
||||
5. In **Behavior & scenarios**, choose **New**, select Operational process (OA), Functional chain (SA), Scenario or State machine, then enter its name. For a scenario, choose what its lifelines represent; **Add optional context…** links a context without changing its layer-root ownership. For a state machine, search for its existing participant owner; optionally select **Create the first state view**. Choose **Create and open** to start authoring work contributions, lifelines, ordered occurrences or states. **Cancel · Esc** discards the creation draft; if another dialog is open, Escape dismisses that dialog first. Creation and its optional first view form one Undo operation. A new state machine starts without regions or states; **Create diagram** can later place its existing contents in a saved view. Behavior supports repeated exchanges, fragments/branches, availability and state-action links. Conditions are descriptive, not executable simulation code. Behavior and Data authoring preserve your other diagram layouts.
|
||||
6. Select an OA or SA element and choose **Create / update counterpart**. Review dependency scope and counterpart choices, then apply one undoable transaction. For an existing trace, **Review semantics…** compares typed content and prior observations, with explicit keep, take or final-value decisions for supported structural, scalar, constructor, individual-row and ordered-collection changes. Open additional trace rows and choose **Include this row** to combine reviewed source contributions into one validated Apply/Undo transaction; conflicting decisions require resolution. Review does not automatically synchronize the perspectives. **Attachments** reviews an existing child’s parent or a relationship endpoint. **Artifact links** reviews metadata, owner moves, explicit source-absence deletion and creation of a reserved counterpart after all introduced metadata is reviewed. These controls have automated coverage; their native acceptance remains pending. Manual traces link other engineering correspondences. **Traceability** also edits artifact URI, revision and fragment metadata.
|
||||
7. Review **Model checks**, then save `.arcadia` source or `.json`. Warnings allow incomplete authoring; structural errors preserve the committed model and rejected draft.
|
||||
|
||||
**Model explorer** groups roots by engineering purpose and opens one container's direct children. Breadcrumbs navigate ownership; **Allocated work** is listed separately. Search names, kinds or `@aliases` to find elements with ancestor context. Results are paged in groups of 100. **Collapse all** folds the outline; **Locate** clears the filter and reveals the selected element's ancestry.
|
||||
@@ -57,7 +88,9 @@ The example opens in an architecture view with work nested inside its performers
|
||||
|
||||
The inspector exposes typed properties, references, ordered lists, aliases and UUID identity. Applying or navigating away attempts to commit the draft; invalid values remain editable. **Escaped strings (advanced)** uses quoted JSON escapes for exact tabs, line breaks and carriage returns, for example `"First\nSecond"`. UUID changes atomically update dependent references. Accepted model/source history retains up to 100 edits within an estimated 32 MiB history budget.
|
||||
|
||||
Choose **Interaction**, **Functional exchange** or **Boundary exchange** in the diagram palette, then click the source and a highlighted compatible target, or drag between them. Functional exchanges use output/input ports; function cards create or reuse real ports atomically. Boundary exchanges use compatible component ports. Middle-button drag pans without losing the chosen source; arrow keys also pan while drawing with the canvas focused. Click empty space to restart, or Escape to cancel. Each completed connection is one model/source history operation; edit its name and carried items in Properties.
|
||||
Choose **Interaction**, **Communication means**, **Functional exchange** or **Boundary exchange** in the diagram palette, then click the source and a highlighted compatible target, or drag between them. Communication means use OA participants directly. Functional exchanges use output/input ports; function cards create or reuse real ports atomically. Boundary exchanges use compatible component ports. Middle-button drag pans without losing the chosen source; arrow keys also pan while drawing with the canvas focused. Click empty space to restart, or Escape to cancel. Each completed connection is one model/source history operation; edit its name and carried items in Properties.
|
||||
|
||||
Create named **Exchange categories** at the perspective root to group Work exchanges or Participant exchanges. In **View properties**, each family defaults to All, including uncategorized exchanges. Selected categories combine by union; an explicit empty selection shows none of that family. Coverage and selected process/chain/scenario contexts intersect with category choices. Explicit hides survive changes to categories and labels. These settings change the saved presentation, not model relationships or node geometry. The [native record](harness/release-current-native-verification.md) covers the source-6 batch crash-recovery/Apply/Undo/Redo flow and a scoped forty-exchange view, including filtering, duplication, hiding and reopening. Communication authoring, remaining view combinations and latest attachment/artifact native acceptance remain pending.
|
||||
|
||||
In **Select / move**, drag cards on a 10-unit grid, drag empty space to pan, and scroll to zoom. Drag ports along their owner's border or onto any of its four sides. Automatic sides account for direction and visible connections. Manual positions are per diagram and remain relative to the owner through movement or resize; right-click **Reset automatic position** restores automatic placement. **Arrange** changes the current view layout; **Fit** frames its projected bounds. SVG exports the current architecture diagram as a view, not an editable model file.
|
||||
|
||||
@@ -69,10 +102,12 @@ In the state view, **Select / move** drags vertices and containers without repar
|
||||
|
||||
## Edit the same model as text
|
||||
|
||||
For a short text-only start, open [the distress-response model](examples/text-first/project.arcadia) and follow [its three-step walkthrough](examples/text-first/README.md). Four declarations and three explicit relationships describe participants, work, responsibility and an exchange; no diagram or handwritten UUID is needed.
|
||||
|
||||
**Textual model** has a source-file folder tree, per-file drafts, syntax highlighting, live linting and explicit **Apply all**. Collapse/Locate navigate the hierarchy; collapsed folders retain draft and diagnostic indicators. Right-click a file for contextual actions. Projects can use relative includes to organize source into files. For example:
|
||||
|
||||
```text
|
||||
arcadia 4;
|
||||
arcadia 7;
|
||||
project harbor "Harbor assistance" {
|
||||
oa_entity control "Harbor control" {}
|
||||
oa_activity respond "Respond to requests" {
|
||||
@@ -102,9 +137,13 @@ Reparenting a nested element through Properties moves its declaration, descendan
|
||||
|
||||
## Save and reopen
|
||||
|
||||
Ctrl+S saves, Ctrl+Shift+S saves as, and Ctrl+O opens. An `.arcadia` suffix selects text; other suffixes select JSON. Opening detects content rather than relying on the filename. Windows uses native dialogs; Linux uses a path-entry dialog with overwrite confirmation and no portal requirement.
|
||||
Ctrl+S saves to the current local or hosted destination, Ctrl+Shift+S opens Save as, and Ctrl+O opens a local file. An `.arcadia` suffix selects text; other suffixes select JSON. Opening detects content rather than relying on the filename. Windows uses native dialogs; Linux uses a path-entry dialog with overwrite confirmation and no portal requirement.
|
||||
|
||||
**Save all** validates a snapshot and saves the source bundle, comparing previously read dependency bytes to reject detected external changes. Each file is replaced atomically; a staged transaction journal allows explicit recovery of interrupted multi-file saves. This is not an atomic multi-file filesystem operation or distributed locking. If recovery is needed, **Recover interrupted save** appears in Textual model. Dirty New/Open/Close operations offer save/discard/cancel. There is no periodic autosave of unsaved edits. Share or commit the entry file and all included source files together.
|
||||
**Save all** validates a snapshot and saves the source bundle, comparing previously read dependency bytes to reject detected external changes. Each file is replaced atomically; a staged transaction journal allows explicit recovery of interrupted multi-file saves. This is not an atomic multi-file filesystem operation or distributed locking. If recovery is needed, **Recover interrupted save** appears in Textual model. Dirty New/Open/Close operations offer save/discard/cancel. Share or commit the entry file and all included source files together.
|
||||
|
||||
While work is unsaved, the desktop attempts a private recovery checkpoint every 10 seconds. It retains the accepted source bundle, raw source buffers, supported pending property/behavior forms and workflow drafts, including rejected input and semantic-review choices. **Home → Recover** opens an unsaved copy with no local or hosted save destination; use **Save as** to choose one. Undo/redo history is not restored. Checkpoints never write model files or save to the server, and credentials are excluded. A failed checkpoint is reported on Home; recent edits since the last completed checkpoint may be unavailable after a crash. Local history and checkpoints live under `%LOCALAPPDATA%/ArcadiaStudio` on Windows or `$XDG_DATA_HOME/arcadia-studio` (otherwise `~/.local/share/arcadia-studio`) on Linux. Explicit saves and version control remain the durable record.
|
||||
|
||||
The [current Windows native record](harness/release-current-native-verification.md) verifies scoped Home/recents workflows and forced-stop recovery of raw invalid source, invalid UUID properties, a pending timed transition, keyed semantic choices and a retained rejected order draft. Accepted repairs were saved and compared with independent source oracles, including exact Undo/Redo cases. It also records the older binary's transient journal-publication failure; the bounded fix has automated evidence in the [journal review](harness/release-journal-publication-review-20260906.md) and awaits new-binary native verification. Subsequent source-6 batch recovery and exact Apply/Save/Undo/Redo comparisons are recorded there too. These results do not accept all recovery variants, latest attachment/artifact workflows, Linux or the complete release.
|
||||
|
||||
## REST service and external tools
|
||||
|
||||
@@ -118,19 +157,25 @@ The default is `127.0.0.1:8787`, with a platform-local data directory. `--data-d
|
||||
|
||||
The API queries and edits complete models, canonical source, multi-file source projects, elements, relationships, artifacts and traces. Transactions and transition previews use the same core validation and source writer as the desktop. Writes require the returned ETag in `If-Match`. One revision protects the accepted model and source bundle together, including comment-only edits. The server retains the current revision only.
|
||||
|
||||
Desktop files and hosted resources transfer explicitly; the desktop has no direct server connection. Use **Save as** to export `system.json`, import it, then edit using the API. The model interchange endpoint accepts a complete JSON model or standalone canonical source:
|
||||
Use **Hosted models...** in the desktop top bar to connect, **Publish as new** to upload the current authored source project, or select a catalog entry and choose **Open selected**. Diagrams, properties and text share the same local editing history. **Save to server** / Ctrl+S explicitly sends valid changes; invalid drafts and failed writes retain your work. A revision conflict preserves local work and checks the server for review, with read-only source files and an explicit, undoable **Reload server version**. **Save as local...** switches back to a local destination after successfully saving an `.arcadia` source project; JSON export keeps the hosted destination. See the [hosted desktop walkthrough](docs/server.md#edit-hosted-models-in-the-desktop) for conflict recovery and connection setup.
|
||||
|
||||
The desktop keeps bearer credentials in memory and accepts HTTPS, with HTTP allowed only on localhost/loopback. Hosted editing does not require a cloud account and does not provide automatic synchronization or merges.
|
||||
|
||||
Scripts can also import a complete JSON model or standalone canonical source through the model interchange endpoint:
|
||||
|
||||
```sh
|
||||
curl --fail-with-body -X POST http://127.0.0.1:8787/api/v1/projects/import \
|
||||
-H 'Content-Type: application/json' --data-binary @system.json
|
||||
```
|
||||
|
||||
The response supplies the service `resource_id` and ETag. After API changes, export `/api/v1/projects/<resource-id>/source` to a new `.arcadia` file and open it in the desktop. This preserves model UUIDs, aliases, diagrams, traces and artifact metadata. Importing creates a separate hosted resource. Artifact URIs and revisions are opaque references for code, CAD, schematics, documents and other evidence; the application does not fetch or execute them.
|
||||
The response supplies the service `resource_id` and ETag. Refresh the desktop catalog to open that resource; after API changes to an open model, use **Check server** to review them. Alternatively, export `/api/v1/projects/<resource-id>/source` to a new `.arcadia` file for local interchange. This preserves model UUIDs, aliases, diagrams, traces and artifact metadata. Importing creates a separate hosted resource. Artifact URIs and revisions are opaque references for code, CAD, schematics, documents and other evidence; the application does not fetch or execute them.
|
||||
|
||||
To preserve authored files and comments, use `POST /api/v1/projects/import-source-project` with a JSON bundle containing `entry` and a `files` map of relative paths to source strings. `GET` and conditional `PUT /api/v1/projects/<resource-id>/source-project` exchange that complete accepted bundle. Include resolution uses only the submitted files; the server never opens the client's disk paths. See the [REST contract](docs/api.rst) for payloads, located diagnostics and admission limits.
|
||||
|
||||
## Development
|
||||
|
||||
Source7 integration adds caller-qualified reusable-process links and explicit interface-operation identity. Its [contract decision](harness/release-source7-integration-decision-20260906.md) and [current state](harness/STATE.md) distinguish prepared code from tested behavior. Current OpenAPI validation passes72structural fixtures across204schemas; source7 core, desktop, HTTP, recovery and native acceptance remain separate gates. Earlier source6 Windows and Linux results retain their exact recorded revision scope. Final full suites, strict checks, optimized/MSRV builds and current release packages are still required.
|
||||
|
||||
```sh
|
||||
cargo fmt --all -- --check
|
||||
cargo clippy --workspace --all-targets --locked -- -D warnings
|
||||
@@ -142,4 +187,4 @@ cargo build --release --workspace --locked
|
||||
- `crates/oa-desktop`: Iced state/drafts, typed forms, architecture/behavior views, source highlighting and file workflows.
|
||||
- `crates/oa-server`: REST transport, conditional writes, bounded queries and atomic local store.
|
||||
|
||||
The [architecture guide](docs/architecture.md) explains extension boundaries. Windows/Linux CI is configured; remote CI was not run in this environment. LA/PA, simulation, native Capella interchange, complete SysML/Capella conformance, direct hosted editing, semantic merge tooling and production-scale collaboration remain outside this prototype.
|
||||
The [architecture guide](docs/architecture.md) explains extension boundaries. Windows/Linux CI is configured; remote CI was not run in this environment. LA/PA, simulation, native Capella interchange, complete SysML/Capella conformance, semantic merge tooling and production-scale collaboration remain outside this prototype.
|
||||
|
||||
@@ -0,0 +1,8 @@
|
||||
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
|
||||
<assembly xmlns="urn:schemas-microsoft-com:asm.v1" manifestVersion="1.0">
|
||||
<trustInfo xmlns="urn:schemas-microsoft-com:asm.v3">
|
||||
<security><requestedPrivileges>
|
||||
<requestedExecutionLevel level="asInvoker" uiAccess="false"/>
|
||||
</requestedPrivileges></security>
|
||||
</trustInfo>
|
||||
</assembly>
|
||||
@@ -0,0 +1 @@
|
||||
1 24 "windows.manifest"
|
||||
@@ -0,0 +1,35 @@
|
||||
// GNU Windows linkers need an explicit normal-user manifest, including tests
|
||||
// named "updates", to avoid Windows installer detection. No elevation is needed.
|
||||
fn main() {
|
||||
println!("cargo:rerun-if-changed=../../build/windows_manifest.rs");
|
||||
println!("cargo:rerun-if-changed=../../build/windows.manifest");
|
||||
println!("cargo:rerun-if-changed=../../build/windows.rc");
|
||||
println!("cargo:rerun-if-env-changed=RC");
|
||||
let target = std::env::var("TARGET").unwrap_or_default();
|
||||
if !target.ends_with("windows-gnu") && !target.ends_with("windows-gnullvm") {
|
||||
return;
|
||||
}
|
||||
let root = std::path::PathBuf::from(std::env::var_os("CARGO_MANIFEST_DIR").unwrap())
|
||||
.join("../../build");
|
||||
let object = std::path::PathBuf::from(std::env::var_os("OUT_DIR").unwrap())
|
||||
.join("normal-user-manifest.o");
|
||||
let compiler = std::env::var_os("RC").unwrap_or_else(|| {
|
||||
if target.ends_with("gnullvm") {
|
||||
"llvm-windres"
|
||||
} else {
|
||||
"windres"
|
||||
}
|
||||
.into()
|
||||
});
|
||||
let result = std::process::Command::new(compiler)
|
||||
.current_dir(root)
|
||||
.args(["-i", "windows.rc", "-O", "coff", "-o"])
|
||||
.arg(&object)
|
||||
.status()
|
||||
.expect("Windows GNU resource compiler is required (set RC if not on PATH)");
|
||||
assert!(
|
||||
result.success(),
|
||||
"Cannot compile the normal-user Windows manifest"
|
||||
);
|
||||
println!("cargo:rustc-link-arg={}", object.display());
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
[package]
|
||||
name = "oa-cli"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
rust-version.workspace = true
|
||||
|
||||
[[bin]]
|
||||
name = "arcadia"
|
||||
path = "src/main.rs"
|
||||
|
||||
[dependencies]
|
||||
oa-core = { path = "../oa-core" }
|
||||
serde.workspace = true
|
||||
serde_json.workspace = true
|
||||
@@ -0,0 +1,451 @@
|
||||
//! Source-only authoring. Preparation captures bytes; only core owns disk writes.
|
||||
use oa_core::{
|
||||
Command, language,
|
||||
persistence::MigrationReport,
|
||||
prepare_command,
|
||||
source_files::{self, DiskProject, SourceFileError},
|
||||
source_project::{self, CompiledSourceProject, ProjectLimits, SourceDiagnostic},
|
||||
validation::Severity,
|
||||
};
|
||||
use serde::Serialize;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
pub const LIMITS: ProjectLimits = ProjectLimits {
|
||||
max_files: 256,
|
||||
max_include_depth: 32,
|
||||
max_include_edges: 1024,
|
||||
model: language::ParseLimits {
|
||||
max_source_bytes: 64 * 1024 * 1024,
|
||||
max_graph_objects: 100_000,
|
||||
max_records: 250_000,
|
||||
max_step_references: 500_000,
|
||||
},
|
||||
};
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub enum Operation {
|
||||
Check,
|
||||
Stabilize,
|
||||
RenameAlias { old: String, new: String },
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
pub struct Location {
|
||||
pub path: String,
|
||||
/// Half-open UTF-8 byte offsets. Line/column are one-based Unicode scalars.
|
||||
pub start: usize,
|
||||
pub end: usize,
|
||||
pub line: Option<usize>,
|
||||
pub column: Option<usize>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
pub struct Diagnostic {
|
||||
pub severity: String,
|
||||
pub code: String,
|
||||
pub message: String,
|
||||
pub coordinate_space: String,
|
||||
pub location: Option<Location>,
|
||||
pub related: Vec<Location>,
|
||||
pub object_id: Option<String>,
|
||||
pub field: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
pub struct Change {
|
||||
pub path: String,
|
||||
/// Exact captured and proposed UTF-8 text, including line endings.
|
||||
pub before: String,
|
||||
pub after: String,
|
||||
pub diff: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize)]
|
||||
pub struct Report {
|
||||
pub format_version: u32,
|
||||
pub entry: String,
|
||||
pub operation: String,
|
||||
pub status: String,
|
||||
pub exit_code: u8,
|
||||
/// True only after a successful changed save. False on failure does not
|
||||
/// promise rollback: consult the specific error/recovery outcome.
|
||||
pub written: bool,
|
||||
pub diagnostics: Vec<Diagnostic>,
|
||||
pub changes: Vec<Change>,
|
||||
pub identities_to_stabilize: usize,
|
||||
pub migration: Option<MigrationReport>,
|
||||
pub notes: Vec<String>,
|
||||
}
|
||||
|
||||
impl Report {
|
||||
pub fn failure(
|
||||
entry: &Path,
|
||||
operation: &str,
|
||||
exit_code: u8,
|
||||
code: &str,
|
||||
message: String,
|
||||
) -> Self {
|
||||
let mut report = Self::empty(entry, operation);
|
||||
report.fail(exit_code, code, message);
|
||||
report
|
||||
}
|
||||
|
||||
fn empty(entry: &Path, operation: &str) -> Self {
|
||||
Self {
|
||||
format_version: 1,
|
||||
entry: entry.to_string_lossy().into_owned(),
|
||||
operation: operation.into(),
|
||||
status: "checked".into(),
|
||||
exit_code: 0,
|
||||
written: false,
|
||||
diagnostics: vec![],
|
||||
changes: vec![],
|
||||
identities_to_stabilize: 0,
|
||||
migration: None,
|
||||
notes: vec![],
|
||||
}
|
||||
}
|
||||
|
||||
fn fail(&mut self, exit_code: u8, code: &str, message: String) {
|
||||
self.status = "rejected".into();
|
||||
self.exit_code = exit_code;
|
||||
self.diagnostics.push(Diagnostic {
|
||||
severity: "error".into(),
|
||||
code: code.into(),
|
||||
message,
|
||||
coordinate_space: "operation".into(),
|
||||
location: None,
|
||||
related: vec![],
|
||||
object_id: None,
|
||||
field: None,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
fn located(issue: SourceDiagnostic, space: &str) -> Diagnostic {
|
||||
let d = issue.diagnostic;
|
||||
Diagnostic {
|
||||
severity: match d.severity {
|
||||
Severity::Error => "error",
|
||||
Severity::Warning => "warning",
|
||||
}
|
||||
.into(),
|
||||
code: d.code,
|
||||
message: d.message,
|
||||
coordinate_space: space.into(),
|
||||
location: Some(Location {
|
||||
path: issue.path,
|
||||
start: d.span.start,
|
||||
end: d.span.end,
|
||||
line: Some(d.line),
|
||||
column: Some(d.column),
|
||||
}),
|
||||
related: issue
|
||||
.related
|
||||
.into_iter()
|
||||
.map(|at| Location {
|
||||
path: at.path,
|
||||
start: at.span.start,
|
||||
end: at.span.end,
|
||||
line: None,
|
||||
column: None,
|
||||
})
|
||||
.collect(),
|
||||
object_id: d.object_id.map(|id| id.to_string()),
|
||||
field: d.field,
|
||||
}
|
||||
}
|
||||
|
||||
fn disk_error(report: &mut Report, error: SourceFileError) {
|
||||
let code = match &error {
|
||||
SourceFileError::Conflict(_) => "external_change",
|
||||
SourceFileError::RecoveryRequired(_) => "recovery_required",
|
||||
SourceFileError::RecoveryFailed { .. } => "recovery_failed",
|
||||
SourceFileError::Path(_) => "unsafe_path",
|
||||
SourceFileError::Limit(_) => "source_limit",
|
||||
SourceFileError::UnknownExpectation(_) => "unknown_disk_expectation",
|
||||
SourceFileError::Invalid(_) => "invalid_save_candidate",
|
||||
SourceFileError::Io { .. } => "io_error",
|
||||
};
|
||||
report.fail(3, code, error.to_string());
|
||||
}
|
||||
|
||||
/// A candidate owns its original expectations and is consumed by saving.
|
||||
/// Callers cannot replace its source/model/expectations after preparation.
|
||||
pub struct Prepared {
|
||||
report: Report,
|
||||
snapshot: DiskProject,
|
||||
compiled: CompiledSourceProject,
|
||||
mutable: bool,
|
||||
}
|
||||
|
||||
impl Prepared {
|
||||
pub fn report(&self) -> &Report {
|
||||
&self.report
|
||||
}
|
||||
|
||||
pub fn into_report(self) -> Report {
|
||||
self.report
|
||||
}
|
||||
|
||||
pub fn write(mut self) -> Report {
|
||||
if !self.mutable {
|
||||
self.report
|
||||
.fail(2, "usage", "check/lint does not accept --write".into());
|
||||
return self.report;
|
||||
}
|
||||
match source_files::save_project(&self.snapshot, &self.compiled, LIMITS) {
|
||||
Ok(_) => {
|
||||
self.report.written = !self.report.changes.is_empty();
|
||||
self.report.status = if self.report.written {
|
||||
"written"
|
||||
} else {
|
||||
"unchanged"
|
||||
}
|
||||
.into();
|
||||
}
|
||||
Err(error) => disk_error(&mut self.report, error),
|
||||
}
|
||||
self.report
|
||||
}
|
||||
}
|
||||
|
||||
pub fn prepare(entry: &Path, operation: Operation) -> Result<Prepared, Box<Report>> {
|
||||
let name = match operation {
|
||||
Operation::Check => "check",
|
||||
Operation::Stabilize => "stabilize",
|
||||
Operation::RenameAlias { .. } => "rename-alias",
|
||||
};
|
||||
let mut report = Report::empty(entry, name);
|
||||
let snapshot = source_files::load_project(entry, LIMITS).map_err(|error| {
|
||||
disk_error(&mut report, error);
|
||||
Box::new(report.clone())
|
||||
})?;
|
||||
let raw = snapshot.reachable_bundle();
|
||||
// The loader may include warnings from stabilized compilation. Only its
|
||||
// discovery/IO diagnostics are authoritative on the original bytes.
|
||||
let mut diagnostics: Vec<_> = snapshot
|
||||
.diagnostics
|
||||
.iter()
|
||||
.filter(|d| {
|
||||
matches!(
|
||||
d.diagnostic.code.as_str(),
|
||||
"pending_save"
|
||||
| "source_encoding"
|
||||
| "source_limit"
|
||||
| "invalid_path"
|
||||
| "missing_include"
|
||||
| "project_limit"
|
||||
)
|
||||
})
|
||||
.cloned()
|
||||
.collect();
|
||||
for diagnostic in source_project::lint_bundle(&raw, LIMITS) {
|
||||
if !diagnostics.contains(&diagnostic) {
|
||||
diagnostics.push(diagnostic);
|
||||
}
|
||||
}
|
||||
let disk_refusal = snapshot.diagnostics.iter().any(|d| {
|
||||
matches!(
|
||||
d.diagnostic.code.as_str(),
|
||||
"pending_save" | "missing_include" | "invalid_path"
|
||||
)
|
||||
});
|
||||
let invalid = diagnostics
|
||||
.iter()
|
||||
.any(|d| d.diagnostic.severity == Severity::Error);
|
||||
report.diagnostics = diagnostics
|
||||
.into_iter()
|
||||
.map(|d| located(d, "input"))
|
||||
.collect();
|
||||
if invalid {
|
||||
// Do not run declaration analysis or any updater on invalid raw text.
|
||||
// Failed lint may also have allocated provisional object identities.
|
||||
for diagnostic in &mut report.diagnostics {
|
||||
diagnostic.object_id = None;
|
||||
}
|
||||
report.status = "invalid".into();
|
||||
report.exit_code = if disk_refusal { 3 } else { 1 };
|
||||
return Err(Box::new(report));
|
||||
}
|
||||
let explicit_ids: std::collections::BTreeSet<_> = raw
|
||||
.files
|
||||
.values()
|
||||
.flat_map(|text| language::analyze(text).declarations)
|
||||
.filter_map(|d| d.id.map(|id| id.to_string()))
|
||||
.collect();
|
||||
for diagnostic in &mut report.diagnostics {
|
||||
if diagnostic
|
||||
.object_id
|
||||
.as_ref()
|
||||
.is_some_and(|id| !explicit_ids.contains(id))
|
||||
{
|
||||
diagnostic.object_id = None;
|
||||
}
|
||||
}
|
||||
let mut compiled = source_project::compile_bundle(&raw, LIMITS).map_err(|diagnostics| {
|
||||
report.status = "invalid".into();
|
||||
report.exit_code = 1;
|
||||
report
|
||||
.diagnostics
|
||||
.extend(diagnostics.into_iter().map(|d| located(d, "candidate")));
|
||||
Box::new(report.clone())
|
||||
})?;
|
||||
report.identities_to_stabilize = raw
|
||||
.files
|
||||
.values()
|
||||
.map(|text| {
|
||||
language::analyze(text)
|
||||
.declarations
|
||||
.into_iter()
|
||||
.filter(|d| d.id.is_none())
|
||||
.count()
|
||||
})
|
||||
.sum();
|
||||
report.migration = compiled.decoded.migration.clone();
|
||||
let mutable = !matches!(operation, Operation::Check);
|
||||
if let Operation::RenameAlias { old, new } = operation {
|
||||
let project = &compiled.decoded.project;
|
||||
let Some((id, _)) = project
|
||||
.identities()
|
||||
.into_iter()
|
||||
.find(|(_, alias)| *alias == old)
|
||||
else {
|
||||
report.fail(
|
||||
1,
|
||||
"unknown_alias",
|
||||
format!("No declaration has alias '{old}'."),
|
||||
);
|
||||
return Err(Box::new(report));
|
||||
};
|
||||
let command = prepare_command(project, &Command::SetAlias(id, new)).map_err(|error| {
|
||||
report.fail(1, "semantic_command_rejected", error.to_string());
|
||||
Box::new(report.clone())
|
||||
})?;
|
||||
compiled = source_project::update_bundle_with_identity_map(
|
||||
&compiled,
|
||||
&command.project,
|
||||
&command.identity_map,
|
||||
LIMITS,
|
||||
)
|
||||
.map_err(|diagnostics| {
|
||||
report.status = "invalid".into();
|
||||
report.exit_code = 1;
|
||||
report
|
||||
.diagnostics
|
||||
.extend(diagnostics.into_iter().map(|d| located(d, "candidate")));
|
||||
Box::new(report.clone())
|
||||
})?;
|
||||
}
|
||||
if mutable {
|
||||
for (path, after) in &compiled.bundle.files {
|
||||
let before = raw.files.get(path).cloned().unwrap_or_default();
|
||||
if &before != after {
|
||||
report.changes.push(Change {
|
||||
path: path.clone(),
|
||||
diff: unified_diff(path, &before, after),
|
||||
before,
|
||||
after: after.clone(),
|
||||
});
|
||||
}
|
||||
}
|
||||
report.status = "preview".into();
|
||||
report.notes.push("This invocation's complete proposed changed-file texts and diffs are reported. Without --write nothing is saved; a later invocation may allocate different missing UUIDs. This is not a saved plan or a digest of unchanged dependencies.".into());
|
||||
}
|
||||
report.notes.push("Diagnostic object IDs are omitted for declarations without authored IDs; lint's temporary identities are not the candidate's identities.".into());
|
||||
report.notes.push("Disk writes use the core journal/conflict checks. This is not cross-process atomic visibility or a power-loss durability guarantee; pending saves are never implicitly recovered. A failed write may require explicit journal recovery.".into());
|
||||
Ok(Prepared {
|
||||
report,
|
||||
snapshot,
|
||||
compiled,
|
||||
mutable,
|
||||
})
|
||||
}
|
||||
|
||||
/// One bounded hunk per file: common prefix/suffix plus three context lines.
|
||||
/// Linear in input size; no quadratic LCS allocation for large modules.
|
||||
fn unified_diff(path: &str, before: &str, after: &str) -> String {
|
||||
let a: Vec<_> = before.split_inclusive('\n').collect();
|
||||
let b: Vec<_> = after.split_inclusive('\n').collect();
|
||||
let prefix = a.iter().zip(&b).take_while(|(a, b)| a == b).count();
|
||||
let suffix = a[prefix..]
|
||||
.iter()
|
||||
.rev()
|
||||
.zip(b[prefix..].iter().rev())
|
||||
.take_while(|(a, b)| a == b)
|
||||
.count();
|
||||
let start = prefix.saturating_sub(3);
|
||||
let a_end = (a.len() - suffix + 3).min(a.len());
|
||||
let b_end = (b.len() - suffix + 3).min(b.len());
|
||||
let a_start = if a_end == start { start } else { start + 1 };
|
||||
let b_start = if b_end == start { start } else { start + 1 };
|
||||
let mut out = format!(
|
||||
"--- a/{path}\n+++ b/{path}\n@@ -{a_start},{} +{b_start},{} @@\n",
|
||||
a_end - start,
|
||||
b_end - start
|
||||
);
|
||||
let mut emit = |prefix: char, line: &str| {
|
||||
out.push(prefix);
|
||||
out.push_str(line);
|
||||
if !line.ends_with('\n') {
|
||||
out.push_str("\n\\ No newline at end of file\n");
|
||||
}
|
||||
};
|
||||
for line in &a[start..prefix] {
|
||||
emit(' ', line);
|
||||
}
|
||||
for line in &a[prefix..a.len() - suffix] {
|
||||
emit('-', line);
|
||||
}
|
||||
for line in &b[prefix..b.len() - suffix] {
|
||||
emit('+', line);
|
||||
}
|
||||
for line in &a[a.len() - suffix..a_end] {
|
||||
emit(' ', line);
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
pub struct Arguments {
|
||||
pub entry: PathBuf,
|
||||
pub operation: Operation,
|
||||
pub write: bool,
|
||||
pub json: bool,
|
||||
}
|
||||
|
||||
pub const HELP: &str = "arcadia check ROOT [--json]\narcadia lint ROOT [--json]\narcadia stabilize ROOT [--write] [--json]\narcadia rename-alias ROOT OLD NEW [--write] [--json]\n\nROOT is an explicit .arcadia entry file; includes resolve relative to it.\nMutation commands preview by default. --write applies this invocation's candidate.\nMissing UUIDs in a preview are provisional until written. No canonical formatting.\nExit: 0 valid/success (engineering warnings allowed), 1 invalid source or semantic\ncommand rejection, 2 usage, 3 disk/path/conflict/pending-journal/output failure.\nNo implicit journal recovery. Limits: 64 MiB, 256 files, include depth32/edges1024,\n100000 graph objects, 250000 records, 500000 ordered references.\n";
|
||||
|
||||
pub fn arguments(args: &[std::ffi::OsString]) -> Result<Arguments, String> {
|
||||
let mut positional = Vec::new();
|
||||
let (mut write, mut json) = (false, false);
|
||||
for arg in args {
|
||||
if arg == "--write" && !write {
|
||||
write = true;
|
||||
} else if arg == "--json" && !json {
|
||||
json = true;
|
||||
} else if arg.to_string_lossy().starts_with('-') {
|
||||
return Err(format!(
|
||||
"Unknown or repeated option: {}",
|
||||
arg.to_string_lossy()
|
||||
));
|
||||
} else {
|
||||
positional.push(arg);
|
||||
}
|
||||
}
|
||||
let command = positional.first().and_then(|s| s.to_str()).unwrap_or("");
|
||||
let operation = match (command, positional.len()) {
|
||||
("check" | "lint", 2) if !write => Operation::Check,
|
||||
("stabilize", 2) => Operation::Stabilize,
|
||||
("rename-alias", 4) => Operation::RenameAlias {
|
||||
old: positional[2].to_str().ok_or("Alias must be UTF-8")?.into(),
|
||||
new: positional[3].to_str().ok_or("Alias must be UTF-8")?.into(),
|
||||
},
|
||||
_ => return Err(HELP.into()),
|
||||
};
|
||||
Ok(Arguments {
|
||||
entry: PathBuf::from(positional[1]),
|
||||
operation,
|
||||
write,
|
||||
json,
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,102 @@
|
||||
use oa_cli::{Report, arguments, prepare};
|
||||
use std::{
|
||||
io::{self, Write},
|
||||
path::Path,
|
||||
process::ExitCode,
|
||||
};
|
||||
|
||||
fn human_report(report: &Report, show_diff: bool) -> io::Result<()> {
|
||||
let mut err = io::stderr().lock();
|
||||
for d in &report.diagnostics {
|
||||
let at = d
|
||||
.location
|
||||
.as_ref()
|
||||
.map(|l| {
|
||||
format!(
|
||||
"{}:{}:{}",
|
||||
l.path,
|
||||
l.line.unwrap_or(0),
|
||||
l.column.unwrap_or(0)
|
||||
)
|
||||
})
|
||||
.unwrap_or_else(|| report.entry.clone());
|
||||
writeln!(
|
||||
err,
|
||||
"{at}: {}[{}] ({}): {}",
|
||||
d.severity, d.code, d.coordinate_space, d.message
|
||||
)?;
|
||||
}
|
||||
writeln!(
|
||||
err,
|
||||
"{}: {} file changes; {} identities to stabilize",
|
||||
report.status,
|
||||
report.changes.len(),
|
||||
report.identities_to_stabilize
|
||||
)?;
|
||||
if let Some(migration) = &report.migration {
|
||||
writeln!(
|
||||
err,
|
||||
"Source migration: schema {} → {} (separate from identity stabilization)",
|
||||
migration.from_schema, migration.to_schema
|
||||
)?;
|
||||
}
|
||||
for note in &report.notes {
|
||||
writeln!(err, "{note}")?;
|
||||
}
|
||||
if show_diff {
|
||||
let mut out = io::stdout().lock();
|
||||
for change in &report.changes {
|
||||
write!(out, "{}", change.diff)?;
|
||||
}
|
||||
out.flush()?;
|
||||
}
|
||||
err.flush()
|
||||
}
|
||||
|
||||
fn run() -> io::Result<u8> {
|
||||
let args: Vec<_> = std::env::args_os().skip(1).collect();
|
||||
if args.len() == 1 && (args[0] == "--help" || args[0] == "-h") {
|
||||
io::stdout().write_all(oa_cli::HELP.as_bytes())?;
|
||||
return Ok(0);
|
||||
}
|
||||
if args.len() == 1 && args[0] == "--version" {
|
||||
writeln!(io::stdout(), "arcadia {}", env!("CARGO_PKG_VERSION"))?;
|
||||
return Ok(0);
|
||||
}
|
||||
let json = args.iter().any(|a| a == "--json");
|
||||
let mut displayed = false;
|
||||
let report = match arguments(&args) {
|
||||
Err(error) => Report::failure(Path::new(""), "usage", 2, "usage", error),
|
||||
Ok(args) => match prepare(&args.entry, args.operation) {
|
||||
Err(report) => *report,
|
||||
Ok(prepared) => {
|
||||
if args.write {
|
||||
if !args.json {
|
||||
human_report(prepared.report(), true)?;
|
||||
displayed = true;
|
||||
}
|
||||
prepared.write()
|
||||
} else {
|
||||
prepared.into_report()
|
||||
}
|
||||
}
|
||||
},
|
||||
};
|
||||
if json {
|
||||
serde_json::to_writer_pretty(io::stdout().lock(), &report)?;
|
||||
writeln!(io::stdout())?;
|
||||
} else {
|
||||
human_report(&report, !displayed)?;
|
||||
}
|
||||
Ok(report.exit_code)
|
||||
}
|
||||
|
||||
fn main() -> ExitCode {
|
||||
match run() {
|
||||
Ok(code) => ExitCode::from(code),
|
||||
Err(error) => {
|
||||
let _ = writeln!(io::stderr(), "Output failed: {error}");
|
||||
ExitCode::from(3)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,425 @@
|
||||
use oa_cli::{LIMITS, Operation, Prepared, prepare};
|
||||
use oa_core::{Id, Project, source_files, source_project};
|
||||
use serde_json::Value;
|
||||
use std::{
|
||||
collections::BTreeMap,
|
||||
fs,
|
||||
path::{Path, PathBuf},
|
||||
process::Command,
|
||||
};
|
||||
|
||||
struct Fixture(PathBuf);
|
||||
impl Fixture {
|
||||
fn new() -> Self {
|
||||
let path = std::env::temp_dir().join(format!("arcadia-cli-test-{}", Id::new_v4()));
|
||||
fs::create_dir(&path).unwrap();
|
||||
Self(path)
|
||||
}
|
||||
fn put(&self, name: &str, text: &str) {
|
||||
let path = self.0.join(name);
|
||||
fs::create_dir_all(path.parent().unwrap()).unwrap();
|
||||
fs::write(path, text).unwrap();
|
||||
}
|
||||
fn entry(&self) -> PathBuf {
|
||||
self.0.join("project.arcadia")
|
||||
}
|
||||
fn read(&self, name: &str) -> String {
|
||||
fs::read_to_string(self.0.join(name)).unwrap()
|
||||
}
|
||||
fn prepare(&self, op: Operation) -> Prepared {
|
||||
prepare(&self.entry(), op).unwrap_or_else(|report| panic!("{report:#?}"))
|
||||
}
|
||||
fn model(&self) -> Project {
|
||||
let disk = source_files::load_project(&self.entry(), LIMITS).unwrap();
|
||||
source_project::compile_bundle(&disk.reachable_bundle(), LIMITS)
|
||||
.unwrap()
|
||||
.decoded
|
||||
.project
|
||||
}
|
||||
fn cli(&self, args: &[&str]) -> (i32, Value) {
|
||||
let mut command = Command::new(env!("CARGO_BIN_EXE_arcadia"));
|
||||
command
|
||||
.arg(args[0])
|
||||
.arg(self.entry())
|
||||
.args(&args[1..])
|
||||
.arg("--json");
|
||||
let output = command.output().unwrap();
|
||||
assert!(
|
||||
output.stderr.is_empty(),
|
||||
"{}",
|
||||
String::from_utf8_lossy(&output.stderr)
|
||||
);
|
||||
(
|
||||
output.status.code().unwrap(),
|
||||
serde_json::from_slice(&output.stdout).unwrap(),
|
||||
)
|
||||
}
|
||||
}
|
||||
impl Drop for Fixture {
|
||||
fn drop(&mut self) {
|
||||
let _ = fs::remove_dir_all(&self.0);
|
||||
}
|
||||
}
|
||||
|
||||
const SIMPLE: &str = "// 雨: authored defaults stay omitted\r\narcadia 7;\r\nproject rescue \"Rescue\" {\r\n oa_entity team \"Team\" {}\r\n}\r\n";
|
||||
|
||||
#[test]
|
||||
fn complete_alarm_example_preview_then_write_and_fixed_point() {
|
||||
let fixture = Fixture::new();
|
||||
let source = include_str!(
|
||||
"../../../harness/experiments/textual-authoring-20260911/alarm-response.arcadia"
|
||||
);
|
||||
fixture.put("project.arcadia", source);
|
||||
let (code, check) = fixture.cli(&["check"]);
|
||||
assert_eq!(code, 0);
|
||||
assert_eq!(check["diagnostics"], serde_json::json!([]));
|
||||
let (code, preview) = fixture.cli(&["stabilize"]);
|
||||
assert_eq!(code, 0);
|
||||
assert_eq!(preview["identities_to_stabilize"], 40);
|
||||
assert_eq!(preview["status"], "preview");
|
||||
assert_eq!(fixture.read("project.arcadia"), source);
|
||||
assert!(
|
||||
preview["changes"][0]["diff"]
|
||||
.as_str()
|
||||
.unwrap()
|
||||
.contains("+project alarm_response")
|
||||
);
|
||||
let (code, written) = fixture.cli(&["stabilize", "--write"]);
|
||||
assert_eq!(code, 0);
|
||||
let saved = fixture.read("project.arcadia");
|
||||
assert_eq!(written["changes"][0]["after"], saved);
|
||||
let project = fixture.model();
|
||||
assert_eq!(project.identities().len(), 40);
|
||||
let mut stripped = saved.clone();
|
||||
for (id, _) in project.identities() {
|
||||
stripped = stripped.replace(&format!(" id \"{id}\""), "");
|
||||
}
|
||||
assert_eq!(stripped, source, "only identity clauses may be inserted");
|
||||
let (code, again) = fixture.cli(&["stabilize", "--write"]);
|
||||
assert_eq!(code, 0);
|
||||
assert_eq!(again["changes"], serde_json::json!([]));
|
||||
assert_eq!(again["status"], "unchanged");
|
||||
assert_eq!(fixture.model(), project);
|
||||
assert_eq!(fixture.read("project.arcadia"), saved);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn captured_candidate_exact_write_preserves_crlf_comments_and_noop_metadata() {
|
||||
let fixture = Fixture::new();
|
||||
fixture.put("project.arcadia", SIMPLE);
|
||||
let candidate = fixture.prepare(Operation::Stabilize);
|
||||
let expected = candidate.report().changes[0].after.clone();
|
||||
assert_eq!(candidate.report().identities_to_stabilize, 2);
|
||||
assert_eq!(fixture.read("project.arcadia"), SIMPLE);
|
||||
assert_eq!(candidate.write().exit_code, 0);
|
||||
assert_eq!(fixture.read("project.arcadia"), expected);
|
||||
assert!(expected.contains("// 雨: authored defaults stay omitted\r\n"));
|
||||
assert!(!expected.contains("description"));
|
||||
let metadata = fs::metadata(fixture.entry()).unwrap().modified().unwrap();
|
||||
let report = fixture.prepare(Operation::Stabilize).write();
|
||||
assert_eq!(report.status, "unchanged");
|
||||
assert!(!report.written);
|
||||
assert_eq!(
|
||||
fs::metadata(fixture.entry()).unwrap().modified().unwrap(),
|
||||
metadata
|
||||
);
|
||||
assert_eq!(fs::read_dir(&fixture.0).unwrap().count(), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn alias_rename_across_modules_changes_only_live_tokens_and_retains_all_identity() {
|
||||
let fixture = Fixture::new();
|
||||
fixture.put("project.arcadia", "arcadia 7; project rescue \"Rescue\" { include \"participants.arcadia\"; include \"work.arcadia\"; }\n");
|
||||
fixture.put(
|
||||
"participants.arcadia",
|
||||
"// @team is quoted documentation\noa_entity team \"Team @team\" {}\n",
|
||||
);
|
||||
fixture.put("work.arcadia", "oa_activity assess \"Assess\" {}\noa_activity report \"Report\" {}\nallocation assigned \"Assigned\" { source @team; target @assess; }\ninteraction transfer \"Transfer\" { source @assess; target @report; }\n");
|
||||
assert_eq!(fixture.prepare(Operation::Stabilize).write().exit_code, 0);
|
||||
let before = fixture.model();
|
||||
let original: BTreeMap<_, _> = ["project.arcadia", "participants.arcadia", "work.arcadia"]
|
||||
.into_iter()
|
||||
.map(|p| (p, fixture.read(p)))
|
||||
.collect();
|
||||
let team = before
|
||||
.identities()
|
||||
.into_iter()
|
||||
.find(|(_, alias)| *alias == "team")
|
||||
.unwrap()
|
||||
.0;
|
||||
let candidate = fixture.prepare(Operation::RenameAlias {
|
||||
old: "team".into(),
|
||||
new: "rescue_team".into(),
|
||||
});
|
||||
assert_eq!(candidate.report().changes.len(), 2);
|
||||
assert_eq!(fixture.model(), before, "preview cannot mutate");
|
||||
assert_eq!(candidate.write().exit_code, 0);
|
||||
let mut expected = before;
|
||||
expected.elements.get_mut(&team).unwrap().alias = "rescue_team".into();
|
||||
assert_eq!(fixture.model(), expected);
|
||||
assert_eq!(fixture.read("project.arcadia"), original["project.arcadia"]);
|
||||
assert_eq!(
|
||||
fixture.read("participants.arcadia"),
|
||||
original["participants.arcadia"].replacen("oa_entity team ", "oa_entity rescue_team ", 1)
|
||||
);
|
||||
assert_eq!(
|
||||
fixture.read("work.arcadia"),
|
||||
original["work.arcadia"].replace("source @team;", "source @rescue_team;")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn invalid_unicode_raw_edit_is_located_and_never_stabilized_or_written() {
|
||||
let fixture = Fixture::new();
|
||||
let raw = "arcadia 7; project p \"雨\" {\n oa_activity a \"A\" {}\n allocation alloc \"Alloc\" { source @missing; target @a; }\n}\n";
|
||||
fixture.put("project.arcadia", raw);
|
||||
for command in [
|
||||
vec!["check"],
|
||||
vec!["stabilize", "--write"],
|
||||
vec!["rename-alias", "a", "b", "--write"],
|
||||
] {
|
||||
let (code, report) = fixture.cli(&command);
|
||||
assert_eq!(code, 1);
|
||||
assert_eq!(fixture.read("project.arcadia"), raw);
|
||||
let diagnostics = report["diagnostics"].as_array().unwrap();
|
||||
assert!(!diagnostics.is_empty());
|
||||
for d in diagnostics {
|
||||
assert_eq!(d["coordinate_space"], "input");
|
||||
let at = &d["location"];
|
||||
let start = at["start"].as_u64().unwrap() as usize;
|
||||
assert!(raw.is_char_boundary(start));
|
||||
assert_eq!(
|
||||
at["line"].as_u64().unwrap() as usize,
|
||||
raw[..start].bytes().filter(|b| *b == b'\n').count() + 1
|
||||
);
|
||||
let line = raw[..start]
|
||||
.rsplit_once('\n')
|
||||
.map_or(&raw[..start], |(_, tail)| tail);
|
||||
assert_eq!(
|
||||
at["column"].as_u64().unwrap() as usize,
|
||||
line.chars().count() + 1
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn missing_id_warning_uses_raw_location_and_never_exposes_ephemeral_lint_id() {
|
||||
let fixture = Fixture::new();
|
||||
let raw = "arcadia 7;\nproject p \"雨\" {\n oa_activity work \"Work\" {}\n}\n";
|
||||
fixture.put("project.arcadia", raw);
|
||||
let (code, result) = fixture.cli(&["lint"]);
|
||||
assert_eq!(code, 0, "engineering warnings do not reject admission");
|
||||
let warning = result["diagnostics"]
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.find(|d| d["code"] == "work_without_behavior_context")
|
||||
.unwrap();
|
||||
assert_eq!(warning["severity"], "warning");
|
||||
assert_eq!(
|
||||
warning["location"]["start"],
|
||||
raw.find("oa_activity").unwrap()
|
||||
);
|
||||
assert_eq!(warning["location"]["line"], 3);
|
||||
assert_eq!(warning["location"]["column"], 5);
|
||||
assert!(warning["object_id"].is_null());
|
||||
assert_eq!(fixture.read("project.arcadia"), raw);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn captured_dependency_change_refuses_all_writes_even_on_noop() {
|
||||
let fixture = Fixture::new();
|
||||
fixture.put("project.arcadia", SIMPLE);
|
||||
let pending = fixture.prepare(Operation::Stabilize);
|
||||
let external = format!("{SIMPLE}// editor changed this\n");
|
||||
fixture.put("project.arcadia", &external);
|
||||
let result = pending.write();
|
||||
assert_eq!(result.exit_code, 3);
|
||||
assert_eq!(result.diagnostics.last().unwrap().code, "external_change");
|
||||
assert_eq!(fixture.read("project.arcadia"), external);
|
||||
assert_eq!(fixture.prepare(Operation::Stabilize).write().exit_code, 0);
|
||||
let noop = fixture.prepare(Operation::Stabilize);
|
||||
assert!(noop.report().changes.is_empty());
|
||||
let latest = format!("{}// another edit\n", fixture.read("project.arcadia"));
|
||||
fixture.put("project.arcadia", &latest);
|
||||
assert_eq!(noop.write().exit_code, 3);
|
||||
assert_eq!(fixture.read("project.arcadia"), latest);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn pending_journal_refuses_read_preview_and_write_without_recovery() {
|
||||
let fixture = Fixture::new();
|
||||
fixture.put("project.arcadia", SIMPLE);
|
||||
assert_eq!(fixture.prepare(Operation::Stabilize).write().exit_code, 0);
|
||||
let noop = fixture.prepare(Operation::Stabilize);
|
||||
let source = fixture.read("project.arcadia");
|
||||
// An opaque incomplete journal must never be interpreted/recovered by CLI.
|
||||
let journal = fixture.0.join(".arcadia-save-project.arcadia.journal");
|
||||
fs::create_dir(&journal).unwrap();
|
||||
fs::write(journal.join("sentinel"), b"retain").unwrap();
|
||||
for op in [Operation::Check, Operation::Stabilize] {
|
||||
let report = prepare(&fixture.entry(), op).err().unwrap();
|
||||
assert_eq!(report.exit_code, 3);
|
||||
assert!(report.diagnostics.iter().any(|d| d.code == "pending_save"));
|
||||
}
|
||||
assert_eq!(
|
||||
noop.write().exit_code,
|
||||
3,
|
||||
"saver must recheck after preview"
|
||||
);
|
||||
assert_eq!(fixture.read("project.arcadia"), source);
|
||||
assert_eq!(fs::read(journal.join("sentinel")).unwrap(), b"retain");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejected_alias_and_same_alias_preserve_source() {
|
||||
let fixture = Fixture::new();
|
||||
fixture.put("project.arcadia", SIMPLE);
|
||||
assert_eq!(fixture.prepare(Operation::Stabilize).write().exit_code, 0);
|
||||
let source = fixture.read("project.arcadia");
|
||||
for (old, new) in [
|
||||
("team", "rescue"),
|
||||
("team", "invalid alias"),
|
||||
("absent", "valid"),
|
||||
] {
|
||||
let (code, result) = fixture.cli(&["rename-alias", old, new, "--write"]);
|
||||
assert_eq!(code, 1);
|
||||
assert_eq!(result["status"], "rejected");
|
||||
assert_eq!(fixture.read("project.arcadia"), source);
|
||||
}
|
||||
let (code, result) = fixture.cli(&["rename-alias", "team", "team", "--write"]);
|
||||
assert_eq!(code, 0);
|
||||
assert_eq!(result["status"], "unchanged");
|
||||
assert_eq!(fixture.read("project.arcadia"), source);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rename_shows_missing_identity_and_separate_source_migration() {
|
||||
let fixture = Fixture::new();
|
||||
let old = "// retain\narcadia 5; project p \"P\" { oa_entity team \"Team\" {} }\n";
|
||||
fixture.put("project.arcadia", old);
|
||||
let candidate = fixture.prepare(Operation::RenameAlias {
|
||||
old: "team".into(),
|
||||
new: "crew".into(),
|
||||
});
|
||||
let report = candidate.report();
|
||||
assert_eq!(report.identities_to_stabilize, 2);
|
||||
assert_eq!(report.migration.as_ref().unwrap().from_schema, 5);
|
||||
assert_eq!(report.migration.as_ref().unwrap().to_schema, 7);
|
||||
assert!(report.changes[0].diff.contains("-arcadia 5;"));
|
||||
assert!(report.changes[0].diff.contains("+arcadia 7;"));
|
||||
assert!(report.changes[0].after.contains("oa_entity crew"));
|
||||
assert_eq!(fixture.read("project.arcadia"), old);
|
||||
assert_eq!(candidate.write().exit_code, 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn entry_is_explicit_and_machine_readable_usage_errors_do_not_write() {
|
||||
let fixture = Fixture::new();
|
||||
fixture.put("project.arcadia", SIMPLE);
|
||||
let output = Command::new(env!("CARGO_BIN_EXE_arcadia"))
|
||||
.current_dir(&fixture.0)
|
||||
.args(["check", "--json"])
|
||||
.output()
|
||||
.unwrap();
|
||||
assert_eq!(output.status.code(), Some(2));
|
||||
let error: Value = serde_json::from_slice(&output.stdout).unwrap();
|
||||
assert_eq!(error["diagnostics"][0]["code"], "usage");
|
||||
assert_eq!(fixture.read("project.arcadia"), SIMPLE);
|
||||
let (code, _) = fixture.cli(&["check", "--write"]);
|
||||
assert_eq!(code, 2);
|
||||
assert!(Path::new(env!("CARGO_BIN_EXE_arcadia")).is_file());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn loader_encoding_missing_dependency_and_invalid_old_source_keep_original_bytes() {
|
||||
let fixture = Fixture::new();
|
||||
let entry = "arcadia 7; project p \"P\" { include \"part.arcadia\"; }";
|
||||
fixture.put("project.arcadia", entry);
|
||||
let (code, report) = fixture.cli(&["stabilize", "--write"]);
|
||||
assert_eq!(code, 3, "a disk dependency could not be read");
|
||||
assert!(
|
||||
report["diagnostics"]
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.any(|d| d["code"] == "missing_include")
|
||||
);
|
||||
fs::write(fixture.0.join("part.arcadia"), [0xff, 0xfe]).unwrap();
|
||||
let (code, report) = fixture.cli(&["stabilize", "--write"]);
|
||||
assert_eq!(code, 1, "invalid encoding is invalid raw source");
|
||||
assert!(
|
||||
report["diagnostics"]
|
||||
.as_array()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.any(|d| d["code"] == "source_encoding")
|
||||
);
|
||||
assert_eq!(fixture.read("project.arcadia"), entry);
|
||||
assert_eq!(
|
||||
fs::read(fixture.0.join("part.arcadia")).unwrap(),
|
||||
[0xff, 0xfe]
|
||||
);
|
||||
for raw in [
|
||||
"arcadia 5; project p \"P\" { oa_entity a \"A\" { ??? } }",
|
||||
"arcadia 2; project p \"P\" {}",
|
||||
] {
|
||||
fixture.put("project.arcadia", raw);
|
||||
let (code, _) = fixture.cli(&["stabilize", "--write"]);
|
||||
assert_eq!(code, 1);
|
||||
assert_eq!(fixture.read("project.arcadia"), raw);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn non_element_alias_detached_file_and_unchanged_dependency_conflict() {
|
||||
let fixture = Fixture::new();
|
||||
fixture.put("project.arcadia", "arcadia 7; project p \"P\" { include \"part.arcadia\"; oa_activity a \"A\" {} allocation responsible \"Responsible\" { source @ // keep edge comment\nteam; target @a; } }");
|
||||
fixture.put("part.arcadia", "oa_entity team \"Team\" {}");
|
||||
fixture.put(
|
||||
"detached.arcadia",
|
||||
"invalid detached draft must stay exact 雨",
|
||||
);
|
||||
assert_eq!(fixture.prepare(Operation::Stabilize).write().exit_code, 0);
|
||||
let before = fixture.model();
|
||||
let relation = before
|
||||
.identities()
|
||||
.into_iter()
|
||||
.find(|(_, alias)| *alias == "responsible")
|
||||
.unwrap()
|
||||
.0;
|
||||
let (code, _) = fixture.cli(&["rename-alias", "responsible", "performs", "--write"]);
|
||||
assert_eq!(code, 0);
|
||||
let mut expected = before;
|
||||
expected.relations.get_mut(&relation).unwrap().alias = "performs".into();
|
||||
assert_eq!(fixture.model(), expected);
|
||||
assert!(
|
||||
fixture
|
||||
.read("project.arcadia")
|
||||
.contains("@ // keep edge comment\nteam")
|
||||
);
|
||||
let captured = fixture.prepare(Operation::RenameAlias {
|
||||
old: "p".into(),
|
||||
new: "rescue".into(),
|
||||
});
|
||||
assert!(
|
||||
captured
|
||||
.report()
|
||||
.changes
|
||||
.iter()
|
||||
.all(|c| c.path != "part.arcadia")
|
||||
);
|
||||
let root_before = fixture.read("project.arcadia");
|
||||
fixture.put("part.arcadia", "// external unchanged-dependency edit\n");
|
||||
assert_eq!(captured.write().exit_code, 3);
|
||||
assert_eq!(fixture.read("project.arcadia"), root_before);
|
||||
assert_eq!(
|
||||
fixture.read("part.arcadia"),
|
||||
"// external unchanged-dependency edit\n"
|
||||
);
|
||||
assert_eq!(
|
||||
fixture.read("detached.arcadia"),
|
||||
"invalid detached draft must stay exact 雨"
|
||||
);
|
||||
}
|
||||
@@ -7,8 +7,15 @@ rust-version.workspace = true
|
||||
|
||||
[dependencies]
|
||||
serde.workspace = true
|
||||
serde_json.workspace = true
|
||||
serde_json = { workspace = true, features = ["unbounded_depth"] }
|
||||
stacker = "0.1.25"
|
||||
uuid.workspace = true
|
||||
thiserror.workspace = true
|
||||
tempfile = "3"
|
||||
same-file = "1"
|
||||
num-bigint = "0.5.1"
|
||||
num-integer = "0.1.47"
|
||||
num-traits = "0.2.19"
|
||||
|
||||
[target.'cfg(target_os = "linux")'.dependencies]
|
||||
libc = "0.2"
|
||||
|
||||
@@ -0,0 +1 @@
|
||||
include!("../../build/windows_manifest.rs");
|
||||
@@ -0,0 +1,53 @@
|
||||
//! Generate only the new teaching-project files; old compatibility examples stay untouched.
|
||||
#[path = "../../../examples/release1/model.rs"]
|
||||
mod teaching;
|
||||
|
||||
fn main() -> Result<(), Box<dyn std::error::Error>> {
|
||||
let directory = std::env::args_os()
|
||||
.nth(1)
|
||||
.map(std::path::PathBuf::from)
|
||||
.unwrap_or_else(|| "examples/release1".into());
|
||||
let lesson = teaching::build();
|
||||
let bundle = teaching::checked_bundle(&lesson.project);
|
||||
for (name, source) in &bundle.files {
|
||||
let path = directory.join(name);
|
||||
std::fs::create_dir_all(path.parent().unwrap())?;
|
||||
std::fs::write(path, source)?;
|
||||
}
|
||||
for (name, value) in [
|
||||
("model.json", serde_json::to_value(&lesson.project)?),
|
||||
(
|
||||
"transition-before.json",
|
||||
serde_json::to_value(&lesson.before_transition)?,
|
||||
),
|
||||
(
|
||||
"transition-request.json",
|
||||
serde_json::to_value(&lesson.request)?,
|
||||
),
|
||||
(
|
||||
"expected-diagnostics.json",
|
||||
serde_json::to_value(oa_core::validation::validate(&lesson.project))?,
|
||||
),
|
||||
] {
|
||||
std::fs::write(
|
||||
directory.join(name),
|
||||
serde_json::to_string_pretty(&value)? + "\n",
|
||||
)?;
|
||||
}
|
||||
println!(
|
||||
"Validated {} elements, {} relations, {} views, {} traces; wrote {} source files to {}",
|
||||
lesson.project.elements.len(),
|
||||
lesson.project.relations.len(),
|
||||
lesson.project.diagrams.len(),
|
||||
lesson.project.traces.len(),
|
||||
bundle.files.len(),
|
||||
directory.display()
|
||||
);
|
||||
for issue in oa_core::validation::validate(&lesson.project) {
|
||||
println!(
|
||||
"{:?} {} {:?}: {}",
|
||||
issue.severity, issue.code, issue.element, issue.message
|
||||
);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,442 @@
|
||||
//! Deterministic dense-view fixture and semantic oracle. No GUI or authored routing.
|
||||
//! cargo run -p oa-core --example release_dense_views -- OUTPUT_DIRECTORY
|
||||
use oa_core::{view_options::*, *};
|
||||
use serde_json::json;
|
||||
use std::{
|
||||
collections::{BTreeMap, BTreeSet},
|
||||
error::Error,
|
||||
fs,
|
||||
path::PathBuf,
|
||||
time::Instant,
|
||||
};
|
||||
|
||||
fn id(n: u32) -> Id {
|
||||
format!("d4060906-0000-4000-8000-{n:012x}").parse().unwrap()
|
||||
}
|
||||
|
||||
fn element(p: &mut Project, n: u32, kind: Kind, alias: &str, name: &str, parent: Option<Id>) -> Id {
|
||||
let identity = id(n);
|
||||
assert!(
|
||||
p.elements
|
||||
.insert(
|
||||
identity,
|
||||
Element {
|
||||
id: identity,
|
||||
alias: alias.into(),
|
||||
name: name.into(),
|
||||
description: String::new(),
|
||||
parent,
|
||||
body: ElementBody::new(kind, Layer::Oa).unwrap()
|
||||
}
|
||||
)
|
||||
.is_none()
|
||||
);
|
||||
identity
|
||||
}
|
||||
|
||||
fn relation(p: &mut Project, n: u32, alias: &str, name: &str, body: RelationBody) -> Id {
|
||||
let identity = id(n);
|
||||
assert!(
|
||||
p.relations
|
||||
.insert(
|
||||
identity,
|
||||
Relation {
|
||||
id: identity,
|
||||
alias: alias.into(),
|
||||
name: name.into(),
|
||||
description: String::new(),
|
||||
body
|
||||
}
|
||||
)
|
||||
.is_none()
|
||||
);
|
||||
identity
|
||||
}
|
||||
|
||||
fn fixture() -> (Project, Id, Vec<Id>, Vec<Id>, Vec<Id>) {
|
||||
let mut p = Project::empty();
|
||||
p.id = id(1);
|
||||
p.alias = "dense_service_views".into();
|
||||
p.name = "Forty service exchanges".into();
|
||||
p.description = "Deterministic release fixture. Forty actual work exchanges share two endpoints; no authored routes or synthetic endpoints.".into();
|
||||
let requester = element(&mut p, 10, Kind::Entity, "requester", "Requester", None);
|
||||
let provider = element(&mut p, 11, Kind::Entity, "provider", "Provider", None);
|
||||
let a = element(
|
||||
&mut p,
|
||||
20,
|
||||
Kind::Activity,
|
||||
"request_service",
|
||||
"Request service",
|
||||
None,
|
||||
);
|
||||
let b = element(
|
||||
&mut p,
|
||||
21,
|
||||
Kind::Activity,
|
||||
"provide_service",
|
||||
"Provide service",
|
||||
None,
|
||||
);
|
||||
relation(
|
||||
&mut p,
|
||||
3000,
|
||||
"requester_work",
|
||||
"Requester responsibility",
|
||||
RelationBody::Allocation {
|
||||
source: requester,
|
||||
target: a,
|
||||
},
|
||||
);
|
||||
relation(
|
||||
&mut p,
|
||||
3001,
|
||||
"provider_work",
|
||||
"Provider responsibility",
|
||||
RelationBody::Allocation {
|
||||
source: provider,
|
||||
target: b,
|
||||
},
|
||||
);
|
||||
let group_names = ["Commands", "Status", "Alerts", "Measurements"];
|
||||
let items: Vec<_> = group_names
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(i, name)| {
|
||||
element(
|
||||
&mut p,
|
||||
100 + i as u32,
|
||||
Kind::ExchangeItem,
|
||||
&format!("payload_{}", i + 1),
|
||||
&format!("{name} payload"),
|
||||
None,
|
||||
)
|
||||
})
|
||||
.collect();
|
||||
let exchanges: Vec<_> = (0..40)
|
||||
.map(|i| {
|
||||
relation(
|
||||
&mut p,
|
||||
2000 + i,
|
||||
&format!("service_data_{:02}", i + 1),
|
||||
&format!("Service data {:02}", i + 1),
|
||||
RelationBody::Interaction {
|
||||
source: a,
|
||||
target: b,
|
||||
items: vec![items[(i / 10) as usize]],
|
||||
},
|
||||
)
|
||||
})
|
||||
.collect();
|
||||
let mut categories = vec![];
|
||||
for (i, name) in group_names.iter().enumerate() {
|
||||
let category = element(
|
||||
&mut p,
|
||||
200 + i as u32,
|
||||
Kind::ExchangeCategory,
|
||||
&format!("concern_{}", i + 1),
|
||||
name,
|
||||
None,
|
||||
);
|
||||
*p.elements.get_mut(&category).unwrap().shared_mut().unwrap() =
|
||||
SharedBody::ExchangeCategory {
|
||||
family: ExchangeFamily::Work,
|
||||
exchanges: exchanges[i * 10..i * 10 + 10].to_vec(),
|
||||
};
|
||||
categories.push(category);
|
||||
}
|
||||
let overlapping = element(
|
||||
&mut p,
|
||||
204,
|
||||
Kind::ExchangeCategory,
|
||||
"critical_concern",
|
||||
"Critical cross-cutting exchanges",
|
||||
None,
|
||||
);
|
||||
*p.elements
|
||||
.get_mut(&overlapping)
|
||||
.unwrap()
|
||||
.shared_mut()
|
||||
.unwrap() = SharedBody::ExchangeCategory {
|
||||
family: ExchangeFamily::Work,
|
||||
exchanges: [0, 10, 20, 30].map(|i| exchanges[i]).to_vec(),
|
||||
};
|
||||
categories.push(overlapping);
|
||||
let mut contexts = vec![];
|
||||
for (group, name) in group_names[..3].iter().enumerate() {
|
||||
let process = element(
|
||||
&mut p,
|
||||
300 + group as u32,
|
||||
Kind::Process,
|
||||
&format!("process_{}", group + 1),
|
||||
&format!("{name} process"),
|
||||
None,
|
||||
);
|
||||
for offset in 0..10 {
|
||||
let index = group * 10 + offset;
|
||||
let occurrence = element(
|
||||
&mut p,
|
||||
1000 + index as u32,
|
||||
Kind::Occurrence,
|
||||
&format!("use_data_{:02}", index + 1),
|
||||
&format!("Use service data {:02}", index + 1),
|
||||
Some(process),
|
||||
);
|
||||
*p.elements
|
||||
.get_mut(&occurrence)
|
||||
.unwrap()
|
||||
.shared_mut()
|
||||
.unwrap() = SharedBody::Occurrence {
|
||||
body: OccurrenceBody::Exchange {
|
||||
operation: None,
|
||||
exchange: Some(exchanges[index]),
|
||||
sender: None,
|
||||
receiver: None,
|
||||
message_kind: MessageKind::Asynchronous,
|
||||
reply_to: None,
|
||||
values: vec![],
|
||||
},
|
||||
precondition: String::new(),
|
||||
postcondition: String::new(),
|
||||
};
|
||||
p.elements
|
||||
.get_mut(&process)
|
||||
.unwrap()
|
||||
.steps_mut()
|
||||
.unwrap()
|
||||
.push(occurrence);
|
||||
}
|
||||
contexts.push(process);
|
||||
}
|
||||
let diagram = id(4000);
|
||||
let nodes = [(a, 80.), (b, 760.)]
|
||||
.into_iter()
|
||||
.enumerate()
|
||||
.map(|(i, (element, x))| {
|
||||
let id = id(4100 + i as u32);
|
||||
(
|
||||
id,
|
||||
NodePlacement {
|
||||
id,
|
||||
alias: format!("service_placement_{}", i + 1),
|
||||
element,
|
||||
position: Position { x, y: 160. },
|
||||
size: Size {
|
||||
width: 230.,
|
||||
height: 150.,
|
||||
},
|
||||
collapsed: false,
|
||||
port_anchors: vec![],
|
||||
},
|
||||
)
|
||||
})
|
||||
.collect();
|
||||
p.diagrams.insert(diagram, Diagram { id: diagram, alias: "forty_exchange_view".into(), name: "Forty service exchanges · all concerns".into(), description: "Start with All. Compare first category, overlapping concerns, global coverage and chosen processes. No hand-routed edges.".into(), layer: Layer::Oa, projection: ProjectionKind::FunctionalDataflow, view_options: ViewOptions::default(), nodes, routes: vec![] });
|
||||
(p, diagram, exchanges, categories, contexts)
|
||||
}
|
||||
|
||||
fn projected(p: &Project, diagram: &Diagram) -> BTreeSet<Id> {
|
||||
projection::project_diagram(p, diagram)
|
||||
.edges
|
||||
.into_iter()
|
||||
.map(|edge| edge.id)
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn overlap(a: routing::RoutingBounds, b: routing::RoutingBounds) -> bool {
|
||||
a.position.x < b.position.x + b.size.width
|
||||
&& b.position.x < a.position.x + a.size.width
|
||||
&& a.position.y < b.position.y + b.size.height
|
||||
&& b.position.y < a.position.y + a.size.height
|
||||
}
|
||||
|
||||
fn main() -> Result<(), Box<dyn Error>> {
|
||||
let output = PathBuf::from(
|
||||
std::env::args_os()
|
||||
.nth(1)
|
||||
.ok_or("Supply an output directory for the dense-view fixture.")?,
|
||||
);
|
||||
let (p, diagram, exchanges, categories, contexts) = fixture();
|
||||
let issues = validation::validate(&p);
|
||||
assert!(
|
||||
!issues
|
||||
.iter()
|
||||
.any(|issue| issue.severity == validation::Severity::Error),
|
||||
"{issues:?}"
|
||||
);
|
||||
let pristine = p.clone();
|
||||
let original = &p.diagrams[&diagram];
|
||||
assert!(original.routes.is_empty());
|
||||
let all = projection::project_view(&p, diagram);
|
||||
assert_eq!(all.nodes.len(), 2);
|
||||
assert_eq!(all.edges.len(), 40);
|
||||
assert_eq!(
|
||||
all.edges
|
||||
.iter()
|
||||
.map(|edge| (edge.source, edge.target))
|
||||
.collect::<BTreeSet<_>>()
|
||||
.len(),
|
||||
1
|
||||
);
|
||||
let sets = |ids: &[Id]| ids.iter().copied().collect::<BTreeSet<_>>();
|
||||
let cases = vec![
|
||||
("all", ViewOptions::default(), sets(&exchanges)),
|
||||
(
|
||||
"first_category",
|
||||
ViewOptions {
|
||||
work_categories: CategorySelection::Any(vec![categories[0]]),
|
||||
..ViewOptions::default()
|
||||
},
|
||||
sets(&exchanges[..10]),
|
||||
),
|
||||
(
|
||||
"first_and_overlap",
|
||||
ViewOptions {
|
||||
work_categories: CategorySelection::Any(vec![categories[0], categories[4]]),
|
||||
..ViewOptions::default()
|
||||
},
|
||||
exchanges[..10]
|
||||
.iter()
|
||||
.copied()
|
||||
.chain([exchanges[10], exchanges[20], exchanges[30]])
|
||||
.collect(),
|
||||
),
|
||||
(
|
||||
"in_behavior",
|
||||
ViewOptions {
|
||||
coverage: Coverage::InBehavior,
|
||||
..ViewOptions::default()
|
||||
},
|
||||
sets(&exchanges[..30]),
|
||||
),
|
||||
(
|
||||
"outside_behavior",
|
||||
ViewOptions {
|
||||
coverage: Coverage::OutsideBehavior,
|
||||
..ViewOptions::default()
|
||||
},
|
||||
sets(&exchanges[30..]),
|
||||
),
|
||||
(
|
||||
"second_process",
|
||||
ViewOptions {
|
||||
work_contexts: ContextSelection::Any(vec![contexts[1]]),
|
||||
..ViewOptions::default()
|
||||
},
|
||||
sets(&exchanges[10..20]),
|
||||
),
|
||||
(
|
||||
"outside_second_process",
|
||||
ViewOptions {
|
||||
coverage: Coverage::OutsideBehavior,
|
||||
work_contexts: ContextSelection::Any(vec![contexts[1]]),
|
||||
..ViewOptions::default()
|
||||
},
|
||||
BTreeSet::new(),
|
||||
),
|
||||
(
|
||||
"empty_categories",
|
||||
ViewOptions {
|
||||
work_categories: CategorySelection::Any(vec![]),
|
||||
..ViewOptions::default()
|
||||
},
|
||||
BTreeSet::new(),
|
||||
),
|
||||
(
|
||||
"empty_contexts",
|
||||
ViewOptions {
|
||||
work_contexts: ContextSelection::Any(vec![]),
|
||||
..ViewOptions::default()
|
||||
},
|
||||
BTreeSet::new(),
|
||||
),
|
||||
(
|
||||
"no_lines",
|
||||
ViewOptions {
|
||||
relation_kinds: RelationKinds::Only(vec![]),
|
||||
..ViewOptions::default()
|
||||
},
|
||||
BTreeSet::new(),
|
||||
),
|
||||
(
|
||||
"first_hide_05",
|
||||
ViewOptions {
|
||||
hidden_edges: vec![exchanges[4]],
|
||||
work_categories: CategorySelection::Any(vec![categories[0]]),
|
||||
exchange_labels: ExchangeLabels::NameAndItems,
|
||||
..ViewOptions::default()
|
||||
},
|
||||
exchanges[..10]
|
||||
.iter()
|
||||
.filter(|edge| **edge != exchanges[4])
|
||||
.copied()
|
||||
.collect(),
|
||||
),
|
||||
];
|
||||
let mut case_results = BTreeMap::new();
|
||||
for (name, options, expected) in cases {
|
||||
assert!(validate_options(&p, Layer::Oa, &options).is_empty());
|
||||
let mut changed = original.clone();
|
||||
changed.view_options = options;
|
||||
assert_eq!(projected(&p, &changed), expected, "{name}");
|
||||
let view = projection::project_diagram(&p, &changed);
|
||||
assert_eq!(
|
||||
view.nodes, all.nodes,
|
||||
"{name}: visibility must not move nodes"
|
||||
);
|
||||
assert_eq!(
|
||||
view.ports, all.ports,
|
||||
"{name}: visibility must not move ports"
|
||||
);
|
||||
assert!(changed.routes.is_empty());
|
||||
case_results.insert(name, json!({"count":expected.len(),"edges":expected}));
|
||||
}
|
||||
assert_eq!(
|
||||
ExchangeLabels::Items.label(&p, exchanges[0]),
|
||||
"Commands payload"
|
||||
);
|
||||
assert_eq!(
|
||||
ExchangeLabels::NameAndItems.label(&p, exchanges[39]),
|
||||
"Service data 40 · Measurements payload"
|
||||
);
|
||||
let began = Instant::now();
|
||||
let routed = routing::route_diagram(&p, original, &all);
|
||||
let route_ms = began.elapsed().as_millis();
|
||||
assert_eq!(routed.edges.len(), 40);
|
||||
let edges: Vec<_> = routed.edges.values().collect();
|
||||
let mut label_overlaps = vec![];
|
||||
let mut coincident_paths = vec![];
|
||||
for (i, first) in edges.iter().enumerate() {
|
||||
for second in &edges[i + 1..] {
|
||||
if overlap(first.label.bounds, second.label.bounds) {
|
||||
label_overlaps.push([first.id, second.id]);
|
||||
}
|
||||
if first.points == second.points {
|
||||
coincident_paths.push([first.id, second.id]);
|
||||
}
|
||||
}
|
||||
}
|
||||
let source = language::format(&p);
|
||||
assert_eq!(
|
||||
language::parse(&source).expect("Canonical fixture source must reopen"),
|
||||
p
|
||||
);
|
||||
let native_json = serde_json::to_vec_pretty(&p)?;
|
||||
assert_eq!(persistence::decode(&native_json)?, p);
|
||||
assert_eq!(
|
||||
p, pristine,
|
||||
"Oracles and routing must not mutate model facts"
|
||||
);
|
||||
let report = json!({"schema":p.schema_version,"project":p.id,"diagram":diagram,"semantic_oracles":"passed","elements":p.elements.len(),"relations":p.relations.len(),"cases":case_results,
|
||||
"routing_ms":route_ms,"label_overlap_pairs":label_overlaps,"exactly_coincident_path_pairs":coincident_paths,
|
||||
"routing_warnings":edges.iter().map(|edge| json!({"edge":edge.id,"warnings":edge.warnings.iter().map(ToString::to_string).collect::<Vec<_>>()})).collect::<Vec<_>>(),
|
||||
"native_readability":"pending; metrics do not establish a usability pass"});
|
||||
fs::create_dir_all(&output)?;
|
||||
fs::write(output.join("dense-40.arcadia"), source)?;
|
||||
fs::write(output.join("dense-40.json"), native_json)?;
|
||||
fs::write(
|
||||
output.join("dense-40-oracle.json"),
|
||||
serde_json::to_vec_pretty(&report)?,
|
||||
)?;
|
||||
println!("{}", serde_json::to_string_pretty(&report)?);
|
||||
Ok(())
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
//! Schema 8 engineering definitions and static admission. No expression evaluation.
|
||||
mod admission;
|
||||
mod expression_lifecycle;
|
||||
pub(crate) mod expression_serde;
|
||||
pub mod references;
|
||||
mod resolve;
|
||||
mod typecheck;
|
||||
mod types;
|
||||
|
||||
pub(crate) use admission::admit_structure_checked;
|
||||
pub use admission::{AdmissionLimits, AdmissionUsage, admit};
|
||||
pub use resolve::{EffectiveBinding, KindHandle, ResolvedAnalysis, ResolvedScalar, ResolvedType};
|
||||
pub use types::*;
|
||||
|
||||
/// Ratified semantic bounds. Aggregate admission work is a separate caller policy.
|
||||
pub const MAX_EXPRESSION_DEPTH: usize = 128;
|
||||
pub const MAX_CLOSURE_NODES: usize = 65_536;
|
||||
pub const MAX_LIST_LENGTH: usize = 1_024;
|
||||
pub const MAX_CALL_DEPTH: usize = 32;
|
||||
|
||||
/// Additional persisted records for existing transport ParseLimits. Definitions
|
||||
/// themselves count as graph objects there; this counts parameters, overrides,
|
||||
/// and every stored expression node, with saturating arithmetic and no recursion.
|
||||
pub(crate) fn nested_record_count(project: &crate::Project) -> usize {
|
||||
let mut count = 0usize;
|
||||
fn binding(value: &Binding, count: &mut usize) {
|
||||
if let Binding::Expression(expression) = value {
|
||||
references::walk(expression, &mut |_| {
|
||||
*count = count.saturating_add(1);
|
||||
});
|
||||
}
|
||||
}
|
||||
for definition in project.definitions.values() {
|
||||
if let DefinitionBody::Calculation(calculation) = &definition.body {
|
||||
count = count.saturating_add(calculation.parameters.len());
|
||||
binding(&calculation.body, &mut count);
|
||||
}
|
||||
}
|
||||
for element in project.elements.values() {
|
||||
match element.shared() {
|
||||
Some(crate::SharedBody::EngineeringProperty { base, .. }) => binding(base, &mut count),
|
||||
Some(crate::SharedBody::AnalysisCase { overrides, .. }) => {
|
||||
count = count.saturating_add(overrides.len());
|
||||
for value in overrides.values() {
|
||||
binding(value, &mut count);
|
||||
}
|
||||
}
|
||||
Some(crate::SharedBody::AnalysisCheck { predicate, .. }) => {
|
||||
binding(predicate, &mut count)
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
count
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,377 @@
|
||||
//! Ordinary expression ownership never consumes stack proportional to tree depth.
|
||||
//! This also covers a partially decoded expression and rejected programmatic input.
|
||||
use super::Expr;
|
||||
use std::{fmt, mem};
|
||||
|
||||
impl Expr {
|
||||
fn clone_shell(&self) -> Self {
|
||||
let leaf = || Box::new(Self::Boolean(false));
|
||||
match self {
|
||||
Self::Boolean(value) => Self::Boolean(*value),
|
||||
Self::Number(value) => Self::Number(value.clone()),
|
||||
Self::Quantity { magnitude, unit } => Self::Quantity {
|
||||
magnitude: magnitude.clone(),
|
||||
unit: *unit,
|
||||
},
|
||||
Self::Property(id) => Self::Property(*id),
|
||||
Self::Parameter(id) => Self::Parameter(*id),
|
||||
Self::List(values) => {
|
||||
Self::List((0..values.len()).map(|_| Self::Boolean(false)).collect())
|
||||
}
|
||||
Self::Unary { op, .. } => Self::Unary {
|
||||
op: *op,
|
||||
operand: leaf(),
|
||||
},
|
||||
Self::Binary { op, .. } => Self::Binary {
|
||||
op: *op,
|
||||
left: leaf(),
|
||||
right: leaf(),
|
||||
},
|
||||
Self::If { .. } => Self::If {
|
||||
condition: leaf(),
|
||||
when_true: leaf(),
|
||||
when_false: leaf(),
|
||||
},
|
||||
Self::Call {
|
||||
definition,
|
||||
arguments,
|
||||
} => Self::Call {
|
||||
definition: *definition,
|
||||
arguments: arguments
|
||||
.keys()
|
||||
.map(|id| (*id, Self::Boolean(false)))
|
||||
.collect(),
|
||||
},
|
||||
Self::Sum { .. } => Self::Sum {
|
||||
values: leaf(),
|
||||
initial: leaf(),
|
||||
},
|
||||
Self::Power { exponent, .. } => Self::Power {
|
||||
base: leaf(),
|
||||
exponent: *exponent,
|
||||
},
|
||||
Self::AsKind { kind, .. } => Self::AsKind {
|
||||
kind: *kind,
|
||||
value: leaf(),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
fn detach_children(&mut self, pending: &mut Vec<Self>) {
|
||||
let mut take = |child: &mut Box<Self>| {
|
||||
pending.push(mem::replace(child.as_mut(), Self::Boolean(false)));
|
||||
};
|
||||
match self {
|
||||
Self::Unary { operand, .. } => take(operand),
|
||||
Self::Binary { left, right, .. } => {
|
||||
take(left);
|
||||
take(right);
|
||||
}
|
||||
Self::If {
|
||||
condition,
|
||||
when_true,
|
||||
when_false,
|
||||
} => {
|
||||
take(condition);
|
||||
take(when_true);
|
||||
take(when_false);
|
||||
}
|
||||
Self::Sum { values, initial } => {
|
||||
take(values);
|
||||
take(initial);
|
||||
}
|
||||
Self::Power { base, .. } => take(base),
|
||||
Self::AsKind { value, .. } => take(value),
|
||||
Self::List(values) => pending.append(values),
|
||||
Self::Call { arguments, .. } => {
|
||||
pending.extend(mem::take(arguments).into_values());
|
||||
}
|
||||
Self::Boolean(_)
|
||||
| Self::Number(_)
|
||||
| Self::Quantity { .. }
|
||||
| Self::Property(_)
|
||||
| Self::Parameter(_) => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for Expr {
|
||||
fn drop(&mut self) {
|
||||
let mut pending = Vec::new();
|
||||
self.detach_children(&mut pending);
|
||||
while let Some(mut node) = pending.pop() {
|
||||
node.detach_children(&mut pending);
|
||||
// node now owns only leaves/empty collections. Its ordinary drop
|
||||
// reenters this method at most once, independently of original depth.
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Clone for Expr {
|
||||
fn clone(&self) -> Self {
|
||||
let mut result = Self::Boolean(false);
|
||||
let mut pending = vec![(self, &mut result)];
|
||||
while let Some((source, destination)) = pending.pop() {
|
||||
*destination = source.clone_shell();
|
||||
match (source, destination) {
|
||||
(Self::List(a), Self::List(b)) => pending.extend(a.iter().zip(b.iter_mut())),
|
||||
(Self::Unary { operand: a, .. }, Self::Unary { operand: b, .. })
|
||||
| (Self::Power { base: a, .. }, Self::Power { base: b, .. })
|
||||
| (Self::AsKind { value: a, .. }, Self::AsKind { value: b, .. }) => {
|
||||
pending.push((a, b));
|
||||
}
|
||||
(
|
||||
Self::Binary {
|
||||
left: a, right: b, ..
|
||||
},
|
||||
Self::Binary {
|
||||
left: c, right: d, ..
|
||||
},
|
||||
)
|
||||
| (
|
||||
Self::Sum {
|
||||
values: a,
|
||||
initial: b,
|
||||
},
|
||||
Self::Sum {
|
||||
values: c,
|
||||
initial: d,
|
||||
},
|
||||
) => {
|
||||
pending.push((a, c));
|
||||
pending.push((b, d));
|
||||
}
|
||||
(
|
||||
Self::If {
|
||||
condition: a,
|
||||
when_true: b,
|
||||
when_false: c,
|
||||
},
|
||||
Self::If {
|
||||
condition: d,
|
||||
when_true: e,
|
||||
when_false: f,
|
||||
},
|
||||
) => {
|
||||
pending.push((a, d));
|
||||
pending.push((b, e));
|
||||
pending.push((c, f));
|
||||
}
|
||||
(Self::Call { arguments: a, .. }, Self::Call { arguments: b, .. }) => {
|
||||
pending.extend(a.values().zip(b.values_mut()));
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
result
|
||||
}
|
||||
}
|
||||
|
||||
impl PartialEq for Expr {
|
||||
fn eq(&self, other: &Self) -> bool {
|
||||
let mut pending = vec![(self, other)];
|
||||
while let Some((a, b)) = pending.pop() {
|
||||
match (a, b) {
|
||||
(Self::Boolean(a), Self::Boolean(b)) if a == b => {}
|
||||
(Self::Number(a), Self::Number(b)) if a == b => {}
|
||||
(
|
||||
Self::Quantity {
|
||||
magnitude: a,
|
||||
unit: b,
|
||||
},
|
||||
Self::Quantity {
|
||||
magnitude: c,
|
||||
unit: d,
|
||||
},
|
||||
) if a == c && b == d => {}
|
||||
(Self::Property(a), Self::Property(b)) if a == b => {}
|
||||
(Self::Parameter(a), Self::Parameter(b)) if a == b => {}
|
||||
(Self::List(a), Self::List(b)) if a.len() == b.len() => {
|
||||
pending.extend(a.iter().zip(b.iter()));
|
||||
}
|
||||
(Self::Unary { op: a, operand: b }, Self::Unary { op: c, operand: d })
|
||||
if a == c =>
|
||||
{
|
||||
pending.push((b, d));
|
||||
}
|
||||
(
|
||||
Self::Binary {
|
||||
op: a,
|
||||
left: b,
|
||||
right: c,
|
||||
},
|
||||
Self::Binary {
|
||||
op: d,
|
||||
left: e,
|
||||
right: f,
|
||||
},
|
||||
) if a == d => {
|
||||
pending.push((b, e));
|
||||
pending.push((c, f));
|
||||
}
|
||||
(
|
||||
Self::If {
|
||||
condition: a,
|
||||
when_true: b,
|
||||
when_false: c,
|
||||
},
|
||||
Self::If {
|
||||
condition: d,
|
||||
when_true: e,
|
||||
when_false: f,
|
||||
},
|
||||
) => {
|
||||
pending.push((a, d));
|
||||
pending.push((b, e));
|
||||
pending.push((c, f));
|
||||
}
|
||||
(
|
||||
Self::Call {
|
||||
definition: a,
|
||||
arguments: b,
|
||||
},
|
||||
Self::Call {
|
||||
definition: c,
|
||||
arguments: d,
|
||||
},
|
||||
) if a == c && b.len() == d.len() => {
|
||||
for ((key_a, value_a), (key_b, value_b)) in b.iter().zip(d.iter()) {
|
||||
if key_a != key_b {
|
||||
return false;
|
||||
}
|
||||
pending.push((value_a, value_b));
|
||||
}
|
||||
}
|
||||
(
|
||||
Self::Sum {
|
||||
values: a,
|
||||
initial: b,
|
||||
},
|
||||
Self::Sum {
|
||||
values: c,
|
||||
initial: d,
|
||||
},
|
||||
) => {
|
||||
pending.push((a, c));
|
||||
pending.push((b, d));
|
||||
}
|
||||
(
|
||||
Self::Power {
|
||||
base: a,
|
||||
exponent: b,
|
||||
},
|
||||
Self::Power {
|
||||
base: c,
|
||||
exponent: d,
|
||||
},
|
||||
) if b == d => {
|
||||
pending.push((a, c));
|
||||
}
|
||||
(Self::AsKind { kind: a, value: b }, Self::AsKind { kind: c, value: d })
|
||||
if a == c =>
|
||||
{
|
||||
pending.push((b, d));
|
||||
}
|
||||
_ => return false,
|
||||
}
|
||||
}
|
||||
true
|
||||
}
|
||||
}
|
||||
impl Eq for Expr {}
|
||||
|
||||
impl fmt::Debug for Expr {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
enum Task<'a> {
|
||||
Node(&'a Expr),
|
||||
Text(&'static str),
|
||||
Scalar(&'a dyn fmt::Debug),
|
||||
}
|
||||
use Task::*;
|
||||
let mut pending = vec![Node(self)];
|
||||
while let Some(task) = pending.pop() {
|
||||
match task {
|
||||
Text(text) => f.write_str(text)?,
|
||||
Scalar(value) => write!(f, "{value:?}")?,
|
||||
Node(node) => match node {
|
||||
Self::Boolean(value) => write!(f, "Boolean({value:?})")?,
|
||||
Self::Number(value) => write!(f, "Number({value:?})")?,
|
||||
Self::Quantity { magnitude, unit } => {
|
||||
write!(f, "Quantity {{ magnitude: {magnitude:?}, unit: {unit:?} }}")?;
|
||||
}
|
||||
Self::Property(id) => write!(f, "Property({id:?})")?,
|
||||
Self::Parameter(id) => write!(f, "Parameter({id:?})")?,
|
||||
Self::List(values) => {
|
||||
f.write_str("List([")?;
|
||||
pending.push(Text("])"));
|
||||
for (index, value) in values.iter().enumerate().rev() {
|
||||
pending.push(Node(value));
|
||||
if index > 0 {
|
||||
pending.push(Text(", "));
|
||||
}
|
||||
}
|
||||
}
|
||||
Self::Unary { op, operand } => {
|
||||
write!(f, "Unary {{ op: {op:?}, operand: ")?;
|
||||
pending.extend([Text(" }"), Node(operand)]);
|
||||
}
|
||||
Self::Binary { op, left, right } => {
|
||||
write!(f, "Binary {{ op: {op:?}, left: ")?;
|
||||
pending.extend([Text(" }"), Node(right), Text(", right: "), Node(left)]);
|
||||
}
|
||||
Self::If {
|
||||
condition,
|
||||
when_true,
|
||||
when_false,
|
||||
} => {
|
||||
f.write_str("If { condition: ")?;
|
||||
pending.extend([
|
||||
Text(" }"),
|
||||
Node(when_false),
|
||||
Text(", when_false: "),
|
||||
Node(when_true),
|
||||
Text(", when_true: "),
|
||||
Node(condition),
|
||||
]);
|
||||
}
|
||||
Self::Call {
|
||||
definition,
|
||||
arguments,
|
||||
} => {
|
||||
write!(f, "Call {{ definition: {definition:?}, arguments: {{")?;
|
||||
pending.push(Text("} }"));
|
||||
for (index, (id, value)) in arguments.iter().enumerate().rev() {
|
||||
pending.extend([Node(value), Text(": "), Scalar(id)]);
|
||||
if index > 0 {
|
||||
pending.push(Text(", "));
|
||||
}
|
||||
}
|
||||
}
|
||||
Self::Sum { values, initial } => {
|
||||
f.write_str("Sum { values: ")?;
|
||||
pending.extend([
|
||||
Text(" }"),
|
||||
Node(initial),
|
||||
Text(", initial: "),
|
||||
Node(values),
|
||||
]);
|
||||
}
|
||||
Self::Power { base, exponent } => {
|
||||
f.write_str("Power { base: ")?;
|
||||
pending.extend([
|
||||
Text(" }"),
|
||||
Scalar(exponent),
|
||||
Text(", exponent: "),
|
||||
Node(base),
|
||||
]);
|
||||
}
|
||||
Self::AsKind { kind, value } => {
|
||||
write!(f, "AsKind {{ kind: {kind:?}, value: ")?;
|
||||
pending.extend([Text(" }"), Node(value)]);
|
||||
}
|
||||
},
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,261 @@
|
||||
//! The existing externally tagged Serde schema, with admission at each Expr edge.
|
||||
//! The private remote derive is the sole wire grammar: it still rejects unknown
|
||||
//! fields/variants, duplicate fields and malformed UUIDs/Exact values.
|
||||
use super::{
|
||||
BinaryOp, DefinitionRef, Expr, MAX_CLOSURE_NODES, MAX_EXPRESSION_DEPTH, MAX_LIST_LENGTH,
|
||||
ParameterId, UnaryOp,
|
||||
};
|
||||
use crate::{Id, analysis_numeric::Exact};
|
||||
use serde::{
|
||||
Deserialize, Serialize,
|
||||
de::{DeserializeSeed, MapAccess, SeqAccess, Visitor},
|
||||
};
|
||||
use std::{cell::Cell, collections::BTreeMap, fmt};
|
||||
|
||||
pub(crate) const MAX_JSON_EXPRESSION_NODES: usize = 262_144;
|
||||
// These are requested segment capacities, not an allocator or RSS guarantee.
|
||||
const RED_ZONE: usize = 64 * 1024;
|
||||
const STACK_SEGMENT: usize = 512 * 1024;
|
||||
|
||||
pub(crate) fn with_stack<R>(operation: impl FnOnce() -> R) -> R {
|
||||
stacker::maybe_grow(RED_ZONE, STACK_SEGMENT, operation)
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
struct Meter {
|
||||
active: bool,
|
||||
depth: usize,
|
||||
nodes: usize,
|
||||
tree_nodes: usize,
|
||||
maximum: usize,
|
||||
}
|
||||
impl Meter {
|
||||
const DEFAULT: Self = Self {
|
||||
active: false,
|
||||
depth: 0,
|
||||
nodes: 0,
|
||||
tree_nodes: 0,
|
||||
maximum: MAX_JSON_EXPRESSION_NODES,
|
||||
};
|
||||
}
|
||||
thread_local! {
|
||||
static DECODING: Cell<Meter> = const { Cell::new(Meter::DEFAULT) };
|
||||
static ENCODING: Cell<Meter> = const { Cell::new(Meter::DEFAULT) };
|
||||
}
|
||||
type LocalMeter = &'static std::thread::LocalKey<Cell<Meter>>;
|
||||
|
||||
/// One codec operation owns the aggregate meter across all disjoint bindings.
|
||||
/// Scope restoration also runs on errors and unwinding; no mutable TLS borrow is
|
||||
/// held across Serde/user code or a stack switch.
|
||||
pub(crate) struct Scope {
|
||||
local: LocalMeter,
|
||||
previous: Meter,
|
||||
}
|
||||
impl Scope {
|
||||
pub(crate) fn decoding(maximum: usize) -> Self {
|
||||
Self::new(&DECODING, maximum)
|
||||
}
|
||||
pub(crate) fn encoding(maximum: usize) -> Self {
|
||||
Self::new(&ENCODING, maximum)
|
||||
}
|
||||
fn new(local: LocalMeter, maximum: usize) -> Self {
|
||||
let next = Meter {
|
||||
active: true,
|
||||
maximum: maximum.min(MAX_JSON_EXPRESSION_NODES),
|
||||
..Meter::DEFAULT
|
||||
};
|
||||
let previous = local.with(|meter| meter.replace(next));
|
||||
Self { local, previous }
|
||||
}
|
||||
}
|
||||
impl Drop for Scope {
|
||||
fn drop(&mut self) {
|
||||
self.local.with(|meter| meter.set(self.previous));
|
||||
}
|
||||
}
|
||||
|
||||
struct NodeGuard {
|
||||
local: LocalMeter,
|
||||
root: bool,
|
||||
}
|
||||
impl NodeGuard {
|
||||
fn enter(local: LocalMeter) -> Result<Self, &'static str> {
|
||||
local.with(|slot| {
|
||||
let mut meter = slot.get();
|
||||
let root = !meter.active;
|
||||
if root {
|
||||
meter = Meter {
|
||||
active: true,
|
||||
..Meter::DEFAULT
|
||||
};
|
||||
}
|
||||
if meter.depth == 0 {
|
||||
meter.tree_nodes = 0;
|
||||
}
|
||||
if meter.depth >= MAX_EXPRESSION_DEPTH {
|
||||
return Err("Expression logical depth exceeds 128.");
|
||||
}
|
||||
if meter.nodes >= meter.maximum {
|
||||
return Err("JSON expression allocation count exceeded.");
|
||||
}
|
||||
if meter.tree_nodes >= MAX_CLOSURE_NODES {
|
||||
return Err("Stored expression node count exceeds 65536.");
|
||||
}
|
||||
meter.depth += 1;
|
||||
meter.nodes += 1;
|
||||
meter.tree_nodes += 1;
|
||||
slot.set(meter);
|
||||
Ok(Self { local, root })
|
||||
})
|
||||
}
|
||||
}
|
||||
impl Drop for NodeGuard {
|
||||
fn drop(&mut self) {
|
||||
self.local.with(|slot| {
|
||||
let mut meter = slot.get();
|
||||
meter.depth -= 1;
|
||||
if self.root {
|
||||
meter.active = false;
|
||||
}
|
||||
slot.set(meter);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
impl<'de> Deserialize<'de> for Expr {
|
||||
fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
|
||||
let _node = NodeGuard::enter(&DECODING).map_err(serde::de::Error::custom)?;
|
||||
with_stack(|| WireExpr::deserialize(deserializer))
|
||||
}
|
||||
}
|
||||
impl Serialize for Expr {
|
||||
fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
|
||||
let _node = NodeGuard::enter(&ENCODING).map_err(serde::ser::Error::custom)?;
|
||||
match self {
|
||||
Self::List(values) if values.len() > MAX_LIST_LENGTH => {
|
||||
return Err(serde::ser::Error::custom(
|
||||
"Expression List exceeds 1024 items.",
|
||||
));
|
||||
}
|
||||
Self::Call { arguments, .. } if arguments.len() > MAX_CLOSURE_NODES => {
|
||||
return Err(serde::ser::Error::custom(
|
||||
"Call argument count exceeds 65536.",
|
||||
));
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
with_stack(|| WireExpr::serialize(self, serializer))
|
||||
}
|
||||
}
|
||||
|
||||
// A private remote derive avoids exposing an unguarded inherent deserialize on
|
||||
// public Expr. Children remain Expr, so every recursive edge enters the guard.
|
||||
#[derive(Serialize, Deserialize)]
|
||||
#[serde(remote = "Expr", deny_unknown_fields)]
|
||||
enum WireExpr {
|
||||
Boolean(bool),
|
||||
Number(Exact),
|
||||
Quantity {
|
||||
magnitude: Exact,
|
||||
unit: DefinitionRef,
|
||||
},
|
||||
Property(Id),
|
||||
Parameter(ParameterId),
|
||||
List(#[serde(deserialize_with = "bounded_list")] Vec<Expr>),
|
||||
Unary {
|
||||
op: UnaryOp,
|
||||
operand: Box<Expr>,
|
||||
},
|
||||
Binary {
|
||||
op: BinaryOp,
|
||||
left: Box<Expr>,
|
||||
right: Box<Expr>,
|
||||
},
|
||||
If {
|
||||
condition: Box<Expr>,
|
||||
when_true: Box<Expr>,
|
||||
when_false: Box<Expr>,
|
||||
},
|
||||
Call {
|
||||
definition: DefinitionRef,
|
||||
#[serde(deserialize_with = "bounded_arguments")]
|
||||
arguments: BTreeMap<ParameterId, Expr>,
|
||||
},
|
||||
Sum {
|
||||
values: Box<Expr>,
|
||||
initial: Box<Expr>,
|
||||
},
|
||||
Power {
|
||||
base: Box<Expr>,
|
||||
exponent: i8,
|
||||
},
|
||||
AsKind {
|
||||
kind: DefinitionRef,
|
||||
value: Box<Expr>,
|
||||
},
|
||||
}
|
||||
|
||||
struct ListItem {
|
||||
allowed: bool,
|
||||
}
|
||||
impl<'de> DeserializeSeed<'de> for ListItem {
|
||||
type Value = Expr;
|
||||
fn deserialize<D: serde::Deserializer<'de>>(self, deserializer: D) -> Result<Expr, D::Error> {
|
||||
if !self.allowed {
|
||||
return Err(serde::de::Error::custom(
|
||||
"Expression List exceeds 1024 items.",
|
||||
));
|
||||
}
|
||||
Expr::deserialize(deserializer)
|
||||
}
|
||||
}
|
||||
fn bounded_list<'de, D: serde::Deserializer<'de>>(deserializer: D) -> Result<Vec<Expr>, D::Error> {
|
||||
struct ListVisitor;
|
||||
impl<'de> Visitor<'de> for ListVisitor {
|
||||
type Value = Vec<Expr>;
|
||||
fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
f.write_str("at most 1024 expression items")
|
||||
}
|
||||
fn visit_seq<A: SeqAccess<'de>>(self, mut access: A) -> Result<Self::Value, A::Error> {
|
||||
let mut values = Vec::new();
|
||||
while let Some(value) = access.next_element_seed(ListItem {
|
||||
allowed: values.len() < MAX_LIST_LENGTH,
|
||||
})? {
|
||||
values.push(value);
|
||||
}
|
||||
Ok(values)
|
||||
}
|
||||
}
|
||||
deserializer.deserialize_seq(ListVisitor)
|
||||
}
|
||||
fn bounded_arguments<'de, D: serde::Deserializer<'de>>(
|
||||
deserializer: D,
|
||||
) -> Result<BTreeMap<ParameterId, Expr>, D::Error> {
|
||||
struct Arguments;
|
||||
impl<'de> Visitor<'de> for Arguments {
|
||||
type Value = BTreeMap<ParameterId, Expr>;
|
||||
fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
f.write_str("unique scoped parameter UUID keys")
|
||||
}
|
||||
fn visit_map<A: MapAccess<'de>>(self, mut access: A) -> Result<Self::Value, A::Error> {
|
||||
let mut values = BTreeMap::new();
|
||||
while let Some(id) = access.next_key::<ParameterId>()? {
|
||||
if values.contains_key(&id) {
|
||||
return Err(serde::de::Error::custom(format!(
|
||||
"Duplicate parameter ID {}",
|
||||
id.0
|
||||
)));
|
||||
}
|
||||
if values.len() >= MAX_CLOSURE_NODES {
|
||||
return Err(serde::de::Error::custom(
|
||||
"Call argument count exceeds 65536.",
|
||||
));
|
||||
}
|
||||
// Count/duplicate checks precede construction of the next subtree.
|
||||
values.insert(id, access.next_value()?);
|
||||
}
|
||||
Ok(values)
|
||||
}
|
||||
}
|
||||
deserializer.deserialize_map(Arguments)
|
||||
}
|
||||
@@ -0,0 +1,246 @@
|
||||
//! Typed live reference domains; parameter IDs and opaque historical captures are separate.
|
||||
use super::*;
|
||||
use crate::{Element, Id, Project, SharedBody};
|
||||
use std::collections::BTreeSet;
|
||||
|
||||
pub fn expression_properties(expression: &Expr) -> BTreeSet<Id> {
|
||||
let mut found = BTreeSet::new();
|
||||
walk(expression, &mut |node| {
|
||||
if let Expr::Property(id) = node {
|
||||
found.insert(*id);
|
||||
}
|
||||
});
|
||||
found
|
||||
}
|
||||
pub fn expression_definitions(expression: &Expr) -> BTreeSet<Id> {
|
||||
let mut found = BTreeSet::new();
|
||||
walk(expression, &mut |node| match node {
|
||||
Expr::Quantity { unit, .. } => {
|
||||
found.insert(unit.local());
|
||||
}
|
||||
Expr::Call { definition, .. } => {
|
||||
found.insert(definition.local());
|
||||
}
|
||||
Expr::AsKind { kind, .. } => {
|
||||
found.insert(kind.local());
|
||||
}
|
||||
_ => {}
|
||||
});
|
||||
found
|
||||
}
|
||||
pub(crate) fn walk<'a>(expression: &'a Expr, visit: &mut impl FnMut(&'a Expr)) {
|
||||
let mut pending = vec![expression];
|
||||
while let Some(node) = pending.pop() {
|
||||
visit(node);
|
||||
match node {
|
||||
Expr::List(items) => pending.extend(items.iter().rev()),
|
||||
Expr::Unary { operand, .. } => pending.push(operand),
|
||||
Expr::Binary { left, right, .. } => {
|
||||
pending.push(right);
|
||||
pending.push(left);
|
||||
}
|
||||
Expr::If {
|
||||
condition,
|
||||
when_true,
|
||||
when_false,
|
||||
} => {
|
||||
pending.push(when_false);
|
||||
pending.push(when_true);
|
||||
pending.push(condition);
|
||||
}
|
||||
Expr::Call { arguments, .. } => pending.extend(arguments.values().rev()),
|
||||
Expr::Sum { values, initial } => {
|
||||
pending.push(values);
|
||||
pending.push(initial);
|
||||
}
|
||||
Expr::Power { base, .. } => pending.push(base),
|
||||
Expr::AsKind { value, .. } => pending.push(value),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
fn walk_mut(expression: &mut Expr, visit: &mut impl FnMut(&mut Expr)) {
|
||||
let mut pending = vec![expression];
|
||||
while let Some(node) = pending.pop() {
|
||||
visit(node);
|
||||
match node {
|
||||
Expr::List(items) => pending.extend(items.iter_mut()),
|
||||
Expr::Unary { operand, .. } => pending.push(operand),
|
||||
Expr::Binary { left, right, .. } => {
|
||||
pending.push(left);
|
||||
pending.push(right);
|
||||
}
|
||||
Expr::If {
|
||||
condition,
|
||||
when_true,
|
||||
when_false,
|
||||
} => {
|
||||
pending.push(condition);
|
||||
pending.push(when_true);
|
||||
pending.push(when_false);
|
||||
}
|
||||
Expr::Call { arguments, .. } => pending.extend(arguments.values_mut()),
|
||||
Expr::Sum { values, initial } => {
|
||||
pending.push(values);
|
||||
pending.push(initial);
|
||||
}
|
||||
Expr::Power { base, .. } => pending.push(base),
|
||||
Expr::AsKind { value, .. } => pending.push(value),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
pub fn element_model_references(element: &Element) -> BTreeSet<Id> {
|
||||
let mut result = BTreeSet::new();
|
||||
let mut binding = |value: &Binding| {
|
||||
if let Binding::Expression(expression) = value {
|
||||
result.extend(expression_properties(expression));
|
||||
}
|
||||
};
|
||||
match element.shared() {
|
||||
Some(SharedBody::EngineeringProperty { base, .. }) => binding(base),
|
||||
Some(SharedBody::AnalysisCase { overrides, .. }) => {
|
||||
for value in overrides.values() {
|
||||
binding(value);
|
||||
}
|
||||
}
|
||||
Some(SharedBody::AnalysisCheck { predicate, .. }) => binding(predicate),
|
||||
_ => {}
|
||||
}
|
||||
match element.shared() {
|
||||
Some(SharedBody::EngineeringProperty { subject, .. }) => {
|
||||
result.insert(subject.id());
|
||||
}
|
||||
Some(SharedBody::AnalysisCase {
|
||||
subject, overrides, ..
|
||||
}) => {
|
||||
result.extend(subject.map(AnalysisSubject::id));
|
||||
result.extend(overrides.keys());
|
||||
}
|
||||
Some(SharedBody::AnalysisCheck {
|
||||
subject,
|
||||
documented_constraint,
|
||||
..
|
||||
}) => {
|
||||
result.extend(subject.map(AnalysisSubject::id));
|
||||
result.extend(documented_constraint);
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
result
|
||||
}
|
||||
fn remap_ref(reference: &mut DefinitionRef, old: Id, new: Id) {
|
||||
let DefinitionRef::Local(id) = reference;
|
||||
if *id == old {
|
||||
*id = new;
|
||||
}
|
||||
}
|
||||
fn remap_type(value: &mut AnalysisType, old: Id, new: Id) {
|
||||
let (AnalysisType::Scalar(scalar) | AnalysisType::List(scalar)) = value;
|
||||
if let ScalarType::Quantity(reference) = scalar {
|
||||
remap_ref(reference, old, new);
|
||||
}
|
||||
}
|
||||
fn remap_binding(value: &mut Binding, old: Id, new: Id) {
|
||||
if let Binding::Expression(expression) = value {
|
||||
walk_mut(expression, &mut |node| match node {
|
||||
Expr::Property(id) if *id == old => *id = new,
|
||||
Expr::Quantity { unit, .. } => remap_ref(unit, old, new),
|
||||
Expr::Call { definition, .. } => remap_ref(definition, old, new),
|
||||
Expr::AsKind { kind, .. } => remap_ref(kind, old, new),
|
||||
_ => {} // Parameter nodes and argument keys are scoped, never global.
|
||||
});
|
||||
}
|
||||
}
|
||||
fn remap_subject(subject: &mut AnalysisSubject, old: Id, new: Id) {
|
||||
let (AnalysisSubject::Element(id) | AnalysisSubject::Relation(id)) = subject;
|
||||
if *id == old {
|
||||
*id = new;
|
||||
}
|
||||
}
|
||||
|
||||
/// Check before any mutation so a map-key collision never silently discards a binding.
|
||||
pub(crate) fn check_remap(project: &Project, old: Id, new: Id) -> Result<(), AnalysisError> {
|
||||
if old != new {
|
||||
for element in project.elements.values() {
|
||||
if let Some(SharedBody::AnalysisCase { overrides, .. }) = element.shared()
|
||||
&& overrides.contains_key(&old)
|
||||
&& overrides.contains_key(&new)
|
||||
{
|
||||
return Err(AnalysisError::new(
|
||||
element.id,
|
||||
"overrides",
|
||||
"analysis_reference_collision",
|
||||
"Reidentification would merge two distinct override keys.",
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(crate) fn remap_project(project: &mut Project, old: Id, new: Id) {
|
||||
for element in project.elements.values_mut() {
|
||||
match element.shared_mut() {
|
||||
Some(SharedBody::EngineeringProperty {
|
||||
subject,
|
||||
value_type,
|
||||
display_unit,
|
||||
base,
|
||||
}) => {
|
||||
remap_subject(subject, old, new);
|
||||
remap_type(value_type, old, new);
|
||||
if let Some(reference) = display_unit {
|
||||
remap_ref(reference, old, new);
|
||||
}
|
||||
remap_binding(base, old, new);
|
||||
}
|
||||
Some(SharedBody::AnalysisCase {
|
||||
subject, overrides, ..
|
||||
}) => {
|
||||
if let Some(subject) = subject {
|
||||
remap_subject(subject, old, new);
|
||||
}
|
||||
if old != new
|
||||
&& let Some(value) = overrides.remove(&old)
|
||||
{
|
||||
overrides.insert(new, value);
|
||||
}
|
||||
for value in overrides.values_mut() {
|
||||
remap_binding(value, old, new);
|
||||
}
|
||||
}
|
||||
Some(SharedBody::AnalysisCheck {
|
||||
subject,
|
||||
documented_constraint,
|
||||
predicate,
|
||||
}) => {
|
||||
if let Some(subject) = subject {
|
||||
remap_subject(subject, old, new);
|
||||
}
|
||||
if *documented_constraint == Some(old) {
|
||||
*documented_constraint = Some(new);
|
||||
}
|
||||
remap_binding(predicate, old, new);
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
for definition in project.definitions.values_mut() {
|
||||
match &mut definition.body {
|
||||
DefinitionBody::QuantityKind(QuantityKindDefinition {
|
||||
algebra: QuantityAlgebra::Affine { difference },
|
||||
..
|
||||
}) => remap_ref(difference, old, new),
|
||||
DefinitionBody::Unit(unit) => remap_ref(&mut unit.kind, old, new),
|
||||
DefinitionBody::Calculation(calculation) => {
|
||||
for parameter in &mut calculation.parameters {
|
||||
remap_type(&mut parameter.value_type, old, new);
|
||||
}
|
||||
remap_type(&mut calculation.result, old, new);
|
||||
remap_binding(&mut calculation.body, old, new);
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,146 @@
|
||||
use super::*;
|
||||
use crate::analysis_numeric::{NumericType, ResolvedKind, Unit};
|
||||
use crate::{Id, Project, SharedBody};
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
/// Bounded local nominal origin; no rooted graph is cloned during arithmetic.
|
||||
/// Full ResolvedKind equality additionally includes dimension/algebra/difference.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
|
||||
pub struct KindHandle {
|
||||
model: Id,
|
||||
definition: Id,
|
||||
}
|
||||
impl KindHandle {
|
||||
pub fn definition(self) -> Id {
|
||||
self.definition
|
||||
}
|
||||
pub(crate) fn local(model: Id, definition: Id) -> Self {
|
||||
Self { model, definition }
|
||||
}
|
||||
}
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub enum ResolvedScalar {
|
||||
Boolean,
|
||||
Numeric(NumericType<KindHandle>),
|
||||
}
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub enum ResolvedType {
|
||||
Scalar(ResolvedScalar),
|
||||
List(ResolvedScalar),
|
||||
}
|
||||
impl ResolvedType {
|
||||
pub(crate) fn boolean() -> Self {
|
||||
Self::Scalar(ResolvedScalar::Boolean)
|
||||
}
|
||||
pub(crate) fn numeric(value: NumericType<KindHandle>) -> Self {
|
||||
Self::Scalar(ResolvedScalar::Numeric(value.normalized()))
|
||||
}
|
||||
}
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
pub struct EffectiveBinding<'a> {
|
||||
pub binding: &'a Binding,
|
||||
pub origin: BindingOrigin,
|
||||
}
|
||||
|
||||
/// Constructed only by admission; exact source/capture provenance stays with its owner.
|
||||
/// Values from different accepted environments must not be mixed by an evaluator.
|
||||
pub struct ResolvedAnalysis<'p> {
|
||||
pub(super) project: &'p Project,
|
||||
pub(super) kinds: BTreeMap<Id, ResolvedKind<KindHandle>>,
|
||||
pub(super) units: BTreeMap<Id, Unit<KindHandle>>,
|
||||
pub(super) limits: AdmissionLimits,
|
||||
pub(super) usage: AdmissionUsage,
|
||||
}
|
||||
impl<'p> ResolvedAnalysis<'p> {
|
||||
pub fn project(&self) -> &'p Project {
|
||||
self.project
|
||||
}
|
||||
pub fn admission_usage(&self) -> AdmissionUsage {
|
||||
self.usage
|
||||
}
|
||||
pub fn admission_limits(&self) -> AdmissionLimits {
|
||||
self.limits
|
||||
}
|
||||
pub fn definition(&self, reference: DefinitionRef) -> Option<&'p Definition> {
|
||||
self.project.definitions.get(&reference.local())
|
||||
}
|
||||
pub fn kind(&self, reference: DefinitionRef) -> Option<&ResolvedKind<KindHandle>> {
|
||||
self.kinds.get(&reference.local())
|
||||
}
|
||||
pub fn unit(&self, reference: DefinitionRef) -> Option<&Unit<KindHandle>> {
|
||||
self.units.get(&reference.local())
|
||||
}
|
||||
pub fn calculation(&self, reference: DefinitionRef) -> Option<&'p CalculationDefinition> {
|
||||
match &self.definition(reference)?.body {
|
||||
DefinitionBody::Calculation(value) => Some(value),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
pub fn declared_type(&self, value: &AnalysisType) -> Option<ResolvedType> {
|
||||
let (AnalysisType::Scalar(scalar) | AnalysisType::List(scalar)) = value;
|
||||
let scalar = match scalar {
|
||||
ScalarType::Boolean => ResolvedScalar::Boolean,
|
||||
ScalarType::Number => ResolvedScalar::Numeric(NumericType::Number),
|
||||
ScalarType::Quantity(reference) => {
|
||||
ResolvedScalar::Numeric(NumericType::Named(self.kind(*reference)?.clone()))
|
||||
}
|
||||
};
|
||||
Some(match value {
|
||||
AnalysisType::Scalar(_) => ResolvedType::Scalar(scalar),
|
||||
AnalysisType::List(_) => ResolvedType::List(scalar),
|
||||
})
|
||||
}
|
||||
pub fn effective_binding(
|
||||
&self,
|
||||
property: Id,
|
||||
context: EvaluationContext,
|
||||
) -> Result<EffectiveBinding<'p>, AnalysisError> {
|
||||
let element = self.project.elements.get(&property).ok_or_else(|| {
|
||||
AnalysisError::new(
|
||||
property,
|
||||
"context",
|
||||
"analysis_property",
|
||||
"Property does not exist.",
|
||||
)
|
||||
})?;
|
||||
let Some(SharedBody::EngineeringProperty { base, .. }) = element.shared() else {
|
||||
return Err(AnalysisError::new(
|
||||
property,
|
||||
"context",
|
||||
"analysis_property",
|
||||
"Target is not an engineering property.",
|
||||
));
|
||||
};
|
||||
if let EvaluationContext::Case(id) = context {
|
||||
let case = self.project.elements.get(&id).ok_or_else(|| {
|
||||
AnalysisError::new(id, "context", "analysis_case", "Case does not exist.")
|
||||
})?;
|
||||
let Some(SharedBody::AnalysisCase { overrides, .. }) = case.shared() else {
|
||||
return Err(AnalysisError::new(
|
||||
id,
|
||||
"context",
|
||||
"analysis_case",
|
||||
"Context is not an analysis case.",
|
||||
));
|
||||
};
|
||||
if case.layer() != element.layer() {
|
||||
return Err(AnalysisError::new(
|
||||
id,
|
||||
"context",
|
||||
"analysis_layer",
|
||||
"Case and property must share a layer.",
|
||||
));
|
||||
}
|
||||
if let Some(binding) = overrides.get(&property) {
|
||||
return Ok(EffectiveBinding {
|
||||
binding,
|
||||
origin: BindingOrigin::CaseOverride(id),
|
||||
});
|
||||
}
|
||||
}
|
||||
Ok(EffectiveBinding {
|
||||
binding: base,
|
||||
origin: BindingOrigin::ModelBaseline,
|
||||
})
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,458 @@
|
||||
//! Static expression checking shares numeric operator algebra with execution.
|
||||
use super::admission::Budget;
|
||||
use super::*;
|
||||
use crate::analysis_numeric::{NumericError, NumericType, ResolvedKind};
|
||||
use crate::{Id, Layer, SharedBody};
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
pub(super) struct BindingContext<'a> {
|
||||
pub owner: Id,
|
||||
pub field: &'a str,
|
||||
pub layer: Option<Layer>,
|
||||
pub parameters: &'a BTreeMap<ParameterId, ResolvedType>,
|
||||
}
|
||||
|
||||
pub(super) fn binding(
|
||||
environment: &ResolvedAnalysis<'_>,
|
||||
context: BindingContext<'_>,
|
||||
value: &Binding,
|
||||
expected: &ResolvedType,
|
||||
budget: &mut Budget,
|
||||
) -> Result<(), AnalysisError> {
|
||||
if let Binding::Expression(expression) = value {
|
||||
let mut checker = Checker {
|
||||
environment,
|
||||
owner: context.owner,
|
||||
field: context.field,
|
||||
layer: context.layer,
|
||||
parameters: context.parameters,
|
||||
budget,
|
||||
};
|
||||
checker.expression(expression, Some(expected))?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
struct Checker<'a, 'p, 'b> {
|
||||
environment: &'a ResolvedAnalysis<'p>,
|
||||
owner: Id,
|
||||
field: &'a str,
|
||||
layer: Option<Layer>,
|
||||
parameters: &'a BTreeMap<ParameterId, ResolvedType>,
|
||||
budget: &'b mut Budget,
|
||||
}
|
||||
|
||||
/// One suspended expression per logical depth. No Expr is owned or cloned by
|
||||
/// a frame, and every stored type/nominal handle has fixed, nonrecursive size.
|
||||
struct Frame<'e, 'p> {
|
||||
expression: &'e Expr,
|
||||
expected: Option<ResolvedType>,
|
||||
state: State<'p>,
|
||||
}
|
||||
|
||||
enum State<'p> {
|
||||
Enter,
|
||||
Unary,
|
||||
BinaryLeft,
|
||||
BinaryRight(ResolvedType),
|
||||
IfCondition,
|
||||
IfTrue,
|
||||
IfFalse(ResolvedType),
|
||||
List {
|
||||
next: usize,
|
||||
},
|
||||
Call {
|
||||
calculation: &'p CalculationDefinition,
|
||||
next: usize,
|
||||
},
|
||||
SumInitial,
|
||||
SumValues(ResolvedType),
|
||||
Power,
|
||||
AsKind(ResolvedKind<KindHandle>),
|
||||
}
|
||||
|
||||
enum Step<'e> {
|
||||
Child(&'e Expr, Option<ResolvedType>),
|
||||
Complete(ResolvedType),
|
||||
}
|
||||
|
||||
impl<'p> Checker<'_, 'p, '_> {
|
||||
fn error(&self, code: &str, message: impl Into<String>) -> AnalysisError {
|
||||
AnalysisError::new(self.owner, self.field, code, message)
|
||||
}
|
||||
fn numeric(&self, value: ResolvedType) -> Result<NumericType<KindHandle>, AnalysisError> {
|
||||
match value {
|
||||
ResolvedType::Scalar(ResolvedScalar::Numeric(value)) => Ok(value),
|
||||
_ => Err(self.error("analysis_type", "A scalar numeric operand is required.")),
|
||||
}
|
||||
}
|
||||
fn operation(
|
||||
&self,
|
||||
result: Result<NumericType<KindHandle>, NumericError>,
|
||||
) -> Result<ResolvedType, AnalysisError> {
|
||||
result
|
||||
.map(ResolvedType::numeric)
|
||||
.map_err(|error| self.error("analysis_type", error.to_string()))
|
||||
}
|
||||
|
||||
/// Explicit continuations replace Rust recursion. Width never expands the
|
||||
/// frame stack: lists and calls schedule only their next ordered child.
|
||||
/// At most 128 frames and one returned scalar/list type are retained. The
|
||||
/// per-node/per-argument meter charges remain identical to recursive entry;
|
||||
/// continuation steps do constant bounded work within those charges.
|
||||
fn expression(
|
||||
&mut self,
|
||||
expression: &Expr,
|
||||
expected: Option<&ResolvedType>,
|
||||
) -> Result<ResolvedType, AnalysisError> {
|
||||
let mut frames = Vec::with_capacity(MAX_EXPRESSION_DEPTH);
|
||||
frames.push(Frame {
|
||||
expression,
|
||||
expected: expected.cloned(),
|
||||
state: State::Enter,
|
||||
});
|
||||
let mut returned = None;
|
||||
loop {
|
||||
let frame = frames.last_mut().expect("active expression frame");
|
||||
match self.advance(frame, returned.take())? {
|
||||
Step::Child(expression, expected) => {
|
||||
if frames.len() == MAX_EXPRESSION_DEPTH {
|
||||
// Preserve entry charging/error precedence without ever
|
||||
// allocating the rejected 129th frame.
|
||||
self.budget.charge(self.owner, self.field, 1)?;
|
||||
return Err(self.error(
|
||||
"analysis_depth",
|
||||
"Expression exceeds the logical depth limit.",
|
||||
));
|
||||
}
|
||||
frames.push(Frame {
|
||||
expression,
|
||||
expected,
|
||||
state: State::Enter,
|
||||
});
|
||||
}
|
||||
Step::Complete(actual) => {
|
||||
let frame = frames.pop().expect("completed expression frame");
|
||||
let expected = frame.expected.as_ref();
|
||||
if expected.is_some_and(|expected| expected != &actual) {
|
||||
return Err(self.error(
|
||||
"analysis_type",
|
||||
format!("Expected {expected:?}; expression has {actual:?}."),
|
||||
));
|
||||
}
|
||||
if frames.is_empty() {
|
||||
return Ok(actual);
|
||||
}
|
||||
returned = Some(actual);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn advance<'e>(
|
||||
&mut self,
|
||||
frame: &mut Frame<'e, 'p>,
|
||||
returned: Option<ResolvedType>,
|
||||
) -> Result<Step<'e>, AnalysisError> {
|
||||
let state = std::mem::replace(&mut frame.state, State::Enter);
|
||||
if let State::Enter = state {
|
||||
self.budget.charge(self.owner, self.field, 1)?;
|
||||
return self.enter(frame);
|
||||
}
|
||||
let child = returned.expect("continuation follows a completed child");
|
||||
match state {
|
||||
State::Enter => unreachable!("handled before consuming child"),
|
||||
State::Unary => {
|
||||
let Expr::Unary { op, .. } = frame.expression else {
|
||||
unreachable!()
|
||||
};
|
||||
Ok(Step::Complete(match op {
|
||||
UnaryOp::Not => ResolvedType::boolean(),
|
||||
UnaryOp::Negate | UnaryOp::Absolute => {
|
||||
self.operation(self.numeric(child)?.unary_result())?
|
||||
}
|
||||
}))
|
||||
}
|
||||
State::BinaryLeft => {
|
||||
let Expr::Binary { right, .. } = frame.expression else {
|
||||
unreachable!()
|
||||
};
|
||||
frame.state = State::BinaryRight(child);
|
||||
Ok(Step::Child(right, None))
|
||||
}
|
||||
State::BinaryRight(left) => {
|
||||
let Expr::Binary { op, .. } = frame.expression else {
|
||||
unreachable!()
|
||||
};
|
||||
Ok(Step::Complete(self.binary(*op, left, child)?))
|
||||
}
|
||||
State::IfCondition => {
|
||||
let Expr::If { when_true, .. } = frame.expression else {
|
||||
unreachable!()
|
||||
};
|
||||
frame.state = State::IfTrue;
|
||||
Ok(Step::Child(when_true, frame.expected.clone()))
|
||||
}
|
||||
State::IfTrue => {
|
||||
let Expr::If { when_false, .. } = frame.expression else {
|
||||
unreachable!()
|
||||
};
|
||||
frame.state = State::IfFalse(child.clone());
|
||||
Ok(Step::Child(when_false, Some(child)))
|
||||
}
|
||||
State::IfFalse(value) => Ok(Step::Complete(value)),
|
||||
State::List { next } => {
|
||||
let ResolvedType::Scalar(scalar) = child else {
|
||||
return Err(self.error(
|
||||
"analysis_list",
|
||||
"Lists are flat; nested lists are not admitted.",
|
||||
));
|
||||
};
|
||||
let Expr::List(items) = frame.expression else {
|
||||
unreachable!()
|
||||
};
|
||||
if let Some(item) = items.get(next) {
|
||||
frame.state = State::List { next: next + 1 };
|
||||
Ok(Step::Child(item, Some(ResolvedType::Scalar(scalar))))
|
||||
} else {
|
||||
Ok(Step::Complete(ResolvedType::List(scalar)))
|
||||
}
|
||||
}
|
||||
State::Call { calculation, next } => self.call_argument(frame, calculation, next),
|
||||
State::SumInitial => {
|
||||
let numeric = self.numeric(child.clone())?;
|
||||
self.operation(numeric.unary_result())?;
|
||||
let ResolvedType::Scalar(scalar) = &child else {
|
||||
unreachable!()
|
||||
};
|
||||
let expected = ResolvedType::List(scalar.clone());
|
||||
let Expr::Sum { values, .. } = frame.expression else {
|
||||
unreachable!()
|
||||
};
|
||||
frame.state = State::SumValues(child);
|
||||
Ok(Step::Child(values, Some(expected)))
|
||||
}
|
||||
State::SumValues(initial) => {
|
||||
let numeric = self.numeric(initial.clone())?;
|
||||
self.operation(numeric.additive_result(&numeric, false))?;
|
||||
Ok(Step::Complete(initial))
|
||||
}
|
||||
State::Power => {
|
||||
let Expr::Power { exponent, .. } = frame.expression else {
|
||||
unreachable!()
|
||||
};
|
||||
Ok(Step::Complete(
|
||||
self.operation(self.numeric(child)?.power_result(*exponent))?,
|
||||
))
|
||||
}
|
||||
State::AsKind(kind) => Ok(Step::Complete(
|
||||
self.operation(self.numeric(child)?.assertion_result(&kind))?,
|
||||
)),
|
||||
}
|
||||
}
|
||||
|
||||
fn enter<'e>(&mut self, frame: &mut Frame<'e, 'p>) -> Result<Step<'e>, AnalysisError> {
|
||||
let actual = match frame.expression {
|
||||
Expr::Boolean(_) => ResolvedType::boolean(),
|
||||
Expr::Number(_) => ResolvedType::numeric(NumericType::Number),
|
||||
Expr::Quantity { unit, .. } => {
|
||||
let unit = self.environment.unit(*unit).ok_or_else(|| {
|
||||
self.error(
|
||||
"analysis_unit",
|
||||
"Quantity literal must reference an existing unit definition.",
|
||||
)
|
||||
})?;
|
||||
ResolvedType::numeric(NumericType::Named(unit.kind().clone()))
|
||||
}
|
||||
Expr::Property(id) => {
|
||||
let layer = self.layer.ok_or_else(|| {
|
||||
self.error(
|
||||
"analysis_purity",
|
||||
"Reusable calculations cannot capture project properties.",
|
||||
)
|
||||
})?;
|
||||
let element =
|
||||
self.environment.project.elements.get(id).ok_or_else(|| {
|
||||
self.error("analysis_property", "Property does not exist.")
|
||||
})?;
|
||||
let Some(SharedBody::EngineeringProperty { value_type, .. }) = element.shared()
|
||||
else {
|
||||
return Err(self.error(
|
||||
"analysis_property",
|
||||
"Reference must target an engineering property.",
|
||||
));
|
||||
};
|
||||
if element.layer() != layer {
|
||||
return Err(self.error(
|
||||
"analysis_layer",
|
||||
"Property references must stay in the same layer.",
|
||||
));
|
||||
}
|
||||
self.environment.declared_type(value_type).ok_or_else(|| {
|
||||
self.error("analysis_kind", "Declared property kind does not resolve.")
|
||||
})?
|
||||
}
|
||||
Expr::Parameter(id) => self.parameters.get(id).cloned().ok_or_else(|| {
|
||||
self.error(
|
||||
"analysis_parameter",
|
||||
"Parameter does not belong to this calculation definition.",
|
||||
)
|
||||
})?,
|
||||
Expr::List(items) => {
|
||||
if items.len() > MAX_LIST_LENGTH {
|
||||
return Err(
|
||||
self.error("analysis_list", "List exceeds the flat-list length limit.")
|
||||
);
|
||||
}
|
||||
let scalar = match &frame.expected {
|
||||
Some(ResolvedType::List(value)) => Some(value.clone()),
|
||||
_ => None,
|
||||
};
|
||||
if let Some(item) = items.first() {
|
||||
frame.state = State::List { next: 1 };
|
||||
return Ok(Step::Child(item, scalar.map(ResolvedType::Scalar)));
|
||||
}
|
||||
ResolvedType::List(scalar.ok_or_else(|| {
|
||||
self.error(
|
||||
"analysis_list",
|
||||
"An empty list requires an explicit surrounding list type.",
|
||||
)
|
||||
})?)
|
||||
}
|
||||
Expr::Unary { op, operand } => {
|
||||
frame.state = State::Unary;
|
||||
let expected = (*op == UnaryOp::Not).then(ResolvedType::boolean);
|
||||
return Ok(Step::Child(operand, expected));
|
||||
}
|
||||
Expr::Binary { left, .. } => {
|
||||
frame.state = State::BinaryLeft;
|
||||
return Ok(Step::Child(left, None));
|
||||
}
|
||||
Expr::If { condition, .. } => {
|
||||
frame.state = State::IfCondition;
|
||||
return Ok(Step::Child(condition, Some(ResolvedType::boolean())));
|
||||
}
|
||||
Expr::Call {
|
||||
definition,
|
||||
arguments,
|
||||
} => {
|
||||
let calculation = self.environment.calculation(*definition).ok_or_else(|| {
|
||||
self.error(
|
||||
"analysis_calculation",
|
||||
"Call must reference a calculation definition.",
|
||||
)
|
||||
})?;
|
||||
if arguments.len() != calculation.parameters.len() {
|
||||
return Err(self.error("analysis_arguments", "Call arguments must bind every declared parameter exactly once, by its scoped identity."));
|
||||
}
|
||||
// Charge the complete key scan before any parameter lookup.
|
||||
self.budget
|
||||
.charge(self.owner, self.field, calculation.parameters.len() as u64)?;
|
||||
if calculation
|
||||
.parameters
|
||||
.iter()
|
||||
.any(|parameter| !arguments.contains_key(¶meter.id))
|
||||
{
|
||||
return Err(self.error("analysis_arguments", "Call arguments must bind every declared parameter exactly once, by its scoped identity."));
|
||||
}
|
||||
return self.call_argument(frame, calculation, 0);
|
||||
}
|
||||
Expr::Sum { initial, .. } => {
|
||||
frame.state = State::SumInitial;
|
||||
return Ok(Step::Child(initial, None));
|
||||
}
|
||||
Expr::Power { base, .. } => {
|
||||
frame.state = State::Power;
|
||||
return Ok(Step::Child(base, None));
|
||||
}
|
||||
Expr::AsKind { kind, value } => {
|
||||
let kind = self
|
||||
.environment
|
||||
.kind(*kind)
|
||||
.ok_or_else(|| {
|
||||
self.error(
|
||||
"analysis_kind",
|
||||
"Kind assertion must reference a quantity kind.",
|
||||
)
|
||||
})?
|
||||
.clone();
|
||||
frame.state = State::AsKind(kind);
|
||||
return Ok(Step::Child(value, None));
|
||||
}
|
||||
};
|
||||
Ok(Step::Complete(actual))
|
||||
}
|
||||
|
||||
/// Arguments follow parameter declaration order, not UUID map order. Retain
|
||||
/// the resolved calculation by reference and schedule one argument at a time.
|
||||
fn call_argument<'e>(
|
||||
&mut self,
|
||||
frame: &mut Frame<'e, 'p>,
|
||||
calculation: &'p CalculationDefinition,
|
||||
next: usize,
|
||||
) -> Result<Step<'e>, AnalysisError> {
|
||||
if let Some(parameter) = calculation.parameters.get(next) {
|
||||
self.budget.charge(self.owner, self.field, 1)?;
|
||||
let expected = self
|
||||
.environment
|
||||
.declared_type(¶meter.value_type)
|
||||
.ok_or_else(|| self.error("analysis_kind", "Parameter kind does not resolve."))?;
|
||||
let Expr::Call { arguments, .. } = frame.expression else {
|
||||
unreachable!()
|
||||
};
|
||||
frame.state = State::Call {
|
||||
calculation,
|
||||
next: next + 1,
|
||||
};
|
||||
Ok(Step::Child(&arguments[¶meter.id], Some(expected)))
|
||||
} else {
|
||||
let result = self
|
||||
.environment
|
||||
.declared_type(&calculation.result)
|
||||
.ok_or_else(|| {
|
||||
self.error("analysis_kind", "Calculation result kind does not resolve.")
|
||||
})?;
|
||||
Ok(Step::Complete(result))
|
||||
}
|
||||
}
|
||||
|
||||
fn binary(
|
||||
&self,
|
||||
op: BinaryOp,
|
||||
left: ResolvedType,
|
||||
right: ResolvedType,
|
||||
) -> Result<ResolvedType, AnalysisError> {
|
||||
match op {
|
||||
BinaryOp::And | BinaryOp::Or => {
|
||||
if left != ResolvedType::boolean() || right != ResolvedType::boolean() {
|
||||
return Err(self.error("analysis_type", "Boolean operands are required."));
|
||||
}
|
||||
Ok(ResolvedType::boolean())
|
||||
}
|
||||
BinaryOp::Equal | BinaryOp::NotEqual
|
||||
if left == ResolvedType::boolean() && right == ResolvedType::boolean() =>
|
||||
{
|
||||
Ok(ResolvedType::boolean())
|
||||
}
|
||||
BinaryOp::Equal
|
||||
| BinaryOp::NotEqual
|
||||
| BinaryOp::Less
|
||||
| BinaryOp::LessOrEqual
|
||||
| BinaryOp::Greater
|
||||
| BinaryOp::GreaterOrEqual => {
|
||||
self.numeric(left)?
|
||||
.comparison_compatible(&self.numeric(right)?)
|
||||
.map_err(|error| self.error("analysis_type", error.to_string()))?;
|
||||
Ok(ResolvedType::boolean())
|
||||
}
|
||||
BinaryOp::Add | BinaryOp::Subtract => self.operation(
|
||||
self.numeric(left)?
|
||||
.additive_result(&self.numeric(right)?, op == BinaryOp::Subtract),
|
||||
),
|
||||
BinaryOp::Multiply | BinaryOp::Divide => self.operation(
|
||||
self.numeric(left)?
|
||||
.multiplicative_result(&self.numeric(right)?, op == BinaryOp::Divide),
|
||||
),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,213 @@
|
||||
//! Persistent analysis vocabulary. This is part of Project, not an evaluation model.
|
||||
use crate::Id;
|
||||
use crate::analysis_numeric::{Dimension, Exact};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
/// Only real local definitions are admitted in schema 8's first environment.
|
||||
/// Imported references require the separately implemented pinned package catalog.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub enum DefinitionRef {
|
||||
Local(Id),
|
||||
}
|
||||
impl DefinitionRef {
|
||||
pub fn local(self) -> Id {
|
||||
match self {
|
||||
Self::Local(id) => id,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Qualified by its owning CalculationDefinition; never a global model identity.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
|
||||
#[serde(transparent)]
|
||||
pub struct ParameterId(pub Id);
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct Definition {
|
||||
pub id: Id,
|
||||
pub alias: String,
|
||||
pub name: String,
|
||||
pub description: String,
|
||||
pub body: DefinitionBody,
|
||||
}
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub enum DefinitionBody {
|
||||
QuantityKind(QuantityKindDefinition),
|
||||
Unit(UnitDefinition),
|
||||
Calculation(CalculationDefinition),
|
||||
}
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct QuantityKindDefinition {
|
||||
pub dimension: Dimension,
|
||||
pub algebra: QuantityAlgebra,
|
||||
}
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub enum QuantityAlgebra {
|
||||
Linear,
|
||||
Affine { difference: DefinitionRef },
|
||||
}
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct UnitDefinition {
|
||||
pub kind: DefinitionRef,
|
||||
pub scale: Exact,
|
||||
pub offset: Exact,
|
||||
pub symbol: String,
|
||||
}
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub enum ScalarType {
|
||||
Boolean,
|
||||
Number,
|
||||
Quantity(DefinitionRef),
|
||||
}
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub enum AnalysisType {
|
||||
Scalar(ScalarType),
|
||||
List(ScalarType),
|
||||
}
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct Parameter {
|
||||
pub id: ParameterId,
|
||||
pub name: String,
|
||||
pub value_type: AnalysisType,
|
||||
}
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct CalculationDefinition {
|
||||
pub parameters: Vec<Parameter>,
|
||||
pub result: AnalysisType,
|
||||
pub body: Binding,
|
||||
}
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub enum Binding {
|
||||
Unbound,
|
||||
Expression(Expr),
|
||||
}
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub enum UnaryOp {
|
||||
Negate,
|
||||
Absolute,
|
||||
Not,
|
||||
}
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub enum BinaryOp {
|
||||
Add,
|
||||
Subtract,
|
||||
Multiply,
|
||||
Divide,
|
||||
Equal,
|
||||
NotEqual,
|
||||
Less,
|
||||
LessOrEqual,
|
||||
Greater,
|
||||
GreaterOrEqual,
|
||||
And,
|
||||
Or,
|
||||
}
|
||||
pub enum Expr {
|
||||
Boolean(bool),
|
||||
Number(Exact),
|
||||
Quantity {
|
||||
magnitude: Exact,
|
||||
unit: DefinitionRef,
|
||||
},
|
||||
Property(Id),
|
||||
Parameter(ParameterId),
|
||||
List(Vec<Expr>),
|
||||
Unary {
|
||||
op: UnaryOp,
|
||||
operand: Box<Expr>,
|
||||
},
|
||||
Binary {
|
||||
op: BinaryOp,
|
||||
left: Box<Expr>,
|
||||
right: Box<Expr>,
|
||||
},
|
||||
If {
|
||||
condition: Box<Expr>,
|
||||
when_true: Box<Expr>,
|
||||
when_false: Box<Expr>,
|
||||
},
|
||||
Call {
|
||||
definition: DefinitionRef,
|
||||
arguments: BTreeMap<ParameterId, Expr>,
|
||||
},
|
||||
Sum {
|
||||
values: Box<Expr>,
|
||||
initial: Box<Expr>,
|
||||
},
|
||||
Power {
|
||||
base: Box<Expr>,
|
||||
exponent: i8,
|
||||
},
|
||||
AsKind {
|
||||
kind: DefinitionRef,
|
||||
value: Box<Expr>,
|
||||
},
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub enum AnalysisSubject {
|
||||
Element(Id),
|
||||
Relation(Id),
|
||||
}
|
||||
impl AnalysisSubject {
|
||||
pub fn id(self) -> Id {
|
||||
match self {
|
||||
Self::Element(id) | Self::Relation(id) => id,
|
||||
}
|
||||
}
|
||||
}
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub enum BaselineBase {
|
||||
ModelBaseline,
|
||||
}
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub enum EvaluationContext {
|
||||
ModelBaseline,
|
||||
Case(Id),
|
||||
}
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub enum BindingOrigin {
|
||||
ModelBaseline,
|
||||
CaseOverride(Id),
|
||||
}
|
||||
|
||||
/// Located structural/static admission failure, not a false or failed evaluation.
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, thiserror::Error)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
#[error("{code} at {object}.{field}: {message}")]
|
||||
pub struct AnalysisError {
|
||||
pub object: Id,
|
||||
pub field: String,
|
||||
pub code: String,
|
||||
pub message: String,
|
||||
}
|
||||
impl AnalysisError {
|
||||
pub(crate) fn new(
|
||||
object: Id,
|
||||
field: impl Into<String>,
|
||||
code: &str,
|
||||
message: impl Into<String>,
|
||||
) -> Self {
|
||||
Self {
|
||||
object,
|
||||
field: field.into(),
|
||||
code: code.into(),
|
||||
message: message.into(),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,103 @@
|
||||
//! Exact numeric foundation for analysis; no model, expression, or package resolver.
|
||||
//!
|
||||
//! Values use reduced rational coordinates. All nontrivial arithmetic takes one
|
||||
//! request-local [WorkMeter]. The future evaluator must also charge *expanded*
|
||||
//! expression/call/property/list/target visits and retain the same logical walk on
|
||||
//! cache hits. Stored AST size is not a dynamic execution limit.
|
||||
//!
|
||||
//! Approximate engineering functions/irrational unit scales require a subsequent
|
||||
//! explicit numeric profile; rationals do not implement degree/radian conversion
|
||||
//! or transcendental mathematics.
|
||||
|
||||
mod dimension;
|
||||
mod exact;
|
||||
mod meter;
|
||||
mod quantity;
|
||||
|
||||
pub use dimension::{Dimension, DimensionAxis};
|
||||
pub use exact::{Exact, ExactWire};
|
||||
pub use meter::{
|
||||
EvaluationStep, NumericOperation, WorkExhaustion, WorkLimits, WorkMeter, WorkResource,
|
||||
WorkSite, WorkUsage,
|
||||
};
|
||||
pub use quantity::{NumericType, NumericValue, ResolvedKind, Unit};
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
use thiserror::Error;
|
||||
|
||||
/// Profile identity includes the accounting rules, not crate-internal timing.
|
||||
pub const WORK_PROFILE: &str = "Q1-logical-work-1";
|
||||
pub const MAX_COMPONENT_BITS: u64 = 4096;
|
||||
/// Cross products require 8192 bits; their sum can require one additional bit.
|
||||
pub const MAX_INTERMEDIATE_BITS: u64 = 8193;
|
||||
pub const MAX_COMPONENT_DIGITS: usize = 1234;
|
||||
pub const MAX_DECIMAL_EXPONENT: i32 = 128;
|
||||
pub const MAX_INTEGER_POWER: i8 = 16;
|
||||
/// Includes ratio punctuation/whitespace without permitting unbounded scanning.
|
||||
pub const MAX_LITERAL_BYTES: usize = 2 * MAX_COMPONENT_DIGITS + 32;
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub enum NumberComponent {
|
||||
Numerator,
|
||||
Denominator,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Error, Serialize, Deserialize)]
|
||||
pub enum NumericLimit {
|
||||
#[error("request work exhausted: {0}")]
|
||||
Work(WorkExhaustion),
|
||||
#[error("{component:?} uses {bits} bits, above the {limit}-bit {stage} limit")]
|
||||
Bits {
|
||||
component: NumberComponent,
|
||||
bits: u64,
|
||||
limit: u64,
|
||||
stage: String,
|
||||
},
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Error, Serialize, Deserialize)]
|
||||
pub enum NumericError {
|
||||
#[error("numeric limit: {0}")]
|
||||
Limit(NumericLimit),
|
||||
#[error("invalid numeric literal")]
|
||||
InvalidLiteral,
|
||||
#[error("numeric literal exceeds its digit or byte limit")]
|
||||
LiteralTooLong,
|
||||
#[error("decimal exponent is outside -128 through 128")]
|
||||
DecimalExponent,
|
||||
#[error("wire rational is not in canonical reduced form")]
|
||||
NonCanonicalWire,
|
||||
#[error("rational denominator is zero")]
|
||||
ZeroDenominator,
|
||||
#[error("division by zero")]
|
||||
DivisionByZero,
|
||||
#[error("zero to the power zero is undefined in this profile")]
|
||||
ZeroPowerZero,
|
||||
#[error("integer power is outside -16 through 16")]
|
||||
IntegerPower,
|
||||
#[error("dimension exponent at {axis:?} is outside -32 through 32: {value}")]
|
||||
DimensionExponent { axis: DimensionAxis, value: i32 },
|
||||
#[error("unit scale must be strictly positive")]
|
||||
UnitScale,
|
||||
#[error("a linear unit must have zero offset")]
|
||||
LinearOffset,
|
||||
#[error("an affine point must have a distinct linear difference kind")]
|
||||
DifferenceKind,
|
||||
#[error("numeric kinds or dimensions are incompatible")]
|
||||
IncompatibleTypes,
|
||||
#[error("operation is not defined for affine points")]
|
||||
AffineOperation,
|
||||
#[error("AsKind requires an anonymous matching dimension and a linear target")]
|
||||
KindAssertion,
|
||||
#[error("request work limits exceed the provisional reference ceilings")]
|
||||
InvalidWorkLimits,
|
||||
}
|
||||
|
||||
impl NumericError {
|
||||
pub fn is_terminal_work_exhaustion(&self) -> bool {
|
||||
matches!(self, Self::Limit(NumericLimit::Work(_)))
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
@@ -0,0 +1,107 @@
|
||||
use super::NumericError;
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub enum DimensionAxis {
|
||||
Length,
|
||||
Mass,
|
||||
Time,
|
||||
ElectricCurrent,
|
||||
Temperature,
|
||||
Amount,
|
||||
LuminousIntensity,
|
||||
}
|
||||
|
||||
impl DimensionAxis {
|
||||
pub const ALL: [Self; 7] = [
|
||||
Self::Length,
|
||||
Self::Mass,
|
||||
Self::Time,
|
||||
Self::ElectricCurrent,
|
||||
Self::Temperature,
|
||||
Self::Amount,
|
||||
Self::LuminousIntensity,
|
||||
];
|
||||
}
|
||||
|
||||
/// SI base-dimension vector in DimensionAxis::ALL order, each entry -32..=32.
|
||||
/// This is a dimension, never a nominal quantity-kind compatibility proof.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
|
||||
#[serde(try_from = "[i16; 7]", into = "[i16; 7]")]
|
||||
pub struct Dimension([i16; 7]);
|
||||
|
||||
impl Dimension {
|
||||
pub const ZERO: Self = Self([0; 7]);
|
||||
|
||||
pub fn new(exponents: [i16; 7]) -> Result<Self, NumericError> {
|
||||
for (index, value) in exponents.iter().copied().enumerate() {
|
||||
if !(-32..=32).contains(&value) {
|
||||
return Err(NumericError::DimensionExponent {
|
||||
axis: DimensionAxis::ALL[index],
|
||||
value: i32::from(value),
|
||||
});
|
||||
}
|
||||
}
|
||||
Ok(Self(exponents))
|
||||
}
|
||||
|
||||
pub fn exponents(self) -> [i16; 7] {
|
||||
self.0
|
||||
}
|
||||
|
||||
pub fn is_dimensionless(self) -> bool {
|
||||
self == Self::ZERO
|
||||
}
|
||||
|
||||
pub fn checked_product(self, rhs: Self) -> Result<Self, NumericError> {
|
||||
self.combine(rhs, 1)
|
||||
}
|
||||
|
||||
pub fn checked_quotient(self, rhs: Self) -> Result<Self, NumericError> {
|
||||
self.combine(rhs, -1)
|
||||
}
|
||||
|
||||
pub fn checked_power(self, exponent: i8) -> Result<Self, NumericError> {
|
||||
if !(-super::MAX_INTEGER_POWER..=super::MAX_INTEGER_POWER).contains(&exponent) {
|
||||
return Err(NumericError::IntegerPower);
|
||||
}
|
||||
let mut output = [0; 7];
|
||||
for (index, value) in self.0.iter().enumerate() {
|
||||
output[index] = Self::checked_exponent(index, i32::from(*value) * i32::from(exponent))?;
|
||||
}
|
||||
Ok(Self(output))
|
||||
}
|
||||
|
||||
fn combine(self, rhs: Self, sign: i32) -> Result<Self, NumericError> {
|
||||
let mut output = [0; 7];
|
||||
for (index, value) in self.0.iter().enumerate() {
|
||||
output[index] =
|
||||
Self::checked_exponent(index, i32::from(*value) + sign * i32::from(rhs.0[index]))?;
|
||||
}
|
||||
Ok(Self(output))
|
||||
}
|
||||
|
||||
fn checked_exponent(index: usize, value: i32) -> Result<i16, NumericError> {
|
||||
if !(-32..=32).contains(&value) {
|
||||
return Err(NumericError::DimensionExponent {
|
||||
axis: DimensionAxis::ALL[index],
|
||||
value,
|
||||
});
|
||||
}
|
||||
Ok(value as i16)
|
||||
}
|
||||
}
|
||||
|
||||
impl TryFrom<[i16; 7]> for Dimension {
|
||||
type Error = NumericError;
|
||||
|
||||
fn try_from(value: [i16; 7]) -> Result<Self, Self::Error> {
|
||||
Self::new(value)
|
||||
}
|
||||
}
|
||||
|
||||
impl From<Dimension> for [i16; 7] {
|
||||
fn from(value: Dimension) -> Self {
|
||||
value.0
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,469 @@
|
||||
use super::meter::{normalization_cost, parse_cost, product_cost, sum_cost, words};
|
||||
use super::{
|
||||
MAX_COMPONENT_BITS, MAX_COMPONENT_DIGITS, MAX_DECIMAL_EXPONENT, MAX_INTEGER_POWER,
|
||||
MAX_INTERMEDIATE_BITS, MAX_LITERAL_BYTES, NumberComponent, NumericError, NumericLimit,
|
||||
NumericOperation, WorkLimits, WorkMeter,
|
||||
};
|
||||
use num_bigint::BigInt;
|
||||
use num_integer::Integer;
|
||||
use num_traits::{One, Signed, Zero};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::cmp::Ordering;
|
||||
|
||||
/// The interchange representation deliberately does not use num-bigint's serde
|
||||
/// format or JSON numeric values. Duplicate/missing/unknown fields reject.
|
||||
/// Its derived decoder allocates String fields before numeric validation; a
|
||||
/// transport/document adapter must bound the encoded envelope and decoded text.
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct ExactWire {
|
||||
pub numerator: String,
|
||||
pub denominator: String,
|
||||
}
|
||||
|
||||
/// Reduced rational with positive denominator and <=4096-bit components.
|
||||
///
|
||||
/// There are no unmetered arithmetic/ordering traits. Eq is structural equality
|
||||
/// of already normalized bounded values, not an expression comparison API.
|
||||
/// Standalone serde admission bounds the subsequent BigInt validation, not the
|
||||
/// preceding String decoding. Document adapters must bound encoded/decoded input
|
||||
/// and aggregate admission work. Evaluation uses one explicit WorkMeter.
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(try_from = "ExactWire", into = "ExactWire")]
|
||||
pub struct Exact {
|
||||
numerator: BigInt,
|
||||
denominator: BigInt,
|
||||
}
|
||||
|
||||
impl Exact {
|
||||
pub fn from_integer(value: i64) -> Self {
|
||||
Self {
|
||||
numerator: BigInt::from(value),
|
||||
denominator: BigInt::one(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn is_zero(&self) -> bool {
|
||||
self.numerator.is_zero()
|
||||
}
|
||||
|
||||
pub fn is_positive(&self) -> bool {
|
||||
self.numerator.is_positive()
|
||||
}
|
||||
|
||||
pub fn component_bits(&self) -> (u64, u64) {
|
||||
(self.numerator.bits(), self.denominator.bits())
|
||||
}
|
||||
|
||||
pub fn to_wire(&self) -> ExactWire {
|
||||
ExactWire {
|
||||
numerator: self.numerator.to_string(),
|
||||
denominator: self.denominator.to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Canonical *literal* spelling, not a generic expression formatter.
|
||||
/// Negative literal nodes use ratio(-n,d), even when d=1. A leading minus
|
||||
/// belongs to the future expression parser's UnaryNegate node instead.
|
||||
pub fn canonical_literal(&self) -> String {
|
||||
if self.denominator.is_one() && !self.numerator.is_negative() {
|
||||
self.numerator.to_string()
|
||||
} else {
|
||||
format!("ratio({}, {})", self.numerator, self.denominator)
|
||||
}
|
||||
}
|
||||
|
||||
pub fn from_wire(wire: &ExactWire, meter: &mut WorkMeter) -> Result<Self, NumericError> {
|
||||
meter.ensure_active()?;
|
||||
let n_digits = wire_digits(&wire.numerator, true)?;
|
||||
let d_digits = wire_digits(&wire.denominator, false)?;
|
||||
let n_bound = decimal_bits(n_digits.len());
|
||||
let d_bound = decimal_bits(d_digits.len());
|
||||
meter.numeric(
|
||||
NumericOperation::ParseWire,
|
||||
parse_cost(n_digits.len(), n_bound)
|
||||
+ parse_cost(d_digits.len(), d_bound)
|
||||
+ normalization_cost(n_bound, d_bound),
|
||||
)?;
|
||||
let numerator = parse_integer(&wire.numerator)?;
|
||||
let denominator = parse_integer(&wire.denominator)?;
|
||||
Self::check_bits(&numerator, &denominator, MAX_COMPONENT_BITS, "wire")?;
|
||||
if denominator.is_zero() {
|
||||
return Err(NumericError::ZeroDenominator);
|
||||
}
|
||||
if !numerator.gcd(&denominator).is_one() {
|
||||
return Err(NumericError::NonCanonicalWire);
|
||||
}
|
||||
Ok(Self {
|
||||
numerator,
|
||||
denominator,
|
||||
})
|
||||
}
|
||||
|
||||
/// Reads one unsigned decimal/integer atom or a ratio(n,d) literal only.
|
||||
/// It does not parse expressions, unary operators, units, calls or names.
|
||||
/// Source ratios/decimals may reduce; wire values must already be canonical.
|
||||
pub fn parse_literal(source: &str, meter: &mut WorkMeter) -> Result<Self, NumericError> {
|
||||
meter.ensure_active()?;
|
||||
if source.len() > MAX_LITERAL_BYTES {
|
||||
return Err(NumericError::LiteralTooLong);
|
||||
}
|
||||
let source = trim_ascii(source);
|
||||
if let Some(body) = source.strip_prefix("ratio(") {
|
||||
let body = body.strip_suffix(')').ok_or(NumericError::InvalidLiteral)?;
|
||||
let (n, d) = body.split_once(',').ok_or(NumericError::InvalidLiteral)?;
|
||||
return Self::parse_ratio(trim_ascii(n), trim_ascii(d), meter);
|
||||
}
|
||||
Self::parse_decimal(source, meter)
|
||||
}
|
||||
|
||||
fn parse_ratio(n: &str, d: &str, meter: &mut WorkMeter) -> Result<Self, NumericError> {
|
||||
let n_digits = source_integer_digits(n, true)?;
|
||||
let d_digits = source_integer_digits(d, false)?;
|
||||
let n_bound = decimal_bits(n_digits.len());
|
||||
let d_bound = decimal_bits(d_digits.len());
|
||||
Self::check_estimates(n_bound, d_bound)?;
|
||||
meter.numeric(
|
||||
NumericOperation::ParseLiteral,
|
||||
parse_cost(n_digits.len(), n_bound)
|
||||
+ parse_cost(d_digits.len(), d_bound)
|
||||
+ normalization_cost(n_bound, d_bound),
|
||||
)?;
|
||||
Self::normalize_precharged(parse_integer(n)?, parse_integer(d)?)
|
||||
}
|
||||
|
||||
fn parse_decimal(source: &str, meter: &mut WorkMeter) -> Result<Self, NumericError> {
|
||||
let mut parts = source.split(['e', 'E']);
|
||||
let mantissa = parts.next().ok_or(NumericError::InvalidLiteral)?;
|
||||
let exponent = match parts.next() {
|
||||
Some(text) => parse_exponent(text)?,
|
||||
None => 0,
|
||||
};
|
||||
if parts.next().is_some() {
|
||||
return Err(NumericError::InvalidLiteral);
|
||||
}
|
||||
let (whole, fraction) = match mantissa.split_once('.') {
|
||||
Some((whole, fraction)) if !fraction.is_empty() => (whole, fraction),
|
||||
Some(_) => return Err(NumericError::InvalidLiteral),
|
||||
None => (mantissa, ""),
|
||||
};
|
||||
source_integer_digits(whole, false)?;
|
||||
if !fraction.bytes().all(|byte| byte.is_ascii_digit()) {
|
||||
return Err(NumericError::InvalidLiteral);
|
||||
}
|
||||
let digit_count = whole.len() + fraction.len();
|
||||
if digit_count > MAX_COMPONENT_DIGITS {
|
||||
return Err(NumericError::LiteralTooLong);
|
||||
}
|
||||
let adjustment = exponent - fraction.len() as i32;
|
||||
let power = adjustment.unsigned_abs();
|
||||
let mantissa_bound = decimal_bits(digit_count);
|
||||
let scale_bound = decimal_bits(power as usize + 1);
|
||||
let (n_bound, d_bound) = if adjustment >= 0 {
|
||||
(mantissa_bound + scale_bound, 1)
|
||||
} else {
|
||||
(mantissa_bound, scale_bound)
|
||||
};
|
||||
Self::check_estimates(n_bound, d_bound)?;
|
||||
// Fixed logical allowance for constructing 10^power; independent of
|
||||
// num-bigint's selected multiplication/exponentiation implementation.
|
||||
let power_steps = 1 + 2 * u64::from(u32::BITS - power.leading_zeros());
|
||||
meter.numeric(
|
||||
NumericOperation::ParseLiteral,
|
||||
parse_cost(digit_count, mantissa_bound)
|
||||
+ power_steps * product_cost(scale_bound, scale_bound)
|
||||
+ product_cost(mantissa_bound, scale_bound)
|
||||
+ normalization_cost(n_bound, d_bound),
|
||||
)?;
|
||||
let digits = format!("{whole}{fraction}");
|
||||
let mut numerator = parse_integer(&digits)?;
|
||||
let scale = BigInt::from(10_u8).pow(power);
|
||||
let denominator = if adjustment >= 0 {
|
||||
numerator *= scale;
|
||||
BigInt::one()
|
||||
} else {
|
||||
scale
|
||||
};
|
||||
Self::normalize_precharged(numerator, denominator)
|
||||
}
|
||||
|
||||
pub fn add(&self, rhs: &Self, meter: &mut WorkMeter) -> Result<Self, NumericError> {
|
||||
self.add_or_subtract(rhs, false, meter)
|
||||
}
|
||||
|
||||
pub fn subtract(&self, rhs: &Self, meter: &mut WorkMeter) -> Result<Self, NumericError> {
|
||||
self.add_or_subtract(rhs, true, meter)
|
||||
}
|
||||
|
||||
fn add_or_subtract(
|
||||
&self,
|
||||
rhs: &Self,
|
||||
subtract: bool,
|
||||
meter: &mut WorkMeter,
|
||||
) -> Result<Self, NumericError> {
|
||||
let (a, b) = self.component_bits();
|
||||
let (c, d) = rhs.component_bits();
|
||||
let left_bound = a + d;
|
||||
let right_bound = c + b;
|
||||
let n_bound = left_bound.max(right_bound) + 1;
|
||||
let d_bound = b + d;
|
||||
Self::check_estimates(n_bound, d_bound)?;
|
||||
meter.numeric(
|
||||
if subtract {
|
||||
NumericOperation::Subtract
|
||||
} else {
|
||||
NumericOperation::Add
|
||||
},
|
||||
product_cost(a, d)
|
||||
+ product_cost(c, b)
|
||||
+ sum_cost(left_bound, right_bound)
|
||||
+ product_cost(b, d)
|
||||
+ normalization_cost(n_bound, d_bound),
|
||||
)?;
|
||||
let left = &self.numerator * &rhs.denominator;
|
||||
let right = &rhs.numerator * &self.denominator;
|
||||
let numerator = if subtract { left - right } else { left + right };
|
||||
let denominator = &self.denominator * &rhs.denominator;
|
||||
Self::normalize_precharged(numerator, denominator)
|
||||
}
|
||||
|
||||
pub fn multiply(&self, rhs: &Self, meter: &mut WorkMeter) -> Result<Self, NumericError> {
|
||||
let (a, b) = self.component_bits();
|
||||
let (c, d) = rhs.component_bits();
|
||||
Self::check_estimates(a + c, b + d)?;
|
||||
meter.numeric(
|
||||
NumericOperation::Multiply,
|
||||
product_cost(a, c) + product_cost(b, d) + normalization_cost(a + c, b + d),
|
||||
)?;
|
||||
Self::normalize_precharged(
|
||||
&self.numerator * &rhs.numerator,
|
||||
&self.denominator * &rhs.denominator,
|
||||
)
|
||||
}
|
||||
|
||||
pub fn divide(&self, rhs: &Self, meter: &mut WorkMeter) -> Result<Self, NumericError> {
|
||||
let (a, b) = self.component_bits();
|
||||
let (c, d) = rhs.component_bits();
|
||||
Self::check_estimates(a + d, b + c)?;
|
||||
meter.numeric(
|
||||
NumericOperation::Divide,
|
||||
product_cost(a, d) + product_cost(b, c) + normalization_cost(a + d, b + c),
|
||||
)?;
|
||||
if rhs.is_zero() {
|
||||
return Err(NumericError::DivisionByZero);
|
||||
}
|
||||
Self::normalize_precharged(
|
||||
&self.numerator * &rhs.denominator,
|
||||
&self.denominator * &rhs.numerator,
|
||||
)
|
||||
}
|
||||
|
||||
pub fn compare(&self, rhs: &Self, meter: &mut WorkMeter) -> Result<Ordering, NumericError> {
|
||||
let (a, b) = self.component_bits();
|
||||
let (c, d) = rhs.component_bits();
|
||||
Self::check_estimates((a + d).max(c + b), 1)?;
|
||||
meter.numeric(
|
||||
NumericOperation::Compare,
|
||||
product_cost(a, d) + product_cost(c, b) + sum_cost(a + d, c + b),
|
||||
)?;
|
||||
Ok((&self.numerator * &rhs.denominator).cmp(&(&rhs.numerator * &self.denominator)))
|
||||
}
|
||||
|
||||
pub fn negated(&self, meter: &mut WorkMeter) -> Result<Self, NumericError> {
|
||||
meter.numeric(NumericOperation::Negate, self.copy_cost())?;
|
||||
Ok(Self {
|
||||
numerator: -&self.numerator,
|
||||
denominator: self.denominator.clone(),
|
||||
})
|
||||
}
|
||||
|
||||
pub fn absolute(&self, meter: &mut WorkMeter) -> Result<Self, NumericError> {
|
||||
meter.numeric(NumericOperation::Absolute, self.copy_cost())?;
|
||||
Ok(Self {
|
||||
numerator: self.numerator.abs(),
|
||||
denominator: self.denominator.clone(),
|
||||
})
|
||||
}
|
||||
|
||||
pub fn reciprocal(&self, meter: &mut WorkMeter) -> Result<Self, NumericError> {
|
||||
meter.numeric(NumericOperation::Reciprocal, self.copy_cost())?;
|
||||
if self.is_zero() {
|
||||
return Err(NumericError::DivisionByZero);
|
||||
}
|
||||
Ok(Self {
|
||||
numerator: if self.numerator.is_negative() {
|
||||
-&self.denominator
|
||||
} else {
|
||||
self.denominator.clone()
|
||||
},
|
||||
denominator: self.numerator.abs(),
|
||||
})
|
||||
}
|
||||
|
||||
/// Fixed left-to-right repeated multiplication, at most 16 multiplications.
|
||||
/// Each reduced stage obeys the same component bound; no large power is
|
||||
/// allocated and subsequently discarded after discovering it is oversized.
|
||||
pub fn power(&self, exponent: i8, meter: &mut WorkMeter) -> Result<Self, NumericError> {
|
||||
meter.numeric(NumericOperation::Power, self.copy_cost())?;
|
||||
if !(-MAX_INTEGER_POWER..=MAX_INTEGER_POWER).contains(&exponent) {
|
||||
return Err(NumericError::IntegerPower);
|
||||
}
|
||||
if self.is_zero() && exponent == 0 {
|
||||
return Err(NumericError::ZeroPowerZero);
|
||||
}
|
||||
let factor = if exponent < 0 {
|
||||
self.reciprocal(meter)?
|
||||
} else {
|
||||
self.clone()
|
||||
};
|
||||
let mut value = Self::from_integer(1);
|
||||
for _ in 0..exponent.unsigned_abs() {
|
||||
value = value.multiply(&factor, meter)?;
|
||||
}
|
||||
Ok(value)
|
||||
}
|
||||
|
||||
pub(super) fn copy_cost(&self) -> u64 {
|
||||
let (n, d) = self.component_bits();
|
||||
1 + words(n) + words(d)
|
||||
}
|
||||
|
||||
fn normalize_precharged(
|
||||
mut numerator: BigInt,
|
||||
mut denominator: BigInt,
|
||||
) -> Result<Self, NumericError> {
|
||||
Self::check_bits(
|
||||
&numerator,
|
||||
&denominator,
|
||||
MAX_INTERMEDIATE_BITS,
|
||||
"intermediate",
|
||||
)?;
|
||||
if denominator.is_zero() {
|
||||
return Err(NumericError::ZeroDenominator);
|
||||
}
|
||||
if denominator.is_negative() {
|
||||
numerator = -numerator;
|
||||
denominator = -denominator;
|
||||
}
|
||||
let gcd = numerator.gcd(&denominator);
|
||||
numerator /= &gcd;
|
||||
denominator /= gcd;
|
||||
Self::check_bits(&numerator, &denominator, MAX_COMPONENT_BITS, "reduced")?;
|
||||
Ok(Self {
|
||||
numerator,
|
||||
denominator,
|
||||
})
|
||||
}
|
||||
|
||||
fn check_estimates(n: u64, d: u64) -> Result<(), NumericError> {
|
||||
Self::check_bit_count(
|
||||
n,
|
||||
NumberComponent::Numerator,
|
||||
MAX_INTERMEDIATE_BITS,
|
||||
"predicted",
|
||||
)?;
|
||||
Self::check_bit_count(
|
||||
d,
|
||||
NumberComponent::Denominator,
|
||||
MAX_INTERMEDIATE_BITS,
|
||||
"predicted",
|
||||
)
|
||||
}
|
||||
|
||||
fn check_bits(n: &BigInt, d: &BigInt, limit: u64, stage: &str) -> Result<(), NumericError> {
|
||||
Self::check_bit_count(n.bits(), NumberComponent::Numerator, limit, stage)?;
|
||||
Self::check_bit_count(d.bits(), NumberComponent::Denominator, limit, stage)
|
||||
}
|
||||
|
||||
fn check_bit_count(
|
||||
bits: u64,
|
||||
component: NumberComponent,
|
||||
limit: u64,
|
||||
stage: &str,
|
||||
) -> Result<(), NumericError> {
|
||||
if bits > limit {
|
||||
return Err(NumericError::Limit(NumericLimit::Bits {
|
||||
component,
|
||||
bits,
|
||||
limit,
|
||||
stage: stage.to_owned(),
|
||||
}));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl TryFrom<ExactWire> for Exact {
|
||||
type Error = NumericError;
|
||||
|
||||
fn try_from(value: ExactWire) -> Result<Self, Self::Error> {
|
||||
// BigInt validation is bounded after ExactWire strings have decoded.
|
||||
// The adapter owns envelope/text/aggregate admission bounds and must not
|
||||
// reset evaluation meters.
|
||||
Self::from_wire(&value, &mut WorkMeter::new(WorkLimits::REFERENCE))
|
||||
}
|
||||
}
|
||||
|
||||
impl From<Exact> for ExactWire {
|
||||
fn from(value: Exact) -> Self {
|
||||
value.to_wire()
|
||||
}
|
||||
}
|
||||
|
||||
fn trim_ascii(text: &str) -> &str {
|
||||
text.trim_matches(|ch: char| ch.is_ascii_whitespace())
|
||||
}
|
||||
|
||||
fn source_integer_digits(text: &str, signed: bool) -> Result<&str, NumericError> {
|
||||
let digits = if signed {
|
||||
text.strip_prefix('-').unwrap_or(text)
|
||||
} else {
|
||||
text
|
||||
};
|
||||
if digits.len() > MAX_COMPONENT_DIGITS {
|
||||
return Err(NumericError::LiteralTooLong);
|
||||
}
|
||||
if digits.is_empty() || !digits.bytes().all(|byte| byte.is_ascii_digit()) {
|
||||
return Err(NumericError::InvalidLiteral);
|
||||
}
|
||||
Ok(digits)
|
||||
}
|
||||
|
||||
fn wire_digits(text: &str, signed: bool) -> Result<&str, NumericError> {
|
||||
let digits = source_integer_digits(text, signed).map_err(|error| match error {
|
||||
NumericError::LiteralTooLong => error,
|
||||
_ => NumericError::NonCanonicalWire,
|
||||
})?;
|
||||
if (digits.len() > 1 && digits.starts_with('0')) || (text.starts_with('-') && digits == "0") {
|
||||
return Err(NumericError::NonCanonicalWire);
|
||||
}
|
||||
Ok(digits)
|
||||
}
|
||||
|
||||
fn parse_integer(text: &str) -> Result<BigInt, NumericError> {
|
||||
BigInt::parse_bytes(text.as_bytes(), 10).ok_or(NumericError::InvalidLiteral)
|
||||
}
|
||||
|
||||
fn parse_exponent(text: &str) -> Result<i32, NumericError> {
|
||||
let (negative, digits) = if let Some(digits) = text.strip_prefix('-') {
|
||||
(true, digits)
|
||||
} else {
|
||||
(false, text.strip_prefix('+').unwrap_or(text))
|
||||
};
|
||||
if digits.is_empty() || !digits.bytes().all(|byte| byte.is_ascii_digit()) {
|
||||
return Err(NumericError::InvalidLiteral);
|
||||
}
|
||||
let mut value = 0_i32;
|
||||
for digit in digits.bytes() {
|
||||
value = value * 10 + i32::from(digit - b'0');
|
||||
if value > MAX_DECIMAL_EXPONENT {
|
||||
return Err(NumericError::DecimalExponent);
|
||||
}
|
||||
}
|
||||
Ok(if negative { -value } else { value })
|
||||
}
|
||||
|
||||
fn decimal_bits(digits: usize) -> u64 {
|
||||
// 3.322 exceeds log2(10); dimensions are bounded before this conversion.
|
||||
(digits as u64 * 3322).div_ceil(1000).max(1)
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
[
|
||||
{
|
||||
"canonical_source": "1000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000",
|
||||
"expression": {
|
||||
"Number": {
|
||||
"denominator": "1",
|
||||
"numerator": "1000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000"
|
||||
}
|
||||
},
|
||||
"name": "ten_to_300"
|
||||
},
|
||||
{
|
||||
"canonical_source": "ratio(1, 522194440706576253345876355358312191289982124523691890192116741641976953985778728424413405967498779170445053357219631418993786719092896803631618043925682638972978488271854999170180795067191859157214035005927973113188159419698856372836167342172293308748403954352901852035642024370059304557233988891799014503343469488440893892973452815095130470299789726716411734651513348221529512507986199933857107770846917779942645743159118957217248367043905936319748237550094520674504208530837546834166925275516486044134775384991808184705966507606898412918594045916828375610659246423184062775112999150206172392431297837246097308511903252956622805412865917690043804311051417135098849101156584508839003337597742539960818209685142687562392007453579567729991395256699805775897135553415567045292136442139895777424891477161767258532611634530697452993846501061481697843891439474220308003706472837459911525285821188577408160690315522951458068463354171428220365223949985950890732881736611925133626529949897998045399734600887312408859224933727829625089164535236559716582775403784110923285873186648442456409760158728501220463308455437074192539205964902261490928669488824051563042951500651206733594863336608245755565801460390869016718045121902354170201577095168)",
|
||||
"expression": {
|
||||
"Number": {
|
||||
"denominator": "522194440706576253345876355358312191289982124523691890192116741641976953985778728424413405967498779170445053357219631418993786719092896803631618043925682638972978488271854999170180795067191859157214035005927973113188159419698856372836167342172293308748403954352901852035642024370059304557233988891799014503343469488440893892973452815095130470299789726716411734651513348221529512507986199933857107770846917779942645743159118957217248367043905936319748237550094520674504208530837546834166925275516486044134775384991808184705966507606898412918594045916828375610659246423184062775112999150206172392431297837246097308511903252956622805412865917690043804311051417135098849101156584508839003337597742539960818209685142687562392007453579567729991395256699805775897135553415567045292136442139895777424891477161767258532611634530697452993846501061481697843891439474220308003706472837459911525285821188577408160690315522951458068463354171428220365223949985950890732881736611925133626529949897998045399734600887312408859224933727829625089164535236559716582775403784110923285873186648442456409760158728501220463308455437074192539205964902261490928669488824051563042951500651206733594863336608245755565801460390869016718045121902354170201577095168",
|
||||
"numerator": "1"
|
||||
}
|
||||
},
|
||||
"name": "one_over_two_to_4095"
|
||||
},
|
||||
{
|
||||
"canonical_source": "ratio(-1044388881413152506691752710716624382579964249047383780384233483283953907971557456848826811934997558340890106714439262837987573438185793607263236087851365277945956976543709998340361590134383718314428070011855946226376318839397712745672334684344586617496807908705803704071284048740118609114467977783598029006686938976881787785946905630190260940599579453432823469303026696443059025015972399867714215541693835559885291486318237914434496734087811872639496475100189041349008417061675093668333850551032972088269550769983616369411933015213796825837188091833656751221318492846368125550225998300412344784862595674492194617023806505913245610825731835380087608622102834270197698202313169017678006675195485079921636419370285375124784014907159135459982790513399611551794271106831134090584272884279791554849782954323534517065223269061394905987693002122963395687782878948440616007412945674919823050571642377154816321380631045902916136926708342856440730447899971901781465763473223850267253059899795996090799469201774624817718449867455659250178329070473119433165550807568221846571746373296884912819520317457002440926616910874148385078411929804522981857338977648103126085903001302413467189726673216491511131602920781738033436090243804708340403154190335, 1)",
|
||||
"expression": {
|
||||
"Number": {
|
||||
"denominator": "1",
|
||||
"numerator": "-1044388881413152506691752710716624382579964249047383780384233483283953907971557456848826811934997558340890106714439262837987573438185793607263236087851365277945956976543709998340361590134383718314428070011855946226376318839397712745672334684344586617496807908705803704071284048740118609114467977783598029006686938976881787785946905630190260940599579453432823469303026696443059025015972399867714215541693835559885291486318237914434496734087811872639496475100189041349008417061675093668333850551032972088269550769983616369411933015213796825837188091833656751221318492846368125550225998300412344784862595674492194617023806505913245610825731835380087608622102834270197698202313169017678006675195485079921636419370285375124784014907159135459982790513399611551794271106831134090584272884279791554849782954323534517065223269061394905987693002122963395687782878948440616007412945674919823050571642377154816321380631045902916136926708342856440730447899971901781465763473223850267253059899795996090799469201774624817718449867455659250178329070473119433165550807568221846571746373296884912819520317457002440926616910874148385078411929804522981857338977648103126085903001302413467189726673216491511131602920781738033436090243804708340403154190335"
|
||||
}
|
||||
},
|
||||
"name": "negative_4096_bit_bound"
|
||||
}
|
||||
]
|
||||
@@ -0,0 +1,240 @@
|
||||
use super::{NumericError, NumericLimit};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use thiserror::Error;
|
||||
|
||||
/// Every event is charged once per dynamic occurrence, before entering it.
|
||||
///
|
||||
/// A Call expression therefore charges Expression and CalculationEntry; a
|
||||
/// Property read charges Expression and PropertyBinding. List element visits
|
||||
/// are additional to evaluation of their expressions. Only executed branches
|
||||
/// are charged. Targets are sorted by category (properties, then checks), then
|
||||
/// stable UUID bytes, by the integrating evaluator.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub enum EvaluationStep {
|
||||
Target,
|
||||
Expression,
|
||||
CalculationEntry,
|
||||
PropertyBinding,
|
||||
ListElement,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub enum NumericOperation {
|
||||
ParseWire,
|
||||
ParseLiteral,
|
||||
Add,
|
||||
Subtract,
|
||||
Multiply,
|
||||
Divide,
|
||||
Compare,
|
||||
Negate,
|
||||
Absolute,
|
||||
Reciprocal,
|
||||
Power,
|
||||
KindAssertion,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub enum WorkResource {
|
||||
DynamicEvents,
|
||||
NumericUnits,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub enum WorkSite {
|
||||
Evaluation(EvaluationStep),
|
||||
Numeric(NumericOperation),
|
||||
}
|
||||
|
||||
/// Failed reservations consume no partial charge. The first failure is latched.
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Error, Serialize, Deserialize)]
|
||||
#[error("{resource:?}: used {used}, requested {requested}, limit {limit}, at {site:?}")]
|
||||
pub struct WorkExhaustion {
|
||||
pub resource: WorkResource,
|
||||
pub used: u64,
|
||||
pub requested: u64,
|
||||
pub limit: u64,
|
||||
pub site: WorkSite,
|
||||
}
|
||||
|
||||
/// Provisional calibration ceilings, not measured execution-time guarantees.
|
||||
///
|
||||
/// Effective limits, profile identity, capture, targets and context must all be
|
||||
/// recorded in request/result/frozen identity. A caller may lower these ceilings.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(try_from = "WorkLimitsWire", into = "WorkLimitsWire")]
|
||||
pub struct WorkLimits {
|
||||
dynamic_events: u64,
|
||||
numeric_units: u64,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
struct WorkLimitsWire {
|
||||
dynamic_events: u64,
|
||||
numeric_units: u64,
|
||||
}
|
||||
|
||||
impl WorkLimits {
|
||||
pub const REFERENCE: Self = Self {
|
||||
dynamic_events: 1_000_000,
|
||||
numeric_units: 50_000_000,
|
||||
};
|
||||
|
||||
pub fn new(dynamic_events: u64, numeric_units: u64) -> Result<Self, NumericError> {
|
||||
if dynamic_events > Self::REFERENCE.dynamic_events
|
||||
|| numeric_units > Self::REFERENCE.numeric_units
|
||||
{
|
||||
return Err(NumericError::InvalidWorkLimits);
|
||||
}
|
||||
Ok(Self {
|
||||
dynamic_events,
|
||||
numeric_units,
|
||||
})
|
||||
}
|
||||
|
||||
pub fn dynamic_events(self) -> u64 {
|
||||
self.dynamic_events
|
||||
}
|
||||
|
||||
pub fn numeric_units(self) -> u64 {
|
||||
self.numeric_units
|
||||
}
|
||||
}
|
||||
|
||||
impl TryFrom<WorkLimitsWire> for WorkLimits {
|
||||
type Error = NumericError;
|
||||
|
||||
fn try_from(value: WorkLimitsWire) -> Result<Self, Self::Error> {
|
||||
Self::new(value.dynamic_events, value.numeric_units)
|
||||
}
|
||||
}
|
||||
|
||||
impl From<WorkLimits> for WorkLimitsWire {
|
||||
fn from(value: WorkLimits) -> Self {
|
||||
Self {
|
||||
dynamic_events: value.dynamic_events,
|
||||
numeric_units: value.numeric_units,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct WorkUsage {
|
||||
pub dynamic_events: u64,
|
||||
pub numeric_units: u64,
|
||||
}
|
||||
|
||||
/// Intentionally neither Clone nor Default: pass the same mutable meter through
|
||||
/// every target, numeric operation and expanded call in one evaluation request.
|
||||
///
|
||||
/// Exhaustion is terminal. Integrators must stop traversing siblings/targets and
|
||||
/// mark already collected causes as incomplete. Replaying an aggregate cache
|
||||
/// cost is insufficient if it changes the exact exhaustion location; initially
|
||||
/// retain logical traversal even when numerical values come from a cache.
|
||||
#[derive(Debug)]
|
||||
pub struct WorkMeter {
|
||||
limits: WorkLimits,
|
||||
usage: WorkUsage,
|
||||
exhausted: Option<WorkExhaustion>,
|
||||
}
|
||||
|
||||
impl WorkMeter {
|
||||
pub fn new(limits: WorkLimits) -> Self {
|
||||
Self {
|
||||
limits,
|
||||
usage: WorkUsage::default(),
|
||||
exhausted: None,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn limits(&self) -> WorkLimits {
|
||||
self.limits
|
||||
}
|
||||
|
||||
pub fn usage(&self) -> WorkUsage {
|
||||
self.usage
|
||||
}
|
||||
|
||||
pub fn exhaustion(&self) -> Option<&WorkExhaustion> {
|
||||
self.exhausted.as_ref()
|
||||
}
|
||||
|
||||
pub fn ensure_active(&self) -> Result<(), NumericError> {
|
||||
match &self.exhausted {
|
||||
Some(failure) => Err(NumericError::Limit(NumericLimit::Work(failure.clone()))),
|
||||
None => Ok(()),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn visit(&mut self, step: EvaluationStep) -> Result<(), NumericError> {
|
||||
self.reserve(WorkResource::DynamicEvents, 1, WorkSite::Evaluation(step))
|
||||
}
|
||||
|
||||
pub(super) fn numeric(
|
||||
&mut self,
|
||||
operation: NumericOperation,
|
||||
units: u64,
|
||||
) -> Result<(), NumericError> {
|
||||
self.reserve(
|
||||
WorkResource::NumericUnits,
|
||||
units,
|
||||
WorkSite::Numeric(operation),
|
||||
)
|
||||
}
|
||||
|
||||
fn reserve(
|
||||
&mut self,
|
||||
resource: WorkResource,
|
||||
requested: u64,
|
||||
site: WorkSite,
|
||||
) -> Result<(), NumericError> {
|
||||
self.ensure_active()?;
|
||||
let (used, limit) = match resource {
|
||||
WorkResource::DynamicEvents => (self.usage.dynamic_events, self.limits.dynamic_events),
|
||||
WorkResource::NumericUnits => (self.usage.numeric_units, self.limits.numeric_units),
|
||||
};
|
||||
// Subtraction is safe: only successful reservations update usage.
|
||||
if requested > limit - used {
|
||||
let failure = WorkExhaustion {
|
||||
resource,
|
||||
used,
|
||||
requested,
|
||||
limit,
|
||||
site,
|
||||
};
|
||||
self.exhausted = Some(failure.clone());
|
||||
return Err(NumericError::Limit(NumericLimit::Work(failure)));
|
||||
}
|
||||
match resource {
|
||||
WorkResource::DynamicEvents => self.usage.dynamic_events += requested,
|
||||
WorkResource::NumericUnits => self.usage.numeric_units += requested,
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
// Logical 64-bit words are platform independent. These are deterministic
|
||||
// accounting weights, not a claim about num-bigint's internal algorithm/timing.
|
||||
pub(super) fn words(bits: u64) -> u64 {
|
||||
bits.max(1).div_ceil(64)
|
||||
}
|
||||
|
||||
pub(super) fn product_cost(a_bits: u64, b_bits: u64) -> u64 {
|
||||
1 + words(a_bits) * words(b_bits)
|
||||
}
|
||||
|
||||
pub(super) fn sum_cost(a_bits: u64, b_bits: u64) -> u64 {
|
||||
1 + words(a_bits.max(b_bits))
|
||||
}
|
||||
|
||||
pub(super) fn normalization_cost(n_bits: u64, d_bits: u64) -> u64 {
|
||||
let width = words(n_bits.max(d_bits));
|
||||
// 64*w² for GCD plus 2*w² for the two quotient operations.
|
||||
1 + 66 * width * width
|
||||
}
|
||||
|
||||
pub(super) fn parse_cost(digits: usize, estimated_bits: u64) -> u64 {
|
||||
1 + digits as u64 * words(estimated_bits)
|
||||
}
|
||||
@@ -0,0 +1,385 @@
|
||||
use super::{Dimension, Exact, MAX_INTEGER_POWER, NumericError, NumericOperation, WorkMeter};
|
||||
use std::cmp::Ordering;
|
||||
|
||||
/// K is supplied by the common resolver's verified nominal compatibility
|
||||
/// relation. It is not inferred from dimension/name/symbol/archive bytes here.
|
||||
/// Coordinate basis/algebra/difference-kind closure must be part of that proof.
|
||||
/// Exact definition references and pins remain the caller's provenance.
|
||||
/// K must be a bounded, cheap-to-clone/compare verified handle. Constructing or
|
||||
/// comparing an unbounded rooted contract graph is resolver admission work and
|
||||
/// must not be hidden inside K's Clone/Eq implementations. Rust trait bounds do
|
||||
/// not enforce this resource contract.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct ResolvedKind<K> {
|
||||
key: K,
|
||||
dimension: Dimension,
|
||||
difference: Option<K>,
|
||||
}
|
||||
|
||||
impl<K> ResolvedKind<K> {
|
||||
pub fn linear(key: K, dimension: Dimension) -> Self {
|
||||
Self {
|
||||
key,
|
||||
dimension,
|
||||
difference: None,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn key(&self) -> &K {
|
||||
&self.key
|
||||
}
|
||||
|
||||
pub fn dimension(&self) -> Dimension {
|
||||
self.dimension
|
||||
}
|
||||
|
||||
pub fn is_affine(&self) -> bool {
|
||||
self.difference.is_some()
|
||||
}
|
||||
}
|
||||
|
||||
impl<K: Clone + Eq> ResolvedKind<K> {
|
||||
pub fn affine(key: K, difference: &Self) -> Result<Self, NumericError> {
|
||||
if difference.is_affine() || key == difference.key {
|
||||
return Err(NumericError::DifferenceKind);
|
||||
}
|
||||
Ok(Self {
|
||||
key,
|
||||
dimension: difference.dimension,
|
||||
difference: Some(difference.key.clone()),
|
||||
})
|
||||
}
|
||||
|
||||
pub fn difference_kind(&self) -> Option<Self> {
|
||||
self.difference
|
||||
.as_ref()
|
||||
.map(|key| Self::linear(key.clone(), self.dimension))
|
||||
}
|
||||
}
|
||||
|
||||
/// Canonical coordinate = magnitude * scale + offset.
|
||||
/// Unit symbols and display preferences are outside this numeric representation.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct Unit<K> {
|
||||
kind: ResolvedKind<K>,
|
||||
scale: Exact,
|
||||
offset: Exact,
|
||||
}
|
||||
|
||||
impl<K: Clone + Eq> Unit<K> {
|
||||
pub fn new(kind: ResolvedKind<K>, scale: Exact, offset: Exact) -> Result<Self, NumericError> {
|
||||
if !scale.is_positive() {
|
||||
return Err(NumericError::UnitScale);
|
||||
}
|
||||
if !kind.is_affine() && !offset.is_zero() {
|
||||
return Err(NumericError::LinearOffset);
|
||||
}
|
||||
Ok(Self {
|
||||
kind,
|
||||
scale,
|
||||
offset,
|
||||
})
|
||||
}
|
||||
|
||||
pub fn kind(&self) -> &ResolvedKind<K> {
|
||||
&self.kind
|
||||
}
|
||||
|
||||
pub fn scale(&self) -> &Exact {
|
||||
&self.scale
|
||||
}
|
||||
|
||||
pub fn offset(&self) -> &Exact {
|
||||
&self.offset
|
||||
}
|
||||
|
||||
/// Fixed multiply-then-add path. Each reduced arithmetic stage is bounded.
|
||||
/// A mathematically cancelling wider intermediate still reports NumericLimit;
|
||||
/// replacing this path with a fused operation requires a new work profile.
|
||||
pub fn to_canonical(
|
||||
&self,
|
||||
magnitude: &Exact,
|
||||
meter: &mut WorkMeter,
|
||||
) -> Result<Exact, NumericError> {
|
||||
magnitude
|
||||
.multiply(&self.scale, meter)?
|
||||
.add(&self.offset, meter)
|
||||
}
|
||||
|
||||
/// Fixed subtract-then-divide path; never rounds a coordinate.
|
||||
pub fn from_canonical(
|
||||
&self,
|
||||
coordinate: &Exact,
|
||||
meter: &mut WorkMeter,
|
||||
) -> Result<Exact, NumericError> {
|
||||
coordinate
|
||||
.subtract(&self.offset, meter)?
|
||||
.divide(&self.scale, meter)
|
||||
}
|
||||
|
||||
pub fn convert(
|
||||
&self,
|
||||
magnitude: &Exact,
|
||||
target: &Self,
|
||||
meter: &mut WorkMeter,
|
||||
) -> Result<Exact, NumericError> {
|
||||
meter.ensure_active()?;
|
||||
if self.kind != target.kind {
|
||||
return Err(NumericError::IncompatibleTypes);
|
||||
}
|
||||
target.from_canonical(&self.to_canonical(magnitude, meter)?, meter)
|
||||
}
|
||||
}
|
||||
|
||||
/// Internal numerical types. Boolean/list/check semantics belong to the common
|
||||
/// expression evaluator. Anonymous zero dimension normalizes to Number.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub enum NumericType<K> {
|
||||
Number,
|
||||
Named(ResolvedKind<K>),
|
||||
Anonymous(Dimension),
|
||||
}
|
||||
|
||||
impl<K> NumericType<K> {
|
||||
pub fn dimension(&self) -> Dimension {
|
||||
match self {
|
||||
Self::Number => Dimension::ZERO,
|
||||
Self::Named(kind) => kind.dimension,
|
||||
Self::Anonymous(dimension) => *dimension,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn is_affine(&self) -> bool {
|
||||
matches!(self, Self::Named(kind) if kind.is_affine())
|
||||
}
|
||||
|
||||
pub fn anonymous(dimension: Dimension) -> Self {
|
||||
if dimension.is_dimensionless() {
|
||||
Self::Number
|
||||
} else {
|
||||
Self::Anonymous(dimension)
|
||||
}
|
||||
}
|
||||
|
||||
pub fn normalized(self) -> Self {
|
||||
match self {
|
||||
Self::Anonymous(dimension) => Self::anonymous(dimension),
|
||||
other => other,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<K: Clone + Eq> NumericType<K> {
|
||||
/// Pure R6 algebra; does not evaluate coordinates or domain conditions.
|
||||
pub fn additive_result(&self, rhs: &Self, subtract: bool) -> Result<Self, NumericError> {
|
||||
use NumericType::{Anonymous, Named, Number};
|
||||
let (left, right) = (self.clone().normalized(), rhs.clone().normalized());
|
||||
match (&left, &right) {
|
||||
(Number, Number) => Ok(Number),
|
||||
(Anonymous(a), Anonymous(b)) if a == b => Ok(Anonymous(*a)),
|
||||
(Named(a), Named(b)) => match (&a.difference, &b.difference) {
|
||||
(None, None) if a == b => Ok(Named(a.clone())),
|
||||
(Some(difference), Some(_)) if subtract && a == b => {
|
||||
Ok(Named(ResolvedKind::linear(difference.clone(), a.dimension)))
|
||||
}
|
||||
(Some(difference), None) if difference == &b.key && a.dimension == b.dimension => {
|
||||
Ok(Named(a.clone()))
|
||||
}
|
||||
(None, Some(difference))
|
||||
if !subtract && difference == &a.key && a.dimension == b.dimension =>
|
||||
{
|
||||
Ok(Named(b.clone()))
|
||||
}
|
||||
_ => Err(NumericError::IncompatibleTypes),
|
||||
},
|
||||
_ => Err(NumericError::IncompatibleTypes),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn multiplicative_result(&self, rhs: &Self, divide: bool) -> Result<Self, NumericError> {
|
||||
use NumericType::Number;
|
||||
let (left, right) = (self.clone().normalized(), rhs.clone().normalized());
|
||||
if left.is_affine() || right.is_affine() {
|
||||
return Err(NumericError::AffineOperation);
|
||||
}
|
||||
match (&left, &right) {
|
||||
(Number, Number) => Ok(Number),
|
||||
(_, Number) => Ok(left),
|
||||
(Number, _) if !divide => Ok(right),
|
||||
_ => Ok(Self::anonymous(if divide {
|
||||
left.dimension().checked_quotient(right.dimension())?
|
||||
} else {
|
||||
left.dimension().checked_product(right.dimension())?
|
||||
})),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn unary_result(&self) -> Result<Self, NumericError> {
|
||||
if self.is_affine() {
|
||||
Err(NumericError::AffineOperation)
|
||||
} else {
|
||||
Ok(self.clone().normalized())
|
||||
}
|
||||
}
|
||||
|
||||
pub fn power_result(&self, exponent: i8) -> Result<Self, NumericError> {
|
||||
if !(-MAX_INTEGER_POWER..=MAX_INTEGER_POWER).contains(&exponent) {
|
||||
return Err(NumericError::IntegerPower);
|
||||
}
|
||||
if self.is_affine() {
|
||||
return Err(NumericError::AffineOperation);
|
||||
}
|
||||
Ok(match exponent {
|
||||
0 => Self::Number,
|
||||
1 => self.clone().normalized(),
|
||||
_ => Self::anonymous(self.dimension().checked_power(exponent)?),
|
||||
})
|
||||
}
|
||||
|
||||
pub fn comparison_compatible(&self, rhs: &Self) -> Result<(), NumericError> {
|
||||
if self.clone().normalized() == rhs.clone().normalized() {
|
||||
Ok(())
|
||||
} else {
|
||||
Err(NumericError::IncompatibleTypes)
|
||||
}
|
||||
}
|
||||
|
||||
pub fn assertion_result(&self, target: &ResolvedKind<K>) -> Result<Self, NumericError> {
|
||||
if target.is_affine()
|
||||
|| matches!(self, Self::Named(_))
|
||||
|| self.dimension() != target.dimension
|
||||
{
|
||||
Err(NumericError::KindAssertion)
|
||||
} else {
|
||||
Ok(Self::Named(target.clone()))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A canonical rational coordinate with an internal numerical type.
|
||||
///
|
||||
/// Derived Eq compares stored representation. Formal equality/ordering must call
|
||||
/// compare(), which rejects mismatched nominal kinds instead of treating them
|
||||
/// as a false predicate. Public property output must still check its declared
|
||||
/// type and anchor the result to that declaration's exact definition reference.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct NumericValue<K> {
|
||||
value_type: NumericType<K>,
|
||||
coordinate: Exact,
|
||||
}
|
||||
|
||||
impl<K: Clone + Eq> NumericValue<K> {
|
||||
pub fn new(value_type: NumericType<K>, coordinate: Exact) -> Self {
|
||||
Self {
|
||||
value_type: value_type.normalized(),
|
||||
coordinate,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn number(coordinate: Exact) -> Self {
|
||||
Self::new(NumericType::Number, coordinate)
|
||||
}
|
||||
|
||||
pub fn from_unit(
|
||||
magnitude: &Exact,
|
||||
unit: &Unit<K>,
|
||||
meter: &mut WorkMeter,
|
||||
) -> Result<Self, NumericError> {
|
||||
meter.ensure_active()?;
|
||||
Ok(Self::new(
|
||||
NumericType::Named(unit.kind.clone()),
|
||||
unit.to_canonical(magnitude, meter)?,
|
||||
))
|
||||
}
|
||||
|
||||
pub fn value_type(&self) -> &NumericType<K> {
|
||||
&self.value_type
|
||||
}
|
||||
|
||||
pub fn coordinate(&self) -> &Exact {
|
||||
&self.coordinate
|
||||
}
|
||||
|
||||
pub fn display_in(&self, unit: &Unit<K>, meter: &mut WorkMeter) -> Result<Exact, NumericError> {
|
||||
meter.ensure_active()?;
|
||||
if !matches!(&self.value_type, NumericType::Named(kind) if kind == &unit.kind) {
|
||||
return Err(NumericError::IncompatibleTypes);
|
||||
}
|
||||
unit.from_canonical(&self.coordinate, meter)
|
||||
}
|
||||
|
||||
pub fn add(&self, rhs: &Self, meter: &mut WorkMeter) -> Result<Self, NumericError> {
|
||||
meter.ensure_active()?;
|
||||
let output = self.value_type.additive_result(&rhs.value_type, false)?;
|
||||
Ok(Self::new(
|
||||
output,
|
||||
self.coordinate.add(&rhs.coordinate, meter)?,
|
||||
))
|
||||
}
|
||||
|
||||
pub fn subtract(&self, rhs: &Self, meter: &mut WorkMeter) -> Result<Self, NumericError> {
|
||||
meter.ensure_active()?;
|
||||
let output = self.value_type.additive_result(&rhs.value_type, true)?;
|
||||
Ok(Self::new(
|
||||
output,
|
||||
self.coordinate.subtract(&rhs.coordinate, meter)?,
|
||||
))
|
||||
}
|
||||
|
||||
pub fn multiply(&self, rhs: &Self, meter: &mut WorkMeter) -> Result<Self, NumericError> {
|
||||
meter.ensure_active()?;
|
||||
let output = self
|
||||
.value_type
|
||||
.multiplicative_result(&rhs.value_type, false)?;
|
||||
Ok(Self::new(
|
||||
output,
|
||||
self.coordinate.multiply(&rhs.coordinate, meter)?,
|
||||
))
|
||||
}
|
||||
|
||||
pub fn divide(&self, rhs: &Self, meter: &mut WorkMeter) -> Result<Self, NumericError> {
|
||||
meter.ensure_active()?;
|
||||
let output = self
|
||||
.value_type
|
||||
.multiplicative_result(&rhs.value_type, true)?;
|
||||
Ok(Self::new(
|
||||
output,
|
||||
self.coordinate.divide(&rhs.coordinate, meter)?,
|
||||
))
|
||||
}
|
||||
|
||||
pub fn negated(&self, meter: &mut WorkMeter) -> Result<Self, NumericError> {
|
||||
meter.ensure_active()?;
|
||||
let output = self.value_type.unary_result()?;
|
||||
Ok(Self::new(output, self.coordinate.negated(meter)?))
|
||||
}
|
||||
|
||||
pub fn absolute(&self, meter: &mut WorkMeter) -> Result<Self, NumericError> {
|
||||
meter.ensure_active()?;
|
||||
let output = self.value_type.unary_result()?;
|
||||
Ok(Self::new(output, self.coordinate.absolute(meter)?))
|
||||
}
|
||||
|
||||
pub fn power(&self, exponent: i8, meter: &mut WorkMeter) -> Result<Self, NumericError> {
|
||||
meter.ensure_active()?;
|
||||
let output = self.value_type.power_result(exponent)?;
|
||||
Ok(Self::new(output, self.coordinate.power(exponent, meter)?))
|
||||
}
|
||||
|
||||
pub fn compare(&self, rhs: &Self, meter: &mut WorkMeter) -> Result<Ordering, NumericError> {
|
||||
meter.ensure_active()?;
|
||||
self.value_type.comparison_compatible(&rhs.value_type)?;
|
||||
self.coordinate.compare(&rhs.coordinate, meter)
|
||||
}
|
||||
|
||||
pub fn as_kind(
|
||||
&self,
|
||||
target: &ResolvedKind<K>,
|
||||
meter: &mut WorkMeter,
|
||||
) -> Result<Self, NumericError> {
|
||||
meter.ensure_active()?;
|
||||
let output = self.value_type.assertion_result(target)?;
|
||||
meter.numeric(NumericOperation::KindAssertion, self.coordinate.copy_cost())?;
|
||||
Ok(Self::new(output, self.coordinate.clone()))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,804 @@
|
||||
use super::*;
|
||||
use num_bigint::BigInt;
|
||||
use num_traits::One;
|
||||
use std::cmp::Ordering;
|
||||
|
||||
fn meter() -> WorkMeter {
|
||||
WorkMeter::new(WorkLimits::REFERENCE)
|
||||
}
|
||||
|
||||
fn exact(n: impl ToString, d: impl ToString) -> Exact {
|
||||
Exact::from_wire(
|
||||
&ExactWire {
|
||||
numerator: n.to_string(),
|
||||
denominator: d.to_string(),
|
||||
},
|
||||
&mut meter(),
|
||||
)
|
||||
.unwrap()
|
||||
}
|
||||
|
||||
fn source(text: &str) -> Exact {
|
||||
Exact::parse_literal(text, &mut meter()).unwrap()
|
||||
}
|
||||
|
||||
fn assert_fraction(value: &Exact, n: impl ToString, d: impl ToString) {
|
||||
assert_eq!(
|
||||
value.to_wire(),
|
||||
ExactWire {
|
||||
numerator: n.to_string(),
|
||||
denominator: d.to_string(),
|
||||
}
|
||||
);
|
||||
}
|
||||
|
||||
// Independent bounded i128 oracle. It does not call the production Exact/GCD
|
||||
// implementation when deriving expected arithmetic or ordering.
|
||||
fn small_fraction(mut n: i128, mut d: i128) -> (i128, i128) {
|
||||
assert_ne!(d, 0);
|
||||
if d < 0 {
|
||||
n = -n;
|
||||
d = -d;
|
||||
}
|
||||
let (mut a, mut b) = (n.abs(), d);
|
||||
while b != 0 {
|
||||
(a, b) = (b, a % b);
|
||||
}
|
||||
(n / a, d / a)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn arithmetic_matches_independent_small_integer_oracle() {
|
||||
for a in [-5_i128, -2, 0, 1, 4] {
|
||||
for b in [1_i128, 2, 3, 7] {
|
||||
for c in [-5_i128, -2, 0, 1, 4] {
|
||||
for d in [1_i128, 2, 3, 7] {
|
||||
let (an, ad) = small_fraction(a, b);
|
||||
let (bn, bd) = small_fraction(c, d);
|
||||
let left = exact(an, ad);
|
||||
let right = exact(bn, bd);
|
||||
let mut work = meter();
|
||||
let (n, den) = small_fraction(a * d + c * b, b * d);
|
||||
assert_fraction(&left.add(&right, &mut work).unwrap(), n, den);
|
||||
let (n, den) = small_fraction(a * d - c * b, b * d);
|
||||
assert_fraction(&left.subtract(&right, &mut work).unwrap(), n, den);
|
||||
let (n, den) = small_fraction(a * c, b * d);
|
||||
assert_fraction(&left.multiply(&right, &mut work).unwrap(), n, den);
|
||||
if c != 0 {
|
||||
let (n, den) = small_fraction(a * d, b * c);
|
||||
assert_fraction(&left.divide(&right, &mut work).unwrap(), n, den);
|
||||
} else {
|
||||
assert_eq!(
|
||||
left.divide(&right, &mut work),
|
||||
Err(NumericError::DivisionByZero)
|
||||
);
|
||||
}
|
||||
assert_eq!(
|
||||
left.compare(&right, &mut work).unwrap(),
|
||||
(a * d).cmp(&(c * b))
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn decimals_are_exact_and_source_ratios_reduce() {
|
||||
assert_fraction(
|
||||
&source("0.1").add(&source("0.2"), &mut meter()).unwrap(),
|
||||
3,
|
||||
10,
|
||||
);
|
||||
assert_fraction(&source("0.50"), 1, 2);
|
||||
assert_fraction(&source("12.50e-2"), 1, 8);
|
||||
assert_fraction(&source("1e+3"), 1000, 1);
|
||||
assert_fraction(&source("0001.2500"), 5, 4);
|
||||
assert_fraction(&source(" ratio( -6, 8 ) "), -3, 4);
|
||||
assert_fraction(&source("ratio(-0, 27)"), 0, 1);
|
||||
assert_eq!(source("0.5").canonical_literal(), "ratio(1, 2)");
|
||||
assert_eq!(source("42").canonical_literal(), "42");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn powers_and_signs_have_explicit_domains() {
|
||||
let x = exact(-2, 3);
|
||||
assert_fraction(&x.power(3, &mut meter()).unwrap(), -8, 27);
|
||||
assert_fraction(&x.power(-3, &mut meter()).unwrap(), -27, 8);
|
||||
assert_fraction(&x.power(0, &mut meter()).unwrap(), 1, 1);
|
||||
assert_fraction(&x.absolute(&mut meter()).unwrap(), 2, 3);
|
||||
assert_fraction(&x.negated(&mut meter()).unwrap(), 2, 3);
|
||||
assert_fraction(&x.reciprocal(&mut meter()).unwrap(), -3, 2);
|
||||
let zero = Exact::from_integer(0);
|
||||
assert_eq!(
|
||||
zero.power(0, &mut meter()),
|
||||
Err(NumericError::ZeroPowerZero)
|
||||
);
|
||||
assert_eq!(
|
||||
zero.power(-1, &mut meter()),
|
||||
Err(NumericError::DivisionByZero)
|
||||
);
|
||||
assert_eq!(x.power(17, &mut meter()), Err(NumericError::IntegerPower));
|
||||
assert_eq!(
|
||||
x.power(i8::MIN, &mut meter()),
|
||||
Err(NumericError::IntegerPower)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn canonical_wire_rejects_both_component_noncanonical_forms() {
|
||||
for (n, d) in [
|
||||
("+1", "1"),
|
||||
("01", "1"),
|
||||
("-0", "1"),
|
||||
("1", "+1"),
|
||||
("1", "-1"),
|
||||
("1", "01"),
|
||||
("2", "4"),
|
||||
("0", "3"),
|
||||
("", "1"),
|
||||
("1", ""),
|
||||
("1.0", "1"),
|
||||
("1", "1.0"),
|
||||
("1e1", "1"),
|
||||
("1", "1e1"),
|
||||
(" 1", "1"),
|
||||
("1", "1 "),
|
||||
] {
|
||||
assert!(
|
||||
Exact::from_wire(
|
||||
&ExactWire {
|
||||
numerator: n.into(),
|
||||
denominator: d.into()
|
||||
},
|
||||
&mut meter(),
|
||||
)
|
||||
.is_err(),
|
||||
"accepted {n}/{d}"
|
||||
);
|
||||
}
|
||||
assert_eq!(
|
||||
Exact::from_wire(
|
||||
&ExactWire {
|
||||
numerator: "1".into(),
|
||||
denominator: "0".into()
|
||||
},
|
||||
&mut meter()
|
||||
),
|
||||
Err(NumericError::ZeroDenominator)
|
||||
);
|
||||
assert_fraction(&exact(0, 1), 0, 1);
|
||||
assert_fraction(&exact(-1, 2), -1, 2);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn serde_uses_closed_canonical_string_wire() {
|
||||
let value = exact(-3, 7);
|
||||
let encoded = serde_json::to_value(&value).unwrap();
|
||||
assert_eq!(
|
||||
encoded,
|
||||
serde_json::json!({"numerator":"-3","denominator":"7"})
|
||||
);
|
||||
assert_eq!(serde_json::from_value::<Exact>(encoded).unwrap(), value);
|
||||
for invalid in [
|
||||
r#"{"numerator":1,"denominator":"2"}"#,
|
||||
r#"{"numerator":"1","denominator":2}"#,
|
||||
r#"{"numerator":"1","denominator":"2","other":0}"#,
|
||||
r#"{"numerator":"1","numerator":"2","denominator":"3"}"#,
|
||||
r#"{"numerator":"1"}"#,
|
||||
r#"{"numerator":"2","denominator":"4"}"#,
|
||||
] {
|
||||
assert!(serde_json::from_str::<Exact>(invalid).is_err(), "{invalid}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn literal_reader_does_not_fold_expression_unary_minus() {
|
||||
assert_eq!(
|
||||
Exact::parse_literal("-2", &mut meter()),
|
||||
Err(NumericError::InvalidLiteral)
|
||||
);
|
||||
let negative_literal = source("ratio(-2, 1)");
|
||||
assert_eq!(negative_literal.canonical_literal(), "ratio(-2, 1)");
|
||||
assert_eq!(source("2").negated(&mut meter()).unwrap(), negative_literal);
|
||||
// Equality of coordinates does not claim AST equality. The expression
|
||||
// parser must preserve UnaryNegate independently of its operand literal.
|
||||
assert_eq!(source("2").canonical_literal(), "2");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn literal_syntax_and_decimal_exponent_are_bounded() {
|
||||
for invalid in [
|
||||
"",
|
||||
"-",
|
||||
"+1",
|
||||
".5",
|
||||
"1.",
|
||||
"1.2.3",
|
||||
"1e",
|
||||
"1ee2",
|
||||
"1e+-2",
|
||||
"1_000",
|
||||
"NaN",
|
||||
"Infinity",
|
||||
"1/2",
|
||||
"ratio(1)",
|
||||
"ratio(1,2,3)",
|
||||
"ratio(1,-2)",
|
||||
"ratio(+1,2)",
|
||||
"ratio(1,2) + 1",
|
||||
"12",
|
||||
] {
|
||||
assert!(
|
||||
Exact::parse_literal(invalid, &mut meter()).is_err(),
|
||||
"{invalid}"
|
||||
);
|
||||
}
|
||||
for invalid in ["1e129", "1e-129", "1e9999999999999999999999"] {
|
||||
assert_eq!(
|
||||
Exact::parse_literal(invalid, &mut meter()),
|
||||
Err(NumericError::DecimalExponent)
|
||||
);
|
||||
}
|
||||
assert!(Exact::parse_literal("1e128", &mut meter()).is_ok());
|
||||
assert!(Exact::parse_literal("1e-128", &mut meter()).is_ok());
|
||||
assert_eq!(
|
||||
Exact::parse_literal(&"1".repeat(MAX_COMPONENT_DIGITS + 1), &mut meter()),
|
||||
Err(NumericError::LiteralTooLong)
|
||||
);
|
||||
assert_eq!(
|
||||
Exact::parse_literal(&" ".repeat(MAX_LITERAL_BYTES + 1), &mut meter()),
|
||||
Err(NumericError::LiteralTooLong)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn full_independent_r7_packets_round_trip_as_literals_and_wire() {
|
||||
let packets: serde_json::Value =
|
||||
serde_json::from_str(include_str!("fixtures/r7-literal-boundaries.json")).unwrap();
|
||||
for packet in packets.as_array().unwrap() {
|
||||
let wire: ExactWire =
|
||||
serde_json::from_value(packet["expression"]["Number"].clone()).unwrap();
|
||||
let expected = Exact::from_wire(&wire, &mut meter()).unwrap();
|
||||
let spelling = packet["canonical_source"].as_str().unwrap();
|
||||
assert_eq!(expected.canonical_literal(), spelling);
|
||||
assert_eq!(
|
||||
Exact::parse_literal(spelling, &mut meter()).unwrap(),
|
||||
expected
|
||||
);
|
||||
let serialized = serde_json::to_string(&expected).unwrap();
|
||||
assert_eq!(
|
||||
serde_json::from_str::<Exact>(&serialized).unwrap(),
|
||||
expected
|
||||
);
|
||||
assert_eq!(expected.to_wire(), wire);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn full_8193_bit_sum_intermediate_can_reduce_to_admitted_value() {
|
||||
// N=(2^4096)-1, D=N-1. gcd(N,D)=1 and D is even.
|
||||
// N/D + N/D = N/(D/2), although its un-reduced numerator needs 8193 bits.
|
||||
let n = (BigInt::one() << 4096_usize) - 1_u8;
|
||||
let d = &n - 1_u8;
|
||||
let value = exact(&n, &d);
|
||||
let result = value.add(&value, &mut meter()).unwrap();
|
||||
assert_fraction(&result, &n, &d / 2_u8);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn cross_products_cancel_before_reduced_component_limit() {
|
||||
let n = BigInt::one() << 4095_usize;
|
||||
let d = &n - 1_u8;
|
||||
let left = exact(&n, &d);
|
||||
let right = exact(&d, &n);
|
||||
assert_fraction(&left.multiply(&right, &mut meter()).unwrap(), 1, 1);
|
||||
assert_fraction(
|
||||
&left
|
||||
.add(&left.negated(&mut meter()).unwrap(), &mut meter())
|
||||
.unwrap(),
|
||||
0,
|
||||
1,
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn both_reduced_component_overflows_are_reported() {
|
||||
let n = BigInt::one() << 4095_usize;
|
||||
let mut work = meter();
|
||||
let failure = exact(&n, 1)
|
||||
.multiply(&Exact::from_integer(2), &mut work)
|
||||
.unwrap_err();
|
||||
assert!(matches!(
|
||||
failure,
|
||||
NumericError::Limit(NumericLimit::Bits {
|
||||
component: NumberComponent::Numerator,
|
||||
bits: 4097,
|
||||
..
|
||||
})
|
||||
));
|
||||
assert!(work.exhaustion().is_none());
|
||||
let failure = exact(1, &n)
|
||||
.divide(&Exact::from_integer(2), &mut work)
|
||||
.unwrap_err();
|
||||
assert!(matches!(
|
||||
failure,
|
||||
NumericError::Limit(NumericLimit::Bits {
|
||||
component: NumberComponent::Denominator,
|
||||
bits: 4097,
|
||||
..
|
||||
})
|
||||
));
|
||||
// Value overflow is a nonterminal supported-operation failure; fuel
|
||||
// exhaustion, in contrast, terminates the entire request.
|
||||
assert_fraction(&source("1").add(&source("1"), &mut work).unwrap(), 2, 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn wire_rejects_4097_bits_before_gcd_can_reduce_them() {
|
||||
let oversized = (BigInt::one() << 4096_usize).to_string();
|
||||
for wire in [
|
||||
ExactWire {
|
||||
numerator: oversized.clone(),
|
||||
denominator: "1".into(),
|
||||
},
|
||||
ExactWire {
|
||||
numerator: "1".into(),
|
||||
denominator: oversized.clone(),
|
||||
},
|
||||
ExactWire {
|
||||
numerator: oversized.clone(),
|
||||
denominator: oversized,
|
||||
},
|
||||
] {
|
||||
assert!(matches!(
|
||||
Exact::from_wire(&wire, &mut meter()),
|
||||
Err(NumericError::Limit(NumericLimit::Bits { stage, .. })) if stage == "wire"
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn numeric_precharge_precedes_big_integer_result_allocation() {
|
||||
let n = BigInt::one() << 4095_usize;
|
||||
let left = exact(&n, 1);
|
||||
let mut work = WorkMeter::new(WorkLimits::new(10, 0).unwrap());
|
||||
let failure = left
|
||||
.multiply(&Exact::from_integer(2), &mut work)
|
||||
.unwrap_err();
|
||||
assert!(failure.is_terminal_work_exhaustion());
|
||||
assert_eq!(work.usage().numeric_units, 0);
|
||||
assert!(matches!(
|
||||
work.exhaustion().unwrap().site,
|
||||
WorkSite::Numeric(NumericOperation::Multiply)
|
||||
));
|
||||
// With available fuel the same operation reaches the 4097-bit result check.
|
||||
assert!(matches!(
|
||||
left.multiply(&Exact::from_integer(2), &mut meter()),
|
||||
Err(NumericError::Limit(NumericLimit::Bits { .. }))
|
||||
));
|
||||
let too_wide_wire = ExactWire {
|
||||
numerator: (BigInt::one() << 4096_usize).to_string(),
|
||||
denominator: "1".into(),
|
||||
};
|
||||
let mut parse_work = WorkMeter::new(WorkLimits::new(0, 0).unwrap());
|
||||
assert!(
|
||||
Exact::from_wire(&too_wide_wire, &mut parse_work)
|
||||
.unwrap_err()
|
||||
.is_terminal_work_exhaustion()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn provisional_limits_and_effective_limits_round_trip() {
|
||||
let limits = WorkLimits::new(500, 2000).unwrap();
|
||||
let encoded = serde_json::to_value(limits).unwrap();
|
||||
assert_eq!(
|
||||
encoded,
|
||||
serde_json::json!({"dynamic_events":500,"numeric_units":2000})
|
||||
);
|
||||
assert_eq!(
|
||||
serde_json::from_value::<WorkLimits>(encoded).unwrap(),
|
||||
limits
|
||||
);
|
||||
assert_eq!(
|
||||
WorkLimits::new(1_000_001, 0),
|
||||
Err(NumericError::InvalidWorkLimits)
|
||||
);
|
||||
assert_eq!(
|
||||
WorkLimits::new(0, 50_000_001),
|
||||
Err(NumericError::InvalidWorkLimits)
|
||||
);
|
||||
assert!(
|
||||
serde_json::from_str::<WorkLimits>(r#"{"dynamic_events":1000001,"numeric_units":0}"#)
|
||||
.is_err()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn exact_accounting_boundary_and_terminal_failure_are_stable() {
|
||||
// One-word addition: three products at 2, one sum at 2,
|
||||
// normalization at 67 => 75 logical numeric units.
|
||||
let mut work = WorkMeter::new(WorkLimits::new(4, 75).unwrap());
|
||||
assert_fraction(&exact(1, 2).add(&exact(1, 3), &mut work).unwrap(), 5, 6);
|
||||
assert_eq!(work.usage().numeric_units, 75);
|
||||
assert!(work.exhaustion().is_none());
|
||||
let first = Exact::from_integer(1).negated(&mut work).unwrap_err();
|
||||
let at_failure = work.usage();
|
||||
assert_eq!(
|
||||
work.exhaustion().unwrap(),
|
||||
&WorkExhaustion {
|
||||
resource: WorkResource::NumericUnits,
|
||||
used: 75,
|
||||
requested: 3,
|
||||
limit: 75,
|
||||
site: WorkSite::Numeric(NumericOperation::Negate),
|
||||
}
|
||||
);
|
||||
assert_eq!(work.visit(EvaluationStep::Target).unwrap_err(), first);
|
||||
assert_eq!(
|
||||
Exact::from_integer(1)
|
||||
.divide(&Exact::from_integer(0), &mut work)
|
||||
.unwrap_err(),
|
||||
first
|
||||
);
|
||||
assert_eq!(
|
||||
work.numeric(NumericOperation::Compare, 0).unwrap_err(),
|
||||
first
|
||||
);
|
||||
assert_eq!(work.usage(), at_failure);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn zero_cost_and_maximum_reservation_do_not_underflow_or_reactivate() {
|
||||
let mut work = WorkMeter::new(WorkLimits::new(0, 0).unwrap());
|
||||
work.numeric(NumericOperation::Compare, 0).unwrap();
|
||||
let failure = work
|
||||
.numeric(NumericOperation::Multiply, u64::MAX)
|
||||
.unwrap_err();
|
||||
assert!(failure.is_terminal_work_exhaustion());
|
||||
assert_eq!(work.usage(), WorkUsage::default());
|
||||
assert_eq!(
|
||||
work.numeric(NumericOperation::Compare, 0).unwrap_err(),
|
||||
failure
|
||||
);
|
||||
let mut dynamic = WorkMeter::new(WorkLimits::new(0, 5).unwrap());
|
||||
assert!(dynamic.visit(EvaluationStep::Target).is_err());
|
||||
assert_eq!(dynamic.usage(), WorkUsage::default());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn multiple_targets_share_one_aggregate_meter() {
|
||||
let mut work = WorkMeter::new(WorkLimits::new(3, 50).unwrap());
|
||||
work.visit(EvaluationStep::Target).unwrap();
|
||||
work.visit(EvaluationStep::Expression).unwrap();
|
||||
work.visit(EvaluationStep::Target).unwrap();
|
||||
let failure = work.visit(EvaluationStep::Expression).unwrap_err();
|
||||
assert!(failure.is_terminal_work_exhaustion());
|
||||
assert_eq!(work.usage().dynamic_events, 3);
|
||||
}
|
||||
|
||||
// A direct bounded call-tree workload, not an expression interpreter/dialect.
|
||||
fn expanded_calls(
|
||||
depth: u8,
|
||||
x: u64,
|
||||
work: &mut WorkMeter,
|
||||
entered: &mut u64,
|
||||
) -> Result<u64, NumericError> {
|
||||
work.visit(EvaluationStep::CalculationEntry)?;
|
||||
*entered += 1;
|
||||
if depth == 0 {
|
||||
return Ok(x);
|
||||
}
|
||||
let left = expanded_calls(depth - 1, 2 * x, work, entered)?;
|
||||
let right = expanded_calls(depth - 1, 2 * x + 1, work, entered)?;
|
||||
Ok(left + right)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn c1_expanded_call_witness_terminates_at_dynamic_limit() {
|
||||
let mut work = WorkMeter::new(WorkLimits::new(10_000, 0).unwrap());
|
||||
let mut entered = 0;
|
||||
let failure = expanded_calls(30, 0, &mut work, &mut entered).unwrap_err();
|
||||
assert!(failure.is_terminal_work_exhaustion());
|
||||
assert_eq!(entered, 10_000);
|
||||
assert_eq!(work.usage().dynamic_events, 10_000);
|
||||
assert_eq!(
|
||||
work.exhaustion().unwrap().site,
|
||||
WorkSite::Evaluation(EvaluationStep::CalculationEntry)
|
||||
);
|
||||
// Nearby finite control: 63 invocations, leaves 0..31, sum 496.
|
||||
let mut bounded = WorkMeter::new(WorkLimits::new(63, 0).unwrap());
|
||||
let mut entered = 0;
|
||||
assert_eq!(
|
||||
expanded_calls(5, 0, &mut bounded, &mut entered).unwrap(),
|
||||
496
|
||||
);
|
||||
assert_eq!(entered, 63);
|
||||
assert!(bounded.exhaustion().is_none());
|
||||
}
|
||||
|
||||
fn dim(value: [i16; 7]) -> Dimension {
|
||||
Dimension::new(value).unwrap()
|
||||
}
|
||||
|
||||
fn linear(key: &str, dimension: Dimension) -> ResolvedKind<String> {
|
||||
ResolvedKind::linear(key.to_owned(), dimension)
|
||||
}
|
||||
|
||||
fn named(n: i64, kind: &ResolvedKind<String>) -> NumericValue<String> {
|
||||
NumericValue::new(NumericType::Named(kind.clone()), Exact::from_integer(n))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dimensions_use_checked_seven_axis_integer_algebra() {
|
||||
let length = dim([1, 0, 0, 0, 0, 0, 0]);
|
||||
let mass = dim([0, 1, 0, 0, 0, 0, 0]);
|
||||
let time = dim([0, 0, 1, 0, 0, 0, 0]);
|
||||
assert_eq!(
|
||||
mass.checked_product(length)
|
||||
.unwrap()
|
||||
.checked_quotient(time.checked_power(2).unwrap())
|
||||
.unwrap(),
|
||||
dim([1, 1, -2, 0, 0, 0, 0])
|
||||
);
|
||||
assert!(time.checked_quotient(time).unwrap().is_dimensionless());
|
||||
assert!(matches!(
|
||||
dim([32, 0, 0, 0, 0, 0, 0]).checked_product(length),
|
||||
Err(NumericError::DimensionExponent {
|
||||
axis: DimensionAxis::Length,
|
||||
value: 33
|
||||
})
|
||||
));
|
||||
assert!(dim([0, 0, -32, 0, 0, 0, 0]).checked_quotient(time).is_err());
|
||||
assert!(length.checked_power(i8::MIN).is_err());
|
||||
assert!(Dimension::new([33, 0, 0, 0, 0, 0, 0]).is_err());
|
||||
assert_eq!(
|
||||
serde_json::to_value(time).unwrap(),
|
||||
serde_json::json!([0, 0, 1, 0, 0, 0, 0])
|
||||
);
|
||||
for invalid in ["[0,0,33,0,0,0,0]", "[0,0,1]", "[0,0,1,0,0,0,0,0]"] {
|
||||
assert!(serde_json::from_str::<Dimension>(invalid).is_err());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn duration_unit_coordinates_are_exact_and_nominal() {
|
||||
let duration = linear("duration", dim([0, 0, 1, 0, 0, 0, 0]));
|
||||
let s = Unit::new(duration.clone(), source("1"), source("0")).unwrap();
|
||||
let ms = Unit::new(duration.clone(), source("0.001"), source("0")).unwrap();
|
||||
assert_fraction(&ms.convert(&source("750"), &s, &mut meter()).unwrap(), 3, 4);
|
||||
let receive = NumericValue::from_unit(&source("750"), &ms, &mut meter()).unwrap();
|
||||
let dispatch = NumericValue::from_unit(&source("1"), &s, &mut meter()).unwrap();
|
||||
let total = receive.add(&dispatch, &mut meter()).unwrap();
|
||||
assert_fraction(total.coordinate(), 7, 4);
|
||||
assert_fraction(&total.display_in(&ms, &mut meter()).unwrap(), 1750, 1);
|
||||
let different = Unit::new(
|
||||
linear("different-kind", duration.dimension()),
|
||||
source("1"),
|
||||
source("0"),
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
ms.convert(&source("750"), &different, &mut meter()),
|
||||
Err(NumericError::IncompatibleTypes)
|
||||
);
|
||||
let inconsistent = Unit::new(
|
||||
linear("duration", dim([1, 0, 0, 0, 0, 0, 0])),
|
||||
source("1"),
|
||||
source("0"),
|
||||
)
|
||||
.unwrap();
|
||||
assert!(
|
||||
ms.convert(&source("1"), &inconsistent, &mut meter())
|
||||
.is_err()
|
||||
);
|
||||
assert!(Unit::new(duration.clone(), source("0"), source("0")).is_err());
|
||||
assert!(Unit::new(duration.clone(), source("ratio(-1,1)"), source("0")).is_err());
|
||||
assert_eq!(
|
||||
Unit::new(duration, source("1"), source("1")).unwrap_err(),
|
||||
NumericError::LinearOffset
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn affine_point_and_difference_arithmetic_has_distinct_kinds() {
|
||||
let interval = linear("temperature-difference", dim([0, 0, 0, 0, 1, 0, 0]));
|
||||
let point = ResolvedKind::affine("temperature-point".to_owned(), &interval).unwrap();
|
||||
let celsius = Unit::new(point.clone(), source("1"), source("273.15")).unwrap();
|
||||
let fahrenheit = Unit::new(
|
||||
point.clone(),
|
||||
source("ratio(5,9)"),
|
||||
source("ratio(45967,180)"),
|
||||
)
|
||||
.unwrap();
|
||||
let kelvin_interval = Unit::new(interval.clone(), source("1"), source("0")).unwrap();
|
||||
assert_fraction(
|
||||
&celsius
|
||||
.convert(&source("0"), &fahrenheit, &mut meter())
|
||||
.unwrap(),
|
||||
32,
|
||||
1,
|
||||
);
|
||||
assert_fraction(
|
||||
&fahrenheit
|
||||
.convert(&source("70"), &celsius, &mut meter())
|
||||
.unwrap(),
|
||||
190,
|
||||
9,
|
||||
);
|
||||
let p20 = NumericValue::from_unit(&source("20"), &celsius, &mut meter()).unwrap();
|
||||
let p10 = NumericValue::from_unit(&source("10"), &celsius, &mut meter()).unwrap();
|
||||
let difference = p20.subtract(&p10, &mut meter()).unwrap();
|
||||
assert_eq!(
|
||||
difference.value_type(),
|
||||
&NumericType::Named(interval.clone())
|
||||
);
|
||||
assert_fraction(
|
||||
&difference
|
||||
.display_in(&kelvin_interval, &mut meter())
|
||||
.unwrap(),
|
||||
10,
|
||||
1,
|
||||
);
|
||||
let delta5 = named(5, &interval);
|
||||
let p25 = p20.add(&delta5, &mut meter()).unwrap();
|
||||
assert_fraction(&p25.display_in(&celsius, &mut meter()).unwrap(), 25, 1);
|
||||
assert_eq!(delta5.add(&p20, &mut meter()).unwrap(), p25);
|
||||
assert!(p20.add(&p10, &mut meter()).is_err());
|
||||
assert!(delta5.subtract(&p20, &mut meter()).is_err());
|
||||
assert_eq!(
|
||||
p20.power(1, &mut meter()),
|
||||
Err(NumericError::AffineOperation)
|
||||
);
|
||||
assert_eq!(
|
||||
p20.negated(&mut meter()),
|
||||
Err(NumericError::AffineOperation)
|
||||
);
|
||||
assert_eq!(p20.compare(&p10, &mut meter()).unwrap(), Ordering::Greater);
|
||||
assert!(p20.display_in(&kelvin_interval, &mut meter()).is_err());
|
||||
assert!(ResolvedKind::affine(interval.key().clone(), &interval).is_err());
|
||||
assert!(ResolvedKind::affine("other".to_owned(), &point).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn affine_conversion_rejects_a_wider_stage_even_when_the_final_value_would_fit() {
|
||||
// A fused coordinate calculation 2*m-m equals m, where m=2^4095 fits.
|
||||
// The fixed multiply stage produces 2^4096, so it must fail before offset
|
||||
// cancellation. The inverse path likewise rejects (m-(-m))/2 at subtraction.
|
||||
let large = BigInt::one() << 4095_usize;
|
||||
let magnitude = exact(&large, 1);
|
||||
let interval = linear("temperature-interval", dim([0, 0, 0, 0, 1, 0, 0]));
|
||||
let point = ResolvedKind::affine("temperature-point".to_owned(), &interval).unwrap();
|
||||
let unit = Unit::new(point, Exact::from_integer(2), exact(-&large, 1)).unwrap();
|
||||
let mut work = meter();
|
||||
for outcome in [
|
||||
unit.to_canonical(&magnitude, &mut work),
|
||||
unit.from_canonical(&magnitude, &mut work),
|
||||
] {
|
||||
assert!(matches!(
|
||||
outcome,
|
||||
Err(NumericError::Limit(NumericLimit::Bits {
|
||||
component: NumberComponent::Numerator,
|
||||
bits: 4097,
|
||||
limit: MAX_COMPONENT_BITS,
|
||||
..
|
||||
}))
|
||||
));
|
||||
}
|
||||
assert!(work.exhaustion().is_none());
|
||||
let half = exact(&large >> 1_usize, 1);
|
||||
assert_fraction(&unit.to_canonical(&half, &mut work).unwrap(), 0, 1);
|
||||
assert_eq!(
|
||||
unit.from_canonical(&Exact::from_integer(0), &mut work)
|
||||
.unwrap(),
|
||||
half
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn r6_anonymous_compound_energy_needs_one_outer_assertion() {
|
||||
let force = linear("force", dim([1, 1, -2, 0, 0, 0, 0]));
|
||||
let length = linear("length", dim([1, 0, 0, 0, 0, 0, 0]));
|
||||
let energy = linear("energy", dim([2, 1, -2, 0, 0, 0, 0]));
|
||||
let a = named(3, &force)
|
||||
.multiply(&named(4, &length), &mut meter())
|
||||
.unwrap();
|
||||
let b = named(2, &force)
|
||||
.multiply(&named(7, &length), &mut meter())
|
||||
.unwrap();
|
||||
assert_eq!(a.value_type(), &NumericType::Anonymous(energy.dimension()));
|
||||
let sum = a.add(&b, &mut meter()).unwrap();
|
||||
let result = sum.as_kind(&energy, &mut meter()).unwrap();
|
||||
assert_fraction(result.coordinate(), 26, 1);
|
||||
assert_eq!(result.value_type(), &NumericType::Named(energy.clone()));
|
||||
assert_eq!(a.compare(&b, &mut meter()).unwrap(), Ordering::Less);
|
||||
assert!(result.add(&sum, &mut meter()).is_err());
|
||||
assert_eq!(
|
||||
result.as_kind(&energy, &mut meter()),
|
||||
Err(NumericError::KindAssertion)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn anonymous_product_then_quotient_closes_and_preserves_scaling() {
|
||||
let mass = linear("mass", dim([0, 1, 0, 0, 0, 0, 0]));
|
||||
let length = linear("length", dim([1, 0, 0, 0, 0, 0, 0]));
|
||||
let time = linear("duration", dim([0, 0, 1, 0, 0, 0, 0]));
|
||||
let momentum = linear("momentum", dim([1, 1, -1, 0, 0, 0, 0]));
|
||||
let result = named(2, &mass)
|
||||
.multiply(&named(3, &length), &mut meter())
|
||||
.unwrap()
|
||||
.divide(&named(2, &time), &mut meter())
|
||||
.unwrap()
|
||||
.as_kind(&momentum, &mut meter())
|
||||
.unwrap();
|
||||
assert_fraction(result.coordinate(), 3, 1);
|
||||
let scalar = NumericValue::number(source("2"));
|
||||
let scaled = scalar.multiply(&named(3, &time), &mut meter()).unwrap();
|
||||
assert_eq!(scaled.value_type(), &NumericType::Named(time.clone()));
|
||||
assert_fraction(scaled.coordinate(), 6, 1);
|
||||
assert_eq!(
|
||||
named(3, &time)
|
||||
.divide(&scalar, &mut meter())
|
||||
.unwrap()
|
||||
.value_type(),
|
||||
&NumericType::Named(time.clone())
|
||||
);
|
||||
assert_eq!(
|
||||
scalar
|
||||
.divide(&named(3, &time), &mut meter())
|
||||
.unwrap()
|
||||
.value_type(),
|
||||
&NumericType::Anonymous(dim([0, 0, -1, 0, 0, 0, 0]))
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn nominal_kinds_survive_comparison_but_explicit_quotients_can_erase_dimension() {
|
||||
let energy = linear("energy", dim([2, 1, -2, 0, 0, 0, 0]));
|
||||
let torque = linear("torque", energy.dimension());
|
||||
let left = named(7, &energy);
|
||||
let right = named(7, &torque);
|
||||
assert!(left.add(&right, &mut meter()).is_err());
|
||||
assert!(left.compare(&right, &mut meter()).is_err());
|
||||
let ratio = left.divide(&right, &mut meter()).unwrap();
|
||||
assert_eq!(ratio.value_type(), &NumericType::Number);
|
||||
assert_fraction(ratio.coordinate(), 1, 1);
|
||||
let named_ratio = linear("chosen-ratio", Dimension::ZERO);
|
||||
let asserted = ratio.as_kind(&named_ratio, &mut meter()).unwrap();
|
||||
assert_eq!(
|
||||
asserted.value_type(),
|
||||
&NumericType::Named(named_ratio.clone())
|
||||
);
|
||||
assert!(asserted.add(&ratio, &mut meter()).is_err());
|
||||
assert_eq!(
|
||||
NumericValue::<String>::new(NumericType::Anonymous(Dimension::ZERO), source("1")),
|
||||
NumericValue::number(source("1"))
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn numerical_power_types_and_dimension_overflow_are_checked() {
|
||||
let length = linear("length", dim([1, 0, 0, 0, 0, 0, 0]));
|
||||
let value = named(2, &length);
|
||||
assert_eq!(
|
||||
value.power(0, &mut meter()).unwrap().value_type(),
|
||||
&NumericType::Number
|
||||
);
|
||||
assert_eq!(
|
||||
value.power(1, &mut meter()).unwrap().value_type(),
|
||||
value.value_type()
|
||||
);
|
||||
assert_eq!(
|
||||
value.power(-2, &mut meter()).unwrap().value_type(),
|
||||
&NumericType::Anonymous(dim([-2, 0, 0, 0, 0, 0, 0]))
|
||||
);
|
||||
let large_dimension = linear("large-dimension", dim([32, 0, 0, 0, 0, 0, 0]));
|
||||
assert!(
|
||||
named(1, &large_dimension)
|
||||
.multiply(&value, &mut meter())
|
||||
.is_err()
|
||||
);
|
||||
assert!(named(1, &large_dimension).power(2, &mut meter()).is_err());
|
||||
}
|
||||
@@ -15,6 +15,7 @@ fn occurrence(
|
||||
let id = add(p, Kind::Occurrence, layer, name, Some(owner));
|
||||
*p.elements.get_mut(&id).unwrap().shared_mut().unwrap() = SharedBody::Occurrence {
|
||||
body: OccurrenceBody::Exchange {
|
||||
operation: None,
|
||||
exchange: Some(exchange),
|
||||
sender,
|
||||
receiver,
|
||||
@@ -78,6 +79,7 @@ fn diagram(
|
||||
description: "A focused projection of the shared engineering model.".into(),
|
||||
layer,
|
||||
projection,
|
||||
view_options: Default::default(),
|
||||
nodes: BTreeMap::new(),
|
||||
routes: vec![],
|
||||
},
|
||||
|
||||
+267
-122
@@ -1,6 +1,12 @@
|
||||
//! Typed OA/SA language, tolerant source analysis, and explicit V1/V2/V3/V4 migration.
|
||||
mod raw_tokens;
|
||||
#[path = "language/semantic_source.rs"]
|
||||
mod semantic_source;
|
||||
mod source3_bridge;
|
||||
// Staged syntax foundation only. Public source8 admission waits for complete
|
||||
// declaration lowering, source updates and the root-owned resource gate.
|
||||
#[cfg(test)]
|
||||
mod analysis_source;
|
||||
#[path = "migration_v2/source.rs"]
|
||||
mod v2_source;
|
||||
use crate::*;
|
||||
@@ -60,7 +66,8 @@ impl ParseLimits {
|
||||
let graph = project
|
||||
.elements
|
||||
.len()
|
||||
.saturating_add(project.relations.len());
|
||||
.saturating_add(project.relations.len())
|
||||
.saturating_add(project.definitions.len());
|
||||
let records = graph
|
||||
.saturating_add(1)
|
||||
.saturating_add(project.diagrams.len())
|
||||
@@ -79,12 +86,26 @@ impl ParseLimits {
|
||||
.sum::<usize>(),
|
||||
)
|
||||
.saturating_add(project.artifact_links.len())
|
||||
.saturating_add(project.traces.len());
|
||||
.saturating_add(project.traces.len())
|
||||
.saturating_add(crate::analysis::nested_record_count(project));
|
||||
let steps = project
|
||||
.elements
|
||||
.values()
|
||||
.map(|e| e.steps().map_or(0, Vec::len))
|
||||
.sum();
|
||||
.sum::<usize>()
|
||||
.saturating_add(
|
||||
project
|
||||
.relations
|
||||
.values()
|
||||
.map(|r| match &r.body {
|
||||
RelationBody::ContextualLink { source, target, .. } => source
|
||||
.references
|
||||
.len()
|
||||
.saturating_add(target.references.len()),
|
||||
_ => 0,
|
||||
})
|
||||
.sum::<usize>(),
|
||||
);
|
||||
self.check_counts(graph, records, steps)
|
||||
}
|
||||
}
|
||||
@@ -132,86 +153,7 @@ pub struct Analysis {
|
||||
/// Tolerant highlighting tokens cover the whole input, including incomplete
|
||||
/// strings and unexpected characters. No model is created or modified.
|
||||
pub fn tokenize(source: &str) -> Vec<TokenSpan> {
|
||||
let mut tokens = Vec::new();
|
||||
let mut cursor = 0;
|
||||
while cursor < source.len() {
|
||||
let start = cursor;
|
||||
let ch = source[cursor..].chars().next().expect("in bounds");
|
||||
let class = if matches!(ch, ' ' | '\t' | '\r' | '\n') {
|
||||
cursor += 1;
|
||||
while source
|
||||
.as_bytes()
|
||||
.get(cursor)
|
||||
.is_some_and(|next| matches!(*next, b' ' | b'\t' | b'\r' | b'\n'))
|
||||
{
|
||||
cursor += 1;
|
||||
}
|
||||
TokenClass::Whitespace
|
||||
} else if source[cursor..].starts_with("//") {
|
||||
cursor += source[cursor..].find('\n').unwrap_or(source.len() - cursor);
|
||||
TokenClass::Comment
|
||||
} else if ch == '"' {
|
||||
cursor += 1;
|
||||
let mut escaped = false;
|
||||
let mut closed = false;
|
||||
while cursor < source.len() {
|
||||
let next = source[cursor..].chars().next().expect("in bounds");
|
||||
cursor += next.len_utf8();
|
||||
if escaped {
|
||||
escaped = false;
|
||||
} else if next == '\\' {
|
||||
escaped = true;
|
||||
} else if next == '"' {
|
||||
closed = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if closed && serde_json::from_str::<String>(&source[start..cursor]).is_ok() {
|
||||
TokenClass::String
|
||||
} else {
|
||||
TokenClass::Error
|
||||
}
|
||||
} else if ch.is_ascii_alphabetic() || ch == '_' {
|
||||
cursor += 1;
|
||||
while source
|
||||
.as_bytes()
|
||||
.get(cursor)
|
||||
.is_some_and(|next| next.is_ascii_alphanumeric() || *next == b'_')
|
||||
{
|
||||
cursor += 1;
|
||||
}
|
||||
if reserved(&source[start..cursor])
|
||||
|| matches!(&source[start..cursor], "true" | "false" | "none")
|
||||
{
|
||||
TokenClass::Keyword
|
||||
} else {
|
||||
TokenClass::Identifier
|
||||
}
|
||||
} else if ch.is_ascii_digit() || matches!(ch, '-' | '+' | '.') {
|
||||
cursor += 1;
|
||||
while source.as_bytes().get(cursor).is_some_and(|next| {
|
||||
next.is_ascii_alphanumeric() || matches!(*next, b'.' | b'+' | b'-' | b'_')
|
||||
}) {
|
||||
cursor += 1;
|
||||
}
|
||||
if serde_json::from_str::<serde_json::Number>(&source[start..cursor]).is_ok() {
|
||||
TokenClass::Number
|
||||
} else {
|
||||
TokenClass::Error
|
||||
}
|
||||
} else if "{}();,[]:=@".contains(ch) {
|
||||
cursor += ch.len_utf8();
|
||||
TokenClass::Punctuation
|
||||
} else {
|
||||
cursor += ch.len_utf8();
|
||||
TokenClass::Error
|
||||
};
|
||||
tokens.push(TokenSpan {
|
||||
class,
|
||||
span: Span { start, end: cursor },
|
||||
});
|
||||
}
|
||||
tokens
|
||||
raw_tokens::legacy(source)
|
||||
}
|
||||
|
||||
pub fn lint(source: &str) -> Vec<Diagnostic> {
|
||||
@@ -343,6 +285,10 @@ fn reference_field(key: &str) -> bool {
|
||||
| "local"
|
||||
| "field"
|
||||
| "path"
|
||||
| "references"
|
||||
| "occurrence"
|
||||
| "allocation"
|
||||
| "work"
|
||||
| "supertype"
|
||||
| "sender"
|
||||
| "receiver"
|
||||
@@ -350,6 +296,9 @@ fn reference_field(key: &str) -> bool {
|
||||
| "lifeline"
|
||||
| "state"
|
||||
| "constrained"
|
||||
| "exchanges"
|
||||
| "hidden_edges"
|
||||
| "Any"
|
||||
| "source"
|
||||
| "target"
|
||||
| "source_port"
|
||||
@@ -531,6 +480,8 @@ fn parse_document(source: &str, limits: ParseLimits) -> Result<ParsedDocument, V
|
||||
cursor: 0,
|
||||
value_depth: 0,
|
||||
limits,
|
||||
#[cfg(test)]
|
||||
mixed: None,
|
||||
}
|
||||
.document()
|
||||
.map_err(|e| vec![diagnostic(source, e)])
|
||||
@@ -965,6 +916,8 @@ pub(crate) fn parse_unit(
|
||||
cursor: 0,
|
||||
value_depth: 0,
|
||||
limits,
|
||||
#[cfg(test)]
|
||||
mixed: None,
|
||||
}
|
||||
.unit(entry, true)
|
||||
.map_err(|e| Box::new(diagnostic(source, e)))
|
||||
@@ -1056,31 +1009,52 @@ fn edit_positions(
|
||||
unit: SourceUnit,
|
||||
) -> Result<Vec<(Id, EditDeclaration)>, Box<Diagnostic>> {
|
||||
let tokens = strict_tokens(source).map_err(|e| Box::new(diagnostic(source, e)))?;
|
||||
let mut ends: Vec<_> = tokens.iter().map(|token| token.span.end).collect();
|
||||
edit_positions_from_tokens(source, &unit, |at| tokens[at], tokens.len(), None)
|
||||
}
|
||||
|
||||
fn edit_positions_from_tokens(
|
||||
source: &str,
|
||||
unit: &SourceUnit,
|
||||
token: impl Fn(usize) -> Lexeme,
|
||||
count: usize,
|
||||
value_ends: Option<&BTreeMap<usize, usize>>,
|
||||
) -> Result<Vec<(Id, EditDeclaration)>, Box<Diagnostic>> {
|
||||
let mut ends: Vec<_> = (0..count).map(|at| token(at).span.end).collect();
|
||||
let mut stack = Vec::new();
|
||||
for (index, token) in tokens.iter().enumerate() {
|
||||
for index in 0..count {
|
||||
let token = token(index);
|
||||
match token.text(source) {
|
||||
"{" | "[" => stack.push(index),
|
||||
"}" | "]" => ends[stack.pop().expect("parser checked delimiters")] = token.span.end,
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
struct Positions<'a> {
|
||||
tokens: &'a [Lexeme],
|
||||
struct Positions<'a, F> {
|
||||
token_at: F,
|
||||
ends: Vec<usize>,
|
||||
value_ends: Option<&'a BTreeMap<usize, usize>>,
|
||||
}
|
||||
impl Positions<'_> {
|
||||
impl<F: Fn(usize) -> Lexeme> Positions<'_, F> {
|
||||
fn token(&self, start: usize) -> usize {
|
||||
self.tokens
|
||||
.partition_point(|token| token.span.start < start)
|
||||
let mut low = 0;
|
||||
let mut high = self.ends.len();
|
||||
while low < high {
|
||||
let middle = low + (high - low) / 2;
|
||||
if (self.token_at)(middle).span.start < start {
|
||||
low = middle + 1;
|
||||
} else {
|
||||
high = middle;
|
||||
}
|
||||
}
|
||||
low
|
||||
}
|
||||
fn fields(&self, fields: &BTreeMap<String, Ast>) -> BTreeMap<String, EditField> {
|
||||
fields
|
||||
.iter()
|
||||
.map(|(key, ast)| {
|
||||
let value = self.value(ast);
|
||||
let start = self.tokens[self.token(value.span.start) - 1].span.start;
|
||||
let end = self.tokens[self.token(value.span.end)].span.end;
|
||||
let start = (self.token_at)(self.token(value.span.start) - 1).span.start;
|
||||
let end = (self.token_at)(self.token(value.span.end)).span.end;
|
||||
(
|
||||
key.clone(),
|
||||
EditField {
|
||||
@@ -1095,10 +1069,15 @@ fn edit_positions(
|
||||
let index = self.token(ast.offset());
|
||||
let span = Span {
|
||||
start: ast.offset(),
|
||||
end: match ast {
|
||||
Ast::Reference(..) | Ast::HistoricalUuid(..) => self.tokens[index + 1].span.end,
|
||||
_ => self.ends[index],
|
||||
},
|
||||
end: self
|
||||
.value_ends
|
||||
.and_then(|ends| ends.get(&ast.offset()).copied())
|
||||
.unwrap_or_else(|| match ast {
|
||||
Ast::Reference(..) | Ast::HistoricalUuid(..) => {
|
||||
(self.token_at)(index + 1).span.end
|
||||
}
|
||||
_ => self.ends[index],
|
||||
}),
|
||||
};
|
||||
let kind = match ast {
|
||||
Ast::Object(fields, _) => EditKind::Record(self.fields(fields)),
|
||||
@@ -1113,11 +1092,12 @@ fn edit_positions(
|
||||
}
|
||||
}
|
||||
let positions = Positions {
|
||||
tokens: &tokens,
|
||||
token_at: &token,
|
||||
ends,
|
||||
value_ends,
|
||||
};
|
||||
unit.declarations
|
||||
.into_iter()
|
||||
.iter()
|
||||
.map(|declaration| {
|
||||
if declaration.id_insertion.is_some() {
|
||||
return Err(Box::new(diagnostic(
|
||||
@@ -1137,8 +1117,8 @@ fn edit_positions(
|
||||
let start = positions.token(declaration.span.start);
|
||||
let header = roles
|
||||
.iter()
|
||||
.zip(&tokens[start..])
|
||||
.map(|(role, token)| (*role, token.span))
|
||||
.zip(start..count)
|
||||
.map(|(role, at)| (*role, token(at).span))
|
||||
.collect();
|
||||
Ok((
|
||||
declaration.id,
|
||||
@@ -1165,10 +1145,35 @@ struct Parser<'a> {
|
||||
cursor: usize,
|
||||
value_depth: usize,
|
||||
limits: ParseLimits,
|
||||
#[cfg(test)]
|
||||
mixed: Option<analysis_source::mixed::State<'a>>,
|
||||
}
|
||||
impl Parser<'_> {
|
||||
fn token(&self, index: usize) -> Option<Lexeme> {
|
||||
#[cfg(test)]
|
||||
if let Some(mixed) = &self.mixed {
|
||||
return mixed.token(index);
|
||||
}
|
||||
self.tokens.get(index).copied()
|
||||
}
|
||||
fn current(&self) -> Lexeme {
|
||||
self.tokens[self.cursor.min(self.tokens.len() - 1)]
|
||||
self.token(self.cursor).unwrap_or(Lexeme {
|
||||
class: TokenClass::Punctuation,
|
||||
span: Span {
|
||||
start: self.source.len(),
|
||||
end: self.source.len(),
|
||||
},
|
||||
})
|
||||
}
|
||||
fn syntax_entry(&mut self) -> Result<(), Error> {
|
||||
#[cfg(test)]
|
||||
{
|
||||
let span = self.current().span;
|
||||
if let Some(mixed) = &mut self.mixed {
|
||||
mixed.entry(span)?;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
fn text(&self) -> &str {
|
||||
self.current().text(self.source)
|
||||
@@ -1205,6 +1210,10 @@ impl Parser<'_> {
|
||||
}
|
||||
fn optional_id(&mut self) -> Result<Id, Error> {
|
||||
if self.text() != "id" {
|
||||
#[cfg(test)]
|
||||
if self.mixed.is_some() {
|
||||
return Err(self.error("Private mixed syntax requires explicit IDs."));
|
||||
}
|
||||
return Ok(Id::new_v4());
|
||||
}
|
||||
self.cursor += 1;
|
||||
@@ -1245,6 +1254,7 @@ impl Parser<'_> {
|
||||
Ok(fields)
|
||||
}
|
||||
fn field(&mut self) -> Result<(String, Ast, Span), Error> {
|
||||
self.syntax_entry()?;
|
||||
let key = self.text().to_owned();
|
||||
if !matches!(
|
||||
self.current().class,
|
||||
@@ -1255,15 +1265,19 @@ impl Parser<'_> {
|
||||
self.cursor += 1;
|
||||
let start = self.current().span.start;
|
||||
let value = self.value()?;
|
||||
let end = self.tokens[self.cursor - 1].span.end;
|
||||
let end = self
|
||||
.token(self.cursor - 1)
|
||||
.expect("consumed token")
|
||||
.span
|
||||
.end;
|
||||
self.take(";")?;
|
||||
Ok((key, value, Span { start, end }))
|
||||
}
|
||||
|
||||
fn nested_header_kind(&self) -> Option<DeclKind> {
|
||||
let kind = declaration_kind(self.text())?;
|
||||
let alias = self.tokens.get(self.cursor + 1)?;
|
||||
let following = self.tokens.get(self.cursor + 2)?;
|
||||
let alias = self.token(self.cursor + 1)?;
|
||||
let following = self.token(self.cursor + 2)?;
|
||||
// A node's ordinary `diagram @view;` field is not a declaration.
|
||||
if !crate::valid_alias(alias.text(self.source)) {
|
||||
return None;
|
||||
@@ -1278,14 +1292,33 @@ impl Parser<'_> {
|
||||
if self.value_depth >= 64 {
|
||||
return Err(self.error("Typed values may not nest more than 64 levels."));
|
||||
}
|
||||
self.syntax_entry()?;
|
||||
self.value_depth += 1;
|
||||
let result = self.value_inner();
|
||||
self.value_depth -= 1;
|
||||
#[cfg(test)]
|
||||
if let Ok(ast) = &result {
|
||||
let end = self
|
||||
.token(self.cursor - 1)
|
||||
.expect("consumed value")
|
||||
.span
|
||||
.end;
|
||||
if let Some(mixed) = &mut self.mixed {
|
||||
mixed.value_ends.insert(ast.offset(), end);
|
||||
}
|
||||
}
|
||||
result
|
||||
}
|
||||
fn value_inner(&mut self) -> Result<Ast, Error> {
|
||||
let token = self.current();
|
||||
let offset = token.span.start;
|
||||
#[cfg(test)]
|
||||
if let Some(mixed) = &self.mixed
|
||||
&& (token.class == TokenClass::Number || matches!(self.text(), "-" | "+"))
|
||||
{
|
||||
let value = mixed.ordinary_number(&mut self.cursor)?;
|
||||
return Ok(Ast::Literal(value, offset));
|
||||
}
|
||||
match self.text() {
|
||||
"uuid" => {
|
||||
self.cursor += 1;
|
||||
@@ -1383,15 +1416,31 @@ impl Parser<'_> {
|
||||
fn unit(&mut self, entry: bool, includes_allowed: bool) -> Result<SourceUnit, Error> {
|
||||
let mut header = if entry {
|
||||
self.take("arcadia")?;
|
||||
if !matches!(self.text(), "3" | "4" | "5") {
|
||||
return Err(self
|
||||
.error("Unsupported schema version: expected 'arcadia 3;', 'arcadia 4;' or 'arcadia 5;'."));
|
||||
#[cfg(test)]
|
||||
let mixed_mode = self.mixed.is_some();
|
||||
#[cfg(not(test))]
|
||||
let mixed_mode = false;
|
||||
if if mixed_mode {
|
||||
self.text() != "8"
|
||||
} else {
|
||||
!matches!(self.text(), "3" | "4" | "5" | "6" | "7")
|
||||
} {
|
||||
return Err(self.error(if mixed_mode {
|
||||
"Private mixed syntax requires arcadia 8."
|
||||
} else {
|
||||
"Unsupported schema version: expected arcadia 3, 4, 5, 6 or 7."
|
||||
}));
|
||||
}
|
||||
let schema_version = self.text().parse().expect("checked source version");
|
||||
self.cursor += 1;
|
||||
self.take(";")?;
|
||||
let start = self.current().span.start;
|
||||
self.take("project")?;
|
||||
#[cfg(test)]
|
||||
if let Some(mixed) = &mut self.mixed {
|
||||
mixed.record(false, Span { start, end: start })?;
|
||||
}
|
||||
self.syntax_entry()?;
|
||||
let alias = self.identifier()?;
|
||||
let name = self.quoted()?;
|
||||
let id_insertion = (self.text() != "id").then_some(self.current().span.start);
|
||||
@@ -1405,6 +1454,7 @@ impl Parser<'_> {
|
||||
alias,
|
||||
name,
|
||||
description: String::new(),
|
||||
definitions: BTreeMap::new(),
|
||||
elements: BTreeMap::new(),
|
||||
relations: BTreeMap::new(),
|
||||
diagrams: BTreeMap::new(),
|
||||
@@ -1431,6 +1481,14 @@ impl Parser<'_> {
|
||||
let mut open: Vec<usize> = Vec::new();
|
||||
loop {
|
||||
let offset = self.current().span.start;
|
||||
#[cfg(test)]
|
||||
if let Some(mixed) = &mut self.mixed
|
||||
&& mixed.typed_header(self.cursor, open.is_empty())
|
||||
{
|
||||
let owner = open.last().map(|&at| declarations[at].id);
|
||||
mixed.parse_typed(&mut self.cursor, owner)?;
|
||||
continue;
|
||||
}
|
||||
if let Some(&owner) = open.last() {
|
||||
if self.text() == "}" {
|
||||
declarations[owner].body.end = offset;
|
||||
@@ -1474,6 +1532,14 @@ impl Parser<'_> {
|
||||
if !includes_allowed {
|
||||
return Err(self.error("An include requires a source bundle; single-string parsing never reads files."));
|
||||
}
|
||||
#[cfg(test)]
|
||||
if let Some(mixed) = &mut self.mixed {
|
||||
mixed.include(Span {
|
||||
start: offset,
|
||||
end: offset,
|
||||
})?;
|
||||
}
|
||||
self.syntax_entry()?;
|
||||
self.cursor += 1;
|
||||
let path = self.quoted()?;
|
||||
self.take(";")?;
|
||||
@@ -1481,7 +1547,11 @@ impl Parser<'_> {
|
||||
path,
|
||||
Span {
|
||||
start: offset,
|
||||
end: self.tokens[self.cursor - 1].span.end,
|
||||
end: self
|
||||
.token(self.cursor - 1)
|
||||
.expect("consumed token")
|
||||
.span
|
||||
.end,
|
||||
},
|
||||
));
|
||||
continue;
|
||||
@@ -1493,20 +1563,40 @@ impl Parser<'_> {
|
||||
if entry_header.description.is_some() {
|
||||
return Err(self.error("Duplicate project description."));
|
||||
}
|
||||
self.syntax_entry()?;
|
||||
self.cursor += 1;
|
||||
let description = self.quoted()?;
|
||||
self.take(";")?;
|
||||
entry_header.project.description = description;
|
||||
entry_header.description = Some(Span {
|
||||
start: offset,
|
||||
end: self.tokens[self.cursor - 1].span.end,
|
||||
end: self
|
||||
.token(self.cursor - 1)
|
||||
.expect("consumed token")
|
||||
.span
|
||||
.end,
|
||||
});
|
||||
header = Some(entry_header);
|
||||
continue;
|
||||
}
|
||||
#[cfg(test)]
|
||||
if self.mixed.is_some() && analysis_source::mixed::long_analysis_word(self.text()) {
|
||||
return Err(self.error("Use the short source8 analysis declaration word."));
|
||||
}
|
||||
self.syntax_entry()?;
|
||||
let word = self.text().to_owned();
|
||||
let kind = declaration_kind(&word)
|
||||
.ok_or_else(|| self.error(format!("Unknown declaration '{word}'.")))?;
|
||||
#[cfg(test)]
|
||||
if let Some(mixed) = &mut self.mixed {
|
||||
mixed.record(
|
||||
matches!(kind, DeclKind::Element(..) | DeclKind::Relation(..)),
|
||||
Span {
|
||||
start: offset,
|
||||
end: offset,
|
||||
},
|
||||
)?;
|
||||
}
|
||||
graph_count += usize::from(matches!(
|
||||
kind,
|
||||
DeclKind::Element(..) | DeclKind::Relation(..)
|
||||
@@ -1534,6 +1624,10 @@ impl Parser<'_> {
|
||||
let body_start = self.current().span.end;
|
||||
self.take("{")?;
|
||||
let lexical_owner = open.last().map(|&owner| declarations[owner].id);
|
||||
#[cfg(test)]
|
||||
if let Some(mixed) = &mut self.mixed {
|
||||
mixed.lexical_owners.push(open.last().copied());
|
||||
}
|
||||
declarations.push(Declaration {
|
||||
kind,
|
||||
alias,
|
||||
@@ -1570,17 +1664,25 @@ impl Parser<'_> {
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn resolve_declarations(
|
||||
// The construction phase is shared with private mixed resolution. Migration and
|
||||
// complete-model admission remain exclusively in each caller's finishing tail.
|
||||
struct ConstructedDeclarations {
|
||||
project: Project,
|
||||
legacy_elements: serde_json::Map<String, Value>,
|
||||
}
|
||||
|
||||
fn construct_declarations<'a>(
|
||||
mut project: Project,
|
||||
declarations: &[Declaration],
|
||||
declarations: impl IntoIterator<Item = &'a Declaration>,
|
||||
aliases: &BTreeMap<String, Id>,
|
||||
limits: ParseLimits,
|
||||
) -> Result<crate::persistence::DecodeResult, (usize, Error)> {
|
||||
mut before_fields: impl FnMut(&Declaration) -> Result<(), Error>,
|
||||
) -> Result<ConstructedDeclarations, (usize, Error)> {
|
||||
let legacy = project.schema_version == 3;
|
||||
let mut legacy_elements = serde_json::Map::new();
|
||||
let mut nodes = Vec::new();
|
||||
for (index, declaration) in declarations.iter().enumerate() {
|
||||
for (index, declaration) in declarations.into_iter().enumerate() {
|
||||
(|| -> Result<(), Error> {
|
||||
before_fields(declaration)?;
|
||||
let mut fields = declaration
|
||||
.fields
|
||||
.iter()
|
||||
@@ -1603,6 +1705,10 @@ pub(crate) fn resolve_declarations(
|
||||
};
|
||||
match d.kind {
|
||||
DeclKind::Element(kind, layer) => {
|
||||
if project.schema_version < 7 { crate::persistence::reject_source7_fields(&Value::Object(fields.clone())).map_err(&conversion_error)?; }
|
||||
if project.schema_version < 6 && !crate::persistence::pre6_element_kind(kind) {
|
||||
return Err(conversion_error(std::format!("{kind:?} requires schema/source 6.")));
|
||||
}
|
||||
if legacy && !crate::persistence::v3::element_allowed(serde_json::to_value(kind).unwrap().as_str().unwrap()) {
|
||||
return Err(conversion_error("Element constructor was not part of schema3.".into()));
|
||||
}
|
||||
@@ -1621,6 +1727,9 @@ pub(crate) fn resolve_declarations(
|
||||
}
|
||||
parent = Some(owner);
|
||||
}
|
||||
if kind.is_analysis() {
|
||||
return Err(conversion_error("Analysis records require the source8 authoring implementation.".into()));
|
||||
}
|
||||
let mut initial = if kind == Kind::Port {
|
||||
if !fields.contains_key("contract") {
|
||||
return Err(conversion_error(
|
||||
@@ -1677,12 +1786,18 @@ pub(crate) fn resolve_declarations(
|
||||
);
|
||||
}
|
||||
DeclKind::Relation(kind) => {
|
||||
if project.schema_version < 7 && kind == RelationKind::ContextualLink { return Err(conversion_error("ContextualLink requires schema/source 7.".into())); }
|
||||
if project.schema_version < 6 && !crate::persistence::pre6_relation_kind(kind) {
|
||||
return Err(conversion_error(std::format!("{kind:?} requires schema/source 6.")));
|
||||
}
|
||||
if legacy && !crate::persistence::v3::relation_allowed(serde_json::to_value(kind).unwrap().as_str().unwrap()) {
|
||||
return Err(conversion_error("Relation constructor was not part of schema3.".into()));
|
||||
}
|
||||
let description =
|
||||
take_string(&mut fields, "description", "").map_err(&conversion_error)?;
|
||||
let required: &[&str] = if kind == RelationKind::FunctionalExchange {
|
||||
let required: &[&str] = if kind == RelationKind::ContextualLink {
|
||||
&["owner", "source", "target", "purpose"]
|
||||
} else if kind == RelationKind::FunctionalExchange {
|
||||
&["source", "target", "source_port", "target_port"]
|
||||
} else {
|
||||
&["source", "target"]
|
||||
@@ -1713,8 +1828,15 @@ pub(crate) fn resolve_declarations(
|
||||
);
|
||||
}
|
||||
DeclKind::Diagram => {
|
||||
if project.schema_version < 7 { crate::persistence::reject_source7_fields(&Value::Object(fields.clone())).map_err(&conversion_error)?; }
|
||||
if project.schema_version < 6 && fields.contains_key("view_options") {
|
||||
return Err(conversion_error("Diagram.view_options requires schema/source 6, including an explicitly supplied default value.".into()));
|
||||
}
|
||||
if project.schema_version < 6 && let Some(key)=fields.keys().find(|key| !matches!(key.as_str(),"description"|"layer"|"projection"|"routes")) {
|
||||
return Err(conversion_error(std::format!("Unknown diagram field '{key}' in the frozen pre6 contract.")));
|
||||
}
|
||||
let defaults =
|
||||
serde_json::json!({"description":"","layer":"Oa","projection":"Overview","routes":[]});
|
||||
serde_json::json!({"description":"","layer":"Oa","projection":"Overview","routes":[],"view_options":crate::view_options::ViewOptions::default()});
|
||||
let mut record = merge_fields(defaults.as_object().unwrap().clone(), fields)
|
||||
.map_err(&conversion_error)?;
|
||||
header(&mut record, d, true);
|
||||
@@ -1785,11 +1907,25 @@ pub(crate) fn resolve_declarations(
|
||||
.map_err(|error| (index, error))?;
|
||||
target.nodes.insert(node.id, node);
|
||||
}
|
||||
Ok(ConstructedDeclarations {
|
||||
project,
|
||||
legacy_elements,
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) fn resolve_declarations(
|
||||
project: Project,
|
||||
declarations: &[Declaration],
|
||||
aliases: &BTreeMap<String, Id>,
|
||||
limits: ParseLimits,
|
||||
) -> Result<crate::persistence::DecodeResult, (usize, Error)> {
|
||||
let legacy = project.schema_version == 3;
|
||||
let ConstructedDeclarations {
|
||||
project,
|
||||
legacy_elements,
|
||||
} = construct_declarations(project, declarations, aliases, |_| Ok(()))?;
|
||||
if legacy {
|
||||
let mut value = serde_json::to_value(&project).expect("project serialization");
|
||||
value["elements"] = Value::Object(legacy_elements);
|
||||
let migrated = serde_json::from_value(value)
|
||||
.map_err(crate::persistence::FileError::Json)
|
||||
let migrated = source3_bridge::from_scratch(project, legacy_elements)
|
||||
.and_then(|old| crate::persistence::v3::migrate(old, limits))
|
||||
.map_err(|error| {
|
||||
let issue = if let crate::persistence::FileError::Model { issues, .. } = &error {
|
||||
@@ -1837,8 +1973,17 @@ pub(crate) fn resolve_declarations(
|
||||
}
|
||||
return Ok(migrated);
|
||||
}
|
||||
if project.schema_version == 4 {
|
||||
return crate::persistence::v4::finish(project, limits).map_err(|error| {
|
||||
if matches!(project.schema_version, 4..=7) {
|
||||
return (if project.schema_version == 4 {
|
||||
crate::persistence::v4::finish(project, limits)
|
||||
} else if project.schema_version == 5 {
|
||||
crate::persistence::migrate_v5(project, limits)
|
||||
} else if project.schema_version == 6 {
|
||||
crate::persistence::migrate_v6(project, limits)
|
||||
} else {
|
||||
crate::persistence::migrate_v7(project, limits)
|
||||
})
|
||||
.map_err(|error| {
|
||||
(
|
||||
usize::MAX,
|
||||
Error {
|
||||
|
||||
@@ -0,0 +1,116 @@
|
||||
//! Unresolved typed source8 syntax, staged for the complete source adapter.
|
||||
//! This module does not admit a Project or enable public source8.
|
||||
mod budget;
|
||||
mod cursor;
|
||||
mod declarations;
|
||||
mod index;
|
||||
mod lex;
|
||||
mod lower;
|
||||
pub(super) mod mixed;
|
||||
mod syntax;
|
||||
mod update;
|
||||
mod write;
|
||||
|
||||
#[cfg(test)]
|
||||
mod model_oracle;
|
||||
|
||||
use super::Span;
|
||||
use crate::analysis::{BinaryOp, UnaryOp};
|
||||
use crate::analysis_numeric::Exact;
|
||||
use budget::Budget;
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct Error {
|
||||
pub span: Span,
|
||||
pub message: String,
|
||||
}
|
||||
fn error(span: Span, message: impl Into<String>) -> Error {
|
||||
Error {
|
||||
span,
|
||||
message: message.into(),
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, PartialEq, Eq)]
|
||||
pub struct Reference {
|
||||
pub name: String,
|
||||
pub span: Span,
|
||||
}
|
||||
#[derive(Debug, PartialEq, Eq)]
|
||||
pub struct Argument {
|
||||
pub parameter: Reference,
|
||||
pub value: Expression,
|
||||
}
|
||||
#[derive(Debug, PartialEq, Eq)]
|
||||
pub struct Expression {
|
||||
pub kind: ExpressionKind,
|
||||
pub span: Span,
|
||||
pub depth: usize,
|
||||
pub grouped: bool,
|
||||
/// Original numeric tokens, including constructor punctuation, excluding
|
||||
/// trivia. The full span retains intervening comments and spelling.
|
||||
pub literal: Option<LiteralSyntax>,
|
||||
}
|
||||
#[derive(Debug, PartialEq, Eq)]
|
||||
pub struct LiteralSyntax {
|
||||
pub span: Span,
|
||||
pub tokens: Vec<Span>,
|
||||
}
|
||||
#[derive(Debug, PartialEq, Eq)]
|
||||
pub enum ExpressionKind {
|
||||
Boolean(bool),
|
||||
Number(Exact),
|
||||
Quantity {
|
||||
magnitude: Exact,
|
||||
unit: Reference,
|
||||
},
|
||||
Property(Reference),
|
||||
Parameter(Reference),
|
||||
List(Vec<Expression>),
|
||||
Unary {
|
||||
op: UnaryOp,
|
||||
operand: Box<Expression>,
|
||||
},
|
||||
Binary {
|
||||
op: BinaryOp,
|
||||
left: Box<Expression>,
|
||||
right: Box<Expression>,
|
||||
},
|
||||
If {
|
||||
condition: Box<Expression>,
|
||||
when_true: Box<Expression>,
|
||||
when_false: Box<Expression>,
|
||||
},
|
||||
Call {
|
||||
definition: Reference,
|
||||
arguments: Vec<Argument>,
|
||||
},
|
||||
Sum {
|
||||
values: Box<Expression>,
|
||||
initial: Box<Expression>,
|
||||
},
|
||||
Power {
|
||||
base: Box<Expression>,
|
||||
exponent: i8,
|
||||
},
|
||||
AsKind {
|
||||
kind: Reference,
|
||||
value: Box<Expression>,
|
||||
},
|
||||
}
|
||||
#[derive(Debug, PartialEq, Eq)]
|
||||
pub enum Binding {
|
||||
Unbound(Span),
|
||||
Expression(Expression),
|
||||
}
|
||||
|
||||
pub fn parse(source: &str, budget: &mut Budget) -> Result<Binding, Error> {
|
||||
let tokens = lex::tokens(source, budget)?;
|
||||
let mut cursor = cursor::Cursor::new(source, &tokens, budget);
|
||||
let binding = syntax::binding(&mut cursor)?;
|
||||
cursor.end()?;
|
||||
Ok(binding)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
@@ -0,0 +1,162 @@
|
||||
//! Candidate limits for measured adoption; one owner spans all parsed files.
|
||||
use super::{Error, Span, error};
|
||||
use crate::analysis_numeric::{Exact, WorkLimits, WorkMeter};
|
||||
use crate::language::ParseLimits;
|
||||
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub struct Limits {
|
||||
pub bytes: usize,
|
||||
pub tokens: usize,
|
||||
pub entries: usize,
|
||||
pub references: usize,
|
||||
pub frames: usize,
|
||||
pub numeric_units: u64,
|
||||
}
|
||||
impl Limits {
|
||||
pub fn source8(caller: ParseLimits) -> Self {
|
||||
let bytes = caller.max_source_bytes.min(64 * 1024 * 1024);
|
||||
Self {
|
||||
bytes,
|
||||
tokens: bytes.min(1_048_576),
|
||||
entries: caller.max_records.min(262_144),
|
||||
references: caller.max_step_references.min(500_000),
|
||||
frames: 256,
|
||||
numeric_units: 50_000_000,
|
||||
}
|
||||
}
|
||||
}
|
||||
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
|
||||
pub struct Usage {
|
||||
pub bytes: usize,
|
||||
pub tokens: usize,
|
||||
pub entries: usize,
|
||||
pub references: usize,
|
||||
pub deepest_frame: usize,
|
||||
}
|
||||
pub struct Budget {
|
||||
limits: Limits,
|
||||
pub usage: Usage,
|
||||
numeric: WorkMeter,
|
||||
failed: Option<Error>,
|
||||
}
|
||||
impl Budget {
|
||||
pub fn new(limits: Limits) -> Result<Self, Error> {
|
||||
let hard = Limits::source8(ParseLimits::UNLIMITED);
|
||||
if limits.bytes > hard.bytes
|
||||
|| limits.tokens > hard.tokens
|
||||
|| limits.entries > hard.entries
|
||||
|| limits.references > hard.references
|
||||
|| limits.frames > hard.frames
|
||||
|| limits.numeric_units > hard.numeric_units
|
||||
{
|
||||
return Err(error(
|
||||
Span::default(),
|
||||
"Source8 profile cannot exceed candidate hard limits.",
|
||||
));
|
||||
}
|
||||
Ok(Self {
|
||||
limits,
|
||||
usage: Usage::default(),
|
||||
numeric: WorkMeter::new(
|
||||
WorkLimits::new(0, limits.numeric_units)
|
||||
.map_err(|e| error(Span::default(), e.to_string()))?,
|
||||
),
|
||||
failed: None,
|
||||
})
|
||||
}
|
||||
pub fn active(&self) -> Result<(), Error> {
|
||||
self.failed.clone().map_or(Ok(()), Err)
|
||||
}
|
||||
fn charge(
|
||||
&mut self,
|
||||
used: usize,
|
||||
amount: usize,
|
||||
maximum: usize,
|
||||
span: Span,
|
||||
name: &str,
|
||||
) -> Result<(), Error> {
|
||||
self.active()?;
|
||||
if amount > maximum.saturating_sub(used) {
|
||||
let failure = error(span, format!("Source8 {name} limit exceeded."));
|
||||
self.failed = Some(failure.clone());
|
||||
return Err(failure);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
pub fn bytes(&mut self, amount: usize, span: Span) -> Result<(), Error> {
|
||||
self.charge(self.usage.bytes, amount, self.limits.bytes, span, "bytes")?;
|
||||
self.usage.bytes += amount;
|
||||
Ok(())
|
||||
}
|
||||
pub fn token(&mut self, span: Span) -> Result<(), Error> {
|
||||
self.charge(self.usage.tokens, 1, self.limits.tokens, span, "tokens")?;
|
||||
self.usage.tokens += 1;
|
||||
Ok(())
|
||||
}
|
||||
pub fn entry(&mut self, span: Span) -> Result<(), Error> {
|
||||
self.charge(
|
||||
self.usage.entries,
|
||||
1,
|
||||
self.limits.entries,
|
||||
span,
|
||||
"syntax entries",
|
||||
)?;
|
||||
self.usage.entries += 1;
|
||||
Ok(())
|
||||
}
|
||||
pub fn reference(&mut self, span: Span) -> Result<(), Error> {
|
||||
self.charge(
|
||||
self.usage.references,
|
||||
1,
|
||||
self.limits.references,
|
||||
span,
|
||||
"references",
|
||||
)?;
|
||||
self.usage.references += 1;
|
||||
Ok(())
|
||||
}
|
||||
pub fn frame(&mut self, depth: usize, span: Span) -> Result<(), Error> {
|
||||
self.charge(0, depth, self.limits.frames, span, "syntax frames")?;
|
||||
self.usage.deepest_frame = self.usage.deepest_frame.max(depth);
|
||||
Ok(())
|
||||
}
|
||||
pub fn exact(&mut self, spelling: &str, span: Span) -> Result<Exact, Error> {
|
||||
self.active()?;
|
||||
match Exact::parse_literal(spelling, &mut self.numeric) {
|
||||
Ok(value) => Ok(value),
|
||||
Err(cause) => {
|
||||
let failure = error(span, cause.to_string());
|
||||
self.failed = Some(failure.clone());
|
||||
Err(failure)
|
||||
}
|
||||
}
|
||||
}
|
||||
pub fn numeric_units(&self) -> u64 {
|
||||
self.numeric.usage().numeric_units
|
||||
}
|
||||
/// Check phase allocation bounds without recharging parsed syntax or exact
|
||||
/// work. S4 must also charge ordinary records through the inherited budget.
|
||||
pub fn lowering_entries(&self, count: usize, span: Span) -> Result<(), Error> {
|
||||
self.active()?;
|
||||
if count > self.limits.entries {
|
||||
return Err(error(span, "Source8 lowering entry limit exceeded."));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
/// Aggregate owned text for an index/update phase, checked before copying.
|
||||
pub fn index_bytes(&self, count: usize, span: Span) -> Result<(), Error> {
|
||||
self.active()?;
|
||||
if count > self.limits.bytes {
|
||||
return Err(error(span, "Source8 index/output byte limit exceeded."));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
pub fn lowering_occurrences(&self, count: usize, span: Span) -> Result<(), Error> {
|
||||
self.active()?;
|
||||
// Parameter declarations are syntax entries, not reference uses.
|
||||
if count > self.limits.references.saturating_add(self.limits.entries) {
|
||||
return Err(error(span, "Source8 lowering occurrence limit exceeded."));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,171 @@
|
||||
//! A borrowed significant-token cursor. Spans always refer to the full source.
|
||||
use super::*;
|
||||
use lex::{Class, Token};
|
||||
|
||||
pub(super) struct Cursor<'a, 'b> {
|
||||
pub source: &'a str,
|
||||
pub tokens: &'a [Token],
|
||||
pub cursor: usize,
|
||||
pub frames: usize,
|
||||
pub budget: &'b mut Budget,
|
||||
}
|
||||
impl<'a, 'b> Cursor<'a, 'b> {
|
||||
pub(super) fn new(source: &'a str, tokens: &'a [Token], budget: &'b mut Budget) -> Self {
|
||||
Self {
|
||||
source,
|
||||
tokens,
|
||||
cursor: 0,
|
||||
frames: 0,
|
||||
budget,
|
||||
}
|
||||
}
|
||||
}
|
||||
impl Cursor<'_, '_> {
|
||||
pub(super) fn span(&self) -> Span {
|
||||
self.tokens.get(self.cursor).map_or(
|
||||
Span {
|
||||
start: self.source.len(),
|
||||
end: self.source.len(),
|
||||
},
|
||||
|token| token.span,
|
||||
)
|
||||
}
|
||||
pub(super) fn text(&self) -> &str {
|
||||
let span = self.span();
|
||||
&self.source[span.start..span.end]
|
||||
}
|
||||
pub(super) fn take(&mut self, expected: &str) -> Result<Span, Error> {
|
||||
if self.text() != expected {
|
||||
return Err(error(self.span(), format!("Expected '{expected}'.")));
|
||||
}
|
||||
let span = self.span();
|
||||
self.cursor += 1;
|
||||
Ok(span)
|
||||
}
|
||||
pub(super) fn end(&self) -> Result<(), Error> {
|
||||
if self.cursor != self.tokens.len() {
|
||||
Err(error(
|
||||
self.span(),
|
||||
"Unexpected content after analysis expression.",
|
||||
))
|
||||
} else {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
pub(super) fn open(&mut self) -> Result<(), Error> {
|
||||
self.budget.frame(self.frames + 1, self.span())?;
|
||||
self.frames += 1;
|
||||
Ok(())
|
||||
}
|
||||
pub(super) fn close(&mut self) {
|
||||
self.frames -= 1;
|
||||
}
|
||||
pub(super) fn reference(&mut self) -> Result<Reference, Error> {
|
||||
self.budget.reference(self.span())?;
|
||||
self.name()
|
||||
}
|
||||
pub(super) fn name(&mut self) -> Result<Reference, Error> {
|
||||
let span = self.span();
|
||||
if !self
|
||||
.tokens
|
||||
.get(self.cursor)
|
||||
.is_some_and(|token| token.class == Class::Word)
|
||||
|| !crate::valid_alias(self.text())
|
||||
{
|
||||
return Err(error(span, "Expected a valid reference or parameter name."));
|
||||
}
|
||||
let name = self.text().to_owned();
|
||||
self.cursor += 1;
|
||||
Ok(Reference { name, span })
|
||||
}
|
||||
pub(super) fn quoted(&mut self) -> Result<String, Error> {
|
||||
let span = self.span();
|
||||
if !self
|
||||
.tokens
|
||||
.get(self.cursor)
|
||||
.is_some_and(|token| token.class == Class::String)
|
||||
{
|
||||
return Err(error(span, "Expected a quoted string."));
|
||||
}
|
||||
let value =
|
||||
serde_json::from_str(self.text()).map_err(|_| error(span, "Invalid quoted string."))?;
|
||||
self.cursor += 1;
|
||||
Ok(value)
|
||||
}
|
||||
pub(super) fn last_end(&self) -> usize {
|
||||
self.tokens[self.cursor - 1].span.end
|
||||
}
|
||||
pub(super) fn exact_literal(&mut self) -> Result<(Exact, LiteralSyntax), Error> {
|
||||
if self.text() == "ratio" {
|
||||
return self.ratio();
|
||||
}
|
||||
let span = self.span();
|
||||
if !self
|
||||
.tokens
|
||||
.get(self.cursor)
|
||||
.is_some_and(|token| token.class == Class::Number)
|
||||
{
|
||||
return Err(error(span, "Expected an exact numeric atom or ratio."));
|
||||
}
|
||||
let value = self
|
||||
.budget
|
||||
.exact(&self.source[span.start..span.end], span)?;
|
||||
self.cursor += 1;
|
||||
Ok((
|
||||
value,
|
||||
LiteralSyntax {
|
||||
span,
|
||||
tokens: vec![span],
|
||||
},
|
||||
))
|
||||
}
|
||||
pub(super) fn integer(&mut self) -> Result<Span, Error> {
|
||||
let span = self.span();
|
||||
let text = self.text();
|
||||
if text.is_empty() || !text.bytes().all(|b| b.is_ascii_digit()) {
|
||||
return Err(error(span, "Expected unsigned integer digits."));
|
||||
}
|
||||
if text.len() > crate::analysis_numeric::MAX_COMPONENT_DIGITS {
|
||||
return Err(error(span, "Integer component exceeds digit limit."));
|
||||
}
|
||||
self.cursor += 1;
|
||||
Ok(span)
|
||||
}
|
||||
pub(super) fn ratio(&mut self) -> Result<(Exact, LiteralSyntax), Error> {
|
||||
let first_token = self.cursor;
|
||||
let start = self.take("ratio")?.start;
|
||||
self.open()?;
|
||||
self.take("(")?;
|
||||
let negative = if self.text() == "-" {
|
||||
self.cursor += 1;
|
||||
true
|
||||
} else {
|
||||
false
|
||||
};
|
||||
let numerator = self.integer()?;
|
||||
self.take(",")?;
|
||||
let denominator = self.integer()?;
|
||||
let end = self.take(")")?.end;
|
||||
self.close();
|
||||
let n = &self.source[numerator.start..numerator.end];
|
||||
let d = &self.source[denominator.start..denominator.end];
|
||||
let length = 9 + usize::from(negative) + n.len() + d.len();
|
||||
if length > crate::analysis_numeric::MAX_LITERAL_BYTES {
|
||||
return Err(error(
|
||||
Span { start, end },
|
||||
"Numeric reconstruction exceeds literal byte limit.",
|
||||
));
|
||||
}
|
||||
let normalized = format!("ratio({}{n}, {d})", if negative { "-" } else { "" });
|
||||
Ok((
|
||||
self.budget.exact(&normalized, Span { start, end })?,
|
||||
LiteralSyntax {
|
||||
span: Span { start, end },
|
||||
tokens: self.tokens[first_token..self.cursor]
|
||||
.iter()
|
||||
.map(|token| token.span)
|
||||
.collect(),
|
||||
},
|
||||
))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,635 @@
|
||||
//! Required typed declaration syntax. No model construction or resolution.
|
||||
use super::cursor::Cursor;
|
||||
use super::*;
|
||||
use crate::{Id, Layer};
|
||||
use std::collections::BTreeSet;
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum DeclarationKind {
|
||||
QuantityKind,
|
||||
Unit,
|
||||
Calculation,
|
||||
Property(Layer),
|
||||
Check(Layer),
|
||||
Case(Layer),
|
||||
}
|
||||
|
||||
/// Contextual recognition only: never add these words to the global alias ban.
|
||||
pub fn declaration_kind(word: &str) -> Option<DeclarationKind> {
|
||||
use DeclarationKind::*;
|
||||
Some(match word {
|
||||
"quantity_kind" => QuantityKind,
|
||||
"unit" => Unit,
|
||||
"calculation" => Calculation,
|
||||
"oa_property" => Property(Layer::Oa),
|
||||
"sa_property" => Property(Layer::Sa),
|
||||
"oa_check" => Check(Layer::Oa),
|
||||
"sa_check" => Check(Layer::Sa),
|
||||
"oa_analysis" => Case(Layer::Oa),
|
||||
"sa_analysis" => Case(Layer::Sa),
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
|
||||
#[derive(Debug, PartialEq, Eq)]
|
||||
pub struct IdentitySyntax {
|
||||
/// Missing IDs stay unresolved here. The bundle stabilization owner assigns
|
||||
/// and inserts an ID once, then reparses the actual returned bytes.
|
||||
pub value: Option<Id>,
|
||||
pub keyword: Option<Span>,
|
||||
pub literal: Option<Span>,
|
||||
pub insertion: Option<usize>,
|
||||
}
|
||||
|
||||
#[derive(Debug, PartialEq, Eq)]
|
||||
pub struct Header {
|
||||
pub kind: DeclarationKind,
|
||||
pub kind_span: Span,
|
||||
pub alias: Reference,
|
||||
pub name: String,
|
||||
pub name_span: Span,
|
||||
pub identity: IdentitySyntax,
|
||||
pub span: Span,
|
||||
}
|
||||
|
||||
#[derive(Debug, PartialEq, Eq)]
|
||||
pub struct Field<T> {
|
||||
/// Complete field including its keyword and trailing semicolon.
|
||||
pub span: Span,
|
||||
pub keyword: Span,
|
||||
/// Same meaning as an ordinary top-level field value span.
|
||||
pub value_span: Span,
|
||||
pub value: T,
|
||||
}
|
||||
|
||||
#[derive(Debug, PartialEq, Eq)]
|
||||
pub struct ScalarSyntax {
|
||||
pub span: Span,
|
||||
pub kind: ScalarKind,
|
||||
}
|
||||
|
||||
#[derive(Debug, PartialEq, Eq)]
|
||||
pub enum ScalarKind {
|
||||
Boolean,
|
||||
Number,
|
||||
Quantity(Reference),
|
||||
}
|
||||
|
||||
#[derive(Debug, PartialEq, Eq)]
|
||||
pub struct TypeSyntax {
|
||||
pub span: Span,
|
||||
pub scalar: ScalarSyntax,
|
||||
pub list: bool,
|
||||
}
|
||||
|
||||
#[derive(Debug, PartialEq, Eq)]
|
||||
pub struct ParameterSyntax {
|
||||
pub span: Span,
|
||||
pub name: Reference,
|
||||
pub identity: IdentitySyntax,
|
||||
pub value_type: TypeSyntax,
|
||||
}
|
||||
|
||||
#[derive(Debug, PartialEq, Eq)]
|
||||
pub struct DimensionEntry {
|
||||
pub axis: Span,
|
||||
pub exponent: Span,
|
||||
pub span: Span,
|
||||
}
|
||||
|
||||
#[derive(Debug, PartialEq, Eq)]
|
||||
pub struct DimensionSyntax {
|
||||
pub exponents: [i16; 7],
|
||||
pub entries: Vec<DimensionEntry>,
|
||||
}
|
||||
|
||||
#[derive(Debug, PartialEq, Eq)]
|
||||
pub enum AlgebraSyntax {
|
||||
Linear,
|
||||
Affine(Reference),
|
||||
}
|
||||
|
||||
#[derive(Debug, PartialEq, Eq)]
|
||||
pub struct ExactSyntax {
|
||||
pub value: Exact,
|
||||
pub literal: LiteralSyntax,
|
||||
}
|
||||
|
||||
#[derive(Debug, PartialEq, Eq)]
|
||||
pub struct OverrideSyntax {
|
||||
pub span: Span,
|
||||
pub target: Reference,
|
||||
pub binding: Binding,
|
||||
pub binding_span: Span,
|
||||
}
|
||||
|
||||
#[derive(Debug, PartialEq, Eq)]
|
||||
pub enum Body {
|
||||
QuantityKind {
|
||||
dimension: Field<DimensionSyntax>,
|
||||
algebra: Field<AlgebraSyntax>,
|
||||
},
|
||||
Unit {
|
||||
kind: Field<Reference>,
|
||||
scale: Field<ExactSyntax>,
|
||||
offset: Field<ExactSyntax>,
|
||||
symbol: Field<String>,
|
||||
},
|
||||
Calculation {
|
||||
parameters: Vec<ParameterSyntax>,
|
||||
result: Field<TypeSyntax>,
|
||||
body: Field<Binding>,
|
||||
},
|
||||
Property {
|
||||
subject: Field<Reference>,
|
||||
value_type: Field<TypeSyntax>,
|
||||
base: Field<Binding>,
|
||||
display_unit: Option<Field<Option<Reference>>>,
|
||||
},
|
||||
Check {
|
||||
subject: Option<Field<Option<Reference>>>,
|
||||
documented_constraint: Option<Field<Option<Reference>>>,
|
||||
predicate: Field<Binding>,
|
||||
},
|
||||
Case {
|
||||
subject: Option<Field<Option<Reference>>>,
|
||||
base: Field<()>,
|
||||
overrides: Field<Vec<OverrideSyntax>>,
|
||||
},
|
||||
}
|
||||
|
||||
#[derive(Debug, PartialEq, Eq)]
|
||||
pub struct Declaration {
|
||||
pub header: Header,
|
||||
pub span: Span,
|
||||
pub body_span: Span,
|
||||
pub description: Option<Field<String>>,
|
||||
/// Analysis roots may explicitly spell `parent none`; definitions may not.
|
||||
pub parent: Option<Field<()>>,
|
||||
pub body: Body,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct Fields {
|
||||
dimension: Option<Field<DimensionSyntax>>,
|
||||
algebra: Option<Field<AlgebraSyntax>>,
|
||||
kind: Option<Field<Reference>>,
|
||||
scale: Option<Field<ExactSyntax>>,
|
||||
offset: Option<Field<ExactSyntax>>,
|
||||
symbol: Option<Field<String>>,
|
||||
result: Option<Field<TypeSyntax>>,
|
||||
body: Option<Field<Binding>>,
|
||||
subject: Option<Field<Reference>>,
|
||||
optional_subject: Option<Field<Option<Reference>>>,
|
||||
value_type: Option<Field<TypeSyntax>>,
|
||||
base: Option<Field<Binding>>,
|
||||
display_unit: Option<Field<Option<Reference>>>,
|
||||
documented_constraint: Option<Field<Option<Reference>>>,
|
||||
predicate: Option<Field<Binding>>,
|
||||
baseline: Option<Field<()>>,
|
||||
overrides: Option<Field<Vec<OverrideSyntax>>>,
|
||||
}
|
||||
|
||||
fn required<T>(value: Option<T>, name: &str, at: Span) -> Result<T, Error> {
|
||||
value.ok_or_else(|| error(at, format!("Missing required field '{name}'.")))
|
||||
}
|
||||
|
||||
impl Fields {
|
||||
fn finish(
|
||||
self,
|
||||
kind: DeclarationKind,
|
||||
parameters: Vec<ParameterSyntax>,
|
||||
at: Span,
|
||||
) -> Result<Body, Error> {
|
||||
Ok(match kind {
|
||||
DeclarationKind::QuantityKind => Body::QuantityKind {
|
||||
dimension: required(self.dimension, "dimension", at)?,
|
||||
algebra: required(self.algebra, "algebra", at)?,
|
||||
},
|
||||
DeclarationKind::Unit => Body::Unit {
|
||||
kind: required(self.kind, "kind", at)?,
|
||||
scale: required(self.scale, "scale", at)?,
|
||||
offset: required(self.offset, "offset", at)?,
|
||||
symbol: required(self.symbol, "symbol", at)?,
|
||||
},
|
||||
DeclarationKind::Calculation => Body::Calculation {
|
||||
parameters,
|
||||
result: required(self.result, "result", at)?,
|
||||
body: required(self.body, "body", at)?,
|
||||
},
|
||||
DeclarationKind::Property(_) => Body::Property {
|
||||
subject: required(self.subject, "subject", at)?,
|
||||
value_type: required(self.value_type, "type", at)?,
|
||||
base: required(self.base, "base", at)?,
|
||||
display_unit: self.display_unit,
|
||||
},
|
||||
DeclarationKind::Check(_) => Body::Check {
|
||||
subject: self.optional_subject,
|
||||
documented_constraint: self.documented_constraint,
|
||||
predicate: required(self.predicate, "predicate", at)?,
|
||||
},
|
||||
DeclarationKind::Case(_) => Body::Case {
|
||||
subject: self.optional_subject,
|
||||
base: required(self.baseline, "base", at)?,
|
||||
overrides: required(self.overrides, "overrides", at)?,
|
||||
},
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// Consume exactly one declaration from already charged full-file tokens.
|
||||
/// `version` is inherited from the caller's entry policy; fragments have no
|
||||
/// independent version header. Public parsing does not call this staged API.
|
||||
pub(super) fn parse(
|
||||
p: &mut Cursor<'_, '_>,
|
||||
version: u32,
|
||||
lexical_owner: Option<Id>,
|
||||
) -> Result<Declaration, Error> {
|
||||
p.budget.active()?;
|
||||
let kind_span = p.span();
|
||||
let kind = declaration_kind(p.text())
|
||||
.ok_or_else(|| error(kind_span, "Expected a short typed declaration word."))?;
|
||||
if version != 8 {
|
||||
return Err(error(kind_span, "Analysis declarations require source8."));
|
||||
}
|
||||
if lexical_owner.is_some() {
|
||||
return Err(error(
|
||||
kind_span,
|
||||
"Analysis declarations and definitions must be roots.",
|
||||
));
|
||||
}
|
||||
p.budget.entry(kind_span)?;
|
||||
p.cursor += 1;
|
||||
let alias = p.name()?;
|
||||
let name_span = p.span();
|
||||
let name = p.quoted()?;
|
||||
let identity = p.identity()?;
|
||||
p.open()?;
|
||||
let opening = p.take("{")?;
|
||||
let header = Header {
|
||||
kind,
|
||||
kind_span,
|
||||
alias,
|
||||
name,
|
||||
name_span,
|
||||
identity,
|
||||
span: Span {
|
||||
start: kind_span.start,
|
||||
end: opening.start,
|
||||
},
|
||||
};
|
||||
let mut fields = Fields::default();
|
||||
let mut description = None;
|
||||
let mut parent = None;
|
||||
let mut parameters = Vec::new();
|
||||
let mut seen = BTreeSet::new();
|
||||
let mut parameter_names = BTreeSet::new();
|
||||
let mut parameter_ids = BTreeSet::new();
|
||||
while p.text() != "}" {
|
||||
let keyword = p.span();
|
||||
p.budget.entry(keyword)?;
|
||||
if p.text() == "input" && kind == DeclarationKind::Calculation {
|
||||
let parameter = p.parameter()?;
|
||||
if !parameter_names.insert(parameter.name.name.clone()) {
|
||||
return Err(error(parameter.name.span, "Duplicate parameter name."));
|
||||
}
|
||||
if let Some(id) = parameter.identity.value
|
||||
&& !parameter_ids.insert(id)
|
||||
{
|
||||
return Err(error(
|
||||
parameter.identity.literal.expect("explicit identity"),
|
||||
"Duplicate parameter identity.",
|
||||
));
|
||||
}
|
||||
parameters.push(parameter);
|
||||
continue;
|
||||
}
|
||||
// Borrow the original spelling for duplicate detection; no field-name
|
||||
// allocation and no map insertion can overwrite an earlier value.
|
||||
let source = p.source;
|
||||
let key = &source[keyword.start..keyword.end];
|
||||
if !seen.insert(key) {
|
||||
return Err(error(keyword, format!("Duplicate field '{key}'.")));
|
||||
}
|
||||
p.cursor += 1;
|
||||
use DeclarationKind::*;
|
||||
match (kind, key) {
|
||||
(_, "description") => description = Some(p.field(keyword, |p| p.quoted())?),
|
||||
(Property(_) | Check(_) | Case(_), "parent") => {
|
||||
parent = Some(p.field(keyword, |p| {
|
||||
p.take("none")?;
|
||||
Ok(())
|
||||
})?)
|
||||
}
|
||||
(QuantityKind, "dimension") => {
|
||||
fields.dimension = Some(p.field(keyword, |p| p.dimension())?)
|
||||
}
|
||||
(QuantityKind, "algebra") => fields.algebra = Some(p.field(keyword, |p| p.algebra())?),
|
||||
(Unit, "kind") => fields.kind = Some(p.field(keyword, |p| p.at_reference())?),
|
||||
(Unit, "scale") => fields.scale = Some(p.field(keyword, |p| p.exact_value())?),
|
||||
(Unit, "offset") => fields.offset = Some(p.field(keyword, |p| p.exact_value())?),
|
||||
(Unit, "symbol") => fields.symbol = Some(p.field(keyword, |p| p.quoted())?),
|
||||
(Calculation, "result") => fields.result = Some(p.field(keyword, |p| p.value_type())?),
|
||||
(Calculation, "body") => fields.body = Some(p.field(keyword, syntax::binding)?),
|
||||
(Property(_), "subject") => {
|
||||
fields.subject = Some(p.field(keyword, |p| p.at_reference())?)
|
||||
}
|
||||
(Property(_), "type") => {
|
||||
fields.value_type = Some(p.field(keyword, |p| p.value_type())?)
|
||||
}
|
||||
(Property(_), "base") => fields.base = Some(p.field(keyword, syntax::binding)?),
|
||||
(Property(_), "display_unit") => {
|
||||
fields.display_unit = Some(p.field(keyword, |p| p.optional_reference())?)
|
||||
}
|
||||
(Check(_) | Case(_), "subject") => {
|
||||
fields.optional_subject = Some(p.field(keyword, |p| p.optional_reference())?)
|
||||
}
|
||||
(Check(_), "documented_constraint") => {
|
||||
fields.documented_constraint = Some(p.field(keyword, |p| p.optional_reference())?)
|
||||
}
|
||||
(Check(_), "predicate") => fields.predicate = Some(p.field(keyword, syntax::binding)?),
|
||||
(Case(_), "base") => {
|
||||
fields.baseline = Some(p.field(keyword, |p| {
|
||||
p.take("ModelBaseline")?;
|
||||
Ok(())
|
||||
})?)
|
||||
}
|
||||
(Case(_), "overrides") => fields.overrides = Some(p.field(keyword, |p| p.overrides())?),
|
||||
_ => {
|
||||
return Err(error(
|
||||
keyword,
|
||||
format!("Unknown field '{key}' for this typed declaration."),
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
let closing = p.take("}")?;
|
||||
p.close();
|
||||
let body = fields.finish(kind, parameters, closing)?;
|
||||
Ok(Declaration {
|
||||
header,
|
||||
span: Span {
|
||||
start: kind_span.start,
|
||||
end: closing.end,
|
||||
},
|
||||
body_span: Span {
|
||||
start: opening.end,
|
||||
end: closing.start,
|
||||
},
|
||||
description,
|
||||
parent,
|
||||
body,
|
||||
})
|
||||
}
|
||||
|
||||
impl Cursor<'_, '_> {
|
||||
fn field<T>(
|
||||
&mut self,
|
||||
keyword: Span,
|
||||
parse: impl FnOnce(&mut Self) -> Result<T, Error>,
|
||||
) -> Result<Field<T>, Error> {
|
||||
let start = self.span().start;
|
||||
let value = parse(self)?;
|
||||
let end = self.last_end();
|
||||
let terminator = self.take(";")?;
|
||||
Ok(Field {
|
||||
span: Span {
|
||||
start: keyword.start,
|
||||
end: terminator.end,
|
||||
},
|
||||
keyword,
|
||||
value_span: Span { start, end },
|
||||
value,
|
||||
})
|
||||
}
|
||||
|
||||
fn identity(&mut self) -> Result<IdentitySyntax, Error> {
|
||||
if self.text() != "id" {
|
||||
return Ok(IdentitySyntax {
|
||||
value: None,
|
||||
keyword: None,
|
||||
literal: None,
|
||||
insertion: Some(self.span().start),
|
||||
});
|
||||
}
|
||||
let keyword = self.take("id")?;
|
||||
let literal = self.span();
|
||||
let spelling = self.quoted()?;
|
||||
if spelling.len() != 36
|
||||
|| ![8, 13, 18, 23]
|
||||
.into_iter()
|
||||
.all(|at| spelling.as_bytes()[at] == b'-')
|
||||
{
|
||||
return Err(error(
|
||||
literal,
|
||||
"Expected UUID in 8-4-4-4-12 hexadecimal form.",
|
||||
));
|
||||
}
|
||||
let id = Id::parse_str(&spelling).map_err(|_| error(literal, "Invalid UUID identity."))?;
|
||||
Ok(IdentitySyntax {
|
||||
value: Some(id),
|
||||
keyword: Some(keyword),
|
||||
literal: Some(literal),
|
||||
insertion: None,
|
||||
})
|
||||
}
|
||||
|
||||
fn parameter(&mut self) -> Result<ParameterSyntax, Error> {
|
||||
let start = self.take("input")?.start;
|
||||
let name = self.name()?;
|
||||
let identity = self.identity()?;
|
||||
self.take(":")?;
|
||||
let value_type = self.value_type()?;
|
||||
let end = self.take(";")?.end;
|
||||
Ok(ParameterSyntax {
|
||||
span: Span { start, end },
|
||||
name,
|
||||
identity,
|
||||
value_type,
|
||||
})
|
||||
}
|
||||
|
||||
fn at_reference(&mut self) -> Result<Reference, Error> {
|
||||
self.take("@")?;
|
||||
self.reference()
|
||||
}
|
||||
|
||||
fn optional_reference(&mut self) -> Result<Option<Reference>, Error> {
|
||||
if self.text() == "none" {
|
||||
self.cursor += 1;
|
||||
Ok(None)
|
||||
} else {
|
||||
self.at_reference().map(Some)
|
||||
}
|
||||
}
|
||||
|
||||
fn exact_value(&mut self) -> Result<ExactSyntax, Error> {
|
||||
let (value, literal) = self.exact_literal()?;
|
||||
Ok(ExactSyntax { value, literal })
|
||||
}
|
||||
|
||||
fn value_type(&mut self) -> Result<TypeSyntax, Error> {
|
||||
let start = self.span().start;
|
||||
self.budget.entry(self.span())?;
|
||||
let list = self.text() == "List";
|
||||
if list {
|
||||
self.open()?;
|
||||
self.cursor += 1;
|
||||
self.take("(")?;
|
||||
}
|
||||
let scalar = self.scalar_type()?;
|
||||
if list {
|
||||
self.take(")")?;
|
||||
self.close();
|
||||
}
|
||||
Ok(TypeSyntax {
|
||||
span: Span {
|
||||
start,
|
||||
end: self.last_end(),
|
||||
},
|
||||
scalar,
|
||||
list,
|
||||
})
|
||||
}
|
||||
|
||||
fn scalar_type(&mut self) -> Result<ScalarSyntax, Error> {
|
||||
let start = self.span().start;
|
||||
let kind = match self.text() {
|
||||
"Boolean" => {
|
||||
self.cursor += 1;
|
||||
ScalarKind::Boolean
|
||||
}
|
||||
"Number" => {
|
||||
self.cursor += 1;
|
||||
ScalarKind::Number
|
||||
}
|
||||
"Quantity" => {
|
||||
self.open()?;
|
||||
self.cursor += 1;
|
||||
self.take("(")?;
|
||||
let reference = self.at_reference()?;
|
||||
self.take(")")?;
|
||||
self.close();
|
||||
ScalarKind::Quantity(reference)
|
||||
}
|
||||
_ => {
|
||||
return Err(error(
|
||||
self.span(),
|
||||
"Expected Boolean, Number or Quantity(@kind); nested List is not a scalar type.",
|
||||
));
|
||||
}
|
||||
};
|
||||
Ok(ScalarSyntax {
|
||||
span: Span {
|
||||
start,
|
||||
end: self.last_end(),
|
||||
},
|
||||
kind,
|
||||
})
|
||||
}
|
||||
|
||||
fn dimension(&mut self) -> Result<DimensionSyntax, Error> {
|
||||
self.open()?;
|
||||
self.take("{")?;
|
||||
let mut exponents = [0; 7];
|
||||
let mut seen = [false; 7];
|
||||
let mut entries = Vec::new();
|
||||
while self.text() != "}" {
|
||||
let axis = self.span();
|
||||
self.budget.entry(axis)?;
|
||||
let index = match self.text() {
|
||||
"length" => 0,
|
||||
"mass" => 1,
|
||||
"time" => 2,
|
||||
"electric_current" => 3,
|
||||
"temperature" => 4,
|
||||
"amount" => 5,
|
||||
"luminous_intensity" => 6,
|
||||
_ => return Err(error(axis, "Unknown dimension axis.")),
|
||||
};
|
||||
if seen[index] {
|
||||
return Err(error(axis, "Duplicate dimension axis."));
|
||||
}
|
||||
seen[index] = true;
|
||||
self.cursor += 1;
|
||||
let start = self.span().start;
|
||||
let negative = self.text() == "-";
|
||||
if negative {
|
||||
self.cursor += 1;
|
||||
}
|
||||
let digits = self.integer()?;
|
||||
let value = self.source[digits.start..digits.end]
|
||||
.parse::<i16>()
|
||||
.map_err(|_| error(digits, "Dimension exponent exceeds -32..32."))?;
|
||||
if value > 32 {
|
||||
return Err(error(digits, "Dimension exponent exceeds -32..32."));
|
||||
}
|
||||
exponents[index] = if negative { -value } else { value };
|
||||
let exponent = Span {
|
||||
start,
|
||||
end: digits.end,
|
||||
};
|
||||
let end = self.take(";")?.end;
|
||||
entries.push(DimensionEntry {
|
||||
axis,
|
||||
exponent,
|
||||
span: Span {
|
||||
start: axis.start,
|
||||
end,
|
||||
},
|
||||
});
|
||||
}
|
||||
self.take("}")?;
|
||||
self.close();
|
||||
Ok(DimensionSyntax { exponents, entries })
|
||||
}
|
||||
|
||||
fn algebra(&mut self) -> Result<AlgebraSyntax, Error> {
|
||||
if self.text() == "Linear" {
|
||||
self.cursor += 1;
|
||||
return Ok(AlgebraSyntax::Linear);
|
||||
}
|
||||
self.take("Affine")?;
|
||||
self.open()?;
|
||||
self.take("(")?;
|
||||
let difference = self.at_reference()?;
|
||||
self.take(")")?;
|
||||
self.close();
|
||||
Ok(AlgebraSyntax::Affine(difference))
|
||||
}
|
||||
|
||||
fn overrides(&mut self) -> Result<Vec<OverrideSyntax>, Error> {
|
||||
self.open()?;
|
||||
self.take("{")?;
|
||||
let mut entries = Vec::new();
|
||||
let mut names = BTreeSet::new();
|
||||
while self.text() != "}" {
|
||||
let start = self.span().start;
|
||||
self.budget.entry(self.span())?;
|
||||
let target = self.at_reference()?;
|
||||
if !names.insert(target.name.clone()) {
|
||||
return Err(error(target.span, "Duplicate override target."));
|
||||
}
|
||||
self.take("=")?;
|
||||
let binding_start = self.span().start;
|
||||
let binding = syntax::binding(self)?;
|
||||
let binding_span = Span {
|
||||
start: binding_start,
|
||||
end: self.last_end(),
|
||||
};
|
||||
let end = self.take(";")?.end;
|
||||
entries.push(OverrideSyntax {
|
||||
span: Span { start, end },
|
||||
target,
|
||||
binding,
|
||||
binding_span,
|
||||
});
|
||||
}
|
||||
self.take("}")?;
|
||||
self.close();
|
||||
Ok(entries)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
@@ -0,0 +1,613 @@
|
||||
use super::*;
|
||||
use crate::language::ParseLimits;
|
||||
use crate::language::analysis_source::budget::Limits;
|
||||
|
||||
fn limits() -> Limits {
|
||||
Limits::source8(ParseLimits::UNLIMITED)
|
||||
}
|
||||
fn budget() -> Budget {
|
||||
Budget::new(limits()).unwrap()
|
||||
}
|
||||
|
||||
fn declaration(source: &str) -> Declaration {
|
||||
let mut budget = budget();
|
||||
let tokens = lex::tokens(source, &mut budget).unwrap();
|
||||
let mut cursor = Cursor::new(source, &tokens, &mut budget);
|
||||
let result = parse(&mut cursor, 8, None).unwrap();
|
||||
cursor.end().unwrap();
|
||||
result
|
||||
}
|
||||
|
||||
fn failure(source: &str) -> Error {
|
||||
let mut budget = budget();
|
||||
let tokens = lex::tokens(source, &mut budget).unwrap();
|
||||
parse(&mut Cursor::new(source, &tokens, &mut budget), 8, None).unwrap_err()
|
||||
}
|
||||
|
||||
fn text(source: &str, span: Span) -> &str {
|
||||
&source[span.start..span.end]
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn required_declarations_have_independent_typed_body_and_header_oracles() {
|
||||
let source = "quantity_kind duration \"Duration\" id \"188b911c-5f8b-431c-9eea-2d41f3953767\" { dimension { time 1; length -2; }; algebra Affine(@difference); description \"雪\"; }";
|
||||
let actual = declaration(source);
|
||||
assert_eq!(actual.header.kind, DeclarationKind::QuantityKind);
|
||||
assert_eq!(actual.header.alias.name, "duration");
|
||||
assert_eq!(actual.header.name, "Duration");
|
||||
assert_eq!(
|
||||
actual.header.identity.value,
|
||||
Some(Id::parse_str("188b911c-5f8b-431c-9eea-2d41f3953767").unwrap())
|
||||
);
|
||||
assert_eq!(actual.description.as_ref().unwrap().value, "雪");
|
||||
assert!(actual.parent.is_none());
|
||||
let Body::QuantityKind { dimension, algebra } = actual.body else {
|
||||
panic!("quantity kind")
|
||||
};
|
||||
assert_eq!(dimension.value.exponents, [-2, 0, 1, 0, 0, 0, 0]);
|
||||
assert_eq!(text(source, dimension.keyword), "dimension");
|
||||
assert_eq!(text(source, dimension.value_span), "{ time 1; length -2; }");
|
||||
assert_eq!(text(source, dimension.value.entries[1].exponent), "-2");
|
||||
let AlgebraSyntax::Affine(difference) = algebra.value else {
|
||||
panic!("affine")
|
||||
};
|
||||
assert_eq!(difference.name, "difference");
|
||||
|
||||
let Body::Unit { kind, scale, offset, symbol } = declaration("unit millisecond \"Millisecond\" { kind @duration; scale ratio (1, // divisor\n 1000); offset 0; symbol \"ms\"; }").body else { panic!("unit") };
|
||||
assert_eq!(kind.value.name, "duration");
|
||||
assert_eq!(scale.value.value.canonical_literal(), "ratio(1, 1000)");
|
||||
assert_eq!(offset.value.value.canonical_literal(), "0");
|
||||
assert_eq!(symbol.value, "ms");
|
||||
|
||||
let Body::Calculation { parameters, result, body } = declaration("calculation combine \"Combine durations\" { input a id \"28ff40b0-1b8f-4735-8536-5a6ab21b56cb\" : Quantity(@duration); input b id \"7a47cc1e-8ae5-4551-b2d8-8a68108e0976\" : Quantity(@duration); result Quantity(@duration); body $a + $b; }").body else { panic!("calculation") };
|
||||
assert_eq!(
|
||||
parameters
|
||||
.iter()
|
||||
.map(|p| p.name.name.as_str())
|
||||
.collect::<Vec<_>>(),
|
||||
["a", "b"]
|
||||
);
|
||||
assert!(!result.value.list);
|
||||
assert!(
|
||||
matches!(result.value.scalar.kind, ScalarKind::Quantity(ref r) if r.name == "duration")
|
||||
);
|
||||
let Binding::Expression(Expression {
|
||||
kind: ExpressionKind::Binary { op, left, right },
|
||||
..
|
||||
}) = body.value
|
||||
else {
|
||||
panic!("binary")
|
||||
};
|
||||
assert_eq!(op, BinaryOp::Add);
|
||||
assert!(matches!(left.kind, ExpressionKind::Parameter(ref r) if r.name == "a"));
|
||||
assert!(matches!(right.kind, ExpressionKind::Parameter(ref r) if r.name == "b"));
|
||||
|
||||
for (word, layer) in [("oa_property", Layer::Oa), ("sa_property", Layer::Sa)] {
|
||||
let actual = declaration(&format!(
|
||||
"{word} receive_time \"Receive time\" {{ subject @receive; type Quantity(@duration); base 750 [@millisecond]; display_unit @millisecond; parent none; }}"
|
||||
));
|
||||
assert_eq!(actual.header.kind, DeclarationKind::Property(layer));
|
||||
assert!(actual.parent.is_some());
|
||||
let Body::Property {
|
||||
subject,
|
||||
value_type,
|
||||
base,
|
||||
display_unit,
|
||||
} = actual.body
|
||||
else {
|
||||
panic!("property")
|
||||
};
|
||||
assert_eq!(subject.value.name, "receive");
|
||||
assert!(matches!(
|
||||
value_type.value.scalar.kind,
|
||||
ScalarKind::Quantity(_)
|
||||
));
|
||||
assert!(matches!(
|
||||
base.value,
|
||||
Binding::Expression(Expression {
|
||||
kind: ExpressionKind::Quantity { .. },
|
||||
..
|
||||
})
|
||||
));
|
||||
assert_eq!(display_unit.unwrap().value.unwrap().name, "millisecond");
|
||||
}
|
||||
for word in ["oa_check", "sa_check"] {
|
||||
let Body::Check { subject, documented_constraint, predicate } = declaration(&format!("{word} budget \"Response budget\" {{ subject none; documented_constraint @constraint; predicate @total_time <= @limit; }}")).body else { panic!("check") };
|
||||
assert!(subject.unwrap().value.is_none());
|
||||
assert_eq!(
|
||||
documented_constraint.unwrap().value.unwrap().name,
|
||||
"constraint"
|
||||
);
|
||||
assert!(matches!(
|
||||
predicate.value,
|
||||
Binding::Expression(Expression {
|
||||
kind: ExpressionKind::Binary {
|
||||
op: BinaryOp::LessOrEqual,
|
||||
..
|
||||
},
|
||||
..
|
||||
})
|
||||
));
|
||||
}
|
||||
for word in ["oa_analysis", "sa_analysis"] {
|
||||
let Body::Case { subject, base, overrides } = declaration(&format!("{word} degraded \"Degraded radio\" {{ subject @respond; base ModelBaseline; overrides {{ @receive_time = unbound; }}; }}")).body else { panic!("case") };
|
||||
assert_eq!(subject.unwrap().value.unwrap().name, "respond");
|
||||
assert!(base.value_span.end > base.value_span.start);
|
||||
assert_eq!(overrides.value.len(), 1);
|
||||
assert_eq!(overrides.value[0].target.name, "receive_time");
|
||||
assert!(matches!(overrides.value[0].binding, Binding::Unbound(_)));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn empty_unbound_and_all_scalar_list_types_are_explicit_valid_syntax() {
|
||||
for (spelling, list, kind) in [
|
||||
("Boolean", false, 0),
|
||||
("Number", false, 1),
|
||||
("Quantity(@duration)", false, 2),
|
||||
("List(Boolean)", true, 0),
|
||||
("List(Number)", true, 1),
|
||||
("List(Quantity(@duration))", true, 2),
|
||||
] {
|
||||
let Body::Calculation {
|
||||
parameters,
|
||||
result,
|
||||
body,
|
||||
} = declaration(&format!(
|
||||
"calculation c \"C\" {{ result {spelling}; body unbound; }}"
|
||||
))
|
||||
.body
|
||||
else {
|
||||
panic!()
|
||||
};
|
||||
assert!(parameters.is_empty());
|
||||
assert_eq!(result.value.list, list);
|
||||
assert_eq!(
|
||||
match result.value.scalar.kind {
|
||||
ScalarKind::Boolean => 0,
|
||||
ScalarKind::Number => 1,
|
||||
ScalarKind::Quantity(_) => 2,
|
||||
},
|
||||
kind
|
||||
);
|
||||
assert!(matches!(body.value, Binding::Unbound(_)));
|
||||
}
|
||||
let Body::QuantityKind { dimension, algebra } =
|
||||
declaration("quantity_kind q \"Q\" { dimension {}; algebra Linear; }").body
|
||||
else {
|
||||
panic!()
|
||||
};
|
||||
assert_eq!(dimension.value.exponents, [0; 7]);
|
||||
assert!(dimension.value.entries.is_empty());
|
||||
assert_eq!(algebra.value, AlgebraSyntax::Linear);
|
||||
let Body::Case {
|
||||
subject, overrides, ..
|
||||
} = declaration("oa_analysis c \"C\" { base ModelBaseline; overrides {}; }").body
|
||||
else {
|
||||
panic!()
|
||||
};
|
||||
assert!(subject.is_none());
|
||||
assert!(overrides.value.is_empty());
|
||||
let Body::Check {
|
||||
subject,
|
||||
documented_constraint,
|
||||
..
|
||||
} = declaration("oa_check c \"C\" { predicate unbound; }").body
|
||||
else {
|
||||
panic!()
|
||||
};
|
||||
assert!(subject.is_none() && documented_constraint.is_none());
|
||||
let Body::Property { display_unit, .. } =
|
||||
declaration("oa_property p \"P\" { subject @s; type Number; base unbound; }").body
|
||||
else {
|
||||
panic!()
|
||||
};
|
||||
assert!(display_unit.is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn missing_required_fields_and_unknown_or_duplicate_entries_reject_locally() {
|
||||
let required_sets: &[(&str, &[&str])] = &[
|
||||
(
|
||||
"quantity_kind q \"Q\"",
|
||||
&["dimension {};", "algebra Linear;"],
|
||||
),
|
||||
(
|
||||
"unit u \"U\"",
|
||||
&["kind @q;", "scale 1;", "offset 0;", "symbol \"u\";"],
|
||||
),
|
||||
("calculation c \"C\"", &["result Number;", "body unbound;"]),
|
||||
(
|
||||
"oa_property p \"P\"",
|
||||
&["subject @s;", "type Number;", "base unbound;"],
|
||||
),
|
||||
("oa_check c \"C\"", &["predicate unbound;"]),
|
||||
(
|
||||
"oa_analysis a \"A\"",
|
||||
&["base ModelBaseline;", "overrides {};"],
|
||||
),
|
||||
];
|
||||
for (header, fields) in required_sets {
|
||||
declaration(&format!("{header} {{ {} }}", fields.join(" ")));
|
||||
for removed in 0..fields.len() {
|
||||
let remaining = fields
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter_map(|(i, field)| (i != removed).then_some(*field))
|
||||
.collect::<Vec<_>>()
|
||||
.join(" ");
|
||||
let error = failure(&format!("{header} {{ {remaining} }}"));
|
||||
assert!(
|
||||
error.message.contains("Missing required field"),
|
||||
"{error:?}"
|
||||
);
|
||||
let duplicate = format!("{header} {{ {} {} }}", fields.join(" "), fields[removed]);
|
||||
assert!(failure(&duplicate).message.contains("Duplicate field"));
|
||||
}
|
||||
}
|
||||
for source in [
|
||||
"quantity_kind q \"Q\" { dimension { time 1; time 2; }; algebra Linear; }",
|
||||
"quantity_kind q \"Q\" { dimension { unknown 1; }; algebra Linear; }",
|
||||
"quantity_kind q \"Q\" { dimension { time 33; }; algebra Linear; }",
|
||||
"unit u \"U\" { kind @q; scale 1 + 2; offset 0; symbol \"u\"; }",
|
||||
"unit u \"U\" { kind @q; scale 1 [@u]; offset 0; symbol \"u\"; }",
|
||||
"unit u \"U\" { kind @q; scale ratio(1, 0); offset 0; symbol \"u\"; }",
|
||||
"calculation c \"C\" { result List(List(Number)); body unbound; }",
|
||||
"calculation c \"C\" { input x : Number; input x : Number; result Number; body unbound; }",
|
||||
"calculation c \"C\" { input x id \"28ff40b0-1b8f-4735-8536-5a6ab21b56cb\" : Number; input y id \"28ff40b0-1b8f-4735-8536-5a6ab21b56cb\" : Number; result Number; body unbound; }",
|
||||
"oa_property p \"P\" { subject none; type Number; base unbound; }",
|
||||
"oa_property p \"P\" { subject @s; type Number; base none; }",
|
||||
"oa_property p \"P\" { subject @s; type Number; base unbound; parent @s; }",
|
||||
"oa_analysis a \"A\" { base @another; overrides {}; }",
|
||||
"oa_analysis a \"A\" { base ModelBaseline; overrides { @p = clear; }; }",
|
||||
"oa_analysis a \"A\" { base ModelBaseline; overrides { @p = 1; @p = 2; }; }",
|
||||
"oa_check c \"C\" { predicate @f(x: 1, x: 2); }",
|
||||
"quantity_kind q \"Q\" { dimension {}; algebra Linear; parent none; }",
|
||||
"oa_check c \"C\" { predicate unbound; invented none; }",
|
||||
] {
|
||||
failure(source);
|
||||
}
|
||||
let duplicate = "oa_analysis a \"A\" { base ModelBaseline; overrides { @p = 1; @p = 2; }; }";
|
||||
let error = failure(duplicate);
|
||||
assert_eq!(text(duplicate, error.span), "p");
|
||||
assert!(error.span.start > duplicate.find("@p").unwrap() + 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn borrowed_cursor_preserves_full_file_spans_and_does_not_rescan_fields() {
|
||||
let source = "// 雪\r\ncalculation c \"C\" { input a : Number; result Number; body @combine(a: ratio (1, // first\r\n 2), b: $a) + @combine(a: 2, b: $a); }\r\nunit u \"U\" { kind @q; scale 1; offset 0; symbol \"u\"; }";
|
||||
let mut shared = budget();
|
||||
let tokens = lex::tokens(source, &mut shared).unwrap();
|
||||
let lexical = shared.usage;
|
||||
let mut cursor = Cursor::new(source, &tokens, &mut shared);
|
||||
let first = parse(&mut cursor, 8, None).unwrap();
|
||||
assert_eq!(cursor.text(), "unit");
|
||||
let first_end = first.span.end;
|
||||
let second = parse(&mut cursor, 8, None).unwrap();
|
||||
cursor.end().unwrap();
|
||||
assert!(second.span.start > first_end);
|
||||
assert_eq!(text(source, first.header.kind_span), "calculation");
|
||||
assert_eq!(text(source, first.header.name_span), "\"C\"");
|
||||
assert_eq!(text(source, second.header.alias.span), "u");
|
||||
assert_eq!(
|
||||
text(source, first.body_span).trim().strip_prefix("input"),
|
||||
Some(
|
||||
" a : Number; result Number; body @combine(a: ratio (1, // first\r\n 2), b: $a) + @combine(a: 2, b: $a);"
|
||||
)
|
||||
);
|
||||
let Body::Calculation {
|
||||
parameters, body, ..
|
||||
} = first.body
|
||||
else {
|
||||
panic!()
|
||||
};
|
||||
assert_eq!(text(source, parameters[0].span), "input a : Number;");
|
||||
assert_eq!(text(source, parameters[0].value_type.span), "Number");
|
||||
let Binding::Expression(Expression {
|
||||
kind: ExpressionKind::Binary { left, right, .. },
|
||||
..
|
||||
}) = body.value
|
||||
else {
|
||||
panic!()
|
||||
};
|
||||
let ExpressionKind::Call {
|
||||
arguments: left, ..
|
||||
} = left.kind
|
||||
else {
|
||||
panic!()
|
||||
};
|
||||
let ExpressionKind::Call {
|
||||
arguments: right, ..
|
||||
} = right.kind
|
||||
else {
|
||||
panic!()
|
||||
};
|
||||
let spans = [
|
||||
left[0].parameter.span,
|
||||
left[1].parameter.span,
|
||||
right[0].parameter.span,
|
||||
right[1].parameter.span,
|
||||
];
|
||||
assert_eq!(spans.map(|span| text(source, span)), ["a", "b", "a", "b"]);
|
||||
assert!(spans.windows(2).all(|pair| pair[0].end < pair[1].start));
|
||||
let literal = left[0].value.literal.as_ref().unwrap();
|
||||
assert_eq!(text(source, literal.span), "ratio (1, // first\r\n 2)");
|
||||
assert_eq!(
|
||||
literal
|
||||
.tokens
|
||||
.iter()
|
||||
.map(|span| text(source, *span))
|
||||
.collect::<Vec<_>>(),
|
||||
["ratio", "(", "1", ",", "2", ")"]
|
||||
);
|
||||
assert_eq!(shared.usage.bytes, source.len());
|
||||
assert_eq!(shared.usage.bytes, lexical.bytes);
|
||||
assert_eq!(shared.usage.tokens, lexical.tokens);
|
||||
assert_eq!(shared.usage.references, 9); // two calls, four keys, two $a, unit kind.
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn missing_id_metadata_is_stable_and_parameter_ids_are_owner_scoped() {
|
||||
let source =
|
||||
"calculation c \"C\" { input a // identity here\r\n : Number; result Number; body $a; }";
|
||||
let first = declaration(source);
|
||||
let second = declaration(source);
|
||||
assert_eq!(first, second);
|
||||
assert_eq!(
|
||||
first.header.identity.insertion,
|
||||
Some(source.find('{').unwrap())
|
||||
);
|
||||
let Body::Calculation { parameters, .. } = first.body else {
|
||||
panic!()
|
||||
};
|
||||
let id = ¶meters[0].identity;
|
||||
assert!(id.value.is_none() && id.literal.is_none() && id.keyword.is_none());
|
||||
assert_eq!(id.insertion, Some(source.find(':').unwrap()));
|
||||
let explicit = "28ff40b0-1b8f-4735-8536-5a6ab21b56cb";
|
||||
// Syntax does not add ParameterIds to a global identity registry, and an
|
||||
// explicit parameter ID can equal its own calculation's global UUID.
|
||||
for name in ["one", "two"] {
|
||||
let source = format!(
|
||||
"calculation {name} \"C\" id \"{explicit}\" {{ input a id \"{explicit}\" : Number; result Number; body $a; }}"
|
||||
);
|
||||
let actual = declaration(&source);
|
||||
let Body::Calculation { parameters, .. } = actual.body else {
|
||||
panic!()
|
||||
};
|
||||
assert_eq!(parameters[0].identity.value, actual.header.identity.value);
|
||||
assert!(parameters[0].identity.insertion.is_none());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn inherited_version_root_and_short_word_contracts_do_not_enable_public8() {
|
||||
let source = "oa_check c \"C\" { predicate unbound; }";
|
||||
for version in [1, 2, 3, 4, 5, 6, 7, 9] {
|
||||
let mut budget = budget();
|
||||
let tokens = lex::tokens(source, &mut budget).unwrap();
|
||||
let error = parse(
|
||||
&mut Cursor::new(source, &tokens, &mut budget),
|
||||
version,
|
||||
None,
|
||||
)
|
||||
.unwrap_err();
|
||||
assert_eq!(text(source, error.span), "oa_check");
|
||||
assert!(error.message.contains("source8"));
|
||||
}
|
||||
let mut budget = budget();
|
||||
let tokens = lex::tokens(source, &mut budget).unwrap();
|
||||
assert!(
|
||||
parse(
|
||||
&mut Cursor::new(source, &tokens, &mut budget),
|
||||
8,
|
||||
Some(Id::nil())
|
||||
)
|
||||
.unwrap_err()
|
||||
.message
|
||||
.contains("roots")
|
||||
);
|
||||
for word in [
|
||||
"oa_engineering_property",
|
||||
"sa_engineering_property",
|
||||
"oa_analysis_check",
|
||||
"sa_analysis_check",
|
||||
"oa_analysis_case",
|
||||
"sa_analysis_case",
|
||||
] {
|
||||
assert!(declaration_kind(word).is_none());
|
||||
}
|
||||
for alias in [
|
||||
"unit",
|
||||
"calculation",
|
||||
"quantity_kind",
|
||||
"oa_property",
|
||||
"if",
|
||||
"and",
|
||||
"List",
|
||||
] {
|
||||
let old = format!("arcadia 7; project {alias} \"P\" {{}}");
|
||||
assert!(crate::language::parse(&old).is_ok(), "{old}");
|
||||
}
|
||||
let contextual =
|
||||
declaration("calculation unit \"C\" { input and : Number; result Number; body $and; }");
|
||||
assert_eq!(contextual.header.alias.name, "unit");
|
||||
assert!(crate::language::parse("arcadia 8; project p \"P\" {}").is_err());
|
||||
for version in 3..=7 {
|
||||
assert!(
|
||||
crate::language::parse(&format!(
|
||||
"arcadia {version}; project p \"P\" {{ {source} }}"
|
||||
))
|
||||
.is_err()
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn declaration_budgets_share_literals_types_references_and_failure_state() {
|
||||
let source = "unit u \"U\" { kind @q; scale ratio(1, 3); offset ratio(2, 7); symbol \"u\"; }";
|
||||
let mut measured = budget();
|
||||
let tokens = lex::tokens(source, &mut measured).unwrap();
|
||||
parse(&mut Cursor::new(source, &tokens, &mut measured), 8, None).unwrap();
|
||||
let numeric = measured.numeric_units();
|
||||
assert!(numeric > 0);
|
||||
// All declaration, field and type entries share the same preallocation
|
||||
// ceiling. Measure a deterministic valid counterpart before reducing it.
|
||||
for (maximum, succeeds) in [
|
||||
(measured.usage.entries, true),
|
||||
(measured.usage.entries - 1, false),
|
||||
] {
|
||||
let mut profile = limits();
|
||||
profile.entries = maximum;
|
||||
let mut shared = Budget::new(profile).unwrap();
|
||||
let tokens = lex::tokens(source, &mut shared).unwrap();
|
||||
let result = parse(&mut Cursor::new(source, &tokens, &mut shared), 8, None);
|
||||
assert_eq!(result.is_ok(), succeeds);
|
||||
if !succeeds {
|
||||
assert!(result.unwrap_err().message.contains("entries"));
|
||||
}
|
||||
}
|
||||
for (maximum, succeeds) in [(numeric, true), (numeric - 1, false)] {
|
||||
let mut profile = limits();
|
||||
profile.numeric_units = maximum;
|
||||
let mut shared = Budget::new(profile).unwrap();
|
||||
let tokens = lex::tokens(source, &mut shared).unwrap();
|
||||
let result = parse(&mut Cursor::new(source, &tokens, &mut shared), 8, None);
|
||||
assert_eq!(result.is_ok(), succeeds);
|
||||
}
|
||||
let first =
|
||||
"calculation c \"C\" { input x : Quantity(@q); result Quantity(@q); body unbound; }";
|
||||
let second = "oa_property p \"P\" { subject @s; type Quantity(@q); base 1 [@u]; }";
|
||||
let mut profile = limits();
|
||||
profile.references = 4;
|
||||
let mut shared = Budget::new(profile).unwrap();
|
||||
let tokens = lex::tokens(first, &mut shared).unwrap();
|
||||
parse(&mut Cursor::new(first, &tokens, &mut shared), 8, None).unwrap();
|
||||
assert_eq!(shared.usage.references, 2);
|
||||
let tokens = lex::tokens(second, &mut shared).unwrap();
|
||||
let error = parse(&mut Cursor::new(second, &tokens, &mut shared), 8, None).unwrap_err();
|
||||
assert_eq!(text(second, error.span), "u");
|
||||
assert_eq!(shared.usage.references, 4);
|
||||
assert_eq!(shared.active().unwrap_err(), error);
|
||||
let numeric_after_failure = shared.numeric_units();
|
||||
assert!(lex::tokens("1", &mut shared).is_err());
|
||||
assert_eq!(shared.numeric_units(), numeric_after_failure);
|
||||
let unbound_tokens = lex::tokens("unbound", &mut budget()).unwrap();
|
||||
assert_eq!(
|
||||
syntax::binding(&mut Cursor::new("unbound", &unbound_tokens, &mut shared)).unwrap_err(),
|
||||
error
|
||||
);
|
||||
assert!(
|
||||
declaration("oa_check fresh \"Fresh\" { predicate true; }")
|
||||
.parent
|
||||
.is_none()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn typed_frame_budget_and_truncated_declaration_cleanup_have_nearby_successes() {
|
||||
let source = "calculation c \"C\" { result List(Quantity(@q)); body unbound; }";
|
||||
for (maximum, succeeds) in [(3, true), (2, false)] {
|
||||
let mut profile = limits();
|
||||
profile.frames = maximum;
|
||||
let mut shared = Budget::new(profile).unwrap();
|
||||
let tokens = lex::tokens(source, &mut shared).unwrap();
|
||||
assert_eq!(
|
||||
parse(&mut Cursor::new(source, &tokens, &mut shared), 8, None).is_ok(),
|
||||
succeeds
|
||||
);
|
||||
}
|
||||
let source = "oa_analysis a \"A\" { base ModelBaseline; overrides { @p = if(true, ratio(1, 2), @f(a: 1)); }; }";
|
||||
let tokens = lex::tokens(source, &mut budget()).unwrap();
|
||||
for token in tokens
|
||||
.iter()
|
||||
.filter(|token| matches!(text(source, token.span), "{" | "(" | "," | ":" | "="))
|
||||
{
|
||||
let prefix = &source[..token.span.end];
|
||||
let mut shared = budget();
|
||||
let tokens = lex::tokens(prefix, &mut shared).unwrap();
|
||||
assert!(parse(&mut Cursor::new(prefix, &tokens, &mut shared), 8, None).is_err());
|
||||
declaration("oa_check fresh \"Fresh\" { predicate true; }");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn typed_brace_frames_have_exact_zero_one_two_boundaries() {
|
||||
let mut profile = limits();
|
||||
profile.frames = 0;
|
||||
let mut shared = Budget::new(profile).unwrap();
|
||||
let tokens = lex::tokens("unbound", &mut shared).unwrap();
|
||||
let mut cursor = Cursor::new("unbound", &tokens, &mut shared);
|
||||
assert!(matches!(
|
||||
syntax::binding(&mut cursor).unwrap(),
|
||||
Binding::Unbound(_)
|
||||
));
|
||||
assert_eq!(cursor.frames, 0);
|
||||
assert_eq!(shared.usage.deepest_frame, 0);
|
||||
|
||||
for (source, needed) in [
|
||||
("calculation c \"C\" { result Number; body unbound; }", 1),
|
||||
("quantity_kind q \"Q\" { dimension {}; algebra Linear; }", 2),
|
||||
(
|
||||
"oa_analysis a \"A\" { base ModelBaseline; overrides {}; }",
|
||||
2,
|
||||
),
|
||||
] {
|
||||
for maximum in 0..=2 {
|
||||
let mut profile = limits();
|
||||
profile.frames = maximum;
|
||||
let mut shared = Budget::new(profile).unwrap();
|
||||
let tokens = lex::tokens(source, &mut shared).unwrap();
|
||||
let mut cursor = Cursor::new(source, &tokens, &mut shared);
|
||||
let result = parse(&mut cursor, 8, None);
|
||||
assert_eq!(
|
||||
result.is_ok(),
|
||||
maximum >= needed,
|
||||
"{source}, limit {maximum}"
|
||||
);
|
||||
if let Err(error) = result {
|
||||
assert!(error.message.contains("frames"));
|
||||
assert_eq!(text(source, error.span), "{");
|
||||
assert_eq!(
|
||||
error.span.start,
|
||||
if maximum == 0 {
|
||||
source.find('{').unwrap()
|
||||
} else {
|
||||
source.rfind('{').unwrap()
|
||||
}
|
||||
);
|
||||
} else {
|
||||
assert_eq!(cursor.frames, 0);
|
||||
cursor.end().unwrap();
|
||||
assert_eq!(shared.usage.deepest_frame, needed);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn declaration_frames_restore_the_callers_inherited_context() {
|
||||
let source = "calculation a \"A\" { result Number; body unbound; } calculation b \"B\" { result Number; body unbound; }";
|
||||
for maximum in [1, 2] {
|
||||
let mut profile = limits();
|
||||
profile.frames = maximum;
|
||||
let mut shared = Budget::new(profile).unwrap();
|
||||
let tokens = lex::tokens(source, &mut shared).unwrap();
|
||||
let mut cursor = Cursor::new(source, &tokens, &mut shared);
|
||||
// Future project/include integration owns this outer context. The
|
||||
// declaration consumer must add to it, then restore it after closing.
|
||||
cursor.frames = 1;
|
||||
let first = parse(&mut cursor, 8, None);
|
||||
if maximum == 1 {
|
||||
let error = first.unwrap_err();
|
||||
assert!(error.message.contains("frames"));
|
||||
assert_eq!(text(source, error.span), "{");
|
||||
} else {
|
||||
assert!(first.is_ok());
|
||||
assert_eq!(cursor.frames, 1);
|
||||
parse(&mut cursor, 8, None).unwrap();
|
||||
assert_eq!(cursor.frames, 1);
|
||||
cursor.end().unwrap();
|
||||
assert_eq!(shared.usage.deepest_frame, 2);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,709 @@
|
||||
//! Temporary typed source witnesses. No arena index becomes a model identity.
|
||||
//! The staged entry point parses each supplied typed file once. A future bundle
|
||||
//! parser must retain the same opaque parse/lower provenance. Occurrence
|
||||
//! completeness trusts that lowerer; the private builder does not prove the
|
||||
//! presence of every syntax reference in a caller-fabricated Lowered value.
|
||||
use super::cursor::Cursor;
|
||||
use super::lower::{self, Child, Field, Lowered, Role, Target, Unit};
|
||||
use super::{Budget, Error, Span, declarations, error, lex};
|
||||
use crate::{Id, Project, analysis as a};
|
||||
use std::cmp::Ordering;
|
||||
use std::collections::{BTreeMap, BTreeSet};
|
||||
use std::fmt;
|
||||
use std::sync::Arc;
|
||||
|
||||
/// Persistent structural path: cloning shares ancestors, and equality/order
|
||||
/// compare the complete edge sequence, never allocation or arena identities.
|
||||
/// Depth is checked against the inherited frame limit before allocation.
|
||||
/// Comparison and Debug walk leaf-to-root without allocating or recursing;
|
||||
/// this private total order need not be root-first lexicographic order.
|
||||
#[derive(Clone, Default)]
|
||||
pub(super) struct Path(Option<Arc<Step>>);
|
||||
struct Step {
|
||||
parent: Path,
|
||||
edge: Child,
|
||||
}
|
||||
impl PartialEq for Path {
|
||||
fn eq(&self, other: &Self) -> bool {
|
||||
self.cmp(other) == Ordering::Equal
|
||||
}
|
||||
}
|
||||
impl Eq for Path {}
|
||||
impl PartialOrd for Path {
|
||||
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
|
||||
Some(self.cmp(other))
|
||||
}
|
||||
}
|
||||
impl Ord for Path {
|
||||
fn cmp(&self, other: &Self) -> Ordering {
|
||||
let (mut left, mut right) = (self, other);
|
||||
loop {
|
||||
match (left.0.as_deref(), right.0.as_deref()) {
|
||||
(Some(a), Some(b)) => {
|
||||
let order = a.edge.cmp(&b.edge);
|
||||
if order != Ordering::Equal {
|
||||
return order;
|
||||
}
|
||||
(left, right) = (&a.parent, &b.parent);
|
||||
}
|
||||
(None, None) => return Ordering::Equal,
|
||||
(None, Some(_)) => return Ordering::Less,
|
||||
(Some(_), None) => return Ordering::Greater,
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
impl fmt::Debug for Path {
|
||||
fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
// Debug intentionally shows the same leaf-to-root order as comparison.
|
||||
let mut list = formatter.debug_list();
|
||||
let mut path = self;
|
||||
while let Some(step) = &path.0 {
|
||||
list.entry(&step.edge);
|
||||
path = &step.parent;
|
||||
}
|
||||
list.finish()
|
||||
}
|
||||
}
|
||||
impl Drop for Path {
|
||||
fn drop(&mut self) {
|
||||
let mut next = self.0.take();
|
||||
while let Some(link) = next {
|
||||
// Shared ancestors remain owned elsewhere. The final owner peels
|
||||
// unique links here, taking the parent before Step is dropped.
|
||||
let Some(mut step) = Arc::into_inner(link) else {
|
||||
break;
|
||||
};
|
||||
next = step.parent.0.take();
|
||||
}
|
||||
}
|
||||
}
|
||||
impl Path {
|
||||
pub fn edges(&self) -> Vec<Child> {
|
||||
let mut result = Vec::new();
|
||||
let mut path = self;
|
||||
while let Some(step) = &path.0 {
|
||||
result.push(step.edge);
|
||||
path = &step.parent;
|
||||
}
|
||||
result.reverse();
|
||||
result
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
|
||||
pub(super) struct ExpressionKey {
|
||||
pub owner: Id,
|
||||
pub field: Field,
|
||||
pub path: Path,
|
||||
}
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
|
||||
pub(super) enum TokenRole {
|
||||
Declaration,
|
||||
Use(Role),
|
||||
}
|
||||
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
|
||||
pub(super) struct OccurrenceKey {
|
||||
pub owner: Id,
|
||||
/// None is a global declaration header, not a binding field.
|
||||
pub field: Option<Field>,
|
||||
/// None is outside an expression; Some(empty) is its root call site.
|
||||
pub path: Option<Path>,
|
||||
pub role: TokenRole,
|
||||
pub target: Target,
|
||||
}
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub(super) struct Location {
|
||||
pub file: usize,
|
||||
pub span: Span,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub(super) struct Index<'s> {
|
||||
// Private provenance: callers can inspect locations, not supply replacements
|
||||
// for the source witness, keys, catalog or occurrence spans.
|
||||
sources: &'s BTreeMap<usize, String>,
|
||||
names: BTreeMap<Target, String>,
|
||||
occurrences: BTreeMap<OccurrenceKey, Location>,
|
||||
expressions: BTreeMap<ExpressionKey, Location>,
|
||||
}
|
||||
impl<'s> Index<'s> {
|
||||
pub fn sources(&self) -> &BTreeMap<usize, String> {
|
||||
self.sources
|
||||
}
|
||||
pub fn names(&self) -> &BTreeMap<Target, String> {
|
||||
&self.names
|
||||
}
|
||||
pub fn occurrences(&self) -> &BTreeMap<OccurrenceKey, Location> {
|
||||
&self.occurrences
|
||||
}
|
||||
pub fn expressions(&self) -> &BTreeMap<ExpressionKey, Location> {
|
||||
&self.expressions
|
||||
}
|
||||
|
||||
/// Typed-only staged adapter. `ordinary` has already been parsed by its
|
||||
/// owner. Missing typed IDs fail in lowering; this never invents UUIDs.
|
||||
/// The caller merges the returned additions and admits the complete model.
|
||||
pub fn parse(
|
||||
ordinary: &Project,
|
||||
sources: &'s BTreeMap<usize, String>,
|
||||
budget: &mut Budget,
|
||||
) -> Result<(Self, Lowered), lower::Failure> {
|
||||
let mut units = Vec::new();
|
||||
let mut witnesses = BTreeMap::new();
|
||||
for (&file, source) in sources {
|
||||
let failure = |error| lower::Failure {
|
||||
file: Some(file),
|
||||
error,
|
||||
};
|
||||
budget
|
||||
.lowering_entries(units.len() + 1, Span::default())
|
||||
.map_err(failure)?;
|
||||
let tokens = lex::tokens(source, budget).map_err(failure)?;
|
||||
let mut cursor = Cursor::new(source, &tokens, budget);
|
||||
let mut parsed = Vec::new();
|
||||
while cursor.cursor < tokens.len() {
|
||||
parsed.push(declarations::parse(&mut cursor, 8, None).map_err(failure)?);
|
||||
}
|
||||
units.push(Unit {
|
||||
file,
|
||||
declarations: parsed,
|
||||
});
|
||||
witnesses.insert(file, tokens);
|
||||
}
|
||||
let lowered = lower::lower(ordinary, &units, budget)?;
|
||||
// A build failure after our own parse/lower is a phase/invariant error,
|
||||
// not an invented file assignment for an ambiguous numeric span.
|
||||
let index = Self::build(ordinary, sources, &units, &witnesses, &lowered, budget)
|
||||
.map_err(|error| lower::Failure { file: None, error })?;
|
||||
Ok((index, lowered))
|
||||
}
|
||||
|
||||
// Same-parse/lower internal seam only. Checks below reject damaged supplied
|
||||
// sites but occurrence completeness is an invariant of our own lowerer.
|
||||
// Do not expose a constructor accepting independently fabricated Lowered.
|
||||
fn build(
|
||||
ordinary: &Project,
|
||||
sources: &'s BTreeMap<usize, String>,
|
||||
units: &[Unit],
|
||||
witnesses: &BTreeMap<usize, Vec<lex::Token>>,
|
||||
lowered: &Lowered,
|
||||
budget: &mut Budget,
|
||||
) -> Result<Self, Error> {
|
||||
budget.active()?;
|
||||
budget.lowering_entries(lowered.expressions.len(), Span::default())?;
|
||||
budget.lowering_occurrences(lowered.occurrences.len(), Span::default())?;
|
||||
let mut names = BTreeMap::new();
|
||||
let mut name_bytes = 0usize;
|
||||
let mut insert_name = |target, name: &str| -> Result<(), Error> {
|
||||
budget.lowering_entries(names.len() + 1, Span::default())?;
|
||||
name_bytes = name_bytes
|
||||
.checked_add(name.len())
|
||||
.ok_or_else(|| error(Span::default(), "Index name size overflow."))?;
|
||||
budget.index_bytes(name_bytes, Span::default())?;
|
||||
if names.insert(target, name.to_owned()).is_some() {
|
||||
return Err(error(
|
||||
Span::default(),
|
||||
"Duplicate qualified catalog identity.",
|
||||
));
|
||||
}
|
||||
Ok(())
|
||||
};
|
||||
// Lowering has already bounded and validated the complete ordinary
|
||||
// identity catalog before this existing convenience visitor allocates.
|
||||
for (id, alias) in ordinary.identities() {
|
||||
insert_name(Target::Global(id), alias)?;
|
||||
}
|
||||
for definition in ordinary
|
||||
.definitions
|
||||
.values()
|
||||
.chain(lowered.definitions.values())
|
||||
{
|
||||
if lowered.definitions.contains_key(&definition.id) {
|
||||
insert_name(Target::Global(definition.id), &definition.alias)?;
|
||||
}
|
||||
if let a::DefinitionBody::Calculation(calculation) = &definition.body {
|
||||
for parameter in &calculation.parameters {
|
||||
insert_name(
|
||||
Target::Parameter {
|
||||
calculation: definition.id,
|
||||
parameter: parameter.id,
|
||||
},
|
||||
¶meter.name,
|
||||
)?;
|
||||
}
|
||||
}
|
||||
}
|
||||
for element in lowered.elements.values() {
|
||||
insert_name(Target::Global(element.id), &element.alias)?;
|
||||
}
|
||||
let mut index = Self {
|
||||
sources,
|
||||
names,
|
||||
occurrences: BTreeMap::new(),
|
||||
expressions: BTreeMap::new(),
|
||||
};
|
||||
let mut owners = BTreeMap::new();
|
||||
let mut physical = BTreeSet::new();
|
||||
for unit in units {
|
||||
for declaration in &unit.declarations {
|
||||
let owner = declaration.header.identity.value.ok_or_else(|| {
|
||||
error(
|
||||
declaration.span,
|
||||
"Missing ID requires source stabilization.",
|
||||
)
|
||||
})?;
|
||||
let location = Location {
|
||||
file: unit.file,
|
||||
span: declaration.span,
|
||||
};
|
||||
checked_source(sources, location)?;
|
||||
budget.lowering_entries(owners.len() + 1, declaration.span)?;
|
||||
if owners.insert(owner, location).is_some() {
|
||||
return Err(error(declaration.span, "Duplicate source owner."));
|
||||
}
|
||||
let key = OccurrenceKey {
|
||||
owner,
|
||||
field: None,
|
||||
path: None,
|
||||
role: TokenRole::Declaration,
|
||||
target: Target::Global(owner),
|
||||
};
|
||||
index.insert(
|
||||
key,
|
||||
Location {
|
||||
file: unit.file,
|
||||
span: declaration.header.alias.span,
|
||||
},
|
||||
witnesses,
|
||||
&mut physical,
|
||||
budget,
|
||||
)?;
|
||||
}
|
||||
}
|
||||
// Parent-before-child is part of the lowering contract. One forward
|
||||
// pass rejects forward, cyclic, cross-file/owner/field and duplicate
|
||||
// paths. Each node allocates one shared edge, not a copied path vector.
|
||||
let mut paths: Vec<(ExpressionKey, usize)> = Vec::new();
|
||||
for (position, site) in lowered.expressions.iter().enumerate() {
|
||||
if !matches!(
|
||||
site.field,
|
||||
Field::Body | Field::Base | Field::Predicate | Field::Override(_)
|
||||
) {
|
||||
return Err(error(
|
||||
site.span,
|
||||
"Expression occurs outside a binding field.",
|
||||
));
|
||||
}
|
||||
let location = Location {
|
||||
file: site.file,
|
||||
span: site.span,
|
||||
};
|
||||
checked_source(sources, location)?;
|
||||
let owner = owners
|
||||
.get(&site.owner)
|
||||
.ok_or_else(|| error(site.span, "Unknown expression owner."))?;
|
||||
contained(*owner, location)?;
|
||||
let (path, depth) = if let Some((parent, edge)) = site.parent {
|
||||
if parent >= position {
|
||||
return Err(error(
|
||||
site.span,
|
||||
"Expression parent must precede its child.",
|
||||
));
|
||||
}
|
||||
let ancestor = &lowered.expressions[parent];
|
||||
if ancestor.owner != site.owner
|
||||
|| ancestor.field != site.field
|
||||
|| ancestor.file != site.file
|
||||
{
|
||||
return Err(error(
|
||||
site.span,
|
||||
"Expression parent crosses its owner, field or file.",
|
||||
));
|
||||
}
|
||||
contained(
|
||||
Location {
|
||||
file: ancestor.file,
|
||||
span: ancestor.span,
|
||||
},
|
||||
location,
|
||||
)?;
|
||||
if ancestor.span == site.span {
|
||||
return Err(error(
|
||||
site.span,
|
||||
"Child expression must be a proper source subtree.",
|
||||
));
|
||||
}
|
||||
let depth = paths[parent].1 + 1;
|
||||
budget.frame(depth, site.span)?;
|
||||
(
|
||||
Path(Some(Arc::new(Step {
|
||||
parent: paths[parent].0.path.clone(),
|
||||
edge,
|
||||
}))),
|
||||
depth,
|
||||
)
|
||||
} else {
|
||||
budget.frame(1, site.span)?;
|
||||
(Path::default(), 1)
|
||||
};
|
||||
let key = ExpressionKey {
|
||||
owner: site.owner,
|
||||
field: site.field,
|
||||
path,
|
||||
};
|
||||
if index.expressions.insert(key.clone(), location).is_some() {
|
||||
return Err(error(site.span, "Duplicate qualified expression path."));
|
||||
}
|
||||
paths.push((key, depth));
|
||||
}
|
||||
for occurrence in &lowered.occurrences {
|
||||
let location = Location {
|
||||
file: occurrence.file,
|
||||
span: occurrence.span,
|
||||
};
|
||||
let owner = owners
|
||||
.get(&occurrence.owner)
|
||||
.ok_or_else(|| error(occurrence.span, "Unknown occurrence owner."))?;
|
||||
contained(*owner, location)?;
|
||||
let path = match occurrence.expression {
|
||||
Some(site) => {
|
||||
let expression = lowered
|
||||
.expressions
|
||||
.get(site)
|
||||
.ok_or_else(|| error(occurrence.span, "Unknown occurrence expression."))?;
|
||||
if expression.owner != occurrence.owner
|
||||
|| expression.field != occurrence.field
|
||||
|| expression.file != occurrence.file
|
||||
{
|
||||
return Err(error(
|
||||
occurrence.span,
|
||||
"Occurrence crosses its expression owner, field or file.",
|
||||
));
|
||||
}
|
||||
contained(
|
||||
Location {
|
||||
file: expression.file,
|
||||
span: expression.span,
|
||||
},
|
||||
location,
|
||||
)?;
|
||||
Some(paths[site].0.path.clone())
|
||||
}
|
||||
None => None,
|
||||
};
|
||||
match (occurrence.role, occurrence.target) {
|
||||
(
|
||||
Role::ParameterDeclaration,
|
||||
Target::Parameter {
|
||||
calculation,
|
||||
parameter,
|
||||
},
|
||||
) if calculation == occurrence.owner
|
||||
&& occurrence.field == Field::Input(parameter)
|
||||
&& path.is_none() => {}
|
||||
(Role::ParameterUse, Target::Parameter { calculation, .. })
|
||||
if calculation == occurrence.owner
|
||||
&& occurrence.field == Field::Body
|
||||
&& path.is_some() => {}
|
||||
(Role::ArgumentLabel, Target::Parameter { .. }) if path.is_some() => {}
|
||||
(Role::OverrideTarget, Target::Global(id))
|
||||
if occurrence.field == Field::Override(id) && path.is_none() => {}
|
||||
(Role::CallTarget, Target::Global(_)) if path.is_some() => {}
|
||||
(Role::Reference, Target::Global(_)) => {}
|
||||
_ => return Err(error(occurrence.span, "Invalid qualified occurrence role.")),
|
||||
}
|
||||
let key = OccurrenceKey {
|
||||
owner: occurrence.owner,
|
||||
field: Some(occurrence.field),
|
||||
path,
|
||||
role: TokenRole::Use(occurrence.role),
|
||||
target: occurrence.target,
|
||||
};
|
||||
index.insert(key, location, witnesses, &mut physical, budget)?;
|
||||
}
|
||||
// Argument labels belong to this precise call site and its callee, not
|
||||
// merely to a parameter UUID/name present somewhere in the catalog.
|
||||
let mut calls = BTreeMap::new();
|
||||
for (key, at) in &index.occurrences {
|
||||
if key.role == TokenRole::Use(Role::CallTarget) {
|
||||
let site = (key.owner, key.field, key.path.clone());
|
||||
if calls.insert(site, key.target).is_some() {
|
||||
return Err(error(at.span, "Multiple callees at one expression site."));
|
||||
}
|
||||
}
|
||||
}
|
||||
for (key, at) in &index.occurrences {
|
||||
if let (TokenRole::Use(Role::ArgumentLabel), Target::Parameter { calculation, .. }) =
|
||||
(key.role, key.target)
|
||||
&& calls.get(&(key.owner, key.field, key.path.clone()))
|
||||
!= Some(&Target::Global(calculation))
|
||||
{
|
||||
return Err(error(
|
||||
at.span,
|
||||
"Argument label crosses its called calculation.",
|
||||
));
|
||||
}
|
||||
}
|
||||
for (position, site) in lowered.expressions.iter().enumerate() {
|
||||
if let Some((parent, Child::Argument(parameter))) = site.parent {
|
||||
let key = &paths[parent].0;
|
||||
let Some(Target::Global(calculation)) =
|
||||
calls.get(&(key.owner, Some(key.field), Some(key.path.clone())))
|
||||
else {
|
||||
return Err(error(site.span, "Argument child has no owning call."));
|
||||
};
|
||||
let label = OccurrenceKey {
|
||||
owner: site.owner,
|
||||
field: Some(site.field),
|
||||
path: Some(key.path.clone()),
|
||||
role: TokenRole::Use(Role::ArgumentLabel),
|
||||
target: Target::Parameter {
|
||||
calculation: *calculation,
|
||||
parameter,
|
||||
},
|
||||
};
|
||||
if !index.occurrences.contains_key(&label) || paths[position].0.path == key.path {
|
||||
return Err(error(site.span, "Argument child has no qualified label."));
|
||||
}
|
||||
}
|
||||
}
|
||||
index.check_syntax_edges(units, lowered, budget)?;
|
||||
Ok(index)
|
||||
}
|
||||
|
||||
/// Check structural edges against the already parsed syntax, not just the
|
||||
/// arena's internally consistent claims. This is one iterative tree walk,
|
||||
/// with indexed span lookup; it does not lex or copy source/path strings.
|
||||
fn check_syntax_edges<'a>(
|
||||
&self,
|
||||
units: &'a [Unit],
|
||||
lowered: &Lowered,
|
||||
budget: &Budget,
|
||||
) -> Result<(), Error> {
|
||||
let mut globals = BTreeMap::new();
|
||||
let mut parameters = BTreeMap::new();
|
||||
for (target, name) in &self.names {
|
||||
match target {
|
||||
Target::Global(id) => {
|
||||
globals.insert(name.as_str(), *id);
|
||||
}
|
||||
Target::Parameter {
|
||||
calculation,
|
||||
parameter,
|
||||
} => {
|
||||
parameters.insert((*calculation, name.as_str()), *parameter);
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut sites = BTreeMap::new();
|
||||
for (position, site) in lowered.expressions.iter().enumerate() {
|
||||
if sites
|
||||
.insert(
|
||||
(
|
||||
site.file,
|
||||
site.owner,
|
||||
site.field,
|
||||
site.span.start,
|
||||
site.span.end,
|
||||
),
|
||||
position,
|
||||
)
|
||||
.is_some()
|
||||
{
|
||||
return Err(error(site.span, "Duplicate expression source ownership."));
|
||||
}
|
||||
}
|
||||
let mut work = Vec::new();
|
||||
let mut root = |file, owner, field, binding: &'a super::Binding| -> Result<(), Error> {
|
||||
if let super::Binding::Expression(expression) = binding {
|
||||
budget.lowering_entries(work.len() + 1, expression.span)?;
|
||||
work.push((file, owner, field, expression, None));
|
||||
}
|
||||
Ok(())
|
||||
};
|
||||
for unit in units {
|
||||
for declaration in &unit.declarations {
|
||||
let owner = declaration.header.identity.value.expect("validated owner");
|
||||
match &declaration.body {
|
||||
declarations::Body::Calculation { body, .. } => {
|
||||
root(unit.file, owner, Field::Body, &body.value)?
|
||||
}
|
||||
declarations::Body::Property { base, .. } => {
|
||||
root(unit.file, owner, Field::Base, &base.value)?
|
||||
}
|
||||
declarations::Body::Check { predicate, .. } => {
|
||||
root(unit.file, owner, Field::Predicate, &predicate.value)?
|
||||
}
|
||||
declarations::Body::Case { overrides, .. } => {
|
||||
for entry in &overrides.value {
|
||||
let target =
|
||||
*globals.get(entry.target.name.as_str()).ok_or_else(|| {
|
||||
error(entry.target.span, "Unknown syntax override target.")
|
||||
})?;
|
||||
root(unit.file, owner, Field::Override(target), &entry.binding)?;
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut visited = 0usize;
|
||||
while let Some((file, owner, field, expression, parent)) = work.pop() {
|
||||
budget.lowering_entries(visited + 1, expression.span)?;
|
||||
visited += 1;
|
||||
let site = *sites
|
||||
.get(&(
|
||||
file,
|
||||
owner,
|
||||
field,
|
||||
expression.span.start,
|
||||
expression.span.end,
|
||||
))
|
||||
.ok_or_else(|| {
|
||||
error(
|
||||
expression.span,
|
||||
"Parsed expression is absent from the source arena.",
|
||||
)
|
||||
})?;
|
||||
if lowered.expressions[site].parent != parent {
|
||||
return Err(error(
|
||||
expression.span,
|
||||
"Arena parent/child edge differs from original syntax.",
|
||||
));
|
||||
}
|
||||
let mut child = |value: &'a super::Expression, edge| -> Result<(), Error> {
|
||||
budget.lowering_entries(work.len() + 1, value.span)?;
|
||||
work.push((file, owner, field, value, Some((site, edge))));
|
||||
Ok(())
|
||||
};
|
||||
use super::ExpressionKind as E;
|
||||
match &expression.kind {
|
||||
E::List(items) => {
|
||||
for (index, item) in items.iter().enumerate() {
|
||||
child(item, Child::Item(index))?;
|
||||
}
|
||||
}
|
||||
E::Unary { operand, .. } => child(operand, Child::Operand)?,
|
||||
E::Binary { left, right, .. } => {
|
||||
child(left, Child::Left)?;
|
||||
child(right, Child::Right)?;
|
||||
}
|
||||
E::If {
|
||||
condition,
|
||||
when_true,
|
||||
when_false,
|
||||
} => {
|
||||
child(condition, Child::Condition)?;
|
||||
child(when_true, Child::WhenTrue)?;
|
||||
child(when_false, Child::WhenFalse)?;
|
||||
}
|
||||
E::Call {
|
||||
definition,
|
||||
arguments,
|
||||
} => {
|
||||
let calculation = *globals
|
||||
.get(definition.name.as_str())
|
||||
.ok_or_else(|| error(definition.span, "Unknown syntax call target."))?;
|
||||
for argument in arguments {
|
||||
let parameter = *parameters
|
||||
.get(&(calculation, argument.parameter.name.as_str()))
|
||||
.ok_or_else(|| {
|
||||
error(argument.parameter.span, "Unknown syntax call parameter.")
|
||||
})?;
|
||||
child(&argument.value, Child::Argument(parameter))?;
|
||||
}
|
||||
}
|
||||
E::Sum { values, initial } => {
|
||||
child(values, Child::Values)?;
|
||||
child(initial, Child::Initial)?;
|
||||
}
|
||||
E::Power { base, .. } => child(base, Child::Base)?,
|
||||
E::AsKind { value, .. } => child(value, Child::Value)?,
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
if visited != lowered.expressions.len() {
|
||||
return Err(error(
|
||||
Span::default(),
|
||||
"Arena contains expressions absent from parsed syntax.",
|
||||
));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn insert(
|
||||
&mut self,
|
||||
key: OccurrenceKey,
|
||||
location: Location,
|
||||
witnesses: &BTreeMap<usize, Vec<lex::Token>>,
|
||||
physical: &mut BTreeSet<(usize, usize, usize)>,
|
||||
budget: &Budget,
|
||||
) -> Result<(), Error> {
|
||||
budget.lowering_occurrences(self.occurrences.len() + 1, location.span)?;
|
||||
let text = checked_source(self.sources, location)?;
|
||||
if self.names.get(&key.target).is_none_or(|name| name != text) {
|
||||
return Err(error(
|
||||
location.span,
|
||||
"Token differs from its qualified target name.",
|
||||
));
|
||||
}
|
||||
let tokens = witnesses
|
||||
.get(&location.file)
|
||||
.ok_or_else(|| error(location.span, "Missing lexical witness."))?;
|
||||
let token = tokens
|
||||
.binary_search_by_key(&location.span.start, |token| token.span.start)
|
||||
.ok()
|
||||
.map(|at| tokens[at]);
|
||||
if token.is_none_or(|token| token.span != location.span || token.class != lex::Class::Word)
|
||||
{
|
||||
return Err(error(
|
||||
location.span,
|
||||
"Occurrence is not an original whole name token.",
|
||||
));
|
||||
}
|
||||
if self.occurrences.contains_key(&key)
|
||||
|| !physical.insert((location.file, location.span.start, location.span.end))
|
||||
{
|
||||
return Err(error(
|
||||
location.span,
|
||||
"Duplicate qualified occurrence or token ownership.",
|
||||
));
|
||||
}
|
||||
self.occurrences.insert(key, location);
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn checked_source(
|
||||
sources: &BTreeMap<usize, String>,
|
||||
location: Location,
|
||||
) -> Result<&str, Error> {
|
||||
if location.span.start >= location.span.end {
|
||||
return Err(error(location.span, "Empty or reversed source span."));
|
||||
}
|
||||
sources
|
||||
.get(&location.file)
|
||||
.and_then(|source| source.get(location.span.start..location.span.end))
|
||||
.ok_or_else(|| {
|
||||
error(
|
||||
location.span,
|
||||
"Source span is outside its original UTF-8 file.",
|
||||
)
|
||||
})
|
||||
}
|
||||
fn contained(parent: Location, child: Location) -> Result<(), Error> {
|
||||
if parent.file != child.file
|
||||
|| child.span.start < parent.span.start
|
||||
|| child.span.end > parent.span.end
|
||||
{
|
||||
return Err(error(
|
||||
child.span,
|
||||
"Source span crosses its containing syntax.",
|
||||
));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
@@ -0,0 +1,630 @@
|
||||
use super::*;
|
||||
use crate::language::ParseLimits;
|
||||
|
||||
const OA: &str = include_str!("../lower/fixtures/typed-oa.arcadia");
|
||||
const ORDINARY: &str = include_str!("../lower/fixtures/ordinary-oa.arcadia");
|
||||
fn budget() -> Budget {
|
||||
Budget::new(super::super::budget::Limits::source8(
|
||||
ParseLimits::UNLIMITED,
|
||||
))
|
||||
.unwrap()
|
||||
}
|
||||
fn ordinary() -> Project {
|
||||
crate::language::parse(ORDINARY).unwrap()
|
||||
}
|
||||
fn sources() -> BTreeMap<usize, String> {
|
||||
let split = OA.find("calculation combine").unwrap();
|
||||
BTreeMap::from([
|
||||
(7, OA[..split].replace('\n', "\r\n")),
|
||||
(19, OA[split..].to_owned()),
|
||||
])
|
||||
}
|
||||
fn raw(
|
||||
sources: &BTreeMap<usize, String>,
|
||||
budget: &mut Budget,
|
||||
) -> (Vec<Unit>, BTreeMap<usize, Vec<lex::Token>>, Lowered) {
|
||||
let mut units = Vec::new();
|
||||
let mut witnesses = BTreeMap::new();
|
||||
for (&file, source) in sources {
|
||||
let tokens = lex::tokens(source, budget).unwrap();
|
||||
let mut cursor = Cursor::new(source, &tokens, budget);
|
||||
let mut declarations = Vec::new();
|
||||
while cursor.cursor < tokens.len() {
|
||||
declarations.push(declarations::parse(&mut cursor, 8, None).unwrap());
|
||||
}
|
||||
units.push(Unit { file, declarations });
|
||||
witnesses.insert(file, tokens);
|
||||
}
|
||||
let lowered = lower::lower(&ordinary(), &units, budget).unwrap();
|
||||
(units, witnesses, lowered)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn staged_index_preserves_complete_oa_sa_models_and_original_file_spans() {
|
||||
for (layer, ordinary_source, typed) in [
|
||||
(crate::Layer::Oa, ORDINARY, OA),
|
||||
(
|
||||
crate::Layer::Sa,
|
||||
include_str!("../lower/fixtures/ordinary-sa.arcadia"),
|
||||
include_str!("../lower/fixtures/typed-sa.arcadia"),
|
||||
),
|
||||
] {
|
||||
let sources = BTreeMap::from([(37, typed.replace('\n', "\r\n"))]);
|
||||
let skeleton = crate::language::parse(ordinary_source).unwrap();
|
||||
let mut work = budget();
|
||||
let (index, lowered) = Index::parse(&skeleton, &sources, &mut work).unwrap();
|
||||
let mut actual = skeleton;
|
||||
actual.definitions.extend(lowered.definitions);
|
||||
actual.elements.extend(lowered.elements);
|
||||
assert_eq!(actual, super::super::model_oracle::project(layer));
|
||||
a::admit(&actual, a::AdmissionLimits::REFERENCE).unwrap();
|
||||
assert_eq!(work.usage.bytes, sources[&37].len(), "one lexical pass");
|
||||
for (key, at) in index.occurrences() {
|
||||
assert_eq!(at.file, 37);
|
||||
assert_eq!(
|
||||
&sources[&37][at.span.start..at.span.end],
|
||||
index.names[&key.target]
|
||||
);
|
||||
}
|
||||
assert!(!index.expressions().is_empty());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn repeated_reordered_calls_have_stable_full_paths_and_four_labels() {
|
||||
let expression = "@combine(b: @dispatch_time, a: @receive_time) // first 雪\n + @combine(a: @receive_time, b: @dispatch_time)";
|
||||
let original = OA.replace("@combine(a: @receive_time, b: @dispatch_time)", expression);
|
||||
let reordered = original.replace(
|
||||
"@combine(b: @dispatch_time, a: @receive_time)",
|
||||
"@combine(a: @receive_time, b: @dispatch_time)",
|
||||
);
|
||||
let first = BTreeMap::from([(7, original)]);
|
||||
let second = BTreeMap::from([(7, reordered)]);
|
||||
let (left, _) = Index::parse(&ordinary(), &first, &mut budget()).unwrap();
|
||||
let (right, _) = Index::parse(&ordinary(), &second, &mut budget()).unwrap();
|
||||
assert_eq!(
|
||||
left.occurrences.keys().collect::<Vec<_>>(),
|
||||
right.occurrences.keys().collect::<Vec<_>>()
|
||||
);
|
||||
assert_eq!(
|
||||
left.expressions.keys().collect::<Vec<_>>(),
|
||||
right.expressions.keys().collect::<Vec<_>>()
|
||||
);
|
||||
let labels: Vec<_> = left
|
||||
.occurrences
|
||||
.iter()
|
||||
.filter(|(key, _)| key.role == TokenRole::Use(Role::ArgumentLabel))
|
||||
.collect();
|
||||
assert_eq!(labels.len(), 4);
|
||||
let paths: BTreeSet<_> = labels
|
||||
.iter()
|
||||
.map(|(key, _)| key.path.as_ref().unwrap().edges())
|
||||
.collect();
|
||||
assert_eq!(
|
||||
paths,
|
||||
BTreeSet::from([vec![Child::Left], vec![Child::Right]])
|
||||
);
|
||||
let spans: BTreeSet<_> = labels
|
||||
.iter()
|
||||
.map(|(_, at)| (at.span.start, at.span.end))
|
||||
.collect();
|
||||
assert_eq!(spans.len(), 4);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn index_checks_every_expression_edge_and_keeps_override_fields_distinct() {
|
||||
let source = OA
|
||||
.replace("body $a + $b;", "body if(if(true, 1 < 2, false), sum([$a, abs(-$b)], 0 [@second]), as_kind(@duration, power(1 [@second], 2) / 1 [@second]));")
|
||||
.replace("@receive_time = 1250 [@millisecond];", "@receive_time = @combine(a: 1 [@second], b: 2 [@second]); @dispatch_time = @combine(b: 2 [@second], a: 1 [@second]);");
|
||||
let sources = BTreeMap::from([(17, source)]);
|
||||
let (index, lowered) = Index::parse(&ordinary(), &sources, &mut budget()).unwrap();
|
||||
let mut project = ordinary();
|
||||
project.definitions.extend(lowered.definitions);
|
||||
project.elements.extend(lowered.elements);
|
||||
a::admit(&project, a::AdmissionLimits::REFERENCE).unwrap();
|
||||
let edges: BTreeSet<_> = index
|
||||
.expressions
|
||||
.keys()
|
||||
.flat_map(|key| key.path.edges())
|
||||
.collect();
|
||||
for edge in [
|
||||
Child::Item(0),
|
||||
Child::Item(1),
|
||||
Child::Operand,
|
||||
Child::Left,
|
||||
Child::Right,
|
||||
Child::Condition,
|
||||
Child::WhenTrue,
|
||||
Child::WhenFalse,
|
||||
Child::Values,
|
||||
Child::Initial,
|
||||
Child::Base,
|
||||
Child::Value,
|
||||
] {
|
||||
assert!(edges.contains(&edge), "missing {edge:?}");
|
||||
}
|
||||
assert!(edges.iter().any(|edge| matches!(edge, Child::Argument(_))));
|
||||
let labels: Vec<_> = index
|
||||
.occurrences
|
||||
.keys()
|
||||
.filter(|key| {
|
||||
key.role == TokenRole::Use(Role::ArgumentLabel)
|
||||
&& matches!(key.field, Some(Field::Override(_)))
|
||||
})
|
||||
.collect();
|
||||
assert_eq!(labels.len(), 4);
|
||||
assert_eq!(
|
||||
labels
|
||||
.iter()
|
||||
.map(|key| key.field)
|
||||
.collect::<BTreeSet<_>>()
|
||||
.len(),
|
||||
2
|
||||
);
|
||||
assert!(
|
||||
labels
|
||||
.iter()
|
||||
.all(|key| key.path.as_ref().unwrap().edges().is_empty())
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn arena_rejects_forward_cycles_and_cross_owner_field_file_parents() {
|
||||
for damage in 0..6 {
|
||||
let sources = sources();
|
||||
let mut work = budget();
|
||||
let (units, witnesses, mut lowered) = raw(&sources, &mut work);
|
||||
let child = lowered
|
||||
.expressions
|
||||
.iter()
|
||||
.position(|site| site.parent.is_some())
|
||||
.unwrap();
|
||||
let parent = lowered.expressions[child].parent.unwrap().0;
|
||||
match damage {
|
||||
0 => lowered.expressions[child].parent = Some((child, Child::Left)),
|
||||
1 => lowered.expressions[parent].parent = Some((child, Child::Right)),
|
||||
2 => lowered.expressions[child].owner = ordinary().id,
|
||||
3 => lowered.expressions[child].field = Field::Predicate,
|
||||
4 => lowered.expressions[child].file = 12345,
|
||||
_ => lowered.expressions[child].parent = Some((parent, Child::Operand)),
|
||||
}
|
||||
assert!(
|
||||
Index::build(
|
||||
&ordinary(),
|
||||
&sources,
|
||||
&units,
|
||||
&witnesses,
|
||||
&lowered,
|
||||
&mut work
|
||||
)
|
||||
.is_err(),
|
||||
"damage {damage}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn arena_rejects_duplicate_sites_occurrences_and_wrong_callee_labels() {
|
||||
for damage in 0..4 {
|
||||
let mut sources = sources();
|
||||
// The other callee is fully valid and reuses both parameter identities
|
||||
// and spellings. Catalog/token validation must not explain rejection.
|
||||
sources.insert(
|
||||
31,
|
||||
r#"calculation other "Other" id "00000000-0000-0000-0000-00000000cafe" {
|
||||
input a id "28ff40b0-1b8f-4735-8536-5a6ab21b56cb" : Quantity(@duration);
|
||||
input b id "7a47cc1e-8ae5-4551-b2d8-8a68108e0976" : Quantity(@duration);
|
||||
result Quantity(@duration); body $a + $b;
|
||||
}"#
|
||||
.into(),
|
||||
);
|
||||
let mut work = budget();
|
||||
let (units, witnesses, mut lowered) = raw(&sources, &mut work);
|
||||
let valid = Index::build(
|
||||
&ordinary(),
|
||||
&sources,
|
||||
&units,
|
||||
&witnesses,
|
||||
&lowered,
|
||||
&mut work,
|
||||
)
|
||||
.unwrap();
|
||||
let mut expected_mismatch_span = None;
|
||||
match damage {
|
||||
0 => {
|
||||
let site = &lowered.expressions[0];
|
||||
lowered.expressions.push(lower::ExpressionSite {
|
||||
file: site.file,
|
||||
owner: site.owner,
|
||||
field: site.field,
|
||||
parent: site.parent,
|
||||
span: site.span,
|
||||
});
|
||||
}
|
||||
1 => {
|
||||
let row = &lowered.occurrences[0];
|
||||
lowered.occurrences.push(lower::Occurrence {
|
||||
file: row.file,
|
||||
owner: row.owner,
|
||||
field: row.field,
|
||||
expression: row.expression,
|
||||
role: row.role,
|
||||
target: row.target,
|
||||
span: row.span,
|
||||
});
|
||||
}
|
||||
2 => {
|
||||
let label = lowered
|
||||
.occurrences
|
||||
.iter_mut()
|
||||
.find(|row| row.role == Role::ArgumentLabel)
|
||||
.unwrap();
|
||||
let original = label.target;
|
||||
let Target::Parameter {
|
||||
calculation,
|
||||
parameter,
|
||||
} = &mut label.target
|
||||
else {
|
||||
panic!("argument label must target a parameter");
|
||||
};
|
||||
let other = Target::Parameter {
|
||||
calculation: Id::from_u128(0xcafe),
|
||||
parameter: *parameter,
|
||||
};
|
||||
assert_eq!(valid.names[&original], valid.names[&other]);
|
||||
*calculation = Id::from_u128(0xcafe);
|
||||
expected_mismatch_span = Some(label.span);
|
||||
}
|
||||
_ => {
|
||||
let row = lowered
|
||||
.occurrences
|
||||
.iter_mut()
|
||||
.find(|row| row.role == Role::OverrideTarget)
|
||||
.unwrap();
|
||||
row.field = Field::Override(ordinary().id);
|
||||
}
|
||||
}
|
||||
let failure = Index::build(
|
||||
&ordinary(),
|
||||
&sources,
|
||||
&units,
|
||||
&witnesses,
|
||||
&lowered,
|
||||
&mut work,
|
||||
)
|
||||
.unwrap_err();
|
||||
if let Some(span) = expected_mismatch_span {
|
||||
assert_eq!(
|
||||
failure.message,
|
||||
"Argument label crosses its called calculation."
|
||||
);
|
||||
assert_eq!(failure.span, span);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn index_rejects_comment_partial_and_non_utf8_occurrence_spans() {
|
||||
for damage in 0..3 {
|
||||
let mut sources = sources();
|
||||
let with_comment =
|
||||
sources[&7].replace("subject @receive;", "subject @receive; // duration 雪\r\n");
|
||||
sources.insert(7, with_comment);
|
||||
let mut work = budget();
|
||||
let (units, witnesses, mut lowered) = raw(&sources, &mut work);
|
||||
let occurrence = lowered
|
||||
.occurrences
|
||||
.iter_mut()
|
||||
.find(|row| row.file == 7 && &sources[&7][row.span.start..row.span.end] == "duration")
|
||||
.unwrap();
|
||||
match damage {
|
||||
0 => {
|
||||
let start = sources[&7].find("// duration").unwrap() + 3;
|
||||
occurrence.span = Span {
|
||||
start,
|
||||
end: start + 8,
|
||||
};
|
||||
}
|
||||
1 => occurrence.span.end -= 1,
|
||||
_ => {
|
||||
let start = sources[&7].find('雪').unwrap() + 1;
|
||||
occurrence.span = Span {
|
||||
start,
|
||||
end: start + 1,
|
||||
};
|
||||
}
|
||||
}
|
||||
assert!(
|
||||
Index::build(
|
||||
&ordinary(),
|
||||
&sources,
|
||||
&units,
|
||||
&witnesses,
|
||||
&lowered,
|
||||
&mut work
|
||||
)
|
||||
.is_err()
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn index_has_shared_budget_and_never_stabilizes_missing_ids() {
|
||||
let source = "calculation f \"F\" { result Number; body unbound; }";
|
||||
let files = BTreeMap::from([(91, source.into())]);
|
||||
let missing = Index::parse(&ordinary(), &files, &mut budget()).unwrap_err();
|
||||
assert_eq!(missing.file, Some(91));
|
||||
assert!(missing.error.message.contains("stabilization"));
|
||||
let mut limits = super::super::budget::Limits::source8(ParseLimits::UNLIMITED);
|
||||
limits.bytes = 1;
|
||||
let mut work = Budget::new(limits).unwrap();
|
||||
assert!(Index::parse(&ordinary(), &sources(), &mut work).is_err());
|
||||
assert!(work.active().is_err());
|
||||
}
|
||||
|
||||
fn on_small_stack(work: impl FnOnce() + Send + 'static) {
|
||||
// Match the established core language_nesting_tests worker-stack request.
|
||||
// This is a requested platform stack size, not a measured peak-byte claim.
|
||||
std::thread::Builder::new()
|
||||
.name("analysis-index-128k".into())
|
||||
.stack_size(128 * 1024)
|
||||
.spawn(work)
|
||||
.unwrap()
|
||||
.join()
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
fn chain(first: Child, edges: usize) -> Path {
|
||||
let mut path = Path::default();
|
||||
for position in 0..edges {
|
||||
path = Path(Some(Arc::new(Step {
|
||||
parent: path,
|
||||
edge: if position == 0 { first } else { Child::Operand },
|
||||
})));
|
||||
}
|
||||
path
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn maximum_index_paths_compare_lookup_debug_and_drop_on_128k_stack() {
|
||||
on_small_stack(|| {
|
||||
let frames = super::super::budget::Limits::source8(ParseLimits::UNLIMITED).frames;
|
||||
assert_eq!(frames, 256);
|
||||
let edges = frames - 1; // root has frame depth one
|
||||
let mut work = budget();
|
||||
work.frame(frames, Span::default()).unwrap();
|
||||
let left = chain(Child::Left, edges);
|
||||
let equal = chain(Child::Left, edges); // independent allocations
|
||||
let right = chain(Child::Right, edges);
|
||||
assert!(!Arc::ptr_eq(
|
||||
left.0.as_ref().unwrap(),
|
||||
equal.0.as_ref().unwrap()
|
||||
));
|
||||
assert_eq!(left, equal);
|
||||
assert_eq!(left.partial_cmp(&equal), Some(Ordering::Equal));
|
||||
// The difference is at the root-most edge: leaf-first walks every link.
|
||||
assert_eq!(left.cmp(&right), Child::Left.cmp(&Child::Right));
|
||||
assert_eq!(right.cmp(&left), left.cmp(&right).reverse());
|
||||
assert!(Path::default() < left);
|
||||
assert!(chain(Child::Operand, edges - 1) < chain(Child::Operand, edges));
|
||||
let shared = left.clone();
|
||||
assert!(Arc::ptr_eq(
|
||||
left.0.as_ref().unwrap(),
|
||||
shared.0.as_ref().unwrap()
|
||||
));
|
||||
let leaf = Arc::downgrade(left.0.as_ref().unwrap());
|
||||
let key = |path| ExpressionKey {
|
||||
owner: Id::from_u128(1),
|
||||
field: Field::Body,
|
||||
path,
|
||||
};
|
||||
let mut expressions = BTreeMap::new();
|
||||
assert_eq!(expressions.insert(key(left.clone()), 1), None);
|
||||
assert_eq!(expressions.insert(key(equal.clone()), 2), Some(1));
|
||||
assert_eq!(expressions.insert(key(right.clone()), 3), None);
|
||||
assert_eq!(expressions.get(&key(equal.clone())), Some(&2));
|
||||
assert_eq!(expressions.get(&key(chain(Child::Right, edges))), Some(&3));
|
||||
assert_eq!(expressions.len(), 2);
|
||||
let occurrence = |path| OccurrenceKey {
|
||||
owner: Id::from_u128(1),
|
||||
field: Some(Field::Body),
|
||||
path: Some(path),
|
||||
role: TokenRole::Use(Role::ParameterUse),
|
||||
target: Target::Parameter {
|
||||
calculation: Id::from_u128(1),
|
||||
parameter: a::ParameterId(Id::from_u128(2)),
|
||||
},
|
||||
};
|
||||
let mut occurrences = BTreeSet::new();
|
||||
assert!(occurrences.insert(occurrence(left.clone())));
|
||||
assert!(!occurrences.insert(occurrence(equal.clone())));
|
||||
assert!(occurrences.contains(&occurrence(chain(Child::Left, edges))));
|
||||
let debug = format!("{left:?}");
|
||||
assert_eq!(debug.matches("Operand").count(), edges - 1);
|
||||
assert!(debug.ends_with("Left]"));
|
||||
assert!(!format!("{expressions:?} {occurrences:?}").is_empty());
|
||||
drop(expressions);
|
||||
drop(occurrences);
|
||||
drop(shared);
|
||||
drop(left);
|
||||
assert!(leaf.upgrade().is_none(), "maps/clones release their chain");
|
||||
drop(equal);
|
||||
drop(right);
|
||||
// Dropping a child stops at a shared ancestor, which remains usable.
|
||||
let parent = chain(Child::Left, edges - 1);
|
||||
let ancestor = Arc::downgrade(parent.0.as_ref().unwrap());
|
||||
let child = Path(Some(Arc::new(Step {
|
||||
parent: parent.clone(),
|
||||
edge: Child::Right,
|
||||
})));
|
||||
drop(child);
|
||||
assert_eq!(parent.edges().len(), edges - 1);
|
||||
drop(parent);
|
||||
assert!(ancestor.upgrade().is_none());
|
||||
// No other strong owners: final destruction must peel the full chain.
|
||||
let unique = chain(Child::Left, edges);
|
||||
let final_leaf = Arc::downgrade(unique.0.as_ref().unwrap());
|
||||
drop(unique);
|
||||
assert!(final_leaf.upgrade().is_none());
|
||||
});
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn deep_parse_index_plan_and_failed_build_cleanup_on_128k_stack() {
|
||||
on_small_stack(|| {
|
||||
use super::super::update::Plan;
|
||||
let deep = format!("{}$a{}", "abs(".repeat(127), ")".repeat(127));
|
||||
let source = format!(
|
||||
r#"calculation f "Deep 雪" id "00000000-0000-0000-0000-000000000081" {{
|
||||
input a id "00000000-0000-0000-0000-000000000083" : Number;
|
||||
result Number; body {deep};
|
||||
}}
|
||||
calculation caller "Caller" id "00000000-0000-0000-0000-000000000082" {{
|
||||
result Number; body @f(a: 1);
|
||||
}}
|
||||
"#
|
||||
);
|
||||
let sources = BTreeMap::from([(47, source.clone())]);
|
||||
let skeleton = ordinary();
|
||||
let mut work = budget();
|
||||
let (index, lowered) = Index::parse(&skeleton, &sources, &mut work).unwrap();
|
||||
assert_eq!(work.usage.bytes, source.len());
|
||||
assert_eq!(index.expressions.len(), 130); // 128 unary/leaf + call/argument
|
||||
assert_eq!(
|
||||
index.expressions.keys().map(|k| k.path.edges().len()).max(),
|
||||
Some(127)
|
||||
);
|
||||
let renames = BTreeMap::from([
|
||||
(Target::Global(Id::from_u128(0x81)), "renamed_deep".into()),
|
||||
(
|
||||
Target::Parameter {
|
||||
calculation: Id::from_u128(0x81),
|
||||
parameter: a::ParameterId(Id::from_u128(0x83)),
|
||||
},
|
||||
"renamed_arg".into(),
|
||||
),
|
||||
]);
|
||||
let usage = work.usage;
|
||||
let plan = Plan::renames(&index, &renames, &work).unwrap();
|
||||
assert_eq!(plan.edit_count(), 5); // declaration/call + input/use/label
|
||||
let output = plan.apply(&sources, &work).unwrap();
|
||||
assert_eq!(work.usage, usage);
|
||||
// Independent complete original-token oracle; no index-derived offsets.
|
||||
let expected_source = source
|
||||
.replace("calculation f ", "calculation renamed_deep ")
|
||||
.replace("input a id", "input renamed_arg id")
|
||||
.replace("$a", "$renamed_arg")
|
||||
.replace("@f(a: 1)", "@renamed_deep(renamed_arg: 1)");
|
||||
assert_eq!(output, BTreeMap::from([(47, expected_source)]));
|
||||
let (renamed_index, renamed) = Index::parse(&skeleton, &output, &mut budget()).unwrap();
|
||||
assert_eq!(
|
||||
index.occurrences.keys().collect::<Vec<_>>(),
|
||||
renamed_index.occurrences.keys().collect::<Vec<_>>()
|
||||
);
|
||||
// Compare complete independently constructed models, including deepest
|
||||
// parameter identity and the call's parameter-keyed argument map.
|
||||
for (lowered, renamed) in [(lowered, false), (renamed, true)] {
|
||||
let mut expected = skeleton.clone();
|
||||
let parameter = a::ParameterId(Id::from_u128(0x83));
|
||||
let mut expression = a::Expr::Parameter(parameter);
|
||||
for _ in 0..127 {
|
||||
expression = a::Expr::Unary {
|
||||
op: a::UnaryOp::Absolute,
|
||||
operand: Box::new(expression),
|
||||
};
|
||||
}
|
||||
for (id, alias, name, parameters, expression) in [
|
||||
(
|
||||
0x81,
|
||||
if renamed { "renamed_deep" } else { "f" },
|
||||
"Deep 雪",
|
||||
vec![a::Parameter {
|
||||
id: parameter,
|
||||
name: if renamed { "renamed_arg" } else { "a" }.into(),
|
||||
value_type: a::AnalysisType::Scalar(a::ScalarType::Number),
|
||||
}],
|
||||
expression,
|
||||
),
|
||||
(
|
||||
0x82,
|
||||
"caller",
|
||||
"Caller",
|
||||
Vec::new(),
|
||||
a::Expr::Call {
|
||||
definition: a::DefinitionRef::Local(Id::from_u128(0x81)),
|
||||
arguments: BTreeMap::from([(
|
||||
parameter,
|
||||
a::Expr::Number(crate::analysis_numeric::Exact::from_integer(1)),
|
||||
)]),
|
||||
},
|
||||
),
|
||||
] {
|
||||
let id = Id::from_u128(id);
|
||||
expected.definitions.insert(
|
||||
id,
|
||||
a::Definition {
|
||||
id,
|
||||
alias: alias.into(),
|
||||
name: name.into(),
|
||||
description: String::new(),
|
||||
body: a::DefinitionBody::Calculation(a::CalculationDefinition {
|
||||
parameters,
|
||||
result: a::AnalysisType::Scalar(a::ScalarType::Number),
|
||||
body: a::Binding::Expression(expression),
|
||||
}),
|
||||
},
|
||||
);
|
||||
}
|
||||
let mut actual = skeleton.clone();
|
||||
actual.definitions.extend(lowered.definitions);
|
||||
actual.elements.extend(lowered.elements);
|
||||
assert_eq!(actual, expected);
|
||||
a::admit(&actual, a::AdmissionLimits::REFERENCE).unwrap();
|
||||
drop(actual);
|
||||
drop(expected);
|
||||
}
|
||||
drop(plan);
|
||||
drop(renamed_index);
|
||||
drop(index);
|
||||
// Failure after the deepest keys have been allocated must clean up on
|
||||
// the same stack; no modified Lowered escapes this private test seam.
|
||||
let mut work = budget();
|
||||
let (units, witnesses, mut lowered) = raw(&sources, &mut work);
|
||||
let deepest = lowered
|
||||
.expressions
|
||||
.iter()
|
||||
.find(|site| &sources[&site.file][site.span.start..site.span.end] == "$a")
|
||||
.unwrap();
|
||||
lowered.expressions.push(lower::ExpressionSite {
|
||||
file: deepest.file,
|
||||
owner: deepest.owner,
|
||||
field: deepest.field,
|
||||
parent: deepest.parent,
|
||||
span: deepest.span,
|
||||
});
|
||||
let failure =
|
||||
Index::build(&skeleton, &sources, &units, &witnesses, &lowered, &mut work).unwrap_err();
|
||||
assert_eq!(failure.message, "Duplicate qualified expression path.");
|
||||
lowered.expressions.pop();
|
||||
let mut limits = super::super::budget::Limits::source8(ParseLimits::UNLIMITED);
|
||||
limits.frames = 127;
|
||||
let mut bounded = Budget::new(limits).unwrap();
|
||||
let failure = Index::build(
|
||||
&skeleton,
|
||||
&sources,
|
||||
&units,
|
||||
&witnesses,
|
||||
&lowered,
|
||||
&mut bounded,
|
||||
)
|
||||
.unwrap_err();
|
||||
assert!(failure.message.contains("syntax frames"));
|
||||
assert!(bounded.active().is_err());
|
||||
drop(lowered);
|
||||
drop(witnesses);
|
||||
drop(units);
|
||||
let rejected = BTreeMap::from([(47, source.replace(&deep, &format!("abs({deep})")))]);
|
||||
let failure = Index::parse(&skeleton, &rejected, &mut budget()).unwrap_err();
|
||||
assert!(failure.error.message.contains("logical depth"));
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
//! Source8 significant-token adapter over the shared raw scanner.
|
||||
use super::super::raw_tokens::{Class as RawClass, Scanner};
|
||||
use super::{Budget, Error, Span, error};
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub enum Class {
|
||||
Word,
|
||||
Number,
|
||||
String,
|
||||
Punctuation,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub struct Token {
|
||||
pub class: Class,
|
||||
pub span: Span,
|
||||
}
|
||||
|
||||
pub fn tokens(source: &str, budget: &mut Budget) -> Result<Vec<Token>, Error> {
|
||||
budget.bytes(
|
||||
source.len(),
|
||||
Span {
|
||||
start: 0,
|
||||
end: source.len(),
|
||||
},
|
||||
)?;
|
||||
let mut scanner = Scanner::new(source);
|
||||
let mut result = Vec::new();
|
||||
let mut offset = 0;
|
||||
while offset < source.len() {
|
||||
// Charge trivia too, before the scanner advances or a token is stored.
|
||||
budget.token(Span {
|
||||
start: offset,
|
||||
end: offset,
|
||||
})?;
|
||||
let token = scanner.next().expect("source remains");
|
||||
offset = token.span.end;
|
||||
let class = match token.class {
|
||||
RawClass::Word => Class::Word,
|
||||
RawClass::Number => Class::Number,
|
||||
RawClass::String => Class::String,
|
||||
RawClass::Punctuation => Class::Punctuation,
|
||||
RawClass::Whitespace | RawClass::Comment => continue,
|
||||
RawClass::Error => return Err(error(token.span, "Invalid source token.")),
|
||||
};
|
||||
result.push(Token {
|
||||
class,
|
||||
span: token.span,
|
||||
});
|
||||
}
|
||||
Ok(result)
|
||||
}
|
||||
@@ -0,0 +1,961 @@
|
||||
//! Staged typed resolution. The caller owns parsing, ID stabilization and the
|
||||
//! single complete-Project semantic admission after merging these additions.
|
||||
use super::declarations::{self as d, Declaration, DeclarationKind};
|
||||
use super::*;
|
||||
use crate::analysis as a;
|
||||
use crate::analysis_numeric::Dimension;
|
||||
use crate::{Element, ElementBody, Id, Kind, Layer, Project, SharedBody};
|
||||
use std::collections::{BTreeMap, BTreeSet};
|
||||
|
||||
/// Caller-assigned file key; spans are original offsets within that file.
|
||||
pub(super) struct Unit {
|
||||
pub file: usize,
|
||||
pub declarations: Vec<Declaration>,
|
||||
}
|
||||
|
||||
#[derive(Debug, PartialEq, Eq)]
|
||||
pub(super) struct Failure {
|
||||
/// None denotes an invalid ordinary skeleton, before typed resolution.
|
||||
pub file: Option<usize>,
|
||||
pub error: Error,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub(super) enum Category {
|
||||
Project,
|
||||
Element(Kind, Layer),
|
||||
Relation,
|
||||
Diagram,
|
||||
Node,
|
||||
Artifact,
|
||||
Trace,
|
||||
QuantityKind,
|
||||
Unit,
|
||||
Calculation,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
|
||||
pub(super) enum Target {
|
||||
Global(Id),
|
||||
Parameter {
|
||||
calculation: Id,
|
||||
parameter: a::ParameterId,
|
||||
},
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
|
||||
pub(super) enum Field {
|
||||
Algebra,
|
||||
Kind,
|
||||
Input(a::ParameterId),
|
||||
Result,
|
||||
Body,
|
||||
Subject,
|
||||
Type,
|
||||
Base,
|
||||
DisplayUnit,
|
||||
DocumentedConstraint,
|
||||
Predicate,
|
||||
Override(Id),
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
|
||||
pub(super) enum Role {
|
||||
Reference,
|
||||
ParameterDeclaration,
|
||||
ParameterUse,
|
||||
CallTarget,
|
||||
ArgumentLabel,
|
||||
OverrideTarget,
|
||||
}
|
||||
|
||||
/// Stable structural edges, independent of alias spelling and argument order.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
|
||||
pub(super) enum Child {
|
||||
Item(usize),
|
||||
Operand,
|
||||
Left,
|
||||
Right,
|
||||
Condition,
|
||||
WhenTrue,
|
||||
WhenFalse,
|
||||
Argument(a::ParameterId),
|
||||
Values,
|
||||
Initial,
|
||||
Base,
|
||||
Value,
|
||||
}
|
||||
|
||||
/// An arena index is only local to this lowering result. Follow parent edges
|
||||
/// to obtain the owner/field/path identity for S3; never persist the index.
|
||||
#[derive(Debug, PartialEq, Eq)]
|
||||
pub(super) struct ExpressionSite {
|
||||
pub file: usize,
|
||||
pub owner: Id,
|
||||
pub field: Field,
|
||||
pub parent: Option<(usize, Child)>,
|
||||
pub span: Span,
|
||||
}
|
||||
|
||||
#[derive(Debug, PartialEq, Eq)]
|
||||
pub(super) struct Occurrence {
|
||||
pub file: usize,
|
||||
pub owner: Id,
|
||||
pub field: Field,
|
||||
pub expression: Option<usize>,
|
||||
pub role: Role,
|
||||
pub target: Target,
|
||||
/// Alias/name token only, excluding @/$ and surrounding trivia.
|
||||
pub span: Span,
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub(super) struct Lowered {
|
||||
pub definitions: BTreeMap<Id, a::Definition>,
|
||||
pub elements: BTreeMap<Id, Element>,
|
||||
pub occurrences: Vec<Occurrence>,
|
||||
pub expressions: Vec<ExpressionSite>,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
struct Symbol {
|
||||
id: Id,
|
||||
category: Category,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
pub(super) struct Tables {
|
||||
aliases: BTreeMap<String, Symbol>,
|
||||
ids: BTreeSet<Id>,
|
||||
parameters: BTreeMap<Id, BTreeMap<String, a::ParameterId>>,
|
||||
entries: usize,
|
||||
}
|
||||
|
||||
fn category(kind: DeclarationKind) -> Category {
|
||||
match kind {
|
||||
DeclarationKind::QuantityKind => Category::QuantityKind,
|
||||
DeclarationKind::Unit => Category::Unit,
|
||||
DeclarationKind::Calculation => Category::Calculation,
|
||||
DeclarationKind::Property(layer) => Category::Element(Kind::EngineeringProperty, layer),
|
||||
DeclarationKind::Check(layer) => Category::Element(Kind::AnalysisCheck, layer),
|
||||
DeclarationKind::Case(layer) => Category::Element(Kind::AnalysisCase, layer),
|
||||
}
|
||||
}
|
||||
|
||||
fn identity(identity: &d::IdentitySyntax, span: Span) -> Result<Id, Error> {
|
||||
identity.value.ok_or_else(|| {
|
||||
error(
|
||||
span,
|
||||
"Missing ID requires source stabilization before lowering.",
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
impl Tables {
|
||||
fn reserve(&mut self, span: Span, budget: &Budget) -> Result<(), Error> {
|
||||
budget.lowering_entries(self.entries + 1, span)?;
|
||||
self.entries += 1;
|
||||
Ok(())
|
||||
}
|
||||
pub(super) fn insert(
|
||||
&mut self,
|
||||
id: Id,
|
||||
alias: &str,
|
||||
category: Category,
|
||||
span: Span,
|
||||
budget: &Budget,
|
||||
) -> Result<(), Error> {
|
||||
// A phase allocation bound, not a second syntax charge. Ordinary
|
||||
// records, typed headers and scoped parameters share this bound.
|
||||
self.reserve(span, budget)?;
|
||||
if self.ids.contains(&id) {
|
||||
return Err(error(span, "Duplicate global identity."));
|
||||
}
|
||||
if self.aliases.contains_key(alias) {
|
||||
return Err(error(span, format!("Duplicate global alias '{alias}'.")));
|
||||
}
|
||||
self.ids.insert(id);
|
||||
self.aliases
|
||||
.insert(alias.to_owned(), Symbol { id, category });
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn ordinary(&mut self, project: &Project, budget: &Budget) -> Result<(), Error> {
|
||||
let at = Span::default();
|
||||
self.insert(project.id, &project.alias, Category::Project, at, budget)?;
|
||||
for value in project.definitions.values() {
|
||||
let category = match &value.body {
|
||||
a::DefinitionBody::QuantityKind(_) => Category::QuantityKind,
|
||||
a::DefinitionBody::Unit(_) => Category::Unit,
|
||||
a::DefinitionBody::Calculation(_) => Category::Calculation,
|
||||
};
|
||||
self.insert(value.id, &value.alias, category, at, budget)?;
|
||||
if let a::DefinitionBody::Calculation(calculation) = &value.body {
|
||||
let mut names = BTreeMap::new();
|
||||
let mut ids = BTreeSet::new();
|
||||
for parameter in &calculation.parameters {
|
||||
self.reserve(at, budget)?;
|
||||
if names.contains_key(¶meter.name) || !ids.insert(parameter.id) {
|
||||
return Err(error(
|
||||
at,
|
||||
"Duplicate parameter name or identity in ordinary catalog.",
|
||||
));
|
||||
}
|
||||
names.insert(parameter.name.clone(), parameter.id);
|
||||
}
|
||||
self.parameters.insert(value.id, names);
|
||||
}
|
||||
}
|
||||
for value in project.elements.values() {
|
||||
self.insert(
|
||||
value.id,
|
||||
&value.alias,
|
||||
Category::Element(value.kind(), value.layer()),
|
||||
at,
|
||||
budget,
|
||||
)?;
|
||||
}
|
||||
for value in project.relations.values() {
|
||||
self.insert(value.id, &value.alias, Category::Relation, at, budget)?;
|
||||
}
|
||||
for value in project.diagrams.values() {
|
||||
self.insert(value.id, &value.alias, Category::Diagram, at, budget)?;
|
||||
for node in value.nodes.values() {
|
||||
self.insert(node.id, &node.alias, Category::Node, at, budget)?;
|
||||
}
|
||||
}
|
||||
for value in project.artifact_links.values() {
|
||||
self.insert(value.id, &value.alias, Category::Artifact, at, budget)?;
|
||||
}
|
||||
for value in project.traces.values() {
|
||||
self.insert(value.id, &value.alias, Category::Trace, at, budget)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(super) fn typed(
|
||||
&mut self,
|
||||
declaration: &Declaration,
|
||||
budget: &Budget,
|
||||
) -> Result<(), Error> {
|
||||
let header = &declaration.header;
|
||||
let id = identity(&header.identity, header.alias.span)?;
|
||||
self.insert(
|
||||
id,
|
||||
&header.alias.name,
|
||||
category(header.kind),
|
||||
header.alias.span,
|
||||
budget,
|
||||
)?;
|
||||
if let d::Body::Calculation { parameters, .. } = &declaration.body {
|
||||
let mut names = BTreeMap::new();
|
||||
let mut ids = BTreeSet::new();
|
||||
for parameter in parameters {
|
||||
self.reserve(parameter.span, budget)?;
|
||||
let id = a::ParameterId(identity(¶meter.identity, parameter.name.span)?);
|
||||
if names.contains_key(¶meter.name.name) || !ids.insert(id) {
|
||||
return Err(error(
|
||||
parameter.name.span,
|
||||
"Duplicate parameter name or identity.",
|
||||
));
|
||||
}
|
||||
names.insert(parameter.name.name.clone(), id);
|
||||
}
|
||||
self.parameters.insert(id, names);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// Inputs must come from the same live Budget and stabilization pass. No scan,
|
||||
/// exact conversion or reference charge occurs here. The ordinary skeleton is
|
||||
/// not semantically admitted: its typed forward references may need additions.
|
||||
pub(super) fn lower(
|
||||
ordinary: &Project,
|
||||
units: &[Unit],
|
||||
budget: &Budget,
|
||||
) -> Result<Lowered, Failure> {
|
||||
budget
|
||||
.active()
|
||||
.map_err(|error| Failure { file: None, error })?;
|
||||
let mut tables = Tables::default();
|
||||
tables
|
||||
.ordinary(ordinary, budget)
|
||||
.map_err(|error| Failure { file: None, error })?;
|
||||
let mut files = BTreeSet::new();
|
||||
for unit in units {
|
||||
budget
|
||||
.lowering_entries(files.len() + 1, Span::default())
|
||||
.map_err(|error| Failure {
|
||||
file: Some(unit.file),
|
||||
error,
|
||||
})?;
|
||||
if !files.insert(unit.file) {
|
||||
return Err(Failure {
|
||||
file: Some(unit.file),
|
||||
error: error(Span::default(), "Duplicate source file key."),
|
||||
});
|
||||
}
|
||||
for declaration in &unit.declarations {
|
||||
tables.typed(declaration, budget).map_err(|error| Failure {
|
||||
file: Some(unit.file),
|
||||
error,
|
||||
})?;
|
||||
}
|
||||
}
|
||||
lower_bodies(
|
||||
&tables,
|
||||
units
|
||||
.iter()
|
||||
.flat_map(|unit| unit.declarations.iter().map(move |d| (unit.file, d))),
|
||||
budget,
|
||||
)
|
||||
}
|
||||
|
||||
/// Catalog and borrowed declarations must be from the same private witness.
|
||||
/// The mixed caller reserves aggregate live storage before entering this body;
|
||||
/// the legacy wrapper retains its original individual phase checks.
|
||||
pub(super) fn lower_bodies<'a>(
|
||||
tables: &Tables,
|
||||
declarations: impl IntoIterator<Item = (usize, &'a Declaration)>,
|
||||
budget: &Budget,
|
||||
) -> Result<Lowered, Failure> {
|
||||
budget
|
||||
.active()
|
||||
.map_err(|error| Failure { file: None, error })?;
|
||||
let mut output = Lowered {
|
||||
definitions: BTreeMap::new(),
|
||||
elements: BTreeMap::new(),
|
||||
occurrences: Vec::new(),
|
||||
expressions: Vec::new(),
|
||||
};
|
||||
for (file, declaration) in declarations {
|
||||
let owner = declaration
|
||||
.header
|
||||
.identity
|
||||
.value
|
||||
.expect("collected stable identity");
|
||||
let mut resolver = Resolver {
|
||||
tables,
|
||||
output: &mut output,
|
||||
budget,
|
||||
file,
|
||||
owner,
|
||||
};
|
||||
resolver.declaration(declaration).map_err(|error| Failure {
|
||||
file: Some(file),
|
||||
error,
|
||||
})?;
|
||||
}
|
||||
Ok(output)
|
||||
}
|
||||
|
||||
struct Resolver<'a> {
|
||||
tables: &'a Tables,
|
||||
output: &'a mut Lowered,
|
||||
budget: &'a Budget,
|
||||
file: usize,
|
||||
owner: Id,
|
||||
}
|
||||
|
||||
impl Resolver<'_> {
|
||||
fn occurrence(
|
||||
&mut self,
|
||||
reference: &Reference,
|
||||
field: Field,
|
||||
expression: Option<usize>,
|
||||
role: Role,
|
||||
target: Target,
|
||||
) -> Result<(), Error> {
|
||||
self.budget
|
||||
.lowering_occurrences(self.output.occurrences.len() + 1, reference.span)?;
|
||||
self.output.occurrences.push(Occurrence {
|
||||
file: self.file,
|
||||
owner: self.owner,
|
||||
field,
|
||||
expression,
|
||||
role,
|
||||
target,
|
||||
span: reference.span,
|
||||
});
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn global(
|
||||
&mut self,
|
||||
reference: &Reference,
|
||||
field: Field,
|
||||
expression: Option<usize>,
|
||||
role: Role,
|
||||
expected: impl FnOnce(Category) -> bool,
|
||||
) -> Result<Symbol, Error> {
|
||||
let symbol = *self.tables.aliases.get(&reference.name).ok_or_else(|| {
|
||||
error(
|
||||
reference.span,
|
||||
format!("Unknown global reference '@{}'.", reference.name),
|
||||
)
|
||||
})?;
|
||||
if !expected(symbol.category) {
|
||||
return Err(error(
|
||||
reference.span,
|
||||
format!(
|
||||
"Wrong reference domain for '@{}': {:?}.",
|
||||
reference.name, symbol.category
|
||||
),
|
||||
));
|
||||
}
|
||||
self.occurrence(
|
||||
reference,
|
||||
field,
|
||||
expression,
|
||||
role,
|
||||
Target::Global(symbol.id),
|
||||
)?;
|
||||
Ok(symbol)
|
||||
}
|
||||
|
||||
fn definition_ref(
|
||||
&mut self,
|
||||
reference: &Reference,
|
||||
field: Field,
|
||||
expression: Option<usize>,
|
||||
expected: Category,
|
||||
) -> Result<a::DefinitionRef, Error> {
|
||||
self.global(reference, field, expression, Role::Reference, |category| {
|
||||
category == expected
|
||||
})
|
||||
.map(|symbol| a::DefinitionRef::Local(symbol.id))
|
||||
}
|
||||
|
||||
fn value_type(
|
||||
&mut self,
|
||||
value: &d::TypeSyntax,
|
||||
field: Field,
|
||||
) -> Result<a::AnalysisType, Error> {
|
||||
let scalar =
|
||||
match &value.scalar.kind {
|
||||
d::ScalarKind::Boolean => a::ScalarType::Boolean,
|
||||
d::ScalarKind::Number => a::ScalarType::Number,
|
||||
d::ScalarKind::Quantity(reference) => a::ScalarType::Quantity(
|
||||
self.definition_ref(reference, field, None, Category::QuantityKind)?,
|
||||
),
|
||||
};
|
||||
Ok(if value.list {
|
||||
a::AnalysisType::List(scalar)
|
||||
} else {
|
||||
a::AnalysisType::Scalar(scalar)
|
||||
})
|
||||
}
|
||||
|
||||
fn subject(&mut self, reference: &Reference) -> Result<a::AnalysisSubject, Error> {
|
||||
let symbol = self.global(
|
||||
reference,
|
||||
Field::Subject,
|
||||
None,
|
||||
Role::Reference,
|
||||
|category| matches!(category, Category::Element(..) | Category::Relation),
|
||||
)?;
|
||||
Ok(if symbol.category == Category::Relation {
|
||||
a::AnalysisSubject::Relation(symbol.id)
|
||||
} else {
|
||||
a::AnalysisSubject::Element(symbol.id)
|
||||
})
|
||||
}
|
||||
|
||||
fn optional_subject(
|
||||
&mut self,
|
||||
subject: &Option<d::Field<Option<Reference>>>,
|
||||
) -> Result<Option<a::AnalysisSubject>, Error> {
|
||||
subject
|
||||
.as_ref()
|
||||
.and_then(|field| field.value.as_ref())
|
||||
.map(|reference| self.subject(reference))
|
||||
.transpose()
|
||||
}
|
||||
|
||||
fn declaration(&mut self, declaration: &Declaration) -> Result<(), Error> {
|
||||
let header = &declaration.header;
|
||||
let definition = match &declaration.body {
|
||||
d::Body::QuantityKind { dimension, algebra } => {
|
||||
Some(a::DefinitionBody::QuantityKind(a::QuantityKindDefinition {
|
||||
dimension: Dimension::new(dimension.value.exponents)
|
||||
.map_err(|cause| error(dimension.value_span, cause.to_string()))?,
|
||||
algebra: match &algebra.value {
|
||||
d::AlgebraSyntax::Linear => a::QuantityAlgebra::Linear,
|
||||
d::AlgebraSyntax::Affine(reference) => a::QuantityAlgebra::Affine {
|
||||
difference: self.definition_ref(
|
||||
reference,
|
||||
Field::Algebra,
|
||||
None,
|
||||
Category::QuantityKind,
|
||||
)?,
|
||||
},
|
||||
},
|
||||
}))
|
||||
}
|
||||
d::Body::Unit {
|
||||
kind,
|
||||
scale,
|
||||
offset,
|
||||
symbol,
|
||||
} => Some(a::DefinitionBody::Unit(a::UnitDefinition {
|
||||
kind: self.definition_ref(
|
||||
&kind.value,
|
||||
Field::Kind,
|
||||
None,
|
||||
Category::QuantityKind,
|
||||
)?,
|
||||
scale: scale.value.value.clone(),
|
||||
offset: offset.value.value.clone(),
|
||||
symbol: symbol.value.clone(),
|
||||
})),
|
||||
d::Body::Calculation {
|
||||
parameters,
|
||||
result,
|
||||
body,
|
||||
} => {
|
||||
let mut lowered = Vec::new();
|
||||
for parameter in parameters {
|
||||
self.budget
|
||||
.lowering_entries(lowered.len() + 1, parameter.span)?;
|
||||
let id = self.tables.parameters[&self.owner][¶meter.name.name];
|
||||
self.occurrence(
|
||||
¶meter.name,
|
||||
Field::Input(id),
|
||||
None,
|
||||
Role::ParameterDeclaration,
|
||||
Target::Parameter {
|
||||
calculation: self.owner,
|
||||
parameter: id,
|
||||
},
|
||||
)?;
|
||||
lowered.push(a::Parameter {
|
||||
id,
|
||||
name: parameter.name.name.clone(),
|
||||
value_type: self.value_type(¶meter.value_type, Field::Input(id))?,
|
||||
});
|
||||
}
|
||||
Some(a::DefinitionBody::Calculation(a::CalculationDefinition {
|
||||
parameters: lowered,
|
||||
result: self.value_type(&result.value, Field::Result)?,
|
||||
body: self.binding(&body.value, Field::Body, Some(self.owner))?,
|
||||
}))
|
||||
}
|
||||
_ => None,
|
||||
};
|
||||
let description = declaration
|
||||
.description
|
||||
.as_ref()
|
||||
.map_or_else(String::new, |field| field.value.clone());
|
||||
if let Some(body) = definition {
|
||||
self.output.definitions.insert(
|
||||
self.owner,
|
||||
a::Definition {
|
||||
id: self.owner,
|
||||
alias: header.alias.name.clone(),
|
||||
name: header.name.clone(),
|
||||
description,
|
||||
body,
|
||||
},
|
||||
);
|
||||
return Ok(());
|
||||
}
|
||||
let (layer, body) = match (&declaration.body, header.kind) {
|
||||
(
|
||||
d::Body::Property {
|
||||
subject,
|
||||
value_type,
|
||||
base,
|
||||
display_unit,
|
||||
},
|
||||
DeclarationKind::Property(layer),
|
||||
) => (
|
||||
layer,
|
||||
SharedBody::EngineeringProperty {
|
||||
subject: self.subject(&subject.value)?,
|
||||
value_type: self.value_type(&value_type.value, Field::Type)?,
|
||||
base: self.binding(&base.value, Field::Base, None)?,
|
||||
display_unit: display_unit
|
||||
.as_ref()
|
||||
.and_then(|field| field.value.as_ref())
|
||||
.map(|reference| {
|
||||
self.definition_ref(reference, Field::DisplayUnit, None, Category::Unit)
|
||||
})
|
||||
.transpose()?,
|
||||
},
|
||||
),
|
||||
(
|
||||
d::Body::Check {
|
||||
subject,
|
||||
documented_constraint,
|
||||
predicate,
|
||||
},
|
||||
DeclarationKind::Check(layer),
|
||||
) => (
|
||||
layer,
|
||||
SharedBody::AnalysisCheck {
|
||||
subject: self.optional_subject(subject)?,
|
||||
documented_constraint: documented_constraint
|
||||
.as_ref()
|
||||
.and_then(|field| field.value.as_ref())
|
||||
.map(|reference| {
|
||||
self.global(
|
||||
reference,
|
||||
Field::DocumentedConstraint,
|
||||
None,
|
||||
Role::Reference,
|
||||
|category| {
|
||||
matches!(category, Category::Element(Kind::Constraint, _))
|
||||
},
|
||||
)
|
||||
.map(|symbol| symbol.id)
|
||||
})
|
||||
.transpose()?,
|
||||
predicate: self.binding(&predicate.value, Field::Predicate, None)?,
|
||||
},
|
||||
),
|
||||
(
|
||||
d::Body::Case {
|
||||
subject, overrides, ..
|
||||
},
|
||||
DeclarationKind::Case(layer),
|
||||
) => {
|
||||
let subject = self.optional_subject(subject)?;
|
||||
let mut lowered = BTreeMap::new();
|
||||
for entry in &overrides.value {
|
||||
let property = self
|
||||
.global(
|
||||
&entry.target,
|
||||
Field::Base,
|
||||
None,
|
||||
Role::OverrideTarget,
|
||||
|category| {
|
||||
matches!(category, Category::Element(Kind::EngineeringProperty, _))
|
||||
},
|
||||
)?
|
||||
.id;
|
||||
// Replace the placeholder field after resolution so the key
|
||||
// and its binding share their stable override identity.
|
||||
self.output
|
||||
.occurrences
|
||||
.last_mut()
|
||||
.expect("override occurrence")
|
||||
.field = Field::Override(property);
|
||||
if lowered.contains_key(&property) {
|
||||
return Err(error(
|
||||
entry.target.span,
|
||||
"Duplicate resolved override target.",
|
||||
));
|
||||
}
|
||||
self.budget
|
||||
.lowering_entries(lowered.len() + 1, entry.span)?;
|
||||
lowered.insert(
|
||||
property,
|
||||
self.binding(&entry.binding, Field::Override(property), None)?,
|
||||
);
|
||||
}
|
||||
(
|
||||
layer,
|
||||
SharedBody::AnalysisCase {
|
||||
subject,
|
||||
base: a::BaselineBase::ModelBaseline,
|
||||
overrides: lowered,
|
||||
},
|
||||
)
|
||||
}
|
||||
_ => {
|
||||
return Err(error(
|
||||
header.kind_span,
|
||||
"Typed declaration header/body mismatch.",
|
||||
));
|
||||
}
|
||||
};
|
||||
self.output.elements.insert(
|
||||
self.owner,
|
||||
Element {
|
||||
id: self.owner,
|
||||
alias: header.alias.name.clone(),
|
||||
name: header.name.clone(),
|
||||
description,
|
||||
parent: None,
|
||||
body: ElementBody::shared_in(layer, body),
|
||||
},
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn binding(
|
||||
&mut self,
|
||||
binding: &Binding,
|
||||
field: Field,
|
||||
calculation: Option<Id>,
|
||||
) -> Result<a::Binding, Error> {
|
||||
match binding {
|
||||
Binding::Unbound(_) => Ok(a::Binding::Unbound),
|
||||
Binding::Expression(expression) => self
|
||||
.expression(expression, field, calculation)
|
||||
.map(a::Binding::Expression),
|
||||
}
|
||||
}
|
||||
|
||||
fn call(
|
||||
&mut self,
|
||||
definition: &Reference,
|
||||
arguments: &[Argument],
|
||||
field: Field,
|
||||
site: usize,
|
||||
) -> Result<Call, Error> {
|
||||
let calculation = self
|
||||
.global(
|
||||
definition,
|
||||
field,
|
||||
Some(site),
|
||||
Role::CallTarget,
|
||||
|category| category == Category::Calculation,
|
||||
)?
|
||||
.id;
|
||||
let tables = self.tables;
|
||||
let signature = &tables.parameters[&calculation];
|
||||
let mut parameters = Vec::new();
|
||||
let mut seen = BTreeSet::new();
|
||||
for argument in arguments {
|
||||
self.budget
|
||||
.lowering_entries(parameters.len() + 1, argument.parameter.span)?;
|
||||
let parameter = *signature.get(&argument.parameter.name).ok_or_else(|| {
|
||||
error(
|
||||
argument.parameter.span,
|
||||
"Unknown argument name in called calculation.",
|
||||
)
|
||||
})?;
|
||||
if !seen.insert(parameter) {
|
||||
return Err(error(
|
||||
argument.parameter.span,
|
||||
"Duplicate resolved argument parameter.",
|
||||
));
|
||||
}
|
||||
self.occurrence(
|
||||
&argument.parameter,
|
||||
field,
|
||||
Some(site),
|
||||
Role::ArgumentLabel,
|
||||
Target::Parameter {
|
||||
calculation,
|
||||
parameter,
|
||||
},
|
||||
)?;
|
||||
parameters.push(parameter);
|
||||
}
|
||||
// Argument-set/type checking remains in existing semantic admission.
|
||||
Ok(Call {
|
||||
calculation,
|
||||
parameters,
|
||||
})
|
||||
}
|
||||
|
||||
fn expression(
|
||||
&mut self,
|
||||
root: &Expression,
|
||||
field: Field,
|
||||
calculation: Option<Id>,
|
||||
) -> Result<a::Expr, Error> {
|
||||
enum Work<'a> {
|
||||
Visit(&'a Expression, Option<(usize, Child)>),
|
||||
Build(&'a Expression, usize, Option<Call>, usize),
|
||||
}
|
||||
let mut work = vec![Work::Visit(root, None)];
|
||||
let mut values = Vec::new();
|
||||
while let Some(task) = work.pop() {
|
||||
match task {
|
||||
Work::Visit(expression, parent) => {
|
||||
self.budget
|
||||
.lowering_entries(self.output.expressions.len() + 1, expression.span)?;
|
||||
let site = self.output.expressions.len();
|
||||
self.output.expressions.push(ExpressionSite {
|
||||
file: self.file,
|
||||
owner: self.owner,
|
||||
field,
|
||||
parent,
|
||||
span: expression.span,
|
||||
});
|
||||
let call = if let ExpressionKind::Call {
|
||||
definition,
|
||||
arguments,
|
||||
} = &expression.kind
|
||||
{
|
||||
Some(self.call(definition, arguments, field, site)?)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
let child_count = match &expression.kind {
|
||||
ExpressionKind::List(items) => items.len(),
|
||||
ExpressionKind::Call { arguments, .. } => arguments.len(),
|
||||
ExpressionKind::Unary { .. }
|
||||
| ExpressionKind::Power { .. }
|
||||
| ExpressionKind::AsKind { .. } => 1,
|
||||
ExpressionKind::Binary { .. } | ExpressionKind::Sum { .. } => 2,
|
||||
ExpressionKind::If { .. } => 3,
|
||||
_ => 0,
|
||||
};
|
||||
self.budget
|
||||
.lowering_entries(work.len() + child_count + 1, expression.span)?;
|
||||
let mut children = Vec::with_capacity(child_count);
|
||||
match &expression.kind {
|
||||
ExpressionKind::List(items) => children.extend(
|
||||
items
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(index, child)| (child, Child::Item(index))),
|
||||
),
|
||||
ExpressionKind::Unary { operand, .. } => {
|
||||
children.push((operand.as_ref(), Child::Operand))
|
||||
}
|
||||
ExpressionKind::Binary { left, right, .. } => children
|
||||
.extend([(left.as_ref(), Child::Left), (right.as_ref(), Child::Right)]),
|
||||
ExpressionKind::If {
|
||||
condition,
|
||||
when_true,
|
||||
when_false,
|
||||
} => children.extend([
|
||||
(condition.as_ref(), Child::Condition),
|
||||
(when_true.as_ref(), Child::WhenTrue),
|
||||
(when_false.as_ref(), Child::WhenFalse),
|
||||
]),
|
||||
ExpressionKind::Call { arguments, .. } => children.extend(
|
||||
arguments
|
||||
.iter()
|
||||
.zip(&call.as_ref().expect("call signature").parameters)
|
||||
.map(|(argument, id)| (&argument.value, Child::Argument(*id))),
|
||||
),
|
||||
ExpressionKind::Sum { values, initial } => children.extend([
|
||||
(values.as_ref(), Child::Values),
|
||||
(initial.as_ref(), Child::Initial),
|
||||
]),
|
||||
ExpressionKind::Power { base, .. } => {
|
||||
children.push((base.as_ref(), Child::Base))
|
||||
}
|
||||
ExpressionKind::AsKind { value, .. } => {
|
||||
children.push((value.as_ref(), Child::Value))
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
work.push(Work::Build(expression, site, call, children.len()));
|
||||
work.extend(
|
||||
children
|
||||
.into_iter()
|
||||
.rev()
|
||||
.map(|(child, edge)| Work::Visit(child, Some((site, edge)))),
|
||||
);
|
||||
}
|
||||
Work::Build(expression, site, call, count) => {
|
||||
let start = values.len() - count;
|
||||
let mut children = values.split_off(start).into_iter();
|
||||
let next = |children: &mut std::vec::IntoIter<a::Expr>| {
|
||||
Box::new(children.next().expect("visited expression child"))
|
||||
};
|
||||
use ExpressionKind as E;
|
||||
let value = match &expression.kind {
|
||||
E::Boolean(value) => a::Expr::Boolean(*value),
|
||||
E::Number(value) => a::Expr::Number(value.clone()),
|
||||
E::Quantity { magnitude, unit } => a::Expr::Quantity {
|
||||
magnitude: magnitude.clone(),
|
||||
unit: self.definition_ref(unit, field, Some(site), Category::Unit)?,
|
||||
},
|
||||
E::Property(reference) => a::Expr::Property(
|
||||
self.global(
|
||||
reference,
|
||||
field,
|
||||
Some(site),
|
||||
Role::Reference,
|
||||
|category| {
|
||||
matches!(
|
||||
category,
|
||||
Category::Element(Kind::EngineeringProperty, _)
|
||||
)
|
||||
},
|
||||
)?
|
||||
.id,
|
||||
),
|
||||
E::Parameter(reference) => {
|
||||
let calculation = calculation.ok_or_else(|| {
|
||||
error(
|
||||
reference.span,
|
||||
"Parameter use is only valid in its calculation body.",
|
||||
)
|
||||
})?;
|
||||
let parameter = *self.tables.parameters[&calculation]
|
||||
.get(&reference.name)
|
||||
.ok_or_else(|| {
|
||||
error(
|
||||
reference.span,
|
||||
"Unknown parameter in owning calculation.",
|
||||
)
|
||||
})?;
|
||||
self.occurrence(
|
||||
reference,
|
||||
field,
|
||||
Some(site),
|
||||
Role::ParameterUse,
|
||||
Target::Parameter {
|
||||
calculation,
|
||||
parameter,
|
||||
},
|
||||
)?;
|
||||
a::Expr::Parameter(parameter)
|
||||
}
|
||||
E::List(_) => a::Expr::List(children.collect()),
|
||||
E::Unary { op, .. } => a::Expr::Unary {
|
||||
op: *op,
|
||||
operand: next(&mut children),
|
||||
},
|
||||
E::Binary { op, .. } => a::Expr::Binary {
|
||||
op: *op,
|
||||
left: next(&mut children),
|
||||
right: next(&mut children),
|
||||
},
|
||||
E::If { .. } => a::Expr::If {
|
||||
condition: next(&mut children),
|
||||
when_true: next(&mut children),
|
||||
when_false: next(&mut children),
|
||||
},
|
||||
E::Call { .. } => {
|
||||
let call = call.expect("resolved call");
|
||||
a::Expr::Call {
|
||||
definition: a::DefinitionRef::Local(call.calculation),
|
||||
arguments: call.parameters.into_iter().zip(children).collect(),
|
||||
}
|
||||
}
|
||||
E::Sum { .. } => a::Expr::Sum {
|
||||
values: next(&mut children),
|
||||
initial: next(&mut children),
|
||||
},
|
||||
E::Power { exponent, .. } => a::Expr::Power {
|
||||
base: next(&mut children),
|
||||
exponent: *exponent,
|
||||
},
|
||||
E::AsKind { kind, .. } => a::Expr::AsKind {
|
||||
kind: self.definition_ref(
|
||||
kind,
|
||||
field,
|
||||
Some(site),
|
||||
Category::QuantityKind,
|
||||
)?,
|
||||
value: next(&mut children),
|
||||
},
|
||||
};
|
||||
self.budget
|
||||
.lowering_entries(values.len() + 1, expression.span)?;
|
||||
values.push(value);
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(values.pop().expect("one lowered expression"))
|
||||
}
|
||||
}
|
||||
|
||||
struct Call {
|
||||
calculation: Id,
|
||||
parameters: Vec<a::ParameterId>,
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
@@ -0,0 +1,7 @@
|
||||
arcadia 7;
|
||||
project response_budget "Response budget" id "4210b9f2-7046-47f0-aa3b-153f626a579d" {
|
||||
oa_activity respond "Respond" id "cabec6a1-7d5d-48f3-8d2d-a7fc8cf78f59" {
|
||||
oa_activity receive "Receive" id "4ab9a8a7-7552-488d-9862-e14b89e7b353" {}
|
||||
oa_activity dispatch "Dispatch" id "6df991ba-4c5e-4535-99e2-524ae274ee8b" {}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
arcadia 7;
|
||||
project response_budget "Response budget" id "c210b9f2-7046-47f0-aa3b-153f626a579d" {
|
||||
sa_function respond "Respond" id "4abec6a1-7d5d-48f3-8d2d-a7fc8cf78f59" {
|
||||
sa_function receive "Receive" id "cab9a8a7-7552-488d-9862-e14b89e7b353" {}
|
||||
sa_function dispatch "Dispatch" id "edf991ba-4c5e-4535-99e2-524ae274ee8b" {}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
// Staged typed roots from the r2 example; ordinary roots are supplied separately.
|
||||
// Forward uses precede the neutral definitions. 雪 keeps offsets UTF-8 sensitive.
|
||||
oa_property receive_time "Receive time" id "63a931c2-675a-4fce-89e5-04361cb99450" {
|
||||
subject @receive; type Quantity(@duration); display_unit @millisecond;
|
||||
base 750 [@millisecond];
|
||||
}
|
||||
oa_property dispatch_time "Dispatch time" id "c33fc772-2a60-4044-9af9-73c61c563ace" {
|
||||
subject @dispatch; type Quantity(@duration); display_unit @second;
|
||||
base 1 [@second];
|
||||
}
|
||||
oa_property total_time "Total time" id "bd5b68e8-65fc-4e35-9071-a73061316a4b" {
|
||||
subject @respond; type Quantity(@duration); display_unit @second;
|
||||
base @combine(a: @receive_time, b: @dispatch_time);
|
||||
}
|
||||
oa_property limit "Allowed duration" id "437bedbb-2cf4-44ee-a139-6563cc5086ec" {
|
||||
subject @respond; type Quantity(@duration); display_unit @second;
|
||||
base 2 [@second];
|
||||
}
|
||||
oa_check budget "Response budget" id "bac0de99-9d2f-4e53-9158-d424ecac61bf" {
|
||||
subject none; documented_constraint none; predicate @total_time <= @limit;
|
||||
}
|
||||
oa_analysis degraded "Degraded radio" id "38036c65-16d4-449c-837b-91eb141c1d93" {
|
||||
subject none; base ModelBaseline;
|
||||
overrides { @receive_time = 1250 [@millisecond]; };
|
||||
}
|
||||
oa_analysis unmeasured "Unmeasured radio" id "99d3e09a-0ec3-4194-9dd4-9f3de6625cde" {
|
||||
subject none; base ModelBaseline;
|
||||
overrides { @receive_time = unbound; };
|
||||
}
|
||||
calculation combine "Combine durations" id "fd7ce7ab-f789-40bc-b699-0c37f1b6902f" {
|
||||
input a id "28ff40b0-1b8f-4735-8536-5a6ab21b56cb" : Quantity(@duration);
|
||||
input b id "7a47cc1e-8ae5-4551-b2d8-8a68108e0976" : Quantity(@duration);
|
||||
result Quantity(@duration); body $a + $b;
|
||||
}
|
||||
unit second "Second" id "534f4672-1ba5-4157-8b0a-b9cf41d0a3ce" {
|
||||
kind @duration; scale 1; offset 0; symbol "s";
|
||||
}
|
||||
unit millisecond "Millisecond" id "39053f37-fec9-4708-9f0a-3959d223f891" {
|
||||
kind @duration; scale ratio(1, 1000); offset 0; symbol "ms";
|
||||
}
|
||||
quantity_kind duration "Duration" id "188b911c-5f8b-431c-9eea-2d41f3953767" {
|
||||
dimension { time 1; }; algebra Linear;
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
// Staged typed roots from the r2 example; ordinary roots are supplied separately.
|
||||
// Forward uses precede the neutral definitions. 雪 keeps offsets UTF-8 sensitive.
|
||||
sa_property receive_time "Receive time" id "e3a931c2-675a-4fce-89e5-04361cb99450" {
|
||||
subject @receive; type Quantity(@duration); display_unit @millisecond;
|
||||
base 750 [@millisecond];
|
||||
}
|
||||
sa_property dispatch_time "Dispatch time" id "433fc772-2a60-4044-9af9-73c61c563ace" {
|
||||
subject @dispatch; type Quantity(@duration); display_unit @second;
|
||||
base 1 [@second];
|
||||
}
|
||||
sa_property total_time "Total time" id "3d5b68e8-65fc-4e35-9071-a73061316a4b" {
|
||||
subject @respond; type Quantity(@duration); display_unit @second;
|
||||
base @combine(a: @receive_time, b: @dispatch_time);
|
||||
}
|
||||
sa_property limit "Allowed duration" id "c37bedbb-2cf4-44ee-a139-6563cc5086ec" {
|
||||
subject @respond; type Quantity(@duration); display_unit @second;
|
||||
base 2 [@second];
|
||||
}
|
||||
sa_check budget "Response budget" id "3ac0de99-9d2f-4e53-9158-d424ecac61bf" {
|
||||
subject none; documented_constraint none; predicate @total_time <= @limit;
|
||||
}
|
||||
sa_analysis degraded "Degraded radio" id "b8036c65-16d4-449c-837b-91eb141c1d93" {
|
||||
subject none; base ModelBaseline;
|
||||
overrides { @receive_time = 1250 [@millisecond]; };
|
||||
}
|
||||
sa_analysis unmeasured "Unmeasured radio" id "19d3e09a-0ec3-4194-9dd4-9f3de6625cde" {
|
||||
subject none; base ModelBaseline;
|
||||
overrides { @receive_time = unbound; };
|
||||
}
|
||||
calculation combine "Combine durations" id "7d7ce7ab-f789-40bc-b699-0c37f1b6902f" {
|
||||
input a id "28ff40b0-1b8f-4735-8536-5a6ab21b56cb" : Quantity(@duration);
|
||||
input b id "7a47cc1e-8ae5-4551-b2d8-8a68108e0976" : Quantity(@duration);
|
||||
result Quantity(@duration); body $a + $b;
|
||||
}
|
||||
unit second "Second" id "d34f4672-1ba5-4157-8b0a-b9cf41d0a3ce" {
|
||||
kind @duration; scale 1; offset 0; symbol "s";
|
||||
}
|
||||
unit millisecond "Millisecond" id "b9053f37-fec9-4708-9f0a-3959d223f891" {
|
||||
kind @duration; scale ratio(1, 1000); offset 0; symbol "ms";
|
||||
}
|
||||
quantity_kind duration "Duration" id "988b911c-5f8b-431c-9eea-2d41f3953767" {
|
||||
dimension { time 1; }; algebra Linear;
|
||||
}
|
||||
@@ -0,0 +1,888 @@
|
||||
use super::*;
|
||||
use crate::language::ParseLimits;
|
||||
use crate::language::analysis_source::{budget::Limits, cursor::Cursor};
|
||||
|
||||
use super::super::model_oracle as oracle;
|
||||
|
||||
const OA: &str = include_str!("fixtures/typed-oa.arcadia");
|
||||
const SA: &str = include_str!("fixtures/typed-sa.arcadia");
|
||||
const ORDINARY_OA: &str = include_str!("fixtures/ordinary-oa.arcadia");
|
||||
const ORDINARY_SA: &str = include_str!("fixtures/ordinary-sa.arcadia");
|
||||
|
||||
fn budget() -> Budget {
|
||||
Budget::new(Limits::source8(ParseLimits::UNLIMITED)).unwrap()
|
||||
}
|
||||
fn id(text: &str) -> Id {
|
||||
Id::parse_str(text).unwrap()
|
||||
}
|
||||
fn by_alias(project: &Project, alias: &str) -> Id {
|
||||
project
|
||||
.identities()
|
||||
.into_iter()
|
||||
.find(|(_, name)| *name == alias)
|
||||
.unwrap()
|
||||
.0
|
||||
}
|
||||
fn ordinary(source: &str) -> Project {
|
||||
crate::language::parse(source).unwrap()
|
||||
}
|
||||
fn unit(source: &str, file: usize, budget: &mut Budget) -> Unit {
|
||||
let tokens = lex::tokens(source, budget).unwrap();
|
||||
let mut cursor = Cursor::new(source, &tokens, budget);
|
||||
let mut declarations = Vec::new();
|
||||
while cursor.cursor < tokens.len() {
|
||||
declarations.push(d::parse(&mut cursor, 8, None).unwrap());
|
||||
}
|
||||
Unit { file, declarations }
|
||||
}
|
||||
fn merge(mut ordinary: Project, lowered: Lowered) -> Project {
|
||||
ordinary.definitions.extend(lowered.definitions);
|
||||
ordinary.elements.extend(lowered.elements);
|
||||
ordinary
|
||||
}
|
||||
fn admit(project: &Project) {
|
||||
a::admit(project, a::AdmissionLimits::REFERENCE).unwrap();
|
||||
}
|
||||
fn failure(source: &str, ordinary: &Project) -> Failure {
|
||||
let mut budget = budget();
|
||||
let unit = unit(source, 7, &mut budget);
|
||||
lower(ordinary, &[unit], &budget).unwrap_err()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn staged_oa_and_sa_lowering_match_complete_independent_17_uuid_oracles() {
|
||||
for (layer, ordinary_source, typed_source) in
|
||||
[(Layer::Oa, ORDINARY_OA, OA), (Layer::Sa, ORDINARY_SA, SA)]
|
||||
{
|
||||
let expected = oracle::project(layer);
|
||||
assert_eq!(expected.name, "Response budget");
|
||||
assert_eq!(expected.identities().len(), 15); // two additional scoped IDs
|
||||
for (alias, name) in oracle::NAMES {
|
||||
let object = by_alias(&expected, alias);
|
||||
let actual_name = expected
|
||||
.definitions
|
||||
.get(&object)
|
||||
.map(|value| value.name.as_str())
|
||||
.or_else(|| {
|
||||
expected
|
||||
.elements
|
||||
.get(&object)
|
||||
.map(|value| value.name.as_str())
|
||||
})
|
||||
.unwrap();
|
||||
assert_eq!(actual_name, name);
|
||||
assert_ne!(actual_name, alias);
|
||||
}
|
||||
let mut budget = budget();
|
||||
let units = [unit(typed_source, 17, &mut budget)];
|
||||
let usage = budget.usage;
|
||||
let numeric = budget.numeric_units();
|
||||
let skeleton = ordinary(ordinary_source);
|
||||
let first = lower(&skeleton, &units, &budget).unwrap();
|
||||
let second = lower(&skeleton, &units, &budget).unwrap();
|
||||
assert_eq!(first.occurrences, second.occurrences);
|
||||
assert_eq!(first.expressions, second.expressions);
|
||||
assert_eq!(budget.usage, usage);
|
||||
assert_eq!(budget.numeric_units(), numeric);
|
||||
assert_eq!(
|
||||
first
|
||||
.occurrences
|
||||
.iter()
|
||||
.filter(|occurrence| occurrence.role != Role::ParameterDeclaration)
|
||||
.count(),
|
||||
usage.references
|
||||
);
|
||||
let actual = merge(skeleton, first);
|
||||
assert_eq!(actual, expected);
|
||||
admit(&actual); // the complete model's one semantic admission
|
||||
}
|
||||
assert!(crate::language::parse(&ORDINARY_OA.replacen("arcadia 7", "arcadia 8", 1)).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn forward_cross_unit_resolution_keeps_original_offsets_and_shared_work() {
|
||||
let source = OA.replace('\n', "\r\n");
|
||||
let split = source.find("calculation combine").unwrap();
|
||||
let sources = [&source[..split], &source[split..]];
|
||||
let mut budget = budget();
|
||||
let mut units = [
|
||||
unit(sources[0], 4, &mut budget),
|
||||
unit(sources[1], 9, &mut budget),
|
||||
];
|
||||
let usage = budget.usage;
|
||||
assert_eq!(usage.bytes, source.len());
|
||||
let lowered = lower(&ordinary(ORDINARY_OA), &units, &budget).unwrap();
|
||||
units.reverse();
|
||||
// This second order uses the same bounded lowerer; output models must not
|
||||
// depend on declaration/file traversal order. It is not an include parser.
|
||||
let reordered = lower(&ordinary(ORDINARY_OA), &units, &budget).unwrap();
|
||||
assert_eq!(
|
||||
merge(ordinary(ORDINARY_OA), reordered),
|
||||
oracle::project(Layer::Oa)
|
||||
);
|
||||
for occurrence in &lowered.occurrences {
|
||||
let source = if occurrence.file == 4 {
|
||||
sources[0]
|
||||
} else {
|
||||
assert_eq!(occurrence.file, 9);
|
||||
sources[1]
|
||||
};
|
||||
let text = &source[occurrence.span.start..occurrence.span.end];
|
||||
assert!(crate::valid_alias(text));
|
||||
assert!(!text.starts_with('@') && !text.starts_with('$'));
|
||||
}
|
||||
assert_eq!(budget.usage, usage);
|
||||
assert_eq!(
|
||||
merge(ordinary(ORDINARY_OA), lowered),
|
||||
oracle::project(Layer::Oa)
|
||||
);
|
||||
}
|
||||
|
||||
fn number(value: i64) -> a::Expr {
|
||||
a::Expr::Number(crate::analysis_numeric::Exact::from_integer(value))
|
||||
}
|
||||
fn binary(op: a::BinaryOp, left: a::Expr, right: a::Expr) -> a::Expr {
|
||||
a::Expr::Binary {
|
||||
op,
|
||||
left: Box::new(left),
|
||||
right: Box::new(right),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn all_thirteen_expression_variants_lower_to_real_typed_values_and_admit() {
|
||||
let mut project = oracle::project(Layer::Oa);
|
||||
let duration = by_alias(&project, "duration");
|
||||
let second = by_alias(&project, "second");
|
||||
let property = by_alias(&project, "receive_time");
|
||||
let owner = by_alias(&project, "total_time");
|
||||
let calculation = by_alias(&project, "combine");
|
||||
let parameter = a::ParameterId(id("28ff40b0-1b8f-4735-8536-5a6ab21b56cb"));
|
||||
let b = a::ParameterId(id("7a47cc1e-8ae5-4551-b2d8-8a68108e0976"));
|
||||
let quantity =
|
||||
a::AnalysisType::Scalar(a::ScalarType::Quantity(a::DefinitionRef::Local(duration)));
|
||||
let numeric = a::AnalysisType::Scalar(a::ScalarType::Number);
|
||||
let boolean = a::AnalysisType::Scalar(a::ScalarType::Boolean);
|
||||
let cases = [
|
||||
("true", a::Expr::Boolean(true), boolean.clone()),
|
||||
(
|
||||
"ratio(3, 2)",
|
||||
a::Expr::Number(
|
||||
Exact::from_wire(
|
||||
&crate::analysis_numeric::ExactWire {
|
||||
numerator: "3".into(),
|
||||
denominator: "2".into(),
|
||||
},
|
||||
&mut crate::analysis_numeric::WorkMeter::new(
|
||||
crate::analysis_numeric::WorkLimits::REFERENCE,
|
||||
),
|
||||
)
|
||||
.unwrap(),
|
||||
),
|
||||
numeric.clone(),
|
||||
),
|
||||
(
|
||||
"2 [@second]",
|
||||
a::Expr::Quantity {
|
||||
magnitude: Exact::from_integer(2),
|
||||
unit: a::DefinitionRef::Local(second),
|
||||
},
|
||||
quantity.clone(),
|
||||
),
|
||||
(
|
||||
"@receive_time",
|
||||
a::Expr::Property(property),
|
||||
quantity.clone(),
|
||||
),
|
||||
("$a", a::Expr::Parameter(parameter), quantity.clone()),
|
||||
(
|
||||
"[1, 2]",
|
||||
a::Expr::List(vec![number(1), number(2)]),
|
||||
a::AnalysisType::List(a::ScalarType::Number),
|
||||
),
|
||||
(
|
||||
"abs(-2)",
|
||||
a::Expr::Unary {
|
||||
op: a::UnaryOp::Absolute,
|
||||
operand: Box::new(a::Expr::Unary {
|
||||
op: a::UnaryOp::Negate,
|
||||
operand: Box::new(number(2)),
|
||||
}),
|
||||
},
|
||||
numeric.clone(),
|
||||
),
|
||||
(
|
||||
"1 + 2",
|
||||
binary(a::BinaryOp::Add, number(1), number(2)),
|
||||
numeric.clone(),
|
||||
),
|
||||
(
|
||||
"if(true, 1, 2)",
|
||||
a::Expr::If {
|
||||
condition: Box::new(a::Expr::Boolean(true)),
|
||||
when_true: Box::new(number(1)),
|
||||
when_false: Box::new(number(2)),
|
||||
},
|
||||
numeric.clone(),
|
||||
),
|
||||
(
|
||||
"@combine(b: 2 [@second], a: 1 [@second])",
|
||||
a::Expr::Call {
|
||||
definition: a::DefinitionRef::Local(calculation),
|
||||
arguments: BTreeMap::from([
|
||||
(
|
||||
parameter,
|
||||
a::Expr::Quantity {
|
||||
magnitude: Exact::from_integer(1),
|
||||
unit: a::DefinitionRef::Local(second),
|
||||
},
|
||||
),
|
||||
(
|
||||
b,
|
||||
a::Expr::Quantity {
|
||||
magnitude: Exact::from_integer(2),
|
||||
unit: a::DefinitionRef::Local(second),
|
||||
},
|
||||
),
|
||||
]),
|
||||
},
|
||||
quantity.clone(),
|
||||
),
|
||||
(
|
||||
"sum([1, 2], 0)",
|
||||
a::Expr::Sum {
|
||||
values: Box::new(a::Expr::List(vec![number(1), number(2)])),
|
||||
initial: Box::new(number(0)),
|
||||
},
|
||||
numeric.clone(),
|
||||
),
|
||||
(
|
||||
"power(2, -2)",
|
||||
a::Expr::Power {
|
||||
base: Box::new(number(2)),
|
||||
exponent: -2,
|
||||
},
|
||||
numeric.clone(),
|
||||
),
|
||||
(
|
||||
"as_kind(@duration, power(1 [@second], 2) / 1 [@second])",
|
||||
a::Expr::AsKind {
|
||||
kind: a::DefinitionRef::Local(duration),
|
||||
value: Box::new(binary(
|
||||
a::BinaryOp::Divide,
|
||||
a::Expr::Power {
|
||||
base: Box::new(a::Expr::Quantity {
|
||||
magnitude: Exact::from_integer(1),
|
||||
unit: a::DefinitionRef::Local(second),
|
||||
}),
|
||||
exponent: 2,
|
||||
},
|
||||
a::Expr::Quantity {
|
||||
magnitude: Exact::from_integer(1),
|
||||
unit: a::DefinitionRef::Local(second),
|
||||
},
|
||||
)),
|
||||
},
|
||||
quantity.clone(),
|
||||
),
|
||||
];
|
||||
// Remove the original check's dependent quantity comparison: each case
|
||||
// installs a different declared result type on total_time below.
|
||||
project.elements.remove(&by_alias(&project, "budget"));
|
||||
for (source, expected, result_type) in cases {
|
||||
let mut budget = budget();
|
||||
let Binding::Expression(syntax) = super::super::parse(source, &mut budget).unwrap() else {
|
||||
panic!("expression")
|
||||
};
|
||||
let mut tables = Tables::default();
|
||||
tables.ordinary(&project, &budget).unwrap();
|
||||
let mut output = Lowered {
|
||||
definitions: BTreeMap::new(),
|
||||
elements: BTreeMap::new(),
|
||||
occurrences: Vec::new(),
|
||||
expressions: Vec::new(),
|
||||
};
|
||||
let is_parameter = source == "$a";
|
||||
let expression_owner = if is_parameter { calculation } else { owner };
|
||||
let actual = Resolver {
|
||||
tables: &tables,
|
||||
output: &mut output,
|
||||
budget: &budget,
|
||||
file: 3,
|
||||
owner: expression_owner,
|
||||
}
|
||||
.expression(
|
||||
&syntax,
|
||||
if is_parameter {
|
||||
Field::Body
|
||||
} else {
|
||||
Field::Base
|
||||
},
|
||||
is_parameter.then_some(calculation),
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(actual, expected, "{source}");
|
||||
assert_eq!(output.expressions[0].span, syntax.span);
|
||||
assert!(output.expressions[0].parent.is_none());
|
||||
let mut candidate = project.clone();
|
||||
if is_parameter {
|
||||
let a::DefinitionBody::Calculation(definition) =
|
||||
&mut candidate.definitions.get_mut(&calculation).unwrap().body
|
||||
else {
|
||||
panic!("calculation")
|
||||
};
|
||||
definition.body = a::Binding::Expression(actual);
|
||||
} else {
|
||||
let SharedBody::EngineeringProperty {
|
||||
value_type,
|
||||
display_unit,
|
||||
base,
|
||||
..
|
||||
} = candidate
|
||||
.elements
|
||||
.get_mut(&owner)
|
||||
.unwrap()
|
||||
.body
|
||||
.shared_mut()
|
||||
.unwrap()
|
||||
else {
|
||||
panic!("property")
|
||||
};
|
||||
*value_type = result_type;
|
||||
*display_unit = None;
|
||||
*base = a::Binding::Expression(actual);
|
||||
}
|
||||
admit(&candidate);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn call_sites_and_parameter_scopes_preserve_distinct_original_occurrences() {
|
||||
let source = OA.replace("base @combine(a: @receive_time, b: @dispatch_time);", "base @combine(a: @receive_time, // first\n b: @dispatch_time) + @combine(// second\n b: @dispatch_time, a: @receive_time);") + r#"
|
||||
calculation other "Other" id "00000000-0000-0000-0000-000000000020" {
|
||||
input a id "28ff40b0-1b8f-4735-8536-5a6ab21b56cb" : Number;
|
||||
result Number; body $a;
|
||||
}
|
||||
quantity_kind collision "Global ID equals a scoped ID" id "28ff40b0-1b8f-4735-8536-5a6ab21b56cb" { dimension {}; algebra Linear; }
|
||||
calculation caller "Caller" id "00000000-0000-0000-0000-000000000021" {
|
||||
input a id "00000000-0000-0000-0000-000000000022" : Number;
|
||||
result Number; body @other(a: $a) + @other(a: 3);
|
||||
}
|
||||
"#;
|
||||
let mut budget = budget();
|
||||
let units = [unit(&source, 2, &mut budget)];
|
||||
let output = lower(&ordinary(ORDINARY_OA), &units, &budget).unwrap();
|
||||
let total = id("bd5b68e8-65fc-4e35-9071-a73061316a4b");
|
||||
let combine = id("fd7ce7ab-f789-40bc-b699-0c37f1b6902f");
|
||||
let labels: Vec<_> = output
|
||||
.occurrences
|
||||
.iter()
|
||||
.filter(|value| value.owner == total && value.role == Role::ArgumentLabel)
|
||||
.collect();
|
||||
assert_eq!(labels.len(), 4);
|
||||
assert_eq!(
|
||||
labels
|
||||
.iter()
|
||||
.map(|value| value.span.start)
|
||||
.collect::<BTreeSet<_>>()
|
||||
.len(),
|
||||
4
|
||||
);
|
||||
let sites: BTreeSet<_> = labels
|
||||
.iter()
|
||||
.map(|value| value.expression.unwrap())
|
||||
.collect();
|
||||
assert_eq!(sites.len(), 2);
|
||||
let paths: Vec<_> = sites
|
||||
.iter()
|
||||
.map(|site| output.expressions[*site].parent.unwrap().1)
|
||||
.collect();
|
||||
assert_eq!(paths, [Child::Left, Child::Right]);
|
||||
for label in labels {
|
||||
assert_eq!(label.field, Field::Base);
|
||||
assert!(
|
||||
matches!(label.target, Target::Parameter { calculation, .. } if calculation == combine)
|
||||
);
|
||||
assert!(matches!(
|
||||
&source[label.span.start..label.span.end],
|
||||
"a" | "b"
|
||||
));
|
||||
}
|
||||
let reused = a::ParameterId(id("28ff40b0-1b8f-4735-8536-5a6ab21b56cb"));
|
||||
let scopes: BTreeSet<_> = output
|
||||
.occurrences
|
||||
.iter()
|
||||
.filter_map(|occurrence| match occurrence.target {
|
||||
Target::Parameter {
|
||||
calculation,
|
||||
parameter,
|
||||
} if parameter == reused => Some(calculation),
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
assert_eq!(
|
||||
scopes,
|
||||
BTreeSet::from([combine, id("00000000-0000-0000-0000-000000000020")])
|
||||
);
|
||||
let caller = id("00000000-0000-0000-0000-000000000021");
|
||||
let use_in_caller = output
|
||||
.occurrences
|
||||
.iter()
|
||||
.find(|value| value.owner == caller && value.role == Role::ParameterUse)
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
use_in_caller.target,
|
||||
Target::Parameter {
|
||||
calculation: caller,
|
||||
parameter: a::ParameterId(id("00000000-0000-0000-0000-000000000022"))
|
||||
}
|
||||
);
|
||||
for site in &output.expressions {
|
||||
assert_eq!(site.file, 2);
|
||||
assert!(source.get(site.span.start..site.span.end).is_some());
|
||||
}
|
||||
admit(&merge(ordinary(ORDINARY_OA), output));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn missing_ids_require_stabilization_without_uuid_or_budget_churn() {
|
||||
for source in [
|
||||
r#"calculation pending "Pending" { result Number; body unbound; }"#,
|
||||
r#"calculation pending "Pending" id "00000000-0000-0000-0000-000000000040" { input value : Number; result Number; body $value; }"#,
|
||||
] {
|
||||
let mut budget = budget();
|
||||
let units = [unit(source, 3, &mut budget)];
|
||||
let usage = budget.usage;
|
||||
let skeleton = ordinary(ORDINARY_OA);
|
||||
let first = lower(&skeleton, &units, &budget).unwrap_err();
|
||||
assert_eq!(first, lower(&skeleton, &units, &budget).unwrap_err());
|
||||
assert!(first.error.message.contains("stabilization"));
|
||||
assert_eq!(budget.usage, usage);
|
||||
let declaration = &units[0].declarations[0];
|
||||
if declaration.header.identity.value.is_none() {
|
||||
assert!(declaration.header.identity.insertion.is_some());
|
||||
} else {
|
||||
let d::Body::Calculation { parameters, .. } = &declaration.body else {
|
||||
panic!("calculation")
|
||||
};
|
||||
assert!(parameters[0].identity.value.is_none());
|
||||
assert!(parameters[0].identity.insertion.is_some());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn duplicate_global_aliases_and_ids_fail_before_body_resolution() {
|
||||
let ordinary = ordinary(ORDINARY_OA);
|
||||
for (source, message) in [
|
||||
(
|
||||
OA.replace("quantity_kind duration", "quantity_kind respond"),
|
||||
"Duplicate global alias",
|
||||
),
|
||||
(
|
||||
OA.replace(
|
||||
"188b911c-5f8b-431c-9eea-2d41f3953767",
|
||||
"cabec6a1-7d5d-48f3-8d2d-a7fc8cf78f59",
|
||||
),
|
||||
"Duplicate global identity",
|
||||
),
|
||||
(format!("{OA}\n{OA}"), "Duplicate global"),
|
||||
] {
|
||||
let failed = failure(&source, &ordinary);
|
||||
assert_eq!(failed.file, Some(7));
|
||||
assert!(failed.error.message.contains(message), "{:?}", failed);
|
||||
assert!(!failed.error.message.contains("Unknown"));
|
||||
}
|
||||
let mut budget = budget();
|
||||
let units = [unit(OA, 3, &mut budget), unit(OA, 5, &mut budget)];
|
||||
let failed = lower(&ordinary, &units, &budget).unwrap_err();
|
||||
assert_eq!(failed.file, Some(5));
|
||||
assert!(failed.error.message.contains("Duplicate global identity"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn typed_reference_domains_unknown_names_and_parameter_scope_fail_at_tokens() {
|
||||
let skeleton = ordinary(ORDINARY_OA);
|
||||
for (old, new, token, message) in [
|
||||
(
|
||||
"subject @receive",
|
||||
"subject @second",
|
||||
"second",
|
||||
"Wrong reference domain",
|
||||
),
|
||||
(
|
||||
"Quantity(@duration)",
|
||||
"Quantity(@second)",
|
||||
"second",
|
||||
"Wrong reference domain",
|
||||
),
|
||||
(
|
||||
"display_unit @second",
|
||||
"display_unit @duration",
|
||||
"duration",
|
||||
"Wrong reference domain",
|
||||
),
|
||||
(
|
||||
"750 [@millisecond]",
|
||||
"750 [@duration]",
|
||||
"duration",
|
||||
"Wrong reference domain",
|
||||
),
|
||||
(
|
||||
"base 1 [@second]",
|
||||
"base @respond",
|
||||
"respond",
|
||||
"Wrong reference domain",
|
||||
),
|
||||
(
|
||||
"@combine(a:",
|
||||
"@second(a:",
|
||||
"second",
|
||||
"Wrong reference domain",
|
||||
),
|
||||
(
|
||||
"@combine(a:",
|
||||
"@combine(unknown:",
|
||||
"unknown",
|
||||
"Unknown argument",
|
||||
),
|
||||
(
|
||||
"body $a + $b",
|
||||
"body $outside + $b",
|
||||
"outside",
|
||||
"Unknown parameter",
|
||||
),
|
||||
(
|
||||
"base 1 [@second]",
|
||||
"base $a",
|
||||
"a",
|
||||
"only valid in its calculation",
|
||||
),
|
||||
(
|
||||
"subject @receive",
|
||||
"subject @missing",
|
||||
"missing",
|
||||
"Unknown global",
|
||||
),
|
||||
(
|
||||
"documented_constraint none",
|
||||
"documented_constraint @respond",
|
||||
"respond",
|
||||
"Wrong reference domain",
|
||||
),
|
||||
(
|
||||
"@receive_time = unbound",
|
||||
"@second = unbound",
|
||||
"second",
|
||||
"Wrong reference domain",
|
||||
),
|
||||
] {
|
||||
let source = OA.replace(old, new);
|
||||
assert_ne!(source, OA, "mutation {old}");
|
||||
let failed = failure(&source, &skeleton);
|
||||
assert!(
|
||||
failed.error.message.contains(message),
|
||||
"{new}: {:?}",
|
||||
failed
|
||||
);
|
||||
assert_eq!(
|
||||
&source[failed.error.span.start..failed.error.span.end],
|
||||
token
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ordinary_non_element_categories_are_collected_and_never_property_fallbacks() {
|
||||
let mut skeleton = ordinary(ORDINARY_OA);
|
||||
let respond = by_alias(&skeleton, "respond");
|
||||
let receive = by_alias(&skeleton, "receive");
|
||||
let relation = Id::from_u128(100);
|
||||
skeleton.relations.insert(
|
||||
relation,
|
||||
crate::Relation {
|
||||
id: relation,
|
||||
alias: "link".into(),
|
||||
name: "Link".into(),
|
||||
description: String::new(),
|
||||
body: crate::RelationBody::new(
|
||||
crate::RelationKind::FunctionalExchange,
|
||||
respond,
|
||||
receive,
|
||||
),
|
||||
},
|
||||
);
|
||||
let diagram = skeleton.ensure_diagram(Layer::Oa);
|
||||
skeleton.diagrams.get_mut(&diagram).unwrap().alias = "view".into();
|
||||
let node = skeleton.place(diagram, respond, crate::Position { x: 0., y: 0. });
|
||||
skeleton
|
||||
.diagrams
|
||||
.get_mut(&diagram)
|
||||
.unwrap()
|
||||
.nodes
|
||||
.get_mut(&node)
|
||||
.unwrap()
|
||||
.alias = "placement".into();
|
||||
let artifact = Id::from_u128(101);
|
||||
skeleton.artifact_links.insert(
|
||||
artifact,
|
||||
crate::ArtifactLink {
|
||||
id: artifact,
|
||||
alias: "document".into(),
|
||||
name: "Document".into(),
|
||||
description: String::new(),
|
||||
owner: respond,
|
||||
relation: crate::ArtifactRelation::References,
|
||||
uri: "urn:test".into(),
|
||||
revision: None,
|
||||
fragment: None,
|
||||
},
|
||||
);
|
||||
let trace = Id::from_u128(102);
|
||||
skeleton.traces.insert(
|
||||
trace,
|
||||
crate::Trace {
|
||||
id: trace,
|
||||
alias: "mapping".into(),
|
||||
name: "Mapping".into(),
|
||||
description: String::new(),
|
||||
oa: respond,
|
||||
sa: receive,
|
||||
kind: crate::TraceKind::Manual,
|
||||
baseline: None,
|
||||
},
|
||||
);
|
||||
// Resolution classification is independent of whole-model admission; the
|
||||
// synthetic trace is deliberately not asserted to be a valid OA/SA trace.
|
||||
let budget = budget();
|
||||
let mut tables = Tables::default();
|
||||
tables.ordinary(&skeleton, &budget).unwrap();
|
||||
for (alias, category) in [
|
||||
("response_budget", Category::Project),
|
||||
("link", Category::Relation),
|
||||
("view", Category::Diagram),
|
||||
("placement", Category::Node),
|
||||
("document", Category::Artifact),
|
||||
("mapping", Category::Trace),
|
||||
] {
|
||||
assert_eq!(tables.aliases[alias].category, category);
|
||||
let failed = failure(
|
||||
&OA.replace("base 1 [@second]", &format!("base @{alias}")),
|
||||
&skeleton,
|
||||
);
|
||||
assert!(
|
||||
failed.error.message.contains("Wrong reference domain"),
|
||||
"{:?}",
|
||||
failed
|
||||
);
|
||||
}
|
||||
let source = OA.replace("subject @receive", "subject @link");
|
||||
let mut budget = self::budget();
|
||||
let units = [unit(&source, 1, &mut budget)];
|
||||
let output = lower(&skeleton, &units, &budget).unwrap();
|
||||
let property = output
|
||||
.elements
|
||||
.values()
|
||||
.find(|value| value.alias == "receive_time")
|
||||
.unwrap();
|
||||
assert!(
|
||||
matches!(property.body.shared(), Some(SharedBody::EngineeringProperty { subject: a::AnalysisSubject::Relation(value), .. }) if *value == relation)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn structural_lowering_defers_type_purity_layer_and_argument_sets_to_admission() {
|
||||
for (old, new) in [
|
||||
("base 750 [@millisecond]", "base true"),
|
||||
(
|
||||
"base 750 [@millisecond]",
|
||||
"base as_kind(@duration, 1 [@second])",
|
||||
),
|
||||
("body $a + $b", "body @receive_time"),
|
||||
("a: @receive_time, b: @dispatch_time", "a: @receive_time"),
|
||||
("oa_property receive_time", "sa_property receive_time"),
|
||||
("base 1 [@second]", "base @dispatch_time"),
|
||||
] {
|
||||
let source = OA.replace(old, new);
|
||||
let mut budget = budget();
|
||||
let units = [unit(&source, 1, &mut budget)];
|
||||
let output = lower(&ordinary(ORDINARY_OA), &units, &budget).unwrap();
|
||||
let project = merge(ordinary(ORDINARY_OA), output);
|
||||
assert!(
|
||||
a::admit(&project, a::AdmissionLimits::REFERENCE).is_err(),
|
||||
"{new}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lowering_phase_bounds_count_ordinary_globals_and_scoped_parameters_together() {
|
||||
let ordinary = oracle::project(Layer::Oa);
|
||||
for (maximum, passes) in [(0, false), (16, false), (17, true)] {
|
||||
let mut limits = Limits::source8(ParseLimits::UNLIMITED);
|
||||
limits.entries = maximum;
|
||||
let budget = Budget::new(limits).unwrap();
|
||||
let result = lower(&ordinary, &[], &budget);
|
||||
assert_eq!(result.is_ok(), passes, "entry bound {maximum}");
|
||||
if let Err(failure) = result {
|
||||
assert!(failure.error.message.contains("lowering entry limit"));
|
||||
assert_eq!(failure.file, None);
|
||||
}
|
||||
assert_eq!(budget.usage, budget::Usage::default());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn affine_kinds_optional_fields_list_signatures_and_unused_unbound_definitions_survive() {
|
||||
let source = r#"
|
||||
unit celsius "Celsius" id "00000000-0000-0000-0000-000000000061" {
|
||||
kind @point; scale 1; offset ratio(27315, 100); symbol "°C";
|
||||
}
|
||||
quantity_kind point "Temperature point" id "00000000-0000-0000-0000-000000000062" {
|
||||
dimension { temperature 1; }; algebra Affine(@interval);
|
||||
}
|
||||
quantity_kind interval "Temperature interval" id "00000000-0000-0000-0000-000000000063" {
|
||||
dimension { temperature 1; }; algebra Linear;
|
||||
}
|
||||
calculation unused "Unused list calculation" id "00000000-0000-0000-0000-000000000064" {
|
||||
input xs id "00000000-0000-0000-0000-000000000065" : List(Quantity(@interval));
|
||||
result List(Quantity(@interval)); body unbound; description "保留";
|
||||
}
|
||||
calculation empty "Empty calculation" id "00000000-0000-0000-0000-000000000066" {
|
||||
result Boolean; body unbound;
|
||||
}
|
||||
oa_property ambient "Ambient temperature" id "00000000-0000-0000-0000-000000000067" {
|
||||
subject @respond; type Quantity(@point); display_unit none; base 0 [@celsius]; parent none;
|
||||
}
|
||||
oa_check documented "Documented check" id "00000000-0000-0000-0000-000000000068" {
|
||||
subject @respond; documented_constraint @requirement; predicate unbound;
|
||||
}
|
||||
oa_analysis changed "Changed temperature" id "00000000-0000-0000-0000-000000000069" {
|
||||
subject @respond; base ModelBaseline; overrides { @ambient = unbound; };
|
||||
}
|
||||
"#;
|
||||
let mut skeleton = ordinary(ORDINARY_OA);
|
||||
let requirement = Id::from_u128(70);
|
||||
skeleton.elements.insert(
|
||||
requirement,
|
||||
Element {
|
||||
id: requirement,
|
||||
alias: "requirement".into(),
|
||||
name: "Requirement".into(),
|
||||
description: String::new(),
|
||||
parent: None,
|
||||
body: ElementBody::shared_in(
|
||||
Layer::Oa,
|
||||
SharedBody::Constraint {
|
||||
expression: String::new(),
|
||||
constrained: Vec::new(),
|
||||
},
|
||||
),
|
||||
},
|
||||
);
|
||||
let mut budget = budget();
|
||||
let units = [unit(source, 8, &mut budget)];
|
||||
let output = lower(&skeleton, &units, &budget).unwrap();
|
||||
assert_eq!(output.definitions.len(), 5);
|
||||
let point = id("00000000-0000-0000-0000-000000000062");
|
||||
let interval = id("00000000-0000-0000-0000-000000000063");
|
||||
let a::DefinitionBody::QuantityKind(kind) = &output.definitions[&point].body else {
|
||||
panic!("quantity kind")
|
||||
};
|
||||
assert_eq!(
|
||||
kind.algebra,
|
||||
a::QuantityAlgebra::Affine {
|
||||
difference: a::DefinitionRef::Local(interval)
|
||||
}
|
||||
);
|
||||
let unused = &output.definitions[&id("00000000-0000-0000-0000-000000000064")];
|
||||
assert_eq!(unused.description, "保留");
|
||||
let a::DefinitionBody::Calculation(calculation) = &unused.body else {
|
||||
panic!("calculation")
|
||||
};
|
||||
assert_eq!(calculation.body, a::Binding::Unbound);
|
||||
assert_eq!(
|
||||
calculation.parameters[0].value_type,
|
||||
a::AnalysisType::List(a::ScalarType::Quantity(a::DefinitionRef::Local(interval)))
|
||||
);
|
||||
assert_eq!(calculation.result, calculation.parameters[0].value_type);
|
||||
assert!(
|
||||
output
|
||||
.occurrences
|
||||
.iter()
|
||||
.any(|occurrence| occurrence.field == Field::DocumentedConstraint
|
||||
&& occurrence.target == Target::Global(requirement))
|
||||
);
|
||||
let override_id = id("00000000-0000-0000-0000-000000000067");
|
||||
assert!(output.occurrences.iter().any(|occurrence| occurrence.field
|
||||
== Field::Override(override_id)
|
||||
&& occurrence.role == Role::OverrideTarget));
|
||||
assert!(
|
||||
output
|
||||
.occurrences
|
||||
.iter()
|
||||
.any(|occurrence| occurrence.owner == point
|
||||
&& occurrence.field == Field::Algebra
|
||||
&& occurrence.target == Target::Global(interval))
|
||||
);
|
||||
admit(&merge(skeleton, output));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn duplicate_file_keys_and_exhausted_shared_budget_cannot_enter_lowering() {
|
||||
let mut budget = budget();
|
||||
let units = [unit("", 3, &mut budget), unit("", 3, &mut budget)];
|
||||
let failed = lower(&ordinary(ORDINARY_OA), &units, &budget).unwrap_err();
|
||||
assert_eq!(failed.file, Some(3));
|
||||
assert!(failed.error.message.contains("Duplicate source file"));
|
||||
let failure = budget
|
||||
.bytes(usize::MAX, Span { start: 5, end: 6 })
|
||||
.unwrap_err();
|
||||
let failed = lower(&ordinary(ORDINARY_OA), &[], &budget).unwrap_err();
|
||||
assert_eq!(failed.error, failure);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn iterative_lowering_preserves_128_deep_and_1024_wide_accepted_expressions() {
|
||||
let deep = format!("{}1{}", "abs(".repeat(127), ")".repeat(127));
|
||||
let wide = std::iter::repeat_n("1", 1024)
|
||||
.collect::<Vec<_>>()
|
||||
.join(", ");
|
||||
let source = format!(
|
||||
r#"
|
||||
calculation deep "Deep" id "00000000-0000-0000-0000-000000000081" {{ result Number; body {deep}; }}
|
||||
calculation wide "Wide" id "00000000-0000-0000-0000-000000000082" {{ result List(Number); body [{wide}]; }}
|
||||
"#
|
||||
);
|
||||
let mut budget = budget();
|
||||
let units = [unit(&source, 1, &mut budget)];
|
||||
let usage = budget.usage;
|
||||
let output = lower(&ordinary(ORDINARY_OA), &units, &budget).unwrap();
|
||||
assert_eq!(output.expressions.len(), 128 + 1025);
|
||||
let a::DefinitionBody::Calculation(deep) = &output.definitions[&Id::from_u128(0x81)].body
|
||||
else {
|
||||
panic!("deep calculation")
|
||||
};
|
||||
let a::Binding::Expression(root) = &deep.body else {
|
||||
panic!("deep expression")
|
||||
};
|
||||
let mut current = root;
|
||||
let mut depth = 1;
|
||||
while let a::Expr::Unary { operand, .. } = current {
|
||||
depth += 1;
|
||||
current = operand;
|
||||
}
|
||||
assert_eq!(depth, 128);
|
||||
assert_eq!(current, &number(1));
|
||||
let a::DefinitionBody::Calculation(wide) = &output.definitions[&Id::from_u128(0x82)].body
|
||||
else {
|
||||
panic!("wide calculation")
|
||||
};
|
||||
let a::Binding::Expression(a::Expr::List(values)) = &wide.body else {
|
||||
panic!("wide list")
|
||||
};
|
||||
assert_eq!(values.len(), 1024);
|
||||
assert!(values.iter().all(|value| *value == number(1)));
|
||||
assert_eq!(budget.usage, usage);
|
||||
admit(&merge(ordinary(ORDINARY_OA), output));
|
||||
}
|
||||
@@ -0,0 +1,406 @@
|
||||
//! Private syntax-only complete-bundle witness. No model admission or edit authority.
|
||||
//!
|
||||
//! One scan charges original bytes and raw tokens (including trivia). Typed
|
||||
//! syntax keeps its existing entry/reference/numeric charges. Ordinary syntax
|
||||
//! charges one entry per project/declaration/include/description, field, and
|
||||
//! value before allocation; array values already account for their list slots.
|
||||
//! These private storage ceilings are independent of caller model record counts.
|
||||
//! Ordinary references consume value storage, not ordered-model-step allowance.
|
||||
//! Typed reference occurrences retain the caller max_step_references ceiling.
|
||||
//! Only declaration graph/record counts are known here; semantic nested-model
|
||||
//! records and ordinary ordered steps still require the later complete admission.
|
||||
//! Metadata phase slots aggregate across all files: retained token-end indices,
|
||||
//! value-end entries, projected value/field/header/declaration positions, lexical
|
||||
//! owner slots and the file table. Checks do not recharge syntax or latch errors;
|
||||
//! every failure must return immediately. Tokens themselves use the token bound.
|
||||
//! This deliberately bounded staging policy is not calibrated public source8.
|
||||
|
||||
use super::{
|
||||
budget::{Budget, Limits},
|
||||
cursor::Cursor,
|
||||
declarations, lex,
|
||||
};
|
||||
use crate::Id;
|
||||
use crate::language::{
|
||||
self, Ast, EditDeclaration, Error, Lexeme, ParseLimits, Parser, SourceUnit, Span, TokenClass,
|
||||
};
|
||||
use crate::source_project::{ProjectLimits, SourceBundle, SourceDiagnostic, traversal::Traversal};
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
struct ModelCounts {
|
||||
limits: ProjectLimits,
|
||||
graph: usize,
|
||||
records: usize,
|
||||
includes: usize,
|
||||
}
|
||||
|
||||
pub(super) struct ParsedMixedSyntax<'s> {
|
||||
bundle: &'s SourceBundle,
|
||||
// Preserve caller policy for the later semantic pass. Syntax storage uses
|
||||
// separate ceilings and cannot stand in for these graph/record/step limits.
|
||||
limits: ProjectLimits,
|
||||
files: Vec<FileSyntax<'s>>,
|
||||
budget: Budget,
|
||||
// Includes the conservative dropped value-end subtotal. The semantic
|
||||
// phase adds syntax entries to this once, not tokens/positions again.
|
||||
metadata: usize,
|
||||
}
|
||||
|
||||
struct FileSyntax<'s> {
|
||||
path: &'s str,
|
||||
source: &'s str,
|
||||
tokens: Vec<lex::Token>,
|
||||
ordinary: SourceUnit,
|
||||
typed: Vec<declarations::Declaration>,
|
||||
positions: Vec<(Id, EditDeclaration)>,
|
||||
// A lexical owner is an occurrence index, not only a possibly repeated UUID.
|
||||
lexical_owners: Vec<Option<usize>>,
|
||||
}
|
||||
|
||||
// Only Parser borrows this state; the stored witness has no self-reference.
|
||||
pub(in crate::language) struct State<'a> {
|
||||
source: &'a str,
|
||||
tokens: &'a [lex::Token],
|
||||
budget: &'a mut Budget,
|
||||
model: &'a mut ModelCounts,
|
||||
typed: Vec<declarations::Declaration>,
|
||||
pub(in crate::language) value_ends: BTreeMap<usize, usize>,
|
||||
pub(in crate::language) lexical_owners: Vec<Option<usize>>,
|
||||
}
|
||||
|
||||
fn ordinary_error(error: super::Error) -> Error {
|
||||
Error {
|
||||
code: "invalid_source",
|
||||
offset: error.span.start,
|
||||
message: error.message,
|
||||
}
|
||||
}
|
||||
|
||||
fn lexeme(token: lex::Token) -> Lexeme {
|
||||
Lexeme {
|
||||
class: match token.class {
|
||||
lex::Class::Word => TokenClass::Identifier,
|
||||
lex::Class::Number => TokenClass::Number,
|
||||
lex::Class::String => TokenClass::String,
|
||||
lex::Class::Punctuation => TokenClass::Punctuation,
|
||||
},
|
||||
span: token.span,
|
||||
}
|
||||
}
|
||||
|
||||
impl State<'_> {
|
||||
pub(in crate::language) fn token(&self, at: usize) -> Option<Lexeme> {
|
||||
self.tokens.get(at).copied().map(lexeme)
|
||||
}
|
||||
pub(in crate::language) fn entry(&mut self, at: Span) -> Result<(), Error> {
|
||||
self.budget.entry(at).map_err(ordinary_error)
|
||||
}
|
||||
pub(in crate::language) fn record(&mut self, graph: bool, at: Span) -> Result<(), Error> {
|
||||
let records = self.model.records.checked_add(1);
|
||||
let graph = self.model.graph.checked_add(usize::from(graph));
|
||||
let (Some(records), Some(graph)) = (records, graph) else {
|
||||
return Err(Error {
|
||||
code: "model_limit",
|
||||
offset: at.start,
|
||||
message: "Declaration count overflow.".into(),
|
||||
});
|
||||
};
|
||||
self.model
|
||||
.limits
|
||||
.model
|
||||
.check_counts(graph, records, 0)
|
||||
.map_err(|message| Error {
|
||||
code: "model_limit",
|
||||
offset: at.start,
|
||||
message,
|
||||
})?;
|
||||
self.model.records = records;
|
||||
self.model.graph = graph;
|
||||
Ok(())
|
||||
}
|
||||
pub(in crate::language) fn include(&mut self, at: Span) -> Result<(), Error> {
|
||||
if self.model.includes >= self.model.limits.max_include_edges {
|
||||
return Err(Error {
|
||||
code: "project_limit",
|
||||
offset: at.start,
|
||||
message: format!(
|
||||
"Include graph exceeds {} edges.",
|
||||
self.model.limits.max_include_edges
|
||||
),
|
||||
});
|
||||
}
|
||||
self.model.includes += 1;
|
||||
Ok(())
|
||||
}
|
||||
pub(in crate::language) fn ordinary_number(
|
||||
&self,
|
||||
at: &mut usize,
|
||||
) -> Result<serde_json::Value, Error> {
|
||||
let first = self.tokens[*at];
|
||||
let mut end = first.span.end;
|
||||
let mut after = *at + 1;
|
||||
// Match the old greedy numeric alphabet only across byte-adjacent raw
|
||||
// tokens. This is consumption of the shared stream, not another scan.
|
||||
while let Some(next) = self.tokens.get(after) {
|
||||
if next.span.start != end
|
||||
|| !self.source[next.span.start..next.span.end]
|
||||
.bytes()
|
||||
.all(|byte| byte.is_ascii_alphanumeric() || b"_.+-".contains(&byte))
|
||||
{
|
||||
break;
|
||||
}
|
||||
end = next.span.end;
|
||||
after += 1;
|
||||
}
|
||||
let value: serde_json::Number = serde_json::from_str(&self.source[first.span.start..end])
|
||||
.map_err(|_| Error {
|
||||
code: "invalid_source",
|
||||
offset: first.span.start,
|
||||
message: "Expected a byte-adjacent finite JSON decimal number.".into(),
|
||||
})?;
|
||||
*at = after;
|
||||
Ok(serde_json::Value::Number(value))
|
||||
}
|
||||
pub(in crate::language) fn typed_header(&self, at: usize, root: bool) -> bool {
|
||||
let Some(token) = self.tokens.get(at) else {
|
||||
return false;
|
||||
};
|
||||
if declarations::declaration_kind(&self.source[token.span.start..token.span.end]).is_none()
|
||||
{
|
||||
return false;
|
||||
}
|
||||
// A generic field named `unit` remains an ordinary field. A declaration
|
||||
// header has an alias and display-name token; only that shape is nested.
|
||||
root || (self
|
||||
.tokens
|
||||
.get(at + 1)
|
||||
.is_some_and(|t| t.class == lex::Class::Word)
|
||||
&& self
|
||||
.tokens
|
||||
.get(at + 2)
|
||||
.is_some_and(|t| t.class == lex::Class::String))
|
||||
}
|
||||
pub(in crate::language) fn parse_typed(
|
||||
&mut self,
|
||||
at: &mut usize,
|
||||
owner: Option<Id>,
|
||||
) -> Result<(), Error> {
|
||||
// Transfer the one active position into the typed consumer and back;
|
||||
// neither consumer scans, clones a stream, nor runs concurrently.
|
||||
self.record(true, self.tokens[*at].span)?;
|
||||
let mut cursor = Cursor::new(self.source, self.tokens, self.budget);
|
||||
cursor.cursor = *at;
|
||||
let result = declarations::parse(&mut cursor, 8, owner);
|
||||
*at = cursor.cursor;
|
||||
let declaration = result.map_err(ordinary_error)?;
|
||||
let missing = declaration.header.identity.value.is_none()
|
||||
|| matches!(&declaration.body, declarations::Body::Calculation { parameters, .. }
|
||||
if parameters.iter().any(|p| p.identity.value.is_none()));
|
||||
if missing {
|
||||
return Err(Error {
|
||||
code: "invalid_source",
|
||||
offset: declaration.span.start,
|
||||
message: "Private mixed syntax requires explicit IDs.".into(),
|
||||
});
|
||||
}
|
||||
self.typed.push(declaration);
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
pub(in crate::language) fn long_analysis_word(word: &str) -> bool {
|
||||
matches!(
|
||||
word,
|
||||
"oa_engineering_property"
|
||||
| "sa_engineering_property"
|
||||
| "oa_analysis_check"
|
||||
| "sa_analysis_check"
|
||||
| "oa_analysis_case"
|
||||
| "sa_analysis_case"
|
||||
)
|
||||
}
|
||||
|
||||
pub(super) fn parse(
|
||||
bundle: &SourceBundle,
|
||||
limits: ProjectLimits,
|
||||
) -> Result<ParsedMixedSyntax<'_>, Vec<SourceDiagnostic>> {
|
||||
let profile = Limits::source8(ParseLimits {
|
||||
// Storage is not the caller's final model record/ordered-step accounting.
|
||||
max_source_bytes: limits.model.max_source_bytes,
|
||||
max_step_references: limits.model.max_step_references,
|
||||
..ParseLimits::UNLIMITED
|
||||
});
|
||||
parse_with_profile(bundle, limits, profile)
|
||||
}
|
||||
|
||||
fn located(path: &str, source: &str, error: Error) -> Vec<SourceDiagnostic> {
|
||||
vec![SourceDiagnostic {
|
||||
path: path.into(),
|
||||
diagnostic: language::diagnostic(source, error),
|
||||
related: Vec::new(),
|
||||
}]
|
||||
}
|
||||
|
||||
fn parse_with_profile(
|
||||
bundle: &SourceBundle,
|
||||
limits: ProjectLimits,
|
||||
profile: Limits,
|
||||
) -> Result<ParsedMixedSyntax<'_>, Vec<SourceDiagnostic>> {
|
||||
let entry_source = bundle.files.get(&bundle.entry).map_or("", String::as_str);
|
||||
let at_entry = |error| located(&bundle.entry, entry_source, ordinary_error(error));
|
||||
let maximum = Limits::source8(ParseLimits {
|
||||
max_source_bytes: limits.model.max_source_bytes,
|
||||
max_step_references: limits.model.max_step_references,
|
||||
..ParseLimits::UNLIMITED
|
||||
});
|
||||
if profile.bytes > maximum.bytes
|
||||
|| profile.tokens > maximum.tokens
|
||||
|| profile.entries > maximum.entries
|
||||
|| profile.references > maximum.references
|
||||
|| profile.frames > maximum.frames
|
||||
|| profile.numeric_units > maximum.numeric_units
|
||||
{
|
||||
return Err(at_entry(super::error(
|
||||
Span::default(),
|
||||
"Mixed test profile may only tighten inherited limits.",
|
||||
)));
|
||||
}
|
||||
let mut budget = Budget::new(profile).map_err(at_entry)?;
|
||||
let bytes = bundle
|
||||
.files
|
||||
.values()
|
||||
.try_fold(0usize, |n, s| n.checked_add(s.len()))
|
||||
.ok_or_else(|| at_entry(super::error(Span::default(), "Source size overflow.")))?;
|
||||
budget
|
||||
.index_bytes(bytes, Span::default())
|
||||
.map_err(at_entry)?;
|
||||
let mut metadata = bundle.files.len();
|
||||
budget
|
||||
.lowering_entries(metadata, Span::default())
|
||||
.map_err(at_entry)?;
|
||||
// Tighter private byte/file-slot limits precede folded-path table and
|
||||
// traversal allocations. Public Traversal's own validation order is intact.
|
||||
let mut traversal = Traversal::new(bundle, limits)?;
|
||||
let mut parsed = BTreeMap::new();
|
||||
let mut model = ModelCounts {
|
||||
limits,
|
||||
graph: 0,
|
||||
records: 0,
|
||||
includes: 0,
|
||||
};
|
||||
while let Some(path) = traversal.next()? {
|
||||
let (path, source) = bundle
|
||||
.files
|
||||
.get_key_value(&path)
|
||||
.expect("traversal checked source");
|
||||
let failure = |error| located(path, source, ordinary_error(error));
|
||||
let tokens = lex::tokens(source, &mut budget).map_err(failure)?;
|
||||
let mut parser = Parser {
|
||||
source,
|
||||
tokens: Vec::new(),
|
||||
cursor: 0,
|
||||
value_depth: 0,
|
||||
limits: limits.model,
|
||||
mixed: Some(State {
|
||||
source,
|
||||
tokens: &tokens,
|
||||
budget: &mut budget,
|
||||
model: &mut model,
|
||||
typed: Vec::new(),
|
||||
value_ends: BTreeMap::new(),
|
||||
lexical_owners: Vec::new(),
|
||||
}),
|
||||
};
|
||||
let ordinary = parser
|
||||
.unit(path == &bundle.entry, true)
|
||||
.map_err(|e| located(path, source, e))?;
|
||||
let state = parser.mixed.take().expect("private parser state");
|
||||
drop(parser);
|
||||
// Projected ordinary AST nodes/fields are bounded before constructing a
|
||||
// second position representation. Count references as slots, not syntax.
|
||||
let projection_slots = ordinary_position_slots(&ordinary);
|
||||
metadata = metadata
|
||||
.checked_add(tokens.len())
|
||||
.and_then(|n| n.checked_add(state.value_ends.len()))
|
||||
.and_then(|n| n.checked_add(projection_slots))
|
||||
.and_then(|n| n.checked_add(state.lexical_owners.len()))
|
||||
.ok_or_else(|| failure(super::error(Span::default(), "Metadata size overflow.")))?;
|
||||
state
|
||||
.budget
|
||||
.lowering_entries(metadata, Span::default())
|
||||
.map_err(failure)?;
|
||||
let positions = language::edit_positions_from_tokens(
|
||||
source,
|
||||
&ordinary,
|
||||
|at| lexeme(tokens[at]),
|
||||
tokens.len(),
|
||||
Some(&state.value_ends),
|
||||
)
|
||||
.map_err(|e| {
|
||||
vec![SourceDiagnostic {
|
||||
path: path.clone(),
|
||||
diagnostic: *e,
|
||||
related: Vec::new(),
|
||||
}]
|
||||
})?;
|
||||
for (raw, span) in &ordinary.includes {
|
||||
traversal.include(path, raw, *span)?;
|
||||
}
|
||||
traversal.finish_file(path.clone());
|
||||
let State {
|
||||
typed,
|
||||
lexical_owners,
|
||||
..
|
||||
} = state;
|
||||
parsed.insert(
|
||||
path.as_str(),
|
||||
FileSyntax {
|
||||
path,
|
||||
source,
|
||||
tokens,
|
||||
ordinary,
|
||||
typed,
|
||||
positions,
|
||||
lexical_owners,
|
||||
},
|
||||
);
|
||||
}
|
||||
traversal.finish()?;
|
||||
budget.active().map_err(at_entry)?;
|
||||
Ok(ParsedMixedSyntax {
|
||||
bundle,
|
||||
limits,
|
||||
files: parsed.into_values().collect(),
|
||||
budget,
|
||||
metadata,
|
||||
})
|
||||
}
|
||||
|
||||
fn ordinary_position_slots(unit: &SourceUnit) -> usize {
|
||||
// Iterative accounting avoids adding a second recursive walk before the
|
||||
// already depth-bounded position projection. Each reference is one value.
|
||||
let mut slots = 0usize;
|
||||
let mut stack = Vec::new();
|
||||
for declaration in &unit.declarations {
|
||||
slots = slots.saturating_add(7); // declaration/body + at most five header roles
|
||||
slots = slots.saturating_add(declaration.fields.len());
|
||||
stack.extend(declaration.fields.values());
|
||||
}
|
||||
while let Some(value) = stack.pop() {
|
||||
slots = slots.saturating_add(1);
|
||||
match value {
|
||||
Ast::Array(items, _) => stack.extend(items),
|
||||
Ast::Object(fields, _) => {
|
||||
slots = slots.saturating_add(fields.len());
|
||||
stack.extend(fields.values());
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
slots
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
|
||||
pub(super) mod project;
|
||||
@@ -0,0 +1,639 @@
|
||||
//! Private complete-Project admission from the actual complete syntax witness.
|
||||
//! No Index, update authority, public source8 dispatch or replacement policy.
|
||||
use super::super::{
|
||||
Binding, Budget, Error as TypedError, Expression, ExpressionKind, Reference, Span,
|
||||
declarations as d, error, lower,
|
||||
};
|
||||
use super::{FileSyntax, ParsedMixedSyntax};
|
||||
use crate::language::{Ast, DeclKind};
|
||||
use crate::source_project::{SourceDiagnostic, SourceLocation};
|
||||
use crate::{Id, Kind, Project, RelationKind, analysis, language, validation};
|
||||
use std::collections::BTreeMap;
|
||||
mod accounting;
|
||||
use accounting::{Ledger, Slots, add};
|
||||
|
||||
/// Read-only authority: every component originates in the consumed syntax.
|
||||
pub(in crate::language::analysis_source) struct ResolvedMixedProject<'s> {
|
||||
syntax: ParsedMixedSyntax<'s>,
|
||||
project: Project,
|
||||
warnings: Vec<SourceDiagnostic>,
|
||||
static_limits: analysis::AdmissionLimits,
|
||||
static_usage: analysis::AdmissionUsage,
|
||||
expressions: Vec<lower::ExpressionSite>,
|
||||
occurrences: Vec<lower::Occurrence>,
|
||||
storage: Ledger,
|
||||
}
|
||||
impl ResolvedMixedProject<'_> {
|
||||
pub fn project(&self) -> &Project {
|
||||
&self.project
|
||||
}
|
||||
pub fn warnings(&self) -> &[SourceDiagnostic] {
|
||||
&self.warnings
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub(in crate::language::analysis_source) struct Failure {
|
||||
pub diagnostics: Vec<SourceDiagnostic>,
|
||||
}
|
||||
impl Failure {
|
||||
// Rejection transport is not retained in a successful witness. In particular
|
||||
// a storage refusal needs a small diagnostic even when its allowance is zero.
|
||||
fn typed(syntax: &ParsedMixedSyntax<'_>, file: Option<usize>, e: TypedError) -> Self {
|
||||
let mut failure = Self::ordinary(
|
||||
syntax,
|
||||
file,
|
||||
language::Error {
|
||||
code: "invalid_source",
|
||||
offset: e.span.start,
|
||||
message: e.message,
|
||||
},
|
||||
);
|
||||
failure.diagnostics[0].diagnostic.span = e.span;
|
||||
failure
|
||||
}
|
||||
fn ordinary(syntax: &ParsedMixedSyntax<'_>, file: Option<usize>, e: language::Error) -> Self {
|
||||
let file = file.unwrap_or_else(|| entry(syntax));
|
||||
let unit = &syntax.files[file];
|
||||
Self {
|
||||
diagnostics: super::located(unit.path, unit.source, e),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
enum OwnerKind {
|
||||
Project,
|
||||
Ordinary(usize),
|
||||
Typed(usize),
|
||||
}
|
||||
#[derive(Clone, Copy)]
|
||||
struct Owner {
|
||||
file: usize,
|
||||
kind: OwnerKind,
|
||||
span: Span,
|
||||
}
|
||||
struct Catalog {
|
||||
tables: lower::Tables,
|
||||
aliases: BTreeMap<String, Id>,
|
||||
owners: BTreeMap<Id, Owner>,
|
||||
tables_storage: Slots,
|
||||
aliases_storage: Slots,
|
||||
owners_storage: Slots,
|
||||
}
|
||||
fn entry(syntax: &ParsedMixedSyntax<'_>) -> usize {
|
||||
syntax
|
||||
.files
|
||||
.iter()
|
||||
.position(|f| f.path == syntax.bundle.entry)
|
||||
.expect("complete entry")
|
||||
}
|
||||
fn category(kind: DeclKind) -> lower::Category {
|
||||
match kind {
|
||||
DeclKind::Element(kind, layer) => lower::Category::Element(kind, layer),
|
||||
DeclKind::Relation(_) => lower::Category::Relation,
|
||||
DeclKind::Diagram => lower::Category::Diagram,
|
||||
DeclKind::Node => lower::Category::Node,
|
||||
DeclKind::Artifact => lower::Category::Artifact,
|
||||
DeclKind::Trace => lower::Category::Trace,
|
||||
}
|
||||
}
|
||||
impl Catalog {
|
||||
fn insert(
|
||||
&mut self,
|
||||
syntax: &ParsedMixedSyntax<'_>,
|
||||
ledger: &mut Ledger,
|
||||
id: Id,
|
||||
alias: &str,
|
||||
owner: Owner,
|
||||
) -> Result<(), Failure> {
|
||||
// Alias first, even when both aliases and IDs collide. Owner is an
|
||||
// occurrence position, never a lookup through the rejected UUID.
|
||||
let prior = self
|
||||
.aliases
|
||||
.get(alias)
|
||||
.map(|id| ("alias", self.owners[id]))
|
||||
.or_else(|| self.owners.get(&id).map(|o| ("identity", *o)));
|
||||
if let Some((domain, prior)) = prior {
|
||||
let mut failure = Failure::typed(
|
||||
syntax,
|
||||
Some(owner.file),
|
||||
error(owner.span, format!("Duplicate global {domain}.")),
|
||||
);
|
||||
failure.diagnostics[0].related.push(SourceLocation {
|
||||
path: syntax.files[prior.file].path.into(),
|
||||
span: prior.span,
|
||||
});
|
||||
return Err(failure);
|
||||
}
|
||||
let alias_slots = Slots {
|
||||
entries: 1,
|
||||
text: alias.len(),
|
||||
..Slots::default()
|
||||
};
|
||||
ledger
|
||||
.reserve(
|
||||
&syntax.budget,
|
||||
alias_slots
|
||||
.add(Slots::entries(1), owner.span)
|
||||
.map_err(|e| Failure::typed(syntax, Some(owner.file), e))?,
|
||||
owner.span,
|
||||
)
|
||||
.map_err(|e| Failure::typed(syntax, Some(owner.file), e))?;
|
||||
self.aliases_storage = self
|
||||
.aliases_storage
|
||||
.add(alias_slots, owner.span)
|
||||
.map_err(|e| Failure::typed(syntax, Some(owner.file), e))?;
|
||||
self.owners_storage = self
|
||||
.owners_storage
|
||||
.add(Slots::entries(1), owner.span)
|
||||
.map_err(|e| Failure::typed(syntax, Some(owner.file), e))?;
|
||||
self.aliases.insert(alias.into(), id);
|
||||
self.owners.insert(id, owner);
|
||||
Ok(())
|
||||
}
|
||||
fn reserve_tables(
|
||||
&mut self,
|
||||
syntax: &ParsedMixedSyntax<'_>,
|
||||
ledger: &mut Ledger,
|
||||
slots: Slots,
|
||||
owner: Owner,
|
||||
) -> Result<(), Failure> {
|
||||
ledger
|
||||
.reserve(&syntax.budget, slots, owner.span)
|
||||
.map_err(|e| Failure::typed(syntax, Some(owner.file), e))?;
|
||||
self.tables_storage = self
|
||||
.tables_storage
|
||||
.add(slots, owner.span)
|
||||
.map_err(|e| Failure::typed(syntax, Some(owner.file), e))?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
fn catalog(syntax: &ParsedMixedSyntax<'_>, ledger: &mut Ledger) -> Result<Catalog, Failure> {
|
||||
let mut catalog = Catalog {
|
||||
tables: lower::Tables::default(),
|
||||
aliases: BTreeMap::new(),
|
||||
owners: BTreeMap::new(),
|
||||
tables_storage: Slots::default(),
|
||||
aliases_storage: Slots::default(),
|
||||
owners_storage: Slots::default(),
|
||||
};
|
||||
let file = entry(syntax);
|
||||
let header = syntax.files[file]
|
||||
.ordinary
|
||||
.header
|
||||
.as_ref()
|
||||
.expect("entry header");
|
||||
let owner = Owner {
|
||||
file,
|
||||
kind: OwnerKind::Project,
|
||||
span: header.span,
|
||||
};
|
||||
catalog.insert(
|
||||
syntax,
|
||||
ledger,
|
||||
header.project.id,
|
||||
&header.project.alias,
|
||||
owner,
|
||||
)?;
|
||||
catalog.reserve_tables(
|
||||
syntax,
|
||||
ledger,
|
||||
Slots {
|
||||
entries: 2,
|
||||
text: header.project.alias.len(),
|
||||
..Slots::default()
|
||||
},
|
||||
owner,
|
||||
)?;
|
||||
catalog
|
||||
.tables
|
||||
.insert(
|
||||
header.project.id,
|
||||
&header.project.alias,
|
||||
lower::Category::Project,
|
||||
header.span,
|
||||
&syntax.budget,
|
||||
)
|
||||
.map_err(|e| Failure::typed(syntax, Some(file), e))?;
|
||||
for (file, unit) in syntax.files.iter().enumerate() {
|
||||
let mut ordinary = unit.ordinary.declarations.iter().enumerate().peekable();
|
||||
let mut typed = unit.typed.iter().enumerate().peekable();
|
||||
while ordinary.peek().is_some() || typed.peek().is_some() {
|
||||
let use_ordinary = match (ordinary.peek(), typed.peek()) {
|
||||
(Some((_, a)), Some((_, b))) => a.span.start < b.span.start,
|
||||
(Some(_), None) => true,
|
||||
_ => false,
|
||||
};
|
||||
if use_ordinary {
|
||||
let (index, d) = ordinary.next().expect("ordinary head");
|
||||
let owner = Owner {
|
||||
file,
|
||||
kind: OwnerKind::Ordinary(index),
|
||||
span: d.span,
|
||||
};
|
||||
catalog.insert(syntax, ledger, d.id, &d.alias, owner)?;
|
||||
catalog.reserve_tables(
|
||||
syntax,
|
||||
ledger,
|
||||
Slots {
|
||||
entries: 2,
|
||||
text: d.alias.len(),
|
||||
..Slots::default()
|
||||
},
|
||||
owner,
|
||||
)?;
|
||||
catalog
|
||||
.tables
|
||||
.insert(d.id, &d.alias, category(d.kind), d.span, &syntax.budget)
|
||||
.map_err(|e| Failure::typed(syntax, Some(file), e))?;
|
||||
} else {
|
||||
let (index, d) = typed.next().expect("typed head");
|
||||
let owner = Owner {
|
||||
file,
|
||||
kind: OwnerKind::Typed(index),
|
||||
span: d.span,
|
||||
};
|
||||
catalog.insert(
|
||||
syntax,
|
||||
ledger,
|
||||
d.header.identity.value.expect("syntax explicit ID"),
|
||||
&d.header.alias.name,
|
||||
owner,
|
||||
)?;
|
||||
let mut slots = Slots {
|
||||
entries: 2,
|
||||
text: d.header.alias.name.len(),
|
||||
..Slots::default()
|
||||
};
|
||||
let mut scratch = 0;
|
||||
if let d::Body::Calculation { parameters, .. } = &d.body {
|
||||
slots.entries = add(
|
||||
slots.entries,
|
||||
add(1, parameters.len(), d.span)
|
||||
.map_err(|e| Failure::typed(syntax, Some(file), e))?,
|
||||
d.span,
|
||||
)
|
||||
.map_err(|e| Failure::typed(syntax, Some(file), e))?;
|
||||
scratch = parameters.len(); // per-signature duplicate-ID set
|
||||
for p in parameters {
|
||||
slots.text = add(slots.text, p.name.name.len(), p.span)
|
||||
.map_err(|e| Failure::typed(syntax, Some(file), e))?;
|
||||
}
|
||||
}
|
||||
catalog.reserve_tables(syntax, ledger, slots, owner)?;
|
||||
ledger
|
||||
.reserve(&syntax.budget, Slots::entries(scratch), d.span)
|
||||
.map_err(|e| Failure::typed(syntax, Some(file), e))?;
|
||||
catalog
|
||||
.tables
|
||||
.typed(d, &syntax.budget)
|
||||
.map_err(|e| Failure::typed(syntax, Some(file), e))?;
|
||||
ledger.release(Slots::entries(scratch));
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(catalog)
|
||||
}
|
||||
|
||||
fn object<'a>(value: Option<&'a Ast>, key: &str) -> Option<&'a Ast> {
|
||||
match value {
|
||||
Some(Ast::Object(fields, _)) => fields.get(key),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
/// Selector only, not a decoder. This executes before ordinary fields clone.
|
||||
fn active_references(
|
||||
declaration: &language::Declaration,
|
||||
budget: &mut Budget,
|
||||
) -> Result<(), language::Error> {
|
||||
let field = |key: &str| declaration.fields.get(key);
|
||||
let arrays = match declaration.kind {
|
||||
DeclKind::Element(Kind::Process | Kind::FunctionalChain | Kind::Scenario, _) => {
|
||||
[field("steps"), None]
|
||||
}
|
||||
DeclKind::Element(Kind::Occurrence, _) => {
|
||||
[object(object(field("body"), "Branch"), "occurrences"), None]
|
||||
}
|
||||
DeclKind::Relation(RelationKind::ContextualLink) => [
|
||||
object(field("source"), "references"),
|
||||
object(field("target"), "references"),
|
||||
],
|
||||
_ => [None, None],
|
||||
};
|
||||
for array in arrays.into_iter().flatten() {
|
||||
if let Ast::Array(items, _) = array {
|
||||
for item in items {
|
||||
let start = item.offset();
|
||||
budget
|
||||
.reference(Span { start, end: start })
|
||||
.map_err(super::ordinary_error)?;
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(in crate::language::analysis_source) fn resolve(
|
||||
mut syntax: ParsedMixedSyntax<'_>,
|
||||
) -> Result<ResolvedMixedProject<'_>, Failure> {
|
||||
let mut storage = Ledger::default();
|
||||
let lower_storage = accounting::syntax(&syntax, &mut storage)?;
|
||||
let catalog = catalog(&syntax, &mut storage)?;
|
||||
let entry = entry(&syntax);
|
||||
// Only the empty model header is copied: retain its original syntax/header
|
||||
// ownership and construct the final model through the shared decoder once.
|
||||
let project = syntax.files[entry]
|
||||
.ordinary
|
||||
.header
|
||||
.as_ref()
|
||||
.expect("entry header")
|
||||
.project
|
||||
.clone();
|
||||
let count = syntax
|
||||
.files
|
||||
.iter()
|
||||
.try_fold(0usize, |n, f| {
|
||||
add(n, f.ordinary.declarations.len(), Span::default())
|
||||
})
|
||||
.map_err(|e| Failure::typed(&syntax, None, e))?;
|
||||
storage
|
||||
.reserve(&syntax.budget, Slots::entries(count), Span::default())
|
||||
.map_err(|e| Failure::typed(&syntax, None, e))?;
|
||||
let declarations: Vec<_> = syntax
|
||||
.files
|
||||
.iter()
|
||||
.enumerate()
|
||||
.flat_map(|(file, unit)| unit.ordinary.declarations.iter().map(move |d| (file, d)))
|
||||
.collect();
|
||||
let mut nodes = 0;
|
||||
let constructed = language::construct_declarations(
|
||||
project,
|
||||
declarations.iter().map(|(_, d)| *d),
|
||||
&catalog.aliases,
|
||||
|d| {
|
||||
active_references(d, &mut syntax.budget)?;
|
||||
if matches!(d.kind, DeclKind::Node) {
|
||||
storage
|
||||
.reserve(&syntax.budget, Slots::entries(1), d.span)
|
||||
.map_err(super::ordinary_error)?;
|
||||
nodes += 1;
|
||||
}
|
||||
Ok(())
|
||||
},
|
||||
)
|
||||
.map_err(|(index, error)| {
|
||||
Failure::ordinary(
|
||||
&syntax,
|
||||
declarations.get(index).map(|(file, _)| *file),
|
||||
error,
|
||||
)
|
||||
})?;
|
||||
let language::ConstructedDeclarations {
|
||||
mut project,
|
||||
legacy_elements,
|
||||
} = constructed;
|
||||
debug_assert!(legacy_elements.is_empty()); // mixed syntax only admits source8
|
||||
drop(legacy_elements);
|
||||
drop(declarations);
|
||||
storage.release(Slots::entries(count));
|
||||
storage.release(Slots::entries(nodes));
|
||||
drop(catalog.aliases);
|
||||
storage.release(catalog.aliases_storage);
|
||||
|
||||
let all_lower = lower_storage
|
||||
.all()
|
||||
.map_err(|e| Failure::typed(&syntax, None, e))?;
|
||||
storage
|
||||
.reserve(&syntax.budget, all_lower, Span::default())
|
||||
.map_err(|e| Failure::typed(&syntax, None, e))?;
|
||||
let lower::Lowered {
|
||||
definitions,
|
||||
elements,
|
||||
occurrences,
|
||||
expressions,
|
||||
} = lower::lower_bodies(
|
||||
&catalog.tables,
|
||||
syntax
|
||||
.files
|
||||
.iter()
|
||||
.enumerate()
|
||||
.flat_map(|(file, unit)| unit.typed.iter().map(move |d| (file, d))),
|
||||
&syntax.budget,
|
||||
)
|
||||
.map_err(|e| Failure::typed(&syntax, e.file, e.error))?;
|
||||
// One global arena transfers verbatim; only now are all Resolver temporaries
|
||||
// dead. Output counts must fit the independently counted reservation.
|
||||
storage.release(Slots {
|
||||
entries: all_lower
|
||||
.entries
|
||||
.checked_sub(expressions.len())
|
||||
.expect("expression bound"),
|
||||
occurrences: all_lower
|
||||
.occurrences
|
||||
.checked_sub(occurrences.len())
|
||||
.expect("occurrence bound"),
|
||||
text: 0,
|
||||
});
|
||||
drop(catalog.tables);
|
||||
storage.release(catalog.tables_storage);
|
||||
for (id, value) in definitions {
|
||||
if project.definitions.contains_key(&id) {
|
||||
return Err(Failure::typed(
|
||||
&syntax,
|
||||
None,
|
||||
error(Span::default(), "Non-disjoint definition merge."),
|
||||
));
|
||||
}
|
||||
project.definitions.insert(id, value);
|
||||
}
|
||||
for (id, value) in elements {
|
||||
if project.elements.contains_key(&id) {
|
||||
return Err(Failure::typed(
|
||||
&syntax,
|
||||
None,
|
||||
error(Span::default(), "Non-disjoint element merge."),
|
||||
));
|
||||
}
|
||||
project.elements.insert(id, value);
|
||||
}
|
||||
syntax
|
||||
.limits
|
||||
.model
|
||||
.check_model(&project)
|
||||
.map_err(|message| {
|
||||
Failure::ordinary(
|
||||
&syntax,
|
||||
None,
|
||||
language::Error {
|
||||
code: "model_limit",
|
||||
offset: 0,
|
||||
message,
|
||||
},
|
||||
)
|
||||
})?;
|
||||
let (issues, admission) = validation::validate_with_usage(&project);
|
||||
// Raw architecture Issues are excluded. Each transferred string, copied path
|
||||
// and destination slot is admitted before mapping/retention; never truncate.
|
||||
let mut warnings = Vec::new();
|
||||
let mut rejected = false;
|
||||
for issue in issues {
|
||||
let owner = issue
|
||||
.element
|
||||
.and_then(|id| catalog.owners.get(&id))
|
||||
.copied()
|
||||
.unwrap_or(catalog.owners[&project.id]);
|
||||
let span = field_span(&syntax.files[owner.file], owner, issue.field.as_deref());
|
||||
let unit = &syntax.files[owner.file];
|
||||
let text = [
|
||||
unit.path.len(),
|
||||
issue.code.len(),
|
||||
issue.field.as_ref().map_or(0, String::len),
|
||||
issue.message.len(),
|
||||
]
|
||||
.into_iter()
|
||||
.try_fold(0, |n, k| add(n, k, span))
|
||||
.map_err(|e| Failure::typed(&syntax, Some(owner.file), e))?;
|
||||
storage
|
||||
.reserve(
|
||||
&syntax.budget,
|
||||
Slots {
|
||||
entries: 1,
|
||||
occurrences: 0,
|
||||
text,
|
||||
},
|
||||
span,
|
||||
)
|
||||
.map_err(|e| Failure::typed(&syntax, Some(owner.file), e))?;
|
||||
rejected |= issue.severity == validation::Severity::Error;
|
||||
let prefix = &unit.source[..span.start];
|
||||
let line = prefix.bytes().filter(|b| *b == b'\n').count() + 1;
|
||||
let column = prefix.rsplit('\n').next().expect("prefix").chars().count() + 1;
|
||||
warnings.push(SourceDiagnostic {
|
||||
path: unit.path.into(),
|
||||
related: Vec::new(),
|
||||
diagnostic: language::Diagnostic {
|
||||
severity: issue.severity,
|
||||
code: issue.code,
|
||||
object_id: issue.element,
|
||||
field: issue.field,
|
||||
message: issue.message,
|
||||
span,
|
||||
line,
|
||||
column,
|
||||
},
|
||||
});
|
||||
}
|
||||
if rejected {
|
||||
return Err(Failure {
|
||||
diagnostics: warnings,
|
||||
});
|
||||
}
|
||||
let (static_limits, static_usage) = admission.expect("successful validation retains admission");
|
||||
drop(catalog.owners);
|
||||
storage.release(catalog.owners_storage);
|
||||
Ok(ResolvedMixedProject {
|
||||
syntax,
|
||||
project,
|
||||
warnings,
|
||||
static_limits,
|
||||
static_usage,
|
||||
expressions,
|
||||
occurrences,
|
||||
storage,
|
||||
})
|
||||
}
|
||||
|
||||
/// Exact known field or explicit whole-owner fallback. Never guess by offsets.
|
||||
fn field_span(file: &FileSyntax<'_>, owner: Owner, field: Option<&str>) -> Span {
|
||||
let Some(field) = field else {
|
||||
return owner.span;
|
||||
};
|
||||
match owner.kind {
|
||||
OwnerKind::Project => file
|
||||
.ordinary
|
||||
.header
|
||||
.as_ref()
|
||||
.and_then(|h| (field == "description").then_some(h.description).flatten())
|
||||
.unwrap_or(owner.span),
|
||||
OwnerKind::Ordinary(index) => file.ordinary.declarations[index]
|
||||
.field_spans
|
||||
.get(field)
|
||||
.copied()
|
||||
.unwrap_or(owner.span),
|
||||
OwnerKind::Typed(index) => typed_field(&file.typed[index], field).unwrap_or(owner.span),
|
||||
}
|
||||
}
|
||||
fn typed_field(d: &d::Declaration, field: &str) -> Option<Span> {
|
||||
if field == "description" {
|
||||
return d.description.as_ref().map(|f| f.value_span);
|
||||
}
|
||||
if field == "alias" {
|
||||
return Some(d.header.alias.span);
|
||||
}
|
||||
if field == "name" {
|
||||
return Some(d.header.name_span);
|
||||
}
|
||||
match &d.body {
|
||||
d::Body::QuantityKind { dimension, algebra } => match field {
|
||||
"dimension" => Some(dimension.value_span),
|
||||
"algebra" => Some(algebra.value_span),
|
||||
_ => None,
|
||||
},
|
||||
d::Body::Unit {
|
||||
kind,
|
||||
scale,
|
||||
offset,
|
||||
symbol,
|
||||
} => match field {
|
||||
"kind" => Some(kind.value_span),
|
||||
"scale" => Some(scale.value_span),
|
||||
"offset" => Some(offset.value_span),
|
||||
"symbol" => Some(symbol.value_span),
|
||||
_ => None,
|
||||
},
|
||||
d::Body::Calculation { result, body, .. } => match field {
|
||||
"result" => Some(result.value_span),
|
||||
"body" => Some(body.value_span),
|
||||
// Current semantic admission reports aggregate "parameters", not a
|
||||
// qualified parameter/type path. Do not manufacture precision from
|
||||
// a UUID substring; lowerer failures already carry exact file/span.
|
||||
_ => None,
|
||||
},
|
||||
d::Body::Property {
|
||||
subject,
|
||||
value_type,
|
||||
base,
|
||||
display_unit,
|
||||
} => match field {
|
||||
"subject" => Some(subject.value_span),
|
||||
"type" | "value_type" => Some(value_type.value_span),
|
||||
"base" => Some(base.value_span),
|
||||
"display_unit" => display_unit.as_ref().map(|f| f.value_span),
|
||||
_ => None,
|
||||
},
|
||||
d::Body::Check {
|
||||
subject,
|
||||
documented_constraint,
|
||||
predicate,
|
||||
} => match field {
|
||||
"subject" => subject.as_ref().map(|f| f.value_span),
|
||||
"documented_constraint" => documented_constraint.as_ref().map(|f| f.value_span),
|
||||
"predicate" => Some(predicate.value_span),
|
||||
_ => None,
|
||||
},
|
||||
d::Body::Case {
|
||||
subject,
|
||||
base,
|
||||
overrides,
|
||||
} => match field {
|
||||
"subject" => subject.as_ref().map(|f| f.value_span),
|
||||
"base" => Some(base.value_span),
|
||||
"overrides" => Some(overrides.value_span),
|
||||
_ => None,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
@@ -0,0 +1,352 @@
|
||||
//! Logical auxiliary storage, separate from model/serde and raw validator heap.
|
||||
use super::*;
|
||||
use crate::language::{EditKind, EditValue};
|
||||
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
|
||||
pub(super) struct Slots {
|
||||
pub entries: usize,
|
||||
pub occurrences: usize,
|
||||
pub text: usize,
|
||||
}
|
||||
impl Slots {
|
||||
pub fn entries(entries: usize) -> Self {
|
||||
Self {
|
||||
entries,
|
||||
..Self::default()
|
||||
}
|
||||
}
|
||||
pub fn text(text: usize) -> Self {
|
||||
Self {
|
||||
text,
|
||||
..Self::default()
|
||||
}
|
||||
}
|
||||
pub fn add(self, other: Self, at: Span) -> Result<Self, super::super::super::Error> {
|
||||
Ok(Self {
|
||||
entries: add(self.entries, other.entries, at)?,
|
||||
occurrences: add(self.occurrences, other.occurrences, at)?,
|
||||
text: add(self.text, other.text, at)?,
|
||||
})
|
||||
}
|
||||
}
|
||||
pub(super) fn add(a: usize, b: usize, at: Span) -> Result<usize, super::super::super::Error> {
|
||||
a.checked_add(b)
|
||||
.ok_or_else(|| error(at, "Mixed auxiliary storage size overflow."))
|
||||
}
|
||||
pub(super) fn mul(a: usize, b: usize, at: Span) -> Result<usize, super::super::super::Error> {
|
||||
a.checked_mul(b)
|
||||
.ok_or_else(|| error(at, "Mixed auxiliary storage size overflow."))
|
||||
}
|
||||
|
||||
#[derive(Debug, Default)]
|
||||
pub(super) struct Ledger {
|
||||
pub live: Slots,
|
||||
}
|
||||
impl Ledger {
|
||||
pub fn reserve(&mut self, budget: &Budget, slots: Slots, at: Span) -> Result<(), TypedError> {
|
||||
let next = self.live.add(slots, at)?;
|
||||
budget.lowering_entries(next.entries, at)?;
|
||||
budget.lowering_occurrences(next.occurrences, at)?;
|
||||
budget.index_bytes(next.text, at)?;
|
||||
self.live = next;
|
||||
Ok(())
|
||||
}
|
||||
pub fn release(&mut self, slots: Slots) {
|
||||
self.live.entries = self
|
||||
.live
|
||||
.entries
|
||||
.checked_sub(slots.entries)
|
||||
.expect("entry reservation");
|
||||
self.live.occurrences = self
|
||||
.live
|
||||
.occurrences
|
||||
.checked_sub(slots.occurrences)
|
||||
.expect("occurrence reservation");
|
||||
self.live.text = self
|
||||
.live
|
||||
.text
|
||||
.checked_sub(slots.text)
|
||||
.expect("text reservation");
|
||||
}
|
||||
}
|
||||
|
||||
/// Exact output-site counts and conservative whole-lowering temporary bound.
|
||||
/// N expression nodes: at most 2N Visit/Build slots, N borrowed child slots,
|
||||
/// N value/split slots. A arguments: A signature slots plus A seen-set slots.
|
||||
/// `Resolver::call` borrows the callee signature. Its parameter Vec/seen set
|
||||
/// contain only supplied arguments, including on incomplete/invalid calls;
|
||||
/// no allocation is proportional to the full signature during body lowering.
|
||||
/// The model expressions/maps themselves are outside this auxiliary ledger.
|
||||
#[derive(Default)]
|
||||
pub(super) struct LowerStorage {
|
||||
pub nodes: usize,
|
||||
pub occurrences: usize,
|
||||
pub arguments: usize,
|
||||
}
|
||||
impl LowerStorage {
|
||||
pub fn all(&self) -> Result<Slots, TypedError> {
|
||||
let at = Span::default();
|
||||
Ok(Slots {
|
||||
entries: add(mul(self.nodes, 5, at)?, mul(self.arguments, 2, at)?, at)?,
|
||||
occurrences: self.occurrences,
|
||||
text: 0,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
enum Item<'a> {
|
||||
Ast(&'a Ast),
|
||||
Edit(&'a EditValue),
|
||||
Expr(&'a Expression),
|
||||
}
|
||||
struct Walk<'a, 'b> {
|
||||
ledger: &'b mut Ledger,
|
||||
budget: &'b Budget,
|
||||
work: Vec<Item<'a>>,
|
||||
lower: LowerStorage,
|
||||
}
|
||||
impl<'a> Walk<'a, '_> {
|
||||
fn text(&mut self, text: &str, at: Span) -> Result<(), TypedError> {
|
||||
self.ledger
|
||||
.reserve(self.budget, Slots::text(text.len()), at)
|
||||
}
|
||||
fn push(&mut self, item: Item<'a>) -> Result<(), TypedError> {
|
||||
self.ledger
|
||||
.reserve(self.budget, Slots::entries(1), Span::default())?;
|
||||
self.work.push(item);
|
||||
Ok(())
|
||||
}
|
||||
fn reference(&mut self, r: &Reference) -> Result<(), TypedError> {
|
||||
self.text(&r.name, r.span)?;
|
||||
self.lower.occurrences = add(self.lower.occurrences, 1, r.span)?;
|
||||
Ok(())
|
||||
}
|
||||
fn optional(&mut self, field: &Option<d::Field<Option<Reference>>>) -> Result<(), TypedError> {
|
||||
if let Some(r) = field.as_ref().and_then(|f| f.value.as_ref()) {
|
||||
self.reference(r)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
fn ty(&mut self, ty: &d::TypeSyntax) -> Result<(), TypedError> {
|
||||
if let d::ScalarKind::Quantity(r) = &ty.scalar.kind {
|
||||
self.reference(r)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
fn binding(&mut self, binding: &'a Binding) -> Result<(), TypedError> {
|
||||
if let Binding::Expression(e) = binding {
|
||||
self.push(Item::Expr(e))?;
|
||||
}
|
||||
self.drain()
|
||||
}
|
||||
fn drain(&mut self) -> Result<(), TypedError> {
|
||||
while let Some(item) = self.work.pop() {
|
||||
self.ledger.release(Slots::entries(1));
|
||||
match item {
|
||||
Item::Ast(ast) => match ast {
|
||||
Ast::Literal(serde_json::Value::String(s), _)
|
||||
| Ast::Word(s, _)
|
||||
| Ast::Reference(s, _) => self.text(s, Span::default())?,
|
||||
Ast::Array(items, _) => {
|
||||
for child in items {
|
||||
self.push(Item::Ast(child))?;
|
||||
}
|
||||
}
|
||||
Ast::Object(fields, _) => {
|
||||
for (key, child) in fields {
|
||||
self.text(key, Span::default())?;
|
||||
self.push(Item::Ast(child))?;
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
},
|
||||
Item::Edit(value) => match &value.kind {
|
||||
EditKind::Reference(s) => self.text(s, value.span)?,
|
||||
EditKind::Record(fields) => {
|
||||
for (key, field) in fields {
|
||||
self.text(key, field.span)?;
|
||||
self.push(Item::Edit(&field.value))?;
|
||||
}
|
||||
}
|
||||
EditKind::List(items) => {
|
||||
for child in items {
|
||||
self.push(Item::Edit(child))?;
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
},
|
||||
Item::Expr(e) => {
|
||||
self.lower.nodes = add(self.lower.nodes, 1, e.span)?;
|
||||
use ExpressionKind as E;
|
||||
match &e.kind {
|
||||
E::Quantity { unit, .. } | E::Property(unit) | E::Parameter(unit) => {
|
||||
self.reference(unit)?
|
||||
}
|
||||
E::List(items) => {
|
||||
for child in items {
|
||||
self.push(Item::Expr(child))?;
|
||||
}
|
||||
}
|
||||
E::Unary { operand, .. } => self.push(Item::Expr(operand))?,
|
||||
E::Binary { left, right, .. } => {
|
||||
self.push(Item::Expr(left))?;
|
||||
self.push(Item::Expr(right))?;
|
||||
}
|
||||
E::If {
|
||||
condition,
|
||||
when_true,
|
||||
when_false,
|
||||
} => {
|
||||
self.push(Item::Expr(condition))?;
|
||||
self.push(Item::Expr(when_true))?;
|
||||
self.push(Item::Expr(when_false))?;
|
||||
}
|
||||
E::Call {
|
||||
definition,
|
||||
arguments,
|
||||
} => {
|
||||
self.reference(definition)?;
|
||||
self.lower.arguments =
|
||||
add(self.lower.arguments, arguments.len(), e.span)?;
|
||||
for argument in arguments {
|
||||
self.reference(&argument.parameter)?;
|
||||
self.push(Item::Expr(&argument.value))?;
|
||||
}
|
||||
}
|
||||
E::Sum { values, initial } => {
|
||||
self.push(Item::Expr(values))?;
|
||||
self.push(Item::Expr(initial))?;
|
||||
}
|
||||
E::Power { base, .. } => self.push(Item::Expr(base))?,
|
||||
E::AsKind { kind, value } => {
|
||||
self.reference(kind)?;
|
||||
self.push(Item::Expr(value))?;
|
||||
}
|
||||
E::Boolean(_) | E::Number(_) => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn syntax(
|
||||
syntax: &ParsedMixedSyntax<'_>,
|
||||
ledger: &mut Ledger,
|
||||
) -> Result<LowerStorage, Failure> {
|
||||
let at = Span::default();
|
||||
ledger
|
||||
.reserve(
|
||||
&syntax.budget,
|
||||
Slots::entries(
|
||||
add(syntax.metadata, syntax.budget.usage.entries, at)
|
||||
.map_err(|e| Failure::typed(syntax, None, e))?,
|
||||
),
|
||||
at,
|
||||
)
|
||||
.map_err(|e| Failure::typed(syntax, None, e))?;
|
||||
let mut walk = Walk {
|
||||
ledger,
|
||||
budget: &syntax.budget,
|
||||
work: Vec::new(),
|
||||
lower: LowerStorage::default(),
|
||||
};
|
||||
for (file, unit) in syntax.files.iter().enumerate() {
|
||||
let mut count = || -> Result<(), TypedError> {
|
||||
if let Some(header) = &unit.ordinary.header {
|
||||
for s in [
|
||||
&header.project.alias,
|
||||
&header.project.name,
|
||||
&header.project.description,
|
||||
] {
|
||||
walk.text(s, header.span)?;
|
||||
}
|
||||
}
|
||||
for (path, span) in &unit.ordinary.includes {
|
||||
walk.text(path, *span)?;
|
||||
}
|
||||
for declaration in &unit.ordinary.declarations {
|
||||
walk.text(&declaration.alias, declaration.span)?;
|
||||
walk.text(&declaration.name, declaration.span)?;
|
||||
for key in declaration.field_spans.keys() {
|
||||
walk.text(key, declaration.span)?;
|
||||
}
|
||||
for (key, value) in &declaration.fields {
|
||||
walk.text(key, declaration.span)?;
|
||||
walk.push(Item::Ast(value))?;
|
||||
walk.drain()?;
|
||||
}
|
||||
}
|
||||
for (_, position) in &unit.positions {
|
||||
walk.push(Item::Edit(&position.fields))?;
|
||||
walk.drain()?;
|
||||
}
|
||||
for declaration in &unit.typed {
|
||||
walk.text(
|
||||
&declaration.header.alias.name,
|
||||
declaration.header.alias.span,
|
||||
)?;
|
||||
walk.text(&declaration.header.name, declaration.header.name_span)?;
|
||||
if let Some(f) = &declaration.description {
|
||||
walk.text(&f.value, f.span)?;
|
||||
}
|
||||
match &declaration.body {
|
||||
d::Body::QuantityKind { algebra, .. } => {
|
||||
if let d::AlgebraSyntax::Affine(r) = &algebra.value {
|
||||
walk.reference(r)?;
|
||||
}
|
||||
}
|
||||
d::Body::Unit { kind, symbol, .. } => {
|
||||
walk.reference(&kind.value)?;
|
||||
walk.text(&symbol.value, symbol.span)?;
|
||||
}
|
||||
d::Body::Calculation {
|
||||
parameters,
|
||||
result,
|
||||
body,
|
||||
} => {
|
||||
for p in parameters {
|
||||
walk.reference(&p.name)?;
|
||||
walk.ty(&p.value_type)?;
|
||||
}
|
||||
walk.ty(&result.value)?;
|
||||
walk.binding(&body.value)?;
|
||||
}
|
||||
d::Body::Property {
|
||||
subject,
|
||||
value_type,
|
||||
base,
|
||||
display_unit,
|
||||
} => {
|
||||
walk.reference(&subject.value)?;
|
||||
walk.ty(&value_type.value)?;
|
||||
walk.binding(&base.value)?;
|
||||
walk.optional(display_unit)?;
|
||||
}
|
||||
d::Body::Check {
|
||||
subject,
|
||||
documented_constraint,
|
||||
predicate,
|
||||
} => {
|
||||
walk.optional(subject)?;
|
||||
walk.optional(documented_constraint)?;
|
||||
walk.binding(&predicate.value)?;
|
||||
}
|
||||
d::Body::Case {
|
||||
subject, overrides, ..
|
||||
} => {
|
||||
walk.optional(subject)?;
|
||||
for entry in &overrides.value {
|
||||
walk.reference(&entry.target)?;
|
||||
walk.binding(&entry.binding)?;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
};
|
||||
count().map_err(|e| Failure::typed(syntax, Some(file), e))?;
|
||||
}
|
||||
Ok(walk.lower)
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,263 @@
|
||||
//! Independent model construction: never parses source or calls the writer.
|
||||
use crate::analysis::*;
|
||||
use crate::analysis_numeric::{Dimension, Exact, ExactWire, WorkLimits, WorkMeter};
|
||||
use crate::*;
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
pub(super) const NAMES: [(&str, &str); 14] = [
|
||||
("duration", "Duration"),
|
||||
("second", "Second"),
|
||||
("millisecond", "Millisecond"),
|
||||
("combine", "Combine durations"),
|
||||
("respond", "Respond"),
|
||||
("receive", "Receive"),
|
||||
("dispatch", "Dispatch"),
|
||||
("receive_time", "Receive time"),
|
||||
("dispatch_time", "Dispatch time"),
|
||||
("total_time", "Total time"),
|
||||
("limit", "Allowed duration"),
|
||||
("budget", "Response budget"),
|
||||
("degraded", "Degraded radio"),
|
||||
("unmeasured", "Unmeasured radio"),
|
||||
];
|
||||
|
||||
fn named(alias: &str) -> String {
|
||||
NAMES
|
||||
.iter()
|
||||
.find(|(key, _)| *key == alias)
|
||||
.unwrap()
|
||||
.1
|
||||
.into()
|
||||
}
|
||||
fn local(id: Id) -> DefinitionRef {
|
||||
DefinitionRef::Local(id)
|
||||
}
|
||||
fn quantity(value: i64, unit: Id) -> Expr {
|
||||
Expr::Quantity {
|
||||
magnitude: Exact::from_integer(value),
|
||||
unit: local(unit),
|
||||
}
|
||||
}
|
||||
fn expression(value: Expr) -> Binding {
|
||||
Binding::Expression(value)
|
||||
}
|
||||
fn binary(op: BinaryOp, left: Expr, right: Expr) -> Expr {
|
||||
Expr::Binary {
|
||||
op,
|
||||
left: Box::new(left),
|
||||
right: Box::new(right),
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn project(layer: Layer) -> Project {
|
||||
// OA is the fixed r2 set; SA independently constructs fresh global IDs.
|
||||
let id = |text| {
|
||||
let id = Id::parse_str(text).unwrap();
|
||||
if layer == Layer::Oa {
|
||||
id
|
||||
} else {
|
||||
Id::from_u128(id.as_u128() ^ (1 << 127))
|
||||
}
|
||||
};
|
||||
let project_id = id("4210b9f2-7046-47f0-aa3b-153f626a579d");
|
||||
let duration = id("188b911c-5f8b-431c-9eea-2d41f3953767");
|
||||
let second = id("534f4672-1ba5-4157-8b0a-b9cf41d0a3ce");
|
||||
let millisecond = id("39053f37-fec9-4708-9f0a-3959d223f891");
|
||||
let combine = id("fd7ce7ab-f789-40bc-b699-0c37f1b6902f");
|
||||
// Parameter IDs may be reused in another calculation/project.
|
||||
let a = ParameterId(Id::parse_str("28ff40b0-1b8f-4735-8536-5a6ab21b56cb").unwrap());
|
||||
let b = ParameterId(Id::parse_str("7a47cc1e-8ae5-4551-b2d8-8a68108e0976").unwrap());
|
||||
let respond = id("cabec6a1-7d5d-48f3-8d2d-a7fc8cf78f59");
|
||||
let receive = id("4ab9a8a7-7552-488d-9862-e14b89e7b353");
|
||||
let dispatch = id("6df991ba-4c5e-4535-99e2-524ae274ee8b");
|
||||
let receive_time = id("63a931c2-675a-4fce-89e5-04361cb99450");
|
||||
let dispatch_time = id("c33fc772-2a60-4044-9af9-73c61c563ace");
|
||||
let total = id("bd5b68e8-65fc-4e35-9071-a73061316a4b");
|
||||
let limit = id("437bedbb-2cf4-44ee-a139-6563cc5086ec");
|
||||
let check = id("bac0de99-9d2f-4e53-9158-d424ecac61bf");
|
||||
let degraded = id("38036c65-16d4-449c-837b-91eb141c1d93");
|
||||
let unmeasured = id("99d3e09a-0ec3-4194-9dd4-9f3de6625cde");
|
||||
let duration_type = || AnalysisType::Scalar(ScalarType::Quantity(local(duration)));
|
||||
let definition = |id, alias: &str, body| Definition {
|
||||
id,
|
||||
alias: alias.into(),
|
||||
name: named(alias),
|
||||
description: String::new(),
|
||||
body,
|
||||
};
|
||||
let shared = |id, alias: &str, body| Element {
|
||||
id,
|
||||
alias: alias.into(),
|
||||
name: named(alias),
|
||||
description: String::new(),
|
||||
parent: None,
|
||||
body: ElementBody::shared_in(layer, body),
|
||||
};
|
||||
let work = |id, alias: &str, parent| Element {
|
||||
id,
|
||||
alias: alias.into(),
|
||||
name: named(alias),
|
||||
description: String::new(),
|
||||
parent,
|
||||
body: if layer == Layer::Oa {
|
||||
ElementBody::Oa(OaBody::Activity)
|
||||
} else {
|
||||
ElementBody::Sa(SaBody::Function)
|
||||
},
|
||||
};
|
||||
let definitions = [
|
||||
definition(
|
||||
duration,
|
||||
"duration",
|
||||
DefinitionBody::QuantityKind(QuantityKindDefinition {
|
||||
dimension: Dimension::new([0, 0, 1, 0, 0, 0, 0]).unwrap(),
|
||||
algebra: QuantityAlgebra::Linear,
|
||||
}),
|
||||
),
|
||||
definition(
|
||||
second,
|
||||
"second",
|
||||
DefinitionBody::Unit(UnitDefinition {
|
||||
kind: local(duration),
|
||||
scale: Exact::from_integer(1),
|
||||
offset: Exact::from_integer(0),
|
||||
symbol: "s".into(),
|
||||
}),
|
||||
),
|
||||
definition(
|
||||
millisecond,
|
||||
"millisecond",
|
||||
DefinitionBody::Unit(UnitDefinition {
|
||||
kind: local(duration),
|
||||
scale: Exact::from_wire(
|
||||
&ExactWire {
|
||||
numerator: "1".into(),
|
||||
denominator: "1000".into(),
|
||||
},
|
||||
&mut WorkMeter::new(WorkLimits::REFERENCE),
|
||||
)
|
||||
.unwrap(),
|
||||
offset: Exact::from_integer(0),
|
||||
symbol: "ms".into(),
|
||||
}),
|
||||
),
|
||||
definition(
|
||||
combine,
|
||||
"combine",
|
||||
DefinitionBody::Calculation(CalculationDefinition {
|
||||
parameters: vec![
|
||||
Parameter {
|
||||
id: a,
|
||||
name: "a".into(),
|
||||
value_type: duration_type(),
|
||||
},
|
||||
Parameter {
|
||||
id: b,
|
||||
name: "b".into(),
|
||||
value_type: duration_type(),
|
||||
},
|
||||
],
|
||||
result: duration_type(),
|
||||
body: expression(binary(
|
||||
BinaryOp::Add,
|
||||
Expr::Parameter(a),
|
||||
Expr::Parameter(b),
|
||||
)),
|
||||
}),
|
||||
),
|
||||
]
|
||||
.into_iter()
|
||||
.map(|definition| (definition.id, definition))
|
||||
.collect();
|
||||
let property = |id, alias, subject, display, base| {
|
||||
shared(
|
||||
id,
|
||||
alias,
|
||||
SharedBody::EngineeringProperty {
|
||||
subject: AnalysisSubject::Element(subject),
|
||||
value_type: duration_type(),
|
||||
display_unit: Some(local(display)),
|
||||
base: expression(base),
|
||||
},
|
||||
)
|
||||
};
|
||||
let case = |id, alias, binding| {
|
||||
shared(
|
||||
id,
|
||||
alias,
|
||||
SharedBody::AnalysisCase {
|
||||
subject: None,
|
||||
base: BaselineBase::ModelBaseline,
|
||||
overrides: BTreeMap::from([(receive_time, binding)]),
|
||||
},
|
||||
)
|
||||
};
|
||||
let elements = [
|
||||
work(respond, "respond", None),
|
||||
work(receive, "receive", Some(respond)),
|
||||
work(dispatch, "dispatch", Some(respond)),
|
||||
property(
|
||||
receive_time,
|
||||
"receive_time",
|
||||
receive,
|
||||
millisecond,
|
||||
quantity(750, millisecond),
|
||||
),
|
||||
property(
|
||||
dispatch_time,
|
||||
"dispatch_time",
|
||||
dispatch,
|
||||
second,
|
||||
quantity(1, second),
|
||||
),
|
||||
property(
|
||||
total,
|
||||
"total_time",
|
||||
respond,
|
||||
second,
|
||||
Expr::Call {
|
||||
definition: local(combine),
|
||||
arguments: BTreeMap::from([
|
||||
(a, Expr::Property(receive_time)),
|
||||
(b, Expr::Property(dispatch_time)),
|
||||
]),
|
||||
},
|
||||
),
|
||||
property(limit, "limit", respond, second, quantity(2, second)),
|
||||
shared(
|
||||
check,
|
||||
"budget",
|
||||
SharedBody::AnalysisCheck {
|
||||
subject: None,
|
||||
documented_constraint: None,
|
||||
predicate: expression(binary(
|
||||
BinaryOp::LessOrEqual,
|
||||
Expr::Property(total),
|
||||
Expr::Property(limit),
|
||||
)),
|
||||
},
|
||||
),
|
||||
case(
|
||||
degraded,
|
||||
"degraded",
|
||||
expression(quantity(1250, millisecond)),
|
||||
),
|
||||
case(unmeasured, "unmeasured", Binding::Unbound),
|
||||
]
|
||||
.into_iter()
|
||||
.map(|element| (element.id, element))
|
||||
.collect();
|
||||
Project {
|
||||
schema_version: 8,
|
||||
id: project_id,
|
||||
alias: "response_budget".into(),
|
||||
name: "Response budget".into(),
|
||||
description: String::new(),
|
||||
definitions,
|
||||
elements,
|
||||
relations: BTreeMap::new(),
|
||||
diagrams: BTreeMap::new(),
|
||||
artifact_links: BTreeMap::new(),
|
||||
traces: BTreeMap::new(),
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,473 @@
|
||||
//! Iterative Pratt machine. Source nesting does not recurse on the native stack.
|
||||
use super::cursor::Cursor;
|
||||
use super::*;
|
||||
use lex::Class;
|
||||
use std::collections::BTreeSet;
|
||||
|
||||
enum SequenceKind {
|
||||
List,
|
||||
If,
|
||||
Sum,
|
||||
Unary(UnaryOp),
|
||||
Call(Reference),
|
||||
}
|
||||
struct Sequence {
|
||||
kind: SequenceKind,
|
||||
start: usize,
|
||||
values: Vec<(Option<Reference>, Expression)>,
|
||||
keys: BTreeSet<String>,
|
||||
}
|
||||
enum Task {
|
||||
Expression(u8),
|
||||
Continue(u8),
|
||||
Binary(Expression, BinaryOp),
|
||||
Unary(usize, UnaryOp),
|
||||
Group(usize),
|
||||
Next(Sequence),
|
||||
Collected(Sequence, Option<Reference>),
|
||||
Power(usize),
|
||||
AsKind(usize, Reference),
|
||||
}
|
||||
pub(super) fn binding(p: &mut Cursor<'_, '_>) -> Result<Binding, Error> {
|
||||
p.budget.active()?;
|
||||
if p.text() == "unbound" {
|
||||
let span = p.span();
|
||||
p.cursor += 1;
|
||||
return Ok(Binding::Unbound(span));
|
||||
}
|
||||
let mut tasks = vec![Task::Expression(0)];
|
||||
let mut values = Vec::new();
|
||||
while let Some(task) = tasks.pop() {
|
||||
p.budget.active()?;
|
||||
match task {
|
||||
Task::Expression(minimum) => {
|
||||
let start = p.span().start;
|
||||
if p.text() != "(" {
|
||||
p.budget.entry(p.span())?;
|
||||
}
|
||||
tasks.push(Task::Continue(minimum));
|
||||
match p.text() {
|
||||
"true" | "false" => {
|
||||
let value = p.text() == "true";
|
||||
let span = p.span();
|
||||
p.cursor += 1;
|
||||
values.push(p.node(ExpressionKind::Boolean(value), span)?);
|
||||
}
|
||||
"-" => {
|
||||
p.open()?;
|
||||
p.cursor += 1;
|
||||
tasks.push(Task::Unary(start, UnaryOp::Negate));
|
||||
tasks.push(Task::Expression(7));
|
||||
}
|
||||
"(" => {
|
||||
p.open()?;
|
||||
p.cursor += 1;
|
||||
tasks.push(Task::Group(start));
|
||||
tasks.push(Task::Expression(0));
|
||||
}
|
||||
"[" => {
|
||||
p.open()?;
|
||||
p.cursor += 1;
|
||||
tasks.push(Task::Next(Sequence::new(SequenceKind::List, start)));
|
||||
}
|
||||
"@" => {
|
||||
p.cursor += 1;
|
||||
let reference = p.reference()?;
|
||||
if p.text() == "(" {
|
||||
p.open()?;
|
||||
p.cursor += 1;
|
||||
tasks.push(Task::Next(Sequence::new(
|
||||
SequenceKind::Call(reference),
|
||||
start,
|
||||
)));
|
||||
} else {
|
||||
let end = reference.span.end;
|
||||
values.push(
|
||||
p.node(ExpressionKind::Property(reference), Span { start, end })?,
|
||||
);
|
||||
}
|
||||
}
|
||||
"$" => {
|
||||
p.cursor += 1;
|
||||
let reference = p.reference()?;
|
||||
let end = reference.span.end;
|
||||
values.push(
|
||||
p.node(ExpressionKind::Parameter(reference), Span { start, end })?,
|
||||
);
|
||||
}
|
||||
"ratio" => {
|
||||
let (value, literal) = p.exact_literal()?;
|
||||
values.push(p.number(value, literal)?);
|
||||
}
|
||||
"abs" | "not" | "if" | "sum" => {
|
||||
let kind = match p.text() {
|
||||
"abs" => SequenceKind::Unary(UnaryOp::Absolute),
|
||||
"not" => SequenceKind::Unary(UnaryOp::Not),
|
||||
"if" => SequenceKind::If,
|
||||
_ => SequenceKind::Sum,
|
||||
};
|
||||
p.cursor += 1;
|
||||
p.open()?;
|
||||
p.take("(")?;
|
||||
tasks.push(Task::Next(Sequence::new(kind, start)));
|
||||
}
|
||||
"power" => {
|
||||
p.cursor += 1;
|
||||
p.open()?;
|
||||
p.take("(")?;
|
||||
tasks.push(Task::Power(start));
|
||||
tasks.push(Task::Expression(0));
|
||||
}
|
||||
"as_kind" => {
|
||||
p.cursor += 1;
|
||||
p.open()?;
|
||||
p.take("(")?;
|
||||
p.take("@")?;
|
||||
let kind = p.reference()?;
|
||||
p.take(",")?;
|
||||
tasks.push(Task::AsKind(start, kind));
|
||||
tasks.push(Task::Expression(0));
|
||||
}
|
||||
_ if p
|
||||
.tokens
|
||||
.get(p.cursor)
|
||||
.is_some_and(|token| token.class == Class::Number) =>
|
||||
{
|
||||
let (value, literal) = p.exact_literal()?;
|
||||
values.push(p.number(value, literal)?);
|
||||
}
|
||||
_ => return Err(error(p.span(), "Expected an analysis expression.")),
|
||||
}
|
||||
}
|
||||
Task::Continue(minimum) => {
|
||||
if let Some((op, precedence)) =
|
||||
operator(p.text()).filter(|(_, prec)| *prec >= minimum)
|
||||
{
|
||||
let left = values.pop().expect("completed Pratt operand");
|
||||
if comparison(op) && ungrouped_comparison(&left) {
|
||||
return Err(error(p.span(), "Comparison children require parentheses."));
|
||||
}
|
||||
p.budget.entry(p.span())?;
|
||||
p.cursor += 1;
|
||||
tasks.push(Task::Continue(minimum));
|
||||
tasks.push(Task::Binary(left, op));
|
||||
tasks.push(Task::Expression(precedence + 1));
|
||||
}
|
||||
}
|
||||
Task::Binary(left, op) => {
|
||||
let right = values.pop().expect("completed right operand");
|
||||
if comparison(op) && ungrouped_comparison(&right) {
|
||||
return Err(error(
|
||||
right.span,
|
||||
"Comparison children require parentheses.",
|
||||
));
|
||||
}
|
||||
let span = Span {
|
||||
start: left.span.start,
|
||||
end: right.span.end,
|
||||
};
|
||||
values.push(p.node(
|
||||
ExpressionKind::Binary {
|
||||
op,
|
||||
left: Box::new(left),
|
||||
right: Box::new(right),
|
||||
},
|
||||
span,
|
||||
)?);
|
||||
}
|
||||
Task::Unary(start, op) => {
|
||||
let operand = values.pop().expect("completed unary operand");
|
||||
let end = operand.span.end;
|
||||
p.close();
|
||||
values.push(p.node(
|
||||
ExpressionKind::Unary {
|
||||
op,
|
||||
operand: Box::new(operand),
|
||||
},
|
||||
Span { start, end },
|
||||
)?);
|
||||
}
|
||||
Task::Group(start) => {
|
||||
let end = p.take(")")?.end;
|
||||
p.close();
|
||||
let value = values.last_mut().expect("completed grouped expression");
|
||||
value.grouped = true;
|
||||
value.span = Span { start, end };
|
||||
}
|
||||
Task::Next(mut sequence) => {
|
||||
let closing = if matches!(sequence.kind, SequenceKind::List) {
|
||||
"]"
|
||||
} else {
|
||||
")"
|
||||
};
|
||||
if p.text() == closing {
|
||||
let end = p.take(closing)?.end;
|
||||
p.close();
|
||||
values.push(p.sequence(sequence, end)?);
|
||||
} else {
|
||||
let count = sequence.values.len();
|
||||
let maximum = match sequence.kind {
|
||||
SequenceKind::List => crate::analysis::MAX_LIST_LENGTH,
|
||||
SequenceKind::Unary(_) => 1,
|
||||
SequenceKind::If => 3,
|
||||
SequenceKind::Sum => 2,
|
||||
SequenceKind::Call(_) => usize::MAX,
|
||||
};
|
||||
if count >= maximum {
|
||||
return Err(error(
|
||||
p.span(),
|
||||
"Too many list members or constructor arguments.",
|
||||
));
|
||||
}
|
||||
let key = if matches!(sequence.kind, SequenceKind::Call(_)) {
|
||||
p.budget.entry(p.span())?;
|
||||
let key = p.reference()?;
|
||||
if !sequence.keys.insert(key.name.clone()) {
|
||||
return Err(error(key.span, "Duplicate call argument name."));
|
||||
}
|
||||
p.take(":")?;
|
||||
Some(key)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
tasks.push(Task::Collected(sequence, key));
|
||||
tasks.push(Task::Expression(0));
|
||||
}
|
||||
}
|
||||
Task::Collected(mut sequence, key) => {
|
||||
sequence
|
||||
.values
|
||||
.push((key, values.pop().expect("completed sequence value")));
|
||||
let closing = if matches!(sequence.kind, SequenceKind::List) {
|
||||
"]"
|
||||
} else {
|
||||
")"
|
||||
};
|
||||
if p.text() != closing {
|
||||
p.take(",")?;
|
||||
if p.text() == closing {
|
||||
return Err(error(p.span(), "Trailing comma is not an expression."));
|
||||
}
|
||||
}
|
||||
tasks.push(Task::Next(sequence));
|
||||
}
|
||||
Task::Power(start) => {
|
||||
let base = values.pop().expect("completed power base");
|
||||
p.take(",")?;
|
||||
let negative = if p.text() == "-" {
|
||||
p.cursor += 1;
|
||||
true
|
||||
} else {
|
||||
false
|
||||
};
|
||||
let span = p.integer()?;
|
||||
let magnitude = p.source[span.start..span.end]
|
||||
.parse::<u8>()
|
||||
.map_err(|_| error(span, "Power exponent is outside -16..16."))?;
|
||||
if magnitude > 16 {
|
||||
return Err(error(span, "Power exponent is outside -16..16."));
|
||||
}
|
||||
let exponent = if negative {
|
||||
-(magnitude as i8)
|
||||
} else {
|
||||
magnitude as i8
|
||||
};
|
||||
let end = p.take(")")?.end;
|
||||
p.close();
|
||||
values.push(p.node(
|
||||
ExpressionKind::Power {
|
||||
base: Box::new(base),
|
||||
exponent,
|
||||
},
|
||||
Span { start, end },
|
||||
)?);
|
||||
}
|
||||
Task::AsKind(start, kind) => {
|
||||
let value = values.pop().expect("completed kind assertion value");
|
||||
let end = p.take(")")?.end;
|
||||
p.close();
|
||||
values.push(p.node(
|
||||
ExpressionKind::AsKind {
|
||||
kind,
|
||||
value: Box::new(value),
|
||||
},
|
||||
Span { start, end },
|
||||
)?);
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(Binding::Expression(
|
||||
values.pop().expect("one complete expression"),
|
||||
))
|
||||
}
|
||||
impl Sequence {
|
||||
fn new(kind: SequenceKind, start: usize) -> Self {
|
||||
Self {
|
||||
kind,
|
||||
start,
|
||||
values: Vec::new(),
|
||||
keys: BTreeSet::new(),
|
||||
}
|
||||
}
|
||||
}
|
||||
impl Cursor<'_, '_> {
|
||||
fn number(&mut self, magnitude: Exact, literal: LiteralSyntax) -> Result<Expression, Error> {
|
||||
let Span { start, end } = literal.span;
|
||||
let mut expression = if self.text() == "[" {
|
||||
self.open()?;
|
||||
self.cursor += 1;
|
||||
self.take("@")?;
|
||||
let unit = self.reference()?;
|
||||
let end = self.take("]")?.end;
|
||||
self.close();
|
||||
self.node(
|
||||
ExpressionKind::Quantity { magnitude, unit },
|
||||
Span { start, end },
|
||||
)
|
||||
} else {
|
||||
self.node(ExpressionKind::Number(magnitude), Span { start, end })
|
||||
}?;
|
||||
expression.literal = Some(literal);
|
||||
Ok(expression)
|
||||
}
|
||||
fn node(&mut self, kind: ExpressionKind, span: Span) -> Result<Expression, Error> {
|
||||
let child_depth = match &kind {
|
||||
ExpressionKind::Unary { operand, .. } => operand.depth,
|
||||
ExpressionKind::Binary { left, right, .. } => left.depth.max(right.depth),
|
||||
ExpressionKind::If {
|
||||
condition,
|
||||
when_true,
|
||||
when_false,
|
||||
} => condition.depth.max(when_true.depth).max(when_false.depth),
|
||||
ExpressionKind::List(values) => values.iter().map(|v| v.depth).max().unwrap_or(0),
|
||||
ExpressionKind::Call { arguments, .. } => {
|
||||
arguments.iter().map(|a| a.value.depth).max().unwrap_or(0)
|
||||
}
|
||||
ExpressionKind::Sum { values, initial } => values.depth.max(initial.depth),
|
||||
ExpressionKind::Power { base, .. } => base.depth,
|
||||
ExpressionKind::AsKind { value, .. } => value.depth,
|
||||
_ => 0,
|
||||
};
|
||||
if child_depth >= crate::analysis::MAX_EXPRESSION_DEPTH {
|
||||
// The rejected parent still owns accepted, potentially depth-128
|
||||
// children. Recursive derived cleanup here runs beneath the parser
|
||||
// frames and can exhaust the bounded native stack before returning
|
||||
// the depth error. Consume those children with an explicit worklist.
|
||||
drop_rejected_kind(kind);
|
||||
return Err(error(span, "Expression logical depth exceeds 128."));
|
||||
}
|
||||
Ok(Expression {
|
||||
kind,
|
||||
span,
|
||||
depth: child_depth + 1,
|
||||
grouped: false,
|
||||
literal: None,
|
||||
})
|
||||
}
|
||||
fn sequence(&mut self, sequence: Sequence, end: usize) -> Result<Expression, Error> {
|
||||
let span = Span {
|
||||
start: sequence.start,
|
||||
end,
|
||||
};
|
||||
let mut values = sequence.values.into_iter();
|
||||
let mut next = || {
|
||||
values
|
||||
.next()
|
||||
.map(|(_, value)| Box::new(value))
|
||||
.ok_or_else(|| error(span, "Missing required constructor argument."))
|
||||
};
|
||||
let kind = match sequence.kind {
|
||||
SequenceKind::If => ExpressionKind::If {
|
||||
condition: next()?,
|
||||
when_true: next()?,
|
||||
when_false: next()?,
|
||||
},
|
||||
SequenceKind::Sum => ExpressionKind::Sum {
|
||||
values: next()?,
|
||||
initial: next()?,
|
||||
},
|
||||
SequenceKind::Unary(op) => ExpressionKind::Unary {
|
||||
op,
|
||||
operand: next()?,
|
||||
},
|
||||
SequenceKind::List => ExpressionKind::List(values.map(|(_, value)| value).collect()),
|
||||
SequenceKind::Call(definition) => ExpressionKind::Call {
|
||||
definition,
|
||||
arguments: values
|
||||
.map(|(parameter, value)| Argument {
|
||||
parameter: parameter.expect("parsed named argument"),
|
||||
value,
|
||||
})
|
||||
.collect(),
|
||||
},
|
||||
};
|
||||
self.node(kind, span)
|
||||
}
|
||||
}
|
||||
fn drop_rejected_kind(kind: ExpressionKind) {
|
||||
let mut pending = vec![kind];
|
||||
while let Some(kind) = pending.pop() {
|
||||
match kind {
|
||||
ExpressionKind::Unary { operand, .. } => pending.push(operand.kind),
|
||||
ExpressionKind::Binary { left, right, .. } => {
|
||||
pending.push(left.kind);
|
||||
pending.push(right.kind);
|
||||
}
|
||||
ExpressionKind::If {
|
||||
condition,
|
||||
when_true,
|
||||
when_false,
|
||||
} => {
|
||||
pending.push(condition.kind);
|
||||
pending.push(when_true.kind);
|
||||
pending.push(when_false.kind);
|
||||
}
|
||||
ExpressionKind::List(values) => pending.extend(values.into_iter().map(|v| v.kind)),
|
||||
ExpressionKind::Call { arguments, .. } => {
|
||||
pending.extend(arguments.into_iter().map(|a| a.value.kind));
|
||||
}
|
||||
ExpressionKind::Sum { values, initial } => {
|
||||
pending.push(values.kind);
|
||||
pending.push(initial.kind);
|
||||
}
|
||||
ExpressionKind::Power { base, .. } => pending.push(base.kind),
|
||||
ExpressionKind::AsKind { value, .. } => pending.push(value.kind),
|
||||
ExpressionKind::Boolean(_)
|
||||
| ExpressionKind::Number(_)
|
||||
| ExpressionKind::Quantity { .. }
|
||||
| ExpressionKind::Property(_)
|
||||
| ExpressionKind::Parameter(_) => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
fn comparison(op: BinaryOp) -> bool {
|
||||
matches!(
|
||||
op,
|
||||
BinaryOp::Equal
|
||||
| BinaryOp::NotEqual
|
||||
| BinaryOp::Less
|
||||
| BinaryOp::LessOrEqual
|
||||
| BinaryOp::Greater
|
||||
| BinaryOp::GreaterOrEqual
|
||||
)
|
||||
}
|
||||
fn ungrouped_comparison(value: &Expression) -> bool {
|
||||
!value.grouped && matches!(&value.kind, ExpressionKind::Binary { op, .. } if comparison(*op))
|
||||
}
|
||||
fn operator(text: &str) -> Option<(BinaryOp, u8)> {
|
||||
Some(match text {
|
||||
"or" => (BinaryOp::Or, 1),
|
||||
"and" => (BinaryOp::And, 2),
|
||||
"==" => (BinaryOp::Equal, 3),
|
||||
"!=" => (BinaryOp::NotEqual, 3),
|
||||
"<" => (BinaryOp::Less, 4),
|
||||
"<=" => (BinaryOp::LessOrEqual, 4),
|
||||
">" => (BinaryOp::Greater, 4),
|
||||
">=" => (BinaryOp::GreaterOrEqual, 4),
|
||||
"+" => (BinaryOp::Add, 5),
|
||||
"-" => (BinaryOp::Subtract, 5),
|
||||
"*" => (BinaryOp::Multiply, 6),
|
||||
"/" => (BinaryOp::Divide, 6),
|
||||
_ => return None,
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,546 @@
|
||||
use super::*;
|
||||
use crate::language::ParseLimits;
|
||||
use budget::{Budget, Limits};
|
||||
|
||||
fn limits() -> Limits {
|
||||
Limits::source8(ParseLimits::UNLIMITED)
|
||||
}
|
||||
fn budget() -> Budget {
|
||||
Budget::new(limits()).unwrap()
|
||||
}
|
||||
fn expression(source: &str) -> Expression {
|
||||
match parse(source, &mut budget()).unwrap() {
|
||||
Binding::Expression(value) => value,
|
||||
Binding::Unbound(_) => panic!("expected expression"),
|
||||
}
|
||||
}
|
||||
fn number(value: &Expression) -> String {
|
||||
let ExpressionKind::Number(exact) = &value.kind else {
|
||||
panic!("expected Number");
|
||||
};
|
||||
exact.canonical_literal()
|
||||
}
|
||||
|
||||
fn binary_children(value: Expression, expected: BinaryOp) -> (Expression, Expression) {
|
||||
let ExpressionKind::Binary { op, left, right } = value.kind else {
|
||||
panic!("expected Binary {expected:?}");
|
||||
};
|
||||
assert_eq!(op, expected);
|
||||
(*left, *right)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mixed_precedence_and_grouping_have_independent_expected_child_topology() {
|
||||
let (one, product) = binary_children(expression("1 + 2 * 3"), BinaryOp::Add);
|
||||
assert_eq!(number(&one), "1");
|
||||
let (two, three) = binary_children(product, BinaryOp::Multiply);
|
||||
assert_eq!(
|
||||
(number(&two), number(&three)),
|
||||
("2".to_owned(), "3".to_owned())
|
||||
);
|
||||
|
||||
let (conjunction, last) =
|
||||
binary_children(expression("not(false) and true or false"), BinaryOp::Or);
|
||||
assert_eq!(last.kind, ExpressionKind::Boolean(false));
|
||||
let (negated, middle) = binary_children(conjunction, BinaryOp::And);
|
||||
assert_eq!(middle.kind, ExpressionKind::Boolean(true));
|
||||
let ExpressionKind::Unary { op, operand } = negated.kind else {
|
||||
panic!("expected Not");
|
||||
};
|
||||
assert_eq!(op, UnaryOp::Not);
|
||||
assert_eq!(operand.kind, ExpressionKind::Boolean(false));
|
||||
|
||||
let (negative, two) = binary_children(expression("-1 * 2"), BinaryOp::Multiply);
|
||||
assert_eq!(number(&two), "2");
|
||||
let ExpressionKind::Unary { op, operand } = negative.kind else {
|
||||
panic!("expected Negate");
|
||||
};
|
||||
assert_eq!(op, UnaryOp::Negate);
|
||||
assert_eq!(number(&operand), "1");
|
||||
|
||||
let (quotient, three) = binary_children(expression("1 / 2 * 3"), BinaryOp::Multiply);
|
||||
assert_eq!(number(&three), "3");
|
||||
let (one, two) = binary_children(quotient, BinaryOp::Divide);
|
||||
assert_eq!(
|
||||
(number(&one), number(&two)),
|
||||
("1".to_owned(), "2".to_owned())
|
||||
);
|
||||
|
||||
let (one, grouped) = binary_children(expression("1 + (2 + 3)"), BinaryOp::Add);
|
||||
assert_eq!(number(&one), "1");
|
||||
assert!(grouped.grouped);
|
||||
let (two, three) = binary_children(grouped, BinaryOp::Add);
|
||||
assert_eq!(
|
||||
(number(&two), number(&three)),
|
||||
("2".to_owned(), "3".to_owned())
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn flat_binary_depth_and_malformed_constructor_retain_bounded_completed_children() {
|
||||
let flat = |count: usize| vec!["true"; count].join(" and ");
|
||||
let deep = flat(128);
|
||||
let mut tree = expression(&deep);
|
||||
assert_eq!(tree.depth, 128);
|
||||
// Independently verify the complete left-associated shape, not just depth.
|
||||
for _ in 1..128 {
|
||||
let (left, right) = binary_children(tree, BinaryOp::And);
|
||||
assert_eq!(right.kind, ExpressionKind::Boolean(true));
|
||||
tree = left;
|
||||
}
|
||||
assert_eq!(tree.kind, ExpressionKind::Boolean(true));
|
||||
assert!(
|
||||
parse(&flat(129), &mut budget())
|
||||
.unwrap_err()
|
||||
.message
|
||||
.contains("logical depth")
|
||||
);
|
||||
|
||||
// The first argument is already a complete depth128 tree when parsing the
|
||||
// second fails. Refusal tears down the held child without building Sum.
|
||||
let malformed = format!("sum({deep}, @)");
|
||||
let failure = parse(&malformed, &mut budget()).unwrap_err();
|
||||
assert_eq!(
|
||||
failure.message,
|
||||
"Expected a valid reference or parameter name."
|
||||
);
|
||||
assert_eq!(&malformed[failure.span.start..failure.span.end], ")");
|
||||
assert_eq!(number(&expression("1")), "1");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_parent_shape_rejects_depth129_and_cleans_children_on_128k_stack() {
|
||||
std::thread::Builder::new()
|
||||
.name("analysis-syntax-rejection-128k".into())
|
||||
.stack_size(128 * 1024)
|
||||
.spawn(|| {
|
||||
// Rotate through every recursive syntax shape, so the rejected
|
||||
// parent's complete child tree also exercises every cleanup arm.
|
||||
let wrap = |shape, child: &str| match shape {
|
||||
0 => format!("abs({child})"),
|
||||
1 => format!("({child}) + 1"),
|
||||
2 => format!("if(true, {child}, 0)"),
|
||||
3 => format!("[{child}]"),
|
||||
4 => format!("@f(a: {child})"),
|
||||
5 => format!("sum({child}, 0)"),
|
||||
6 => format!("power({child}, 1)"),
|
||||
7 => format!("as_kind(@k, {child})"),
|
||||
_ => unreachable!(),
|
||||
};
|
||||
let mut deep = "1".to_owned();
|
||||
for layer in 0..127 {
|
||||
deep = wrap(layer % 8, &deep);
|
||||
}
|
||||
assert_eq!(expression(&deep).depth, 128);
|
||||
for shape in 0..8 {
|
||||
let source = wrap(shape, &deep);
|
||||
let failure = parse(&source, &mut budget()).unwrap_err();
|
||||
assert_eq!(failure.message, "Expression logical depth exceeds 128.");
|
||||
assert_eq!(
|
||||
failure.span,
|
||||
Span {
|
||||
start: 0,
|
||||
end: source.len()
|
||||
}
|
||||
);
|
||||
assert_eq!(number(&expression("1")), "1");
|
||||
}
|
||||
})
|
||||
.unwrap()
|
||||
.join()
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn significant_ratio_and_quantity_trivia_preserve_original_spans() {
|
||||
let source = "ratio // explanation café\n ( - // sign\n 3, // denominator\n 4 ) // measurement\n [@millisecond]";
|
||||
let parsed = expression(source);
|
||||
assert_eq!(
|
||||
parsed.span,
|
||||
Span {
|
||||
start: 0,
|
||||
end: source.len()
|
||||
}
|
||||
);
|
||||
let literal = parsed.literal.as_ref().unwrap();
|
||||
assert!(source[literal.span.start..literal.span.end].contains("// denominator"));
|
||||
assert_eq!(
|
||||
literal
|
||||
.tokens
|
||||
.iter()
|
||||
.map(|span| &source[span.start..span.end])
|
||||
.collect::<Vec<_>>(),
|
||||
["ratio", "(", "-", "3", ",", "4", ")"]
|
||||
);
|
||||
let ExpressionKind::Quantity { magnitude, unit } = parsed.kind else {
|
||||
panic!("expected Quantity");
|
||||
};
|
||||
assert_eq!(magnitude.canonical_literal(), "ratio(-3, 4)");
|
||||
assert_eq!(unit.name, "millisecond");
|
||||
assert_eq!(&source[unit.span.start..unit.span.end], "millisecond");
|
||||
let mut renamed = source.to_owned();
|
||||
renamed.replace_range(unit.span.start..unit.span.end, "ms");
|
||||
assert_eq!(renamed, source.replacen("millisecond", "ms", 1));
|
||||
assert_eq!(
|
||||
number(&expression("ratio (1, // rationale\n 2)")),
|
||||
"ratio(1, 2)"
|
||||
);
|
||||
for invalid in [
|
||||
"1 e - 2",
|
||||
"1e // x\n -2",
|
||||
"1 . 2",
|
||||
"ratio(1 + 2, 3)",
|
||||
"ratio(1, -2)",
|
||||
"ratio(+1, 2)",
|
||||
"ratio(1.0, 2)",
|
||||
"ratio(1, 0)",
|
||||
] {
|
||||
assert!(parse(invalid, &mut budget()).is_err(), "{invalid}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn raw_numeric_lexing_preserves_exact_atoms_and_operator_boundaries() {
|
||||
let source = "1-2 1e-2 ratio(-1,2) -(1) <= >= == !=";
|
||||
let tokens = lex::tokens(source, &mut budget()).unwrap();
|
||||
let text: Vec<_> = tokens
|
||||
.iter()
|
||||
.map(|t| &source[t.span.start..t.span.end])
|
||||
.collect();
|
||||
assert_eq!(
|
||||
text,
|
||||
[
|
||||
"1", "-", "2", "1e-2", "ratio", "(", "-", "1", ",", "2", ")", "-", "(", "1", ")", "<=",
|
||||
">=", "==", "!="
|
||||
]
|
||||
);
|
||||
let huge = "9".repeat(400);
|
||||
assert_eq!(
|
||||
lex::tokens(&huge, &mut budget()).unwrap()[0].class,
|
||||
lex::Class::Number
|
||||
);
|
||||
assert_eq!(number(&expression(&huge)), huge);
|
||||
for invalid in ["1e", "1e+", "1_0", "0x1", "1.2.3"] {
|
||||
assert!(lex::tokens(invalid, &mut budget()).is_err(), "{invalid}");
|
||||
}
|
||||
let quoted = "\"quoted\\\" café\"";
|
||||
let tokens = lex::tokens(quoted, &mut budget()).unwrap();
|
||||
assert_eq!(tokens[0].class, lex::Class::String);
|
||||
assert_eq!("ed[tokens[0].span.start..tokens[0].span.end], quoted);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unary_literals_precedence_and_comparison_children_keep_distinct_trees() {
|
||||
assert_eq!(number(&expression("ratio(-1, 1)")), "ratio(-1, 1)");
|
||||
let negative = expression("-(1)");
|
||||
assert!(matches!(
|
||||
negative.kind,
|
||||
ExpressionKind::Unary {
|
||||
op: UnaryOp::Negate,
|
||||
..
|
||||
}
|
||||
));
|
||||
let left = expression("(1 - 2) - 3");
|
||||
let right = expression("1 - (2 - 3)");
|
||||
let ExpressionKind::Binary {
|
||||
left, right: last, ..
|
||||
} = left.kind
|
||||
else {
|
||||
panic!();
|
||||
};
|
||||
assert!(matches!(
|
||||
left.kind,
|
||||
ExpressionKind::Binary {
|
||||
op: BinaryOp::Subtract,
|
||||
..
|
||||
}
|
||||
));
|
||||
assert_eq!(number(&last), "3");
|
||||
let ExpressionKind::Binary {
|
||||
left: first, right, ..
|
||||
} = right.kind
|
||||
else {
|
||||
panic!();
|
||||
};
|
||||
assert_eq!(number(&first), "1");
|
||||
assert!(matches!(
|
||||
right.kind,
|
||||
ExpressionKind::Binary {
|
||||
op: BinaryOp::Subtract,
|
||||
..
|
||||
}
|
||||
));
|
||||
for valid in [
|
||||
"(1 < 2) == true",
|
||||
"(true == false) == true",
|
||||
"true == (1 < 2)",
|
||||
"1 + 2 * 3",
|
||||
"not(false) and true or false",
|
||||
] {
|
||||
parse(valid, &mut budget()).unwrap();
|
||||
}
|
||||
for invalid in [
|
||||
"1 < 2 == true",
|
||||
"true == false == true",
|
||||
"1 < 2 < 3",
|
||||
"true == 1 < 2",
|
||||
] {
|
||||
assert!(parse(invalid, &mut budget()).is_err(), "{invalid}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_expression_shape_and_exact_constructor_arity_is_represented() {
|
||||
let tree = expression("if(true, sum([@p, $x], 0), as_kind(@duration, power(abs(-(2)), -2)))");
|
||||
let ExpressionKind::If {
|
||||
condition,
|
||||
when_true,
|
||||
when_false,
|
||||
} = tree.kind
|
||||
else {
|
||||
panic!();
|
||||
};
|
||||
assert_eq!(condition.kind, ExpressionKind::Boolean(true));
|
||||
let ExpressionKind::Sum { values, initial } = when_true.kind else {
|
||||
panic!();
|
||||
};
|
||||
assert_eq!(number(&initial), "0");
|
||||
let ExpressionKind::List(values) = values.kind else {
|
||||
panic!();
|
||||
};
|
||||
assert!(matches!(&values[0].kind, ExpressionKind::Property(r) if r.name == "p"));
|
||||
assert!(matches!(&values[1].kind, ExpressionKind::Parameter(r) if r.name == "x"));
|
||||
let ExpressionKind::AsKind { kind, value } = when_false.kind else {
|
||||
panic!();
|
||||
};
|
||||
assert_eq!(kind.name, "duration");
|
||||
assert!(matches!(
|
||||
value.kind,
|
||||
ExpressionKind::Power { exponent: -2, .. }
|
||||
));
|
||||
assert!(matches!(expression("[]").kind, ExpressionKind::List(v) if v.is_empty()));
|
||||
assert!(
|
||||
matches!(expression("@zero()").kind, ExpressionKind::Call { arguments, .. } if arguments.is_empty())
|
||||
);
|
||||
assert!(matches!(
|
||||
parse(" unbound // pending", &mut budget()).unwrap(),
|
||||
Binding::Unbound(_)
|
||||
));
|
||||
for invalid in [
|
||||
"sum([1])",
|
||||
"sum([1], 0, 2)",
|
||||
"if(true, 1)",
|
||||
"abs()",
|
||||
"not(true, false)",
|
||||
"power(2, 17)",
|
||||
"power(2, 1.0)",
|
||||
"as_kind(duration, 1)",
|
||||
"[1,]",
|
||||
"[1 2]",
|
||||
"(1+2)[@unit]",
|
||||
] {
|
||||
assert!(parse(invalid, &mut budget()).is_err(), "{invalid}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn repeated_call_argument_occurrences_have_distinct_original_spans() {
|
||||
let source = "@combine(a: @p, b: 2) + @combine(a: @q, b: 4)";
|
||||
let tree = expression(source);
|
||||
let ExpressionKind::Binary { left, right, .. } = tree.kind else {
|
||||
panic!();
|
||||
};
|
||||
let ExpressionKind::Call {
|
||||
definition: first,
|
||||
arguments: a,
|
||||
} = left.kind
|
||||
else {
|
||||
panic!();
|
||||
};
|
||||
let ExpressionKind::Call {
|
||||
definition: second,
|
||||
arguments: b,
|
||||
} = right.kind
|
||||
else {
|
||||
panic!();
|
||||
};
|
||||
assert_eq!(first.name, second.name);
|
||||
assert_ne!(first.span, second.span);
|
||||
assert_eq!(a[0].parameter.name, b[0].parameter.name);
|
||||
assert_ne!(a[0].parameter.span, b[0].parameter.span);
|
||||
for argument in a.iter().chain(&b) {
|
||||
assert_eq!(
|
||||
&source[argument.parameter.span.start..argument.parameter.span.end],
|
||||
argument.parameter.name
|
||||
);
|
||||
}
|
||||
assert!(
|
||||
parse("@combine(a: 1, a: 2)", &mut budget())
|
||||
.unwrap_err()
|
||||
.message
|
||||
.contains("Duplicate")
|
||||
);
|
||||
assert!(parse("@combine(a: 1, b:)", &mut budget()).is_err());
|
||||
// Resolution to owner-qualified ParameterId and actual source rewrites are
|
||||
// deliberately a later stage; this oracle establishes unique syntax spans.
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn budgets_aggregate_across_fragments_and_latch_numeric_exhaustion() {
|
||||
let mut first = budget();
|
||||
parse("ratio(1, 3)", &mut first).unwrap();
|
||||
let cost = first.numeric_units();
|
||||
assert!(cost > 0);
|
||||
let mut settings = limits();
|
||||
settings.numeric_units = cost;
|
||||
let mut shared = Budget::new(settings).unwrap();
|
||||
parse("ratio (1, // same numeric cost\n 3)", &mut shared).unwrap();
|
||||
assert_eq!(shared.numeric_units(), cost);
|
||||
let failure = parse("2", &mut shared).unwrap_err();
|
||||
let usage = shared.usage;
|
||||
assert_eq!(parse("unbound", &mut shared).unwrap_err(), failure);
|
||||
assert_eq!(shared.usage, usage);
|
||||
parse("2", &mut budget()).unwrap();
|
||||
|
||||
let mut settings = limits();
|
||||
settings.entries = 2;
|
||||
let mut shared = Budget::new(settings).unwrap();
|
||||
parse("true", &mut shared).unwrap();
|
||||
parse("false", &mut shared).unwrap();
|
||||
assert!(
|
||||
parse("true", &mut shared)
|
||||
.unwrap_err()
|
||||
.message
|
||||
.contains("entries")
|
||||
);
|
||||
assert_eq!(shared.usage.entries, 2);
|
||||
let mut settings = limits();
|
||||
settings.references = 1;
|
||||
let mut shared = Budget::new(settings).unwrap();
|
||||
parse("@one", &mut shared).unwrap();
|
||||
assert!(
|
||||
parse("$two", &mut shared)
|
||||
.unwrap_err()
|
||||
.message
|
||||
.contains("references")
|
||||
);
|
||||
assert_eq!(shared.usage.references, 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn byte_token_frame_logical_and_list_boundaries_have_nearby_successes() {
|
||||
let mut settings = limits();
|
||||
settings.bytes = 4;
|
||||
let mut shared = Budget::new(settings).unwrap();
|
||||
parse("true", &mut shared).unwrap();
|
||||
assert!(
|
||||
parse(" ", &mut shared)
|
||||
.unwrap_err()
|
||||
.message
|
||||
.contains("bytes")
|
||||
);
|
||||
assert_eq!(shared.usage.bytes, 4);
|
||||
let mut settings = limits();
|
||||
settings.tokens = 2;
|
||||
let mut shared = Budget::new(settings).unwrap();
|
||||
parse("true ", &mut shared).unwrap();
|
||||
assert!(
|
||||
parse("// note", &mut shared)
|
||||
.unwrap_err()
|
||||
.message
|
||||
.contains("tokens")
|
||||
);
|
||||
assert_eq!(shared.usage.tokens, 2);
|
||||
let nested = |depth: usize| format!("{}true{}", "(".repeat(depth), ")".repeat(depth));
|
||||
let mut shared = budget();
|
||||
assert_eq!(
|
||||
match parse(&nested(256), &mut shared).unwrap() {
|
||||
Binding::Expression(e) => e.depth,
|
||||
_ => 0,
|
||||
},
|
||||
1
|
||||
);
|
||||
assert_eq!(shared.usage.deepest_frame, 256);
|
||||
assert!(
|
||||
parse(&nested(257), &mut budget())
|
||||
.unwrap_err()
|
||||
.message
|
||||
.contains("frames")
|
||||
);
|
||||
let unary = |depth: usize| format!("{}true{}", "not(".repeat(depth - 1), ")".repeat(depth - 1));
|
||||
assert_eq!(expression(&unary(128)).depth, 128);
|
||||
assert!(
|
||||
parse(&unary(129), &mut budget())
|
||||
.unwrap_err()
|
||||
.message
|
||||
.contains("logical depth")
|
||||
);
|
||||
let list = |count: usize| format!("[{}]", vec!["true"; count].join(","));
|
||||
parse(&list(1024), &mut budget()).unwrap();
|
||||
assert!(parse(&list(1025), &mut budget()).is_err());
|
||||
let lowered = Limits::source8(ParseLimits {
|
||||
max_source_bytes: 8,
|
||||
max_graph_objects: 3,
|
||||
max_records: 5,
|
||||
max_step_references: 2,
|
||||
});
|
||||
assert_eq!(
|
||||
(
|
||||
lowered.bytes,
|
||||
lowered.tokens,
|
||||
lowered.entries,
|
||||
lowered.references
|
||||
),
|
||||
(8, 8, 5, 2)
|
||||
);
|
||||
let mut above = limits();
|
||||
above.frames += 1;
|
||||
assert!(Budget::new(above).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn partial_wide_and_deep_input_cleanup_does_not_poison_a_fresh_parse() {
|
||||
let source = "@f(a: if(true, [ratio (1, //why\n 2), @p], sum([1, 2], 0)), b: power(2, -3))";
|
||||
let tokens = lex::tokens(source, &mut budget()).unwrap();
|
||||
for token in tokens.iter().filter(|token| {
|
||||
matches!(
|
||||
&source[token.span.start..token.span.end],
|
||||
"(" | "[" | "," | ":" | "@"
|
||||
)
|
||||
}) {
|
||||
assert!(parse(&source[..token.span.end], &mut budget()).is_err());
|
||||
assert_eq!(number(&expression("ratio(2, 3)")), "ratio(2, 3)");
|
||||
}
|
||||
for malformed in [
|
||||
format!("{}true", "(".repeat(256)),
|
||||
format!("[{}", vec!["true"; 1024].join(",")),
|
||||
"-".repeat(10_000),
|
||||
] {
|
||||
assert!(parse(&malformed, &mut budget()).is_err());
|
||||
parse("true", &mut budget()).unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn public_source_headers_and_existing_numeric_token_controls_are_unchanged() {
|
||||
assert!(crate::language::parse("arcadia 8; project p \"P\" {}").is_err());
|
||||
for accepted in ["-1.5", "1e-2", "0", "-0"] {
|
||||
let tokens = crate::language::tokenize(accepted);
|
||||
assert_eq!(tokens.len(), 1);
|
||||
assert_eq!(tokens[0].class, crate::language::TokenClass::Number);
|
||||
assert_eq!(
|
||||
tokens[0].span,
|
||||
Span {
|
||||
start: 0,
|
||||
end: accepted.len()
|
||||
}
|
||||
);
|
||||
}
|
||||
for rejected in ["+1", "1_0", "0x1", "1e"] {
|
||||
assert!(
|
||||
crate::language::tokenize(rejected)
|
||||
.iter()
|
||||
.any(|t| t.class == crate::language::TokenClass::Error)
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,316 @@
|
||||
//! Simultaneous typed token edits. This is a staged plan, not source acceptance:
|
||||
//! the bundle owner must merge ordinary edits, reparse/recompile the exact bytes,
|
||||
//! admit once and compare the complete intended Project before installation.
|
||||
use super::index::{Index, Location, OccurrenceKey, checked_source};
|
||||
use super::lower::Target;
|
||||
use super::{Budget, Error, Span, error};
|
||||
use std::collections::{BTreeMap, BTreeSet};
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
struct Edit {
|
||||
key: OccurrenceKey,
|
||||
location: Location,
|
||||
}
|
||||
#[derive(Debug)]
|
||||
pub(super) struct Plan<'i, 's> {
|
||||
index: &'i Index<'s>,
|
||||
names: BTreeMap<Target, String>,
|
||||
edits: Vec<Edit>,
|
||||
}
|
||||
impl<'i, 's> Plan<'i, 's> {
|
||||
/// All names are the desired final names. Validate the final namespaces,
|
||||
/// rather than applying one rename at a time: alias/parameter swaps are legal.
|
||||
pub fn renames(
|
||||
index: &'i Index<'s>,
|
||||
renames: &BTreeMap<Target, String>,
|
||||
budget: &Budget,
|
||||
) -> Result<Self, Error> {
|
||||
let plan = Self::prepare(index, renames, budget)?;
|
||||
plan.validate(index.sources(), budget)?;
|
||||
plan.output_lengths(index.sources(), budget)?;
|
||||
Ok(plan)
|
||||
}
|
||||
|
||||
fn validate_names(
|
||||
index: &Index<'_>,
|
||||
renames: &BTreeMap<Target, String>,
|
||||
budget: &Budget,
|
||||
) -> Result<(), Error> {
|
||||
budget.active()?;
|
||||
budget.lowering_entries(renames.len(), Span::default())?;
|
||||
let mut bytes = 0usize;
|
||||
for (target, name) in renames {
|
||||
if !index.names().contains_key(target) {
|
||||
return Err(error(
|
||||
Span::default(),
|
||||
"Rename has no qualified source target.",
|
||||
));
|
||||
}
|
||||
if !crate::valid_alias(name) {
|
||||
return Err(error(
|
||||
Span::default(),
|
||||
"Invalid alias or scoped parameter name.",
|
||||
));
|
||||
}
|
||||
bytes = bytes
|
||||
.checked_add(name.len())
|
||||
.ok_or_else(|| error(Span::default(), "Rename size overflow."))?;
|
||||
budget.index_bytes(bytes, Span::default())?;
|
||||
}
|
||||
let mut final_names = BTreeSet::new();
|
||||
for (target, original) in index.names() {
|
||||
let name = renames.get(target).unwrap_or(original);
|
||||
let scope = match target {
|
||||
Target::Global(_) => None,
|
||||
Target::Parameter { calculation, .. } => Some(*calculation),
|
||||
};
|
||||
budget.lowering_entries(final_names.len() + 1, Span::default())?;
|
||||
if !final_names.insert((scope, name.as_str())) {
|
||||
return Err(error(
|
||||
Span::default(),
|
||||
"Rename creates a duplicate name in its namespace.",
|
||||
));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn prepare(
|
||||
index: &'i Index<'s>,
|
||||
renames: &BTreeMap<Target, String>,
|
||||
budget: &Budget,
|
||||
) -> Result<Self, Error> {
|
||||
// Validate record/name storage before copying any owned final names.
|
||||
Self::validate_names(index, renames, budget)?;
|
||||
let mut edits = Vec::new();
|
||||
for (key, location) in index.occurrences() {
|
||||
if renames
|
||||
.get(&key.target)
|
||||
.is_some_and(|name| index.names().get(&key.target) != Some(name))
|
||||
{
|
||||
budget.lowering_occurrences(edits.len() + 1, location.span)?;
|
||||
edits.push(Edit {
|
||||
key: key.clone(),
|
||||
location: *location,
|
||||
});
|
||||
}
|
||||
}
|
||||
edits.sort_by_key(|edit| {
|
||||
(
|
||||
edit.location.file,
|
||||
edit.location.span.start,
|
||||
edit.location.span.end,
|
||||
)
|
||||
});
|
||||
Ok(Self {
|
||||
index,
|
||||
names: renames.clone(),
|
||||
edits,
|
||||
})
|
||||
}
|
||||
|
||||
pub fn edit_count(&self) -> usize {
|
||||
self.edits.len()
|
||||
}
|
||||
|
||||
/// Recheck the complete original witness and complete rename intent.
|
||||
/// A changed unrelated file is stale too. This does not construct output.
|
||||
fn validate(&self, current: &BTreeMap<usize, String>, budget: &Budget) -> Result<(), Error> {
|
||||
budget.active()?;
|
||||
if current != self.index.sources() {
|
||||
return Err(error(
|
||||
Span::default(),
|
||||
"Source index is stale: original file set or bytes changed.",
|
||||
));
|
||||
}
|
||||
budget.lowering_entries(current.len(), Span::default())?;
|
||||
budget.lowering_occurrences(self.edits.len(), Span::default())?;
|
||||
let mut previous: Option<Location> = None;
|
||||
let mut seen = BTreeSet::new();
|
||||
for edit in &self.edits {
|
||||
let at = edit.location;
|
||||
if self.index.occurrences().get(&edit.key) != Some(&at) || !seen.insert(&edit.key) {
|
||||
return Err(error(at.span, "Forged or duplicate edit occurrence."));
|
||||
}
|
||||
let old = checked_source(current, at)?;
|
||||
if self
|
||||
.index
|
||||
.names()
|
||||
.get(&edit.key.target)
|
||||
.is_none_or(|name| name != old)
|
||||
{
|
||||
return Err(error(at.span, "Stale original token spelling."));
|
||||
}
|
||||
self.names
|
||||
.get(&edit.key.target)
|
||||
.ok_or_else(|| error(at.span, "Edit has no final target name."))?;
|
||||
if previous.is_some_and(|prior| {
|
||||
prior.file > at.file || (prior.file == at.file && prior.span.end > at.span.start)
|
||||
}) {
|
||||
return Err(error(at.span, "Overlapping or unordered source edits."));
|
||||
}
|
||||
previous = Some(at);
|
||||
}
|
||||
for (key, at) in self.index.occurrences() {
|
||||
let required = self
|
||||
.names
|
||||
.get(&key.target)
|
||||
.is_some_and(|name| self.index.names().get(&key.target) != Some(name));
|
||||
if required != seen.contains(key) {
|
||||
return Err(error(
|
||||
at.span,
|
||||
"Edit set differs from the complete qualified rename plan.",
|
||||
));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Standalone output preflight, after ownership validation. Composition
|
||||
/// defers this hypothetical typed-only size to its future combined emitter.
|
||||
fn output_lengths(
|
||||
&self,
|
||||
current: &BTreeMap<usize, String>,
|
||||
budget: &Budget,
|
||||
) -> Result<BTreeMap<usize, usize>, Error> {
|
||||
let mut lengths: BTreeMap<_, _> = current
|
||||
.iter()
|
||||
.map(|(&file, source)| (file, source.len()))
|
||||
.collect();
|
||||
for edit in &self.edits {
|
||||
let at = edit.location;
|
||||
let length = lengths.get_mut(&at.file).expect("validated edit file");
|
||||
*length = length
|
||||
.checked_sub(at.span.end - at.span.start)
|
||||
.and_then(|size| size.checked_add(self.names[&edit.key.target].len()))
|
||||
.ok_or_else(|| error(at.span, "Updated source size overflow."))?;
|
||||
}
|
||||
let mut total = 0usize;
|
||||
for length in lengths.values() {
|
||||
total = total
|
||||
.checked_add(*length)
|
||||
.ok_or_else(|| error(Span::default(), "Updated bundle size overflow."))?;
|
||||
budget.index_bytes(total, Span::default())?;
|
||||
}
|
||||
Ok(lengths)
|
||||
}
|
||||
|
||||
pub fn apply(
|
||||
&self,
|
||||
current: &BTreeMap<usize, String>,
|
||||
budget: &Budget,
|
||||
) -> Result<BTreeMap<usize, String>, Error> {
|
||||
self.validate(current, budget)?;
|
||||
let lengths = self.output_lengths(current, budget)?;
|
||||
let mut result = BTreeMap::new();
|
||||
let mut edits = self.edits.iter().peekable();
|
||||
for (&file, source) in current {
|
||||
let mut output = String::with_capacity(lengths[&file]);
|
||||
let mut start = 0;
|
||||
while edits.peek().is_some_and(|edit| edit.location.file == file) {
|
||||
let edit = edits.next().expect("peeked edit");
|
||||
output.push_str(&source[start..edit.location.span.start]);
|
||||
output.push_str(&self.names[&edit.key.target]);
|
||||
start = edit.location.span.end;
|
||||
}
|
||||
output.push_str(&source[start..]);
|
||||
result.insert(file, output);
|
||||
}
|
||||
Ok(result)
|
||||
}
|
||||
}
|
||||
|
||||
/// Private typed-only composition planning. The caller must supply its inherited
|
||||
/// parse Budget; this type keeps that same immutable budget through export.
|
||||
/// It does not establish the future complete bundle/file-table/parse-session
|
||||
/// witness. In particular, an Index currently does not store its parse profile.
|
||||
pub(super) struct Composition<'b, 'i, 's> {
|
||||
plan: Plan<'i, 's>,
|
||||
budget: &'b Budget,
|
||||
}
|
||||
impl std::fmt::Debug for Composition<'_, '_, '_> {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.debug_struct("Composition")
|
||||
.field("plan", &self.plan)
|
||||
.finish_non_exhaustive()
|
||||
}
|
||||
}
|
||||
impl<'b, 'i, 's> Composition<'b, 'i, 's> {
|
||||
pub fn renames(
|
||||
index: &'i Index<'s>,
|
||||
renames: &BTreeMap<Target, String>,
|
||||
inherited: &'b Budget,
|
||||
) -> Result<Self, Error> {
|
||||
let plan = Plan::prepare(index, renames, inherited)?;
|
||||
plan.validate(index.sources(), inherited)?;
|
||||
Ok(Self {
|
||||
plan,
|
||||
budget: inherited,
|
||||
})
|
||||
}
|
||||
|
||||
/// Export the entire validated plan against exact original numeric file keys
|
||||
/// and bytes. There is no output allocation, application or subset-accept API.
|
||||
/// A future collector must check this actual index witness and the complete
|
||||
/// combined output bounds before applying either producer's edits once.
|
||||
pub fn original_edits(
|
||||
&self,
|
||||
current: &BTreeMap<usize, String>,
|
||||
) -> Result<OriginalEdits<'_, 'i, 's>, Error> {
|
||||
Plan::validate_names(self.plan.index, &self.plan.names, self.budget)?;
|
||||
self.plan.validate(current, self.budget)?;
|
||||
Ok(OriginalEdits { plan: &self.plan })
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub(super) struct OriginalEdits<'p, 'i, 's> {
|
||||
plan: &'p Plan<'i, 's>,
|
||||
}
|
||||
impl<'s> OriginalEdits<'_, '_, 's> {
|
||||
pub fn index(&self) -> &Index<'s> {
|
||||
self.plan.index
|
||||
}
|
||||
pub fn len(&self) -> usize {
|
||||
self.plan.edits.len()
|
||||
}
|
||||
pub fn is_empty(&self) -> bool {
|
||||
self.plan.edits.is_empty()
|
||||
}
|
||||
pub fn iter(&self) -> impl ExactSizeIterator<Item = OriginalEdit<'_>> {
|
||||
self.plan.edits.iter().map(|edit| OriginalEdit {
|
||||
key: &edit.key,
|
||||
location: edit.location,
|
||||
original: &self.plan.index.sources()[&edit.location.file]
|
||||
[edit.location.span.start..edit.location.span.end],
|
||||
replacement: &self.plan.names[&edit.key.target],
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// A borrowed inspection record, never independent edit authority. Only an
|
||||
/// intact OriginalEdits batch can carry this producer's complete rename intent.
|
||||
#[derive(Debug)]
|
||||
pub(super) struct OriginalEdit<'p> {
|
||||
key: &'p OccurrenceKey,
|
||||
location: Location,
|
||||
original: &'p str,
|
||||
replacement: &'p str,
|
||||
}
|
||||
impl OriginalEdit<'_> {
|
||||
pub fn key(&self) -> &OccurrenceKey {
|
||||
self.key
|
||||
}
|
||||
pub fn location(&self) -> Location {
|
||||
self.location
|
||||
}
|
||||
pub fn original(&self) -> &str {
|
||||
self.original
|
||||
}
|
||||
pub fn replacement(&self) -> &str {
|
||||
self.replacement
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
@@ -0,0 +1,744 @@
|
||||
use super::super::budget::Limits;
|
||||
use super::*;
|
||||
use crate::analysis as a;
|
||||
use crate::analysis_numeric::Exact;
|
||||
use crate::language::ParseLimits;
|
||||
use crate::{Id, Layer, Project};
|
||||
|
||||
const DEFINITIONS: &str = "// 雪 @f(a:) $a: comment spellings stay exact\r\n\
|
||||
calculation f \"f a b\" id \"00000000-0000-0000-0000-000000000100\" {\r\n\
|
||||
input a id \"00000000-0000-0000-0000-000000000200\" : Number;\r\n\
|
||||
input b id \"00000000-0000-0000-0000-000000000201\" : Number;\r\n\
|
||||
result Number; body $a + $b;\r\n}\r\n\
|
||||
calculation g \"g a b\" id \"00000000-0000-0000-0000-000000000200\" {\r\n\
|
||||
input a id \"00000000-0000-0000-0000-000000000200\" : Number;\r\n\
|
||||
input b id \"00000000-0000-0000-0000-000000000201\" : Number;\r\n\
|
||||
result Number; body $a + $b;\r\n}\r\n";
|
||||
const CALLER: &str = "calculation caller \"Caller\" id \"00000000-0000-0000-0000-000000000300\" {\n\
|
||||
result Number; body @f(b: 2, a: 1) // first 雪 @f(a:)\n\
|
||||
+ @f(a: 3, b: 4) // second\n\
|
||||
+ @g(a: 5, b: 6);\n}\n";
|
||||
fn budget() -> Budget {
|
||||
Budget::new(Limits::source8(ParseLimits::UNLIMITED)).unwrap()
|
||||
}
|
||||
fn global(id: u128) -> Target {
|
||||
Target::Global(Id::from_u128(id))
|
||||
}
|
||||
fn parameter(calculation: u128, parameter: u128) -> Target {
|
||||
Target::Parameter {
|
||||
calculation: Id::from_u128(calculation),
|
||||
parameter: a::ParameterId(Id::from_u128(parameter)),
|
||||
}
|
||||
}
|
||||
fn sources() -> BTreeMap<usize, String> {
|
||||
BTreeMap::from([(11, DEFINITIONS.into()), (23, CALLER.into())])
|
||||
}
|
||||
fn skeleton() -> Project {
|
||||
let mut project = super::super::model_oracle::project(Layer::Oa);
|
||||
project.definitions.clear();
|
||||
project
|
||||
.elements
|
||||
.retain(|_, element| !element.kind().is_analysis());
|
||||
project
|
||||
}
|
||||
fn binary(left: a::Expr, right: a::Expr) -> a::Expr {
|
||||
a::Expr::Binary {
|
||||
op: a::BinaryOp::Add,
|
||||
left: Box::new(left),
|
||||
right: Box::new(right),
|
||||
}
|
||||
}
|
||||
fn expected(renamed: bool) -> Project {
|
||||
// Independent model construction: no parsed AST, source index, writer or
|
||||
// generated edit participates in this expected complete Project.
|
||||
let mut project = skeleton();
|
||||
let p = |id| a::ParameterId(Id::from_u128(id));
|
||||
for (id, alias, name) in [
|
||||
(0x100, if renamed { "g" } else { "f" }, "f a b"),
|
||||
(0x200, if renamed { "f" } else { "g" }, "g a b"),
|
||||
] {
|
||||
let names = if renamed && id == 0x100 {
|
||||
["b", "a"]
|
||||
} else {
|
||||
["a", "b"]
|
||||
};
|
||||
let body = a::CalculationDefinition {
|
||||
parameters: [(0x200, names[0]), (0x201, names[1])]
|
||||
.into_iter()
|
||||
.map(|(id, name)| a::Parameter {
|
||||
id: p(id),
|
||||
name: name.into(),
|
||||
value_type: a::AnalysisType::Scalar(a::ScalarType::Number),
|
||||
})
|
||||
.collect(),
|
||||
result: a::AnalysisType::Scalar(a::ScalarType::Number),
|
||||
body: a::Binding::Expression(binary(
|
||||
a::Expr::Parameter(p(0x200)),
|
||||
a::Expr::Parameter(p(0x201)),
|
||||
)),
|
||||
};
|
||||
let id = Id::from_u128(id);
|
||||
project.definitions.insert(
|
||||
id,
|
||||
a::Definition {
|
||||
id,
|
||||
alias: alias.into(),
|
||||
name: name.into(),
|
||||
description: String::new(),
|
||||
body: a::DefinitionBody::Calculation(body),
|
||||
},
|
||||
);
|
||||
}
|
||||
let call = |id, x, y| a::Expr::Call {
|
||||
definition: a::DefinitionRef::Local(Id::from_u128(id)),
|
||||
arguments: BTreeMap::from([
|
||||
(p(0x200), a::Expr::Number(Exact::from_integer(x))),
|
||||
(p(0x201), a::Expr::Number(Exact::from_integer(y))),
|
||||
]),
|
||||
};
|
||||
let id = Id::from_u128(0x300);
|
||||
project.definitions.insert(
|
||||
id,
|
||||
a::Definition {
|
||||
id,
|
||||
alias: "caller".into(),
|
||||
name: "Caller".into(),
|
||||
description: String::new(),
|
||||
body: a::DefinitionBody::Calculation(a::CalculationDefinition {
|
||||
parameters: Vec::new(),
|
||||
result: a::AnalysisType::Scalar(a::ScalarType::Number),
|
||||
body: a::Binding::Expression(binary(
|
||||
binary(call(0x100, 1, 2), call(0x100, 3, 4)),
|
||||
call(0x200, 5, 6),
|
||||
)),
|
||||
}),
|
||||
},
|
||||
);
|
||||
project
|
||||
}
|
||||
fn merge(mut project: Project, lowered: super::super::lower::Lowered) -> Project {
|
||||
project.definitions.extend(lowered.definitions);
|
||||
project.elements.extend(lowered.elements);
|
||||
project
|
||||
}
|
||||
fn rename_map() -> BTreeMap<Target, String> {
|
||||
BTreeMap::from([
|
||||
(global(0x100), "g".into()),
|
||||
(global(0x200), "f".into()),
|
||||
(parameter(0x100, 0x200), "b".into()),
|
||||
(parameter(0x100, 0x201), "a".into()),
|
||||
])
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn simultaneous_global_and_scoped_swaps_match_original_token_and_whole_model_oracles() {
|
||||
let sources = sources();
|
||||
let mut work = budget();
|
||||
let (index, lowered) = Index::parse(&skeleton(), &sources, &mut work).unwrap();
|
||||
assert_eq!(merge(skeleton(), lowered), expected(false));
|
||||
let plan = Plan::renames(&index, &rename_map(), &work).unwrap();
|
||||
// List expected edits against the original authored bytes independently of
|
||||
// the index. Full contexts deliberately exclude equal strings/comments.
|
||||
let mut edits = Vec::new();
|
||||
let mut add = |file, context: &str, token: &str, replacement: &str| {
|
||||
let source = &sources[&file];
|
||||
let context_start = source.find(context).unwrap();
|
||||
let start = context_start + context.find(token).unwrap();
|
||||
edits.push((file, start, start + token.len(), replacement.to_owned()));
|
||||
};
|
||||
add(11, "calculation f ", "f", "g");
|
||||
add(11, "calculation g ", "g", "f");
|
||||
add(11, "input a id", "a", "b");
|
||||
add(11, "input b id", "b", "a");
|
||||
add(11, "body $a + $b;", "a", "b");
|
||||
add(11, "body $a + $b;", "b;", "a;");
|
||||
// The last oracle edit above includes ';' to disambiguate 'b' in 'body';
|
||||
// restrict it back to the exact name token for the span oracle.
|
||||
edits.last_mut().unwrap().2 -= 1;
|
||||
edits.last_mut().unwrap().3.pop();
|
||||
for call in ["@f(b: 2, a: 1)", "@f(a: 3, b: 4)"] {
|
||||
add_call_edits(&sources, &mut edits, call);
|
||||
}
|
||||
let start = CALLER.find("@g(a: 5, b: 6)").unwrap() + 1;
|
||||
edits.push((23, start, start + 1, "f".into()));
|
||||
edits.sort_by_key(|edit| (edit.0, edit.1));
|
||||
assert_eq!(plan.edit_count(), 13);
|
||||
assert_eq!(
|
||||
plan.edits
|
||||
.iter()
|
||||
.map(|edit| (
|
||||
edit.location.file,
|
||||
edit.location.span.start,
|
||||
edit.location.span.end,
|
||||
plan.names[&edit.key.target].clone()
|
||||
))
|
||||
.collect::<Vec<_>>(),
|
||||
edits
|
||||
);
|
||||
let mut exact = BTreeMap::new();
|
||||
for (&file, source) in &sources {
|
||||
let mut output = source.clone();
|
||||
for (_, start, end, value) in edits.iter().filter(|edit| edit.0 == file).rev() {
|
||||
output.replace_range(*start..*end, value);
|
||||
}
|
||||
exact.insert(file, output);
|
||||
}
|
||||
let output = plan.apply(&sources, &work).unwrap();
|
||||
assert_eq!(output, exact);
|
||||
assert!(output[&11].contains("// 雪 @f(a:) $a: comment spellings stay exact\r\n"));
|
||||
assert!(output[&23].contains("// first 雪 @f(a:)\n"));
|
||||
assert!(output[&11].contains("\"f a b\""));
|
||||
let (_, lowered) = Index::parse(&skeleton(), &output, &mut budget()).unwrap();
|
||||
let actual = merge(skeleton(), lowered);
|
||||
assert_eq!(actual, expected(true));
|
||||
a::admit(&actual, a::AdmissionLimits::REFERENCE).unwrap();
|
||||
}
|
||||
fn add_call_edits(
|
||||
sources: &BTreeMap<usize, String>,
|
||||
edits: &mut Vec<(usize, usize, usize, String)>,
|
||||
call: &str,
|
||||
) {
|
||||
let start = sources[&23].find(call).unwrap();
|
||||
for (offset, replacement) in [
|
||||
(1, "g"),
|
||||
(call.find("a:").unwrap(), "b"),
|
||||
(call.find("b:").unwrap(), "a"),
|
||||
] {
|
||||
edits.push((23, start + offset, start + offset + 1, replacement.into()));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn alias_edits_preserve_unit_type_override_tokens_and_unrelated_authored_bytes() {
|
||||
let source = include_str!("../lower/fixtures/typed-oa.arcadia")
|
||||
.replace("750 [@millisecond]", "750 // exact 雪\r\n [@millisecond]");
|
||||
let files = BTreeMap::from([(59, source.clone())]);
|
||||
let mut work = budget();
|
||||
let (index, _) = Index::parse(&skeleton(), &files, &mut work).unwrap();
|
||||
let mut expected_project = super::super::model_oracle::project(Layer::Oa);
|
||||
let id = |name: &str| {
|
||||
index
|
||||
.names()
|
||||
.iter()
|
||||
.find(|(target, alias)| matches!(target, Target::Global(_)) && alias.as_str() == name)
|
||||
.map(|(target, _)| *target)
|
||||
.unwrap()
|
||||
};
|
||||
let renames = BTreeMap::from([
|
||||
(id("duration"), "time_kind".into()),
|
||||
(id("millisecond"), "ms_unit".into()),
|
||||
(id("receive_time"), "arrival".into()),
|
||||
]);
|
||||
let plan = Plan::renames(&index, &renames, &work).unwrap();
|
||||
let output = plan.apply(&files, &work).unwrap();
|
||||
let expected_source = source
|
||||
.replace("quantity_kind duration ", "quantity_kind time_kind ")
|
||||
.replace("@duration", "@time_kind")
|
||||
.replace("unit millisecond ", "unit ms_unit ")
|
||||
.replace("@millisecond", "@ms_unit")
|
||||
.replace("oa_property receive_time ", "oa_property arrival ")
|
||||
.replace("@receive_time", "@arrival");
|
||||
assert_eq!(output[&59], expected_source);
|
||||
for definition in expected_project.definitions.values_mut() {
|
||||
if let Some(name) = renames.get(&Target::Global(definition.id)) {
|
||||
definition.alias = name.clone();
|
||||
}
|
||||
}
|
||||
for element in expected_project.elements.values_mut() {
|
||||
if let Some(name) = renames.get(&Target::Global(element.id)) {
|
||||
element.alias = name.clone();
|
||||
}
|
||||
}
|
||||
let (_, lowered) = Index::parse(&skeleton(), &output, &mut budget()).unwrap();
|
||||
assert_eq!(merge(skeleton(), lowered), expected_project);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rename_rejects_unknown_invalid_and_colliding_final_names_but_allows_noop() {
|
||||
let sources = sources();
|
||||
let work = &mut budget();
|
||||
let (index, _) = Index::parse(&skeleton(), &sources, work).unwrap();
|
||||
for renames in [
|
||||
BTreeMap::from([(global(999), "new".into())]),
|
||||
BTreeMap::from([(global(0x100), "bad name".into())]),
|
||||
BTreeMap::from([(global(0x100), "g".into())]),
|
||||
BTreeMap::from([(parameter(0x100, 0x200), "b".into())]),
|
||||
] {
|
||||
assert!(Plan::renames(&index, &renames, work).is_err());
|
||||
}
|
||||
let plan = Plan::renames(&index, &BTreeMap::from([(global(0x100), "f".into())]), work).unwrap();
|
||||
assert_eq!(plan.edit_count(), 0);
|
||||
assert_eq!(plan.apply(&sources, work).unwrap(), sources);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn stale_file_sets_bytes_forged_spans_and_duplicate_edits_fail_before_output() {
|
||||
let sources = sources();
|
||||
let mut work = budget();
|
||||
let (index, _) = Index::parse(&skeleton(), &sources, &mut work).unwrap();
|
||||
for damage in 0..6 {
|
||||
let mut current = sources.clone();
|
||||
let mut plan = Plan::renames(&index, &rename_map(), &work).unwrap();
|
||||
match damage {
|
||||
0 => current
|
||||
.get_mut(&23)
|
||||
.unwrap()
|
||||
.push_str("// unrelated change"),
|
||||
1 => {
|
||||
current.remove(&23);
|
||||
}
|
||||
2 => {
|
||||
current.insert(99, String::new());
|
||||
}
|
||||
3 => plan.edits[0].location.span.start += 1,
|
||||
4 => plan.edits.insert(1, plan.edits[0].clone()),
|
||||
_ => {
|
||||
plan.edits.pop();
|
||||
}
|
||||
}
|
||||
assert!(plan.apply(¤t, &work).is_err(), "damage {damage}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn output_and_plan_limits_are_aggregate_and_do_not_reset_parse_work() {
|
||||
let sources = sources();
|
||||
let mut work = budget();
|
||||
let (index, _) = Index::parse(&skeleton(), &sources, &mut work).unwrap();
|
||||
let usage = work.usage;
|
||||
let numeric = work.numeric_units();
|
||||
let plan = Plan::renames(&index, &rename_map(), &work).unwrap();
|
||||
let output = plan.apply(&sources, &work).unwrap();
|
||||
assert_eq!(work.usage, usage);
|
||||
assert_eq!(work.numeric_units(), numeric);
|
||||
let bytes = output.values().map(String::len).sum();
|
||||
let mut limits = Limits::source8(ParseLimits::UNLIMITED);
|
||||
limits.bytes = bytes;
|
||||
assert!(plan.apply(&sources, &Budget::new(limits).unwrap()).is_ok());
|
||||
limits.bytes -= 1;
|
||||
assert!(plan.apply(&sources, &Budget::new(limits).unwrap()).is_err());
|
||||
limits = Limits::source8(ParseLimits::UNLIMITED);
|
||||
limits.references = 0;
|
||||
limits.entries = 0;
|
||||
assert!(Plan::renames(&index, &rename_map(), &Budget::new(limits).unwrap()).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn composition_exports_complete_borrowed_swap_witnesses_and_empty_noops() {
|
||||
use super::super::index::TokenRole;
|
||||
use super::super::lower::{Child, Field, Role};
|
||||
type Key = (Id, Option<Field>, Option<Vec<Child>>, TokenRole, Target);
|
||||
type Row = (Location, String, String, Key);
|
||||
|
||||
let sources = sources();
|
||||
let mut work = budget();
|
||||
let (index, _) = Index::parse(&skeleton(), &sources, &mut work).unwrap();
|
||||
let usage = work.usage;
|
||||
let numeric = work.numeric_units();
|
||||
let composition = Composition::renames(&index, &rename_map(), &work).unwrap();
|
||||
assert!(std::ptr::eq(composition.budget, &work));
|
||||
// A byte-identical snapshot is valid; records still borrow the actual index.
|
||||
let batch = composition.original_edits(&sources.clone()).unwrap();
|
||||
assert!(std::ptr::eq(batch.index(), &index));
|
||||
assert_eq!(batch.len(), 13);
|
||||
assert!(!batch.is_empty());
|
||||
assert_eq!(batch.iter().len(), 13);
|
||||
|
||||
// Independently authored occurrence identities and full source contexts.
|
||||
// No index offset/path or generated output defines this oracle.
|
||||
let mut expected: Vec<Row> = Vec::new();
|
||||
let mut add = |file, context: &str, prefix: &str, old: &str, new: &str, key: Key| {
|
||||
let start = sources[&file].find(context).unwrap() + prefix.len();
|
||||
assert_eq!(&sources[&file][start..start + old.len()], old);
|
||||
expected.push((
|
||||
Location {
|
||||
file,
|
||||
span: Span {
|
||||
start,
|
||||
end: start + old.len(),
|
||||
},
|
||||
},
|
||||
old.into(),
|
||||
new.into(),
|
||||
key,
|
||||
));
|
||||
};
|
||||
for (id, old, new, context) in [
|
||||
(0x100, "f", "g", "calculation f "),
|
||||
(0x200, "g", "f", "calculation g "),
|
||||
] {
|
||||
add(
|
||||
11,
|
||||
context,
|
||||
"calculation ",
|
||||
old,
|
||||
new,
|
||||
(
|
||||
Id::from_u128(id),
|
||||
None,
|
||||
None,
|
||||
TokenRole::Declaration,
|
||||
global(id),
|
||||
),
|
||||
);
|
||||
}
|
||||
for (id, old, new, context, edge, prefix) in [
|
||||
(0x200, "a", "b", "input a id", Child::Left, "body $"),
|
||||
(0x201, "b", "a", "input b id", Child::Right, "body $a + $"),
|
||||
] {
|
||||
let target = parameter(0x100, id);
|
||||
add(
|
||||
11,
|
||||
context,
|
||||
"input ",
|
||||
old,
|
||||
new,
|
||||
(
|
||||
Id::from_u128(0x100),
|
||||
Some(Field::Input(a::ParameterId(Id::from_u128(id)))),
|
||||
None,
|
||||
TokenRole::Use(Role::ParameterDeclaration),
|
||||
target,
|
||||
),
|
||||
);
|
||||
add(
|
||||
11,
|
||||
"body $a + $b;",
|
||||
prefix,
|
||||
old,
|
||||
new,
|
||||
(
|
||||
Id::from_u128(0x100),
|
||||
Some(Field::Body),
|
||||
Some(vec![edge]),
|
||||
TokenRole::Use(Role::ParameterUse),
|
||||
target,
|
||||
),
|
||||
);
|
||||
}
|
||||
for (context, path) in [
|
||||
("@f(b: 2, a: 1)", vec![Child::Left, Child::Left]),
|
||||
("@f(a: 3, b: 4)", vec![Child::Left, Child::Right]),
|
||||
] {
|
||||
add(
|
||||
23,
|
||||
context,
|
||||
"@",
|
||||
"f",
|
||||
"g",
|
||||
(
|
||||
Id::from_u128(0x300),
|
||||
Some(Field::Body),
|
||||
Some(path.clone()),
|
||||
TokenRole::Use(Role::CallTarget),
|
||||
global(0x100),
|
||||
),
|
||||
);
|
||||
for (id, old, new) in [(0x200, "a", "b"), (0x201, "b", "a")] {
|
||||
let offset = context.find(&format!("{old}:")).unwrap();
|
||||
add(
|
||||
23,
|
||||
context,
|
||||
&context[..offset],
|
||||
old,
|
||||
new,
|
||||
(
|
||||
Id::from_u128(0x300),
|
||||
Some(Field::Body),
|
||||
Some(path.clone()),
|
||||
TokenRole::Use(Role::ArgumentLabel),
|
||||
parameter(0x100, id),
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
add(
|
||||
23,
|
||||
"@g(a: 5, b: 6)",
|
||||
"@",
|
||||
"g",
|
||||
"f",
|
||||
(
|
||||
Id::from_u128(0x300),
|
||||
Some(Field::Body),
|
||||
Some(vec![Child::Right]),
|
||||
TokenRole::Use(Role::CallTarget),
|
||||
global(0x200),
|
||||
),
|
||||
);
|
||||
expected.sort_by_key(|row| (row.0.file, row.0.span.start, row.0.span.end));
|
||||
let actual: Vec<Row> = batch
|
||||
.iter()
|
||||
.map(|edit| {
|
||||
let key = edit.key();
|
||||
(
|
||||
edit.location(),
|
||||
edit.original().into(),
|
||||
edit.replacement().into(),
|
||||
(
|
||||
key.owner,
|
||||
key.field,
|
||||
key.path.as_ref().map(|path| path.edges()),
|
||||
key.role,
|
||||
key.target,
|
||||
),
|
||||
)
|
||||
})
|
||||
.collect();
|
||||
assert_eq!(actual, expected);
|
||||
|
||||
let noop = Composition::renames(
|
||||
&index,
|
||||
&BTreeMap::from([
|
||||
(global(0x100), "f".into()),
|
||||
(parameter(0x200, 0x200), "a".into()),
|
||||
]),
|
||||
&work,
|
||||
)
|
||||
.unwrap();
|
||||
let empty = noop.original_edits(&sources).unwrap();
|
||||
assert!(empty.is_empty());
|
||||
assert_eq!(empty.len(), 0);
|
||||
assert_eq!(empty.iter().count(), 0);
|
||||
assert_eq!(work.usage, usage);
|
||||
assert_eq!(work.numeric_units(), numeric);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn composition_rejects_stale_or_damaged_complete_batches_before_export() {
|
||||
let mut sources = sources();
|
||||
sources.insert(99, "// unrelated 雪\r\n".into());
|
||||
let original = sources.clone();
|
||||
let mut work = budget();
|
||||
let (index, _) = Index::parse(&skeleton(), &sources, &mut work).unwrap();
|
||||
for damage in 0..10 {
|
||||
let mut current = sources.clone();
|
||||
let mut composition = Composition::renames(&index, &rename_map(), &work).unwrap();
|
||||
match damage {
|
||||
0 => current.get_mut(&99).unwrap().push_str("changed"),
|
||||
1 => {
|
||||
current.remove(&23);
|
||||
}
|
||||
2 => {
|
||||
current.insert(101, String::new());
|
||||
}
|
||||
3 => composition.plan.edits[0].location.span.start += 1,
|
||||
4 => composition
|
||||
.plan
|
||||
.edits
|
||||
.insert(1, composition.plan.edits[0].clone()),
|
||||
5 => {
|
||||
composition.plan.edits.pop();
|
||||
}
|
||||
6 => composition.plan.edits.swap(0, 1),
|
||||
7 => {
|
||||
composition
|
||||
.plan
|
||||
.names
|
||||
.insert(global(0x100), "bad name".into());
|
||||
}
|
||||
8 => {
|
||||
composition.plan.names.insert(global(0x100), "f".into());
|
||||
}
|
||||
_ => {
|
||||
composition.plan.names.insert(global(999), "missing".into());
|
||||
}
|
||||
}
|
||||
let before = current.clone();
|
||||
assert!(
|
||||
composition.original_edits(¤t).is_err(),
|
||||
"damage {damage}"
|
||||
);
|
||||
assert_eq!(current, before);
|
||||
}
|
||||
assert_eq!(sources, original);
|
||||
let failure = work.frame(257, Span::default()).unwrap_err();
|
||||
assert_eq!(
|
||||
Composition::renames(&index, &rename_map(), &work).unwrap_err(),
|
||||
failure
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn composition_defers_only_typed_output_size_with_independent_shrink_arithmetic() {
|
||||
let sources = sources();
|
||||
let cap = sources.values().map(String::len).sum();
|
||||
let mut limits = Limits::source8(ParseLimits::UNLIMITED);
|
||||
limits.bytes = cap;
|
||||
let mut work = Budget::new(limits).unwrap();
|
||||
let (index, _) = Index::parse(&skeleton(), &sources, &mut work).unwrap();
|
||||
assert_eq!(work.usage.bytes, cap);
|
||||
let usage = work.usage;
|
||||
let numeric = work.numeric_units();
|
||||
let names = BTreeMap::from([(global(0x100), "ff".into())]);
|
||||
assert_eq!(
|
||||
Plan::renames(&index, &names, &work).unwrap_err().message,
|
||||
"Source8 index/output byte limit exceeded."
|
||||
);
|
||||
let composition = Composition::renames(&index, &names, &work).unwrap();
|
||||
let batch = composition.original_edits(&sources).unwrap();
|
||||
assert_eq!(batch.len(), 3); // declaration and two distinct call targets
|
||||
let growth: usize = batch
|
||||
.iter()
|
||||
.map(|edit| edit.replacement().len() - edit.original().len())
|
||||
.sum();
|
||||
assert_eq!(growth, 3);
|
||||
assert_eq!(
|
||||
composition.plan.apply(&sources, &work).unwrap_err().message,
|
||||
"Source8 index/output byte limit exceeded."
|
||||
);
|
||||
|
||||
// Independent future ordinary/scalar producer witness on untouched display
|
||||
// name bytes. This is size/offset arithmetic only: this typed-only harness
|
||||
// has no ordinary collector, mixed ownership proof or accepted output.
|
||||
let start = DEFINITIONS.find("\"f a b\"").unwrap() + 1;
|
||||
let shrink = Location {
|
||||
file: 11,
|
||||
span: Span {
|
||||
start,
|
||||
end: start + "f a b".len(),
|
||||
},
|
||||
};
|
||||
assert_eq!(
|
||||
&sources[&shrink.file][shrink.span.start..shrink.span.end],
|
||||
"f a b"
|
||||
);
|
||||
for edit in batch.iter() {
|
||||
let at = edit.location();
|
||||
assert!(
|
||||
at.file != shrink.file
|
||||
|| at.span.end <= shrink.span.start
|
||||
|| shrink.span.end <= at.span.start
|
||||
);
|
||||
}
|
||||
let original_len = shrink.span.end - shrink.span.start;
|
||||
assert_eq!(cap + growth - original_len + "fa".len(), cap);
|
||||
assert_eq!(cap + growth - original_len + "fab".len(), cap + 1);
|
||||
assert_eq!(work.usage, usage);
|
||||
assert_eq!(work.numeric_units(), numeric);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn composition_keeps_name_storage_and_rename_record_limits_before_allocation() {
|
||||
let sources = sources();
|
||||
let cap = sources.values().map(String::len).sum();
|
||||
let mut limits = Limits::source8(ParseLimits::UNLIMITED);
|
||||
limits.bytes = cap;
|
||||
let mut work = Budget::new(limits).unwrap();
|
||||
let (index, _) = Index::parse(&skeleton(), &sources, &mut work).unwrap();
|
||||
let exact = BTreeMap::from([(global(0x100), "x".repeat(cap))]);
|
||||
assert_eq!(
|
||||
Composition::renames(&index, &exact, &work)
|
||||
.unwrap()
|
||||
.original_edits(&sources)
|
||||
.unwrap()
|
||||
.len(),
|
||||
3
|
||||
);
|
||||
let over = BTreeMap::from([(global(0x100), "x".repeat(cap + 1))]);
|
||||
assert_eq!(
|
||||
Composition::renames(&index, &over, &work)
|
||||
.unwrap_err()
|
||||
.message,
|
||||
"Source8 index/output byte limit exceeded."
|
||||
);
|
||||
for invalid in [
|
||||
BTreeMap::from([(global(999), "unknown".into())]),
|
||||
BTreeMap::from([(global(0x100), "bad name".into())]),
|
||||
BTreeMap::from([(global(0x100), "g".into())]),
|
||||
BTreeMap::from([(parameter(0x100, 0x200), "b".into())]),
|
||||
] {
|
||||
assert!(Composition::renames(&index, &invalid, &work).is_err());
|
||||
}
|
||||
|
||||
// A typed-empty fixture isolates the rename-map record bound without
|
||||
// syntax entry usage masking it. No ordinary edits are authorized here.
|
||||
let ordinary = skeleton();
|
||||
let count = ordinary.identities().len();
|
||||
let files = BTreeMap::from([(1, "// empty typed unit\n".into())]);
|
||||
let mut limits = Limits::source8(ParseLimits::UNLIMITED);
|
||||
limits.entries = count;
|
||||
limits.references = 0;
|
||||
let mut inherited = Budget::new(limits).unwrap();
|
||||
let (index, _) = Index::parse(&ordinary, &files, &mut inherited).unwrap();
|
||||
let mut names: BTreeMap<_, _> = index
|
||||
.names()
|
||||
.keys()
|
||||
.enumerate()
|
||||
.map(|(i, target)| (*target, format!("renamed_{i}")))
|
||||
.collect();
|
||||
assert_eq!(names.len(), count);
|
||||
assert!(
|
||||
Composition::renames(&index, &names, &inherited)
|
||||
.unwrap()
|
||||
.original_edits(&files)
|
||||
.unwrap()
|
||||
.is_empty()
|
||||
);
|
||||
names.insert(global(999), "additional".into());
|
||||
assert_eq!(
|
||||
Composition::renames(&index, &names, &inherited)
|
||||
.unwrap_err()
|
||||
.message,
|
||||
"Source8 lowering entry limit exceeded."
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn composition_checks_edit_record_ceiling_before_duplicate_membership() {
|
||||
let sources = sources();
|
||||
let mut limits = Limits::source8(ParseLimits::UNLIMITED);
|
||||
limits.entries = 128;
|
||||
limits.references = 32;
|
||||
let ceiling = limits.entries + limits.references;
|
||||
let mut work = Budget::new(limits).unwrap();
|
||||
let (index, _) = Index::parse(&skeleton(), &sources, &mut work).unwrap();
|
||||
let mut composition = Composition::renames(&index, &rename_map(), &work).unwrap();
|
||||
assert_eq!(composition.original_edits(&sources).unwrap().len(), 13);
|
||||
let duplicate = composition.plan.edits[0].clone();
|
||||
composition.plan.edits = vec![duplicate.clone(); ceiling];
|
||||
// At the exact count bound validation proceeds to the independent ownership
|
||||
// error. The damaged plan never becomes a successful/authoritative batch.
|
||||
assert_eq!(
|
||||
composition.original_edits(&sources).unwrap_err().message,
|
||||
"Forged or duplicate edit occurrence."
|
||||
);
|
||||
composition.plan.edits.push(duplicate);
|
||||
assert_eq!(
|
||||
composition.original_edits(&sources).unwrap_err().message,
|
||||
"Source8 lowering occurrence limit exceeded."
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn standalone_noop_apply_keeps_tighter_file_only_budget_and_output_boundary() {
|
||||
let sources = sources();
|
||||
let mut inherited = budget();
|
||||
let (index, _) = Index::parse(&skeleton(), &sources, &mut inherited).unwrap();
|
||||
let plan = Plan::renames(
|
||||
&index,
|
||||
&BTreeMap::from([(global(0x100), "f".into())]),
|
||||
&inherited,
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(plan.edit_count(), 0);
|
||||
assert!(index.names().len() > sources.len());
|
||||
let mut limits = Limits::source8(ParseLimits::UNLIMITED);
|
||||
limits.entries = sources.len();
|
||||
limits.references = 0;
|
||||
limits.bytes = sources.values().map(String::len).sum();
|
||||
// Standalone apply checks file/edit records, not the already validated
|
||||
// catalog/name-storage allocation from construction. Rechecking the catalog
|
||||
// under this intentionally tighter probe budget would reject this no-op.
|
||||
assert_eq!(
|
||||
plan.apply(&sources, &Budget::new(limits).unwrap()).unwrap(),
|
||||
sources
|
||||
);
|
||||
limits.bytes -= 1;
|
||||
assert_eq!(
|
||||
plan.apply(&sources, &Budget::new(limits).unwrap())
|
||||
.unwrap_err()
|
||||
.message,
|
||||
"Source8 index/output byte limit exceeded."
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,664 @@
|
||||
//! Private typed canonical output. Complete semantic admission belongs to the
|
||||
//! caller. No public formatter, version dispatch or source edits use this yet.
|
||||
mod expression;
|
||||
pub(super) use expression::{Parent, Side};
|
||||
|
||||
use super::{budget, lower::Field};
|
||||
use crate::analysis as a;
|
||||
use crate::analysis_numeric::Exact;
|
||||
use crate::{Id, Kind, Layer, Project, SharedBody};
|
||||
use std::collections::{BTreeMap, BTreeSet};
|
||||
use std::io::Write;
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
pub(super) struct Limits {
|
||||
pub bytes: usize,
|
||||
pub entries: usize,
|
||||
}
|
||||
impl Limits {
|
||||
pub fn source8(caller: crate::language::ParseLimits) -> Self {
|
||||
let limits = budget::Limits::source8(caller);
|
||||
Self {
|
||||
bytes: limits.bytes,
|
||||
entries: limits.entries,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub(super) struct Error {
|
||||
pub owner: Option<Id>,
|
||||
pub field: &'static str,
|
||||
pub message: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
|
||||
pub(super) struct Usage {
|
||||
pub bytes: usize,
|
||||
pub entries: usize,
|
||||
}
|
||||
|
||||
struct Sink {
|
||||
buffer: Vec<u8>,
|
||||
written: usize,
|
||||
maximum: usize,
|
||||
}
|
||||
impl Sink {
|
||||
fn room(&self, bytes: usize) -> std::io::Result<()> {
|
||||
if bytes > self.maximum.saturating_sub(self.written) {
|
||||
return Err(std::io::Error::other(
|
||||
"Source8 writer output byte limit exceeded.",
|
||||
));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
impl Write for Sink {
|
||||
fn write(&mut self, bytes: &[u8]) -> std::io::Result<usize> {
|
||||
self.room(bytes.len())?;
|
||||
self.buffer.extend_from_slice(bytes);
|
||||
self.written += bytes.len();
|
||||
Ok(bytes.len())
|
||||
}
|
||||
fn flush(&mut self) -> std::io::Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) struct Writer<'p> {
|
||||
project: &'p Project,
|
||||
parameters: BTreeMap<Id, BTreeMap<a::ParameterId, &'p a::Parameter>>,
|
||||
limits: Limits,
|
||||
entries: usize,
|
||||
sink: Sink,
|
||||
owner: Option<Id>,
|
||||
field: &'static str,
|
||||
failed: Option<Error>,
|
||||
}
|
||||
|
||||
impl<'p> Writer<'p> {
|
||||
pub fn new(project: &'p Project, limits: Limits) -> Result<Self, Error> {
|
||||
let hard = Limits::source8(crate::language::ParseLimits::UNLIMITED);
|
||||
if limits.bytes > hard.bytes || limits.entries > hard.entries {
|
||||
return Err(Error {
|
||||
owner: None,
|
||||
field: "writer",
|
||||
message: "Writer limits exceed the source8 profile.".into(),
|
||||
});
|
||||
}
|
||||
let mut writer = Self {
|
||||
project,
|
||||
parameters: BTreeMap::new(),
|
||||
limits,
|
||||
entries: 0,
|
||||
sink: Sink {
|
||||
buffer: Vec::new(),
|
||||
written: 0,
|
||||
maximum: limits.bytes,
|
||||
},
|
||||
owner: None,
|
||||
field: "writer",
|
||||
failed: None,
|
||||
};
|
||||
for definition in project.definitions.values() {
|
||||
writer.owner = Some(definition.id);
|
||||
writer.field = "parameters";
|
||||
writer.entry()?;
|
||||
if let a::DefinitionBody::Calculation(calculation) = &definition.body {
|
||||
let mut parameters = BTreeMap::new();
|
||||
let mut names = BTreeSet::new();
|
||||
for parameter in &calculation.parameters {
|
||||
writer.entry()?;
|
||||
if parameters.contains_key(¶meter.id)
|
||||
|| !names.insert(parameter.name.as_str())
|
||||
{
|
||||
return Err(writer.error("Duplicate scoped parameter identity or name."));
|
||||
}
|
||||
parameters.insert(parameter.id, parameter);
|
||||
}
|
||||
writer.parameters.insert(definition.id, parameters);
|
||||
}
|
||||
}
|
||||
Ok(writer)
|
||||
}
|
||||
|
||||
pub fn usage(&self) -> Usage {
|
||||
Usage {
|
||||
bytes: self.sink.written,
|
||||
entries: self.entries,
|
||||
}
|
||||
}
|
||||
|
||||
fn error(&self, message: impl Into<String>) -> Error {
|
||||
Error {
|
||||
owner: self.owner,
|
||||
field: self.field,
|
||||
message: message.into(),
|
||||
}
|
||||
}
|
||||
fn entry(&mut self) -> Result<(), Error> {
|
||||
if self.entries == self.limits.entries {
|
||||
return Err(self.error("Source8 writer entry limit exceeded."));
|
||||
}
|
||||
self.entries += 1;
|
||||
Ok(())
|
||||
}
|
||||
fn pending(&self, count: usize) -> Result<(), Error> {
|
||||
if count > self.limits.entries {
|
||||
return Err(self.error("Source8 writer pending work limit exceeded."));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
fn text(&mut self, text: &str) -> Result<(), Error> {
|
||||
self.sink
|
||||
.write_all(text.as_bytes())
|
||||
.map_err(|cause| self.error(cause.to_string()))
|
||||
}
|
||||
fn quote(&mut self, text: &str) -> Result<(), Error> {
|
||||
// Identical serde_json string escaping to language::quote, streamed
|
||||
// directly to the checked sink instead of an unbounded scratch String.
|
||||
self.sink
|
||||
.room(text.len().saturating_add(2))
|
||||
.map_err(|cause| self.error(cause.to_string()))?;
|
||||
serde_json::to_writer(&mut self.sink, text).map_err(|cause| self.error(cause.to_string()))
|
||||
}
|
||||
fn name(&mut self, name: &str) -> Result<(), Error> {
|
||||
self.sink
|
||||
.room(name.len())
|
||||
.map_err(|cause| self.error(cause.to_string()))?;
|
||||
if !crate::valid_alias(name) {
|
||||
return Err(self.error("Invalid alias or parameter name."));
|
||||
}
|
||||
self.text(name)
|
||||
}
|
||||
fn exact(&mut self, exact: &Exact) -> Result<(), Error> {
|
||||
// At most two already-bounded 4096-bit components, never an Expr-sized
|
||||
// temporary or a second parse/normalization of the stored value.
|
||||
self.text(&exact.canonical_literal())
|
||||
}
|
||||
fn run(
|
||||
&mut self,
|
||||
owner: Id,
|
||||
field: &'static str,
|
||||
emit: impl FnOnce(&mut Self) -> Result<(), Error>,
|
||||
) -> Result<String, Error> {
|
||||
if let Some(error) = &self.failed {
|
||||
return Err(error.clone());
|
||||
}
|
||||
self.owner = Some(owner);
|
||||
self.field = field;
|
||||
debug_assert!(self.sink.buffer.is_empty());
|
||||
if let Err(error) = emit(self) {
|
||||
self.sink.buffer.clear();
|
||||
self.failed = Some(error.clone());
|
||||
return Err(error);
|
||||
}
|
||||
Ok(String::from_utf8(std::mem::take(&mut self.sink.buffer))
|
||||
.expect("text and JSON string writes are UTF-8"))
|
||||
}
|
||||
|
||||
fn definition_name(
|
||||
&self,
|
||||
reference: a::DefinitionRef,
|
||||
kind: DefinitionKind,
|
||||
) -> Result<&'p str, Error> {
|
||||
let definition = self
|
||||
.project
|
||||
.definitions
|
||||
.get(&reference.local())
|
||||
.ok_or_else(|| self.error("Unknown definition reference."))?;
|
||||
let matches = matches!(
|
||||
(&definition.body, kind),
|
||||
(
|
||||
a::DefinitionBody::QuantityKind(_),
|
||||
DefinitionKind::QuantityKind
|
||||
) | (a::DefinitionBody::Unit(_), DefinitionKind::Unit)
|
||||
| (
|
||||
a::DefinitionBody::Calculation(_),
|
||||
DefinitionKind::Calculation
|
||||
)
|
||||
);
|
||||
if !matches {
|
||||
return Err(self.error("Wrong definition reference domain."));
|
||||
}
|
||||
Ok(&definition.alias)
|
||||
}
|
||||
fn definition_ref(
|
||||
&mut self,
|
||||
reference: a::DefinitionRef,
|
||||
kind: DefinitionKind,
|
||||
) -> Result<(), Error> {
|
||||
let alias = self.definition_name(reference, kind)?;
|
||||
self.text("@")?;
|
||||
self.name(alias)
|
||||
}
|
||||
fn property_name(&self, id: Id) -> Result<&'p str, Error> {
|
||||
self.project
|
||||
.elements
|
||||
.get(&id)
|
||||
.filter(|value| value.kind() == Kind::EngineeringProperty)
|
||||
.map(|value| value.alias.as_str())
|
||||
.ok_or_else(|| self.error("Unknown property reference or wrong reference domain."))
|
||||
}
|
||||
fn subject(&mut self, subject: a::AnalysisSubject) -> Result<(), Error> {
|
||||
let alias = match subject {
|
||||
a::AnalysisSubject::Element(id) => self
|
||||
.project
|
||||
.elements
|
||||
.get(&id)
|
||||
.filter(|value| !value.kind().is_analysis())
|
||||
.map(|value| value.alias.as_str()),
|
||||
a::AnalysisSubject::Relation(id) => self
|
||||
.project
|
||||
.relations
|
||||
.get(&id)
|
||||
.map(|value| value.alias.as_str()),
|
||||
}
|
||||
.ok_or_else(|| self.error("Unknown architectural subject or wrong reference domain."))?;
|
||||
self.text("@")?;
|
||||
self.name(alias)
|
||||
}
|
||||
fn optional_subject(&mut self, subject: Option<a::AnalysisSubject>) -> Result<(), Error> {
|
||||
if let Some(subject) = subject {
|
||||
self.subject(subject)
|
||||
} else {
|
||||
self.text("none")
|
||||
}
|
||||
}
|
||||
fn type_value(&mut self, value: &a::AnalysisType) -> Result<(), Error> {
|
||||
self.entry()?;
|
||||
let (scalar, list) = match value {
|
||||
a::AnalysisType::Scalar(value) => (value, false),
|
||||
a::AnalysisType::List(value) => (value, true),
|
||||
};
|
||||
if list {
|
||||
self.text("List(")?;
|
||||
}
|
||||
match scalar {
|
||||
a::ScalarType::Boolean => self.text("Boolean")?,
|
||||
a::ScalarType::Number => self.text("Number")?,
|
||||
a::ScalarType::Quantity(kind) => {
|
||||
self.text("Quantity(")?;
|
||||
self.definition_ref(*kind, DefinitionKind::QuantityKind)?;
|
||||
self.text(")")?;
|
||||
}
|
||||
}
|
||||
if list {
|
||||
self.text(")")?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
pub fn value_type(&mut self, owner: Id, value: &a::AnalysisType) -> Result<String, Error> {
|
||||
self.run(owner, "type", |writer| writer.type_value(value))
|
||||
}
|
||||
fn model_binding(
|
||||
&self,
|
||||
owner: Id,
|
||||
field: Field,
|
||||
) -> Result<(&'p a::Binding, Option<Id>), Error> {
|
||||
if field == Field::Body {
|
||||
if let Some(a::Definition {
|
||||
body: a::DefinitionBody::Calculation(calculation),
|
||||
..
|
||||
}) = self.project.definitions.get(&owner)
|
||||
{
|
||||
return Ok((&calculation.body, Some(owner)));
|
||||
}
|
||||
} else if let Some(element) = self.project.elements.get(&owner) {
|
||||
match (element.shared(), field) {
|
||||
(Some(SharedBody::EngineeringProperty { base, .. }), Field::Base) => {
|
||||
return Ok((base, None));
|
||||
}
|
||||
(Some(SharedBody::AnalysisCheck { predicate, .. }), Field::Predicate) => {
|
||||
return Ok((predicate, None));
|
||||
}
|
||||
(Some(SharedBody::AnalysisCase { overrides, .. }), Field::Override(property)) => {
|
||||
return overrides
|
||||
.get(&property)
|
||||
.map(|binding| (binding, None))
|
||||
.ok_or_else(|| self.error("Missing override binding."));
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
Err(self.error("Binding field does not belong to the requested owner."))
|
||||
}
|
||||
fn binding_value(
|
||||
&mut self,
|
||||
binding: &a::Binding,
|
||||
calculation: Option<Id>,
|
||||
) -> Result<(), Error> {
|
||||
match binding {
|
||||
a::Binding::Unbound => {
|
||||
self.entry()?;
|
||||
self.text("unbound")
|
||||
}
|
||||
a::Binding::Expression(expression) => {
|
||||
self.emit_expression(expression, calculation, Parent::Root)
|
||||
}
|
||||
}
|
||||
}
|
||||
pub fn binding(&mut self, owner: Id, field: Field) -> Result<String, Error> {
|
||||
self.run(owner, binding_field(field), |writer| {
|
||||
let (binding, scope) = writer.model_binding(owner, field)?;
|
||||
writer.binding_value(binding, scope)
|
||||
})
|
||||
}
|
||||
pub fn expression(
|
||||
&mut self,
|
||||
owner: Id,
|
||||
field: Field,
|
||||
expression: &a::Expr,
|
||||
parent: Parent,
|
||||
) -> Result<String, Error> {
|
||||
self.run(owner, binding_field(field), |writer| {
|
||||
let (_, scope) = writer.model_binding(owner, field)?;
|
||||
writer.emit_expression(expression, scope, parent)
|
||||
})
|
||||
}
|
||||
fn parameter_value(&mut self, calculation: Id, id: a::ParameterId) -> Result<(), Error> {
|
||||
self.entry()?;
|
||||
let parameter = *self
|
||||
.parameters
|
||||
.get(&calculation)
|
||||
.and_then(|parameters| parameters.get(&id))
|
||||
.ok_or_else(|| self.error("Unknown scoped parameter."))?;
|
||||
self.text("input ")?;
|
||||
self.name(¶meter.name)?;
|
||||
self.text(" id \"")?;
|
||||
self.text(¶meter.id.0.to_string())?;
|
||||
self.text("\" : ")?;
|
||||
self.type_value(¶meter.value_type)?;
|
||||
self.text(";")
|
||||
}
|
||||
pub fn parameter(
|
||||
&mut self,
|
||||
calculation: Id,
|
||||
parameter: a::ParameterId,
|
||||
) -> Result<String, Error> {
|
||||
self.run(calculation, "input", |writer| {
|
||||
writer.parameter_value(calculation, parameter)
|
||||
})
|
||||
}
|
||||
fn override_value(&mut self, property: Id, binding: &a::Binding) -> Result<(), Error> {
|
||||
self.entry()?;
|
||||
let alias = self.property_name(property)?;
|
||||
self.text("@")?;
|
||||
self.name(alias)?;
|
||||
self.text(" = ")?;
|
||||
self.binding_value(binding, None)?;
|
||||
self.text(";")
|
||||
}
|
||||
pub fn override_entry(&mut self, case: Id, property: Id) -> Result<String, Error> {
|
||||
self.run(case, "overrides", |writer| {
|
||||
let (binding, _) = writer.model_binding(case, Field::Override(property))?;
|
||||
writer.override_value(property, binding)
|
||||
})
|
||||
}
|
||||
fn header(
|
||||
&mut self,
|
||||
word: &str,
|
||||
alias: &str,
|
||||
name: &str,
|
||||
id: Id,
|
||||
description: &str,
|
||||
) -> Result<(), Error> {
|
||||
self.entry()?;
|
||||
self.text(" ")?;
|
||||
self.text(word)?;
|
||||
self.text(" ")?;
|
||||
self.name(alias)?;
|
||||
self.text(" ")?;
|
||||
self.quote(name)?;
|
||||
self.text(" id \"")?;
|
||||
self.text(&id.to_string())?;
|
||||
self.text("\" {\n")?;
|
||||
self.start_field("description")?;
|
||||
self.quote(description)?;
|
||||
self.text(";\n")
|
||||
}
|
||||
fn start_field(&mut self, name: &'static str) -> Result<(), Error> {
|
||||
self.field = name;
|
||||
self.entry()?;
|
||||
self.text(" ")?;
|
||||
self.text(name)?;
|
||||
self.text(" ")
|
||||
}
|
||||
pub fn definition(&mut self, id: Id) -> Result<String, Error> {
|
||||
self.run(id, "definition", |writer| {
|
||||
let project = writer.project;
|
||||
let definition = project
|
||||
.definitions
|
||||
.get(&id)
|
||||
.ok_or_else(|| writer.error("Unknown definition."))?;
|
||||
let word = match &definition.body {
|
||||
a::DefinitionBody::QuantityKind(_) => "quantity_kind",
|
||||
a::DefinitionBody::Unit(_) => "unit",
|
||||
a::DefinitionBody::Calculation(_) => "calculation",
|
||||
};
|
||||
writer.header(
|
||||
word,
|
||||
&definition.alias,
|
||||
&definition.name,
|
||||
id,
|
||||
&definition.description,
|
||||
)?;
|
||||
match &definition.body {
|
||||
a::DefinitionBody::QuantityKind(kind) => {
|
||||
writer.start_field("dimension")?;
|
||||
writer.text("{")?;
|
||||
const AXES: [&str; 7] = [
|
||||
"length",
|
||||
"mass",
|
||||
"time",
|
||||
"electric_current",
|
||||
"temperature",
|
||||
"amount",
|
||||
"luminous_intensity",
|
||||
];
|
||||
let mut nonzero = false;
|
||||
for (axis, exponent) in AXES.into_iter().zip(kind.dimension.exponents()) {
|
||||
if exponent != 0 {
|
||||
writer.entry()?;
|
||||
writer.text(" ")?;
|
||||
writer.text(axis)?;
|
||||
writer.text(" ")?;
|
||||
writer.text(&exponent.to_string())?;
|
||||
writer.text(";")?;
|
||||
nonzero = true;
|
||||
}
|
||||
}
|
||||
if nonzero {
|
||||
writer.text(" ")?;
|
||||
}
|
||||
writer.text("};\n")?;
|
||||
writer.start_field("algebra")?;
|
||||
match kind.algebra {
|
||||
a::QuantityAlgebra::Linear => writer.text("Linear")?,
|
||||
a::QuantityAlgebra::Affine { difference } => {
|
||||
writer.text("Affine(")?;
|
||||
writer.definition_ref(difference, DefinitionKind::QuantityKind)?;
|
||||
writer.text(")")?;
|
||||
}
|
||||
}
|
||||
writer.text(";\n")?;
|
||||
}
|
||||
a::DefinitionBody::Unit(unit) => {
|
||||
writer.start_field("kind")?;
|
||||
writer.definition_ref(unit.kind, DefinitionKind::QuantityKind)?;
|
||||
writer.text(";\n")?;
|
||||
writer.start_field("scale")?;
|
||||
writer.exact(&unit.scale)?;
|
||||
writer.text(";\n")?;
|
||||
writer.start_field("offset")?;
|
||||
writer.exact(&unit.offset)?;
|
||||
writer.text(";\n")?;
|
||||
writer.start_field("symbol")?;
|
||||
writer.quote(&unit.symbol)?;
|
||||
writer.text(";\n")?;
|
||||
}
|
||||
a::DefinitionBody::Calculation(calculation) => {
|
||||
for parameter in &calculation.parameters {
|
||||
writer.field = "input";
|
||||
writer.text(" ")?;
|
||||
writer.parameter_value(id, parameter.id)?;
|
||||
writer.text("\n")?;
|
||||
}
|
||||
writer.start_field("result")?;
|
||||
writer.type_value(&calculation.result)?;
|
||||
writer.text(";\n")?;
|
||||
writer.start_field("body")?;
|
||||
writer.binding_value(&calculation.body, Some(id))?;
|
||||
writer.text(";\n")?;
|
||||
}
|
||||
}
|
||||
writer.text(" }\n\n")
|
||||
})
|
||||
}
|
||||
pub fn analysis_element(&mut self, id: Id) -> Result<String, Error> {
|
||||
self.run(id, "element", |writer| {
|
||||
let project = writer.project;
|
||||
let element = project
|
||||
.elements
|
||||
.get(&id)
|
||||
.ok_or_else(|| writer.error("Unknown analysis element."))?;
|
||||
let word = match (element.kind(), element.layer()) {
|
||||
(Kind::EngineeringProperty, Layer::Oa) => "oa_property",
|
||||
(Kind::EngineeringProperty, Layer::Sa) => "sa_property",
|
||||
(Kind::AnalysisCheck, Layer::Oa) => "oa_check",
|
||||
(Kind::AnalysisCheck, Layer::Sa) => "sa_check",
|
||||
(Kind::AnalysisCase, Layer::Oa) => "oa_analysis",
|
||||
(Kind::AnalysisCase, Layer::Sa) => "sa_analysis",
|
||||
_ => return Err(writer.error("Expected an analysis element.")),
|
||||
};
|
||||
if element.parent.is_some() {
|
||||
return Err(writer.error("Analysis declarations must be roots."));
|
||||
}
|
||||
writer.header(
|
||||
word,
|
||||
&element.alias,
|
||||
&element.name,
|
||||
id,
|
||||
&element.description,
|
||||
)?;
|
||||
writer.start_field("parent")?;
|
||||
writer.text("none;\n")?;
|
||||
match element.shared().expect("analysis kind is a shared body") {
|
||||
SharedBody::EngineeringProperty {
|
||||
subject,
|
||||
value_type,
|
||||
display_unit,
|
||||
base,
|
||||
} => {
|
||||
writer.start_field("subject")?;
|
||||
writer.subject(*subject)?;
|
||||
writer.text(";\n")?;
|
||||
writer.start_field("type")?;
|
||||
writer.type_value(value_type)?;
|
||||
writer.text(";\n")?;
|
||||
writer.start_field("display_unit")?;
|
||||
if let Some(unit) = display_unit {
|
||||
writer.definition_ref(*unit, DefinitionKind::Unit)?;
|
||||
} else {
|
||||
writer.text("none")?;
|
||||
}
|
||||
writer.text(";\n")?;
|
||||
writer.start_field("base")?;
|
||||
writer.binding_value(base, None)?;
|
||||
writer.text(";\n")?;
|
||||
}
|
||||
SharedBody::AnalysisCheck {
|
||||
subject,
|
||||
documented_constraint,
|
||||
predicate,
|
||||
} => {
|
||||
writer.start_field("subject")?;
|
||||
writer.optional_subject(*subject)?;
|
||||
writer.text(";\n")?;
|
||||
writer.start_field("documented_constraint")?;
|
||||
if let Some(id) = documented_constraint {
|
||||
let alias = project
|
||||
.elements
|
||||
.get(id)
|
||||
.filter(|element| element.kind() == Kind::Constraint)
|
||||
.map(|element| element.alias.as_str())
|
||||
.ok_or_else(|| {
|
||||
writer.error("Unknown constraint or wrong reference domain.")
|
||||
})?;
|
||||
writer.text("@")?;
|
||||
writer.name(alias)?;
|
||||
} else {
|
||||
writer.text("none")?;
|
||||
}
|
||||
writer.text(";\n")?;
|
||||
writer.start_field("predicate")?;
|
||||
writer.binding_value(predicate, None)?;
|
||||
writer.text(";\n")?;
|
||||
}
|
||||
SharedBody::AnalysisCase {
|
||||
subject,
|
||||
base: a::BaselineBase::ModelBaseline,
|
||||
overrides,
|
||||
} => {
|
||||
writer.start_field("subject")?;
|
||||
writer.optional_subject(*subject)?;
|
||||
writer.text(";\n")?;
|
||||
writer.start_field("base")?;
|
||||
writer.text("ModelBaseline;\n")?;
|
||||
writer.start_field("overrides")?;
|
||||
if overrides.is_empty() {
|
||||
writer.text("{};\n")?;
|
||||
} else {
|
||||
writer.text("{\n")?;
|
||||
for (property, binding) in overrides {
|
||||
writer.text(" ")?;
|
||||
writer.override_value(*property, binding)?;
|
||||
writer.text("\n")?;
|
||||
}
|
||||
writer.text(" };\n")?;
|
||||
}
|
||||
}
|
||||
_ => return Err(writer.error("Expected an analysis body.")),
|
||||
}
|
||||
writer.text(" }\n\n")
|
||||
})
|
||||
}
|
||||
pub fn typed_declarations(&mut self) -> Result<Vec<(Id, String)>, Error> {
|
||||
if let Some(error) = &self.failed {
|
||||
return Err(error.clone());
|
||||
}
|
||||
let project = self.project;
|
||||
let mut declarations = Vec::new();
|
||||
for id in project.definitions.keys() {
|
||||
declarations.push((*id, self.definition(*id)?));
|
||||
}
|
||||
for element in project
|
||||
.elements
|
||||
.values()
|
||||
.filter(|element| element.kind().is_analysis())
|
||||
{
|
||||
declarations.push((element.id, self.analysis_element(element.id)?));
|
||||
}
|
||||
Ok(declarations)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
enum DefinitionKind {
|
||||
QuantityKind,
|
||||
Unit,
|
||||
Calculation,
|
||||
}
|
||||
|
||||
fn binding_field(field: Field) -> &'static str {
|
||||
match field {
|
||||
Field::Body => "body",
|
||||
Field::Base => "base",
|
||||
Field::Predicate => "predicate",
|
||||
Field::Override(_) => "overrides",
|
||||
_ => "binding",
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
@@ -0,0 +1,284 @@
|
||||
use super::*;
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
pub enum Side {
|
||||
Left,
|
||||
Right,
|
||||
}
|
||||
#[derive(Clone, Copy)]
|
||||
pub enum Parent {
|
||||
Root,
|
||||
Binary(a::BinaryOp, Side),
|
||||
Negate,
|
||||
}
|
||||
|
||||
fn operator(op: a::BinaryOp) -> (&'static str, u8) {
|
||||
use a::BinaryOp::*;
|
||||
match op {
|
||||
Or => (" or ", 1),
|
||||
And => (" and ", 2),
|
||||
Equal => (" == ", 3),
|
||||
NotEqual => (" != ", 3),
|
||||
Less => (" < ", 4),
|
||||
LessOrEqual => (" <= ", 4),
|
||||
Greater => (" > ", 4),
|
||||
GreaterOrEqual => (" >= ", 4),
|
||||
Add => (" + ", 5),
|
||||
Subtract => (" - ", 5),
|
||||
Multiply => (" * ", 6),
|
||||
Divide => (" / ", 6),
|
||||
}
|
||||
}
|
||||
fn comparison(op: a::BinaryOp) -> bool {
|
||||
matches!(operator(op).1, 3 | 4)
|
||||
}
|
||||
fn group(expression: &a::Expr, parent: Parent) -> bool {
|
||||
let a::Expr::Binary { op, .. } = expression else {
|
||||
return false;
|
||||
};
|
||||
match parent {
|
||||
Parent::Root => false,
|
||||
Parent::Negate => true,
|
||||
Parent::Binary(parent, side) => {
|
||||
(comparison(*op) && comparison(parent))
|
||||
|| operator(*op).1 < operator(parent).1
|
||||
|| (operator(*op).1 == operator(parent).1 && matches!(side, Side::Right))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
enum Task<'a> {
|
||||
Expression(&'a a::Expr, Parent, usize),
|
||||
Text(&'static str),
|
||||
Alias(&'a str),
|
||||
Literal(&'a Exact),
|
||||
Exponent(i8),
|
||||
}
|
||||
fn schedule<'a>(
|
||||
writer: &Writer<'_>,
|
||||
tasks: &mut Vec<Task<'a>>,
|
||||
ordered: &[Task<'a>],
|
||||
) -> Result<(), Error> {
|
||||
writer.pending(tasks.len().saturating_add(ordered.len()))?;
|
||||
tasks.extend(ordered.iter().rev().copied());
|
||||
Ok(())
|
||||
}
|
||||
|
||||
impl Writer<'_> {
|
||||
pub(super) fn emit_expression(
|
||||
&mut self,
|
||||
expression: &a::Expr,
|
||||
calculation: Option<Id>,
|
||||
parent: Parent,
|
||||
) -> Result<(), Error> {
|
||||
self.pending(1)?;
|
||||
let mut tasks = vec![Task::Expression(expression, parent, 1)];
|
||||
while let Some(task) = tasks.pop() {
|
||||
match task {
|
||||
Task::Text(text) => self.text(text)?,
|
||||
Task::Alias(name) => {
|
||||
self.entry()?;
|
||||
self.name(name)?;
|
||||
}
|
||||
Task::Literal(exact) => self.exact(exact)?,
|
||||
Task::Exponent(exponent) => self.text(&exponent.to_string())?,
|
||||
Task::Expression(expression, parent, depth) => {
|
||||
self.entry()?;
|
||||
if depth > a::MAX_EXPRESSION_DEPTH {
|
||||
return Err(self.error("Expression depth exceeds128."));
|
||||
}
|
||||
if group(expression, parent) {
|
||||
self.text("(")?;
|
||||
schedule(self, &mut tasks, &[Task::Text(")")])?;
|
||||
}
|
||||
use Task::{Alias, Exponent, Expression as Child, Literal, Text};
|
||||
use a::Expr as E;
|
||||
match expression {
|
||||
E::Boolean(value) => self.text(if *value { "true" } else { "false" })?,
|
||||
E::Number(value) => self.exact(value)?,
|
||||
E::Quantity { magnitude, unit } => {
|
||||
let alias = self.definition_name(*unit, DefinitionKind::Unit)?;
|
||||
schedule(
|
||||
self,
|
||||
&mut tasks,
|
||||
&[Literal(magnitude), Text(" [@"), Alias(alias), Text("]")],
|
||||
)?;
|
||||
}
|
||||
E::Property(id) => {
|
||||
let alias = self.property_name(*id)?;
|
||||
schedule(self, &mut tasks, &[Text("@"), Alias(alias)])?;
|
||||
}
|
||||
E::Parameter(parameter) => {
|
||||
let calculation = calculation.ok_or_else(|| {
|
||||
self.error("Parameter use requires an owning calculation.")
|
||||
})?;
|
||||
let parameter = *self
|
||||
.parameters
|
||||
.get(&calculation)
|
||||
.and_then(|parameters| parameters.get(parameter))
|
||||
.ok_or_else(|| {
|
||||
self.error("Unknown parameter in owning calculation.")
|
||||
})?;
|
||||
schedule(self, &mut tasks, &[Text("$"), Alias(¶meter.name)])?;
|
||||
}
|
||||
E::List(items) => {
|
||||
if items.len() > a::MAX_LIST_LENGTH {
|
||||
return Err(self.error("List exceeds1024 items."));
|
||||
}
|
||||
self.pending(
|
||||
tasks
|
||||
.len()
|
||||
.saturating_add(items.len().saturating_mul(2))
|
||||
.saturating_add(1),
|
||||
)?;
|
||||
self.text("[")?;
|
||||
tasks.push(Text("]"));
|
||||
for (index, item) in items.iter().enumerate().rev() {
|
||||
tasks.push(Child(item, Parent::Root, depth + 1));
|
||||
if index != 0 {
|
||||
tasks.push(Text(", "));
|
||||
}
|
||||
}
|
||||
}
|
||||
E::Unary { op, operand } => match op {
|
||||
a::UnaryOp::Negate => schedule(
|
||||
self,
|
||||
&mut tasks,
|
||||
&[Text("- "), Child(operand, Parent::Negate, depth + 1)],
|
||||
)?,
|
||||
a::UnaryOp::Absolute | a::UnaryOp::Not => schedule(
|
||||
self,
|
||||
&mut tasks,
|
||||
&[
|
||||
Text(if *op == a::UnaryOp::Absolute {
|
||||
"abs("
|
||||
} else {
|
||||
"not("
|
||||
}),
|
||||
Child(operand, Parent::Root, depth + 1),
|
||||
Text(")"),
|
||||
],
|
||||
)?,
|
||||
},
|
||||
E::Binary { op, left, right } => schedule(
|
||||
self,
|
||||
&mut tasks,
|
||||
&[
|
||||
Child(left, Parent::Binary(*op, Side::Left), depth + 1),
|
||||
Text(operator(*op).0),
|
||||
Child(right, Parent::Binary(*op, Side::Right), depth + 1),
|
||||
],
|
||||
)?,
|
||||
E::If {
|
||||
condition,
|
||||
when_true,
|
||||
when_false,
|
||||
} => schedule(
|
||||
self,
|
||||
&mut tasks,
|
||||
&[
|
||||
Text("if("),
|
||||
Child(condition, Parent::Root, depth + 1),
|
||||
Text(", "),
|
||||
Child(when_true, Parent::Root, depth + 1),
|
||||
Text(", "),
|
||||
Child(when_false, Parent::Root, depth + 1),
|
||||
Text(")"),
|
||||
],
|
||||
)?,
|
||||
E::Call {
|
||||
definition,
|
||||
arguments,
|
||||
} => {
|
||||
let alias =
|
||||
self.definition_name(*definition, DefinitionKind::Calculation)?;
|
||||
let project = self.project;
|
||||
let a::DefinitionBody::Calculation(callee) =
|
||||
&project.definitions[&definition.local()].body
|
||||
else {
|
||||
unreachable!("checked calculation domain")
|
||||
};
|
||||
if arguments.len() != callee.parameters.len()
|
||||
|| callee
|
||||
.parameters
|
||||
.iter()
|
||||
.any(|parameter| !arguments.contains_key(¶meter.id))
|
||||
{
|
||||
return Err(self.error(
|
||||
"Call argument IDs must match the called signature exactly.",
|
||||
));
|
||||
}
|
||||
self.pending(
|
||||
tasks
|
||||
.len()
|
||||
.saturating_add(arguments.len().saturating_mul(4))
|
||||
.saturating_add(1),
|
||||
)?;
|
||||
self.entry()?;
|
||||
self.text("@")?;
|
||||
self.name(alias)?;
|
||||
self.text("(")?;
|
||||
tasks.push(Text(")"));
|
||||
for (index, parameter) in callee.parameters.iter().enumerate().rev() {
|
||||
tasks.push(Child(
|
||||
&arguments[¶meter.id],
|
||||
Parent::Root,
|
||||
depth + 1,
|
||||
));
|
||||
tasks.push(Text(": "));
|
||||
tasks.push(Alias(¶meter.name));
|
||||
if index != 0 {
|
||||
tasks.push(Text(", "));
|
||||
}
|
||||
}
|
||||
}
|
||||
E::Sum { values, initial } => schedule(
|
||||
self,
|
||||
&mut tasks,
|
||||
&[
|
||||
Text("sum("),
|
||||
Child(values, Parent::Root, depth + 1),
|
||||
Text(", "),
|
||||
Child(initial, Parent::Root, depth + 1),
|
||||
Text(")"),
|
||||
],
|
||||
)?,
|
||||
E::Power { base, exponent } => {
|
||||
if !(-16..=16).contains(exponent) {
|
||||
return Err(self.error("Power exponent exceeds -16..16."));
|
||||
}
|
||||
schedule(
|
||||
self,
|
||||
&mut tasks,
|
||||
&[
|
||||
Text("power("),
|
||||
Child(base, Parent::Root, depth + 1),
|
||||
Text(", "),
|
||||
Exponent(*exponent),
|
||||
Text(")"),
|
||||
],
|
||||
)?;
|
||||
}
|
||||
E::AsKind { kind, value } => {
|
||||
let alias =
|
||||
self.definition_name(*kind, DefinitionKind::QuantityKind)?;
|
||||
schedule(
|
||||
self,
|
||||
&mut tasks,
|
||||
&[
|
||||
Text("as_kind(@"),
|
||||
Alias(alias),
|
||||
Text(", "),
|
||||
Child(value, Parent::Root, depth + 1),
|
||||
Text(")"),
|
||||
],
|
||||
)?;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,910 @@
|
||||
use super::super::{cursor::Cursor, declarations, lex, lower, model_oracle};
|
||||
use super::*;
|
||||
use crate::language::ParseLimits;
|
||||
use a::{
|
||||
AnalysisType, BinaryOp, Binding, DefinitionBody, DefinitionRef, Expr, ParameterId, ScalarType,
|
||||
UnaryOp,
|
||||
};
|
||||
|
||||
fn limits() -> Limits {
|
||||
Limits::source8(ParseLimits::UNLIMITED)
|
||||
}
|
||||
fn writer(project: &Project) -> Writer<'_> {
|
||||
Writer::new(project, limits()).unwrap()
|
||||
}
|
||||
fn id(text: &str) -> Id {
|
||||
Id::parse_str(text).unwrap()
|
||||
}
|
||||
fn object(project: &Project, alias: &str) -> Id {
|
||||
project
|
||||
.identities()
|
||||
.into_iter()
|
||||
.find(|(_, name)| *name == alias)
|
||||
.unwrap()
|
||||
.0
|
||||
}
|
||||
fn number(value: i64) -> Expr {
|
||||
Expr::Number(Exact::from_integer(value))
|
||||
}
|
||||
fn unary(op: UnaryOp, value: Expr) -> Expr {
|
||||
Expr::Unary {
|
||||
op,
|
||||
operand: Box::new(value),
|
||||
}
|
||||
}
|
||||
fn binary(op: BinaryOp, left: Expr, right: Expr) -> Expr {
|
||||
Expr::Binary {
|
||||
op,
|
||||
left: Box::new(left),
|
||||
right: Box::new(right),
|
||||
}
|
||||
}
|
||||
fn quantity(value: i64, unit: Id) -> Expr {
|
||||
Expr::Quantity {
|
||||
magnitude: Exact::from_integer(value),
|
||||
unit: DefinitionRef::Local(unit),
|
||||
}
|
||||
}
|
||||
fn budget() -> budget::Budget {
|
||||
budget::Budget::new(budget::Limits::source8(ParseLimits::UNLIMITED)).unwrap()
|
||||
}
|
||||
fn unit(source: &str, budget: &mut budget::Budget) -> Result<lower::Unit, super::super::Error> {
|
||||
let tokens = lex::tokens(source, budget)?;
|
||||
let mut cursor = Cursor::new(source, &tokens, budget);
|
||||
let mut parsed = Vec::new();
|
||||
while cursor.cursor < tokens.len() {
|
||||
parsed.push(declarations::parse(&mut cursor, 8, None)?);
|
||||
}
|
||||
Ok(lower::Unit {
|
||||
file: 1,
|
||||
declarations: parsed,
|
||||
})
|
||||
}
|
||||
fn merge(mut project: Project, lowered: lower::Lowered) -> Project {
|
||||
project.definitions.extend(lowered.definitions);
|
||||
project.elements.extend(lowered.elements);
|
||||
project
|
||||
}
|
||||
fn parse_typed(project: Project, source: &str) -> Project {
|
||||
let mut budget = budget();
|
||||
let unit = unit(source, &mut budget).unwrap();
|
||||
let lowered = lower::lower(&project, &[unit], &budget).unwrap();
|
||||
merge(project, lowered)
|
||||
}
|
||||
fn skeleton(project: &Project) -> Project {
|
||||
let mut project = project.clone();
|
||||
project.definitions.clear();
|
||||
project
|
||||
.elements
|
||||
.retain(|_, element| !element.kind().is_analysis());
|
||||
project
|
||||
}
|
||||
fn canonical(project: &Project) -> String {
|
||||
writer(project)
|
||||
.typed_declarations()
|
||||
.unwrap()
|
||||
.into_iter()
|
||||
.map(|(_, text)| text)
|
||||
.collect()
|
||||
}
|
||||
fn read_expression(project: &Project, source: &str) -> Expr {
|
||||
// A staged syntax/lowering wrapper, not a whole public source8 parser.
|
||||
let source = format!(
|
||||
r#"calculation writer_probe "Probe" id "00000000-0000-0000-0000-000000000099" {{
|
||||
input a id "28ff40b0-1b8f-4735-8536-5a6ab21b56cb" : Quantity(@duration);
|
||||
input b id "7a47cc1e-8ae5-4551-b2d8-8a68108e0976" : Quantity(@duration);
|
||||
result Number; body {source};
|
||||
}}"#
|
||||
);
|
||||
let mut parsed = parse_typed(project.clone(), &source);
|
||||
let definition = parsed.definitions.remove(&Id::from_u128(0x99)).unwrap();
|
||||
let DefinitionBody::Calculation(calculation) = definition.body else {
|
||||
panic!("calculation")
|
||||
};
|
||||
let Binding::Expression(expression) = calculation.body else {
|
||||
panic!("expression")
|
||||
};
|
||||
expression
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn typed_oa_sa_canonical_roundtrips_match_independent_projects() {
|
||||
for (layer, ordinary_source) in [
|
||||
(
|
||||
Layer::Oa,
|
||||
include_str!("../lower/fixtures/ordinary-oa.arcadia"),
|
||||
),
|
||||
(
|
||||
Layer::Sa,
|
||||
include_str!("../lower/fixtures/ordinary-sa.arcadia"),
|
||||
),
|
||||
] {
|
||||
let expected = model_oracle::project(layer);
|
||||
for (alias, name) in model_oracle::NAMES {
|
||||
let id = object(&expected, alias);
|
||||
assert_eq!(
|
||||
expected
|
||||
.definitions
|
||||
.get(&id)
|
||||
.map(|value| value.name.as_str())
|
||||
.or_else(|| expected.elements.get(&id).map(|value| value.name.as_str()))
|
||||
.unwrap(),
|
||||
name
|
||||
);
|
||||
}
|
||||
let text = canonical(&expected);
|
||||
let actual = parse_typed(crate::language::parse(ordinary_source).unwrap(), &text);
|
||||
assert_eq!(actual, expected);
|
||||
a::admit(&actual, a::AdmissionLimits::REFERENCE).unwrap();
|
||||
assert_eq!(canonical(&actual), text);
|
||||
assert!(
|
||||
!text.contains("engineering_property")
|
||||
&& !text.contains("analysis_case")
|
||||
&& !text.contains("analysis_check")
|
||||
);
|
||||
let prefix = if layer == Layer::Oa { "oa" } else { "sa" };
|
||||
for word in ["property", "check", "analysis"] {
|
||||
assert!(text.contains(&format!("{prefix}_{word} ")));
|
||||
}
|
||||
}
|
||||
assert!(crate::language::parse("arcadia 8; project p \"P\" {}").is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn typed_declaration_order_and_required_empty_values_are_canonical() {
|
||||
let mut project = model_oracle::project(Layer::Oa);
|
||||
let duration = object(&project, "duration");
|
||||
let total = object(&project, "total_time");
|
||||
if let Some(SharedBody::EngineeringProperty { display_unit, .. }) =
|
||||
project.elements.get_mut(&total).unwrap().body.shared_mut()
|
||||
{
|
||||
*display_unit = None;
|
||||
}
|
||||
let empty_case = object(&project, "unmeasured");
|
||||
if let Some(SharedBody::AnalysisCase { overrides, .. }) = project
|
||||
.elements
|
||||
.get_mut(&empty_case)
|
||||
.unwrap()
|
||||
.body
|
||||
.shared_mut()
|
||||
{
|
||||
overrides.clear();
|
||||
}
|
||||
let degraded = object(&project, "degraded");
|
||||
let dispatch = object(&project, "dispatch_time");
|
||||
let second = object(&project, "second");
|
||||
if let Some(SharedBody::AnalysisCase { overrides, .. }) = project
|
||||
.elements
|
||||
.get_mut(°raded)
|
||||
.unwrap()
|
||||
.body
|
||||
.shared_mut()
|
||||
{
|
||||
overrides.insert(dispatch, Binding::Expression(quantity(1, second)));
|
||||
}
|
||||
let definitions = [
|
||||
(
|
||||
100,
|
||||
"dimensionless",
|
||||
DefinitionBody::QuantityKind(a::QuantityKindDefinition {
|
||||
dimension: crate::analysis_numeric::Dimension::ZERO,
|
||||
algebra: a::QuantityAlgebra::Linear,
|
||||
}),
|
||||
),
|
||||
(
|
||||
101,
|
||||
"point",
|
||||
DefinitionBody::QuantityKind(a::QuantityKindDefinition {
|
||||
dimension: crate::analysis_numeric::Dimension::new([0, 0, 1, 0, 0, 0, 0]).unwrap(),
|
||||
algebra: a::QuantityAlgebra::Affine {
|
||||
difference: DefinitionRef::Local(duration),
|
||||
},
|
||||
}),
|
||||
),
|
||||
(
|
||||
102,
|
||||
"point_unit",
|
||||
DefinitionBody::Unit(a::UnitDefinition {
|
||||
kind: DefinitionRef::Local(Id::from_u128(101)),
|
||||
scale: Exact::from_integer(1),
|
||||
offset: Exact::from_integer(-2),
|
||||
symbol: "\"café\"\n雪".into(),
|
||||
}),
|
||||
),
|
||||
(
|
||||
103,
|
||||
"unused",
|
||||
DefinitionBody::Calculation(a::CalculationDefinition {
|
||||
parameters: Vec::new(),
|
||||
result: AnalysisType::List(ScalarType::Number),
|
||||
body: Binding::Unbound,
|
||||
}),
|
||||
),
|
||||
];
|
||||
for (id, alias, body) in definitions {
|
||||
let id = Id::from_u128(id);
|
||||
project.definitions.insert(
|
||||
id,
|
||||
a::Definition {
|
||||
id,
|
||||
alias: alias.into(),
|
||||
name: alias.into(),
|
||||
description: String::new(),
|
||||
body,
|
||||
},
|
||||
);
|
||||
}
|
||||
let mut writer = writer(&project);
|
||||
let declarations = writer.typed_declarations().unwrap();
|
||||
let ids: Vec<_> = declarations.iter().map(|(id, _)| *id).collect();
|
||||
let expected_ids: Vec<_> = project
|
||||
.definitions
|
||||
.keys()
|
||||
.copied()
|
||||
.chain(
|
||||
project
|
||||
.elements
|
||||
.values()
|
||||
.filter(|element| element.kind().is_analysis())
|
||||
.map(|element| element.id),
|
||||
)
|
||||
.collect();
|
||||
assert_eq!(ids, expected_ids);
|
||||
let text: String = declarations.into_iter().map(|(_, text)| text).collect();
|
||||
assert!(text.find("@receive_time =").unwrap() < text.find("@dispatch_time =").unwrap());
|
||||
for expected in [
|
||||
"dimension {};",
|
||||
"dimension { time 1; };",
|
||||
"algebra Affine(@duration);",
|
||||
"offset ratio(-2, 1);",
|
||||
"result List(Number);",
|
||||
"body unbound;",
|
||||
"display_unit none;",
|
||||
"overrides {};",
|
||||
"parent none;",
|
||||
"subject none;",
|
||||
"documented_constraint none;",
|
||||
] {
|
||||
assert!(text.contains(expected), "{expected}");
|
||||
}
|
||||
assert_eq!(
|
||||
text.matches("\" id \"").count(),
|
||||
project.definitions.len() + 7
|
||||
);
|
||||
let actual = parse_typed(skeleton(&project), &text);
|
||||
assert_eq!(actual, project);
|
||||
a::admit(&actual, a::AdmissionLimits::REFERENCE).unwrap();
|
||||
assert_eq!(canonical(&actual), text);
|
||||
assert_eq!(
|
||||
self::writer(&project)
|
||||
.override_entry(empty_case, total)
|
||||
.unwrap_err()
|
||||
.field,
|
||||
"overrides"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn all_expr_variants_and_precedence_preserve_exact_trees() {
|
||||
let mut project = model_oracle::project(Layer::Oa);
|
||||
let second = object(&project, "second");
|
||||
let duration = object(&project, "duration");
|
||||
let property = object(&project, "receive_time");
|
||||
let total = object(&project, "total_time");
|
||||
let combine = object(&project, "combine");
|
||||
let a = ParameterId(id("28ff40b0-1b8f-4735-8536-5a6ab21b56cb"));
|
||||
let b = ParameterId(id("7a47cc1e-8ae5-4551-b2d8-8a68108e0976"));
|
||||
let numeric = AnalysisType::Scalar(ScalarType::Number);
|
||||
let boolean = AnalysisType::Scalar(ScalarType::Boolean);
|
||||
let duration_type = AnalysisType::Scalar(ScalarType::Quantity(DefinitionRef::Local(duration)));
|
||||
let cases = [
|
||||
(Expr::Boolean(true), "true", boolean.clone()),
|
||||
(number(-1), "ratio(-1, 1)", numeric.clone()),
|
||||
(
|
||||
quantity(-1, second),
|
||||
"ratio(-1, 1) [@second]",
|
||||
duration_type.clone(),
|
||||
),
|
||||
(
|
||||
Expr::Property(property),
|
||||
"@receive_time",
|
||||
duration_type.clone(),
|
||||
),
|
||||
(Expr::Parameter(a), "$a", duration_type.clone()),
|
||||
(
|
||||
Expr::List(vec![number(1), number(2)]),
|
||||
"[1, 2]",
|
||||
AnalysisType::List(ScalarType::Number),
|
||||
),
|
||||
(
|
||||
unary(UnaryOp::Absolute, unary(UnaryOp::Negate, number(2))),
|
||||
"abs(- 2)",
|
||||
numeric.clone(),
|
||||
),
|
||||
(
|
||||
binary(BinaryOp::Add, number(1), number(2)),
|
||||
"1 + 2",
|
||||
numeric.clone(),
|
||||
),
|
||||
(
|
||||
Expr::If {
|
||||
condition: Box::new(Expr::Boolean(true)),
|
||||
when_true: Box::new(number(1)),
|
||||
when_false: Box::new(number(2)),
|
||||
},
|
||||
"if(true, 1, 2)",
|
||||
numeric.clone(),
|
||||
),
|
||||
(
|
||||
Expr::Call {
|
||||
definition: DefinitionRef::Local(combine),
|
||||
arguments: BTreeMap::from([(b, quantity(2, second)), (a, quantity(1, second))]),
|
||||
},
|
||||
"@combine(a: 1 [@second], b: 2 [@second])",
|
||||
duration_type.clone(),
|
||||
),
|
||||
(
|
||||
Expr::Sum {
|
||||
values: Box::new(Expr::List(vec![number(1), number(2)])),
|
||||
initial: Box::new(number(0)),
|
||||
},
|
||||
"sum([1, 2], 0)",
|
||||
numeric.clone(),
|
||||
),
|
||||
(
|
||||
Expr::Power {
|
||||
base: Box::new(number(2)),
|
||||
exponent: -2,
|
||||
},
|
||||
"power(2, -2)",
|
||||
numeric.clone(),
|
||||
),
|
||||
(
|
||||
Expr::AsKind {
|
||||
kind: DefinitionRef::Local(duration),
|
||||
value: Box::new(binary(
|
||||
BinaryOp::Divide,
|
||||
Expr::Power {
|
||||
base: Box::new(quantity(1, second)),
|
||||
exponent: 2,
|
||||
},
|
||||
quantity(1, second),
|
||||
)),
|
||||
},
|
||||
"as_kind(@duration, power(1 [@second], 2) / 1 [@second])",
|
||||
duration_type,
|
||||
),
|
||||
];
|
||||
project.elements.remove(&object(&project, "budget"));
|
||||
for (expected, golden, value_type) in cases {
|
||||
let parameter = matches!(expected, Expr::Parameter(_));
|
||||
let owner = if parameter { combine } else { total };
|
||||
let field = if parameter { Field::Body } else { Field::Base };
|
||||
let text = writer(&project)
|
||||
.expression(owner, field, &expected, Parent::Root)
|
||||
.unwrap();
|
||||
assert_eq!(text, golden);
|
||||
let actual = read_expression(&project, &text);
|
||||
assert_eq!(actual, expected);
|
||||
let mut candidate = project.clone();
|
||||
if parameter {
|
||||
let DefinitionBody::Calculation(calculation) =
|
||||
&mut candidate.definitions.get_mut(&combine).unwrap().body
|
||||
else {
|
||||
panic!()
|
||||
};
|
||||
calculation.body = Binding::Expression(actual);
|
||||
} else {
|
||||
let Some(SharedBody::EngineeringProperty {
|
||||
base,
|
||||
value_type: ty,
|
||||
display_unit,
|
||||
..
|
||||
}) = candidate
|
||||
.elements
|
||||
.get_mut(&total)
|
||||
.unwrap()
|
||||
.body
|
||||
.shared_mut()
|
||||
else {
|
||||
panic!()
|
||||
};
|
||||
*base = Binding::Expression(actual);
|
||||
*ty = value_type;
|
||||
*display_unit = None;
|
||||
}
|
||||
a::admit(&candidate, a::AdmissionLimits::REFERENCE).unwrap();
|
||||
}
|
||||
let cases = [
|
||||
(unary(UnaryOp::Negate, number(1)), "- 1"),
|
||||
(unary(UnaryOp::Negate, number(-1)), "- ratio(-1, 1)"),
|
||||
(
|
||||
unary(UnaryOp::Negate, unary(UnaryOp::Negate, number(1))),
|
||||
"- - 1",
|
||||
),
|
||||
(
|
||||
unary(UnaryOp::Negate, binary(BinaryOp::Add, number(1), number(2))),
|
||||
"- (1 + 2)",
|
||||
),
|
||||
(unary(UnaryOp::Not, Expr::Boolean(true)), "not(true)"),
|
||||
(
|
||||
binary(
|
||||
BinaryOp::Subtract,
|
||||
number(1),
|
||||
binary(BinaryOp::Subtract, number(2), number(3)),
|
||||
),
|
||||
"1 - (2 - 3)",
|
||||
),
|
||||
(
|
||||
binary(
|
||||
BinaryOp::Subtract,
|
||||
binary(BinaryOp::Subtract, number(1), number(2)),
|
||||
number(3),
|
||||
),
|
||||
"1 - 2 - 3",
|
||||
),
|
||||
(
|
||||
binary(
|
||||
BinaryOp::Add,
|
||||
number(1),
|
||||
binary(BinaryOp::Add, number(2), number(3)),
|
||||
),
|
||||
"1 + (2 + 3)",
|
||||
),
|
||||
(
|
||||
binary(
|
||||
BinaryOp::Multiply,
|
||||
binary(BinaryOp::Add, number(1), number(2)),
|
||||
number(3),
|
||||
),
|
||||
"(1 + 2) * 3",
|
||||
),
|
||||
(
|
||||
binary(
|
||||
BinaryOp::Equal,
|
||||
binary(BinaryOp::Less, number(1), number(2)),
|
||||
Expr::Boolean(true),
|
||||
),
|
||||
"(1 < 2) == true",
|
||||
),
|
||||
(
|
||||
binary(
|
||||
BinaryOp::Equal,
|
||||
binary(BinaryOp::Equal, Expr::Boolean(true), Expr::Boolean(false)),
|
||||
Expr::Boolean(true),
|
||||
),
|
||||
"(true == false) == true",
|
||||
),
|
||||
(
|
||||
binary(
|
||||
BinaryOp::Equal,
|
||||
Expr::Boolean(true),
|
||||
binary(BinaryOp::Less, number(1), number(2)),
|
||||
),
|
||||
"true == (1 < 2)",
|
||||
),
|
||||
(Expr::List(Vec::new()), "[]"),
|
||||
];
|
||||
for (expected, golden) in cases {
|
||||
let text = writer(&project)
|
||||
.expression(total, Field::Base, &expected, Parent::Root)
|
||||
.unwrap();
|
||||
assert_eq!(text, golden);
|
||||
assert_eq!(read_expression(&project, &text), expected);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn canonical_calls_use_callee_parameter_order_and_qualified_names() {
|
||||
let mut project = model_oracle::project(Layer::Oa);
|
||||
let combine = object(&project, "combine");
|
||||
let total = object(&project, "total_time");
|
||||
let duration = object(&project, "duration");
|
||||
let a = ParameterId(id("28ff40b0-1b8f-4735-8536-5a6ab21b56cb"));
|
||||
let b = ParameterId(id("7a47cc1e-8ae5-4551-b2d8-8a68108e0976"));
|
||||
let DefinitionBody::Calculation(calculation) =
|
||||
&mut project.definitions.get_mut(&combine).unwrap().body
|
||||
else {
|
||||
panic!()
|
||||
};
|
||||
calculation.parameters.reverse();
|
||||
let other = Id::from_u128(120);
|
||||
project.definitions.insert(
|
||||
other,
|
||||
a::Definition {
|
||||
id: other,
|
||||
alias: "other".into(),
|
||||
name: "Other".into(),
|
||||
description: String::new(),
|
||||
body: DefinitionBody::Calculation(a::CalculationDefinition {
|
||||
parameters: vec![a::Parameter {
|
||||
id: a,
|
||||
name: "first".into(),
|
||||
value_type: AnalysisType::Scalar(ScalarType::Quantity(DefinitionRef::Local(
|
||||
duration,
|
||||
))),
|
||||
}],
|
||||
result: AnalysisType::Scalar(ScalarType::Quantity(DefinitionRef::Local(duration))),
|
||||
body: Binding::Expression(Expr::Parameter(a)),
|
||||
}),
|
||||
},
|
||||
);
|
||||
project.definitions.insert(
|
||||
a.0,
|
||||
a::Definition {
|
||||
id: a.0,
|
||||
alias: "collision".into(),
|
||||
name: "Collision".into(),
|
||||
description: String::new(),
|
||||
body: DefinitionBody::QuantityKind(a::QuantityKindDefinition {
|
||||
dimension: crate::analysis_numeric::Dimension::ZERO,
|
||||
algebra: a::QuantityAlgebra::Linear,
|
||||
}),
|
||||
},
|
||||
);
|
||||
let mut out = writer(&project);
|
||||
let text = out.binding(total, Field::Base).unwrap();
|
||||
assert!(text.starts_with("@combine(b: @dispatch_time, a: @receive_time)"));
|
||||
let call = Expr::Call {
|
||||
definition: DefinitionRef::Local(other),
|
||||
arguments: BTreeMap::from([(a, Expr::Parameter(a))]),
|
||||
};
|
||||
assert_eq!(
|
||||
out.expression(combine, Field::Body, &call, Parent::Root)
|
||||
.unwrap(),
|
||||
"@other(first: $a)"
|
||||
);
|
||||
assert!(out.parameter(combine, a).unwrap().starts_with("input a id"));
|
||||
assert!(
|
||||
out.parameter(other, a)
|
||||
.unwrap()
|
||||
.starts_with("input first id")
|
||||
);
|
||||
assert!(out.parameter(combine, b).unwrap().starts_with("input b id"));
|
||||
let text = canonical(&project);
|
||||
let actual = parse_typed(skeleton(&project), &text);
|
||||
assert_eq!(actual, project);
|
||||
a::admit(&actual, a::AdmissionLimits::REFERENCE).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn subtree_output_respects_parent_context_and_retained_delimiters() {
|
||||
let project = model_oracle::project(Layer::Oa);
|
||||
let owner = object(&project, "total_time");
|
||||
for replacement in [
|
||||
binary(BinaryOp::Add, number(1), number(2)),
|
||||
number(-1),
|
||||
unary(UnaryOp::Negate, number(1)),
|
||||
] {
|
||||
let text = writer(&project)
|
||||
.expression(owner, Field::Base, &replacement, Parent::Negate)
|
||||
.unwrap();
|
||||
let source = format!("-{text}"); // replace the entire original operand span `(1)` in `-(1)`
|
||||
assert_eq!(
|
||||
read_expression(&project, &source),
|
||||
unary(UnaryOp::Negate, replacement)
|
||||
);
|
||||
}
|
||||
let value = binary(BinaryOp::Subtract, number(2), number(3));
|
||||
let text = writer(&project)
|
||||
.expression(
|
||||
owner,
|
||||
Field::Base,
|
||||
&value,
|
||||
Parent::Binary(BinaryOp::Subtract, Side::Right),
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(text, "(2 - 3)");
|
||||
assert_eq!(
|
||||
read_expression(&project, &format!("1 - {text}")),
|
||||
binary(BinaryOp::Subtract, number(1), value)
|
||||
);
|
||||
assert_eq!(
|
||||
writer(&project)
|
||||
.value_type(owner, &AnalysisType::List(ScalarType::Boolean))
|
||||
.unwrap(),
|
||||
"List(Boolean)"
|
||||
);
|
||||
let case = object(&project, "unmeasured");
|
||||
let property = object(&project, "receive_time");
|
||||
assert_eq!(
|
||||
writer(&project).override_entry(case, property).unwrap(),
|
||||
"@receive_time = unbound;"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn canonical_strings_and_exact_literals_use_existing_encodings() {
|
||||
let mut project = model_oracle::project(Layer::Oa);
|
||||
let second = object(&project, "second");
|
||||
let text = "\"\\\n\r\t\u{0000} café 雪";
|
||||
project.definitions.get_mut(&second).unwrap().name = text.into();
|
||||
project.definitions.get_mut(&second).unwrap().description = text.into();
|
||||
let DefinitionBody::Unit(unit) = &mut project.definitions.get_mut(&second).unwrap().body else {
|
||||
panic!()
|
||||
};
|
||||
unit.symbol = text.into();
|
||||
let output = writer(&project).definition(second).unwrap();
|
||||
assert_eq!(output.matches(&crate::language::quote(text)).count(), 3);
|
||||
let actual = parse_typed(skeleton(&project), &canonical(&project));
|
||||
assert_eq!(actual, project);
|
||||
let owner = object(&project, "total_time");
|
||||
for source in ["0", "ratio(-1, 1)", "ratio(3, 2)", "1e100"] {
|
||||
let expression = read_expression(&project, source);
|
||||
let Expr::Number(value) = &expression else {
|
||||
panic!()
|
||||
};
|
||||
assert_eq!(
|
||||
writer(&project)
|
||||
.expression(owner, Field::Base, &expression, Parent::Root)
|
||||
.unwrap(),
|
||||
value.canonical_literal()
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn writer_limits_are_aggregate_exact_and_latched_without_partial_results() {
|
||||
let project = model_oracle::project(Layer::Oa);
|
||||
let owner = object(&project, "total_time");
|
||||
let mut one = Writer::new(
|
||||
&project,
|
||||
Limits {
|
||||
bytes: 1,
|
||||
..limits()
|
||||
},
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
one.expression(owner, Field::Base, &number(1), Parent::Root)
|
||||
.unwrap(),
|
||||
"1"
|
||||
);
|
||||
let failure = one
|
||||
.expression(owner, Field::Base, &number(2), Parent::Root)
|
||||
.unwrap_err();
|
||||
assert_eq!(
|
||||
failure,
|
||||
one.expression(owner, Field::Base, &number(0), Parent::Root)
|
||||
.unwrap_err()
|
||||
);
|
||||
assert_eq!(one.usage().bytes, 1);
|
||||
let mut measured = writer(&project);
|
||||
measured
|
||||
.expression(owner, Field::Base, &number(1), Parent::Root)
|
||||
.unwrap();
|
||||
let usage = measured.usage();
|
||||
for (maximum, pass) in [(usage.entries, true), (usage.entries - 1, false)] {
|
||||
let mut bounded = Writer::new(
|
||||
&project,
|
||||
Limits {
|
||||
entries: maximum,
|
||||
..limits()
|
||||
},
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
bounded
|
||||
.expression(owner, Field::Base, &number(1), Parent::Root)
|
||||
.is_ok(),
|
||||
pass
|
||||
);
|
||||
}
|
||||
let output = canonical(&project);
|
||||
let mut exact = Writer::new(
|
||||
&project,
|
||||
Limits {
|
||||
bytes: output.len(),
|
||||
..limits()
|
||||
},
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(exact.typed_declarations().unwrap().len(), 11);
|
||||
let mut short = Writer::new(
|
||||
&project,
|
||||
Limits {
|
||||
bytes: output.len() - 1,
|
||||
..limits()
|
||||
},
|
||||
)
|
||||
.unwrap();
|
||||
assert!(short.typed_declarations().is_err());
|
||||
assert_eq!(canonical(&project), output);
|
||||
let mut quoted = project.clone();
|
||||
let unit_id = object("ed, "second");
|
||||
quoted.definitions.get_mut(&unit_id).unwrap().name = "雪\n\"".into();
|
||||
let text = writer("ed).definition(unit_id).unwrap();
|
||||
for (maximum, pass) in [(text.len(), true), (text.len() - 1, false)] {
|
||||
assert_eq!(
|
||||
Writer::new(
|
||||
"ed,
|
||||
Limits {
|
||||
bytes: maximum,
|
||||
..limits()
|
||||
}
|
||||
)
|
||||
.unwrap()
|
||||
.definition(unit_id)
|
||||
.is_ok(),
|
||||
pass
|
||||
);
|
||||
}
|
||||
assert!(
|
||||
Writer::new(
|
||||
&project,
|
||||
Limits {
|
||||
bytes: usize::MAX,
|
||||
..limits()
|
||||
}
|
||||
)
|
||||
.is_err()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn writer_lookup_scope_shape_and_depth_failures_are_model_located() {
|
||||
let project = model_oracle::project(Layer::Oa);
|
||||
let owner = object(&project, "total_time");
|
||||
let combine = object(&project, "combine");
|
||||
let duration = object(&project, "duration");
|
||||
let a = ParameterId(id("28ff40b0-1b8f-4735-8536-5a6ab21b56cb"));
|
||||
let cases = [
|
||||
Expr::Property(duration),
|
||||
Expr::Property(Id::nil()),
|
||||
Expr::Quantity {
|
||||
magnitude: Exact::from_integer(1),
|
||||
unit: DefinitionRef::Local(duration),
|
||||
},
|
||||
Expr::Parameter(a),
|
||||
Expr::Call {
|
||||
definition: DefinitionRef::Local(duration),
|
||||
arguments: BTreeMap::new(),
|
||||
},
|
||||
Expr::Call {
|
||||
definition: DefinitionRef::Local(combine),
|
||||
arguments: BTreeMap::new(),
|
||||
},
|
||||
Expr::Call {
|
||||
definition: DefinitionRef::Local(combine),
|
||||
arguments: BTreeMap::from([(ParameterId(Id::nil()), number(1)), (a, number(2))]),
|
||||
},
|
||||
Expr::Power {
|
||||
base: Box::new(number(1)),
|
||||
exponent: 17,
|
||||
},
|
||||
Expr::List((0..1025).map(|_| number(1)).collect()),
|
||||
];
|
||||
for expression in cases {
|
||||
let error = writer(&project)
|
||||
.expression(owner, Field::Base, &expression, Parent::Root)
|
||||
.unwrap_err();
|
||||
assert_eq!(error.owner, Some(owner));
|
||||
assert_eq!(error.field, "base");
|
||||
}
|
||||
assert!(
|
||||
writer(&project)
|
||||
.expression(
|
||||
combine,
|
||||
Field::Body,
|
||||
&Expr::Parameter(ParameterId(Id::nil())),
|
||||
Parent::Root
|
||||
)
|
||||
.is_err()
|
||||
);
|
||||
assert!(writer(&project).binding(owner, Field::Body).is_err());
|
||||
assert!(
|
||||
writer(&project)
|
||||
.analysis_element(object(&project, "respond"))
|
||||
.is_err()
|
||||
);
|
||||
let mut deep = number(-1);
|
||||
for _ in 0..128 {
|
||||
deep = unary(UnaryOp::Negate, deep);
|
||||
}
|
||||
assert!(
|
||||
writer(&project)
|
||||
.expression(owner, Field::Base, &deep, Parent::Root)
|
||||
.unwrap_err()
|
||||
.message
|
||||
.contains("depth")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn negate_override_roundtrip_preserves_depth128_within_frame256() {
|
||||
let original = model_oracle::project(Layer::Oa);
|
||||
let prefix = format!("{}ratio(-1, 1)", "- ".repeat(127));
|
||||
let grouped = format!("{}ratio(-1, 1){}", "-(".repeat(127), ")".repeat(127));
|
||||
let property = r#"oa_property measure "Measure" id "00000000-0000-0000-0000-000000000130" { subject @respond; type Number; base unbound; }"#;
|
||||
let case = |expression: &str| {
|
||||
format!(
|
||||
r#"oa_analysis measured "Measured" id "00000000-0000-0000-0000-000000000131" {{ base ModelBaseline; overrides {{ @measure = {expression}; }}; }}"#
|
||||
)
|
||||
};
|
||||
let calculation = |expression: &str| {
|
||||
format!(
|
||||
r#"calculation measured_calc "Measured calculation" id "00000000-0000-0000-0000-000000000132" {{ result Number; body {expression}; }}"#
|
||||
)
|
||||
};
|
||||
for (source, frames) in [
|
||||
(case(&prefix), 130),
|
||||
(calculation(&prefix), 129),
|
||||
(calculation(&grouped), 256),
|
||||
] {
|
||||
let mut budget = budget();
|
||||
unit(&source, &mut budget).unwrap();
|
||||
assert_eq!(budget.usage.deepest_frame, frames);
|
||||
}
|
||||
let mut failed_budget = budget();
|
||||
let error = unit(&case(&grouped), &mut failed_budget).err().unwrap();
|
||||
assert!(error.message.contains("syntax frames"));
|
||||
assert_eq!(failed_budget.usage.deepest_frame, 256);
|
||||
let project = parse_typed(original, &format!("{property}\n{}", case(&prefix)));
|
||||
a::admit(&project, a::AdmissionLimits::REFERENCE).unwrap();
|
||||
let case_id = Id::from_u128(0x131);
|
||||
let property_id = Id::from_u128(0x130);
|
||||
let Some(SharedBody::AnalysisCase { overrides, .. }) = project.elements[&case_id].shared()
|
||||
else {
|
||||
panic!()
|
||||
};
|
||||
let Binding::Expression(root) = &overrides[&property_id] else {
|
||||
panic!()
|
||||
};
|
||||
let mut current = root;
|
||||
let mut negates = 0;
|
||||
while let Expr::Unary {
|
||||
op: UnaryOp::Negate,
|
||||
operand,
|
||||
} = current
|
||||
{
|
||||
current = operand;
|
||||
negates += 1;
|
||||
}
|
||||
assert_eq!(negates, 127);
|
||||
assert_eq!(current, &number(-1));
|
||||
let text = writer(&project).analysis_element(case_id).unwrap();
|
||||
assert!(text.contains(&prefix));
|
||||
let mut budget = budget();
|
||||
unit(&text, &mut budget).unwrap();
|
||||
assert_eq!(budget.usage.deepest_frame, 130);
|
||||
let mut before_case = project.clone();
|
||||
before_case.elements.remove(&case_id);
|
||||
let actual = parse_typed(before_case, &text);
|
||||
assert_eq!(actual, project);
|
||||
assert_eq!(writer(&actual).analysis_element(case_id).unwrap(), text);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn iterative_writer_preserves_width1024_and_empty_call_topology() {
|
||||
let mut project = model_oracle::project(Layer::Oa);
|
||||
let owner = object(&project, "total_time");
|
||||
let expected = Expr::List((0..1024).map(|_| number(1)).collect());
|
||||
let text = writer(&project)
|
||||
.expression(owner, Field::Base, &expected, Parent::Root)
|
||||
.unwrap();
|
||||
assert_eq!(read_expression(&project, &text), expected);
|
||||
let empty = Id::from_u128(140);
|
||||
project.definitions.insert(
|
||||
empty,
|
||||
a::Definition {
|
||||
id: empty,
|
||||
alias: "empty".into(),
|
||||
name: "Empty".into(),
|
||||
description: String::new(),
|
||||
body: DefinitionBody::Calculation(a::CalculationDefinition {
|
||||
parameters: Vec::new(),
|
||||
result: AnalysisType::Scalar(ScalarType::Number),
|
||||
body: Binding::Unbound,
|
||||
}),
|
||||
},
|
||||
);
|
||||
let call = Expr::Call {
|
||||
definition: DefinitionRef::Local(empty),
|
||||
arguments: BTreeMap::new(),
|
||||
};
|
||||
let text = writer(&project)
|
||||
.expression(owner, Field::Base, &call, Parent::Root)
|
||||
.unwrap();
|
||||
assert_eq!(text, "@empty()");
|
||||
assert_eq!(read_expression(&project, &text), call);
|
||||
}
|
||||
@@ -0,0 +1,347 @@
|
||||
//! One raw lexical scan for legacy adapters and staged typed source syntax.
|
||||
//! Numbers remain source spans; only consumers choose a numeric domain.
|
||||
use super::Span;
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub(super) enum Class {
|
||||
Word,
|
||||
Number,
|
||||
String,
|
||||
Punctuation,
|
||||
Whitespace,
|
||||
Comment,
|
||||
Error,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
pub(super) struct Token {
|
||||
pub class: Class,
|
||||
pub span: Span,
|
||||
/// Entire token belongs to the old greedy numeric-token alphabet.
|
||||
pub legacy_number_part: bool,
|
||||
}
|
||||
|
||||
pub(super) struct Scanner<'a> {
|
||||
source: &'a str,
|
||||
cursor: usize,
|
||||
}
|
||||
|
||||
impl<'a> Scanner<'a> {
|
||||
pub fn new(source: &'a str) -> Self {
|
||||
Self { source, cursor: 0 }
|
||||
}
|
||||
}
|
||||
|
||||
impl Iterator for Scanner<'_> {
|
||||
type Item = Token;
|
||||
|
||||
fn next(&mut self) -> Option<Token> {
|
||||
let source = self.source;
|
||||
let bytes = source.as_bytes();
|
||||
let start = self.cursor;
|
||||
let first = *bytes.get(start)?;
|
||||
let mut legacy_number_part = false;
|
||||
let class = if matches!(first, b' ' | b'\t' | b'\r' | b'\n') {
|
||||
self.cursor += 1;
|
||||
while bytes
|
||||
.get(self.cursor)
|
||||
.is_some_and(|b| matches!(b, b' ' | b'\t' | b'\r' | b'\n'))
|
||||
{
|
||||
self.cursor += 1;
|
||||
}
|
||||
Class::Whitespace
|
||||
} else if bytes[start..].starts_with(b"//") {
|
||||
self.cursor += 2;
|
||||
while bytes.get(self.cursor).is_some_and(|b| *b != b'\n') {
|
||||
self.cursor += 1;
|
||||
}
|
||||
Class::Comment
|
||||
} else if first.is_ascii_alphabetic() || first == b'_' {
|
||||
self.cursor += 1;
|
||||
while bytes
|
||||
.get(self.cursor)
|
||||
.is_some_and(|b| b.is_ascii_alphanumeric() || *b == b'_')
|
||||
{
|
||||
self.cursor += 1;
|
||||
}
|
||||
legacy_number_part = true;
|
||||
Class::Word
|
||||
} else if first.is_ascii_digit() {
|
||||
while bytes.get(self.cursor).is_some_and(u8::is_ascii_digit) {
|
||||
self.cursor += 1;
|
||||
}
|
||||
let mut valid = true;
|
||||
if bytes.get(self.cursor) == Some(&b'.') {
|
||||
self.cursor += 1;
|
||||
let fraction = self.cursor;
|
||||
while bytes.get(self.cursor).is_some_and(u8::is_ascii_digit) {
|
||||
self.cursor += 1;
|
||||
}
|
||||
valid &= self.cursor != fraction;
|
||||
}
|
||||
if matches!(bytes.get(self.cursor), Some(b'e' | b'E')) {
|
||||
self.cursor += 1;
|
||||
if matches!(bytes.get(self.cursor), Some(b'+' | b'-')) {
|
||||
self.cursor += 1;
|
||||
}
|
||||
let exponent = self.cursor;
|
||||
while bytes.get(self.cursor).is_some_and(u8::is_ascii_digit) {
|
||||
self.cursor += 1;
|
||||
}
|
||||
valid &= self.cursor != exponent;
|
||||
}
|
||||
if bytes
|
||||
.get(self.cursor)
|
||||
.is_some_and(|b| b.is_ascii_alphabetic() || matches!(b, b'_' | b'.'))
|
||||
{
|
||||
valid = false;
|
||||
while bytes
|
||||
.get(self.cursor)
|
||||
.is_some_and(|b| b.is_ascii_alphanumeric() || matches!(b, b'_' | b'.'))
|
||||
{
|
||||
self.cursor += 1;
|
||||
}
|
||||
}
|
||||
legacy_number_part = true;
|
||||
if valid { Class::Number } else { Class::Error }
|
||||
} else if first == b'"' {
|
||||
self.cursor += 1;
|
||||
let mut escaped = false;
|
||||
let mut closed = false;
|
||||
while self.cursor < bytes.len() {
|
||||
let ch = source[self.cursor..]
|
||||
.chars()
|
||||
.next()
|
||||
.expect("UTF-8 boundary");
|
||||
self.cursor += ch.len_utf8();
|
||||
if escaped {
|
||||
escaped = false;
|
||||
} else if ch == '\\' {
|
||||
escaped = true;
|
||||
} else if ch == '"' {
|
||||
closed = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if closed && serde_json::from_str::<String>(&source[start..self.cursor]).is_ok() {
|
||||
Class::String
|
||||
} else {
|
||||
Class::Error
|
||||
}
|
||||
} else if b"{}();,[]:=@$+-*/<>!".contains(&first) {
|
||||
self.cursor += 1;
|
||||
if matches!(first, b'<' | b'>' | b'=' | b'!') && bytes.get(self.cursor) == Some(&b'=') {
|
||||
self.cursor += 1;
|
||||
}
|
||||
legacy_number_part = matches!(first, b'+' | b'-');
|
||||
Class::Punctuation
|
||||
} else {
|
||||
self.cursor += source[start..]
|
||||
.chars()
|
||||
.next()
|
||||
.expect("UTF-8 boundary")
|
||||
.len_utf8();
|
||||
legacy_number_part = first == b'.';
|
||||
Class::Error
|
||||
};
|
||||
Some(Token {
|
||||
class,
|
||||
span: Span {
|
||||
start,
|
||||
end: self.cursor,
|
||||
},
|
||||
legacy_number_part,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// Preserve the existing public token shapes, including greedy signed JSON
|
||||
/// numbers and single-character rejection of newer expression operators.
|
||||
pub(super) fn legacy(source: &str) -> Vec<super::TokenSpan> {
|
||||
use super::{TokenClass, TokenSpan};
|
||||
let mut scanner = Scanner::new(source).peekable();
|
||||
let mut out = Vec::new();
|
||||
while let Some(token) = scanner.next() {
|
||||
let mut span = token.span;
|
||||
let first = source.as_bytes()[span.start];
|
||||
if first.is_ascii_digit() || matches!(first, b'+' | b'-' | b'.') {
|
||||
while scanner
|
||||
.peek()
|
||||
.is_some_and(|next| next.legacy_number_part && next.span.start == span.end)
|
||||
{
|
||||
span.end = scanner.next().expect("peeked token").span.end;
|
||||
}
|
||||
let class = if serde_json::from_str::<serde_json::Number>(&source[span.start..span.end])
|
||||
.is_ok()
|
||||
{
|
||||
TokenClass::Number
|
||||
} else {
|
||||
TokenClass::Error
|
||||
};
|
||||
out.push(TokenSpan { class, span });
|
||||
continue;
|
||||
}
|
||||
let class = match token.class {
|
||||
Class::Word => {
|
||||
let word = &source[span.start..span.end];
|
||||
if super::reserved(word) || matches!(word, "true" | "false" | "none") {
|
||||
TokenClass::Keyword
|
||||
} else {
|
||||
TokenClass::Identifier
|
||||
}
|
||||
}
|
||||
Class::String => TokenClass::String,
|
||||
Class::Whitespace => TokenClass::Whitespace,
|
||||
Class::Comment => TokenClass::Comment,
|
||||
Class::Punctuation => {
|
||||
// The raw scanner joins comparison operators. Legacy syntax
|
||||
// classified their ASCII characters individually.
|
||||
for at in span.start..span.end {
|
||||
let class = if b"{}();,[]:=@".contains(&source.as_bytes()[at]) {
|
||||
TokenClass::Punctuation
|
||||
} else {
|
||||
TokenClass::Error
|
||||
};
|
||||
out.push(TokenSpan {
|
||||
class,
|
||||
span: Span {
|
||||
start: at,
|
||||
end: at + 1,
|
||||
},
|
||||
});
|
||||
}
|
||||
continue;
|
||||
}
|
||||
Class::Error => TokenClass::Error,
|
||||
Class::Number => unreachable!("number tokens start with a digit"),
|
||||
};
|
||||
out.push(TokenSpan { class, span });
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::super::{TokenClass, tokenize};
|
||||
|
||||
#[test]
|
||||
fn legacy_adapter_retains_authored_numeric_operator_and_trivia_tokens() {
|
||||
use TokenClass::*;
|
||||
let cases: &[(&str, &[(TokenClass, &str)])] = &[
|
||||
(
|
||||
"-1.5 1e-2 -0",
|
||||
&[
|
||||
(Number, "-1.5"),
|
||||
(Whitespace, " "),
|
||||
(Number, "1e-2"),
|
||||
(Whitespace, " "),
|
||||
(Number, "-0"),
|
||||
],
|
||||
),
|
||||
(
|
||||
"1-2 1 -2 1 - 2",
|
||||
&[
|
||||
(Error, "1-2"),
|
||||
(Whitespace, " "),
|
||||
(Number, "1"),
|
||||
(Whitespace, " "),
|
||||
(Number, "-2"),
|
||||
(Whitespace, " "),
|
||||
(Number, "1"),
|
||||
(Whitespace, " "),
|
||||
(Error, "-"),
|
||||
(Whitespace, " "),
|
||||
(Number, "2"),
|
||||
],
|
||||
),
|
||||
(
|
||||
"+1 .5 1_0 0x1 1e 1e+",
|
||||
&[
|
||||
(Error, "+1"),
|
||||
(Whitespace, " "),
|
||||
(Error, ".5"),
|
||||
(Whitespace, " "),
|
||||
(Error, "1_0"),
|
||||
(Whitespace, " "),
|
||||
(Error, "0x1"),
|
||||
(Whitespace, " "),
|
||||
(Error, "1e"),
|
||||
(Whitespace, " "),
|
||||
(Error, "1e+"),
|
||||
],
|
||||
),
|
||||
(
|
||||
"<= != == >= / * $ !",
|
||||
&[
|
||||
(Error, "<"),
|
||||
(Punctuation, "="),
|
||||
(Whitespace, " "),
|
||||
(Error, "!"),
|
||||
(Punctuation, "="),
|
||||
(Whitespace, " "),
|
||||
(Punctuation, "="),
|
||||
(Punctuation, "="),
|
||||
(Whitespace, " "),
|
||||
(Error, ">"),
|
||||
(Punctuation, "="),
|
||||
(Whitespace, " "),
|
||||
(Error, "/"),
|
||||
(Whitespace, " "),
|
||||
(Error, "*"),
|
||||
(Whitespace, " "),
|
||||
(Error, "$"),
|
||||
(Whitespace, " "),
|
||||
(Error, "!"),
|
||||
],
|
||||
),
|
||||
(
|
||||
"// π\r\n\"雪\" @alias",
|
||||
&[
|
||||
(Comment, "// π\r"),
|
||||
(Whitespace, "\n"),
|
||||
(String, "\"雪\""),
|
||||
(Whitespace, " "),
|
||||
(Punctuation, "@"),
|
||||
(Keyword, "alias"),
|
||||
],
|
||||
),
|
||||
("\"incomplete 雪", &[(Error, "\"incomplete 雪")]),
|
||||
("\"bad\\q\"", &[(Error, "\"bad\\q\"")]),
|
||||
(
|
||||
"雪\u{b}a",
|
||||
&[(Error, "雪"), (Error, "\u{b}"), (Identifier, "a")],
|
||||
),
|
||||
(
|
||||
"unit calculation quantity_kind if and List Number",
|
||||
&[
|
||||
(Identifier, "unit"),
|
||||
(Whitespace, " "),
|
||||
(Identifier, "calculation"),
|
||||
(Whitespace, " "),
|
||||
(Identifier, "quantity_kind"),
|
||||
(Whitespace, " "),
|
||||
(Identifier, "if"),
|
||||
(Whitespace, " "),
|
||||
(Identifier, "and"),
|
||||
(Whitespace, " "),
|
||||
(Identifier, "List"),
|
||||
(Whitespace, " "),
|
||||
(Identifier, "Number"),
|
||||
],
|
||||
),
|
||||
];
|
||||
for (source, expected) in cases {
|
||||
let actual = tokenize(source);
|
||||
assert_eq!(actual.len(), expected.len(), "{source:?}");
|
||||
let mut offset = 0;
|
||||
for (token, (class, spelling)) in actual.iter().zip(*expected) {
|
||||
assert_eq!(token.class, *class, "{source:?} at {offset}");
|
||||
assert_eq!(token.span.start, offset);
|
||||
offset += spelling.len();
|
||||
assert_eq!(token.span.end, offset);
|
||||
assert_eq!(&source[token.span.start..token.span.end], *spelling);
|
||||
}
|
||||
assert_eq!(offset, source.len());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -109,8 +109,16 @@ pub(super) fn resolve_baseline(
|
||||
continue;
|
||||
}
|
||||
let json = raw(value)?;
|
||||
if version < 7 {
|
||||
crate::persistence::reject_source7_fields(&json)
|
||||
.map_err(|cause| error(value, cause))?;
|
||||
}
|
||||
let baseline: SemanticBaseline = serde_json::from_value(json.clone())
|
||||
.map_err(|cause| error(value, format!("Invalid semantic baseline: {cause}")))?;
|
||||
if version < 6 {
|
||||
crate::persistence::check_pre6_baseline(&baseline)
|
||||
.map_err(|cause| error(value, cause.to_string()))?;
|
||||
}
|
||||
let slots = historical_source_slots(&baseline).into_iter().collect();
|
||||
validate_tokens(value, &mut vec![], &slots)?;
|
||||
resolved.insert(key.clone(), json);
|
||||
@@ -186,6 +194,8 @@ pub(super) fn row_key(source: &str, origins: &BTreeMap<Id, Id>) -> Option<String
|
||||
cursor: 0,
|
||||
value_depth: 0,
|
||||
limits: ParseLimits::UNLIMITED,
|
||||
#[cfg(test)]
|
||||
mixed: None,
|
||||
};
|
||||
let ast = parser.value().ok()?;
|
||||
let facet = serde_json::from_value(raw(&ast).ok()?).ok()?;
|
||||
|
||||
@@ -0,0 +1,52 @@
|
||||
//! Convert only source3 lowering scratch state into its frozen migration input.
|
||||
//! This is not a current-to-legacy exporter: fields outside that scratch state
|
||||
//! must reject instead of being silently discarded.
|
||||
use crate::Project;
|
||||
use crate::persistence::{FileError, v3};
|
||||
use serde_json::{Map, Value};
|
||||
|
||||
pub(super) fn from_scratch(
|
||||
project: Project,
|
||||
legacy_elements: Map<String, Value>,
|
||||
) -> Result<v3::Project3, FileError> {
|
||||
// No `..`: a future Project field requires an explicit compatibility decision.
|
||||
let Project {
|
||||
schema_version,
|
||||
id,
|
||||
alias,
|
||||
name,
|
||||
description,
|
||||
definitions,
|
||||
elements,
|
||||
relations,
|
||||
diagrams,
|
||||
artifact_links,
|
||||
traces,
|
||||
} = project;
|
||||
if schema_version != 3 {
|
||||
return Err(FileError::Invalid(
|
||||
"Expected source3 lowering state.".into(),
|
||||
));
|
||||
}
|
||||
if !definitions.is_empty() || !elements.is_empty() {
|
||||
return Err(FileError::Invalid(
|
||||
"Source3 lowering state cannot contain current definitions or elements.".into(),
|
||||
));
|
||||
}
|
||||
Ok(v3::Project3 {
|
||||
schema_version,
|
||||
id,
|
||||
alias,
|
||||
name,
|
||||
description,
|
||||
elements: serde_json::from_value(Value::Object(legacy_elements))?,
|
||||
// Keep the frozen nested contracts, including strict trace baselines.
|
||||
relations: serde_json::from_value(serde_json::to_value(relations)?)?,
|
||||
diagrams,
|
||||
artifact_links,
|
||||
traces: serde_json::from_value(serde_json::to_value(traces)?)?,
|
||||
})
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
@@ -0,0 +1,188 @@
|
||||
use super::*;
|
||||
use crate::{Id, language, persistence};
|
||||
use serde_json::json;
|
||||
|
||||
const SOURCE3: &str = include_str!("../../../tests/fixtures/v3-data-contract.arcadia");
|
||||
const JSON3: &[u8] = include_bytes!("../../../tests/fixtures/v3-data-contract.json");
|
||||
const PROSE: &str = r#"arcadia 3;
|
||||
project review "Review" id "00000000-0000-0000-0000-000000000001" {
|
||||
oa_activity reviewed_activity "Live OA" id "00000000-0000-0000-0000-000000000002" {}
|
||||
sa_function function "Live SA" id "00000000-0000-0000-0000-000000000003" {}
|
||||
trace review_link "Review link" id "00000000-0000-0000-0000-000000000004" {
|
||||
oa @reviewed_activity; sa @function; kind Refinement;
|
||||
baseline {
|
||||
oa { name "Approved OA"; description "First\nΩ rationale"; };
|
||||
sa { name "Approved SA"; description "Prior SA prose"; };
|
||||
};
|
||||
}
|
||||
}"#;
|
||||
|
||||
fn id(value: u128) -> Id {
|
||||
Id::from_u128(value)
|
||||
}
|
||||
|
||||
fn prose_json() -> Value {
|
||||
json!({
|
||||
"schema_version":3,"id":id(1),"alias":"review","name":"Review","description":"",
|
||||
"elements": {
|
||||
id(2).to_string(): {"id":id(2),"alias":"reviewed_activity","name":"Live OA","description":"","parent":null,"body":{"Oa":"Activity"}},
|
||||
id(3).to_string(): {"id":id(3),"alias":"function","name":"Live SA","description":"","parent":null,"body":{"Sa":"Function"}}
|
||||
},
|
||||
"relations":{},"diagrams":{},"artifact_links":{},
|
||||
"traces": {id(4).to_string():{
|
||||
"id":id(4),"alias":"review_link","name":"Review link","description":"",
|
||||
"oa":id(2),"sa":id(3),"kind":"Refinement",
|
||||
"baseline":{"oa":{"name":"Approved OA","description":"First\nΩ rationale"},"sa":{"name":"Approved SA","description":"Prior SA prose"}}
|
||||
}}
|
||||
})
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn frozen_source3_and_json3_have_complete_model_and_migration_parity() {
|
||||
let source = language::parse_with_report(SOURCE3).unwrap();
|
||||
let json = persistence::decode_with_report(JSON3).unwrap();
|
||||
assert_eq!(source.project, json.project);
|
||||
assert_eq!(source.migration, json.migration);
|
||||
assert!(source.project.definitions.is_empty());
|
||||
let report = source.migration.unwrap();
|
||||
assert_eq!(
|
||||
(report.from_schema, report.to_schema),
|
||||
(3, crate::SCHEMA_VERSION)
|
||||
);
|
||||
// This tests direct legacy lowering. Canonical source8 reopening remains a
|
||||
// separate, unchanged public integration gate.
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn frozen_wire_still_rejects_new_unknown_and_duplicate_fields() {
|
||||
let original: Value = serde_json::from_slice(JSON3).unwrap();
|
||||
for definitions in [
|
||||
json!({}),
|
||||
Value::Null,
|
||||
json!({id(90).to_string(): {"name":"new"}}),
|
||||
] {
|
||||
let mut bad = original.clone();
|
||||
bad["definitions"] = definitions;
|
||||
let error = persistence::decode(&serde_json::to_vec(&bad).unwrap())
|
||||
.err()
|
||||
.unwrap()
|
||||
.to_string();
|
||||
assert!(error.contains("unknown field `definitions`"), "{error}");
|
||||
}
|
||||
let mut bad = original;
|
||||
bad["unrecognized"] = json!(true);
|
||||
assert!(
|
||||
persistence::decode(&serde_json::to_vec(&bad).unwrap())
|
||||
.err()
|
||||
.unwrap()
|
||||
.to_string()
|
||||
.contains("unknown field `unrecognized`")
|
||||
);
|
||||
let raw = std::str::from_utf8(JSON3).unwrap();
|
||||
let duplicate = raw.replacen(
|
||||
"\"schema_version\": 3",
|
||||
"\"schema_version\": 3, \"schema_version\": 3",
|
||||
1,
|
||||
);
|
||||
assert_ne!(duplicate, raw);
|
||||
assert!(
|
||||
persistence::decode(duplicate.as_bytes())
|
||||
.err()
|
||||
.unwrap()
|
||||
.to_string()
|
||||
.contains("duplicate")
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn old_review_prose_survives_without_admitting_semantic_fields() {
|
||||
let source = language::parse_with_report(PROSE).unwrap();
|
||||
let json =
|
||||
persistence::decode_with_report(&serde_json::to_vec(&prose_json()).unwrap()).unwrap();
|
||||
assert_eq!(source.project, json.project);
|
||||
assert_eq!(source.migration, json.migration);
|
||||
let baseline = source.project.traces[&id(4)].baseline.as_ref().unwrap();
|
||||
assert_eq!(baseline.oa.name, "Approved OA");
|
||||
assert_eq!(baseline.oa.description, "First\nΩ rationale");
|
||||
assert_eq!(baseline.sa.description, "Prior SA prose");
|
||||
assert!(baseline.semantic.is_none());
|
||||
for semantic in [Value::Null, json!({"facets":[]})] {
|
||||
let mut bad = prose_json();
|
||||
bad["traces"][id(4).to_string()]["baseline"]["semantic"] = semantic;
|
||||
let error = persistence::decode(&serde_json::to_vec(&bad).unwrap())
|
||||
.err()
|
||||
.unwrap()
|
||||
.to_string();
|
||||
assert!(error.contains("semantic"), "{error}");
|
||||
}
|
||||
for field in ["semantic none;", "semantic { facets []; };"] {
|
||||
let bad = PROSE.replace("baseline {", &format!("baseline {{ {field}"));
|
||||
let errors = language::parse(&bad).err().unwrap();
|
||||
assert!(
|
||||
errors
|
||||
.iter()
|
||||
.any(|e| e.message.contains("require schema/source5")),
|
||||
"{errors:?}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn scratch_bridge_refuses_to_discard_current_only_data() {
|
||||
let mut empty = Project::empty();
|
||||
empty.schema_version = 3;
|
||||
assert!(from_scratch(empty.clone(), Map::new()).is_ok());
|
||||
let mut wrong_version = empty.clone();
|
||||
wrong_version.schema_version = crate::SCHEMA_VERSION;
|
||||
assert!(from_scratch(wrong_version, Map::new()).is_err());
|
||||
let mut definition = empty;
|
||||
definition.definitions.insert(
|
||||
id(90),
|
||||
crate::analysis::Definition {
|
||||
id: id(90),
|
||||
alias: "dimensionless".into(),
|
||||
name: "Dimensionless".into(),
|
||||
description: String::new(),
|
||||
body: crate::analysis::DefinitionBody::QuantityKind(
|
||||
crate::analysis::QuantityKindDefinition {
|
||||
dimension: crate::analysis_numeric::Dimension::ZERO,
|
||||
algebra: crate::analysis::QuantityAlgebra::Linear,
|
||||
},
|
||||
),
|
||||
},
|
||||
);
|
||||
assert!(
|
||||
from_scratch(definition, Map::new())
|
||||
.err()
|
||||
.unwrap()
|
||||
.to_string()
|
||||
.contains("definitions or elements")
|
||||
);
|
||||
let mut current = persistence::decode_with_report(&serde_json::to_vec(&prose_json()).unwrap())
|
||||
.unwrap()
|
||||
.project;
|
||||
current.schema_version = 3;
|
||||
assert!(
|
||||
from_scratch(current.clone(), Map::new())
|
||||
.err()
|
||||
.unwrap()
|
||||
.to_string()
|
||||
.contains("definitions or elements")
|
||||
);
|
||||
current.elements.clear();
|
||||
current
|
||||
.traces
|
||||
.get_mut(&id(4))
|
||||
.unwrap()
|
||||
.baseline
|
||||
.as_mut()
|
||||
.unwrap()
|
||||
.semantic = Some(crate::semantic::SemanticBaseline { facets: Vec::new() });
|
||||
assert!(
|
||||
from_scratch(current, Map::new())
|
||||
.err()
|
||||
.unwrap()
|
||||
.to_string()
|
||||
.contains("semantic")
|
||||
);
|
||||
}
|
||||
@@ -402,6 +402,37 @@ fn checked_in_source_project() -> SourceBundle {
|
||||
}
|
||||
}
|
||||
|
||||
fn assert_architecture_example_warnings(compiled: &crate::source_project::CompiledSourceProject) {
|
||||
// This architecture-only example intentionally has no process/scenario
|
||||
// context. Preserve its explicit incompleteness instead of inventing work.
|
||||
let expected: std::collections::BTreeSet<_> = [
|
||||
("unspecified_exchange_mechanism", "oa_report_data"),
|
||||
("unspecified_exchange_mechanism", "sa_report_data"),
|
||||
("work_without_behavior_context", "report_distress"),
|
||||
("work_without_behavior_context", "assess_incident"),
|
||||
("work_without_behavior_context", "transmit_report"),
|
||||
("work_without_behavior_context", "assess_report"),
|
||||
("work_without_behavior_context", "review_response"),
|
||||
("exchange_without_behavior_context", "distress_signal"),
|
||||
("exchange_without_behavior_context", "validated_report"),
|
||||
("capability_without_behavior_context", "protect_life"),
|
||||
("capability_without_behavior_context", "coordinate_response"),
|
||||
]
|
||||
.into_iter()
|
||||
.map(|(code, alias)| (code, Some(identity(&compiled.decoded.project, alias))))
|
||||
.collect();
|
||||
let actual: std::collections::BTreeSet<_> = compiled
|
||||
.diagnostics
|
||||
.iter()
|
||||
.map(|issue| {
|
||||
assert_eq!(issue.diagnostic.severity, validation::Severity::Warning);
|
||||
(issue.diagnostic.code.as_str(), issue.diagnostic.object_id)
|
||||
})
|
||||
.collect();
|
||||
assert_eq!(actual, expected);
|
||||
assert_eq!(compiled.diagnostics.len(), expected.len());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn checked_in_nested_example_has_stable_ids_typed_exchanges_and_three_clear_views() {
|
||||
let input = checked_in_source_project();
|
||||
@@ -428,15 +459,7 @@ fn checked_in_nested_example_has_stable_ids_typed_exchanges_and_three_clear_view
|
||||
let reopened = compile_bundle(&compiled.bundle, ProjectLimits::default()).unwrap();
|
||||
assert_eq!(reopened.bundle, compiled.bundle);
|
||||
assert!(reopened.decoded.migration.is_none());
|
||||
assert_eq!(compiled.diagnostics.len(), 2);
|
||||
assert!(
|
||||
compiled
|
||||
.diagnostics
|
||||
.iter()
|
||||
.all(|issue| issue.diagnostic.code == "unspecified_exchange_mechanism"),
|
||||
"{:?}",
|
||||
compiled.diagnostics
|
||||
);
|
||||
assert_architecture_example_warnings(&compiled);
|
||||
let project = &compiled.decoded.project;
|
||||
assert_eq!(project.diagrams.len(), 3);
|
||||
let assess = identity(project, "assess_report");
|
||||
@@ -495,15 +518,7 @@ fn checked_in_example_supports_cross_file_reparent_without_changing_allocations(
|
||||
ProjectLimits::default(),
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(result.diagnostics.len(), 2);
|
||||
assert!(
|
||||
result
|
||||
.diagnostics
|
||||
.iter()
|
||||
.all(|issue| issue.diagnostic.code == "unspecified_exchange_mechanism"),
|
||||
"{:?}",
|
||||
result.diagnostics
|
||||
);
|
||||
assert_architecture_example_warnings(&result);
|
||||
assert_eq!(
|
||||
result.index.declarations[&assess].path,
|
||||
"sa/assurance.arcadia"
|
||||
|
||||
@@ -1,7 +1,10 @@
|
||||
//! Framework-independent OA/SA model, transactional commands and editing services.
|
||||
pub mod analysis;
|
||||
pub mod analysis_numeric;
|
||||
pub mod data;
|
||||
pub mod language;
|
||||
pub mod model;
|
||||
pub mod operations;
|
||||
pub mod persistence;
|
||||
pub mod ports;
|
||||
pub mod projection;
|
||||
@@ -11,8 +14,10 @@ pub mod semantic;
|
||||
pub mod session;
|
||||
pub mod source_files;
|
||||
pub mod source_project;
|
||||
pub mod topology_context;
|
||||
pub mod transitions;
|
||||
pub mod validation;
|
||||
pub mod view_options;
|
||||
pub use model::*;
|
||||
pub use ports::*;
|
||||
pub use semantic::*;
|
||||
|
||||
@@ -67,12 +67,15 @@ impl Project4 {
|
||||
if self.schema_version != 4 {
|
||||
return Err(FileError::Invalid("Expected schema_version 4.".into()));
|
||||
}
|
||||
crate::persistence::check_pre6_relations(self.relations.values())?;
|
||||
crate::persistence::check_pre6_elements(self.elements.values())?;
|
||||
Ok(Project {
|
||||
schema_version: SCHEMA_VERSION,
|
||||
id: self.id,
|
||||
alias: self.alias,
|
||||
name: self.name,
|
||||
description: self.description,
|
||||
definitions: BTreeMap::new(),
|
||||
elements: self.elements,
|
||||
relations: self.relations,
|
||||
diagrams: self.diagrams,
|
||||
@@ -102,6 +105,8 @@ pub(crate) fn review_defaults(project: &Project, report: &mut MigrationReport) {
|
||||
}
|
||||
|
||||
pub(crate) fn finish(mut project: Project, limits: ParseLimits) -> Result<DecodeResult, FileError> {
|
||||
crate::persistence::check_pre6_relations(project.relations.values())?;
|
||||
crate::persistence::check_pre6_elements(project.elements.values())?;
|
||||
project.schema_version = SCHEMA_VERSION;
|
||||
limits.check_model(&project).map_err(FileError::Limit)?;
|
||||
let mut report = MigrationReport::data_upgrade(4);
|
||||
|
||||
@@ -0,0 +1,62 @@
|
||||
//! Frozen schema5/6/7 top-level envelope. No schema8 definition catalog/defaults.
|
||||
//! Unchanged nested records are shared only after the closed old-kind check.
|
||||
use crate::persistence::FileError;
|
||||
use crate::*;
|
||||
use serde::Deserialize;
|
||||
use std::collections::BTreeMap;
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub(crate) struct Project7 {
|
||||
pub schema_version: u32,
|
||||
pub id: Id,
|
||||
pub alias: String,
|
||||
pub name: String,
|
||||
pub description: String,
|
||||
#[serde(deserialize_with = "crate::unique_id_map")]
|
||||
pub elements: BTreeMap<Id, Element>,
|
||||
#[serde(deserialize_with = "crate::unique_id_map")]
|
||||
pub relations: BTreeMap<Id, Relation>,
|
||||
#[serde(deserialize_with = "crate::unique_id_map")]
|
||||
pub diagrams: BTreeMap<Id, Diagram>,
|
||||
#[serde(deserialize_with = "crate::unique_id_map")]
|
||||
pub artifact_links: BTreeMap<Id, ArtifactLink>,
|
||||
#[serde(deserialize_with = "crate::unique_id_map")]
|
||||
pub traces: BTreeMap<Id, Trace>,
|
||||
}
|
||||
impl Project7 {
|
||||
pub(crate) fn into_current(self) -> Result<Project, FileError> {
|
||||
if !(5..=7).contains(&self.schema_version) {
|
||||
return Err(FileError::Invalid(
|
||||
"Expected frozen schema5, 6 or 7.".into(),
|
||||
));
|
||||
}
|
||||
reject_elements(self.elements.values())?;
|
||||
Ok(Project {
|
||||
schema_version: self.schema_version,
|
||||
id: self.id,
|
||||
alias: self.alias,
|
||||
name: self.name,
|
||||
description: self.description,
|
||||
definitions: BTreeMap::new(),
|
||||
elements: self.elements,
|
||||
relations: self.relations,
|
||||
diagrams: self.diagrams,
|
||||
artifact_links: self.artifact_links,
|
||||
traces: self.traces,
|
||||
})
|
||||
}
|
||||
}
|
||||
pub(crate) fn reject_elements<'a>(
|
||||
elements: impl Iterator<Item = &'a Element>,
|
||||
) -> Result<(), FileError> {
|
||||
for element in elements {
|
||||
if element.kind().is_analysis() {
|
||||
return Err(FileError::Invalid(format!(
|
||||
"{:?} requires schema/source 8.",
|
||||
element.kind()
|
||||
)));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
+152
-7
@@ -6,7 +6,7 @@ use std::{
|
||||
use uuid::Uuid;
|
||||
|
||||
pub type Id = Uuid;
|
||||
pub const SCHEMA_VERSION: u32 = 5;
|
||||
pub const SCHEMA_VERSION: u32 = 8;
|
||||
pub const MAX_COORDINATE: f32 = 1_000_000.;
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
|
||||
@@ -39,6 +39,7 @@ pub enum Kind {
|
||||
Mission,
|
||||
FunctionalChain,
|
||||
ExchangeItem,
|
||||
ExchangeCategory,
|
||||
DataType,
|
||||
DataField,
|
||||
Interface,
|
||||
@@ -63,9 +64,12 @@ pub enum Kind {
|
||||
Terminate,
|
||||
Event,
|
||||
Constraint,
|
||||
EngineeringProperty,
|
||||
AnalysisCase,
|
||||
AnalysisCheck,
|
||||
}
|
||||
impl Kind {
|
||||
pub const ALL: [Self; 38] = [
|
||||
pub const ALL: [Self; 42] = [
|
||||
Self::Entity,
|
||||
Self::Actor,
|
||||
Self::Role,
|
||||
@@ -80,6 +84,7 @@ impl Kind {
|
||||
Self::Mission,
|
||||
Self::FunctionalChain,
|
||||
Self::ExchangeItem,
|
||||
Self::ExchangeCategory,
|
||||
Self::DataType,
|
||||
Self::DataField,
|
||||
Self::Interface,
|
||||
@@ -104,6 +109,9 @@ impl Kind {
|
||||
Self::Terminate,
|
||||
Self::Event,
|
||||
Self::Constraint,
|
||||
Self::EngineeringProperty,
|
||||
Self::AnalysisCase,
|
||||
Self::AnalysisCheck,
|
||||
];
|
||||
pub fn label(self) -> &'static str {
|
||||
match self {
|
||||
@@ -121,6 +129,7 @@ impl Kind {
|
||||
Self::Mission => "Mission",
|
||||
Self::FunctionalChain => "Functional chain",
|
||||
Self::ExchangeItem => "Exchange item",
|
||||
Self::ExchangeCategory => "Exchange category",
|
||||
Self::DataType => "Data type",
|
||||
Self::DataField => "Data field",
|
||||
Self::Interface => "Interface",
|
||||
@@ -145,6 +154,9 @@ impl Kind {
|
||||
Self::Terminate => "Terminate",
|
||||
Self::Event => "Event",
|
||||
Self::Constraint => "Constraint",
|
||||
Self::EngineeringProperty => "Engineering property",
|
||||
Self::AnalysisCase => "Analysis case",
|
||||
Self::AnalysisCheck => "Analysis check",
|
||||
}
|
||||
}
|
||||
pub fn is_performer(self) -> bool {
|
||||
@@ -153,6 +165,9 @@ impl Kind {
|
||||
Self::Entity | Self::Actor | Self::System | Self::SystemActor
|
||||
)
|
||||
}
|
||||
pub fn is_analysis(self) -> bool {
|
||||
matches!(self, Self::EngineeringProperty | Self::AnalysisCase | Self::AnalysisCheck)
|
||||
}
|
||||
pub fn is_work(self) -> bool {
|
||||
matches!(self, Self::Activity | Self::Function)
|
||||
}
|
||||
@@ -520,6 +535,28 @@ pub struct MessageValue {
|
||||
pub field: Id,
|
||||
pub expression: String,
|
||||
}
|
||||
/// Explicit operation intent. A missing allocation remains an unfinished operation,
|
||||
/// whereas an absent OperationUse retains ordinary channel-message semantics.
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct OperationUse {
|
||||
pub allocation: Option<Id>,
|
||||
}
|
||||
/// A contribution in a caller instance. Paths contain reference occurrence IDs,
|
||||
/// never sequence definitions; repeated references therefore remain distinct.
|
||||
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Serialize, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct OccurrenceEndpoint {
|
||||
pub references: Vec<Id>,
|
||||
pub occurrence: Id,
|
||||
}
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub enum ContextualLinkPurpose {
|
||||
Precedence { guard: String },
|
||||
Exchange { exchange: Id },
|
||||
CommonWork { work: Id },
|
||||
}
|
||||
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub enum OccurrenceBody {
|
||||
@@ -533,6 +570,8 @@ pub enum OccurrenceBody {
|
||||
reply_to: Option<Id>,
|
||||
#[serde(default)]
|
||||
values: Vec<MessageValue>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
operation: Option<OperationUse>,
|
||||
},
|
||||
Action {
|
||||
action: Option<Id>,
|
||||
@@ -564,6 +603,10 @@ pub enum OccurrenceBody {
|
||||
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub enum SharedBody {
|
||||
ExchangeCategory {
|
||||
family: crate::view_options::ExchangeFamily,
|
||||
exchanges: Vec<Id>,
|
||||
},
|
||||
ExchangeItem {
|
||||
kind: ExchangeItemKind,
|
||||
mechanism: ExchangeMechanism,
|
||||
@@ -621,6 +664,23 @@ pub enum SharedBody {
|
||||
expression: String,
|
||||
constrained: Vec<Id>,
|
||||
},
|
||||
EngineeringProperty {
|
||||
subject: crate::analysis::AnalysisSubject,
|
||||
value_type: crate::analysis::AnalysisType,
|
||||
display_unit: Option<crate::analysis::DefinitionRef>,
|
||||
base: crate::analysis::Binding,
|
||||
},
|
||||
AnalysisCase {
|
||||
subject: Option<crate::analysis::AnalysisSubject>,
|
||||
base: crate::analysis::BaselineBase,
|
||||
#[serde(deserialize_with = "unique_id_map")]
|
||||
overrides: BTreeMap<Id, crate::analysis::Binding>,
|
||||
},
|
||||
AnalysisCheck {
|
||||
subject: Option<crate::analysis::AnalysisSubject>,
|
||||
documented_constraint: Option<Id>,
|
||||
predicate: crate::analysis::Binding,
|
||||
},
|
||||
}
|
||||
impl Element {
|
||||
pub fn layer(&self) -> Layer {
|
||||
@@ -721,7 +781,8 @@ impl ElementBody {
|
||||
}
|
||||
}
|
||||
pub fn new(kind: Kind, layer: Layer) -> Option<Self> {
|
||||
if !kind.supports(layer) {
|
||||
// Analysis creation requires explicitly authored types and bindings.
|
||||
if !kind.supports(layer) || kind.is_analysis() {
|
||||
return None;
|
||||
}
|
||||
Some(match kind {
|
||||
@@ -754,6 +815,10 @@ impl ElementBody {
|
||||
default: None,
|
||||
unit: String::new(),
|
||||
},
|
||||
Kind::ExchangeCategory => SharedBody::ExchangeCategory {
|
||||
family: crate::view_options::ExchangeFamily::Work,
|
||||
exchanges: vec![],
|
||||
},
|
||||
Kind::DataField => SharedBody::DataField {
|
||||
type_ref: TypeRef::String,
|
||||
minimum: 1,
|
||||
@@ -786,6 +851,7 @@ impl ElementBody {
|
||||
message_kind: MessageKind::Asynchronous,
|
||||
reply_to: None,
|
||||
values: vec![],
|
||||
operation: None,
|
||||
},
|
||||
precondition: String::new(),
|
||||
postcondition: String::new(),
|
||||
@@ -815,6 +881,7 @@ impl SharedBody {
|
||||
pub fn kind(&self) -> Kind {
|
||||
match self {
|
||||
Self::ExchangeItem { .. } => Kind::ExchangeItem,
|
||||
Self::ExchangeCategory { .. } => Kind::ExchangeCategory,
|
||||
Self::DataType { .. } => Kind::DataType,
|
||||
Self::DataField { .. } => Kind::DataField,
|
||||
Self::Interface { .. } => Kind::Interface,
|
||||
@@ -827,6 +894,9 @@ impl SharedBody {
|
||||
Self::Region => Kind::Region,
|
||||
Self::State { kind, .. } => kind.kind(),
|
||||
Self::Constraint { .. } => Kind::Constraint,
|
||||
Self::EngineeringProperty { .. } => Kind::EngineeringProperty,
|
||||
Self::AnalysisCase { .. } => Kind::AnalysisCase,
|
||||
Self::AnalysisCheck { .. } => Kind::AnalysisCheck,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -844,12 +914,14 @@ pub enum RelationKind {
|
||||
RoleAssignment,
|
||||
FunctionalExchange,
|
||||
BoundaryExchange,
|
||||
CommunicationMean,
|
||||
MissionCapability,
|
||||
CapabilityInclude,
|
||||
CapabilityExtend,
|
||||
CapabilityGeneralization,
|
||||
MissionInvolvement,
|
||||
SequenceLink,
|
||||
ContextualLink,
|
||||
StateTransition,
|
||||
Availability,
|
||||
ExchangeAllocation,
|
||||
@@ -858,7 +930,7 @@ pub enum RelationKind {
|
||||
StateAction,
|
||||
}
|
||||
impl RelationKind {
|
||||
pub const ALL: [Self; 23] = [
|
||||
pub const ALL: [Self; 25] = [
|
||||
Self::InterfaceItemAllocation,
|
||||
Self::DataAssociation,
|
||||
Self::Allocation,
|
||||
@@ -870,12 +942,14 @@ impl RelationKind {
|
||||
Self::RoleAssignment,
|
||||
Self::FunctionalExchange,
|
||||
Self::BoundaryExchange,
|
||||
Self::CommunicationMean,
|
||||
Self::MissionCapability,
|
||||
Self::CapabilityInclude,
|
||||
Self::CapabilityExtend,
|
||||
Self::CapabilityGeneralization,
|
||||
Self::MissionInvolvement,
|
||||
Self::SequenceLink,
|
||||
Self::ContextualLink,
|
||||
Self::StateTransition,
|
||||
Self::Availability,
|
||||
Self::ExchangeAllocation,
|
||||
@@ -902,6 +976,10 @@ impl RelationKind {
|
||||
Self::RoleAssignment => from == Kind::Role && to == Kind::Activity,
|
||||
Self::FunctionalExchange => from == Kind::Function && to == Kind::Function,
|
||||
Self::BoundaryExchange => from == Kind::Port && to == Kind::Port,
|
||||
Self::CommunicationMean => {
|
||||
matches!(from, Kind::Entity | Kind::Actor)
|
||||
&& matches!(to, Kind::Entity | Kind::Actor)
|
||||
}
|
||||
Self::MissionCapability => matches!(
|
||||
(from, to),
|
||||
(Kind::OperationalMission, Kind::Capability)
|
||||
@@ -919,7 +997,9 @@ impl RelationKind {
|
||||
(Kind::Entity | Kind::Actor, Kind::OperationalMission)
|
||||
| (Kind::System | Kind::SystemActor, Kind::Mission)
|
||||
),
|
||||
Self::SequenceLink => from == Kind::Occurrence && to == Kind::Occurrence,
|
||||
Self::SequenceLink | Self::ContextualLink => {
|
||||
from == Kind::Occurrence && to == Kind::Occurrence
|
||||
}
|
||||
Self::StateTransition => from.is_state() && to.is_state(),
|
||||
Self::ExchangeAllocation => false,
|
||||
Self::InterfaceProvision | Self::InterfaceRequirement => {
|
||||
@@ -953,6 +1033,7 @@ impl RelationKind {
|
||||
Self::RoleAssignment => "OA role → activity",
|
||||
Self::FunctionalExchange => "SA function → SA function",
|
||||
Self::BoundaryExchange => "Output port → input port",
|
||||
Self::CommunicationMean => "OA entity/actor → OA entity/actor",
|
||||
Self::MissionCapability => "Mission → capability in the same perspective",
|
||||
Self::CapabilityInclude => "Including capability → included capability",
|
||||
Self::CapabilityExtend => {
|
||||
@@ -961,9 +1042,12 @@ impl RelationKind {
|
||||
Self::CapabilityGeneralization => "Specific capability → general capability",
|
||||
Self::MissionInvolvement => "Participant → mission in the same perspective",
|
||||
Self::SequenceLink => "Preceding → following contribution in the same process or chain",
|
||||
Self::ContextualLink => {
|
||||
"Contributions addressed in an explicit process or chain caller"
|
||||
}
|
||||
Self::StateTransition => "State → state in one machine",
|
||||
Self::ExchangeAllocation => {
|
||||
"Boundary exchange → operational interaction / functional exchange"
|
||||
"Communication means / boundary exchange → operational interaction / functional exchange"
|
||||
}
|
||||
Self::InterfaceProvision => "Participant/port → provided interface",
|
||||
Self::InterfaceRequirement => "Participant/port → required interface",
|
||||
@@ -986,12 +1070,14 @@ impl fmt::Display for RelationKind {
|
||||
Self::RoleAssignment => "Role assignment",
|
||||
Self::FunctionalExchange => "Functional exchange",
|
||||
Self::BoundaryExchange => "Boundary exchange",
|
||||
Self::CommunicationMean => "Communication means",
|
||||
Self::MissionCapability => "Mission capability",
|
||||
Self::CapabilityInclude => "Capability include",
|
||||
Self::CapabilityExtend => "Capability extend",
|
||||
Self::CapabilityGeneralization => "Capability generalization",
|
||||
Self::MissionInvolvement => "Mission involvement",
|
||||
Self::SequenceLink => "Sequence link",
|
||||
Self::ContextualLink => "Contextual link",
|
||||
Self::StateTransition => "State transition",
|
||||
Self::ExchangeAllocation => "Exchange allocation",
|
||||
Self::InterfaceProvision => "Interface provision",
|
||||
@@ -1074,6 +1160,12 @@ pub enum RelationBody {
|
||||
oriented: bool,
|
||||
items: Vec<Id>,
|
||||
},
|
||||
CommunicationMean {
|
||||
source: Id,
|
||||
target: Id,
|
||||
oriented: bool,
|
||||
items: Vec<Id>,
|
||||
},
|
||||
MissionCapability {
|
||||
source: Id,
|
||||
target: Id,
|
||||
@@ -1100,6 +1192,12 @@ pub enum RelationBody {
|
||||
target: Id,
|
||||
guard: String,
|
||||
},
|
||||
ContextualLink {
|
||||
owner: Id,
|
||||
source: OccurrenceEndpoint,
|
||||
target: OccurrenceEndpoint,
|
||||
purpose: ContextualLinkPurpose,
|
||||
},
|
||||
StateTransition {
|
||||
source: Id,
|
||||
target: Id,
|
||||
@@ -1136,6 +1234,13 @@ pub enum RelationBody {
|
||||
},
|
||||
}
|
||||
impl Relation {
|
||||
/// Caller ownership cannot be inferred from a contextual link's leaf IDs.
|
||||
pub fn contextual_owner(&self) -> Option<Id> {
|
||||
match self.body {
|
||||
RelationBody::ContextualLink { owner, .. } => Some(owner),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
pub fn kind(&self) -> RelationKind {
|
||||
self.body.kind()
|
||||
}
|
||||
@@ -1160,12 +1265,14 @@ impl RelationBody {
|
||||
Self::RoleAssignment { .. } => RelationKind::RoleAssignment,
|
||||
Self::FunctionalExchange { .. } => RelationKind::FunctionalExchange,
|
||||
Self::BoundaryExchange { .. } => RelationKind::BoundaryExchange,
|
||||
Self::CommunicationMean { .. } => RelationKind::CommunicationMean,
|
||||
Self::MissionCapability { .. } => RelationKind::MissionCapability,
|
||||
Self::CapabilityInclude { .. } => RelationKind::CapabilityInclude,
|
||||
Self::CapabilityExtend { .. } => RelationKind::CapabilityExtend,
|
||||
Self::CapabilityGeneralization { .. } => RelationKind::CapabilityGeneralization,
|
||||
Self::MissionInvolvement { .. } => RelationKind::MissionInvolvement,
|
||||
Self::SequenceLink { .. } => RelationKind::SequenceLink,
|
||||
Self::ContextualLink { .. } => RelationKind::ContextualLink,
|
||||
Self::StateTransition { .. } => RelationKind::StateTransition,
|
||||
Self::ExchangeAllocation { .. } => RelationKind::ExchangeAllocation,
|
||||
Self::InterfaceProvision { .. } => RelationKind::InterfaceProvision,
|
||||
@@ -1176,6 +1283,7 @@ impl RelationBody {
|
||||
}
|
||||
pub fn endpoints(&self) -> (Id, Id) {
|
||||
match self {
|
||||
Self::ContextualLink { source, target, .. } => (source.occurrence, target.occurrence),
|
||||
Self::InterfaceItemAllocation { source, target, .. }
|
||||
| Self::DataAssociation { source, target, .. }
|
||||
| Self::Allocation { source, target }
|
||||
@@ -1187,6 +1295,7 @@ impl RelationBody {
|
||||
| Self::RoleAssignment { source, target }
|
||||
| Self::FunctionalExchange { source, target, .. }
|
||||
| Self::BoundaryExchange { source, target, .. }
|
||||
| Self::CommunicationMean { source, target, .. }
|
||||
| Self::MissionCapability { source, target }
|
||||
| Self::CapabilityInclude { source, target }
|
||||
| Self::CapabilityExtend { source, target, .. }
|
||||
@@ -1203,6 +1312,10 @@ impl RelationBody {
|
||||
}
|
||||
pub fn set_endpoints(&mut self, a: Id, b: Id) {
|
||||
match self {
|
||||
Self::ContextualLink { source, target, .. } => {
|
||||
source.occurrence = a;
|
||||
target.occurrence = b;
|
||||
}
|
||||
Self::InterfaceItemAllocation { source, target, .. }
|
||||
| Self::DataAssociation { source, target, .. }
|
||||
| Self::Allocation { source, target }
|
||||
@@ -1214,6 +1327,7 @@ impl RelationBody {
|
||||
| Self::RoleAssignment { source, target }
|
||||
| Self::FunctionalExchange { source, target, .. }
|
||||
| Self::BoundaryExchange { source, target, .. }
|
||||
| Self::CommunicationMean { source, target, .. }
|
||||
| Self::MissionCapability { source, target }
|
||||
| Self::CapabilityInclude { source, target }
|
||||
| Self::CapabilityExtend { source, target, .. }
|
||||
@@ -1235,7 +1349,8 @@ impl RelationBody {
|
||||
match self {
|
||||
Self::Interaction { items, .. }
|
||||
| Self::FunctionalExchange { items, .. }
|
||||
| Self::BoundaryExchange { items, .. } => items,
|
||||
| Self::BoundaryExchange { items, .. }
|
||||
| Self::CommunicationMean { items, .. } => items,
|
||||
_ => &[],
|
||||
}
|
||||
}
|
||||
@@ -1285,6 +1400,12 @@ impl RelationBody {
|
||||
oriented: true,
|
||||
items: vec![],
|
||||
},
|
||||
RelationKind::CommunicationMean => Self::CommunicationMean {
|
||||
source,
|
||||
target,
|
||||
oriented: false,
|
||||
items: vec![],
|
||||
},
|
||||
RelationKind::MissionCapability => Self::MissionCapability { source, target },
|
||||
RelationKind::CapabilityInclude => Self::CapabilityInclude { source, target },
|
||||
RelationKind::CapabilityExtend => Self::CapabilityExtend {
|
||||
@@ -1301,6 +1422,20 @@ impl RelationBody {
|
||||
target,
|
||||
guard: String::new(),
|
||||
},
|
||||
RelationKind::ContextualLink => Self::ContextualLink {
|
||||
owner: Id::nil(),
|
||||
source: OccurrenceEndpoint {
|
||||
references: vec![],
|
||||
occurrence: source,
|
||||
},
|
||||
target: OccurrenceEndpoint {
|
||||
references: vec![],
|
||||
occurrence: target,
|
||||
},
|
||||
purpose: ContextualLinkPurpose::Precedence {
|
||||
guard: String::new(),
|
||||
},
|
||||
},
|
||||
RelationKind::StateTransition => Self::StateTransition {
|
||||
source,
|
||||
target,
|
||||
@@ -1387,6 +1522,8 @@ pub struct Diagram {
|
||||
pub description: String,
|
||||
pub layer: Layer,
|
||||
pub projection: ProjectionKind,
|
||||
#[serde(default)]
|
||||
pub view_options: crate::view_options::ViewOptions,
|
||||
#[serde(deserialize_with = "unique_id_map")]
|
||||
pub nodes: BTreeMap<Id, NodePlacement>,
|
||||
#[serde(default)]
|
||||
@@ -1521,6 +1658,8 @@ pub struct Project {
|
||||
pub name: String,
|
||||
pub description: String,
|
||||
#[serde(deserialize_with = "unique_id_map")]
|
||||
pub definitions: BTreeMap<Id, crate::analysis::Definition>,
|
||||
#[serde(deserialize_with = "unique_id_map")]
|
||||
pub elements: BTreeMap<Id, Element>,
|
||||
#[serde(deserialize_with = "unique_id_map")]
|
||||
pub relations: BTreeMap<Id, Relation>,
|
||||
@@ -1613,6 +1752,7 @@ impl Project {
|
||||
alias: "mission".into(),
|
||||
name: "Untitled mission".into(),
|
||||
description: String::new(),
|
||||
definitions: BTreeMap::new(),
|
||||
elements: BTreeMap::new(),
|
||||
relations: BTreeMap::new(),
|
||||
diagrams: BTreeMap::new(),
|
||||
@@ -1622,6 +1762,7 @@ impl Project {
|
||||
}
|
||||
pub fn identities(&self) -> Vec<(Id, &str)> {
|
||||
let mut out = vec![(self.id, self.alias.as_str())];
|
||||
out.extend(self.definitions.values().map(|v| (v.id, v.alias.as_str())));
|
||||
out.extend(self.elements.values().map(|v| (v.id, v.alias.as_str())));
|
||||
out.extend(self.relations.values().map(|v| (v.id, v.alias.as_str())));
|
||||
out.extend(self.diagrams.values().map(|v| (v.id, v.alias.as_str())));
|
||||
@@ -1679,6 +1820,9 @@ impl Project {
|
||||
if id == self.id {
|
||||
return &self.name;
|
||||
}
|
||||
if let Some(v) = self.definitions.get(&id) {
|
||||
return &v.name;
|
||||
}
|
||||
if let Some(v) = self.elements.get(&id) {
|
||||
return &v.name;
|
||||
}
|
||||
@@ -1814,6 +1958,7 @@ impl Project {
|
||||
description: String::new(),
|
||||
layer,
|
||||
projection: ProjectionKind::Overview,
|
||||
view_options: crate::view_options::ViewOptions::default(),
|
||||
nodes: BTreeMap::new(),
|
||||
routes: vec![],
|
||||
},
|
||||
|
||||
@@ -0,0 +1,345 @@
|
||||
//! One operation resolver for admission, forms and scenario labels.
|
||||
use crate::*;
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct ResolvedOperation {
|
||||
/// The actual Call/Asynchronous declaration, also when resolving its Reply.
|
||||
pub invocation: Id,
|
||||
pub allocation: Id,
|
||||
pub interface: Id,
|
||||
pub item: Id,
|
||||
pub caller_port: Id,
|
||||
pub provider_port: Id,
|
||||
pub transmission: TransmissionProtocol,
|
||||
}
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub enum OperationResolution {
|
||||
Ordinary,
|
||||
Unresolved { invocation: Id, reason: String },
|
||||
Selected(ResolvedOperation),
|
||||
}
|
||||
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
|
||||
#[error("{message}")]
|
||||
pub struct OperationError {
|
||||
pub code: &'static str,
|
||||
pub message: String,
|
||||
}
|
||||
fn error(code: &'static str, message: &str) -> OperationError {
|
||||
OperationError {
|
||||
code,
|
||||
message: message.into(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn resolve(p: &Project, occurrence: Id) -> Result<OperationResolution, OperationError> {
|
||||
let e = p
|
||||
.elements
|
||||
.get(&occurrence)
|
||||
.ok_or_else(|| error("operation_context", "The message no longer exists."))?;
|
||||
let Some(SharedBody::Occurrence {
|
||||
body:
|
||||
OccurrenceBody::Exchange {
|
||||
operation,
|
||||
message_kind,
|
||||
reply_to,
|
||||
..
|
||||
},
|
||||
..
|
||||
}) = e.shared()
|
||||
else {
|
||||
return Ok(OperationResolution::Ordinary);
|
||||
};
|
||||
let invocation = if *message_kind == MessageKind::Reply {
|
||||
if operation.is_some() {
|
||||
return Err(error(
|
||||
"reply_operation",
|
||||
"A Reply derives its operation from its exact Call; it cannot store a second selection.",
|
||||
));
|
||||
}
|
||||
let Some(call) = reply_to else {
|
||||
return Ok(OperationResolution::Ordinary);
|
||||
};
|
||||
if !matches!(
|
||||
p.elements.get(call).and_then(Element::shared),
|
||||
Some(SharedBody::Occurrence {
|
||||
body: OccurrenceBody::Exchange {
|
||||
message_kind: MessageKind::Call,
|
||||
..
|
||||
},
|
||||
..
|
||||
})
|
||||
) {
|
||||
return Ok(OperationResolution::Ordinary);
|
||||
}
|
||||
*call
|
||||
} else {
|
||||
occurrence
|
||||
};
|
||||
let Some(SharedBody::Occurrence {
|
||||
body:
|
||||
body @ OccurrenceBody::Exchange {
|
||||
operation: Some(operation),
|
||||
message_kind,
|
||||
exchange,
|
||||
sender,
|
||||
receiver,
|
||||
..
|
||||
},
|
||||
..
|
||||
}) = p.elements.get(&invocation).and_then(Element::shared)
|
||||
else {
|
||||
return Ok(OperationResolution::Ordinary);
|
||||
};
|
||||
if p.layer_of(invocation) != Some(Layer::Sa)
|
||||
|| !matches!(message_kind, MessageKind::Call | MessageKind::Asynchronous)
|
||||
|| validation::ancestor_of_kind(p, invocation, Kind::Scenario)
|
||||
.and_then(|id| p.elements.get(&id))
|
||||
.and_then(Element::shared)
|
||||
.is_none_or(|body| {
|
||||
!matches!(
|
||||
body,
|
||||
SharedBody::Scenario {
|
||||
viewpoint: ScenarioViewpoint::BoundaryInterface,
|
||||
..
|
||||
}
|
||||
)
|
||||
})
|
||||
{
|
||||
return Err(error(
|
||||
"operation_context",
|
||||
"Operation use belongs to a Call or Asynchronous message in an SA BoundaryInterface scenario.",
|
||||
));
|
||||
}
|
||||
let unresolved = |reason: &str| {
|
||||
Ok(OperationResolution::Unresolved {
|
||||
invocation,
|
||||
reason: reason.into(),
|
||||
})
|
||||
};
|
||||
if exchange
|
||||
.and_then(|id| p.relations.get(&id))
|
||||
.is_some_and(|r| r.kind() != RelationKind::BoundaryExchange)
|
||||
{
|
||||
return Err(error(
|
||||
"operation_channel",
|
||||
"Operation use requires an explicit boundary exchange channel.",
|
||||
));
|
||||
}
|
||||
let Some(allocation) = operation.allocation else {
|
||||
return unresolved(
|
||||
"Choose the interface operation allocation; existing value expressions are preserved.",
|
||||
);
|
||||
};
|
||||
let Some(relation) = p.relations.get(&allocation) else {
|
||||
return Err(error(
|
||||
"operation_allocation",
|
||||
"The selected interface operation allocation no longer exists.",
|
||||
));
|
||||
};
|
||||
let RelationBody::InterfaceItemAllocation {
|
||||
source: interface,
|
||||
target: item,
|
||||
transmission,
|
||||
..
|
||||
} = relation.body
|
||||
else {
|
||||
return Err(error(
|
||||
"operation_allocation",
|
||||
"Choose an InterfaceItemAllocation, not an item or another relationship.",
|
||||
));
|
||||
};
|
||||
if p.layer_of(allocation) != Some(Layer::Sa)
|
||||
|| !matches!(
|
||||
p.elements.get(&item).and_then(Element::shared),
|
||||
Some(SharedBody::ExchangeItem {
|
||||
kind: ExchangeItemKind::Information,
|
||||
mechanism: ExchangeMechanism::Operation,
|
||||
..
|
||||
})
|
||||
)
|
||||
{
|
||||
return Err(error(
|
||||
"operation_allocation",
|
||||
"The selected SA allocation must declare an Information item with Operation mechanism.",
|
||||
));
|
||||
}
|
||||
let Some(channel) = exchange.and_then(|id| p.relations.get(&id)) else {
|
||||
return Err(error(
|
||||
"operation_channel",
|
||||
"A selected operation requires an existing boundary exchange carrying its item; clear the allocation to retain unresolved intent.",
|
||||
));
|
||||
};
|
||||
if channel.kind() != RelationKind::BoundaryExchange
|
||||
|| !channel
|
||||
.body
|
||||
.items()
|
||||
.iter()
|
||||
.any(|carried| data::item_satisfies(p, *carried, item))
|
||||
{
|
||||
return Err(error(
|
||||
"operation_channel",
|
||||
"The boundary exchange must carry the selected operation item or an admitted subtype.",
|
||||
));
|
||||
}
|
||||
if sender.is_none() || receiver.is_none() {
|
||||
return Err(error(
|
||||
"operation_lifelines",
|
||||
"A selected operation requires actual caller and provider lifelines; clear the allocation to retain unresolved intent.",
|
||||
));
|
||||
}
|
||||
let (caller_port, provider_port) = match validation::resolve_message_endpoints(p, body) {
|
||||
validation::MessageEndpointResolution::Resolved { source, target } => (source, target),
|
||||
validation::MessageEndpointResolution::Conflict => {
|
||||
return Err(error(
|
||||
"operation_direction",
|
||||
"The selected lifelines conflict with the boundary channel's actual caller/provider direction.",
|
||||
));
|
||||
}
|
||||
_ => {
|
||||
return Err(error(
|
||||
"operation_direction",
|
||||
"A selected operation requires a proven actual caller/provider channel direction; clear the allocation to retain unresolved intent.",
|
||||
));
|
||||
}
|
||||
};
|
||||
for port in [caller_port, provider_port] {
|
||||
if !matches!(
|
||||
p.elements.get(&port).and_then(ports::port_contract),
|
||||
Some(PortContract::Component {
|
||||
kind: ComponentPortKind::Standard,
|
||||
..
|
||||
})
|
||||
) {
|
||||
return Err(error(
|
||||
"operation_ports",
|
||||
"Operation proof requires concrete Standard component ports.",
|
||||
));
|
||||
}
|
||||
}
|
||||
let exposes = |interface| {
|
||||
data::effective_interface_allocations(p, interface)
|
||||
.iter()
|
||||
.any(|r| r.id == allocation)
|
||||
};
|
||||
let providers: Vec<_> = p
|
||||
.relations
|
||||
.values()
|
||||
.filter(|r| {
|
||||
r.kind() == RelationKind::InterfaceProvision
|
||||
&& r.source() == provider_port
|
||||
&& exposes(r.target())
|
||||
})
|
||||
.map(Relation::target)
|
||||
.collect();
|
||||
let valid = p.relations.values().any(|r| {
|
||||
r.kind() == RelationKind::InterfaceRequirement
|
||||
&& r.source() == caller_port
|
||||
&& exposes(r.target())
|
||||
&& providers
|
||||
.iter()
|
||||
.any(|provided| data::interface_satisfies(p, *provided, r.target()))
|
||||
});
|
||||
if !valid {
|
||||
return Err(error(
|
||||
"operation_roles",
|
||||
"The actual receiver port must provide, and sender port require, compatible interfaces exposing this exact allocation.",
|
||||
));
|
||||
}
|
||||
if !matches!(
|
||||
(message_kind, transmission),
|
||||
(_, TransmissionProtocol::Unspecified)
|
||||
| (MessageKind::Call, TransmissionProtocol::Synchronous)
|
||||
| (
|
||||
MessageKind::Asynchronous,
|
||||
TransmissionProtocol::Asynchronous
|
||||
)
|
||||
) {
|
||||
return Err(error(
|
||||
"operation_transmission",
|
||||
"Calls require synchronous transmission; asynchronous operation messages require asynchronous transmission.",
|
||||
));
|
||||
}
|
||||
let selected = ResolvedOperation {
|
||||
invocation,
|
||||
allocation,
|
||||
interface,
|
||||
item,
|
||||
caller_port,
|
||||
provider_port,
|
||||
transmission,
|
||||
};
|
||||
if occurrence != invocation {
|
||||
let Some(SharedBody::Occurrence {
|
||||
body:
|
||||
OccurrenceBody::Exchange {
|
||||
exchange: reply_exchange,
|
||||
..
|
||||
},
|
||||
..
|
||||
}) = e.shared()
|
||||
else {
|
||||
unreachable!()
|
||||
};
|
||||
if let Some(response) = reply_exchange.and_then(|id| p.relations.get(&id))
|
||||
&& response.id != channel.id
|
||||
&& !response
|
||||
.body
|
||||
.items()
|
||||
.iter()
|
||||
.any(|carried| data::item_satisfies(p, *carried, item))
|
||||
{
|
||||
return Err(error(
|
||||
"operation_reply_channel",
|
||||
"A separate reply channel must carry the Call's selected operation item or an admitted subtype, including parameterless returns.",
|
||||
));
|
||||
}
|
||||
}
|
||||
Ok(OperationResolution::Selected(selected))
|
||||
}
|
||||
|
||||
/// Valid selections under the proposed message context, without mutating the model.
|
||||
pub fn eligible_allocations(p: &Project, occurrence: Id) -> Vec<Id> {
|
||||
let mut candidate = p.clone();
|
||||
let ids: Vec<_> = p
|
||||
.relations
|
||||
.values()
|
||||
.filter(|r| r.kind() == RelationKind::InterfaceItemAllocation)
|
||||
.map(|r| r.id)
|
||||
.collect();
|
||||
ids.into_iter()
|
||||
.filter(|id| {
|
||||
let Some(SharedBody::Occurrence {
|
||||
body: OccurrenceBody::Exchange { operation, .. },
|
||||
..
|
||||
}) = candidate
|
||||
.elements
|
||||
.get_mut(&occurrence)
|
||||
.and_then(Element::shared_mut)
|
||||
else {
|
||||
return false;
|
||||
};
|
||||
*operation = Some(OperationUse {
|
||||
allocation: Some(*id),
|
||||
});
|
||||
matches!(
|
||||
resolve(&candidate, occurrence),
|
||||
Ok(OperationResolution::Selected(_))
|
||||
)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Reuse the existing bounded field-path engine with exactly one selected item.
|
||||
pub fn signature_relation(operation: &ResolvedOperation) -> Relation {
|
||||
Relation {
|
||||
id: operation.allocation,
|
||||
alias: String::new(),
|
||||
name: String::new(),
|
||||
description: String::new(),
|
||||
body: RelationBody::Interaction {
|
||||
source: operation.caller_port,
|
||||
target: operation.provider_port,
|
||||
items: vec![operation.item],
|
||||
},
|
||||
}
|
||||
}
|
||||
@@ -2,6 +2,10 @@ use crate::*;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::{io::Write, path::Path};
|
||||
use thiserror::Error;
|
||||
mod json_codec;
|
||||
#[cfg(test)]
|
||||
#[path = "persistence/source_save_tests.rs"]
|
||||
mod source_save_tests;
|
||||
#[path = "migration_v2/mod.rs"]
|
||||
pub(crate) mod v2;
|
||||
pub(crate) use v2::adapter::migrate as migrate_v2_limited;
|
||||
@@ -9,6 +13,8 @@ pub(crate) use v2::adapter::migrate as migrate_v2_limited;
|
||||
pub(crate) mod v3;
|
||||
#[path = "migration_v4.rs"]
|
||||
pub(crate) mod v4;
|
||||
#[path = "migration_v7.rs"]
|
||||
pub(crate) mod v7;
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
@@ -130,6 +136,19 @@ pub fn decode_limited(
|
||||
pub fn decode_with_report_limited(
|
||||
bytes: &[u8],
|
||||
limits: crate::language::ParseLimits,
|
||||
) -> Result<DecodeResult, FileError> {
|
||||
decode_with_report_profile(
|
||||
bytes,
|
||||
limits,
|
||||
json_codec::Profile::with_byte_limit(limits.max_source_bytes),
|
||||
json_codec::DEPTH_128_VALIDATED,
|
||||
)
|
||||
}
|
||||
fn decode_with_report_profile(
|
||||
bytes: &[u8],
|
||||
limits: crate::language::ParseLimits,
|
||||
profile: json_codec::Profile,
|
||||
depth_128: bool,
|
||||
) -> Result<DecodeResult, FileError> {
|
||||
if bytes.len() > limits.max_source_bytes {
|
||||
return Err(FileError::Limit(format!(
|
||||
@@ -138,26 +157,43 @@ pub fn decode_with_report_limited(
|
||||
)));
|
||||
}
|
||||
let decoded = if bytes.iter().find(|b| !b.is_ascii_whitespace()) == Some(&b'{') {
|
||||
let header: serde_json::Value = serde_json::from_slice(bytes)?;
|
||||
match header
|
||||
.get("schema_version")
|
||||
.and_then(serde_json::Value::as_u64)
|
||||
{
|
||||
json_codec::preflight(bytes, profile)?;
|
||||
let version = json_codec::version(bytes)?;
|
||||
if version.is_some_and(|version| version <= 6) {
|
||||
let header = json_codec::legacy(bytes)?;
|
||||
let result = check_legacy_header(&header, version);
|
||||
json_codec::discard_value(header);
|
||||
result?;
|
||||
}
|
||||
match version {
|
||||
Some(1) => {
|
||||
let old = serde_json::from_slice(bytes)?;
|
||||
let old = json_codec::legacy(bytes)?;
|
||||
check_v1_limits(&old, limits).map_err(FileError::Limit)?;
|
||||
migrate_v1_with_report_limited(old, limits)?
|
||||
}
|
||||
Some(2) => migrate_v2_limited(serde_json::from_slice(bytes)?, limits)?,
|
||||
Some(3) => v3::migrate(serde_json::from_slice(bytes)?, limits)?,
|
||||
Some(4) => v4::migrate(serde_json::from_slice(bytes)?, limits)?,
|
||||
Some(5) => DecodeResult {
|
||||
project: serde_json::from_slice(bytes)?,
|
||||
Some(2) => migrate_v2_limited(json_codec::legacy(bytes)?, limits)?,
|
||||
Some(3) => v3::migrate(json_codec::legacy(bytes)?, limits)?,
|
||||
Some(4) => v4::migrate(json_codec::legacy(bytes)?, limits)?,
|
||||
Some(5) => migrate_v5(
|
||||
json_codec::legacy::<v7::Project7>(bytes)?.into_current()?,
|
||||
limits,
|
||||
)?,
|
||||
Some(6) => migrate_v6(
|
||||
json_codec::legacy::<v7::Project7>(bytes)?.into_current()?,
|
||||
limits,
|
||||
)?,
|
||||
Some(7) => migrate_v7(
|
||||
json_codec::legacy::<v7::Project7>(bytes)?.into_current()?,
|
||||
limits,
|
||||
)?,
|
||||
Some(8) => DecodeResult {
|
||||
project: json_codec::current(bytes, profile, depth_128)?,
|
||||
migration: None,
|
||||
},
|
||||
_ => {
|
||||
return Err(FileError::Invalid(
|
||||
"Unsupported or missing schema_version; expected 1, 2, 3, 4 or 5.".into(),
|
||||
"Unsupported or missing schema_version; expected 1, 2, 3, 4, 5, 6, 7 or 8."
|
||||
.into(),
|
||||
));
|
||||
}
|
||||
}
|
||||
@@ -186,6 +222,269 @@ pub fn decode_with_report_limited(
|
||||
Ok(decoded)
|
||||
}
|
||||
|
||||
fn check_legacy_header(header: &serde_json::Value, version: Option<u64>) -> Result<(), FileError> {
|
||||
reject_source7_fields(header).map_err(FileError::Invalid)?;
|
||||
if version.is_some_and(|version| version <= 5)
|
||||
&& let Some(diagrams) = header
|
||||
.get("diagrams")
|
||||
.and_then(serde_json::Value::as_object)
|
||||
{
|
||||
for diagram in diagrams.values().filter_map(serde_json::Value::as_object) {
|
||||
for key in diagram.keys() {
|
||||
if key == "view_options" {
|
||||
return Err(FileError::Invalid("Diagram.view_options requires schema/source 6, including an explicitly supplied default value.".into()));
|
||||
}
|
||||
if !matches!(
|
||||
key.as_str(),
|
||||
"id" | "alias"
|
||||
| "name"
|
||||
| "description"
|
||||
| "layer"
|
||||
| "projection"
|
||||
| "nodes"
|
||||
| "routes"
|
||||
) {
|
||||
return Err(FileError::Invalid(format!(
|
||||
"Unknown diagram field '{key}' in the frozen pre6 contract."
|
||||
)));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Versions 4 and 5 share unchanged typed records, but their constructor set
|
||||
/// remains frozen. Apply this before normalizing the advertised version.
|
||||
pub(crate) fn pre6_relation_kind(kind: RelationKind) -> bool {
|
||||
matches!(
|
||||
kind,
|
||||
RelationKind::InterfaceItemAllocation
|
||||
| RelationKind::DataAssociation
|
||||
| RelationKind::Allocation
|
||||
| RelationKind::PortAllocation
|
||||
| RelationKind::Interaction
|
||||
| RelationKind::CapabilityInvolvement
|
||||
| RelationKind::ChainInvolvement
|
||||
| RelationKind::RoleRealization
|
||||
| RelationKind::RoleAssignment
|
||||
| RelationKind::FunctionalExchange
|
||||
| RelationKind::BoundaryExchange
|
||||
| RelationKind::MissionCapability
|
||||
| RelationKind::CapabilityInclude
|
||||
| RelationKind::CapabilityExtend
|
||||
| RelationKind::CapabilityGeneralization
|
||||
| RelationKind::MissionInvolvement
|
||||
| RelationKind::SequenceLink
|
||||
| RelationKind::StateTransition
|
||||
| RelationKind::Availability
|
||||
| RelationKind::ExchangeAllocation
|
||||
| RelationKind::InterfaceProvision
|
||||
| RelationKind::InterfaceRequirement
|
||||
| RelationKind::StateAction
|
||||
)
|
||||
}
|
||||
pub(crate) fn pre6_element_kind(kind: Kind) -> bool {
|
||||
matches!(
|
||||
kind,
|
||||
Kind::Entity
|
||||
| Kind::Actor
|
||||
| Kind::Role
|
||||
| Kind::Activity
|
||||
| Kind::Capability
|
||||
| Kind::OperationalMission
|
||||
| Kind::Process
|
||||
| Kind::System
|
||||
| Kind::SystemActor
|
||||
| Kind::Function
|
||||
| Kind::SystemCapability
|
||||
| Kind::Mission
|
||||
| Kind::FunctionalChain
|
||||
| Kind::ExchangeItem
|
||||
| Kind::DataType
|
||||
| Kind::DataField
|
||||
| Kind::Interface
|
||||
| Kind::Port
|
||||
| Kind::Scenario
|
||||
| Kind::Lifeline
|
||||
| Kind::Occurrence
|
||||
| Kind::StateMachine
|
||||
| Kind::Region
|
||||
| Kind::State
|
||||
| Kind::Mode
|
||||
| Kind::Initial
|
||||
| Kind::Final
|
||||
| Kind::Choice
|
||||
| Kind::Junction
|
||||
| Kind::Fork
|
||||
| Kind::Join
|
||||
| Kind::ShallowHistory
|
||||
| Kind::DeepHistory
|
||||
| Kind::EntryPoint
|
||||
| Kind::ExitPoint
|
||||
| Kind::Terminate
|
||||
| Kind::Event
|
||||
| Kind::Constraint
|
||||
)
|
||||
}
|
||||
pub(crate) fn check_pre6_relations<'a>(
|
||||
relations: impl Iterator<Item = &'a Relation>,
|
||||
) -> Result<(), FileError> {
|
||||
for relation in relations {
|
||||
if !pre6_relation_kind(relation.kind()) {
|
||||
return Err(FileError::Invalid(format!(
|
||||
"{:?} requires schema/source 6.",
|
||||
relation.kind()
|
||||
)));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
pub(crate) fn check_pre6_elements<'a>(
|
||||
elements: impl Iterator<Item = &'a Element>,
|
||||
) -> Result<(), FileError> {
|
||||
for element in elements {
|
||||
if !pre6_element_kind(element.kind()) {
|
||||
return Err(FileError::Invalid(format!(
|
||||
"{:?} requires schema/source 6.",
|
||||
element.kind()
|
||||
)));
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
pub(crate) fn check_pre6_baseline(baseline: &SemanticBaseline) -> Result<(), FileError> {
|
||||
if baseline.facets.iter().any(|f| {
|
||||
matches!(
|
||||
f,
|
||||
FacetReview::Category(_)
|
||||
| FacetReview::Member {
|
||||
collection: ReferenceCollection::CategoryExchanges,
|
||||
..
|
||||
}
|
||||
)
|
||||
}) {
|
||||
return Err(FileError::Invalid(
|
||||
"Exchange category semantic facts require schema/source 6.".into(),
|
||||
));
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
pub(crate) fn migrate_v5(
|
||||
mut project: Project,
|
||||
limits: crate::language::ParseLimits,
|
||||
) -> Result<DecodeResult, FileError> {
|
||||
if project.schema_version != 5 {
|
||||
return Err(FileError::Invalid("Expected schema_version 5.".into()));
|
||||
}
|
||||
reject_pre8_project(&project)?;
|
||||
check_pre6_relations(project.relations.values())?;
|
||||
check_pre6_elements(project.elements.values())?;
|
||||
for baseline in project
|
||||
.traces
|
||||
.values()
|
||||
.filter_map(|t| t.baseline.as_ref().and_then(|b| b.semantic.as_ref()))
|
||||
{
|
||||
check_pre6_baseline(baseline)?;
|
||||
}
|
||||
limits.check_model(&project).map_err(FileError::Limit)?;
|
||||
project.schema_version = SCHEMA_VERSION;
|
||||
Ok(DecodeResult {
|
||||
project,
|
||||
migration: Some(MigrationReport::data_upgrade(5)),
|
||||
})
|
||||
}
|
||||
|
||||
/// Reject explicit new fields before serde defaults can erase their presence.
|
||||
/// This is also applied to source's resolved structured values.
|
||||
pub(crate) fn reject_source7_fields(value: &serde_json::Value) -> Result<(), String> {
|
||||
let mut pending = vec![value];
|
||||
while let Some(value) = pending.pop() {
|
||||
match value {
|
||||
serde_json::Value::Object(fields) => {
|
||||
if fields.contains_key("ContextualLink") {
|
||||
return Err("ContextualLink requires schema/source 7.".into());
|
||||
}
|
||||
if fields.get("Relation").and_then(serde_json::Value::as_str)
|
||||
== Some("ContextualLink")
|
||||
{
|
||||
return Err("ContextualLink view selectors require schema/source 7.".into());
|
||||
}
|
||||
if fields.keys().any(|key| {
|
||||
matches!(
|
||||
key.as_str(),
|
||||
"Operation"
|
||||
| "ContextOwner"
|
||||
| "ContextSource"
|
||||
| "ContextTarget"
|
||||
| "ContextPurpose"
|
||||
)
|
||||
}) {
|
||||
return Err(
|
||||
"Operation/contextual-link semantic facets require schema/source 7.".into(),
|
||||
);
|
||||
}
|
||||
if fields
|
||||
.get("Exchange")
|
||||
.and_then(serde_json::Value::as_object)
|
||||
.is_some_and(|body| body.contains_key("operation"))
|
||||
{
|
||||
return Err(
|
||||
"Exchange.operation requires schema/source 7, including explicit null."
|
||||
.into(),
|
||||
);
|
||||
}
|
||||
pending.extend(fields.values().rev());
|
||||
}
|
||||
serde_json::Value::Array(values) => {
|
||||
pending.extend(values.iter().rev());
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
pub(crate) fn migrate_v6(
|
||||
mut project: Project,
|
||||
limits: crate::language::ParseLimits,
|
||||
) -> Result<DecodeResult, FileError> {
|
||||
if project.schema_version != 6 {
|
||||
return Err(FileError::Invalid("Expected schema_version 6.".into()));
|
||||
}
|
||||
reject_pre8_project(&project)?;
|
||||
reject_source7_fields(&serde_json::to_value(&project)?).map_err(FileError::Invalid)?;
|
||||
limits.check_model(&project).map_err(FileError::Limit)?;
|
||||
project.schema_version = SCHEMA_VERSION;
|
||||
Ok(DecodeResult {
|
||||
project,
|
||||
migration: Some(MigrationReport::data_upgrade(6)),
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) fn migrate_v7(
|
||||
mut project: Project,
|
||||
limits: crate::language::ParseLimits,
|
||||
) -> Result<DecodeResult, FileError> {
|
||||
if project.schema_version != 7 {
|
||||
return Err(FileError::Invalid("Expected schema_version 7.".into()));
|
||||
}
|
||||
reject_pre8_project(&project)?;
|
||||
limits.check_model(&project).map_err(FileError::Limit)?;
|
||||
project.schema_version = SCHEMA_VERSION;
|
||||
Ok(DecodeResult {
|
||||
project,
|
||||
migration: Some(MigrationReport::data_upgrade(7)),
|
||||
})
|
||||
}
|
||||
fn reject_pre8_project(project: &Project) -> Result<(), FileError> {
|
||||
if !project.definitions.is_empty() {
|
||||
return Err(FileError::Invalid(
|
||||
"Definitions require schema/source 8.".into(),
|
||||
));
|
||||
}
|
||||
v7::reject_elements(project.elements.values())
|
||||
}
|
||||
|
||||
pub(crate) fn migrate_v1_with_report_limited(
|
||||
old: v1::Project,
|
||||
limits: crate::language::ParseLimits,
|
||||
@@ -603,6 +902,9 @@ pub(crate) mod v1 {
|
||||
}
|
||||
|
||||
fn validate_project(p: &Project) -> Result<(), FileError> {
|
||||
json_codec::document_stack(|| validate_project_inner(p))
|
||||
}
|
||||
fn validate_project_inner(p: &Project) -> Result<(), FileError> {
|
||||
if let Some(i) = validation::validate(p)
|
||||
.into_iter()
|
||||
.find(|i| i.severity == validation::Severity::Error)
|
||||
@@ -618,7 +920,10 @@ pub fn load(path: &Path) -> Result<Project, FileError> {
|
||||
load_with_report(path).map(|decoded| decoded.project)
|
||||
}
|
||||
pub fn load_with_report(path: &Path) -> Result<DecodeResult, FileError> {
|
||||
decode_with_report(&std::fs::read(path)?)
|
||||
decode_with_report(&json_codec::read_bounded(
|
||||
path,
|
||||
json_codec::MAX_DOCUMENT_BYTES,
|
||||
)?)
|
||||
}
|
||||
/// Serialize to a sibling temporary file, flush, then atomically replace the destination.
|
||||
pub fn save(path: &Path, p: &Project) -> Result<(), FileError> {
|
||||
@@ -631,19 +936,69 @@ pub fn save_checked(
|
||||
path: &Path,
|
||||
p: &Project,
|
||||
expected: Option<&[u8]>,
|
||||
) -> Result<Vec<u8>, FileError> {
|
||||
save_checked_profile(
|
||||
path,
|
||||
p,
|
||||
expected,
|
||||
json_codec::Profile::DOCUMENT,
|
||||
json_codec::DEPTH_128_VALIDATED,
|
||||
)
|
||||
}
|
||||
fn save_checked_profile(
|
||||
path: &Path,
|
||||
p: &Project,
|
||||
expected: Option<&[u8]>,
|
||||
profile: json_codec::Profile,
|
||||
depth_128: bool,
|
||||
) -> Result<Vec<u8>, FileError> {
|
||||
save_checked_profile_with_source(path, p, expected, profile, depth_128, |project| {
|
||||
crate::language::format(project).into_bytes()
|
||||
})
|
||||
}
|
||||
// Keep the source writer replaceable only at this private seam so regressions
|
||||
// can prove that malformed or lossy output never reaches filesystem staging.
|
||||
fn save_checked_profile_with_source(
|
||||
path: &Path,
|
||||
p: &Project,
|
||||
expected: Option<&[u8]>,
|
||||
profile: json_codec::Profile,
|
||||
depth_128: bool,
|
||||
source: impl FnOnce(&Project) -> Vec<u8>,
|
||||
) -> Result<Vec<u8>, FileError> {
|
||||
validate_project(p)?;
|
||||
let mut bytes = if path
|
||||
let is_source = path
|
||||
.extension()
|
||||
.is_some_and(|ext| ext.eq_ignore_ascii_case("arcadia"))
|
||||
{
|
||||
crate::language::format(p).into_bytes()
|
||||
.is_some_and(|ext| ext.eq_ignore_ascii_case("arcadia"));
|
||||
let mut bytes = if is_source {
|
||||
source(p)
|
||||
} else {
|
||||
serde_json::to_vec_pretty(p)?
|
||||
json_codec::encode(p, profile, depth_128)?
|
||||
};
|
||||
if !bytes.ends_with(b"\n") {
|
||||
bytes.push(b'\n');
|
||||
}
|
||||
if is_source {
|
||||
// Check exactly the final bytes, including their newline, through the
|
||||
// public reader before creating a temp file or replacing a destination.
|
||||
let decoded = decode_with_report_limited(
|
||||
&bytes,
|
||||
crate::language::ParseLimits {
|
||||
max_source_bytes: profile.bytes,
|
||||
..crate::language::ParseLimits::UNLIMITED
|
||||
},
|
||||
)?;
|
||||
if decoded.project != *p {
|
||||
return Err(FileError::Invalid(
|
||||
"Generated source does not reproduce the complete requested project.".into(),
|
||||
));
|
||||
}
|
||||
if decoded.migration.is_some() {
|
||||
return Err(FileError::Invalid(
|
||||
"Generated source unexpectedly requires migration.".into(),
|
||||
));
|
||||
}
|
||||
}
|
||||
let parent = path
|
||||
.parent()
|
||||
.filter(|p| !p.as_os_str().is_empty())
|
||||
@@ -652,8 +1007,8 @@ pub fn save_checked(
|
||||
temp.write_all(&bytes)?;
|
||||
temp.as_file().sync_all()?;
|
||||
if let Some(expected) = expected {
|
||||
match std::fs::read(path) {
|
||||
Ok(current) if current == expected => {}
|
||||
match json_codec::matches_file(path, expected) {
|
||||
Ok(true) => {}
|
||||
Ok(_) => return Err(FileError::Conflict),
|
||||
Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Err(FileError::Conflict),
|
||||
Err(e) => return Err(FileError::Io(e)),
|
||||
|
||||
@@ -0,0 +1,427 @@
|
||||
//! Private persistence JSON boundary. Scan original bytes before Serde allocates;
|
||||
//! the scanner is a resource meter, never a second accepting JSON grammar.
|
||||
use super::FileError;
|
||||
use crate::{
|
||||
Project,
|
||||
analysis::expression_serde::{self, Scope},
|
||||
};
|
||||
use serde::{
|
||||
Deserialize,
|
||||
de::{IgnoredAny, MapAccess, Visitor},
|
||||
};
|
||||
use std::{
|
||||
fmt,
|
||||
io::{self, Read, Write},
|
||||
};
|
||||
|
||||
pub(super) const MAX_DOCUMENT_BYTES: usize = 64 * 1024 * 1024;
|
||||
const MAX_CONTAINERS: usize = 512;
|
||||
// This switch stays false until Windows/Linux debug/release codec + ordinary
|
||||
// lifecycle gates pass. Tests exercise the candidate through the same private
|
||||
// entry point with depth_128=true. It is not a user-controlled parser option.
|
||||
pub(super) const DEPTH_128_VALIDATED: bool = false;
|
||||
|
||||
/// Allocation cardinalities, independent of graph admission and numeric work.
|
||||
/// The default deliberately admits the existing CLI's 100000 graph objects,
|
||||
/// 250000 records and 500000 ordered references within its 64 MiB envelope.
|
||||
/// Strings have no new 1 MiB restriction: any span fitting that envelope fits.
|
||||
/// These are explicit slot/text bounds, not an assertion of process RSS.
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub(super) struct Profile {
|
||||
pub bytes: usize,
|
||||
pub tokens: usize,
|
||||
pub entries: usize,
|
||||
pub container_entries: usize,
|
||||
pub string_bytes: usize,
|
||||
pub total_string_bytes: usize,
|
||||
pub expression_nodes: usize,
|
||||
}
|
||||
impl Profile {
|
||||
pub const DOCUMENT: Self = Self {
|
||||
bytes: MAX_DOCUMENT_BYTES,
|
||||
tokens: 16 * 1024 * 1024,
|
||||
entries: 8 * 1024 * 1024,
|
||||
container_entries: 500_000,
|
||||
string_bytes: MAX_DOCUMENT_BYTES,
|
||||
total_string_bytes: MAX_DOCUMENT_BYTES,
|
||||
expression_nodes: expression_serde::MAX_JSON_EXPRESSION_NODES,
|
||||
};
|
||||
pub fn with_byte_limit(maximum: usize) -> Self {
|
||||
Self {
|
||||
bytes: maximum.min(MAX_DOCUMENT_BYTES),
|
||||
..Self::DOCUMENT
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
|
||||
pub(super) struct Usage {
|
||||
pub tokens: usize,
|
||||
pub entries: usize,
|
||||
pub string_bytes: usize,
|
||||
pub deepest_container: usize,
|
||||
}
|
||||
#[derive(Clone, Copy)]
|
||||
struct Container {
|
||||
delimiter: u8,
|
||||
entries: usize,
|
||||
first: bool,
|
||||
}
|
||||
const EMPTY: Container = Container {
|
||||
delimiter: 0,
|
||||
entries: 0,
|
||||
first: true,
|
||||
};
|
||||
|
||||
fn limit(message: &str) -> FileError {
|
||||
FileError::Limit(message.into())
|
||||
}
|
||||
fn charge(used: &mut usize, amount: usize, maximum: usize, message: &str) -> Result<(), FileError> {
|
||||
if amount > maximum.saturating_sub(*used) {
|
||||
return Err(limit(message));
|
||||
}
|
||||
*used += amount;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(super) fn preflight(bytes: &[u8], profile: Profile) -> Result<Usage, FileError> {
|
||||
if bytes.len() > profile.bytes {
|
||||
return Err(limit("JSON input byte limit exceeded."));
|
||||
}
|
||||
// Fixed storage: no Vec/Value/String and no recursive calls during preflight.
|
||||
let mut containers = [EMPTY; MAX_CONTAINERS];
|
||||
let mut depth = 0usize;
|
||||
let mut usage = Usage::default();
|
||||
let mut cursor = 0usize;
|
||||
while cursor < bytes.len() {
|
||||
let byte = bytes[cursor];
|
||||
if byte.is_ascii_whitespace() {
|
||||
cursor += 1;
|
||||
continue;
|
||||
}
|
||||
charge(
|
||||
&mut usage.tokens,
|
||||
1,
|
||||
profile.tokens,
|
||||
"JSON token limit exceeded.",
|
||||
)?;
|
||||
if !matches!(byte, b',' | b':' | b'}' | b']') && depth > 0 {
|
||||
let frame = &mut containers[depth - 1];
|
||||
if frame.first {
|
||||
charge(
|
||||
&mut frame.entries,
|
||||
1,
|
||||
profile.container_entries,
|
||||
"JSON container entry limit exceeded.",
|
||||
)?;
|
||||
charge(
|
||||
&mut usage.entries,
|
||||
1,
|
||||
profile.entries,
|
||||
"JSON aggregate entry limit exceeded.",
|
||||
)?;
|
||||
frame.first = false;
|
||||
}
|
||||
}
|
||||
match byte {
|
||||
b'{' | b'[' => {
|
||||
if depth == MAX_CONTAINERS {
|
||||
return Err(limit("JSON container depth exceeds 512."));
|
||||
}
|
||||
containers[depth] = Container {
|
||||
delimiter: byte,
|
||||
..EMPTY
|
||||
};
|
||||
depth += 1;
|
||||
usage.deepest_container = usage.deepest_container.max(depth);
|
||||
cursor += 1;
|
||||
}
|
||||
b'}' | b']' => {
|
||||
if depth == 0
|
||||
|| !matches!(
|
||||
(containers[depth - 1].delimiter, byte),
|
||||
(b'{', b'}') | (b'[', b']')
|
||||
)
|
||||
{
|
||||
return Err(FileError::Invalid(
|
||||
"Mismatched JSON container delimiter.".into(),
|
||||
));
|
||||
}
|
||||
depth -= 1;
|
||||
cursor += 1;
|
||||
}
|
||||
b',' => {
|
||||
if depth > 0 {
|
||||
containers[depth - 1].first = true;
|
||||
}
|
||||
cursor += 1;
|
||||
}
|
||||
b':' => cursor += 1,
|
||||
b'"' => {
|
||||
cursor += 1;
|
||||
let start = cursor;
|
||||
let mut closed = false;
|
||||
while cursor < bytes.len() {
|
||||
match bytes[cursor] {
|
||||
b'"' => {
|
||||
closed = true;
|
||||
break;
|
||||
}
|
||||
b'\\' => {
|
||||
// Skip exactly one escaped byte, including an escaped
|
||||
// backslash. Serde validates actual escapes/UTF-8.
|
||||
cursor += 1;
|
||||
if cursor < bytes.len() {
|
||||
cursor += 1;
|
||||
}
|
||||
}
|
||||
_ => cursor += 1,
|
||||
}
|
||||
}
|
||||
let span = cursor - start;
|
||||
if span > profile.string_bytes {
|
||||
return Err(limit("JSON string byte limit exceeded."));
|
||||
}
|
||||
charge(
|
||||
&mut usage.string_bytes,
|
||||
span,
|
||||
profile.total_string_bytes,
|
||||
"JSON aggregate string byte limit exceeded.",
|
||||
)?;
|
||||
if !closed {
|
||||
return Err(FileError::Invalid("Unterminated JSON string.".into()));
|
||||
}
|
||||
cursor += 1;
|
||||
}
|
||||
_ => {
|
||||
// Count a scalar token without interpreting its value. Invalid
|
||||
// tokens and invalid whitespace must still fail the Serde pass.
|
||||
cursor += 1;
|
||||
while cursor < bytes.len()
|
||||
&& !bytes[cursor].is_ascii_whitespace()
|
||||
&& !matches!(
|
||||
bytes[cursor],
|
||||
b'{' | b'[' | b'}' | b']' | b',' | b':' | b'"'
|
||||
)
|
||||
{
|
||||
cursor += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if depth != 0 {
|
||||
return Err(FileError::Invalid("Unclosed JSON container.".into()));
|
||||
}
|
||||
Ok(usage)
|
||||
}
|
||||
|
||||
struct Version(Option<u64>);
|
||||
impl<'de> Deserialize<'de> for Version {
|
||||
fn deserialize<D: serde::Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
|
||||
struct Header;
|
||||
impl<'de> Visitor<'de> for Header {
|
||||
type Value = Version;
|
||||
fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
f.write_str("a project header")
|
||||
}
|
||||
fn visit_map<A: MapAccess<'de>>(self, mut access: A) -> Result<Version, A::Error> {
|
||||
#[derive(Deserialize)]
|
||||
#[serde(field_identifier)]
|
||||
enum Key {
|
||||
#[serde(rename = "schema_version")]
|
||||
Schema,
|
||||
#[serde(other)]
|
||||
Other,
|
||||
}
|
||||
let mut version = None;
|
||||
while let Some(key) = access.next_key::<Key>()? {
|
||||
match key {
|
||||
Key::Schema => {
|
||||
if version.is_some() {
|
||||
return Err(serde::de::Error::duplicate_field("schema_version"));
|
||||
}
|
||||
version = Some(access.next_value()?);
|
||||
}
|
||||
Key::Other => {
|
||||
access.next_value::<IgnoredAny>()?;
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(Version(version))
|
||||
}
|
||||
}
|
||||
deserializer.deserialize_map(Header)
|
||||
}
|
||||
}
|
||||
|
||||
/// IgnoredAny in serde_json walks arbitrary ignored containers iteratively.
|
||||
/// This probe does not materialize ignored subtrees. Serde's scratch buffer for
|
||||
/// container markers/escaped keys is bounded by the preceding raw scan. It
|
||||
/// consumes the entire original stream and rejects duplicate/escaped versions.
|
||||
pub(super) fn version(bytes: &[u8]) -> Result<Option<u64>, FileError> {
|
||||
document_stack(|| {
|
||||
let mut deserializer = serde_json::Deserializer::from_slice(bytes);
|
||||
let version = Version::deserialize(&mut deserializer)?;
|
||||
deserializer.end()?;
|
||||
Ok(version.0)
|
||||
})
|
||||
}
|
||||
|
||||
pub(super) fn document_stack<R>(operation: impl FnOnce() -> R) -> R {
|
||||
// Non-Expr Project and historical schemas are finitely nested by their
|
||||
// concrete Rust types. Reserve for that outer generated Serde frame chain;
|
||||
// only recursive Expr edges use the smaller repeated boundary guard.
|
||||
stacker::maybe_grow(512 * 1024, 2 * 1024 * 1024, operation)
|
||||
}
|
||||
pub(super) fn current(
|
||||
bytes: &[u8],
|
||||
profile: Profile,
|
||||
depth_128: bool,
|
||||
) -> Result<Project, FileError> {
|
||||
preflight(bytes, profile)?;
|
||||
let _scope = Scope::decoding(profile.expression_nodes);
|
||||
document_stack(|| {
|
||||
let mut deserializer = serde_json::Deserializer::from_slice(bytes);
|
||||
if depth_128 {
|
||||
deserializer.disable_recursion_limit();
|
||||
}
|
||||
let project = Project::deserialize(&mut deserializer)?;
|
||||
deserializer.end()?;
|
||||
Ok(project)
|
||||
})
|
||||
}
|
||||
pub(super) fn legacy<T: serde::de::DeserializeOwned>(bytes: &[u8]) -> Result<T, FileError> {
|
||||
// Never disable the legacy recursion guard, including its temporary Value.
|
||||
document_stack(|| Ok(serde_json::from_slice(bytes)?))
|
||||
}
|
||||
|
||||
pub(super) fn discard_value(value: serde_json::Value) {
|
||||
let mut pending = vec![value];
|
||||
while let Some(value) = pending.pop() {
|
||||
match value {
|
||||
serde_json::Value::Array(values) => pending.extend(values),
|
||||
serde_json::Value::Object(values) => pending.extend(values.into_values()),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn reserve_bounded(bytes: &mut Vec<u8>, additional: usize, maximum: usize) -> io::Result<()> {
|
||||
let required = bytes.len() + additional;
|
||||
if required > bytes.capacity() {
|
||||
let next = bytes
|
||||
.capacity()
|
||||
.max(4096)
|
||||
.saturating_mul(2)
|
||||
.max(required)
|
||||
.min(maximum);
|
||||
bytes
|
||||
.try_reserve_exact(next - bytes.len())
|
||||
.map_err(io::Error::other)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
struct CappedWriter {
|
||||
bytes: Vec<u8>,
|
||||
maximum: usize,
|
||||
exceeded: bool,
|
||||
}
|
||||
impl CappedWriter {
|
||||
fn new(maximum: usize) -> Self {
|
||||
Self {
|
||||
bytes: Vec::new(),
|
||||
maximum,
|
||||
exceeded: false,
|
||||
}
|
||||
}
|
||||
}
|
||||
impl Write for CappedWriter {
|
||||
fn write(&mut self, bytes: &[u8]) -> io::Result<usize> {
|
||||
if bytes.len() > self.maximum.saturating_sub(self.bytes.len()) {
|
||||
self.exceeded = true;
|
||||
return Err(io::Error::other("JSON output byte limit exceeded."));
|
||||
}
|
||||
// Check before reserve/extend; failed output never creates a giant Vec.
|
||||
reserve_bounded(&mut self.bytes, bytes.len(), self.maximum)?;
|
||||
self.bytes.extend_from_slice(bytes);
|
||||
Ok(bytes.len())
|
||||
}
|
||||
fn flush(&mut self) -> io::Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// Compact output avoids indentation multiplying the cost of legal depth128.
|
||||
/// The returned bytes have already passed the identical reader resource profile.
|
||||
pub(super) fn encode(
|
||||
project: &Project,
|
||||
profile: Profile,
|
||||
depth_128: bool,
|
||||
) -> Result<Vec<u8>, FileError> {
|
||||
let _scope = Scope::encoding(profile.expression_nodes);
|
||||
let mut writer = CappedWriter::new(profile.bytes);
|
||||
let result = document_stack(|| serde_json::to_writer(&mut writer, project));
|
||||
if writer.exceeded {
|
||||
return Err(limit("JSON output byte limit exceeded."));
|
||||
}
|
||||
result?;
|
||||
writer.write_all(b"\n").map_err(|error| {
|
||||
if writer.exceeded {
|
||||
limit("JSON output byte limit exceeded.")
|
||||
} else {
|
||||
FileError::Io(error)
|
||||
}
|
||||
})?;
|
||||
// Establish save/reopen symmetry before filesystem mutation, including the
|
||||
// conservative production guard until the deeper profile is validated.
|
||||
let reopened = current(&writer.bytes, profile, depth_128)?;
|
||||
if reopened != *project {
|
||||
return Err(FileError::Invalid(
|
||||
"JSON serialization did not preserve the project value.".into(),
|
||||
));
|
||||
}
|
||||
Ok(writer.bytes)
|
||||
}
|
||||
|
||||
pub(super) fn read_bounded(path: &std::path::Path, maximum: usize) -> Result<Vec<u8>, FileError> {
|
||||
let mut file = std::fs::File::open(path)?;
|
||||
if file.metadata()?.len() > maximum as u64 {
|
||||
return Err(limit("Input file byte limit exceeded."));
|
||||
}
|
||||
let mut bytes = Vec::new();
|
||||
let mut chunk = [0u8; 8192];
|
||||
loop {
|
||||
let count = file.read(&mut chunk)?;
|
||||
if count == 0 {
|
||||
return Ok(bytes);
|
||||
}
|
||||
if count > maximum.saturating_sub(bytes.len()) {
|
||||
return Err(limit("Input file byte limit exceeded."));
|
||||
}
|
||||
reserve_bounded(&mut bytes, count, maximum)?;
|
||||
bytes.extend_from_slice(&chunk[..count]);
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn matches_file(path: &std::path::Path, expected: &[u8]) -> io::Result<bool> {
|
||||
let mut file = std::fs::File::open(path)?;
|
||||
if file.metadata()?.len() != expected.len() as u64 {
|
||||
return Ok(false);
|
||||
}
|
||||
let mut compared = 0usize;
|
||||
let mut chunk = [0u8; 8192];
|
||||
loop {
|
||||
let count = file.read(&mut chunk)?;
|
||||
if count == 0 {
|
||||
return Ok(compared == expected.len());
|
||||
}
|
||||
if expected.get(compared..compared + count) != Some(&chunk[..count]) {
|
||||
return Ok(false);
|
||||
}
|
||||
compared += count;
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
@@ -0,0 +1,612 @@
|
||||
use super::*;
|
||||
use crate::{
|
||||
Element, ElementBody, Id, OaBody,
|
||||
analysis::{
|
||||
AnalysisType, Binding, CalculationDefinition, Definition, DefinitionBody, Expr, Parameter,
|
||||
ParameterId, ScalarType, UnaryOp,
|
||||
},
|
||||
language::ParseLimits,
|
||||
persistence,
|
||||
};
|
||||
use std::{
|
||||
fmt::Write as _,
|
||||
process::{Command, Stdio},
|
||||
time::{Duration, Instant},
|
||||
};
|
||||
|
||||
const IDENTITY: &str = "00000000-0000-0000-0000-000000000001";
|
||||
const PARAMETER: &str = "00000000-0000-0000-0000-000000000002";
|
||||
const MAIN: &str = "00000000-0000-0000-0000-000000000003";
|
||||
fn id(value: &str) -> Id {
|
||||
Id::parse_str(value).unwrap()
|
||||
}
|
||||
fn boolean_type() -> AnalysisType {
|
||||
AnalysisType::Scalar(ScalarType::Boolean)
|
||||
}
|
||||
fn definition(id: Id, alias: &str, parameters: Vec<Parameter>, body: Expr) -> Definition {
|
||||
Definition {
|
||||
id,
|
||||
alias: alias.into(),
|
||||
name: alias.into(),
|
||||
description: String::new(),
|
||||
body: DefinitionBody::Calculation(CalculationDefinition {
|
||||
parameters,
|
||||
result: boolean_type(),
|
||||
body: Binding::Expression(body),
|
||||
}),
|
||||
}
|
||||
}
|
||||
fn project() -> Project {
|
||||
let mut project = Project::empty();
|
||||
project.id = Id::from_u128(1000);
|
||||
project.definitions.insert(
|
||||
id(IDENTITY),
|
||||
definition(
|
||||
id(IDENTITY),
|
||||
"identity",
|
||||
vec![Parameter {
|
||||
id: ParameterId(id(PARAMETER)),
|
||||
name: "value".into(),
|
||||
value_type: boolean_type(),
|
||||
}],
|
||||
Expr::Parameter(ParameterId(id(PARAMETER))),
|
||||
),
|
||||
);
|
||||
project.definitions.insert(
|
||||
id(MAIN),
|
||||
definition(id(MAIN), "main", vec![], Expr::Boolean(true)),
|
||||
);
|
||||
project
|
||||
}
|
||||
fn wire(expression: &str) -> Vec<u8> {
|
||||
let shallow = serde_json::to_string(&project()).unwrap();
|
||||
assert_eq!(shallow.matches(r#"{"Boolean":true}"#).count(), 1);
|
||||
shallow
|
||||
.replace(r#"{"Boolean":true}"#, expression)
|
||||
.into_bytes()
|
||||
}
|
||||
fn chain(depth: usize, call: bool) -> String {
|
||||
assert!(depth > 0);
|
||||
let prefix = if call {
|
||||
format!(r#"{{"Call":{{"definition":{{"Local":"{IDENTITY}"}},"arguments":{{"{PARAMETER}":"#)
|
||||
} else {
|
||||
r#"{"Unary":{"op":"Not","operand":"#.into()
|
||||
};
|
||||
let suffix = if call { "}}}" } else { "}}" };
|
||||
format!(
|
||||
"{}{}{}",
|
||||
prefix.repeat(depth - 1),
|
||||
r#"{"Boolean":true}"#,
|
||||
suffix.repeat(depth - 1)
|
||||
)
|
||||
}
|
||||
fn candidate(bytes: &[u8], profile: Profile) -> Result<Project, FileError> {
|
||||
persistence::decode_with_report_profile(bytes, ParseLimits::UNLIMITED, profile, true)
|
||||
.map(|decoded| decoded.project)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn resource_preflight_has_exact_lowerable_boundaries() {
|
||||
let bytes = br#"{"key":["a\\\"[{}]",0,true],"other":"\u0061"}"#;
|
||||
let usage = preflight(bytes, Profile::DOCUMENT).unwrap();
|
||||
let exact = Profile {
|
||||
bytes: bytes.len(),
|
||||
tokens: usage.tokens,
|
||||
entries: usage.entries,
|
||||
container_entries: 3,
|
||||
string_bytes: 9,
|
||||
total_string_bytes: usage.string_bytes,
|
||||
..Profile::DOCUMENT
|
||||
};
|
||||
preflight(bytes, exact).unwrap();
|
||||
for lower in [
|
||||
Profile {
|
||||
bytes: exact.bytes - 1,
|
||||
..exact
|
||||
},
|
||||
Profile {
|
||||
tokens: exact.tokens - 1,
|
||||
..exact
|
||||
},
|
||||
Profile {
|
||||
entries: exact.entries - 1,
|
||||
..exact
|
||||
},
|
||||
Profile {
|
||||
container_entries: 2,
|
||||
..exact
|
||||
},
|
||||
Profile {
|
||||
total_string_bytes: exact.total_string_bytes - 1,
|
||||
..exact
|
||||
},
|
||||
Profile {
|
||||
string_bytes: exact.string_bytes - 1,
|
||||
..exact
|
||||
},
|
||||
] {
|
||||
assert!(matches!(preflight(bytes, lower), Err(FileError::Limit(_))));
|
||||
}
|
||||
let deepest = format!("{}0{}", "[".repeat(512), "]".repeat(512));
|
||||
assert_eq!(
|
||||
preflight(deepest.as_bytes(), Profile::DOCUMENT)
|
||||
.unwrap()
|
||||
.deepest_container,
|
||||
512
|
||||
);
|
||||
assert!(matches!(
|
||||
preflight(format!("[{deepest}]").as_bytes(), Profile::DOCUMENT),
|
||||
Err(FileError::Limit(_))
|
||||
));
|
||||
// A huge ignored scalar array exhausts preflight before a header is decoded.
|
||||
assert!(matches!(
|
||||
preflight(
|
||||
br#"{"schema_version":8,"junk":[0,0,0,0]}"#,
|
||||
Profile {
|
||||
container_entries: 3,
|
||||
..Profile::DOCUMENT
|
||||
}
|
||||
),
|
||||
Err(FileError::Limit(_))
|
||||
));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn scanner_is_not_a_parallel_json_grammar() {
|
||||
for bytes in [
|
||||
br#"{"schema_version":8}{}"#.as_slice(),
|
||||
br#"{"schema_version":8,}"#,
|
||||
br#"{"schema_version":8 "junk":0}"#,
|
||||
br#"{"schema_version":8,"schema_version":8}"#,
|
||||
br#"{"schema_version":8,"\u0073chema_version":8}"#,
|
||||
br#"{"schema_version":8,"junk":"\q"}"#,
|
||||
br#"{"schema_version":8,"junk":"unfinished}"#,
|
||||
br#"{"schema_version":8,"junk":[}"#,
|
||||
] {
|
||||
assert!(candidate(bytes, Profile::DOCUMENT).is_err(), "{bytes:?}");
|
||||
}
|
||||
let mut invalid_utf8 = wire(r#"{"Boolean":true}"#);
|
||||
let offset = invalid_utf8
|
||||
.windows(7)
|
||||
.position(|window| window == b"mission")
|
||||
.unwrap();
|
||||
invalid_utf8[offset] = 0xff;
|
||||
assert!(candidate(&invalid_utf8, Profile::DOCUMENT).is_err());
|
||||
let escaped = String::from_utf8(wire(r#"{"Boolean":true}"#))
|
||||
.unwrap()
|
||||
.replace(r#""schema_version""#, r#""\u0073chema_version""#);
|
||||
assert_eq!(
|
||||
candidate(escaped.as_bytes(), Profile::DOCUMENT).unwrap(),
|
||||
project()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn remote_serde_keeps_each_existing_expression_variant() {
|
||||
let n = r#"{"Number":{"numerator":"1","denominator":"1"}}"#;
|
||||
let b = r#"{"Boolean":true}"#;
|
||||
let expressions = [
|
||||
b.to_string(),
|
||||
n.to_string(),
|
||||
format!(
|
||||
r#"{{"Quantity":{{"magnitude":{{"numerator":"1","denominator":"1"}},"unit":{{"Local":"{IDENTITY}"}}}}}}"#
|
||||
),
|
||||
format!(r#"{{"Property":"{IDENTITY}"}}"#),
|
||||
format!(r#"{{"Parameter":"{PARAMETER}"}}"#),
|
||||
format!(r#"{{"List":[{n},{n}]}}"#),
|
||||
format!(r#"{{"Unary":{{"op":"Not","operand":{b}}}}}"#),
|
||||
format!(r#"{{"Binary":{{"op":"Add","left":{n},"right":{n}}}}}"#),
|
||||
format!(r#"{{"If":{{"condition":{b},"when_true":{n},"when_false":{n}}}}}"#),
|
||||
format!(
|
||||
r#"{{"Call":{{"definition":{{"Local":"{IDENTITY}"}},"arguments":{{"{PARAMETER}":{b}}}}}}}"#
|
||||
),
|
||||
format!(r#"{{"Sum":{{"values":{{"List":[{n}]}},"initial":{n}}}}}"#),
|
||||
format!(r#"{{"Power":{{"base":{n},"exponent":2}}}}"#),
|
||||
format!(r#"{{"AsKind":{{"kind":{{"Local":"{IDENTITY}"}},"value":{n}}}}}"#),
|
||||
];
|
||||
for original in expressions {
|
||||
let value: Expr = serde_json::from_str(&original).unwrap();
|
||||
let copy = value.clone();
|
||||
assert!(value == copy);
|
||||
assert_eq!(serde_json::to_string(&value).unwrap(), original);
|
||||
assert_eq!(format!("{value:?}"), format!("{copy:?}"));
|
||||
}
|
||||
let list = Expr::List(vec![Expr::Boolean(true), Expr::Boolean(false)]);
|
||||
assert_eq!(format!("{list:?}"), "List([Boolean(true), Boolean(false)])");
|
||||
assert!(list != Expr::List(vec![Expr::Boolean(false), Expr::Boolean(true)]));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn json_profile_does_not_contract_declared_cli_collection_counts() {
|
||||
// Exercise original-byte typed construction at the existing graph ceiling.
|
||||
// This gate checks codec/count compatibility, not 100000-object UI speed.
|
||||
let mut model = Project::empty();
|
||||
model.id = Id::from_u128(1_000_000);
|
||||
for value in 1..=100_000 {
|
||||
let id = Id::from_u128(value);
|
||||
model.elements.insert(
|
||||
id,
|
||||
Element {
|
||||
id,
|
||||
alias: format!("activity_{value}"),
|
||||
name: String::new(),
|
||||
description: String::new(),
|
||||
parent: None,
|
||||
body: ElementBody::Oa(OaBody::Activity),
|
||||
},
|
||||
);
|
||||
}
|
||||
let bytes = encode(&model, Profile::DOCUMENT, true).unwrap();
|
||||
let decoded = current(&bytes, Profile::DOCUMENT, true).unwrap();
|
||||
assert_eq!(decoded.elements.len(), 100_000);
|
||||
let cli = ParseLimits {
|
||||
max_source_bytes: 64 * 1024 * 1024,
|
||||
max_graph_objects: 100_000,
|
||||
max_records: 250_000,
|
||||
max_step_references: 500_000,
|
||||
};
|
||||
cli.check_model(&decoded).unwrap();
|
||||
let references = format!(
|
||||
"[{}\"{IDENTITY}\"]",
|
||||
format!("\"{IDENTITY}\",").repeat(499_999)
|
||||
);
|
||||
preflight(references.as_bytes(), Profile::DOCUMENT).unwrap();
|
||||
assert!(matches!(
|
||||
preflight(
|
||||
format!("[\"{IDENTITY}\",{}]", &references[1..references.len() - 1]).as_bytes(),
|
||||
Profile::DOCUMENT
|
||||
),
|
||||
Err(FileError::Limit(_))
|
||||
));
|
||||
// Metadata over the initially proposed 1 MiB limit remains admissible.
|
||||
let mut text = Project::empty();
|
||||
text.description = "x".repeat(1024 * 1024 + 1);
|
||||
let bytes = encode(&text, Profile::DOCUMENT, true).unwrap();
|
||||
assert_eq!(current(&bytes, Profile::DOCUMENT, true).unwrap(), text);
|
||||
eprintln!(
|
||||
"JSON profile: graph bytes={}, ordered-reference bytes={}, max container entries={}",
|
||||
serde_json::to_string(&model).unwrap().len(),
|
||||
references.len(),
|
||||
Profile::DOCUMENT.container_entries
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn production_save_always_reopens_with_its_reader_profile() {
|
||||
let deep = candidate(&wire(&chain(128, true)), Profile::DOCUMENT).unwrap();
|
||||
let directory = tempfile::tempdir().unwrap();
|
||||
let path = directory.path().join("project.json");
|
||||
std::fs::write(&path, b"previous").unwrap();
|
||||
let saved = persistence::save_checked(&path, &deep, Some(b"previous"));
|
||||
if DEPTH_128_VALIDATED {
|
||||
let bytes = saved.unwrap();
|
||||
assert_eq!(persistence::decode(&bytes).unwrap(), deep);
|
||||
} else {
|
||||
assert!(saved.is_err());
|
||||
assert_eq!(std::fs::read(&path).unwrap(), b"previous");
|
||||
}
|
||||
}
|
||||
|
||||
fn accepted_phase() {
|
||||
for call in [false, true] {
|
||||
let bytes = wire(&chain(128, call));
|
||||
let usage = preflight(&bytes, Profile::DOCUMENT).unwrap();
|
||||
let model = candidate(&bytes, Profile::DOCUMENT).unwrap();
|
||||
let copy = model.clone();
|
||||
assert!(model == copy);
|
||||
let debug = format!("{model:?}");
|
||||
assert!(!debug.is_empty());
|
||||
let output = encode(&model, Profile::DOCUMENT, true).unwrap();
|
||||
assert!(candidate(&output, Profile::DOCUMENT).unwrap() == model);
|
||||
let directory = tempfile::tempdir().unwrap();
|
||||
let path = directory.path().join("deep.json");
|
||||
let saved = persistence::save_checked_profile(&path, &model, None, Profile::DOCUMENT, true)
|
||||
.unwrap();
|
||||
assert!(
|
||||
candidate(
|
||||
&read_bounded(&path, MAX_DOCUMENT_BYTES).unwrap(),
|
||||
Profile::DOCUMENT
|
||||
)
|
||||
.unwrap()
|
||||
== model
|
||||
);
|
||||
assert_eq!(saved, output);
|
||||
eprintln!(
|
||||
"accepted call={call} depth128 input={} output={} tokens={} entries={} raw strings={} containers={} debug={}",
|
||||
bytes.len(),
|
||||
output.len(),
|
||||
usage.tokens,
|
||||
usage.entries,
|
||||
usage.string_bytes,
|
||||
usage.deepest_container,
|
||||
debug.len()
|
||||
);
|
||||
}
|
||||
}
|
||||
fn refused_phase() {
|
||||
for call in [false, true] {
|
||||
let error = candidate(&wire(&chain(129, call)), Profile::DOCUMENT).unwrap_err();
|
||||
assert!(error.to_string().contains("logical depth"), "{error}");
|
||||
}
|
||||
let wide = format!(
|
||||
r#"{{"List":[{}null]}}"#,
|
||||
r#"{"Boolean":true},"#.repeat(1024)
|
||||
);
|
||||
let error = candidate(&wire(&wide), Profile::DOCUMENT).unwrap_err();
|
||||
assert!(error.to_string().contains("1024"), "{error}");
|
||||
let bytes = wire(&chain(128, true));
|
||||
let exact_model = candidate(
|
||||
&bytes,
|
||||
Profile {
|
||||
expression_nodes: 129,
|
||||
..Profile::DOCUMENT
|
||||
},
|
||||
)
|
||||
.unwrap();
|
||||
let error = candidate(
|
||||
&bytes,
|
||||
Profile {
|
||||
expression_nodes: 128,
|
||||
..Profile::DOCUMENT
|
||||
},
|
||||
)
|
||||
.unwrap_err();
|
||||
// Identity's Parameter plus main's 128-node expression exceed this total.
|
||||
assert!(error.to_string().contains("allocation count"), "{error}");
|
||||
let scan = preflight(&bytes, Profile::DOCUMENT).unwrap();
|
||||
assert!(matches!(
|
||||
candidate(
|
||||
&bytes,
|
||||
Profile {
|
||||
tokens: scan.tokens - 1,
|
||||
..Profile::DOCUMENT
|
||||
}
|
||||
),
|
||||
Err(FileError::Limit(_))
|
||||
));
|
||||
document_stack(|| {
|
||||
use crate::analysis::{AdmissionLimits, admit};
|
||||
let events = admit(&exact_model, AdmissionLimits::REFERENCE)
|
||||
.unwrap()
|
||||
.admission_usage()
|
||||
.static_events;
|
||||
admit(
|
||||
&exact_model,
|
||||
AdmissionLimits {
|
||||
max_static_events: events,
|
||||
},
|
||||
)
|
||||
.unwrap();
|
||||
let error = match admit(
|
||||
&exact_model,
|
||||
AdmissionLimits {
|
||||
max_static_events: events - 1,
|
||||
},
|
||||
) {
|
||||
Ok(_) => panic!("Static work below the measured exact count must refuse."),
|
||||
Err(error) => error,
|
||||
};
|
||||
assert_eq!(error.code, "analysis_limit");
|
||||
});
|
||||
let mut tree = r#"{"Boolean":true}"#.to_owned();
|
||||
for _ in 0..15 {
|
||||
tree = format!(r#"{{"Binary":{{"op":"And","left":{tree},"right":{tree}}}}}"#);
|
||||
}
|
||||
// 65535 balanced nodes plus one unary node is the stored-tree boundary.
|
||||
tree = format!(r#"{{"Unary":{{"op":"Not","operand":{tree}}}}}"#);
|
||||
let at_tree_limit = wire(&tree);
|
||||
current(&at_tree_limit, Profile::DOCUMENT, true).unwrap();
|
||||
let beyond = wire(&format!(r#"{{"Unary":{{"op":"Not","operand":{tree}}}}}"#));
|
||||
assert!(
|
||||
current(&beyond, Profile::DOCUMENT, true)
|
||||
.unwrap_err()
|
||||
.to_string()
|
||||
.contains("65536")
|
||||
);
|
||||
// No downstream work after refusal poisons the next ordinary operation.
|
||||
candidate(&wire(&chain(128, true)), Profile::DOCUMENT).unwrap();
|
||||
}
|
||||
fn malformed_phase() {
|
||||
let deep = chain(127, false);
|
||||
for (label, expression) in [
|
||||
(
|
||||
"duplicate operand",
|
||||
format!(r#"{{"Unary":{{"op":"Not","operand":{deep},"operand":null}}}}"#),
|
||||
),
|
||||
(
|
||||
"escaped duplicate",
|
||||
format!(r#"{{"Unary":{{"op":"Not","operand":{deep},"\u006fperand":null}}}}"#),
|
||||
),
|
||||
(
|
||||
"unknown field",
|
||||
format!(r#"{{"Unary":{{"op":"Not","operand":{deep},"surprise":null}}}}"#),
|
||||
),
|
||||
(
|
||||
"duplicate enum",
|
||||
format!(r#"{{"Unary":{{"op":"Not","operand":{deep}}},"Boolean":true}}"#),
|
||||
),
|
||||
(
|
||||
"duplicate parameter",
|
||||
format!(
|
||||
r#"{{"Call":{{"definition":{{"Local":"{IDENTITY}"}},"arguments":{{"{PARAMETER}":{deep},"\u0030{}":null}}}}}}"#,
|
||||
&PARAMETER[1..]
|
||||
),
|
||||
),
|
||||
] {
|
||||
let error = candidate(&wire(&expression), Profile::DOCUMENT).unwrap_err();
|
||||
assert!(
|
||||
!error.to_string().contains("logical depth"),
|
||||
"{label}: {error}"
|
||||
);
|
||||
eprintln!("{label}: {error}");
|
||||
}
|
||||
let complete = String::from_utf8(wire(&chain(128, true))).unwrap();
|
||||
let duplicate_late = format!(
|
||||
r#"{},"name":"late duplicate"}}"#,
|
||||
&complete[..complete.len() - 1]
|
||||
);
|
||||
assert!(candidate(duplicate_late.as_bytes(), Profile::DOCUMENT).is_err());
|
||||
assert!(candidate(format!("{complete} null").as_bytes(), Profile::DOCUMENT).is_err());
|
||||
let invalid_surrogate = complete.replace(r#""description":"""#, r#""description":"\uD800""#);
|
||||
assert!(candidate(invalid_surrogate.as_bytes(), Profile::DOCUMENT).is_err());
|
||||
// Fully rejected raw depth also tears down without a recursive JSON Value.
|
||||
let excessive = format!("{}0{}", "[".repeat(100_000), "]".repeat(100_000));
|
||||
assert!(matches!(
|
||||
preflight(excessive.as_bytes(), Profile::DOCUMENT),
|
||||
Err(FileError::Limit(_))
|
||||
));
|
||||
}
|
||||
fn ownership_phase() {
|
||||
let mut value = Expr::Boolean(true);
|
||||
for _ in 1..100_000 {
|
||||
value = Expr::Unary {
|
||||
op: UnaryOp::Not,
|
||||
operand: Box::new(value),
|
||||
};
|
||||
}
|
||||
let mut copy = value.clone();
|
||||
assert!(value == copy);
|
||||
let mut cursor = &mut copy;
|
||||
loop {
|
||||
match cursor {
|
||||
Expr::Unary { operand, .. } => cursor = operand,
|
||||
Expr::Boolean(leaf) => {
|
||||
*leaf = false;
|
||||
break;
|
||||
}
|
||||
_ => unreachable!(),
|
||||
}
|
||||
}
|
||||
assert!(value != copy);
|
||||
// A streaming formatter avoids retaining a 100000-node Debug string.
|
||||
struct Counter(usize);
|
||||
impl fmt::Write for Counter {
|
||||
fn write_str(&mut self, value: &str) -> fmt::Result {
|
||||
self.0 += value.len();
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
let mut debug = Counter(0);
|
||||
write!(&mut debug, "{value:?}").unwrap();
|
||||
assert!(debug.0 > 100_000);
|
||||
assert!(serde_json::to_writer(io::sink(), &value).is_err());
|
||||
drop(value);
|
||||
drop(copy);
|
||||
eprintln!(
|
||||
"iterative manual100000 ownership/debug/drop completed; debug bytes={}",
|
||||
debug.0
|
||||
);
|
||||
}
|
||||
fn atomic_phase() {
|
||||
let model = project();
|
||||
let bytes = encode(&model, Profile::DOCUMENT, true).unwrap();
|
||||
let exact = Profile {
|
||||
bytes: bytes.len(),
|
||||
..Profile::DOCUMENT
|
||||
};
|
||||
assert_eq!(encode(&model, exact, true).unwrap(), bytes);
|
||||
let directory = tempfile::tempdir().unwrap();
|
||||
let path = directory.path().join("preserved.json");
|
||||
std::fs::write(&path, b"original").unwrap();
|
||||
let error = persistence::save_checked_profile(
|
||||
&path,
|
||||
&model,
|
||||
Some(b"original"),
|
||||
Profile {
|
||||
bytes: bytes.len() - 1,
|
||||
..Profile::DOCUMENT
|
||||
},
|
||||
true,
|
||||
)
|
||||
.unwrap_err();
|
||||
assert!(matches!(error, FileError::Limit(_)));
|
||||
assert_eq!(std::fs::read(&path).unwrap(), b"original");
|
||||
assert_eq!(std::fs::read_dir(directory.path()).unwrap().count(), 1);
|
||||
let error = persistence::save_checked_profile(
|
||||
&path,
|
||||
&model,
|
||||
Some(b"different"),
|
||||
Profile::DOCUMENT,
|
||||
true,
|
||||
)
|
||||
.unwrap_err();
|
||||
assert!(matches!(error, FileError::Conflict));
|
||||
assert_eq!(std::fs::read(&path).unwrap(), b"original");
|
||||
assert_eq!(std::fs::read_dir(directory.path()).unwrap().count(), 1);
|
||||
assert!(read_bounded(&path, 7).is_err());
|
||||
assert_eq!(read_bounded(&path, 8).unwrap(), b"original");
|
||||
let mut writer = CappedWriter::new(3);
|
||||
writer.write_all(b"abc").unwrap();
|
||||
let capacity = writer.bytes.capacity();
|
||||
assert!(writer.write_all(b"d").is_err());
|
||||
assert_eq!(writer.bytes, b"abc");
|
||||
assert_eq!(writer.bytes.capacity(), capacity);
|
||||
}
|
||||
|
||||
/// Root runs this exact test in each approved target/profile. Each phase runs in
|
||||
/// another process so a stack overflow is an explicit failed phase, and inside
|
||||
/// a 128 KiB thread (smaller than the ordinary test stack). No RUST_MIN_STACK
|
||||
/// override, ignored test, release-only path or increased test stack.
|
||||
#[test]
|
||||
fn codec_lifecycle_subprocess() {
|
||||
const PHASE: &str = "ARCADIA_CODEC_LIFECYCLE_PHASE";
|
||||
if let Ok(phase) = std::env::var(PHASE) {
|
||||
eprintln!("codec child phase={phase}, configured thread stack=131072");
|
||||
std::thread::Builder::new()
|
||||
.name(format!("codec-{phase}"))
|
||||
.stack_size(128 * 1024)
|
||||
.spawn(move || match phase.as_str() {
|
||||
"accepted" => accepted_phase(),
|
||||
"refused" => refused_phase(),
|
||||
"malformed" => malformed_phase(),
|
||||
"ownership" => ownership_phase(),
|
||||
"atomic" => atomic_phase(),
|
||||
_ => panic!("Unknown codec phase"),
|
||||
})
|
||||
.unwrap()
|
||||
.join()
|
||||
.unwrap();
|
||||
return;
|
||||
}
|
||||
for phase in ["accepted", "refused", "malformed", "ownership", "atomic"] {
|
||||
let mut child = Command::new(std::env::current_exe().unwrap())
|
||||
.args([
|
||||
"--exact",
|
||||
"persistence::json_codec::tests::codec_lifecycle_subprocess",
|
||||
"--test-threads=1",
|
||||
"--nocapture",
|
||||
])
|
||||
.env(PHASE, phase)
|
||||
.stdout(Stdio::piped())
|
||||
.stderr(Stdio::piped())
|
||||
.spawn()
|
||||
.unwrap();
|
||||
let start = Instant::now();
|
||||
loop {
|
||||
if child.try_wait().unwrap().is_some() {
|
||||
break;
|
||||
}
|
||||
if start.elapsed() > Duration::from_secs(120) {
|
||||
child.kill().unwrap();
|
||||
let output = child.wait_with_output().unwrap();
|
||||
panic!(
|
||||
"codec {phase} timed out: {}",
|
||||
String::from_utf8_lossy(&output.stderr)
|
||||
);
|
||||
}
|
||||
std::thread::sleep(Duration::from_millis(20));
|
||||
}
|
||||
let output = child.wait_with_output().unwrap();
|
||||
eprintln!(
|
||||
"codec {phase}: status={} elapsed={:?}\n{}{}",
|
||||
output.status,
|
||||
start.elapsed(),
|
||||
String::from_utf8_lossy(&output.stdout),
|
||||
String::from_utf8_lossy(&output.stderr)
|
||||
);
|
||||
assert!(
|
||||
output.status.success(),
|
||||
"codec phase {phase} aborted or failed"
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,145 @@
|
||||
//! Containment while the complete source8 adapter remains unavailable.
|
||||
use super::*;
|
||||
use crate::analysis::{Definition, DefinitionBody, QuantityAlgebra, QuantityKindDefinition};
|
||||
use crate::analysis_numeric::Dimension;
|
||||
use std::fs;
|
||||
|
||||
const ORDINARY_SOURCE7: &str = concat!(
|
||||
"arcadia 7;\n",
|
||||
"project saved \"Saved model\" id \"4210b9f2-7046-47f0-aa3b-153f626a579d\" {\n",
|
||||
" description \"Retain café and exact identity\";\n",
|
||||
"}",
|
||||
);
|
||||
|
||||
fn ordinary() -> Project {
|
||||
let decoded = decode_with_report(ORDINARY_SOURCE7.as_bytes()).unwrap();
|
||||
assert!(decoded.migration.is_some());
|
||||
decoded.project
|
||||
}
|
||||
|
||||
fn directory_entries(path: &Path) -> Vec<std::ffi::OsString> {
|
||||
let mut names = fs::read_dir(path)
|
||||
.unwrap()
|
||||
.map(|entry| entry.unwrap().file_name())
|
||||
.collect::<Vec<_>>();
|
||||
names.sort();
|
||||
names
|
||||
}
|
||||
|
||||
// A missing parent makes a mistakenly early NamedTempFile creation observable
|
||||
// as Io, even when the temp would otherwise be removed again on error.
|
||||
fn rejected_output(
|
||||
project: &Project,
|
||||
output: &[u8],
|
||||
profile: json_codec::Profile,
|
||||
check: impl Fn(&FileError),
|
||||
) {
|
||||
let root = tempfile::tempdir().unwrap();
|
||||
let existing = root.path().join("existing.arcadia");
|
||||
let sentinel = b"external bytes must survive\r\n";
|
||||
fs::write(&existing, sentinel).unwrap();
|
||||
for path in [
|
||||
existing.clone(),
|
||||
root.path().join("new.arcadia"),
|
||||
root.path().join("missing-parent/new.arcadia"),
|
||||
] {
|
||||
let before = directory_entries(root.path());
|
||||
let expected = (path == existing).then_some(sentinel.as_slice());
|
||||
let error =
|
||||
save_checked_profile_with_source(&path, project, expected, profile, false, |_| {
|
||||
output.to_vec()
|
||||
})
|
||||
.unwrap_err();
|
||||
check(&error);
|
||||
assert_eq!(directory_entries(root.path()), before);
|
||||
assert_eq!(fs::read(&existing).unwrap(), sentinel);
|
||||
if path != existing {
|
||||
assert!(!path.exists());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn malformed_generated_source_rejects_before_any_filesystem_staging() {
|
||||
rejected_output(
|
||||
&ordinary(),
|
||||
b"arcadia",
|
||||
json_codec::Profile::DOCUMENT,
|
||||
|error| assert!(matches!(error, FileError::Text(_)), "{error}"),
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parseable_source_omitting_a_definition_cannot_replace_the_whole_project() {
|
||||
let mut project = ordinary();
|
||||
let id = Id::parse_str("188b911c-5f8b-431c-9eea-2d41f3953767").unwrap();
|
||||
project.definitions.insert(
|
||||
id,
|
||||
Definition {
|
||||
id,
|
||||
alias: "duration".into(),
|
||||
name: "Duration".into(),
|
||||
description: "Unused definitions are still authored model data.".into(),
|
||||
body: DefinitionBody::QuantityKind(QuantityKindDefinition {
|
||||
dimension: Dimension::new([0, 0, 1, 0, 0, 0, 0]).unwrap(),
|
||||
algebra: QuantityAlgebra::Linear,
|
||||
}),
|
||||
},
|
||||
);
|
||||
validate_project(&project).unwrap();
|
||||
let decoded = decode(ORDINARY_SOURCE7.as_bytes()).unwrap();
|
||||
assert_eq!(decoded.id, project.id);
|
||||
assert_eq!(decoded.name, project.name);
|
||||
assert_eq!(decoded.elements, project.elements);
|
||||
assert!(decoded.definitions.is_empty());
|
||||
assert_ne!(decoded, project);
|
||||
rejected_output(
|
||||
&project,
|
||||
ORDINARY_SOURCE7.as_bytes(),
|
||||
json_codec::Profile::DOCUMENT,
|
||||
|error| {
|
||||
assert!(
|
||||
matches!(error, FileError::Invalid(message)
|
||||
if message == "Generated source does not reproduce the complete requested project."),
|
||||
"{error}"
|
||||
);
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn equal_project_from_generated_legacy_source_still_rejects_migration() {
|
||||
rejected_output(
|
||||
&ordinary(),
|
||||
ORDINARY_SOURCE7.as_bytes(),
|
||||
json_codec::Profile::DOCUMENT,
|
||||
|error| {
|
||||
assert!(
|
||||
matches!(error, FileError::Invalid(message)
|
||||
if message == "Generated source unexpectedly requires migration."),
|
||||
"{error}"
|
||||
);
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn generated_source_admission_checks_final_newline_under_the_effective_byte_limit() {
|
||||
let project = ordinary();
|
||||
let profile = json_codec::Profile::with_byte_limit(ORDINARY_SOURCE7.len());
|
||||
rejected_output(&project, ORDINARY_SOURCE7.as_bytes(), profile, |error| {
|
||||
assert!(matches!(error, FileError::Limit(_)), "{error}");
|
||||
});
|
||||
let mut terminated = ORDINARY_SOURCE7.as_bytes().to_vec();
|
||||
terminated.push(b'\n');
|
||||
let profile = json_codec::Profile::with_byte_limit(terminated.len());
|
||||
// Existing final newline is not added twice: decoding now reaches the
|
||||
// independent migration refusal, rather than exceeding this exact limit.
|
||||
rejected_output(&project, &terminated, profile, |error| {
|
||||
assert!(
|
||||
matches!(error, FileError::Invalid(message)
|
||||
if message == "Generated source unexpectedly requires migration."),
|
||||
"{error}"
|
||||
);
|
||||
});
|
||||
}
|
||||
@@ -1182,6 +1182,48 @@ pub(crate) fn validate_exchange_allocation(p: &Project, r: &Relation, out: &mut
|
||||
else {
|
||||
return;
|
||||
};
|
||||
if let RelationBody::CommunicationMean {
|
||||
source,
|
||||
target,
|
||||
oriented,
|
||||
..
|
||||
} = &boundary.body
|
||||
{
|
||||
let actual = (
|
||||
actual_performer(p, work.source()),
|
||||
actual_performer(p, work.target()),
|
||||
);
|
||||
let compatible = |a, b| {
|
||||
actual.0.is_none_or(|owner| owner == a) && actual.1.is_none_or(|owner| owner == b)
|
||||
};
|
||||
if !compatible(*source, *target) && (*oriented || !compatible(*target, *source)) {
|
||||
error(
|
||||
out,
|
||||
r.id,
|
||||
"exchange_allocation_performer",
|
||||
"endpoints",
|
||||
"Actual activity allocations must agree with one permitted communication direction; review the means or the activity allocations.",
|
||||
);
|
||||
} else if actual.0.is_none() || actual.1.is_none() {
|
||||
warning(
|
||||
out,
|
||||
r.id,
|
||||
"incomplete_exchange_allocation",
|
||||
"endpoints",
|
||||
"Add or review actual activity-to-participant Allocations; role responsibility alone does not resolve communication allocation.",
|
||||
);
|
||||
}
|
||||
if !items_satisfy(p, work.body.items(), boundary.body.items()) {
|
||||
error(
|
||||
out,
|
||||
r.id,
|
||||
"exchange_allocation_items",
|
||||
"items",
|
||||
"Communication means must declare every allocated interaction item; review the carried item contract explicitly.",
|
||||
);
|
||||
}
|
||||
return;
|
||||
}
|
||||
let RelationBody::BoundaryExchange {
|
||||
source: a,
|
||||
target: b,
|
||||
@@ -1219,7 +1261,11 @@ pub(crate) fn validate_exchange_allocation(p: &Project, r: &Relation, out: &mut
|
||||
r.id,
|
||||
"legacy_exchange_allocation",
|
||||
"endpoints",
|
||||
"Resolve legacy ports and explicitly allocate the corresponding typed ports.",
|
||||
if p.layer_of(boundary.id) == Some(Layer::Oa) {
|
||||
"This preserved OA boundary uses legacy ports; review its communication representation without inventing SA port contracts."
|
||||
} else {
|
||||
"Resolve legacy ports and explicitly allocate the corresponding typed ports."
|
||||
},
|
||||
);
|
||||
for (function, port) in [(work.source(), *a), (work.target(), *b)] {
|
||||
match (actual_performer(p, function), owner(port)) {
|
||||
|
||||
@@ -226,8 +226,58 @@ pub fn project_view(p: &Project, diagram: Id) -> ProjectedView {
|
||||
};
|
||||
project_diagram(p, d)
|
||||
}
|
||||
/// Reuse an index built for this accepted semantic revision during presentation
|
||||
/// previews. Callers must invalidate it when semantic records change.
|
||||
pub fn project_view_with_index(
|
||||
p: &Project,
|
||||
diagram: Id,
|
||||
index: &crate::view_options::ViewIndex,
|
||||
) -> ProjectedView {
|
||||
p.diagrams
|
||||
.get(&diagram)
|
||||
.map_or_else(ProjectedView::default, |d| {
|
||||
project_diagram_with_index(p, d, index)
|
||||
})
|
||||
}
|
||||
/// Project alternate placement geometry without copying or mutating semantics.
|
||||
pub fn project_diagram(p: &Project, d: &Diagram) -> ProjectedView {
|
||||
let index = crate::view_options::ViewIndex::new(p);
|
||||
project_diagram_with_index(p, d, &index)
|
||||
}
|
||||
pub fn project_diagram_with_index(
|
||||
p: &Project,
|
||||
d: &Diagram,
|
||||
index: &crate::view_options::ViewIndex,
|
||||
) -> ProjectedView {
|
||||
project_diagram_impl(p, d, None, Some(index))
|
||||
}
|
||||
/// Unfiltered eligibility from the same projection/anchor/fold decisions used
|
||||
/// for drawing. Compute once for a view-options editor, then combine with the
|
||||
/// prepared filter's reasons; hidden lines remain geometrically eligible here.
|
||||
pub fn edge_availability(
|
||||
p: &Project,
|
||||
d: &Diagram,
|
||||
) -> BTreeMap<Id, crate::view_options::EdgeAvailability> {
|
||||
let mut availability = p
|
||||
.relations
|
||||
.keys()
|
||||
.chain(p.traces.keys())
|
||||
.map(|id| {
|
||||
(
|
||||
*id,
|
||||
crate::view_options::EdgeAvailability::OutsideProjection,
|
||||
)
|
||||
})
|
||||
.collect();
|
||||
project_diagram_impl(p, d, Some(&mut availability), None);
|
||||
availability
|
||||
}
|
||||
fn project_diagram_impl(
|
||||
p: &Project,
|
||||
d: &Diagram,
|
||||
mut availability: Option<&mut BTreeMap<Id, crate::view_options::EdgeAvailability>>,
|
||||
index: Option<&crate::view_options::ViewIndex>,
|
||||
) -> ProjectedView {
|
||||
let parents = parents(p, d);
|
||||
let mut nodes = Vec::new();
|
||||
for n in d.nodes.values() {
|
||||
@@ -354,6 +404,7 @@ pub fn project_diagram(p: &Project, d: &Diagram) -> ProjectedView {
|
||||
RelationKind::Interaction
|
||||
| RelationKind::FunctionalExchange
|
||||
| RelationKind::BoundaryExchange
|
||||
| RelationKind::CommunicationMean
|
||||
),
|
||||
ProjectionKind::FunctionalDataflow => matches!(
|
||||
r.kind(),
|
||||
@@ -367,20 +418,36 @@ pub fn project_diagram(p: &Project, d: &Diagram) -> ProjectedView {
|
||||
| RelationKind::MissionCapability
|
||||
| RelationKind::MissionInvolvement
|
||||
| RelationKind::CapabilityInvolvement
|
||||
| RelationKind::CommunicationMean
|
||||
),
|
||||
_ => true,
|
||||
};
|
||||
if !included {
|
||||
continue;
|
||||
}
|
||||
if let (Some(source), Some(target)) = (anchor(r.source()), anchor(r.target()))
|
||||
&& (source != target
|
||||
|| ((d.projection.state_machine().is_some()
|
||||
|| r.kind() == RelationKind::DataAssociation)
|
||||
&& r.source() == r.target()
|
||||
&& nodes
|
||||
.iter()
|
||||
.any(|n| n.id == source && n.element == r.source())))
|
||||
let ends = (anchor(r.source()), anchor(r.target()));
|
||||
let self_loop = (d.projection.state_machine().is_some()
|
||||
|| r.kind() == RelationKind::DataAssociation)
|
||||
&& r.source() == r.target()
|
||||
&& nodes
|
||||
.iter()
|
||||
.any(|n| Some(n.id) == ends.0 && n.element == r.source());
|
||||
if let Some(availability) = availability.as_deref_mut() {
|
||||
use crate::view_options::EdgeAvailability as A;
|
||||
availability.insert(
|
||||
r.id,
|
||||
match ends {
|
||||
(Some(a), Some(b)) if a != b || self_loop => A::Visible,
|
||||
(Some(_), Some(_)) => A::FoldedInternal,
|
||||
(a, b) => A::EndpointNotShown {
|
||||
source: a.is_none(),
|
||||
target: b.is_none(),
|
||||
},
|
||||
},
|
||||
);
|
||||
}
|
||||
if let (Some(source), Some(target)) = ends
|
||||
&& (source != target || self_loop)
|
||||
{
|
||||
let (source_port, target_port) = match &r.body {
|
||||
RelationBody::FunctionalExchange {
|
||||
@@ -402,6 +469,9 @@ pub fn project_diagram(p: &Project, d: &Diagram) -> ProjectedView {
|
||||
RelationBody::BoundaryExchange {
|
||||
oriented: false,
|
||||
..
|
||||
} | RelationBody::CommunicationMean {
|
||||
oriented: false,
|
||||
..
|
||||
} | RelationBody::DataAssociation { .. }
|
||||
),
|
||||
source_port: source_port.filter(|id| visible_ports.contains(id)),
|
||||
@@ -411,7 +481,22 @@ pub fn project_diagram(p: &Project, d: &Diagram) -> ProjectedView {
|
||||
}
|
||||
if d.projection == ProjectionKind::Traceability {
|
||||
for t in p.traces.values() {
|
||||
if let (Some(source), Some(target)) = (anchor(t.oa), anchor(t.sa))
|
||||
let ends = (anchor(t.oa), anchor(t.sa));
|
||||
if let Some(availability) = availability.as_deref_mut() {
|
||||
use crate::view_options::EdgeAvailability as A;
|
||||
availability.insert(
|
||||
t.id,
|
||||
match ends {
|
||||
(Some(a), Some(b)) if a != b => A::Visible,
|
||||
(Some(_), Some(_)) => A::FoldedInternal,
|
||||
(a, b) => A::EndpointNotShown {
|
||||
source: a.is_none(),
|
||||
target: b.is_none(),
|
||||
},
|
||||
},
|
||||
);
|
||||
}
|
||||
if let (Some(source), Some(target)) = ends
|
||||
&& source != target
|
||||
{
|
||||
edges.push(ProjectedEdge {
|
||||
@@ -433,6 +518,16 @@ pub fn project_diagram(p: &Project, d: &Diagram) -> ProjectedView {
|
||||
} else {
|
||||
port_layout::layout(p, d, &mut nodes, &edges)
|
||||
};
|
||||
// Port geometry uses every eligible edge. Presentation filters must never
|
||||
// move visible ports when another line is hidden or a category is selected.
|
||||
if let Some(index) = index {
|
||||
let filter = if d.projection == ProjectionKind::Traceability {
|
||||
index.prepare_cross_layer(d.layer, &d.view_options)
|
||||
} else {
|
||||
index.prepare(d.layer, &d.view_options)
|
||||
};
|
||||
edges.retain(|edge| filter.includes(edge.id));
|
||||
}
|
||||
ProjectedView {
|
||||
nodes,
|
||||
edges,
|
||||
|
||||
@@ -53,7 +53,12 @@ pub fn state_header_height(p: &Project, element: Id) -> f32 {
|
||||
if *source == element)
|
||||
})
|
||||
.count();
|
||||
64. + if actions { 28. } else { 0. } + internal as f32 * 56.
|
||||
let typed_actions = p
|
||||
.relations
|
||||
.values()
|
||||
.filter(|r| r.kind() == RelationKind::StateAction && r.source() == element)
|
||||
.count();
|
||||
64. + if actions { 28. } else { 0. } + typed_actions as f32 * 28. + internal as f32 * 56.
|
||||
}
|
||||
|
||||
pub(crate) fn node_size(p: &Project, e: &Element, size: Size, collapsed: bool) -> Size {
|
||||
|
||||
@@ -1,8 +1,14 @@
|
||||
use crate::*;
|
||||
use std::collections::BTreeSet;
|
||||
|
||||
/// Every live reference in a typed element, including structural ownership.
|
||||
/// Architectural/project references, including analysis subjects/properties.
|
||||
/// Layer-neutral definition references and scoped parameters have separate domains.
|
||||
pub fn element_references(e: &Element) -> Vec<Id> {
|
||||
if e.kind().is_analysis() {
|
||||
let mut references: Vec<_> = crate::analysis::references::element_model_references(e).into_iter().collect();
|
||||
references.extend(e.parent);
|
||||
return references;
|
||||
}
|
||||
let mut copy = e.clone();
|
||||
let mut refs = Vec::new();
|
||||
visit_element_refs(&mut copy, |id| refs.push(*id));
|
||||
@@ -14,6 +20,8 @@ pub fn relation_references(r: &Relation) -> Vec<Id> {
|
||||
visit_relation_refs(&mut copy, |id| refs.push(*id));
|
||||
refs
|
||||
}
|
||||
/// Architectural mutable slots only. Analysis map keys require the fallible
|
||||
/// whole-project remap; use analysis::references for its typed domains.
|
||||
pub fn visit_element_refs(e: &mut Element, mut visit: impl FnMut(&mut Id)) {
|
||||
if let Some(parent) = &mut e.parent {
|
||||
visit(parent);
|
||||
@@ -29,6 +37,11 @@ pub fn visit_element_refs(e: &mut Element, mut visit: impl FnMut(&mut Id)) {
|
||||
}
|
||||
if let Some(shared) = e.shared_mut() {
|
||||
match shared {
|
||||
SharedBody::ExchangeCategory { exchanges, .. } => {
|
||||
for id in exchanges {
|
||||
visit(id);
|
||||
}
|
||||
}
|
||||
SharedBody::DataField {
|
||||
type_ref: TypeRef::Named(id),
|
||||
..
|
||||
@@ -82,8 +95,15 @@ pub fn visit_element_refs(e: &mut Element, mut visit: impl FnMut(&mut Id)) {
|
||||
receiver,
|
||||
reply_to,
|
||||
values,
|
||||
operation,
|
||||
..
|
||||
} => {
|
||||
if let Some(id) = operation
|
||||
.as_mut()
|
||||
.and_then(|operation| operation.allocation.as_mut())
|
||||
{
|
||||
visit(id);
|
||||
}
|
||||
for id in [exchange, sender, receiver, reply_to].into_iter().flatten() {
|
||||
visit(id);
|
||||
}
|
||||
@@ -145,6 +165,22 @@ pub fn visit_relation_refs(r: &mut Relation, mut visit: impl FnMut(&mut Id)) {
|
||||
visit(&mut target);
|
||||
r.body.set_endpoints(source, target);
|
||||
match &mut r.body {
|
||||
RelationBody::ContextualLink {
|
||||
owner,
|
||||
source,
|
||||
target,
|
||||
purpose,
|
||||
} => {
|
||||
visit(owner);
|
||||
for id in source.references.iter_mut().chain(&mut target.references) {
|
||||
visit(id);
|
||||
}
|
||||
match purpose {
|
||||
ContextualLinkPurpose::Exchange { exchange } => visit(exchange),
|
||||
ContextualLinkPurpose::CommonWork { work } => visit(work),
|
||||
ContextualLinkPurpose::Precedence { .. } => {}
|
||||
}
|
||||
}
|
||||
RelationBody::StateTransition {
|
||||
triggers, effects, ..
|
||||
} => {
|
||||
@@ -152,7 +188,9 @@ pub fn visit_relation_refs(r: &mut Relation, mut visit: impl FnMut(&mut Id)) {
|
||||
visit(id);
|
||||
}
|
||||
}
|
||||
RelationBody::Interaction { items, .. } | RelationBody::BoundaryExchange { items, .. } => {
|
||||
RelationBody::Interaction { items, .. }
|
||||
| RelationBody::BoundaryExchange { items, .. }
|
||||
| RelationBody::CommunicationMean { items, .. } => {
|
||||
for id in items {
|
||||
visit(id);
|
||||
}
|
||||
@@ -173,7 +211,10 @@ pub fn visit_relation_refs(r: &mut Relation, mut visit: impl FnMut(&mut Id)) {
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
pub fn remap_references(p: &mut Project, old: Id, new: Id) {
|
||||
pub fn remap_references(p: &mut Project, old: Id, new: Id) -> Result<(), ModelError> {
|
||||
crate::analysis::references::check_remap(p, old, new)
|
||||
.map_err(|error| ModelError(error.to_string()))?;
|
||||
crate::analysis::references::remap_project(p, old, new);
|
||||
for e in p.elements.values_mut() {
|
||||
visit_element_refs(e, |id| {
|
||||
if *id == old {
|
||||
@@ -189,6 +230,11 @@ pub fn remap_references(p: &mut Project, old: Id, new: Id) {
|
||||
});
|
||||
}
|
||||
for d in p.diagrams.values_mut() {
|
||||
d.view_options.visit_references(|id| {
|
||||
if *id == old {
|
||||
*id = new;
|
||||
}
|
||||
});
|
||||
if let ProjectionKind::StateMachine { machine } = &mut d.projection
|
||||
&& *machine == old
|
||||
{
|
||||
@@ -230,6 +276,7 @@ pub fn remap_references(p: &mut Project, old: Id, new: Id) {
|
||||
});
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
/// IDs removed by a cascade. Cross-layer traced counterparts are never included.
|
||||
pub fn deletion_impact(p: &Project, id: Id) -> BTreeSet<Id> {
|
||||
@@ -262,6 +309,8 @@ fn deletion_impact_inner(p: &Project, id: Id, defer_exchange_allocations: bool)
|
||||
});
|
||||
if removed.contains(&r.source())
|
||||
|| removed.contains(&r.target())
|
||||
|| (r.kind() == RelationKind::ContextualLink
|
||||
&& relation_references(r).iter().any(|id| removed.contains(id)))
|
||||
|| port_removed
|
||||
|| work_allocation_removed
|
||||
{
|
||||
@@ -368,12 +417,16 @@ fn remove_objects(p: &mut Project, removed: BTreeSet<Id>) {
|
||||
.iter()
|
||||
.map(|id| (*id, p.named(*id).to_string()))
|
||||
.collect();
|
||||
// Analysis dependencies remain live: deleting their target rejects the
|
||||
// transaction unless that transaction also explicitly repairs/removes them.
|
||||
p.definitions.retain(|id, _| !removed.contains(id));
|
||||
p.elements.retain(|id, _| !removed.contains(id));
|
||||
p.relations.retain(|id, _| !removed.contains(id));
|
||||
p.diagrams.retain(|id, _| !removed.contains(id));
|
||||
p.traces.retain(|id, _| !removed.contains(id));
|
||||
p.artifact_links.retain(|id, _| !removed.contains(id));
|
||||
for d in p.diagrams.values_mut() {
|
||||
d.view_options.retain_references(|id| !removed.contains(id));
|
||||
d.nodes.retain(|id, _| !removed.contains(id));
|
||||
d.routes.retain(|route| !removed.contains(&route.edge));
|
||||
for node in d.nodes.values_mut() {
|
||||
@@ -417,7 +470,11 @@ fn remove_objects(p: &mut Project, removed: BTreeSet<Id>) {
|
||||
}
|
||||
SharedBody::Scenario { context, .. } => clear(context),
|
||||
SharedBody::Lifeline { represented } => clear(represented),
|
||||
SharedBody::Constraint { constrained, .. } => {
|
||||
SharedBody::ExchangeCategory {
|
||||
exchanges: constrained,
|
||||
..
|
||||
}
|
||||
| SharedBody::Constraint { constrained, .. } => {
|
||||
constrained.retain(|id| !removed.contains(id))
|
||||
}
|
||||
SharedBody::Occurrence { body, .. } => match body {
|
||||
@@ -427,8 +484,12 @@ fn remove_objects(p: &mut Project, removed: BTreeSet<Id>) {
|
||||
receiver,
|
||||
reply_to,
|
||||
values,
|
||||
operation,
|
||||
..
|
||||
} => {
|
||||
if let Some(operation) = operation {
|
||||
clear(&mut operation.allocation);
|
||||
}
|
||||
clear(exchange);
|
||||
clear(sender);
|
||||
clear(receiver);
|
||||
@@ -487,7 +548,8 @@ fn remove_objects(p: &mut Project, removed: BTreeSet<Id>) {
|
||||
}
|
||||
}
|
||||
RelationBody::Interaction { items, .. }
|
||||
| RelationBody::BoundaryExchange { items, .. } => {
|
||||
| RelationBody::BoundaryExchange { items, .. }
|
||||
| RelationBody::CommunicationMean { items, .. } => {
|
||||
items.retain(|id| !removed.contains(id))
|
||||
}
|
||||
RelationBody::FunctionalExchange { items, .. } => {
|
||||
|
||||
@@ -607,6 +607,7 @@ fn route_diagram_impl(
|
||||
.flatten();
|
||||
routed.label = make_label(
|
||||
project,
|
||||
diagram.view_options.exchange_labels,
|
||||
edge.id,
|
||||
&routed.points,
|
||||
authored_label,
|
||||
@@ -1232,6 +1233,7 @@ fn label_text(project: &Project, edge: Id) -> String {
|
||||
RelationKind::Interaction
|
||||
| RelationKind::FunctionalExchange
|
||||
| RelationKind::BoundaryExchange
|
||||
| RelationKind::CommunicationMean
|
||||
| RelationKind::DataAssociation => relation.name.as_str(),
|
||||
RelationKind::CapabilityInclude => "«include»",
|
||||
RelationKind::CapabilityExtend => "«extend»",
|
||||
@@ -1262,8 +1264,11 @@ fn empty_label() -> EdgeLabelGeometry {
|
||||
}
|
||||
}
|
||||
|
||||
// Keep semantic label inputs and the independent collision sets explicit.
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
fn make_label(
|
||||
project: &Project,
|
||||
labels: crate::view_options::ExchangeLabels,
|
||||
edge: Id,
|
||||
points: &[Position],
|
||||
authored: Option<&crate::EdgeLabel>,
|
||||
@@ -1271,7 +1276,21 @@ fn make_label(
|
||||
previous_labels: &[RoutingBounds],
|
||||
strokes: &[Segment],
|
||||
) -> EdgeLabelGeometry {
|
||||
let text = label_text(project, edge);
|
||||
let text = if labels != crate::view_options::ExchangeLabels::Name
|
||||
&& project
|
||||
.relations
|
||||
.get(&edge)
|
||||
.is_some_and(|r| crate::view_options::exchange_family(r.kind()).is_some())
|
||||
{
|
||||
let label = labels.label(project, edge);
|
||||
if label.chars().count() > 48 {
|
||||
label.chars().take(47).chain(std::iter::once('…')).collect()
|
||||
} else {
|
||||
label
|
||||
}
|
||||
} else {
|
||||
label_text(project, edge)
|
||||
};
|
||||
let size = Size {
|
||||
width: if text.is_empty() {
|
||||
0.0
|
||||
|
||||
@@ -81,6 +81,35 @@ impl Own {
|
||||
}
|
||||
let kind = enum_tag(value)?.to_string();
|
||||
prefix.push(kind.clone());
|
||||
let mut whole = whole;
|
||||
if let Some(SharedBody::Occurrence {
|
||||
body:
|
||||
OccurrenceBody::Exchange {
|
||||
message_kind: MessageKind::Call | MessageKind::Asynchronous,
|
||||
..
|
||||
},
|
||||
..
|
||||
}) = project.elements.get(&id).and_then(Element::shared)
|
||||
&& project.layer_of(id) == Some(Layer::Sa)
|
||||
&& crate::validation::ancestor_of_kind(project, id, Kind::Scenario)
|
||||
.and_then(|id| project.elements.get(&id))
|
||||
.and_then(Element::shared)
|
||||
.is_some_and(|body| {
|
||||
matches!(
|
||||
body,
|
||||
SharedBody::Scenario {
|
||||
viewpoint: ScenarioViewpoint::BoundaryInterface,
|
||||
..
|
||||
}
|
||||
)
|
||||
})
|
||||
{
|
||||
let mut operation_path = prefix.clone();
|
||||
operation_path.extend(["body".into(), "Exchange".into()]);
|
||||
if let Some(body) = at_mut(&mut whole, &operation_path).and_then(Value::as_object_mut) {
|
||||
body.entry("operation").or_insert(Value::Null);
|
||||
}
|
||||
}
|
||||
Some(Self {
|
||||
whole,
|
||||
prefix,
|
||||
@@ -163,6 +192,9 @@ fn path(own: &Own, facet: &FacetSelector) -> Option<Vec<String>> {
|
||||
F::Occurrence(OccurrenceFacet::ReplyTo) => {
|
||||
("Occurrence", &["body", "Exchange", "reply_to"])
|
||||
}
|
||||
F::Occurrence(OccurrenceFacet::Operation) => {
|
||||
("Occurrence", &["body", "Exchange", "operation"])
|
||||
}
|
||||
F::Occurrence(OccurrenceFacet::Action) => ("Occurrence", &["body", "Action", "action"]),
|
||||
F::Occurrence(OccurrenceFacet::ActionLifeline) => {
|
||||
("Occurrence", &["body", "Action", "lifeline"])
|
||||
@@ -191,8 +223,13 @@ fn path(own: &Own, facet: &FacetSelector) -> Option<Vec<String>> {
|
||||
F::State(StateFacet::Exit) => ("State", &["exit"]),
|
||||
F::State(StateFacet::DoActivity) => ("State", &["do_activity"]),
|
||||
F::Constraint(ConstraintFacet::Expression) => ("Constraint", &["expression"]),
|
||||
F::Relation(RelationFacet::Source) => ("*", &["source"]),
|
||||
F::Relation(RelationFacet::Target) => ("*", &["target"]),
|
||||
F::Category(CategoryFacet::Family) => ("ExchangeCategory", &["family"]),
|
||||
F::Relation(RelationFacet::Source) if own.kind != "ContextualLink" => ("*", &["source"]),
|
||||
F::Relation(RelationFacet::Target) if own.kind != "ContextualLink" => ("*", &["target"]),
|
||||
F::Relation(RelationFacet::ContextOwner) => ("ContextualLink", &["owner"]),
|
||||
F::Relation(RelationFacet::ContextSource) => ("ContextualLink", &["source"]),
|
||||
F::Relation(RelationFacet::ContextTarget) => ("ContextualLink", &["target"]),
|
||||
F::Relation(RelationFacet::ContextPurpose) => ("ContextualLink", &["purpose"]),
|
||||
F::Relation(RelationFacet::AllocationOrder) => ("InterfaceItemAllocation", &["order"]),
|
||||
F::Relation(RelationFacet::Transmission) => ("InterfaceItemAllocation", &["transmission"]),
|
||||
F::Relation(RelationFacet::Acquisition) => ("InterfaceItemAllocation", &["acquisition"]),
|
||||
@@ -206,7 +243,7 @@ fn path(own: &Own, facet: &FacetSelector) -> Option<Vec<String>> {
|
||||
F::Relation(RelationFacet::TargetNavigable) => ("DataAssociation", &["target_navigable"]),
|
||||
F::Relation(RelationFacet::SourcePort) => ("FunctionalExchange", &["source_port"]),
|
||||
F::Relation(RelationFacet::TargetPort) => ("FunctionalExchange", &["target_port"]),
|
||||
F::Relation(RelationFacet::Oriented) => ("BoundaryExchange", &["oriented"]),
|
||||
F::Relation(RelationFacet::Oriented) => ("*", &["oriented"]),
|
||||
F::Relation(RelationFacet::ExtendCondition) => ("CapabilityExtend", &["condition"]),
|
||||
F::Relation(RelationFacet::SequenceGuard) => ("SequenceLink", &["guard"]),
|
||||
F::Relation(RelationFacet::TransitionKind) => ("StateTransition", &["transition_kind"]),
|
||||
@@ -311,7 +348,8 @@ pub(crate) fn collection(project: &Project, id: Id, which: ReferenceCollection)
|
||||
Some(
|
||||
RelationBody::Interaction { items, .. }
|
||||
| RelationBody::FunctionalExchange { items, .. }
|
||||
| RelationBody::BoundaryExchange { items, .. },
|
||||
| RelationBody::BoundaryExchange { items, .. }
|
||||
| RelationBody::CommunicationMean { items, .. },
|
||||
) => Some(items.clone()),
|
||||
_ => None,
|
||||
},
|
||||
@@ -327,6 +365,10 @@ pub(crate) fn collection(project: &Project, id: Id, which: ReferenceCollection)
|
||||
Some(SharedBody::Constraint { constrained, .. }) => Some(constrained.clone()),
|
||||
_ => None,
|
||||
},
|
||||
C::CategoryExchanges => match shared {
|
||||
Some(SharedBody::ExchangeCategory { exchanges, .. }) => Some(exchanges.clone()),
|
||||
_ => None,
|
||||
},
|
||||
}
|
||||
}
|
||||
pub(crate) fn order_collection(which: OrderedCollection) -> ReferenceCollection {
|
||||
@@ -562,6 +604,9 @@ fn catalog_facets(
|
||||
include_linked: bool,
|
||||
) -> Result<Vec<FacetDrift>, String> {
|
||||
let (oa, sa) = (trace.oa, trace.sa);
|
||||
if [oa, sa].iter().any(|id| project.elements.get(id).is_some_and(|element| element.kind().is_analysis())) {
|
||||
return Err("Semantic review of analysis records is not implemented; header-only review is refused.".into());
|
||||
}
|
||||
let mut selectors: BTreeSet<_> = scalar_selectors()
|
||||
.into_iter()
|
||||
.filter(|s| {
|
||||
@@ -575,6 +620,7 @@ fn catalog_facets(
|
||||
ReferenceCollection::FunctionOutputItems,
|
||||
ReferenceCollection::SignalItems,
|
||||
ReferenceCollection::ExchangeItems,
|
||||
ReferenceCollection::CategoryExchanges,
|
||||
ReferenceCollection::TransitionTriggers,
|
||||
ReferenceCollection::TransitionEffects,
|
||||
ReferenceCollection::Constrained,
|
||||
@@ -919,6 +965,7 @@ mod coverage {
|
||||
] {
|
||||
add(SharedBody::Occurrence {
|
||||
body: OccurrenceBody::Exchange {
|
||||
operation: None,
|
||||
exchange: Some(id),
|
||||
sender: Some(id),
|
||||
receiver: Some(id),
|
||||
@@ -1036,6 +1083,11 @@ mod coverage {
|
||||
p
|
||||
};
|
||||
for (kind, parts, which) in [
|
||||
(
|
||||
"ExchangeCategory",
|
||||
vec!["exchanges"],
|
||||
ReferenceCollection::CategoryExchanges,
|
||||
),
|
||||
("Process", vec!["steps"], ReferenceCollection::Steps),
|
||||
("FunctionalChain", vec!["steps"], ReferenceCollection::Steps),
|
||||
("Scenario", vec!["steps"], ReferenceCollection::Steps),
|
||||
@@ -1079,6 +1131,11 @@ mod coverage {
|
||||
vec!["items"],
|
||||
ReferenceCollection::ExchangeItems,
|
||||
),
|
||||
(
|
||||
"CommunicationMean",
|
||||
vec!["items"],
|
||||
ReferenceCollection::ExchangeItems,
|
||||
),
|
||||
(
|
||||
"StateTransition",
|
||||
vec!["triggers"],
|
||||
|
||||
@@ -73,6 +73,7 @@ macro_rules! enums {
|
||||
} )* };
|
||||
}
|
||||
enums!(
|
||||
crate::view_options::ExchangeFamily,
|
||||
ExchangeItemKind,
|
||||
ExchangeMechanism,
|
||||
ParameterDirection,
|
||||
@@ -170,6 +171,31 @@ impl Historical for LifelineBinding {
|
||||
w.at("local", |w| self.local.walk(w));
|
||||
}
|
||||
}
|
||||
impl Historical for OperationUse {
|
||||
fn walk(&mut self, w: &mut Walk<'_>) {
|
||||
w.at("allocation", |w| self.allocation.walk(w));
|
||||
}
|
||||
}
|
||||
impl Historical for OccurrenceEndpoint {
|
||||
fn walk(&mut self, w: &mut Walk<'_>) {
|
||||
if self.references.len() > crate::topology_context::MAX_REFERENCE_DEPTH {
|
||||
w.error("historical contextual path depth exceeded");
|
||||
}
|
||||
w.at("references", |w| self.references.walk(w));
|
||||
w.at("occurrence", |w| self.occurrence.walk(w));
|
||||
}
|
||||
}
|
||||
impl Historical for ContextualLinkPurpose {
|
||||
fn walk(&mut self, w: &mut Walk<'_>) {
|
||||
match self {
|
||||
Self::Precedence { guard } => w.at("Precedence", |w| w.at("guard", |w| guard.walk(w))),
|
||||
Self::Exchange { exchange } => {
|
||||
w.at("Exchange", |w| w.at("exchange", |w| exchange.walk(w)))
|
||||
}
|
||||
Self::CommonWork { work } => w.at("CommonWork", |w| w.at("work", |w| work.walk(w))),
|
||||
}
|
||||
}
|
||||
}
|
||||
impl Historical for DataValue {
|
||||
fn walk(&mut self, w: &mut Walk<'_>) {
|
||||
match self {
|
||||
|
||||
@@ -63,7 +63,8 @@ pub(crate) fn set_collection(
|
||||
Some(
|
||||
RelationBody::Interaction { items, .. }
|
||||
| RelationBody::FunctionalExchange { items, .. }
|
||||
| RelationBody::BoundaryExchange { items, .. },
|
||||
| RelationBody::BoundaryExchange { items, .. }
|
||||
| RelationBody::CommunicationMean { items, .. },
|
||||
) => Some(items),
|
||||
_ => None,
|
||||
},
|
||||
@@ -79,6 +80,10 @@ pub(crate) fn set_collection(
|
||||
Some(SharedBody::Constraint { constrained, .. }) => Some(constrained),
|
||||
_ => None,
|
||||
},
|
||||
C::CategoryExchanges => match p.elements.get_mut(&id).and_then(Element::shared_mut) {
|
||||
Some(SharedBody::ExchangeCategory { exchanges, .. }) => Some(exchanges),
|
||||
_ => None,
|
||||
},
|
||||
}
|
||||
.ok_or("Collection is inapplicable on target")?;
|
||||
*slot = list;
|
||||
@@ -350,10 +355,7 @@ pub(crate) fn write_fact(
|
||||
else {
|
||||
return Err("Target has no message annotations".into());
|
||||
};
|
||||
values.retain(|v| AnnotationKey::from(v) != *key);
|
||||
if let Some(row) = row {
|
||||
values.push(row);
|
||||
}
|
||||
replace_keyed_row(values, row, |v| AnnotationKey::from(v) == *key);
|
||||
Ok(())
|
||||
}
|
||||
FacetReview::Binding { keys, review } => {
|
||||
@@ -374,10 +376,7 @@ pub(crate) fn write_fact(
|
||||
else {
|
||||
return Err("Target has no scenario bindings".into());
|
||||
};
|
||||
bindings.retain(|v| v.referenced != key);
|
||||
if let Some(row) = row {
|
||||
bindings.push(row);
|
||||
}
|
||||
replace_keyed_row(bindings, row, |v| v.referenced == key);
|
||||
Ok(())
|
||||
}
|
||||
FacetReview::Child { keys, review } => {
|
||||
@@ -467,6 +466,27 @@ pub(crate) fn write_fact(
|
||||
}
|
||||
}
|
||||
|
||||
// Reviewing an unordered row does not authorize changing its authored position.
|
||||
// Preserve surviving entries in place; only genuinely new rows append.
|
||||
fn replace_keyed_row<T: PartialEq>(
|
||||
rows: &mut Vec<T>,
|
||||
row: Option<T>,
|
||||
matches: impl FnMut(&T) -> bool,
|
||||
) {
|
||||
match (rows.iter().position(matches), row) {
|
||||
(Some(index), Some(row)) => {
|
||||
if rows[index] != row {
|
||||
rows[index] = row;
|
||||
}
|
||||
}
|
||||
(Some(index), None) => {
|
||||
rows.remove(index);
|
||||
}
|
||||
(None, Some(row)) => rows.push(row),
|
||||
(None, None) => {}
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn constructor_contains(group: &FacetSelector, facet: &FacetSelector) -> bool {
|
||||
use FacetSelector as F;
|
||||
match group {
|
||||
@@ -498,7 +518,11 @@ pub(crate) fn constructor_contains(group: &FacetSelector, facet: &FacetSelector)
|
||||
}
|
||||
F::Occurrence(OccurrenceFacet::MessageKind) => matches!(
|
||||
facet,
|
||||
F::Occurrence(OccurrenceFacet::MessageKind | OccurrenceFacet::TimerExpression)
|
||||
F::Occurrence(
|
||||
OccurrenceFacet::MessageKind
|
||||
| OccurrenceFacet::TimerExpression
|
||||
| OccurrenceFacet::Operation
|
||||
)
|
||||
),
|
||||
F::Event(EventFacet::Constructor) => matches!(
|
||||
facet,
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
use super::catalog::{capture_observation, collection, is_constructor, replace_observation, sides};
|
||||
use super::historical::keyed_slots_overlap;
|
||||
use super::historical::{keyed_slots_overlap, selector_slots};
|
||||
use super::mutate::*;
|
||||
use super::*;
|
||||
use crate::model::*;
|
||||
@@ -297,16 +297,22 @@ fn apply_canonical_slot(
|
||||
let fact = replace_observation(fact, Layer::Sa, desired.clone())?;
|
||||
write_fact(project, owner, &fact, Layer::Sa, Layer::Sa, false)
|
||||
}
|
||||
fn target_only(selector: &FacetSelector, source: Layer, target: Layer) -> bool {
|
||||
match selector {
|
||||
FacetSelector::Member { keys, .. } | FacetSelector::Binding(keys) => {
|
||||
chosen(keys, source).is_none() && chosen(keys, target).is_some()
|
||||
fn member_present(fact: &FacetReview, layer: Layer) -> bool {
|
||||
fn observed<T>(review: &Reviewed<T>, layer: Layer) -> &Observed<T> {
|
||||
match layer {
|
||||
Layer::Oa => &review.oa,
|
||||
Layer::Sa => &review.sa,
|
||||
}
|
||||
FacetSelector::Literal(keys) => {
|
||||
chosen(keys, source).is_none() && chosen(keys, target).is_some()
|
||||
}
|
||||
match fact {
|
||||
FacetReview::Member { review, .. } | FacetReview::Literal { review, .. } => {
|
||||
matches!(observed(review, layer), Observed::Value(true))
|
||||
}
|
||||
FacetSelector::Annotation(keys) => {
|
||||
chosen(keys, source).is_none() && chosen(keys, target).is_some()
|
||||
FacetReview::Annotation { review, .. } => {
|
||||
matches!(observed(review, layer), Observed::Value(Some(_)))
|
||||
}
|
||||
FacetReview::Binding { review, .. } => {
|
||||
matches!(observed(review, layer), Observed::Value(Some(_)))
|
||||
}
|
||||
_ => false,
|
||||
}
|
||||
@@ -320,15 +326,19 @@ fn preserve_constructor_members(
|
||||
source_layer: Layer,
|
||||
target_layer: Layer,
|
||||
) -> Result<(), String> {
|
||||
// A correspondence key can exist without membership on that side (for
|
||||
// example an OA literal automatically projects the same SA literal key).
|
||||
// Preserve actual target-only values, except previously reviewed removals.
|
||||
for fact in initial_facts {
|
||||
if !constructor_contains(group, &fact.selector)
|
||||
|| !target_only(&fact.selector, source_layer, target_layer)
|
||||
|| member_present(&fact.current, source_layer)
|
||||
|| !member_present(&fact.current, target_layer)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
let slot = target_slot(target, &fact.selector, target_layer)?;
|
||||
let was_corresponding = baseline.facets.iter().any(|old| {
|
||||
!target_only(&old.selector(), source_layer, target_layer)
|
||||
member_present(old, source_layer)
|
||||
&& target_slot(target, &old.selector(), target_layer).ok() == Some(slot.clone())
|
||||
});
|
||||
if was_corresponding {
|
||||
@@ -723,12 +733,28 @@ fn build_review(
|
||||
constructor_actions.push((target, selected.clone(), local_record));
|
||||
}
|
||||
let refreshed = semantic_facets(observed, &trace, &references)?;
|
||||
let group_selectors: BTreeSet<_> = refreshed
|
||||
let mut group_selectors: BTreeSet<_> = refreshed
|
||||
.iter()
|
||||
.chain(all.iter())
|
||||
.map(|f| f.selector.clone())
|
||||
.filter(|f| constructor_contains(selected, f))
|
||||
.collect();
|
||||
// A constructor copy can turn a live one-sided member into a
|
||||
// pair. Its initial projection is not another reviewed fact.
|
||||
// Established one-sided history still requires an explicit reset.
|
||||
let paired_sides: BTreeSet<_> = group_selectors
|
||||
.iter()
|
||||
.map(selector_slots)
|
||||
.filter(|slots| slots.len() == 2)
|
||||
.flatten()
|
||||
.collect();
|
||||
group_selectors.retain(|selector| {
|
||||
!paired_sides.contains(selector)
|
||||
|| baseline
|
||||
.facets
|
||||
.iter()
|
||||
.any(|old| old.selector() == *selector)
|
||||
});
|
||||
let mut group = vec![];
|
||||
for selector in group_selectors {
|
||||
match capture_facet(observed, oa, sa, &selector) {
|
||||
@@ -769,7 +795,18 @@ fn build_review(
|
||||
current.clone()
|
||||
};
|
||||
if resolution.decision == SemanticDecision::TakeSource {
|
||||
fact = remap_fact(&fact, &map, source_layer)?;
|
||||
fact = if let Some(adapted) = transitions::review_endpoint_fact(
|
||||
initial,
|
||||
&plan.request.transition,
|
||||
&map,
|
||||
request.source,
|
||||
target,
|
||||
&fact,
|
||||
)? {
|
||||
adapted
|
||||
} else {
|
||||
remap_fact(&fact, &map, source_layer)?
|
||||
};
|
||||
}
|
||||
// A Keep reads the frozen target, never a value written by an earlier source.
|
||||
if resolution.decision != SemanticDecision::KeepTarget {
|
||||
|
||||
@@ -86,6 +86,7 @@ macro_rules! scalar_families {
|
||||
ExchangeItem, ExchangeItemFacet, ExchangeItemReview {
|
||||
Nature: ExchangeItemKind, Mechanism: ExchangeMechanism, Supertype: Option<Id>
|
||||
}
|
||||
Category, CategoryFacet, CategoryReview { Family: crate::view_options::ExchangeFamily }
|
||||
Interface, InterfaceFacet, InterfaceReview { Supertype: Option<Id> }
|
||||
Data, DataFacet, DataReview {
|
||||
Constructor: DataConstructor,
|
||||
@@ -111,6 +112,7 @@ macro_rules! scalar_families {
|
||||
Constructor: OccurrenceConstructor, Precondition: String, Postcondition: String,
|
||||
Exchange: Option<Id>, Sender: Option<Id>, Receiver: Option<Id>,
|
||||
MessageKind: MessageConstructor, TimerExpression: String, ReplyTo: Option<Id>,
|
||||
Operation: Option<OperationUse>,
|
||||
Action: Option<Id>, ActionLifeline: Option<Id>, ControlKind: ControlKind,
|
||||
Sequence: Option<Id>, Scenario: Option<Id>, State: Option<Id>,
|
||||
StateLifeline: Option<Id>, FragmentOperator: FragmentOperator, BranchGuard: String
|
||||
@@ -128,6 +130,8 @@ macro_rules! scalar_families {
|
||||
SourcePort: Id, TargetPort: Id, Oriented: bool, ExtendCondition: String,
|
||||
SequenceGuard: String, TransitionKind: TransitionKind, Trigger: String,
|
||||
Guard: String, Effect: String, StateActionPhase: StateActionKind
|
||||
, ContextOwner: Id, ContextSource: OccurrenceEndpoint, ContextTarget: OccurrenceEndpoint,
|
||||
ContextPurpose: ContextualLinkPurpose
|
||||
}
|
||||
}};
|
||||
}
|
||||
@@ -197,6 +201,7 @@ pub enum ReferenceCollection {
|
||||
FunctionOutputItems,
|
||||
SignalItems,
|
||||
ExchangeItems,
|
||||
CategoryExchanges,
|
||||
TransitionTriggers,
|
||||
TransitionEffects,
|
||||
Constrained,
|
||||
|
||||
@@ -19,6 +19,21 @@ pub enum Command {
|
||||
},
|
||||
CreateElement(Element),
|
||||
EditElement(Id, Element),
|
||||
CreateDefinition(crate::analysis::Definition),
|
||||
EditDefinition(Id, crate::analysis::Definition),
|
||||
SetAnalysisBase {
|
||||
property: Id,
|
||||
binding: crate::analysis::Binding,
|
||||
},
|
||||
SetAnalysisOverride {
|
||||
case: Id,
|
||||
property: Id,
|
||||
binding: crate::analysis::Binding,
|
||||
},
|
||||
ClearAnalysisOverride {
|
||||
case: Id,
|
||||
property: Id,
|
||||
},
|
||||
CreateRelation(Relation),
|
||||
EditRelation(Id, Relation),
|
||||
CreateDiagram(Diagram),
|
||||
@@ -453,6 +468,47 @@ fn apply_command(
|
||||
}
|
||||
Some(value.id)
|
||||
}
|
||||
Command::CreateDefinition(value) => {
|
||||
vacant(p, value.id)?;
|
||||
p.definitions.insert(value.id, value.clone());
|
||||
Some(value.id)
|
||||
}
|
||||
Command::EditDefinition(old, value) => {
|
||||
if !p.definitions.contains_key(old) { return Err(missing()); }
|
||||
let mut definition = value.clone();
|
||||
definition.id = *old;
|
||||
p.definitions.insert(*old, definition);
|
||||
reidentify_tracked(p, *old, value.id, provenance)?;
|
||||
Some(value.id)
|
||||
}
|
||||
Command::SetAnalysisBase { property, binding } => {
|
||||
let element = p.elements.get_mut(property).ok_or_else(missing)?;
|
||||
let Some(SharedBody::EngineeringProperty { base, .. }) = element.shared_mut() else {
|
||||
return Err(ModelError("SetAnalysisBase requires an engineering property.".into()));
|
||||
};
|
||||
*base = binding.clone();
|
||||
Some(*property)
|
||||
}
|
||||
Command::SetAnalysisOverride { case, property, binding } => {
|
||||
let element = p.elements.get_mut(case).ok_or_else(missing)?;
|
||||
let Some(SharedBody::AnalysisCase { overrides, .. }) = element.shared_mut() else {
|
||||
return Err(ModelError("SetAnalysisOverride requires an analysis case.".into()));
|
||||
};
|
||||
overrides.insert(*property, binding.clone());
|
||||
Some(*case)
|
||||
}
|
||||
Command::ClearAnalysisOverride { case, property } => {
|
||||
let target = p.elements.get(property).ok_or_else(missing)?;
|
||||
if target.kind() != Kind::EngineeringProperty { return Err(ModelError("ClearAnalysisOverride requires an engineering property target.".into())); }
|
||||
let layer = target.layer();
|
||||
let element = p.elements.get_mut(case).ok_or_else(missing)?;
|
||||
if element.layer() != layer { return Err(ModelError("Case and property must share a layer.".into())); }
|
||||
let Some(SharedBody::AnalysisCase { overrides, .. }) = element.shared_mut() else {
|
||||
return Err(ModelError("ClearAnalysisOverride requires an analysis case.".into()));
|
||||
};
|
||||
overrides.remove(property);
|
||||
Some(*case)
|
||||
}
|
||||
Command::CreateRelation(value) => {
|
||||
vacant(p, value.id)?;
|
||||
p.relations.insert(value.id, value.clone());
|
||||
@@ -660,6 +716,7 @@ fn apply_command(
|
||||
.unwrap();
|
||||
*occ.shared_mut().unwrap() = SharedBody::Occurrence {
|
||||
body: OccurrenceBody::Exchange {
|
||||
operation: None,
|
||||
exchange: Some(*exchange),
|
||||
sender: None,
|
||||
receiver: None,
|
||||
@@ -834,6 +891,10 @@ fn edit_header(
|
||||
assign(&mut p.name, &mut p.description, &mut p.alias);
|
||||
return Ok(());
|
||||
}
|
||||
if let Some(v) = p.definitions.get_mut(&id) {
|
||||
assign(&mut v.name, &mut v.description, &mut v.alias);
|
||||
return Ok(());
|
||||
}
|
||||
if let Some(v) = p.elements.get_mut(&id) {
|
||||
assign(&mut v.name, &mut v.description, &mut v.alias);
|
||||
return Ok(());
|
||||
@@ -877,8 +938,13 @@ pub fn reidentify(p: &mut Project, old: Id, new: Id) -> Result<(), ModelError> {
|
||||
return Ok(());
|
||||
}
|
||||
vacant(p, new)?;
|
||||
crate::analysis::references::check_remap(p, old, new)
|
||||
.map_err(|error| ModelError(error.to_string()))?;
|
||||
if p.id == old {
|
||||
p.id = new;
|
||||
} else if let Some(mut v) = p.definitions.remove(&old) {
|
||||
v.id = new;
|
||||
p.definitions.insert(new, v);
|
||||
} else if let Some(mut v) = p.elements.remove(&old) {
|
||||
v.id = new;
|
||||
p.elements.insert(new, v);
|
||||
@@ -903,7 +969,7 @@ pub fn reidentify(p: &mut Project, old: Id, new: Id) -> Result<(), ModelError> {
|
||||
}
|
||||
}
|
||||
}
|
||||
crate::references::remap_references(p, old, new);
|
||||
crate::references::remap_references(p, old, new)?;
|
||||
Ok(())
|
||||
}
|
||||
fn layout(p: &mut Project, diagram: Id) -> Result<(), ModelError> {
|
||||
|
||||
@@ -9,6 +9,13 @@
|
||||
//! may remain after interruption during staging/completed cleanup. They contain
|
||||
//! no pending transaction unless named `.arcadia-save-ENTRY.journal`. Windows
|
||||
//! has no portable directory fsync; this is not a power-loss durability promise.
|
||||
//! Journal v2 records whether writes may have begun with a flushed marker.
|
||||
//! Recovery of a v2 journal without that marker discards only journal metadata;
|
||||
//! v1 journals retain their prior rollback rules.
|
||||
//! Journal publication refuses replacement on Windows and Linux, including a
|
||||
//! competing empty directory. Linux requires kernel/filesystem support for
|
||||
//! `renameat2(RENAME_NOREPLACE)` and fails without a fallback when unavailable.
|
||||
//! Other operating systems retain standard rename semantics.
|
||||
use crate::{language, source_project::*};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::{
|
||||
@@ -22,6 +29,8 @@ use thiserror::Error;
|
||||
const MAX_PATH_BYTES: usize = 4096;
|
||||
const MAX_JOURNAL_BYTES: usize = 32 * 1024 * 1024;
|
||||
const MAX_JOURNAL_FILES: usize = 4096;
|
||||
const WRITE_STARTED: &str = "write-started";
|
||||
const WRITE_STARTED_BYTES: &[u8] = b"Arcadia journal v2: model writes may have started\n";
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub enum DiskExpectation {
|
||||
@@ -588,6 +597,127 @@ fn staged_path(journal: &Path, index: usize, suffix: &str) -> PathBuf {
|
||||
journal.join(format!("{index}.{suffix}"))
|
||||
}
|
||||
|
||||
fn publish_journal(stage: &Path, journal: &Path) -> Result<(), SourceFileError> {
|
||||
#[cfg(windows)]
|
||||
{
|
||||
publish_journal_with_retry(
|
||||
stage,
|
||||
journal,
|
||||
rename_journal_without_replacement,
|
||||
std::thread::sleep,
|
||||
)
|
||||
}
|
||||
#[cfg(target_os = "linux")]
|
||||
{
|
||||
rename_journal_without_replacement(stage, journal).map_err(|error| io_at(journal, error))
|
||||
}
|
||||
// Other platforms retain their existing rename behavior; the native
|
||||
// no-replacement publication guarantee is currently Windows/Linux only.
|
||||
#[cfg(not(any(windows, target_os = "linux")))]
|
||||
{
|
||||
fs::rename(stage, journal).map_err(|error| io_at(journal, error))
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(target_os = "linux")]
|
||||
fn rename_journal_without_replacement(stage: &Path, journal: &Path) -> io::Result<()> {
|
||||
use std::{ffi::CString, os::unix::ffi::OsStrExt};
|
||||
|
||||
let path_bytes = |path: &Path| {
|
||||
CString::new(path.as_os_str().as_bytes()).map_err(|_| {
|
||||
io::Error::new(
|
||||
io::ErrorKind::InvalidInput,
|
||||
"Journal path contains an interior NUL.",
|
||||
)
|
||||
})
|
||||
};
|
||||
let (stage, journal) = (path_bytes(stage)?, path_bytes(journal)?);
|
||||
// Use libc's architecture-specific syscall number, avoiding a dependency on
|
||||
// the newer glibc renameat2 wrapper. Both NUL-terminated byte buffers remain
|
||||
// alive for the call. RENAME_NOREPLACE makes even an empty competing directory
|
||||
// an error. Unsupported kernels/filesystems fail closed: never fall back to
|
||||
// ordinary rename, whose replacement semantics would lose journal ownership.
|
||||
let result = unsafe {
|
||||
libc::syscall(
|
||||
libc::SYS_renameat2,
|
||||
libc::AT_FDCWD as libc::c_long,
|
||||
stage.as_ptr(),
|
||||
libc::AT_FDCWD as libc::c_long,
|
||||
journal.as_ptr(),
|
||||
libc::RENAME_NOREPLACE as libc::c_ulong,
|
||||
)
|
||||
};
|
||||
if result == -1 {
|
||||
Err(io::Error::last_os_error())
|
||||
} else {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
fn rename_journal_without_replacement(stage: &Path, journal: &Path) -> io::Result<()> {
|
||||
use std::os::windows::ffi::OsStrExt;
|
||||
#[link(name = "kernel32")]
|
||||
unsafe extern "system" {
|
||||
fn MoveFileExW(existing: *const u16, destination: *const u16, flags: u32) -> i32;
|
||||
}
|
||||
let wide = |path: &Path| -> io::Result<Vec<u16>> {
|
||||
let mut value: Vec<_> = path.as_os_str().encode_wide().collect();
|
||||
if value.contains(&0) {
|
||||
return Err(io::Error::new(
|
||||
io::ErrorKind::InvalidInput,
|
||||
"Journal path contains an interior NUL.",
|
||||
));
|
||||
}
|
||||
value.push(0);
|
||||
Ok(value)
|
||||
};
|
||||
let (stage, journal) = (wide(stage)?, wide(journal)?);
|
||||
// Both terminated UTF-16 buffers live through the call. Flags=0 requests
|
||||
// neither replacement, cross-volume copying nor deferred execution. Unlike
|
||||
// fs::rename on modern Windows, an existing empty directory is not replaced.
|
||||
if unsafe { MoveFileExW(stage.as_ptr(), journal.as_ptr(), 0) } == 0 {
|
||||
Err(io::Error::last_os_error())
|
||||
} else {
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
// Windows scanners may briefly open newly written stage files without delete
|
||||
// sharing. Retry only publication, before any model file has been replaced.
|
||||
// Ownership still transfers only after one successful rename. Never overwrite
|
||||
// a journal that appeared while waiting, and retain the final OS error/path.
|
||||
#[cfg(any(windows, test))]
|
||||
fn publish_journal_with_retry(
|
||||
stage: &Path,
|
||||
journal: &Path,
|
||||
mut rename: impl FnMut(&Path, &Path) -> io::Result<()>,
|
||||
mut pause: impl FnMut(std::time::Duration),
|
||||
) -> Result<(), SourceFileError> {
|
||||
let mut delays = [5, 10, 25, 50, 100, 200].into_iter();
|
||||
loop {
|
||||
match fs::symlink_metadata(journal) {
|
||||
Ok(_) => return Err(SourceFileError::RecoveryRequired(journal.into())),
|
||||
Err(error) if error.kind() == io::ErrorKind::NotFound => {}
|
||||
Err(error) => return Err(io_at(journal, error)),
|
||||
}
|
||||
match rename(stage, journal) {
|
||||
Ok(()) => return Ok(()),
|
||||
Err(error) => {
|
||||
// ERROR_ACCESS_DENIED, ERROR_SHARING_VIOLATION, ERROR_LOCK_VIOLATION.
|
||||
// A permanent ACL failure is still returned after at most 390 ms.
|
||||
if matches!(error.raw_os_error(), Some(5 | 32 | 33))
|
||||
&& let Some(delay) = delays.next()
|
||||
{
|
||||
pause(std::time::Duration::from_millis(delay));
|
||||
continue;
|
||||
}
|
||||
return Err(io_at(journal, error));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn write_synced(path: &Path, bytes: &[u8]) -> Result<(), SourceFileError> {
|
||||
let mut file = File::options()
|
||||
.write(true)
|
||||
@@ -699,6 +829,26 @@ fn save_with_hook(
|
||||
compiled: &CompiledSourceProject,
|
||||
limits: ProjectLimits,
|
||||
mut after_replace: impl FnMut(usize) -> io::Result<()>,
|
||||
) -> Result<DiskProject, SourceFileError> {
|
||||
save_with_phases(snapshot, compiled, limits, |phase| match phase {
|
||||
SavePhase::AfterReplace(count) => after_replace(count),
|
||||
_ => Ok(()),
|
||||
})
|
||||
}
|
||||
|
||||
enum SavePhase {
|
||||
BeforePublish,
|
||||
AfterPublish,
|
||||
AfterWriteMarker,
|
||||
AfterReplace(usize),
|
||||
BeforeRetire,
|
||||
}
|
||||
|
||||
fn save_with_phases(
|
||||
snapshot: &DiskProject,
|
||||
compiled: &CompiledSourceProject,
|
||||
limits: ProjectLimits,
|
||||
mut phase: impl FnMut(SavePhase) -> io::Result<()>,
|
||||
) -> Result<DiskProject, SourceFileError> {
|
||||
check_snapshot(snapshot, limits)?;
|
||||
let checked = compile_bundle(&compiled.bundle, limits).map_err(|diagnostics| {
|
||||
@@ -739,7 +889,7 @@ fn save_with_hook(
|
||||
// Stable dependency order, with the project entry committed last.
|
||||
entries.sort_by_key(|file| (file.path == snapshot.bundle.entry, file.path.clone()));
|
||||
let journal = Journal {
|
||||
version: 1,
|
||||
version: 2,
|
||||
entry: snapshot.bundle.entry.clone(),
|
||||
files: entries,
|
||||
};
|
||||
@@ -775,20 +925,46 @@ fn save_with_hook(
|
||||
}
|
||||
write_synced(&stage.path().join("journal.json"), &metadata)?;
|
||||
sync_directory(stage.path())?;
|
||||
phase(SavePhase::BeforePublish).map_err(|error| io_at(&journal_dir, error))?;
|
||||
// Publishing a complete directory makes interrupted staging harmless.
|
||||
fs::rename(stage.path(), &journal_dir).map_err(|error| io_at(&journal_dir, error))?;
|
||||
publish_journal(stage.path(), &journal_dir)?;
|
||||
let _ = stage.keep(); // The renamed directory now belongs to recovery.
|
||||
sync_directory(&snapshot.root)?;
|
||||
phase(SavePhase::AfterPublish).map_err(|error| io_at(&journal_dir, error))?;
|
||||
// Publication may have waited while another writer completed the same
|
||||
// candidate. Nothing has been written by this save: never interpret their
|
||||
// matching after-bytes as ours and roll them back. The absent v2 marker
|
||||
// also preserves this distinction after interruption or retirement failure.
|
||||
if let Err(error) = check_conflicts(&snapshot.root, &snapshot.expectations) {
|
||||
let retirement = phase(SavePhase::BeforeRetire)
|
||||
.map_err(|error| io_at(&journal_dir, error))
|
||||
.and_then(|()| retire_journal(&snapshot.root, &journal_dir, &journal));
|
||||
return match retirement {
|
||||
Ok(()) => Err(error),
|
||||
Err(retirement) => Err(SourceFileError::RecoveryFailed {
|
||||
save: error.to_string(),
|
||||
recovery: retirement.to_string(),
|
||||
journal: journal_dir,
|
||||
}),
|
||||
};
|
||||
}
|
||||
write_synced(&journal_dir.join(WRITE_STARTED), WRITE_STARTED_BYTES)?;
|
||||
sync_directory(&journal_dir)?;
|
||||
phase(SavePhase::AfterWriteMarker).map_err(|error| io_at(&journal_dir, error))?;
|
||||
let result = (|| {
|
||||
let mut current = snapshot.expectations.clone();
|
||||
let mut replacements = 0;
|
||||
for file in journal.files.iter().filter(|file| file.write) {
|
||||
check_conflicts(&snapshot.root, ¤t)?;
|
||||
// The first check is above, before the durable write-attempt marker.
|
||||
// Further checks follow real write attempts and may need rollback.
|
||||
if replacements != 0 {
|
||||
check_conflicts(&snapshot.root, ¤t)?;
|
||||
}
|
||||
let bytes = compiled.bundle.files[&file.path].as_bytes();
|
||||
atomic_write(&snapshot.root, &file.path, bytes)?;
|
||||
current.insert(file.path.clone(), DiskExpectation::Bytes(bytes.to_vec()));
|
||||
replacements += 1;
|
||||
after_replace(replacements)
|
||||
phase(SavePhase::AfterReplace(replacements))
|
||||
.map_err(|error| io_at(&snapshot.root.join(&file.path), error))?;
|
||||
}
|
||||
check_conflicts(&snapshot.root, ¤t)?;
|
||||
@@ -804,6 +980,7 @@ fn save_with_hook(
|
||||
}),
|
||||
};
|
||||
}
|
||||
phase(SavePhase::BeforeRetire).map_err(|error| io_at(&journal_dir, error))?;
|
||||
retire_journal(&snapshot.root, &journal_dir, &journal)?;
|
||||
Ok(saved_snapshot(snapshot, compiled))
|
||||
}
|
||||
@@ -833,6 +1010,14 @@ fn remove_journal(directory: &Path, journal: &Journal) -> Result<(), SourceFileE
|
||||
}
|
||||
}
|
||||
}
|
||||
if journal.version == 2 {
|
||||
let marker = directory.join(WRITE_STARTED);
|
||||
match fs::remove_file(&marker) {
|
||||
Ok(()) => {}
|
||||
Err(error) if error.kind() == io::ErrorKind::NotFound => {}
|
||||
Err(error) => return Err(io_at(&marker, error)),
|
||||
}
|
||||
}
|
||||
let metadata = directory.join("journal.json");
|
||||
fs::remove_file(&metadata).map_err(|error| io_at(&metadata, error))?;
|
||||
fs::remove_dir(directory).map_err(|error| io_at(directory, error))
|
||||
@@ -898,7 +1083,10 @@ fn recover_with_hook(
|
||||
let bytes = read_journal_file(&metadata_path, MAX_JOURNAL_BYTES)?;
|
||||
let journal: Journal = serde_json::from_slice(&bytes)
|
||||
.map_err(|error| SourceFileError::Invalid(format!("Invalid recovery journal: {error}")))?;
|
||||
if journal.version != 1 || journal.entry != entry || journal.files.len() > limits.max_files {
|
||||
if !matches!(journal.version, 1 | 2)
|
||||
|| journal.entry != entry
|
||||
|| journal.files.len() > limits.max_files
|
||||
{
|
||||
return Err(SourceFileError::Invalid(
|
||||
"Recovery journal version, entry or file budget is invalid.".into(),
|
||||
));
|
||||
@@ -908,6 +1096,25 @@ fn recover_with_hook(
|
||||
let mut folded = BTreeSet::new();
|
||||
let (mut before_bytes, mut after_bytes) = (0usize, 0usize);
|
||||
let mut allowed = BTreeSet::from(["journal.json".to_string()]);
|
||||
let write_started = if journal.version == 2 {
|
||||
let marker = directory.join(WRITE_STARTED);
|
||||
match fs::symlink_metadata(&marker) {
|
||||
Ok(_) => {
|
||||
if read_journal_file(&marker, WRITE_STARTED_BYTES.len())? != WRITE_STARTED_BYTES {
|
||||
return Err(SourceFileError::Invalid(
|
||||
"Invalid journal write-started marker.".into(),
|
||||
));
|
||||
}
|
||||
allowed.insert(WRITE_STARTED.into());
|
||||
true
|
||||
}
|
||||
Err(error) if error.kind() == io::ErrorKind::NotFound => false,
|
||||
Err(error) => return Err(io_at(&marker, error)),
|
||||
}
|
||||
} else {
|
||||
// Frozen v1 journals predate the marker and retain their rollback rules.
|
||||
true
|
||||
};
|
||||
for (index, file) in journal.files.iter().enumerate() {
|
||||
disk_path(&root, &file.path)?;
|
||||
if !folded.insert(file.path.to_lowercase()) {
|
||||
@@ -952,6 +1159,10 @@ fn recover_with_hook(
|
||||
));
|
||||
}
|
||||
}
|
||||
if !write_started {
|
||||
retire_journal(&root, &directory, &journal)?;
|
||||
return Ok(true);
|
||||
}
|
||||
let mut current = BTreeMap::new();
|
||||
let mut conflicts = Vec::new();
|
||||
for (path, before) in &original {
|
||||
@@ -995,6 +1206,342 @@ fn recover_with_hook(
|
||||
mod transaction_tests {
|
||||
use super::*;
|
||||
|
||||
#[cfg(target_os = "linux")]
|
||||
#[test]
|
||||
fn linux_journal_publication_preserves_competing_destinations_and_our_stage() {
|
||||
use std::os::unix::{fs::MetadataExt, fs::symlink};
|
||||
|
||||
for kind in ["empty directory", "nonempty directory", "file", "symlink"] {
|
||||
let directory = tempfile::tempdir().unwrap();
|
||||
let stage = directory.path().join("stage");
|
||||
let journal = directory.path().join("journal");
|
||||
fs::create_dir(&stage).unwrap();
|
||||
fs::write(stage.join("journal.json"), b"our complete metadata").unwrap();
|
||||
// Simulate a competitor arriving after the caller's absence check.
|
||||
assert!(!journal.exists());
|
||||
match kind {
|
||||
"empty directory" => fs::create_dir(&journal).unwrap(),
|
||||
"nonempty directory" => {
|
||||
fs::create_dir(&journal).unwrap();
|
||||
fs::write(journal.join("journal.json"), b"competitor metadata").unwrap();
|
||||
}
|
||||
"file" => fs::write(&journal, b"competitor file").unwrap(),
|
||||
"symlink" => symlink("absent competitor target", &journal).unwrap(),
|
||||
_ => unreachable!(),
|
||||
}
|
||||
let before = fs::symlink_metadata(&journal).unwrap();
|
||||
let error = publish_journal(&stage, &journal).unwrap_err();
|
||||
assert!(
|
||||
matches!(error, SourceFileError::Io { path, source }
|
||||
if path == journal && source.raw_os_error() == Some(libc::EEXIST)),
|
||||
"{kind} must refuse publication"
|
||||
);
|
||||
let after = fs::symlink_metadata(&journal).unwrap();
|
||||
assert_eq!((before.dev(), before.ino()), (after.dev(), after.ino()));
|
||||
assert_eq!(
|
||||
fs::read(stage.join("journal.json")).unwrap(),
|
||||
b"our complete metadata"
|
||||
);
|
||||
match kind {
|
||||
"empty directory" => assert_eq!(fs::read_dir(&journal).unwrap().count(), 0),
|
||||
"nonempty directory" => assert_eq!(
|
||||
fs::read(journal.join("journal.json")).unwrap(),
|
||||
b"competitor metadata"
|
||||
),
|
||||
"file" => assert_eq!(fs::read(&journal).unwrap(), b"competitor file"),
|
||||
"symlink" => assert_eq!(
|
||||
fs::read_link(&journal).unwrap(),
|
||||
Path::new("absent competitor target")
|
||||
),
|
||||
_ => unreachable!(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(target_os = "linux")]
|
||||
#[test]
|
||||
fn linux_journal_publication_preserves_raw_path_bytes_and_rejects_nul() {
|
||||
use std::{ffi::OsStr, os::unix::ffi::OsStrExt};
|
||||
|
||||
let directory = tempfile::tempdir().unwrap();
|
||||
let stage = directory.path().join(OsStr::from_bytes(b"stage-\xff"));
|
||||
let journal = directory.path().join(OsStr::from_bytes(b"journal-\xfe"));
|
||||
fs::create_dir(&stage).unwrap();
|
||||
fs::write(stage.join("journal.json"), b"complete metadata").unwrap();
|
||||
for (a, b) in [
|
||||
(Path::new("bad\0path"), journal.as_path()),
|
||||
(stage.as_path(), Path::new("bad\0path")),
|
||||
] {
|
||||
let error = rename_journal_without_replacement(a, b).unwrap_err();
|
||||
assert_eq!(error.kind(), io::ErrorKind::InvalidInput);
|
||||
assert!(stage.join("journal.json").exists());
|
||||
assert!(!journal.exists());
|
||||
}
|
||||
publish_journal(&stage, &journal).unwrap();
|
||||
assert!(!stage.exists());
|
||||
assert_eq!(
|
||||
fs::read(journal.join("journal.json")).unwrap(),
|
||||
b"complete metadata"
|
||||
);
|
||||
}
|
||||
|
||||
#[cfg(target_os = "linux")]
|
||||
#[test]
|
||||
fn linux_journal_publication_has_one_winner_for_concurrent_stages() {
|
||||
use std::sync::Barrier;
|
||||
|
||||
let directory = tempfile::tempdir().unwrap();
|
||||
let journal = directory.path().join("journal");
|
||||
let stages = [
|
||||
directory.path().join("stage-a"),
|
||||
directory.path().join("stage-b"),
|
||||
];
|
||||
for (i, stage) in stages.iter().enumerate() {
|
||||
fs::create_dir(stage).unwrap();
|
||||
fs::write(stage.join("journal.json"), format!("complete writer {i}")).unwrap();
|
||||
}
|
||||
let barrier = Barrier::new(2);
|
||||
let results = std::thread::scope(|scope| {
|
||||
let journal = &journal;
|
||||
let barrier = &barrier;
|
||||
let handles: Vec<_> = stages
|
||||
.iter()
|
||||
.map(|stage| {
|
||||
scope.spawn(move || {
|
||||
assert!(!journal.exists());
|
||||
barrier.wait();
|
||||
publish_journal(stage, journal)
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
handles
|
||||
.into_iter()
|
||||
.map(|handle| handle.join().unwrap())
|
||||
.collect::<Vec<_>>()
|
||||
});
|
||||
assert_eq!(results.iter().filter(|result| result.is_ok()).count(), 1);
|
||||
for (i, result) in results.into_iter().enumerate() {
|
||||
match result {
|
||||
Ok(()) => {
|
||||
assert!(!stages[i].exists());
|
||||
assert_eq!(
|
||||
fs::read_to_string(journal.join("journal.json")).unwrap(),
|
||||
format!("complete writer {i}")
|
||||
);
|
||||
}
|
||||
Err(SourceFileError::Io { path, source }) => {
|
||||
assert_eq!(path, journal);
|
||||
assert_eq!(source.raw_os_error(), Some(libc::EEXIST));
|
||||
assert_eq!(
|
||||
fs::read_to_string(stages[i].join("journal.json")).unwrap(),
|
||||
format!("complete writer {i}")
|
||||
);
|
||||
}
|
||||
Err(error) => panic!("unexpected publication error: {error}"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(target_os = "linux")]
|
||||
#[test]
|
||||
#[ignore = "requires strace renameat2 error injection and OA_TEST_RENAMEAT2_ERRNO"]
|
||||
fn linux_journal_publication_injected_unsupported_error_is_fail_closed() {
|
||||
let errno: i32 = std::env::var("OA_TEST_RENAMEAT2_ERRNO")
|
||||
.expect("set OA_TEST_RENAMEAT2_ERRNO to the injected Linux errno")
|
||||
.parse()
|
||||
.unwrap();
|
||||
assert!(matches!(
|
||||
errno,
|
||||
libc::ENOSYS | libc::EINVAL | libc::EOPNOTSUPP
|
||||
));
|
||||
let (directory, snapshot, compiled) = fixture();
|
||||
let journal = journal_path(&snapshot.root, &snapshot.bundle.entry);
|
||||
let original: Vec<_> = snapshot
|
||||
.bundle
|
||||
.files
|
||||
.keys()
|
||||
.map(|path| (path.clone(), fs::read(directory.path().join(path)).unwrap()))
|
||||
.collect();
|
||||
let error = save_with_phases(&snapshot, &compiled, ProjectLimits::default(), |phase| {
|
||||
if matches!(
|
||||
phase,
|
||||
SavePhase::AfterPublish | SavePhase::AfterWriteMarker | SavePhase::AfterReplace(_)
|
||||
) {
|
||||
panic!("unsupported no-replace publication must stop before ownership transfer");
|
||||
}
|
||||
Ok(())
|
||||
})
|
||||
.unwrap_err();
|
||||
assert!(matches!(error, SourceFileError::Io { path, source }
|
||||
if path == journal && source.raw_os_error() == Some(errno)));
|
||||
assert!(!journal.exists());
|
||||
for (path, bytes) in original {
|
||||
assert_eq!(fs::read(directory.path().join(path)).unwrap(), bytes);
|
||||
}
|
||||
check_conflicts(&snapshot.root, &snapshot.expectations).unwrap();
|
||||
}
|
||||
|
||||
#[cfg(target_os = "linux")]
|
||||
#[test]
|
||||
fn linux_journal_publication_refusal_never_starts_model_writes() {
|
||||
let (directory, snapshot, compiled) = fixture();
|
||||
let journal = journal_path(&snapshot.root, &snapshot.bundle.entry);
|
||||
let original: Vec<_> = snapshot
|
||||
.bundle
|
||||
.files
|
||||
.keys()
|
||||
.map(|path| (path.clone(), fs::read(directory.path().join(path)).unwrap()))
|
||||
.collect();
|
||||
let error = save_with_phases(&snapshot, &compiled, ProjectLimits::default(), |phase| {
|
||||
match phase {
|
||||
SavePhase::BeforePublish => fs::create_dir(&journal).unwrap(),
|
||||
SavePhase::AfterPublish
|
||||
| SavePhase::AfterWriteMarker
|
||||
| SavePhase::AfterReplace(_) => {
|
||||
panic!("a rejected publisher must not obtain ownership or write source files")
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
Ok(())
|
||||
})
|
||||
.unwrap_err();
|
||||
assert!(matches!(error, SourceFileError::Io { path, source }
|
||||
if path == journal && source.raw_os_error() == Some(libc::EEXIST)));
|
||||
assert_eq!(fs::read_dir(&journal).unwrap().count(), 0);
|
||||
assert!(!journal.join(WRITE_STARTED).exists());
|
||||
for (path, bytes) in original {
|
||||
assert_eq!(fs::read(directory.path().join(path)).unwrap(), bytes);
|
||||
}
|
||||
check_conflicts(&snapshot.root, &snapshot.expectations).unwrap();
|
||||
}
|
||||
|
||||
#[cfg(windows)]
|
||||
#[test]
|
||||
fn journal_publication_does_not_replace_empty_target_created_after_precheck() {
|
||||
let directory = tempfile::tempdir().unwrap();
|
||||
let stage = directory.path().join("stage");
|
||||
let journal = directory.path().join("journal");
|
||||
fs::create_dir(&stage).unwrap();
|
||||
fs::write(stage.join("journal.json"), b"our journal").unwrap();
|
||||
let mut called = false;
|
||||
let result = publish_journal_with_retry(
|
||||
&stage,
|
||||
&journal,
|
||||
|a, b| {
|
||||
assert!(!called);
|
||||
called = true;
|
||||
fs::create_dir(b).unwrap();
|
||||
rename_journal_without_replacement(a, b)
|
||||
},
|
||||
|_| {},
|
||||
);
|
||||
assert!(result.is_err());
|
||||
assert!(called);
|
||||
assert_eq!(
|
||||
fs::read(stage.join("journal.json")).unwrap(),
|
||||
b"our journal"
|
||||
);
|
||||
assert_eq!(fs::read_dir(&journal).unwrap().count(), 0);
|
||||
assert!(
|
||||
matches!(rename_journal_without_replacement(Path::new("bad\0path"), &journal), Err(error) if error.kind() == io::ErrorKind::InvalidInput)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn journal_publication_retries_only_transient_windows_errors_before_transferring_ownership() {
|
||||
let directory = tempfile::tempdir().unwrap();
|
||||
let stage = directory.path().join("stage");
|
||||
let journal = directory.path().join("journal");
|
||||
fs::create_dir(&stage).unwrap();
|
||||
fs::write(stage.join("journal.json"), b"complete staged metadata").unwrap();
|
||||
let mut errors = [5, 32, 33].into_iter();
|
||||
let mut waits = vec![];
|
||||
publish_journal_with_retry(
|
||||
&stage,
|
||||
&journal,
|
||||
|a, b| {
|
||||
assert!(a.join("journal.json").exists());
|
||||
assert!(!b.exists());
|
||||
match errors.next() {
|
||||
Some(code) => Err(io::Error::from_raw_os_error(code)),
|
||||
None => fs::rename(a, b),
|
||||
}
|
||||
},
|
||||
|delay| waits.push(delay.as_millis()),
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(waits, [5, 10, 25]);
|
||||
assert!(!stage.exists());
|
||||
assert_eq!(
|
||||
fs::read(journal.join("journal.json")).unwrap(),
|
||||
b"complete staged metadata"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn journal_publication_exhaustion_and_permanent_errors_keep_stage_and_report_original_path() {
|
||||
for (code, expected_calls, expected_wait) in [(5, 7, 390), (123, 1, 0)] {
|
||||
let directory = tempfile::tempdir().unwrap();
|
||||
let stage = directory.path().join("stage");
|
||||
let journal = directory.path().join("journal");
|
||||
fs::create_dir(&stage).unwrap();
|
||||
fs::write(stage.join("journal.json"), b"before publication").unwrap();
|
||||
let (mut calls, mut waited) = (0, 0);
|
||||
let error = publish_journal_with_retry(
|
||||
&stage,
|
||||
&journal,
|
||||
|_, _| {
|
||||
calls += 1;
|
||||
Err(io::Error::from_raw_os_error(code))
|
||||
},
|
||||
|delay| waited += delay.as_millis(),
|
||||
)
|
||||
.unwrap_err();
|
||||
assert_eq!((calls, waited), (expected_calls, expected_wait));
|
||||
assert!(
|
||||
matches!(error, SourceFileError::Io { path, source } if path == journal && source.raw_os_error() == Some(code))
|
||||
);
|
||||
assert_eq!(
|
||||
fs::read(stage.join("journal.json")).unwrap(),
|
||||
b"before publication"
|
||||
);
|
||||
assert!(!journal.exists());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn journal_publication_never_replaces_another_journal_that_appears_during_retry() {
|
||||
let directory = tempfile::tempdir().unwrap();
|
||||
let stage = directory.path().join("stage");
|
||||
let journal = directory.path().join("journal");
|
||||
fs::create_dir(&stage).unwrap();
|
||||
fs::write(stage.join("journal.json"), b"our staged journal").unwrap();
|
||||
let mut calls = 0;
|
||||
let error = publish_journal_with_retry(
|
||||
&stage,
|
||||
&journal,
|
||||
|_, _| {
|
||||
calls += 1;
|
||||
Err(io::Error::from_raw_os_error(32))
|
||||
},
|
||||
|_| {
|
||||
fs::create_dir(&journal).unwrap();
|
||||
fs::write(journal.join("journal.json"), b"other save owns this").unwrap();
|
||||
},
|
||||
)
|
||||
.unwrap_err();
|
||||
assert_eq!(calls, 1);
|
||||
assert!(matches!(error, SourceFileError::RecoveryRequired(path) if path == journal));
|
||||
assert_eq!(
|
||||
fs::read(journal.join("journal.json")).unwrap(),
|
||||
b"other save owns this"
|
||||
);
|
||||
assert_eq!(
|
||||
fs::read(stage.join("journal.json")).unwrap(),
|
||||
b"our staged journal"
|
||||
);
|
||||
}
|
||||
|
||||
fn fixture() -> (tempfile::TempDir, DiskProject, CompiledSourceProject) {
|
||||
let directory = tempfile::tempdir().unwrap();
|
||||
fs::write(
|
||||
@@ -1014,6 +1561,160 @@ mod transaction_tests {
|
||||
(directory, snapshot, compiled)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unwritten_journal_never_rolls_back_a_completed_writer_with_identical_after_bytes() {
|
||||
for interrupt_retirement in [false, true] {
|
||||
let (directory, snapshot, compiled) = fixture();
|
||||
let error = save_with_phases(&snapshot, &compiled, ProjectLimits::default(), |phase| {
|
||||
match phase {
|
||||
SavePhase::BeforePublish => {
|
||||
// A competing save finishes during our publication wait.
|
||||
save_project(&snapshot, &compiled, ProjectLimits::default()).unwrap();
|
||||
}
|
||||
SavePhase::BeforeRetire if interrupt_retirement => {
|
||||
return Err(io::Error::other("injected no-write retirement failure"));
|
||||
}
|
||||
SavePhase::AfterWriteMarker | SavePhase::AfterReplace(_) => {
|
||||
panic!("losing writer must not start writes")
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
Ok(())
|
||||
})
|
||||
.unwrap_err();
|
||||
assert!(matches!(
|
||||
error,
|
||||
SourceFileError::Conflict(_) | SourceFileError::RecoveryFailed { .. }
|
||||
));
|
||||
for (path, bytes) in &compiled.bundle.files {
|
||||
assert_eq!(
|
||||
fs::read_to_string(directory.path().join(path)).unwrap(),
|
||||
*bytes
|
||||
);
|
||||
}
|
||||
let journal = journal_path(&snapshot.root, &snapshot.bundle.entry);
|
||||
assert_eq!(journal.exists(), interrupt_retirement);
|
||||
if interrupt_retirement {
|
||||
assert!(!journal.join(WRITE_STARTED).exists());
|
||||
// Explicit recovery after a failed retirement must also leave
|
||||
// the completed other writer untouched, even matching after bytes.
|
||||
assert!(
|
||||
recover_project(
|
||||
&directory.path().join("project.arcadia"),
|
||||
ProjectLimits::default()
|
||||
)
|
||||
.unwrap()
|
||||
);
|
||||
for (path, bytes) in &compiled.bundle.files {
|
||||
assert_eq!(
|
||||
fs::read_to_string(directory.path().join(path)).unwrap(),
|
||||
*bytes
|
||||
);
|
||||
}
|
||||
}
|
||||
assert!(!journal.exists());
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn recovery_before_any_write_accepts_v2_marker_and_keeps_v1_rollback_compatibility() {
|
||||
for version in [1, 2] {
|
||||
let (directory, snapshot, compiled) = fixture();
|
||||
let interrupted = std::panic::catch_unwind(|| {
|
||||
let _ = save_with_phases(&snapshot, &compiled, ProjectLimits::default(), |phase| {
|
||||
if matches!(phase, SavePhase::AfterWriteMarker) {
|
||||
panic!("interrupted before atomic write");
|
||||
}
|
||||
Ok(())
|
||||
});
|
||||
});
|
||||
assert!(interrupted.is_err());
|
||||
check_conflicts(&snapshot.root, &snapshot.expectations).unwrap();
|
||||
let journal = journal_path(&snapshot.root, &snapshot.bundle.entry);
|
||||
assert_eq!(
|
||||
fs::read(journal.join(WRITE_STARTED)).unwrap(),
|
||||
WRITE_STARTED_BYTES
|
||||
);
|
||||
if version == 1 {
|
||||
// A frozen v1 journal has no marker and means writes may have begun.
|
||||
let path = journal.join("journal.json");
|
||||
let mut metadata: Journal =
|
||||
serde_json::from_slice(&fs::read(&path).unwrap()).unwrap();
|
||||
metadata.version = 1;
|
||||
fs::write(path, serde_json::to_vec(&metadata).unwrap()).unwrap();
|
||||
fs::remove_file(journal.join(WRITE_STARTED)).unwrap();
|
||||
for (path, bytes) in &compiled.bundle.files {
|
||||
fs::write(directory.path().join(path), bytes).unwrap();
|
||||
}
|
||||
}
|
||||
assert!(
|
||||
recover_project(
|
||||
&directory.path().join("project.arcadia"),
|
||||
ProjectLimits::default()
|
||||
)
|
||||
.unwrap()
|
||||
);
|
||||
check_conflicts(&snapshot.root, &snapshot.expectations).unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn interrupted_publication_without_write_marker_never_rolls_back_external_matching_bytes() {
|
||||
let (directory, snapshot, compiled) = fixture();
|
||||
let interrupted = std::panic::catch_unwind(|| {
|
||||
let _ = save_with_phases(&snapshot, &compiled, ProjectLimits::default(), |phase| {
|
||||
if matches!(phase, SavePhase::AfterPublish) {
|
||||
panic!("interrupted before write marker");
|
||||
}
|
||||
Ok(())
|
||||
});
|
||||
});
|
||||
assert!(interrupted.is_err());
|
||||
let journal = journal_path(&snapshot.root, &snapshot.bundle.entry);
|
||||
assert!(!journal.join(WRITE_STARTED).exists());
|
||||
for (path, bytes) in &compiled.bundle.files {
|
||||
fs::write(directory.path().join(path), bytes).unwrap();
|
||||
}
|
||||
assert!(
|
||||
recover_project(
|
||||
&directory.path().join("project.arcadia"),
|
||||
ProjectLimits::default()
|
||||
)
|
||||
.unwrap()
|
||||
);
|
||||
for (path, bytes) in &compiled.bundle.files {
|
||||
assert_eq!(
|
||||
fs::read_to_string(directory.path().join(path)).unwrap(),
|
||||
*bytes
|
||||
);
|
||||
}
|
||||
assert!(!journal.exists());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn malformed_v2_write_marker_refuses_recovery_without_changing_source_bytes() {
|
||||
let (directory, snapshot, compiled) = fixture();
|
||||
let _ = std::panic::catch_unwind(|| {
|
||||
let _ = save_with_phases(&snapshot, &compiled, ProjectLimits::default(), |phase| {
|
||||
if matches!(phase, SavePhase::AfterWriteMarker) {
|
||||
panic!("interrupted");
|
||||
}
|
||||
Ok(())
|
||||
});
|
||||
});
|
||||
let journal = journal_path(&snapshot.root, &snapshot.bundle.entry);
|
||||
fs::write(journal.join(WRITE_STARTED), b"partial").unwrap();
|
||||
assert!(matches!(
|
||||
recover_project(
|
||||
&directory.path().join("project.arcadia"),
|
||||
ProjectLimits::default()
|
||||
),
|
||||
Err(SourceFileError::Invalid(_))
|
||||
));
|
||||
check_conflicts(&snapshot.root, &snapshot.expectations).unwrap();
|
||||
assert!(journal.exists());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn partial_save_failures_restore_every_original_and_write_entry_last() {
|
||||
for stop in 1..=3 {
|
||||
|
||||
@@ -8,6 +8,7 @@ use std::collections::{BTreeMap, BTreeSet};
|
||||
mod source_migration;
|
||||
#[path = "source_project/source_structure.rs"]
|
||||
mod source_structure;
|
||||
pub(crate) mod traversal;
|
||||
|
||||
/// A portable slash-separated path, checked at every bundle boundary.
|
||||
pub type LogicalPath = String;
|
||||
@@ -304,71 +305,7 @@ fn compile_once(
|
||||
bundle: &SourceBundle,
|
||||
limits: ProjectLimits,
|
||||
) -> Result<(CompiledSourceProject, Edits), Vec<SourceDiagnostic>> {
|
||||
let fail = |code, message| {
|
||||
vec![problem(
|
||||
bundle,
|
||||
&bundle.entry,
|
||||
Span::default(),
|
||||
code,
|
||||
message,
|
||||
)]
|
||||
};
|
||||
if bundle.entry.contains('/') {
|
||||
return Err(fail(
|
||||
"invalid_path",
|
||||
"The entry file must be at the source project root.".into(),
|
||||
));
|
||||
}
|
||||
if bundle.files.len() > limits.max_files {
|
||||
return Err(fail(
|
||||
"project_limit",
|
||||
format!("Source project exceeds {} files.", limits.max_files),
|
||||
));
|
||||
}
|
||||
let bytes = bundle
|
||||
.files
|
||||
.values()
|
||||
.fold(0usize, |sum, text| sum.saturating_add(text.len()));
|
||||
if bytes > limits.model.max_source_bytes {
|
||||
return Err(fail(
|
||||
"source_limit",
|
||||
format!(
|
||||
"Combined source exceeds {} bytes.",
|
||||
limits.model.max_source_bytes
|
||||
),
|
||||
));
|
||||
}
|
||||
let mut folded = BTreeMap::new();
|
||||
for path in std::iter::once(&bundle.entry).chain(bundle.files.keys()) {
|
||||
if resolve_include("", path).as_ref() != Ok(path) {
|
||||
return Err(fail(
|
||||
"invalid_path",
|
||||
format!("Non-canonical source path '{path}'."),
|
||||
));
|
||||
}
|
||||
if let Some(previous) = folded.insert(path.to_lowercase(), path)
|
||||
&& previous != path
|
||||
{
|
||||
return Err(fail(
|
||||
"duplicate_path",
|
||||
format!("Case-colliding source paths '{previous}' and '{path}'."),
|
||||
));
|
||||
}
|
||||
}
|
||||
if !bundle.files.contains_key(&bundle.entry) {
|
||||
return Err(fail(
|
||||
"missing_include",
|
||||
"The entry file is missing from the source bundle.".into(),
|
||||
));
|
||||
}
|
||||
|
||||
enum Visit {
|
||||
Enter(LogicalPath, usize, Option<SourceLocation>),
|
||||
Leave,
|
||||
}
|
||||
let mut stack = vec![Visit::Enter(bundle.entry.clone(), 0, None)];
|
||||
let mut active: Vec<LogicalPath> = Vec::new();
|
||||
let mut visited = BTreeSet::new();
|
||||
let mut traversal = traversal::Traversal::new(bundle, limits)?;
|
||||
let mut declarations = Vec::new();
|
||||
let mut declaration_paths = Vec::new();
|
||||
let mut aliases = BTreeMap::new();
|
||||
@@ -381,51 +318,8 @@ fn compile_once(
|
||||
let mut includes = Vec::new();
|
||||
let mut insertions: Edits = BTreeMap::new();
|
||||
let mut graph_count = 0usize;
|
||||
while let Some(visit) = stack.pop() {
|
||||
let Visit::Enter(path, depth, origin) = visit else {
|
||||
active.pop();
|
||||
continue;
|
||||
};
|
||||
let at = origin.unwrap_or(SourceLocation {
|
||||
path: path.clone(),
|
||||
span: Span::default(),
|
||||
});
|
||||
if let Some(start) = active.iter().position(|file| file == &path) {
|
||||
let chain = active[start..]
|
||||
.iter()
|
||||
.chain(std::iter::once(&path))
|
||||
.cloned()
|
||||
.collect::<Vec<_>>()
|
||||
.join(" -> ");
|
||||
return Err(vec![problem(
|
||||
bundle,
|
||||
&at.path,
|
||||
at.span,
|
||||
"include_cycle",
|
||||
format!("Include cycle: {chain}."),
|
||||
)]);
|
||||
}
|
||||
if depth > limits.max_include_depth {
|
||||
return Err(vec![problem(
|
||||
bundle,
|
||||
&at.path,
|
||||
at.span,
|
||||
"project_limit",
|
||||
format!("Include depth exceeds {}.", limits.max_include_depth),
|
||||
)]);
|
||||
}
|
||||
if !visited.insert(path.clone()) {
|
||||
continue;
|
||||
}
|
||||
let Some(source) = bundle.files.get(&path) else {
|
||||
return Err(vec![problem(
|
||||
bundle,
|
||||
&at.path,
|
||||
at.span,
|
||||
"missing_include",
|
||||
format!("Included file '{path}' is missing."),
|
||||
)]);
|
||||
};
|
||||
while let Some(path) = traversal.next()? {
|
||||
let source = &bundle.files[&path];
|
||||
let mut unit = language::parse_unit(source, path == bundle.entry, limits.model).map_err(
|
||||
|diagnostic| {
|
||||
vec![SourceDiagnostic {
|
||||
@@ -513,46 +407,12 @@ fn compile_once(
|
||||
declarations.push(declaration);
|
||||
declaration_paths.push(path.clone());
|
||||
}
|
||||
let mut children = Vec::new();
|
||||
for (raw, span) in unit.includes {
|
||||
let target = resolve_include(&path, &raw)
|
||||
.map_err(|message| vec![problem(bundle, &path, span, "invalid_path", message)])?;
|
||||
let location = SourceLocation {
|
||||
path: path.clone(),
|
||||
span,
|
||||
};
|
||||
includes.push(IncludeLocation {
|
||||
location: location.clone(),
|
||||
target: target.clone(),
|
||||
});
|
||||
if includes.len() > limits.max_include_edges {
|
||||
return Err(vec![problem(
|
||||
bundle,
|
||||
&path,
|
||||
span,
|
||||
"project_limit",
|
||||
format!("Include graph exceeds {} edges.", limits.max_include_edges),
|
||||
)]);
|
||||
}
|
||||
children.push(Visit::Enter(
|
||||
target,
|
||||
depth.saturating_add(1),
|
||||
Some(location),
|
||||
));
|
||||
includes.push(traversal.include(&path, &raw, span)?);
|
||||
}
|
||||
active.push(path);
|
||||
stack.push(Visit::Leave);
|
||||
stack.extend(children.into_iter().rev());
|
||||
}
|
||||
if let Some(path) = bundle.files.keys().find(|path| !visited.contains(*path)) {
|
||||
return Err(vec![problem(
|
||||
bundle,
|
||||
path,
|
||||
Span::default(),
|
||||
"unreachable_file",
|
||||
"Supplied source file is not reachable from the entry file.",
|
||||
)]);
|
||||
traversal.finish_file(path);
|
||||
}
|
||||
traversal.finish()?;
|
||||
let header = project_header.expect("validated entry header");
|
||||
let index = SourceIndex {
|
||||
declarations: declaration_locations,
|
||||
@@ -1553,7 +1413,11 @@ fn semantic_owner(project: &Project, id: Id) -> Option<Id> {
|
||||
return element.parent;
|
||||
}
|
||||
if let Some(relation) = project.relations.get(&id) {
|
||||
return Some(relation.source());
|
||||
return Some(
|
||||
relation
|
||||
.contextual_owner()
|
||||
.unwrap_or_else(|| relation.source()),
|
||||
);
|
||||
}
|
||||
if let Some(artifact) = project.artifact_links.get(&id) {
|
||||
return Some(artifact.owner);
|
||||
|
||||
@@ -0,0 +1,258 @@
|
||||
//! Shared include traversal policy for ordinary compilation and private syntax.
|
||||
use super::*;
|
||||
|
||||
enum Visit {
|
||||
Enter(LogicalPath, usize, Option<SourceLocation>),
|
||||
Leave,
|
||||
}
|
||||
|
||||
pub(crate) struct Traversal<'a> {
|
||||
bundle: &'a SourceBundle,
|
||||
limits: ProjectLimits,
|
||||
stack: Vec<Visit>,
|
||||
active: Vec<LogicalPath>,
|
||||
visited: BTreeSet<LogicalPath>,
|
||||
children: Vec<Visit>,
|
||||
depth: usize,
|
||||
edges: usize,
|
||||
}
|
||||
|
||||
impl<'a> Traversal<'a> {
|
||||
pub(crate) fn new(
|
||||
bundle: &'a SourceBundle,
|
||||
limits: ProjectLimits,
|
||||
) -> Result<Self, Vec<SourceDiagnostic>> {
|
||||
let fail = |code, message| {
|
||||
vec![problem(
|
||||
bundle,
|
||||
&bundle.entry,
|
||||
Span::default(),
|
||||
code,
|
||||
message,
|
||||
)]
|
||||
};
|
||||
if bundle.entry.contains('/') {
|
||||
return Err(fail(
|
||||
"invalid_path",
|
||||
"The entry file must be at the source project root.".into(),
|
||||
));
|
||||
}
|
||||
if bundle.files.len() > limits.max_files {
|
||||
return Err(fail(
|
||||
"project_limit",
|
||||
format!("Source project exceeds {} files.", limits.max_files),
|
||||
));
|
||||
}
|
||||
let bytes = bundle
|
||||
.files
|
||||
.values()
|
||||
.fold(0usize, |sum, text| sum.saturating_add(text.len()));
|
||||
if bytes > limits.model.max_source_bytes {
|
||||
return Err(fail(
|
||||
"source_limit",
|
||||
format!(
|
||||
"Combined source exceeds {} bytes.",
|
||||
limits.model.max_source_bytes
|
||||
),
|
||||
));
|
||||
}
|
||||
let mut folded = BTreeMap::new();
|
||||
for path in std::iter::once(&bundle.entry).chain(bundle.files.keys()) {
|
||||
if resolve_include("", path).as_ref() != Ok(path) {
|
||||
return Err(fail(
|
||||
"invalid_path",
|
||||
format!("Non-canonical source path '{path}'."),
|
||||
));
|
||||
}
|
||||
if let Some(previous) = folded.insert(path.to_lowercase(), path)
|
||||
&& previous != path
|
||||
{
|
||||
return Err(fail(
|
||||
"duplicate_path",
|
||||
format!("Case-colliding source paths '{previous}' and '{path}'."),
|
||||
));
|
||||
}
|
||||
}
|
||||
if !bundle.files.contains_key(&bundle.entry) {
|
||||
return Err(fail(
|
||||
"missing_include",
|
||||
"The entry file is missing from the source bundle.".into(),
|
||||
));
|
||||
}
|
||||
Ok(Self {
|
||||
bundle,
|
||||
limits,
|
||||
stack: vec![Visit::Enter(bundle.entry.clone(), 0, None)],
|
||||
active: Vec::new(),
|
||||
visited: BTreeSet::new(),
|
||||
children: Vec::new(),
|
||||
depth: 0,
|
||||
edges: 0,
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) fn next(&mut self) -> Result<Option<LogicalPath>, Vec<SourceDiagnostic>> {
|
||||
while let Some(visit) = self.stack.pop() {
|
||||
let Visit::Enter(path, depth, origin) = visit else {
|
||||
self.active.pop();
|
||||
continue;
|
||||
};
|
||||
let at = origin.unwrap_or(SourceLocation {
|
||||
path: path.clone(),
|
||||
span: Span::default(),
|
||||
});
|
||||
if let Some(start) = self.active.iter().position(|file| file == &path) {
|
||||
let chain = self.active[start..]
|
||||
.iter()
|
||||
.chain(std::iter::once(&path))
|
||||
.cloned()
|
||||
.collect::<Vec<_>>()
|
||||
.join(" -> ");
|
||||
return Err(vec![problem(
|
||||
self.bundle,
|
||||
&at.path,
|
||||
at.span,
|
||||
"include_cycle",
|
||||
format!("Include cycle: {chain}."),
|
||||
)]);
|
||||
}
|
||||
if depth > self.limits.max_include_depth {
|
||||
return Err(vec![problem(
|
||||
self.bundle,
|
||||
&at.path,
|
||||
at.span,
|
||||
"project_limit",
|
||||
format!("Include depth exceeds {}.", self.limits.max_include_depth),
|
||||
)]);
|
||||
}
|
||||
if !self.visited.insert(path.clone()) {
|
||||
continue;
|
||||
}
|
||||
if !self.bundle.files.contains_key(&path) {
|
||||
return Err(vec![problem(
|
||||
self.bundle,
|
||||
&at.path,
|
||||
at.span,
|
||||
"missing_include",
|
||||
format!("Included file '{path}' is missing."),
|
||||
)]);
|
||||
}
|
||||
self.depth = depth;
|
||||
return Ok(Some(path));
|
||||
}
|
||||
Ok(None)
|
||||
}
|
||||
|
||||
pub(crate) fn include(
|
||||
&mut self,
|
||||
path: &str,
|
||||
raw: &str,
|
||||
span: Span,
|
||||
) -> Result<IncludeLocation, Vec<SourceDiagnostic>> {
|
||||
let target = resolve_include(path, raw)
|
||||
.map_err(|message| vec![problem(self.bundle, path, span, "invalid_path", message)])?;
|
||||
let location = SourceLocation {
|
||||
path: path.into(),
|
||||
span,
|
||||
};
|
||||
if self.edges >= self.limits.max_include_edges {
|
||||
return Err(vec![problem(
|
||||
self.bundle,
|
||||
path,
|
||||
span,
|
||||
"project_limit",
|
||||
format!(
|
||||
"Include graph exceeds {} edges.",
|
||||
self.limits.max_include_edges
|
||||
),
|
||||
)]);
|
||||
}
|
||||
self.edges += 1;
|
||||
self.children.push(Visit::Enter(
|
||||
target.clone(),
|
||||
self.depth.saturating_add(1),
|
||||
Some(location.clone()),
|
||||
));
|
||||
Ok(IncludeLocation { location, target })
|
||||
}
|
||||
|
||||
pub(crate) fn finish_file(&mut self, path: LogicalPath) {
|
||||
self.active.push(path);
|
||||
self.stack.push(Visit::Leave);
|
||||
self.stack.extend(self.children.drain(..).rev());
|
||||
}
|
||||
|
||||
pub(crate) fn finish(self) -> Result<(), Vec<SourceDiagnostic>> {
|
||||
if let Some(path) = self
|
||||
.bundle
|
||||
.files
|
||||
.keys()
|
||||
.find(|path| !self.visited.contains(*path))
|
||||
{
|
||||
return Err(vec![problem(
|
||||
self.bundle,
|
||||
path,
|
||||
Span::default(),
|
||||
"unreachable_file",
|
||||
"Supplied source file is not reachable from the entry file.",
|
||||
)]);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn ordinary_compile_once_keeps_include_order_and_cycle_source_location() {
|
||||
let mut bundle = SourceBundle {
|
||||
entry: "main.arcadia".into(),
|
||||
files: BTreeMap::from([
|
||||
("main.arcadia".into(), "arcadia 7; project p \"P\" id \"00000000-0000-0000-0000-000000000001\" { include \"dir/left.arcadia\"; include \"dir/right.arcadia\"; }".into()),
|
||||
("dir/left.arcadia".into(), "include \"../shared.arcadia\";".into()),
|
||||
("dir/right.arcadia".into(), "include \"../shared.arcadia\";".into()),
|
||||
("shared.arcadia".into(), "// one shared ordinary fragment\n".into()),
|
||||
]),
|
||||
};
|
||||
let original = bundle.clone();
|
||||
// This is the existing initial ordinary pass, before schema migration's
|
||||
// separate output/reparse. It makes no public source8 acceptance claim.
|
||||
let (compiled, insertions) =
|
||||
super::super::compile_once(&bundle, ProjectLimits::default()).unwrap();
|
||||
assert!(insertions.is_empty());
|
||||
assert_eq!(compiled.bundle, original);
|
||||
assert_eq!(compiled.index.declarations.len(), 1);
|
||||
assert_eq!(
|
||||
compiled
|
||||
.index
|
||||
.includes
|
||||
.iter()
|
||||
.map(|i| (i.location.path.as_str(), i.target.as_str()))
|
||||
.collect::<Vec<_>>(),
|
||||
[
|
||||
("main.arcadia", "dir/left.arcadia"),
|
||||
("main.arcadia", "dir/right.arcadia"),
|
||||
("dir/left.arcadia", "shared.arcadia"),
|
||||
("dir/right.arcadia", "shared.arcadia"),
|
||||
]
|
||||
);
|
||||
let cycle = "// 雪\r\ninclude \"main.arcadia\";";
|
||||
bundle.files.insert("shared.arcadia".into(), cycle.into());
|
||||
let before = bundle.clone();
|
||||
let errors = super::super::compile_once(&bundle, ProjectLimits::default()).unwrap_err();
|
||||
assert_eq!(errors[0].diagnostic.code, "include_cycle");
|
||||
assert_eq!(errors[0].path, "shared.arcadia");
|
||||
assert_eq!(errors[0].diagnostic.line, 2);
|
||||
assert_eq!(
|
||||
&cycle[errors[0].diagnostic.span.start..errors[0].diagnostic.span.end],
|
||||
"include \"main.arcadia\";"
|
||||
);
|
||||
assert_eq!(
|
||||
errors[0].diagnostic.message,
|
||||
"Include cycle: main.arcadia -> dir/left.arcadia -> shared.arcadia -> main.arcadia."
|
||||
);
|
||||
assert_eq!(bundle, before);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,352 @@
|
||||
//! Caller-qualified process/chain addresses. Cache residency never affects admission.
|
||||
use crate::*;
|
||||
use std::{
|
||||
cell::RefCell,
|
||||
collections::{BTreeMap, BTreeSet},
|
||||
};
|
||||
|
||||
mod analysis;
|
||||
pub use analysis::*;
|
||||
pub const MAX_REFERENCE_DEPTH: usize = 64;
|
||||
pub const MAX_ANALYSIS_NODES: usize = 50_000;
|
||||
pub const MAX_ANALYSIS_EDGES: usize = 100_000;
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
|
||||
pub struct ContextAddress {
|
||||
pub owner: Id,
|
||||
pub endpoint: OccurrenceEndpoint,
|
||||
}
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct ResolvedOccurrence {
|
||||
pub address: ContextAddress,
|
||||
pub defining_sequence: Id,
|
||||
pub work: Option<Id>,
|
||||
pub exchange: Option<Id>,
|
||||
}
|
||||
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
|
||||
#[error("{message}")]
|
||||
pub struct ContextError {
|
||||
pub code: &'static str,
|
||||
pub message: String,
|
||||
}
|
||||
fn failure(code: &'static str, message: &str) -> ContextError {
|
||||
ContextError {
|
||||
code,
|
||||
message: message.into(),
|
||||
}
|
||||
}
|
||||
struct Record {
|
||||
parent: Option<Id>,
|
||||
layer: Layer,
|
||||
kind: Kind,
|
||||
reference: Option<Id>,
|
||||
work: Option<Id>,
|
||||
exchange: Option<Id>,
|
||||
contribution: bool,
|
||||
}
|
||||
pub struct TopologyIndex<'a> {
|
||||
project: &'a Project,
|
||||
records: BTreeMap<Id, Record>,
|
||||
children: BTreeMap<Id, Vec<Id>>,
|
||||
link_definitions: BTreeMap<Id, Vec<Id>>,
|
||||
contextual_callers: BTreeSet<Id>,
|
||||
cache: RefCell<BTreeMap<ContextAddress, ResolvedOccurrence>>,
|
||||
cache_capacity: usize,
|
||||
}
|
||||
impl<'a> TopologyIndex<'a> {
|
||||
pub fn new(project: &'a Project) -> Self {
|
||||
Self::with_cache_capacity(project, 4096)
|
||||
}
|
||||
pub fn with_cache_capacity(project: &'a Project, cache_capacity: usize) -> Self {
|
||||
let records: BTreeMap<_, _> = project
|
||||
.elements
|
||||
.values()
|
||||
.map(|e| {
|
||||
let (reference, work, exchange, contribution) = match e.shared() {
|
||||
Some(SharedBody::Occurrence { body, .. }) => match body {
|
||||
OccurrenceBody::SequenceReference { sequence } => {
|
||||
(*sequence, None, None, true)
|
||||
}
|
||||
OccurrenceBody::Action { action, .. } => (None, *action, None, true),
|
||||
OccurrenceBody::Exchange { exchange, .. } => (None, None, *exchange, true),
|
||||
OccurrenceBody::Control { .. } => (None, None, None, true),
|
||||
_ => (None, None, None, false),
|
||||
},
|
||||
_ => (None, None, None, false),
|
||||
};
|
||||
(
|
||||
e.id,
|
||||
Record {
|
||||
parent: e.parent,
|
||||
layer: e.layer(),
|
||||
kind: e.kind(),
|
||||
reference,
|
||||
work,
|
||||
exchange,
|
||||
contribution,
|
||||
},
|
||||
)
|
||||
})
|
||||
.collect();
|
||||
let mut children: BTreeMap<_, _> = project
|
||||
.elements
|
||||
.values()
|
||||
.filter_map(|e| e.steps().map(|steps| (e.id, steps.clone())))
|
||||
.collect();
|
||||
let mut child_sets: BTreeMap<_, BTreeSet<_>> = children
|
||||
.iter()
|
||||
.map(|(owner, children)| (*owner, children.iter().copied().collect()))
|
||||
.collect();
|
||||
for (id, record) in &records {
|
||||
if record.contribution
|
||||
&& let Some(parent) = record.parent
|
||||
{
|
||||
let list = children.entry(parent).or_default();
|
||||
if child_sets.entry(parent).or_default().insert(*id) {
|
||||
list.push(*id);
|
||||
}
|
||||
}
|
||||
}
|
||||
for (owner, list) in &mut children {
|
||||
list.retain(|id| {
|
||||
records
|
||||
.get(id)
|
||||
.is_some_and(|r| r.parent == Some(*owner) && r.contribution)
|
||||
});
|
||||
}
|
||||
let mut link_definitions: BTreeMap<_, Vec<_>> = BTreeMap::new();
|
||||
let mut contextual_callers = BTreeSet::new();
|
||||
for relation in project.relations.values() {
|
||||
let owner = relation.contextual_owner().or_else(|| {
|
||||
if relation.kind() == RelationKind::SequenceLink {
|
||||
records.get(&relation.source()).and_then(|r| r.parent)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
});
|
||||
if let Some(owner) = owner {
|
||||
link_definitions.entry(owner).or_default().push(relation.id);
|
||||
}
|
||||
if let Some(owner) = relation.contextual_owner() {
|
||||
contextual_callers.insert(owner);
|
||||
}
|
||||
}
|
||||
let mut callers: BTreeMap<_, Vec<_>> = BTreeMap::new();
|
||||
for record in records.values() {
|
||||
if let (Some(parent), Some(reference)) = (record.parent, record.reference) {
|
||||
callers.entry(reference).or_default().push(parent);
|
||||
}
|
||||
}
|
||||
let mut pending: Vec<_> = contextual_callers.iter().copied().collect();
|
||||
while let Some(sequence) = pending.pop() {
|
||||
for caller in callers.get(&sequence).into_iter().flatten() {
|
||||
if contextual_callers.insert(*caller) {
|
||||
pending.push(*caller);
|
||||
}
|
||||
}
|
||||
}
|
||||
Self {
|
||||
project,
|
||||
records,
|
||||
children,
|
||||
link_definitions,
|
||||
contextual_callers,
|
||||
cache: RefCell::new(BTreeMap::new()),
|
||||
cache_capacity,
|
||||
}
|
||||
}
|
||||
/// Resolve a caller path while an endpoint leaf is still being edited.
|
||||
pub fn resolve_scope(&self, owner: Id, references: &[Id]) -> Result<Id, ContextError> {
|
||||
if references.len() > MAX_REFERENCE_DEPTH {
|
||||
return Err(failure(
|
||||
"context_depth",
|
||||
"A contextual path exceeds 64 references.",
|
||||
));
|
||||
}
|
||||
let root = self.records.get(&owner).ok_or_else(|| {
|
||||
failure(
|
||||
"context_owner",
|
||||
"The caller must be an existing process or functional chain.",
|
||||
)
|
||||
})?;
|
||||
if !matches!(root.kind, Kind::Process | Kind::FunctionalChain) {
|
||||
return Err(failure(
|
||||
"context_owner",
|
||||
"The caller must be a process or functional chain.",
|
||||
));
|
||||
}
|
||||
let mut current = owner;
|
||||
let mut visited = BTreeSet::from([owner]);
|
||||
for step in references {
|
||||
let reference = self.records.get(step).ok_or_else(|| {
|
||||
failure(
|
||||
"context_path",
|
||||
"A reference occurrence in the endpoint path no longer exists.",
|
||||
)
|
||||
})?;
|
||||
if reference.parent != Some(current) || reference.layer != root.layer {
|
||||
return Err(failure(
|
||||
"context_path",
|
||||
"Each reference occurrence must belong directly to the preceding caller context.",
|
||||
));
|
||||
}
|
||||
let next = reference.reference.ok_or_else(|| {
|
||||
failure(
|
||||
"context_path",
|
||||
"Each path component must be a resolved sequence-reference occurrence.",
|
||||
)
|
||||
})?;
|
||||
let target = self.records.get(&next).ok_or_else(|| {
|
||||
failure(
|
||||
"context_path",
|
||||
"A referenced process or chain no longer exists.",
|
||||
)
|
||||
})?;
|
||||
if target.layer != root.layer || target.kind != root.kind {
|
||||
return Err(failure(
|
||||
"context_path",
|
||||
"References must resolve to sequences of the same kind and layer.",
|
||||
));
|
||||
}
|
||||
if !visited.insert(next) {
|
||||
return Err(failure(
|
||||
"context_cycle",
|
||||
"A contextual endpoint cannot traverse recursive sequence reuse.",
|
||||
));
|
||||
}
|
||||
current = next;
|
||||
}
|
||||
Ok(current)
|
||||
}
|
||||
pub fn resolve(
|
||||
&self,
|
||||
owner: Id,
|
||||
endpoint: &OccurrenceEndpoint,
|
||||
) -> Result<ResolvedOccurrence, ContextError> {
|
||||
if endpoint.references.len() > MAX_REFERENCE_DEPTH {
|
||||
return Err(failure(
|
||||
"context_depth",
|
||||
"A contextual endpoint exceeds the 64-reference depth limit.",
|
||||
));
|
||||
}
|
||||
let address = ContextAddress {
|
||||
owner,
|
||||
endpoint: endpoint.clone(),
|
||||
};
|
||||
if let Some(cached) = self.cache.borrow().get(&address) {
|
||||
return Ok(cached.clone());
|
||||
}
|
||||
let current = self.resolve_scope(owner, &endpoint.references)?;
|
||||
let root = &self.records[&owner];
|
||||
let leaf = self.records.get(&endpoint.occurrence).ok_or_else(|| {
|
||||
failure(
|
||||
"context_leaf",
|
||||
"The endpoint contribution no longer exists.",
|
||||
)
|
||||
})?;
|
||||
if leaf.parent != Some(current) || leaf.layer != root.layer || !leaf.contribution {
|
||||
return Err(failure(
|
||||
"context_leaf",
|
||||
"The endpoint must be a direct contribution of its resolved process or chain.",
|
||||
));
|
||||
}
|
||||
let resolved = ResolvedOccurrence {
|
||||
address: address.clone(),
|
||||
defining_sequence: current,
|
||||
work: leaf.work,
|
||||
exchange: leaf.exchange,
|
||||
};
|
||||
if self.cache_capacity > 0 {
|
||||
let mut cache = self.cache.borrow_mut();
|
||||
if cache.len() >= self.cache_capacity {
|
||||
cache.pop_first();
|
||||
}
|
||||
cache.insert(address, resolved.clone());
|
||||
}
|
||||
Ok(resolved)
|
||||
}
|
||||
/// Validate a caller-owned semantic connection, independent of graphical expansion.
|
||||
pub fn validate_link(
|
||||
&self,
|
||||
owner: Id,
|
||||
source: &OccurrenceEndpoint,
|
||||
target: &OccurrenceEndpoint,
|
||||
purpose: &ContextualLinkPurpose,
|
||||
) -> Result<(ResolvedOccurrence, ResolvedOccurrence), ContextError> {
|
||||
let a = self.resolve(owner, source)?;
|
||||
let b = self.resolve(owner, target)?;
|
||||
if a.address == b.address {
|
||||
return Err(failure(
|
||||
"context_self",
|
||||
"A contextual link needs two distinct occurrence addresses.",
|
||||
));
|
||||
}
|
||||
match purpose {
|
||||
ContextualLinkPurpose::Precedence { guard } => {
|
||||
if source.references.is_empty() && target.references.is_empty() {
|
||||
return Err(failure(
|
||||
"context_direct_precedence",
|
||||
"Use a SequenceLink for precedence between two direct contributions.",
|
||||
));
|
||||
}
|
||||
if !validation::valid_text(guard) {
|
||||
return Err(failure(
|
||||
"invalid_text",
|
||||
"The precedence guard contains invalid text.",
|
||||
));
|
||||
}
|
||||
let previous = a.exchange.and_then(|id| self.project.relations.get(&id));
|
||||
let next = b.exchange.and_then(|id| self.project.relations.get(&id));
|
||||
let mismatch = match (a.work, previous, b.work, next) {
|
||||
(Some(work), _, _, Some(exchange)) => work != exchange.source(),
|
||||
(_, Some(exchange), Some(work), _) => exchange.target() != work,
|
||||
(_, Some(previous), _, Some(next)) => previous.target() != next.source(),
|
||||
_ => false,
|
||||
};
|
||||
if mismatch {
|
||||
return Err(failure(
|
||||
"sequence_exchange_endpoint",
|
||||
"Adjacent work/exchange contributions must agree with the referenced exchange endpoints.",
|
||||
));
|
||||
}
|
||||
}
|
||||
ContextualLinkPurpose::Exchange { exchange } => {
|
||||
let relation = self.project.relations.get(exchange).ok_or_else(|| {
|
||||
failure("context_exchange", "Choose an existing work exchange.")
|
||||
})?;
|
||||
let expected = if self.project.layer_of(owner) == Some(Layer::Oa) {
|
||||
RelationKind::Interaction
|
||||
} else {
|
||||
RelationKind::FunctionalExchange
|
||||
};
|
||||
if relation.kind() != expected
|
||||
|| self.project.layer_of(*exchange) != self.project.layer_of(owner)
|
||||
|| a.work != Some(relation.source())
|
||||
|| b.work != Some(relation.target())
|
||||
{
|
||||
return Err(failure(
|
||||
"context_exchange",
|
||||
"The selected same-layer exchange must connect the exact work referenced by the source and target Actions.",
|
||||
));
|
||||
}
|
||||
}
|
||||
ContextualLinkPurpose::CommonWork { work } => {
|
||||
if !self.project.elements.get(work).is_some_and(|e| {
|
||||
e.kind().is_work() && Some(e.layer()) == self.project.layer_of(owner)
|
||||
}) || a.work != Some(*work)
|
||||
|| b.work != Some(*work)
|
||||
{
|
||||
return Err(failure(
|
||||
"context_common_work",
|
||||
"Both Actions must reference the exact same existing work in this layer.",
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok((a, b))
|
||||
}
|
||||
/// Direct child candidates for lazy UI exploration; never expands a Cartesian reuse tree.
|
||||
pub fn contributions(&self, sequence: Id) -> Vec<Id> {
|
||||
self.children.get(&sequence).cloned().unwrap_or_default()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,529 @@
|
||||
use super::*;
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "analysis_tests.rs"]
|
||||
mod tests;
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
|
||||
pub enum ReferenceBoundary {
|
||||
Entry,
|
||||
Exit,
|
||||
}
|
||||
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
|
||||
pub struct ContextVertex {
|
||||
pub address: ContextAddress,
|
||||
pub boundary: Option<ReferenceBoundary>,
|
||||
}
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub enum ContextEdgeKind {
|
||||
Authored,
|
||||
SyntheticBoundary,
|
||||
LegacyOrder,
|
||||
}
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct ContextEdge {
|
||||
pub relation: Option<Id>,
|
||||
pub instance: Vec<Id>,
|
||||
pub source: ContextVertex,
|
||||
pub target: ContextVertex,
|
||||
pub guard: String,
|
||||
pub kind: ContextEdgeKind,
|
||||
}
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct ContextAssembly {
|
||||
pub relation: Id,
|
||||
pub instance: Vec<Id>,
|
||||
pub source: ContextAddress,
|
||||
pub target: ContextAddress,
|
||||
pub purpose: ContextualLinkPurpose,
|
||||
}
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct ContextNotice {
|
||||
pub address: ContextAddress,
|
||||
pub code: &'static str,
|
||||
pub message: String,
|
||||
pub relations: Vec<Id>,
|
||||
}
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
pub struct AnalysisLimits {
|
||||
pub nodes: usize,
|
||||
pub edges: usize,
|
||||
}
|
||||
impl Default for AnalysisLimits {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
nodes: MAX_ANALYSIS_NODES,
|
||||
edges: MAX_ANALYSIS_EDGES,
|
||||
}
|
||||
}
|
||||
}
|
||||
#[derive(Debug, Clone, Default)]
|
||||
pub struct ContextAnalysis {
|
||||
pub nodes: BTreeMap<ContextAddress, ResolvedOccurrence>,
|
||||
pub precedence: Vec<ContextEdge>,
|
||||
pub assembly: Vec<ContextAssembly>,
|
||||
pub entries: Vec<ContextVertex>,
|
||||
pub exits: Vec<ContextVertex>,
|
||||
pub notices: Vec<ContextNotice>,
|
||||
/// A partial expansion must never be used for complete reachability conclusions.
|
||||
pub complete: bool,
|
||||
}
|
||||
struct Builder<'a, 'p> {
|
||||
index: &'a TopologyIndex<'p>,
|
||||
root: Id,
|
||||
limits: AnalysisLimits,
|
||||
result: ContextAnalysis,
|
||||
definitions: BTreeMap<Id, Vec<&'p Relation>>,
|
||||
examined_edges: usize,
|
||||
exhausted: bool,
|
||||
}
|
||||
impl TopologyIndex<'_> {
|
||||
pub fn analyze(&self, owner: Id, limits: AnalysisLimits) -> ContextAnalysis {
|
||||
self.analyze_counted(owner, limits).0
|
||||
}
|
||||
fn analyze_counted(&self, owner: Id, limits: AnalysisLimits) -> (ContextAnalysis, usize) {
|
||||
let mut definitions: BTreeMap<_, Vec<_>> = BTreeMap::new();
|
||||
for (owner, relations) in &self.link_definitions {
|
||||
definitions.insert(
|
||||
*owner,
|
||||
relations
|
||||
.iter()
|
||||
.filter_map(|id| self.project.relations.get(id))
|
||||
.collect(),
|
||||
);
|
||||
}
|
||||
let mut b = Builder {
|
||||
index: self,
|
||||
root: owner,
|
||||
limits,
|
||||
result: ContextAnalysis {
|
||||
complete: true,
|
||||
..ContextAnalysis::default()
|
||||
},
|
||||
definitions,
|
||||
examined_edges: 0,
|
||||
exhausted: false,
|
||||
};
|
||||
(b.result.entries, b.result.exits) = b.expand(owner, &[], &mut BTreeSet::new());
|
||||
if b.result.complete {
|
||||
b.cardinality();
|
||||
b.connectivity();
|
||||
}
|
||||
(b.result, b.examined_edges)
|
||||
}
|
||||
pub fn has_contextual_links(&self, owner: Id) -> bool {
|
||||
self.contextual_callers.contains(&owner)
|
||||
}
|
||||
}
|
||||
impl Builder<'_, '_> {
|
||||
fn address(&self, path: &[Id], occurrence: Id) -> ContextAddress {
|
||||
ContextAddress {
|
||||
owner: self.root,
|
||||
endpoint: OccurrenceEndpoint {
|
||||
references: path.to_vec(),
|
||||
occurrence,
|
||||
},
|
||||
}
|
||||
}
|
||||
fn vertex(&self, address: ContextAddress, source: bool) -> ContextVertex {
|
||||
let reference = self
|
||||
.index
|
||||
.project
|
||||
.elements
|
||||
.get(&address.endpoint.occurrence)
|
||||
.and_then(Element::shared)
|
||||
.is_some_and(|s| {
|
||||
matches!(
|
||||
s,
|
||||
SharedBody::Occurrence {
|
||||
body: OccurrenceBody::SequenceReference { .. },
|
||||
..
|
||||
}
|
||||
)
|
||||
});
|
||||
ContextVertex {
|
||||
address,
|
||||
boundary: reference.then_some(if source {
|
||||
ReferenceBoundary::Exit
|
||||
} else {
|
||||
ReferenceBoundary::Entry
|
||||
}),
|
||||
}
|
||||
}
|
||||
fn incomplete(&mut self, address: ContextAddress, code: &'static str, message: &str) {
|
||||
self.result.complete = false;
|
||||
if !self
|
||||
.result
|
||||
.notices
|
||||
.iter()
|
||||
.any(|n| n.address == address && n.code == code)
|
||||
{
|
||||
self.result.notices.push(ContextNotice {
|
||||
address,
|
||||
code,
|
||||
message: message.into(),
|
||||
relations: vec![],
|
||||
});
|
||||
}
|
||||
}
|
||||
// Reserve work before resolving an authored endpoint, not merely before storing
|
||||
// its output. Repeated malformed or filtered endpoints consume the same budget.
|
||||
fn reserve_edge(&mut self, address: ContextAddress) -> bool {
|
||||
if self.exhausted {
|
||||
return false;
|
||||
}
|
||||
if self.examined_edges >= self.limits.edges {
|
||||
self.exhausted = true;
|
||||
self.incomplete(
|
||||
address,
|
||||
"context_analysis_limit",
|
||||
"Contextual edge limit reached; connectivity analysis is incomplete.",
|
||||
);
|
||||
return false;
|
||||
}
|
||||
self.examined_edges += 1;
|
||||
true
|
||||
}
|
||||
fn edge(&mut self, edge: ContextEdge) -> bool {
|
||||
if !self.reserve_edge(edge.source.address.clone()) {
|
||||
return false;
|
||||
}
|
||||
self.result.precedence.push(edge);
|
||||
true
|
||||
}
|
||||
fn expand(
|
||||
&mut self,
|
||||
sequence: Id,
|
||||
prefix: &[Id],
|
||||
active: &mut BTreeSet<Id>,
|
||||
) -> (Vec<ContextVertex>, Vec<ContextVertex>) {
|
||||
if self.exhausted {
|
||||
return (vec![], vec![]);
|
||||
}
|
||||
if prefix.len() > MAX_REFERENCE_DEPTH || !active.insert(sequence) {
|
||||
self.incomplete(
|
||||
self.address(prefix, sequence),
|
||||
"context_analysis_incomplete",
|
||||
"Recursive or over-depth reuse has no proven boundary path.",
|
||||
);
|
||||
return (vec![], vec![]);
|
||||
}
|
||||
let children = self.index.contributions(sequence);
|
||||
if children.is_empty() {
|
||||
self.incomplete(
|
||||
self.address(prefix, sequence),
|
||||
"context_analysis_incomplete",
|
||||
"An empty or unresolved sequence has no proven boundary path.",
|
||||
);
|
||||
active.remove(&sequence);
|
||||
return (vec![], vec![]);
|
||||
}
|
||||
let start = self.result.precedence.len();
|
||||
for id in &children {
|
||||
let address = self.address(prefix, *id);
|
||||
if self.result.nodes.len() >= self.limits.nodes {
|
||||
self.exhausted = true;
|
||||
self.incomplete(
|
||||
address,
|
||||
"context_analysis_limit",
|
||||
"Contextual node limit reached; connectivity analysis is incomplete.",
|
||||
);
|
||||
break;
|
||||
}
|
||||
match self.index.resolve(self.root, &address.endpoint) {
|
||||
Ok(resolved) => {
|
||||
self.result.nodes.insert(address.clone(), resolved);
|
||||
}
|
||||
Err(e) => {
|
||||
self.incomplete(address, "context_analysis_incomplete", &e.message);
|
||||
continue;
|
||||
}
|
||||
}
|
||||
let reference = self.index.project.elements[id]
|
||||
.shared()
|
||||
.and_then(|s| match s {
|
||||
SharedBody::Occurrence {
|
||||
body: OccurrenceBody::SequenceReference { sequence },
|
||||
..
|
||||
} => Some(*sequence),
|
||||
_ => None,
|
||||
});
|
||||
if let Some(reference) = reference {
|
||||
let Some(callee) = reference else {
|
||||
self.incomplete(
|
||||
address,
|
||||
"context_analysis_incomplete",
|
||||
"An unresolved reference has no proven boundary path.",
|
||||
);
|
||||
continue;
|
||||
};
|
||||
let mut path = prefix.to_vec();
|
||||
path.push(*id);
|
||||
let (entries, exits) = self.expand(callee, &path, active);
|
||||
if self.exhausted {
|
||||
active.remove(&sequence);
|
||||
return (vec![], vec![]);
|
||||
}
|
||||
if entries.is_empty() || exits.is_empty() {
|
||||
self.incomplete(
|
||||
address.clone(),
|
||||
"context_analysis_incomplete",
|
||||
"No referenced entry or exit is proven; no bypass is inferred.",
|
||||
);
|
||||
}
|
||||
for target in entries {
|
||||
if !self.edge(ContextEdge {
|
||||
relation: None,
|
||||
instance: prefix.to_vec(),
|
||||
source: self.vertex(address.clone(), false),
|
||||
target,
|
||||
guard: String::new(),
|
||||
kind: ContextEdgeKind::SyntheticBoundary,
|
||||
}) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
for source in exits {
|
||||
if !self.edge(ContextEdge {
|
||||
relation: None,
|
||||
instance: prefix.to_vec(),
|
||||
source,
|
||||
target: self.vertex(address.clone(), true),
|
||||
guard: String::new(),
|
||||
kind: ContextEdgeKind::SyntheticBoundary,
|
||||
}) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
if self.exhausted {
|
||||
break;
|
||||
}
|
||||
}
|
||||
if self.exhausted {
|
||||
active.remove(&sequence);
|
||||
return (vec![], vec![]);
|
||||
}
|
||||
let relations = self.definitions.get(&sequence).cloned().unwrap_or_default();
|
||||
for r in &relations {
|
||||
if !self.reserve_edge(self.address(prefix, r.source())) {
|
||||
break;
|
||||
}
|
||||
let (source, target, purpose) = match &r.body {
|
||||
RelationBody::SequenceLink {
|
||||
source,
|
||||
target,
|
||||
guard,
|
||||
} => (
|
||||
OccurrenceEndpoint {
|
||||
references: vec![],
|
||||
occurrence: *source,
|
||||
},
|
||||
OccurrenceEndpoint {
|
||||
references: vec![],
|
||||
occurrence: *target,
|
||||
},
|
||||
ContextualLinkPurpose::Precedence {
|
||||
guard: guard.clone(),
|
||||
},
|
||||
),
|
||||
RelationBody::ContextualLink {
|
||||
source,
|
||||
target,
|
||||
purpose,
|
||||
..
|
||||
} => (source.clone(), target.clone(), purpose.clone()),
|
||||
_ => continue,
|
||||
};
|
||||
let qualify = |mut endpoint: OccurrenceEndpoint| {
|
||||
let mut path = prefix.to_vec();
|
||||
path.extend(endpoint.references);
|
||||
endpoint.references = path;
|
||||
ContextAddress {
|
||||
owner: self.root,
|
||||
endpoint,
|
||||
}
|
||||
};
|
||||
let source = qualify(source);
|
||||
let target = qualify(target);
|
||||
if !self.result.nodes.contains_key(&source) || !self.result.nodes.contains_key(&target)
|
||||
{
|
||||
self.incomplete(
|
||||
source,
|
||||
"context_analysis_incomplete",
|
||||
"A link endpoint is unresolved in this bounded analysis.",
|
||||
);
|
||||
continue;
|
||||
}
|
||||
match purpose {
|
||||
ContextualLinkPurpose::Precedence { guard } => {
|
||||
self.result.precedence.push(ContextEdge {
|
||||
relation: Some(r.id),
|
||||
instance: prefix.to_vec(),
|
||||
source: self.vertex(source, true),
|
||||
target: self.vertex(target, false),
|
||||
guard,
|
||||
kind: ContextEdgeKind::Authored,
|
||||
})
|
||||
}
|
||||
purpose => {
|
||||
self.result.assembly.push(ContextAssembly {
|
||||
relation: r.id,
|
||||
instance: prefix.to_vec(),
|
||||
source,
|
||||
target,
|
||||
purpose,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
if self.exhausted {
|
||||
active.remove(&sequence);
|
||||
return (vec![], vec![]);
|
||||
}
|
||||
if relations.is_empty()
|
||||
&& children.iter().all(|id| {
|
||||
matches!(
|
||||
self.index.project.elements[id].shared(),
|
||||
Some(SharedBody::Occurrence {
|
||||
body: OccurrenceBody::Exchange { .. },
|
||||
..
|
||||
})
|
||||
)
|
||||
})
|
||||
{
|
||||
for pair in children.windows(2) {
|
||||
if !self.edge(ContextEdge {
|
||||
relation: None,
|
||||
instance: prefix.to_vec(),
|
||||
source: self.vertex(self.address(prefix, pair[0]), true),
|
||||
target: self.vertex(self.address(prefix, pair[1]), false),
|
||||
guard: String::new(),
|
||||
kind: ContextEdgeKind::LegacyOrder,
|
||||
}) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
if self.exhausted {
|
||||
active.remove(&sequence);
|
||||
return (vec![], vec![]);
|
||||
}
|
||||
// Intrinsic boundaries are determined before any enclosing caller links.
|
||||
let edges = &self.result.precedence[start..];
|
||||
let targets: BTreeSet<_> = edges.iter().map(|e| &e.target).collect();
|
||||
let sources: BTreeSet<_> = edges.iter().map(|e| &e.source).collect();
|
||||
let entries = children
|
||||
.iter()
|
||||
.map(|id| self.vertex(self.address(prefix, *id), false))
|
||||
.filter(|v| !targets.contains(v))
|
||||
.collect();
|
||||
let exits = children
|
||||
.iter()
|
||||
.map(|id| self.vertex(self.address(prefix, *id), true))
|
||||
.filter(|v| !sources.contains(v))
|
||||
.collect();
|
||||
active.remove(&sequence);
|
||||
(entries, exits)
|
||||
}
|
||||
fn cardinality(&mut self) {
|
||||
// Index authored incidence once; synthetic boundaries never count as controls.
|
||||
let mut incoming: BTreeMap<_, Vec<_>> = BTreeMap::new();
|
||||
let mut outgoing: BTreeMap<_, Vec<_>> = BTreeMap::new();
|
||||
for edge in &self.result.precedence {
|
||||
if edge.kind == ContextEdgeKind::Authored {
|
||||
incoming.entry(&edge.target.address).or_default().push(edge);
|
||||
outgoing.entry(&edge.source.address).or_default().push(edge);
|
||||
}
|
||||
}
|
||||
for address in self.result.nodes.keys() {
|
||||
let ins = incoming.get(address).cloned().unwrap_or_default();
|
||||
let outs = outgoing.get(address).cloned().unwrap_or_default();
|
||||
let before = ins.len();
|
||||
let after = outs.len();
|
||||
let control = match self.index.project.elements[&address.endpoint.occurrence].shared() {
|
||||
Some(SharedBody::Occurrence {
|
||||
body: OccurrenceBody::Control { kind },
|
||||
..
|
||||
}) => Some(*kind),
|
||||
_ => None,
|
||||
};
|
||||
let issue = match control {
|
||||
Some(kind) => { let valid = match kind { ControlKind::Choice | ControlKind::Fork => before == 1 && after >= 2, ControlKind::Merge | ControlKind::Join => before >= 2 && after == 1, ControlKind::Loop => before >= 1 && after >= 2 }; (!valid).then_some(("control_cardinality", format!("{kind:?} has {before} incoming and {after} outgoing authored precedence links in this caller context. Review the intended paths."))) }
|
||||
None => (before > 1 || after > 1).then_some(("ambiguous_sequence_branch", "This contribution has multiple incoming or outgoing precedence links in this caller context. Review whether explicit merge/join or branching control is needed to describe the intended paths.".into())),
|
||||
};
|
||||
if let Some((code, message)) = issue {
|
||||
self.result.notices.push(ContextNotice {
|
||||
address: address.clone(),
|
||||
code,
|
||||
message,
|
||||
relations: ins.iter().chain(&outs).filter_map(|e| e.relation).collect(),
|
||||
});
|
||||
}
|
||||
if matches!(control, Some(ControlKind::Choice | ControlKind::Loop)) {
|
||||
for edge in outs.iter().filter(|e| e.guard.trim().is_empty()) {
|
||||
self.result.notices.push(ContextNotice { address: address.clone(), code: "missing_sequence_guard", message: "Describe the choice/loop condition for this path, or use an explicit 'else' guard.".into(), relations: edge.relation.into_iter().collect() });
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
fn connectivity(&mut self) {
|
||||
let mut forward: BTreeMap<_, Vec<_>> = BTreeMap::new();
|
||||
let mut reverse: BTreeMap<_, Vec<_>> = BTreeMap::new();
|
||||
for edge in &self.result.precedence {
|
||||
forward
|
||||
.entry(edge.source.clone())
|
||||
.or_default()
|
||||
.push(edge.target.clone());
|
||||
reverse
|
||||
.entry(edge.target.clone())
|
||||
.or_default()
|
||||
.push(edge.source.clone());
|
||||
}
|
||||
let visit = |starts: &[ContextVertex],
|
||||
graph: &BTreeMap<ContextVertex, Vec<ContextVertex>>| {
|
||||
let mut pending = starts.to_vec();
|
||||
let mut seen = BTreeSet::new();
|
||||
while let Some(vertex) = pending.pop() {
|
||||
if seen.insert(vertex.clone()) {
|
||||
pending.extend(graph.get(&vertex).into_iter().flatten().cloned());
|
||||
}
|
||||
}
|
||||
seen
|
||||
};
|
||||
let from_start = visit(&self.result.entries, &forward);
|
||||
let to_end = visit(&self.result.exits, &reverse);
|
||||
for address in self.result.nodes.keys() {
|
||||
let entry = self.vertex(address.clone(), false);
|
||||
let exit = self.vertex(address.clone(), true);
|
||||
for (missing, code, message) in [
|
||||
(
|
||||
!from_start.contains(&entry),
|
||||
"unreachable_contribution",
|
||||
"No path from a structural caller entry reaches this contribution in this context.",
|
||||
),
|
||||
(
|
||||
!to_end.contains(&exit),
|
||||
"nonterminating_contribution",
|
||||
"No structural caller exit is reachable from this contribution in this context; review the intended loop.",
|
||||
),
|
||||
(
|
||||
self.result.nodes.len() > 1
|
||||
&& !reverse.contains_key(&entry)
|
||||
&& !forward.contains_key(&exit),
|
||||
"isolated_contribution",
|
||||
"This contribution has no incoming or outgoing precedence path in this caller context; assembly incidence is separate.",
|
||||
),
|
||||
] {
|
||||
if missing {
|
||||
self.result.notices.push(ContextNotice {
|
||||
address: address.clone(),
|
||||
code,
|
||||
message: message.into(),
|
||||
relations: vec![],
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,172 @@
|
||||
use super::*;
|
||||
|
||||
fn occurrence(p: &mut Project, owner: Id, name: &str, body: OccurrenceBody) -> Id {
|
||||
let id = p
|
||||
.add_element(Kind::Occurrence, Layer::Sa, name, Some(owner))
|
||||
.unwrap();
|
||||
*p.elements.get_mut(&id).unwrap().shared_mut().unwrap() = SharedBody::Occurrence {
|
||||
body,
|
||||
precondition: String::new(),
|
||||
postcondition: String::new(),
|
||||
};
|
||||
p.elements
|
||||
.get_mut(&owner)
|
||||
.unwrap()
|
||||
.steps_mut()
|
||||
.unwrap()
|
||||
.push(id);
|
||||
id
|
||||
}
|
||||
|
||||
fn repeated(references: usize, links: usize) -> (Project, Id, Id) {
|
||||
let mut p = Project::empty();
|
||||
let root = p
|
||||
.add_element(Kind::FunctionalChain, Layer::Sa, "Caller", None)
|
||||
.unwrap();
|
||||
let procedure = p
|
||||
.add_element(Kind::FunctionalChain, Layer::Sa, "Reusable procedure", None)
|
||||
.unwrap();
|
||||
let mut leaves = Vec::new();
|
||||
for name in ["A", "B"] {
|
||||
let action = p
|
||||
.add_element(Kind::Function, Layer::Sa, name, None)
|
||||
.unwrap();
|
||||
leaves.push(occurrence(
|
||||
&mut p,
|
||||
procedure,
|
||||
name,
|
||||
OccurrenceBody::Action {
|
||||
action: Some(action),
|
||||
lifeline: None,
|
||||
},
|
||||
));
|
||||
}
|
||||
for _ in 0..links {
|
||||
p.relate(
|
||||
RelationKind::SequenceLink,
|
||||
"Authored A to B",
|
||||
leaves[0],
|
||||
leaves[1],
|
||||
);
|
||||
}
|
||||
for _ in 0..references {
|
||||
occurrence(
|
||||
&mut p,
|
||||
root,
|
||||
"Reuse",
|
||||
OccurrenceBody::SequenceReference {
|
||||
sequence: Some(procedure),
|
||||
},
|
||||
);
|
||||
}
|
||||
(p, root, procedure)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn edge_work_budget_stops_repeated_expansion_not_just_output_storage() {
|
||||
// Only ~3,000 possible contribution nodes, but a million authored edge
|
||||
// instances. The edge budget must stop actual work before later references.
|
||||
let (p, root, _) = repeated(1_000, 1_000);
|
||||
let limits = AnalysisLimits::default();
|
||||
let index = TopologyIndex::with_cache_capacity(&p, 1);
|
||||
let (first, attempts) = index.analyze_counted(root, limits);
|
||||
assert_eq!(attempts, limits.edges);
|
||||
assert_eq!(first.precedence.len(), limits.edges);
|
||||
assert!(!first.complete);
|
||||
assert!(first.entries.is_empty() && first.exits.is_empty());
|
||||
assert!(
|
||||
first.nodes.len() < 1_000,
|
||||
"later caller references must not be expanded"
|
||||
);
|
||||
assert_eq!(
|
||||
first
|
||||
.notices
|
||||
.iter()
|
||||
.filter(|n| n.code == "context_analysis_limit")
|
||||
.count(),
|
||||
1
|
||||
);
|
||||
assert!(
|
||||
first
|
||||
.notices
|
||||
.iter()
|
||||
.all(|n| n.code == "context_analysis_limit")
|
||||
);
|
||||
let (warm, warm_attempts) = index.analyze_counted(root, limits);
|
||||
assert_eq!(warm_attempts, attempts);
|
||||
assert_eq!(warm.nodes, first.nodes);
|
||||
assert_eq!(warm.precedence, first.precedence);
|
||||
assert_eq!(warm.notices, first.notices);
|
||||
drop(warm);
|
||||
let (uncached, uncached_attempts) =
|
||||
TopologyIndex::with_cache_capacity(&p, 0).analyze_counted(root, limits);
|
||||
assert_eq!(uncached_attempts, attempts);
|
||||
assert_eq!(uncached.precedence, first.precedence);
|
||||
assert_eq!(uncached.notices, first.notices);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn unresolved_authored_edges_consume_work_budget_without_stored_output() {
|
||||
let (mut p, root, _) = repeated(20, 100);
|
||||
let missing = Id::nil();
|
||||
for relation in p.relations.values_mut() {
|
||||
relation.body.set_endpoints(relation.source(), missing);
|
||||
}
|
||||
let (result, attempts) = TopologyIndex::new(&p).analyze_counted(
|
||||
root,
|
||||
AnalysisLimits {
|
||||
nodes: 1_000,
|
||||
edges: 17,
|
||||
},
|
||||
);
|
||||
assert_eq!(attempts, 17);
|
||||
assert!(result.precedence.is_empty());
|
||||
assert_eq!(result.nodes.len(), 3);
|
||||
assert!(!result.complete);
|
||||
assert!(result.entries.is_empty() && result.exits.is_empty());
|
||||
assert_eq!(
|
||||
result
|
||||
.notices
|
||||
.iter()
|
||||
.filter(|n| n.code == "context_analysis_limit")
|
||||
.count(),
|
||||
1
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn exact_edge_budget_includes_reference_boundaries_and_node_abort_has_no_bypass() {
|
||||
let (p, root, _) = repeated(1, 2);
|
||||
let index = TopologyIndex::new(&p);
|
||||
let (complete, count) = index.analyze_counted(root, AnalysisLimits { nodes: 3, edges: 4 });
|
||||
assert!(complete.complete);
|
||||
assert_eq!(count, 4); // two authored edges plus entry and exit connectors
|
||||
assert_eq!(
|
||||
complete
|
||||
.precedence
|
||||
.iter()
|
||||
.filter(|e| e.kind == ContextEdgeKind::SyntheticBoundary)
|
||||
.count(),
|
||||
2
|
||||
);
|
||||
for limits in [
|
||||
AnalysisLimits { nodes: 3, edges: 3 },
|
||||
AnalysisLimits {
|
||||
nodes: 1,
|
||||
edges: 10,
|
||||
},
|
||||
] {
|
||||
let (partial, count) = index.analyze_counted(root, limits);
|
||||
assert!(!partial.complete);
|
||||
assert!(partial.entries.is_empty() && partial.exits.is_empty());
|
||||
assert!(count <= limits.edges);
|
||||
assert_eq!(
|
||||
partial
|
||||
.notices
|
||||
.iter()
|
||||
.filter(|n| n.code == "context_analysis_limit")
|
||||
.count(),
|
||||
1
|
||||
);
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,8 @@
|
||||
use crate::*;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::collections::{BTreeMap, BTreeSet};
|
||||
mod communication;
|
||||
pub(crate) use communication::review_endpoint_fact;
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub enum TransitionDirection {
|
||||
@@ -53,6 +55,36 @@ pub struct FieldResolution {
|
||||
pub field: TransitionField,
|
||||
pub decision: FieldDecision,
|
||||
}
|
||||
/// Technical endpoint choices are scoped to one OA exchange. Participant
|
||||
/// correspondence remains in `mappings`, never in these port identities.
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub enum CommunicationPortChoice {
|
||||
Reuse {
|
||||
port: Id,
|
||||
},
|
||||
Create {
|
||||
id: Id,
|
||||
alias: String,
|
||||
name: String,
|
||||
description: String,
|
||||
kind: ComponentPortKind,
|
||||
orientation: ComponentPortOrientation,
|
||||
},
|
||||
}
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct CommunicationEndpointDecision {
|
||||
pub source: Id,
|
||||
pub source_port: CommunicationPortChoice,
|
||||
pub target_port: CommunicationPortChoice,
|
||||
}
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct OperationOmission {
|
||||
pub source: Id,
|
||||
pub rationale: String,
|
||||
}
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub struct TransitionRequest {
|
||||
@@ -63,6 +95,10 @@ pub struct TransitionRequest {
|
||||
pub fields: Vec<TransitionField>,
|
||||
pub resolutions: Vec<FieldResolution>,
|
||||
pub destination_diagram: Option<Id>,
|
||||
#[serde(default)]
|
||||
pub communication_endpoints: Vec<CommunicationEndpointDecision>,
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub operation_omissions: Vec<OperationOmission>,
|
||||
}
|
||||
impl TransitionRequest {
|
||||
pub fn new(direction: TransitionDirection, sources: Vec<Id>) -> Self {
|
||||
@@ -74,6 +110,8 @@ impl TransitionRequest {
|
||||
fields: vec![TransitionField::Name, TransitionField::Description],
|
||||
resolutions: vec![],
|
||||
destination_diagram: None,
|
||||
communication_endpoints: vec![],
|
||||
operation_omissions: vec![],
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -177,6 +215,7 @@ fn inferred_kind(kind: Kind, direction: TransitionDirection) -> Option<Kind> {
|
||||
|| matches!(
|
||||
k,
|
||||
Kind::ExchangeItem
|
||||
| Kind::ExchangeCategory
|
||||
| Kind::DataType
|
||||
| Kind::DataField
|
||||
| Kind::Interface
|
||||
@@ -255,6 +294,28 @@ fn mapped_relation(r: &Relation, direction: TransitionDirection) -> Option<Relat
|
||||
items: items.clone(),
|
||||
}
|
||||
}
|
||||
(
|
||||
RelationBody::CommunicationMean {
|
||||
oriented, items, ..
|
||||
},
|
||||
TransitionDirection::OaToSa,
|
||||
) => RelationBody::BoundaryExchange {
|
||||
source,
|
||||
target,
|
||||
oriented: *oriented,
|
||||
items: items.clone(),
|
||||
},
|
||||
(
|
||||
RelationBody::BoundaryExchange {
|
||||
oriented, items, ..
|
||||
},
|
||||
TransitionDirection::SaToOa,
|
||||
) => RelationBody::CommunicationMean {
|
||||
source,
|
||||
target,
|
||||
oriented: *oriented,
|
||||
items: items.clone(),
|
||||
},
|
||||
(
|
||||
RelationBody::Allocation { .. }
|
||||
| RelationBody::InterfaceItemAllocation { .. }
|
||||
@@ -267,6 +328,7 @@ fn mapped_relation(r: &Relation, direction: TransitionDirection) -> Option<Relat
|
||||
| RelationBody::MissionInvolvement { .. }
|
||||
| RelationBody::MissionCapability { .. }
|
||||
| RelationBody::SequenceLink { .. }
|
||||
| RelationBody::ContextualLink { .. }
|
||||
| RelationBody::ChainInvolvement { .. }
|
||||
| RelationBody::BoundaryExchange { .. }
|
||||
| RelationBody::InterfaceProvision { .. }
|
||||
@@ -318,7 +380,7 @@ fn trace_kind(p: &Project, oa: Id, sa: Id) -> TraceKind {
|
||||
_ => TraceKind::Manual,
|
||||
},
|
||||
_ => {
|
||||
if matches!((p.relations.get(&oa),p.relations.get(&sa)),(Some(a),Some(b))if a.kind()==RelationKind::Interaction&&b.kind()==RelationKind::FunctionalExchange)
|
||||
if matches!((p.relations.get(&oa),p.relations.get(&sa)),(Some(a),Some(b))if exchange_counterparts(a.kind(), b.kind()))
|
||||
{
|
||||
TraceKind::Exchange
|
||||
} else {
|
||||
@@ -349,11 +411,12 @@ fn sa_port_omissions(p: &Project) -> BTreeSet<Id> {
|
||||
.collect();
|
||||
loop {
|
||||
let before = omitted.len();
|
||||
for r in p
|
||||
.relations
|
||||
.values()
|
||||
.filter(|r| r.kind() != RelationKind::FunctionalExchange)
|
||||
{
|
||||
for r in p.relations.values().filter(|r| {
|
||||
!matches!(
|
||||
r.kind(),
|
||||
RelationKind::FunctionalExchange | RelationKind::BoundaryExchange
|
||||
)
|
||||
}) {
|
||||
if crate::references::relation_references(r)
|
||||
.iter()
|
||||
.any(|id| omitted.contains(id))
|
||||
@@ -386,6 +449,13 @@ pub fn plan_transition(
|
||||
request: &TransitionRequest,
|
||||
) -> Result<TransitionPlan, ModelError> {
|
||||
validate_candidate(project)?;
|
||||
let is_analysis = |id: &Id| project.elements.get(id).is_some_and(|element| element.kind().is_analysis());
|
||||
if request.sources.iter().any(is_analysis)
|
||||
|| request.mappings.iter().any(|mapping| is_analysis(&mapping.source)
|
||||
|| mapping.target.as_ref().is_some_and(is_analysis)
|
||||
|| mapping.target_kind.is_some_and(Kind::is_analysis)) {
|
||||
return Err(ModelError("Analysis transition semantics are not implemented; copying or reviewing only record headers is refused.".into()));
|
||||
}
|
||||
let mut plan = TransitionPlan {
|
||||
base_fingerprint: project_fingerprint(project),
|
||||
request: request.clone(),
|
||||
@@ -395,11 +465,30 @@ pub fn plan_transition(
|
||||
commands: vec![],
|
||||
};
|
||||
let mut selected: BTreeSet<_> = request.sources.iter().copied().collect();
|
||||
let omitted = if request.direction == TransitionDirection::SaToOa {
|
||||
let mut omitted = if request.direction == TransitionDirection::SaToOa {
|
||||
sa_port_omissions(project)
|
||||
} else {
|
||||
BTreeSet::new()
|
||||
};
|
||||
// An explicit existing Legacy counterpart can be compared and reviewed
|
||||
// without inventing an OA typed port. Only this port is retained: dependent
|
||||
// SA implementation records and new counterpart requests stay omitted.
|
||||
for mapping in &request.mappings {
|
||||
if project
|
||||
.elements
|
||||
.get(&mapping.source)
|
||||
.is_some_and(|e| e.layer() == Layer::Sa && crate::ports::port_contract(e).is_some())
|
||||
&& mapping
|
||||
.target
|
||||
.and_then(|target| project.elements.get(&target))
|
||||
.is_some_and(|e| {
|
||||
e.layer() == Layer::Oa
|
||||
&& crate::ports::port_contract(e) == Some(&PortContract::Legacy)
|
||||
})
|
||||
{
|
||||
omitted.remove(&mapping.source);
|
||||
}
|
||||
}
|
||||
let mut reported_omissions = BTreeSet::new();
|
||||
if selected.len() != request.sources.len() {
|
||||
conflict(
|
||||
@@ -428,7 +517,16 @@ pub fn plan_transition(
|
||||
continue;
|
||||
}
|
||||
if let Some(e) = project.elements.get(&id) {
|
||||
selected.extend(crate::references::element_references(e));
|
||||
let mut dependencies = e.clone();
|
||||
if request.direction == TransitionDirection::SaToOa
|
||||
&& let Some(SharedBody::Occurrence {
|
||||
body: OccurrenceBody::Exchange { operation, .. },
|
||||
..
|
||||
}) = dependencies.shared_mut()
|
||||
{
|
||||
*operation = None;
|
||||
}
|
||||
selected.extend(crate::references::element_references(&dependencies));
|
||||
// Allocations are owned by interfaces. Independent data
|
||||
// associations travel only when both endpoint types are
|
||||
// already required; they do not expand the dictionary.
|
||||
@@ -451,12 +549,13 @@ pub fn plan_transition(
|
||||
// their endpoint involvements, independently of list order.
|
||||
if matches!(e.kind(), Kind::Process | Kind::FunctionalChain) {
|
||||
selected.extend(project.relations.values().filter_map(|relation| {
|
||||
(relation.kind() == RelationKind::SequenceLink
|
||||
&& project
|
||||
.elements
|
||||
.get(&relation.source())
|
||||
.and_then(|e| e.parent)
|
||||
== Some(id))
|
||||
(relation.contextual_owner() == Some(id)
|
||||
|| (relation.kind() == RelationKind::SequenceLink
|
||||
&& project
|
||||
.elements
|
||||
.get(&relation.source())
|
||||
.and_then(|e| e.parent)
|
||||
== Some(id)))
|
||||
.then_some(relation.id)
|
||||
}));
|
||||
}
|
||||
@@ -480,6 +579,15 @@ pub fn plan_transition(
|
||||
}
|
||||
} else if let Some(r) = project.relations.get(&id) {
|
||||
if request.direction == TransitionDirection::SaToOa
|
||||
&& r.kind() == RelationKind::BoundaryExchange
|
||||
{
|
||||
selected.extend(
|
||||
[r.source(), r.target()].into_iter().filter_map(|port| {
|
||||
project.elements.get(&port).and_then(|e| e.parent)
|
||||
}),
|
||||
);
|
||||
selected.extend(r.body.items());
|
||||
} else if request.direction == TransitionDirection::SaToOa
|
||||
&& let RelationBody::FunctionalExchange {
|
||||
source,
|
||||
target,
|
||||
@@ -507,12 +615,76 @@ pub fn plan_transition(
|
||||
}
|
||||
}
|
||||
}
|
||||
if selected.iter().any(is_analysis) {
|
||||
return Err(ModelError("Transition dependency closure includes analysis records; explicit analysis transition semantics are required.".into()));
|
||||
}
|
||||
selected.retain(|id| {
|
||||
if omitted.contains(id) {
|
||||
if reported_omissions.insert(*id) { plan.warnings.push(format!("SA-only omission: {} ({id}) has no OA port counterpart; the original is preserved.", project.named(*id))); }
|
||||
false
|
||||
} else { true }
|
||||
});
|
||||
let mut operation_omissions = BTreeSet::new();
|
||||
for decision in &request.operation_omissions {
|
||||
if request.direction != TransitionDirection::SaToOa
|
||||
|| !selected.contains(&decision.source)
|
||||
|| !matches!(
|
||||
project
|
||||
.elements
|
||||
.get(&decision.source)
|
||||
.and_then(Element::shared),
|
||||
Some(SharedBody::Occurrence {
|
||||
body: OccurrenceBody::Exchange {
|
||||
operation: Some(_),
|
||||
message_kind: MessageKind::Call | MessageKind::Asynchronous,
|
||||
..
|
||||
},
|
||||
..
|
||||
})
|
||||
)
|
||||
|| decision.rationale.trim().is_empty()
|
||||
|| !validation::valid_text(&decision.rationale)
|
||||
|| !operation_omissions.insert(decision.source)
|
||||
{
|
||||
conflict(
|
||||
&mut plan,
|
||||
Some(decision.source),
|
||||
None,
|
||||
None,
|
||||
"Operation omission needs one selected SA invocation, SA→OA direction, and a nonempty rationale; irrelevant or duplicate decisions reject.",
|
||||
);
|
||||
} else {
|
||||
plan.warnings.push(format!(
|
||||
"Reviewed operation omission: {} ({}): {}. Source contract is preserved.",
|
||||
project.named(decision.source),
|
||||
decision.source,
|
||||
decision.rationale
|
||||
));
|
||||
}
|
||||
}
|
||||
if request.direction == TransitionDirection::SaToOa {
|
||||
for source in &selected {
|
||||
if matches!(
|
||||
project.elements.get(source).and_then(Element::shared),
|
||||
Some(SharedBody::Occurrence {
|
||||
body: OccurrenceBody::Exchange {
|
||||
operation: Some(_),
|
||||
..
|
||||
},
|
||||
..
|
||||
})
|
||||
) && !operation_omissions.contains(source)
|
||||
{
|
||||
conflict(
|
||||
&mut plan,
|
||||
Some(*source),
|
||||
None,
|
||||
None,
|
||||
"This technical operation has no OA operation slot. Review an explicit per-invocation omission with rationale; Reply derives the Call's decision.",
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut choices = BTreeMap::new();
|
||||
for mapping in &request.mappings {
|
||||
if choices.insert(mapping.source, mapping).is_some() {
|
||||
@@ -676,6 +848,8 @@ pub fn plan_transition(
|
||||
}
|
||||
}
|
||||
let mut working = project.clone();
|
||||
let communication_pairs =
|
||||
communication::prepare_ports(project, &mut working, &targets, &mut plan);
|
||||
let ordered_creations: Vec<_> = selected
|
||||
.iter()
|
||||
.filter(|id| creating.contains(id) && project.elements.contains_key(id))
|
||||
@@ -704,6 +878,15 @@ pub fn plan_transition(
|
||||
let mut created = e.clone();
|
||||
created.id = target;
|
||||
created.body = body;
|
||||
if request.direction == TransitionDirection::SaToOa
|
||||
&& operation_omissions.contains(source)
|
||||
&& let Some(SharedBody::Occurrence {
|
||||
body: OccurrenceBody::Exchange { operation, .. },
|
||||
..
|
||||
}) = created.shared_mut()
|
||||
{
|
||||
*operation = None;
|
||||
}
|
||||
created.alias = working.fresh_alias(
|
||||
&format!(
|
||||
"{}_{}",
|
||||
@@ -745,6 +928,25 @@ pub fn plan_transition(
|
||||
let mut created = r.clone();
|
||||
created.id = target;
|
||||
created.body = body;
|
||||
// SA technical ports project through their reviewed owners; never
|
||||
// place a port→participant pair in the global correspondence map.
|
||||
if request.direction == TransitionDirection::SaToOa
|
||||
&& r.kind() == RelationKind::BoundaryExchange
|
||||
{
|
||||
let owners = [r.source(), r.target()]
|
||||
.map(|port| project.elements.get(&port).and_then(|e| e.parent));
|
||||
if let [Some(a), Some(b)] = owners {
|
||||
created.body.set_endpoints(a, b);
|
||||
} else {
|
||||
conflict(
|
||||
&mut plan,
|
||||
Some(*source),
|
||||
Some(target),
|
||||
None,
|
||||
"Boundary endpoints need participant owners before communication transition.",
|
||||
);
|
||||
}
|
||||
}
|
||||
created.alias = working.fresh_alias(
|
||||
&format!(
|
||||
"{}_{}",
|
||||
@@ -759,6 +961,21 @@ pub fn plan_transition(
|
||||
*id = *mapped;
|
||||
}
|
||||
});
|
||||
if request.direction == TransitionDirection::OaToSa
|
||||
&& r.kind() == RelationKind::CommunicationMean
|
||||
{
|
||||
if let Some((a, b)) = communication_pairs.get(source) {
|
||||
created.body.set_endpoints(*a, *b);
|
||||
} else {
|
||||
conflict(
|
||||
&mut plan,
|
||||
Some(*source),
|
||||
Some(target),
|
||||
None,
|
||||
"Choose an explicit SA component-port pair for this communication means; participant mappings cannot stand in for ports.",
|
||||
);
|
||||
}
|
||||
}
|
||||
for dependency in crate::references::relation_references(&created) {
|
||||
if dependency.is_nil()
|
||||
&& request.direction == TransitionDirection::OaToSa
|
||||
@@ -1120,9 +1337,22 @@ fn compatible_existing(
|
||||
(Some(a), Some(b)) => compatible_kinds(a.kind(), b.kind(), direction),
|
||||
_ => match (p.relations.get(&source), p.relations.get(&target)) {
|
||||
(Some(a), Some(b)) => {
|
||||
mapped_relation(a, direction).is_some_and(|body| body.kind() == b.kind())
|
||||
(a.kind() == RelationKind::BoundaryExchange
|
||||
&& b.kind() == RelationKind::BoundaryExchange)
|
||||
|| mapped_relation(a, direction).is_some_and(|body| body.kind() == b.kind())
|
||||
}
|
||||
_ => false,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn exchange_counterparts(oa: RelationKind, sa: RelationKind) -> bool {
|
||||
matches!(
|
||||
(oa, sa),
|
||||
(RelationKind::Interaction, RelationKind::FunctionalExchange)
|
||||
| (
|
||||
RelationKind::CommunicationMean,
|
||||
RelationKind::BoundaryExchange
|
||||
)
|
||||
)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,210 @@
|
||||
use super::*;
|
||||
|
||||
fn port_id(choice: &CommunicationPortChoice) -> Id {
|
||||
match choice {
|
||||
CommunicationPortChoice::Reuse { port } => *port,
|
||||
CommunicationPortChoice::Create { id, .. } => *id,
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn prepare_ports(
|
||||
original: &Project,
|
||||
working: &mut Project,
|
||||
targets: &BTreeMap<Id, Id>,
|
||||
plan: &mut TransitionPlan,
|
||||
) -> BTreeMap<Id, (Id, Id)> {
|
||||
let mut pairs = BTreeMap::new();
|
||||
for decision in plan.request.communication_endpoints.clone() {
|
||||
let result = (|| -> Result<(Id, Id), String> {
|
||||
if plan.request.direction != TransitionDirection::OaToSa {
|
||||
return Err(
|
||||
"SA endpoint choices apply only to OA→SA communication transition.".into(),
|
||||
);
|
||||
}
|
||||
let means = original
|
||||
.relations
|
||||
.get(&decision.source)
|
||||
.filter(|r| r.kind() == RelationKind::CommunicationMean)
|
||||
.ok_or("Endpoint decision must select an OA communication means.")?;
|
||||
if !plan.request.sources.contains(&means.id) && !targets.contains_key(&means.id) {
|
||||
return Err("Endpoint decision is outside this transition selection.".into());
|
||||
}
|
||||
if pairs.contains_key(&decision.source) {
|
||||
return Err("Choose one component-port pair per communication means.".into());
|
||||
}
|
||||
let mut pending = vec![];
|
||||
for (participant, choice) in [
|
||||
(means.source(), &decision.source_port),
|
||||
(means.target(), &decision.target_port),
|
||||
] {
|
||||
let owner = targets.get(&participant).copied().ok_or("Review each OA participant's SA counterpart before selecting its component port.")?;
|
||||
if working.elements.get(&owner).is_some_and(|e| {
|
||||
e.layer() != Layer::Sa || !matches!(e.kind(), Kind::System | Kind::SystemActor)
|
||||
}) {
|
||||
return Err(
|
||||
"Component-port owner must be the reviewed SA participant counterpart."
|
||||
.into(),
|
||||
);
|
||||
}
|
||||
match choice {
|
||||
CommunicationPortChoice::Reuse { port } => {
|
||||
let e = working
|
||||
.elements
|
||||
.get(port)
|
||||
.ok_or("Selected component port does not exist.")?;
|
||||
if e.parent != Some(owner)
|
||||
|| e.layer() != Layer::Sa
|
||||
|| !matches!(
|
||||
crate::ports::port_contract(e),
|
||||
Some(PortContract::Component { .. })
|
||||
)
|
||||
{
|
||||
return Err("Selected component port must belong to the reviewed SA participant and have an explicit component contract.".into());
|
||||
}
|
||||
}
|
||||
CommunicationPortChoice::Create {
|
||||
id,
|
||||
alias,
|
||||
name,
|
||||
description,
|
||||
kind,
|
||||
orientation,
|
||||
} => {
|
||||
if id.is_nil()
|
||||
|| working.contains(*id)
|
||||
|| pending.iter().any(|e: &Element| e.id == *id)
|
||||
{
|
||||
return Err("New component-port identity must be unused; choose Reuse for an existing port.".into());
|
||||
}
|
||||
pending.push(Element {
|
||||
id: *id,
|
||||
alias: alias.clone(),
|
||||
name: name.clone(),
|
||||
description: description.clone(),
|
||||
parent: Some(owner),
|
||||
body: ElementBody::shared_in(
|
||||
Layer::Sa,
|
||||
SharedBody::Port {
|
||||
contract: PortContract::Component {
|
||||
kind: *kind,
|
||||
orientation: *orientation,
|
||||
},
|
||||
legacy: None,
|
||||
},
|
||||
),
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
let pair = (
|
||||
port_id(&decision.source_port),
|
||||
port_id(&decision.target_port),
|
||||
);
|
||||
if pair.0 == pair.1 || targets.get(&means.source()) == targets.get(&means.target()) {
|
||||
return Err("Communication counterparts must have different participant owners; review the participant boundary mapping.".into());
|
||||
}
|
||||
for e in pending {
|
||||
working.elements.insert(e.id, e.clone());
|
||||
plan.commands.push(Command::CreateElement(e));
|
||||
}
|
||||
Ok(pair)
|
||||
})();
|
||||
match result {
|
||||
Ok(pair) => {
|
||||
pairs.insert(decision.source, pair);
|
||||
}
|
||||
Err(message) => conflict(
|
||||
plan,
|
||||
Some(decision.source),
|
||||
targets.get(&decision.source).copied(),
|
||||
None,
|
||||
message,
|
||||
),
|
||||
}
|
||||
}
|
||||
pairs
|
||||
}
|
||||
|
||||
/// Adapt only the transferred endpoint value. Reviewed baseline facts continue
|
||||
/// to retain the actual participant/port identities on their respective sides.
|
||||
pub(crate) fn review_endpoint_fact(
|
||||
project: &Project,
|
||||
request: &TransitionRequest,
|
||||
map: &BTreeMap<Id, Id>,
|
||||
source: Id,
|
||||
target: Id,
|
||||
fact: &FacetReview,
|
||||
) -> Result<Option<FacetReview>, String> {
|
||||
let (Some(a), Some(b)) = (
|
||||
project.relations.get(&source),
|
||||
project.relations.get(&target),
|
||||
) else {
|
||||
return Ok(None);
|
||||
};
|
||||
let forward =
|
||||
a.kind() == RelationKind::CommunicationMean && b.kind() == RelationKind::BoundaryExchange;
|
||||
let reverse =
|
||||
a.kind() == RelationKind::BoundaryExchange && b.kind() == RelationKind::CommunicationMean;
|
||||
if !forward && !reverse {
|
||||
return Ok(None);
|
||||
}
|
||||
let (endpoint, is_source) = match fact {
|
||||
FacetReview::Relation(RelationReview::Source(_)) => (a.source(), true),
|
||||
FacetReview::Relation(RelationReview::Target(_)) => (a.target(), false),
|
||||
_ => return Ok(None),
|
||||
};
|
||||
let mapped = if forward {
|
||||
let decision = request.communication_endpoints.iter().find(|d| d.source == source)
|
||||
.ok_or("Taking an OA endpoint requires this exchange's explicit SA component-port decision.")?;
|
||||
let port = port_id(if is_source {
|
||||
&decision.source_port
|
||||
} else {
|
||||
&decision.target_port
|
||||
});
|
||||
let expected_owner = map.get(&endpoint).ok_or(
|
||||
"Review the participant counterpart before taking its communication endpoint.",
|
||||
)?;
|
||||
let e = project
|
||||
.elements
|
||||
.get(&port)
|
||||
.ok_or("Selected communication endpoint port does not exist.")?;
|
||||
if e.parent != Some(*expected_owner)
|
||||
|| e.layer() != Layer::Sa
|
||||
|| !matches!(
|
||||
crate::ports::port_contract(e),
|
||||
Some(PortContract::Component { .. })
|
||||
)
|
||||
{
|
||||
return Err(
|
||||
"Selected component port disagrees with the reviewed participant counterpart."
|
||||
.into(),
|
||||
);
|
||||
}
|
||||
port
|
||||
} else {
|
||||
let owner = project
|
||||
.elements
|
||||
.get(&endpoint)
|
||||
.and_then(|e| e.parent)
|
||||
.ok_or("SA boundary port needs a participant owner.")?;
|
||||
let participant = *map.get(&owner).ok_or(
|
||||
"Review the SA port owner's OA participant counterpart before taking this endpoint.",
|
||||
)?;
|
||||
if !project.elements.get(&participant).is_some_and(|e| {
|
||||
e.layer() == Layer::Oa && matches!(e.kind(), Kind::Entity | Kind::Actor)
|
||||
}) {
|
||||
return Err("Boundary endpoint owner must map to an OA entity or actor.".into());
|
||||
}
|
||||
participant
|
||||
};
|
||||
let mut result = fact.clone();
|
||||
if let FacetReview::Relation(RelationReview::Source(values) | RelationReview::Target(values)) =
|
||||
&mut result
|
||||
{
|
||||
match request.direction.source_layer() {
|
||||
Layer::Oa => values.oa = Observed::Value(mapped),
|
||||
Layer::Sa => values.sa = Observed::Value(mapped),
|
||||
}
|
||||
}
|
||||
Ok(Some(result))
|
||||
}
|
||||
@@ -2,6 +2,8 @@ use crate::*;
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::collections::{BTreeMap, BTreeSet};
|
||||
|
||||
mod coverage;
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub enum Severity {
|
||||
Error,
|
||||
@@ -178,7 +180,103 @@ fn check_ids(out: &mut Vec<Issue>, owner: Id, field: &str, ids: &[Id]) {
|
||||
}
|
||||
|
||||
pub fn validate(p: &Project) -> Vec<Issue> {
|
||||
validate_with_usage(p).0
|
||||
}
|
||||
|
||||
/// Runs the shared static/architectural route once and retains successful static
|
||||
/// metadata without retaining a Project-borrowing environment. Architectural
|
||||
/// issue production is outside the static meter and any caller auxiliary ledger;
|
||||
/// callers must reserve separately before mapping or retaining these issues.
|
||||
pub(crate) fn validate_with_usage(
|
||||
p: &Project,
|
||||
) -> (
|
||||
Vec<Issue>,
|
||||
Option<(
|
||||
crate::analysis::AdmissionLimits,
|
||||
crate::analysis::AdmissionUsage,
|
||||
)>,
|
||||
) {
|
||||
// Bound analysis trees before architectural visitors can clone an element.
|
||||
// Admission itself never enters this public validator recursively.
|
||||
let environment = match crate::analysis::admit_structure_checked(
|
||||
p,
|
||||
crate::analysis::AdmissionLimits::REFERENCE,
|
||||
) {
|
||||
Ok(environment) => environment,
|
||||
Err(failure) => {
|
||||
let mut out = Vec::new();
|
||||
error(
|
||||
&mut out,
|
||||
failure.object,
|
||||
&failure.code,
|
||||
&failure.field,
|
||||
failure.message,
|
||||
);
|
||||
return (out, None);
|
||||
}
|
||||
};
|
||||
let metadata = (
|
||||
environment.admission_limits(),
|
||||
environment.admission_usage(),
|
||||
);
|
||||
drop(environment);
|
||||
(validate_structure(p), Some(metadata))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod shared_admission_tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn successful_static_metadata_survives_architectural_warnings() {
|
||||
let mut project = Project::empty();
|
||||
project.name.clear();
|
||||
let (issues, metadata) = validate_with_usage(&project);
|
||||
let (limits, usage) = metadata.expect("static admission succeeds");
|
||||
assert_eq!(limits, crate::analysis::AdmissionLimits::REFERENCE);
|
||||
assert!(usage.static_events > 0);
|
||||
assert_eq!(usage.stored_expression_nodes, 0);
|
||||
assert!(issues.iter().any(|issue| issue.code == "unnamed"
|
||||
&& issue.element == Some(project.id)
|
||||
&& issue.severity == Severity::Warning));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn static_failure_returns_no_metadata_and_skips_architectural_warnings() {
|
||||
use crate::analysis::{
|
||||
AnalysisType, Binding, CalculationDefinition, Definition, DefinitionBody, ScalarType,
|
||||
};
|
||||
let mut project = Project::empty();
|
||||
project.name.clear();
|
||||
let key = Id::from_u128(10);
|
||||
project.definitions.insert(
|
||||
key,
|
||||
Definition {
|
||||
id: Id::from_u128(11),
|
||||
alias: "f".into(),
|
||||
name: "F".into(),
|
||||
description: String::new(),
|
||||
body: DefinitionBody::Calculation(CalculationDefinition {
|
||||
parameters: Vec::new(),
|
||||
result: AnalysisType::Scalar(ScalarType::Number),
|
||||
body: Binding::Unbound,
|
||||
}),
|
||||
},
|
||||
);
|
||||
let (issues, metadata) = validate_with_usage(&project);
|
||||
assert!(metadata.is_none());
|
||||
assert_eq!(issues.len(), 1);
|
||||
assert_eq!(issues[0].severity, Severity::Error);
|
||||
assert_eq!(issues[0].element, Some(key));
|
||||
assert_eq!(issues[0].code, "identity_mismatch");
|
||||
}
|
||||
}
|
||||
|
||||
/// Architecture/header validation without recursively re-entering analysis admission.
|
||||
pub(crate) fn validate_structure(p: &Project) -> Vec<Issue> {
|
||||
let mut out = Vec::new();
|
||||
let coverage = coverage::Index::new(p);
|
||||
let topology_index = crate::topology_context::TopologyIndex::new(p);
|
||||
if p.schema_version != SCHEMA_VERSION {
|
||||
error(
|
||||
&mut out,
|
||||
@@ -346,19 +444,15 @@ pub fn validate(p: &Project) -> Vec<Issue> {
|
||||
);
|
||||
}
|
||||
if matches!(e.kind(), Kind::Capability | Kind::SystemCapability)
|
||||
&& !p.relations.values().any(|r| {
|
||||
matches!(
|
||||
r.kind(),
|
||||
RelationKind::CapabilityInvolvement | RelationKind::ChainInvolvement
|
||||
) && r.target() == e.id
|
||||
})
|
||||
&& !coverage.grouping.contains(&e.id)
|
||||
&& !coverage.supported_capabilities.contains(&e.id)
|
||||
{
|
||||
warning(
|
||||
&mut out,
|
||||
e.id,
|
||||
"unsupported_capability",
|
||||
"involvement",
|
||||
"Connect the capability to involved participants, work, or a process/chain.",
|
||||
"Connect the capability to involved participants, work, a process/chain, or an explicit scenario context.",
|
||||
);
|
||||
}
|
||||
if let Some(steps) = e.steps() {
|
||||
@@ -384,10 +478,27 @@ pub fn validate(p: &Project) -> Vec<Issue> {
|
||||
"Add ordered occurrences.",
|
||||
);
|
||||
}
|
||||
validate_sequence(p, e, steps, &mut out);
|
||||
validate_sequence(p, e, steps, &topology_index, &mut out);
|
||||
}
|
||||
if let Some(shared) = e.shared() {
|
||||
match shared {
|
||||
SharedBody::ExchangeCategory { family, exchanges } => {
|
||||
for issue in crate::view_options::validate_category(
|
||||
p,
|
||||
e.layer(),
|
||||
e.parent,
|
||||
*family,
|
||||
exchanges,
|
||||
) {
|
||||
error(
|
||||
&mut out,
|
||||
e.id,
|
||||
"exchange_category",
|
||||
issue.field,
|
||||
issue.message,
|
||||
);
|
||||
}
|
||||
}
|
||||
SharedBody::DataType { .. }
|
||||
| SharedBody::DataField { .. }
|
||||
| SharedBody::Interface { .. }
|
||||
@@ -584,7 +695,7 @@ pub fn validate(p: &Project) -> Vec<Issue> {
|
||||
}
|
||||
text(&mut out, r.id, "name", &r.name);
|
||||
text(&mut out, r.id, "description", &r.description);
|
||||
validate_relation(p, r, &mut out);
|
||||
validate_relation(p, r, &topology_index, &mut out);
|
||||
crate::data::validate_relation(p, r, &mut out);
|
||||
crate::ports::validate_boundary_interface_requirements(p, r, &mut out);
|
||||
validate_relation_context(p, r, &mut out);
|
||||
@@ -602,6 +713,14 @@ pub fn validate(p: &Project) -> Vec<Issue> {
|
||||
}
|
||||
text(&mut out, d.id, "name", &d.name);
|
||||
text(&mut out, d.id, "description", &d.description);
|
||||
let option_issues = if d.projection == ProjectionKind::Traceability {
|
||||
crate::view_options::validate_options_cross_layer(p, &d.view_options)
|
||||
} else {
|
||||
crate::view_options::validate_options(p, d.layer, &d.view_options)
|
||||
};
|
||||
for issue in option_issues {
|
||||
error(&mut out, d.id, "view_options", issue.field, issue.message);
|
||||
}
|
||||
if let Some(machine) = d.projection.state_machine()
|
||||
&& !p
|
||||
.elements
|
||||
@@ -921,12 +1040,62 @@ pub fn validate(p: &Project) -> Vec<Issue> {
|
||||
);
|
||||
}
|
||||
}
|
||||
if !out.iter().any(|issue| issue.severity == Severity::Error) {
|
||||
coverage.validate(p, &mut out);
|
||||
}
|
||||
out
|
||||
}
|
||||
fn validate_sequence(p: &Project, e: &Element, steps: &[Id], out: &mut Vec<Issue>) {
|
||||
fn validate_sequence(
|
||||
p: &Project,
|
||||
e: &Element,
|
||||
steps: &[Id],
|
||||
topology: &crate::topology_context::TopologyIndex<'_>,
|
||||
out: &mut Vec<Issue>,
|
||||
) {
|
||||
if !matches!(e.kind(), Kind::Process | Kind::FunctionalChain) {
|
||||
return;
|
||||
}
|
||||
if topology.has_contextual_links(e.id) {
|
||||
let analysis = topology.analyze(e.id, crate::topology_context::AnalysisLimits::default());
|
||||
for notice in analysis.notices {
|
||||
let breadcrumb = notice
|
||||
.address
|
||||
.endpoint
|
||||
.references
|
||||
.iter()
|
||||
.chain(std::iter::once(¬ice.address.endpoint.occurrence))
|
||||
.map(|id| format!("{} ({id})", p.named(*id)))
|
||||
.collect::<Vec<_>>()
|
||||
.join(" / ");
|
||||
warning(
|
||||
out,
|
||||
e.id,
|
||||
notice.code,
|
||||
"steps",
|
||||
format!("Caller '{}', {breadcrumb}: {}", e.name, notice.message),
|
||||
);
|
||||
}
|
||||
if analysis.complete {
|
||||
for (code, label, count) in [
|
||||
("sequence_starts", "start", analysis.entries.len()),
|
||||
("sequence_ends", "end", analysis.exits.len()),
|
||||
] {
|
||||
if count != 1 {
|
||||
warning(
|
||||
out,
|
||||
e.id,
|
||||
code,
|
||||
"steps",
|
||||
format!(
|
||||
"Caller '{}' has {count} structural {label} boundaries; review the intended independent paths.",
|
||||
e.name
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
return;
|
||||
}
|
||||
let links: Vec<_> = p
|
||||
.relations
|
||||
.values()
|
||||
@@ -1254,40 +1423,149 @@ pub fn semantic_representation_compatible(
|
||||
pub fn lifeline_matches_endpoint(p: &Project, line: Id, endpoint: Id) -> Option<bool> {
|
||||
semantic_representation_compatible(p, represented(p, line)?, endpoint)
|
||||
}
|
||||
/// Effective semantic direction, including a Reply that reuses its Call exchange.
|
||||
/// An incomplete reply correlation and a local timer have no inferred endpoints.
|
||||
pub fn message_endpoints(p: &Project, body: &OccurrenceBody) -> Option<(Id, Id)> {
|
||||
/// A single shared answer for scenario admission, drawing, and endpoint pickers.
|
||||
/// Incomplete or ambiguous bindings never choose an arbitrary direction.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum MessageEndpointResolution {
|
||||
NotApplicable,
|
||||
Incomplete,
|
||||
Resolved { source: Id, target: Id },
|
||||
Ambiguous,
|
||||
Conflict,
|
||||
}
|
||||
pub fn resolve_message_endpoints(p: &Project, body: &OccurrenceBody) -> MessageEndpointResolution {
|
||||
use MessageEndpointResolution as R;
|
||||
let OccurrenceBody::Exchange {
|
||||
exchange: Some(exchange),
|
||||
message_kind,
|
||||
reply_to,
|
||||
sender,
|
||||
receiver,
|
||||
..
|
||||
} = body
|
||||
else {
|
||||
return None;
|
||||
return R::NotApplicable;
|
||||
};
|
||||
if matches!(message_kind, MessageKind::Timer { .. }) {
|
||||
return None;
|
||||
return R::NotApplicable;
|
||||
}
|
||||
let Some(relation) = p.relations.get(exchange) else {
|
||||
return R::Incomplete;
|
||||
};
|
||||
let mut candidates = vec![relation.body.endpoints()];
|
||||
// A mapped unoriented SA boundary retains the OA communication's possible
|
||||
// directions. Fixed oriented/legacy exchange behavior remains unchanged.
|
||||
let communication = matches!(
|
||||
relation.body,
|
||||
RelationBody::CommunicationMean { .. }
|
||||
| RelationBody::BoundaryExchange {
|
||||
oriented: false,
|
||||
..
|
||||
}
|
||||
);
|
||||
if matches!(
|
||||
relation.body,
|
||||
RelationBody::CommunicationMean {
|
||||
oriented: false,
|
||||
..
|
||||
} | RelationBody::BoundaryExchange {
|
||||
oriented: false,
|
||||
..
|
||||
}
|
||||
) {
|
||||
candidates.push((relation.target(), relation.source()));
|
||||
}
|
||||
if matches!(
|
||||
relation.body,
|
||||
RelationBody::BoundaryExchange {
|
||||
oriented: false,
|
||||
..
|
||||
}
|
||||
) {
|
||||
candidates.retain(|(source, target)| {
|
||||
match (
|
||||
p.elements.get(source).and_then(crate::ports::port_contract),
|
||||
p.elements.get(target).and_then(crate::ports::port_contract),
|
||||
) {
|
||||
(
|
||||
Some(a @ PortContract::Component { .. }),
|
||||
Some(b @ PortContract::Component { .. }),
|
||||
) => {
|
||||
crate::ports::component_allows(a, true)
|
||||
&& crate::ports::component_allows(b, false)
|
||||
}
|
||||
// Legacy direction contracts remain fixed even for an
|
||||
// unoriented declaration; do not reinterpret old ports.
|
||||
_ => (*source, *target) == relation.body.endpoints(),
|
||||
}
|
||||
});
|
||||
}
|
||||
let relation = p.relations.get(exchange)?;
|
||||
if message_kind == &MessageKind::Reply {
|
||||
let Some(reply_to) = reply_to else {
|
||||
return R::Incomplete;
|
||||
};
|
||||
let Some(SharedBody::Occurrence {
|
||||
body:
|
||||
OccurrenceBody::Exchange {
|
||||
call_body @ OccurrenceBody::Exchange {
|
||||
message_kind: MessageKind::Call,
|
||||
exchange: Some(call_exchange),
|
||||
..
|
||||
},
|
||||
..
|
||||
}) = p.elements.get(&(*reply_to)?).and_then(Element::shared)
|
||||
}) = p.elements.get(reply_to).and_then(Element::shared)
|
||||
else {
|
||||
return None;
|
||||
return R::Incomplete;
|
||||
};
|
||||
if call_exchange == exchange {
|
||||
return Some((relation.target(), relation.source()));
|
||||
let R::Resolved { source, target } = resolve_message_endpoints(p, call_body) else {
|
||||
return R::Incomplete;
|
||||
};
|
||||
candidates = vec![(target, source)];
|
||||
} else if communication {
|
||||
let R::Resolved { source, target } = resolve_message_endpoints(p, call_body) else {
|
||||
return R::Incomplete;
|
||||
};
|
||||
let owner = |id| {
|
||||
p.elements
|
||||
.get(&id)
|
||||
.filter(|e| e.kind() == Kind::Port)
|
||||
.and_then(|e| e.parent)
|
||||
.unwrap_or(id)
|
||||
};
|
||||
candidates.retain(|(a, b)| {
|
||||
semantic_representation_compatible(p, owner(*a), owner(target)) == Some(true)
|
||||
&& semantic_representation_compatible(p, owner(*b), owner(source)) == Some(true)
|
||||
});
|
||||
}
|
||||
}
|
||||
Some(relation.body.endpoints())
|
||||
if communication {
|
||||
candidates.retain(|(a, b)| {
|
||||
sender.is_none_or(|line| lifeline_matches_endpoint(p, line, *a) != Some(false))
|
||||
&& receiver.is_none_or(|line| lifeline_matches_endpoint(p, line, *b) != Some(false))
|
||||
});
|
||||
if candidates.is_empty() {
|
||||
return R::Conflict;
|
||||
}
|
||||
if sender.and_then(|line| represented(p, line)).is_none()
|
||||
|| receiver.and_then(|line| represented(p, line)).is_none()
|
||||
{
|
||||
return R::Incomplete;
|
||||
}
|
||||
if candidates.len() > 1 {
|
||||
return R::Ambiguous;
|
||||
}
|
||||
}
|
||||
let Some((source, target)) = candidates.first().copied() else {
|
||||
return R::Conflict;
|
||||
};
|
||||
R::Resolved { source, target }
|
||||
}
|
||||
/// Compatibility adapter: only a resolved direction has inferred endpoints.
|
||||
pub fn message_endpoints(p: &Project, body: &OccurrenceBody) -> Option<(Id, Id)> {
|
||||
match resolve_message_endpoints(p, body) {
|
||||
MessageEndpointResolution::Resolved { source, target } => Some((source, target)),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
/// Only report order guaranteed by a common sequence or an enclosing branch path.
|
||||
/// A call in one alternative does not become an unconditional call after the fragment.
|
||||
@@ -1418,6 +1696,7 @@ fn validate_message(p: &Project, e: &Element, body: &OccurrenceBody, out: &mut V
|
||||
receiver,
|
||||
reply_to,
|
||||
values,
|
||||
..
|
||||
} = body
|
||||
else {
|
||||
return;
|
||||
@@ -1440,7 +1719,9 @@ fn validate_message(p: &Project, e: &Element, body: &OccurrenceBody, out: &mut V
|
||||
ScenarioViewpoint::Functional => relation.kind() == RelationKind::FunctionalExchange,
|
||||
ScenarioViewpoint::ParticipantInteraction => matches!(
|
||||
relation.kind(),
|
||||
RelationKind::Interaction | RelationKind::BoundaryExchange
|
||||
RelationKind::Interaction
|
||||
| RelationKind::BoundaryExchange
|
||||
| RelationKind::CommunicationMean
|
||||
),
|
||||
ScenarioViewpoint::BoundaryInterface => matches!(
|
||||
relation.kind(),
|
||||
@@ -1628,6 +1909,34 @@ fn validate_message(p: &Project, e: &Element, body: &OccurrenceBody, out: &mut V
|
||||
}
|
||||
}
|
||||
let relation = exchange.and_then(|id| p.relations.get(&id));
|
||||
let operation = crate::operations::resolve(p, e.id);
|
||||
let signature = match &operation {
|
||||
Ok(crate::operations::OperationResolution::Selected(selected)) => {
|
||||
if selected.transmission == TransmissionProtocol::Unspecified {
|
||||
warning(
|
||||
out,
|
||||
e.id,
|
||||
"operation_transmission_unspecified",
|
||||
"operation",
|
||||
"The selected operation transmission protocol is unspecified.",
|
||||
);
|
||||
}
|
||||
Some(crate::operations::signature_relation(selected))
|
||||
}
|
||||
Ok(crate::operations::OperationResolution::Unresolved { reason, .. }) => {
|
||||
warning(out, e.id, "operation_unresolved", "operation", reason);
|
||||
None
|
||||
}
|
||||
Err(problem) => {
|
||||
error(out, e.id, problem.code, "operation", &problem.message);
|
||||
None
|
||||
}
|
||||
_ => None,
|
||||
};
|
||||
let value_relation = match &operation {
|
||||
Ok(crate::operations::OperationResolution::Ordinary) => relation,
|
||||
_ => signature.as_ref(),
|
||||
};
|
||||
if message_kind == &MessageKind::Call
|
||||
&& relation.is_some_and(|r| {
|
||||
!r.body
|
||||
@@ -1673,10 +1982,48 @@ fn validate_message(p: &Project, e: &Element, body: &OccurrenceBody, out: &mut V
|
||||
"The value path exceeds the bounded authoring depth.",
|
||||
);
|
||||
}
|
||||
if let Some(r) = relation {
|
||||
if matches!(
|
||||
operation,
|
||||
Ok(crate::operations::OperationResolution::Unresolved { .. })
|
||||
) && let Some(owner) = value
|
||||
.path
|
||||
.first()
|
||||
.or(Some(&value.field))
|
||||
.and_then(|id| p.elements.get(id))
|
||||
.and_then(|field| field.parent)
|
||||
{
|
||||
let path_context = Relation {
|
||||
id: e.id,
|
||||
alias: String::new(),
|
||||
name: String::new(),
|
||||
description: String::new(),
|
||||
body: RelationBody::Interaction {
|
||||
source: e.id,
|
||||
target: e.id,
|
||||
items: vec![owner],
|
||||
},
|
||||
};
|
||||
if crate::data::carried_value_path(p, &path_context, &value.path, value.field).is_none()
|
||||
{
|
||||
error(
|
||||
out,
|
||||
e.id,
|
||||
"message_value_path",
|
||||
"values.path",
|
||||
"Even while the operation is unresolved, a value path must follow existing Value record fields in order.",
|
||||
);
|
||||
}
|
||||
}
|
||||
if let Some(r) = value_relation {
|
||||
if let Some(path) = crate::data::carried_value_path(p, r, &value.path, value.field) {
|
||||
if crate::data::item_mechanism(p, path.item) == Some(ExchangeMechanism::Operation) {
|
||||
let permitted = match message_kind {
|
||||
MessageKind::Asynchronous if signature.is_some() => matches!(
|
||||
path.direction,
|
||||
ParameterDirection::Unspecified
|
||||
| ParameterDirection::In
|
||||
| ParameterDirection::InOut
|
||||
),
|
||||
MessageKind::Call => matches!(
|
||||
path.direction,
|
||||
ParameterDirection::Unspecified
|
||||
@@ -1920,6 +2267,7 @@ fn validate_occurrence(p: &Project, e: &Element, body: &OccurrenceBody, out: &mu
|
||||
RelationKind::Interaction
|
||||
| RelationKind::FunctionalExchange
|
||||
| RelationKind::BoundaryExchange
|
||||
| RelationKind::CommunicationMean
|
||||
) => {}
|
||||
_ => error(
|
||||
out,
|
||||
@@ -2115,7 +2463,24 @@ fn relation_path_exists(p: &Project, kind: RelationKind, from: Id, to: Id) -> bo
|
||||
false
|
||||
}
|
||||
|
||||
fn validate_relation(p: &Project, r: &Relation, out: &mut Vec<Issue>) {
|
||||
fn validate_relation(
|
||||
p: &Project,
|
||||
r: &Relation,
|
||||
topology: &crate::topology_context::TopologyIndex<'_>,
|
||||
out: &mut Vec<Issue>,
|
||||
) {
|
||||
if let RelationBody::ContextualLink {
|
||||
owner,
|
||||
source,
|
||||
target,
|
||||
purpose,
|
||||
} = &r.body
|
||||
{
|
||||
if let Err(problem) = topology.validate_link(*owner, source, target, purpose) {
|
||||
error(out, r.id, problem.code, "body", problem.message);
|
||||
}
|
||||
return;
|
||||
}
|
||||
let (source, target) = r.body.endpoints();
|
||||
for id in crate::references::relation_references(r) {
|
||||
// Most relation references name elements. Avoid constructing all model
|
||||
@@ -2134,18 +2499,20 @@ fn validate_relation(p: &Project, r: &Relation, out: &mut Vec<Issue>) {
|
||||
if let RelationBody::ExchangeAllocation { .. } = r.body {
|
||||
match (p.relations.get(&source), p.relations.get(&target)) {
|
||||
(Some(a), Some(b))
|
||||
if a.kind() == RelationKind::BoundaryExchange
|
||||
if ((a.kind() == RelationKind::BoundaryExchange
|
||||
&& matches!(
|
||||
b.kind(),
|
||||
RelationKind::FunctionalExchange | RelationKind::Interaction
|
||||
)
|
||||
))
|
||||
|| (a.kind() == RelationKind::CommunicationMean
|
||||
&& b.kind() == RelationKind::Interaction))
|
||||
&& p.layer_of(source) == p.layer_of(target) => {}
|
||||
_ => error(
|
||||
out,
|
||||
r.id,
|
||||
"exchange_allocation",
|
||||
"endpoints",
|
||||
"Exchange allocation relates a boundary exchange to a work exchange in the same layer.",
|
||||
"Exchange allocation relates communication means to an OA interaction, or a boundary exchange to a work exchange, in the same layer.",
|
||||
),
|
||||
};
|
||||
validate_exchange_allocation(p, r, out);
|
||||
@@ -2396,7 +2763,7 @@ pub fn trace_permits(p: &Project, t: &Trace) -> bool {
|
||||
_ => false,
|
||||
},
|
||||
_ => {
|
||||
matches!((p.relations.get(&t.oa),p.relations.get(&t.sa)),(Some(a),Some(b))if t.kind==TraceKind::Exchange&&a.kind()==RelationKind::Interaction&&b.kind()==RelationKind::FunctionalExchange)
|
||||
matches!((p.relations.get(&t.oa),p.relations.get(&t.sa)),(Some(a),Some(b))if t.kind==TraceKind::Exchange&&crate::transitions::exchange_counterparts(a.kind(), b.kind()))
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -2491,7 +2858,12 @@ pub fn can_connect(p: &Project, kind: RelationKind, source: Id, target: Id) -> b
|
||||
*transition_kind = TransitionKind::Local;
|
||||
}
|
||||
let mut issues = vec![];
|
||||
validate_relation(p, &candidate, &mut issues);
|
||||
validate_relation(
|
||||
p,
|
||||
&candidate,
|
||||
&crate::topology_context::TopologyIndex::new(p),
|
||||
&mut issues,
|
||||
);
|
||||
validate_relation_context(p, &candidate, &mut issues);
|
||||
if kind == RelationKind::StateTransition {
|
||||
for endpoint in [source, target] {
|
||||
@@ -2521,7 +2893,12 @@ pub fn can_connect_boundary(p: &Project, source: Id, target: Id, oriented: bool)
|
||||
},
|
||||
};
|
||||
let mut issues = vec![];
|
||||
validate_relation(p, &candidate, &mut issues);
|
||||
validate_relation(
|
||||
p,
|
||||
&candidate,
|
||||
&crate::topology_context::TopologyIndex::new(p),
|
||||
&mut issues,
|
||||
);
|
||||
validate_relation_context(p, &candidate, &mut issues);
|
||||
!issues.iter().any(|i| i.severity == Severity::Error)
|
||||
}
|
||||
@@ -2737,6 +3114,23 @@ fn validate_occurrence_context(
|
||||
OccurrenceBody::Exchange {
|
||||
sender, receiver, ..
|
||||
} => {
|
||||
match resolve_message_endpoints(p, body) {
|
||||
MessageEndpointResolution::Conflict => error(
|
||||
out,
|
||||
e.id,
|
||||
"scenario_endpoint",
|
||||
"sender",
|
||||
"Sender and receiver must agree with one permitted communication direction and the correlated Call.",
|
||||
),
|
||||
MessageEndpointResolution::Ambiguous => warning(
|
||||
out,
|
||||
e.id,
|
||||
"ambiguous_message_direction",
|
||||
"sender",
|
||||
"Bind explicit participant lifelines to resolve the communication direction; shared roles allow both directions.",
|
||||
),
|
||||
_ => {}
|
||||
}
|
||||
if let Some((source, target)) = message_endpoints(p, body) {
|
||||
check(out, *sender, Some(source), "sender");
|
||||
check(out, *receiver, Some(target), "receiver");
|
||||
|
||||
@@ -0,0 +1,174 @@
|
||||
//! Advisory presence of explicit behavior evidence, never inferred execution.
|
||||
use super::*;
|
||||
|
||||
#[derive(Default)]
|
||||
pub(super) struct Index {
|
||||
pub grouping: BTreeSet<Id>,
|
||||
pub supported_capabilities: BTreeSet<Id>,
|
||||
contextual_capabilities: BTreeSet<Id>,
|
||||
supported_missions: BTreeSet<Id>,
|
||||
}
|
||||
|
||||
impl Index {
|
||||
pub fn new(p: &Project) -> Self {
|
||||
let mut index = Self::default();
|
||||
for element in p.elements.values() {
|
||||
if let Some(parent) = element.parent.and_then(|id| p.elements.get(&id))
|
||||
&& parent.kind() == element.kind()
|
||||
&& parent.layer() == element.layer()
|
||||
{
|
||||
index.grouping.insert(parent.id);
|
||||
}
|
||||
if let Some(SharedBody::Scenario {
|
||||
context: Some(id), ..
|
||||
}) = element.shared()
|
||||
&& p.elements.get(id).is_some_and(|context| {
|
||||
matches!(context.kind(), Kind::Capability | Kind::SystemCapability)
|
||||
&& context.layer() == element.layer()
|
||||
})
|
||||
{
|
||||
index.contextual_capabilities.insert(*id);
|
||||
index.supported_capabilities.insert(*id);
|
||||
}
|
||||
}
|
||||
for relation in p.relations.values() {
|
||||
let (Some(source), Some(target)) = (
|
||||
p.elements.get(&relation.source()),
|
||||
p.elements.get(&relation.target()),
|
||||
) else {
|
||||
continue;
|
||||
};
|
||||
if source.layer() != target.layer()
|
||||
|| !relation.kind().permits(source.kind(), target.kind())
|
||||
{
|
||||
continue;
|
||||
}
|
||||
match relation.kind() {
|
||||
RelationKind::CapabilityInvolvement => {
|
||||
index.supported_capabilities.insert(target.id);
|
||||
}
|
||||
RelationKind::ChainInvolvement => {
|
||||
index.supported_capabilities.insert(target.id);
|
||||
index.contextual_capabilities.insert(target.id);
|
||||
}
|
||||
RelationKind::MissionCapability => {
|
||||
index.supported_missions.insert(source.id);
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
index
|
||||
}
|
||||
|
||||
pub fn validate(&self, p: &Project, out: &mut Vec<Issue>) {
|
||||
let (work, exchanges) = included_evidence(p);
|
||||
for element in p.elements.values() {
|
||||
if element.kind().is_work()
|
||||
&& !self.grouping.contains(&element.id)
|
||||
&& !work.contains(&element.id)
|
||||
{
|
||||
warning(
|
||||
out,
|
||||
element.id,
|
||||
"work_without_behavior_context",
|
||||
"",
|
||||
"Include this leaf activity/function in a process/chain or scenario through a work action or exchange occurrence.",
|
||||
);
|
||||
}
|
||||
if matches!(element.kind(), Kind::OperationalMission | Kind::Mission)
|
||||
&& !self.supported_missions.contains(&element.id)
|
||||
{
|
||||
warning(
|
||||
out,
|
||||
element.id,
|
||||
"mission_without_capability",
|
||||
"",
|
||||
"Connect this mission to a capability that delivers it.",
|
||||
);
|
||||
}
|
||||
if matches!(element.kind(), Kind::Capability | Kind::SystemCapability)
|
||||
&& !self.grouping.contains(&element.id)
|
||||
&& self.supported_capabilities.contains(&element.id)
|
||||
&& !self.contextual_capabilities.contains(&element.id)
|
||||
{
|
||||
warning(
|
||||
out,
|
||||
element.id,
|
||||
"capability_without_behavior_context",
|
||||
"",
|
||||
"Add an explicit behavior context: link a process/chain with Chain involvement, or set a scenario's Context to this capability.",
|
||||
);
|
||||
}
|
||||
}
|
||||
for relation in p.relations.values().filter(|r| work_exchange(r.kind())) {
|
||||
let mut non_leaf = false;
|
||||
for (field, endpoint) in [("source", relation.source()), ("target", relation.target())]
|
||||
{
|
||||
if self.grouping.contains(&endpoint) {
|
||||
non_leaf = true;
|
||||
warning(
|
||||
out,
|
||||
relation.id,
|
||||
"non_leaf_work_exchange",
|
||||
field,
|
||||
"Choose the leaf activity/function responsible for this exchange; keep any typed port owned by that function.",
|
||||
);
|
||||
}
|
||||
}
|
||||
if !non_leaf && !exchanges.contains(&relation.id) {
|
||||
warning(
|
||||
out,
|
||||
relation.id,
|
||||
"exchange_without_behavior_context",
|
||||
"",
|
||||
"Use this exchange in a process/chain or scenario.",
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn work_exchange(kind: RelationKind) -> bool {
|
||||
matches!(
|
||||
kind,
|
||||
RelationKind::Interaction | RelationKind::FunctionalExchange
|
||||
)
|
||||
}
|
||||
|
||||
/// Only ordered, owned occurrences contribute. Each identity is visited once,
|
||||
/// including reused containers; this remains bounded even on malformed drafts.
|
||||
fn included_evidence(p: &Project) -> (BTreeSet<Id>, BTreeSet<Id>) {
|
||||
let crate::view_options::BehaviorEvidence { work, exchanges } =
|
||||
crate::view_options::all_behavior_evidence(p);
|
||||
(work, exchanges)
|
||||
}
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn malformed_self_reuse_is_bounded_even_without_structural_gate() {
|
||||
let mut p = Project::empty();
|
||||
let scenario = p
|
||||
.add_element(Kind::Scenario, Layer::Oa, "Self reuse", None)
|
||||
.unwrap();
|
||||
let occurrence = p
|
||||
.add_element(Kind::Occurrence, Layer::Oa, "Cycle", Some(scenario))
|
||||
.unwrap();
|
||||
if let Some(SharedBody::Occurrence { body, .. }) =
|
||||
p.elements.get_mut(&occurrence).unwrap().shared_mut()
|
||||
{
|
||||
*body = OccurrenceBody::ScenarioUse {
|
||||
scenario: Some(scenario),
|
||||
bindings: vec![],
|
||||
};
|
||||
}
|
||||
p.elements
|
||||
.get_mut(&scenario)
|
||||
.unwrap()
|
||||
.steps_mut()
|
||||
.unwrap()
|
||||
.push(occurrence);
|
||||
assert_eq!(included_evidence(&p), (BTreeSet::new(), BTreeSet::new()));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,733 @@
|
||||
//! Persisted view intent and pure visibility decisions over actual model identities.
|
||||
//! Build `ViewIndex` once per accepted model revision. Preparing a view performs
|
||||
//! set unions/reachability once; testing an edge never walks the model.
|
||||
use crate::{
|
||||
ContextualLinkPurpose, Id, Kind, Layer, OccurrenceBody, Project, RelationBody, RelationKind,
|
||||
SharedBody,
|
||||
};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use std::collections::{BTreeMap, BTreeSet};
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub enum ExchangeFamily {
|
||||
Work,
|
||||
Participant,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub enum EdgeKind {
|
||||
Relation(RelationKind),
|
||||
Trace,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub enum RelationKinds {
|
||||
#[default]
|
||||
All,
|
||||
Only(Vec<EdgeKind>),
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub enum CategorySelection {
|
||||
#[default]
|
||||
All,
|
||||
Any(Vec<Id>),
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(deny_unknown_fields)]
|
||||
pub enum ContextSelection {
|
||||
#[default]
|
||||
All,
|
||||
Any(Vec<Id>),
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub enum Coverage {
|
||||
#[default]
|
||||
All,
|
||||
InBehavior,
|
||||
OutsideBehavior,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub enum ExchangeLabels {
|
||||
#[default]
|
||||
Name,
|
||||
Items,
|
||||
NameAndItems,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
|
||||
#[serde(default, deny_unknown_fields)]
|
||||
pub struct ViewOptions {
|
||||
pub hidden_edges: Vec<Id>,
|
||||
pub relation_kinds: RelationKinds,
|
||||
pub work_categories: CategorySelection,
|
||||
pub participant_categories: CategorySelection,
|
||||
pub coverage: Coverage,
|
||||
pub work_contexts: ContextSelection,
|
||||
pub exchange_labels: ExchangeLabels,
|
||||
}
|
||||
|
||||
impl ViewOptions {
|
||||
pub fn visit_references(&mut self, mut visit: impl FnMut(&mut Id)) {
|
||||
for id in &mut self.hidden_edges {
|
||||
visit(id);
|
||||
}
|
||||
for selection in [&mut self.work_categories, &mut self.participant_categories] {
|
||||
if let CategorySelection::Any(ids) = selection {
|
||||
for id in ids {
|
||||
visit(id);
|
||||
}
|
||||
}
|
||||
}
|
||||
if let ContextSelection::Any(ids) = &mut self.work_contexts {
|
||||
for id in ids {
|
||||
visit(id);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Removing the last selected identity retains the explicit empty selector.
|
||||
pub fn retain_references(&mut self, mut keep: impl FnMut(&Id) -> bool) {
|
||||
self.hidden_edges.retain(&mut keep);
|
||||
for selection in [&mut self.work_categories, &mut self.participant_categories] {
|
||||
if let CategorySelection::Any(ids) = selection {
|
||||
ids.retain(&mut keep);
|
||||
}
|
||||
}
|
||||
if let ContextSelection::Any(ids) = &mut self.work_contexts {
|
||||
ids.retain(keep);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Stable field names allow core/source adapters to locate the offending option.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct OptionError {
|
||||
pub field: &'static str,
|
||||
pub reference: Option<Id>,
|
||||
pub message: String,
|
||||
}
|
||||
|
||||
pub fn exchange_family(kind: RelationKind) -> Option<ExchangeFamily> {
|
||||
match kind {
|
||||
RelationKind::Interaction | RelationKind::FunctionalExchange => Some(ExchangeFamily::Work),
|
||||
RelationKind::BoundaryExchange | RelationKind::CommunicationMean => {
|
||||
Some(ExchangeFamily::Participant)
|
||||
}
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
fn category_member(p: &Project, layer: Layer, family: ExchangeFamily, id: Id) -> bool {
|
||||
p.relations.get(&id).is_some_and(|r| {
|
||||
p.layer_of(id) == Some(layer)
|
||||
&& matches!(
|
||||
(family, layer, r.kind()),
|
||||
(ExchangeFamily::Work, Layer::Oa, RelationKind::Interaction)
|
||||
| (
|
||||
ExchangeFamily::Work,
|
||||
Layer::Sa,
|
||||
RelationKind::FunctionalExchange
|
||||
)
|
||||
| (
|
||||
ExchangeFamily::Participant,
|
||||
Layer::Oa,
|
||||
RelationKind::CommunicationMean
|
||||
)
|
||||
| (
|
||||
ExchangeFamily::Participant,
|
||||
_,
|
||||
RelationKind::BoundaryExchange
|
||||
)
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
fn context_kind(kind: Kind) -> bool {
|
||||
matches!(kind, Kind::Process | Kind::FunctionalChain | Kind::Scenario)
|
||||
}
|
||||
|
||||
fn edge_layers(p: &Project, id: Id) -> Vec<Layer> {
|
||||
if p.relations.contains_key(&id) {
|
||||
p.layer_of(id).into_iter().collect()
|
||||
} else if p.traces.get(&id).is_some_and(|trace| {
|
||||
p.layer_of(trace.oa) == Some(Layer::Oa) && p.layer_of(trace.sa) == Some(Layer::Sa)
|
||||
}) {
|
||||
vec![Layer::Oa, Layer::Sa]
|
||||
} else {
|
||||
vec![]
|
||||
}
|
||||
}
|
||||
|
||||
fn error(field: &'static str, reference: Option<Id>, message: &str) -> OptionError {
|
||||
OptionError {
|
||||
field,
|
||||
reference,
|
||||
message: message.into(),
|
||||
}
|
||||
}
|
||||
|
||||
fn distinct_ids(field: &'static str, ids: &[Id], out: &mut Vec<OptionError>) {
|
||||
let mut seen = BTreeSet::new();
|
||||
for id in ids {
|
||||
if !seen.insert(*id) {
|
||||
out.push(error(
|
||||
field,
|
||||
Some(*id),
|
||||
"Each identity must occur only once.",
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn validate_category(
|
||||
p: &Project,
|
||||
layer: Layer,
|
||||
parent: Option<Id>,
|
||||
family: ExchangeFamily,
|
||||
exchanges: &[Id],
|
||||
) -> Vec<OptionError> {
|
||||
let mut out = vec![];
|
||||
if parent.is_some() {
|
||||
out.push(error(
|
||||
"parent",
|
||||
parent,
|
||||
"Exchange categories belong at the layer root.",
|
||||
));
|
||||
}
|
||||
distinct_ids("exchanges", exchanges, &mut out);
|
||||
for id in exchanges {
|
||||
if !category_member(p, layer, family, *id) {
|
||||
out.push(error(
|
||||
"exchanges",
|
||||
Some(*id),
|
||||
"Choose an existing exchange of this category's family and layer.",
|
||||
));
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
pub fn validate_options(p: &Project, layer: Layer, options: &ViewOptions) -> Vec<OptionError> {
|
||||
validate_options_in(p, Some(layer), options)
|
||||
}
|
||||
|
||||
/// Traceability views admit references from either architecture layer.
|
||||
pub fn validate_options_cross_layer(p: &Project, options: &ViewOptions) -> Vec<OptionError> {
|
||||
validate_options_in(p, None, options)
|
||||
}
|
||||
|
||||
fn validate_options_in(
|
||||
p: &Project,
|
||||
layer: Option<Layer>,
|
||||
options: &ViewOptions,
|
||||
) -> Vec<OptionError> {
|
||||
let mut out = vec![];
|
||||
distinct_ids("hidden_edges", &options.hidden_edges, &mut out);
|
||||
for id in &options.hidden_edges {
|
||||
let layers = edge_layers(p, *id);
|
||||
if layers.is_empty() || layer.is_some_and(|layer| !layers.contains(&layer)) {
|
||||
out.push(error(
|
||||
"hidden_edges",
|
||||
Some(*id),
|
||||
"Choose an existing relationship or applicable trace in this view's layer.",
|
||||
));
|
||||
}
|
||||
}
|
||||
if let RelationKinds::Only(kinds) = &options.relation_kinds {
|
||||
for (index, kind) in kinds.iter().enumerate() {
|
||||
if kinds[..index].contains(kind) {
|
||||
out.push(error(
|
||||
"relation_kinds",
|
||||
None,
|
||||
"Each relationship-line kind must occur only once.",
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
for (field, selection, family) in [
|
||||
(
|
||||
"work_categories",
|
||||
&options.work_categories,
|
||||
ExchangeFamily::Work,
|
||||
),
|
||||
(
|
||||
"participant_categories",
|
||||
&options.participant_categories,
|
||||
ExchangeFamily::Participant,
|
||||
),
|
||||
] {
|
||||
if let CategorySelection::Any(ids) = selection {
|
||||
distinct_ids(field, ids, &mut out);
|
||||
for id in ids {
|
||||
if !p.elements.get(id).is_some_and(|e| {
|
||||
layer.is_none_or(|layer| e.layer() == layer)
|
||||
&& matches!(e.shared(), Some(SharedBody::ExchangeCategory { family: f, .. }) if *f == family)
|
||||
}) {
|
||||
out.push(error(field, Some(*id), "Choose a category of this selector's family and layer."));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if let ContextSelection::Any(ids) = &options.work_contexts {
|
||||
distinct_ids("work_contexts", ids, &mut out);
|
||||
for id in ids {
|
||||
if !p.elements.get(id).is_some_and(|e| {
|
||||
layer.is_none_or(|layer| e.layer() == layer) && context_kind(e.kind())
|
||||
}) {
|
||||
out.push(error(
|
||||
"work_contexts",
|
||||
Some(*id),
|
||||
"Choose a Process, Functional chain or Scenario in this view's layer.",
|
||||
));
|
||||
}
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Default, PartialEq, Eq)]
|
||||
pub struct BehaviorEvidence {
|
||||
pub work: BTreeSet<Id>,
|
||||
pub exchanges: BTreeSet<Id>,
|
||||
}
|
||||
|
||||
/// Explicit inclusion/reuse graph, independent of semantic-parent descendants.
|
||||
#[derive(Debug, Clone, Default)]
|
||||
struct BehaviorIndex {
|
||||
roots: BTreeMap<Id, Layer>,
|
||||
next: BTreeMap<Id, Vec<Id>>,
|
||||
facts: BTreeMap<Id, BehaviorEvidence>,
|
||||
}
|
||||
|
||||
impl BehaviorIndex {
|
||||
fn new(p: &Project) -> Self {
|
||||
let mut index = Self::default();
|
||||
for element in p.elements.values() {
|
||||
let id = element.id;
|
||||
if context_kind(element.kind()) {
|
||||
index.roots.insert(id, element.layer());
|
||||
}
|
||||
let next = index.next.entry(id).or_default();
|
||||
if let Some(steps) = element.steps() {
|
||||
next.extend(
|
||||
steps
|
||||
.iter()
|
||||
.filter(|step| {
|
||||
p.elements.get(step).is_some_and(|child| {
|
||||
child.kind() == Kind::Occurrence
|
||||
&& child.parent == Some(id)
|
||||
&& child.layer() == element.layer()
|
||||
})
|
||||
})
|
||||
.copied(),
|
||||
);
|
||||
}
|
||||
let Some(SharedBody::Occurrence { body, .. }) = element.shared() else {
|
||||
continue;
|
||||
};
|
||||
match body {
|
||||
OccurrenceBody::Action {
|
||||
action: Some(work), ..
|
||||
} => {
|
||||
if p.elements
|
||||
.get(work)
|
||||
.is_some_and(|e| e.kind().is_work() && e.layer() == element.layer())
|
||||
{
|
||||
index.facts.entry(id).or_default().work.insert(*work);
|
||||
}
|
||||
}
|
||||
OccurrenceBody::Exchange {
|
||||
exchange: Some(exchange),
|
||||
..
|
||||
} => {
|
||||
if let Some(r) = p.relations.get(exchange)
|
||||
&& exchange_family(r.kind()) == Some(ExchangeFamily::Work)
|
||||
&& [r.source(), r.target()].iter().all(|id| {
|
||||
p.elements
|
||||
.get(id)
|
||||
.is_some_and(|e| e.kind().is_work() && e.layer() == element.layer())
|
||||
})
|
||||
{
|
||||
let facts = index.facts.entry(id).or_default();
|
||||
facts.exchanges.insert(*exchange);
|
||||
facts.work.extend([r.source(), r.target()]);
|
||||
}
|
||||
}
|
||||
OccurrenceBody::Fragment { branches, .. } => {
|
||||
next.extend(
|
||||
branches
|
||||
.iter()
|
||||
.filter(|branch| {
|
||||
p.elements.get(branch).is_some_and(|child| {
|
||||
child.parent == Some(id)
|
||||
&& child.layer() == element.layer()
|
||||
&& matches!(
|
||||
child.shared(),
|
||||
Some(SharedBody::Occurrence {
|
||||
body: OccurrenceBody::Branch { .. },
|
||||
..
|
||||
})
|
||||
)
|
||||
})
|
||||
})
|
||||
.copied(),
|
||||
);
|
||||
}
|
||||
OccurrenceBody::SequenceReference {
|
||||
sequence: Some(sequence),
|
||||
} => {
|
||||
if let Some(owner) = element.parent.and_then(|id| p.elements.get(&id))
|
||||
&& matches!(owner.kind(), Kind::Process | Kind::FunctionalChain)
|
||||
&& p.elements.get(sequence).is_some_and(|target| {
|
||||
target.kind() == owner.kind() && target.layer() == element.layer()
|
||||
})
|
||||
{
|
||||
next.push(*sequence);
|
||||
}
|
||||
}
|
||||
OccurrenceBody::ScenarioUse {
|
||||
scenario: Some(scenario),
|
||||
..
|
||||
} if p.elements.get(scenario).is_some_and(|target| {
|
||||
target.kind() == Kind::Scenario && target.layer() == element.layer()
|
||||
}) =>
|
||||
{
|
||||
next.push(*scenario);
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
let topology = crate::topology_context::TopologyIndex::new(p);
|
||||
for relation in p.relations.values() {
|
||||
if let RelationBody::ContextualLink {
|
||||
owner,
|
||||
source,
|
||||
target,
|
||||
purpose: purpose @ ContextualLinkPurpose::Exchange { exchange },
|
||||
} = &relation.body
|
||||
&& topology
|
||||
.validate_link(*owner, source, target, purpose)
|
||||
.is_ok()
|
||||
{
|
||||
let facts = index.facts.entry(*owner).or_default();
|
||||
facts.exchanges.insert(*exchange);
|
||||
if let Some(exchange) = p.relations.get(exchange) {
|
||||
facts.work.extend([exchange.source(), exchange.target()]);
|
||||
}
|
||||
}
|
||||
}
|
||||
index
|
||||
}
|
||||
|
||||
fn evidence(&self, roots: impl IntoIterator<Item = Id>) -> BehaviorEvidence {
|
||||
let mut pending: Vec<_> = roots
|
||||
.into_iter()
|
||||
.filter(|id| self.roots.contains_key(id))
|
||||
.collect();
|
||||
let mut seen = BTreeSet::new();
|
||||
let mut result = BehaviorEvidence::default();
|
||||
while let Some(id) = pending.pop() {
|
||||
if !seen.insert(id) {
|
||||
continue;
|
||||
}
|
||||
if let Some(next) = self.next.get(&id) {
|
||||
pending.extend(next);
|
||||
}
|
||||
if let Some(facts) = self.facts.get(&id) {
|
||||
result.work.extend(&facts.work);
|
||||
result.exchanges.extend(&facts.exchanges);
|
||||
}
|
||||
}
|
||||
result
|
||||
}
|
||||
}
|
||||
|
||||
pub fn behavior_evidence(p: &Project, roots: impl IntoIterator<Item = Id>) -> BehaviorEvidence {
|
||||
BehaviorIndex::new(p).evidence(roots)
|
||||
}
|
||||
|
||||
pub fn all_behavior_evidence(p: &Project) -> BehaviorEvidence {
|
||||
let index = BehaviorIndex::new(p);
|
||||
index.evidence(index.roots.keys().copied())
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
struct EdgeFact {
|
||||
kind: EdgeKind,
|
||||
family: Option<ExchangeFamily>,
|
||||
layers: Vec<Layer>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
struct CategoryFact {
|
||||
layer: Layer,
|
||||
family: ExchangeFamily,
|
||||
exchanges: BTreeSet<Id>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct ViewIndex {
|
||||
edges: BTreeMap<Id, EdgeFact>,
|
||||
categories: BTreeMap<Id, CategoryFact>,
|
||||
behavior: BehaviorIndex,
|
||||
global: BehaviorEvidence,
|
||||
}
|
||||
|
||||
impl ViewIndex {
|
||||
pub fn new(p: &Project) -> Self {
|
||||
let behavior = BehaviorIndex::new(p);
|
||||
let global = behavior.evidence(behavior.roots.keys().copied());
|
||||
let mut edges: BTreeMap<_, _> = p
|
||||
.relations
|
||||
.values()
|
||||
.map(|r| {
|
||||
(
|
||||
r.id,
|
||||
EdgeFact {
|
||||
kind: EdgeKind::Relation(r.kind()),
|
||||
family: exchange_family(r.kind()),
|
||||
layers: edge_layers(p, r.id),
|
||||
},
|
||||
)
|
||||
})
|
||||
.collect();
|
||||
edges.extend(p.traces.keys().map(|id| {
|
||||
(
|
||||
*id,
|
||||
EdgeFact {
|
||||
kind: EdgeKind::Trace,
|
||||
family: None,
|
||||
layers: edge_layers(p, *id),
|
||||
},
|
||||
)
|
||||
}));
|
||||
let categories = p
|
||||
.elements
|
||||
.values()
|
||||
.filter_map(|e| {
|
||||
let SharedBody::ExchangeCategory { family, exchanges } = e.shared()? else {
|
||||
return None;
|
||||
};
|
||||
Some((
|
||||
e.id,
|
||||
CategoryFact {
|
||||
layer: e.layer(),
|
||||
family: *family,
|
||||
exchanges: exchanges
|
||||
.iter()
|
||||
.filter(|id| category_member(p, e.layer(), *family, **id))
|
||||
.copied()
|
||||
.collect(),
|
||||
},
|
||||
))
|
||||
})
|
||||
.collect();
|
||||
Self {
|
||||
edges,
|
||||
categories,
|
||||
behavior,
|
||||
global,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn all_evidence(&self) -> &BehaviorEvidence {
|
||||
&self.global
|
||||
}
|
||||
|
||||
/// Options must pass `validate_options` before model admission. Malformed
|
||||
/// selectors are nevertheless fail-closed here, useful for draft previews.
|
||||
pub fn prepare(&self, layer: Layer, options: &ViewOptions) -> PreparedFilter<'_> {
|
||||
self.prepare_in(layer, options, false)
|
||||
}
|
||||
|
||||
fn prepare_in(
|
||||
&self,
|
||||
layer: Layer,
|
||||
options: &ViewOptions,
|
||||
cross_layer: bool,
|
||||
) -> PreparedFilter<'_> {
|
||||
let category_union = |selection: &CategorySelection, family| match selection {
|
||||
CategorySelection::All => None,
|
||||
CategorySelection::Any(ids) => Some(
|
||||
ids.iter()
|
||||
.filter_map(|id| self.categories.get(id))
|
||||
.filter(|c| (cross_layer || c.layer == layer) && c.family == family)
|
||||
.flat_map(|c| c.exchanges.iter().copied())
|
||||
.collect(),
|
||||
),
|
||||
};
|
||||
let contexts = match &options.work_contexts {
|
||||
ContextSelection::All => None,
|
||||
ContextSelection::Any(ids) => Some(
|
||||
self.behavior
|
||||
.evidence(
|
||||
ids.iter()
|
||||
.filter(|id| {
|
||||
self.behavior
|
||||
.roots
|
||||
.get(id)
|
||||
.is_some_and(|candidate| cross_layer || *candidate == layer)
|
||||
})
|
||||
.copied(),
|
||||
)
|
||||
.exchanges,
|
||||
),
|
||||
};
|
||||
PreparedFilter {
|
||||
index: self,
|
||||
layer,
|
||||
cross_layer,
|
||||
hidden: options.hidden_edges.iter().copied().collect(),
|
||||
kinds: options.relation_kinds.clone(),
|
||||
coverage: options.coverage,
|
||||
work_categories: category_union(&options.work_categories, ExchangeFamily::Work),
|
||||
participant_categories: category_union(
|
||||
&options.participant_categories,
|
||||
ExchangeFamily::Participant,
|
||||
),
|
||||
contexts,
|
||||
}
|
||||
}
|
||||
|
||||
/// Traceability diagrams admit edges, categories and contexts in both layers.
|
||||
pub fn prepare_cross_layer(&self, layer: Layer, options: &ViewOptions) -> PreparedFilter<'_> {
|
||||
self.prepare_in(layer, options, true)
|
||||
}
|
||||
}
|
||||
|
||||
/// Projection reports why an actual edge cannot have a drawable endpoint pair.
|
||||
/// Filtering does not perform anchoring, folding, layout or placement insertion.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub enum EdgeAvailability {
|
||||
Visible,
|
||||
OutsideProjection,
|
||||
EndpointNotShown { source: bool, target: bool },
|
||||
FoldedInternal,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub enum OmissionReason {
|
||||
ExplicitHide,
|
||||
RelationKind,
|
||||
Category(ExchangeFamily),
|
||||
Coverage,
|
||||
WorkContext,
|
||||
OutsideProjection,
|
||||
EndpointNotShown { source: bool, target: bool },
|
||||
FoldedInternal,
|
||||
WrongLayer,
|
||||
UnknownEdge,
|
||||
}
|
||||
|
||||
pub struct PreparedFilter<'a> {
|
||||
index: &'a ViewIndex,
|
||||
layer: Layer,
|
||||
cross_layer: bool,
|
||||
hidden: BTreeSet<Id>,
|
||||
kinds: RelationKinds,
|
||||
coverage: Coverage,
|
||||
work_categories: Option<BTreeSet<Id>>,
|
||||
participant_categories: Option<BTreeSet<Id>>,
|
||||
contexts: Option<BTreeSet<Id>>,
|
||||
}
|
||||
|
||||
impl PreparedFilter<'_> {
|
||||
pub fn includes(&self, edge: Id) -> bool {
|
||||
self.reasons(edge, EdgeAvailability::Visible).is_empty()
|
||||
}
|
||||
|
||||
pub fn reasons(&self, edge: Id, availability: EdgeAvailability) -> Vec<OmissionReason> {
|
||||
let mut out = vec![];
|
||||
if self.hidden.contains(&edge) {
|
||||
out.push(OmissionReason::ExplicitHide);
|
||||
}
|
||||
match availability {
|
||||
EdgeAvailability::Visible => {}
|
||||
EdgeAvailability::OutsideProjection => out.push(OmissionReason::OutsideProjection),
|
||||
EdgeAvailability::EndpointNotShown { source, target } => {
|
||||
out.push(OmissionReason::EndpointNotShown { source, target })
|
||||
}
|
||||
EdgeAvailability::FoldedInternal => out.push(OmissionReason::FoldedInternal),
|
||||
}
|
||||
let Some(fact) = self.index.edges.get(&edge) else {
|
||||
out.push(OmissionReason::UnknownEdge);
|
||||
return out;
|
||||
};
|
||||
if !fact.layers.contains(&self.layer) && !(self.cross_layer && !fact.layers.is_empty()) {
|
||||
out.push(OmissionReason::WrongLayer);
|
||||
}
|
||||
if let RelationKinds::Only(kinds) = &self.kinds
|
||||
&& !kinds.contains(&fact.kind)
|
||||
{
|
||||
out.push(OmissionReason::RelationKind);
|
||||
}
|
||||
if let Some(family) = fact.family {
|
||||
let categories = match family {
|
||||
ExchangeFamily::Work => &self.work_categories,
|
||||
ExchangeFamily::Participant => &self.participant_categories,
|
||||
};
|
||||
if categories.as_ref().is_some_and(|ids| !ids.contains(&edge)) {
|
||||
out.push(OmissionReason::Category(family));
|
||||
}
|
||||
if family == ExchangeFamily::Work {
|
||||
let covered = self.index.global.exchanges.contains(&edge);
|
||||
if matches!(self.coverage, Coverage::InBehavior) && !covered
|
||||
|| matches!(self.coverage, Coverage::OutsideBehavior) && covered
|
||||
{
|
||||
out.push(OmissionReason::Coverage);
|
||||
}
|
||||
if self
|
||||
.contexts
|
||||
.as_ref()
|
||||
.is_some_and(|ids| !ids.contains(&edge))
|
||||
{
|
||||
out.push(OmissionReason::WorkContext);
|
||||
}
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
}
|
||||
|
||||
impl ExchangeLabels {
|
||||
pub fn label(self, p: &Project, edge: Id) -> String {
|
||||
let name = p.named(edge);
|
||||
let Some(relation) = p
|
||||
.relations
|
||||
.get(&edge)
|
||||
.filter(|r| exchange_family(r.kind()).is_some())
|
||||
else {
|
||||
return name.into();
|
||||
};
|
||||
if self == Self::Name {
|
||||
return name.into();
|
||||
}
|
||||
let items = if relation.body.items().is_empty() {
|
||||
"No items".into()
|
||||
} else {
|
||||
relation
|
||||
.body
|
||||
.items()
|
||||
.iter()
|
||||
.map(|id| p.named(*id))
|
||||
.collect::<Vec<_>>()
|
||||
.join(", ")
|
||||
};
|
||||
if self == Self::Items {
|
||||
items
|
||||
} else {
|
||||
format!("{name} · {items}")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "view_options_tests.rs"]
|
||||
mod tests;
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user