Coccinelle release 1.0.0-rc15
[bpt/coccinelle.git] / parsing_c / ast_c.ml
1 (* Yoann Padioleau
2 *
3 * Copyright (C) 2010, University of Copenhagen DIKU and INRIA.
4 * Copyright (C) 2002, 2006, 2007, 2008, 2009 Yoann Padioleau
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 open Common
16
17 (*****************************************************************************)
18 (* The AST C related types *)
19 (*****************************************************************************)
20 (*
21 * Some stuff are tagged semantic: which means that they are computed
22 * after parsing.
23 *
24 * This means that some elements in this AST are present only if
25 * some annotation/transformation has been done on the original AST returned
26 * by the parser. Cf type_annotater, comment_annotater, cpp_ast_c, etc.
27 *)
28
29
30 (* ------------------------------------------------------------------------- *)
31 (* Token/info *)
32 (* ------------------------------------------------------------------------- *)
33
34 (* To allow some transformations over the AST, we keep as much information
35 * as possible in the AST such as the tokens content and their locations.
36 * Those info are called 'info' (how original) and can be tagged.
37 * For instance one tag may say that the unparser should remove this token.
38 *
39 * Update: Now I use a ref! in those 'info' so take care.
40 * That means that modifications of the info of tokens can have
41 * an effect on the info stored in the ast (which is sometimes
42 * convenient, cf unparse_c.ml or comment_annotater_c.ml)
43 *
44 * convention: I often use 'ii' for the name of a list of info.
45 *
46 * Sometimes we want to add someting at the beginning or at the end
47 * of a construct. For 'function' and 'decl' we want to add something
48 * to their left and for 'if' 'while' et 'for' and so on at their right.
49 * We want some kinds of "virtual placeholders" that represent the start or
50 * end of a construct. We use fakeInfo for that purpose.
51 * To identify those cases I have added a fakestart/fakeend comment.
52 *
53 * cocci: Each token will be decorated in the future by the mcodekind
54 * of cocci. It is the job of the pretty printer to look at this
55 * information and decide to print or not the token (and also the
56 * pending '+' associated sometimes with the token).
57 *
58 * The first time that we parse the original C file, the mcodekind is
59 * empty, or more precisely all is tagged as a CONTEXT with NOTHING
60 * associated. This is what I call a "clean" expr/statement/....
61 *
62 * Each token will also be decorated in the future with an environment,
63 * because the pending '+' may contain metavariables that refer to some
64 * C code.
65 *
66 *)
67
68 (* for unparser: *)
69
70 type posl = int * int (* line-col, for MetaPosValList, for position variables *)
71 (* with sexp *)
72
73 (* the virtual position is set in Parsing_hacks.insert_virtual_positions *)
74 type virtual_position = Common.parse_info * int (* character offset *)
75 (* with sexp *)
76
77 type parse_info =
78 (* Present both in ast and list of tokens *)
79 | OriginTok of Common.parse_info
80 (* Present only in ast and generated after parsing. Used mainly
81 * by Julia, to add stuff at virtual places, beginning of func or decl *)
82 | FakeTok of string * virtual_position
83 (* Present both in ast and list of tokens. *)
84 | ExpandedTok of Common.parse_info * virtual_position
85
86 (* Present neither in ast nor in list of tokens
87 * but only in the '+' of the mcode of some tokens. Those kind of tokens
88 * are used to be able to use '=' to compare big ast portions.
89 *)
90 | AbstractLineTok of Common.parse_info (* local to the abstracted thing *)
91 (* with sexp *)
92
93 type info = {
94 pinfo : parse_info;
95
96 (* this cocci_tag can be changed, which is how we can express some program
97 * transformations by tagging the tokens involved in this transformation.
98 *)
99 cocci_tag: (Ast_cocci.mcodekind * metavars_binding list) option ref;
100 (* set in comment_annotater_c.ml *)
101 comments_tag: comments_around ref;
102
103 (* todo? token_info : sometimes useful to know what token it was *)
104 }
105 and il = info list
106
107 (* wrap2 is like wrap, except that I use it often for separator such
108 * as ','. In that case the info is associated to the argument that
109 * follows, so in 'a,b' I will have in the list [(a,[]); (b,[','])].
110 *
111 * wrap3 is like wrap, except that I use it in case sometimes it
112 * will be empty because the info will be included in a nested
113 * entity (e.g. for Ident in expr because it's inlined in the name)
114 * so user should never assume List.length wrap3 > 0.
115 *)
116 and 'a wrap = 'a * il
117 and 'a wrap2 = 'a * il
118 and 'a wrap3 = 'a * il (* * evotype*)
119
120 (* ------------------------------------------------------------------------- *)
121 (* Name *)
122 (* ------------------------------------------------------------------------- *)
123
124 (* was called 'ident' before, but 'name' is I think better
125 * as concatenated strings can be used not only for identifiers and for
126 * declarators, but also for fields, for labels, etc.
127 *
128 * Note: because now the info is embeded in the name, the info for
129 * expression like Ident, or types like Typename, are not anymore
130 * stored in the expression or type. Hence if you assume this,
131 * which was true before, you are now wrong. So never write code like
132 * let (unwrape,_), ii = e and use 'ii' believing it contains
133 * the local ii to e. If you want to do that, use the appropiate
134 * wrapper get_local_ii_of_expr_inlining_ii_of_name.
135 *)
136 and name =
137 | RegularName of string wrap
138 | CppConcatenatedName of (string wrap) wrap2 (* the ## separators *) list
139 (* normally only used inside list of things, as in parameters or arguments
140 * in which case, cf cpp-manual, it has a special meaning *)
141 | CppVariadicName of string wrap (* ## s *)
142 | CppIdentBuilder of string wrap (* s ( ) *) *
143 ((string wrap) wrap2 list) (* arguments *)
144
145
146 (* ------------------------------------------------------------------------- *)
147 (* C Type *)
148 (* ------------------------------------------------------------------------- *)
149 (* Could have more precise type in fullType, in expression, etc, but
150 * it requires to do too much things in parsing such as checking no
151 * conflicting structname, computing value, etc. Better to separate
152 * concern. So I put '=>' to mean what we would really like. In fact
153 * what we really like is defining another fullType, expression, etc
154 * from scratch, because many stuff are just sugar.
155 *
156 * invariant: Array and FunctionType have also typeQualifier but they
157 * dont have sense. I put this to factorise some code. If you look in
158 * the grammar, you see that we can never specify const for the array
159 * himself (but we can do it for pointer) or function, we always
160 * have in the action rule of the grammar a { (nQ, FunctionType ...) }.
161 *
162 *
163 * Because of ExprStatement, we can have more 'new scope' events, but
164 * rare I think. For instance with 'array of constExpression' there can
165 * have an exprStatement and a new (local) struct defined. Same for
166 * Constructor.
167 *
168 *)
169
170
171 and fullType = typeQualifier * typeC
172 and typeC = typeCbis wrap (* todo reput wrap3 *)
173
174 and typeCbis =
175 NoType (* for c++ only *)
176 | BaseType of baseType
177
178 | Pointer of fullType
179 | Array of constExpression option * fullType
180 | FunctionType of functionType
181
182 | Enum of string option * enumType
183 | StructUnion of structUnion * string option * structType (* new scope *)
184
185 | EnumName of string
186 | StructUnionName of structUnion * string
187
188 | TypeName of name * fullType option (* semantic: filled later *)
189
190 | ParenType of fullType (* for unparser: *)
191
192 (* gccext: TypeOfType below may seems useless; Why declare a
193 * __typeof__(int) x; ?
194 * When used with macros, it allows to fix a problem of C which
195 * is that type declaration can be spread around the ident. Indeed it
196 * may be difficult to have a macro such as
197 * '#define macro(type, ident) type ident;'
198 * because when you want to do a
199 * macro(char[256], x),
200 * then it will generate invalid code, but with a
201 * '#define macro(type, ident) __typeof(type) ident;'
202 * it will work.
203 *)
204 | TypeOfExpr of expression
205 | TypeOfType of fullType
206
207 (* cppext: IfdefType TODO *)
208
209 (* -------------------------------------- *)
210 and baseType = Void
211 | IntType of intType
212 | FloatType of floatType
213 | SizeType
214 | SSizeType
215 | PtrDiffType
216
217 (* stdC: type section
218 * add a | SizeT ?
219 * note: char and signed char are semantically different!!
220 *)
221 and intType = CChar (* obsolete? | CWchar *)
222 | Si of signed
223
224 and signed = sign * base
225 and base = CChar2 | CShort | CInt | CLong | CLongLong (* gccext: *)
226 and sign = Signed | UnSigned
227
228 and floatType = CFloat | CDouble | CLongDouble
229
230
231 (* -------------------------------------- *)
232 and structUnion = Struct | Union
233 and structType = field list
234 and field =
235 | DeclarationField of field_declaration
236 (* gccext: *)
237 | EmptyField of info
238
239 (* cppext: *)
240 | MacroDeclField of (string * argument wrap2 list)
241 wrap (* optional ';'*)
242
243 (* cppext: *)
244 | CppDirectiveStruct of cpp_directive
245 | IfdefStruct of ifdef_directive (* * field list list *)
246
247
248 (* before unparser, I didn't have a FieldDeclList but just a Field. *)
249 and field_declaration =
250 | FieldDeclList of fieldkind wrap2 list (* , *) wrap (* ; *)
251
252 (* At first I thought that a bitfield could be only Signed/Unsigned.
253 * But it seems that gcc allow char i:4. C rule must say that you
254 * can cast into int so enum too, ...
255 *)
256 and fieldkind =
257 | Simple of name option * fullType
258 | BitField of name option * fullType *
259 info (* : *) * constExpression
260 (* fullType => BitFieldInt | BitFieldUnsigned *)
261
262
263 (* -------------------------------------- *)
264 and enumType = oneEnumType wrap2 (* , *) list
265 (* => string * int list *)
266
267 and oneEnumType = name * (info (* = *) * constExpression) option
268
269 (* -------------------------------------- *)
270 (* return * (params * has "...") *)
271 and functionType = fullType * (parameterType wrap2 list * bool wrap)
272 and parameterType =
273 { p_namei: name option;
274 p_register: bool wrap;
275 p_type: fullType;
276 }
277 (* => (bool (register) * fullType) list * bool *)
278
279
280 and typeQualifier = typeQualifierbis wrap
281 and typeQualifierbis = {const: bool; volatile: bool}
282
283 (* gccext: cppext: *)
284 and attribute = attributebis wrap
285 and attributebis =
286 | Attribute of string
287
288 (* ------------------------------------------------------------------------- *)
289 (* C expression *)
290 (* ------------------------------------------------------------------------- *)
291 and expression = (expressionbis * exp_info ref (* semantic: *)) wrap3
292 and exp_info = exp_type option * test
293 and exp_type = fullType (* Type_c.completed_and_simplified *) * local
294 and local = LocalVar of parse_info | StaticLocalVar of parse_info
295 | NotLocalVar (* cocci: *)
296 and test = Test | NotTest (* cocci: *)
297
298 and expressionbis =
299
300 (* Ident can be a enumeration constant, a simple variable, a name of a func.
301 * With cppext, Ident can also be the name of a macro. Sparse says
302 * "an identifier with a meaning is a symbol" *)
303 | Ident of name (* todo? more semantic info such as LocalFunc *)
304
305 | Constant of constant
306 | FunCall of expression * argument wrap2 (* , *) list
307 (* gccext: x ? /* empty */ : y <=> x ? x : y; hence the 'option' below *)
308 | CondExpr of expression * expression option * expression
309
310 (* should be considered as statements, bad C langage *)
311 | Sequence of expression * expression
312 | Assignment of expression * assignOp * expression
313
314
315 | Postfix of expression * fixOp
316 | Infix of expression * fixOp
317
318 | Unary of expression * unaryOp
319 | Binary of expression * binaryOp * expression
320
321 | ArrayAccess of expression * expression
322
323 (* field ident access *)
324 | RecordAccess of expression * name
325 | RecordPtAccess of expression * name
326 (* redundant normally, could replace it by DeRef RecordAcces *)
327
328 | SizeOfExpr of expression
329 | SizeOfType of fullType
330 | Cast of fullType * expression
331
332 (* gccext: *)
333 | StatementExpr of compound wrap (* ( ) new scope *)
334 | Constructor of fullType * initialiser
335
336 (* for unparser: *)
337 | ParenExpr of expression
338
339 (* for C++: *)
340 | New of argument
341 | Delete of expression
342
343 (* cppext: IfdefExpr TODO *)
344
345 (* cppext: normally just expression *)
346 and argument = (expression, weird_argument) Common.either
347 and weird_argument =
348 | ArgType of parameterType
349 | ArgAction of action_macro
350 and action_macro =
351 (* todo: ArgStatement of statement, possibly have ghost token *)
352 | ActMisc of il
353
354
355 (* I put string for Int and Float because int would not be enough because
356 * OCaml int are 31 bits. So simpler to do string. Same reason to have
357 * string instead of int list for the String case.
358 *
359 * note: -2 is not a constant, it is the unary operator '-'
360 * applied to constant 2. So the string must represent a positive
361 * integer only. *)
362
363 and constant =
364 | String of (string * isWchar)
365 | MultiString of string list (* can contain MacroString, todo: more info *)
366 | Char of (string * isWchar) (* normally it is equivalent to Int *)
367 | Int of (string * intType)
368 | Float of (string * floatType)
369
370 and isWchar = IsWchar | IsChar
371
372
373 and unaryOp = GetRef | DeRef | UnPlus | UnMinus | Tilde | Not
374 | GetRefLabel (* gccext: GetRefLabel, via &&label notation *)
375 and assignOp = SimpleAssign | OpAssign of arithOp
376 and fixOp = Dec | Inc
377
378 and binaryOp = Arith of arithOp | Logical of logicalOp
379
380 and arithOp =
381 | Plus | Minus | Mul | Div | Mod
382 | DecLeft | DecRight
383 | And | Or | Xor
384
385 and logicalOp =
386 | Inf | Sup | InfEq | SupEq
387 | Eq | NotEq
388 | AndLog | OrLog
389
390 and constExpression = expression (* => int *)
391
392 (* ------------------------------------------------------------------------- *)
393 (* C statement *)
394 (* ------------------------------------------------------------------------- *)
395 (* note: that assignement is not a statement but an expression;
396 * wonderful C langage.
397 *
398 * note: I use 'and' for type definition cos gccext allow statement as
399 * expression, so need mutual recursive type definition.
400 *
401 *)
402
403 and statement = statementbis wrap3
404 and statementbis =
405 | Labeled of labeled
406 | Compound of compound (* new scope *)
407 | ExprStatement of exprStatement
408 | Selection of selection (* have fakeend *)
409 | Iteration of iteration (* have fakeend *)
410 | Jump of jump
411
412 (* simplify cocci: only at the beginning of a compound normally *)
413 | Decl of declaration
414
415 (* gccext: *)
416 | Asm of asmbody
417 | NestedFunc of definition
418
419 (* cppext: *)
420 | MacroStmt
421
422
423
424 and labeled = Label of name * statement
425 | Case of expression * statement
426 | CaseRange of expression * expression * statement (* gccext: *)
427 | Default of statement
428
429 (* cppext:
430 * old: compound = (declaration list * statement list)
431 * old: (declaration, statement) either list
432 * Simplify cocci to just have statement list, by integrating Decl in stmt.
433 *
434 * update: now introduce also the _sequencable to allow ifdef in the middle.
435 * Indeed, I now allow ifdefs in the ast but they must be only between
436 * "sequencable" elements. They can be put in a type only if this type
437 * is used in a list, like at the toplevel, used in a 'toplevel list',
438 * or inside a compound, used in a 'statement list'. I must not allow
439 * ifdef anywhere. For instance I can not make ifdef a statement
440 * cos some instruction like If accept only one statement and the
441 * ifdef directive must not take the place of a legitimate instruction.
442 * We had a similar phenomena in SmPL where we have the notion
443 * of statement and sequencable statement too. Once you have
444 * such a type of sequencable thing, then s/xx list/xx_sequencable list/
445 * and introduce the ifdef.
446 *
447 * update: those ifdefs are either passed, or present in the AST but in
448 * a flat form. To structure those flat ifdefs you have to run
449 * a transformation that will put in a tree the statements inside
450 * ifdefs branches. Cf cpp_ast_c.ml. This is for instance the difference
451 * between a IfdefStmt (flat) and IfdefStmt2 (tree structured).
452 *
453 *)
454 and compound = statement_sequencable list
455
456 (* cppext: easier to put at statement_list level than statement level *)
457 and statement_sequencable =
458 | StmtElem of statement
459
460 (* cppext: *)
461 | CppDirectiveStmt of cpp_directive
462 | IfdefStmt of ifdef_directive
463
464 (* this will be build in cpp_ast_c from the previous flat IfdefStmt *)
465 | IfdefStmt2 of ifdef_directive list * (statement_sequencable list) list
466
467 and exprStatement = expression option
468
469 and declOrExpr = ForDecl of declaration | ForExp of expression option wrap
470
471 (* for Switch, need check that all elements in the compound start
472 * with a case:, otherwise unreachable code.
473 *)
474 and selection =
475 | If of expression * statement * statement
476 | Switch of expression * statement
477
478
479 and iteration =
480 | While of expression * statement
481 | DoWhile of statement * expression
482 | For of declOrExpr * exprStatement wrap * exprStatement wrap *
483 statement
484 (* cppext: *)
485 | MacroIteration of string * argument wrap2 list * statement
486
487 and jump = Goto of name
488 | Continue | Break
489 | Return | ReturnExpr of expression
490 | GotoComputed of expression (* gccext: goto *exp ';' *)
491
492
493 (* gccext: *)
494 and asmbody = il (* string list *) * colon wrap (* : *) list
495 and colon = Colon of colon_option wrap2 list
496 and colon_option = colon_option_bis wrap
497 and colon_option_bis = ColonMisc | ColonExpr of expression
498
499
500 (* ------------------------------------------------------------------------- *)
501 (* Declaration *)
502 (* ------------------------------------------------------------------------- *)
503 (* (string * ...) option cos can have empty declaration or struct tag
504 * declaration.
505 *
506 * Before I had a Typedef constructor, but why make this special case and not
507 * have StructDef, EnumDef, ... so that 'struct t {...} v' will generate 2
508 * declarations ? So I try to generalise and not have Typedef either. This
509 * requires more work in parsing. Better to separate concern.
510 *
511 * Before the need for unparser, I didn't have a DeclList but just a Decl.
512 *
513 * I am not sure what it means to declare a prototype inline, but gcc
514 * accepts it.
515 *)
516
517 and declaration =
518 | DeclList of onedecl wrap2 (* , *) list wrap (* ; fakestart sto *)
519 (* cppext: *)
520 (* bool is true if there is a ; at the end *)
521 | MacroDecl of (string * argument wrap2 list * bool) wrap (* fakestart *)
522 | MacroDeclInit of
523 (string * argument wrap2 list * initialiser) wrap (* fakestart *)
524
525 and onedecl =
526 { v_namei: (name * v_init) option;
527 v_type: fullType;
528 (* semantic: set in type annotated and used in cocci_vs_c
529 * when we transform some initialisation into affectation
530 *)
531 v_type_bis: fullType (* Type_c.completed_and_simplified *) option ref;
532 v_storage: storage;
533 v_local: local_decl; (* cocci: *)
534 v_attr: attribute list; (* gccext: *)
535 }
536 and v_init =
537 NoInit | ValInit of info * initialiser
538 | ConstrInit of argument wrap2 (* , *) list wrap
539 and storage = storagebis * bool (* gccext: inline or not *)
540 and storagebis = NoSto | StoTypedef | Sto of storageClass
541 and storageClass = Auto | Static | Register | Extern
542
543 and local_decl = LocalDecl | NotLocalDecl
544
545 (* fullType is the type used if the type should be converted to
546 an assignment. It can be adjusted in the type annotation
547 phase when typedef information is availalble *)
548 and initialiser = initialiserbis wrap
549 and initialiserbis =
550 | InitExpr of expression
551 | InitList of initialiser wrap2 (* , *) list
552 (* gccext: *)
553 | InitDesignators of designator list * initialiser
554 | InitFieldOld of string * initialiser
555 | InitIndexOld of expression * initialiser
556
557 (* ex: [2].y = x, or .y[2] or .y.x. They can be nested *)
558 and designator = designatorbis wrap
559 and designatorbis =
560 | DesignatorField of string
561 | DesignatorIndex of expression
562 | DesignatorRange of expression * expression
563
564 (* ------------------------------------------------------------------------- *)
565 (* Function definition *)
566 (* ------------------------------------------------------------------------- *)
567 (* Normally we should define another type functionType2 because there
568 * are more restrictions on what can define a function than a pointer
569 * function. For instance a function declaration can omit the name of the
570 * parameter whereas a function definition can not. But, in some cases such
571 * as 'f(void) {', there is no name too, so I simplified and reused the
572 * same functionType type for both declaration and function definition.
573 *
574 * Also old style C does not have type in the parameter, so again simpler
575 * to abuse the functionType and allow missing type.
576 *)
577 and definition = definitionbis wrap (* ( ) { } fakestart sto *)
578 and definitionbis =
579 { f_name: name;
580 f_type: functionType; (* less? a functionType2 ? *)
581 f_storage: storage;
582 f_body: compound;
583 f_attr: attribute list; (* gccext: *)
584 f_old_c_style: declaration list option;
585 }
586 (* cppext: IfdefFunHeader TODO *)
587
588 (* ------------------------------------------------------------------------- *)
589 (* cppext: cpp directives, #ifdef, #define and #include body *)
590 (* ------------------------------------------------------------------------- *)
591 and cpp_directive =
592 | Define of define
593 | Include of includ
594 | PragmaAndCo of il
595 (*| Ifdef ? no, ifdefs are handled differently, cf ifdef_directive below *)
596
597 and define = string wrap (* #define s eol *) * (define_kind * define_val)
598 and define_kind =
599 | DefineVar
600 | DefineFunc of ((string wrap) wrap2 list) wrap (* () *)
601 | Undef
602 and define_val =
603 (* most common case; e.g. to define int constant *)
604 | DefineExpr of expression
605
606 | DefineStmt of statement
607 | DefineType of fullType
608 | DefineDoWhileZero of (statement * expression) wrap (* do { } while(0) *)
609
610 | DefineFunction of definition
611 | DefineInit of initialiser (* in practice only { } with possible ',' *)
612
613 (* TODO DefineMulti of define_val list *)
614
615 | DefineText of string wrap
616 | DefineEmpty
617
618 | DefineTodo
619
620
621
622 and includ =
623 { i_include: inc_file wrap; (* #include s *)
624 (* cocci: computed in ? *)
625 i_rel_pos: include_rel_pos option ref;
626 (* cocci: cf -test incl *)
627 i_is_in_ifdef: bool;
628 (* cf cpp_ast_c.ml. set to None at parsing time. *)
629 i_content: (Common.filename (* full path *) * program) option;
630 }
631 and inc_file =
632 | Local of inc_elem list
633 | NonLocal of inc_elem list
634 | Weird of string (* ex: #include SYSTEM_H *)
635 and inc_elem = string
636
637 (* cocci: to tag the first of #include <xx/> and last of #include <yy/>
638 *
639 * The first_of and last_of store the list of prefixes that was
640 * introduced by the include. On #include <a/b/x>, if the include was
641 * the first in the file, it would give in first_of the following
642 * prefixes a/b/c; a/b/; a/ ; <empty>
643 *
644 * This is set after parsing, in cocci.ml, in update_rel_pos.
645 *)
646 and include_rel_pos = {
647 first_of : string list list;
648 last_of : string list list;
649 }
650
651
652
653 (* todo? to specialize if someone need more info *)
654 and ifdef_directive = (* or and 'a ifdefed = 'a list wrap *)
655 | IfdefDirective of (ifdefkind * matching_tag) wrap
656 and ifdefkind =
657 | Ifdef (* todo? of string ? of formula_cpp ? *)
658 | IfdefElseif (* same *)
659 | IfdefElse (* same *)
660 | IfdefEndif
661 (* set in Parsing_hacks.set_ifdef_parenthize_info. It internally use
662 * a global so it means if you parse the same file twice you may get
663 * different id. I try now to avoid this pb by resetting it each
664 * time I parse a file.
665 *)
666 and matching_tag =
667 IfdefTag of (int (* tag *) * int (* total with this tag *))
668
669
670
671
672
673 (* ------------------------------------------------------------------------- *)
674 (* The toplevels elements *)
675 (* ------------------------------------------------------------------------- *)
676 and toplevel =
677 | Declaration of declaration
678 | Definition of definition
679
680 (* cppext: *)
681 | CppTop of cpp_directive
682 | IfdefTop of ifdef_directive (* * toplevel list *)
683
684 (* cppext: *)
685 | MacroTop of string * argument wrap2 list * il
686
687 | EmptyDef of il (* gccext: allow redundant ';' *)
688 | NotParsedCorrectly of il
689
690 | FinalDef of info (* EOF *)
691
692 (* ------------------------------------------------------------------------- *)
693 and program = toplevel list
694
695 (*****************************************************************************)
696 (* Cocci Bindings *)
697 (*****************************************************************************)
698 (* Was previously in pattern.ml, but because of the transformer,
699 * we need to decorate each token with some cocci code AND the environment
700 * for this cocci code.
701 *)
702 and metavars_binding = (Ast_cocci.meta_name, metavar_binding_kind) assoc
703 and metavar_binding_kind =
704 | MetaIdVal of string *
705 Ast_cocci.meta_name list (* negative constraints *)
706 | MetaFuncVal of string
707 | MetaLocalFuncVal of string
708
709 | MetaExprVal of expression (* a "clean expr" *) *
710 (*subterm constraints, currently exprs*)
711 Ast_cocci.meta_name list
712 | MetaExprListVal of argument wrap2 list
713 | MetaParamVal of parameterType
714 | MetaParamListVal of parameterType wrap2 list
715
716 | MetaTypeVal of fullType
717 | MetaInitVal of initialiser
718 | MetaInitListVal of initialiser wrap2 list
719 | MetaDeclVal of declaration
720 | MetaFieldVal of field
721 | MetaFieldListVal of field list
722 | MetaStmtVal of statement
723
724 (* Could also be in Lib_engine.metavars_binding2 with the ParenVal,
725 * because don't need to have the value for a position in the env of
726 * a '+'. But ParenVal or LabelVal are used only by CTL, they are not
727 * variables accessible via SmPL whereas the position can be one day
728 * so I think it's better to put MetaPosVal here *)
729 | MetaPosVal of (Ast_cocci.fixpos * Ast_cocci.fixpos) (* max, min *)
730 | MetaPosValList of
731 (Common.filename * string (*element*) * posl * posl) list (* min, max *)
732 | MetaListlenVal of int
733
734
735 (*****************************************************************************)
736 (* C comments *)
737 (*****************************************************************************)
738
739 (* convention: I often use "m" for comments as I can not use "c"
740 * (already use for c stuff) and "com" is too long.
741 *)
742
743 (* this type will be associated to each token.
744 *)
745 and comments_around = {
746 mbefore: Token_c.comment_like_token list;
747 mafter: Token_c.comment_like_token list;
748
749 (* less: could remove ? do something simpler than CComment for
750 * coccinelle, cf above. *)
751 mbefore2: comment_and_relative_pos list;
752 mafter2: comment_and_relative_pos list;
753 }
754 and comment_and_relative_pos = {
755
756 minfo: Common.parse_info;
757 (* the int represent the number of lines of difference between the
758 * current token and the comment. When on same line, this number is 0.
759 * When previous line, -1. In some way the after/before in previous
760 * record is useless because the sign of the integer can helps
761 * do the difference too, but I keep it that way.
762 *)
763 mpos: int;
764 (* todo?
765 * cppbetween: bool; touse? if false positive
766 * is_alone_in_line: bool; (*for labels, to avoid false positive*)
767 *)
768 }
769
770 and comment = Common.parse_info
771 and com = comment list ref
772
773 (* with sexp *)
774
775
776 (*****************************************************************************)
777 (* Some constructors *)
778 (*****************************************************************************)
779 let nullQualif = ({const=false; volatile= false}, [])
780 let nQ = nullQualif
781
782 let defaultInt = (BaseType (IntType (Si (Signed, CInt))))
783
784 let noType () = ref (None,NotTest)
785 let noInstr = (ExprStatement (None), [])
786 let noTypedefDef () = None
787
788 let emptyMetavarsBinding =
789 ([]: metavars_binding)
790
791 let emptyAnnotCocci =
792 (Ast_cocci.CONTEXT (Ast_cocci.NoPos,Ast_cocci.NOTHING),
793 ([] : metavars_binding list))
794
795 let emptyAnnot =
796 (None: (Ast_cocci.mcodekind * metavars_binding list) option)
797
798 (* compatibility mode *)
799 let mcode_and_env_of_cocciref aref =
800 match !aref with
801 | Some x -> x
802 | None -> emptyAnnotCocci
803
804
805 let emptyComments= {
806 mbefore = [];
807 mafter = [];
808 mbefore2 = [];
809 mafter2 = [];
810 }
811
812
813 (* for include, some meta information needed by cocci *)
814 let noRelPos () =
815 ref (None: include_rel_pos option)
816 let noInIfdef () =
817 ref false
818
819
820 (* When want add some info in ast that does not correspond to
821 * an existing C element.
822 * old: or when don't want 'synchronize' on it in unparse_c.ml
823 * (now have other mark for tha matter).
824 *)
825 let no_virt_pos = ({str="";charpos=0;line=0;column=0;file=""},-1)
826
827 let fakeInfo pi =
828 { pinfo = FakeTok ("",no_virt_pos);
829 cocci_tag = ref emptyAnnot;
830 comments_tag = ref emptyComments;
831 }
832
833 let noii = []
834 let noattr = []
835 let noi_content = (None: ((Common.filename * program) option))
836
837 (*****************************************************************************)
838 (* Wrappers *)
839 (*****************************************************************************)
840 let unwrap = fst
841
842 let unwrap2 = fst
843
844 let unwrap_expr ((unwrap_e, typ), iie) = unwrap_e
845 let rewrap_expr ((_old_unwrap_e, typ), iie) newe = ((newe, typ), iie)
846
847 let unwrap_typeC (qu, (typeC, ii)) = typeC
848 let rewrap_typeC (qu, (typeC, ii)) newtypeC = (qu, (newtypeC, ii))
849
850 let unwrap_typeCbis (typeC, ii) = typeC
851
852 let unwrap_st (unwrap_st, ii) = unwrap_st
853
854 (* ------------------------------------------------------------------------- *)
855 let mk_e unwrap_e ii = (unwrap_e, noType()), ii
856 let mk_e_bis unwrap_e ty ii = (unwrap_e, ty), ii
857
858 let mk_ty typeC ii = nQ, (typeC, ii)
859 let mk_tybis typeC ii = (typeC, ii)
860
861 let mk_st unwrap_st ii = (unwrap_st, ii)
862
863 (* ------------------------------------------------------------------------- *)
864 let get_ii_typeC_take_care (typeC, ii) = ii
865 let get_ii_st_take_care (st, ii) = ii
866 let get_ii_expr_take_care (e, ii) = ii
867
868 let get_st_and_ii (st, ii) = st, ii
869 let get_ty_and_ii (qu, (typeC, ii)) = qu, (typeC, ii)
870 let get_e_and_ii (e, ii) = e, ii
871
872
873 (* ------------------------------------------------------------------------- *)
874 let get_type_expr ((unwrap_e, typ), iie) = !typ
875 let set_type_expr ((unwrap_e, oldtyp), iie) newtyp =
876 oldtyp := newtyp
877 (* old: (unwrap_e, newtyp), iie *)
878
879 let get_onlytype_expr ((unwrap_e, typ), iie) =
880 match !typ with
881 | Some (ft,_local), _test -> Some ft
882 | None, _ -> None
883
884 let get_onlylocal_expr ((unwrap_e, typ), iie) =
885 match !typ with
886 | Some (ft,local), _test -> Some local
887 | None, _ -> None
888
889 (* ------------------------------------------------------------------------- *)
890 let rewrap_str s ii =
891 {ii with pinfo =
892 (match ii.pinfo with
893 OriginTok pi -> OriginTok { pi with Common.str = s;}
894 | ExpandedTok (pi,vpi) -> ExpandedTok ({ pi with Common.str = s;},vpi)
895 | FakeTok (_,vpi) -> FakeTok (s,vpi)
896 | AbstractLineTok pi -> OriginTok { pi with Common.str = s;})}
897
898 let rewrap_pinfo pi ii =
899 {ii with pinfo = pi}
900
901
902
903 (* info about the current location *)
904 let get_pi = function
905 OriginTok pi -> pi
906 | ExpandedTok (_,(pi,_)) -> pi
907 | FakeTok (_,(pi,_)) -> pi
908 | AbstractLineTok pi -> pi
909
910 (* original info *)
911 let get_opi = function
912 OriginTok pi -> pi
913 | ExpandedTok (pi,_) -> pi (* diff with get_pi *)
914 | FakeTok (_,_) -> failwith "no position information"
915 | AbstractLineTok pi -> pi
916
917 let str_of_info ii =
918 match ii.pinfo with
919 OriginTok pi -> pi.Common.str
920 | ExpandedTok (pi,_) -> pi.Common.str
921 | FakeTok (s,_) -> s
922 | AbstractLineTok pi -> pi.Common.str
923
924 let get_info f ii =
925 match ii.pinfo with
926 OriginTok pi -> f pi
927 | ExpandedTok (_,(pi,_)) -> f pi
928 | FakeTok (_,(pi,_)) -> f pi
929 | AbstractLineTok pi -> f pi
930
931 let get_orig_info f ii =
932 match ii.pinfo with
933 OriginTok pi -> f pi
934 | ExpandedTok (pi,_) -> f pi (* diff with get_info *)
935 | FakeTok (_,(pi,_)) -> f pi
936 | AbstractLineTok pi -> f pi
937
938 let make_expanded ii =
939 {ii with pinfo = ExpandedTok (get_opi ii.pinfo,no_virt_pos)}
940
941 let pos_of_info ii = get_info (function x -> x.Common.charpos) ii
942 let opos_of_info ii = get_orig_info (function x -> x.Common.charpos) ii
943 let line_of_info ii = get_orig_info (function x -> x.Common.line) ii
944 let col_of_info ii = get_orig_info (function x -> x.Common.column) ii
945 let file_of_info ii = get_orig_info (function x -> x.Common.file) ii
946 let mcode_of_info ii = fst (mcode_and_env_of_cocciref ii.cocci_tag)
947 let pinfo_of_info ii = ii.pinfo
948 let parse_info_of_info ii = get_pi ii.pinfo
949
950 let strloc_of_info ii =
951 spf "%s:%d" (file_of_info ii) (line_of_info ii)
952
953 let is_fake ii =
954 match ii.pinfo with
955 FakeTok (_,_) -> true
956 | _ -> false
957
958 let is_origintok ii =
959 match ii.pinfo with
960 | OriginTok pi -> true
961 | _ -> false
962
963 (* ------------------------------------------------------------------------- *)
964 type posrv = Real of Common.parse_info | Virt of virtual_position
965
966 let compare_pos ii1 ii2 =
967 let get_pos = function
968 OriginTok pi -> Real pi
969 | FakeTok (s,vpi) -> Virt vpi
970 | ExpandedTok (pi,vpi) -> Virt vpi
971 | AbstractLineTok pi -> Real pi in (* used for printing *)
972 let pos1 = get_pos (pinfo_of_info ii1) in
973 let pos2 = get_pos (pinfo_of_info ii2) in
974 match (pos1,pos2) with
975 (Real p1, Real p2) ->
976 compare p1.Common.charpos p2.Common.charpos
977 | (Virt (p1,_), Real p2) ->
978 if (compare p1.Common.charpos p2.Common.charpos) =|= (-1) then (-1) else 1
979 | (Real p1, Virt (p2,_)) ->
980 if (compare p1.Common.charpos p2.Common.charpos) =|= 1 then 1 else (-1)
981 | (Virt (p1,o1), Virt (p2,o2)) ->
982 let poi1 = p1.Common.charpos in
983 let poi2 = p2.Common.charpos in
984 match compare poi1 poi2 with
985 -1 -> -1
986 | 0 -> compare o1 o2
987 | x -> x
988
989 let equal_posl (l1,c1) (l2,c2) =
990 (l1 =|= l2) && (c1 =|= c2)
991
992 let compare_posl (l1,c1) (l2,c2) =
993 match l2 - l1 with
994 0 -> c2 - c1
995 | r -> r
996
997 let info_to_fixpos ii =
998 match pinfo_of_info ii with
999 OriginTok pi -> Ast_cocci.Real pi.Common.charpos
1000 | ExpandedTok (_,(pi,offset)) ->
1001 Ast_cocci.Virt (pi.Common.charpos,offset)
1002 | FakeTok (_,(pi,offset)) ->
1003 Ast_cocci.Virt (pi.Common.charpos,offset)
1004 | AbstractLineTok pi -> failwith "unexpected abstract"
1005
1006 (* cocci: *)
1007 let is_test (e : expression) =
1008 let (_,info), _ = e in
1009 let (_,test) = !info in
1010 test =*= Test
1011
1012 (*****************************************************************************)
1013 (* Abstract line *)
1014 (*****************************************************************************)
1015
1016 (* When we have extended the C Ast to add some info to the tokens,
1017 * such as its line number in the file, we can not use anymore the
1018 * ocaml '=' to compare Ast elements. To overcome this problem, to be
1019 * able to use again '=', we just have to get rid of all those extra
1020 * information, to "abstract those line" (al) information.
1021 *
1022 * Julia then modifies it a little to have a tokenindex, so the original
1023 * true al_info is in fact real_al_info.
1024 *)
1025
1026 let al_info tokenindex x =
1027 { pinfo =
1028 (AbstractLineTok
1029 {charpos = tokenindex;
1030 line = tokenindex;
1031 column = tokenindex;
1032 file = "";
1033 str = str_of_info x});
1034 cocci_tag = ref emptyAnnot;
1035 comments_tag = ref emptyComments;
1036 }
1037
1038 let semi_al_info x =
1039 { x with
1040 cocci_tag = ref emptyAnnot;
1041 comments_tag = ref emptyComments;
1042 }
1043
1044 let magic_real_number = -10
1045
1046 let real_al_info x =
1047 { pinfo =
1048 (AbstractLineTok
1049 {charpos = magic_real_number;
1050 line = magic_real_number;
1051 column = magic_real_number;
1052 file = "";
1053 str = str_of_info x});
1054 cocci_tag = ref emptyAnnot;
1055 comments_tag = ref emptyComments;
1056 }
1057
1058 let al_comments x =
1059 let keep_cpp l =
1060 List.filter (function (Token_c.TCommentCpp _,_) -> true | _ -> false) l in
1061 let al_com (x,i) =
1062 (x,{i with Common.charpos = magic_real_number;
1063 Common.line = magic_real_number;
1064 Common.column = magic_real_number}) in
1065 {mbefore = []; (* duplicates mafter of the previous token *)
1066 mafter = List.map al_com (keep_cpp x.mafter);
1067 mbefore2=[];
1068 mafter2=[];
1069 }
1070
1071 let al_info_cpp tokenindex x =
1072 { pinfo =
1073 (AbstractLineTok
1074 {charpos = tokenindex;
1075 line = tokenindex;
1076 column = tokenindex;
1077 file = "";
1078 str = str_of_info x});
1079 cocci_tag = ref emptyAnnot;
1080 comments_tag = ref (al_comments !(x.comments_tag));
1081 }
1082
1083 let semi_al_info_cpp x =
1084 { x with
1085 cocci_tag = ref emptyAnnot;
1086 comments_tag = ref (al_comments !(x.comments_tag));
1087 }
1088
1089 let real_al_info_cpp x =
1090 { pinfo =
1091 (AbstractLineTok
1092 {charpos = magic_real_number;
1093 line = magic_real_number;
1094 column = magic_real_number;
1095 file = "";
1096 str = str_of_info x});
1097 cocci_tag = ref emptyAnnot;
1098 comments_tag = ref (al_comments !(x.comments_tag));
1099 }
1100
1101
1102 (*****************************************************************************)
1103 (* Views *)
1104 (*****************************************************************************)
1105
1106 (* Transform a list of arguments (or parameters) where the commas are
1107 * represented via the wrap2 and associated with an element, with
1108 * a list where the comma are on their own. f(1,2,2) was
1109 * [(1,[]); (2,[,]); (2,[,])] and become [1;',';2;',';2].
1110 *
1111 * Used in cocci_vs_c.ml, to have a more direct correspondance between
1112 * the ast_cocci of julia and ast_c.
1113 *)
1114 let rec (split_comma: 'a wrap2 list -> ('a, il) either list) =
1115 function
1116 | [] -> []
1117 | (e, ii)::xs ->
1118 if null ii
1119 then (Left e)::split_comma xs
1120 else Right ii::Left e::split_comma xs
1121
1122 let rec (unsplit_comma: ('a, il) either list -> 'a wrap2 list) =
1123 function
1124 | [] -> []
1125 | Right ii::Left e::xs ->
1126 (e, ii)::unsplit_comma xs
1127 | Left e::xs ->
1128 let empty_ii = [] in
1129 (e, empty_ii)::unsplit_comma xs
1130 | Right ii::_ ->
1131 raise Impossible
1132
1133
1134
1135
1136 (*****************************************************************************)
1137 (* Helpers, could also be put in lib_parsing_c.ml instead *)
1138 (*****************************************************************************)
1139
1140 (* should maybe be in pretty_print_c ? *)
1141
1142 let s_of_inc_file inc_file =
1143 match inc_file with
1144 | Local xs -> xs +> Common.join "/"
1145 | NonLocal xs -> xs +> Common.join "/"
1146 | Weird s -> s
1147
1148 let s_of_inc_file_bis inc_file =
1149 match inc_file with
1150 | Local xs -> "\"" ^ xs +> Common.join "/" ^ "\""
1151 | NonLocal xs -> "<" ^ xs +> Common.join "/" ^ ">"
1152 | Weird s -> s
1153
1154 let fieldname_of_fieldkind fieldkind =
1155 match fieldkind with
1156 | Simple (sopt, ft) -> sopt
1157 | BitField (sopt, ft, info, expr) -> sopt
1158
1159
1160 let s_of_attr attr =
1161 attr
1162 +> List.map (fun (Attribute s, ii) -> s)
1163 +> Common.join ","
1164
1165
1166 (* ------------------------------------------------------------------------- *)
1167 let str_of_name ident =
1168 match ident with
1169 | RegularName (s,ii) -> s
1170 | CppConcatenatedName xs ->
1171 xs +> List.map (fun (x,iiop) -> unwrap x) +> Common.join "##"
1172 | CppVariadicName (s, ii) -> "##" ^ s
1173 | CppIdentBuilder ((s,iis), xs) ->
1174 s ^ "(" ^
1175 (xs +> List.map (fun ((x,iix), iicomma) -> x) +> Common.join ",") ^
1176 ")"
1177
1178 let get_s_and_ii_of_name name =
1179 match name with
1180 | RegularName (s, iis) -> s, iis
1181 | CppIdentBuilder ((s, iis), xs) -> s, iis
1182 | CppVariadicName (s,iis) ->
1183 let (iop, iis) = Common.tuple_of_list2 iis in
1184 s, [iis]
1185 | CppConcatenatedName xs ->
1186 (match xs with
1187 | [] -> raise Impossible
1188 | ((s,iis),noiiop)::xs ->
1189 s, iis
1190 )
1191
1192 let get_s_and_info_of_name name =
1193 let (s,ii) = get_s_and_ii_of_name name in
1194 s, List.hd ii
1195
1196 let info_of_name name =
1197 let (s,ii) = get_s_and_ii_of_name name in
1198 List.hd ii
1199
1200 let ii_of_name name =
1201 let (s,ii) = get_s_and_ii_of_name name in
1202 ii
1203
1204 let get_local_ii_of_expr_inlining_ii_of_name e =
1205 let (ebis,_),ii = e in
1206 match ebis, ii with
1207 | Ident name, noii ->
1208 assert(null noii);
1209 ii_of_name name
1210 | RecordAccess (e, name), ii ->
1211 ii @ ii_of_name name
1212 | RecordPtAccess (e, name), ii ->
1213 ii @ ii_of_name name
1214 | _, ii -> ii
1215
1216
1217 let get_local_ii_of_tybis_inlining_ii_of_name ty =
1218 match ty with
1219 | TypeName (name, _typ), [] -> ii_of_name name
1220 | _, ii -> ii
1221
1222 (* the following is used to obtain the argument to LocalVar *)
1223 let info_of_type ft =
1224 let (qu, ty) = ft in
1225 (* bugfix: because of string->name, the ii can be deeper *)
1226 let ii = get_local_ii_of_tybis_inlining_ii_of_name ty in
1227 match ii with
1228 | ii::_ -> Some ii.pinfo
1229 | [] -> None
1230
1231 (* only Label and Goto have name *)
1232 let get_local_ii_of_st_inlining_ii_of_name st =
1233 match st with
1234 | Labeled (Label (name, st)), ii -> ii_of_name name @ ii
1235 | Jump (Goto name), ii ->
1236 let (i1, i3) = Common.tuple_of_list2 ii in
1237 [i1] @ ii_of_name name @ [i3]
1238 | _, ii -> ii
1239
1240
1241
1242 (* ------------------------------------------------------------------------- *)
1243 let name_of_parameter param =
1244 param.p_namei +> Common.map_option (str_of_name)
1245