package genprint

  1. Overview
  2. Docs
Legend:
Page
Library
Module
Module type
Parameter
Class
Class type
Source

Source file ppx_genprint.ml

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
open Ppxlib

let count = ref 0

let expand ~loc ~path (msg: string) (e : expression) =
  incr count;
(* Printf.printf "GOT: %s -> %s/%d\n" path msg !count; *)
  [%expr [%e Ast_builder.Default.(

    pexp_apply ~loc
      (pexp_ident ~loc (Located.mk ~loc (Longident.parse "Genprint.print") ))
      [Nolabel,estring ~loc msg;
       Nolabel,pexp_tuple ~loc [ e; (eint ~loc !count); (estring ~loc @@ Filename.basename path) ]
      ]
  )]]


let genprint =
  Extension.declare
    "prs"
    Extension.Context.expression
    (* pattern appearing in [%pr "..." v] is the application of the string to the value *)
    Ast_pattern.(pstr ((pstr_eval (pexp_apply (estring __)
                                     (
                                      no_label __ ^:: nil)   ) nil ) ^:: nil))
    expand


let () =
  Driver.register_transformation "genprint" ~extensions:[ genprint ]


let expand_ff ~loc ~path (lid : longident) (el : (arg_label * expression) list) =
  incr count;
  match List.rev el with
  | [] -> assert false
  | (_,e) :: tl ->
    let first_word = Longident.name lid in
    let msg = List.fold_left (fun msg (_,word) ->
        match word.pexp_desc with
        | Pexp_ident id ->
          let word'= Longident.name id.txt in
          (" "^ word' ^msg)
        | _ ->
          Location.raise_errorf ~loc:word.pexp_loc "this should be a word")
        "" tl in

  [%expr [%e Ast_builder.Default.(
    pexp_apply ~loc
      (pexp_ident ~loc (Located.mk ~loc (Longident.parse "Genprint.print") ))
      [Nolabel,estring ~loc (first_word ^ msg);
       Nolabel,pexp_tuple ~loc [ e; (eint ~loc !count); (estring ~loc @@ Filename.basename path) ]
      ]
  )]]

let genprint_freeform =
    Extension.declare
      "pr"
      Extension.Context.expression
      (* pattern appearing in [%pr "..." v] is the application of the string to the value *)
      Ast_pattern.(pstr ((pstr_eval (pexp_apply (pexp_ident __) ( __)  ) nil ) ^:: nil))
      expand_ff




let () =
  Driver.register_transformation "genprint-freeform" ~extensions:[ genprint_freeform ]

OCaml

Innovation. Community. Security.