Skip to main content

codeint_config/
finding_anchor.rs

1use std::collections::{BTreeMap, HashMap, VecDeque};
2
3use codeint_model::StableHasher;
4use serde::{Deserialize, Serialize};
5
6#[cfg(test)]
7mod tests;
8
9const MAX_EXACT_MATCH_GROUP: usize = 64;
10const MAX_LINE_DISTANCE: u32 = 1_000_000;
11const MATCH_WEIGHT: i64 = 1 << 44;
12const CONTEXT_SHIFT: u32 = 34;
13const LINE_SHIFT: u32 = 7;
14
15#[derive(Debug, Clone, Default, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
16#[serde(deny_unknown_fields)]
17pub struct FindingAnchor {
18    pub id: String,
19    #[serde(default, skip_serializing_if = "Option::is_none")]
20    pub content: Option<String>,
21    #[serde(default, skip_serializing_if = "Option::is_none")]
22    pub body: Option<String>,
23    #[serde(default, skip_serializing_if = "Vec::is_empty")]
24    pub paths: Vec<String>,
25    #[serde(default, skip_serializing_if = "Option::is_none")]
26    pub before: Option<String>,
27    #[serde(default, skip_serializing_if = "Option::is_none")]
28    pub after: Option<String>,
29    #[serde(default, skip_serializing_if = "Option::is_none")]
30    pub line: Option<u32>,
31}
32
33impl FindingAnchor {
34    pub fn id_only(id: impl Into<String>) -> FindingAnchor {
35        FindingAnchor {
36            id: id.into(),
37            content: None,
38            body: None,
39            paths: Vec::new(),
40            before: None,
41            after: None,
42            line: None,
43        }
44    }
45
46    pub fn from_hashes(
47        id: String,
48        content: u64,
49        before: Option<u64>,
50        after: Option<u64>,
51        line: Option<u32>,
52    ) -> FindingAnchor {
53        FindingAnchor {
54            id,
55            content: Some(format!("{content:016x}")),
56            body: None,
57            paths: Vec::new(),
58            before: before.map(|value| format!("{value:016x}")),
59            after: after.map(|value| format!("{value:016x}")),
60            line,
61        }
62    }
63
64    pub fn with_body_and_paths(mut self, body: Option<u64>, paths: Vec<String>) -> FindingAnchor {
65        self.body = body
66            .filter(|&value| value != 0)
67            .map(|value| format!("{value:016x}"));
68        let mut hashed: Vec<String> = paths
69            .into_iter()
70            .map(|path| hash_anchor_path(&path))
71            .collect();
72        hashed.sort();
73        hashed.dedup();
74        self.paths = hashed;
75        self
76    }
77}
78
79fn hash_anchor_path(path: &str) -> String {
80    let digest = StableHasher::new()
81        .write_bytes(b"codeint.anchor.path.v1")
82        .write_u64(path.len() as u64)
83        .write_bytes(path.as_bytes())
84        .finish();
85    format!("{digest:016x}")
86}
87
88#[derive(Debug, Clone, Default, PartialEq, Eq)]
89pub struct AnchorMatch {
90    pub matched_pairs: Vec<(usize, usize)>,
91}
92
93impl AnchorMatch {
94    pub fn matched_references(&self, len: usize) -> Vec<bool> {
95        let mut matched = vec![false; len];
96        for &(reference_index, _) in &self.matched_pairs {
97            matched[reference_index] = true;
98        }
99        matched
100    }
101
102    pub fn matched_candidates(&self, len: usize) -> Vec<bool> {
103        let mut matched = vec![false; len];
104        for &(_, candidate_index) in &self.matched_pairs {
105            matched[candidate_index] = true;
106        }
107        matched
108    }
109}
110
111pub fn remap_anchor_paths(
112    anchor: &FindingAnchor,
113    renames: &BTreeMap<String, String>,
114) -> FindingAnchor {
115    if renames.is_empty() {
116        return anchor.clone();
117    }
118    let mut remapped = anchor.clone();
119    remapped.id = remap_paths_in_id(&anchor.id, renames);
120    remapped
121}
122
123pub fn match_anchors_with_renames(
124    references: &[FindingAnchor],
125    candidates: &[FindingAnchor],
126    renames: &BTreeMap<String, String>,
127) -> AnchorMatch {
128    if renames.is_empty() {
129        return match_anchors(references, candidates);
130    }
131    let remapped_references: Vec<FindingAnchor> = references
132        .iter()
133        .map(|reference| remap_anchor_paths(reference, renames))
134        .collect();
135    let direct = match_anchors(&remapped_references, candidates);
136    let max_matches = references.len().min(candidates.len());
137    if direct.matched_pairs.len() == max_matches {
138        return direct;
139    }
140    let mut used_references = direct.matched_references(references.len());
141    let mut used_candidates = direct.matched_candidates(candidates.len());
142    let mut matched_pairs = direct.matched_pairs;
143    match_remapped_ids(
144        references,
145        &remapped_references,
146        candidates,
147        &mut used_references,
148        &mut used_candidates,
149        &mut matched_pairs,
150    );
151    if matched_pairs.len() < max_matches {
152        match_renamed_body_groups(
153            references,
154            candidates,
155            renames,
156            &used_references,
157            &used_candidates,
158            &mut matched_pairs,
159        );
160    }
161    matched_pairs.sort_unstable();
162    AnchorMatch { matched_pairs }
163}
164
165fn match_candidates_by_id<'a>(
166    candidates: &'a [FindingAnchor],
167    used_references: &mut [bool],
168    used_candidates: &mut [bool],
169    matched_pairs: &mut Vec<(usize, usize)>,
170    reference_ids: impl Iterator<Item = (usize, &'a str)>,
171) {
172    let mut candidates_by_id: HashMap<&str, VecDeque<usize>> = HashMap::new();
173    for (index, candidate) in candidates.iter().enumerate() {
174        if !used_candidates[index] {
175            candidates_by_id
176                .entry(candidate.id.as_str())
177                .or_default()
178                .push_back(index);
179        }
180    }
181    for (ref_index, target_id) in reference_ids {
182        if let Some(queue) = candidates_by_id.get_mut(target_id)
183            && let Some(cand_index) = queue.pop_front()
184        {
185            used_references[ref_index] = true;
186            used_candidates[cand_index] = true;
187            matched_pairs.push((ref_index, cand_index));
188        }
189    }
190}
191
192fn match_remapped_ids(
193    references: &[FindingAnchor],
194    remapped_references: &[FindingAnchor],
195    candidates: &[FindingAnchor],
196    used_references: &mut [bool],
197    used_candidates: &mut [bool],
198    matched_pairs: &mut Vec<(usize, usize)>,
199) {
200    let targets: Vec<(usize, &str)> = references
201        .iter()
202        .zip(remapped_references.iter())
203        .enumerate()
204        .filter(|&(index, (original, remapped))| {
205            !used_references[index] && original.id != remapped.id
206        })
207        .map(|(index, (_, remapped))| (index, remapped.id.as_str()))
208        .collect();
209    match_candidates_by_id(
210        candidates,
211        used_references,
212        used_candidates,
213        matched_pairs,
214        targets.into_iter(),
215    );
216}
217
218fn canonical_paths(paths: &[String], renames: Option<&HashMap<String, String>>) -> Vec<String> {
219    let mut normalized: Vec<String> = paths
220        .iter()
221        .map(|path| match renames.and_then(|map| map.get(path)) {
222            Some(renamed) => renamed.clone(),
223            None => path.clone(),
224        })
225        .collect();
226    normalized.sort();
227    normalized.dedup();
228    normalized
229}
230
231fn build_rename_lookup(renames: &BTreeMap<String, String>) -> HashMap<String, String> {
232    let mut lookup = HashMap::with_capacity(renames.len() * 2);
233    for (old_path, new_path) in renames {
234        lookup.insert(old_path.clone(), new_path.clone());
235        lookup.insert(hash_anchor_path(old_path), hash_anchor_path(new_path));
236    }
237    lookup
238}
239
240fn group_anchors_by_body_and_paths<'a>(
241    anchors: &'a [FindingAnchor],
242    used: &[bool],
243    rename_lookup: Option<&HashMap<String, String>>,
244) -> BTreeMap<(&'a str, Vec<String>), Vec<usize>> {
245    let mut groups: BTreeMap<(&'a str, Vec<String>), Vec<usize>> = BTreeMap::new();
246    for (index, anchor) in anchors.iter().enumerate() {
247        if used[index] || anchor.paths.is_empty() {
248            continue;
249        }
250        let Some(body) = anchor.body.as_deref() else {
251            continue;
252        };
253        if let Some(lookup) = rename_lookup
254            && !anchor.paths.iter().any(|path| lookup.contains_key(path))
255        {
256            continue;
257        }
258        let key = (body, canonical_paths(&anchor.paths, rename_lookup));
259        groups.entry(key).or_default().push(index);
260    }
261    groups
262}
263
264fn match_renamed_body_groups(
265    references: &[FindingAnchor],
266    candidates: &[FindingAnchor],
267    renames: &BTreeMap<String, String>,
268    used_references: &[bool],
269    used_candidates: &[bool],
270    matched_pairs: &mut Vec<(usize, usize)>,
271) {
272    let rename_lookup = build_rename_lookup(renames);
273    let reference_groups =
274        group_anchors_by_body_and_paths(references, used_references, Some(&rename_lookup));
275    if reference_groups.is_empty() {
276        return;
277    }
278    let candidate_groups = group_anchors_by_body_and_paths(candidates, used_candidates, None);
279    for (key, ref_indices) in reference_groups {
280        let Some(cand_indices) = candidate_groups.get(&key) else {
281            continue;
282        };
283        match_content_group(
284            references,
285            candidates,
286            &ref_indices,
287            cand_indices,
288            matched_pairs,
289        );
290    }
291}
292
293pub fn match_anchors_with_aliases(
294    references: &[FindingAnchor],
295    candidates: &[FindingAnchor],
296    candidate_aliases: &[Option<FindingAnchor>],
297    renames: &BTreeMap<String, String>,
298) -> AnchorMatch {
299    let direct = match_anchors_with_renames(references, candidates, renames);
300    if candidate_aliases.is_empty()
301        || direct.matched_pairs.len() == references.len().min(candidates.len())
302    {
303        return direct;
304    }
305    let ref_used = direct.matched_references(references.len());
306    let cand_used = direct.matched_candidates(candidates.len());
307
308    let unmatched_ref_indices: Vec<usize> = ref_used
309        .iter()
310        .enumerate()
311        .filter_map(|(index, &used)| (!used).then_some(index))
312        .collect();
313    let unmatched_alias_entries: Vec<(usize, FindingAnchor)> = candidate_aliases
314        .iter()
315        .enumerate()
316        .filter_map(|(index, alias)| {
317            if index < candidates.len() && !cand_used[index] {
318                alias.clone().map(|anchor| (index, anchor))
319            } else {
320                None
321            }
322        })
323        .collect();
324    if unmatched_ref_indices.is_empty() || unmatched_alias_entries.is_empty() {
325        return direct;
326    }
327
328    let unmatched_refs: Vec<FindingAnchor> = unmatched_ref_indices
329        .iter()
330        .map(|&index| references[index].clone())
331        .collect();
332    let unmatched_aliases: Vec<FindingAnchor> = unmatched_alias_entries
333        .iter()
334        .map(|(_, anchor)| anchor.clone())
335        .collect();
336    let alias_match = match_anchors(&unmatched_refs, &unmatched_aliases);
337    if alias_match.matched_pairs.is_empty() {
338        return direct;
339    }
340
341    let mut matched_pairs = direct.matched_pairs;
342    for (local_ref, local_alias) in alias_match.matched_pairs {
343        matched_pairs.push((
344            unmatched_ref_indices[local_ref],
345            unmatched_alias_entries[local_alias].0,
346        ));
347    }
348    matched_pairs.sort_unstable();
349    AnchorMatch { matched_pairs }
350}
351
352fn remap_paths_in_id(id: &str, renames: &BTreeMap<String, String>) -> String {
353    if let Some(exact) = renames.get(id) {
354        return exact.clone();
355    }
356    let mut ordered: Vec<(&str, &str)> = renames
357        .iter()
358        .filter(|(old_path, _)| !old_path.is_empty() && id.contains(old_path.as_str()))
359        .map(|(old_path, new_path)| (old_path.as_str(), new_path.as_str()))
360        .collect();
361    if ordered.is_empty() {
362        return id.to_owned();
363    }
364    ordered.sort_by(|left, right| {
365        right
366            .0
367            .len()
368            .cmp(&left.0.len())
369            .then_with(|| left.0.cmp(right.0))
370    });
371    let mut result = id.to_owned();
372    for (old_path, new_path) in ordered {
373        result = replace_path_bounded(&result, old_path, new_path);
374    }
375    result
376}
377
378fn replace_path_bounded(text: &str, old_path: &str, new_path: &str) -> String {
379    let mut output = String::with_capacity(text.len());
380    let mut rest = text;
381    let mut offset = 0usize;
382    while let Some(pos) = rest.find(old_path) {
383        let abs_start = offset + pos;
384        let abs_end = abs_start + old_path.len();
385        let left_ok = abs_start == 0
386            || text[..abs_start]
387                .chars()
388                .next_back()
389                .is_some_and(is_path_delimiter);
390        let right_ok = abs_end == text.len()
391            || text[abs_end..]
392                .chars()
393                .next()
394                .is_some_and(is_path_delimiter);
395        output.push_str(&rest[..pos]);
396        if left_ok && right_ok {
397            output.push_str(new_path);
398        } else {
399            output.push_str(old_path);
400        }
401        let advance = pos + old_path.len();
402        rest = &rest[advance..];
403        offset += advance;
404    }
405    output.push_str(rest);
406    output
407}
408
409fn is_path_delimiter(ch: char) -> bool {
410    matches!(
411        ch,
412        ':' | ',' | ' ' | '\t' | '|' | '[' | ']' | '(' | ')' | '#' | '@' | ';'
413    )
414}
415
416pub fn match_anchors(references: &[FindingAnchor], candidates: &[FindingAnchor]) -> AnchorMatch {
417    if references.is_empty() || candidates.is_empty() {
418        return AnchorMatch::default();
419    }
420    let mut matched_pairs = Vec::new();
421    let mut used_references = vec![false; references.len()];
422    let mut used_candidates = vec![false; candidates.len()];
423
424    match_id_only_references(
425        references,
426        candidates,
427        &mut used_references,
428        &mut used_candidates,
429        &mut matched_pairs,
430    );
431
432    let reference_groups = group_unused_by_content(references, &used_references);
433    let candidate_groups = group_unused_by_content(candidates, &used_candidates);
434
435    for (content, ref_indices) in reference_groups {
436        let Some(cand_indices) = candidate_groups.get(content) else {
437            continue;
438        };
439        match_content_group(
440            references,
441            candidates,
442            &ref_indices,
443            cand_indices,
444            &mut matched_pairs,
445        );
446    }
447
448    matched_pairs.sort_unstable();
449    AnchorMatch { matched_pairs }
450}
451
452fn group_unused_by_content<'a>(
453    anchors: &'a [FindingAnchor],
454    used: &[bool],
455) -> BTreeMap<&'a str, Vec<usize>> {
456    let mut groups: BTreeMap<&'a str, Vec<usize>> = BTreeMap::new();
457    for (index, anchor) in anchors.iter().enumerate() {
458        if !used[index]
459            && let Some(content) = anchor.content.as_deref()
460        {
461            groups.entry(content).or_default().push(index);
462        }
463    }
464    groups
465}
466
467fn match_id_only_references(
468    references: &[FindingAnchor],
469    candidates: &[FindingAnchor],
470    used_references: &mut [bool],
471    used_candidates: &mut [bool],
472    matched_pairs: &mut Vec<(usize, usize)>,
473) {
474    let targets = references
475        .iter()
476        .enumerate()
477        .filter(|(_, reference)| reference.content.is_none())
478        .map(|(index, reference)| (index, reference.id.as_str()));
479    match_candidates_by_id(
480        candidates,
481        used_references,
482        used_candidates,
483        matched_pairs,
484        targets,
485    );
486}
487
488fn match_content_group(
489    references: &[FindingAnchor],
490    candidates: &[FindingAnchor],
491    ref_indices: &[usize],
492    cand_indices: &[usize],
493    matched_pairs: &mut Vec<(usize, usize)>,
494) {
495    if ref_indices.len() == 1 && cand_indices.len() == 1 {
496        matched_pairs.push((ref_indices[0], cand_indices[0]));
497        return;
498    }
499    if ref_indices.len().max(cand_indices.len()) <= MAX_EXACT_MATCH_GROUP {
500        match_group_exact(
501            references,
502            candidates,
503            ref_indices,
504            cand_indices,
505            matched_pairs,
506        );
507    } else {
508        match_group_bucketed(
509            references,
510            candidates,
511            ref_indices,
512            cand_indices,
513            matched_pairs,
514        );
515    }
516}
517
518fn match_group_exact(
519    references: &[FindingAnchor],
520    candidates: &[FindingAnchor],
521    ref_indices: &[usize],
522    cand_indices: &[usize],
523    matched_pairs: &mut Vec<(usize, usize)>,
524) {
525    let size = ref_indices.len().max(cand_indices.len());
526    let mut weights = vec![vec![0i64; size]; size];
527    for (row, &ref_index) in ref_indices.iter().enumerate() {
528        for (col, &cand_index) in cand_indices.iter().enumerate() {
529            weights[row][col] = pair_weight(&references[ref_index], &candidates[cand_index]);
530        }
531    }
532    let assignment = hungarian_max_weight(&weights);
533    for (row, &col) in assignment.iter().enumerate() {
534        if row < ref_indices.len() && col < cand_indices.len() {
535            matched_pairs.push((ref_indices[row], cand_indices[col]));
536        }
537    }
538}
539
540fn pair_weight(reference: &FindingAnchor, candidate: &FindingAnchor) -> i64 {
541    let context_score = context_match_score(reference, candidate);
542    let line_bonus = line_proximity_bonus(reference.line, candidate.line);
543    let same_id = i64::from(reference.id == candidate.id);
544    MATCH_WEIGHT + (context_score << CONTEXT_SHIFT) + (line_bonus << LINE_SHIFT) + same_id
545}
546
547fn context_match_score(reference: &FindingAnchor, candidate: &FindingAnchor) -> i64 {
548    let has_line_bounds = reference.line.is_some() && candidate.line.is_some();
549    side_match_score(
550        reference.before.as_deref(),
551        candidate.before.as_deref(),
552        has_line_bounds,
553    ) + side_match_score(
554        reference.after.as_deref(),
555        candidate.after.as_deref(),
556        has_line_bounds,
557    )
558}
559
560fn side_match_score(
561    reference_side: Option<&str>,
562    candidate_side: Option<&str>,
563    has_line_bounds: bool,
564) -> i64 {
565    match (reference_side, candidate_side) {
566        (Some(left), Some(right)) if left == right => 3,
567        (None, None) if has_line_bounds => 2,
568        _ => 0,
569    }
570}
571
572fn line_proximity_bonus(reference_line: Option<u32>, candidate_line: Option<u32>) -> i64 {
573    let distance = match (reference_line, candidate_line) {
574        (Some(left), Some(right)) => left.abs_diff(right).min(MAX_LINE_DISTANCE),
575        _ => MAX_LINE_DISTANCE,
576    };
577    i64::from(MAX_LINE_DISTANCE - distance)
578}
579
580struct HungarianSolver<'a> {
581    weights: &'a [Vec<i64>],
582    max_weight: i64,
583    u: Vec<i64>,
584    v: Vec<i64>,
585    p: Vec<usize>,
586    way: Vec<usize>,
587}
588
589impl<'a> HungarianSolver<'a> {
590    fn new(weights: &'a [Vec<i64>]) -> HungarianSolver<'a> {
591        let n = weights.len();
592        let max_weight = weights
593            .iter()
594            .flat_map(|row| row.iter().copied())
595            .max()
596            .unwrap_or(0);
597        HungarianSolver {
598            weights,
599            max_weight,
600            u: vec![0; n + 1],
601            v: vec![0; n + 1],
602            p: vec![0; n + 1],
603            way: vec![0; n + 1],
604        }
605    }
606
607    fn solve(mut self) -> Vec<usize> {
608        let n = self.weights.len();
609        for row in 1..=n {
610            self.augment_row(row);
611        }
612        let mut assignment = vec![0usize; n];
613        for col in 1..=n {
614            if self.p[col] > 0 {
615                assignment[self.p[col] - 1] = col - 1;
616            }
617        }
618        assignment
619    }
620
621    fn augment_row(&mut self, row: usize) {
622        let n = self.weights.len();
623        self.p[0] = row;
624        let mut col0 = 0usize;
625        let mut min_v = vec![i64::MAX; n + 1];
626        let mut used = vec![false; n + 1];
627        loop {
628            used[col0] = true;
629            let (delta, next_col) = self.relax_columns(col0, &used, &mut min_v);
630            self.shift_potentials(&used, &mut min_v, delta);
631            col0 = next_col;
632            if self.p[col0] == 0 {
633                break;
634            }
635        }
636        self.unwind_path(col0);
637    }
638
639    fn relax_columns(&mut self, col0: usize, used: &[bool], min_v: &mut [i64]) -> (i64, usize) {
640        let row0 = self.p[col0];
641        let mut delta = i64::MAX;
642        let mut best_col = 0usize;
643        for col in 1..=self.weights.len() {
644            if used[col] {
645                continue;
646            }
647            let cost = self.max_weight - self.weights[row0 - 1][col - 1];
648            let current = cost - self.u[row0] - self.v[col];
649            if current < min_v[col] {
650                min_v[col] = current;
651                self.way[col] = col0;
652            }
653            if min_v[col] < delta {
654                delta = min_v[col];
655                best_col = col;
656            }
657        }
658        (delta, best_col)
659    }
660
661    fn shift_potentials(&mut self, used: &[bool], min_v: &mut [i64], delta: i64) {
662        for col in 0..=self.weights.len() {
663            if used[col] {
664                self.u[self.p[col]] += delta;
665                self.v[col] -= delta;
666            } else {
667                min_v[col] -= delta;
668            }
669        }
670    }
671
672    fn unwind_path(&mut self, mut col0: usize) {
673        while col0 != 0 {
674            let col1 = self.way[col0];
675            self.p[col0] = self.p[col1];
676            col0 = col1;
677        }
678    }
679}
680
681fn hungarian_max_weight(weights: &[Vec<i64>]) -> Vec<usize> {
682    HungarianSolver::new(weights).solve()
683}
684
685struct BucketedMatcher<'a> {
686    references: &'a [FindingAnchor],
687    candidates: &'a [FindingAnchor],
688    ref_indices: &'a [usize],
689    cand_indices: &'a [usize],
690    ref_used: Vec<bool>,
691    cand_used: Vec<bool>,
692}
693
694impl<'a> BucketedMatcher<'a> {
695    fn pair_by_key<K: Eq + std::hash::Hash>(
696        &mut self,
697        matched_pairs: &mut Vec<(usize, usize)>,
698        key_of: impl Fn(&'a FindingAnchor) -> Option<K>,
699    ) {
700        let mut buckets: HashMap<K, VecDeque<usize>> = HashMap::new();
701        for (cand_pos, &cand_index) in self.cand_indices.iter().enumerate() {
702            if !self.cand_used[cand_pos]
703                && let Some(key) = key_of(&self.candidates[cand_index])
704            {
705                buckets.entry(key).or_default().push_back(cand_pos);
706            }
707        }
708        for (ref_pos, &ref_index) in self.ref_indices.iter().enumerate() {
709            if self.ref_used[ref_pos] {
710                continue;
711            }
712            if let Some(key) = key_of(&self.references[ref_index])
713                && let Some(queue) = buckets.get_mut(&key)
714                && let Some(cand_pos) = queue.pop_front()
715            {
716                self.ref_used[ref_pos] = true;
717                self.cand_used[cand_pos] = true;
718                matched_pairs.push((ref_index, self.cand_indices[cand_pos]));
719            }
720        }
721    }
722}
723
724fn match_group_bucketed(
725    references: &[FindingAnchor],
726    candidates: &[FindingAnchor],
727    ref_indices: &[usize],
728    cand_indices: &[usize],
729    matched_pairs: &mut Vec<(usize, usize)>,
730) {
731    let mut matcher = BucketedMatcher {
732        references,
733        candidates,
734        ref_indices,
735        cand_indices,
736        ref_used: vec![false; ref_indices.len()],
737        cand_used: vec![false; cand_indices.len()],
738    };
739    matcher.pair_by_key(matched_pairs, |anchor| {
740        Some((anchor.before.as_deref(), anchor.after.as_deref()))
741    });
742    matcher.pair_by_key(matched_pairs, |anchor| anchor.before.as_deref());
743    matcher.pair_by_key(matched_pairs, |anchor| anchor.after.as_deref());
744    let remaining_refs = ref_indices
745        .iter()
746        .enumerate()
747        .filter(|&(pos, _)| !matcher.ref_used[pos])
748        .map(|(_, &index)| index);
749    let remaining_cands = cand_indices
750        .iter()
751        .enumerate()
752        .filter(|&(pos, _)| !matcher.cand_used[pos])
753        .map(|(_, &index)| index);
754    matched_pairs.extend(remaining_refs.zip(remaining_cands));
755}