rustc_hir_typeck/fn_ctxt/
arg_matrix.rs

1use 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// An issue that might be found in the compatibility matrix
26#[derive(Debug)]
27enum Issue {
28    /// The given argument is the invalid type for the input
29    Invalid(usize),
30    /// There is a missing input
31    Missing(usize),
32    /// There's a superfluous argument
33    Extra(usize),
34    /// Two arguments should be swapped
35    Swap(usize, usize),
36    /// Several arguments should be reordered
37    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/// Similar to `Issue`, but contains some extra information
47#[derive(Debug, PartialEq, Eq)]
48pub(crate) enum Error<'tcx> {
49    /// The provided argument is the invalid type for the expected input
50    Invalid(ProvidedIdx, ExpectedIdx, Compatibility<'tcx>),
51    /// There is a missing input
52    Missing(ExpectedIdx),
53    /// There's a superfluous argument
54    Extra(ProvidedIdx),
55    /// Two arguments should be swapped
56    Swap(ProvidedIdx, ProvidedIdx, ExpectedIdx, ExpectedIdx),
57    /// Several arguments should be reordered
58    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    /// Maps the indices in the `compatibility_matrix` rows to the indices of
91    /// the *user provided* inputs
92    provided_indices: Vec<ProvidedIdx>,
93    /// Maps the indices in the `compatibility_matrix` columns to the indices
94    /// of the *expected* args
95    expected_indices: Vec<ExpectedIdx>,
96    /// The first dimension (rows) are the remaining user provided inputs to
97    /// match and the second dimension (cols) are the remaining expected args
98    /// to match
99    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    /// Remove a given input from consideration
123    fn eliminate_provided(&mut self, idx: usize) {
124        self.provided_indices.remove(idx);
125        self.compatibility_matrix.remove(idx);
126    }
127
128    /// Remove a given argument from consideration
129    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    /// "satisfy" an input with a given arg, removing both from consideration
137    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    // Returns a `Vec` of (user input, expected arg) of matched arguments. These
143    // are inputs on the remaining diagonal that match.
144    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    // Find some issue in the compatibility matrix
157    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        // Issue: 100478, when we end the iteration,
163        // `next_unmatched_idx` will point to the index of the first unmatched
164        let mut next_unmatched_idx = 0;
165        for i in 0..cmp::max(ai.len(), ii.len()) {
166            // If we eliminate the last row, any left-over arguments are considered missing
167            if i >= mat.len() {
168                return Some(Issue::Missing(next_unmatched_idx));
169            }
170            // If we eliminate the last column, any left-over inputs are extra
171            if mat[i].len() == 0 {
172                return Some(Issue::Extra(next_unmatched_idx));
173            }
174
175            // Make sure we don't pass the bounds of our matrix
176            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                // This is a satisfied input, so move along
180                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 we find at least one input this argument could satisfy
189                    // this argument isn't unsatisfiable
190                    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 we find at least one argument that could satisfy this input
199                    // this input isn't useless
200                    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                // If an argument is unsatisfied, and the input in its position is useless
209                // then the most likely explanation is that we just got the types wrong
210                (true, true, true, true) => return Some(Issue::Invalid(i)),
211                // Otherwise, if an input is useless then indicate that this is an extra input
212                (true, _, true, _) => return Some(Issue::Extra(i)),
213                // Otherwise, if an argument is unsatisfiable, indicate that it's missing
214                (_, true, _, true) => return Some(Issue::Missing(i)),
215                (true, true, _, _) => {
216                    // The argument isn't useless, and the input isn't unsatisfied,
217                    // so look for a parameter we might swap it with
218                    // We look for swaps explicitly, instead of just falling back on permutations
219                    // so that cases like (A,B,C,D) given (B,A,D,C) show up as two swaps,
220                    // instead of a large permutation of 4 elements.
221                    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        // We didn't find any of the individual issues above, but
239        // there might be a larger permutation of parameters, so we now check for that
240        // by checking for cycles
241        // We use a double option at position i in this vec to represent:
242        // - None: We haven't computed anything about this argument yet
243        // - Some(None): This argument definitely doesn't participate in a cycle
244        // - Some(Some(x)): the i-th argument could permute to the x-th position
245        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                // We've already decided whether this argument is or is not in a loop
250                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                // Look for params this one could slot into
260                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                    // try to find a cycle even when this could go into multiple slots, see #101097
270                    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                // If we encounter a cycle of 1 or 2 elements, we'll let the
281                // "satisfy" and "swap" code above handle those
282                is_cycle = false;
283            }
284            // We've built up some chain, some of which might be a cycle
285            // ex: [1,2,3,4]; last = 2; j = 2;
286            // So, we want to mark 4, 3, and 2 as part of a permutation
287            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                        // From here on out, we're a tail leading into a cycle,
294                        // not the cycle itself
295                        is_cycle = false;
296                    }
297                } else {
298                    // Some(None) ensures we save time by skipping this argument again
299                    permutation[x] = Some(None);
300                }
301            }
302        }
303
304        if permutation_found {
305            // Map unwrap to remove the first layer of Some
306            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    // Obviously, detecting exact user intention is impossible, so the goal here is to
314    // come up with as likely of a story as we can to be helpful.
315    //
316    // We'll iteratively removed "satisfied" input/argument pairs,
317    // then check for the cases above, until we've eliminated the entire grid
318    //
319    // We'll want to know which arguments and inputs these rows and columns correspond to
320    // even after we delete them.
321    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        // For each expected argument, the matched *actual* input
328        let mut matched_inputs: IndexVec<ExpectedIdx, Option<ProvidedIdx>> =
329            IndexVec::from_elem_n(None, self.expected_indices.len());
330
331        // Before we start looking for issues, eliminate any arguments that are already satisfied,
332        // so that an argument which is already spoken for by the input it's in doesn't
333        // spill over into another similarly typed input
334        // ex:
335        //   fn some_func(_a: i32, _b: i32) {}
336        //   some_func(1, "");
337        // Without this elimination, the first argument causes the second argument
338        // to show up as both a missing input and extra argument, rather than
339        // just an invalid type.
340        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                    // Subtract 1 because we already removed the "min" row
372                    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                    // We didn't find any issues, so we need to push the algorithm forward
400                    // First, eliminate any arguments that currently satisfy their inputs
401                    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        // sort errors with same type by the order they appear in the source
411        // so that suggestion will be handled properly, see #112507
412        errors.sort();
413        (errors, matched_inputs)
414    }
415}