-
Notifications
You must be signed in to change notification settings - Fork 48
Expand file tree
/
Copy pathparser.ml
More file actions
1974 lines (1812 loc) · 57.2 KB
/
parser.ml
File metadata and controls
1974 lines (1812 loc) · 57.2 KB
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
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
open Ast.Impl
type link_kind =
| Reference
| Footnote of { id: string; label: string }
type 'attr link_def =
{ label : string
; destination : string
; title : string option
; attributes : 'attr
; kind : link_kind
}
let is_whitespace = function
| ' ' | '\t' | '\010' .. '\013' -> true
| _ -> false
let is_punct = function
| '!' | '"' | '#' | '$' | '%' | '&' | '\'' | '(' | ')' | '*' | '+' | ',' | '-'
| '.' | '/' | ':' | ';' | '<' | '=' | '>' | '?' | '@' | '[' | '\\' | ']' | '^'
| '_' | '`' | '{' | '|' | '}' | '~' ->
true
| _ -> false
exception Fail
(** Raised when a parser fails, used for control flow rather than error
handling *)
(** Stateful parser combinators *)
module P : sig
type state
type 'a t = state -> 'a
val of_string : string -> state
val peek : char option t
(** [Some c] if [c] is the next character in the input, or [None]
if the input is exhausted.
NOTE: Does not advance the state. *)
val peek_exn : char t
(** the next character in the input, or raises [Fail] if the
input is exhausted.
NOTE: Does not advance the state. *)
val peek_before : char -> state -> char
(** the previous character in the input, or the next
character, if we are at the start of the input.
NOTE: Does not advance the state. *)
val peek_after : char -> state -> char
(** the character after the next in the input, or the next
character, if we are at the end of the input.
NOTE: Does not advance the state. *)
val pos : state -> int
val range : state -> int -> int -> string
val set_pos : state -> int -> unit
val junk : unit t
(** ignores the next character in the input *)
val char : char -> unit t
(** accepts a [c] *)
val next : char t
val ws : unit t
(** accepts 0 or more white space characters *)
val sp : unit t
(** accepts 0 or more spaces or tabs *)
val ws1 : unit t
(** accepts 1 or more spaces or tabs, fails if none is found *)
val ( ||| ) : 'a t -> 'a t -> 'a t
(** [p ||| q] tries to accept [p], but in case [p] fails, it accepts [q]
(which can fail). *)
val ( >>> ) : unit t -> 'a t -> 'a t
(** [p >>> q] accepts [p] followed by [q], returning whatever [q] does *)
val ( <<< ) : 'a t -> unit t -> 'a t
(** [p >>> q] accepts [p] followed by [q], returning whatever [q] does *)
val protect : 'a t -> 'a t
(** run the given parser, resetting the state back to it's initial condition
if the parser fails *)
val pair : 'a t -> 'b t -> ('a * 'b) t
val on_sub : (StrSlice.t -> 'a * StrSlice.t) -> 'a t
(** Given a function [f] that takes a prefix of a string slice to a value [x]
of type ['a] and some remainder of the slice, [on_sub f] produces [x] from
the state, and advances the input the length of the slice that was
consumed by [f]. *)
end = struct
type state =
{ str : string
; mutable pos : int
}
let of_string str = { str; pos = 0 }
type 'a t = state -> 'a
let char c st =
if st.pos >= String.length st.str then raise Fail
else if st.str.[st.pos] <> c then raise Fail
else st.pos <- st.pos + 1
let next st =
if st.pos >= String.length st.str then raise Fail
else
let c = st.str.[st.pos] in
st.pos <- st.pos + 1;
c
let peek st =
if st.pos >= String.length st.str then None else Some st.str.[st.pos]
let peek_exn st = match peek st with Some c -> c | None -> raise Fail
let peek_before c st = if st.pos = 0 then c else st.str.[st.pos - 1]
let peek_after c st =
if st.pos + 1 >= String.length st.str then c else st.str.[st.pos + 1]
let pos st = st.pos
let range st pos n = String.sub st.str pos n
let set_pos st pos = st.pos <- pos
let junk st = if st.pos < String.length st.str then st.pos <- st.pos + 1
let protect p st =
let off = pos st in
try p st
with e ->
set_pos st off;
raise e
let ( ||| ) p1 p2 st = try protect p1 st with Fail -> p2 st
let ws st =
let rec loop () =
if is_whitespace (peek_exn st) then (
junk st;
loop ())
in
try loop () with Fail -> ()
let sp st =
let rec loop () =
match peek_exn st with
| ' ' | '\t' ->
junk st;
loop ()
| _ -> ()
in
try loop () with Fail -> ()
let ws1 st =
if is_whitespace (peek_exn st) then (
junk st;
ws st)
else raise Fail
let ( >>> ) p q st =
p st;
q st
let ( <<< ) p q st =
let x = p st in
q st;
x
let pair p q st =
let x = p st in
let y = q st in
(x, y)
let on_sub fn st =
let result, s = fn (StrSlice.of_string ~off:st.pos st.str) in
st.pos <- StrSlice.get_offset s;
result
end
type html_kind =
| Hcontains of string list
| Hblank
type code_block_kind =
| Tilde
| Backtick
type t =
| Lempty
| Lblockquote of StrSlice.t
| Lthematic_break
| Latx_heading of int * string * attributes
| Lsetext_heading of
{ level : int
; len : int
} (** the level of the heading and how long the underline marker is *)
| Lfenced_code of int * int * code_block_kind * (string * string) * attributes
| Lindented_code of StrSlice.t
| Lhtml of bool * html_kind
| Llist_item of list_type * int * StrSlice.t
| Lparagraph
| Ldef_list of string
| Ltable_line of StrSlice.t list
(* drop up to 3 spaces, returning the number of spaces dropped and the remainder of the string *)
let sp3 s =
match StrSlice.take 3 s with
| [ ' '; ' '; ' ' ] -> (3, StrSlice.drop 3 s)
| ' ' :: ' ' :: _ -> (2, StrSlice.drop 2 s)
| ' ' :: _ -> (1, StrSlice.drop 1 s)
| _ -> (0, s)
(** TODO Why is this here? Doesn't it almost exactly repeat the one in [P], only with slices?
Why is this kind of repetition needed? *)
let ( ||| ) p1 p2 s = try p1 s with Fail -> p2 s
let trim_leading_ws s = StrSlice.drop_while is_whitespace s
let trim_trailing_ws s = StrSlice.drop_last_while is_whitespace s
let trim_ws s = trim_leading_ws s |> trim_trailing_ws
let is_empty s = StrSlice.is_empty (trim_leading_ws s)
(* See https://spec.commonmark.org/0.30/#thematic-breaks *)
let thematic_break =
(* Accepts thematic break chars or fail, counting how many chars we find *)
let f symb c count =
if Char.equal symb c then succ count
else if is_whitespace c then
(* Thematic break chars can be separated by spaces *)
count
else raise Fail
in
fun s ->
match StrSlice.head s with
| Some (('*' | '_' | '-') as symb) ->
if StrSlice.fold_left (f symb) 0 s >= 3 then
(* Three or more of the same thematic break chars found *)
Lthematic_break
else raise Fail
| Some _ | None -> raise Fail
(* See https://spec.commonmark.org/0.30/#setext-heading *)
let setext_heading s =
(* The first char determines if possible setext and the level of the heading *)
let level, symb =
match StrSlice.head s with
| Some '=' -> (1, '=')
| Some '-' -> (2, '-')
| _ -> raise Fail
in
let heading_chars, rest =
StrSlice.split_at (fun c -> not (Char.equal c symb)) s
in
let len = StrSlice.length heading_chars in
if Char.equal symb '-' && len = 1 then
(* can be interpreted as an empty list item *)
raise Fail
else if not (StrSlice.for_all is_whitespace rest) then
(* if anything except whitespace is left, it can't be a setext heading underline *)
raise Fail
else Lsetext_heading { level; len }
(* Parses a string slice in pandoc-style into an association list
See https://pandoc.org/MANUAL.html#extension-header_attributes *)
let parse_attributes s =
let attributes = String.split_on_char ' ' s in
let f (id, classes, acc) s =
if s = "" then (id, classes, acc)
else
match s.[0] with
| '#' -> (Some (String.sub s 1 (String.length s - 1)), classes, acc)
| '.' -> (id, String.sub s 1 (String.length s - 1) :: classes, acc)
| _ -> (
let attr = String.split_on_char '=' s in
match attr with
| [] -> (id, classes, acc)
| h :: t -> (id, classes, (h, String.concat "=" t) :: acc))
in
let id, classes, acc = List.fold_left f (None, [], []) attributes in
let acc = List.rev acc in
let acc =
match classes with
| [] -> acc
| _ :: _ ->
let classes = String.concat " " (List.rev classes) in
("class", classes) :: acc
in
match id with Some id -> ("id", id) :: acc | None -> acc
(* Parses a string slice into an attribute list (possibly empty) and the non-attribute part of the string
These are pandoc style attributes https://pandoc.org/MANUAL.html#extension-attributes *)
let attribute_string s =
let buf = Buffer.create 64 in
let rec loop s =
match StrSlice.head s with
| None -> (StrSlice.of_string (Buffer.contents buf), None)
| Some ('\\' as c) -> (
let s = StrSlice.tail s in
match StrSlice.head s with
| Some c when is_punct c ->
Buffer.add_char buf c;
loop (StrSlice.tail s)
| Some _ | None ->
Buffer.add_char buf c;
loop s)
| Some '{' ->
let buf' = Buffer.create 64 in
let rec loop' s =
match StrSlice.head s with
| Some '}' -> (
(* Found a closing bracket not at the end of the line *)
let s = StrSlice.tail s in
match StrSlice.head s with
| None ->
(* At end of line, so we've finished parsing the attributes *)
( StrSlice.of_string (Buffer.contents buf)
, Some (Buffer.contents buf') )
| Some _ ->
(* Not at end of line, so this can't be a set of attributes *)
Buffer.add_char buf '{';
Buffer.add_buffer buf buf';
Buffer.add_char buf '}';
loop s)
| None ->
Buffer.add_char buf '{';
Buffer.add_buffer buf buf';
(StrSlice.of_string (Buffer.contents buf), None)
| Some '{' ->
Buffer.add_char buf '{';
Buffer.add_buffer buf buf';
Buffer.reset buf';
loop' (StrSlice.tail s)
| Some c ->
Buffer.add_char buf' c;
loop' (StrSlice.tail s)
in
loop' (StrSlice.tail s)
| Some c ->
Buffer.add_char buf c;
loop (StrSlice.tail s)
in
let s', a = loop (trim_leading_ws s) in
let attrs = Option.map parse_attributes a |> Option.value ~default:[] in
(s', attrs)
let atx_heading s =
let rec loop n s =
if n > 6 then raise Fail;
match StrSlice.head s with
| Some '#' -> loop (succ n) (StrSlice.tail s)
| Some w when is_whitespace w ->
let s, a =
match StrSlice.last s with
| Some '}' -> attribute_string s
| _ -> (s, [])
in
let s = trim_ws s in
let rec loop t =
match StrSlice.last t with
| Some '#' -> loop (StrSlice.drop_last t)
| Some w when is_whitespace w -> trim_trailing_ws t
| None -> trim_trailing_ws t
| Some _ -> s
in
Latx_heading (n, StrSlice.to_string (trim_leading_ws (loop s)), a)
| Some _ -> raise Fail
| None -> Latx_heading (n, StrSlice.to_string s, [])
in
loop 0 s
let entity s =
match StrSlice.take 2 s with
| '#' :: ('x' | 'X') :: _ ->
let rec loop m n s =
if m > 6 then raise Fail;
match StrSlice.head s with
| Some ('a' .. 'f' as c) ->
loop
(succ m)
((n * 16) + Char.code c - Char.code 'a' + 10)
(StrSlice.tail s)
| Some ('A' .. 'F' as c) ->
loop
(succ m)
((n * 16) + Char.code c - Char.code 'A' + 10)
(StrSlice.tail s)
| Some ('0' .. '9' as c) ->
loop
(succ m)
((n * 16) + Char.code c - Char.code '0')
(StrSlice.tail s)
| Some ';' ->
if m = 0 then raise Fail;
let u =
if n = 0 || not (Uchar.is_valid n) then Uchar.rep
else Uchar.of_int n
in
([ u ], StrSlice.tail s)
| Some _ | None -> raise Fail
in
loop 0 0 (StrSlice.drop 2 s)
| '#' :: _ ->
let rec loop m n s =
if m > 7 then raise Fail;
match StrSlice.head s with
| Some ('0' .. '9' as c) ->
loop
(succ m)
((n * 10) + Char.code c - Char.code '0')
(StrSlice.tail s)
| Some ';' ->
if m = 0 then raise Fail;
let u =
if n = 0 || not (Uchar.is_valid n) then Uchar.rep
else Uchar.of_int n
in
([ u ], StrSlice.tail s)
| Some _ | None -> raise Fail
in
loop 0 0 (StrSlice.tail s)
| ('a' .. 'z' | 'A' .. 'Z') :: _ ->
let rec loop len t =
match StrSlice.head t with
| Some ('a' .. 'z' | 'A' .. 'Z' | '0' .. '9') ->
loop (succ len) (StrSlice.tail t)
| Some ';' -> (
let name = StrSlice.to_string (StrSlice.sub ~len s) in
match Entities.f name with
| [] -> raise Fail
| cps -> (cps, StrSlice.tail t))
| Some _ | None -> raise Fail
in
loop 1 (StrSlice.tail s)
| _ -> raise Fail
let info_string c s =
let buf = Buffer.create 17 in
let s, a =
match StrSlice.last s with Some '}' -> attribute_string s | _ -> (s, [])
in
let s = trim_ws s in
let rec loop s =
match StrSlice.head s with
(* TODO use is_whitespace *)
| Some (' ' | '\t' | '\010' .. '\013') | None ->
if c = '`' && StrSlice.exists (function '`' -> true | _ -> false) s
then raise Fail;
((Buffer.contents buf, StrSlice.to_string (trim_leading_ws s)), a)
| Some '`' when c = '`' -> raise Fail
| Some ('\\' as c) -> (
let s = StrSlice.tail s in
match StrSlice.head s with
| Some c when is_punct c ->
Buffer.add_char buf c;
loop (StrSlice.tail s)
| Some _ | None ->
Buffer.add_char buf c;
loop s)
| Some ('&' as c) -> (
let s = StrSlice.tail s in
match entity s with
| ul, s ->
List.iter (Uutf.Buffer.add_utf_8 buf) ul;
loop s
| exception Fail ->
Buffer.add_char buf c;
loop s)
| Some c ->
Buffer.add_char buf c;
loop (StrSlice.tail s)
in
loop (trim_leading_ws s)
let fenced_code ind s =
match StrSlice.head s with
| Some (('`' | '~') as c) ->
let rec loop n s =
match StrSlice.head s with
| Some c1 when c = c1 -> loop (succ n) (StrSlice.tail s)
| Some _ | None ->
if n < 3 then raise Fail;
let s, a = info_string c s in
let c = if c = '`' then Backtick else Tilde in
Lfenced_code (ind, n, c, s, a)
in
loop 1 (StrSlice.tail s)
| Some _ | None -> raise Fail
let indent s =
let rec loop n s =
match StrSlice.head s with
| Some ' ' -> loop (n + 1) (StrSlice.tail s)
| Some '\t' -> loop (n + 4) (StrSlice.tail s)
| Some _ | None -> n
in
loop 0 s
let unordered_list_item ind s =
match StrSlice.head s with
| Some (('+' | '-' | '*') as c) ->
let s = StrSlice.tail s in
if is_empty s then Llist_item (Bullet c, 2 + ind, s)
else
let n = indent s in
if n = 0 then raise Fail;
let n = if n <= 4 then n else 1 in
Llist_item (Bullet c, n + 1 + ind, StrSlice.offset n s)
| Some _ | None -> raise Fail
let ordered_list_item ind s =
let rec loop n m s =
match StrSlice.head s with
| Some ('0' .. '9' as c) ->
if n >= 9 then raise Fail;
loop (succ n) ((m * 10) + Char.code c - Char.code '0') (StrSlice.tail s)
| Some (('.' | ')') as c) ->
let s = StrSlice.tail s in
if is_empty s then Llist_item (Ordered (m, c), n + 1 + ind, s)
else
let ind' = indent s in
if ind' = 0 then raise Fail;
let ind' = if ind' <= 4 then ind' else 1 in
Llist_item (Ordered (m, c), n + ind + ind' + 1, StrSlice.offset ind' s)
| Some _ | None -> raise Fail
in
loop 0 0 s
let tag_name s0 =
match StrSlice.head s0 with
| Some ('a' .. 'z' | 'A' .. 'Z') ->
let rec loop len s =
match StrSlice.head s with
| Some ('a' .. 'z' | 'A' .. 'Z' | '0' .. '9' | '-') ->
loop (succ len) (StrSlice.tail s)
| Some _ | None -> (StrSlice.to_string (StrSlice.sub s0 ~len), s)
in
loop 1 (StrSlice.tail s0)
| Some _ | None -> raise Fail
let known_tags =
[ "address"
; "aside"
; "base"
; "basefont"
; "blockquote"
; "body"
; "caption"
; "center"
; "col"
; "colgroup"
; "dd"
; "details"
; "dialog"
; "dir"
; "div"
; "dl"
; "dt"
; "fieldset"
; "figcaption"
; "figure"
; "footer"
; "form"
; "frame"
; "frameset"
; "h1"
; "h2"
; "h3"
; "h4"
; "h5"
; "h6"
; "head"
; "header"
; "hr"
; "html"
; "iframe"
; "legend"
; "li"
; "link"
; "main"
; "menu"
; "menuitem"
; "meta"
; "nav"
; "noframes"
; "ol"
; "optgroup"
; "option"
; "p"
; "param"
; "section"
; "source"
; "summary"
; "table"
; "tbody"
; "td"
; "tfoot"
; "th"
; "thead"
; "title"
; "tr"
; "track"
; "ul"
]
let special_tags = [ "pre"; "script"; "style"; "textarea" ]
let known_tag s =
let s = String.lowercase_ascii s in
List.mem s known_tags
let special_tag s =
let s = String.lowercase_ascii s in
List.mem s special_tags
let closing_tag s =
let s = trim_leading_ws s in
match StrSlice.head s with
| Some '>' ->
if not (is_empty (StrSlice.tail s)) then raise Fail;
Lhtml (false, Hblank)
| Some _ | None -> raise Fail
let special_tag tag s =
if not (special_tag tag) then raise Fail;
match StrSlice.head s with
| Some (' ' | '\t' | '\010' .. '\013' | '>') | None ->
Lhtml (true, Hcontains [ "</script>"; "</pre>"; "</style>" ])
| Some _ -> raise Fail
let known_tag tag s =
if not (known_tag tag) then raise Fail;
match StrSlice.take 2 s with
| (' ' | '\t' | '\010' .. '\013') :: _ | [] | '>' :: _ | '/' :: '>' :: _ ->
Lhtml (true, Hblank)
| _ -> raise Fail
(** TODO Why these repeated functions that look just like thos in [P]? *)
let ws1 s =
match StrSlice.head s with
| Some w when is_whitespace w -> trim_leading_ws s
| Some _ | None -> raise Fail
let attribute_name s =
match StrSlice.head s with
| Some ('a' .. 'z' | 'A' .. 'Z' | '_' | ':') ->
let rec loop s =
match StrSlice.head s with
| Some ('a' .. 'z' | 'A' .. 'Z' | '_' | '.' | ':' | '0' .. '9') ->
loop (StrSlice.tail s)
| Some _ | None -> s
in
loop s
| Some _ | None -> raise Fail
let attribute_value s =
match StrSlice.head s with
| Some (('\'' | '"') as c) ->
let rec loop s =
match StrSlice.head s with
| Some c1 when c = c1 -> StrSlice.tail s
| Some _ -> loop (StrSlice.tail s)
| None -> raise Fail
in
loop (StrSlice.tail s)
| Some _ ->
let rec loop first s =
match StrSlice.head s with
| Some
(' ' | '\t' | '\010' .. '\013' | '"' | '\'' | '=' | '<' | '>' | '`')
| None ->
if first then raise Fail;
s
| Some _ -> loop false (StrSlice.tail s)
in
loop true s
| None -> raise Fail
let attribute s =
let s = ws1 s in
let s = attribute_name s in
let s = trim_leading_ws s in
match StrSlice.head s with
| Some '=' ->
let s = trim_leading_ws (StrSlice.tail s) in
attribute_value s
| Some _ | None -> s
let attributes s =
let rec loop s = match attribute s with s -> loop s | exception Fail -> s in
loop s
let open_tag s =
let s = attributes s in
let s = trim_leading_ws s in
let n =
match StrSlice.take 2 s with
| '/' :: '>' :: _ -> 2
| '>' :: _ -> 1
| _ -> raise Fail
in
if not (is_empty (StrSlice.drop n s)) then raise Fail;
Lhtml (false, Hblank)
let raw_html s =
match StrSlice.take 10 s with
| '<' :: '?' :: _ -> Lhtml (true, Hcontains [ "?>" ])
| '<' :: '!' :: '-' :: '-' :: _ -> Lhtml (true, Hcontains [ "-->" ])
| '<' :: '!' :: '[' :: 'C' :: 'D' :: 'A' :: 'T' :: 'A' :: '[' :: _ ->
Lhtml (true, Hcontains [ "]]>" ])
| '<' :: '!' :: _ -> Lhtml (true, Hcontains [ ">" ])
| '<' :: '/' :: _ ->
let tag, s = tag_name (StrSlice.drop 2 s) in
(known_tag tag ||| closing_tag) s
| '<' :: _ ->
let tag, s = tag_name (StrSlice.drop 1 s) in
(special_tag tag ||| known_tag tag ||| open_tag) s
| _ -> raise Fail
let blank s =
if not (is_empty s) then raise Fail;
Lempty
let tag_string s =
let buf = Buffer.create 17 in
let s, a =
match StrSlice.last s with Some '}' -> attribute_string s | _ -> (s, [])
in
let s = trim_ws s in
let rec loop s =
match StrSlice.head s with
(* TODO use is_whitespace *)
| Some (' ' | '\t' | '\010' .. '\013') | None -> (Buffer.contents buf, a)
| Some c ->
Buffer.add_char buf c;
loop (StrSlice.tail s)
in
loop (trim_leading_ws s)
let def_list s =
let s = StrSlice.tail s in
match StrSlice.head s with
| Some w when is_whitespace w ->
Ldef_list (String.trim (StrSlice.to_string s))
| _ -> raise Fail
let indented_code ind s =
if indent s + ind < 4 then raise Fail;
Lindented_code (StrSlice.offset (4 - ind) s)
(* A sequence of cell contents separated by unescaped '|'
characters. *)
let table_row ~pipe_prefix s =
let rec loop items seen_pipe s =
match StrSlice.index_unescaped '|' s with
| None ->
if StrSlice.for_all is_whitespace s then (items, seen_pipe)
else (s :: items, false)
| Some i ->
let item = StrSlice.take_prefix i s in
loop (item :: items) true (StrSlice.drop (i + 1) s)
in
let items, terminating_pipe = loop [] pipe_prefix s in
match (pipe_prefix, items, terminating_pipe) with
| true, _, _ | _, _ :: _, true | _, _ :: _ :: _, _ ->
Ltable_line (List.rev_map StrSlice.trim items)
| _ -> raise Fail
let parse s0 =
let ind, s = sp3 s0 in
match StrSlice.head s with
| Some '>' ->
let s = StrSlice.offset 1 s in
let s = if indent s > 0 then StrSlice.offset 1 s else s in
Lblockquote s
| Some '=' -> (setext_heading ||| table_row ~pipe_prefix:false) s
| Some '-' ->
(setext_heading
||| thematic_break
||| unordered_list_item ind
||| table_row ~pipe_prefix:false)
s
| Some '_' -> thematic_break s
| Some '#' -> atx_heading s
| Some ('~' | '`') -> fenced_code ind s
| Some '<' -> raw_html s
| Some '*' -> (thematic_break ||| unordered_list_item ind) s
| Some '+' -> unordered_list_item ind s
| Some '0' .. '9' ->
(ordered_list_item ind ||| table_row ~pipe_prefix:false) s
| Some ':' -> (def_list ||| table_row ~pipe_prefix:false) s
| Some '|' -> table_row ~pipe_prefix:true (StrSlice.tail s)
| Some _ -> (blank ||| indented_code ind ||| table_row ~pipe_prefix:false) s
| None -> Lempty
let parse s = try parse s with Fail -> Lparagraph
open P
let is_empty st =
let off = pos st in
try
let rec loop () =
match next st with
| c when is_whitespace c -> loop ()
| _ ->
set_pos st off;
false
in
loop ()
with Fail ->
set_pos st off;
true
let inline_attribute_string s =
let ppos = pos s in
ws s;
let a =
match peek s with
| Some '{' ->
let buf = Buffer.create 64 in
let rec loop s pos =
match peek s with
| Some '}' ->
junk s;
Some (Buffer.contents buf)
| None | Some '{' ->
set_pos s pos;
None
| Some c ->
Buffer.add_char buf c;
junk s;
loop s pos
in
junk s;
loop s (pos s)
| _ -> None
in
let attr = Option.map parse_attributes a |> Option.value ~default:[] in
if attr = [] then set_pos s ppos;
attr
let entity buf st =
junk st;
match on_sub entity st with
| cs -> List.iter (Uutf.Buffer.add_utf_8 buf) cs
| exception Fail -> Buffer.add_char buf '&'
module Pre = struct
type delim =
| Ws
| Punct
| Other
type emph_style =
| Star
| Underscore
type link_kind =
| Img
| Url
type t =
| Bang_left_bracket
| Left_bracket of link_kind
| Emph of delim * delim * emph_style * int
| R of attributes inline
let concat = function [ x ] -> x | l -> Concat ([], l)
let left_flanking = function
| Emph (_, Other, _, _) | Emph ((Ws | Punct), Punct, _, _) -> true
| _ -> false
let right_flanking = function
| Emph (Other, _, _, _) | Emph (Punct, (Ws | Punct), _, _) -> true
| _ -> false
let is_opener = function
| Emph (pre, _, Underscore, _) as x ->
left_flanking x && ((not (right_flanking x)) || pre = Punct)
| Emph (_, _, Star, _) as x -> left_flanking x
| _ -> false
let is_closer = function
| Emph (_, post, Underscore, _) as x ->
right_flanking x && ((not (left_flanking x)) || post = Punct)
| Emph (_, _, Star, _) as x -> right_flanking x
| _ -> false
let classify_delim = function
| '!' | '"' | '#' | '$' | '%' | '&' | '\'' | '(' | ')' | '*' | '+' | ','
| '-' | '.' | '/' | ':' | ';' | '<' | '=' | '>' | '?' | '@' | '[' | '\\'
| ']' | '^' | '_' | '`' | '{' | '|' | '}' | '~' ->
Punct
| ' ' | '\t' | '\010' .. '\013' | '\160' -> Ws
| _ -> Other
let to_r = function
| Bang_left_bracket -> Text ([], "![")
| Left_bracket Img -> Text ([], "![")
| Left_bracket Url -> Text ([], "[")
| Emph (_, _, Star, n) -> Text ([], String.make n '*')
| Emph (_, _, Underscore, n) -> Text ([], String.make n '_')
| R x -> x
let rec find_next_emph = function
| Emph (pre, post, style, n) :: _ -> Some (pre, post, style, n)
| _ :: xs -> find_next_emph xs
| [] -> None
let rec find_next_closer_emph = function
| (Emph (pre, post, style, n) as e) :: _ when is_closer e ->
Some (pre, post, style, n)
| _ :: xs -> find_next_closer_emph xs
| [] -> None
(* Checks the lengths of two different emphasis delimiters to see if there can be a match.
From the spec: "If one of the delimiters can both open and close emphasis, then the sum of the lengths
of the delimiter runs containing the opening and closing delimiters must not be
a multiple of 3 unless both lengths are multiples of 3" *)
let is_emph_match n1 n2 =
(*
- *foo**bar**baz*
*foo** -> the second delimiter ** is both an opening and closing delimiter.
The sum of the length of both delimiters is 3, so they can't be matched.
**bar** -> they are both opening and closing delemiters.
Their sum is 4 which is not a multiple of 3 so they can be matched to produce <strong>bar</strong>
The end result is: <em>foo<strong>bar</strong>baz</em>
- *foo***bar**baz*
*foo*** -> *** is both an opening and closing delimiter.
Their sum is 4 so they can be matched to produce: <em>foo</em>**
**bar** -> they are both opening and closing delemiters.
Their sum is 4 which is not a multiple of 3 so they can be matched to produce <strong>bar</strong>
The end result is: <em>foo</em><strong>bar</strong>baz*
- ***foo***bar**baz*
***foo*** -> the second delimiter *** is both an opening and closing delimiter.
Their sum is 6 which is a multiple of 3. However, both lengths are multiples of 3
so they can be matched to produce: <em><strong>foo</strong></em>
bar**baz* -> ** is both an opening and closing delimiter.
Their sum is 3 so they can't be matched
The end result is: <em><strong>foo</strong></em>bar**baz*
*)
if (n1 + n2) mod 3 = 0 && n1 mod 3 != 0 && n2 mod 3 != 0 then false
else true
let rec parse_emph = function
| (Emph (pre, _, q1, n1) as x1) :: xs when is_opener x1 ->
let rec loop acc = function
| (Emph (_, post, q2, n2) as x2) :: xs1 as xs
when is_closer x2 && q1 = q2 ->
(* At this point we have an openener followed by a closer. Both are of the same style (either * or _) *)
if (is_opener x2 || is_closer x1) && not (is_emph_match n1 n2)
then
(*
The second delimiter (the closer) is also an opener, and both delimiters don't match together,
according to the "mod 3" rule. In that case, we check if the next delimiter can match.
*foo**bar**baz* The second delimiter that's both an opener/closer ( ** before bar)
matches with the next delimiter ( ** after bar). They'll become
<strong>bar</strong>. The end result will be: <em>foo<strong>bar</strong>baz</em>
*foo**bar*baz* The second delimiter that's both an opener/closer ( ** before bar)
doesn't match with the next delimiter ( * after bar). **bar will be
considered as regular text. The end result will be: <em>foo**bar</em>baz*
*)
match find_next_emph xs1 with
| Some (_, _, _, n3) when is_emph_match n3 n2 ->
let xs' = parse_emph xs in
loop acc xs'
| _ -> loop (x2 :: acc) xs1
else
let xs =
if n1 >= 2 && n2 >= 2 then
if n2 > 2 then Emph (Other, post, q2, n2 - 2) :: xs1