Debian Codegraph @

third_party/rust/syn/tests/test_expr.rs

raw
1 #![allow(
2 clippy::needless_lifetimes,
3 clippy::single_element_loop,
4 clippy::uninlined_format_args
5 )]
6
7 #[macro_use]
8 mod macros;
9
10 use proc_macro2::{Delimiter, Group};
11 use quote::{quote, ToTokens as _};
12 use std::mem;
13 use syn::punctuated::Punctuated;
14 use syn::visit_mut::{self, VisitMut};
15 use syn::{parse_quote, token, Expr, ExprRange, ExprTuple, Stmt, Token};
16
17 #[test]
18 fn test_expr_parse() {
19 let tokens = quote!(..100u32);
20 snapshot!(tokens as Expr, @r#"
21 Expr::Range {
22 limits: RangeLimits::HalfOpen,
23 end: Some(Expr::Lit {
24 lit: 100u32,
25 }),
26 }
27 "#);
28
29 let tokens = quote!(..100u32);
30 snapshot!(tokens as ExprRange, @r#"
31 ExprRange {
32 limits: RangeLimits::HalfOpen,
33 end: Some(Expr::Lit {
34 lit: 100u32,
35 }),
36 }
37 "#);
38 }
39
40 #[test]
41 fn test_await() {
42 // Must not parse as Expr::Field.
43 let tokens = quote!(fut.await);
44
45 snapshot!(tokens as Expr, @r#"
46 Expr::Await {
47 base: Expr::Path {
48 path: Path {
49 segments: [
50 PathSegment {
51 ident: "fut",
52 },
53 ],
54 },
55 },
56 }
57 "#);
58 }
59
60 #[rustfmt::skip]
61 #[test]
62 fn test_tuple_multi_index() {
63 let expected = snapshot!("tuple.0.0" as Expr, @r#"
64 Expr::Field {
65 base: Expr::Field {
66 base: Expr::Path {
67 path: Path {
68 segments: [
69 PathSegment {
70 ident: "tuple",
71 },
72 ],
73 },
74 },
75 member: Member::Unnamed(Index {
76 index: 0,
77 }),
78 },
79 member: Member::Unnamed(Index {
80 index: 0,
81 }),
82 }
83 "#);
84
85 for &input in &[
86 "tuple .0.0",
87 "tuple. 0.0",
88 "tuple.0 .0",
89 "tuple.0. 0",
90 "tuple . 0 . 0",
91 ] {
92 assert_eq!(expected, syn::parse_str(input).unwrap());
93 }
94
95 for tokens in [
96 quote!(tuple.0.0),
97 quote!(tuple .0.0),
98 quote!(tuple. 0.0),
99 quote!(tuple.0 .0),
100 quote!(tuple.0. 0),
101 quote!(tuple . 0 . 0),
102 ] {
103 assert_eq!(expected, syn::parse2(tokens).unwrap());
104 }
105 }
106
107 #[test]
108 fn test_macro_variable_func() {
109 // mimics the token stream corresponding to `$fn()`
110 let path = Group::new(Delimiter::None, quote!(f));
111 let tokens = quote!(#path());
112
113 snapshot!(tokens as Expr, @r#"
114 Expr::Call {
115 func: Expr::Group {
116 expr: Expr::Path {
117 path: Path {
118 segments: [
119 PathSegment {
120 ident: "f",
121 },
122 ],
123 },
124 },
125 },
126 }
127 "#);
128
129 let path = Group::new(Delimiter::None, quote! { #[inside] f });
130 let tokens = quote!(#[outside] #path());
131
132 snapshot!(tokens as Expr, @r#"
133 Expr::Call {
134 attrs: [
135 Attribute {
136 style: AttrStyle::Outer,
137 meta: Meta::Path {
138 segments: [
139 PathSegment {
140 ident: "outside",
141 },
142 ],
143 },
144 },
145 ],
146 func: Expr::Group {
147 expr: Expr::Path {
148 attrs: [
149 Attribute {
150 style: AttrStyle::Outer,
151 meta: Meta::Path {
152 segments: [
153 PathSegment {
154 ident: "inside",
155 },
156 ],
157 },
158 },
159 ],
160 path: Path {
161 segments: [
162 PathSegment {
163 ident: "f",
164 },
165 ],
166 },
167 },
168 },
169 }
170 "#);
171 }
172
173 #[test]
174 fn test_macro_variable_macro() {
175 // mimics the token stream corresponding to `$macro!()`
176 let mac = Group::new(Delimiter::None, quote!(m));
177 let tokens = quote!(#mac!());
178
179 snapshot!(tokens as Expr, @r#"
180 Expr::Macro {
181 mac: Macro {
182 path: Path {
183 segments: [
184 PathSegment {
185 ident: "m",
186 },
187 ],
188 },
189 delimiter: MacroDelimiter::Paren,
190 tokens: TokenStream(``),
191 },
192 }
193 "#);
194 }
195
196 #[test]
197 fn test_macro_variable_struct() {
198 // mimics the token stream corresponding to `$struct {}`
199 let s = Group::new(Delimiter::None, quote! { S });
200 let tokens = quote!(#s {});
201
202 snapshot!(tokens as Expr, @r#"
203 Expr::Struct {
204 path: Path {
205 segments: [
206 PathSegment {
207 ident: "S",
208 },
209 ],
210 },
211 }
212 "#);
213 }
214
215 #[test]
216 fn test_macro_variable_unary() {
217 // mimics the token stream corresponding to `$expr.method()` where expr is `&self`
218 let inner = Group::new(Delimiter::None, quote!(&self));
219 let tokens = quote!(#inner.method());
220 snapshot!(tokens as Expr, @r#"
221 Expr::MethodCall {
222 receiver: Expr::Group {
223 expr: Expr::Reference {
224 expr: Expr::Path {
225 path: Path {
226 segments: [
227 PathSegment {
228 ident: "self",
229 },
230 ],
231 },
232 },
233 },
234 },
235 method: "method",
236 }
237 "#);
238 }
239
240 #[test]
241 fn test_macro_variable_match_arm() {
242 // mimics the token stream corresponding to `match v { _ => $expr }`
243 let expr = Group::new(Delimiter::None, quote! { #[a] () });
244 let tokens = quote!(match v { _ => #expr });
245 snapshot!(tokens as Expr, @r#"
246 Expr::Match {
247 expr: Expr::Path {
248 path: Path {
249 segments: [
250 PathSegment {
251 ident: "v",
252 },
253 ],
254 },
255 },
256 arms: [
257 Arm {
258 pat: Pat::Wild,
259 body: Expr::Group {
260 expr: Expr::Tuple {
261 attrs: [
262 Attribute {
263 style: AttrStyle::Outer,
264 meta: Meta::Path {
265 segments: [
266 PathSegment {
267 ident: "a",
268 },
269 ],
270 },
271 },
272 ],
273 },
274 },
275 },
276 ],
277 }
278 "#);
279
280 let expr = Group::new(Delimiter::None, quote!(loop {} + 1));
281 let tokens = quote!(match v { _ => #expr });
282 snapshot!(tokens as Expr, @r#"
283 Expr::Match {
284 expr: Expr::Path {
285 path: Path {
286 segments: [
287 PathSegment {
288 ident: "v",
289 },
290 ],
291 },
292 },
293 arms: [
294 Arm {
295 pat: Pat::Wild,
296 body: Expr::Group {
297 expr: Expr::Binary {
298 left: Expr::Loop {
299 body: Block {
300 stmts: [],
301 },
302 },
303 op: BinOp::Add,
304 right: Expr::Lit {
305 lit: 1,
306 },
307 },
308 },
309 },
310 ],
311 }
312 "#);
313 }
314
315 // https://github.com/dtolnay/syn/issues/1019
316 #[test]
317 fn test_closure_vs_rangefull() {
318 #[rustfmt::skip] // rustfmt bug: https://github.com/rust-lang/rustfmt/issues/4808
319 let tokens = quote!(|| .. .method());
320 snapshot!(tokens as Expr, @r#"
321 Expr::MethodCall {
322 receiver: Expr::Closure {
323 output: ReturnType::Default,
324 body: Expr::Range {
325 limits: RangeLimits::HalfOpen,
326 },
327 },
328 method: "method",
329 }
330 "#);
331 }
332
333 #[test]
334 fn test_postfix_operator_after_cast() {
335 syn::parse_str::<Expr>("|| &x as T[0]").unwrap_err();
336 syn::parse_str::<Expr>("|| () as ()()").unwrap_err();
337 }
338
339 #[test]
340 fn test_range_kinds() {
341 syn::parse_str::<Expr>("..").unwrap();
342 syn::parse_str::<Expr>("..hi").unwrap();
343 syn::parse_str::<Expr>("lo..").unwrap();
344 syn::parse_str::<Expr>("lo..hi").unwrap();
345
346 syn::parse_str::<Expr>("..=").unwrap_err();
347 syn::parse_str::<Expr>("..=hi").unwrap();
348 syn::parse_str::<Expr>("lo..=").unwrap_err();
349 syn::parse_str::<Expr>("lo..=hi").unwrap();
350
351 syn::parse_str::<Expr>("...").unwrap_err();
352 syn::parse_str::<Expr>("...hi").unwrap_err();
353 syn::parse_str::<Expr>("lo...").unwrap_err();
354 syn::parse_str::<Expr>("lo...hi").unwrap_err();
355 }
356
357 #[test]
358 fn test_range_precedence() {
359 snapshot!(".. .." as Expr, @r#"
360 Expr::Range {
361 limits: RangeLimits::HalfOpen,
362 end: Some(Expr::Range {
363 limits: RangeLimits::HalfOpen,
364 }),
365 }
366 "#);
367
368 snapshot!(".. .. ()" as Expr, @r#"
369 Expr::Range {
370 limits: RangeLimits::HalfOpen,
371 end: Some(Expr::Range {
372 limits: RangeLimits::HalfOpen,
373 end: Some(Expr::Tuple),
374 }),
375 }
376 "#);
377
378 snapshot!("() .. .." as Expr, @r#"
379 Expr::Range {
380 start: Some(Expr::Tuple),
381 limits: RangeLimits::HalfOpen,
382 end: Some(Expr::Range {
383 limits: RangeLimits::HalfOpen,
384 }),
385 }
386 "#);
387
388 // A range with a lower bound cannot be the upper bound of another range,
389 // and a range with an upper bound cannot be the lower bound of another
390 // range.
391 syn::parse_str::<Expr>(".. x ..").unwrap_err();
392 syn::parse_str::<Expr>("x .. x ..").unwrap_err();
393 }
394
395 #[test]
396 fn test_ambiguous_label() {
397 for stmt in [
398 quote! {
399 return 'label: loop { break 'label 42; };
400 },
401 quote! {
402 break ('label: loop { break 'label 42; });
403 },
404 quote! {
405 break 1 + 'label: loop { break 'label 42; };
406 },
407 quote! {
408 break 'outer 'inner: loop { break 'inner 42; };
409 },
410 ] {
411 syn::parse2::<Stmt>(stmt).unwrap();
412 }
413
414 for stmt in [
415 // Parentheses required. See https://github.com/rust-lang/rust/pull/87026.
416 quote! {
417 break 'label: loop { break 'label 42; };
418 },
419 ] {
420 syn::parse2::<Stmt>(stmt).unwrap_err();
421 }
422 }
423
424 #[test]
425 fn test_extended_interpolated_path() {
426 let path = Group::new(Delimiter::None, quote!(a::b));
427
428 let tokens = quote!(if #path {});
429 snapshot!(tokens as Expr, @r#"
430 Expr::If {
431 cond: Expr::Group {
432 expr: Expr::Path {
433 path: Path {
434 segments: [
435 PathSegment {
436 ident: "a",
437 },
438 Token![::],
439 PathSegment {
440 ident: "b",
441 },
442 ],
443 },
444 },
445 },
446 then_branch: Block {
447 stmts: [],
448 },
449 }
450 "#);
451
452 let tokens = quote!(#path {});
453 snapshot!(tokens as Expr, @r#"
454 Expr::Struct {
455 path: Path {
456 segments: [
457 PathSegment {
458 ident: "a",
459 },
460 Token![::],
461 PathSegment {
462 ident: "b",
463 },
464 ],
465 },
466 }
467 "#);
468
469 let tokens = quote!(#path :: c);
470 snapshot!(tokens as Expr, @r#"
471 Expr::Path {
472 path: Path {
473 segments: [
474 PathSegment {
475 ident: "a",
476 },
477 Token![::],
478 PathSegment {
479 ident: "b",
480 },
481 Token![::],
482 PathSegment {
483 ident: "c",
484 },
485 ],
486 },
487 }
488 "#);
489
490 let nested = Group::new(Delimiter::None, quote!(a::b || true));
491 let tokens = quote!(if #nested && false {});
492 snapshot!(tokens as Expr, @r#"
493 Expr::If {
494 cond: Expr::Binary {
495 left: Expr::Group {
496 expr: Expr::Binary {
497 left: Expr::Path {
498 path: Path {
499 segments: [
500 PathSegment {
501 ident: "a",
502 },
503 Token![::],
504 PathSegment {
505 ident: "b",
506 },
507 ],
508 },
509 },
510 op: BinOp::Or,
511 right: Expr::Lit {
512 lit: Lit::Bool {
513 value: true,
514 },
515 },
516 },
517 },
518 op: BinOp::And,
519 right: Expr::Lit {
520 lit: Lit::Bool {
521 value: false,
522 },
523 },
524 },
525 then_branch: Block {
526 stmts: [],
527 },
528 }
529 "#);
530 }
531
532 #[test]
533 fn test_tuple_comma() {
534 let mut expr = ExprTuple {
535 attrs: Vec::new(),
536 paren_token: token::Paren::default(),
537 elems: Punctuated::new(),
538 };
539 snapshot!(expr.to_token_stream() as Expr, @"Expr::Tuple");
540
541 expr.elems.push_value(parse_quote!(continue));
542 // Must not parse to Expr::Paren
543 snapshot!(expr.to_token_stream() as Expr, @r#"
544 Expr::Tuple {
545 elems: [
546 Expr::Continue,
547 Token![,],
548 ],
549 }
550 "#);
551
552 expr.elems.push_punct(<Token![,]>::default());
553 snapshot!(expr.to_token_stream() as Expr, @r#"
554 Expr::Tuple {
555 elems: [
556 Expr::Continue,
557 Token![,],
558 ],
559 }
560 "#);
561
562 expr.elems.push_value(parse_quote!(continue));
563 snapshot!(expr.to_token_stream() as Expr, @r#"
564 Expr::Tuple {
565 elems: [
566 Expr::Continue,
567 Token![,],
568 Expr::Continue,
569 ],
570 }
571 "#);
572
573 expr.elems.push_punct(<Token![,]>::default());
574 snapshot!(expr.to_token_stream() as Expr, @r#"
575 Expr::Tuple {
576 elems: [
577 Expr::Continue,
578 Token![,],
579 Expr::Continue,
580 Token![,],
581 ],
582 }
583 "#);
584 }
585
586 #[test]
587 fn test_binop_associativity() {
588 // Left to right.
589 snapshot!("() + () + ()" as Expr, @r#"
590 Expr::Binary {
591 left: Expr::Binary {
592 left: Expr::Tuple,
593 op: BinOp::Add,
594 right: Expr::Tuple,
595 },
596 op: BinOp::Add,
597 right: Expr::Tuple,
598 }
599 "#);
600
601 // Right to left.
602 snapshot!("() += () += ()" as Expr, @r#"
603 Expr::Binary {
604 left: Expr::Tuple,
605 op: BinOp::AddAssign,
606 right: Expr::Binary {
607 left: Expr::Tuple,
608 op: BinOp::AddAssign,
609 right: Expr::Tuple,
610 },
611 }
612 "#);
613
614 // Parenthesization is required.
615 syn::parse_str::<Expr>("() == () == ()").unwrap_err();
616 }
617
618 #[test]
619 fn test_assign_range_precedence() {
620 // Range has higher precedence as the right-hand of an assignment, but
621 // ambiguous precedence as the left-hand of an assignment.
622 snapshot!("() = () .. ()" as Expr, @r#"
623 Expr::Assign {
624 left: Expr::Tuple,
625 right: Expr::Range {
626 start: Some(Expr::Tuple),
627 limits: RangeLimits::HalfOpen,
628 end: Some(Expr::Tuple),
629 },
630 }
631 "#);
632
633 snapshot!("() += () .. ()" as Expr, @r#"
634 Expr::Binary {
635 left: Expr::Tuple,
636 op: BinOp::AddAssign,
637 right: Expr::Range {
638 start: Some(Expr::Tuple),
639 limits: RangeLimits::HalfOpen,
640 end: Some(Expr::Tuple),
641 },
642 }
643 "#);
644
645 syn::parse_str::<Expr>("() .. () = ()").unwrap_err();
646 syn::parse_str::<Expr>("() .. () += ()").unwrap_err();
647 }
648
649 #[test]
650 fn test_chained_comparison() {
651 // https://github.com/dtolnay/syn/issues/1738
652 let _ = syn::parse_str::<Expr>("a = a < a <");
653 let _ = syn::parse_str::<Expr>("a = a .. a ..");
654 let _ = syn::parse_str::<Expr>("a = a .. a +=");
655
656 let err = syn::parse_str::<Expr>("a < a < a").unwrap_err();
657 assert_eq!("comparison operators cannot be chained", err.to_string());
658
659 let err = syn::parse_str::<Expr>("a .. a .. a").unwrap_err();
660 assert_eq!("unexpected token", err.to_string());
661
662 let err = syn::parse_str::<Expr>("a .. a += a").unwrap_err();
663 assert_eq!("unexpected token", err.to_string());
664 }
665
666 #[test]
667 fn test_fixup() {
668 struct FlattenParens;
669
670 impl VisitMut for FlattenParens {
671 fn visit_expr_mut(&mut self, e: &mut Expr) {
672 while let Expr::Paren(paren) = e {
673 *e = mem::replace(&mut *paren.expr, Expr::PLACEHOLDER);
674 }
675 visit_mut::visit_expr_mut(self, e);
676 }
677 }
678
679 for tokens in [
680 quote! { 2 * (1 + 1) },
681 quote! { 0 + (0 + 0) },
682 quote! { (a = b) = c },
683 quote! { (x as i32) < 0 },
684 quote! { 1 + (x as i32) < 0 },
685 quote! { (1 + 1).abs() },
686 quote! { (lo..hi)[..] },
687 quote! { (a..b)..(c..d) },
688 quote! { (&mut fut).await },
689 quote! { &mut (x as i32) },
690 quote! { -(x as i32) },
691 quote! { if (S {} == 1) {} },
692 quote! { { (m! {}) - 1 } },
693 quote! { match m { _ => ({}) - 1 } },
694 quote! { if let _ = (a && b) && c {} },
695 quote! { if let _ = (S {}) {} },
696 quote! { break ('a: loop { break 'a 1 } + 1) },
697 quote! { a + (|| b) + c },
698 quote! { if let _ = ((break) - 1 || true) {} },
699 quote! { if let _ = (break + 1 || true) {} },
700 quote! { (break)() },
701 quote! { (..) = () },
702 quote! { (..) += () },
703 quote! { (1 < 2) == (3 < 4) },
704 quote! { { (let _ = ()) } },
705 ] {
706 let original: Expr = syn::parse2(tokens).unwrap();
707
708 let mut flat = original.clone();
709 FlattenParens.visit_expr_mut(&mut flat);
710 let reconstructed: Expr = match syn::parse2(flat.to_token_stream()) {
711 Ok(reconstructed) => reconstructed,
712 Err(err) => panic!("failed to parse `{}`: {}", flat.to_token_stream(), err),
713 };
714
715 assert!(
716 original == reconstructed,
717 "original: {}\nreconstructed: {}",
718 original.to_token_stream(),
719 reconstructed.to_token_stream(),
720 );
721 }
722 }