Debian Codegraph @

src/ppx_custom_printf.ml

raw symbols SCIP
1 open Base
2 open Ppxlib
3 open Ast_builder.Default
4
5 (* returns the index of the conversion spec (unless the end of string is reached) *)
6 let rec skip_over_format_flags fmt i =
7 if i >= String.length fmt
8 then `Eoi
9 else (
10 match fmt.[i] with
11 | '*' | '#' | '-' | ' ' | '+' | '_' | '0' .. '9' | '.' ->
12 skip_over_format_flags fmt (i + 1)
13 | _ -> `Ok i)
14 ;;
15
16 (* doesn't check to make sure the format string is well-formed *)
17 (* Formats with subformats are skipped for the following reasons:
18
19 One is that they are hard to understand and not often used.
20
21 Another is that subformats like "%(%{Module}%)" won't work, since it
22 is impossible to produce a format of type [(Module.t -> 'a,...) format].
23 *)
24 let has_subformats (fmt : string) =
25 let lim = String.length fmt - 1 in
26 let rec loop i =
27 if i > lim
28 then false
29 else if Char.equal fmt.[i] '%'
30 then (
31 match skip_over_format_flags fmt (i + 1) with
32 | `Eoi -> false
33 | `Ok i ->
34 (match fmt.[i] with
35 | '(' | ')' | '}' -> true
36 | _ -> loop (i + 1)))
37 else loop (i + 1)
38 in
39 loop 0
40 ;;
41
42 (* returns a list of strings where even indexed elements are parts of the format string
43 that the preprocessor won't touch and odd indexed elements are the contents of %{...}
44 specifications. *)
45 let explode ~loc (s : string) =
46 let len = String.length s in
47 (* for cases where we can't parse the string with custom format specifiers, consider
48 the string as a regular format string *)
49 let as_normal_format_string = [ s ] in
50 if has_subformats s
51 then as_normal_format_string
52 else (
53 let sub from to_ = String.sub s ~pos:from ~len:(to_ - from) in
54 let rec loop acc from to_ =
55 assert (List.length acc % 2 = 0);
56 if to_ >= len
57 then List.rev (if from >= len then acc else sub from len :: acc)
58 else if Char.( <> ) s.[to_] '%'
59 then loop acc from (to_ + 1)
60 else (
61 match skip_over_format_flags s (to_ + 1) with
62 | `Eoi -> as_normal_format_string
63 | `Ok i ->
64 (match s.[i] with
65 | '[' ->
66 (* Scan char sets are not allowed by printf-like functions. So we might as
67 well disallow them at compile-time so that we can reuse them as magic
68 format strings in this implementation. *)
69 Location.raise_errorf
70 ~loc
71 "ppx_custom_printf: scan char sets are not allowed in custom format \
72 strings"
73 | '{' ->
74 if to_ + 1 <> i
75 then
76 Location.raise_errorf
77 ~loc
78 "ppx_custom_printf: unexpected format flags before %%{} specification \
79 in %S"
80 s;
81 (match String.index_from s (to_ + 2) '}' with
82 | None -> as_normal_format_string
83 | Some i ->
84 let l = sub (to_ + 2) i :: sub from to_ :: acc in
85 loop l (i + 1) (i + 1))
86 | _ -> loop acc from (i + 1)))
87 (* skip the conversion spec *)
88 in
89 loop [] 0 0)
90 ;;
91
92 let processed_format_string ~exploded_format_string =
93 let l =
94 let rec loop i l =
95 match l with
96 | s1 :: _s2 :: l -> s1 :: Printf.sprintf "%%%d[.]" i :: loop (i + 1) l
97 | [ s1 ] -> [ s1 ]
98 | [] -> []
99 in
100 loop 0 exploded_format_string
101 in
102 String.concat l ~sep:""
103 ;;
104
105 let rec evens = function
106 | ([] | [ _ ]) as l -> l
107 | x :: _ :: l -> x :: evens l
108 ;;
109
110 let odds = function
111 | [] -> []
112 | _ :: l -> evens l
113 ;;
114
115 (* Returns a pair of:
116
117 - a format string, which is [s] where all custom format specifications have been
118 replaced by ["%" ^ string_of_int index ^ "[.]"] where [index] is the number of
119 the custom format specification, starting from 0. This string can be passed directly
120 to [CamlinternalFormat.fmt_ebb_of_string]
121 - an array of custom format specifications, in the order they appear in the original
122 string
123 *)
124 let extract_custom_format_specifications ~loc s =
125 let exploded_format_string = explode ~loc s in
126 let processed = processed_format_string ~exploded_format_string in
127 let custom_specs = Array.of_list (odds exploded_format_string) in
128 processed, custom_specs
129 ;;
130
131 let gen_symbol = gen_symbol ~prefix:"_custom_printf"
132
133 let is_space = function
134 | ' ' | '\t' | '\n' | '\r' -> true
135 | _ -> false
136 ;;
137
138 let strip s =
139 let a = ref 0 in
140 let b = ref (String.length s - 1) in
141 while !a <= !b && is_space s.[!a] do
142 Int.incr a
143 done;
144 while !a <= !b && is_space s.[!b] do
145 Int.decr b
146 done;
147 if !a > !b then "" else String.sub s ~pos:!a ~len:(!b - !a + 1)
148 ;;
149
150 let string_to_expr ~loc s =
151 let sexp_converter_opt =
152 match String.lsplit2 s ~on:':' with
153 | None -> None
154 | Some ("sexp", colon_suffix) ->
155 Some ([%expr Ppx_sexp_conv_lib.Sexp.to_string_hum], colon_suffix)
156 | Some (colon_prefix, colon_suffix) ->
157 (match String.chop_prefix colon_prefix ~prefix:"sexp#" with
158 | None -> None
159 | Some hash_suffix ->
160 Some
161 ( pexp_ident
162 ~loc
163 (Located.mk
164 ~loc
165 (Longident.parse ("Ppx_sexp_conv_lib.Sexp.to_string_" ^ hash_suffix)))
166 , colon_suffix ))
167 in
168 match sexp_converter_opt with
169 | Some (sexp_converter, unparsed_type) ->
170 let lexbuf = Lexing.from_string unparsed_type in
171 (* ~loc is the position of the string, not the position of the %{bla} group we're
172 looking at. The format strings don't contain location information, so we can't
173 actually find the proper positions. *)
174 lexbuf.lex_abs_pos <- loc.loc_start.pos_cnum;
175 lexbuf.lex_curr_p <- loc.loc_start;
176 let ty = Parse.core_type lexbuf in
177 let e = Ppx_sexp_conv_expander.Sexp_of.core_type ty in
178 let arg = gen_symbol () in
179 pexp_fun
180 ~loc
181 Nolabel
182 None
183 (pvar ~loc arg)
184 (eapply ~loc sexp_converter [ eapply ~loc e [ evar ~loc arg ] ])
185 | None ->
186 let fail loc =
187 Location.raise_errorf
188 ~loc
189 "ppx_custom_printf: string %S should be of the form <Module>, \
190 <Module>.<identifier>, <Module>#identifier, sexp:<type>, or sexp#mach:<type>"
191 s
192 in
193 let s, has_hash_suffix, to_string =
194 match String.lsplit2 s ~on:'#' with
195 | None -> s, false, "to_string"
196 | Some (s, hash_suffix) -> s, true, "to_string_" ^ hash_suffix
197 in
198 let to_string_id : Longident.t =
199 let s = strip s in
200 match s with
201 | "" -> Lident to_string
202 | _ ->
203 (match Longident.parse s with
204 | (Lident n | Ldot (_, n)) as id ->
205 if String.( <> ) n "" && Char.equal (Char.uppercase n.[0]) n.[0]
206 then Longident.Ldot (id, to_string)
207 else if not has_hash_suffix
208 then id
209 else fail loc
210 | _ -> fail loc)
211 in
212 let func = pexp_ident ~loc (Located.mk ~loc to_string_id) in
213 (* Eta-expand as the to_string function might take optional arguments *)
214 let arg = gen_symbol () in
215 pexp_fun ~loc Nolabel None (pvar ~loc arg) (eapply ~loc func [ evar ~loc arg ])
216 ;;
217
218 class lifter ~loc ~custom_specs =
219 object (self)
220 inherit [expression] Format_lifter.lift as super
221 inherit Ppxlib_metaquot_lifters.expression_lifters loc
222
223 method! fmt
224 : type f0
225 f1
226 f2
227 f3
228 f4
229 f5. (f0 -> expression)
230 -> (f1 -> expression)
231 -> (f2 -> expression)
232 -> (f3 -> expression)
233 -> (f4 -> expression)
234 -> (f5 -> expression)
235 -> (f0, f1, f2, f3, f4, f5) CamlinternalFormatBasics.fmt
236 -> expression =
237 fun f0 f1 f2 f3 f4 f5 fmt ->
238 let open CamlinternalFormatBasics in
239 match fmt with
240 (* Recognize the special form "%index[...whatever...]" *)
241 | Scan_char_set (Some idx, _, fmt)
242 (* [custom_specs] is empty if [explode] couldn't parse the string. In this case we
243 can have some scar char sets left. *)
244 when idx >= 0 && idx < Array.length custom_specs ->
245 let rest = self#fmt (fun _ -> assert false) f1 f2 f3 f4 f5 fmt in
246 let func = string_to_expr ~loc custom_specs.(idx) in
247 [%expr Custom (Custom_succ Custom_zero, (fun () -> [%e func]), [%e rest])]
248 | _ -> super#fmt f0 f1 f2 f3 f4 f5 fmt
249 end
250
251 let expand_format_string ~loc fmt_string =
252 let processed_fmt_string, custom_specs =
253 extract_custom_format_specifications ~loc fmt_string
254 in
255 let (CamlinternalFormat.Fmt_EBB fmt) =
256 try CamlinternalFormat.fmt_ebb_of_string processed_fmt_string with
257 | e ->
258 Location.raise_errorf
259 ~loc
260 "%s"
261 (match e with
262 (* [fmt_ebb_of_string] normally raises [Failure] on invalid input *)
263 | Failure msg -> msg
264 | e -> Exn.to_string e)
265 in
266 let lifter = new lifter ~loc ~custom_specs in
267 let format6 = CamlinternalFormatBasics.Format (fmt, fmt_string) in
268 let phantom _ = assert false in
269 let e = lifter#format6 phantom phantom phantom phantom phantom phantom format6 in
270 [%expr ([%e e] : (_, _, _, _, _, _) CamlinternalFormatBasics.format6)]
271 ;;
272
273 let expand e =
274 match e.pexp_desc with
275 | Pexp_apply
276 ( { pexp_attributes = ident_attrs; _ }
277 , [ ( Nolabel
278 , { pexp_desc = Pexp_constant (Pconst_string (str, _, _))
279 ; pexp_loc = loc
280 ; pexp_loc_stack = _
281 ; pexp_attributes = str_attrs
282 } )
283 ] ) ->
284 assert_no_attributes ident_attrs;
285 assert_no_attributes str_attrs;
286 let e' = expand_format_string ~loc str in
287 Some { e' with pexp_attributes = Merlin_helpers.hide_attribute :: e.pexp_attributes }
288 | _ -> None
289 ;;
290
291 let () =
292 Driver.register_transformation
293 "custom_printf"
294 ~rules:[ Context_free.Rule.special_function "!" expand ]
295 ;;