Skip to main content

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