-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathHTMLParser.java
More file actions
1357 lines (1221 loc) · 60.5 KB
/
HTMLParser.java
File metadata and controls
1357 lines (1221 loc) · 60.5 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
package org.perlonjava.runtime.perlmodule;
import org.perlonjava.runtime.runtimetypes.*;
import org.perlonjava.runtime.mro.InheritanceResolver;
import static org.perlonjava.runtime.runtimetypes.RuntimeScalarCache.*;
import java.nio.charset.StandardCharsets;
/**
* Java XS implementation of HTML::Parser and HTML::Entities.
* <p>
* Mirrors the original Parser.xs which contains both PACKAGE = HTML::Parser
* and PACKAGE = HTML::Entities in a single file, loaded via
* XSLoader::load('HTML::Parser').
* <p>
* Phase 1: Full HTML::Entities support (decode_entities, _decode_entities)
* plus HTML::Parser stubs for construction and configuration.
*/
public class HTMLParser extends PerlModuleBase {
public static final String XS_VERSION = "3.83";
public HTMLParser() {
super("HTML::Parser", false);
}
public static void initialize() {
HTMLParser module = new HTMLParser();
try {
// ============================================================
// PACKAGE = HTML::Parser
// ============================================================
module.registerMethod("_alloc_pstate", null);
module.registerMethod("parse", null);
module.registerMethod("eof", "parserEof", null);
// 13 boolean attribute accessors (aliased in XS via strict_comment)
module.registerMethod("strict_comment", null);
module.registerMethod("strict_names", null);
module.registerMethod("xml_mode", null);
module.registerMethod("unbroken_text", null);
module.registerMethod("marked_sections", null);
module.registerMethod("attr_encoded", null);
module.registerMethod("case_sensitive", null);
module.registerMethod("strict_end", null);
module.registerMethod("closing_plaintext", null);
module.registerMethod("utf8_mode", null);
module.registerMethod("empty_element_tags", null);
module.registerMethod("xml_pic", null);
module.registerMethod("backquote", null);
module.registerMethod("boolean_attribute_value", null);
module.registerMethod("handler", null);
module.registerMethod("report_tags", "tagListAccessor", null);
module.registerMethod("ignore_tags", "tagListAccessor", null);
module.registerMethod("ignore_elements", "tagListAccessor", null);
} catch (NoSuchMethodException e) {
System.err.println("Warning: Missing HTMLParser method: " + e.getMessage());
}
// ============================================================
// PACKAGE = HTML::Entities
// Cross-package registration: these functions go into the
// HTML::Entities:: namespace but are loaded by HTML::Parser's XS.
// ============================================================
try {
java.lang.invoke.MethodHandle mh;
RuntimeCode code;
mh = RuntimeCode.lookup.findStatic(HTMLParser.class, "decode_entities", RuntimeCode.methodType);
code = new RuntimeCode(mh, null, null);
code.isStatic = true;
GlobalVariable.getGlobalCodeRef("HTML::Entities::decode_entities").set(new RuntimeScalar(code));
mh = RuntimeCode.lookup.findStatic(HTMLParser.class, "_decode_entities", RuntimeCode.methodType);
code = new RuntimeCode(mh, null, null);
code.isStatic = true;
GlobalVariable.getGlobalCodeRef("HTML::Entities::_decode_entities").set(new RuntimeScalar(code));
mh = RuntimeCode.lookup.findStatic(HTMLParser.class, "UNICODE_SUPPORT", RuntimeCode.methodType);
code = new RuntimeCode(mh, null, null);
code.isStatic = true;
GlobalVariable.getGlobalCodeRef("HTML::Entities::UNICODE_SUPPORT").set(new RuntimeScalar(code));
mh = RuntimeCode.lookup.findStatic(HTMLParser.class, "_probably_utf8_chunk", RuntimeCode.methodType);
code = new RuntimeCode(mh, null, null);
code.isStatic = true;
GlobalVariable.getGlobalCodeRef("HTML::Entities::_probably_utf8_chunk").set(new RuntimeScalar(code));
} catch (NoSuchMethodException | IllegalAccessException e) {
System.err.println("Warning: Missing HTMLEntities method: " + e.getMessage());
}
}
// ================================================================
// HTML::Parser methods
// ================================================================
/**
* _alloc_pstate($self)
* Allocates parser state and stores it in $self->{_hparser_xs_state}.
* We use a RuntimeHash to hold the parser configuration.
*/
public static RuntimeList _alloc_pstate(RuntimeArray args, int ctx) {
RuntimeScalar self = args.get(0);
RuntimeHash selfHash = self.hashDeref();
// Create parser state as a hash holding boolean flags, handlers, etc.
RuntimeHash pstate = new RuntimeHash();
// Initialize boolean flags to false
String[] boolFlags = {
"strict_comment", "strict_names", "xml_mode", "unbroken_text",
"marked_sections", "attr_encoded", "case_sensitive", "strict_end",
"closing_plaintext", "utf8_mode", "empty_element_tags", "xml_pic",
"backquote"
};
for (String flag : boolFlags) {
pstate.put(flag, scalarFalse);
}
// Initialize handler slots
String[] events = {
"declaration", "comment", "start", "end", "text",
"process", "start_document", "end_document", "default"
};
RuntimeHash handlers = new RuntimeHash();
for (String event : events) {
handlers.put(event + "_cb", scalarUndef);
handlers.put(event + "_argspec", scalarUndef);
}
pstate.put("_handlers", handlers.createReference());
// State tracking
pstate.put("_parsing", scalarFalse);
pstate.put("_eof", scalarFalse);
pstate.put("_buf", new RuntimeScalar(""));
pstate.put("_bool_attr_val", scalarUndef);
pstate.put("_in_cdata", scalarFalse);
// Store in self
selfHash.put("_hparser_xs_state", pstate.createReference());
return new RuntimeList();
}
/**
* parse($self, $chunk)
* Feeds HTML to the parser. Phase 1: basic event-driven parsing.
*/
public static RuntimeList parse(RuntimeArray args, int ctx) {
RuntimeScalar self = args.get(0);
RuntimeHash selfHash = self.hashDeref();
RuntimeHash pstate = getPstate(selfHash);
if (pstate.get("_parsing").getBoolean()) {
throw new RuntimeException("Parse loop not allowed");
}
pstate.put("_parsing", scalarTrue);
try {
if (args.size() > 1) {
RuntimeScalar chunk = args.get(1);
if (chunk.getDefinedBoolean()) {
String chunkStr = chunk.toString();
// When utf8_mode is set and the input is a BYTE_STRING, try to
// decode UTF-8 byte sequences to characters. If decoding fails
// (e.g., the bytes are Latin-1, not UTF-8), keep the original
// string unchanged - each byte maps to the corresponding Unicode
// code point, which preserves Latin-1 characters like ø (0xF8).
// This matches Perl 5's XS parser behavior where character values
// are preserved regardless of utf8_mode.
if (pstate.get("utf8_mode").getBoolean()
&& chunk.type == RuntimeScalarType.BYTE_STRING) {
byte[] bytes = chunkStr.getBytes(StandardCharsets.ISO_8859_1);
java.nio.charset.CharsetDecoder decoder = StandardCharsets.UTF_8.newDecoder()
.onMalformedInput(java.nio.charset.CodingErrorAction.REPORT)
.onUnmappableCharacter(java.nio.charset.CodingErrorAction.REPORT);
try {
chunkStr = decoder.decode(java.nio.ByteBuffer.wrap(bytes)).toString();
} catch (java.nio.charset.CharacterCodingException e) {
// Not valid UTF-8; keep original string (Latin-1 identity mapping)
}
}
String html = pstate.get("_buf").toString() + chunkStr;
pstate.put("_buf", new RuntimeScalar(""));
parseHtml(self, selfHash, pstate, html);
}
}
} finally {
pstate.put("_parsing", scalarFalse);
}
if (pstate.get("_eof").getBoolean()) {
pstate.put("_eof", scalarFalse);
return scalarUndef.getList();
}
return self.getList();
}
/**
* eof($self)
* Signals end-of-document, flushes buffered text.
*/
public static RuntimeList parserEof(RuntimeArray args, int ctx) {
RuntimeScalar self = args.get(0);
RuntimeHash selfHash = self.hashDeref();
RuntimeHash pstate = getPstate(selfHash);
if (pstate.get("_parsing").getBoolean()) {
pstate.put("_eof", scalarTrue);
} else {
pstate.put("_parsing", scalarTrue);
try {
// Flush any remaining buffered text
String remaining = pstate.get("_buf").toString();
if (!remaining.isEmpty()) {
pstate.put("_buf", new RuntimeScalar(""));
parseHtml(self, selfHash, pstate, remaining);
}
// Fire end_document event
fireEvent(self, selfHash, pstate, "end_document");
} finally {
pstate.put("_parsing", scalarFalse);
}
}
return self.getList();
}
// 13 boolean attribute getter/setters - each delegates to booleanAccessorHelper
public static RuntimeList strict_comment(RuntimeArray args, int ctx) { return booleanAccessorHelper(args, "strict_comment"); }
public static RuntimeList strict_names(RuntimeArray args, int ctx) { return booleanAccessorHelper(args, "strict_names"); }
public static RuntimeList xml_mode(RuntimeArray args, int ctx) { return booleanAccessorHelper(args, "xml_mode"); }
public static RuntimeList unbroken_text(RuntimeArray args, int ctx) { return booleanAccessorHelper(args, "unbroken_text"); }
public static RuntimeList marked_sections(RuntimeArray args, int ctx) { return booleanAccessorHelper(args, "marked_sections"); }
public static RuntimeList attr_encoded(RuntimeArray args, int ctx) { return booleanAccessorHelper(args, "attr_encoded"); }
public static RuntimeList case_sensitive(RuntimeArray args, int ctx) { return booleanAccessorHelper(args, "case_sensitive"); }
public static RuntimeList strict_end(RuntimeArray args, int ctx) { return booleanAccessorHelper(args, "strict_end"); }
public static RuntimeList closing_plaintext(RuntimeArray args, int ctx) { return booleanAccessorHelper(args, "closing_plaintext"); }
public static RuntimeList utf8_mode(RuntimeArray args, int ctx) { return booleanAccessorHelper(args, "utf8_mode"); }
public static RuntimeList empty_element_tags(RuntimeArray args, int ctx) { return booleanAccessorHelper(args, "empty_element_tags"); }
public static RuntimeList xml_pic(RuntimeArray args, int ctx) { return booleanAccessorHelper(args, "xml_pic"); }
public static RuntimeList backquote(RuntimeArray args, int ctx) { return booleanAccessorHelper(args, "backquote"); }
private static RuntimeList booleanAccessorHelper(RuntimeArray args, String attrName) {
RuntimeScalar self = args.get(0);
RuntimeHash selfHash = self.hashDeref();
RuntimeHash pstate = getPstate(selfHash);
RuntimeScalar old = pstate.get(attrName);
RuntimeScalar retval = (old != null && old.getBoolean()) ? scalarTrue : scalarFalse;
if (args.size() > 1) {
pstate.put(attrName, args.get(1).getBoolean() ? scalarTrue : scalarFalse);
}
return retval.getList();
}
/**
* boolean_attribute_value($pstate, [$new_value])
*/
public static RuntimeList boolean_attribute_value(RuntimeArray args, int ctx) {
RuntimeScalar self = args.get(0);
RuntimeHash selfHash = self.hashDeref();
RuntimeHash pstate = getPstate(selfHash);
RuntimeScalar old = pstate.get("_bool_attr_val");
if (args.size() > 1) {
pstate.put("_bool_attr_val", args.get(1));
}
return old.getList();
}
/**
* handler($pstate, $eventname, [$callback, $argspec])
*/
public static RuntimeList handler(RuntimeArray args, int ctx) {
RuntimeScalar self = args.get(0);
RuntimeHash selfHash = self.hashDeref();
RuntimeHash pstate = getPstate(selfHash);
if (args.size() < 2) {
throw new RuntimeException("Usage: $p->handler(event => cb, argspec)");
}
String eventName = args.get(1).toString();
RuntimeHash handlers = pstate.get("_handlers").hashDeref();
// Return old handler
RuntimeScalar oldCb = handlers.get(eventName + "_cb");
// Update handler if new callback provided
if (args.size() > 2) {
RuntimeScalar newCb = args.get(2);
handlers.put(eventName + "_cb", newCb);
}
if (args.size() > 3) {
RuntimeScalar argspec = args.get(3);
handlers.put(eventName + "_argspec", argspec);
}
return (oldCb != null) ? oldCb.getList() : scalarUndef.getList();
}
/**
* Tag list accessor (report_tags, ignore_tags, ignore_elements).
*/
public static RuntimeList tagListAccessor(RuntimeArray args, int ctx) {
// Phase 1 stub - tag filtering not yet implemented
return new RuntimeList();
}
// ================================================================
// HTML::Entities methods (PACKAGE = HTML::Entities in Parser.xs)
// ================================================================
/**
* decode_entities(...)
* <p>
* In void context: decodes entities in-place in the arguments.
* In scalar context with multiple args: only processes first argument, returns copy.
* In list context: returns decoded copies of all arguments.
*/
public static RuntimeList decode_entities(RuntimeArray args, int ctx) {
RuntimeHash entity2char = GlobalVariable.getGlobalHash("HTML::Entities::entity2char");
int items = args.size();
if (ctx == RuntimeContextType.SCALAR && items > 1) {
items = 1;
}
if (ctx == RuntimeContextType.VOID) {
// Void context: modify in-place
for (int i = 0; i < items; i++) {
RuntimeScalar sv = args.get(i);
String decoded = decodeEntitiesString(sv.toString(), entity2char, false);
sv.set(decoded);
}
return new RuntimeList();
} else {
// Scalar/list context: return decoded copies
RuntimeList result = new RuntimeList();
for (int i = 0; i < items; i++) {
String decoded = decodeEntitiesString(args.get(i).toString(), entity2char, false);
result.add(new RuntimeScalar(decoded));
}
return result;
}
}
/**
* _decode_entities($string, \%entity2char, $expand_prefix)
* In-place decode with explicit entity hash and optional prefix expansion.
*/
public static RuntimeList _decode_entities(RuntimeArray args, int ctx) {
if (args.size() < 2) {
throw new RuntimeException("Usage: _decode_entities(string, entity2char_hash, [expand_prefix])");
}
RuntimeScalar stringSv = args.get(0);
RuntimeScalar entitiesSv = args.get(1);
boolean expandPrefix = args.size() > 2 && args.get(2).getBoolean();
RuntimeHash entityHash = null;
if (entitiesSv.getDefinedBoolean()) {
if (RuntimeScalarType.isReference(entitiesSv)) {
try {
entityHash = entitiesSv.hashDeref();
} catch (Exception e) {
// Not a hash reference
}
}
if (entityHash == null) {
throw new RuntimeException("2nd argument must be hash reference");
}
}
String decoded = decodeEntitiesString(stringSv.toString(), entityHash, expandPrefix);
stringSv.set(decoded);
return new RuntimeList();
}
/**
* UNICODE_SUPPORT() - always returns 1
*/
public static RuntimeList UNICODE_SUPPORT(RuntimeArray args, int ctx) {
return new RuntimeScalar(1).getList();
}
/**
* _probably_utf8_chunk($string) - checks if string looks like valid UTF-8
*/
public static RuntimeList _probably_utf8_chunk(RuntimeArray args, int ctx) {
if (args.isEmpty()) {
return scalarFalse.getList();
}
String s = args.get(0).toString();
for (int i = 0; i < s.length(); i++) {
if (s.charAt(i) > 0x7F) {
return scalarTrue.getList();
}
}
return scalarFalse.getList();
}
// ================================================================
// Internal helpers
// ================================================================
/**
* Retrieve the parser state hash from $self->{_hparser_xs_state}.
*/
private static RuntimeHash getPstate(RuntimeHash selfHash) {
RuntimeScalar ref = selfHash.get("_hparser_xs_state");
if (ref == null || !ref.getDefinedBoolean()) {
throw new RuntimeException("HTML::Parser not initialized (missing _hparser_xs_state)");
}
return ref.hashDeref();
}
/**
* Fire a parser event by calling the registered handler.
* Supports three callback types:
* - String: method name to call on $self
* - Code ref: subroutine reference to call directly
* - Array ref: accumulator for PullParser/TokeParser (push event data)
*
* @param self the original blessed parser object (for method dispatch)
* @param selfHash the dereferenced hash of the parser
* @param pstate the parser state hash
* @param eventName the event type (start, end, text, etc.)
* @param eventArgs the event-specific arguments
*/
private static void fireEvent(RuntimeScalar self, RuntimeHash selfHash, RuntimeHash pstate, String eventName, RuntimeScalar... eventArgs) {
RuntimeHash handlers = pstate.get("_handlers").hashDeref();
RuntimeScalar cb = handlers.get(eventName + "_cb");
if (cb == null || !cb.getDefinedBoolean()) {
return;
}
// Parse argspec to determine what arguments to pass
RuntimeScalar argspecSv = handlers.get(eventName + "_argspec");
String argspec = (argspecSv != null && argspecSv.getDefinedBoolean()) ?
argspecSv.toString() : "";
if (cb.type == RuntimeScalarType.ARRAYREFERENCE) {
// Array ref accumulator - used by PullParser/TokeParser
// Build event data per argspec and push as array ref onto accumulator
RuntimeArray accum = (RuntimeArray) cb.value;
RuntimeArray eventData = buildEventDataFromArgspec(argspec, eventName, eventArgs, self, false, pstate);
RuntimeArray.push(accum, eventData.createReference());
} else if (cb.type == RuntimeScalarType.STRING || cb.type == RuntimeScalarType.BYTE_STRING) {
// Method name - call as $self->method(...)
String methodName = cb.toString();
RuntimeArray callArgs = new RuntimeArray();
RuntimeArray.push(callArgs, self);
// Build args from argspec if available, otherwise pass raw eventArgs
// skipSelf=true: "self" in argspec specifies the invocant for method dispatch
// but should NOT be duplicated in the method arguments
if (!argspec.isEmpty()) {
RuntimeArray eventData = buildEventDataFromArgspec(argspec, eventName, eventArgs, self, true, pstate);
for (int idx = 0; idx < eventData.size(); idx++) {
RuntimeArray.push(callArgs, eventData.get(idx));
}
} else {
for (RuntimeScalar arg : eventArgs) {
RuntimeArray.push(callArgs, arg);
}
}
// Look up method in the object's class hierarchy using the blessed class
int blessId = RuntimeScalarType.blessedId(self);
String className = (blessId != 0) ?
NameNormalizer.getBlessStr(blessId) : "HTML::Parser";
RuntimeScalar method = InheritanceResolver.findMethodInHierarchy(
methodName, className, null, 0);
if (method != null) {
RuntimeCode.apply(method, callArgs, RuntimeContextType.VOID);
}
} else if (cb.type == RuntimeScalarType.REFERENCE || cb.type == RuntimeScalarType.CODE) {
// Code reference - call directly
RuntimeArray callArgs = new RuntimeArray();
if (!argspec.isEmpty()) {
RuntimeArray eventData = buildEventDataFromArgspec(argspec, eventName, eventArgs, self, false, pstate);
for (int idx = 0; idx < eventData.size(); idx++) {
RuntimeArray.push(callArgs, eventData.get(idx));
}
} else {
for (RuntimeScalar arg : eventArgs) {
RuntimeArray.push(callArgs, arg);
}
}
RuntimeCode.apply(cb, callArgs, RuntimeContextType.VOID);
}
}
/**
* Build event data array from an argspec string.
* Argspec is a comma-separated list of tokens that specify what data to include.
*
* Supported argspec tokens:
* - Quoted literals: 'S', 'E', 'T', 'C', 'D', 'PI' etc.
* - tagname: the tag name
* - attr: hash ref of attributes (for start events)
* - attrseq: array ref of attribute names in order (for start events)
* - text: original HTML text
* - dtext: decoded text (entities decoded)
* - is_cdata: boolean - is this CDATA?
* - self: the parser object
* - event: the event name
* - tag: same as tagname (alias)
* - offset: byte offset in document
* - length: length of original text
* - offset_end: end offset
* - line: line number
* - column: column number
* - token0: first token (for PI)
* - skipped_text: text skipped by handler
*
* For start events, eventArgs = [tagname, attr_ref, attrseq_ref, origtext]
* For end events, eventArgs = [tagname, origtext]
* For text events, eventArgs = [text]
* For comment events, eventArgs = [comment]
* For declaration events, eventArgs = [decl_text]
* For process events, eventArgs = [pi_text]
*/
private static RuntimeArray buildEventDataFromArgspec(String argspec, String eventName, RuntimeScalar[] eventArgs, RuntimeScalar self, boolean skipSelf, RuntimeHash pstate) {
RuntimeArray result = new RuntimeArray();
if (argspec.isEmpty()) {
// No argspec - pass raw event args
for (RuntimeScalar arg : eventArgs) {
RuntimeArray.push(result, arg);
}
return result;
}
// Parse comma-separated argspec tokens
String[] tokens = argspec.split(",");
for (String rawToken : tokens) {
String token = rawToken.trim();
if (token.isEmpty()) continue;
// Check for quoted literal: 'X' or "X"
if ((token.startsWith("'") && token.endsWith("'")) ||
(token.startsWith("\"") && token.endsWith("\""))) {
String literal = token.substring(1, token.length() - 1);
RuntimeArray.push(result, new RuntimeScalar(literal));
continue;
}
switch (token) {
case "tagname":
case "tag":
// First arg for start/end events is tagname
if (eventArgs.length > 0) {
RuntimeArray.push(result, eventArgs[0]);
} else {
RuntimeArray.push(result, scalarUndef);
}
break;
case "attr":
// Second arg for start events is attr hash ref
if ("start".equals(eventName) && eventArgs.length > 1) {
RuntimeArray.push(result, eventArgs[1]);
} else {
// Return empty hash ref for non-start events
RuntimeArray.push(result, new RuntimeHash().createReference());
}
break;
case "attrseq":
// Third arg for start events is attrseq array ref
if ("start".equals(eventName) && eventArgs.length > 2) {
RuntimeArray.push(result, eventArgs[2]);
} else {
RuntimeArray.push(result, new RuntimeArray().createReference());
}
break;
case "text":
// Original text: last arg for start/end, first arg for text
if ("text".equals(eventName) && eventArgs.length > 0) {
RuntimeArray.push(result, eventArgs[0]);
} else if ("start".equals(eventName) && eventArgs.length > 3) {
RuntimeArray.push(result, eventArgs[3]);
} else if ("end".equals(eventName) && eventArgs.length > 1) {
RuntimeArray.push(result, eventArgs[1]);
} else if ("comment".equals(eventName) && eventArgs.length > 0) {
RuntimeArray.push(result, new RuntimeScalar("<!--" + eventArgs[0].toString() + "-->"));
} else if ("declaration".equals(eventName) && eventArgs.length > 0) {
RuntimeArray.push(result, eventArgs[0]);
} else if ("process".equals(eventName) && eventArgs.length > 0) {
RuntimeArray.push(result, eventArgs[0]);
} else if (eventArgs.length > 0) {
RuntimeArray.push(result, eventArgs[eventArgs.length - 1]);
} else {
RuntimeArray.push(result, new RuntimeScalar(""));
}
break;
case "dtext":
// Decoded text (entity-decoded) - for text events
if ("text".equals(eventName) && eventArgs.length > 0) {
// Decode entities in the text
String rawText = eventArgs[0].toString();
RuntimeHash entity2char = GlobalVariable.getGlobalHash("HTML::Entities::entity2char");
String decoded = decodeEntitiesString(rawText, entity2char, false);
RuntimeArray.push(result, new RuntimeScalar(decoded));
} else if (eventArgs.length > 0) {
RuntimeArray.push(result, eventArgs[eventArgs.length - 1]);
} else {
RuntimeArray.push(result, new RuntimeScalar(""));
}
break;
case "is_cdata":
// Boolean: is this CDATA section?
// Check the _in_cdata flag set by marked section parsing
RuntimeScalar inCdata = pstate.get("_in_cdata");
RuntimeArray.push(result, (inCdata != null && inCdata.getBoolean()) ? scalarTrue : scalarFalse);
break;
case "self":
// For method callbacks, "self" is already the invocant
// and should not be duplicated in the args
if (!skipSelf) {
RuntimeArray.push(result, self);
}
break;
case "event":
RuntimeArray.push(result, new RuntimeScalar(eventName));
break;
case "offset":
case "offset_end":
// Offset tracking not implemented yet
RuntimeArray.push(result, new RuntimeScalar(0));
break;
case "length":
// Length of original text
if (eventArgs.length > 0) {
String lastArg;
if ("start".equals(eventName) && eventArgs.length > 3) {
lastArg = eventArgs[3].toString();
} else if ("end".equals(eventName) && eventArgs.length > 1) {
lastArg = eventArgs[1].toString();
} else {
lastArg = eventArgs[0].toString();
}
RuntimeArray.push(result, new RuntimeScalar(lastArg.length()));
} else {
RuntimeArray.push(result, new RuntimeScalar(0));
}
break;
case "line":
case "column":
// Line/column tracking not implemented yet
RuntimeArray.push(result, new RuntimeScalar(0));
break;
case "token0":
// First token for process instructions
if ("process".equals(eventName) && eventArgs.length > 0) {
String piText = eventArgs[0].toString();
// Extract first token from <?token ...?>
if (piText.startsWith("<?")) {
piText = piText.substring(2);
if (piText.endsWith("?>")) {
piText = piText.substring(0, piText.length() - 2);
}
String[] parts = piText.trim().split("\\s+", 2);
RuntimeArray.push(result, new RuntimeScalar(parts[0]));
} else {
RuntimeArray.push(result, new RuntimeScalar(""));
}
} else {
// Fall back to tokens[0] for non-PI events
RuntimeArray tokensArr = buildTokensArray(eventName, eventArgs);
if (tokensArr.size() > 0) {
RuntimeArray.push(result, tokensArr.get(0));
} else {
RuntimeArray.push(result, new RuntimeScalar(""));
}
}
break;
case "tokens":
// Array reference of all tokens for this event.
// start => [tagname, attr1, val1, attr2, val2, ...]
// end => [tagname]
// text/dtext => [text]
// comment => [comment_body]
// declaration => [declaration_body]
// process => [pi_body]
RuntimeArray.push(result,
buildTokensArray(eventName, eventArgs).createReference());
break;
case "tokenpos":
// Array reference of [start, end] byte-offset pairs
// matching `tokens`. We don't track byte offsets yet, so
// return a same-length arrayref of [0, 0] pairs. This is
// good enough for callers that just iterate; downstream
// modules treating tokenpos as authoritative will need
// proper offset tracking (currently a TODO at the
// `offset`/`offset_end` cases).
{
RuntimeArray pos = new RuntimeArray();
RuntimeArray tokensArr = buildTokensArray(eventName, eventArgs);
for (int i = 0; i < tokensArr.size(); i++) {
RuntimeArray pair = new RuntimeArray();
RuntimeArray.push(pair, new RuntimeScalar(0));
RuntimeArray.push(pair, new RuntimeScalar(0));
RuntimeArray.push(pos, pair.createReference());
}
RuntimeArray.push(result, pos.createReference());
}
break;
case "skipped_text":
RuntimeArray.push(result, new RuntimeScalar(""));
break;
default:
// tokenN where N is a non-negative integer => tokens[N]
if (token.length() > 5 && token.startsWith("token")
&& token.substring(5).chars().allMatch(Character::isDigit)) {
int idx;
try {
idx = Integer.parseInt(token.substring(5));
} catch (NumberFormatException e) {
idx = -1;
}
RuntimeArray tokensArr = buildTokensArray(eventName, eventArgs);
if (idx >= 0 && idx < tokensArr.size()) {
RuntimeArray.push(result, tokensArr.get(idx));
} else {
RuntimeArray.push(result, new RuntimeScalar(""));
}
} else {
// Unknown argspec token - pass empty string
RuntimeArray.push(result, new RuntimeScalar(""));
}
break;
}
}
return result;
}
/**
* Build the `tokens` array for a given event, per HTML::Parser semantics.
* See `case "tokens":` above for the per-event shape.
*
* @param eventName the event name (start, end, text, comment, ...)
* @param eventArgs the internal event-arg tuple as passed to fireEvent
* @return a flat RuntimeArray of token scalars (NOT yet a reference)
*/
private static RuntimeArray buildTokensArray(String eventName, RuntimeScalar[] eventArgs) {
RuntimeArray tokens = new RuntimeArray();
if (eventArgs == null || eventArgs.length == 0) {
return tokens;
}
switch (eventName) {
case "start":
// eventArgs = [tagname, attr_hashref, attrseq_arrayref, original_text]
RuntimeArray.push(tokens, eventArgs[0]);
if (eventArgs.length > 2) {
RuntimeScalar attrHashRef = eventArgs[1];
RuntimeScalar attrSeqRef = eventArgs[2];
RuntimeHash attrHash = attrHashRef.hashDeref();
RuntimeArray attrSeq = attrSeqRef.arrayDeref();
int n = attrSeq.size();
for (int i = 0; i < n; i++) {
RuntimeScalar key = attrSeq.get(i);
String keyStr = key.toString();
RuntimeArray.push(tokens, key);
RuntimeArray.push(tokens, attrHash.get(keyStr));
}
}
break;
case "end":
case "text":
case "dtext":
case "comment":
case "declaration":
case "process":
case "default":
RuntimeArray.push(tokens, eventArgs[0]);
break;
default:
// Unknown event: best-effort, push the first arg.
RuntimeArray.push(tokens, eventArgs[0]);
break;
}
return tokens;
}
/**
* Basic HTML parser - fires text, start, end events.
* This is a simplified version; Phase 2 will port the full hparser.c logic.
*/
private static void parseHtml(RuntimeScalar self, RuntimeHash selfHash, RuntimeHash pstate, String html) {
int len = html.length();
int i = 0;
int textStart = 0;
while (i < len) {
if (html.charAt(i) == '<') {
// Flush pending text
if (i > textStart) {
fireEvent(self, selfHash, pstate, "text",
new RuntimeScalar(html.substring(textStart, i)));
}
int tagStart = i;
i++; // skip '<'
// If we're at end of input, buffer the '<' for next parse() call
if (i >= len) {
pstate.put("_buf", new RuntimeScalar(html.substring(tagStart)));
return;
}
if (i < len && html.charAt(i) == '/') {
// End tag
i++;
int nameStart = i;
while (i < len && html.charAt(i) != '>' && !Character.isWhitespace(html.charAt(i))) {
i++;
}
String tagName = html.substring(nameStart, i).toLowerCase();
while (i < len && html.charAt(i) != '>') i++;
if (i >= len) {
// Incomplete end tag - buffer for next parse() call
pstate.put("_buf", new RuntimeScalar(html.substring(tagStart)));
return;
}
if (i < len) i++; // skip '>'
fireEvent(self, selfHash, pstate, "end",
new RuntimeScalar(tagName),
new RuntimeScalar(html.substring(tagStart, i)));
textStart = i;
} else if (i < len && html.charAt(i) == '!') {
// Comment, marked section, or declaration
i++;
// Check for marked sections: <![KEYWORD[...]]>
boolean markedSections = pstate.get("marked_sections").getBoolean()
|| pstate.get("xml_mode").getBoolean();
if (i < len && html.charAt(i) == '[') {
if (markedSections) {
i++; // skip '['
// Extract keyword (CDATA, INCLUDE, IGNORE, etc.)
int kwStart = i;
while (i < len && html.charAt(i) != '[' && html.charAt(i) != ']') i++;
String keyword = html.substring(kwStart, i).trim().toUpperCase();
if (i < len && html.charAt(i) == '[') {
i++; // skip second '['
int contentStart = i;
int endIdx = html.indexOf("]]>", i);
if (endIdx < 0) {
// Unterminated marked section - buffer
pstate.put("_buf", new RuntimeScalar(html.substring(tagStart)));
return;
}
String content = html.substring(contentStart, endIdx);
i = endIdx + 3; // skip ]]>
switch (keyword) {
case "CDATA":
// Emit as text with is_cdata=true
pstate.put("_in_cdata", scalarTrue);
fireEvent(self, selfHash, pstate, "text",
new RuntimeScalar(content));
pstate.put("_in_cdata", scalarFalse);
break;
case "IGNORE":
// Skip content entirely
break;
case "INCLUDE":
default:
// Recursively parse content as HTML
// Save and restore textStart since we recurse
RuntimeScalar savedBuf = pstate.get("_buf");
pstate.put("_buf", new RuntimeScalar(""));
parseHtml(self, selfHash, pstate, content);
pstate.put("_buf", savedBuf);
break;
}
} else {
// Malformed <![...] without second [ - treat as declaration
int endIdx = html.indexOf('>', i);
if (endIdx >= 0) {
String decl = html.substring(tagStart, endIdx + 1);
i = endIdx + 1;
fireEvent(self, selfHash, pstate, "declaration",
new RuntimeScalar(decl));
} else {
pstate.put("_buf", new RuntimeScalar(html.substring(tagStart)));
return;
}
}
} else {
// marked_sections disabled - treat as bogus comment (text up to >)
int endIdx = html.indexOf('>', i);
if (endIdx >= 0) {
String comment = html.substring(i, endIdx);
i = endIdx + 1;
fireEvent(self, selfHash, pstate, "comment",
new RuntimeScalar(comment));
} else {
pstate.put("_buf", new RuntimeScalar(html.substring(tagStart)));
return;
}
}
} else if (i + 1 < len && html.charAt(i) == '-' && html.charAt(i + 1) == '-') {
// Comment
i += 2;
int commentStart = i;
int endIdx = html.indexOf("-->", i);
if (endIdx >= 0) {
String comment = html.substring(commentStart, endIdx);
i = endIdx + 3;
fireEvent(self, selfHash, pstate, "comment",
new RuntimeScalar(comment));
} else {
// Unterminated comment - buffer it
pstate.put("_buf", new RuntimeScalar(html.substring(tagStart)));
return;
}
} else {
// Declaration
int endIdx = html.indexOf('>', i);
if (endIdx >= 0) {
String decl = html.substring(tagStart, endIdx + 1);
i = endIdx + 1;
fireEvent(self, selfHash, pstate, "declaration",
new RuntimeScalar(decl));
} else {
pstate.put("_buf", new RuntimeScalar(html.substring(tagStart)));
return;
}
}
textStart = i;
} else if (i < len && html.charAt(i) == '?') {
// Processing instruction
int endIdx = html.indexOf("?>", i);
if (endIdx >= 0) {
String pi = html.substring(tagStart, endIdx + 2);
i = endIdx + 2;
fireEvent(self, selfHash, pstate, "process",
new RuntimeScalar(pi));
} else {
pstate.put("_buf", new RuntimeScalar(html.substring(tagStart)));
return;
}
textStart = i;
} else {
// Start tag
int nameStart = i;
while (i < len && html.charAt(i) != '>' && html.charAt(i) != '/'
&& !Character.isWhitespace(html.charAt(i))) {
i++;
}
String tagName = html.substring(nameStart, i).toLowerCase();
// Parse attributes
RuntimeHash attrs = new RuntimeHash();
RuntimeArray attrSeq = new RuntimeArray();
while (i < len && html.charAt(i) != '>' && html.charAt(i) != '/') {
// Skip whitespace
while (i < len && Character.isWhitespace(html.charAt(i))) i++;
if (i >= len || html.charAt(i) == '>' || html.charAt(i) == '/') break;
// Attribute name
int attrNameStart = i;
while (i < len && html.charAt(i) != '=' && html.charAt(i) != '>'
&& html.charAt(i) != '/' && !Character.isWhitespace(html.charAt(i))) {
i++;
}
String attrName = html.substring(attrNameStart, i).toLowerCase();
RuntimeArray.push(attrSeq, new RuntimeScalar(attrName));