Skip to main content

no_mistakes_postgres_engine/embedded/helpers/
template.rs

1//! Helpers that return one untagged template whose interpolations are their
2//! own parameters, e.g. `` (parent: string) => `(${parent} IS NULL)` ``.
3//!
4//! The template is summarized once per file as structured data. A call whose
5//! every argument is a string literal splices the literals in as SQL text.
6
7use super::split::{compose, plain, split, Marker};
8use crate::embedded::placeholders::INTERNAL_PLACEHOLDER;
9use crate::embedded::unpublished_sql_text;
10use crate::embedded::walk::resolve::functions::provenance::RecoveredSql;
11use no_mistakes_ts_facts::syntax_helpers::unwrap_ts_wrappers;
12use oxc_ast::ast::{BindingPattern, Expression, FormalParameters};
13use std::ops::Range;
14
15#[derive(Clone, PartialEq, Eq)]
16pub struct TemplateHelper {
17    /// The whole template, each `${param}` kept as an internal placeholder.
18    sql: RecoveredSql,
19    /// Parameter index behind each placeholder, in text order.
20    slots: Vec<usize>,
21    parameters: usize,
22}
23
24/// One string-literal argument. `at` is the literal's physical location;
25/// `None` keeps the helper `${param}` line (a synthetic site with no caller).
26pub(crate) struct Spliced<'a> {
27    pub(crate) text: std::borrow::Cow<'a, str>,
28    pub(crate) at: Option<Marker>,
29}
30
31impl TemplateHelper {
32    /// Splices one string literal per parameter. `None` for any other call shape.
33    pub(crate) fn apply(&self, literals: &[Spliced<'_>]) -> Option<RecoveredSql> {
34        if literals.len() != self.parameters
35            || !literals.iter().all(|literal| splice_safe(&literal.text))
36        {
37            return None;
38        }
39        // `summarize` made exactly one placeholder per slot, in the same order.
40        let markers = placeholder_ranges(&self.sql.sql);
41        let (pieces, origins) = split(&self.sql, &markers);
42        let mut parts = Vec::with_capacity(pieces.len() * 2);
43        let mut pieces = pieces.into_iter();
44        parts.extend(pieces.next());
45        for ((slot, marker), piece) in self.slots.iter().zip(origins).zip(pieces) {
46            // The literal was written once. Every use of that parameter reads
47            // from the caller, not from this `${param}`.
48            let at = literals[*slot].at.clone().unwrap_or(marker);
49            parts.push(plain(literals[*slot].text.to_string(), at));
50            parts.push(piece);
51        }
52        compose(parts)
53    }
54}
55
56/// A literal is spliced verbatim, so it must keep the physical line map exact
57/// and must not forge an internal marker.
58fn splice_safe(text: &str) -> bool {
59    !text.contains(['\n', '\r', '\u{10FFFE}', '\u{10FFFF}'])
60}
61
62fn placeholder_ranges(sql: &str) -> Vec<Range<usize>> {
63    sql.match_indices(INTERNAL_PLACEHOLDER)
64        .map(|(start, marker)| {
65            let digits_start = start + marker.len();
66            let digits = sql[digits_start..]
67                .bytes()
68                .take_while(u8::is_ascii_digit)
69                .count();
70            start..digits_start + digits
71        })
72        .collect()
73}
74
75/// Summarizes one callable, or `None` when it is not a literal-identifier template.
76pub(crate) fn summarize(
77    params: &FormalParameters<'_>,
78    returned: &Expression<'_>,
79    source: &str,
80) -> Option<TemplateHelper> {
81    let names = parameter_names(params)?;
82    let Expression::TemplateLiteral(template) = unwrap_ts_wrappers(returned) else {
83        return None;
84    };
85    if template.expressions.is_empty() {
86        return None;
87    }
88    let slots = template
89        .expressions
90        .iter()
91        .map(|expression| match unwrap_ts_wrappers(expression) {
92            Expression::Identifier(ident) => {
93                names.iter().position(|name| *name == ident.name.as_str())
94            }
95            _ => None,
96        })
97        .collect::<Option<Vec<_>>>()?;
98    let sql = unpublished_sql_text(returned)?;
99    Some(TemplateHelper {
100        sql: RecoveredSql::literal(returned, source, sql),
101        slots,
102        parameters: names.len(),
103    })
104}
105
106/// Plain identifiers only: no default, rest, optional or destructured parameter.
107fn parameter_names<'a>(params: &'a FormalParameters<'_>) -> Option<Vec<&'a str>> {
108    if params.rest.is_some() {
109        return None;
110    }
111    let mut names = Vec::with_capacity(params.items.len());
112    for param in &params.items {
113        let BindingPattern::BindingIdentifier(ident) = &param.pattern else {
114            return None;
115        };
116        if param.initializer.is_some() || param.optional || names.contains(&ident.name.as_str()) {
117            return None;
118        }
119        names.push(ident.name.as_str());
120    }
121    Some(names)
122}