Debian Codegraph @

third_party/rust/typenum/build/op.rs

raw
1 #[derive(Debug, Copy, Clone, Eq, PartialEq)]
2 enum OpType {
3 Operator,
4 Function,
5 }
6
7 use self::OpType::*;
8
9 struct Op {
10 token: &'static str,
11 operator: &'static str,
12 example: (&'static str, &'static str),
13 precedence: u8,
14 n_args: u8,
15 op_type: OpType,
16 }
17
18 pub fn write_op_macro() -> ::std::io::Result<()> {
19 let out_dir = ::std::env::var("OUT_DIR").unwrap();
20 let dest = ::std::path::Path::new(&out_dir).join("op.rs");
21 #[cfg(not(feature = "force_unix_path_separator"))]
22 println!("cargo:rustc-env=TYPENUM_BUILD_OP={}", dest.display());
23 let mut f = ::std::fs::File::create(&dest).unwrap();
24
25 // Operator precedence is taken from
26 // https://doc.rust-lang.org/reference.html#operator-precedence
27 //
28 // We choose 16 as the highest precedence (functions are set to 255 but it doesn't matter
29 // for them). We also only use operators that are left associative so we don't have to worry
30 // about that.
31 let ops = &[
32 Op {
33 token: "*",
34 operator: "Prod",
35 example: ("P2 * P3", "P6"),
36 precedence: 16,
37 n_args: 2,
38 op_type: Operator,
39 },
40 Op {
41 token: "/",
42 operator: "Quot",
43 example: ("P6 / P2", "P3"),
44 precedence: 16,
45 n_args: 2,
46 op_type: Operator,
47 },
48 Op {
49 token: "%",
50 operator: "Mod",
51 example: ("P5 % P3", "P2"),
52 precedence: 16,
53 n_args: 2,
54 op_type: Operator,
55 },
56 Op {
57 token: "+",
58 operator: "Sum",
59 example: ("P2 + P3", "P5"),
60 precedence: 15,
61 n_args: 2,
62 op_type: Operator,
63 },
64 Op {
65 token: "-",
66 operator: "Diff",
67 example: ("P2 - P3", "N1"),
68 precedence: 15,
69 n_args: 2,
70 op_type: Operator,
71 },
72 Op {
73 token: "<<",
74 operator: "Shleft",
75 example: ("U1 << U5", "U32"),
76 precedence: 14,
77 n_args: 2,
78 op_type: Operator,
79 },
80 Op {
81 token: ">>",
82 operator: "Shright",
83 example: ("U32 >> U5", "U1"),
84 precedence: 14,
85 n_args: 2,
86 op_type: Operator,
87 },
88 Op {
89 token: "&",
90 operator: "And",
91 example: ("U5 & U3", "U1"),
92 precedence: 13,
93 n_args: 2,
94 op_type: Operator,
95 },
96 Op {
97 token: "^",
98 operator: "Xor",
99 example: ("U5 ^ U3", "U6"),
100 precedence: 12,
101 n_args: 2,
102 op_type: Operator,
103 },
104 Op {
105 token: "|",
106 operator: "Or",
107 example: ("U5 | U3", "U7"),
108 precedence: 11,
109 n_args: 2,
110 op_type: Operator,
111 },
112 Op {
113 token: "==",
114 operator: "Eq",
115 example: ("P5 == P3 + P2", "True"),
116 precedence: 10,
117 n_args: 2,
118 op_type: Operator,
119 },
120 Op {
121 token: "!=",
122 operator: "NotEq",
123 example: ("P5 != P3 + P2", "False"),
124 precedence: 10,
125 n_args: 2,
126 op_type: Operator,
127 },
128 Op {
129 token: "<=",
130 operator: "LeEq",
131 example: ("P6 <= P3 + P2", "False"),
132 precedence: 10,
133 n_args: 2,
134 op_type: Operator,
135 },
136 Op {
137 token: ">=",
138 operator: "GrEq",
139 example: ("P6 >= P3 + P2", "True"),
140 precedence: 10,
141 n_args: 2,
142 op_type: Operator,
143 },
144 Op {
145 token: "<",
146 operator: "Le",
147 example: ("P4 < P3 + P2", "True"),
148 precedence: 10,
149 n_args: 2,
150 op_type: Operator,
151 },
152 Op {
153 token: ">",
154 operator: "Gr",
155 example: ("P5 < P3 + P2", "False"),
156 precedence: 10,
157 n_args: 2,
158 op_type: Operator,
159 },
160 Op {
161 token: "cmp",
162 operator: "Compare",
163 example: ("cmp(P2, P3)", "Less"),
164 precedence: !0,
165 n_args: 2,
166 op_type: Function,
167 },
168 Op {
169 token: "sqr",
170 operator: "Square",
171 example: ("sqr(P2)", "P4"),
172 precedence: !0,
173 n_args: 1,
174 op_type: Function,
175 },
176 Op {
177 token: "sqrt",
178 operator: "Sqrt",
179 example: ("sqrt(U9)", "U3"),
180 precedence: !0,
181 n_args: 1,
182 op_type: Function,
183 },
184 Op {
185 token: "abs",
186 operator: "AbsVal",
187 example: ("abs(N2)", "P2"),
188 precedence: !0,
189 n_args: 1,
190 op_type: Function,
191 },
192 Op {
193 token: "cube",
194 operator: "Cube",
195 example: ("cube(P2)", "P8"),
196 precedence: !0,
197 n_args: 1,
198 op_type: Function,
199 },
200 Op {
201 token: "pow",
202 operator: "Exp",
203 example: ("pow(P2, P3)", "P8"),
204 precedence: !0,
205 n_args: 2,
206 op_type: Function,
207 },
208 Op {
209 token: "min",
210 operator: "Minimum",
211 example: ("min(P2, P3)", "P2"),
212 precedence: !0,
213 n_args: 2,
214 op_type: Function,
215 },
216 Op {
217 token: "max",
218 operator: "Maximum",
219 example: ("max(P2, P3)", "P3"),
220 precedence: !0,
221 n_args: 2,
222 op_type: Function,
223 },
224 Op {
225 token: "log2",
226 operator: "Log2",
227 example: ("log2(U9)", "U3"),
228 precedence: !0,
229 n_args: 1,
230 op_type: Function,
231 },
232 Op {
233 token: "gcd",
234 operator: "Gcf",
235 example: ("gcd(U9, U21)", "U3"),
236 precedence: !0,
237 n_args: 2,
238 op_type: Function,
239 },
240 ];
241
242 use std::io::Write;
243 write!(
244 f,
245 "
246 /**
247 Convenient type operations.
248
249 Any types representing values must be able to be expressed as `ident`s. That means they need to be
250 in scope.
251
252 For example, `P5` is okay, but `typenum::P5` is not.
253
254 You may combine operators arbitrarily, although doing so excessively may require raising the
255 recursion limit.
256
257 # Example
258 ```rust
259 #![recursion_limit=\"128\"]
260 #[macro_use] extern crate typenum;
261 use typenum::consts::*;
262
263 fn main() {{
264 assert_type!(
265 op!(min((P1 - P2) * (N3 + N7), P5 * (P3 + P4)) == P10)
266 );
267 }}
268 ```
269 Operators are evaluated based on the operator precedence outlined
270 [here](https://doc.rust-lang.org/reference.html#operator-precedence).
271
272 The full list of supported operators and functions is as follows:
273
274 {}
275
276 They all expand to type aliases defined in the `operator_aliases` module. Here is an expanded list,
277 including examples:
278
279 ",
280 ops.iter()
281 .map(|op| format!("`{}`", op.token))
282 .collect::<Vec<_>>()
283 .join(", ")
284 )?;
285
286 //write!(f, "Token | Alias | Example\n ===|===|===\n")?;
287
288 for op in ops.iter() {
289 write!(
290 f,
291 "---\nOperator `{token}`. Expands to `{operator}`.
292
293 ```rust
294 # #[macro_use] extern crate typenum;
295 # use typenum::*;
296 # fn main() {{
297 assert_type_eq!(op!({ex0}), {ex1});
298 # }}
299 ```\n
300 ",
301 token = op.token,
302 operator = op.operator,
303 ex0 = op.example.0,
304 ex1 = op.example.1
305 )?;
306 }
307
308 write!(
309 f,
310 "*/
311 #[macro_export(local_inner_macros)]
312 macro_rules! op {{
313 ($($tail:tt)*) => ( __op_internal__!($($tail)*) );
314 }}
315
316 #[doc(hidden)]
317 #[macro_export(local_inner_macros)]
318 macro_rules! __op_internal__ {{
319 "
320 )?;
321
322 // We first us the shunting-yard algorithm to produce our tokens in Polish notation.
323 // See: https://en.wikipedia.org/wiki/Shunting-yard_algorithm
324
325 // Note: Due to macro asymmetry, "the top of the stack" refers to the first element, not the
326 // last
327
328 // -----------------------------------------------------------------------------------------
329 // Stage 1: There are tokens to be read:
330
331 // -------
332 // Case 1: Token is a function => Push it onto the stack:
333 for fun in ops.iter().filter(|f| f.op_type == Function) {
334 write!(
335 f,
336 "
337 (@stack[$($stack:ident,)*] @queue[$($queue:ident,)*] @tail: {f_token} $($tail:tt)*) => (
338 __op_internal__!(@stack[{f_op}, $($stack,)*] @queue[$($queue,)*] @tail: $($tail)*)
339 );",
340 f_token = fun.token,
341 f_op = fun.operator
342 )?;
343 }
344
345 // -------
346 // Case 2: Token is a comma => Until the top of the stack is a LParen,
347 // Pop operators from stack to queue
348
349 // Base case: Top of stack is LParen, ditch comma and continue
350 write!(
351 f,
352 "
353 (@stack[LParen, $($stack:ident,)*] @queue[$($queue:ident,)*] @tail: , $($tail:tt)*) => (
354 __op_internal__!(@stack[LParen, $($stack,)*] @queue[$($queue,)*] @tail: $($tail)*)
355 );"
356 )?;
357 // Recursive case: Not LParen, pop from stack to queue
358 write!(
359 f,
360 "
361 (@stack[$stack_top:ident, $($stack:ident,)*] @queue[$($queue:ident,)*] @tail: , $($tail:tt)*) => (
362 __op_internal__!(@stack[$($stack,)*] @queue[$stack_top, $($queue,)*] @tail: , $($tail)*)
363 );"
364 )?;
365
366 // -------
367 // Case 3: Token is an operator, o1:
368 for o1 in ops.iter().filter(|op| op.op_type == Operator) {
369 // If top of stack is operator o2 with o1.precedence <= o2.precedence,
370 // Then pop o2 off stack onto queue:
371 for o2 in ops
372 .iter()
373 .filter(|op| op.op_type == Operator)
374 .filter(|o2| o1.precedence <= o2.precedence)
375 {
376 write!(
377 f,
378 "
379 (@stack[{o2_op}, $($stack:ident,)*] @queue[$($queue:ident,)*] @tail: {o1_token} $($tail:tt)*) => (
380 __op_internal__!(@stack[$($stack,)*] @queue[{o2_op}, $($queue,)*] @tail: {o1_token} $($tail)*)
381 );",
382 o2_op = o2.operator,
383 o1_token = o1.token
384 )?;
385 }
386 // Base case: push o1 onto stack
387 write!(
388 f,
389 "
390 (@stack[$($stack:ident,)*] @queue[$($queue:ident,)*] @tail: {o1_token} $($tail:tt)*) => (
391 __op_internal__!(@stack[{o1_op}, $($stack,)*] @queue[$($queue,)*] @tail: $($tail)*)
392 );",
393 o1_op = o1.operator,
394 o1_token = o1.token
395 )?;
396 }
397
398 // -------
399 // Case 4: Token is "(": push it onto stack as "LParen". Also convert the ")" to "RParen" to
400 // appease the macro gods:
401 write!(
402 f,
403 "
404 (@stack[$($stack:ident,)*] @queue[$($queue:ident,)*] @tail: ( $($stuff:tt)* ) $($tail:tt)* )
405 => (
406 __op_internal__!(@stack[LParen, $($stack,)*] @queue[$($queue,)*]
407 @tail: $($stuff)* RParen $($tail)*)
408 );"
409 )?;
410
411 // -------
412 // Case 5: Token is "RParen":
413 // 1. Pop from stack to queue until we see an "LParen",
414 // 2. Kill the "LParen",
415 // 3. If the top of the stack is a function, pop it onto the queue
416 // 2. Base case:
417 write!(
418 f,
419 "
420 (@stack[LParen, $($stack:ident,)*] @queue[$($queue:ident,)*] @tail: RParen $($tail:tt)*) => (
421 __op_internal__!(@rp3 @stack[$($stack,)*] @queue[$($queue,)*] @tail: $($tail)*)
422 );"
423 )?;
424 // 1. Recursive case:
425 write!(
426 f,
427 "
428 (@stack[$stack_top:ident, $($stack:ident,)*] @queue[$($queue:ident,)*] @tail: RParen $($tail:tt)*)
429 => (
430 __op_internal__!(@stack[$($stack,)*] @queue[$stack_top, $($queue,)*] @tail: RParen $($tail)*)
431 );"
432 )?;
433 // 3. Check for function:
434 for fun in ops.iter().filter(|f| f.op_type == Function) {
435 write!(
436 f,
437 "
438 (@rp3 @stack[{fun_op}, $($stack:ident,)*] @queue[$($queue:ident,)*] @tail: $($tail:tt)*) => (
439 __op_internal__!(@stack[$($stack,)*] @queue[{fun_op}, $($queue,)*] @tail: $($tail)*)
440 );",
441 fun_op = fun.operator
442 )?;
443 }
444 // 3. If no function found:
445 write!(
446 f,
447 "
448 (@rp3 @stack[$($stack:ident,)*] @queue[$($queue:ident,)*] @tail: $($tail:tt)*) => (
449 __op_internal__!(@stack[$($stack,)*] @queue[$($queue,)*] @tail: $($tail)*)
450 );"
451 )?;
452
453 // -------
454 // Case 6: Token is a number: Push it onto the queue
455 write!(
456 f,
457 "
458 (@stack[$($stack:ident,)*] @queue[$($queue:ident,)*] @tail: $num:ident $($tail:tt)*) => (
459 __op_internal__!(@stack[$($stack,)*] @queue[$num, $($queue,)*] @tail: $($tail)*)
460 );"
461 )?;
462
463 // -------
464 // Case 7: Out of tokens:
465 // Base case: Stack empty: Start evaluating
466 write!(
467 f,
468 "
469 (@stack[] @queue[$($queue:ident,)*] @tail: ) => (
470 __op_internal__!(@reverse[] @input: $($queue,)*)
471 );"
472 )?;
473 // Recursive case: Pop stack to queue
474 write!(
475 f,
476 "
477 (@stack[$stack_top:ident, $($stack:ident,)*] @queue[$($queue:ident,)*] @tail:) => (
478 __op_internal__!(@stack[$($stack,)*] @queue[$stack_top, $($queue,)*] @tail: )
479 );"
480 )?;
481
482 // -----------------------------------------------------------------------------------------
483 // Stage 2: Reverse so we have RPN
484 write!(
485 f,
486 "
487 (@reverse[$($revved:ident,)*] @input: $head:ident, $($tail:ident,)* ) => (
488 __op_internal__!(@reverse[$head, $($revved,)*] @input: $($tail,)*)
489 );"
490 )?;
491 write!(
492 f,
493 "
494 (@reverse[$($revved:ident,)*] @input: ) => (
495 __op_internal__!(@eval @stack[] @input[$($revved,)*])
496 );"
497 )?;
498
499 // -----------------------------------------------------------------------------------------
500 // Stage 3: Evaluate in Reverse Polish Notation
501 // Operators / Operators with 2 args:
502 for op in ops.iter().filter(|op| op.n_args == 2) {
503 // Note: We have to switch $a and $b here, otherwise non-commutative functions are backwards
504 write!(
505 f,
506 "
507 (@eval @stack[$a:ty, $b:ty, $($stack:ty,)*] @input[{op}, $($tail:ident,)*]) => (
508 __op_internal__!(@eval @stack[$crate::{op}<$b, $a>, $($stack,)*] @input[$($tail,)*])
509 );",
510 op = op.operator
511 )?;
512 }
513 // Operators with 1 arg:
514 for op in ops.iter().filter(|op| op.n_args == 1) {
515 write!(
516 f,
517 "
518 (@eval @stack[$a:ty, $($stack:ty,)*] @input[{op}, $($tail:ident,)*]) => (
519 __op_internal__!(@eval @stack[$crate::{op}<$a>, $($stack,)*] @input[$($tail,)*])
520 );",
521 op = op.operator
522 )?;
523 }
524
525 // Wasn't a function or operator, so must be a value => push onto stack
526 write!(
527 f,
528 "
529 (@eval @stack[$($stack:ty,)*] @input[$head:ident, $($tail:ident,)*]) => (
530 __op_internal__!(@eval @stack[$head, $($stack,)*] @input[$($tail,)*])
531 );"
532 )?;
533
534 // No input left:
535 write!(
536 f,
537 "
538 (@eval @stack[$stack:ty,] @input[]) => (
539 $stack
540 );"
541 )?;
542
543 // -----------------------------------------------------------------------------------------
544 // Stage 0: Get it started
545 write!(
546 f,
547 "
548 ($($tail:tt)* ) => (
549 __op_internal__!(@stack[] @queue[] @tail: $($tail)*)
550 );"
551 )?;
552
553 write!(
554 f,
555 "
556 }}"
557 )?;
558
559 Ok(())
560 }