]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_hir/src/pat_util.rs
Auto merge of #81427 - klensy:eat-digits, r=m-ou-se
[rust.git] / compiler / rustc_hir / src / pat_util.rs
1 use crate::def::{CtorOf, DefKind, Res};
2 use crate::def_id::DefId;
3 use crate::hir::{self, HirId, PatKind};
4 use rustc_span::symbol::Ident;
5 use rustc_span::Span;
6
7 use std::iter::{Enumerate, ExactSizeIterator};
8
9 pub struct EnumerateAndAdjust<I> {
10     enumerate: Enumerate<I>,
11     gap_pos: usize,
12     gap_len: usize,
13 }
14
15 impl<I> Iterator for EnumerateAndAdjust<I>
16 where
17     I: Iterator,
18 {
19     type Item = (usize, <I as Iterator>::Item);
20
21     fn next(&mut self) -> Option<(usize, <I as Iterator>::Item)> {
22         self.enumerate
23             .next()
24             .map(|(i, elem)| (if i < self.gap_pos { i } else { i + self.gap_len }, elem))
25     }
26
27     fn size_hint(&self) -> (usize, Option<usize>) {
28         self.enumerate.size_hint()
29     }
30 }
31
32 pub trait EnumerateAndAdjustIterator {
33     fn enumerate_and_adjust(
34         self,
35         expected_len: usize,
36         gap_pos: Option<usize>,
37     ) -> EnumerateAndAdjust<Self>
38     where
39         Self: Sized;
40 }
41
42 impl<T: ExactSizeIterator> EnumerateAndAdjustIterator for T {
43     fn enumerate_and_adjust(
44         self,
45         expected_len: usize,
46         gap_pos: Option<usize>,
47     ) -> EnumerateAndAdjust<Self>
48     where
49         Self: Sized,
50     {
51         let actual_len = self.len();
52         EnumerateAndAdjust {
53             enumerate: self.enumerate(),
54             gap_pos: gap_pos.unwrap_or(expected_len),
55             gap_len: expected_len - actual_len,
56         }
57     }
58 }
59
60 impl hir::Pat<'_> {
61     /// Call `f` on every "binding" in a pattern, e.g., on `a` in
62     /// `match foo() { Some(a) => (), None => () }`
63     pub fn each_binding(&self, mut f: impl FnMut(hir::BindingAnnotation, HirId, Span, Ident)) {
64         self.walk_always(|p| {
65             if let PatKind::Binding(binding_mode, _, ident, _) = p.kind {
66                 f(binding_mode, p.hir_id, p.span, ident);
67             }
68         });
69     }
70
71     /// Call `f` on every "binding" in a pattern, e.g., on `a` in
72     /// `match foo() { Some(a) => (), None => () }`.
73     ///
74     /// When encountering an or-pattern `p_0 | ... | p_n` only `p_0` will be visited.
75     pub fn each_binding_or_first(
76         &self,
77         f: &mut impl FnMut(hir::BindingAnnotation, HirId, Span, Ident),
78     ) {
79         self.walk(|p| match &p.kind {
80             PatKind::Or(ps) => {
81                 ps[0].each_binding_or_first(f);
82                 false
83             }
84             PatKind::Binding(bm, _, ident, _) => {
85                 f(*bm, p.hir_id, p.span, *ident);
86                 true
87             }
88             _ => true,
89         })
90     }
91
92     /// Checks if the pattern contains any patterns that bind something to
93     /// an ident, e.g., `foo`, or `Foo(foo)` or `foo @ Bar(..)`.
94     pub fn contains_bindings(&self) -> bool {
95         self.satisfies(|p| matches!(p.kind, PatKind::Binding(..)))
96     }
97
98     /// Checks if the pattern satisfies the given predicate on some sub-pattern.
99     fn satisfies(&self, pred: impl Fn(&hir::Pat<'_>) -> bool) -> bool {
100         let mut satisfies = false;
101         self.walk_short(|p| {
102             if pred(p) {
103                 satisfies = true;
104                 false // Found one, can short circuit now.
105             } else {
106                 true
107             }
108         });
109         satisfies
110     }
111
112     pub fn simple_ident(&self) -> Option<Ident> {
113         match self.kind {
114             PatKind::Binding(
115                 hir::BindingAnnotation::Unannotated | hir::BindingAnnotation::Mutable,
116                 _,
117                 ident,
118                 None,
119             ) => Some(ident),
120             _ => None,
121         }
122     }
123
124     /// Returns variants that are necessary to exist for the pattern to match.
125     pub fn necessary_variants(&self) -> Vec<DefId> {
126         let mut variants = vec![];
127         self.walk(|p| match &p.kind {
128             PatKind::Or(_) => false,
129             PatKind::Path(hir::QPath::Resolved(_, path))
130             | PatKind::TupleStruct(hir::QPath::Resolved(_, path), ..)
131             | PatKind::Struct(hir::QPath::Resolved(_, path), ..) => {
132                 if let Res::Def(DefKind::Variant | DefKind::Ctor(CtorOf::Variant, ..), id) =
133                     path.res
134                 {
135                     variants.push(id);
136                 }
137                 true
138             }
139             _ => true,
140         });
141         variants.sort();
142         variants.dedup();
143         variants
144     }
145
146     /// Checks if the pattern contains any `ref` or `ref mut` bindings, and if
147     /// yes whether it contains mutable or just immutables ones.
148     //
149     // FIXME(tschottdorf): this is problematic as the HIR is being scraped, but
150     // ref bindings are be implicit after #42640 (default match binding modes). See issue #44848.
151     pub fn contains_explicit_ref_binding(&self) -> Option<hir::Mutability> {
152         let mut result = None;
153         self.each_binding(|annotation, _, _, _| match annotation {
154             hir::BindingAnnotation::Ref => match result {
155                 None | Some(hir::Mutability::Not) => result = Some(hir::Mutability::Not),
156                 _ => {}
157             },
158             hir::BindingAnnotation::RefMut => result = Some(hir::Mutability::Mut),
159             _ => {}
160         });
161         result
162     }
163 }