Skip to main content

ruau_bytecode/compile/
mod.rs

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