Skip to content

Commit 1713ac4

Browse files
varkordlrobertson
authored andcommitted
Initial implementation of or patterns
1 parent ac60ca0 commit 1713ac4

File tree

17 files changed

+134
-26
lines changed

17 files changed

+134
-26
lines changed

src/librustc/cfg/construct.rs

+5
Original file line numberDiff line numberDiff line change
@@ -140,6 +140,11 @@ impl<'a, 'tcx> CFGBuilder<'a, 'tcx> {
140140
self.add_ast_node(pat.hir_id.local_id, &[pats_exit])
141141
}
142142

143+
PatKind::Or(ref pats) => {
144+
let branches: Vec<_> = pats.iter().map(|p| self.pat(p, pred)).collect();
145+
self.add_ast_node(pat.hir_id.local_id, &branches)
146+
}
147+
143148
PatKind::Slice(ref pre, ref vec, ref post) => {
144149
let pre_exit = self.pats_all(pre.iter(), pred);
145150
let vec_exit = self.pats_all(vec.iter(), pre_exit);

src/librustc/hir/intravisit.rs

+1
Original file line numberDiff line numberDiff line change
@@ -709,6 +709,7 @@ pub fn walk_pat<'v, V: Visitor<'v>>(visitor: &mut V, pattern: &'v Pat) {
709709
visitor.visit_pat(&field.pat)
710710
}
711711
}
712+
PatKind::Or(ref pats) => walk_list!(visitor, visit_pat, pats),
712713
PatKind::Tuple(ref tuple_elements, _) => {
713714
walk_list!(visitor, visit_pat, tuple_elements);
714715
}

src/librustc/hir/lowering.rs

+3
Original file line numberDiff line numberDiff line change
@@ -2669,6 +2669,9 @@ impl<'a> LoweringContext<'a> {
26692669
let (pats, ddpos) = self.lower_pat_tuple(pats, "tuple struct");
26702670
hir::PatKind::TupleStruct(qpath, pats, ddpos)
26712671
}
2672+
PatKind::Or(ref pats) => {
2673+
hir::PatKind::Or(pats.iter().map(|x| self.lower_pat(x)).collect())
2674+
}
26722675
PatKind::Path(ref qself, ref path) => {
26732676
let qpath = self.lower_qpath(
26742677
p.id,

src/librustc/hir/mod.rs

+4
Original file line numberDiff line numberDiff line change
@@ -882,6 +882,7 @@ impl Pat {
882882
PatKind::TupleStruct(_, ref s, _) | PatKind::Tuple(ref s, _) => {
883883
s.iter().all(|p| p.walk_(it))
884884
}
885+
PatKind::Or(ref pats) => pats.iter().all(|p| p.walk_(it)),
885886
PatKind::Box(ref s) | PatKind::Ref(ref s, _) => {
886887
s.walk_(it)
887888
}
@@ -976,6 +977,9 @@ pub enum PatKind {
976977
/// `0 <= position <= subpats.len()`
977978
TupleStruct(QPath, HirVec<P<Pat>>, Option<usize>),
978979

980+
/// An or-pattern `A | B | C`.
981+
Or(Vec<P<Pat>>),
982+
979983
/// A path pattern for an unit struct/variant or a (maybe-associated) constant.
980984
Path(QPath),
981985

src/librustc/hir/print.rs

+5-1
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@ use syntax::source_map::{SourceMap, Spanned};
44
use syntax::parse::ParseSess;
55
use syntax::print::pp::{self, Breaks};
66
use syntax::print::pp::Breaks::{Consistent, Inconsistent};
7-
use syntax::print::pprust::{self, Comments, PrintState};
7+
use syntax::print::pprust::{self, Comments, PrintState, SeparatorSpacing};
88
use syntax::symbol::kw;
99
use syntax::util::parser::{self, AssocOp, Fixity};
1010
use syntax_pos::{self, BytePos, FileName};
@@ -1687,6 +1687,10 @@ impl<'a> State<'a> {
16871687
self.s.space();
16881688
self.s.word("}");
16891689
}
1690+
PatKind::Or(ref pats) => {
1691+
let spacing = SeparatorSpacing::Both;
1692+
self.strsep("|", spacing, Inconsistent, &pats[..], |s, p| s.print_pat(&p))?;
1693+
}
16901694
PatKind::Tuple(ref elts, ddpos) => {
16911695
self.popen();
16921696
if let Some(ddpos) = ddpos {

src/librustc/middle/mem_categorization.rs

+6
Original file line numberDiff line numberDiff line change
@@ -1290,6 +1290,12 @@ impl<'a, 'tcx> MemCategorizationContext<'a, 'tcx> {
12901290
}
12911291
}
12921292

1293+
PatKind::Or(ref pats) => {
1294+
for pat in pats {
1295+
self.cat_pattern_(cmt.clone(), &pat, op)?;
1296+
}
1297+
}
1298+
12931299
PatKind::Binding(.., Some(ref subpat)) => {
12941300
self.cat_pattern_(cmt, &subpat, op)?;
12951301
}

src/librustc_mir/build/matches/mod.rs

+6
Original file line numberDiff line numberDiff line change
@@ -657,6 +657,12 @@ impl<'a, 'tcx> Builder<'a, 'tcx> {
657657
self.visit_bindings(&subpattern.pattern, subpattern_user_ty, f);
658658
}
659659
}
660+
PatternKind::Or { ref pats } => {
661+
// FIXME(#47184): extract or handle `pattern_user_ty` somehow
662+
for pat in pats {
663+
self.visit_bindings(&pat, &pattern_user_ty.clone(), f);
664+
}
665+
}
660666
}
661667
}
662668
}

src/librustc_mir/build/matches/simplify.rs

+4
Original file line numberDiff line numberDiff line change
@@ -195,6 +195,10 @@ impl<'a, 'tcx> Builder<'a, 'tcx> {
195195
candidate.match_pairs.push(MatchPair::new(place, subpattern));
196196
Ok(())
197197
}
198+
199+
PatternKind::Or { .. } => {
200+
Err(match_pair)
201+
}
198202
}
199203
}
200204
}

src/librustc_mir/build/matches/test.rs

+2
Original file line numberDiff line numberDiff line change
@@ -87,6 +87,7 @@ impl<'a, 'tcx> Builder<'a, 'tcx> {
8787
PatternKind::AscribeUserType { .. } |
8888
PatternKind::Array { .. } |
8989
PatternKind::Wild |
90+
PatternKind::Or { .. } |
9091
PatternKind::Binding { .. } |
9192
PatternKind::Leaf { .. } |
9293
PatternKind::Deref { .. } => {
@@ -130,6 +131,7 @@ impl<'a, 'tcx> Builder<'a, 'tcx> {
130131
PatternKind::Slice { .. } |
131132
PatternKind::Array { .. } |
132133
PatternKind::Wild |
134+
PatternKind::Or { .. } |
133135
PatternKind::Binding { .. } |
134136
PatternKind::AscribeUserType { .. } |
135137
PatternKind::Leaf { .. } |

src/librustc_mir/hair/pattern/_match.rs

+7-3
Original file line numberDiff line numberDiff line change
@@ -75,9 +75,6 @@
7575
/// D((r_1, p_(i,2), .., p_(i,n)))
7676
/// D((r_2, p_(i,2), .., p_(i,n)))
7777
///
78-
/// Note that the OR-patterns are not always used directly in Rust, but are used to derive
79-
/// the exhaustive integer matching rules, so they're written here for posterity.
80-
///
8178
/// The algorithm for computing `U`
8279
/// -------------------------------
8380
/// The algorithm is inductive (on the number of columns: i.e., components of tuple patterns).
@@ -1359,6 +1356,9 @@ fn pat_constructors<'tcx>(cx: &mut MatchCheckCtxt<'_, 'tcx>,
13591356
Some(vec![Slice(pat_len)])
13601357
}
13611358
}
1359+
PatternKind::Or { .. } => {
1360+
bug!("support for or-patterns has not been fully implemented yet.");
1361+
}
13621362
}
13631363
}
13641364

@@ -1884,6 +1884,10 @@ fn specialize<'p, 'a: 'p, 'tcx>(
18841884
"unexpected ctor {:?} for slice pat", constructor)
18851885
}
18861886
}
1887+
1888+
PatternKind::Or { .. } => {
1889+
bug!("support for or-patterns has not been fully implemented yet.");
1890+
}
18871891
};
18881892
debug!("specialize({:#?}, {:#?}) = {:#?}", r[0], wild_patterns, head);
18891893

src/librustc_mir/hair/pattern/mod.rs

+36-11
Original file line numberDiff line numberDiff line change
@@ -175,6 +175,11 @@ pub enum PatternKind<'tcx> {
175175
slice: Option<Pattern<'tcx>>,
176176
suffix: Vec<Pattern<'tcx>>,
177177
},
178+
179+
/// or-pattern
180+
Or {
181+
pats: Vec<Pattern<'tcx>>,
182+
},
178183
}
179184

180185
#[derive(Copy, Clone, Debug, PartialEq)]
@@ -186,6 +191,18 @@ pub struct PatternRange<'tcx> {
186191

187192
impl<'tcx> fmt::Display for Pattern<'tcx> {
188193
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
194+
// Printing lists is a chore.
195+
let mut first = true;
196+
let mut start_or_continue = |s| {
197+
if first {
198+
first = false;
199+
""
200+
} else {
201+
s
202+
}
203+
};
204+
let mut start_or_comma = || start_or_continue(", ");
205+
189206
match *self.kind {
190207
PatternKind::Wild => write!(f, "_"),
191208
PatternKind::AscribeUserType { ref subpattern, .. } =>
@@ -224,9 +241,6 @@ impl<'tcx> fmt::Display for Pattern<'tcx> {
224241
}
225242
};
226243

227-
let mut first = true;
228-
let mut start_or_continue = || if first { first = false; "" } else { ", " };
229-
230244
if let Some(variant) = variant {
231245
write!(f, "{}", variant.ident)?;
232246

@@ -241,12 +255,12 @@ impl<'tcx> fmt::Display for Pattern<'tcx> {
241255
continue;
242256
}
243257
let name = variant.fields[p.field.index()].ident;
244-
write!(f, "{}{}: {}", start_or_continue(), name, p.pattern)?;
258+
write!(f, "{}{}: {}", start_or_comma(), name, p.pattern)?;
245259
printed += 1;
246260
}
247261

248262
if printed < variant.fields.len() {
249-
write!(f, "{}..", start_or_continue())?;
263+
write!(f, "{}..", start_or_comma())?;
250264
}
251265

252266
return write!(f, " }}");
@@ -257,7 +271,7 @@ impl<'tcx> fmt::Display for Pattern<'tcx> {
257271
if num_fields != 0 || variant.is_none() {
258272
write!(f, "(")?;
259273
for i in 0..num_fields {
260-
write!(f, "{}", start_or_continue())?;
274+
write!(f, "{}", start_or_comma())?;
261275

262276
// Common case: the field is where we expect it.
263277
if let Some(p) = subpatterns.get(i) {
@@ -305,25 +319,29 @@ impl<'tcx> fmt::Display for Pattern<'tcx> {
305319
}
306320
PatternKind::Slice { ref prefix, ref slice, ref suffix } |
307321
PatternKind::Array { ref prefix, ref slice, ref suffix } => {
308-
let mut first = true;
309-
let mut start_or_continue = || if first { first = false; "" } else { ", " };
310322
write!(f, "[")?;
311323
for p in prefix {
312-
write!(f, "{}{}", start_or_continue(), p)?;
324+
write!(f, "{}{}", start_or_comma(), p)?;
313325
}
314326
if let Some(ref slice) = *slice {
315-
write!(f, "{}", start_or_continue())?;
327+
write!(f, "{}", start_or_comma())?;
316328
match *slice.kind {
317329
PatternKind::Wild => {}
318330
_ => write!(f, "{}", slice)?
319331
}
320332
write!(f, "..")?;
321333
}
322334
for p in suffix {
323-
write!(f, "{}{}", start_or_continue(), p)?;
335+
write!(f, "{}{}", start_or_comma(), p)?;
324336
}
325337
write!(f, "]")
326338
}
339+
PatternKind::Or { ref pats } => {
340+
for pat in pats {
341+
write!(f, "{}{}", start_or_continue(" | "), pat)?;
342+
}
343+
Ok(())
344+
}
327345
}
328346
}
329347
}
@@ -655,6 +673,12 @@ impl<'a, 'tcx> PatternContext<'a, 'tcx> {
655673

656674
self.lower_variant_or_leaf(res, pat.hir_id, pat.span, ty, subpatterns)
657675
}
676+
677+
PatKind::Or(ref pats) => {
678+
PatternKind::Or {
679+
pats: pats.iter().map(|p| self.lower_pattern(p)).collect(),
680+
}
681+
}
658682
};
659683

660684
Pattern {
@@ -1436,6 +1460,7 @@ impl<'tcx> PatternFoldable<'tcx> for PatternKind<'tcx> {
14361460
slice: slice.fold_with(folder),
14371461
suffix: suffix.fold_with(folder)
14381462
},
1463+
PatternKind::Or { ref pats } => PatternKind::Or { pats: pats.fold_with(folder) },
14391464
}
14401465
}
14411466
}

src/librustc_typeck/check/_match.rs

+8
Original file line numberDiff line numberDiff line change
@@ -53,6 +53,7 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
5353
let is_non_ref_pat = match pat.node {
5454
PatKind::Struct(..) |
5555
PatKind::TupleStruct(..) |
56+
PatKind::Or(_) |
5657
PatKind::Tuple(..) |
5758
PatKind::Box(_) |
5859
PatKind::Range(..) |
@@ -309,6 +310,13 @@ impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
309310
PatKind::Struct(ref qpath, ref fields, etc) => {
310311
self.check_pat_struct(pat, qpath, fields, etc, expected, def_bm, discrim_span)
311312
}
313+
PatKind::Or(ref pats) => {
314+
let expected_ty = self.structurally_resolved_type(pat.span, expected);
315+
for pat in pats {
316+
self.check_pat_walk(pat, expected, def_bm, false);
317+
}
318+
expected_ty
319+
}
312320
PatKind::Tuple(ref elements, ddpos) => {
313321
let mut expected_len = elements.len();
314322
if ddpos.is_some() {

src/librustdoc/clean/mod.rs

+3
Original file line numberDiff line numberDiff line change
@@ -4107,6 +4107,9 @@ fn name_from_pat(p: &hir::Pat) -> String {
41074107
if etc { ", .." } else { "" }
41084108
)
41094109
}
4110+
PatKind::Or(ref pats) => {
4111+
pats.iter().map(|p| name_from_pat(&**p)).collect::<Vec<String>>().join(" | ")
4112+
}
41104113
PatKind::Tuple(ref elts, _) => format!("({})", elts.iter().map(|p| name_from_pat(&**p))
41114114
.collect::<Vec<String>>().join(", ")),
41124115
PatKind::Box(ref p) => name_from_pat(&**p),

src/libsyntax/ast.rs

+7-3
Original file line numberDiff line numberDiff line change
@@ -572,9 +572,10 @@ impl Pat {
572572
match &self.node {
573573
PatKind::Ident(_, _, Some(p)) => p.walk(it),
574574
PatKind::Struct(_, fields, _) => fields.iter().all(|field| field.pat.walk(it)),
575-
PatKind::TupleStruct(_, s) | PatKind::Tuple(s) | PatKind::Slice(s) => {
576-
s.iter().all(|p| p.walk(it))
577-
}
575+
PatKind::TupleStruct(_, s)
576+
| PatKind::Tuple(s)
577+
| PatKind::Slice(s)
578+
| PatKind::Or(s) => s.iter().all(|p| p.walk(it)),
578579
PatKind::Box(s) | PatKind::Ref(s, _) | PatKind::Paren(s) => s.walk(it),
579580
PatKind::Wild
580581
| PatKind::Rest
@@ -648,6 +649,9 @@ pub enum PatKind {
648649
/// A tuple struct/variant pattern (`Variant(x, y, .., z)`).
649650
TupleStruct(Path, Vec<P<Pat>>),
650651

652+
/// An or-pattern `A | B | C`.
653+
Or(Vec<P<Pat>>),
654+
651655
/// A possibly qualified path pattern.
652656
/// Unqualified path patterns `A::B::C` can legally refer to variants, structs, constants
653657
/// or associated constants. Qualified path patterns `<A>::B::C`/`<A as Trait>::B::C` can

src/libsyntax/mut_visit.rs

+3-2
Original file line numberDiff line numberDiff line change
@@ -1050,15 +1050,16 @@ pub fn noop_visit_pat<T: MutVisitor>(pat: &mut P<Pat>, vis: &mut T) {
10501050
vis.visit_span(span);
10511051
};
10521052
}
1053-
PatKind::Tuple(elems) => visit_vec(elems, |elem| vis.visit_pat(elem)),
10541053
PatKind::Box(inner) => vis.visit_pat(inner),
10551054
PatKind::Ref(inner, _mutbl) => vis.visit_pat(inner),
10561055
PatKind::Range(e1, e2, Spanned { span: _, node: _ }) => {
10571056
vis.visit_expr(e1);
10581057
vis.visit_expr(e2);
10591058
vis.visit_span(span);
10601059
}
1061-
PatKind::Slice(elems) => visit_vec(elems, |elem| vis.visit_pat(elem)),
1060+
PatKind::Tuple(elems)
1061+
| PatKind::Slice(elems)
1062+
| PatKind::Or(elems) => visit_vec(elems, |elem| vis.visit_pat(elem)),
10621063
PatKind::Paren(inner) => vis.visit_pat(inner),
10631064
PatKind::Mac(mac) => vis.visit_mac(mac),
10641065
}

0 commit comments

Comments
 (0)