-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathast_to_flow2.ml
1399 lines (1174 loc) · 47.8 KB
/
ast_to_flow2.ml
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
(*
* Copyright 2005-2009, Ecole des Mines de Nantes, University of Copenhagen
* Yoann Padioleau, Julia Lawall, Rene Rydhof Hansen, Henrik Stuart, Gilles Muller, Jesper Andersen
* This file is part of Coccinelle.
*
* Coccinelle is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, according to version 2 of the License.
*
* Coccinelle 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
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Coccinelle. If not, see <http://www.gnu.org/licenses/>.
*
* The authors reserve the right to distribute this or future versions of
* Coccinelle under other licenses.
*)
open Common
open Ast_c
open Control_flow_c2
open Ograph_extended
open Oassoc
open Oassocb
(*****************************************************************************)
(* todo?: compute target level with goto (but rare that different I think)
* ver1: just do init,
* ver2: compute depth of label (easy, intercept compound in the visitor)
*
* checktodo: after a switch, need check that all the st in the
* compound start with a case: ?
*
* checktodo: how ensure that when we call aux_statement recursivly, we
* pass it xi_lbl and not just auxinfo ? how enforce that ?
* in fact we must either pass a xi_lbl or a newxi
*
* todo: can have code (and so nodes) in many places, in the size of an
* array, in the init of initializer, but also in StatementExpr, ...
*
* todo?: steal code from CIL ? (but seems complicated ... again) *)
(*****************************************************************************)
(*****************************************************************************)
(* Types *)
(*****************************************************************************)
type error =
| DeadCode of Common.parse_info option
| CaseNoSwitch of Common.parse_info
| OnlyBreakInSwitch of Common.parse_info
| NoEnclosingLoop of Common.parse_info
| GotoCantFindLabel of string * Common.parse_info
| NoExit of Common.parse_info
| DuplicatedLabel of string
| NestedFunc
| ComputedGoto
| Define of Common.parse_info
exception Error of error
(*****************************************************************************)
(* Helpers *)
(*****************************************************************************)
let rec stmt_elems_of_sequencable xs =
xs +>
Common.map (fun x ->
match x with
| Ast_c.StmtElem e -> [e]
| Ast_c.CppDirectiveStmt _
| Ast_c.IfdefStmt _
->
[]
| Ast_c.IfdefStmt2 (_ifdef, xxs) ->
xxs +> List.map (fun xs ->
let xs' = stmt_elems_of_sequencable xs in
xs'
) +> List.flatten
) +> List.flatten
let add_node node labels nodestr g =
g#add_node (Control_flow_c2.mk_node node labels [] nodestr)
let add_bc_node node labels parent_labels nodestr g =
g#add_node (Control_flow_c2.mk_node node labels parent_labels nodestr)
let add_arc_opt (starti, nodei) g =
starti +> do_option (fun starti -> g#add_arc ((starti, nodei), Direct))
let lbl_0 = []
let pinfo_of_ii ii = Ast_c.get_opi (List.hd ii).Ast_c.pinfo
(*****************************************************************************)
(* Contextual information passed in aux_statement *)
(*****************************************************************************)
(* Sometimes have a continue/break and we must know where we must jump.
*
* ctl_brace: The node list in context_info record the number of '}' at the
* context point, for instance at the switch point. So that when deeper,
* we can compute the difference between the number of '}' from root to
* the context point to close the good number of '}' . For instance
* where there is a 'continue', we must close only until the for.
*)
type context_info =
| NoInfo
| LoopInfo of nodei * nodei (* start, end *) * node list * int list
| SwitchInfo of nodei * nodei (* start, end *) * node list * int list
(* for the Compound case I need to do different things depending if
* the compound is the compound of the function definition, the compound of
* a switch, so this type allows to specify this and enable to factorize
* code for the Compound
*)
and compound_caller =
FunctionDef | Statement | Switch of (nodei -> xinfo -> xinfo)
(* other information used internally in ast_to_flow and passed recursively *)
and xinfo = {
ctx: context_info; (* cf above *)
ctx_stack: context_info list;
(* are we under a ifthen[noelse]. Used for ErrorExit *)
under_ifthen: bool;
compound_caller: compound_caller;
(* does not change recursively. Some kind of globals. *)
labels_assoc: (string, nodei) oassoc;
exiti: nodei option;
errorexiti: nodei option;
(* ctl_braces: the nodei list is to handle current imbrication depth.
* It contains the must-close '}'.
* update: now it is instead a node list.
*)
braces: node list;
(* ctl: *)
labels: int list;
}
let initial_info = {
ctx = NoInfo;
ctx_stack = [];
under_ifthen = false;
compound_caller = Statement;
braces = [];
labels = [];
(* don't change when recurse *)
labels_assoc = new oassocb [];
exiti = None;
errorexiti = None;
}
(*****************************************************************************)
(* (Semi) Globals, Julia's style. *)
(*****************************************************************************)
(* global graph *)
let g = ref (new ograph_mutable)
let counter_for_labels = ref 0
let counter_for_braces = ref 0
(* For switch we use compteur too (or pass int ref) cos need know order of the
* case if then later want to go from CFG to (original) AST.
* update: obsolete now I think
*)
let counter_for_switch = ref 0
(*****************************************************************************)
(* helpers *)
(*****************************************************************************)
let id_of_name name =
match name with
| RegularName(s, il) -> s
| _ -> "NOT SUPPORTED"
(* alt: do via a todo list, so can do all in one pass (but more complex)
* todo: can also count the depth level and associate it to the node, for
* the ctl_braces:
*)
let compute_labels_and_create_them st =
(* map C label to index number in graph *)
let (h: (string, nodei) oassoc ref) = ref (new oassocb []) in
begin
st +> Visitor_c.vk_statement { Visitor_c.default_visitor_c with
Visitor_c.kstatement =
(fun (k, bigf) st ->
match st with
| Labeled (Ast_c.Label (s, _st)),ii ->
(* at this point I put a lbl_0, but later I will put the
* good labels. *)
let id = id_of_name s in
let newi = !g +> add_node (Label (st,(id,ii))) lbl_0 (id^":") in
begin
(* the C label already exists ? *)
if (!h#haskey id) then raise (Error (DuplicatedLabel id));
h := !h#add (id, newi);
(* not k _st !!! otherwise in lbl1: lbl2: i++; we miss lbl2 *)
k st;
end
| st -> k st
)
};
!h;
end
(* ctl_braces: *)
let insert_all_braces xs starti =
xs +> List.fold_left (fun acc node ->
(* Have to build a new node (clone), cos cant share it.
* update: This is now done by the caller. The clones are in xs.
*)
let newi = !g#add_node node in
!g#add_arc ((acc, newi), Direct);
newi
) starti
(*****************************************************************************)
(* Statement *)
(*****************************************************************************)
(* Take in a (optional) start node, return an (optional) end node.
*
* history:
*
* ver1: old code was returning an nodei, but goto has no end, so
* aux_statement should return nodei option.
*
* ver2: old code was taking a nodei, but should also take nodei
* option.
*
* ver3: deadCode detection. What is dead code ? When there is no
* starti to start from ? So make starti an option too ? Si on arrive
* sur un label: au moment d'un deadCode, on peut verifier les
* predecesseurs de ce label, auquel cas si y'en a, ca veut dire
* qu'en fait c'est pas du deadCode et que donc on peut se permettre
* de partir d'un starti à None. Mais si on a xx; goto far:; near:
* yy; zz; far: goto near:. Bon ca doit etre un cas tres tres rare,
* mais a cause de notre parcours, on va rejeter ce programme car au
* moment d'arriver sur near: on n'a pas encore de predecesseurs pour
* ce label. De meme, meme le cas simple ou la derniere instruction
* c'est un return, alors ca va generer un DeadCode :(
*
* So make a first pass where dont launch exn at all. Create nodes,
* if starti is None then dont add arc. Then make a second pass that
* just checks that all nodes (except enter) have predecessors.
* So make starti an option too. So type is now
*
* nodei option -> statement -> nodei option.
*
* todo?: if the pb is at a fake node, then try first successos that
* is non fake.
*
* ver4: because of special needs of coccinelle, need pass more info, cf
* type additionnal_info defined above.
*
* - to complete (break, continue (and enclosing loop), switch (and
* associated case, casedefault)) we need to pass additionnal info.
* The start/exit when enter in a loop, to know the current 'for'.
*
* - to handle the braces, need again pass additionnal info.
*
* - need pass the labels.
*
* convention: xi for the auxinfo passed recursively
*
*)
let rec (aux_statement: (nodei option * xinfo) -> statement -> nodei option) =
fun (starti, xi) stmt ->
if not !Flag_parsing_c.label_strategy_2
then incr counter_for_labels;
let lbl =
if !Flag_parsing_c.label_strategy_2
then xi.labels
else xi.labels @ [!counter_for_labels]
in
(* Normally the new auxinfo to pass recursively to the next aux_statement.
* But in some cases we add additionnal stuff in which case we don't use
* this 'xi_lbl' but a 'newxi' specially built.
*)
let xi_lbl =
if !Flag_parsing_c.label_strategy_2
then { xi with
compound_caller = Statement;
}
else { xi with
labels = xi.labels @ [ !counter_for_labels ];
compound_caller = Statement;
}
in
(* ------------------------- *)
match stmt with
(* coupling: the Switch case copy paste parts of the Compound case *)
| Ast_c.Compound statxs, ii ->
(* flow_to_ast: *)
let (i1, i2) = tuple_of_list2 ii in
(* ctl_braces: *)
incr counter_for_braces;
let brace = !counter_for_braces in
let s1 = "{" ^ i_to_s brace in
let s2 = "}" ^ i_to_s brace in
let lbl = match xi.compound_caller with
| FunctionDef -> xi.labels (* share label with function header *)
| Statement -> xi.labels @ [!counter_for_labels]
| Switch _ -> xi.labels
in
let newi = !g +> add_node (SeqStart (stmt, brace, i1)) lbl s1 in
let endnode = mk_node (SeqEnd (brace, i2)) lbl [] s2 in
let endnode_dup = mk_fake_node (SeqEnd (brace, i2)) lbl [] s2 in
(*
let _endnode_dup =
mk_node (SeqEnd (brace, Ast_c.fakeInfo())) lbl [] s2 in
*)
let newxi = { xi_lbl with braces = endnode_dup:: xi_lbl.braces } in
let newxi = match xi.compound_caller with
| Switch todo_in_compound ->
(* note that side effect in todo_in_compound *)
todo_in_compound newi newxi
| FunctionDef | Statement -> newxi
in
!g +> add_arc_opt (starti, newi);
let starti = Some newi in
aux_statement_list starti (xi, newxi) statxs
(* braces: *)
+> Common.fmap (fun starti ->
(* subtil: not always return a Some.
* Note that if starti is None, alors forcement ca veut dire
* qu'il y'a eu un return (ou goto), et donc forcement les
* braces auront au moins ete crée une fois, et donc flow_to_ast
* marchera.
* Sauf si le goto revient en arriere ? mais dans ce cas
* ca veut dire que le programme boucle. Pour qu'il boucle pas
* il faut forcement au moins un return.
*)
let endi = !g#add_node endnode in
!g#add_arc ((starti, endi), Direct);
endi
)
(* ------------------------- *)
| Labeled (Ast_c.Label (id, st)), ii ->
let s = id_of_name id in
let ilabel = xi.labels_assoc#find s in
let node = mk_node (unwrap (!g#nodes#find ilabel)) lbl [] (s ^ ":") in
!g#replace_node (ilabel, node);
!g +> add_arc_opt (starti, ilabel);
aux_statement (Some ilabel, xi_lbl) st
| Jump (Ast_c.Goto id), ii ->
let s = id_of_name id in
(* special_cfg_ast: *)
let newi = !g +> add_node (Goto (stmt, (s,ii))) lbl ("goto " ^ s ^ ":") in
!g +> add_arc_opt (starti, newi);
let ilabel =
try xi.labels_assoc#find s
with Not_found ->
(* jump vers ErrorExit a la place ?
* pourquoi tant de "cant jump" ? pas detecté par gcc ?
*)
raise (Error (GotoCantFindLabel (s, pinfo_of_ii ii)))
in
(* !g +> add_arc_opt (starti, ilabel);
* todo: special_case: suppose that always goto to toplevel of function,
* hence the Common.init
* todo?: can perhaps report when a goto is not a classic error_goto ?
* that is when it does not jump to the toplevel of the function.
*)
let newi = insert_all_braces (Common.list_init xi.braces) newi in
!g#add_arc ((newi, ilabel), Direct);
None
| Jump (Ast_c.GotoComputed e), ii ->
raise (Error (ComputedGoto))
(* ------------------------- *)
| Ast_c.ExprStatement opte, ii ->
(* flow_to_ast: old: when opte = None, then do not add in CFG. *)
let s =
match opte with
| None -> "empty;"
| Some e ->
let ((unwrap_e, typ), ii) = e in
(match unwrap_e with
| FunCall (((Ident f, _typ), _ii), _args) ->
(id_of_name f) ^ "(...)"
| Assignment (((Ident var, _typ), _ii), SimpleAssign, e) ->
(id_of_name var) ^ " = ... ;"
| Assignment
(((RecordAccess (((Ident var, _typ), _ii), field), _typ2),
_ii2),
SimpleAssign,
e) ->
(id_of_name var) ^ "." ^ (id_of_name field) ^ " = ... ;"
| _ -> "statement"
)
in
let newi = !g +> add_node (ExprStatement (stmt, (opte, ii))) lbl s in
!g +> add_arc_opt (starti, newi);
Some newi
(* ------------------------- *)
| Selection (Ast_c.If (e, st1, (Ast_c.ExprStatement (None), []))), ii ->
(* sometome can have ExprStatement None but it is a if-then-else,
* because something like if() xx else ;
* so must force to have [] in the ii associated with ExprStatement
*)
let (i1,i2,i3, iifakeend) = tuple_of_list4 ii in
let ii = [i1;i2;i3] in
(* starti -> newi ---> newfakethen -> ... -> finalthen --> lasti
* | |
* |-> newfakeelse -> ... -> finalelse -|
* update: there is now also a link directly to lasti.
*
* because of CTL, now do different things if we are in a ifthen or
* ifthenelse.
*)
let newi = !g +> add_node (IfHeader (stmt, (e, ii))) lbl ("if") in
!g +> add_arc_opt (starti, newi);
let newfakethen = !g +> add_node TrueNode lbl "[then]" in
let newfakeelse = !g +> add_node FallThroughNode lbl "[fallthrough]" in
let afteri = !g +> add_node AfterNode lbl "[after]" in
let lasti = !g +> add_node (EndStatement (Some iifakeend)) lbl "[endif]"
in
(* for ErrorExit heuristic *)
let newxi = { xi_lbl with under_ifthen = true; } in
!g#add_arc ((newi, newfakethen), Direct);
!g#add_arc ((newi, newfakeelse), Direct);
!g#add_arc ((newi, afteri), Direct);
!g#add_arc ((afteri, lasti), Direct);
!g#add_arc ((newfakeelse, lasti), Direct);
let finalthen = aux_statement (Some newfakethen, newxi) st1 in
!g +> add_arc_opt (finalthen, lasti);
Some lasti
| Selection (Ast_c.If (e, st1, st2)), ii ->
(* starti -> newi ---> newfakethen -> ... -> finalthen --> lasti
* | |
* |-> newfakeelse -> ... -> finalelse -|
* update: there is now also a link directly to lasti.
*)
let (iiheader, iielse, iifakeend) =
match ii with
| [i1;i2;i3;i4;i5] -> [i1;i2;i3], i4, i5
| _ -> raise (Impossible 42)
in
let newi = !g +> add_node (IfHeader (stmt, (e, iiheader))) lbl "if" in
!g +> add_arc_opt (starti, newi);
let newfakethen = !g +> add_node TrueNode lbl "[then]" in
let newfakeelse = !g +> add_node FalseNode lbl "[else]" in
let elsenode = !g +> add_node (Else iielse) lbl "else" in
!g#add_arc ((newi, newfakethen), Direct);
!g#add_arc ((newi, newfakeelse), Direct);
!g#add_arc ((newfakeelse, elsenode), Direct);
let finalthen = aux_statement (Some newfakethen, xi_lbl) st1 in
let finalelse = aux_statement (Some elsenode, xi_lbl) st2 in
(match finalthen, finalelse with
| (None, None) -> None
| _ ->
let lasti =
!g +> add_node (EndStatement(Some iifakeend)) lbl "[endif]" in
let afteri =
!g +> add_node AfterNode lbl "[after]" in
!g#add_arc ((newi, afteri), Direct);
!g#add_arc ((afteri, lasti), Direct);
begin
!g +> add_arc_opt (finalthen, lasti);
!g +> add_arc_opt (finalelse, lasti);
Some lasti
end)
(* ------------------------- *)
| Selection (Ast_c.Switch (e, st)), ii ->
let (i1,i2,i3, iifakeend) = tuple_of_list4 ii in
let ii = [i1;i2;i3] in
(* The newswitchi is for the labels to know where to attach.
* The newendswitch (endi) is for the 'break'. *)
let newswitchi=
!g+> add_node (SwitchHeader(stmt,(e,ii))) lbl "switch" in
let newendswitch =
!g +> add_node (EndStatement (Some iifakeend)) lbl "[endswitch]" in
!g +> add_arc_opt (starti, newswitchi);
(* call compound case. Need special info to pass to compound case
* because we need to build a context_info that need some of the
* information build inside the compound case: the nodei of {
*)
let finalthen =
match st with
| Ast_c.Compound statxs, ii ->
let statxs = stmt_elems_of_sequencable statxs in
(* todo? we should not allow to match a stmt that corresponds
* to a compound of a switch, so really SeqStart (stmt, ...)
* here ? so maybe should change the SeqStart labeling too.
* So need pass a todo_in_compound2 function.
*)
let todo_in_compound newi newxi =
let newxi' = { newxi with
ctx = SwitchInfo (newi(*!!*), newendswitch, xi.braces, lbl);
ctx_stack = newxi.ctx::newxi.ctx_stack
}
in
!g#add_arc ((newswitchi, newi), Direct);
(* new: if have not a default case, then must add an edge
* between start to end.
* todo? except if the case[range] coverthe whole spectrum
*)
if not (statxs +> List.exists (function
| (Labeled (Ast_c.Default _), _) -> true
| _ -> false
))
then begin
(* when there is no default, then a valid path is
* from the switchheader to the end. In between we
* add a Fallthrough.
*)
let newafter = !g+>add_node FallThroughNode lbl "[switchfall]"
in
!g#add_arc ((newafter, newendswitch), Direct);
!g#add_arc ((newswitchi, newafter), Direct);
(* old:
!g#add_arc ((newswitchi, newendswitch), Direct) +> adjust_g;
*)
end;
newxi'
in
let newxi = { xi with compound_caller =
Switch todo_in_compound
}
in
aux_statement (None (* no starti *), newxi) st
| x -> raise (Impossible 42)
in
!g +> add_arc_opt (finalthen, newendswitch);
(* what if has only returns inside. We must try to see if the
* newendswitch has been used via a 'break;' or because no
* 'default:')
*)
let res =
(match finalthen with
| Some finalthen ->
let afteri = !g +> add_node AfterNode lbl "[after]" in
!g#add_arc ((newswitchi, afteri), Direct);
!g#add_arc ((afteri, newendswitch), Direct);
!g#add_arc ((finalthen, newendswitch), Direct);
Some newendswitch
| None ->
if (!g#predecessors newendswitch)#null
then begin
assert ((!g#successors newendswitch)#null);
!g#del_node newendswitch;
None
end
else begin
let afteri = !g +> add_node AfterNode lbl "[after]" in
!g#add_arc ((newswitchi, afteri), Direct);
!g#add_arc ((afteri, newendswitch), Direct);
Some newendswitch
end
)
in
res
| Labeled (Ast_c.Case (_, _)), ii
| Labeled (Ast_c.CaseRange (_, _, _)), ii ->
incr counter_for_switch;
let switchrank = !counter_for_switch in
let node, st =
match stmt with
| Labeled (Ast_c.Case (e, st)), ii ->
(Case (stmt, (e, ii))), st
| Labeled (Ast_c.CaseRange (e, e2, st)), ii ->
(CaseRange (stmt, ((e, e2), ii))), st
| _ -> raise (Impossible 42)
in
let newi = !g +> add_node node lbl "case:" in
(match Common.optionise (fun () ->
(* old: xi.ctx *)
(xi.ctx::xi.ctx_stack) +> Common.find_some (function
| SwitchInfo (a, b, c, _) -> Some (a, b, c)
| _ -> None
))
with
| Some (startbrace, switchendi, _braces) ->
(* no need to attach to previous for the first case, cos would be
* redundant. *)
starti +> do_option (fun starti ->
if starti <> startbrace
then !g +> add_arc_opt (Some starti, newi);
);
let s = ("[casenode] " ^ i_to_s switchrank) in
let newcasenodei = !g +> add_node (CaseNode switchrank) lbl s in
!g#add_arc ((startbrace, newcasenodei), Direct);
!g#add_arc ((newcasenodei, newi), Direct);
| None -> raise (Error (CaseNoSwitch (pinfo_of_ii ii)))
);
aux_statement (Some newi, xi_lbl) st
| Labeled (Ast_c.Default st), ii ->
incr counter_for_switch;
let switchrank = !counter_for_switch in
let newi = !g +> add_node (Default(stmt, ((),ii))) lbl "case default:" in
!g +> add_arc_opt (starti, newi);
(match xi.ctx with
| SwitchInfo (startbrace, switchendi, _braces, _parent_lbl) ->
let s = ("[casenode] " ^ i_to_s switchrank) in
let newcasenodei = !g +> add_node (CaseNode switchrank) lbl s in
!g#add_arc ((startbrace, newcasenodei), Direct);
!g#add_arc ((newcasenodei, newi), Direct);
| _ -> raise (Error (CaseNoSwitch (pinfo_of_ii ii)))
);
aux_statement (Some newi, xi_lbl) st
(* ------------------------- *)
| Iteration (Ast_c.While (e, st)), ii ->
(* starti -> newi ---> newfakethen -> ... -> finalthen -
* |---|-----------------------------------|
* |-> newfakelse
*)
let (i1,i2,i3, iifakeend) = tuple_of_list4 ii in
let ii = [i1;i2;i3] in
let newi = !g +> add_node (WhileHeader (stmt, (e,ii))) lbl "while" in
!g +> add_arc_opt (starti, newi);
let newfakethen = !g +> add_node InLoopNode lbl "[whiletrue]" in
(* let newfakeelse = !g +> add_node FalseNode lbl "[endwhile]" in *)
let newafter = !g +> add_node FallThroughNode lbl "[whilefall]" in
let newfakeelse =
!g +> add_node (EndStatement (Some iifakeend)) lbl "[endwhile]" in
let newxi = { xi_lbl with
ctx = LoopInfo (newi, newfakeelse, xi_lbl.braces, lbl);
ctx_stack = xi_lbl.ctx::xi_lbl.ctx_stack
}
in
!g#add_arc ((newi, newfakethen), Direct);
!g#add_arc ((newafter, newfakeelse), Direct);
!g#add_arc ((newi, newafter), Direct);
let finalthen = aux_statement (Some newfakethen, newxi) st in
!g +> add_arc_opt (finalthen, newi);
Some newfakeelse
(* This time, may return None, for instance if goto in body of dowhile
* (whereas While cant return None). But if return None, certainly
* some deadcode.
*)
| Iteration (Ast_c.DoWhile (st, e)), ii ->
(* starti -> doi ---> ... ---> finalthen (opt) ---> whiletaili
* |--------- newfakethen ---------------| |---> newfakelse
*)
let is_zero =
match Ast_c.unwrap_expr e with
| Constant (Int ("0", intType)) -> true
| _ -> false
in
let (iido, iiwhiletail, iifakeend) =
match ii with
| [i1;i2;i3;i4;i5;i6] -> i1, [i2;i3;i4;i5], i6
| _ -> raise (Impossible 42)
in
let doi = !g +> add_node (DoHeader (stmt, e, iido)) lbl "do" in
!g +> add_arc_opt (starti, doi);
let taili = !g +> add_node (DoWhileTail (e, iiwhiletail)) lbl "whiletail"
in
(*let newfakeelse = !g +> add_node FalseNode lbl "[enddowhile]" in *)
let newafter = !g +> add_node FallThroughNode lbl "[dowhilefall]" in
let newfakeelse =
!g +> add_node (EndStatement (Some iifakeend)) lbl "[enddowhile]" in
let newxi = { xi_lbl with
ctx = LoopInfo (taili, newfakeelse, xi_lbl.braces, lbl);
ctx_stack = xi_lbl.ctx::xi_lbl.ctx_stack
}
in
if not is_zero
then begin
let newfakethen = !g +> add_node InLoopNode lbl "[dowhiletrue]" in
!g#add_arc ((taili, newfakethen), Direct);
!g#add_arc ((newfakethen, doi), Direct);
end;
!g#add_arc ((newafter, newfakeelse), Direct);
!g#add_arc ((taili, newafter), Direct);
let finalthen = aux_statement (Some doi, newxi) st in
(match finalthen with
| None ->
if (!g#predecessors taili)#null
then raise (Error (DeadCode (Some (pinfo_of_ii ii))))
else Some newfakeelse
| Some finali ->
!g#add_arc ((finali, taili), Direct);
Some newfakeelse
)
| Iteration (Ast_c.For (ForExp e1opt, e2opt, e3opt, st)), ii ->
let (i1,i2,i3, iifakeend) = tuple_of_list4 ii in
let ii = [i1;i2;i3] in
let newi =
!g+>add_node(ForHeader(stmt,((e1opt,e2opt,e3opt),ii))) lbl "for" in
!g +> add_arc_opt (starti, newi);
let newfakethen = !g +> add_node InLoopNode lbl "[fortrue]" in
(*let newfakeelse = !g +> add_node FalseNode lbl "[endfor]" in*)
let newafter = !g +> add_node FallThroughNode lbl "[forfall]" in
let newfakeelse =
!g +> add_node (EndStatement (Some iifakeend)) lbl "[endfor]" in
let newxi = { xi_lbl with
ctx = LoopInfo (newi, newfakeelse, xi_lbl.braces, lbl);
ctx_stack = xi_lbl.ctx::xi_lbl.ctx_stack
}
in
!g#add_arc ((newi, newfakethen), Direct);
!g#add_arc ((newafter, newfakeelse), Direct);
!g#add_arc ((newi, newafter), Direct);
let finalthen = aux_statement (Some newfakethen, newxi) st in
!g +> add_arc_opt (finalthen, newi);
Some newfakeelse
(* to generate less exception with the breakInsideLoop, analyse
* correctly the loop deguisé comme list_for_each. Add a case ForMacro
* in ast_c (and in lexer/parser), and then do code that imitates the
* code for the For.
* update: the list_for_each was previously converted into Tif by the
* lexer, now they are returned as Twhile so less pbs. But not perfect.
* update: now I recognize the list_for_each macro so no more problems.
*)
| Iteration (Ast_c.MacroIteration (s, es, st)), ii ->
let (i1,i2,i3, iifakeend) = tuple_of_list4 ii in
let ii = [i1;i2;i3] in
let newi =
!g+>add_node(MacroIterHeader(stmt,((s,es),ii))) lbl "foreach" in
!g +> add_arc_opt (starti, newi);
let newfakethen = !g +> add_node InLoopNode lbl "[fortrue]" in
(*let newfakeelse = !g +> add_node FalseNode lbl "[endfor]" in*)
let newafter = !g +> add_node FallThroughNode lbl "[foreachfall]" in
let newfakeelse =
!g +> add_node (EndStatement (Some iifakeend)) lbl "[endforeach]" in
let newxi = { xi_lbl with
ctx = LoopInfo (newi, newfakeelse, xi_lbl.braces, lbl);
ctx_stack = xi_lbl.ctx::xi_lbl.ctx_stack
}
in
!g#add_arc ((newi, newfakethen), Direct);
!g#add_arc ((newafter, newfakeelse), Direct);
!g#add_arc ((newi, newafter), Direct);
let finalthen = aux_statement (Some newfakethen, newxi) st in
!g +> add_arc_opt (finalthen, newi);
Some newfakeelse
(* ------------------------- *)
| Jump ((Ast_c.Continue|Ast_c.Break) as x),ii ->
let context_info =
match xi.ctx with
SwitchInfo (startbrace, loopendi, braces, parent_lbl) ->
if x = Ast_c.Break
then xi.ctx
else
(try
xi.ctx_stack +> Common.find_some (function
LoopInfo (_,_,_,_) as c -> Some c
| _ -> None)
with Not_found ->
raise (Error (OnlyBreakInSwitch (pinfo_of_ii ii))))
| LoopInfo (loopstarti, loopendi, braces, parent_lbl) -> xi.ctx
| NoInfo -> raise (Error (NoEnclosingLoop (pinfo_of_ii ii))) in
let parent_label =
match context_info with
LoopInfo (loopstarti, loopendi, braces, parent_lbl) -> parent_lbl
| SwitchInfo (startbrace, loopendi, braces, parent_lbl) -> parent_lbl
| NoInfo -> raise (Impossible 42) in
(* flow_to_ast: *)
let (node_info, string) =
let parent_string =
String.concat "," (List.map string_of_int parent_label) in
(match x with
| Ast_c.Continue ->
(Continue (stmt, ((), ii)),
Printf.sprintf "continue; [%s]" parent_string)
| Ast_c.Break ->
(Break (stmt, ((), ii)),
Printf.sprintf "break; [%s]" parent_string)
| _ -> raise (Impossible 42)
) in
(* idea: break or continue records the label of its parent loop or
switch *)
let newi = !g +> add_bc_node node_info lbl parent_label string in
!g +> add_arc_opt (starti, newi);
(* let newi = some starti in *)
(match context_info with
| LoopInfo (loopstarti, loopendi, braces, parent_lbl) ->
let desti =
(match x with
| Ast_c.Break -> loopendi
| Ast_c.Continue -> loopstarti
| x -> raise (Impossible 42)
) in
let difference = List.length xi.braces - List.length braces in
assert (difference >= 0);
let toend = take difference xi.braces in
let newi = insert_all_braces toend newi in
!g#add_arc ((newi, desti), Direct);
None
| SwitchInfo (startbrace, loopendi, braces, parent_lbl) ->
assert (x = Ast_c.Break);
let difference = List.length xi.braces - List.length braces in
assert (difference >= 0);
let toend = take difference xi.braces in
let newi = insert_all_braces toend newi in
!g#add_arc ((newi, loopendi), Direct);
None
| NoInfo -> raise (Impossible 42)
)
| Jump ((Ast_c.Return | Ast_c.ReturnExpr _) as kind), ii ->
(match xi.exiti, xi.errorexiti with
| None, None -> raise (Error (NoExit (pinfo_of_ii ii)))
| Some exiti, Some errorexiti ->
(* flow_to_ast: *)
let s =
match kind with
| Ast_c.Return -> "return"
| Ast_c.ReturnExpr _ -> "return ..."
| _ -> raise (Impossible 42)
in
let newi =
!g +> add_node
(match kind with
| Ast_c.Return -> Return (stmt, ((),ii))
| Ast_c.ReturnExpr e -> ReturnExpr (stmt, (e, ii))
| _ -> raise (Impossible 42)
)
lbl s
in
!g +> add_arc_opt (starti, newi);
let newi = insert_all_braces xi.braces newi in
if xi.under_ifthen
then !g#add_arc ((newi, errorexiti), Direct)
else !g#add_arc ((newi, exiti), Direct)
;
None
| _ -> raise (Impossible 42)
)
(* ------------------------- *)
| Ast_c.Decl decl, ii ->
let s =
match decl with
| (Ast_c.DeclList
([{v_namei = Some (name,_); v_type = typ; v_storage = sto}, _], _)) ->
"decl:" ^ (id_of_name name)
| _ -> "decl_novar_or_multivar"
in
let newi = !g +> add_node (Decl (decl)) lbl s in
!g +> add_arc_opt (starti, newi);
Some newi
(* ------------------------- *)
| Ast_c.Asm body, ii ->
let newi = !g +> add_node (Asm (stmt, ((body,ii)))) lbl "asm;" in
!g +> add_arc_opt (starti, newi);
Some newi
| Ast_c.MacroStmt, ii ->
let newi = !g +> add_node (MacroStmt (stmt, ((),ii))) lbl "macro;" in
!g +> add_arc_opt (starti, newi);
Some newi
(* ------------------------- *)
| Ast_c.NestedFunc def, ii ->
raise (Error NestedFunc)
and aux_statement_list starti (xi, newxi) statxs =
statxs
+> List.fold_left (fun starti statement_seq ->
if !Flag_parsing_c.label_strategy_2
then incr counter_for_labels;
let newxi' =
if !Flag_parsing_c.label_strategy_2
then { newxi with labels = xi.labels @ [ !counter_for_labels ] }
else newxi
in
match statement_seq with
| Ast_c.StmtElem statement ->
aux_statement (starti, newxi') statement
| Ast_c.CppDirectiveStmt directive ->
pr2_once ("ast_to_flow: filter a directive");
starti