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 settings;
45pub mod support;
46pub mod tooling;
47
48use std::path::Path;
49
50pub use compiler::reconstruct;
51pub use compiler::{
52 COMPILE_SCHEMA_VERSION, CompilationArtifact, CompileDiagnostic, CompileFailureClass,
53 CompileOutput, CompileReport, CompileResult, CompileStatus, Compiler, CompilerIdentity,
54 IntegrationDiagnostic, IntegrationError, LinkReport, ScriptDiagnostic, WORKSHOP_RS_VERSION,
55};
56use diag::Span;
57pub use diag::{OpyError, OpyResult};
58pub use lower::lower;
59pub use parser::parse;
60pub use preprocess::{preprocess, preprocess_with_overlay};
61
62#[cfg(test)]
63mod tests {
64 use super::compile;
65 use std::path::Path;
66
67 #[test]
68 fn unsupported_operator_aliases_fail_at_the_source_boundary() {
69 for expression in ["a // 2", "a //= 2", "a ^ 2", "a && 2", "a || 2", "a = !2"] {
70 let source = format!(
71 "globalvar a\nrule \"unsupported operator\":\n @Event global\n {expression}\n"
72 );
73 let error = compile(&source, "unsupported-operator.opy", Path::new("."))
74 .expect_err("unsupported operator alias unexpectedly compiled");
75 assert!(matches!(error.code.as_str(), "lex-error" | "parse-error"));
76 assert!(error.span.is_some(), "{expression}: missing source span");
77 }
78 }
79
80 #[test]
81 fn implicit_event_player_defaults_satisfy_hir_reference_validation() {
82 let hir = compile(
83 "rule \"implicit player\":\n @Event eachPlayer\n eventPlayer.A = 1\n",
84 "implicit-player.opy",
85 Path::new("."),
86 )
87 .expect("implicit event-player default must resolve");
88 hir.validate()
89 .expect("implicit event-player default must satisfy HIR invariants");
90 }
91}
92
93/// The producer identity for generated HIR.
94///
95/// The producer identity and the Opy HIR protocol envelope (`wright/opy-hir`
96/// v2) is emitted for the ordered switch-arm wire grammar; v1 consumers must
97/// reject it until they migrate to the v2 contract.
98pub const LANGUAGE_NAME: &str = "opy-rs";
99pub const LANGUAGE_VERSION: &str = env!("CARGO_PKG_VERSION");
100
101/// Compile one `.opy` source end-to-end into the Opy HIR contract:
102/// preprocess (includes/defines) → parse (CST) → lower (HIR).
103///
104/// `main_path` is the file's display path recorded in the HIR file registry;
105/// `root` is the include base. `compile` never requires Node or OverPy.
106pub fn compile(source: &str, main_path: &str, root: &Path) -> OpyResult<hir::Program> {
107 compile_with_overlay(source, main_path, root, &std::collections::BTreeMap::new())
108}
109
110/// Compile with open-document overlays: includes resolve to overlay text
111/// (keyed by the include string or the resolved canonical path) before the
112/// filesystem, so unsaved editor buffers participate in include resolution.
113pub fn compile_with_overlay(
114 source: &str,
115 main_path: &str,
116 root: &Path,
117 overlay: &std::collections::BTreeMap<String, String>,
118) -> OpyResult<hir::Program> {
119 let outcome = compile_with_overlay_outcome(source, main_path, root, overlay);
120 match outcome.hir {
121 Some(hir) => Ok(hir),
122 None => Err(outcome
123 .error
124 .expect("a failed compile outcome always carries an error")),
125 }
126}
127
128/// The outcome of a compile with overlays.
129///
130/// Unlike [`compile_with_overlay`], this retains the source file registry
131/// even when parsing or lowering fails, so language tooling can map span file
132/// ids to their actual source identities without building a diagnostics-only
133/// project model.
134pub struct CompileOutcome {
135 pub hir: Option<hir::Program>,
136 pub error: Option<OpyError>,
137 pub diagnostics: Vec<tooling::Diagnostic>,
138 pub files: Vec<preprocess::FileRecord>,
139 /// The declared `#!postCompileHook` script, when the source declared one
140 /// and compilation succeeded.
141 ///
142 /// This is the declaration record, not an execution result: the OPY
143 /// implementation
144 /// recognizes, parses, validates, and records the directive, but never
145 /// executes the hook. Execution against the final Workshop text is
146 /// lowering-dependent (workshop-rs emission, issue #8); source analysis
147 /// never fabricates a Workshop payload.
148 pub post_compile_hook: Option<PostCompileHookRecord>,
149}
150
151/// The recorded declaration of a `#!postCompileHook` script.
152///
153/// The declared `#!postCompileHook` script; execution against the final
154/// Workshop text is lowering-dependent (workshop-rs emission, issue #8). The
155/// frontend never fabricates a Workshop payload.
156#[derive(Debug, Clone, PartialEq, Eq)]
157pub struct PostCompileHookRecord {
158 /// The resolved project-relative script path.
159 pub script: String,
160 /// The resolved script source, retained for the backend hook ABI.
161 pub source: String,
162 /// The directive's source span, when known.
163 pub span: Option<Span>,
164}
165
166/// Compile with open-document overlays while retaining the source file registry
167/// on parse/lower failure.
168///
169/// This is the compile contract view of [`tooling::check_with_overlay`]: the
170/// two share one pipeline, so `check` and `compile` never disagree about
171/// whether a project is clean.
172pub fn compile_with_overlay_outcome(
173 source: &str,
174 main_path: &str,
175 root: &Path,
176 overlay: &std::collections::BTreeMap<String, String>,
177) -> CompileOutcome {
178 let outcome = tooling::check_with_overlay(source, main_path, root, overlay);
179 // Every failed check carries at least one error diagnostic, so a None model
180 // always yields an error (the compile outcome invariant).
181 let error = outcome
182 .diagnostics
183 .iter()
184 .find(|diagnostic| diagnostic.severity == tooling::DiagnosticSeverity::Error)
185 .map(|diagnostic| OpyError {
186 code: diagnostic.code.clone(),
187 message: diagnostic.message.clone(),
188 span: diagnostic
189 .span
190 .as_ref()
191 .map(tooling::SourceLocation::to_span),
192 });
193 // The directive was parsed, validated, and recorded by preprocessing; the
194 // source implementation never executes the hook (real hook execution receives the
195 // final Workshop text and is lowering-dependent, issue #8 — see
196 // `PostCompileHookRecord`).
197 let post_compile_hook = outcome.post_compile_hook.map(|hook| PostCompileHookRecord {
198 script: hook.path,
199 source: hook.source,
200 span: Some(hook.span),
201 });
202 CompileOutcome {
203 hir: outcome.model.map(|model| model.hir),
204 error,
205 diagnostics: outcome.diagnostics,
206 files: outcome.files,
207 post_compile_hook,
208 }
209}