use crate::error::TranspileError;
use crate::hir::HirModule;
use anyhow::Result;
use std::fmt;
#[derive(Debug, thiserror::Error)]
pub enum ValidationError {
#[error("Invalid syntax: {0}")]
InvalidSyntax(String),
#[error("Type error: {0}")]
TypeError(String),
#[error("Unsupported feature: {0}")]
UnsupportedFeature(String),
}
pub trait TranspilationBackend: Send + Sync {
fn transpile(&self, hir: &HirModule) -> Result<String, TranspileError>;
fn validate_output(&self, code: &str) -> Result<(), ValidationError>;
fn optimize(&self, hir: &HirModule) -> HirModule {
hir.clone()
}
fn target_name(&self) -> &str;
fn file_extension(&self) -> &str;
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum TranspilationTarget {
Rust,
#[cfg(feature = "ruchy")]
Ruchy,
}
impl Default for TranspilationTarget {
fn default() -> Self {
Self::Rust
}
}
impl fmt::Display for TranspilationTarget {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Rust => write!(f, "rust"),
#[cfg(feature = "ruchy")]
Self::Ruchy => write!(f, "ruchy"),
}
}
}
impl TranspilationTarget {
pub fn file_extension(&self) -> &str {
match self {
Self::Rust => "rs",
#[cfg(feature = "ruchy")]
Self::Ruchy => "ruchy",
}
}
}
impl std::str::FromStr for TranspilationTarget {
type Err = String;
fn from_str(s: &str) -> Result<Self, Self::Err> {
match s.to_lowercase().as_str() {
"rust" | "rs" => Ok(Self::Rust),
#[cfg(feature = "ruchy")]
"ruchy" | "ruc" => Ok(Self::Ruchy),
_ => Err(format!("Unknown transpilation target: {}", s)),
}
}
}
impl TranspileError {
pub fn backend_error(msg: impl Into<String>) -> Self {
Self::new(crate::error::ErrorKind::CodeGenerationError(msg.into()))
}
pub fn transform_error(msg: impl Into<String>) -> Self {
Self::new(crate::error::ErrorKind::CodeGenerationError(
format!("Transformation failed: {}", msg.into())
))
}
pub fn optimization_error(msg: impl Into<String>) -> Self {
Self::new(crate::error::ErrorKind::InternalError(
format!("Optimization failed: {}", msg.into())
))
}
}
pub use crate::error::TranspileError as BackendError;