assert-struct 0.4.2

A procedural macro for ergonomic structural assertions in tests
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
//! Error types and formatting for assert_struct macro failures.

use std::collections::HashMap;
use std::fmt;
use std::path::PathBuf;
use std::sync::{Arc, LazyLock, RwLock};

use annotate_snippets::{AnnotationKind, Level, Renderer, Snippet};

thread_local! {
    static PLAIN_OUTPUT: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
}

/// RAII guard that forces plain (non-colored) `ErrorReport` output on the current thread.
///
/// Intended for test utilities that capture panic messages and compare them as strings.
/// Dropping the guard restores colored output.
#[doc(hidden)]
pub struct PlainOutputGuard;

impl Default for PlainOutputGuard {
    fn default() -> Self {
        Self::new()
    }
}

impl PlainOutputGuard {
    pub fn new() -> Self {
        PLAIN_OUTPUT.with(|c| c.set(true));
        PlainOutputGuard
    }
}

impl Drop for PlainOutputGuard {
    fn drop(&mut self) {
        PLAIN_OUTPUT.with(|c| c.set(false));
    }
}

/// Global cache of source file contents, keyed by absolute path.
/// Shared across all `assert_struct!` failures in a test binary so each
/// file is read at most once regardless of how many assertions fail.
static SOURCE_CACHE: LazyLock<RwLock<HashMap<PathBuf, Arc<str>>>> =
    LazyLock::new(|| RwLock::new(HashMap::new()));

fn cached_source(path: &PathBuf) -> Option<Arc<str>> {
    // Fast path: already cached.
    if let Ok(cache) = SOURCE_CACHE.read() {
        if let Some(content) = cache.get(path) {
            return Some(content.clone());
        }
    }
    // Slow path: read file and populate cache.
    let content: Arc<str> = std::fs::read_to_string(path).ok()?.into();
    if let Ok(mut cache) = SOURCE_CACHE.write() {
        cache.entry(path.clone()).or_insert_with(|| content.clone());
    }
    Some(content)
}

/// Derive the absolute source file path from two compile-time constants:
/// - `manifest_dir`: value of `env!("CARGO_MANIFEST_DIR")` — absolute path to the package root
/// - `file_path`: value of `file!()` — path relative to the workspace root
///
/// In a Rust workspace, `file!()` is workspace-root-relative while `CARGO_MANIFEST_DIR`
/// is package-root-absolute. The package dir name(s) appear as a suffix of `manifest_dir`
/// and as a matching prefix of `file_path`. By stripping that overlap we get the workspace
/// root, then join with `file_path` for a fully absolute path.
///
/// Example (flat workspace):
///   manifest_dir = /workspace/my-crate
///   file_path    = my-crate/src/lib.rs
///   overlap      = my-crate  →  workspace root = /workspace
///   result       = /workspace/my-crate/src/lib.rs
///
/// Works for nested members too (overlap spans multiple path components).
fn absolute_source_path(manifest_dir: &str, file_path: &str) -> PathBuf {
    use std::path::Path;

    let manifest = Path::new(manifest_dir);
    let file = Path::new(file_path);

    // Collect path components for each side.
    let manifest_components: Vec<_> = manifest.components().collect();
    let file_components: Vec<_> = file.components().collect();

    // Find the longest suffix of manifest_components that matches a prefix of file_components.
    let mut overlap = 0;
    for len in 1..=manifest_components.len().min(file_components.len()) {
        let suffix = &manifest_components[manifest_components.len() - len..];
        let prefix = &file_components[..len];
        if suffix == prefix {
            overlap = len;
        }
    }

    // Workspace root = manifest_dir minus the overlapping suffix.
    let workspace_root: PathBuf = manifest_components[..manifest_components.len() - overlap]
        .iter()
        .collect();

    workspace_root.join(file)
}

/// Compute the byte offset of a (line, col) position within a source string.
/// `line` is 1-indexed; `col` is 0-indexed (as returned by proc_macro2's span locations).
/// Returns 0 when `line` is 0 (synthetic span with no real source location).
fn byte_offset_of(source: &str, line: u32, col: u32) -> usize {
    if line == 0 {
        return 0;
    }
    let line_start: usize = source
        .split('\n')
        .take((line - 1) as usize)
        .map(|l| l.len() + 1) // +1 for the '\n'
        .sum();
    (line_start + col as usize).min(source.len())
}

/// Context information for a failed assertion.
#[derive(Debug, Clone)]
#[allow(dead_code)]
struct ErrorContext {
    actual_value: String,
    /// For equality patterns where we need to show the expected value
    expected_value: Option<String>,
    /// The specific pattern node that failed
    error_node: &'static PatternNode,
}

/// Collected assertion errors for reporting.
#[derive(Debug)]
pub struct ErrorReport {
    errors: Vec<ErrorContext>,
    /// Absolute path used to read the file from disk.
    abs_path: PathBuf,
    /// Workspace-relative path used for display (the raw `file!()` value).
    rel_path: String,
}

/// Tree-based pattern representation, generated by the macro at compile time.
pub struct PatternNode {
    pub kind: NodeKind,
    pub parent: Option<&'static PatternNode>,
    /// 1-indexed line of the first character of this pattern in source.
    pub line_start: u32,
    /// 0-indexed column of the first character of this pattern in source.
    pub col_start: u32,
    /// 1-indexed line of the last character of this pattern in source.
    pub line_end: u32,
    /// 0-indexed column one past the last character of this pattern in source.
    pub col_end: u32,
}

/// The kind of pattern node.
#[derive(Debug)]
pub enum NodeKind {
    // Collection patterns
    Slice {
        items: &'static [&'static PatternNode],
        rest: bool,
    },
    Set {
        items: &'static [&'static PatternNode],
        rest: bool,
    },
    Tuple {
        items: &'static [&'static PatternNode],
    },
    Map {
        entries: &'static [(&'static str, &'static PatternNode)],
        rest: bool,
    },
    Struct {
        name: &'static str,
        fields: &'static [(&'static str, &'static PatternNode)],
        rest: bool,
    },

    // Enum patterns
    EnumVariant {
        path: &'static str,
        args: Option<&'static [&'static PatternNode]>,
    },

    // Leaf patterns
    Simple {
        value: &'static str,
    },
    Comparison {
        op: ComparisonOp,
        value: &'static str,
    },
    Range {
        pattern: &'static str,
    },
    Regex {
        pattern: &'static str,
    },
    Like {
        expr: &'static str,
    },

    // Special
    Wildcard,
    Closure {
        closure: &'static str,
    },
}

/// Comparison operators used in patterns.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ComparisonOp {
    Less,
    LessEqual,
    Greater,
    GreaterEqual,
    Equal,
    NotEqual,
}

impl ComparisonOp {
    /// Get the string representation of this operator
    pub fn as_str(&self) -> &'static str {
        match self {
            ComparisonOp::Less => "<",
            ComparisonOp::LessEqual => "<=",
            ComparisonOp::Greater => ">",
            ComparisonOp::GreaterEqual => ">=",
            ComparisonOp::Equal => "==",
            ComparisonOp::NotEqual => "!=",
        }
    }
}

impl ErrorReport {
    pub fn new(manifest_dir: &str, file_path: &str) -> Self {
        ErrorReport {
            errors: Vec::new(),
            abs_path: absolute_source_path(manifest_dir, file_path),
            rel_path: file_path.to_string(),
        }
    }

    /// Create a disposable probe report used during set-pattern backtracking.
    /// The report is never displayed; callers check `is_empty()` to determine
    /// whether a trial pattern assertion succeeded.
    pub fn new_probe() -> Self {
        ErrorReport {
            errors: Vec::new(),
            abs_path: PathBuf::new(),
            rel_path: String::new(),
        }
    }

    pub fn is_empty(&self) -> bool {
        self.errors.is_empty()
    }

    pub fn push(
        &mut self,
        error_node: &'static PatternNode,
        actual: String,
        expected: Option<String>,
    ) {
        self.errors.push(ErrorContext {
            actual_value: actual,
            expected_value: expected,
            error_node,
        });
    }
}

/// Build a human-readable annotation label for a failed assertion.
fn error_label(error: &ErrorContext) -> String {
    match &error.error_node.kind {
        NodeKind::Comparison {
            op: ComparisonOp::Equal,
            ..
        } => format!(
            "expected {}, got {}",
            error.expected_value.as_deref().unwrap_or("?"),
            error.actual_value,
        ),
        NodeKind::EnumVariant { .. } => format!(
            "expected variant {}, got {}",
            error.error_node, error.actual_value,
        ),
        NodeKind::Slice { items, rest } => {
            if *rest {
                format!("slice pattern mismatch, got {}", error.actual_value)
            } else {
                let n = items.len();
                let suffix = if n == 1 { "element" } else { "elements" };
                format!(
                    "expected slice with {} {}, got {}",
                    n, suffix, error.actual_value
                )
            }
        }
        NodeKind::Set { rest, .. } => {
            if *rest {
                format!("set pattern mismatch, got {}", error.actual_value)
            } else {
                format!("set pattern mismatch (exact), got {}", error.actual_value)
            }
        }
        NodeKind::Closure { .. } => format!(
            "closure condition not satisfied, got {}",
            error.actual_value,
        ),
        _ => format!("got {}", error.actual_value),
    }
}

impl fmt::Display for ErrorReport {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        if self.errors.is_empty() {
            return Ok(());
        }

        let source_content = cached_source(&self.abs_path);

        // Pre-compute labels so their lifetimes outlive the report construction.
        let labels: Vec<String> = self.errors.iter().map(error_label).collect();

        let renderer = if PLAIN_OUTPUT.with(|c| c.get())
            || std::env::var_os("NO_COLOR").is_some()
            || !std::io::IsTerminal::is_terminal(&std::io::stderr())
        {
            Renderer::plain()
        } else {
            Renderer::styled()
        };

        if let Some(source) = &source_content {
            let annotations: Vec<_> = self
                .errors
                .iter()
                .zip(labels.iter())
                .map(|(error, label)| {
                    let start = byte_offset_of(
                        source,
                        error.error_node.line_start,
                        error.error_node.col_start,
                    );
                    let end =
                        byte_offset_of(source, error.error_node.line_end, error.error_node.col_end)
                            .max(start + 1);
                    AnnotationKind::Primary
                        .span(start..end)
                        .label(label.as_str())
                })
                .collect();

            let snippet = Snippet::source(&**source)
                .line_start(1)
                .path(&self.rel_path)
                .annotations(annotations);

            let report = Level::ERROR
                .primary_title("assert_struct! failed")
                .element(snippet);

            write!(f, "{}", renderer.render(&[report]))?;
        } else {
            // Fallback when the source file cannot be read: show location + description.
            write!(f, "assert_struct! failed:")?;
            for (error, label) in self.errors.iter().zip(labels.iter()) {
                write!(
                    f,
                    "\n  --> {}:{}\n  {label}",
                    self.rel_path, error.error_node.line_start
                )?;
            }
        }

        Ok(())
    }
}

impl fmt::Debug for PatternNode {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("PatternNode")
            .field("kind", &self.kind)
            .field("parent", &self.parent.map(|_| "<parent>"))
            .field("line_start", &self.line_start)
            .field("col_start", &self.col_start)
            .field("line_end", &self.line_end)
            .field("col_end", &self.col_end)
            .finish()
    }
}

impl fmt::Display for PatternNode {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match &self.kind {
            NodeKind::Struct { name, .. } => write!(f, "{} {{ ... }}", name),
            NodeKind::Slice { .. } => write!(f, "[...]"),
            NodeKind::Set { .. } => write!(f, "#(...)"),
            NodeKind::Tuple { items } => write!(f, "({})", ".., ".repeat(items.len())),
            NodeKind::Map { entries, .. } => write!(f, "#{{ {} entries }}", entries.len()),
            NodeKind::EnumVariant { path, args } => {
                if args.is_some() {
                    write!(f, "{}(...)", path)
                } else {
                    write!(f, "{}", path)
                }
            }
            NodeKind::Simple { value } => write!(f, "{}", value),
            NodeKind::Comparison { op, value } => write!(f, "{} {}", op.as_str(), value),
            NodeKind::Range { pattern } => write!(f, "{}", pattern),
            NodeKind::Regex { pattern } => write!(f, "=~ {}", pattern),
            NodeKind::Like { expr } => write!(f, "=~ {}", expr),
            NodeKind::Wildcard => write!(f, "_"),
            NodeKind::Closure { closure } => write!(f, "{}", closure),
        }
    }
}