Skip to main content

shallguard_macros/
lib.rs

1//! Implementation of ShallGuard's requirement-traceability anchor macros.
2//!
3//! A repository keeps numbered system requirements (`REQ-<AREA>-<NNN>`,
4//! e.g. `REQ-HRS-002`) in its configured requirements documents. These
5//! attributes anchor code and tests to those requirements so the link
6//! between document and implementation is machine-checkable instead of
7//! living only in developers' heads:
8//!
9//! Consumers use these macros through the `shallguard` crate's public
10//! namespace; they do not need to depend on this implementation crate.
11//!
12//! - [`macro@enforces`] marks an item as an enforcement site of one or
13//!   more requirements — "this code exists because this contract exists".
14//! - [`macro@verifies`] marks a test as verification evidence for one or
15//!   more requirements — it backs a `✅` entry in a requirement's
16//!   *Verified:* line.
17//!
18//! All anchor forms are compile-time no-ops: the annotated item is
19//! emitted unchanged and nothing is added at runtime. What the macros do
20//! check, at compile time, is the anchor itself — a malformed or
21//! duplicated requirement ID is a build error, so typos cannot survive
22//! as dead anchors. Whether a well-formed ID actually exists in the
23//! requirements documents is deliberately out of scope here (a macro
24//! cannot detect *missing* anchors either); that is the job of the
25//! external ShallGuard checker, which scans anchors syntactically.
26//! Comments are never anchors.
27//!
28//! Placement conventions:
29//!
30//! - `#[shallguard::enforces]` attaches to items — and, inside a struct or enum
31//!   that itself carries `#[shallguard::enforces]` (with IDs, or bare as a
32//!   container marker), to individual fields and variants: the container
33//!   attribute validates and strips the field-level anchors before the compiler
34//!   or any derive sees them.
35//! - A contract living on a specific branch, match arm, or statement is
36//!   anchored with the statement-position `shallguard::enforces_here!` macro,
37//!   which expands to nothing.
38//! - `#[shallguard::verifies]` goes on test functions only, above the `#[test]` /
39//!   `#[tokio::test]` attribute; it rejects non-test placements and
40//!   `#[ignore]`d tests at compile time.
41//! - The relation is many-to-many: one item may enforce several
42//!   requirements, and one requirement may be enforced or verified at
43//!   several sites.
44//!
45//! ```
46//! # use shallguard_macros as shallguard;
47//!
48//! #[shallguard::enforces("REQ-RD-006", "REQ-RD-007")]
49//! fn resolve_identity_claim() {}
50//!
51//! #[shallguard::verifies("REQ-RD-006")]
52//! #[test]
53//! fn req_rd_006_exact_worker_claim_wins() {}
54//! ```
55//!
56//! Malformed IDs and invalid placements fail the build:
57//!
58//! ```compile_fail
59//! # use shallguard_macros as shallguard;
60//!
61//! #[shallguard::enforces("REQ-hrs-2")]
62//! fn broken() {}
63//! ```
64//!
65//! ```compile_fail
66//! # use shallguard_macros as shallguard;
67//!
68//! #[shallguard::verifies()]
69//! fn missing_id() {}
70//! ```
71//!
72//! ```compile_fail
73//! # use shallguard_macros as shallguard;
74//!
75//! // Not a test function.
76//! #[shallguard::verifies("REQ-RD-006")]
77//! fn not_a_test() {}
78//! ```
79//!
80//! ```compile_fail
81//! # use shallguard_macros as shallguard;
82//!
83//! // Not a function at all.
84//! #[shallguard::verifies("REQ-RD-006")]
85//! struct NotAFunction;
86//! ```
87//!
88//! ```compile_fail
89//! # use shallguard_macros as shallguard;
90//!
91//! // Ignored tests are not evidence.
92//! #[shallguard::verifies("REQ-RD-006")]
93//! #[test]
94//! #[ignore]
95//! fn ignored_test() {}
96//! ```
97
98// The crate-level doctest shows #[shallguard::verifies] above #[test] — the real
99// usage — which trips clippy's test_attr_in_doctest; the example is
100// illustrative, not an executed unit test.
101#![allow(clippy::test_attr_in_doctest)]
102
103use proc_macro::TokenStream;
104use proc_macro2::Span;
105use quote::quote;
106use syn::parse::Parser;
107use syn::punctuated::Punctuated;
108use syn::{LitStr, Token};
109
110/// Marks an item as an enforcement site of the listed requirements.
111///
112/// Takes one or more requirement IDs as string literals. Expands to the
113/// item unchanged; the IDs are validated for form (`REQ-<AREA>-<NNN>`)
114/// and uniqueness at compile time.
115///
116/// On a struct or enum, individual fields and variants may carry their
117/// own `#[shallguard::enforces("REQ-...")]` anchors; this container attribute
118/// validates them and strips them from the emitted item (so derives and
119/// the compiler never see them). In that case the container attribute
120/// itself may be bare — `#[shallguard::enforces]` — acting purely as the marker
121/// that enables field-level anchors.
122#[proc_macro_attribute]
123pub fn enforces(args: TokenStream, item: TokenStream) -> TokenStream {
124    match syn::parse::<syn::Item>(item.clone()) {
125        Ok(syn::Item::Struct(mut s)) => {
126            let mut errors = proc_macro2::TokenStream::new();
127            let field_anchors = strip_field_anchors(s.fields.iter_mut(), &mut errors);
128            validate_container_args(args, field_anchors, &mut errors);
129            quote! { #errors #s }.into()
130        }
131        Ok(syn::Item::Enum(mut e)) => {
132            let mut errors = proc_macro2::TokenStream::new();
133            let mut field_anchors = 0;
134            for variant in &mut e.variants {
135                field_anchors += strip_anchor_attrs(&mut variant.attrs, &mut errors);
136                field_anchors += strip_field_anchors(variant.fields.iter_mut(), &mut errors);
137            }
138            validate_container_args(args, field_anchors, &mut errors);
139            quote! { #errors #e }.into()
140        }
141        _ => anchor("enforces", args, item),
142    }
143}
144
145/// Statement-position enforcement anchor: marks the surrounding branch,
146/// match arm, or statement sequence as an enforcement site of the listed
147/// requirements. Expands to nothing; the IDs are validated for form and
148/// uniqueness at compile time exactly like [`macro@enforces`].
149///
150/// ```
151/// # use shallguard_macros as shallguard;
152///
153/// fn floor(configured: usize) -> usize {
154///     shallguard::enforces_here!("REQ-HRS-002");
155///     configured.max(1)
156/// }
157/// ```
158#[proc_macro]
159pub fn enforces_here(input: TokenStream) -> TokenStream {
160    let mut errors = proc_macro2::TokenStream::new();
161    validate_id_list("enforces_here", input, false, &mut errors);
162    errors.into()
163}
164
165/// Validates the ID arguments of a container-level `#[shallguard::enforces]`:
166/// bare is allowed only when field-level anchors exist, IDs are validated as
167/// usual.
168fn validate_container_args(
169    args: TokenStream,
170    field_anchors: usize,
171    errors: &mut proc_macro2::TokenStream,
172) {
173    validate_id_list("enforces", args, field_anchors > 0, errors);
174}
175
176/// Strips `#[shallguard::enforces(...)]` anchors off every field in the
177/// iterator, validating their IDs; returns how many anchors were stripped.
178fn strip_field_anchors<'a>(
179    fields: impl Iterator<Item = &'a mut syn::Field>,
180    errors: &mut proc_macro2::TokenStream,
181) -> usize {
182    fields
183        .map(|field| strip_anchor_attrs(&mut field.attrs, errors))
184        .sum()
185}
186
187/// Strips `#[shallguard::enforces(...)]` attributes from an attribute list,
188/// validating each stripped anchor's IDs; `#[shallguard::verifies]` here is an
189/// error.
190/// Returns the number of stripped enforcement anchors.
191fn strip_anchor_attrs(
192    attrs: &mut Vec<syn::Attribute>,
193    errors: &mut proc_macro2::TokenStream,
194) -> usize {
195    let mut stripped = 0;
196    attrs.retain(|attr| {
197        let name = attr.path().segments.last().map(|s| s.ident.to_string());
198        match name.as_deref() {
199            Some("enforces") => {
200                match &attr.meta {
201                    syn::Meta::List(list) => {
202                        validate_id_list("enforces", list.tokens.clone().into(), false, errors);
203                    }
204                    _ => errors.extend(
205                        syn::Error::new_spanned(
206                            attr,
207                            "field-level #[shallguard::enforces] needs at least one requirement ID",
208                        )
209                        .to_compile_error(),
210                    ),
211                }
212                stripped += 1;
213                false
214            }
215            Some("verifies") => {
216                errors.extend(
217                    syn::Error::new_spanned(
218                        attr,
219                        "#[shallguard::verifies] applies only to test functions; \
220                         use #[shallguard::enforces] for enforcement sites",
221                    )
222                    .to_compile_error(),
223                );
224                false
225            }
226            _ => true,
227        }
228    });
229    stripped
230}
231
232/// Parses a comma-separated list of string-literal requirement IDs and
233/// validates form and uniqueness. An empty list is an error unless
234/// `allow_empty`.
235fn validate_id_list(
236    name: &str,
237    args: TokenStream,
238    allow_empty: bool,
239    errors: &mut proc_macro2::TokenStream,
240) {
241    match Punctuated::<LitStr, Token![,]>::parse_terminated.parse(args) {
242        Ok(ids) if ids.is_empty() => {
243            if !allow_empty {
244                let msg = format!(
245                    "{name} needs at least one requirement ID, \
246                     e.g. {name}(\"REQ-HRS-002\")"
247                );
248                errors.extend(syn::Error::new(Span::call_site(), msg).to_compile_error());
249            }
250        }
251        Ok(ids) => {
252            let mut seen = std::collections::HashSet::new();
253            for lit in &ids {
254                let id = lit.value();
255                if let Err(msg) = validate_req_id(&id) {
256                    errors.extend(syn::Error::new(lit.span(), msg).to_compile_error());
257                } else if !seen.insert(id) {
258                    let msg = format!("duplicate requirement ID {:?}", lit.value());
259                    errors.extend(syn::Error::new(lit.span(), msg).to_compile_error());
260                }
261            }
262        }
263        Err(err) => errors.extend(err.to_compile_error()),
264    }
265}
266
267/// Marks a test as verification evidence for the listed requirements.
268///
269/// Takes one or more requirement IDs as string literals. Expands to the
270/// item unchanged. At compile time it validates the IDs for form
271/// (`REQ-<AREA>-<NNN>`) and uniqueness, and validates the placement:
272/// the item must be a function carrying a recognized test attribute
273/// (`#[test]`, `#[tokio::test]`, or any attribute whose path ends in
274/// `test`) and must not be `#[ignore]`d — evidence that does not run is
275/// not evidence.
276#[proc_macro_attribute]
277pub fn verifies(args: TokenStream, item: TokenStream) -> TokenStream {
278    let mut errors = proc_macro2::TokenStream::new();
279    match syn::parse::<syn::Item>(item.clone()) {
280        Ok(syn::Item::Fn(fun)) => {
281            let is_test = fun.attrs.iter().any(|attr| {
282                attr.path()
283                    .segments
284                    .last()
285                    .is_some_and(|segment| segment.ident == "test")
286            });
287            let is_ignored = fun.attrs.iter().any(|attr| attr.path().is_ident("ignore"));
288            if !is_test {
289                errors.extend(
290                    syn::Error::new_spanned(
291                        &fun.sig.ident,
292                        "#[shallguard::verifies] requires a test function: add #[test] / \
293                         #[tokio::test] below the anchor, or remove the anchor",
294                    )
295                    .to_compile_error(),
296                );
297            }
298            if is_ignored {
299                errors.extend(
300                    syn::Error::new_spanned(
301                        &fun.sig.ident,
302                        "#[shallguard::verifies] must not be placed on an #[ignore]d test: \
303                         evidence that does not run is not evidence",
304                    )
305                    .to_compile_error(),
306                );
307            }
308        }
309        Ok(other) => {
310            errors.extend(
311                syn::Error::new_spanned(
312                    &other,
313                    "#[shallguard::verifies] applies only to test functions; \
314                     use #[shallguard::enforces] for enforcement sites",
315                )
316                .to_compile_error(),
317            );
318        }
319        Err(err) => errors.extend(err.to_compile_error()),
320    }
321    let validated = anchor("verifies", args, item);
322    let mut out: proc_macro2::TokenStream = errors;
323    out.extend(proc_macro2::TokenStream::from(validated));
324    out.into()
325}
326
327fn anchor(name: &str, args: TokenStream, item: TokenStream) -> TokenStream {
328    let mut errors = proc_macro2::TokenStream::new();
329    validate_id_list(&format!("#[{name}]"), args, false, &mut errors);
330    let item = proc_macro2::TokenStream::from(item);
331    quote! { #errors #item }.into()
332}
333
334/// Checks the `REQ-<AREA>-<NNN>` form: `AREA` is two or more uppercase
335/// ASCII letters, `NNN` is exactly three ASCII digits.
336///
337/// Only the form is checked here. Existence in the requirements documents
338/// is the external checker's job — validating it in the macro would couple
339/// every `cargo build` to the doc files.
340fn validate_req_id(id: &str) -> Result<(), String> {
341    let bad = || {
342        format!(
343            "{id:?} is not a valid requirement ID \
344             (expected REQ-<AREA>-<NNN>, e.g. \"REQ-HRS-002\")"
345        )
346    };
347    let rest = id.strip_prefix("REQ-").ok_or_else(bad)?;
348    let (area, num) = rest.split_once('-').ok_or_else(bad)?;
349    if area.len() >= 2
350        && area.bytes().all(|b| b.is_ascii_uppercase())
351        && num.len() == 3
352        && num.bytes().all(|b| b.is_ascii_digit())
353    {
354        Ok(())
355    } else {
356        Err(bad())
357    }
358}
359
360#[cfg(test)]
361mod tests {
362    use super::validate_req_id;
363
364    #[test]
365    fn accepts_known_area_shapes() {
366        for id in [
367            "REQ-RD-001",
368            "REQ-HRS-002",
369            "REQ-SAFE-010",
370            "REQ-PERF-025",
371            "REQ-AUTH-029",
372        ] {
373            assert!(validate_req_id(id).is_ok(), "{id} should be valid");
374        }
375    }
376
377    #[test]
378    fn rejects_malformed_ids() {
379        for id in [
380            "",
381            "REQ-",
382            "REQ-HRS",
383            "REQ-HRS-",
384            "REQ-HRS-2",    // number must be three digits
385            "REQ-HRS-0002", // number must be three digits
386            "REQ-hrs-002",  // area must be uppercase
387            "REQ-H-002",    // area must be at least two letters
388            "REQ-HRS-00X",  // number must be digits
389            "req-HRS-002",  // prefix is case-sensitive
390            "REQHRS-002",
391            "HRS-002",
392            "REQ-HRS-002 ", // no surrounding whitespace
393        ] {
394            assert!(validate_req_id(id).is_err(), "{id:?} should be rejected");
395        }
396    }
397}