]> git.lizzy.rs Git - rust.git/blob - src/tools/rustfmt/tests/source/match.rs
Rollup merge of #107166 - petrochenkov:nooptable, r=oli-obk
[rust.git] / src / tools / rustfmt / tests / source / match.rs
1 // rustfmt-normalize_comments: true
2 // Match expressions.
3
4 fn foo() {
5     // A match expression.
6     match x {
7         // Some comment.
8         a => foo(),
9         b if 0 < 42 => foo(),
10         c => { // Another comment.
11             // Comment.
12             an_expression;
13             foo()
14         }
15         Foo(ref bar) =>
16             aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa,
17         Pattern1 | Pattern2 | Pattern3 => false,
18         Paternnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnn |
19         Paternnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnn => {
20             blah
21         }
22         Patternnnnnnnnnnnnnnnnnnn |
23         Patternnnnnnnnnnnnnnnnnnn |
24         Patternnnnnnnnnnnnnnnnnnn |
25         Patternnnnnnnnnnnnnnnnnnn => meh,
26
27         Patternnnnnnnnnnnnnnnnnnn |
28         Patternnnnnnnnnnnnnnnnnnn if looooooooooooooooooong_guard => meh,
29
30         Patternnnnnnnnnnnnnnnnnnnnnnnnn |
31         Patternnnnnnnnnnnnnnnnnnnnnnnnn if looooooooooooooooooooooooooooooooooooooooong_guard =>
32             meh,
33
34         // Test that earlier patterns can take the guard space
35         (aaaa, bbbbb, ccccccc, aaaaa, bbbbbbbb, cccccc, aaaa, bbbbbbbb, cccccc, dddddd) |
36         Patternnnnnnnnnnnnnnnnnnnnnnnnn if loooooooooooooooooooooooooooooooooooooooooong_guard => {}
37
38         _ => {}
39         ast::PathParameters::AngleBracketedParameters(ref data) if data.lifetimes.len() > 0 ||
40                                                                    data.types.len() > 0 ||
41                                                                    data.bindings.len() > 0 => {}
42     }
43
44     let whatever = match something {
45         /// DOC COMMENT!
46         Some(_) => 42,
47         // Comment on an attribute.
48         #[an_attribute]
49         // Comment after an attribute.
50         None => 0,
51         #[rustfmt::skip]
52         Blurb     =>     {                  }
53     };
54 }
55
56 // Test that a match on an overflow line is laid out properly.
57 fn main() {
58     let sub_span =
59         match xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx {
60             Some(sub_span) => Some(sub_span),
61             None => sub_span,
62         };
63 }
64
65 // Test that one-line bodies align.
66 fn main() {
67     match r {
68         Variableeeeeeeeeeeeeeeeee => (    "variable",
69                                       vec!("id", "name", "qualname",
70                                            "value", "type", "scopeid"),
71                                       true,
72                                       true),
73         Enummmmmmmmmmmmmmmmmmmmm => ("enum",
74                                      vec!("id","qualname","scopeid","value"),
75                                      true,
76                                      true),
77         Variantttttttttttttttttttttttt => ("variant",
78                                            vec!("id",
79                                                 "name",
80                                                 "qualname",
81                                                 "type",
82                                                 "value",
83                                                 "scopeid"),
84                                            true,
85                                            true),
86     };
87
88     match  x{
89     y=>{/*Block with comment. Preserve me.*/  }
90     z=>{stmt();} }
91 }
92
93 fn matches() {
94     match 1 {
95         -1 => 10,
96         1 => 1, // foo
97         2 => 2,
98         // bar
99         3 => 3,
100         _ => 0 // baz
101     }
102 }
103
104 fn match_skip() {
105     let _ = match Some(1) {
106         #[rustfmt::skip]
107         Some( n ) => n,
108         None      => 1,
109     };
110 }
111
112 fn issue339() {
113     match a {
114         b => {}
115         c => { }
116         d => {
117         }
118         e => {
119
120
121
122         }
123         // collapsing here is safe
124         ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff => {
125         }
126         // collapsing here exceeds line length
127         ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffg => {
128         }
129         h => { // comment above block
130         }
131         i => {
132         } // comment below block
133         j => {
134             // comment inside block
135         }
136         j2 => {
137             // comments inside...
138         } // ... and after
139         // TODO uncomment when vertical whitespace is handled better
140         // k => {
141         //
142         //     // comment with WS above
143         // }
144         // l => {
145         //     // comment with ws below
146         //     
147         // }
148         m => {
149         } n => { } o =>
150         {
151
152         }
153         p => { // Don't collapse me
154         } q => { } r =>
155         {
156
157         }
158         s => 0, // s comment
159         // t comment
160         t => 1,
161         u => 2,
162         v => {
163         } /* funky block
164            * comment */
165         // final comment
166     }
167 }
168
169 fn issue355() {
170     match mac {
171         a => println!("a", b),
172         b => vec!(1, 2),
173         c => vec!(3; 4),
174         d => {
175             println!("a", b)
176         }
177         e => {
178             vec!(1, 2)
179         }
180         f => {
181             vec!(3; 4)
182         }
183         h => println!("a", b), // h comment
184         i => vec!(1, 2), // i comment
185         j => vec!(3; 4), // j comment
186         // k comment
187         k => println!("a", b),
188         // l comment
189         l => vec!(1, 2),
190         // m comment
191         m => vec!(3; 4),
192         // Rewrite splits macro
193         nnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnn => println!("a", b),
194         // Rewrite splits macro
195         oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo => vec!(1, 2),
196         // Macro support fails to recognise this macro as splittable
197         // We push the whole expr to a new line, TODO split this macro as well
198         pppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppp => vec!(3; 4),
199         // q, r and s: Rewrite splits match arm
200         qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq => println!("a", b),
201         rrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrr => vec!(1, 2),
202         ssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssss => vec!(3; 4),
203         // Funky bracketing styles
204         t =>      println!{"a", b},
205         u => vec!{1, 2},
206         v => vec!{3; 4},
207         w => println!["a", b],
208         x =>      vec![1, 2],
209         y =>vec![3; 4],
210         // Brackets with comments
211         tc => println!{"a", b}, // comment
212         uc => vec!{1, 2}, // comment
213         vc =>vec!{3; 4}, // comment
214         wc =>println!["a", b], // comment
215         xc => vec![1,2], // comment
216         yc =>        vec![3; 4], // comment
217         yd =>
218             looooooooooooooooooooooooooooooooooooooooooooooooooooooooong_func(aaaaaaaaaa,
219                                                                               bbbbbbbbbb,
220                                                                               cccccccccc,
221                                                                               dddddddddd),
222     }
223 }
224
225 fn issue280() {
226     {
227         match x {
228             CompressionMode::DiscardNewline | CompressionMode::CompressWhitespaceNewline => ch ==
229                                                                                             '\n',
230             ast::ItemConst(ref typ, ref expr) => self.process_static_or_const_item(item,
231                                                                                    &typ,
232                                                                                    &expr),
233         }
234     }
235 }
236
237 fn issue383() {
238     match resolution.last_private {LastImport{..} => false, _ => true};
239 }
240
241 fn issue507() {
242     match 1 {
243         1 => unsafe { std::intrinsics::abort() },
244         _ => (),
245     }
246 }
247
248 fn issue508() {
249     match s.type_id() {
250         Some(NodeTypeId::Element(ElementTypeId::HTMLElement(
251                     HTMLElementTypeId::HTMLCanvasElement))) => true,
252         Some(NodeTypeId::Element(ElementTypeId::HTMLElement(
253                         HTMLElementTypeId::HTMLObjectElement))) => s.has_object_data(),
254         Some(NodeTypeId::Element(_)) => false,
255     }
256 }
257
258 fn issue496() {{{{
259     match def {
260         def::DefConst(def_id) | def::DefAssociatedConst(def_id) =>
261             match const_eval::lookup_const_by_id(cx.tcx, def_id, Some(self.pat.id)) {
262                 Some(const_expr) => { x }}}}}}}
263
264 fn issue494() {
265     {
266         match stmt.node {
267              hir::StmtExpr(ref expr, id) | hir::StmtSemi(ref expr, id) =>
268                 result.push(
269                     StmtRef::Mirror(
270                         Box::new(Stmt { span: stmt.span,
271                                         kind: StmtKind::Expr {
272                                             scope: cx.tcx.region_maps.node_extent(id),
273                                             expr: expr.to_ref() } }))),
274         }
275     }
276 }
277
278 fn issue386() {
279     match foo {
280         BiEq | BiLt | BiLe | BiNe | BiGt | BiGe =>
281                     true,
282         BiAnd | BiOr | BiAdd | BiSub | BiMul | BiDiv | BiRem |
283         BiBitXor | BiBitAnd | BiBitOr | BiShl | BiShr =>
284             false,
285     }
286 }
287
288 fn guards() {
289     match foo {
290         aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa if foooooooooooooo && barrrrrrrrrrrr => {}
291         aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa | aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa if foooooooooooooo && barrrrrrrrrrrr => {}
292         aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
293             if fooooooooooooooooooooo &&
294                (bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb || cccccccccccccccccccccccccccccccccccccccc) => {}
295     }
296 }
297
298 fn issue1371() {
299     Some(match type_ {
300         sfEvtClosed => Closed,
301         sfEvtResized => {
302             let e = unsafe { *event.size.as_ref() };
303
304             Resized {
305                 width: e.width,
306                 height: e.height,
307             }
308         }
309         sfEvtLostFocus => LostFocus,
310         sfEvtGainedFocus => GainedFocus,
311         sfEvtTextEntered => {
312             TextEntered {
313                 unicode: unsafe {
314                     ::std::char::from_u32((*event.text.as_ref()).unicode)
315                         .expect("Invalid unicode encountered on TextEntered event")
316                 },
317             }
318         }
319         sfEvtKeyPressed => {
320             let e = unsafe { event.key.as_ref() };
321
322             KeyPressed {
323                 code: unsafe { ::std::mem::transmute(e.code) },
324                 alt: e.alt.to_bool(),
325                 ctrl: e.control.to_bool(),
326                 shift: e.shift.to_bool(),
327                 system: e.system.to_bool(),
328             }
329         }
330         sfEvtKeyReleased => {
331             let e = unsafe { event.key.as_ref() };
332
333             KeyReleased {
334                 code: unsafe { ::std::mem::transmute(e.code) },
335                 alt: e.alt.to_bool(),
336                 ctrl: e.control.to_bool(),
337                 shift: e.shift.to_bool(),
338                 system: e.system.to_bool(),
339             }
340         }
341     })
342 }
343
344 fn issue1395() {
345     let bar = Some(true);
346     let foo = Some(true);
347     let mut x = false;
348     bar.and_then(|_| {
349         match foo {
350             None => None,
351             Some(b) => {
352                 x = true;
353                 Some(b)
354             }
355         }
356     });
357 }
358
359 fn issue1456() {
360     Ok(Recording {
361         artists: match reader.evaluate(".//mb:recording/mb:artist-credit/mb:name-credit")? {
362             Nodeset(nodeset) => {
363                 let res: Result<Vec<ArtistRef>, ReadError> = nodeset
364                     .iter()
365                     .map(|node| {
366                         XPathNodeReader::new(node, &context).and_then(|r| ArtistRef::from_xml(&r))
367                     })
368                     .collect();
369                 res?
370             }
371             _ => Vec::new(),
372         },
373     })
374 }
375
376 fn issue1460() {
377     let _ = match foo {
378         REORDER_BUFFER_CHANGE_INTERNAL_SPEC_INSERT => "internal_spec_insert_internal_spec_insert_internal_spec_insert",
379         _ => "reorder_something",
380     };
381 }
382
383 fn issue525() {
384     foobar(f, "{}", match *self {
385         TaskState::Started => "started",
386         TaskState::Success => "success",
387         TaskState::Failed => "failed",
388     });
389 }
390
391 // #1838, #1839
392 fn match_with_near_max_width() {
393     let (this_line_uses_99_characters_and_is_formatted_properly, x012345) = match some_expression   {
394         _ => unimplemented!(),
395     };
396
397     let (should_be_formatted_like_the_line_above_using_100_characters, x0) = match some_expression  {
398         _ => unimplemented!(),
399     };
400
401     let (should_put_the_brace_on_the_next_line_using_101_characters, x0000) = match some_expression
402     {
403         _ => unimplemented!(),
404     };
405     match m {
406         Variant::Tag | Variant::Tag2 | Variant::Tag3 | Variant::Tag4 | Variant::Tag5 | Variant::Tag6 =>
407         {}
408     }
409 }
410
411 fn match_with_trailing_spaces() {
412     match x {    
413         
414         Some(..) => 0,
415         None => 1,
416     }
417 }
418
419 fn issue_2099() {
420     let a = match x {
421 };
422     let b = match x {
423         
424     };
425
426     match x {}
427 }
428
429 // #2021
430 impl<'tcx> Const<'tcx> {
431     pub fn from_constval<'a>() -> Const<'tcx> {
432         let val = match *cv {
433             ConstVal::Variant(_) | ConstVal::Aggregate(..) | ConstVal::Unevaluated(..) => bug!("MIR must not use `{:?}` (aggregates are expanded to MIR rvalues)", cv),
434         };
435     }
436 }
437
438 // #2151
439 fn issue_2151() {
440     match either {
441         x => {
442
443         }y => ()
444     }
445 }
446
447 // #2152
448 fn issue_2152() {
449     match m {
450         "aaaaaaaaaaaaa" | "bbbbbbbbbbbbb" | "cccccccccccccccccccccccccccccccccccccccccccc" if true => {}
451         "bind" | "writev" | "readv" | "sendmsg" | "recvmsg" if android && (aarch64 || x86_64) => true,
452     }
453 }
454
455 // #2376
456 // Preserve block around expressions with condition.
457 fn issue_2376() {
458     let mut x = None;
459     match x {
460         Some(0) => {
461             for i in 1..11 {
462                 x = Some(i);
463             }
464         }
465         Some(ref mut y) => {
466             while *y < 10 {
467                 *y += 1;
468             }
469         }
470         None => {
471             while let None = x {
472                 x = Some(10);
473             }
474         }
475     }
476 }
477
478 // #2621
479 // Strip leading `|` in match arm patterns
480 fn issue_2621() {
481     let x = Foo::A;
482     match x {
483         Foo::A => println!("No vert single condition"),
484         Foo::B | Foo::C => println!("Center vert two conditions"),
485         | Foo::D => println!("Preceding vert single condition"),
486         | Foo::E
487         | Foo::F => println!("Preceding vert over two lines"),
488         Foo::G |
489         Foo::H => println!("Trailing vert over two lines"),
490         // Comment on its own line
491         | Foo::I => println!("With comment"), // Comment after line
492     }
493 }
494
495 fn issue_2377() {
496     match tok {
497         Tok::Not
498         | Tok::BNot
499         | Tok::Plus
500         | Tok::Minus
501         | Tok::PlusPlus
502         | Tok::MinusMinus
503         | Tok::Void
504         | Tok::Delete if prec <= 16 => {
505             // code here...
506         }
507         Tok::TypeOf if prec <= 16 => {}
508     }
509 }
510
511 // #3040
512 fn issue_3040() {
513     {
514         match foo {
515             DevtoolScriptControlMsg::WantsLiveNotifications(id, to_send) => {
516                 match documents.find_window(id) {
517                     Some(window) => devtools::handle_wants_live_notifications(window.upcast(), to_send),
518                     None => return warn!("Message sent to closed pipeline {}.", id),
519                 }
520             }
521         }
522     }
523 }
524
525 // #3030
526 fn issue_3030() {
527     match input.trim().parse::<f64>() {
528         Ok(val)
529             if !(
530     // A valid number is the same as what rust considers to be valid,
531     // except for +1., NaN, and Infinity.
532                 val.is_infinite() || val
533                     .is_nan() || input.ends_with(".") || input.starts_with("+")
534             )
535             => {
536             }
537     }
538 }
539
540 fn issue_3005() {
541             match *token {
542                  Token::Dimension {
543                      value, ref unit, ..
544                  } if num_context.is_ok(context.parsing_mode, value) =>
545                  {
546                      return NoCalcLength::parse_dimension(context, value, unit)
547                          .map(LengthOrPercentage::Length)
548                          .map_err(|()| location.new_unexpected_token_error(token.clone()));
549                  },
550              }
551 }
552
553 // #3774
554 fn issue_3774() {
555     {
556         {
557             {
558                 match foo {
559                     Lam(_, _, _) | Pi(_, _, _) | Let(_, _, _, _) | Embed(_) | Var(_) => unreachab(),
560                     Lam(_, _, _) | Pi(_, _, _) | Let(_, _, _, _) | Embed(_) | Var(_) => unreacha!(),
561                     Lam(_, _, _) | Pi(_, _, _) | Let(_, _, _, _) | Embed(_) | Var(_) => unreachabl(),
562                     Lam(_, _, _) | Pi(_, _, _) | Let(_, _, _, _) | Embed(_) | Var(_) => unreachae!(),
563                     Lam(_, _, _) | Pi(_, _, _) | Let(_, _, _, _) | Embed(_) | Var(_) => unreachable(),
564                     Lam(_, _, _) | Pi(_, _, _) | Let(_, _, _, _) | Embed(_) | Var(_) => unreachable!(),
565                     Lam(_, _, _) | Pi(_, _, _) | Let(_, _, _, _) | Embed(_) | Var(_) => rrunreachable!(),
566                 }
567             }
568         }
569     }
570 }
571
572 // #4109
573 fn issue_4109() {
574     match () {
575         _ => {
576 #[cfg(debug_assertions)]
577 {
578 println!("Foo");
579 }
580 }
581 }
582
583 match () {
584 _ => {
585 #[allow(unsafe_code)]
586 unsafe {}
587 }
588 }
589 }