pre-proc-macro 0.2.1

Procedural marco implementations for [pre](https://crates.io/crates/pre/).
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
//! Defines the different kinds of preconditions.

use proc_macro2::{Span, TokenStream};
use quote::quote;
use std::{cmp::Ordering, fmt};
use syn::{
    ext::IdentExt,
    parenthesized,
    parse::{Parse, ParseStream},
    spanned::Spanned,
    token::Paren,
    Error, Expr, Ident, LitStr, Token,
};

/// The custom keywords used by the precondition kinds.
mod custom_keywords {
    use syn::custom_keyword;

    custom_keyword!(valid_ptr);
    custom_keyword!(proper_align);
    custom_keyword!(r);
    custom_keyword!(w);
}

/// The different kinds of preconditions.
#[derive(Clone)]
pub(crate) enum Precondition {
    /// Requires that the given pointer is valid.
    ValidPtr {
        /// The `valid_ptr` keyword.
        valid_ptr_keyword: custom_keywords::valid_ptr,
        /// The parentheses following the `valid_ptr` keyword.
        parentheses: Paren,
        /// The identifier of the pointer.
        ident: Ident,
        /// The comma between the identifier and the read/write information.
        _comma: Token![,],
        /// Information on what accesses of the pointer must be valid.
        read_write: ReadWrite,
    },
    ProperAlign {
        /// The `proper_align` keyword.
        proper_align_keyword: custom_keywords::proper_align,
        /// The parentheses following the `proper_align` keyword.
        parentheses: Paren,
        /// The identifier of the pointer.
        ident: Ident,
    },
    /// An expression that should evaluate to a boolean value.
    Boolean(Box<Expr>),
    /// A custom precondition that is spelled out in a string.
    Custom(LitStr),
}

impl fmt::Display for Precondition {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self {
            Precondition::ValidPtr {
                ident, read_write, ..
            } => write!(f, "valid_ptr({}, {})", ident.to_string(), read_write),
            Precondition::ProperAlign { ident, .. } => {
                write!(f, "proper_align({})", ident.to_string())
            }
            Precondition::Boolean(expr) => write!(f, "{}", quote! { #expr }),
            Precondition::Custom(lit) => write!(f, "{:?}", lit.value()),
        }
    }
}

/// Parses an identifier that is valid for use in a precondition.
fn parse_precondition_ident(input: ParseStream) -> syn::Result<Ident> {
    let lookahead = input.lookahead1();

    if lookahead.peek(Token![self]) {
        input.call(Ident::parse_any)
    } else if lookahead.peek(Ident) {
        input.parse()
    } else {
        Err(lookahead.error())
    }
}

impl Parse for Precondition {
    fn parse(input: ParseStream) -> syn::Result<Self> {
        let start_span = input.span();

        if input.peek(custom_keywords::valid_ptr) {
            let valid_ptr_keyword = input.parse()?;
            let content;
            let parentheses = parenthesized!(content in input);
            let ident = parse_precondition_ident(&content)?;
            let comma = content.parse()?;
            let read_write = content.parse()?;

            if content.is_empty() {
                Ok(Precondition::ValidPtr {
                    valid_ptr_keyword,
                    parentheses,
                    ident,
                    _comma: comma,
                    read_write,
                })
            } else {
                Err(content.error("unexpected token"))
            }
        } else if input.peek(custom_keywords::proper_align) {
            let proper_align_keyword = input.parse()?;
            let content;
            let parentheses = parenthesized!(content in input);
            let ident = parse_precondition_ident(&content)?;

            if content.is_empty() {
                Ok(Precondition::ProperAlign {
                    proper_align_keyword,
                    parentheses,
                    ident,
                })
            } else {
                Err(content.error("unexpected token"))
            }
        } else if input.peek(LitStr) {
            Ok(Precondition::Custom(input.parse()?))
        } else {
            let expr = input.parse();

            match expr {
                Ok(expr) => Ok(Precondition::Boolean(Box::new(expr))),
                Err(mut err) => {
                    err.combine(Error::new(
                        start_span,
                        "expected `valid_ptr`, `proper_align`, a string literal or a boolean expression",
                    ));

                    Err(err)
                }
            }
        }
    }
}

impl Spanned for Precondition {
    fn span(&self) -> Span {
        match self {
            Precondition::ValidPtr {
                valid_ptr_keyword,
                parentheses,
                ..
            } => valid_ptr_keyword
                .span()
                .join(parentheses.span)
                .unwrap_or_else(|| valid_ptr_keyword.span()),
            Precondition::ProperAlign {
                proper_align_keyword,
                parentheses,
                ..
            } => proper_align_keyword
                .span()
                .join(parentheses.span)
                .unwrap_or_else(|| proper_align_keyword.span()),
            Precondition::Boolean(expr) => expr.span(),
            Precondition::Custom(lit) => lit.span(),
        }
    }
}

impl Precondition {
    /// Returns a unique id for each descriminant.
    fn descriminant_id(&self) -> usize {
        match self {
            Precondition::ValidPtr { .. } => 0,
            Precondition::ProperAlign { .. } => 1,
            Precondition::Boolean(_) => 2,
            Precondition::Custom(_) => 3,
        }
    }
}

// Define an order for the preconditions here.
//
// The exact ordering does not really matter, as long as it is deterministic.
impl Ord for Precondition {
    fn cmp(&self, other: &Self) -> Ordering {
        match (self, other) {
            (
                Precondition::ValidPtr {
                    ident: ident_self, ..
                },
                Precondition::ValidPtr {
                    ident: ident_other, ..
                },
            ) => ident_self.cmp(ident_other),
            (
                Precondition::ProperAlign {
                    ident: ident_self, ..
                },
                Precondition::ProperAlign {
                    ident: ident_other, ..
                },
            ) => ident_self.cmp(ident_other),
            (Precondition::Boolean(expr_self), Precondition::Boolean(expr_other)) => {
                quote!(#expr_self)
                    .to_string()
                    .cmp(&quote!(#expr_other).to_string())
            }
            (Precondition::Custom(lit_self), Precondition::Custom(lit_other)) => {
                lit_self.value().cmp(&lit_other.value())
            }
            _ => {
                debug_assert_ne!(self.descriminant_id(), other.descriminant_id());

                self.descriminant_id().cmp(&other.descriminant_id())
            }
        }
    }
}

impl PartialOrd for Precondition {
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        Some(self.cmp(other))
    }
}

impl PartialEq for Precondition {
    fn eq(&self, other: &Self) -> bool {
        self.cmp(other) == Ordering::Equal
    }
}

impl Eq for Precondition {}

/// Whether something is readable, writable or both.
#[derive(Clone)]
pub(crate) enum ReadWrite {
    /// The described thing is only readable.
    Read {
        /// The `r` keyword, indicating readability.
        r_keyword: custom_keywords::r,
    },
    /// The described thing is only writable.
    Write {
        /// The `w` keyword, indicating writability.
        w_keyword: custom_keywords::w,
    },
    /// The described thing is both readable and writable.
    Both {
        /// The `r` keyword, indicating readability.
        r_keyword: custom_keywords::r,
        /// The `+` between the `r` and the `w`, if both are present.
        _plus: Token![+],
        /// The `w` keyword, indicating writability.
        w_keyword: custom_keywords::w,
    },
}

impl ReadWrite {
    /// Generates a short description suitable for usage in generated documentation.
    ///
    /// The generated description should finish the sentence
    /// "The pointer must be valid for...".
    pub(crate) fn doc_description(&self) -> &str {
        match self {
            ReadWrite::Read { .. } => "reads",
            ReadWrite::Write { .. } => "writes",
            ReadWrite::Both { .. } => "reads and writes",
        }
    }
}

impl fmt::Display for ReadWrite {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match self {
            ReadWrite::Read { .. } => write!(f, "r"),
            ReadWrite::Write { .. } => write!(f, "w"),
            ReadWrite::Both { .. } => write!(f, "r+w"),
        }
    }
}

impl Parse for ReadWrite {
    fn parse(input: ParseStream) -> syn::Result<Self> {
        let lookahead = input.lookahead1();

        if lookahead.peek(custom_keywords::w) {
            Ok(ReadWrite::Write {
                w_keyword: input.parse()?,
            })
        } else if lookahead.peek(custom_keywords::r) {
            let r_keyword = input.parse()?;

            if input.peek(Token![+]) {
                let plus = input.parse()?;
                let w_keyword = input.parse()?;

                Ok(ReadWrite::Both {
                    r_keyword,
                    _plus: plus,
                    w_keyword,
                })
            } else {
                Ok(ReadWrite::Read { r_keyword })
            }
        } else {
            Err(lookahead.error())
        }
    }
}

impl Spanned for ReadWrite {
    fn span(&self) -> Span {
        match self {
            ReadWrite::Read { r_keyword } => r_keyword.span,
            ReadWrite::Write { w_keyword } => w_keyword.span,
            ReadWrite::Both {
                r_keyword,
                w_keyword,
                ..
            } => r_keyword
                .span
                .join(w_keyword.span)
                .unwrap_or(r_keyword.span),
        }
    }
}

/// A precondition with an optional `cfg` applying to it.
pub(crate) struct CfgPrecondition {
    /// The precondition with additional data.
    pub(crate) precondition: Precondition,
    /// The `cfg` applying to the precondition.
    #[allow(dead_code)]
    pub(crate) cfg: Option<TokenStream>,
    /// The span best representing the precondition.
    pub(crate) span: Span,
}

impl CfgPrecondition {
    /// The raw precondition.
    pub(crate) fn precondition(&self) -> &Precondition {
        &self.precondition
    }
}

impl Spanned for CfgPrecondition {
    fn span(&self) -> Span {
        self.span
    }
}

impl PartialEq for CfgPrecondition {
    fn eq(&self, other: &Self) -> bool {
        matches!(self.cmp(other), Ordering::Equal)
    }
}

impl Eq for CfgPrecondition {}

impl PartialOrd for CfgPrecondition {
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        Some(self.cmp(other))
    }
}

impl Ord for CfgPrecondition {
    fn cmp(&self, other: &Self) -> Ordering {
        self.precondition.cmp(&other.precondition)
    }
}

#[cfg(test)]
mod tests {
    use quote::quote;
    use syn::parse2;

    use super::*;

    #[test]
    fn parse_correct_custom() {
        let result: Result<Precondition, _> = parse2(quote! {
            "foo"
        });
        assert!(result.is_ok());
    }

    #[test]
    fn parse_correct_valid_ptr() {
        {
            let result: Result<Precondition, _> = parse2(quote! {
                valid_ptr(foo, r)
            });
            assert!(result.is_ok());
        }

        {
            let result: Result<Precondition, _> = parse2(quote! {
                valid_ptr(foo, r+w)
            });
            assert!(result.is_ok());
        }

        {
            let result: Result<Precondition, _> = parse2(quote! {
                valid_ptr(foo, w)
            });
            assert!(result.is_ok());
        }
    }

    #[test]
    fn parse_wrong_expr() {
        {
            let result: Result<Precondition, _> = parse2(quote! {
                a ++ b
            });
            assert!(result.is_err());
        }

        {
            let result: Result<Precondition, _> = parse2(quote! {
                17 - + -- + []
            });
            assert!(result.is_err());
        }
    }

    #[test]
    fn parse_extra_tokens() {
        {
            let result: Result<Precondition, _> = parse2(quote! {
                "foo" bar
            });
            assert!(result.is_err());
        }

        {
            let result: Result<Precondition, _> = parse2(quote! {
                valid_ptr(foo, r+w+x)
            });
            assert!(result.is_err());
        }
    }
}