-
-
Notifications
You must be signed in to change notification settings - Fork 16
/
html_parser.ml
2846 lines (2388 loc) · 91.7 KB
/
html_parser.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
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
(* This file is part of Markup.ml, released under the MIT license. See
LICENSE.md for details, or visit https://github.com/aantron/markup.ml. *)
open Common
open Token_tag
open Kstream
(* Namespaces for pattern matching. *)
type ns = [ `HTML | `MathML | `SVG | `Other of string ]
type qname = ns * string
module Ns :
sig
val to_string : ns -> string
end =
struct
let to_string = function
| `HTML -> html_ns
| `MathML -> mathml_ns
| `SVG -> svg_ns
| `Other s -> s
end
(* Specialization of List.mem at qname list, to avoid polymorphic
comparison. *)
let list_mem_qname ((ns, tag) : qname) l =
let rec loop = function
| [] -> false
| (ns', tag')::_ when ns' = ns && tag' = tag -> true
| _::rest -> loop rest
in
loop l
(* Elements. *)
type element =
{element_name : qname;
location : location;
is_html_integration_point : bool;
suppress : bool;
mutable buffering : bool;
mutable is_open : bool;
mutable attributes : (name * string) list;
mutable end_location : location;
mutable children : annotated_node list;
mutable parent : element}
and node =
| Element of element
| Text of string list
| PI of string * string
| Comment of string
and annotated_node = location * node
(* Element helpers. *)
module Element :
sig
val create :
?is_html_integration_point:bool ->
?suppress:bool ->
qname -> location ->
element
val dummy : element
val is_special : qname -> bool
val is_not_hidden : Token_tag.t -> bool
end =
struct
let rec dummy =
{element_name = `HTML, "dummy";
location = 1, 1;
is_html_integration_point = false;
suppress = true;
buffering = false;
is_open = false;
attributes = [];
end_location = 1, 1;
children = [];
parent = dummy}
let create
?(is_html_integration_point = false) ?(suppress = false) name location =
{element_name = name;
location;
is_html_integration_point;
suppress;
buffering = false;
is_open = true;
attributes = [];
end_location = 1, 1;
children = [];
parent = dummy}
let is_special name =
list_mem_qname name
[`HTML, "address"; `HTML, "applet"; `HTML, "area";
`HTML, "article"; `HTML, "aside"; `HTML, "base";
`HTML, "basefont"; `HTML, "bgsound"; `HTML, "blockquote";
`HTML, "body"; `HTML, "br"; `HTML, "button";
`HTML, "caption"; `HTML, "center"; `HTML, "col";
`HTML, "colgroup"; `HTML, "dd"; `HTML, "details";
`HTML, "dir"; `HTML, "div"; `HTML, "dl";
`HTML, "dt"; `HTML, "embed"; `HTML, "fieldset";
`HTML, "figcaption"; `HTML, "figure"; `HTML, "footer";
`HTML, "form"; `HTML, "frame"; `HTML, "frameset";
`HTML, "h1"; `HTML, "h2"; `HTML, "h3";
`HTML, "h4"; `HTML, "h5"; `HTML, "h6";
`HTML, "head"; `HTML, "header"; `HTML, "hgroup";
`HTML, "hr"; `HTML, "html"; `HTML, "iframe";
`HTML, "img"; `HTML, "input"; `HTML, "isindex";
`HTML, "li"; `HTML, "link"; `HTML, "listing";
`HTML, "main"; `HTML, "marquee"; `HTML, "meta";
`HTML, "nav"; `HTML, "noembed"; `HTML, "noframes";
`HTML, "noscript"; `HTML, "object"; `HTML, "ol";
`HTML, "p"; `HTML, "param"; `HTML, "plaintext";
`HTML, "pre"; `HTML, "script"; `HTML, "section";
`HTML, "select"; `HTML, "source"; `HTML, "style";
`HTML, "summary"; `HTML, "table"; `HTML, "tbody";
`HTML, "td"; `HTML, "template"; `HTML, "textarea";
`HTML, "tfoot"; `HTML, "th"; `HTML, "thead";
`HTML, "title"; `HTML, "tr"; `HTML, "track";
`HTML, "ul"; `HTML, "wbr"; `HTML, "xmp";
`MathML, "mi"; `MathML, "mo"; `MathML, "mn";
`MathML, "ms"; `MathML, "mtext"; `MathML, "annotation-xml";
`SVG, "foreignObject"; `SVG, "desc"; `SVG, "title"]
let is_not_hidden tag =
tag.Token_tag.attributes |> List.exists (fun (name, value) ->
name = "type" && value <> "hidden")
end
(* Context detection. *)
type simple_context = [ `Document | `Fragment of string ]
type context = [ `Document | `Fragment of qname ]
module Context :
sig
type t
val uninitialized : unit -> t
val initialize :
(location * Html_tokenizer.token) Kstream.t ->
[< simple_context ] option ->
t ->
unit cps
val the_context : t -> context
val element : t -> element option
val token : t -> string option
end =
struct
let detect tokens throw k =
let tokens, restore = checkpoint tokens in
let last_name = ref None in
let next_token k =
next_expected tokens throw (fun token ->
begin match token with
| _, `Start {name} -> last_name := Some name
| _ -> ()
end;
k token)
in
let k context = restore (); k (context, !last_name) in
let rec scan () =
next_token begin function
| _, `Doctype _ -> k `Document
| _, `Char c when not @@ is_whitespace c -> k (`Fragment "body")
| _, `Char _ -> scan ()
| _, `EOF -> k (`Fragment "body")
| _, `Start {name = "html"} -> k `Document
| _, `Start {name = "head" | "body" | "frameset"} ->
k (`Fragment "html")
| _, `Start {name =
"base" | "basefont" | "bgsound" | "link" | "meta" | "noframes" |
"style" | "template" | "title"} ->
k (`Fragment "head")
| _, `Start {name = "frame"} -> k (`Fragment "frameset")
| _, `Start {name = "li"} -> k (`Fragment "ul")
| _, `Start {name =
"caption" | "col" | "colgroup" | "tbody" | "tfoot" | "thead"} ->
k (`Fragment "table")
| _, `Start {name = "tr"} -> k (`Fragment "tbody")
| _, `Start {name = "td" | "th"} -> k (`Fragment "tr")
| _, `Start {name = "optgroup" | "option"} -> k (`Fragment "select")
| _, `Start {name =
"altglyph" | "altglyphdef" | "altglyphitem" | "animate" |
"animatecolor" | "animatemotion" | "animatetransform" | "circle" |
"clippath" | "color-profile" | "cursor" | "defs" | "desc" |
"ellipse" | "feblend" | "fecolormatrix" | "fecomponenttransfer" |
"fecomposite" | "fediffuselighting" | "fedisplacementmap" |
"fedistantlight" | "feflood" | "fefunca" | "fefuncb" | "fefuncg" |
"fefuncr" | "fegaussianblur" | "feimage" | "femerge" |
"femergenode" | "femorphology" | "feoffset" | "fepointlight" |
"fespecularlighting" | "fespotlight" | "fetile" | "feturbulence" |
"filter" | "font-face" | "font-face-format" | "font-face-name" |
"font-face-src" | "font-face-uri" | "foreignobject" | "g" |
"glyph" | "glyphref" | "hkern" | "image" | "line" |
"lineargradient" | "marker" | "mask" | "metadata" |
"missing-glyph" | "mpath" | "path" | "pattern" | "polygon" |
"polyline" | "radialgradient" | "rect" | "set" | "stop" | "switch" |
"symbol" | "text" | "textpath" | "tref" | "tspan" | "use"} ->
k (`Fragment "svg")
| _, `Start {name =
"maction" | "maligngroup" | "malignmark" | "menclose" | "merror" |
"mfenced" | "mfrac" | "mglyph" | "mi" | "mlabeledtr" | "mlongdiv" |
"mmultiscripts" | "mn" | "mo" | "mover" | "mpadded" | "mphantom" |
"mroot" | "mrow" | "ms" | "mscarries" | "mscarry" | "msgroup" |
"msline" | "mspace" | "msqrt" | "msrow" | "mstack" | "mstyle" |
"msub" | "msup" | "msubsup" | "mtable" | "mtd" | "mtext" | "mtr" |
"munder" | "munderover" | "semantics" | "annotation" |
"annotation-xml"} ->
k (`Fragment "math")
| _, `Start _ -> k (`Fragment "body")
| _, (`End _ | `Comment _) -> scan ()
end
in
scan ()
type t = (context * element option * string option) ref
let uninitialized () = ref (`Document, None, None)
let initialize tokens requested_context state throw k =
(fun k ->
match requested_context with
| Some (`Fragment element) ->
(* HTML element names are case-insensitive, even in foreign content.
Lowercase the element name given by the user before analysis by the
parser, to match this convention. [String.lowercase] is acceptable
here because the API assumes the string [element] is in UTF-8. *)
k (`Fragment (String.lowercase_ascii element), None)
| Some (`Document as c) -> k (c, None)
| None -> detect tokens throw k)
(fun (detected_context, deciding_token) ->
let context =
match detected_context with
| `Document -> `Document
| `Fragment "math" -> `Fragment (`MathML, "math")
| `Fragment "svg" -> `Fragment (`SVG, "svg")
| `Fragment name -> `Fragment (`HTML, name)
in
let context_element =
match context with
| `Document -> None
| `Fragment name ->
let is_html_integration_point =
match name with
| `SVG, ("foreignObject" | "desc" | "title") -> true
| _ -> false
in
Some (Element.create
~is_html_integration_point ~suppress:true name (1, 1))
in
state := context, context_element, deciding_token;
k ())
let the_context {contents = (c, _, _)} = c
let element {contents = (_, e, _)} = e
let token {contents = (_, _, t)} = t
end
(* Heplers for foreign content. *)
module Foreign :
sig
val is_mathml_text_integration_point : qname -> bool
val is_html_integration_point :
ns -> string -> (string * string) list -> bool
val adjust_mathml_attributes :
((string * string) * string) list -> ((string * string) * string) list
val adjust_svg_attributes :
((string * string) * string) list -> ((string * string) * string) list
val adjust_svg_tag_name : string -> string
end =
struct
let is_mathml_text_integration_point qname =
list_mem_qname qname
[`MathML, "mi"; `MathML, "mo"; `MathML, "mn"; `MathML, "ms";
`MathML, "mtext"]
let is_html_integration_point namespace tag_name attributes =
match namespace with
| `HTML | `Other _ -> false
| `MathML ->
tag_name = "annotation-xml" &&
attributes |> List.exists (function
| "encoding", "text/html" -> true
| "encoding", "application/xhtml+xml" -> true
| _ -> false)
| `SVG ->
list_mem_string tag_name ["foreignObject"; "desc"; "title"]
let adjust_mathml_attributes attributes =
attributes |> List.map (fun ((ns, name), value) ->
let name =
if ns = mathml_ns && name = "definitionurl" then "definitionURL"
else name
in
(ns, name), value)
let adjust_svg_attributes attributes =
attributes |> List.map (fun ((ns, name), value) ->
let name =
match name with
| "attributename" -> "attributeName"
| "attributetype" -> "attributeType"
| "basefrequency" -> "baseFrequency"
| "baseprofile" -> "baseProfile"
| "calcmode" -> "calcMode"
| "clippathunits" -> "clipPathUnits"
| "contentscripttype" -> "contentScriptType"
| "contentstyletype" -> "contentStyleType"
| "diffuseconstant" -> "diffuseConstant"
| "edgemode" -> "edgeMode"
| "externalresourcesrequired" -> "externalResourcesRequired"
| "filterres" -> "filterRes"
| "filterunits" -> "filterUnits"
| "glyphref" -> "glyphRef"
| "gradienttransform" -> "gradientTransform"
| "gradientunits" -> "gradientUnits"
| "kernelmatrix" -> "kernelMatrix"
| "kernelunitlength" -> "kernelUnitLength"
| "keypoints" -> "keyPoints"
| "keysplines" -> "keySplines"
| "keytimes" -> "keyTimes"
| "lengthadjust" -> "lengthAdjust"
| "limitingconeangle" -> "limitingConeAngle"
| "markerheight" -> "markerHeight"
| "markerunits" -> "markerUnits"
| "markerwidth" -> "markerWidth"
| "maskcontentunits" -> "maskContentUnits"
| "maskunits" -> "maskUnits"
| "numoctaves" -> "numOctaves"
| "pathlength" -> "pathLength"
| "patterncontentunits" -> "patternContentUnits"
| "patterntransform" -> "patternTransform"
| "patternunits" -> "patternUnits"
| "pointsatx" -> "pointsAtX"
| "pointsaty" -> "pointsAtY"
| "pointsatz" -> "pointsAtZ"
| "preservealpha" -> "preserveAlpha"
| "preserveaspectratio" -> "preserveAspectRatio"
| "primitiveunits" -> "primitiveUnits"
| "refx" -> "refX"
| "refy" -> "refY"
| "repeatcount" -> "repeatCount"
| "repeatdur" -> "repeatDur"
| "requiredextensions" -> "requiredExtensions"
| "requiredfeatures" -> "requiredFeatures"
| "specularconstant" -> "specularConstant"
| "specularexponent" -> "specularExponent"
| "spreadmethod" -> "spreadMethod"
| "startoffset" -> "startOffset"
| "stddeviation" -> "stdDeviation"
| "stitchtiles" -> "stitchTiles"
| "surfacescale" -> "surfaceScale"
| "systemlanguage" -> "systemLanguage"
| "tablevalues" -> "tableValues"
| "targetx" -> "targetX"
| "targety" -> "targetY"
| "textlength" -> "textLength"
| "viewbox" -> "viewBox"
| "viewtarget" -> "viewTarget"
| "xchannelselector" -> "xChannelSelector"
| "ychannelselector" -> "yChannelSelector"
| "zoomandpan" -> "zoomAndPan"
| _ -> name
in
(ns, name), value)
let adjust_svg_tag_name = function
| "altglyph" -> "altGlyph"
| "altglyphdef" -> "altGlyphDef"
| "altglyphitem" -> "altGlyphItem"
| "animatecolor" -> "animateColor"
| "animatemotion" -> "animateMotion"
| "animatetransform" -> "animateTransform"
| "clippath" -> "clipPath"
| "feblend" -> "feBlend"
| "fecolormatrix" -> "feColorMatrix"
| "fecomponenttransfer" -> "feComponentTransfer"
| "fecomposite" -> "feComposite"
| "feconvolvematrix" -> "feConvolveMatrix"
| "fediffuselighting" -> "feDiffuseLighting"
| "fedisplacementmap" -> "feDisplacementMap"
| "fedistantlight" -> "feDistantLight"
| "fedropshadow" -> "feDropShadow"
| "feflood" -> "feFlood"
| "fefunca" -> "feFuncA"
| "fefuncb" -> "feFuncB"
| "fefuncg" -> "feFuncG"
| "fefuncr" -> "feFuncR"
| "fegaussianblur" -> "feGaussianBlur"
| "feimage" -> "feImage"
| "femerge" -> "feMerge"
| "femergenode" -> "feMergeNode"
| "femorphology" -> "feMorphology"
| "feoffset" -> "feOffset"
| "fepointlight" -> "fePointLight"
| "fespecularlighting" -> "feSpecularLighting"
| "fespotlight" -> "feSpotLight"
| "fetile" -> "feTile"
| "feturbulence" -> "feTurbulence"
| "foreignobject" -> "foreignObject"
| "glyphref" -> "glyphRef"
| "lineargradient" -> "linearGradient"
| "radialgradient" -> "radialGradient"
| "textpath" -> "textPath"
| s -> s
end
(* Stack of open elements. *)
module Stack :
sig
type t = element list ref
val create : unit -> t
val current_element : t -> element option
val require_current_element : t -> element
val adjusted_current_element : Context.t -> t -> element option
val current_element_is : t -> string list -> bool
val current_element_is_foreign : Context.t -> t -> bool
val has : t -> string -> bool
val in_scope : t -> string -> bool
val in_button_scope : t -> string -> bool
val in_list_item_scope : t -> string -> bool
val in_table_scope : t -> string -> bool
val in_select_scope : t -> string -> bool
val one_in_scope : t -> string list -> bool
val one_in_table_scope : t -> string list -> bool
val target_in_scope : t -> element -> bool
val remove : t -> element -> unit
val replace : t -> old:element -> new_:element -> unit
val insert_below : t -> anchor:element -> new_:element -> unit
end =
struct
type t = element list ref
let create () = ref []
let current_element open_elements =
match !open_elements with
| [] -> None
| element::_ -> Some element
let require_current_element open_elements =
match current_element open_elements with
| None -> failwith "require_current_element: None"
| Some element -> element
let adjusted_current_element context open_elements =
match !open_elements, Context.element context with
| [_], Some element -> Some element
| [], _ -> None
| element::_, _ -> Some element
let current_element_is open_elements names =
match !open_elements with
| {element_name = `HTML, name}::_ -> list_mem_string name names
| _ -> false
let current_element_is_foreign context open_elements =
match adjusted_current_element context open_elements with
| Some {element_name = ns, _} when ns <> `HTML -> true
| _ -> false
let has open_elements name =
List.exists
(fun {element_name = ns, name'} ->
ns = `HTML && name' = name) !open_elements
let in_scope_general scope_delimiters open_elements name' =
let rec scan = function
| [] -> false
| {element_name = ns, name'' as name}::more ->
if ns = `HTML && name'' = name' then true
else
if list_mem_qname name scope_delimiters then false
else scan more
in
scan !open_elements
let scope_delimiters =
[`HTML, "applet"; `HTML, "caption"; `HTML, "html";
`HTML, "table"; `HTML, "td"; `HTML, "th";
`HTML, "marquee"; `HTML, "object"; `HTML, "template";
`MathML, "mi"; `MathML, "mo"; `MathML, "mn";
`MathML, "ms"; `MathML, "mtext"; `MathML, "annotation-xml";
`SVG, "foreignObject"; `SVG, "desc"; `SVG, "title"]
let in_scope = in_scope_general scope_delimiters
let in_button_scope = in_scope_general ((`HTML, "button")::scope_delimiters)
let in_list_item_scope =
in_scope_general ((`HTML, "ol")::(`HTML, "ul")::scope_delimiters)
let in_table_scope =
in_scope_general [`HTML, "html"; `HTML, "table"; `HTML, "template"]
let in_select_scope open_elements name =
let rec scan = function
| [] -> false
| {element_name = ns, name'}::more ->
if ns <> `HTML then false
else
if name' = name then true
else
if name' = "optgroup" || name' = "option" then scan more
else false
in
scan !open_elements
let one_in_scope open_elements names =
let rec scan = function
| [] -> false
| {element_name = ns, name' as name}::more ->
if ns = `HTML && list_mem_string name' names then true
else
if list_mem_qname name scope_delimiters then false
else scan more
in
scan !open_elements
let one_in_table_scope open_elements names =
let rec scan = function
| [] -> false
| {element_name = ns, name' as name}::more ->
if ns = `HTML && list_mem_string name' names then true
else
if list_mem_qname name
[`HTML, "html"; `HTML, "table"; `HTML, "template"] then
false
else scan more
in
scan !open_elements
let target_in_scope open_elements node =
let rec scan = function
| [] -> false
| e::more ->
if e == node then true
else
if list_mem_qname node.element_name scope_delimiters then false
else scan more
in
scan !open_elements
let remove open_elements element =
open_elements := List.filter ((!=) element) !open_elements;
element.is_open <- false
let replace open_elements ~old ~new_ =
open_elements :=
List.map (fun e ->
if e == old then (e.is_open <- false; new_) else e) !open_elements
let insert_below open_elements ~anchor ~new_ =
let rec insert prefix = function
| [] -> List.rev prefix
| e::more when e == anchor -> (List.rev prefix) @ (new_::e::more)
| e::more -> insert (e::prefix) more
in
open_elements := insert [] !open_elements
end
(* List of active formatting elements. *)
module Active :
sig
type entry =
| Marker
| Element_ of element * location * Token_tag.t
type t = entry list ref
val create : unit -> t
val add_marker : t -> unit
val clear_until_marker : t -> unit
val has : t -> element -> bool
val remove : t -> element -> unit
val replace : t -> old:element -> new_:element -> unit
val insert_after : t -> anchor:element -> new_:element -> unit
val has_before_marker : t -> string -> element option
end =
struct
type entry =
| Marker
| Element_ of element * location * Token_tag.t
type t = entry list ref
let create () = ref []
let add_marker active_formatting_elements =
active_formatting_elements := Marker::!active_formatting_elements
let clear_until_marker active_formatting_elements =
let rec iterate = function
| Marker::rest -> rest
| (Element_ _)::rest -> iterate rest
| [] -> []
in
active_formatting_elements := iterate !active_formatting_elements
let has active_formatting_elements element =
!active_formatting_elements |> List.exists (function
| Element_ (e, _, _) when e == element -> true
| _ -> false)
let remove active_formatting_elements element =
active_formatting_elements :=
!active_formatting_elements |> List.filter (function
| Element_ (e, _, _) when e == element -> false
| _ -> true)
let replace active_formatting_elements ~old ~new_ =
active_formatting_elements :=
!active_formatting_elements |> List.map (function
| Element_ (e, l, t) when e == old -> Element_ (new_, l, t)
| e -> e)
let insert_after active_formatting_elements ~anchor ~new_ =
let rec insert prefix = function
| [] -> List.rev prefix
| (Element_ (e, l, t) as v)::more when e == anchor ->
let new_entry = Element_ (new_, l, t) in
(List.rev prefix) @ (v::new_entry::more)
| v::more -> insert (v::prefix) more
in
active_formatting_elements := insert [] !active_formatting_elements
let has_before_marker active_formatting_elements name =
let rec scan = function
| [] | Marker::_ -> None
| Element_ (n, _, _)::_ when n.element_name = (`HTML, name) -> Some n
| _::more -> scan more
in
scan !active_formatting_elements
end
type mode = unit -> unit
(* Stack of template insertion modes. *)
module Template :
sig
type t = mode list ref
val create : unit -> t
val push : t -> mode -> unit
val pop : t -> unit
end =
struct
type t = (unit -> unit) list ref
let create () = ref []
let push template_insertion_modes mode =
template_insertion_modes := mode::!template_insertion_modes
let pop template_insertion_modes =
match !template_insertion_modes with
| [] -> ()
| _::rest -> template_insertion_modes := rest
end
(* Subtree buffers. HTML specifies the "adoption agency algorithm" for
recovering from certain kinds of errors. This algorithm is (apparently)
incompatible with streaming parsers that do not maintain a DOM - such as
Markup.ml. So, when the Markup.ml parser encounters a situation in which it
may be necessary to later run the adoption agency algorithm, it buffers its
signal output. Instead of being emitted, the signals are used to construct a
DOM subtree. If the algorithm is run, it is run on this subtree. Whenever the
parser can "prove" that the subtree can no longer be involved in the adoption
agency algorithm, it serializes the subtree into the signal stream. In
practice, this means that buffering begins when a formatting element is
encountered, and ends when the parent of the formatting element is popped off
the open element stack. *)
module Subtree :
sig
type t
val create : Stack.t -> t
val accumulate : t -> location -> signal -> bool
val enable : t -> unit
val disable : t -> (location * signal) list
val adoption_agency_algorithm :
t -> Active.t -> location -> string -> bool * (location * Error.t) list
end =
struct
type t =
{open_elements : Stack.t;
mutable enabled : bool;
mutable position : element}
let create open_elements =
{open_elements;
enabled = false;
position = Element.dummy}
let accumulate subtree_buffer l s =
if not subtree_buffer.enabled then true
else begin
begin match s with
| `Start_element (_, attributes) ->
let parent = subtree_buffer.position in
let child =
Stack.require_current_element subtree_buffer.open_elements in
child.attributes <- attributes;
child.parent <- parent;
parent.children <- (l, Element child)::parent.children;
subtree_buffer.position <- child
| `End_element ->
subtree_buffer.position.end_location <- l;
subtree_buffer.position <-
Stack.require_current_element subtree_buffer.open_elements
| `Text ss ->
subtree_buffer.position.children <-
(l, Text ss)::subtree_buffer.position.children
| `PI (t, s) ->
subtree_buffer.position.children <-
(l, PI (t, s))::subtree_buffer.position.children
| `Comment s ->
subtree_buffer.position.children <-
(l, Comment s)::subtree_buffer.position.children
| `Xml _ | `Doctype _ -> ()
end;
false
end
let enable subtree_buffer =
if subtree_buffer.enabled then ()
else
match Stack.current_element subtree_buffer.open_elements with
| None -> ()
| Some element ->
element.buffering <- true;
subtree_buffer.position <- element;
subtree_buffer.enabled <- true
let disable subtree_buffer =
let rec traverse acc = function
| l, Element {element_name; attributes; end_location; children} ->
let name = Ns.to_string (fst element_name), snd element_name in
let start_signal = l, `Start_element (name, attributes) in
let end_signal = end_location, `End_element in
start_signal::(List.fold_left traverse (end_signal::acc) children)
| l, Text ss ->
begin match acc with
| (_, `Text ss')::rest -> (l, `Text (ss @ ss'))::rest
| _ -> (l, `Text ss)::acc
end
| l, PI (t, s) -> (l, `PI (t, s))::acc
| l, Comment s -> (l, `Comment s)::acc
in
let result =
List.fold_left traverse []
(Stack.require_current_element subtree_buffer.open_elements).children
in
subtree_buffer.enabled <- false;
result
(* Part of 8.2.5.4.7. *)
let adoption_agency_algorithm
subtree_buffer active_formatting_elements l subject =
let open_elements = subtree_buffer.open_elements in
let above_removed_nodes = ref [] in
let rec above_in_stack node = function
| e::e'::_ when e == node -> e'
| _::more -> above_in_stack node more
| [] -> failwith "above_in_stack: not found"
in
let above_node node =
if node.is_open then above_in_stack node !open_elements
else
try List.find (fun (e, _) -> e == node) !above_removed_nodes |> snd
with Not_found -> failwith "above_node: not found"
in
let remove_node node =
above_removed_nodes :=
(node, above_in_stack node !open_elements)::!above_removed_nodes;
Stack.remove open_elements node
in
let reparent node new_parent =
let old_parent = node.parent in
let entry, filtered_children =
let rec remove prefix = function
| (_, Element e as entry)::rest when e == node ->
entry, (List.rev prefix) @ rest
| e::rest -> remove (e::prefix) rest
| [] -> (node.location, Element node), old_parent.children
in
remove [] old_parent.children
in
old_parent.children <- filtered_children;
new_parent.children <- entry::new_parent.children;
node.parent <- new_parent
in
let inner_loop formatting_element furthest_block =
let rec repeat inner_loop_counter node last_node bookmark =
let node = above_node node in
if node == formatting_element then last_node, bookmark
else begin
if inner_loop_counter > 3 then
Active.remove active_formatting_elements node;
if not @@ Active.has active_formatting_elements node then begin
remove_node node;
repeat (inner_loop_counter + 1) node last_node bookmark
end
else begin
let new_node =
{node with is_open = true; children = []; parent = Element.dummy}
in
node.end_location <- l;
Stack.replace open_elements ~old:node ~new_:new_node;
Active.replace active_formatting_elements ~old:node ~new_:new_node;
reparent last_node new_node;
repeat (inner_loop_counter + 1) new_node new_node
(if last_node == furthest_block then Some new_node else bookmark)
end
end
in
repeat 1 furthest_block furthest_block None
in
let find_formatting_element () =
let rec scan = function
| [] -> None
| Active.Marker::_ -> None
| (Active.Element_ ({element_name = `HTML, n} as e, _, _))::_
when n = subject -> Some e
| _::rest -> scan rest
in
scan !active_formatting_elements
in
let find_furthest_block formatting_element =
let rec scan furthest = function
| [] -> furthest
| e::_ when e == formatting_element -> furthest
| e::more when Element.is_special e.element_name -> scan (Some e) more
| _::more -> scan furthest more
in
scan None !open_elements
in
let pop_to_formatting_element formatting_element =
let rec pop () =
match !open_elements with
| [] -> ()
| e::more ->
open_elements := more;
e.is_open <- false;
e.end_location <- l;
if e != formatting_element then pop ()
in
pop ();
subtree_buffer.position <- Stack.require_current_element open_elements
in
let rec outer_loop outer_loop_counter errors =
let outer_loop_counter = outer_loop_counter + 1 in
if outer_loop_counter >= 8 then true, List.rev errors
else begin
match find_formatting_element () with
| None -> false, List.rev errors
| Some formatting_element ->
if not formatting_element.is_open then begin
Active.remove active_formatting_elements formatting_element;
true, List.rev ((l, `Unmatched_end_tag subject)::errors)
end
else begin
if not @@ Stack.target_in_scope open_elements
formatting_element then begin
true, List.rev ((l, `Unmatched_end_tag subject)::errors)
end
else begin
let errors =
if Stack.require_current_element open_elements ==
formatting_element then
errors
else (l, `Unmatched_end_tag subject)::errors
in
match find_furthest_block formatting_element with
| None ->
pop_to_formatting_element formatting_element;
Active.remove active_formatting_elements formatting_element;
true, List.rev errors
| Some furthest_block ->
formatting_element.end_location <- l;
let common_ancestor =
above_in_stack formatting_element !open_elements in
let last_node, bookmark =
inner_loop formatting_element furthest_block in
reparent last_node common_ancestor;
let new_node =
{formatting_element with
is_open = true; children = []; parent = Element.dummy}
in
new_node.children <- furthest_block.children;
furthest_block.children <- [];
new_node.children |> List.iter (function
| _, Element child -> child.parent <- new_node
| _ -> ());
reparent new_node furthest_block;
begin match bookmark with
| None ->
Active.replace active_formatting_elements
~old:formatting_element ~new_:new_node
| Some node ->
Active.remove active_formatting_elements formatting_element;
Active.insert_after
active_formatting_elements ~anchor:node ~new_:new_node
end;
Stack.remove open_elements formatting_element;
Stack.insert_below
open_elements ~anchor:furthest_block ~new_:new_node;
outer_loop outer_loop_counter errors
end
end
end
in