File: cpp_ast_c.ml

package info (click to toggle)
coccinelle 1.0.8.deb-5
  • links: PTS, VCS
  • area: main
  • in suites: bullseye, sid
  • size: 26,148 kB
  • sloc: ml: 136,392; ansic: 23,594; sh: 2,189; makefile: 2,157; perl: 1,576; lisp: 840; python: 823; awk: 70; csh: 12
file content (320 lines) | stat: -rw-r--r-- 9,901 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
(* Yoann Padioleau
 *
 * Copyright (C) 2010, University of Copenhagen DIKU and INRIA.
 * Copyright (C) 2008, 2009 University of Urbana Champaign
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License (GPL)
 * version 2 as published by the Free Software Foundation.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * file license.txt for more details.
 *)
open Common

open Ast_c

(*****************************************************************************)
(* Wrappers *)
(*****************************************************************************)
let pr2, pr2_once =
  Common.mk_pr2_wrappers Flag_parsing_c.verbose_cpp_ast
let pr2_debug,pr2_debug_once =
  Common.mk_pr2_wrappers Flag_parsing_c.debug_cpp_ast

(*****************************************************************************)
(* Cpp Ast Manipulations *)
(*****************************************************************************)

(*
 * cpp-include-expander-builtin.
 *
 * alternative1: parse and call cpp tour a tour. So let cpp work at
 *  the token level. That's what most tools do.
 * alternative2: apply cpp at the very end. Process that go through ast
 *  and do the stuff such as #include,  macro expand,
 *  ifdef but on the ast!
 *
 * But need keep those info in ast at least, even bad
 * macro for instance, and for parse error region ? maybe can
 * get another chance ?
 * I think it's better to do the cpp-include-expander in a different step
 * rather than embedding it in the parser. The parser is already too complex.
 * Also keep with the tradition to try to parse as-is.
 *
 * todo? but maybe could discover new info that could help reparse
 * the ParseError in original file. Try again parsing it by
 * putting it in a minifile ?
 *
 *
 * todo? maybe can do some pass that work at the ifdef level and for instance
 * try to paren them, so have in Ast some stuff that are not
 * present at parsing time but that can then be constructed after
 * some processing (a little bit like my type for expression filler,
 * or position info filler, or include relative position filler).
 *
 * ??add such info about what was done somewhere ? could build new
 * ??ast each time but too tedious (maybe need delta-programming!)
 *
 * todo? maybe change cpp_ast_c to go deeper on local "" ?
 *
 *
 * TODO: macro expand,
 * TODO: handle ifdef
 *)



(*****************************************************************************)
(* Types  *)
(*****************************************************************************)

type cpp_option =
  | I of Common.dirname
  | D of string * string option



let i_of_cpp_options xs =
  xs +> Common.map_filter (function
  | I f -> Some f
  | D _ -> None
  )

let cpp_option_of_cmdline (xs, ys) =
  (xs +> List.map (fun s -> I s)) @
  (ys +> List.map (fun s ->
    if s =~ "\\([A-Z][A-Z0-9_]*\\)=\\(.*\\)"
    then
      let (def, value) = matched2 s in
      D (def, Some value)
    else
      D (s, None)
  ))

(*****************************************************************************)
(* Debug *)
(*****************************************************************************)
let (show_cpp_i_opts: string list -> unit) = fun xs ->
  if xs <> [] then begin
    pr2 "-I";
    xs +> List.iter pr2
  end


let (show_cpp_d_opts: string list -> unit) = fun xs ->
  if xs <> [] then begin
    pr2 "-D";
    xs +> List.iter pr2
  end

(* ---------------------------------------------------------------------- *)
let trace_cpp_process depth mark inc_file =
  pr2_debug (spf "%s>%s %s"
          (Common.repeat "-" depth +> String.concat "")
          mark
          (s_of_inc_file_bis inc_file));
  ()



(*****************************************************************************)
(* Helpers *)
(*****************************************************************************)


let _hcandidates = Hashtbl.create 101

let init_adjust_candidate_header_files dir =
  let ext = "[h]" in
  let files = Common.files_of_dir_or_files ext [dir] in

  files +> List.iter (fun file ->
    let base = Filename.basename file in
    pr2_debug file;
    Hashtbl.add _hcandidates base file;
  );
  ()



(* may return a list of match ? *)
let find_header_file1 cppopts dirname inc_file =
  match inc_file with
  | Local f ->
      let finalfile =
        Filename.concat dirname (Ast_c.s_of_inc_file inc_file) in
      if Sys.file_exists finalfile
      then [finalfile]
      else []
  | NonLocal f ->
      i_of_cpp_options cppopts +> Common.map_filter (fun dirname ->
        let finalfile =
          Filename.concat dirname (Ast_c.s_of_inc_file inc_file) in
        if Sys.file_exists finalfile
        then Some finalfile
        else None
      )
  | Weird s ->
      pr2 ("CPPAST: weird include not handled:" ^ s);
      []

(* todo? can try find most precise ? first just use basename but
 * then maybe look if have also some dir in common ?
 *)
let find_header_file2 inc_file =
  match inc_file with
  | Local f
  | NonLocal f ->
      let s = (Ast_c.s_of_inc_file inc_file) in
      let base = Filename.basename s in

      let res = Hashtbl.find_all _hcandidates base in
      (match res with
      | [file] ->
          pr2_debug ("CPPAST: find header in other dir: " ^ file);
          res
      | [] ->
          []
      | x::y::xs -> res
      )
  | Weird s ->
      []


let find_header_file cppopts dirname inc_file =
  let res1 = find_header_file1 cppopts dirname inc_file in
  match res1 with
  | [file] -> res1
  | [] -> find_header_file2 inc_file
  | x::y::xs -> res1




(* ---------------------------------------------------------------------- *)
let _headers_hash = Hashtbl.create 101

(* On freebsd ocaml is trashing, use up to 1.6Go of memory and then
 * building the database_c takes ages.
 *
 * So just limit with following threshold to avoid this trashing, simple.
 *
 * On netbsd, got a Out_of_memory exn on this file;
 * /home/pad/software-os-src2/netbsd/dev/microcode/cyclades-z/
 * even if the cache is small. That's because huge single
 * ast element and probably the ast marshalling fail.
 *)
let default_threshold_cache_nb_files = 200

let parse_c_and_cpp_cache
  ?(threshold_cache_nb_files= default_threshold_cache_nb_files) file =

  if Hashtbl.length _headers_hash > threshold_cache_nb_files
  then Hashtbl.clear _headers_hash;

  Common.memoized _headers_hash file (fun () ->
    Parse_c.parse_c_and_cpp false false file (* no need to parse strings *)
  )



(*****************************************************************************)
(* Main entry *)
(*****************************************************************************)


let (cpp_expand_include2:
 ?depth_limit:int option ->
 ?threshold_cache_nb_files:int ->
 cpp_option list -> Common.dirname -> Ast_c.program -> Ast_c.program) =
 fun ?(depth_limit=None) ?threshold_cache_nb_files iops dirname ast ->

  if !Flag_parsing_c.debug_cpp_ast
  then pr2_xxxxxxxxxxxxxxxxx();

  let already_included = ref [] in

  let rec aux stack dirname ast =
    let depth = List.length stack in

    ast +> Visitor_c.vk_program_s { Visitor_c.default_visitor_c_s with
      Visitor_c.kcppdirective_s = (fun (k, bigf) cpp ->
        match cpp with
        | Include {i_include = (inc_file, ii);
                   i_rel_pos = h_rel_pos;
                   i_overall_rel_pos = o_rel_pos;
                   i_is_in_ifdef = b;
                   i_content = copt;
                   }
          ->
          (match depth_limit with
          | Some limit when depth >= limit -> cpp
          | _ ->

            (match find_header_file iops dirname inc_file with
            | [file] ->
                if List.mem file !already_included
                then begin
                  (* pr2 ("already included: " ^ file); *)
                  trace_cpp_process depth "*" inc_file;
                  k cpp
                end else begin
                  trace_cpp_process depth "" inc_file;
                  Common.push2 file already_included;
                  (* CONFIG *)
                  Flag_parsing_c.verbose_parsing := false;
                  Flag_parsing_c.verbose_lexing := false;
                  let (ast2, _stat) =
                    parse_c_and_cpp_cache ?threshold_cache_nb_files file
                  in

                  let ast = Parse_c.program_of_program2 ast2 in
                  let dirname' = Filename.dirname file in

                  (* recurse *)
                  let ast' = aux (file::stack) dirname' ast in

                  Include {i_include = (inc_file, ii);
                           i_rel_pos = h_rel_pos;
			   i_overall_rel_pos = o_rel_pos;
                           i_is_in_ifdef = b;
                           i_content = Some (file, ast');
                  }
                end
            | [] ->
                trace_cpp_process depth "!!" inc_file;
                pr2 "CPPAST: file not found";
                k cpp
            | x::y::zs ->
                trace_cpp_process depth "!!" inc_file;
                pr2 "CPPAST: too much candidates";
                k cpp
            )
          )
        | _ -> k cpp
      );
    }
  in
  aux [] dirname ast


let cpp_expand_include ?depth_limit ?threshold_cache_nb_files a b c =
  Common.profile_code "cpp_expand_include"
   (fun () -> cpp_expand_include2 ?depth_limit ?threshold_cache_nb_files a b c)

(*
let unparse_showing_include_content ?
*)

(*****************************************************************************)
(* Macro *)
(*****************************************************************************)

let (cpp_expand_macro_expr:
  Ast_c.define_kind -> Ast_c.argument Ast_c.wrap2 list ->
  Ast_c.expression option) =
 fun defkind args ->
   raise Todo