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
use crate::term_colored::TermColored;
use crate::text::Text;
use derive_new::new;
use pretty::{BoxAllocator, DocAllocator};
use std::hash::Hash;
use termcolor::{Color, ColorSpec};

#[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd, Hash)]
pub enum ShellStyle {
    Delimiter,
    Key,
    Value,
    Equals,
    Kind,
    Keyword,
    Operator,
    Variable,
    Primitive,
    Opaque,
    Description,
    Error,
}

impl From<ShellAnnotation> for ColorSpec {
    fn from(ann: ShellAnnotation) -> ColorSpec {
        match ann.style {
            ShellStyle::Delimiter => ColorSpec::new()
                .set_fg(Some(Color::White))
                .set_intense(false)
                .clone(),
            ShellStyle::Key => ColorSpec::new()
                .set_fg(Some(Color::Black))
                .set_intense(true)
                .clone(),
            ShellStyle::Value => ColorSpec::new()
                .set_fg(Some(Color::White))
                .set_intense(true)
                .clone(),
            ShellStyle::Equals => ColorSpec::new()
                .set_fg(Some(Color::Black))
                .set_intense(true)
                .clone(),
            ShellStyle::Kind => ColorSpec::new().set_fg(Some(Color::Cyan)).clone(),
            ShellStyle::Variable => ColorSpec::new()
                .set_fg(Some(Color::Green))
                .set_intense(true)
                .clone(),
            ShellStyle::Keyword => ColorSpec::new().set_fg(Some(Color::Magenta)).clone(),
            ShellStyle::Operator => ColorSpec::new().set_fg(Some(Color::Yellow)).clone(),
            ShellStyle::Primitive => ColorSpec::new()
                .set_fg(Some(Color::Green))
                .set_intense(true)
                .clone(),
            ShellStyle::Opaque => ColorSpec::new()
                .set_fg(Some(Color::Yellow))
                .set_intense(true)
                .clone(),
            ShellStyle::Description => ColorSpec::new()
                .set_fg(Some(Color::Black))
                .set_intense(true)
                .clone(),
            ShellStyle::Error => ColorSpec::new()
                .set_fg(Some(Color::Red))
                .set_intense(true)
                .clone(),
        }
    }
}

#[derive(Clone, Copy, Eq, Ord, PartialEq, PartialOrd, Hash, new)]
pub struct ShellAnnotation {
    style: ShellStyle,
}

impl std::fmt::Debug for ShellAnnotation {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "{:?}", self.style)
    }
}

impl ShellAnnotation {
    pub fn style(style: impl Into<ShellStyle>) -> ShellAnnotation {
        ShellAnnotation {
            style: style.into(),
        }
    }
}

pub type PrettyDebugDoc =
    pretty::Doc<'static, pretty::BoxDoc<'static, ShellAnnotation>, ShellAnnotation>;

pub type PrettyDebugDocBuilder = pretty::DocBuilder<'static, pretty::BoxAllocator, ShellAnnotation>;

pub use self::DebugDocBuilder as b;

#[derive(Clone, new)]
pub struct DebugDocBuilder {
    pub inner: PrettyDebugDocBuilder,
}

impl PrettyDebug for DebugDocBuilder {
    fn pretty(&self) -> DebugDocBuilder {
        self.clone()
    }
}

impl std::ops::Add for DebugDocBuilder {
    type Output = DebugDocBuilder;

    fn add(self, rhs: DebugDocBuilder) -> DebugDocBuilder {
        DebugDocBuilder::new(self.inner.append(rhs.inner))
    }
}

impl DebugDocBuilder {
    pub fn from_doc(doc: DebugDoc) -> DebugDocBuilder {
        DebugDocBuilder {
            inner: BoxAllocator.nil().append(doc),
        }
    }

    pub fn blank() -> DebugDocBuilder {
        BoxAllocator.nil().into()
    }

    pub fn delimiter(string: impl std::fmt::Display) -> DebugDocBuilder {
        DebugDocBuilder::styled(string, ShellStyle::Delimiter)
    }

    pub fn key(string: impl std::fmt::Display) -> DebugDocBuilder {
        DebugDocBuilder::styled(string, ShellStyle::Key)
    }

    pub fn value(string: impl std::fmt::Display) -> DebugDocBuilder {
        DebugDocBuilder::styled(string, ShellStyle::Value)
    }

    pub fn as_value(self) -> DebugDocBuilder {
        self.inner
            .annotate(ShellAnnotation::style(ShellStyle::Value))
            .into()
    }

    pub fn equals() -> DebugDocBuilder {
        DebugDocBuilder::styled("=", ShellStyle::Equals)
    }

    pub fn kind(string: impl std::fmt::Display) -> DebugDocBuilder {
        DebugDocBuilder::styled(string, ShellStyle::Kind)
    }

    pub fn as_kind(self) -> DebugDocBuilder {
        self.inner
            .annotate(ShellAnnotation::style(ShellStyle::Kind))
            .into()
    }

    pub fn typed(kind: &str, value: DebugDocBuilder) -> DebugDocBuilder {
        b::delimit("(", b::kind(kind) + b::space() + value.group(), ")").group()
    }

    pub fn subtyped(
        kind: &str,
        subkind: impl std::fmt::Display,
        value: DebugDocBuilder,
    ) -> DebugDocBuilder {
        b::delimit(
            "(",
            (b::kind(kind) + b::delimit("[", b::kind(format!("{}", subkind)), "]")).group()
                + b::space()
                + value.group(),
            ")",
        )
        .group()
    }

    pub fn keyword(string: impl std::fmt::Display) -> DebugDocBuilder {
        DebugDocBuilder::styled(string, ShellStyle::Keyword)
    }

    pub fn var(string: impl std::fmt::Display) -> DebugDocBuilder {
        DebugDocBuilder::styled(string, ShellStyle::Variable)
    }

    pub fn operator(string: impl std::fmt::Display) -> DebugDocBuilder {
        DebugDocBuilder::styled(string, ShellStyle::Operator)
    }

    pub fn primitive(string: impl std::fmt::Display) -> DebugDocBuilder {
        DebugDocBuilder::styled(format!("{}", string), ShellStyle::Primitive)
    }

    pub fn opaque(string: impl std::fmt::Display) -> DebugDocBuilder {
        DebugDocBuilder::styled(string, ShellStyle::Opaque)
    }

    pub fn description(string: impl std::fmt::Display) -> DebugDocBuilder {
        DebugDocBuilder::styled(string, ShellStyle::Description)
    }

    pub fn error(string: impl std::fmt::Display) -> DebugDocBuilder {
        DebugDocBuilder::styled(string, ShellStyle::Error)
    }

    pub fn delimit(start: &str, doc: DebugDocBuilder, end: &str) -> DebugDocBuilder {
        DebugDocBuilder::delimiter(start) + doc + DebugDocBuilder::delimiter(end)
    }

    pub fn preceded(before: DebugDocBuilder, body: DebugDocBuilder) -> DebugDocBuilder {
        if body.is_empty() {
            body
        } else {
            before + body
        }
    }

    pub fn surrounded_option(
        before: Option<DebugDocBuilder>,
        builder: Option<DebugDocBuilder>,
        after: Option<DebugDocBuilder>,
    ) -> DebugDocBuilder {
        match builder {
            None => DebugDocBuilder::blank(),
            Some(b) => b::option(before) + b + b::option(after),
        }
    }

    pub fn preceded_option(
        before: Option<DebugDocBuilder>,
        builder: Option<DebugDocBuilder>,
    ) -> DebugDocBuilder {
        DebugDocBuilder::surrounded_option(before, builder, None)
    }

    pub fn option(builder: Option<DebugDocBuilder>) -> DebugDocBuilder {
        match builder {
            None => DebugDocBuilder::blank(),
            Some(b) => b,
        }
    }

    pub fn space() -> DebugDocBuilder {
        BoxAllocator.space().into()
    }

    pub fn newline() -> DebugDocBuilder {
        BoxAllocator.newline().into()
    }

    pub fn is_empty(&self) -> bool {
        match &self.inner.1 {
            pretty::Doc::Nil => true,
            _ => false,
        }
    }

    pub fn or(self, doc: DebugDocBuilder) -> DebugDocBuilder {
        if self.is_empty() {
            doc
        } else {
            self
        }
    }

    pub fn group(self) -> DebugDocBuilder {
        self.inner.group().into()
    }

    pub fn nest(self) -> DebugDocBuilder {
        self.inner.nest(1).group().into()
    }

    pub fn intersperse_with_source<'a, T: PrettyDebugWithSource + 'a>(
        list: impl IntoIterator<Item = &'a T>,
        separator: DebugDocBuilder,
        source: &str,
    ) -> DebugDocBuilder {
        BoxAllocator
            .intersperse(
                list.into_iter().filter_map(|item| {
                    let item = item.pretty_debug(source);
                    if item.is_empty() {
                        None
                    } else {
                        Some(item)
                    }
                }),
                separator,
            )
            .into()
    }

    pub fn intersperse<T: PrettyDebug>(
        list: impl IntoIterator<Item = T>,
        separator: DebugDocBuilder,
    ) -> DebugDocBuilder {
        BoxAllocator
            .intersperse(
                list.into_iter().filter_map(|item| {
                    let item = item.pretty();
                    if item.is_empty() {
                        None
                    } else {
                        Some(item)
                    }
                }),
                separator,
            )
            .into()
    }

    pub fn list(list: impl IntoIterator<Item = DebugDocBuilder>) -> DebugDocBuilder {
        let mut result: DebugDocBuilder = BoxAllocator.nil().into();

        for item in list {
            result = result + item;
        }

        result.into()
    }

    fn styled(string: impl std::fmt::Display, style: ShellStyle) -> DebugDocBuilder {
        BoxAllocator
            .text(string.to_string())
            .annotate(ShellAnnotation::style(style))
            .into()
    }
}

impl std::ops::Deref for DebugDocBuilder {
    type Target = PrettyDebugDocBuilder;

    fn deref(&self) -> &Self::Target {
        &self.inner
    }
}

#[derive(Clone, Debug, Eq, Ord, PartialEq, PartialOrd, new)]
pub struct DebugDoc {
    pub inner: PrettyDebugDoc,
}

pub trait PrettyDebugWithSource: Sized {
    fn pretty_debug(&self, source: &str) -> DebugDocBuilder;

    // This is a transitional convenience method
    fn debug(&self, source: impl Into<Text>) -> String
    where
        Self: Clone,
    {
        self.clone().debuggable(source).display()
    }

    fn debuggable(self, source: impl Into<Text>) -> DebuggableWithSource<Self> {
        DebuggableWithSource {
            inner: self,
            source: source.into(),
        }
    }
}

impl<T: PrettyDebug> PrettyDebugWithSource for T {
    fn pretty_debug(&self, _source: &str) -> DebugDocBuilder {
        self.pretty()
    }
}

pub struct DebuggableWithSource<T: PrettyDebugWithSource> {
    inner: T,
    source: Text,
}

impl<T> PrettyDebug for DebuggableWithSource<T>
where
    T: PrettyDebugWithSource,
{
    fn pretty(&self) -> DebugDocBuilder {
        self.inner.pretty_debug(&self.source)
    }
}

impl PrettyDebug for DebugDoc {
    fn pretty(&self) -> DebugDocBuilder {
        DebugDocBuilder::new(BoxAllocator.nil().append(self.inner.clone()))
    }
}

pub trait PrettyDebug {
    fn pretty(&self) -> DebugDocBuilder;

    fn to_doc(&self) -> DebugDoc {
        DebugDoc::new(self.pretty().into())
    }

    fn pretty_doc(&self) -> PrettyDebugDoc {
        let builder = self.pretty();
        builder.inner.into()
    }

    fn pretty_builder(&self) -> PrettyDebugDocBuilder {
        let doc = self.pretty();
        doc.inner
    }

    /// A convenience method that prints out the document without colors in
    /// 70 columns. Generally, you should use plain_string or colored_string
    /// if possible, but display() can be useful for trace lines and things
    /// like that, where you don't have control over the terminal.
    fn display(&self) -> String {
        self.plain_string(70)
    }

    fn plain_string(&self, width: usize) -> String {
        let doc = self.pretty_doc();
        let mut buffer = termcolor::Buffer::no_color();

        doc.render_raw(width, &mut TermColored::new(&mut buffer))
            .unwrap();

        String::from_utf8_lossy(buffer.as_slice()).to_string()
    }

    fn colored_string(&self, width: usize) -> String {
        let doc = self.pretty_doc();
        let mut buffer = termcolor::Buffer::ansi();

        doc.render_raw(width, &mut TermColored::new(&mut buffer))
            .unwrap();

        String::from_utf8_lossy(buffer.as_slice()).to_string()
    }
}

impl Into<DebugDocBuilder> for PrettyDebugDocBuilder {
    fn into(self) -> DebugDocBuilder {
        DebugDocBuilder { inner: self }
    }
}

impl std::ops::Deref for DebugDoc {
    type Target = PrettyDebugDoc;

    fn deref(&self) -> &Self::Target {
        &self.inner
    }
}

impl From<DebugDoc> for PrettyDebugDoc {
    fn from(input: DebugDoc) -> PrettyDebugDoc {
        input.inner
    }
}

impl Into<PrettyDebugDoc> for DebugDocBuilder {
    fn into(self) -> PrettyDebugDoc {
        self.inner.into()
    }
}

fn hash_doc<H: std::hash::Hasher>(doc: &PrettyDebugDoc, state: &mut H) {
    match doc {
        pretty::Doc::Nil => 0u8.hash(state),
        pretty::Doc::Append(a, b) => {
            1u8.hash(state);
            hash_doc(&*a, state);
            hash_doc(&*b, state);
        }
        pretty::Doc::Group(a) => {
            2u8.hash(state);
            hash_doc(&*a, state);
        }
        pretty::Doc::Nest(a, b) => {
            3u8.hash(state);
            a.hash(state);
            hash_doc(&*b, state);
        }
        pretty::Doc::Space => 4u8.hash(state),
        pretty::Doc::Newline => 5u8.hash(state),
        pretty::Doc::Text(t) => {
            6u8.hash(state);
            t.hash(state);
        }
        pretty::Doc::Annotated(a, b) => {
            7u8.hash(state);
            a.hash(state);
            hash_doc(&*b, state);
        }
    }
}

impl std::hash::Hash for DebugDoc {
    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
        hash_doc(&self.inner, state);
    }
}