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 declared `#!postCompileHook` script, when the source declared one
144 /// and compilation succeeded.
145 ///
146 /// This is the declaration record, not an execution result: the OPY
147 /// implementation
148 /// recognizes, parses, validates, and records the directive, but never
149 /// executes the hook. Execution against the final Workshop text is
150 /// lowering-dependent (workshop-rs emission, issue #8); source analysis
151 /// never fabricates a Workshop payload.
152 pub post_compile_hook: Option<PostCompileHookRecord>,
153}
154
155/// The recorded declaration of a `#!postCompileHook` script.
156///
157/// The declared `#!postCompileHook` script; execution against the final
158/// Workshop text is lowering-dependent (workshop-rs emission, issue #8). The
159/// frontend never fabricates a Workshop payload.
160#[derive(Debug, Clone, PartialEq, Eq)]
161pub struct PostCompileHookRecord {
162 /// The resolved project-relative script path.
163 pub script: String,
164 /// The resolved script source, retained for the backend hook ABI.
165 pub source: String,
166 /// The directive's source span, when known.
167 pub span: Option<Span>,
168}
169
170/// Compile with open-document overlays while retaining the source file registry
171/// on parse/lower failure.
172///
173/// This is the compile contract view of [`tooling::check_with_overlay`]: the
174/// two share one pipeline, so `check` and `compile` never disagree about
175/// whether a project is clean.
176pub fn compile_with_overlay_outcome(
177 source: &str,
178 main_path: &str,
179 root: &Path,
180 overlay: &std::collections::BTreeMap<String, String>,
181) -> CompileOutcome {
182 let outcome = tooling::check_with_overlay(source, main_path, root, overlay);
183 // Every failed check carries at least one error diagnostic, so a None model
184 // always yields an error (the compile outcome invariant).
185 let error = outcome
186 .diagnostics
187 .iter()
188 .find(|diagnostic| diagnostic.severity == tooling::DiagnosticSeverity::Error)
189 .map(|diagnostic| OpyError {
190 code: diagnostic.code.clone(),
191 message: diagnostic.message.clone(),
192 span: diagnostic
193 .span
194 .as_ref()
195 .map(tooling::SourceLocation::to_span),
196 });
197 // The directive was parsed, validated, and recorded by preprocessing; the
198 // source implementation never executes the hook (real hook execution receives the
199 // final Workshop text and is lowering-dependent, issue #8 — see
200 // `PostCompileHookRecord`).
201 let post_compile_hook = outcome.post_compile_hook.map(|hook| PostCompileHookRecord {
202 script: hook.path,
203 source: hook.source,
204 span: Some(hook.span),
205 });
206 CompileOutcome {
207 hir: outcome.model.map(|model| model.hir),
208 error,
209 diagnostics: outcome.diagnostics,
210 files: outcome.files,
211 post_compile_hook,
212 }
213}