1use ruau_ast::parse::{ParseConfig, SyntaxFlags};
2use serde::{Deserialize, Serialize};
3
4use crate::builder::DEFAULT_VERSION;
5
6#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
13#[serde(rename_all = "camelCase")]
14#[serde(default)]
15pub struct CompileOptions {
16 pub optimization_level: u8,
18 pub debug_level: u8,
20 pub coverage_level: u8,
22}
23
24impl CompileOptions {
25 #[must_use]
27 pub fn new() -> Self {
28 Self::default()
29 }
30
31 #[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#[doc(hidden)]
63#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
64#[serde(rename_all = "camelCase")]
65#[serde(default)]
66pub struct UpstreamCompilerOptions {
67 pub optimization_level: u8,
69 pub debug_level: u8,
71 pub type_info_level: u8,
73 pub coverage_level: u8,
75 pub syntax_flags: SyntaxFlags,
77 pub parse_options: UpstreamParseOptions,
79 pub fast_flags: Vec<FastFlag>,
81 pub fast_ints: Vec<FastInt>,
83 pub vector_lib: Option<String>,
85 pub vector_ctor: Option<String>,
87 pub vector_type: Option<String>,
89 pub mutable_globals: Vec<String>,
91 pub userdata_types: Vec<String>,
93 pub disabled_builtins: Vec<String>,
95 pub known_members: Vec<KnownMember>,
97 #[serde(skip)]
103 pub clear_dead_stack_slots: bool,
104 #[serde(skip)]
112 pub preserve_fenv_semantics: bool,
113}
114
115impl UpstreamCompilerOptions {
116 #[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 #[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 #[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 #[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#[doc(hidden)]
209#[derive(Clone, Copy, Debug, Default, Deserialize, Eq, PartialEq, Serialize)]
210#[serde(rename_all = "camelCase")]
211#[serde(default)]
212pub struct UpstreamParseOptions {
213 pub allow_declaration_syntax: bool,
215 pub capture_comments: bool,
217 pub parse_fragment: bool,
219 pub store_cst_data: bool,
221 pub no_error_limit: bool,
223}
224
225#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
227#[serde(rename_all = "camelCase")]
228pub struct FastFlag {
229 pub name: String,
231 pub value: bool,
233}
234
235#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
237#[serde(rename_all = "camelCase")]
238pub struct FastInt {
239 pub name: String,
241 pub value: i32,
243}
244
245#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
247#[serde(rename_all = "camelCase")]
248pub struct KnownMember {
249 pub library: String,
251 pub member: String,
253 pub value: KnownMemberValue,
255}
256
257#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
259#[serde(tag = "kind", rename_all = "camelCase")]
260pub enum KnownMemberValue {
261 Nil,
263 Boolean {
265 value: bool,
267 },
268 Number {
270 value: f64,
272 },
273 Integer {
275 value: i64,
277 },
278 Vector {
280 value: [f32; 4],
282 },
283 String {
285 value: String,
287 },
288}
289
290#[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#[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}