431d107595e17e35e2249b6b004462a25d813103
[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 | NotLocalVar (* cocci: *)
295 and test = Test | NotTest (* cocci: *)
296
297 and expressionbis =
298
299 (* Ident can be a enumeration constant, a simple variable, a name of a func.
300 * With cppext, Ident can also be the name of a macro. Sparse says
301 * "an identifier with a meaning is a symbol" *)
302 | Ident of name (* todo? more semantic info such as LocalFunc *)
303
304 | Constant of constant
305 | FunCall of expression * argument wrap2 (* , *) list
306 (* gccext: x ? /* empty */ : y <=> x ? x : y; hence the 'option' below *)
307 | CondExpr of expression * expression option * expression
308
309 (* should be considered as statements, bad C langage *)
310 | Sequence of expression * expression
311 | Assignment of expression * assignOp * expression
312
313
314 | Postfix of expression * fixOp
315 | Infix of expression * fixOp
316
317 | Unary of expression * unaryOp
318 | Binary of expression * binaryOp * expression
319
320 | ArrayAccess of expression * expression
321
322 (* field ident access *)
323 | RecordAccess of expression * name
324 | RecordPtAccess of expression * name
325 (* redundant normally, could replace it by DeRef RecordAcces *)
326
327 | SizeOfExpr of expression
328 | SizeOfType of fullType
329 | Cast of fullType * expression
330
331 (* gccext: *)
332 | StatementExpr of compound wrap (* ( ) new scope *)
333 | Constructor of fullType * initialiser wrap2 (* , *) list
334
335 (* for unparser: *)
336 | ParenExpr of expression
337
338 (* for C++: *)
339 | New of argument
340
341 (* cppext: IfdefExpr TODO *)
342
343 (* cppext: normmally just expression *)
344 and argument = (expression, weird_argument) Common.either
345 and weird_argument =
346 | ArgType of parameterType
347 | ArgAction of action_macro
348 and action_macro =
349 (* todo: ArgStatement of statement, possibly have ghost token *)
350 | ActMisc of il
351
352
353 (* I put string for Int and Float because int would not be enough because
354 * OCaml int are 31 bits. So simpler to do string. Same reason to have
355 * string instead of int list for the String case.
356 *
357 * note: -2 is not a constant, it is the unary operator '-'
358 * applied to constant 2. So the string must represent a positive
359 * integer only. *)
360
361 and constant =
362 | String of (string * isWchar)
363 | MultiString of string list (* can contain MacroString, todo: more info *)
364 | Char of (string * isWchar) (* normally it is equivalent to Int *)
365 | Int of (string * intType)
366 | Float of (string * floatType)
367
368 and isWchar = IsWchar | IsChar
369
370
371 and unaryOp = GetRef | DeRef | UnPlus | UnMinus | Tilde | Not
372 | GetRefLabel (* gccext: GetRefLabel, via &&label notation *)
373 and assignOp = SimpleAssign | OpAssign of arithOp
374 and fixOp = Dec | Inc
375
376 and binaryOp = Arith of arithOp | Logical of logicalOp
377
378 and arithOp =
379 | Plus | Minus | Mul | Div | Mod
380 | DecLeft | DecRight
381 | And | Or | Xor
382
383 and logicalOp =
384 | Inf | Sup | InfEq | SupEq
385 | Eq | NotEq
386 | AndLog | OrLog
387
388 and constExpression = expression (* => int *)
389
390 (* ------------------------------------------------------------------------- *)
391 (* C statement *)
392 (* ------------------------------------------------------------------------- *)
393 (* note: that assignement is not a statement but an expression;
394 * wonderful C langage.
395 *
396 * note: I use 'and' for type definition cos gccext allow statement as
397 * expression, so need mutual recursive type definition.
398 *
399 *)
400
401 and statement = statementbis wrap3
402 and statementbis =
403 | Labeled of labeled
404 | Compound of compound (* new scope *)
405 | ExprStatement of exprStatement
406 | Selection of selection (* have fakeend *)
407 | Iteration of iteration (* have fakeend *)
408 | Jump of jump
409
410 (* simplify cocci: only at the beginning of a compound normally *)
411 | Decl of declaration
412
413 (* gccext: *)
414 | Asm of asmbody
415 | NestedFunc of definition
416
417 (* cppext: *)
418 | MacroStmt
419
420
421
422 and labeled = Label of name * statement
423 | Case of expression * statement
424 | CaseRange of expression * expression * statement (* gccext: *)
425 | Default of statement
426
427 (* cppext:
428 * old: compound = (declaration list * statement list)
429 * old: (declaration, statement) either list
430 * Simplify cocci to just have statement list, by integrating Decl in stmt.
431 *
432 * update: now introduce also the _sequencable to allow ifdef in the middle.
433 * Indeed, I now allow ifdefs in the ast but they must be only between
434 * "sequencable" elements. They can be put in a type only if this type
435 * is used in a list, like at the toplevel, used in a 'toplevel list',
436 * or inside a compound, used in a 'statement list'. I must not allow
437 * ifdef anywhere. For instance I can not make ifdef a statement
438 * cos some instruction like If accept only one statement and the
439 * ifdef directive must not take the place of a legitimate instruction.
440 * We had a similar phenomena in SmPL where we have the notion
441 * of statement and sequencable statement too. Once you have
442 * such a type of sequencable thing, then s/xx list/xx_sequencable list/
443 * and introduce the ifdef.
444 *
445 * update: those ifdefs are either passed, or present in the AST but in
446 * a flat form. To structure those flat ifdefs you have to run
447 * a transformation that will put in a tree the statements inside
448 * ifdefs branches. Cf cpp_ast_c.ml. This is for instance the difference
449 * between a IfdefStmt (flat) and IfdefStmt2 (tree structured).
450 *
451 *)
452 and compound = statement_sequencable list
453
454 (* cppext: easier to put at statement_list level than statement level *)
455 and statement_sequencable =
456 | StmtElem of statement
457
458 (* cppext: *)
459 | CppDirectiveStmt of cpp_directive
460 | IfdefStmt of ifdef_directive
461
462 (* this will be build in cpp_ast_c from the previous flat IfdefStmt *)
463 | IfdefStmt2 of ifdef_directive list * (statement_sequencable list) list
464
465 and exprStatement = expression option
466
467 (* for Switch, need check that all elements in the compound start
468 * with a case:, otherwise unreachable code.
469 *)
470 and selection =
471 | If of expression * statement * statement
472 | Switch of expression * statement
473
474
475 and iteration =
476 | While of expression * statement
477 | DoWhile of statement * expression
478 | For of exprStatement wrap * exprStatement wrap * exprStatement wrap *
479 statement
480 (* cppext: *)
481 | MacroIteration of string * argument wrap2 list * statement
482
483 and jump = Goto of name
484 | Continue | Break
485 | Return | ReturnExpr of expression
486 | GotoComputed of expression (* gccext: goto *exp ';' *)
487
488
489 (* gccext: *)
490 and asmbody = il (* string list *) * colon wrap (* : *) list
491 and colon = Colon of colon_option wrap2 list
492 and colon_option = colon_option_bis wrap
493 and colon_option_bis = ColonMisc | ColonExpr of expression
494
495
496 (* ------------------------------------------------------------------------- *)
497 (* Declaration *)
498 (* ------------------------------------------------------------------------- *)
499 (* (string * ...) option cos can have empty declaration or struct tag
500 * declaration.
501 *
502 * Before I had a Typedef constructor, but why make this special case and not
503 * have StructDef, EnumDef, ... so that 'struct t {...} v' will generate 2
504 * declarations ? So I try to generalise and not have Typedef either. This
505 * requires more work in parsing. Better to separate concern.
506 *
507 * Before the need for unparser, I didn't have a DeclList but just a Decl.
508 *
509 * I am not sure what it means to declare a prototype inline, but gcc
510 * accepts it.
511 *)
512
513 and declaration =
514 | DeclList of onedecl wrap2 (* , *) list wrap (* ; fakestart sto *)
515 (* cppext: *)
516 | MacroDecl of (string * argument wrap2 list) wrap (* fakestart *)
517
518 and onedecl =
519 { v_namei: (name * (info (* = *) * initialiser) option) option;
520 v_type: fullType;
521 (* semantic: set in type annotated and used in cocci_vs_c
522 * when we transform some initialisation into affectation
523 *)
524 v_type_bis: fullType (* Type_c.completed_and_simplified *) option ref;
525 v_storage: storage;
526 v_local: local_decl; (* cocci: *)
527 v_attr: attribute list; (* gccext: *)
528 }
529 and storage = storagebis * bool (* gccext: inline or not *)
530 and storagebis = NoSto | StoTypedef | Sto of storageClass
531 and storageClass = Auto | Static | Register | Extern
532
533 and local_decl = LocalDecl | NotLocalDecl
534
535 (* fullType is the type used if the type should be converted to
536 an assignment. It can be adjusted in the type annotation
537 phase when typedef information is availalble *)
538 and initialiser = initialiserbis wrap
539 and initialiserbis =
540 | InitExpr of expression
541 | InitList of initialiser wrap2 (* , *) list
542 (* gccext: *)
543 | InitDesignators of designator list * initialiser
544 | InitFieldOld of string * initialiser
545 | InitIndexOld of expression * initialiser
546
547 (* ex: [2].y = x, or .y[2] or .y.x. They can be nested *)
548 and designator = designatorbis wrap
549 and designatorbis =
550 | DesignatorField of string
551 | DesignatorIndex of expression
552 | DesignatorRange of expression * expression
553
554 (* ------------------------------------------------------------------------- *)
555 (* Function definition *)
556 (* ------------------------------------------------------------------------- *)
557 (* Normally we should define another type functionType2 because there
558 * are more restrictions on what can define a function than a pointer
559 * function. For instance a function declaration can omit the name of the
560 * parameter whereas a function definition can not. But, in some cases such
561 * as 'f(void) {', there is no name too, so I simplified and reused the
562 * same functionType type for both declaration and function definition.
563 *
564 * Also old style C does not have type in the parameter, so again simpler
565 * to abuse the functionType and allow missing type.
566 *)
567 and definition = definitionbis wrap (* ( ) { } fakestart sto *)
568 and definitionbis =
569 { f_name: name;
570 f_type: functionType; (* less? a functionType2 ? *)
571 f_storage: storage;
572 f_body: compound;
573 f_attr: attribute list; (* gccext: *)
574 f_old_c_style: declaration list option;
575 }
576 (* cppext: IfdefFunHeader TODO *)
577
578 (* ------------------------------------------------------------------------- *)
579 (* cppext: cpp directives, #ifdef, #define and #include body *)
580 (* ------------------------------------------------------------------------- *)
581 and cpp_directive =
582 | Define of define
583 | Include of includ
584 | PragmaAndCo of il
585 (*| Ifdef ? no, ifdefs are handled differently, cf ifdef_directive below *)
586
587 and define = string wrap (* #define s eol *) * (define_kind * define_val)
588 and define_kind =
589 | DefineVar
590 | DefineFunc of ((string wrap) wrap2 list) wrap (* () *)
591 | Undef
592 and define_val =
593 (* most common case; e.g. to define int constant *)
594 | DefineExpr of expression
595
596 | DefineStmt of statement
597 | DefineType of fullType
598 | DefineDoWhileZero of (statement * expression) wrap (* do { } while(0) *)
599
600 | DefineFunction of definition
601 | DefineInit of initialiser (* in practice only { } with possible ',' *)
602
603 (* TODO DefineMulti of define_val list *)
604
605 | DefineText of string wrap
606 | DefineEmpty
607
608 | DefineTodo
609
610
611
612 and includ =
613 { i_include: inc_file wrap; (* #include s *)
614 (* cocci: computed in ? *)
615 i_rel_pos: include_rel_pos option ref;
616 (* cocci: cf -test incl *)
617 i_is_in_ifdef: bool;
618 (* cf cpp_ast_c.ml. set to None at parsing time. *)
619 i_content: (Common.filename (* full path *) * program) option;
620 }
621 and inc_file =
622 | Local of inc_elem list
623 | NonLocal of inc_elem list
624 | Weird of string (* ex: #include SYSTEM_H *)
625 and inc_elem = string
626
627 (* cocci: to tag the first of #include <xx/> and last of #include <yy/>
628 *
629 * The first_of and last_of store the list of prefixes that was
630 * introduced by the include. On #include <a/b/x>, if the include was
631 * the first in the file, it would give in first_of the following
632 * prefixes a/b/c; a/b/; a/ ; <empty>
633 *
634 * This is set after parsing, in cocci.ml, in update_rel_pos.
635 *)
636 and include_rel_pos = {
637 first_of : string list list;
638 last_of : string list list;
639 }
640
641
642
643 (* todo? to specialize if someone need more info *)
644 and ifdef_directive = (* or and 'a ifdefed = 'a list wrap *)
645 | IfdefDirective of (ifdefkind * matching_tag) wrap
646 and ifdefkind =
647 | Ifdef (* todo? of string ? of formula_cpp ? *)
648 | IfdefElseif (* same *)
649 | IfdefElse (* same *)
650 | IfdefEndif
651 (* set in Parsing_hacks.set_ifdef_parenthize_info. It internally use
652 * a global so it means if you parse the same file twice you may get
653 * different id. I try now to avoid this pb by resetting it each
654 * time I parse a file.
655 *)
656 and matching_tag =
657 IfdefTag of (int (* tag *) * int (* total with this tag *))
658
659
660
661
662
663 (* ------------------------------------------------------------------------- *)
664 (* The toplevels elements *)
665 (* ------------------------------------------------------------------------- *)
666 and toplevel =
667 | Declaration of declaration
668 | Definition of definition
669
670 (* cppext: *)
671 | CppTop of cpp_directive
672 | IfdefTop of ifdef_directive (* * toplevel list *)
673
674 (* cppext: *)
675 | MacroTop of string * argument wrap2 list * il
676
677 | EmptyDef of il (* gccext: allow redundant ';' *)
678 | NotParsedCorrectly of il
679
680 | FinalDef of info (* EOF *)
681
682 (* ------------------------------------------------------------------------- *)
683 and program = toplevel list
684
685 (*****************************************************************************)
686 (* Cocci Bindings *)
687 (*****************************************************************************)
688 (* Was previously in pattern.ml, but because of the transformer,
689 * we need to decorate each token with some cocci code AND the environment
690 * for this cocci code.
691 *)
692 and metavars_binding = (Ast_cocci.meta_name, metavar_binding_kind) assoc
693 and metavar_binding_kind =
694 | MetaIdVal of string *
695 Ast_cocci.meta_name list (* negative constraints *)
696 | MetaFuncVal of string
697 | MetaLocalFuncVal of string
698
699 | MetaExprVal of expression (* a "clean expr" *) *
700 (*subterm constraints, currently exprs*)
701 Ast_cocci.meta_name list
702 | MetaExprListVal of argument wrap2 list
703 | MetaParamVal of parameterType
704 | MetaParamListVal of parameterType wrap2 list
705
706 | MetaTypeVal of fullType
707 | MetaInitVal of initialiser
708 | MetaDeclVal of declaration
709 | MetaFieldVal of field
710 | MetaStmtVal of statement
711
712 (* Could also be in Lib_engine.metavars_binding2 with the ParenVal,
713 * because don't need to have the value for a position in the env of
714 * a '+'. But ParenVal or LabelVal are used only by CTL, they are not
715 * variables accessible via SmPL whereas the position can be one day
716 * so I think it's better to put MetaPosVal here *)
717 | MetaPosVal of (Ast_cocci.fixpos * Ast_cocci.fixpos) (* max, min *)
718 | MetaPosValList of
719 (Common.filename * string (*element*) * posl * posl) list (* min, max *)
720 | MetaListlenVal of int
721
722
723 (*****************************************************************************)
724 (* C comments *)
725 (*****************************************************************************)
726
727 (* convention: I often use "m" for comments as I can not use "c"
728 * (already use for c stuff) and "com" is too long.
729 *)
730
731 (* this type will be associated to each token.
732 *)
733 and comments_around = {
734 mbefore: Token_c.comment_like_token list;
735 mafter: Token_c.comment_like_token list;
736
737 (* less: could remove ? do something simpler than CComment for
738 * coccinelle, cf above. *)
739 mbefore2: comment_and_relative_pos list;
740 mafter2: comment_and_relative_pos list;
741 }
742 and comment_and_relative_pos = {
743
744 minfo: Common.parse_info;
745 (* the int represent the number of lines of difference between the
746 * current token and the comment. When on same line, this number is 0.
747 * When previous line, -1. In some way the after/before in previous
748 * record is useless because the sign of the integer can helps
749 * do the difference too, but I keep it that way.
750 *)
751 mpos: int;
752 (* todo?
753 * cppbetween: bool; touse? if false positive
754 * is_alone_in_line: bool; (*for labels, to avoid false positive*)
755 *)
756 }
757
758 and comment = Common.parse_info
759 and com = comment list ref
760
761 (* with sexp *)
762
763
764 (*****************************************************************************)
765 (* Some constructors *)
766 (*****************************************************************************)
767 let nullQualif = ({const=false; volatile= false}, [])
768 let nQ = nullQualif
769
770 let defaultInt = (BaseType (IntType (Si (Signed, CInt))))
771
772 let noType () = ref (None,NotTest)
773 let noInstr = (ExprStatement (None), [])
774 let noTypedefDef () = None
775
776 let emptyMetavarsBinding =
777 ([]: metavars_binding)
778
779 let emptyAnnotCocci =
780 (Ast_cocci.CONTEXT (Ast_cocci.NoPos,Ast_cocci.NOTHING),
781 ([] : metavars_binding list))
782
783 let emptyAnnot =
784 (None: (Ast_cocci.mcodekind * metavars_binding list) option)
785
786 (* compatibility mode *)
787 let mcode_and_env_of_cocciref aref =
788 match !aref with
789 | Some x -> x
790 | None -> emptyAnnotCocci
791
792
793 let emptyComments= {
794 mbefore = [];
795 mafter = [];
796 mbefore2 = [];
797 mafter2 = [];
798 }
799
800
801 (* for include, some meta information needed by cocci *)
802 let noRelPos () =
803 ref (None: include_rel_pos option)
804 let noInIfdef () =
805 ref false
806
807
808 (* When want add some info in ast that does not correspond to
809 * an existing C element.
810 * old: or when don't want 'synchronize' on it in unparse_c.ml
811 * (now have other mark for tha matter).
812 *)
813 let no_virt_pos = ({str="";charpos=0;line=0;column=0;file=""},-1)
814
815 let fakeInfo pi =
816 { pinfo = FakeTok ("",no_virt_pos);
817 cocci_tag = ref emptyAnnot;
818 comments_tag = ref emptyComments;
819 }
820
821 let noii = []
822 let noattr = []
823 let noi_content = (None: ((Common.filename * program) option))
824
825 (*****************************************************************************)
826 (* Wrappers *)
827 (*****************************************************************************)
828 let unwrap = fst
829
830 let unwrap2 = fst
831
832 let unwrap_expr ((unwrap_e, typ), iie) = unwrap_e
833 let rewrap_expr ((_old_unwrap_e, typ), iie) newe = ((newe, typ), iie)
834
835 let unwrap_typeC (qu, (typeC, ii)) = typeC
836 let rewrap_typeC (qu, (typeC, ii)) newtypeC = (qu, (newtypeC, ii))
837
838 let unwrap_typeCbis (typeC, ii) = typeC
839
840 let unwrap_st (unwrap_st, ii) = unwrap_st
841
842 (* ------------------------------------------------------------------------- *)
843 let mk_e unwrap_e ii = (unwrap_e, noType()), ii
844 let mk_e_bis unwrap_e ty ii = (unwrap_e, ty), ii
845
846 let mk_ty typeC ii = nQ, (typeC, ii)
847 let mk_tybis typeC ii = (typeC, ii)
848
849 let mk_st unwrap_st ii = (unwrap_st, ii)
850
851 (* ------------------------------------------------------------------------- *)
852 let get_ii_typeC_take_care (typeC, ii) = ii
853 let get_ii_st_take_care (st, ii) = ii
854 let get_ii_expr_take_care (e, ii) = ii
855
856 let get_st_and_ii (st, ii) = st, ii
857 let get_ty_and_ii (qu, (typeC, ii)) = qu, (typeC, ii)
858 let get_e_and_ii (e, ii) = e, ii
859
860
861 (* ------------------------------------------------------------------------- *)
862 let get_type_expr ((unwrap_e, typ), iie) = !typ
863 let set_type_expr ((unwrap_e, oldtyp), iie) newtyp =
864 oldtyp := newtyp
865 (* old: (unwrap_e, newtyp), iie *)
866
867 let get_onlytype_expr ((unwrap_e, typ), iie) =
868 match !typ with
869 | Some (ft,_local), _test -> Some ft
870 | None, _ -> None
871
872 let get_onlylocal_expr ((unwrap_e, typ), iie) =
873 match !typ with
874 | Some (ft,local), _test -> Some local
875 | None, _ -> None
876
877 (* ------------------------------------------------------------------------- *)
878 let rewrap_str s ii =
879 {ii with pinfo =
880 (match ii.pinfo with
881 OriginTok pi -> OriginTok { pi with Common.str = s;}
882 | ExpandedTok (pi,vpi) -> ExpandedTok ({ pi with Common.str = s;},vpi)
883 | FakeTok (_,vpi) -> FakeTok (s,vpi)
884 | AbstractLineTok pi -> OriginTok { pi with Common.str = s;})}
885
886 let rewrap_pinfo pi ii =
887 {ii with pinfo = pi}
888
889
890
891 (* info about the current location *)
892 let get_pi = function
893 OriginTok pi -> pi
894 | ExpandedTok (_,(pi,_)) -> pi
895 | FakeTok (_,(pi,_)) -> pi
896 | AbstractLineTok pi -> pi
897
898 (* original info *)
899 let get_opi = function
900 OriginTok pi -> pi
901 | ExpandedTok (pi,_) -> pi (* diff with get_pi *)
902 | FakeTok (_,_) -> failwith "no position information"
903 | AbstractLineTok pi -> pi
904
905 let str_of_info ii =
906 match ii.pinfo with
907 OriginTok pi -> pi.Common.str
908 | ExpandedTok (pi,_) -> pi.Common.str
909 | FakeTok (s,_) -> s
910 | AbstractLineTok pi -> pi.Common.str
911
912 let get_info f ii =
913 match ii.pinfo with
914 OriginTok pi -> f pi
915 | ExpandedTok (_,(pi,_)) -> f pi
916 | FakeTok (_,(pi,_)) -> f pi
917 | AbstractLineTok pi -> f pi
918
919 let get_orig_info f ii =
920 match ii.pinfo with
921 OriginTok pi -> f pi
922 | ExpandedTok (pi,_) -> f pi (* diff with get_info *)
923 | FakeTok (_,(pi,_)) -> f pi
924 | AbstractLineTok pi -> f pi
925
926 let make_expanded ii =
927 {ii with pinfo = ExpandedTok (get_opi ii.pinfo,no_virt_pos)}
928
929 let pos_of_info ii = get_info (function x -> x.Common.charpos) ii
930 let opos_of_info ii = get_orig_info (function x -> x.Common.charpos) ii
931 let line_of_info ii = get_orig_info (function x -> x.Common.line) ii
932 let col_of_info ii = get_orig_info (function x -> x.Common.column) ii
933 let file_of_info ii = get_orig_info (function x -> x.Common.file) ii
934 let mcode_of_info ii = fst (mcode_and_env_of_cocciref ii.cocci_tag)
935 let pinfo_of_info ii = ii.pinfo
936 let parse_info_of_info ii = get_pi ii.pinfo
937
938 let strloc_of_info ii =
939 spf "%s:%d" (file_of_info ii) (line_of_info ii)
940
941 let is_fake ii =
942 match ii.pinfo with
943 FakeTok (_,_) -> true
944 | _ -> false
945
946 let is_origintok ii =
947 match ii.pinfo with
948 | OriginTok pi -> true
949 | _ -> false
950
951 (* ------------------------------------------------------------------------- *)
952 type posrv = Real of Common.parse_info | Virt of virtual_position
953
954 let compare_pos ii1 ii2 =
955 let get_pos = function
956 OriginTok pi -> Real pi
957 | FakeTok (s,vpi) -> Virt vpi
958 | ExpandedTok (pi,vpi) -> Virt vpi
959 | AbstractLineTok pi -> Real pi in (* used for printing *)
960 let pos1 = get_pos (pinfo_of_info ii1) in
961 let pos2 = get_pos (pinfo_of_info ii2) in
962 match (pos1,pos2) with
963 (Real p1, Real p2) ->
964 compare p1.Common.charpos p2.Common.charpos
965 | (Virt (p1,_), Real p2) ->
966 if (compare p1.Common.charpos p2.Common.charpos) =|= (-1) then (-1) else 1
967 | (Real p1, Virt (p2,_)) ->
968 if (compare p1.Common.charpos p2.Common.charpos) =|= 1 then 1 else (-1)
969 | (Virt (p1,o1), Virt (p2,o2)) ->
970 let poi1 = p1.Common.charpos in
971 let poi2 = p2.Common.charpos in
972 match compare poi1 poi2 with
973 -1 -> -1
974 | 0 -> compare o1 o2
975 | x -> x
976
977 let equal_posl (l1,c1) (l2,c2) =
978 (l1 =|= l2) && (c1 =|= c2)
979
980 let info_to_fixpos ii =
981 match pinfo_of_info ii with
982 OriginTok pi -> Ast_cocci.Real pi.Common.charpos
983 | ExpandedTok (_,(pi,offset)) ->
984 Ast_cocci.Virt (pi.Common.charpos,offset)
985 | FakeTok (_,(pi,offset)) ->
986 Ast_cocci.Virt (pi.Common.charpos,offset)
987 | AbstractLineTok pi -> failwith "unexpected abstract"
988
989 (* cocci: *)
990 let is_test (e : expression) =
991 let (_,info), _ = e in
992 let (_,test) = !info in
993 test =*= Test
994
995 (*****************************************************************************)
996 (* Abstract line *)
997 (*****************************************************************************)
998
999 (* When we have extended the C Ast to add some info to the tokens,
1000 * such as its line number in the file, we can not use anymore the
1001 * ocaml '=' to compare Ast elements. To overcome this problem, to be
1002 * able to use again '=', we just have to get rid of all those extra
1003 * information, to "abstract those line" (al) information.
1004 *
1005 * Julia then modifies it a little to have a tokenindex, so the original
1006 * true al_info is in fact real_al_info.
1007 *)
1008
1009 let al_info tokenindex x =
1010 { pinfo =
1011 (AbstractLineTok
1012 {charpos = tokenindex;
1013 line = tokenindex;
1014 column = tokenindex;
1015 file = "";
1016 str = str_of_info x});
1017 cocci_tag = ref emptyAnnot;
1018 comments_tag = ref emptyComments;
1019 }
1020
1021 let semi_al_info x =
1022 { x with
1023 cocci_tag = ref emptyAnnot;
1024 comments_tag = ref emptyComments;
1025 }
1026
1027 let magic_real_number = -10
1028
1029 let real_al_info x =
1030 { pinfo =
1031 (AbstractLineTok
1032 {charpos = magic_real_number;
1033 line = magic_real_number;
1034 column = magic_real_number;
1035 file = "";
1036 str = str_of_info x});
1037 cocci_tag = ref emptyAnnot;
1038 comments_tag = ref emptyComments;
1039 }
1040
1041 let al_comments x =
1042 let keep_cpp l =
1043 List.filter (function (Token_c.TCommentCpp _,_) -> true | _ -> false) l in
1044 let al_com (x,i) =
1045 (x,{i with Common.charpos = magic_real_number;
1046 Common.line = magic_real_number;
1047 Common.column = magic_real_number}) in
1048 {mbefore = []; (* duplicates mafter of the previous token *)
1049 mafter = List.map al_com (keep_cpp x.mafter);
1050 mbefore2=[];
1051 mafter2=[];
1052 }
1053
1054 let al_info_cpp tokenindex x =
1055 { pinfo =
1056 (AbstractLineTok
1057 {charpos = tokenindex;
1058 line = tokenindex;
1059 column = tokenindex;
1060 file = "";
1061 str = str_of_info x});
1062 cocci_tag = ref emptyAnnot;
1063 comments_tag = ref (al_comments !(x.comments_tag));
1064 }
1065
1066 let semi_al_info_cpp x =
1067 { x with
1068 cocci_tag = ref emptyAnnot;
1069 comments_tag = ref (al_comments !(x.comments_tag));
1070 }
1071
1072 let real_al_info_cpp x =
1073 { pinfo =
1074 (AbstractLineTok
1075 {charpos = magic_real_number;
1076 line = magic_real_number;
1077 column = magic_real_number;
1078 file = "";
1079 str = str_of_info x});
1080 cocci_tag = ref emptyAnnot;
1081 comments_tag = ref (al_comments !(x.comments_tag));
1082 }
1083
1084
1085 (*****************************************************************************)
1086 (* Views *)
1087 (*****************************************************************************)
1088
1089 (* Transform a list of arguments (or parameters) where the commas are
1090 * represented via the wrap2 and associated with an element, with
1091 * a list where the comma are on their own. f(1,2,2) was
1092 * [(1,[]); (2,[,]); (2,[,])] and become [1;',';2;',';2].
1093 *
1094 * Used in cocci_vs_c.ml, to have a more direct correspondance between
1095 * the ast_cocci of julia and ast_c.
1096 *)
1097 let rec (split_comma: 'a wrap2 list -> ('a, il) either list) =
1098 function
1099 | [] -> []
1100 | (e, ii)::xs ->
1101 if null ii
1102 then (Left e)::split_comma xs
1103 else Right ii::Left e::split_comma xs
1104
1105 let rec (unsplit_comma: ('a, il) either list -> 'a wrap2 list) =
1106 function
1107 | [] -> []
1108 | Right ii::Left e::xs ->
1109 (e, ii)::unsplit_comma xs
1110 | Left e::xs ->
1111 let empty_ii = [] in
1112 (e, empty_ii)::unsplit_comma xs
1113 | Right ii::_ ->
1114 raise Impossible
1115
1116
1117
1118
1119 (*****************************************************************************)
1120 (* Helpers, could also be put in lib_parsing_c.ml instead *)
1121 (*****************************************************************************)
1122
1123 (* should maybe be in pretty_print_c ? *)
1124
1125 let s_of_inc_file inc_file =
1126 match inc_file with
1127 | Local xs -> xs +> Common.join "/"
1128 | NonLocal xs -> xs +> Common.join "/"
1129 | Weird s -> s
1130
1131 let s_of_inc_file_bis inc_file =
1132 match inc_file with
1133 | Local xs -> "\"" ^ xs +> Common.join "/" ^ "\""
1134 | NonLocal xs -> "<" ^ xs +> Common.join "/" ^ ">"
1135 | Weird s -> s
1136
1137 let fieldname_of_fieldkind fieldkind =
1138 match fieldkind with
1139 | Simple (sopt, ft) -> sopt
1140 | BitField (sopt, ft, info, expr) -> sopt
1141
1142
1143 let s_of_attr attr =
1144 attr
1145 +> List.map (fun (Attribute s, ii) -> s)
1146 +> Common.join ","
1147
1148
1149 (* ------------------------------------------------------------------------- *)
1150 let str_of_name ident =
1151 match ident with
1152 | RegularName (s,ii) -> s
1153 | CppConcatenatedName xs ->
1154 xs +> List.map (fun (x,iiop) -> unwrap x) +> Common.join "##"
1155 | CppVariadicName (s, ii) -> "##" ^ s
1156 | CppIdentBuilder ((s,iis), xs) ->
1157 s ^ "(" ^
1158 (xs +> List.map (fun ((x,iix), iicomma) -> x) +> Common.join ",") ^
1159 ")"
1160
1161 let get_s_and_ii_of_name name =
1162 match name with
1163 | RegularName (s, iis) -> s, iis
1164 | CppIdentBuilder ((s, iis), xs) -> s, iis
1165 | CppVariadicName (s,iis) ->
1166 let (iop, iis) = Common.tuple_of_list2 iis in
1167 s, [iis]
1168 | CppConcatenatedName xs ->
1169 (match xs with
1170 | [] -> raise Impossible
1171 | ((s,iis),noiiop)::xs ->
1172 s, iis
1173 )
1174
1175 let get_s_and_info_of_name name =
1176 let (s,ii) = get_s_and_ii_of_name name in
1177 s, List.hd ii
1178
1179 let info_of_name name =
1180 let (s,ii) = get_s_and_ii_of_name name in
1181 List.hd ii
1182
1183 let ii_of_name name =
1184 let (s,ii) = get_s_and_ii_of_name name in
1185 ii
1186
1187 let get_local_ii_of_expr_inlining_ii_of_name e =
1188 let (ebis,_),ii = e in
1189 match ebis, ii with
1190 | Ident name, noii ->
1191 assert(null noii);
1192 ii_of_name name
1193 | RecordAccess (e, name), ii ->
1194 ii @ ii_of_name name
1195 | RecordPtAccess (e, name), ii ->
1196 ii @ ii_of_name name
1197 | _, ii -> ii
1198
1199
1200 let get_local_ii_of_tybis_inlining_ii_of_name ty =
1201 match ty with
1202 | TypeName (name, _typ), [] -> ii_of_name name
1203 | _, ii -> ii
1204
1205 (* the following is used to obtain the argument to LocalVar *)
1206 let info_of_type ft =
1207 let (qu, ty) = ft in
1208 (* bugfix: because of string->name, the ii can be deeper *)
1209 let ii = get_local_ii_of_tybis_inlining_ii_of_name ty in
1210 match ii with
1211 | ii::_ -> ii.pinfo
1212 | [] -> failwith "type has no text; need to think again"
1213
1214 (* only Label and Goto have name *)
1215 let get_local_ii_of_st_inlining_ii_of_name st =
1216 match st with
1217 | Labeled (Label (name, st)), ii -> ii_of_name name @ ii
1218 | Jump (Goto name), ii ->
1219 let (i1, i3) = Common.tuple_of_list2 ii in
1220 [i1] @ ii_of_name name @ [i3]
1221 | _, ii -> ii
1222
1223
1224
1225 (* ------------------------------------------------------------------------- *)
1226 let name_of_parameter param =
1227 param.p_namei +> Common.map_option (str_of_name)
1228