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