File: cocci_vs_c.ml

package info (click to toggle)
coccinelle 1.0.8.deb-5
  • links: PTS, VCS
  • area: main
  • in suites: bullseye, sid
  • size: 26,148 kB
  • sloc: ml: 136,392; ansic: 23,594; sh: 2,189; makefile: 2,157; perl: 1,576; lisp: 840; python: 823; awk: 70; csh: 12
file content (5406 lines) | stat: -rw-r--r-- 185,323 bytes parent folder | download
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
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
(*
 * This file is part of Coccinelle, licensed under the terms of the GPL v2.
 * See copyright.txt in the Coccinelle source code for more information.
 * The Coccinelle source code can be obtained at http://coccinelle.lip6.fr
 *)

open Common

module A = Ast_cocci
module B = Ast_c

module F = Control_flow_c

module FlagM = Flag_matcher

(*****************************************************************************)
(* Wrappers *)
(*****************************************************************************)
let pr2, pr2_once = Common.mk_pr2_wrappers FlagM.verbose_matcher

let (+++) a b = match a with Some x -> Some x | None -> b

let error ii str =
  match ii with
    [] -> failwith str
  | ii::_ ->
      failwith
	(Printf.sprintf "%s: %d: %s"
	   (Ast_c.file_of_info ii) (Ast_c.line_of_info ii) str)

(*****************************************************************************)
(* Helpers *)
(*****************************************************************************)

type sequence = Ordered | Unordered

let seqstyle eas = Ordered

let (need_unordered_initialisers : B.initialiser B.wrap2 list -> bool) =
 fun ibs ->
   ibs +> List.exists (fun (ib, icomma) ->
     match B.unwrap ib with
     | B.InitDesignators _
     | B.InitFieldOld _
     | B.InitIndexOld _
       -> true
     | B.InitExpr _
     | B.InitList _
       -> false)

(* For the #include <linux/...> in the .cocci, need to find where is
 * the '+' attached to this element, to later find the first concrete
 * #include <linux/xxx.h> or last one in the series of #includes in the
 * .c.
 *)
type include_requirement =
  | IncludeMcodeBefore
  | IncludeMcodeAfter
  | IncludeNothing



(* todo? put in semantic_c.ml *)
type info_ident =
  | Function
  | LocalFunction (* entails Function *)
  | DontKnow


let term      mc = A.unwrap_mcode mc
let mcodekind mc = A.get_mcodekind mc


let mcode_contain_plus = function
  | A.CONTEXT (_,A.NOTHING) -> false
  | A.CONTEXT _ -> true
  | A.MINUS (_,_,_,A.NOREPLACEMENT) -> false
  | A.MINUS (_,_,_,A.REPLACEMENT _) -> true (* repl is nonempty *)
  | A.PLUS _ -> raise (Impossible 13)

let mcode_simple_minus = function
  | A.MINUS (_,_,_,A.NOREPLACEMENT) -> true
  | _ -> false


(* In transformation.ml sometime I build some mcodekind myself and
 * julia has put None for the pos. But there is no possible raise
 * NoMatch in those cases because it is for the minusall trick or for
 * the distribute, so either have to build those pos, in fact a range,
 * because for the distribute have to erase a fullType with one
 * mcodekind, or add an argument to tag_with_mck such as "safe" that
 * don't do the check_pos. Hence this DontCarePos constructor. *)

let minusizer =
  ("fake","fake"),
  {A.line = 0; A.column =0; A.strbef=[]; A.straft=[]; A.whitespace=""},
  (A.MINUS(A.DontCarePos,[],A.ALLMINUS,A.NOREPLACEMENT)),
  []

let generalize_mcode ia =
  let (s1, i, mck, pos) = ia in
  let new_mck =
    match mck with
    | A.PLUS _ -> raise (Impossible 14)
    | A.CONTEXT (A.NoPos,x) ->
	A.CONTEXT (A.DontCarePos,x)
    | A.MINUS   (A.NoPos,inst,adj,x) ->
	A.MINUS   (A.DontCarePos,inst,adj,x)

    | A.CONTEXT ((A.FixPos _|A.DontCarePos), _)
    | A.MINUS ((A.FixPos _|A.DontCarePos), _, _, _)
        ->
        raise (Impossible 15)
  in
  (s1, i, new_mck, pos)



(*---------------------------------------------------------------------------*)

(* 0x0 is equivalent to 0,  value format isomorphism *)
let equal_c_int s1 s2 =
  try
    int_of_string s1 = int_of_string s2
  with Failure _ ->
    s1 = s2



(*---------------------------------------------------------------------------*)
(* Normally A should reuse some types of Ast_c, so those
 * functions should not exist.
 *
 * update: but now Ast_c depends on A, so can't make too
 * A depends on Ast_c, so have to stay with those equal_xxx
 * functions.
 *)

let equal_unaryOp a b =
  match a, b with
  | A.GetRef   , B.GetRef  -> true
  | A.GetRefLabel, B.GetRefLabel -> true
  | A.DeRef    , B.DeRef   -> true
  | A.UnPlus   , B.UnPlus  -> true
  | A.UnMinus  , B.UnMinus -> true
  | A.Tilde    , B.Tilde   -> true
  | A.Not      , B.Not     -> true
  | _, (B.Not|B.Tilde|B.UnMinus|B.UnPlus|B.DeRef|B.GetRef|B.GetRefLabel) ->
      false
let equal_arithOp a b =
  match (A.unwrap_mcode a), b with
  | A.Plus     , B.Plus     -> true
  | A.Minus    , B.Minus    -> true
  | A.Mul      , B.Mul      -> true
  | A.Div      , B.Div      -> true
  | A.Min      , B.Min      -> true
  | A.Max      , B.Max      -> true
  | A.Mod      , B.Mod      -> true
  | A.DecLeft  , B.DecLeft  -> true
  | A.DecRight , B.DecRight -> true
  | A.And      , B.And      -> true
  | A.Or       , B.Or       -> true
  | A.Xor      , B.Xor      -> true
  | _, (B.Xor|B.Or|B.And|B.DecRight|B.DecLeft|B.Mod|B.Div|B.Mul|B.Minus|B.Plus|B.Min|B.Max)
      -> false
let equal_logicalOp a b =
  match (A.unwrap_mcode a), b with
  | A.Inf    , B.Inf    -> true
  | A.Sup    , B.Sup    -> true
  | A.InfEq  , B.InfEq  -> true
  | A.SupEq  , B.SupEq  -> true
  | A.Eq     , B.Eq     -> true
  | A.NotEq  , B.NotEq  -> true
  | A.AndLog , B.AndLog -> true
  | A.OrLog  , B.OrLog  -> true
  | _, (B.OrLog|B.AndLog|B.NotEq|B.Eq|B.SupEq|B.InfEq|B.Sup|B.Inf)
      -> false
let equal_fixOp a b =
  match a, b with
  | A.Dec, B.Dec -> true
  | A.Inc, B.Inc -> true
  | _, (B.Inc|B.Dec) -> false

let equal_structUnion a b =
  match a, b with
  | A.Struct, B.Struct -> true
  | A.Union,  B.Union -> true
  | _, (B.Struct|B.Union) -> false

let equal_sign a b =
  match a, b with
  | A.Signed,    B.Signed   -> true
  | A.Unsigned,  B.UnSigned -> true
  | _, (B.UnSigned|B.Signed) -> false

let equal_storage a b =
  match a, b with
  | A.Static   , B.Sto B.Static
  | A.Auto     , B.Sto B.Auto
  | A.Register , B.Sto B.Register
  | A.Extern   , B.Sto B.Extern
      -> true
  | _, (B.NoSto | B.StoTypedef) -> false
  | _, (B.Sto (B.Register|B.Static|B.Auto|B.Extern)) -> false


(*---------------------------------------------------------------------------*)

let equal_metavarval valu valu' =
  match valu, valu' with
  | Ast_c.MetaIdVal a, Ast_c.MetaIdVal b -> a = b
  | Ast_c.MetaAssignOpVal a, Ast_c.MetaAssignOpVal b -> a = b
  | Ast_c.MetaBinaryOpVal a, Ast_c.MetaBinaryOpVal b -> a = b
  | Ast_c.MetaFuncVal a, Ast_c.MetaFuncVal b -> a = b
  | Ast_c.MetaLocalFuncVal a, Ast_c.MetaLocalFuncVal b ->
      (* do something more ? *)
      a = b

  (* al_expr before comparing !!! and accept when they match.
   * Note that here we have Astc._expression, so it is a match
   * modulo isomorphism (there is no metavariable involved here,
   * just isomorphisms). => TODO call isomorphism_c_c instead of
   * =. Maybe would be easier to transform ast_c in ast_cocci
   * and call the iso engine of julia. *)
  | Ast_c.MetaExprVal (a,_,_), Ast_c.MetaExprVal (b,_,_) ->
      Lib_parsing_c.al_expr a = Lib_parsing_c.al_expr b
  | Ast_c.MetaExprListVal a, Ast_c.MetaExprListVal b ->
      Lib_parsing_c.al_arguments a = Lib_parsing_c.al_arguments b

  | Ast_c.MetaFmtVal a, Ast_c.MetaFmtVal b ->
      Lib_parsing_c.al_string_format a = Lib_parsing_c.al_string_format b
  | Ast_c.MetaFragListVal a, Ast_c.MetaFragListVal b ->
      Lib_parsing_c.al_string_fragments a =
      Lib_parsing_c.al_string_fragments b

  | Ast_c.MetaDeclVal(a,_), Ast_c.MetaDeclVal(b,_) ->
      Lib_parsing_c.al_declaration a = Lib_parsing_c.al_declaration b
  | Ast_c.MetaFieldVal a, Ast_c.MetaFieldVal b ->
      Lib_parsing_c.al_field a = Lib_parsing_c.al_field b
  | Ast_c.MetaFieldListVal a, Ast_c.MetaFieldListVal b ->
      Lib_parsing_c.al_fields a = Lib_parsing_c.al_fields b
  | Ast_c.MetaStmtVal(a,_,_), Ast_c.MetaStmtVal(b,_,_) ->
      Lib_parsing_c.al_statement a = Lib_parsing_c.al_statement b
  | Ast_c.MetaStmtListVal(a,_), Ast_c.MetaStmtListVal(b,_) ->
      Lib_parsing_c.al_statement_seq_list a =
      Lib_parsing_c.al_statement_seq_list b
  | Ast_c.MetaInitVal a, Ast_c.MetaInitVal b ->
      Lib_parsing_c.al_init a = Lib_parsing_c.al_init b
  | Ast_c.MetaInitListVal a, Ast_c.MetaInitListVal b ->
      Lib_parsing_c.al_inits a = Lib_parsing_c.al_inits b
  | Ast_c.MetaTypeVal a, Ast_c.MetaTypeVal b ->
      (* old: Lib_parsing_c.al_type a = Lib_parsing_c.al_type b *)
      C_vs_c.eq_type a b

  | Ast_c.MetaListlenVal a, Ast_c.MetaListlenVal b -> a = b

  | Ast_c.MetaParamVal a, Ast_c.MetaParamVal b ->
      Lib_parsing_c.al_param a = Lib_parsing_c.al_param b
  | Ast_c.MetaParamListVal a, Ast_c.MetaParamListVal b ->
      Lib_parsing_c.al_params a = Lib_parsing_c.al_params b
  | Ast_c.MetaDParamListVal a, Ast_c.MetaDParamListVal b ->
      Lib_parsing_c.al_define_params a = Lib_parsing_c.al_define_params b

  | Ast_c.MetaPosVal (posa1,posa2), Ast_c.MetaPosVal (posb1,posb2) ->
      Ast_cocci.equal_pos posa1 posb1 && Ast_cocci.equal_pos posa2 posb2

  | Ast_c.MetaPosValList l1, Ast_c.MetaPosValList l2 ->
      List.exists
	(function (fla,cea,_cepa,posa1,posa2) ->
	  List.exists
	    (function (flb,ceb,_cepb,posb1,posb2) ->
	      fla = flb && cea = ceb &&
	      Ast_c.equal_posl posa1 posb1 && Ast_c.equal_posl posa2 posb2)
            l2)
	l1

  | Ast_c.MetaComValList l1, Ast_c.MetaComValList l2 -> l1 = l2

  | (Ast_c.MetaNoVal, _) | (_, Ast_c.MetaNoVal) -> false

  | (B.MetaPosValList _|B.MetaComValList _|B.MetaListlenVal _|B.MetaPosVal _
      |B.MetaStmtVal _
      |B.MetaStmtListVal _
      |B.MetaDeclVal _ |B.MetaFieldVal _ |B.MetaFieldListVal _
      |B.MetaTypeVal _ |B.MetaInitVal _ |B.MetaInitListVal _
      |B.MetaDParamListVal _|B.MetaParamListVal _|B.MetaParamVal _
      |B.MetaExprListVal _
      |B.MetaExprVal _|B.MetaLocalFuncVal _|B.MetaFuncVal _|B.MetaIdVal _
      |B.MetaAssignOpVal _ | B.MetaBinaryOpVal _
      |B.MetaFmtVal _|B.MetaFragListVal _
    ), _
      -> raise (Impossible 16)

let equal_unwrap a b = B.unwrap a = B.unwrap b

(* probably only one argument needs to be stripped, because inherited
metavariables containing expressions are stripped in advance. But don't
know which one is which... *)
let equal_inh_metavarval valu valu'=
  match valu, valu' with
  | Ast_c.MetaIdVal a, Ast_c.MetaIdVal b -> a = b
  | Ast_c.MetaAssignOpVal a, Ast_c.MetaAssignOpVal b -> equal_unwrap a b
  | Ast_c.MetaBinaryOpVal a, Ast_c.MetaBinaryOpVal b -> equal_unwrap a b
  | Ast_c.MetaFuncVal a, Ast_c.MetaFuncVal b -> a = b
  | Ast_c.MetaLocalFuncVal a, Ast_c.MetaLocalFuncVal b ->
      (* do something more ? *)
      a = b

  (* al_expr before comparing !!! and accept when they match.
   * Note that here we have Astc._expression, so it is a match
   * modulo isomorphism (there is no metavariable involved here,
   * just isomorphisms). => TODO call isomorphism_c_c instead of
   * =. Maybe would be easier to transform ast_c in ast_cocci
   * and call the iso engine of julia. *)
  | Ast_c.MetaExprVal (a,_,ty1), Ast_c.MetaExprVal (b,_,ty2) ->
      if ty1 = Ast_c.WITHOUT_TYPES || ty2 = Ast_c.WITHOUT_TYPES
      then Lib_parsing_c.real_al_expr a = Lib_parsing_c.real_al_expr b
      else Lib_parsing_c.al_inh_expr a = Lib_parsing_c.al_inh_expr b
  | Ast_c.MetaExprListVal a, Ast_c.MetaExprListVal b ->
      Lib_parsing_c.al_inh_arguments a = Lib_parsing_c.al_inh_arguments b

  | Ast_c.MetaFmtVal a, Ast_c.MetaFmtVal b ->
      Lib_parsing_c.al_inh_string_format a =
      Lib_parsing_c.al_inh_string_format b
  | Ast_c.MetaFragListVal a, Ast_c.MetaFragListVal b ->
      Lib_parsing_c.al_inh_string_fragments a =
      Lib_parsing_c.al_inh_string_fragments b

  | Ast_c.MetaDeclVal(a,_), Ast_c.MetaDeclVal(b,_) ->
      Lib_parsing_c.al_inh_declaration a = Lib_parsing_c.al_inh_declaration b
  | Ast_c.MetaFieldVal a, Ast_c.MetaFieldVal b ->
      Lib_parsing_c.al_inh_field a = Lib_parsing_c.al_inh_field b
  | Ast_c.MetaFieldListVal a, Ast_c.MetaFieldListVal b ->
      Lib_parsing_c.al_inh_field_list a = Lib_parsing_c.al_inh_field_list b
  | Ast_c.MetaStmtVal(a,orig_a,ty1), Ast_c.MetaStmtVal(b,orig_b,ty2) ->
      if ty1 = Ast_c.WITHOUT_TYPES || ty2 = Ast_c.WITHOUT_TYPES
      then
	Lib_parsing_c.real_al_statement a = Lib_parsing_c.real_al_statement b
      else Lib_parsing_c.al_inh_statement a = Lib_parsing_c.al_inh_statement b
  | Ast_c.MetaStmtListVal(a,ty1), Ast_c.MetaStmtListVal(b,ty2) ->
      if ty1 = Ast_c.WITHOUT_TYPES || ty2 = Ast_c.WITHOUT_TYPES
      then
	Lib_parsing_c.real_al_statement_seq_list a =
	Lib_parsing_c.real_al_statement_seq_list b
      else
	Lib_parsing_c.al_inh_statement_seq_list a =
	Lib_parsing_c.al_inh_statement_seq_list b
  | Ast_c.MetaInitVal a, Ast_c.MetaInitVal b ->
      Lib_parsing_c.al_inh_init a = Lib_parsing_c.al_inh_init b
  | Ast_c.MetaInitListVal a, Ast_c.MetaInitListVal b ->
      Lib_parsing_c.al_inh_inits a = Lib_parsing_c.al_inh_inits b
  | Ast_c.MetaTypeVal a, Ast_c.MetaTypeVal b ->
      (* old: Lib_parsing_c.al_inh_type a = Lib_parsing_c.al_inh_type b *)
      C_vs_c.eq_type a b

  | Ast_c.MetaListlenVal a, Ast_c.MetaListlenVal b -> a = b

  | Ast_c.MetaParamVal a, Ast_c.MetaParamVal b ->
      Lib_parsing_c.al_param a = Lib_parsing_c.al_param b
  | Ast_c.MetaParamListVal a, Ast_c.MetaParamListVal b ->
      Lib_parsing_c.al_params a = Lib_parsing_c.al_params b
  | Ast_c.MetaDParamListVal a, Ast_c.MetaDParamListVal b ->
      Lib_parsing_c.al_define_params a = Lib_parsing_c.al_define_params b

  | Ast_c.MetaPosVal (posa1,posa2), Ast_c.MetaPosVal (posb1,posb2) ->
      Ast_cocci.equal_pos posa1 posb1 && Ast_cocci.equal_pos posa2 posb2

  | Ast_c.MetaPosValList l1, Ast_c.MetaPosValList l2 ->
      List.exists
	(function (fla,cea,_cepa,posa1,posa2) ->
	  List.exists
	    (function (flb,ceb,_cepb,posb1,posb2) ->
	      fla = flb && cea = ceb &&
	      Ast_c.equal_posl posa1 posb1 && Ast_c.equal_posl posa2 posb2)
            l2)
	l1

  | Ast_c.MetaComValList l1, Ast_c.MetaComValList l2 -> l1 = l2

  | (Ast_c.MetaNoVal, _) | (_, Ast_c.MetaNoVal) -> false

  | (B.MetaPosValList _|B.MetaComValList _|B.MetaListlenVal _|B.MetaPosVal _
      |B.MetaStmtVal _
      |B.MetaStmtListVal _
      |B.MetaDeclVal _ |B.MetaFieldVal _ |B.MetaFieldListVal _
      |B.MetaTypeVal _ |B.MetaInitVal _ |B.MetaInitListVal _
      |B.MetaDParamListVal _|B.MetaParamListVal _|B.MetaParamVal _
      |B.MetaExprListVal _
      |B.MetaExprVal _|B.MetaLocalFuncVal _|B.MetaFuncVal _|B.MetaIdVal _
      |B.MetaAssignOpVal _ | B.MetaBinaryOpVal _
      |B.MetaFmtVal _|B.MetaFragListVal _
    ), _
      -> raise (Impossible 17)


(*---------------------------------------------------------------------------*)
(* could put in ast_c.ml, next to the split/unsplit_comma *)
let split_signb_baseb_ii (baseb, ii) =
  let iis = ii +> List.map (fun info -> (B.str_of_info info), info) in
  match baseb, iis with

  | B.Void, ["void",i1] -> None, [i1]

  | B.FloatType (B.CFloat),["float",i1] -> None, [i1]
  | B.FloatType (B.CDouble),["double",i1] -> None, [i1]
  | B.FloatType (B.CFloatComplex),["float",i1;"complex",i2] -> None, [i1;i2]
  | B.FloatType (B.CDoubleComplex),["double",i1;"complex",i2] -> None, [i1;i2]
  | B.FloatType (B.CLongDouble),["long",i1;"double",i2] -> None,[i1;i2]
  | B.FloatType (B.CLongDoubleComplex),["long",i1;"double",i2;"complex",i3] ->
      None,[i1;i2;i3]

  | B.IntType (B.CChar), ["char",i1] -> None, [i1]


  | B.IntType (B.Si (sign, base)), xs ->
      let (signed,rest) =
	match (sign,xs) with
	  (_,[]) -> None,[]
	| (B.Signed,(("signed",i1)::rest)) -> (Some (B.Signed,i1),rest)
	| (B.Signed,rest) -> (None,rest)
	| (B.UnSigned,(("unsigned",i1)::rest)) -> (Some (B.UnSigned,i1),rest)
	| (B.UnSigned,rest) -> (* is this case possible? *) (None,rest) in
      (* The original code only allowed explicit signed and unsigned for char,
	 while this code allows char by itself.  Not sure that needs to be
	 checked for here.  If it does, then add a special case. *)
      let base_res =
	match (base,rest) with
	  B.CInt, ["int",i1] -> [i1]
	| B.CInt, [] -> []

	| B.CInt, ["",i1] -> (* no type is specified at all *)
	    (match i1.B.pinfo with
	      B.FakeTok(_,_) -> []
	    | _ -> error [i1] ("unrecognized signed int: "^
			      (String.concat " "(List.map fst iis))))

	| B.CChar2, ["char",i2] -> [i2]

	| B.CShort, ["short",i1] -> [i1]
	| B.CShort, ["short",i1;"int",i2] -> [i1;i2]

	| B.CLong, ["long",i1] -> [i1]
	| B.CLong, ["long",i1;"int",i2] -> [i1;i2]

	| B.CLongLong, ["long",i1;"long",i2] -> [i1;i2]
	| B.CLongLong, ["long",i1;"long",i2;"int",i3] -> [i1;i2;i3]

	| _ ->
	    error (List.map snd iis)
	      ("strange type1, maybe because of weird order: "^
	       (String.concat " " (List.map fst iis))) in
      (signed,base_res)

  | B.SizeType, ["size_t",i1] -> None, [i1]
  | B.SSizeType, ["ssize_t",i1] -> None, [i1]
  | B.PtrDiffType, ["ptrdiff_t",i1] -> None, [i1]

  | _ ->
      error (List.map snd iis)
	("strange type2, maybe because of weird order: "^
	 (String.concat " " (List.map fst iis)))

(*---------------------------------------------------------------------------*)

let rec unsplit_icomma xs =
  match xs with
  | [] -> []
  | x::y::xs ->
      (match A.unwrap y with
      | A.IComma mcode ->
          (x, y)::unsplit_icomma xs
      | _ -> failwith "wrong ast_cocci in initializer"
      )
  | _ ->
      failwith ("wrong ast_cocci in initializer, should have pair " ^
                "number of Icomma")



let resplit_initialiser ibs iicomma =
  match iicomma, ibs with
  | [], [] -> []
  | [], _ ->
      failwith "should have a iicomma, do you generate fakeInfo in parser?"
  | iicommas, [] ->
      error iicommas "shouldn't have a iicomma"
  | [iicomma], x::xs ->
      let elems = List.map fst (x::xs) in
      let commas = List.map snd (x::xs) +> List.flatten in
      let commas = commas @ [iicomma] in
      zip elems commas
  | _ -> raise (Impossible 18)



let rec split_icomma xs =
  match xs with
  | [] -> []
  | (x,y)::xs -> x::y::split_icomma xs

let rec unsplit_initialiser ibs_unsplit =
  match ibs_unsplit with
  | [] -> [],  [] (* empty iicomma *)
  | (x, commax)::xs ->
      let (xs, lastcomma) = unsplit_initialiser_bis commax xs in
      (x, [])::xs,  lastcomma

and unsplit_initialiser_bis comma_before = function
  | [] -> [], [comma_before]
  | (x, commax)::xs ->
      let (xs, lastcomma) = unsplit_initialiser_bis commax xs in
      (x, [comma_before])::xs,  lastcomma




(*---------------------------------------------------------------------------*)
(* coupling: same in type_annotater_c.ml *)
let structdef_to_struct_name ty =
  match ty with
  | qu, (B.StructUnion (su, sopt, fields), iis) ->
      (match sopt,iis with
      | Some s , [i1;i2;i3;i4] ->
          qu, (B.StructUnionName (su, s), [i1;i2])
      | None, _ ->
          ty

      | x -> raise (Impossible 19)
      )
  | _ -> raise (Impossible 20)

(*---------------------------------------------------------------------------*)
let one_initialisation_to_affectation x =
  let ({B.v_namei = var;
         B.v_type = returnType;
         B.v_type_bis = tybis;
         B.v_storage = storage;
         B.v_local = local},
       iisep) = x in
  match var with
  | Some (name, iniopt) ->
      (match iniopt with
      | B.ValInit (iini, (B.InitExpr e, ii_empty2)) ->
	  let local =
	    match local with
	      Ast_c.NotLocalDecl -> Ast_c.NotLocalVar
	    | Ast_c.LocalDecl ->
		(match Ast_c.info_of_type returnType with
		  None -> failwith "no returnType info"
		| Some ii -> Ast_c.LocalVar ii) in
          let typexp =
                    (* old: Lib_parsing_c.al_type returnType
                       * but this type has not the typename completed so
                       * instead try to use tybis
                    *)
            match !tybis with
            | Some ty_with_typename_completed -> ty_with_typename_completed
            | None -> raise (Impossible 21)
          in

          let typ = ref (Some (typexp,local), Ast_c.NotTest) in
          let ident = name in
          let idexpr = Ast_c.mk_e_bis (B.Ident ident) typ Ast_c.noii in
          let assign =
            Ast_c.mk_e (B.Assignment (idexpr, (B.SimpleAssign, [iini]), e)) [] in
          Some assign
      | _ -> None)
  | _ -> None

let initialisation_to_affectation decl =
  match decl with
  | B.MacroDecl _ -> F.Decl decl
  | B.MacroDeclInit _ -> F.Decl decl (* not sure... *)
  | B.DeclList (xs, iis) ->

      (* todo?: should not do that if the variable is an array cos
       *  will have x[] = , mais de toute facon ca sera pas un InitExp
       *)
      let possible_assignment =
	List.fold_left
	  (function prev ->
	    function x ->
	      match prev,one_initialisation_to_affectation x with
		_,None -> prev
	      |	None,Some x -> Some x
	      |	Some prev,Some x ->
		  (* [] is clearly an invalid ii value for a sequence.
		     hope that no one looks at it, since nothing will
		     match the sequence.  Fortunately, SmPL doesn't
		     support , expressions. *)
		  Some (Ast_c.mk_e (Ast_c.Sequence (prev, x)) []))
	  None xs in
      match possible_assignment with
	Some x -> F.DefineExpr x
      |	None -> F.Decl decl

(*****************************************************************************)
(* Functor parameter combinators *)
(*****************************************************************************)
(* monad like stuff
 * src: papers on parser combinators in haskell (cf a pearl by meijer in ICFP)
 *
 * version0: was not tagging the SP, so just tag the C
 *  val (>>=):
 *   (tin -> 'c tout)  -> ('c -> (tin -> 'b tout)) -> (tin -> 'b tout)
 *   val return : 'b -> tin -> 'b tout
 *   val fail : tin -> 'b tout
 *
 * version1: now also tag the SP so return a ('a * 'b)
 *)

type mode = PatternMode | TransformMode

module type PARAM =
  sig
    type tin
    type 'x tout


    type ('a, 'b) matcher = 'a -> 'b  -> tin -> ('a * 'b) tout

    val constraint_checker:
	(A.meta_name -> B.metavar_binding_kind ->
	  (A.meta_name -> B.metavar_binding_kind) -> A.constraints -> tin ->
	    (unit * unit) tout) ref

    val mode : mode

    val (>>=):
      (tin -> ('a * 'b) tout)  ->
      ('a -> 'b -> (tin -> ('c * 'd) tout)) ->
      (tin -> ('c * 'd) tout)

    val return : ('a * 'b) -> tin -> ('a *'b) tout
    val fail : tin -> ('a * 'b) tout

    val (>||>) :
      (tin -> 'x tout) ->
      (tin -> 'x tout) ->
      (tin -> 'x tout)

    val (>|+|>) :
      (tin -> 'x tout) ->
      (tin -> 'x tout) ->
      (tin -> 'x tout)

    val (>&&>) : (tin -> bool) -> (tin -> 'x tout) -> (tin -> 'x tout)

    val mnot : (tin -> 'a tout) -> 'a -> tin -> 'a tout

    val tokenf : ('a A.mcode, B.info) matcher
    val tokenf_mck : (A.mcodekind, B.info) matcher

    val distrf_e :
      (A.meta_name A.mcode, B.expression) matcher
    val distrf_assignOp :
      (A.meta_name A.mcode, B.assignOp) matcher
    val distrf_binaryOp :
      (A.meta_name A.mcode, B.binaryOp) matcher
    val distrf_args :
      (A.meta_name A.mcode, (Ast_c.argument, Ast_c.il) either list) matcher
    val distrf_type :
      (A.meta_name A.mcode, Ast_c.fullType) matcher
    val distrf_params :
      (A.meta_name A.mcode,
       (Ast_c.parameterType, Ast_c.il) either list) matcher
    val distrf_param :
      (A.meta_name A.mcode, Ast_c.parameterType) matcher
    val distrf_ini :
      (A.meta_name A.mcode, Ast_c.initialiser) matcher
    val distrf_inis :
      (A.meta_name A.mcode, (Ast_c.initialiser, Ast_c.il) either list) matcher
    val distrf_decl :
      (A.meta_name A.mcode, Ast_c.declaration) matcher
    val distrf_field :
      (A.meta_name A.mcode, Ast_c.field) matcher
    val distrf_node :
      (A.meta_name A.mcode, F.node) matcher
    val distrf_fragments :
      (A.meta_name A.mcode, (Ast_c.string_fragment, Ast_c.il) either list)
      matcher
    val distrf_format :
      (A.meta_name A.mcode, Ast_c.string_format) matcher

    val distrf_define_params :
      (A.meta_name A.mcode, (string Ast_c.wrap, Ast_c.il) either list) matcher

    val distrf_enum_fields :
      (A.meta_name A.mcode, (B.oneEnumType, B.il) either list) matcher

    val distrf_struct_fields :
      (A.meta_name A.mcode, B.field list) matcher

    val distrf_cst :
      (A.meta_name A.mcode, (B.constant, string) either B.wrap) matcher

    val distrf_ident_list :
      (A.meta_name A.mcode, (Ast_c.name, Ast_c.il) either list) matcher

    val distrf_exec_code_list :
      (A.meta_name A.mcode, (Ast_c.exec_code, Ast_c.il) either list) matcher

    val distrf_attrs :
      (A.meta_name A.mcode, (Ast_c.attribute, Ast_c.il) either list) matcher

    val cocciExp :
      (A.expression, B.expression) matcher -> (A.expression, F.node) matcher

    val cocciExpExp :
      A.mcodekind ->
      (A.expression, B.expression) matcher ->
	(A.expression, B.expression) matcher

    val cocciTy :
      (A.fullType, B.fullType) matcher -> (A.fullType, F.node) matcher

    val cocciId :
      (A.ident, Ast_c.name) matcher -> (A.ident, F.node) matcher

    val cocciInit :
      (A.initialiser, B.initialiser) matcher -> (A.initialiser, F.node) matcher

    val envf :
      A.keep_binding -> A.inherited ->
      A.meta_name A.mcode * Ast_c.metavar_binding_kind *
	  (unit -> Ast_c.info list) ->
      (unit -> tin -> 'x tout) -> (tin -> 'x tout)

    val check_constraints :
	A.meta_name -> B.metavar_binding_kind -> A.constraints ->
	  (unit -> tin -> 'x tout) -> tin -> 'x tout

    val check_re_constraints :
	A.meta_name -> A.constraints ->
	  (unit -> tin -> 'x tout) -> tin -> 'x tout

    val check_constraints_ne :
      ('a, 'b) matcher -> 'a list -> 'b ->
	(unit -> tin -> 'x tout) -> (tin -> 'x tout)

    val all_bound : A.meta_name list -> (tin -> bool)

    val optional_storage_flag : (bool -> tin -> 'x tout) -> (tin -> 'x tout)
    val optional_qualifier_flag : (bool -> tin -> 'x tout) -> (tin -> 'x tout)
    val value_format_flag : (bool -> tin -> 'x tout) -> (tin -> 'x tout)
    val optional_declarer_semicolon_flag :
	(bool -> tin -> 'x tout) -> (tin -> 'x tout)
    val optional_attributes_flag :
	(bool -> tin -> 'x tout) -> (tin -> 'x tout)

  end

let satisfies_script_constraint (name, lang, params, pos, body) ida idb env =
  let values =
    try Some ((ida, idb) :: List.map (fun (p,_) -> (p, env p)) params)
    with Not_found -> None in
  match values with
    None -> false
  | Some args ->
      begin
	match lang with
	  "ocaml" -> Run_ocamlcocci.run_constraint name (List.map snd args)
	| "python" -> Pycocci.run_constraint args pos body
	| _ -> failwith "languages other than ocaml or python not supported"
      end

let rec extract_sub_constraints = function
    A.CstrAnd l ->
      let f (sub_acc, l_acc) c =
	let (sub, l') = extract_sub_constraints c in
	List.rev_append sub sub_acc, l' :: l_acc in
      let (sub, l') = List.fold_left f ([], []) l in
      sub, A.CstrAnd l'
  | A.CstrSub l -> l, A.CstrTrue
  | c -> [], c

let string_of_expression exp =
  let warning s = pr2_once ("WARNING: "^s); "" in
  match Ast_c.unwrap_expr exp with
    Ast_c.Ident (name) ->
      (match name with
	Ast_c.RegularName     rname -> Ast_c.unwrap_st rname
      | Ast_c.CppConcatenatedName _ ->
	  warning
	    "Unable to apply a constraint on a CppConcatenatedName identifier!"
      | Ast_c.CppVariadicName     _ ->
	  warning
	    "Unable to apply a constraint on a CppVariadicName identifier!"
      | Ast_c.CppIdentBuilder     _ ->
	  warning
	    "Unable to apply a constraint on a CppIdentBuilder identifier!")
  | Ast_c.Constant cst ->
      (match cst with
	Ast_c.String (str, _) -> str
      | Ast_c.MultiString strlist ->
	  warning "Unable to apply a constraint on a multistring constant!"
      | Ast_c.Char  (char , _) -> char
      | Ast_c.Int   (int  , _) -> int
      | Ast_c.Float (float, _) -> float
      | Ast_c.DecimalConst (d, n, p) ->
	  warning "Unable to apply a constraint on a decimal constant!")
  | Ast_c.StringConstant (cst,orig,w) -> orig
  | _ -> warning "Unable to apply a constraint on an expression!"

(*****************************************************************************)
(* Functor code, "Cocci vs C" *)
(*****************************************************************************)

module COCCI_VS_C =
  functor (X : PARAM) ->
struct

type ('a, 'b) matcher = 'a -> 'b  -> X.tin -> ('a * 'b) X.tout

let (>>=) = X.(>>=)
let return = X.return
let fail = X.fail

let (>||>) = X.(>||>)
let (>|+|>) = X.(>|+|>)
let (>&&>) = X.(>&&>)

let tokenf = X.tokenf

(* should be raise Impossible when called from transformation.ml *)
let fail2 () =
  match X.mode with
  | PatternMode -> fail
  | TransformMode -> raise (Impossible 22)


let (option: ('a,'b) matcher -> ('a option,'b option) matcher)= fun f t1 t2 ->
  match (t1,t2) with
  | (Some t1, Some t2) ->
      f t1 t2 >>= (fun t1 t2 ->
        return (Some t1, Some t2)
      )
  | (None, None) -> return (None, None)
  | _ -> fail

(* Dots are sometimes used as metavariables, since like metavariables they
can match other things.  But they no longer have the same type.  Perhaps these
functions could be avoided by introducing an appropriate level of polymorphism,
but I don't know how to declare polymorphism across functors *)
let dots2metavar (_,info,mcodekind,pos) =
  (("","..."),info,mcodekind,pos)
let metavar2dots (_,info,mcodekind,pos) = ("...",info,mcodekind,pos)
let metavar2ndots (_,info,mcodekind,pos) = ("<+...",info,mcodekind,pos)


(* ------------------------------------------------------------------------- *)
(* This has to be up here to allow adequate polymorphism *)

let match_len_value len leninfo =
  (match leninfo with
  | A.MetaListLen (lenname,constraints,lenkeep,leninherited) ->
      let max_min _ = failwith "no pos" in
      let mn = Ast_c.MetaListlenVal len in
      (fun k ->
	X.check_constraints (A.unwrap_mcode lenname) mn constraints
	  (fun () ->
	    X.envf lenkeep leninherited (lenname, mn, max_min) k))
  | A.CstListLen n ->
      if len = n
      then (function f -> f())
      else (function f -> fail)
  | A.AnyListLen -> function f -> f())

let match_len infos leninfo =
  let len = List.length infos in
  match_len_value len leninfo

let list_matcher match_dots rebuild_dots match_comma rebuild_comma
    match_metalist rebuild_metalist mktermval special_cases
    element distrf split_comma unsplit_comma get_iis lenfilter = fun eas ebs ->
  let rec loop = function
      [], [] -> return ([], [])
    | [], eb::ebs -> fail
    | ea::eas, ebs ->
	X.all_bound (A.get_inherited ea) >&&>
	let try_matches =
	  (match match_dots ea, ebs with
	    Some (mcode, optexpr), ys ->
          (* todo: if optexpr, then a WHEN and so may have to filter yys *)
              if optexpr <> None then failwith "not handling when in a list";

          (* '...' can take more or less the beginnings of the arguments *)
              let startendxs =
		(* if eas is empty there is only one possible match.
		   the same if eas is just a comma *)
		match eas with
		  [] -> [(ys,[])]
		| [c] when not(ys=[]) &&
		   (match match_comma c with Some _ -> true | None -> false) ->
		    let r = List.rev ys in
		    [(List.rev(List.tl r),[List.hd r])]
		| _ ->
		  Common.zip (Common.inits ys) (Common.tails ys) in
	      Some
		(startendxs +> List.fold_left (fun acc (startxs, endxs) ->
		  acc >||> (

              (* allow '...', and maybe its associated ',' to match nothing.
		 * for the associated ',' see below how we handle the EComma
		 * to match nothing.
              *)
		  (if startxs=[]
		  then
                    if mcode_contain_plus (mcodekind mcode)
                    then fail
                  (*failwith
		     "I have no token that I could accroche myself on"*)
                    else return (dots2metavar mcode, [])
		  else
                (* subtil: we don't want the '...' to match until the
                   * comma. cf -test pb_params_iso. We would get at
                   * "already tagged" error.
                   * this is because both f (... x, ...) and f (..., x, ...)
                   * would match a  f(x,3)  with our "optional-comma" strategy.
                *)
                    (match Common.last startxs with
                    | Right _ -> fail
                    | Left _ -> distrf (dots2metavar mcode) startxs))

		    >>= (fun mcode startxs ->
		      let mcode = metavar2dots mcode in
                      loop (eas, endxs) >>= (fun eas endxs ->
			return (
			(rebuild_dots (mcode, optexpr) +> A.rewrap ea) ::eas,
			startxs @ endxs
			  )))
		    )
		    ) fail)

	  | None,_ -> None)
	    +++
	    (match match_comma ea, ebs with
	    | Some ia1, Right ii::ebs ->
		Some
		  (let ib1 = tuple_of_list1 ii in
		  tokenf ia1 ib1 >>= (fun ia1 ib1 ->
		    loop (eas, ebs) >>= (fun eas ebs ->
		      return (
                      (rebuild_comma ia1 +> A.rewrap ea)::eas,
                      (Right [ib1])::ebs
				       )
			)))
	    | Some ia1, ebs ->
          (* allow ',' to matching nothing. optional comma trick *)
		Some
		  (if mcode_contain_plus (mcodekind ia1)
		  then fail
		  else loop (eas, ebs))
	    | None,_ -> None)
	    +++
	    (match match_metalist ea, ebs with
	      Some (ida,leninfo,constraints,keep,inherited,extra), ys ->
		let startendxs =
		  Common.zip (Common.inits ys) (Common.tails ys) in
		Some
		  (startendxs +> List.fold_left (fun acc (startxs, endxs) ->
		    acc >||> (
		    let ok =
		      if startxs=[]
		      then
			if mcode_contain_plus (mcodekind ida)
			then false
                    (* failwith "no token that I could accroche myself on" *)
			else true
		      else
			(match Common.last startxs with
			| Right _ -> false
			| Left _ -> true)
		    in
		    if not ok
		    then fail
		    else
		      let startxs' = unsplit_comma startxs in
		      (match lenfilter startxs' with
			None -> (function _ -> fail)
		      | Some infos -> match_len infos leninfo)
		      (fun () ->
			let max_min _ =
			  match startxs with
			    [] -> []
			  | _ -> get_iis startxs in
			(match extra with
			  Some extra ->
			    extra startxs' max_min
			      (fun _ -> return ((),()))
			| None -> return ((),()))
			  >>=
			(fun _ _ ->
			  X.envf keep inherited
			    (ida, mktermval startxs', max_min)
			    (fun () ->
			      if startxs=[]
			      then return (ida, [])
			      else distrf ida (split_comma startxs'))
			    >>= (fun ida startxs ->
			      loop (eas, endxs) >>= (fun eas endxs ->
				return (
				(rebuild_metalist ea
				   (ida,leninfo,constraints,keep,inherited))
				  +> A.rewrap ea::eas,
				startxs @ endxs
				  )))
				)
			    )
			)) fail)
	    | None,_ -> None)
	    +++
	    special_cases ea eas ebs in
	match try_matches with
	  Some res -> res
	| None ->
	    (match ebs with
	    | (Left eb)::ebs ->
		element ea eb >>= (fun ea eb ->
		  loop (eas, ebs) >>= (fun eas ebs ->
		    return (ea::eas, Left eb::ebs)))
	    | (Right y)::ys -> raise (Impossible 23)
	    | [] -> fail) in
  loop (eas,ebs)

(*---------------------------------------------------------------------------*)
(* toc:
 *  - expression
 *  - ident
 *  - arguments
 *  - parameters
 *  - declaration
 *  - initialisers
 *  - type
 *  - node
 *)

let arithA_of_arithB = function
  | B.Plus -> A.Plus
  | B.Minus -> A.Minus
  | B.Mul -> A.Mul
  | B.Div -> A.Div
  | B.Mod -> A.Mod
  | B.DecLeft -> A.DecLeft
  | B.DecRight -> A.DecRight
  | B.And -> A.And
  | B.Or -> A.Or
  | B.Xor -> A.Xor
  | B.Min -> A.Min
  | B.Max -> A.Max

let logicalA_of_logicalB = function
  | B.Inf -> A.Inf
  | B.Sup -> A.Sup
  | B.InfEq -> A.InfEq
  | B.SupEq -> A.SupEq
  | B.Eq -> A.Eq
  | B.NotEq -> A.NotEq
  | B.AndLog -> A.AndLog
  | B.OrLog -> A.OrLog

let assignOpA_of_assignOpB = function
  | B.SimpleAssign -> A.SimpleAssign (A.make_mcode "=")
  | B.OpAssign op -> A.OpAssign (A.make_mcode (arithA_of_arithB op))

let binaryOpA_of_binaryOpB = function
  | B.Arith op -> A.Arith (A.make_mcode (arithA_of_arithB op))
  | B.Logical op -> A.Logical (A.make_mcode (logicalA_of_logicalB op))

let assignOp_eq op1 op2 = match (op1, op2) with
  | A.SimpleAssign _, A.SimpleAssign _ -> true
  | A.OpAssign o1, A.OpAssign o2 -> (A.unwrap_mcode o1) = (A.unwrap_mcode o2)
  | _ -> false

let binaryOp_eq op1 op2 = match (op1, op2) with
  | A.Arith o1, A.Arith o2 -> (A.unwrap_mcode o1) = (A.unwrap_mcode o2)
  | A.Logical o1, A.Logical o2 -> (A.unwrap_mcode o1) = (A.unwrap_mcode o2)
  | _ -> false

(*---------------------------------------------------------------------------*)
let rec (rule_elem_node: (A.rule_elem, F.node) matcher) =
 fun re node ->

   let check_constraints cstr mida idb =
     X.check_constraints (A.unwrap_mcode mida) idb cstr in

let rec (expression: (A.expression, Ast_c.expression) matcher) =
 fun ea eb ->
   if A.get_test_exp ea && not (Ast_c.is_test eb) then
     fail
   else
  X.all_bound (A.get_inherited ea) >&&>
  let wa x = A.rewrap ea x in
  match A.unwrap ea, eb with

  (* general case: a MetaExpr can match everything *)
  | A.MetaExpr (ida,constraints,keep,opttypa,form,inherited,bitfield),
    (((expr, opttypb), ii) as expb) ->

      (* old: before have a MetaConst. Now we factorize and use 'form' to
       * differentiate between different cases *)
      let rec matches_id = function
	  B.Ident(name) -> true
	| B.Cast(ty,e) -> matches_id (B.unwrap_expr e)
	| _ -> false in
      let form_ok =
	match (form,expr) with
	  (A.ANY,_) -> true
	| (A.CONST,e) ->
	    let rec matches = function
		B.Constant(c) -> true
              | B.Ident (nameidb) ->
                  let s = Ast_c.str_of_name nameidb in
                  if s =~ "^[A-Z_][A-Z_0-9]*$"
                  then begin
		    pr2_once ("warning: " ^ s ^ " treated as a constant");
		    true
                  end
                  else false
	      | B.Cast(ty,e) -> matches (B.unwrap_expr e)
	      |	B.Unary(e,B.UnMinus) -> matches (B.unwrap_expr e)
	      | B.SizeOfExpr(exp) -> true
	      | B.SizeOfType(ty) -> true
	      | _ -> false in
	    matches e
	| (A.LocalID,e) ->
	    (matches_id e) &&
	    (match !opttypb with
	      (Some (_,Ast_c.LocalVar _),_) -> true
	    | _ -> false)
	| (A.GlobalID,e) ->
	    (matches_id e) &&
	    (match !opttypb with
	      (Some (_,Ast_c.LocalVar _),_) -> false
	    | _ -> true)
	| (A.ID,e) -> matches_id e in
      if form_ok
      then
	(let (opttypb,_testb) = !opttypb in
	match opttypa, opttypb with
        | None, _ -> return ((),())
        | Some _, None ->
            pr2_once ("Missing type information. Certainly a pb in " ^
                      "annotate_typer.ml");
            fail

        | Some tas, Some tb ->
            tas +> List.fold_left (fun acc ta ->
              acc >|+|> compatible_type ta tb) fail
	) >>=
	(fun () () -> match bitfield, fst !opttypb with
	  None, _ -> return ((), ())
	| Some _, None -> assert false
	| Some bitfield', Some tb ->
	    begin
	      match fst tb with
		(_, (Ast_c.FieldType (_, _, Some be), _)) ->
		  begin
		    match fst (fst be) with
		      Ast_c.Constant (Ast_c.Int (value, _)) ->
			match_len_value (int_of_string value) bitfield'
			  (fun () -> return ((), ()))
		    | _ ->
			pr2_once "Unable to evaluate bitfield expression";
			return ((), ())
		  end
	      | _ -> fail
	    end
	  ) >>=
	(fun () () ->
	  (* wraps on C code, so has types *)
	  let meta_expr_val l x = Ast_c.MetaExprVal(x,l,Ast_c.WITH_TYPES) in
	  begin
	    let l, constraints' = extract_sub_constraints constraints in
	    check_constraints constraints' ida
	      (B.MetaExprVal (eb, [], B.WITH_TYPES))
	      (fun () -> return (meta_expr_val l,()))
	  end)
	  >>=
	(fun wrapper () ->
	  let max_min _ = Lib_parsing_c.ii_of_expr expb in
	  X.envf keep inherited (ida, wrapper expb, max_min)
	    (fun () ->
	      X.distrf_e ida expb >>=
	      (fun ida expb ->
		return (
		A.MetaExpr (ida,constraints,keep,opttypa,form,inherited,None)+>
		A.rewrap ea,
		expb
		  ))
		))
      else fail

  (* old:
   * | A.MetaExpr(ida,false,opttypa,_inherited), expb ->
   *   D.distribute_mck (mcodekind ida) D.distribute_mck_e expb binding
   *
   * but bug! because if have not tagged SP, then transform without doing
   * any checks. Hopefully now have tagged SP technique.
   *)

  | A.AsExpr(exp,asexp), expb ->
      expression exp expb >>= (fun exp expb ->
      expression asexp expb >>= (fun asexp expb ->
	return(
	  ((A.AsExpr(exp,asexp)) +> wa,
	   expb))))
  | A.AsSExpr(exp,asstm), expb ->
      expression exp expb >>= (fun exp expb ->
      rule_elem_node asstm node >>= (fun asstm _node ->
	return(
	  ((A.AsSExpr(exp,asstm)) +> wa,
	   expb))))

  (* old:
   * | A.Edots _, _ -> raise Impossible.
   *
   * In fact now can also have the Edots inside normal expression, not
   * just in arg lists. in 'x[...];' less: in if(<... x ... y ...>)
   *)
  | A.Edots (mcode, None), expb    ->
      X.distrf_e (dots2metavar mcode) expb >>= (fun mcode expb ->
        return (
        A.Edots (metavar2dots mcode, None) +> A.rewrap ea ,
        expb
          ))


  | A.Edots (_, Some expr), _    -> failwith "not handling when on Edots"


  | A.Ident ida,   ((B.Ident (nameidb), typ),noii) ->
      assert (noii = []);
      ident_cpp DontKnow ida nameidb >>= (fun ida nameidb ->
        return (
        ((A.Ident ida)) +> wa,
        ((B.Ident (nameidb), typ),Ast_c.noii)
          ))




  | A.MetaErr _,     _ -> failwith "not handling MetaErr"

  (* todo?: handle some isomorphisms in int/float ? can have different
   * format : 1l can match a 1.
   *
   * todo: normally string can contain some metavar too, so should
   * recurse on the string
   *)
  | A.Constant (ia1), ((B.Constant (ib) , typ),ii) ->
      (* for everything except the String case where can have multi elems *)
      let do1 () =
        let ib1 = tuple_of_list1 ii in
        tokenf ia1 ib1 >>= (fun ia1 ib1 ->
          return (
            ((A.Constant ia1)) +> wa,
            ((B.Constant (ib), typ),[ib1])
          ))
      in
      (match term ia1, ib with
      | A.Int x, B.Int (y,_) ->
          X.value_format_flag (fun use_value_equivalence ->
            if use_value_equivalence
            then
              if equal_c_int x y
              then do1()
              else fail
            else
              if x = y
              then do1()
            else fail
          )
      | A.Char x, B.Char (y,_) when x = y  (* todo: use kind ? *)
          -> do1()
      | A.Float x, B.Float (y,_) when x = y (* todo: use floatType ? *)
          -> do1()
      | A.DecimalConst (x,lx,px),B.DecimalConst (y,ly,py)
	when x = y && lx = ly && px = py(*lx etc perhaps implied by x=y*)
          -> do1()

      |	 A.String sa, B.String (sb,_kind) when sa = sb ->
          (match ii with
          | [ib1] ->
            tokenf ia1 ib1 >>= (fun ia1 ib1 ->
              return (
                ((A.Constant ia1)) +> wa,
                ((B.Constant (ib), typ),[ib1])
              ))
          |  _ -> fail (* multi string, not handled *)
          )

      | _, B.MultiString _ -> (* todo cocci? *) fail
      | _, (B.String _ | B.Float _ | B.Char _ | B.Int _ | B.DecimalConst _) ->
	  fail
      )

  | A.StringConstant (lq,frags1,rq),
      ((B.StringConstant (frags2,os,w), typ), ii) ->
      let (ib1, ib2) = tuple_of_list2 ii in
      tokenf lq ib1 >>= (fun lq ib1 ->
      tokenf rq ib2 >>= (fun rq ib2 ->
      string_fragments (A.unwrap frags1) (B.split_nocomma frags2) >>=
	(fun frags1unwrap frags2splitted ->
        let frags1 = A.rewrap frags1 frags1unwrap in
	let frags2 = Ast_c.unsplit_nocomma frags2splitted in
	return (
	  ((A.StringConstant (lq,frags1,rq)) +> wa,
	   ((B.StringConstant (frags2,os,w), typ), [ib1; ib2]))))))

  | A.FunCall (ea, ia1, eas, ia2),  ((B.FunCall (eb, ebs), typ),ii) ->
      (* todo: do special case to allow IdMetaFunc, cos doing the
       * recursive call will be too late, match_ident will not have the
       * info whether it was a function. todo: but how detect when do
       * x.field = f; how know that f is a Func ? By having computed
       * some information before the matching!
       *
       * Allow match with FunCall containing types. Now ast_cocci allow
       * type in parameter, and morover ast_cocci allow f(...) and those
       * ... could match type.
       *)
      let (ib1, ib2) = tuple_of_list2 ii in
      expression ea eb >>= (fun ea eb ->
      tokenf ia1 ib1 >>= (fun ia1 ib1 ->
      tokenf ia2 ib2 >>= (fun ia2 ib2 ->
      arguments (seqstyle eas) (A.unwrap eas) ebs >>= (fun easunwrap ebs ->
        let eas = A.rewrap eas easunwrap in
        return (
          ((A.FunCall (ea, ia1, eas, ia2)) +> wa,
          ((B.FunCall (eb, ebs),typ), [ib1;ib2])
        ))))))

  | A.Assignment (ea1, opa, ea2, simple),
      ((B.Assignment (eb1, opb, eb2), typ),ii) ->
      if ii<>[] then failwith "In cocci_vs_c, ii for Assign should be empty."
      else (
      expression ea1 eb1 >>= (fun ea1 eb1 ->
      assignOp opa opb >>= (fun opa opb ->
      expression ea2 eb2 >>= (fun ea2 eb2 ->
        return (
          (A.Assignment (ea1, opa, ea2, simple)) +> wa,
          ((B.Assignment (eb1, opb, eb2), typ), [])
      )))))

  | A.Sequence (ea1, opa, ea2),
      ((B.Sequence (eb1, eb2), typ),ii) ->
      let (opbi) = tuple_of_list1 ii in
        expression ea1 eb1 >>= (fun ea1 eb1 ->
        expression ea2 eb2 >>= (fun ea2 eb2 ->
        tokenf opa opbi >>= (fun opa opbi ->
          return (
            (A.Sequence (ea1, opa, ea2)) +> wa,
            ((B.Sequence (eb1, eb2), typ), [opbi])
        ))))

  | A.CondExpr(ea1,ia1,ea2opt,ia2,ea3),((B.CondExpr(eb1,eb2opt,eb3),typ),ii) ->
      let (ib1, ib2) = tuple_of_list2 ii in
      expression ea1 eb1 >>= (fun ea1 eb1 ->
      option expression ea2opt eb2opt >>= (fun  ea2opt eb2opt ->
      expression ea3 eb3 >>= (fun ea3 eb3 ->
      tokenf ia1 ib1 >>= (fun ia1 ib1 ->
      tokenf ia2 ib2 >>= (fun ia2 ib2 ->
        return (
          ((A.CondExpr(ea1,ia1,ea2opt,ia2,ea3))) +> wa,
          ((B.CondExpr (eb1, eb2opt, eb3),typ), [ib1;ib2])
        ))))))

  (* todo?: handle some isomorphisms here ? *)
  | A.Postfix (ea, opa), ((B.Postfix (eb, opb), typ),ii) ->
      let opbi = tuple_of_list1 ii in
      if equal_fixOp (term opa) opb
      then
        expression ea eb >>= (fun ea eb ->
        tokenf opa opbi >>= (fun opa opbi ->
          return (
            ((A.Postfix (ea, opa))) +> wa,
            ((B.Postfix (eb, opb), typ),[opbi])
        )))
      else fail


  | A.Infix (ea, opa), ((B.Infix (eb, opb), typ),ii) ->
      let opbi = tuple_of_list1 ii in
      if equal_fixOp (term opa) opb
      then
        expression ea eb >>= (fun ea eb ->
        tokenf opa opbi >>= (fun opa opbi ->
          return (
            ((A.Infix (ea, opa))) +> wa,
            ((B.Infix (eb, opb), typ),[opbi])
        )))
      else fail

  | A.Unary (ea, opa), ((B.Unary (eb, opb), typ),ii) ->
      let opbi = tuple_of_list1 ii in
      if equal_unaryOp (term opa) opb
      then
        expression ea eb >>= (fun ea eb ->
        tokenf opa opbi >>= (fun opa opbi ->
          return (
            ((A.Unary (ea, opa))) +> wa,
            ((B.Unary (eb, opb), typ),[opbi])
        )))
      else fail

  | A.Binary (ea1, opa, ea2), ((B.Binary (eb1, opb, eb2), typ),ii) ->
      if ii <> []
      then failwith "cocci_vs_c: ii should be empty for binary operators."
      else
	expression ea1 eb1 >>= (fun ea1 eb1 ->
	binaryOp opa opb >>= (fun opa opb ->
	expression ea2 eb2 >>= (fun ea2 eb2 ->
	  return (
          ((A.Binary (ea1, opa, ea2))) +> wa,
          ((B.Binary (eb1, opb, eb2), typ),[]
	     )))))

  | A.Nested (ea1, opa, ea2), eb ->
      let rec loop eb =
	expression ea1 eb >|+|>
	(match eb with
	  ((B.Binary (eb1, opb, eb2), typ),ii) ->
	    if ii<>[]
	    then
	      failwith "cocci_vs_c: ii should be empty for nested operators."
            else
	      let left_to_right =
		expression ea1 eb1 >>= (fun ea1 eb1 ->
		binaryOp opa opb >>= (fun opa opb ->
		expression ea2 eb2 >>= (fun ea2 eb2 ->
		  return (
		  ((A.Binary (ea1, opa, ea2))) +> wa,
		  ((B.Binary (eb1, opb, eb2), typ),[]
		     ))))) in
	      let right_to_left =
		expression ea2 eb1 >>= (fun ea2 eb1 ->
                binaryOp opa opb >>= (fun opa opb ->
		expression ea1 eb2 >>= (fun ea1 eb2 ->
		  return (
		  ((A.Binary (ea2, opa, ea1))) +> wa,
		  ((B.Binary (eb1, opb, eb2), typ),[]
		     ))))) in
	      let in_left =
		expression ea2 eb2 >>= (fun ea2 eb2 ->
		binaryOp opa opb >>= (fun opa opb ->
		(* be last, to be sure the rest is marked *)
		loop eb1 >>= (fun ea1 eb1 ->
		  return (
		    ((A.Binary (ea1, opa, ea2))) +> wa,
		    ((B.Binary (eb1, opb, eb2), typ),[]
		       ))))) in
	      let in_right =
		expression ea2 eb1 >>= (fun ea2 eb1 ->
		binaryOp opa opb >>= (fun opa opb ->
		(* be last, to be sure the rest is marked *)
		loop eb2 >>= (fun ea1 eb2 ->
		  return (
		  ((A.Binary (ea2, opa, ea1))) +> wa,
		  ((B.Binary (eb1, opb, eb2), typ),[]
		     ))))) in
	      left_to_right >|+|> right_to_left >|+|> in_left >|+|> in_right
	    | _ -> fail) in
      loop eb

  (* todo?: handle some isomorphisms here ?  (with pointers = Unary Deref) *)
  | A.ArrayAccess (ea1, ia1, ea2, ia2),((B.ArrayAccess (eb1, eb2), typ),ii) ->
      let (ib1, ib2) = tuple_of_list2 ii in
      expression ea1 eb1 >>= (fun ea1 eb1 ->
      expression ea2 eb2 >>= (fun ea2 eb2 ->
      tokenf ia1 ib1 >>= (fun ia1 ib1 ->
      tokenf ia2 ib2 >>= (fun ia2 ib2 ->
        return (
          ((A.ArrayAccess (ea1, ia1, ea2, ia2))) +> wa,
          ((B.ArrayAccess (eb1, eb2),typ), [ib1;ib2])
        )))))

  (* todo?: handle some isomorphisms here ? *)
  | A.RecordAccess (ea, ia1, ida), ((B.RecordAccess (eb, idb), typ),ii) ->
      let (ib1) = tuple_of_list1 ii in
      ident_cpp DontKnow ida idb >>= (fun ida idb ->
      tokenf ia1 ib1 >>= (fun ia1 ib1 ->
      expression ea eb >>= (fun ea eb ->
        return (
          ((A.RecordAccess (ea, ia1, ida))) +> wa,
          ((B.RecordAccess (eb, idb), typ), [ib1])
        ))))



  | A.RecordPtAccess (ea,ia1,ida),((B.RecordPtAccess (eb, idb), typ), ii) ->
      let (ib1) = tuple_of_list1 ii in
      ident_cpp DontKnow ida idb >>= (fun ida idb ->
      tokenf ia1 ib1 >>= (fun ia1 ib1 ->
      expression ea eb >>= (fun ea eb ->
        return (
          ((A.RecordPtAccess (ea, ia1, ida))) +> wa,
          ((B.RecordPtAccess (eb, idb), typ), [ib1])
        ))))


  (* todo?: handle some isomorphisms here ?
   * todo?: do some iso-by-absence on cast ?
   *    by trying | ea, B.Case (typb, eb) -> match_e_e ea eb ?
   *)

  | A.Cast (ia1, typa, ia2, ea), ((B.Cast (typb, eb), typ),ii) ->
      let (ib1, ib2) = tuple_of_list2 ii in
      fullType typa typb >>= (fun typa typb ->
      expression ea eb >>= (fun ea eb ->
      tokenf ia1 ib1 >>= (fun ia1 ib1 ->
      tokenf ia2 ib2 >>= (fun ia2 ib2 ->
        return (
          ((A.Cast (ia1, typa, ia2, ea))) +> wa,
          ((B.Cast (typb, eb),typ),[ib1;ib2])
        )))))

  | A.SizeOfExpr (ia1, ea), ((B.SizeOfExpr (eb), typ),ii) ->
      let ib1 = tuple_of_list1 ii in
      expression ea eb >>= (fun ea eb ->
      tokenf ia1 ib1 >>= (fun ia1 ib1 ->
        return (
          ((A.SizeOfExpr (ia1, ea))) +> wa,
          ((B.SizeOfExpr (eb), typ),[ib1])
      )))

  | A.SizeOfType (ia1, ia2, typa, ia3), ((B.SizeOfType typb, typ),ii) ->
      let (ib1,ib2,ib3) = tuple_of_list3 ii in
      fullType typa typb >>= (fun typa typb ->
      tokenf ia1 ib1 >>= (fun ia1 ib1 ->
      tokenf ia2 ib2 >>= (fun ia2 ib2 ->
      tokenf ia3 ib3 >>= (fun ia3 ib3 ->
        return (
          ((A.SizeOfType (ia1, ia2, typa, ia3))) +> wa,
          ((B.SizeOfType (typb),typ),[ib1;ib2;ib3])
      )))))


  (* todo? iso ? allow all the combinations ? *)
  | A.Paren (ia1, ea, ia2), ((B.ParenExpr (eb), typ),ii) ->
      let (ib1, ib2) = tuple_of_list2 ii in
      expression ea eb >>= (fun ea eb ->
      tokenf ia1 ib1 >>= (fun ia1 ib1 ->
      tokenf ia2 ib2 >>= (fun ia2 ib2 ->
        return (
          ((A.Paren (ia1, ea, ia2))) +> wa,
          ((B.ParenExpr (eb), typ), [ib1;ib2])
      ))))

  | A.NestExpr(starter,exps,ender,None,true), eb ->
      (match A.unwrap exps with
	[exp] ->
	  (* if minus and trafo do nothing *)
	  X.cocciExpExp (A.get_mcodekind starter)
	    expression exp eb >>= (fun exp eb ->
	  (* minus and trafo will do something here *)
          X.distrf_e (dots2metavar starter) eb >>= (fun mcode eb ->
            return (
            (A.NestExpr
	       (metavar2ndots mcode,
		A.rewrap exps [exp],ender,None,true)) +> wa,
            eb
            )
	  ))
      |	_ ->
	  failwith
	    "for nestexpr, only handling the case with dots and only one exp")

  | A.NestExpr _,     _ ->
      failwith "only handling multi and no when code in a nest expr"

  (* only in arg lists or in define body *)
  | A.TypeExp _,    _ -> fail

  | A.Constructor (ia1, typa, ia2, ia), ((B.Constructor (typb, ib), typ),ii) ->
      let (ib1, ib2) = tuple_of_list2 ii in
      fullType typa typb >>= (fun typa typb ->
      initialiser ia ib >>= (fun ia ib ->
      tokenf ia1 ib1 >>= (fun ia1 ib1 ->
      tokenf ia2 ib2 >>= (fun ia2 ib2 ->
        return (
          ((A.Constructor (ia1, typa, ia2, ia))) +> wa,
          ((B.Constructor (typb, ib),typ),[ib1;ib2])
        )))))

  (* only in arg lists *)
  | A.MetaExprList _,    _
  | A.EComma _,    _
      ->
	raise (Impossible 24)

  | A.DisjExpr eas, eb ->
      (* remains inside nests, not sure if this is necessary *)
      eas +> List.fold_left (fun acc ea -> acc >|+|> (expression ea eb)) fail

  | A.ConjExpr eas, eb ->
      let rec loop acc_exp eb = function
	  [] -> return (A.ConjExpr (List.rev acc_exp) +> wa, eb)
	| e::es ->
	    expression e eb >>= (fun exp eb ->
	      loop (exp::acc_exp) eb es) in
      loop [] eb eas

  | A.OptExp e,_ ->
      Pretty_print_cocci.expression e;
      Format.print_newline();
      failwith
        (Printf.sprintf "not handling Opt/Multi on expr on line %d"
           (A.get_line e))

 (* Because of Exp can't put a raise Impossible; have to put a fail *)

 (* have not a counter part in coccinelle, for the moment *)
  | _, ((B.Sequence _,_),_)
  | _, ((B.StatementExpr _,_),_)
  | _, ((B.New _,_),_)
  | _, ((B.Delete _,_),_)
  | _, ((B.Defined _,_),_)
    -> fail


  | _,
     (((B.Cast (_, _)|B.ParenExpr _|B.SizeOfType _|B.SizeOfExpr _|
     B.Constructor (_, _)|
     B.RecordPtAccess (_, _)|
     B.RecordAccess (_, _)|B.ArrayAccess (_, _)|
     B.Binary (_, _, _)|B.Unary (_, _)|
     B.Infix (_, _)|B.Postfix (_, _)|
     B.Assignment (_, _, _)|B.CondExpr (_, _, _)|
     B.FunCall (_, _)|B.Constant _|B.StringConstant _|B.Ident _),
     _),_)
       -> fail

(* Allow ... to match nothing.  Useful in for loop headers and in array
declarations.  Put a metavariable to require it to match something. *)
and (eoption:
       (A.expression,B.expression) matcher ->
	 (A.expression option,B.expression option) matcher) = fun f t1 t2 ->
  match (t1,t2) with
    (Some t, None) ->
      (match A.unwrap t with
	A.Edots(edots,None) ->
	  return (t1,t2)
      | _ -> option f t1 t2)
  | _ -> option f t1 t2

and assignOp opa opb =
  match (A.unwrap opa), opb with
    A.SimpleAssign a, (B.SimpleAssign, opb') ->
      let opbi = tuple_of_list1 opb' in
      tokenf a opbi >>= (fun a opbi ->
	return
	  (A.rewrap opa (A.SimpleAssign a), (B.SimpleAssign, [opbi])))
  | A.OpAssign oa, (B.OpAssign ob,opb') ->
    if equal_arithOp oa ob
    then
      let opbi = tuple_of_list1 opb' in
      tokenf oa opbi >>= (fun oa opbi_ ->
	return
          (A.rewrap opa (A.OpAssign oa), (B.OpAssign ob,[opbi])))
    else fail
  | A.MetaAssign (mv, c, keep, inherited), _ ->
      let mv' = B.MetaAssignOpVal opb in
      check_constraints c mv mv'
	(fun () ->
	  let max_min _ = Lib_parsing_c.ii_of_assignOp opb in
	  X.envf keep inherited (mv,mv',max_min)
	    (fun () -> X.distrf_assignOp mv opb
		>>=
	      (fun mv opb ->
		return (A.MetaAssign(mv,c,keep,inherited)+> A.rewrap opa,opb))))
  | _ -> fail

and binaryOp opa opb =
  match (A.unwrap opa), opb with
    A.Arith oa, (B.Arith ob,opb') ->
      if equal_arithOp oa ob
      then
	let opbi = tuple_of_list1 opb' in
	tokenf oa opbi >>= (fun oa opbi ->
	  return
            (A.rewrap opa (A.Arith oa), (B.Arith ob,[opbi])))
      else fail
  | A.Logical oa, (B.Logical ob,opb') ->
      if equal_logicalOp oa ob
      then
	let opbi = tuple_of_list1 opb' in
	tokenf oa opbi >>= (fun oa opbi ->
	  return
            (A.rewrap opa (A.Logical oa), (B.Logical ob,[opbi])))
      else fail
  | A.MetaBinary (mv, c, keep, inherited), _ ->
      let mv' = B.MetaBinaryOpVal opb in
      check_constraints c mv mv'
	(fun () ->
	  let max_min _ = Lib_parsing_c.ii_of_binaryOp opb in
	  X.envf keep inherited (mv,mv',max_min)
            (fun () -> X.distrf_binaryOp mv opb
		>>=
	      (fun mv opb ->
		return (A.MetaBinary(mv,c,keep,inherited)+> A.rewrap opa,opb))))
  | _ -> fail

and string_fragments eas ebs =
  let match_dots ea =
    match A.unwrap ea with
      A.Strdots(mcode) -> Some (mcode, None)
    |  _ -> None in
  let build_dots (mcode,_) = A.Strdots(mcode) in
  let match_comma ea = None in
  let build_comma _ = failwith "no commas" in
  let match_metalist ea =
    match A.unwrap ea with
      A.MetaFormatList(pct,ida,leninfo,constraints,keep,inherited) ->
        Some(ida,leninfo,constraints,keep,inherited,None)
    |  _ -> None in
  let build_metalist ea (ida,leninfo,constraints,keep,inherited) =
    match A.unwrap ea with
      A.MetaFormatList(pct,_,_,_,_,_) ->
	A.MetaFormatList(pct,ida,leninfo,constraints,keep,inherited)
    | _ -> failwith "build metalist: not possible" in
  let mktermval v = Ast_c.MetaFragListVal v in
  let list_filter_function l =
    Some
      (List.filter
	 (function
	     B.FormatFragment _,_ -> true
	   | _ -> false)
	 l) in
  let special_cases ea eas ebs = None in
  list_matcher match_dots build_dots match_comma build_comma
    match_metalist build_metalist mktermval
    special_cases string_fragment X.distrf_fragments
    B.split_nocomma B.unsplit_nocomma
    Lib_parsing_c.ii_of_fragments list_filter_function eas ebs

and string_fragment ea (eb,ii) =
  X.all_bound (A.get_inherited ea) >&&>
  let wa x = A.rewrap ea x in
  match A.unwrap ea,eb with
    A.ConstantFragment(str1), B.ConstantFragment(str2)
      when A.unwrap_mcode str1 = str2 ->
      let ib1 = tuple_of_list1 ii in
      tokenf str1 ib1 >>= (fun str1 ib1 ->
	return
	  (A.ConstantFragment(str1) +> wa,
	   (B.ConstantFragment(str2),[ib1])))
  | A.FormatFragment(pct1,fmt1), B.FormatFragment(fmt2) ->
      let ib1 = tuple_of_list1 ii in
      tokenf pct1 ib1 >>= (fun pct1 ib1 ->
      string_format fmt1 fmt2 >>= (fun fmt1 fmt2 ->
	return
	  (A.FormatFragment(pct1,fmt1) +> wa,
	   (B.FormatFragment(fmt2), [ib1]))))
  | A.Strdots dots, eb -> failwith "string_fragment: strdots: not possible"
  | A.MetaFormatList(pct1,name1,lenname1,_,_,_), eb ->
      failwith "string_fragment: meta format list: not possible"
  | _,_ -> fail

and string_format ea eb =
  X.all_bound (A.get_inherited ea) >&&>
  let wa x = A.rewrap ea x in
  match A.unwrap ea,eb with
    A.ConstantFormat(str1), (B.ConstantFormat(str2),ii) ->
      let ib1 = tuple_of_list1 ii in
      if A.unwrap_mcode str1 = str2
      then
	tokenf str1 ib1 >>= (fun str1 ib1 ->
	  return
	    (A.ConstantFormat(str1) +> wa,
	     (B.ConstantFormat(str2),[ib1])))
      else fail
  | A.MetaFormat(ida,constraints,keep,inherited),(B.ConstantFormat(str2),ii) ->
      check_constraints constraints ida (B.MetaIdVal str2)
      (fun () ->
	let max_min _ = Lib_parsing_c.ii_of_format eb in
	X.envf keep inherited (ida,Ast_c.MetaFmtVal eb,max_min) (fun () ->
          X.distrf_format ida eb
            ) >>= (fun ida eb ->
              return (A.MetaFormat(ida,constraints,keep,inherited) +> wa,eb)))

(* ------------------------------------------------------------------------- *)

and exec_code_list eas ebs =
  let match_dots ea =
    match A.unwrap ea with
      A.ExecDots(mcode) -> Some (mcode, None)
    |  _ -> None in
  let build_dots (mcode,_) = A.ExecDots(mcode) in
  let match_comma ea = None in
  let build_comma _ = failwith "no commas" in
  let match_metalist ea = None in
  let build_metalist ea (ida,leninfo,constraints,keep,inherited) =
    failwith "no metalist" in
  let mktermval v = failwith "no metavariables" in
  let special_cases ea eas ebs = None in
  list_matcher match_dots build_dots match_comma build_comma
    match_metalist build_metalist mktermval
    special_cases exec_code X.distrf_exec_code_list
    B.split_nocomma B.unsplit_nocomma
    Lib_parsing_c.ii_of_exec_code_list (function x -> Some x) eas ebs

and exec_code ea (eb,ii) =
  X.all_bound (A.get_inherited ea) >&&>
  let wa x = A.rewrap ea x in
  match A.unwrap ea,eb with
    A.ExecEval(colon1,id1),B.ExecEval(id2) ->
      let colon2 = tuple_of_list1 ii in
      tokenf colon1 colon2 >>= (fun colon1 colon2 ->
      expression id1 id2 >>= (fun id1 id2 ->
	return(
	  A.ExecEval(colon1,id1) +> wa,
	  (B.ExecEval(id2),[colon2]))))
  | A.ExecToken(tok1),B.ExecToken ->
      let tok2 = tuple_of_list1 ii in
      tokenf tok1 tok2 >>= (fun tok1 tok2 ->
	return(
	  A.ExecToken(tok1) +> wa,
	  (B.ExecToken,[tok2])))
  | A.ExecDots(dots), eb -> failwith "exec_code: exec dots: not possible"
  | _,_ -> fail

(* ------------------------------------------------------------------------- *)
and (ident_cpp: info_ident -> (A.ident, B.name) matcher) =
 fun infoidb ida idb ->
   match idb with
   | B.RegularName (s, iis) ->
       let iis = tuple_of_list1 iis in
       ident infoidb ida (s, iis) >>= (fun ida (s,iis) ->
         return (
           ida,
           (B.RegularName (s, [iis]))
         ))
   | B.CppConcatenatedName _ | B.CppVariadicName _ |B.CppIdentBuilder _
       ->
	 (* This should be moved to the Id case of ident.  Metavariables
	 should be allowed to be bound to such variables.  But doing so
	 would require implementing an appropriate distr function *)
	 fail

and (ident: info_ident -> (A.ident, string * Ast_c.info) matcher) =
 fun infoidb ida ((idb, iib) as ib) -> (* (idb, iib) as ib *)
  X.all_bound (A.get_inherited ida) >&&>
  match A.unwrap ida with
  | A.Id sa ->
      if (term sa) = idb then
      tokenf sa iib >>= (fun sa iib ->
        return (
          ((A.Id sa)) +> A.rewrap ida,
          (idb, iib)
        ))
      else fail

  | A.MetaId(mida,constraints,keep,inherited) ->
      check_constraints constraints mida (B.MetaIdVal idb)
      (fun () ->
      let max_min _ = [iib] in
      (* use drop_pos for ids so that the pos is not added a second time in
	 the call to tokenf *)
      X.envf keep inherited (A.drop_pos mida, Ast_c.MetaIdVal idb, max_min)
	(fun () ->
        tokenf mida iib >>= (fun mida iib ->
          return (
            ((A.MetaId (mida, constraints, keep, inherited)) +> A.rewrap ida,
            (idb, iib)
            )))
      ))

  | A.MetaFunc(mida,constraints,keep,inherited) ->
      let is_function _ =
	check_constraints constraints mida (B.MetaIdVal idb)
	(fun () ->
          let max_min _ = [iib] in
          X.envf keep inherited (A.drop_pos mida,Ast_c.MetaFuncVal idb,max_min)
	    (fun () ->
            tokenf mida iib >>= (fun mida iib ->
              return (
                ((A.MetaFunc(mida,constraints,keep,inherited)))+>A.rewrap ida,
                (idb, iib)
              ))
          )) in
      (match infoidb with
      | LocalFunction | Function -> is_function()
      | DontKnow ->
	  failwith "MetaFunc, need more semantic info about id"
	  (* the following implementation could possibly be useful, if one
	     follows the convention that a macro is always in capital letters
	     and that a macro is not a function.
	  (if idb =~ "^[A-Z_][A-Z_0-9]*$" then fail else is_function())*)
      )

  | A.MetaLocalFunc(mida,constraints,keep,inherited) ->
      (match infoidb with
      | LocalFunction ->
	  check_constraints constraints mida (B.MetaIdVal idb)
	  (fun () ->
          let max_min _ = [iib] in
          X.envf keep inherited
	    (A.drop_pos mida,Ast_c.MetaLocalFuncVal idb, max_min)
	    (fun () ->
            tokenf mida iib >>= (fun mida iib ->
              return (
                ((A.MetaLocalFunc(mida,constraints,keep,inherited)))
		   +> A.rewrap ida,
                (idb, iib)
              ))
          ))
      | Function -> fail
      | DontKnow -> failwith "MetaLocalFunc, need more semantic info about id"
      )

  | A.AsIdent(id,asid) ->
      ident infoidb id ib >>= (fun id ib ->
      ident infoidb asid ib >>= (fun asid ib ->
	return(
	  ((A.AsIdent(id,asid)) +> A.rewrap ida,
	   ib))))

  (* needed with identifier rule header *)
  | A.DisjId ias ->
      ias +> List.fold_left (fun acc ia -> acc >|+|> (ident infoidb ia ib)) fail
  | A.ConjId ias ->
      let rec loop acc_id ib = function
	  [] -> return (A.ConjId (List.rev acc_id) +> A.rewrap ida, ib)
	| ia::ias ->
	    ident infoidb ia ib >>= (fun ia ib ->
	      loop (ia::acc_id) ib ias) in
      loop [] ib ias

  | A.OptIdent _ -> failwith "not handling Opt for ident"

(* ------------------------------------------------------------------------- *)
and (arguments: sequence ->
  (A.expression list, Ast_c.argument Ast_c.wrap2 list) matcher) =
  fun seqstyle eas ebs ->
    match seqstyle with
    | Unordered -> failwith "not handling ooo"
    | Ordered ->
	arguments_bis eas (Ast_c.split_comma ebs) >>= (fun eas ebs_splitted ->
          return (eas, (Ast_c.unsplit_comma ebs_splitted))
	    )
(* because '...' can match nothing, need to take care when have
   * ', ...'   or '...,'  as in  f(..., X, Y, ...). It must match
   * f(1,2) for instance.
   * So I have added special cases such as (if startxs = []) and code
   * in the Ecomma matching rule.
   *
   * old: Must do some try, for instance when f(...,X,Y,...) have to
   * test the transfo for all the combinations    and if multiple transfo
   * possible ? pb ? => the type is to return a expression option ? use
   * some combinators to help ?
   * update: with the tag-SP approach, no more a problem.
*)

and arguments_bis = fun eas ebs ->
  let match_dots ea =
    match A.unwrap ea with
      A.Edots(mcode, optexpr) -> Some (mcode, optexpr)
    | _ -> None in
  let build_dots (mcode, optexpr) = A.Edots(mcode, optexpr) in
  let match_comma ea =
    match A.unwrap ea with
      A.EComma ia1 -> Some ia1
    | _ -> None in
  let build_comma ia1 = A.EComma ia1 in
  let match_metalist ea =
    match A.unwrap ea with
      A.MetaExprList(ida,leninfo,constraints,keep,inherited) ->
	Some(ida,leninfo,constraints,keep,inherited,None)
    | _ -> None in
  let build_metalist _ (ida,leninfo,constraints,keep,inherited) =
    A.MetaExprList(ida,leninfo,constraints,keep,inherited) in
  let mktermval v = Ast_c.MetaExprListVal v in
  let special_cases ea eas ebs = None in
  list_matcher match_dots build_dots match_comma build_comma
    match_metalist build_metalist mktermval
    special_cases argument X.distrf_args B.split_comma  B.unsplit_comma
    Lib_parsing_c.ii_of_args (function x -> Some x) eas ebs

and argument arga argb =
  X.all_bound (A.get_inherited arga) >&&>
  match A.unwrap arga, argb with
  | A.TypeExp tya,
    Right (B.ArgType {B.p_register=b,iib; p_namei=sopt;p_type=tyb}) ->
      if b || sopt <> None
      then
        (* failwith "the argument have a storage and ast_cocci does not have"*)
        fail
      else
        (* b = false and sopt = None *)
        fullType tya tyb >>= (fun tya tyb ->
          return (
            (A.TypeExp tya) +> A.rewrap arga,
            (Right (B.ArgType {B.p_register=(b,iib);
                               p_namei=sopt;
                               p_type=tyb;}))
        ))

  | A.TypeExp tya,  _                                  -> fail
  | _,              Right (B.ArgType _) -> fail
  | _, Left argb ->
      expression arga argb >>= (fun arga argb ->
        return (arga, Left argb)
      )
  | _, Right (B.ArgAction y) -> fail

(* ------------------------------------------------------------------------- *)
(* todo? facto code with argument ? *)
and (parameters: sequence ->
      (A.parameterTypeDef list, Ast_c.parameterType Ast_c.wrap2 list)
        matcher) =
 fun seqstyle eas ebs ->
  match seqstyle with
  | Unordered -> failwith "not handling ooo"
  | Ordered ->
      parameters_bis eas (Ast_c.split_comma ebs) >>= (fun eas ebs_splitted ->
        return (eas, (Ast_c.unsplit_comma ebs_splitted))
      )

and parameters_bis eas ebs =
  let match_dots ea =
    match A.unwrap ea with
      A.Pdots(mcode) -> Some (mcode, None)
    | _ -> None in
  let build_dots (mcode, _optexpr) = A.Pdots(mcode) in
  let match_comma ea =
    match A.unwrap ea with
      A.PComma ia1 -> Some ia1
    | _ -> None in
  let build_comma ia1 = A.PComma ia1 in
  let match_metalist ea =
    let rec loop acc p =
      match A.unwrap p with
	A.AsParam(p,e) -> loop (e :: acc) p
      | A.MetaParamList(ida,leninfo,constraints,keep,inherited) ->
	  Some ((ida,leninfo,constraints,keep,inherited),acc)
      | _ -> None in
    match loop [] ea with
      Some ((ida,leninfo,constraints,keep,inherited),ids) ->
	(match ids with
	  [] -> Some(ida,leninfo,constraints,keep,inherited,None)
	| _ ->
	    let extra vl max_min k =
	      let vl =
		Ast_c.MetaExprListVal
		     (List.map
			(function (v,i) ->
			  match v.Ast_c.p_namei with
			    Some name ->
			      (Left(Ast_c.mk_e (B.Ident name) Ast_c.noii),i)
			  | None -> failwith "no name in parameter list")
			vl) in
	      let rec loop = function
		  [] -> k ()
		| x::xs ->
		    (match A.unwrap x with
		      A.MetaExprList
			(ida,A.AnyListLen,constraints,keep, inherited) ->
			  check_constraints constraints ida vl
			    (fun ()->
			      X.envf keep inherited
				(ida, vl, max_min)
				(fun () -> loop xs))
		    | A.MetaExprList _ ->
			failwith "length not supported"
		    | _ -> failwith "unexpected expression") in
	      loop ids in
	    Some(ida,leninfo,constraints,keep,inherited,Some extra))
    | None -> None in
  let rec build_metalist ea (ida,leninfo,constraints,keep,inherited) =
    match A.unwrap ea with
      A.MetaParamList _ ->
	A.MetaParamList(ida,leninfo,constraints,keep,inherited)
    | A.AsParam(p,e) ->
	A.AsParam(A.rewrap p
		    (build_metalist p (ida,leninfo,constraints,keep,inherited)),
		  e)
    | _ -> failwith "parameters: build metalist: not possible" in
  let mktermval v = Ast_c.MetaParamListVal v in
  let special_cases ea eas ebs =
    (* a case where one smpl parameter matches a list of C parameters *)
    match A.unwrap ea,ebs with
      A.VoidParam ta, ys ->
	Some
          (match eas, ebs with
          | [], [Left eb] ->
              let {B.p_register=(hasreg,iihasreg);
                    p_namei = idbopt;
                    p_type=tb; } = eb in

              if idbopt = None && not hasreg
              then
                match tb with
                | (qub, (B.BaseType B.Void,_)) ->
                    fullType ta tb >>= (fun ta tb ->
                      return (
                      [(A.VoidParam ta) +> A.rewrap ea],
                      [Left {B.p_register=(hasreg, iihasreg);
                              p_namei = idbopt;
                              p_type = tb;}]
			))
                | _ -> fail
              else fail
          | _ -> fail)
    | _ -> None in
  list_matcher match_dots build_dots match_comma build_comma
    match_metalist build_metalist mktermval
    special_cases parameter X.distrf_params
    B.split_comma B.unsplit_comma
    Lib_parsing_c.ii_of_params (function x -> Some x) eas ebs

(*
   let split_register_param = fun (hasreg, idb, ii_b_s) ->
   match hasreg, idb,  ii_b_s with
   | false, Some s, [i1] -> Left (s, [], i1)
   | true, Some s, [i1;i2] -> Left (s, [i1], i2)
   | _, None, ii -> Right ii
   | _ -> raise Impossible
*)


and parameter = fun parama paramb ->
  match A.unwrap parama, paramb with
    A.MetaParam (ida,constraints,keep,inherited), eb ->
      (* todo: use quaopt, hasreg ? *)
      let max_min _ = Lib_parsing_c.ii_of_param eb in
      let mn = Ast_c.MetaParamVal eb in
      check_constraints constraints ida mn
	(fun () ->
	  X.envf keep inherited (ida,mn,max_min) (fun () ->
            X.distrf_param ida eb)
	    >>= (fun ida eb ->
	      return
		(A.MetaParam(ida,constraints,keep,inherited)+>
		 A.rewrap parama,eb)))
  | A.Param (typa, idaopt), eb ->
      let {B.p_register = (hasreg,iihasreg);
	    p_namei = nameidbopt;
	    p_type = typb;} = paramb in

      fullType typa typb >>= (fun typa typb ->
	match idaopt, nameidbopt with
	| Some ida, Some nameidb ->
      (* todo: if minus on ida, should also minus the iihasreg ? *)
	    ident_cpp DontKnow ida nameidb >>= (fun ida nameidb ->
              return (
              A.Param (typa, Some ida)+> A.rewrap parama,
              {B.p_register = (hasreg, iihasreg);
		p_namei = Some (nameidb);
		p_type = typb}
		))

	| None, None ->
	    return (
            A.Param (typa, None)+> A.rewrap parama,
            {B.p_register=(hasreg,iihasreg);
              p_namei = None;
              p_type = typb;}
	      )
  (* why handle this case ? because of transform_proto ? we may not
   * have an ident in the proto.
   * If have some plus on ida ? do nothing about ida ?
   *)
 (* not anymore !!! now that julia is handling the proto.
  | _, Right iihasreg ->
      return (
        (idaopt, typa),
        ((hasreg, None, typb), iihasreg)
      )
 *)

	| Some _, None -> fail
	| None, Some _ -> fail)
  | A.OptParam _, _ ->
      failwith "not handling Opt for Param"
  | _ -> fail

(* ------------------------------------------------------------------------- *)
and (declaration: (A.mcodekind * bool * A.declaration,B.declaration) matcher) =
 fun (mckstart, allminus, decla) declb ->
  X.all_bound (A.get_inherited decla) >&&>
  match A.unwrap decla, declb with

  (* Un MetaDecl est introduit dans l'asttoctl pour sauter au dessus
   * de toutes les declarations qui sont au debut d'un fonction et
   * commencer le reste du match au premier statement. Alors, ca matche
   * n'importe quelle declaration. On n'a pas besoin d'ajouter
   * quoi que ce soit dans l'environnement. C'est une sorte de DDots.
   *
   * When the SP want to remove the whole function, the minus is not
   * on the MetaDecl but on the MetaRuleElem. So there should
   * be no transform of MetaDecl, just matching are allowed.
   *)

  | A.MetaDecl (ida,constraints,keep,inherited), _ ->
      let max_min _ = Lib_parsing_c.ii_of_decl declb in
      let mv = Ast_c.MetaDeclVal(declb,declb) in
      check_constraints constraints ida mv
	(fun () ->
	  X.envf keep inherited (ida, mv, max_min)
	    (fun () ->
              X.distrf_decl ida declb)
	    >>= (fun ida declb ->
	      return ((mckstart, allminus,
		       (A.MetaDecl (ida, constraints,keep, inherited))+>
		       A.rewrap decla),
		      declb)))

  | A.AsDecl(dec,asdec), decb ->
      declaration (mckstart, allminus, dec) decb >>=
      (fun (mckstart, allminus, dec) decb ->
	let asmckstart = A.CONTEXT(A.NoPos,A.NOTHING) in
      declaration (asmckstart,false,asdec) decb >>= (fun (_,_,asdec) decb ->
	return(
	((mckstart, allminus,
	  (A.AsDecl(dec,asdec)) +> A.rewrap decla),
	 decb))))

  | _, (B.DeclList ([var], iiptvirgb::iifakestart::iisto)) ->
      onedecl allminus decla (var,iiptvirgb,iisto) >>=
      (fun decla (var,iiptvirgb,iisto)->
        X.tokenf_mck mckstart iifakestart >>= (fun mckstart iifakestart ->
          return (
            (mckstart, allminus, decla),
            (B.DeclList ([var], iiptvirgb::iifakestart::iisto))
          )))

  | _, (B.DeclList (xs, (iiptvirgb::iifakestart::iisto))) ->
      let indexify l =
	let rec loop n = function
	    [] -> []
	  | x::xs -> (n,x)::(loop (n+1) xs) in
	loop 0 l in
      let rec repln n vl cur = function
	  [] -> []
	| x::xs ->
	    if n = cur then vl :: xs else x :: (repln n vl (cur+1) xs) in
      let doit _ =
	(indexify xs) +> List.fold_left (fun acc (n,var) ->
	  (* consider all possible matches *)
          acc >||> (function tin -> (
            onedecl allminus decla (var, iiptvirgb, iisto) >>=
            (fun decla (var, iiptvirgb, iisto) ->
	      (* tokenf has to be after the onedecl, because ondecl
		 detects whether there is actually a match and the
		 tokenf should be done *)
              X.tokenf_mck mckstart iifakestart >>=
	      (fun mckstart iifakestart ->
                return (
                (mckstart, allminus, decla),
		    (* adjust the variable that was chosen *)
                (B.DeclList (repln n var 0 xs,
			     iiptvirgb::iifakestart::iisto))
                  )))) tin))
          fail in
      if !Flag.sgrep_mode2(*X.mode = PatternMode *) ||
         A.get_safe_decl decla = A.Safe ||
	 (A.get_safe_decl decla = A.NoStorage && iisto = [])
      then doit()
      else
	begin
	  (* rather clunky... we only want to print the warning message if
	     there is a match *)
	  let firstii = iiptvirgb in
	  let contextified_decla =
	    let mcode (x,info,mc,pos) =
	      let newmc =
		match mc with
		  A.MINUS(pos,_,_,_)
		| A.CONTEXT(pos,_) -> A.CONTEXT(pos,A.NOTHING)
		| _ -> failwith "only minus/context expected in pattern" in
	      (x,info,newmc,pos) in
	    let donothing r k e = k e in
	    let v =
	      Visitor_ast.rebuilder
		mcode mcode mcode mcode mcode mcode mcode mcode mcode
		mcode mcode mcode mcode mcode
		donothing donothing donothing donothing donothing donothing
		donothing donothing donothing donothing donothing donothing
		donothing donothing donothing donothing donothing donothing
		donothing donothing donothing donothing donothing donothing
	        donothing donothing in
	    v.Visitor_ast.rebuilder_declaration decla in

	  xs +> List.fold_left (fun acc var ->
	  (* consider all possible matches *)
            (function tin -> (
              onedecl allminus contextified_decla (var, iiptvirgb, iisto) >>=
              (fun _ _ ->
		pr2_once
		  (Printf.sprintf "%s: %d: %s"
		     (Ast_c.file_of_info firstii) (Ast_c.line_of_info firstii)
		     "More than one variable in the declaration, and so it cannot be transformed.  Check that there is no transformation on the type or the ;.  Consider using ++ for an addition.");
		fail)) tin))
	      fail
	end

  | A.MacroDecl (stoa,sa,lpa,eas,rpa,enda),
	B.MacroDecl ((stob,sb,ebs,true),ii) ->
      let (iisb, lpb, rpb, iiendb, iifakestart, iistob) =
        (match ii with
        | iisb::lpb::rpb::iiendb::iifakestart::iisto ->
            (iisb,lpb,rpb,iiendb, iifakestart,iisto)
        | _ -> raise (Impossible 26)
        ) in
        storage_optional_allminus allminus
          stoa ((stob, false), iistob) >>= (fun stoa ((stob, _), iistob) ->
        X.tokenf_mck mckstart iifakestart >>= (fun mckstart iifakestart ->
	ident DontKnow sa (sb, iisb) >>= (fun sa (sb, iisb) ->
        tokenf lpa lpb >>= (fun lpa lpb ->
        tokenf rpa rpb >>= (fun rpa rpb ->
        tokenf enda iiendb >>= (fun enda iiendb ->
        arguments (seqstyle eas) (A.unwrap eas) ebs >>= (fun easunwrap ebs ->
        let eas = A.rewrap eas easunwrap in

          return (
            (mckstart, allminus,
            (A.MacroDecl (stoa,sa,lpa,eas,rpa,enda)) +> A.rewrap decla),
            (B.MacroDecl ((stob,sb,ebs,true),
                         [iisb;lpb;rpb;iiendb;iifakestart] @ iistob))
          ))))))))

  | A.MacroDecl (None,sa,lpa,eas,rpa,enda),
      B.MacroDecl ((B.NoSto,sb,ebs,false),ii) ->
	(* This is for macrodecls with no semicolons, which come from
	   a parsing rule that deals with function prototypes with no
	   return type.  That parsing rule would have a conflict if there
	   were storage, so there is no point to treat the possibility of
	   storage here. *)
      X.optional_declarer_semicolon_flag (fun optional_declarer_semicolon ->
      match mcodekind enda, optional_declarer_semicolon with
	A.CONTEXT (_,A.NOTHING), true ->
	  let (iisb, lpb, rpb, iifakestart) =
            (match ii with
            | [iisb;lpb;rpb;iifakestart] ->
		(iisb,lpb,rpb,iifakestart)
            | _ -> raise (Impossible 27)) in
	    X.tokenf_mck mckstart iifakestart >>=
	    (fun mckstart iifakestart ->
	      ident DontKnow sa (sb, iisb) >>= (fun sa (sb, iisb) ->
	      tokenf lpa lpb >>= (fun lpa lpb ->
	      tokenf rpa rpb >>= (fun rpa rpb ->
	      arguments (seqstyle eas) (A.unwrap eas) ebs >>=
		(fun easunwrap ebs ->
		  let eas = A.rewrap eas easunwrap in

		  return (
		  (mckstart, allminus,
		   (A.MacroDecl (None,sa,lpa,eas,rpa,enda)) +> A.rewrap decla),
		  (B.MacroDecl ((B.NoSto,sb,ebs,false),
				[iisb;lpb;rpb;iifakestart]))
		  ))))))
      | _ -> fail)

  | A.MacroDeclInit (stoa,sa,lpa,eas,rpa,weqa,inia,enda),
      B.MacroDeclInit ((stob,sb,ebs,inib),ii) ->
      let (iisb, lpb, rpb, weqb, iiendb, iifakestart, iistob) =
        (match ii with
        |  iisb::lpb::rpb::weqb::iiendb::iifakestart::iisto ->
            (iisb,lpb,rpb,weqb,iiendb, iifakestart,iisto)
        |  _ -> raise (Impossible 28)
        ) in
        storage_optional_allminus allminus
          stoa ((stob, false), iistob) >>= (fun stoa ((stob, _), iistob) ->
        X.tokenf_mck mckstart iifakestart >>= (fun mckstart iifakestart ->
        ident DontKnow sa (sb, iisb) >>= (fun sa (sb, iisb) ->
        tokenf lpa lpb >>= (fun lpa lpb ->
        tokenf rpa rpb >>= (fun rpa rpb ->
        tokenf weqa weqb >>= (fun weqa weqb ->
        tokenf enda iiendb >>= (fun enda iiendb ->
        arguments (seqstyle eas) (A.unwrap eas) ebs >>= (fun easunwrap ebs ->
	initialiser inia inib >>= (fun inia inib ->
        let eas = A.rewrap eas easunwrap in

          return (
            (mckstart, allminus,
             (A.MacroDeclInit(stoa,sa,lpa,eas,rpa,weqa,inia,enda)) +>
	     A.rewrap decla),
            (B.MacroDeclInit ((stob,sb,ebs,inib),
                         [iisb;lpb;rpb;iiendb;iifakestart] @ iistob))
          ))))))))))


  | A.MacroDeclInit (stoa,sa,lpa,eas,rpa,weqa,inia,enda), _ -> fail

  | _, (B.MacroDecl _ |B.MacroDeclInit _ |B.DeclList _) -> fail


and annotated_decl decla declb =
  match A.unwrap decla with
    A.DElem(mckstart, allminus, decl) ->
      declaration (mckstart, allminus, decl) declb >>=
      fun (mckstart, allminus, decl) declb ->
	return
	  (A.DElem(mckstart, allminus, decl) +> A.rewrap decla,
	   declb)

and onedecl = fun allminus decla (declb, iiptvirgb, iistob) ->
 X.all_bound (A.get_inherited decla) >&&>
 match A.unwrap decla, declb with

 (* kind of typedef iso, we must unfold, it's for the case
  * T { }; that we want to match against typedef struct { } xx_t;
  *)

 | A.TyDecl (tya0, ptvirga),
   ({B.v_namei = Some (nameidb, B.NoInit);
     B.v_type = typb0;
     B.v_storage = (B.StoTypedef, inl);
     B.v_local = local;
     B.v_attr = attrs;
     B.v_endattr = endattrs;
     B.v_type_bis = typb0bis;
   }, iivirg) ->

   (match A.unwrap tya0, typb0 with
   | A.Type(allminus,cv1,tya1), ((qu,il),typb1) ->
       (* allminus doesn't seem useful here - nothing done with cv1 *)

     (match A.unwrap tya1, typb1 with
     | A.StructUnionDef(tya2, lba, declsa, rba),
      (B.StructUnion (sub, sbopt, declsb), ii) ->

       let (iisub, iisbopt, lbb, rbb) =
         match sbopt with
         | None ->
             let (iisub, lbb, rbb) = tuple_of_list3 ii in
             (iisub, [], lbb, rbb)
         | Some s ->
             pr2 (Printf.sprintf
              "warning: both a typedef (%s) and struct name introduction (%s)"
              (Ast_c.str_of_name nameidb) s
             );
             pr2 "warning: I will consider only the typedef";
             let (iisub, iisb, lbb, rbb) = tuple_of_list4 ii in
             (iisub, [iisb], lbb, rbb)
       in
       let structnameb =
         structdef_to_struct_name
           (Ast_c.nQ, (B.StructUnion (sub, sbopt, declsb), ii))
       in
       let fake_typeb =
         Ast_c.nQ,((B.TypeName (nameidb, Some
           (Lib_parsing_c.al_type structnameb))), [])
       in

       struct_fields (A.unwrap declsa) declsb >>= (fun undeclsa declsb ->
         tokenf ptvirga iiptvirgb >>= (fun ptvirga iiptvirgb ->
         tokenf lba lbb >>= (fun lba lbb ->
         tokenf rba rbb >>= (fun rba rbb ->
         let declsa = A.rewrap declsa undeclsa in

         (match A.unwrap tya2 with
         | A.Type(allminus, cv3, tya3) -> (* again allminus not used *)
           (match A.unwrap tya3 with
           | A.MetaType(ida, cstr, keep, inherited) ->

               fullType tya2 fake_typeb >>= (fun tya2 fake_typeb ->
		 let tya1 =
		   A.StructUnionDef(tya2,lba,declsa,rba)+> A.rewrap tya1 in
		 let tya0 = A.Type(allminus, cv1, tya1) +> A.rewrap tya0 in


		 let typb1 = B.StructUnion (sub,sbopt, declsb),
                   [iisub] @ iisbopt @ [lbb;rbb] in
		 let typb0 = ((qu, il), typb1) in

		 match fake_typeb with
		 | _nQ, ((B.TypeName (nameidb, typ)),[]) ->
		     begin
		       match typ with
			 Some typ' ->
			   check_constraints cstr ida (B.MetaTypeVal typ')
			     (fun () ->
			       return (
			       (A.TyDecl (tya0, ptvirga)) +> A.rewrap decla,
			       (({B.v_namei = Some (nameidb, B.NoInit);
				  B.v_type = typb0;
				  B.v_storage = (B.StoTypedef, inl);
				  B.v_local = local;
				  B.v_attr = attrs;
				  B.v_endattr = endattrs;
				  B.v_type_bis = typb0bis;
				},
				 iivirg),iiptvirgb,iistob)
			      ))
		       | None -> fail
		     end
		 | _ -> raise (Impossible 29)
             )

	   (* do we need EnumName here too? *)
           | A.StructUnionName(sua, sa) ->
             fullType tya2 structnameb >>= (fun tya2 structnameb ->

               let tya1 = A.StructUnionDef(tya2,lba,declsa,rba)+> A.rewrap tya1
               in
               let tya0 = A.Type(allminus, cv1, tya1) +> A.rewrap tya0 in

               match structnameb with
               | _nQ, (B.StructUnionName (sub, s), [iisub;iisbopt]) ->

                   let typb1 = B.StructUnion (sub,sbopt, declsb),
                     [iisub;iisbopt;lbb;rbb] in
                   let typb0 = ((qu, il), typb1) in

                   return (
                     (A.TyDecl (tya0, ptvirga)) +> A.rewrap decla,
                     (({B.v_namei = Some (nameidb, B.NoInit);
                        B.v_type = typb0;
                        B.v_storage = (B.StoTypedef, inl);
                        B.v_local = local;
                        B.v_attr = attrs;
                        B.v_endattr = endattrs;
                        B.v_type_bis = typb0bis;
                     },
                      iivirg),iiptvirgb,iistob)
                   )
               | _ -> raise (Impossible 30)
             )
           | _ -> raise (Impossible 31)
           )
         | _ -> fail
       )))))
     | _ -> fail
     )
   | _ -> fail
   )

   | A.UnInit (stoa, typa, ida, attra, ptvirga),
     ({B.v_namei= Some (nameidb, _);B.v_storage= (B.StoTypedef,_);}, iivirg)
     -> fail

   | A.Init (stoa, typa, ida, attra, eqa, inia, ptvirga),
     ({B.v_namei=Some(nameidb, _);B.v_storage=(B.StoTypedef,_);}, iivirg)
       -> fail



    (* could handle iso here but handled in standard.iso *)
   | A.UnInit (stoa, typa, ida, attrsa, ptvirga),
     ({B.v_namei = Some (nameidb, B.NoInit);
       B.v_type = typb;
       B.v_storage = stob;
       B.v_local = local;
       B.v_attr = attrs;
       B.v_endattr = endattrs;
       B.v_type_bis = typbbis;
     }, iivirg) ->
       ident_cpp DontKnow ida nameidb >>= (fun ida nameidb ->
       tokenf ptvirga iiptvirgb >>= (fun ptvirga iiptvirgb ->
       fullType typa typb >>= (fun typa typb ->
       attribute_list attrsa endattrs >>= (fun attrsa endattrs ->
       storage_optional_allminus allminus stoa (stob, iistob) >>=
        (fun stoa (stob, iistob) ->
         return (
           (A.UnInit (stoa, typa, ida, attrsa, ptvirga)) +>  A.rewrap decla,
           (({B.v_namei = Some (nameidb, B.NoInit);
              B.v_type = typb;
              B.v_storage = stob;
              B.v_local = local;
              B.v_attr = attrs;
              B.v_endattr = endattrs;
              B.v_type_bis = typbbis;
           },iivirg),
	    iiptvirgb,iistob)
         ))))))

   | A.Init (stoa, typa, ida, attrsa, eqa, inia, ptvirga),
     ({B.v_namei = Some(nameidb, B.ValInit (iieqb, inib));
       B.v_type = typb;
       B.v_storage = stob;
       B.v_local = local;
       B.v_attr = attrs;
       B.v_endattr = endattrs;
       B.v_type_bis = typbbis;
     },iivirg) ->
       ident_cpp DontKnow ida nameidb >>= (fun ida nameidb ->
       tokenf ptvirga iiptvirgb >>= (fun ptvirga iiptvirgb ->
       tokenf eqa iieqb >>= (fun eqa iieqb ->
       fullType typa typb >>= (fun typa typb ->
       attribute_list attrsa endattrs >>= (fun attrsa endattrs ->
       storage_optional_allminus allminus stoa (stob, iistob) >>=
       (fun stoa (stob, iistob) ->
       initialiser inia inib >>= (fun inia inib ->
         return (
           (A.Init (stoa,typa,ida,attrsa,eqa,inia,ptvirga)) +> A.rewrap decla,
           (({B.v_namei = Some(nameidb, B.ValInit (iieqb, inib));
              B.v_type = typb;
              B.v_storage = stob;
              B.v_local = local;
              B.v_attr = attrs;
              B.v_endattr = endattrs;
              B.v_type_bis = typbbis;
           },iivirg),
           iiptvirgb,iistob)
         ))))))))

   | A.Init (stoa, typa, ida, attra, eqa, inia, ptvirga),
     ({B.v_namei = Some(nameidb, B.ConstrInit _);
       B.v_type = typb;
       B.v_storage = stob;
       B.v_local = local;
       B.v_attr = attrs;
       B.v_endattr = endattrs;
       B.v_type_bis = typbbis;
     },iivirg)
       -> fail (* C++ constructor declaration not supported in SmPL *)

   | A.FunProto(fninfoa,ida,lpa,paramsa,va,rpa,sema),
     ({B.v_namei = Some (idb, B.NoInit);
       B.v_type =
	((({B.const = false; B.volatile = false},[]) as q),
	 (B.FunctionType(tyb, (paramsb, (isvaargs, iidotsb))), ii));
       B.v_storage = stob;
       B.v_local = local;
       B.v_attr = attrs;
       B.v_endattr = endattrs;
       B.v_type_bis = typbbis;
     }, iivirg) ->
       (match (va,isvaargs) with
        | (None,false) -> return (va,(isvaargs, iidotsb))
        | (Some (commaa, dotsa), true) ->
           let (commab, dotsb) = tuple_of_list2 iidotsb in
           tokenf commaa commab >>= (fun commaa commab ->
           tokenf dotsa dotsb >>= (fun dotsa dotsb ->
           return (Some(commaa,dotsa), (true,[commab;dotsb]))
                                  ))
        | _ -> fail
       ) >>=
        (fun va (isvaargs, iidotsb) -> let (lpb, rpb) = tuple_of_list2 ii in
        ident_cpp DontKnow ida idb >>= (fun ida idb ->
        tokenf lpa lpb >>= (fun lpa lpb ->
        tokenf rpa rpb >>= (fun rpa rpb ->
        tokenf sema iiptvirgb >>= (fun sema iiptvirgb ->
	let (stoa,tya,inla,attras) = get_fninfo fninfoa in
        inline_optional_allminus allminus
          inla (stob, iistob) >>= (fun inla (stob, iistob) ->
        storage_optional_allminus allminus
          stoa (stob, iistob) >>= (fun stoa (stob, iistob) ->
        attribute_list attras attrs >>= (fun attras attrs ->
        fullType_optional_allminus allminus tya tyb >>= (fun tya tyb ->
	let fninfoa = put_fninfo stoa tya inla attras in
        parameters (seqstyle paramsa) (A.unwrap paramsa) paramsb >>=
          (fun paramsaunwrap paramsb ->
            let paramsa = A.rewrap paramsa paramsaunwrap in
            return (
              (A.FunProto(fninfoa,ida,lpa,paramsa,va,rpa,sema) +> A.rewrap decla,
	       (({B.v_namei = Some (idb, B.NoInit);
		  B.v_type =
		  (q,
		   (B.FunctionType(tyb, (paramsb, (isvaargs, iidotsb))),
		    [lpb; rpb]));
		  B.v_storage = stob;
		  B.v_local = local;
		  B.v_attr = attrs;
		  B.v_endattr = endattrs;
		  B.v_type_bis = typbbis;
		}, iivirg), iiptvirgb, iistob))))
	      )))))))))

   (* do iso-by-absence here ? allow typedecl and var ? *)
   | A.TyDecl (typa, ptvirga),
     ({B.v_namei = None; B.v_type = typb;
       B.v_storage = stob;
       B.v_local = local;
       B.v_attr = attrs;
       B.v_endattr = endattrs;
       B.v_type_bis = typbbis;
     }, iivirg)  ->

       if stob = (B.NoSto, false)
       then
         fullType typa typb >>= (fun typa typb ->
         tokenf ptvirga iiptvirgb >>= (fun ptvirga iiptvirgb ->
           return (
             (A.TyDecl (typa, ptvirga)) +> A.rewrap decla,
             (({B.v_namei = None;
                B.v_type = typb;
                B.v_storage = stob;
                B.v_local = local;
                B.v_attr = attrs;
                B.v_endattr = endattrs;
                B.v_type_bis = typbbis;
             }, iivirg), iiptvirgb, iistob)
           )))
       else fail


   | A.Typedef (stoa, typa, ida, ptvirga),
     ({B.v_namei = Some (nameidb, B.NoInit);
       B.v_type = typb;
       B.v_storage = (B.StoTypedef,inline);
       B.v_local = local;
       B.v_attr = attrs;
       B.v_endattr = endattrs;
       B.v_type_bis = typbbis;
     },iivirg) ->

       fullType typa typb >>= (fun typa typb ->
       tokenf ptvirga iiptvirgb >>= (fun ptvirga iiptvirgb ->
       (match iistob with
       | [iitypedef] ->
           tokenf stoa iitypedef >>= (fun stoa iitypedef ->
             return (stoa, [iitypedef])
           )
       | _ -> error iistob "weird, have both typedef and inline or nothing";
       ) >>= (fun stoa iistob ->
       (match A.unwrap ida with
       | A.MetaType(_,_,_,_) ->

           let fake_typeb =
             Ast_c.nQ, ((B.TypeName (nameidb, Ast_c.noTypedefDef())), [])
           in
           fullTypebis ida fake_typeb >>= (fun ida fake_typeb ->
             match fake_typeb with
             | _nQ, ((B.TypeName (nameidb, _typ)), []) ->
                 return (ida, nameidb)
             | _ -> raise (Impossible 32)
           )

       | A.TypeName sa ->
           (match nameidb with
           | B.RegularName (sb, iidb) ->
               let iidb1 = tuple_of_list1 iidb in

               if (term sa) = sb
               then
                 tokenf sa iidb1 >>= (fun sa iidb1 ->
                   return (
                     (A.TypeName sa) +> A.rewrap ida,
                     B.RegularName (sb, [iidb1])
                   ))
               else fail

           | B.CppConcatenatedName _ | B.CppVariadicName _ |B.CppIdentBuilder _
               -> raise Todo
           )

       | _ -> raise (Impossible 33)

       ) >>= (fun ida nameidb ->
         return (
           (A.Typedef (stoa, typa, ida, ptvirga)) +> A.rewrap decla,
           (({B.v_namei = Some (nameidb, B.NoInit);
              B.v_type = typb;
              B.v_storage = (B.StoTypedef,inline);
              B.v_local = local;
              B.v_attr = attrs;
              B.v_endattr = endattrs;
              B.v_type_bis = typbbis;
           },
	     iivirg),
            iiptvirgb, iistob)
         )
       ))))


   | _, ({B.v_namei = None;}, _) ->
       (* old:   failwith "no variable in this declaration, weird" *)
      fail



   | A.DisjDecl declas, declb -> failwith "DisjDecl should not arise"
(*
      declas +> List.fold_left (fun acc decla ->
        acc >|+|>
            (* (declaration (mckstart, allminus, decla) declb) *)
            (onedecl allminus decla (declb,iiptvirgb, iistob))
      ) fail
*)

  | A.ConjDecl declas, declb ->
      let rec loop acc_decl db = function
	  [] -> return (A.ConjDecl (List.rev acc_decl) +> A.rewrap decla, db)
	| d::ds ->
	    onedecl allminus d db >>= (fun decl db ->
	      loop (decl::acc_decl) db ds) in
      loop [] (declb, iiptvirgb, iistob) declas

   | A.OptDecl _,    _ ->
       failwith "not handling Opt Decl"

   | _, ({B.v_namei=Some _}, _) ->
       fail

and onefield = fun allminus decla (declb, iiptvirgb) ->
  let match_option f a b =
    match a, b with
      None, None -> return (None, None)
    | Some a, Some b -> f a b >>= (fun a b -> return (Some a, Some b))
    | None, Some _ | Some _, None -> fail in
 X.all_bound (A.get_inherited decla) >&&>
 match A.unwrap decla, declb with
   A.Field (typa, ida, None, ptvirga),
   (B.Simple (nameidb, typb), iivirg) ->
     match_option (ident_cpp DontKnow) ida nameidb >>= (fun ida nameidb ->
     tokenf ptvirga iiptvirgb >>= (fun ptvirga iiptvirgb ->
     fullType typa typb >>= (fun typa typb ->
       return (
       (A.Field (typa, ida, None, ptvirga) +>  A.rewrap decla),
       ((B.Simple (nameidb, typb),iivirg), iiptvirgb)))))
 | A.Field (typa, ida, Some (ca, ea), ptvirga),
     (B.BitField (nameidb, typb, info, eb), iivirg) ->
     match_option (ident_cpp DontKnow) ida nameidb >>= (fun ida nameidb ->
     tokenf ptvirga iiptvirgb >>= (fun ptvirga iiptvirgb ->
     fullType typa typb >>= (fun typa typb ->
     tokenf ca info >>= (fun ca info ->
     expression ea eb >>= (fun ea eb ->
       return (
       (A.Field (typa, ida, Some (ca, ea), ptvirga) +>  A.rewrap decla),
       ((B.BitField (nameidb, typb, info, eb),iivirg), iiptvirgb)))))))

   | A.DisjField declas, declb -> failwith "DisjField should not arise"
(*
      declas +> List.fold_left (fun acc decla ->
        acc >|+|>
            (* (declaration (mckstart, allminus, decla) declb) *)
            (onedecl allminus decla (declb,iiptvirgb, iistob))
      ) fail
*)

  | A.ConjField declas, declb ->
      let rec loop acc_decl db = function
	  [] -> return (A.ConjField (List.rev acc_decl) +> A.rewrap decla, db)
	| d::ds ->
	    onefield allminus d db >>= (fun decl db ->
	      loop (decl::acc_decl) db ds) in
      loop [] (declb, iiptvirgb) declas

   | A.OptField _,    _ ->
       failwith "not handling Opt Field"

   | _, _ ->
       fail

and get_fninfo fninfoa =
      (* fninfoa records the order in which the SP specified the various
	 information, but this isn't taken into account in the matching.
	 Could this be a problem for transformation? *)
  let stoa =
    match
      List.filter (function A.FStorage(s) -> true | _ -> false) fninfoa
    with [A.FStorage(s)] -> Some s | _ -> None in
  let tya =
    match List.filter (function A.FType(s) -> true | _ -> false) fninfoa
    with [A.FType(t)] -> Some t | _ -> None in

  let inla =
    match List.filter (function A.FInline(i) -> true | _ -> false) fninfoa
    with [A.FInline(i)] -> Some i | _ -> None in

  let attras =
    match List.filter (function A.FAttr(a) -> true | _ -> false) fninfoa
    with
      [] -> [] |(* _ -> failwith "matching of attributes not supported"*)
	(* The following provides matching of one attribute against one
	   attribute.  But the problem is that in the C ast there are no
	   attributes in the attr field.  The attributes are all comments.
	   So there is nothing to match against. *)
	(**)  [A.FAttr(a)] -> [a]
	(*| [] -> None*)
	| _ -> failwith "only one attr match allowed" (**) in
  (stoa,tya,inla,attras)

and put_fninfo stoa tya inla attras =
  (match stoa  with Some st -> [A.FStorage st] | None -> []) @
    (match inla   with Some i -> [A.FInline i] | None -> []) @
    (match tya    with Some t -> [A.FType t] | None -> []) @
    (List.map (fun x -> A.FAttr x) attras)

(* ------------------------------------------------------------------------- *)

and (initialiser: (A.initialiser, Ast_c.initialiser) matcher) =  fun ia ib ->
    X.all_bound (A.get_inherited ia) >&&>
    match (A.unwrap ia,ib) with

    | (A.MetaInit(ida,constraints,keep,inherited), ib) ->
	let max_min _ = Lib_parsing_c.ii_of_ini ib in
	let mv = Ast_c.MetaInitVal ib in
	check_constraints constraints ida mv
	  (fun () ->
	    X.envf keep inherited (ida, mv, max_min)
	      (fun () ->
		X.distrf_ini ida ib >>= (fun ida ib ->
		  return (
	          A.MetaInit (ida,constraints,keep,inherited) +> A.rewrap ia,
	          ib
		 ))
	      ))

    | A.AsInit(ini,asini), inib ->
	initialiser ini inib >>= (fun ini inib ->
	initialiser asini inib >>= (fun asini inib ->
	  return(
	  ((A.AsInit(ini,asini)) +> A.rewrap ia,
	   inib))))

    | (A.InitExpr expa, ib) ->
        (match A.unwrap expa, ib with
        | A.Edots (mcode, None), ib    ->
            X.distrf_ini (dots2metavar mcode) ib >>= (fun mcode ib ->
              return (
                A.InitExpr
                  (A.Edots (metavar2dots mcode, None) +> A.rewrap expa)
                    +>  A.rewrap ia,
                ib
               ))

        | A.Edots (_, Some expr), _    -> failwith "not handling when on Edots"

        | _, (B.InitExpr expb, ii) ->
            assert (ii = []);
            expression expa expb >>= (fun expa expb ->
              return (
                (A.InitExpr expa) +> A.rewrap ia,
                (B.InitExpr expb, ii)
              ))
        | _ -> fail
        )

    | (A.ArInitList (ia1, ias, ia2), (B.InitList ibs, ii)) ->
        (match ii with
	| ib1::ib2::iicommaopt ->
            tokenf ia1 ib1 >>= (fun ia1 ib1 ->
            tokenf ia2 ib2 >>= (fun ia2 ib2 ->
            ar_initialisers (A.unwrap ias) (ibs, iicommaopt) >>=
	      (fun iasunwrap (ibs,iicommaopt) ->
              return (
                (A.ArInitList (ia1, A.rewrap ias iasunwrap, ia2)) +> A.rewrap ia,
                (B.InitList ibs, ib1::ib2::iicommaopt)
              ))))

        | _ -> raise (Impossible 35)
        )

    | (A.StrInitList (allminus, ia1, ias, ia2, []), (B.InitList ibs, ii)) ->
        (match ii with
        | ib1::ib2::iicommaopt ->
            tokenf ia1 ib1 >>= (fun ia1 ib1 ->
            tokenf ia2 ib2 >>= (fun ia2 ib2 ->
            str_initialisers allminus ias (ibs, iicommaopt) >>=
	      (fun ias (ibs,iicommaopt) ->
              return (
                (A.StrInitList (allminus, ia1, ias, ia2, [])) +> A.rewrap ia,
                (B.InitList ibs, ib1::ib2::iicommaopt)
              ))))

        | _ -> raise (Impossible 36)
        )

    | (A.StrInitList (allminus, i1, ias, i2, whencode),
       (B.InitList ibs, _ii)) ->
        failwith "TODO: not handling whencode in initialisers"


    | (A.InitGccExt (designatorsa, ia2, inia),
      (B.InitDesignators (designatorsb, inib), ii2))->

        let iieq = tuple_of_list1 ii2 in

        tokenf ia2 iieq >>= (fun ia2 iieq ->
	designators designatorsa designatorsb >>=
	  (fun designatorsa designatorsb ->
        initialiser inia inib >>= (fun inia inib ->
          return (
            (A.InitGccExt (designatorsa, ia2, inia)) +> A.rewrap ia,
            (B.InitDesignators (designatorsb, inib), [iieq])
          ))))




    | (A.InitGccName (ida, ia1, inia), (B.InitFieldOld (idb, inib), ii)) ->
        (match ii with
        | [iidb;iicolon] ->
            ident DontKnow ida (idb, iidb) >>= (fun ida (idb, iidb) ->
            initialiser inia inib >>= (fun inia inib ->
            tokenf ia1 iicolon >>= (fun ia1 iicolon ->
              return (
                (A.InitGccName (ida, ia1, inia)) +> A.rewrap ia,
                (B.InitFieldOld (idb, inib), [iidb;iicolon])
              ))))
        | _ -> fail
        )



    | A.IComma(comma), _ ->
        raise (Impossible 37)

    | A.OptIni _,_ ->
      failwith "not handling Opt on initialisers"

    | _, (B.InitIndexOld (_, _), _) -> fail
    | _, (B.InitFieldOld (_, _), _) -> fail

    | _, ((B.InitDesignators (_, _)|B.InitList _|B.InitExpr _), _)
        -> fail

and designators dla dlb =
  match (dla,dlb) with
    ([],[]) -> return ([], [])
  | ([],_) | (_,[]) -> fail
  | (da::dla,db::dlb) ->
      designator da db >>= (fun da db ->
      designators dla dlb >>= (fun dla dlb ->
      return (da::dla, db::dlb)))

and designator da db =
  match (da,db) with
    (A.DesignatorField (ia1, ida), (B.DesignatorField idb,ii1)) ->

        let (iidot, iidb) = tuple_of_list2 ii1 in
        tokenf ia1 iidot >>= (fun ia1 iidot ->
        ident DontKnow ida (idb, iidb) >>= (fun ida (idb, iidb) ->
          return (
            A.DesignatorField (ia1, ida),
            (B.DesignatorField idb, [iidot;iidb])
          )))

  | (A.DesignatorIndex (ia1,ea,ia2), (B.DesignatorIndex eb, ii1)) ->

        let (ib1, ib2) = tuple_of_list2 ii1 in
        tokenf ia1 ib1 >>= (fun ia1 ib1 ->
        tokenf ia2 ib2 >>= (fun ia2 ib2 ->
        expression ea eb >>= (fun ea eb ->
          return (
            A.DesignatorIndex (ia1,ea,ia2),
            (B.DesignatorIndex eb, [ib1;ib2])
          ))))

  | (A.DesignatorRange (ia1,e1a,ia2,e2a,ia3),
     (B.DesignatorRange (e1b, e2b), ii1)) ->

        let (ib1, ib2, ib3) = tuple_of_list3 ii1 in
        tokenf ia1 ib1 >>= (fun ia1 ib1 ->
        tokenf ia2 ib2 >>= (fun ia2 ib2 ->
        tokenf ia3 ib3 >>= (fun ia3 ib3 ->
        expression e1a e1b >>= (fun e1a e1b ->
        expression e2a e2b >>= (fun e2a e2b ->
          return (
            A.DesignatorRange (ia1,e1a,ia2,e2a,ia3),
            (B.DesignatorRange (e1b, e2b), [ib1;ib2;ib3])
          ))))))
  | (_, ((B.DesignatorField _|B.DesignatorIndex _|B.DesignatorRange _), _)) ->
      fail

and str_initialisers = fun allminus ias (ibs, iicomma) ->
  let ias_unsplit = unsplit_icomma      ias in
  let ibs_split   = resplit_initialiser ibs iicomma in

  (* need unordered is to check if an expensive computation is useful, but if
     ias is null, then the computation is not expensive *)
  if (ias = [] && ibs = []) || need_unordered_initialisers ibs
  then
    initialisers_unordered2 allminus ias_unsplit ibs_split >>=
    (fun ias_unsplit ibs_split ->
      return (
      split_icomma ias_unsplit,
      unsplit_initialiser ibs_split))
  else fail

and ar_initialisers = fun ias (ibs, iicomma) ->
  (* this doesn't check need_unordered_initialisers because ... can be
     implemented as ordered, even if it matches unordered initializers *)
  let ibs = resplit_initialiser ibs iicomma in
  let ibs =
    List.concat
      (List.map (function (elem,comma) -> [Left elem; Right [comma]]) ibs) in
  initialisers_ordered2 ias ibs >>=
  (fun ias ibs_split ->
    let ibs,iicomma =
      match List.rev ibs_split with
	(Right comma)::rest -> (Ast_c.unsplit_comma (List.rev rest),comma)
      | (Left _)::_ -> (Ast_c.unsplit_comma ibs_split,[]) (* possible *)
      | [] -> ([],[]) in
    return (ias, (ibs,iicomma)))

and initialisers_ordered2 = fun ias ibs ->
  let match_dots ea =
    match A.unwrap ea with
      A.Idots(mcode, optexpr) -> Some (mcode, optexpr)
    |  _ -> None in
  let build_dots (mcode, optexpr) = A.Idots(mcode, optexpr) in
  let match_comma ea =
    match A.unwrap ea with
      A.IComma ia1 -> Some ia1
    |  _ -> None in
  let build_comma ia1 = A.IComma ia1 in
  let match_metalist ea =
    match A.unwrap ea with
      A.MetaInitList(ida,leninfo,cstr,keep,inherited) ->
	Some(ida,leninfo,cstr,keep,inherited,None)
    | _ -> None in
  let build_metalist _ (ida,leninfo,cstr,keep,inherited) =
    A.MetaInitList(ida,leninfo,cstr,keep,inherited) in
  let mktermval v = Ast_c.MetaInitListVal v in
  let special_cases ea eas ebs = None in
  let no_ii x = failwith "initialisers: no ii: not possible" in
  list_matcher match_dots build_dots match_comma build_comma
    match_metalist build_metalist mktermval
    special_cases initialiser X.distrf_inis
    B.split_comma B.unsplit_comma no_ii
    (function x -> Some x) ias ibs

and initialisers_unordered2 = fun allminus ias ibs ->
  match ias, ibs with
  | [], ys ->
      if allminus
      then
	let rec loop = function
	    [] -> return ([],[])
	  | (ib,comma)::ibs ->
	      X.distrf_ini minusizer ib >>= (fun _ ib ->
		tokenf minusizer comma >>= (fun _ comma ->
		  loop ibs >>= (fun l ibs ->
		    return(l,(ib,comma)::ibs)))) in
	loop ibs
      else return ([], ys)
  | x::xs, ys ->
      let permut = Common.uncons_permut_lazy ys in
      permut +> List.fold_left (fun acc ((e, pos), rest) ->
        acc >||>
          (initialiser_comma x e
            >>= (fun x e ->
              let rest = Lazy.force rest in
              initialisers_unordered2 allminus xs rest >>= (fun xs rest ->
                return (
                  x::xs,
                  Common.insert_elem_pos (e, pos) rest
                ))))
      ) fail

and initialiser_comma (x,xcomma) (y, commay) =
  match A.unwrap xcomma with
    A.IComma commax ->
      tokenf commax commay >>= (fun commax commay ->
        initialiser x y >>= (fun x y ->
          return (
          (x, (A.IComma commax) +> A.rewrap xcomma),
          (y, commay))))
  | _ -> raise (Impossible 38) (* unsplit_iicomma wrong *)

(* ------------------------------------------------------------------------- *)
and (struct_fields: (A.annotated_field list, B.field list) matcher) =
 fun eas ebs ->
  let match_dots ea =
    match A.unwrap ea with
      A.Fdots(mcode, optexpr) -> Some (mcode, optexpr)
    | _ -> None in
  let build_dots (mcode, optexpr) = A.Fdots(mcode, optexpr) in
  let match_comma ea = None in
  let build_comma ia1 = failwith "struct_fields: build comma: not possible" in
  let match_metalist ea =
    match A.unwrap ea with
      A.FElem(mckstart,allminus,d) ->
	(match A.unwrap d with
	  A.MetaFieldList(ida,leninfo,cstr,keep,inherited) ->
	    Some(ida,leninfo,cstr,keep,inherited,None)
	| _ -> None)
    | _ -> None in
  let build_metalist ea (ida,leninfo,cstr,keep,inherited) =
    match A.unwrap ea with
      A.FElem(mckstart,allminus,d) ->
	A.FElem(mckstart,allminus,
		(A.rewrap ea
		   (A.MetaFieldList(ida,leninfo,cstr,keep,inherited))))
    | _ -> failwith "struct_fields: build meta list: not possible" in
  let mktermval v =
    (* drop empty ii information, because nothing between elements *)
    let v = List.map Ast_c.unwrap v in
    Ast_c.MetaFieldListVal v in
  let special_cases ea eas ebs = None in
  let no_ii x = failwith "struct_fields: no ii: not possible" in
  let make_ebs ebs = List.map (function x -> Left x) ebs in
  let unmake_ebs ebs =
    List.map (function Left x -> x | Right x -> failwith "no right") ebs in
  let distrf mcode startxs =
    let startxs = unmake_ebs startxs in
    X.distrf_struct_fields mcode startxs >>=
    (fun mcode startxs -> return (mcode,make_ebs startxs)) in
  let filter_fields l =
    Some
      (List.filter
	 (function x ->
	   match Ast_c.unwrap x with
	     Ast_c.DeclarationField fld -> true
	   | Ast_c.EmptyField info -> true
	   | Ast_c.MacroDeclField decl -> true
	   | Ast_c.CppDirectiveStruct cpp -> false
	   | Ast_c.IfdefStruct ifdef -> false)
	 l) in
  list_matcher match_dots build_dots match_comma build_comma
    match_metalist build_metalist mktermval
    special_cases struct_field distrf
    B.split_comma B.unsplit_comma no_ii
    filter_fields eas (make_ebs ebs) >>=
  (fun eas ebs -> return (eas,unmake_ebs ebs))

and (struct_field: (A.annotated_field, B.field) matcher) =
  fun fa fb ->
    match A.unwrap fa with
      A.Fdots _ -> failwith "dots should be treated otherwise"
    | A.FElem(mckstart,allminus,ifa) ->

	(match A.unwrap ifa,fb with
	| A.MetaField (ida,cstr,keep,inherited), B.CppDirectiveStruct _
	| A.MetaField (ida,cstr,keep,inherited), B.IfdefStruct _ ->
	    (* not really fields *) fail
	| A.MetaField (ida,cstr,keep,inherited), _ ->
	    let max_min _ = Lib_parsing_c.ii_of_field fb in
	    let mv = Ast_c.MetaFieldVal fb in
	    check_constraints cstr ida mv
	      (fun () ->
		X.envf keep inherited (ida, mv, max_min)
		  (fun () ->
		    X.distrf_field ida fb
		  ) >>= (fun ida fb ->
		    return
		      (A.FElem
			 (mckstart,allminus,
			  (A.MetaField (ida, cstr, keep, inherited))
			    +> A.rewrap ifa)
			 +> A.rewrap fa,
		       fb)))
	| _,B.DeclarationField (B.FieldDeclList ([onevar,iivirg],iiptvirg)) ->

        (* no modif possible on iistartb; included for parallelism with
	   DeclList *)
	    let (iiptvirgb,iifakestart) = tuple_of_list2 iiptvirg in

	    assert (iivirg = []);
	    X.tokenf_mck mckstart iifakestart >>=
	    (fun mckstart iifakestart ->
	      (* build a declaration from a struct field *)
	      onefield allminus ifa ((onevar, iivirg),iiptvirgb) >>=
		  (fun ifa (onevar,iiptvirgb) ->
		    return (
		    (A.FElem(mckstart,allminus,ifa) +> A.rewrap fa),
		    ((B.DeclarationField
			(B.FieldDeclList([onevar],
					 [iiptvirgb;iifakestart])))))))

	| _,B.DeclarationField (B.FieldDeclList (xs,iiptvirg)) ->

	    let (iiptvirgb,iifakestart) = tuple_of_list2 iiptvirg in

	    let indexify l =
	      let rec loop n = function
		  [] -> []
		| x::xs -> (n,x)::(loop (n+1) xs) in
	      loop 0 l in
	    let rec repln n vl cur = function
		[] -> []
	      | x::xs ->
		  if n = cur then vl :: xs else x :: (repln n vl (cur+1) xs) in
	    let doit _ =
	      (indexify xs) +> List.fold_left (fun acc (n,(onevar,iivirg)) ->
          (* consider all possible matches *)
		acc >||>
		(X.tokenf_mck mckstart iifakestart >>=
		 (fun mckstart iifakestart ->
		   onefield allminus ifa ((onevar,iivirg), iiptvirgb) >>=
		     (fun ifa (one_var,iiptvirgb) ->
		       return (
		       (A.FElem(mckstart,allminus,ifa) +> A.rewrap fa),
		       ((B.DeclarationField
			   (B.FieldDeclList
			      (repln n (onevar,iivirg) 0 xs,
			       [iiptvirgb;iifakestart])))))))))
		fail in
	    if !Flag.sgrep_mode2(*X.mode = PatternMode *) ||
	       not(A.get_safe_decl ifa = A.Unsafe)
	    then doit()
	    else
	      begin
	        (* unambitious version of the DeclList case... *)
		pr2_once "PB: More that one variable in decl. Have to split";
		fail
	      end

	| _,B.EmptyField _iifield ->
	    fail

	| _,B.MacroDeclField ((sb,ebs),ii) -> fail

	| _,B.CppDirectiveStruct directive -> fail
	| _,B.IfdefStruct directive -> fail)

(* ---------------------------------------------------------------------- *)

and enum_fields = fun eas ebs ->
  let match_dots ea =
    match A.unwrap ea with
      A.Edots(mcode, optexpr) -> Some (mcode, optexpr)
    | _ -> None in
  let build_dots (mcode, optexpr) = A.Edots(mcode, optexpr) in
  let match_comma ea =
    match A.unwrap ea with
      A.EComma ia1 -> Some ia1
    | _ -> None in
  let build_comma ia1 = A.EComma ia1 in
  let match_metalist ea = None in
  let build_metalist _ (ida,leninfo,cstr,keep,inherited) =
    failwith "enum: build meta list: not possible" in
  let mktermval v = failwith "enum: mk term val: not possible" in
  let special_cases ea eas ebs = None in
  list_matcher match_dots build_dots match_comma build_comma
    match_metalist build_metalist mktermval
    special_cases enum_field X.distrf_enum_fields
    B.split_comma B.unsplit_comma
    Lib_parsing_c.ii_of_enum_fields (function x -> Some x) eas ebs

and enum_field ida idb =
  X.all_bound (A.get_inherited ida) >&&>
  match A.unwrap ida, idb with
    A.Ident(id),(nameidb,None) ->
      ident_cpp DontKnow id nameidb >>= (fun id nameidb ->
        return ((A.Ident id) +> A.rewrap ida, (nameidb,None)))
  | A.Ident(id),(nameidb,Some _) -> fail (* should we have an iso? *)
  | A.Assignment(ea1,opa,ea2,init),(nameidb,Some(opbi,eb2)) ->
      (match A.unwrap ea1 with
	A.Ident(id) ->
	  let assignOp opa0 opbi =
	    match A.unwrap opa0 with
              A.SimpleAssign oa ->
		tokenf oa opbi >>= fun oa opbi ->
		  return
                    (A.rewrap opa (A.SimpleAssign oa), opbi)
            | _ -> failwith "only simple assignment possible here" in
	  ident_cpp DontKnow id nameidb >>= (fun id nameidb ->
	  expression ea2 eb2 >>= (fun ea2 eb2 ->
          assignOp opa opbi >>= (fun opa opbi ->(* only one kind of assignop *)
	    return (
	    (A.Assignment((A.Ident(id)) +> A.rewrap ea1,opa,ea2,init)) +>
	    A.rewrap ida,
	    (nameidb,Some(opbi,eb2))))))
      |	_ -> failwith "enum: assignment: not possible")
  | A.Assignment(ea1,opa,ea2,init),(nameidb,None) -> fail
  | _ -> failwith ("not possible: "^(Dumper.dump (A.unwrap ida)))

(* ------------------------------------------------------------------------- *)
and (fullType: (A.fullType, Ast_c.fullType) matcher) =
 fun typa typb ->
   X.optional_qualifier_flag (fun optional_qualifier ->
   X.all_bound (A.get_inherited typa) >&&>
   match A.unwrap typa, typb with
   | A.Type(allminus,cv,ty1), ((qu,il),ty2) ->

       if qu.B.const && qu.B.volatile
       then
	 pr2_once
	   ("warning: the type is both const & volatile but cocci " ^
            "does not handle that");

	(* Drop out the const/volatile part that has been matched.
         * This is because a SP can contain  const T v; in which case
         * later in match_t_t when we encounter a T, we must not add in
         * the environment the whole type.
         *)


       (match cv with
       (* "iso-by-absence" *)
       | None ->
           let do_stuff () =
             fullTypebis ty1 ((qu,il), ty2) >>= (fun ty1 ((qu,il), ty2) ->
             (if allminus
	     then minusize_list il
	     else return ((), il)
	     ) >>= (fun () il ->
	       return (
                 (A.Type(allminus, None, ty1)) +> A.rewrap typa,
                 ((qu,il), ty2)
               )))
           in
           (match optional_qualifier, qu.B.const || qu.B.volatile with
           | false, false -> do_stuff ()
           | false, true -> fail
           | true, false -> do_stuff ()
           | true, true ->
               if !FlagM.show_misc
               then pr2_once "USING optional_qualifier builtin isomorphism";
               do_stuff()
           )


       | Some x ->
          (* todo: can be __const__ ? can be const & volatile so
           * should filter instead ?
           *)
           (match term x, il with
           | A.Const, [i1] when qu.B.const ->

               tokenf x i1 >>= (fun x i1 ->
               fullTypebis ty1 (Ast_c.nQ,ty2) >>= (fun ty1 (_, ty2) ->
                 return (
                   (A.Type(allminus, Some x, ty1)) +> A.rewrap typa,
                   ((qu, [i1]), ty2)
                 )))

           | A.Volatile, [i1] when qu.B.volatile ->
               tokenf x i1 >>= (fun x i1 ->
               fullTypebis ty1 (Ast_c.nQ,ty2) >>= (fun ty1 (_, ty2) ->
                 return (
                   (A.Type(allminus, Some x, ty1)) +> A.rewrap typa,
                   ((qu, [i1]), ty2)
                 )))

           | _ -> fail
           )
       )

  | A.AsType(ty,asty), tyb ->
      fullType ty tyb >>= (fun ty tyb ->
      fullType asty tyb >>= (fun asty tyb ->
	return(
	  ((A.AsType(ty,asty)) +> A.rewrap typa,
	   tyb))))

  | A.DisjType typas, typb ->
      typas +>
      List.fold_left (fun acc typa -> acc >|+|> (fullType typa typb)) fail

  | A.ConjType typas, typb ->
      let rec loop acc_ty typb = function
	  [] -> return (A.ConjType (List.rev acc_ty) +> A.rewrap typa, typb)
	| t::ts ->
	    fullType t typb >>= (fun t typb ->
	      loop (t::acc_ty) typb ts) in
      loop [] typb typas

   | A.OptType(_), _ -> failwith "not handling Opt on type"
   )


(*
 * Why not (A.typeC, Ast_c.typeC) matcher ?
 * because when there is MetaType, we want that T record the whole type,
 * including the qualifier, and so this type (and the new_il function in
 * preceding function).
*)

and (fullTypebis: (A.typeC, Ast_c.fullType) matcher) =
  fun ta tb ->
  X.all_bound (A.get_inherited ta) >&&>
  match A.unwrap ta, tb with

  (* cas general *)
  | A.MetaType(ida,cstr,keep, inherited),  typb ->
      let type_present =
	let (tyq, (ty, tyii)) = typb in
	match ty with
	  B.NoType -> false
	| _ -> true in
      let position_required_but_unavailable =
	match A.get_pos_var ida with
	  [] -> false
	| _ ->
	    let (tyq, (ty, tyii)) = typb in
	    let tyii =
	      match ty with
		B.TypeName(name,typ) ->
		  (* promoted typedef has ii information in the type name *)
		  let (_s, iis) = B.get_s_and_info_of_name name in
		  [iis]
	      |	_ -> tyii in
	    List.for_all Ast_c.is_fake tyii in
      if type_present && not position_required_but_unavailable
      then
	let max_min _ = Lib_parsing_c.ii_of_type typb in
	check_constraints cstr ida (B.MetaTypeVal typb)
	  (fun () ->
	    X.envf keep inherited (ida, B.MetaTypeVal typb, max_min) (fun () ->
	      X.distrf_type ida typb >>= (fun ida typb ->
		return (
		A.MetaType(ida, cstr, keep, inherited) +> A.rewrap ta,
		typb)))
	      )
      else fail (* K&R, or macro, or C++? *)
  | unwrap, (qub, typb) ->
      typeC ta typb >>= (fun ta typb ->
        return (ta, (qub, typb))
      )

and simulate_signed ta basea stringsa signaopt tb baseb ii rebuilda =
      (* In ii there is a list, sometimes of length 1 or 2 or 3.
       * And even if in baseb we have a Signed Int, that does not mean
       * that ii is of length 2, cos Signed is the default, so if in signa
       * we have Signed explicitly ? we cannot "accrocher" this mcode to
       * something :( So for the moment when there is signed in cocci,
       * we force that there is a signed in c too (done in pattern.ml).
       *)
      let signbopt, iibaseb = split_signb_baseb_ii (baseb, ii) in


      (* handle some iso on type ? (cf complex C rule for possible implicit
	 casting) *)
      match basea, baseb with
      | A.VoidType,   B.Void
      | A.FloatType,  B.FloatType (B.CFloat)
      | A.DoubleType, B.FloatType (B.CDouble)
      | A.SizeType,   B.SizeType
      | A.SSizeType,  B.SSizeType
      | A.PtrDiffType,B.PtrDiffType ->
	  assert (signaopt = None);
	  let stringa = tuple_of_list1 stringsa in
	  let (ibaseb) = tuple_of_list1 ii in
	  tokenf stringa ibaseb >>= (fun stringa ibaseb ->
	    return (
	    (rebuilda ([stringa], signaopt)) +> A.rewrap ta,
	    (B.BaseType baseb, [ibaseb])
          ))

      | A.LongDoubleType, B.FloatType B.CLongDouble
      | A.FloatComplexType,  B.FloatType (B.CFloatComplex)
      | A.DoubleComplexType, B.FloatType (B.CDoubleComplex) ->
           assert (signaopt = None);
	   let (stringa1,stringa2) = tuple_of_list2 stringsa in
           let (ibaseb1,ibaseb2) = tuple_of_list2 ii in
           tokenf stringa1 ibaseb1 >>= (fun stringa1 ibaseb1 ->
           tokenf stringa2 ibaseb2 >>= (fun stringa2 ibaseb2 ->
             return (
               (rebuilda ([stringa1;stringa2], signaopt)) +> A.rewrap ta,
               (B.BaseType baseb, [ibaseb1;ibaseb2])
             )))

      | A.LongDoubleComplexType, B.FloatType (B.CLongDoubleComplex) ->
           assert (signaopt = None);
	   let (stringa1,stringa2,stringa3) = tuple_of_list3 stringsa in
           let (ibaseb1,ibaseb2,ibaseb3) = tuple_of_list3 ii in
           tokenf stringa1 ibaseb1 >>= (fun stringa1 ibaseb1 ->
           tokenf stringa2 ibaseb2 >>= (fun stringa2 ibaseb2 ->
           tokenf stringa3 ibaseb3 >>= (fun stringa3 ibaseb3 ->
             return (
               (rebuilda ([stringa1;stringa2;stringa3], signaopt)) +> A.rewrap ta,
               (B.BaseType baseb, [ibaseb1;ibaseb2;ibaseb3])
             ))))

      | A.CharType,  B.IntType B.CChar when signaopt = None ->
	  let stringa = tuple_of_list1 stringsa in
          let ibaseb = tuple_of_list1 ii in
           tokenf stringa ibaseb >>= (fun stringa ibaseb ->
             return (
               (rebuilda ([stringa], signaopt)) +> A.rewrap ta,
               (B.BaseType (B.IntType B.CChar), [ibaseb])
             ))

      | A.CharType,B.IntType (B.Si (_sign, B.CChar2)) when signaopt <> None ->
	  let stringa = tuple_of_list1 stringsa in
          let ibaseb = tuple_of_list1 iibaseb in
          sign signaopt signbopt >>= (fun signaopt iisignbopt ->
          tokenf stringa ibaseb >>= (fun stringa ibaseb ->
            return (
               (rebuilda ([stringa], signaopt)) +> A.rewrap ta,
               (B.BaseType (baseb), iisignbopt @ [ibaseb])
               )))

      | A.ShortType, B.IntType (B.Si (_, B.CShort))
      | A.IntType,   B.IntType (B.Si (_, B.CInt))
      | A.LongType,  B.IntType (B.Si (_, B.CLong))  ->
	  let stringa = tuple_of_list1 stringsa in
          (match iibaseb with
          | [] ->
              (* iso-by-presence ? *)
              (* when unsigned int in SP,  allow have just unsigned in C ? *)
              if mcode_contain_plus (mcodekind stringa)
              then fail
              else

                sign signaopt signbopt >>= (fun signaopt iisignbopt ->
                    return (
                      (rebuilda ([stringa], signaopt)) +> A.rewrap ta,
                      (B.BaseType (baseb), iisignbopt)
                    ))


          | [x;y] ->
              (*pr2_once
                "warning: long int or short int not handled by ast_cocci";*)
              fail

          | [ibaseb] ->
          sign signaopt signbopt >>= (fun signaopt iisignbopt ->
          tokenf stringa ibaseb >>= (fun stringa ibaseb ->
            return (
               (rebuilda ([stringa], signaopt)) +> A.rewrap ta,
               (B.BaseType (baseb), iisignbopt @ [ibaseb])
               )))
          | _ -> raise (Impossible 41)

          )

      | A.LongLongIntType, B.IntType (B.Si (_, B.CLongLong)) ->
	  let (string1a,string2a,string3a) = tuple_of_list3 stringsa in
          (match iibaseb with
            [ibase1b;ibase2b;ibase3b] ->
              sign signaopt signbopt >>= (fun signaopt iisignbopt ->
              tokenf string1a ibase1b >>= (fun base1a ibase1b ->
              tokenf string2a ibase2b >>= (fun base2a ibase2b ->
              tokenf string3a ibase3b >>= (fun base3a ibase3b ->
              return (
		(rebuilda ([base1a;base2a;base3a], signaopt)) +> A.rewrap ta,
		(B.BaseType (baseb), iisignbopt @ [ibase1b;ibase2b;ibase3b])
              )))))
	  | [ibase1b;ibase2b] -> fail (* int omitted *)
	  | [] -> fail (* should something be done in this case? *)
	  | _ -> raise (Impossible 42))


      | A.LongLongType, B.IntType (B.Si (_, B.CLongLong))
      | A.LongIntType,  B.IntType (B.Si (_, B.CLong))
      | A.ShortIntType, B.IntType (B.Si (_, B.CShort)) ->
	  let (string1a,string2a) = tuple_of_list2 stringsa in
          (match iibaseb with
            [ibase1b;ibase2b] ->
              sign signaopt signbopt >>= (fun signaopt iisignbopt ->
              tokenf string1a ibase1b >>= (fun base1a ibase1b ->
              tokenf string2a ibase2b >>= (fun base2a ibase2b ->
              return (
		(rebuilda ([base1a;base2a], signaopt)) +> A.rewrap ta,
		(B.BaseType (baseb), iisignbopt @ [ibase1b;ibase2b])
              ))))
	  | [ibase1b] -> fail (* short or long *)
	  | [ibase1b;ibase2b;ibase3b] -> fail (* long long case *)
	  | [] -> fail (* should something be done in this case? *)
	  | _ -> raise (Impossible 43))

      | _, (B.Void|B.FloatType _|B.IntType _
	    |B.SizeType|B.SSizeType|B.PtrDiffType) -> fail

and simulate_signed_meta ta basea signaopt tb baseb ii rebuilda =
      (* In ii there is a list, sometimes of length 1 or 2 or 3.
       * And even if in baseb we have a Signed Int, that does not mean
       * that ii is of length 2, cos Signed is the default, so if in signa
       * we have Signed explicitly ? we cannot "accrocher" this mcode to
       * something :( So for the moment when there is signed in cocci,
       * we force that there is a signed in c too (done in pattern.ml).
       *)
      let signbopt, iibaseb = split_signb_baseb_ii (baseb, ii) in

      let match_to_type rebaseb =
	sign signaopt signbopt >>= (fun signaopt iisignbopt ->
	let fta = A.rewrap basea (A.Type(false(*don't know*),None,basea)) in
	let ftb = Ast_c.nQ,(B.BaseType (rebaseb), iibaseb) in
	fullType fta ftb >>= (fun fta (_,tb) ->
	  (match A.unwrap fta,tb with
	    A.Type(_,_,basea), (B.BaseType baseb, ii) ->
	      return (
	      (rebuilda (basea, signaopt)) +> A.rewrap ta,
	      (B.BaseType (baseb), iisignbopt @ ii)
		)
	  | _ -> failwith "simulate signed: not possible"))) in

      (* handle some iso on type ? (cf complex C rule for possible implicit
	 casting) *)
      match baseb with
      | B.IntType (B.Si (_sign, B.CChar2)) ->
	  match_to_type (B.IntType B.CChar)

      | B.IntType (B.Si (_, ty)) ->
          (match iibaseb with
          | [] -> fail (* metavariable has to match something *)

          | _ -> match_to_type (B.IntType (B.Si (B.Signed, ty)))

          )

      | (B.Void|B.FloatType _|B.IntType _
         |B.SizeType|B.SSizeType|B.PtrDiffType) -> fail

and (typeC: (A.typeC, Ast_c.typeC) matcher) =
  fun ta tb ->
  match A.unwrap ta, tb with
    | A.BaseType (basea,stringsa), (B.BaseType baseb, ii) ->
	simulate_signed ta basea stringsa None tb baseb ii
	  (function (stringsa, signaopt) -> A.BaseType (basea,stringsa))
    | A.SignedT (signaopt, Some basea), (B.BaseType baseb, ii) ->
	(match A.unwrap basea with
	  A.BaseType (basea1,strings1) ->
	    simulate_signed ta basea1 strings1 (Some signaopt) tb baseb ii
	      (function (strings1, Some signaopt) ->
		A.SignedT
		  (signaopt,
		   Some (A.rewrap basea (A.BaseType (basea1,strings1))))
		| _ -> failwith "typeC: signed: base: not possible")
	| A.MetaType(ida, cstr, keep, inherited) ->
	    check_constraints cstr ida (B.MetaTypeVal (Ast_c.nQ, tb))
	      (fun () ->
		simulate_signed_meta ta basea (Some signaopt) tb baseb ii
		  (function (basea, Some signaopt) ->
		    A.SignedT(signaopt,Some basea)
		    | _ -> failwith "typeC: signed: meta: not possible")
		  )
	| _ -> failwith "typeC: signed: not possible")
    | A.SignedT (signa,None),   (B.BaseType baseb, ii) ->
        let signbopt, iibaseb = split_signb_baseb_ii (baseb, ii) in
        (match iibaseb, baseb with
        | [], B.IntType (B.Si (_sign, B.CInt)) ->
            sign (Some signa) signbopt >>= (fun signaopt iisignbopt ->
              match signaopt with
              | None -> raise (Impossible 45)
              | Some signa ->
                  return (
                    (A.SignedT (signa,None)) +> A.rewrap ta,
                    (B.BaseType baseb, iisignbopt)
                  )
            )
        | _ -> fail
        )



    (* todo? iso with array *)
    | A.Pointer (typa, iamult),            (B.Pointer typb, ii) ->
        let (ibmult) = tuple_of_list1 ii in
        fullType typa typb >>= (fun typa typb ->
        tokenf iamult ibmult >>= (fun iamult ibmult ->
          return (
            (A.Pointer (typa, iamult)) +> A.rewrap ta,
            (B.Pointer typb, [ibmult])
          )))

    | A.FunctionPointer(tya,lp1a,stara,rp1a,lp2a,paramsa,rp2a),
        (B.ParenType t1, ii) ->
        let (lp1b, rp1b) = tuple_of_list2 ii in
        let (qu1b, t1b) = t1 in
        (match t1b with
        | B.Pointer t2, ii ->
            let (starb) = tuple_of_list1 ii in
            let (qu2b, t2b) = t2 in
            (match t2b with
            | B.FunctionType (tyb, (paramsb, (isvaargs, iidotsb))), ii ->
                let (lp2b, rp2b) = tuple_of_list2 ii in

                if isvaargs
                then
		  pr2_once
		    ("Not handling well variable length arguments func. "^
		     "You have been warned");

                fullType tya tyb >>= (fun tya tyb ->
                tokenf lp1a lp1b >>= (fun lp1a lp1b ->
                tokenf rp1a rp1b >>= (fun rp1a rp1b ->
                tokenf lp2a lp2b >>= (fun lp2a lp2b ->
                tokenf rp2a rp2b >>= (fun rp2a rp2b ->
                tokenf stara starb >>= (fun stara starb ->
                parameters (seqstyle paramsa) (A.unwrap paramsa) paramsb >>=
                (fun paramsaunwrap paramsb ->
                  let paramsa = A.rewrap paramsa paramsaunwrap in

                  let t2 =
                    (qu2b,
                    (B.FunctionType (tyb, (paramsb, (isvaargs, iidotsb))),
                    [lp2b;rp2b]))
                  in
                  let t1 =
                    (qu1b,
                    (B.Pointer t2, [starb]))
                  in

                  return (
                    (A.FunctionPointer(tya,lp1a,stara,rp1a,lp2a,paramsa,rp2a))
                    +> A.rewrap ta,
                    (B.ParenType t1, [lp1b;rp1b])
                  )
                )))))))



            | _ -> fail
            )
        | _ -> fail
        )



    (* todo: handle the iso on optional size specification ? *)
    | A.Array (typa, ia1, eaopt, ia2), (B.Array (ebopt, typb), ii) ->
        let (ib1, ib2) = tuple_of_list2 ii in
        fullType typa typb >>= (fun typa typb ->
        eoption expression eaopt ebopt >>= (fun eaopt ebopt ->
        tokenf ia1 ib1 >>= (fun ia1 ib1 ->
        tokenf ia2 ib2 >>= (fun ia2 ib2 ->
          return (
            (A.Array (typa, ia1, eaopt, ia2)) +> A.rewrap ta,
            (B.Array (ebopt, typb), [ib1;ib2])
          )))))


    | A.Decimal(dec,lp,length,Some comma,Some precision,rp),
	(B.Decimal (len, Some prec), ii) ->
        let (ib1, ib2, ib3, ib4) = tuple_of_list4 ii in
        expression length len >>= (fun length len ->
        expression precision prec >>= (fun precision prec ->
        tokenf dec ib1   >>= (fun dec ib1 ->
        tokenf lp ib2    >>= (fun lp ib2 ->
        tokenf comma ib3 >>= (fun comma ib3 ->
        tokenf rp ib4    >>= (fun rp ib4 ->
          return (
            (A.Decimal(dec,lp,length,Some comma,Some precision,rp)) +>
	      A.rewrap ta,
            (B.Decimal (len, Some prec), [ib1;ib2;ib3;ib4])
          )))))))


    | A.Decimal(dec,lp,length,None,None,rp),
	(B.Decimal (len, None), ii) ->
        let (ib1, ib2, ib3) = tuple_of_list3 ii in
        expression length len >>= (fun length len ->
        tokenf dec ib1 >>= (fun dec ib1 ->
        tokenf lp ib2  >>= (fun lp ib2 ->
        tokenf rp ib3  >>= (fun rp ib3 ->
          return (
            (A.Decimal(dec,lp,length,None,None,rp)) +> A.rewrap ta,
            (B.Decimal (len,None), [ib1;ib2;ib3])
          )))))


     (* todo: could also match a Struct that has provided a name *)
     (* This is for the case where the SmPL code contains "struct x", without
	a definition.  In this case, the name field is always present.
        This case is also called from the case for A.StructUnionDef when
        a name is present in the C code. *)
    | A.StructUnionName(sua, Some sa), (B.StructUnionName (sub, sb), ii) ->
        (* sa is now an ident, not an mcode, old: ... && (term sa) = sb *)
        let (ib1, ib2) = tuple_of_list2 ii in
        if equal_structUnion  (term sua) sub
        then
          ident DontKnow sa (sb, ib2) >>= (fun sa (sb, ib2) ->
          tokenf sua ib1 >>= (fun sua ib1 ->
            return (
              (A.StructUnionName (sua, Some sa)) +> A.rewrap ta,
              (B.StructUnionName (sub, sb), [ib1;ib2])
              )))
        else fail


    | A.StructUnionDef(ty, lba, declsa, rba),
     (B.StructUnion (sub, sbopt, declsb), ii) ->

       let (ii_sub_sb, lbb, rbb) =
	 match ii with
	   [iisub; lbb; rbb] -> (Common.Left iisub,lbb,rbb)
	 | [iisub; iisb; lbb; rbb] -> (Common.Right (iisub,iisb),lbb,rbb)
	 | _ -> error ii "list of length 3 or 4 expected" in

       let process_type =
         match (sbopt,ii_sub_sb) with
           (None,Common.Left iisub) ->
	     (* the following doesn't reconstruct the complete SP code, just
		the part that matched *)
	     let rec loop s =
	       match A.unwrap s with
		 A.Type(allminus,None,ty) ->
		   (match A.unwrap ty with
		     A.StructUnionName(sua, None) ->
		       (match (term sua, sub) with
			 (A.Struct,B.Struct)
		       | (A.Union,B.Union) -> return ((),())
		       | _ -> fail) >>=
		       (fun _ _ ->
			 tokenf sua iisub >>= (fun sua iisub ->
			   let ty =
			     A.Type(allminus,None,
				    A.StructUnionName(sua, None) +> A.rewrap ty)
			       +> A.rewrap s in
			   return (ty,[iisub])))
		   | _ -> fail)
	       | A.DisjType(disjs) -> (* do we need a conj type case here? *)
		   disjs +>
		   List.fold_left (fun acc disj -> acc >|+|> (loop disj)) fail
	       | _ -> fail in
	     loop ty

         | (Some sb,Common.Right (iisub,iisb)) ->

             (* build a StructUnionName from a StructUnion *)
             let fake_su = B.nQ, (B.StructUnionName (sub, sb), [iisub;iisb]) in

             fullType ty fake_su >>= (fun ty fake_su ->
               match fake_su with
               | _nQ, (B.StructUnionName (sub, sb), [iisub;iisb]) ->
                   return (ty,  [iisub; iisb])
               | _ -> raise (Impossible 46))
	 | _ -> fail in

       process_type
	 >>= (fun ty ii_sub_sb ->

            tokenf lba lbb >>= (fun lba lbb ->
            tokenf rba rbb >>= (fun rba rbb ->
            struct_fields (A.unwrap declsa) declsb >>=(fun undeclsa declsb ->
              let declsa = A.rewrap declsa undeclsa in

              return (
                (A.StructUnionDef(ty, lba, declsa, rba)) +> A.rewrap ta,
                (B.StructUnion (sub, sbopt, declsb),ii_sub_sb@[lbb;rbb])
              )))))


  | A.TypeOfExpr (ia1, ia2, ea, ia3), (B.TypeOfExpr eb,ii) ->
      let (ib1,ib2,ib3) = tuple_of_list3 ii in
      expression ea eb >>= (fun ea eb ->
      tokenf ia1 ib1 >>= (fun ia1 ib1 ->
      tokenf ia2 ib2 >>= (fun ia2 ib2 ->
      tokenf ia3 ib3 >>= (fun ia3 ib3 ->
        return (
          ((A.TypeOfExpr (ia1, ia2, ea, ia3))) +> A.rewrap ta,
          (B.TypeOfExpr (eb),[ib1;ib2;ib3])
      )))))

  | A.TypeOfType (ia1, ia2, typa, ia3), (B.TypeOfType typb,ii) ->
      let (ib1,ib2,ib3) = tuple_of_list3 ii in
      fullType typa typb >>= (fun typa typb ->
      tokenf ia1 ib1 >>= (fun ia1 ib1 ->
      tokenf ia2 ib2 >>= (fun ia2 ib2 ->
      tokenf ia3 ib3 >>= (fun ia3 ib3 ->
        return (
          ((A.TypeOfType (ia1, ia2, typa, ia3))) +> A.rewrap ta,
          (B.TypeOfType (typb),[ib1;ib2;ib3])
      )))))


   (* todo? handle isomorphisms ? because Unsigned Int can be match on a
    * uint in the C code. But some CEs consists in renaming some types,
    * so we don't want apply isomorphisms every time.
    *)
    | A.TypeName sa,  (B.TypeName (nameb, typb), noii) ->
        assert (noii = []);

        (match nameb with
        | B.RegularName (sb, iidb) ->
            let iidb1 = tuple_of_list1 iidb in

            if (term sa) = sb
            then
              tokenf sa iidb1 >>= (fun sa iidb1 ->
                return (
                  (A.TypeName sa) +> A.rewrap ta,
                  (B.TypeName (B.RegularName (sb, [iidb1]), typb), noii)
                   ))
               else fail

           | B.CppConcatenatedName _ | B.CppVariadicName _ |B.CppIdentBuilder _
               -> raise Todo
        )
    | _, (B.FieldType (tyb, _, _), _) ->
	typeC ta (snd tyb)

    | _, (B.NoType, ii) -> fail
    | _, (B.TypeOfExpr e, ii) -> fail
    | _, (B.TypeOfType e, ii) -> fail

    | _, (B.ParenType e, ii) -> fail (* todo ?*)
    | A.EnumName(en,Some namea), (B.EnumName nameb, ii) ->
        let (ib1,ib2) = tuple_of_list2 ii in
	ident DontKnow namea (nameb, ib2) >>= (fun namea (nameb, ib2) ->
          tokenf en ib1 >>= (fun en ib1 ->
          return (
          (A.EnumName (en, Some namea)) +> A.rewrap ta,
          (B.EnumName nameb, [ib1;ib2])
          )))

    | A.EnumDef(ty, lba, idsa, rba),
	(B.Enum (sbopt, idsb), ii) ->

       let (ii_sub_sb, lbb, rbb, comma_opt) =
	 match ii with
	   [iisub; lbb; rbb; comma_opt] ->
	     (Common.Left iisub,lbb,rbb,comma_opt)
	 | [iisub; iisb; lbb; rbb; comma_opt] ->
	     (Common.Right (iisub,iisb),lbb,rbb,comma_opt)
	 | _ -> error ii "list of length 4 or 5 expected" in

       let process_type =
         match (sbopt,ii_sub_sb) with
           (None,Common.Left iisub) ->
	     (* the following doesn't reconstruct the complete SP code, just
		the part that matched *)
	     let rec loop s =
	       match A.unwrap s with
		 A.Type(allminus,None,ty) ->
		   (match A.unwrap ty with
		     A.EnumName(sua, None) ->
		       tokenf sua iisub >>= (fun sua iisub ->
			 let ty =
			   A.Type(allminus,None,A.EnumName(sua, None) +>
				  A.rewrap ty)
			     +> A.rewrap s in
			 return (ty,[iisub]))
		   | _ -> fail)
	       | A.DisjType(disjs) -> (* do we need a conj type case here? *)
		   disjs +>
		   List.fold_left (fun acc disj -> acc >|+|> (loop disj)) fail
	       | _ -> fail in
	     loop ty

         | (Some sb,Common.Right (iisub,iisb)) ->

             (* build an EnumName from an Enum *)
             let fake_su = B.nQ, (B.EnumName sb, [iisub;iisb]) in

             fullType ty fake_su >>= (fun ty fake_su ->
               match fake_su with
               | _nQ, (B.EnumName sb, [iisub;iisb]) ->
                   return (ty,  [iisub; iisb])
               | _ -> raise (Impossible 47))
	 | _ -> fail in

       process_type
	 >>= (fun ty ii_sub_sb ->

            tokenf lba lbb >>= (fun lba lbb ->
            tokenf rba rbb >>= (fun rba rbb ->
	      let idsb = resplit_initialiser idsb [comma_opt] in
	      let idsb =
		List.concat
		  (List.map
		     (function (elem,comma) -> [Left elem; Right [comma]])
		     idsb) in
            enum_fields (A.unwrap idsa) idsb >>= (fun unidsa idsb ->
              let idsa = A.rewrap idsa unidsa in
	      let idsb,iicomma =
		match List.rev idsb with
		  (Right comma)::rest ->
		    (Ast_c.unsplit_comma (List.rev rest),comma)
		| (Left _)::_ -> (Ast_c.unsplit_comma idsb,[]) (* possible *)
		| [] -> ([],[]) in
              return (
                (A.EnumDef(ty, lba, idsa, rba)) +> A.rewrap ta,
                (B.Enum (sbopt, idsb),ii_sub_sb@[lbb;rbb]@iicomma)
              ))
		)))

    | _, (B.Enum _, _) -> fail (* todo cocci ?*)

    | _,
     ((B.TypeName _ | B.StructUnionName (_, _) | B.EnumName _ |
      B.StructUnion (_, _, _) |
      B.FunctionType _ | B.Array (_, _) | B.Decimal(_, _) |
      B.Pointer _ | B.BaseType _),
     _)
     -> fail


(* todo: iso on sign, if not mentioned then free.  tochange?
 * but that require to know if signed int because explicit
 * signed int,  or because implicit signed int.
 *)

and sign signa signb =
  match signa, signb with
  | None, None -> return (None, [])
  | Some signa,  Some (signb, ib) ->
      if equal_sign (term signa) signb
      then tokenf signa ib >>= (fun signa ib ->
        return (Some signa, [ib])
      )
      else fail
  | _, _ -> fail


and minusize_list iixs =
  iixs +> List.fold_left (fun acc ii ->
    acc >>= (fun xs ys ->
    tokenf minusizer ii >>= (fun minus ii ->
      return (minus::xs, ii::ys)
    ))) (return ([],[]))
   >>= (fun _xsminys ys ->
     return ((), List.rev ys)
   )

and storage_optional_allminus allminus stoa (stob, iistob) =
  (* "iso-by-absence" for storage, and return type. *)
  X.optional_storage_flag (fun optional_storage ->
  match stoa, stob with
  | None, (stobis, inline) ->
      let do_minus () =
        if allminus
        then
          minusize_list iistob >>= (fun () iistob ->
            return (None, (stob, iistob))
          )
        else return (None, (stob, iistob))
      in

      (match optional_storage, stobis with
      | false, B.NoSto -> do_minus ()
      | false, _ -> fail
      | true, B.NoSto -> do_minus ()
      | true, _ ->
          if !FlagM.show_misc
          then pr2_once "USING optional_storage builtin isomorphism";
          do_minus()
      )

  | Some x, ((stobis, inline)) ->
      if equal_storage (term x) stobis
      then
	let rec loop acc = function
	    [] -> fail
	  | i1::iistob ->
	      let str = B.str_of_info i1 in
	      (match str with
		"static" | "extern" | "auto" | "register" ->
		  (* not very elegant, but tokenf doesn't know what token to
		     match with *)
		  tokenf x i1 >>= (fun x i1 ->
		    let rebuilt = (List.rev acc) @ i1 :: iistob in
		    return (Some x,  ((stobis, inline), rebuilt)))
	      |	_ -> loop (i1::acc) iistob) in
	loop [] iistob
      else fail
  )

and inline_optional_allminus allminus inla (stob, iistob) =
  (* "iso-by-absence" for storage, and return type. *)
  X.optional_storage_flag (fun optional_storage ->
  match inla, stob with
  | None, (stobis, inline) ->
      let do_minus () =
        if allminus
        then
          minusize_list iistob >>= (fun () iistob ->
            return (None, (stob, iistob))
          )
        else return (None, (stob, iistob))
      in

      if inline
      then
	if optional_storage
	then
	  begin
	    if !FlagM.show_misc
            then pr2_once "USING optional_storage builtin isomorphism";
            do_minus()
	  end
	else fail (* inline not in SP and present in C code *)
      else do_minus()

  | Some x, ((stobis, inline)) ->
      if inline
      then
	let rec loop acc = function
	    [] -> fail
	  | i1::iistob ->
	      let str = B.str_of_info i1 in
	      (match str with
		"inline" ->
		  (* not very elegant, but tokenf doesn't know what token to
		     match with *)
		  tokenf x i1 >>= (fun x i1 ->
		    let rebuilt = (List.rev acc) @ i1 :: iistob in
		    return (Some x,  ((stobis, inline), rebuilt)))
	      |	_ -> loop (i1::acc) iistob) in
	loop [] iistob
      else fail (* SP has inline, but the C code does not *)
  )

and fullType_optional_allminus allminus tya retb =
  match tya with
  | None ->
      if allminus
      then
        X.distrf_type minusizer retb >>= (fun _x retb ->
          return (None, retb)
        )

      else return (None, retb)
  | Some tya ->
      fullType tya retb >>= (fun tya retb ->
        return (Some tya, retb)
      )

(* Works for many attributes, but assumes order will be preserved.  Looks
for an exact match.  Actually the call site only allows a list of length
one to come through.  Makes no requirement if attributes not present. *)

(* The following is the intended version, on lists.  Unfortunately, this
   requires SmPL attributes to be wrapped.  Which they are not, for some
   reason. *)
(*
and attribute_list attras attrbs =
  X.optional_attributes_flag (fun optional_attributes ->
  match attras with
    None -> return (None, attrbs)
  | Some attras ->
      let match_dots ea = None in
      let build_dots (mcode, optexpr) =
        failwith "attribute: build dots: not possible" in
      let match_comma ea = None in
      let build_comma ia1 =
        failwith "attribute list: build comma: not possible" in
      let match_metalist ea = None in
      let build_metalist _ (ida,leninfo,keep,inherited) =
	failwith "attribute list: build meta list: not possible" in
      let mktermval v = failwith "attribute: mk term val: not possible" in
      let special_cases ea eas ebs = None in
      let no_ii x = failwith "attribute: no ii: not possible" in
      list_matcher match_dots build_dots match_comma build_comma
	match_metalist build_metalist mktermval
	special_cases attribute X.distrf_attrs
	B.split_nocomma B.unsplit_nocomma no_ii
	(function x -> Some x) attras attrbs >>=
      (fun attras attrbs -> return (Some attras, attrbs))) *)

(* The cheap hackish version.  No wrapping requires... *)

and attribute_list attras attrbs =
  X.optional_attributes_flag (fun optional_attributes ->
  match attras,attrbs with
    [], _ when optional_attributes || attrbs = [] ->
      return ([], attrbs)
  | [], _ -> fail
  | [attra], [attrb] ->
    attribute attra attrb >>= (fun attra attrb ->
      return ([attra], [attrb])
    )
  | [attra], attrb -> fail
  | _ -> failwith "only one attribute allowed in SmPL")

and attribute = fun ea eb ->
  match ea, eb with
    attra, (B.Attribute attrb, ii)
      when (A.unwrap_mcode attra) = attrb ->
      let ib1 = tuple_of_list1 ii in
      tokenf attra ib1 >>= (fun attra ib1 ->
	return (
	  attra,
	  (B.Attribute attrb, [ib1])
        ))
  | _ -> fail

(*---------------------------------------------------------------------------*)

and compatible_base_type a signa b =
  let ok  = return ((),()) in

  match a, b with
    A.VoidType,    B.Void
  | A.SizeType,    B.SizeType
  | A.SSizeType,   B.SSizeType
  | A.PtrDiffType, B.PtrDiffType ->
      assert (signa = None);
      ok
  | A.CharType, B.IntType B.CChar when signa = None ->
      ok
  | A.CharType, B.IntType (B.Si (signb, B.CChar2)) ->
      compatible_sign signa signb
  | A.ShortType, B.IntType (B.Si (signb, B.CShort)) ->
      compatible_sign signa signb
  | A.IntType, B.IntType (B.Si (signb, B.CInt)) ->
      compatible_sign signa signb
  | A.LongType, B.IntType (B.Si (signb, B.CLong)) ->
      compatible_sign signa signb
  | A.LongLongType, B.IntType (B.Si (signb, B.CLongLong)) ->
      compatible_sign signa signb
  | A.FloatType, B.FloatType B.CFloat
  | A.DoubleType, B.FloatType B.CDouble
  | A.FloatComplexType, B.FloatType B.CFloatComplex
  | A.DoubleComplexType, B.FloatType B.CDoubleComplex
  | A.LongDoubleType, B.FloatType B.CLongDouble ->
      assert (signa = None);
      ok
  | A.BoolType, _ -> failwith "no booltype in C"

  | _, (B.Void|B.FloatType _|B.IntType _
        |B.SizeType|B.SSizeType|B.PtrDiffType) -> fail

and compatible_base_type_meta a signa qua b ii local =
  let fullType_of_baseType b = Ast_c.mk_ty (Ast_c.BaseType b) [] in
  match A.unwrap a, b with
    A.MetaType(ida, cstr, keep, inherited),
    B.IntType (B.Si (signb, B.CChar2)) ->
      check_constraints cstr ida (B.MetaTypeVal (fullType_of_baseType b))
	(fun () ->
	  compatible_sign signa signb >>= fun _ _ ->
	    let newb = ((qua, (B.BaseType (B.IntType B.CChar),ii)),local) in
	    compatible_typeC a newb
	    )
  | A.MetaType(ida, cstr, keep, inherited), B.IntType (B.Si (signb, ty)) ->
      check_constraints cstr ida (B.MetaTypeVal (fullType_of_baseType b))
	(fun () ->
	  compatible_sign signa signb >>= fun _ _ ->
	    let newb =
	      ((qua, (B.BaseType (B.IntType (B.Si (B.Signed, ty))),ii)),
	       local) in
	    compatible_typeC a newb
	    )
  | _, B.FloatType B.CLongDouble ->
      pr2_once "no longdouble in cocci";
      fail

  | _, (B.Void|B.FloatType _|B.IntType _
        |B.SizeType|B.SSizeType|B.PtrDiffType) -> fail

and compatible_type a (b,local) =
  match A.unwrap a, b with
    A.Type (false, None, a'), _ ->
      compatible_typeC a' (b, local)
  | A.Type (false, Some const_vol, a'), (qub, b') ->
      if (fst qub).B.const && (fst qub).B.volatile
      then
        begin
          pr2_once ("warning: the type is both const & volatile but cocci " ^
                    "does not handle that");
          fail
        end
      else if
        (match A.unwrap_mcode const_vol with
        | A.Const -> (fst qub).B.const
        | A.Volatile -> (fst qub).B.volatile
        )
      then compatible_typeC a' ((Ast_c.nQ, b'), local)
      else fail
  | _ ->
      failwith "Cocci_vs_c.compatible_type: unimplemented"
and compatible_typeC a (b,local) =
  let ok  = return ((),()) in

  let rec loop tya tyb =
    match A.unwrap tya, tyb with
    | _, (qua, (B.NoType, _)) ->
	failwith "compatible_type: matching with NoType"
  (* for metavariables of type expression *^* *)
  (* must be before the general BaseType case *)
    | A.BaseType (A.Unknown, _) , _ -> ok
    | A.BaseType (a, _), (qua, (B.BaseType b,ii)) ->
	compatible_base_type a None b

    | A.SignedT (signa,None), (qua, (B.BaseType b,ii)) ->
        compatible_base_type A.IntType (Some signa) b

    | A.SignedT (signa,Some ty), (qua, (B.BaseType b,ii)) ->
        (match A.unwrap ty with
          A.BaseType (ty, _) ->
	    compatible_base_type ty (Some signa) b
        | A.MetaType(ida, cstr, keep, inherited) ->
	    check_constraints cstr ida (B.MetaTypeVal tyb)
	      (fun () ->
		compatible_base_type_meta ty (Some signa) qua b ii local
		  )
	| _ -> failwith "compatible_typeC: not possible")

    | A.Pointer (a, _), (qub, (B.Pointer b, ii)) ->
	compatible_type a (b, local)
    | A.FunctionPointer (a, _, _, _, _, _, _), _ ->
	failwith
	  "TODO: function pointer type doesn't store enough information to determine compatibility"
    | A.Array (a, _, _, _), (qub, (B.Array (eopt, b),ii)) ->
      (* no size info for cocci *)
	compatible_type a (b, local)
    | A.Decimal(_, _, e1, _, e2, _), (qub, (B.Decimal(l,p),ii)) ->
	(match X.mode with
	  TransformMode -> ok (* nothing to do here *)
	| PatternMode ->
      (* no size info for cocci *)
	    expression e1 l >>=
	    (fun _ _ -> (* no transformation to record *)
	      match p with
		None -> failwith "not allowed in a type"
	      | Some p ->
                  match e2 with
                  | None -> ok
                  | Some e2 ->
                      expression e2 p >>=
                      (fun _ _ -> (* no transformation to record *)
                        ok)))
    | A.StructUnionName (sua, name),
	(qub, (B.StructUnionName (sub, sb),ii)) ->
	  if equal_structUnion_type_cocci sua sub
	  then structure_type_name name sb ii
	  else fail
    | A.EnumName (_, name),
	(qub, (B.EnumName (sb),ii)) -> structure_type_name name sb ii
    | A.TypeName sa, (qub, (B.TypeName (namesb, _typb),noii)) ->
        let sb = Ast_c.str_of_name namesb in
	if A.unwrap_mcode sa = sb
	then ok
	else fail

    | A.MetaType (ida, cstr, keep, inherited), typb ->
	let max_min _ = Lib_parsing_c.ii_of_type typb in
        let ida' = A.make_mcode (A.unwrap_mcode ida) in
      check_constraints cstr ida (B.MetaTypeVal typb)
	(fun () ->
          X.envf keep inherited (ida', B.MetaTypeVal typb, max_min)
	    (fun () -> ok
            )
	    )
    | _, (_, (B.FieldType (typb, _, _), _)) ->
	loop tya typb

  (* subtil: must be after the MetaType case *)
    | a, (qub, (B.TypeName (_namesb, Some b), noii)) ->
      (* kind of typedef iso *)
	loop tya b

    | (_,
      (_,
      ((
       B.TypeOfType _|B.TypeOfExpr _|B.ParenType _|
       B.EnumName _|B.StructUnion (_, _, _)|B.Enum (_, _)
      ),
      _))) -> fail

    | (_,
      (_,
      ((
       B.StructUnionName (_, _)|
       B.FunctionType _|
       B.Array (_, _)|B.Decimal (_, _)|B.Pointer _|B.TypeName _|
       B.BaseType _
      ),
      _))) -> fail
(*
and decimal_type_exp nm sb ii =
    match nm with
      A.NoName -> failwith "unexpected NoName in decimal type"
    | A.Name sa ->
	(match B.unwrap sb with
	  B.Ident name ->
	    let ida = A.make_term(A.Id(A.make_mcode n)) in
	    ident_cpp DontKnow ida nameidb >>= (fun ida nameidb -> ok)
	| _ -> fail)
    | A.Num sa ->
    | A.MV(ida,keep,inherited) ->
	(* degenerate version of MetaId, no transformation possible *)
        let (ib1, ib2) = tuple_of_list2 ii in
	let max_min _ = [ib2] in
	let mida = A.make_mcode ida in
	X.envf keep inherited (mida, B.MetaIdVal sb, max_min)
	  (fun () -> ok)
*)
and structure_type_name nm sb ii =
    match nm with
      None -> ok
    | Some nm' ->
        match A.unwrap nm' with
        | A.Id id ->
            if A.unwrap_mcode id = sb
            then ok
            else fail
        | A.MetaId (ida, constraints, keep, inherited) ->
	    check_constraints constraints ida (B.MetaIdVal sb)
	      (fun () ->
		(* degenerate version of MetaId, no transformation possible *)
		let (ib1, ib2) = tuple_of_list2 ii in
		let max_min _ = [ib2] in
		X.envf keep inherited (ida, B.MetaIdVal sb, max_min)
		  (fun () -> ok))
        | _ -> failwith "Cocci_vs_c.structure_type_name: unimplemented"
  in
  loop a b

and compatible_sign signa signb =
  let ok  = return ((),()) in
  match Common.map_option A.unwrap_mcode signa, signb with
  | None, B.Signed
  | Some A.Signed, B.Signed
  | Some A.Unsigned, B.UnSigned
      -> ok
  | _ -> fail


and equal_structUnion_type_cocci a b =
  match Ast_cocci.unwrap_mcode a, b with
    A.Struct, B.Struct -> true
  | A.Union,  B.Union -> true
  | _, (B.Struct | B.Union) -> false



(*---------------------------------------------------------------------------*)
and inc_file (a, before_after) (b, h_rel_pos, o_rel_pos) =

  let rec aux_inc rel_pos (ass, bss) passed =
    match ass, bss with
    | [], [] -> true
    | [A.IncDots], _ ->
        let passed = List.rev passed in

        (match before_after, !rel_pos with
        | IncludeNothing, _ -> true
        | IncludeMcodeBefore, Some x ->
	    List.mem passed (x.Ast_c.first_of)

        | IncludeMcodeAfter, Some x ->
            List.mem passed (x.Ast_c.last_of)

        (* no info, maybe cos of a #include <xx.h> that was already in a .h *)
        | _, None -> false
        )

    | (A.IncPath x)::xs, y::ys -> x = y && aux_inc rel_pos (xs, ys) (x::passed)
    | _ -> failwith "IncDots not in last place or other pb"

  in

  match a, b with
  | A.Local ass, B.Local bss ->
      aux_inc h_rel_pos (ass, bss) []
  | A.NonLocal ass, B.NonLocal bss ->
      aux_inc h_rel_pos (ass, bss) []
  | A.AnyInc, (B.Local bss | B.NonLocal bss) ->
      aux_inc o_rel_pos ([A.IncDots], bss) []
  | _ -> false



(*---------------------------------------------------------------------------*)

and (define_params: sequence ->
  (A.define_param list, (string B.wrap) B.wrap2 list) matcher) =
 fun seqstyle eas ebs ->
  match seqstyle with
  | Unordered -> failwith "not handling ooo"
  | Ordered ->
      define_paramsbis eas (Ast_c.split_comma ebs) >>= (fun eas ebs_splitted ->
        return (eas, (Ast_c.unsplit_comma ebs_splitted))
      )

(* todo? facto code with argument and parameters ? *)
and define_paramsbis = fun eas ebs ->
  let match_dots ea =
    match A.unwrap ea with
      A.DPdots(mcode) -> Some (mcode, None)
    | _ -> None in
  let build_dots (mcode, _optexpr) = A.DPdots(mcode) in
  let match_comma ea =
    match A.unwrap ea with
      A.DPComma ia1 -> Some ia1
    | _ -> None in
  let build_comma ia1 = A.DPComma ia1 in
  let match_metalist ea =
    match A.unwrap ea with
      A.MetaDParamList(ida,leninfo,cstr,keep,inherited) ->
        Some(ida,leninfo,cstr,keep,inherited,None)
    |  _ -> None in
  let build_metalist ea (ida,leninfo,cstr,keep,inherited) =
    match A.unwrap ea with
      A.MetaDParamList(_,_,_,_,_) ->
	A.MetaDParamList(ida,leninfo,cstr,keep,inherited)
    | _ -> failwith "define_param: build meta list: not possible" in
  let mktermval v = Ast_c.MetaDParamListVal v in
  let special_cases ea eas ebs = None in
  let no_ii x = failwith "define_param: no ii: not possible" in
  list_matcher match_dots build_dots match_comma build_comma
    match_metalist build_metalist mktermval
    special_cases define_parameter X.distrf_define_params
    B.split_comma B.unsplit_comma no_ii
    (function x -> Some x) eas ebs

and define_parameter = fun parama paramb ->
  match A.unwrap parama, paramb with
    A.DParam ida, (idb, ii) ->
      let ib1 = tuple_of_list1 ii in
      ident DontKnow ida (idb, ib1) >>= (fun ida (idb, ib1) ->
        return ((A.DParam ida)+> A.rewrap parama,(idb, [ib1])))
  | A.OptDParam _, _ -> failwith "handling Opt for define parameters"
  | _ -> fail in

  let rec check_constraints ida idb env c =
    let get_assignOp op = assignOpA_of_assignOpB (fst op) in
    let get_binaryOp op = binaryOpA_of_binaryOpB (fst op) in
    let check_string f =
      let s =
	match idb with
	  B.MetaIdVal s -> Some s
	| B.MetaExprVal (e, _, _) -> Some (string_of_expression e)
	| B.MetaTypeVal t -> Some (Pretty_print_c.string_of_fullType t)
	| B.MetaAssignOpVal op ->
	    Some (A.string_of_assignOp (A.make_term (get_assignOp op)))
	| B.MetaBinaryOpVal op ->
	    Some (A.string_of_binaryOp (A.make_term (get_binaryOp op)))
	| _ -> None in
      match s with
	Some s -> f s
      | None -> fail in
    let check_int f =
      let i =
	match idb with
	  B.MetaExprVal (e, _, _) ->
	    begin
	      match B.unwrap_expr e with
		B.Constant (B.Int (i, _)) -> Some i
	      | _ -> None
	    end
	| B.MetaListlenVal i -> Some (string_of_int i)
	| _ -> None in
      match i with
	Some i -> f i
      | None -> fail in
    let check_operator c =
      match c, idb with
	A.CstrAssignOp op, B.MetaAssignOpVal op' ->
	  assignOp_eq (A.unwrap op) (get_assignOp op')
      | A.CstrBinaryOp op, B.MetaBinaryOpVal op' ->
	  binaryOp_eq (A.unwrap op) (get_binaryOp op')
      | _ -> false in
    let bool b =
      if b then return ((), ())
      else fail in
    match c with
      A.CstrFalse -> fail
    | A.CstrTrue -> return ((), ())
    | A.CstrAnd list ->
	let rec loop list =
	  match list with
	    [] -> return ((), ())
	  | hd :: tl ->
	      check_constraints ida idb env hd >>=
	      (fun () () -> loop tl) in
	loop list
    | A.CstrOr list ->
	let rec loop list =
	  match list with
	    [] -> fail
	  | hd :: tl ->
	      check_constraints ida idb env hd >||>
	      loop tl in
	loop list
    | A.CstrNot c ->
	X.mnot (check_constraints ida idb env c) ((), ())
    | A.CstrConstant (A.CstrString s) ->
	check_string (fun s' -> bool (s = s'))
    | A.CstrConstant (A.CstrInt c') ->
	let interp s =
	  int_of_string(List.hd(Str.split (Str.regexp "[UL]") s)) in
	check_int (fun i' -> bool (match c' with
	  A.CstrIntEq i -> i' = i
	| A.CstrIntLeq i -> interp i' <= i
	| A.CstrIntGeq i -> interp i' >= i))
    | A.CstrOperator c -> bool (check_operator c)
    | A.CstrMeta_name mn ->
	begin
	  match Common.optionise (fun () -> env mn) with
	    Some mv when equal_inh_metavarval mv idb -> return ((), ())
	  | _ -> fail
	end
    | A.CstrRegexp (s, re) ->
	check_string (fun s' -> bool (Regexp.string_match re s'))
    | A.CstrScript(local,script_constraint) ->
	if local
	then bool (satisfies_script_constraint script_constraint ida idb env)
	else bool true
    | A.CstrExpr e ->
	begin
	  match idb with
	    B.MetaExprVal (e', _, _) ->
	      expression e e' >>= (fun _ _ -> return ((), ()))
	  | _ ->
	      match A.string_of_expression e with
		Some s -> check_string (fun s' -> bool (s = s'))
	      | _ -> fail
	end
    | A.CstrSub _ -> failwith "Sub-expression constraint unallowed here"
    | A.CstrType ty ->
	begin
	  match idb with
	    B.MetaTypeVal ty' ->
	      fullType ty ty' >>= (fun _ _ -> return ((), ()))
	  | _ -> fail
	end in
  X.constraint_checker := check_constraints;

(*****************************************************************************)
(* Entry points *)
(*****************************************************************************)

(* no global solution for positions here, because for a statement metavariable
we want a MetaStmtVal, and for the others, it's not clear what we want *)

(*
let rec (rule_elem_node: (A.rule_elem, F.node) matcher) =
 fun re node ->
*)
  let rewrap x =
    x >>= (fun a b -> return (A.rewrap re a, F.rewrap node b))
  in
  X.all_bound (A.get_inherited re) >&&>

  (rewrap (
  match A.unwrap re, F.unwrap node with

  (* note: the order of the clauses is important. *)

  | _, F.Enter | _, F.Exit | _, F.ErrorExit -> fail2()

  (* the metaRuleElem contains just '-' information. We don't need to add
   * stuff in the environment. If we need stuff in environment, because
   * there is a + S somewhere, then this will be done via MetaStmt, not
   * via MetaRuleElem.
   * Can match TrueNode/FalseNode/... so must be placed before those cases.
   *)

  | A.MetaRuleElem(mcode,cstr,keep,inherited), unwrap_node ->
      let default = A.MetaRuleElem(mcode,cstr,keep,inherited), unwrap_node in
      (match unwrap_node with
      | F.CaseNode _
      | F.TrueNode _ | F.FalseNode | F.AfterNode _ | F.EndNode
      | F.LoopFallThroughNode  | F.FallThroughNode
      | F.InLoopNode ->
          if X.mode = PatternMode
          then return default
          else
            if mcode_contain_plus (mcodekind mcode)
            then failwith "try add stuff on fake node"
              (* minusize or contextize a fake node is ok *)
            else return default

      | F.EndStatement None ->
          if X.mode = PatternMode then return default
          else
              (* DEAD CODE NOW ? only useful in -no_cocci_vs_c_3 ?
                 if mcode_contain_plus (mcodekind mcode)
                 then
                 let fake_info = Ast_c.fakeInfo() in
                 distrf distrf_node (mcodekind mcode)
                 (F.EndStatement (Some fake_info))
                 else return unwrap_node
              *)
            raise Todo

      | F.EndStatement (Some i1) ->
          tokenf mcode i1 >>= (fun mcode i1 ->
            return (
              A.MetaRuleElem (mcode,cstr,keep, inherited),
              F.EndStatement (Some i1)
            ))

      | F.FunHeader _ ->
          if X.mode = PatternMode then return default
          else failwith "a MetaRuleElem can't transform a headfunc"
      | _n ->
          if X.mode = PatternMode then return default
          else
          X.distrf_node (generalize_mcode mcode) node >>= (fun mcode node ->
            return (
              A.MetaRuleElem(mcode,cstr,keep, inherited),
              F.unwrap node
            ))
      )


  (* rene cannot have found that a state containing a fake/exit/... should be
   * transformed
   * TODO: and F.Fake ?
   *)
  | _, F.EndStatement _ | _, F.CaseNode _
  | _, F.TrueNode _ | _, F.FalseNode | _, F.AfterNode _
  | _, F.FallThroughNode | _, F.LoopFallThroughNode
  | _, F.InLoopNode -> fail2()

  (* really ? diff between pattern.ml and transformation.ml *)
  | _, F.Fake -> fail2()


  (* cas general: a Meta can match everything. It matches only
   * "header"-statement. We transform only MetaRuleElem, not MetaStmt.
   * So can't have been called in transform.
   *)
  | A.MetaStmt (ida,cstr,keep,metainfoMaybeTodo,inherited),  F.Decl(_) -> fail

  | A.MetaStmt (ida,cstr,keep,metainfoMaybeTodo,inherited),  unwrap_node ->
      (* todo: should not happen in transform mode *)

      (match F.extract_fullstatement node with
      | Some stb ->
	    let max_min _ = Lib_parsing_c.ii_of_stmt stb in
	    let mv = Ast_c.MetaStmtVal(stb,stb,Ast_c.WITH_TYPES) in
	    X.check_constraints (A.unwrap_mcode ida) mv cstr
              (fun () ->
		X.envf keep inherited
		  (ida, mv, max_min)
		  (fun () ->
		    (* no need tag ida, we can't be called in transform-mode *)
		    return (
		    A.MetaStmt (ida, cstr, keep, metainfoMaybeTodo, inherited),
		    unwrap_node
		   ))
	    )
      | None -> fail
      )

  | A.MetaStmtList (ida,leninfo,cstr,keep,inherited),  unwrap_node ->
      (* todo: should not happen in transform mode *)

      (match F.extract_fullstatement node with
      | Some (B.Compound stb,_) ->
	  match_len stb leninfo
	    (fun _ ->
	      let max_min _ = Lib_parsing_c.ii_of_stmtseqlist stb in
	      let mv = Ast_c.MetaStmtListVal(stb,Ast_c.WITH_TYPES) in
	      X.check_constraints (A.unwrap_mcode ida) mv cstr
		(fun () ->
		  X.envf keep inherited
		    (ida, mv, max_min)
		    (fun () ->
		    (* no need tag ida, we can't be called in transform-mode *)
		      return (
		      A.MetaStmtList (ida, leninfo, cstr, keep, inherited),
		      unwrap_node
		     ))))
      | _ -> fail
      )

  | A.TopExp ea, F.DefineExpr eb  ->
      expression ea eb >>= (fun ea eb ->
        return (
          A.TopExp ea,
          F.DefineExpr eb
        ))

  | A.TopExp ea, F.DefineType eb  ->
      (match A.unwrap ea with
	A.TypeExp(ft) ->
	  fullType ft eb >>= (fun ft eb ->
            return (
              A.TopExp (A.rewrap ea (A.TypeExp(ft))),
              F.DefineType eb
            ))
      |	_ -> fail)
  | A.TopInit ea, F.DefineInit eb  ->
      initialiser ea eb >>= (fun ea eb ->
        return (
          A.TopInit ea,
          F.DefineInit eb
        ))


  (* It is important to put this case before the one that fails because
   * of the lack of the counter part of a C construct in SmPL (for instance
   * there is not yet a CaseRange in SmPL). Even if SmPL don't handle
   * yet certain constructs, those constructs may contain expression
   * that we still want and can transform.
   *)

  | A.Exp exp, nodeb ->
     (* Now keep fullstatement inside the control flow node,
      * so that can then get in a MetaStmtVar the fullstatement to later
      * pp back when the S is in a +. But that means that
      * Exp will match an Ifnode even if there is no such exp
      * inside the condition of the Ifnode (because the exp may
      * be deeper, in the then branch). So have to not visit
      * all inside a node anymore.
      *
      * update: j'ai choisi d'accrocher au noeud du CFG à la
      * fois le fullstatement et le partialstatement et appeler le
      * visiteur que sur le partialstatement.
      *)
      let expfn =
        match Ast_cocci.get_pos re with
        | None -> expression
        | Some pos ->
            (fun ea eb ->
              let (max,min) =
                Lib_parsing_c.max_min_by_pos (Lib_parsing_c.ii_of_expr eb) in
              let keep = A.Unitary in
              let inherited = false in
	      let max_min _ = failwith "no pos" in
              X.envf keep inherited (pos, B.MetaPosVal (min,max), max_min)
		(fun () ->
                  expression ea eb
              )
            )
      in

      (* kind of iso, initialisation vs affectation *)
      (match A.unwrap exp, nodeb with
      | A.Assignment (ea, op, eb, true), F.Decl decl ->
	  let n =
            initialisation_to_affectation decl +> F.rewrap node in
	  X.cocciExp expfn exp n >>= (fun exp n ->
            return (
            A.Exp exp,
	    (* should be ok to keep node, because the changed part is inside *)
            F.unwrap node))
      | _ ->
	  X.cocciExp expfn exp node >>= (fun exp node ->
            return (
            A.Exp exp,
            F.unwrap node)))

  | A.Ty ty, nodeb ->
      X.cocciTy fullType ty node >>= (fun ty node ->
        return (
          A.Ty ty,
          F.unwrap node
        )
      )

  | A.TopId id, nodeb ->
      X.cocciId (ident_cpp DontKnow) id node >>= (fun id node ->
        return (
          A.TopId id,
          F.unwrap node
        )
      )

  | A.TopInit init, nodeb ->
      X.cocciInit initialiser init node >>= (fun init node ->
        return (
          A.TopInit init,
          F.unwrap node
        )
      )


  | A.FunHeader (mckstart, allminus, fninfoa, ida, oparen, paramsa, va, cparen),
    F.FunHeader ({B.f_name = nameidb;
                  f_type = (retb, (paramsb, (isvaargs, iidotsb)));
                  f_storage = stob;
                  f_attr = attrs;
                  f_body = body;
                  f_old_c_style = oldstyle;
                  }, ii) ->
      assert (body = []);

      if oldstyle <> None
      then pr2 "OLD STYLE DECL NOT WELL SUPPORTED";

      let (stoa,tya,inla,attras) = get_fninfo fninfoa in

      (match ii with
      | ioparenb::icparenb::iifakestart::iistob ->

          (* maybe important to put ident as the first tokens to transform.
           * It's related to transform_proto. So don't change order
           * between the >>=.
           *)
          ident_cpp LocalFunction ida nameidb >>= (fun ida nameidb ->
          X.tokenf_mck mckstart iifakestart >>= (fun mckstart iifakestart ->
          tokenf oparen ioparenb >>= (fun oparen ioparenb ->
          tokenf cparen icparenb >>= (fun cparen icparenb ->
          parameters (seqstyle paramsa)
            (A.unwrap paramsa) paramsb >>=
            (fun paramsaunwrap paramsb ->
              let paramsa = A.rewrap paramsa paramsaunwrap in
          inline_optional_allminus allminus
            inla (stob, iistob) >>= (fun inla (stob, iistob) ->
          storage_optional_allminus allminus
            stoa (stob, iistob) >>= (fun stoa (stob, iistob) ->
          attribute_list attras attrs >>= (fun attras attrs ->
              (
                if isvaargs
                then
		  pr2_once
		    ("Not handling well variable length arguments func. "^
		     "You have been warned");
                if allminus
                then minusize_list iidotsb
                else return ((),iidotsb)
              ) >>= (fun () iidotsb ->

           fullType_optional_allminus allminus tya retb >>= (fun tya retb ->

             let fninfoa = put_fninfo stoa tya inla attras in

             return (
               A.FunHeader(mckstart,allminus,fninfoa,ida,oparen,
                          paramsa,va,cparen),
               F.FunHeader ({B.f_name = nameidb;
                             f_type = (retb, (paramsb, (isvaargs, iidotsb)));
                             f_storage = stob;
                             f_attr = attrs;
                             f_body = body;
                             f_old_c_style = oldstyle; (* TODO *)
                           },
                           ioparenb::icparenb::iifakestart::iistob)
                )
              ))))))))))
      | _ -> raise (Impossible 49)
      )

  | A.Decl decla, F.Decl declb ->
      annotated_decl decla declb >>=
       (fun decla declb ->
        return (
          A.Decl decla,
          F.Decl declb
        ))


  | A.SeqStart mcode, F.SeqStart (st, level, i1) ->
      tokenf mcode i1 >>= (fun mcode i1 ->
        return (
          A.SeqStart mcode,
          F.SeqStart (st, level, i1)
        ))

  | A.SeqEnd mcode, F.SeqEnd (level, i1) ->
      tokenf mcode i1 >>= (fun mcode i1 ->
        return (
          A.SeqEnd mcode,
          F.SeqEnd (level, i1)
          ))

  | A.ExprStatement (Some ea, ia1), F.ExprStatement (st, (Some eb, ii)) ->
      let ib1 = tuple_of_list1 ii in
      expression ea eb >>= (fun ea eb ->
      tokenf ia1 ib1 >>= (fun ia1 ib1 ->
        return (
          A.ExprStatement (Some ea, ia1),
          F.ExprStatement (st, (Some eb, [ib1]))
        )
      ))

  | A.ExprStatement (None, ia1), F.ExprStatement (st, (None, [ib1])) ->
      (* ia1/ib1 represents a ; *)
      tokenf ia1 ib1 >>= (fun ia1 ib1 ->
        return (
          A.ExprStatement (None, ia1),
          F.ExprStatement (st, (None, [ib1]))
        )
      )

  | _, F.ExprStatement (st, (None, [])) ->
      (* This case occurs when we have eg nothing after a switch label
	 and so there is no semicolon.  Indeed, there is no match, so any
	 match against this fails. *)
      fail

  | A.IfHeader (ia1,ia2, ea, ia3), F.IfHeader (st, (eb,ii)) ->
      let (ib1, ib2, ib3) = tuple_of_list3 ii in
      expression ea eb >>= (fun ea eb ->
      tokenf ia1 ib1 >>= (fun ia1 ib1 ->
      tokenf ia2 ib2 >>= (fun ia2 ib2 ->
      tokenf ia3 ib3 >>= (fun ia3 ib3 ->
        return (
          A.IfHeader (ia1, ia2, ea, ia3),
          F.IfHeader (st, (eb,[ib1;ib2;ib3]))
        )))))

  | A.Else ia, F.Else ib ->
      tokenf ia ib >>= (fun ia ib ->
        return (A.Else ia, F.Else ib)
      )

  | A.WhileHeader (ia1, ia2, ea, ia3), F.WhileHeader (st, (eb, ii)) ->
      let (ib1, ib2, ib3) = tuple_of_list3 ii in
      expression ea eb >>= (fun ea eb ->
      tokenf ia1 ib1 >>= (fun ia1 ib1 ->
      tokenf ia2 ib2 >>= (fun ia2 ib2 ->
      tokenf ia3 ib3 >>= (fun ia3 ib3 ->
        return (
          A.WhileHeader (ia1, ia2, ea, ia3),
          F.WhileHeader (st, (eb, [ib1;ib2;ib3]))
        )))))

  | A.DoHeader ia, F.DoHeader (st, ib) ->
      tokenf ia ib >>= (fun ia ib ->
        return (
          A.DoHeader ia,
          F.DoHeader (st, ib)
        ))
  | A.WhileTail (ia1,ia2,ea,ia3,ia4), F.DoWhileTail (eb, ii) ->
      let (ib1, ib2, ib3, ib4) = tuple_of_list4 ii in
      expression ea eb >>= (fun ea eb ->
      tokenf ia1 ib1 >>= (fun ia1 ib1 ->
      tokenf ia2 ib2 >>= (fun ia2 ib2 ->
      tokenf ia3 ib3 >>= (fun ia3 ib3 ->
      tokenf ia4 ib4 >>= (fun ia4 ib4 ->
        return (
          A.WhileTail (ia1,ia2,ea,ia3,ia4),
          F.DoWhileTail (eb, [ib1;ib2;ib3;ib4])
        ))))))
  | A.IteratorHeader (ia1, ia2, eas, ia3), F.MacroIterHeader (st, ((s,ebs),ii))
      ->
      let (ib1, ib2, ib3) = tuple_of_list3 ii in

      ident DontKnow ia1 (s, ib1) >>= (fun ia1 (s, ib1) ->
      tokenf ia2 ib2 >>= (fun ia2 ib2 ->
      tokenf ia3 ib3 >>= (fun ia3 ib3 ->
      arguments (seqstyle eas) (A.unwrap eas) ebs >>= (fun easunwrap ebs ->
       let eas = A.rewrap eas easunwrap in
       return (
         A.IteratorHeader (ia1, ia2, eas, ia3),
         F.MacroIterHeader (st, ((s,ebs), [ib1;ib2;ib3]))
       )))))



  | A.ForHeader (ia1, ia2, firsta, ea2opt, ia4, ea3opt, ia5),
    F.ForHeader (st, ((firstb, (eb2opt,ib4s), (eb3opt,ib4vide)), ii))
    ->
      assert (ib4vide = []);
      let (ib1, ib2, ib5) = tuple_of_list3 ii in
      let ib4 = tuple_of_list1 ib4s in

      (match (firsta,firstb) with
	(A.ForExp(ea1opt, ia3),B.ForExp(eb1opt,ib3s)) ->
	  let ib3 = tuple_of_list1 ib3s in
	  tokenf ia3 ib3 >>= (fun ia3 ib3 ->
	  eoption expression ea1opt eb1opt >>= (fun ea1opt eb1opt ->
	    return (A.ForExp(ea1opt, ia3),B.ForExp(eb1opt,[ib3]))))
      |	(A.ForDecl decla,B.ForDecl declb) ->
	  annotated_decl decla declb >>=
	  (fun decla declb ->
	    return (
            A.ForDecl decla,
            B.ForDecl declb
          ))
      |	_ -> fail)
	>>=
      (fun firsta firstb ->
      tokenf ia1 ib1 >>= (fun ia1 ib1 ->
      tokenf ia2 ib2 >>= (fun ia2 ib2 ->
      tokenf ia4 ib4 >>= (fun ia4 ib4 ->
      tokenf ia5 ib5 >>= (fun ia5 ib5 ->
      eoption expression ea2opt eb2opt >>= (fun ea2opt eb2opt ->
      eoption expression ea3opt eb3opt >>= (fun ea3opt eb3opt ->
        return (
          A.ForHeader(ia1, ia2, firsta, ea2opt, ia4, ea3opt, ia5),
          F.ForHeader(st,((firstb,(eb2opt,[ib4]),(eb3opt,[])),[ib1;ib2;ib5]))
        ))))))))


  | A.SwitchHeader(ia1,ia2,ea,ia3), F.SwitchHeader (st, (eb,ii)) ->
      let (ib1, ib2, ib3) = tuple_of_list3 ii in
      tokenf ia1 ib1 >>= (fun ia1 ib1 ->
      tokenf ia2 ib2 >>= (fun ia2 ib2 ->
      tokenf ia3 ib3 >>= (fun ia3 ib3 ->
      expression ea eb >>= (fun ea eb ->
        return (
          A.SwitchHeader(ia1,ia2,ea,ia3),
          F.SwitchHeader (st, (eb,[ib1;ib2;ib3]))
        )))))

  | A.Break (ia1, ia2), F.Break (st, ((),ii),fromswitch) ->
      let (ib1, ib2) = tuple_of_list2 ii in
      tokenf ia1 ib1 >>= (fun ia1 ib1 ->
      tokenf ia2 ib2 >>= (fun ia2 ib2 ->
        return (
          A.Break (ia1, ia2),
          F.Break (st, ((),[ib1;ib2]), fromswitch)
        )))

  | A.Continue (ia1, ia2), F.Continue (st, ((),ii)) ->
      let (ib1, ib2) = tuple_of_list2 ii in
      tokenf ia1 ib1 >>= (fun ia1 ib1 ->
      tokenf ia2 ib2 >>= (fun ia2 ib2 ->
        return (
          A.Continue (ia1, ia2),
          F.Continue (st, ((),[ib1;ib2]))
        )))

  | A.Return (ia1, ia2), F.Return (st, ((),ii)) ->
      let (ib1, ib2) = tuple_of_list2 ii in
      tokenf ia1 ib1 >>= (fun ia1 ib1 ->
      tokenf ia2 ib2 >>= (fun ia2 ib2 ->
        return (
          A.Return (ia1, ia2),
          F.Return (st, ((),[ib1;ib2]))
        )))

  | A.ReturnExpr (ia1, ea, ia2), F.ReturnExpr (st, (eb, ii)) ->
      let (ib1, ib2) = tuple_of_list2 ii in
      tokenf ia1 ib1 >>= (fun ia1 ib1 ->
      tokenf ia2 ib2 >>= (fun ia2 ib2 ->
      expression ea eb >>= (fun ea eb ->
        return (
          A.ReturnExpr (ia1, ea, ia2),
          F.ReturnExpr (st, (eb, [ib1;ib2]))
        ))))


  | A.Include(incla,filea),
    F.Include {B.i_include = (fileb, ii);
               B.i_rel_pos = h_rel_pos;
               B.i_overall_rel_pos = o_rel_pos;
               B.i_is_in_ifdef = inifdef;
               B.i_content = copt;
              } ->
      assert (copt = None);

      let include_requirment =
        match mcodekind incla, mcodekind filea with
        | A.CONTEXT (_, A.BEFORE _), _ ->
            IncludeMcodeBefore
        | _, A.CONTEXT (_, A.AFTER _) ->
            IncludeMcodeAfter
        | _ ->
            IncludeNothing
      in

      let (inclb, iifileb) = tuple_of_list2 ii in
      if inc_file (term filea,include_requirment) (fileb,h_rel_pos,o_rel_pos)
      then
        tokenf incla inclb >>= (fun incla inclb ->
        tokenf filea iifileb >>= (fun filea iifileb ->
          return (
            A.Include(incla, filea),
            F.Include {B.i_include = (fileb, [inclb;iifileb]);
                       B.i_rel_pos = h_rel_pos;
		       B.i_overall_rel_pos = o_rel_pos;
                       B.i_is_in_ifdef = inifdef;
                       B.i_content = copt;
            }
          )))
      else fail

  | A.MetaInclude(incla,filea),
    F.Include {B.i_include = (fileb, ii);
               B.i_rel_pos = h_rel_pos;
               B.i_overall_rel_pos = o_rel_pos;
               B.i_is_in_ifdef = inifdef;
               B.i_content = copt;
              } ->
      let (inclb, iifileb) = tuple_of_list2 ii in
      tokenf incla inclb >>= (fun incla inclb ->
      expression filea
	  (Ast_c.mk_e (B.Constant(B.String(B.str_of_info(iifileb),B.IsChar)))
	     [iifileb]) >>=
	(fun filea _ (* no change allowed *) ->
	  return (
	    A.MetaInclude(incla,filea),
	    F.Include {B.i_include = (fileb, ii);
               B.i_rel_pos = h_rel_pos;
               B.i_overall_rel_pos = o_rel_pos;
               B.i_is_in_ifdef = inifdef;
               B.i_content = copt;
              }
	)))

  | A.Undef(undefa,ida), F.DefineHeader ((idb, ii), B.Undef) ->
      let (defineb, iidb, ieol) = tuple_of_list3 ii in
      ident DontKnow ida (idb, iidb) >>= (fun ida (idb, iidb) ->
      tokenf undefa defineb >>= (fun undefa defineb ->
        return (
	  A.Undef(undefa,ida),
          F.DefineHeader ((idb,[defineb;iidb;ieol]),B.Undef)
        ))
      )


  | A.DefineHeader(definea,ida,params), F.DefineHeader ((idb, ii), defkind) ->
      let (defineb, iidb, ieol) = tuple_of_list3 ii in
      ident DontKnow ida (idb, iidb) >>= (fun ida (idb, iidb) ->
      tokenf definea defineb >>= (fun definea defineb ->
      (match A.unwrap params, defkind with
      | A.NoParams, B.DefineVar ->
          return (
            A.NoParams +> A.rewrap params,
            B.DefineVar
          )
      | A.DParams(lpa,eas,rpa), (B.DefineFunc (ebs, ii)) ->
          let (lpb, rpb) = tuple_of_list2 ii in
          tokenf lpa lpb >>= (fun lpa lpb ->
          tokenf rpa rpb >>= (fun rpa rpb ->

          define_params (seqstyle eas) (A.unwrap eas) ebs >>=
            (fun easunwrap ebs ->
              let eas = A.rewrap eas easunwrap in
              return (
                A.DParams (lpa,eas,rpa) +> A.rewrap params,
                B.DefineFunc (ebs,[lpb;rpb])
                )
            )))
      | _ -> fail
      ) >>= (fun params defkind ->
        return (
          A.DefineHeader (definea, ida, params),
          F.DefineHeader ((idb,[defineb;iidb;ieol]),defkind)
        ))
      ))

  | A.Pragma(prga,ida,pragmainfoa),
    F.PragmaHeader ((idb, [(restb,[rest_iidb])]), ii) ->
      let (prgb, ieol) = tuple_of_list2 ii in
      ident_cpp DontKnow ida idb >>= (fun ida idb ->
      tokenf prga prgb >>= (fun prga prgb ->
      let wp x = A.rewrap pragmainfoa x  in
      (match A.unwrap pragmainfoa with
	A.PragmaString(sa) ->
	  tokenf sa rest_iidb >>= (fun sa rest_iidb ->
	  return(
	    A.PragmaString(sa) +> wp,
	    rest_iidb
	  ))
      | A.PragmaDots(mcode) ->
	  tokenf mcode rest_iidb >>= (fun mcode rest_iidb ->
	  return(
	    A.PragmaDots(mcode) +> wp,
	    rest_iidb
	  ))
      ) >>= (fun pragmainfoa rest_iidb ->
        return (
	  A.Pragma(prga,ida,pragmainfoa),
	  F.PragmaHeader ((idb, [(restb,[rest_iidb])]), [prgb;ieol])
        ))
      ))

  | A.Pragma(prga,ida,pragmainfoa),
    F.PragmaHeader ((idb, [(restb,rest_iib)]), ii) ->
      (* matches against multiline pragmas not supported *)
      fail

  | A.Default(def,colon), F.Default (st, ((),ii)) ->
      let (ib1, ib2) = tuple_of_list2 ii in
      tokenf def ib1 >>= (fun def ib1 ->
      tokenf colon ib2 >>= (fun colon ib2 ->
        return (
          A.Default(def,colon),
          F.Default (st, ((),[ib1;ib2]))
        )))

  | A.Case(case,ea,colon), F.Case (st, (eb,ii)) ->
      let (ib1, ib2) = tuple_of_list2 ii in
      tokenf case ib1 >>= (fun case ib1 ->
      expression ea eb >>= (fun ea eb ->
      tokenf colon ib2 >>= (fun colon ib2 ->
        return (
          A.Case(case,ea,colon),
          F.Case (st, (eb,[ib1;ib2]))
        ))))

  (* only occurs in the predicates generated by asttomember *)
  | A.DisjRuleElem eas, _ ->
      (eas +>
      List.fold_left (fun acc ea -> acc >|+|> (rule_elem_node ea node)) fail)
	>>= (fun ea eb -> return (A.unwrap ea,F.unwrap eb))

  | _, F.ExprStatement (_, (None, ii)) -> fail (* happen ? *)

  | A.Label(id,dd), F.Label (st, nameb, ((),ii)) ->
      let (ib2) = tuple_of_list1 ii in
      ident_cpp DontKnow id nameb >>= (fun ida nameb ->
      tokenf dd ib2 >>= (fun dd ib2 ->
	return (
	A.Label (ida,dd),
	F.Label (st,nameb, ((),[ib2]))
      )))

  | A.Goto(goto,id,sem),          F.Goto (st,nameb, ((),ii))       ->
      let (ib1,ib3) = tuple_of_list2 ii in
      tokenf goto ib1 >>= (fun goto ib1 ->
      ident_cpp DontKnow id nameb >>= (fun id nameb ->
      tokenf sem ib3 >>= (fun sem ib3 ->
	return(
	    A.Goto(goto,id,sem),
            F.Goto (st,nameb, ((),[ib1;ib3]))
          ))))

  | A.Exec(exec,lang,code,sem), F.Exec(st,(code2,ii)) ->
      let (exec2,lang2,sem2) = tuple_of_list3 ii in
      tokenf exec exec2 >>= (fun exec exec2 ->
      tokenf lang lang2 >>= (fun lang lang2 ->
      tokenf sem sem2 >>= (fun sem sem2 ->
      exec_code_list (A.unwrap code) (B.split_nocomma code2) >>=
	(fun code_unwrap code2_splitted ->
	  let code = A.rewrap code code_unwrap in
	  let code2 = Ast_c.unsplit_nocomma code2_splitted in
	  return(
	    A.Exec(exec,lang,code,sem),
	    F.Exec(st,(code2,[exec2;lang2;sem2])))))))

  | (A.AsRe(re,asre), b) ->
      rule_elem_node re node >>= (fun re _node ->
      rule_elem_node asre node >>= (fun asre _node ->
	return(
	  (A.AsRe(re,asre),b))))

  (* have not a counter part in coccinelle, for the moment *)
  (* todo?: print a warning at least ? *)
  | _, F.CaseRange _
  | _, F.Asm _
    -> fail2()
  | _, F.MacroTop _
    -> fail2()

  | _, (F.IfdefEndif _|F.IfdefElse _|F.IfdefHeader _)
    -> fail2 ()

  | _, F.IfdefIteHeader _
    -> fail2 ()

  | _,
    (F.MacroStmt (_, _)| F.DefineDoWhileZeroHeader _| F.EndNode|F.TopNode)
      -> fail
  | _,
    (F.Label (_, _, _)|F.Break (_, _, _)|F.Continue (_, _)|F.Default (_, _)|
    F.Case (_, _)|F.Include _|F.Goto _|F.ExprStatement _|F.Exec _|
    F.DefineType _|F.DefineExpr _|F.DefineInit _|F.DefineTodo|
    F.DefineHeader (_, _)|F.PragmaHeader (_, _)|
    F.ReturnExpr (_, _)|F.Return (_, _)|
    F.MacroIterHeader (_, _)|
    F.SwitchHeader (_, _)|F.ForHeader (_, _)|F.DoWhileTail _|F.DoHeader (_, _)|
    F.WhileHeader (_, _)|F.Else _|F.IfHeader (_, _)|
    F.SeqEnd (_, _)|F.SeqStart (_, _, _)|
    F.Decl _|F.FunHeader _)
      -> fail


  )) >>=
  (fun a b ->
  let rec loop = function
      [] -> return(a,b)
    | (nm,cstr)::rest ->
	X.check_re_constraints nm cstr (fun () -> loop rest) in
  loop (A.get_constraints re))

end