Skip to main content

ruau_bytecode/compile/
mod.rs

1//! Minimal AST-to-bytecode compiler entry points.
2
3use std::{
4    fmt,
5    rc::Rc,
6    sync::{
7        Arc,
8        atomic::{AtomicBool, Ordering},
9    },
10};
11
12use ruau_ast::{
13    Location,
14    parse::{parse_file_bytes_with, parse_file_with},
15    syntax::Stat,
16    visit::{Visitor, WalkControl, walk_stat},
17};
18
19use crate::BytecodeChunk;
20
21mod analysis;
22mod builtin_folding;
23mod context;
24mod function_compiler;
25mod helpers;
26mod inline_cost;
27mod options;
28
29use analysis::ConstantValue;
30use context::CompileContext;
31#[cfg(test)]
32use function_compiler::constant_ad_operand;
33use function_compiler::{
34    BreakBranchKind, FunctionCompiler, LoopControlBranchKind, LoopUnrollPlan, TypeAliasInfo,
35};
36use helpers::*;
37pub use options::{
38    CompileOptions, FastFlag, FastInt, KnownMember, KnownMemberValue, UpstreamCompilerOptions,
39    UpstreamParseOptions, effective_compile_options, source_compile_options,
40};
41
42pub const CONSTANT_STRING_FOLD_LIMIT: usize = 4096;
43const EXPORT_TOP_LEVEL_MESSAGE: &str = "'export' may only be applied to top-level statements";
44const EXPORT_RETURN_CONFLICT_MESSAGE: &str =
45    "Exporting values is not compatible with top-level return (export/return conflict)";
46
47/// Compiler failure.
48///
49/// Failures carry structured data, not just display text: [`kind`](Self::kind)
50/// is the stable category, [`location`](Self::location) the source range when
51/// one is known, and [`message`](Self::message) the text without any location
52/// prefix. Compilation is chunk-name-agnostic — a chunk name is bound when a
53/// compiled chunk is loaded into a VM — so a compile error carries no chunk
54/// name; an embedder prefixes its own.
55#[derive(Clone, Debug, Eq, PartialEq)]
56pub struct CompileError {
57    kind: CompileErrorKind,
58    location: Option<Location>,
59    message: String,
60}
61
62/// Stable category of a [`CompileError`].
63#[derive(Clone, Copy, Debug, Eq, PartialEq)]
64#[non_exhaustive]
65pub enum CompileErrorKind {
66    /// The source did not parse (or used a rejected construct); `location`
67    /// carries the failing range when known.
68    Parse,
69    /// Compilation was cancelled at a cooperative safepoint.
70    Cancelled,
71    /// The compiler hit an internal limit or invariant.
72    Internal,
73}
74
75impl CompileError {
76    /// An [`CompileErrorKind::Internal`] error with no location: a compiler
77    /// limit or invariant, not a source-text fault. Public so layers above the
78    /// compiler (artifact validation of a freshly compiled chunk) can report
79    /// their own internal failures in the compiler's error vocabulary.
80    pub fn new(message: impl Into<String>) -> Self {
81        Self {
82            kind: CompileErrorKind::Internal,
83            location: None,
84            message: message.into(),
85        }
86    }
87
88    /// A cancellation error with no source location.
89    pub fn cancelled() -> Self {
90        Self {
91            kind: CompileErrorKind::Cancelled,
92            location: None,
93            message: "compilation cancelled".to_owned(),
94        }
95    }
96
97    fn parse(message: impl Into<String>, location: Location) -> Self {
98        Self {
99            kind: CompileErrorKind::Parse,
100            location: Some(location),
101            message: message.into(),
102        }
103    }
104
105    /// Stable error category.
106    #[must_use]
107    pub fn kind(&self) -> CompileErrorKind {
108        self.kind
109    }
110
111    /// Source range associated with the failure, when known.
112    ///
113    /// Parse failures carry the failing token's full range with zero-based
114    /// [`Location`] lines and columns; [`Display`](fmt::Display) renders the
115    /// 1-based `begin` position as `line:column: message`. Internal
116    /// compiler-limit failures track no source position and return `None`.
117    #[must_use]
118    pub fn location(&self) -> Option<Location> {
119        self.location
120    }
121
122    /// Human-readable failure text (without location prefix).
123    #[must_use]
124    pub fn message(&self) -> &str {
125        &self.message
126    }
127}
128
129impl fmt::Display for CompileError {
130    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
131        if let Some(location) = self.location {
132            write!(
133                f,
134                "{}:{}: {}",
135                location.begin.line + 1,
136                location.begin.column + 1,
137                self.message
138            )
139        } else {
140            f.write_str(&self.message)
141        }
142    }
143}
144
145impl std::error::Error for CompileError {}
146
147/// Compiles source into a decoded bytecode chunk.
148///
149/// A malformed program is reported as the wire-compatible
150/// `Ok(BytecodeChunk::Error { .. })` chunk, with its `":<line>: <message>"`
151/// payload rendered from the structured [`CompileErrorKind::Parse`] failure
152/// the strict channel reports.
153///
154/// # Errors
155/// Returns an internal error for compiler limits, or
156/// [`CompileErrorKind::Cancelled`] when the `cancel` flag is set at a
157/// cooperative compiler safepoint.
158pub fn compile_source(
159    source: &str,
160    options: &CompileOptions,
161    cancel: Option<Arc<AtomicBool>>,
162) -> Result<BytecodeChunk, CompileError> {
163    chunkify_parse_error(compile_source_strict(source, options, cancel))
164}
165
166/// Compiles arbitrary source bytes into a decoded bytecode chunk.
167///
168/// Mirrors [`compile_source`] for inputs that are not valid UTF-8: string
169/// literals and byte-column locations preserve the original bytes, while a
170/// same-length surrogate string drives lexing and leading hot-comment scanning.
171///
172/// # Errors
173/// As [`compile_source`].
174pub fn compile_source_bytes(
175    source: &[u8],
176    options: &CompileOptions,
177    cancel: Option<Arc<AtomicBool>>,
178) -> Result<BytecodeChunk, CompileError> {
179    chunkify_parse_error(compile_source_bytes_strict(source, options, cancel))
180}
181
182/// Compiles source, returning malformed programs as `Err`.
183///
184/// # Errors
185/// Returns a parse error for malformed source, an internal error for compiler
186/// limits, or [`CompileErrorKind::Cancelled`] when the `cancel` flag is set at
187/// a cooperative compiler safepoint.
188pub fn compile_source_strict(
189    source: &str,
190    options: &CompileOptions,
191    cancel: Option<Arc<AtomicBool>>,
192) -> Result<BytecodeChunk, CompileError> {
193    let options = options.to_upstream_options();
194    compile_source_strict_with_upstream_options(source, &options, cancel)
195}
196
197/// Compiles source with the repository's upstream-fixture option shape,
198/// returning malformed programs as `Err`.
199///
200/// Wrap the result in [`chunkify_parse_error`] for the lenient error-chunk
201/// behavior of [`compile_source`].
202#[doc(hidden)]
203pub fn compile_source_strict_with_upstream_options(
204    source: &str,
205    options: &UpstreamCompilerOptions,
206    cancel: Option<Arc<AtomicBool>>,
207) -> Result<BytecodeChunk, CompileError> {
208    let effective = source_compile_options(source, options);
209    check_compile_cancelled(cancel.as_ref())?;
210    let parse = parse_file_with(source, &effective.parse_config());
211    if let Some(error) = parse.errors.first() {
212        // Upstream reports only the *first* parse error (`Compiler.cpp`);
213        // recovery may queue more. The error keeps the parser's structured
214        // location rather than round-tripping through rendered text.
215        return Err(CompileError::parse(error.message.clone(), error.location));
216    }
217    compile_ast_with_implicit_return_delta(
218        parse.root,
219        &effective,
220        u8::from(source.ends_with('\n')),
221        cancel,
222    )
223}
224
225/// Byte-preserving form of [`compile_source_strict`].
226///
227/// # Errors
228/// As [`compile_source_strict`].
229pub fn compile_source_bytes_strict(
230    source: &[u8],
231    options: &CompileOptions,
232    cancel: Option<Arc<AtomicBool>>,
233) -> Result<BytecodeChunk, CompileError> {
234    let options = options.to_upstream_options();
235    compile_source_bytes_strict_with_upstream_options(source, &options, cancel)
236}
237
238/// Byte-preserving form of [`compile_source_strict_with_upstream_options`].
239#[doc(hidden)]
240pub fn compile_source_bytes_strict_with_upstream_options(
241    source: &[u8],
242    options: &UpstreamCompilerOptions,
243    cancel: Option<Arc<AtomicBool>>,
244) -> Result<BytecodeChunk, CompileError> {
245    // Hot comments and `--!` directives are ASCII at the file head, so a lossy
246    // view is sufficient to derive the effective options; the byte-precise
247    // content flows through `parse_file_bytes_with`.
248    let lossy = String::from_utf8_lossy(source);
249    let effective = source_compile_options(&lossy, options);
250    check_compile_cancelled(cancel.as_ref())?;
251    let parse = parse_file_bytes_with(source, &effective.parse_config());
252    if let Some(error) = parse.errors.first() {
253        return Err(CompileError::parse(error.message.clone(), error.location));
254    }
255    compile_ast_with_implicit_return_delta(
256        parse.root,
257        &effective,
258        u8::from(source.ends_with(b"\n")),
259        cancel,
260    )
261}
262
263/// Folds a parse-shaped failure into the wire-compatible error chunk: upstream
264/// encodes it as ":<line>: <message>" (`Compiler.cpp`); the chunk-id prefix is
265/// added by the caller (`luau_load`/`loadstring`), which knows the chunk name.
266/// Internal compiler-limit errors stay on the `Err` channel.
267///
268/// Public (but hidden) so fixture tooling and the VM's `loadstring` path can
269/// combine it with the `*_with_upstream_options` strict entry points to get
270/// the lenient behavior of [`compile_source`]/[`compile_source_bytes`].
271#[doc(hidden)]
272pub fn chunkify_parse_error(
273    result: Result<BytecodeChunk, CompileError>,
274) -> Result<BytecodeChunk, CompileError> {
275    match result {
276        Err(error) if error.kind() == CompileErrorKind::Parse => {
277            let message = match error.location() {
278                Some(location) => {
279                    format!(":{}: {}", location.begin.line + 1, error.message())
280                }
281                None => error.message().to_owned(),
282            };
283            Ok(BytecodeChunk::Error {
284                message: message.into_bytes(),
285            })
286        }
287        other => other,
288    }
289}
290
291/// The single-position [`Location`] of a 1-based source line whose column is
292/// not tracked, for compile-stage failures that know only their line.
293fn line_location(line: u32) -> Location {
294    let position = ruau_ast::Position {
295        line: line.saturating_sub(1),
296        column: 0,
297    };
298    Location {
299        begin: position,
300        end: position,
301    }
302}
303
304fn compile_ast_with_implicit_return_delta(
305    root: Stat,
306    options: &UpstreamCompilerOptions,
307    implicit_return_line_delta: u8,
308    cancel: Option<Arc<AtomicBool>>,
309) -> Result<BytecodeChunk, CompileError> {
310    check_compile_cancelled(cancel.as_ref())?;
311    if let Some((line, message)) = repeat_continue_condition_error(&root) {
312        return Err(CompileError::parse(message, line_location(line)));
313    }
314    if let Some((location, message)) = export_value_ast_error(&root) {
315        return Err(CompileError::parse(message, location));
316    }
317
318    // Takes the root by value and shares it (`Rc`) between the context and the
319    // compile pass — the compile pipeline never deep-copies the module AST.
320    let root = Rc::new(root);
321    let context = CompileContext::with_cancel(Rc::clone(&root), options, cancel);
322    context.check_cancelled()?;
323    let mut compiler = FunctionCompiler::new(context, implicit_return_line_delta);
324    compiler.compile_registered_functions_for_root(&root)?;
325    compiler.compile_root(&root)?;
326    Ok(compiler.finish())
327}
328
329fn check_compile_cancelled(cancel: Option<&Arc<AtomicBool>>) -> Result<(), CompileError> {
330    if cancel.is_some_and(|cancel| cancel.load(Ordering::Relaxed)) {
331        return Err(CompileError::cancelled());
332    }
333    Ok(())
334}
335
336fn export_value_ast_error(root: &Stat) -> Option<(Location, &'static str)> {
337    let Stat::Block { body, .. } = root else {
338        return exported_value_location(root).map(|location| (location, EXPORT_TOP_LEVEL_MESSAGE));
339    };
340
341    let mut has_export = false;
342    let mut has_return = false;
343    for stat in body {
344        if let Some(location) = nested_exported_value_location(stat) {
345            return Some((location, EXPORT_TOP_LEVEL_MESSAGE));
346        }
347        if let Some(location) = exported_value_location(stat) {
348            if has_return {
349                return Some((location, EXPORT_RETURN_CONFLICT_MESSAGE));
350            }
351            has_export = true;
352        }
353        if let Stat::Return {
354            location: Some(location),
355            ..
356        } = stat
357        {
358            if has_export {
359                return Some((*location, EXPORT_RETURN_CONFLICT_MESSAGE));
360            }
361            has_return = true;
362        }
363    }
364
365    None
366}
367
368fn nested_exported_value_location(stat: &Stat) -> Option<Location> {
369    struct NestedExportFinder {
370        skip_root: bool,
371        location: Option<Location>,
372    }
373
374    impl<'ast> Visitor<'ast> for NestedExportFinder {
375        fn visit_stat(&mut self, stat: &'ast Stat) -> WalkControl {
376            if self.skip_root {
377                self.skip_root = false;
378                return WalkControl::Continue;
379            }
380            if self.location.is_none() {
381                self.location = exported_value_location(stat);
382            }
383            if self.location.is_some() {
384                WalkControl::SkipChildren
385            } else {
386                WalkControl::Continue
387            }
388        }
389    }
390
391    let mut finder = NestedExportFinder {
392        skip_root: true,
393        location: None,
394    };
395    walk_stat(stat, &mut finder);
396    finder.location
397}
398
399fn exported_value_location(stat: &Stat) -> Option<Location> {
400    match stat {
401        Stat::Local {
402            exported: true,
403            location,
404            ..
405        }
406        | Stat::LocalFunction {
407            exported: true,
408            location,
409            ..
410        }
411        | Stat::Class {
412            exported: true,
413            location,
414            ..
415        } => *location,
416        _ => None,
417    }
418}
419
420#[cfg(test)]
421mod tests;