1use ruau_syntax::parse::{Config, 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) -> 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 #[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 {
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#[doc(hidden)]
203#[derive(Clone, Copy, Debug, Default, Deserialize, Eq, PartialEq, Serialize)]
204#[serde(rename_all = "camelCase")]
205#[serde(default)]
206pub struct UpstreamParseOptions {
207 pub allow_declaration_syntax: bool,
209 pub capture_comments: bool,
211 pub parse_fragment: bool,
213 pub store_cst_data: bool,
215 pub no_error_limit: bool,
217}
218
219#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
221#[serde(rename_all = "camelCase")]
222pub struct FastFlag {
223 pub name: String,
225 pub value: bool,
227}
228
229#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
231#[serde(rename_all = "camelCase")]
232pub struct FastInt {
233 pub name: String,
235 pub value: i32,
237}
238
239#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
241#[serde(rename_all = "camelCase")]
242pub struct KnownMember {
243 pub library: String,
245 pub member: String,
247 pub value: KnownMemberValue,
249}
250
251#[derive(Clone, Debug, Deserialize, PartialEq, Serialize)]
253#[serde(tag = "kind", rename_all = "camelCase")]
254pub enum KnownMemberValue {
255 Nil,
257 Boolean {
259 value: bool,
261 },
262 Number {
264 value: f64,
266 },
267 Integer {
269 value: i64,
271 },
272 Vector {
274 value: [f32; 4],
276 },
277 String {
279 value: String,
281 },
282}
283
284#[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#[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}