Skip to main content

unionid_query/
lib.rs

1//! Compile-time checked inline queries for Unionid Rust applications.
2//!
3//! `queries!` binds one or more inline Unionid operations against an explicit
4//! declarative schema, then expands to the same typed Rust bindings produced by
5//! `unionid query rust --dir`.
6//!
7//! Binding errors are reported while compiling the Rust crate. For example,
8//! this unknown field is rejected before the application can run:
9//!
10//! ```compile_fail
11//! unionid_query::queries! {
12//!     schema "tests/schema.unid"
13//!     query unknown_field {
14//!         from tasks
15//!         filter missing == 1
16//!     }
17//! }
18//! ```
19//!
20//! Constructors are checked against the schema:
21//!
22//! ```compile_fail
23//! unionid_query::queries! {
24//!     schema "tests/schema.unid"
25//!     query invalid_constructor {
26//!         from tasks
27//!         filter match state {
28//!             Missing => true
29//!             _ => false
30//!         }
31//!     }
32//! }
33//! ```
34//!
35//! A parameter must have one inferred type throughout a query:
36//!
37//! ```compile_fail
38//! unionid_query::queries! {
39//!     schema "tests/schema.unid"
40//!     query parameter_conflict {
41//!         from tasks
42//!         filter id == $value && title == $value
43//!     }
44//! }
45//! ```
46//!
47//! Matches must cover every constructor:
48//!
49//! ```compile_fail
50//! unionid_query::queries! {
51//!     schema "tests/schema.unid"
52//!     query non_exhaustive_match {
53//!         from tasks
54//!         filter match state {
55//!             Pending => true
56//!             Running {..} => false
57//!         }
58//!     }
59//! }
60//! ```
61
62//! Generated defaults may be omitted on insert, but an upsert key is required:
63//!
64//! ```compile_fail,E0308
65//! unionid_query::queries! {
66//!     schema "tests/generated.unid"
67//!     query replace_item {upsert items $item}
68//! }
69//! let _ = replace_item::ReplaceItemParams {
70//!     item: replace_item::ReplaceItemParamsItem {
71//!         id: None,
72//!         owner: "missing key".into(),
73//!         state: State::Pending,
74//!         detail: Detail {note: None},
75//!         public_id: None,
76//!         created_at: None,
77//!     },
78//! };
79//! ```
80
81use std::path::{Path, PathBuf};
82
83use proc_macro::TokenStream;
84use proc_macro2::{Delimiter, LineColumn, Span, TokenStream as TokenStream2, TokenTree};
85use quote::quote;
86use syn::parse::{Parse, ParseStream};
87use syn::{Ident, LitStr, Result, braced, parse_macro_input};
88
89mod keyword {
90    syn::custom_keyword!(schema);
91    syn::custom_keyword!(query);
92}
93
94struct QueriesInput {
95    schema: LitStr,
96    queries: Vec<InlineQuery>,
97}
98
99struct InlineQuery {
100    name: Ident,
101    source: String,
102    body_span: Span,
103}
104
105impl Parse for QueriesInput {
106    fn parse(input: ParseStream<'_>) -> Result<Self> {
107        input.parse::<keyword::schema>()?;
108        let schema = input.parse::<LitStr>()?;
109        let mut queries = Vec::new();
110        while !input.is_empty() {
111            input.parse::<keyword::query>()?;
112            let name = input.parse::<Ident>()?;
113            let content;
114            let braces = braced!(content in input);
115            let tokens = content.parse::<TokenStream2>()?;
116            let source = source_from_tokens(&tokens, braces.span.join())?;
117            if source.trim().is_empty() {
118                return Err(syn::Error::new(name.span(), "query body cannot be empty"));
119            }
120            queries.push(InlineQuery {
121                name,
122                source,
123                body_span: braces.span.join(),
124            });
125        }
126        if queries.is_empty() {
127            return Err(syn::Error::new(
128                schema.span(),
129                "expected at least one `query name { ... }` entry",
130            ));
131        }
132        Ok(Self { schema, queries })
133    }
134}
135
136fn source_from_tokens(tokens: &TokenStream2, fallback_span: Span) -> Result<String> {
137    if tokens.is_empty() {
138        return Err(syn::Error::new(
139            fallback_span,
140            "inline query body cannot be empty",
141        ));
142    }
143    render_stream(tokens).ok_or_else(|| {
144        syn::Error::new(
145            fallback_span,
146            "cannot recover inline query token positions; write the query directly in this macro invocation",
147        )
148    })
149}
150
151fn render_stream(tokens: &TokenStream2) -> Option<String> {
152    let mut output = String::new();
153    let mut previous_end = None;
154    for tree in tokens.clone() {
155        let start = tree.span().start();
156        if start.line == 0 {
157            return None;
158        }
159        if let Some(end) = previous_end {
160            write_gap(&mut output, end, start);
161        }
162        render_tree(&mut output, tree.clone())?;
163        previous_end = Some(tree.span().end());
164    }
165    Some(output.trim().to_string())
166}
167
168fn write_gap(output: &mut String, previous: LineColumn, next: LineColumn) {
169    if next.line > previous.line {
170        for _ in previous.line..next.line {
171            output.push('\n');
172        }
173    } else if next.column > previous.column {
174        output.push(' ');
175    }
176}
177
178fn render_tree(output: &mut String, tree: TokenTree) -> Option<()> {
179    match tree {
180        TokenTree::Group(group) => {
181            let delimiters = match group.delimiter() {
182                Delimiter::Parenthesis => Some(('(', ')')),
183                Delimiter::Brace => Some(('{', '}')),
184                Delimiter::Bracket => Some(('[', ']')),
185                Delimiter::None => None,
186            };
187            if let Some((open, _)) = delimiters {
188                output.push(open);
189            }
190            output.push_str(&render_stream(&group.stream())?);
191            if let Some((_, close)) = delimiters {
192                output.push(close);
193            }
194        }
195        TokenTree::Ident(ident) => output.push_str(&ident.to_string()),
196        TokenTree::Punct(punct) => output.push(punct.as_char()),
197        TokenTree::Literal(literal) => output.push_str(&literal.to_string()),
198    }
199    Some(())
200}
201
202fn schema_path(path: &LitStr) -> Result<PathBuf> {
203    let relative = PathBuf::from(path.value());
204    if relative.as_os_str().is_empty() || relative.is_absolute() {
205        return Err(syn::Error::new(
206            path.span(),
207            "schema path must be a non-empty path relative to CARGO_MANIFEST_DIR",
208        ));
209    }
210    let manifest = std::env::var_os("CARGO_MANIFEST_DIR").ok_or_else(|| {
211        syn::Error::new(
212            path.span(),
213            "CARGO_MANIFEST_DIR is unavailable while expanding Unionid queries",
214        )
215    })?;
216    Ok(PathBuf::from(manifest).join(relative))
217}
218
219fn read_schema(path: &Path, span: Span) -> Result<String> {
220    const MAX_SCHEMA_BYTES: u64 = 1024 * 1024;
221    let metadata = std::fs::metadata(path).map_err(|error| {
222        syn::Error::new(
223            span,
224            format!("cannot inspect schema '{}': {error}", path.display()),
225        )
226    })?;
227    if !metadata.is_file() {
228        return Err(syn::Error::new(
229            span,
230            format!("schema '{}' is not a regular file", path.display()),
231        ));
232    }
233    if metadata.len() > MAX_SCHEMA_BYTES {
234        return Err(syn::Error::new(
235            span,
236            format!("schema '{}' exceeds the 1 MiB source limit", path.display()),
237        ));
238    }
239    std::fs::read_to_string(path).map_err(|error| {
240        syn::Error::new(
241            span,
242            format!("cannot read UTF-8 schema '{}': {error}", path.display()),
243        )
244    })
245}
246
247fn expand(input: QueriesInput) -> Result<TokenStream2> {
248    let path = schema_path(&input.schema)?;
249    let schema = read_schema(&path, input.schema.span())?;
250    let descriptions = input
251        .queries
252        .iter()
253        .map(|query| {
254            unionid::query_contract::describe(&schema, &query.source)
255                .map(|description| (query.name.to_string(), description))
256                .map_err(|error| {
257                    syn::Error::new(
258                        query.body_span,
259                        format!("Unionid query '{}' failed to bind: {error}", query.name),
260                    )
261                })
262        })
263        .collect::<Result<Vec<_>>>()?;
264    let generated = unionid::codegen::rust_query_bundle_from_descriptions(&schema, &descriptions)
265        .map_err(|error| {
266        syn::Error::new(
267            input.schema.span(),
268            format!("Unionid inline query generation failed: {error}"),
269        )
270    })?;
271    let generated = generated.parse::<TokenStream2>().map_err(|error| {
272        syn::Error::new(
273            input.schema.span(),
274            format!("Unionid generated invalid Rust tokens: {error}"),
275        )
276    })?;
277    let tracked_path = LitStr::new(
278        path.to_str().ok_or_else(|| {
279            syn::Error::new(input.schema.span(), "schema path must be valid UTF-8")
280        })?,
281        input.schema.span(),
282    );
283    Ok(quote! {
284        const _: &str = include_str!(#tracked_path);
285        #generated
286    })
287}
288
289/// Bind inline Unionid queries against a declarative schema and generate typed
290/// Rust models, parameters, result rows, and execution functions.
291#[proc_macro]
292pub fn queries(input: TokenStream) -> TokenStream {
293    let input = parse_macro_input!(input as QueriesInput);
294    expand(input)
295        .unwrap_or_else(syn::Error::into_compile_error)
296        .into()
297}