Skip to main content

no_mistakes_postgres_engine/embedded/helpers/program/lower/
mod.rs

1//! Lowers a top-level helper's AST to a [`Program`].
2
3mod compound;
4mod expr;
5mod stmt;
6mod switch;
7mod template;
8
9pub(crate) use switch::names as throwing_names;
10
11use super::{Mark, Param, Program, Stmt};
12use crate::embedded::tags::SqlTagNames;
13use no_mistakes_ts_facts::syntax_helpers::byte_offset_to_line;
14use oxc_ast::ast::{BindingPattern, FormalParameters, FunctionBody, TSType, TSTypeName};
15use oxc_span::GetSpan;
16use std::collections::HashSet;
17
18/// What lowering reads about the declaring file.
19pub(crate) struct Ctx<'a> {
20    pub(crate) source: &'a str,
21    pub(crate) tags: &'a SqlTagNames,
22    /// Local names of the `SQLStatement` type.
23    pub(crate) builder_types: &'a HashSet<String>,
24    /// Names that are not the trusted tag even when spelled like it
25    /// (top-level rebindings; the function's own parameters are added here).
26    pub(crate) rebound: &'a dyn Fn(&str) -> bool,
27    /// Same-file functions whose bodies always throw.
28    pub(crate) throws: &'a HashSet<String>,
29}
30
31/// The body of a callable: statements, or an arrow function's expression.
32pub(crate) enum Body<'a, 'b> {
33    Statements(&'b FunctionBody<'a>),
34    Expression(&'b oxc_ast::ast::Expression<'a>),
35}
36
37/// Lowering state for one function.
38pub(super) struct Scope<'c, 'a> {
39    pub(super) ctx: &'c Ctx<'a>,
40    /// Parameter names, which can shadow the trusted tag.
41    pub(super) params: Vec<String>,
42    /// Names declared so far in the function (parameters and locals).
43    pub(super) declared: Vec<String>,
44    /// A nested function declaration was seen; see `Program::body`.
45    pub(super) hoisted: bool,
46}
47
48impl Scope<'_, '_> {
49    pub(super) fn is_rebound(&self, name: &str) -> bool {
50        self.declared.iter().any(|declared| declared == name) || (self.ctx.rebound)(name)
51    }
52
53    pub(super) fn mark(&self, span: oxc_span::Span) -> Mark {
54        let origin = span.start;
55        Mark {
56            line: byte_offset_to_line(self.ctx.source, origin as usize),
57            origin,
58        }
59    }
60}
61
62/// `None` for a parameter list the model cannot bind (destructuring, rest,
63/// duplicate names). Statements it cannot model lower to `Opaque` instead.
64pub(crate) fn lower(
65    params: &FormalParameters<'_>,
66    body: Body<'_, '_>,
67    ctx: &Ctx<'_>,
68) -> Option<Program> {
69    if params.rest.is_some() {
70        return None;
71    }
72    let mut scope = Scope {
73        ctx,
74        params: Vec::new(),
75        declared: Vec::new(),
76        hoisted: false,
77    };
78    for param in &params.items {
79        let BindingPattern::BindingIdentifier(ident) = &param.pattern else {
80            return None;
81        };
82        let name = ident.name.to_string();
83        if scope.declared.contains(&name) {
84            return None;
85        }
86        scope.declared.push(name.clone());
87        scope.params.push(name);
88    }
89    let mut lowered = Vec::with_capacity(params.items.len());
90    for (param, name) in params.items.iter().zip(scope.params.clone()) {
91        let default = param
92            .initializer
93            .as_ref()
94            .map(|default| expr::lower(&mut scope, default));
95        let builder = is_builder_type(param, ctx.builder_types);
96        lowered.push(Param {
97            name,
98            builder,
99            default,
100        });
101    }
102    let mut body = match body {
103        Body::Statements(body) => stmt::block(&mut scope, &body.statements)?,
104        Body::Expression(expression) => {
105            let mark = scope.mark(expression.span());
106            vec![Stmt::Return(
107                Some(expr::lower(&mut scope, expression)),
108                mark,
109            )]
110        }
111    };
112    if scope.hoisted {
113        // Runs first, so a hoisted function is never silently skipped.
114        body.insert(0, Stmt::Opaque);
115    }
116    Some(Program::new(lowered, body))
117}
118
119impl Program {
120    /// Whether any reachable-looking node can contribute SQL text.
121    pub(crate) fn contributes_sql(&self) -> bool {
122        self.body.iter().any(stmt::contributes_sql)
123    }
124}
125
126fn is_builder_type(param: &oxc_ast::ast::FormalParameter<'_>, types: &HashSet<String>) -> bool {
127    let Some(annotation) = &param.type_annotation else {
128        return false;
129    };
130    let TSType::TSTypeReference(reference) = &annotation.type_annotation else {
131        return false;
132    };
133    matches!(
134        &reference.type_name,
135        TSTypeName::IdentifierReference(ty) if types.contains(ty.name.as_str())
136    )
137}