3 * Copyright (C) 2010, University of Copenhagen DIKU and INRIA.
4 * Copyright (C) 2002, 2006, 2007, 2008, 2009 Yoann Padioleau
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.
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.
17 (*****************************************************************************)
18 (* The AST C related types *)
19 (*****************************************************************************)
21 * Some stuff are tagged semantic: which means that they are computed
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.
30 (* ------------------------------------------------------------------------- *)
32 (* ------------------------------------------------------------------------- *)
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.
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)
44 * convention: I often use 'ii' for the name of a list of info.
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.
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).
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/....
62 * Each token will also be decorated in the future with an environment,
63 * because the pending '+' may contain metavariables that refer to some
70 type posl
= int * int (* line-col, for MetaPosValList, for position variables *)
73 (* the virtual position is set in Parsing_hacks.insert_virtual_positions *)
74 type virtual_position
= Common.parse_info
* int (* character offset *)
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
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.
90 | AbstractLineTok
of Common.parse_info
(* local to the abstracted thing *)
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.
99 cocci_tag
: (Ast_cocci.mcodekind
* metavars_binding list
) option ref;
100 (* set in comment_annotater_c.ml *)
101 comments_tag
: comments_around
ref;
103 (* todo? token_info : sometimes useful to know what token it was *)
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,[','])].
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.
116 and 'a wrap
= 'a
* il
117 and 'a wrap2
= 'a
* il
118 and 'a wrap3
= 'a
* il
(* * evotype*)
120 (* ------------------------------------------------------------------------- *)
122 (* ------------------------------------------------------------------------- *)
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.
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.
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 *)
146 (* ------------------------------------------------------------------------- *)
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.
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 ...) }.
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
171 and fullType
= typeQualifier
* typeC
172 and typeC
= typeCbis wrap
(* todo reput wrap3 *)
175 | BaseType
of baseType
177 | Pointer
of fullType
178 | Array
of constExpression
option * fullType
179 | FunctionType
of functionType
181 | Enum
of string option * enumType
182 | StructUnion
of structUnion
* string option * structType
(* new scope *)
185 | StructUnionName
of structUnion
* string
187 | TypeName
of name
* fullType
option (* semantic: filled later *)
189 | ParenType
of fullType
(* forunparser: *)
191 (* gccext: TypeOfType below may seems useless; Why declare a
192 * __typeof__(int) x; ?
193 * When used with macros, it allows to fix a problem of C which
194 * is that type declaration can be spread around the ident. Indeed it
195 * may be difficult to have a macro such as
196 * '#define macro(type, ident) type ident;'
197 * because when you want to do a
198 * macro(char[256], x),
199 * then it will generate invalid code, but with a
200 * '#define macro(type, ident) __typeof(type) ident;'
203 | TypeOfExpr
of expression
204 | TypeOfType
of fullType
206 (* cppext: IfdefType TODO *)
208 (* -------------------------------------- *)
211 | FloatType
of floatType
216 (* stdC: type section
218 * note: char and signed char are semantically different!!
220 and intType
= CChar
(* obsolete? | CWchar *)
223 and signed
= sign
* base
224 and base
= CChar2
| CShort
| CInt
| CLong
| CLongLong
(* gccext: *)
225 and sign
= Signed
| UnSigned
227 and floatType
= CFloat
| CDouble
| CLongDouble
230 (* -------------------------------------- *)
231 and structUnion
= Struct
| Union
232 and structType
= field list
234 | DeclarationField
of field_declaration
239 | MacroDeclField
of (string * argument wrap2 list
)
240 wrap
(* optional ';'*)
243 | CppDirectiveStruct
of cpp_directive
244 | IfdefStruct
of ifdef_directive
(* * field list list *)
247 (* before unparser, I didn't have a FieldDeclList but just a Field. *)
248 and field_declaration
=
249 | FieldDeclList
of fieldkind wrap2 list
(* , *) wrap
(* ; *)
251 (* At first I thought that a bitfield could be only Signed/Unsigned.
252 * But it seems that gcc allow char i:4. C rule must say that you
253 * can cast into int so enum too, ...
256 | Simple
of name
option * fullType
257 | BitField
of name
option * fullType
*
258 info
(* : *) * constExpression
259 (* fullType => BitFieldInt | BitFieldUnsigned *)
262 (* -------------------------------------- *)
263 and enumType
= oneEnumType wrap2
(* , *) list
264 (* => string * int list *)
266 and oneEnumType
= name
* (info
(* = *) * constExpression
) option
268 (* -------------------------------------- *)
269 (* return * (params * has "...") *)
270 and functionType
= fullType
* (parameterType wrap2 list
* bool wrap
)
272 { p_namei
: name
option;
273 p_register
: bool wrap
;
276 (* => (bool (register) * fullType) list * bool *)
279 and typeQualifier
= typeQualifierbis wrap
280 and typeQualifierbis
= {const
: bool; volatile
: bool}
282 (* gccext: cppext: *)
283 and attribute
= attributebis wrap
285 | Attribute
of string
287 (* ------------------------------------------------------------------------- *)
289 (* ------------------------------------------------------------------------- *)
290 and expression
= (expressionbis
* exp_info
ref (* semantic: *)) wrap3
291 and exp_info
= exp_type
option * test
292 and exp_type
= fullType
(* Type_c.completed_and_simplified *) * local
293 and local
= LocalVar
of parse_info
| NotLocalVar
(* cocci: *)
294 and test
= Test
| NotTest
(* cocci: *)
298 (* Ident can be a enumeration constant, a simple variable, a name of a func.
299 * With cppext, Ident can also be the name of a macro. Sparse says
300 * "an identifier with a meaning is a symbol" *)
301 | Ident
of name
(* todo? more semantic info such as LocalFunc *)
303 | Constant
of constant
304 | FunCall
of expression
* argument wrap2
(* , *) list
305 (* gccext: x ? /* empty */ : y <=> x ? x : y; hence the 'option' below *)
306 | CondExpr
of expression
* expression
option * expression
308 (* should be considered as statements, bad C langage *)
309 | Sequence
of expression
* expression
310 | Assignment
of expression
* assignOp
* expression
313 | Postfix
of expression
* fixOp
314 | Infix
of expression
* fixOp
316 | Unary
of expression
* unaryOp
317 | Binary
of expression
* binaryOp
* expression
319 | ArrayAccess
of expression
* expression
321 (* field ident access *)
322 | RecordAccess
of expression
* name
323 | RecordPtAccess
of expression
* name
324 (* redundant normally, could replace it by DeRef RecordAcces *)
326 | SizeOfExpr
of expression
327 | SizeOfType
of fullType
328 | Cast
of fullType
* expression
331 | StatementExpr
of compound wrap
(* ( ) new scope *)
332 | Constructor
of fullType
* initialiser wrap2
(* , *) list
335 | ParenExpr
of expression
337 (* cppext: IfdefExpr TODO *)
339 (* cppext: normmally just expression *)
340 and argument
= (expression
, weird_argument
) Common.either
342 | ArgType
of parameterType
343 | ArgAction
of action_macro
345 (* todo: ArgStatement of statement, possibly have ghost token *)
349 (* I put string for Int and Float because int would not be enough because
350 * OCaml int are 31 bits. So simpler to do string. Same reason to have
351 * string instead of int list for the String case.
353 * note: -2 is not a constant, it is the unary operator '-'
354 * applied to constant 2. So the string must represent a positive
358 | String
of (string * isWchar
)
359 | MultiString
of string list
(* can contain MacroString, todo: more info *)
360 | Char
of (string * isWchar
) (* normally it is equivalent to Int *)
361 | Int
of (string * intType
)
362 | Float
of (string * floatType
)
364 and isWchar
= IsWchar
| IsChar
367 and unaryOp
= GetRef
| DeRef
| UnPlus
| UnMinus
| Tilde
| Not
368 | GetRefLabel
(* gccext: GetRefLabel, via &&label notation *)
369 and assignOp
= SimpleAssign
| OpAssign
of arithOp
370 and fixOp
= Dec
| Inc
372 and binaryOp
= Arith
of arithOp
| Logical
of logicalOp
375 | Plus
| Minus
| Mul
| Div
| Mod
380 | Inf
| Sup
| InfEq
| SupEq
384 and constExpression
= expression
(* => int *)
387 (* ------------------------------------------------------------------------- *)
389 (* ------------------------------------------------------------------------- *)
390 (* note: that assignement is not a statement but an expression;
391 * wonderful C langage.
393 * note: I use 'and' for type definition cos gccext allow statement as
394 * expression, so need mutual recursive type definition.
398 and statement
= statementbis wrap3
401 | Compound
of compound
(* new scope *)
402 | ExprStatement
of exprStatement
403 | Selection
of selection
(* have fakeend *)
404 | Iteration
of iteration
(* have fakeend *)
407 (* simplify cocci: only at the beginning of a compound normally *)
408 | Decl
of declaration
412 | NestedFunc
of definition
419 and labeled
= Label
of name
* statement
420 | Case
of expression
* statement
421 | CaseRange
of expression
* expression
* statement
(* gccext: *)
422 | Default
of statement
425 * old: compound = (declaration list * statement list)
426 * old: (declaration, statement) either list
427 * Simplify cocci to just have statement list, by integrating Decl in stmt.
429 * update: now introduce also the _sequencable to allow ifdef in the middle.
430 * Indeed, I now allow ifdefs in the ast but they must be only between
431 * "sequencable" elements. They can be put in a type only if this type
432 * is used in a list, like at the toplevel, used in a 'toplevel list',
433 * or inside a compound, used in a 'statement list'. I must not allow
434 * ifdef anywhere. For instance I can not make ifdef a statement
435 * cos some instruction like If accept only one statement and the
436 * ifdef directive must not take the place of a legitimate instruction.
437 * We had a similar phenomena in SmPL where we have the notion
438 * of statement and sequencable statement too. Once you have
439 * such a type of sequencable thing, then s/xx list/xx_sequencable list/
440 * and introduce the ifdef.
442 * update: those ifdefs are either passed, or present in the AST but in
443 * a flat form. To structure those flat ifdefs you have to run
444 * a transformation that will put in a tree the statements inside
445 * ifdefs branches. Cf cpp_ast_c.ml. This is for instance the difference
446 * between a IfdefStmt (flat) and IfdefStmt2 (tree structured).
449 and compound
= statement_sequencable list
451 (* cppext: easier to put at statement_list level than statement level *)
452 and statement_sequencable
=
453 | StmtElem
of statement
456 | CppDirectiveStmt
of cpp_directive
457 | IfdefStmt
of ifdef_directive
459 (* this will be build in cpp_ast_c from the previous flat IfdefStmt *)
460 | IfdefStmt2
of ifdef_directive list
* (statement_sequencable list
) list
462 and exprStatement
= expression
option
464 (* for Switch, need check that all elements in the compound start
465 * with a case:, otherwise unreachable code.
468 | If
of expression
* statement
* statement
469 | Switch
of expression
* statement
473 | While
of expression
* statement
474 | DoWhile
of statement
* expression
475 | For
of exprStatement wrap
* exprStatement wrap
* exprStatement wrap
*
478 | MacroIteration
of string * argument wrap2 list
* statement
480 and jump
= Goto
of name
482 | Return
| ReturnExpr
of expression
483 | GotoComputed
of expression
(* gccext: goto *exp ';' *)
487 and asmbody
= il
(* string list *) * colon wrap
(* : *) list
488 and colon
= Colon
of colon_option wrap2 list
489 and colon_option
= colon_option_bis wrap
490 and colon_option_bis
= ColonMisc
| ColonExpr
of expression
493 (* ------------------------------------------------------------------------- *)
495 (* ------------------------------------------------------------------------- *)
496 (* (string * ...) option cos can have empty declaration or struct tag
499 * Before I had a Typedef constructor, but why make this special case and not
500 * have StructDef, EnumDef, ... so that 'struct t {...} v' will generate 2
501 * declarations ? So I try to generalise and not have Typedef either. This
502 * requires more work in parsing. Better to separate concern.
504 * Before the need for unparser, I didn't have a DeclList but just a Decl.
506 * I am not sure what it means to declare a prototype inline, but gcc
511 | DeclList
of onedecl wrap2
(* , *) list wrap
(* ; fakestart sto *)
513 | MacroDecl
of (string * argument wrap2 list
) wrap
(* fakestart *)
516 { v_namei
: (name
* (info
(* = *) * initialiser
) option) option;
518 (* semantic: set in type annotated and used in cocci_vs_c
519 * when we transform some initialisation into affectation
521 v_type_bis
: fullType
(* Type_c.completed_and_simplified *) option ref;
523 v_local
: local_decl
; (* cocci: *)
524 v_attr
: attribute list
; (* gccext: *)
526 and storage
= storagebis
* bool (* gccext: inline or not *)
527 and storagebis
= NoSto
| StoTypedef
| Sto
of storageClass
528 and storageClass
= Auto
| Static
| Register
| Extern
530 and local_decl
= LocalDecl
| NotLocalDecl
532 (* fullType is the type used if the type should be converted to
533 an assignment. It can be adjusted in the type annotation
534 phase when typedef information is availalble *)
535 and initialiser
= initialiserbis wrap
537 | InitExpr
of expression
538 | InitList
of initialiser wrap2
(* , *) list
540 | InitDesignators
of designator list
* initialiser
541 | InitFieldOld
of string * initialiser
542 | InitIndexOld
of expression
* initialiser
544 (* ex: [2].y = x, or .y[2] or .y.x. They can be nested *)
545 and designator
= designatorbis wrap
547 | DesignatorField
of string
548 | DesignatorIndex
of expression
549 | DesignatorRange
of expression
* expression
551 (* ------------------------------------------------------------------------- *)
552 (* Function definition *)
553 (* ------------------------------------------------------------------------- *)
554 (* Normally we should define another type functionType2 because there
555 * are more restrictions on what can define a function than a pointer
556 * function. For instance a function declaration can omit the name of the
557 * parameter whereas a function definition can not. But, in some cases such
558 * as 'f(void) {', there is no name too, so I simplified and reused the
559 * same functionType type for both declaration and function definition.
561 * Also old style C does not have type in the parameter, so again simpler
562 * to abuse the functionType and allow missing type.
564 and definition
= definitionbis wrap
(* ( ) { } fakestart sto *)
567 f_type
: functionType
; (* less? a functionType2 ? *)
570 f_attr
: attribute list
; (* gccext: *)
571 f_old_c_style
: declaration list
option;
573 (* cppext: IfdefFunHeader TODO *)
575 (* ------------------------------------------------------------------------- *)
576 (* cppext: cpp directives, #ifdef, #define and #include body *)
577 (* ------------------------------------------------------------------------- *)
581 | Undef
of string wrap
583 (*| Ifdef ? no, ifdefs are handled differently, cf ifdef_directive below *)
585 and define
= string wrap
(* #define s eol *) * (define_kind
* define_val
)
588 | DefineFunc
of ((string wrap
) wrap2 list
) wrap
(* () *)
590 (* most common case; e.g. to define int constant *)
591 | DefineExpr
of expression
593 | DefineStmt
of statement
594 | DefineType
of fullType
595 | DefineDoWhileZero
of (statement
* expression
) wrap
(* do { } while(0) *)
597 | DefineFunction
of definition
598 | DefineInit
of initialiser
(* in practice only { } with possible ',' *)
600 (* TODO DefineMulti of define_val list *)
602 | DefineText
of string wrap
610 { i_include
: inc_file wrap
; (* #include s *)
611 (* cocci: computed in ? *)
612 i_rel_pos
: include_rel_pos
option ref;
613 (* cocci: cf -test incl *)
615 (* cf cpp_ast_c.ml. set to None at parsing time. *)
616 i_content
: (Common.filename
(* full path *) * program
) option;
619 | Local
of inc_elem list
620 | NonLocal
of inc_elem list
621 | Weird
of string (* ex: #include SYSTEM_H *)
622 and inc_elem
= string
624 (* cocci: to tag the first of #include <xx/> and last of #include <yy/>
626 * The first_of and last_of store the list of prefixes that was
627 * introduced by the include. On #include <a/b/x>, if the include was
628 * the first in the file, it would give in first_of the following
629 * prefixes a/b/c; a/b/; a/ ; <empty>
631 * This is set after parsing, in cocci.ml, in update_rel_pos.
633 and include_rel_pos
= {
634 first_of
: string list list
;
635 last_of
: string list list
;
640 (* todo? to specialize if someone need more info *)
641 and ifdef_directive
= (* or and 'a ifdefed = 'a list wrap *)
642 | IfdefDirective
of (ifdefkind
* matching_tag
) wrap
644 | Ifdef
(* todo? of string ? of formula_cpp ? *)
645 | IfdefElseif
(* same *)
646 | IfdefElse
(* same *)
648 (* set in Parsing_hacks.set_ifdef_parenthize_info. It internally use
649 * a global so it means if you parse the same file twice you may get
650 * different id. I try now to avoid this pb by resetting it each
651 * time I parse a file.
654 IfdefTag
of (int (* tag *) * int (* total with this tag *))
660 (* ------------------------------------------------------------------------- *)
661 (* The toplevels elements *)
662 (* ------------------------------------------------------------------------- *)
664 | Declaration
of declaration
665 | Definition
of definition
668 | CppTop
of cpp_directive
669 | IfdefTop
of ifdef_directive
(* * toplevel list *)
672 | MacroTop
of string * argument wrap2 list
* il
674 | EmptyDef
of il
(* gccext: allow redundant ';' *)
675 | NotParsedCorrectly
of il
677 | FinalDef
of info
(* EOF *)
679 (* ------------------------------------------------------------------------- *)
680 and program
= toplevel list
682 (*****************************************************************************)
684 (*****************************************************************************)
685 (* Was previously in pattern.ml, but because of the transformer,
686 * we need to decorate each token with some cocci code AND the environment
687 * for this cocci code.
689 and metavars_binding
= (Ast_cocci.meta_name
, metavar_binding_kind
) assoc
690 and metavar_binding_kind
=
691 | MetaIdVal
of string *
692 Ast_cocci.meta_name list
(* negative constraints *)
693 | MetaFuncVal
of string
694 | MetaLocalFuncVal
of string
696 | MetaExprVal
of expression
(* a "clean expr" *) *
697 (*subterm constraints, currently exprs*)
698 Ast_cocci.meta_name list
699 | MetaExprListVal
of argument wrap2 list
700 | MetaParamVal
of parameterType
701 | MetaParamListVal
of parameterType wrap2 list
703 | MetaTypeVal
of fullType
704 | MetaInitVal
of initialiser
705 | MetaDeclVal
of declaration
706 | MetaFieldVal
of field
707 | MetaStmtVal
of statement
709 (* Could also be in Lib_engine.metavars_binding2 with the ParenVal,
710 * because don't need to have the value for a position in the env of
711 * a '+'. But ParenVal or LabelVal are used only by CTL, they are not
712 * variables accessible via SmPL whereas the position can be one day
713 * so I think it's better to put MetaPosVal here *)
714 | MetaPosVal
of (Ast_cocci.fixpos
* Ast_cocci.fixpos
) (* max, min *)
716 (Common.filename
* string (*element*) * posl
* posl
) list
(* min, max *)
717 | MetaListlenVal
of int
720 (*****************************************************************************)
722 (*****************************************************************************)
724 (* convention: I often use "m" for comments as I can not use "c"
725 * (already use for c stuff) and "com" is too long.
728 (* this type will be associated to each token.
730 and comments_around
= {
731 mbefore
: Token_c.comment_like_token list
;
732 mafter
: Token_c.comment_like_token list
;
734 (* less: could remove ? do something simpler than CComment for
735 * coccinelle, cf above. *)
736 mbefore2
: comment_and_relative_pos list
;
737 mafter2
: comment_and_relative_pos list
;
739 and comment_and_relative_pos
= {
741 minfo
: Common.parse_info
;
742 (* the int represent the number of lines of difference between the
743 * current token and the comment. When on same line, this number is 0.
744 * When previous line, -1. In some way the after/before in previous
745 * record is useless because the sign of the integer can helps
746 * do the difference too, but I keep it that way.
750 * cppbetween: bool; touse? if false positive
751 * is_alone_in_line: bool; (*for labels, to avoid false positive*)
755 and comment
= Common.parse_info
756 and com
= comment list
ref
761 (*****************************************************************************)
762 (* Some constructors *)
763 (*****************************************************************************)
764 let nullQualif = ({const
=false; volatile
= false}, [])
767 let defaultInt = (BaseType
(IntType
(Si
(Signed
, CInt
))))
769 let noType () = ref (None
,NotTest
)
770 let noInstr = (ExprStatement
(None
), [])
771 let noTypedefDef () = None
773 let emptyMetavarsBinding =
774 ([]: metavars_binding
)
776 let emptyAnnotCocci =
777 (Ast_cocci.CONTEXT
(Ast_cocci.NoPos
,Ast_cocci.NOTHING
),
778 ([] : metavars_binding list
))
781 (None
: (Ast_cocci.mcodekind
* metavars_binding list
) option)
783 (* compatibility mode *)
784 let mcode_and_env_of_cocciref aref
=
787 | None
-> emptyAnnotCocci
798 (* for include, some meta information needed by cocci *)
800 ref (None
: include_rel_pos
option)
805 (* When want add some info in ast that does not correspond to
806 * an existing C element.
807 * old: or when don't want 'synchronize' on it in unparse_c.ml
808 * (now have other mark for tha matter).
810 let no_virt_pos = ({str
="";charpos
=0;line
=0;column
=0;file
=""},-1)
813 { pinfo
= FakeTok
("",no_virt_pos);
814 cocci_tag
= ref emptyAnnot;
815 comments_tag
= ref emptyComments;
820 let noi_content = (None
: ((Common.filename
* program
) option))
822 (*****************************************************************************)
824 (*****************************************************************************)
829 let unwrap_expr ((unwrap_e
, typ
), iie
) = unwrap_e
830 let rewrap_expr ((_old_unwrap_e
, typ
), iie
) newe
= ((newe
, typ
), iie
)
832 let unwrap_typeC (qu
, (typeC
, ii
)) = typeC
833 let rewrap_typeC (qu
, (typeC
, ii
)) newtypeC
= (qu
, (newtypeC
, ii
))
835 let unwrap_typeCbis (typeC
, ii
) = typeC
837 let unwrap_st (unwrap_st, ii
) = unwrap_st
839 (* ------------------------------------------------------------------------- *)
840 let mk_e unwrap_e ii
= (unwrap_e
, noType()), ii
841 let mk_e_bis unwrap_e ty ii
= (unwrap_e
, ty
), ii
843 let mk_ty typeC ii
= nQ, (typeC
, ii
)
844 let mk_tybis typeC ii
= (typeC
, ii
)
846 let mk_st unwrap_st ii
= (unwrap_st, ii
)
848 (* ------------------------------------------------------------------------- *)
849 let get_ii_typeC_take_care (typeC
, ii
) = ii
850 let get_ii_st_take_care (st
, ii
) = ii
851 let get_ii_expr_take_care (e
, ii
) = ii
853 let get_st_and_ii (st
, ii
) = st
, ii
854 let get_ty_and_ii (qu
, (typeC
, ii
)) = qu
, (typeC
, ii
)
855 let get_e_and_ii (e
, ii
) = e
, ii
858 (* ------------------------------------------------------------------------- *)
859 let get_type_expr ((unwrap_e
, typ
), iie
) = !typ
860 let set_type_expr ((unwrap_e
, oldtyp
), iie
) newtyp
=
862 (* old: (unwrap_e, newtyp), iie *)
864 let get_onlytype_expr ((unwrap_e
, typ
), iie
) =
866 | Some
(ft
,_local
), _test
-> Some ft
869 let get_onlylocal_expr ((unwrap_e
, typ
), iie
) =
871 | Some
(ft
,local
), _test
-> Some local
874 (* ------------------------------------------------------------------------- *)
875 let rewrap_str s ii
=
878 OriginTok pi
-> OriginTok
{ pi
with Common.str
= s
;}
879 | ExpandedTok
(pi
,vpi
) -> ExpandedTok
({ pi
with Common.str
= s
;},vpi
)
880 | FakeTok
(_
,vpi
) -> FakeTok
(s
,vpi
)
881 | AbstractLineTok pi
-> OriginTok
{ pi
with Common.str
= s
;})}
883 let rewrap_pinfo pi ii
=
888 (* info about the current location *)
889 let get_pi = function
891 | ExpandedTok
(_
,(pi
,_
)) -> pi
892 | FakeTok
(_
,(pi
,_
)) -> pi
893 | AbstractLineTok pi
-> pi
896 let get_opi = function
898 | ExpandedTok
(pi
,_
) -> pi
(* diff with get_pi *)
899 | FakeTok
(_
,_
) -> failwith
"no position information"
900 | AbstractLineTok pi
-> pi
904 OriginTok pi
-> pi
.Common.str
905 | ExpandedTok
(pi
,_
) -> pi
.Common.str
907 | AbstractLineTok pi
-> pi
.Common.str
912 | ExpandedTok
(_
,(pi
,_
)) -> f pi
913 | FakeTok
(_
,(pi
,_
)) -> f pi
914 | AbstractLineTok pi
-> f pi
916 let get_orig_info f ii
=
919 | ExpandedTok
(pi
,_
) -> f pi
(* diff with get_info *)
920 | FakeTok
(_
,(pi
,_
)) -> f pi
921 | AbstractLineTok pi
-> f pi
923 let make_expanded ii
=
924 {ii
with pinfo
= ExpandedTok
(get_opi ii
.pinfo
,no_virt_pos)}
926 let pos_of_info ii
= get_info (function x
-> x
.Common.charpos
) ii
927 let opos_of_info ii
= get_orig_info (function x
-> x
.Common.charpos
) ii
928 let line_of_info ii
= get_orig_info (function x
-> x
.Common.line
) ii
929 let col_of_info ii
= get_orig_info (function x
-> x
.Common.column
) ii
930 let file_of_info ii
= get_orig_info (function x
-> x
.Common.file
) ii
931 let mcode_of_info ii
= fst
(mcode_and_env_of_cocciref ii
.cocci_tag
)
932 let pinfo_of_info ii
= ii
.pinfo
933 let parse_info_of_info ii
= get_pi ii
.pinfo
935 let strloc_of_info ii
=
936 spf
"%s:%d" (file_of_info ii
) (line_of_info ii
)
940 FakeTok
(_
,_
) -> true
943 let is_origintok ii
=
945 | OriginTok pi
-> true
948 (* ------------------------------------------------------------------------- *)
949 type posrv
= Real
of Common.parse_info
| Virt
of virtual_position
951 let compare_pos ii1 ii2
=
952 let get_pos = function
953 OriginTok pi
-> Real pi
954 | FakeTok
(s
,vpi
) -> Virt vpi
955 | ExpandedTok
(pi
,vpi
) -> Virt vpi
956 | AbstractLineTok pi
-> Real pi
in (* used for printing *)
957 let pos1 = get_pos (pinfo_of_info ii1
) in
958 let pos2 = get_pos (pinfo_of_info ii2
) in
959 match (pos1,pos2) with
960 (Real p1
, Real p2
) ->
961 compare p1
.Common.charpos p2
.Common.charpos
962 | (Virt
(p1
,_
), Real p2
) ->
963 if (compare p1
.Common.charpos p2
.Common.charpos
) =|= (-1) then (-1) else 1
964 | (Real p1
, Virt
(p2
,_
)) ->
965 if (compare p1
.Common.charpos p2
.Common.charpos
) =|= 1 then 1 else (-1)
966 | (Virt
(p1
,o1
), Virt
(p2
,o2
)) ->
967 let poi1 = p1
.Common.charpos
in
968 let poi2 = p2
.Common.charpos
in
969 match compare
poi1 poi2 with
974 let equal_posl (l1
,c1
) (l2
,c2
) =
975 (l1
=|= l2
) && (c1
=|= c2
)
977 let info_to_fixpos ii
=
978 match pinfo_of_info ii
with
979 OriginTok pi
-> Ast_cocci.Real pi
.Common.charpos
980 | ExpandedTok
(_
,(pi
,offset
)) ->
981 Ast_cocci.Virt
(pi
.Common.charpos
,offset
)
982 | FakeTok
(_
,(pi
,offset
)) ->
983 Ast_cocci.Virt
(pi
.Common.charpos
,offset
)
984 | AbstractLineTok pi
-> failwith
"unexpected abstract"
987 let is_test (e
: expression
) =
988 let (_
,info
), _
= e
in
989 let (_
,test
) = !info
in
992 (*****************************************************************************)
994 (*****************************************************************************)
996 (* When we have extended the C Ast to add some info to the tokens,
997 * such as its line number in the file, we can not use anymore the
998 * ocaml '=' to compare Ast elements. To overcome this problem, to be
999 * able to use again '=', we just have to get rid of all those extra
1000 * information, to "abstract those line" (al) information.
1002 * Julia then modifies it a little to have a tokenindex, so the original
1003 * true al_info is in fact real_al_info.
1006 let al_info tokenindex x
=
1009 {charpos
= tokenindex
;
1011 column
= tokenindex
;
1013 str
= str_of_info x
});
1014 cocci_tag
= ref emptyAnnot;
1015 comments_tag
= ref emptyComments;
1018 let semi_al_info x
=
1020 cocci_tag
= ref emptyAnnot;
1021 comments_tag
= ref emptyComments;
1024 let magic_real_number = -10
1026 let real_al_info x
=
1029 {charpos
= magic_real_number;
1030 line
= magic_real_number;
1031 column
= magic_real_number;
1033 str
= str_of_info x
});
1034 cocci_tag
= ref emptyAnnot;
1035 comments_tag
= ref emptyComments;
1040 List.filter
(function (Token_c.TCommentCpp _
,_
) -> true | _
-> false) l
in
1042 (x
,{i
with Common.charpos
= magic_real_number;
1043 Common.line
= magic_real_number;
1044 Common.column
= magic_real_number}) in
1045 {mbefore
= []; (* duplicates mafter of the previous token *)
1046 mafter
= List.map
al_com (keep_cpp x
.mafter
);
1051 let al_info_cpp tokenindex x
=
1054 {charpos
= tokenindex
;
1056 column
= tokenindex
;
1058 str
= str_of_info x
});
1059 cocci_tag
= ref emptyAnnot;
1060 comments_tag
= ref (al_comments !(x
.comments_tag
));
1063 let semi_al_info_cpp x
=
1065 cocci_tag
= ref emptyAnnot;
1066 comments_tag
= ref (al_comments !(x
.comments_tag
));
1069 let real_al_info_cpp x
=
1072 {charpos
= magic_real_number;
1073 line
= magic_real_number;
1074 column
= magic_real_number;
1076 str
= str_of_info x
});
1077 cocci_tag
= ref emptyAnnot;
1078 comments_tag
= ref (al_comments !(x
.comments_tag
));
1082 (*****************************************************************************)
1084 (*****************************************************************************)
1086 (* Transform a list of arguments (or parameters) where the commas are
1087 * represented via the wrap2 and associated with an element, with
1088 * a list where the comma are on their own. f(1,2,2) was
1089 * [(1,[]); (2,[,]); (2,[,])] and become [1;',';2;',';2].
1091 * Used in cocci_vs_c.ml, to have a more direct correspondance between
1092 * the ast_cocci of julia and ast_c.
1094 let rec (split_comma
: 'a wrap2 list
-> ('a
, il
) either list
) =
1099 then (Left e
)::split_comma xs
1100 else Right ii
::Left e
::split_comma xs
1102 let rec (unsplit_comma
: ('a
, il
) either list
-> 'a wrap2 list
) =
1105 | Right ii
::Left e
::xs
->
1106 (e
, ii
)::unsplit_comma xs
1108 let empty_ii = [] in
1109 (e
, empty_ii)::unsplit_comma xs
1116 (*****************************************************************************)
1117 (* Helpers, could also be put in lib_parsing_c.ml instead *)
1118 (*****************************************************************************)
1120 (* should maybe be in pretty_print_c ? *)
1122 let s_of_inc_file inc_file
=
1124 | Local xs
-> xs
+> Common.join
"/"
1125 | NonLocal xs
-> xs
+> Common.join
"/"
1128 let s_of_inc_file_bis inc_file
=
1130 | Local xs
-> "\"" ^ xs
+> Common.join
"/" ^
"\""
1131 | NonLocal xs
-> "<" ^ xs
+> Common.join
"/" ^
">"
1134 let fieldname_of_fieldkind fieldkind
=
1135 match fieldkind
with
1136 | Simple
(sopt
, ft
) -> sopt
1137 | BitField
(sopt
, ft
, info
, expr
) -> sopt
1140 let s_of_attr attr
=
1142 +> List.map
(fun (Attribute s
, ii
) -> s
)
1146 (* ------------------------------------------------------------------------- *)
1147 let str_of_name ident
=
1149 | RegularName
(s
,ii
) -> s
1150 | CppConcatenatedName xs
->
1151 xs
+> List.map
(fun (x
,iiop
) -> unwrap x
) +> Common.join
"##"
1152 | CppVariadicName
(s
, ii
) -> "##" ^ s
1153 | CppIdentBuilder
((s
,iis
), xs
) ->
1155 (xs
+> List.map
(fun ((x
,iix
), iicomma
) -> x
) +> Common.join
",") ^
1158 let get_s_and_ii_of_name name
=
1160 | RegularName
(s
, iis
) -> s
, iis
1161 | CppIdentBuilder
((s
, iis
), xs
) -> s
, iis
1162 | CppVariadicName
(s
,iis
) ->
1163 let (iop
, iis
) = Common.tuple_of_list2 iis
in
1165 | CppConcatenatedName xs
->
1167 | [] -> raise Impossible
1168 | ((s
,iis
),noiiop
)::xs
->
1172 let get_s_and_info_of_name name
=
1173 let (s
,ii
) = get_s_and_ii_of_name name
in
1176 let info_of_name name
=
1177 let (s
,ii
) = get_s_and_ii_of_name name
in
1180 let ii_of_name name
=
1181 let (s
,ii
) = get_s_and_ii_of_name name
in
1184 let get_local_ii_of_expr_inlining_ii_of_name e
=
1185 let (ebis
,_
),ii
= e
in
1187 | Ident name
, noii ->
1190 | RecordAccess
(e
, name
), ii
->
1191 ii
@ ii_of_name name
1192 | RecordPtAccess
(e
, name
), ii
->
1193 ii
@ ii_of_name name
1197 let get_local_ii_of_tybis_inlining_ii_of_name ty
=
1199 | TypeName
(name
, _typ
), [] -> ii_of_name name
1202 (* the following is used to obtain the argument to LocalVar *)
1203 let info_of_type ft
=
1204 let (qu
, ty
) = ft
in
1205 (* bugfix: because of string->name, the ii can be deeper *)
1206 let ii = get_local_ii_of_tybis_inlining_ii_of_name ty
in
1209 | [] -> failwith
"type has no text; need to think again"
1211 (* only Label and Goto have name *)
1212 let get_local_ii_of_st_inlining_ii_of_name st
=
1214 | Labeled
(Label
(name
, st
)), ii -> ii_of_name name
@ ii
1215 | Jump
(Goto name
), ii ->
1216 let (i1
, i3
) = Common.tuple_of_list2
ii in
1217 [i1
] @ ii_of_name name
@ [i3
]
1222 (* ------------------------------------------------------------------------- *)
1223 let name_of_parameter param
=
1224 param
.p_namei
+> Common.map_option
(str_of_name)