Skip to main content

ruau_bytecode/compile/
options.rs

1use ruau_ast::parse::{ParseConfig, 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/// [`UpstreamCompilerOptions`].
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_upstream_options(&self) -> UpstreamCompilerOptions {
35        let mut options = UpstreamCompilerOptions {
36            clear_dead_stack_slots: true,
37            ..UpstreamCompilerOptions::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/// Upstream-fixture-shaped 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 UpstreamCompilerOptions {
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: UpstreamParseOptions,
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 UpstreamCompilerOptions {
116    /// Returns the parser configuration for this fixture posture: the sidecar
117    /// parse options combined with the sidecar syntax flags.
118    #[must_use]
119    pub fn parse_config(&self) -> ParseConfig {
120        ParseConfig {
121            allow_declaration_syntax: self.parse_options.allow_declaration_syntax,
122            capture_comments: self.parse_options.capture_comments,
123            parse_fragment: self.parse_options.parse_fragment,
124            store_cst_data: self.parse_options.store_cst_data,
125            no_error_limit: self.parse_options.no_error_limit,
126            syntax: self.syntax_flags,
127        }
128    }
129
130    /// Returns defaults suitable for code that will run inside `ruau-vm`.
131    #[must_use]
132    pub fn for_vm_execution() -> Self {
133        Self {
134            clear_dead_stack_slots: true,
135            preserve_fenv_semantics: true,
136            ..Self::default()
137        }
138    }
139
140    /// Returns a bytecode-visible fast-flag value with upstream fallback
141    /// semantics for flags that are not present in fixture sidecars.
142    #[must_use]
143    pub fn fast_flag(&self, name: &str) -> bool {
144        self.fast_flags
145            .iter()
146            .rev()
147            .find(|flag| flag.name == name)
148            .map_or_else(|| default_fast_flag(name), |flag| flag.value)
149    }
150
151    /// Returns a bytecode-visible fast-int value with upstream fallback
152    /// semantics for ints that are not present in fixture sidecars.
153    #[must_use]
154    pub fn fast_int(&self, name: &str) -> i32 {
155        self.fast_ints
156            .iter()
157            .rev()
158            .find(|fast_int| fast_int.name == name)
159            .map_or_else(|| default_fast_int(name), |fast_int| fast_int.value)
160    }
161
162    pub(crate) fn bytecode_version(&self) -> u8 {
163        if self.fast_flag("LuauEmitCallFeedback") {
164            11
165        } else if self.fast_flag("DebugLuauUserDefinedClasses") {
166            10
167        } else if self.fast_flag("LuauCompileUdataDirect") {
168            9
169        } else if self.fast_flag("LuauIntegerType") || self.fast_flag("LuauIntegerType2") {
170            8
171        } else if self.coverage_level > 0 || self.fast_flag("LuauCompileDuptableConstantPack2") {
172            7
173        } else {
174            DEFAULT_VERSION
175        }
176    }
177}
178
179impl Default for UpstreamCompilerOptions {
180    fn default() -> Self {
181        Self {
182            optimization_level: 1,
183            debug_level: 1,
184            type_info_level: 0,
185            coverage_level: 0,
186            syntax_flags: SyntaxFlags::default(),
187            parse_options: UpstreamParseOptions::default(),
188            fast_flags: Vec::new(),
189            fast_ints: Vec::new(),
190            vector_lib: None,
191            vector_ctor: None,
192            vector_type: None,
193            mutable_globals: Vec::new(),
194            userdata_types: Vec::new(),
195            disabled_builtins: Vec::new(),
196            known_members: Vec::new(),
197            clear_dead_stack_slots: false,
198            preserve_fenv_semantics: false,
199        }
200    }
201}
202
203/// Parser options mirroring upstream `parseOptions` fixture sidecars.
204///
205/// Kept separate from [`ParseConfig`] so sidecar JSON keeps its exact shape:
206/// upstream sidecars carry `parseOptions` and `syntaxFlags` as sibling
207/// objects. Combine both via [`UpstreamCompilerOptions::parse_config`].
208#[doc(hidden)]
209#[derive(Clone, Copy, Debug, Default, Deserialize, Eq, PartialEq, Serialize)]
210#[serde(rename_all = "camelCase")]
211#[serde(default)]
212pub struct UpstreamParseOptions {
213    /// Enables declaration syntax.
214    pub allow_declaration_syntax: bool,
215    /// Captures comments in parse results.
216    pub capture_comments: bool,
217    /// Parses a fragment instead of a whole chunk.
218    pub parse_fragment: bool,
219    /// Stores CST data.
220    pub store_cst_data: bool,
221    /// Disables upstream's parse-error limit.
222    pub no_error_limit: bool,
223}
224
225/// Fast-flag override.
226#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
227#[serde(rename_all = "camelCase")]
228pub struct FastFlag {
229    /// Flag name.
230    pub name: String,
231    /// Flag value.
232    pub value: bool,
233}
234
235/// Fast-int override.
236#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
237#[serde(rename_all = "camelCase")]
238pub struct FastInt {
239    /// Fast-int name.
240    pub name: String,
241    /// Fast-int value.
242    pub value: i32,
243}
244
245/// Known library-member constant.
246#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
247#[serde(rename_all = "camelCase")]
248pub struct KnownMember {
249    /// Library name.
250    pub library: String,
251    /// Member name.
252    pub member: String,
253    /// Constant value.
254    pub value: KnownMemberValue,
255}
256
257/// Reified known-member constant values.
258#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
259#[serde(tag = "kind", rename_all = "camelCase")]
260pub enum KnownMemberValue {
261    /// Nil.
262    Nil,
263    /// Boolean.
264    Boolean {
265        /// Value.
266        value: bool,
267    },
268    /// Number.
269    Number {
270        /// Value.
271        value: f64,
272    },
273    /// 64-bit integer.
274    Integer {
275        /// Value.
276        value: i64,
277    },
278    /// Vector.
279    Vector {
280        /// Components.
281        value: [f32; 4],
282    },
283    /// String.
284    String {
285        /// Value.
286        value: String,
287    },
288}
289
290/// Applies source hot comments and attributes to input compiler options.
291#[must_use]
292pub fn effective_compile_options(
293    source: &str,
294    options: &UpstreamCompilerOptions,
295) -> UpstreamCompilerOptions {
296    let mut effective = options.clone();
297    apply_leading_hot_comments(source.lines(), &mut effective);
298    if source.contains("@native") {
299        effective.optimization_level = 2;
300        effective.type_info_level = 1;
301    }
302    effective
303}
304
305/// Applies source directives that the bytecode compiler itself observes.
306#[must_use]
307pub fn source_compile_options(
308    source: &str,
309    options: &UpstreamCompilerOptions,
310) -> UpstreamCompilerOptions {
311    let mut effective = effective_compile_options(source, options);
312    apply_leading_hot_comments(
313        source.lines().skip_while(|line| line.trim().is_empty()),
314        &mut effective,
315    );
316    effective
317}
318
319fn apply_leading_hot_comments<'a>(
320    lines: impl Iterator<Item = &'a str>,
321    options: &mut UpstreamCompilerOptions,
322) {
323    for line in lines.take_while(|line| line.trim_start().starts_with("--")) {
324        apply_hot_comment(line, options);
325    }
326}
327
328fn apply_hot_comment(line: &str, options: &mut UpstreamCompilerOptions) {
329    let trimmed = line.trim_start();
330    if let Some(value) = trimmed.strip_prefix("--!optimize") {
331        let level = value
332            .trim()
333            .parse::<u8>()
334            .map_or(options.optimization_level, |level| level.min(2));
335        options.optimization_level = level;
336    }
337    if trimmed.starts_with("--!native") {
338        options.optimization_level = 2;
339        options.type_info_level = 1;
340    }
341}
342
343fn default_fast_flag(_name: &str) -> bool {
344    false
345}
346
347fn default_fast_int(name: &str) -> i32 {
348    match name {
349        "LuauCompileLoopUnrollThreshold" => 25,
350        "LuauCompileLoopUnrollThresholdMaxBoost" => 300,
351        "LuauCompileInlineThreshold" => 25,
352        "LuauCompileInlineThresholdMaxBoost" => 300,
353        "LuauCompileInlineDepth" => 5,
354        _ => 0,
355    }
356}
357
358#[cfg(test)]
359mod tests {
360    use super::{
361        FastFlag, FastInt, UpstreamCompilerOptions, effective_compile_options,
362        source_compile_options,
363    };
364
365    #[test]
366    fn default_options_match_upstream_defaults() {
367        let options = UpstreamCompilerOptions::default();
368        assert_eq!(options.optimization_level, 1);
369        assert_eq!(options.debug_level, 1);
370        assert_eq!(options.type_info_level, 0);
371        assert_eq!(options.coverage_level, 0);
372    }
373
374    #[test]
375    fn fast_flags_default_false_and_sidecars_override() {
376        let options = UpstreamCompilerOptions::default();
377        assert!(!options.fast_flag("LuauEmitCallFeedback"));
378
379        let options = UpstreamCompilerOptions {
380            fast_flags: vec![FastFlag {
381                name: "LuauEmitCallFeedback".to_owned(),
382                value: true,
383            }],
384            ..Default::default()
385        };
386        assert!(options.fast_flag("LuauEmitCallFeedback"));
387    }
388
389    #[test]
390    fn fast_ints_use_upstream_defaults_and_sidecars_override() {
391        let options = UpstreamCompilerOptions::default();
392        assert_eq!(options.fast_int("LuauCompileInlineThreshold"), 25);
393        assert_eq!(options.fast_int("LuauCompileInlineThresholdMaxBoost"), 300);
394        assert_eq!(options.fast_int("LuauCompileInlineDepth"), 5);
395        assert_eq!(options.fast_int("UnknownFastInt"), 0);
396
397        let options = UpstreamCompilerOptions {
398            fast_ints: vec![FastInt {
399                name: "LuauCompileInlineThreshold".to_owned(),
400                value: 10,
401            }],
402            ..Default::default()
403        };
404        assert_eq!(options.fast_int("LuauCompileInlineThreshold"), 10);
405    }
406
407    #[test]
408    fn bytecode_version_uses_fast_flag_helpers() {
409        let options = UpstreamCompilerOptions::default();
410        assert_eq!(options.bytecode_version(), 7);
411
412        let options = UpstreamCompilerOptions {
413            fast_flags: vec![FastFlag {
414                name: "LuauEmitCallFeedback".to_owned(),
415                value: true,
416            }],
417            ..Default::default()
418        };
419        assert_eq!(options.bytecode_version(), 11);
420
421        let options = UpstreamCompilerOptions {
422            fast_flags: vec![FastFlag {
423                name: "LuauIntegerType2".to_owned(),
424                value: true,
425            }],
426            ..Default::default()
427        };
428        assert_eq!(options.bytecode_version(), 8);
429    }
430
431    #[test]
432    fn source_hot_comments_override_options() {
433        let options = effective_compile_options(
434            "--!optimize 2\nreturn 1",
435            &UpstreamCompilerOptions::default(),
436        );
437        assert_eq!(options.optimization_level, 2);
438
439        let options = source_compile_options(
440            "\n--!optimize 2\nreturn 1",
441            &UpstreamCompilerOptions::default(),
442        );
443        assert_eq!(options.optimization_level, 2);
444    }
445}