use std::{
fmt,
rc::Rc,
sync::{
Arc,
atomic::{AtomicBool, Ordering},
},
};
use ruau_ast::{
Location,
parse::{parse_file_bytes_with, parse_file_with},
syntax::Stat,
};
use crate::BytecodeChunk;
mod analysis;
mod builtin_folding;
mod context;
mod function_compiler;
mod helpers;
mod inline_cost;
mod options;
use analysis::ConstantValue;
use context::CompileContext;
#[cfg(test)]
use function_compiler::constant_ad_operand;
use function_compiler::{
BreakBranchKind, FunctionCompiler, LoopControlBranchKind, LoopUnrollPlan, TypeAliasInfo,
};
use helpers::*;
pub use options::{
CompileOptions, CompilerOptions, FastFlag, FastInt, KnownMember, KnownMemberValue,
effective_compile_options, source_compile_options,
};
pub const CONSTANT_STRING_FOLD_LIMIT: usize = 4096;
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct CompileError {
kind: CompileErrorKind,
location: Option<Location>,
message: String,
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
#[non_exhaustive]
pub enum CompileErrorKind {
Parse,
Cancelled,
Internal,
}
impl CompileError {
pub fn new(message: impl Into<String>) -> Self {
Self {
kind: CompileErrorKind::Internal,
location: None,
message: message.into(),
}
}
pub fn cancelled() -> Self {
Self {
kind: CompileErrorKind::Cancelled,
location: None,
message: "compilation cancelled".to_owned(),
}
}
fn parse(message: impl Into<String>, location: Location) -> Self {
Self {
kind: CompileErrorKind::Parse,
location: Some(location),
message: message.into(),
}
}
#[must_use]
pub fn kind(&self) -> CompileErrorKind {
self.kind
}
#[must_use]
pub fn location(&self) -> Option<Location> {
self.location
}
#[must_use]
pub fn message(&self) -> &str {
&self.message
}
}
impl fmt::Display for CompileError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
if let Some(location) = self.location {
write!(
f,
"{}:{}: {}",
location.begin.line + 1,
location.begin.column + 1,
self.message
)
} else {
f.write_str(&self.message)
}
}
}
impl std::error::Error for CompileError {}
pub fn compile_source(
source: &str,
options: &CompileOptions,
) -> Result<BytecodeChunk, CompileError> {
compile_source_with_cancel(source, options, None)
}
pub fn compile_source_with_cancel(
source: &str,
options: &CompileOptions,
cancel: Option<Arc<AtomicBool>>,
) -> Result<BytecodeChunk, CompileError> {
let options = options.to_compiler_options();
compile_source_with_compiler_options_and_cancel(source, &options, cancel)
}
#[doc(hidden)]
pub fn compile_source_with_compiler_options(
source: &str,
options: &CompilerOptions,
) -> Result<BytecodeChunk, CompileError> {
compile_source_with_compiler_options_and_cancel(source, options, None)
}
#[doc(hidden)]
pub fn compile_source_with_compiler_options_and_cancel(
source: &str,
options: &CompilerOptions,
cancel: Option<Arc<AtomicBool>>,
) -> Result<BytecodeChunk, CompileError> {
chunkify_parse_error(compile_source_strict_with_compiler_options_and_cancel(
source, options, cancel,
))
}
pub fn compile_source_bytes(
source: &[u8],
options: &CompileOptions,
) -> Result<BytecodeChunk, CompileError> {
compile_source_bytes_with_cancel(source, options, None)
}
pub fn compile_source_bytes_with_cancel(
source: &[u8],
options: &CompileOptions,
cancel: Option<Arc<AtomicBool>>,
) -> Result<BytecodeChunk, CompileError> {
let options = options.to_compiler_options();
compile_source_bytes_with_compiler_options_and_cancel(source, &options, cancel)
}
#[doc(hidden)]
pub fn compile_source_bytes_with_compiler_options(
source: &[u8],
options: &CompilerOptions,
) -> Result<BytecodeChunk, CompileError> {
compile_source_bytes_with_compiler_options_and_cancel(source, options, None)
}
#[doc(hidden)]
pub fn compile_source_bytes_with_compiler_options_and_cancel(
source: &[u8],
options: &CompilerOptions,
cancel: Option<Arc<AtomicBool>>,
) -> Result<BytecodeChunk, CompileError> {
chunkify_parse_error(
compile_source_bytes_strict_with_compiler_options_and_cancel(source, options, cancel),
)
}
pub fn compile_source_strict(
source: &str,
options: &CompileOptions,
) -> Result<BytecodeChunk, CompileError> {
compile_source_strict_with_cancel(source, options, None)
}
pub fn compile_source_strict_with_cancel(
source: &str,
options: &CompileOptions,
cancel: Option<Arc<AtomicBool>>,
) -> Result<BytecodeChunk, CompileError> {
let options = options.to_compiler_options();
compile_source_strict_with_compiler_options_and_cancel(source, &options, cancel)
}
#[doc(hidden)]
pub fn compile_source_strict_with_compiler_options(
source: &str,
options: &CompilerOptions,
) -> Result<BytecodeChunk, CompileError> {
compile_source_strict_with_compiler_options_and_cancel(source, options, None)
}
#[doc(hidden)]
pub fn compile_source_strict_with_compiler_options_and_cancel(
source: &str,
options: &CompilerOptions,
cancel: Option<Arc<AtomicBool>>,
) -> Result<BytecodeChunk, CompileError> {
let effective = source_compile_options(source, options);
check_compile_cancelled(cancel.as_ref())?;
let parse = parse_file_with(source, effective.parse_options, effective.syntax_flags);
if let Some(error) = parse.errors.first() {
return Err(CompileError::parse(error.message.clone(), error.location));
}
let Some(root) = parse.root else {
return Err(CompileError::new("parser did not produce a root block"));
};
compile_ast_with_implicit_return_delta(
root,
&effective,
u8::from(source.ends_with('\n')),
cancel,
)
}
pub fn compile_source_bytes_strict(
source: &[u8],
options: &CompileOptions,
) -> Result<BytecodeChunk, CompileError> {
compile_source_bytes_strict_with_cancel(source, options, None)
}
pub fn compile_source_bytes_strict_with_cancel(
source: &[u8],
options: &CompileOptions,
cancel: Option<Arc<AtomicBool>>,
) -> Result<BytecodeChunk, CompileError> {
let options = options.to_compiler_options();
compile_source_bytes_strict_with_compiler_options_and_cancel(source, &options, cancel)
}
#[doc(hidden)]
pub fn compile_source_bytes_strict_with_compiler_options(
source: &[u8],
options: &CompilerOptions,
) -> Result<BytecodeChunk, CompileError> {
compile_source_bytes_strict_with_compiler_options_and_cancel(source, options, None)
}
#[doc(hidden)]
pub fn compile_source_bytes_strict_with_compiler_options_and_cancel(
source: &[u8],
options: &CompilerOptions,
cancel: Option<Arc<AtomicBool>>,
) -> Result<BytecodeChunk, CompileError> {
let lossy = String::from_utf8_lossy(source);
let effective = source_compile_options(&lossy, options);
check_compile_cancelled(cancel.as_ref())?;
let parse = parse_file_bytes_with(source, effective.parse_options, effective.syntax_flags);
if let Some(error) = parse.errors.first() {
return Err(CompileError::parse(error.message.clone(), error.location));
}
let Some(root) = parse.root else {
return Err(CompileError::new("parser did not produce a root block"));
};
compile_ast_with_implicit_return_delta(
root,
&effective,
u8::from(source.ends_with(b"\n")),
cancel,
)
}
fn chunkify_parse_error(
result: Result<BytecodeChunk, CompileError>,
) -> Result<BytecodeChunk, CompileError> {
match result {
Err(error) if error.kind() == CompileErrorKind::Parse => {
let message = match error.location() {
Some(location) => {
format!(":{}: {}", location.begin.line + 1, error.message())
}
None => error.message().to_owned(),
};
Ok(BytecodeChunk::Error {
message: message.into_bytes(),
})
}
other => other,
}
}
fn line_location(line: u32) -> Location {
let position = ruau_ast::Position {
line: line.saturating_sub(1),
column: 0,
};
Location {
begin: position,
end: position,
}
}
fn compile_ast_with_implicit_return_delta(
root: Stat,
options: &CompilerOptions,
implicit_return_line_delta: u8,
cancel: Option<Arc<AtomicBool>>,
) -> Result<BytecodeChunk, CompileError> {
check_compile_cancelled(cancel.as_ref())?;
if let Some((line, message)) = repeat_continue_condition_error(&root) {
return Err(CompileError::parse(message, line_location(line)));
}
let root = Rc::new(root);
let context = CompileContext::with_cancel(Rc::clone(&root), options, cancel);
context.check_cancelled()?;
let mut compiler = FunctionCompiler::new(context, implicit_return_line_delta);
compiler.compile_registered_functions()?;
compiler.compile_root(&root)?;
Ok(compiler.finish())
}
fn check_compile_cancelled(cancel: Option<&Arc<AtomicBool>>) -> Result<(), CompileError> {
if cancel.is_some_and(|cancel| cancel.load(Ordering::Relaxed)) {
return Err(CompileError::cancelled());
}
Ok(())
}
#[cfg(test)]
mod tests;