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
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
// deduxit © Fabian Lukas Grubmüller 2026
// Licensed under the EUPL

//! Rocq: a derivation as a certificate for one of two kernels
//! ([`Kernel`]): a proof script that the NanoYalla kernel checks, version
//! [`NANOYALLA`], the kernel of Click & coLLecT, or a proof term that
//! deduxit's own Rocq library checks ([`DEDUXIT`]). Where the options name
//! no kernel, the derivation's mode chooses: classical linear logic goes
//! to NanoYalla, Mix, affine and intuitionistic logic to deduxit's
//! library, which states each in its own calculus; so does a sequent with
//! a quantifier, which the library's first-order development states and
//! NanoYalla's formulas cannot.
//!
//! For NanoYalla the script is a
//! `Lemma` whose statement is the sequent as a list of the kernel's
//! formulas, `ll [dual A; tens A (dual B); B]`, over the atoms as
//! variables of type `formula`, and whose proof applies one derived rule
//! of the kernel's `macroll` module per inference, conclusion first:
//! `tens_r_ext`, `parr_r_ext`, `oc_r_ext`, `co_r_ext` and so on, the
//! axiom as `ax_expansion`. `Qed` closes it, so Rocq accepts the file only
//! if the kernel accepts the proof.
//!
//! The kernel's sequents are lists and its rules act on a formula at a
//! given position, so the script keeps the list of every goal: the lemma
//! states the conclusion in occurrence order, each rule takes the prefix
//! before its principal formula, and a `⊗` alone, whose left premise must
//! hold what precedes the `⊗` and whose right premise what follows it,
//! gets an exchange `ex_perm_r` before it when the goal is not already in
//! that order.
//!
//! The NanoYalla certificate is one of classical linear logic: a
//! two-sided derivation is exported as the one-sided derivation behind it
//! (the one-sided [`Rule`] of every [`Named`](crate::linear::proofs::Named) rule), which proves the same
//! sequent read one-sided.
//! Mix, the weakening of affine mode, a cut and an open goal have no rule
//! in the kernel, and a derivation with one is refused ([`Unsupported`]). A
//! fragment is the lemma alone, for a file that imports `macroll`; a
//! standalone file starts with [`Options::prelude`].
//!
//! For deduxit's library the certificate is a lemma stating the sequent
//! over the library's own calculus, `ll` one-sided with the rules the
//! mode allows or `ill` two-sided for a two-sided derivation, with cut
//! where the derivation uses one, proved by
//! the library's soundness theorem applied to the derivation as a proof
//! term, which Rocq's `vm_compute` checks: atoms are strings, every rule
//! has a term, and nothing is refused but an open goal and a compact run.
//!
//! An atom's name becomes a Rocq identifier: letters, digits, `_` and `'`
//! stay, any other character becomes its code point in hexadecimal between
//! underscores, a leading digit or `'` gets an underscore before it, and a
//! name that would clash with a keyword, a name of the kernel, the lemma's
//! name or another atom gets `'` appended until it is free.
//!
//! Needs the cargo feature `rocq` (on by default).
//!
//! # Examples
//!
#![cfg_attr(feature = "parse", doc = "```")]
#![cfg_attr(not(feature = "parse"), doc = "```ignore")]
//! use deduxit::export::rocq::{self, Options};
//! use deduxit::linear::{Mode, Options as Search, Sequent, Verdict, prove};
//!
//! let sequent: Sequent = "A, A -o B |- B".parse()?;
//! let outcome = prove(&sequent, Mode::CLASSICAL, &Search::default())?;
//! let Verdict::Proved(proof) = &outcome.verdict else {
//!     panic!("provable");
//! };
//! let mut written = String::new();
//! rocq::write(&proof.derivation()?, &Options::default(), &mut written, |_| false)?;
//! assert_eq!(
//!     written,
//!     "Lemma certificate (A B : formula) : ll [dual A; tens A (dual B); B].
//! Proof.
//! apply (tens_r_ext [dual A]); cbn_sequent.
//! {
//!   ax_expansion.
//! }
//! {
//!   ax_expansion.
//! }
//! Qed."
//! );
//! # Ok::<(), Box<dyn std::error::Error>>(())
//! ```

use super::notation::{Step, flush, walk};
use super::{Drawable, Form};
use crate::hash::{HashMap, HashSet};
use crate::linear::occurrences::{Forest, OccId};
use crate::linear::proofs::{Derivation, InfId, Rule};
use crate::linear::sequents::{Sequent, Stop, Stops, Term, TermId};
use crate::{Error, linear::Mode};
use std::fmt::Write;
use thiserror::Error;

mod deduxit;

/// The version of NanoYalla the scripts are written for: the `nanoyalla`
/// directory of Click & coLLecT, whose `macroll` module defines the
/// derived rules the scripts apply. It builds on Rocq 9 with the standard
/// library, without Yalla.
pub const NANOYALLA: &str = "1.1.3";

/// What a user may vary in a certificate.
#[non_exhaustive]
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serialize", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "serialize", serde(default, deny_unknown_fields))]
pub struct Options {
    /// The lemma alone, or a whole file that starts with the prelude.
    pub form: Form,
    /// The name of the lemma.
    pub lemma: Identifier,
    /// The lines a standalone file starts with, before the lemma, or
    /// `None` for the target's own: the import of NanoYalla's `macroll`
    /// for a linear certificate ([`NANOYALLA_PRELUDE`]), of deduxit's
    /// library for one of its kernel ([`DEDUXIT_PRELUDE`],
    /// [`DEDUXIT_TWO_SIDED_PRELUDE`], and for a sequent with a quantifier
    /// [`DEDUXIT_FIRST_ORDER_PRELUDE`] and
    /// [`DEDUXIT_FIRST_ORDER_TWO_SIDED_PRELUDE`]), of the standard library's excluded
    /// middle for a classical one over `Prop` ([`CLASSICAL_PRELUDE`]),
    /// nothing for one of LJ.
    pub prelude: Option<String>,
    /// The kernel a linear certificate is written for, or `None` for the
    /// one the derivation's mode chooses: NanoYalla for classical linear
    /// logic, deduxit's library for Mix, affine and intuitionistic logic
    /// and for a sequent with a quantifier.
    /// A certificate of ordinary logic needs no kernel and ignores it.
    pub kernel: Option<Kernel>,
}

impl Default for Options {
    /// Returns the lemma `certificate` alone, and each target's own
    /// prelude for a whole file.
    fn default() -> Self {
        Self {
            form: Form::Fragment,
            lemma: Identifier::new("certificate").expect("an identifier"),
            prelude: None,
            kernel: None,
        }
    }
}

impl Options {
    /// Returns the options with the form given.
    #[must_use]
    pub fn with_form(self, form: Form) -> Self {
        Self { form, ..self }
    }

    /// Returns the options with the lemma given.
    #[must_use]
    pub fn with_lemma(self, lemma: Identifier) -> Self {
        Self { lemma, ..self }
    }

    /// Returns the options with the prelude given, `None` for each
    /// target's own.
    #[must_use]
    pub fn with_prelude(self, prelude: Option<String>) -> Self {
        Self { prelude, ..self }
    }

    /// Returns the options with the kernel given, `None` for the one the
    /// mode chooses.
    #[must_use]
    pub fn with_kernel(self, kernel: Option<Kernel>) -> Self {
        Self { kernel, ..self }
    }
}

/// The Rocq kernel a certificate of linear logic is written for.
#[non_exhaustive]
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[cfg_attr(feature = "serialize", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "serialize", serde(rename_all = "lowercase"))]
pub enum Kernel {
    /// NanoYalla [`NANOYALLA`], the kernel of Click & coLLecT: classical
    /// linear logic one-sided, without Mix, cut or the weakening of
    /// affine mode, checked rule by rule by a proof script.
    NanoYalla,
    /// deduxit's own Rocq library [`DEDUXIT`]: one-sided linear logic with
    /// Mix and weakening where the mode allows them, and two-sided
    /// intuitionistic linear logic and its affine variant, each with cut
    /// where the proof uses one, checked by the library's checker on a
    /// proof term. Read from `"linlog"` too, its name up to 0.2.0.
    #[cfg_attr(feature = "serialize", serde(alias = "linlog"))]
    Deduxit,
}

/// The version of deduxit's Rocq library the certificates of its kernel
/// are written for: the package `rocq-deduxit` of the repository
/// <https://github.com/deduxit/rocq-deduxit>, logical root `Deduxit`, its
/// linear logic under `Deduxit.Linear`, built with Rocq 9 and its standard
/// library.
pub const DEDUXIT: &str = "0.3.0";

/// The prelude of a one-sided certificate for deduxit's library: the
/// imports of its soundness theorems, of lists and of strings, whose
/// notations the lemma uses.
pub const DEDUXIT_PRELUDE: &str = "From Stdlib Require Import List String.
From Deduxit.Linear Require Import Soundness.
Import ListNotations.
Open Scope string_scope.";

/// The prelude of a two-sided certificate for deduxit's library: as
/// [`DEDUXIT_PRELUDE`], with the two-sided calculus and its theorem.
pub const DEDUXIT_TWO_SIDED_PRELUDE: &str = "From Stdlib Require Import List String.
From Deduxit.Linear Require Import IntuitionisticCheck.
Import ListNotations.
Open Scope string_scope.";

/// The prelude of a certificate of a first-order derivation for deduxit's
/// library: as [`DEDUXIT_PRELUDE`], with the first-order calculus and its
/// theorems, and the propositional calculus's module, whose optional
/// rules the statement names.
pub const DEDUXIT_FIRST_ORDER_PRELUDE: &str = "From Stdlib Require Import List String.
From Deduxit.Linear Require Calculus.
From Deduxit.Linear Require Import FirstOrderSoundness.
Import ListNotations.
Open Scope string_scope.";

/// The prelude of a two-sided certificate of a first-order derivation for
/// deduxit's library: as [`DEDUXIT_FIRST_ORDER_PRELUDE`], with the two-sided
/// calculus and its theorem.
pub const DEDUXIT_FIRST_ORDER_TWO_SIDED_PRELUDE: &str = "From Stdlib Require Import List String.
From Deduxit.Linear Require Intuitionistic.
From Deduxit.Linear Require Import FirstOrderIntuitionisticCheck.
Import ListNotations.
Open Scope string_scope.";

/// The prelude of a certificate of non-derivability for deduxit's library:
/// the imports of its refutation theorems (`Weights`, which exports the
/// others), of lists, strings and integers, whose notations the lemma uses.
pub const DEDUXIT_REFUTATION_PRELUDE: &str = "From Stdlib Require Import List String ZArith.
From Deduxit.Linear Require Import Weights.
Import ListNotations.
Open Scope string_scope.";

/// The prelude of a certificate of non-derivability of a sequent with a
/// quantifier for deduxit's library: as [`DEDUXIT_REFUTATION_PRELUDE`], with
/// the first-order calculi, the first-order weighted count, Booleans and
/// the modules whose names the statement and the weights use.
pub const DEDUXIT_FIRST_ORDER_REFUTATION_PRELUDE: &str =
    "From Stdlib Require Import Bool List String ZArith.
From Deduxit.Linear Require Calculus Intuitionistic TermsCheck.
From Deduxit.Linear Require Import FirstOrderCalculus FirstOrderIntuitionistic FirstOrderWeights.
Import ListNotations.
Open Scope string_scope.";

/// The prelude of a linear certificate: the import of NanoYalla's
/// `macroll`, which brings the kernel's `ll`, its formulas and its derived
/// rules into scope.
pub const NANOYALLA_PRELUDE: &str = "From NanoYalla Require Import macroll.";

/// The prelude of a classical certificate over `Prop`: the import of the
/// standard library's excluded middle, for `NNPP`.
pub const CLASSICAL_PRELUDE: &str = "From Stdlib Require Import Classical_Prop.";

/// A Rocq identifier, which a lemma's name must be: an ASCII letter or
/// `_` and then letters, digits, `_` and `'`, and no keyword of Rocq.
/// The names a kernel uses are its writer's to avoid, so a name stays an
/// identifier whatever kernel a later release adds.
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub struct Identifier(Box<str>);

impl Identifier {
    /// Returns the identifier `name` is.
    ///
    /// # Errors
    ///
    /// [`Error::InvalidOption`] for a name that is no identifier or a
    /// keyword.
    pub fn new(name: &str) -> Result<Self, Error> {
        let mut chars = name.chars();
        let lexical = chars
            .next()
            .is_some_and(|c| c.is_ascii_alphabetic() || c == '_')
            && chars.all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '\'');
        let why = if !lexical {
            "is no Rocq identifier: an ASCII letter or _, then letters, digits, _ and '"
        } else if KEYWORDS.contains(&name) {
            "is a keyword of Rocq"
        } else {
            return Ok(Self(name.into()));
        };
        Err(Error::InvalidOption {
            key: "rocq.lemma",
            message: format!("`{name}` {why}"),
        })
    }

    /// Returns the identifier's text.
    pub fn as_str(&self) -> &str {
        &self.0
    }
}

impl std::str::FromStr for Identifier {
    type Err = Error;

    /// Reads an identifier as [`new`](Self::new) does.
    fn from_str(name: &str) -> Result<Self, Error> {
        Self::new(name)
    }
}

impl std::fmt::Display for Identifier {
    /// Writes the identifier.
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(&self.0)
    }
}

#[cfg(feature = "serialize")]
impl serde::Serialize for Identifier {
    /// Serializes the identifier as its text.
    fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
        serializer.serialize_str(&self.0)
    }
}

#[cfg(feature = "serialize")]
impl<'a> serde::Deserialize<'a> for Identifier {
    /// Deserializes an identifier from its text, refusing what
    /// [`new`](Self::new) refuses.
    fn deserialize<D: serde::Deserializer<'a>>(deserializer: D) -> Result<Self, D::Error> {
        let name = <std::borrow::Cow<'a, str>>::deserialize(deserializer)?;
        Self::new(&name).map_err(serde::de::Error::custom)
    }
}

/// Why a derivation has no certificate: it uses a rule the kernel lacks.
#[non_exhaustive]
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Error)]
#[cfg_attr(
    feature = "serialize",
    derive(serde::Serialize),
    serde(rename_all = "snake_case")
)]
pub enum Unsupported {
    /// The derivation has an open goal: it is a proof in progress.
    #[error("the proof is not finished: an open goal has no certificate")]
    Open,
    /// The derivation uses Mix.
    #[error("NanoYalla has no Mix rule, so a proof with Mix has no certificate")]
    Mix,
    /// The derivation uses a cut, which NanoYalla's kernel has as an
    /// axiom or as a theorem of the Yalla library only.
    #[error(
        "NanoYalla's kernel has no cut rule, so a proof with a cut has its certificate in deduxit's library"
    )]
    Cut,
    /// The derivation weakens a formula that is not a `?` formula.
    #[error(
        "NanoYalla weakens ? formulas only, so a proof with the weakening of affine mode has no certificate"
    )]
    AffineWeakening,
    /// The derivation draws a run of a structural rule as one inference,
    /// which names none of the formulas after the first.
    #[error(
        "a compact derivation names one formula of a run of structural rules, so it has no certificate: build the derivation with every rule"
    )]
    Compact,
    /// A disproof was to be written for NanoYalla, which states
    /// derivations only.
    #[error(
        "NanoYalla's kernel states derivations only, so a refutation has its certificate in deduxit's library"
    )]
    Disproof,
    /// The refutation of an ordinary sequent's image is no assignment that
    /// falsifies the sequent read classically.
    #[error(
        "only a classical assignment that falsifies the sequent certifies that it is not valid, and its image's refutation is none"
    )]
    NotValid,
    /// The derivation or disproof is of an ordered mode, which neither
    /// kernel's calculi have: their sequents are commutative.
    #[error(
        "the Rocq calculi are commutative, so a derivation or a disproof of the cyclic mode has no certificate"
    )]
    Ordered,
    /// The disproof's refutation is a saturated set, which the library's
    /// calculi have no theorem for: its certificate is the set itself,
    /// which the disproof's check verifies.
    #[error(
        "deduxit's library has no theorem for a saturated set, so a refutation by one has no certificate in Rocq"
    )]
    Saturated,
    /// The sequent has a quantifier, which NanoYalla's kernel and the
    /// library's theorem of the count equation lack.
    #[error(
        "NanoYalla's kernel and deduxit's theorem of the count equation have no quantifiers, so a sequent with ∀ or ∃ has a certificate for deduxit's library only, and no refutation by the count equation"
    )]
    Quantifiers,
    /// The disproof's refutation is an exhausted search, which no
    /// invariant states: only the search that was exhaustive rules the
    /// proofs out.
    #[error(
        "an exhausted search states no invariant, so only the search rules the proofs out and Rocq has nothing to check"
    )]
    Exhausted,
}

/// Rocq's keywords, which no atom and no lemma may take.
pub(crate) const KEYWORDS: &[&str] = &[
    "_",
    "Axiom",
    "CoFixpoint",
    "Definition",
    "Fixpoint",
    "Hypothesis",
    "IF",
    "Lemma",
    "Parameter",
    "Proof",
    "Prop",
    "Qed",
    "SProp",
    "Set",
    "Theorem",
    "Type",
    "Variable",
    "as",
    "at",
    "by",
    "cofix",
    "discriminated",
    "else",
    "end",
    "exists",
    "exists2",
    "fix",
    "for",
    "forall",
    "fun",
    "if",
    "in",
    "lazymatch",
    "let",
    "match",
    "multimatch",
    "return",
    "then",
    "using",
    "where",
    "with",
];

/// The names of the kernel a script uses, which no atom may take.
const KERNEL: &[&str] = &[
    "Atom",
    "app",
    "aplus",
    "apply",
    "awith",
    "ax_expansion",
    "ax_r_ext",
    "bidual",
    "bot",
    "bot_r_ext",
    "cbn_sequent",
    "co_r_ext",
    "cons",
    "covar",
    "de_r_ext",
    "dual",
    "ex_perm_r",
    "ex_transpL",
    "formula",
    "list",
    "ll",
    "map",
    "nat",
    "nil",
    "O",
    "oc",
    "oc_r_ext",
    "one",
    "one_r_ext",
    "parr",
    "parr_r_ext",
    "permL_of_perm",
    "plus_r1_ext",
    "plus_r2_ext",
    "S",
    "tens",
    "tens_r_ext",
    "top",
    "top_r_ext",
    "var",
    "with_r_ext",
    "wk_r_ext",
    "wn",
    "zero",
];

/// Returns an atom's name as a Rocq identifier, before the check for
/// clashes.
fn identifier(name: &str) -> String {
    let mut out = String::with_capacity(name.len());
    if name.starts_with(|c: char| c.is_ascii_digit() || c == '\'') {
        out.push('_');
    }
    for c in name.chars() {
        if c.is_ascii_alphanumeric() || c == '_' || c == '\'' {
            out.push(c);
        } else {
            write!(out, "_{:x}_", c as u32).unwrap();
        }
    }
    if out.is_empty() {
        out.push('_');
    }
    out
}

/// Returns the identifiers of atoms with these names, in their order,
/// each free of clashes with the keywords, the kernel, `lemma` and the
/// others: the first clash of an identifier gets `'` appended, the later
/// ones `'2`, `'3` and so on.
pub(crate) fn identifiers(atoms: &[String], lemma: &str) -> Vec<String> {
    let mut names: Vec<String> = Vec::with_capacity(atoms.len());
    // The names taken so far, so that a clash costs a lookup: comparing
    // with every earlier name was quadratic in the atoms, seconds before
    // the first poll on a dictionary of a hundred thousand.
    let mut taken: HashSet<String> = HashSet::default();
    // Per identifier, the suffixes given to its clashes so far: names
    // that all map to one identifier (`ä` and `_e4_`) each took a prime
    // more than the last, quadratic in their number.
    let mut clashes: HashMap<String, u32> = HashMap::default();
    for name in atoms {
        let base = identifier(name);
        let free = |id: &str, taken: &HashSet<String>| {
            !KEYWORDS.contains(&id) && !KERNEL.contains(&id) && id != lemma && !taken.contains(id)
        };
        let mut id = base.clone();
        if !free(&id, &taken) {
            let suffix = clashes.entry(base.clone()).or_insert(0);
            loop {
                *suffix += 1;
                id = match *suffix {
                    1 => format!("{base}'"),
                    n => format!("{base}'{n}"),
                };
                if free(&id, &taken) {
                    break;
                }
            }
        }
        taken.insert(id.clone());
        names.push(id);
    }
    names
}

/// Writes the formula at `id` in the kernel's constructors, in brackets if
/// `argument` is set and it is an application.
fn term(out: &mut String, sequent: &Sequent, names: &[String], id: TermId, argument: bool) {
    use Term::*;
    for visit in Stops::new(id, argument, |k| sequent.term(k).operands()) {
        match visit {
            Stop::Enter(k, argument) => {
                let t = sequent.term(k);
                if argument && !matches!(t, Atom(_) | One | Bot | Top | Zero) {
                    out.push('(');
                }
                match t {
                    Atom(a) => out.push_str(&names[a.index()]),
                    DualAtom(a) => {
                        out.push_str("dual ");
                        out.push_str(&names[a.index()]);
                        if argument {
                            out.push(')');
                        }
                    }
                    One => out.push_str("one"),
                    Bot => out.push_str("bot"),
                    Top => out.push_str("top"),
                    Zero => out.push_str("zero"),
                    Tensor(..) => out.push_str("tens "),
                    Par(..) => out.push_str("parr "),
                    With(..) => out.push_str("awith "),
                    Plus(..) => out.push_str("aplus "),
                    Bang(_) => out.push_str("oc "),
                    Quest(_) => out.push_str("wn "),
                    Forall(_) | Exists(_) => {
                        unreachable!("NanoYalla's certificate refuses a sequent with a binder")
                    }
                }
            }
            Stop::Between(_) => out.push(' '),
            // What has subformulas is an application.
            Stop::Exit(_, argument) => {
                if argument {
                    out.push(')');
                }
            }
        }
    }
}

/// Writes occurrences as a list of the kernel's formulas, `[A; dual B]`.
fn list(out: &mut String, forest: &Forest, names: &[String], occurrences: &[OccId]) {
    out.push('[');
    for (i, &o) in occurrences.iter().enumerate() {
        if i > 0 {
            out.push_str("; ");
        }
        term(out, forest.sequent(), names, forest.term(o), false);
    }
    out.push(']');
}

/// The script in progress.
struct Script<'a> {
    /// The derivation being written.
    derivation: &'a Derivation<'a>,
    /// The forest its occurrences index.
    forest: &'a Forest,
    /// The identifier of every atom.
    names: Vec<String>,
    /// The text so far.
    out: String,
    /// The list of formulas Rocq shows as the goal of each inference not
    /// yet written, set when its conclusion is written.
    goals: Vec<Vec<OccId>>,
    /// Whether an inference is a premise of a binary rule, whose script
    /// goes into braces of its own.
    braced: Vec<bool>,
    /// How many braces are open.
    depth: usize,
}

impl Script<'_> {
    /// Writes a tactic line at the current indentation.
    fn line(&mut self, text: &str) {
        for _ in 0..self.depth {
            self.out.push_str("  ");
        }
        self.out.push_str(text);
        self.out.push('\n');
    }

    /// Writes a rule's tactic, `apply (<rule> <arguments>); cbn_sequent.`,
    /// without the `cbn_sequent` when the rule leaves no goal.
    fn apply(&mut self, rule: &str, arguments: &[String], leaf: bool) {
        let mut text = format!("apply ({rule}");
        for a in arguments {
            text.push(' ');
            text.push_str(a);
        }
        text.push(')');
        text.push_str(if leaf { "." } else { "; cbn_sequent." });
        self.line(&text);
    }

    /// Returns occurrences as a list of the kernel's formulas.
    fn list(&self, occurrences: &[OccId]) -> String {
        let mut out = String::new();
        list(&mut out, self.forest, &self.names, occurrences);
        out
    }

    /// Writes the tactic of the inference `id`, whose goal is `goal`, and
    /// sets the goals of its premises.
    fn inference(&mut self, id: InfId, goal: Vec<OccId>) {
        let (derivation, forest) = (self.derivation, self.forest);
        let inference = derivation.inference(id);
        let rule = inference.rule.rule;
        if rule == Rule::Ax {
            self.line("ax_expansion.");
            return;
        }
        let o = inference.sequent[inference.principal.unwrap()];
        let at = goal.iter().position(|&x| x == o.occ()).unwrap();
        let (before, after) = (&goal[..at], &goal[at + 1..]);
        let prefix = self.list(before);
        let (left, right) = (forest.left(o.occ()), forest.right(o.occ()));
        // The goal of the premise when the rule replaces the principal
        // formula by `with`.
        let replaced = |with: &[OccId]| {
            let mut up = Vec::with_capacity(goal.len() + 1);
            up.extend_from_slice(before);
            up.extend_from_slice(with);
            up.extend_from_slice(after);
            up
        };
        let premise = |script: &mut Self, up: Vec<OccId>| {
            script.goals[inference.premises[0].index()] = up;
        };
        match rule {
            // The export refuses a sequent with binders.
            Rule::Forall | Rule::Exists => unreachable!("NanoYalla's certificate refuses a binder"),
            Rule::One => self.line("apply one_r_ext."),
            Rule::Top => self.apply("top_r_ext", &[prefix], true),
            Rule::Bot => {
                self.apply("bot_r_ext", &[prefix], false);
                premise(self, replaced(&[]));
            }
            Rule::Par => {
                self.apply("parr_r_ext", &[prefix], false);
                premise(self, replaced(&[left.unwrap(), right.unwrap()]));
            }
            Rule::PlusLeft => {
                self.apply("plus_r1_ext", &[prefix], false);
                premise(self, replaced(&[left.unwrap()]));
            }
            Rule::PlusRight => {
                self.apply("plus_r2_ext", &[prefix], false);
                premise(self, replaced(&[right.unwrap()]));
            }
            Rule::Dereliction => {
                self.apply("de_r_ext", &[prefix], false);
                premise(self, replaced(&[left.unwrap()]));
            }
            Rule::Weakening => {
                self.apply("wk_r_ext", &[prefix], false);
                premise(self, replaced(&[]));
            }
            Rule::Contraction => {
                self.apply("co_r_ext", &[prefix], false);
                premise(self, replaced(&[o.occ(), o.occ()]));
            }
            Rule::Promotion => {
                // The context is `?` formulas, which the rule takes
                // without their `?`.
                let under: Vec<OccId> = before
                    .iter()
                    .chain(after)
                    .map(|&q| forest.left(q).unwrap())
                    .collect();
                let (l1, l2) = under.split_at(before.len());
                let mut a = String::from("(");
                term(
                    &mut a,
                    forest.sequent(),
                    &self.names,
                    forest.term(left.unwrap()),
                    false,
                );
                a.push(')');
                let arguments = [self.list(l1), a, self.list(l2)];
                self.apply("oc_r_ext", &arguments, false);
                premise(self, replaced(&[left.unwrap()]));
            }
            Rule::With => {
                self.apply("with_r_ext", &[prefix], false);
                let (l, r) = (inference.premises[0], inference.premises[1]);
                self.goals[l.index()] = replaced(&[left.unwrap()]);
                self.goals[r.index()] = replaced(&[right.unwrap()]);
                self.braced[l.index()] = true;
                self.braced[r.index()] = true;
            }
            Rule::Tensor => self.tensor(id, goal),
            Rule::Ax | Rule::Mix | Rule::AffineWeakening | Rule::Cut | Rule::Open => {
                unreachable!("refused before anything is written")
            }
        }
    }

    /// Writes the tactics of a `⊗`: the exchange that puts the left
    /// premise's context before the `⊗` and the right premise's after it,
    /// when the goal is not in that order already, then the rule.
    fn tensor(&mut self, id: InfId, goal: Vec<OccId>) {
        let (derivation, forest) = (self.derivation, self.forest);
        let inference = derivation.inference(id);
        let o = inference.sequent[inference.principal.unwrap()];
        let (a, b) = (
            forest.left(o.occ()).unwrap(),
            forest.right(o.occ()).unwrap(),
        );
        let (l, r) = (inference.premises[0], inference.premises[1]);
        // The left context, consumed as the goal's formulas are assigned.
        let mut left: Vec<OccId> = derivation
            .inference(l)
            .sequent
            .iter()
            .map(|m| m.occ())
            .collect();
        left.remove(left.iter().position(|&x| x == a).unwrap());
        let (mut before, mut after) = (Vec::new(), Vec::new());
        let mut principal = false;
        for &x in &goal {
            if x == o.occ() && !principal {
                principal = true;
            } else if let Some(i) = left.iter().position(|&y| y == x) {
                left.remove(i);
                before.push(x);
            } else {
                after.push(x);
            }
        }
        let mut target = before.clone();
        target.push(o.occ());
        target.extend_from_slice(&after);
        if target != goal {
            // `ex_perm_r p l` proves `l` permuted so that position `i`
            // holds `l[p[i]]`, from `l`.
            let mut used = vec![false; target.len()];
            let p: Vec<String> = goal
                .iter()
                .map(|&x| {
                    let j = (0..target.len())
                        .find(|&j| !used[j] && target[j] == x)
                        .unwrap();
                    used[j] = true;
                    j.to_string()
                })
                .collect();
            let arguments = [format!("[{}]", p.join("; ")), self.list(&target)];
            self.apply("ex_perm_r", &arguments, true);
        }
        let prefix = self.list(&before);
        self.apply("tens_r_ext", &[prefix], false);
        before.push(a);
        after.insert(0, b);
        self.goals[l.index()] = before;
        self.goals[r.index()] = after;
        self.braced[l.index()] = true;
        self.braced[r.index()] = true;
    }
}

/// Writes the certificate of a derivation into `out`, in the options'
/// form, one inference at a time, and asks `stop` after each; a
/// derivation without a certificate is refused before anything is
/// written. A linear derivation is a lemma for the kernel the options
/// name or the mode chooses ([`Options::kernel`]): with its proof script
/// for NanoYalla, checked one-sided, or proved from its proof term by
/// deduxit's library, one-sided or, for a two-sided derivation, two-sided.
/// One of LK or LJ, which must have passed
/// [`check`](crate::ordinary::Derivation::check), is the lemma
/// `options.lemma` stating the ordinary sequent over `Prop`, every atom a
/// proposition bound by `forall`, the hypotheses as premises and the
/// formulas right of `⊢` as their disjunction (`False` for none), proved
/// by a term made rule by rule; it needs no library, but a classical one
/// uses the excluded middle of the standard library (`NNPP`), which a
/// standalone file imports through `options.prelude`, by default
/// [`CLASSICAL_PRELUDE`]. A `String` takes the whole.
///
/// # Errors
///
/// [`Error::Unsupported`] for a derivation without a certificate (an
/// open goal, a compact run, a proof of the cyclic mode, and for
/// NanoYalla Mix and affine weakening), [`Error::GoalProof`]
/// for one of a goal off the roots, [`Refusal::Stopped`](crate::Refusal::Stopped)
/// when `stop` fired and [`Error::WriteFailed`] when `out` refused the
/// text.
pub fn write<'a>(
    derivation: impl Into<Drawable<'a>>,
    options: &Options,
    out: &mut impl Write,
    stop: impl FnMut(crate::limits::Progress) -> bool,
) -> Result<(), Error> {
    let stop = crate::limits::counting(stop, crate::limits::Phase::Write);
    match derivation.into() {
        Drawable::Linear(derivation) => linear(derivation, options, out, stop),
        Drawable::Ordinary(derivation) => {
            crate::ordinary::rocq::write(derivation, options, out, stop)
        }
        // The certificate is the proof's, whichever way it is drawn.
        Drawable::Classical(view) => linear(view.derivation(), options, out, stop),
    }
}

/// Writes the certificate that a disproof's goal has no derivation, for
/// deduxit's library ([`Kernel::Deduxit`], whatever the mode): the lemma
/// `options.lemma` stating that the mode's calculus does not derive the
/// goal, `~ ll R Γ` one-sided or, in intuitionistic mode, `~ ill R Γ C`
/// two-sided, with `R` the mode's rules, proved by the library's theorem
/// of the refutation's invariant (`classical_refutation`,
/// `unbalanced_refutation`, `equation_refutation`, `weighted_refutation`
/// and `affine_refutation`, or their two-sided forms) from the
/// assignment's true atoms, the unbalanced atom or the weights, which
/// Rocq's `vm_compute` checks: a one-sided count weighs its atom `±1`, a
/// state equation its atoms as the refutation does, the atoms no firing
/// reaches declared dead in the bodies' sign. A sequent with a quantifier
/// is stated over the first-order calculi, its counts proved by the
/// first-order weighted theorem. Every refutation
/// [`Disproof::check`](crate::linear::Disproof::check) verifies has one but a
/// saturated set and the count equation of a sequent with a quantifier,
/// and the disproof is checked first. Standalone, the
/// file starts with `options.prelude`, by default
/// [`DEDUXIT_REFUTATION_PRELUDE`], or [`DEDUXIT_FIRST_ORDER_REFUTATION_PRELUDE`]
/// for a sequent with a quantifier.
///
/// # Errors
///
/// [`Error::Refutation`] for a refutation the check does not accept,
/// [`Error::Unsupported`]
/// with [`Unsupported::Disproof`] where the options name NanoYalla,
/// [`Unsupported::Ordered`] in the cyclic mode,
/// [`Unsupported::Saturated`] for a refutation by a saturated set,
/// [`Unsupported::Exhausted`] for an exhausted search and
/// [`Unsupported::Quantifiers`] for the count equation of a sequent with
/// a quantifier,
/// [`Error::GoalOutputs`] for an intuitionistic goal without exactly one
/// conclusion, the errors of [`Forest::new`] and of the intuitionistic
/// reading, and
/// [`Error::WriteFailed`] when `out` refused the text.
pub fn write_disproof(
    disproof: &crate::linear::Disproof,
    options: &Options,
    out: &mut impl Write,
) -> Result<(), Error> {
    if options.kernel == Some(Kernel::NanoYalla) {
        return Err(Unsupported::Disproof.into());
    }
    if disproof.mode().is_ordered() {
        return Err(Unsupported::Ordered.into());
    }
    if let crate::linear::search::Refutation::Saturated(_) = disproof.refutation() {
        return Err(Unsupported::Saturated.into());
    }
    if let crate::linear::search::Refutation::Exhausted = disproof.refutation() {
        return Err(Unsupported::Exhausted.into());
    }
    deduxit::disproof(disproof, options, out)
}

/// Writes the certificate that an ordinary sequent is not valid, from its
/// image's disproof: the lemma `options.lemma` stating `~ (forall a b :
/// Prop, Γ -> Δ)`, the sequent as [`write()`] states it over `Prop`,
/// proved by instantiating each atom with `True` or `False` as the
/// image's classical refutation assigns it, which makes the formula
/// false. It needs no library, in classical and intuitionistic logic
/// alike; standalone, it starts with `options.prelude` where one is
/// given.
///
/// # Errors
///
/// [`Error::Unsupported`] with [`Unsupported::NotValid`] where the image's
/// refutation is no classical assignment or does not falsify the
/// sequent, [`Error::Refutation`] where it does not falsify the image,
/// and [`Error::WriteFailed`] when `out` refused the text.
pub fn write_not_valid(
    image: &crate::ordinary::Image,
    disproof: &crate::linear::Disproof,
    options: &Options,
    out: &mut impl Write,
) -> Result<(), Error> {
    crate::ordinary::rocq::not_valid(image, disproof, options, out)
}

/// Writes the certificate of a linear derivation for the kernel the
/// options name or the mode chooses, as [`write()`] does.
fn linear(
    derivation: &Derivation,
    options: &Options,
    out: &mut impl Write,
    stop: impl FnMut() -> bool,
) -> Result<(), Error> {
    if derivation.is_of_goal() {
        return Err(Error::GoalProof);
    }
    if derivation.mode().is_some_and(Mode::is_ordered) {
        return Err(Unsupported::Ordered.into());
    }
    let uses = |rule| derivation.inferences().iter().any(|i| i.rule.rule == rule);
    let (mix, weakening, cut) = (
        uses(Rule::Mix),
        uses(Rule::AffineWeakening),
        uses(Rule::Cut),
    );
    let mode = derivation.mode();
    let binders = derivation.forest().has_binders();
    let kernel = options.kernel.unwrap_or(match mode {
        Some(mode) if mode.is_intuitionistic() || mode.is_affine() || mode.has_mix() => {
            Kernel::Deduxit
        }
        // Classical linear logic, or a proof that records no mode and
        // shows its own: NanoYalla, unless it needs what the kernel lacks.
        _ if mix
            || weakening
            || cut
            || binders
            || (mode.is_none() && derivation.reading().is_some()) =>
        {
            Kernel::Deduxit
        }
        _ => Kernel::NanoYalla,
    });
    match kernel {
        // NanoYalla's formulas have no quantifier.
        Kernel::NanoYalla if binders => Err(Unsupported::Quantifiers.into()),
        Kernel::NanoYalla => nanoyalla(derivation, options, out, stop),
        Kernel::Deduxit => {
            // The calculus states what the mode allows and what the proof
            // uses, which a proof checked in another mode may exceed.
            let calculus = deduxit::Calculus {
                mix: mix || mode.is_some_and(Mode::has_mix),
                weakening: weakening || mode.is_some_and(Mode::is_affine),
                cut,
            };
            deduxit::write(derivation, options, calculus, out, stop)
        }
    }
}

/// Writes the NanoYalla certificate of a linear derivation as [`write()`]
/// does.
fn nanoyalla(
    derivation: &Derivation,
    options: &Options,
    out: &mut impl Write,
    mut stop: impl FnMut() -> bool,
) -> Result<(), Error> {
    for inference in derivation.inferences() {
        if inference.times > 1 {
            return Err(Unsupported::Compact.into());
        }
        match inference.rule.rule {
            Rule::Open => return Err(Unsupported::Open.into()),
            Rule::Mix => return Err(Unsupported::Mix.into()),
            Rule::AffineWeakening => return Err(Unsupported::AffineWeakening.into()),
            Rule::Cut => return Err(Unsupported::Cut.into()),
            Rule::Forall | Rule::Exists => return Err(Unsupported::Quantifiers.into()),
            Rule::Ax
            | Rule::Tensor
            | Rule::Par
            | Rule::One
            | Rule::Bot
            | Rule::With
            | Rule::PlusLeft
            | Rule::PlusRight
            | Rule::Top
            | Rule::Promotion
            | Rule::Dereliction
            | Rule::Contraction
            | Rule::Weakening => {}
        }
    }
    let forest = derivation.forest();
    let names = identifiers(forest.sequent().atom_names(), options.lemma.as_str());
    let count = derivation.inferences().len();
    let mut script = Script {
        derivation,
        forest,
        names,
        out: String::new(),
        goals: vec![Vec::new(); count],
        braced: vec![false; count],
        depth: 0,
    };
    let root = derivation.root();
    script.goals[root.index()] = derivation
        .inference(root)
        .sequent
        .iter()
        .map(|m| m.occ())
        .collect();

    if options.form == Form::Standalone {
        let prelude = options.prelude.as_deref().unwrap_or(NANOYALLA_PRELUDE);
        write!(out, "{}\n\n", prelude.trim_end())?;
    }
    write!(script.out, "Lemma {}", options.lemma)?;
    if !script.names.is_empty() {
        write!(script.out, " ({} : formula)", script.names.join(" "))?;
    }
    script.out.push_str(" : ll ");
    let conclusion = script.list(&script.goals[root.index()]);
    script.out.push_str(&conclusion);
    script.out.push_str(".\nProof.\n");
    walk(derivation, |step| {
        match step {
            Step::Enter(id, _) => {
                if script.braced[id.index()] {
                    script.line("{");
                    script.depth += 1;
                }
                let goal = std::mem::take(&mut script.goals[id.index()]);
                script.inference(id, goal);
            }
            Step::Exit(id, _) => {
                if script.braced[id.index()] {
                    script.depth -= 1;
                    script.line("}");
                }
            }
        }
        flush(out, &mut script.out, &mut stop)
    })?;
    out.write_str("Qed.")?;
    Ok(())
}

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

    /// Letters, digits, `_` and `'` stay; other characters become their
    /// code points; a clash with a keyword, the kernel, the lemma or
    /// another atom gets `'` appended.
    #[test]
    fn names_become_identifiers() {
        for (name, expected) in [
            ("A", "A"),
            ("x_1", "x_1"),
            ("p'", "p'"),
            ("1a", "_1a"),
            ("α", "_3b1_"),
            ("a b", "a_20_b"),
            ("", "_"),
        ] {
            assert_eq!(identifier(name), expected, "{name:?}");
        }
        let atoms: Vec<String> = ["tens", "with", "certificate", "α", "_3b1_", "_"]
            .map(String::from)
            .into();
        assert_eq!(
            identifiers(&atoms, "certificate"),
            ["tens'", "with'", "certificate'", "_3b1_", "_3b1_'", "_'"]
        );
        // Names that all map to one identifier take one suffix each.
        let atoms: Vec<String> = ["ää", "ä_e4_", "_e4_ä", "_e4__e4_"]
            .map(String::from)
            .into();
        assert_eq!(
            identifiers(&atoms, "certificate"),
            ["_e4__e4_", "_e4__e4_'", "_e4__e4_'2", "_e4__e4_'3"]
        );
    }
}