Introduce CompilationResult struct
This commit introduces the `CompilationResult` struct to encapsulate the outcome of a compilation pass. It holds either a successfully compiled `TypedNode` or a `Diagnostics` object containing errors. Helper methods for creating success or error results and for converting to a `Result` are also included. This improves error handling and clarity in the compilation process.
This commit is contained in:
@@ -19,3 +19,39 @@ pub use optimizer::*;
|
||||
pub use specializer::*;
|
||||
pub use lowering::*;
|
||||
pub use type_checker::*;
|
||||
|
||||
use crate::ast::diagnostics::Diagnostics;
|
||||
|
||||
/// The result of a compilation pass: either a typed AST or a set of diagnostics.
|
||||
pub struct CompilationResult {
|
||||
pub ast: Option<TypedNode>,
|
||||
pub diagnostics: Diagnostics,
|
||||
}
|
||||
|
||||
impl CompilationResult {
|
||||
pub fn success(ast: TypedNode) -> Self {
|
||||
Self {
|
||||
ast: Some(ast),
|
||||
diagnostics: Diagnostics::new(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn error(msg: impl Into<String>) -> Self {
|
||||
let mut diag = Diagnostics::new();
|
||||
diag.push_error(msg, None);
|
||||
Self {
|
||||
ast: None,
|
||||
diagnostics: diag,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn into_result(self) -> Result<TypedNode, String> {
|
||||
if self.diagnostics.has_errors() {
|
||||
Err(self.diagnostics.format_errors())
|
||||
} else if let Some(ast) = self.ast {
|
||||
Ok(ast)
|
||||
} else {
|
||||
Err("Compilation failed without diagnostics".to_string())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user