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
//! Pretty-printing of generated values: how a failing test reports what it
//! drew, and how to take part in that report.
//!
//! When a test fails, Hegel replays the minimal failing example and prints
//! every drawn value as a `let` binding:
//!
//! ```text
//! let records = [Record {
//! name: "000",
//! tags: None,
//! scores: {"0": 0} }];
//! ```
//!
//! Values print the way `{:?}` shows them — the `Debug` representation every
//! Rust type already has — laid out by libhegel's layout engine so that a
//! large value wraps one element or field per line instead of running off
//! the edge of the terminal. This page explains the machinery behind that
//! report and what to do when the compiler tells you a draw is not
//! printable.
//!
//! # Printing is the generator's job
//!
//! A value often cannot print itself: there is no `Debug` for a drawn
//! closure, and the useful representation of a `HegelRandom` (the `rand`
//! integration's fake PRNG) is the sequence of values it hands out *after*
//! it is drawn. The process that constructed a value can always describe it,
//! so in Hegel printing is a capability of the generator, not the value.
//! That capability is the
//! [`PrintableGenerator`](crate::PrintableGenerator) trait: a
//! [`Generator`](crate::Generator) draws silently through `do_draw`, and a
//! `PrintableGenerator` can also draw-and-describe through
//! `do_draw_and_print`. [`TestCase::draw`](crate::TestCase::draw) accepts
//! only printable generators, so that the failure report can say what was
//! drawn; [`TestCase::draw_silent`](crate::TestCase::draw_silent) accepts
//! any generator and reports nothing.
//!
//! Most generators are printable without anyone thinking about it:
//!
//! - Every leaf generator prints: integers, floats, booleans, strings and
//! regexes, bytes, characters, dates and times, UUIDs, IP addresses,
//! emails, URLs, durations.
//! - Structural combinators print whenever their components do:
//! collections, tuples, [`optional`](crate::generators::optional),
//! [`one_of!`](crate::one_of), `filter`, `flat_map`,
//! [`recursive`](crate::generators::recursive), and the generators
//! `#[derive(DefaultGenerator)]` produces. These print as they draw,
//! element by element and field by field, so an element's own printing
//! (a [`print_with`](crate::Generator::print_with) closure, a deferred
//! `HegelRandom`) shows up inside the containing value.
//! - Value-producing combinators print whenever the produced type
//! implements `Debug`: `map`, [`just`](crate::generators::just),
//! [`sampled_from`](crate::generators::sampled_from),
//! [`boxed`](crate::Generator::boxed), and
//! [`#[hegel::composite]`](crate::composite) functions. These print the
//! finished value through [`PrettyPrinter::debug`], not the draws that
//! built it: a composite's inner draws never appear in the report, only
//! its return value.
//!
//! # When a draw is not printable
//!
//! A draw fails to compile only when a generator that prints by value
//! produces a type without a `Debug` implementation, or when a hand-written
//! [`Generator`](crate::Generator) never implemented printing. The fixes,
//! in order of preference:
//!
//! - `#[derive(Debug)]` on your own type makes every generator of it
//! printable at once.
//! - [`print_with`](crate::Generator::print_with) — print a custom
//! representation from a closure taking the value and the printer:
//! `.print_with(|value, printer| printer.text(&format!("make({})", value.id)))`.
//! Also the way to mask a secret, or to print a foreign type whose `Debug`
//! output is opaque (a tagged pointer, a bit-packed struct).
//! - [`print_as_debug`](crate::Generator::print_as_debug) — make a
//! hand-written generator of a `Debug` type printable.
//! - [`print_as_call`](crate::generators::Mapped::print_as_call) — on a
//! `map` whose input draw is printable, print the input instead of the
//! output: `.map(KeyData::from_ffi).print_as_call("KeyData::from_ffi")`
//! reports `KeyData::from_ffi(3)`.
//! - [`TestCase::draw_silent`](crate::TestCase::draw_silent) — draw without
//! reporting the value, when it isn't worth reporting.
//!
//! # Helpers and type erasure
//!
//! Printability lives in the generator's concrete type, so anything that
//! erases the type can erase printability with it — and the compile error
//! then appears at the draw sites, far from the erasing line. There are two
//! forms to watch for:
//!
//! - A helper declared `-> impl Generator<T>` is only ever a silent
//! generator to its callers, no matter what it returns — a printing
//! adapter added inside the helper changes nothing. Declare
//! generator-returning helpers `-> impl PrintableGenerator<T>`.
//! - [`Generator::boxed`](crate::Generator::boxed) keeps only value
//! printing: the boxed generator prints drawn values by their `Debug`
//! representation, so boxing preserves printability for `Debug` value
//! types but drops a printing strategy carried by the erased generator (a
//! `print_with` closure, say). To keep the generator's own printing
//! through the erasure, box with
//! [`boxed_printable`](crate::PrintableGenerator::boxed_printable)
//! instead, which exists only on generators that are already printable.
//!
//! The adapter methods come from the [`Generator`](crate::Generator) trait
//! and `boxed_printable` from [`PrintableGenerator`](crate::PrintableGenerator),
//! so both need to be in scope. `use hegel::prelude::*;` imports both (see
//! [`prelude`](crate::prelude)).
//!
//! # Draw names
//!
//! The `let records = …` name above is the binding's own name:
//! `#[hegel::test]` (and `#[state_machine]` rule bodies) rewrite
//! `let x = tc.draw(..)` so the report names the draw `x`. The rewrite only
//! sees draws written directly in that body — a draw inside a helper
//! function falls back to the anonymous `draw_1`, `draw_2`, …. Mark such a
//! helper [`#[hegel::test_helper]`](macro@crate::test_helper) to apply the
//! same rewrite to its body (names gain a per-call counter: `x_1`, `x_2`, …),
//! or name a single draw with
//! [`TestCase::draw_named`](crate::TestCase::draw_named).
//!
//! # The layout engine
//!
//! Everything above renders through a shared layout engine, which you meet
//! directly when writing a [`print_with`](crate::Generator::print_with)
//! closure or a [`PrintableGenerator`](crate::PrintableGenerator)
//! implementation.
//!
//! [`Document`] owns one pretty-printed document: its builder methods
//! choose the layout options, [`Document::printer`] exposes the surface to
//! write through, and [`Document::finish`] consumes it to render exactly
//! once at the end. In a test run the document belongs to the test case,
//! and user code only ever writes. Rendering happens after the test body
//! finishes.
//!
//! [`PrettyPrinter`] is that write surface, wrapping libhegel's layout
//! engine (an Oppen-style pretty-printer ported from Hypothesis's
//! `hypothesis.vendor.pretty`). Output is built from three primitives:
//! [`PrettyPrinter::text`] emits literal text, [`PrettyPrinter::breakable`]
//! marks a point that renders as a separator when the enclosing group fits
//! on one line and as a newline plus indentation when it does not, and
//! [`PrettyPrinter::begin_group`] / [`PrettyPrinter::end_group`] delimit
//! the groups those decisions are made over. A group either fits — every
//! breakable renders as its separator — or breaks as a whole, outermost
//! groups first. On top of those sit the conveniences most printing code
//! wants: [`PrettyPrinter::debug`] prints any `Debug` value with its
//! bracket structure recovered by libhegel's reflower, so it wraps like a
//! structurally printed one; [`PrettyPrinter::group`] and
//! [`PrettyPrinter::seq`] write a delimited group or a comma-separated
//! sequence from a closure; [`PrettyPrinter::separator`] is the `,` plus
//! break point between two items.
//!
//! Because printing happens *during* the draw, the printer is more than an
//! append-only stream: a combinator that may reject a draw (a `filter`
//! retry, a duplicate collection element) prints each attempt into a
//! speculative region ([`PrettyPrinter::speculate`]) and commits only the
//! accepted one, and cloning a printer opens a child region that later
//! (even from another thread) fills in at the point where the clone was
//! made. Hand-written implementations can use the same mechanisms.
use crate;
use Cell;
use Debug;
use PhantomData;
/// Accept a printer operation's outcome: misuse panics with libhegel's
/// diagnostic, while writing to a dead region — a straggling thread printing
/// after the document was read, or into a region whose anchor was retracted
/// — is a silent no-op, so a writer that outlives its document never brings
/// the process down.
pub
use crateinvalid_argument;
/// The line width documents are laid out to when none is configured.
pub const DEFAULT_MAX_WIDTH: u64 = 79;
/// One pretty-printed document: the owner of its layout options, its
/// content, and its rendering.
///
/// Configure the layout with the builder methods (before anything is
/// printed), write content through [`printer`](Document::printer), and
/// render by consuming the document with [`finish`](Document::finish) —
/// rendering happens exactly once, at the end. The [`PrettyPrinter`] this
/// hands out is write-only, so code that is *given* a printer (a
/// [`print_with`](crate::Generator::print_with) closure, a
/// [`PrintableGenerator`](crate::PrintableGenerator)) can never render or
/// otherwise observe the document it is contributing to.
///
/// # Example
///
/// ```
/// use hegel::Document;
///
/// let mut doc = Document::new().max_width(10);
/// let p = doc.printer();
/// p.begin_group(1, "[");
/// p.text("first");
/// p.text(",");
/// p.breakable(" ");
/// p.text("second");
/// p.end_group("]");
/// assert_eq!(doc.finish(), "[first,\n second]");
/// ```
/// The write surface of a pretty-printed document.
///
/// See the [module docs](self) for the printing model. Obtained from
/// [`Document::printer`] — or received, already positioned, by printing
/// code such as a [`print_with`](crate::Generator::print_with) closure.
/// Rejections of the layout protocol (an [`end_group`](PrettyPrinter::end_group)
/// with no open group) panic, since they indicate a bug in the calling
/// printing code.
/// Cloning a printer opens a *child region*: a hole in the document,
/// anchored at the printer's current position, that the clone writes into.
///
/// Whatever the clone prints — at any later point, from any thread that owns
/// it — appears at the anchor when the document renders, with line-breaking
/// behaving as if it had been printed inline. This is how output crosses
/// threads deterministically (each clone's output lands where the clone was
/// made, however the threads were scheduled), and how a generator whose
/// value's representation is only known during test execution (a
/// Hegel-controlled random number generator, say) prints: it clones the
/// printer at draw time and records into the clone as the value is used.
///
/// A child region dies when the document renders, or when a speculative
/// region its anchor sat inside is aborted; a dead region's writes are
/// silent no-ops, so a clone that outlives its document can keep trying to
/// record without consequence. Cloning a no-op printer yields a no-op
/// printer, and cloning into a dead region yields a printer whose writes
/// discard.
/// An open speculative region on a [`PrettyPrinter`]; see
/// [`PrettyPrinter::speculate`].
/// Dropping an uncommitted speculation — most importantly during an unwind
/// out of a speculative draw, such as a budget-exhausted `StopTest` or a
/// failed assumption mid-attempt — discards its output, so a partial attempt
/// never corrupts the document. The result is deliberately ignored: this can
/// run during a panic, where a second panic would abort the process.