-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathregex-parser.c
More file actions
1905 lines (1688 loc) · 74.9 KB
/
regex-parser.c
File metadata and controls
1905 lines (1688 loc) · 74.9 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
/*
===============================================================================
librex-ast - A PCRE2-Compatible Regex Engine
Author: Mounir IDRASSI <mounir.idrassi@amcrypto.jp>
Date: July 19, 2025
License: MIT
Description:
------------
This file is part of a high-performance, feature-rich, and PCRE2-compatible
regular expression engine written in C. The library implements both a
sophisticated parser and a bytecode execution engine (virtual machine) to
provide a complete compile-and-match solution. It is designed for
portability, performance, and API clarity, with extensive support for
modern regex features including Unicode properties, advanced grouping,
and recursive patterns.
Key Architectural Features:
---------------------------
- Two-Stage Compilation:
1. A recursive descent parser builds a detailed Abstract Syntax Tree (AST)
from the regex pattern.
2. An AST-to-bytecode compiler translates the tree into a linear, compact
instruction set for the VM.
- NFA-based Virtual Machine (VM):
* A custom VM executes the compiled bytecode to perform the match.
* Implements a non-recursive, stack-based backtracking NFA algorithm.
Alternative execution paths (NFA states) are managed on an explicit stack.
* Uses a "visited" set for memoization to prevent redundant work and handle
complex patterns with overlapping subproblems efficiently.
- Pluggable Memory Management:
* Core API supports custom allocators ('malloc', 'realloc', 'free'),
allowing integration into projects with specific memory strategies.
* The parser uses an internal arena allocator for efficient AST node
management during compilation.
- Comprehensive PCRE2 Compatibility:
* Supports a wide array of advanced constructs found in PCRE2 and Perl.
* The implementation is validated by a test suite covering syntax, matching,
edge cases, and error conditions.
- Detailed Error Reporting:
* Provides structured error objects with error codes, messages, and the
exact line/column number of the error in the pattern.
- Unicode-Awareness:
* Full UTF-8 support in both the parser and the matching engine.
* Built-in support for Unicode property matching (\p, \P) using a
partial, internal Unicode character database to generate efficient bitmaps.
Implementation Details:
-----------------------
- Parser:
* Recursive descent with two-phase fixup for resolving forward references
(e.g., '\k<name>' before '(?<name>...)').
* Detailed tracking of parser state, including capture counts, named groups,
and inline flag modifiers.
* Semantic validation, including fixed-width checks for lookbehind assertions.
- AST-to-Bytecode Compiler:
* Translates the AST into a simple and efficient instruction set (e.g.,
CHAR, ANY, SPLIT, JMP, SAVE, CALL).
* Capturing groups are compiled into self-contained, callable subroutines
invoked via dedicated I_CALL and I_RETURN instructions.
- NFA Virtual Machine (VM):
* The core matching logic is a loop processing VM instructions.
* Backtracking is managed by pushing alternative execution paths (threads)
onto a stack.
* Instructions for advanced features like atomic groups ('I_MARK_ATOMIC',
'I_CUT_TO_MARK'), conditionals ('I_GCOND'), and assertions ('I_ACOND', 'I_LBCOND').
- Unicode:
* Safe, single-pass UTF-8 decoding.
* Unicode property matching uses a built-in table of character ranges
to build bitmaps. These bitmaps are allocated in the AST's memory arena
for efficient cleanup.
* Unified character class builder handles standard classes ('[a-z]'),
shorthands ('\d', '\w'), and POSIX classes ('[[:digit:]]') in a
Unicode-aware manner.
- API:
* Clean, two-stage API ('regex_compile', 'regex_match', 'regex_free').
* Opaque 'regex_compiled*' handle encapsulates the compiled pattern.
* Match results are returned in a structured, easy-to-use format.
Supported Regex Constructs:
---------------------------
Basic Elements:
- Literal characters (full Unicode support)
- Character classes '[abc]', '[^abc]', '[a-z]'
- Predefined classes: '\d', '\D', '\w', '\W', '\s', '\S'
- Dot metacharacter '.' (respects single-line mode)
- Anchors: '^', '$', '\A', '\z', '\b', '\B'
Quantifiers:
- Greedy: '*', '+', '?', '{n}', '{n,}', '{n,m}'
- Lazy (Non-greedy): '*?', '+?', '??', '{n,m}?'
- Possessive: '*+', '++', '?+', '{n,m}+'
Groups:
- Capturing groups: '(...)'
- Non-capturing groups: '(?:...)'
- Named groups: '(?<name>...)', '(?'name'...)'
- Atomic groups: '(?>...)'
- Branch-reset groups: '(?|...)'
Assertions:
- Positive lookahead: '(?=...)'
- Negative lookahead: '(?!...)'
- Positive lookbehind: '(?<=...)'
- Negative lookbehind: '(?<!...)'
Backreferences:
- Numbered: '\1', '\2', etc.
- Named: '\k<name>', '\k'name''
Conditionals:
- By group number: '(?(1)yes|no)'
- By group name: '(?(<name>)yes|no)'
- By assertion: '(?(?=...)yes|no)'
Subroutines:
- Full pattern recursion: '(?R)'
- By group number: '(?1)', '(?2)', etc.
- By group name: '(?&name)'
Modifiers & Comments:
- Inline flags: '(?i)', '(?-m)', etc.
- Scoped flags: '(?i:...)'
- Comments: '(?#...)'
Unicode & Escapes:
- UTF-8 input processing and validation.
- Unicode properties: '\p{L}', '\P{Sc}', etc.
- Hex escapes: '\x20', '\x{1F600}'
- Quoted sequences: '\Q...\E'
- Partial POSIX support (common classes like [[:alpha:]], Unicode-aware where database allows).
Current Limitations:
--------------------
- No AST or bytecode optimization passes are currently performed.
- Lookbehind assertions must be fixed-length (variable-length lookbehind is not supported).
- Maximum lookbehind length is 255 characters (PCRE2 compatible).
- The built-in Unicode property support is based on a partial character database and does not cover all scripts or categories.
- Recursion/subroutine depth limited to 32 (MAX_CALL_DEPTH).
- POSIX classes partially supported and Unicode-aware only for covered properties.
- No full grapheme matching or script runs.
- No support for '\g{...}' backreference/subroutine syntax (use '\k<>', '(?n)' instead).
- No support for script runs or grapheme clusters ('\X').
- No support for generic newline sequences ('\R').
- No support for control verbs like '(*SKIP)', '(*FAIL)', '(*ACCEPT)'.
- No support for callouts.
===============================================================================
*/
#ifdef _WIN32
#define _CRT_SECURE_NO_WARNINGS
#define _CRT_NONSTDC_NO_WARNINGS
#include <windows.h>
#endif
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <stdarg.h>
#include "regex-parser.h"
#include "regex-unicode.h"
#include "regex-internals.h"
// ----------------------------------------------------------------------------
// 1. Allocator Implementation
// ----------------------------------------------------------------------------
// Default allocator implementation using standard library functions
static void* default_malloc(size_t size, void* user_data) {
(void)user_data; // Unused
return malloc(size);
}
static void default_free(void* ptr, void* user_data) {
(void)user_data; // Unused
free(ptr);
}
static void* default_realloc(void* ptr, size_t new_size, void* user_data) {
(void)user_data; // Unused
return realloc(ptr, new_size);
}
// Global static instance of the default allocator for convenience.
static const regex_allocator default_allocator = {
.malloc_func = default_malloc,
.free_func = default_free,
.realloc_func = default_realloc,
.user_data = NULL
};
// ----------------------------------------------------------------------------
// 2. Arena Allocation
// ----------------------------------------------------------------------------
void *arena_alloc(AstArena *arena, size_t size) {
if (!arena->blocks || arena->blocks->used + size > arena->blocks->cap) {
size_t cap = size > 64*1024 ? size : 64*1024;
Block *block = arena->allocator.malloc_func(sizeof(Block), arena->allocator.user_data);
if (!block) return NULL;
block->data = arena->allocator.malloc_func(cap, arena->allocator.user_data);
if (!block->data) {
arena->allocator.free_func(block, arena->allocator.user_data);
return NULL;
}
block->used = 0;
block->cap = cap;
block->next = arena->blocks;
arena->blocks = block;
arena->total_allocated += cap;
}
void *ptr = (char*)arena->blocks->data + arena->blocks->used;
arena->blocks->used += size;
return ptr;
}
static void arena_free(AstArena *arena) {
Block *block = arena->blocks;
while (block) {
Block *next = block->next;
arena->allocator.free_func(block->data, arena->allocator.user_data);
arena->allocator.free_func(block, arena->allocator.user_data);
block = next;
}
arena->blocks = NULL;
arena->total_allocated = 0;
}
// ----------------------------------------------------------------------------
// 3. Error Handling
// ----------------------------------------------------------------------------
static const char* error_messages[] = {
[REGEX_OK] = "Success",
[REGEX_ERR_MEMORY] = "Memory allocation failed",
[REGEX_ERR_INVALID_SYNTAX] = "Invalid regex syntax",
[REGEX_ERR_INVALID_UTF8] = "Invalid UTF-8 sequence",
[REGEX_ERR_INVALID_ESCAPE] = "Invalid escape sequence",
[REGEX_ERR_INVALID_CLASS] = "Invalid character class syntax",
[REGEX_ERR_INVALID_QUANT] = "Invalid quantifier",
[REGEX_ERR_INVALID_GROUP] = "Invalid group syntax",
[REGEX_ERR_INVALID_BACKREF] = "Invalid backreference",
[REGEX_ERR_INVALID_PROP] = "Unknown Unicode property",
[REGEX_ERR_UNMATCHED_PAREN] = "Unmatched parenthesis",
[REGEX_ERR_INVALID_RANGE] = "Invalid range in character class",
[REGEX_ERR_LOOKBEHIND_VAR] = "Lookbehind assertion is not fixed-length",
[REGEX_ERR_LOOKBEHIND_LONG] = "Lookbehind assertion is too long",
[REGEX_ERR_DUPLICATE_NAME] = "Duplicate capture group name",
[REGEX_ERR_UNDEFINED_GROUP] = "Reference to undefined group",
[REGEX_ERR_INVALID_CONDITION] = "Invalid conditional pattern",
};
const char* regex_error_message(int error_code) {
size_t num_errors = sizeof(error_messages) / sizeof(error_messages[0]);
if (error_code < 0 || (size_t)error_code >= num_errors) {
return "Unknown error";
}
return error_messages[error_code];
}
// ----------------------------------------------------------------------------
// 4. Updated Parser State and Error Handling
// ----------------------------------------------------------------------------
// Fixup structure for deferred validation
typedef struct {
RegexNode *node;
char *name;
} Fixup;
typedef struct {
char* name;
int index;
} NamedGroup;
// Parser state
typedef struct {
const char *pattern;
int pos;
int capture_count;
regex_err error;
bool has_error;
int line_number;
int column_start;
NamedGroup *named_groups;
int named_group_count;
int named_group_capacity;
uint32_t flags;
AstArena *arena;
Fixup *fixups;
int fixup_count;
int fixup_capacity;
unsigned compile_flags;
bool in_conditional;
} ParserState;
// Wrapper for strdup using the provided allocator
static char* pstrdup(ParserState* state, const char* s) {
if (!s) return NULL;
size_t len = strlen(s) + 1;
char* new_str = state->arena->allocator.malloc_func(len, state->arena->allocator.user_data);
if (!new_str) return NULL;
memcpy(new_str, s, len);
return new_str;
}
// Updated set_error to populate the structured error object
void set_error(ParserState *state, int error_code, const char *msg_override) {
if (state->has_error) return;
int line = 1;
int col = 1;
for (int i = 0; i < state->pos; i++) {
if (state->pattern[i] == '\n') {
line++;
col = 1;
} else {
col++;
}
}
state->error.code = error_code;
state->error.pos = state->pos;
state->error.line = line;
state->error.col = col;
state->error.msg = msg_override ? msg_override : regex_error_message(error_code);
state->has_error = true;
}
// ----------------------------------------------------------------------------
// 5. UTF-8 Decoder and Unicode Support
// ----------------------------------------------------------------------------
static size_t utf8_decode(const char *str, uint32_t *codepoint) {
const unsigned char *s = (const unsigned char*)str;
if (s[0] < 0x80) {
*codepoint = s[0];
return 1;
} else if ((s[0] & 0xE0) == 0xC0) {
if ((s[1] & 0xC0) != 0x80) return 0;
*codepoint = ((s[0] & 0x1F) << 6) | (s[1] & 0x3F);
return 2;
} else if ((s[0] & 0xF0) == 0xE0) {
if ((s[1] & 0xC0) != 0x80 || (s[2] & 0xC0) != 0x80) return 0;
*codepoint = ((s[0] & 0x0F) << 12) | ((s[1] & 0x3F) << 6) | (s[2] & 0x3F);
return 3;
} else if ((s[0] & 0xF8) == 0xF0) {
if ((s[1] & 0xC0) != 0x80 || (s[2] & 0xC0) != 0x80 || (s[3] & 0xC0) != 0x80) return 0;
*codepoint = ((s[0] & 0x07) << 18) | ((s[1] & 0x3F) << 12) | ((s[2] & 0x3F) << 6) | (s[3] & 0x3F);
return 4;
}
return 0;
}
static char *ascii_lower(const char *str, ParserState* state) {
size_t len = strlen(str);
char *result = state->arena->allocator.malloc_func(len + 1, state->arena->allocator.user_data);
if (!result) {
set_error(state, REGEX_ERR_MEMORY, NULL);
return NULL;
}
for (size_t i = 0; i < len; i++) {
result[i] = (char) tolower(str[i]);
}
result[len] = '\0';
return result;
}
// ----------------------------------------------------------------------------
// 6. Unicode Properties Support
// ----------------------------------------------------------------------------
// Enhanced property existence check
static bool unicode_property_exists(const char* name) {
if (!name) return false;
// Check standard Unicode categories
const char* standard_props[] = {
"l", "lu", "ll", "lt", "lm", "lo", // Letters
"m", "mn", "mc", "me", // Marks
"n", "nd", "nl", "no", // Numbers
"p", "pc", "pd", "ps", "pe", "pi", "pf", "po", // Punctuation
"s", "sm", "sc", "sk", "so", // Symbols
"z", "zs", "zl", "zp", // Separators
"c", "cc", "cf", "cs", "co", "cn", // Other
NULL
};
for (int i = 0; standard_props[i]; i++) {
if (strcmp(name, standard_props[i]) == 0) {
return true;
}
}
// Check common aliases
const char* aliases[] = {
"alpha", "alnum", "digit", "space", "upper", "lower", "punct", "word",
NULL
};
for (int i = 0; aliases[i]; i++) {
if (strcmp(name, aliases[i]) == 0) {
return true;
}
}
return false;
}
// ----------------------------------------------------------------------------
// 7. Forward declarations
// ----------------------------------------------------------------------------
RegexNode* parse_regex(ParserState *state);
RegexNode* parse_term(ParserState *state);
RegexNode* parse_factor(ParserState *state);
RegexNode* parse_atom(ParserState *state);
void set_error(ParserState *state, int error_code, const char *msg_override);
int compute_width(RegexNode *node, int *min, int *max);
// ----------------------------------------------------------------------------
// 8. Helper functions for creating AST nodes
// ----------------------------------------------------------------------------
RegexNode* create_node(RegexNodeType type, ParserState *state) {
RegexNode *node = (RegexNode*)arena_alloc(state->arena, sizeof(RegexNode));
if (!node) {
set_error(state, REGEX_ERR_MEMORY, NULL);
return NULL;
}
memset(node, 0, sizeof(RegexNode));
node->type = type;
node->token_start = state ? state->column_start : -1;
node->token_end = state ? state->pos : -1;
return node;
}
RegexNode* create_char_node(uint32_t codepoint, ParserState *state) {
RegexNode *node = create_node(REGEX_NODE_CHAR, state);
if (!node) return NULL;
node->data.codepoint = codepoint;
return node;
}
RegexNode* create_concat_node(RegexNode *left, RegexNode *right, ParserState *state) {
if (!left && !right) {
RegexNode *node = create_node(REGEX_NODE_CONCAT, state);
if (!node) return NULL;
node->data.children.left = NULL;
node->data.children.right = NULL;
return node;
}
if (!left) return right;
if (!right) return left;
RegexNode *node = create_node(REGEX_NODE_CONCAT, state);
if (!node) return NULL;
node->data.children.left = left;
node->data.children.right = right;
return node;
}
RegexNode* create_alternation_node(RegexNode *left, RegexNode *right, ParserState *state) {
RegexNode *node = create_node(REGEX_NODE_ALTERNATION, state);
if (!node) return NULL;
node->data.children.left = left;
node->data.children.right = right;
return node;
}
RegexNode* create_quantifier_node(RegexNode *child, int min, int max, QuantifierType type, ParserState *state) {
RegexNode *node = create_node(REGEX_NODE_QUANTIFIER, state);
if (!node) return NULL;
node->data.quantifier.child = child;
node->data.quantifier.min = min;
node->data.quantifier.max = max;
node->data.quantifier.quant_type = type;
return node;
}
RegexNode* create_group_node(RegexNode *child, int capture_index, char *name, bool is_atomic, ParserState *state) {
RegexNode *node = create_node(REGEX_NODE_GROUP, state);
if (!node) return NULL;
node->data.group.child = child;
node->data.group.capture_index = capture_index;
node->data.group.name = name;
node->data.group.is_atomic = is_atomic;
node->data.group.enter_flags = 0;
node->data.group.exit_flags = 0;
return node;
}
RegexNode* create_char_class_node(char *set, bool negated, bool is_posix, ParserState *state) {
RegexNode *node = create_node(REGEX_NODE_CHAR_CLASS, state);
if (!node) return NULL;
node->data.char_class.set = set;
node->data.char_class.negated = negated;
node->data.char_class.is_posix = is_posix;
return node;
}
RegexNode* create_anchor_node(char type, ParserState *state) {
RegexNode *node = create_node(REGEX_NODE_ANCHOR, state);
if (!node) return NULL;
node->data.anchor_type = type;
return node;
}
RegexNode* create_dot_node(ParserState *state) {
return create_node(REGEX_NODE_DOT, state);
}
RegexNode* create_backref_node(int index, char *name, ParserState *state) {
RegexNode *node = create_node(REGEX_NODE_BACKREF, state);
if (!node) return NULL;
node->data.backref.ref_index = index;
node->data.backref.ref_name = name;
return node;
}
RegexNode* create_assertion_node(RegexNode *child, AssertionType type, ParserState *state) {
RegexNode *node = create_node(REGEX_NODE_ASSERTION, state);
if (!node) return NULL;
node->data.assertion.child = child;
node->data.assertion.assert_type = type;
return node;
}
RegexNode* create_uni_prop_node(bool negated, char *prop_name, ParserState *state) {
RegexNode *node = create_node(REGEX_NODE_UNI_PROP, state);
if (!node) return NULL;
node->data.uni_prop.negated = negated;
node->data.uni_prop.prop_name = prop_name;
return node;
}
RegexNode* create_conditional_node(Condition cond, RegexNode *if_true, RegexNode *if_false, ParserState *state) {
RegexNode *node = create_node(REGEX_NODE_CONDITIONAL, state);
if (!node) return NULL;
node->data.conditional.cond = cond;
node->data.conditional.if_true = if_true;
node->data.conditional.if_false = if_false;
return node;
}
RegexNode* create_subroutine_node(bool is_recursion, int target_index, char *target_name, ParserState *state) {
RegexNode *node = create_node(REGEX_NODE_SUBROUTINE, state);
if (!node) return NULL;
node->data.subroutine.is_recursion = is_recursion;
node->data.subroutine.target_index = target_index;
node->data.subroutine.target_name = target_name;
return node;
}
// ----------------------------------------------------------------------------
// 9. Fixup and Named Group Management
// ----------------------------------------------------------------------------
static void add_fixup(ParserState *state, RegexNode *node, char *name) {
if (state->fixup_count >= state->fixup_capacity) {
state->fixup_capacity = state->fixup_capacity > 0 ? state->fixup_capacity * 2 : 8;
Fixup *new_fixups = state->arena->allocator.realloc_func(
state->fixups, state->fixup_capacity * sizeof(Fixup), state->arena->allocator.user_data);
if (!new_fixups) {
set_error(state, REGEX_ERR_MEMORY, NULL);
return;
}
state->fixups = new_fixups;
}
state->fixups[state->fixup_count].node = node;
state->fixups[state->fixup_count].name = pstrdup(state, name);
state->fixup_count++;
}
static int find_named_group_index(ParserState *state, const char *name) {
for (int i = 0; i < state->named_group_count; i++) {
if (strcmp(state->named_groups[i].name, name) == 0) {
return state->named_groups[i].index;
}
}
return -1;
}
static void process_fixups(ParserState *state) {
for (int i = 0; i < state->fixup_count; i++) {
Fixup *fixup = &state->fixups[i];
int group_index = find_named_group_index(state, fixup->name);
if (group_index != -1) {
if (fixup->node->type == REGEX_NODE_BACKREF) {
fixup->node->data.backref.ref_index = group_index;
} else if (fixup->node->type == REGEX_NODE_SUBROUTINE) {
fixup->node->data.subroutine.target_index = group_index;
}
} else {
if (fixup->node->type == REGEX_NODE_BACKREF) {
set_error(state, REGEX_ERR_UNDEFINED_GROUP, "Backreference to undefined named group");
} else {
set_error(state, REGEX_ERR_UNDEFINED_GROUP, "Subroutine call to undefined named group");
}
return;
}
}
}
// ----------------------------------------------------------------------------
// 10. Named group management
// ----------------------------------------------------------------------------
static bool add_named_group(ParserState *state, const char *name, int capture_index) {
for (int i = 0; i < state->named_group_count; i++) {
if (strcmp(state->named_groups[i].name, name) == 0) {
set_error(state, REGEX_ERR_DUPLICATE_NAME, NULL);
return false;
}
}
if (state->named_group_count >= state->named_group_capacity) {
state->named_group_capacity = state->named_group_capacity > 0 ? state->named_group_capacity * 2 : 8;
NamedGroup *new_groups = state->arena->allocator.realloc_func(
state->named_groups, state->named_group_capacity * sizeof(NamedGroup), state->arena->allocator.user_data);
if (!new_groups) {
set_error(state, REGEX_ERR_MEMORY, NULL);
return false;
}
state->named_groups = new_groups;
}
state->named_groups[state->named_group_count].name = pstrdup(state, name);
if (!state->named_groups[state->named_group_count].name) {
set_error(state, REGEX_ERR_MEMORY, NULL);
return false;
}
state->named_groups[state->named_group_count].index = capture_index;
state->named_group_count++;
return true;
}
// ----------------------------------------------------------------------------
// 11. Parser utilities
// ----------------------------------------------------------------------------
static uint32_t peek_codepoint(ParserState *state) {
if (state->pattern[state->pos] == '\0') return 0;
uint32_t codepoint;
size_t len = utf8_decode(&state->pattern[state->pos], &codepoint);
if (len == 0) {
set_error(state, REGEX_ERR_INVALID_UTF8, NULL);
return 0;
}
return codepoint;
}
static uint32_t next_codepoint(ParserState *state) {
state->column_start = state->pos;
if (state->pattern[state->pos] == '\0') return 0;
uint32_t codepoint;
size_t len = utf8_decode(&state->pattern[state->pos], &codepoint);
if (len == 0) {
set_error(state, REGEX_ERR_INVALID_UTF8, NULL);
return 0;
}
state->pos += (int) len;
return codepoint;
}
static bool match_codepoint(ParserState *state, uint32_t expected) {
if (peek_codepoint(state) == expected) {
next_codepoint(state);
return true;
}
return false;
}
static bool match_sequence(ParserState *state, const char *seq) {
if (strncmp(&state->pattern[state->pos], seq, strlen(seq)) == 0) {
state->pos += (int) strlen(seq);
return true;
}
return false;
}
static bool parse_number(ParserState *state, int *out_value, int max_digits) {
int start_pos = state->pos;
char *end;
long val = strtol(&state->pattern[state->pos], &end, 10);
if (end == &state->pattern[state->pos] || (max_digits > 0 && (end - &state->pattern[start_pos] > max_digits))) {
return false;
}
*out_value = (int)val;
state->pos = (int)(end - state->pattern);
return true;
}
static char* parse_plain_name(ParserState *state) {
int start = state->pos;
while (true) {
uint32_t cp = peek_codepoint(state);
if ((cp >= 'A' && cp <= 'Z') || (cp >= 'a' && cp <= 'z') || (cp >= '0' && cp <= '9') || cp == '_') {
next_codepoint(state);
} else {
break;
}
}
int end = state->pos;
if (end == start) {
set_error(state, REGEX_ERR_INVALID_CONDITION, "Missing name in subroutine call");
return NULL;
}
int len = end - start;
char *name = malloc(len + 1);
if (!name) {
set_error(state, REGEX_ERR_MEMORY, NULL);
return NULL;
}
memcpy(name, &state->pattern[start], len);
name[len] = '\0';
return name;
}
static int hexval(uint32_t c) {
if (c >= '0' && c <= '9') return c - '0';
if (c >= 'a' && c <= 'f') return c - 'a' + 10;
if (c >= 'A' && c <= 'F') return c - 'A' + 10;
return -1;
}
static bool is_quantifier(uint32_t cp) {
return cp == '*' || cp == '+' || cp == '?' || cp == '{';
}
// ----------------------------------------------------------------------------
// 12. Width analysis for lookbehind validation
// ----------------------------------------------------------------------------
int compute_width(RegexNode *node, int *min, int *max) {
if (!node) {
*min = *max = 0;
return 0;
}
switch (node->type) {
case REGEX_NODE_CHAR:
case REGEX_NODE_DOT:
case REGEX_NODE_CHAR_CLASS:
case REGEX_NODE_UNI_PROP:
*min = *max = 1;
return 0;
case REGEX_NODE_ANCHOR:
case REGEX_NODE_BACKREF: // Can have variable width
case REGEX_NODE_SUBROUTINE:
*min = 0; *max = -1; // Unbounded
return 0;
case REGEX_NODE_CONCAT: {
int lmin, lmax, rmin, rmax;
compute_width(node->data.children.left, &lmin, &lmax);
compute_width(node->data.children.right, &rmin, &rmax);
*min = lmin + rmin;
*max = (lmax == -1 || rmax == -1) ? -1 : lmax + rmax;
return 0;
}
case REGEX_NODE_ALTERNATION: {
int lmin, lmax, rmin, rmax;
compute_width(node->data.children.left, &lmin, &lmax);
compute_width(node->data.children.right, &rmin, &rmax);
*min = (lmin < rmin) ? lmin : rmin;
*max = (lmax == -1 || rmax == -1) ? -1 : ((lmax > rmax) ? lmax : rmax);
return 0;
}
case REGEX_NODE_QUANTIFIER: {
int cmin, cmax;
compute_width(node->data.quantifier.child, &cmin, &cmax);
*min = cmin * node->data.quantifier.min;
*max = (node->data.quantifier.max == -1 || cmax == -1) ? -1 : cmax * node->data.quantifier.max;
return 0;
}
case REGEX_NODE_GROUP:
case REGEX_NODE_BRESET_GROUP:
return compute_width(node->data.group.child, min, max);
case REGEX_NODE_CONDITIONAL: {
int t_min, t_max, f_min = 0, f_max = 0;
compute_width(node->data.conditional.if_true, &t_min, &t_max);
if (node->data.conditional.if_false) {
compute_width(node->data.conditional.if_false, &f_min, &f_max);
}
*min = (t_min < f_min) ? t_min : f_min;
*max = (t_max == -1 || f_max == -1) ? -1 : ((t_max > f_max) ? t_max : f_max);
return 0;
}
default: // Assertions, comments are 0-width
*min = *max = 0;
return 0;
}
}
static void check_lookbehind(RegexNode *node, ParserState *state) {
int min, max;
compute_width(node, &min, &max);
/* PCRE2 allows different fixed‑length alternatives; */
/* it disallows only unbounded or too‑long paths. */
if (max == -1) {
set_error(state, REGEX_ERR_LOOKBEHIND_VAR,
"Lookbehind assertion is not fixed length");
}
if (max > 255) { // same limit as PCRE
set_error(state, REGEX_ERR_LOOKBEHIND_LONG,
"Lookbehind assertion is too long");
}
}
// ----------------------------------------------------------------------------
// 13. Flag parsing for inline modifiers
// ----------------------------------------------------------------------------
static void scan_flag_string(const char *str, int *pos, uint32_t *flags) {
bool negate = false;
while (str[*pos] && str[*pos] != ')' && str[*pos] != ':') {
char c = str[*pos];
(*pos)++;
if (c == '-') {
negate = true;
continue;
}
uint32_t flag = 0;
switch (c) {
case 'i': flag = REG_IGNORECASE; break;
case 'm': flag = REG_MULTILINE; break;
case 's': flag = REG_SINGLELINE; break;
case 'x': flag = REG_EXTENDED; break;
case 'U': flag = REG_UNGREEDY; break;
default: continue;
}
if (negate) {
*flags &= ~flag;
} else {
*flags |= flag;
}
}
}
// ----------------------------------------------------------------------------
// 14. Parsing functions
// ----------------------------------------------------------------------------
char* parse_char_class_content(ParserState *state, bool *is_posix) {
*is_posix = false;
int start_pos = state->pos;
int nesting_level = 1;
bool at_start = true;
if (strncmp(&state->pattern[state->pos], "[[:", 3) == 0) {
*is_posix = true;
}
while (state->pattern[state->pos] != '\0') {
if (state->pattern[state->pos] == '\n') {
set_error(state, REGEX_ERR_INVALID_SYNTAX, "Invalid newline in character class");
return NULL;
}
if (state->pattern[state->pos] == '[' && !*is_posix) {
if (strncmp(&state->pattern[state->pos], "[[:", 3) != 0) {
nesting_level++;
}
} else if (state->pattern[state->pos] == ']') {
if (at_start) {
// ']' is a literal if it's the first character
} else {
nesting_level--;
if (nesting_level == 0) break;
}
} else if (state->pattern[state->pos] == '\\') {
state->pos++;
if (state->pattern[state->pos] != '\0') {
state->pos++;
}
at_start = false;
continue;
}
at_start = false;
state->pos++;
}
if (nesting_level != 0) {
set_error(state, REGEX_ERR_INVALID_SYNTAX, "Unmatched '[' in character class");
return NULL;
}
int len = state->pos - start_pos;
char *content = malloc(len + 1);
if (!content) {
set_error(state, REGEX_ERR_MEMORY, NULL);
return NULL;
}
memcpy(content, &state->pattern[start_pos], len);
content[len] = '\0';
state->pos++; // consume closing ']'
return content;
}
char* parse_group_name(ParserState *state) {
uint32_t first = peek_codepoint(state);
if (!(first >= 'A' && first <= 'Z') && !(first >= 'a' && first <= 'z') && first != '_') {
set_error(state, REGEX_ERR_INVALID_SYNTAX, "Invalid group name: must start with letter or underscore");
return NULL;
}
int start = state->pos;
next_codepoint(state);
while (true) {
uint32_t cp = peek_codepoint(state);
if ((cp >= 'A' && cp <= 'Z') || (cp >= 'a' && cp <= 'z') || (cp >= '0' && cp <= '9') || cp == '_') {
next_codepoint(state);
} else {
break;
}
}
if (!match_codepoint(state, '>')) {
set_error(state, REGEX_ERR_UNMATCHED_PAREN, "Unmatched '<' in named group");
return NULL;
}
int end = state->pos - 1; // back up over '>'
int len = end - start;
char *name = malloc(len + 1);
if (!name) {
set_error(state, REGEX_ERR_MEMORY, NULL);
return NULL;
}
memcpy(name, &state->pattern[start], len);
name[len] = '\0';
return name;
}
static Condition parse_condition(ParserState *state) {
Condition cond = {0};
/* Look-ahead / look-behind assertions start with '?' here because
the opening '(' has already been consumed. */
if (peek_codepoint(state) == '?') {
/* Rewind one byte to give parse_atom() the '(' it expects. */
state->pos--; /* now on '(' */
cond.data.assertion = parse_atom(state);
if (cond.data.assertion && cond.data.assertion->type == REGEX_NODE_ASSERTION) {
cond.type = COND_ASSERTION;
return cond;
}
set_error(state, REGEX_ERR_INVALID_CONDITION, "Condition is not a valid assertion");
return cond;
}
// This handles '(?(?<=...) ...)'
if (peek_codepoint(state) == '(') {
cond.type = COND_ASSERTION;
cond.data.assertion = parse_atom(state);
if (state->has_error || !cond.data.assertion || cond.data.assertion->type != REGEX_NODE_ASSERTION) {
set_error(state, REGEX_ERR_INVALID_CONDITION, "Condition is not a valid assertion");
cond.type = COND_INVALID;
}
} else if (peek_codepoint(state) == '<' || peek_codepoint(state) == '\'') {
cond.type = COND_NAMED;
char opener = (char) next_codepoint(state);
char closer = (opener == '<') ? '>' : '\'';
int start = state->pos;
while (peek_codepoint(state) != (uint32_t)closer && peek_codepoint(state) != 0) {
next_codepoint(state);
}
if (!match_codepoint(state, closer)) {
set_error(state, REGEX_ERR_UNMATCHED_PAREN, "Unclosed named condition");
cond.type = COND_INVALID;
return cond;
}
int len = state->pos - start - 1;
cond.data.group_name = malloc(len + 1);
if (!cond.data.group_name) {
set_error(state, REGEX_ERR_MEMORY, NULL);
cond.type = COND_INVALID;
return cond;