comperr 1.0.0

A minimal, lightweight crate for emitting span-accurate compile-time errors from procedural macros.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
//! # comperr
//!
//! A minimal crate, backed by a single dependency (`proc_macro2`), for emitting
//! span-accurate compile-time errors from procedural macros.
//!
//! ## Overview
//!
//! When writing proc-macros, you often need to emit a `compile_error!` that
//! points at a specific location in the user's source code, but you don't want to
//! bloat compilation time by pulling in a massive crate.
//!
//! The naive approach of formatting a string and calling `.parse()` loses the span
//! entirely, because tokens born from a string have no source location. `comperr`
//! constructs the error `TokenStream` token by token, attaching the correct
//! [`Span`] to each one so the compiler diagnostic lands exactly where you
//! want it.
//!
//! ## Usage
//!
//! One-shot with the free function:
//!
//! ```ignore
//! use proc_macro2::{Span, TokenStream};
//!
//! pub fn my_macro(input: TokenStream) -> TokenStream {
//!     return comperr::error(Span::call_site(), "something went wrong");
//! }
//! ```
//!
//! Or using the [`Error`] struct directly:
//!
//! ```ignore
//! use proc_macro2::{Span, TokenStream};
//!
//! pub fn my_macro(input: TokenStream) -> TokenStream {
//!     let e = comperr::Error::new(Span::call_site(), "something went wrong");
//!     return e.to_compile_error();
//! }
//! ```
//!
//! Accumulating errors across a validation loop:
//!
//! ```ignore
//! use comperr::Error;
//! use proc_macro2::{Span, TokenStream};
//!
//! pub fn my_macro(input: TokenStream) -> TokenStream {
//!     let mut errors = Error::empty();
//!     // validate items, combining any errors as you go
//!     for item in parse_items(&input) {
//!         if let Err(e) = validate(item) {
//!             errors.combine(e);
//!         }
//!     }
//!     if !errors.is_empty() {
//!         return errors.to_compile_error();
//!     }
//!     // emit normal output
//!     TokenStream::new()
//! }
//! ```
//!
//! Collecting errors from an iterator:
//!
//! ```ignore
//! use comperr::Error;
//!
//! let combined: Error = items
//!     .iter()
//!     .filter_map(|item| validate(item).err())
//!     .collect();
//! if !combined.is_empty() {
//!     return combined.to_compile_error();
//! }
//! ```
//!
//! ## How It Works
//!
//! Every token in a `TokenStream` carries a [`Span`] that tells the compiler
//! where in the source code that token came from. When `compile_error!` is
//! invoked, the compiler reads the span off the tokens it receives and uses
//! that to place the diagnostic. By constructing each token manually and
//! calling `.set_span()` on it, the resulting error points at the original
//! source location rather than at a meaningless internal position.
//!
//! ## Performance
//!
//! All work happens at compile time during macro expansion.
//! There is no runtime overhead in your final binary.

#![warn(missing_docs)]

use proc_macro2::{Delimiter, Group, Ident, Literal, Punct, Spacing, Span, TokenStream, TokenTree};
use std::fmt;

/// A compile-time error tied to a source location.
///
/// Construct one with [`Error::new`] and convert it to a [`TokenStream`] with
/// [`Error::to_compile_error`], or use the [`error`] free function for the
/// common one-shot case.
///
/// Multiple errors can be batched together with [`Error::combine`] or by
/// collecting an iterator via [`FromIterator`]. An empty accumulator can be
/// created with [`Error::empty`] and checked with [`Error::is_empty`].
///
/// # Example
///
/// ```ignore
/// use comperr::Error;
/// use proc_macro2::Span;
///
/// let e = Error::new(Span::call_site(), "something went wrong");
/// let ts = e.to_compile_error();
/// ```
#[derive(Debug, Clone)]
pub struct Error {
    inner: Option<(Span, String)>,
    overflow: Option<Vec<(Span, String)>>,
}

impl Error {
    /// Creates a new [`Error`] at the given span with the given message.
    ///
    /// The `message` can be any type that implements [`Into<String>`], so both
    /// `&str` and `String` work naturally.
    ///
    /// # Arguments
    ///
    /// - `span`: The source location the error should point at. This is
    ///   typically obtained from a token in the macro input, for example via
    ///   a `Literal::span()` call.
    /// - `message`: A human-readable description of what went wrong.
    ///
    /// # Example
    ///
    /// ```ignore
    /// use comperr::Error;
    /// use proc_macro2::Span;
    ///
    /// let e = Error::new(Span::call_site(), "expected a string literal");
    /// ```
    #[must_use]
    #[inline]
    pub fn new(span: Span, message: impl Into<String>) -> Self {
        Self {
            inner: Some((span, message.into())),
            overflow: None,
        }
    }

    /// Creates an empty [`Error`] containing no messages.
    ///
    /// Use this as a starting point when accumulating errors in a loop via
    /// [`Error::combine`] or [`Error::extend`]. Check whether any errors were
    /// added with [`Error::is_empty`] before returning the token stream.
    ///
    /// An empty error produces an empty [`TokenStream`] from
    /// [`Error::to_compile_error`], which is a no-op when returned from a
    /// proc-macro.
    ///
    /// # Example
    ///
    /// ```ignore
    /// use comperr::Error;
    /// use proc_macro2::Span;
    ///
    /// let mut errors = Error::empty();
    /// // ... accumulate errors ...
    /// if !errors.is_empty() {
    ///     return errors.to_compile_error();
    /// }
    /// ```
    #[must_use]
    #[inline]
    pub fn empty() -> Self {
        Self {
            inner: None,
            overflow: None,
        }
    }

    /// Returns `true` if this error contains no messages.
    ///
    /// Errors created with [`Error::new`] or [`Error::from_token_stream`] are
    /// always non-empty. Only [`Error::empty`] produces an error for which this
    /// returns `true`.
    ///
    /// # Example
    ///
    /// ```ignore
    /// use comperr::Error;
    /// use proc_macro2::Span;
    ///
    /// let mut acc = Error::empty();
    /// assert!(acc.is_empty());
    /// acc.combine(Error::new(Span::call_site(), "oops"));
    /// assert!(!acc.is_empty());
    /// ```
    #[inline]
    #[must_use] 
    pub fn is_empty(&self) -> bool {
        self.inner.is_none()
    }

    /// Converts the error into a [`TokenStream`] containing a `compile_error!`
    /// invocation with the span attached to every token.
    ///
    /// When this [`TokenStream`] is returned from a proc-macro, the Rust
    /// compiler emits a compile error pointing at the original source location
    /// recorded in the span.
    ///
    /// # How the Span Is Preserved
    ///
    /// Each token in the resulting `compile_error!(...)` invocation has its
    /// span set explicitly via `.set_span()`. The tokens carry the span as
    /// attached metadata, and `compile_error!` reads that metadata to place
    /// the diagnostic. This is why the error points at the right location
    /// rather than at an internal or meaningless position.
    ///
    /// # Example
    ///
    /// ```ignore
    /// use comperr::Error;
    /// use proc_macro2::{Span, TokenStream};
    ///
    /// pub fn my_macro(input: TokenStream) -> TokenStream {
    ///     let e = Error::new(Span::call_site(), "something went wrong");
    ///     e.to_compile_error()
    /// }
    /// ```
    #[must_use]
    #[inline]
    pub fn to_compile_error(&self) -> TokenStream {
        let mut tokens = TokenStream::new();
        let iter = self.inner.iter().chain(self.overflow.iter().flatten());
        for (span, msg) in iter {
            let ident = Ident::new("compile_error", *span);
            let mut bang = Punct::new('!', Spacing::Alone);
            bang.set_span(*span);
            let mut lit = Literal::string(msg);
            lit.set_span(*span);
            let mut group = Group::new(Delimiter::Parenthesis, TokenTree::from(lit).into());
            group.set_span(*span);
            let mut semi = Punct::new(';', Spacing::Alone);
            semi.set_span(*span);
            tokens.extend([
                TokenTree::Ident(ident),
                TokenTree::Punct(bang),
                TokenTree::Group(group),
                TokenTree::Punct(semi),
            ]);
        }
        tokens
    }

    /// Combines another error with this one.
    ///
    /// When [`Error::to_compile_error`] is called, all combined errors are
    /// emitted as separate `compile_error!` invocations. If `self` was created
    /// with [`Error::empty`], it adopts `other` as its first message rather
    /// than prepending an empty entry.
    ///
    /// # Example
    ///
    /// ```ignore
    /// use comperr::Error;
    /// use proc_macro2::Span;
    ///
    /// let mut e1 = Error::new(Span::call_site(), "first error");
    /// let e2 = Error::new(Span::call_site(), "second error");
    /// e1.combine(e2);
    /// ```
    #[inline]
    pub fn combine(&mut self, mut other: Self) {
        match (&mut self.inner, other.inner.take()) {
            (Some(_), Some(msg)) => {
                self.overflow.get_or_insert_with(Vec::new).push(msg);
            }
            (inner @ None, Some(msg)) => {
                *inner = Some(msg);
            }
            (_, None) => {}
        }
        if let Some(v) = other.overflow.take() {
            let out = self.overflow.get_or_insert_with(Vec::new);
            out.extend(v);
        }
    }

    /// Reconstructs an [`Error`] from a [`TokenStream`] containing
    /// `compile_error!` invocations.
    ///
    /// This is the inverse of [`Error::to_compile_error`]. It scans the token
    /// stream for `compile_error!("...")` patterns and reconstructs the
    /// [`Error`] with the recorded span and message. Multiple invocations are
    /// combined into a single [`Error`] using [`Error::combine`], so all
    /// diagnostics are preserved.
    ///
    /// The primary use case is receiving a [`TokenStream`] that may already
    /// contain errors produced by a nested macro call or helper crate, and
    /// needing to inspect, log, or re-combine those errors before deciding
    /// whether to re-emit or suppress them.
    ///
    /// If the token stream contains no valid `compile_error!` invocation, a
    /// fallback error with a generic message is returned instead of failing
    /// silently.
    ///
    /// # Known Limitation
    ///
    /// String literals whose original message contained escaped quotes will be
    /// reconstructed with the escaped form (e.g. `\"`) rather than the
    /// original quote character. This is a consequence of reading back the
    /// token's string representation without a full literal parser.
    ///
    /// # Example
    ///
    /// ```ignore
    /// use comperr::Error;
    /// use proc_macro2::Span;
    ///
    /// let original = Error::new(Span::call_site(), "something went wrong");
    /// let ts = original.to_compile_error();
    /// let recovered = Error::from_token_stream(ts);
    /// assert_eq!(recovered.to_string(), "something went wrong");
    /// ```
    #[must_use]
    pub fn from_token_stream(tokens: TokenStream) -> Self {
        let mut combined_error: Option<Self> = None;
        let mut iter = tokens.into_iter().peekable();

        while let Some(token) = iter.next() {
            if let TokenTree::Ident(ident) = &token {
                if ident == "compile_error" {
                    let error_span = ident.span();

                    let has_bang =
                        matches!(iter.next(), Some(TokenTree::Punct(p)) if p.as_char() == '!');

                    if has_bang {
                        if let Some(TokenTree::Group(group)) = iter.next() {
                            let message = Self::extract_message_from_group(&group);
                            let new_error = Self::new(error_span, message);

                            match combined_error.as_mut() {
                                Some(e) => e.combine(new_error),
                                None => combined_error = Some(new_error),
                            }
                        }
                    }
                }
            }
        }

        combined_error.unwrap_or_else(|| {
            Self::new(
                Span::call_site(),
                "An unexpected error occurred during parsing",
            )
        })
    }

    /// Helper to find and clean the string literal inside the macro group.
    fn extract_message_from_group(group: &proc_macro2::Group) -> String {
        group
            .stream()
            .into_iter()
            .find_map(|tt| {
                if let TokenTree::Literal(lit) = tt {
                    let s = lit.to_string();
                    if s.starts_with('"') && s.ends_with('"') {
                        return Some(s[1..s.len() - 1].to_string());
                    }
                }
                None
            })
            .unwrap_or_else(|| "unknown error message".to_string())
    }
}

impl fmt::Display for Error {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let mut first = true;
        for (_, msg) in self.inner.iter().chain(self.overflow.iter().flatten()) {
            if !first {
                f.write_str("\n")?;
            }
            f.write_str(msg)?;
            first = false;
        }
        Ok(())
    }
}

impl std::error::Error for Error {}

impl Extend<Error> for Error {
    fn extend<I: IntoIterator<Item = Error>>(&mut self, iter: I) {
        for err in iter {
            self.combine(err);
        }
    }
}

impl FromIterator<Error> for Error {
    /// Collects an iterator of errors into a single combined [`Error`].
    ///
    /// Collecting an empty iterator produces [`Error::empty`]. Use
    /// [`Error::is_empty`] to check whether any errors were actually gathered
    /// before returning the token stream.
    fn from_iter<I: IntoIterator<Item = Error>>(iter: I) -> Self {
        let mut combined = Error::empty();
        for err in iter {
            combined.combine(err);
        }
        combined
    }
}

/// Emits a span-accurate compile-time error in one call.
///
/// This is a convenience wrapper around [`Error::new`] and
/// [`Error::to_compile_error`]. Use this when you need to emit a single error
/// and return immediately. For more complex cases, use [`Error`] directly.
///
/// # Arguments
///
/// - `span`: The source location the error should point at.
/// - `message`: A human-readable description of what went wrong.
///
/// # Example
///
/// ```ignore
/// use comperr::error;
/// use proc_macro2::{Span, TokenStream};
///
/// pub fn my_macro(input: TokenStream) -> TokenStream {
///     return error(Span::call_site(), "something went wrong");
/// }
/// ```
#[must_use]
#[inline]
pub fn error(span: Span, message: impl Into<String>) -> TokenStream {
    Error::new(span, message).to_compile_error()
}