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
//! Utilities for emitting GraphViz dot files.

use crate::ir::*;
use crate::*;
use std::fs;
use std::path::Path;

impl Module {
    /// Generate a [GraphViz Dot](https://graphviz.org/) file for this module,
    /// showing the relationship between various structures in the module and
    /// its instructions.
    ///
    /// # Example
    ///
    /// First, generate a `.dot` file with this method:
    ///
    /// ```
    /// # fn foo() -> walrus::Result<()> {
    /// # let get_module_from_somewhere = || unimplemented!();
    /// let my_module: walrus::Module = get_module_from_somewhere();
    /// my_module.write_graphviz_dot("my_module.dot")?;
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// Second, use the `dot` command-line tool to render an SVG (or PNG,
    /// etc...):
    ///
    /// ```bash
    /// dot my_module.dot \       # Provide our generated `.dot`.
    ///     -T svg \              # Generate an SVG image.
    ///     -o my_module.svg      # Write to this output file.
    /// ```
    pub fn write_graphviz_dot(&self, path: impl AsRef<Path>) -> Result<()> {
        let mut dot_string = String::new();
        self.dot(&mut dot_string);
        fs::write(path, dot_string)?;
        Ok(())
    }
}

trait Dot {
    /// Append a top-level graphviz dot form to the `out` string.
    fn dot(&self, out: &mut String);
}

trait DotName {
    /// Get this thing's unique name in the graphviz dot file.
    fn dot_name(&self) -> String;
}

trait FieldAggregator {
    /// Add a field for the current node.
    fn add_field(&mut self, field: &[&str]);

    /// Add a field with a named port for the current node.
    fn add_field_with_port(&mut self, port: &str, field: &str);
}

trait EdgeAggregator {
    /// Add an outgoing edge from the current node.
    fn add_edge(&mut self, to: &impl DotName);

    /// Add an outgoing edge form the current node at a specific port.
    fn add_edge_from_port(&mut self, port: &str, to: &impl DotName);
}

/// A trait for generating a top-level node with multiple fields and some number
/// of edges to other nodes.
///
/// Anything that implements this trait automatically gets nice HTML tables for
/// the fields and doesn't have to worry about the details of serializing to the
/// Dot language, just have to add fields/edges on the respective aggregator.
trait DotNode: DotName {
    /// For each field that should show up in this node's record, call
    /// `fields.add_field([...])`.
    fn fields(&self, fields: &mut impl FieldAggregator);

    /// For each outgoing edge from this node to another node, call
    /// `edges.add_edge(..)`.
    fn edges(&self, edges: &mut impl EdgeAggregator);
}

impl<T: DotNode> Dot for T {
    fn dot(&self, out: &mut String) {
        let dot_name = self.dot_name();

        out.push_str("    ");
        out.push_str(&dot_name);
        out.push_str(" [shape=\"none\", label=<<table align=\"left\" cellborder=\"0\">");
        self.fields(&mut AppendFields { out });
        out.push_str("</table>>];\n");

        self.edges(&mut AppendEdges {
            out,
            from: &dot_name,
        });
        return;

        struct AppendFields<'a> {
            out: &'a mut String,
        }

        impl FieldAggregator for AppendFields<'_> {
            fn add_field(&mut self, field: &[&str]) {
                assert!(field.len() > 0);
                self.out.push_str("<tr>");
                for f in field {
                    self.out.push_str("<td>");
                    self.out.push_str(f);
                    self.out.push_str("</td>");
                }
                self.out.push_str("</tr>");
            }

            fn add_field_with_port(&mut self, port: &str, field: &str) {
                assert!(field.len() > 0);
                self.out.push_str("<tr>");
                self.out.push_str("<td port=\"");
                self.out.push_str(port);
                self.out.push_str("\">");
                self.out.push_str(field);
                self.out.push_str("</td>");
                self.out.push_str("</tr>");
            }
        }

        struct AppendEdges<'a> {
            out: &'a mut String,
            from: &'a str,
        }

        impl EdgeAggregator for AppendEdges<'_> {
            fn add_edge(&mut self, to: &impl DotName) {
                self.out.push_str("    ");
                self.out.push_str(self.from);
                self.out.push_str(" -> ");
                self.out.push_str(&to.dot_name());
                self.out.push_str(";\n");
            }

            fn add_edge_from_port(&mut self, port: &str, to: &impl DotName) {
                self.out.push_str("    ");
                self.out.push_str(self.from);
                self.out.push_str(":");
                self.out.push_str(port);
                self.out.push_str(" -> ");
                self.out.push_str(&to.dot_name());
                self.out.push_str(";\n");
            }
        }
    }
}

impl Dot for Module {
    fn dot(&self, out: &mut String) {
        out.push_str("digraph {\n");

        self.imports.dot(out);
        self.tables.dot(out);
        self.types.dot(out);
        self.funcs.dot(out);
        self.globals.dot(out);
        self.locals.dot(out);
        self.exports.dot(out);
        self.memories.dot(out);
        self.data.dot(out);
        self.elements.dot(out);

        // TODO?
        // self.start.dot(out);
        // self.producers.dot(out);
        // self.customs.dot(out);
        // self.name.dot(out);
        // self.config.dot(out);

        out.push_str("}");
    }
}

macro_rules! impl_dot_name_for_id {
    ( $( $id:ident; )* ) => {
        $(
            impl DotName for $id {
                fn dot_name(&self) -> String {
                    // NB: the hash contains the arena id as well as the index,
                    // which is important for differentiating instruction
                    // sequences that have the same arena index but live in
                    // different function's arenas.
                    use std::hash::{Hash, Hasher};
                    let mut hasher = crate::map::IdHasher::default();
                    self.hash(&mut hasher);
                    format!("{}_{:x}", stringify!($id), hasher.finish())
                }
            }
        )*
    }
}

impl_dot_name_for_id! {
    ImportId;
    TableId;
    TypeId;
    FunctionId;
    GlobalId;
    LocalId;
    ExportId;
    MemoryId;
    DataId;
    ElementId;
    InstrSeqId;
}

macro_rules! impl_dot_via_iter {
    ( $( $t:ty; )* ) => {
        $(
            impl Dot for $t {
                fn dot(&self, out: &mut String) {
                    out.push_str(concat!("    // ", stringify!($t), "\n"));
                    for x in self.iter() {
                        x.dot(out);
                    }
                    out.push_str("\n");
                }
            }
        )*
    }
}

impl_dot_via_iter! {
    ModuleImports;
    ModuleTables;
    ModuleTypes;
    ModuleFunctions;
    ModuleGlobals;
    ModuleLocals;
    ModuleExports;
    ModuleMemories;
    ModuleData;
    ModuleElements;
}

macro_rules! impl_dot_name_via_id {
    ( $( $t:ty; )* ) => {
        $(
            impl DotName for $t {
                fn dot_name(&self) -> String {
                    self.id().dot_name()
                }
            }
        )*
    }
}

impl_dot_name_via_id! {
    Import;
    Table;
    Type;
    Function;
    Global;
    Local;
    Export;
    Memory;
    Data;
    Element;
    InstrSeq;
}

impl DotNode for Import {
    fn fields(&self, fields: &mut impl FieldAggregator) {
        fields.add_field(&[&format!("<b>Import {:?}</b>", self.id())]);
        fields.add_field(&["module", &self.module]);
        fields.add_field(&["name", &self.name]);
    }

    fn edges(&self, _edges: &mut impl EdgeAggregator) {}
}

impl DotNode for Table {
    fn fields(&self, fields: &mut impl FieldAggregator) {
        fields.add_field(&[&format!("<b>Table {:?}</b>", self.id())]);
        fields.add_field(&["initial", &self.initial.to_string()]);
        fields.add_field(&["maximum", &format!("{:?}", self.maximum)]);
        fields.add_field(&["kind", &format!("{:?}", self.kind)]);
        if self.import.is_some() {
            fields.add_field_with_port("import", "import");
        }
    }

    fn edges(&self, edges: &mut impl EdgeAggregator) {
        if let Some(imp) = self.import {
            edges.add_edge_from_port("import", &imp);
        }
    }
}

impl DotNode for Type {
    fn fields(&self, fields: &mut impl FieldAggregator) {
        fields.add_field(&[&format!("<b>Type {:?}</b>", self.id())]);
        fields.add_field(&["params", &format!("{:?}", self.params())]);
        fields.add_field(&["results", &format!("{:?}", self.results())]);
    }

    fn edges(&self, _edges: &mut impl EdgeAggregator) {}
}

impl Dot for Function {
    fn dot(&self, out: &mut String) {
        FunctionHeader(self).dot(out);
        if let FunctionKind::Local(ref l) = self.kind {
            l.dot(out);
        }
    }
}

struct FunctionHeader<'a>(&'a Function);

impl std::ops::Deref for FunctionHeader<'_> {
    type Target = Function;
    fn deref(&self) -> &Function {
        self.0
    }
}

impl DotName for FunctionHeader<'_> {
    fn dot_name(&self) -> String {
        self.0.dot_name()
    }
}

impl DotNode for FunctionHeader<'_> {
    fn fields(&self, fields: &mut impl FieldAggregator) {
        fields.add_field(&[&format!("<b>Function {:?}</b>", self.id())]);
        if let Some(name) = self.name.as_ref() {
            fields.add_field(&["name", name]);
        }
        fields.add_field_with_port("type", "type");
        match &self.kind {
            FunctionKind::Import(_) => {
                fields.add_field_with_port("import", "import");
            }
            FunctionKind::Local(_) => {
                fields.add_field_with_port("body", "body");
            }
            FunctionKind::Uninitialized(_) => unreachable!(),
        }
    }

    fn edges(&self, edges: &mut impl EdgeAggregator) {
        edges.add_edge_from_port("type", &self.ty());
        match &self.kind {
            FunctionKind::Import(imp_func) => {
                edges.add_edge_from_port("import", &imp_func.import);
            }
            FunctionKind::Local(local_func) => {
                edges.add_edge_from_port("body", local_func);
            }
            FunctionKind::Uninitialized(_) => unreachable!(),
        }
    }
}

impl DotName for LocalFunction {
    fn dot_name(&self) -> String {
        self.entry_block().dot_name()
    }
}

impl Dot for LocalFunction {
    fn dot(&self, out: &mut String) {
        let visitor = &mut DotVisitor { out };
        dfs_in_order(visitor, self, self.entry_block());

        struct DotVisitor<'a> {
            out: &'a mut String,
        }

        impl<'a, 'instr> Visitor<'instr> for DotVisitor<'a> {
            fn start_instr_seq(&mut self, seq: &'instr InstrSeq) {
                seq.dot(self.out);
            }
        }
    }
}

impl DotNode for InstrSeq {
    fn fields(&self, fields: &mut impl FieldAggregator) {
        for (i, instr) in self.instrs.iter().enumerate() {
            fields.add_field_with_port(&i.to_string(), &format!("{:?}", instr));
        }
    }

    fn edges(&self, edges: &mut impl EdgeAggregator) {
        for (i, instr) in self.instrs.iter().enumerate() {
            let port = i.to_string();
            instr.visit(&mut DotVisitor { port, edges });
        }

        struct DotVisitor<'a, E> {
            port: String,
            edges: &'a mut E,
        }

        impl<'a, 'instr, E> Visitor<'instr> for DotVisitor<'a, E>
        where
            E: EdgeAggregator,
        {
            fn visit_instr_seq_id(&mut self, instr_seq_id: &InstrSeqId) {
                self.edges.add_edge_from_port(&self.port, instr_seq_id);
            }

            fn visit_local_id(&mut self, local: &crate::LocalId) {
                self.edges.add_edge_from_port(&self.port, local);
            }

            fn visit_memory_id(&mut self, memory: &crate::MemoryId) {
                self.edges.add_edge_from_port(&self.port, memory);
            }

            fn visit_table_id(&mut self, table: &crate::TableId) {
                self.edges.add_edge_from_port(&self.port, table);
            }

            fn visit_global_id(&mut self, global: &crate::GlobalId) {
                self.edges.add_edge_from_port(&self.port, global);
            }

            fn visit_function_id(&mut self, function: &crate::FunctionId) {
                self.edges.add_edge_from_port(&self.port, function);
            }

            fn visit_data_id(&mut self, data: &crate::DataId) {
                self.edges.add_edge_from_port(&self.port, data);
            }

            fn visit_type_id(&mut self, ty: &crate::TypeId) {
                self.edges.add_edge_from_port(&self.port, ty);
            }
        }
    }
}

impl DotNode for Global {
    fn fields(&self, fields: &mut impl FieldAggregator) {
        fields.add_field(&[&format!("<b>Global {:?}</b>", self.id())]);
        fields.add_field_with_port("type", "type");
        fields.add_field(&["mutable", if self.mutable { "true" } else { "false" }]);
        match self.kind {
            GlobalKind::Import(_imp) => {
                fields.add_field_with_port("import", "import");
            }
            GlobalKind::Local(_init) => {
                // TODO FITZGEN
            }
        }
    }

    fn edges(&self, edges: &mut impl EdgeAggregator) {
        if let GlobalKind::Import(imp) = self.kind {
            edges.add_edge_from_port("import", &imp);
        }
    }
}

impl DotNode for Local {
    fn fields(&self, fields: &mut impl FieldAggregator) {
        fields.add_field(&[&format!("<b>Local {:?}</b>", self.id())]);
        fields.add_field(&["type", &format!("{:?}", self.ty())]);
    }

    fn edges(&self, _edges: &mut impl EdgeAggregator) {}
}

impl DotNode for Export {
    fn fields(&self, fields: &mut impl FieldAggregator) {
        fields.add_field(&[&format!("<b>Export {:?}</b>", self.id())]);
        fields.add_field(&["name", &self.name]);
        fields.add_field_with_port("item", "item");
    }

    fn edges(&self, edges: &mut impl EdgeAggregator) {
        match self.item {
            ExportItem::Function(f) => edges.add_edge_from_port("item", &f),
            ExportItem::Table(t) => edges.add_edge_from_port("item", &t),
            ExportItem::Memory(m) => edges.add_edge_from_port("item", &m),
            ExportItem::Global(g) => edges.add_edge_from_port("item", &g),
        }
    }
}

impl DotNode for Memory {
    fn fields(&self, fields: &mut impl FieldAggregator) {
        fields.add_field(&[&format!("<b>Memory {:?}</b>", self.id())]);
        fields.add_field(&["shared", if self.shared { "true" } else { "false" }]);
        fields.add_field(&["initial", &self.initial.to_string()]);
        fields.add_field(&["maximum", &format!("{:?}", self.maximum)]);
        if self.import.is_some() {
            fields.add_field_with_port("import", "import");
        }
    }

    fn edges(&self, edges: &mut impl EdgeAggregator) {
        if let Some(imp) = self.import {
            edges.add_edge_from_port("import", &imp);
        }
    }
}

impl DotNode for Data {
    fn fields(&self, fields: &mut impl FieldAggregator) {
        fields.add_field(&[&format!("<b>Data {:?}</b>", self.id())]);
        fields.add_field_with_port("kind", &format!("{:?}", self.kind));
        // `self.value` ommitted because it is likely too big and just gibberish
        // anyways.
    }

    fn edges(&self, edges: &mut impl EdgeAggregator) {
        if let DataKind::Active(ref a) = self.kind {
            edges.add_edge_from_port("kind", &a.memory);
        }
    }
}

impl DotNode for Element {
    fn fields(&self, fields: &mut impl FieldAggregator) {
        fields.add_field(&[&format!("<b>Element {:?}</b>", self.id())]);
    }

    fn edges(&self, edges: &mut impl EdgeAggregator) {
        for m in self.members.iter() {
            edges.add_edge(m);
        }
    }
}