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