opy_rs/lib.rs
1//! The standalone OverPy-compatible `.opy` implementation (opy-rs).
2//!
3//! Owns the OPY source-language surface of the `opy-rs` repository: a lexer,
4//! an indentation-aware CST/parser with structured diagnostics and recovery,
5//! token-level preprocessing (includes and `#!define`/`#!defineMember` macros), semantic
6//! resolution, and lowering into the opy-rs-owned Opy HIR contract
7//! ([`hir::Program`]). Everything from source through the Opy HIR semantic
8//! model is Workshop-independent: source analysis never depends on `workshop-rs`,
9//! OverPy, or Node. The bounded source-to-Workshop compiler is exposed from
10//! this same crate behind the explicit [`Compiler`] API.
11//!
12//! Pipeline: [`lexer::lex`] → [`preprocess::preprocess`] →
13//! [`parser::parse`] → [`lower::lower`] → Opy HIR ([`hir`]).
14//!
15//! OverPy-compatible `__script__("…")` macros execute at compile time through
16//! the bounded embedded macro runtime: script macros expand
17//! during preprocessing with the reference's argument-injection ABI, and
18//! resource limits mirror the pinned reference constants
19//! (`macro_js::Limits::default()`). Script-macro expansion is
20//! compile-time behavior and is source-supported.
21//!
22//! `#!postCompileHook` is recognized, parsed, validated, and recorded only
23//! (see [`preprocess`] and [`CompileOutcome::post_compile_hook`]): the
24//! The source implementation never executes the hook. Real hook execution
25//! receives the final Workshop text produced by lowering and is
26//! lowering-dependent (workshop-rs emission, issue #8); source analysis never
27//! fabricates a Workshop payload.
28//!
29//! This crate owns the OverPy source-language implementation, its bounded
30//! compiler, Workshop→OPY reconstruction, and the isolated differential
31//! harness entry points.
32
33pub(crate) mod compile_time;
34pub(crate) mod compiler;
35pub mod cst;
36pub mod diag;
37pub mod hir;
38pub mod lexer;
39pub mod lower;
40mod macro_js;
41pub mod manifest;
42pub mod parser;
43pub mod preprocess;
44pub mod project;
45#[cfg(test)]
46pub(crate) mod resource_metrics;
47pub mod settings;
48mod string_entities;
49pub mod tooling;
50
51use std::path::Path;
52
53pub use compiler::reconstruct;
54pub use compiler::{
55 COMPILE_SCHEMA_VERSION, CompilationArtifact, CompileDiagnostic, CompileFailureClass,
56 CompileOutput, CompileReport, CompileResult, CompileStatus, Compiler, CompilerIdentity,
57 IntegrationDiagnostic, IntegrationError, LinkReport, ScriptDiagnostic,
58};
59use diag::Span;
60pub use diag::{OpyError, OpyResult};
61pub use lower::lower;
62pub use parser::parse;
63pub use preprocess::{preprocess, preprocess_with_overlay};
64pub use project::{FilesystemProject, FilesystemProjectError};
65
66#[cfg(test)]
67mod tests {
68 use super::compile;
69 use std::path::Path;
70
71 #[test]
72 fn unsupported_operator_aliases_fail_at_the_source_boundary() {
73 for expression in ["a // 2", "a //= 2", "a ^ 2", "a && 2", "a || 2", "a = !2"] {
74 let source = format!(
75 "globalvar a\nrule \"unsupported operator\":\n @Event global\n {expression}\n"
76 );
77 let error = compile(&source, "unsupported-operator.opy", Path::new("."))
78 .expect_err("unsupported operator alias unexpectedly compiled");
79 assert!(matches!(error.code.as_str(), "lex-error" | "parse-error"));
80 assert!(error.span.is_some(), "{expression}: missing source span");
81 }
82 }
83
84 #[test]
85 fn implicit_event_player_defaults_satisfy_hir_reference_validation() {
86 let hir = compile(
87 "rule \"implicit player\":\n @Event eachPlayer\n eventPlayer.A = 1\n",
88 "implicit-player.opy",
89 Path::new("."),
90 )
91 .expect("implicit event-player default must resolve");
92 hir.validate()
93 .expect("implicit event-player default must satisfy HIR invariants");
94 }
95}
96
97/// The producer identity for generated HIR.
98///
99/// The producer identity and the Opy HIR protocol envelope (`wright/opy-hir`
100/// v2) is emitted for the ordered switch-arm wire grammar; v1 consumers must
101/// reject it until they migrate to the v2 contract.
102pub const LANGUAGE_NAME: &str = "opy-rs";
103pub const LANGUAGE_VERSION: &str = env!("CARGO_PKG_VERSION");
104
105/// Compile one `.opy` source end-to-end into the Opy HIR contract:
106/// preprocess (includes/defines) → parse (CST) → lower (HIR).
107///
108/// `main_path` is the file's display path recorded in the HIR file registry;
109/// `root` is the include base. `compile` never requires Node or OverPy.
110pub fn compile(source: &str, main_path: &str, root: &Path) -> OpyResult<hir::Program> {
111 compile_with_overlay(source, main_path, root, &std::collections::BTreeMap::new())
112}
113
114/// Compile with open-document overlays: includes resolve to overlay text
115/// (keyed by the include string or the resolved canonical path) before the
116/// filesystem, so unsaved editor buffers participate in include resolution.
117pub fn compile_with_overlay(
118 source: &str,
119 main_path: &str,
120 root: &Path,
121 overlay: &std::collections::BTreeMap<String, String>,
122) -> OpyResult<hir::Program> {
123 let outcome = compile_with_overlay_outcome(source, main_path, root, overlay);
124 match outcome.hir {
125 Some(hir) => Ok(hir),
126 None => Err(outcome
127 .error
128 .expect("a failed compile outcome always carries an error")),
129 }
130}
131
132/// The outcome of a compile with overlays.
133///
134/// Unlike [`compile_with_overlay`], this retains the source file registry
135/// even when parsing or lowering fails, so language tooling can map span file
136/// ids to their actual source identities without building a diagnostics-only
137/// project model.
138pub struct CompileOutcome {
139 pub hir: Option<hir::Program>,
140 pub error: Option<OpyError>,
141 pub diagnostics: Vec<tooling::Diagnostic>,
142 pub files: Vec<preprocess::FileRecord>,
143 /// The directory the `files` display paths resolve against — the
144 /// `#!mainFile` effective directory when the entry redirects the project
145 /// root, otherwise the canonicalized input root.
146 pub display_root: std::path::PathBuf,
147 /// The declared `#!postCompileHook` script, when the source declared one
148 /// and compilation succeeded.
149 ///
150 /// This is the declaration record, not an execution result: the OPY
151 /// implementation
152 /// recognizes, parses, validates, and records the directive, but never
153 /// executes the hook. Execution against the final Workshop text is
154 /// lowering-dependent (workshop-rs emission, issue #8); source analysis
155 /// never fabricates a Workshop payload.
156 pub post_compile_hook: Option<PostCompileHookRecord>,
157}
158
159/// The recorded declaration of a `#!postCompileHook` script.
160///
161/// The declared `#!postCompileHook` script; execution against the final
162/// Workshop text is lowering-dependent (workshop-rs emission, issue #8). The
163/// frontend never fabricates a Workshop payload.
164#[derive(Debug, Clone, PartialEq, Eq)]
165pub struct PostCompileHookRecord {
166 /// The resolved project-relative script path.
167 pub script: String,
168 /// The resolved script source, retained for the backend hook ABI.
169 pub source: String,
170 /// The directive's source span, when known.
171 pub span: Option<Span>,
172}
173
174/// Compile with open-document overlays while retaining the source file registry
175/// on parse/lower failure.
176///
177/// This is the compile contract view of [`tooling::check_with_overlay`]: the
178/// two share one pipeline, so `check` and `compile` never disagree about
179/// whether a project is clean.
180pub fn compile_with_overlay_outcome(
181 source: &str,
182 main_path: &str,
183 root: &Path,
184 overlay: &std::collections::BTreeMap<String, String>,
185) -> CompileOutcome {
186 let outcome = tooling::check_with_overlay(source, main_path, root, overlay);
187 // Every failed check carries at least one error diagnostic, so a None model
188 // always yields an error (the compile outcome invariant).
189 let error = outcome
190 .diagnostics
191 .iter()
192 .find(|diagnostic| diagnostic.severity == tooling::DiagnosticSeverity::Error)
193 .map(|diagnostic| OpyError {
194 code: diagnostic.code.clone(),
195 message: diagnostic.message.clone(),
196 span: diagnostic
197 .span
198 .as_ref()
199 .map(tooling::SourceLocation::to_span),
200 });
201 // The directive was parsed, validated, and recorded by preprocessing; the
202 // source implementation never executes the hook (real hook execution receives the
203 // final Workshop text and is lowering-dependent, issue #8 — see
204 // `PostCompileHookRecord`).
205 let post_compile_hook = outcome.post_compile_hook.map(|hook| PostCompileHookRecord {
206 script: hook.path,
207 source: hook.source,
208 span: Some(hook.span),
209 });
210 CompileOutcome {
211 hir: outcome.model.map(|model| model.hir),
212 error,
213 diagnostics: outcome.diagnostics,
214 files: outcome.files,
215 display_root: outcome.display_root,
216 post_compile_hook,
217 }
218}