use std::rc::Rc;
use std::sync::Arc;
use hamelin_lib::err::TranslationErrors;
use hamelin_lib::func::registry::FunctionRegistry;
use hamelin_lib::provider::{EnvironmentProvider, NoOpProvider};
use hamelin_lib::tree::ast::identifier::{CompoundIdentifier, Identifier, SimpleIdentifier};
use hamelin_lib::tree::typed_ast::context::StatementTranslationContext;
use hamelin_lib::tree::typed_ast::query::TypedStatement;
use crate::ir::IRStatement;
use crate::normalize::normalize_statement;
pub fn lower(statement: Rc<TypedStatement>) -> Result<IRStatement, TranslationErrors> {
LoweringOptions::default().lower(statement)
}
pub fn lower_with() -> LoweringOptions {
LoweringOptions::default()
}
#[derive(Clone)]
pub struct LoweringOptions {
registry: Arc<FunctionRegistry>,
provider: Arc<dyn EnvironmentProvider>,
timestamp_field: Identifier,
message_field: Identifier,
}
impl Default for LoweringOptions {
fn default() -> Self {
Self {
registry: Arc::new(FunctionRegistry::default()),
provider: Arc::new(NoOpProvider::default()),
timestamp_field: SimpleIdentifier::new("timestamp").into(),
message_field: CompoundIdentifier::new(
SimpleIdentifier::new("event"),
SimpleIdentifier::new("original"),
vec![],
)
.into(),
}
}
}
impl LoweringOptions {
pub fn with_registry(mut self, registry: Arc<FunctionRegistry>) -> Self {
self.registry = registry;
self
}
pub fn with_provider(mut self, provider: Arc<dyn EnvironmentProvider>) -> Self {
self.provider = provider;
self
}
pub fn with_timestamp_field(mut self, field: impl Into<Identifier>) -> Self {
self.timestamp_field = field.into();
self
}
pub fn with_message_field(mut self, field: impl Into<Identifier>) -> Self {
self.message_field = field.into();
self
}
pub fn lower(self, statement: Rc<TypedStatement>) -> Result<IRStatement, TranslationErrors> {
let mut ctx = StatementTranslationContext::new(self.registry, self.provider)
.with_timestamp_field(self.timestamp_field)
.with_message_field(self.message_field);
let normalized =
normalize_statement(statement, &mut ctx).map_err(|e| (*e).clone().single())?;
IRStatement::from_typed(normalized, &mut ctx).map_err(|e| (*e).clone().single())
}
}