-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNAVFoundation.RegexLexerHelpers.axi
More file actions
3593 lines (3107 loc) · 134 KB
/
NAVFoundation.RegexLexerHelpers.axi
File metadata and controls
3593 lines (3107 loc) · 134 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
PROGRAM_NAME='NAVFoundation.RegexLexerHelpers'
/*
_ _ _ ___ __
| \ | | ___ _ __ __ _ __ _| |_ ___ / \ \ / /
| \| |/ _ \| '__/ _` |/ _` | __/ _ \ / _ \ \ / /
| |\ | (_) | | | (_| | (_| | || __// ___ \ V /
|_| \_|\___/|_| \__, |\__,_|\__\___/_/ \_\_/
|___/
MIT License
Copyright (c) 2010-2026 Norgate AV
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
*/
/**
* Regex Lexer Helper Functions
*
* Contains utility functions for the Lexer phase of regex compilation.
* These functions handle:
* - Pattern cursor navigation
* - Character validation
* - Group name validation
* - Quantifier validation
* - Token type name lookup
*/
#IF_NOT_DEFINED __NAV_FOUNDATION_REGEX_LEXER_HELPERS__
#DEFINE __NAV_FOUNDATION_REGEX_LEXER_HELPERS__ 'NAVFoundation.RegexLexerHelpers'
#include 'NAVFoundation.Core.h.axi'
#include 'NAVFoundation.StringUtils.axi'
#include 'NAVFoundation.ErrorLogUtils.axi'
#include 'NAVFoundation.RegexLexer.h.axi'
#include 'NAVFoundation.Regex.h.axi' // For shared constants: MAX_REGEX_CHAR_RANGES, MAX_REGEX_GROUP_NAME_LENGTH
// ============================================================================
// PATTERN NAVIGATION
// ============================================================================
/**
* @function NAVRegexLexerHasMoreChars
* @private
* @description Check if there are more characters to process in the pattern.
*
* @param {_NAVRegexLexer} lexer - The lexer structure
*
* @returns {char} True (1) if more characters exist, False (0) otherwise
*/
define_function char NAVRegexLexerHasMoreChars(_NAVRegexLexer lexer) {
return lexer.pattern.cursor < lexer.pattern.length
}
/**
* @function NAVRegexLexerCanReadCurrentChar
* @private
* @description Check if the current cursor position is valid for reading.
*
* In NetLinx's 1-based indexing, cursor positions 1 through length are valid.
* This includes the last character at position length.
*
* @param {_NAVRegexLexer} lexer - The lexer structure
*
* @returns {char} True (1) if current position can be read, False (0) otherwise
*/
define_function char NAVRegexLexerCanReadCurrentChar(_NAVRegexLexer lexer) {
return lexer.pattern.cursor <= lexer.pattern.length
}
/**
* @function NAVRegexLexerCursorIsOutOfBounds
* @private
* @description Check if the pattern cursor is out of bounds.
*
* @param {_NAVRegexLexer} lexer - The lexer structure
*
* @returns {char} True (1) if cursor is invalid (<= 0 or > length), False (0) otherwise
*/
define_function char NAVRegexLexerCursorIsOutOfBounds(_NAVRegexLexer lexer) {
return lexer.pattern.cursor <= 0 || lexer.pattern.cursor > lexer.pattern.length
}
/**
* @function NAVRegexLexerAdvanceCursor
* @private
* @description Advance the pattern cursor by one position.
*
* @param {_NAVRegexLexer} lexer - The lexer structure
*
* @returns {char} True (1) if successful, False (0) if cursor goes out of bounds
*/
define_function char NAVRegexLexerAdvanceCursor(_NAVRegexLexer lexer) {
return NAVRegexLexerAdvanceCursorBy(lexer, 1)
}
/**
* @function NAVRegexLexerAdvanceCursorBy
* @private
* @description Advance the pattern cursor by a specified number of positions.
*
* This is useful when you need to skip over multiple characters at once,
* such as when parsing multi-character sequences like '(?:' or '(?P<'.
*
* @param {_NAVRegexLexer} lexer - The lexer structure
* @param {integer} count - Number of positions to advance
*
* @returns {char} True (1) if successful, False (0) if cursor goes out of bounds
*/
define_function char NAVRegexLexerAdvanceCursorBy(_NAVRegexLexer lexer, integer count) {
// Validate count
if (count <= 0) {
NAVLibraryFunctionErrorLog(NAV_LOG_LEVEL_ERROR,
__NAV_FOUNDATION_REGEX_LEXER_HELPERS__,
'NAVRegexLexerAdvanceCursorBy',
"'Invalid count: ', itoa(count), ' (must be > 0)'")
return false
}
lexer.pattern.cursor = lexer.pattern.cursor + count
// Check if final position would be out of bounds
if (NAVRegexLexerCursorIsOutOfBounds(lexer)) {
NAVLibraryFunctionErrorLog(NAV_LOG_LEVEL_ERROR,
__NAV_FOUNDATION_REGEX_LEXER_HELPERS__,
'NAVRegexLexerAdvanceCursorBy',
"'Pattern cursor out of bounds: ', itoa(lexer.pattern.cursor), ' (tried to advance by ', itoa(count), ')'")
return false
}
return true
}
/**
* @function NAVRegexLexerBacktrackCursor
* @private
* @description Backtrack the pattern cursor by one position.
*
* @param {_NAVRegexLexer} lexer - The lexer structure
*
* @returns {char} True (1) if successful, False (0) if cursor goes out of bounds
*/
define_function char NAVRegexLexerBacktrackCursor(_NAVRegexLexer lexer) {
return NAVRegexLexerBacktrackCursorBy(lexer, 1)
}
/**
* @function NAVRegexLexerBacktrackCursorBy
* @private
* @description Backtrack the pattern cursor by a specified number of positions.
*
* This is useful when you need to move the cursor back multiple characters,
* such as when re-evaluating previously read characters.
*
* @param {_NAVRegexLexer} lexer - The lexer structure
* @param {integer} count - Number of positions to backtrack
*
* @returns {char} True (1) if successful, False (0) if cursor goes out of bounds
*/
define_function char NAVRegexLexerBacktrackCursorBy(_NAVRegexLexer lexer, integer count) {
// Validate count
if (count <= 0) {
NAVLibraryFunctionErrorLog(NAV_LOG_LEVEL_ERROR,
__NAV_FOUNDATION_REGEX_LEXER_HELPERS__,
'NAVRegexLexerBacktrackCursorBy',
"'Invalid count: ', itoa(count), ' (must be > 0)'")
return false
}
lexer.pattern.cursor = lexer.pattern.cursor - count
// Check if final position would be out of bounds
if (NAVRegexLexerCursorIsOutOfBounds(lexer)) {
NAVLibraryFunctionErrorLog(NAV_LOG_LEVEL_ERROR,
__NAV_FOUNDATION_REGEX_LEXER_HELPERS__,
'NAVRegexLexerBacktrackCursorBy',
"'Pattern cursor out of bounds: ', itoa(lexer.pattern.cursor), ' (tried to backtrack by ', itoa(count), ')'")
return false
}
return true
}
/**
* @function NAVRegexLexerGetCurrentChar
* @private
* @description Get the character at the current cursor position.
*
* Returns the character that the cursor is currently pointing to
* in the pattern string.
*
* @param {_NAVRegexLexer} lexer - The lexer structure
*
* @returns {char} The character at the cursor position, or 0 if cursor is out of bounds
*/
define_function char NAVRegexLexerGetCurrentChar(_NAVRegexLexer lexer) {
if (NAVRegexLexerCursorIsOutOfBounds(lexer)) {
return 0
}
return NAVCharCodeAt(lexer.pattern.value, lexer.pattern.cursor)
}
// ============================================================================
// CHARACTER VALIDATION
// ============================================================================
/**
* @function NAVRegexLexerIsValidEscapeChar
* @private
* @description Check if a character is a valid escape sequence.
*
* Validates both:
* - Special character classes: \d, \w, \s, etc.
* - Metacharacters that can be escaped: \., \*, \+, etc.
*
* @param {char} c - The character after the backslash
*
* @returns {char} True (1) if valid escape sequence, False (0) otherwise
*/
define_function char NAVRegexLexerIsValidEscapeChar(char c) {
// Check if this is a valid escape character
// Letters that are valid escape sequences
switch (c) {
case 'b': // Word boundary
case 'B': // Not word boundary
case 'd': // Digit
case 'D': // Not digit
case 'w': // Word character
case 'W': // Not word character
case 's': // Whitespace
case 'S': // Not whitespace
case 'x': // Hex
case 'n': // Newline
case 'r': // Return
case 't': // Tab
case 'f': // Form feed
case 'v': // Vertical tab
case 'a': // Bell
case 'e': // Escape
case 'k': // Named backreference
case '1': // Numbered backreferences
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
case '8':
case '9':
case 'A': // String start anchor
case 'Z': // String end anchor (before final newline)
case 'z': // String end anchor (absolute)
case '0': { // Octal escape
return true
}
}
// Special characters that can be escaped (literal matching)
// These include regex metacharacters: . * + ? ^ $ { } [ ] ( ) | \
switch (c) {
case '.':
case '*':
case '+':
case '?':
case '^':
case '$':
case '{':
case '}':
case '[':
case ']':
case '(':
case ')':
case '|':
case '\':
case '/': { // Forward slash for delimiter
return true
}
}
// If we get here, it's not a valid escape sequence
return false
}
// ============================================================================
// GROUP NAME VALIDATION
// ============================================================================
/**
* @function NAVRegexLexerIsValidGroupName
* @private
* @description Validate a group name according to regex naming rules.
*
* Rules:
* - Must start with letter or underscore
* - Can contain letters, digits, or underscores
* - Cannot be empty
*
* @param {char[]} name - The group name to validate
*
* @returns {char} True (1) if valid, False (0) otherwise
*/
define_function char NAVRegexLexerIsValidGroupName(char name[]) {
stack_var integer length
stack_var integer x
stack_var char c
length = length_array(name)
if (length == 0) {
return false
}
// First character must be a letter or underscore
c = NAVCharCodeAt(name, 1)
if (!((c >= 'a' && c <= 'z') ||
(c >= 'A' && c <= 'Z') ||
c == '_')) {
return false
}
// Remaining characters can be letters, digits, or underscores
for (x = 2; x <= length; x++) {
c = NAVCharCodeAt(name, x)
if (!((c >= 'a' && c <= 'z') ||
(c >= 'A' && c <= 'Z') ||
(c >= '0' && c <= '9') ||
c == '_')) {
return false
}
}
return true
}
/**
* @function NAVRegexLexerIsGroupNameUnique
* @private
* @description Check if a group name is unique within the pattern.
*
* @param {_NAVRegexLexer} lexer - The lexer structure containing existing groups
* @param {char[]} name - The group name to check
*
* @returns {char} True (1) if unique, False (0) if duplicate found
*/
define_function char NAVRegexLexerIsGroupNameUnique(_NAVRegexLexer lexer, char name[]) {
stack_var integer x
// Scan existing tokens for duplicate group names
for (x = 1; x <= lexer.tokenCount; x++) {
if (lexer.tokens[x].type == REGEX_TOKEN_GROUP_START) {
if (lexer.tokens[x].groupInfo.isNamed) {
if (lexer.tokens[x].groupInfo.name == name) {
return false // Duplicate found
}
}
}
}
return true
}
// ============================================================================
// QUANTIFIER VALIDATION
// ============================================================================
/**
* @function NAVRegexLexerCanQuantify
* @private
* @description Check if the previous token can be quantified.
*
* Validates:
* - There is a previous token
* - Previous token is not already a quantifier
* - Previous token is not an anchor
*
* @param {_NAVRegexLexer} lexer - The lexer structure
*
* @returns {char} True (1) if can quantify, False (0) otherwise
*/
define_function char NAVRegexLexerCanQuantify(_NAVRegexLexer lexer) {
// Check if there's a previous token that can be quantified
if (lexer.tokenCount == 0) {
NAVLibraryFunctionErrorLog(NAV_LOG_LEVEL_ERROR,
__NAV_FOUNDATION_REGEX_LEXER_HELPERS__,
'NAVRegexLexerCanQuantify',
"'Quantifier at start of pattern - nothing to quantify'")
return false // No previous token
}
// Check if previous token is already a quantifier
// (Lazy quantifiers are identified by the isLazy flag, not separate token types)
switch (lexer.tokens[lexer.tokenCount].type) {
case REGEX_TOKEN_STAR:
case REGEX_TOKEN_PLUS:
case REGEX_TOKEN_QUESTIONMARK:
case REGEX_TOKEN_QUANTIFIER: {
NAVLibraryFunctionErrorLog(NAV_LOG_LEVEL_ERROR,
__NAV_FOUNDATION_REGEX_LEXER_HELPERS__,
'NAVRegexLexerCanQuantify',
"'Consecutive quantifiers - cannot quantify a quantifier'")
return false // Can't quantify a quantifier
}
case REGEX_TOKEN_BEGIN:
case REGEX_TOKEN_END: {
NAVLibraryFunctionErrorLog(NAV_LOG_LEVEL_ERROR,
__NAV_FOUNDATION_REGEX_LEXER_HELPERS__,
'NAVRegexLexerCanQuantify',
"'Cannot quantify an anchor (^ or $)'")
return false // Can't quantify anchors
}
}
return true
}
// ============================================================================
// GROUP TRACKING
// ============================================================================
/**
* @function NAVRegexLexerIncrementGroupCount
* @private
* @description Increment the capturing group count.
*
* @param {_NAVRegexLexer} lexer - The lexer structure
*
* @returns {char} True (1) if successful, False (0) if max groups exceeded
*/
define_function char NAVRegexLexerIncrementGroupCount(_NAVRegexLexer lexer) {
// Check if we've exceeded max groups BEFORE incrementing
if (lexer.groupCount >= MAX_REGEX_GROUPS) {
NAVLibraryFunctionErrorLog(NAV_LOG_LEVEL_ERROR,
__NAV_FOUNDATION_REGEX_LEXER_HELPERS__,
'NAVRegexLexerIncrementGroupCount',
"'Too many capturing groups (max: ', itoa(MAX_REGEX_GROUPS), ')'")
return false
}
lexer.groupCount++
return true
}
/**
* @function NAVRegexLexerIncrementGroupDepth
* @private
* @description Increment the group nesting depth.
*
* @param {_NAVRegexLexer} lexer - The lexer structure
*
* @returns {char} True (1) if successful, False (0) if max depth exceeded
*/
define_function char NAVRegexLexerIncrementGroupDepth(_NAVRegexLexer lexer) {
// Check depth before using as array index
if (lexer.groupDepth >= MAX_REGEX_GROUPS) {
NAVLibraryFunctionErrorLog(NAV_LOG_LEVEL_ERROR,
__NAV_FOUNDATION_REGEX_LEXER_HELPERS__,
'NAVRegexLexerIncrementGroupDepth',
"'Group nesting too deep (max: ', itoa(MAX_REGEX_GROUPS), ')'")
return false
}
lexer.groupDepth++
return true
}
/**
* @function NAVRegexLexerDecrementGroupDepth
* @private
* @description Decrement the group nesting depth.
*
* @param {_NAVRegexLexer} lexer - The lexer structure
*
* @returns {char} True (1) if successful, False (0) if no matching opening parenthesis
*/
define_function char NAVRegexLexerDecrementGroupDepth(_NAVRegexLexer lexer) {
// Check if we have a matching opening parenthesis
if (lexer.groupDepth <= 0) {
NAVLibraryFunctionErrorLog(NAV_LOG_LEVEL_ERROR,
__NAV_FOUNDATION_REGEX_LEXER_HELPERS__,
'NAVRegexLexerDecrementGroupDepth',
"'Unmatched closing parenthesis `)` in pattern'")
return false
}
// Pop from stack
lexer.groupDepth--
return true
}
// ============================================================================
// TOKEN MANAGEMENT
// ============================================================================
/**
* @function NAVRegexLexerCanAddToken
* @private
* @description Check if there is space to add another token.
*
* Simple check that the token count hasn't exceeded the maximum limit
* defined by MAX_REGEX_TOKENS. Does not log errors.
*
* @param {_NAVRegexLexer} lexer - The lexer structure
*
* @returns {char} True (1) if space available, False (0) if limit reached
*/
define_function char NAVRegexLexerCanAddToken(_NAVRegexLexer lexer) {
return lexer.tokenCount < MAX_REGEX_TOKENS
}
/**
* @function NAVRegexLexerAddToken
* @private
* @description Add a new token to the lexer's token array with type and value.
*
* Checks capacity, increments token count, and sets the token's type and value.
* Logs an error if the maximum token limit has been reached.
*
* @param {_NAVRegexLexer} lexer - The lexer structure
* @param {integer} type - The token type (REGEX_TOKEN_)
* @param {char} value - The token value
*
* @returns {char} True (1) if token added successfully, False (0) if limit reached
*/
define_function char NAVRegexLexerAddToken(_NAVRegexLexer lexer, integer type, char value) {
if (!NAVRegexLexerCanAddToken(lexer)) {
NAVLibraryFunctionErrorLog(NAV_LOG_LEVEL_ERROR,
__NAV_FOUNDATION_REGEX_LEXER_HELPERS__,
'NAVRegexLexerAddToken',
"'Maximum token limit reached (', itoa(MAX_REGEX_TOKENS), ')'")
return false
}
lexer.tokenCount++
lexer.tokens[lexer.tokenCount].type = type
lexer.tokens[lexer.tokenCount].value = value
set_length_array(lexer.tokens, lexer.tokenCount)
return true
}
/**
* @function NAVRegexLexerPeekChar
* @private
* @description Look ahead at a character in the pattern relative to the cursor.
*
* Allows lookahead in the pattern string without advancing the cursor.
* The offset is relative to the current cursor position.
*
* This function silently returns 0 when peeking beyond the pattern bounds,
* as this is expected behavior that calling code handles appropriately.
*
* @param {_NAVRegexLexer} lexer - The lexer structure
* @param {integer} offset - The offset from current cursor position (1 = next char, 2 = char after that, etc.)
*
* @returns {char} The character at cursor + offset, or 0 if out of bounds
*/
define_function char NAVRegexLexerPeekChar(_NAVRegexLexer lexer, integer offset) {
stack_var integer position
position = lexer.pattern.cursor + offset
if (position < 1 || position > lexer.pattern.length) {
// Silently return 0 - peeking beyond bounds is expected and handled by callers
return 0
}
return NAVCharCodeAt(lexer.pattern.value, position)
}
/**
* @function NAVRegexLexerPeekNextChar
* @private
* @description Look ahead at the next character in the pattern.
*
* Convenience function to peek at the character immediately after
* the current cursor position (cursor + 1).
*
* @param {_NAVRegexLexer} lexer - The lexer structure
*
* @returns {char} The next character in the pattern, or 0 if out of bounds
*/
define_function char NAVRegexLexerPeekNextChar(_NAVRegexLexer lexer) {
return NAVRegexLexerPeekChar(lexer, 1)
}
// ============================================================================
// TOKEN TYPE LOOKUP
// ============================================================================
/**
* @function NAVRegexLexerGetTokenType
* @public
* @description Get the name of a token type for debugging and error messages.
*
* @param {integer} type - The token type constant
*
* @returns {char[NAV_MAX_CHARS]} The string name of the token type
*/
define_function char[NAV_MAX_CHARS] NAVRegexLexerGetTokenType(integer type) {
switch (type) {
case REGEX_TOKEN_NONE: { return 'NONE' }
case REGEX_TOKEN_EOF: { return 'EOF' }
case REGEX_TOKEN_DOT: { return 'DOT' }
case REGEX_TOKEN_BEGIN: { return 'BEGIN' }
case REGEX_TOKEN_END: { return 'END' }
case REGEX_TOKEN_QUESTIONMARK: { return 'QUESTIONMARK' }
case REGEX_TOKEN_STAR: { return 'STAR' }
case REGEX_TOKEN_PLUS: { return 'PLUS' }
case REGEX_TOKEN_CHAR: { return 'CHAR' }
case REGEX_TOKEN_CHAR_CLASS: { return 'CHAR_CLASS' }
case REGEX_TOKEN_INV_CHAR_CLASS: { return 'INV_CHAR_CLASS' }
case REGEX_TOKEN_DIGIT: { return 'DIGIT' }
case REGEX_TOKEN_NOT_DIGIT: { return 'NOT_DIGIT' }
case REGEX_TOKEN_ALPHA: { return 'ALPHA' }
case REGEX_TOKEN_NOT_ALPHA: { return 'NOT_ALPHA' }
case REGEX_TOKEN_WHITESPACE: { return 'WHITESPACE' }
case REGEX_TOKEN_NOT_WHITESPACE: { return 'NOT_WHITESPACE' }
case REGEX_TOKEN_ALTERNATION: { return 'ALTERNATION' }
case REGEX_TOKEN_GROUP: { return 'GROUP' }
case REGEX_TOKEN_QUANTIFIER: { return 'QUANTIFIER' }
case REGEX_TOKEN_ESCAPE: { return 'ESCAPE' }
case REGEX_TOKEN_EPSILON: { return 'EPSILON' }
case REGEX_TOKEN_WORD_BOUNDARY: { return 'WORD_BOUNDARY' }
case REGEX_TOKEN_NOT_WORD_BOUNDARY: { return 'NOT_WORD_BOUNDARY' }
case REGEX_TOKEN_HEX: { return 'HEX' }
case REGEX_TOKEN_NEWLINE: { return 'NEWLINE' }
case REGEX_TOKEN_RETURN: { return 'RETURN' }
case REGEX_TOKEN_TAB: { return 'TAB' }
case REGEX_TOKEN_FORMFEED: { return 'FORMFEED' }
case REGEX_TOKEN_VTAB: { return 'VTAB' }
case REGEX_TOKEN_BELL: { return 'BELL' }
case REGEX_TOKEN_ESC: { return 'ESC' }
case REGEX_TOKEN_GROUP_START: { return 'GROUP_START' }
case REGEX_TOKEN_GROUP_END: { return 'GROUP_END' }
case REGEX_TOKEN_LOOKAHEAD_POSITIVE: { return 'LOOKAHEAD_POSITIVE' }
case REGEX_TOKEN_LOOKAHEAD_NEGATIVE: { return 'LOOKAHEAD_NEGATIVE' }
case REGEX_TOKEN_LOOKBEHIND_POSITIVE: { return 'LOOKBEHIND_POSITIVE' }
case REGEX_TOKEN_LOOKBEHIND_NEGATIVE: { return 'LOOKBEHIND_NEGATIVE' }
case REGEX_TOKEN_NUMERIC_ESCAPE: { return 'NUMERIC_ESCAPE' }
case REGEX_TOKEN_BACKREF_NAMED: { return 'BACKREF_NAMED' }
case REGEX_TOKEN_STRING_START: { return 'STRING_START' }
case REGEX_TOKEN_STRING_END: { return 'STRING_END' }
case REGEX_TOKEN_STRING_END_ABSOLUTE: { return 'STRING_END_ABSOLUTE' }
case REGEX_TOKEN_FLAG_CASE_INSENSITIVE: { return 'FLAG_CASE_INSENSITIVE' }
case REGEX_TOKEN_FLAG_MULTILINE: { return 'FLAG_MULTILINE' }
case REGEX_TOKEN_FLAG_DOTALL: { return 'FLAG_DOTALL' }
case REGEX_TOKEN_FLAG_EXTENDED: { return 'FLAG_EXTENDED' }
case REGEX_TOKEN_COMMENT: { return 'COMMENT' }
default: { return "'UNKNOWN (', itoa(type), ')'" }
}
}
// ============================================================================
// SPECIALIZED TOKEN ADD FUNCTIONS
// ============================================================================
/**
* @function NAVRegexLexerAddQuantifierToken
* @private
* @description Add a quantifier token with min/max bounds.
*
* Used for bounded quantifiers like {n}, {n,}, or {n,m}.
*
* @param {_NAVRegexLexer} lexer - The lexer structure
* @param {integer} tokenType - The token type (REGEX_TOKEN_QUANTIFIER)
* @param {sinteger} minVal - Minimum repetitions
* @param {sinteger} maxVal - Maximum repetitions (-1 = unlimited)
*
* @returns {char} True (1) if token added successfully, False (0) if limit reached
*/
define_function char NAVRegexLexerAddQuantifierToken(_NAVRegexLexer lexer,
integer tokenType,
sinteger minVal,
sinteger maxVal) {
if (!NAVRegexLexerCanAddToken(lexer)) {
NAVLibraryFunctionErrorLog(NAV_LOG_LEVEL_ERROR,
__NAV_FOUNDATION_REGEX_LEXER_HELPERS__,
'NAVRegexLexerAddQuantifierToken',
"'Maximum token limit reached (', itoa(MAX_REGEX_TOKENS), ')'")
return false
}
lexer.tokenCount++
lexer.tokens[lexer.tokenCount].type = tokenType
lexer.tokens[lexer.tokenCount].min = minVal
lexer.tokens[lexer.tokenCount].max = maxVal
set_length_array(lexer.tokens, lexer.tokenCount)
return true
}
/**
* @function NAVRegexLexerAddNamedBackrefToken
* @private
* @description Add a named backreference token.
*
* Used for backreferences like \k<name>.
*
* @param {_NAVRegexLexer} lexer - The lexer structure
* @param {char[]} backrefName - The group name being referenced
* @param {char} value - The token value (usually the backslash)
*
* @returns {char} True (1) if token added successfully, False (0) if limit reached
*/
define_function char NAVRegexLexerAddNamedBackrefToken(_NAVRegexLexer lexer,
char backrefName[],
char value) {
if (!NAVRegexLexerCanAddToken(lexer)) {
NAVLibraryFunctionErrorLog(NAV_LOG_LEVEL_ERROR,
__NAV_FOUNDATION_REGEX_LEXER_HELPERS__,
'NAVRegexLexerAddNamedBackrefToken',
"'Maximum token limit reached (', itoa(MAX_REGEX_TOKENS), ')'")
return false
}
lexer.tokenCount++
lexer.tokens[lexer.tokenCount].type = REGEX_TOKEN_BACKREF_NAMED
lexer.tokens[lexer.tokenCount].value = value
lexer.tokens[lexer.tokenCount].name = backrefName
set_length_array(lexer.tokens, lexer.tokenCount)
return true
}
/**
* @function NAVRegexLexerAddCharClassToken
* @private
* @description Add a fully parsed character class token.
*
* Used for character classes like [abc], [a-z], or [^0-9].
* The character class should already be parsed into ranges.
*
* @param {_NAVRegexLexer} lexer - The lexer structure
* @param {_NAVRegexCharClass} charclass - The fully parsed character class
* @param {char} isNegated - True for [^...], false for [...]
*
* @returns {char} True (1) if token added successfully, False (0) if limit reached
*/
define_function char NAVRegexLexerAddCharClassToken(_NAVRegexLexer lexer,
_NAVRegexCharClass charclass,
char isNegated) {
if (!NAVRegexLexerCanAddToken(lexer)) {
NAVLibraryFunctionErrorLog(NAV_LOG_LEVEL_ERROR,
__NAV_FOUNDATION_REGEX_LEXER_HELPERS__,
'NAVRegexLexerAddCharClassToken',
"'Maximum token limit reached (', itoa(MAX_REGEX_TOKENS), ')'")
return false
}
lexer.tokenCount++
// Set token type and negation flag
if (isNegated) {
lexer.tokens[lexer.tokenCount].type = REGEX_TOKEN_INV_CHAR_CLASS
lexer.tokens[lexer.tokenCount].isNegated = true
}
else {
lexer.tokens[lexer.tokenCount].type = REGEX_TOKEN_CHAR_CLASS
lexer.tokens[lexer.tokenCount].isNegated = false
}
// Copy the entire parsed character class
lexer.tokens[lexer.tokenCount].charclass = charclass
set_length_array(lexer.tokens, lexer.tokenCount)
return true
}
/**
* @function NAVRegexLexerAddNumericEscapeToken
* @private
* @description Add a numeric escape token (ambiguous octal/backreference).
*
* This function handles escape sequences like \1, \10, \101, \377 which
* could be either octal escapes or backreferences depending on context.
* The lexer stores the digit string and metadata; the parser will decide
* the final interpretation based on the number of capturing groups.
*
* Disambiguation rules (applied by parser):
* - If digits start with 0 (\0...), always treat as octal
* - If value ≤ group count, treat as backreference
* - Otherwise, treat as octal (if valid)
*
* @param {_NAVRegexLexer} lexer - The lexer structure
* @param {char[]} digitStr - The digit string (e.g., "1", "10", "101")
* @param {char} leadingZero - True if sequence started with \0
*
* @returns {char} True (1) if token added successfully, False (0) if limit reached
*/
define_function char NAVRegexLexerAddNumericEscapeToken(_NAVRegexLexer lexer,
char digitStr[],
char leadingZero) {
if (!NAVRegexLexerCanAddToken(lexer)) {
NAVLibraryFunctionErrorLog(NAV_LOG_LEVEL_ERROR,
__NAV_FOUNDATION_REGEX_LEXER_HELPERS__,
'NAVRegexLexerAddNumericEscapeToken',
"'Maximum token limit reached (', itoa(MAX_REGEX_TOKENS), ')'")
return false
}
lexer.tokenCount++
lexer.tokens[lexer.tokenCount].type = REGEX_TOKEN_NUMERIC_ESCAPE
lexer.tokens[lexer.tokenCount].numericEscapeDigits = digitStr
lexer.tokens[lexer.tokenCount].numericEscapeLeadingZero = leadingZero
set_length_array(lexer.tokens, lexer.tokenCount)
return true
}
/**
* @function NAVRegexLexerIsHexDigit
* @private
* @description Check if a character is a valid hexadecimal digit (0-9, A-F, a-f).
*
* @param {char} c - The character to check
*
* @returns {char} True (1) if valid hex digit, False (0) otherwise
*/
define_function char NAVRegexLexerIsHexDigit(char c) {
// Check if character is 0-9
if (c >= '0' && c <= '9') {
return true
}
// Check if character is A-F
if (c >= 'A' && c <= 'F') {
return true
}
// Check if character is a-f
if (c >= 'a' && c <= 'f') {
return true
}
return false
}
/**
* @function NAVRegexLexerHexCharToValue
* @private
* @description Convert a hex character to its numeric value.
*
* @param {char} c - The hex character (0-9, A-F, a-f)
*
* @returns {integer} The numeric value (0-15)
*/
define_function integer NAVRegexLexerHexCharToValue(char c) {
// 0-9
if (c >= '0' && c <= '9') {
return c - '0'
}
// A-F
if (c >= 'A' && c <= 'F') {
return (c - 'A') + 10
}
// a-f
if (c >= 'a' && c <= 'f') {
return (c - 'a') + 10
}
return 0
}
/**
* @function NAVRegexLexerAddHexToken
* @private
* @description Add a hex escape token.
*
* Used for hex escapes like \xNN where NN is a 2-digit hex value.
*
* @param {_NAVRegexLexer} lexer - The lexer structure
* @param {integer} hexValue - The hex character code (decimal value)
*
* @returns {char} True (1) if token added successfully, False (0) if limit reached
*/
define_function char NAVRegexLexerAddHexToken(_NAVRegexLexer lexer,
integer hexValue) {
if (!NAVRegexLexerCanAddToken(lexer)) {
NAVLibraryFunctionErrorLog(NAV_LOG_LEVEL_ERROR,
__NAV_FOUNDATION_REGEX_LEXER_HELPERS__,
'NAVRegexLexerAddHexToken',
"'Maximum token limit reached (', itoa(MAX_REGEX_TOKENS), ')'")
return false
}
lexer.tokenCount++
lexer.tokens[lexer.tokenCount].type = REGEX_TOKEN_HEX
#IF_DEFINED REGEX_LEXER_DEBUG
NAVLog("'[ AddHexToken ]: hexValue (integer)=', itoa(hexValue), ', about to type_cast to char'")
#END_IF
lexer.tokens[lexer.tokenCount].value = type_cast(hexValue)
#IF_DEFINED REGEX_LEXER_DEBUG
NAVLog("'[ AddHexToken ]: After type_cast, token.value=', itoa(lexer.tokens[lexer.tokenCount].value)")
#END_IF
set_length_array(lexer.tokens, lexer.tokenCount)
return true
}
/**
* @function NAVRegexLexerAddFlagToken
* @private
* @description Add an inline flag token.
*
* Used for inline flags like (?i), (?m), (?s), (?x).
*
* @param {_NAVRegexLexer} lexer - The lexer structure
* @param {integer} tokenType - The token type (REGEX_TOKEN_FLAG_)
* @param {char} enabled - True to enable flag, False to disable (for (?-i) syntax)
* @param {char} value - The token value (usually the opening parenthesis)
*
* @returns {char} True (1) if token added successfully, False (0) if limit reached
*/
define_function char NAVRegexLexerAddFlagToken(_NAVRegexLexer lexer,
integer tokenType,
char enabled,
char value) {
if (!NAVRegexLexerCanAddToken(lexer)) {
NAVLibraryFunctionErrorLog(NAV_LOG_LEVEL_ERROR,
__NAV_FOUNDATION_REGEX_LEXER_HELPERS__,
'NAVRegexLexerAddFlagToken',
"'Maximum token limit reached (', itoa(MAX_REGEX_TOKENS), ')'")
return false
}
lexer.tokenCount++
lexer.tokens[lexer.tokenCount].type = tokenType
lexer.tokens[lexer.tokenCount].flagEnabled = enabled
lexer.tokens[lexer.tokenCount].value = value
set_length_array(lexer.tokens, lexer.tokenCount)
return true
}
/**
* @function NAVRegexLexerAddCommentToken
* @private
* @description Add a comment token.
*
* Used for inline comments like (?#comment). Comment tokens are purely
* informational and don't affect pattern matching or NFA construction.
*
* @param {_NAVRegexLexer} lexer - The lexer structure