Source file preprocessor.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
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
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
type tokenizer = unit -> Parser.token * Pos.t
let mk_tokenizer ?(fname = "") lexbuf =
Sedlexing.set_filename lexbuf fname;
fun () ->
match Lexer.token lexbuf with
| Parser.PP_STRING (s, pos) -> (Parser.STRING s, pos)
| Parser.PP_REGEXP (r, flags, pos) -> (Parser.REGEXP (r, flags), pos)
| token -> (token, Sedlexing.lexing_bytes_positions lexbuf)
let eval_ifdefs tokenizer =
let state = ref 0 in
let rec token () =
let go_on () =
incr state;
token ()
in
let rec skip () =
match tokenizer () with
| Parser.PP_ENDIF, _ -> token ()
| Parser.PP_ELSE, _ -> go_on ()
| _ -> skip ()
in
match tokenizer () with
| (Parser.PP_IFDEF v, _ | Parser.PP_IFNDEF v, _) as tok ->
let test =
match fst tok with
| Parser.PP_IFDEF _ -> fun x -> x
| Parser.PP_IFNDEF _ -> not
| _ -> assert false
in
if test (Environment.has_builtin v) then go_on () else skip ()
| Parser.PP_IFVERSION (cmp, ver), _ ->
let current = Lang_string.Version.of_string Build_config.version in
let ver = Lang_string.Version.of_string ver in
let test =
let compare = Lang_string.Version.compare current ver in
match cmp with
| `Eq -> compare = 0
| `Geq -> compare >= 0
| `Leq -> compare <= 0
| `Gt -> compare > 0
| `Lt -> compare < 0
in
if test then go_on () else skip ()
| (Parser.PP_IFENCODER, _ | Parser.PP_IFNENCODER, _) as tok ->
let has_enc =
try
let fmt =
let token = fst (tokenizer ()) in
match token with
| Parser.ENCODER e ->
!Hooks.make_encoder ~pos:None (Term.make Term.unit) (e, [])
| _ -> failwith "expected an encoding format after %ifencoder"
in
!Hooks.has_encoder fmt
with _ -> false
in
let test =
if fst tok = Parser.PP_IFENCODER then fun x -> x else not
in
if test has_enc then go_on () else skip ()
| Parser.PP_ELSE, _ ->
if !state = 0 then failwith "no %ifdef to end here";
decr state;
skip ()
| Parser.PP_ENDIF, _ ->
if !state = 0 then failwith "no %ifdef to end here";
decr state;
token ()
| x -> x
in
token
type includer_entry = {
tokenizer : tokenizer;
path : string;
channel : in_channel;
}
exception Skip_optional
(** Expand %include statements by inserting the content of files. Filenames are
understood relatively to the current directory, which can be a relative path
such as "." or "..". *)
let includer ~pwd tokenizer =
let stack = Stack.create () in
let peek () =
try (Stack.top stack).tokenizer with Stack.Empty -> tokenizer
in
let current_dir () = try (Stack.top stack).path with Stack.Empty -> pwd in
let rec token () =
match peek () () with
| (Parser.PP_INCLUDE fname as tok), (_, curp)
| (Parser.PP_INCLUDE_EXTRA fname as tok), (_, curp) -> (
try
let resolved_fname =
try
Utils.check_readable ~current_dir:(current_dir ())
~pos:[(curp, curp)]
fname
with _ when tok = Parser.PP_INCLUDE_EXTRA fname ->
raise Skip_optional
in
let channel = open_in resolved_fname in
let lexbuf = Sedlexing.Utf8.from_channel channel in
let tokenizer = mk_tokenizer ~fname lexbuf in
Stack.push
{ tokenizer; path = Filename.dirname resolved_fname; channel }
stack;
token ()
with Skip_optional -> token ())
| (Parser.EOF, _) as tok ->
if Stack.is_empty stack then tok
else (
close_in (Stack.pop stack).channel;
token ())
| x -> x
in
token
type exp_item =
| String of string
| Expr of tokenizer
| Concat
| RPar
| LPar
| String_of
let expand_string ?fname tokenizer =
let state = Queue.create () in
let add pos x = Queue.add (x, pos) state in
let pop () = ignore (Queue.take state) in
let parse s pos =
let l = Regexp.split (Regexp.regexp "#{(.*?)}") s in
let l = if l = [] then [""] else l in
let add = add pos in
let rec parse = function
| s :: x :: l ->
let lexbuf = Sedlexing.Utf8.from_string x in
let tokenizer = mk_tokenizer ?fname lexbuf in
let tokenizer () = (fst (tokenizer ()), pos) in
List.iter add
[String s; Concat; LPar; String_of; Expr tokenizer; RPar; RPar];
if l <> [] then (
add Concat;
parse l)
| [x] -> add (String x)
| [] -> assert false
in
parse l
in
let rec token () =
if Queue.is_empty state then (
match tokenizer () with
| Parser.STRING s, pos ->
parse s pos;
if Queue.length state > 1 then (
add pos RPar;
(Parser.LPAR, pos))
else token ()
| x -> x)
else (
let el, pos = Queue.peek state in
match el with
| String s ->
pop ();
(Parser.STRING s, pos)
| Concat ->
pop ();
(Parser.BIN2 "^", pos)
| RPar ->
pop ();
(Parser.RPAR, pos)
| LPar ->
pop ();
(Parser.LPAR, pos)
| String_of ->
pop ();
(Parser.VARLPAR "string", pos)
| Expr tokenizer -> (
match tokenizer () with
| Parser.EOF, _ ->
pop ();
token ()
| x, _ -> (x, pos)))
in
token
type doc_type = [ `Full | `Argsof of string list ]
let tokenizer =
let documented_def decoration (doc, doc_startp) (startp, endp) =
let startp =
match doc_startp with Some startp -> startp | None -> startp
in
let doc =
List.map
(fun x ->
Regexp.substitute
(Regexp.regexp ~flags:[`g] "^\\s*#\\s?")
~subst:(fun _ -> "")
x)
doc
in
let doc =
if doc = [] then None
else (
let rec parse_doc (main, special, params, methods) = function
| [] -> (main, special, params, methods)
| line :: lines -> (
try
let sub =
Regexp.exec
(Regexp.regexp
"^\\s*@(category|docof|flag|param|method|argsof)\\s*(.*)$")
line
in
let s = Option.get (List.nth sub.Regexp.matches 2) in
match Option.get (List.nth sub.Regexp.matches 1) with
| "docof" ->
let doc = Doc.Value.get s in
let main =
if doc.description <> "" then doc.description :: main
else main
in
let params =
List.filter_map
(fun (l, a) ->
match a.Doc.Value.arg_description with
| Some d -> Some (l, d)
| None -> None)
doc.arguments
@ params
in
let doc_specials =
`Category (Doc.Value.string_of_category doc.category)
:: List.map
(fun f -> `Flag (Doc.Value.string_of_flag f))
doc.flags
in
parse_doc
(main, doc_specials @ special, params, methods)
lines
| "argsof" ->
let s, only, except =
try
let sub =
Regexp.exec
(Regexp.regexp
"^\\s*([^\\[]+)\\[([^\\]]+)\\]\\s*$")
s
in
let s = Option.get (List.nth sub.Regexp.matches 1) in
let args =
List.filter
(fun s -> s <> "")
(List.map String.trim
(String.split_on_char ','
(Option.get (List.nth sub.Regexp.matches 2))))
in
let only, except =
List.fold_left
(fun (only, except) v ->
if String.length v > 0 && v.[0] = '!' then
( only,
String.sub v 1 (String.length v - 1)
:: except )
else (v :: only, except))
([], []) args
in
(s, only, except)
with Not_found -> (s, [], [])
in
let doc = Doc.Value.get s in
let args =
List.filter
(fun (n, _) ->
match n with
| None -> false
| Some n -> (
match (only, except) with
| [], except -> not (List.mem n except)
| only, except ->
List.mem n only
&& not (List.mem n except)))
doc.arguments
in
let args =
List.filter_map
(fun (n, a) ->
Option.map
(fun d -> (n, d))
a.Doc.Value.arg_description)
args
in
parse_doc (main, special, args @ params, methods) lines
| "category" ->
parse_doc
(main, `Category s :: special, params, methods)
lines
| "flag" ->
parse_doc
(main, `Flag s :: special, params, methods)
lines
| "param" ->
let sub =
Regexp.exec
(Regexp.regexp "^(~?[a-zA-Z0-9_.]+)\\s*(.*)$")
s
in
let label = Option.get (List.nth sub.Regexp.matches 1) in
let descr = Option.get (List.nth sub.Regexp.matches 2) in
let label =
if label.[0] = '~' then
Some (String.sub label 1 (String.length label - 1))
else None
in
let rec parse_descr descr lines =
match lines with
| [] -> raise Not_found
| line :: lines ->
let line =
Regexp.substitute
(Regexp.regexp ~flags:[`g] "^ *")
~subst:(fun _ -> "")
line
in
let n = String.length line - 1 in
if line.[n] = '\\' then (
let descr = String.sub line 0 n :: descr in
parse_descr descr lines)
else (
let descr = List.rev (line :: descr) in
(String.concat "" descr, lines))
in
let descr, lines = parse_descr [] (descr :: lines) in
parse_doc
(main, special, (label, descr) :: params, methods)
lines
| "method" ->
let sub =
Regexp.exec
(Regexp.regexp "^(~?[a-zA-Z0-9_.]+)\\s*(.*)$")
s
in
let label = Option.get (List.nth sub.Regexp.matches 1) in
let descr = Option.get (List.nth sub.Regexp.matches 2) in
parse_doc
(main, special, params, (label, descr) :: methods)
lines
| d -> failwith ("Unknown documentation item: " ^ d)
with Not_found ->
parse_doc (line :: main, special, params, methods) lines)
in
let main, special, params, methods = parse_doc ([], [], [], []) doc in
let main = List.rev main in
let params =
List.map
(fun (l, d) ->
( l,
Doc.Value.
{
arg_type = "???";
arg_default = None;
arg_description = Some d;
} ))
(List.rev params)
in
let methods =
List.map
(fun (l, d) ->
(l, Doc.Value.{ meth_type = "???"; meth_description = Some d }))
(List.rev methods)
in
let main = String.concat "\n" main in
let main = Lang_string.unbreak_md main in
let category, flags =
List.fold_left
(fun (c, f) s ->
match s with `Category c -> (c, f) | `Flag flag -> (c, flag :: f))
("Uncategorized", []) special
in
let category = String.trim category in
let category =
match Doc.Value.category_of_string category with
| Some c -> c
| None ->
failwith
(Printf.sprintf "Unknown category: %s (%s)." category
(Pos.to_string (startp, endp)))
in
let flags =
let f f =
match Doc.Value.flag_of_string f with
| Some f -> f
| None ->
failwith
(Printf.sprintf "Unknown flag: %s (%s)." f
(Pos.to_string (startp, endp)))
in
List.map f flags
in
Some
Doc.Value.
{
typ = "???";
category;
flags;
description = main;
examples = [];
arguments = params;
methods;
})
in
(Parser.DEF (doc, decoration), (startp, endp))
in
let = ref ([], None) in
let rec token () =
match tokenizer () with
| Parser.PP_COMMENT c, (startp, _) ->
comment := (c, Some startp);
token ()
| Parser.PP_DEF decoration, pos ->
let decoration =
Parser_helper.let_decoration_of_lexer_let_decoration decoration
in
let c = !comment in
comment := ([], None);
documented_def decoration c pos
| x ->
comment := ([], None);
x
in
token
(** Special token in order to avoid 3.{s = "a"} to be parsed as a float followed
by a record. *)
let int_meth tokenizer =
let q = Queue.create () in
let fill () =
match tokenizer () with
| Parser.PP_INT_DOT_LCUR n, (spos, epos) ->
let a n pos =
{ pos with Lexing.pos_cnum = pos.Lexing.pos_cnum - n }
in
Queue.add_seq q
(List.to_seq
[
(Parser.INT n, (spos, a 2 epos));
(Parser.DOT, (a 2 spos, a 1 epos));
(Parser.LCUR, (a 1 spos, epos));
])
| t -> Queue.add t q
in
let token () =
if Queue.is_empty q then fill ();
Queue.pop q
in
token
let dotvar tokenizer =
let state = ref None in
let token () =
match !state with
| Some t ->
state := None;
t
| None -> (
match tokenizer () with
| Parser.DOTVAR v, pos ->
state := Some (Parser.VAR v, pos);
(Parser.DOT, pos)
| t -> t)
in
token
(** Change MINUS to UMINUS if the minus is not preceded by a number (or an
expression which could produce a number). *)
let uminus tokenizer =
let was_number = ref false in
let token () =
match tokenizer () with
| ( Parser.INT _, _
| Parser.FLOAT _, _
| Parser.VAR _, _
| Parser.RPAR, _
| Parser.RCUR, _ ) as t ->
was_number := true;
t
| Parser.MINUS, pos when not !was_number ->
was_number := false;
(Parser.UMINUS, pos)
| t ->
was_number := false;
t
in
token
let strip_newlines tokenizer =
let state = ref None in
let rec token () =
let inject_varlpar var v =
match tokenizer () with
| Parser.LPAR, (_, endp) ->
state := None;
let startp = fst (snd v) in
(Parser.VARLPAR var, (startp, endp))
| Parser.LBRA, (_, endp) when var <> "in" ->
state := None;
let startp = fst (snd v) in
(Parser.VARLBRA var, (startp, endp))
| Parser.PP_ENDL, _ ->
state := None;
v
| x ->
state := Some x;
v
in
match !state with
| None -> (
match tokenizer () with
| Parser.PP_ENDL, _ -> token ()
| (Parser.VAR _, _) as v ->
state := Some v;
token ()
| x -> x)
| Some ((Parser.VAR var, _) as v) -> inject_varlpar var v
| Some ((Parser.UNDERSCORE, _) as v) -> inject_varlpar "_" v
| Some x ->
state := None;
x
in
token
let mk_tokenizer ?fname ~pwd lexbuf =
let tokenizer =
mk_tokenizer ?fname lexbuf |> includer ~pwd |> eval_ifdefs |> parse_comments
|> expand_string ?fname |> int_meth |> dotvar |> uminus |> strip_newlines
in
fun () ->
let t, (startp, endp) = tokenizer () in
(t, startp, endp)