Skip to main content

ruprizzle_macros/
lib.rs

1//! Proc-macro support for the ruprizzle runtime.
2//!
3//! Implemented alongside P4; see
4//! `ProjectPlan/ImplementationPlan/ImplPlan05QueryBuilderRuntime.md`.
5//!
6//! This crate stays deliberately thin. The ORM's type safety comes from
7//! generated column tokens (ADR-005), not from macro magic, so the only macros
8//! here are conveniences such as the injection-safe `raw!` fragment builder.
9
10#![forbid(unsafe_code)]
11#![warn(missing_docs, clippy::pedantic)]
12
13use std::collections::HashMap;
14use std::{env, fs};
15
16use proc_macro::TokenStream;
17use proc_macro_crate::FoundCrate;
18use quote::quote;
19use syn::{Expr, Token, parse_macro_input, punctuated::Punctuated};
20
21/// Resolves the path prefix to the `ruprizzle` crate at macro-expansion time.
22///
23/// Inside the `ruprizzle` crate itself (e.g. its own unit or integration tests)
24/// this returns `crate`. For downstream crates it returns the crate name as
25/// declared in the user's `Cargo.toml` (commonly `::ruprizzle`).
26fn crate_path() -> Result<proc_macro2::TokenStream, syn::Error> {
27    match proc_macro_crate::crate_name("ruprizzle") {
28        Ok(FoundCrate::Itself) => Ok(quote!(crate)),
29        Ok(FoundCrate::Name(name)) => {
30            let ident = proc_macro2::Ident::new(&name, proc_macro2::Span::call_site());
31            Ok(quote!(::#ident))
32        }
33        Err(err) => Err(syn::Error::new(
34            proc_macro2::Span::call_site(),
35            format!("raw! requires the `ruprizzle` crate to be present in Cargo.toml: {err}"),
36        )),
37    }
38}
39
40/// Builds an injection-safe raw SQL fragment.
41///
42/// The first argument is a string literal containing `{}` placeholders. Each
43/// remaining argument is an expression whose value is bound as a SQL parameter.
44/// The placeholders are replaced with bind markers; the actual values are never
45/// interpolated into the SQL string.
46#[proc_macro]
47pub fn raw(input: TokenStream) -> TokenStream {
48    let args = parse_macro_input!(input with Punctuated::<Expr, Token![,]>::parse_terminated);
49
50    let mut iter = args.into_iter();
51    let Some(first) = iter.next() else {
52        return syn::Error::new(
53            proc_macro2::Span::call_site(),
54            "raw! requires at least a format string",
55        )
56        .to_compile_error()
57        .into();
58    };
59
60    let Expr::Lit(syn::ExprLit {
61        lit: syn::Lit::Str(format_str),
62        ..
63    }) = &first
64    else {
65        return syn::Error::new_spanned(
66            first,
67            "the first argument to raw! must be a string literal",
68        )
69        .to_compile_error()
70        .into();
71    };
72
73    let values: Vec<Expr> = iter.collect();
74    let literal = format_str.value();
75    let placeholder_count = literal.matches("{}").count();
76
77    if placeholder_count != values.len() {
78        return syn::Error::new_spanned(
79            format_str,
80            format!(
81                "raw! format string has {placeholder_count} placeholders but {} expressions were provided",
82                values.len()
83            ),
84        )
85        .to_compile_error()
86        .into();
87    }
88
89    if let Some(err) = offline_schema_check(&literal, format_str) {
90        return err.to_compile_error().into();
91    }
92
93    let parts: Vec<String> = literal.split("{}").map(String::from).collect();
94
95    let part_lits: Vec<proc_macro2::Literal> = parts
96        .iter()
97        .map(|part| proc_macro2::Literal::string(part))
98        .collect();
99
100    let crate_path = match crate_path() {
101        Ok(path) => path,
102        Err(e) => return e.to_compile_error().into(),
103    };
104    let binds_ident = proc_macro2::Ident::new("__rz_raw_binds", proc_macro2::Span::mixed_site());
105
106    let push_binds: Vec<proc_macro2::TokenStream> = values
107        .iter()
108        .map(|expr| quote! { #binds_ident.push(#crate_path::Encodable::to_value(&#expr)); })
109        .collect();
110
111    let expanded = quote! {
112        #crate_path::RawFragment::new(
113            ::std::vec![#(::std::string::String::from(#part_lits)),*],
114            {
115                let mut #binds_ident = ::std::vec![];
116                #(#push_binds)*
117                #binds_ident
118            },
119        )
120    };
121
122    expanded.into()
123}
124
125fn offline_schema_check(sql: &str, format_str: &syn::LitStr) -> Option<syn::Error> {
126    let Ok(path) = env::var("RUPRIZZLE_OFFLINE_SCHEMA") else {
127        return None;
128    };
129    let source = match fs::read_to_string(&path) {
130        Ok(s) => s,
131        Err(e) => {
132            return Some(syn::Error::new_spanned(
133                format_str,
134                format!("RUPRIZZLE_OFFLINE_SCHEMA points to unreadable file `{path}`: {e}"),
135            ));
136        }
137    };
138
139    let schema = match ruprizzle_parser::parse(&path, &source) {
140        Ok(s) => s,
141        Err(e) => {
142            return Some(syn::Error::new_spanned(
143                format_str,
144                format!("failed to parse offline schema `{path}`: {e:?}"),
145            ));
146        }
147    };
148
149    let table_to_model: HashMap<&str, &ruprizzle_core::ir::Model> = schema
150        .models
151        .values()
152        .map(|m| (m.table.as_str(), m))
153        .collect();
154
155    let tokens = tokenise_sql(sql);
156    for (idx, token) in tokens.iter().enumerate() {
157        if let Some(model) = table_to_model.get(token.as_str()) {
158            if let Some(next) = tokens.get(idx + 1) {
159                if next == "." {
160                    if let Some(column) = tokens.get(idx + 2) {
161                        if !model.fields.values().any(|f| f.column == *column) {
162                            return Some(syn::Error::new_spanned(
163                                format_str,
164                                format!("unknown column `{column}` on table `{token}`"),
165                            ));
166                        }
167                    }
168                }
169            }
170            continue;
171        }
172
173        if idx > 0
174            && tokens
175                .get(idx - 1)
176                .is_some_and(|prev| is_table_context(prev))
177            && !is_sql_keyword(token)
178            && !looks_like_string_or_param(token)
179        {
180            return Some(syn::Error::new_spanned(
181                format_str,
182                format!("unknown table `{token}`"),
183            ));
184        }
185    }
186
187    None
188}
189
190fn tokenise_sql(sql: &str) -> Vec<String> {
191    let mut tokens = Vec::new();
192    let mut current = String::new();
193    let mut in_string = false;
194    let mut string_quote = '\0';
195
196    for c in sql.chars() {
197        if in_string {
198            current.push(c);
199            if c == string_quote {
200                in_string = false;
201            }
202            continue;
203        }
204        if c == '\'' || c == '"' {
205            if !current.is_empty() {
206                tokens.push(std::mem::take(&mut current));
207            }
208            in_string = true;
209            string_quote = c;
210            current.push(c);
211            continue;
212        }
213        if c.is_alphanumeric() || c == '_' || c == '*' || c == '$' {
214            current.push(c);
215        } else {
216            if !current.is_empty() {
217                tokens.push(std::mem::take(&mut current));
218            }
219            if c == '.' {
220                tokens.push(".".to_owned());
221            }
222        }
223    }
224    if !current.is_empty() {
225        tokens.push(current);
226    }
227    tokens
228}
229
230fn is_table_context(prev: &str) -> bool {
231    matches!(
232        prev.to_ascii_uppercase().as_str(),
233        "FROM" | "JOIN" | "INTO" | "UPDATE" | "TABLE"
234    )
235}
236
237fn is_sql_keyword(token: &str) -> bool {
238    const KEYWORDS: &[&str] = &[
239        "SELECT", "FROM", "WHERE", "AND", "OR", "NOT", "INSERT", "UPDATE", "DELETE", "JOIN",
240        "INNER", "LEFT", "RIGHT", "FULL", "OUTER", "ON", "GROUP", "BY", "ORDER", "LIMIT", "OFFSET",
241        "HAVING", "VALUES", "SET", "AS", "WITH", "UNION", "ALL", "DISTINCT", "IS", "NULL", "TRUE",
242        "FALSE", "IN", "BETWEEN", "LIKE", "EXISTS", "CASE", "WHEN", "THEN", "ELSE", "END",
243    ];
244    KEYWORDS.iter().any(|&k| k == token.to_ascii_uppercase())
245}
246
247fn looks_like_string_or_param(token: &str) -> bool {
248    token.starts_with('\'') || token.starts_with('"') || token.starts_with('$')
249}