mod compound;
mod expr;
mod stmt;
mod switch;
mod template;
pub(crate) use switch::names as throwing_names;
use super::{Mark, Param, Program, Stmt};
use crate::embedded::tags::SqlTagNames;
use no_mistakes_ts_facts::syntax_helpers::byte_offset_to_line;
use oxc_ast::ast::{BindingPattern, FormalParameters, FunctionBody, TSType, TSTypeName};
use oxc_span::GetSpan;
use std::collections::HashSet;
pub(crate) struct Ctx<'a> {
pub(crate) source: &'a str,
pub(crate) tags: &'a SqlTagNames,
pub(crate) builder_types: &'a HashSet<String>,
pub(crate) rebound: &'a dyn Fn(&str) -> bool,
pub(crate) throws: &'a HashSet<String>,
}
pub(crate) enum Body<'a, 'b> {
Statements(&'b FunctionBody<'a>),
Expression(&'b oxc_ast::ast::Expression<'a>),
}
pub(super) struct Scope<'c, 'a> {
pub(super) ctx: &'c Ctx<'a>,
pub(super) params: Vec<String>,
pub(super) declared: Vec<String>,
pub(super) hoisted: bool,
}
impl Scope<'_, '_> {
pub(super) fn is_rebound(&self, name: &str) -> bool {
self.declared.iter().any(|declared| declared == name) || (self.ctx.rebound)(name)
}
pub(super) fn mark(&self, span: oxc_span::Span) -> Mark {
let origin = span.start;
Mark {
line: byte_offset_to_line(self.ctx.source, origin as usize),
origin,
}
}
}
pub(crate) fn lower(
params: &FormalParameters<'_>,
body: Body<'_, '_>,
ctx: &Ctx<'_>,
) -> Option<Program> {
if params.rest.is_some() {
return None;
}
let mut scope = Scope {
ctx,
params: Vec::new(),
declared: Vec::new(),
hoisted: false,
};
for param in ¶ms.items {
let BindingPattern::BindingIdentifier(ident) = ¶m.pattern else {
return None;
};
let name = ident.name.to_string();
if scope.declared.contains(&name) {
return None;
}
scope.declared.push(name.clone());
scope.params.push(name);
}
let mut lowered = Vec::with_capacity(params.items.len());
for (param, name) in params.items.iter().zip(scope.params.clone()) {
let default = param
.initializer
.as_ref()
.map(|default| expr::lower(&mut scope, default));
let builder = is_builder_type(param, ctx.builder_types);
lowered.push(Param {
name,
builder,
default,
});
}
let mut body = match body {
Body::Statements(body) => stmt::block(&mut scope, &body.statements)?,
Body::Expression(expression) => {
let mark = scope.mark(expression.span());
vec![Stmt::Return(
Some(expr::lower(&mut scope, expression)),
mark,
)]
}
};
if scope.hoisted {
body.insert(0, Stmt::Opaque);
}
Some(Program::new(lowered, body))
}
impl Program {
pub(crate) fn contributes_sql(&self) -> bool {
self.body.iter().any(stmt::contributes_sql)
}
}
fn is_builder_type(param: &oxc_ast::ast::FormalParameter<'_>, types: &HashSet<String>) -> bool {
let Some(annotation) = ¶m.type_annotation else {
return false;
};
let TSType::TSTypeReference(reference) = &annotation.type_annotation else {
return false;
};
matches!(
&reference.type_name,
TSTypeName::IdentifierReference(ty) if types.contains(ty.name.as_str())
)
}