Repository navigation
Expand file tree
/
Copy pathtextparser.c
More file actions
10743 lines (9738 loc) · 417 KB
/
Copy pathtextparser.c
File metadata and controls
10743 lines (9738 loc) · 417 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
#include <textparser.h>
#include "adv_regex.h"
#include "logger.h"
#include "string_pool.h"
#include <os.h>
#include <string.h>
#include <stdlib.h>
#include <stddef.h>
#include <stdio.h>
#include <fcntl.h>
#include <stdbool.h>
#include <stdatomic.h>
#include <ctype.h>
#include <time.h>
#ifndef SSIZE_MAX
#define SSIZE_MAX ((ssize_t)((((size_t)-1) << 1) >> 1))
#endif
#define MAX_PARSE_SIZE (16 * 1024 * 1024)
#define TOKEN_NOT_FOUND -1
/*
* Internal node_flags marker recording that a node's subtree has been through
* textparser_post_process. Cast/declaration disambiguation mutate token IDs in
* place without synthesizing a tagged node, so this marker is the only reliable
* way for the incremental engine to know that a tree is in AST mode and must be
* re-derived after an edit. Bit 5 is unused by the public TEXTPARSER_NODE_* set.
*/
#define TEXTPARSER_NODE_POST_PROCESSED (1u << 5)
#define exit_with_error(handle, error_text, offset, error_len) \
LOGE("Error: %s at %zu", error_text, offset); \
if(handle) (handle)->error = error_text; \
if(handle) (handle)->error_offset = offset; \
if(handle) (handle)->error_length = error_len; \
goto exit; \
#define check_and_exit_on_fatal_parsing_error(handle, child, offset) \
if ((handle)->error) { \
LOGW("Fatal error detected(%s) at offset %zu. exiting..", (handle)->error, offset); \
goto exit; \
} \
if ((child)->len == 0) { \
LOGW("child->len == 0 detected(%s) at offset %zu. exiting..", (handle)->error ? (handle)->error : "none", offset); \
exit_with_error(handle, "infinite loop due to 0-length token", offset, 0); \
}
#define check_and_exit_on_fatal_parsing_error_start_stop(handle, child, offset) \
if ((handle)->error) { \
LOGW("Fatal error detected(%s) at offset %zu. exiting..", (handle)->error, offset); \
goto exit; \
}
static size_t calculate_chunk_size(size_t text_size);
static size_t textparser_skip_whitespace(const struct textparser_handle *handle, size_t pos);
/**
* Check whether a given token ID corresponds to trivia (unprocessed text, whitespace, or delimiters).
*
* @param token_id Integer ID of the token to evaluate.
* @return true if token_id is UNPROCESSED, WHITESPACE, START_DELIMITER, or END_DELIMITER; false otherwise.
*/
static inline bool is_trivia_token_id(int token_id)
{
return token_id == TEXTPARSER_TOKEN_ID_UNPROCESSED ||
token_id == TEXTPARSER_TOKEN_ID_WHITESPACE ||
token_id == TEXTPARSER_TOKEN_ID_START_DELIMITER ||
token_id == TEXTPARSER_TOKEN_ID_END_DELIMITER;
}
enum parent_start_stop{
TEXTPARSER_SEARCH_END_TOKEN,
TEXTPARSER_SEARCH_START_TOKEN,
};
typedef struct textparser_handler_entry {
char *name;
textparser_semantic_handler handler;
void *user_data;
struct textparser_handler_entry *next;
} textparser_handler_entry;
typedef struct textparser_capture_entry {
const char *name;
size_t start;
size_t end;
struct textparser_capture_entry *next;
} textparser_capture_entry;
typedef struct {
const char *handler_name;
textparser_event event;
} textparser_pending_event;
typedef struct textparser_decoder_entry {
char *name;
textparser_decoder_fn decoder;
void *user_data;
struct textparser_decoder_entry *next;
} textparser_decoder_entry;
typedef struct textparser_validator_entry {
char *name;
textparser_validator_fn validator;
void *user_data;
struct textparser_validator_entry *next;
} textparser_validator_entry;
typedef struct textparser_operand_validator_entry {
char *name;
textparser_operand_validator_fn validator;
void *user_data;
struct textparser_operand_validator_entry *next;
} textparser_operand_validator_entry;
typedef struct textparser_predicate_entry {
char *name;
textparser_predicate_fn predicate;
textparser_parser_predicate_fn parser_predicate;
void *user_data;
struct textparser_predicate_entry *next;
} textparser_predicate_entry;
typedef struct textparser_context_entry {
char *name;
int64_t value;
struct textparser_context_entry *next;
} textparser_context_entry;
#define TEXTPARSER_MAX_MODE_STACK 64
typedef struct {
textparser_t owner;
const textparser_language_definition *language;
size_t source_offset;
size_t token_index;
size_t pending_event_count;
unsigned speculation_depth;
unsigned recovery_depth;
bool has_previous_token;
textparser_lex_token previous_token;
} textparser_parser_runtime;
typedef struct {
int kind;
size_t start;
size_t end;
} textparser_cached_trivia;
typedef struct textparser_lexer_cache_entry {
size_t source_offset;
int source_rule;
uint64_t capture_generation;
char *mode;
char *goal;
textparser_lex_token token;
struct textparser_lexer_cache_entry *next;
} textparser_lexer_cache_entry;
/* A dynamic lexer capture (e.g. a here-doc delimiter). Stored as raw subject
* bytes so the dynamic match can compare without re-encoding. */
typedef struct {
char *bytes;
size_t byte_length;
size_t unit_length;
bool strip_tabs;
bool strip_indent;
size_t body_start;
} textparser_lexer_capture;
/* FIFO of captures for one slot (bash reads queued here-docs in order). */
typedef struct {
textparser_lexer_capture *items;
size_t count;
size_t capacity;
} textparser_lexer_capture_queue;
/* Reusable chunked bump allocator. `scratch` is reset at the start of every
* incremental parse and only holds per-call temporaries. */
typedef struct {
void **chunks;
size_t chunk_count;
size_t chunk_capacity;
size_t chunk_size;
void *current_chunk;
size_t current_chunk_index;
size_t current_chunk_used;
} textparser_arena;
struct textparser_handle {
const textparser_language_definition *language;
adv_regex_context *regex_ctx;
void *start_regex;
void *end_regex;
void *mmap_addr;
size_t mmap_size;
void *owned_buffer;
size_t owned_buffer_capacity;
enum textparser_bom bom;
enum textparser_encoding text_format;
textparser_token_item *first_item;
size_t error_offset;
size_t error_length;
const char *error;
size_t token_count;
const char *text_addr;
size_t text_size;
size_t no_lines;
size_t *lines;
/* Cached end-of-line offset for the single-line search bound. Valid for any
* position in [line_cache_anchor, line_cache_end); reset per parse. */
size_t line_cache_anchor;
size_t line_cache_end;
// Arena allocator fields
textparser_arena arena; // live token tree
textparser_arena scratch; // per-call temporaries
void (*callback)(textparser_t, textparser_token_item *, enum textparser_callback_type callback_type, void *user_data);
void *user_data;
int recursion_depth;
size_t parse_steps;
size_t parse_step_limit;
bool parse_budget_exceeded;
char *filename;
/* Semantic action handlers & node ID generation */
uint64_t next_node_id;
textparser_handler_entry *handlers;
textparser_pending_event *pending_events;
size_t pending_event_capacity;
/* Phase 3: Decoders & Validators */
textparser_decoder_entry *decoders;
textparser_validator_entry *validators;
/* Phase 3: Lexer Mode Stack & Goals */
char *mode_stack[TEXTPARSER_MAX_MODE_STACK];
size_t mode_stack_depth;
char *lexical_goal;
/* Phase 4: Predicates & Scoped Contexts */
textparser_predicate_entry *predicates;
textparser_context_entry *contexts;
/* Phase 5: Operator Precedence & Pratt Engine */
textparser_operator_def *operators;
size_t operator_count;
size_t operator_capacity;
textparser_operand_validator_entry *operand_validators;
/* Phase 6: Multi-Diagnostic Vector */
textparser_diagnostic *diagnostics;
size_t diagnostic_count;
size_t diagnostic_capacity;
/* Immutable lexer snapshot for the latest successful parse. The buffers are
* retained across incremental edits so a rebuild reuses capacity instead of
* freeing and reallocating on every edit. */
textparser_lex_token *lexer_tokens;
size_t lexer_token_count;
size_t lexer_token_capacity;
textparser_lex_trivia *lexer_trivia;
size_t lexer_trivia_count;
size_t lexer_trivia_capacity;
textparser_lexer_cache_entry *lexer_cache;
uint64_t capture_generation;
/* Dynamic lexer captures (here-doc delimiters). Slot 0 is unused; slots are
* 1-based to match the JSON `capture`/`dynamic` fields. */
textparser_lexer_capture_queue lexer_captures[TEXTPARSER_MAX_LEXER_CAPTURES];
/* Phase 3 — position bias for the flat snapshot arrays.
*
* In-leaf edits change the length of one leaf without restructuring the
* tree. Instead of walking the entire suffix of `lexer_tokens` and
* `lexer_trivia` to shift every entry's `start`/`end` by `delta_units`,
* the delta is recorded here and applied lazily:
*
* For i >= lexer_snapshot_token_bias_start:
* effective start = lexer_tokens[i].start + lexer_snapshot_bias
* effective end = lexer_tokens[i].end + lexer_snapshot_bias
*
* For j >= lexer_snapshot_trivia_bias_start:
* effective start = lexer_trivia[j].start + lexer_snapshot_bias
* effective end = lexer_trivia[j].end + lexer_snapshot_bias
*
* Callers that need absolute positions (binary-search find functions,
* memo-shift reads) must use the LEXER_TOKEN_START / LEXER_TOKEN_END /
* LEXER_TRIVIA_START / LEXER_TRIVIA_END accessor macros. The bias is
* materialized (applied to every suffix entry) before any full rebuild and
* on stream clear, so the grammar executor always sees correct values.
*
* Multiple consecutive in-leaf edits with the same bias threshold
* accumulate into a single delta field without extra allocation. */
ssize_t lexer_snapshot_bias;
size_t lexer_snapshot_token_bias_start;
size_t lexer_snapshot_trivia_bias_start;
/* Packrat memoization table for grammar productions. */
struct textparser_memo_entry *grammar_memo;
uint64_t next_memo_seq;
/* Packrat memoization of legacy parser failures, keyed by
* (token_id, offset, parent_token_id, prev_token_id). Bounds the
* exponential candidate retry loop on nested ambiguous input. */
struct textparser_parse_memo **parse_memo;
size_t parse_memo_buckets;
size_t parse_memo_count;
/* Shared transactional state used by all grammar operations. */
textparser_parser_runtime parser;
};
static void textparser_memo_clear(struct textparser_handle *handle);
static void textparser_memo_shift_and_invalidate(
struct textparser_handle *handle,
size_t dirty_start_token,
size_t dirty_end_token,
ssize_t delta_tokens);
/**
* Release cached contextual lexer lookup entries.
*
* The cache is keyed by absolute source offset, so any text edit or stream
* rebuild invalidates every entry. The token/trivia snapshot buffers are
* deliberately left intact so they can be reused by the next rebuild.
*
* @param handle Pointer to the textparser handle whose lexer cache will be cleared.
*/
static void textparser_free_capture_queues(textparser_lexer_capture_queue *queues) {
for (int i = 0; i < TEXTPARSER_MAX_LEXER_CAPTURES; i++) {
textparser_lexer_capture_queue *queue = &queues[i];
for (size_t j = 0; j < queue->count; j++) free(queue->items[j].bytes);
free(queue->items);
queue->items = nullptr;
queue->count = 0;
queue->capacity = 0;
}
}
static void textparser_clear_lexer_cache(struct textparser_handle *handle)
{
if (handle == nullptr) return;
textparser_lexer_cache_entry *entry = handle->lexer_cache;
while (entry != nullptr) {
textparser_lexer_cache_entry *next = entry->next;
free(entry->mode);
free(entry->goal);
free(entry);
entry = next;
}
handle->lexer_cache = nullptr;
textparser_free_capture_queues(handle->lexer_captures);
handle->capture_generation++;
}
/* ---- Phase 3: snapshot position-bias accessor macros --------------------
*
* These macros must be used by any code that reads a lexer_tokens[i].start/end
* or lexer_trivia[j].start/end after a potential in-leaf patch. The bias is
* zero (no-op) when lexer_snapshot_bias == 0 or the index is below the
* threshold. The grammar executor and full-rebuild paths always see a
* materialized (bias-free) snapshot, so they can read the fields directly.
*/
#define LEXER_TOKEN_START(h, i) \
((size_t)((ssize_t)(h)->lexer_tokens[(i)].start + \
((i) >= (h)->lexer_snapshot_token_bias_start ? (h)->lexer_snapshot_bias : 0)))
#define LEXER_TOKEN_END(h, i) \
((size_t)((ssize_t)(h)->lexer_tokens[(i)].end + \
((i) >= (h)->lexer_snapshot_token_bias_start ? (h)->lexer_snapshot_bias : 0)))
#define LEXER_TRIVIA_START(h, j) \
((size_t)((ssize_t)(h)->lexer_trivia[(j)].start + \
((j) >= (h)->lexer_snapshot_trivia_bias_start ? (h)->lexer_snapshot_bias : 0)))
#define LEXER_TRIVIA_END(h, j) \
((size_t)((ssize_t)(h)->lexer_trivia[(j)].end + \
((j) >= (h)->lexer_snapshot_trivia_bias_start ? (h)->lexer_snapshot_bias : 0)))
/**
* Materialize a pending snapshot position bias into the stored arrays.
*
* Each in-leaf patch records a `lexer_snapshot_bias` delta instead of walking
* the O(n) suffix. Before any full rebuild or stream release the bias must be
* applied so the stored values are correct absolute positions again.
*
* The function is O(n_suffix_tokens + n_suffix_trivia) — the same cost as the
* old per-edit loops — but is called at most once per structural edit (rebuild)
* rather than once per in-leaf edit, so the total work over a sequence of k
* in-leaf edits followed by one rebuild drops from O(k*n) to O(n).
*
* @param handle Pointer to the textparser handle.
*/
static void textparser_snapshot_materialize_bias(struct textparser_handle *handle)
{
if (handle == nullptr || handle->lexer_snapshot_bias == 0) return;
ssize_t bias = handle->lexer_snapshot_bias;
for (size_t i = handle->lexer_snapshot_token_bias_start;
i < handle->lexer_token_count; i++) {
handle->lexer_tokens[i].start =
(size_t)((ssize_t)handle->lexer_tokens[i].start + bias);
handle->lexer_tokens[i].end =
(size_t)((ssize_t)handle->lexer_tokens[i].end + bias);
}
for (size_t j = handle->lexer_snapshot_trivia_bias_start;
j < handle->lexer_trivia_count; j++) {
handle->lexer_trivia[j].start =
(size_t)((ssize_t)handle->lexer_trivia[j].start + bias);
handle->lexer_trivia[j].end =
(size_t)((ssize_t)handle->lexer_trivia[j].end + bias);
}
handle->lexer_snapshot_bias = 0;
handle->lexer_snapshot_token_bias_start = 0;
handle->lexer_snapshot_trivia_bias_start = 0;
}
/**
* Release allocated lexer token streams, trivia streams, and cached lexer lookup entries stored in the handle.
*
* @param handle Pointer to the textparser handle whose lexer streams will be cleared.
*/
static void textparser_clear_lexer_streams(struct textparser_handle *handle)
{
if (handle == nullptr) return;
free(handle->lexer_tokens);
free(handle->lexer_trivia);
handle->lexer_tokens = nullptr;
handle->lexer_token_count = 0;
handle->lexer_token_capacity = 0;
handle->lexer_trivia = nullptr;
handle->lexer_trivia_count = 0;
handle->lexer_trivia_capacity = 0;
handle->lexer_snapshot_bias = 0;
handle->lexer_snapshot_token_bias_start = 0;
handle->lexer_snapshot_trivia_bias_start = 0;
textparser_clear_lexer_cache(handle);
}
/**
* Convert a character code unit offset into an absolute byte offset based on document text encoding.
*
* @param handle Pointer to the textparser handle holding encoding configuration.
* @param pos Character unit offset within the input text.
* @return Absolute byte offset corresponding to pos.
*/
static size_t textparser_get_byte_offset(const struct textparser_handle *handle, size_t pos)
{
switch (handle->text_format)
{
case TEXTPARSER_ENCODING_UNICODE:
case TEXTPARSER_ENCODING_UTF_16:
return pos * sizeof(uint16_t);
case TEXTPARSER_ENCODING_UTF_32:
return pos * sizeof(uint32_t);
default:
return pos;
}
}
/**
* Convert a character code unit length into a byte length based on document text encoding.
*
* @param handle Pointer to the textparser handle holding encoding configuration.
* @param len Length in character code units.
* @return Length expressed in bytes.
*/
static size_t textparser_get_byte_len(const struct textparser_handle *handle, size_t len)
{
return textparser_get_byte_offset(handle, len);
}
/**
* Calculate the total number of character code units in the active document text buffer.
*
* @param handle Pointer to the textparser handle.
* @return Total character code units in text_addr.
*/
static size_t textparser_get_total_units(const struct textparser_handle *handle)
{
switch (handle->text_format)
{
case TEXTPARSER_ENCODING_UNICODE:
case TEXTPARSER_ENCODING_UTF_16:
return handle->text_size / sizeof(uint16_t);
case TEXTPARSER_ENCODING_UTF_32:
return handle->text_size / sizeof(uint32_t);
default:
return handle->text_size;
}
}
/**
* Retrieve the character code unit at a specific unit offset in the text buffer.
*
* @param handle Pointer to the textparser handle.
* @param pos 0-based character unit offset to read.
* @return Character code unit value cast to uint32_t.
*/
static uint32_t textparser_get_unit_at(const struct textparser_handle *handle, size_t pos)
{
switch (handle->text_format)
{
case TEXTPARSER_ENCODING_UNICODE:
case TEXTPARSER_ENCODING_UTF_16:
return ((const uint16_t *)handle->text_addr)[pos];
case TEXTPARSER_ENCODING_UTF_32:
return ((const uint32_t *)handle->text_addr)[pos];
default:
return (unsigned char)handle->text_addr[pos];
}
}
/**
* Determine the code unit length of a single character starting at pos (e.g. multi-byte UTF-8 sequence).
*
* @param handle Pointer to the textparser handle.
* @param pos Character unit offset where the character begins.
* @return Length of the character in code units (1 to 4 units).
*/
static size_t textparser_char_len(const struct textparser_handle *handle, size_t pos)
{
if (handle->text_format == TEXTPARSER_ENCODING_UTF_8)
{
unsigned char c = (unsigned char)handle->text_addr[pos];
if ((c & 0x80) == 0) return 1;
if ((c & 0xE0) == 0xC0) return 2;
if ((c & 0xF0) == 0xE0) return 3;
if ((c & 0xF8) == 0xF0) return 4;
return 1;
}
return 1;
}
/**
* Scan forward from pos to locate the character unit offset of the line ending.
*
* @param handle Pointer to the textparser handle.
* @param pos Starting character unit offset.
* @return Unit offset immediately preceding the newline sequence, or end-of-text if on the last line.
*/
static size_t textparser_get_end_of_line_units(const struct textparser_handle *handle, size_t pos)
{
// The parser queries the line end for every single-line candidate at every
// position. Scanning to the newline each time is O(line length) per call,
// which is O(n^2) for long lines. Cache the line end: any position in
// [anchor, end) shares the same newline.
struct textparser_handle *mutable_handle = (struct textparser_handle *)handle;
if (mutable_handle->line_cache_end > pos && pos >= mutable_handle->line_cache_anchor) {
return mutable_handle->line_cache_end - pos;
}
size_t total = textparser_get_total_units(handle);
size_t cur = pos;
while (cur < total) {
uint32_t ch = textparser_get_unit_at(handle, cur);
if (ch == '\n' || ch == '\r')
break;
cur++;
}
mutable_handle->line_cache_anchor = pos;
mutable_handle->line_cache_end = cur;
return cur - pos;
}
/**
* Determine the maximum searchable unit length from pos depending on the token multi_line configuration.
*
* @param handle Pointer to the textparser handle.
* @param pos Starting unit offset for search.
* @param token_def Token definition determining whether searching is bounded by the current line.
* @return Maximum number of character code units available for matching.
*/
static size_t textparser_get_search_len(const struct textparser_handle *handle, size_t pos, const textparser_token *token_def)
{
size_t len = textparser_get_total_units(handle) - pos;
if (token_def != nullptr && token_def->multi_line == false) {
size_t line_len = textparser_get_end_of_line_units(handle, pos);
if (line_len < len)
len = line_len;
}
return len;
}
/**
* Validate whether a raw byte buffer conforms to well-formed UTF-8 encoding rules.
*
* @param text Pointer to raw byte buffer.
* @param len Buffer length in bytes.
* @return true if all byte sequences form valid UTF-8 code points; false otherwise.
*/
static bool textparser_validate_utf8(const char *text, size_t len)
{
size_t i = 0;
while (i < len) {
unsigned char c = (unsigned char)text[i];
if (c < 0x80) { i += 1; continue; }
size_t extra;
uint32_t cp;
if ((c & 0xE0) == 0xC0) { extra = 1; cp = c & 0x1F; }
else if ((c & 0xF0) == 0xE0) { extra = 2; cp = c & 0x0F; }
else if ((c & 0xF8) == 0xF0) { extra = 3; cp = c & 0x07; }
else return false;
if (i + extra >= len) return false;
for (size_t k = 1; k <= extra; k++) {
unsigned char cc = (unsigned char)text[i + k];
if ((cc & 0xC0) != 0x80) return false;
cp = (cp << 6) | (cc & 0x3F);
}
if ((extra == 1 && cp < 0x80) || (extra == 2 && cp < 0x800) ||
(extra == 3 && cp < 0x10000) || cp > 0x10FFFF ||
(cp >= 0xD800 && cp <= 0xDFFF))
return false;
i += extra + 1;
}
return true;
}
/**
* Validate whether a raw byte buffer conforms to well-formed UTF-16 encoding with valid surrogate pairs.
*
* @param handle Pointer to the active textparser handle.
* @return true if buffer length is 16-bit aligned and surrogates are paired properly; false otherwise.
*/
static bool textparser_validate_utf16(const struct textparser_handle *handle)
{
size_t units = textparser_get_total_units(handle);
const uint16_t *u = (const uint16_t *)handle->text_addr;
for (size_t i = 0; i < units; i++) {
uint16_t w = u[i];
if (w >= 0xD800 && w <= 0xDBFF) {
if (i + 1 >= units) return false;
uint16_t low = u[i + 1];
if (!(low >= 0xDC00 && low <= 0xDFFF)) return false;
i++;
} else if (w >= 0xDC00 && w <= 0xDFFF) {
return false;
}
}
return true;
}
/**
* Validate whether a raw byte buffer conforms to well-formed UTF-32 code points in valid Unicode ranges.
*
* @param handle Pointer to the active textparser handle.
* @return true if buffer length is 32-bit aligned and all values represent valid Unicode scalars; false otherwise.
*/
static bool textparser_validate_utf32(const struct textparser_handle *handle)
{
size_t units = textparser_get_total_units(handle);
const uint32_t *u = (const uint32_t *)handle->text_addr;
for (size_t i = 0; i < units; i++) {
uint32_t c = u[i];
if (c > 0x10FFFF || (c >= 0xD800 && c <= 0xDFFF)) return false;
}
return true;
}
/**
* Validate the entire active text buffer according to the handle configured text_format encoding.
*
* @param handle Pointer to the textparser handle.
* @return true if the buffer content is valid for handle->text_format; false otherwise.
*/
static bool textparser_validate_text_encoding(const struct textparser_handle *handle)
{
switch (handle->text_format) {
case TEXTPARSER_ENCODING_UTF_8:
return textparser_validate_utf8(handle->text_addr, handle->text_size);
case TEXTPARSER_ENCODING_UTF_16:
case TEXTPARSER_ENCODING_UNICODE:
return textparser_validate_utf16(handle);
case TEXTPARSER_ENCODING_UTF_32:
return textparser_validate_utf32(handle);
default:
return true; // LATIN1: pcre2 runs without the UTF flag
}
}
/**
* Compute an optimal memory chunk size for the arena allocator based on document text size.
*
* @param filesize Size of input file in bytes.
* @return Calculated arena allocation chunk size in bytes.
*/
static size_t calculate_chunk_size(size_t filesize)
{
size_t min_chunk = 4096; // 4KB minimum
size_t max_chunk = 4194304; // 4MB initial cap
// Estimate initial arena size as 75% of file size
size_t estimated = (filesize * 3) / 4;
if (estimated < min_chunk) {
return min_chunk;
}
size_t chunk_size = min_chunk;
while (chunk_size < estimated && chunk_size < max_chunk) {
chunk_size *= 2;
}
return chunk_size;
}
/**
* Convert a UTF-16 Big-Endian text buffer into native host endianness in place.
*
* @param src Pointer to UTF-16 Big-Endian byte buffer.
* @param size Size of the buffer in bytes.
* @return Pointer to converted native buffer, or NULL on error.
*/
static void *textparser_convert_utf16be_to_native(const char *src, size_t size)
{
size_t unit_count = size / sizeof(uint16_t);
if (unit_count == 0)
return nullptr;
uint16_t *buf = (uint16_t *)malloc(size);
if (buf == nullptr)
return nullptr;
const uint16_t *units = (const uint16_t *)src;
for (size_t i = 0; i < unit_count; i++) {
buf[i] = (uint16_t)((units[i] >> 8) | (units[i] << 8));
}
return buf;
}
/**
* Release all memory chunks held by an arena and reset it.
*
* @param arena Pointer to the arena to free.
*/
static void arena_free(textparser_arena *arena)
{
if (arena->chunks) {
for (size_t i = 0; i < arena->chunk_count; i++) {
free(arena->chunks[i]);
}
free(arena->chunks);
}
memset(arena, 0, sizeof(*arena));
}
/**
* Reset an arena so its existing chunks are reused from the start,
* releasing any high-water chunks beyond the base chunk.
*
* @param arena Pointer to the arena to reset.
*/
static void arena_reset(textparser_arena *arena)
{
if (arena->chunk_count > 1) {
for (size_t i = 1; i < arena->chunk_count; i++) {
free(arena->chunks[i]);
arena->chunks[i] = nullptr;
}
arena->chunk_count = 1;
}
arena->current_chunk_index = 0;
arena->current_chunk_used = 0;
arena->current_chunk = (arena->chunk_count > 0) ? arena->chunks[0] : nullptr;
}
/**
* Allocate zero-initialized, pointer-aligned memory from an arena.
*
* @param arena Pointer to the arena.
* @param size Number of bytes to allocate.
* @return Pointer to the allocation, or NULL on allocation failure.
*/
static void *arena_alloc(textparser_arena *arena, size_t size)
{
const size_t align = sizeof(void *);
size = (size + align - 1) & ~(align - 1);
if (arena->current_chunk == nullptr ||
arena->current_chunk_used + size > arena->chunk_size)
{
if (arena->current_chunk != nullptr &&
arena->current_chunk_index + 1 < arena->chunk_count)
{
arena->current_chunk_index++;
arena->current_chunk = arena->chunks[arena->current_chunk_index];
arena->current_chunk_used = 0;
}
else
{
size_t chunk_size = (size > arena->chunk_size) ? size : arena->chunk_size;
void *new_chunk = malloc(chunk_size);
if (new_chunk == nullptr) {
return nullptr;
}
if (arena->chunk_count >= arena->chunk_capacity) {
size_t new_capacity = arena->chunk_capacity == 0 ? 4 : arena->chunk_capacity * 2;
void **new_chunks = realloc(arena->chunks, new_capacity * sizeof(void *));
if (new_chunks == nullptr) {
free(new_chunk);
return nullptr;
}
arena->chunks = new_chunks;
arena->chunk_capacity = new_capacity;
}
arena->chunks[arena->chunk_count] = new_chunk;
arena->current_chunk = new_chunk;
arena->current_chunk_index = arena->chunk_count;
arena->chunk_count++;
arena->current_chunk_used = 0;
}
}
void *ret = (char *)arena->current_chunk + arena->current_chunk_used;
arena->current_chunk_used += size;
return ret;
}
/**
* Release all memory chunks managed by the handle's live arena and reset allocation cursors.
*
* @param handle Pointer to the textparser handle.
*/
static void free_arena(struct textparser_handle *handle)
{
arena_free(&handle->arena);
}
typedef struct {
size_t chunk_index;
size_t chunk_used;
size_t chunk_count;
size_t token_count;
uint64_t next_node_id;
} textparser_arena_checkpoint;
/**
* Capture the current arena chunk index and used bytes watermark for speculative rollback.
*
* @param handle Pointer to the textparser handle.
* @return Watermark checkpoint snapshot of current arena state.
*/
static inline textparser_arena_checkpoint textparser_arena_checkpoint_save(const struct textparser_handle *handle)
{
textparser_arena_checkpoint cp;
cp.chunk_index = handle->arena.current_chunk_index;
cp.chunk_used = handle->arena.current_chunk_used;
cp.chunk_count = handle->arena.chunk_count;
cp.token_count = handle->token_count;
cp.next_node_id = handle->next_node_id;
return cp;
}
/**
* Roll back arena memory allocations to a previously saved checkpoint watermark.
*
* @param handle Pointer to the textparser handle.
* @param cp Pointer to the checkpoint watermark to restore.
*/
static inline void textparser_arena_checkpoint_restore(struct textparser_handle *handle, const textparser_arena_checkpoint *cp)
{
handle->arena.current_chunk_index = cp->chunk_index;
if (handle->arena.chunks && cp->chunk_index < handle->arena.chunk_count) {
handle->arena.current_chunk = handle->arena.chunks[cp->chunk_index];
} else {
handle->arena.current_chunk = nullptr;
}
handle->arena.current_chunk_used = cp->chunk_used;
handle->token_count = cp->token_count;
handle->next_node_id = cp->next_node_id;
}
/**
* Attempt to match the start delimiter or initial pattern of a token using fast matchers or regex.
*
* @param handle Pointer to the textparser handle.
* @param token_id Integer token ID to match.
* @param text Pointer to current position in text buffer.
* @param len Length in character code units.
* @param offset Output pointer receiving matched offset relative to pos.
* @param match_len Output pointer receiving matched span length.
* @param only_at_start true if match must be anchored at the current position.
* @return true if start token matched successfully; false otherwise.
*/
static inline bool textparser_match_start_token(
const struct textparser_handle *handle,
int token_id,
const char *text,
size_t len,
size_t *offset,
size_t *match_len,
bool only_at_start,
bool whole_match)
{
const textparser_token *token_def = &handle->language->tokens[token_id];
bool ret;
if (token_def->startRegexFunction != NULL) {
ret = token_def->startRegexFunction(
handle->text_format,
text,
len,
offset,
match_len,
!handle->language->case_sensitivity,
only_at_start
);
} else {
ret = adv_regex_find_pattern_capture_ctx(
handle->regex_ctx,
token_def->start_regex,
(void **)handle->start_regex + token_id,
handle->text_format,
text,
len,
offset,
match_len,
!handle->language->case_sensitivity,
only_at_start,
whole_match,
0, NULL, NULL
);
}
return ret;
}
/**
* Attempt to match the end delimiter or closing pattern of a container token.
*
* @param handle Pointer to the textparser handle.
* @param token_id Integer token ID of the container.
* @param text Pointer to current position in text buffer.
* @param len Length in character code units.
* @param offset Output pointer receiving matched offset relative to pos.
* @param match_len Output pointer receiving matched span length.
* @param only_at_start true if match must be anchored at the current position.
* @return true if end token matched successfully; false otherwise.
*/
static inline bool textparser_match_end_token(
const struct textparser_handle *handle,
int token_id,
const char *text,
size_t len,
size_t *offset,
size_t *match_len,
bool only_at_start)
{
const textparser_token *token_def = &handle->language->tokens[token_id];
bool ret;
if (token_def->endRegexFunction != NULL) {
ret = token_def->endRegexFunction(
handle->text_format,
text,
len,
offset,
match_len,
!handle->language->case_sensitivity,
only_at_start
);
} else {
ret = adv_regex_find_pattern_ctx(
handle->regex_ctx,
token_def->end_regex,
(void **)handle->end_regex + token_id,
handle->text_format,
text,
len,
offset,
match_len,
!handle->language->case_sensitivity,
only_at_start
);
}
return ret;
}
/**
* Allocate a new zero-initialized textparser_token_item node from the handle arena allocator.
*
* @param handle Pointer to the textparser handle.
* @param token_id Token ID assigned to the node.
* @param len Length in character code units spanned by the token.
* @return Pointer to the allocated token item node, or NULL on allocation failure.
*/
static textparser_token_item *textparser_alloc_token(struct textparser_handle *handle, int token_id, size_t len)
{
textparser_token_item *ret = arena_alloc(&handle->arena, sizeof(textparser_token_item));
if (ret == nullptr) {
handle->error = "Can't allocate memory!";
return nullptr;
}
memset(ret, 0, sizeof(textparser_token_item));
ret->id = ++handle->next_node_id;
ret->token_id = token_id;
ret->len = len;
ret->span_len = len;
ret->text_color = TEXTPARSER_NOCOLOR;
ret->text_background = TEXTPARSER_NOCOLOR;