symbolica 2.0.0

A blazing fast computer algebra system
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
//! Python API bindings.
//!
//! All Symbolica community extensions must implement the [SymbolicaCommunityModule] trait.

use std::{
    borrow::Cow,
    fs::File,
    hash::{Hash, Hasher},
    io::{BufReader, BufWriter},
    ops::{Deref, Neg},
    sync::{Arc, Mutex},
};

use ahash::{HashMap, HashSet};
use brotli::CompressorWriter;
use numpy::{
    AllowTypeChange, Complex64, IntoPyArray, PyArrayDyn, PyArrayLike1, PyArrayLikeDyn,
    ndarray::{ArrayD, Axis, CowArray, IxDyn},
};
use pyo3::{
    Borrowed, Bound, FromPyObject, IntoPyObject, IntoPyObjectExt, Py, PyAny, PyErr, PyRef,
    PyResult, PyTypeInfo, Python,
    exceptions::{self, PyIndexError},
    pybacked::PyBackedStr,
    pyclass::CompareOp,
    pyfunction, pymethods,
    types::{
        PyAnyMethods, PyBytes, PyBytesMethods, PyComplex, PyDict, PyDictMethods, PyInt, PyIterator,
        PyModule, PyNone, PyTuple, PyTupleMethods, PyType, PyTypeMethods,
    },
    wrap_pyfunction,
};
use pyo3::{pyclass, types::PyModuleMethods};

#[cfg(feature = "python_stubgen")]
use pyo3::types::PyList;

#[cfg(feature = "python_stubgen")]
use pyo3_stub_gen::{
    PyStubType, TypeInfo,
    derive::{gen_stub_pyclass, gen_stub_pyclass_enum, gen_stub_pyfunction, gen_stub_pymethods},
    impl_stub_type,
    inventory::submit,
    type_info::{
        MethodInfo, MethodType, ParameterDefault, ParameterInfo, ParameterKind, PyFunctionInfo,
        PyMethodsInfo,
    },
};
#[cfg(not(feature = "python_stubgen"))]
use pyo3_stub_gen_derive::remove_gen_stub;

use rand::{Rng, RngCore};
use rug::Complete;
use self_cell::self_cell;
use smallvec::SmallVec;
use smartstring::{LazyCompact, SmartString};

#[cfg(not(feature = "python_export"))]
use pyo3::pymodule;

use crate::{
    LicenseManager,
    atom::{
        Atom, AtomCore, AtomType, AtomView, DefaultNamespace, EvaluationInfo, Indeterminate,
        ListIterator, Symbol, SymbolAttribute, SymbolBuilder, UserData, UserDataKey,
    },
    coefficient::{Coefficient, CoefficientView, ConvertToRing},
    domains::{
        Ring, RingOps, SelfRing,
        algebraic_number::AlgebraicExtension,
        atom::AtomField,
        dual::HyperDual,
        finite_field::{FiniteFieldCore, PrimeIteratorU64, ToFiniteField, Z2, Zp64},
        float::{Complex, DoubleFloat, F64, Float, PythonMultiPrecisionFloat, RealLike},
        integer::{FromFiniteField, Integer, IntegerRelationError, IntegerRing, Z},
        rational::{Q, Rational, RationalField},
        rational_polynomial::{
            FromNumeratorAndDenominator, RationalPolynomial, RationalPolynomialField,
        },
    },
    error,
    evaluate::{
        BatchEvaluator, CompileOptions, CompiledComplexEvaluator, CompiledCudaComplexEvaluator,
        CompiledCudaRealEvaluator, CompiledNumber, CompiledRealEvaluator,
        CompiledSimdComplexEvaluator, CompiledSimdRealEvaluator, ComplexEvaluatorSettings,
        CudaComplexf64, CudaLoadSettings, CudaRealf64, Dualizer, EvaluatorLoader, ExportSettings,
        ExpressionEvaluator, FunctionMap, InlineASM, Instruction, JITCompilationSettings,
        JITCompiledEvaluator, OptimizationSettings, Slot,
    },
    graph::{GenerationSettings, Graph, HalfEdge},
    id::{
        Condition, ConditionResult, Evaluate, Match, MatchSettings, MatchStack, Pattern,
        PatternAtomTreeIterator, PatternRestriction, Relation, ReplaceIterator, ReplaceSettings,
        ReplaceWith, Replacement, WildcardRestriction,
    },
    numerical_integration::{ContinuousGrid, DiscreteGrid, Grid, MonteCarloRng, Probe, Sample},
    parser::{ParseMode, ParseSettings, Token},
    poly::{
        GrevLexOrder, INLINED_EXPONENTS, LexOrder, PolyVariable, factor::Factorize,
        gcd::PolynomialGCD, groebner::GroebnerBasis, polynomial::MultivariatePolynomial,
        series::Series,
    },
    printer::{
        AtomPrinter, ColorMode, PrintMode, PrintOptions, PrintState, PrintUserData,
        PrintUserDataKey,
    },
    solve::SolveError,
    state::{RecycledAtom, State, Workspace},
    streaming::{TermStreamer, TermStreamerConfig},
    tensors::matrix::Matrix,
    transformer::{StatsOptions, Transformer, TransformerError, TransformerState},
    try_parse, warn,
};

#[cfg(feature = "python_stubgen")]
static NONE_ARG: fn() -> String = || "None".into();

static DEFAULT_PRINT_OPTIONS: std::sync::LazyLock<PrintOptions> =
    std::sync::LazyLock::new(|| PrintOptions {
        hide_namespace: Some(Cow::Borrowed("python")),
        ..PrintOptions::new()
    });

static PLAIN_PRINT_OPTIONS: std::sync::LazyLock<PrintOptions> =
    std::sync::LazyLock::new(|| PrintOptions {
        hide_namespace: Some(Cow::Borrowed("python")),
        ..PrintOptions::file()
    });

static LATEX_PRINT_OPTIONS: std::sync::LazyLock<PrintOptions> =
    std::sync::LazyLock::new(|| PrintOptions {
        hide_namespace: Some(Cow::Borrowed("python")),
        ..PrintOptions::latex()
    });

mod atom;
mod evaluator;
mod expression;
mod graph;
mod integer;
mod integration;
mod matrix;
mod polynomial;
mod series;

pub use atom::*;
pub use evaluator::*;
pub use expression::*;
pub use graph::*;
pub use integer::*;
pub use integration::*;
pub use matrix::*;
pub use polynomial::*;
pub use series::*;

/// Trait for registering Python submodules for Symbolica, which enables
/// multiple crates to use the same Symbolica kernel.
///
/// You must create a global variable called `CommunityModule`:
/// ```rust
/// pub struct CommunityModule;
///
/// impl SymbolicaCommunityModule for CommunityModule {
///     fn get_name() -> String {
///         "NAME".to_string()
///     }
///
///     fn register_module(m: &Bound<'_, PyModule>) -> PyResult<()> {
///         // add your functions and classes
///         Ok(())
///     }
/// }
/// ```
///
/// And you must set the modules of your functions and classes to
/// `symbolica.community.NAME`, .i.e,
/// ```
/// #[pyclass(module = "symbolica.community.NAME")]
/// struct MyPythonStruct {}
/// ```
#[cfg(feature = "python_export")]
pub trait SymbolicaCommunityModule {
    /// The name of the submodule. Must be used in all defined Python structures, as such:
    /// ```
    /// #[pyclass(module = "symbolica.community.NAME")]
    /// struct MyPythonStruct {}
    /// ```
    fn get_name() -> String;

    /// Register all classes, functions and methods in the submodule `m`.
    /// This function must not register any Symbolica symbols. All initialization
    /// should be performed in the [SymbolicaCommunityModule::initialize] function.
    fn register_module(m: &Bound<'_, PyModule>) -> PyResult<()>;

    /// Initialize the community module. Called when the submodule is imported.
    fn initialize(_py: Python) -> PyResult<()> {
        Ok(())
    }
}

/// Specifies the print mode.
#[cfg_attr(feature = "python_stubgen", gen_stub_pyclass_enum)]
#[pyclass(
    from_py_object,
    name = "ParseMode",
    eq,
    eq_int,
    module = "symbolica.core"
)]
#[derive(Clone, Copy, PartialEq, Eq, Hash)]
pub enum PythonParseMode {
    /// parse using Symbolica notation.
    Symbolica,
    /// Parse using Mathematica notation.
    Mathematica,
}

impl From<PythonParseMode> for ParseMode {
    fn from(mode: PythonParseMode) -> Self {
        match mode {
            PythonParseMode::Symbolica => ParseMode::Symbolica,
            PythonParseMode::Mathematica => ParseMode::Mathematica,
        }
    }
}

/// Specifies the print mode.
#[cfg_attr(feature = "python_stubgen", gen_stub_pyclass_enum)]
#[pyclass(
    from_py_object,
    name = "PrintMode",
    eq,
    eq_int,
    module = "symbolica.core"
)]
#[derive(Clone, Copy, PartialEq, Eq, Hash)]
pub enum PythonPrintMode {
    /// Print using Symbolica notation.
    Symbolica,
    /// Print using LaTeX notation.
    Latex,
    /// Print using Mathematica notation.
    Mathematica,
    /// Print using Sympy notation.
    Sympy,
    /// Print using Typst notation.
    Typst,
}

impl From<PrintMode> for PythonPrintMode {
    fn from(mode: PrintMode) -> Self {
        match mode {
            PrintMode::Symbolica => PythonPrintMode::Symbolica,
            PrintMode::Latex => PythonPrintMode::Latex,
            PrintMode::Mathematica => PythonPrintMode::Mathematica,
            PrintMode::Sympy => PythonPrintMode::Sympy,
            PrintMode::Typst => PythonPrintMode::Typst,
            _ => {
                error!("Unsupported PrintMode: {:?}", mode);
                PythonPrintMode::Symbolica
            }
        }
    }
}

impl From<PythonPrintMode> for PrintMode {
    fn from(mode: PythonPrintMode) -> Self {
        match mode {
            PythonPrintMode::Symbolica => PrintMode::Symbolica,
            PythonPrintMode::Latex => PrintMode::Latex,
            PythonPrintMode::Mathematica => PrintMode::Mathematica,
            PythonPrintMode::Sympy => PrintMode::Sympy,
            PythonPrintMode::Typst => PrintMode::Typst,
        }
    }
}

/// A formatted string with rich notebook display representations.
#[cfg_attr(feature = "python_stubgen", gen_stub_pyclass)]
#[pyclass(
    name = "FormattedOutput",
    skip_from_py_object,
    module = "symbolica.core"
)]
#[derive(Clone)]
pub struct PythonFormattedOutput {
    pub text: String,
    pub html: Option<String>,
    pub latex: Option<String>,
}

#[cfg_attr(feature = "python_stubgen", gen_stub_pymethods)]
#[cfg_attr(not(feature = "python_stubgen"), remove_gen_stub)]
#[pymethods]
impl PythonFormattedOutput {
    /// Create a formatted output object.
    #[new]
    #[pyo3(signature = (text, html = None, latex = None))]
    pub fn new(text: String, html: Option<String>, latex: Option<String>) -> Self {
        Self { text, html, latex }
    }

    /// Convert the formatted output into plain text.
    pub fn __str__(&self) -> String {
        self.text.clone()
    }

    /// Convert the formatted output into plain text.
    pub fn __repr__(&self) -> String {
        self.text.clone()
    }

    /// Convert the formatted output into plain text.
    pub fn format_plain(&self) -> String {
        self.text.clone()
    }

    /// Convert the formatted output into an HTML representation.
    pub fn _repr_html_(&self) -> Option<String> {
        self.html.clone()
    }

    /// Convert the formatted output into a LaTeX representation.
    pub fn _repr_latex_(&self) -> Option<String> {
        self.latex.clone()
    }

    /// Convert the formatted output into a pretty string representation.
    pub fn _repr_pretty_(&self, pretty: &Bound<'_, PyAny>, cycle: bool) -> PyResult<()> {
        let text = if cycle { "..." } else { &self.text };
        pretty.call_method1("text", (text,))?;
        Ok(())
    }
}

/// Create a Symbolica Python module.
pub fn create_symbolica_module<'a, 'b>(
    m: &'b Bound<'a, PyModule>,
) -> PyResult<&'b Bound<'a, PyModule>> {
    m.add_class::<PythonFormattedOutput>()?;
    m.add_class::<PythonExpression>()?;
    m.add_class::<PythonHeldExpression>()?;
    m.add_class::<PythonTransformer>()?;
    m.add_class::<PythonPolynomial>()?;
    m.add_class::<PythonFiniteFieldPolynomial>()?;
    m.add_class::<PythonNumberFieldPolynomial>()?;
    m.add_class::<PythonRationalPolynomial>()?;
    m.add_class::<PythonFiniteFieldRationalPolynomial>()?;
    m.add_class::<PythonMatrix>()?;
    m.add_class::<PythonNumericalIntegrator>()?;
    m.add_class::<PythonSample>()?;
    m.add_class::<PythonProbe>()?;
    m.add_class::<PythonAtomType>()?;
    m.add_class::<PythonAtomTree>()?;
    m.add_class::<PythonSymbolAttribute>()?;
    m.add_class::<PythonParseMode>()?;
    m.add_class::<PythonPrintMode>()?;
    m.add_class::<PythonCondition>()?;
    m.add_class::<PythonReplacement>()?;
    m.add_class::<PythonExpressionEvaluator>()?;
    m.add_class::<PythonCompiledRealExpressionEvaluator>()?;
    m.add_class::<PythonCompiledComplexExpressionEvaluator>()?;
    m.add_class::<PythonCompiledSimdRealExpressionEvaluator>()?;
    m.add_class::<PythonCompiledSimdComplexExpressionEvaluator>()?;
    m.add_class::<PythonCompiledCudaRealExpressionEvaluator>()?;
    m.add_class::<PythonCompiledCudaComplexExpressionEvaluator>()?;
    m.add_class::<PythonRandomNumberGenerator>()?;
    m.add_class::<PythonPatternRestriction>()?;
    m.add_class::<PythonTermStreamer>()?;
    m.add_class::<PythonSeries>()?;
    m.add_class::<PythonHalfEdge>()?;
    m.add_class::<PythonGraph>()?;
    m.add_class::<PythonInteger>()?;

    m.add_function(wrap_pyfunction!(symbol_shorthand, m)?)?;
    m.add_function(wrap_pyfunction!(number_shorthand, m)?)?;
    m.add_function(wrap_pyfunction!(expression_shorthand, m)?)?;
    m.add_function(wrap_pyfunction!(transformer_shorthand, m)?)?;
    m.add_function(wrap_pyfunction!(poly_shorthand, m)?)?;

    m.add_function(wrap_pyfunction!(get_version, m)?)?;
    m.add_function(wrap_pyfunction!(is_licensed, m)?)?;
    m.add_function(wrap_pyfunction!(set_license_key, m)?)?;
    m.add_function(wrap_pyfunction!(request_hobbyist_license, m)?)?;
    m.add_function(wrap_pyfunction!(request_trial_license, m)?)?;
    m.add_function(wrap_pyfunction!(request_sublicense, m)?)?;
    m.add_function(wrap_pyfunction!(get_license_key, m)?)?;
    m.add_function(wrap_pyfunction!(use_custom_logger, m)?)?;
    m.add_function(wrap_pyfunction!(get_namespace, m)?)?;
    m.add_function(wrap_pyfunction!(set_namespace, m)?)?;

    m.add("__version__", env!("CARGO_PKG_VERSION"))?;

    Ok(m)
}

fn print_options_to_dict<'py>(
    options: &PrintOptions,
    state: &PrintState,
    py: Python<'py>,
) -> PyResult<Bound<'py, PyDict>> {
    let dict = PyDict::new(py);
    dict.set_item("mode", PythonPrintMode::from(options.mode))?;
    dict.set_item("max_line_length", options.max_line_length)?;
    dict.set_item("indentation", options.indentation)?;
    dict.set_item("fill_indented_lines", options.fill_indented_lines)?;
    dict.set_item("terms_on_new_line", options.terms_on_new_line)?;
    dict.set_item("color_top_level_sum", options.color_top_level_sum)?;
    dict.set_item("color_builtin_symbols", options.color_builtin_symbols)?;
    dict.set_item("bracket_level_colors", options.bracket_level_colors)?;
    dict.set_item("print_ring", options.print_ring)?;
    dict.set_item(
        "symmetric_representation_for_finite_field",
        options.symmetric_representation_for_finite_field,
    )?;
    dict.set_item(
        "explicit_rational_polynomial",
        options.explicit_rational_polynomial,
    )?;
    dict.set_item(
        "number_thousands_separator",
        options.number_thousands_separator,
    )?;
    dict.set_item("multiplication_operator", options.multiplication_operator)?;
    dict.set_item(
        "double_star_for_exponentiation",
        options.double_star_for_exponentiation,
    )?;
    dict.set_item("function_brackets", options.function_brackets)?;
    dict.set_item("num_exp_as_superscript", options.num_exp_as_superscript)?;
    dict.set_item("precision", options.precision)?;
    dict.set_item("pretty_matrix", options.pretty_matrix)?;
    dict.set_item("hide_namespace", options.hide_namespace.as_deref())?;
    dict.set_item("hide_all_namespaces", options.hide_all_namespaces)?;
    dict.set_item("color_namespace", options.color_namespace)?;
    dict.set_item("max_terms", options.max_terms)?;
    let custom_print_mode = PyDict::new(py);
    for (name, value) in &options.custom_print_mode {
        custom_print_mode.set_item(name, PythonBorrowedPrintUserData(value))?;
    }
    dict.set_item("custom_print_mode", custom_print_mode)?;

    dict.set_item("level", state.level)?;
    dict.set_item("bracket_level", state.bracket_level)?;
    dict.set_item("indentation_level", state.indentation_level)?;

    Ok(dict)
}

/// Represents user-defined data that can be used as a key in [PythonPrintUserData].
#[derive(Clone, PartialEq, Eq, Hash)]
pub struct PythonPrintUserDataKey(pub PrintUserDataKey);

impl<'py> FromPyObject<'_, 'py> for PythonPrintUserDataKey {
    type Error = PyErr;

    fn extract(ob: Borrowed<'_, 'py, pyo3::PyAny>) -> PyResult<Self> {
        if let Ok(num) = ob.extract::<i64>() {
            Ok(PythonPrintUserDataKey(PrintUserDataKey::Integer(num)))
        } else if let Ok(s) = ob.extract::<PyBackedStr>() {
            Ok(PythonPrintUserDataKey(PrintUserDataKey::String(
                s.to_string(),
            )))
        } else {
            Err(exceptions::PyTypeError::new_err(
                "Cannot convert to PrintUserDataKey",
            ))
        }
    }
}

/// Represents user-defined data that can be attached to [PrintOptions] in Python.
#[derive(Clone)]
pub struct PythonPrintUserData(pub PrintUserData);

#[cfg(feature = "python_stubgen")]
impl_stub_type!(PythonPrintUserData = i64 | PyBackedStr | PyDict | PyList);

impl<'py> FromPyObject<'_, 'py> for PythonPrintUserData {
    type Error = PyErr;

    fn extract(ob: Borrowed<'_, 'py, pyo3::PyAny>) -> PyResult<Self> {
        if let Ok(num) = ob.extract::<i64>() {
            Ok(PythonPrintUserData(PrintUserData::Integer(num)))
        } else if let Ok(s) = ob.extract::<PyBackedStr>() {
            Ok(PythonPrintUserData(PrintUserData::String(s.to_string())))
        } else if let Ok(list) = ob.extract::<Vec<PythonPrintUserData>>() {
            Ok(PythonPrintUserData(PrintUserData::List(
                list.into_iter().map(|x| x.0).collect(),
            )))
        } else if let Ok(map) = ob.extract::<HashMap<PythonPrintUserDataKey, PythonPrintUserData>>()
        {
            Ok(PythonPrintUserData(PrintUserData::Map(
                map.into_iter().map(|(k, v)| (k.0, v.0)).collect(),
            )))
        } else {
            Err(exceptions::PyTypeError::new_err(
                "Cannot convert to PrintUserData",
            ))
        }
    }
}

pub(super) struct PythonBorrowedPrintUserData<'a>(pub(super) &'a PrintUserData);

impl<'a, 'py> IntoPyObject<'py> for PythonBorrowedPrintUserData<'a> {
    type Target = PyAny;
    type Output = Bound<'py, Self::Target>;
    type Error = PyErr;

    fn into_pyobject(self, py: Python<'py>) -> Result<Self::Output, Self::Error> {
        match self.0 {
            PrintUserData::Integer(i) => i.into_bound_py_any(py),
            PrintUserData::String(s) => s.into_bound_py_any(py),
            PrintUserData::List(l) => {
                let pl: Vec<PythonBorrowedPrintUserData> =
                    l.iter().map(PythonBorrowedPrintUserData).collect();
                pl.into_bound_py_any(py)
            }
            PrintUserData::Map(m) => {
                let dict = PyDict::new(py);
                for (key, value) in m {
                    match key {
                        PrintUserDataKey::Integer(i) => {
                            dict.set_item(i, PythonBorrowedPrintUserData(value))?
                        }
                        PrintUserDataKey::String(s) => {
                            dict.set_item(s, PythonBorrowedPrintUserData(value))?
                        }
                    }
                }
                dict.into_bound_py_any(py)
            }
        }
    }
}

/// Set the Symbolica namespace for the calling module.
/// All subsequently created symbols in the calling module will be defined within this namespace.
///
/// This function sets the `SYMBOLICA_NAMESPACE` variable in the global scope of the calling module.
///
/// Parameters
/// ----------
/// namespace: str
///     The namespace to set for subsequently created symbols.
#[cfg_attr(
    feature = "python_stubgen",
    gen_stub_pyfunction(module = "symbolica.core")
)]
#[pyfunction]
pub fn set_namespace(py: Python, namespace: String) -> PyResult<()> {
    let ptr = unsafe { pyo3::ffi::PyEval_GetGlobals() };

    if ptr.is_null() {
        return Err(PyErr::new::<pyo3::exceptions::PyRuntimeError, _>(
            "No active Python frame found to inject globals into.",
        ));
    }

    let globals = unsafe { Bound::from_borrowed_ptr(py, ptr) };

    globals.set_item("SYMBOLICA_NAMESPACE", namespace)?;

    Ok(())
}

static INTERNED_STRINGS: std::sync::LazyLock<Mutex<HashSet<&'static str>>> =
    std::sync::LazyLock::new(|| Mutex::new(HashSet::default()));

fn intern_string(string: &str) -> &'static str {
    let mut ns = INTERNED_STRINGS.lock().unwrap();
    if let Some(s) = ns.get::<str>(&string) {
        s
    } else {
        let b = Box::leak(string.to_string().into_boxed_str()) as &'static str;
        ns.insert(b);
        b
    }
}

/// Get the Symbolica namespace for the calling module.
#[cfg_attr(
    feature = "python_stubgen",
    gen_stub_pyfunction(module = "symbolica.core")
)]
#[pyfunction]
pub fn get_namespace(py: Python) -> PyResult<&'static str> {
    let ptr = unsafe { pyo3::ffi::PyEval_GetGlobals() };

    if ptr.is_null() {
        return Err(PyErr::new::<pyo3::exceptions::PyRuntimeError, _>(
            "No active Python frame found",
        ));
    }

    let globals = unsafe { Bound::from_borrowed_ptr(py, ptr) };
    Ok(
        match globals.cast::<PyDict>()?.get_item("SYMBOLICA_NAMESPACE") {
            Ok(Some(val)) => intern_string(&val.extract::<PyBackedStr>()?),
            Err(_) => "python",
            Ok(None) => "python",
        },
    )
}

/// Symbolica is a blazing fast computer algebra system.
///
/// It can be used to perform mathematical operations,
/// such as symbolic differentiation, integration, simplification,
/// pattern matching and solving equations.
///
/// Examples
/// --------
///
/// >>> from symbolica import *
/// >>> e = E('x^2*log(2*x + y) + exp(3*x)')
/// >>> a = e.derivative(S('x'))
/// >>> print("d/dx {} = {}".format(e, a))
#[cfg(feature = "python_api")]
#[pymodule]
fn symbolica(m: &Bound<'_, PyModule>) -> PyResult<()> {
    pyo3_log::init();
    create_symbolica_module(m).map(|_| ())
}

/// Enable logging using Python's logging module instead of using the default logging.
/// This is useful when using Symbolica in a Jupyter notebook or other environments
/// where stdout is not easily accessible.
///
/// This function must be called before any Symbolica logging events are emitted.
#[pyfunction]
fn use_custom_logger() {
    crate::GLOBAL_SETTINGS
        .initialize_tracing
        .store(false, std::sync::atomic::Ordering::Relaxed);
}

/// Get the current Symbolica version.
#[cfg_attr(
    feature = "python_stubgen",
    gen_stub_pyfunction(module = "symbolica.core")
)]
#[pyfunction]
fn get_version() -> String {
    LicenseManager::get_version().to_string()
}

/// Check if the current Symbolica instance has a valid license key set.
#[cfg_attr(
    feature = "python_stubgen",
    gen_stub_pyfunction(module = "symbolica.core")
)]
#[pyfunction]
fn is_licensed() -> bool {
    LicenseManager::is_licensed()
}

/// Set the Symbolica license key for this computer. Can only be called before calling any other Symbolica functions
/// and before importing any community modules.
///
/// Parameters
/// ----------
/// key: str
///     The license key to register for this machine.
#[cfg_attr(
    feature = "python_stubgen",
    gen_stub_pyfunction(module = "symbolica.core")
)]
#[pyfunction]
fn set_license_key(key: String) -> PyResult<()> {
    LicenseManager::set_license_key(&key).map_err(exceptions::PyException::new_err)
}

/// Request a key for **non-professional** use for the user `name`, that will be sent to the e-mail address `email`.
///
/// Parameters
/// ----------
/// name: str
///     The name of the user.
/// email: str
///     The email address that should receive the license.
#[cfg_attr(
    feature = "python_stubgen",
    gen_stub_pyfunction(module = "symbolica.core")
)]
#[pyfunction]
fn request_hobbyist_license(name: String, email: String) -> PyResult<()> {
    LicenseManager::request_hobbyist_license(&name, &email)
        .map(|_| println!("A license key was sent to your e-mail address."))
        .map_err(exceptions::PyConnectionError::new_err)
}

/// Request a key for a trial license for the user `name` working at `company`, that will be sent to the e-mail address `email`.
///
/// Parameters
/// ----------
/// name: str
///     The name of the user.
/// email: str
///     The email address that should receive the license.
/// company: str
///     The company of the user.
#[cfg_attr(
    feature = "python_stubgen",
    gen_stub_pyfunction(module = "symbolica.core")
)]
#[pyfunction]
fn request_trial_license(name: String, email: String, company: String) -> PyResult<()> {
    LicenseManager::request_trial_license(&name, &email, &company)
        .map(|_| println!("A license key was sent to your e-mail address."))
        .map_err(exceptions::PyConnectionError::new_err)
}

/// Request a sublicense key for the user `name` working at `company` that has the site-wide license `super_license`.
/// The key will be sent to the e-mail address `email`.
///
/// Parameters
/// ----------
/// name: str
///     The name of the sublicense user.
/// email: str
///     The email address that should receive the sublicense.
/// company: str
///     The company of the sublicense user.
/// super_license: str
///     The parent site-wide license key.
#[cfg_attr(
    feature = "python_stubgen",
    gen_stub_pyfunction(module = "symbolica.core")
)]
#[pyfunction]
fn request_sublicense(
    name: String,
    email: String,
    company: String,
    super_license: String,
) -> PyResult<()> {
    LicenseManager::request_sublicense(&name, &email, &company, &super_license)
        .map(|_| println!("A license key was sent to your e-mail address."))
        .map_err(exceptions::PyConnectionError::new_err)
}

/// Get the license key for the account registered with the provided email address.
///
/// Parameters
/// ----------
/// email: str
///     The email address of the licensed account.
#[cfg_attr(
    feature = "python_stubgen",
    gen_stub_pyfunction(module = "symbolica.core")
)]
#[pyfunction]
fn get_license_key(email: String) -> PyResult<()> {
    LicenseManager::get_license_key(&email)
        .map(|_| println!("A license key was sent to your e-mail address."))
        .map_err(exceptions::PyConnectionError::new_err)
}

#[pyfunction(name = "S", signature = (*names,is_symmetric=None,is_antisymmetric=None,is_cyclesymmetric=None,is_linear=None,is_scalar=None,is_real=None,is_integer=None,is_positive=None,tags=None,aliases=None,normalization=None,print=None,derivative=None,series=None,eval=None,data=None))]
/// Create new symbols from `names`. Symbols can have attributes,
/// such as symmetries. If no attributes
/// are specified and the symbol was previously defined, the attributes are inherited.
/// Once attributes are defined on a symbol, they cannot be redefined later.
///
/// Examples
/// --------
/// Define a regular symbol and use it as a variable:
/// >>> x = S('x')
/// >>> e = x**2 + 5
/// >>> print(e)  # x**2 + 5
///
/// Define a regular symbol and use it as a function:
/// >>> f = S('f')
/// >>> e = f(1,2)
/// >>> print(e)  # f(1,2)
///
///
/// Define a symmetric function:
/// >>> f = S('f', is_symmetric=True)
/// >>> e = f(2,1)
/// >>> print(e)  # f(1,2)
///
///
/// Define a linear and symmetric function:
/// >>> p1, p2, p3, p4 = S('p1', 'p2', 'p3', 'p4')
/// >>> dot = S('dot', is_symmetric=True, is_linear=True)
/// >>> e = dot(p2+2*p3,p1+3*p2-p3)
/// dot(p1,p2)+2*dot(p1,p3)+3*dot(p2,p2)-dot(p2,p3)+6*dot(p2,p3)-2*dot(p3,p3)
///
/// Define a custom normalization function:
/// >>> e = S('real_log', normalization=T().replace(E("x_(exp(x1_))"), E("x1_")))
/// >>> E("real_log(exp(x)) + real_log(5)")
///
/// Define a custom print function:
/// >>> def print_mu(mu: Expression, mode: PrintMode, **kwargs) -> str | None:
/// >>>     if mode == PrintMode.Latex:
/// >>>         if mu.get_type() == AtomType.Fn:
/// >>>             return "\\mu_{" + ",".join(a.format() for a in mu) + "}"
/// >>>         else:
/// >>>             return "\\mu"
/// >>> mu = S("mu", print=print_mu)
/// >>> expr = E("mu + mu(1,2)")
/// >>> print(expr.to_latex())
///
/// If the function returns `None`, the default print function is used.
///
/// Define a custom derivative function:
/// >>> tag = S('tag', derivative=lambda f, index: f)
/// >>> x = S('x')
/// >>> tag(3, x).derivative(x)
///
/// Define a custom series function that returns the principal part and the regular part,
/// or `None` if a standard construction through the derivative can be used:
/// >>> def inv_series(args: Sequence[Series]) -> tuple[Expression, Expression] | None:
/// >>>     return (N(0), args[0].pow(-1).to_expression())
/// >>>
/// >>> t = S('t')
/// >>> inv = S('inv', series=inv_series)
///
/// Define a function with a custom evaluation:
/// >>> cosh = S(
/// >>>     "my_cosh",
/// >>>     eval={
/// >>>         "float": lambda args: math.cosh(args[0]),
/// >>>         "complex": lambda args: cmath.cosh(args[0]),
/// >>>         "cpp": "template<typename T> T python_my_cosh(T a) { return std::cosh(a); }",
/// >>>     },
/// >>> )
///
/// Add custom data to a symbol:
/// >>> x = S('x', data={'my_tag': 'my_value'})
/// >>> r = x.get_symbol_data('my_tag')
///
/// Parameters
/// ----------
/// *names : str
///     The name of the symbol
/// is_symmetric : bool | None
///     Set to true if the symbol is symmetric.
/// is_antisymmetric : bool | None
///     Set to true if the symbol is antisymmetric.
/// is_cyclesymmetric : bool | None
///     Set to true if the symbol is cyclesymmetric.
/// is_linear : bool | None
///     Set to true if the symbol is linear.
/// is_scalar : bool | None
///     Set to true if the symbol is a scalar. It will be moved out of linear functions.
/// is_real : bool | None
///     Set to true if the symbol is a real number.
/// is_integer : bool | None
///     Set to true if the symbol is an integer.
/// is_positive : bool | None
///     Set to true if the symbol is a positive number.
/// tags: Sequence[str] | None = None
///     A list of tags to associate with the symbol.
/// aliases: Sequence[str] | None = None
///     A list of aliases to associate with the symbol.
/// normalization : Transformer | None
///     A transformer that is called after every normalization. Note that the symbol
///     name cannot be used in the transformer as this will lead to a definition of the
///     symbol. Use a wildcard with the same attributes instead.
/// print : Callable[..., str | None] | None:
///     A function that is called when printing the variable/function, which is provided as its first argument.
///     This function should return a string, or `None` if the default print function should be used.
///     The custom print function takes in keyword arguments that are the same as the arguments of the `format` function.
/// derivative: Callable[[Expression, int], Expression] | None:
///     A function that is called when computing the derivative of a function in a given argument.
/// series: Callable[[Sequence[Series]], tuple[Expression, Expression] | None] | None:
///     A function that is called for custom series expansion. It receives the argument series and can return
///     the singular factor and regularized expression, or `None` to use the default series expansion.
/// eval: dict[str, Any] | None:
///     Numeric evaluation function(s). The dictionary may contain:
///     - `tag_count: int`: the number of leading symbolic tag arguments.
///     - `cpp: str`: a C++ function definition inserted into exported C++ code for this symbol.
///
///     For arbitrary precision evaluation of constant functions, register a function that
///     maps the tags and the requested decimal precision to a number:
///     - `constant`: (Sequence[Expression], int) -> Decimal | float | complex | tuple[Decimal, Decimal]]
///
///     Evaluators for non-constant functions when `tag_count = 0`:
///     - `float`: Sequence[float] -> float
///     - `complex`: Sequence[complex] -> complex
///     - `decimal`: Sequence[Decimal] -> Decimal
///     - `decimal_complex`: Sequence[tuple[Decimal, Decimal]] -> tuple[Decimal, Decimal]
///
///     Evaluators for non-constant functions when `tag_count > 0` are generators:
///     - `float`: Sequence[Expression] -> (Sequence[float] -> float)
///     - `complex`: Sequence[Expression] -> (Sequence[complex] -> complex)
///     - `decimal`: Sequence[Expression] -> (Sequence[Decimal] -> Decimal)
///     - `decimal_complex`: Sequence[Expression] -> (Sequence[tuple[Decimal, Decimal]] -> tuple[Decimal, Decimal])
/// data: str | int | Expression | bytes | list | dict | None = None
///     Custom user data to associate with the symbol.
fn symbol_shorthand(
    names: &Bound<'_, PyTuple>,
    is_symmetric: Option<bool>,
    is_antisymmetric: Option<bool>,
    is_cyclesymmetric: Option<bool>,
    is_linear: Option<bool>,
    is_scalar: Option<bool>,
    is_real: Option<bool>,
    is_integer: Option<bool>,
    is_positive: Option<bool>,
    tags: Option<Vec<String>>,
    aliases: Option<Vec<String>>,
    normalization: Option<PythonTransformer>,
    print: Option<Py<PyAny>>,
    derivative: Option<Py<PyAny>>,
    series: Option<Py<PyAny>>,
    eval: Option<Py<PyAny>>,
    data: Option<PythonUserData>,
    py: Python,
) -> PyResult<Py<PyAny>> {
    PythonExpression::symbol(
        &PythonExpression::type_object(py),
        py,
        names,
        is_symmetric,
        is_antisymmetric,
        is_cyclesymmetric,
        is_linear,
        is_scalar,
        is_real,
        is_integer,
        is_positive,
        tags,
        aliases,
        normalization,
        print,
        derivative,
        series,
        eval,
        data,
    )
}

#[derive(Clone)]
struct PythonEvalSpec {
    tag_count: usize,
    float: Option<Py<PyAny>>,
    complex: Option<Py<PyAny>>,
    decimal: Option<Py<PyAny>>,
    decimal_complex: Option<Py<PyAny>>,
    constant: Option<Py<PyAny>>,
    cpp: Option<String>,
}

impl PythonEvalSpec {
    const ALLOWED_KEYS: &[&str] = &[
        "tag_count",
        "float",
        "complex",
        "decimal",
        "decimal_complex",
        "constant",
        "cpp",
    ];

    fn from_py(py: Python, eval: Py<PyAny>) -> PyResult<Self> {
        let eval_bound = eval.bind(py);

        let dict = eval_bound
            .cast::<PyDict>()
            .map_err(|_| exceptions::PyTypeError::new_err("eval must be a dictionary"))?;
        Self::validate_eval_dict_keys(dict)?;

        let tag_count = match dict.get_item("tag_count") {
            Ok(Some(t)) => t.extract::<usize>()?,
            Ok(None) => 0,
            Err(_) => 0,
        };

        let spec = Self {
            tag_count,
            float: Self::get_eval_callable(dict, "float")?,
            complex: Self::get_eval_callable(dict, "complex")?,
            decimal: Self::get_eval_callable(dict, "decimal")?,
            decimal_complex: Self::get_eval_callable(dict, "decimal_complex")?,
            constant: Self::get_eval_callable(dict, "constant")?,
            cpp: Self::get_eval_string(dict, "cpp")?,
        };

        if spec.constant.is_some()
            && (spec.float.is_some()
                || spec.complex.is_some()
                || spec.decimal.is_some()
                || spec.decimal_complex.is_some())
        {
            return Err(exceptions::PyValueError::new_err(
                "eval['constant'] cannot be combined with other eval callbacks",
            ));
        }

        Ok(spec)
    }

    fn validate_eval_dict_keys(dict: &Bound<'_, PyDict>) -> PyResult<()> {
        for key in dict.keys() {
            let key = key.extract::<String>().map_err(|_| {
                exceptions::PyTypeError::new_err("eval dictionary keys must be strings")
            })?;

            if !Self::ALLOWED_KEYS.contains(&key.as_str()) {
                return Err(exceptions::PyValueError::new_err(format!(
                    "Unknown eval dictionary entry '{key}'. Allowed entries are: {}",
                    Self::ALLOWED_KEYS.join(", ")
                )));
            }
        }

        Ok(())
    }

    fn into_evaluation_info(self) -> EvaluationInfo {
        let tag_count = self.tag_count;
        let mut info = if let Some(f) = self.constant {
            EvaluationInfo::constant(move |tags, prec| {
                if tags.len() != tag_count {
                    return Err(format!(
                        "Python eval expected {tag_count} tags, got {}",
                        tags.len()
                    ));
                }

                Python::attach(|py| {
                    let f = Self::python_eval_callable(py, &f, tags, tag_count)?;
                    let decimal_prec = Self::decimal_digits_from_binary_prec(prec);
                    let args = Vec::<(PythonMultiPrecisionFloat, PythonMultiPrecisionFloat)>::new();
                    let value = f.call1(py, (args.into_py_any(py)?, decimal_prec))?;
                    Self::extract_python_constant(py, value)
                })
                .map_err(|e| e.to_string())
            })
            .with_tags(tag_count)
        } else {
            EvaluationInfo::new().with_tags(tag_count)
        };

        if let Some(f) = self.float {
            if tag_count == 0 {
                info = info.register(move |args: &[f64]| {
                    match Python::attach(|py| {
                        f.call1(py, (args.to_vec().into_py_any(py)?,))?
                            .extract::<f64>(py)
                    }) {
                        Ok(value) => value,
                        Err(err) => {
                            error!("Python eval callback for f64 failed: {err}");
                            f64::NAN
                        }
                    }
                });
            } else {
                info = info.register_tagged(move |tags| {
                    let f = match Python::attach(|py| {
                        Self::python_eval_callable(py, &f, tags, tag_count)
                    }) {
                        Ok(f) => f,
                        Err(err) => {
                            error!("Python tagged eval callback for f64 failed: {err}");
                            return Box::new(|_: &[f64]| f64::NAN);
                        }
                    };
                    Box::new(move |args: &[f64]| {
                        match Python::attach(|py| {
                            f.call1(py, (args.to_vec().into_py_any(py)?,))?
                                .extract::<f64>(py)
                        }) {
                            Ok(value) => value,
                            Err(err) => {
                                error!("Python eval callback for f64 failed: {err}");
                                f64::NAN
                            }
                        }
                    })
                });
            }
        }

        if let Some(f) = self.complex {
            if tag_count == 0 {
                info = info.register(move |args: &[Complex<f64>]| {
                    match Python::attach(|py| {
                        let args = args
                            .iter()
                            .map(|x| PyComplex::from_doubles(py, x.re, x.im))
                            .collect::<Vec<_>>();
                        f.call1(py, (args.into_py_any(py)?,))?
                            .extract::<Complex<f64>>(py)
                    }) {
                        Ok(value) => value,
                        Err(err) => {
                            error!("Python eval callback for complex f64 failed: {err}");
                            Complex::new(f64::NAN, f64::NAN)
                        }
                    }
                });
            } else {
                info = info.register_tagged(move |tags| {
                    let f = match Python::attach(|py| {
                        Self::python_eval_callable(py, &f, tags, tag_count)
                    }) {
                        Ok(f) => f,
                        Err(err) => {
                            error!("Python tagged eval callback for complex f64 failed: {err}");
                            return Box::new(|_: &[Complex<f64>]| Complex::new(f64::NAN, f64::NAN));
                        }
                    };
                    Box::new(move |args: &[Complex<f64>]| {
                        match Python::attach(|py| {
                            let args = args
                                .iter()
                                .map(|x| PyComplex::from_doubles(py, x.re, x.im))
                                .collect::<Vec<_>>();
                            f.call1(py, (args.into_py_any(py)?,))?
                                .extract::<Complex<f64>>(py)
                        }) {
                            Ok(value) => value,
                            Err(err) => {
                                error!("Python eval callback for complex f64 failed: {err}");
                                Complex::new(f64::NAN, f64::NAN)
                            }
                        }
                    })
                });
            }
        }

        if let Some(f) = self.decimal {
            if tag_count == 0 {
                info = info.register(move |args: &[Float]| {
                    match Python::attach(|py| {
                        let args = args
                            .iter()
                            .cloned()
                            .map(PythonMultiPrecisionFloat)
                            .collect::<Vec<_>>();
                        f.call1(py, (args.into_py_any(py)?,))?
                            .extract::<PythonMultiPrecisionFloat>(py)
                            .map(|x| x.0)
                    }) {
                        Ok(value) => value,
                        Err(err) => {
                            error!("Python eval callback for decimal failed: {err}");
                            Float::with_val(53, f64::NAN)
                        }
                    }
                });
            } else {
                info = info.register_tagged(move |tags| {
                    let f = match Python::attach(|py| {
                        Self::python_eval_callable(py, &f, tags, tag_count)
                    }) {
                        Ok(f) => f,
                        Err(err) => {
                            error!("Python tagged eval callback for decimal failed: {err}");
                            return Box::new(|_: &[Float]| Float::with_val(53, f64::NAN));
                        }
                    };
                    Box::new(move |args: &[Float]| {
                        match Python::attach(|py| {
                            let args = args
                                .iter()
                                .cloned()
                                .map(PythonMultiPrecisionFloat)
                                .collect::<Vec<_>>();
                            f.call1(py, (args.into_py_any(py)?,))?
                                .extract::<PythonMultiPrecisionFloat>(py)
                                .map(|x| x.0)
                        }) {
                            Ok(value) => value,
                            Err(err) => {
                                error!("Python eval callback for decimal failed: {err}");
                                Float::with_val(53, f64::NAN)
                            }
                        }
                    })
                });
            }
        }

        if let Some(f) = self.decimal_complex {
            if tag_count == 0 {
                info = info.register(move |args: &[Complex<Float>]| {
                    match Python::attach(|py| {
                        let args = args
                            .iter()
                            .map(|x| (x.re.clone().into(), x.im.clone().into()))
                            .collect::<Vec<(PythonMultiPrecisionFloat, PythonMultiPrecisionFloat)>>(
                            );
                        let (re, im) = f.call1(py, (args.into_py_any(py)?,))?.extract::<(
                            PythonMultiPrecisionFloat,
                            PythonMultiPrecisionFloat,
                        )>(
                            py
                        )?;
                        Ok::<Complex<Float>, PyErr>(Complex::new(re.0, im.0))
                    }) {
                        Ok(value) => value,
                        Err(err) => {
                            error!("Python eval callback for decimal complex failed: {err}");
                            Complex::new(
                                Float::with_val(53, f64::NAN),
                                Float::with_val(53, f64::NAN),
                            )
                        }
                    }
                });
            } else {
                info = info.register_tagged(move |tags| {
                    let f = match Python::attach(|py| {
                        Self::python_eval_callable(py, &f, tags, tag_count)
                    }) {
                        Ok(f) => f,
                        Err(err) => {
                            error!("Python tagged eval callback for decimal complex failed: {err}");
                            return Box::new(|_: &[Complex<Float>]| {
                                Complex::new(
                                    Float::with_val(53, f64::NAN),
                                    Float::with_val(53, f64::NAN),
                                )
                            });
                        }
                    };
                    Box::new(move |args: &[Complex<Float>]| {
                        match Python::attach(|py| {
                            let args = args
                                .iter()
                                .map(|x| (x.re.clone().into(), x.im.clone().into()))
                                .collect::<Vec<(
                                    PythonMultiPrecisionFloat,
                                    PythonMultiPrecisionFloat,
                                )>>();
                            let (re, im) = f.call1(py, (args.into_py_any(py)?,))?.extract::<(
                                PythonMultiPrecisionFloat,
                                PythonMultiPrecisionFloat,
                            )>(
                                py
                            )?;
                            Ok::<Complex<Float>, PyErr>(Complex::new(re.0, im.0))
                        }) {
                            Ok(value) => value,
                            Err(err) => {
                                error!("Python eval callback for decimal complex failed: {err}");
                                Complex::new(
                                    Float::with_val(53, f64::NAN),
                                    Float::with_val(53, f64::NAN),
                                )
                            }
                        }
                    })
                });
            }
        }

        if let Some(snippet) = self.cpp {
            info.with_cpp(snippet)
        } else {
            info
        }
    }

    fn get_eval_callable(dict: &Bound<'_, PyDict>, key: &str) -> PyResult<Option<Py<PyAny>>> {
        if let Ok(Some(value)) = dict.get_item(key) {
            if !value.is_callable() {
                return Err(exceptions::PyTypeError::new_err(format!(
                    "eval['{key}'] must be callable"
                )));
            }

            return Ok(Some(value.unbind()));
        }

        Ok(None)
    }

    fn get_eval_string(dict: &Bound<'_, PyDict>, key: &str) -> PyResult<Option<String>> {
        if let Ok(Some(value)) = dict.get_item(key) {
            return value.extract::<String>().map(Some).map_err(|_| {
                exceptions::PyTypeError::new_err(format!("eval['{key}'] must be a string"))
            });
        }

        Ok(None)
    }

    fn decimal_digits_from_binary_prec(prec: u32) -> u32 {
        ((prec as f64 / std::f64::consts::LOG2_10).ceil() as u32).max(1)
    }

    fn extract_python_constant(py: Python, value: Py<PyAny>) -> PyResult<Complex<Float>> {
        if let Ok((re, im)) = value.extract::<(PythonExpression, PythonExpression)>(py)
            && let Ok(re_f) = Float::try_from(&re.expr)
            && let Ok(im_f) = Float::try_from(&im.expr)
        {
            Ok(Complex::new(re_f, im_f))
        } else if let Ok(re) = value.extract::<PythonExpression>(py)
            && let Ok(re_f) = Float::try_from(&re.expr)
        {
            Ok(re_f.into())
        } else if let Ok((re, im)) =
            value.extract::<(PythonMultiPrecisionFloat, PythonMultiPrecisionFloat)>(py)
        {
            Ok(Complex::new(re.0, im.0))
        } else if let Ok(re) = value.extract::<PythonMultiPrecisionFloat>(py) {
            Ok(re.0.into())
        } else if let Ok(value) = value.extract::<Complex<f64>>(py) {
            Ok(Complex::new(value.re.into(), value.im.into()))
        } else {
            Err(exceptions::PyTypeError::new_err(
                "eval['constant'] must return a number or a (real, imag) tuple",
            ))
        }
    }

    fn atom_view_tags_to_python(py: Python, tags: &[AtomView]) -> PyResult<Py<PyAny>> {
        tags.iter()
            .map(|x| PythonExpression::from(x.to_owned()))
            .collect::<Vec<_>>()
            .into_py_any(py)
    }

    fn python_eval_callable(
        py: Python,
        f: &Py<PyAny>,
        tags: &[AtomView],
        tag_count: usize,
    ) -> PyResult<Py<PyAny>> {
        if tags.len() != tag_count {
            return Err(exceptions::PyValueError::new_err(format!(
                "Python eval expected {tag_count} tags, got {}",
                tags.len()
            )));
        }

        if tag_count == 0 {
            Ok(f.clone_ref(py))
        } else {
            let tagged = f.call1(py, (Self::atom_view_tags_to_python(py, tags)?,))?;
            if tagged.bind(py).is_callable() {
                Ok(tagged)
            } else {
                Err(exceptions::PyTypeError::new_err(
                    "tagged Python eval callback must return a callable",
                ))
            }
        }
    }
}

#[cfg(feature = "python_stubgen")]
submit! {
PyFunctionInfo {
            name: "S",
            parameters: &[
                ParameterInfo {
                    name: "names",
                    kind: ParameterKind::VarPositional,
                    type_info: || <&str>::type_input(),
                    default: ParameterDefault::Expr(NONE_ARG),
                },
                ParameterInfo {
                    name: "is_symmetric",
                    kind: ParameterKind::PositionalOrKeyword,
                    default: ParameterDefault::Expr(NONE_ARG),
                    type_info: || Option::<bool>::type_input(),
                },
                ParameterInfo {
                    name: "is_antisymmetric",
                    kind: ParameterKind::PositionalOrKeyword,
                    default: ParameterDefault::Expr(NONE_ARG),
                    type_info: || Option::<bool>::type_input(),
                },
                ParameterInfo {
                    name: "is_cyclesymmetric",
                    kind: ParameterKind::PositionalOrKeyword,
                    default: ParameterDefault::Expr(NONE_ARG),
                    type_info: || Option::<bool>::type_input(),
                },
                ParameterInfo {
                    name: "is_linear",
                    kind: ParameterKind::PositionalOrKeyword,
                    default: ParameterDefault::Expr(NONE_ARG),
                    type_info: || Option::<bool>::type_input(),
                },
                ParameterInfo {
                    name: "is_scalar",
                    kind: ParameterKind::PositionalOrKeyword,
                    default: ParameterDefault::Expr(NONE_ARG),
                    type_info: || Option::<bool>::type_input(),
                },
                ParameterInfo {
                    name: "is_real",
                    kind: ParameterKind::PositionalOrKeyword,
                    default: ParameterDefault::Expr(NONE_ARG),
                    type_info: || Option::<bool>::type_input(),
                },
                ParameterInfo {
                    name: "is_integer",
                    kind: ParameterKind::PositionalOrKeyword,
                    default: ParameterDefault::Expr(NONE_ARG),
                    type_info: || Option::<bool>::type_input(),
                },
                ParameterInfo {
                    name: "is_positive",
                    kind: ParameterKind::PositionalOrKeyword,
                    default: ParameterDefault::Expr(NONE_ARG),
                    type_info: || Option::<bool>::type_input(),
                },
                ParameterInfo {
                    name: "tags",
                    kind: ParameterKind::PositionalOrKeyword,
                    default: ParameterDefault::Expr(NONE_ARG),
                    type_info: || Option::<Vec<String>>::type_input(),
                },
            ],
            r#return: || Vec::<PythonExpression>::type_output(),
            doc:
            r#"Create new symbols from `names`. Symbols can have attributes,
such as symmetries. If no attributes
are specified and the symbol was previously defined, the attributes are inherited.
Once attributes are defined on a symbol, they cannot be redefined later.

Examples
--------
Define two regular symbols:
>>> x, y = S('x', 'y')

Define two symmetric functions:
>>> f, g = S('f', 'g', is_symmetric=True)
>>> e = f(2,1)
>>> print(e)  # f(1,2)

Parameters
----------
*names : str
    The name of the symbol
is_symmetric : bool | None
    Set to true if the symbol is symmetric.
is_antisymmetric : bool | None
    Set to true if the symbol is antisymmetric.
is_cyclesymmetric : bool | None
    Set to true if the symbol is cyclesymmetric.
is_linear : bool | None
    Set to true if the symbol is multilinear.
is_scalar : bool | None
    Set to true if the symbol is a scalar. It will be moved out of linear functions.
is_real : bool | None
    Set to true if the symbol is a real number.
is_integer : bool | None
    Set to true if the symbol is an integer.
is_positive : bool | None
    Set to true if the symbol is a positive number.
tags: Sequence[str] | None = None
    A list of tags to associate with the symbol."#,
            module: Some("symbolica.core"),
            is_async: false,
            deprecated: None,
            type_ignored: None,
            is_overload: true,
            file: "symbolica.rs",
            line: line!(),
            column: column!(),
            index: 0,
        }
}

#[cfg(feature = "python_stubgen")]
submit! {
PyFunctionInfo {
            name: "S",
            parameters: &[
                ParameterInfo {
                    name: "name",
                    kind: ParameterKind::PositionalOrKeyword,
                    default: ParameterDefault::None,
                    type_info: || <&str>::type_input(),
                },
                ParameterInfo {
                    name: "is_symmetric",
                    kind: ParameterKind::PositionalOrKeyword,
                    default: ParameterDefault::Expr(NONE_ARG),
                    type_info: || Option::<bool>::type_input(),
                },
                ParameterInfo {
                    name: "is_antisymmetric",
                    kind: ParameterKind::PositionalOrKeyword,
                    default: ParameterDefault::Expr(NONE_ARG),
                    type_info: || Option::<bool>::type_input(),
                },
                ParameterInfo {
                    name: "is_cyclesymmetric",
                    kind: ParameterKind::PositionalOrKeyword,
                    default: ParameterDefault::Expr(NONE_ARG),
                    type_info: || Option::<bool>::type_input(),
                },
                ParameterInfo {
                    name: "is_linear",
                    kind: ParameterKind::PositionalOrKeyword,
                    default: ParameterDefault::Expr(NONE_ARG),
                    type_info: || Option::<bool>::type_input(),
                },
                ParameterInfo {
                    name: "is_scalar",
                    kind: ParameterKind::PositionalOrKeyword,
                    default: ParameterDefault::Expr(NONE_ARG),
                    type_info: || Option::<bool>::type_input(),
                },
                ParameterInfo {
                    name: "is_real",
                    kind: ParameterKind::PositionalOrKeyword,
                    default: ParameterDefault::Expr(NONE_ARG),
                    type_info: || Option::<bool>::type_input(),
                },
                ParameterInfo {
                    name: "is_integer",
                    kind: ParameterKind::PositionalOrKeyword,
                    default: ParameterDefault::Expr(NONE_ARG),
                    type_info: || Option::<bool>::type_input(),
                },
                ParameterInfo {
                    name: "is_positive",
                    kind: ParameterKind::PositionalOrKeyword,
                    default: ParameterDefault::Expr(NONE_ARG),
                    type_info: || Option::<bool>::type_input(),
                },
                ParameterInfo {
                    name: "tags",
                    kind: ParameterKind::PositionalOrKeyword,
                    default: ParameterDefault::Expr(NONE_ARG),
                    type_info: || Option::<Vec<String>>::type_input(),
                },
                ParameterInfo {
                    name: "aliases",
                    kind: ParameterKind::PositionalOrKeyword,
                    default: ParameterDefault::Expr(NONE_ARG),
                    type_info: || Option::<Vec<String>>::type_input(),
                },
                ParameterInfo {
                    name: "normalization",
                    kind: ParameterKind::PositionalOrKeyword,
                    default: ParameterDefault::Expr(NONE_ARG),
                    type_info: || Option::<PythonTransformer>::type_input(),
                },
                ParameterInfo {
                    name: "print",
                    kind: ParameterKind::PositionalOrKeyword,
                    default: ParameterDefault::Expr(NONE_ARG),
                    type_info: || TypeInfo::unqualified("typing.Optional[typing.Callable[..., typing.Optional[str]]]"),
                },
                ParameterInfo {
                    name: "derivative",
                    kind: ParameterKind::PositionalOrKeyword,
                    default: ParameterDefault::Expr(NONE_ARG),
                    type_info: || TypeInfo::unqualified("typing.Optional[typing.Callable[[Expression, int], Expression]]"),
                },
                ParameterInfo {
                    name: "series",
                    kind: ParameterKind::PositionalOrKeyword,
                    default: ParameterDefault::Expr(NONE_ARG),
                    type_info: || TypeInfo::unqualified("typing.Optional[typing.Callable[[typing.Sequence[Series]], typing.Optional[tuple[Expression, Expression]]]]"),
                },
                ParameterInfo {
                    name: "eval",
                    kind: ParameterKind::PositionalOrKeyword,
                    default: ParameterDefault::Expr(NONE_ARG),
                    type_info: || TypeInfo::unqualified("typing.Optional[dict[str, typing.Any]]"),
                },
                ParameterInfo {
                    name: "data",
                    kind: ParameterKind::PositionalOrKeyword,
                    default: ParameterDefault::Expr(NONE_ARG),
                    type_info: || TypeInfo::unqualified("typing.Optional[str | int | Expression | bytes | list | dict]"),
                },
            ],
            r#return: || PythonExpression::type_output(),
            doc:
            r#"Create new symbols from `names`. Symbols can have attributes,
such as symmetries. If no attributes
are specified and the symbol was previously defined, the attributes are inherited.
Once attributes are defined on a symbol, they cannot be redefined later.

Examples
--------
Define a regular symbol and use it as a variable:
>>> x = S('x')
>>> e = x**2 + 5
>>> print(e)  # x**2 + 5

Define a regular symbol and use it as a function:
>>> f = S('f')
>>> e = f(1,2)
>>> print(e)  # f(1,2)


Define a symmetric function:
>>> f = S('f', is_symmetric=True)
>>> e = f(2,1)
>>> print(e)  # f(1,2)


Define a linear and symmetric function:
>>> p1, p2, p3, p4 = S('p1', 'p2', 'p3', 'p4')
>>> dot = S('dot', is_symmetric=True, is_linear=True)
>>> e = dot(p2+2*p3,p1+3*p2-p3)
dot(p1,p2)+2*dot(p1,p3)+3*dot(p2,p2)-dot(p2,p3)+6*dot(p2,p3)-2*dot(p3,p3)

Define a custom normalization function:
>>> e = S('real_log', normalization=T().replace(E("x_(exp(x1_))"), E("x1_")))
>>> E("real_log(exp(x)) + real_log(5)")

Define a custom print function:
>>> def print_mu(mu: Expression, mode: PrintMode, **kwargs) -> str | None:
>>>     if mode == PrintMode.Latex:
>>>         if mu.get_type() == AtomType.Fn:
>>>             return "\\mu_{" + ",".join(a.format() for a in mu) + "}"
>>>         else:
>>>             return "\\mu"
>>> mu = S("mu", print=print_mu)
>>> expr = E("mu + mu(1,2)")
>>> print(expr.to_latex())

If the function returns `None`, the default print function is used.

Define a custom derivative function:
>>> tag = S('tag', derivative=lambda f, index: f)
>>> x = S('x')
>>> tag(3, x).derivative(x)

Define a custom series function that returns the principal part and the regular part,
or `None` if a standard construction through the derivative can be used:
>>> def inv_series(args: Sequence[Series]) -> tuple[Expression, Expression] | None:
>>>     return (N(0), args[0].pow(-1).to_expression())
>>>
>>> t = S('t')
>>> inv = S('inv', series=inv_series)

Define a function with a custom evaluation:
>>> cosh = S(
>>>     "my_cosh",
>>>     eval={
>>>         "float": lambda args: math.cosh(args[0]),
>>>         "complex": lambda args: cmath.cosh(args[0]),
>>>         "cpp": "template<typename T> T python_my_cosh(T a) { return std::cosh(a); }",
>>>     },
>>> )

Add custom data to a symbol:
>>> x = S('x', data={'my_tag': 'my_value'})
>>> r = x.get_symbol_data('my_tag')

Parameters
----------
name : str
    The name of the symbol
is_symmetric : bool | None
    Set to true if the symbol is symmetric.
is_antisymmetric : bool | None
    Set to true if the symbol is antisymmetric.
is_cyclesymmetric : bool | None
    Set to true if the symbol is cyclesymmetric.
is_linear : bool | None
    Set to true if the symbol is linear.
is_scalar : bool | None
    Set to true if the symbol is a scalar. It will be moved out of linear functions.
is_real : bool | None
    Set to true if the symbol is a real number.
is_integer : bool | None
    Set to true if the symbol is an integer.
is_positive : bool | None
    Set to true if the symbol is a positive number.
tags: Sequence[str] | None = None
    A list of tags to associate with the symbol.
aliases: Sequence[str] | None = None
    A list of aliases to associate with the symbol.
normalization : Transformer | None
    A transformer that is called after every normalization. Note that the symbol
    name cannot be used in the transformer as this will lead to a definition of the
    symbol. Use a wildcard with the same attributes instead.
print : Callable[..., str | None] | None:
    A function that is called when printing the variable/function, which is provided as its first argument.
    This function should return a string, or `None` if the default print function should be used.
    The custom print function takes in keyword arguments that are the same as the arguments of the `format` function.
derivative: Callable[[Expression, int], Expression] | None:
    A function that is called when computing the derivative of a function in a given argument.
series: Callable[[Sequence[Series]], tuple[Expression, Expression] | None] | None:
    A function that is called for custom series expansion. It receives the argument series and can return
    the singular factor and regularized expression, or `None` to use the default series expansion.
eval: dict[str, Any] | None:
    Numeric evaluation function(s). The dictionary may contain:
    - `tag_count: int`: the number of leading symbolic tag arguments.
    - `cpp: str`: a C++ function definition inserted into exported C++ code for this symbol.

    For arbitrary precision evaluation of constant functions, register a function that
    maps the tags and the requested decimal precision to a number:
    - `constant`: (Sequence[Expression], int) -> Decimal | float | complex | tuple[Decimal, Decimal]]

    Evaluators for non-constant functions when `tag_count = 0`:
    - `float`: Sequence[float] -> float
    - `complex`: Sequence[complex] -> complex
    - `decimal`: Sequence[Decimal] -> Decimal
    - `decimal_complex`: Sequence[tuple[Decimal, Decimal]] -> tuple[Decimal, Decimal]

    Evaluators for non-constant functions when `tag_count > 0` are generators:
    - `float`: Sequence[Expression] -> (Sequence[float] -> float)
    - `complex`: Sequence[Expression] -> (Sequence[complex] -> complex)
    - `decimal`: Sequence[Expression] -> (Sequence[Decimal] -> Decimal)
    - `decimal_complex`: Sequence[Expression] -> (Sequence[tuple[Decimal, Decimal]] -> tuple[Decimal, Decimal])
data: str | int | Expression | bytes | list | dict | None = None
    Custom user data to associate with the symbol."#,
            module: Some("symbolica.core"),
            is_async: false,
            deprecated: None,
            type_ignored: None,
            is_overload: true,
            file: "symbolica.rs",
            line: line!(),
            column: column!(),
            index: 1,
        }
}

/// Create a new Symbolica number from an int, a float, or a string.
/// A floating point number is kept as a float with the same precision as the input,
/// but it can also be converted to the smallest rational number given a `relative_error`.
///
/// Examples
/// --------
/// >>> e = N(1) / 2
/// >>> print(e)  # 1/2
///
/// >>> print(N(1/3))
/// >>> print(N(0.33, 0.1))
/// >>> print(N('0.333`3'))
/// >>> print(N(Decimal('0.1234')))
/// 3.3333333333333331e-1
/// 1/3
/// 3.33e-1
/// 1.2340e-1
///
/// Parameters
/// ----------
/// num: int | float | complex | str | Decimal
///     The value to convert into a Symbolica number.
/// relative_error: float | None
///     The maximum relative error used when converting floating-point input to a rational number.
#[cfg_attr(
    feature = "python_stubgen",
    gen_stub_pyfunction(module = "symbolica.core")
)]
#[cfg_attr(not(feature = "python_stubgen"), remove_gen_stub)]
#[pyfunction(name = "N", signature = (num,relative_error=None))]
fn number_shorthand(
    #[gen_stub(override_type(type_repr = "int | float | complex | str | decimal.Decimal", imports = ("decimal")))]
    num: Py<PyAny>,
    relative_error: Option<f64>,
    py: Python,
) -> PyResult<PythonExpression> {
    PythonExpression::num(&PythonExpression::type_object(py), py, num, relative_error)
}

/// Parse a Symbolica expression from a string.
///
/// Parameters
/// ----------
/// expr: str
///     An input string. UTF-8 characters are allowed.
/// mode: ParseMode
///     The parsing mode to use. Use `ParseMode.Mathematica` to parse Mathematica expressions.
/// default_namespace: str
///     The default namespace to use when parsing symbols.
///
/// Examples
/// --------
/// >>> e = E('x^2+y+y*4')
/// >>> print(e)
/// x^2+5*y
///
/// >>> e = E('Cos[test`x] (2+ 3 I)', mode=ParseMode.Mathematica)
/// >>> print(e)
///
/// `cos(test::x)(2+3i)`
///
/// Raises
/// ------
/// ValueError
///     If the input is not a valid expression.
#[cfg_attr(
    feature = "python_stubgen",
    gen_stub_pyfunction(module = "symbolica.core")
)]
#[pyfunction(name = "E", signature = (expr, mode=PythonParseMode::Symbolica, default_namespace=None))]
fn expression_shorthand(
    expr: &str,
    mode: PythonParseMode,
    default_namespace: Option<String>,
    py: Python,
) -> PyResult<PythonExpression> {
    PythonExpression::parse(
        &PythonExpression::type_object(py),
        py,
        expr,
        mode,
        default_namespace,
    )
}

/// Create a new transformer that maps an expression.
#[cfg_attr(
    feature = "python_stubgen",
    gen_stub_pyfunction(module = "symbolica.core")
)]
#[pyfunction(name = "T")]
fn transformer_shorthand() -> PythonTransformer {
    PythonTransformer::new()
}

#[pyfunction(name = "P", signature = (expr, default_namespace=None, modulus = None, power = None, minimal_poly = None, vars = None))]
/// Parse a string to a polynomial, optionally, with the variables and the ordering specified in `vars`.
/// All non-polynomial elements will be converted to new independent variables.
///
/// The coefficients will be converted to finite field elements modulo `modulus`.
/// If on top a `power` is provided, for example `(2, a)`, the polynomial will be converted to the Galois field
/// `GF(modulus^2)` where `a` is the variable of the minimal polynomial of the field.
///
/// If a `minimal_poly` is provided, the Galois field will be created with `minimal_poly` as the minimal polynomial.
///
/// Parameters
/// ----------
/// expr: str
///     The polynomial expression to parse.
/// modulus: int
///     The modulus that defines the finite field.
/// default_namespace: str | None
///     The namespace assumed for unqualified symbols during parsing.
/// power: tuple[int, Expression] | None
///     The extension degree and generator that define the finite field.
/// minimal_poly: Polynomial | None
///     The minimal polynomial that defines the algebraic extension.
/// vars: Sequence[Expression] | None
///     The variables to treat as polynomial variables, in the given order.
fn poly_shorthand(
    expr: &str,
    default_namespace: Option<String>,
    modulus: Option<u64>,
    power: Option<(u16, Symbol)>,
    minimal_poly: Option<PythonPolynomial>,
    vars: Option<Vec<PythonExpression>>,
    py: Python,
) -> PyResult<Py<PyAny>> {
    PythonExpression::parse(
        &PythonExpression::type_object(py),
        py,
        expr,
        PythonParseMode::Symbolica,
        default_namespace,
    )?
    .to_polynomial(modulus, power, minimal_poly, vars, py)
}

#[cfg(feature = "python_stubgen")]
submit! {
PyFunctionInfo {
        name: "P",
        parameters: &[
            ParameterInfo {
                name: "poly",
                kind: ParameterKind::PositionalOrKeyword,
                default: ParameterDefault::None,
                type_info: || <&str>::type_input(),
            },
            ParameterInfo {
                name: "default_namespace",
                kind: ParameterKind::PositionalOrKeyword,
                default: ParameterDefault::Expr(NONE_ARG),
                type_info: || <Option<&str>>::type_input(),
            },
            ParameterInfo {
                name: "vars",
                kind: ParameterKind::PositionalOrKeyword,
                default: ParameterDefault::Expr(NONE_ARG),
                type_info: || Option::<Vec<PythonExpression>>::type_input(),
            },
        ],
        r#return: || PythonPolynomial::type_output(),
        doc:
        r#"Parse a string to a polynomial, optionally, with the variable ordering specified in `vars`.
All non-polynomial parts will be converted to new, independent variables.

Parameters
----------
poly: str
    The polynomial expression to parse.
default_namespace: str | None
    The namespace assumed for unqualified symbols during parsing.
vars: Sequence[Expression] | None
    The variables to treat as polynomial variables, in the given order."#,
        module: Some("symbolica.core"),
        is_async: false,
        deprecated: None,
        type_ignored: None,
        is_overload: true,
        file: "symbolica.rs",
        line: line!(),
        column: column!(),
        index: 0,
        }
    }

#[cfg(feature = "python_stubgen")]
submit! {
    PyFunctionInfo {
        name: "P",
        parameters: &[
            ParameterInfo {
                name: "poly",
                kind: ParameterKind::PositionalOrKeyword,
                default: ParameterDefault::None,
                type_info: || <&str>::type_input(),
            },
            ParameterInfo {
                name: "minimal_poly",
                kind: ParameterKind::PositionalOrKeyword,
                default: ParameterDefault::None,
                type_info: || PythonPolynomial::type_input(),
            },
            ParameterInfo {
                name: "default_namespace",
                kind: ParameterKind::PositionalOrKeyword,
                default: ParameterDefault::Expr(NONE_ARG),
                type_info: || <Option<&str>>::type_input(),
            },
            ParameterInfo {
                name: "vars",
                kind: ParameterKind::PositionalOrKeyword,
                default: ParameterDefault::Expr(NONE_ARG),
                type_info: || Option::<Vec<PythonExpression>>::type_input(),
            },
        ],
        r#return: || PythonNumberFieldPolynomial::type_output(),
        doc:
        r#"Parse a string to a polynomial, optionally, with the variables and the ordering specified in `vars`.
All non-polynomial elements will be converted to new independent variables.

The coefficients will be converted to a number field with the minimal polynomial `minimal_poly`.
The minimal polynomial must be a monic, irreducible univariate polynomial.

Parameters
----------
poly: str
    The polynomial expression to parse.
minimal_poly: Polynomial
    The minimal polynomial that defines the algebraic extension.
default_namespace: str | None
    The namespace assumed for unqualified symbols during parsing.
vars: Sequence[Expression] | None
    The variables to treat as polynomial variables, in the given order."#,
        module: Some("symbolica.core"),
        is_async: false,
        deprecated: None,
        type_ignored: None,
        is_overload: true,
        file: "symbolica.rs",
        line: line!(),
        column: column!(),
        index: 1,
    }
}

#[cfg(feature = "python_stubgen")]
submit! {
    PyFunctionInfo {
        name: "P",
        parameters: &[
            ParameterInfo {
                name: "poly",
                kind: ParameterKind::PositionalOrKeyword,
                default: ParameterDefault::None,
                type_info: || <&str>::type_input(),
            },
            ParameterInfo {
                name: "modulus",
                kind: ParameterKind::PositionalOrKeyword,
                default: ParameterDefault::None,
                type_info: || usize::type_input(),
            },
            ParameterInfo {
                name: "power",
                kind: ParameterKind::PositionalOrKeyword,
                default: ParameterDefault::Expr(NONE_ARG),
                type_info: || Option::<(usize, PythonExpression)>::type_input(),
            },
            ParameterInfo {
                name: "default_namespace",
                kind: ParameterKind::PositionalOrKeyword,
                default: ParameterDefault::Expr(NONE_ARG),
                type_info: || <Option<&str>>::type_input(),
            },
            ParameterInfo {
                name: "minimal_poly",
                kind: ParameterKind::PositionalOrKeyword,
                default: ParameterDefault::Expr(NONE_ARG),
                type_info: || Option::<PythonPolynomial>::type_input(),
            },
            ParameterInfo {
                name: "vars",
                kind: ParameterKind::PositionalOrKeyword,
                default: ParameterDefault::Expr(NONE_ARG),
                type_info: || Option::<Vec<PythonExpression>>::type_input(),
            },
        ],
        r#return: || PythonFiniteFieldPolynomial::type_output(),
        doc:
        r#"Parse a string to a polynomial, optionally, with the variables and the ordering specified in `vars`.
All non-polynomial elements will be converted to new independent variables.

The coefficients will be converted to finite field elements modulo `modulus`.
If on top a `power` is provided, for example `(2, a)`, the polynomial will be converted to the Galois field
`GF(modulus^2)` where `a` is the variable of the minimal polynomial of the field.

If a `minimal_poly` is provided, the Galois field will be created with `minimal_poly` as the minimal polynomial.

Parameters
----------
poly: str
    The polynomial expression to parse.
modulus: int
    The modulus that defines the finite field.
default_namespace: str | None
    The namespace assumed for unqualified symbols during parsing.
power: tuple[int, Expression] | None
    The extension degree and generator that define the finite field.
minimal_poly: Polynomial | None
    The minimal polynomial that defines the algebraic extension.
vars: Sequence[Expression] | None
    The variables to treat as polynomial variables, in the given order."#,
        module: Some("symbolica.core"),
        is_async: false,
        deprecated: None,
        type_ignored: None,
        is_overload: true,
        file: "symbolica.rs",
        line: line!(),
        column: column!(),
        index: 2,
    }
}