Skip to main content

ruau_bytecode/compile/
options.rs

1use ruau_ast::parse::{Options, SyntaxFlags};
2use serde::{Deserialize, Serialize};
3
4use crate::builder::DEFAULT_VERSION;
5
6/// Public compile policy for Ruau VM bytecode.
7///
8/// This is the ordinary embedder-facing surface: it keeps VM-safe hardening
9/// enabled and exposes only the knobs that are meaningful for current pinned
10/// Luau compilation. Upstream fixture compatibility uses
11/// [`CompilerOptions`].
12#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
13#[serde(rename_all = "camelCase")]
14#[serde(default)]
15pub struct CompileOptions {
16    /// Upstream optimization level.
17    pub optimization_level: u8,
18    /// Upstream debug level.
19    pub debug_level: u8,
20    /// Upstream coverage level.
21    pub coverage_level: u8,
22}
23
24impl CompileOptions {
25    /// Returns the default VM compile policy.
26    #[must_use]
27    pub fn new() -> Self {
28        Self::default()
29    }
30
31    /// Returns compiler-internal options for ordinary VM execution.
32    #[doc(hidden)]
33    #[must_use]
34    pub fn to_compiler_options(&self) -> CompilerOptions {
35        let mut options = CompilerOptions {
36            clear_dead_stack_slots: true,
37            ..CompilerOptions::default()
38        };
39        options.optimization_level = self.optimization_level;
40        options.debug_level = self.debug_level;
41        options.coverage_level = self.coverage_level;
42        options
43    }
44}
45
46impl Default for CompileOptions {
47    fn default() -> Self {
48        Self {
49            optimization_level: 1,
50            debug_level: 1,
51            coverage_level: 0,
52        }
53    }
54}
55
56/// Bytecode-visible compiler options.
57///
58/// This type is public only for repository tooling and compatibility fixtures
59/// that need to mirror upstream Luau sidecars. Ordinary embedders should use
60/// [`CompileOptions`] through `Surface`, `RuntimeCapabilities`, host, or runner
61/// APIs.
62#[doc(hidden)]
63#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
64#[serde(rename_all = "camelCase")]
65#[serde(default)]
66pub struct CompilerOptions {
67    /// Upstream optimization level.
68    pub optimization_level: u8,
69    /// Upstream debug level.
70    pub debug_level: u8,
71    /// Upstream type-info level.
72    pub type_info_level: u8,
73    /// Upstream coverage level.
74    pub coverage_level: u8,
75    /// Parser syntax flags.
76    pub syntax_flags: SyntaxFlags,
77    /// Parser options.
78    pub parse_options: Options,
79    /// Bytecode-visible fast flags.
80    pub fast_flags: Vec<FastFlag>,
81    /// Bytecode-visible fast ints.
82    pub fast_ints: Vec<FastInt>,
83    /// Alternative vector library.
84    pub vector_lib: Option<String>,
85    /// Alternative vector constructor.
86    pub vector_ctor: Option<String>,
87    /// Alternative vector type.
88    pub vector_type: Option<String>,
89    /// Mutable globals.
90    pub mutable_globals: Vec<String>,
91    /// Userdata types emitted in type info.
92    pub userdata_types: Vec<String>,
93    /// Disabled builtin names.
94    pub disabled_builtins: Vec<String>,
95    /// Reified known-member constants.
96    pub known_members: Vec<KnownMember>,
97    /// Clear dead stack slots after their last compiler-visible use.
98    ///
99    /// This is an Ruau VM execution hardening option, not an upstream Luau
100    /// compiler option. Keep it out of fixture sidecars so bytecode-oracle
101    /// comparisons continue to use upstream-compatible defaults.
102    #[serde(skip)]
103    pub clear_dead_stack_slots: bool,
104    /// Suppress import-path and related fast-path lowering when source uses
105    /// `getfenv` or `setfenv`.
106    ///
107    /// This is an Ruau VM execution correctness option. Upstream bytecode
108    /// fixtures still use upstream-compatible defaults, where `getfenv` /
109    /// `setfenv` affect some optimizer decisions but do not globally rewrite
110    /// ordinary imports into table lookups.
111    #[serde(skip)]
112    pub preserve_fenv_semantics: bool,
113}
114
115impl CompilerOptions {
116    /// Returns defaults suitable for code that will run inside `ruau-vm`.
117    #[must_use]
118    pub fn for_vm_execution() -> Self {
119        Self {
120            clear_dead_stack_slots: true,
121            preserve_fenv_semantics: true,
122            ..Self::default()
123        }
124    }
125
126    /// Returns a bytecode-visible fast-flag value with upstream fallback
127    /// semantics for flags that are not present in fixture sidecars.
128    #[must_use]
129    pub fn fast_flag(&self, name: &str) -> bool {
130        self.fast_flags
131            .iter()
132            .rev()
133            .find(|flag| flag.name == name)
134            .map_or_else(|| default_fast_flag(name), |flag| flag.value)
135    }
136
137    /// Returns a bytecode-visible fast-int value with upstream fallback
138    /// semantics for ints that are not present in fixture sidecars.
139    #[must_use]
140    pub fn fast_int(&self, name: &str) -> i32 {
141        self.fast_ints
142            .iter()
143            .rev()
144            .find(|fast_int| fast_int.name == name)
145            .map_or_else(|| default_fast_int(name), |fast_int| fast_int.value)
146    }
147
148    pub(crate) fn bytecode_version(&self) -> u8 {
149        if self.fast_flag("LuauEmitCallFeedback") {
150            11
151        } else if self.fast_flag("DebugLuauUserDefinedClasses") {
152            10
153        } else if self.fast_flag("LuauCompileUdataDirect") {
154            9
155        } else if self.fast_flag("LuauIntegerType") {
156            8
157        } else if self.coverage_level > 0 || self.fast_flag("LuauCompileDuptableConstantPack2") {
158            7
159        } else {
160            DEFAULT_VERSION
161        }
162    }
163}
164
165impl Default for CompilerOptions {
166    fn default() -> Self {
167        Self {
168            optimization_level: 1,
169            debug_level: 1,
170            type_info_level: 0,
171            coverage_level: 0,
172            syntax_flags: SyntaxFlags::default(),
173            parse_options: Options::default(),
174            fast_flags: Vec::new(),
175            fast_ints: Vec::new(),
176            vector_lib: None,
177            vector_ctor: None,
178            vector_type: None,
179            mutable_globals: Vec::new(),
180            userdata_types: Vec::new(),
181            disabled_builtins: Vec::new(),
182            known_members: Vec::new(),
183            clear_dead_stack_slots: false,
184            preserve_fenv_semantics: false,
185        }
186    }
187}
188
189/// Fast-flag override.
190#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
191#[serde(rename_all = "camelCase")]
192pub struct FastFlag {
193    /// Flag name.
194    pub name: String,
195    /// Flag value.
196    pub value: bool,
197}
198
199/// Fast-int override.
200#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
201#[serde(rename_all = "camelCase")]
202pub struct FastInt {
203    /// Fast-int name.
204    pub name: String,
205    /// Fast-int value.
206    pub value: i32,
207}
208
209/// Known library-member constant.
210#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
211#[serde(rename_all = "camelCase")]
212pub struct KnownMember {
213    /// Library name.
214    pub library: String,
215    /// Member name.
216    pub member: String,
217    /// Constant value.
218    pub value: KnownMemberValue,
219}
220
221/// Reified known-member constant values.
222#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
223#[serde(tag = "kind", rename_all = "camelCase")]
224pub enum KnownMemberValue {
225    /// Nil.
226    Nil,
227    /// Boolean.
228    Boolean {
229        /// Value.
230        value: bool,
231    },
232    /// Number.
233    Number {
234        /// Value.
235        value: f64,
236    },
237    /// 64-bit integer.
238    Integer {
239        /// Value.
240        value: i64,
241    },
242    /// Vector.
243    Vector {
244        /// Components.
245        value: [f32; 4],
246    },
247    /// String.
248    String {
249        /// Value.
250        value: String,
251    },
252}
253
254/// Applies source hot comments and attributes to input compiler options.
255#[must_use]
256pub fn effective_compile_options(source: &str, options: &CompilerOptions) -> CompilerOptions {
257    let mut effective = options.clone();
258    apply_leading_hot_comments(source.lines(), &mut effective);
259    if source.contains("@native") {
260        effective.optimization_level = 2;
261        effective.type_info_level = 1;
262    }
263    effective
264}
265
266/// Applies source directives that the bytecode compiler itself observes.
267#[must_use]
268pub fn source_compile_options(source: &str, options: &CompilerOptions) -> CompilerOptions {
269    let mut effective = effective_compile_options(source, options);
270    apply_leading_hot_comments(
271        source.lines().skip_while(|line| line.trim().is_empty()),
272        &mut effective,
273    );
274    effective
275}
276
277fn apply_leading_hot_comments<'a>(
278    lines: impl Iterator<Item = &'a str>,
279    options: &mut CompilerOptions,
280) {
281    for line in lines.take_while(|line| line.trim_start().starts_with("--")) {
282        apply_hot_comment(line, options);
283    }
284}
285
286fn apply_hot_comment(line: &str, options: &mut CompilerOptions) {
287    let trimmed = line.trim_start();
288    if let Some(value) = trimmed.strip_prefix("--!optimize") {
289        let level = value
290            .trim()
291            .parse::<u8>()
292            .map_or(options.optimization_level, |level| level.min(2));
293        options.optimization_level = level;
294    }
295    if trimmed.starts_with("--!native") {
296        options.optimization_level = 2;
297        options.type_info_level = 1;
298    }
299}
300
301fn default_fast_flag(_name: &str) -> bool {
302    false
303}
304
305fn default_fast_int(name: &str) -> i32 {
306    match name {
307        "LuauCompileLoopUnrollThreshold" => 25,
308        "LuauCompileLoopUnrollThresholdMaxBoost" => 300,
309        "LuauCompileInlineThreshold" => 25,
310        "LuauCompileInlineThresholdMaxBoost" => 300,
311        "LuauCompileInlineDepth" => 5,
312        _ => 0,
313    }
314}
315
316#[cfg(test)]
317mod tests {
318    use super::{
319        CompilerOptions, FastFlag, FastInt, effective_compile_options, source_compile_options,
320    };
321
322    #[test]
323    fn default_options_match_upstream_defaults() {
324        let options = CompilerOptions::default();
325        assert_eq!(options.optimization_level, 1);
326        assert_eq!(options.debug_level, 1);
327        assert_eq!(options.type_info_level, 0);
328        assert_eq!(options.coverage_level, 0);
329    }
330
331    #[test]
332    fn fast_flags_default_false_and_sidecars_override() {
333        let options = CompilerOptions::default();
334        assert!(!options.fast_flag("LuauEmitCallFeedback"));
335
336        let options = CompilerOptions {
337            fast_flags: vec![FastFlag {
338                name: "LuauEmitCallFeedback".to_owned(),
339                value: true,
340            }],
341            ..Default::default()
342        };
343        assert!(options.fast_flag("LuauEmitCallFeedback"));
344    }
345
346    #[test]
347    fn fast_ints_use_upstream_defaults_and_sidecars_override() {
348        let options = CompilerOptions::default();
349        assert_eq!(options.fast_int("LuauCompileInlineThreshold"), 25);
350        assert_eq!(options.fast_int("LuauCompileInlineThresholdMaxBoost"), 300);
351        assert_eq!(options.fast_int("LuauCompileInlineDepth"), 5);
352        assert_eq!(options.fast_int("UnknownFastInt"), 0);
353
354        let options = CompilerOptions {
355            fast_ints: vec![FastInt {
356                name: "LuauCompileInlineThreshold".to_owned(),
357                value: 10,
358            }],
359            ..Default::default()
360        };
361        assert_eq!(options.fast_int("LuauCompileInlineThreshold"), 10);
362    }
363
364    #[test]
365    fn bytecode_version_uses_fast_flag_helpers() {
366        let options = CompilerOptions::default();
367        assert_eq!(options.bytecode_version(), 6);
368
369        let options = CompilerOptions {
370            fast_flags: vec![FastFlag {
371                name: "LuauEmitCallFeedback".to_owned(),
372                value: true,
373            }],
374            ..Default::default()
375        };
376        assert_eq!(options.bytecode_version(), 11);
377    }
378
379    #[test]
380    fn source_hot_comments_override_options() {
381        let options =
382            effective_compile_options("--!optimize 2\nreturn 1", &CompilerOptions::default());
383        assert_eq!(options.optimization_level, 2);
384
385        let options =
386            source_compile_options("\n--!optimize 2\nreturn 1", &CompilerOptions::default());
387        assert_eq!(options.optimization_level, 2);
388    }
389}