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
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
#![feature(ptr_internals)]
#![allow(non_upper_case_globals)]
#[macro_use]
extern crate bitflags;
extern crate clingo_sys;
extern crate failure;
#[macro_use]
extern crate failure_derive;
extern crate libc;

use std::mem;
use std::ptr::Unique;
use std::marker::PhantomData;
use std::cmp::Ordering;
use std::hash::{Hash, Hasher};
use std::ffi::CStr;
use std::ffi::CString;
use std::ffi::NulError;
use std::str::Utf8Error;
use libc::c_char;
use clingo_sys::*;
pub use failure::Error;

/// Functions and data structures to work with program ASTs.
pub mod ast;

/// Error from the clingo library.
///
/// **Note:** Errors can only be recovered from if explicitly mentioned; most
/// functions do not provide strong exception guarantees.  This means that in
/// case of errors associated objects cannot be used further.
#[derive(Debug, Fail)]
#[fail(display = "ErrorType::{:?}: {}", error_type, msg)]
pub struct ClingoError {
    pub error_type: ErrorType,
    pub msg: &'static str,
}

/// Error in the rust wrapper, like null pointers or failed calls to C functions.
#[derive(Debug, Fail)]
#[fail(display = "Error in the wrapper: {}", msg)]
pub struct WrapperError {
    msg: &'static str,
}

/// Enumeration of clingo error types for [`ClingoError`](struct.ClingoError.html).
#[derive(Debug, Copy, Clone)]
pub enum ErrorType {
    /// Successful API calls
    Success = clingo_error_clingo_error_success as isize,
    /// Errors only detectable at runtime like invalid input
    Runtime = clingo_error_clingo_error_runtime as isize,
    /// Wrong usage of the clingo API
    Logic = clingo_error_clingo_error_logic as isize,
    /// Memory could not be allocated
    BadAlloc = clingo_error_clingo_error_bad_alloc as isize,
    /// Errors unrelated to clingo
    Unknown = clingo_error_clingo_error_unknown as isize,
}
impl From<i32> for ErrorType {
    fn from(error: i32) -> Self {
        match error as u32 {
            clingo_error_clingo_error_success => ErrorType::Success,
            clingo_error_clingo_error_runtime => ErrorType::Runtime,
            clingo_error_clingo_error_logic => ErrorType::Logic,
            clingo_error_clingo_error_bad_alloc => ErrorType::BadAlloc,
            clingo_error_clingo_error_unknown => ErrorType::Unknown,
            x => panic!("Failed to match clingo_error: {}.", x),
        }
    }
}

/// Represents three-valued truth values.
#[derive(Debug, Copy, Clone)]
pub enum TruthValue {
    // No truth value
    Free = clingo_truth_value_clingo_truth_value_free as isize,
    //     True
    True = clingo_truth_value_clingo_truth_value_true as isize,
    //     False
    False = clingo_truth_value_clingo_truth_value_false as isize,
}

/// Enumeration of clause types determining the lifetime of a clause.
///
/// Clauses in the solver are either cleaned up based on a configurable deletion policy or at the end of a solving step.
/// The values of this enumeration determine if a clause is subject to one of the above deletion strategies.
#[derive(Debug, Copy, Clone)]
pub enum ClauseType {
    /// The clause is subject to the solvers deletion policy
    Learnt = clingo_clause_type_clingo_clause_type_learnt as isize,
    /// The clause is not subject to the solvers deletion policy
    Static = clingo_clause_type_clingo_clause_type_static as isize,
    /// Like `Learnt` but the clause is deleted after a solving step
    Volatile = clingo_clause_type_clingo_clause_type_volatile as isize,
    /// Like `Static` but the clause is deleted after a solving step
    VolatileStatic = clingo_clause_type_clingo_clause_type_volatile_static as isize,
}

/// Enumeration of solve events.
#[derive(Debug, Copy, Clone, PartialEq)]
pub enum SolveEventType {
    /// Issued if a model is found.
    Model = clingo_solve_event_type_clingo_solve_event_type_model as isize,
    /// Issued if the search has completed.
    Finish = clingo_solve_event_type_clingo_solve_event_type_finish as isize,
}

/// Enumeration for entries of the statistics.
#[derive(Debug, Copy, Clone)]
pub enum StatisticsType {
    /// The entry is invalid (has neither of the types below)
    Empty = clingo_statistics_type_clingo_statistics_type_empty as isize,
    /// The entry is a (string) value
    Value = clingo_statistics_type_clingo_statistics_type_value as isize,
    /// The entry is an array
    Array = clingo_statistics_type_clingo_statistics_type_array as isize,
    /// The entry is a map
    Map = clingo_statistics_type_clingo_statistics_type_map as isize,
}

/// Enumeration of available symbol types.
#[derive(Debug, Copy, Clone, PartialEq)]
pub enum SymbolType {
    /// The `#inf` symbol
    Infimum = clingo_symbol_type_clingo_symbol_type_infimum as isize,
    /// A numeric symbol, e.g., `1`
    Number = clingo_symbol_type_clingo_symbol_type_number as isize,
    /// A string symbol, e.g., `"a"`
    String = clingo_symbol_type_clingo_symbol_type_string as isize,
    /// A numeric symbol, e.g., `c`, `(1, "a")`, or `f(1,"a")`
    Function = clingo_symbol_type_clingo_symbol_type_function as isize,
    /// The `#sup` symbol
    Supremum = clingo_symbol_type_clingo_symbol_type_supremum as isize,
}

/// Enumeration of warning codes.
#[derive(Debug, Copy, Clone)]
pub enum Warning {
    /// Undefined arithmetic operation or weight of aggregate
    OperationUndefined = clingo_warning_clingo_warning_operation_undefined as isize,
    /// To report multiple errors; a corresponding runtime error is raised later
    RuntimeError = clingo_warning_clingo_warning_runtime_error as isize,
    /// An undefined atom in program
    AtomUndefined = clingo_warning_clingo_warning_atom_undefined as isize,
    /// The Same file included multiple times
    FileIncluded = clingo_warning_clingo_warning_file_included as isize,
    /// CSP variable with unbounded domain
    VariableUnbound = clingo_warning_clingo_warning_variable_unbounded as isize,
    /// A global variable in tuple of aggregate element
    GlobalVariable = clingo_warning_clingo_warning_global_variable as isize,
    /// Other kinds of warnings
    Other = clingo_warning_clingo_warning_other as isize,
}

/// Enumeration of different external statements.
#[derive(Debug, Copy, Clone)]
pub enum ExternalType {
    /// Allow an external to be assigned freely
    Free = clingo_external_type_clingo_external_type_free as isize,
    /// Assign an external to true
    True = clingo_external_type_clingo_external_type_true as isize,
    /// Assign an external to false
    False = clingo_external_type_clingo_external_type_false as isize,
    /// No longer treat an atom as external
    Release = clingo_external_type_clingo_external_type_release as isize,
}

/// Enumeration of different heuristic modifiers.
#[derive(Debug, Copy, Clone)]
pub enum HeuristicType {
    /// Set the level of an atom
    Level = clingo_heuristic_type_clingo_heuristic_type_level as isize,
    /// Configure which sign to chose for an atom
    Sign = clingo_heuristic_type_clingo_heuristic_type_sign as isize,
    /// Modify VSIDS factor of an atom
    Factor = clingo_heuristic_type_clingo_heuristic_type_factor as isize,
    /// Modify the initial VSIDS score of an atom
    Init = clingo_heuristic_type_clingo_heuristic_type_init as isize,
    /// Set the level of an atom and choose a positive sign
    True = clingo_heuristic_type_clingo_heuristic_type_true as isize,
    /// Set the level of an atom and choose a negative sign
    False = clingo_heuristic_type_clingo_heuristic_type_false as isize,
}

/// Enumeration of theory term types.
#[derive(Debug, Copy, Clone)]
pub enum TheoryTermType {
    /// A tuple term, e.g., `(1,2,3)`
    Tuple = clingo_theory_term_type_clingo_theory_term_type_tuple as isize,
    /// A list term, e.g., `[1,2,3]`
    List = clingo_theory_term_type_clingo_theory_term_type_list as isize,
    /// A set term, e.g., `{1,2,3}`
    Set = clingo_theory_term_type_clingo_theory_term_type_set as isize,
    /// A function term, e.g., `f(1,2,3)`
    Function = clingo_theory_term_type_clingo_theory_term_type_function as isize,
    /// A number term, e.g., `42`
    Number = clingo_theory_term_type_clingo_theory_term_type_number as isize,
    /// A symbol term, e.g., `c`
    Symbol = clingo_theory_term_type_clingo_theory_term_type_symbol as isize,
}

/// Enumeration for the different model types.
#[derive(Debug, Copy, Clone)]
pub enum ModelType {
    /// The model represents a stable model.
    StableModel = clingo_model_type_clingo_model_type_stable_model as isize,
    /// The model represents a set of brave consequences.
    BraveConsequences = clingo_model_type_clingo_model_type_brave_consequences as isize,
    /// The model represents a set of cautious consequences.
    CautiousConsequences = clingo_model_type_clingo_model_type_cautious_consequences as isize,
}

/// Supported check modes for propagators.
#[derive(Debug, Copy, Clone)]
pub enum PropagatorCheckMode {
    /// Do not call [`Propagator::check()`](trait.Propagator.html#method.check) at all
    None = clingo_propagator_check_mode_clingo_propagator_check_mode_none as isize,
    /// Call [`Propagator::check()`](trait.Propagator.html#method.check) on total assignment
    Total = clingo_propagator_check_mode_clingo_propagator_check_mode_total as isize,
    /// Call [`Propagator::check()`](trait.Propagator.html#method.check) on propagation fixpoints
    Fixpoint = clingo_propagator_check_mode_clingo_propagator_check_mode_fixpoint as isize,
}

bitflags! {
    /// Bitset describing the entries of the configuration.
    pub struct ConfigurationType: u32 {
        const VALUE =
            clingo_configuration_type_clingo_configuration_type_value;
        const ARRAY =
            clingo_configuration_type_clingo_configuration_type_array;
        const MAP =
            clingo_configuration_type_clingo_configuration_type_map;
    }
}
bitflags! {
    /// Bitset describing solve modes.
    pub struct SolveMode: u32 {
        const ASYNC = clingo_solve_mode_clingo_solve_mode_async;
        const YIELD = clingo_solve_mode_clingo_solve_mode_yield;
    }
}
bitflags! {
    /// Bitset describing symbols in models.
    pub struct ShowType: u32 {
        const CSP  = clingo_show_type_clingo_show_type_csp;
        const SHOWN = clingo_show_type_clingo_show_type_shown;
        const ATOMS = clingo_show_type_clingo_show_type_atoms;
        const TERMS = clingo_show_type_clingo_show_type_terms;
        const EXTRA = clingo_show_type_clingo_show_type_extra;
        const ALL = clingo_show_type_clingo_show_type_all;
        const COMPLEMENT = clingo_show_type_clingo_show_type_complement;
    }
}
bitflags! {
    /// Bitset that describes the result of a solve call.
    pub struct SolveResult: u32 {
        /// The problem is satisfiable.
        const SATISFIABLE = clingo_solve_result_clingo_solve_result_satisfiable;
        /// The problem is unsatisfiable.
        const UNSATISFIABLE =
            clingo_solve_result_clingo_solve_result_unsatisfiable;
        /// The search space was exhausted.
        const EXHAUSTED = clingo_solve_result_clingo_solve_result_exhausted;
        /// The search was interupted.
        const INTERRUPTED = clingo_solve_result_clingo_solve_result_interrupted;
    }
}
type SolveEventCallback = unsafe extern "C" fn(
    type_: clingo_solve_event_type_t,
    event: *mut ::std::os::raw::c_void,
    data: *mut ::std::os::raw::c_void,
    goon: *mut bool,
) -> bool;
pub trait SolveEventHandler {
    /// Callback function called during search to notify when the search is finished or a model is ready.
    ///
    /// If a (non-recoverable) clingo API function fails in this callback, it must return false.
    /// In case of errors not related to clingo, set error code [`ErrorType::Unknown`](enum.ErrorType.html#variant.Unknown) and return false to stop solving with an error.
    ///
    /// **Attention:** If the search is finished, the model is NULL.
    ///
    /// # Arguments
    ///
    /// * `etype` - the type of the solve event
    /// * `goon` - can be set to false to stop solving
    ///
    /// **Returns** whether the call was successful
    ///
    /// **See:** [`Control::solve()`](struct.Control.html#method.solve)
    fn on_solve_event(&mut self, etype: SolveEventType, goon: &mut bool) -> bool;
    #[doc(hidden)]
    unsafe extern "C" fn unsafe_solve_callback<T: SolveEventHandler>(
        etype: clingo_solve_event_type_t,
        event: *mut ::std::os::raw::c_void,
        data: *mut ::std::os::raw::c_void,
        goon: *mut bool,
    ) -> bool {
        // assert!(!event.is_null());
        let etype = match etype {
            clingo_solve_event_type_clingo_solve_event_type_model => SolveEventType::Model,
            clingo_solve_event_type_clingo_solve_event_type_finish => SolveEventType::Finish,
            x => panic!("Failed to match clingo_solve_event_type: {}.", x),
        };

        let msg = match (data as *mut T).as_mut() {
            Some(event_handler) => {
                if let Some(goon) = goon.as_mut() {
                    return event_handler.on_solve_event(etype, goon);
                } else {
                    "unsafe_solve_callback tried casting a null pointer to &bool."
                }
            }
            None => "unsafe_solve_callback tried casting a null pointer to &SolveEventHandler.",
        };
        set_internal_error(ErrorType::Runtime, msg);
        false
    }
}

type AstCallback =
    unsafe extern "C" fn(arg1: *const clingo_ast_statement_t, arg2: *mut ::std::os::raw::c_void)
        -> bool;
pub trait AstStatementHandler {
    /// Callback function called on an ast statement while traversing the ast.
    ///
    /// **Returns** whether the call was successful
    fn on_statement<T>(&mut self, arg1: &AstStatement<T>) -> bool;
    #[doc(hidden)]
    unsafe extern "C" fn unsafe_ast_callback<T: AstStatementHandler>(
        stm: *const clingo_ast_statement_t,
        data: *mut ::std::os::raw::c_void,
    ) -> bool {
        if let Some(stm) = (stm as *const AstStatement<T>).as_ref() {
            if let Some(data) = (data as *mut T).as_mut() {
                return data.on_statement(stm);
            } else {
                set_internal_error(
                    ErrorType::Runtime,
                    "unsafe_ast_callback tried casting a null pointer to &mut AstStatementHandler.",
                );
            }
        } else {
            set_internal_error(
                ErrorType::Runtime,
                "unsafe_ast_callback tried casting a null pointer to &AstStatement.",
            );
        }
        false
    }
}

type LoggingCallback = unsafe extern "C" fn(
    code: clingo_warning_t,
    message: *const ::std::os::raw::c_char,
    data: *mut ::std::os::raw::c_void,
);
pub trait Logger {
    /// Callback to intercept warning messages.
    ///
    /// # Arguments
    ///
    /// * `code` - associated warning code
    /// * `message` - warning message
    ///
    /// **See:**
    ///
    /// * [`Control::new_with_logger()`](struct.Control.html#method.new_with_logger)
    /// * [`parse_term_with_logger()`](fn.parse_term_with_logger.html)
    /// * [`parse_program_with_logger()`](fn.parse_program_with_logger.html)
    fn log(&mut self, code: Warning, message: &str);
    #[doc(hidden)]
    unsafe extern "C" fn unsafe_logging_callback<L: Logger>(
        code: clingo_warning_t,
        message: *const ::std::os::raw::c_char,
        data: *mut ::std::os::raw::c_void,
    ) {
        let code = match code as u32 {
            clingo_warning_clingo_warning_atom_undefined => Warning::AtomUndefined,
            clingo_warning_clingo_warning_file_included => Warning::FileIncluded,
            clingo_warning_clingo_warning_global_variable => Warning::GlobalVariable,
            clingo_warning_clingo_warning_operation_undefined => Warning::OperationUndefined,
            clingo_warning_clingo_warning_other => Warning::Other,
            clingo_warning_clingo_warning_runtime_error => Warning::RuntimeError,
            clingo_warning_clingo_warning_variable_unbounded => Warning::VariableUnbound,
            x => panic!("Failed to match clingo_warning: {}.", x),
        };

        assert!(!message.is_null());
        let c_str = CStr::from_ptr(message);
        match c_str.to_str() {
            Ok(message) => {
                if let Some(logger) = (data as *mut L).as_mut() {
                    logger.log(code, message);
                } else {
                    set_internal_error(
                        ErrorType::Runtime,
                        "unsafe_logging_callback tried casting a null pointer to &mut Logger.",
                    );
                }
            }
            Err(e) => {
                set_internal_error(
                    ErrorType::Runtime,
                    "unsafe_logging_callback message with invalid UTF-8 data.",
                );
            }
        }
    }
}

type GroundCallback = unsafe extern "C" fn(
    location: *const clingo_location_t,
    name: *const ::std::os::raw::c_char,
    arguments: *const clingo_symbol_t,
    arguments_size: usize,
    data: *mut ::std::os::raw::c_void,
    symbol_callback: clingo_symbol_callback_t,
    symbol_callback_data: *mut ::std::os::raw::c_void,
) -> bool;
pub trait ExternalFunctionHandler {
    /// Callback function to implement external functions.
    ///
    /// If an external function of form `@name(parameters)` occurs in a logic program,
    /// then this function is called with its location, name, parameters, and a callback to inject symbols as arguments.
    /// The callback can be called multiple times; all symbols passed are injected.
    ///
    /// If a (non-recoverable) clingo API function fails in this callback, for example, the symbol callback, the callback must return false.
    /// In case of errors not related to clingo, this function can set error [`ErrorType::Unknown`](enum.ErrorType.html#variant.Unknown) and return false to stop grounding with an error.
    ///
    /// # Arguments
    ///
    /// * `location` - location from which the external function was called
    /// * `name` - name of the called external function
    /// * `arguments` - arguments of the called external function
    ///
    /// **Returns** a vector of symbols
    ///
    /// **See:** [`Control::ground_with_event_handler()`](struct.Control.html#method.ground_with_event_handler)
    ///
    /// The following example implements the external function `@f()` returning 42.
    /// ```
    /// fn on_external_function(
    ///     &mut self,
    ///     _location: &Location,
    ///     name: &str,
    ///     arguments: &[Symbol],
    /// ) -> Result<Vec<Symbol>,ClingoError> {
    ///     if name == "f" && arguments.len() == 0 {
    ///         let symbol = Symbol::create_number(42);
    ///         Ok(vec![symbol])
    ///     } else {
    ///        Err(ClingoError {
    ///          type_: ErrorType::Runtime,
    ///          msg: "function not found",
    ///        })
    ///    }
    /// }
    /// ```
    fn on_external_function(
        &mut self,
        location: &Location,
        name: &str,
        arguments: &[Symbol],
    ) -> Result<Vec<Symbol>, ClingoError>;
    #[doc(hidden)]
    unsafe extern "C" fn unsafe_ground_callback<T: ExternalFunctionHandler>(
        location: *const clingo_location_t,
        name: *const ::std::os::raw::c_char,
        arguments: *const clingo_symbol_t,
        arguments_size: usize,
        data: *mut ::std::os::raw::c_void,
        symbol_callback: clingo_symbol_callback_t,
        symbol_callback_data: *mut ::std::os::raw::c_void,
    ) -> bool {
        assert!(!name.is_null());
        let c_str = CStr::from_ptr(name);
        match c_str.to_str() {
            Ok(name) => {
                if let Some(location) = (location as *const Location).as_ref() {
                    if arguments_size > 0 {
                        assert!(!arguments.is_null());
                    }
                    let arguments =
                        std::slice::from_raw_parts(arguments as *const Symbol, arguments_size);

                    if let Some(event_handler) = (data as *mut T).as_mut() {
                        match event_handler.on_external_function(location, name, arguments) {
                            Ok(symbols) => {
                                if let Some(symbol_injector) = symbol_callback {
                                    let mut v: Vec<
                                        clingo_symbol_t,
                                    > = symbols.iter().map(|symbol| symbol.clone().0).collect();
                                    return symbol_injector(
                                        v.as_slice().as_ptr(),
                                        v.len(),
                                        symbol_callback_data,
                                    );
                                } else {
                                    return true;
                                }
                            }
                            Err(e) => {
                                set_internal_error(e.error_type, e.msg);
                            }
                        }
                    } else {
                        set_internal_error(
                ErrorType::Runtime,"unsafe_ground_callback tried casting a null pointer to &mut ExternalFunctionHandler."
            );
                    }
                } else {
                    set_internal_error(
                        ErrorType::Runtime,
                        "unsafe_ground_callback tried casting a null pointer to &Location.",
                    );
                }
            }
            Err(e) => {
                println!("{:?}", e);
            }
        }
        false
    }
}

/// Represents a symbolic literal.
#[derive(Debug, Copy, Clone)]
pub struct SymbolicLiteral(clingo_symbolic_literal_t);
impl SymbolicLiteral {
    /// Get the associated symbol (must be a function)
    pub fn symbol(&self) -> Symbol {
        Symbol(self.0.symbol)
    }
    /// Whether the literal has a sign
    pub fn positive(&self) -> bool {
        self.0.positive
    }
}

/// Signed integer type used for aspif and solver literals.
#[derive(Debug, Copy, Clone, PartialEq)]
pub struct Literal(clingo_literal_t);
impl Literal {
    pub fn negate(&self) -> Literal {
        Literal(-(self.0))
    }
    pub fn from(Atom(atom): Atom) -> Literal {
        Literal(atom as clingo_literal_t)
    }
    pub fn get_integer(&self) -> i32 {
        self.0
    }
}

/// Unsigned integer type used for aspif atoms.
#[derive(Debug, Copy, Clone)]
pub struct Atom(clingo_atom_t);

/// Unsigned integer type used in various places.
#[derive(Debug, Copy, Clone)]
pub struct Id(clingo_id_t);
impl Id {
    pub fn get_integer(&self) -> u32 {
        self.0
    }
}

/// A Literal with an associated weight.
#[derive(Debug, Copy, Clone)]
pub struct WeightedLiteral(clingo_weighted_literal);
impl WeightedLiteral {
    pub fn literal(&self) -> Literal {
        Literal(self.0.literal)
    }
    pub fn weight(&self) -> i32 {
        self.0.weight
    }
}

/// Represents a source code location marking its beginnig and end.
///
/// **Note:** Not all locations refer to physical files.
/// By convention, such locations use a name put in angular brackets as filename.
#[derive(Debug, Copy, Clone)]
pub struct Location(clingo_location);
impl Location {
    /// Create a new location.
    ///
    /// # Arguments
    ///
    /// - `begin_file` - the file where the location begins
    /// - `end_file` -  the file where the location ends
    /// - `begin_line` -  the line where the location begins
    /// - `end_line` -  the line where the location ends
    /// - `begin_column` -  the column where the location begins
    /// - `end_column` -  the column where the location ends
    ///
    /// # Errors
    ///
    /// - [`NulError`](https://doc.rust-lang.org/std/ffi/struct.NulError.html) - if `begin_file` `end_file` or contain a nul byte
    pub fn new(
        begin_file: &str,
        end_file: &str,
        begin_line: usize,
        end_line: usize,
        begin_column: usize,
        end_column: usize,
    ) -> Result<Location, NulError> {
        let begin_file = CString::new(begin_file)?;
        let end_file = CString::new(end_file)?;
        let loc = clingo_location {
            begin_line: begin_line,
            end_line: end_line,
            begin_column: begin_column,
            end_column: end_column,
            begin_file: begin_file.as_ptr(),
            end_file: end_file.as_ptr(),
        };
        Ok(Location(loc))
    }
    /// the file where the location begins
    pub fn begin_file(&self) -> Result<&str, Utf8Error> {
        if self.0.begin_file.is_null() {
            Ok("")
        } else {
            let c_str = unsafe { CStr::from_ptr(self.0.begin_file) };
            c_str.to_str()
        }
    }
    /// the file where the location ends
    pub fn end_file(&self) -> Result<&str, Utf8Error> {
        if self.0.end_file.is_null() {
            Ok("")
        } else {
            let c_str = unsafe { CStr::from_ptr(self.0.end_file) };
            c_str.to_str()
        }
    }
    /// the line where the location begins
    pub fn begin_line(&self) -> usize {
        self.0.begin_line
    }
    /// the line where the location ends
    pub fn end_line(&self) -> usize {
        self.0.end_line
    }
    /// the column where the location begins
    pub fn begin_column(&self) -> usize {
        self.0.begin_column
    }
    /// the column where the location ends
    pub fn end_column(&self) -> usize {
        self.0.end_column
    }
}

/// Represents a predicate signature.
///
/// Signatures have a name and an arity, and can be positive or negative (to
/// represent classical negation).
#[derive(Debug, Copy, Clone)]
pub struct Signature(clingo_signature_t);
impl PartialEq for Signature {
    /// Check if two signatures are equal.
    fn eq(&self, other: &Signature) -> bool {
        unsafe { clingo_signature_is_equal_to(self.0, other.0) }
    }
}
impl Eq for Signature {}
impl PartialOrd for Signature {
    /// Compare two signatures.
    ///
    /// Signatures are compared first by sign (unsigned < signed), then by arity,
    /// then by name.
    fn partial_cmp(&self, other: &Signature) -> Option<Ordering> {
        if unsafe { clingo_signature_is_less_than(self.0, other.0) } {
            Some(Ordering::Less)
        } else if unsafe { clingo_signature_is_less_than(other.0, self.0) } {
            Some(Ordering::Greater)
        } else {
            Some(Ordering::Equal)
        }
    }
}
impl Hash for Signature {
    /// Calculate a hash code of a signature.
    fn hash<H: Hasher>(&self, state: &mut H) {
        unsafe { clingo_signature_hash(self.0) }.hash(state);
    }
}
impl Signature {
    /// Create a new signature.
    ///
    /// # Arguments
    ///
    /// * `name` name of the signature
    /// * `arity` arity of the signature
    /// * `positive` false if the signature has a classical negation sign
    ///
    /// # Errors
    ///
    /// - [`ErrorType::BadAlloc`](enum.ErrorType.html#variant.BadAlloc)
    /// - [`NulError`](https://doc.rust-lang.org/std/ffi/struct.NulError.html) - if `name` contains a nul byte
    pub fn new(name: &str, arity: u32, positive: bool) -> Result<Signature, Error> {
        let name = CString::new(name)?;
        let mut signature = 0;
        if unsafe { clingo_signature_create(name.as_ptr(), arity, positive, &mut signature) } {
            Ok(Signature(signature))
        } else {
            Err(error())?
        }
    }

    /// Create a statement for the signature.
    pub fn ast_statement(&self, Location(loc): Location) -> AstStatement<Signature> {
        let _bg_union_2 = clingo_ast_statement__bindgen_ty_1 {
            project_signature: self.0 as clingo_signature_t,
        };
        let stm = clingo_ast_statement_t {
            location: loc,
            type_: ast::StatementType::ProjectAtomSignature as clingo_ast_statement_type_t,
            __bindgen_anon_1: _bg_union_2,
        };
        AstStatement {
            data: stm,
            phantom: PhantomData,
        }
    }

    /// Get the name of a signature.
    ///
    /// # Errors
    ///
    /// - [`Utf8Error`](https://doc.rust-lang.org/std/str/struct.Utf8Error.html)
    pub fn name(&self) -> Result<&str, Utf8Error> {
        let char_ptr: *const c_char = unsafe { clingo_signature_name(self.0) };
        if char_ptr.is_null() {
            Ok("")
        } else {
            let c_str = unsafe { CStr::from_ptr(char_ptr) };
            c_str.to_str()
        }
    }

    /// Get the arity of a signature.
    pub fn arity(&self) -> u32 {
        unsafe { clingo_signature_arity(self.0) }
    }

    /// Whether the signature is positive (is not classically negated).
    pub fn is_positive(&self) -> bool {
        unsafe { clingo_signature_is_positive(self.0) }
    }

    /// Whether the signature is negative (is classically negated).
    pub fn is_negative(&self) -> bool {
        unsafe { clingo_signature_is_negative(self.0) }
    }
}

/// Represents a symbol.
///
/// This includes numbers, strings, functions (including constants when
/// arguments are empty and tuples when the name is empty), \#inf and \#sup.
#[derive(Debug, Copy, Clone)]
pub struct Symbol(clingo_symbol_t);
impl PartialEq for Symbol {
    fn eq(&self, other: &Symbol) -> bool {
        unsafe { clingo_symbol_is_equal_to(self.0, other.0) }
    }
}
impl Eq for Symbol {}
impl PartialOrd for Symbol {
    /// Compare two symbols.
    ///
    /// Symbols are first compared by type.  If the types are equal, the values are
    /// compared (where strings are compared using strcmp).  Functions are first
    /// compared by signature and then lexicographically by arguments.
    fn partial_cmp(&self, other: &Symbol) -> Option<Ordering> {
        if unsafe { clingo_symbol_is_less_than(self.0, other.0) } {
            Some(Ordering::Less)
        } else if unsafe { clingo_symbol_is_less_than(other.0, self.0) } {
            Some(Ordering::Greater)
        } else {
            Some(Ordering::Equal)
        }
    }
}
impl Hash for Symbol {
    /// Calculate a hash code of a symbol.
    fn hash<H: Hasher>(&self, state: &mut H) {
        unsafe { clingo_symbol_hash(self.0) }.hash(state);
    }
}
impl Symbol {
    /// Construct a symbol representing a number.
    pub fn create_number(number: i32) -> Symbol {
        let mut symbol = 0 as clingo_symbol_t;
        unsafe { clingo_symbol_create_number(number, &mut symbol) };
        Symbol(symbol)
    }

    /// Construct a symbol representing \#sup.
    pub fn create_supremum() -> Symbol {
        let mut symbol = 0 as clingo_symbol_t;
        unsafe { clingo_symbol_create_supremum(&mut symbol) };
        Symbol(symbol)
    }

    /// Construct a symbol representing \#inf
    pub fn create_infimum() -> Symbol {
        let mut symbol = 0 as clingo_symbol_t;
        unsafe { clingo_symbol_create_infimum(&mut symbol) };
        Symbol(symbol)
    }

    /// Construct a symbol representing a string.
    ///
    /// # Arguments
    ///
    /// * `string` - the string
    ///
    /// #  Errors:
    ///
    /// - [`NulError`](https://doc.rust-lang.org/std/ffi/struct.NulError.html) - if `string` contains a nul byte
    /// - [`ErrorType::BadAlloc`](enum.ErrorType.html#variant.BadAlloc)
    pub fn create_string(string: &str) -> Result<Symbol, Error> {
        let mut symbol = 0 as clingo_symbol_t;
        let c_str = CString::new(string)?;
        if unsafe { clingo_symbol_create_string(c_str.as_ptr(), &mut symbol) } {
            Ok(Symbol(symbol))
        } else {
            Err(error())?
        }
    }

    /// Construct a symbol representing an id.
    ///
    /// **Note:** This is just a shortcut for [`create_function()`](struct.Symbol.html#method.create_function) with
    /// empty arguments.
    ///
    /// # Arguments
    ///
    /// * `name` - the name of the symbol
    /// * `positive` - whether the symbol has a classical negation sign
    ///
    /// # Errors
    ///
    /// - [`NulError`](https://doc.rust-lang.org/std/ffi/struct.NulError.html) - if `name` contains a nul byte
    /// - [`ErrorType::BadAlloc`](enum.ErrorType.html#variant.BadAlloc)
    pub fn create_id(name: &str, positive: bool) -> Result<Symbol, Error> {
        let mut symbol = 0 as clingo_symbol_t;
        let name = CString::new(name)?;
        if unsafe { clingo_symbol_create_id(name.as_ptr(), positive, &mut symbol) } {
            Ok(Symbol(symbol))
        } else {
            Err(error())?
        }
    }

    /// Construct a symbol representing a function or tuple.
    ///
    ///
    /// **Note:** To create tuples, the empty string has to be used as name.
    ///
    /// # Arguments
    ///
    /// * `name` - the name of the function
    /// * `arguments` - the arguments of the function
    /// * `positive` - whether the symbol has a classical negation sign
    ///
    /// # Errors
    ///
    /// - [`NulError`](https://doc.rust-lang.org/std/ffi/struct.NulError.html) - if `name` contains a nul byte
    /// - [`ErrorType::BadAlloc`](enum.ErrorType.html#variant.BadAlloc)
    pub fn create_function(
        name: &str,
        arguments: &[Symbol],
        positive: bool,
    ) -> Result<Symbol, Error> {
        let mut symbol = 0 as clingo_symbol_t;
        let name = CString::new(name)?;
        if unsafe {
            clingo_symbol_create_function(
                name.as_ptr(),
                arguments.as_ptr() as *const clingo_symbol_t,
                arguments.len(),
                positive,
                &mut symbol,
            )
        } {
            Ok(Symbol(symbol))
        } else {
            Err(error())?
        }
    }

    /// Get the number of a symbol.
    ///
    /// # Errors
    ///
    /// - [`ErrorType::Runtime`](enum.ErrorType.html#variant.Runtime) if symbol is not of type [`SymbolType::Number`](enum.SymbolType.html#variant.Number)
    pub fn number(&self) -> Result<i32, ClingoError> {
        let mut number = 0;
        if unsafe { clingo_symbol_number(self.0, &mut number) } {
            Ok(number)
        } else {
            Err(error())
        }
    }

    /// Get the name of a symbol.
    ///
    /// # Errors
    ///
    /// - [`ErrorType::Runtime`](enum.ErrorType.html#variant.Runtime) if symbol is not of type [`SymbolType::Function`](enum.SymbolType.html#variant.Function)
    /// - [`Utf8Error`](https://doc.rust-lang.org/std/str/struct.Utf8Error.html)
    pub fn name(&self) -> Result<&str, Error> {
        let mut char_ptr = std::ptr::null() as *const c_char;
        if unsafe { clingo_symbol_name(self.0, &mut char_ptr) } {
            let c_str = unsafe { CStr::from_ptr(char_ptr) };
            Ok(c_str.to_str()?)
        } else {
            Err(error())?
        }
    }

    /// Get the string of a symbol.
    ///
    /// # Errors
    ///
    /// - [`ErrorType::Runtime`](enum.ErrorType.html#variant.Runtime) if symbol is not of type [`SymbolType::String`](enum.SymbolType.html#variant.String)
    /// - [`Utf8Error`](https://doc.rust-lang.org/std/str/struct.Utf8Error.html)
    pub fn string(&self) -> Result<&str, Error> {
        let mut char_ptr = std::ptr::null() as *const c_char;
        if unsafe { clingo_symbol_string(self.0, &mut char_ptr) } {
            let c_str = unsafe { CStr::from_ptr(char_ptr) };
            Ok(c_str.to_str()?)
        } else {
            Err(error())?
        }
    }

    /// Check if a function is positive (does not have a sign).
    ///
    /// # Errors
    ///
    /// - [`ErrorType::Runtime`](enum.ErrorType.html#variant.Runtime) if symbol is not of type [`SymbolType::Function`](enum.SymbolType.html#variant.Function)
    pub fn is_positive(&self) -> Result<bool, ClingoError> {
        let mut positive = false;
        if unsafe { clingo_symbol_is_positive(self.0, &mut positive) } {
            Ok(positive)
        } else {
            Err(error())
        }
    }

    /// Check if a function is negative (has a sign).
    ///
    /// # Errors
    ///
    /// - [`ErrorType::Runtime`](enum.ErrorType.html#variant.Runtime) if symbol is not of type [`SymbolType::Function`](enum.SymbolType.html#variant.Function)
    pub fn is_negative(&self) -> Result<bool, ClingoError> {
        let mut negative = false;
        if unsafe { clingo_symbol_is_negative(self.0, &mut negative) } {
            Ok(negative)
        } else {
            Err(error())
        }
    }

    /// Get the arguments of a symbol.
    ///
    /// # Errors
    ///
    /// - [`ErrorType::Runtime`](enum.ErrorType.html#variant.Runtime) if symbol is not of type [`SymbolType::Function`](enum.SymbolType.html#variant.Function)
    pub fn arguments(&self) -> Result<Vec<Symbol>, ClingoError> {
        let mut symbol_ptr = std::ptr::null() as *const clingo_symbol_t;
        let mut size: usize = 0;
        if unsafe { clingo_symbol_arguments(self.0, &mut symbol_ptr, &mut size) } {
            let mut symbols = Vec::<Symbol>::with_capacity(size);
            for _ in 0..size {
                let nsymbol = unsafe { *symbol_ptr };
                symbols.push(Symbol(nsymbol));
                symbol_ptr = unsafe { symbol_ptr.offset(1) };
            }
            Ok(symbols)
        } else {
            Err(error())
        }
    }

    /// Get the type of a symbol.
    ///
    /// # Errors
    ///
    /// - may failed to match clingo symbol type
    pub fn symbol_type(&self) -> SymbolType {
        let stype = unsafe { clingo_symbol_type(self.0) };
        match stype as u32 {
            clingo_symbol_type_clingo_symbol_type_infimum => SymbolType::Infimum,
            clingo_symbol_type_clingo_symbol_type_number => SymbolType::Number,
            clingo_symbol_type_clingo_symbol_type_string => SymbolType::String,
            clingo_symbol_type_clingo_symbol_type_function => SymbolType::Function,
            clingo_symbol_type_clingo_symbol_type_supremum => SymbolType::Supremum,
            x => panic!("Failed to match clingo_symbol_type: {}.", x),
        }
    }

    /// Get the string representation of a symbol.
    ///
    /// # Errors
    ///
    /// - [`ErrorType::BadAlloc`](enum.ErrorType.html#variant.BadAlloc)
    /// - [`Utf8Error`](https://doc.rust-lang.org/std/str/struct.Utf8Error.html)
    pub fn to_string(&self) -> Result<String, Error> {
        let mut size: usize = 0;
        if unsafe { clingo_symbol_to_string_size(self.0, &mut size) } {
            let a1 = vec![1; size];
            let cstring = unsafe { CString::from_vec_unchecked(a1) };
            if unsafe { clingo_symbol_to_string(self.0, cstring.as_ptr() as *mut c_char, size) } {
                Ok(cstring.into_string()?)
            } else {
                Err(error())?
            }
        } else {
            Err(error())?
        }
    }
}

// impl Logger for u32 {
//     fn log(&mut self, code: Warning, message: &str) {
//         print!("log {}: {}", self, message);
//         println!("warn: {:?}", code);
//         *self += 1;
//     }
// }

/// Parse the given program and return an abstract syntax tree for each statement via a callback.
///
/// # Arguments
///
/// * `program` - the program in gringo syntax
/// * `handler` - implementing the trait [`AstStatementHandler`](trait.AstStatementHandler.html)
///
/// # Errors
///
/// - [`NulError`](https://doc.rust-lang.org/std/ffi/struct.NulError.html) - if `program` contains a nul byte
/// - [`ErrorType::Runtime`](enum.ErrorType.html#variant.Runtime) if parsing fails
/// - [`ErrorType::BadAlloc`](enum.ErrorType.html#variant.BadAlloc)
pub fn parse_program<T: AstStatementHandler>(program: &str, handler: &mut T) -> Result<(), Error> {
    let logger = None;
    let logger_data = std::ptr::null_mut();
    let program = CString::new(program)?;
    let data = handler as *mut T;
    if unsafe {
        clingo_parse_program(
            program.as_ptr(),
            Some(T::unsafe_ast_callback::<T> as AstCallback),
            data as *mut ::std::os::raw::c_void,
            logger,
            logger_data,
            0,
        )
    } {
        Ok(())
    } else {
        Err(error())?
    }
}

/// Parse the given program and return an abstract syntax tree for each statement via a callback.
///
/// # Arguments
///
/// * `program` - the program in gringo syntax
/// * `handler` - implementating the trait [`AstStatementHandler`](trait.AstStatementHandler.html)
/// * `logger` - implementing the trait [`Logger`](trait.Logger.html) to report messages during parsing
/// * `message_limit` - the maximum number of times the logger is called
///
/// # Errors
///
/// - [`NulError`](https://doc.rust-lang.org/std/ffi/struct.NulError.html) - if `program` contains a nul byte
/// - [`ErrorType::Runtime`](enum.ErrorType.html#variant.Runtime) if parsing fails
/// - [`ErrorType::BadAlloc`](enum.ErrorType.html#variant.BadAlloc)
pub fn parse_program_with_logger<T: AstStatementHandler, L: Logger>(
    program: &str,
    handler: &mut T,
    logger: &mut L,
    message_limit: u32,
) -> Result<(), Error> {
    let handler_data = handler as *mut T;
    let logger_data = logger as *mut L;
    let program = CString::new(program)?;
    if unsafe {
        clingo_parse_program(
            program.as_ptr(),
            Some(T::unsafe_ast_callback::<T> as AstCallback),
            handler_data as *mut ::std::os::raw::c_void,
            Some(L::unsafe_logging_callback::<L> as LoggingCallback),
            logger_data as *mut ::std::os::raw::c_void,
            message_limit,
        )
    } {
        Ok(())
    } else {
        Err(error())?
    }
}

/// Obtain the clingo version.
///
/// `(major version, minor version, revision number)`
pub fn version() -> (i32, i32, i32) {
    let mut major = 0;
    let mut minor = 0;
    let mut revision = 0;
    unsafe { clingo_version(&mut major, &mut minor, &mut revision) };

    (major, minor, revision)
}

/// Struct used to specify the program parts that have to be grounded.
///
/// Programs may be structured into parts, which can be grounded independently with [`Control::ground()`](struct.Control.html#method.ground).
/// Program parts are mainly interesting for incremental grounding and multi-shot solving.
/// For single-shot solving, program parts are not needed.
///
/// **Note:** Parts of a logic program without an explicit `#program`
/// specification are by default put into a program called `base` - without
/// arguments.
///
/// **See:** [`Control::ground()`](struct.Control.html#method.ground)
pub struct Part<'a> {
    name: CString,
    params: &'a [Symbol],
}
impl<'a> Part<'a> {
    /// Create a new program part object.
    ///
    /// # Arguments
    ///
    /// * `name` - the identifier of the program
    /// * `params` - the parameter of the program
    ///
    /// # Errors
    ///
    /// - [`NulError`](https://doc.rust-lang.org/std/ffi/struct.NulError.html) - if `name` contains a nul byte
    /// - [`ErrorType::BadAlloc`](enum.ErrorType.html#variant.BadAlloc)
    /// - [`ErrorType::Runtime`](enum.ErrorType.html#variant.Runtime) if argument parsing fails
    /// - [`WrapperError`](struct.WrapperError.html)
    pub fn new(name: &str, params: &'a [Symbol]) -> Result<Part<'a>, Error> {
        Ok(Part {
            name: CString::new(name)?,
            params: params,
        })
    }

    fn from(&self) -> clingo_part {
        clingo_part {
            name: self.name.as_ptr(),
            params: self.params.as_ptr() as *const clingo_symbol_t,
            size: self.params.len(),
        }
    }
}
/// Get the last error code set by a clingo API call.
///
/// **Note:** Each thread has its own local error code.
fn error() -> ClingoError {
    ClingoError {
        error_type: ErrorType::from(unsafe { clingo_error_code() }),
        msg: error_message(),
    }
}

/// Get the last error message set if an API call fails.
///
/// **Note:** Each thread has its own local error message.
fn error_message() -> &'static str {
    let char_ptr: *const c_char = unsafe { clingo_error_message() };
    if char_ptr.is_null() {
        "Ooops, original error message is null."
    } else {
        let c_str = unsafe { CStr::from_ptr(char_ptr) };
        c_str
            .to_str()
            .unwrap_or("Ooops, original error message was no valid utf8 string.")
    }
}

/// Set an error code and message in the active thread.
///
/// # Errors
///
/// - [`NulError`](https://doc.rust-lang.org/std/ffi/struct.NulError.html) - if `name` contains a nul byte
pub fn set_error(code: ErrorType, message: &str) -> Result<(), NulError> {
    let message = CString::new(message)?;
    unsafe { clingo_set_error(code as clingo_error_t, message.as_ptr()) }
    Ok(())
}

fn set_internal_error(code: ErrorType, message: &'static str) {
    // unwrap won't panic, because the function only used internally on valid UTF-8 strings
    let message = CString::new(message).unwrap();
    unsafe { clingo_set_error(code as clingo_error_t, message.as_ptr()) }
}

/// An instance of this trait has to be registered with a solver to implement a custom propagator.
///
/// For all functions exist default implementations and they must not be implemented manually.
pub trait Propagator {
    /// This function is called once before each solving step.
    /// It is used to map relevant program literals to solver literals, add watches for solver
    /// literals, and initialize the data structures used during propagation.
    ///
    /// **Note:** This is the last point to access symbolic and theory atoms.
    /// Once the search has started, they are no longer accessible.
    ///
    /// # Arguments
    ///
    /// * `init` - initizialization object
    ///
    /// **Returns** whether the call was successful
    fn init(&mut self, _init: &mut PropagateInit) -> bool {
        true
    }
    #[doc(hidden)]
    unsafe extern "C" fn unsafe_init<T: Propagator>(
        init: *mut clingo_propagate_init_t,
        data: *mut ::std::os::raw::c_void,
    ) -> bool {
        assert!(!init.is_null());
        if let Some(init) = (init as *mut PropagateInit).as_mut() {
            assert!(!data.is_null());
            if let Some(propagator) = (data as *mut T).as_mut() {
                return propagator.init(init);
            } else {
                set_internal_error(
                    ErrorType::Runtime,
                    "unsafe_init tried casting a null pointer to &mut Propagator.",
                );
            }
        } else {
            set_internal_error(
                ErrorType::Runtime,
                "unsafe_init tried casting a null pointer to &mut PropagateInit.",
            );
        }
        false
    }
    /// Can be used to propagate solver literals given a
    /// [partial assignment](struct.Assignment.html).
    ///
    /// Called during propagation with a non-empty array of
    /// [watched solver literals](struct.PropagateInit.html#method.add_watch)
    /// that have been assigned to true since the last call to either propagate, undo, (or the start
    /// of the search) - the change set.
    /// Only watched solver literals are contained in the change set.
    /// Each literal in the change set is true w.r.t. the current
    /// [assignment](struct.Assignment.html).
    /// [`PropagateControl::add_clause()`](struct.PropagateControl.html#method.add_clause) can be
    /// used to add clauses.
    /// If a clause is unit resulting, it can be propagated using
    /// [`PropagateControl::propagate()`](struct.PropagateControl.html#method.propagate).
    /// If the result of either of the two methods is false, the propagate function must return
    /// immediately.
    ///
    /// The following snippet shows how to use the methods to add clauses and propagate consequences
    /// within the callback.
    /// The important point is to return true (true to indicate there was no error) if the result of
    /// either of the methods is false.
    /// ```
    /// let clause: &[ ... ];
    /// // add a clause
    /// if let Ok(x) = control.add_clause(clause, ClauseType::Learnt) {
    ///     if !x {
    ///         true
    ///     }
    /// } else {
    ///     false
    /// }
    /// // propagate its consequences
    /// if let Ok(x) = control.propagate() {
    ///     if !x {
    ///         true
    ///     }
    /// } else {
    ///     false
    /// }
    /// // add further clauses and propagate them
    /// ...
    /// true
    /// ```
    ///
    /// **Note:**
    /// This function can be called from different solving threads.
    /// Each thread has its own assignment and id, which can be obtained using
    /// [`PropagateControl::thread_id()`](struct.PropagateControl.html#method.thread_id).
    ///
    /// # Arguments
    ///
    /// * `control` - control object for the target solver
    /// * `changes` - the change set
    ///
    /// **Returns** whether the call was successful
    fn propagate(&mut self, _control: &mut PropagateControl, _changes: &[Literal]) -> bool {
        true
    }
    #[doc(hidden)]
    unsafe extern "C" fn unsafe_propagate<T: Propagator>(
        control: *mut clingo_propagate_control_t,
        changes: *const clingo_literal_t,
        size: usize,
        data: *mut ::std::os::raw::c_void,
    ) -> bool {
        assert!(!control.is_null());
        if let Some(control) = (control as *mut PropagateControl).as_mut() {
            assert!(!changes.is_null());
            let changes = std::slice::from_raw_parts(changes as *const Literal, size);

            assert!(!data.is_null());
            if let Some(propagator) = (data as *mut T).as_mut() {
                return propagator.propagate(control, changes);
            } else {
                set_internal_error(
                    ErrorType::Runtime,
                    "unsafe_propagate tried casting a null pointer to &mut Propagator.",
                );
            }
        } else {
            set_internal_error(
                ErrorType::Runtime,
                "unsafe_propagate tried casting a null pointer to &mut PropagateControl.",
            );
        }
        false
    }
    /// Called whenever a solver undoes assignments to watched solver literals.
    ///
    /// This callback is meant to update assignment dependent state in the propagator.
    ///
    /// **Note:** No clauses must be propagated in this callback.
    ///
    /// # Arguments
    ///
    /// * `control` - control object for the target solver
    /// * `changes` - the change set
    fn undo(&mut self, _control: &mut PropagateControl, _changes: &[Literal]) -> bool {
        true
    }
    #[doc(hidden)]
    unsafe extern "C" fn unsafe_undo<T: Propagator>(
        control: *mut clingo_propagate_control_t,
        changes: *const clingo_literal_t,
        size: usize,
        data: *mut ::std::os::raw::c_void,
    ) -> bool {
        if let Some(control) = (control as *mut PropagateControl).as_mut() {
            assert!(!changes.is_null());
            let changes = std::slice::from_raw_parts(changes as *const Literal, size);

            if let Some(propagator) = (data as *mut T).as_mut() {
                return propagator.undo(control, changes);
            } else {
                set_internal_error(
                    ErrorType::Runtime,
                    "unsafe_undo tried casting a null pointer to &mut Propagator.",
                );
            }
        } else {
            set_internal_error(
                ErrorType::Runtime,
                "unsafe_undo tried casting a null pointer to &mut PropagateControl.",
            );
        }
        false
    }
    /// This function is similar to
    /// [`PropagateControl::propagate()`](struct.PropagateControl.html#method.propagate) but is only
    /// called on total assignments without a change set.
    ///
    /// When exactly this function is called, can be configured using the
    /// [`PropagateInit::set_check_mode()`](struct.PropagateInit.html#method.set_check_mode)
    /// function.
    ///
    /// **Note:** This function is called even if no watches have been added.
    ///
    /// # Arguments
    ///
    /// * `control` - control object for the target solver
    ///
    /// **Returns** whether the call was successful
    fn check(&mut self, _control: &mut PropagateControl) -> bool {
        true
    }
    #[doc(hidden)]
    unsafe extern "C" fn unsafe_check<T: Propagator>(
        control: *mut clingo_propagate_control_t,
        data: *mut ::std::os::raw::c_void,
    ) -> bool {
        if let Some(control) = (control as *mut PropagateControl).as_mut() {
            if let Some(propagator) = (data as *mut T).as_mut() {
                return propagator.check(control);
            } else {
                set_internal_error(
                    ErrorType::Runtime,
                    "unsafe_check tried casting a null pointer to &mut Propagator.",
                );
            }
        } else {
            set_internal_error(
                ErrorType::Runtime,
                "unsafe_check tried casting a null pointer to &mut PropagateControl.",
            );
        }
        false
    }
}

/// Control object holding grounding and solving state.
#[derive(Debug)]
pub struct Control {
    ctl: Unique<clingo_control_t>,
}
impl Drop for Control {
    fn drop(&mut self) {
        //         println!("drop Control");
        unsafe { clingo_control_free(self.ctl.as_ptr()) }
    }
}
impl Control {
    /// Create a new control object.
    ///
    /// **Note:** Only gringo options (without `--output`) and clasp's options are supported as
    /// arguments,  except basic options such as `--help`.
    /// Furthermore, a control object is blocked while a search call is active;
    /// you must not call any member function during search.
    ///
    /// Messages are printed to stderr.
    ///
    /// # Arguments
    ///
    /// * `arguments` - string array of command line arguments
    ///
    /// # Errors
    ///
    /// - [`NulError`](https://doc.rust-lang.org/std/ffi/struct.NulError.html) - if an argument contains a nul byte
    /// - [`ErrorType::BadAlloc`](enum.ErrorType.html#variant.BadAlloc)
    /// - [`ErrorType::Runtime`](enum.ErrorType.html#variant.Runtime) if argument parsing fails
    /// - [`WrapperError`](struct.WrapperError.html)
    pub fn new(arguments: std::vec::Vec<String>) -> Result<Control, Error> {
        let logger = None;
        let logger_data = std::ptr::null_mut();

        // create a vector of zero terminated strings
        let mut args = vec![];
        for arg in arguments {
            args.push(CString::new(arg)?);
        }

        // convert the strings to raw pointers
        let c_args = args.iter()
            .map(|arg| arg.as_ptr())
            .collect::<Vec<*const c_char>>();

        let mut ctl_ptr = unsafe { mem::uninitialized() };

        if unsafe {
            clingo_control_new(
                c_args.as_ptr(),
                c_args.len(),
                logger,
                logger_data,
                0,
                &mut ctl_ptr,
            )
        } {
            match Unique::new(ctl_ptr) {
                Some(ctl) => Ok(Control { ctl: ctl }),
                None => Err(WrapperError {
                    msg: "tried creating Unique from a null pointer.",
                })?,
            }
        } else {
            Err(error())?
        }
    }

    /// Create a new control object.
    ///
    /// **Note:** Only gringo options (without `--output`) and clasp's options are supported as
    /// arguments,
    /// except basic options such as `--help`.
    /// Furthermore, a control object is blocked while a search call is active;
    /// you must not call any member function during search.
    ///
    /// # Arguments
    ///
    /// * `arguments` - string array of command line arguments
    /// * `logger` - callback functions for warnings and info messages
    /// * `message_limit` - maximum number of times the logger callback is called
    ///
    /// # Errors
    ///
    /// - [`NulError`](https://doc.rust-lang.org/std/ffi/struct.NulError.html) - if an argument contains a nul byte
    /// - [`ErrorType::BadAlloc`](enum.ErrorType.html#variant.BadAlloc)
    /// - [`ErrorType::Runtime`](enum.ErrorType.html#variant.Runtime) if argument parsing fails

    pub fn new_with_logger<L: Logger>(
        arguments: Vec<String>,
        logger: &mut L,
        message_limit: u32,
    ) -> Result<Control, Error> {
        let mut args = vec![];
        for arg in arguments {
            args.push(CString::new(arg)?);
        }

        // convert the strings to raw pointers
        let c_args = args.iter()
            .map(|arg| arg.as_ptr())
            .collect::<Vec<*const c_char>>();

        let mut ctl_ptr = unsafe { mem::uninitialized() };

        let data = logger as *mut L;
        if unsafe {
            clingo_control_new(
                c_args.as_ptr(),
                c_args.len(),
                Some(L::unsafe_logging_callback::<L> as LoggingCallback),
                data as *mut ::std::os::raw::c_void,
                message_limit,
                &mut ctl_ptr,
            )
        } {
            match Unique::new(ctl_ptr) {
                Some(ctl) => Ok(Control { ctl: ctl }),
                None => Err(WrapperError {
                    msg: "tried creating Unique from a null pointer.",
                })?,
            }
        } else {
            Err(error())?
        }
    }

    //NODO: pub fn clingo_control_load(control: *mut Control, file: *const c_char) -> bool;

    /// Extend the logic program with the given non-ground logic program in string form.
    ///
    /// This function puts the given program into a block of form: `#program name(parameters).`
    ///
    /// After extending the logic program, the corresponding program parts are typically grounded
    /// with `ground()`.
    ///
    /// # Arguments
    ///
    /// * `name` - name of the program block
    /// * `parameters` - string array of parameters of the program block
    /// * `program` - string representation of the program
    ///
    /// # Errors
    ///
    /// - [`NulError`](https://doc.rust-lang.org/std/ffi/struct.NulError.html) - if a any argument contains a nul byte
    /// - [`ErrorType::BadAlloc`](enum.ErrorType.html#variant.BadAlloc)
    /// - [`ErrorType::Runtime`](enum.ErrorType.html#variant.Runtime) if parsing fails
    pub fn add(&mut self, name: &str, parameters: &[&str], program: &str) -> Result<(), Error> {
        let name = CString::new(name)?;

        let program = CString::new(program)?;
        let program_ptr = program.as_ptr();

        let parameters_size = parameters.len();

        // create a vector of zero terminated strings
        let mut l_parameters = vec![];
        for arg in parameters {
            l_parameters.push(CString::new(*arg)?);
        }

        // convert the strings to raw pointers
        let c_parameters = l_parameters
            .iter()
            .map(|arg| arg.as_ptr())
            .collect::<Vec<*const c_char>>();

        if unsafe {
            clingo_control_add(
                self.ctl.as_ptr(),
                name.as_ptr(),
                c_parameters.as_ptr(),
                parameters_size,
                program_ptr,
            )
        } {
            Ok(())
        } else {
            Err(error())?
        }
    }

    /// Ground the selected [parts](struct.Part.html) of the current (non-ground) logic
    /// program.
    ///
    /// After grounding, logic programs can be solved with [`solve()`](struct.Control.html.method.solve).
    ///
    /// **Note:** Parts of a logic program without an explicit `#program`
    /// specification are by default put into a program called `base` - without
    /// arguments.
    ///
    /// # Arguments
    ///
    /// * `parts` -  array of [parts](struct.Part.html) to ground
    ///
    /// # Errors
    ///
    /// - [`ErrorType::BadAlloc`](enum.ErrorType.html#variant.BadAlloc)
    pub fn ground(&mut self, parts: &[Part]) -> Result<(), ClingoError> {
        let parts_size = parts.len();
        let parts = parts
            .iter()
            .map(|arg| arg.from())
            .collect::<Vec<clingo_part>>();

        if unsafe {
            clingo_control_ground(
                self.ctl.as_ptr(),
                parts.as_ptr(),
                parts_size,
                None,
                std::ptr::null_mut() as *mut ::std::os::raw::c_void,
            )
        } {
            Ok(())
        } else {
            Err(error())
        }
    }

    /// Ground the selected [parts](struct.Part.html) of the current (non-ground) logic
    /// program.
    ///
    /// After grounding, logic programs can be solved with [`solve()`](struct.Control.html.method.solve).
    ///
    /// **Note:** Parts of a logic program without an explicit `#program`
    /// specification are by default put into a program called `base` - without
    /// arguments.
    ///
    /// # Arguments
    ///
    /// * `parts` - array of [parts](struct.Part.html) to ground
    /// * `handler` - implementing the trait [`ExternalFunctionHandler`](trait.ExternalFunctionHandler.html) to evaluate external functions
    ///
    /// # Errors
    ///
    /// - [`ErrorType::BadAlloc`](enum.ErrorType.html#variant.BadAlloc)
    //TODO: the error code set in ExternalFunctionHandler is overwritten
    pub fn ground_with_event_handler<T: ExternalFunctionHandler>(
        &mut self,
        parts: &[Part],
        handler: &mut T,
    ) -> Result<(), ClingoError> {
        let parts_size = parts.len();
        let parts = parts
            .iter()
            .map(|arg| arg.from())
            .collect::<Vec<clingo_part>>();

        let data = handler as *mut T;
        if unsafe {
            clingo_control_ground(
                self.ctl.as_ptr(),
                parts.as_ptr(),
                parts_size,
                Some(T::unsafe_ground_callback::<T> as GroundCallback),
                data as *mut ::std::os::raw::c_void,
            )
        } {
            Ok(())
        } else {
            Err(error())
        }
    }

    /// Solve the currently [grounded](struct.Control.html#method.ground) logic program
    /// enumerating its models.
    ///
    /// # Arguments
    ///
    /// * `mode` - configures the search mode
    /// * `assumptions` - array of assumptions to solve under
    ///
    /// # Errors
    ///
    /// - [`ErrorType::BadAlloc`](enum.ErrorType.html#variant.BadAlloc)
    /// - [`ErrorType::Runtime`](enum.ErrorType.html#variant.Runtime) if solving could not be started
    /// - [`WrapperError`](struct.WrapperError.html)
    pub fn solve(
        &mut self,
        mode: &SolveMode,
        assumptions: &[SymbolicLiteral],
    ) -> Result<SolveHandle, Error> {
        let mut handle = std::ptr::null_mut() as *mut clingo_solve_handle_t;
        if unsafe {
            clingo_control_solve(
                self.ctl.as_ptr(),
                mode.bits(),
                assumptions.as_ptr() as *const clingo_symbolic_literal_t,
                assumptions.len(),
                None,
                std::ptr::null_mut() as *mut ::std::os::raw::c_void,
                &mut handle,
            )
        } {
            match unsafe { handle.as_mut() } {
                Some(handle_ref) => Ok(SolveHandle { theref: handle_ref }),
                None => Err(WrapperError {
                    msg: "tried casting a null pointer to &mut clingo_solve_handle.",
                })?,
            }
        } else {
            Err(error())?
        }
    }

    /// Solve the currently [grounded](struct.Control.html#method.ground) logic program
    /// enumerating its models.
    ///
    /// # Arguments
    ///
    /// * `mode` - configures the search mode
    /// * `assumptions` - array of assumptions to solve under
    /// * `handler` - implementing the trait [`SolveEventHandler`](trait.SolveEventHandler.html)
    ///
    /// # Errors
    ///
    /// - [`WrapperError`](struct.WrapperError.html)
    /// - [`ErrorType::BadAlloc`](enum.ErrorType.html#variant.BadAlloc)
    /// - [`ErrorType::Runtime`](enum.ErrorType.html#variant.Runtime) if solving could not be started
    pub fn solve_with_event_handler<T: SolveEventHandler>(
        &mut self,
        mode: &SolveMode,
        assumptions: &[SymbolicLiteral],
        handler: &mut T,
    ) -> Result<SolveHandle, Error> {
        let mut handle = std::ptr::null_mut() as *mut clingo_solve_handle_t;
        let data = handler as *mut T;
        if unsafe {
            clingo_control_solve(
                self.ctl.as_ptr(),
                mode.bits(),
                assumptions.as_ptr() as *const clingo_symbolic_literal_t,
                assumptions.len(),
                Some(T::unsafe_solve_callback::<T> as SolveEventCallback),
                data as *mut ::std::os::raw::c_void,
                &mut handle,
            )
        } {
            match unsafe { handle.as_mut() } {
                Some(handle_ref) => Ok(SolveHandle { theref: handle_ref }),
                None => Err(WrapperError {
                    msg: "tried casting a null pointer to &mut clingo_solve_handle.",
                })?,
            }
        } else {
            Err(error())?
        }
    }

    /// Clean up the domains of clingo's grounding component using the solving
    /// component's top level assignment.
    ///
    /// This function removes atoms from domains that are false and marks atoms as
    /// facts that are true.  With multi-shot solving, this can result in smaller
    /// groundings because less rules have to be instantiated and more
    /// simplifications can be applied.
    ///
    /// # Errors
    ///
    /// - [`ErrorType::BadAlloc`](enum.ErrorType.html#variant.BadAlloc)
    pub fn cleanup(&mut self) -> Result<(), ClingoError> {
        if unsafe { clingo_control_cleanup(self.ctl.as_ptr()) } {
            Ok(())
        } else {
            Err(error())
        }
    }

    /// Assign a truth value to an external atom.
    ///
    /// If the atom does not exist or is not external, this is a noop.
    ///
    /// # Arguments
    ///
    /// * `atom` - atom to assign
    /// * `value` - the truth value
    ///
    /// # Errors
    ///
    /// - [`ErrorType::BadAlloc`](enum.ErrorType.html#variant.BadAlloc)
    pub fn assign_external(
        &mut self,
        symbol: &Symbol,
        value: TruthValue,
    ) -> Result<(), ClingoError> {
        if unsafe {
            clingo_control_assign_external(
                self.ctl.as_ptr(),
                symbol.0,
                value as clingo_truth_value_t,
            )
        } {
            Ok(())
        } else {
            Err(error())
        }
    }

    /// Release an external atom.
    ///
    /// After this call, an external atom is no longer external and subject to
    /// program simplifications.  If the atom does not exist or is not external,
    /// this is a noop.
    ///
    /// # Arguments
    ///
    /// * `atom` - atom to release
    ///
    /// # Errors
    ///
    /// - [`ErrorType::BadAlloc`](enum.ErrorType.html#variant.BadAlloc)
    pub fn release_external(&mut self, Symbol(atom): Symbol) -> Result<(), ClingoError> {
        if unsafe { clingo_control_release_external(self.ctl.as_ptr(), atom) } {
            Ok(())
        } else {
            Err(error())
        }
    }

    /// Register a custom propagator with the control object.
    ///
    /// If the sequential flag is set to true, the propagator is called
    /// sequentially when solving with multiple threads.
    ///
    /// # Arguments
    ///
    /// * `propagator` - implementing the trait [`Propagator`](trait.Propagator.html)
    /// * `sequential` - whether the propagator should be called sequentially
    ///
    /// # Errors
    ///
    /// - [`ErrorType::BadAlloc`](enum.ErrorType.html#variant.BadAlloc)
    pub fn register_propagator<T: Propagator>(
        &mut self,
        propagator: &mut T,
        sequential: bool,
    ) -> Result<(), ClingoError> {
        let data_ptr = propagator as *mut T;
        let propagator = clingo_propagator_t {
            init: Some(T::unsafe_init::<T>),
            propagate: Some(T::unsafe_propagate::<T>),
            undo: Some(T::unsafe_undo::<T>),
            check: Some(T::unsafe_check::<T>),
        };
        if unsafe {
            clingo_control_register_propagator(
                self.ctl.as_ptr(),
                &propagator,
                data_ptr as *mut ::std::os::raw::c_void,
                sequential,
            )
        } {
            Ok(())
        } else {
            Err(error())
        }
    }

    /// Get a statistics object to inspect solver statistics.
    ///
    /// Statistics are updated after a solve call.
    ///
    /// **Attention:**
    /// The level of detail of the statistics depends on the stats option
    /// (which can be set using [`Configuration`](struct.Configuration.html) or passed as an
    /// option when [creating the control object](struct.Control.html#method.new)).
    /// The default level zero only provides basic statistics,
    /// level one provides extended and accumulated statistics,
    /// and level two provides per-thread statistics.
    ///
    /// # Errors
    ///
    /// - [`ErrorType::BadAlloc`](enum.ErrorType.html#variant.BadAlloc)
    pub fn statistics(&self) -> Result<&Statistics, Error> {
        let mut stat = std::ptr::null() as *const clingo_statistics_t;
        if unsafe { clingo_control_statistics(self.ctl.as_ptr(), &mut stat) } {
            match unsafe { (stat as *mut Statistics).as_ref() } {
                Some(x) => Ok(x),
                None => Err(WrapperError {
                    msg: "tried casting a null pointer to &Statistics.",
                })?,
            }
        } else {
            Err(error())?
        }
    }

    /// Interrupt the active solve call (or the following solve call right at the beginning).
    pub fn interrupt(&mut self) {
        unsafe {
            clingo_control_interrupt(self.ctl.as_ptr());
        }
    }

    /// Get a configuration object to change the solver configuration.
    pub fn configuration_mut(&mut self) -> Option<&mut Configuration> {
        let mut conf = std::ptr::null_mut() as *mut clingo_configuration_t;
        if unsafe { clingo_control_configuration(self.ctl.as_ptr(), &mut conf) } {
            unsafe { (conf as *mut Configuration).as_mut() }
        } else {
            None
        }
    }

    /// Get a configuration object to change the solver configuration.
    pub fn configuration(&self) -> Option<&Configuration> {
        let mut conf = std::ptr::null_mut() as *mut clingo_configuration_t;
        if unsafe { clingo_control_configuration(self.ctl.as_ptr(), &mut conf) } {
            unsafe { (conf as *const Configuration).as_ref() }
        } else {
            None
        }
    }

    /// Configure how learnt constraints are handled during enumeration.
    ///
    /// If the enumeration assumption is enabled, then all information learnt from
    /// the solver's various enumeration modes is removed after a solve call. This
    /// includes enumeration of cautious or brave consequences, enumeration of
    /// answer sets with or without projection, or finding optimal models, as well
    /// as clauses added with clingo_solve_control_add_clause().
    ///
    /// **Attention:** For practical purposes, this option is only interesting for single-shot
    /// solving or before the last solve call to squeeze out a tiny bit of performance.
    /// Initially, the enumeration assumption is enabled.
    ///
    /// # Arguments
    ///
    /// * `enable` - whether to enable the assumption
    pub fn use_enumeration_assumption(&mut self, enable: bool) -> Option<()> {
        if unsafe { clingo_control_use_enumeration_assumption(self.ctl.as_ptr(), enable) } {
            Some(())
        } else {
            None
        }
    }

    /// Return the symbol for a constant definition of form: `#const name = symbol`.
    ///
    /// # Arguments
    ///
    /// * `name` - the name of the constant if it exists
    pub fn get_const(&self, name: &str) -> Option<Symbol> {
        if let Ok(name) = CString::new(name) {
            let mut symbol = 0 as clingo_symbol_t;
            if unsafe { clingo_control_get_const(self.ctl.as_ptr(), name.as_ptr(), &mut symbol) } {
                Some(Symbol(symbol))
            } else {
                None
            }
        } else {
            None
        }
    }

    /// Check if there is a constant definition for the given constant.
    ///
    /// # Arguments
    ///
    /// * `name` - the name of the constant
    ///
    /// **See:** [`Part::get_const()`](struct.Part.html#method.get_const)
    pub fn has_const(&self, name: &str) -> bool {
        if let Ok(name) = CString::new(name) {
            let mut exist = false;
            if unsafe { clingo_control_has_const(self.ctl.as_ptr(), name.as_ptr(), &mut exist) } {
                return exist;
            }
        }
        false
    }

    /// Get an object to inspect symbolic atoms (the relevant Herbrand base) used
    /// for grounding.
    pub fn symbolic_atoms(&self) -> Option<&SymbolicAtoms> {
        let mut atoms = std::ptr::null() as *const clingo_symbolic_atoms_t;
        if unsafe { clingo_control_symbolic_atoms(self.ctl.as_ptr(), &mut atoms) } {
            unsafe { (atoms as *const SymbolicAtoms).as_ref() }
        } else {
            None
        }
    }

    /// Get an object to inspect theory atoms that occur in the grounding.
    pub fn theory_atoms(&self) -> Option<&TheoryAtoms> {
        let mut atoms = std::ptr::null() as *const clingo_theory_atoms_t;
        if unsafe { clingo_control_theory_atoms(self.ctl.as_ptr(), &mut atoms) } {
            unsafe { (atoms as *const TheoryAtoms).as_ref() }
        } else {
            None
        }
    }

    /// Register a program observer with the control object.
    ///
    /// # Arguments
    ///
    /// * `observer` - the observer to register
    /// * `replace` - just pass the grounding to the observer but not the solver
    ///
    /// **Returns** whether the call was successful
    pub fn register_observer<T: GroundProgramObserver>(
        &mut self,
        observer: &mut T,
        replace: bool,
    ) -> bool {
        let data = observer as *mut T;
        let gpo = clingo_ground_program_observer_t {
            init_program: Some(T::unsafe_init_program::<T>),
            begin_step: Some(T::unsafe_begin_step::<T>),
            end_step: Some(T::unsafe_end_step::<T>),
            rule: Some(T::unsafe_rule::<T>),
            weight_rule: Some(T::unsafe_weight_rule::<T>),
            minimize: Some(T::unsafe_minimize::<T>),
            project: Some(T::unsafe_project::<T>),
            output_atom: Some(T::unsafe_output_atom::<T>),
            output_term: Some(T::unsafe_output_term::<T>),
            output_csp: Some(T::unsafe_output_csp::<T>),
            external: Some(T::unsafe_external::<T>),
            assume: Some(T::unsafe_assume::<T>),
            heuristic: Some(T::unsafe_heuristic::<T>),
            acyc_edge: Some(T::unsafe_acyc_edge::<T>),
            theory_term_number: Some(T::unsafe_theory_term_number::<T>),
            theory_term_string: Some(T::unsafe_theory_term_string::<T>),
            theory_term_compound: Some(T::unsafe_theory_term_compound::<T>),
            theory_element: Some(T::unsafe_theory_element::<T>),
            theory_atom: Some(T::unsafe_theory_atom::<T>),
            theory_atom_with_guard: Some(T::unsafe_theory_atom_with_guard::<T>),
        };
        unsafe {
            clingo_control_register_observer(
                self.ctl.as_ptr(),
                &gpo,
                replace,
                data as *mut ::std::os::raw::c_void,
            )
        }
    }

    /// Get an object to add ground directives to the program.
    ///
    /// # Errors
    ///
    /// - [`ErrorType::BadAlloc`](enum.ErrorType.html#variant.BadAlloc)
    pub fn backend(&mut self) -> Option<&mut Backend> {
        let mut backend = std::ptr::null_mut();
        if unsafe { clingo_control_backend(self.ctl.as_ptr(), &mut backend) } {
            unsafe { (backend as *mut Backend).as_mut() }
        } else {
            None
        }
    }

    /// Get an object to add non-ground directives to the program.
    pub fn program_builder(&mut self) -> Result<ProgramBuilder, WrapperError> {
        let mut builder = std::ptr::null_mut() as *mut clingo_program_builder_t;
        if unsafe { clingo_control_program_builder(self.ctl.as_ptr(), &mut builder) } {
            // begin building the program
            if unsafe { clingo_program_builder_begin(builder) } {
                match unsafe { builder.as_mut() } {
                    Some(builder_ref) => Ok(ProgramBuilder {
                        theref: builder_ref,
                    }),
                    None => Err(WrapperError {
                        msg: "tried casting a null pointer to &mut clingo_program_builder.",
                    }),
                }
            } else {
                Err(WrapperError {
                    msg: "clingo_program_builder_begin() failed.",
                })
            }
        } else {
            Err(WrapperError {
                msg: "clingo_control_program_builder() failed.",
            })
        }
    }

    // NODO: pub fn clingo_control_clasp_facade()
}

/// Representation of a program statement.
#[derive(Clone)]
pub struct AstStatement<'a, T: 'a> {
    data: clingo_ast_statement_t,
    phantom: PhantomData<&'a T>,
}
impl<'a, T> AstStatement<'a, T> {
    /// Get the location of the statement.
    pub fn location(&self) -> Location {
        Location(self.data.location)
    }

    /// Get the type of the statement.
    pub fn statement_type(&self) -> ast::StatementType {
        match self.data.type_ as u32 {
            clingo_ast_statement_type_clingo_ast_statement_type_rule => ast::StatementType::Rule,
            clingo_ast_statement_type_clingo_ast_statement_type_const => ast::StatementType::Const,
            clingo_ast_statement_type_clingo_ast_statement_type_show_signature => {
                ast::StatementType::ShowSignature
            }
            clingo_ast_statement_type_clingo_ast_statement_type_show_term => {
                ast::StatementType::ShowTerm
            }
            clingo_ast_statement_type_clingo_ast_statement_type_minimize => {
                ast::StatementType::Minimize
            }
            clingo_ast_statement_type_clingo_ast_statement_type_script => {
                ast::StatementType::Script
            }
            clingo_ast_statement_type_clingo_ast_statement_type_program => {
                ast::StatementType::Program
            }
            clingo_ast_statement_type_clingo_ast_statement_type_external => {
                ast::StatementType::External
            }
            clingo_ast_statement_type_clingo_ast_statement_type_edge => ast::StatementType::Edge,
            clingo_ast_statement_type_clingo_ast_statement_type_heuristic => {
                ast::StatementType::Heuristic
            }
            clingo_ast_statement_type_clingo_ast_statement_type_project_atom => {
                ast::StatementType::ProjectAtom
            }
            clingo_ast_statement_type_clingo_ast_statement_type_project_atom_signature => {
                ast::StatementType::ProjectAtomSignature
            }
            clingo_ast_statement_type_clingo_ast_statement_type_theory_definition => {
                ast::StatementType::TheoryDefinition
            }
            x => panic!("Failed to match clingo_ast_statement_type: {}.", x),
        }
    }

    /// Get a reference to the rule if the statement is a rule.
    pub fn rule(&self) -> Result<&ast::Rule, WrapperError> {
        match self.statement_type() {
            ast::StatementType::Rule => {
                let rule = unsafe { self.data.__bindgen_anon_1.rule as *const clingo_ast_rule_t };
                match unsafe { (rule as *const ast::Rule).as_ref() } {
                    Some(reference) => Ok(reference),
                    None => Err(WrapperError {
                        msg: "tried casting a null pointer to &ast::Rule.",
                    }),
                }
            }
            _ => Err(WrapperError {
                msg: "Wrong StatementType,",
            }),
        }
    }

    /// Get a reference to the external if the [statement type](#method.statement_type) is [`External`](ast/enum.StatementType.html#variant.External).
    pub fn external(&self) -> Result<&ast::External, WrapperError> {
        match self.statement_type() {
            ast::StatementType::External => {
                let external =
                    unsafe { self.data.__bindgen_anon_1.external as *const clingo_ast_external_t };
                match unsafe { (external as *const ast::External).as_ref() } {
                    Some(reference) => Ok(reference),
                    None => Err(WrapperError {
                        msg: "tried casting a null pointer to &ast::External.",
                    }),
                }
            }
            _ => Err(WrapperError {
                msg: "Wrong StatementType,",
            }),
        }
    }

    /// Get project signature if the [statement type](#method.statement_type) is [`ProjectAtomSignature`](ast/enum.StatementType.html#variant.ProjectAtomSignature).
    pub fn project_signature(&self) -> Result<Signature, WrapperError> {
        match self.statement_type() {
            ast::StatementType::ProjectAtomSignature => {
                let project_signature = unsafe { self.data.__bindgen_anon_1.project_signature };
                Ok(Signature(project_signature))
            }
            _ => Err(WrapperError {
                msg: "Wrong StatementType,",
            }),
        }
    }
}

/// Object to build non-ground programs.
pub struct ProgramBuilder<'a> {
    theref: &'a mut clingo_program_builder_t,
}
impl<'a> ProgramBuilder<'a> {
    /// Adds a statement to the program.
    ///
    /// **Attention:** The [`end()`](struct.ProgramBuilder.html#method.end) must be called after
    /// all statements have been added.
    ///
    /// # Arguments
    ///
    /// * `statement` - the statement to add
    ///
    /// # Errors
    ///
    /// - [`ErrorType::Runtime`](enum.ErrorType.html#variant.Runtime) for statements of invalid form
    /// - [`ErrorType::BadAlloc`](enum.ErrorType.html#variant.BadAlloc)
    pub fn add<T>(&mut self, stm: &AstStatement<T>) -> Result<(), ClingoError> {
        if unsafe { clingo_program_builder_add(self.theref, &stm.data) } {
            Ok(())
        } else {
            Err(error())
        }
    }

    /// End building a program.
    /// The method consumes the program builder.
    pub fn end(self) -> Option<()> {
        if unsafe { clingo_program_builder_end(self.theref) } {
            Some(())
        } else {
            None
        }
    }
}

/// Handle for to the solver configuration.
#[derive(Debug, Copy, Clone)]
pub struct Configuration(clingo_configuration_t);
impl Configuration {
    /// Get the root key of the configuration.
    pub fn root(&self) -> Option<Id> {
        let mut root_key = 0 as clingo_id_t;
        if unsafe { clingo_configuration_root(&self.0, &mut root_key) } {
            Some(Id(root_key))
        } else {
            None
        }
    }

    /// Get the type of a key.
    /// The type is a bitset, an entry can have multiple (but at least one) type.
    pub fn configuration_type(&self, Id(key): Id) -> Option<ConfigurationType> {
        let mut ctype = 0 as clingo_configuration_type_bitset_t;
        if unsafe { clingo_configuration_type(&self.0, key, &mut ctype) } {
            ConfigurationType::from_bits(ctype)
        } else {
            None
        }
    }

    /// Get the description of an entry.
    pub fn description(&self, Id(key): Id) -> Result<&str, WrapperError> {
        let mut description_ptr = unsafe { mem::uninitialized() };
        if unsafe {
            clingo_configuration_description(
                &self.0,
                key,
                &mut description_ptr as *mut *const c_char,
            )
        } {
            let cstr = unsafe { CStr::from_ptr(description_ptr) };
            // all descriptions should be valid UTF-8 strings
            Ok(cstr.to_str().unwrap())
        } else {
            Err(WrapperError {
                msg: "clingo_configuration_description() failed.",
            })
        }
    }

    /// Get the size of an array entry.
    ///
    /// # Pre-condition
    ///
    /// The [type](struct.Configuration.html#method.type) of the entry must be  [`ConfigurationType::ARRAY`](struct.ConfigurationType.html#associatedconstant.ARRAY).
    pub fn array_size(&self, Id(key): Id) -> Option<usize> {
        let mut size = 0;
        if unsafe { clingo_configuration_array_size(&self.0, key, &mut size) } {
            Some(size)
        } else {
            None
        }
    }

    /// Get the subkey at the given offset of an array entry.
    ///
    /// **Note:** Some array entries, like fore example the solver configuration, can be accessed
    /// past there actual size to add subentries.
    ///
    /// # Pre-condition
    ///
    /// The [type](struct.Configuration.html#method.type) of the entry must be [`ConfigurationType::ARRAY`](struct.ConfigurationType.html#associatedconstant.ARRAY).
    ///
    /// # Arguments
    ///
    /// * `key` - the key
    /// * `offset` - the offset in the array
    pub fn array_at(&self, Id(key): Id, offset: usize) -> Option<Id> {
        let mut nkey = 0 as clingo_id_t;
        if unsafe { clingo_configuration_array_at(&self.0, key, offset, &mut nkey) } {
            Some(Id(nkey))
        } else {
            None
        }
    }

    /// Get the number of subkeys of a map entry.
    ///
    /// # Pre-condition
    ///
    /// The [type](struct.Configuration.html#method.type) of the entry must be [`ConfigurationType::MAP`](struct.ConfigurationType.html#associatedconstant.MAP).
    pub fn map_size(&self, Id(key): Id) -> Option<usize> {
        let mut size = 0;
        if unsafe { clingo_configuration_map_size(&self.0, key, &mut size) } {
            Some(size)
        } else {
            None
        }
    }

    /// Query whether the map has a key.
    ///
    /// # Pre-condition
    ///
    /// The [type](struct.Configuration.html#method.type) of the entry must be [`ConfigurationType::Map`](enum.ConfigurationType.html#variant.Map).
    ///
    /// **Note:** Multiple levels can be looked up by concatenating keys with a period.
    ///
    /// # Arguments
    ///
    /// * `key` - the key
    /// * `name` - the name to lookup the subkey
    ///
    /// **Returns** whether the key is in the map
    pub fn map_has_subkey(&self, Id(key): Id, name: &str) -> Option<bool> {
        let mut result = false;
        if let Ok(name) = CString::new(name) {
            if unsafe {
                clingo_configuration_map_has_subkey(&self.0, key, name.as_ptr(), &mut result)
            } {
                Some(result)
            } else {
                None
            }
        } else {
            Some(false)
        }
    }

    /// Get the name associated with the offset-th subkey.
    ///
    /// # Pre-condition
    ///
    /// The [type](struct.Configuration.html#method.type) of the entry must be [`ConfigurationType::MAP`](struct.ConfigurationType.html#associatedconstant.MAP).
    ///
    /// # Arguments
    ///
    /// * `key` - the key
    /// * `offset` - the offset of the name
    pub fn map_subkey_name(&self, Id(key): Id, offset: usize) -> Result<&str, WrapperError> {
        let mut name_ptr = unsafe { mem::uninitialized() };
        if unsafe {
            clingo_configuration_map_subkey_name(
                &self.0,
                key,
                offset,
                &mut name_ptr as *mut *const c_char,
            )
        } {
            let cstr = unsafe { CStr::from_ptr(name_ptr) };
            // all configuration keys should be valid UTF-8 strings
            Ok(cstr.to_str().unwrap())
        } else {
            Err(WrapperError {
                msg: "clingo_configuration_map_subkey_name() failed.",
            })
        }
    }

    /// Lookup a subkey under the given name.
    ///
    /// # Pre-condition
    ///
    /// The [type](struct.Configuration.html#method.type) of the entry must be [`ConfigurationType::MAP`](struct.ConfigurationType.html#associatedconstant.MAP).
    ///
    /// **Note:** Multiple levels can be looked up by concatenating keys with a period.
    pub fn map_at(&self, Id(key): Id, name: &str) -> Option<Id> {
        let mut nkey = 0 as clingo_id_t;
        if let Ok(name) = CString::new(name) {
            if unsafe { clingo_configuration_map_at(&self.0, key, name.as_ptr(), &mut nkey) } {
                return Some(Id(nkey));
            }
        }
        None
    }

    /// Check whether a entry has a value.
    ///
    /// # Pre-condition
    ///
    /// The [type](struct.Configuration.html#method.type) of the entry must be [`ConfigurationType::VALUE`](struct.ConfigurationType.html#associatedconstant.VALUE).
    ///
    /// # Arguments
    ///
    /// * `key` - the key
    pub fn value_is_assigned(&self, Id(key): Id) -> Option<bool> {
        let mut assigned = false;
        if unsafe { clingo_configuration_value_is_assigned(&self.0, key, &mut assigned) } {
            Some(assigned)
        } else {
            None
        }
    }

    //NODO: clingo_configuration_value_get_size(&mut self.0, key, &mut size)

    /// Get the string value of the given entry.
    ///
    /// # Pre-condition
    ///
    /// The [type](struct.Configuration.html#method.type) of the entry must be [`ConfigurationType::VALUE`](struct.ConfigurationType.html#associatedconstant.VALUE).
    ///
    /// # Arguments
    ///
    /// * `key` - the key
    ///
    /// # Errors
    ///
    /// - [`WrapperError`](struct.WrapperError.html)
    /// - [`Utf8Error`](https://doc.rust-lang.org/std/str/struct.Utf8Error.html)
    pub fn value_get(&self, Id(key): Id) -> Result<&str, Error> {
        let mut size = 0;
        if unsafe { clingo_configuration_value_get_size(&self.0, key, &mut size) } {
            let mut value_ptr = unsafe { mem::uninitialized() };
            if unsafe { clingo_configuration_value_get(&self.0, key, &mut value_ptr, size) } {
                let cstr = unsafe { CStr::from_ptr(&value_ptr) };
                Ok(cstr.to_str()?)
            } else {
                Err(WrapperError {
                    msg: "clingo_configuration_value_get() failed.",
                })?
            }
        } else {
            Err(WrapperError {
                msg: "clingo_configuration_value_get_size() failed.",
            })?
        }
    }

    /// Set the value of an entry.
    ///
    /// # Pre-condition
    ///
    /// The [type](struct.Configuration.html#method.type) of the entry must be [`ConfigurationType::VALUE`](struct.ConfigurationType.html#associatedconstant.VALUE).
    ///
    /// # Arguments
    ///
    /// * `key` - the key
    /// * `value` - the value to set
    ///
    /// # Errors
    ///
    /// - [`NulError`](https://doc.rust-lang.org/std/ffi/struct.NulError.html) - if `value` contains a nul byte
    /// - [`WrapperError`](struct.WrapperError.html)
    pub fn value_set(&mut self, Id(key): Id, value: &str) -> Result<(), Error> {
        let value = CString::new(value)?;
        if unsafe { clingo_configuration_value_set(&mut self.0, key, value.as_ptr()) } {
            Ok(())
        } else {
            Err(WrapperError {
                msg: "clingo_configuration_value_set() failed.",
            })?
        }
    }
}

/// Handle to the backend to add directives in aspif format.
#[derive(Debug, Copy, Clone)]
pub struct Backend(clingo_backend_t);
impl Backend {
    /// Add a rule to the program.
    ///
    /// # Arguments
    ///
    /// * `choice` determines if the head is a choice or a disjunction
    /// * `head` - the head atoms
    /// * `body` - the body literals
    ///
    /// # Errors
    ///
    /// - [`ErrorType::BadAlloc`](enum.ErrorType.html#variant.BadAlloc)
    pub fn rule(
        &mut self,
        choice: bool,
        head: &[Atom],
        body: &[Literal],
    ) -> Result<(), ClingoError> {
        if unsafe {
            clingo_backend_rule(
                &mut self.0,
                choice,
                head.as_ptr() as *const clingo_atom_t,
                head.len(),
                body.as_ptr() as *const clingo_literal_t,
                body.len(),
            )
        } {
            Ok(())
        } else {
            Err(error())
        }
    }

    /// Add a weight rule to the program.
    ///
    /// **Attention:** All weights and the lower bound must be positive.
    ///
    /// # Arguments
    /// * `choice` - determines if the head is a choice or a disjunction
    /// * `head` - the head atoms
    /// * `lower_bound` - the lower bound of the weight rule
    /// * `body` - the weighted body literals
    ///
    /// # Errors
    ///
    /// - [`ErrorType::BadAlloc`](enum.ErrorType.html#variant.BadAlloc)
    pub fn weight_rule(
        &mut self,
        choice: bool,
        head: &[Atom],
        lower_bound: i32,
        body: &[WeightedLiteral],
    ) -> Result<(), ClingoError> {
        if unsafe {
            clingo_backend_weight_rule(
                &mut self.0,
                choice,
                head.as_ptr() as *const clingo_atom_t,
                head.len(),
                lower_bound,
                body.as_ptr() as *const clingo_weighted_literal_t,
                body.len(),
            )
        } {
            Ok(())
        } else {
            Err(error())
        }
    }

    /// Add a minimize constraint (or weak constraint) to the program.
    ///
    /// # Arguments
    ///
    /// * `priority` - the priority of the constraint
    /// * `literals` - the weighted literals whose sum to minimize
    ///
    /// # Errors
    ///
    /// - [`ErrorType::BadAlloc`](enum.ErrorType.html#variant.BadAlloc)
    pub fn minimize(
        &mut self,
        priority: i32,
        literals: &[WeightedLiteral],
    ) -> Result<(), ClingoError> {
        if unsafe {
            clingo_backend_minimize(
                &mut self.0,
                priority,
                literals.as_ptr() as *const clingo_weighted_literal_t,
                literals.len(),
            )
        } {
            Ok(())
        } else {
            Err(error())
        }
    }

    /// Add a projection directive.
    ///
    /// # Arguments
    ///
    /// * `atoms` - the atoms to project on
    ///
    /// # Errors
    ///
    /// - [`ErrorType::BadAlloc`](enum.ErrorType.html#variant.BadAlloc)
    pub fn project(&mut self, atoms: &[Atom]) -> Result<(), ClingoError> {
        if unsafe {
            clingo_backend_project(
                &mut self.0,
                atoms.as_ptr() as *const clingo_atom_t,
                atoms.len(),
            )
        } {
            Ok(())
        } else {
            Err(error())
        }
    }

    /// Add an external statement.
    ///
    /// # Arguments
    ///
    /// * `atom` - the external atom
    /// * `type` - the type of the external statement
    ///
    /// # Errors
    ///
    /// - [`ErrorType::BadAlloc`](enum.ErrorType.html#variant.BadAlloc)
    pub fn external(&mut self, atom: &Atom, type_: ExternalType) -> Result<(), ClingoError> {
        if unsafe { clingo_backend_external(&mut self.0, atom.0, type_ as clingo_external_type_t) }
        {
            Ok(())
        } else {
            Err(error())
        }
    }

    /// Add an assumption directive.
    ///
    /// # Arguments
    ///
    /// * `literals` - the literals to assume (positive literals are true and negative literals
    /// false for the next solve call)
    ///
    /// # Errors
    ///
    /// - [`ErrorType::BadAlloc`](enum.ErrorType.html#variant.BadAlloc)
    pub fn assume(&mut self, literals: &[Literal]) -> Result<(), ClingoError> {
        let size = literals.len();
        if unsafe {
            clingo_backend_assume(
                &mut self.0,
                literals.as_ptr() as *const clingo_literal_t,
                size,
            )
        } {
            Ok(())
        } else {
            Err(error())
        }
    }

    /// Add an heuristic directive.
    ///
    /// # Arguments
    ///
    /// * `atom` - the target atom
    /// * `type` - the type of the heuristic modification
    /// * `bias` - the heuristic bias
    /// * `priority` - the heuristic priority
    /// * `condition` - the condition under which to apply the heuristic modification
    ///
    /// # Errors
    ///
    /// - [`ErrorType::BadAlloc`](enum.ErrorType.html#variant.BadAlloc)
    pub fn heuristic(
        &mut self,
        atom: &Atom,
        type_: HeuristicType,
        bias: i32,
        priority: u32,
        condition: &[Literal],
    ) -> Result<(), ClingoError> {
        let size = condition.len();
        if unsafe {
            clingo_backend_heuristic(
                &mut self.0,
                atom.0,
                type_ as clingo_heuristic_type_t,
                bias,
                priority,
                condition.as_ptr() as *const clingo_literal_t,
                size,
            )
        } {
            Ok(())
        } else {
            Err(error())
        }
    }

    /// Add an edge directive.
    ///
    /// # Arguments
    ///
    /// * `node_u` - the start vertex of the edge
    /// * `node_v` - the end vertex of the edge
    /// * `condition` - the condition under which the edge is part of the graph
    ///
    /// # Errors
    ///
    /// - [`ErrorType::BadAlloc`](enum.ErrorType.html#variant.BadAlloc)
    pub fn acyc_edge(
        &mut self,
        node_u: i32,
        node_v: i32,
        condition: &[Literal],
    ) -> Result<(), ClingoError> {
        let size = condition.len();
        if unsafe {
            clingo_backend_acyc_edge(
                &mut self.0,
                node_u,
                node_v,
                condition.as_ptr() as *const clingo_literal_t,
                size,
            )
        } {
            Ok(())
        } else {
            Err(error())
        }
    }

    /// Get a fresh atom to be used in aspif directives.
    pub fn add_atom(&mut self) -> Option<Atom> {
        let mut atom = 0 as clingo_atom_t;
        if unsafe { clingo_backend_add_atom(&mut self.0, &mut atom) } {
            Some(Atom(atom))
        } else {
            None
        }
    }
}

/// Handle for to the solver statistics.
#[derive(Debug, Copy, Clone)]
pub struct Statistics(clingo_statistics_t);
impl Statistics {
    /// Get the root key of the statistics.
    pub fn root(&self) -> Option<u64> {
        let mut root_key = 0 as u64;
        if unsafe { clingo_statistics_root(&self.0, &mut root_key) } {
            Some(root_key)
        } else {
            None
        }
    }

    /// Get the type of a key.
    pub fn statistics_type(&self, key: u64) -> Option<StatisticsType> {
        let mut stype = 0 as clingo_statistics_type_t;
        if unsafe { clingo_statistics_type(&self.0, key, &mut stype) } {
            match stype as u32 {
                clingo_statistics_type_clingo_statistics_type_empty => Some(StatisticsType::Empty),
                clingo_statistics_type_clingo_statistics_type_value => Some(StatisticsType::Value),
                clingo_statistics_type_clingo_statistics_type_array => Some(StatisticsType::Array),
                clingo_statistics_type_clingo_statistics_type_map => Some(StatisticsType::Map),
                x => panic!("Failed to match clingo_statistics_type: {}.", x),
            }
        } else {
            None
        }
    }

    /// Get the size of an array entry.
    ///
    /// # Pre-condition
    ///
    /// The [statistics type](struct.Statistics.html#method.statistics_type) of the entry must be
    /// [`StatisticsType::Array`](enum.StatisticsType.html#variant.Array).
    pub fn array_size(&self, key: u64) -> Option<usize> {
        let mut size = 0 as usize;
        if unsafe { clingo_statistics_array_size(&self.0, key, &mut size) } {
            Some(size)
        } else {
            None
        }
    }

    /// Get the subkey at the given offset of an array entry.
    ///
    /// # Pre-condition
    ///
    /// The [statistics type](struct.Statistics.html#method.statistics_type) of the entry must be
    /// [`StatisticsType::Array`](enum.StatisticsType.html#variant.Array).
    ///
    /// # Arguments
    ///
    /// * `key` - the key
    /// * `offset` - the offset in the array
    pub fn statistics_array_at(&self, key: u64, offset: usize) -> Option<u64> {
        let mut subkey = 0 as u64;
        if unsafe { clingo_statistics_array_at(&self.0, key, offset, &mut subkey) } {
            Some(subkey)
        } else {
            None
        }
    }

    /// Get the number of subkeys of a map entry.
    ///
    /// # Pre-condition
    ///
    /// The [statistics type](struct.Statistics.html#method.statistics_type) of the entry must
    /// be [`StatisticsType::Map`](enum.StatisticsType.html#variant.Map).
    pub fn map_size(&self, key: u64) -> Option<usize> {
        let mut size = 0 as usize;
        if unsafe { clingo_statistics_map_size(&self.0, key, &mut size) } {
            Some(size)
        } else {
            None
        }
    }

    /// Get the name associated with the offset-th subkey.
    ///
    /// # Pre-condition
    ///
    /// The [statistics type](struct.Statistics.html#method.statistics_type) of the entry must be
    /// [`StatisticsType::Map`](enum.StatisticsType.html#variant.Map).
    ///
    /// # Arguments
    ///
    /// * `key` - the key
    /// * `offset` - the offset of the name
    pub fn map_subkey_name(&self, key: u64, offset: usize) -> Result<&str, Error> {
        let mut name = std::ptr::null() as *const c_char;
        if unsafe { clingo_statistics_map_subkey_name(&self.0, key, offset, &mut name) } {
            Ok(unsafe { CStr::from_ptr(name) }.to_str()?)
        } else {
            Err(WrapperError {
                msg: "clingo_statistics_map_subkey_name() failed.",
            })?
        }
    }

    /// Lookup a subkey under the given name.
    ///
    /// # Pre-condition
    ///
    /// The [statistics type](struct.Statistics.html#method.statistics_type) of the entry must be
    /// [`StatisticsType::Map`](enum.StatisticsType.html#variant.Map).
    ///
    /// **Note:** Multiple levels can be looked up by concatenating keys with a period.
    ///
    /// # Arguments
    ///
    /// * `key` - the key
    /// * `name` - the name to lookup the subkey
    pub fn map_at(&self, key: u64, name: &str) -> Option<u64> {
        let mut subkey = 0 as u64;
        if let Ok(name) = CString::new(name) {
            if unsafe { clingo_statistics_map_at(&self.0, key, name.as_ptr(), &mut subkey) } {
                return Some(subkey);
            }
        }
        None
    }

    /// Get the value of the given entry.
    ///
    /// # Pre-condition
    ///
    /// The [statistics type](struct.Statistics.html#method.statistics_type) of the entry must be
    /// [`StatisticsType::Value`](enum.StatisticsType.html#variant.Value).
    pub fn value_get(&self, key: u64) -> Option<f64> {
        let mut value = 0.0 as f64;
        if unsafe { clingo_statistics_value_get(&self.0, key, &mut value) } {
            Some(value)
        } else {
            None
        }
    }
}
/// Container that stores symbolic atoms in a program -- the relevant Herbrand base
/// gringo uses to instantiate programs.
///
/// **See:** [`Control::symbolic_atoms()`](struct.Control.html#method.symbolic_atoms)
#[derive(Debug, Copy, Clone)]
pub struct SymbolicAtoms(clingo_symbolic_atoms_t);
impl SymbolicAtoms {
    /// Get the number of different atoms occurring in a logic program.
    pub fn size(&self) -> Option<usize> {
        let mut size = 0 as usize;
        if unsafe { clingo_symbolic_atoms_size(&self.0, &mut size) } {
            Some(size)
        } else {
            None
        }
    }

    /// Get a forward iterator of the sequence of all symbolic atoms.
    pub fn iter(&self) -> SymbolicAtomsIterator {
        let mut begin = 0 as clingo_symbolic_atom_iterator_t;
        if !unsafe { clingo_symbolic_atoms_begin(&self.0, std::ptr::null(), &mut begin) } {
            panic!("Failed to create iterator for clingo_symbolic_atoms.");
        }
        let mut end = 0 as clingo_symbolic_atom_iterator_t;
        if !unsafe { clingo_symbolic_atoms_end(&self.0, &mut end) } {
            panic!("Failed to create iterator for clingo_symbolic_atoms.");
        }
        SymbolicAtomsIterator {
            cur: begin,
            end: end,
            atoms: &self.0,
        }
    }
    /// Get a forward iterator of the sequence of all symbolic atoms restricted to a given signature.
    ///
    /// # Arguments
    ///
    /// * `signature` - the signature
    pub fn iter_with_signature(&self, sig: &Signature) -> SymbolicAtomsIterator {
        let mut begin = 0 as clingo_symbolic_atom_iterator_t;
        if !unsafe { clingo_symbolic_atoms_begin(&self.0, &sig.0, &mut begin) } {
            panic!("Failed to create iterator for clingo_symbolic_atoms.");
        }
        let mut end = 0 as clingo_symbolic_atom_iterator_t;
        if !unsafe { clingo_symbolic_atoms_end(&self.0, &mut end) } {
            panic!("Failed to create iterator for clingo_symbolic_atoms.");
        }
        SymbolicAtomsIterator {
            cur: begin,
            end: end,
            atoms: &self.0,
        }
    }

    //NODO: fn clingo_symbolic_atoms_signatures_size()

    /// Get the predicate signatures occurring in a logic program.
    ///
    /// # Errors
    ///
    /// - [`ErrorType::BadAlloc`](enum.ErrorType.html#variant.BadAlloc)
    /// - [`ErrorType::Runtime`](enum.ErrorType.html#variant.Runtime) if the size is too small
    pub fn signatures(&self) -> Result<Vec<Signature>, ClingoError> {
        let mut size = 0;
        if unsafe { clingo_symbolic_atoms_signatures_size(&self.0, &mut size) } {
            let signatures = Vec::<Signature>::with_capacity(size);
            let signatures_ptr = signatures.as_ptr();
            if unsafe {
                clingo_symbolic_atoms_signatures(
                    &self.0,
                    signatures_ptr as *mut clingo_signature_t,
                    size,
                )
            } {
                let signatures_ref =
                    unsafe { std::slice::from_raw_parts(signatures_ptr as *const Signature, size) };
                Ok(signatures_ref.to_owned())
            } else {
                Err(error())
            }
        } else {
            Err(error())
        }
    }

    //NODO clingo_symbolic_atoms_is_valid()
}
/// An iterator over symbolic atoms.
pub struct SymbolicAtomsIterator<'a> {
    cur: clingo_symbolic_atom_iterator_t,
    end: clingo_symbolic_atom_iterator_t,
    atoms: &'a clingo_symbolic_atoms_t,
}
impl<'a> Iterator for SymbolicAtomsIterator<'a> {
    type Item = SymbolicAtom<'a>;

    fn next(&mut self) -> Option<SymbolicAtom<'a>> {
        let mut equal = false;
        if unsafe {
            clingo_symbolic_atoms_iterator_is_equal_to(self.atoms, self.cur, self.end, &mut equal)
        } {
            if equal {
                None
            } else {
                let ret = SymbolicAtom {
                    cur: self.cur,
                    atoms: self.atoms,
                };
                if !unsafe { clingo_symbolic_atoms_next(self.atoms, self.cur, &mut self.cur) } {
                    panic!("Failure in SymbolicAtomsIterator.");
                }
                Some(ret)
            }
        } else {
            None
        }
    }
}
/// A symbolic atom in a program.
pub struct SymbolicAtom<'a> {
    cur: clingo_symbolic_atom_iterator_t,
    atoms: &'a clingo_symbolic_atoms_t,
}
impl<'a> SymbolicAtom<'a> {
    /// Check whether an atom is a fact.
    ///
    /// **Note:** This does not determine if an atom is a cautious consequence. The
    /// grounding or solving component's simplifications can only detect this in
    /// some cases.
    pub fn is_fact(&self) -> Option<bool> {
        let mut fact = false;
        if unsafe { clingo_symbolic_atoms_is_fact(self.atoms, self.cur, &mut fact) } {
            Some(fact)
        } else {
            None
        }
    }

    /// Check whether an atom is external.
    ///
    /// An atom is external if it has been defined using an external directive and
    /// has not been released or defined by a rule.
    pub fn is_external(&self) -> Option<bool> {
        let mut external = false;
        if unsafe { clingo_symbolic_atoms_is_external(self.atoms, self.cur, &mut external) } {
            Some(external)
        } else {
            None
        }
    }

    /// Get the symbolic representation of an atom.
    pub fn symbol(&self) -> Option<Symbol> {
        let mut symbol = 0 as clingo_symbol_t;
        if unsafe { clingo_symbolic_atoms_symbol(self.atoms, self.cur, &mut symbol) } {
            Some(Symbol(symbol))
        } else {
            None
        }
    }

    /// Returns the (numeric) aspif literal corresponding to the given symbolic atom.
    ///
    /// Such a literal can be mapped to a solver literal (see [`Propagator`](struct.Propagator)).
    /// or be used in rules in aspif format (see [`ProgramBuilder`](struct.ProgramBuilder.html)).
    pub fn literal(&self) -> Option<Literal> {
        let mut literal = 0 as clingo_literal_t;
        if unsafe { clingo_symbolic_atoms_literal(self.atoms, self.cur, &mut literal) } {
            Some(Literal(literal))
        } else {
            None
        }
    }
}

/// Container that stores theory atoms, elements, and terms of a program.
///
/// **See:** [`Control::theory_atoms()`](struct.Control.html#method.theory_atoms)
#[derive(Debug, Copy, Clone)]
pub struct TheoryAtoms(clingo_theory_atoms_t);
impl TheoryAtoms {
    /// Get the total number of theory atoms.
    pub fn size(&self) -> Result<usize, WrapperError> {
        let mut size = 0 as usize;
        if unsafe { clingo_theory_atoms_size(&self.0, &mut size) } {
            Ok(size)
        } else {
            Err(WrapperError {
                msg: "clingo_theory_atoms_size() failed.",
            })
        }
    }

    ///  Returns an iterator over the theory atoms.
    pub fn iter(&self) -> TheoryAtomsIterator {
        TheoryAtomsIterator {
            count: 0,
            atoms: &self,
            atoms_size: self.size().unwrap(),
        }
    }

    /// Get the type of the given theory term.
    ///
    /// # Arguments
    ///
    /// * `term` - id of the term
    pub fn term_type(&self, Id(term): Id) -> Option<TheoryTermType> {
        let mut ttype = 0 as clingo_theory_term_type_t;
        if unsafe { clingo_theory_atoms_term_type(&self.0, term, &mut ttype) } {
            match ttype as u32 {
                clingo_theory_term_type_clingo_theory_term_type_tuple => {
                    Some(TheoryTermType::Tuple)
                }
                clingo_theory_term_type_clingo_theory_term_type_list => Some(TheoryTermType::List),
                clingo_theory_term_type_clingo_theory_term_type_set => Some(TheoryTermType::Set),
                clingo_theory_term_type_clingo_theory_term_type_function => {
                    Some(TheoryTermType::Function)
                }
                clingo_theory_term_type_clingo_theory_term_type_number => {
                    Some(TheoryTermType::Number)
                }
                clingo_theory_term_type_clingo_theory_term_type_symbol => {
                    Some(TheoryTermType::Symbol)
                }
                x => panic!("Failed to match clingo_theory_term_type: {}.", x),
            }
        } else {
            None
        }
    }

    /// Get the number of the given numeric theory term.
    ///
    /// # Pre-condition
    ///
    /// The term must be of type [`TermType::Number`](enum.TermType.html#variant.Number).
    ///
    /// # Arguments
    ///
    /// * `term` - id of the term
    pub fn term_number(&self, Id(term): Id) -> Option<i32> {
        let mut number = 0;
        if unsafe { clingo_theory_atoms_term_number(&self.0, term, &mut number) } {
            Some(number)
        } else {
            None
        }
    }

    /// Get the name of the given constant or function theory term.
    ///
    /// # Pre-condition
    ///
    /// The term must be of type [`TermType::Function`](enum.TermType.html#variant.Function) or
    /// [`TermType::Symbol`](enum.TermType.html#variant.Symbol).
    ///
    /// # Arguments
    ///
    /// * `term` id of the term
    pub fn term_name<'a>(&self, Id(term): Id) -> Result<&'a str, Error> {
        let mut char_ptr = std::ptr::null() as *const c_char;
        if unsafe { clingo_theory_atoms_term_name(&self.0, term, &mut char_ptr) } {
            let c_str = unsafe { CStr::from_ptr(char_ptr) };
            Ok(c_str.to_str()?)
        } else {
            Err(WrapperError {
                msg: "clingo_theory_atoms_term_name() failed.",
            })?
        }
    }

    /// Get the arguments of the given function theory term.
    ///
    /// # Pre-condition
    ///
    /// The term must be of type [`TermType::Function`](enum.TermType.html#variant.Function).
    ///
    /// # Arguments
    ///
    /// * `term` - id of the term
    pub fn term_arguments(&self, Id(term): Id) -> Option<Vec<Id>> {
        let mut size = 0;
        let mut c_ptr = unsafe { mem::uninitialized() };
        if unsafe { clingo_theory_atoms_term_arguments(&self.0, term, &mut c_ptr, &mut size) } {
            let arguments_ref = unsafe { std::slice::from_raw_parts(c_ptr as *const Id, size) };
            Some(arguments_ref.to_owned())
        } else {
            None
        }
    }

    //NODO: pub fn clingo_theory_atoms_term_to_string_size()

    /// Get the string representation of the given theory term.
    ///
    /// # Arguments
    ///
    /// * `term` - id of the term
    ///
    /// # Errors
    ///
    /// - [`ErrorType::Runtime`](enum.ErrorType.html#variant.Runtime) if the size is too small
    /// - [`ErrorType::BadAlloc`](enum.ErrorType.html#variant.BadAlloc)
    pub fn term_to_string(&self, Id(term): Id) -> Result<&str, Error> {
        let mut size = 0;
        if unsafe { clingo_theory_atoms_term_to_string_size(&self.0, term, &mut size) } {
            let mut c_ptr = unsafe { mem::uninitialized() };
            if unsafe { clingo_theory_atoms_term_to_string(&self.0, term, &mut c_ptr, size) } {
                let cstr = unsafe { CStr::from_ptr(&c_ptr) };
                Ok(cstr.to_str()?)
            } else {
                Err(error())?
            }
        } else {
            Err(error())?
        }
    }

    /// Get the tuple (array of theory terms) of the given theory element.
    ///
    /// # Arguments
    ///
    /// * `element` - id of the element
    pub fn element_tuple(&self, Id(element): Id) -> Option<Vec<Id>> {
        let mut size = 0;
        let mut tuple_ptr = unsafe { mem::uninitialized() };
        if unsafe { clingo_theory_atoms_element_tuple(&self.0, element, &mut tuple_ptr, &mut size) }
        {
            let tuple_ref = unsafe { std::slice::from_raw_parts(tuple_ptr as *const Id, size) };
            Some(tuple_ref.to_owned())
        } else {
            None
        }
    }

    /// Get the condition (array of aspif literals) of the given theory element.
    ///
    /// # Arguments
    ///
    /// * `element` - id of the element
    pub fn element_condition(&self, Id(element): Id) -> Option<Vec<Literal>> {
        let mut size = 0;
        let mut condition_ptr = unsafe { mem::uninitialized() };
        if unsafe {
            clingo_theory_atoms_element_condition(&self.0, element, &mut condition_ptr, &mut size)
        } {
            let condition_ref =
                unsafe { std::slice::from_raw_parts(condition_ptr as *const Literal, size) };
            Some(condition_ref.to_owned())
        } else {
            None
        }
    }

    /// Get the id of the condition of the given theory element.
    ///
    /// **Note:**
    /// This id can be mapped to a solver literal using [`PropagateInit::solver_literal()`](struct.PropagateInit.html#method.solver_literal).
    /// This id is not (necessarily) an aspif literal;
    /// to get aspif literals use [`TheoryAtoms::element_condition()`](struct.TheoryAtoms.html#method.element_condition).
    ///
    /// # Arguments
    ///
    /// * `element` - id of the element
    pub fn element_condition_id(&self, Id(element): Id) -> Option<Literal> {
        let mut condition = unsafe { mem::uninitialized() };
        if unsafe { clingo_theory_atoms_element_condition_id(&self.0, element, &mut condition) } {
            Some(Literal(condition))
        } else {
            None
        }
    }

    //NODO: pub fn clingo_theory_atoms_element_to_string_size()

    /// Get the string representation of the given theory element.
    ///
    /// # Arguments
    ///
    /// * `element` - id of the element
    ///
    /// # Errors
    ///
    /// - [`ErrorType::Runtime`](enum.ErrorType.html#variant.Runtime) if the size is too small
    /// - [`ErrorType::BadAlloc`](enum.ErrorType.html#variant.BadAlloc)
    pub fn element_to_string(&self, Id(element): Id) -> Result<&str, Error> {
        let mut size = 0;
        if unsafe { clingo_theory_atoms_element_to_string_size(&self.0, element, &mut size) } {
            let mut c_ptr = unsafe { mem::uninitialized() };
            if unsafe { clingo_theory_atoms_element_to_string(&self.0, element, &mut c_ptr, size) }
            {
                let cstr = unsafe { CStr::from_ptr(&c_ptr) };
                Ok(cstr.to_str()?)
            } else {
                Err(error())?
            }
        } else {
            Err(error())?
        }
    }

    /// Get the theory term associated with the theory atom.
    ///
    /// # Arguments
    ///
    /// * `atom` id of the atom
    pub fn atom_term(&self, Id(atom): Id) -> Option<Id> {
        let mut term = 0 as clingo_id_t;
        if unsafe { clingo_theory_atoms_atom_term(&self.0, atom, &mut term) } {
            Some(Id(term))
        } else {
            None
        }
    }

    /// Get the theory elements associated with the theory atom.
    ///
    /// # Arguments
    ///
    /// * `atom` - id of the atom
    pub fn atom_elements(&self, Id(atom): Id) -> Option<Vec<Id>> {
        let mut size = 0;
        let mut elements_ptr = unsafe { mem::uninitialized() };
        if unsafe { clingo_theory_atoms_atom_elements(&self.0, atom, &mut elements_ptr, &mut size) }
        {
            let elements = unsafe { std::slice::from_raw_parts(elements_ptr as *const Id, size) };
            Some(elements.to_owned())
        } else {
            None
        }
    }

    /// Whether the theory atom has a guard.
    ///
    /// # Arguments
    ///
    /// * `atom` id of the atom
    pub fn atom_has_guard(&self, Id(atom): Id) -> Option<bool> {
        let mut has_guard = false;
        if unsafe { clingo_theory_atoms_atom_has_guard(&self.0, atom, &mut has_guard) } {
            Some(has_guard)
        } else {
            None
        }
    }

    /// Get the guard consisting of a theory operator and a theory term of the given theory atom.
    ///
    /// # Arguments
    ///
    /// * `atom` - id of the atom
    pub fn atom_guard(&self, Id(atom): Id) -> Result<(&str, Id), Error> {
        let mut c_ptr = unsafe { mem::uninitialized() };
        let mut term = 0 as clingo_id_t;
        if unsafe { clingo_theory_atoms_atom_guard(&self.0, atom, &mut c_ptr, &mut term) } {
            let cstr = unsafe { CStr::from_ptr(c_ptr) };
            Ok((cstr.to_str()?, Id(term)))
        } else {
            Err(WrapperError {
                msg: "clingo_theory_atoms_atom_guard() failed.",
            })?
        }
    }

    /// Get the aspif literal associated with the given theory atom.
    ///
    /// # Arguments
    ///
    /// * `atom` id of the atom
    pub fn atom_literal(&self, Id(atom): Id) -> Option<Literal> {
        let mut literal = 0 as clingo_literal_t;
        if unsafe { clingo_theory_atoms_atom_literal(&self.0, atom, &mut literal) } {
            Some(Literal(literal))
        } else {
            None
        }
    }

    //NODO: pub fn clingo_theory_atoms_atom_to_string_size()

    /// Get the string representation of the given theory atom.
    ///
    /// # Arguments
    ///
    /// * `atom` - id of the element
    ///
    /// # Errors
    ///
    /// - [`ErrorType::Runtime`](enum.ErrorType.html#variant.Runtime) if the size is too small
    /// - [`ErrorType::BadAlloc`](enum.ErrorType.html#variant.BadAlloc)
    pub fn atom_to_string(&self, Id(atom): Id) -> Result<&str, Error> {
        let mut size = 0;
        if unsafe { clingo_theory_atoms_atom_to_string_size(&self.0, atom, &mut size) } {
            let mut c_ptr = unsafe { mem::uninitialized() };
            if unsafe { clingo_theory_atoms_atom_to_string(&self.0, atom, &mut c_ptr, size) } {
                let cstr = unsafe { CStr::from_ptr(&c_ptr) };
                Ok(cstr.to_str()?)
            } else {
                Err(error())?
            }
        } else {
            Err(error())?
        }
    }
}

/// Iterator over theory atoms.
pub struct TheoryAtomsIterator<'a> {
    count: usize,
    atoms: &'a TheoryAtoms,
    atoms_size: usize,
}
impl<'a> Iterator for TheoryAtomsIterator<'a> {
    type Item = Id;

    fn next(&mut self) -> Option<Id> {
        // check to see if we've finished counting or not.
        if self.count < self.atoms_size {
            let ret = Id(self.count as clingo_id_t);
            // increment our count.
            self.count += 1;
            Some(ret)
        } else {
            None
        }
    }
}

/// Represents a model.
#[derive(Debug, Copy, Clone)]
pub struct Model(clingo_model_t);
impl Model {
    /// Get the type of the model.
    pub fn model_type(&self) -> Option<ModelType> {
        let mut mtype = 0 as clingo_model_type_t;
        if unsafe { clingo_model_type(&self.0, &mut mtype) } {
            match mtype as u32 {
                clingo_model_type_clingo_model_type_stable_model => Some(ModelType::StableModel),
                clingo_model_type_clingo_model_type_brave_consequences => {
                    Some(ModelType::BraveConsequences)
                }
                clingo_model_type_clingo_model_type_cautious_consequences => {
                    Some(ModelType::CautiousConsequences)
                }
                x => panic!("Failed to match clingo_model_type: {}.", x),
            }
        } else {
            None
        }
    }

    /// Get the running number of the model.
    pub fn number(&self) -> Option<u64> {
        let mut number = 0;
        if unsafe { clingo_model_number(&self.0, &mut number) } {
            Some(number)
        } else {
            None
        }
    }

    //NODO: pub fn clingo_model_symbols_size()

    /// Get the symbols of the selected types in the model.
    ///
    /// **Note:** CSP assignments are represented using functions with name "$"
    /// where the first argument is the name of the CSP variable and the second one its
    /// value.
    ///
    /// # Arguments
    ///
    /// * `show` - which symbols to select
    ///
    /// # Errors
    ///
    /// - [`ErrorType::BadAlloc`](enum.ErrorType.html#variant.BadAlloc)
    /// - [`ErrorType::Runtime`](enum.ErrorType.html#variant.Runtime) if the size is too small
    pub fn symbols(&self, show: &ShowType) -> Result<Vec<Symbol>, ClingoError> {
        let mut size: usize = 0;
        if unsafe { clingo_model_symbols_size(&self.0, show.bits(), &mut size) } {
            let symbols = Vec::<Symbol>::with_capacity(size);
            let symbols_ptr = symbols.as_ptr();
            if unsafe {
                clingo_model_symbols(
                    &self.0,
                    show.bits(),
                    symbols_ptr as *mut clingo_symbol_t,
                    size,
                )
            } {
                let symbols_ref =
                    unsafe { std::slice::from_raw_parts(symbols_ptr as *const Symbol, size) };
                Ok(symbols_ref.to_owned())
            } else {
                Err(error())
            }
        } else {
            Err(error())
        }
    }

    /// Constant time lookup to test whether an atom is in a model.
    ///
    /// # Arguments
    ///
    /// * `atom` - the atom to lookup
    pub fn contains(&self, Symbol(atom): Symbol) -> Option<bool> {
        let mut contained = false;
        if unsafe { clingo_model_contains(&self.0, atom, &mut contained) } {
            Some(contained)
        } else {
            None
        }
    }

    /// Check whether a program literal is true in a model.
    ///
    /// # Arguments
    ///
    /// * `literal` - the literal to lookup
    pub fn is_true(&self, literal: Literal) -> Option<bool> {
        let mut is_true = false;
        if unsafe { clingo_model_is_true(&self.0, literal.0, &mut is_true) } {
            Some(is_true)
        } else {
            None
        }
    }

    //NODO: pub fn clingo_model_cost_size(model: *mut Model, size: *mut size_t) -> u8;

    /// Get the cost vector of a model.
    ///
    /// # Errors
    ///
    /// - [`ErrorType::BadAlloc`](enum.ErrorType.html#variant.BadAlloc)
    /// - [`ErrorType::Runtime`](enum.ErrorType.html#variant.Runtime) if the size is too small
    ///
    /// **See:** [`Model::optimality_proven()`](struct.Model.html#method.optimality_proven)
    pub fn cost(&self) -> Result<Vec<i64>, ClingoError> {
        let mut size: usize = 0;
        if unsafe { clingo_model_cost_size(&self.0, &mut size) } {
            let cost = Vec::<i64>::with_capacity(size);
            let cost_ptr = cost.as_ptr();
            if unsafe { clingo_model_cost(&self.0, cost_ptr as *mut i64, size) } {
                let cost_ref = unsafe { std::slice::from_raw_parts(cost_ptr as *const i64, size) };
                Ok(cost_ref.to_owned())
            } else {
                Err(error())
            }
        } else {
            Err(error())
        }
    }

    /// Whether the optimality of a model has been proven.
    ///
    /// **See:** [`Model::cost()`](struct.Model.html#method.cost)
    pub fn optimality_proven(&self) -> Option<bool> {
        let mut proven = false;
        if unsafe { clingo_model_optimality_proven(&self.0, &mut proven) } {
            Some(proven)
        } else {
            None
        }
    }

    /// Get the id of the solver thread that found the model.
    pub fn thread_id(&self) -> Option<Id> {
        let mut id = 0 as clingo_id_t;
        if unsafe { clingo_model_thread_id(&self.0, &mut id) } {
            Some(Id(id))
        } else {
            None
        }
    }

    /// Get the associated solve control object of a model.
    ///
    /// This object allows for adding clauses during model enumeration.
    pub fn context(&mut self) -> Option<&mut SolveControl> {
        let mut control = unsafe { mem::uninitialized() };
        if unsafe { clingo_model_context(&mut self.0, &mut control) } {
            unsafe { (control as *mut SolveControl).as_mut() }
        } else {
            None
        }
    }
}

/// Object to add clauses during search.
#[derive(Debug, Copy, Clone)]
pub struct SolveControl(clingo_solve_control_t);
impl SolveControl {
    /// Add a clause that applies to the current solving step during model
    /// enumeration.
    ///
    /// **Note:** The [`Propagator`](trait.Propagator.html) trait provides a more sophisticated
    /// interface to add clauses - even on partial assignments.
    ///
    /// # Arguments
    ///
    /// * `clause` - array of literals representing the clause
    ///
    /// # Errors
    ///
    /// - [`ErrorType::BadAlloc`](enum.ErrorType.html#variant.BadAlloc)
    /// - [`ErrorType::Runtime`](enum.ErrorType.html#variant.Runtime) if adding the clause fails
    pub fn add_clause(&mut self, clause: &[Literal]) -> Result<(), ClingoError> {
        if unsafe {
            clingo_solve_control_add_clause(
                &mut self.0,
                clause.as_ptr() as *const clingo_literal_t,
                clause.len(),
            )
        } {
            Ok(())
        } else {
            Err(error())
        }
    }

    /// Get an object to inspect the symbolic atoms.
    pub fn symbolic_atoms(&mut self) -> Option<&SymbolicAtoms> {
        let mut atoms = std::ptr::null_mut() as *const clingo_symbolic_atoms_t;
        if unsafe { clingo_solve_control_symbolic_atoms(&mut self.0, &mut atoms) } {
            unsafe { (atoms as *const SymbolicAtoms).as_ref() }
        } else {
            None
        }
    }
}

/// Represents a (partial) assignment of a particular solver.
///
/// An assignment assigns truth values to a set of literals.
/// A literal is assigned to either [true or false, or is unassigned](struct.Assignment.html#method.truth_value).
/// Furthermore, each assigned literal is associated with a [decision level](struct.Assignment.html#method.level).
/// There is exactly one [decision literal](struct.Assignment.html#method.decision) for each decision level greater than zero.
/// Assignments to all other literals on the same level are consequences implied by the current and possibly previous decisions.
/// Assignments on level zero are immediate consequences of the current program.
/// Decision levels are consecutive numbers starting with zero up to and including the [current decision level](struct.Assignment.html#method.decision_level).
#[derive(Debug, Copy, Clone)]
pub struct Assignment(clingo_assignment_t);
impl Assignment {
    /// Get the current decision level.
    pub fn decision_level(&self) -> u32 {
        unsafe { clingo_assignment_decision_level(&self.0) }
    }

    /// Check whether the given assignment is conflicting.
    pub fn has_conflict(&self) -> bool {
        unsafe { clingo_assignment_has_conflict(&self.0) }
    }

    /// Check whether the given literal is part of a (partial) assignment.
    ///
    /// # Arguments
    ///
    /// * `literal` - the literal
    pub fn has_literal(&self, literal: Literal) -> bool {
        unsafe { clingo_assignment_has_literal(&self.0, literal.0) }
    }

    /// Determine the decision level of a given literal.
    ///
    /// # Arguments
    ///
    /// * `literal` - the literal
    ///
    /// **Returns** the decision level of the given literal
    pub fn level(&self, literal: Literal) -> Option<u32> {
        let mut level = 0;
        if unsafe { clingo_assignment_level(&self.0, literal.0, &mut level) } {
            Some(level)
        } else {
            None
        }
    }

    /// Determine the decision literal given a decision level.
    ///
    /// # Arguments
    ///
    /// * `level` - the level
    ///
    /// **Returns** the decision literal for the given decision level
    pub fn decision(&self, level: u32) -> Option<Literal> {
        let mut lit = 0 as clingo_literal_t;
        if unsafe { clingo_assignment_decision(&self.0, level, &mut lit) } {
            Some(Literal(lit))
        } else {
            None
        }
    }

    /// Check if a literal has a fixed truth value.
    ///
    /// # Arguments
    ///
    /// * `literal` - the literal
    ///
    /// **Returns** whether the literal is fixed
    pub fn is_fixed(&self, literal: Literal) -> Option<bool> {
        let mut is_fixed = false;
        if unsafe { clingo_assignment_is_fixed(&self.0, literal.0, &mut is_fixed) } {
            Some(is_fixed)
        } else {
            None
        }
    }

    /// Check if a literal is true.
    ///
    /// # Arguments
    ///
    /// * `literal` - the literal
    /// **Returns** whether the literal is true (see [`Assignment::truth_value()`](struct.Assignment.html#method.truth_value))
    pub fn is_true(&self, literal: Literal) -> Option<bool> {
        let mut is_true = false;
        if unsafe { clingo_assignment_is_true(&self.0, literal.0, &mut is_true) } {
            Some(is_true)
        } else {
            None
        }
    }

    /// Check if a literal has a fixed truth value.
    ///
    /// # Arguments
    /// * `literal` - the literal
    ///
    /// **Returns** whether the literal is false (see [`Assignment::truth_value()`](struct.Assignment.html#method.truth_value))
    pub fn is_false(&self, literal: Literal) -> Option<bool> {
        let mut is_false = false;
        if unsafe { clingo_assignment_is_false(&self.0, literal.0, &mut is_false) } {
            Some(is_false)
        } else {
            None
        }
    }

    /// Determine the truth value of a given literal.
    ///
    /// # Arguments
    ///
    /// * `literal` - the literal
    /// * `value` - the resulting truth value
    ///
    /// **Returns** whether the call was successful
    pub fn truth_value(&self, literal: Literal) -> Option<TruthValue> {
        let mut value = 0;
        if unsafe { clingo_assignment_truth_value(&self.0, literal.0, &mut value) } {
            match value as u32 {
                clingo_truth_value_clingo_truth_value_false => Some(TruthValue::False),
                clingo_truth_value_clingo_truth_value_true => Some(TruthValue::True),
                clingo_truth_value_clingo_truth_value_free => Some(TruthValue::Free),
                x => panic!("Failed to match clingo_truth_value: {}.", x),
            }
        } else {
            None
        }
    }

    /// The number of assigned literals in the assignment.
    pub fn size(&self) -> usize {
        unsafe { clingo_assignment_size(&self.0) }
    }

    /// The maximum size of the assignment (if all literals are assigned).
    pub fn max_size(&self) -> usize {
        unsafe { clingo_assignment_max_size(&self.0) }
    }

    /// Check if the assignmen is total, i.e. - size == max_size.
    pub fn is_total(&self) -> bool {
        unsafe { clingo_assignment_is_total(&self.0) }
    }
}

/// This object can be used to add clauses and propagate literals while solving.
#[derive(Debug, Copy, Clone)]
pub struct PropagateControl(clingo_propagate_control_t);
impl PropagateControl {
    /// Get the id of the underlying solver thread.
    ///
    /// Thread ids are consecutive numbers starting with zero.
    pub fn thread_id(&mut self) -> u32 {
        unsafe { clingo_propagate_control_thread_id(&mut self.0) }
    }

    /// Get the assignment associated with the underlying solver.
    pub fn assignment(&self) -> Result<&Assignment, WrapperError> {
        match unsafe {
            (clingo_propagate_control_assignment(&self.0) as *const Assignment).as_ref()
        } {
            Some(stm) => Ok(stm),
            None => Err(WrapperError {
                msg: "tried casting a null pointer to &Assignment.",
            }),
        }
    }

    /// Get the assignment associated with the underlying solver.
    pub fn assignment_mut(&mut self) -> Result<&mut Assignment, WrapperError> {
        match unsafe {
            (clingo_propagate_control_assignment(&mut self.0) as *mut Assignment).as_mut()
        } {
            Some(stm) => Ok(stm),
            None => Err(WrapperError {
                msg: "tried casting a null pointer to &mut Assignment.",
            }),
        }
    }

    /// Adds a new volatile literal to the underlying solver thread.
    ///
    /// **Attention:** The literal is only valid within the current solving step and solver thread.
    /// All volatile literals and clauses involving a volatile literal are deleted after the current search.
    ///
    /// # Arguments
    ///
    /// * `result` - the (positive) solver literal
    ///
    /// **Errors:**
    ///
    /// - [`ErrorType::BadAlloc`](enum.ErrorType.html#variant.BadAlloc)
    /// - [`ErrorType::Logic`](enum.ErrorType.html#variant.Logic) if the assignment is conflicting
    pub fn add_literal(&mut self, result: &mut Literal) -> Result<(), ClingoError> {
        if unsafe { clingo_propagate_control_add_literal(&mut self.0, &mut result.0) } {
            Ok(())
        } else {
            Err(error())
        }
    }

    /// Add a watch for the solver literal in the given phase.
    ///
    /// **Note:** Unlike [`PropagateInit::add_watch()`](struct.PropagateInit.html#method.add_watch) this does not add a watch to all solver threads but just the current one.
    ///
    /// # Arguments
    ///
    /// * `literal` - the literal to watch
    ///
    /// **Errors:**
    ///
    /// - [`ErrorType::BadAlloc`](enum.ErrorType.html#variant.BadAlloc)
    /// - [`ErrorType::Logic`](enum.ErrorType.html#variant.Logic) if the literal is invalid
    ///
    /// **See:** [`PropagateControl::remove_watch()`](struct.PropagateControl.html#method.remove_watch)
    pub fn add_watch(&mut self, literal: Literal) -> Result<(), ClingoError> {
        if unsafe { clingo_propagate_control_add_watch(&mut self.0, literal.0) } {
            Ok(())
        } else {
            Err(error())
        }
    }

    /// Check whether a literal is watched in the current solver thread.
    ///
    /// # Arguments
    ///
    /// * `literal` - the literal to check
    pub fn has_watch(&self, literal: Literal) -> bool {
        unsafe { clingo_propagate_control_has_watch(&self.0, literal.0) }
    }

    /// Removes the watch (if any) for the given solver literal.
    ///
    /// **Note:** Similar to [`PropagateInit::add_watch()`](struct.PropagateInit.html#method.add_watch) this just removes the watch in the current solver thread.
    ///
    /// # Arguments
    ///
    /// * `literal` - the literal to remove
    pub fn remove_watch(&mut self, literal: Literal) {
        unsafe { clingo_propagate_control_remove_watch(&mut self.0, literal.0) }
    }

    /// Add the given clause to the solver.
    ///
    /// This method sets its result to false if the current propagation must be stopped for the solver to backtrack.
    ///
    /// **Attention:** No further calls on the control object or functions on the assignment should be called when the result of this method is false.
    ///
    /// # Arguments
    ///
    /// * `clause` - the clause to add
    /// * `ctype` - the clause type determining its lifetime
    ///
    /// # Errors
    ///
    /// - [`ErrorType::BadAlloc`](enum.ErrorType.html#variant.BadAlloc)
    pub fn add_clause(
        &mut self,
        clause: &[Literal],
        ctype: ClauseType,
    ) -> Result<bool, ClingoError> {
        let mut result = false;
        if unsafe {
            clingo_propagate_control_add_clause(
                &mut self.0,
                clause.as_ptr() as *const clingo_literal_t,
                clause.len(),
                ctype as clingo_clause_type_t,
                &mut result,
            )
        } {
            Ok(result)
        } else {
            Err(error())
        }
    }

    /// Propagate implied literals (resulting from added clauses).
    ///
    /// This method sets its result to false if the current propagation must be stopped for the
    /// solver to backtrack.
    ///
    /// **Attention:** No further calls on the control object or functions on the assignment should
    /// be called when the result of this method is false.
    ///
    /// **Returns** result indicating whether propagation has to be stopped
    ///
    /// # Errors
    ///
    /// - [`ErrorType::BadAlloc`](enum.ErrorType.html#variant.BadAlloc)
    pub fn propagate(&mut self) -> Result<bool, ClingoError> {
        let mut result = false;
        if unsafe { clingo_propagate_control_propagate(&mut self.0, &mut result) } {
            Ok(result)
        } else {
            Err(error())
        }
    }
}

/// Object to initialize a user-defined propagator before each solving step.
///
/// Each [symbolic](struct.SymbolicAtoms.html) or [theory atom](struct.TheoryAtoms.html) is uniquely associated with an aspif atom in form of a positive integer ([`Literal`](struct.Literal.html)).
/// Aspif literals additionally are signed to represent default negation.
/// Furthermore, there are non-zero integer solver literals (also represented using [`Literal`](struct.Literal.html).
/// There is a surjective mapping from program atoms to solver literals.
///
/// All methods called during propagation use solver literals whereas [`SymbolicAtoms::literal()`](struct.SymbolicAtoms.html#method.literal) and [`TheoryAtoms::atom_literal()`](struct.TheoryAtoms.html#method.atom_literal) return program literals.
/// The function [`PropagateInit::solver_literal()`](struct.PropagateInit.html#method.solver_literal) can be used to map program literals or [condition ids](struct.TheoryAtoms.html#method.element_condition_id) to solver literals.
#[derive(Debug, Copy, Clone)]
pub struct PropagateInit(clingo_propagate_init_t);
impl PropagateInit {
    /// Map the given program literal or condition id to its solver literal.
    ///
    /// # Arguments
    ///
    /// * `aspif_literal` - the aspif literal to map
    ///
    /// **Returns** the corresponding solver literal
    pub fn solver_literal(&self, Literal(aspif_literal): Literal) -> Option<Literal> {
        let mut solver_literal = 0 as clingo_literal_t;
        if unsafe {
            clingo_propagate_init_solver_literal(&self.0, aspif_literal, &mut solver_literal)
        } {
            Some(Literal(solver_literal))
        } else {
            None
        }
    }

    /// Add a watch for the solver literal in the given phase.
    ///
    /// # Arguments
    ///
    /// * `solver_literal` - the solver literal
    pub fn add_watch(&mut self, Literal(solver_literal): Literal) -> Option<()> {
        if unsafe { clingo_propagate_init_add_watch(&mut self.0, solver_literal) } {
            Some(())
        } else {
            None
        }
    }

    /// Get an object to inspect the symbolic atoms.
    pub fn symbolic_atoms(&self) -> Option<&SymbolicAtoms> {
        let mut atoms_ptr = std::ptr::null() as *const clingo_symbolic_atoms_t;
        if unsafe { clingo_propagate_init_symbolic_atoms(&self.0, &mut atoms_ptr) } {
            unsafe { (atoms_ptr as *const SymbolicAtoms).as_ref() }
        } else {
            None
        }
    }

    /// Get an object to inspect the theory atoms.
    pub fn theory_atoms(&self) -> Option<&TheoryAtoms> {
        let mut atoms_ptr = std::ptr::null() as *const clingo_theory_atoms_t;
        if unsafe { clingo_propagate_init_theory_atoms(&self.0, &mut atoms_ptr) } {
            unsafe { (atoms_ptr as *const TheoryAtoms).as_ref() }
        } else {
            None
        }
    }

    /// Get the number of threads used in subsequent solving.
    ///
    /// **See:** [`PropagateControl::thread_id()`](struct.PropagateControl.html#method.thread_id)
    pub fn number_of_threads(&self) -> usize {
        (unsafe { clingo_propagate_init_number_of_threads(&self.0) } as usize)
    }

    /// Configure when to call the check method of the propagator.
    ///
    /// # Arguments
    ///
    /// * `mode` - bitmask when to call the propagator
    ///
    /// **See:** [`Propagator::check()`](trait.Propagator.html#method.check)
    pub fn set_check_mode(&mut self, mode: PropagatorCheckMode) {
        unsafe {
            clingo_propagate_init_set_check_mode(
                &mut self.0,
                mode as clingo_propagator_check_mode_t,
            )
        }
    }

    /// Get the current check mode of the propagator.
    ///
    /// **Returns**  bitmask when to call the propagator
    ///
    /// **See:** [`PropagateInit::set_check_mode()`](struct.PropagateInit.html#method.set_check_mode)
    pub fn get_check_mode(&self) -> PropagatorCheckMode {
        match unsafe { clingo_propagate_init_get_check_mode(&self.0) } as u32 {
            clingo_propagator_check_mode_clingo_propagator_check_mode_fixpoint => {
                PropagatorCheckMode::Fixpoint
            }
            clingo_propagator_check_mode_clingo_propagator_check_mode_total => {
                PropagatorCheckMode::Total
            }
            clingo_propagator_check_mode_clingo_propagator_check_mode_none => {
                PropagatorCheckMode::None
            }
            x => panic!("Failed to match clingo_propagator_check_mode: {}.", x),
        }
    }
}

/// Search handle to a solve call.
#[derive(Debug)]
pub struct SolveHandle<'a> {
    theref: &'a mut clingo_solve_handle_t,
}
impl<'a> SolveHandle<'a> {
    /// Get the next solve result.
    ///
    /// Blocks until the result is ready.
    /// When yielding partial solve results can be obtained, i.e.,
    /// when a model is ready, the result will be satisfiable but neither the search exhausted nor the optimality proven.
    ///
    /// # Errors
    ///
    /// - [`ErrorType::BadAlloc`](enum.ErrorType.html#variant.BadAlloc)
    /// - [`ErrorType::Runtime`](enum.ErrorType.html#variant.Runtime) if solving fails
    pub fn get(&mut self) -> Result<SolveResult, ClingoError> {
        let mut result = 0;
        if unsafe { clingo_solve_handle_get(self.theref, &mut result) } {
            if let Some(res) = SolveResult::from_bits(result) {
                Ok(res)
            } else {
                panic!("Unknown bitflag in clingo_solve_result: {}.", result);
            }
        } else {
            Err(error())
        }
    }

    /// Wait for the specified amount of time to check if the next result is ready.
    ///
    /// If the time is set to zero, this function can be used to poll if the search is still active.
    /// If the time is negative, the function blocks until the search is finished.
    ///
    /// # Arguments
    ///
    /// * `timeout` - the maximum time to wait
    ///
    /// **Returns:**  whether the search has finished
    pub fn wait(&mut self, timeout: f64) -> bool {
        let mut result = false;
        unsafe { clingo_solve_handle_wait(self.theref, timeout, &mut result) };
        result
    }

    /// Get the next model (or zero if there are no more models).
    /// (it is NULL if there are no more models)
    ///
    /// # Errors
    ///
    /// - [`ErrorType::BadAlloc`](enum.ErrorType.html#variant.BadAlloc)
    /// - [`ErrorType::Runtime`](enum.ErrorType.html#variant.Runtime) if solving fails
    pub fn model(&self) -> Result<&Model, Error> {
        let mut model = std::ptr::null_mut() as *mut clingo_model_t;
        if unsafe { clingo_solve_handle_model(self.theref, &mut model) } {
            match unsafe { (model as *const Model).as_ref() } {
                Some(x) => Ok(x),
                None => Err(WrapperError {
                    msg: "tried casting a null pointer to &Model.",
                })?,
            }
        } else {
            Err(error())?
        }
    }

    /// Get the next model (or zero if there are no more models).
    /// (it is NULL if there are no more models)
    ///
    /// # Errors
    ///
    /// - [`ErrorType::BadAlloc`](enum.ErrorType.html#variant.BadAlloc)
    /// - [`ErrorType::Runtime`](enum.ErrorType.html#variant.Runtime) if solving fails
    pub fn model_mut(&mut self) -> Result<&mut Model, Error> {
        let mut model = std::ptr::null_mut() as *mut clingo_model_t;
        if unsafe { clingo_solve_handle_model(self.theref, &mut model) } {
            match unsafe { (model as *mut Model).as_mut() } {
                Some(x) => Ok(x),
                None => Err(WrapperError {
                    msg: "tried casting a null pointer to &mut Model.",
                })?,
            }
        } else {
            Err(error())?
        }
    }
    /// Discards the last model and starts the search for the next one.
    ///
    /// If the search has been started asynchronously, this function continues the search in the
    /// background.
    ///
    /// **Note:** This function does not block.
    ///
    /// # Errors
    ///
    /// - [`ErrorType::BadAlloc`](enum.ErrorType.html#variant.BadAlloc)
    /// - [`ErrorType::Runtime`](enum.ErrorType.html#variant.Runtime) if solving fails
    pub fn resume(&mut self) -> Result<(), ClingoError> {
        if unsafe { clingo_solve_handle_resume(self.theref) } {
            Ok(())
        } else {
            Err(error())
        }
    }

    /// Stop the running search and block until done.
    ///
    /// # Arguments
    ///
    /// * `handle` - the target
    ///
    /// # Errors
    ///
    /// - [`ErrorType::BadAlloc`](enum.ErrorType.html#variant.BadAlloc)
    /// - [`ErrorType::Runtime`](enum.ErrorType.html#variant.Runtime) if solving fails
    pub fn cancel(&mut self) -> Result<(), ClingoError> {
        if unsafe { clingo_solve_handle_cancel(self.theref) } {
            Ok(())
        } else {
            Err(error())
        }
    }

    /// Stops the running search and releases the handle.
    ///
    /// Blocks until the search is stopped (as if an implicit cancel was called before the handle is
    /// released).
    ///
    /// # Errors
    ///
    /// - [`ErrorType::BadAlloc`](enum.ErrorType.html#variant.BadAlloc)
    /// - [`ErrorType::Runtime`](enum.ErrorType.html#variant.Runtime) if solving fails
    pub fn close(self) -> Result<(), ClingoError> {
        if unsafe { clingo_solve_handle_close(self.theref) } {
            Ok(())
        } else {
            Err(error())
        }
    }
}

/// Internalize a string.
///
/// This functions takes a string as input and returns an equal unique string
/// that is (at the moment) not freed until the program is closed.  All strings
/// returned from clingo API functions are internalized and must not be freed.
///
/// # Arguments
///
/// * `string` - the string to internalize
/// * `result` - the internalized string
///
/// # Errors
///
/// - [`ErrorType::BadAlloc`](enum.ErrorType.html#variant.BadAlloc)
pub fn add_string(string: &str) -> Result<&'static str, Error> {
    let in_cstr = CString::new(string)?;
    let mut out_ptr = unsafe { mem::uninitialized() };
    if unsafe { clingo_add_string(in_cstr.as_ptr(), &mut out_ptr) } {
        let out_cstr = unsafe { CStr::from_ptr(out_ptr) };
        Ok(out_cstr.to_str()?)
    } else {
        Err(error())?
    }
}

/// Parse a term in string form.
///
/// The result of this function is a symbol. The input term can contain
/// unevaluated functions, which are evaluated during parsing.
///
/// # Arguments
///
/// * `string` - the string to parse
///
/// # Errors
///
/// - [`NulError`](https://doc.rust-lang.org/std/ffi/struct.NulError.html) - if `string` contains a nul byte
/// - [`ErrorType::BadAlloc`](enum.ErrorType.html#variant.BadAlloc)
/// - [`ErrorType::Runtime`](enum.ErrorType.html#variant.Runtime) if parsing fails
pub fn parse_term(string: &str) -> Result<Symbol, Error> {
    let c_str = CString::new(string)?;
    let mut symbol = 0 as clingo_symbol_t;
    if unsafe { clingo_parse_term(c_str.as_ptr(), None, std::ptr::null_mut(), 0, &mut symbol) } {
        Ok(Symbol(symbol))
    } else {
        Err(error())?
    }
}

/// Parse a term in string form.
///
/// The result of this function is a symbol. The input term can contain
/// unevaluated functions, which are evaluated during parsing.
///
/// # Arguments
///
/// * `string` - the string to parse
/// * `logger` -  logger to report warnings during parsing
/// * `message_limit` - maximum number of times to call the logger
///
/// # Errors
///
/// - [`NulError`](https://doc.rust-lang.org/std/ffi/struct.NulError.html) - if `string` contains a nul byte
/// - [`ErrorType::BadAlloc`](enum.ErrorType.html#variant.BadAlloc)
/// - [`ErrorType::Runtime`](enum.ErrorType.html#variant.Runtime) if parsing fails
pub fn parse_term_with_logger<L: Logger>(
    string: &str,
    logger: &mut L,
    message_limit: u32,
) -> Result<Symbol, Error> {
    let c_str = CString::new(string)?;
    let data = logger as *mut L;
    let mut symbol = 0 as clingo_symbol_t;
    if unsafe {
        clingo_parse_term(
            c_str.as_ptr(),
            Some(L::unsafe_logging_callback::<L> as LoggingCallback),
            data as *mut ::std::os::raw::c_void,
            message_limit,
            &mut symbol,
        )
    } {
        Ok(Symbol(symbol))
    } else {
        Err(error())?
    }
}

pub trait GroundProgramObserver {
    /// Called once in the beginning.
    ///
    /// If the incremental flag is true, there can be multiple calls to
    /// [`Control::solve()`](struct.Control.html#method.solve).
    ///
    /// # Arguments
    ///
    /// * `incremental` - whether the program is incremental
    ///
    /// **Returns** whether the call was successful
    fn init_program(&mut self, incremental: bool) -> bool;
    #[doc(hidden)]
    unsafe extern "C" fn unsafe_init_program<T: GroundProgramObserver>(
        incremental: bool,
        data: *mut ::std::os::raw::c_void,
    ) -> bool {
        if let Some(gpo) = (data as *mut T).as_mut() {
            gpo.init_program(incremental)
        } else {
            set_internal_error(
                ErrorType::Runtime,
                "unsafe_init_program tried casting a null pointer to &mut GroundProgramObserver.",
            );
            false
        }
    }

    /// Marks the beginning of a block of directives passed to the solver.
    ///
    /// **See:** [`end_step()`](trait.GroundProgramObserver.html#tymethod.end_step)
    ///
    /// **Returns** whether the call was successful
    fn begin_step(&mut self) -> bool;
    #[doc(hidden)]
    unsafe extern "C" fn unsafe_begin_step<T: GroundProgramObserver>(
        data: *mut ::std::os::raw::c_void,
    ) -> bool {
        if let Some(gpo) = (data as *mut T).as_mut() {
            gpo.begin_step()
        } else {
            set_internal_error(
                ErrorType::Runtime,
                "unsafe_begin_step tried casting a null pointer to &mut GroundProgramObserver.",
            );
            false
        }
    }

    /// Marks the end of a block of directives passed to the solver.
    ///
    /// This function is called before solving starts.
    ///
    /// **See:** [`begin_step()`](trait.GroundProgramObserver.html#tymethod.begin_step)
    ///
    /// **Returns** whether the call was successful
    fn end_step(&mut self) -> bool;
    #[doc(hidden)]
    unsafe extern "C" fn unsafe_end_step<T: GroundProgramObserver>(
        data: *mut ::std::os::raw::c_void,
    ) -> bool {
        if let Some(gpo) = (data as *mut T).as_mut() {
            gpo.end_step()
        } else {
            set_internal_error(
                ErrorType::Runtime,
                "unsafe_end_step tried casting a null pointer to &mut GroundProgramObserver.",
            );
            false
        }
    }

    /// Observe rules passed to the solver.
    ///
    /// # Arguments
    ///
    /// * `choice` - determines if the head is a choice or a disjunction
    /// * `head` - the head atoms
    /// * `body` - the body literals
    ///
    /// **Returns** whether the call was successful
    fn rule(&mut self, choice: bool, head: &[Atom], body: &[Literal]) -> bool;
    #[doc(hidden)]
    unsafe extern "C" fn unsafe_rule<T: GroundProgramObserver>(
        choice: bool,
        head: *const clingo_atom_t,
        head_size: usize,
        body: *const clingo_literal_t,
        body_size: usize,
        data: *mut ::std::os::raw::c_void,
    ) -> bool {
        assert!(!head.is_null());
        let head = std::slice::from_raw_parts(head as *const Atom, head_size);

        assert!(!body.is_null());
        let body = std::slice::from_raw_parts(body as *const Literal, body_size);

        if let Some(gpo) = (data as *mut T).as_mut() {
            gpo.rule(choice, head, body)
        } else {
            set_internal_error(
                ErrorType::Runtime,
                "unsafe_rule tried casting a null pointer to &mut GroundProgramObserver.",
            );
            false
        }
    }

    /// Observe weight rules passed to the solver.
    ///
    /// # Arguments
    ///
    /// * `choice` - determines if the head is a choice or a disjunction
    /// * `head` - the head atoms
    /// * `lower_bound` - the lower bound of the weight rule
    /// * `body` - the weighted body literals
    ///
    /// **Returns** whether the call was successful
    fn weight_rule(
        &mut self,
        choice: bool,
        head: &[Atom],
        lower_bound: i32,
        body: &[WeightedLiteral],
    ) -> bool;
    #[doc(hidden)]
    unsafe extern "C" fn unsafe_weight_rule<T: GroundProgramObserver>(
        choice: bool,
        head: *const clingo_atom_t,
        head_size: usize,
        lower_bound: clingo_weight_t,
        body: *const clingo_weighted_literal_t,
        body_size: usize,
        data: *mut ::std::os::raw::c_void,
    ) -> bool {
        assert!(!head.is_null());
        let head = std::slice::from_raw_parts(head as *const Atom, head_size);

        assert!(!body.is_null());
        let body = std::slice::from_raw_parts(body as *const WeightedLiteral, body_size);

        if let Some(gpo) = (data as *mut T).as_mut() {
            gpo.weight_rule(choice, head, lower_bound, body)
        } else {
            set_internal_error(
                ErrorType::Runtime,
                "unsafe_weight_rule tried casting a null pointer to &mut GroundProgramObserver.",
            );
            false
        }
    }

    /// Observe minimize constraints (or weak constraints) passed to the solver.
    ///
    /// # Arguments
    ///
    /// * `priority` - the priority of the constraint
    /// * `literals` - the weighted literals whose sum to minimize
    ///
    /// **Returns** whether the call was successful
    fn minimize(&mut self, priority: i32, literals: &[WeightedLiteral]) -> bool;
    #[doc(hidden)]
    unsafe extern "C" fn unsafe_minimize<T: GroundProgramObserver>(
        priority: clingo_weight_t,
        literals: *const clingo_weighted_literal_t,
        size: usize,
        data: *mut ::std::os::raw::c_void,
    ) -> bool {
        assert!(!literals.is_null());
        let literals = std::slice::from_raw_parts(literals as *const WeightedLiteral, size);

        if let Some(gpo) = (data as *mut T).as_mut() {
            gpo.minimize(priority, literals)
        } else {
            set_internal_error(
                ErrorType::Runtime,
                "unsafe_minimize tried casting a null pointer to &mut GroundProgramObserver.",
            );
            false
        }
    }

    /// Observe projection directives passed to the solver.
    ///
    /// # Arguments
    ///
    /// * `atoms` - the atoms to project on
    ///
    /// **Returns** whether the call was successful
    fn project(&mut self, atoms: &[Atom]) -> bool;
    #[doc(hidden)]
    unsafe extern "C" fn unsafe_project<T: GroundProgramObserver>(
        atoms: *const clingo_atom_t,
        size: usize,
        data: *mut ::std::os::raw::c_void,
    ) -> bool {
        assert!(!atoms.is_null());
        let atoms = std::slice::from_raw_parts(atoms as *const Atom, size);

        if let Some(gpo) = (data as *mut T).as_mut() {
            gpo.project(atoms)
        } else {
            set_internal_error(
                ErrorType::Runtime,
                "unsafe_project tried casting a null pointer to &mut GroundProgramObserver.",
            );
            false
        }
    }

    /// Observe shown atoms passed to the solver.
    ///
    /// **Note:** Facts do not have an associated aspif atom.
    /// The value of the atom is set to zero.
    ///
    /// # Arguments
    ///
    /// * `symbol` - the symbolic representation of the atom
    /// * `atom` - the aspif atom (0 for facts)
    ///
    /// **Returns** whether the call was successful
    fn output_atom(&mut self, symbol: Symbol, atom: Atom) -> bool;
    #[doc(hidden)]
    unsafe extern "C" fn unsafe_output_atom<T: GroundProgramObserver>(
        symbol: clingo_symbol_t,
        atom: clingo_atom_t,
        data: *mut ::std::os::raw::c_void,
    ) -> bool {
        if let Some(gpo) = (data as *mut T).as_mut() {
            gpo.output_atom(Symbol(symbol), Atom(atom))
        } else {
            set_internal_error(
                ErrorType::Runtime,
                "unsafe_output_atom tried casting a null pointer to &mut GroundProgramObserver.",
            );
            false
        }
    }

    /// Observe shown terms passed to the solver.
    ///
    /// # Arguments
    ///
    /// * `symbol` - the symbolic representation of the term
    /// * `condition` - the literals of the condition
    ///
    /// **Returns** whether the call was successful
    fn output_term(&mut self, symbol: Symbol, condition: &[Literal]) -> bool;
    #[doc(hidden)]
    unsafe extern "C" fn unsafe_output_term<T: GroundProgramObserver>(
        symbol: clingo_symbol_t,
        condition: *const clingo_literal_t,
        size: usize,
        data: *mut ::std::os::raw::c_void,
    ) -> bool {
        assert!(!condition.is_null());
        let condition = std::slice::from_raw_parts(condition as *const Literal, size);

        if let Some(gpo) = (data as *mut T).as_mut() {
            gpo.output_term(Symbol(symbol), condition)
        } else {
            set_internal_error(
                ErrorType::Runtime,
                "unsafe_output_term tried casting a null pointer to &mut GroundProgramObserver.",
            );
            false
        }
    }

    /// Observe shown csp variables passed to the solver.
    ///
    /// # Arguments
    ///
    /// * `symbol` - the symbolic representation of the variable
    /// * `value` - the value of the variable
    /// * `condition` - the literals of the condition
    ///
    /// **Returns** whether the call was successful
    fn output_csp(&mut self, symbol: Symbol, value: i32, condition: &[Literal]) -> bool;
    #[doc(hidden)]
    unsafe extern "C" fn unsafe_output_csp<T: GroundProgramObserver>(
        symbol: clingo_symbol_t,
        value: ::std::os::raw::c_int,
        condition: *const clingo_literal_t,
        size: usize,
        data: *mut ::std::os::raw::c_void,
    ) -> bool {
        assert!(!condition.is_null());
        let condition = std::slice::from_raw_parts(condition as *const Literal, size);

        if let Some(gpo) = (data as *mut T).as_mut() {
            gpo.output_csp(Symbol(symbol), value, condition)
        } else {
            set_internal_error(
                ErrorType::Runtime,
                "unsafe_output_csp tried casting a null pointer to &mut GroundProgramObserver.",
            );
            false
        }
    }

    /// Observe external statements passed to the solver.
    ///
    /// # Arguments
    ///
    /// * `atom` - the external atom
    /// * `type` - the type of the external statement
    ///
    /// **Returns** whether the call was successful
    fn external(&mut self, atom: Atom, type_: ExternalType) -> bool;
    #[doc(hidden)]
    unsafe extern "C" fn unsafe_external<T: GroundProgramObserver>(
        atom: clingo_atom_t,
        type_: clingo_external_type_t,
        data: *mut ::std::os::raw::c_void,
    ) -> bool {
        let type_ = match type_ as u32 {
            clingo_external_type_clingo_external_type_false => ExternalType::False,
            clingo_external_type_clingo_external_type_free => ExternalType::Free,
            clingo_external_type_clingo_external_type_release => ExternalType::Release,
            clingo_external_type_clingo_external_type_true => ExternalType::True,
            x => panic!("Failed to match clingo_external_type: {}.", x),
        };

        if let Some(gpo) = (data as *mut T).as_mut() {
            gpo.external(Atom(atom), type_)
        } else {
            set_internal_error(
                ErrorType::Runtime,
                "unsafe_external tried casting a null pointer to &mut GroundProgramObserver.",
            );
            false
        }
    }

    /// Observe assumption directives passed to the solver.
    ///
    /// # Arguments
    ///
    /// * `literals` - the literals to assume (positive literals are true and negative literals
    /// false for the next solve call)
    ///
    /// **Returns** whether the call was successful
    fn assume(&mut self, literals: &[Literal]) -> bool;
    #[doc(hidden)]
    unsafe extern "C" fn unsafe_assume<T: GroundProgramObserver>(
        literals: *const clingo_literal_t,
        size: usize,
        data: *mut ::std::os::raw::c_void,
    ) -> bool {
        assert!(!literals.is_null());
        let literals = std::slice::from_raw_parts(literals as *const Literal, size);

        if let Some(gpo) = (data as *mut T).as_mut() {
            gpo.assume(literals)
        } else {
            set_internal_error(
                ErrorType::Runtime,
                "unsafe_assume tried casting a null pointer to &mut GroundProgramObserver.",
            );
            false
        }
    }

    /// Observe heuristic directives passed to the solver.
    ///
    /// # Arguments
    ///
    /// * `atom` - the target atom
    /// * `type` - the type of the heuristic modification
    /// * `bias` - the heuristic bias
    /// * `priority` - the heuristic priority
    /// * `condition` - the condition under which to apply the heuristic modification
    ///
    /// **Returns** whether the call was successful
    fn heuristic(
        &mut self,
        atom: Atom,
        type_: HeuristicType,
        bias: i32,
        priority: u32,
        condition: &[Literal],
    ) -> bool;
    #[doc(hidden)]
    unsafe extern "C" fn unsafe_heuristic<T: GroundProgramObserver>(
        atom: clingo_atom_t,
        type_: clingo_heuristic_type_t,
        bias: ::std::os::raw::c_int,
        priority: ::std::os::raw::c_uint,
        condition: *const clingo_literal_t,
        size: usize,
        data: *mut ::std::os::raw::c_void,
    ) -> bool {
        let type_ = match type_ as u32 {
            clingo_heuristic_type_clingo_heuristic_type_factor => HeuristicType::Factor,
            clingo_heuristic_type_clingo_heuristic_type_false => HeuristicType::False,
            clingo_heuristic_type_clingo_heuristic_type_init => HeuristicType::Init,
            clingo_heuristic_type_clingo_heuristic_type_level => HeuristicType::Level,
            clingo_heuristic_type_clingo_heuristic_type_sign => HeuristicType::Sign,
            clingo_heuristic_type_clingo_heuristic_type_true => HeuristicType::True,
            x => panic!("Failed to match clingo_heuristic_type: {}.", x),
        };

        assert!(!condition.is_null());
        let condition = std::slice::from_raw_parts(condition as *const Literal, size);

        if let Some(gpo) = (data as *mut T).as_mut() {
            gpo.heuristic(Atom(atom), type_, bias, priority, condition)
        } else {
            set_internal_error(
                ErrorType::Runtime,
                "unsafe_heuristic tried casting a null pointer to &mut GroundProgramObserver.",
            );
            false
        }
    }

    /// Observe edge directives passed to the solver.
    ///
    /// # Arguments
    ///
    /// * `node_u` - the start vertex of the edge
    /// * `node_v` - the end vertex of the edge
    /// * `condition` - the condition under which the edge is part of the graph
    ///
    /// **Returns** whether the call was successful
    fn acyc_edge(&mut self, node_u: i32, node_v: i32, condition: &[Literal]) -> bool;
    #[doc(hidden)]
    unsafe extern "C" fn unsafe_acyc_edge<T: GroundProgramObserver>(
        node_u: ::std::os::raw::c_int,
        node_v: ::std::os::raw::c_int,
        condition: *const clingo_literal_t,
        size: usize,
        data: *mut ::std::os::raw::c_void,
    ) -> bool {
        assert!(!condition.is_null());
        let condition = std::slice::from_raw_parts(condition as *const Literal, size);

        if let Some(gpo) = (data as *mut T).as_mut() {
            gpo.acyc_edge(node_u, node_v, condition)
        } else {
            set_internal_error(
                ErrorType::Runtime,
                "unsafe_acyc_edge tried casting a null pointer to &mut GroundProgramObserver.",
            );
            false
        }
    }

    /// Observe numeric theory terms.
    ///
    /// # Arguments
    ///
    /// * `term_id` - the id of the term
    /// * `number` - the value of the term
    ///
    /// **Returns** whether the call was successful
    fn theory_term_number(&mut self, term_id: Id, number: i32) -> bool;
    #[doc(hidden)]
    unsafe extern "C" fn unsafe_theory_term_number<T: GroundProgramObserver>(
        term_id: clingo_id_t,
        number: ::std::os::raw::c_int,
        data: *mut ::std::os::raw::c_void,
    ) -> bool {
        if let Some(gpo) = (data as *mut T).as_mut() {
            gpo.theory_term_number(Id(term_id), number)
        } else {
            set_internal_error(
                        ErrorType::Runtime,
                            "unsafe_theory_term_number tried casting a null pointer to &mut GroundProgramObserver."
                    );
            false
        }
    }

    /// Observe string theory terms.
    ///
    /// # Arguments
    ///
    /// * `term_id` - the id of the term
    /// * `name` - the value of the term
    ///
    /// **Returns** whether the call was successful
    fn theory_term_string(&mut self, term_id: Id, name: &str) -> bool;
    #[doc(hidden)]
    unsafe extern "C" fn unsafe_theory_term_string<T: GroundProgramObserver>(
        term_id: clingo_id_t,
        name: *const ::std::os::raw::c_char,
        data: *mut ::std::os::raw::c_void,
    ) -> bool {
        assert!(!name.is_null());
        let cstr = CStr::from_ptr(name);
        let name = cstr.to_str().unwrap_or_else(|err| panic!(err));

        if let Some(gpo) = (data as *mut T).as_mut() {
            gpo.theory_term_string(Id(term_id), name)
        } else {
            set_internal_error(
                        ErrorType::Runtime,
                            "unsafe_theory_term_string tried casting a null pointer to &mut GroundProgramObserver."
                    );
            false
        }
    }

    /// Observe compound theory terms.
    ///
    /// The name_id_or_type gives the type of the compound term:
    /// - if it is -1, then it is a tuple
    /// - if it is -2, then it is a set
    /// - if it is -3, then it is a list
    /// - otherwise, it is a function and name_id_or_type refers to the id of the name (in form of a
    /// string term)
    ///
    /// # Arguments
    ///
    /// * `term_id` - the id of the term
    /// * `name_id_or_type` - the name or type of the term
    /// * `arguments` - the arguments of the term
    ///
    /// **Returns** whether the call was successful
    fn theory_term_compound(&mut self, term_id: Id, name_id_or_type: i32, arguments: &[Id])
        -> bool;
    #[doc(hidden)]
    unsafe extern "C" fn unsafe_theory_term_compound<T: GroundProgramObserver>(
        term_id: clingo_id_t,
        name_id_or_type: ::std::os::raw::c_int,
        arguments: *const clingo_id_t,
        size: usize,
        data: *mut ::std::os::raw::c_void,
    ) -> bool {
        assert!(!arguments.is_null());
        let arguments = std::slice::from_raw_parts(arguments as *const Id, size);

        if let Some(gpo) = (data as *mut T).as_mut() {
            gpo.theory_term_compound(Id(term_id), name_id_or_type, arguments)
        } else {
            set_internal_error(
                        ErrorType::Runtime,
                            "unsafe_theory_term_compound tried casting a null pointer to &mut GroundProgramObserver."
                    );
            false
        }
    }

    /// Observe theory elements.
    ///
    /// # Arguments
    ///
    /// * `element_id` - the id of the element
    /// * `terms` - the term tuple of the element
    /// * `condition` - the condition of the element
    ///
    /// **Returns** whether the call was successful
    fn theory_element(&mut self, element_id: Id, terms: &[Id], condition: &[Literal]) -> bool;
    #[doc(hidden)]
    unsafe extern "C" fn unsafe_theory_element<T: GroundProgramObserver>(
        element_id: clingo_id_t,
        terms: *const clingo_id_t,
        terms_size: usize,
        condition: *const clingo_literal_t,
        condition_size: usize,
        data: *mut ::std::os::raw::c_void,
    ) -> bool {
        assert!(!terms.is_null());
        let terms = std::slice::from_raw_parts(terms as *const Id, terms_size);

        assert!(!condition.is_null());
        let condition = std::slice::from_raw_parts(condition as *const Literal, condition_size);

        if let Some(gpo) = (data as *mut T).as_mut() {
            gpo.theory_element(Id(element_id), terms, condition)
        } else {
            set_internal_error(
                ErrorType::Runtime,
                "unsafe_theory_element tried casting a null pointer to &mut GroundProgramObserver.",
            );
            false
        }
    }

    /// Observe theory atoms without guard.
    ///
    /// # Arguments
    ///
    /// * `atom_id_or_zero` - the id of the atom or zero for directives
    /// * `term_id` - the term associated with the atom
    /// * `elements` - the elements of the atom
    ///
    /// **Returns** whether the call was successful
    fn theory_atom(&mut self, atom_id_or_zero: Id, term_id: Id, elements: &[Id]) -> bool;
    #[doc(hidden)]
    unsafe extern "C" fn unsafe_theory_atom<T: GroundProgramObserver>(
        atom_id_or_zero: clingo_id_t,
        term_id: clingo_id_t,
        elements: *const clingo_id_t,
        size: usize,
        data: *mut ::std::os::raw::c_void,
    ) -> bool {
        assert!(!elements.is_null());
        let elements = std::slice::from_raw_parts(elements as *const Id, size);

        if let Some(gpo) = (data as *mut T).as_mut() {
            gpo.theory_atom(Id(atom_id_or_zero), Id(term_id), elements)
        } else {
            set_internal_error(
                ErrorType::Runtime,
                "unsafe_theory_atom tried casting a null pointer to &mut GroundProgramObserver.",
            );
            false
        }
    }

    /// Observe theory atoms with guard.
    ///
    /// # Arguments
    ///
    /// * `atom_id_or_zero` - the id of the atom or zero for directives
    /// * `term_id` - the term associated with the atom
    /// * `elements` - the elements of the atom
    /// * `operator_id` - the id of the operator (a string term)
    /// * `right_hand_side_id` - the id of the term on the right hand side of the atom
    ///
    /// **Returns** whether the call was successful
    fn theory_atom_with_guard(
        &mut self,
        atom_id_or_zero: Id,
        term_id: Id,
        elements: &[Id],
        operator_id: Id,
        right_hand_side_id: Id,
    ) -> bool;
    #[doc(hidden)]
    unsafe extern "C" fn unsafe_theory_atom_with_guard<T: GroundProgramObserver>(
        atom_id_or_zero: clingo_id_t,
        term_id: clingo_id_t,
        elements: *const clingo_id_t,
        size: usize,
        operator_id: clingo_id_t,
        right_hand_side_id: clingo_id_t,
        data: *mut ::std::os::raw::c_void,
    ) -> bool {
        assert!(!elements.is_null());
        let elements = std::slice::from_raw_parts(elements as *const Id, size);

        if let Some(gpo) = (data as *mut T).as_mut() {
            gpo.theory_atom_with_guard(
                Id(atom_id_or_zero),
                Id(term_id),
                elements,
                Id(operator_id),
                Id(right_hand_side_id),
            )
        } else {
            set_internal_error(
                        ErrorType::Runtime,
                            "unsafe_theory_atom_with_guard tried casting a null pointer to &mut GroundProgramObserver."
                    );
            false
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    #[test]
    fn version_test() {
        let (ma, mi, re) = version();
        assert!(ma == 5);
        assert!(mi == 2);
        assert!(re == 2);
    }
    #[test]
    fn parse_program_test() {
        let mut sym = Symbol::create_number(42);
        assert!(42 == sym.number().unwrap());
        sym = Symbol::create_infimum();
        assert!(SymbolType::Infimum == sym.symbol_type());
    }
}