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
//! This crate defines a macro to imitate the ternary operator
//! found in C-like languages such as C, C++, Java, etc.
//! The macro can be used to make more compact conditional
//! expressions in Rust code.
//!
//! For example, this code in plain rust:
//! ```
//! let a = 20;
//! let b = 30;
//!
//! // This is the part we will be able to simplify
//! let min = if a < b {
//! a
//! } else {
//! b
//! };
//!
//! // Check the result
//! assert_eq!(min, a);
//! ```
//! ... Can be shortened to the following, with this crate:
//!
//! ```
//! let a = 20;
//! let b = 30;
//!
//! // Shortened from the previous example
//! let min = iffy::i!(a < b ? a : b);
//!
//! // Check the result
//! assert_eq!(min, a);
//! ```
extern crate proc_macro;
use TokenStream;
use quote;
use ;
use ;
type ParseResult<T> = Result;
/// Ternary operator macro.
///
/// Modeled after the ternary operator in C-like languages.
///
/// # Examples
///
/// **Basic usage**
/// ```
/// // Include the macro
/// use iffy::i;
///
/// // Define some variables to use in the
/// // with the macro, so that we keep things
/// // neat
/// let a = 20;
/// let b = 30;
///
/// // Use the macro in place of Rust's `if..else`
/// // expressions, for more compact code
/// let result = i!(a > b ? "a wins" : "b wins");
///
/// // Make sure `b` is the winner
/// assert_eq!(result, "b wins");
/// ```
///
/// **Nested usage**
///
/// The crate currently does not support nested ternary syntax,
/// so a temporary variable is needed to simulate this.
/// ```
/// // Include the macro
/// use iffy::i;
///
/// // Define some variables to use in the
/// // with the macro, so that we keep things
/// // neat
/// let a = 20;
/// let b = 30;
/// let c = 50;
///
/// // Temporary variables are required for
/// // nesting ternary operators
/// let tmp0 = i!(b > c ? "b wins" : "c wins");
/// let tmp1 = i!(a > c ? "a wins" : "c wins");
///
/// // Use the macro in place of Rust's `if..else`
/// // expressions, for more compact code
/// let result = i!(b > a ? tmp0 : tmp1);
///
/// // Make sure `c` is the winner
/// assert_eq!(result, "c wins");
/// assert_eq!(tmp0, "c wins");
/// assert_eq!(tmp1, "c wins");
///
/// ```