Skip to main content

hamelin_lib/
lib.rs

1//! Hamelin core library — parser, AST, type-checker, and translation logic.
2//!
3//! Start with [`parse`] to get an AST, then [`type_check`] to type-check it.
4//! Each function has a `_with_options` variant that takes an options struct
5//! built via `bon::Builder` for customising behaviour (interner, provider,
6//! time range, etc.).
7//!
8//! All functions return [`WithTranslationErrors<T>`] which can be converted to
9//! `Result` via `.result()`, or destructured to access `.output` and `.errors`.
10
11extern crate core;
12
13use std::sync::Arc;
14
15use crate::err::WithTranslationErrors;
16use crate::provider::{EnvironmentProvider, NoOpProvider};
17use crate::tree::ast::context::ParseContext;
18use crate::tree::ast::expression::Expression;
19use crate::tree::ast::query::Query;
20use crate::tree::ast::{ParseWithContext, TypeCheck};
21use crate::tree::options::{template_context_from_specs, ParseOptions, TypeCheckOptions};
22use crate::tree::typed_ast::context::ExpressionTranslationContext;
23use crate::tree::typed_ast::context::StatementTranslationContext;
24use crate::tree::typed_ast::expression::TypedExpression;
25use crate::tree::typed_ast::query::TypedStatement;
26
27pub use crate::err::TemplateSubstitutionError;
28pub use crate::time_range::TimeRange;
29pub use crate::tree::options::{
30    parse_default_space, ExpressionTypeCheckOptions, QueryValidationMode, TemplateParameterKind,
31    TemplateParameterValue, TranslateOptions,
32};
33pub use crate::tree::substitute_query;
34pub use crate::tree::{
35    combine_parsed_queries_for_inlining, combine_queries_for_inlining, rewrite_table_references,
36    CombineQueriesError, CombineQueriesOk, CteInline, ParsedCteInline,
37};
38
39pub mod antlr;
40mod cast_semantics;
41pub mod catalog;
42pub mod completion;
43mod completion_boost;
44pub mod err;
45pub mod func;
46pub mod interner;
47pub mod operator;
48pub mod parser;
49pub mod provider;
50pub mod sql;
51pub mod time_range;
52pub mod translation;
53pub mod tree;
54pub mod types;
55mod write_utils;
56
57pub use cast_semantics::{f64_to_i64, parse_string_as_bool, parse_timestamp_to_utc};
58pub use completion_boost::{
59    BARE_DATASET_BOOST, CONNECTOR_DATASET_BOOST, CURRENT_SPACE_BOOST, EVENTS_DATASET_BOOST,
60    FIELD_BOOST, PIPELINE_DEF_BOOST, SIGNALS_DATASET_BOOST, UNRECOGNIZED_DATASET_BOOST,
61};
62pub use write_utils::Indent;
63
64pub const VERSION: &str = env!("CARGO_PKG_VERSION");
65
66// ---------------------------------------------------------------------------
67// Parse
68// ---------------------------------------------------------------------------
69
70/// Parse a Hamelin query string into an AST.
71///
72/// Uses default options. Call `.result()` to get `Result`, or access
73/// `.output` / `.errors` directly.
74pub fn parse(input: impl Into<String>) -> WithTranslationErrors<Query> {
75    parse_with_options(input, ParseOptions::default())
76}
77
78/// Parse a Hamelin query string with configurable options.
79pub fn parse_with_options(
80    input: impl Into<String>,
81    opts: ParseOptions,
82) -> WithTranslationErrors<Query> {
83    let ctx = match opts.interner {
84        Some(interner) => ParseContext::with_interner(interner),
85        None => ParseContext::new(),
86    };
87    let (output, errors) = Query::parse_with_context(input.into(), ctx);
88    WithTranslationErrors::new(output, errors)
89}
90
91// ---------------------------------------------------------------------------
92// Type-check
93// ---------------------------------------------------------------------------
94
95/// Type-check a parsed AST with default options.
96///
97/// Works for both `Query` and `Pipeline` (anything implementing `TypeCheck`).
98pub fn type_check<Ast: TypeCheck>(ast: impl Into<Arc<Ast>>) -> WithTranslationErrors<Ast::Output> {
99    type_check_with_options(ast, TypeCheckOptions::default())
100}
101
102pub fn type_check_with_provider<Ast: TypeCheck>(
103    ast: impl Into<Arc<Ast>>,
104    provider: Arc<dyn EnvironmentProvider>,
105) -> WithTranslationErrors<Ast::Output> {
106    type_check_with_options(ast, TypeCheckOptions::builder().provider(provider).build())
107}
108
109/// Type-check a parsed AST with configurable options.
110///
111/// Works for both `Query` and `Pipeline` (anything implementing `TypeCheck`).
112pub fn type_check_with_options<Ast: TypeCheck>(
113    ast: impl Into<Arc<Ast>>,
114    opts: TypeCheckOptions,
115) -> WithTranslationErrors<Ast::Output> {
116    let (template_types, template_enums) =
117        template_context_from_specs(opts.template_parameters.as_ref());
118    let mut ctx = StatementTranslationContext::new(opts.registry, opts.provider)
119        .with_query_validation_mode(opts.validation_mode)
120        .with_template_param_types(template_types)
121        .with_template_param_enums(template_enums);
122    if let Some(interner) = opts.interner {
123        ctx = ctx.with_interner(interner);
124    }
125    if let Some(timestamp_field) = opts.timestamp_field {
126        ctx = ctx.with_timestamp_field(timestamp_field);
127    }
128    if let Some(message_field) = opts.message_field {
129        ctx = ctx.with_message_field(message_field);
130    }
131    if let Some(default_space) = opts.default_space {
132        ctx = ctx.with_default_space(default_space);
133    }
134    let output = Ast::type_check_with_context(ast.into(), &mut ctx);
135    let errors = ctx.take_errors();
136    WithTranslationErrors::new(output, errors)
137}
138
139// ---------------------------------------------------------------------------
140// Combined parse + type-check
141// ---------------------------------------------------------------------------
142
143/// Parse and type-check a Hamelin query string in one step.
144pub fn parse_and_typecheck(input: impl Into<String>) -> WithTranslationErrors<TypedStatement> {
145    parse_and_typecheck_with_options(input, TypeCheckOptions::default())
146}
147
148/// Parse and type-check a Hamelin query string with configurable options.
149///
150/// The `interner` field in `TypeCheckOptions` is shared across both parse and
151/// type-check passes.
152pub fn parse_and_typecheck_with_options(
153    input: impl Into<String>,
154    opts: TypeCheckOptions,
155) -> WithTranslationErrors<TypedStatement> {
156    let parse_opts = ParseOptions {
157        interner: opts.interner.clone(),
158    };
159    let WithTranslationErrors {
160        output: ast,
161        errors: parse_errors,
162    } = parse_with_options(input, parse_opts);
163
164    let WithTranslationErrors {
165        output: typed,
166        errors: tc_errors,
167    } = type_check_with_options(ast, opts);
168
169    let mut all_errors = parse_errors;
170    all_errors.extend(tc_errors);
171    WithTranslationErrors::new(typed, all_errors)
172}
173
174// ---------------------------------------------------------------------------
175// Expression type-check (used internally, not a top-level API)
176// ---------------------------------------------------------------------------
177
178/// Type-check an expression AST node with configurable options.
179pub fn type_check_expression(
180    ast: impl Into<Arc<Expression>>,
181    opts: ExpressionTypeCheckOptions,
182) -> WithTranslationErrors<TypedExpression> {
183    let ast = ast.into();
184    let provider = Arc::new(NoOpProvider::default());
185    let (template_types, template_enums) =
186        template_context_from_specs(opts.template_parameters.as_ref());
187    let mut pipeline_ctx = StatementTranslationContext::new(opts.registry.clone(), provider)
188        .with_template_param_types(template_types)
189        .with_template_param_enums(template_enums);
190    if let Some(interner) = opts.interner {
191        pipeline_ctx = pipeline_ctx.with_interner(interner);
192    }
193    let mut expr_ctx = ExpressionTranslationContext::new(
194        opts.bindings,
195        opts.registry,
196        opts.fctx,
197        &mut pipeline_ctx,
198    );
199
200    let typed_expr = TypedExpression::from_ast_with_context(ast, &mut expr_ctx);
201    let errors = pipeline_ctx.take_errors();
202    WithTranslationErrors::new(typed_expr, errors)
203}