vhdl_lang 0.59.0

VHDL Language Frontend
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
// This Source Code Form is subject to the terms of the Mozilla Public
// License, v. 2.0. If a copy of the MPL was not distributed with this file,
// You can obtain one at http://mozilla.org/MPL/2.0/.
//
// Copyright (c) 2023, Olof Kraigher olof.kraigher@gmail.com

use fnv::FnvHashSet;

use super::analyze::*;
use super::association::ResolvedFormal;
use super::expression::ExpressionType;
use super::formal_region::InterfaceEnt;
use super::named_entity::*;
use super::region::*;
use crate::ast::search::clear_references;
use crate::ast::*;
use crate::data::*;

#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Disambiguated<'a> {
    Unambiguous(OverloadedEnt<'a>),
    Ambiguous(Vec<OverloadedEnt<'a>>),
}

#[derive(Clone, Debug, PartialEq, Eq)]
pub enum DisambiguatedType<'a> {
    Unambiguous(TypeEnt<'a>),
    Ambiguous(FnvHashSet<BaseType<'a>>),
}
#[derive(Copy, Clone)]
pub enum SubprogramKind<'a> {
    Function(Option<TypeEnt<'a>>),
    Procedure,
}

// The reason a subprogram was rejected as a candidate of a call
#[derive(Debug)]
enum Rejection<'a> {
    // The return type of the subprogram is not correct
    ReturnType,

    // The subprogram is a procedure but we expected a function
    Procedure,

    // The amount of actuals or named actuals do not match formals
    MissingFormals(Vec<InterfaceEnt<'a>>),
}

struct Candidate<'a> {
    ent: OverloadedEnt<'a>,
    rejection: Option<Rejection<'a>>,
}

struct Candidates<'a>(Vec<Candidate<'a>>);

impl<'a> Candidates<'a> {
    fn new(candidates: &OverloadedName<'a>) -> Self {
        Self(
            candidates
                .entities()
                .map(|ent| Candidate {
                    ent,
                    rejection: None,
                })
                .collect(),
        )
    }

    fn remaining(&mut self) -> impl Iterator<Item = &mut Candidate<'a>> {
        self.0.iter_mut().filter(|cand| cand.rejection.is_none())
    }

    fn split(self) -> (Vec<OverloadedEnt<'a>>, Vec<Candidate<'a>>) {
        let (remaining, rejected): (Vec<_>, Vec<_>) = self
            .0
            .into_iter()
            .partition(|cand| cand.rejection.is_none());
        let remaining: Vec<_> = remaining.into_iter().map(|cand| cand.ent).collect();
        (remaining, rejected)
    }

    fn finish(
        self,
        name: &WithPos<Designator>,
        ttyp: Option<TypeEnt<'a>>,
    ) -> Result<Disambiguated<'a>, Diagnostic> {
        let (remaining, mut rejected) = self.split();

        if remaining.len() == 1 {
            Ok(Disambiguated::Unambiguous(remaining[0]))
        } else if !remaining.is_empty() {
            Ok(Disambiguated::Ambiguous(remaining))
        } else {
            if let [ref single] = rejected.as_slice() {
                if let Some(ttyp) = ttyp {
                    if matches!(single.rejection, Some(Rejection::ReturnType))
                        && matches!(single.ent.kind(), Overloaded::EnumLiteral(_))
                    {
                        // Special case to get better error for single rejected enumeration literal
                        // For example when assigning true to an integer.
                        return Err(Diagnostic::error(
                            name,
                            format!("'{}' does not match {}", name, ttyp.describe()),
                        ));
                    }
                }
            }

            let err_prefix = if rejected.len() == 1 {
                // Provide better error for unique function name
                "Invalid call to"
            } else {
                "Could not resolve"
            };

            let mut diag = Diagnostic::error(name, format!("{err_prefix} '{name}'"));

            rejected.sort_by(|x, y| x.ent.decl_pos().cmp(&y.ent.decl_pos()));

            for cand in rejected {
                if let Some(decl_pos) = cand.ent.decl_pos() {
                    let rejection = cand.rejection.unwrap();

                    match rejection {
                        Rejection::ReturnType => diag.add_related(
                            decl_pos,
                            format!("Does not match return type of {}", cand.ent.describe()),
                        ),
                        Rejection::Procedure => diag.add_related(
                            decl_pos,
                            format!(
                                "Procedure {} cannot be used as a function",
                                cand.ent.describe()
                            ),
                        ),
                        Rejection::MissingFormals(missing) => {
                            for formal in missing.iter() {
                                diag.add_related(
                                    decl_pos,
                                    format!("Missing association of {}", formal.describe()),
                                )
                            }
                        }
                    };
                }
            }
            Err(diag)
        }
    }
}

impl<'a> Disambiguated<'a> {
    pub fn into_type(self) -> DisambiguatedType<'a> {
        match self {
            Disambiguated::Unambiguous(ent) => {
                DisambiguatedType::Unambiguous(ent.return_type().unwrap())
            }
            Disambiguated::Ambiguous(overloaded) => DisambiguatedType::Ambiguous(
                overloaded
                    .into_iter()
                    .map(|e| e.return_type().unwrap().base())
                    .collect(),
            ),
        }
    }
}

#[derive(Clone)]
pub(super) struct ResolvedCall<'a> {
    pub subpgm: OverloadedEnt<'a>,
    pub formals: Vec<ResolvedFormal<'a>>,
}

impl<'a> AsRef<OverloadedEnt<'a>> for OverloadedEnt<'a> {
    fn as_ref(&self) -> &OverloadedEnt<'a> {
        self
    }
}

impl<'a> AsRef<OverloadedEnt<'a>> for ResolvedCall<'a> {
    fn as_ref(&self) -> &OverloadedEnt<'a> {
        &self.subpgm
    }
}

impl<'a> AnalyzeContext<'a> {
    /// Typecheck one overloaded call where the exact subprogram is known
    pub fn check_call(
        &self,
        scope: &Scope<'a>,
        error_pos: &SrcPos,
        ent: OverloadedEnt<'a>,
        assocs: &mut [AssociationElement],
        diagnostics: &mut dyn DiagnosticHandler,
    ) -> FatalResult {
        self.analyze_assoc_elems_with_formal_region(
            error_pos,
            ent.formals(),
            scope,
            assocs,
            diagnostics,
        )?;
        Ok(())
    }

    fn disambiguate_by_kind(candidates: &mut Vec<OverloadedEnt<'a>>, kind: SubprogramKind<'a>) {
        match kind {
            SubprogramKind::Function(_) => candidates.retain(|cand| cand.is_function()),
            SubprogramKind::Procedure => candidates.retain(|cand| cand.is_procedure()),
        };
    }

    fn disambiguate_by_assoc_formals(
        &self,
        scope: &Scope<'a>,
        call_pos: &SrcPos,
        candidates: &[OverloadedEnt<'a>],
        assocs: &mut [AssociationElement],
    ) -> EvalResult<Vec<ResolvedCall<'a>>> {
        let mut result = Vec::with_capacity(candidates.len());
        for ent in candidates.iter() {
            if let Some(resolved) = as_fatal(self.resolve_association_formals(
                call_pos,
                ent.formals(),
                scope,
                assocs,
                &mut NullDiagnostics,
            ))? {
                result.push(ResolvedCall {
                    subpgm: *ent,
                    formals: resolved,
                });
            }

            for elem in assocs.iter_mut() {
                clear_references(elem);
            }
        }

        Ok(result)
    }

    fn actual_types(
        &self,
        scope: &Scope<'a>,
        assocs: &mut [AssociationElement],
        diagnostics: &mut dyn DiagnosticHandler,
    ) -> EvalResult<Vec<Option<ExpressionType<'a>>>> {
        let mut actual_types = Vec::with_capacity(assocs.len());

        for assoc in assocs.iter_mut() {
            match &mut assoc.actual.item {
                ActualPart::Expression(expr) => {
                    let actual_type =
                        self.expr_pos_type(scope, &assoc.actual.pos, expr, diagnostics)?;
                    actual_types.push(Some(actual_type));
                }
                ActualPart::Open => {
                    actual_types.push(None);
                }
            }
        }

        Ok(actual_types)
    }

    #[allow(clippy::too_many_arguments)]
    pub fn disambiguate(
        &self,
        scope: &Scope<'a>,
        call_pos: &SrcPos,               // The position of the entire call
        call_name: &WithPos<Designator>, // The position and name of the subprogram name in the call
        assocs: &mut [AssociationElement],
        kind: SubprogramKind<'a>,
        all_overloaded: Vec<OverloadedEnt<'a>>,
        diagnostics: &mut dyn DiagnosticHandler,
    ) -> EvalResult<Disambiguated<'a>> {
        if all_overloaded.len() == 1 {
            let ent = all_overloaded[0];
            self.check_call(scope, call_pos, ent, assocs, diagnostics)?;
            return Ok(Disambiguated::Unambiguous(ent));
        }

        let mut ok_kind = all_overloaded.clone();
        Self::disambiguate_by_kind(&mut ok_kind, kind);

        // Does not need disambiguation
        if ok_kind.len() == 1 {
            let ent = ok_kind[0];
            self.check_call(scope, call_pos, ent, assocs, diagnostics)?;
            return Ok(Disambiguated::Unambiguous(ent));
        } else if ok_kind.is_empty() {
            diagnostics.push(Diagnostic::could_not_resolve(call_name, all_overloaded));
            return Err(EvalError::Unknown);
        }

        let ok_formals = self.disambiguate_by_assoc_formals(scope, call_pos, &ok_kind, assocs)?;

        // Only one candidate matched actual/formal profile
        if ok_formals.len() == 1 {
            let ent = ok_formals[0].subpgm;
            self.check_call(scope, call_pos, ent, assocs, diagnostics)?;
            return Ok(Disambiguated::Unambiguous(ent));
        } else if ok_formals.is_empty() {
            // No candidate matched actual/formal profile
            diagnostics.push(Diagnostic::could_not_resolve(call_name, ok_kind));
            return Err(EvalError::Unknown);
        }

        let actual_types = self.actual_types(scope, assocs, diagnostics)?;

        let mut ok_assoc_types = ok_formals.clone();
        self.implicit_matcher()
            .disambiguate_by_assoc_types(&actual_types, &mut ok_assoc_types);

        if ok_assoc_types.len() == 1 {
            let ent = ok_assoc_types[0].subpgm;
            self.check_call(scope, call_pos, ent, assocs, diagnostics)?;
            return Ok(Disambiguated::Unambiguous(ent));
        } else if ok_assoc_types.is_empty() {
            diagnostics.push(Diagnostic::could_not_resolve(
                call_name,
                ok_formals.into_iter().map(|resolved| resolved.subpgm),
            ));
            return Err(EvalError::Unknown);
        }

        let ok_return_type = if let SubprogramKind::Function(rtyp) = kind {
            let mut ok_return_type = ok_assoc_types.clone();
            self.implicit_matcher()
                .disambiguate_op_by_return_type(&mut ok_return_type, rtyp);

            // Only one candidate matches type profile, check it
            if ok_return_type.len() == 1 {
                let ent = ok_return_type[0].subpgm;
                self.check_call(scope, call_pos, ent, assocs, diagnostics)?;
                return Ok(Disambiguated::Unambiguous(ent));
            } else if ok_return_type.is_empty() {
                diagnostics.push(Diagnostic::could_not_resolve(
                    call_name,
                    ok_assoc_types.into_iter().map(|resolved| resolved.subpgm),
                ));
                return Err(EvalError::Unknown);
            }
            ok_return_type
        } else {
            ok_assoc_types
        };

        let mut strict_ok_assoc_types = ok_return_type.clone();
        self.strict_matcher()
            .disambiguate_by_assoc_types(&actual_types, &mut strict_ok_assoc_types);

        if strict_ok_assoc_types.len() == 1 {
            let ent = strict_ok_assoc_types[0].subpgm;
            self.check_call(scope, call_pos, ent, assocs, diagnostics)?;
            return Ok(Disambiguated::Unambiguous(ent));
        } else if strict_ok_assoc_types.is_empty() {
            // Do not disambiguate away to emtpy result
            strict_ok_assoc_types = ok_return_type.clone();
        }

        Ok(Disambiguated::Ambiguous(
            strict_ok_assoc_types
                .into_iter()
                .map(|resolved| resolved.subpgm)
                .collect(),
        ))
    }

    pub fn disambiguate_no_actuals(
        &self,
        name: &WithPos<Designator>,
        ttyp: Option<TypeEnt<'a>>,
        overloaded: &OverloadedName<'a>,
    ) -> Result<Option<Disambiguated<'a>>, Diagnostic> {
        let mut candidates = Candidates::new(overloaded);

        let tbase = ttyp.map(|ttyp| ttyp.base());

        for cand in candidates.remaining() {
            if !cand.ent.signature().can_be_called_without_actuals() {
                cand.rejection = Some(Rejection::MissingFormals(
                    cand.ent.signature().formals_without_defaults().collect(),
                ));
            } else if let Some(return_type) = cand.ent.return_type() {
                if let Some(tbase) = tbase {
                    if !self.can_be_target_type(return_type, tbase) {
                        cand.rejection = Some(Rejection::ReturnType);
                    }
                }
            } else {
                cand.rejection = Some(Rejection::Procedure);
            }
        }

        Ok(Some(candidates.finish(name, ttyp)?))
    }
}

impl Diagnostic {
    fn could_not_resolve<'a>(
        name: &WithPos<Designator>,
        rejected: impl IntoIterator<Item = OverloadedEnt<'a>>,
    ) -> Self {
        let mut diag = Diagnostic::error(
            &name.pos,
            format!("Could not resolve call to '{}'", name.designator()),
        );
        diag.add_subprogram_candidates("Does not match", rejected);
        diag
    }
}

#[cfg(test)]
mod tests {

    use super::*;
    use crate::analysis::tests::TestSetup;
    use crate::data::DiagnosticHandler;
    use crate::syntax::test::check_diagnostics;
    use crate::syntax::test::Code;

    impl<'a> TestSetup<'a> {
        fn disambiguate(
            &'a self,
            code: &Code,
            ttyp: Option<TypeEnt<'a>>,
            diagnostics: &mut dyn DiagnosticHandler,
        ) -> Option<Disambiguated<'a>> {
            let mut fcall = code.function_call();

            let des = if let Name::Designator(des) = &fcall.item.name.item {
                WithPos::new(des.item.clone(), fcall.item.name.pos.clone())
            } else {
                panic!("Expected designator")
            };

            let overloaded = if let NamedEntities::Overloaded(overloaded) =
                self.scope.lookup(&fcall.item.name.pos, &des.item).unwrap()
            {
                overloaded
            } else {
                panic!("Expected overloaded")
            };

            as_fatal(self.ctx().disambiguate(
                &self.scope,
                &fcall.pos,
                &des,
                &mut fcall.item.parameters,
                SubprogramKind::Function(ttyp),
                overloaded.entities().collect(),
                diagnostics,
            ))
            .unwrap()
        }
    }

    #[test]
    fn single_fcall() {
        let test = TestSetup::new();
        let decl = test.declarative_part(
            "
function myfun return integer;
        ",
        );

        let func = test.lookup_overloaded(decl.s1("myfun"));

        assert_eq!(
            test.disambiguate(&test.snippet("myfun"), None, &mut NoDiagnostics),
            Some(Disambiguated::Unambiguous(func))
        );
    }

    #[test]
    fn single_fcall_bad_type() {
        let test = TestSetup::new();
        let decl = test.declarative_part(
            "
function myfun(arg : integer) return integer;
        ",
        );

        let mut diagnostics = Vec::new();
        let call = test.snippet("myfun('c')");
        assert_eq!(
            test.disambiguate(&call, None, &mut diagnostics),
            Some(Disambiguated::Unambiguous(
                test.lookup_overloaded(decl.s1("myfun"))
            )),
        );

        check_diagnostics(
            diagnostics,
            vec![Diagnostic::error(
                call.s1("'c'"),
                "character literal does not match integer type 'INTEGER'",
            )],
        );
    }

    #[test]
    fn disambiguate_fcall_based_on_named_association() {
        let test = TestSetup::new();
        let decl = test.declarative_part(
            "
function myfun(arg1 : integer) return integer;
function myfun(arg2 : integer) return character;
        ",
        );

        let func = test.lookup_overloaded(decl.s1("myfun(arg1").s1("myfun"));

        assert_eq!(
            test.disambiguate(&test.snippet("myfun(arg1 => 0)"), None, &mut NoDiagnostics),
            Some(Disambiguated::Unambiguous(func))
        );
    }

    #[test]
    fn disambiguate_fcall_formal_mismatch() {
        let test = TestSetup::new();
        let decl = test.declarative_part(
            "
function myfun(arg1 : integer) return integer;
        ",
        );

        let fcall = test.snippet("myfun(missing => 0)");
        let mut diagnostics = Vec::new();
        assert_eq!(
            test.disambiguate(&fcall, None, &mut diagnostics),
            Some(Disambiguated::Unambiguous(
                test.lookup_overloaded(decl.s1("myfun"))
            ))
        );
        check_diagnostics(
            diagnostics,
            vec![
                Diagnostic::error(fcall.s1("missing"), "No declaration of 'missing'"),
                Diagnostic::error(fcall, "No association of interface constant 'arg1'")
                    .related(decl.s1("arg1"), "Defined here"),
            ],
        );
    }

    #[test]
    fn disambiguate_fcall_no_candidates_matching_actuals() {
        let test = TestSetup::new();
        let decl = test.declarative_part(
            "
function myfun(arg1 : integer) return integer;
function myfun(arg2 : integer) return character;
        ",
        );

        let fcall = test.snippet("myfun");
        let mut diagnostics = Vec::new();
        assert_eq!(test.disambiguate(&fcall, None, &mut diagnostics), None);
        check_diagnostics(
            diagnostics,
            vec![
                Diagnostic::error(fcall.s1("myfun"), "Could not resolve call to 'myfun'")
                    .related(
                        decl.s1("myfun"),
                        "Does not match myfun[INTEGER return INTEGER]",
                    )
                    .related(
                        decl.s("myfun", 2),
                        "Does not match myfun[INTEGER return CHARACTER]",
                    ),
            ],
        );
    }

    #[test]
    fn disambiguate_fcall_based_on_type() {
        let test = TestSetup::new();
        let decl = test.declarative_part(
            "
function myfun(arg1 : character) return integer;
function myfun(arg1 : integer) return integer;
        ",
        );
        let fcall = test.snippet("myfun('c')");
        assert_eq!(
            test.disambiguate(&fcall, None, &mut NoDiagnostics),
            Some(Disambiguated::Unambiguous(
                test.lookup_overloaded(decl.s1("myfun"))
            ))
        );

        let fcall = test.snippet("myfun(0)");
        assert_eq!(
            test.disambiguate(&fcall, None, &mut NoDiagnostics),
            Some(Disambiguated::Unambiguous(
                test.lookup_overloaded(decl.s("myfun", 2))
            ))
        );
    }

    #[test]
    fn ambiguous_call() {
        let test = TestSetup::new();
        let decl = test.declarative_part(
            "
function myfun(arg1 : integer) return character;
function myfun(arg1 : integer) return integer;
        ",
        );
        let fcall = test.snippet("myfun(0)");
        assert_eq!(
            test.disambiguate(&fcall, None, &mut NoDiagnostics),
            Some(Disambiguated::Ambiguous(vec![
                test.lookup_overloaded(decl.s("myfun", 2)),
                test.lookup_overloaded(decl.s1("myfun")),
            ]))
        );
    }

    #[test]
    fn ambiguous_call_without_match() {
        let test = TestSetup::new();
        let decl = test.declarative_part(
            "
function myfun(arg1 : character) return integer;
function myfun(arg1 : character) return character;
        ",
        );
        let fcall = test.snippet("myfun(0)");
        let mut diagnostics = Vec::new();
        assert_eq!(test.disambiguate(&fcall, None, &mut diagnostics), None);
        check_diagnostics(
            diagnostics,
            vec![
                Diagnostic::error(fcall.s1("myfun"), "Could not resolve call to 'myfun'")
                    .related(
                        decl.s1("myfun"),
                        "Does not match myfun[CHARACTER return INTEGER]",
                    )
                    .related(
                        decl.s("myfun", 2),
                        "Does not match myfun[CHARACTER return CHARACTER]",
                    ),
            ],
        );
    }

    #[test]
    fn disambiguates_target_type() {
        let test = TestSetup::new();
        let decl = test.declarative_part(
            "
function myfun(arg1 : integer) return integer;
function myfun(arg1 : integer) return character;
        ",
        );
        let fcall = test.snippet("myfun(0)");
        assert_eq!(
            test.disambiguate(
                &fcall,
                Some(test.lookup_type("integer")),
                &mut NoDiagnostics
            ),
            Some(Disambiguated::Unambiguous(
                test.lookup_overloaded(decl.s1("myfun"))
            ))
        );
    }

    #[test]
    fn target_type_no_match() {
        let test = TestSetup::new();
        let decl = test.declarative_part(
            "
function myfun(arg1 : integer) return integer;
function myfun(arg1 : integer) return character;
        ",
        );
        let fcall = test.snippet("myfun(0)");
        let mut diagnostics = Vec::new();

        assert_eq!(
            test.disambiguate(&fcall, Some(test.lookup_type("boolean")), &mut diagnostics),
            None,
        );

        check_diagnostics(
            diagnostics,
            vec![
                Diagnostic::error(fcall.s1("myfun"), "Could not resolve call to 'myfun'")
                    .related(
                        decl.s1("myfun"),
                        "Does not match myfun[INTEGER return INTEGER]",
                    )
                    .related(
                        decl.s("myfun", 2),
                        "Does not match myfun[INTEGER return CHARACTER]",
                    ),
            ],
        )
    }

    #[test]
    fn ambiguous_builtin_favors_non_implicit_conversion_unary() {
        let test = TestSetup::new();
        let code = test.snippet("to_string(0)");

        let uint_to_string = test
            .ctx()
            .universal_integer()
            .lookup_implicit_of("TO_STRING");

        assert_eq!(
            test.disambiguate(&code, None, &mut NoDiagnostics),
            Some(Disambiguated::Unambiguous(uint_to_string))
        );
    }

    #[test]
    fn ambiguous_builtin_favors_non_implicit_conversion_binary() {
        let test = TestSetup::new();
        let code = test.snippet("minimum(0, integer'(0))");

        let minimum = test.ctx().integer().lookup_implicit_of("MINIMUM");

        assert_eq!(
            test.disambiguate(&code, None, &mut NoDiagnostics),
            Some(Disambiguated::Unambiguous(minimum))
        );
    }
}