Debian Codegraph @

src/ppx_optcomp.ml

raw symbols SCIP
1 open Base
2 open Stdio
3 open Ppxlib
4 open Ast_builder.Default
5 module Filename = Stdlib.Filename
6 module Env = Interpreter.Env
7 module Value = Interpreter.Value
8
9 module Of_item = struct
10 (* boilerplate code to pull extensions out of different ast nodes *)
11 open Token
12
13 let directive_or_block_of_ext ~item ({ txt = ext_name; loc }, payload) attrs =
14 match Directive.of_string_opt ext_name with
15 | None -> (* not one of our extensions *) Block [ item ]
16 | Some dir ->
17 assert_no_attributes attrs;
18 Directive (dir, loc, payload)
19 ;;
20
21 let structure item =
22 match item.pstr_desc with
23 | Pstr_extension (ext, attrs) -> directive_or_block_of_ext ~item ext attrs
24 | _ -> Block [ item ]
25 ;;
26
27 let signature item =
28 match item.psig_desc with
29 | Psig_extension (ext, attrs) -> directive_or_block_of_ext ~item ext attrs
30 | _ -> Block [ item ]
31 ;;
32
33 let class_structure item =
34 match item.pcf_desc with
35 | Pcf_extension ext -> directive_or_block_of_ext ~item ext []
36 | _ -> Block [ item ]
37 ;;
38
39 let class_signature item =
40 match item.pctf_desc with
41 | Pctf_extension ext -> directive_or_block_of_ext ~item ext []
42 | _ -> Block [ item ]
43 ;;
44 end
45
46 module Ast_utils = struct
47 let get_expr ~loc payload =
48 match payload with
49 | PStr [ { pstr_desc = Pstr_eval (e, attrs); _ } ] ->
50 assert_no_attributes attrs;
51 e
52 | _ ->
53 Location.raise_errorf
54 ~loc
55 "optcomp: invalid directive syntax, expected single expression."
56 ;;
57
58 let assert_no_arguments ~loc payload =
59 match payload with
60 | PStr [] -> ()
61 | _ ->
62 Location.raise_errorf
63 ~loc
64 "optcomp: invalid directive syntax, expected no arguments."
65 ;;
66
67 let make_apply_fun ~loc name expr =
68 let iname = { txt = Lident name; loc } in
69 eapply ~loc (pexp_ident ~loc iname) [ expr ]
70 ;;
71
72 let get_ident ~loc payload =
73 let e = get_expr ~loc payload in
74 Interpreter.lid_of_expr e
75 ;;
76
77 let get_var ~loc payload =
78 let e = get_expr ~loc payload in
79 Interpreter.var_of_expr e
80 ;;
81
82 let get_var_expr ~loc payload =
83 let apply_e = get_expr ~loc payload in
84 match apply_e.pexp_desc with
85 | Pexp_apply (var_e, [ (Nolabel, val_e) ]) ->
86 Interpreter.var_of_expr var_e, Some val_e
87 | Pexp_construct (var_li, Some val_e) -> Interpreter.var_of_lid var_li, Some val_e
88 | Pexp_apply (var_e, []) -> Interpreter.var_of_expr var_e, None
89 | Pexp_construct (var_li, None) -> Interpreter.var_of_lid var_li, None
90 | _ ->
91 Location.raise_errorf
92 ~loc
93 "optcomp: invalid directive syntax, expected var and expr"
94 ;;
95
96 let get_string ~loc payload =
97 let e = get_expr ~loc payload in
98 match e with
99 | { pexp_desc = Pexp_constant (Pconst_string (x, _, _)); _ } -> x
100 | _ -> Location.raise_errorf ~loc "optcomp: invalid directive syntax, expected string"
101 ;;
102 end
103
104 module Token_stream : sig
105 type 'a t = 'a Token.t list
106
107 val of_items : 'a list -> of_item:('a -> 'a Token.t) -> 'a t
108 end = struct
109 type 'a t = 'a Token.t list
110
111 type ftype =
112 | Ocaml
113 | C
114
115 let resolve_import ~loc ~filename : string * ftype =
116 let ext = Filename.extension (Filename.basename filename) in
117 let ftype =
118 match ext with
119 | ".ml" | ".mlh" -> Ocaml
120 | ".h" -> C
121 | _ ->
122 Location.raise_errorf
123 ~loc
124 "optcomp: unknown file extension: %s\nMust be one of: .ml, .mlh or .h."
125 ext
126 in
127 let fbase = Filename.dirname loc.loc_start.pos_fname in
128 let fpath =
129 if Filename.is_relative filename then Filename.concat fbase filename else filename
130 in
131 fpath, ftype
132 ;;
133
134 let import_open ~loc payload =
135 let filename = Ast_utils.get_string ~loc payload in
136 let fpath, ftype = resolve_import ~loc ~filename in
137 let in_ch =
138 try In_channel.create fpath with
139 | exn ->
140 let msg =
141 match exn with
142 | Sys_error msg -> msg
143 | _ -> Exn.to_string exn
144 in
145 Location.raise_errorf ~loc "optcomp: cannot open imported file: %s: %s" fpath msg
146 in
147 (* disable old optcomp on imported files, or it consumes all variables :( *)
148 Lexer.set_preprocessor (fun () -> ()) (fun x -> x);
149 let lexbuf = Lexing.from_channel in_ch in
150 lexbuf.lex_curr_p <- { pos_fname = fpath; pos_lnum = 1; pos_bol = 0; pos_cnum = 0 };
151 in_ch, lexbuf, ftype
152 ;;
153
154 let unroll (stack : 'a Token.t list) : 'a Token.t * 'a Token.t list =
155 let bs, _, rest_rev =
156 List.fold stack ~init:([], false, []) ~f:(fun (bs, found, rest) x ->
157 match x, found with
158 | Block b, false -> b @ bs, false, rest
159 | _ -> bs, true, x :: rest)
160 in
161 Block bs, List.rev rest_rev
162 ;;
163
164 let rec of_items : 'a. 'a list -> of_item:('a -> 'a Token.t) -> 'a t =
165 fun items ~of_item ->
166 let of_items_st x = of_items ~of_item:Of_item.structure x in
167 let tokens_rev =
168 List.fold items ~init:[] ~f:(fun acc item ->
169 match of_item item with
170 | Directive (dir, loc, payload) as token ->
171 let last_block, rest = unroll acc in
172 (match dir with
173 | Import ->
174 let in_ch, lexbuf, ftype = import_open ~loc payload in
175 let new_tokens =
176 match ftype with
177 | C -> Cparser.parse_loop lexbuf
178 | Ocaml ->
179 let st_items = Parse.implementation lexbuf in
180 Token.just_directives_exn ~loc (of_items_st st_items)
181 in
182 In_channel.close in_ch;
183 List.rev new_tokens @ (last_block :: rest)
184 | _ -> token :: last_block :: rest)
185 | _ ->
186 (match acc with
187 | Block items :: acc -> Block (items @ [ item ]) :: acc
188 | _ -> Block [ item ] :: acc))
189 in
190 List.rev tokens_rev
191 ;;
192 end
193
194 module Meta_ast : sig
195 type 'a t
196
197 val of_tokens : 'a Token.t list -> 'a t
198
199 val eval
200 : drop_item:('a -> unit)
201 -> eval_item:(Env.t -> 'a -> 'a)
202 -> env:Env.t
203 -> 'a t
204 -> Env.t * 'a list
205
206 val attr_mapper
207 : to_loc:('a -> location)
208 -> to_attrs:('a -> attributes)
209 -> replace_attrs:('a -> attributes -> 'a)
210 -> env:Env.t
211 -> 'a
212 -> 'a option
213 end = struct
214 open Ast_utils
215
216 type 'a t =
217 | Leaf of 'a list
218 | If of expression * 'a t * 'a t
219 | Block of 'a t list
220 | Define of string Location.loc * expression option
221 | Undefine of string Location.loc
222 | Import of string Location.loc
223 | Error of string Location.loc
224 | Warning of string Location.loc
225
226 type 'a partial_if =
227 | EmptyIf of ('a t -> 'a t -> 'a t) (* [If] waiting for both blocks *)
228 | PartialIf of ('a t -> 'a t)
229 (* [If] waiting for else block *)
230
231 type 'a temp_ast =
232 | Full of 'a t
233 | Partial of 'a partial_if loc
234
235 let deprecated_ifs ~loc =
236 Location.raise_errorf ~loc "optcomp: elif(n)def is deprecated, use elif defined()."
237 ;;
238
239 let unroll_exn ~loc (acc : 'a temp_ast list) : 'a t * 'a partial_if * 'a temp_ast list =
240 (* split by first EmptyIf/PartialIf *)
241 let pre, if_fun, post =
242 List.fold acc ~init:([], None, []) ~f:(fun (pre, found, post) x ->
243 match found with
244 | Some _ -> pre, found, x :: post
245 | None ->
246 (match x with
247 | Partial { txt = f; _ } -> pre, Some f, post
248 | Full ast -> ast :: pre, None, post))
249 in
250 match if_fun with
251 | None -> Location.raise_errorf ~loc "optcomp: else/endif/elif outside of if"
252 | Some f -> Block pre, f, List.rev post
253 ;;
254
255 let make_if ~loc cond =
256 let if_fun ast1 ast2 = If (cond, ast1, ast2) in
257 Partial { txt = EmptyIf if_fun; loc }
258 ;;
259
260 let of_tokens (tokens : 'a Token.t list) : 'a t =
261 let pre_parsed =
262 List.fold
263 tokens
264 ~init:([] : 'a temp_ast list)
265 ~f:(fun acc token ->
266 match token with
267 | Token.Block [] -> acc
268 | Token.Block b -> Full (Leaf b) :: acc
269 | Token.Directive (dir, loc, payload) ->
270 (match dir with
271 | If -> make_if ~loc (get_expr ~loc payload) :: acc
272 | Endif ->
273 assert_no_arguments ~loc payload;
274 let last_block, if_fun, tail = unroll_exn ~loc acc in
275 (match if_fun with
276 | PartialIf f -> Full (f last_block) :: tail
277 | EmptyIf f -> Full (f last_block (Block [])) :: tail)
278 | Elif ->
279 let cond = get_expr ~loc payload in
280 let last_block, if_fun, tail = unroll_exn ~loc acc in
281 (match if_fun with
282 | EmptyIf f ->
283 let new_if_fun ast1 ast2 = f last_block (If (cond, ast1, ast2)) in
284 Partial { txt = EmptyIf new_if_fun; loc } :: tail
285 | PartialIf _ ->
286 Location.raise_errorf ~loc "optcomp: elif after else clause.")
287 | Else ->
288 assert_no_arguments ~loc payload;
289 let last_block, if_fun, tail = unroll_exn ~loc acc in
290 (match if_fun with
291 | EmptyIf f -> Partial { txt = PartialIf (f last_block); loc } :: tail
292 | PartialIf _ -> Location.raise_errorf ~loc "optcomp: second else clause.")
293 | Define ->
294 let ident, expr = get_var_expr ~loc payload in
295 Full (Define (ident, expr)) :: acc
296 | Undef -> Full (Undefine (get_var ~loc payload)) :: acc
297 | Error -> Full (Error { txt = get_string ~loc payload; loc }) :: acc
298 | Warning -> Full (Warning { txt = get_string ~loc payload; loc }) :: acc
299 | Import -> Full (Import { txt = get_string ~loc payload; loc }) :: acc
300 | Ifdef ->
301 let ident = pexp_ident ~loc (get_ident ~loc payload) in
302 let expr = make_apply_fun ~loc "defined" ident in
303 make_if ~loc expr :: acc
304 | Ifndef ->
305 let ident = pexp_ident ~loc (get_ident ~loc payload) in
306 let expr = make_apply_fun ~loc "not_defined" ident in
307 make_if ~loc expr :: acc
308 | Elifdef -> deprecated_ifs ~loc
309 | Elifndef -> deprecated_ifs ~loc))
310 in
311 let extract_full = function
312 | Full x -> x
313 | Partial { loc; _ } -> Location.raise_errorf ~loc "optcomp: unterminated if"
314 in
315 Block (List.rev_map pre_parsed ~f:extract_full)
316 ;;
317
318 let eval ~drop_item ~eval_item ~env ast =
319 let rec drop ast =
320 match ast with
321 | Leaf l -> List.iter l ~f:drop_item
322 | Block (ast :: asts) ->
323 drop ast;
324 drop (Block asts)
325 | If (cond, ast1, ast2) ->
326 Attribute.explicitly_drop#expression cond;
327 drop ast1;
328 drop ast2
329 | _ -> ()
330 in
331 let rec aux_eval ~env (ast : 'a t) : Env.t * 'a list list =
332 match ast with
333 | Leaf l ->
334 let l' = List.map l ~f:(eval_item env) in
335 env, [ l' ]
336 | Block (ast :: asts) ->
337 let new_env, res = aux_eval ~env ast in
338 let newer_env, ress = aux_eval ~env:new_env (Block asts) in
339 newer_env, res @ ress
340 | Block [] -> env, []
341 | Define (ident, Some expr) ->
342 Env.add env ~var:ident ~value:(Interpreter.eval env expr), []
343 | Define (ident, None) -> Env.add env ~var:ident ~value:(Value.Tuple []), []
344 | Undefine ident -> Env.undefine env ident, []
345 | Import { loc; _ } ->
346 Location.raise_errorf ~loc "optcomp: import not supported in this context."
347 | If (cond, ast1, ast2) ->
348 let cond =
349 (* Explicitely allow the following pattern:
350 {[
351 [%%ifndef FOO]
352 [%%define FOO]
353 ]}
354 *)
355 match cond.pexp_desc, ast1 with
356 | ( Pexp_apply
357 ( { pexp_desc = Pexp_ident { txt = Lident "not_defined"; _ }; _ }
358 , [ ( Nolabel
359 , ({ pexp_desc = Pexp_ident { txt = Lident i1; loc }; _ } as expr) )
360 ] )
361 , Block (Define ({ txt = i2; _ }, None) :: _) )
362 when String.( = ) i1 i2 -> make_apply_fun ~loc "not_defined_permissive" expr
363 | _ -> cond
364 in
365 (match Interpreter.eval env cond with
366 | Bool b ->
367 drop (if b then ast2 else ast1);
368 aux_eval ~env (if b then ast1 else ast2)
369 | v ->
370 Location.raise_errorf
371 ~loc:cond.pexp_loc
372 "optcomp: if condition evaluated to non-bool: %s"
373 (Value.to_string v))
374 | Error { loc; txt } -> Location.raise_errorf ~loc "%s" txt
375 | Warning { txt; loc } ->
376 let ppf = Stdlib.Format.err_formatter in
377 Stdlib.Format.fprintf ppf "%a:@.Warning %s@." Location.print loc txt;
378 env, []
379 in
380 let new_env, res = aux_eval ~env ast in
381 new_env, List.join res
382 ;;
383
384 let attr_mapper ~to_loc ~to_attrs ~replace_attrs ~env item =
385 let loc = to_loc item in
386 let is_our_attribute { attr_name = { txt; _ }; _ } =
387 Token.Directive.matches txt ~expected:"if"
388 in
389 let our_as, other_as = List.partition_tf (to_attrs item) ~f:is_our_attribute in
390 match our_as with
391 | [] -> Some item
392 | [ ({ attr_name = { loc; _ }; attr_payload = payload; attr_loc = _ } as our_a) ] ->
393 Attribute.mark_as_handled_manually our_a;
394 (match Interpreter.eval env (get_expr ~loc payload) with
395 | Bool b -> if b then Some (replace_attrs item other_as) else None
396 | v ->
397 Location.raise_errorf
398 ~loc
399 "optcomp: if condition evaulated to non-bool: %s"
400 (Value.to_string v))
401 | _ -> Location.raise_errorf ~loc "optcomp: multiple [@if] attributes are not allowed"
402 ;;
403 end
404
405 let rewrite ~drop_item ~eval_item ~of_item ~env (x : 'a list) : Env.t * 'a list =
406 let tokens : 'a Token.t list = Token_stream.of_items x ~of_item in
407 let ast = Meta_ast.of_tokens tokens in
408 Meta_ast.eval ~drop_item ~eval_item ~env ast
409 ;;
410
411 let map =
412 object (self)
413 inherit [Env.t] Ast_traverse.map_with_context as super
414
415 method structure_gen env x =
416 rewrite
417 x
418 ~env
419 ~drop_item:Attribute.explicitly_drop#structure_item
420 ~eval_item:self#structure_item
421 ~of_item:Of_item.structure
422
423 method signature_gen env x =
424 rewrite
425 x
426 ~env
427 ~drop_item:Attribute.explicitly_drop#signature_item
428 ~eval_item:self#signature_item
429 ~of_item:Of_item.signature
430
431 method! structure env x = snd (self#structure_gen env x)
432 method! signature env x = snd (self#signature_gen env x)
433
434 method! class_structure env x =
435 let _, rewritten =
436 rewrite
437 x.pcstr_fields
438 ~env
439 ~drop_item:Attribute.explicitly_drop#class_field
440 ~eval_item:self#class_field
441 ~of_item:Of_item.class_structure
442 in
443 { x with pcstr_fields = rewritten }
444
445 method! class_signature env x =
446 let _, rewritten =
447 rewrite
448 x.pcsig_fields
449 ~env
450 ~drop_item:Attribute.explicitly_drop#class_type_field
451 ~eval_item:self#class_type_field
452 ~of_item:Of_item.class_signature
453 in
454 { x with pcsig_fields = rewritten }
455
456 method! type_kind env x =
457 let x =
458 match x with
459 | Ptype_variant cs ->
460 let f =
461 Meta_ast.attr_mapper
462 ~env
463 ~to_loc:(fun c -> c.pcd_loc)
464 ~to_attrs:(fun c -> c.pcd_attributes)
465 ~replace_attrs:(fun c attrs -> { c with pcd_attributes = attrs })
466 in
467 let filtered_cs = List.filter_map cs ~f in
468 Ptype_variant filtered_cs
469 | _ -> x
470 in
471 super#type_kind env x
472
473 method! expression_desc env x =
474 let f =
475 Meta_ast.attr_mapper
476 ~env
477 ~to_loc:(fun c -> c.pc_lhs.ppat_loc)
478 ~to_attrs:(fun c -> c.pc_lhs.ppat_attributes)
479 ~replace_attrs:(fun ({ pc_lhs; _ } as c) attrs ->
480 { c with pc_lhs = { pc_lhs with ppat_attributes = attrs } })
481 in
482 let x =
483 match x with
484 | Pexp_function (params, constr, Pfunction_cases (cs, loc, attr)) ->
485 Pexp_function (params, constr, Pfunction_cases (List.filter_map cs ~f, loc, attr))
486 | Pexp_match (e, cs) -> Pexp_match (super#expression env e, List.filter_map cs ~f)
487 | Pexp_try (e, cs) -> Pexp_try (super#expression env e, List.filter_map cs ~f)
488 | _ -> x
489 in
490 super#expression_desc env x
491 end
492 ;;
493
494 (* Preserve the enrivonment between invocation using cookies *)
495 let state = ref Env.init
496
497 let () =
498 Driver.Cookies.add_simple_handler "ppx_optcomp.env" Ast_pattern.__ ~f:(function
499 | None -> state := Env.init
500 | Some x -> state := Interpreter.EnvIO.of_expression x);
501 Driver.Cookies.add_post_handler (fun cookies ->
502 Driver.Cookies.set cookies "ppx_optcomp.env" (Interpreter.EnvIO.to_expression !state))
503 ;;
504
505 let preprocess ~f x =
506 let new_env, x = f !state x in
507 state := new_env;
508 x
509 ;;
510
511 let () =
512 Driver.register_transformation
513 "optcomp"
514 ~preprocess_impl:(preprocess ~f:map#structure_gen)
515 ~preprocess_intf:(preprocess ~f:map#signature_gen)
516 ;;