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};
17
18use crate::BytecodeChunk;
19
20mod analysis;
21mod builtin_folding;
22mod context;
23mod function_compiler;
24mod helpers;
25mod inline_cost;
26mod options;
27
28use analysis::ConstantValue;
29use context::CompileContext;
30#[cfg(test)]
31use function_compiler::constant_ad_operand;
32use function_compiler::{
33 BreakBranchKind, FunctionCompiler, LoopControlBranchKind, LoopUnrollPlan, TypeAliasInfo,
34};
35use helpers::*;
36pub use options::{
37 CompileOptions, CompilerOptions, FastFlag, FastInt, KnownMember, KnownMemberValue,
38 effective_compile_options, source_compile_options,
39};
40
41pub const CONSTANT_STRING_FOLD_LIMIT: usize = 4096;
42
43#[derive(Clone, Debug, Eq, PartialEq)]
52pub struct CompileError {
53 kind: CompileErrorKind,
54 location: Option<Location>,
55 message: String,
56}
57
58#[derive(Clone, Copy, Debug, Eq, PartialEq)]
60#[non_exhaustive]
61pub enum CompileErrorKind {
62 Parse,
65 Cancelled,
67 Internal,
69}
70
71impl CompileError {
72 pub fn new(message: impl Into<String>) -> Self {
77 Self {
78 kind: CompileErrorKind::Internal,
79 location: None,
80 message: message.into(),
81 }
82 }
83
84 pub fn cancelled() -> Self {
86 Self {
87 kind: CompileErrorKind::Cancelled,
88 location: None,
89 message: "compilation cancelled".to_owned(),
90 }
91 }
92
93 fn parse(message: impl Into<String>, location: Location) -> Self {
94 Self {
95 kind: CompileErrorKind::Parse,
96 location: Some(location),
97 message: message.into(),
98 }
99 }
100
101 #[must_use]
103 pub fn kind(&self) -> CompileErrorKind {
104 self.kind
105 }
106
107 #[must_use]
114 pub fn location(&self) -> Option<Location> {
115 self.location
116 }
117
118 #[must_use]
120 pub fn message(&self) -> &str {
121 &self.message
122 }
123}
124
125impl fmt::Display for CompileError {
126 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
127 if let Some(location) = self.location {
128 write!(
129 f,
130 "{}:{}: {}",
131 location.begin.line + 1,
132 location.begin.column + 1,
133 self.message
134 )
135 } else {
136 f.write_str(&self.message)
137 }
138 }
139}
140
141impl std::error::Error for CompileError {}
142
143pub fn compile_source(
150 source: &str,
151 options: &CompileOptions,
152) -> Result<BytecodeChunk, CompileError> {
153 compile_source_with_cancel(source, options, None)
154}
155
156pub fn compile_source_with_cancel(
162 source: &str,
163 options: &CompileOptions,
164 cancel: Option<Arc<AtomicBool>>,
165) -> Result<BytecodeChunk, CompileError> {
166 let options = options.to_compiler_options();
167 compile_source_with_compiler_options_and_cancel(source, &options, cancel)
168}
169
170#[doc(hidden)]
172pub fn compile_source_with_compiler_options(
173 source: &str,
174 options: &CompilerOptions,
175) -> Result<BytecodeChunk, CompileError> {
176 compile_source_with_compiler_options_and_cancel(source, options, None)
177}
178
179#[doc(hidden)]
181pub fn compile_source_with_compiler_options_and_cancel(
182 source: &str,
183 options: &CompilerOptions,
184 cancel: Option<Arc<AtomicBool>>,
185) -> Result<BytecodeChunk, CompileError> {
186 chunkify_parse_error(compile_source_strict_with_compiler_options_and_cancel(
187 source, options, cancel,
188 ))
189}
190
191pub fn compile_source_bytes(
197 source: &[u8],
198 options: &CompileOptions,
199) -> Result<BytecodeChunk, CompileError> {
200 compile_source_bytes_with_cancel(source, options, None)
201}
202
203pub fn compile_source_bytes_with_cancel(
209 source: &[u8],
210 options: &CompileOptions,
211 cancel: Option<Arc<AtomicBool>>,
212) -> Result<BytecodeChunk, CompileError> {
213 let options = options.to_compiler_options();
214 compile_source_bytes_with_compiler_options_and_cancel(source, &options, cancel)
215}
216
217#[doc(hidden)]
219pub fn compile_source_bytes_with_compiler_options(
220 source: &[u8],
221 options: &CompilerOptions,
222) -> Result<BytecodeChunk, CompileError> {
223 compile_source_bytes_with_compiler_options_and_cancel(source, options, None)
224}
225
226#[doc(hidden)]
228pub fn compile_source_bytes_with_compiler_options_and_cancel(
229 source: &[u8],
230 options: &CompilerOptions,
231 cancel: Option<Arc<AtomicBool>>,
232) -> Result<BytecodeChunk, CompileError> {
233 chunkify_parse_error(
234 compile_source_bytes_strict_with_compiler_options_and_cancel(source, options, cancel),
235 )
236}
237
238pub fn compile_source_strict(
244 source: &str,
245 options: &CompileOptions,
246) -> Result<BytecodeChunk, CompileError> {
247 compile_source_strict_with_cancel(source, options, None)
248}
249
250pub fn compile_source_strict_with_cancel(
256 source: &str,
257 options: &CompileOptions,
258 cancel: Option<Arc<AtomicBool>>,
259) -> Result<BytecodeChunk, CompileError> {
260 let options = options.to_compiler_options();
261 compile_source_strict_with_compiler_options_and_cancel(source, &options, cancel)
262}
263
264#[doc(hidden)]
267pub fn compile_source_strict_with_compiler_options(
268 source: &str,
269 options: &CompilerOptions,
270) -> Result<BytecodeChunk, CompileError> {
271 compile_source_strict_with_compiler_options_and_cancel(source, options, None)
272}
273
274#[doc(hidden)]
276pub fn compile_source_strict_with_compiler_options_and_cancel(
277 source: &str,
278 options: &CompilerOptions,
279 cancel: Option<Arc<AtomicBool>>,
280) -> Result<BytecodeChunk, CompileError> {
281 let effective = source_compile_options(source, options);
282 check_compile_cancelled(cancel.as_ref())?;
283 let parse = parse_file_with(source, effective.parse_options, effective.syntax_flags);
284 if let Some(error) = parse.errors.first() {
285 return Err(CompileError::parse(error.message.clone(), error.location));
289 }
290 let Some(root) = parse.root else {
291 return Err(CompileError::new("parser did not produce a root block"));
292 };
293 compile_ast_with_implicit_return_delta(
294 root,
295 &effective,
296 u8::from(source.ends_with('\n')),
297 cancel,
298 )
299}
300
301pub fn compile_source_bytes_strict(
306 source: &[u8],
307 options: &CompileOptions,
308) -> Result<BytecodeChunk, CompileError> {
309 compile_source_bytes_strict_with_cancel(source, options, None)
310}
311
312pub fn compile_source_bytes_strict_with_cancel(
318 source: &[u8],
319 options: &CompileOptions,
320 cancel: Option<Arc<AtomicBool>>,
321) -> Result<BytecodeChunk, CompileError> {
322 let options = options.to_compiler_options();
323 compile_source_bytes_strict_with_compiler_options_and_cancel(source, &options, cancel)
324}
325
326#[doc(hidden)]
328pub fn compile_source_bytes_strict_with_compiler_options(
329 source: &[u8],
330 options: &CompilerOptions,
331) -> Result<BytecodeChunk, CompileError> {
332 compile_source_bytes_strict_with_compiler_options_and_cancel(source, options, None)
333}
334
335#[doc(hidden)]
337pub fn compile_source_bytes_strict_with_compiler_options_and_cancel(
338 source: &[u8],
339 options: &CompilerOptions,
340 cancel: Option<Arc<AtomicBool>>,
341) -> Result<BytecodeChunk, CompileError> {
342 let lossy = String::from_utf8_lossy(source);
346 let effective = source_compile_options(&lossy, options);
347 check_compile_cancelled(cancel.as_ref())?;
348 let parse = parse_file_bytes_with(source, effective.parse_options, effective.syntax_flags);
349 if let Some(error) = parse.errors.first() {
350 return Err(CompileError::parse(error.message.clone(), error.location));
351 }
352 let Some(root) = parse.root else {
353 return Err(CompileError::new("parser did not produce a root block"));
354 };
355 compile_ast_with_implicit_return_delta(
356 root,
357 &effective,
358 u8::from(source.ends_with(b"\n")),
359 cancel,
360 )
361}
362
363fn chunkify_parse_error(
368 result: Result<BytecodeChunk, CompileError>,
369) -> Result<BytecodeChunk, CompileError> {
370 match result {
371 Err(error) if error.kind() == CompileErrorKind::Parse => {
372 let message = match error.location() {
373 Some(location) => {
374 format!(":{}: {}", location.begin.line + 1, error.message())
375 }
376 None => error.message().to_owned(),
377 };
378 Ok(BytecodeChunk::Error {
379 message: message.into_bytes(),
380 })
381 }
382 other => other,
383 }
384}
385
386fn line_location(line: u32) -> Location {
389 let position = ruau_ast::Position {
390 line: line.saturating_sub(1),
391 column: 0,
392 };
393 Location {
394 begin: position,
395 end: position,
396 }
397}
398
399fn compile_ast_with_implicit_return_delta(
400 root: Stat,
401 options: &CompilerOptions,
402 implicit_return_line_delta: u8,
403 cancel: Option<Arc<AtomicBool>>,
404) -> Result<BytecodeChunk, CompileError> {
405 check_compile_cancelled(cancel.as_ref())?;
406 if let Some((line, message)) = repeat_continue_condition_error(&root) {
407 return Err(CompileError::parse(message, line_location(line)));
408 }
409
410 let root = Rc::new(root);
413 let context = CompileContext::with_cancel(Rc::clone(&root), options, cancel);
414 context.check_cancelled()?;
415 let mut compiler = FunctionCompiler::new(context, implicit_return_line_delta);
416 compiler.compile_registered_functions()?;
417 compiler.compile_root(&root)?;
418 Ok(compiler.finish())
419}
420
421fn check_compile_cancelled(cancel: Option<&Arc<AtomicBool>>) -> Result<(), CompileError> {
422 if cancel.is_some_and(|cancel| cancel.load(Ordering::Relaxed)) {
423 return Err(CompileError::cancelled());
424 }
425 Ok(())
426}
427
428#[cfg(test)]
429mod tests;