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