1use std::{
4 fmt,
5 sync::{
6 Arc,
7 atomic::{AtomicBool, Ordering},
8 },
9};
10
11use ruau_syntax::{
12 Location, Stat,
13 parse::{ParsedModule, parse_module_bytes_with_config, parse_module_with_config},
14 visit::{Visitor, WalkControl, walk_stat},
15};
16
17use crate::BytecodeChunk;
18
19mod analysis;
20mod builtin_folding;
21mod context;
22mod function_compiler;
23mod helpers;
24mod inline_cost;
25mod options;
26
27use analysis::ConstantValue;
28use context::CompileContext;
29#[cfg(test)]
30use function_compiler::constant_ad_operand;
31use function_compiler::{
32 BreakBranchKind, FunctionCompiler, LoopControlBranchKind, LoopUnrollPlan, TypeAliasInfo,
33};
34use helpers::*;
35pub use options::{
36 CompileOptions, FastFlag, FastInt, KnownMember, KnownMemberValue, UpstreamCompilerOptions,
37 UpstreamParseOptions, effective_compile_options, source_compile_options,
38};
39
40pub const CONSTANT_STRING_FOLD_LIMIT: usize = 4096;
41const EXPORT_TOP_LEVEL_MESSAGE: &str = "'export' may only be applied to top-level statements";
42const EXPORT_RETURN_CONFLICT_MESSAGE: &str =
43 "Exporting values is not compatible with top-level return (export/return conflict)";
44
45#[derive(Clone, Debug, Eq, PartialEq)]
54pub struct CompileError {
55 kind: CompileErrorKind,
56 location: Option<Location>,
57 message: String,
58}
59
60#[derive(Clone, Copy, Debug, Eq, PartialEq)]
62#[non_exhaustive]
63pub enum CompileErrorKind {
64 Parse,
67 Cancelled,
69 Internal,
71}
72
73impl CompileError {
74 pub fn new(message: impl Into<String>) -> Self {
79 Self {
80 kind: CompileErrorKind::Internal,
81 location: None,
82 message: message.into(),
83 }
84 }
85
86 pub fn cancelled() -> Self {
88 Self {
89 kind: CompileErrorKind::Cancelled,
90 location: None,
91 message: "compilation cancelled".to_owned(),
92 }
93 }
94
95 fn parse(message: impl Into<String>, location: Location) -> Self {
96 Self {
97 kind: CompileErrorKind::Parse,
98 location: Some(location),
99 message: message.into(),
100 }
101 }
102
103 #[must_use]
105 pub fn kind(&self) -> CompileErrorKind {
106 self.kind
107 }
108
109 #[must_use]
116 pub fn location(&self) -> Option<Location> {
117 self.location
118 }
119
120 #[must_use]
122 pub fn message(&self) -> &str {
123 &self.message
124 }
125}
126
127impl fmt::Display for CompileError {
128 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
129 if let Some(location) = self.location {
130 write!(
131 f,
132 "{}:{}: {}",
133 location.begin.line + 1,
134 location.begin.column + 1,
135 self.message
136 )
137 } else {
138 f.write_str(&self.message)
139 }
140 }
141}
142
143impl std::error::Error for CompileError {}
144
145pub fn compile_source(
157 source: &str,
158 options: &CompileOptions,
159 cancel: Option<Arc<AtomicBool>>,
160) -> Result<BytecodeChunk, CompileError> {
161 chunkify_parse_error(compile_source_strict(source, options, cancel))
162}
163
164pub fn compile_source_bytes(
173 source: &[u8],
174 options: &CompileOptions,
175 cancel: Option<Arc<AtomicBool>>,
176) -> Result<BytecodeChunk, CompileError> {
177 chunkify_parse_error(compile_source_bytes_strict(source, options, cancel))
178}
179
180pub fn compile_source_strict(
187 source: &str,
188 options: &CompileOptions,
189 cancel: Option<Arc<AtomicBool>>,
190) -> Result<BytecodeChunk, CompileError> {
191 let options = options.to_upstream_options();
192 compile_source_strict_with_upstream_options(source, &options, cancel)
193}
194
195#[doc(hidden)]
201pub fn compile_source_strict_with_upstream_options(
202 source: &str,
203 options: &UpstreamCompilerOptions,
204 cancel: Option<Arc<AtomicBool>>,
205) -> Result<BytecodeChunk, CompileError> {
206 let effective = source_compile_options(source, options);
207 check_compile_cancelled(cancel.as_ref())?;
208 let parsed = parse_module_with_config(source, &effective.parse_config());
209 compile_parsed_module_with_effective(&parsed, &effective, cancel)
210}
211
212pub fn compile_source_bytes_strict(
217 source: &[u8],
218 options: &CompileOptions,
219 cancel: Option<Arc<AtomicBool>>,
220) -> Result<BytecodeChunk, CompileError> {
221 let options = options.to_upstream_options();
222 compile_source_bytes_strict_with_upstream_options(source, &options, cancel)
223}
224
225#[doc(hidden)]
227pub fn compile_source_bytes_strict_with_upstream_options(
228 source: &[u8],
229 options: &UpstreamCompilerOptions,
230 cancel: Option<Arc<AtomicBool>>,
231) -> Result<BytecodeChunk, CompileError> {
232 let lossy = String::from_utf8_lossy(source);
236 let effective = source_compile_options(&lossy, options);
237 check_compile_cancelled(cancel.as_ref())?;
238 let parsed = parse_module_bytes_with_config(source, &effective.parse_config());
239 compile_parsed_module_with_effective(&parsed, &effective, cancel)
240}
241
242#[doc(hidden)]
255pub fn compile_parsed_module_strict_with_upstream_options(
256 parsed: &ParsedModule,
257 options: &UpstreamCompilerOptions,
258 cancel: Option<Arc<AtomicBool>>,
259) -> Result<BytecodeChunk, CompileError> {
260 let lossy = String::from_utf8_lossy(parsed.source());
261 let effective = source_compile_options(&lossy, options);
262 check_compile_cancelled(cancel.as_ref())?;
263 compile_parsed_module_with_effective(parsed, &effective, cancel)
264}
265
266fn compile_parsed_module_with_effective(
267 parsed: &ParsedModule,
268 effective: &UpstreamCompilerOptions,
269 cancel: Option<Arc<AtomicBool>>,
270) -> Result<BytecodeChunk, CompileError> {
271 if !parsed
272 .config()
273 .ast_compatible_with(effective.parse_config())
274 {
275 return Err(CompileError::new(
276 "parsed module options do not match effective compiler syntax options",
277 ));
278 }
279 if let Some(error) = parsed.errors().first() {
280 return Err(CompileError::parse(error.message.clone(), error.location));
284 }
285 let mut effective = effective.clone();
286 apply_native_attribute_options(parsed.root(), &mut effective);
287 compile_ast_with_implicit_return_delta(
288 parsed.root(),
289 &effective,
290 u8::from(parsed.source().ends_with(b"\n")),
291 cancel,
292 )
293}
294
295fn apply_native_attribute_options(root: &Stat, options: &mut UpstreamCompilerOptions) {
296 struct NativeAttributeVisitor {
297 found: bool,
298 }
299
300 impl<'ast> Visitor<'ast> for NativeAttributeVisitor {
301 fn visit_expr(&mut self, expr: &'ast ruau_syntax::Expr) -> WalkControl {
302 if let ruau_syntax::Expr::Function { attributes, .. } = expr
303 && attributes
304 .iter()
305 .any(|attribute| attribute.name.as_str() == "native")
306 {
307 self.found = true;
308 return WalkControl::SkipChildren;
309 }
310 WalkControl::Continue
311 }
312 }
313
314 let mut visitor = NativeAttributeVisitor { found: false };
315 walk_stat(root, &mut visitor);
316 if visitor.found {
317 options.optimization_level = 2;
318 options.type_info_level = 1;
319 }
320}
321
322#[doc(hidden)]
331pub fn chunkify_parse_error(
332 result: Result<BytecodeChunk, CompileError>,
333) -> Result<BytecodeChunk, CompileError> {
334 match result {
335 Err(error) if error.kind() == CompileErrorKind::Parse => {
336 let message = match error.location() {
337 Some(location) => {
338 format!(":{}: {}", location.begin.line + 1, error.message())
339 }
340 None => error.message().to_owned(),
341 };
342 Ok(BytecodeChunk::Error {
343 message: message.into_bytes(),
344 })
345 }
346 other => other,
347 }
348}
349
350fn line_location(line: u32) -> Location {
353 let position = ruau_syntax::Position {
354 line: line.saturating_sub(1),
355 column: 0,
356 };
357 Location {
358 begin: position,
359 end: position,
360 }
361}
362
363fn compile_ast_with_implicit_return_delta(
364 root: &Arc<Stat>,
365 options: &UpstreamCompilerOptions,
366 implicit_return_line_delta: u8,
367 cancel: Option<Arc<AtomicBool>>,
368) -> Result<BytecodeChunk, CompileError> {
369 check_compile_cancelled(cancel.as_ref())?;
370 if let Some((line, message)) = repeat_continue_condition_error(root) {
371 return Err(CompileError::parse(message, line_location(line)));
372 }
373 if let Some((location, message)) = export_value_ast_error(root) {
374 return Err(CompileError::parse(message, location));
375 }
376
377 let context = CompileContext::with_cancel(Arc::clone(root), options, cancel);
378 context.check_cancelled()?;
379 let mut compiler = FunctionCompiler::new(context, implicit_return_line_delta);
380 compiler.compile_registered_functions_for_root(root)?;
381 compiler.compile_root(root)?;
382 Ok(compiler.finish())
383}
384
385fn check_compile_cancelled(cancel: Option<&Arc<AtomicBool>>) -> Result<(), CompileError> {
386 if cancel.is_some_and(|cancel| cancel.load(Ordering::Relaxed)) {
387 return Err(CompileError::cancelled());
388 }
389 Ok(())
390}
391
392fn export_value_ast_error(root: &Stat) -> Option<(Location, &'static str)> {
393 let Stat::Block { body, .. } = root else {
394 return exported_value_location(root).map(|location| (location, EXPORT_TOP_LEVEL_MESSAGE));
395 };
396
397 let mut has_export = false;
398 let mut has_return = false;
399 for stat in body {
400 if let Some(location) = nested_exported_value_location(stat) {
401 return Some((location, EXPORT_TOP_LEVEL_MESSAGE));
402 }
403 if let Some(location) = exported_value_location(stat) {
404 if has_return {
405 return Some((location, EXPORT_RETURN_CONFLICT_MESSAGE));
406 }
407 has_export = true;
408 }
409 if let Stat::Return {
410 location: Some(location),
411 ..
412 } = stat
413 {
414 if has_export {
415 return Some((*location, EXPORT_RETURN_CONFLICT_MESSAGE));
416 }
417 has_return = true;
418 }
419 }
420
421 None
422}
423
424fn nested_exported_value_location(stat: &Stat) -> Option<Location> {
425 struct NestedExportFinder {
426 skip_root: bool,
427 location: Option<Location>,
428 }
429
430 impl<'ast> Visitor<'ast> for NestedExportFinder {
431 fn visit_stat(&mut self, stat: &'ast Stat) -> WalkControl {
432 if self.skip_root {
433 self.skip_root = false;
434 return WalkControl::Continue;
435 }
436 if self.location.is_none() {
437 self.location = exported_value_location(stat);
438 }
439 if self.location.is_some() {
440 WalkControl::SkipChildren
441 } else {
442 WalkControl::Continue
443 }
444 }
445 }
446
447 let mut finder = NestedExportFinder {
448 skip_root: true,
449 location: None,
450 };
451 walk_stat(stat, &mut finder);
452 finder.location
453}
454
455fn exported_value_location(stat: &Stat) -> Option<Location> {
456 match stat {
457 Stat::Local {
458 exported: true,
459 location,
460 ..
461 }
462 | Stat::LocalFunction {
463 exported: true,
464 location,
465 ..
466 }
467 | Stat::Class {
468 exported: true,
469 location,
470 ..
471 } => *location,
472 _ => None,
473 }
474}
475
476#[cfg(test)]
477mod tests;