deduxit 0.3.0

Logic suites, linear logic first: decides, checks, proves step by step and exports sequents of classical and intuitionistic linear logic, and ordinary propositional logic through its embeddings.
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
// deduxit © Fabian Lukas Grubmüller 2026
// Licensed under the EUPL

use super::proofs::Proof;
use super::sequents::Sequent as SequentForm;
use crate::limits::{Limits, Space};
use crate::linear::fragment::{Fragment, Mode};
use crate::linear::occurrences::{Member, OccId, Sign};
use crate::linear::search::{
    Bias, Cadence, Classical, Disproof, Engine, Equation, Jobs, OneSided, OneSidedSymbol,
    Outcome as Out, Reason, Refutation, Saturated, Stable, StateEquation, Statistics, Unbalanced,
    UnbalancedSymbol, Verdict,
};
use crate::linear::sequents::{Atom, Symbol};
use crate::wire::{self, Readable};
use serde::{Deserialize, Deserializer, Serialize, Serializer};

impl Serialize for Fragment {
    /// Serializes the fragment as its name, such as `"MALL"`.
    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        serializer.serialize_str(self.name())
    }
}

impl<'a> Deserialize<'a> for Fragment {
    /// Deserializes a fragment from its name, giving the named fragment,
    /// which contains every fragment of that name.
    fn deserialize<D: Deserializer<'a>>(deserializer: D) -> Result<Self, D::Error> {
        let name = String::deserialize(deserializer)?;
        name.parse().map_err(serde::de::Error::custom)
    }
}

impl Serialize for Mode {
    /// Serializes the mode as its name, such as `"intuitionistic"`.
    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        serializer.serialize_str(self.name())
    }
}

impl<'a> Deserialize<'a> for Mode {
    /// Deserializes a mode from its name, refusing an unknown one by
    /// naming the known ones.
    fn deserialize<D: Deserializer<'a>>(deserializer: D) -> Result<Self, D::Error> {
        let name = <std::borrow::Cow<'a, str>>::deserialize(deserializer)?;
        name.parse().map_err(serde::de::Error::custom)
    }
}

/// The serialized form of a reason: its `kind`, with the bound for the
/// copy bound and for the memory limit. A kind it does not know is no
/// reason, never one of these.
#[derive(Serialize, Deserialize)]
#[serde(tag = "kind", rename_all = "snake_case")]
pub(super) enum Why {
    /// The stop condition fired.
    Stopped,
    /// The recursion limit was reached.
    RecursionLimit {
        /// The depth the limits allowed.
        depth: u32,
    },
    /// Every level up to this copy bound hit it.
    CopyBound {
        /// The bound.
        copies: u32,
    },
    /// The search held this many bytes with its memo emptied.
    MemoryLimit {
        /// The bound.
        limit_bytes: u64,
    },
    /// A structure of the search outgrew its indices.
    IndexLimit,
    /// The work limit was reached.
    WorkLimit {
        /// The bound.
        limit: u64,
    },
    /// A proof was found whose check would hold more than the memory bound.
    Unchecked {
        /// The bound.
        limit_bytes: u64,
    },
    /// A binding would have passed the witness depth.
    WitnessDepth {
        /// The bound.
        depth: u32,
    },
    /// An instance would have passed the bound on instances.
    Instances {
        /// The bound.
        instances: u32,
    },
}

impl From<Reason> for Why {
    /// Converts a reason into its serialized form.
    fn from(r: Reason) -> Self {
        match r {
            Reason::Stopped => Why::Stopped,
            Reason::RecursionLimit { depth } => Why::RecursionLimit { depth },
            Reason::CopyBound { copies } => Why::CopyBound { copies },
            Reason::MemoryLimit { limit_bytes } => Why::MemoryLimit { limit_bytes },
            Reason::IndexLimit => Why::IndexLimit,
            Reason::WorkLimit { limit } => Why::WorkLimit { limit },
            Reason::Unchecked { limit_bytes } => Why::Unchecked { limit_bytes },
            Reason::WitnessDepth { depth } => Why::WitnessDepth { depth },
            Reason::Instances { instances } => Why::Instances { instances },
        }
    }
}

impl From<Why> for Reason {
    /// Converts a reason's serialized form back.
    fn from(w: Why) -> Self {
        match w {
            Why::Stopped => Reason::Stopped,
            Why::RecursionLimit { depth } => Reason::RecursionLimit { depth },
            Why::CopyBound { copies } => Reason::CopyBound { copies },
            Why::MemoryLimit { limit_bytes } => Reason::MemoryLimit { limit_bytes },
            Why::IndexLimit => Reason::IndexLimit,
            Why::WorkLimit { limit } => Reason::WorkLimit { limit },
            Why::Unchecked { limit_bytes } => Reason::Unchecked { limit_bytes },
            Why::WitnessDepth { depth } => Reason::WitnessDepth { depth },
            Why::Instances { instances } => Reason::Instances { instances },
        }
    }
}

impl Serialize for Reason {
    /// Serializes the reason tagged by its `kind`.
    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        Why::from(*self).serialize(serializer)
    }
}

impl<'a> Deserialize<'a> for Reason {
    /// Deserializes a reason from its `kind`, refusing one it does not
    /// know.
    fn deserialize<D: Deserializer<'a>>(deserializer: D) -> Result<Self, D::Error> {
        Why::deserialize(deserializer).map(Reason::from)
    }
}

/// A literal of an atom as a refutation names it: the atom, or its
/// negation.
#[derive(Clone, Copy, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
enum Literal {
    /// The atom `a`.
    Atom,
    /// Its negation `~a`.
    Dual,
}

impl From<Sign> for Literal {
    /// The literal of the sign.
    fn from(sign: Sign) -> Self {
        match sign {
            Sign::Atom => Literal::Atom,
            Sign::Dual => Literal::Dual,
        }
    }
}

impl From<Literal> for Sign {
    /// The sign of the literal.
    fn from(literal: Literal) -> Self {
        match literal {
            Literal::Atom => Sign::Atom,
            Literal::Dual => Sign::Dual,
        }
    }
}

/// The serialized form of a refutation: its `kind`, with the counts or
/// the weights that rule a proof out. A kind it does not know is no
/// refutation, never one of these.
#[derive(Serialize, Deserialize)]
#[serde(tag = "kind", rename_all = "snake_case")]
enum WhyNot {
    /// The search was exhaustive.
    Exhausted,
    /// An atom's literals cannot pair up.
    Unbalanced {
        /// The atom's index into the sequent's atoms.
        atom: u32,
        /// The least excess of positive over negative literals.
        least: i32,
        /// The greatest.
        most: i32,
    },
    /// An atom's literals cannot pair up, though copies may add one sign.
    OneSided {
        /// The atom's index into the sequent's atoms.
        atom: u32,
        /// The least excess outside the exponentials.
        least: i32,
        /// The greatest.
        most: i32,
        /// The literal every one of the atom below an exponential is.
        copied: Literal,
    },
    /// The count equation fails.
    Equation {
        /// The formulas.
        formulas: u64,
        /// The formulas the equation asks for.
        needed: i64,
        /// The `⊗`.
        tensors: u64,
        /// The `⅋`.
        pars: u64,
        /// The `1`.
        ones: u64,
        /// The `⊥`.
        bottoms: u64,
        /// Whether Mix was allowed.
        mix: bool,
    },
    /// The state equation of the Petri net has no solution.
    StateEquation {
        /// The atoms that weigh something, by index, with their weights.
        atoms: Vec<(u32, i64)>,
        /// The clauses used once that weigh something, by occurrence, with
        /// their weights.
        clauses: Vec<(u32, i64)>,
        /// The clauses that can never fire, by occurrence.
        dropped: Vec<u32>,
    },
    /// The classical reading is false under an assignment.
    Classical {
        /// The value of each atom, by index.
        assignment: Vec<bool>,
    },
    /// A forward search saturated.
    Saturated {
        /// The positive literal of each atom, by index.
        positive: Vec<Literal>,
        /// The sequents of the set.
        sequents: Vec<StableForm>,
    },
    /// A predicate's literals cannot pair up, all its atoms counted.
    UnbalancedSymbol {
        /// The predicate's index into the sequent's symbols.
        symbol: u32,
        /// The least excess of positive over negative literals.
        least: i32,
        /// The greatest.
        most: i32,
    },
    /// A predicate's literals cannot pair up, though copies may add one
    /// sign.
    OneSidedSymbol {
        /// The predicate's index into the sequent's symbols.
        symbol: u32,
        /// The least excess outside the exponentials.
        least: i32,
        /// The greatest.
        most: i32,
        /// The literal every one of the predicate below an exponential
        /// is.
        copied: Literal,
    },
}

/// The serialized form of a stable sequent of a saturated set: its zones
/// by occurrence, and whether it absorbs.
#[derive(Serialize, Deserialize)]
struct StableForm {
    /// The linear zone, sorted, with repeats.
    linear: Vec<u32>,
    /// The unrestricted zone, sorted.
    unrestricted: Vec<u32>,
    /// Whether a `⊤` above absorbs any further linear member.
    absorbs: bool,
}

impl From<&Refutation> for WhyNot {
    /// Converts a refutation into its serialized form.
    fn from(r: &Refutation) -> Self {
        match r {
            &Refutation::Unbalanced(Unbalanced { atom, least, most }) => WhyNot::Unbalanced {
                atom: atom.get(),
                least,
                most,
            },
            &Refutation::OneSided(OneSided {
                atom,
                least,
                most,
                copied,
            }) => WhyNot::OneSided {
                atom: atom.get(),
                least,
                most,
                copied: copied.into(),
            },
            &Refutation::Equation(Equation {
                formulas,
                needed,
                tensors,
                pars,
                ones,
                bottoms,
                mix,
            }) => WhyNot::Equation {
                formulas,
                needed,
                tensors,
                pars,
                ones,
                bottoms,
                mix,
            },
            Refutation::StateEquation(StateEquation {
                atoms,
                clauses,
                dropped,
            }) => WhyNot::StateEquation {
                atoms: atoms.iter().map(|&(a, w)| (a.get(), w)).collect(),
                clauses: clauses.iter().map(|&(o, w)| (o.get(), w)).collect(),
                dropped: dropped.iter().map(|o| o.get()).collect(),
            },
            Refutation::Classical(Classical { assignment }) => WhyNot::Classical {
                assignment: assignment.clone(),
            },
            Refutation::Saturated(Saturated { positive, sequents }) => WhyNot::Saturated {
                positive: positive.iter().map(|&sign| sign.into()).collect(),
                sequents: sequents
                    .iter()
                    .map(|s| StableForm {
                        linear: s.linear.iter().map(|o| o.get()).collect(),
                        unrestricted: s.unrestricted.iter().map(|o| o.get()).collect(),
                        absorbs: s.absorbs,
                    })
                    .collect(),
            },
            &Refutation::UnbalancedSymbol(UnbalancedSymbol {
                symbol,
                least,
                most,
            }) => WhyNot::UnbalancedSymbol {
                symbol: symbol.get(),
                least,
                most,
            },
            &Refutation::OneSidedSymbol(OneSidedSymbol {
                symbol,
                least,
                most,
                copied,
            }) => WhyNot::OneSidedSymbol {
                symbol: symbol.get(),
                least,
                most,
                copied: copied.into(),
            },
            Refutation::Exhausted => WhyNot::Exhausted,
        }
    }
}

impl From<WhyNot> for Refutation {
    /// Converts a refutation's serialized form back; its indices are the
    /// disproof's to check against its sequent.
    fn from(w: WhyNot) -> Self {
        match w {
            WhyNot::Exhausted => Refutation::Exhausted,
            WhyNot::Unbalanced { atom, least, most } => Refutation::Unbalanced(Unbalanced {
                atom: Atom::new(atom),
                least,
                most,
            }),
            WhyNot::OneSided {
                atom,
                least,
                most,
                copied,
            } => Refutation::OneSided(OneSided {
                atom: Atom::new(atom),
                least,
                most,
                copied: copied.into(),
            }),
            WhyNot::Equation {
                formulas,
                needed,
                tensors,
                pars,
                ones,
                bottoms,
                mix,
            } => Refutation::Equation(Equation {
                formulas,
                needed,
                tensors,
                pars,
                ones,
                bottoms,
                mix,
            }),
            WhyNot::StateEquation {
                atoms,
                clauses,
                dropped,
            } => Refutation::StateEquation(StateEquation {
                atoms: atoms.into_iter().map(|(a, w)| (Atom::new(a), w)).collect(),
                clauses: clauses
                    .into_iter()
                    .map(|(o, w)| (OccId::new(o), w))
                    .collect(),
                dropped: dropped.into_iter().map(OccId::new).collect(),
            }),
            WhyNot::Classical { assignment } => Refutation::Classical(Classical { assignment }),
            WhyNot::UnbalancedSymbol {
                symbol,
                least,
                most,
            } => Refutation::UnbalancedSymbol(UnbalancedSymbol {
                symbol: Symbol::new(symbol),
                least,
                most,
            }),
            WhyNot::OneSidedSymbol {
                symbol,
                least,
                most,
                copied,
            } => Refutation::OneSidedSymbol(OneSidedSymbol {
                symbol: Symbol::new(symbol),
                least,
                most,
                copied: copied.into(),
            }),
            WhyNot::Saturated { positive, sequents } => Refutation::Saturated(Saturated::new(
                positive.into_iter().map(Sign::from).collect(),
                sequents
                    .into_iter()
                    .map(|s| {
                        Stable::new(
                            s.linear.into_iter().map(OccId::new).collect(),
                            s.unrestricted.into_iter().map(OccId::new).collect(),
                            s.absorbs,
                        )
                    })
                    .collect(),
            )),
        }
    }
}

impl Serialize for Refutation {
    /// Serializes the refutation tagged by its `kind`.
    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        WhyNot::from(self).serialize(serializer)
    }
}

impl<'a> Deserialize<'a> for Refutation {
    /// Deserializes a refutation from its `kind`, refusing one it does not
    /// know.
    fn deserialize<D: Deserializer<'a>>(deserializer: D) -> Result<Self, D::Error> {
        WhyNot::deserialize(deserializer).map(Refutation::from)
    }
}

/// The serialized form of a disproof: its level at the top of a
/// document, the sequent, the mode, the refutation and the goal where it
/// is not the roots. An unprovable outcome holds the same keys, so it
/// reads back as its disproof.
#[derive(Serialize, Deserialize)]
struct DisproofForm {
    /// The wire level, written only at the top of a document.
    #[serde(
        default,
        skip_serializing_if = "Option::is_none",
        deserialize_with = "wire::version"
    )]
    version: Option<u32>,
    /// The sequent.
    sequent: SequentForm,
    /// The mode it is refuted in.
    mode: Mode,
    /// Why it is unprovable.
    refutation: WhyNot,
    /// The goal refuted, absent for the roots.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    goal: Option<Vec<u32>>,
}

impl DisproofForm {
    /// Rebuilds the disproof the form holds, its sequent within `limits`,
    /// every atom and occurrence it names checked against the sequent; the
    /// refutation itself is not checked.
    fn within(self, limits: &Limits) -> Result<Disproof, crate::Error> {
        let sequent = self.sequent.within(limits)?;
        let atoms = sequent.atom_names().len();
        let occurrences = usize::try_from(sequent.occurrences()).unwrap_or(usize::MAX);
        let atom = |atom: Atom| match atom.index() {
            index if index < atoms => Ok(()),
            index => Err(crate::Error::IndexOutOfBounds {
                space: Space::Atom,
                index,
                len: atoms,
            }),
        };
        let symbols = sequent.symbols().len();
        let symbol = |symbol: Symbol| match symbol.index() {
            index if index < symbols => Ok(()),
            index => Err(crate::Error::IndexOutOfBounds {
                space: Space::Symbol,
                index,
                len: symbols,
            }),
        };
        let occurrence = |index: usize| match index {
            index if index < occurrences => Ok(()),
            index => Err(crate::Error::IndexOutOfBounds {
                space: Space::Occurrence,
                index,
                len: occurrences,
            }),
        };
        let refutation = Refutation::from(self.refutation);
        match &refutation {
            Refutation::Unbalanced(unbalanced) => atom(unbalanced.atom)?,
            Refutation::OneSided(one_sided) => atom(one_sided.atom)?,
            Refutation::UnbalancedSymbol(unbalanced) => symbol(unbalanced.symbol)?,
            Refutation::OneSidedSymbol(one_sided) => symbol(one_sided.symbol)?,
            Refutation::StateEquation(equation) => {
                for &(a, _) in &equation.atoms {
                    atom(a)?;
                }
                for &(o, _) in &equation.clauses {
                    occurrence(o.index())?;
                }
                for o in &equation.dropped {
                    occurrence(o.index())?;
                }
            }
            Refutation::Saturated(saturated) => {
                for s in &saturated.sequents {
                    for o in s.linear.iter().chain(&s.unrestricted) {
                        occurrence(o.index())?;
                    }
                }
            }
            Refutation::Exhausted | Refutation::Equation(_) | Refutation::Classical(_) => {}
        }
        let disproof = Disproof::new(sequent, self.mode, refutation);
        Ok(match self.goal {
            None => disproof,
            Some(goal) => {
                for &m in &goal {
                    occurrence(m as usize)?;
                }
                disproof.of_goal(goal.into_iter().map(Member::new).collect())
            }
        })
    }
}

impl Serialize for Disproof {
    /// Serializes the disproof as a document.
    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        DisproofForm {
            version: Some(
                wire::level_of(self.refutation(), self.mode())
                    .max(wire::level_of_sequent(self.sequent())),
            ),
            sequent: SequentForm::from(self.sequent()),
            mode: self.mode(),
            refutation: WhyNot::from(self.refutation()),
            goal: self
                .goal()
                .map(|goal| goal.iter().map(|m| m.get()).collect()),
        }
        .serialize(serializer)
    }
}

impl<'a> Deserialize<'a> for Disproof {
    /// Deserializes a disproof within the default limits, as
    /// [`wire::upgrade`] does.
    fn deserialize<D: Deserializer<'a>>(deserializer: D) -> Result<Self, D::Error> {
        Self::read(deserializer, &Limits::default())
    }
}

impl crate::sealed::Readable for Disproof {}

impl Readable for Disproof {
    const FORM: &'static str = "disproof";

    /// Reads a disproof: rebuilds its sequent within the limits and checks
    /// every index of its refutation and goal, not the refutation.
    fn read<'de, D: Deserializer<'de>>(deserializer: D, limits: &Limits) -> Result<Self, D::Error> {
        DisproofForm::deserialize(deserializer)?
            .within(limits)
            .map_err(wire::fail)
    }
}

/// The keys an unprovable outcome adds for its disproof beside its
/// `mode` and `refutation`: the sequent, and the goal when it is not the
/// roots.
#[derive(Serialize)]
struct DisproofKeys<'a> {
    /// The sequent.
    sequent: SequentForm,
    /// The goal refuted, absent for the roots.
    #[serde(skip_serializing_if = "Option::is_none")]
    goal: Option<&'a [Member]>,
}

/// The serialized form of an outcome: the verdict as a word, the reason for
/// `unknown`, how the search ran, and for `proved` the proof's sequent and
/// nodes as keys of the outcome itself, so that the outcome reads as a
/// proof file too.
#[derive(Serialize)]
struct Outcome<'a> {
    /// The wire level.
    version: u32,
    /// The crate's version, which wrote the outcome.
    deduxit: &'static str,
    /// `proved`, `unprovable` or `unknown`.
    verdict: &'static str,
    /// Whether the proof passed the checker, for `proved`.
    #[serde(skip_serializing_if = "Option::is_none")]
    checked: Option<bool>,
    /// Why the search could not decide.
    #[serde(skip_serializing_if = "Option::is_none")]
    reason: Option<Why>,
    /// Why the sequent is unprovable.
    #[serde(skip_serializing_if = "Option::is_none")]
    refutation: Option<WhyNot>,
    /// The fragment searched in, by its name in the mode.
    fragment: &'static str,
    /// The mode searched in.
    mode: Mode,
    /// The engine that ran.
    engine: Engine,
    /// What the search cost.
    statistics: Statistics,
    /// The proof, for `proved`.
    #[serde(flatten)]
    proof: Option<Proof>,
    /// What the disproof adds, for `unprovable`.
    #[serde(flatten)]
    disproof: Option<DisproofKeys<'a>>,
}

impl Serialize for Out {
    /// Serializes the outcome as its verdict, the fragment, mode and engine
    /// of the search, the statistics, and the proof if there is one.
    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        let verdict = self.verdict.name();
        let (reason, refutation, proof, disproof) = match &self.verdict {
            Verdict::Proved(p) => (None, None, Some(Proof::keys(p)), None),
            Verdict::Unprovable(d) => {
                let keys = DisproofKeys {
                    sequent: SequentForm::from(d.sequent()),
                    goal: d.goal(),
                };
                let why = WhyNot::from(d.refutation());
                (None, Some(why), None, Some(keys))
            }
            Verdict::Unknown(r) => (Some(Why::from(*r)), None, None, None),
        };
        let version = match &self.verdict {
            Verdict::Unprovable(d) => {
                wire::level_of(d.refutation(), self.mode).max(wire::level_of_sequent(d.sequent()))
            }
            Verdict::Proved(p) => {
                wire::level_in(Some(self.mode)).max(wire::level_of_sequent(p.sequent()))
            }
            Verdict::Unknown(_) => wire::level_in(Some(self.mode)),
        };
        Outcome {
            version,
            deduxit: env!("CARGO_PKG_VERSION"),
            verdict,
            checked: proof.as_ref().map(|_| self.checked),
            reason,
            refutation,
            fragment: self.fragment.name_in(self.mode),
            mode: self.mode,
            engine: self.engine,
            statistics: self.statistics,
            proof,
            disproof,
        }
        .serialize(serializer)
    }
}

impl Serialize for Engine {
    /// Serializes the engine as its name, such as `"focus"`.
    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        serializer.collect_str(self)
    }
}

impl<'a> Deserialize<'a> for Engine {
    /// Deserializes an engine from its name.
    fn deserialize<D: Deserializer<'a>>(deserializer: D) -> Result<Self, D::Error> {
        String::deserialize(deserializer)?
            .parse()
            .map_err(serde::de::Error::custom)
    }
}

impl Serialize for Bias {
    /// Serializes the rule as its name, such as `"rarer"`.
    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        serializer.collect_str(self)
    }
}

impl<'a> Deserialize<'a> for Bias {
    /// Deserializes a rule from its name.
    fn deserialize<D: Deserializer<'a>>(deserializer: D) -> Result<Self, D::Error> {
        String::deserialize(deserializer)?
            .parse()
            .map_err(serde::de::Error::custom)
    }
}

/// A value written `"auto"` or as a number.
#[derive(Serialize, Deserialize)]
#[serde(untagged)]
enum AutoOrNumber {
    /// A number.
    Number(u64),
    /// A word, of which `"auto"` is the one read.
    Word(String),
}

impl AutoOrNumber {
    /// Returns the number, or `None` for `"auto"`, or the error for any
    /// other word.
    fn number<E: serde::de::Error>(self) -> Result<Option<u64>, E> {
        match self {
            Self::Number(n) => Ok(Some(n)),
            Self::Word(word) if word == "auto" => Ok(None),
            Self::Word(word) => Err(E::custom(format!(
                "expected a number or \"auto\", found {word:?}"
            ))),
        }
    }
}

impl Serialize for Jobs {
    /// Serializes the threads as `"auto"` or their number.
    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        match self {
            Self::Auto => serializer.serialize_str("auto"),
            Self::Count(n) => serializer.serialize_u64(u64::try_from(*n).unwrap_or(u64::MAX)),
        }
    }
}

impl<'a> Deserialize<'a> for Jobs {
    /// Deserializes the threads from `"auto"` or a number.
    fn deserialize<D: Deserializer<'a>>(deserializer: D) -> Result<Self, D::Error> {
        Ok(match AutoOrNumber::deserialize(deserializer)?.number()? {
            None => Self::Auto,
            Some(n) => Self::Count(usize::try_from(n).unwrap_or(usize::MAX)),
        })
    }
}

impl Serialize for Cadence {
    /// Serializes the cadence as `"auto"` or the number of links.
    fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        match self {
            Self::Auto => serializer.serialize_str("auto"),
            Self::Every(n) => serializer.serialize_u32(*n),
        }
    }
}

impl<'a> Deserialize<'a> for Cadence {
    /// Deserializes the cadence from `"auto"` or a number of links.
    fn deserialize<D: Deserializer<'a>>(deserializer: D) -> Result<Self, D::Error> {
        Ok(match AutoOrNumber::deserialize(deserializer)?.number()? {
            None => Self::Auto,
            Some(n) => Self::Every(u32::try_from(n).map_err(serde::de::Error::custom)?),
        })
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    /// Every reason reads back as itself, and a kind no reason has is
    /// refused.
    #[test]
    fn reasons_read_back() {
        for reason in [
            Reason::Stopped,
            Reason::RecursionLimit { depth: 2048 },
            Reason::CopyBound { copies: 3 },
            Reason::MemoryLimit {
                limit_bytes: 1 << 30,
            },
            Reason::IndexLimit,
            Reason::WorkLimit { limit: 1 << 20 },
            Reason::Unchecked {
                limit_bytes: 1 << 30,
            },
            Reason::WitnessDepth { depth: 64 },
            Reason::Instances { instances: 1 << 16 },
        ] {
            let json = serde_json::to_string(&reason).unwrap();
            assert_eq!(
                serde_json::from_str::<Reason>(&json).unwrap(),
                reason,
                "{json}"
            );
        }
        assert_eq!(
            serde_json::to_string(&Reason::CopyBound { copies: 3 }).unwrap(),
            r#"{"kind":"copy_bound","copies":3}"#
        );
        let unknown = serde_json::from_str::<Reason>(r#"{"kind":"tired"}"#);
        assert!(
            unknown
                .unwrap_err()
                .to_string()
                .contains("unknown variant `tired`")
        );
    }

    /// Every refutation reads back as itself, and a kind no refutation
    /// has is refused, never read as `exhausted`.
    #[test]
    fn refutations_read_back() {
        let (a, o) = (Atom::new, OccId::new);
        for refutation in [
            Refutation::Exhausted,
            Refutation::Unbalanced(Unbalanced {
                atom: a(1),
                least: 1,
                most: 2,
            }),
            Refutation::OneSided(OneSided {
                atom: a(0),
                least: -2,
                most: -1,
                copied: Sign::Dual,
            }),
            Refutation::Equation(Equation {
                formulas: 2,
                needed: 3,
                tensors: 1,
                pars: 0,
                ones: 0,
                bottoms: 0,
                mix: false,
            }),
            Refutation::StateEquation(StateEquation {
                atoms: vec![(a(0), 2), (a(2), -1)],
                clauses: vec![(o(3), 1)],
                dropped: vec![o(5)],
            }),
            Refutation::Saturated(Saturated::new(
                vec![Sign::Atom, Sign::Dual],
                vec![
                    Stable::new(vec![o(1), o(1), o(4)], vec![o(2)], false),
                    Stable::new(Vec::new(), Vec::new(), true),
                ],
            )),
        ] {
            let json = serde_json::to_string(&refutation).unwrap();
            let back = serde_json::from_str::<Refutation>(&json).unwrap();
            assert_eq!(back, refutation, "{json}");
        }
        let unknown = serde_json::from_str::<Refutation>(r#"{"kind":"tableau"}"#);
        let message = unknown.unwrap_err().to_string();
        assert!(message.contains("unknown variant `tableau`"), "{message}");
    }
}