vhdl_lang 0.86.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
// 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 super::names::*;
use super::*;
use crate::ast::token_range::WithTokenSpan;
use crate::ast::*;
use crate::data::error_codes::ErrorCode;
use crate::data::*;
use crate::named_entity::{Signature, *};
use crate::{ast, HasTokenSpan};
use analyze::*;
use itertools::Itertools;
use vhdl_lang::TokenSpan;

impl<'a> AnalyzeContext<'a, '_> {
    fn subprogram_header(
        &self,
        scope: &Scope<'a>,
        parent: EntRef<'a>,
        header: &mut SubprogramHeader,
        diagnostics: &mut dyn DiagnosticHandler,
    ) -> FatalResult<Region<'a>> {
        let mut region = Region::default();
        for decl in header.generic_list.items.iter_mut() {
            if let Some(ents) =
                as_fatal(self.analyze_interface_declaration(scope, parent, decl, diagnostics))?
            {
                for ent in ents {
                    region.add(ent, diagnostics);
                    scope.add(ent, diagnostics);
                }
            }
        }
        self.analyze_map_aspect(scope, &mut header.map_aspect, diagnostics)?;
        Ok(region)
    }

    pub(crate) fn subprogram_body(
        &self,
        scope: &Scope<'a>,
        parent: EntRef<'a>,
        body: &mut SubprogramBody,
        diagnostics: &mut dyn DiagnosticHandler,
    ) -> FatalResult {
        let (subpgm_region, subpgm_ent) = match as_fatal(self.subprogram_specification(
            scope,
            parent,
            &mut body.specification,
            body.span,
            Overloaded::Subprogram,
            diagnostics,
        ))? {
            Some(r) => r,
            None => {
                return Ok(());
            }
        };

        scope.add(subpgm_ent, diagnostics);

        self.define_labels_for_sequential_part(
            &subpgm_region,
            subpgm_ent,
            &mut body.statements,
            diagnostics,
        )?;
        self.analyze_declarative_part(
            &subpgm_region,
            subpgm_ent,
            &mut body.declarations,
            diagnostics,
        )?;

        self.analyze_sequential_part(
            &subpgm_region,
            subpgm_ent,
            &mut body.statements,
            diagnostics,
        )?;
        Ok(())
    }

    fn push_invalid_formals_into_diagnostics(
        &self,
        invalid_formals: &[InterfaceEnt<'a>],
        diagnostics: &mut dyn DiagnosticHandler,
    ) {
        for invalid_formal in invalid_formals {
            if let Some(decl_pos) = invalid_formal.decl_pos() {
                diagnostics.push(Diagnostic::invalid_formal(decl_pos))
            }
        }
    }

    pub(crate) fn subprogram_specification(
        &self,
        scope: &Scope<'a>,
        parent: EntRef<'a>,
        subprogram: &mut SubprogramSpecification,
        span: TokenSpan,
        to_kind: impl Fn(Signature<'a>) -> Overloaded<'a>,
        diagnostics: &mut dyn DiagnosticHandler,
    ) -> EvalResult<(Scope<'a>, EntRef<'a>)> {
        let subpgm_region = scope.nested();
        let ent = self.arena.explicit(
            subprogram
                .subpgm_designator()
                .item
                .clone()
                .into_designator(),
            parent,
            AnyEntKind::Overloaded(to_kind(Signature::new(ParameterRegion::default(), None))),
            Some(subprogram.subpgm_designator().pos(self.ctx)),
            span,
            Some(self.source()),
        );

        let (signature, generic_map) = match subprogram {
            SubprogramSpecification::Function(fun) => {
                let generic_map = if let Some(header) = &mut fun.header {
                    Some(self.subprogram_header(&subpgm_region, ent, header, diagnostics)?)
                } else {
                    None
                };
                let params = if let Some(parameter_list) = &mut fun.parameter_list {
                    self.analyze_interface_list(&subpgm_region, ent, parameter_list, diagnostics)
                } else {
                    Ok(FormalRegion::new_params())
                };
                let return_type = self.type_name(
                    &subpgm_region,
                    fun.return_type.span,
                    &mut fun.return_type.item,
                    diagnostics,
                );
                match ParameterRegion::from_formal_region(params?) {
                    Ok(params) => (Signature::new(params, Some(return_type?)), generic_map),
                    Err(invalid_formals) => {
                        self.push_invalid_formals_into_diagnostics(&invalid_formals, diagnostics);
                        return Err(EvalError::Unknown);
                    }
                }
            }
            SubprogramSpecification::Procedure(procedure) => {
                let generic_map = if let Some(header) = &mut procedure.header {
                    Some(self.subprogram_header(&subpgm_region, ent, header, diagnostics)?)
                } else {
                    None
                };
                let params = if let Some(parameter_list) = &mut procedure.parameter_list {
                    self.analyze_interface_list(&subpgm_region, ent, parameter_list, diagnostics)
                } else {
                    Ok(FormalRegion::new_params())
                };
                match ParameterRegion::from_formal_region(params?) {
                    Ok(params) => (Signature::new(params, None), generic_map),
                    Err(invalid_formals) => {
                        self.push_invalid_formals_into_diagnostics(&invalid_formals, diagnostics);
                        return Err(EvalError::Unknown);
                    }
                }
            }
        };

        let mut kind = to_kind(signature);
        if let Some(map) = generic_map {
            match kind {
                Overloaded::SubprogramDecl(signature) => {
                    kind = Overloaded::UninstSubprogramDecl(signature, map)
                }
                Overloaded::Subprogram(signature) => {
                    kind = Overloaded::UninstSubprogram(signature, map)
                }
                _ => unreachable!(),
            }
        }

        match kind {
            Overloaded::Subprogram(_) => {
                let declared_by =
                    self.find_subpgm_specification(scope, subprogram, kind.signature());

                if let Some(declared_by) = declared_by {
                    unsafe {
                        ent.set_declared_by(declared_by.into());
                    }
                }
            }
            Overloaded::UninstSubprogram(_, _) => {
                let declared_by =
                    self.find_uninst_subpgm_specification(scope, subprogram, kind.signature());

                if let Some(declared_by) = declared_by {
                    unsafe {
                        ent.set_declared_by(declared_by.into());
                    }
                }
            }
            _ => {}
        }

        unsafe {
            ent.set_kind(AnyEntKind::Overloaded(kind));
        }
        subprogram.set_decl_id(ent.id());
        Ok((subpgm_region, ent))
    }

    pub fn resolve_signature(
        &self,
        scope: &Scope<'a>,
        signature: &mut WithTokenSpan<ast::Signature>,
        diagnostics: &mut dyn DiagnosticHandler,
    ) -> EvalResult<SignatureKey<'_>> {
        let (args, return_type) = match &mut signature.item {
            ast::Signature::Function(ref mut args, ref mut ret) => {
                let args: Vec<_> = args
                    .iter_mut()
                    .map(|arg| self.type_name(scope, arg.span, &mut arg.item, diagnostics))
                    .collect();
                let return_type = self.type_name(scope, ret.span, &mut ret.item, diagnostics);
                (args, Some(return_type))
            }
            ast::Signature::Procedure(args) => {
                let args: Vec<_> = args
                    .iter_mut()
                    .map(|arg| self.type_name(scope, arg.span, &mut arg.item, diagnostics))
                    .collect();
                (args, None)
            }
        };

        let mut params = Vec::with_capacity(args.len());
        for arg in args {
            params.push(arg?.base());
        }

        if let Some(return_type) = return_type {
            Ok(SignatureKey::new(
                params,
                Some(return_type?.base_type().base()),
            ))
        } else {
            Ok(SignatureKey::new(params, None))
        }
    }

    /// Analyze a generic subprogram instance, i.e.,
    /// ```vhdl
    /// procedure my_proc is new my_proc generic map (T => std_logic);
    /// ```
    ///
    /// # Arguments
    ///
    /// * `scope` - The scope that this instance was declared in
    /// * `inst_subprogram_ent` - A reference to the instantiated subprogram entity.
    ///   Used to set the parent reference of the signature
    /// * `uninst_name` - The [ResolvedName] of the uninstantiated subprogram
    /// * `instance` - A reference to the AST element of the subprogram instantiation
    /// * `diagnostics` - The diagnostics handler
    ///
    /// # Returns
    /// The signature after applying the optional map aspect of the uninstantiated subprogram
    pub(crate) fn generic_subprogram_instance(
        &self,
        scope: &Scope<'a>,
        inst_subprogram_ent: &EntRef<'a>,
        uninst_name: &ResolvedName<'a>,
        instance: &mut SubprogramInstantiation,
        diagnostics: &mut dyn DiagnosticHandler,
    ) -> EvalResult<Signature<'_>> {
        let uninstantiated_subprogram =
            self.resolve_uninstantiated_subprogram(scope, uninst_name, instance, diagnostics)?;
        self.check_instantiated_subprogram_kind_matches_declared(
            &uninstantiated_subprogram,
            instance,
            diagnostics,
        );
        instance
            .subprogram_name
            .item
            .set_unique_reference(&uninstantiated_subprogram);
        let region = match uninstantiated_subprogram.kind() {
            Overloaded::UninstSubprogramDecl(_, region) => region,
            Overloaded::UninstSubprogram(_, region) => region,
            _ => unreachable!(),
        };

        let nested = scope.nested();

        match as_fatal(self.generic_instance(
            inst_subprogram_ent,
            scope,
            instance.ident.tree.pos(self.ctx),
            region,
            &mut instance.generic_map,
            diagnostics,
        ))? {
            None => Ok(uninstantiated_subprogram.signature().clone()),
            Some((_, mapping)) => {
                match self.map_signature(
                    Some(inst_subprogram_ent),
                    &mapping,
                    uninstantiated_subprogram.signature(),
                    &nested,
                ) {
                    Ok(signature) => Ok(signature),
                    Err((err, code)) => {
                        let mut diag =
                            Diagnostic::new(instance.ident.tree.pos(self.ctx), err, code);
                        if let Some(pos) = uninstantiated_subprogram.decl_pos() {
                            diag.add_related(pos, "When instantiating this declaration");
                        }
                        diagnostics.push(diag);
                        Err(EvalError::Unknown)
                    }
                }
            }
        }
    }

    /// Given a `ResolvedName` and the subprogram instantiation,
    /// find the uninstantiated subprogram that the resolved name references.
    /// Return that resolved subprogram, if it exists, else return an `Err`
    fn resolve_uninstantiated_subprogram(
        &self,
        scope: &Scope<'a>,
        name: &ResolvedName<'a>,
        instantiation: &mut SubprogramInstantiation,
        diagnostics: &mut dyn DiagnosticHandler,
    ) -> EvalResult<OverloadedEnt<'a>> {
        let signature_key = match &mut instantiation.signature {
            None => None,
            Some(ref mut signature) => Some((
                self.resolve_signature(scope, signature, diagnostics)?,
                signature.pos(self.ctx),
            )),
        };
        let overloaded_ent = match name {
            ResolvedName::Overloaded(_, overloaded) => {
                let choices = overloaded
                    .entities()
                    .filter(|ent| ent.is_uninst_subprogram())
                    .collect_vec();
                if choices.is_empty() {
                    diagnostics.add(
                        instantiation.ident.tree.pos(self.ctx),
                        format!(
                            "{} does not denote an uninstantiated subprogram",
                            name.describe()
                        ),
                        ErrorCode::MismatchedKinds,
                    );
                    return Err(EvalError::Unknown);
                } else if choices.len() == 1 {
                    // There is only one possible candidate
                    let ent = choices[0];
                    // If the instantiated program has a signature, check that it matches
                    // that of the uninstantiated subprogram
                    if let Some((key, pos)) = signature_key {
                        match overloaded.get(&SubprogramKey::Uninstantiated(key)) {
                            None => {
                                diagnostics.add(
                                    pos.clone(),
                                    format!(
                                        "Signature does not match the the signature of {}",
                                        ent.describe()
                                    ),
                                    ErrorCode::SignatureMismatch,
                                );
                                return Err(EvalError::Unknown);
                            }
                            Some(_) => ent,
                        }
                    } else {
                        ent
                    }
                } else if let Some((key, _)) = signature_key {
                    // There are multiple candidates
                    // but there is a signature that we can try to resolve
                    if let Some(resolved_ent) =
                        overloaded.get(&SubprogramKey::Uninstantiated(key.clone()))
                    {
                        resolved_ent
                    } else {
                        diagnostics.add(
                            instantiation.subprogram_name.pos(self.ctx),
                            format!(
                                "No uninstantiated subprogram exists with signature {}",
                                key.describe()
                            ),
                            ErrorCode::Unresolved,
                        );
                        return Err(EvalError::Unknown);
                    }
                } else {
                    // There are multiple candidates
                    // and there is no signature to resolve
                    let mut err = Diagnostic::new(
                        instantiation.subprogram_name.pos(self.ctx),
                        format!("Ambiguous instantiation of '{}'", overloaded.designator()),
                        ErrorCode::AmbiguousInstantiation,
                    );
                    for ent in choices {
                        if let Some(pos) = &ent.decl_pos {
                            err.add_related(pos.clone(), format!("Might be {}", ent.describe()))
                        }
                    }
                    diagnostics.push(err);
                    return Err(EvalError::Unknown);
                }
            }
            _ => {
                diagnostics.add(
                    instantiation.subprogram_name.pos(self.ctx),
                    format!(
                        "{} does not denote an uninstantiated subprogram",
                        name.describe()
                    ),
                    ErrorCode::MismatchedKinds,
                );
                return Err(EvalError::Unknown);
            }
        };
        if overloaded_ent.is_uninst_subprogram() {
            Ok(overloaded_ent)
        } else {
            diagnostics.add(
                instantiation.subprogram_name.pos(self.ctx),
                format!("{} cannot be instantiated", overloaded_ent.describe()),
                ErrorCode::MismatchedKinds,
            );
            Err(EvalError::Unknown)
        }
    }

    /// Checks that an instantiated subprogram kind matches the declared subprogram.
    /// For instance, when a subprogram was instantiated using
    /// ```vhdl
    /// function my_func is new proc;
    /// ```
    /// where proc is
    /// ```vhdl
    /// procedure proc is
    /// ...
    /// ```
    ///
    /// This function will push an appropriate diagnostic.
    fn check_instantiated_subprogram_kind_matches_declared(
        &self,
        ent: &OverloadedEnt<'_>,
        instance: &SubprogramInstantiation,
        diagnostics: &mut dyn DiagnosticHandler,
    ) {
        let err_msg = if ent.is_function() && instance.kind != SubprogramKind::Function {
            Some("Instantiating function as procedure")
        } else if ent.is_procedure() && instance.kind != SubprogramKind::Procedure {
            Some("Instantiating procedure as function")
        } else {
            None
        };
        if let Some(msg) = err_msg {
            let mut err = Diagnostic::new(
                self.ctx.get_pos(instance.get_start_token()),
                msg,
                ErrorCode::MismatchedSubprogramInstantiation,
            );
            if let Some(pos) = ent.decl_pos() {
                err.add_related(pos, format!("{} declared here", ent.describe()));
            }
            diagnostics.push(err)
        }
    }

    fn find_subpgm_specification(
        &self,
        scope: &Scope<'a>,
        decl: &SubprogramSpecification,
        signature: &Signature<'_>,
    ) -> Option<OverloadedEnt<'a>> {
        let des = decl.subpgm_designator().item.clone().into_designator();

        if let Some(NamedEntities::Overloaded(overloaded)) = scope.lookup_immediate(&des) {
            let ent = overloaded.get(&SubprogramKey::Normal(signature.key()))?;

            if ent.is_subprogram_decl() {
                return Some(ent);
            }
        }
        None
    }

    fn find_uninst_subpgm_specification(
        &self,
        scope: &Scope<'a>,
        decl: &SubprogramSpecification,
        signature: &Signature<'_>,
    ) -> Option<OverloadedEnt<'a>> {
        let des = decl.subpgm_designator().item.clone().into_designator();

        if let Some(NamedEntities::Overloaded(overloaded)) = scope.lookup_immediate(&des) {
            // Note: This does not work in common circumstances with a generic type parameter
            // since the parameters of the declared subprogram and the subprogram with body
            // point to two different type-ID's. For example:
            // function foo generic (type F) return F;
            //                            ^-- F has EntityId X
            // function foo generic (type F) return F is ... end function foo;
            //                            ^-- F has EntityId Y
            // A future improvement must take this fact into account.
            let ent = overloaded.get(&SubprogramKey::Uninstantiated(signature.key()))?;

            if ent.is_uninst_subprogram_decl() {
                return Some(ent);
            }
        }
        None
    }
}