1use std::{
4 fmt,
5 rc::Rc,
6 sync::{
7 Arc,
8 atomic::{AtomicBool, Ordering},
9 },
10};
11
12use ruau_ast::{
13 Location,
14 parse::{parse_file_bytes_with, parse_file_with},
15 syntax::Stat,
16 visit::{Visitor, WalkControl, walk_stat},
17};
18
19use crate::BytecodeChunk;
20
21mod analysis;
22mod builtin_folding;
23mod context;
24mod function_compiler;
25mod helpers;
26mod inline_cost;
27mod options;
28
29use analysis::ConstantValue;
30use context::CompileContext;
31#[cfg(test)]
32use function_compiler::constant_ad_operand;
33use function_compiler::{
34 BreakBranchKind, FunctionCompiler, LoopControlBranchKind, LoopUnrollPlan, TypeAliasInfo,
35};
36use helpers::*;
37pub use options::{
38 CompileOptions, FastFlag, FastInt, KnownMember, KnownMemberValue, UpstreamCompilerOptions,
39 UpstreamParseOptions, effective_compile_options, source_compile_options,
40};
41
42pub const CONSTANT_STRING_FOLD_LIMIT: usize = 4096;
43const EXPORT_TOP_LEVEL_MESSAGE: &str = "'export' may only be applied to top-level statements";
44const EXPORT_RETURN_CONFLICT_MESSAGE: &str =
45 "Exporting values is not compatible with top-level return (export/return conflict)";
46
47#[derive(Clone, Debug, Eq, PartialEq)]
56pub struct CompileError {
57 kind: CompileErrorKind,
58 location: Option<Location>,
59 message: String,
60}
61
62#[derive(Clone, Copy, Debug, Eq, PartialEq)]
64#[non_exhaustive]
65pub enum CompileErrorKind {
66 Parse,
69 Cancelled,
71 Internal,
73}
74
75impl CompileError {
76 pub fn new(message: impl Into<String>) -> Self {
81 Self {
82 kind: CompileErrorKind::Internal,
83 location: None,
84 message: message.into(),
85 }
86 }
87
88 pub fn cancelled() -> Self {
90 Self {
91 kind: CompileErrorKind::Cancelled,
92 location: None,
93 message: "compilation cancelled".to_owned(),
94 }
95 }
96
97 fn parse(message: impl Into<String>, location: Location) -> Self {
98 Self {
99 kind: CompileErrorKind::Parse,
100 location: Some(location),
101 message: message.into(),
102 }
103 }
104
105 #[must_use]
107 pub fn kind(&self) -> CompileErrorKind {
108 self.kind
109 }
110
111 #[must_use]
118 pub fn location(&self) -> Option<Location> {
119 self.location
120 }
121
122 #[must_use]
124 pub fn message(&self) -> &str {
125 &self.message
126 }
127}
128
129impl fmt::Display for CompileError {
130 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
131 if let Some(location) = self.location {
132 write!(
133 f,
134 "{}:{}: {}",
135 location.begin.line + 1,
136 location.begin.column + 1,
137 self.message
138 )
139 } else {
140 f.write_str(&self.message)
141 }
142 }
143}
144
145impl std::error::Error for CompileError {}
146
147pub fn compile_source(
159 source: &str,
160 options: &CompileOptions,
161 cancel: Option<Arc<AtomicBool>>,
162) -> Result<BytecodeChunk, CompileError> {
163 chunkify_parse_error(compile_source_strict(source, options, cancel))
164}
165
166pub fn compile_source_bytes(
175 source: &[u8],
176 options: &CompileOptions,
177 cancel: Option<Arc<AtomicBool>>,
178) -> Result<BytecodeChunk, CompileError> {
179 chunkify_parse_error(compile_source_bytes_strict(source, options, cancel))
180}
181
182pub fn compile_source_strict(
189 source: &str,
190 options: &CompileOptions,
191 cancel: Option<Arc<AtomicBool>>,
192) -> Result<BytecodeChunk, CompileError> {
193 let options = options.to_upstream_options();
194 compile_source_strict_with_upstream_options(source, &options, cancel)
195}
196
197#[doc(hidden)]
203pub fn compile_source_strict_with_upstream_options(
204 source: &str,
205 options: &UpstreamCompilerOptions,
206 cancel: Option<Arc<AtomicBool>>,
207) -> Result<BytecodeChunk, CompileError> {
208 let effective = source_compile_options(source, options);
209 check_compile_cancelled(cancel.as_ref())?;
210 let parse = parse_file_with(source, &effective.parse_config());
211 if let Some(error) = parse.errors.first() {
212 return Err(CompileError::parse(error.message.clone(), error.location));
216 }
217 compile_ast_with_implicit_return_delta(
218 parse.root,
219 &effective,
220 u8::from(source.ends_with('\n')),
221 cancel,
222 )
223}
224
225pub fn compile_source_bytes_strict(
230 source: &[u8],
231 options: &CompileOptions,
232 cancel: Option<Arc<AtomicBool>>,
233) -> Result<BytecodeChunk, CompileError> {
234 let options = options.to_upstream_options();
235 compile_source_bytes_strict_with_upstream_options(source, &options, cancel)
236}
237
238#[doc(hidden)]
240pub fn compile_source_bytes_strict_with_upstream_options(
241 source: &[u8],
242 options: &UpstreamCompilerOptions,
243 cancel: Option<Arc<AtomicBool>>,
244) -> Result<BytecodeChunk, CompileError> {
245 let lossy = String::from_utf8_lossy(source);
249 let effective = source_compile_options(&lossy, options);
250 check_compile_cancelled(cancel.as_ref())?;
251 let parse = parse_file_bytes_with(source, &effective.parse_config());
252 if let Some(error) = parse.errors.first() {
253 return Err(CompileError::parse(error.message.clone(), error.location));
254 }
255 compile_ast_with_implicit_return_delta(
256 parse.root,
257 &effective,
258 u8::from(source.ends_with(b"\n")),
259 cancel,
260 )
261}
262
263#[doc(hidden)]
272pub fn chunkify_parse_error(
273 result: Result<BytecodeChunk, CompileError>,
274) -> Result<BytecodeChunk, CompileError> {
275 match result {
276 Err(error) if error.kind() == CompileErrorKind::Parse => {
277 let message = match error.location() {
278 Some(location) => {
279 format!(":{}: {}", location.begin.line + 1, error.message())
280 }
281 None => error.message().to_owned(),
282 };
283 Ok(BytecodeChunk::Error {
284 message: message.into_bytes(),
285 })
286 }
287 other => other,
288 }
289}
290
291fn line_location(line: u32) -> Location {
294 let position = ruau_ast::Position {
295 line: line.saturating_sub(1),
296 column: 0,
297 };
298 Location {
299 begin: position,
300 end: position,
301 }
302}
303
304fn compile_ast_with_implicit_return_delta(
305 root: Stat,
306 options: &UpstreamCompilerOptions,
307 implicit_return_line_delta: u8,
308 cancel: Option<Arc<AtomicBool>>,
309) -> Result<BytecodeChunk, CompileError> {
310 check_compile_cancelled(cancel.as_ref())?;
311 if let Some((line, message)) = repeat_continue_condition_error(&root) {
312 return Err(CompileError::parse(message, line_location(line)));
313 }
314 if let Some((location, message)) = export_value_ast_error(&root) {
315 return Err(CompileError::parse(message, location));
316 }
317
318 let root = Rc::new(root);
321 let context = CompileContext::with_cancel(Rc::clone(&root), options, cancel);
322 context.check_cancelled()?;
323 let mut compiler = FunctionCompiler::new(context, implicit_return_line_delta);
324 compiler.compile_registered_functions_for_root(&root)?;
325 compiler.compile_root(&root)?;
326 Ok(compiler.finish())
327}
328
329fn check_compile_cancelled(cancel: Option<&Arc<AtomicBool>>) -> Result<(), CompileError> {
330 if cancel.is_some_and(|cancel| cancel.load(Ordering::Relaxed)) {
331 return Err(CompileError::cancelled());
332 }
333 Ok(())
334}
335
336fn export_value_ast_error(root: &Stat) -> Option<(Location, &'static str)> {
337 let Stat::Block { body, .. } = root else {
338 return exported_value_location(root).map(|location| (location, EXPORT_TOP_LEVEL_MESSAGE));
339 };
340
341 let mut has_export = false;
342 let mut has_return = false;
343 for stat in body {
344 if let Some(location) = nested_exported_value_location(stat) {
345 return Some((location, EXPORT_TOP_LEVEL_MESSAGE));
346 }
347 if let Some(location) = exported_value_location(stat) {
348 if has_return {
349 return Some((location, EXPORT_RETURN_CONFLICT_MESSAGE));
350 }
351 has_export = true;
352 }
353 if let Stat::Return {
354 location: Some(location),
355 ..
356 } = stat
357 {
358 if has_export {
359 return Some((*location, EXPORT_RETURN_CONFLICT_MESSAGE));
360 }
361 has_return = true;
362 }
363 }
364
365 None
366}
367
368fn nested_exported_value_location(stat: &Stat) -> Option<Location> {
369 struct NestedExportFinder {
370 skip_root: bool,
371 location: Option<Location>,
372 }
373
374 impl<'ast> Visitor<'ast> for NestedExportFinder {
375 fn visit_stat(&mut self, stat: &'ast Stat) -> WalkControl {
376 if self.skip_root {
377 self.skip_root = false;
378 return WalkControl::Continue;
379 }
380 if self.location.is_none() {
381 self.location = exported_value_location(stat);
382 }
383 if self.location.is_some() {
384 WalkControl::SkipChildren
385 } else {
386 WalkControl::Continue
387 }
388 }
389 }
390
391 let mut finder = NestedExportFinder {
392 skip_root: true,
393 location: None,
394 };
395 walk_stat(stat, &mut finder);
396 finder.location
397}
398
399fn exported_value_location(stat: &Stat) -> Option<Location> {
400 match stat {
401 Stat::Local {
402 exported: true,
403 location,
404 ..
405 }
406 | Stat::LocalFunction {
407 exported: true,
408 location,
409 ..
410 }
411 | Stat::Class {
412 exported: true,
413 location,
414 ..
415 } => *location,
416 _ => None,
417 }
418}
419
420#[cfg(test)]
421mod tests;