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
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
// 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) 2019, Olof Kraigher olof.kraigher@gmail.com
use super::formal_region::FormalRegion;
use super::formal_region::RecordRegion;
use super::named_entity::*;
use super::names::*;
use super::sequential::SequentialRoot;
use super::*;
use crate::ast;
use crate::ast::*;
use crate::data::*;
use analyze::*;
use fnv::FnvHashMap;
use named_entity::Signature;
use region::*;
use std::collections::hash_map::Entry;
impl<'a> AnalyzeContext<'a> {
pub fn analyze_declarative_part(
&self,
scope: &Scope<'a>,
declarations: &mut [Declaration],
diagnostics: &mut dyn DiagnosticHandler,
) -> FatalResult {
let mut incomplete_types: FnvHashMap<Symbol, (EntRef<'a>, SrcPos)> = FnvHashMap::default();
for i in 0..declarations.len() {
// Handle incomplete types
let (decl, remaining) = declarations[i..].split_first_mut().unwrap();
match decl {
Declaration::Type(type_decl) => match type_decl.def {
TypeDefinition::Incomplete(ref mut reference) => {
match incomplete_types.entry(type_decl.ident.name().clone()) {
Entry::Vacant(entry) => {
let full_definiton =
find_full_type_definition(type_decl.ident.name(), remaining);
let decl_pos = match full_definiton {
Some(full_decl) => full_decl.ident.pos(),
None => {
let mut error = Diagnostic::error(
type_decl.ident.pos(),
format!(
"Missing full type declaration of incomplete type '{}'",
type_decl.ident.name()
),
);
error.add_related(type_decl.ident.pos(), "The full type declaration shall occur immediately within the same declarative part");
diagnostics.push(error);
type_decl.ident.pos()
}
};
let designator =
Designator::Identifier(type_decl.ident.name().clone());
// Set incomplete type defintion to position of full declaration
let ent = self.arena.explicit(
designator,
AnyEntKind::Type(Type::Incomplete),
Some(decl_pos),
);
reference.set_unique_reference(ent);
entry.insert((ent, type_decl.ident.pos().clone()));
scope.add(ent, diagnostics);
}
Entry::Occupied(entry) => {
let (_, decl_pos) = entry.get();
diagnostics.push(duplicate_error(
&type_decl.ident,
type_decl.ident.pos(),
Some(decl_pos),
));
}
}
}
_ => {
let incomplete_type = incomplete_types.get(type_decl.ident.name());
if let Some((incomplete_type, _)) = incomplete_type {
self.analyze_type_declaration(
scope,
type_decl,
Some(incomplete_type.id()),
diagnostics,
)?;
} else {
self.analyze_type_declaration(scope, type_decl, None, diagnostics)?;
}
}
},
_ => {
self.analyze_declaration(scope, &mut declarations[i], diagnostics)?;
}
}
}
Ok(())
}
fn analyze_alias_declaration(
&self,
scope: &Scope<'a>,
alias: &mut AliasDeclaration,
diagnostics: &mut dyn DiagnosticHandler,
) -> EvalResult<EntRef<'a>> {
let AliasDeclaration {
designator,
name,
subtype_indication,
signature,
} = alias;
let resolved_name = self.name_resolve(scope, &name.pos, &mut name.item, diagnostics);
if let Some(ref mut subtype_indication) = subtype_indication {
// Object alias
self.analyze_subtype_indication(scope, subtype_indication, diagnostics)?;
}
let resolved_name = resolved_name?;
let kind = {
match resolved_name {
ResolvedName::ObjectName(oname) => {
if let Some(ref signature) = signature {
diagnostics.push(Diagnostic::should_not_have_signature("Alias", signature));
}
match oname.base {
ObjectBase::Object(base_object) => AnyEntKind::ObjectAlias {
base_object,
type_mark: oname.type_mark(),
},
ObjectBase::ObjectAlias(base_object, _) => AnyEntKind::ObjectAlias {
base_object,
type_mark: oname.type_mark(),
},
ObjectBase::ExternalName(class) => AnyEntKind::ExternalAlias {
class,
type_mark: oname.type_mark(),
},
ObjectBase::DeferredConstant(_) => {
// @TODO handle
return Err(EvalError::Unknown);
}
}
}
ResolvedName::Library(_)
| ResolvedName::Design(_)
| ResolvedName::Expression(_) => {
if let Some(ref signature) = signature {
diagnostics.push(Diagnostic::should_not_have_signature("Alias", signature));
}
diagnostics.error(
&name.pos,
format!("{} cannot be aliased", resolved_name.describe_type()),
);
return Err(EvalError::Unknown);
}
ResolvedName::Type(typ) => {
if let Some(ref signature) = signature {
diagnostics.push(Diagnostic::should_not_have_signature("Alias", signature));
}
AnyEntKind::Type(Type::Alias(typ))
}
ResolvedName::Overloaded(des, overloaded) => {
if let Some(ref mut signature) = signature {
match self.resolve_signature(scope, signature) {
Ok(signature_key) => {
if let Some(ent) = overloaded.get(&signature_key) {
if let Some(reference) = name.item.suffix_reference_mut() {
reference.set_unique_reference(&ent);
}
AnyEntKind::Overloaded(Overloaded::Alias(ent))
} else {
diagnostics.push(Diagnostic::no_overloaded_with_signature(
&des.pos,
&des.item,
&overloaded,
));
return Err(EvalError::Unknown);
}
}
Err(err) => {
err.add_to(diagnostics)?;
return Err(EvalError::Unknown);
}
}
} else {
diagnostics.push(Diagnostic::signature_required(name));
return Err(EvalError::Unknown);
}
}
ResolvedName::Final(_) => {
// @TODO some of these can probably be aliased
return Err(EvalError::Unknown);
}
}
};
Ok(designator.define(self.arena, kind))
}
pub(crate) fn analyze_declaration(
&self,
scope: &Scope<'a>,
decl: &mut Declaration,
diagnostics: &mut dyn DiagnosticHandler,
) -> FatalResult {
match decl {
Declaration::Alias(alias) => {
if let Some(ent) =
as_fatal(self.analyze_alias_declaration(scope, alias, diagnostics))?
{
scope.add(ent, diagnostics);
for implicit in ent.as_actual().implicits.iter() {
match OverloadedEnt::from_any(implicit) {
Ok(implicit) => {
let impicit_alias = self.arena.implicit(
ent,
implicit.designator().clone(),
AnyEntKind::Overloaded(Overloaded::Alias(implicit)),
ent.decl_pos(),
);
scope.add(impicit_alias, diagnostics);
}
Err(ent) => {
eprintln!(
"Expect implicit declaration to be overloaded, got: {}",
ent.describe()
)
}
}
}
}
}
Declaration::Object(ref mut object_decl) => {
let subtype = self.resolve_subtype_indication(
scope,
&mut object_decl.subtype_indication,
diagnostics,
);
if let Some(ref mut expr) = object_decl.expression {
if let Ok(ref subtype) = subtype {
self.expr_pos_with_ttyp(
scope,
subtype.type_mark(),
&expr.pos,
&mut expr.item,
diagnostics,
)?;
} else {
self.expr_unknown_ttyp(scope, expr, diagnostics)?;
}
}
match subtype {
Ok(subtype) => {
let kind = if object_decl.class == ObjectClass::Constant
&& object_decl.expression.is_none()
{
AnyEntKind::DeferredConstant(subtype)
} else {
AnyEntKind::Object(Object {
class: object_decl.class,
mode: None,
has_default: object_decl.expression.is_some(),
subtype,
})
};
let declared_by = if object_decl.class == ObjectClass::Constant
&& object_decl.expression.is_some()
{
self.find_deferred_constant_declaration(
scope,
&object_decl.ident.tree.item,
)
} else {
None
};
let object_ent = self.arena.alloc(
object_decl.ident.tree.item.clone().into(),
if let Some(declared_by) = declared_by {
Related::DeclaredBy(declared_by)
} else {
Related::None
},
kind,
Some(object_decl.ident.tree.pos().clone()),
);
object_decl.ident.decl = Some(object_ent.id());
scope.add(object_ent, diagnostics);
}
Err(err) => err.add_to(diagnostics)?,
}
}
Declaration::File(ref mut file) => {
let FileDeclaration {
ident,
subtype_indication,
open_info,
file_name,
} = file;
let subtype =
match self.resolve_subtype_indication(scope, subtype_indication, diagnostics) {
Ok(subtype) => Some(subtype),
Err(err) => {
err.add_to(diagnostics)?;
None
}
};
if let Some(ref mut expr) = open_info {
self.expr_unknown_ttyp(scope, expr, diagnostics)?;
}
if let Some(ref mut expr) = file_name {
self.expr_unknown_ttyp(scope, expr, diagnostics)?;
}
if let Some(subtype) = subtype {
scope.add(
self.arena.define(ident, AnyEntKind::File(subtype)),
diagnostics,
);
}
}
Declaration::Component(ref mut component) => {
let nested = scope.nested();
self.analyze_interface_list(&nested, &mut component.generic_list, diagnostics)?;
self.analyze_interface_list(&nested, &mut component.port_list, diagnostics)?;
scope.add(
self.arena.define(
&mut component.ident,
AnyEntKind::Component(nested.into_region()),
),
diagnostics,
);
}
Declaration::Attribute(ref mut attr) => match attr {
Attribute::Declaration(ref mut attr_decl) => {
match self.resolve_type_mark(scope, &mut attr_decl.type_mark) {
Ok(typ) => {
scope.add(
self.arena
.define(&mut attr_decl.ident, AnyEntKind::Attribute(typ)),
diagnostics,
);
}
Err(err) => {
err.add_to(diagnostics)?;
}
}
}
// @TODO Ignored for now
Attribute::Specification(ref mut attr_spec) => {
let AttributeSpecification {
ident,
entity_name,
// @TODO also check the entity class
entity_class: _,
expr,
} = attr_spec;
match scope.lookup(
&ident.item.pos,
&Designator::Identifier(ident.item.name().clone()),
) {
Ok(NamedEntities::Single(ent)) => {
ident.set_unique_reference(ent);
if let AnyEntKind::Attribute(typ) = ent.actual_kind() {
self.expr_pos_with_ttyp(
scope,
*typ,
&expr.pos,
&mut expr.item,
diagnostics,
)?;
} else {
diagnostics.error(
&ident.item.pos,
format!("{} is not an attribute", ent.describe()),
);
}
}
Ok(NamedEntities::Overloaded(_)) => {
diagnostics.error(
&ident.item.pos,
format!("Overloaded name '{}' is not an attribute", ident.item),
);
}
Err(err) => {
diagnostics.push(err);
}
}
if let EntityName::Name(EntityTag {
designator,
signature,
}) = entity_name
{
match scope.lookup(&designator.pos, &designator.item.item) {
Ok(NamedEntities::Single(ent)) => {
designator.set_unique_reference(ent);
if let Some(signature) = signature {
diagnostics.push(Diagnostic::should_not_have_signature(
"Attribute specification",
&signature.pos,
));
}
}
Ok(NamedEntities::Overloaded(overloaded)) => {
if let Some(signature) = signature {
match self.resolve_signature(scope, signature) {
Ok(signature_key) => {
if let Some(ent) = overloaded.get(&signature_key) {
designator.set_unique_reference(&ent);
} else {
diagnostics.push(
Diagnostic::no_overloaded_with_signature(
&designator.pos,
&designator.item.item,
&overloaded,
),
);
}
}
Err(err) => {
err.add_to(diagnostics)?;
}
}
} else {
diagnostics.push(Diagnostic::signature_required(designator));
}
}
Err(err) => {
diagnostics.push(err);
}
}
}
}
},
Declaration::SubprogramBody(ref mut body) => {
let subpgm_region = scope.nested();
let signature = self.analyze_subprogram_declaration(
&subpgm_region,
&mut body.specification,
diagnostics,
);
// End mutable borrow of scope
let subpgm_region = Scope::new(subpgm_region.into_region());
// Overwrite subprogram definition with full signature
let sroot = match signature {
Ok(signature) => {
let sroot = if let Some(return_type) = signature.return_type() {
SequentialRoot::Function(return_type)
} else {
SequentialRoot::Procedure
};
let declared_by =
self.find_subpgm_declaration(scope, &body.specification, &signature);
let subpgm_ent = body.specification.define(
self.arena,
AnyEntKind::Overloaded(Overloaded::Subprogram(signature)),
declared_by,
);
scope.add(subpgm_ent, diagnostics);
sroot
}
Err(err) => {
err.add_to(diagnostics)?;
SequentialRoot::Unknown
}
};
let subpgm_region = subpgm_region.with_parent(scope);
self.analyze_declarative_part(&subpgm_region, &mut body.declarations, diagnostics)?;
self.analyze_sequential_part(
&subpgm_region,
&sroot,
&mut body.statements,
diagnostics,
)?;
}
Declaration::SubprogramDeclaration(ref mut subdecl) => {
let subpgm_region = scope.nested();
let signature =
self.analyze_subprogram_declaration(&subpgm_region, subdecl, diagnostics);
drop(subpgm_region);
match signature {
Ok(signature) => {
scope.add(
subdecl.define(
self.arena,
AnyEntKind::Overloaded(Overloaded::SubprogramDecl(signature)),
None,
),
diagnostics,
);
}
Err(err) => err.add_to(diagnostics)?,
}
}
Declaration::Use(ref mut use_clause) => {
self.analyze_use_clause(scope, &mut use_clause.item, diagnostics)?;
}
Declaration::Package(ref mut instance) => {
if let Some(pkg_region) =
as_fatal(self.generic_package_instance(scope, instance, diagnostics))?
{
scope.add(
self.arena.define(
&mut instance.ident,
AnyEntKind::Design(Design::PackageInstance(pkg_region)),
),
diagnostics,
);
}
}
Declaration::Configuration(..) => {}
Declaration::Type(..) => unreachable!("Handled elsewhere"),
};
Ok(())
}
fn find_subpgm_declaration(
&self,
scope: &Scope<'a>,
decl: &SubprogramDeclaration,
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(&signature.key())?;
if ent.is_subprogram_decl() {
return Some(ent);
}
}
None
}
fn find_deferred_constant_declaration(
&self,
scope: &Scope<'a>,
ident: &Symbol,
) -> Option<EntRef<'a>> {
if let Some(NamedEntities::Single(ent)) = scope.lookup_immediate(&ident.into()) {
if ent.kind().is_deferred_constant() {
return Some(ent);
}
}
None
}
pub(crate) fn analyze_type_declaration(
&self,
scope: &Scope<'a>,
type_decl: &mut TypeDeclaration,
// Is the full type declaration of an incomplete type
// Overwrite id when defining full type
overwrite_id: Option<EntityId>,
diagnostics: &mut dyn DiagnosticHandler,
) -> FatalResult {
match type_decl.def {
TypeDefinition::Enumeration(ref mut enumeration) => {
let enum_type = TypeEnt::define_with_opt_id(
self.arena,
overwrite_id,
&mut type_decl.ident,
None,
Type::Enum(
enumeration
.iter()
.map(|literal| literal.tree.item.clone().into_designator())
.collect(),
),
);
let signature = Signature::new(
FormalRegion::new(InterfaceListType::Parameter),
Some(enum_type),
);
for literal in enumeration.iter_mut() {
let literal_ent = self.arena.explicit(
literal.tree.item.clone().into_designator(),
AnyEntKind::Overloaded(Overloaded::EnumLiteral(signature.clone())),
Some(&literal.tree.pos),
);
literal.decl = Some(literal_ent.id());
unsafe {
self.arena.add_implicit(enum_type.id(), literal_ent);
}
scope.add(literal_ent, diagnostics);
}
scope.add(enum_type.into(), diagnostics);
for ent in self.enum_implicits(enum_type, self.has_matching_op(enum_type)) {
unsafe {
self.arena.add_implicit(enum_type.id(), ent);
}
scope.add(ent, diagnostics);
}
}
TypeDefinition::ProtectedBody(ref mut body) => {
match scope.lookup_immediate(&type_decl.ident.tree.item.clone().into()) {
Some(visible) => {
let is_ok = match visible.clone().into_non_overloaded() {
Ok(ent) => {
if let AnyEntKind::Type(Type::Protected(ptype_region, is_body)) =
ent.kind()
{
let region = Scope::extend(ptype_region, Some(scope));
self.analyze_declarative_part(
®ion,
&mut body.decl,
diagnostics,
)?;
if *is_body {
if let Some(prev_pos) = ent.decl_pos() {
diagnostics.push(duplicate_error(
&type_decl.ident.tree,
&type_decl.ident.tree.pos,
Some(prev_pos),
))
}
} else {
let ptype_body: &'a AnyEnt = TypeEnt::define_with_opt_id(
self.arena,
overwrite_id,
&mut type_decl.ident,
Some(ent),
Type::Protected(region.into_region(), true),
)
.into();
scope.add(ptype_body, diagnostics);
}
true
} else {
false
}
}
_ => false,
};
if !is_ok {
diagnostics.push(Diagnostic::error(
type_decl.ident.pos(),
format!("'{}' is not a protected type", &type_decl.ident),
));
}
}
None => {
diagnostics.push(Diagnostic::error(
type_decl.ident.pos(),
format!("No declaration of protected type '{}'", &type_decl.ident),
));
}
};
}
TypeDefinition::Protected(ref mut prot_decl) => {
// Protected type name is visible inside its declarative region
// This will be overwritten later when the protected type region is finished
let ptype: &'a AnyEnt = TypeEnt::define_with_opt_id(
self.arena,
overwrite_id,
&mut type_decl.ident,
None,
Type::Protected(Region::default(), false),
)
.into();
scope.add(ptype, diagnostics);
let region = scope.nested();
for item in prot_decl.items.iter_mut() {
match item {
ProtectedTypeDeclarativeItem::Subprogram(ref mut subprogram) => {
let subpgm_region = region.nested();
let signature = self.analyze_subprogram_declaration(
&subpgm_region,
subprogram,
diagnostics,
);
drop(subpgm_region);
match signature {
Ok(signature) => {
region.add(
subprogram.define(
self.arena,
AnyEntKind::Overloaded(Overloaded::SubprogramDecl(
signature,
)),
None,
),
diagnostics,
);
}
Err(err) => {
err.add_to(diagnostics)?;
}
}
}
}
}
// This is safe since we are in a single thread and no other reference can exist yes
// Also the region is stored inside an Arc which cannot move
{
let AnyEntKind::Type(Type::Protected(region_ptr, _)) = ptype.kind() else {
unreachable!();
};
let region_ptr = unsafe {
let region_ptr = region_ptr as *const Region;
let region_ptr = region_ptr as *mut Region;
&mut *region_ptr as &mut Region
};
*region_ptr = region.into_region();
}
}
TypeDefinition::Record(ref mut element_decls) => {
let mut elems = RecordRegion::default();
let mut region = Region::default();
for elem_decl in element_decls.iter_mut() {
let subtype =
self.resolve_subtype_indication(scope, &mut elem_decl.subtype, diagnostics);
match subtype {
Ok(subtype) => {
let elem = self.arena.define(
&mut elem_decl.ident,
AnyEntKind::ElementDeclaration(subtype),
);
region.add(elem, diagnostics);
elems.add(elem);
}
Err(err) => {
err.add_to(diagnostics)?;
}
}
}
region.close(diagnostics);
let type_ent = TypeEnt::define_with_opt_id(
self.arena,
overwrite_id,
&mut type_decl.ident,
None,
Type::Record(elems),
);
scope.add(type_ent.into(), diagnostics);
for ent in self.record_implicits(type_ent) {
unsafe {
self.arena.add_implicit(type_ent.id(), ent);
}
scope.add(ent, diagnostics);
}
}
TypeDefinition::Access(ref mut subtype_indication) => {
let subtype =
self.resolve_subtype_indication(scope, subtype_indication, diagnostics);
match subtype {
Ok(subtype) => {
let type_ent = TypeEnt::define_with_opt_id(
self.arena,
overwrite_id,
&mut type_decl.ident,
None,
Type::Access(subtype),
);
scope.add(type_ent.into(), diagnostics);
for ent in self.access_implicits(type_ent) {
unsafe {
self.arena.add_implicit(type_ent.id(), ent);
}
scope.add(ent, diagnostics);
}
}
Err(err) => err.add_to(diagnostics)?,
}
}
TypeDefinition::Array(ref mut array_indexes, ref mut subtype_indication) => {
let mut indexes: Vec<Option<BaseType>> = Vec::with_capacity(array_indexes.len());
for index in array_indexes.iter_mut() {
indexes.push(as_fatal(self.analyze_array_index(
scope,
index,
diagnostics,
))?);
}
let elem_type =
match self.resolve_subtype_indication(scope, subtype_indication, diagnostics) {
Ok(subtype) => subtype.type_mark().to_owned(),
Err(err) => {
err.add_to(diagnostics)?;
return Ok(());
}
};
let is_1d = indexes.len() == 1;
let array_ent = TypeEnt::define_with_opt_id(
self.arena,
overwrite_id,
&mut type_decl.ident,
None,
Type::Array { indexes, elem_type },
);
scope.add(array_ent.into(), diagnostics);
for ent in self.array_implicits(array_ent, is_1d && self.has_matching_op(elem_type))
{
unsafe {
self.arena.add_implicit(array_ent.id(), ent);
}
scope.add(ent, diagnostics);
}
}
TypeDefinition::Subtype(ref mut subtype_indication) => {
match self.resolve_subtype_indication(scope, subtype_indication, diagnostics) {
Ok(subtype) => {
let type_ent = TypeEnt::define_with_opt_id(
self.arena,
overwrite_id,
&mut type_decl.ident,
None,
Type::Subtype(subtype),
);
scope.add(type_ent.into(), diagnostics);
}
Err(err) => {
err.add_to(diagnostics)?;
}
}
}
TypeDefinition::Physical(ref mut physical) => {
self.range_with_ttyp(
scope,
self.universal_integer().into(),
&mut physical.range,
diagnostics,
)?;
let phys_type = TypeEnt::define_with_opt_id(
self.arena,
overwrite_id,
&mut type_decl.ident,
None,
Type::Physical,
);
scope.add(phys_type.into(), diagnostics);
let primary = self.arena.define(
&mut physical.primary_unit,
AnyEntKind::PhysicalLiteral(phys_type),
);
unsafe {
self.arena.add_implicit(phys_type.id(), primary);
}
scope.add(primary, diagnostics);
for (secondary_unit_name, value) in physical.secondary_units.iter_mut() {
match self.resolve_physical_unit(scope, &mut value.unit) {
Ok(secondary_unit_type) => {
if secondary_unit_type.base_type() != phys_type {
diagnostics.error(
&value.unit.item.pos,
format!(
"Physical unit of type '{}' does not match {}",
secondary_unit_type.designator(),
phys_type.describe()
),
)
}
}
Err(err) => diagnostics.push(err),
}
let secondary_unit = self
.arena
.define(secondary_unit_name, AnyEntKind::PhysicalLiteral(phys_type));
unsafe {
self.arena.add_implicit(phys_type.id(), secondary_unit);
}
scope.add(secondary_unit, diagnostics)
}
for ent in self.physical_implicits(phys_type) {
unsafe {
self.arena.add_implicit(phys_type.id(), ent);
}
scope.add(ent, diagnostics);
}
}
TypeDefinition::Incomplete(..) => {
unreachable!("Handled elsewhere");
}
TypeDefinition::Numeric(ref mut range) => {
self.range_unknown_typ(scope, range, diagnostics)?;
let universal_type = if let Some(range_typ) =
as_fatal(self.range_type(scope, range, diagnostics))?
{
if range_typ.is_any_integer() {
UniversalType::Integer
} else if range_typ.is_any_real() {
UniversalType::Real
} else {
diagnostics.error(&range.pos(), "Expected real or integer range");
return Ok(());
}
} else {
return Ok(());
};
let type_ent = TypeEnt::define_with_opt_id(
self.arena,
overwrite_id,
&mut type_decl.ident,
None,
match universal_type {
UniversalType::Integer => Type::Integer,
UniversalType::Real => Type::Real,
},
);
scope.add(type_ent.into(), diagnostics);
for ent in self.numeric_implicits(universal_type, type_ent) {
unsafe {
self.arena.add_implicit(type_ent.id(), ent);
}
scope.add(ent, diagnostics);
}
}
TypeDefinition::File(ref mut type_mark) => {
let file_type = TypeEnt::define_with_opt_id(
self.arena,
overwrite_id,
&mut type_decl.ident,
None,
Type::File,
);
match self.resolve_type_mark(scope, type_mark) {
Ok(type_mark) => {
for ent in self.create_implicit_file_type_subprograms(file_type, type_mark)
{
unsafe {
self.arena.add_implicit(file_type.id(), ent);
}
scope.add(ent, diagnostics);
}
}
Err(err) => {
err.add_to(diagnostics)?;
}
}
scope.add(file_type.into(), diagnostics);
}
}
Ok(())
}
/// The matching operators such as ?= are defined for 1d arrays of bit and std_ulogic element type
fn has_matching_op(&self, typ: TypeEnt<'a>) -> bool {
if self.is_std_logic_1164 {
// Within the std_logic_1164 we do not have efficient access to the types
typ.designator() == &Designator::Identifier(self.root.symbol_utf8("std_ulogic"))
} else {
if let Some(ref standard_types) = self.root.standard_types {
if typ.id() == standard_types.bit {
return true;
}
}
if let Some(id) = self.root.std_ulogic {
if typ.id() == id {
return true;
}
}
false
}
}
pub fn resolve_signature(
&self,
scope: &Scope<'a>,
signature: &mut WithPos<ast::Signature>,
) -> AnalysisResult<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.resolve_type_mark(scope, arg))
.collect();
let return_type = self.resolve_type_mark(scope, ret);
(args, Some(return_type))
}
ast::Signature::Procedure(args) => {
let args: Vec<_> = args
.iter_mut()
.map(|arg| self.resolve_type_mark(scope, arg))
.collect();
(args, None)
}
};
let mut params = Vec::with_capacity(args.len());
for arg in args {
params.push(arg?.base_type().id());
}
if let Some(return_type) = return_type {
Ok(SignatureKey::new(
params,
Some(return_type?.base_type().id()),
))
} else {
Ok(SignatureKey::new(params, None))
}
}
fn analyze_interface_declaration(
&self,
scope: &Scope<'a>,
decl: &mut InterfaceDeclaration,
diagnostics: &mut dyn DiagnosticHandler,
) -> AnalysisResult<EntRef<'a>> {
let ent = match decl {
InterfaceDeclaration::File(ref mut file_decl) => {
let file_type = self.resolve_subtype_indication(
scope,
&mut file_decl.subtype_indication,
diagnostics,
)?;
self.arena.define(
&mut file_decl.ident,
AnyEntKind::InterfaceFile(file_type.type_mark().to_owned()),
)
}
InterfaceDeclaration::Object(ref mut object_decl) => {
let subtype = self.resolve_subtype_indication(
scope,
&mut object_decl.subtype_indication,
diagnostics,
);
if let Some(ref mut expression) = object_decl.expression {
if let Ok(ref subtype) = subtype {
self.expr_pos_with_ttyp(
scope,
subtype.type_mark(),
&expression.pos,
&mut expression.item,
diagnostics,
)?;
} else {
self.expr_unknown_ttyp(scope, expression, diagnostics)?
}
}
let subtype = subtype?;
self.arena.define(
&mut object_decl.ident,
AnyEntKind::Object(Object {
class: object_decl.class,
mode: Some(object_decl.mode),
subtype,
has_default: object_decl.expression.is_some(),
}),
)
}
InterfaceDeclaration::Type(ref mut ident) => {
let typ =
TypeEnt::from_any(self.arena.define(ident, AnyEntKind::Type(Type::Interface)))
.unwrap();
let implicit = [
self.comparison(Operator::EQ, typ),
self.comparison(Operator::NE, typ),
];
for ent in implicit {
unsafe {
self.arena.add_implicit(typ.id(), ent);
}
scope.add(ent, diagnostics);
}
typ.into()
}
InterfaceDeclaration::Subprogram(ref mut subpgm, ..) => {
let subpgm_region = scope.nested();
let signature =
self.analyze_subprogram_declaration(&subpgm_region, subpgm, diagnostics);
drop(subpgm_region);
subpgm.define(
self.arena,
AnyEntKind::Overloaded(Overloaded::InterfaceSubprogram(signature?)),
None,
)
}
InterfaceDeclaration::Package(ref mut instance) => {
let package_region =
self.analyze_package_instance_name(scope, &mut instance.package_name)?;
self.arena.define(
&mut instance.ident,
AnyEntKind::Design(Design::PackageInstance(package_region.clone())),
)
}
};
Ok(ent)
}
pub fn analyze_interface_list(
&self,
scope: &Scope<'a>,
declarations: &mut [InterfaceDeclaration],
diagnostics: &mut dyn DiagnosticHandler,
) -> FatalResult {
for decl in declarations.iter_mut() {
match self.analyze_interface_declaration(scope, decl, diagnostics) {
Ok(ent) => {
scope.add(ent, diagnostics);
}
Err(err) => {
err.add_to(diagnostics)?;
}
}
}
Ok(())
}
pub fn analyze_parameter_list(
&self,
scope: &Scope<'a>,
declarations: &mut [InterfaceDeclaration],
diagnostics: &mut dyn DiagnosticHandler,
) -> FatalResult<FormalRegion<'a>> {
let mut params = FormalRegion::new(InterfaceListType::Parameter);
for decl in declarations.iter_mut() {
match self.analyze_interface_declaration(scope, decl, diagnostics) {
Ok(ent) => {
scope.add(ent, diagnostics);
params.add(ent);
}
Err(err) => {
err.add_to(diagnostics)?;
}
}
}
Ok(params)
}
fn analyze_array_index(
&self,
scope: &Scope<'a>,
array_index: &mut ArrayIndex,
diagnostics: &mut dyn DiagnosticHandler,
) -> EvalResult<BaseType<'a>> {
match array_index {
ArrayIndex::IndexSubtypeDefintion(ref mut type_mark) => {
match self.resolve_type_mark(scope, type_mark) {
Ok(typ) => Ok(typ.base()),
Err(err) => {
err.add_to(diagnostics)?;
Err(EvalError::Unknown)
}
}
}
ArrayIndex::Discrete(ref mut drange) => self.drange_type(scope, drange, diagnostics),
}
}
fn analyze_subtype_constraint(
&self,
scope: &Scope<'a>,
pos: &SrcPos, // The position of the root type mark
base_type: BaseType<'a>,
constraint: &mut SubtypeConstraint,
diagnostics: &mut dyn DiagnosticHandler,
) -> FatalResult {
match constraint {
SubtypeConstraint::Array(ref mut dranges, ref mut constraint) => {
if let Type::Array { indexes, elem_type } = base_type.kind() {
for (idx, drange) in dranges.iter_mut().enumerate() {
if let Some(index_typ) = indexes.get(idx) {
if let Some(index_typ) = index_typ {
self.drange_with_ttyp(
scope,
(*index_typ).into(),
drange,
diagnostics,
)?;
} else {
self.drange_unknown_type(scope, drange, diagnostics)?;
}
} else {
diagnostics.error(
drange.pos(),
format!("Got extra index constraint for {}", base_type.describe()),
);
}
}
// empty dranges means (open)
if dranges.len() < indexes.len() && !dranges.is_empty() {
diagnostics.error(
pos,
format!(
"Too few index constraints for {}. Got {} but expected {}",
base_type.describe(),
dranges.len(),
indexes.len()
),
);
}
if let Some(constraint) = constraint {
self.analyze_subtype_constraint(
scope,
&constraint.pos,
elem_type.base(),
&mut constraint.item,
diagnostics,
)?;
}
} else {
diagnostics.error(
pos,
format!(
"Array constraint cannot be used for {}",
base_type.describe()
),
);
}
}
SubtypeConstraint::Range(ref mut range) => {
if base_type.is_scalar() {
self.range_with_ttyp(scope, base_type.into(), range, diagnostics)?;
} else {
diagnostics.error(
pos,
format!(
"Scalar constraint cannot be used for {}",
base_type.describe()
),
);
}
}
SubtypeConstraint::Record(ref mut constraints) => {
if let Type::Record(region) = base_type.kind() {
for constraint in constraints.iter_mut() {
let ElementConstraint { ident, constraint } = constraint;
let des = Designator::Identifier(ident.item.clone());
if let Some(elem) = region.lookup(&des) {
self.analyze_subtype_constraint(
scope,
&constraint.pos,
elem.type_mark().base(),
&mut constraint.item,
diagnostics,
)?;
} else {
diagnostics.push(Diagnostic::no_declaration_within(
&base_type, &ident.pos, &des,
))
}
}
} else {
diagnostics.error(
pos,
format!(
"Record constraint cannot be used for {}",
base_type.describe()
),
);
}
}
}
Ok(())
}
pub fn resolve_subtype_indication(
&self,
scope: &Scope<'a>,
subtype_indication: &mut SubtypeIndication,
diagnostics: &mut dyn DiagnosticHandler,
) -> AnalysisResult<Subtype<'a>> {
// @TODO more
let SubtypeIndication {
type_mark,
constraint,
..
} = subtype_indication;
let base_type = self.resolve_type_mark(scope, type_mark)?;
if let Some(constraint) = constraint {
self.analyze_subtype_constraint(
scope,
&type_mark.pos,
base_type.base(),
&mut constraint.item,
diagnostics,
)?;
}
Ok(Subtype::new(base_type))
}
pub fn analyze_subtype_indication(
&self,
scope: &Scope<'a>,
subtype_indication: &mut SubtypeIndication,
diagnostics: &mut dyn DiagnosticHandler,
) -> FatalResult {
if let Err(err) = self.resolve_subtype_indication(scope, subtype_indication, diagnostics) {
err.add_to(diagnostics)?;
}
Ok(())
}
fn analyze_subprogram_declaration(
&self,
scope: &Scope<'a>,
subprogram: &mut SubprogramDeclaration,
diagnostics: &mut dyn DiagnosticHandler,
) -> AnalysisResult<Signature<'a>> {
match subprogram {
SubprogramDeclaration::Function(fun) => {
let params =
self.analyze_parameter_list(scope, &mut fun.parameter_list, diagnostics);
let return_type = self.resolve_type_mark(scope, &mut fun.return_type);
Ok(Signature::new(params?, Some(return_type?)))
}
SubprogramDeclaration::Procedure(procedure) => {
let params =
self.analyze_parameter_list(scope, &mut procedure.parameter_list, diagnostics);
Ok(Signature::new(params?, None))
}
}
}
}
fn find_full_type_definition<'a>(
name: &Symbol,
decls: &'a [Declaration],
) -> Option<&'a TypeDeclaration> {
for decl in decls.iter() {
if let Declaration::Type(type_decl) = decl {
match type_decl.def {
TypeDefinition::Incomplete(..) => {
// ignored
}
_ => {
if type_decl.ident.name() == name {
return Some(type_decl);
}
}
}
}
}
None
}
impl Diagnostic {
fn no_overloaded_with_signature(
pos: &SrcPos,
des: &Designator,
overloaded: &OverloadedName,
) -> Diagnostic {
let mut diagnostic = Diagnostic::error(
pos,
format!(
"Could not find declaration of {} with given signature",
des.describe()
),
);
diagnostic.add_subprogram_candidates("Found", overloaded.entities());
diagnostic
}
fn should_not_have_signature(prefix: &str, pos: impl AsRef<SrcPos>) -> Diagnostic {
Diagnostic::error(
pos,
format!("{prefix} should only have a signature for subprograms and enum literals"),
)
}
fn signature_required(pos: impl AsRef<SrcPos>) -> Diagnostic {
Diagnostic::error(
pos,
"Signature required for alias of subprogram and enum literals",
)
}
}