cfc2f87e10c938bbd0463ca4fcc26e6cb3e392cc
[bpt/coccinelle.git] / parsing_c / parsing_hacks.ml
1 (* Yoann Padioleau
2 *
3 * Copyright (C) 2010, University of Copenhagen DIKU and INRIA.
4 * Copyright (C) 2007, 2008 Ecole des Mines de Nantes
5 *
6 * This program is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU General Public License (GPL)
8 * version 2 as published by the Free Software Foundation.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * file license.txt for more details.
14 *)
15
16 open Common
17
18 module TH = Token_helpers
19 module TV = Token_views_c
20 module LP = Lexer_parser
21
22 module Stat = Parsing_stat
23
24 open Parser_c
25
26 open TV
27
28 (*****************************************************************************)
29 (* Some debugging functions *)
30 (*****************************************************************************)
31
32 let pr2, pr2_once = Common.mk_pr2_wrappers Flag_parsing_c.verbose_parsing
33
34 let pr2_cpp s =
35 if !Flag_parsing_c.debug_cpp
36 then Common.pr2_once ("CPP-" ^ s)
37
38
39 let msg_gen cond is_known printer s =
40 if cond
41 then
42 if not (!Flag_parsing_c.filter_msg)
43 then printer s
44 else
45 if not (is_known s)
46 then printer s
47
48
49 (* In the following, there are some harcoded names of types or macros
50 * but they are not used by our heuristics! They are just here to
51 * enable to detect false positive by printing only the typedef/macros
52 * that we don't know yet. If we print everything, then we can easily
53 * get lost with too much verbose tracing information. So those
54 * functions "filter" some messages. So our heuristics are still good,
55 * there is no more (or not that much) hardcoded linux stuff.
56 *)
57
58 let is_known_typdef =
59 (fun s ->
60 (match s with
61 | "u_char" | "u_short" | "u_int" | "u_long"
62 | "u8" | "u16" | "u32" | "u64"
63 | "s8" | "s16" | "s32" | "s64"
64 | "__u8" | "__u16" | "__u32" | "__u64"
65 -> true
66
67 | "acpi_handle"
68 | "acpi_status"
69 -> true
70
71 | "FILE"
72 | "DIR"
73 -> true
74
75 | s when s =~ ".*_t$" -> true
76 | _ -> false
77 )
78 )
79
80 (* note: cant use partial application with let msg_typedef =
81 * because it would compute msg_typedef at compile time when
82 * the flag debug_typedef is always false
83 *)
84 let msg_typedef s n =
85 incr Stat.nTypedefInfer;
86 msg_gen (!Flag_parsing_c.debug_typedef)
87 is_known_typdef
88 (fun s ->
89 (*pr2_cpp (Printf.sprintf "TYPEDEF: promoting(%d): %s" n s)*)
90 pr2_cpp (Printf.sprintf "TYPEDEF: promoting: %s" s)
91 )
92 s
93
94 let msg_maybe_dangereous_typedef s =
95 if not (is_known_typdef s)
96 then
97 pr2
98 ("PB MAYBE: dangerous typedef inference, maybe not a typedef: " ^ s)
99
100
101
102 let msg_declare_macro s =
103 incr Stat.nMacroDecl;
104 msg_gen (!Flag_parsing_c.debug_cpp)
105 (fun s ->
106 (match s with
107 | "DECLARE_MUTEX" | "DECLARE_COMPLETION" | "DECLARE_RWSEM"
108 | "DECLARE_WAITQUEUE" | "DECLARE_WAIT_QUEUE_HEAD"
109 | "DEFINE_SPINLOCK" | "DEFINE_TIMER"
110 | "DEVICE_ATTR" | "CLASS_DEVICE_ATTR" | "DRIVER_ATTR"
111 | "SENSOR_DEVICE_ATTR"
112 | "LIST_HEAD"
113 | "DECLARE_WORK" | "DECLARE_TASKLET"
114 | "PORT_ATTR_RO" | "PORT_PMA_ATTR"
115 | "DECLARE_BITMAP"
116
117 -> true
118 (*
119 | s when s =~ "^DECLARE_.*" -> true
120 | s when s =~ ".*_ATTR$" -> true
121 | s when s =~ "^DEFINE_.*" -> true
122 *)
123
124 | _ -> false
125 )
126 )
127 (fun s -> pr2_cpp ("MACRO: found declare-macro: " ^ s))
128 s
129
130
131 let msg_foreach s =
132 incr Stat.nIteratorHeuristic;
133 pr2_cpp ("MACRO: found foreach: " ^ s)
134
135
136 (* ??
137 let msg_debug_macro s =
138 pr2_cpp ("MACRO: found debug-macro: " ^ s)
139 *)
140
141
142 let msg_macro_noptvirg s =
143 incr Stat.nMacroStmt;
144 pr2_cpp ("MACRO: found macro with param noptvirg: " ^ s)
145
146 let msg_macro_toplevel_noptvirg s =
147 incr Stat.nMacroStmt;
148 pr2_cpp ("MACRO: found toplevel macro noptvirg: " ^ s)
149
150 let msg_macro_noptvirg_single s =
151 incr Stat.nMacroStmt;
152 pr2_cpp ("MACRO: found single-macro noptvirg: " ^ s)
153
154
155
156
157 let msg_macro_higher_order s =
158 incr Stat.nMacroHigherOrder;
159 msg_gen (!Flag_parsing_c.debug_cpp)
160 (fun s ->
161 (match s with
162 | "DBGINFO"
163 | "DBGPX"
164 | "DFLOW"
165 -> true
166 | _ -> false
167 )
168 )
169 (fun s -> pr2_cpp ("MACRO: found higher ordre macro : " ^ s))
170 s
171
172
173 let msg_stringification s =
174 incr Stat.nMacroString;
175 msg_gen (!Flag_parsing_c.debug_cpp)
176 (fun s ->
177 (match s with
178 | "REVISION"
179 | "UTS_RELEASE"
180 | "SIZE_STR"
181 | "DMA_STR"
182 -> true
183 (* s when s =~ ".*STR.*" -> true *)
184 | _ -> false
185 )
186 )
187 (fun s -> pr2_cpp ("MACRO: found string-macro " ^ s))
188 s
189
190 let msg_stringification_params s =
191 incr Stat.nMacroString;
192 pr2_cpp ("MACRO: string-macro with params : " ^ s)
193
194
195
196 let msg_apply_known_macro s =
197 incr Stat.nMacroExpand;
198 pr2_cpp ("MACRO: found known macro = " ^ s)
199
200 let msg_apply_known_macro_hint s =
201 incr Stat.nMacroHint;
202 pr2_cpp ("MACRO: found known macro hint = " ^ s)
203
204
205
206
207 let msg_ifdef_bool_passing is_ifdef_positif =
208 incr Stat.nIfdefZero; (* of Version ? *)
209 if is_ifdef_positif
210 then pr2_cpp "commenting parts of a #if 1 or #if LINUX_VERSION"
211 else pr2_cpp "commenting a #if 0 or #if LINUX_VERSION or __cplusplus"
212
213
214 let msg_ifdef_mid_something () =
215 incr Stat.nIfdefExprPassing;
216 pr2_cpp "found ifdef-mid-something"
217
218 let msg_ifdef_funheaders () =
219 incr Stat.nIfdefFunheader;
220 ()
221
222 let msg_ifdef_cparen_else () =
223 incr Stat.nIfdefPassing;
224 pr2_cpp("found ifdef-cparen-else")
225
226
227 let msg_attribute s =
228 incr Stat.nMacroAttribute;
229 pr2_cpp("ATTR:" ^ s)
230
231
232
233 (*****************************************************************************)
234 (* The regexp and basic view definitions *)
235 (*****************************************************************************)
236
237 (* opti: better to built then once and for all, especially regexp_foreach *)
238
239 let regexp_macro = Str.regexp
240 "^[A-Z_][A-Z_0-9]*$"
241
242 (* linuxext: *)
243 let regexp_annot = Str.regexp
244 "^__.*$"
245
246 (* linuxext: *)
247 let regexp_declare = Str.regexp
248 ".*DECLARE.*"
249
250 (* linuxext: *)
251 let regexp_foreach = Str.regexp_case_fold
252 ".*\\(for_?each\\|for_?all\\|iterate\\|loop\\|walk\\|scan\\|each\\|for\\)"
253
254 let regexp_typedef = Str.regexp
255 ".*_t$"
256
257 let false_typedef = [
258 "printk";
259 ]
260
261
262 let ok_typedef s = not (List.mem s false_typedef)
263
264 let not_annot s =
265 not (s ==~ regexp_annot)
266
267
268
269
270 (*****************************************************************************)
271 (* Helpers *)
272 (*****************************************************************************)
273
274 (* ------------------------------------------------------------------------- *)
275 (* the pair is the status of '()' and '{}', ex: (-1,0)
276 * if too much ')' and good '{}'
277 * could do for [] too ?
278 * could do for ',' if encounter ',' at "toplevel", not inside () or {}
279 * then if have ifdef, then certainly can lead to a problem.
280 *)
281 let (count_open_close_stuff_ifdef_clause: TV.ifdef_grouped list -> (int * int))=
282 fun xs ->
283 let cnt_paren, cnt_brace = ref 0, ref 0 in
284 xs +> TV.iter_token_ifdef (fun x ->
285 (match x.tok with
286 | x when TH.is_opar x -> incr cnt_paren
287 | TOBrace _ -> incr cnt_brace
288 | x when TH.is_cpar x -> decr cnt_paren
289 | TCBrace _ -> decr cnt_brace
290 | _ -> ()
291 )
292 );
293 !cnt_paren, !cnt_brace
294
295
296 (* ------------------------------------------------------------------------- *)
297 let forLOOKAHEAD = 30
298
299
300 (* look if there is a '{' just after the closing ')', and handling the
301 * possibility to have nested expressions inside nested parenthesis
302 *
303 * todo: use indentation instead of premier(statement) ?
304 *)
305 let rec is_really_foreach xs =
306 let rec is_foreach_aux = function
307 | [] -> false, []
308 | TCPar _::TOBrace _::xs -> true, xs
309 (* the following attempts to handle the cases where there is a
310 single statement in the body of the loop. undoubtedly more
311 cases are needed.
312 todo: premier(statement) - suivant(funcall)
313 *)
314 | TCPar _::TIdent _::xs -> true, xs
315 | TCPar _::Tif _::xs -> true, xs
316 | TCPar _::Twhile _::xs -> true, xs
317 | TCPar _::Tfor _::xs -> true, xs
318 | TCPar _::Tswitch _::xs -> true, xs
319 | TCPar _::Treturn _::xs -> true, xs
320
321
322 | TCPar _::xs -> false, xs
323 | TOPar _::xs ->
324 let (_, xs') = is_foreach_aux xs in
325 is_foreach_aux xs'
326 | x::xs -> is_foreach_aux xs
327 in
328 is_foreach_aux xs +> fst
329
330
331 (* ------------------------------------------------------------------------- *)
332 let set_ifdef_token_parenthize_info cnt x =
333 match x with
334 | TIfdef (tag, _)
335 | TIfdefelse (tag, _)
336 | TIfdefelif (tag, _)
337 | TEndif (tag, _)
338
339 | TIfdefBool (_, tag, _)
340 | TIfdefMisc (_, tag, _)
341 | TIfdefVersion (_, tag, _)
342 ->
343 tag := Some cnt;
344
345 | _ -> raise Impossible
346
347
348
349 let ifdef_paren_cnt = ref 0
350
351
352 let rec set_ifdef_parenthize_info xs =
353 xs +> List.iter (function
354 | NotIfdefLine xs -> ()
355 | Ifdefbool (_, xxs, info_ifdef)
356 | Ifdef (xxs, info_ifdef) ->
357
358 incr ifdef_paren_cnt;
359 let total_directives = List.length info_ifdef in
360
361 info_ifdef +> List.iter (fun x ->
362 set_ifdef_token_parenthize_info (!ifdef_paren_cnt, total_directives)
363 x.tok);
364 xxs +> List.iter set_ifdef_parenthize_info
365 )
366
367
368 (*****************************************************************************)
369 (* The parsing hack for #define *)
370 (*****************************************************************************)
371
372 (* To parse macro definitions I need to do some tricks
373 * as some information can be get only at the lexing level. For instance
374 * the space after the name of the macro in '#define foo (x)' is meaningful
375 * but the grammar can not get this information. So define_ident below
376 * look at such space and generate a special TOpardefine. In a similar
377 * way macro definitions can contain some antislash and newlines
378 * and the grammar need to know where the macro ends (which is
379 * a line-level and so low token-level information). Hence the
380 * function 'define_line' below and the TDefEol.
381 *
382 * update: TDefEol is handled in a special way at different places,
383 * a little bit like EOF, especially for error recovery, so this
384 * is an important token that should not be retagged!
385 *
386 *
387 * ugly hack, a better solution perhaps would be to erase TDefEOL
388 * from the Ast and list of tokens in parse_c.
389 *
390 * note: I do a +1 somewhere, it's for the unparsing to correctly sync.
391 *
392 * note: can't replace mark_end_define by simply a fakeInfo(). The reason
393 * is where is the \n TCommentSpace. Normally there is always a last token
394 * to synchronize on, either EOF or the token of the next toplevel.
395 * In the case of the #define we got in list of token
396 * [TCommentSpace "\n"; TDefEOL] but if TDefEOL is a fakeinfo then we will
397 * not synchronize on it and so we will not print the "\n".
398 * A solution would be to put the TDefEOL before the "\n".
399 * (jll: tried to do this, see the comment "Put end of line..." below)
400 *
401 * todo?: could put a ExpandedTok for that ?
402 *)
403 let mark_end_define ii =
404 let ii' =
405 { Ast_c.pinfo = Ast_c.OriginTok { (Ast_c.parse_info_of_info ii) with
406 Common.str = "";
407 Common.charpos = Ast_c.pos_of_info ii + 1
408 };
409 cocci_tag = ref Ast_c.emptyAnnot;
410 comments_tag = ref Ast_c.emptyComments;
411 }
412 in
413 TDefEOL (ii')
414
415 (* put the TDefEOL at the good place *)
416 let rec define_line_1 acc xs =
417 match xs with
418 | [] -> List.rev acc
419 | TDefine ii::xs ->
420 let line = Ast_c.line_of_info ii in
421 let acc = (TDefine ii) :: acc in
422 define_line_2 acc line ii xs
423 | TUndef ii::xs ->
424 let line = Ast_c.line_of_info ii in
425 let acc = (TUndef ii) :: acc in
426 define_line_2 acc line ii xs
427 | TCppEscapedNewline ii::xs ->
428 pr2 ("SUSPICIOUS: a \\ character appears outside of a #define at");
429 pr2 (Ast_c.strloc_of_info ii);
430 let acc = (TCommentSpace ii) :: acc in
431 define_line_1 acc xs
432 | x::xs -> define_line_1 (x::acc) xs
433
434 and define_line_2 acc line lastinfo xs =
435 match xs with
436 | [] ->
437 (* should not happened, should meet EOF before *)
438 pr2 "PB: WEIRD";
439 List.rev (mark_end_define lastinfo::acc)
440 | x::xs ->
441 let line' = TH.line_of_tok x in
442 let info = TH.info_of_tok x in
443
444 (match x with
445 | EOF ii ->
446 let acc = (mark_end_define lastinfo) :: acc in
447 let acc = (EOF ii) :: acc in
448 define_line_1 acc xs
449 | TCppEscapedNewline ii ->
450 if (line' <> line) then pr2 "PB: WEIRD: not same line number";
451 let acc = (TCommentSpace ii) :: acc in
452 define_line_2 acc (line+1) info xs
453 | x ->
454 if line' =|= line
455 then define_line_2 (x::acc) line info xs
456 else
457 (* Put end of line token before the newline. A newline at least
458 must be there because the line changed and because we saw a
459 #define previously to get to this function at all *)
460 define_line_1
461 ((List.hd acc)::(mark_end_define lastinfo::(List.tl acc)))
462 (x::xs)
463 )
464
465 let rec define_ident acc xs =
466 match xs with
467 | [] -> List.rev acc
468 | TUndef ii::xs ->
469 let acc = TUndef ii :: acc in
470 (match xs with
471 TCommentSpace i1::TIdent (s,i2)::xs ->
472 let acc = (TCommentSpace i1) :: acc in
473 let acc = (TIdentDefine (s,i2)) :: acc in
474 define_ident acc xs
475 | _ ->
476 pr2 "WEIRD: weird #define body";
477 define_ident acc xs
478 )
479 | TDefine ii::xs ->
480 let acc = TDefine ii :: acc in
481 (match xs with
482 | TCommentSpace i1::TIdent (s,i2)::TOPar (i3)::xs ->
483 (* Change also the kind of TIdent to avoid bad interaction
484 * with other parsing_hack tricks. For instant if keep TIdent then
485 * the stringication algo can believe the TIdent is a string-macro.
486 * So simpler to change the kind of the ident too.
487 *)
488 (* if TOParDefine sticked to the ident, then
489 * it's a macro-function. Change token to avoid ambiguity
490 * between #define foo(x) and #define foo (x)
491 *)
492 let acc = (TCommentSpace i1) :: acc in
493 let acc = (TIdentDefine (s,i2)) :: acc in
494 let acc = (TOParDefine i3) :: acc in
495 define_ident acc xs
496
497 | TCommentSpace i1::TIdent (s,i2)::xs ->
498 let acc = (TCommentSpace i1) :: acc in
499 let acc = (TIdentDefine (s,i2)) :: acc in
500 define_ident acc xs
501
502 (* bugfix: ident of macro (as well as params, cf below) can be tricky
503 * note, do we need to subst in the body of the define ? no cos
504 * here the issue is the name of the macro, as in #define inline,
505 * so obviously the name of this macro will not be used in its
506 * body (it would be a recursive macro, which is forbidden).
507 *)
508
509 | TCommentSpace i1::t::xs ->
510
511 let s = TH.str_of_tok t in
512 let ii = TH.info_of_tok t in
513 if s ==~ Common.regexp_alpha
514 then begin
515 pr2 (spf "remapping: %s to an ident in macro name" s);
516 let acc = (TCommentSpace i1) :: acc in
517 let acc = (TIdentDefine (s,ii)) :: acc in
518 define_ident acc xs
519 end
520 else begin
521 pr2 "WEIRD: weird #define body";
522 define_ident acc xs
523 end
524
525 | _ ->
526 pr2 "WEIRD: weird #define body";
527 define_ident acc xs
528 )
529 | x::xs ->
530 let acc = x :: acc in
531 define_ident acc xs
532
533
534
535 let fix_tokens_define2 xs =
536 define_ident [] (define_line_1 [] xs)
537
538 let fix_tokens_define a =
539 Common.profile_code "C parsing.fix_define" (fun () -> fix_tokens_define2 a)
540
541
542
543
544
545 (* ------------------------------------------------------------------------- *)
546 (* Other parsing hacks related to cpp, Include/Define hacks *)
547 (* ------------------------------------------------------------------------- *)
548
549 (* Sometimes I prefer to generate a single token for a list of things in the
550 * lexer so that if I have to passed them, like for passing TInclude then
551 * it's easy. Also if I don't do a single token, then I need to
552 * parse the rest which may not need special stuff, like detecting
553 * end of line which the parser is not really ready for. So for instance
554 * could I parse a #include <a/b/c/xxx.h> as 2 or more tokens ? just
555 * lex #include ? so then need recognize <a/b/c/xxx.h> as one token ?
556 * but this kind of token is valid only after a #include and the
557 * lexing and parsing rules are different for such tokens so not that
558 * easy to parse such things in parser_c.mly. Hence the following hacks.
559 *
560 * less?: maybe could get rid of this like I get rid of some of fix_define.
561 *)
562
563 (* helpers *)
564
565 (* used to generate new token from existing one *)
566 let new_info posadd str ii =
567 { Ast_c.pinfo =
568 Ast_c.OriginTok { (Ast_c.parse_info_of_info ii) with
569 charpos = Ast_c.pos_of_info ii + posadd;
570 str = str;
571 column = Ast_c.col_of_info ii + posadd;
572 };
573 (* must generate a new ref each time, otherwise share *)
574 cocci_tag = ref Ast_c.emptyAnnot;
575 comments_tag = ref Ast_c.emptyComments;
576 }
577
578
579 let rec comment_until_defeol xs =
580 match xs with
581 | [] ->
582 (* job not done in Cpp_token_c.define_parse ? *)
583 failwith "cant find end of define token TDefEOL"
584 | x::xs ->
585 (match x with
586 | Parser_c.TDefEOL i ->
587 Parser_c.TCommentCpp (Token_c.CppDirective, TH.info_of_tok x)
588 ::xs
589 | _ ->
590 let x' =
591 (* bugfix: otherwise may lose a TComment token *)
592 if TH.is_real_comment x
593 then x
594 else Parser_c.TCommentCpp (Token_c.CppPassingNormal (*good?*), TH.info_of_tok x)
595 in
596 x'::comment_until_defeol xs
597 )
598
599 let drop_until_defeol xs =
600 List.tl
601 (Common.drop_until (function Parser_c.TDefEOL _ -> true | _ -> false) xs)
602
603
604
605 (* ------------------------------------------------------------------------- *)
606 (* returns a pair (replaced token, list of next tokens) *)
607 (* ------------------------------------------------------------------------- *)
608
609 let tokens_include (info, includes, filename, inifdef) =
610 Parser_c.TIncludeStart (Ast_c.rewrap_str includes info, inifdef),
611 [Parser_c.TIncludeFilename
612 (filename, (new_info (String.length includes) filename info))
613 ]
614
615
616
617
618 (*****************************************************************************)
619 (* CPP handling: macros, ifdefs, macros defs *)
620 (*****************************************************************************)
621
622 (* ------------------------------------------------------------------------- *)
623 (* special skip_start skip_end handling *)
624 (* ------------------------------------------------------------------------- *)
625
626 (* note: after this normally the token list should not contain any more the
627 * TCommentSkipTagStart and End tokens.
628 *)
629 let rec commentize_skip_start_to_end xs =
630 match xs with
631 | [] -> ()
632 | x::xs ->
633 (match x with
634 | {tok = TCommentSkipTagStart info} ->
635 (try
636 let (before, x2, after) =
637 xs +> Common.split_when (function
638 | {tok = TCommentSkipTagEnd _ } -> true
639 | _ -> false
640 )
641 in
642 let topass = x::x2::before in
643 topass +> List.iter (fun tok ->
644 set_as_comment Token_c.CppPassingExplicit tok
645 );
646 commentize_skip_start_to_end after
647 with Not_found ->
648 failwith "could not find end of skip_start special comment"
649 )
650 | {tok = TCommentSkipTagEnd info} ->
651 failwith "found skip_end comment but no skip_start"
652 | _ ->
653 commentize_skip_start_to_end xs
654 )
655
656
657
658
659 (* ------------------------------------------------------------------------- *)
660 (* ifdef keeping/passing *)
661 (* ------------------------------------------------------------------------- *)
662
663 (* #if 0, #if 1, #if LINUX_VERSION handling *)
664 let rec find_ifdef_bool xs =
665 xs +> List.iter (function
666 | NotIfdefLine _ -> ()
667 | Ifdefbool (is_ifdef_positif, xxs, info_ifdef_stmt) ->
668
669 msg_ifdef_bool_passing is_ifdef_positif;
670
671 (match xxs with
672 | [] -> raise Impossible
673 | firstclause::xxs ->
674 info_ifdef_stmt +> List.iter (set_as_comment Token_c.CppDirective);
675
676 if is_ifdef_positif
677 then xxs +> List.iter
678 (iter_token_ifdef (set_as_comment Token_c.CppPassingNormal))
679 else begin
680 firstclause +> iter_token_ifdef (set_as_comment Token_c.CppPassingNormal);
681 (match List.rev xxs with
682 (* keep only last *)
683 | last::startxs ->
684 startxs +> List.iter
685 (iter_token_ifdef (set_as_comment Token_c.CppPassingNormal))
686 | [] -> (* not #else *) ()
687 );
688 end
689 );
690
691 | Ifdef (xxs, info_ifdef_stmt) -> xxs +> List.iter find_ifdef_bool
692 )
693
694
695
696 let thresholdIfdefSizeMid = 6
697
698 (* infer ifdef involving not-closed expressions/statements *)
699 let rec find_ifdef_mid xs =
700 xs +> List.iter (function
701 | NotIfdefLine _ -> ()
702 | Ifdef (xxs, info_ifdef_stmt) ->
703 (match xxs with
704 | [] -> raise Impossible
705 | [first] -> ()
706 | first::second::rest ->
707 (* don't analyse big ifdef *)
708 if xxs +> List.for_all
709 (fun xs -> List.length xs <= thresholdIfdefSizeMid) &&
710 (* don't want nested ifdef *)
711 xxs +> List.for_all (fun xs ->
712 xs +> List.for_all
713 (function NotIfdefLine _ -> true | _ -> false)
714 )
715
716 then
717 let counts = xxs +> List.map count_open_close_stuff_ifdef_clause in
718 let cnt1, cnt2 = List.hd counts in
719 if cnt1 <> 0 || cnt2 <> 0 &&
720 counts +> List.for_all (fun x -> x =*= (cnt1, cnt2))
721 (*
722 if counts +> List.exists (fun (cnt1, cnt2) ->
723 cnt1 <> 0 || cnt2 <> 0
724 )
725 *)
726 then begin
727 msg_ifdef_mid_something();
728
729 (* keep only first, treat the rest as comment *)
730 info_ifdef_stmt +> List.iter (set_as_comment Token_c.CppDirective);
731 (second::rest) +> List.iter
732 (iter_token_ifdef (set_as_comment Token_c.CppPassingCosWouldGetError));
733 end
734
735 );
736 List.iter find_ifdef_mid xxs
737
738 (* no need complex analysis for ifdefbool *)
739 | Ifdefbool (_, xxs, info_ifdef_stmt) ->
740 List.iter find_ifdef_mid xxs
741
742
743 )
744
745
746 let thresholdFunheaderLimit = 4
747
748 (* ifdef defining alternate function header, type *)
749 let rec find_ifdef_funheaders = function
750 | [] -> ()
751 | NotIfdefLine _::xs -> find_ifdef_funheaders xs
752
753 (* ifdef-funheader if ifdef with 2 lines and a '{' in next line *)
754 | Ifdef
755 ([(NotIfdefLine (({col = 0} as _xline1)::line1))::ifdefblock1;
756 (NotIfdefLine (({col = 0} as xline2)::line2))::ifdefblock2
757 ], info_ifdef_stmt
758 )
759 ::NotIfdefLine (({tok = TOBrace i; col = 0})::line3)
760 ::xs
761 when List.length ifdefblock1 <= thresholdFunheaderLimit &&
762 List.length ifdefblock2 <= thresholdFunheaderLimit
763 ->
764 find_ifdef_funheaders xs;
765
766 msg_ifdef_funheaders ();
767 info_ifdef_stmt +> List.iter (set_as_comment Token_c.CppDirective);
768 let all_toks = [xline2] @ line2 in
769 all_toks +> List.iter (set_as_comment Token_c.CppPassingCosWouldGetError) ;
770 ifdefblock2 +> iter_token_ifdef (set_as_comment Token_c.CppPassingCosWouldGetError);
771
772 (* ifdef with nested ifdef *)
773 | Ifdef
774 ([[NotIfdefLine (({col = 0} as _xline1)::line1)];
775 [Ifdef
776 ([[NotIfdefLine (({col = 0} as xline2)::line2)];
777 [NotIfdefLine (({col = 0} as xline3)::line3)];
778 ], info_ifdef_stmt2
779 )
780 ]
781 ], info_ifdef_stmt
782 )
783 ::NotIfdefLine (({tok = TOBrace i; col = 0})::line4)
784 ::xs
785 ->
786 find_ifdef_funheaders xs;
787
788 msg_ifdef_funheaders ();
789 info_ifdef_stmt +> List.iter (set_as_comment Token_c.CppDirective);
790 info_ifdef_stmt2 +> List.iter (set_as_comment Token_c.CppDirective);
791 let all_toks = [xline2;xline3] @ line2 @ line3 in
792 all_toks +> List.iter (set_as_comment Token_c.CppPassingCosWouldGetError);
793
794 (* ifdef with elseif *)
795 | Ifdef
796 ([[NotIfdefLine (({col = 0} as _xline1)::line1)];
797 [NotIfdefLine (({col = 0} as xline2)::line2)];
798 [NotIfdefLine (({col = 0} as xline3)::line3)];
799 ], info_ifdef_stmt
800 )
801 ::NotIfdefLine (({tok = TOBrace i; col = 0})::line4)
802 ::xs
803 ->
804 find_ifdef_funheaders xs;
805
806 msg_ifdef_funheaders ();
807 info_ifdef_stmt +> List.iter (set_as_comment Token_c.CppDirective);
808 let all_toks = [xline2;xline3] @ line2 @ line3 in
809 all_toks +> List.iter (set_as_comment Token_c.CppPassingCosWouldGetError)
810
811 (* recurse *)
812 | Ifdef (xxs,info_ifdef_stmt)::xs
813 | Ifdefbool (_, xxs,info_ifdef_stmt)::xs ->
814 List.iter find_ifdef_funheaders xxs;
815 find_ifdef_funheaders xs
816
817
818
819 (* ?? *)
820 let rec adjust_inifdef_include xs =
821 xs +> List.iter (function
822 | NotIfdefLine _ -> ()
823 | Ifdef (xxs, info_ifdef_stmt) | Ifdefbool (_, xxs, info_ifdef_stmt) ->
824 xxs +> List.iter (iter_token_ifdef (fun tokext ->
825 match tokext.tok with
826 | Parser_c.TInclude (s1, s2, inifdef_ref, ii) ->
827 inifdef_ref := true;
828 | _ -> ()
829 ));
830 )
831
832
833
834
835
836
837
838 let rec find_ifdef_cparen_else xs =
839 let rec aux xs =
840 xs +> List.iter (function
841 | NotIfdefLine _ -> ()
842 | Ifdef (xxs, info_ifdef_stmt) ->
843 (match xxs with
844 | [] -> raise Impossible
845 | [first] -> ()
846 | first::second::rest ->
847
848 (* found a closing ')' just after the #else *)
849
850 (* Too bad ocaml does not support better list pattern matching
851 * a la Prolog-III where can match the end of lists.
852 *)
853 let condition =
854 if List.length first = 0 then false
855 else
856 let last_line = Common.last first in
857 match last_line with
858 | NotIfdefLine xs ->
859 if List.length xs = 0 then false
860 else
861 let last_tok = Common.last xs in
862 TH.is_cpar last_tok.tok
863 | Ifdef _ | Ifdefbool _ -> false
864 in
865 if condition then begin
866 msg_ifdef_cparen_else();
867
868 (* keep only first, treat the rest as comment *)
869 info_ifdef_stmt +> List.iter (set_as_comment Token_c.CppDirective);
870 (second::rest) +> List.iter
871 (iter_token_ifdef (set_as_comment Token_c.CppPassingCosWouldGetError));
872 end
873
874 );
875 List.iter aux xxs
876
877 (* no need complex analysis for ifdefbool *)
878 | Ifdefbool (_, xxs, info_ifdef_stmt) ->
879 List.iter aux xxs
880 )
881 in aux xs
882
883
884 (* ------------------------------------------------------------------------- *)
885 (* cpp-builtin part2, macro, using standard.h or other defs *)
886 (* ------------------------------------------------------------------------- *)
887
888 (* now in cpp_token_c.ml *)
889
890 (* ------------------------------------------------------------------------- *)
891 (* stringification *)
892 (* ------------------------------------------------------------------------- *)
893
894 let rec find_string_macro_paren xs =
895 match xs with
896 | [] -> ()
897 | Parenthised(xxs, info_parens)::xs ->
898 xxs +> List.iter (fun xs ->
899 if xs +> List.exists
900 (function PToken({tok = (TString _| TMacroString _)}) -> true | _ -> false) &&
901 xs +> List.for_all
902 (function PToken({tok = (TString _| TMacroString _)}) | PToken({tok = TIdent _}) ->
903 true | _ -> false)
904 then
905 xs +> List.iter (fun tok ->
906 match tok with
907 | PToken({tok = TIdent (s,_)} as id) ->
908 msg_stringification s;
909 id.tok <- TMacroString (s, TH.info_of_tok id.tok);
910 | _ -> ()
911 )
912 else
913 find_string_macro_paren xs
914 );
915 find_string_macro_paren xs
916 | PToken(tok)::xs ->
917 find_string_macro_paren xs
918
919
920 (* ------------------------------------------------------------------------- *)
921 (* macro2 *)
922 (* ------------------------------------------------------------------------- *)
923
924 (* don't forget to recurse in each case *)
925 let rec find_macro_paren xs =
926 match xs with
927 | [] -> ()
928
929 (* attribute *)
930 | PToken ({tok = Tattribute _} as id)
931 ::Parenthised (xxs,info_parens)
932 ::xs
933 ->
934 pr2_cpp ("MACRO: __attribute detected ");
935 [Parenthised (xxs, info_parens)] +>
936 iter_token_paren (set_as_comment Token_c.CppAttr);
937 set_as_comment Token_c.CppAttr id;
938 find_macro_paren xs
939
940 | PToken ({tok = TattributeNoarg _} as id)
941 ::xs
942 ->
943 pr2_cpp ("MACRO: __attributenoarg detected ");
944 set_as_comment Token_c.CppAttr id;
945 find_macro_paren xs
946
947 (*
948 (* attribute cpp, __xxx id *)
949 | PToken ({tok = TIdent (s,i1)} as id)
950 ::PToken ({tok = TIdent (s2, i2)} as id2)
951 ::xs when s ==~ regexp_annot
952 ->
953 msg_attribute s;
954 id.tok <- TMacroAttr (s, i1);
955 find_macro_paren ((PToken id2)::xs); (* recurse also on id2 ? *)
956
957 (* attribute cpp, id __xxx *)
958 | PToken ({tok = TIdent (s,i1)} as _id)
959 ::PToken ({tok = TIdent (s2, i2)} as id2)
960 ::xs when s2 ==~ regexp_annot && (not (s ==~ regexp_typedef))
961 ->
962 msg_attribute s2;
963 id2.tok <- TMacroAttr (s2, i2);
964 find_macro_paren xs
965
966 | PToken ({tok = (Tstatic _ | Textern _)} as tok1)
967 ::PToken ({tok = TIdent (s,i1)} as attr)
968 ::xs when s ==~ regexp_annot
969 ->
970 pr2_cpp ("storage attribute: " ^ s);
971 attr.tok <- TMacroAttrStorage (s,i1);
972 (* recurse, may have other storage attributes *)
973 find_macro_paren (PToken (tok1)::xs)
974
975 *)
976
977 (* storage attribute *)
978 | PToken ({tok = (Tstatic _ | Textern _)} as tok1)
979 ::PToken ({tok = TMacroAttr (s,i1)} as attr)::xs
980 ->
981 pr2_cpp ("storage attribute: " ^ s);
982 attr.tok <- TMacroAttrStorage (s,i1);
983 (* recurse, may have other storage attributes *)
984 find_macro_paren (PToken (tok1)::xs)
985
986
987 (* stringification
988 *
989 * the order of the matching clause is important
990 *
991 *)
992
993 (* string macro with params, before case *)
994 | PToken ({tok = (TString _| TMacroString _)})::PToken ({tok = TIdent (s,_)} as id)
995 ::Parenthised (xxs, info_parens)
996 ::xs ->
997
998 msg_stringification_params s;
999 id.tok <- TMacroString (s, TH.info_of_tok id.tok);
1000 [Parenthised (xxs, info_parens)] +>
1001 iter_token_paren (set_as_comment Token_c.CppMacro);
1002 find_macro_paren xs
1003
1004 (* after case *)
1005 | PToken ({tok = TIdent (s,_)} as id)
1006 ::Parenthised (xxs, info_parens)
1007 ::PToken ({tok = (TString _ | TMacroString _)})
1008 ::xs ->
1009
1010 msg_stringification_params s;
1011 id.tok <- TMacroString (s, TH.info_of_tok id.tok);
1012 [Parenthised (xxs, info_parens)] +>
1013 iter_token_paren (set_as_comment Token_c.CppMacro);
1014 find_macro_paren xs
1015
1016
1017 (* for the case where the string is not inside a funcall, but
1018 * for instance in an initializer.
1019 *)
1020
1021 (* string macro variable, before case *)
1022 | PToken ({tok = (TString _ | TMacroString _)})::PToken ({tok = TIdent (s,_)} as id)
1023 ::xs ->
1024
1025 msg_stringification s;
1026 id.tok <- TMacroString (s, TH.info_of_tok id.tok);
1027 find_macro_paren xs
1028
1029 (* after case *)
1030 | PToken ({tok = TIdent (s,_)} as id)
1031 ::PToken ({tok = (TString _ | TMacroString _)})
1032 ::xs ->
1033
1034 msg_stringification s;
1035 id.tok <- TMacroString (s, TH.info_of_tok id.tok);
1036 find_macro_paren xs
1037
1038
1039
1040
1041
1042 (* recurse *)
1043 | (PToken x)::xs -> find_macro_paren xs
1044 | (Parenthised (xxs, info_parens))::xs ->
1045 xxs +> List.iter find_macro_paren;
1046 find_macro_paren xs
1047
1048
1049
1050
1051
1052 (* don't forget to recurse in each case *)
1053 let rec find_macro_lineparen xs =
1054 match xs with
1055 | [] -> ()
1056
1057 (* linuxext: ex: static [const] DEVICE_ATTR(); *)
1058 | (Line
1059 (
1060 [PToken ({tok = Tstatic _});
1061 PToken ({tok = TIdent (s,_)} as macro);
1062 Parenthised (xxs,info_parens);
1063 PToken ({tok = TPtVirg _});
1064 ]
1065 ))
1066 ::xs
1067 when (s ==~ regexp_macro) ->
1068
1069 msg_declare_macro s;
1070 let info = TH.info_of_tok macro.tok in
1071 macro.tok <- TMacroDecl (Ast_c.str_of_info info, info);
1072
1073 find_macro_lineparen (xs)
1074
1075 (* the static const case *)
1076 | (Line
1077 (
1078 [PToken ({tok = Tstatic _});
1079 PToken ({tok = Tconst _} as const);
1080 PToken ({tok = TIdent (s,_)} as macro);
1081 Parenthised (xxs,info_parens);
1082 PToken ({tok = TPtVirg _});
1083 ]
1084 (*as line1*)
1085
1086 ))
1087 ::xs
1088 when (s ==~ regexp_macro) ->
1089
1090 msg_declare_macro s;
1091 let info = TH.info_of_tok macro.tok in
1092 macro.tok <- TMacroDecl (Ast_c.str_of_info info, info);
1093
1094 (* need retag this const, otherwise ambiguity in grammar
1095 21: shift/reduce conflict (shift 121, reduce 137) on Tconst
1096 decl2 : Tstatic . TMacroDecl TOPar argument_list TCPar ...
1097 decl2 : Tstatic . Tconst TMacroDecl TOPar argument_list TCPar ...
1098 storage_class_spec : Tstatic . (137)
1099 *)
1100 const.tok <- TMacroDeclConst (TH.info_of_tok const.tok);
1101
1102 find_macro_lineparen (xs)
1103
1104
1105 (* same but without trailing ';'
1106 *
1107 * I do not put the final ';' because it can be on a multiline and
1108 * because of the way mk_line is coded, we will not have access to
1109 * this ';' on the next line, even if next to the ')' *)
1110 | (Line
1111 ([PToken ({tok = Tstatic _});
1112 PToken ({tok = TIdent (s,_)} as macro);
1113 Parenthised (xxs,info_parens);
1114 ]
1115 ))
1116 ::xs
1117 when s ==~ regexp_macro ->
1118
1119 msg_declare_macro s;
1120 let info = TH.info_of_tok macro.tok in
1121 macro.tok <- TMacroDecl (Ast_c.str_of_info info, info);
1122
1123 find_macro_lineparen (xs)
1124
1125
1126
1127
1128 (* on multiple lines *)
1129 | (Line
1130 (
1131 (PToken ({tok = Tstatic _})::[]
1132 )))
1133 ::(Line
1134 (
1135 [PToken ({tok = TIdent (s,_)} as macro);
1136 Parenthised (xxs,info_parens);
1137 PToken ({tok = TPtVirg _});
1138 ]
1139 )
1140 )
1141 ::xs
1142 when (s ==~ regexp_macro) ->
1143
1144 msg_declare_macro s;
1145 let info = TH.info_of_tok macro.tok in
1146 macro.tok <- TMacroDecl (Ast_c.str_of_info info, info);
1147
1148 find_macro_lineparen (xs)
1149
1150
1151 (* linuxext: ex: DECLARE_BITMAP();
1152 *
1153 * Here I use regexp_declare and not regexp_macro because
1154 * Sometimes it can be a FunCallMacro such as DEBUG(foo());
1155 * Here we don't have the preceding 'static' so only way to
1156 * not have positive is to restrict to .*DECLARE.* macros.
1157 *
1158 * but there is a grammar rule for that, so don't need this case anymore
1159 * unless the parameter of the DECLARE_xxx are weird and can not be mapped
1160 * on a argument_list
1161 *)
1162
1163 | (Line
1164 ([PToken ({tok = TIdent (s,_)} as macro);
1165 Parenthised (xxs,info_parens);
1166 PToken ({tok = TPtVirg _});
1167 ]
1168 ))
1169 ::xs
1170 when (s ==~ regexp_declare) ->
1171
1172 msg_declare_macro s;
1173 let info = TH.info_of_tok macro.tok in
1174 macro.tok <- TMacroDecl (Ast_c.str_of_info info, info);
1175
1176 find_macro_lineparen (xs)
1177
1178
1179 (* toplevel macros.
1180 * module_init(xxx)
1181 *
1182 * Could also transform the TIdent in a TMacroTop but can have false
1183 * positive, so easier to just change the TCPar and so just solve
1184 * the end-of-stream pb of ocamlyacc
1185 *)
1186 | (Line
1187 ([PToken ({tok = TIdent (s,ii); col = col1; where = ctx} as _macro);
1188 Parenthised (xxs,info_parens);
1189 ] as _line1
1190 ))
1191 ::xs when col1 =|= 0
1192 ->
1193 let condition =
1194 (* to reduce number of false positive *)
1195 (match xs with
1196 | (Line (PToken ({col = col2 } as other)::restline2))::_ ->
1197 TH.is_eof other.tok || (col2 =|= 0 &&
1198 (match other.tok with
1199 | TOBrace _ -> false (* otherwise would match funcdecl *)
1200 | TCBrace _ when ctx <> InFunction -> false
1201 | TPtVirg _
1202 | TDotDot _
1203 -> false
1204 | tok when TH.is_binary_operator tok -> false
1205
1206 | _ -> true
1207 )
1208 )
1209 | _ -> false
1210 )
1211 in
1212 if condition
1213 then begin
1214
1215 msg_macro_toplevel_noptvirg s;
1216 (* just to avoid the end-of-stream pb of ocamlyacc *)
1217 let tcpar = Common.last info_parens in
1218 tcpar.tok <- TCParEOL (TH.info_of_tok tcpar.tok);
1219
1220 (*macro.tok <- TMacroTop (s, TH.info_of_tok macro.tok);*)
1221
1222 end;
1223
1224 find_macro_lineparen (xs)
1225
1226
1227
1228 (* macro with parameters
1229 * ex: DEBUG()
1230 * return x;
1231 *)
1232 | (Line
1233 ([PToken ({tok = TIdent (s,ii); col = col1; where = ctx} as macro);
1234 Parenthised (xxs,info_parens);
1235 ] as _line1
1236 ))
1237 ::(Line
1238 (PToken ({col = col2 } as other)::restline2
1239 ) as line2)
1240 ::xs
1241 (* when s ==~ regexp_macro *)
1242 ->
1243 let condition =
1244 (col1 =|= col2 &&
1245 (match other.tok with
1246 | TOBrace _ -> false (* otherwise would match funcdecl *)
1247 | TCBrace _ when ctx <> InFunction -> false
1248 | TPtVirg _
1249 | TDotDot _
1250 -> false
1251 | tok when TH.is_binary_operator tok -> false
1252
1253 | _ -> true
1254 )
1255 )
1256 ||
1257 (col2 <= col1 &&
1258 (match other.tok, restline2 with
1259 | TCBrace _, _ when ctx =*= InFunction -> true
1260 | Treturn _, _ -> true
1261 | Tif _, _ -> true
1262 | Telse _, _ -> true
1263
1264 (* case of label, usually put in first line *)
1265 | TIdent _, (PToken ({tok = TDotDot _}))::_ ->
1266 true
1267
1268
1269 | _ -> false
1270 )
1271 )
1272
1273 in
1274
1275 if condition
1276 then
1277 if col1 =|= 0 then ()
1278 else begin
1279 msg_macro_noptvirg s;
1280 macro.tok <- TMacroStmt (s, TH.info_of_tok macro.tok);
1281 [Parenthised (xxs, info_parens)] +>
1282 iter_token_paren (set_as_comment Token_c.CppMacro);
1283 end;
1284
1285 find_macro_lineparen (line2::xs)
1286
1287 (* linuxext:? single macro
1288 * ex: LOCK
1289 * foo();
1290 * UNLOCK
1291 *
1292 * todo: factorize code with previous rule ?
1293 *)
1294 | (Line
1295 ([PToken ({tok = TIdent (s,ii); col = col1; where = ctx} as macro);
1296 ] as _line1
1297 ))
1298 ::(Line
1299 (PToken ({col = col2 } as other)::restline2
1300 ) as line2)
1301 ::xs ->
1302 (* when s ==~ regexp_macro *)
1303
1304 let condition =
1305 (col1 =|= col2 &&
1306 col1 <> 0 && (* otherwise can match typedef of fundecl*)
1307 (match other.tok with
1308 | TPtVirg _ -> false
1309 | TOr _ -> false
1310 | TCBrace _ when ctx <> InFunction -> false
1311 | tok when TH.is_binary_operator tok -> false
1312
1313 | _ -> true
1314 )) ||
1315 (col2 <= col1 &&
1316 (match other.tok with
1317 | TCBrace _ when ctx =*= InFunction -> true
1318 | Treturn _ -> true
1319 | Tif _ -> true
1320 | Telse _ -> true
1321 | _ -> false
1322 ))
1323 in
1324
1325 if condition
1326 then begin
1327 msg_macro_noptvirg_single s;
1328 macro.tok <- TMacroStmt (s, TH.info_of_tok macro.tok);
1329 end;
1330 find_macro_lineparen (line2::xs)
1331
1332 | x::xs ->
1333 find_macro_lineparen xs
1334
1335
1336
1337 (* ------------------------------------------------------------------------- *)
1338 (* define tobrace init *)
1339 (* ------------------------------------------------------------------------- *)
1340
1341 let rec find_define_init_brace_paren xs =
1342 let rec aux xs =
1343 match xs with
1344 | [] -> ()
1345
1346 (* mainly for firefox *)
1347 | (PToken {tok = TDefine _})
1348 ::(PToken {tok = TIdentDefine (s,_)})
1349 ::(PToken ({tok = TOBrace i1} as tokbrace))
1350 ::(PToken tok2)
1351 ::(PToken tok3)
1352 ::xs ->
1353 let is_init =
1354 match tok2.tok, tok3.tok with
1355 | TInt _, TComma _ -> true
1356 | TString _, TComma _ -> true
1357 | TIdent _, TComma _ -> true
1358 | _ -> false
1359
1360 in
1361 if is_init
1362 then begin
1363 pr2_cpp("found define initializer: " ^s);
1364 tokbrace.tok <- TOBraceDefineInit i1;
1365 end;
1366
1367 aux xs
1368
1369 (* mainly for linux, especially in sound/ *)
1370 | (PToken {tok = TDefine _})
1371 ::(PToken {tok = TIdentDefine (s,_)})
1372 ::(Parenthised(xxx, info_parens))
1373 ::(PToken ({tok = TOBrace i1} as tokbrace))
1374 ::(PToken tok2)
1375 ::(PToken tok3)
1376 ::xs ->
1377 let is_init =
1378 match tok2.tok, tok3.tok with
1379 | TInt _, TComma _ -> true
1380 | TDot _, TIdent _ -> true
1381 | TIdent _, TComma _ -> true
1382 | _ -> false
1383
1384 in
1385 if is_init
1386 then begin
1387 pr2_cpp("found define initializer with param: " ^ s);
1388 tokbrace.tok <- TOBraceDefineInit i1;
1389 end;
1390
1391 aux xs
1392
1393
1394
1395 (* recurse *)
1396 | (PToken x)::xs -> aux xs
1397 | (Parenthised (xxs, info_parens))::xs ->
1398 (* not need for tobrace init:
1399 * xxs +> List.iter aux;
1400 *)
1401 aux xs
1402 in
1403 aux xs
1404
1405
1406 (* ------------------------------------------------------------------------- *)
1407 (* action *)
1408 (* ------------------------------------------------------------------------- *)
1409
1410 (* obsolete now with macro expansion ? get some regression if comment.
1411 * todo: if do bad decision here, then it can influence other phases
1412 * and make it hard to parse. So maybe when have a parse error, should
1413 * undo some of the guess those heuristics have done, and restore
1414 * the original token value.
1415 *)
1416
1417 let rec find_actions = function
1418 | [] -> ()
1419
1420 | PToken ({tok = TIdent (s,ii)})
1421 ::Parenthised (xxs,info_parens)
1422 ::xs ->
1423 find_actions xs;
1424 xxs +> List.iter find_actions;
1425 let modified = find_actions_params xxs in
1426 if modified
1427 then msg_macro_higher_order s
1428
1429 | x::xs ->
1430 find_actions xs
1431
1432 and find_actions_params xxs =
1433 xxs +> List.fold_left (fun acc xs ->
1434 let toks = tokens_of_paren xs in
1435 if toks +> List.exists (fun x -> TH.is_statement x.tok)
1436 (* undo: && List.length toks > 1
1437 * good for sparse, not good for linux
1438 *)
1439 then begin
1440 xs +> iter_token_paren (fun x ->
1441 if TH.is_eof x.tok
1442 then
1443 (* certainly because paren detection had a pb because of
1444 * some ifdef-exp. Do similar additional checking than
1445 * what is done in set_as_comment.
1446 *)
1447 pr2 "PB: weird, I try to tag an EOF token as an action"
1448 else
1449 (* cf tests-bis/no_cpar_macro.c *)
1450 if TH.is_eom x.tok
1451 then
1452 pr2 "PB: weird, I try to tag an EOM token as an action"
1453 else
1454 x.tok <- TAction (TH.info_of_tok x.tok);
1455 );
1456 true (* modified *)
1457 end
1458 else acc
1459 ) false
1460
1461
1462
1463 (* ------------------------------------------------------------------------- *)
1464 (* main fix cpp function *)
1465 (* ------------------------------------------------------------------------- *)
1466
1467 let filter_cpp_stuff xs =
1468 List.filter
1469 (function x ->
1470 (match x.tok with
1471 | tok when TH.is_comment tok -> false
1472 (* don't want drop the define, or if drop, have to drop
1473 * also its body otherwise the line heuristics may be lost
1474 * by not finding the TDefine in column 0 but by finding
1475 * a TDefineIdent in a column > 0
1476 *)
1477 | Parser_c.TDefine _ -> true
1478 | tok when TH.is_cpp_instruction tok -> false
1479 | _ -> true
1480 ))
1481 xs
1482
1483 let insert_virtual_positions l =
1484 let strlen x = String.length (Ast_c.str_of_info x) in
1485 let rec loop prev offset acc = function
1486 [] -> List.rev acc
1487 | x::xs ->
1488 let ii = TH.info_of_tok x in
1489 let inject pi =
1490 TH.visitor_info_of_tok (function ii -> Ast_c.rewrap_pinfo pi ii) x in
1491 match Ast_c.pinfo_of_info ii with
1492 Ast_c.OriginTok pi ->
1493 let prev = Ast_c.parse_info_of_info ii in
1494 loop prev (strlen ii) (x::acc) xs
1495 | Ast_c.ExpandedTok (pi,_) ->
1496 let x' = inject (Ast_c.ExpandedTok (pi,(prev,offset))) in
1497 loop prev (offset + (strlen ii)) (x'::acc) xs
1498 | Ast_c.FakeTok (s,_) ->
1499 let x' = inject (Ast_c.FakeTok (s,(prev,offset))) in
1500 loop prev (offset + (strlen ii)) (x'::acc) xs
1501 | Ast_c.AbstractLineTok _ -> failwith "abstract not expected" in
1502 let rec skip_fake = function
1503 | [] -> []
1504 | x::xs ->
1505 let ii = TH.info_of_tok x in
1506 match Ast_c.pinfo_of_info ii with
1507 | Ast_c.OriginTok pi ->
1508 let prev = Ast_c.parse_info_of_info ii in
1509 let res = loop prev (strlen ii) [] xs in
1510 x::res
1511 | _ -> x::skip_fake xs in
1512 skip_fake l
1513
1514 (* ------------------------------------------------------------------------- *)
1515
1516 let fix_tokens_cpp2 ~macro_defs tokens =
1517 let tokens2 = ref (tokens +> Common.acc_map TV.mk_token_extended) in
1518
1519 begin
1520 (* the order is important, if you put the action heuristic first,
1521 * then because of ifdef, can have not closed paren
1522 * and so may believe that higher order macro
1523 * and it will eat too much tokens. So important to do
1524 * first the ifdef.
1525 *
1526 * I recompute multiple times cleaner cos the mutable
1527 * can have be changed and so may have more comments
1528 * in the token original list.
1529 *
1530 *)
1531
1532 commentize_skip_start_to_end !tokens2;
1533
1534 (* ifdef *)
1535 let cleaner = !tokens2 +> List.filter (fun x ->
1536 (* is_comment will also filter the TCommentCpp created in
1537 * commentize_skip_start_to_end *)
1538 not (TH.is_comment x.tok) (* could filter also #define/#include *)
1539 ) in
1540 let ifdef_grouped = TV.mk_ifdef cleaner in
1541 set_ifdef_parenthize_info ifdef_grouped;
1542
1543 find_ifdef_funheaders ifdef_grouped;
1544 find_ifdef_bool ifdef_grouped;
1545 find_ifdef_mid ifdef_grouped;
1546 (* change order ? maybe cparen_else heuristic make some of the funheaders
1547 * heuristics irrelevant ?
1548 *)
1549 find_ifdef_cparen_else ifdef_grouped;
1550 adjust_inifdef_include ifdef_grouped;
1551
1552
1553 (* macro 1 *)
1554 let cleaner = !tokens2 +> filter_cpp_stuff in
1555
1556 let paren_grouped = TV.mk_parenthised cleaner in
1557 Cpp_token_c.apply_macro_defs
1558 ~msg_apply_known_macro
1559 ~msg_apply_known_macro_hint
1560 macro_defs paren_grouped;
1561 (* because the before field is used by apply_macro_defs *)
1562 tokens2 := TV.rebuild_tokens_extented !tokens2;
1563
1564 (* tagging contextual info (InFunc, InStruct, etc). Better to do
1565 * that after the "ifdef-simplification" phase.
1566 *)
1567 let cleaner = !tokens2 +> List.filter (fun x ->
1568 not (TH.is_comment x.tok) (* could filter also #define/#include *)
1569 ) in
1570
1571 let brace_grouped = TV.mk_braceised cleaner in
1572 set_context_tag brace_grouped;
1573
1574 (* macro *)
1575 let cleaner = !tokens2 +> filter_cpp_stuff in
1576
1577 let paren_grouped = TV.mk_parenthised cleaner in
1578 let line_paren_grouped = TV.mk_line_parenthised paren_grouped in
1579 find_define_init_brace_paren paren_grouped;
1580 find_string_macro_paren paren_grouped;
1581 find_macro_lineparen line_paren_grouped;
1582 find_macro_paren paren_grouped;
1583
1584
1585 (* obsolete: actions ? not yet *)
1586 let cleaner = !tokens2 +> filter_cpp_stuff in
1587 let paren_grouped = TV.mk_parenthised cleaner in
1588 find_actions paren_grouped;
1589
1590
1591
1592 insert_virtual_positions (!tokens2 +> Common.acc_map (fun x -> x.tok))
1593 end
1594
1595 let time_hack1 ~macro_defs a =
1596 Common.profile_code_exclusif "HACK" (fun () -> fix_tokens_cpp2 ~macro_defs a)
1597
1598 let fix_tokens_cpp ~macro_defs a =
1599 Common.profile_code "C parsing.fix_cpp" (fun () -> time_hack1 ~macro_defs a)
1600
1601
1602
1603
1604 (*****************************************************************************)
1605 (* Lexing with lookahead *)
1606 (*****************************************************************************)
1607
1608 (* Why using yet another parsing_hack technique ? The fix_xxx where do
1609 * some pre-processing on the full list of tokens is not enough ?
1610 * No cos sometimes we need more contextual info, and even if
1611 * set_context() tries to give some contextual info, it's not completely
1612 * accurate so the following code give yet another alternative, yet another
1613 * chance to transform some tokens.
1614 *
1615 * todo?: maybe could try to get rid of this technique. Maybe a better
1616 * set_context() would make possible to move this code using a fix_xx
1617 * technique.
1618 *
1619 * LALR(k) trick. We can do stuff by adding cases in lexer_c.mll, but
1620 * it is more general to do it via my LALR(k) tech. Because here we can
1621 * transform some token give some context information. So sometimes it
1622 * makes sense to transform a token in one context, sometimes not, and
1623 * lex can not provide us this context information. Note that the order
1624 * in the pattern matching in lookahead is important. Do not cut/paste.
1625 *
1626 * Note that in next there is only "clean" tokens, there is no comment
1627 * or space tokens. This is done by the caller.
1628 *
1629 *)
1630
1631 open Lexer_parser (* for the fields of lexer_hint type *)
1632
1633 let not_struct_enum = function
1634 | (Parser_c.Tstruct _ | Parser_c.Tunion _ | Parser_c.Tenum _)::_ -> false
1635 | _ -> true
1636
1637 let pointer = function
1638 TMul _ -> true
1639 | TAnd _ when !Flag.c_plus_plus -> true
1640 | _ -> false
1641
1642 let lookahead2 ~pass next before =
1643
1644 match (next, before) with
1645
1646 (* c++ hacks *)
1647 (* yy xx( and in function *)
1648 | TOPar i1::_, TIdent(s,i2)::TypedefIdent _::_
1649 when !Flag.c_plus_plus && (LP.current_context () = (LP.InFunction)) ->
1650 pr2_cpp("constructed_object: " ^s);
1651 TOParCplusplusInit i1
1652 | TypedefIdent(s,i)::TOPar i1::_,_
1653 when !Flag.c_plus_plus && (LP.current_context () = (LP.InFunction)) ->
1654 TIdent(s,i)
1655
1656 (*-------------------------------------------------------------*)
1657 (* typedef inference, parse_typedef_fix3 *)
1658 (*-------------------------------------------------------------*)
1659 (* xx xx *)
1660 | (TIdent(s,i1)::TIdent(s2,i2)::_ , _) when not_struct_enum before && s =$= s2
1661 && ok_typedef s
1662 (* (take_safe 1 !passed_tok <> [TOPar]) -> *)
1663 ->
1664 (* parse_typedef_fix3:
1665 * acpi_object acpi_object;
1666 * etait mal parsé, car pas le temps d'appeler dt() dans le type_spec.
1667 * Le parser en interne a deja appelé le prochain token pour pouvoir
1668 * decider des choses.
1669 * => special case in lexer_heuristic, again
1670 *)
1671 if !Flag_parsing_c.debug_typedef
1672 then pr2 ("TYPEDEF: disable typedef cos special case: " ^ s);
1673
1674 LP.disable_typedef();
1675
1676 msg_typedef s 1; LP.add_typedef_root s;
1677 TypedefIdent (s, i1)
1678
1679 (* xx yy *)
1680 | (TIdent (s, i1)::TIdent (s2, i2)::_ , _) when not_struct_enum before
1681 && ok_typedef s
1682 ->
1683 (* && not_annot s2 BUT lead to false positive*)
1684
1685 msg_typedef s 2; LP.add_typedef_root s;
1686 TypedefIdent (s, i1)
1687
1688
1689 (* xx inline *)
1690 | (TIdent (s, i1)::Tinline i2::_ , _) when not_struct_enum before
1691 && ok_typedef s
1692 ->
1693 msg_typedef s 3; LP.add_typedef_root s;
1694 TypedefIdent (s, i1)
1695
1696
1697 (* [,(] xx [,)] AND param decl *)
1698 | (TIdent (s, i1)::(TComma _|TCPar _)::_ , (TComma _ |TOPar _)::_ )
1699 when not_struct_enum before && (LP.current_context() =*= LP.InParameter)
1700 && ok_typedef s
1701 ->
1702 msg_typedef s 4; LP.add_typedef_root s;
1703 TypedefIdent (s, i1)
1704
1705 (* xx* [,)] *)
1706 (* specialcase: [,(] xx* [,)] *)
1707 | (TIdent (s, i1)::ptr::(TComma _|TCPar _)::_ , (*(TComma _|TOPar _)::*)_ )
1708 when pointer ptr && not_struct_enum before
1709 (* && !LP._lexer_hint = Some LP.ParameterDeclaration *)
1710 && ok_typedef s
1711 ->
1712 msg_typedef s 5; LP.add_typedef_root s;
1713 TypedefIdent (s, i1)
1714
1715
1716 (* xx** [,)] *)
1717 (* specialcase: [,(] xx** [,)] *)
1718 | (TIdent (s, i1)::TMul _::TMul _::(TComma _|TCPar _)::_ , (*(TComma _|TOPar _)::*)_ )
1719 when not_struct_enum before
1720 (* && !LP._lexer_hint = Some LP.ParameterDeclaration *)
1721 && ok_typedef s
1722 ->
1723 msg_typedef s 6; LP.add_typedef_root s;
1724 TypedefIdent (s, i1)
1725
1726
1727
1728 (* xx const * USELESS because of next rule ? *)
1729 | (TIdent (s, i1)::(Tconst _|Tvolatile _|Trestrict _)::TMul _::_ , _ )
1730 when not_struct_enum before
1731 (* && !LP._lexer_hint = Some LP.ParameterDeclaration *)
1732 && ok_typedef s
1733 ->
1734
1735 msg_typedef s 7; LP.add_typedef_root s;
1736 TypedefIdent (s, i1)
1737
1738 (* xx const *)
1739 | (TIdent (s, i1)::(Tconst _|Tvolatile _|Trestrict _)::_ , _ )
1740 when not_struct_enum before
1741 && ok_typedef s
1742 (* && !LP._lexer_hint = Some LP.ParameterDeclaration *)
1743 ->
1744
1745 msg_typedef s 8; LP.add_typedef_root s;
1746 TypedefIdent (s, i1)
1747
1748
1749 (* xx * const *)
1750 | (TIdent (s, i1)::ptr::(Tconst _ | Tvolatile _|Trestrict _)::_ , _ )
1751 when pointer ptr && not_struct_enum before
1752 && ok_typedef s
1753 ->
1754 (* && !LP._lexer_hint = Some LP.ParameterDeclaration *)
1755
1756 msg_typedef s 9; LP.add_typedef_root s;
1757 TypedefIdent (s, i1)
1758
1759
1760 (* ( const xx) *)
1761 | (TIdent (s, i1)::TCPar _::_, (Tconst _ | Tvolatile _|Trestrict _)::TOPar _::_) when
1762 ok_typedef s ->
1763 msg_typedef s 10; LP.add_typedef_root s;
1764 TypedefIdent (s, i1)
1765
1766
1767
1768 (* ( xx ) [sizeof, ~] *)
1769 | (TIdent (s, i1)::TCPar _::(Tsizeof _|TTilde _)::_ , TOPar _::_ )
1770 when not_struct_enum before
1771 && ok_typedef s
1772 ->
1773 msg_typedef s 11; LP.add_typedef_root s;
1774 TypedefIdent (s, i1)
1775
1776 (* [(,] xx [ AND parameterdeclaration *)
1777 | (TIdent (s, i1)::TOCro _::_, (TComma _ |TOPar _)::_)
1778 when (LP.current_context() =*= LP.InParameter)
1779 && ok_typedef s
1780 ->
1781 msg_typedef s 12; LP.add_typedef_root s;
1782 TypedefIdent (s, i1)
1783
1784 (*------------------------------------------------------------*)
1785 (* if 'x*y' maybe an expr, maybe just a classic multiplication *)
1786 (* but if have a '=', or ',' I think not *)
1787 (*------------------------------------------------------------*)
1788
1789 (* static xx * yy *)
1790 | (TIdent (s, i1)::ptr::TIdent (s2, i2)::_ ,
1791 (Tregister _|Tstatic _ |Tvolatile _|Tconst _|Trestrict _)::_) when
1792 pointer ptr && ok_typedef s
1793 ->
1794 msg_typedef s 13; LP.add_typedef_root s;
1795 TypedefIdent (s, i1)
1796
1797 (* TODO xx * yy ; AND in start of compound element *)
1798
1799
1800 (* xx * yy, AND in paramdecl *)
1801 | (TIdent (s, i1)::ptr::TIdent (s2, i2)::TComma _::_ , _)
1802 when not_struct_enum before && (LP.current_context() =*= LP.InParameter)
1803 && pointer ptr && ok_typedef s
1804 ->
1805
1806 msg_typedef s 14; LP.add_typedef_root s;
1807 TypedefIdent (s, i1)
1808
1809
1810 (* xx * yy ; AND in Toplevel, except when have = before *)
1811 | (TIdent (s, i1)::TMul _::TIdent (s2, i2)::TPtVirg _::_ , TEq _::_) ->
1812 TIdent (s, i1)
1813 | (TIdent (s, i1)::ptr::TIdent (s2, i2)::TPtVirg _::_ , _)
1814 when not_struct_enum before && pointer ptr &&
1815 (LP.is_top_or_struct (LP.current_context ()))
1816 ->
1817 msg_typedef s 15; LP.add_typedef_root s;
1818 TypedefIdent (s, i1)
1819
1820 (* xx * yy , AND in Toplevel *)
1821 | (TIdent (s, i1)::ptr::TIdent (s2, i2)::TComma _::_ , _)
1822 when not_struct_enum before && (LP.current_context () =*= LP.InTopLevel)
1823 && ok_typedef s && pointer ptr
1824 ->
1825
1826 msg_typedef s 16; LP.add_typedef_root s;
1827 TypedefIdent (s, i1)
1828
1829 (* xx * yy ( AND in Toplevel *)
1830 | (TIdent (s, i1)::ptr::TIdent (s2, i2)::TOPar _::_ , _)
1831 when not_struct_enum before
1832 && (LP.is_top_or_struct (LP.current_context ()))
1833 && ok_typedef s && pointer ptr
1834 ->
1835 msg_typedef s 17; LP.add_typedef_root s;
1836 TypedefIdent (s, i1)
1837
1838 (* xx * yy [ *)
1839 (* todo? enough ? cos in struct def we can have some expression ! *)
1840 | (TIdent (s, i1)::ptr::TIdent (s2, i2)::TOCro _::_ , _)
1841 when not_struct_enum before &&
1842 (LP.is_top_or_struct (LP.current_context ()))
1843 && ok_typedef s && pointer ptr
1844 ->
1845 msg_typedef s 18; LP.add_typedef_root s;
1846 TypedefIdent (s, i1)
1847
1848 (* u16: 10; in struct *)
1849 | (TIdent (s, i1)::TDotDot _::_ , (TOBrace _ | TPtVirg _)::_)
1850 when (LP.is_top_or_struct (LP.current_context ()))
1851 && ok_typedef s
1852 ->
1853 msg_typedef s 19; LP.add_typedef_root s;
1854 TypedefIdent (s, i1)
1855
1856
1857 (* why need TOPar condition as stated in preceding rule ? really needed ? *)
1858 (* YES cos at toplevel can have some expression !! for instance when *)
1859 (* enter in the dimension of an array *)
1860 (*
1861 | (TIdent s::TMul::TIdent s2::_ , _)
1862 when (take_safe 1 !passed_tok <> [Tstruct] &&
1863 (take_safe 1 !passed_tok <> [Tenum]))
1864 &&
1865 !LP._lexer_hint = Some LP.Toplevel ->
1866 msg_typedef s 20; LP.add_typedef_root s;
1867 TypedefIdent s
1868 *)
1869
1870 (* xx * yy = *)
1871 | (TIdent (s, i1)::ptr::TIdent (s2, i2)::TEq _::_ , _)
1872 when not_struct_enum before
1873 && ok_typedef s && pointer ptr
1874 ->
1875 msg_typedef s 21; LP.add_typedef_root s;
1876 TypedefIdent (s, i1)
1877
1878
1879 (* xx * yy) AND in paramdecl *)
1880 | (TIdent (s, i1)::ptr::TIdent (s2, i2)::TCPar _::_ , _)
1881 when not_struct_enum before && (LP.current_context () =*= LP.InParameter)
1882 && ok_typedef s && pointer ptr
1883 ->
1884 msg_typedef s 22; LP.add_typedef_root s;
1885 TypedefIdent (s, i1)
1886
1887
1888 (* xx * yy; *) (* wrong ? *)
1889 | (TIdent (s, i1)::ptr::TIdent (s2, i2)::TPtVirg _::_ ,
1890 (TOBrace _| TPtVirg _)::_) when not_struct_enum before
1891 && ok_typedef s & pointer ptr
1892 ->
1893 msg_typedef s 23; LP.add_typedef_root s;
1894 msg_maybe_dangereous_typedef s;
1895 TypedefIdent (s, i1)
1896
1897
1898 (* xx * yy, and ';' before xx *) (* wrong ? *)
1899 | (TIdent (s, i1)::ptr::TIdent (s2, i2)::TComma _::_ ,
1900 (TOBrace _| TPtVirg _)::_) when
1901 ok_typedef s && pointer ptr
1902 ->
1903 msg_typedef s 24; LP.add_typedef_root s;
1904 TypedefIdent (s, i1)
1905
1906
1907 (* xx_t * yy *)
1908 | (TIdent (s, i1)::ptr::TIdent (s2, i2)::_ , _)
1909 when s ==~ regexp_typedef && not_struct_enum before
1910 (* struct user_info_t sometimes *)
1911 && ok_typedef s && pointer ptr
1912 ->
1913 msg_typedef s 25; LP.add_typedef_root s;
1914 TypedefIdent (s, i1)
1915
1916 (* xx ** yy *) (* wrong ? *)
1917 | (TIdent (s, i1)::TMul _::TMul _::TIdent (s2, i2)::_ , _)
1918 when not_struct_enum before
1919 (* && !LP._lexer_hint = Some LP.ParameterDeclaration *)
1920 && ok_typedef s
1921 ->
1922 msg_typedef s 26; LP.add_typedef_root s;
1923 TypedefIdent (s, i1)
1924
1925 (* xx *** yy *)
1926 | (TIdent (s, i1)::TMul _::TMul _::TMul _::TIdent (s2, i2)::_ , _)
1927 when not_struct_enum before
1928 && ok_typedef s
1929 (* && !LP._lexer_hint = Some LP.ParameterDeclaration *)
1930 ->
1931 msg_typedef s 27; LP.add_typedef_root s;
1932 TypedefIdent (s, i1)
1933
1934 (* xx ** ) *)
1935 | (TIdent (s, i1)::TMul _::TMul _::TCPar _::_ , _)
1936 when not_struct_enum before
1937 (* && !LP._lexer_hint = Some LP.ParameterDeclaration *)
1938 && ok_typedef s
1939 ->
1940 msg_typedef s 28; LP.add_typedef_root s;
1941 TypedefIdent (s, i1)
1942
1943
1944
1945 (* ----------------------------------- *)
1946 (* old: why not do like for other rules and start with TIdent ?
1947 * why do TOPar :: TIdent :: ..., _ and not TIdent :: ..., TOPAr::_ ?
1948 * new: prefer now start with TIdent because otherwise the add_typedef_root
1949 * may have no effect if in second pass or if have disable the add_typedef.
1950 *)
1951
1952 (* (xx) yy *)
1953 | (TIdent (s, i1)::TCPar i2::(TIdent (_,i3)|TInt (_,i3))::_ ,
1954 (TOPar info)::x::_)
1955 when not (TH.is_stuff_taking_parenthized x) &&
1956 Ast_c.line_of_info i2 =|= Ast_c.line_of_info i3
1957 && ok_typedef s
1958 ->
1959
1960 msg_typedef s 29; LP.add_typedef_root s;
1961 (*TOPar info*)
1962 TypedefIdent (s, i1)
1963
1964
1965 (* (xx) ( yy)
1966 * but false positif: typedef int (xxx_t)(...), so do specialisation below.
1967 *)
1968 (*
1969 | (TIdent (s, i1)::TCPar _::TOPar _::_ , (TOPar info)::x::_)
1970 when not (TH.is_stuff_taking_parenthized x)
1971 && ok_typedef s
1972 ->
1973 msg_typedef s 30; LP.add_typedef_root s;
1974 (* TOPar info *)
1975 TypedefIdent (s, i1)
1976 *)
1977 (* special case: = (xx) ( yy) *)
1978 | (TIdent (s, i1)::TCPar _::TOPar _::_ ,
1979 (TOPar info)::(TEq _ |TEqEq _)::_)
1980 when ok_typedef s
1981 ->
1982 msg_typedef s 31; LP.add_typedef_root s;
1983 (* TOPar info *)
1984 TypedefIdent (s, i1)
1985
1986
1987 (* (xx * ) yy *)
1988 | (TIdent (s, i1)::ptr::TCPar _::TIdent (s2, i2)::_ , (TOPar info)::_)
1989 when ok_typedef s && pointer ptr
1990 ->
1991 msg_typedef s 32; LP.add_typedef_root s;
1992 (*TOPar info*)
1993 TypedefIdent (s,i1)
1994
1995
1996 (* (xx){ ... } constructor *)
1997 | (TIdent (s, i1)::TCPar _::TOBrace _::_ , TOPar _::x::_)
1998 when (*s ==~ regexp_typedef && *) not (TH.is_stuff_taking_parenthized x)
1999 && ok_typedef s
2000 ->
2001 msg_typedef s 33; LP.add_typedef_root s;
2002 TypedefIdent (s, i1)
2003
2004
2005 (* can have sizeof on expression
2006 | (Tsizeof::TOPar::TIdent s::TCPar::_, _) ->
2007 msg_typedef s; LP.add_typedef_root s;
2008 Tsizeof
2009 *)
2010
2011
2012 (* ----------------------------------- *)
2013 (* x ( *y )(params), function pointer *)
2014 | (TIdent (s, i1)::TOPar _::TMul _::TIdent _::TCPar _::TOPar _::_, _)
2015 when not_struct_enum before
2016 && ok_typedef s
2017 ->
2018 msg_typedef s 34; LP.add_typedef_root s;
2019 TypedefIdent (s, i1)
2020
2021 (* x* ( *y )(params), function pointer 2 *)
2022 | (TIdent (s, i1)::TMul _::TOPar _::TMul _::TIdent _::TCPar _::TOPar _::_, _)
2023 when not_struct_enum before
2024 && ok_typedef s
2025 ->
2026 msg_typedef s 35; LP.add_typedef_root s;
2027 TypedefIdent (s, i1)
2028
2029
2030 (*-------------------------------------------------------------*)
2031 (* CPP *)
2032 (*-------------------------------------------------------------*)
2033 | ((TIfdef (_,ii) |TIfdefelse (_,ii) |TIfdefelif (_,ii) |TEndif (_,ii) |
2034 TIfdefBool (_,_,ii)|TIfdefMisc(_,_,ii)|TIfdefVersion(_,_,ii))
2035 as x)
2036 ::_, _
2037 ->
2038 (*
2039 if not !Flag_parsing_c.ifdef_to_if
2040 then TCommentCpp (Ast_c.CppDirective, ii)
2041 else
2042 *)
2043 (* not !LP._lexer_hint.toplevel *)
2044 if !Flag_parsing_c.ifdef_directive_passing
2045 || (pass >= 2)
2046 then begin
2047
2048 if (LP.current_context () =*= LP.InInitializer)
2049 then begin
2050 pr2_cpp "In Initializer passing"; (* cheat: dont count in stat *)
2051 incr Stat.nIfdefInitializer;
2052 end else begin
2053 pr2_cpp("IFDEF: or related inside function. I treat it as comment");
2054 incr Stat.nIfdefPassing;
2055 end;
2056 TCommentCpp (Token_c.CppDirective, ii)
2057 end
2058 else x
2059
2060 | (TUndef (ii) as x)::_, _
2061 ->
2062 if (pass >= 2)
2063 then begin
2064 pr2_cpp("UNDEF: I treat it as comment");
2065 TCommentCpp (Token_c.CppDirective, ii)
2066 end
2067 else x
2068
2069 | (TCppDirectiveOther (ii) as x)::_, _
2070 ->
2071 if (pass >= 2)
2072 then begin
2073 pr2_cpp ("OTHER directive: I treat it as comment");
2074 TCommentCpp (Token_c.CppDirective, ii)
2075 end
2076 else x
2077
2078 (* If ident contain a for_each, then certainly a macro. But to be
2079 * sure should look if there is a '{' after the ')', but it requires
2080 * to count the '('. Because this can be expensive, we do that only
2081 * when the token contains "for_each".
2082 *)
2083 | (TIdent (s, i1)::TOPar _::rest, _)
2084 when not (LP.current_context () =*= LP.InTopLevel)
2085 (* otherwise a function such as static void loopback_enable(int i) {
2086 * will be considered as a loop
2087 *)
2088 ->
2089
2090 if s ==~ regexp_foreach &&
2091 is_really_foreach (Common.take_safe forLOOKAHEAD rest)
2092
2093 then begin
2094 msg_foreach s;
2095 TMacroIterator (s, i1)
2096 end
2097 else TIdent (s, i1)
2098
2099 (*-------------------------------------------------------------*)
2100 | v::xs, _ -> v
2101 | _ -> raise Impossible
2102
2103 let lookahead ~pass a b =
2104 Common.profile_code "C parsing.lookahead" (fun () -> lookahead2 ~pass a b)
2105
2106