summaryrefslogtreecommitdiff
path: root/packages/base/regexpr/regexpr.pp
blob: 9dd7ea14bf9656e41836e60558e89476ca2e06db (plain)
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
{ $DEFINE DEBUG}

{
    This unit implements basic regular expression support

    This file is part of the Free Pascal run time library.
    Copyright (c) 2000-2006 by Florian Klaempfland Carl Eric Codere

    See the file COPYING.FPC, included in this distribution,
    for details about the copyright.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.

 **********************************************************************}
{.$ define DEBUG}

(*
  - newline handling (uses all known formats of ASCII, #10,#13,#13#10 and #$85

  TODO:
     - correct backtracking, for example in (...)*
     - full | support (currently requires to put all items with | operator
        between parenthesis (in a group) to take care over order priority.
          Therefore the following would work: (foo)|(nofoo) but not
          foo|nofoo
     - getting substrings and using substrings with \1 etc.
     - do we treat several multiline characters in a row as a single
        newline character for $ and ^?
*)

{$IFDEF FPC}
{$mode objfpc}
{$ENDIF}

{** @abstract(Regular expression unit)

    This unit implements a basic regular expression parser that mostly conforms
    to the POSIX extended-regular expression syntax. It also supports standard
    escape characters for patterns (as defined in PERL).
}
unit regexpr;

  interface

    { the following declarions are only in the interface because }
    { some procedures return pregexprentry but programs which   }
    { use this unit shouldn't access this data structures        }
    type
       tcharset = set of char;
       tregexprentrytype = (ret_charset,ret_or,
          ret_illegalend,ret_backtrace,ret_startline,
          ret_endline,ret_pattern);

       pregexprentry = ^tregexprentry;
       tregexprentry = record
          next,nextdestroy : pregexprentry;
          case typ : tregexprentrytype of
             ret_charset : (chars : tcharset; elsepath : pregexprentry);
             {** This is a complete pattern path ()+ , ()* or ()?, n,m }
             ret_pattern: (pattern: pregexprentry; minoccurs: integer; maxoccurs: integer; alternative : pregexprentry);
       end;

       tregexprflag = (
         ref_singleline,
         {** This indicates that a start of line is either the
             start of the pattern or a linebreak. }
         ref_multiline,
         {** The match will be done in a case-insensitive way
              according to US-ASCII character set. }
         ref_caseinsensitive);
       tregexprflags = set of tregexprflag;

       TRegExprEngine = record
          Data : pregexprentry;
          DestroyList : pregexprentry;
          Flags : TRegExprFlags;
       end;

     const
        cs_allchars : tcharset = [#0..#255];
        cs_wordchars : tcharset = ['A'..'Z','a'..'z','_','0'..'9'];
        cs_newline : tcharset = [#10];
        cs_digits : tcharset = ['0'..'9'];
        cs_whitespace : tcharset = [' ',#9];

     var
        { these are initilized in the init section of the unit }
        cs_nonwordchars : tcharset;
        cs_nondigits : tcharset;
        cs_nonwhitespace : tcharset;

     { the following procedures can be used by units basing }
     { on the regexpr unit                                  }

     {** From a regular expression, compile an encoded version of the regular expression.

         @param(regexpr Regular expression to compile)
         @param(flags Flags relating to the type of parsing that will occur)
         @param(RegExprEngine The actual encoded version of the regular expression)
         @returns(true if success, otherwise syntax error in compiling regular expression)
     }
     function GenerateRegExprEngine(regexpr : pchar;flags : tregexprflags;var RegExprEngine: TRegExprEngine): boolean;

{$IFDEF FPC}
    {** Backward compatibility routine }
     function GenerateRegExprEngine(regexpr : pchar;flags : tregexprflags): TREGExprEngine;
{$ENDIF}

     {** Frees all up resources used for the encoded regular expression }
     procedure DestroyRegExprEngine(var regexpr : TRegExprEngine);

     {** @abstract(Matches a regular expression)

        @param(RegExprEngine The actual compiled regular expression to match against)
        @param(p The text to search for for a match)
        @param(index zero-based index to the start of the match -1 if no match in p)
        @param(len length of the match)
        @returns(true if there was a match, otherwise false)
     }
     function RegExprPos(RegExprEngine : TRegExprEngine;p : pchar;var index,len : longint) : boolean;

     function RegExprReplaceAll(RegExprEngine : TRegExprEngine;const src,newstr : ansistring;var dest : ansistring) : sizeint;

     { This function Escape known regex chars and place the result on Return. If something went wrong the
       function will return false. }
     function RegExprEscapeStr (const S : string) : string;

  implementation

{$ifdef DEBUG}
     procedure writecharset(c : tcharset);

       var
          b : byte;

       begin
          for b:=20 to 255 do
            if chr(b) in c then
              write(chr(b));
          writeln;
       end;


    const

      typ2str : array[tregexprentrytype] of string =
      (
        'ret_charset',
        'ret_or',
        'ret_illegalend',
        'ret_backtrace',
        'ret_startline',
        'ret_endline',
        'ret_pattern'
      );


     { Dumps all the next elements of a tree }
     procedure dumptree(space: string; regentry: pregexprentry);
      begin
        while assigned(regentry) do
          begin
            WriteLn(space+'------- Node Type ',typ2str[regentry^.typ]);
            if (regentry^.typ = ret_charset) then
              WriteCharSet(regentry^.chars);
            { dump embedded pattern information }
            if regentry^.typ = ret_pattern then
               begin
                 dumptree(space+#9,regentry^.pattern);
                 WriteLn(space+#9,' --- Alternative nodes ');
                 if assigned(regentry^.alternative) then
                   dumptree(space+#9#9,regentry^.alternative);
               end;
            if regentry^.typ = ret_startline then
               dumptree(space+#9,regentry^.pattern);
            regentry:=regentry^.next;
          end;
      end;
{$endif DEBUG}


     {** Determines the length of a pattern, including sub-patterns.

         It goes through the nodes and returns the pattern length
         between the two, using minOccurs as required.

         Called recursively.
     }
     function patlength(hp1: pregexprentry): integer;
       var
        count: integer;
        hp: pregexprentry;
       begin
        count:=0;
        if hp1^.typ=ret_pattern then
            hp:=hp1^.pattern
        else
            hp:=hp1;
        { now go through all chars and get the length
          does not currently take care of embedded patterns
        }
        while assigned(hp) do
          begin
            if hp^.typ = ret_pattern then
              begin
                inc(count,patlength(hp));
              end
            else
            if hp^.typ = ret_charset then
               inc(count);
            hp:=hp^.next;
          end;
        if hp1^.typ=ret_pattern then
          begin
            count:=hp1^.minOccurs*count;
          end;
         patlength:=count;
       end;

     function GenerateRegExprEngine(regexpr : pchar;flags : tregexprflags; var RegExprEngine:TRegExprEngine) : boolean;

       var
          first : pregexprentry;

       procedure doregister(p : pregexprentry);

         begin
           p^.nextdestroy:=first;
           first:=p;
         end;

       var
          currentpos : pchar;
          error : boolean;

       procedure readchars(var chars: tcharset);

         var
            c1 : char;

         begin
            chars:=[];
            case currentpos^ of
               #0:
                  exit;
               '.':
                  begin
                     inc(currentpos);
                     chars:=cs_allchars-cs_newline;
                  end;
               '\':
                  begin
                     inc(currentpos);
                     case currentpos^ of
                        #0:
                          begin
                             error:=true;
                             exit;
                          end;
                        't':
                           begin
                              inc(currentpos);
                              chars:=[#9];
                           end;
                        'n':
                           begin
                              inc(currentpos);
                              chars:=[#10];
                           end;
                        'r':
                           begin
                              inc(currentpos);
                              chars:=[#13];
                           end;
                        'd':
                          begin
                             inc(currentpos);
                             chars:=cs_digits;
                          end;
                        'D':
                          begin
                             inc(currentpos);
                             chars:=cs_nondigits;
                          end;
                        's':
                          begin
                             inc(currentpos);
                             chars:=cs_whitespace;
                          end;
                        'S':
                          begin
                             inc(currentpos);
                             chars:=cs_nonwhitespace;
                          end;
                        'w':
                           begin
                              inc(currentpos);
                              chars:=cs_wordchars;
                           end;
                        'W':
                           begin
                              inc(currentpos);
                              chars:=cs_nonwordchars;
                           end;
                        'f' :
                            begin
                              inc(currentpos);
                              chars:= [#12];
                            end;
                        'a' :
                            begin
                              inc(currentpos);
                              chars:= [#7];
                            end;
                         else
                           begin { Some basic escaping...}
                              chars := [currentpos^];
                              inc (currentpos);
                              {error:=true;
                              exit;}
                           end;
                     end;
                  end;
               else
                 begin
                    if ref_caseinsensitive in flags then
                       c1:=upcase(currentpos^)
                    else
                       c1:=currentpos^;

                    inc(currentpos);
                    if currentpos^='-' then
                      begin
                         inc(currentpos);
                         if currentpos^=#0 then
                           begin
                              error:=true;
                              exit;
                           end;
                         if ref_caseinsensitive in flags then
                           chars:=[c1..upcase(currentpos^)]
                         else
                           chars:=[c1..currentpos^];
                         inc(currentpos);
                      end
                    else
                      chars:=[c1];
                 end;
            end;
         end;


       procedure readcharset(var charset: tcharset);

         var
           chars: tcharset;
         begin
            charset:=[];
            case currentpos^ of
               #0:
                  exit;
               '[':
                  begin
                     inc(currentpos);
                     while currentpos^<>']' do
                       begin
                          if currentpos^='^' then
                            begin
                               inc(currentpos);
                               readchars(chars);
                               charset:=charset+(cs_allchars-chars);
                            end
                          else
                            begin
                              readchars(chars);
                              charset:=charset+chars;
                            end;
                          if error or (currentpos^=#0) then
                            begin
                               error:=true;
                               exit;
                            end;
                       end;
                     inc(currentpos);
                  end;
               '^':
                  begin
                     inc(currentpos);
                     readchars(chars);
                     charset:=cs_allchars-chars;
                  end;
               else
                  begin
                    readchars(chars);
                    charset:=chars;
                  end;
            end;
         end;


       (* takes care of parsing the {n}, {n,} and {n,m} regular expression
          elements. In case of error, sets error to true and returns false,
          otherwise returns true and set minoccurs and maxoccurs accordingly
          (-1 if not present). *)
       function parseoccurences(var currentpos: pchar; var minoccurs,maxoccurs: integer): boolean;
         var
          minOccursString: string;
          maxOccursString: string;
         begin
           parseoccurences:=false;
           minOccurs:=-1;
           maxOccurs:=-1;
           inc(currentpos);
           minOccursString:='';
           if currentPos^ = #0 then
             begin
               error:=true;
               exit;
             end;
            while (currentpos^<>#0) and (currentpos^ in ['0'..'9']) do
                begin
                   minOccursString:=minOccursString+currentPos^;
                   inc(currentpos);
                end;
            if length(minOccursString) = 0 then
                begin
                  error:=true;
                  exit;
                end;
            Val(minOccursString,minOccurs);
            { possible cases here: commad or end bracket }
            if currentpos^= '}' then
              begin
                inc(currentpos);
                maxOccurs:=minOccurs;
                parseoccurences:=true;
                exit;
              end;
            if currentpos^= ',' then
              begin
                maxOccursString:='';
                inc(currentpos);
                while (currentpos^<>#0) and (currentpos^ in ['0'..'9']) do
                begin
                   maxOccursString:=maxOccursString+currentPos^;
                   inc(currentpos);
                end;
                if currentpos^= '}' then
                 begin
                   { If the length of the string is zero, then there is
                     no upper bound. }
                   if length(maxOccursString) > 0 then
                      Val(maxOccursString,maxOccurs)
                   else
                      maxOccurs:=high(integer);
                   inc(currentpos);
                   parseoccurences:=true;
                   exit;
                 end;
              end;
              error:=true;
         end;


       function parseregexpr(next,elsepath : pregexprentry) : pregexprentry;

         var
            hp : pregexprentry;
            minOccurs,maxOccurs: integer;
            hp3: pregexprentry;
            cs : tcharset;
            chaining : ^pregexprentry;

         begin
            chaining:=nil;
            parseregexpr:=nil;
            elsepath:=nil;
            if error then
              exit;
            { this dummy allows us to redirect the elsepath later }
{            new(ep);
            doregister(ep);
            ep^.typ:=ret_charset;
            ep^.chars:=[];
            ep^.elsepath:=elsepath;
            elsepath:=ep;}
            while true do
              begin
                 if error then
                   exit;
                 case currentpos^ of
                    '(':
                       begin
                          inc(currentpos);
                          hp:=parseregexpr(nil,nil);
                          { Special characters after the bracket }
                           if error then
                              exit;
                          if currentpos^<>')' then
                            begin
                               error:=true;
                               exit;
                            end;
                          inc(currentpos);
                            case currentpos^ of
                            '*':
                               begin
                                  inc(currentpos);
                                  new(hp3);
                                  doregister(hp3);
                                  hp3^.typ:=ret_pattern;
                                  hp3^.alternative:=nil;
                                  hp3^.pattern:=hp;
                                  hp3^.elsepath:=elsepath;
                                  hp3^.minoccurs:=0;
                                  hp3^.maxoccurs:=high(integer);
                                  hp3^.next:=nil;
                                  if assigned(chaining) then
                                    chaining^:=hp3
                                  else
                                    parseregexpr:=hp3;
                                  chaining:=@hp3^.next;
                               end;
                            '+':
                               begin
                                  inc(currentpos);
                                  new(hp3);
                                  doregister(hp3);
                                  hp3^.typ:=ret_pattern;
                                  hp3^.alternative:=nil;
                                  hp3^.pattern:=hp;
                                  hp3^.elsepath:=elsepath;
                                  hp3^.minoccurs:=1;
                                  hp3^.maxoccurs:=high(integer);
                                  hp3^.next:=nil;
                                  if assigned(chaining) then
                                    chaining^:=hp3
                                  else
                                    parseregexpr:=hp3;
                                  chaining:=@hp3^.next;
                               end;

                            '?':
                               begin
                                  inc(currentpos);
                                  new(hp3);
                                  doregister(hp3);
                                  hp3^.typ:=ret_pattern;
                                  hp3^.alternative:=nil;
                                  hp3^.pattern:=hp;
                                  hp3^.elsepath:=elsepath;
                                  hp3^.minoccurs:=0;
                                  hp3^.maxoccurs:=1;
                                  hp3^.next:=nil;
                                  if assigned(chaining) then
                                    chaining^:=hp3
                                  else
                                    parseregexpr:=hp3;
                                  chaining:=@hp3^.next;
                               end;
                            '{':
                               begin
                                 if not parseOccurences(currentPos,minOccurs,maxOccurs) then
                                   exit;
                                  inc(currentpos);
                                  new(hp3);
                                  doregister(hp3);
                                  hp3^.typ:=ret_pattern;
                                  hp3^.alternative:=nil;
                                  hp3^.pattern:=hp;
                                  hp3^.elsepath:=elsepath;
                                  hp3^.minoccurs:=minOccurs;
                                  hp3^.maxoccurs:=maxOccurs;
                                  hp3^.next:=nil;
                                  if assigned(chaining) then
                                    chaining^:=hp3
                                  else
                                    parseregexpr:=hp3;
                                  chaining:=@hp3^.next;
                               end;
                            else
                              begin
                                { go to end of this list - always the
                                  last next used }
(*
                                hp3:=hp;
                                while assigned(hp3^.next) do
                                  begin
                                    hp3:=hp3^.next;
                                  end;
                                if assigned(chaining) then
                                   chaining^:=hp
                                else
                                   parseregexpr:=hp;
                                chaining:=@hp3^.next;*)
                                  new(hp3);
                                  doregister(hp3);
                                  hp3^.typ:=ret_pattern;
                                  hp3^.alternative:=nil;
                                  hp3^.pattern:=hp;
                                  hp3^.elsepath:=elsepath;
                                  hp3^.minoccurs:=1;
                                  hp3^.maxoccurs:=1;
                                  hp3^.next:=nil;
                                  if assigned(chaining) then
                                    chaining^:=hp3
                                  else
                                    parseregexpr:=hp3;
                                  chaining:=@hp3^.next;

                              end;
                          end;
                       end;
{ This is only partially implemented currently, as the terms before
  the | character must be grouped together with parenthesis, which
  is also compatible with other regular expressions.
}
                    '|':
                       begin
{$ifdef DEBUG}
                          writeln('Creating or entry');
{$endif DEBUG}
                          if (not assigned (hp3)) then
                            begin
                              error:=true;
                              exit;
                            end;
                          if (hp3^.typ <> ret_pattern) then
                            begin
                              error:=true;
                              exit;
                            end;
                          while currentpos^='|' do
                            begin
                              inc(currentpos);
                              if currentpos^=#0 then
                                begin
                                   error:=true;
                                   exit;
                                end;
                              { always put the longest pattern first, so
                                swap the trees as necessary.
                              }
                              hp := parseregexpr (next, elsepath);
                              if patlength(hp) > patlength(hp3^.pattern) then
                                begin
                                  hp3^.alternative:=hp3^.pattern;
                                  hp3^.pattern:=hp;
                                end
                              else
                                 hp3^.alternative:=hp;
                            end;
                       end;
                    ')':
                       exit;
                    '^':
                       begin
                          inc(currentpos);
                          hp:=parseregexpr(nil,nil);
                          { Special characters after the bracket }
                           if error then
                              exit;
                           new(hp3);
                           doregister(hp3);
                           hp3^.typ:=ret_startline;
                           hp3^.pattern:=hp;
                           hp3^.elsepath:=elsepath;
                           hp3^.next:=nil;
                           if assigned(chaining) then
                              chaining^:=hp3
                           else
                              parseregexpr:=hp3;
                           chaining:=@hp3^.next;
                       end;
                    '$':
                       begin
                          inc(currentpos);
                          new(hp);
                          doregister(hp);
                          hp^.typ:=ret_endline;
                          hp^.elsepath:=elsepath;
                          hp^.next:=nil;
                          if assigned(chaining) then
                            chaining^:=hp
                          else
                            parseregexpr:=hp;
                          chaining:=@hp^.next;
                       end;
                    #0:
                       exit;
                    else
                      begin
                         readcharset(cs);
                         if error then
                           exit;
                         case currentpos^ of
                            '*':
                               begin
                                  inc(currentpos);
                                  new(hp);
                                  doregister(hp);
                                  hp^.typ:=ret_charset;
                                  hp^.chars:=cs;
                                  hp^.elsepath:=nil;
                                  hp^.next:=nil;
                                  new(hp3);
                                  doregister(hp3);
                                  hp3^.typ:=ret_pattern;
                                  hp3^.alternative:=nil;
                                  hp3^.pattern:=hp;
                                  hp3^.elsepath:=elsepath;
                                  hp3^.minoccurs:=0;
                                  hp3^.maxoccurs:=high(integer);
                                  hp3^.next:=nil;
                                  if assigned(chaining) then
                                    chaining^:=hp3
                                  else
                                    parseregexpr:=hp3;
                                  chaining:=@hp3^.next;
                               end;
                            '+':
                               begin
                                  inc(currentpos);
                                  new(hp);
                                  doregister(hp);
                                  hp^.typ:=ret_charset;
                                  hp^.chars:=cs;
                                  hp^.elsepath:=nil;
                                  hp^.next:=nil;

                                  new(hp3);
                                  doregister(hp3);
                                  hp3^.typ:=ret_pattern;
                                  hp3^.alternative:=nil;
                                  hp3^.pattern:=hp;
                                  hp3^.elsepath:=elsepath;
                                  hp3^.minoccurs:=1;
                                  hp3^.maxoccurs:=high(integer);
                                  hp3^.next:=nil;
                                  if assigned(chaining) then
                                    chaining^:=hp3
                                  else
                                    parseregexpr:=hp3;
                                  chaining:=@hp3^.next;
                               end;
                            '?':
                               begin
                                  inc(currentpos);
                                  new(hp);
                                  doregister(hp);
                                  hp^.typ:=ret_charset;
                                  hp^.chars:=cs;
                                  hp^.elsepath:=nil;
                                  hp^.next:=nil;

                                  new(hp3);
                                  doregister(hp3);
                                  hp3^.typ:=ret_pattern;
                                  hp3^.pattern:=hp;
                                  hp3^.alternative:=nil;
                                  hp3^.elsepath:=elsepath;
                                  hp3^.minoccurs:=0;
                                  hp3^.maxoccurs:=1;
                                  hp3^.next:=nil;
                                  if assigned(chaining) then
                                    chaining^:=hp3
                                  else
                                    parseregexpr:=hp3;
                                  chaining:=@hp3^.next;
                               end;
                            '{':
                               begin
                                 if not parseOccurences(currentPos,minOccurs,maxOccurs) then
                                   exit;
                                  new(hp);
                                  doregister(hp);
                                  hp^.typ:=ret_charset;
                                  hp^.chars:=cs;
                                  hp^.elsepath:=nil;
                                  hp^.next:=nil;

                                  new(hp3);
                                  doregister(hp3);
                                  hp3^.typ:=ret_pattern;
                                  hp3^.alternative:=nil;
                                  hp3^.pattern:=hp;
                                  hp3^.elsepath:=elsepath;
                                  hp3^.minoccurs:=minOccurs;
                                  hp3^.maxoccurs:=maxOccurs;
                                  hp3^.next:=nil;
                                  if assigned(chaining) then
                                    chaining^:=hp3
                                  else
                                    parseregexpr:=hp3;
                                  chaining:=@hp3^.next;

                                end;
                            else
                               { Normal character }
                               begin
                                  new(hp);
                                  doregister(hp);
                                  hp^.typ:=ret_charset;
                                  hp^.chars:=cs;
                                  hp^.elsepath:=elsepath;
                                  hp^.next:=next;
                                  if assigned(chaining) then
                                    chaining^:=hp
                                  else
                                    parseregexpr:=hp;
                                  chaining:=@hp^.next;
                                  continue;
                               end;
                           { This was a pattern }
                         end; { END CASE }
                      end;
                 end;
              end;
         end;

       var
          endp : pregexprentry;

       begin
          GenerateRegExprEngine:=false;
          RegExprEngine.Data:=nil;
          RegExprEngine.DestroyList:=nil;
          if regexpr=nil then
            exit;
          first:=nil;
          if (ref_singleline in flags) and (ref_multiline in flags) then
            exit;
          currentpos:=regexpr;
          GenerateRegExprEngine:=true;
          error:=false;
          new(endp);
          doregister(endp);
          endp^.typ:=ret_illegalend;
          RegExprEngine.flags:=flags;
          RegExprEngine.Data:=parseregexpr(nil,endp);
{$IFDEF DEBUG}
          writeln('========== Generating tree ============');
          dumptree('',RegExprEngine.Data);
{$ENDIF}
          RegExprEngine.DestroyList:=first;
          if error or (currentpos^<>#0) then
            begin
              GenerateRegExprEngine:=false;
              DestroyRegExprEngine(RegExprEngine);
            end;
       end;


{$IFDEF FPC}
    function GenerateRegExprEngine(regexpr : pchar;flags : tregexprflags): TREGExprEngine;
    var
     r: TRegExprEngine;
    begin
      GenerateRegExprEngine(regexpr,flags,r);
      GenerateRegExprEngine:=r;
    end;
{$ENDIF}

    procedure DestroyRegExprEngine(var regexpr : TRegExprEngine);

       var
          hp : pregexprentry;

       begin
          hp:=regexpr.DestroyList;
          while assigned(hp) do
            begin
               regexpr.DestroyList:=hp^.nextdestroy;
               dispose(hp);
               hp:=regexpr.DestroyList;
            end;
          regexpr.Data:=nil;
          regexpr.DestroyList:=nil;
       end;

     function RegExprPos(regexprengine : TRegExprEngine;p : pchar;var index,len : longint) : boolean;

       var
          lastpos : pchar;
          firstpos: pchar;

       { Does the actual search of the data - return true if the term was found }
       function dosearch(regexprentry : pregexprentry;pos : pchar) : boolean;
       var
          found: boolean;
          checkvalue: boolean;
          savedpos: pchar;
          counter: word;

         begin
            dosearch:=false;
            while true do
              begin
                 {$IFDEF Debug}
                 writeln('Entering ',typ2str[regexprentry^.typ]);
                 writeln('Pattern length ',patlength(regexprentry));
                 {$ENDIF Debug}
                 case regexprentry^.typ of
                    ret_endline:
                      begin
                         { automatically a match! }
                         if pos^ = #0 then
                            begin
                              dosearch:=true;
                              exit;
                            end;
                         if ref_multiline in regexprengine.flags then
                            begin
                              { Supports DOS/Commodore/UNIX/IBM Mainframe line formats }
                              { avoid reading invalid memory also }
                                  if (pos^=#13) and ((pos+1)^=#10) then
                                    begin
                                      regexprentry:=regexprentry^.next;
                                    end
                                  else
                                  if (pos^=#$85) or (pos^=#10) or ((pos^=#13) and ((pos-1) >= firstpos) and ((pos-1)^ <> #10)) then
                                    begin
                                       regexprentry:=regexprentry^.next;
                                    end
                                  else
                                    begin
                                       dosearch:=false;
                                       exit;
                                    end;
                             end
                           else
                             exit;
                      end;
                    ret_pattern:
                      begin
                         found:=false;
                         { Take care of occurences here }
                         savedpos:=pos;
                         counter:=0;
                         repeat
                           found:=dosearch(regexprentry^.pattern,pos);
                           if not found then
                            break;
                           pos:=lastpos;
                           inc(counter);
                         until (not found) or (counter >= regexprentry^.maxoccurs) or (pos^= #0);

                         if counter = 0 then
                           begin
                             { If there was no occurence and the minimum occurence is > 0 then
                               problem.
                             }
                             if (regexprentry^.minoccurs > 0) then
                              begin
                                dosearch:=false;
                                { verify alternative path as required }
                                if assigned(regexprentry^.alternative) then
                                  begin
                                     dosearch:=dosearch(regexprentry^.alternative,savedpos);
                                     exit;
                                  end;
                                exit;
                              end;
                             dosearch:=true;
                             lastpos:=savedpos;
                           end
                         else
                           { found }
                           begin
                              { Possible choices :
                                 - found and (counter >= minOccurences) and (counter =< maxOccurences) = true
                                 - found and (counter < minOccurences) or (counter > maxOccurences) = false
                              }
                              if (counter < regexprentry^.minoccurs) or (counter > regexprentry^.maxoccurs) then
                                begin
                                  dosearch:=false;
                                  exit;
                                end;
                              dosearch:=true;
                              { if all matches were found, and the current position
                                points to zero (processed all characters) }
                              if pos^=#0 then
                                begin
                                  dosearch:=true;
                                  exit;
                                end;
                           end;
                         { If we are that means the matches were valid, go to next element to match
                         }
                         regexprentry:=regexprentry^.next;
                         if (counter = 0) and not assigned(regexprentry) then
                           exit;
                      end;
                    ret_startline:
                      begin
                         checkvalue:=pos=firstpos;
                         if ref_multiline in regexprengine.flags then
                           begin
                             { Supports DOS/Commodore/UNIX/IBM Mainframe line formats }
                             { avoid reading invalid memory also }
                             if
                                 (
                                   ((pos-1) >= firstpos) and ((pos-1)^=#$85)
                                  )
                              or
                                 (
                                   ((pos-1) >= firstpos) and ((pos-1)^=#10)
                                  )
                              or
                                (
                                 ((pos-1) >= firstpos) and ((pos-1)^=#13) and
                                 ((pos)^ <> #10)
                                )
                             then
                               begin
                                 checkvalue:=true;
                               end;
                           end;
                          if checkvalue then
                            begin
                              dosearch:=dosearch(regexprentry^.pattern,pos);
                              regexprentry:=regexprentry^.next;
                              if not dosearch then
                                exit;
                              pos:=lastpos;
                            end
                          else
                            begin
                              dosearch:=false;
                              exit;
                            end;
                      end;
                    ret_charset:
                      begin
                         if (pos^ in regexprentry^.chars) or
                           ((ref_caseinsensitive in regexprengine.flags) and
                            (upcase(pos^) in regexprentry^.chars)) then
                           begin
{$ifdef DEBUG}
                              writeln('Found matching: ',pos^);
{$endif DEBUG}
                              regexprentry:=regexprentry^.next;
                              inc(pos);
                           end
                         else
                           begin
{$ifdef DEBUG}
                              writeln('Found unmatching: ',pos^);
{$endif DEBUG}
                              exit;
                           end;
                      end;
                    ret_backtrace:
                      begin
{$ifdef DEBUG}
                         writeln('Starting backtrace');
{$endif DEBUG}
                         if dosearch(regexprentry^.next,pos) then
                           begin
                              dosearch:=true;
                              exit;
                           end
                         else if dosearch(regexprentry^.elsepath,pos) then
                           begin
                              dosearch:=true;
                              exit;
                           end
                         else
                           exit;
                      end;
                 end;
                 lastpos:=pos;
                 if regexprentry=nil then
                   begin
                      dosearch:=true;
                      exit;
                   end;
                 if regexprentry^.typ=ret_illegalend then
                   exit;
                 { end of string, and we were expecting an end of string }
                 if (pos^=#0) and (regexprentry^.typ = ret_endline) and
                    (not assigned(regexprentry^.next)) then
                   begin
                     dosearch:=true;
                     exit;
                   end;
                 if pos^=#0 then
                   exit;
              end;
         end;

       begin
          RegExprPos:=false;
          index:=0;
          len:=0;
          firstpos:=p;
          if regexprengine.Data=nil then
            exit;
          while p^<>#0 do
            begin
               if dosearch(regexprengine.Data,p) then
                 begin
                    len:=lastpos-p;
                    RegExprPos:=true;
                    exit;
                 end
               else
                 begin
                    inc(p);
                    inc(index);
                 end;
            end;
          index:=-1;
       end;


  function RegExprReplaceAll(RegExprEngine : TRegExprEngine;const src,newstr : ansistring;var dest : ansistring) : sizeint;
    var
      index,len : longint;
      pos,lastpos : pchar;
      first : boolean;
      oldlength : PtrInt;
    begin
      pos:=pchar(src);
      lastpos:=nil;
      first:=true;
      Result:=0;
      { estimate some length }
      SetLength(dest,length(src)+((length(src) div 10)*length(newstr)));
      while RegExprPos(RegExprEngine,pos,index,len) do
        begin
          inc(pos,index);
          if (lastpos = nil) or (pos>lastpos) then
            begin
              if lastpos = nil then lastpos := pchar(src);
              { copy skipped part }

              { because we cheat with SetLength a SetLength(...,0) isn't what we want
                so we've to trick at the first SetLength call
              }
              if first then
                begin
                  SetLength(dest,(pos-lastpos));
                  { cast dest here because it is already unified }
                  move(lastpos^,char(dest[1]),pos-lastpos);
                end
              else
                begin
                  oldlength:=Length(dest);
                  SetLength(dest,oldlength+(pos-lastpos));
                  move(lastpos^,char(dest[oldlength+1]),pos-lastpos);
                end;
              first:=false;
            end;
          { found }
          inc(Result);
          dest:=dest+newstr;
          inc(pos,len);
          lastpos:=pos;
        end;
      { copy remainder }
      len:=strlen(pos);
      if first then
        begin
          SetLength(dest,len);
          move(pos^,char(dest[length(dest)+1]),len);
        end
      else
        begin
          oldlength:=Length(dest);
          SetLength(dest,oldlength+len);
          move(pos^,char(dest[oldlength+1]),len);
        end
    end;


  function RegExprEscapeStr (const S : string) : string;
    var
     i, len   : integer;
     s1: string;
    begin
      RegExprEscapeStr:= '';
      s1:='';
      if (S = '') then
       exit;

      len := Length (S);

      for i := 1 to len do
        begin
          if (S [i] in ['(','|', '.', '*', '?', '^', '$', '-', '[', '{', '}', ']', ')', '\']) then
            begin
              s1 := s1 + '\';
            end;

          s1 := s1 + S[i];
        end;
      RegExprEscapeStr:=s1;
    end;

begin
   cs_nonwordchars:=cs_allchars-cs_wordchars;
   cs_nondigits:=cs_allchars-cs_digits;
   cs_nonwhitespace:=cs_allchars-cs_whitespace;
end.