tiny_pretty 0.3.0

Tiny implementation of Wadler-style pretty printer.
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
use std::{borrow::Cow, rc::Rc};

#[derive(Clone, Debug)]
/// The data structure that describes about pretty printing.
///
/// You should avoid using variants on this enum;
/// instead, use helper functions on this enum.
pub enum Doc<'a> {
    #[doc(hidden)]
    Nil,

    #[doc(hidden)]
    /// The first component is for "flat" mode;
    /// the second component is for "break" mode.
    Alt(Rc<Doc<'a>>, Rc<Doc<'a>>),

    #[doc(hidden)]
    /// Try printing the first doc.
    /// If it exceeds the width limitation, print the second doc.
    Union(Rc<Doc<'a>>, Rc<Doc<'a>>),

    #[doc(hidden)]
    Nest(usize, Rc<Doc<'a>>),

    #[doc(hidden)]
    Text(Cow<'a, str>),

    #[doc(hidden)]
    NewLine,

    #[doc(hidden)]
    EmptyLine,

    #[doc(hidden)]
    /// The first component is the number of spaces if it can be put on a single line;
    /// the second component is the number of offset if it will be broken into different lines.
    Break(usize, usize),

    #[doc(hidden)]
    Group(Cow<'a, [Doc<'a>]>),

    #[doc(hidden)]
    List(Vec<Doc<'a>>),

    #[doc(hidden)]
    Slice(&'a [Doc<'a>]),
}

impl<'a> Doc<'a> {
    #[inline]
    /// Insert a piece of text. It **must not** contain line breaks.
    ///
    /// ```
    /// use tiny_pretty::{print, Doc};
    ///
    /// let doc = Doc::text("code");
    /// assert_eq!("code", &print(&doc, &Default::default()));
    ///
    /// let doc = Doc::text(String::from("code"));
    /// assert_eq!("code", &print(&doc, &Default::default()));
    /// ```
    pub fn text(s: impl Into<Cow<'a, str>>) -> Doc<'a> {
        Doc::Text(s.into())
    }

    #[inline]
    /// Empty doc, which does nothing.
    ///
    /// ```
    /// use tiny_pretty::{print, Doc};
    ///
    /// let doc = Doc::nil();
    /// assert!(print(&doc, &Default::default()).is_empty());
    /// ```
    pub fn nil() -> Doc<'a> {
        Doc::Nil
    }

    #[inline]
    /// Just a space. This is just short for calling [`text`](Doc::text) with a space.
    ///
    /// ```
    /// use tiny_pretty::{print, Doc};
    ///
    /// let doc = Doc::space();
    /// assert_eq!(" ", &print(&doc, &Default::default()));
    /// ```
    pub fn space() -> Doc<'a> {
        Doc::Text(" ".into())
    }

    #[inline]
    /// Force to print a line break.
    ///
    /// ```
    /// use tiny_pretty::{print, Doc, LineBreak, PrintOptions};
    ///
    /// let doc = Doc::hard_line();
    /// let options = Default::default();
    /// assert_eq!("\n", &print(&doc, &options));
    /// let options = PrintOptions {
    ///     line_break: LineBreak::Crlf,
    ///     ..Default::default()
    /// };
    /// assert_eq!("\r\n", &print(&doc, &options));
    ///
    /// // There's a `hard_line` call inside a group,
    /// // so the group always breaks even it doesn't exceed the width limitation.
    /// let doc = Doc::text("fn(")
    ///     .append(Doc::line_or_space())
    ///     .append(Doc::hard_line())
    ///     .group();
    /// assert_eq!("fn(\n\n", &print(&doc, &Default::default()));
    /// ```
    pub fn hard_line() -> Doc<'a> {
        Doc::NewLine
    }

    #[inline]
    /// "Soft line" allows you to put docs on a single line as many as possible.
    /// Once it's going to exceed the width limitation, it will insert a line break,
    /// but before that it will insert spaces instead of line break.
    ///
    /// This is different from [`line_or_space`](Doc::line_or_space). See the examples below.
    ///
    /// ```
    /// use tiny_pretty::{print, Doc, PrintOptions};
    ///
    /// let options = PrintOptions { width: 10, ..Default::default() };
    /// assert_eq!(
    ///     "aaaa bbbb\ncccc",
    ///     &print(
    ///         &Doc::list(vec![
    ///             Doc::text("aaaa"),
    ///             Doc::soft_line(),
    ///             Doc::text("bbbb"),
    ///             Doc::soft_line(),
    ///             Doc::text("cccc"),
    ///         ]).group(),
    ///         &options,
    ///     ),
    /// );
    /// assert_eq!(
    ///     "aaaa\nbbbb\ncccc",
    ///     &print(
    ///         &Doc::list(vec![
    ///             Doc::text("aaaa"),
    ///             Doc::line_or_space(),
    ///             Doc::text("bbbb"),
    ///             Doc::line_or_space(),
    ///             Doc::text("cccc"),
    ///         ]).group(),
    ///         &options,
    ///     ),
    /// );
    /// ```
    pub fn soft_line() -> Doc<'a> {
        Doc::Group(vec![Doc::Break(1, 0)].into())
    }

    #[inline]
    /// "Empty line" is similar to [`hard_line`](Doc::hard_line) but it won't be
    /// affected by indentation. That is, it always prints an empty line without
    /// spaces or tabs indented.
    ///
    /// ```
    /// use tiny_pretty::{print, Doc, PrintOptions};
    ///
    /// assert_eq!(
    ///     "\n",
    ///     &print(
    ///         &Doc::empty_line().nest(1),
    ///         &Default::default(),
    ///     ),
    /// );
    /// assert_eq!(
    ///     "\n ",
    ///     &print(
    ///         &Doc::hard_line().nest(1),
    ///         &Default::default(),
    ///     ),
    /// );
    /// ```
    pub fn empty_line() -> Doc<'a> {
        Doc::EmptyLine
    }

    #[inline]
    /// Create a list of docs.
    ///
    /// ```
    /// use tiny_pretty::{print, Doc};
    ///
    /// let doc = Doc::list(vec![Doc::text("a"), Doc::text("b"), Doc::text("c")]);
    /// assert_eq!("abc", &print(&doc, &Default::default()));
    /// ```
    pub fn list(docs: Vec<Doc<'a>>) -> Doc<'a> {
        Doc::List(docs)
    }

    #[inline]
    /// Create a slice of docs, similar to [`list`](Doc::list).
    ///
    /// This won't create a [`Vec`] with allocation, but calling [`append`](Doc::append) or [`concat`](Doc::concat) on it will create a [`Vec`].
    ///
    /// ```
    /// use tiny_pretty::{print, Doc};
    ///
    /// let docs = [Doc::text("a"), Doc::text("b"), Doc::text("c")];
    /// assert_eq!("abc", &print(&Doc::slice(&docs), &Default::default()));
    /// ```
    pub fn slice(docs: &'a [Doc<'a>]) -> Doc<'a> {
        Doc::Slice(docs)
    }

    #[inline]
    /// Print a space if doc can be put on a single line, otherwise print a line break.
    ///
    /// *This won't take any effects if used outside a group: it will just print a line break.*
    ///
    /// ```
    /// use tiny_pretty::{print, Doc, PrintOptions};
    ///
    /// let options = PrintOptions { width: 10, ..Default::default() };
    /// assert_eq!(
    ///     "aaaa\nbbbb\ncccc",
    ///     &print(
    ///         &Doc::list(vec![
    ///             Doc::text("aaaa"),
    ///             Doc::line_or_space(),
    ///             Doc::text("bbbb"),
    ///             Doc::line_or_space(),
    ///             Doc::text("cccc"),
    ///         ]).group(),
    ///         &options,
    ///     ),
    /// );
    /// assert_eq!(
    ///     "a b",
    ///     &print(
    ///         &Doc::list(vec![
    ///             Doc::text("a"),
    ///             Doc::line_or_space(),
    ///             Doc::text("b"),
    ///         ]).group(),
    ///         &options,
    ///     ),
    /// );
    ///
    /// assert_eq!(
    ///     "a\nb",
    ///     &print(
    ///         &Doc::list(vec![
    ///             Doc::text("a"),
    ///             Doc::line_or_space(),
    ///             Doc::text("b"),
    ///         ]), // <-- no grouping here
    ///         &options,
    ///     ),
    /// );
    /// ```
    pub fn line_or_space() -> Doc<'a> {
        Doc::Break(1, 0)
    }

    #[inline]
    /// Print nothing if doc can be put on a single line, otherwise print a line break.
    ///
    /// *This won't take any effects if used outside a group: it will just print a line break.*
    ///
    /// ```
    /// use tiny_pretty::{print, Doc, PrintOptions};
    ///
    /// let options = PrintOptions { width: 5, ..Default::default() };
    /// assert_eq!(
    ///     "func(\narg",
    ///     &print(
    ///         &Doc::list(vec![
    ///             Doc::text("func("),
    ///             Doc::line_or_nil(),
    ///             Doc::text("arg"),
    ///         ]).group(),
    ///         &options,
    ///     ),
    /// );
    /// assert_eq!(
    ///     "f(arg",
    ///     &print(
    ///         &Doc::list(vec![
    ///             Doc::text("f("),
    ///             Doc::line_or_nil(),
    ///             Doc::text("arg"),
    ///         ]).group(),
    ///         &options,
    ///     ),
    /// );
    ///
    /// assert_eq!(
    ///     "f(\narg",
    ///     &print(
    ///         &Doc::list(vec![
    ///             Doc::text("f("),
    ///             Doc::line_or_nil(),
    ///             Doc::text("arg"),
    ///         ]), // <-- no grouping here
    ///         &options,
    ///     ),
    /// );
    /// ```
    pub fn line_or_nil() -> Doc<'a> {
        Doc::Break(0, 0)
    }

    #[inline]
    /// Apply `doc_flat` when it can be put on a single line,
    /// otherwise apply `doc_break`.
    ///
    /// *This won't take any effects if used outside a group: it will just apply `doc_break`.*
    ///
    /// ```
    /// use tiny_pretty::{print, Doc, PrintOptions};
    ///
    /// let doc = Doc::list(vec![
    ///     Doc::text("function("),
    ///     Doc::line_or_nil(),
    ///     Doc::text("arg"),
    ///     Doc::flat_or_break(Doc::nil(), Doc::text(",")),
    ///     Doc::line_or_nil(),
    ///     Doc::text(")"),
    /// ]).group();
    ///
    /// let options = PrintOptions {
    ///     width: 10,
    ///     ..Default::default()
    /// };
    /// assert_eq!("function(\narg,\n)", &print(&doc, &options));
    ///
    /// let options = PrintOptions {
    ///     width: 20,
    ///     ..Default::default()
    /// };
    /// assert_eq!("function(arg)", &print(&doc, &options));
    ///
    ///
    ///
    /// let doc = Doc::list(vec![
    ///     Doc::text("function("),
    ///     Doc::line_or_nil(),
    ///     Doc::text("arg"),
    ///     Doc::flat_or_break(Doc::nil(), Doc::text(",")),
    ///     Doc::line_or_nil(),
    ///     Doc::text(")"),
    /// ]); // <-- no grouping here
    ///
    /// let options = PrintOptions {
    ///     width: 20,
    ///     ..Default::default()
    /// };
    /// assert_eq!("function(\narg,\n)", &print(&doc, &options));
    /// ```
    pub fn flat_or_break(doc_flat: Doc<'a>, doc_break: Doc<'a>) -> Doc<'a> {
        Doc::Alt(Rc::new(doc_flat), Rc::new(doc_break))
    }

    #[inline]
    /// Try applying the current doc. If it exceeds the width limitation, apply the `alternate` doc.
    ///
    /// This looks similar to [`flat_or_break`](Doc::flat_or_break),
    /// but you should use [`flat_or_break`](Doc::flat_or_break) with [`group`](Doc::group) as possible.
    ///
    /// Only consider using this if there're some [`hard_line`](Doc::hard_line) calls in your doc,
    /// since [`hard_line`](Doc::hard_line) will always break in a group.
    /// ```
    /// use tiny_pretty::{print, Doc, PrintOptions};
    ///
    /// let closure = Doc::list(vec![
    ///     Doc::text("|| {"),
    ///     Doc::hard_line()
    ///         .append(
    ///             Doc::text("call2(|| {")
    ///                 .append(Doc::hard_line().append(Doc::text("value")).nest(4))
    ///                 .append(Doc::hard_line())
    ///                 .append(Doc::text("})"))
    ///         )
    ///         .nest(4),
    ///     Doc::hard_line(),
    ///     Doc::text("}"),
    /// ]);
    ///
    /// let doc = Doc::text("fn main() {")
    ///     .append(
    ///         Doc::hard_line()
    ///             .append(
    ///                 Doc::list(vec![
    ///                     Doc::text("call1("),
    ///                     Doc::nil()
    ///                         .append(Doc::text("very_long_arg"))
    ///                         .append(Doc::text(","))
    ///                         .append(Doc::space())
    ///                         .append(closure.clone())
    ///                         .nest(0),
    ///                     Doc::text(")"),
    ///                 ]).union(Doc::list(vec![
    ///                     Doc::text("call1("),
    ///                         Doc::hard_line()
    ///                             .append(Doc::text("very_long_arg"))
    ///                             .append(Doc::text(","))
    ///                             .append(Doc::hard_line())
    ///                             .append(closure)
    ///                             .nest(4),
    ///                         Doc::hard_line(),
    ///                         Doc::text(")"),
    ///                 ])),
    ///             )
    ///             .nest(4)
    ///     )
    ///     .append(Doc::hard_line())
    ///     .append(Doc::text("}"));
    ///
    /// let options = PrintOptions {
    ///     width: 10,
    ///     ..Default::default()
    /// };
    /// assert_eq!("fn main() {
    ///     call1(
    ///         very_long_arg,
    ///         || {
    ///             call2(|| {
    ///                 value
    ///             })
    ///         }
    ///     )
    /// }", &print(&doc, &options));
    ///
    /// let options = PrintOptions {
    ///     width: 30,
    ///     ..Default::default()
    /// };
    /// assert_eq!("fn main() {
    ///     call1(very_long_arg, || {
    ///         call2(|| {
    ///             value
    ///         })
    ///     })
    /// }", &print(&doc, &options));
    /// ```
    pub fn union(self, alternate: Doc<'a>) -> Doc<'a> {
        Doc::Union(Rc::new(self), Rc::new(alternate))
    }

    #[inline]
    /// Mark the docs as a group.
    ///
    /// For a group of docs, when printing,
    /// they will be checked if those docs can be put on a single line.
    /// If they can't, it may insert line breaks according to the
    /// [`line_or_space`](Doc::line_or_space), [`line_or_nil`](Doc::line_or_nil)
    /// or [`soft_line`](Doc::soft_line) calls in the group.
    /// (Also, please read examples of those functions for usage of `group`.)
    ///
    /// Calling this on text won’t take any effects.
    ///
    /// ```
    /// use tiny_pretty::{print, Doc};
    ///
    /// let doc = Doc::text("code").group();
    /// assert_eq!("code", &print(&doc, &Default::default()));
    /// ```
    pub fn group(self) -> Doc<'a> {
        match self {
            Doc::List(list) => Doc::Group(list.into()),
            Doc::Slice(slice) => Doc::Group(slice.into()),
            Doc::Group(..) => self,
            doc => Doc::Group(vec![doc].into()),
        }
    }

    #[inline]
    /// Join two docs.
    ///
    /// ```
    /// use tiny_pretty::{print, Doc};
    ///
    /// let doc = Doc::text("a").append(Doc::text("b")).append(Doc::text("c"));
    /// assert_eq!("abc", &print(&doc, &Default::default()));
    /// ```
    pub fn append(self, other: Doc<'a>) -> Doc<'a> {
        let mut current = if let Doc::List(docs) = self {
            docs
        } else {
            vec![self]
        };
        match other {
            Doc::List(mut docs) => current.append(&mut docs),
            _ => current.push(other),
        }
        Doc::List(current)
    }

    #[inline]
    /// Concatenate an iterator whose items are docs.
    ///
    /// ```
    /// use tiny_pretty::{print, Doc};
    ///
    /// let doc = Doc::text("a").concat(vec![Doc::text("b"), Doc::text("c")].into_iter());
    /// assert_eq!("abc", &print(&doc, &Default::default()));
    /// ```
    pub fn concat(self, iter: impl Iterator<Item = Doc<'a>>) -> Doc<'a> {
        let mut current = if let Doc::List(docs) = self {
            docs
        } else {
            vec![self]
        };
        current.extend(iter);
        Doc::List(current)
    }

    #[inline]
    /// Increase indentation level. Usually this method should be called on group
    /// or line break. Calling this on text won't take any effects.
    ///
    /// ```
    /// use tiny_pretty::{print, Doc};
    ///
    /// let doc = Doc::hard_line().nest(2);
    /// assert_eq!("\n  ", &print(&doc, &Default::default()));
    ///
    /// let doc = Doc::text("code").nest(2);
    /// assert_eq!("code", &print(&doc, &Default::default()));
    /// ```
    pub fn nest(mut self, size: usize) -> Doc<'a> {
        if let Doc::Break(_, offset) = &mut self {
            *offset += size;
            self
        } else {
            Doc::Nest(size, Rc::new(self))
        }
    }
}