compare_variables_macro 0.2.2

Procedural macro for crate `compare_variables`
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
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
#![cfg_attr(debug_assertions, allow(unused_imports))]

use proc_macro::{self, TokenStream};
use proc_macro_error::abort;
use proc_macro2::{Ident, Span, TokenStream as TokenStream2};
use quote::quote;
use syn::ext::IdentExt;
use syn::parse::Parse;
use syn::{Token, parse_macro_input};

/**
A macro to compare types which implement `PartialOrd`.

# Overview

This macro performs comparison between two or three values of any type `T` which
implements  `PartialOrd`. If the comparison evaluates to `true`, the macro
returns `Result::Ok(())`, otherwise it returns a
`Result::Err(compare_variables::Operator)` which can be formatted into a
string showcasing the failed comparison.

The macro syntax is
```math
compare_variables(x _ y)
```
for comparing two values and
```math
compare_variables(x _ y _ z)
```
for comparing three values with `_` being any of the comparison operators
`<, <=, ==, !=, >, >=`.

`x`, `y` and `z` can be either a literal (e.g. `3.141` or `1e10`) or a variable:

```rust
use compare_variables::compare_variables;

assert!(compare_variables!(2.0 > 1.5).is_ok());

let x = 1;
let y = 2;
assert!(compare_variables!(x < 2 == y).is_ok());
assert!(compare_variables!(x >= 2).is_err());
assert!(compare_variables!(x != y).is_ok());
```

It is possible to combine the macro with the question mark operator:
```rust
use compare_variables::{compare_variables, Operator};

fn checked_sub(left: u16, right: u16) -> Result<u16, Operator<u16>> {
    compare_variables!(left >= right)?;
    return Ok(left - right);
}

assert_eq!(checked_sub(2, 1).unwrap(), 1);
assert_eq!(checked_sub(2, 2).unwrap(), 0);
assert!(checked_sub(2, 3).is_err());
```

It is also possible to use named and anonymous struct fields as inputs:

```
use compare_variables::compare_variables;

struct NamedField {
   x: f64
}
let n = NamedField {x: 1.0};
assert!(compare_variables!(n.x > -1.0).is_ok());
assert!(compare_variables!(n.x > 1.0).is_err());

struct AnonymousField(i32);
let a = AnonymousField(-5);
assert!(compare_variables!(a.0 > -6).is_ok());
assert!(compare_variables!(a.0 > 1).is_err());
```

# Error message

The error message is created via the struct [`Operator`](https://docs.rs/compare_variables/0.1.0/compare_variables/struct.Operator.html).
Please refer to its documentation for more details. The keywords `val` and `as` allow to customize the treatment of variable names in the error message:

```
use compare_variables::compare_variables;

// Error message with literals only
let err = compare_variables!(5i32 <= -1i32).unwrap_err();
assert_eq!(err.to_string(), "`5 <= -1` is false");

let x = 1;
let y = 2;

// Default error message
let err = compare_variables!(x > y).unwrap_err();
assert_eq!(err.to_string(), "`x (value: 1) > y (value: 2)` is false");

// Rename x in the error message
let err = compare_variables!(x as variable > y).unwrap_err();
assert_eq!(err.to_string(), "`variable (value: 1) > y (value: 2)` is false");

// Only display the underlying value, not the variable name:
let err = compare_variables!(val x > y).unwrap_err();
assert_eq!(err.to_string(), "`1 > y (value: 2)` is false");

// `as` is ignored if used together with `val`:
let err = compare_variables!(val x as variable > y).unwrap_err();
assert_eq!(err.to_string(), "`1 > y (value: 2)` is false");
```

# Examples

```rust
use compare_variables::compare_variables;

// Different float types:
assert!(compare_variables!(1.5 < 2.0 == 3.0).is_err());
assert!(compare_variables!(1.7f32 == 1.7f32).is_ok());
let f = 2.0;
assert!(compare_variables!(f < 5.2).is_ok());
assert!(compare_variables!(f as f_var == val f).is_ok());

// Signed and unsigned integers
assert!(compare_variables!(1i32 >= 2i32).is_err());
let u = 3usize;
assert!(compare_variables!(2usize < u < 4usize).is_ok());
let i = 15i64;
assert!(compare_variables!(-10i64 <= i).is_ok());
assert!(compare_variables!(-10i64 <= i <= 10i64).is_err());

// Custom types implementing `PartialOrd`.
// Clone and Copy are not required and are only used here for the example.
#[derive(PartialEq, Clone, Copy)]
struct MyFloat64(f64);

impl PartialOrd for MyFloat64 {
   fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
       return self.0.partial_cmp(&other.0);
   }
}

let myfloat1 = MyFloat64(1.0);
let myfloat2 = MyFloat64(2.0);
assert!(compare_variables!(myfloat1 == myfloat1).is_ok());
assert!(compare_variables!(myfloat1 <= myfloat2).is_ok());
assert!(compare_variables!(myfloat1 >= myfloat2).is_err());
```
 */
#[proc_macro]
pub fn compare_variables(input: TokenStream) -> TokenStream {
    let comparison_error_info: ComparisonErrorInfo = parse_macro_input!(input);

    let first_arg = comparison_error_info.first_arg.as_token_stream();
    let relation_first_to_second = comparison_error_info
        .relation_first_to_second
        .as_token_stream();
    let second_arg = comparison_error_info.second_arg.as_token_stream();
    let relation_second_to_third = comparison_error_info
        .relation_second_to_third
        .as_token_stream();
    let third_arg = match comparison_error_info.third_arg {
        Some(arg) => {
            let ts = arg.as_token_stream();
            quote! {Some(#ts)}
        }
        None => quote! {None},
    };

    // Build the input for the compare_variables function
    let stream = quote! {
        compare_variables::Operator::new(
            #first_arg,
            #relation_first_to_second,
            #second_arg,
            #relation_second_to_third,
            #third_arg,
        )
    };

    return TokenStream::from(stream);
}

#[repr(u8)]
enum Operator {
    Lesser,
    LesserOrEqual,
    Equal,
    Inequal,
    GreaterOrEqual,
    Greater,
}

impl Operator {
    fn as_token_stream(&self) -> proc_macro2::TokenStream {
        match self {
            Operator::Lesser => {
                quote! {
                    compare_variables::ComparisonOperator::Lesser
                }
            }
            Operator::LesserOrEqual => {
                quote! {
                    compare_variables::ComparisonOperator::LesserOrEqual
                }
            }
            Operator::Equal => {
                quote! {
                    compare_variables::ComparisonOperator::Equal
                }
            }
            Operator::Inequal => {
                quote! {
                    compare_variables::ComparisonOperator::Inequal
                }
            }
            Operator::GreaterOrEqual => {
                quote! {
                    compare_variables::ComparisonOperator::GreaterOrEqual
                }
            }
            Operator::Greater => {
                quote! {
                    compare_variables::ComparisonOperator::Greater
                }
            }
        }
    }
}

impl Parse for Operator {
    fn parse(input: syn::parse::ParseStream) -> syn::Result<Self> {
        // If Token![<] is tested before Token![<=], then "<" is parsed, leaving only
        // "=". This will then lead to a compile error.
        if input.peek(Token![<=]) {
            input.parse::<Token![<=]>()?;
            Ok(Operator::LesserOrEqual)
        } else if input.peek(Token![>=]) {
            input.parse::<Token![>=]>()?;
            Ok(Operator::GreaterOrEqual)
        } else if input.peek(Token![==]) {
            input.parse::<Token![==]>()?;
            Ok(Operator::Equal)
        } else if input.peek(Token![!=]) {
            input.parse::<Token![!=]>()?;
            Ok(Operator::Inequal)
        } else if input.peek(Token![<]) {
            input.parse::<Token![<]>()?;
            Ok(Operator::Lesser)
        } else if input.peek(Token![>]) {
            input.parse::<Token![>]>()?;
            Ok(Operator::Greater)
        } else {
            Err(syn::Error::new(
                input.span(),
                "no comparison operator could be identified. Valid
                    operators are \"<\", \"<=\", \"==\", \"!=\", \">=\" or \">\".",
            ))
        }
    }
}

enum VariableOrLiteral {
    Other {
        arg_names: Vec<String>,
        arg_names_display: Vec<String>,
    },
    LitFloat(syn::LitFloat),
    LitInt(syn::LitInt),
}

impl VariableOrLiteral {
    fn as_token_stream(&self) -> proc_macro2::TokenStream {
        match self {
            VariableOrLiteral::Other {
                arg_names,
                arg_names_display,
            } => {
                // Build a token stream out of arg_name and arg_name_display, using . as a
                // delimiter
                let arg_value = arg_names.join(".");
                let arg_value_ts: TokenStream2 = match str::parse::<TokenStream2>(&arg_value) {
                    Ok(ts) => ts,
                    Err(_) => abort!(
                        Span::call_site(),
                        format!("could not interpret {arg_value} as rust code")
                    ),
                };
                if arg_names_display.is_empty() {
                    quote! {
                        compare_variables::ComparisonValue::new(#arg_value_ts, None)
                    }
                } else {
                    let arg_name_display = arg_names_display.join(".");
                    quote! {
                        compare_variables::ComparisonValue::new(#arg_value_ts, Some(#arg_name_display))
                    }
                }
            }
            VariableOrLiteral::LitFloat(lit) => {
                quote! {
                    compare_variables::ComparisonValue::new(#lit, None)
                }
            }
            VariableOrLiteral::LitInt(lit) => {
                quote! {
                    compare_variables::ComparisonValue::new(#lit, None)
                }
            }
        }
    }
}

impl Parse for VariableOrLiteral {
    fn parse(input: syn::parse::ParseStream) -> syn::Result<Self> {
        fn parse_composite_varname(
            input: &syn::parse::ParseStream,
            vec: &mut Vec<String>,
        ) -> syn::Result<()> {
            loop {
                if input.peek(syn::LitInt) {
                    let lit = input.parse::<syn::LitInt>()?;
                    vec.push(lit.to_string());
                } else {
                    let ident: syn::Ident = input.call(Ident::parse_any)?;
                    vec.push(ident.to_string()); // parse_any also handles stuff like self
                }

                if input.peek(Token![.]) {
                    // Throw the token away
                    let _ = input.parse::<Token![.]>()?;
                } else {
                    // Field access is done ==> Finish the loop
                    break;
                }
            }
            return Ok(());
        } // parse_composite_varname

        if input.peek(syn::LitFloat) {
            // Parse the float literal
            let val = input.parse::<syn::LitFloat>()?;
            return Ok(VariableOrLiteral::LitFloat(val));
        } else if input.peek(syn::LitInt) {
            // Parse the float literal
            let val = input.parse::<syn::LitInt>()?;
            return Ok(VariableOrLiteral::LitInt(val));
        } else {
            let mut display_arg_names = true;

            // Input is possibly a variable name.
            let mut arg_names: Vec<String> = Vec::new();

            // First check if the first identifier is "val":
            let first_ident: Ident = input.call(Ident::parse_any)?; // parse_any also handles stuff like self

            // Next identifier is not a "." -> Check if first_ident is "val". If not, the
            // macro is used wrong
            if input.peek(Token![.]) {
                // Throw the token away
                let _ = input.parse::<Token![.]>()?;

                // Try continuing to parse and keep the first identifier
                arg_names.push(first_ident.to_string());
                parse_composite_varname(&input, &mut arg_names)?;
            } else {
                if input.peek(syn::Ident) {
                    if first_ident == "val" {
                        display_arg_names = false;

                        // Try continuing to parse
                        parse_composite_varname(&input, &mut arg_names)?;
                    } else {
                        abort!(
                            Span::call_site(),
                            format!("found unexpected tokens behind {first_ident}")
                        )
                    }
                } else {
                    arg_names.push(first_ident.to_string());
                }
            }

            // Resolve the alias, if the variable name should be displayed
            let arg_names_display: Vec<String> = if input.peek(Token![as]) {
                input.parse::<Token![as]>()?;
                let mut arg_names_display: Vec<String> = Vec::new();
                parse_composite_varname(&input, &mut arg_names_display)?;
                if display_arg_names {
                    arg_names_display
                } else {
                    Vec::new()
                }
            } else {
                if display_arg_names {
                    arg_names.clone()
                } else {
                    Vec::new()
                }
            };

            return Ok(VariableOrLiteral::Other {
                arg_names,
                arg_names_display,
            });
        }
    }
}

// Parser for the compare_variables macro
struct ComparisonErrorInfo {
    first_arg: VariableOrLiteral,
    relation_first_to_second: Operator,
    second_arg: VariableOrLiteral,
    relation_second_to_third: Operator,
    third_arg: Option<VariableOrLiteral>,
}

impl Parse for ComparisonErrorInfo {
    fn parse(input: syn::parse::ParseStream) -> syn::Result<Self> {
        // Read the arguments
        let first_arg = VariableOrLiteral::parse(&input)?;
        let relation_first_to_second = Operator::parse(&input)?;
        let second_arg = VariableOrLiteral::parse(&input)?;

        // If the input continues, parse the third argument
        let (relation_second_to_third, third_arg) = if let Ok(operator) = Operator::parse(&input) {
            (operator, Some(VariableOrLiteral::parse(&input)?))
        } else {
            (Operator::Equal, None)
        };

        return Ok(ComparisonErrorInfo {
            first_arg,
            relation_first_to_second,
            second_arg,
            relation_second_to_third,
            third_arg,
        });
    }
}

#[cfg(test)]
mod tests {

    use super::*;

    #[test]
    fn test_parse_check_bounds_info() {
        // Assert that the parse was successfull

        // Float
        let _: ComparisonErrorInfo = syn::parse_quote!(0.0 < arg);
        let _: ComparisonErrorInfo = syn::parse_quote!(0.0 <= arg);
        let _: ComparisonErrorInfo = syn::parse_quote!(0.0 <= arg as alternative_arg);
        let _: ComparisonErrorInfo = syn::parse_quote!(0.0 < arg <= 1.0);
        let _: ComparisonErrorInfo = syn::parse_quote!(0.0 < arg as alternative_arg <= 1.0);
        let _: ComparisonErrorInfo = syn::parse_quote!(arg < 1.0);
        let _: ComparisonErrorInfo = syn::parse_quote!(arg <= 1.0);
        let _: ComparisonErrorInfo = syn::parse_quote!(arg as alternative_arg <= 1.0);

        // Int
        let _: ComparisonErrorInfo = syn::parse_quote!(-1 < arg);
        let _: ComparisonErrorInfo = syn::parse_quote!(-1 < -2);
        let _: ComparisonErrorInfo = syn::parse_quote!(-1 < arg as alternative_arg <= 2);
    }
}