Skip to main content

cel_rs_macros/
lib.rs

1//! Procedural macros for the cel-rs crate.
2//!
3//! This crate provides procedural macros for working with CEL (Common Expression Language)
4//! expressions in Rust. It includes macros for validating CEL expressions at compile time
5//! and debugging token parsing.
6//!
7//! # Examples
8//!
9//! ## Validating CEL expressions
10//!
11//! ```rust
12//! use cel_rs_macros::expression;
13//!
14//! // This will compile only if the expression is valid CEL
15//! expression! {
16//!     54 + 25 * (11 + 6 * 6)
17//! };
18//! ```
19//!
20//! ## Debugging token parsing
21//!
22//! ```rust
23//! use cel_rs_macros::print_tokens;
24//!
25//! // This will print the parsed tokens to stdout during compilation
26//! print_tokens! {
27//!     10 + 20
28//! };
29//! ```
30
31use cel_parser::{CELParser, OpLookup};
32use proc_macro::TokenStream as ProcMacroTokenStream;
33use proc_macro2::{Literal, TokenStream};
34use quote::{quote, quote_spanned};
35
36/// Validates that the input contains a valid CEL expression.
37///
38/// Emits no code on success and a spanned compiler diagnostic on invalid input.
39///
40/// - Complexity: Includes the parser's time and temporary storage for the input.
41///
42/// # Examples
43/// ```rust
44/// use cel_rs_macros::expression;
45/// expression! {
46///     54 + 25 * (11 + 6 * 6)
47/// };
48/// ```
49#[proc_macro]
50pub fn expression(input: ProcMacroTokenStream) -> ProcMacroTokenStream {
51    expression_tokens(input.into()).into()
52}
53
54/// Returns no tokens for valid CEL, or spanned compile errors for invalid CEL.
55///
56/// - Complexity: Includes the parser's time and temporary storage for the input.
57fn expression_tokens(input: TokenStream) -> TokenStream {
58    let mut parser = CELParser::new(OpLookup::new());
59    match parser.parse_tokens(input.into_iter()) {
60        Ok(_) => TokenStream::new(),
61        Err(e) => {
62            let msg_lit = Literal::string(e.message());
63            let start_error = quote_spanned!(e.span() => compile_error!(#msg_lit));
64            if let Some(end) = e.end_span() {
65                // Intentional second diagnostic at the expression end span. A single merged
66                // underline requires `Span::join()`, which is not stable; until then we emit
67                // two `compile_error!` invocations so both start and end locations are reported.
68                let end_lit = Literal::string("expression continues here");
69                let end_error = quote_spanned!(end => compile_error!(#end_lit));
70                // Two bare compile_error!() are not valid in expression context;
71                // wrapping in a block makes the expansion a valid block expression
72                // while still causing the compiler to expand both invocations.
73                quote!({ #start_error; #end_error })
74            } else {
75                start_error
76            }
77        }
78    }
79}
80
81/// Prints the tokens for debugging purposes.
82///
83/// Prints the source to stdout and top-level token kinds to stderr, then emits no code.
84///
85/// - Complexity: O(n) formatting time and output for n debug-representation bytes.
86///
87/// # Examples
88/// ```rust
89/// use cel_rs_macros::print_tokens;
90/// print_tokens! {
91///     "hello"_key
92/// };
93/// ```
94#[proc_macro]
95pub fn print_tokens(input: ProcMacroTokenStream) -> ProcMacroTokenStream {
96    println!("{input}");
97    write_token_kinds(input.into(), std::io::stderr().lock())
98        .expect("failed to print CEL token kinds");
99    ProcMacroTokenStream::new()
100}
101
102/// Writes top-level token kinds and their debug representations in source order.
103///
104/// - Complexity: O(n) formatting time and output for n debug-representation bytes.
105///
106/// # Errors
107/// Returns an error when the destination cannot accept the diagnostic output.
108fn write_token_kinds(input: TokenStream, mut output: impl std::io::Write) -> std::io::Result<()> {
109    for e in input {
110        match e {
111            proc_macro2::TokenTree::Punct(punct) => {
112                writeln!(output, "punct: {punct:?}")?;
113            }
114            proc_macro2::TokenTree::Ident(ident) => {
115                writeln!(output, "ident: {ident:?}")?;
116            }
117            proc_macro2::TokenTree::Group(group) => {
118                writeln!(output, "group: {group:?}")?;
119            }
120            proc_macro2::TokenTree::Literal(lit) => {
121                writeln!(output, "literal: {lit:?}")?;
122            }
123        }
124    }
125    Ok(())
126}
127
128#[cfg(test)]
129mod tests {
130    use super::*;
131
132    /// Validates expressions without generating executable runtime code.
133    #[test]
134    fn valid_expression_emits_no_tokens() {
135        assert!(expression_tokens("54 + 25 * (11 + 6 * 6)".parse().unwrap()).is_empty());
136    }
137
138    /// Reports malformed, undefined and ill-typed input through compile-error expansions.
139    #[test]
140    fn invalid_expressions_emit_compiler_diagnostics() {
141        for source in ["54 +", "missing_name", "1 + true"] {
142            let expansion = expression_tokens(source.parse().unwrap()).to_string();
143            assert!(expansion.contains("compile_error"), "{source}: {expansion}");
144        }
145    }
146
147    /// Writes each top-level token kind in source order without flattening groups.
148    #[test]
149    fn token_kind_diagnostics() {
150        let mut output = Vec::new();
151        write_token_kinds("name + (42) \"text\"".parse().unwrap(), &mut output).unwrap();
152        let output = String::from_utf8(output).unwrap();
153        let kinds: Vec<_> = output
154            .lines()
155            .map(|line| line.split_once(':').unwrap().0)
156            .collect();
157        assert_eq!(kinds, ["ident", "punct", "group", "literal"]);
158        let mut empty = Vec::new();
159        write_token_kinds(TokenStream::new(), &mut empty).unwrap();
160        assert!(empty.is_empty());
161    }
162
163    /// Reports an output failure instead of silently omitting token diagnostics.
164    #[test]
165    fn token_kind_output_error() {
166        let mut buffer = [];
167        let output = std::io::Cursor::new(&mut buffer[..]);
168        assert!(write_token_kinds("name".parse().unwrap(), output).is_err());
169    }
170}