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