rustc_hir_typeck/fn_ctxt/
arg_matrix.rs1use core::cmp::Ordering;
2use std::cmp;
3
4use rustc_index::IndexVec;
5use rustc_middle::ty::error::TypeError;
6
7rustc_index::newtype_index! {
8 #[orderable]
9 #[debug_format = "ExpectedIdx({})"]
10 pub(crate) struct ExpectedIdx {}
11}
12
13rustc_index::newtype_index! {
14 #[orderable]
15 #[debug_format = "ProvidedIdx({})"]
16 pub(crate) struct ProvidedIdx {}
17}
18
19impl ExpectedIdx {
20 pub(crate) fn to_provided_idx(self) -> ProvidedIdx {
21 ProvidedIdx::from_usize(self.as_usize())
22 }
23}
24
25#[derive(Debug)]
27enum Issue {
28 Invalid(usize),
30 Missing(usize),
32 Extra(usize),
34 Swap(usize, usize),
36 Permutation(Vec<Option<usize>>),
38}
39
40#[derive(Clone, Debug, Eq, PartialEq)]
41pub(crate) enum Compatibility<'tcx> {
42 Compatible,
43 Incompatible(Option<TypeError<'tcx>>),
44}
45
46#[derive(Debug, PartialEq, Eq)]
48pub(crate) enum Error<'tcx> {
49 Invalid(ProvidedIdx, ExpectedIdx, Compatibility<'tcx>),
51 Missing(ExpectedIdx),
53 Extra(ProvidedIdx),
55 Swap(ProvidedIdx, ProvidedIdx, ExpectedIdx, ExpectedIdx),
57 Permutation(Vec<(ExpectedIdx, ProvidedIdx)>),
59}
60
61impl Ord for Error<'_> {
62 fn cmp(&self, other: &Self) -> Ordering {
63 let key = |error: &Error<'_>| -> usize {
64 match error {
65 Error::Invalid(..) => 0,
66 Error::Extra(_) => 1,
67 Error::Missing(_) => 2,
68 Error::Swap(..) => 3,
69 Error::Permutation(..) => 4,
70 }
71 };
72 match (self, other) {
73 (Error::Invalid(a, _, _), Error::Invalid(b, _, _)) => a.cmp(b),
74 (Error::Extra(a), Error::Extra(b)) => a.cmp(b),
75 (Error::Missing(a), Error::Missing(b)) => a.cmp(b),
76 (Error::Swap(a, b, ..), Error::Swap(c, d, ..)) => a.cmp(c).then(b.cmp(d)),
77 (Error::Permutation(a), Error::Permutation(b)) => a.cmp(b),
78 _ => key(self).cmp(&key(other)),
79 }
80 }
81}
82
83impl PartialOrd for Error<'_> {
84 fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
85 Some(self.cmp(other))
86 }
87}
88
89pub(crate) struct ArgMatrix<'tcx> {
90 provided_indices: Vec<ProvidedIdx>,
93 expected_indices: Vec<ExpectedIdx>,
96 compatibility_matrix: Vec<Vec<Compatibility<'tcx>>>,
100}
101
102impl<'tcx> ArgMatrix<'tcx> {
103 pub(crate) fn new<F: FnMut(ProvidedIdx, ExpectedIdx) -> Compatibility<'tcx>>(
104 provided_count: usize,
105 expected_input_count: usize,
106 mut is_compatible: F,
107 ) -> Self {
108 let compatibility_matrix = (0..provided_count)
109 .map(|i| {
110 (0..expected_input_count)
111 .map(|j| is_compatible(ProvidedIdx::from_usize(i), ExpectedIdx::from_usize(j)))
112 .collect()
113 })
114 .collect();
115 ArgMatrix {
116 provided_indices: (0..provided_count).map(ProvidedIdx::from_usize).collect(),
117 expected_indices: (0..expected_input_count).map(ExpectedIdx::from_usize).collect(),
118 compatibility_matrix,
119 }
120 }
121
122 fn eliminate_provided(&mut self, idx: usize) {
124 self.provided_indices.remove(idx);
125 self.compatibility_matrix.remove(idx);
126 }
127
128 fn eliminate_expected(&mut self, idx: usize) {
130 self.expected_indices.remove(idx);
131 for row in &mut self.compatibility_matrix {
132 row.remove(idx);
133 }
134 }
135
136 fn satisfy_input(&mut self, provided_idx: usize, expected_idx: usize) {
138 self.eliminate_provided(provided_idx);
139 self.eliminate_expected(expected_idx);
140 }
141
142 fn eliminate_satisfied(&mut self) -> Vec<(ProvidedIdx, ExpectedIdx)> {
145 let num_args = cmp::min(self.provided_indices.len(), self.expected_indices.len());
146 let mut eliminated = vec![];
147 for i in (0..num_args).rev() {
148 if matches!(self.compatibility_matrix[i][i], Compatibility::Compatible) {
149 eliminated.push((self.provided_indices[i], self.expected_indices[i]));
150 self.satisfy_input(i, i);
151 }
152 }
153 eliminated
154 }
155
156 fn find_issue(&self) -> Option<Issue> {
158 let mat = &self.compatibility_matrix;
159 let ai = &self.expected_indices;
160 let ii = &self.provided_indices;
161
162 let mut next_unmatched_idx = 0;
165 for i in 0..cmp::max(ai.len(), ii.len()) {
166 if i >= mat.len() {
168 return Some(Issue::Missing(next_unmatched_idx));
169 }
170 if mat[i].len() == 0 {
172 return Some(Issue::Extra(next_unmatched_idx));
173 }
174
175 let is_arg = i < ai.len();
177 let is_input = i < ii.len();
178 if is_arg && is_input && matches!(mat[i][i], Compatibility::Compatible) {
179 next_unmatched_idx += 1;
181 continue;
182 }
183
184 let mut useless = true;
185 let mut unsatisfiable = true;
186 if is_arg {
187 for j in 0..ii.len() {
188 if matches!(mat[j][i], Compatibility::Compatible) {
191 unsatisfiable = false;
192 break;
193 }
194 }
195 }
196 if is_input {
197 for j in 0..ai.len() {
198 if matches!(mat[i][j], Compatibility::Compatible) {
201 useless = false;
202 break;
203 }
204 }
205 }
206
207 match (is_input, is_arg, useless, unsatisfiable) {
208 (true, true, true, true) => return Some(Issue::Invalid(i)),
211 (true, _, true, _) => return Some(Issue::Extra(i)),
213 (_, true, _, true) => return Some(Issue::Missing(i)),
215 (true, true, _, _) => {
216 for j in 0..cmp::min(ai.len(), ii.len()) {
222 if i == j || matches!(mat[j][j], Compatibility::Compatible) {
223 continue;
224 }
225 if matches!(mat[i][j], Compatibility::Compatible)
226 && matches!(mat[j][i], Compatibility::Compatible)
227 {
228 return Some(Issue::Swap(i, j));
229 }
230 }
231 }
232 _ => {
233 continue;
234 }
235 }
236 }
237
238 let mut permutation: Vec<Option<Option<usize>>> = vec![None; mat.len()];
246 let mut permutation_found = false;
247 for i in 0..mat.len() {
248 if permutation[i].is_some() {
249 continue;
251 }
252
253 let mut stack = vec![];
254 let mut j = i;
255 let mut last = i;
256 let mut is_cycle = true;
257 loop {
258 stack.push(j);
259 let compat: Vec<_> =
261 mat[j]
262 .iter()
263 .enumerate()
264 .filter_map(|(i, c)| {
265 if matches!(c, Compatibility::Compatible) { Some(i) } else { None }
266 })
267 .collect();
268 if compat.len() < 1 {
269 is_cycle = false;
271 break;
272 }
273 j = compat[0];
274 if stack.contains(&j) {
275 last = j;
276 break;
277 }
278 }
279 if stack.len() <= 2 {
280 is_cycle = false;
283 }
284 permutation_found = is_cycle;
288 while let Some(x) = stack.pop() {
289 if is_cycle {
290 permutation[x] = Some(Some(j));
291 j = x;
292 if j == last {
293 is_cycle = false;
296 }
297 } else {
298 permutation[x] = Some(None);
300 }
301 }
302 }
303
304 if permutation_found {
305 let final_permutation: Vec<Option<usize>> =
307 permutation.into_iter().map(|x| x.unwrap()).collect();
308 return Some(Issue::Permutation(final_permutation));
309 }
310 None
311 }
312
313 pub(crate) fn find_errors(
322 mut self,
323 ) -> (Vec<Error<'tcx>>, IndexVec<ExpectedIdx, Option<ProvidedIdx>>) {
324 let provided_arg_count = self.provided_indices.len();
325
326 let mut errors: Vec<Error<'tcx>> = vec![];
327 let mut matched_inputs: IndexVec<ExpectedIdx, Option<ProvidedIdx>> =
329 IndexVec::from_elem_n(None, self.expected_indices.len());
330
331 for (provided, expected) in self.eliminate_satisfied() {
341 matched_inputs[expected] = Some(provided);
342 }
343
344 while !self.provided_indices.is_empty() || !self.expected_indices.is_empty() {
345 let res = self.find_issue();
346 match res {
347 Some(Issue::Invalid(idx)) => {
348 let compatibility = self.compatibility_matrix[idx][idx].clone();
349 let input_idx = self.provided_indices[idx];
350 let arg_idx = self.expected_indices[idx];
351 self.satisfy_input(idx, idx);
352 errors.push(Error::Invalid(input_idx, arg_idx, compatibility));
353 }
354 Some(Issue::Extra(idx)) => {
355 let input_idx = self.provided_indices[idx];
356 self.eliminate_provided(idx);
357 errors.push(Error::Extra(input_idx));
358 }
359 Some(Issue::Missing(idx)) => {
360 let arg_idx = self.expected_indices[idx];
361 self.eliminate_expected(idx);
362 errors.push(Error::Missing(arg_idx));
363 }
364 Some(Issue::Swap(idx, other)) => {
365 let input_idx = self.provided_indices[idx];
366 let other_input_idx = self.provided_indices[other];
367 let arg_idx = self.expected_indices[idx];
368 let other_arg_idx = self.expected_indices[other];
369 let (min, max) = (cmp::min(idx, other), cmp::max(idx, other));
370 self.satisfy_input(min, max);
371 self.satisfy_input(max - 1, min);
373 errors.push(Error::Swap(input_idx, other_input_idx, arg_idx, other_arg_idx));
374 matched_inputs[other_arg_idx] = Some(input_idx);
375 matched_inputs[arg_idx] = Some(other_input_idx);
376 }
377 Some(Issue::Permutation(args)) => {
378 let mut idxs: Vec<usize> = args.iter().filter_map(|&a| a).collect();
379
380 let mut real_idxs: IndexVec<ProvidedIdx, Option<(ExpectedIdx, ProvidedIdx)>> =
381 IndexVec::from_elem_n(None, provided_arg_count);
382 for (src, dst) in
383 args.iter().enumerate().filter_map(|(src, dst)| dst.map(|dst| (src, dst)))
384 {
385 let src_input_idx = self.provided_indices[src];
386 let dst_input_idx = self.provided_indices[dst];
387 let dest_arg_idx = self.expected_indices[dst];
388 real_idxs[src_input_idx] = Some((dest_arg_idx, dst_input_idx));
389 matched_inputs[dest_arg_idx] = Some(src_input_idx);
390 }
391 idxs.sort();
392 idxs.reverse();
393 for i in idxs {
394 self.satisfy_input(i, i);
395 }
396 errors.push(Error::Permutation(real_idxs.into_iter().flatten().collect()));
397 }
398 None => {
399 let eliminated = self.eliminate_satisfied();
402 assert!(!eliminated.is_empty(), "didn't eliminated any indice in this round");
403 for (inp, arg) in eliminated {
404 matched_inputs[arg] = Some(inp);
405 }
406 }
407 };
408 }
409
410 errors.sort();
413 (errors, matched_inputs)
414 }
415}