File: pretty_print_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 (1676 lines) | stat: -rw-r--r-- 52,363 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
(* Yoann Padioleau, Julia Lawall
 *
 * Copyright (C) 2010, University of Copenhagen DIKU and INRIA.
 * Copyright (C) 2006, 2007, 2008, 2009 Ecole des Mines de Nantes and DIKU
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License (GPL)
 * version 2 as published by the Free Software Foundation.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * file license.txt for more details.
 *)
open Common

open Ast_c

module F = Control_flow_c

(*****************************************************************************)
(* Wrappers *)
(*****************************************************************************)
let pr2, pr2_once = Common.mk_pr2_wrappers Flag_parsing_c.verbose_unparsing

(*****************************************************************************)
(* Types *)
(*****************************************************************************)

type type_with_ident = Ast_c.fullType -> (unit -> unit) -> unit

type 'a printer = 'a -> unit

type pretty_printers = {
  expression      : Ast_c.expression printer;
  assignOp        : Ast_c.assignOp printer;
  binaryOp        : Ast_c.binaryOp printer;
  arg_list        : (Ast_c.argument Ast_c.wrap2 list) printer;
  arg             : Ast_c.argument printer;
  statement       : Ast_c.statement printer;
  statement_seq_list : Ast_c.statement_sequencable list printer;
  decl            : Ast_c.declaration printer;
  field           : Ast_c.field printer;
  field_list      : Ast_c.field list printer;
  init            : Ast_c.initialiser printer;
  init_list       : (Ast_c.initialiser wrap2 list) printer;
  param           : Ast_c.parameterType printer;
  paramlist       : (Ast_c.parameterType Ast_c.wrap2 list) printer;
  dparamlist      : ((string Ast_c.wrap) Ast_c.wrap2 list) printer;
  ty              : Ast_c.fullType printer;
  type_with_ident : type_with_ident;
  base_type       : Ast_c.fullType printer;
  type_with_ident_rest : type_with_ident;
  toplevel        : Ast_c.toplevel printer;
  fragment        : Ast_c.string_fragment printer;
  fragment_list   : (Ast_c.string_fragment list) printer;
  format          : Ast_c.string_format printer;
  flow            : Control_flow_c.node printer;
  name            : Ast_c.name printer
}



(*****************************************************************************)

(* This module is used by unparse_c, but because unparse_c have also
 * the list of tokens, pretty_print_c could be useless in the future
 * (except that the ast_c have some fake tokens not present in the list
 * of tokens so it's still useful). But this module is also useful to
 * unparse C when you don't have the ordered list of tokens separately,
 * or tokens without position information, for instance when you want
 * to pretty print some piece of C that was generated, or some
 * abstract-lined piece of code, etc. *)

let mk_pretty_printers
    ~pr_elem ~pr_space
    ~pr_nl ~pr_indent ~pr_outdent ~pr_unindent
 =
  let start_block () = pr_nl(); pr_indent() in
  let end_block   () = pr_unindent(); pr_nl() in
(*
  let pr_nl_slash _ = (* multiline macro *)
    let slash = (Ast_c.fakeInfo() +> Ast_c.rewrap_str " \\") in
    pr_elem slash; pr_nl() in
*)
  let indent_if_needed st f =
    match Ast_c.unwrap_st st with
      Compound _ -> pr_space(); f()
    | _ ->
        (*no newline at the end - someone else will do that*)
	start_block(); f(); pr_unindent() in


  let pp_list printer l =
    l +> List.iter (fun (e, opt) ->
      assert (List.length opt <= 1); (* opt must be a comma? *)
      opt +> List.iter (function x -> pr_elem x; pr_space());
      printer e) in

  let pp_list2 printer l = (* no comma case *)
    l +> List.iter printer in

  let rec pp_expression = fun ((exp, typ), ii) ->
    (match exp, ii with
    | Ident (ident),         []     -> pp_name ident
    (* only a MultiString can have multiple ii *)
    | Constant (MultiString _), is     ->
	is +> Common.print_between pr_space pr_elem
    | Constant (c),         [i]     -> pr_elem i
    | StringConstant(s,os,w),  [i1;i2] ->
	pr_elem i1;
	s +> (List.iter pp_string_fragment);
	pr_elem i2
    | FunCall  (e, es),     [i1;i2] ->
        pp_expression e; pr_elem i1;
	pp_arg_list es;
        pr_elem i2;

    | CondExpr (e1, e2, e3),    [i1;i2]    ->
        pp_expression e1; pr_space(); pr_elem i1; pr_space();
	do_option (function x -> pp_expression x; pr_space()) e2; pr_elem i2;
        pr_space(); pp_expression e3
    | Sequence (e1, e2),          [i]  ->
        pp_expression e1; pr_elem i; pr_space(); pp_expression e2
    | Assignment (e1, op, e2),    []  ->
        pp_expression e1; pr_space(); pr_assignOp op; pr_space(); pp_expression e2

    | Postfix  (e, op),    [i] -> pp_expression e; pr_elem i;
    | Infix    (e, op),    [i] -> pr_elem i; pp_expression e;
    | Unary    (e, op),    [i] -> pr_elem i; pp_expression e
    | Binary   (e1, op, e2),    [] ->
        pp_expression e1; pr_space(); pr_binaryOp op; pr_space(); pp_expression e2

    | ArrayAccess    (e1, e2),   [i1;i2] ->
        pp_expression e1; pr_elem i1; pp_expression e2; pr_elem i2
    | RecordAccess   (e, name),     [i1] ->
        pp_expression e; pr_elem i1; pp_name name;
    | RecordPtAccess (e, name),     [i1] ->
        pp_expression e; pr_elem i1; pp_name name;

    | SizeOfExpr  (e),     [i] ->
	pr_elem i;
	(match Ast_c.unwrap e with
	  ParenExpr (e), _ -> ()
	| _ -> pr_space());
	pp_expression e
    | SizeOfType  (t),     [i1;i2;i3] ->
        pr_elem i1; pr_elem i2; pp_type t; pr_elem i3
    | Cast    (t, e),      [i1;i2] ->
        pr_elem i1; pp_type t; pr_elem i2; pp_expression e

    | StatementExpr (statxs, [ii1;ii2]),  [i1;i2] ->
        pr_elem i1;
        pr_elem ii1;
        statxs +> List.iter pp_statement_seq;
        pr_elem ii2;
        pr_elem i2;
    | Constructor (t, init), [lp;rp] ->
        pr_elem lp;
        pp_type t;
        pr_elem rp;
	pp_init init

    | ParenExpr (e), [i1;i2] -> pr_elem i1; pp_expression e; pr_elem i2;

    | New   (None, t),     [i1] -> pr_elem i1; pp_argument t
    | New   (Some ts, t),     [i1; i2; i3] ->
	pr_elem i1; pr_elem i2; pp_arg_list ts; pr_elem i3; pp_argument t
    | Delete(false,t), [i1] -> pr_elem i1; pr_space(); pp_expression t
    | Delete(true,t), [i1;i2;i3] ->
	pr_elem i1; pr_space(); pr_elem i2; pr_elem i3; pr_space();
	pp_expression t

    | Defined name, [i1] ->
        pr_elem i1; (* defined *) pr_space();
        pp_name name;
    | Defined name, [i1;i2;i3] ->
        pr_elem i1; (* defined *) pr_space();
        pr_elem i2; (* ( *)
        pp_name name;
        pr_elem i3; (* ) *)

    | (Ident (_) | Constant _ | StringConstant _ | FunCall (_,_)
    | CondExpr (_,_,_) | Sequence (_,_) | Assignment (_,_,_)
    | Postfix (_,_) | Infix (_,_) | Unary (_,_) | Binary (_,_,_)
    | ArrayAccess (_,_) | RecordAccess (_,_) | RecordPtAccess (_,_)
    | SizeOfExpr (_) | SizeOfType (_) | Cast (_,_)
    | StatementExpr (_) | Constructor _
    | ParenExpr (_) | New (_) | Delete (_,_)
    | Defined (_)),_ -> raise (Impossible 95)
    );

    if !Flag_parsing_c.pretty_print_type_info
    then begin
      pr_elem (Ast_c.fakeInfo() +> Ast_c.rewrap_str "/*");
      !typ +>
      (fun (ty,_test) -> ty +>
	Common.do_option
	  (fun (x,l) -> pp_type x;
	    let s = match l with
	      Ast_c.LocalVar _ -> ", local"
	    | _ -> "" in
	    pr_elem (Ast_c.fakeInfo() +> Ast_c.rewrap_str s)));
      pr_elem (Ast_c.fakeInfo() +> Ast_c.rewrap_str "*/");
    end

  and pr_assignOp (_,ii) =
    let i = Common.tuple_of_list1 ii in
    pr_elem i

  and pr_binaryOp (_,ii) =
    let i = Common.tuple_of_list1 ii in
    pr_elem i

  and pp_arg_list es = pp_list pp_argument es

  and pp_argument argument =
    let pp_action (ActMisc ii) = ii +> List.iter pr_elem in
    match argument with
    | Left e -> pp_expression e
    | Right weird ->
	(match weird with
	| ArgType param -> pp_param param
	| ArgAction action -> pp_action action)

(* ---------------------- *)
  and pp_name = function
    | RegularName (s, ii) ->
        let (i1) = Common.tuple_of_list1 ii in
        pr_elem i1
    | CppConcatenatedName xs ->
        xs +> List.iter (fun ((x,ii1), ii2) ->
          ii2 +> List.iter pr_elem;
          ii1 +> List.iter pr_elem;
        )
    | CppVariadicName (s, ii) ->
        ii +> List.iter pr_elem
    | CppIdentBuilder ((s,iis), xs) ->
        let (iis, iop, icp) = Common.tuple_of_list3 iis in
        pr_elem iis;
        pr_elem iop;
        xs +> List.iter (fun ((x,iix), iicomma) ->
          iicomma +> List.iter pr_elem;
          iix +> List.iter pr_elem;
        );
        pr_elem icp

and pp_string_fragment (e,ii) =
  match (e,ii) with
    ConstantFragment(str), ii ->
      let (i) = Common.tuple_of_list1 ii in
      pr_elem i
  | FormatFragment(fmt), ii ->
      let (i) = Common.tuple_of_list1 ii in
      pr_elem i;
      pp_string_format fmt

and pp_string_fragment_list sfl = pp_list2 pp_string_fragment sfl

and pp_string_format (e,ii) =
  match (e,ii) with
    ConstantFormat(str), ii ->
      let (i) = Common.tuple_of_list1 ii in
      pr_elem i

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

  and pp_statement_seq_list statxs =
    statxs +> Common.print_between pr_nl pp_statement_seq

  and pp_statement = fun st ->
    match Ast_c.get_st_and_ii st with
    | Labeled (Label (name, st)), ii ->
        let (i2) = Common.tuple_of_list1 ii in
	pr_outdent(); pp_name name; pr_elem i2; pr_nl(); pp_statement st
    | Labeled (Case  (e, st)), [i1;i2] ->
	pr_unindent();
        pr_elem i1; pr_space(); pp_expression e; pr_elem i2; pr_nl();
	pr_indent(); pp_statement st
    | Labeled (CaseRange  (e, e2, st)), [i1;i2;i3] ->
	pr_unindent();
        pr_elem i1; pr_space(); pp_expression e; pr_elem i2;
	pp_expression e2; pr_elem i3; pr_nl(); pr_indent();
        pp_statement st
    | Labeled (Default st), [i1;i2] ->
	pr_unindent(); pr_elem i1; pr_elem i2; pr_nl(); pr_indent();
	pp_statement st
    | Compound statxs, [i1;i2] ->
        pr_elem i1; start_block(); pp_statement_seq_list statxs;
        end_block(); pr_elem i2;

    | ExprStatement (None), [i] -> pr_elem i;
    | ExprStatement (None), [] -> ()
    | ExprStatement (Some e), [i] -> pp_expression e; pr_elem i
        (* the last ExprStatement of a for does not have a trailing
           ';' hence the [] for ii *)
    | ExprStatement (Some e), [] -> pp_expression e;
    | Selection  (If (e, st1, st2)), i1::i2::i3::is ->
        pp_ifthen e st1 i1 i2 i3;
        pp_else st2 is
    | Selection  (Ifdef_Ite (e, st1, st2)), i1::i2::i3::i4::is ->
        pr_elem i1;
        pp_ifthen e st1 i2 i3 i4;
        pp_else st2 is
    | Selection (Ifdef_Ite2 (e, st1, st2, st3)), i1::i2::i3::i4::is ->
        pr_elem i1;
        pp_ifthen e st1 i2 i3 i4;
        (* else #else S #endif *)
	(match is with
          [i4;i5;i6;iifakend] ->
            pr_elem i4; (* else *)
            pr_elem i5; (* #else *)
            indent_if_needed st2 (function _ -> pp_statement st2);
            pr_elem i6; (* #endif *)
            indent_if_needed st3 (function _ -> pp_statement st3);
            pr_elem iifakend
	| _ -> raise (Impossible 90))
    | Selection  (Switch (e, st)), [i1;i2;i3;iifakend] ->
        pr_elem i1; pr_space(); pr_elem i2; pp_expression e; pr_elem i3;
	indent_if_needed st (function _-> pp_statement st); pr_elem iifakend
    | Iteration  (While (e, st)), [i1;i2;i3;iifakend] ->
        pr_elem i1; pr_space(); pr_elem i2; pp_expression e; pr_elem i3;
	indent_if_needed st (function _-> pp_statement st); pr_elem iifakend
    | Iteration  (DoWhile (st, e)), [i1;i2;i3;i4;i5;iifakend] ->
        pr_elem i1;
	indent_if_needed st (function _ -> pp_statement st);
	pr_elem i2; pr_elem i3; pp_expression e;
        pr_elem i4; pr_elem i5;
        pr_elem iifakend


    | Iteration  (For (first,(e2opt,il2),(e3opt, il3),st)),
        [i1;i2;i3;iifakend] ->

          pr_elem i1; pr_space();
          pr_elem i2;
	  (match first with
	    ForExp (e1opt,il1) ->
              pp_statement (Ast_c.mk_st (ExprStatement e1opt) il1)
	  | ForDecl decl -> pp_decl decl);
	  pr_space();
          pp_statement (Ast_c.mk_st (ExprStatement e2opt) il2);
          assert (il3 = []);
	  pr_space();
          pp_statement (Ast_c.mk_st (ExprStatement e3opt) il3);
          pr_elem i3;
          indent_if_needed st (function _ -> pp_statement st);
          pr_elem iifakend

    | Iteration  (MacroIteration (s,es,st)), [i1;i2;i3;iifakend] ->
        pr_elem i1; pr_space();
        pr_elem i2;

        es +> List.iter (fun (e, opt) ->
          assert (List.length opt <= 1);
          opt +> List.iter pr_elem;
          pp_argument e;
        );

        pr_elem i3;
        indent_if_needed st (function _ -> pp_statement st);
        pr_elem iifakend

    | Jump (Goto name), ii               ->
        let (i1, i3) = Common.tuple_of_list2 ii in
        pr_elem i1; pr_space(); pp_name name; pr_elem i3;
    | Jump ((Continue|Break|Return)), [i1;i2] -> pr_elem i1; pr_elem i2;
    | Jump (ReturnExpr e), [i1;i2] ->
	pr_elem i1; pr_space(); pp_expression e; pr_elem i2
    | Jump (GotoComputed e), [i1;i2;i3] ->
        pr_elem i1; pr_elem i2; pp_expression e; pr_elem i3

    | Decl decl, [] -> pp_decl decl
    | Asm asmbody, ii ->
        (match ii with
        | [iasm;iopar;icpar;iptvirg] ->
            pr_elem iasm; pr_elem iopar;
            pp_asmbody asmbody;
            pr_elem icpar; pr_elem iptvirg
        | [iasm;ivolatile;iopar;icpar;iptvirg] ->
            pr_elem iasm; pr_elem ivolatile; pr_elem iopar;
            pp_asmbody asmbody;
            pr_elem icpar; pr_elem iptvirg
        | _ -> raise (Impossible 97)
        )

    | NestedFunc def, ii ->
        assert (ii = []);
        pp_def def
    | MacroStmt, ii ->
        ii +> List.iter pr_elem ;

    | Exec(code), [exec;lang;sem] ->
	pr_elem exec; pr_space(); pr_elem lang; pr_space();
	pp_list2 pp_exec_code code; pr_elem sem

    | IfdefStmt1 (ifdefs, xs), [] ->
	pp_statement_seq
	  (IfdefStmt2 (ifdefs,List.map (fun x -> [StmtElem x]) xs))

    | (Labeled (Case  (_,_))
    | Labeled (CaseRange  (_,_,_)) | Labeled (Default _)
    | Compound _ | ExprStatement _
    | Selection  (If (_, _, _)) | Selection  (Switch (_, _))
    | Selection (Ifdef_Ite _) | Selection (Ifdef_Ite2 _)
    | Iteration  (While (_, _)) | Iteration  (DoWhile (_, _))
    | Iteration  (For (_, (_,_), (_, _), _))
    | Iteration  (MacroIteration (_,_,_))
    | Jump ((Continue|Break|Return)) | Jump (ReturnExpr _)
    | Jump (GotoComputed _)
    | Decl _ | Exec _ | IfdefStmt1 _
	), _ -> raise (Impossible 98)

  and pp_statement_seq = function
    | StmtElem st -> pp_statement st
    | IfdefStmt ifdef -> pp_ifdef ifdef
    | CppDirectiveStmt cpp -> pp_directive cpp
    | IfdefStmt2 (ifdef, xxs) -> pp_ifdef_tree_sequence ifdef xxs

  and pp_ifthen e st1 i1 i2 i3 =
        (* if (<e>) *)
        pr_elem i1; pr_space(); pr_elem i2; pp_expression e; pr_elem i3;
        indent_if_needed st1 (function _ -> pp_statement st1);
  and pp_else st2 is =
        match (Ast_c.get_st_and_ii st2, is) with
          | ((ExprStatement None, []), [])  -> ()
          | ((ExprStatement None, []), [iifakend])  -> pr_elem iifakend
          | _st2, [i4;iifakend] ->
              pr_elem i4;
              indent_if_needed st2 (function _ -> pp_statement st2);
              pr_elem iifakend
          | _st2, [i4;i5;iifakend] -> (* else #endif S *)
              pr_elem i4;
              pr_elem i5;
              indent_if_needed st2 (function _ -> pp_statement st2);
              pr_elem iifakend
          | x -> raise (Impossible 96)


(* ifdef XXX elsif YYY elsif ZZZ endif *)
  and pp_ifdef_tree_sequence ifdef xxs =
    match ifdef with
    | if1::ifxs ->
        pp_ifdef if1;
        pp_ifdef_tree_sequence_aux  ifxs xxs
    | _ -> raise (Impossible 99)

(* XXX elsif YYY elsif ZZZ endif *)
  and pp_ifdef_tree_sequence_aux ifdefs xxs =
    Common.zip ifdefs xxs +> List.iter (fun (ifdef, xs) ->
      xs +> List.iter pp_statement_seq;
      pp_ifdef ifdef
    )





(* ---------------------- *)
  and pp_asmbody (string_list, colon_list) =
    string_list +> List.iter pr_elem ;
    colon_list +> List.iter (fun (Colon xs, ii) ->
      ii +> List.iter pr_elem;
      xs +> List.iter (fun (x,iicomma) ->
	assert ((List.length iicomma) <= 1);
	iicomma +> List.iter (function x -> pr_elem x; pr_space());
	(match x with
	| ColonMisc, ii -> ii +> List.iter pr_elem;
	| ColonExpr e, [istring;iopar;icpar] ->
            pr_elem istring;
            pr_elem iopar;
            pp_expression e;
            pr_elem icpar
	  (* the following case used to be just raise Impossible, but
	     the code __asm__ __volatile__ ("dcbz 0, %[input]"
                                ::[input]"r"(&coherence_data[i]));
	     in linux-2.6.34/drivers/video/fsl-diu-fb.c matches this case *)
	| (ColonExpr e), ii ->
	    (match List.rev ii with
	      icpar::iopar::istring::rest ->
		List.iter pr_elem (List.rev rest);
		pr_elem istring;
		pr_elem iopar;
		pp_expression e;
		pr_elem icpar
	    | _ -> raise (Impossible 100)))
        ))

  and pp_exec_code = function
    ExecEval name, [colon] -> pr_elem colon; pp_expression name
  | ExecToken, [tok] -> pr_elem tok
  | _ -> raise (Impossible 101)


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

(*
   pp_type_with_ident
   pp_base_type
   pp_type_with_ident_rest
   pp_type_left
   pp_type_right
   pp_type

   pp_decl
*)
  and (pp_type_with_ident:
	 (unit -> unit) option -> (storage * il) option ->
	   fullType -> attribute list -> attribute list ->
	     unit) =
    fun ident sto ft attrs endattrs ->
      pp_base_type ft  sto;
      (match (ident, Ast_c.unwrap_typeC ft) with
	(Some _,_) | (_,Pointer _) -> pr_space()
      |	_ -> ());
      pp_type_with_ident_rest ident ft attrs endattrs


  and (pp_base_type: fullType -> (storage * il) option -> unit) =
    fun (qu, (ty, iity)) sto ->
      let get_sto sto =
        match sto with
        | None -> [] | Some (s, iis) -> (*assert (List.length iis = 1);*) iis
      in
      let print_sto_qu (sto, (qu, iiqu)) =
        let all_ii = get_sto sto @ iiqu in
        all_ii
          +> List.sort Ast_c.compare_pos
          +> Common.print_between pr_space pr_elem

      in
      let print_sto_qu_ty (sto, (qu, iiqu), iity) =
        let all_ii = get_sto sto @ iiqu @ iity in
        let all_ii2 = all_ii +> List.sort Ast_c.compare_pos in

        if all_ii <> all_ii2
        then begin
            (* TODO in fact for pointer, the qualifier is after the type
             * cf -test strangeorder
             *)
          pr2 "STRANGEORDER";
          all_ii2 +> Common.print_between pr_space pr_elem
        end
        else all_ii2 +> Common.print_between pr_space pr_elem
      in

      match ty, iity with
      |	(NoType,_) -> ()
      | (Pointer t, [i])                           -> pp_base_type t sto
      | (ParenType t, _)                           -> pp_base_type t sto
      | (Array (eopt, t), [i1;i2])                 -> pp_base_type t sto
      | (FunctionType (returnt, paramst), [i1;i2]) ->
          pp_base_type returnt sto;


      | (StructUnion (su, sopt, fields),iis) ->
          print_sto_qu (sto, qu);

          (match sopt,iis with
          | Some s , [i1;i2;i3;i4] ->
              pr_elem i1; pr_space(); pr_elem i2; pr_space(); pr_elem i3;
          | None, [i1;i2;i3] ->
              pr_elem i1; pr_space(); pr_elem i2;
          | x -> raise (Impossible 101)
	  );

          fields +> List.iter (fun x -> pr_nl(); pr_indent(); pp_field x);
	  pr_nl();

          (match sopt,iis with
          | Some s , [i1;i2;i3;i4] -> pr_elem i4
          | None, [i1;i2;i3] ->       pr_elem i3;
          | x -> raise (Impossible 102)
	  );



      | (Enum  (sopt, enumt), iis) ->
          print_sto_qu (sto, qu);

          (match sopt, iis with
          | (Some s, ([i1;i2;i3;i4]|[i1;i2;i3;i4;_])) ->
              pr_elem i1; pr_elem i2; pr_elem i3;
          | (None, ([i1;i2;i3]|[i1;i2;i3;_])) ->
              pr_elem i1; pr_elem i2
          | x -> raise (Impossible 103)
	  );

          enumt +> List.iter (fun ((name, eopt), iicomma) ->
            assert (List.length iicomma <= 1);
            iicomma +> List.iter (function x -> pr_elem x; pr_space());
            pp_name name;
            eopt +> Common.do_option (fun (ieq, e) ->
              pr_elem ieq;
              pp_expression e;
	  ));

          (match sopt, iis with
          | (Some s, [i1;i2;i3;i4]) ->    pr_elem i4
          | (Some s, [i1;i2;i3;i4;i5]) ->
              pr_elem i5; pr_elem i4 (* trailing comma *)
          | (None, [i1;i2;i3]) ->         pr_elem i3
          | (None, [i1;i2;i3;i4]) ->
              pr_elem i4; pr_elem i3 (* trailing comma *)


          | x -> raise (Impossible 104)
	  );


      | (BaseType _, iis) ->
          print_sto_qu_ty (sto, qu, iis);

      | (StructUnionName (s, structunion), iis) ->
          assert (List.length iis = 2);
          print_sto_qu_ty (sto, qu, iis);

      | (EnumName  s, iis) ->
          assert (List.length iis = 2);
          print_sto_qu_ty (sto, qu, iis);

      | (Decimal(l,p), [dec;lp;cm;rp]) ->
	  (* hope that sto before qu is right... cf print_sto_qu_ty *)
	  let stoqulp = get_sto sto @ (snd qu) @ [dec] in
	  Common.print_between pr_space pr_elem stoqulp;
	  pr_elem lp; pp_expression l; pr_elem cm;
	  do_option pp_expression p; pr_elem rp

      | (TypeName (name,typ), noii) ->
          assert (noii = []);
          let (_s, iis) = get_s_and_info_of_name name in
          print_sto_qu_ty (sto, qu, [iis]);

          if !Flag_parsing_c.pretty_print_typedef_value
          then begin
            pr_elem (Ast_c.fakeInfo() +> Ast_c.rewrap_str "{*");
            typ +> Common.do_option (fun typ ->
                pp_type typ;
            );
            pr_elem (Ast_c.fakeInfo() +> Ast_c.rewrap_str "*}");
          end;

      | (FieldType (t, _, _), iis) ->
	  pp_base_type t sto

      | (TypeOfExpr (e), iis) ->
          print_sto_qu (sto, qu);
          (match iis with
          | [itypeof;iopar;icpar] ->
              pr_elem itypeof; pr_elem iopar;
              pp_expression e;
              pr_elem icpar;
          | _ -> raise (Impossible 105)
          )

      | (TypeOfType (t), iis) ->
          print_sto_qu (sto, qu);
          (match iis with
          | [itypeof;iopar;icpar] ->
              pr_elem itypeof; pr_elem iopar;
              pp_type t;
              pr_elem icpar;
          | _ -> raise (Impossible 106)
	  )

      | (Pointer _ | (*ParenType _ |*) Array _ | FunctionType _ | Decimal _
            (* | StructUnion _ | Enum _ | BaseType _ *)
            (* | StructUnionName _ | EnumName _ | TypeName _  *)
            (* | TypeOfExpr _ | TypeOfType _ *)
         ), _ -> raise (Impossible 107)

  and pp_field_list fields = fields +>  Common.print_between pr_nl pp_field
  and pp_field = function
      DeclarationField
	(FieldDeclList(onefield_multivars,[iiptvirg;ifakestart])) ->
	pr_elem ifakestart;
        (match onefield_multivars with
          x::xs ->
	    (* handling the first var. Special case, with the
               first var, we print the whole type *)

	    (match x with
	      (Simple (nameopt, typ)), iivirg ->
              (* first var cannot have a preceding ',' *)
		assert (List.length iivirg = 0);
		let identinfo =
                  match nameopt with
		  | None -> None
                  | Some name -> Some (function _ -> pp_name name)
                in
		pp_type_with_ident identinfo None typ Ast_c.noattr
		  Ast_c.noattr;

	    | (BitField (nameopt, typ, iidot, expr)), iivirg ->
                      (* first var cannot have a preceding ',' *)
		assert (List.length iivirg = 0);
		(match nameopt with
		| None ->
		    pp_type typ;
		| Some name ->
		    pp_type_with_ident (Some (function _ -> pp_name name))
		      None typ Ast_c.noattr Ast_c.noattr;
		    );
                pr_elem iidot;
		pp_expression expr

                  ); (* match x, first onefield_multivars *)

                      (* for other vars *)
	    xs +> List.iter (function
	      | (Simple (nameopt, typ)), iivirg ->
		  iivirg +> List.iter pr_elem;
		  let identinfo =
		    match nameopt with
		    | None -> None
		    | Some name -> Some (function _ -> pp_name name)
		  in
		  pp_type_with_ident_rest identinfo typ
		    Ast_c.noattr Ast_c.noattr

	      | (BitField (nameopt, typ, iidot, expr)), iivirg ->
		  iivirg +> List.iter pr_elem;
		  (match nameopt with
		  | Some name ->
		      pp_type_with_ident_rest
			(Some (function _ -> pp_name name))
			typ Ast_c.noattr Ast_c.noattr;
		      pr_elem iidot;
		      pp_expression expr
		  | None ->
		      (* was raise Impossible, but have no idea why because
			 nameless bit fields are accepted by the parser and
			 nothing seems to be done to give them names *)
		      pr_elem iidot;
		      pp_expression expr
			)); (* iter other vars *)

	| [] -> raise (Impossible 108)
	      ); (* onefield_multivars *)
	pr_elem iiptvirg

    | DeclarationField(FieldDeclList(onefield_multivars,_)) ->
	failwith "wrong number of tokens"

    | MacroDeclField ((s, es), ii)  ->
        let (iis, lp, rp, iiend, ifakestart) =
          Common.tuple_of_list5 ii in
                 (* iis::lp::rp::iiend::ifakestart::iisto
	            iisto +> List.iter pr_elem; (* static and const *)
                 *)
	pr_elem ifakestart;
	pr_elem iis;
	pr_elem lp;
	es +> List.iter (fun (e, opt) ->
          assert (List.length opt <= 1);
          opt +> List.iter pr_elem;
          pp_argument e;
	  );

	pr_elem rp;
	pr_elem iiend;



    | EmptyField iipttvirg_when_emptyfield ->
        pr_elem iipttvirg_when_emptyfield

    | CppDirectiveStruct cpp -> pp_directive cpp
    | IfdefStruct ifdef -> pp_ifdef ifdef

(* used because of DeclList, in    int i,*j[23];  we don't print anymore the
   int before *j *)
  and (pp_type_with_ident_rest: (unit -> unit) option ->
    fullType -> attribute list -> attribute list -> unit) =

    fun ident (((qu, iiqu), (ty, iity)) as fullt) attrs endattrs ->

      let print_ident ident = Common.do_option (fun f ->
        (* XXX attrs +> pp_attributes pr_elem pr_space; *)
        f();
	(if not(endattrs = []) then pr_space());
        endattrs +> pp_attributes pr_elem pr_space
	) ident
      in

      match ty, iity with
      (* the work is to do in base_type !! *)
      | (NoType, iis)                           -> ()
      | (BaseType _, iis)                       -> print_ident ident
      | (Enum  (sopt, enumt), iis)              -> print_ident ident
      | (StructUnion (_, sopt, fields),iis)     -> print_ident ident
      | (StructUnionName (s, structunion), iis) -> print_ident ident
      | (EnumName  s, iis)                      -> print_ident ident
      | (Decimal _, iis)                        -> print_ident ident
      | (TypeName (_name,_typ), iis)            -> print_ident ident
      | (FieldType (_typ,_,_), iis)             -> print_ident ident
      | (TypeOfExpr (e), iis)                   -> print_ident ident
      | (TypeOfType (e), iis)                   -> print_ident ident



      | (Pointer t, [i]) ->
          (* subtil:  void ( *done)(int i)   is a Pointer
             (FunctionType (return=void, params=int i) *)
          (*WRONG I THINK, use left & right function *)
          (* bug: pp_type_with_ident_rest None t;      print_ident ident *)
          pr_elem i;
          iiqu +> List.iter pr_elem; (* le const est forcement apres le '*' *)
          pp_type_with_ident_rest ident t attrs Ast_c.noattr;

      (* ugly special case ... todo? maybe sufficient in practice *)
      | (ParenType ttop, [i1;i2]) ->
          (match Ast_c.get_ty_and_ii ttop with
          | (_q1, (Pointer t2, [ipointer])) ->
              (match Ast_c.get_ty_and_ii t2 with
              | (q2, (FunctionType t, ii3)) ->

		  pp_type_left (q2, mk_tybis (FunctionType t) ii3);
		  pr_elem i1;
		  pr_elem ipointer;
		  print_ident ident;
		  pr_elem i2;
		  pp_type_right (q2, mk_tybis (FunctionType t) ii3);
              | _ ->
                  pr2 "PB PARENTYPE ZARB, I forget about the ()";
                  pp_type_with_ident_rest ident ttop attrs Ast_c.noattr;
              )
          (* another ugly special case *)
          | _q1, (Array (eopt,t2 ), [iarray1;iarray2]) ->
              (match Ast_c.get_ty_and_ii t2 with
              | (_q2, (Pointer t3, [ipointer])) ->
                  (match Ast_c.get_ty_and_ii t3 with
                  | (q3, (FunctionType t, iifunc)) ->

		      pp_type_left (q3, mk_tybis (FunctionType t) iifunc);
		      pr_elem i1;
		      pr_elem ipointer;
		      print_ident ident;
		      pr_elem iarray1;
		      do_option pp_expression eopt;
		      pr_elem iarray2;
		      pr_elem i2;
		      pp_type_right (q3, mk_tybis (FunctionType t) iifunc)
                  | _ ->
                      pr2 "PB PARENTYPE ZARB, I forget about the ()";
                      pp_type_with_ident_rest ident ttop attrs Ast_c.noattr;
                  )
              | _ ->
                  pr2 "PB PARENTYPE ZARB, I forget about the ()";
                  pp_type_with_ident_rest ident ttop attrs Ast_c.noattr;
              )
          | _t ->

              pr2 "PB PARENTYPE ZARB, I forget about the ()";
              pp_type_with_ident_rest ident ttop attrs Ast_c.noattr;
          )


      | (Array (eopt, t), [i1;i2]) ->
          pp_type_left fullt;

          iiqu +> List.iter pr_elem;
          print_ident ident;

          pp_type_right fullt;


      | (FunctionType (returnt, paramst), [i1;i2]) ->
          pp_type_left fullt;

          iiqu +> List.iter pr_elem;
          print_ident ident;

          pp_type_right fullt;


      | (FunctionType _ | Array _ | ParenType _ | Pointer _), _ ->
	  raise (Impossible 109)


  and (pp_type_left: fullType -> unit) =
    fun ((qu, iiqu), (ty, iity)) ->
      match ty, iity with
	(NoType,_) -> failwith "pp_type_left: unexpected NoType"
      | (Pointer t, [i]) ->
          pr_elem i;
          iiqu +> List.iter pr_elem; (* le const est forcement apres le '*' *)
          pp_type_left t

      | (Array (eopt, t), [i1;i2]) -> pp_type_left t
      | (FunctionType (returnt, paramst), [i1;i2]) -> pp_type_left returnt

      | (ParenType t, _) ->  failwith "parenType"


      | (BaseType _, iis)    -> ()
      | (Enum  (sopt, enumt), iis) -> ()
      | (StructUnion (_, sopt, fields),iis)  -> ()
      | (StructUnionName (s, structunion), iis) -> ()
      | (EnumName  s, iis) -> ()
      | (Decimal(l,p), iis) -> ()
      | (TypeName (_name,_typ), iis) -> ()
      | FieldType (_, _, _), _ -> ()
      | TypeOfType _, _ -> ()
      | TypeOfExpr _, _ -> ()

      | (FunctionType _ | Array _ | Pointer _), _ -> raise (Impossible 110)


  and pp_param param =
    let {p_namei = nameopt;
         p_register = (b,iib);
         p_type=t;} = param in

    iib +> List.iter pr_elem;

    match nameopt with
    | None ->
        pp_type t
    | Some name ->
	pp_type_with_ident (Some (function _ -> pp_name name))
	  None t Ast_c.noattr Ast_c.noattr




  and pp_type_right (((qu, iiqu), (ty, iity)) : fullType) =
    match ty, iity with
      (NoType,_) -> failwith "pp_type_right: unexpected NoType"
    | (Pointer t, [i]) ->  pp_type_right t

    | (Array (eopt, t), [i1;i2]) ->
        pr_elem i1;
        eopt +> do_option pp_expression;
        pr_elem i2;
        pp_type_right t

    | (ParenType t, _) ->  failwith "parenType"
    | (FunctionType (returnt, paramst), [i1;i2]) ->
        pr_elem i1;
        (match paramst with
        | (ts, (b, iib)) ->
            ts +> List.iter (fun (param,iicomma) ->
              assert ((List.length iicomma) <= 1);
              iicomma +> List.iter (function x -> pr_elem x; pr_space());

              pp_param param;
	    );
            iib +> List.iter pr_elem;
        );
        pr_elem i2

    | (BaseType _, iis)        -> ()
    | (Enum  (sopt, enumt), iis) -> ()
    | (StructUnion (_, sopt, fields),iis)-> ()
    | (StructUnionName (s, structunion), iis) -> ()
    | (EnumName  s, iis) -> ()
    | (Decimal(l,p), iis) -> ()
    | (TypeName (name,_typ), iis) -> ()
    | (FieldType (_, _, _), _) -> ()

    | TypeOfType _, _ -> ()
    | TypeOfExpr _, _ -> ()

    | (FunctionType _ | Array _ | Pointer _), _ -> raise (Impossible 111)

  and pp_type t =
    pp_type_with_ident None None t Ast_c.noattr Ast_c.noattr
  and pp_type_ident t i =
    pp_type_with_ident (Some i) None t Ast_c.noattr Ast_c.noattr
  and pp_type_ident_rest t i =
    pp_type_with_ident_rest (Some i) t Ast_c.noattr Ast_c.noattr
  and pp_base_type2 t =
    pp_base_type t None

(* ---------------------- *)
  and pp_decl = function
    | DeclList ((({v_namei = var;
                   v_type = returnType;
                   v_storage = storage;
                   v_attr = attrs;
                   v_endattr = endattrs;
                  },[])::xs),
	       iivirg::ifakestart::iisto) ->

	pr_elem ifakestart;

        (* old: iisto +> List.iter pr_elem; *)


        (* handling the first var. Special case, we print the whole type *)
	(match var with
	| Some (name, iniopt) ->
	    pp_type_with_ident
	      (Some (function _ -> pp_name name)) (Some (storage, iisto))
	      returnType attrs endattrs;
	    (match iniopt with
	      Ast_c.NoInit -> ()
	    | Ast_c.ValInit(iini,init) ->
		pr_space(); pr_elem iini; pr_space(); pp_init init
	    | Ast_c.ConstrInit((init,[lp;rp])) ->
		pr_elem lp; pp_arg_list init; pr_elem rp
	    | Ast_c.ConstrInit _ -> raise (Impossible 112))
	| None -> pp_type returnType
	);

      (* for other vars, we just call pp_type_with_ident_rest. *)
	xs +> List.iter (function
	| ({v_namei = Some (name, iniopt);
	    v_type = returnType;
	    v_storage = storage2;
	    v_attr = attrs;
	    v_endattr = endattrs;
	  }, iivirg) ->

	    assert (storage2 = storage);
	    iivirg +> List.iter pr_elem;
	    pp_type_with_ident_rest (Some (function _ -> pp_name name))
	      returnType attrs endattrs;
	    (match iniopt with
	      Ast_c.NoInit -> ()
	    | Ast_c.ValInit(iini,init) -> pr_elem iini; pp_init init
	    | Ast_c.ConstrInit((init,[lp;rp])) ->
		pr_elem lp; pp_arg_list init; pr_elem rp
	    | Ast_c.ConstrInit _ -> raise (Impossible 113));


	| x -> raise (Impossible 114)
	);

	pr_elem iivirg;

    | MacroDecl ((sto, s, es, true), iis::lp::rp::iiend::ifakestart::iisto) ->
	pr_elem ifakestart;
	iisto +> List.iter pr_elem; (* static and const *)
	pr_elem iis;
	pr_elem lp;
	es +> List.iter (fun (e, opt) ->
          assert (List.length opt <= 1);
          opt +> List.iter pr_elem;
          pp_argument e;
	);

	pr_elem rp;
	pr_elem iiend;

    | MacroDecl ((sto, s, es, false), iis::lp::rp::ifakestart::iisto) ->
	pr_elem ifakestart;
	iisto +> List.iter pr_elem; (* static and const *)
	pr_elem iis;
	pr_elem lp;
	es +> List.iter (fun (e, opt) ->
          assert (List.length opt <= 1);
          opt +> List.iter pr_elem;
          pp_argument e;
	);

	pr_elem rp;

    | MacroDeclInit
	((sto, s, es, ini), iis::lp::rp::eq::iiend::ifakestart::iisto) ->
	pr_elem ifakestart;
	iisto +> List.iter pr_elem; (* static and const *)
	pr_elem iis;
	pr_elem lp;
	es +> List.iter (fun (e, opt) ->
          assert (List.length opt <= 1);
          opt +> List.iter pr_elem;
          pp_argument e;
	);

	pr_elem rp;
	pr_elem eq;
	pp_init ini;
	pr_elem iiend;

    | (DeclList (_, _) | (MacroDecl _) | (MacroDeclInit _)) ->
	raise (Impossible 115)

(* ---------------------- *)
and pp_init (init, iinit) =
  match init, iinit with
      | InitExpr e, [] -> pp_expression e;
      | InitList xs, i1::i2::iicommaopt ->
          pr_elem i1; start_block();
          xs +> List.iter (fun (x, ii) ->
            assert (List.length ii <= 1);
            ii +> List.iter (function e -> pr_elem e; pr_nl());
            pp_init x
          );
          iicommaopt +> List.iter pr_elem;
	  end_block();
          pr_elem i2;

      | InitDesignators (xs, initialiser), [i1] -> (* : *)
          xs +> List.iter pp_designator;
          pr_elem i1;
          pp_init initialiser

    (* no use of '=' in the "Old" style *)
      | InitFieldOld (string, initialiser), [i1;i2] -> (* label:   in oldgcc *)
          pr_elem i1; pr_elem i2; pp_init initialiser
      | InitIndexOld (expression, initialiser), [i1;i2] -> (* [1] in oldgcc *)
          pr_elem i1; pp_expression expression; pr_elem i2;
          pp_init initialiser

      | (InitIndexOld _ | InitFieldOld _ | InitDesignators _
      | InitList _ | InitExpr _
	  ), _ -> raise (Impossible 116)

  and pp_init_list ini = pp_list pp_init ini

  and pp_designator = function
    | DesignatorField (s), [i1; i2] ->
	pr_elem i1; pr_elem i2;
    | DesignatorIndex (expression), [i1;i2] ->
	pr_elem i1; pp_expression expression; pr_elem i2;

    | DesignatorRange (e1, e2), [iocro;iellipsis;iccro] ->
	pr_elem iocro; pp_expression e1; pr_elem iellipsis;
	pp_expression e2; pr_elem iccro;

    | (DesignatorField _ | DesignatorIndex _ | DesignatorRange _
	), _ -> raise (Impossible 117)


(* ---------------------- *)
  and pp_attributes pr_elem pr_space attrs =
    attrs +> List.iter (fun (attr, ii) ->
      ii +> List.iter pr_elem;
    );

(* ---------------------- *)
  and pp_def_start defbis iifunc1 iifunc2 ifakestart isto =
    let {f_name = name;
          f_type = (returnt, (paramst, (b, iib)));
          f_storage = sto;
          f_body = statxs;
          f_attr = attrs;
	} = defbis in
    pr_elem ifakestart;

    pp_type_with_ident None (Some (sto, isto))
      returnt Ast_c.noattr Ast_c.noattr;

    pp_attributes pr_elem pr_space attrs;
    pr_space();
    pp_name name;

    pr_elem iifunc1;

        (* not anymore, cf tests/optional_name_parameter and
           macro_parameter_shortcut.c
           (match paramst with
           | [(((bool, None, t), ii_b_s), iicomma)] ->
               assert
		 (match t with
		 | qu, (BaseType Void, ii) -> true
		 | _ -> true
	       );
               assert (iicomma = []);
               assert (ii_b_s = []);
               pp_type_with_ident None None t

           | paramst ->
               paramst +> List.iter (fun (((bool, s, t), ii_b_s), iicomma) ->
	       iicomma +> List.iter pr_elem;

	       (match b, s, ii_b_s with
               | false, Some s, [i1] ->
		   pp_type_with_ident (Some (function _ -> pr_elem i1)) None t;
               | true, Some s, [i1;i2] ->
		   pr_elem i1;
		   pp_type_with_ident (Some (function _ -> pr_elem i2)) None t;

            (* in definition we have name for params, except when f(void) *)
               | _, None, _ -> raise Impossible
               | false, None, [] ->

               | _ -> raise Impossible
           )));

         (* normally ii represent the ",..." but it is also abused
            with the f(void) case *)
         (* assert (List.length iib <= 2);*)
           iib +> List.iter pr_elem;

        *)
    pp_param_list paramst;
    iib +> List.iter pr_elem;


    pr_elem iifunc2

  and pp_def def =
    let defbis, ii = def in
    match ii with
    | iifunc1::iifunc2::i1::i2::ifakestart::isto ->
	pp_def_start defbis iifunc1 iifunc2 ifakestart isto;
	pr_space();
        pr_elem i1;
	pp_statement_seq_list defbis.f_body;
        pr_elem i2
    | _ -> raise (Impossible 118)

  and pp_fun_header def =
    let defbis, ii = def in
    match ii with
    | iifunc1::iifunc2::ifakestart::isto ->
	pp_def_start defbis iifunc1 iifunc2 ifakestart isto
    | _ -> raise (Impossible 1180)

  and pp_param_list paramst = pp_list pp_param paramst

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

  and pp_ifdef ifdef =
    match ifdef with
    | IfdefDirective (ifdef, ii) ->
	List.iter pr_elem ii


  and pp_directive = function
    | Include {i_include = (s, ii);} ->
	let (i1,i2) = Common.tuple_of_list2 ii in
	pr_elem i1; pr_space(); pr_elem i2
    | Define ((s,ii), (defkind, defval)) ->
	let (idefine,iident,ieol) = Common.tuple_of_list3 ii in
	pr_elem idefine; pr_space();
	pr_elem iident; pr_space();

	let define_val = function
          | DefineExpr e -> pp_expression e
          | DefineStmt st -> pp_statement st
          | DefineDoWhileZero ((st,e), ii) ->
              (match ii with
              | [ido;iwhile;iopar;icpar] ->
                  pr_elem ido;
                  pp_statement st;
                  pr_elem iwhile; pr_elem iopar;
                  pp_expression e;
                  pr_elem icpar
              | _ -> raise (Impossible 119)
	      )
          | DefineFunction def -> pp_def def

          | DefineType ty -> pp_type ty
          | DefineText (s, ii) -> List.iter pr_elem ii
          | DefineEmpty -> ()
          | DefineInit ini -> pp_init ini
	  | DefineMulti ss ->
	      ss +> List.iter pp_statement
          | DefineTodo -> pr2 "DefineTodo"
	in
	(match defkind with
	| DefineVar | Undef -> ()
	| DefineFunc (params, ii) ->
            let (i1,i2) = tuple_of_list2 ii in
            pr_elem i1;
	    pp_define_param_list params;
            pr_elem i2;
	);
	define_val defval;
	pr_elem ieol

    | Pragma((name,rest), ii) ->
	let (ipragma,ieol) = Common.tuple_of_list2 ii in
	pr_elem ipragma; pr_space();
	pp_name name; pr_space();
	List.iter (List.iter pr_elem) (List.map snd rest); pr_elem ieol

    | OtherDirective (ii) ->
	List.iter pr_elem ii

  and pp_define_param_list dparams =
    pp_list (fun (s,iis) -> iis +> List.iter pr_elem) dparams in

  let rec pp_toplevel = function
    | Declaration decl -> pp_decl decl
    | Definition def -> pp_def def

    | CppTop directive -> pp_directive directive


    | MacroTop (s, es,   [i1;i2;i3;i4]) ->
	pr_elem i1;
	pr_elem i2;
	es +> List.iter (fun (e, opt) ->
          assert (List.length opt <= 1);
          opt +> List.iter pr_elem;
          pp_argument e;
	);
	pr_elem i3;
	pr_elem i4;


    | EmptyDef ii -> ii +> List.iter pr_elem
    | NotParsedCorrectly ii ->
	assert (List.length ii >= 1);
	ii +> List.iter pr_elem
    | FinalDef info -> pr_elem (Ast_c.rewrap_str "" info)

    | IfdefTop ifdefdir -> pp_ifdef ifdefdir

    | Namespace (tls, [i1; i2; i3; i4]) ->
	pr_elem i1; pr_elem i2; pr_elem i3;
	List.iter pp_toplevel tls;
	pr_elem i4;
    | (MacroTop _) | (Namespace _) -> raise (Impossible 120) in




  let pp_flow n =
    match F.unwrap n  with
    | F.FunHeader (({f_name =idb;
                      f_type = (rett, (paramst,(isvaargs,iidotsb)));
                      f_storage = stob;
                      f_body = body;
                      f_attr = attrs},ii) as def) ->

			assert (body = []);
			pp_fun_header def


    | F.Decl decl -> pp_decl decl

    | F.ExprStatement (st, (eopt, ii)) ->
	pp_statement (Ast_c.mk_st (ExprStatement eopt) ii)

    | F.IfHeader (_, (e,ii)) ->
	let (i1,i2,i3) = tuple_of_list3 ii in
	pr_elem i1; pr_space(); pr_elem i2; pp_expression e; pr_elem i3
    | F.SwitchHeader (_, (e,ii)) ->
	let (i1,i2,i3) = tuple_of_list3 ii in
	pr_elem i1; pr_space(); pr_elem i2; pp_expression e; pr_elem i3
    | F.WhileHeader (_, (e,ii)) ->
	let (i1,i2,i3) = tuple_of_list3 ii in
	pr_elem i1; pr_space(); pr_elem i2; pp_expression e; pr_elem i3
    | F.DoWhileTail (e,ii) ->
	let (i1,i2,i3,i4) = tuple_of_list4 ii in
	pr_elem i1; pr_elem i2; pp_expression e;
	pr_elem i3; pr_elem i4


    | F.ForHeader (_st, ((first, (e2opt,il2), (e3opt,il3)), ii)) ->
	let (i1,i2,i3) = tuple_of_list3 ii in
	pr_elem i1; pr_space();
	pr_elem i2;
	(match first with
	  ForExp (e1opt,il1) ->
	    pp_statement (Ast_c.mk_st (ExprStatement e1opt) il1)
	| ForDecl decl -> pp_decl decl);
	pr_space();
	pp_statement (Ast_c.mk_st (ExprStatement e2opt) il2);
	assert (il3 = []);
	pr_space();
	pp_statement (Ast_c.mk_st (ExprStatement e3opt) il3);
	pr_elem i3

    | F.MacroIterHeader (_s, ((s,es), ii)) ->
	let (i1,i2,i3) = tuple_of_list3 ii in
	pr_elem i1; pr_space();
	pr_elem i2;

	es +> List.iter (fun (e, opt) ->
	  assert (List.length opt <= 1);
	  opt +> List.iter pr_elem;
	  pp_argument e;
	  );

	pr_elem i3

    | F.ReturnExpr (_st, (e,ii)) ->
	let (i1,i2) = tuple_of_list2 ii in
	pr_elem i1; pr_space(); pp_expression e; pr_elem i2

    | F.Case (_st, (e,ii)) ->
	let (i1,i2) = tuple_of_list2 ii in
	pr_elem i1; pr_space(); pp_expression e; pr_elem i2

    | F.CaseRange (_st, ((e1, e2),ii)) ->
	let (i1,i2,i3) = tuple_of_list3 ii in
	pr_elem i1; pr_space(); pp_expression e1; pr_elem i2;
	pp_expression e2; pr_elem i3

    | F.CaseNode i -> ()

    | F.DefineExpr e  -> pp_expression e

    | F.DefineType ft  -> pp_type ft

    | F.DefineHeader ((s,ii), (defkind))  ->
        let (idefine,iident,ieol) = Common.tuple_of_list3 ii in
	pr_elem idefine; pr_space();
	pr_elem iident; pr_space();
	(match defkind with
	| DefineVar | Undef -> ()
	| DefineFunc (params, ii) ->
	    let (i1,i2) = tuple_of_list2 ii in
	    pr_elem i1;
	    pp_define_param_list params;
	    pr_elem i2)

    | F.DefineDoWhileZeroHeader (((),ii)) ->
	(* not sure what it is, ignore *)
        (* iif ii *)
	pr2 "DefineDoWhileZeroHeader"

    | F.DefineInit ini -> pp_init ini

    | F.PragmaHeader((name,rest), ii) ->
	let (ipragma,irest,ieol) = Common.tuple_of_list3 ii in
	pr_elem ipragma; pr_space();
	pp_name name; pr_space();
	pr_elem irest; pr_elem ieol

    | F.Include ({i_include = (s, ii);} as a) ->
	pp_directive (Include a)

    | F.MacroTop (s, args, ii) ->
	pp_toplevel(MacroTop (s, args, ii))

    | F.Break    (st,((),ii),fromswitch) ->
	let (i1,i2) = tuple_of_list2 ii in
	pr_elem i1; pr_elem i2
    | F.Continue (st,((),ii)) ->
	let (i1,i2) = tuple_of_list2 ii in
	pr_elem i1; pr_elem i2
    | F.Default  (st,((),ii)) ->
	let (i1,i2) = tuple_of_list2 ii in
	pr_elem i1; pr_elem i2
    | F.Return   (st,((),ii)) ->
	let (i1,i2) = tuple_of_list2 ii in
	pr_elem i1; pr_elem i2
    | F.Goto  (st, name, ((),ii)) ->
	let (i1, i3) = Common.tuple_of_list2 ii in
	pr_elem i1; pr_space(); pp_name name; pr_elem i3
    | F.Label (st, name, ((),ii)) ->
	let (i2) = Common.tuple_of_list1 ii in
	pp_name name; pr_elem i2
    | F.EndStatement iopt ->
        (* do_option infof iopt *)
	pr2 "EndStatement"
    | F.DoHeader (st, info) ->
	pr_elem info
    | F.Else info ->
	pr_elem info
    | F.SeqEnd (i, info) ->
	pr_elem info
    | F.SeqStart (st, i, info) ->
	pr_elem info

    | F.MacroStmt (st, ((),ii)) ->
	pp_statement (MacroStmt,ii)
    | F.Asm (st, (asmbody,ii)) ->
	pp_statement (Asm asmbody, ii)

    | F.Exec(st,(code,ii)) ->
	pp_statement (Exec code, ii)

    | F.IfdefHeader (info) ->
	pp_ifdef info
    | F.IfdefElse (info) ->
	pp_ifdef info
    | F.IfdefEndif (info) ->
	pp_ifdef info

    | F.IfdefIteHeader _ii ->
        pr2 "IfdefIteHeader"

    | F.DefineTodo ->
	pr2 "DefineTodo"


    | F.TopNode -> pr2 "TopNode"
    | F.EndNode -> pr2 "EndNode"
    | F.ErrorExit -> pr2 "ErrorExit"
    | F.Exit -> pr2 "Exit"
    | F.Enter -> pr2 "Enter"
    | F.LoopFallThroughNode -> pr2 "LoopFallThroughNode"
    | F.FallThroughNode -> pr2 "FallThroughNode"
    | F.AfterNode _ -> pr2 "AfterNode"
    | F.FalseNode -> pr2 "FalseNode"
    | F.TrueNode _ -> pr2 "TrueNode"
    | F.InLoopNode -> pr2 "InLoopNode"
    | F.Fake -> pr2 "Fake" in


  { expression = pp_expression;
    assignOp   = pr_assignOp;
    binaryOp   = pr_binaryOp;
    arg_list   = pp_arg_list;
    arg        = pp_argument;
    statement  = pp_statement;
    statement_seq_list = pp_statement_seq_list;
    decl       = pp_decl;
    field      = pp_field;
    field_list = pp_field_list;
    init       = pp_init;
    init_list  = pp_init_list;
    param      = pp_param;
    paramlist  = pp_param_list;
    dparamlist = pp_define_param_list;
    ty         = pp_type;
    type_with_ident = pp_type_ident;
    type_with_ident_rest = pp_type_ident_rest;
    base_type  = pp_base_type2;
    toplevel   = pp_toplevel;
    fragment   = pp_string_fragment;
    fragment_list = pp_string_fragment_list;
    format     = pp_string_format;
    flow       = pp_flow;
    name       = pp_name;
  }

(*****************************************************************************)

(* Here we do not use (mcode, env). It is a simple C pretty printer. *)
let pr_elem info =
  let s = Ast_c.str_of_info info in
  if !Flag_parsing_c.pretty_print_comment_info
  then
    (match get_comments_before info with
      [] -> ()
    | before ->
	pp "-->";
	before +> List.iter (fun (comment_like, pinfo) ->
          let s = pinfo.Common.str in
          pp s
	    );
	pp "<--");
  pp s;
  if !Flag_parsing_c.pretty_print_comment_info
  then
    (match get_comments_after info with
      [] -> ()
    | before ->
	pp "==>";
	before +> List.iter (fun (comment_like, pinfo) ->
          let s = pinfo.Common.str in
          pp s
	    );
	pp "<==")

let pr_space _ = Format.print_space()

let pr_nl _ = ()
let pr_indent _ = ()
let pr_outdent _ = ()
let pr_unindent _ = ()


let ppc =
  mk_pretty_printers
    ~pr_elem ~pr_space ~pr_nl ~pr_outdent ~pr_indent ~pr_unindent

let pp_expression_simple = ppc.expression
let pp_arg_list_simple   = ppc.arg_list
let pp_assignOp_simple   = ppc.assignOp
let pp_binaryOp_simple   = ppc.binaryOp
let pp_decl_simple       = ppc.decl
let pp_field_simple      = ppc.field
let pp_statement_simple  = ppc.statement
let pp_statement_seq_list_simple  = ppc.statement_seq_list
let pp_type_simple       = ppc.ty
let pp_init_simple       = ppc.init
let pp_toplevel_simple   = ppc.toplevel
let pp_string_fragment_simple = ppc.fragment
let pp_string_format_simple = ppc.format
let pp_flow_simple       = ppc.flow
let pp_name              = ppc.name


let pp_elem_sp ~pr_elem ~pr_space =
  mk_pretty_printers
    ~pr_elem ~pr_space
    ~pr_nl ~pr_outdent ~pr_indent ~pr_unindent

let pp_expression_gen ~pr_elem ~pr_space =
  (pp_elem_sp pr_elem pr_space).expression

let pp_assignOp_gen ~pr_elem ~pr_space =
  (pp_elem_sp pr_elem pr_space).assignOp

let pp_binaryOp_gen ~pr_elem ~pr_space =
  (pp_elem_sp pr_elem pr_space).binaryOp

let pp_arg_list_gen ~pr_elem ~pr_space =
  (pp_elem_sp pr_elem pr_space).arg_list

let pp_arg_gen ~pr_elem ~pr_space =
  (pp_elem_sp pr_elem pr_space).arg

let pp_statement_gen ~pr_elem ~pr_space =
  (pp_elem_sp pr_elem pr_space).statement

let pp_statement_seq_list_gen ~pr_elem ~pr_space =
  (pp_elem_sp pr_elem pr_space).statement_seq_list

let pp_decl_gen ~pr_elem ~pr_space =
  (pp_elem_sp pr_elem pr_space).decl

let pp_field_gen ~pr_elem ~pr_space =
  (pp_elem_sp pr_elem pr_space).field

let pp_field_list_gen ~pr_elem ~pr_space =
  (pp_elem_sp pr_elem pr_space).field_list

let pp_init_gen ~pr_elem ~pr_space =
  (pp_elem_sp pr_elem pr_space).init

let pp_init_list_gen ~pr_elem ~pr_space =
  (pp_elem_sp pr_elem pr_space).init_list

let pp_param_gen ~pr_elem ~pr_space =
  (pp_elem_sp pr_elem pr_space).param

let pp_param_list_gen ~pr_elem ~pr_space =
  (pp_elem_sp pr_elem pr_space).paramlist

let pp_define_param_list_gen ~pr_elem ~pr_space =
  (pp_elem_sp pr_elem pr_space).dparamlist

let pp_type_gen ~pr_elem ~pr_space =
  (pp_elem_sp pr_elem pr_space).ty

let pp_type_with_ident_gen pr_elem pr_space =
  (pp_elem_sp pr_elem pr_space).type_with_ident

let pp_string_fragment_list_gen ~pr_elem ~pr_space =
  (pp_elem_sp pr_elem pr_space).fragment_list

let pp_string_format_gen ~pr_elem ~pr_space =
  (pp_elem_sp pr_elem pr_space).format

let pp_program_gen ~pr_elem ~pr_space =
  (pp_elem_sp pr_elem pr_space).toplevel


let string_of_expression e =
  Common.format_to_string (fun () ->
    pp_expression_simple e
  )

let string_of_ifdef_guard = function
  | Gifdef s  -> "defined(" ^ s ^ ")"
  | Gifndef s -> "!defined(" ^ s ^ ")"
  | Gif_str s -> s
  | Gif e     -> string_of_expression e
  | Gnone     -> "0"

let string_of_toplevel top =
  Common.format_to_string (fun () ->
    pp_toplevel_simple top
  )

let string_of_fullType t =
  Common.format_to_string (fun () ->
    pp_type_simple t
  )

let string_of_name name =
  Common.format_to_string (fun () ->
    pp_name name
  )

let (debug_info_of_node:
       Control_flow_c.G.key -> Control_flow_c.cflow -> string) =
  fun nodei flow ->
    let node = Control_flow_c.KeyMap.find nodei flow#nodes in
    let s = Common.format_to_string (fun () ->
      pp_flow_simple node
    ) in
    let pos = Lib_parsing_c.min_pinfo_of_node node in
    (spf "%s(n%d)--> %s" (Common.string_of_parse_info_bis pos) nodei s)