cadical-sys 0.8.0

Safe bindings for the CaDiCaL SAT solver, made with the cxx crate and wrapped in a 1 to 1 API.
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
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
#![doc = include_str!("../README.md")]

use bridge::ffi;
use cxx::memory::UniquePtrTarget;
use cxx::UniquePtr;
use std::cell::RefCell;
use std::rc::Rc;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Arc;

// The raw FFI bindings. They are private: they take `UniquePtr`s that may be
// null and C++ objects whose lifetimes they cannot check, so exposing them as
// safe functions would let safe code cause undefined behaviour.
mod bridge;

/// The C++ shim reports success as an empty string and failure as an error message.
fn into_result(message: String) -> Result<(), String> {
    if message.is_empty() {
        Ok(())
    } else {
        Err(message)
    }
}

/// Literals must be non-zero and not `i32::MIN`; `CaDiCaL` aborts the process
/// otherwise, so the safe API panics first.
#[track_caller]
fn require_valid_lit(function: &str, lit: i32) {
    assert!(
        lit != 0 && lit != i32::MIN,
        "{function} called with invalid literal {lit}"
    );
}

/// Whether `CaDiCaL` requires the variables of added clauses to be declared
/// (see `Solver::add`).
fn requires_declared_vars(factor: i32, factorcheck: i32) -> bool {
    factorcheck == 2 || (factorcheck == 1 && factor != 0)
}

/// Like [`require_valid_lit`] for functions where zero terminates a clause.
#[track_caller]
fn require_valid_lit_or_zero(function: &str, lit: i32) {
    assert!(
        lit != i32::MIN,
        "{function} called with invalid literal {lit}"
    );
}

/// The SAT competition standardized the exit code of SAT solvers to the
/// following which then is also used return code for 'solve' functions.
/// In the following example we use those constants for brevity though.
#[derive(Debug, PartialEq, Eq, Hash, Clone, Copy)]
pub enum Status {
    SATISFIABLE = 10,
    UNSATISFIABLE = 20,
    UNKNOWN = 0,
}

impl From<i32> for Status {
    fn from(val: i32) -> Self {
        match val {
            10 => Status::SATISFIABLE,
            20 => Status::UNSATISFIABLE,
            0 => Status::UNKNOWN,
            _ => unreachable!(),
        }
    }
}

/// States are represented by a bit-set in order to combine them.
#[derive(Debug, PartialEq, Eq, Hash, Clone, Copy)]
pub enum State {
    /// during initialization (invalid)
    INITIALIZING = 1,
    /// configure options (with 'set')
    CONFIGURING = 2,
    /// ready to call 'solve'
    STEADY = 4,
    /// adding clause literals (zero missing)
    ADDING = 8,
    /// while solving (within 'solve')
    SOLVING = 16,
    /// satisfiable allows 'val'
    SATISFIED = 32,
    /// unsatisfiable allows 'failed'
    UNSATISFIED = 64,
    /// during and after deletion (invalid)
    DELETING = 128,
    /// unknown allows 'implied'
    INCONCLUSIVE = 256,

    /// These combined states are used to check contracts.
    /// CONFIGURING | STEADY | SATISFIED | UNSATISFIED | INCONCLUSIVE,
    READY = 358,
    /// READY | ADDING
    VALID = 366,
    /// INITIALIZING | DELETING
    INVALID = 129,
}

impl From<i32> for State {
    fn from(val: i32) -> Self {
        match val {
            1 => State::INITIALIZING,
            2 => State::CONFIGURING,
            4 => State::STEADY,
            8 => State::ADDING,
            16 => State::SOLVING,
            32 => State::SATISFIED,
            64 => State::UNSATISFIED,
            128 => State::DELETING,
            256 => State::INCONCLUSIVE,
            358 => State::READY,
            366 => State::VALID,
            129 => State::INVALID,
            _ => unreachable!(),
        }
    }
}

/// A Rust callback object together with the C++ wrapper that calls into it.
///
/// The C++ wrapper only holds a raw pointer to the callback, so the callback
/// is boxed and owned here rather than borrowed from the caller. This is what
/// guarantees the callback outlives every call the solver makes into it.
struct Connected<W: UniquePtrTarget> {
    wrapper: UniquePtr<W>,
    callback: *mut u8,
    drop_callback: unsafe fn(*mut u8),
}

impl<W: UniquePtrTarget> Connected<W> {
    /// Boxes `callback` and builds its C++ wrapper from a pointer to it.
    fn new<T>(callback: T, make_wrapper: impl FnOnce(*mut u8) -> UniquePtr<W>) -> Self {
        unsafe fn drop_box<T>(ptr: *mut u8) {
            drop(unsafe { Box::from_raw(ptr.cast::<T>()) });
        }
        let callback = Box::into_raw(Box::new(callback)).cast::<u8>();
        Self {
            wrapper: make_wrapper(callback),
            callback,
            drop_callback: drop_box::<T>,
        }
    }
}

impl<W: UniquePtrTarget> Drop for Connected<W> {
    fn drop(&mut self) {
        // Free the wrapper before the callback it points to.
        drop(std::mem::replace(&mut self.wrapper, UniquePtr::null()));
        unsafe { (self.drop_callback)(self.callback) };
    }
}

/// A `CaDiCaL` solver.
///
/// Methods that take a literal panic if it is `0` or `i32::MIN` (except
/// [`CaDiCal::add`] and [`CaDiCal::constrain`], where `0` ends the clause), and
/// methods with a state precondition panic when it does not hold. `CaDiCaL`
/// itself would abort the whole process in both cases.
///
/// With the `factor` option (off by default), or `factorcheck` set to 2,
/// clauses may only use variables declared with
/// [`CaDiCal::declare_more_variables`] (or [`CaDiCal::resize`]); adding others
/// panics. One case is not checked: with `factor` the solver adds extension
/// variables of its own, and passing one of those to a method that takes a
/// literal still aborts.
///
/// `CaDiCaL`'s own checking options, e.g. `checkfrozen` (which makes reusing
/// a variable that was not frozen across `solve` calls fatal), abort the
/// process when their check fails; that is what they are for.
///
/// `CaDiCaL` reads options from `CADICAL_<OPTION>` environment variables. The
/// debugging variable `CADICAL_LIDRUP_TRACE` makes every solver write a proof
/// to the given file, and `CaDiCaL` aborts the process when a second solver
/// is created while it is set.
pub struct CaDiCal {
    // Declared first so the solver is destroyed before the callbacks it may call.
    solver: UniquePtr<ffi::Solver>,
    last_terminator: Option<Connected<ffi::Terminator>>,
    last_learner: Option<Connected<ffi::Learner>>,
    last_external_propagator: Option<Connected<ffi::ExternalPropagator>>,
    last_fixed_listener: Option<Connected<ffi::FixedAssignmentListener>>,
    last_tracer: Option<Connected<ffi::Tracer>>,
    // Whether the last proof file opened with `trace_proof*` is still open.
    proof_file_open: bool,
    // Whether a proof file was closed. CaDiCaL then closes it again (and
    // crashes) when a later proof file is closed, so no new one may be opened.
    proof_file_closed: bool,
    // The `factor` and `factorcheck` options, which decide whether CaDiCaL
    // requires the variables of added clauses to be declared. Options only
    // change while CONFIGURING, through `set`, `set_long_option`, `configure`,
    // `read_dimacs*` and `copy`, which update these.
    factor_option: i32,
    factorcheck_option: i32,
}

/// Cloning copies the formula and options (see [`CaDiCal::copy`]) but not any
/// connected callbacks; the clone starts with none connected. Like `copy`, it
/// panics if the solver is not READY, e.g. in the middle of adding a clause.
impl Clone for CaDiCal {
    fn clone(&self) -> Self {
        let mut r = Self::new();
        Self::copy(self, &mut r);
        r
    }
}

impl Drop for CaDiCal {
    fn drop(&mut self) {
        // CaDiCaL deletes tracers that are still connected when it is destroyed,
        // but ours is owned (and deleted) by `last_tracer`.
        self.disconnect_proof_tracer1();
    }
}

impl Default for CaDiCal {
    fn default() -> Self {
        Self::new()
    }
}

impl CaDiCal {
    #[must_use]
    #[inline]
    pub fn new() -> Self {
        let mut solver = Self {
            solver: ffi::constructor(),
            last_terminator: None,
            last_learner: None,
            last_external_propagator: None,
            last_fixed_listener: None,
            last_tracer: None,
            proof_file_open: false,
            proof_file_closed: false,
            factor_option: 0,
            factorcheck_option: 1,
        };
        // Options can also be set through `CADICAL_<OPTION>` environment
        // variables, which CaDiCaL reads when the solver is created.
        solver.update_declared_vars_only();
        // With this (debugging) environment variable set, CaDiCaL opens a
        // proof file itself when the solver is created.
        solver.proof_file_open = std::env::var_os("CADICAL_LIDRUP_TRACE")
            .or_else(|| std::env::var_os("CADICALLIDRUPTRACE"))
            .is_some();
        solver
    }

    /// Core functionality as in the IPASIR incremental SAT solver interface.
    /// (recall 'READY = CONFIGURING | STEADY  | SATISFIED | UNSATISFIED | INCONCLUSIVE').
    /// Further note that 'lit' is required to be different from '`INT_MIN`' and
    /// different from '0' except for 'add'.
    ///
    /// Add valid literal to clause or zero to terminate clause.
    ///
    ///   require (VALID)                   recall 'VALID = READY | ADDING'
    ///
    ///   if (lit) ensure (ADDING)          and thus VALID but not READY
    ///
    ///   if (!lit) ensure (STEADY )        and thus READY
    ///
    #[inline]
    #[track_caller]
    pub fn add(&mut self, lit: i32) {
        require_valid_lit_or_zero("add", lit);
        if lit != 0 {
            self.require_declared("add", lit);
        }
        ffi::add(&mut self.solver, lit);
    }

    /// Here are functions simplifying clause addition. The given literals
    /// should all be valid (different from '`INT_MIN`' and different from '0').
    ///
    ///   require (VALID)
    ///   ensure (STEADY )
    ///
    #[inline]
    #[track_caller]
    pub fn clause1(&mut self, l1: i32) {
        require_valid_lit("clause1", l1);
        self.require_declared("clause1", l1);
        ffi::clause1(&mut self.solver, l1);
    }

    #[inline]
    #[track_caller]
    pub fn clause2(&mut self, l1: i32, l2: i32) {
        for lit in [l1, l2] {
            require_valid_lit("clause2", lit);
            self.require_declared("clause2", lit);
        }
        ffi::clause2(&mut self.solver, l1, l2);
    }

    #[inline]
    #[track_caller]
    pub fn clause3(&mut self, l1: i32, l2: i32, l3: i32) {
        for lit in [l1, l2, l3] {
            require_valid_lit("clause3", lit);
            self.require_declared("clause3", lit);
        }
        ffi::clause3(&mut self.solver, l1, l2, l3);
    }

    #[inline]
    #[track_caller]
    pub fn clause4(&mut self, l1: i32, l2: i32, l3: i32, l4: i32) {
        for lit in [l1, l2, l3, l4] {
            require_valid_lit("clause4", lit);
            self.require_declared("clause4", lit);
        }
        ffi::clause4(&mut self.solver, l1, l2, l3, l4);
    }

    #[inline]
    #[track_caller]
    pub fn clause5(&mut self, l1: i32, l2: i32, l3: i32, l4: i32, l5: i32) {
        for lit in [l1, l2, l3, l4, l5] {
            require_valid_lit("clause5", lit);
            self.require_declared("clause5", lit);
        }
        ffi::clause5(&mut self.solver, l1, l2, l3, l4, l5);
    }

    #[inline]
    #[track_caller]
    pub fn clause6(&mut self, v: &[i32]) {
        for &lit in v {
            require_valid_lit("clause6", lit);
            self.require_declared("clause6", lit);
        }
        ffi::clause6(&mut self.solver, v);
    }

    /// This function can be used to check if the formula is already
    /// inconsistent (contains the empty clause or was proven to be
    /// root-level unsatisfiable).
    #[inline]
    pub fn inconsistent(&mut self) -> bool {
        ffi::inconsistent(&mut self.solver)
    }

    /// Assume valid non zero literal for next call to 'solve'.  These
    /// assumptions are reset after the call to 'solve' as well as after
    /// returning from 'simplify' and 'lookahead.
    ///
    ///   require (READY)
    ///   ensure (STEADY )
    ///
    #[inline]
    #[track_caller]
    pub fn assume(&mut self, lit: i32) {
        require_valid_lit("assume", lit);
        self.require_ready("assume");
        ffi::assume(&mut self.solver, lit);
    }

    /// Try to solve the current formula.  Returns
    ///
    ///    0 = UNKNOWN      (limit reached or interrupted through 'terminate')
    ///   10 = SATISFIABLE
    ///   20 = UNSATISFIABLE
    ///
    ///   require (READY)
    ///   ensure (INCONCLUSIVE  | SATISFIED | UNSATISFIED)
    ///
    /// Note, that while in this call the solver actually transitions to state
    /// 'SOLVING', which however is only visible from a different context,
    /// i.e., from a different thread or from a signal handler.  Only right
    /// before returning from this call it goes into a 'READY' state.
    ///
    /// # Panics
    ///
    /// If the solver is in the middle of adding a clause or constraint (not READY). `CaDiCaL` would otherwise abort the process.
    ///
    #[inline]
    #[track_caller]
    pub fn solve(&mut self) -> Status {
        self.require_ready("solve");
        ffi::solve(&mut self.solver).into()
    }

    /// Get value (-lit=false, lit=true) of valid non-zero literal.
    ///
    ///   require (SATISFIED)
    ///   ensure (SATISFIED)
    ///
    /// # Panics
    ///
    /// If the solver is not in the `SATISFIED` state or `lit` is not a valid
    /// literal (zero or `i32::MIN`). `CaDiCaL` would otherwise abort the process.
    ///
    #[inline]
    #[track_caller]
    pub fn val(&mut self, lit: i32) -> i32 {
        self.require("val", State::SATISFIED, lit);
        ffi::val(&mut self.solver, lit)
    }

    /// Try to flip the value of the given literal without falsifying the
    /// formula.  Returns 'true' if this was successful. Otherwise the model is
    /// not changed and 'false' is returned.  If a literal was eliminated or
    /// substituted flipping will fail on that literal and in particular the
    /// solver will not taint it nor restore any clauses.
    ///
    /// The 'flip' function can only flip the value of a variables not acting
    /// as witness on the reconstruction stack.
    ///
    /// As a side effect of calling this function first all assigned variables
    /// are propagated again without using blocking literal.  Thus the first
    /// call to this function after obtaining a model adds a substantial
    /// overhead.  Subsequent calls will not need to properly propagate again.
    ///
    /// Furthermore if the reconstruction stack is non-empty and has been
    /// traversed to reconstruct a full extended model for eliminated
    /// variables (and to satisfy removed blocked clauses), the values of these
    /// witness variables obtained via 'val' before become invalid. The user
    /// thus will need to call 'val' again after calling 'flip' which will
    /// trigger then a traversal of the reconstruction stack.
    ///
    /// So try to avoid mixing 'flip' and 'val' (for efficiency only).
    /// Further, this functionality is currently not supported in the presence
    /// of an external propagator.
    ///
    ///   require (SATISFIED)
    ///   ensure (SATISFIED)
    ///
    /// # Panics
    ///
    /// If the solver is not in the `SATISFIED` state, `lit` is not a valid
    /// literal, or an external propagator is connected. `CaDiCaL` would
    /// otherwise abort the process.
    ///
    #[inline]
    #[track_caller]
    pub fn flip(&mut self, lit: i32) -> bool {
        self.require("flip", State::SATISFIED, lit);
        assert!(
            self.last_external_propagator.is_none(),
            "flip is not supported while an external propagator is connected"
        );
        ffi::flip(&mut self.solver, lit)
    }

    /// Same as 'flip' without actually flipping it. This functionality is
    /// currently not supported in the presence of an external propagator.
    ///
    ///   require (SATISFIED)
    ///   ensure (SATISFIED)
    ///
    /// # Panics
    ///
    /// If the solver is not in the `SATISFIED` state, `lit` is not a valid
    /// literal, or an external propagator is connected. `CaDiCaL` would
    /// otherwise abort the process.
    ///
    #[inline]
    #[track_caller]
    pub fn flippable(&mut self, lit: i32) -> bool {
        self.require("flippable", State::SATISFIED, lit);
        assert!(
            self.last_external_propagator.is_none(),
            "flippable is not supported while an external propagator is connected"
        );
        ffi::flippable(&mut self.solver, lit)
    }

    /// Determine whether the valid non-zero literal is in the core.
    /// Returns 'true' if the literal is in the core and 'false' otherwise.
    /// Note that the core does not have to be minimal.
    ///
    ///   require (UNSATISFIED)
    ///   ensure (UNSATISFIED)
    ///
    /// # Panics
    ///
    /// If the solver is not in the `UNSATISFIED` state or `lit` is not a valid
    /// literal (zero or `i32::MIN`). `CaDiCaL` would otherwise abort the process.
    ///
    #[inline]
    #[track_caller]
    pub fn failed(&mut self, lit: i32) -> bool {
        self.require("failed", State::UNSATISFIED, lit);
        ffi::failed(&mut self.solver, lit)
    }

    /// Add call-back which is checked regularly for termination.  There can
    /// only be one terminator connected.  If a second (non-zero) one is added
    /// the first one is implicitly disconnected.
    ///
    ///   require (VALID)
    ///   ensure (VALID)
    ///
    /// The solver takes ownership of `terminator` and drops it when it is
    /// disconnected, replaced, or the solver is dropped. To read its state
    /// afterwards, pass an `Rc<RefCell<_>>` and keep a clone of the `Rc`.
    ///
    /// The callback must be `'static`, so it cannot borrow from a value that
    /// might be dropped while the solver still calls it:
    ///
    /// ```compile_fail,E0597
    /// # use cadical_sys::{CaDiCal, Terminator};
    /// # struct Cb<'a>(&'a mut u32);
    /// # impl Terminator for Cb<'_> { fn terminated(&mut self) -> bool { false } }
    /// let mut solver = CaDiCal::new();
    /// let mut calls = 0;
    /// solver.connect_terminator(Cb(&mut calls)); // error: `calls` does not live long enough
    /// ```
    ///
    #[inline]
    pub fn connect_terminator<T: Terminator + 'static>(&mut self, terminator: T) {
        fn f<T: Terminator>(state: *mut u8) -> bool {
            let ptr: *mut T = state.cast::<T>();
            let i = unsafe { &mut *ptr };
            i.terminated()
        }
        let mut terminator = Connected::new(terminator, |state| unsafe {
            ffi::new_terminator(state, f::<T>)
        });
        ffi::connect_terminator(&mut self.solver, &mut terminator.wrapper);
        // Only drop the previous terminator once the solver no longer points to it.
        self.last_terminator = Some(terminator);
    }

    #[inline]
    pub fn disconnect_terminator(&mut self) {
        ffi::disconnect_terminator(&mut self.solver);
        self.last_terminator = None;
    }

    /// Add call-back which allows to export learned clauses.
    ///
    ///   require (VALID)
    ///   ensure (VALID)
    ///
    /// The solver takes ownership of `learner` and drops it when it is
    /// disconnected, replaced, or the solver is dropped. To read its state
    /// afterwards, pass an `Rc<RefCell<_>>` and keep a clone of the `Rc`.
    ///
    /// The callback must be `'static`, so it cannot borrow from a value that
    /// might be dropped while the solver still calls it:
    ///
    /// ```compile_fail,E0597
    /// # use cadical_sys::{CaDiCal, Learner};
    /// # struct Cb<'a>(&'a mut u32);
    /// # impl Learner for Cb<'_> { fn learning(&mut self, _: i32) -> bool { false } fn learn(&mut self, _: i32) {} }
    /// let mut solver = CaDiCal::new();
    /// let mut calls = 0;
    /// solver.connect_learner(Cb(&mut calls)); // error: `calls` does not live long enough
    /// ```
    ///
    #[inline]
    pub fn connect_learner<T: Learner + 'static>(&mut self, learner: T) {
        fn learning<T: Learner>(state: *mut u8, size: i32) -> bool {
            let ptr: *mut T = state.cast::<T>();
            let i = unsafe { &mut *ptr };
            i.learning(size)
        }

        fn learn<T: Learner>(state: *mut u8, lit: i32) {
            let ptr: *mut T = state.cast::<T>();
            let i = unsafe { &mut *ptr };
            i.learn(lit);
        }

        let mut learner = Connected::new(learner, |state| unsafe {
            ffi::new_learner(state, learning::<T>, learn::<T>)
        });
        ffi::connect_learner(&mut self.solver, &mut learner.wrapper);
        self.last_learner = Some(learner);
    }

    #[inline]
    pub fn disconnect_learner(&mut self) {
        ffi::disconnect_learner(&mut self.solver);
        self.last_learner = None;
    }

    /// Add call-back which allows to observe when a variable is fixed.
    ///
    ///   require (VALID)
    ///   ensure (VALID)
    ///
    /// The solver takes ownership of `fixed_listener` and drops it when it is
    /// disconnected, replaced, or the solver is dropped. To read its state
    /// afterwards, pass an `Rc<RefCell<_>>` and keep a clone of the `Rc`.
    ///
    /// The callback must be `'static`, so it cannot borrow from a value that
    /// might be dropped while the solver still calls it:
    ///
    /// ```compile_fail,E0597
    /// # use cadical_sys::{CaDiCal, FixedAssignmentListener};
    /// # struct Cb<'a>(&'a mut u32);
    /// # impl FixedAssignmentListener for Cb<'_> { fn notify_fixed_assignment(&mut self, _: i32) {} }
    /// let mut solver = CaDiCal::new();
    /// let mut calls = 0;
    /// solver.connect_fixed_listener(Cb(&mut calls)); // error: `calls` does not live long enough
    /// ```
    ///
    pub fn connect_fixed_listener<F: FixedAssignmentListener + 'static>(
        &mut self,
        fixed_listener: F,
    ) {
        fn notify_fixed_assignment<F: FixedAssignmentListener>(state: *mut u8, lit: i32) {
            let ptr: *mut F = state.cast::<F>();
            let i = unsafe { &mut *ptr };
            i.notify_fixed_assignment(lit);
        }

        let mut listener = Connected::new(fixed_listener, |state| unsafe {
            ffi::new_fixed_assignment_listener(state, notify_fixed_assignment::<F>)
        });
        ffi::connect_fixed_listener(&mut self.solver, &mut listener.wrapper);
        self.last_fixed_listener = Some(listener);
    }

    #[inline]
    pub fn disconnect_fixed_listener(&mut self) {
        ffi::disconnect_fixed_listener(&mut self.solver);
        self.last_fixed_listener = None;
    }

    /// Add call-back which allows to learn, propagate and backtrack based on
    /// external constraints. Only one external propagator can be connected
    /// and after connection every related variables must be 'observed' (use
    /// '`add_observed_var`' function).
    /// Disconnection of the external propagator resets all the observed
    /// variables.
    ///
    ///   require (VALID)
    ///   ensure (VALID)
    ///
    /// The solver takes ownership of `propagator` and drops it when it is
    /// disconnected, replaced, or the solver is dropped. To read its state
    /// afterwards, pass an `Rc<RefCell<_>>` and keep a clone of the `Rc`.
    /// Connecting a propagator disconnects any propagator connected earlier,
    /// which also resets the observed variables.
    ///
    pub fn connect_external_propagator<T: ExternalPropagator + 'static>(
        &mut self,
        mut propagator: T,
    ) {
        fn notify_assignment<T: ExternalPropagator>(state: *mut u8, x: &[i32]) {
            let ptr: *mut T = state.cast::<T>();
            let i = unsafe { &mut *ptr };
            i.notify_assignment(x);
        }
        fn notify_new_decision_level<T: ExternalPropagator>(state: *mut u8) {
            let ptr: *mut T = state.cast::<T>();
            let i = unsafe { &mut *ptr };
            i.notify_new_decision_level();
        }
        fn notify_backtrack<T: ExternalPropagator>(state: *mut u8, x: usize) {
            let ptr: *mut T = state.cast::<T>();
            let i = unsafe { &mut *ptr };
            i.notify_backtrack(x);
        }
        fn cb_check_found_model<T: ExternalPropagator>(state: *mut u8, x: &[i32]) -> bool {
            let ptr: *mut T = state.cast::<T>();
            let i = unsafe { &mut *ptr };
            i.cb_check_found_model(x)
        }
        fn cb_decide<T: ExternalPropagator>(state: *mut u8) -> i32 {
            let ptr: *mut T = state.cast::<T>();
            let i = unsafe { &mut *ptr };
            i.cb_decide()
        }
        fn cb_propagate<T: ExternalPropagator>(state: *mut u8) -> i32 {
            let ptr: *mut T = state.cast::<T>();
            let i = unsafe { &mut *ptr };
            i.cb_propagate()
        }
        fn cb_add_reason_clause_lit<T: ExternalPropagator>(state: *mut u8, x: i32) -> i32 {
            let ptr: *mut T = state.cast::<T>();
            let i = unsafe { &mut *ptr };
            i.cb_add_reason_clause_lit(x)
        }
        fn cb_has_external_clause<T: ExternalPropagator>(state: *mut u8, x: *mut bool) -> bool {
            let ptr: *mut T = state.cast::<T>();
            let i = unsafe { &mut *ptr };
            i.cb_has_external_clause(unsafe { &mut *x })
        }
        fn cb_add_external_clause_lit<T: ExternalPropagator>(state: *mut u8) -> i32 {
            let ptr: *mut T = state.cast::<T>();
            let i = unsafe { &mut *ptr };
            i.cb_add_external_clause_lit()
        }
        // CaDiCaL aborts when connecting a second propagator.
        self.disconnect_external_propagator();

        let is_lazy = propagator.is_lazy();
        let are_reasons_forgettable = propagator.are_reasons_forgettable();

        let mut external_propagator = Connected::new(propagator, |state| unsafe {
            ffi::new_external_propagator(
                state,
                is_lazy,
                are_reasons_forgettable,
                notify_assignment::<T>,
                notify_new_decision_level::<T>,
                notify_backtrack::<T>,
                cb_check_found_model::<T>,
                cb_decide::<T>,
                cb_propagate::<T>,
                cb_add_reason_clause_lit::<T>,
                cb_has_external_clause::<T>,
                cb_add_external_clause_lit::<T>,
            )
        });
        ffi::connect_external_propagator(&mut self.solver, &mut external_propagator.wrapper);
        self.last_external_propagator = Some(external_propagator);
    }
    pub fn disconnect_external_propagator(&mut self) {
        // CaDiCaL 3 aborts when disconnecting without a connected propagator.
        // `_propagator` is only dropped after CaDiCaL has let go of it.
        if let Some(_propagator) = self.last_external_propagator.take() {
            ffi::disconnect_external_propagator(&mut self.solver);
        }
    }

    /// Mark as 'observed' those variables that are relevant to the external
    /// propagator. External propagation, clause addition during search and
    /// notifications are all over these observed variabes.
    /// A variable can not be observed witouth having an external propagator
    /// connected. Observed variables are "frozen" internally, and so
    /// inprocessing will not consider them as candidates for elimination.
    /// An observed variable is allowed to be a fresh variable and it can be
    /// added also during solving.
    ///
    ///   require (`VALID_OR_SOLVING`)
    ///   ensure (`VALID_OR_SOLVING`)
    ///
    /// Observing a variable that preprocessing or inprocessing has already
    /// eliminated is not checked and aborts the process. Observe variables
    /// before solving, or [`CaDiCal::freeze`] them.
    ///
    /// # Panics
    ///
    /// If no external propagator is connected. `CaDiCaL` would otherwise
    /// abort the process.
    ///
    #[inline]
    #[track_caller]
    pub fn add_observed_var(&mut self, var: i32) {
        require_valid_lit("add_observed_var", var);
        self.require_propagator("add_observed_var");
        ffi::add_observed_var(&mut self.solver, var);
    }

    /// Removes the 'observed' flag from the given variable. A variable can be
    /// set unobserved only between solve calls, not during it (to guarantee
    /// that no yet unexplained external propagation involves it).
    ///
    ///   require (VALID)
    ///   ensure (VALID)
    ///
    /// # Panics
    ///
    /// If no external propagator is connected. `CaDiCaL` would otherwise
    /// abort the process.
    ///
    #[inline]
    #[track_caller]
    pub fn remove_observed_var(&mut self, var: i32) {
        require_valid_lit("remove_observed_var", var);
        self.require_propagator("remove_observed_var");
        ffi::remove_observed_var(&mut self.solver, var);
    }

    /// Removes all the 'observed' flags from the variables. Disconnecting the
    /// propagator invokes this step as well.
    ///
    ///   require (VALID)
    ///   ensure (VALID)
    ///
    /// # Panics
    ///
    /// If no external propagator is connected. `CaDiCaL` would otherwise
    /// abort the process.
    ///
    #[inline]
    #[track_caller]
    pub fn reset_observed_vars(&mut self) {
        self.require_propagator("reset_observed_vars");
        ffi::reset_observed_vars(&mut self.solver);
    }

    /// Get reason of valid observed literal (true = it is an observed variable
    /// and it got assigned by a decision during the CDCL loop. Otherwise:
    /// false.
    ///
    ///   require (`VALID_OR_SOLVING`)
    ///   ensure (`VALID_OR_SOLVING`)
    ///
    #[inline]
    #[track_caller]
    pub fn is_decision(&mut self, lit: i32) -> bool {
        require_valid_lit("is_decision", lit);
        ffi::is_decision(&mut self.solver, lit)
    }

    //------------------------------------------------------------------------
    /// Adds a literal to the constraint clause. Same functionality as 'add'
    /// but the clause only exists for the next call to solve (same lifetime as
    /// assumptions). Only one constraint may exists at a time. A new
    /// constraint replaces the old. The main application of this functonality
    /// is the model checking algorithm IC3. See our FMCAD'21 paper
    /// [FroleyksBiere-FMCAD'19] for more details.
    ///
    /// Add valid literal to the constraint clause or zero to terminate it.
    ///
    ///   require (VALID)                     /// recall 'VALID = READY |
    ///   ADDING' if (lit) ensure (ADDING)            /// and thus VALID but not
    ///   READY if (!lit) && !`adding_clause` ensure (STEADY ) // and thus READY
    ///
    #[inline]
    #[track_caller]
    pub fn constrain(&mut self, lit: i32) {
        require_valid_lit_or_zero("constrain", lit);
        ffi::constrain(&mut self.solver, lit);
    }

    /// Determine whether the constraint was used to proof the
    /// unsatisfiability. Note that the formula might still be unsatisfiable
    /// without the constraint.
    ///
    ///   require (UNSATISFIED)
    ///   ensure (UNSATISFIED)
    ///
    /// # Panics
    ///
    /// If the solver is not in the `UNSATISFIED` state. `CaDiCaL` would otherwise abort the process.
    ///
    #[inline]
    #[track_caller]
    pub fn constraint_failed(&mut self) -> bool {
        self.require_state("constraint_failed", State::UNSATISFIED);
        ffi::constraint_failed(&mut self.solver)
    }

    //------------------------------------------------------------------------
    /// This function determines a good splitting literal.  The result can be
    /// zero if the formula is proven to be satisfiable or unsatisfiable.  This
    /// can then be checked by 'state ()'.  If the formula is empty and
    /// the function is not able to determine satisfiability also zero is
    /// returned but the state remains steady.
    ///
    ///   require (READY)
    ///   ensure (STEADY |SATISFIED|UNSATISFIED)
    ///
    /// # Panics
    ///
    /// If the solver is in the middle of adding a clause or constraint (not
    /// READY), which `CaDiCaL` would silently cut short.
    ///
    #[inline]
    #[track_caller]
    pub fn lookahead(&mut self) -> i32 {
        self.require_ready("lookahead");
        ffi::lookahead(&mut self.solver)
    }

    /// Generate cubes for cube-and-conquer, up to the given depth.
    ///
    /// Note: `CaDiCaL` 3.0.1 does not map the literals of the generated cubes
    /// back to the user's variable numbering (`External::generate_cubes`
    /// discards the mapped values), so after preprocessing has renumbered
    /// variables the cubes may refer to internal variables.
    ///
    #[inline]
    pub fn generate_cubes(&mut self, x: i32, min_depth: i32, result_cubes: &mut Vec<i32>) -> i32 {
        ffi::generate_cubes(&mut self.solver, x, min_depth, result_cubes)
    }

    /// # Panics
    ///
    /// If the solver is in the middle of adding a clause or constraint (not
    /// READY), which `CaDiCaL` would silently cut short.
    ///
    #[inline]
    #[track_caller]
    pub fn reset_assumptions(&mut self) {
        self.require_ready("reset_assumptions");
        ffi::reset_assumptions(&mut self.solver);
    }

    /// # Panics
    ///
    /// If the solver is in the middle of adding a clause or constraint (not
    /// READY), which `CaDiCaL` would silently cut short.
    ///
    #[inline]
    #[track_caller]
    pub fn reset_constraint(&mut self) {
        self.require_ready("reset_constraint");
        ffi::reset_constraint(&mut self.solver);
    }

    /// Return the current state of the solver as defined above.
    ///
    #[must_use]
    #[inline]
    pub fn state(&self) -> State {
        ffi::state(&self.solver).into()
    }

    /// Panics where `CaDiCaL` would abort the process on a contract violation,
    /// so misuse of the safe API is reported as a catchable Rust panic.
    #[track_caller]
    fn require(&self, function: &str, expected: State, lit: i32) {
        self.require_state(function, expected);
        require_valid_lit(function, lit);
    }

    #[track_caller]
    fn require_state(&self, function: &str, expected: State) {
        let state = self.state();
        assert!(
            state == expected,
            "{function} requires the solver to be in state {expected:?}, but it is in state {state:?}"
        );
    }

    #[track_caller]
    fn require_ready(&self, function: &str) {
        let state = self.state();
        assert!(
            (state as i32) & (State::READY as i32) != 0,
            "{function} requires the solver to be READY, but it is in state {state:?}"
        );
    }

    #[track_caller]
    fn require_one_of(&self, function: &str, expected: &[State]) {
        let state = self.state();
        assert!(
            expected.contains(&state),
            "{function} requires the solver to be in one of the states {expected:?}, but it is in state {state:?}"
        );
    }

    #[track_caller]
    fn require_proof_file(&self, function: &str) {
        assert!(
            self.proof_file_open,
            "{function} requires an open proof file (see trace_proof1 and trace_proof2)"
        );
    }

    fn update_declared_vars_only(&mut self) {
        self.factor_option = self.get("factor");
        self.factorcheck_option = self.get("factorcheck");
    }

    fn declared_vars_only(&self) -> bool {
        requires_declared_vars(self.factor_option, self.factorcheck_option)
    }

    #[track_caller]
    fn require_declared(&mut self, function: &str, lit: i32) {
        if self.declared_vars_only() {
            let vars = self.vars();
            assert!(
                lit.unsigned_abs() <= vars.unsigned_abs(),
                "{function} called with literal {lit} of an undeclared variable (only {vars} are declared, see declare_more_variables), which the 'factor'/'factorcheck' options forbid"
            );
        }
    }

    #[track_caller]
    fn require_no_closed_proof_file(&self, function: &str) {
        assert!(
            !self.proof_file_closed,
            "{function} cannot open a proof file after a proof file was closed"
        );
    }

    #[track_caller]
    fn require_propagator(&self, function: &str) {
        assert!(
            self.last_external_propagator.is_some(),
            "{function} requires a connected external propagator"
        );
    }

    /// Similar to 'state ()' but using the staddard competition exit codes of
    /// '10' for 'SATISFIABLE', '20' for 'UNSATISFIABLE' and '0' otherwise.
    ///
    #[must_use]
    #[inline]
    pub fn status(&self) -> Status {
        ffi::status(&self.solver).into()
    }

    /// return version string
    #[must_use]
    #[inline]
    pub fn version() -> String {
        ffi::version()
    }

    /// return the name and version of the incremental SAT solving library
    #[must_use]
    #[inline]
    pub fn signature() -> String {
        ffi::signature()
    }

    /*----------------------------------------------------------------------*/
    /// Copy 'this' into a fresh 'other'.  The copy procedure is not a deep
    /// clone, but only copies irredundant clauses and units.  It also makes
    /// sure that witness reconstruction works with the copy as with the
    /// original formula such that both solvers have the same models.
    /// Assumptions are not copied.  Options however are copied as well as
    /// flags which remember the current state of variables in preprocessing.
    ///
    ///   require (READY)          /// for 'this'
    ///   ensure (READY)           /// for 'this'
    ///
    ///   other.require (CONFIGURING)
    ///   other.ensure (CONFIGURING | STEADY )
    ///
    /// A pending constraint (see [`CaDiCal::constrain`]) is copied as an
    /// ordinary, permanent clause.
    ///
    /// # Panics
    ///
    /// If `source` is not READY (e.g. a clause was started with
    /// [`CaDiCal::add`] but not terminated), if `destination` is not in the
    /// `CONFIGURING` state, or if `source` has clauses (including frozen units)
    /// and the `factor` or `factorcheck` options of either solver require
    /// declared variables (the copy would add them before declaring any).
    /// `CaDiCaL` would otherwise abort the process.
    ///
    #[inline]
    #[track_caller]
    pub fn copy(source: &CaDiCal, destination: &mut CaDiCal) {
        source.require_ready("copy");
        destination.require_state("copy", State::CONFIGURING);
        // `Options::copy` only overwrites the destination's options where the
        // source's differ from the defaults (`factor` 0, `factorcheck` 1).
        let factor = if source.factor_option == 0 {
            destination.factor_option
        } else {
            source.factor_option
        };
        let factorcheck = if source.factorcheck_option == 1 {
            destination.factorcheck_option
        } else {
            source.factorcheck_option
        };
        if requires_declared_vars(factor, factorcheck) {
            // Traversal is aborted (returns false) at the first non-empty
            // clause, which would be added to the destination before it has
            // declared variables. (The empty clause of an inconsistent solver
            // has no literals, and units that are not frozen are copied as
            // witnesses instead.)
            struct StopAtFirstClause;
            impl ClauseIterator for StopAtFirstClause {
                fn clause(&mut self, clause: &[i32]) -> bool {
                    clause.is_empty()
                }
            }
            assert!(
                source.traverse_clauses(&mut StopAtFirstClause),
                "copy cannot copy clauses while the 'factor'/'factorcheck' options require declared variables"
            );
        }
        ffi::copy(&source.solver, &mut destination.solver);
        destination.update_declared_vars_only();
    }

    /*----------------------------------------------------------------------*/
    /// Variables are usually added and initialized implicitly whenever a
    /// literal is used as an argument except for the functions 'val', 'fixed',
    /// 'failed' and 'frozen'.  However, the library internally keeps a maximum
    /// variable index, which can be queried.
    ///
    ///   require (VALID | SOLVING)
    ///   ensure (VALID | SOLVING)
    ///
    #[inline]
    pub fn vars(&mut self) -> i32 {
        ffi::vars(&mut self.solver)
    }

    /// Increase the maximum variable index explicitly.  This function makes
    /// sure that at least '`min_max_var`' variables are initialized.  Since it
    /// might need to reallocate tables, it destroys a satisfying assignment
    /// and has the same state transition and conditions as 'assume' etc.
    ///
    ///   require (READY)
    ///   ensure (STEADY )
    ///
    /// # Panics
    ///
    /// If the solver is in the middle of adding a clause or constraint (not
    /// READY), which `CaDiCaL` would silently cut short.
    ///
    #[inline]
    #[track_caller]
    pub fn resize(&mut self, min_max_var: i32) {
        self.require_ready("resize");
        ffi::resize(&mut self.solver, min_max_var);
    }

    /// Increase the maximum variable index by a number of new variables.
    /// initializes '`number_of_additional_new_vars`' new variables and protects
    /// them from being used by the solver as extension variables (BVA).
    ///
    /// It returns the new maximum variable index which is the highest
    /// variable name of the consecutive range of newly declared variables.
    /// It has the same state transition and conditions as 'resize' above.
    ///
    ///   require (READY)
    ///   ensure (STEADY)
    ///
    /// # Panics
    ///
    /// If the solver is in the middle of adding a clause or constraint (not
    /// READY), which `CaDiCaL` would silently cut short, or if
    /// `number_of_additional_new_vars` is negative or would overflow the
    /// variable index.
    ///
    #[inline]
    #[track_caller]
    pub fn declare_more_variables(&mut self, number_of_additional_new_vars: i32) -> i32 {
        self.require_ready("declare_more_variables");
        let vars = self.vars();
        assert!(
            number_of_additional_new_vars >= 0
                && vars.checked_add(number_of_additional_new_vars).is_some(),
            "declare_more_variables called with {number_of_additional_new_vars} variables, but {vars} already exist"
        );
        ffi::declare_more_variables(&mut self.solver, number_of_additional_new_vars)
    }

    /// Returns the next fresh variable that was not used internally.
    ///
    /// # Panics
    ///
    /// If the solver is in the middle of adding a clause or constraint (not
    /// READY), which `CaDiCaL` would silently cut short.
    ///
    #[inline]
    #[track_caller]
    pub fn declare_one_more_variable(&mut self) -> i32 {
        self.require_ready("declare_one_more_variable");
        ffi::declare_one_more_variable(&mut self.solver)
    }

    /// Get the value of some statistics or -1 if the statistics does not
    /// exist or is not supported. Only requires the state to be initialized.
    ///
    #[must_use]
    #[inline]
    pub fn get_statistic_value(&self, name: &str) -> i64 {
        ffi::get_statistic_value(&self.solver, name.to_owned())
    }

    /// Renamed to [`CaDiCal::resize`] in `CaDiCaL` 3.
    #[deprecated(since = "0.8.0", note = "renamed to `resize` in CaDiCaL 3")]
    #[inline]
    pub fn reserve(&mut self, min_max_var: i32) {
        self.resize(min_max_var);
    }

    // pub fn `trace_api_calls(&mut` self, file: String);

    //------------------------------------------------------------------------
    /// Option handling.
    /// Determine whether 'name' is a valid option name.
    ///
    #[must_use]
    #[inline]
    pub fn is_valid_option(name: &str) -> bool {
        ffi::is_valid_option(name.to_owned())
    }

    /// Determine whether 'name' enables a specific preprocessing technique.
    ///
    #[must_use]
    #[inline]
    pub fn is_preprocessing_option(name: &str) -> bool {
        ffi::is_preprocessing_option(name.to_owned())
    }

    /// Determine whether 'arg' is a valid long option of the form `--<name>`,
    /// `--<name>=<val>` or `--no-<name>` similar to '`set_long_option`' below.
    /// Legal values are 'true', 'false', or `[-]<mantissa>[e<exponent>]`.
    #[must_use]
    #[inline]
    pub fn is_valid_long_option(arg: &str) -> bool {
        ffi::is_valid_long_option(arg.to_owned())
    }

    /// Get the current value of the option 'name'.  If 'name' is invalid then
    /// zero is returned.  Here '--...' arguments as invalid options.
    ///
    #[inline]
    pub fn get(&mut self, name: &str) -> i32 {
        ffi::get(&mut self.solver, name.to_owned())
    }

    /// Set the default verbose message prefix (default "c ").
    ///
    #[inline]
    pub fn prefix(&mut self, verbose_message_prefix: &str) {
        ffi::prefix(&mut self.solver, verbose_message_prefix.to_owned());
    }

    /// This crate builds `CaDiCaL` with `QUIET`, which removes the options
    /// `quiet`, `verbose`, `report` and `log`; setting them returns false.
    ///
    /// Explicit version of setting an option.  If the option `<name>` exists
    /// and `<val>` can be parsed then 'true' is returned.  If the option value
    /// is out of range the actual value is computed as the closest (minimum or
    /// maximum) value possible, but still 'true' is returned.
    ///
    ///   require (CONFIGURING)
    ///   ensure (CONFIGURING)
    ///
    /// Thus options can only bet set right after initialization.
    ///
    /// # Panics
    ///
    /// If the solver is not in the `CONFIGURING` state, unless `name` is one of
    /// `log`, `quiet`, `report` and `verbose`. `CaDiCaL` would otherwise abort the process.
    ///
    #[inline]
    #[track_caller]
    pub fn set(&mut self, name: &str, val: i32) -> bool {
        if !matches!(name, "log" | "quiet" | "report" | "verbose") {
            self.require_state("set", State::CONFIGURING);
        }
        let res = ffi::set(&mut self.solver, name.to_owned(), val);
        self.update_declared_vars_only();
        res
    }

    /// This function accepts options in command line syntax:
    ///
    ///   `--<name>=<val>`, `--<name>`, or `--no-<name>`
    ///
    /// It actually calls the previous 'set' function after parsing 'arg'.  The
    /// same values are expected as for '`is_valid_long_option`' above and as
    /// with 'set' any value outside of the range of legal values for a
    /// particular option are set to either the minimum or maximum depending on
    /// which side of the valid interval they lie.
    ///
    ///   require (CONFIGURING)
    ///   ensure (CONFIGURING)
    ///
    /// # Panics
    ///
    /// If the solver is not in the `CONFIGURING` state. `CaDiCaL` would otherwise abort the process.
    ///
    #[inline]
    #[track_caller]
    pub fn set_long_option(&mut self, arg: &str) -> bool {
        self.require_state("set_long_option", State::CONFIGURING);
        let res = ffi::set_long_option(&mut self.solver, arg.to_owned());
        self.update_declared_vars_only();
        res
    }

    /// Determine whether 'name' is a valid configuration.
    ///
    #[must_use]
    #[inline]
    pub fn is_valid_configuration(name: &str) -> bool {
        ffi::is_valid_configuration(name.to_owned())
    }

    /// Overwrite (some) options with the forced values of the configuration.
    /// The result is 'true' iff the 'name' is a valid configuration.
    ///
    ///   require (CONFIGURING)
    ///   ensure (CONFIGURING)
    ///
    /// # Panics
    ///
    /// If the solver is not in the `CONFIGURING` state. `CaDiCaL` would otherwise abort the process.
    ///
    #[inline]
    #[track_caller]
    pub fn configure(&mut self, name: &str) -> bool {
        self.require_state("configure", State::CONFIGURING);
        let res = ffi::configure(&mut self.solver, name.to_owned());
        self.update_declared_vars_only();
        res
    }

    /// Increase preprocessing and inprocessing limits: each limit marked as
    /// optimizable is multiplied by `2^<val>` or `10^<val>` (depending on the
    /// option) and capped at its maximum. Values below '0' are ignored and
    /// values above '31' are reduced to '31'.
    ///
    ///   require (READY)
    ///   ensure (READY)
    ///
    #[inline]
    pub fn optimize(&mut self, val: i32) {
        ffi::optimize(&mut self.solver, val);
    }

    /// Specify search limits, where currently 'name' can be "conflicts",
    /// "decisions", "preprocessing", or "localsearch".  The first two limits
    /// are unbounded by default.  Thus using a negative limit for conflicts or
    /// decisions switches back to the default of unlimited search (for that
    /// particular limit).  The preprocessing limit determines the number of
    /// preprocessing rounds, which is zero by default.  Similarly, the local
    /// search limit determines the number of local search rounds (also zero by
    /// default).  As with 'set', the return value denotes whether the limit
    /// 'name' is valid.  These limits are only valid for the next 'solve' or
    /// 'simplify' call and reset to their default after 'solve' returns (as
    /// well as overwritten and reset during calls to 'simplify' and
    /// 'lookahead').  We actually also have an internal "terminate" limit
    /// which however should only be used for testing and debugging.
    ///
    ///   require (READY)
    ///   ensure (READY)
    ///
    #[inline]
    pub fn limit(&mut self, arg: &str, val: i32) -> bool {
        ffi::limit(&mut self.solver, arg.to_owned(), val)
    }
    #[inline]
    pub fn is_valid_limit(&mut self, arg: &str) -> bool {
        ffi::is_valid_limit(&mut self.solver, arg.to_owned())
    }

    /// The number of currently active variables and clauses can be queried by
    /// these functions.  Variables become active if a clause is added with it.
    /// They become inactive if they are eliminated or fixed at the root level
    /// Clauses become inactive if they are satisfied, subsumed, eliminated.
    /// Redundant clauses are reduced regularly and thus the 'redundant'
    /// function is less useful.
    ///
    ///   require (VALID)
    ///   ensure (VALID)
    ///
    /// Number of active variables.
    #[must_use]
    #[inline]
    pub fn active(&self) -> i32 {
        ffi::active(&self.solver)
    }

    /// Number of active redundant clauses.
    #[must_use]
    #[inline]
    pub fn redundant(&self) -> i64 {
        ffi::redundant(&self.solver)
    }

    /// Number of active irredundant clauses.
    #[must_use]
    #[inline]
    pub fn irredundant(&self) -> i64 {
        ffi::irredundant(&self.solver)
    }

    //------------------------------------------------------------------------
    /// This function executes the given number of preprocessing rounds. It is
    /// similar to 'solve' with 'limits ("preprocessing", rounds)' except that
    /// no CDCL nor local search, nor lucky phases are executed.  The result
    /// values are also the same: 0=UNKNOWN, 10=SATISFIABLE, 20=UNSATISFIABLE.
    /// As 'solve' it resets current assumptions and limits before returning.
    /// The numbers of rounds should not be negative.  If the number of rounds
    /// is zero only clauses are restored (if necessary) and top level unit
    /// propagation is performed, which both take some time.
    ///
    ///   require (READY)
    ///   ensure (INCONCLUSIVE | SATISFIED | UNSATISFIED)
    ///
    /// # Panics
    ///
    /// If the solver is in the middle of adding a clause or constraint (not READY),
    /// or if `rounds` is negative. `CaDiCaL` would otherwise abort the process.
    ///
    #[inline]
    #[track_caller]
    pub fn simplify(&mut self, rounds: i32) -> Status {
        self.require_ready("simplify");
        assert!(rounds >= 0, "simplify called with negative rounds {rounds}");
        ffi::simplify(&mut self.solver, rounds).into()
    }

    /// This function executes the given number of preprocessing rounds
    /// without search: it only performs unit propagation by assuming the
    /// currently defined (potentially empty) set of assumptions. In case unit
    /// propagation leads to a conflict it returns `UNSATISFIABLE`. Otherwise
    /// it usually returns `UNKNOWN`, and the implied literals can be queried
    /// with [`CaDiCal::implied`]. In rare cases (no decision needed) it
    /// returns `SATISFIABLE`.
    ///
    ///   require (READY)
    ///   ensure (INCONCLUSIVE | SATISFIED | UNSATISFIED)
    ///
    /// # Panics
    ///
    /// If the solver is in the middle of adding a clause or constraint (not
    /// READY), which `CaDiCaL` would silently cut short.
    ///
    #[inline]
    #[track_caller]
    pub fn propagate(&mut self) -> Status {
        self.require_ready("propagate");
        ffi::propagate(&mut self.solver).into()
    }

    /// The literals implied by the last call to [`CaDiCal::propagate`].
    ///
    ///   require (INCONCLUSIVE | SATISFIED)
    ///   ensure (INCONCLUSIVE | SATISFIED)
    ///
    /// # Panics
    ///
    /// If the solver is not in the `INCONCLUSIVE` or `SATISFIED` state.
    /// `CaDiCaL` would otherwise abort the process.
    ///
    #[must_use]
    #[track_caller]
    pub fn implied(&mut self) -> Vec<i32> {
        self.require_one_of("implied", &[State::INCONCLUSIVE, State::SATISFIED]);
        let mut implicants = Vec::new();
        ffi::implied(&mut self.solver, &mut implicants);
        implicants
    }

    //------------------------------------------------------------------------
    /// Force termination of 'solve' asynchronously.
    ///
    /// Since `solve` borrows the solver mutably, this can only be called
    /// between `solve` calls, where it makes the next `solve` return
    /// [`Status::UNKNOWN`] (unless the formula is trivially decided, e.g.
    /// already inconsistent). To stop a running `solve` from another thread,
    /// connect a [`TerminateFlag`] instead.
    ///
    ///  require (SOLVING | READY)
    ///  ensure (STEADY )           /// actually not immediately (synchronously)
    ///
    #[inline]
    pub fn terminate(&mut self) {
        ffi::terminate(&mut self.solver);
    }

    //------------------------------------------------------------------------

    /// We have the following common reference counting functions, which avoid
    /// to restore clauses but require substantial user guidance.  This was the
    /// only way to use inprocessing in incremental SAT solving in Lingeling
    /// (and before in `MiniSAT`'s 'freeze' / 'thaw') and which did not use
    /// automatic clause restoring.  In general this is slower than
    /// restoring clauses and should not be used.
    ///
    /// In essence the user freezes variables which potentially are still
    /// needed in clauses added or assumptions used after the next 'solve'
    /// call.  As in Lingeling you can freeze a variable multiple times, but
    /// then have to melt it the same number of times again in order to enable
    /// variable eliminating on it etc.  The arguments can be literals
    /// (negative indices) but conceptually variables are frozen.
    ///
    /// In the old way of doing things without restore you should not use a
    /// variable incrementally (in 'add' or 'assume'), which was used before
    /// and potentially could have been eliminated in a previous 'solve' call.
    /// This can lead to spurious satisfying assignment.  In order to check
    /// this API contract one can use the 'checkfrozen' option.  This has the
    /// drawback that restoring clauses implicitly would fail with a fatal
    /// error message even if in principle the solver could just restore
    /// clauses. Thus this option is disabled by default.
    ///
    /// See our SAT'19 paper [FazekasBiereScholl-SAT'19] for more details.
    ///
    ///   require (VALID)
    ///   ensure (VALID)
    ///
    #[must_use]
    #[inline]
    #[track_caller]
    pub fn frozen(&self, lit: i32) -> bool {
        require_valid_lit("frozen", lit);
        ffi::frozen(&self.solver, lit)
    }

    #[inline]
    #[track_caller]
    pub fn freeze(&mut self, lit: i32) {
        require_valid_lit("freeze", lit);
        ffi::freeze(&mut self.solver, lit);
    }

    /// Undo one [`CaDiCal::freeze`] of `lit`.
    ///
    /// # Panics
    ///
    /// If `lit` is not frozen. `CaDiCaL` would otherwise abort the process.
    ///
    #[inline]
    #[track_caller]
    pub fn melt(&mut self, lit: i32) {
        require_valid_lit("melt", lit);
        assert!(
            self.frozen(lit),
            "melt called on literal {lit}, which is not frozen"
        );
        ffi::melt(&mut self.solver, lit);
    }

    //------------------------------------------------------------------------
    /// Root level assigned variables can be queried with this function.
    /// It returns '1' if the literal is implied by the formula, '-1' if its
    /// negation is implied, or '0' if this is unclear at this point.
    ///
    ///   require (VALID)
    ///   ensure (VALID)
    ///
    #[must_use]
    #[inline]
    #[track_caller]
    pub fn fixed(&self, lit: i32) -> i32 {
        require_valid_lit("fixed", lit);
        ffi::fixed(&self.solver, lit)
    }

    //------------------------------------------------------------------------
    /// Force the default decision phase of a variable to a certain value.
    ///
    #[inline]
    #[track_caller]
    pub fn phase(&mut self, lit: i32) {
        require_valid_lit("phase", lit);
        ffi::phase(&mut self.solver, lit);
    }

    #[inline]
    #[track_caller]
    pub fn unphase(&mut self, lit: i32) {
        require_valid_lit("unphase", lit);
        ffi::unphase(&mut self.solver, lit);
    }

    //------------------------------------------------------------------------
    /// Enables clausal proof tracing in DRAT format and returns 'true' if
    /// successfully opened for writing.  Writing proofs has to be enabled
    /// before calling 'solve', 'add' and 'dimacs', that is in state
    /// 'CONFIGURING'.  Otherwise only partial proofs would be written.
    ///
    ///   require (CONFIGURING)
    ///   ensure (CONFIGURING)
    ///
    /// Write DRAT proof. `name` is ignored. As with [`CaDiCal::trace_proof2`],
    /// a `.gz`, `.bz2`, `.xz` or `.7z` suffix compresses the proof through
    /// the external program of that name, and `false` is returned if it is
    /// not in `PATH`.
    ///
    /// # Panics
    ///
    /// If the solver is not in the `CONFIGURING` state, or a proof file was
    /// already closed with [`CaDiCal::close_proof_trace`]. `CaDiCaL` would
    /// otherwise abort or crash.
    ///
    #[inline]
    #[track_caller]
    pub fn trace_proof1(&mut self, file: &str, name: &str) -> bool {
        self.require_state("trace_proof1", State::CONFIGURING);
        self.require_no_closed_proof_file("trace_proof1");
        let opened = ffi::trace_proof1(&mut self.solver, file.to_owned(), name.to_owned());
        self.proof_file_open |= opened;
        opened
    }

    /// Open & write proof. A `.gz`, `.bz2`, `.xz` or `.7z` suffix compresses
    /// the proof through the external program of that name; `false` is
    /// returned if it is not in `PATH` or the file cannot be written.
    ///
    /// # Panics
    ///
    /// If the solver is not in the `CONFIGURING` state, or a proof file was
    /// already closed with [`CaDiCal::close_proof_trace`]. `CaDiCaL` would
    /// otherwise abort or crash.
    ///
    #[inline]
    #[track_caller]
    pub fn trace_proof2(&mut self, path: &str) -> bool {
        self.require_state("trace_proof2", State::CONFIGURING);
        self.require_no_closed_proof_file("trace_proof2");
        let opened = ffi::trace_proof2(&mut self.solver, path.to_owned());
        self.proof_file_open |= opened;
        opened
    }

    /// Flushing the proof trace file eventually calls 'fflush' on the actual
    /// file or pipe and thus if this function returns all the proof steps
    /// should have been written (with the same guarantees as 'fflush').
    ///
    /// The additional optional argument forces to print the number of addition
    /// and deletion steps in the proof even if the verbosity level is zero but
    /// not if quiet is set as well.  The default for the stand-alone solver is
    /// to print this information (in the 'closing proof' section) but for API
    /// usage of the library we want to stay silent unless explicitly requested
    /// or verbosity is non-zero (and as explained quiet is not set).
    ///
    /// This function can be called multiple times.
    ///
    ///   require (VALID)
    ///   ensure (VALID)
    ///
    /// # Panics
    ///
    /// If no proof file is open (see [`CaDiCal::trace_proof2`]). `CaDiCaL`
    /// would otherwise abort the process.
    ///
    #[inline]
    #[track_caller]
    pub fn flush_proof_trace(&mut self, print: bool) {
        self.require_proof_file("flush_proof_trace");
        ffi::flush_proof_trace(&mut self.solver, print);
    }

    /// Close proof trace early.  Similar to 'flush' we allow the user to
    /// control with 'print' in a more fine-grained way whether statistics
    /// about the size of the written proof file and if compressed on-the-fly
    /// the number of actual bytes written (including deflation percentage) are
    /// printed.  Before actually closing (or detaching in case of writing to
    /// `<stdout>`) we check whether '`flush_proof_trace`' was called since the
    /// last time a proof step (addition or deletion) was traced.  If this is
    /// not the case we would call '`flush_proof_trace`' with the same 'print'
    /// argument.
    ///
    ///   require (VALID)
    ///   ensure (VALID)
    ///
    /// # Panics
    ///
    /// If no proof file is open, including when it was already closed.
    /// `CaDiCaL` would otherwise abort the process.
    ///
    #[inline]
    #[track_caller]
    pub fn close_proof_trace(&mut self, print: bool) {
        self.require_proof_file("close_proof_trace");
        self.proof_file_open = false;
        self.proof_file_closed = true;
        ffi::close_proof_trace(&mut self.solver, print);
    }

    /// Enables clausal proof tracing with or without antecedents using
    /// the Tracer interface defined in 'tracer.hpp'.
    ///
    /// `CaDiCaL`'s built-in `FileTracer` and `StatTracer` are not exposed
    /// directly; use [`CaDiCal::trace_proof1`] or [`CaDiCal::trace_proof2`]
    /// to write a proof file.
    ///
    ///   require (CONFIGURING)
    ///   ensure (CONFIGURING)
    ///
    /// The solver takes ownership of `tracer` and drops it when it is
    /// disconnected, replaced, or the solver is dropped. To read its state
    /// afterwards, pass an `Rc<RefCell<_>>` and keep a clone of the `Rc`.
    /// Connecting a tracer disconnects any tracer connected earlier.
    ///
    /// [`ProofTracer::finalize_clause`] is only called when `finalize_clauses`
    /// is true.
    ///
    /// # Panics
    ///
    /// If the solver is not in the `CONFIGURING` state, i.e. clauses have
    /// already been added. `CaDiCaL` would otherwise abort the process.
    ///
    #[allow(clippy::too_many_lines)]
    #[track_caller]
    pub fn connect_proof_tracer1<T: ProofTracer + 'static>(
        &mut self,
        tracer: T,
        antecedents: bool,
        finalize_clauses: bool,
    ) {
        fn add_original_clause<T: ProofTracer>(
            state: *mut u8,
            id: i64,
            redundant: bool,
            clause: &[i32],
            restored: bool,
        ) {
            let ptr: *mut T = state.cast::<T>();
            let t = unsafe { &mut *ptr };
            t.add_original_clause(id, redundant, clause, restored);
        }

        fn add_derived_clause<T: ProofTracer>(
            state: *mut u8,
            id: i64,
            redundant: bool,
            witness: i32,
            clause: &[i32],
            antecedents: &[i64],
        ) {
            let ptr: *mut T = state.cast::<T>();
            let t = unsafe { &mut *ptr };
            t.add_derived_clause(id, redundant, witness, clause, antecedents);
        }

        fn delete_clause<T: ProofTracer>(state: *mut u8, id: i64, redundant: bool, clause: &[i32]) {
            let ptr: *mut T = state.cast::<T>();
            let t = unsafe { &mut *ptr };
            t.delete_clause(id, redundant, clause);
        }

        fn weaken_minus<T: ProofTracer>(state: *mut u8, id: i64, clause: &[i32]) {
            let ptr: *mut T = state.cast::<T>();
            let t = unsafe { &mut *ptr };
            t.weaken_minus(id, clause);
        }

        fn strengthen<T: ProofTracer>(state: *mut u8, id: i64) {
            let ptr: *mut T = state.cast::<T>();
            let t = unsafe { &mut *ptr };
            t.strengthen(id);
        }

        fn finalize_clause<T: ProofTracer>(state: *mut u8, id: i64, clause: &[i32]) {
            let ptr: *mut T = state.cast::<T>();
            let t = unsafe { &mut *ptr };
            t.finalize_clause(id, clause);
        }

        fn add_assumption<T: ProofTracer>(state: *mut u8, lit: i32) {
            let ptr: *mut T = state.cast::<T>();
            let t = unsafe { &mut *ptr };
            t.add_assumption(lit);
        }

        fn add_constraint<T: ProofTracer>(state: *mut u8, clause: &[i32]) {
            let ptr: *mut T = state.cast::<T>();
            let t = unsafe { &mut *ptr };
            t.add_constraint(clause);
        }

        fn reset_assumptions<T: ProofTracer>(state: *mut u8) {
            let ptr: *mut T = state.cast::<T>();
            let t = unsafe { &mut *ptr };
            t.reset_assumptions();
        }

        fn add_assumption_clause<T: ProofTracer>(
            state: *mut u8,
            id: i64,
            clause: &[i32],
            antecedents: &[i64],
        ) {
            let ptr: *mut T = state.cast::<T>();
            let t = unsafe { &mut *ptr };
            t.add_assumption_clause(id, clause, antecedents);
        }

        fn conclude_sat<T: ProofTracer>(state: *mut u8, conclusion_type: i32, model: &[i32]) {
            let ptr: *mut T = state.cast::<T>();
            let t = unsafe { &mut *ptr };
            t.conclude_sat(conclusion_type, model);
        }

        fn conclude_unsat<T: ProofTracer>(
            state: *mut u8,
            conclusion_type: i32,
            clause_ids: &[i64],
        ) {
            let ptr: *mut T = state.cast::<T>();
            let t = unsafe { &mut *ptr };
            t.conclude_unsat(conclusion_type, clause_ids);
        }

        fn conclude_unknown<T: ProofTracer>(state: *mut u8, trail: &[i32]) {
            let ptr: *mut T = state.cast::<T>();
            let t = unsafe { &mut *ptr };
            t.conclude_unknown(trail);
        }

        fn demote_clause<T: ProofTracer>(state: *mut u8, id: i64, clause: &[i32]) {
            let ptr: *mut T = state.cast::<T>();
            let t = unsafe { &mut *ptr };
            t.demote_clause(id, clause);
        }

        fn report_status<T: ProofTracer>(state: *mut u8, status: i32, id: i64) {
            let ptr: *mut T = state.cast::<T>();
            let t = unsafe { &mut *ptr };
            t.report_status(status, id);
        }

        fn begin_proof<T: ProofTracer>(state: *mut u8, first_derived_id: i64) {
            let ptr: *mut T = state.cast::<T>();
            let t = unsafe { &mut *ptr };
            t.begin_proof(first_derived_id);
        }

        fn solve_query<T: ProofTracer>(state: *mut u8) {
            let ptr: *mut T = state.cast::<T>();
            let t = unsafe { &mut *ptr };
            t.solve_query();
        }

        fn notify_equivalence<T: ProofTracer>(state: *mut u8, lit: i32, other: i32) {
            let ptr: *mut T = state.cast::<T>();
            let t = unsafe { &mut *ptr };
            t.notify_equivalence(lit, other);
        }

        let solver_state = self.state();
        assert!(
            solver_state == State::CONFIGURING,
            "connect_proof_tracer1 requires the solver to be in state CONFIGURING, but it is in state {solver_state:?}"
        );
        // Unlike the other callbacks, CaDiCaL keeps every connected tracer, so
        // the previous one must be disconnected before it is dropped.
        self.disconnect_proof_tracer1();

        let mut tracer = Connected::new(tracer, |state| unsafe {
            ffi::new_tracer(
                state,
                add_original_clause::<T>,
                add_derived_clause::<T>,
                delete_clause::<T>,
                weaken_minus::<T>,
                strengthen::<T>,
                finalize_clause::<T>,
                add_assumption::<T>,
                add_constraint::<T>,
                reset_assumptions::<T>,
                add_assumption_clause::<T>,
                conclude_sat::<T>,
                conclude_unsat::<T>,
                conclude_unknown::<T>,
                demote_clause::<T>,
                report_status::<T>,
                begin_proof::<T>,
                solve_query::<T>,
                notify_equivalence::<T>,
            )
        });
        ffi::connect_proof_tracer1(
            &mut self.solver,
            &mut tracer.wrapper,
            antecedents,
            finalize_clauses,
        );
        self.last_tracer = Some(tracer);
    }

    /// Triggers the conclusion of incremental proofs.
    /// if the solver is SATISFIED it will trigger extend ()
    /// and give the model to the proof tracer through `conclude_sat` ()
    /// if the solver is UNSATISFIED it will trigger failing ()
    /// which will learn new clauses as explained below:
    /// In case of failed assumptions will provide a core negated
    /// as a clause through the proof tracer interface.
    /// With a failing contraint these can be multiple clauses.
    /// Then it will trigger a `conclude_unsat` event with the id(s)
    /// of the newly learnt clauses or the id of the global conflict.
    ///
    ///   require (SATISFIED || UNSATISFIED)
    ///   ensure (SATISFIED || UNSATISFIED)
    ///
    /// # Panics
    ///
    /// If the solver has not finished a `solve` (it is not `SATISFIED`,
    /// `UNSATISFIED` or `INCONCLUSIVE`). `CaDiCaL` would otherwise abort the process.
    ///
    #[inline]
    #[track_caller]
    pub fn conclude(&mut self) {
        self.require_one_of(
            "conclude",
            &[State::SATISFIED, State::UNSATISFIED, State::INCONCLUSIVE],
        );
        ffi::conclude(&mut self.solver);
    }

    /// Disconnect the proof tracer connected with
    /// [`CaDiCal::connect_proof_tracer1`] and drop it. Does nothing if no
    /// tracer is connected.
    ///
    ///   require (VALID)
    ///   ensure (VALID)
    ///
    pub fn disconnect_proof_tracer1(&mut self) {
        if let Some(mut tracer) = self.last_tracer.take() {
            ffi::disconnect_proof_tracer1(&mut self.solver, &mut tracer.wrapper);
        }
    }

    /// print usage information for long options
    #[inline]
    pub fn usage() {
        ffi::usage();
    }

    /// print configuration usage options
    #[inline]
    pub fn configurations() {
        ffi::configurations();
    }

    ///   require (!DELETING)
    ///   ensure (!DELETING)
    ///
    /// print statistics
    ///
    /// This crate builds `CaDiCaL` with `QUIET`, so this prints nothing.
    #[inline]
    pub fn statistics(&mut self) {
        ffi::statistics(&mut self.solver);
    }

    /// print resource usage (time and memory)
    ///
    /// This crate builds `CaDiCaL` with `QUIET`, so this prints nothing.
    #[inline]
    pub fn resources(&mut self) {
        ffi::resources(&mut self.solver);
    }

    ///   require (VALID)
    ///   ensure (VALID)
    ///
    /// print current option and value list
    ///
    /// This crate builds `CaDiCaL` with `QUIET`, so this prints nothing.
    #[inline]
    pub fn options(&mut self) {
        ffi::options(&mut self.solver);
    }

    //------------------------------------------------------------------------
    /// Traverse irredundant clauses or the extension stack in reverse order.
    ///
    /// The return value is false if traversal is aborted early due to one of
    /// the visitor functions returning false.  See description of the
    /// iterators below for more details on how to use these functions.
    ///
    ///   require (VALID)
    ///   ensure (VALID)
    ///
    #[inline]
    pub fn traverse_clauses<I: ClauseIterator>(&self, i: &mut I) -> bool {
        fn f<I: ClauseIterator>(state: *mut u8, clause: &[i32]) -> bool {
            let ptr: *mut I = state.cast::<I>();
            let i = unsafe { &mut *ptr };
            i.clause(clause)
        }
        let mut iter =
            unsafe { ffi::new_clause_iterator(std::ptr::from_mut(i).cast::<u8>(), f::<I>) };
        ffi::traverse_clauses(&self.solver, &mut iter)
    }

    #[inline]
    pub fn traverse_witnesses_backward<I: WitnessIterator>(&self, i: &mut I) -> bool {
        fn f<I: WitnessIterator>(state: *mut u8, clause: &[i32], witness: &[i32], id: i64) -> bool {
            let ptr: *mut I = state.cast::<I>();
            let i = unsafe { &mut *ptr };
            i.witness(clause, witness, id)
        }
        let mut iter =
            unsafe { ffi::new_witness_iterator(std::ptr::from_mut(i).cast::<u8>(), f::<I>) };
        ffi::traverse_witnesses_backward(&self.solver, &mut iter)
    }

    #[inline]
    pub fn traverse_witnesses_forward<I: WitnessIterator>(&self, i: &mut I) -> bool {
        fn f<I: WitnessIterator>(state: *mut u8, clause: &[i32], witness: &[i32], id: i64) -> bool {
            let ptr: *mut I = state.cast::<I>();
            let i = unsafe { &mut *ptr };
            i.witness(clause, witness, id)
        }
        let mut iter =
            unsafe { ffi::new_witness_iterator(std::ptr::from_mut(i).cast::<u8>(), f::<I>) };
        ffi::traverse_witnesses_forward(&self.solver, &mut iter)
    }

    //------------------------------------------------------------------------
    /// Files with explicit path argument support compressed input and output
    /// if appropriate helper functions 'gzip' etc. are available.  They are
    /// called through opening a pipe to an external command.
    ///
    /// If the 'strict' argument is zero then the number of variables and
    /// clauses specified in the DIMACS headers are ignored, i.e., the header
    /// 'p cnf 0 0' is always legal.  If the 'strict' argument is larger '1'
    /// strict formatting of the header is required, i.e., single spaces
    /// everywhere and no trailing white space.
    ///
    /// Returns `Err` with `CaDiCaL`'s error message if unsuccessful.
    ///
    ///   require (VALID)
    ///   ensure (VALID)
    ///
    /// # Errors
    ///
    /// If the file cannot be opened or parsed.
    ///
    /// # Panics
    ///
    /// If the solver is not in the `CONFIGURING` state, i.e. clauses have
    /// already been added. `CaDiCaL` would otherwise abort the process.
    ///
    #[inline]
    #[track_caller]
    pub fn read_dimacs1(
        &mut self,
        file: &str,
        name: &str,
        vars: &mut i32,
        strict: i32,
    ) -> Result<(), String> {
        self.require_state("read_dimacs1", State::CONFIGURING);
        let res = ffi::read_dimacs1(
            &mut self.solver,
            file.to_owned(),
            name.to_owned(),
            vars,
            strict,
        );
        // 'c --option' lines in the header set options from C++.
        self.update_declared_vars_only();
        into_result(res)
    }

    /// # Errors
    ///
    /// If the file cannot be opened or parsed.
    ///
    /// # Panics
    ///
    /// If the solver is not in the `CONFIGURING` state, i.e. clauses have
    /// already been added. `CaDiCaL` would otherwise abort the process.
    ///
    #[inline]
    #[track_caller]
    pub fn read_dimacs2(&mut self, path: &str, vars: &mut i32, strict: i32) -> Result<(), String> {
        self.require_state("read_dimacs2", State::CONFIGURING);
        let res = ffi::read_dimacs2(&mut self.solver, path.to_owned(), vars, strict);
        // 'c --option' lines in the header set options from C++.
        self.update_declared_vars_only();
        into_result(res)
    }

    /// The following routines work the same way but parse both DIMACS and
    /// INCCNF files (with 'p inccnf' header and `a <cube>` lines).  If the
    /// parser finds and 'p inccnf' header or cubes then '*incremental' is set
    /// to true and the cubes are stored in the given vector (each cube
    /// terminated by a zero).
    ///
    /// # Errors
    ///
    /// If the file cannot be opened or parsed.
    ///
    /// # Panics
    ///
    /// If the solver is not in the `CONFIGURING` state, i.e. clauses have
    /// already been added. `CaDiCaL` would otherwise abort the process.
    ///
    #[inline]
    #[track_caller]
    pub fn read_dimacs3(
        &mut self,
        file: &str,
        name: &str,
        vars: &mut i32,
        strict: i32,
        incremental: &mut bool,
        cubes: &mut Vec<i32>,
    ) -> Result<(), String> {
        self.require_state("read_dimacs3", State::CONFIGURING);
        let res = ffi::read_dimacs3(
            &mut self.solver,
            file.to_owned(),
            name.to_owned(),
            vars,
            strict,
            incremental,
            cubes,
        );
        // 'c --option' lines in the header set options from C++.
        self.update_declared_vars_only();
        into_result(res)
    }

    /// # Errors
    ///
    /// If the file cannot be opened or parsed.
    ///
    /// # Panics
    ///
    /// If the solver is not in the `CONFIGURING` state, i.e. clauses have
    /// already been added. `CaDiCaL` would otherwise abort the process.
    ///
    #[inline]
    #[track_caller]
    pub fn read_dimacs4(
        &mut self,
        path: &str,
        vars: &mut i32,
        strict: i32,
        incremental: &mut bool,
        cubes: &mut Vec<i32>,
    ) -> Result<(), String> {
        self.require_state("read_dimacs4", State::CONFIGURING);
        let res = ffi::read_dimacs4(
            &mut self.solver,
            path.to_owned(),
            vars,
            strict,
            incremental,
            cubes,
        );
        // 'c --option' lines in the header set options from C++.
        self.update_declared_vars_only();
        into_result(res)
    }

    //------------------------------------------------------------------------
    /// Write current irredundant clauses and all derived unit clauses
    /// to a file in DIMACS format.  Clauses on the extension stack are
    /// not included, nor any redundant clauses.
    ///
    /// The '`min_max_var`' parameter gives a lower bound on the number `<vars>`
    /// of variables used in the DIMACS `p cnf <vars> ...` header.
    ///
    /// Returns `Err` with `CaDiCaL`'s error message if unsuccessful.
    ///
    ///   require (VALID)
    ///   ensure (VALID)
    ///
    /// # Errors
    ///
    /// If the file cannot be written.
    ///
    #[inline]
    pub fn write_dimacs(&mut self, path: &str, min_max_var: i32) -> Result<(), String> {
        into_result(ffi::write_dimacs(
            &mut self.solver,
            path.to_owned(),
            min_max_var,
        ))
    }

    /// The extension stack for reconstruction a solution can be written too.
    ///
    /// # Errors
    ///
    /// If the file cannot be written.
    ///
    #[inline]
    pub fn write_extension(&mut self, path: &str) -> Result<(), String> {
        into_result(ffi::write_extension(&mut self.solver, path.to_owned()))
    }

    /// Print build configuration to a file with prefix 'c '.  If the file
    /// is `<stdout>` or `<stderr>` then terminal color codes might be used.
    ///
    /// # Errors
    ///
    /// If the file cannot be opened.
    ///
    #[inline]
    pub fn build(file: &str, prefix: &str) -> Result<(), String> {
        into_result(ffi::build(file.to_owned(), prefix.to_owned()))
    }
}

/// Connected terminators are checked for termination regularly.  If the
/// 'terminate' function of the terminator returns true the solver is
/// terminated synchronously as soon it calls this function.
pub trait Terminator {
    fn terminated(&mut self) -> bool;
}

/// A [`Terminator`] that can be triggered from any thread, e.g. to stop a
/// long-running [`CaDiCal::solve`] after a timeout. Clones share the same flag.
#[derive(Debug, Clone, Default)]
pub struct TerminateFlag(Arc<AtomicBool>);

impl TerminateFlag {
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// Ask the solver to stop as soon as possible; `solve` then returns
    /// [`Status::UNKNOWN`] unless it has already decided the formula.
    pub fn terminate(&self) {
        self.0.store(true, Ordering::Relaxed);
    }

    /// Clear the flag so that the solver can be used again.
    pub fn reset(&self) {
        self.0.store(false, Ordering::Relaxed);
    }

    #[must_use]
    pub fn is_terminated(&self) -> bool {
        self.0.load(Ordering::Relaxed)
    }
}

impl Terminator for TerminateFlag {
    fn terminated(&mut self) -> bool {
        self.is_terminated()
    }
}

/// Connected learners which can be used to export learned clauses.
/// The 'learning' can check the size of the learn clause and only if it
/// returns true then the individual literals of the learned clause are given
/// to the learn through 'learn' one by one terminated by a zero literal.
pub trait Learner {
    fn learning(&mut self, size: i32) -> bool;
    fn learn(&mut self, lit: i32);
}

/// Connected listener gets notified whenever the truth value of a variable is
/// fixed (for example during inprocessing or due to some derived unit clauses).
pub trait FixedAssignmentListener {
    fn notify_fixed_assignment(&mut self, lit: i32);
}

use std::vec::Vec;

/// Allows to connect an external propagator to propagate values to variables
/// with an external clause as a reason or to learn new clauses during the
/// CDCL loop (without restart).
pub trait ExternalPropagator {
    /// lazy propagator only checks complete assignments
    fn is_lazy(&mut self) -> bool {
        false
    }

    /// Reason external clauses can be deleted
    fn are_reasons_forgettable(&mut self) -> bool {
        false
    }

    /// Notify the propagator about assignments to observed variables.
    /// The notification is not necessarily eager. It usually happens before
    /// the call of propagator callbacks and when a driving clause is leading
    /// to an assignment.
    fn notify_assignment(&mut self, lits: &[i32]);

    fn notify_new_decision_level(&mut self);

    fn notify_backtrack(&mut self, new_level: usize);

    /// Check by the external propagator the found complete solution (after
    /// solution reconstruction). If it returns false, the propagator must
    /// provide an external clause during the next callback.
    fn cb_check_found_model(&mut self, model: &[i32]) -> bool;

    /// Ask the external propagator for the next decision literal. If it
    /// returns 0, the solver makes its own choice.
    fn cb_decide(&mut self) -> i32 {
        0
    }

    /// Ask the external propagator if there is an external propagation to make
    /// under the current assignment. It returns either a literal to be
    /// propagated or 0, indicating that there is no external propagation under
    /// the current assignment.
    fn cb_propagate(&mut self) -> i32 {
        0
    }

    /// Ask the external propagator for the reason clause of a previous
    /// external propagation step (done by `cb_propagate`). The clause must be
    /// added literal-by-literal closed with a 0. Further, the clause must
    /// contain the propagated literal.
    ///
    /// The clause will be learned as an Irredundant Non-Forgettable Clause (see
    /// below at '`cb_has_external_clause`' more details about it).
    fn cb_add_reason_clause_lit(&mut self, _propagated_lit: i32) -> i32 {
        0
    }

    /// The following two functions are used to add external clauses to the
    /// solver during the CDCL loop. The external clause is added
    /// literal-by-literal and learned by the solver as an irredundant
    /// (original) input clause. The clause can be arbitrary, but if it is
    /// root-satisfied or tautology, the solver will ignore it without learning
    /// it. Root-falsified literals are eagerly removed from the clause.
    /// Falsified clauses trigger conflict analysis, propagating clauses
    /// trigger propagation. In case chrono is 0, the solver backtracks to
    /// propagate the new literal on the right decision level, otherwise it
    /// potentially will be an out-of-order assignment on the current level.
    /// Unit clauses always (unless root-satisfied, see above) trigger
    /// backtracking (independently from the value of the chrono option and
    /// independently from being falsified or satisfied or unassigned) to level
    /// 0. Empty clause (or root falsified clause, see above) makes the problem
    /// unsat and stops the search immediately. A literal 0 must close the
    /// clause.
    ///
    /// The external propagator indicates that there is a clause to add.
    /// The parameter of the function allows the user to indicate that how
    /// 'forgettable' is the external clause. Forgettable clauses are allowed
    /// to be removed by the SAT solver during clause database reduction.
    /// However, it is up to the solver to decide when actually the clause is
    /// deleted. For example, unit clauses, even forgettable ones, will not be
    /// deleted. In case the clause is not 'forgettable' (the parameter is false),
    /// the solver considers the clause to be irredundant.
    ///
    /// In case the solver produces incremental proofs, these external clauses
    /// are added to the proof during solving at real-time, i.e., the proof
    /// checker can ignore them until that point (so added as input clause, but
    /// input after the query line).
    ///
    /// Reason clauses of external propagation steps are assumed to be
    /// forgettable, parameter '`reason_forgettable`' can be used to change it.
    ///
    /// Currently, every external clause is expected to be over observed
    /// (therefore frozen) variables, hence no tainting or restore steps
    /// are performed upon their addition. This will be changed in later
    /// versions probably.
    fn cb_has_external_clause(&mut self, is_forgettable: &mut bool) -> bool;

    /// The actual function called to add the external clause.
    fn cb_add_external_clause_lit(&mut self) -> i32;
}

/// Allows to traverse all remaining irredundant clauses.  Satisfied and
/// eliminated clauses are not included, nor any derived units unless such
/// a unit literal is frozen. Falsified literals are skipped.  If the solver
/// is inconsistent only the empty clause is traversed.
///
/// If 'clause' returns false traversal aborts early.
pub trait ClauseIterator {
    fn clause(&mut self, clause: &[i32]) -> bool;
}

/// Allows to traverse all clauses on the extension stack together with their
/// witness cubes.  If the solver is inconsistent, i.e., an empty clause is
/// found and the formula is unsatisfiable, then nothing is traversed.
///
/// The clauses traversed in '`traverse_clauses`' together with the clauses on
/// the extension stack are logically equivalent to the original clauses.
/// See our SAT'19 paper for more details.
///
/// The witness literals can be used to extend and fix an assignment on the
/// remaining clauses to satisfy the clauses on the extension stack too.
///
/// All derived units of non-frozen variables are included too.
///
/// If 'witness' returns false traversal aborts early.
pub trait WitnessIterator {
    fn witness(&mut self, clause: &[i32], witness: &[i32], id: i64) -> bool;
}

/// Trait for proof tracing that allows you to track proof events in real-time.
/// This is useful for SMT solvers that need to interleave SAT solver clauses
/// with theory clauses to generate eDRAT proofs.
pub trait ProofTracer {
    /// Called when an original clause is added to the solver
    fn add_original_clause(&mut self, id: i64, redundant: bool, clause: &[i32], restored: bool);

    /// Called when a derived clause is learned by the SAT solver. If `witness`
    /// is not zero the clause is a RAT clause with that witness literal.
    fn add_derived_clause(
        &mut self,
        id: i64,
        redundant: bool,
        witness: i32,
        clause: &[i32],
        antecedents: &[i64],
    );

    /// Called when a clause is deleted
    fn delete_clause(&mut self, id: i64, redundant: bool, clause: &[i32]);

    /// Called when a clause is weakened (might be restored later)
    fn weaken_minus(&mut self, id: i64, clause: &[i32]);

    /// Called when a clause is strengthened
    fn strengthen(&mut self, id: i64);

    /// Called when a clause is finalized
    fn finalize_clause(&mut self, id: i64, clause: &[i32]);

    /// Called when an assumption is added
    fn add_assumption(&mut self, lit: i32);

    /// Called when a constraint is added
    fn add_constraint(&mut self, clause: &[i32]);

    /// Called when assumptions are reset
    fn reset_assumptions(&mut self);

    /// Called when an assumption clause is added (negation of failing assumptions)
    fn add_assumption_clause(&mut self, id: i64, clause: &[i32], antecedents: &[i64]);

    /// Called when the solver concludes SAT
    fn conclude_sat(&mut self, conclusion_type: i32, model: &[i32]);

    /// Called when the solver concludes UNSAT
    fn conclude_unsat(&mut self, conclusion_type: i32, clause_ids: &[i64]);

    /// Called when the solver concludes UNKNOWN
    fn conclude_unknown(&mut self, trail: &[i32]);

    /// Called when a clause is demoted from irredundant to redundant
    fn demote_clause(&mut self, _id: i64, _clause: &[i32]) {}

    /// Called when a solve call ends with the given status. If the status is
    /// UNSAT and an empty clause has been derived, `id` is its id.
    fn report_status(&mut self, _status: i32, _id: i64) {}

    /// Called when the proof begins; ids below `first_derived_id` are
    /// reserved for original clauses
    fn begin_proof(&mut self, _first_derived_id: i64) {}

    /// Called when a solve call (query) starts
    fn solve_query(&mut self) {}

    /// Called when two literals are found to be equivalent (possibly
    /// including variables added by the solver, e.g. through BVA)
    fn notify_equivalence(&mut self, _lit: i32, _other: i32) {}
}

// ************************************************************************************************
// Shared callbacks
// ************************************************************************************************

// The solver owns its callbacks, so these impls let the caller keep an `Rc` to
// a callback and inspect it while it is connected (e.g. after `solve`).

impl<T: Terminator> Terminator for Rc<RefCell<T>> {
    fn terminated(&mut self) -> bool {
        self.borrow_mut().terminated()
    }
}

impl<T: Learner> Learner for Rc<RefCell<T>> {
    fn learning(&mut self, size: i32) -> bool {
        self.borrow_mut().learning(size)
    }
    fn learn(&mut self, lit: i32) {
        self.borrow_mut().learn(lit);
    }
}

impl<T: FixedAssignmentListener> FixedAssignmentListener for Rc<RefCell<T>> {
    fn notify_fixed_assignment(&mut self, lit: i32) {
        self.borrow_mut().notify_fixed_assignment(lit);
    }
}

impl<T: ExternalPropagator> ExternalPropagator for Rc<RefCell<T>> {
    fn is_lazy(&mut self) -> bool {
        self.borrow_mut().is_lazy()
    }
    fn are_reasons_forgettable(&mut self) -> bool {
        self.borrow_mut().are_reasons_forgettable()
    }
    fn notify_assignment(&mut self, lits: &[i32]) {
        self.borrow_mut().notify_assignment(lits);
    }
    fn notify_new_decision_level(&mut self) {
        self.borrow_mut().notify_new_decision_level();
    }
    fn notify_backtrack(&mut self, new_level: usize) {
        self.borrow_mut().notify_backtrack(new_level);
    }
    fn cb_check_found_model(&mut self, model: &[i32]) -> bool {
        self.borrow_mut().cb_check_found_model(model)
    }
    fn cb_decide(&mut self) -> i32 {
        self.borrow_mut().cb_decide()
    }
    fn cb_propagate(&mut self) -> i32 {
        self.borrow_mut().cb_propagate()
    }
    fn cb_add_reason_clause_lit(&mut self, propagated_lit: i32) -> i32 {
        self.borrow_mut().cb_add_reason_clause_lit(propagated_lit)
    }
    fn cb_has_external_clause(&mut self, is_forgettable: &mut bool) -> bool {
        self.borrow_mut().cb_has_external_clause(is_forgettable)
    }
    fn cb_add_external_clause_lit(&mut self) -> i32 {
        self.borrow_mut().cb_add_external_clause_lit()
    }
}

impl<T: ProofTracer> ProofTracer for Rc<RefCell<T>> {
    fn add_original_clause(&mut self, id: i64, redundant: bool, clause: &[i32], restored: bool) {
        self.borrow_mut()
            .add_original_clause(id, redundant, clause, restored);
    }
    fn add_derived_clause(
        &mut self,
        id: i64,
        redundant: bool,
        witness: i32,
        clause: &[i32],
        antecedents: &[i64],
    ) {
        self.borrow_mut()
            .add_derived_clause(id, redundant, witness, clause, antecedents);
    }
    fn delete_clause(&mut self, id: i64, redundant: bool, clause: &[i32]) {
        self.borrow_mut().delete_clause(id, redundant, clause);
    }
    fn weaken_minus(&mut self, id: i64, clause: &[i32]) {
        self.borrow_mut().weaken_minus(id, clause);
    }
    fn strengthen(&mut self, id: i64) {
        self.borrow_mut().strengthen(id);
    }
    fn finalize_clause(&mut self, id: i64, clause: &[i32]) {
        self.borrow_mut().finalize_clause(id, clause);
    }
    fn add_assumption(&mut self, lit: i32) {
        self.borrow_mut().add_assumption(lit);
    }
    fn add_constraint(&mut self, clause: &[i32]) {
        self.borrow_mut().add_constraint(clause);
    }
    fn reset_assumptions(&mut self) {
        self.borrow_mut().reset_assumptions();
    }
    fn add_assumption_clause(&mut self, id: i64, clause: &[i32], antecedents: &[i64]) {
        self.borrow_mut()
            .add_assumption_clause(id, clause, antecedents);
    }
    fn conclude_sat(&mut self, conclusion_type: i32, model: &[i32]) {
        self.borrow_mut().conclude_sat(conclusion_type, model);
    }
    fn conclude_unsat(&mut self, conclusion_type: i32, clause_ids: &[i64]) {
        self.borrow_mut()
            .conclude_unsat(conclusion_type, clause_ids);
    }
    fn conclude_unknown(&mut self, trail: &[i32]) {
        self.borrow_mut().conclude_unknown(trail);
    }
    fn demote_clause(&mut self, id: i64, clause: &[i32]) {
        self.borrow_mut().demote_clause(id, clause);
    }
    fn report_status(&mut self, status: i32, id: i64) {
        self.borrow_mut().report_status(status, id);
    }
    fn begin_proof(&mut self, first_derived_id: i64) {
        self.borrow_mut().begin_proof(first_derived_id);
    }
    fn solve_query(&mut self) {
        self.borrow_mut().solve_query();
    }
    fn notify_equivalence(&mut self, lit: i32, other: i32) {
        self.borrow_mut().notify_equivalence(lit, other);
    }
}