polonius 0.3.0

Core definition for the Rust borrow checker
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
use crate::facts::*;
use crate::intern::InternerTables;
use crate::intern::*;
use polonius_engine::{Atom as PoloniusEngineAtom, Output};
use rustc_hash::FxHashMap;
use std::collections::HashMap;
use std::collections::{BTreeMap, BTreeSet};
use std::fs::File;
use std::hash::Hash;
use std::io::{self, Write};
use std::path::PathBuf;

pub(crate) fn dump_output(
    output: &Output<Region, Loan, Point>,
    output_dir: &Option<PathBuf>,
    intern: &InternerTables,
) -> io::Result<()> {
    dump_rows(
        &mut writer_for(output_dir, "errors")?,
        intern,
        &output.errors,
    )?;

    if output.dump_enabled {
        dump_rows(
            &mut writer_for(output_dir, "restricts")?,
            intern,
            &output.restricts,
        )?;
        dump_rows(
            &mut writer_for(output_dir, "restricts_anywhere")?,
            intern,
            &output.restricts_anywhere,
        )?;
        dump_rows(
            &mut writer_for(output_dir, "region_live_at")?,
            intern,
            &output.region_live_at,
        )?;
        dump_rows(
            &mut writer_for(output_dir, "invalidates")?,
            intern,
            &output.invalidates,
        )?;
        dump_rows(
            &mut writer_for(output_dir, "borrow_live_at")?,
            intern,
            &output.borrow_live_at,
        )?;
        dump_rows(
            &mut writer_for(output_dir, "subset_anywhere")?,
            intern,
            &output.subset_anywhere,
        )?;
    }
    return Ok(());

    fn writer_for(out_dir: &Option<PathBuf>, name: &str) -> io::Result<Box<Write>> {
        // create a writer for the provided output.
        // If we have an output directory use that, otherwise just dump to stdout
        use std::fs;

        Ok(match out_dir {
            Some(dir) => {
                fs::create_dir_all(&dir)?;
                let mut of = dir.join(name);
                of.set_extension("facts");
                Box::new(fs::File::create(of)?)
            }
            None => {
                let mut stdout = io::stdout();
                write!(&mut stdout, "# {}\n\n", name)?;
                Box::new(stdout)
            }
        })
    }
}

trait OutputDump {
    fn push_all<'a>(
        &'a self,
        intern: &'a InternerTables,
        prefix: &mut Vec<&'a str>,
        output: &mut Vec<Vec<&'a str>>,
    );
}

fn dump_rows(
    stream: &mut Write,
    intern: &InternerTables,
    value: &impl OutputDump,
) -> io::Result<()> {
    let mut rows = Vec::new();
    OutputDump::push_all(value, intern, &mut vec![], &mut rows);
    let col_width: usize = rows
        .iter()
        .map(|cols| cols.iter().map(|s| s.len()).max().unwrap_or(0))
        .max()
        .unwrap_or(0);
    for row in &rows {
        let mut string = String::new();

        let (last, not_last) = row.split_last().unwrap();
        for col in not_last {
            string.push_str(col);

            let padding = col_width - col.len();
            for _ in 0..=padding {
                string.push(' ');
            }
        }
        string.push_str(last);

        writeln!(stream, "{}", string)?;
    }

    Ok(())
}

impl<K, V> OutputDump for FxHashMap<K, V>
where
    K: Atom + Eq + Hash + Ord,
    V: OutputDump,
{
    fn push_all<'a>(
        &'a self,
        intern: &'a InternerTables,
        prefix: &mut Vec<&'a str>,
        output: &mut Vec<Vec<&'a str>>,
    ) {
        let table = K::table(intern);
        let mut keys: Vec<_> = self.keys().collect();
        keys.sort();
        for key in keys {
            preserve(prefix, |prefix| {
                prefix.push(table.untern(*key));

                let value = &self[key];
                value.push_all(intern, prefix, output);
            });
        }
    }
}

impl<K, V> OutputDump for BTreeMap<K, V>
where
    K: Atom + Eq + Hash + Ord,
    V: OutputDump,
{
    fn push_all<'a>(
        &'a self,
        intern: &'a InternerTables,
        prefix: &mut Vec<&'a str>,
        output: &mut Vec<Vec<&'a str>>,
    ) {
        let table = K::table(intern);
        let mut keys: Vec<_> = self.keys().collect();
        keys.sort();
        for key in keys {
            preserve(prefix, |prefix| {
                prefix.push(table.untern(*key));

                let value = &self[key];
                value.push_all(intern, prefix, output);
            });
        }
    }
}

impl<K> OutputDump for BTreeSet<K>
where
    K: OutputDump,
{
    fn push_all<'a>(
        &'a self,
        intern: &'a InternerTables,
        prefix: &mut Vec<&'a str>,
        output: &mut Vec<Vec<&'a str>>,
    ) {
        for key in self {
            key.push_all(intern, prefix, output);
        }
    }
}

impl<V> OutputDump for Vec<V>
where
    V: OutputDump,
{
    fn push_all<'a>(
        &'a self,
        intern: &'a InternerTables,
        prefix: &mut Vec<&'a str>,
        output: &mut Vec<Vec<&'a str>>,
    ) {
        for value in self {
            value.push_all(intern, prefix, output);
        }
    }
}

impl<T: Atom> OutputDump for T {
    fn push_all<'a>(
        &'a self,
        intern: &'a InternerTables,
        prefix: &mut Vec<&'a str>,
        output: &mut Vec<Vec<&'a str>>,
    ) {
        let table = T::table(intern);
        let text = table.untern(*self);
        preserve(prefix, |prefix| {
            prefix.push(text);
            output.push(prefix.clone());
        });
    }
}

impl<T1: Atom> OutputDump for (T1,) {
    fn push_all<'a>(
        &'a self,
        intern: &'a InternerTables,
        prefix: &mut Vec<&'a str>,
        output: &mut Vec<Vec<&'a str>>,
    ) {
        let (ref a1,) = self;
        let t1_table = T1::table(intern);
        let a1_text = t1_table.untern(*a1);
        preserve(prefix, |prefix| {
            prefix.push(a1_text);
            output.push(prefix.clone());
        });
    }
}

impl<T1: Atom, T2: Atom> OutputDump for (T1, T2) {
    fn push_all<'a>(
        &'a self,
        intern: &'a InternerTables,
        prefix: &mut Vec<&'a str>,
        output: &mut Vec<Vec<&'a str>>,
    ) {
        let (ref a1, ref a2) = self;
        let t1_table = T1::table(intern);
        let t2_table = T2::table(intern);
        let a1_text = t1_table.untern(*a1);
        let a2_text = t2_table.untern(*a2);
        preserve(prefix, |prefix| {
            prefix.push(a1_text);
            prefix.push(a2_text);
            output.push(prefix.clone());
        });
    }
}

fn preserve<'a>(s: &mut Vec<&'a str>, op: impl FnOnce(&mut Vec<&'a str>)) {
    let len = s.len();
    op(s);
    s.truncate(len);
}

pub(crate) trait Atom: Copy + From<usize> + Into<usize> {
    fn table(intern: &InternerTables) -> &Interner<Self>;
}

impl Atom for Region {
    fn table(intern: &InternerTables) -> &Interner<Self> {
        &intern.regions
    }
}

impl Atom for Point {
    fn table(intern: &InternerTables) -> &Interner<Self> {
        &intern.points
    }
}

impl Atom for Loan {
    fn table(intern: &InternerTables) -> &Interner<Self> {
        &intern.loans
    }
}

fn facts_by_point<F: Clone, Out: OutputDump>(
    facts: impl Iterator<Item = F>,
    point: impl Fn(F) -> (Point, Out),
    name: String,
    point_pos: usize,
    intern: &InternerTables,
) -> HashMap<Point, String> {
    let mut by_point: HashMap<Point, Vec<Out>> = HashMap::new();
    for f in facts {
        let (p, o) = point(f);
        by_point.entry(p).or_insert_with(Vec::new).push(o);
    }
    by_point
        .into_iter()
        .map(|(p, o)| {
            let mut rows: Vec<Vec<&str>> = Vec::new();
            OutputDump::push_all(&o, intern, &mut vec![], &mut rows);
            let s = rows
                .into_iter()
                .map(|mut vals| {
                    vals.insert(point_pos, "_");
                    escape_for_graphviz(
                        format!(
                            "{}({})",
                            name,
                            vals.into_iter()
                                .map(|x| x.to_string())
                                .collect::<Vec<_>>()
                                .join(", ")
                        )
                        .as_str(),
                    )
                })
                .collect::<Vec<_>>()
                .join("\\l")
                + "\\l";
            // in graphviz, \l is a \n that left-aligns
            (p, s)
        })
        .collect()
}

fn build_inputs_by_point_for_visualization(
    all_facts: &AllFacts,
    intern: &InternerTables,
) -> Vec<HashMap<Point, String>> {
    vec![
        facts_by_point(
            all_facts.borrow_region.iter().cloned(),
            |(a, b, p)| (p, (a, b)),
            "borrow_region".to_string(),
            2,
            intern,
        ),
        facts_by_point(
            all_facts.killed.iter().cloned(),
            |(l, p)| (p, (l,)),
            "killed".to_string(),
            1,
            intern,
        ),
        facts_by_point(
            all_facts.outlives.iter().cloned(),
            |(r1, r2, p)| (p, (r1, r2)),
            "outlives".to_string(),
            2,
            intern,
        ),
        facts_by_point(
            all_facts.region_live_at.iter().cloned(),
            |(r, p)| (p, (r,)),
            "region_live_at".to_string(),
            1,
            intern,
        ),
        facts_by_point(
            all_facts.invalidates.iter().cloned(),
            |(p, l)| (p, (l,)),
            "invalidates".to_string(),
            0,
            intern,
        ),
    ]
}

fn build_outputs_by_point_for_visualization(
    output: &Output<Region, Loan, Point>,
    intern: &InternerTables,
) -> Vec<HashMap<Point, String>> {
    vec![
        facts_by_point(
            output.borrow_live_at.iter(),
            |(pt, loans)| (*pt, loans.clone()),
            "borrow_live_at".to_string(),
            0,
            intern,
        ),
        facts_by_point(
            output.restricts.iter(),
            |(pt, region_to_loans)| (*pt, region_to_loans.clone()),
            "restricts".to_string(),
            0,
            intern,
        ),
        facts_by_point(
            output.invalidates.iter(),
            |(pt, loans)| (*pt, loans.clone()),
            "invalidates".to_string(),
            0,
            intern,
        ),
        facts_by_point(
            output.subset.iter(),
            |(pt, region_to_regions)| (*pt, region_to_regions.clone()),
            "subset".to_string(),
            0,
            intern,
        ),
    ]
}

pub(crate) fn graphviz(
    output: &Output<Region, Loan, Point>,
    all_facts: &AllFacts,
    output_file: &PathBuf,
    intern: &InternerTables,
) -> io::Result<()> {
    let mut file = File::create(output_file)?;
    let mut output_fragments: Vec<String> = Vec::new();
    let mut seen_nodes = BTreeSet::new();

    let inputs_by_point = build_inputs_by_point_for_visualization(all_facts, intern);
    let outputs_by_point = build_outputs_by_point_for_visualization(output, intern);

    output_fragments.push("digraph g {\n  graph [\n  rankdir = \"TD\"\n];\n".to_string());
    for (idx, &(p1, p2)) in all_facts.cfg_edge.iter().enumerate() {
        let graphviz_code = graphviz_for_edge(
            p1,
            p2,
            idx,
            &mut seen_nodes,
            &inputs_by_point,
            &outputs_by_point,
            intern,
        )
        .into_iter();
        output_fragments.extend(graphviz_code);
    }
    output_fragments.push("}".to_string()); // close digraph
    let output_bytes = output_fragments.join("").bytes().collect::<Vec<_>>();
    file.write_all(&output_bytes)?;
    Ok(())
}

fn graphviz_for_edge(
    p1: Point,
    p2: Point,
    edge_index: usize,
    seen_points: &mut BTreeSet<usize>,
    inputs_by_point: &[HashMap<Point, String>],
    outputs_by_point: &[HashMap<Point, String>],
    intern: &InternerTables,
) -> Vec<String> {
    let mut ret = Vec::new();
    maybe_render_point(
        p1,
        seen_points,
        inputs_by_point,
        outputs_by_point,
        &mut ret,
        intern,
    );
    maybe_render_point(
        p2,
        seen_points,
        inputs_by_point,
        outputs_by_point,
        &mut ret,
        intern,
    );
    ret.push(format!(
        "\"node{0}\" -> \"node{1}\":f0 [\n  id = {2}\n];\n",
        p1.index(),
        p2.index(),
        edge_index
    ));
    ret
}

fn maybe_render_point(
    pt: Point,
    seen_points: &mut BTreeSet<usize>,
    inputs_by_point: &[HashMap<Point, String>],
    outputs_by_point: &[HashMap<Point, String>],
    render_vec: &mut Vec<String>,
    intern: &InternerTables,
) {
    if seen_points.contains(&pt.index()) {
        return;
    }
    seen_points.insert(pt.index());

    let input_tuples = inputs_by_point
        .iter()
        .filter_map(|inp| inp.get(&pt).map(|s| s.to_string()))
        .collect::<Vec<_>>()
        .join(" | ");

    let output_tuples = outputs_by_point
        .iter()
        .filter_map(|outp| outp.get(&pt).map(|s| s.to_string()))
        .collect::<Vec<_>>()
        .join(" | ");

    render_vec.push(format!("\"node{0}\" [\n  label = \"{{ <f0> {1} | INPUTS | {2} | OUTPUTS | {3} }}\"\n  shape = \"record\"\n];\n",
                     pt.index(),
                     escape_for_graphviz(Point::table(intern).untern(pt)),
                     &input_tuples,
                     &output_tuples));
}

fn write_string(f: &mut File, s: &str) -> io::Result<()> {
    f.write_all(&s.bytes().collect::<Vec<_>>())?;
    Ok(())
}

fn escape_for_graphviz(s: &str) -> String {
    s.replace(r"\", r"\\")
        .replace("\"", "\\\"")
        .replace(r"(", r"\(")
        .replace(r")", r"\)")
        .replace("\n", r"\n")
        .to_string()
}