]> git.lizzy.rs Git - rust.git/blob - tests/target/match.rs
Merge pull request #3576 from rchaser53/issue-3567
[rust.git] / 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 => {
130             // comment above block
131         }
132         i => {} // 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 => {}
150         o => {}
151         p => {
152             // Don't collapse me
153         }
154         q => {}
155         r => {}
156         s => 0, // s comment
157         // t comment
158         t => 1,
159         u => 2,
160         v => {} /* funky block
161                  * comment */
162                 /* final comment */
163     }
164 }
165
166 fn issue355() {
167     match mac {
168         a => println!("a", b),
169         b => vec![1, 2],
170         c => vec![3; 4],
171         d => println!("a", b),
172         e => vec![1, 2],
173         f => vec![3; 4],
174         h => println!("a", b), // h comment
175         i => vec![1, 2],       // i comment
176         j => vec![3; 4],       // j comment
177         // k comment
178         k => println!("a", b),
179         // l comment
180         l => vec![1, 2],
181         // m comment
182         m => vec![3; 4],
183         // Rewrite splits macro
184         nnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnn => {
185             println!("a", b)
186         }
187         // Rewrite splits macro
188         oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo => {
189             vec![1, 2]
190         }
191         // Macro support fails to recognise this macro as splittable
192         // We push the whole expr to a new line, TODO split this macro as well
193         pppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppppp => {
194             vec![3; 4]
195         }
196         // q, r and s: Rewrite splits match arm
197         qqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqqq => {
198             println!("a", b)
199         }
200         rrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrr => {
201             vec![1, 2]
202         }
203         ssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssssss => {
204             vec![3; 4]
205         }
206         // Funky bracketing styles
207         t => println! {"a", b},
208         u => vec![1, 2],
209         v => vec![3; 4],
210         w => println!["a", b],
211         x => vec![1, 2],
212         y => vec![3; 4],
213         // Brackets with comments
214         tc => println! {"a", b}, // comment
215         uc => vec![1, 2],        // comment
216         vc => vec![3; 4],        // comment
217         wc => println!["a", b],  // comment
218         xc => vec![1, 2],        // comment
219         yc => vec![3; 4],        // comment
220         yd => looooooooooooooooooooooooooooooooooooooooooooooooooooooooong_func(
221             aaaaaaaaaa, bbbbbbbbbb, cccccccccc, dddddddddd,
222         ),
223     }
224 }
225
226 fn issue280() {
227     {
228         match x {
229             CompressionMode::DiscardNewline | CompressionMode::CompressWhitespaceNewline => {
230                 ch == '\n'
231             }
232             ast::ItemConst(ref typ, ref expr) => {
233                 self.process_static_or_const_item(item, &typ, &expr)
234             }
235         }
236     }
237 }
238
239 fn issue383() {
240     match resolution.last_private {
241         LastImport { .. } => false,
242         _ => true,
243     };
244 }
245
246 fn issue507() {
247     match 1 {
248         1 => unsafe { std::intrinsics::abort() },
249         _ => (),
250     }
251 }
252
253 fn issue508() {
254     match s.type_id() {
255         Some(NodeTypeId::Element(ElementTypeId::HTMLElement(
256             HTMLElementTypeId::HTMLCanvasElement,
257         ))) => true,
258         Some(NodeTypeId::Element(ElementTypeId::HTMLElement(
259             HTMLElementTypeId::HTMLObjectElement,
260         ))) => s.has_object_data(),
261         Some(NodeTypeId::Element(_)) => false,
262     }
263 }
264
265 fn issue496() {
266     {
267         {
268             {
269                 match def {
270                     def::DefConst(def_id) | def::DefAssociatedConst(def_id) => {
271                         match const_eval::lookup_const_by_id(cx.tcx, def_id, Some(self.pat.id)) {
272                             Some(const_expr) => x,
273                         }
274                     }
275                 }
276             }
277         }
278     }
279 }
280
281 fn issue494() {
282     {
283         match stmt.node {
284             hir::StmtExpr(ref expr, id) | hir::StmtSemi(ref expr, id) => {
285                 result.push(StmtRef::Mirror(Box::new(Stmt {
286                     span: stmt.span,
287                     kind: StmtKind::Expr {
288                         scope: cx.tcx.region_maps.node_extent(id),
289                         expr: expr.to_ref(),
290                     },
291                 })))
292             }
293         }
294     }
295 }
296
297 fn issue386() {
298     match foo {
299         BiEq | BiLt | BiLe | BiNe | BiGt | BiGe => true,
300         BiAnd | BiOr | BiAdd | BiSub | BiMul | BiDiv | BiRem | BiBitXor | BiBitAnd | BiBitOr
301         | BiShl | BiShr => false,
302     }
303 }
304
305 fn guards() {
306     match foo {
307         aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
308             if foooooooooooooo && barrrrrrrrrrrr => {}
309         aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
310         | aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
311             if foooooooooooooo && barrrrrrrrrrrr => {}
312         aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
313             if fooooooooooooooooooooo
314                 && (bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb
315                     || cccccccccccccccccccccccccccccccccccccccc) => {}
316     }
317 }
318
319 fn issue1371() {
320     Some(match type_ {
321         sfEvtClosed => Closed,
322         sfEvtResized => {
323             let e = unsafe { *event.size.as_ref() };
324
325             Resized {
326                 width: e.width,
327                 height: e.height,
328             }
329         }
330         sfEvtLostFocus => LostFocus,
331         sfEvtGainedFocus => GainedFocus,
332         sfEvtTextEntered => TextEntered {
333             unicode: unsafe {
334                 ::std::char::from_u32((*event.text.as_ref()).unicode)
335                     .expect("Invalid unicode encountered on TextEntered event")
336             },
337         },
338         sfEvtKeyPressed => {
339             let e = unsafe { event.key.as_ref() };
340
341             KeyPressed {
342                 code: unsafe { ::std::mem::transmute(e.code) },
343                 alt: e.alt.to_bool(),
344                 ctrl: e.control.to_bool(),
345                 shift: e.shift.to_bool(),
346                 system: e.system.to_bool(),
347             }
348         }
349         sfEvtKeyReleased => {
350             let e = unsafe { event.key.as_ref() };
351
352             KeyReleased {
353                 code: unsafe { ::std::mem::transmute(e.code) },
354                 alt: e.alt.to_bool(),
355                 ctrl: e.control.to_bool(),
356                 shift: e.shift.to_bool(),
357                 system: e.system.to_bool(),
358             }
359         }
360     })
361 }
362
363 fn issue1395() {
364     let bar = Some(true);
365     let foo = Some(true);
366     let mut x = false;
367     bar.and_then(|_| match foo {
368         None => None,
369         Some(b) => {
370             x = true;
371             Some(b)
372         }
373     });
374 }
375
376 fn issue1456() {
377     Ok(Recording {
378         artists: match reader.evaluate(".//mb:recording/mb:artist-credit/mb:name-credit")? {
379             Nodeset(nodeset) => {
380                 let res: Result<Vec<ArtistRef>, ReadError> = nodeset
381                     .iter()
382                     .map(|node| {
383                         XPathNodeReader::new(node, &context).and_then(|r| ArtistRef::from_xml(&r))
384                     })
385                     .collect();
386                 res?
387             }
388             _ => Vec::new(),
389         },
390     })
391 }
392
393 fn issue1460() {
394     let _ = match foo {
395         REORDER_BUFFER_CHANGE_INTERNAL_SPEC_INSERT => {
396             "internal_spec_insert_internal_spec_insert_internal_spec_insert"
397         }
398         _ => "reorder_something",
399     };
400 }
401
402 fn issue525() {
403     foobar(
404         f,
405         "{}",
406         match *self {
407             TaskState::Started => "started",
408             TaskState::Success => "success",
409             TaskState::Failed => "failed",
410         },
411     );
412 }
413
414 // #1838, #1839
415 fn match_with_near_max_width() {
416     let (this_line_uses_99_characters_and_is_formatted_properly, x012345) = match some_expression {
417         _ => unimplemented!(),
418     };
419
420     let (should_be_formatted_like_the_line_above_using_100_characters, x0) = match some_expression {
421         _ => unimplemented!(),
422     };
423
424     let (should_put_the_brace_on_the_next_line_using_101_characters, x0000) = match some_expression
425     {
426         _ => unimplemented!(),
427     };
428     match m {
429         Variant::Tag
430         | Variant::Tag2
431         | Variant::Tag3
432         | Variant::Tag4
433         | Variant::Tag5
434         | Variant::Tag6 => {}
435     }
436 }
437
438 fn match_with_trailing_spaces() {
439     match x {
440         #![allow(simple_match)]
441         Some(..) => 0,
442         None => 1,
443     }
444 }
445
446 fn issue_2099() {
447     let a = match x {};
448     let b = match x {};
449
450     match x {}
451 }
452
453 // #2021
454 impl<'tcx> Const<'tcx> {
455     pub fn from_constval<'a>() -> Const<'tcx> {
456         let val = match *cv {
457             ConstVal::Variant(_) | ConstVal::Aggregate(..) | ConstVal::Unevaluated(..) => bug!(
458                 "MIR must not use `{:?}` (aggregates are expanded to MIR rvalues)",
459                 cv
460             ),
461         };
462     }
463 }
464
465 // #2151
466 fn issue_2151() {
467     match either {
468         x => {}
469         y => (),
470     }
471 }
472
473 // #2152
474 fn issue_2152() {
475     match m {
476         "aaaaaaaaaaaaa" | "bbbbbbbbbbbbb" | "cccccccccccccccccccccccccccccccccccccccccccc"
477             if true => {}
478         "bind" | "writev" | "readv" | "sendmsg" | "recvmsg" if android && (aarch64 || x86_64) => {
479             true
480         }
481     }
482 }
483
484 // #2376
485 // Preserve block around expressions with condition.
486 fn issue_2376() {
487     let mut x = None;
488     match x {
489         Some(0) => {
490             for i in 1..11 {
491                 x = Some(i);
492             }
493         }
494         Some(ref mut y) => {
495             while *y < 10 {
496                 *y += 1;
497             }
498         }
499         None => {
500             while let None = x {
501                 x = Some(10);
502             }
503         }
504     }
505 }
506
507 // #2621
508 // Strip leading `|` in match arm patterns
509 fn issue_2621() {
510     let x = Foo::A;
511     match x {
512         Foo::A => println!("No vert single condition"),
513         Foo::B | Foo::C => println!("Center vert two conditions"),
514         Foo::D => println!("Preceding vert single condition"),
515         Foo::E | Foo::F => println!("Preceding vert over two lines"),
516         Foo::G | Foo::H => println!("Trailing vert over two lines"),
517         // Comment on its own line
518         Foo::I => println!("With comment"), // Comment after line
519     }
520 }
521
522 fn issue_2377() {
523     match tok {
524         Tok::Not
525         | Tok::BNot
526         | Tok::Plus
527         | Tok::Minus
528         | Tok::PlusPlus
529         | Tok::MinusMinus
530         | Tok::Void
531         | Tok::Delete
532             if prec <= 16 =>
533         {
534             // code here...
535         }
536         Tok::TypeOf if prec <= 16 => {}
537     }
538 }
539
540 // #3040
541 fn issue_3040() {
542     {
543         match foo {
544             DevtoolScriptControlMsg::WantsLiveNotifications(id, to_send) => {
545                 match documents.find_window(id) {
546                     Some(window) => {
547                         devtools::handle_wants_live_notifications(window.upcast(), to_send)
548                     }
549                     None => return warn!("Message sent to closed pipeline {}.", id),
550                 }
551             }
552         }
553     }
554 }
555
556 // #3030
557 fn issue_3030() {
558     match input.trim().parse::<f64>() {
559         Ok(val)
560             if !(
561                 // A valid number is the same as what rust considers to be valid,
562                 // except for +1., NaN, and Infinity.
563                 val.is_infinite() || val.is_nan() || input.ends_with(".") || input.starts_with("+")
564             ) => {}
565     }
566 }
567
568 fn issue_3005() {
569     match *token {
570         Token::Dimension {
571             value, ref unit, ..
572         } if num_context.is_ok(context.parsing_mode, value) => {
573             return NoCalcLength::parse_dimension(context, value, unit)
574                 .map(LengthOrPercentage::Length)
575                 .map_err(|()| location.new_unexpected_token_error(token.clone()));
576         }
577     }
578 }