Skip to main content

ruau_bytecode/compile/
options.rs

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