Source file sedlex.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
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
module Cset = Cset
type tag_op =
| Set_position of { dst : int }
| Set_value of { dst : int; value : int }
| Copy of { dst : int; src : int }
type node = {
id : int; (** Unique identifier; nodes are compared by it. *)
mutable eps : node list; (** Epsilon successors (no input consumed). *)
mutable trans : (Cset.t * node) list; (** Char-set-labelled transitions. *)
tag : tag_op option; (** Tag operation executed when entering this node. *)
}
type regexp = node -> node
let cur_id = ref 0
let new_node () =
incr cur_id;
{ id = !cur_id; eps = []; trans = []; tag = None }
let new_tagged_node tag_op =
incr cur_id;
{ id = !cur_id; eps = []; trans = []; tag = Some tag_op }
let seq r1 r2 succ = r1 (r2 succ)
let is_chars final = function
| { eps = []; trans = [(c, f)]; tag = None; _ } when f == final -> Some c
| _ -> None
let chars c succ =
let n = new_node () in
n.trans <- [(c, succ)];
n
let alt r1 r2 succ =
let nr1 = r1 succ and nr2 = r2 succ in
match (is_chars succ nr1, is_chars succ nr2) with
| Some c1, Some c2 -> chars (Cset.union c1 c2) succ
| _ ->
let n = new_node () in
n.eps <- [nr1; nr2];
n
let rep r succ =
let n = new_node () in
n.eps <- [r n; succ];
n
let plus r succ = r (rep r succ)
let eps succ = succ
let rec repeat r n m succ =
assert (0 <= n && n <= m);
match (n, m) with
| 0, 0 -> succ
| 0, m -> alt (fun succ -> r (repeat r 0 (m - 1) succ)) eps succ
| n, m -> r (repeat r (n - 1) (m - 1) succ)
let compl r =
let n = new_node () in
match is_chars n (r n) with
| Some c -> Some (chars (Cset.difference Cset.any c))
| _ -> None
let pair_op f r0 r1 =
let n = new_node () in
let to_chars r = is_chars n (r n) in
match (to_chars r0, to_chars r1) with
| Some c0, Some c1 -> Some (chars (f c0 c1))
| _ -> None
let subtract = pair_op Cset.difference
let intersection = pair_op Cset.intersection
let cur_tag = ref 0
let reset_tags () = cur_tag := 0
let new_tag () =
let t = !cur_tag in
incr cur_tag;
t
let bind r =
let start_tag = new_tag () in
let end_tag = new_tag () in
let wrapped succ =
let end_node = new_tagged_node (Set_position { dst = end_tag }) in
end_node.eps <- [succ];
let inner = r end_node in
let start_node = new_tagged_node (Set_position { dst = start_tag }) in
start_node.eps <- [inner];
start_node
in
(wrapped, start_tag, end_tag)
let bind_start_only r =
let start_tag = new_tag () in
let wrapped succ =
let inner = r succ in
let start_node = new_tagged_node (Set_position { dst = start_tag }) in
start_node.eps <- [inner];
start_node
in
(wrapped, start_tag)
let bind_end_only r =
let end_tag = new_tag () in
let wrapped succ =
let end_node = new_tagged_node (Set_position { dst = end_tag }) in
end_node.eps <- [succ];
r end_node
in
(wrapped, end_tag)
let new_disc_cell () = new_tag ()
let bind_disc r cell value =
let wrapped succ =
let disc_node = new_tagged_node (Set_value { dst = cell; value }) in
disc_node.eps <- [succ];
r disc_node
in
wrapped
type rule = { entry : node; final : node }
let compile_re (re : regexp) : rule =
let final = new_node () in
{ entry = re final; final }
type accept = { rule : int; final_ops : tag_op list }
type dfa_state = {
trans : (Cset.t * int * tag_op list) array;
accept : accept option;
}
type dfa = dfa_state array
type compiled = { dfa : dfa; num_tags : int }
let op_dest = function
| Copy { dst; _ } | Set_position { dst } | Set_value { dst; _ } -> dst
type cell = int
module TagMap = Map.Make (Int)
module CellMap = Map.Make (Int)
type write = Position | Value of int
let op_of_write (dst : cell) : write -> tag_op = function
| Position -> Set_position { dst }
| Value value -> Set_value { dst; value }
type addr = Cell of cell | Pending of write
type 'a config = { node : node; tags : 'a TagMap.t; delayed : write TagMap.t }
type 'a state = 'a config list
type candidate = addr state
type stored = cell state
let is_relevant (node : node) : bool = node.trans <> [] || node.eps = []
let eps_closure (seeds : addr config list) : candidate =
let visited = Hashtbl.create 16 in
let acc = ref [] in
let rec visit node tags delayed =
if not (Hashtbl.mem visited node.id) then (
Hashtbl.add visited node.id ();
let delayed =
match node.tag with
| None -> delayed
| Some (Set_position { dst }) -> TagMap.add dst Position delayed
| Some (Set_value { dst; value }) ->
TagMap.add dst (Value value) delayed
| Some (Copy _) -> assert false
in
if is_relevant node then acc := { node; tags; delayed } :: !acc;
List.iter (fun n -> visit n tags delayed) node.eps)
in
List.iter (fun c -> visit c.node c.tags c.delayed) seeds;
List.rev !acc
let split_moves (moves : (Cset.t * addr config) list) :
(Cset.t * addr config list) list =
let add_move pieces (cset, cfg) =
let rec insert cset pieces =
if Cset.is_empty cset then pieces
else (
match pieces with
| [] -> [(cset, [cfg])]
| (piece, seeds) :: rest ->
let inter = Cset.intersection piece cset in
if Cset.is_empty inter then (piece, seeds) :: insert cset rest
else (
let piece_only = Cset.difference piece inter in
let cset_rest = Cset.difference cset inter in
let with_cfg = (inter, seeds @ [cfg]) in
if Cset.is_empty piece_only then
with_cfg :: insert cset_rest rest
else (piece_only, seeds) :: with_cfg :: insert cset_rest rest))
in
insert cset pieces
in
List.fold_left add_move [] moves
module Registers : sig
type t
val create : num_logical:int -> t
val alloc : t -> cell
val is_working : t -> cell -> bool
val count : t -> int
end = struct
type t = { num_logical : int; mutable next_cell : int }
let create ~num_logical = { num_logical; next_cell = num_logical }
let alloc t =
let c = t.next_cell in
t.next_cell <- c + 1;
c
let is_working t c = c >= t.num_logical
let count t = t.next_cell
end
module State_key : sig
type t
val of_candidate : candidate -> t
module Tbl : Hashtbl.S with type key = t
end = struct
type t = (int * (int * int) list * (int * write) list) list
let of_candidate configs =
let tbl = Hashtbl.create 8 in
let canon tag a =
match Hashtbl.find_opt tbl (tag, a) with
| Some i -> i
| None ->
let i = Hashtbl.length tbl in
Hashtbl.add tbl (tag, a) i;
i
in
List.map
(fun c ->
( c.node.id,
List.map (fun (t, a) -> (t, canon t a)) (TagMap.bindings c.tags),
TagMap.bindings c.delayed ))
configs
module Tbl = Hashtbl.Make (struct
type nonrec t = t
let equal = ( = )
let hash = Hashtbl.hash
end)
end
type state_table = {
by_key : int State_key.Tbl.t;
configs : (int, stored) Hashtbl.t;
defs : (int, dfa_state) Hashtbl.t;
mutable n_states : int;
}
let make_state_table () : state_table =
{
by_key = State_key.Tbl.create 31;
configs = Hashtbl.create 31;
defs = Hashtbl.create 31;
n_states = 0;
}
let add_state (tbl : state_table) (key : State_key.t) (configs : stored) : int =
let num = tbl.n_states in
tbl.n_states <- num + 1;
State_key.Tbl.add tbl.by_key key num;
Hashtbl.add tbl.configs num configs;
num
type ctx = { regs : Registers.t; rules : rule array; tbl : state_table }
let assign_cells (regs : Registers.t) (candidate : candidate) :
stored * tag_op list =
let assigned = Hashtbl.create 4 in
let ops = ref [] in
let cell_for_new tag w =
match Hashtbl.find_opt assigned (tag, w) with
| Some c -> c
| None ->
let c = Registers.alloc regs in
Hashtbl.add assigned (tag, w) c;
ops := op_of_write c w :: !ops;
c
in
let configs =
List.map
(fun c ->
{
c with
tags =
TagMap.mapi
(fun tag a ->
match a with
| Cell cell -> cell
| Pending w -> cell_for_new tag w)
c.tags;
})
candidate
in
(configs, !ops)
let register_moves (candidate : candidate) (existing : stored) : tag_op list =
let moves = ref CellMap.empty in
let set_move dst op =
match CellMap.find_opt dst !moves with
| None -> moves := CellMap.add dst op !moves
| Some op' -> assert (op = op')
in
List.iter2
(fun cand ex ->
TagMap.iter
(fun tag a ->
let dst = TagMap.find tag ex.tags in
match a with
| Cell src -> if src <> dst then set_move dst (Copy { dst; src })
| Pending w -> set_move dst (op_of_write dst w))
cand.tags)
candidate existing;
List.map snd (CellMap.bindings !moves)
let final_ops_of (regs : Registers.t) (accepting : cell config) : tag_op list =
let copies =
TagMap.fold
(fun tag cell acc ->
if cell = tag || TagMap.mem tag accepting.delayed then acc
else (
assert (Registers.is_working regs cell);
Copy { dst = tag; src = cell } :: acc))
accepting.tags []
in
TagMap.fold
(fun tag w acc -> op_of_write tag w :: acc)
accepting.delayed copies
let accept_of (ctx : ctx) (configs : stored) : accept option =
let n = Array.length ctx.rules in
let rec first_accepting rule =
if rule = n then None
else (
let final = ctx.rules.(rule).final in
match List.find_opt (fun c -> c.node == final) configs with
| Some accepting ->
Some { rule; final_ops = final_ops_of ctx.regs accepting }
| None -> first_accepting (rule + 1))
in
first_accepting 0
let rec find_or_add_state (ctx : ctx) (candidate : candidate) :
int * tag_op list =
let key = State_key.of_candidate candidate in
match State_key.Tbl.find_opt ctx.tbl.by_key key with
| Some num ->
(num, register_moves candidate (Hashtbl.find ctx.tbl.configs num))
| None ->
let configs, ops = assign_cells ctx.regs candidate in
let num = add_state ctx.tbl key configs in
build_state ctx num configs;
(num, ops)
and build_state (ctx : ctx) (num : int) (configs : stored) : unit =
let trans = transitions ctx configs in
let accept = accept_of ctx configs in
Hashtbl.add ctx.tbl.defs num { trans; accept }
and transitions (ctx : ctx) (configs : stored) :
(Cset.t * int * tag_op list) array =
let is_final c = Array.exists (fun r -> r.final == c.node) ctx.rules in
let moves_of ~eof c =
let tags =
TagMap.fold
(fun tag w tags -> TagMap.add tag (Pending w) tags)
c.delayed
(TagMap.map (fun cell -> Cell cell) c.tags)
in
List.filter_map
(fun (cset, node) ->
let cset =
if eof then Cset.intersection cset Cset.eof
else Cset.difference cset Cset.eof
in
if Cset.is_empty cset then None
else Some (cset, { node; tags; delayed = TagMap.empty }))
c.node.trans
in
let on_eof =
let seeds = List.concat (List.map (moves_of ~eof:true) configs) in
match List.find_opt is_final (eps_closure (List.map snd seeds)) with
| Some accepting -> [(Cset.eof, [accepting])]
| None -> []
in
let on_chars =
List.map
(fun (cset, seeds) -> (cset, eps_closure seeds))
(split_moves (List.concat (List.map (moves_of ~eof:false) configs)))
in
let pieces = Array.of_list (on_eof @ on_chars) in
Array.sort (fun (c1, _) (c2, _) -> compare c1 c2) pieces;
Array.map
(fun (cset, candidate) ->
let num, ops = find_or_add_state ctx candidate in
(cset, num, ops))
pieces
let compile (rs : regexp array) : compiled =
let rules = Array.map compile_re rs in
let ctx =
{
regs = Registers.create ~num_logical:!cur_tag;
rules;
tbl = make_state_table ();
}
in
let seeds =
List.map
(fun r -> { node = r.entry; tags = TagMap.empty; delayed = TagMap.empty })
(Array.to_list rules)
in
let num0, ops = find_or_add_state ctx (eps_closure seeds) in
assert (num0 = 0);
assert (ops = []);
{
dfa = Array.init ctx.tbl.n_states (Hashtbl.find ctx.tbl.defs);
num_tags = Registers.count ctx.regs;
}
type pos_expr =
| Tag of { tag : int; offset : int }
| Start_plus of int
| End_minus of int
type compiled_binding = {
name : string;
start_pos : pos_expr;
end_pos : pos_expr;
disc : (int * int) list;
}
type compiled_ir = {
dfa : dfa;
num_tags : int;
bindings : compiled_binding list array;
}
let shift_pos pe delta =
match (pe, delta) with
| Some (Start_plus n), Some d -> Some (Start_plus (n + d))
| Some (End_minus n), Some d -> Some (End_minus (n - d))
| Some (Tag { tag; offset }), Some d ->
Some (Tag { tag; offset = offset + d })
| _ -> None
let advance pe len = shift_pos pe len
let retreat pe len = shift_pos pe (Option.map Int.neg len)
let add_discriminators (branches : (regexp * compiled_binding list) list) =
let fold_alt = function
| [] -> assert false
| (r, _) :: rest -> List.fold_left (fun acc (r, _) -> alt acc r) r rest
in
let all_same =
match branches with
| [] | [_] -> true
| (_, first) :: rest -> List.for_all (fun (_, tags) -> tags = first) rest
in
if all_same then (fold_alt branches, snd (List.hd branches))
else (
let disc_cell = new_disc_cell () in
let stamp value tags =
List.map
(fun (ti : compiled_binding) ->
{ ti with disc = (disc_cell, value) :: ti.disc })
tags
in
let next_val = ref 0 in
let seen : (compiled_binding list * int) list ref = ref [] in
let get_value tags =
match List.assoc_opt tags !seen with
| Some v -> v
| None ->
let v = !next_val in
incr next_val;
seen := (tags, v) :: !seen;
v
in
let wrapped =
List.map
(fun (r, tags) ->
let v = get_value tags in
(bind_disc r disc_cell v, stamp v tags))
branches
in
(fold_alt wrapped, List.concat_map snd wrapped))
let rec lower ~left ~right (ir : Ir.t) : regexp * compiled_binding list =
match ir with
| Ir.Chars cset -> (chars cset, [])
| Ir.Eps -> (eps, [])
| Ir.Star inner ->
let r, _ = lower ~left:None ~right:None inner in
(rep r, [])
| Ir.Plus inner ->
let r, _ = lower ~left:None ~right:None inner in
(plus r, [])
| Ir.Rep (inner, n, m) ->
let r, _ = lower ~left:None ~right:None inner in
(repeat r n m, [])
| Ir.Capture (name, inner) ->
let r, tags = lower ~left ~right inner in
let elem_len = Ir.fixed_length inner in
let known_start =
match left with Some _ -> left | None -> retreat right elem_len
in
let known_end =
match right with
| Some _ -> right
| None -> advance known_start elem_len
in
let st, et, r =
match (known_start, known_end) with
| Some st, Some et -> (st, et, r)
| Some st, None ->
let wrapped, end_tag = bind_end_only r in
(st, Tag { tag = end_tag; offset = 0 }, wrapped)
| None, Some et ->
let wrapped, start_tag = bind_start_only r in
(Tag { tag = start_tag; offset = 0 }, et, wrapped)
| None, None -> (
match elem_len with
| Some len ->
let wrapped, start_tag = bind_start_only r in
( Tag { tag = start_tag; offset = 0 },
Tag { tag = start_tag; offset = len },
wrapped )
| None ->
let wrapped, start_tag, end_tag = bind r in
( Tag { tag = start_tag; offset = 0 },
Tag { tag = end_tag; offset = 0 },
wrapped ))
in
(r, { name; start_pos = st; end_pos = et; disc = [] } :: tags)
| Ir.Alt branches ->
let lowered = List.map (lower ~left ~right) branches in
add_discriminators lowered
| Ir.Seq elems ->
let _, rights =
List.fold_right
(fun e (acc, l) -> (retreat acc (Ir.fixed_length e), acc :: l))
elems (right, [])
in
let left_from_end_tag ir tags' =
match ir with
| Ir.Capture _ -> (
match tags' with
| { end_pos = Tag _ as et; _ } :: _ -> Some et
| _ -> None)
| _ -> None
in
let _, r_acc, tags_acc =
List.fold_left2
(fun (cur_left, r_acc, tags_acc) e right ->
let r', tags' = lower ~left:cur_left ~right e in
let new_left =
match advance cur_left (Ir.fixed_length e) with
| Some _ as s -> s
| None -> left_from_end_tag e tags'
in
(new_left, seq r_acc r', tags_acc @ tags'))
(left, eps, []) elems rights
in
(r_acc, tags_acc)
let compile_ir (rules : Ir.t array) =
Array.iter (fun ir -> Ir.check_invariant ir) rules;
reset_tags ();
let lowered =
Array.map
(fun ir ->
lower ~left:(Some (Start_plus 0)) ~right:(Some (End_minus 0)) ir)
rules
in
let regexps = Array.map fst lowered in
let bindings = Array.map snd lowered in
let compiled = compile regexps in
{ dfa = compiled.dfa; num_tags = compiled.num_tags; bindings }
let cset_to_label cset =
let escape_dot c =
match c with
| '"' -> "\\\""
| '\\' -> "\\\\"
| '<' -> "\\<"
| '>' -> "\\>"
| _ -> String.make 1 c
in
let format_interval (lo, hi) =
if lo = -1 && hi = -1 then "EOF"
else if lo = hi then
if lo >= 32 && lo <= 126 then "'" ^ escape_dot (Char.chr lo) ^ "'"
else Printf.sprintf "U+%04X" lo
else if lo >= 32 && lo <= 126 && hi >= 32 && hi <= 126 then
"'" ^ escape_dot (Char.chr lo) ^ "'-'" ^ escape_dot (Char.chr hi) ^ "'"
else Printf.sprintf "U+%04X-U+%04X" lo hi
in
String.concat ", "
(List.map format_interval (cset : Cset.t :> (int * int) list))
let tag_op_to_string = function
| Set_position { dst } -> "t" ^ string_of_int dst
| Set_value { dst; value } ->
"d" ^ string_of_int dst ^ "=" ^ string_of_int value
| Copy { dst; src } -> "t" ^ string_of_int dst ^ "<-t" ^ string_of_int src
let dfa_to_dot dfa =
let buf = Buffer.create 1024 in
let bprintf = Printf.bprintf in
bprintf buf "digraph {\n";
bprintf buf " rankdir=LR;\n";
bprintf buf " node [shape=circle];\n\n";
bprintf buf " _start [shape=point];\n";
bprintf buf " _start -> state0;\n\n";
Array.iteri
(fun i { trans; accept } ->
(match accept with
| None -> bprintf buf " state%d [label=\"%d\"];\n" i i
| Some { rule; final_ops } ->
let ops =
if final_ops = [] then ""
else
"\\n{"
^ String.concat "," (List.map tag_op_to_string final_ops)
^ "}"
in
bprintf buf
" state%d [label=\"%d\\n[rule %d]%s\", shape=doublecircle];\n" i
i rule ops);
Array.iter
(fun (cset, target, tags) ->
let label = cset_to_label cset in
let label =
if tags = [] then label
else
label ^ " {"
^ String.concat "," (List.map tag_op_to_string tags)
^ "}"
in
bprintf buf " state%d -> state%d [label=\"%s\"];\n" i target label)
trans)
dfa;
bprintf buf "}\n";
Buffer.contents buf