-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathregexp.pas
3230 lines (3029 loc) · 84 KB
/
regexp.pas
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
(*****************************************************************
* Copyright (C), 2001 Pawel Ziemian, All rights reserved *
*****************************************************************)
(*****************************************************************
*
* SOURCE FILE: REGEXP.PAS
*
* MODULE NAME: Regular Expression for Objects
*
* PURPOSE:
*
* AUTHOR: Pawel Ziemian (PZ)
*
* REVIEWED BY:
*
* ORIGINAL NOTES:
* ===============================================================
* Based on: REGEX.C, REGEX.H 2001.09.16
* ---------------------------------------------------------------
* Copyright (c) 1986 by University of Toronto.
* Written by Henry Spencer. Not derived from licensed software.
*
* Permission is granted to anyone to use this software for any
* purpose on any computer system, and to redistribute it freely,
* subject to the following restrictions:
*
* 1. The author is not responsible for the consequences of use of
* this software, no matter how awful, even if they arise
* from defects in it.
*
* 2. The origin of this software must not be misrepresented, either
* by explicit claim or by omission.
*
* 3. Altered versions must be plainly marked as such, and must not
* be misrepresented as being the original software.
*
* Beware that some of this code is subtly aware of the way operator
* precedence is structured in regular expressions. Serious changes
* in regular-expression syntax might require a total rethink.
* ===============================================================
* Based on: REGEXPR.PAS v. 0.942 2001.10.24
* ---------------------------------------------------------------
* Copyright (c) 1999-00 by Andrey V. Sorokin <anso@mail.ru>
*
* This software is provided as it is, without any kind of warranty
* given. Use it at your own risk.
*
* You may use this software in any kind of development, including
* comercial, redistribute, and modify it freely, under the
* following restrictions :
* 1. The origin of this software may not be mispresented, you must
* not claim that you wrote the original software. If you use
* this software in any kind of product, it would be appreciated
* that there in a information box, or in the documentation would
* be an acknowledgmnent like this
* Partial Copyright (c) 2000 by Andrey V. Sorokin
* 2. You may not have any income from distributing this source
* to other developers. When you use this product in a comercial
* package, the source may not be charged seperatly.
* ===============================================================
*
* HISTORY:
*
* Ver Date Sign Description
*
* 0.01 2001.09.16 PZ Created based on REGEX.C
* 0.02 2001.09.20 PZ Object version
* 0.03 2001.09.23 PZ Optimized
* 0.04 2001.09.26 PZ Added '\:#' escapes
* 0.05 2001.09.27 PZ Optimized
* 0.06 2001.10.01 PZ Fixed bugs in '\:#'
* 0.07 2001.10.02 PZ Added '\a', '\b' and '\v'
* 0.08 2001.10.03 PZ Added posibility to define
* user '\:#' escapes ('#' is 0..9)
* 0.09 2001.10.18 PZ Added Substitution methods
* ('\0'..'\9' for '(..)')
* 0.10 2001.10.22 PZ Added tagged expressions
* - '(?dX)' where d is 1..9
* - '(?:X)' no tagged
* - '\1'..'\9' escapes
* 0.11 2001.10.24 PZ Added '{n,m}' syntax (by REGEXPR.PAS).
* 0.12 2001.11.13 PZ Fixed bugs
*
*****************************************************************)
{$I STDEFINE.INC}
{$UNDEF DEBUG}
{$DEFINE ComplexBraces}
{ define for beta-version of braces }
{ (in stable version it works only for simple cases) }
unit RegExp;
interface
uses
Objects2
;
type
TRegExpStatus = (
resOK,
resCanceled,
resNilArgument,
resInvalidArgument,
resRegExpTooBig,
resOutOfSpace,
resCorruptedProgram,
resUnmatchedParenthesis,
resJunkOnEnd,
resStarPlusOperandCouldBeEmpty,
resNestedStarQuotePlus,
resInvalidEscape,
resInvalidPredefinedExp,
resUndefinedPredefinedExp,
resStackOverflow,
resInvalidSetRange,
resUnmatchedSquareBracket,
resInternalUrp,
resOperatorFollowsNothing,
resTrailingBackSlash,
resInternalDisaster,
resNoExpression,
resMemoryCorruption,
resCorruptedPointers,
resInternalFoulup,
resDuplicatedTaggedExp,
resInvalidTaggedExp,
resComplexBracesNotImplemented,
resInvalidBraces,
resLoopStackExceeded,
resLoopWithoutEntry
);
type
(*
* Flags to be passed up and down.
*)
TRegExpFlag = (
refHasWidth, (* Known never to match null string. *)
refSimple, (* Simple enough to be STAR/PLUS operand. *)
refSpStart (* Starts with * or +. *)
);
TRegExpFlags = set of TRegExpFlag;
const
LoopStackMax = 10; { max depth of loops stack }
type
PRegExp = ^TRegExp;
TRegExp = object(TObject)
{Cat: íâ®â ®¡ê¥ªâ ¢ë¥á¥ ¢ ¯« £¨ãî ¬®¤¥«ì; ¨§¬¥ïâì ªà ©¥ ®áâ®à®¦®!}
{$IFDEF DEBUG}
Narrate: Boolean;
{$ENDIF DEBUG}
FStatus: TRegExpStatus;
FStart: Integer;
FLength: Integer;
constructor Init;
destructor Done; virtual;
procedure Reset;
function CompileString(const AExpression: String): Boolean;
function CompileStr(AExpression: PChar): Boolean;
function Compile(AExpression: PChar; ALength: Integer): Boolean;
function Execute(AString: PChar; ALength: Integer): Boolean;
function SubstituteString(ASrc: PChar; const AReplace: String;
var ADest: String): Boolean;
function SubstituteStr(ASrc, AReplace: PChar; ADest: PChar;
var ALength: Integer): Boolean;
function Substitute(ASrc, AReplace: PChar; ARLen: Integer;
ADest: PChar; var ADLen: Integer): Boolean;
procedure Error(AStatus: TRegExpStatus); virtual;
function CheckBreak: Boolean; virtual;
procedure Escape(AChar: Char; var ASubExp: PChar; var ALen: Integer)
; virtual;
{$IFDEF DEBUG}
procedure Dump;
{$ENDIF DEBUG}
private
(*
* The "internal use only" fields in regexp.h are present to pass info
* from compile to execute that permits the execute phase to run lots
* faster on simple cases. They are:
*
* regstart char that must begin a match; '\0' if none obvious
* reganch is the match anchored (at beginning-of-line only)?
* regmust string (pointer into program) that match must include, or NULL
* regmlen length of regmust string
*
* Regstart and reganch permit very fast decisions on suitable starting
* points for a match, cutting down the work a lot. Regmust permits fast
* rejection of lines that cannot possibly match. The regmust tests are
* costly enough that regcomp() supplies a regmust only if the r.e. contains
* something potentially expensive (at present, the only such thing detected
* is * or + at the start of the r.e., which can involve a lot of backup).
* Regmlen is supplied because the test in regexec() needs it and regcomp()
* is computing it anyway.
*)
FFlags: set of (
ffCompiled, { expression is compiled }
ffAnchored, { expression is anchored }
ffStart, { expression starts with FStartCh }
ffParsing, { calculating code size }
ffMatchNext,
ffBreak, { 'Execute' is cancelled }
ffAutoTag { automatic tagged expressions }
);
FCodeSize: Word; { *1* }
FCodeData: PChar; { *2* }
FStartP: array[1..9] of Integer; { founded expr starting points }
FEndP: array[1..9] of Integer; { founded expr end points }
FStartCh: Char;
FMust: PString; { *3* }
FInput: PChar; { *4* }
FInputBol: PChar; { *5* }
FInputEol: PChar; { *6* }
FLStack: array[1..LoopStackMax] of Integer;
{ state before entering loop }
FLStackId: Integer; { 0 - out of all loops }
{
// The following variables have different meaning while parsing or
// compiling the regular expression:
//
// *1* - Calculates the program size while parsing.
// *2* - Not used while parsing except it must be non-nil.
// Points to the next emited code byte while compiling.
// *3* - Points to internal stack while parsing or compiling.
// *4* - Points to the next character of being parsed or compiled
// (sub)expression.
// *5* - Points to the being parsed or compiled (sub)expression.
// *6* - Points just beyond the being parsed/compiled expression.
}
{ Compilation routines }
function RegCompile(AExpression: PChar; ALength: Integer): Boolean;
procedure IncRegSize(I: Integer);
function Reg(Paren: Integer; var FlagP: TRegExpFlags): PChar;
function RegBranch(var FlagP: TRegExpFlags): PChar;
function RegPiece(var FlagP: TRegExpFlags): PChar;
function RegAtom(var FlagP: TRegExpFlags): PChar;
function RegEnter(Op: Char; Tagged: Boolean): Boolean;
procedure RegLeave;
function RegLoadNumber(Base: Integer; Digits: Integer; var AResult)
: Boolean;
function RegEscape(var AResult: Char): Boolean;
function RegSet: PChar;
function RegExactly(var FlagP: TRegExpFlags): PChar;
function RegNode(Op: Char): PChar;
procedure RegC(B: Char);
function RegInsert(Op: Char; Opnd: PChar; ASize: Integer): PChar;
procedure RegTail(P: PChar; Val: PChar);
procedure RegOpTail(P: PChar; Val: PChar);
{ Execute routines }
function RegExecute(AString: PChar; ALength: Integer): Boolean;
function RegTry(AString: PChar): Boolean;
function RegMatch(Prog: PChar): Boolean;
function RegRepeat(P: PChar; AMax: Integer): Integer;
{ Common routines }
function RegNext(P: PChar): PChar;
procedure RegClearTags;
{ Replace support }
function RegSub(ASrc, AReplace: PChar; ARLen: Integer; ADest: PChar;
var ADLen: Integer): Boolean;
end;
implementation
uses
Strings,
Memory, Advance
;
(*****************************************************************
*
* FUNCTION: StrScan2
*
* PURPOSE: This function returns a pointer to the first
* occurrence of a character in a string.
*
* INPUTS: P - A string to scan.
* C - A character to scan.
* P2 - An address just beyond the string.
*
* OUTPUTS: None.
*
* RETURNS: nil - A character not found.
* Other - An address of the character in P.
*
* NOTES:
*
* HISTORY:
*
*****************************************************************)
function StrScan2(P: PChar; C: Char; P2: PChar): PChar;
{$IFDEF NOASM}
begin
StrScan2 := nil;
while P < P2 do
begin
if P[0] = C then
begin
StrScan2 := P;
Exit;
end;
Inc(P);
end;
end;
{$ELSE ASM}
assembler;
{&Frame-} {&USES EDI, ECX}
asm
MOV EDI,P
MOV ECX,P2
XOR EAX,EAX { default nil result }
SUB ECX,EDI { calculate length }
JBE @@1 { P2 must be greater than P }
MOV AL,C
CLD
REPNE SCASB
MOV AL,0 { restore the nil }
JNE @@1
LEA EAX,[EDI-1] { get the address }
@@1:
end;
{$ENDIF ASM}
(*****************************************************************
*
* TRegExp support types and routines.
*
*****************************************************************)
(*****************************************************************
*
* Structure for regexp "program". This is essentially a linear
* encoding of a nondeterministic finite-state machine (aka syntax
* charts or "railroad normal form" in parsing technology). Each
* node is an opcode plus a "next" pointer, possibly plus an operand.
* "Next" pointers of all nodes except BRANCH implement concatenation;
* a "next" pointer with a BRANCH on both ends of it is connecting
* two alternatives. (Here we have one of the subtle syntax
* dependencies: an individual BRANCH (as opposed to a collection of
* them) is never concatenated with anything because of operator
* precedence.) The operand of some types of node is a literal
* string; for others, it is a node leading into a sub-FSM.
* In particular, the operand of a BRANCH node is the first node
* of the branch. (NB this is *not* a tree structure: the tail of
* the branch connects to the thing following the set of BRANCHes.)
* The opcodes are:
*)
const
(* definition number opnd? meaning *)
ropEND = #00; (* no End of program. *)
ropBOL = #01; (* no Match "" at beginning of line. *)
ropEOL = #02; (* no Match "" at end of line. *)
ropANY = #03; (* no Match any one character. *)
ropANYOF = #04; (* str Match any character in this string. *)
ropANYBUT = #05; (* str Match any character not in this string. *)
ropBRANCH = #06; (* node Match this alternative, or the next... *)
ropBACK = #07; (* no Match "", "next" ptr points backward. *)
ropEXACTLY = #08; (* str Match this string. *)
ropNOTHING = #09; (* no Match empty string. *)
ropSTAR = #10; (* node Match this (simple) thing 0 or more times. *)
ropPLUS = #11; (* node Match this (simple) thing 1 or more times. *)
ropOPEN = #12; (* no Mark this point in input as start of #. *)
ropCLOSE = #13; (* no Analogous to OPEN. *)
ropBRACES = #14;
{ n,m Match this (simple) thing from n to m times. }
ropSTARNG = #15; { Same as START but in non-greedy mode }
ropPLUSNG = #16; { Same as PLUS but in non-greedy mode }
ropBRACESNG = #17; { Same as BRACES but in non-greedy mode }
ropLOOPENTRY = #18;
{ node Start of loop (LOOP - Node for this loop) }
ropLOOP = #19; { n,m Back jump for LOOPENTRY. }
ropLOOPNG = #20; { Same as LOOP but in non-greedy mode }
ropOPEN0 = #30; (* no Mark this point in input as start of #n. *)
ropOPEN9 = #39;
ropCLOSE0 = #40; (* no Analogous to OPEN0. *)
ropCLOSE9 = #49;
(*
* Opcode notes:
*
* BRANCH The set of branches constituting a single choice are hooked
* together with their "next" pointers, since precedence prevents
* anything being concatenated to any individual branch. The
* "next" pointer of the last BRANCH in a choice points to the
* thing following the whole choice. This is also where the
* final "next" pointer of each individual branch points; each
* branch starts with the operand node of a BRANCH node.
*
* BACK Normal "next" pointers all implicitly point forward; BACK
* exists to make loop structures possible.
*
* STAR,PLUS '?', and complex '*' and '+', are implemented as circular
* BRANCH structures using BACK. Simple cases (one character
* per match) are implemented with STAR and PLUS for speed
* and to minimize recursive plunges.
*
* OPEN,CLOSE
*
*****************************************************************)
(*****************************************************************
*
* The first byte of the regexp internal "program" is actually
* this magic number; the start node begins in the second byte.
*
*****************************************************************)
const
magic = #$9C; { 0234 }
(*****************************************************************
*
* This is the maximum size of an compiled regexp program.
* The limit is caused by size of "Next" pointer in the regexp
* instruction which takes only two bytes.
*
*****************************************************************)
const
MaxRegSize = 32768;
(*****************************************************************
*
* The internal stack is introduced to allow compile '\:#' escape
* sequences. The predefined sequence can be called recursively
* in regular expression. There is already defined one recursive
* call for '\:p' which uses '\:f' in their definition.
*
* The current stack size is two items, which is enough for '\:p'
* (One for entry to subexpression and one for nested '\:f').
*
* 2001.10.03
* The current stack is 10 due to user escapes '\:0'..'\:9' are
* introduced. Any of them can call recursively other escape.
*
*****************************************************************)
const
MaxRegExpStack = 10;
const
ParseNumBaseMask = $00FF;
ParseNumInteger = $0100;
const
MaxBracesArg = Ord(High(Char));
type
TRegExpStackItem = record
Entry: Integer;
bol: PChar;
Cur: PChar;
Eol: PChar;
end;
PRegExpStack = ^TRegExpStack;
TRegExpStack = record
Entries: Integer;
Entry: Integer;
FNPar: Integer;
Level: Integer;
Stack: array[0..MaxRegExpStack-1] of TRegExpStackItem;
TagStarts: array[1..9] of PChar;
TagEnds: array[1..9] of PChar;
end;
{$IFDEF DEBUG}
(*****************************************************************
*
* FUNCTION: RegProp
*
* PURPOSE: This function returns printable representation of
* opcode.
*
* INPUTS: Op - An opcode.
*
* OUTPUTS: None.
*
* RETURNS: None.
*
* NOTES:
*
* HISTORY:
*
*****************************************************************)
function RegProp(Op: PChar): String;
var
s: String;
begin
case Op[0] of
ropBOL:
s := 'BOL';
ropEOL:
s := 'EOL';
ropANY:
s := 'ANY';
ropANYOF:
s := 'ANYOF';
ropANYBUT:
s := 'ANYBUT';
ropBRANCH:
s := 'BRANCH';
ropEXACTLY:
s := 'EXACTLY';
ropNOTHING:
s := 'NOTHING';
ropBACK:
s := 'BACK';
ropEND:
s := 'END';
ropOPEN:
s := 'OPEN';
ropCLOSE:
s := 'CLOSE';
ropSTAR:
s := 'STAR';
ropPLUS:
s := 'PLUS';
ropBRACES:
s := 'BRACES';
ropSTARNG:
s := 'STARNG';
ropPLUSNG:
s := 'PLUSNG';
ropBRACESNG:
s := 'BRACESNG';
ropLOOPENTRY:
s := 'LOOPENTRY';
ropLOOP:
s := 'LOOP';
ropLOOPNG:
s := 'LOOPNG';
else {case}
if Op[0] in [ropOPEN0..ropOPEN9] then
begin
Str(Ord(Op[0])-Ord(ropOPEN0), s);
s := 'OPEN'+s;
end
else if Op[0] in [ropCLOSE0..ropCLOSE9] then
begin
Str(Ord(Op[0])-Ord(ropCLOSE0), s);
s := 'CLOSE'+s;
end
else
begin
Str(Ord(Op[0]), s);
s := '#'+s;
end;
end {case};
RegProp := ':'+s;
end { RegProp };
{$ENDIF DEBUG}
(*****************************************************************
*
* TRegExp
*
*****************************************************************)
constructor TRegExp.Init;
begin
inherited Init;
FCodeSize := 0;
FCodeData := nil;
FFlags := [];
FStatus := resOK;
end;
destructor TRegExp.Done;
begin
Reset;
inherited Done;
end;
procedure TRegExp.Reset;
begin
if FCodeSize > 0 then
begin
if FCodeData <> nil then
FreeMem(FCodeData, FCodeSize);
FCodeSize := 0;
FCodeData := nil;
Exclude(FFlags, ffCompiled);
end;
FStatus := resOK;
end;
function TRegExp.CompileString(const AExpression: String): Boolean;
begin
CompileString := Compile(@AExpression[1], Length(AExpression));
end;
function TRegExp.CompileStr(AExpression: PChar): Boolean;
begin
CompileStr := Compile(AExpression, StrLen(AExpression));
end;
(*****************************************************************
*
* FUNCTION: TRegExp.Compile
*
* PURPOSE: This function compile a regular expression into
* internal code and invoke Error if required.
*
* INPUTS: AExpression - A regular expspression string.
* ALength - A length of the expression string.
*
* OUTPUTS: None.
*
* RETURNS: False - Error.
* True - Successful.
*
* NOTES:
*
* HISTORY:
*
*****************************************************************)
function TRegExp.Compile(AExpression: PChar; ALength: Integer): Boolean;
begin
Compile := RegCompile(AExpression, ALength);
if FStatus <> resOK then
Error(FStatus);
end;
(*****************************************************************
*
* FUNCTION: TRegExp.Execute
*
* PURPOSE: This function match a regexp against a string
* and invokes Error method if required.
*
* INPUTS: AString - A source string.
* ALength - A string length.
*
* OUTPUTS: None.
*
* RETURNS: True - The given string match.
* False - The given string does not match.
*
* NOTES:
*
* HISTORY:
*
*****************************************************************)
function TRegExp.Execute(AString: PChar; ALength: Integer): Boolean;
begin
Execute := RegExecute(AString, ALength);
if FStatus <> resOK then
Error(FStatus);
end;
(*****************************************************************
*
* FUNCTION: TRegExp.Error
*
* PURPOSE: This function is called is status is not resOK
* after compiling or executing regular expression.
*
* INPUTS: AStatus - The status of an operation.
*
* OUTPUTS: None.
*
* RETURNS: None.
*
* NOTES:
*
* HISTORY:
*
*****************************************************************)
procedure TRegExp.Error(AStatus: TRegExpStatus);
begin
end;
(*****************************************************************
*
* FUNCTION: TRegExp.CheckBreak
*
* PURPOSE: This function is called periodically to check if
* if current searching is canceled.
*
* INPUTS: None.
*
* OUTPUTS: None.
*
* RETURNS: True - Cancel the search.
* False - Continue search.
*
* NOTES:
*
* HISTORY:
*
*****************************************************************)
function TRegExp.CheckBreak: Boolean;
begin
CheckBreak := False;
end;
(*****************************************************************
*
* PROCEDURE: Escape
*
* PURPOSE: This procedure is called to obtain user defined
* escape sequence.
*
* INPUTS: AChar - A '#' character in '\:#' escape code.
* ASubExp - Buffer for an expression address.
* ALen - Buffer for a length of the expression.
*
* OUTPUTS: ASubExp - Buffer with address of the expression.
* ALen - Buffer with length of the expression.
*
* NOTES: 1. If ASubExp is nil then the escape code is
* invalid.
* 2. If ALen is zero then expression is not defined.
* 3. The method must be overide in derived objects
* to provide its own escapes.
*
* HISTORY:
*
*****************************************************************)
procedure TRegExp.Escape(AChar: Char; var ASubExp: PChar;
var ALen: Integer);
begin
ASubExp := nil;
ALen := 0;
end;
(*****************************************************************
*
* FUNCTION: TRegExp.RegCompile
*
* PURPOSE: This function compile a regular expression into
* internal code.
*
* INPUTS: AExpression - A regular expspression string.
* ALength - A length of the expression string.
*
* OUTPUTS: None.
*
* RETURNS: True - Successful.
* False - Error.
*
* NOTES: We can't allocate space until we know how big the
* compiled form will be, but we can't compile it
* (and thus know how big it is) until we've got a
* place to put the code. So we cheat: we compile
* it twice, once with code generation turned off and
* size counting turned on, and once "for real".
* This also means that we don't allocate space until
* we are sure that the thing really will compile
* successfully, and we never have to move the code
* and thus invalidate pointers into it.
* (Note that it has to be in one piece because free()
* must be able to free it all.)
*
* Beware that the optimization-preparation code in
* here knows about some of the structure of the
* compiled regexp.
*
* HISTORY:
*
*****************************************************************)
function TRegExp.RegCompile(AExpression: PChar; ALength: Integer): Boolean;
var
scan: PChar;
len: Integer;
flags: TRegExpFlags;
p: Pointer;
dummy: Char;
stack: TRegExpStack;
begin
{$IFDEF DEBUG}
FillChar(stack, SizeOf(stack), 0);
{$ENDIF DEBUG}
RegCompile := False;
Reset;
if AExpression = nil then
begin
FStatus := resNilArgument;
Exit;
end;
if ALength <= 0 then
begin
FStatus := resInvalidArgument;
Exit;
end;
FMust := @stack;
FInputBol := AExpression;
FInputEol := AExpression+ALength;
(* First pass: determine size, legality. *)
FInput := AExpression;
FCodeSize := 0;
FCodeData := @dummy; { must be non-nil }
stack.Entries := 0;
stack.Entry := 0;
stack.Level := 0;
stack.FNPar := 1;
RegC(magic);
FFlags := FFlags+[ffParsing, ffAutoTag];
RegClearTags;
p := Reg(0, flags);
Exclude(FFlags, ffParsing);
if p = nil then
begin
FCodeSize := 0;
FCodeData := nil;
Exit;
end;
(* Small enough for pointer-storage convention? *)
if FCodeSize >= MaxRegSize then
begin (* Probably could be 65535. *)
FStatus := resRegExpTooBig;
Exit;
end;
(* Allocate space. *)
p := MemAlloc(FCodeSize);
if p = nil then
begin
FStatus := resOutOfSpace;
Exit;
end;
{$IFDEF DEBUG}
FillChar(p^, FCodeSize, $FF);
{$ENDIF DEBUG}
(* Second pass: emit code. *)
FInput := AExpression;
FCodeData := PChar(p);
stack.Entries := 0;
stack.Entry := 0;
stack.Level := 0;
stack.FNPar := 1;
RegC(magic);
RegClearTags;
Reg(0, flags); { this should return with non-nil result }
FCodeData := p;
(* Dig out information for optimizations. *)
FFlags := [];
FMust := nil;
scan := @FCodeData[1]; (* First BRANCH. *)
if RegNext(scan)[0] = ropEND then
begin
(* Only one top-level choice. *)
scan := @scan[3];
(* Starting-point info. *)
if scan[0] = ropEXACTLY then
begin
FStartCh := scan[4];
Include(FFlags, ffStart);
end
else if scan[0] = ropBOL then
begin
Include(FFlags, ffAnchored);
end;
(*
* If there's something expensive in the r.e., find the
* longest literal string that must appear and make it the
* regmust. Resolve ties in favor of later strings, since
* the regstart check works with the beginning of the r.e.
* and avoiding duplication strengthens checking. Not a
* strong reason, but sufficient in the absence of others.
*)
if refSpStart in flags then
begin
p := nil;
len := 0;
while scan <> nil do
begin
if (scan[0] = ropEXACTLY) and (Ord(scan[3]) >= len) then
begin
p := @scan[3];
len := Ord(scan[3]);
end;
scan := RegNext(scan);
end;
FMust := PString(p);
end;
end;
Include(FFlags, ffCompiled);
RegCompile := True;
end { TRegExp.RegCompile };
(*****************************************************************
*
* FUNCTION: TRegExp.IncRegSize
*
* PURPOSE: This function is used to calculate size of compiled
* expression.
*
* INPUTS: I - Size of next chunk of code.
*
* OUTPUTS: None.
*
* RETURNS: None.
*
* NOTES:
*
* HISTORY:
*
*****************************************************************)
procedure TRegExp.IncRegSize(I: Integer);
begin
if FCodeSize <= MaxRegSize then
Inc(FCodeSize, I);
end;
(*****************************************************************
*
* FUNCTION: TRegExp.Reg
*
* PURPOSE: This function parses regular expression, i.e.
* main body or parenthesized thing.
*
* INPUTS: Paren - 0 = main body;
* -1 = parenthesized (auto-tag);
* 1..9 = tagged expression 1..9;
* FlagP - Buffer with flags.
*
* OUTPUTS: FlagP - Buffer with flags.
*
* RETURNS: nil - If error.
* !nil - Address of RegExp byte code.
*
* NOTES: 1. Caller must absorb opening parenthesis.
*
* 2. Combining parenthesis handling with the base
* level of regular expression is a trifle forced,
* but the need to tie the tails of the branches
* to what follows makes it hard to avoid.
*
* HISTORY:
*
*****************************************************************)
function TRegExp.Reg(Paren: Integer; var FlagP: TRegExpFlags): PChar;
var
ret: PChar;
br: PChar;
ender: PChar;
flags: TRegExpFlags;
parno: Integer;
stack: PRegExpStack absolute FMust;
begin
Reg := nil;
FlagP := [refHasWidth]; (* Tentatively. *)
(* Make an OPEN node, if parenthesized. *)
if Paren <> 0 then
begin
parno := Paren; { use selected tagged expression }
if ffAutoTag in FFlags then
begin
if parno = -1 then
begin
parno := stack^.FNPar;
Inc(stack^.FNPar);
end
else
begin
RegClearTags; { clear currently defined tags }
Exclude(FFlags, ffAutoTag);
end;
end;
if not (parno in [1..9]) then
begin
ret := RegNode(ropOPEN);
end
else
begin
ret := RegNode(Char(Ord(ropOPEN0)+parno));
if stack^.TagStarts[parno] <> nil then
begin
FStatus := resDuplicatedTaggedExp;
Exit;
end;
stack^.TagStarts[parno] := FInput;
FStartP[parno] := stack^.Entry;
end;
end