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
use crate::{
impl_table_key,
ir::{ExtUnit, Signature, Unit, UnitBuilder, UnitData, UnitName},
table::{PrimaryTable, TableKey},
verifier::Verifier,
};
use rayon::prelude::*;
use std::collections::{BTreeSet, HashMap};
#[derive(Serialize, Deserialize)]
pub struct Module {
pub(crate) units: PrimaryTable<UnitId, UnitData>,
unit_order: BTreeSet<UnitId>,
pub(crate) decls: PrimaryTable<DeclId, DeclData>,
decl_order: BTreeSet<DeclId>,
link_table: Option<HashMap<(UnitId, ExtUnit), LinkedUnit>>,
location_hints: HashMap<UnitId, usize>,
}
impl Module {
pub fn new() -> Self {
Self {
units: PrimaryTable::new(),
unit_order: BTreeSet::new(),
decls: PrimaryTable::new(),
decl_order: BTreeSet::new(),
link_table: None,
location_hints: Default::default(),
}
}
pub fn dump(&self) -> ModuleDumper {
ModuleDumper(self)
}
pub fn add_unit(&mut self, data: UnitData) -> UnitId {
let unit = self.units.add(data);
self.unit_order.insert(unit);
self.link_table = None;
unit
}
pub fn remove_unit(&mut self, unit: UnitId) {
self.units.remove(unit);
self.unit_order.remove(&unit);
}
pub fn declare(&mut self, name: UnitName, sig: Signature) -> DeclId {
self.add_decl(DeclData {
name,
sig,
loc: None,
})
}
pub fn add_decl(&mut self, data: DeclData) -> DeclId {
let decl = self.decls.add(data);
self.decl_order.insert(decl);
self.link_table = None;
decl
}
pub fn remove_decl(&mut self, decl: DeclId) {
self.decls.remove(decl);
self.decl_order.remove(&decl);
}
pub fn units<'a>(&'a self) -> impl Iterator<Item = Unit<'a>> + 'a {
self.unit_order.iter().map(move |&id| self.unit(id))
}
pub fn units_mut<'a>(&'a mut self) -> impl Iterator<Item = UnitBuilder<'a>> + 'a {
self.units
.storage
.iter_mut()
.map(|(&id, data)| UnitBuilder::new(UnitId::new(id), data))
}
pub fn par_units<'a>(&'a self) -> impl ParallelIterator<Item = Unit<'a>> + 'a {
self.unit_order.par_iter().map(move |&id| self.unit(id))
}
pub fn par_units_mut<'a>(&'a mut self) -> impl ParallelIterator<Item = UnitBuilder<'a>> + 'a {
self.units
.storage
.par_iter_mut()
.map(|(&id, data)| UnitBuilder::new(UnitId::new(id), data))
}
pub fn functions<'a>(&'a self) -> impl Iterator<Item = Unit<'a>> + 'a {
self.units().filter(|unit| unit.is_function())
}
pub fn processes<'a>(&'a self) -> impl Iterator<Item = Unit<'a>> + 'a {
self.units().filter(|unit| unit.is_process())
}
pub fn entities<'a>(&'a self) -> impl Iterator<Item = Unit<'a>> + 'a {
self.units().filter(|unit| unit.is_entity())
}
pub fn decls<'a>(&'a self) -> impl Iterator<Item = DeclId> + 'a {
self.decl_order.iter().cloned()
}
pub fn unit(&self, unit: UnitId) -> Unit {
Unit::new(unit, &self[unit])
}
pub fn unit_mut(&mut self, unit: UnitId) -> UnitBuilder {
self.link_table = None;
UnitBuilder::new(unit, &mut self[unit])
}
pub fn symbols<'a>(&'a self) -> impl Iterator<Item = (&UnitName, LinkedUnit, &Signature)> + 'a {
self.units()
.map(|unit| (unit.name(), LinkedUnit::Def(unit.id()), unit.sig()))
.chain(
self.decls()
.map(move |decl| (&self[decl].name, LinkedUnit::Decl(decl), &self[decl].sig)),
)
}
pub fn local_symbols<'a>(
&'a self,
) -> impl Iterator<Item = (&UnitName, LinkedUnit, &Signature)> + 'a {
self.symbols().filter(|&(name, ..)| name.is_local())
}
pub fn global_symbols<'a>(
&'a self,
) -> impl Iterator<Item = (&UnitName, LinkedUnit, &Signature)> + 'a {
self.symbols().filter(|&(name, ..)| name.is_global())
}
pub fn is_linked(&self) -> bool {
self.link_table.is_some()
}
pub fn link(&mut self) {
let mut failed = false;
let mut symbols = HashMap::new();
for (name, unit, sig) in self.symbols() {
if let Some((existing, _)) = symbols.insert(name, (unit, sig)) {
if !existing.is_decl() {
eprintln!("unit {} declared multiple times", name);
failed = true;
}
}
}
if failed {
panic!("linking failed; multiple uses of the same name");
}
let mut linked = HashMap::new();
for unit in self.units() {
for (ext_unit, data) in unit.extern_units() {
let (to, to_sig) = match symbols.get(&data.name).cloned() {
Some(to) => to,
None => {
eprintln!(
"unit {} not found; referenced in {}",
data.name,
unit.name()
);
failed = true;
continue;
}
};
if to_sig != &data.sig {
eprintln!(
"signature mismatch: {} has {}, but reference in {} expects {}",
data.name,
to_sig,
unit.name(),
data.sig
);
failed = true;
continue;
}
linked.insert((unit.id(), ext_unit), to);
}
}
if failed {
panic!("linking failed; unresolved references");
}
self.link_table = Some(linked);
}
pub fn verify(&self) {
let mut verifier = Verifier::new();
verifier.verify_module(self);
match verifier.finish() {
Ok(()) => (),
Err(errs) => {
eprintln!("");
eprintln!("Verified module:");
eprintln!("{}", self.dump());
eprintln!("");
eprintln!("Verification errors:");
eprintln!("{}", errs);
panic!("verification failed");
}
}
}
pub fn lookup_ext_unit(&self, ext_unit: ExtUnit, within: UnitId) -> Option<LinkedUnit> {
self.link_table
.as_ref()
.and_then(|lt| lt.get(&(within, ext_unit)))
.cloned()
}
pub fn set_location_hint(&mut self, mod_unit: UnitId, loc: usize) {
self.location_hints.insert(mod_unit, loc);
}
pub fn location_hint(&self, mod_unit: UnitId) -> Option<usize> {
self.location_hints.get(&mod_unit).cloned()
}
}
impl std::ops::Index<UnitId> for Module {
type Output = UnitData;
fn index(&self, idx: UnitId) -> &UnitData {
&self.units[idx]
}
}
impl std::ops::IndexMut<UnitId> for Module {
fn index_mut(&mut self, idx: UnitId) -> &mut UnitData {
self.link_table = None;
&mut self.units[idx]
}
}
impl std::ops::Index<DeclId> for Module {
type Output = DeclData;
fn index(&self, idx: DeclId) -> &DeclData {
&self.decls[idx]
}
}
impl std::ops::IndexMut<DeclId> for Module {
fn index_mut(&mut self, idx: DeclId) -> &mut DeclData {
self.link_table = None;
&mut self.decls[idx]
}
}
pub struct ModuleDumper<'a>(&'a Module);
impl std::fmt::Display for ModuleDumper<'_> {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
let mut newline = false;
for unit in self.0.units() {
if newline {
writeln!(f, "")?;
writeln!(f, "")?;
}
newline = true;
write!(f, "{}: ", unit.id())?;
write!(f, "{}", unit)?;
}
if newline && !self.0.decls().count() > 0 {
writeln!(f, "")?;
}
for decl in self.0.decls() {
if newline {
writeln!(f, "")?;
}
newline = true;
let data = &self.0[decl];
write!(f, "declare {} {}", data.name, data.sig)?;
}
Ok(())
}
}
impl_table_key! {
struct UnitId(u32) as "u";
struct DeclId(u32) as "decl";
}
#[derive(Serialize, Deserialize)]
pub struct DeclData {
pub sig: Signature,
pub name: UnitName,
pub loc: Option<usize>,
}
#[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
pub enum LinkedUnit {
Def(UnitId),
Decl(DeclId),
}
impl LinkedUnit {
pub fn is_def(&self) -> bool {
match self {
LinkedUnit::Def(..) => true,
_ => false,
}
}
pub fn is_decl(&self) -> bool {
match self {
LinkedUnit::Decl(..) => true,
_ => false,
}
}
}