ddbug 0.5.0

Display debugging information
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
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
use std::cmp;
use std::collections::BinaryHeap;
use std::io::Write;

use parser::FileHash;

use crate::code::Code;
use crate::{Options, Result};

mod text;
pub use self::text::TextPrinter;

mod html;
pub use self::html::HtmlPrinter;

pub(crate) mod base_type;
pub(crate) mod enumeration;
pub(crate) mod file;
pub(crate) mod frame_location;
pub(crate) mod function;
pub(crate) mod function_call;
pub(crate) mod inherit;
pub(crate) mod inlined_function;
pub(crate) mod local_variable;
pub(crate) mod location;
pub(crate) mod member;
pub(crate) mod namespace;
pub(crate) mod parameter;
pub(crate) mod range;
pub(crate) mod register;
pub(crate) mod section;
pub(crate) mod source;
pub(crate) mod struct_type;
pub(crate) mod symbol;
pub(crate) mod type_def;
pub(crate) mod types;
pub(crate) mod union_type;
pub(crate) mod unit;
pub(crate) mod variable;

#[derive(Debug, Clone, Copy, Eq, PartialEq)]
pub enum DiffPrefix {
    None,
    Equal,
    Delete,
    Add,
    Modify,
}

#[derive(Debug, Clone, Copy, Eq, PartialEq)]
pub enum Id {
    None,
    Unit {
        unit_index: usize,
    },
    Type {
        unit_index: usize,
        type_index: usize,
    },
    Function {
        unit_index: usize,
        function_index: usize,
    },
    Variable {
        unit_index: usize,
        variable_index: usize,
    },
}

pub trait Printer {
    fn value(
        &mut self,
        buf: &mut Vec<u8>,
        f: &mut dyn FnMut(&mut dyn ValuePrinter) -> Result<()>,
    ) -> Result<()>;

    /// Calls `f` to write to a temporary buffer.
    fn buffer(
        &mut self,
        buf: &mut Vec<u8>,
        f: &mut dyn FnMut(&mut dyn Printer) -> Result<()>,
    ) -> Result<()>;
    fn write_buf(&mut self, buf: &[u8]) -> Result<()>;

    fn line_break(&mut self) -> Result<()>;

    fn line(&mut self, label: &str, buf: &[u8]) -> Result<()>;
    fn line_diff(&mut self, label: &str, a: &[u8], b: &[u8]) -> Result<()>;

    fn indent_body(
        &mut self,
        buf: &mut Vec<u8>,
        body: &mut dyn FnMut(&mut dyn Printer) -> Result<()>,
    ) -> Result<()>;
    fn indent_header(
        &mut self,
        collapsed: bool,
        body: &[u8],
        header: &mut dyn FnMut(&mut dyn Printer) -> Result<()>,
    ) -> Result<()>;
    fn indent_id(
        &mut self,
        id: usize,
        header: &mut dyn FnMut(&mut dyn Printer) -> Result<()>,
        body: &mut dyn FnMut(&mut dyn Printer) -> Result<()>,
    ) -> Result<()>;
    fn indent_detail(&mut self, id: &str, label: &str) -> Result<()>;

    fn prefix(&mut self, prefix: DiffPrefix);
    fn get_prefix(&self) -> DiffPrefix;

    fn inline_begin(&mut self) -> bool;
    fn inline_end(&mut self);

    fn instruction(&mut self, address: Option<u64>, mnemonic: &str, buf: &[u8]) -> Result<()>;
}

pub trait ValuePrinter: Write {
    fn link(
        &mut self,
        id: usize,
        f: &mut dyn FnMut(&mut dyn ValuePrinter) -> Result<()>,
    ) -> Result<()>;

    fn name(&mut self, name: &str) -> Result<()>;
}

impl ValuePrinter for Vec<u8> {
    fn link(
        &mut self,
        _id: usize,
        f: &mut dyn FnMut(&mut dyn ValuePrinter) -> Result<()>,
    ) -> Result<()> {
        f(self)
    }

    fn name(&mut self, name: &str) -> Result<()> {
        self.write_all(name.as_bytes())?;
        Ok(())
    }
}

pub(crate) struct PrintState<'a> {
    // 'w lifetime needed due to invariance
    printer: &'a mut dyn Printer,

    // The remaining fields contain information that is commonly needed in print methods.
    hash: &'a FileHash<'a>,
    code: Option<&'a Code<'a>>,
    options: &'a Options,
}

impl<'a> PrintState<'a> {
    #[inline]
    pub fn hash(&self) -> &'a FileHash<'a> {
        self.hash
    }

    #[inline]
    pub fn options(&self) -> &'a Options {
        self.options
    }

    pub fn new(
        printer: &'a mut dyn Printer,
        hash: &'a FileHash<'a>,
        code: Option<&'a Code<'a>>,
        options: &'a Options,
    ) -> Self {
        PrintState {
            printer,
            hash,
            code,
            options,
        }
    }

    pub fn id<FHeader, FBody>(
        &mut self,
        id: usize,
        mut header: FHeader,
        mut body: FBody,
    ) -> Result<()>
    where
        FHeader: FnMut(&mut PrintState) -> Result<()>,
        FBody: FnMut(&mut PrintState) -> Result<()>,
    {
        let hash = self.hash;
        let code = self.code;
        let options = self.options;
        self.printer.indent_id(
            id,
            &mut |printer| {
                let mut state = PrintState::new(printer, hash, code, options);
                header(&mut state)?;
                Ok(())
            },
            &mut |printer| {
                let mut state = PrintState::new(printer, hash, code, options);
                body(&mut state)?;
                Ok(())
            },
        )
    }

    pub fn field_detail<FBody>(&mut self, id: &str, label: &str, body: FBody) -> Result<()>
    where
        FBody: FnMut(&mut PrintState) -> Result<()>,
    {
        if self.options.http {
            self.printer.indent_detail(id, label)
        } else {
            self.indent_impl(true, true, |state| state.label(label), body)
        }
    }

    // Output the header with an indented body.
    // If optional is true, then only output if the body is not empty.
    fn indent_impl<FHeader, FBody>(
        &mut self,
        optional: bool,
        collapsed: bool,
        mut header: FHeader,
        mut body: FBody,
    ) -> Result<()>
    where
        FHeader: FnMut(&mut PrintState) -> Result<()>,
        FBody: FnMut(&mut PrintState) -> Result<()>,
    {
        let hash = self.hash;
        let code = self.code;
        let options = self.options;
        let mut body_buf = Vec::new();
        self.printer.indent_body(&mut body_buf, &mut |printer| {
            let mut state = PrintState::new(printer, hash, code, options);
            body(&mut state)?;
            Ok(())
        })?;
        if !body_buf.is_empty() {
            self.printer
                .indent_header(collapsed, &body_buf, &mut |printer| {
                    let mut state = PrintState::new(printer, hash, code, options);
                    header(&mut state)?;
                    Ok(())
                })?;
        } else if !optional {
            header(self)?;
        }
        Ok(())
    }

    pub fn collapsed<FHeader, FBody>(&mut self, header: FHeader, body: FBody) -> Result<()>
    where
        FHeader: FnMut(&mut PrintState) -> Result<()>,
        FBody: FnMut(&mut PrintState) -> Result<()>,
    {
        self.indent_impl(false, true, header, body)
    }

    pub fn expanded<FHeader, FBody>(&mut self, header: FHeader, body: FBody) -> Result<()>
    where
        FHeader: FnMut(&mut PrintState) -> Result<()>,
        FBody: FnMut(&mut PrintState) -> Result<()>,
    {
        self.indent_impl(false, false, header, body)
    }

    pub fn field_collapsed<FBody>(&mut self, label: &str, body: FBody) -> Result<()>
    where
        FBody: FnMut(&mut PrintState) -> Result<()>,
    {
        self.indent_impl(true, true, |state| state.label(label), body)
    }

    pub fn field_expanded<FBody>(&mut self, label: &str, body: FBody) -> Result<()>
    where
        FBody: FnMut(&mut PrintState) -> Result<()>,
    {
        self.indent_impl(true, false, |state| state.label(label), body)
    }

    pub fn inline<F>(&mut self, mut f: F) -> Result<()>
    where
        F: FnMut(&mut PrintState) -> Result<()>,
    {
        if self.printer.inline_begin() {
            let ret = f(self);
            self.printer.inline_end();
            ret
        } else {
            Ok(())
        }
    }

    fn prefix(
        &mut self,
        prefix: DiffPrefix,
        f: &mut dyn FnMut(&mut PrintState) -> Result<()>,
    ) -> Result<()> {
        self.printer.prefix(prefix);
        f(self)
    }

    pub fn line_break(&mut self) -> Result<()> {
        self.printer.line_break()
    }

    pub fn label(&mut self, label: &str) -> Result<()> {
        self.printer.line(label, &[])
    }

    fn line_impl<F>(&mut self, label: &str, mut f: F) -> Result<()>
    where
        F: FnMut(&mut dyn ValuePrinter, &FileHash) -> Result<()>,
    {
        let mut buf = Vec::new();
        let hash = self.hash;
        self.printer
            .value(&mut buf, &mut |printer| f(printer, hash))?;
        if !buf.is_empty() {
            self.printer.line(label, &buf)?;
        }
        Ok(())
    }

    pub fn line<F>(&mut self, f: F) -> Result<()>
    where
        F: FnMut(&mut dyn ValuePrinter, &FileHash) -> Result<()>,
    {
        self.line_impl("", f)
    }

    pub fn field<F>(&mut self, label: &str, f: F) -> Result<()>
    where
        F: FnMut(&mut dyn ValuePrinter, &FileHash) -> Result<()>,
    {
        self.line_impl(label, f)
    }

    pub fn field_u64(&mut self, label: &str, arg: u64) -> Result<()> {
        self.field(label, |w, _| {
            write!(w, "{}", arg)?;
            Ok(())
        })
    }

    pub fn instruction<F>(&mut self, address: Option<u64>, mnemonic: &str, mut f: F) -> Result<()>
    where
        F: FnMut(&mut dyn ValuePrinter, &FileHash) -> Result<()>,
    {
        let mut buf = Vec::new();
        let hash = self.hash;
        self.printer
            .value(&mut buf, &mut |printer| f(printer, hash))?;
        self.printer.instruction(address, mnemonic, &buf)
    }

    pub fn list<T: Print>(&mut self, arg: &T::Arg, list: &[T]) -> Result<()> {
        for item in list {
            item.print(self, arg)?;
        }
        Ok(())
    }

    pub fn sort_list<T: SortList>(&mut self, arg: &T::Arg, list: &mut [&T]) -> Result<()> {
        list.sort_by(|a, b| T::cmp_by(self.hash, a, self.hash, b, self.options));
        for item in list {
            item.print(self, arg)?;
        }
        Ok(())
    }
}

pub(crate) struct DiffState<'a> {
    printer: &'a mut dyn Printer,

    // True if DiffPrefix::Delete or DiffPrefix::Add was printed.
    diff: bool,

    // The remaining fields contain information that is commonly needed in print methods.
    hash_a: &'a FileHash<'a>,
    hash_b: &'a FileHash<'a>,
    code_a: Option<&'a Code<'a>>,
    code_b: Option<&'a Code<'a>>,
    options: &'a Options,
}

impl<'a> DiffState<'a> {
    #[inline]
    fn a(&'_ mut self) -> PrintState<'_> {
        PrintState::new(self.printer, self.hash_a, self.code_a, self.options)
    }

    #[inline]
    fn b(&'_ mut self) -> PrintState<'_> {
        PrintState::new(self.printer, self.hash_b, self.code_b, self.options)
    }

    #[inline]
    pub fn hash_a(&self) -> &'a FileHash<'a> {
        self.hash_a
    }

    #[inline]
    pub fn hash_b(&self) -> &'a FileHash<'a> {
        self.hash_b
    }

    #[inline]
    pub fn options(&self) -> &'a Options {
        self.options
    }

    pub fn new(
        printer: &'a mut dyn Printer,
        hash_a: &'a FileHash<'a>,
        hash_b: &'a FileHash<'a>,
        code_a: Option<&'a Code<'a>>,
        code_b: Option<&'a Code<'a>>,
        options: &'a Options,
    ) -> Self {
        DiffState {
            printer,
            diff: false,
            hash_a,
            hash_b,
            code_a,
            code_b,
            options,
        }
    }

    // Write output of `f` to a temporary buffer, then only
    // output that buffer if there were any differences.
    fn print_if_diff<F>(&mut self, mut f: F) -> Result<()>
    where
        F: FnMut(&mut DiffState) -> Result<()>,
    {
        let hash_a = self.hash_a;
        let hash_b = self.hash_b;
        let code_a = self.code_a;
        let code_b = self.code_b;
        let options = self.options;
        let mut buf = Vec::new();
        let mut diff = false;
        self.printer.buffer(&mut buf, &mut |printer| {
            let mut state = DiffState::new(printer, hash_a, hash_b, code_a, code_b, options);
            f(&mut state)?;
            diff = state.diff;
            Ok(())
        })?;
        self.diff |= diff;
        if diff || options.html {
            self.printer.write_buf(&buf)?;
        }
        Ok(())
    }

    // Don't allow `f` to update self.diff if flag is true.
    pub fn ignore_diff<F>(&mut self, flag: bool, mut f: F) -> Result<()>
    where
        F: FnMut(&mut DiffState) -> Result<()>,
    {
        let diff = self.diff;
        f(self)?;
        if flag {
            self.diff = diff;
        }
        Ok(())
    }

    pub fn id<FHeader, FBody>(
        &mut self,
        id: usize,
        mut header: FHeader,
        mut body: FBody,
    ) -> Result<()>
    where
        FHeader: FnMut(&mut DiffState) -> Result<()>,
        FBody: FnMut(&mut DiffState) -> Result<()>,
    {
        let hash_a = self.hash_a;
        let hash_b = self.hash_b;
        let code_a = self.code_a;
        let code_b = self.code_b;
        let options = self.options;

        // Render the body first so that we can determine if there are differences.
        // TODO: this makes the initial HTTP load much slower than it could be.
        let mut body_buf = Vec::new();
        let mut diff = false;
        self.printer.indent_body(&mut body_buf, &mut |printer| {
            printer.prefix(DiffPrefix::Equal);
            let mut state = DiffState::new(printer, hash_a, hash_b, code_a, code_b, options);
            body(&mut state)?;
            diff |= state.diff;
            Ok(())
        })?;

        self.printer.indent_id(
            id,
            &mut |printer| {
                if diff {
                    printer.prefix(DiffPrefix::Modify);
                } else {
                    printer.prefix(DiffPrefix::Equal);
                }
                let mut state = DiffState::new(printer, hash_a, hash_b, code_a, code_b, options);
                header(&mut state)?;
                diff |= state.diff;
                Ok(())
            },
            &mut |printer| {
                printer.write_buf(&body_buf)?;
                Ok(())
            },
        )?;
        self.diff |= diff;
        Ok(())
    }

    // Output the header with an indented body.
    // If optional is true, then only output if the body is not empty.
    fn indent_impl<FHeader, FBody>(
        &mut self,
        optional: bool,
        collapsed: bool,
        mut header: FHeader,
        mut body: FBody,
    ) -> Result<()>
    where
        FHeader: FnMut(&mut DiffState) -> Result<()>,
        FBody: FnMut(&mut DiffState) -> Result<()>,
    {
        let hash_a = self.hash_a;
        let hash_b = self.hash_b;
        let code_a = self.code_a;
        let code_b = self.code_b;
        let options = self.options;

        // Render the body first so that we can determine if there are differences
        // or if it is empty.
        let mut body_buf = Vec::new();
        let mut diff = false;
        self.printer.indent_body(&mut body_buf, &mut |printer| {
            printer.prefix(DiffPrefix::Equal);
            let mut state = DiffState::new(printer, hash_a, hash_b, code_a, code_b, options);
            body(&mut state)?;
            if state.diff {
                diff = true;
            }
            Ok(())
        })?;

        if !body_buf.is_empty() {
            self.printer
                .indent_header(collapsed, &body_buf, &mut |printer| {
                    if diff {
                        printer.prefix(DiffPrefix::Modify);
                    } else {
                        printer.prefix(DiffPrefix::Equal);
                    }
                    let mut state =
                        DiffState::new(printer, hash_a, hash_b, code_a, code_b, options);
                    header(&mut state)?;
                    if state.diff {
                        diff = true;
                    }
                    Ok(())
                })?;
            self.diff |= diff;
        } else if !optional {
            header(self)?;
        }
        Ok(())
    }

    pub fn collapsed<FHeader, FBody>(&mut self, header: FHeader, body: FBody) -> Result<()>
    where
        FHeader: FnMut(&mut DiffState) -> Result<()>,
        FBody: FnMut(&mut DiffState) -> Result<()>,
    {
        self.indent_impl(false, true, header, body)
    }

    pub fn expanded<FHeader, FBody>(&mut self, header: FHeader, body: FBody) -> Result<()>
    where
        FHeader: FnMut(&mut DiffState) -> Result<()>,
        FBody: FnMut(&mut DiffState) -> Result<()>,
    {
        self.indent_impl(false, false, header, body)
    }

    pub fn field_collapsed<FBody>(&mut self, label: &str, body: FBody) -> Result<()>
    where
        FBody: FnMut(&mut DiffState) -> Result<()>,
    {
        self.indent_impl(true, true, |state| state.label(label), body)
    }

    pub fn field_expanded<FBody>(&mut self, label: &str, body: FBody) -> Result<()>
    where
        FBody: FnMut(&mut DiffState) -> Result<()>,
    {
        self.indent_impl(true, false, |state| state.label(label), body)
    }

    pub fn inline<F>(&mut self, mut f: F) -> Result<()>
    where
        F: FnMut(&mut DiffState) -> Result<()>,
    {
        if self.printer.inline_begin() {
            let ret = f(self);
            self.printer.inline_end();
            ret
        } else {
            Ok(())
        }
    }

    fn prefix_delete<F>(&mut self, mut f: F) -> Result<()>
    where
        F: FnMut(&mut PrintState) -> Result<()>,
    {
        self.a().prefix(DiffPrefix::Delete, &mut f)?;
        // Assume something is always written.
        self.diff = true;
        Ok(())
    }

    fn prefix_add<F>(&mut self, mut f: F) -> Result<()>
    where
        F: FnMut(&mut PrintState) -> Result<()>,
    {
        self.b().prefix(DiffPrefix::Add, &mut f)?;
        // Assume something is always written.
        self.diff = true;
        Ok(())
    }

    // Multiline blocks that are always different, but may be empty.
    pub fn block<F, T>(&mut self, arg_a: T, arg_b: T, mut f: F) -> Result<()>
    where
        F: FnMut(&mut PrintState, T) -> Result<()>,
        T: Copy,
    {
        let hash_a = self.hash_a;
        let hash_b = self.hash_b;
        let code_a = self.code_a;
        let code_b = self.code_b;
        let options = self.options;
        let mut buf = Vec::new();
        self.printer.buffer(&mut buf, &mut |printer| {
            let mut state = DiffState::new(printer, hash_a, hash_b, code_a, code_b, options);
            state
                .a()
                .prefix(DiffPrefix::Delete, &mut |state| f(state, arg_a))?;
            state
                .b()
                .prefix(DiffPrefix::Add, &mut |state| f(state, arg_b))?;
            Ok(())
        })?;
        if !buf.is_empty() {
            self.printer.write_buf(&buf)?;
            self.diff = true;
        }
        Ok(())
    }

    pub fn line_break(&mut self) -> Result<()> {
        self.printer.line_break()
    }

    pub fn label(&mut self, label: &str) -> Result<()> {
        if self.printer.get_prefix() != DiffPrefix::Modify {
            self.printer.prefix(DiffPrefix::Equal);
        }
        self.printer.line(label, &[])
    }

    fn line_impl<F, T>(&mut self, label: &str, arg_a: T, arg_b: T, mut f: F) -> Result<()>
    where
        F: FnMut(&mut dyn ValuePrinter, &FileHash, T) -> Result<()>,
        T: Copy,
    {
        let mut a = Vec::new();
        let hash_a = self.hash_a;
        self.printer
            .value(&mut a, &mut |printer| f(printer, hash_a, arg_a))?;

        let mut b = Vec::new();
        let hash_b = self.hash_b;
        self.printer
            .value(&mut b, &mut |printer| f(printer, hash_b, arg_b))?;

        if a == b {
            if !a.is_empty() {
                if self.printer.get_prefix() != DiffPrefix::Modify {
                    self.printer.prefix(DiffPrefix::Equal);
                }
                self.printer.line(label, &a)?;
            }
        } else {
            if a.is_empty() {
                self.printer.prefix(DiffPrefix::Add);
                self.printer.line(label, &b)?;
            } else if b.is_empty() {
                self.printer.prefix(DiffPrefix::Delete);
                self.printer.line(label, &a)?;
            } else {
                self.printer.line_diff(label, &a, &b)?;
            }
            self.diff = true;
        }
        Ok(())
    }

    pub fn line<F, T>(&mut self, arg_a: T, arg_b: T, f: F) -> Result<()>
    where
        F: FnMut(&mut dyn ValuePrinter, &FileHash, T) -> Result<()>,
        T: Copy,
    {
        self.line_impl("", arg_a, arg_b, f)
    }

    pub fn field<F, T>(&mut self, label: &str, arg_a: T, arg_b: T, f: F) -> Result<()>
    where
        F: FnMut(&mut dyn ValuePrinter, &FileHash, T) -> Result<()>,
        T: Copy,
    {
        self.line_impl(label, arg_a, arg_b, f)
    }

    pub fn field_u64(&mut self, label: &str, arg_a: u64, arg_b: u64) -> Result<()> {
        let base = arg_a;
        self.field(label, arg_a, arg_b, |w, _hash, arg| {
            write!(w, "{}", arg)?;
            if arg != base {
                write!(w, " ({:+})", arg as i64 - base as i64)?;
            }
            Ok(())
        })
    }

    pub fn list<T: DiffList>(
        &mut self,
        arg_a: &T::Arg,
        list_a: &[T],
        arg_b: &T::Arg,
        list_b: &[T],
    ) -> Result<()> {
        let path = shortest_path(
            list_a,
            list_b,
            |a| a.step_cost(self, arg_a),
            |b| b.step_cost(self, arg_b),
            |a, b| T::diff_cost(self, arg_a, a, arg_b, b),
        );
        let mut iter_a = list_a.iter();
        let mut iter_b = list_b.iter();
        for dir in path {
            match dir {
                Direction::None => break,
                Direction::Diagonal => {
                    if let (Some(a), Some(b)) = (iter_a.next(), iter_b.next()) {
                        T::diff(self, arg_a, a, arg_b, b)?;
                    }
                }
                Direction::Horizontal => {
                    if let Some(a) = iter_a.next() {
                        self.prefix_delete(|state| a.print(state, arg_a))?;
                    }
                }
                Direction::Vertical => {
                    if let Some(b) = iter_b.next() {
                        self.prefix_add(|state| b.print(state, arg_b))?;
                    }
                }
            }
        }
        Ok(())
    }

    // This is similar to `list`, but because the items are ordered
    // we can do a greedy search.
    //
    // The caller must provide lists that are already sorted.
    pub fn ord_list<T: Ord + Print>(
        &mut self,
        arg_a: &T::Arg,
        list_a: &[T],
        arg_b: &T::Arg,
        list_b: &[T],
    ) -> Result<()> {
        for item in MergeIterator::new(list_a.iter(), list_b.iter(), <&T>::cmp) {
            match item {
                MergeResult::Both(a, b) => {
                    T::diff(self, arg_a, a, arg_b, b)?;
                }
                MergeResult::Left(a) => {
                    self.prefix_delete(|state| a.print(state, arg_a))?;
                }
                MergeResult::Right(b) => {
                    self.prefix_add(|state| b.print(state, arg_b))?;
                }
            }
        }
        Ok(())
    }

    // Sort then display a merged list of items.
    //
    // Items with no difference are not displayed.
    //
    // Also, self.options controls:
    // - sort order
    // - display of added/deleted options
    pub fn sort_list<'i, T>(
        &mut self,
        arg_a: &T::Arg,
        arg_b: &T::Arg,
        list: &mut [MergeResult<&'i T, &'i T>],
    ) -> Result<()>
    where
        T: SortList + 'i,
    {
        list.sort_by(|x, y| {
            MergeResult::cmp(x, y, &self.hash_a, &self.hash_b, |x, hash_x, y, hash_y| {
                T::cmp_by(hash_x, x, hash_y, y, self.options)
            })
        });

        for item in list {
            match *item {
                MergeResult::Both(a, b) => {
                    self.print_if_diff(|state| T::diff(state, arg_a, a, arg_b, b))?;
                }
                MergeResult::Left(a) => {
                    if !self.options.ignore_deleted {
                        self.prefix_delete(|state| a.print(state, arg_a))?;
                    }
                }
                MergeResult::Right(b) => {
                    if !self.options.ignore_added {
                        self.prefix_add(|state| b.print(state, arg_b))?;
                    }
                }
            }
        }
        Ok(())
    }
}

pub(crate) trait Print {
    type Arg;

    // TODO: need associated type constructor to avoid requiring arg to be a reference?
    fn print(&self, state: &mut PrintState, arg: &Self::Arg) -> Result<()>;

    fn diff(
        state: &mut DiffState,
        arg_a: &Self::Arg,
        a: &Self,
        arg_b: &Self::Arg,
        b: &Self,
    ) -> Result<()>;
}

impl<'a, T> Print for &'a T
where
    T: Print,
{
    type Arg = T::Arg;

    fn print(&self, state: &mut PrintState, arg: &Self::Arg) -> Result<()> {
        T::print(*self, state, arg)
    }

    fn diff(
        state: &mut DiffState,
        arg_a: &Self::Arg,
        a: &Self,
        arg_b: &Self::Arg,
        b: &Self,
    ) -> Result<()> {
        T::diff(state, arg_a, *a, arg_b, *b)
    }
}

pub(crate) trait PrintHeader {
    fn print_header(&self, state: &mut PrintState) -> Result<()>;
    fn print_body(&self, state: &mut PrintState, unit: &parser::Unit) -> Result<()>;
    fn diff_header(state: &mut DiffState, a: &Self, b: &Self) -> Result<()>
    where
        Self: Sized;
    fn diff_body(
        state: &mut DiffState,
        unit_a: &parser::Unit,
        a: &Self,
        unit_b: &parser::Unit,
        b: &Self,
    ) -> Result<()>
    where
        Self: Sized;
}

pub(crate) trait DiffList: Print {
    fn step_cost(&self, state: &DiffState, arg: &Self::Arg) -> usize;

    fn diff_cost(
        state: &DiffState,
        arg_a: &Self::Arg,
        a: &Self,
        arg_b: &Self::Arg,
        b: &Self,
    ) -> usize;
}

pub(crate) trait SortList: Print {
    fn cmp_id(
        hash_a: &FileHash,
        a: &Self,
        hash_b: &FileHash,
        b: &Self,
        options: &Options,
    ) -> cmp::Ordering;

    fn cmp_id_for_sort(
        hash_a: &FileHash,
        a: &Self,
        hash_b: &FileHash,
        b: &Self,
        options: &Options,
    ) -> cmp::Ordering {
        Self::cmp_id(hash_a, a, hash_b, b, options)
    }

    fn cmp_by(
        hash_a: &FileHash,
        a: &Self,
        hash_b: &FileHash,
        b: &Self,
        options: &Options,
    ) -> cmp::Ordering;
}

pub enum MergeResult<T, U> {
    Left(T),
    Right(U),
    Both(T, U),
}

impl<T> MergeResult<T, T> {
    fn cmp<Arg, F>(x: &Self, y: &Self, arg_left: Arg, arg_right: Arg, f: F) -> cmp::Ordering
    where
        Arg: Copy,
        F: Fn(&T, Arg, &T, Arg) -> cmp::Ordering,
    {
        match x {
            MergeResult::Both(_, x_right) => match y {
                MergeResult::Both(_, y_right) => f(x_right, arg_right, y_right, arg_right),
                MergeResult::Left(y_left) => f(x_right, arg_right, y_left, arg_left),
                MergeResult::Right(y_right) => f(x_right, arg_right, y_right, arg_right),
            },
            MergeResult::Left(x_left) => match y {
                MergeResult::Both(_, y_right) => f(x_left, arg_left, y_right, arg_right),
                MergeResult::Left(y_left) => f(x_left, arg_left, y_left, arg_left),
                MergeResult::Right(y_right) => f(x_left, arg_left, y_right, arg_right),
            },
            MergeResult::Right(x_right) => match y {
                MergeResult::Both(_, y_right) => f(x_right, arg_right, y_right, arg_right),
                MergeResult::Left(y_left) => f(x_right, arg_right, y_left, arg_left),
                MergeResult::Right(y_right) => f(x_right, arg_right, y_right, arg_right),
            },
        }
    }
}

pub struct MergeIterator<T, U, L, R, C>
where
    L: Iterator<Item = T>,
    R: Iterator<Item = U>,
    C: Fn(&T, &U) -> cmp::Ordering,
{
    iter_left: L,
    iter_right: R,
    item_left: Option<T>,
    item_right: Option<U>,
    item_cmp: C,
}

impl<T, U, L, R, C> MergeIterator<T, U, L, R, C>
where
    L: Iterator<Item = T>,
    R: Iterator<Item = U>,
    C: Fn(&T, &U) -> cmp::Ordering,
{
    pub fn new(mut iter_left: L, mut iter_right: R, item_cmp: C) -> Self {
        let item_left = iter_left.next();
        let item_right = iter_right.next();
        MergeIterator {
            iter_left,
            iter_right,
            item_left,
            item_right,
            item_cmp,
        }
    }
}

impl<T, U, L, R, C> Iterator for MergeIterator<T, U, L, R, C>
where
    L: Iterator<Item = T>,
    R: Iterator<Item = U>,
    C: Fn(&T, &U) -> cmp::Ordering,
{
    type Item = MergeResult<T, U>;

    fn next(&mut self) -> Option<MergeResult<T, U>> {
        match (self.item_left.take(), self.item_right.take()) {
            (Some(left), Some(right)) => match (self.item_cmp)(&left, &right) {
                cmp::Ordering::Equal => {
                    self.item_left = self.iter_left.next();
                    self.item_right = self.iter_right.next();
                    Some(MergeResult::Both(left, right))
                }
                cmp::Ordering::Less => {
                    self.item_left = self.iter_left.next();
                    self.item_right = Some(right);
                    Some(MergeResult::Left(left))
                }
                cmp::Ordering::Greater => {
                    self.item_left = Some(left);
                    self.item_right = self.iter_right.next();
                    Some(MergeResult::Right(right))
                }
            },
            (Some(left), None) => {
                self.item_left = self.iter_left.next();
                Some(MergeResult::Left(left))
            }
            (None, Some(right)) => {
                self.item_right = self.iter_right.next();
                Some(MergeResult::Right(right))
            }
            (None, None) => None,
        }
    }
}

#[derive(Debug, Clone, Copy)]
pub enum Direction {
    None,
    Diagonal,
    Horizontal,
    Vertical,
}

#[derive(Debug, Clone, Copy)]
struct Node {
    cost: usize,
    from: Direction,
    done: bool,
}

#[derive(Debug, Eq, PartialEq)]
struct State {
    cost: usize,
    index1: usize,
    index2: usize,
}

impl Ord for State {
    fn cmp(&self, other: &State) -> cmp::Ordering {
        // min-heap
        other.cost.cmp(&self.cost)
    }
}

impl PartialOrd for State {
    fn partial_cmp(&self, other: &State) -> Option<cmp::Ordering> {
        Some(self.cmp(other))
    }
}

// Use Dijkstra's algorithm to find the shortest edit path between two arrays.
//
// step_cost is used for add/delete operations.
//
// diff_cost is used to calculate the cost for modify operations. It should
// return:
//     0 for items that are completely equal
//     (2 * step_cost) for items that are completely different
//     values in between for items that are partially equal
fn shortest_path<Item, Step1, Step2, Diff>(
    item1: &[Item],
    item2: &[Item],
    step_cost1: Step1,
    step_cost2: Step2,
    diff_cost: Diff,
) -> Vec<Direction>
where
    Step1: Fn(&Item) -> usize,
    Step2: Fn(&Item) -> usize,
    Diff: Fn(&Item, &Item) -> usize,
{
    // len + 1 because we need to allow for the 0 items state too.
    let len1 = item1.len() + 1;
    let len2 = item2.len() + 1;
    let len = len1 * len2;

    let mut node: Vec<Node> = vec![
        Node {
            cost: usize::MAX,
            from: Direction::None,
            done: false,
        };
        len
    ];
    let mut heap = BinaryHeap::new();

    fn push(
        node: &mut Node,
        heap: &mut BinaryHeap<State>,
        index1: usize,
        index2: usize,
        cost: usize,
        from: Direction,
    ) {
        if cost < node.cost {
            node.cost = cost;
            node.from = from;
            heap.push(State {
                cost,
                index1,
                index2,
            });
        }
    }

    // Start at the end.  This makes indexing and boundary conditions
    // simpler, and also means we can backtrack in order.
    push(
        &mut node[len - 1],
        &mut heap,
        len1 - 1,
        len2 - 1,
        0,
        Direction::None,
    );

    while let Some(State { index1, index2, .. }) = heap.pop() {
        if (index1, index2) == (0, 0) {
            let mut result = Vec::new();
            let mut index1 = 0;
            let mut index2 = 0;
            loop {
                let index = index1 + index2 * len1;
                let from = node[index].from;
                match from {
                    Direction::None => {
                        return result;
                    }
                    Direction::Diagonal => {
                        index1 += 1;
                        index2 += 1;
                    }
                    Direction::Horizontal => {
                        index1 += 1;
                    }
                    Direction::Vertical => {
                        index2 += 1;
                    }
                }
                result.push(from);
            }
        }

        let index = index1 + index2 * len1;
        if node[index].done {
            continue;
        }
        node[index].done = true;

        if index2 > 0 {
            let next2 = index2 - 1;
            let next = index - len1;
            if !node[next].done {
                let cost = node[index].cost + step_cost2(&item2[next2]);
                push(
                    &mut node[next],
                    &mut heap,
                    index1,
                    next2,
                    cost,
                    Direction::Vertical,
                );
            }
        }
        if index1 > 0 {
            let next1 = index1 - 1;
            let next = index - 1;
            if !node[next].done {
                let cost = node[index].cost + step_cost1(&item1[next1]);
                push(
                    &mut node[next],
                    &mut heap,
                    next1,
                    index2,
                    cost,
                    Direction::Horizontal,
                );
            }
        }
        if index1 > 0 && index2 > 0 {
            let next1 = index1 - 1;
            let next2 = index2 - 1;
            let next = index - len1 - 1;
            if !node[next].done {
                let step_cost = step_cost1(&item1[next1]) + step_cost2(&item2[next2]);
                let diff_cost = diff_cost(&item1[next1], &item2[next2]);
                if diff_cost < step_cost {
                    let cost = node[index].cost + diff_cost;
                    push(
                        &mut node[next],
                        &mut heap,
                        next1,
                        next2,
                        cost,
                        Direction::Diagonal,
                    );
                }
            }
        }
    }

    panic!("failed to find shortest path");
}