Release coccinelle-0.2.4rc6
[bpt/coccinelle.git] / parsing_c / lexer_c.mll
1 {
2 (* Yoann Padioleau
3 *
4 * Copyright (C) 2002, 2006, 2007, 2008, 2009, Ecole des Mines de Nantes
5 *
6 * This program is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU General Public License (GPL)
8 * version 2 as published by the Free Software Foundation.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * file license.txt for more details.
14 *)
15 open Common
16
17 open Parser_c
18
19 open Ast_c (* to factorise tokens, OpAssign, ... *)
20
21 (*****************************************************************************)
22 (*
23 * subtil: ocamllex use side effect on lexbuf, so must take care.
24 * For instance must do
25 *
26 * let info = tokinfo lexbuf in
27 * TComment (info +> tok_add_s (comment lexbuf))
28 *
29 * and not
30 *
31 * TComment (tokinfo lexbuf +> tok_add_s (comment lexbuf))
32 *
33 * because of the "wierd" order of evaluation of OCaml.
34 *
35 *
36 *
37 * note: can't use Lexer_parser._lexer_hint here to do different
38 * things, because now we call the lexer to get all the tokens
39 * (tokens_all), and then we parse. So we can't have the _lexer_hint
40 * info here. We can have it only in parse_c. For the same reason, the
41 * typedef handling here is now useless.
42 *)
43 (*****************************************************************************)
44
45 (*****************************************************************************)
46 (* Wrappers *)
47 (*****************************************************************************)
48 let pr2, pr2_once = Common.mk_pr2_wrappers Flag_parsing_c.verbose_lexing
49
50 (*****************************************************************************)
51
52
53 exception Lexical of string
54
55 let tok lexbuf = Lexing.lexeme lexbuf
56
57 let tokinfo lexbuf =
58 {
59 pinfo = Ast_c.OriginTok {
60 Common.charpos = Lexing.lexeme_start lexbuf;
61 Common.str = Lexing.lexeme lexbuf;
62 (* info filled in a post-lexing phase *)
63 Common.line = -1;
64 Common.column = -1;
65 Common.file = "";
66 };
67 (* must generate a new ref each time, otherwise share *)
68 cocci_tag = ref Ast_c.emptyAnnot;
69 comments_tag = ref Ast_c.emptyComments;
70 }
71
72 (* cppext: must generate a new ref each time, otherwise share *)
73 let no_ifdef_mark () = ref (None: (int * int) option)
74
75 let tok_add_s s ii = Ast_c.rewrap_str ((Ast_c.str_of_info ii) ^ s) ii
76
77
78 (* opti: less convenient, but using a hash is faster than using a match *)
79 let keyword_table = Common.hash_of_list [
80
81 (* c: *)
82 "void", (fun ii -> Tvoid ii);
83 "char", (fun ii -> Tchar ii);
84 "short", (fun ii -> Tshort ii);
85 "int", (fun ii -> Tint ii);
86 "long", (fun ii -> Tlong ii);
87 "float", (fun ii -> Tfloat ii);
88 "double", (fun ii -> Tdouble ii);
89 "size_t", (fun ii -> Tsize_t ii);
90 "ssize_t", (fun ii -> Tssize_t ii);
91 "ptrdiff_t", (fun ii -> Tptrdiff_t ii);
92
93 "unsigned", (fun ii -> Tunsigned ii);
94 "signed", (fun ii -> Tsigned ii);
95
96 "auto", (fun ii -> Tauto ii);
97 "register", (fun ii -> Tregister ii);
98 "extern", (fun ii -> Textern ii);
99 "static", (fun ii -> Tstatic ii);
100
101 "const", (fun ii -> Tconst ii);
102 "volatile", (fun ii -> Tvolatile ii);
103
104 "struct", (fun ii -> Tstruct ii);
105 "union", (fun ii -> Tunion ii);
106 "enum", (fun ii -> Tenum ii);
107 "typedef", (fun ii -> Ttypedef ii);
108
109 "if", (fun ii -> Tif ii);
110 "else", (fun ii -> Telse ii);
111 "break", (fun ii -> Tbreak ii);
112 "continue", (fun ii -> Tcontinue ii);
113 "switch", (fun ii -> Tswitch ii);
114 "case", (fun ii -> Tcase ii);
115 "default", (fun ii -> Tdefault ii);
116 "for", (fun ii -> Tfor ii);
117 "do", (fun ii -> Tdo ii);
118 "while", (fun ii -> Twhile ii);
119 "return", (fun ii -> Treturn ii);
120 "goto", (fun ii -> Tgoto ii);
121
122 "sizeof", (fun ii -> Tsizeof ii);
123
124
125 (* gccext: cppext: linuxext: synonyms *)
126 "asm", (fun ii -> Tasm ii);
127 "__asm__", (fun ii -> Tasm ii);
128 "__asm", (fun ii -> Tasm ii);
129
130 "inline", (fun ii -> Tinline ii);
131 "__inline__", (fun ii -> Tinline ii);
132 "__inline", (fun ii -> Tinline ii);
133
134 "__attribute__", (fun ii -> Tattribute ii);
135 "__attribute", (fun ii -> Tattribute ii);
136
137 "typeof", (fun ii -> Ttypeof ii);
138 "__typeof__", (fun ii -> Ttypeof ii);
139 "__typeof", (fun ii -> Ttypeof ii);
140
141 (* found a lot in expanded code *)
142 "__extension__", (fun ii -> TattributeNoarg ii);
143
144
145 (* gccext: alias *)
146 "__signed__", (fun ii -> Tsigned ii);
147
148 "__const__", (fun ii -> Tconst ii);
149 "__const", (fun ii -> Tconst ii);
150
151 "__volatile__", (fun ii -> Tvolatile ii);
152 "__volatile", (fun ii -> Tvolatile ii);
153
154 (* windowsext: *)
155 "__declspec", (fun ii -> Tattribute ii);
156
157 "__stdcall", (fun ii -> TattributeNoarg ii);
158 "__cdecl", (fun ii -> TattributeNoarg ii);
159 "WINAPI", (fun ii -> TattributeNoarg ii);
160 "APIENTRY", (fun ii -> TattributeNoarg ii);
161 "CALLBACK", (fun ii -> TattributeNoarg ii);
162
163 (* c99: *)
164 (* no just "restrict" ? maybe for backward compatibility they avoided
165 * to use restrict which people may have used in their program already
166 *)
167 "__restrict", (fun ii -> Trestrict ii);
168 "__restrict__", (fun ii -> Trestrict ii);
169
170 ]
171
172 let error_radix s =
173 ("numeric " ^ s ^ " constant contains digits beyond the radix:")
174
175 (* julia: functions for figuring out the type of integers *)
176
177 let is_long_dec s int uint long ulong =
178 match !Flag_parsing_c.int_thresholds with
179 None -> int
180 | Some (_,_,uint_threshold,long_threshold,ulong_threshold) ->
181 let bn = Big_int.big_int_of_string s in
182 if Big_int.ge_big_int bn ulong_threshold
183 then ulong
184 else
185 if Big_int.ge_big_int bn long_threshold
186 then long
187 else
188 if Big_int.ge_big_int bn uint_threshold
189 then long
190 else int
191
192 let is_long_ho s int uint long ulong drop bpd count =
193 match !Flag_parsing_c.int_thresholds with
194 None -> int
195 | Some (uint_sz,ulong_sz,_,_,_) ->
196 let len = String.length s in
197 (* this assumes that all of the hex/oct digits are significant *)
198 (* drop is 2 for hex (0x) and 1 for oct (0) *)
199 let s = String.sub s drop (len - drop) in
200 let len =
201 ((len-drop) * bpd) -
202 (count (int_of_string("0x"^(String.sub s 0 1)))) in
203 if len < uint_sz
204 then int
205 else
206 if len = uint_sz
207 then uint
208 else
209 if len < ulong_sz
210 then long
211 else ulong
212
213 let is_long_oct s int uint long ulong =
214 is_long_ho s int uint long ulong 1 3
215 (* stupid, but probably more efficient than taking logs *)
216 (function 0 -> 3 | 1 -> 2 | n when n < 4 -> 1 | _ -> 0)
217 let is_long_hex s int uint long ulong =
218 is_long_ho s int uint long ulong 2 4
219 (* stupid, but probably more efficient than taking logs *)
220 (function 0 -> 4 | 1 -> 3 | n when n < 4 -> 2 | n when n < 8 -> 1
221 | _ -> 0)
222
223 let sint = (Signed,CInt)
224 let uint = (UnSigned,CInt)
225 let slong = (Signed,CLong)
226 let ulong = (UnSigned,CLong)
227
228 }
229
230 (*****************************************************************************)
231 let letter = ['A'-'Z' 'a'-'z' '_']
232 let digit = ['0'-'9']
233
234 (* not used for the moment *)
235 let punctuation = ['!' '"' '#' '%' '&' '\'' '(' ')' '*' '+' ',' '-' '.' '/' ':'
236 ';' '<' '=' '>' '?' '[' '\\' ']' '^' '{' '|' '}' '~']
237 let space = [' ' '\t' '\n' '\r' '\011' '\012' ]
238 let additionnal = [ ' ' '\b' '\t' '\011' '\n' '\r' '\007' ]
239 (* 7 = \a = bell in C. this is not the only char allowed !!
240 * ex @ and $ ` are valid too
241 *)
242
243 let cchar = (letter | digit | punctuation | additionnal)
244
245 let sp = [' ' '\t']+
246 let spopt = [' ' '\t']*
247
248 let dec = ['0'-'9']
249 let oct = ['0'-'7']
250 let hex = ['0'-'9' 'a'-'f' 'A'-'F']
251
252 let decimal = ('0' | (['1'-'9'] dec*))
253 let octal = ['0'] oct+
254 let hexa = ("0x" |"0X") hex+
255
256
257 let pent = dec+
258 let pfract = dec+
259 let sign = ['-' '+']
260 let exp = ['e''E'] sign? dec+
261 let real = pent exp | ((pent? '.' pfract | pent '.' pfract? ) exp?)
262
263 let id = letter (letter | digit) *
264
265 (*****************************************************************************)
266 rule token = parse
267
268 (* ----------------------------------------------------------------------- *)
269 (* spacing/comments *)
270 (* ----------------------------------------------------------------------- *)
271
272 (* note: this lexer generate tokens for comments!! so can not give
273 * this lexer as-is to the parsing function. The caller must preprocess
274 * it, e.g. by using techniques like cur_tok ref in parse_c.ml.
275 *
276 * update: we now also generate a separate token for newlines, so now
277 * the caller may also have to reagglomerate all those commentspace
278 * tokens if he was assuming that spaces were agglomerate in a single
279 * token.
280 *)
281
282 | ['\n'] [' ' '\t' '\r' '\011' '\012' ]*
283 (* starting a new line; the newline character followed by whitespace *)
284 { TCommentNewline (tokinfo lexbuf) }
285 | [' ' '\t' '\r' '\011' '\012' ]+
286 { TCommentSpace (tokinfo lexbuf) }
287 | "/*"
288 { let info = tokinfo lexbuf in
289 let com = comment lexbuf in
290
291 let info' = info +> tok_add_s com in
292 let s = Ast_c.str_of_info info' in
293 (* could be more flexible, use [\t ]* instead of hardcoded
294 * single space. *)
295 match s with
296 | "/* {{coccinelle:skip_start}} */" ->
297 TCommentSkipTagStart (info')
298 | "/* {{coccinelle:skip_end}} */" ->
299 TCommentSkipTagEnd (info')
300 | _ -> TComment(info')
301 }
302
303
304 (* C++ comment are allowed via gccext, but normally they are deleted by cpp.
305 * So need this here only when dont call cpp before.
306 * note that we don't keep the trailing \n; it will be in another token.
307 *)
308 | "//" [^'\r' '\n' '\011']* { TComment (tokinfo lexbuf) }
309
310 (* ----------------------------------------------------------------------- *)
311 (* cpp *)
312 (* ----------------------------------------------------------------------- *)
313
314 (* old:
315 * | '#' { endline lexbuf} // should be line, and not endline
316 * and endline = parse | '\n' { token lexbuf}
317 * | _ { endline lexbuf}
318 *)
319
320 (* less?:
321 * have found a # #else in "newfile-2.6.c", legal ? and also a #/* ...
322 * => just "#" -> token {lexbuf} (that is ignore)
323 * il y'a 1 #elif sans rien apres
324 * il y'a 1 #error sans rien apres
325 * il y'a 2 mov dede, #xxx qui genere du coup exn car
326 * entouré par des #if 0
327 * => make as for comment, call a comment_cpp that when #endif finish the
328 * comment and if other cpp stuff raise exn
329 * il y'a environ 10 #if(xxx) ou le ( est collé direct
330 * il y'a des include"" et include<
331 * il y'a 1 ` (derriere un #ifndef linux)
332 *)
333
334
335
336 (* ---------------------- *)
337 (* misc *)
338 (* ---------------------- *)
339
340 (* bugfix: I want now to keep comments for the cComment study
341 * so cant do: sp [^'\n']+ '\n'
342 * http://gcc.gnu.org/onlinedocs/gcc/Pragmas.html
343 *)
344
345 | "#" spopt "pragma" sp [^'\n']* '\n'
346 | "#" spopt "ident" sp [^'\n']* '\n'
347 | "#" spopt "line" sp [^'\n']* '\n'
348 | "#" spopt "error" sp [^'\n']* '\n'
349 | "#" spopt "warning" sp [^'\n']* '\n'
350 | "#" spopt "abort" sp [^'\n']* '\n'
351 { TCppDirectiveOther (tokinfo lexbuf) }
352
353 | "#" [' ' '\t']* '\n'
354 { TCppDirectiveOther (tokinfo lexbuf) }
355
356 (* only after cpp, ex: # 1 "include/linux/module.h" 1 *)
357 | "#" sp pent sp '"' [^ '"']* '"' (spopt pent)* spopt '\n'
358 { TCppDirectiveOther (tokinfo lexbuf) }
359
360
361
362 (* ---------------------- *)
363 (* #define, #undef *)
364 (* ---------------------- *)
365
366 (* the rest of the lexing/parsing of define is done in fix_tokens_define
367 * where we parse until a TCppEscapedNewline and generate a TDefEol
368 *)
369 | "#" [' ' '\t']* "define" { TDefine (tokinfo lexbuf) }
370
371 (* note: in some cases can have stuff after the ident as in #undef XXX 50,
372 * but I currently don't handle it cos I think it's bad code.
373 *)
374 | (("#" [' ' '\t']* "undef" [' ' '\t']+) as _undef) (id as id)
375 { let info = tokinfo lexbuf in
376 TUndef (id, info)
377 (*+> tok_add_s (cpp_eat_until_nl lexbuf))*)
378 }
379
380
381 (* ---------------------- *)
382 (* #include *)
383 (* ---------------------- *)
384
385 (* The difference between a local "" and standard <> include is computed
386 * later in parser_c.mly. So redo a little bit of lexing there; ugly but
387 * simpler to generate a single token here. *)
388 | (("#" [' ''\t']* "include" [' ' '\t']*) as includes)
389 (('"' ([^ '"']+) '"' |
390 '<' [^ '>']+ '>' |
391 ['A'-'Z''_']+
392 ) as filename)
393 { let info = tokinfo lexbuf in
394 TInclude (includes, filename, Ast_c.noInIfdef(), info)
395 }
396 (* gccext: found in glibc *)
397 | (("#" [' ''\t']* "include_next" [' ' '\t']*) as includes)
398 (('"' ([^ '"']+) '"' |
399 '<' [^ '>']+ '>' |
400 ['A'-'Z''_']+
401 ) as filename)
402 { let info = tokinfo lexbuf in
403 TInclude (includes, filename, Ast_c.noInIfdef(), info)
404 }
405
406 (* ---------------------- *)
407 (* #ifdef *)
408 (* ---------------------- *)
409
410 (* The ifdef_mark will be set later in Parsing_hacks.set_ifdef_parenthize_info
411 * when working on the ifdef view.
412 *)
413
414 (* '0'+ because sometimes it is a #if 000 *)
415 | "#" [' ' '\t']* "if" [' ' '\t']* '0'+ (* [^'\n']* '\n' *)
416 { let info = tokinfo lexbuf in
417 TIfdefBool (false, no_ifdef_mark(), info)
418 (* +> tok_add_s (cpp_eat_until_nl lexbuf)*)
419 }
420
421 | "#" [' ' '\t']* "if" [' ' '\t']* '1' (* [^'\n']* '\n' *)
422 { let info = tokinfo lexbuf in
423 TIfdefBool (true, no_ifdef_mark(), info)
424
425 }
426
427 (* DO NOT cherry pick to lexer_cplusplus !!! often used for the extern "C" { *)
428 | "#" [' ' '\t']* "if" sp "defined" sp "(" spopt "__cplusplus" spopt ")" [^'\n']* '\n'
429 { let info = tokinfo lexbuf in
430 TIfdefMisc (false, no_ifdef_mark(), info)
431 }
432
433 (* DO NOT cherry pick to lexer_cplusplus !!! *)
434 | "#" [' ' '\t']* "ifdef" [' ' '\t']* "__cplusplus" [^'\n']* '\n'
435 { let info = tokinfo lexbuf in
436 TIfdefMisc (false, no_ifdef_mark(), info)
437 }
438
439 (* in glibc *)
440 | "#" spopt ("ifdef"|"if") sp "__STDC__"
441 { let info = tokinfo lexbuf in
442 TIfdefVersion (true, no_ifdef_mark(),
443 info +> tok_add_s (cpp_eat_until_nl lexbuf))
444 }
445
446
447 (* linuxext: different possible variations (we do not manage all of them):
448
449 #if LINUX_VERSION_CODE >= KERNEL_VERSION(2,4,0)
450 #if LINUX_VERSION_CODE <= KERNEL_VERSION(2,4,2)
451 #if LINUX_VERSION_CODE < KERNEL_VERSION(2,5,0)
452 #if LINUX_VERSION_CODE > KERNEL_VERSION(2,3,0)
453 #if LINUX_VERSION_CODE < 0x020600
454 #if LINUX_VERSION_CODE >= 0x2051c
455 #if (LINUX_VERSION_CODE < KERNEL_VERSION(2,5,0))
456 #if !(LINUX_VERSION_CODE > KERNEL_VERSION(2,5,73))
457 #if STREAMER_IOCTL && (LINUX_VERSION_CODE < KERNEL_VERSION(2,5,0))
458 #if LINUX_VERSION_CODE >= KERNEL_VERSION(2,4,20) && LINUX_VERSION_CODE < KERNEL_VERSION(2,5,0)
459 #if LINUX_VERSION_CODE >= KERNEL_VERSION(2,4,20) && \
460 # if defined(MODULE) && LINUX_VERSION_CODE >= KERNEL_VERSION(2,1,30)
461 #if LINUX_VERSION_CODE > LinuxVersionCode(2,3,12)
462 #elif LINUX_VERSION_CODE >= KERNEL_VERSION(2,1,93)
463 #ifndef LINUX_VERSION_CODE
464 #if LINUX_VERSION_CODE < ASC_LINUX_VERSION(2,2,0) || \
465 (LINUX_VERSION_CODE > ASC_LINUX_VERSION(2,3,0) && \
466 LINUX_VERSION_CODE < ASC_LINUX_VERSION(2,4,0))
467 #if (KERNEL_VERSION(2,4,0) > LINUX_VERSION_CODE)
468 #if LINUX_VERSION_CODE >= ASC_LINUX_VERSION(1,3,0)
469 # if defined(MODULE) && LINUX_VERSION_CODE >= KERNEL_VERSION(2,1,30)
470
471 *)
472
473 (* linuxext: must be before the generic rules for if and ifdef *)
474 | "#" spopt "if" sp "("? "LINUX_VERSION_CODE" sp (">=" | ">") sp
475 { let info = tokinfo lexbuf in
476 TIfdefVersion (true, no_ifdef_mark(),
477 info +> tok_add_s (cpp_eat_until_nl lexbuf))
478 }
479 (* linuxext: *)
480 | "#" spopt "if" sp "!" "("? "LINUX_VERSION_CODE" sp (">=" | ">") sp
481 | "#" spopt "if" sp ['(']? "LINUX_VERSION_CODE" sp ("<=" | "<") sp
482
483 { let info = tokinfo lexbuf in
484 TIfdefVersion (false, no_ifdef_mark(),
485 info +> tok_add_s (cpp_eat_until_nl lexbuf))
486 }
487
488
489
490
491 (* can have some ifdef 0 hence the letter|digit even at beginning of word *)
492 | "#" [' ''\t']* "ifdef" [' ''\t']+ (letter|digit) ((letter|digit)*) [' ''\t']*
493 { TIfdef (no_ifdef_mark(), tokinfo lexbuf) }
494 | "#" [' ''\t']* "ifndef" [' ''\t']+ (letter|digit) ((letter|digit)*) [' ''\t']*
495 { TIfdef (no_ifdef_mark(), tokinfo lexbuf) }
496 | "#" [' ''\t']* "if" [' ' '\t']+
497 { let info = tokinfo lexbuf in
498 TIfdef (no_ifdef_mark(), info +> tok_add_s (cpp_eat_until_nl lexbuf))
499 }
500 | "#" [' ' '\t']* "if" '('
501 { let info = tokinfo lexbuf in
502 TIfdef (no_ifdef_mark(), info +> tok_add_s (cpp_eat_until_nl lexbuf))
503 }
504
505 | "#" [' ' '\t']* "elif" [' ' '\t']+
506 { let info = tokinfo lexbuf in
507 TIfdefelif (no_ifdef_mark(), info +> tok_add_s (cpp_eat_until_nl lexbuf))
508 }
509
510
511 (* bugfix: can have #endif LINUX but at the same time if I eat everything
512 * until next line, I may miss some TComment which for some tools
513 * are important such as aComment
514 *)
515 | "#" [' ' '\t']* "endif" (*[^'\n']* '\n'*) {
516 TEndif (no_ifdef_mark(), tokinfo lexbuf)
517 }
518 (* can be at eof *)
519 (*| "#" [' ' '\t']* "endif" { TEndif (tokinfo lexbuf) }*)
520
521 | "#" [' ' '\t']* "else" [' ' '\t' '\n']
522 { TIfdefelse (no_ifdef_mark(), tokinfo lexbuf) }
523
524
525
526
527 (* ---------------------- *)
528 (* #define body *)
529 (* ---------------------- *)
530
531 (* only in cpp directives normally *)
532 | "\\" '\n' { TCppEscapedNewline (tokinfo lexbuf) }
533
534 (* We must generate separate tokens for #, ## and extend the grammar.
535 * Note there can be "elaborated" idents in many different places, in
536 * expression but also in declaration, in function name. So having 3 tokens
537 * for an ident does not work well with how we add info in
538 * ast_c. Was easier to generate just one token, just one info,
539 * even if have later to reanalyse those tokens and unsplit. But then,
540 * handling C++ lead to having not just a string for ident but something
541 * more complex. Also when we want to parse elaborated function headers
542 * (e.g. void METH(foo)(int x)), we need anyway to go from a string
543 * to something more. So having also for C something more than just
544 * string for ident is natural.
545 *
546 * todo: our heuristics in parsing_hacks rely on TIdent. So maybe
547 * an easier solution would be to augment the TIdent type such as
548 * TIdent of string * info * cpp_ident_additionnal_info
549 *
550 * old:
551 * | id ([' ''\t']* "##" [' ''\t']* id)+
552 * { let info = tokinfo lexbuf in
553 * TIdent (tok lexbuf, info)
554 * }
555 * | "##" spopt id
556 * { let info = tokinfo lexbuf in
557 * TIdent (tok lexbuf, info)
558 * }
559 *
560 *)
561 (* cppext: string concatenation of idents, also ##args for variadic macro. *)
562 | "##" { TCppConcatOp (tokinfo lexbuf) }
563
564 (* cppext: stringification.
565 * bugfix: this case must be after the other cases such as #endif
566 * otherwise take precedent.
567 *)
568 | "#" spopt id
569 { let info = tokinfo lexbuf in
570 TIdent (tok lexbuf, info)
571 }
572 (* the ... next to id, e.g. arg..., works with ##, e.g. ##arg *)
573 | ((id as s) "...")
574 { TDefParamVariadic (s, tokinfo lexbuf) }
575
576
577
578
579
580 (* ----------------------------------------------------------------------- *)
581 (* C symbols *)
582 (* ----------------------------------------------------------------------- *)
583 (* stdC:
584 ... && -= >= ~ + ; ]
585 <<= &= -> >> % , < ^
586 >>= *= /= ^= & - = {
587 != ++ << |= ( . > |
588 %= += <= || ) / ? }
589 -- == ! * : [
590 recent addition: <: :> <% %>
591 only at processing: %: %:%: # ##
592 *)
593
594
595 | '[' { TOCro(tokinfo lexbuf) } | ']' { TCCro(tokinfo lexbuf) }
596 | '(' { TOPar(tokinfo lexbuf) } | ')' { TCPar(tokinfo lexbuf) }
597 | '{' { TOBrace(tokinfo lexbuf) } | '}' { TCBrace(tokinfo lexbuf) }
598
599 | '+' { TPlus(tokinfo lexbuf) } | '*' { TMul(tokinfo lexbuf) }
600 | '-' { TMinus(tokinfo lexbuf) } | '/' { TDiv(tokinfo lexbuf) }
601 | '%' { TMod(tokinfo lexbuf) }
602
603 | "++"{ TInc(tokinfo lexbuf) } | "--"{ TDec(tokinfo lexbuf) }
604
605 | "=" { TEq(tokinfo lexbuf) }
606
607 | "-=" { TAssign (OpAssign Minus, (tokinfo lexbuf))}
608 | "+=" { TAssign (OpAssign Plus, (tokinfo lexbuf))}
609 | "*=" { TAssign (OpAssign Mul, (tokinfo lexbuf))}
610 | "/=" { TAssign (OpAssign Div, (tokinfo lexbuf))}
611 | "%=" { TAssign (OpAssign Mod, (tokinfo lexbuf))}
612 | "&=" { TAssign (OpAssign And, (tokinfo lexbuf))}
613 | "|=" { TAssign (OpAssign Or, (tokinfo lexbuf)) }
614 | "^=" { TAssign (OpAssign Xor, (tokinfo lexbuf))}
615 | "<<=" {TAssign (OpAssign DecLeft, (tokinfo lexbuf)) }
616 | ">>=" {TAssign (OpAssign DecRight, (tokinfo lexbuf))}
617
618 | "==" { TEqEq(tokinfo lexbuf) } | "!=" { TNotEq(tokinfo lexbuf) }
619 | ">=" { TSupEq(tokinfo lexbuf) } | "<=" { TInfEq(tokinfo lexbuf) }
620 | "<" { TInf(tokinfo lexbuf) } | ">" { TSup(tokinfo lexbuf) }
621
622 | "&&" { TAndLog(tokinfo lexbuf) } | "||" { TOrLog(tokinfo lexbuf) }
623 | ">>" { TShr(tokinfo lexbuf) } | "<<" { TShl(tokinfo lexbuf) }
624 | "&" { TAnd(tokinfo lexbuf) } | "|" { TOr(tokinfo lexbuf) }
625 | "^" { TXor(tokinfo lexbuf) }
626 | "..." { TEllipsis(tokinfo lexbuf) }
627 | "->" { TPtrOp(tokinfo lexbuf) } | '.' { TDot(tokinfo lexbuf) }
628 | ',' { TComma(tokinfo lexbuf) }
629 | ";" { TPtVirg(tokinfo lexbuf) }
630 | "?" { TWhy(tokinfo lexbuf) } | ":" { TDotDot(tokinfo lexbuf) }
631 | "!" { TBang(tokinfo lexbuf) } | "~" { TTilde(tokinfo lexbuf) }
632
633 | "<:" { TOCro(tokinfo lexbuf) } | ":>" { TCCro(tokinfo lexbuf) }
634 | "<%" { TOBrace(tokinfo lexbuf) } | "%>" { TCBrace(tokinfo lexbuf) }
635
636
637
638 (* ----------------------------------------------------------------------- *)
639 (* C keywords and ident *)
640 (* ----------------------------------------------------------------------- *)
641
642 (* StdC: must handle at least name of length > 509, but can
643 * truncate to 31 when compare and truncate to 6 and even lowerise
644 * in the external linkage phase
645 *)
646 | letter (letter | digit) *
647 { let info = tokinfo lexbuf in
648 let s = tok lexbuf in
649 Common.profile_code "C parsing.lex_ident" (fun () ->
650 match Common.optionise (fun () -> Hashtbl.find keyword_table s)
651 with
652 | Some f -> f info
653
654 (* parse_typedef_fix.
655 * if Lexer_parser.is_typedef s
656 * then TypedefIdent (s, info)
657 * else TIdent (s, info)
658 *
659 * update: now this is no more useful, cos
660 * as we use tokens_all, it first parse all as an ident and
661 * later transform an indent in a typedef. so the typedef job is
662 * now done in parse_c.ml.
663 *)
664
665 | None -> TIdent (s, info)
666 )
667 }
668 (* gccext: apparently gcc allows dollar in variable names. found such
669 * thing a few time in linux and in glibc. No need look in keyword_table
670 * here.
671 *)
672 | (letter | '$') (letter | digit | '$') *
673 {
674 let info = tokinfo lexbuf in
675 let s = tok lexbuf in
676 pr2 ("LEXER: identifier with dollar: " ^ s);
677 TIdent (s, info)
678 }
679
680
681 (* ----------------------------------------------------------------------- *)
682 (* C constant *)
683 (* ----------------------------------------------------------------------- *)
684
685 | "'"
686 { let info = tokinfo lexbuf in
687 let s = char lexbuf in
688 TChar ((s, IsChar), (info +> tok_add_s (s ^ "'")))
689 }
690 | '"'
691 { let info = tokinfo lexbuf in
692 let s = string lexbuf in
693 TString ((s, IsChar), (info +> tok_add_s (s ^ "\"")))
694 }
695 (* wide character encoding, TODO L'toto' valid ? what is allowed ? *)
696 | 'L' "'"
697 { let info = tokinfo lexbuf in
698 let s = char lexbuf in
699 TChar ((s, IsWchar), (info +> tok_add_s (s ^ "'")))
700 }
701 | 'L' '"'
702 { let info = tokinfo lexbuf in
703 let s = string lexbuf in
704 TString ((s, IsWchar), (info +> tok_add_s (s ^ "\"")))
705 }
706
707
708 (* Take care of the order ? No because lex tries the longest match. The
709 * strange diff between decimal and octal constant semantic is not
710 * understood too by refman :) refman:11.1.4, and ritchie.
711 *)
712
713 | decimal as x
714 { TInt ((x, is_long_dec x sint slong slong ulong), tokinfo lexbuf) }
715 | hexa as x
716 { TInt ((x, is_long_hex x sint uint slong ulong), tokinfo lexbuf) }
717 | octal as x
718 { TInt ((x, is_long_oct x sint uint slong ulong), tokinfo lexbuf) }
719 | ((decimal as s) ['u' 'U']) as x
720 { TInt ((x, is_long_dec s uint uint ulong ulong), tokinfo lexbuf) }
721 | ((hexa as s) ['u' 'U']) as x
722 { TInt ((x, is_long_hex s uint uint ulong ulong), tokinfo lexbuf) }
723 | ((octal as s) ['u' 'U']) as x
724 { TInt ((x, is_long_oct s uint uint ulong ulong), tokinfo lexbuf) }
725 | (( decimal as s) ['l' 'L']) as x
726 { TInt ((x, is_long_dec s slong slong slong ulong), tokinfo lexbuf) }
727 | ((hexa as s) ['l' 'L']) as x
728 { TInt ((x, is_long_hex s slong slong slong ulong), tokinfo lexbuf) }
729 | ((octal as s) ['l' 'L']) as x
730 { TInt ((x, is_long_oct s slong slong slong ulong), tokinfo lexbuf) }
731 | ((( decimal | hexa | octal) ['l' 'L'] ['u' 'U'])
732 | (( decimal | hexa | octal) ['u' 'U'] ['l' 'L'])) as x
733 { TInt ((x, (UnSigned,CLong)), tokinfo lexbuf) }
734 | (( decimal | hexa | octal) ['l' 'L'] ['l' 'L']) as x
735 { TInt ((x, (Signed,CLongLong)), tokinfo lexbuf) }
736 | (( decimal | hexa | octal) ['u' 'U'] ['l' 'L'] ['l' 'L']) as x
737 { TInt ((x, (UnSigned,CLongLong)), tokinfo lexbuf) }
738
739 | (real ['f' 'F']) as x { TFloat ((x, CFloat), tokinfo lexbuf) }
740 | (real ['l' 'L']) as x { TFloat ((x, CLongDouble), tokinfo lexbuf) }
741 | (real as x) { TFloat ((x, CDouble), tokinfo lexbuf) }
742
743 | ['0'] ['0'-'9']+
744 { pr2 ("LEXER: " ^ error_radix "octal" ^ tok lexbuf);
745 TUnknown (tokinfo lexbuf)
746 }
747 | ("0x" |"0X") ['0'-'9' 'a'-'z' 'A'-'Z']+
748 { pr2 ("LEXER: " ^ error_radix "hexa" ^ tok lexbuf);
749 TUnknown (tokinfo lexbuf)
750 }
751
752
753 (* !!! to put after other rules !!! otherwise 0xff
754 * will be parsed as an ident.
755 *)
756 | ['0'-'9']+ letter (letter | digit) *
757 { pr2 ("LEXER: ZARB integer_string, certainly a macro:" ^ tok lexbuf);
758 TIdent (tok lexbuf, tokinfo lexbuf)
759 }
760
761 (* gccext: http://gcc.gnu.org/onlinedocs/gcc/Binary-constants.html *)
762 (*
763 | "0b" ['0'-'1'] { TInt (((tok lexbuf)<!!>(??,??)) +> int_of_stringbits) }
764 | ['0'-'1']+'b' { TInt (((tok lexbuf)<!!>(0,-2)) +> int_of_stringbits) }
765 *)
766
767
768 (*------------------------------------------------------------------------ *)
769 | eof { EOF (tokinfo lexbuf +> Ast_c.rewrap_str "") }
770
771 | _
772 {
773 if !Flag_parsing_c.verbose_lexing
774 then pr2_once ("LEXER:unrecognised symbol, in token rule:"^tok lexbuf);
775 TUnknown (tokinfo lexbuf)
776 }
777
778
779
780 (*****************************************************************************)
781 and char = parse
782 | (_ as x) "'" { String.make 1 x }
783 (* todo?: as for octal, do exception beyond radix exception ? *)
784 | (("\\" (oct | oct oct | oct oct oct)) as x "'") { x }
785 (* this rule must be after the one with octal, lex try first longest
786 * and when \7 we want an octal, not an exn.
787 *)
788 | (("\\x" ((hex | hex hex))) as x "'") { x }
789 | (("\\" (_ as v)) as x "'")
790 {
791 (match v with (* Machine specific ? *)
792 | 'n' -> () | 't' -> () | 'v' -> () | 'b' -> () | 'r' -> ()
793 | 'f' -> () | 'a' -> ()
794 | '\\' -> () | '?' -> () | '\'' -> () | '"' -> ()
795 | 'e' -> () (* linuxext: ? *)
796 | _ ->
797 pr2 ("LEXER: unrecognised symbol in char:"^tok lexbuf);
798 );
799 x
800 }
801 | _
802 { pr2 ("LEXER: unrecognised symbol in char:"^tok lexbuf);
803 tok lexbuf
804 }
805
806
807
808 (*****************************************************************************)
809
810 (* todo? factorise code with char ? but not same ending token so hard. *)
811 and string = parse
812 | '"' { "" }
813 | (_ as x) { string_of_char x^string lexbuf}
814 | ("\\" (oct | oct oct | oct oct oct)) as x { x ^ string lexbuf }
815 | ("\\x" (hex | hex hex)) as x { x ^ string lexbuf }
816 | ("\\" (_ as v)) as x
817 {
818 (match v with (* Machine specific ? *)
819 | 'n' -> () | 't' -> () | 'v' -> () | 'b' -> () | 'r' -> ()
820 | 'f' -> () | 'a' -> ()
821 | '\\' -> () | '?' -> () | '\'' -> () | '"' -> ()
822 | 'e' -> () (* linuxext: ? *)
823
824 (* old: "x" -> 10 gccext ? todo ugly, I put a fake value *)
825
826 (* cppext: can have \ for multiline in string too *)
827 | '\n' -> ()
828 | _ -> pr2 ("LEXER: unrecognised symbol in string:"^tok lexbuf);
829 );
830 x ^ string lexbuf
831 }
832
833 | eof { pr2 "LEXER: WIERD end of file in string"; ""}
834
835 (* Bug if add following code, cos match also the '"' that is needed
836 * to finish the string, and so go until end of file.
837 *)
838 (*
839 | [^ '\\']+
840 { let cs = lexbuf +> tok +> list_of_string +> List.map Char.code in
841 cs ++ string lexbuf
842 }
843 *)
844
845
846
847 (*****************************************************************************)
848
849 (* less: allow only char-'*' ? *)
850 and comment = parse
851 | "*/" { tok lexbuf }
852 (* noteopti: *)
853 | [^ '*']+ { let s = tok lexbuf in s ^ comment lexbuf }
854 | [ '*'] { let s = tok lexbuf in s ^ comment lexbuf }
855 | eof { pr2 "LEXER: end of file in comment"; "*/"}
856 | _
857 { let s = tok lexbuf in
858 pr2 ("LEXER: unrecognised symbol in comment:"^s);
859 s ^ comment lexbuf
860 }
861
862
863
864 (*****************************************************************************)
865
866 (* cpp recognize C comments, so when #define xx (yy) /* comment \n ... */
867 * then he has already erased the /* comment. So:
868 * - dont eat the start of the comment otherwise afterwards we are in the middle
869 * of a comment and so will problably get a parse error somewhere.
870 * - have to recognize comments in cpp_eat_until_nl.
871 *)
872
873 and cpp_eat_until_nl = parse
874 (* bugfix: *)
875 | "/*"
876 { let s = tok lexbuf in
877 let s2 = comment lexbuf in
878 let s3 = cpp_eat_until_nl lexbuf in
879 s ^ s2 ^ s3
880 }
881 | '\\' "\n" { let s = tok lexbuf in s ^ cpp_eat_until_nl lexbuf }
882
883 | "\n" { tok lexbuf }
884 (* noteopti:
885 * update: need also deal with comments chars now
886 *)
887 | [^ '\n' '\\' '/' '*' ]+
888 { let s = tok lexbuf in s ^ cpp_eat_until_nl lexbuf }
889 | eof { pr2 "LEXER: end of file in cpp_eat_until_nl"; ""}
890 | _ { let s = tok lexbuf in s ^ cpp_eat_until_nl lexbuf }