File: regex.c

package info (click to toggle)
hexer 0.1.5-3
  • links: PTS, VCS
  • area: main
  • in suites: squeeze
  • size: 724 kB
  • ctags: 967
  • sloc: ansic: 12,189; makefile: 99
file content (1751 lines) | stat: -rw-r--r-- 50,764 bytes parent folder | download
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
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
/* regex.c	8/19/1995
 * Regular expressions, version 0.3
 *
 * This file provides a set of functions for dealing with binary regular
 * expressions, where binary means that some extesions have been made to
 * the standard UN*X-regular expressions making it possible to search for
 * an arbitrary byte pattern.
 *
 * NOTE:  In some esoteric cases the function `regex_match()' does not find
 *   the longest string that matches a given regex.  Example:
 *   the expression
 *     a*\(abcd\|bc\)
 *   doesn't not match the whole string `aaabcd' but only the substring
 *   `aaabc`.  I'm not sure if this is a bug, since `vi' and 'vim' do the
 *   same.
 */

/* Copyright (c) 1995,1996 Sascha Demetrio
 * Copyright (c) 2009 Peter Pentchev
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 *    If you modify any part of HEXER and resitribute it, you must add
 *    a notice to the `README' file and the modified source files containing
 *    information about the  changes you made.  I do not want to take
 *    credit or be blamed for your modifications.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 *    If you modify any part of HEXER and resitribute it in binary form,
 *    you must supply a `README' file containing information about the
 *    changes you made.
 * 3. The name of the developer may not be used to endorse or promote
 *    products derived from this software without specific prior written
 *    permission.
 *
 * HEXER WAS DEVELOPED BY SASCHA DEMETRIO.
 * THIS SOFTWARE SHOULD NOT BE CONSIDERED TO BE A COMMERCIAL PRODUCT.
 * THE DEVELOPER URGES THAT USERS WHO REQUIRE A COMMERCIAL PRODUCT
 * NOT MAKE USE OF THIS WORK.
 *
 * DISCLAIMER:
 * THIS SOFTWARE IS PROVIDED BY THE DEVELOPER ``AS IS'' AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
 * ARE DISCLAIMED.  IN NO EVENT SHALL THE DEVELOPER BE LIABLE
 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
 * SUCH DAMAGE.
 */

#include <stdio.h>
#include <assert.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>

#include "defs.h"

#undef EOF

#include "regex.h"

#define REGEX_MAXMATCH_DFL (1 << 10) /* default value for `rx_maxmatch'. */
#define REGEX_MAX_PARS (64) /* the maximum number of opened parentheses */
#define REGEX_MAX_BRANCH (64) /* the maximum number of branches per command */
#define REGEX_BLOCKSIZE_EXP 12

#define REGEX_BLOCKSIZE (1 << REGEX_BLOCKSIZE_EXP)
#define REGEX_BLOCKMASK (REGEX_BLOCKSIZE - 1)

/* The linear encoding of the RE generated by `regex_compile()' and
 * executed by `regex_match()' is:
 * (long ro)    `ro' is the offset of the replace code of the expression.
 * <search expression>
 *              the search expression may contain any of the commands below;
 *              each expression and subexpression is terminated with an
 *              `EOX' (end of expression) command.
 * (long 0)     a zero long is placed between the search expression and the
 *              replace expression.  there's no technical reason for that,
 *              it just makes the debugging a little bit easier.
 * <replace expression>
 *              the replace expression is made up of `STRING' and
 *              `BACKREF'-commands. it's terminated with an `EOX'-command.
 *              this part may be empty.
 * (long 0)     a trailing 0, just for fun.
 */

enum regex_e {  /* arguments
                 *   description. */

  ANY_CHAR = 1, /*   matches any character. */
  ANY_OF,       /* (char n) <list of `n' characters>
                 *   matches any of the characters in the list.  the list
		 *   has to be sorted. */
  ANY_BUT,      /* (char n) <list of `n' characters>
                 *   matches any but the listed characters.  the list has to
		 *   be sorted. */
  CHAR,         /* (char c)
                 *   matches the character `c'. */
  STRING,       /* (long n) <string of length `n'>
                 *   matches the given string exactly.  the null-character is
		 *   *not* interpreted as the end of the string. */
  PAR_OPEN,     /*   opening parenthesis. */
  PAR_CLOSE,    /* (long slot)
                 *   closing parenthesis.  the input matched since the last
		 *   unmatched opening parenthesis is stored in slot `n'. */
  BACKREF,      /* (long slot)
                 *   matches the string stored in the given slot exactly.
		 *   if the slot is undefined, it matches the empty string. */
  BRANCH,       /* (long n) (long m)
                 *   the following `n' bytes are two (`EOX'-terminated,
		 *   respectively) expressions, the first of which is `m'
		 *   bytes long.  these expressions are read as two alternate
		 *   branches. */
  REPEAT,       /* (long min) (long max) (long n)
                 *   the following `n' bytes are an `EOX'-terminated
		 *   expression E.  the `REPEAT'-expression R matches, if E
		 *   matches at least `min' succsessive strings.  R matches
		 *   at most `max' succsessive E strings.  if `max < 0',
		 *   `max' is set to `rx_maxmatch'. */
  FIXREPEAT,    /* (long min) (long max) (long len) (long n)
                 *   works like `REPEAT', but all matches found have to be
		 *   of the same (fixed) length `len'.  if `max < 0',
		 *   `max' is set to infinity, i.e. the number of matches
		 *   is not limited by `rx_maxmatch'. */
  BEGIN_WORD,   /*   matches the empty string, if it is preceded immediately
                 *   by the beginning of the buffer/file or a
		 *   non-alphanumerical character that is not an underscore. */
  END_WORD,     /*   matches the empty string, if it is followed immediately
                 *   by the end of the buffer/file or a non-alphanumerical
		 *   character that is not an underscore. */
  BEGIN_LINE,   /*   matches the empty string at the beginning of a line. */
  END_LINE,     /*   matches the empty string at the end of a line.
                 *   `\n' and `\r' are treated as end-of-line markers. */
  EOF,          /*   matches the empty string at the end of the file. */
  EOX           /*   end-of-expression.  */
};

#define SIZE_BRANCH 3
#define SIZE_REPEAT 4
#define SIZE_FIXREPEAT 5

enum error_e {
  E_no_error = 0,
  E_invalid_range,
  E_invalid_character,
  E_unmatched_opening_parenthesis,
  E_unmatched_closing_parenthesis,
  E_operator_without_operand,
  E_malformed_operator,
  E_operand_with_variable_length,
  E_unmatched_bracket,
  E_interrupt
};

char *rx_error_msg[] = {
  "", /* no error */ "invalid range", "invalid character", "unmatched `('",
  "unmatched `)'", "operator without operand", "malformed operator",
  "operand of `++' and `**' must have fixed length", "unmatched `['",
  "interrupted", 0
};

int rx_error;
static int interrupt = 0;
volatile int *rx_interrupt = &interrupt;

#undef isoct
#undef ishex
#define isoct(x) ((x) >= '0' && (x) < '8')
#define ishex(x) (isdigit(x) || (tolower(x) >= 'a' && tolower(x) <= 'f'))

#undef u_char
#undef u_short
#undef u_long
#define u_char unsigned char
#define u_short unsigned short
#define u_long unsigned long

static long (*rx_read)(char *target, long count);
  /* pointer to a function used for reading from the buffer/file.
   */
static long (*rx_seek)(long position);
  /* pointer to a function used for setting the pointer in the buffer/file.
   */
static long (*rx_tell)(void);
  /* pointer to a function returning the current position if the buffer/file.
   */
static long rx_size = 0;
  /* `rx_size == 0': the end of the buffer/file has not yet been hit.
   *   that means there are at least `REGEX_BLOCKSIZE' unread characters
   *   left.
   * `rx_size > 0': the end of the buffer/file has been hit.  the size of
   *   the buffer/file is `rx_size'.
   */
static int rx_start;
  /* character that a match has to start with.  if `rx_start == -1', matches
   * may start with different characters.
   */
static long rx_match_skip;
  /* if `regex_match()' (`regex_match_()' actually) matches an expression
   * (or subexpression), `rx_match_skip' is set to the position next
   * to the last character of that match.
   */

int rx_nomagic = 0;
  /* `rx_nomagic == 1': all special characters exept `*' and `[' have to be
   *   prefixed with `\'.
   */
int rx_allmagic = 0;
  /* `rx_allmagic == 1': special characters don't have to be prefixed
   *   with `\'.
   */
long rx_maxmatch = REGEX_MAXMATCH_DFL;
  /* `rx_maxmatch' is the maximum number of matches a repeat operator
   * can match, i.e. the search string `.*' matches at most `rx_maxmatch'
   * characters.
   */

int rx_special_nl = 0;
  /* if `rx_special_nl' is set, the newline character (0xa) is treated as a
   * special cahacter, i.e. the dot and `ANY_BUT'-ranges ("[^...]") do
   * *not* match a newline character.
   */

static char buffer_[3 * REGEX_BLOCKSIZE];
static char *buffer = buffer_ + REGEX_BLOCKSIZE;
static char *bp;
static long buffer_base;

#define REGEX_ADVANCE {                                                       \
  if (bp >= buffer + REGEX_BLOCKSIZE) {                                       \
    long ii;                                                                   \
    rx_memmove(buffer - REGEX_BLOCKSIZE, buffer, 2 * REGEX_BLOCKSIZE);        \
    buffer_base += REGEX_BLOCKSIZE;                                           \
    rx_seek(buffer_base + REGEX_BLOCKSIZE);                                   \
    ii = rx_read(buffer + REGEX_BLOCKSIZE, REGEX_BLOCKSIZE);                   \
    if (ii < REGEX_BLOCKSIZE) {                                                \
      rx_size = buffer_base + REGEX_BLOCKSIZE + ii;                            \
      memset(buffer + REGEX_BLOCKSIZE + ii, 0, REGEX_BLOCKSIZE - ii);           \
    }                                                                         \
    bp -= REGEX_BLOCKSIZE;                                                    \
  } else if (bp < buffer) {                                                   \
    rx_memmove(buffer + REGEX_BLOCKSIZE, buffer, REGEX_BLOCKSIZE);            \
    buffer_base -= REGEX_BLOCKSIZE;                                           \
    if (position >= REGEX_BLOCKSIZE) {                                        \
      rx_seek(buffer_base - REGEX_BLOCKSIZE);                                 \
      rx_read(buffer - REGEX_BLOCKSIZE, 2 * REGEX_BLOCKSIZE);                 \
    } else {                                                                  \
      rx_seek(buffer_base);                                                   \
      rx_read(buffer, REGEX_BLOCKSIZE);                                       \
    }                                                                         \
    bp += REGEX_BLOCKSIZE;                                                    \
  }                                                                           \
}

#if !HAVE_MEMMOVE
  static void
rx_memmove(char *t, const char *s, const long count)
{
  register long i;

  if (t > s)
    for (i = count - 1; i >= 0; --i) t[i] = s[i];
  else
    for (i = 0; i < count; ++i) t[i] = s[i];
}
/* rx_memmove */
#else
#define rx_memmove(a, b, c) (void)memmove(a, b, c)
#endif

  int
regex_init(long (*read)(char *, long), long (*seek)(long), long (*tell)(void))
{
  rx_read = read;
  rx_seek = seek;
  rx_tell = tell;
  return 0;
}
/* regex_init */

  static int
regex_set_position(long position)
  /* NOTE: `bp' and `buffer_base' *must* be initialized before calling
   *   `regex_set_position'.
   */
{
  long i;

  if (position - buffer_base >= 0) {
    if (position - buffer_base > REGEX_BLOCKSIZE) {
      if (position - buffer_base < 2 * REGEX_BLOCKSIZE) {
	bp = buffer + (position & REGEX_BLOCKMASK);
	rx_memmove(buffer - REGEX_BLOCKSIZE, buffer, 2 * REGEX_BLOCKSIZE);
	buffer_base += REGEX_BLOCKSIZE;
	rx_seek(buffer_base);
	i = rx_read(buffer + REGEX_BLOCKSIZE, REGEX_BLOCKSIZE);
	if (i < REGEX_BLOCKSIZE) {
	  rx_size = buffer_base + i;
	  memset(buffer + REGEX_BLOCKSIZE + i, 0, REGEX_BLOCKSIZE - i);
	}
	return 0;
      } else
        goto rebuild_buffer;
    }
    bp = buffer + (position & REGEX_BLOCKMASK);
    return 0;
  }

rebuild_buffer:
  bp = buffer + (position & REGEX_BLOCKMASK);
  buffer_base = position & ~REGEX_BLOCKMASK;
  rx_seek(buffer_base);
  i = rx_read(buffer, 2 * REGEX_BLOCKSIZE);
  if (i < 2 * REGEX_BLOCKSIZE) {
    rx_size = buffer_base + i;
    memset(buffer + i, 0, 2 * REGEX_BLOCKSIZE - i);
  }
  return 0;
}
/* regex_set_position */

#define RX_NSLOTS 256

static long rx_store_begin[RX_NSLOTS];
static long rx_store_end[RX_NSLOTS];
static char *rx_store_match[RX_NSLOTS];
static int rx_store_initialized = 0;

  static int
regex_store(long slot, long begin, long end)
  /* The text between the positions `begin' (incl.) and `end' (excl.) is
   * stored in slot `slot'.  (Actually only the `begin' and `end' positions
   * are stored.)
   */
{
  assert(slot >= 0 && slot < RX_NSLOTS);
  assert(end >= begin);
  if (!rx_store_initialized) {
    memset(rx_store_begin, 0, RX_NSLOTS * sizeof(long));
    memset(rx_store_end, 0, RX_NSLOTS * sizeof(long));
    memset(rx_store_match, 0, RX_NSLOTS * sizeof(char *));
    rx_store_initialized = 1;
  }
  if (rx_store_match[slot]) {
    free((char *)rx_store_match[slot]);
    rx_store_match[slot] = 0;
  }
  rx_store_begin[slot] = begin;
  rx_store_end[slot] = end;
  return 0;
}
/* regex_store */

  static char *
regex_ref(int slot)
  /* The contents of undefined slots default to an empty string, therefore
   * the return value is always a valid (non-zero) pointer.
   */
{
  long position, count;

  assert(slot >= 0 && slot < RX_NSLOTS);
  if (!rx_store_initialized) {
    memset(rx_store_begin, 0, RX_NSLOTS * sizeof(long));
    memset(rx_store_end, 0, RX_NSLOTS * sizeof(long));
    memset(rx_store_match, 0, RX_NSLOTS * sizeof(char *));
    rx_store_initialized = 1;
  }
  position = rx_store_begin[slot];
  count = rx_store_end[slot] - position;
  if (!rx_store_match[slot] && count) {
    rx_store_match[slot] = malloc(count);
    rx_seek(position);
    rx_read(rx_store_match[slot], count);
    return rx_store_match[slot];
  } else if (rx_store_match[slot])
    return rx_store_match[slot];
  else
    return "";
}
/* regex_ref */

  static long
regex_ref_len(int slot)
  /* The length of an undefined slot is 0.
   */
{
  long position, count;

  assert(slot >= 0 && slot < RX_NSLOTS);
  if (!rx_store_initialized) {
    memset(rx_store_begin, 0, RX_NSLOTS * sizeof(long));
    memset(rx_store_end, 0, RX_NSLOTS * sizeof(long));
    memset(rx_store_match, 0, RX_NSLOTS * sizeof(char *));
    rx_store_initialized = 1;
  }
  position = rx_store_begin[slot];
  count = rx_store_end[slot] - position;
  return count;
}
/* regex_ref_len */

  static void
regex_clear(void)
  /* clear all slots.
   */
{
  int i;

  if (!rx_store_initialized) {
    memset(rx_store_begin, 0, RX_NSLOTS * sizeof(long));
    memset(rx_store_end, 0, RX_NSLOTS * sizeof(long));
    memset(rx_store_match, 0, RX_NSLOTS * sizeof(char *));
    rx_store_initialized = 1;
  } else {
    for (i = 0; i < RX_NSLOTS; ++i) {
      if (rx_store_match[i]) {
	free((char *)rx_store_match[i]);
	rx_store_match[i] = 0;
      }
      rx_store_begin[i] = rx_store_end[i] = 0;
    }
  }
}
/* regex_clear */

  int
regex_reset()
{
  rx_error = 0;

  return 0;
}
/* regex_reset */

  long
regex_search(regex, begin, end, start, direction,
             replace_str, replace_len, match_len)
  long *regex;
  long begin;
  long end;
  long start;
  int direction; /* >=0: forward; <0: reverse. */
  char **replace_str;
  long *replace_len;  /* the replace-string for the match is written to
		       * `*replace_str'/`replace_len'.  the memory for
		       * `*replace_str' is allocated by `regex_match()'
		       * via `malloc()'. */
  long *match_len;
{
  long position;
  int i;
  char *bp1;
  long base1;

  direction = direction < 0 ? -1 : 1;
  if (end < 0) end = (u_long)~0 >> 1;
  position = start;

  /* initialize the buffer */
  bp = buffer + (position & REGEX_BLOCKMASK);
  buffer_base = position & ~REGEX_BLOCKMASK;
  rx_seek(buffer_base);
  i = rx_read(buffer, 2 * REGEX_BLOCKSIZE);
  if (i < 2 * REGEX_BLOCKSIZE) {
    rx_size = buffer_base + i;
    memset(buffer + i, 0, 2 * REGEX_BLOCKSIZE - i);
  } else
    rx_size = 0;

  if (rx_size && end > rx_size) end = rx_size;
  if (rx_size && position >= rx_size) position = rx_size - 1;
  while (position < end && position >= begin) {
    if (rx_start >= 0)
      while (*bp != rx_start && position < end) {
	if (*rx_interrupt) {
	  rx_error = (int)E_interrupt;
          *rx_interrupt = 0;
	  regex_clear();
	  return -1;
	}
	bp += direction;
	position += direction;
	REGEX_ADVANCE;
	if (rx_size && end > rx_size) end = rx_size;
      }
    bp1 = bp;
    base1 = buffer_base;
    if (regex_match(regex, position, replace_str, replace_len, match_len))
      return position;
    if (rx_error) return -1;
    if (rx_size && end > rx_size) end = rx_size;
    position += direction;
    if (base1 == buffer_base) {
      bp = bp1 + direction;
      REGEX_ADVANCE;
    } else {
      regex_set_position(position);
      if (rx_size && end > rx_size) end = rx_size;
    }
  }
  return -1;
}
/* regex_search */

  static int
regex_match_(long *regex, long position, int *parstack, int *parsp)
{
  long *pp = regex;
  long p = position;

  enum regex_e opcode;
  long min, max;
  long operand;
  long operand2;
  char *bp1;
  long base1;
  int i;

  int local_parstack[REGEX_MAX_PARS];
  int local_parsp = *parsp;
    /* Stack of unmatched parentheses while running the regex-code.
     */

  for (i = local_parsp - 1; i >= 0; --i) local_parstack[i] = parstack[i];
  if (rx_error) return 0;
  regex_set_position(p);
  for (; !rx_error;) {
    if (*rx_interrupt) {
      rx_error = (int)E_interrupt;
      regex_clear();
      *rx_interrupt = 0;
      return 0;
    }
    if ((opcode = (enum regex_e)*pp++) == EOX) goto match;
    if (rx_size) {
      if (opcode == EOF && p >= rx_size) goto match;
      if (p > rx_size) goto fail;
      if (p == rx_size && opcode != END_WORD && opcode != END_LINE) goto fail;
    }
    assert(local_parsp >= 0);
    switch (opcode) {
      case ANY_CHAR:
        if (rx_special_nl && *bp == '\n') goto fail;
	++p, ++bp;
	break;
      case CHAR:
	if (*bp++ != *pp++) goto fail;
	++p;
	break;
      case STRING:
        operand = *pp++; /* length of the string. */
	if (rx_size && p + operand > rx_size) goto fail;
	/* if (memcmp(bp, pp, operand)) goto fail; */
        for (; operand; --operand) if (*pp++ != *bp++) goto fail;
        /*
	pp += operand;
	bp += operand;
        */
	p += operand;
	break;
      case ANY_OF:
        operand = *pp++; /* number of characters */
	for (i = 0; i < operand && *bp > *pp; ++pp, ++i);
	if (*bp != *pp) goto fail;
	pp += operand - i;
	++p, ++bp;
	break;
      case ANY_BUT:
        operand = *pp++; /* number of characters */
        for (i = 0; i < operand && *bp > *pp; ++pp, ++i);
	if (*bp == *pp) goto fail;
        if (rx_special_nl && *bp == '\n') goto fail;
	pp += operand - i;
	++p, ++bp;
	break;
      case PAR_OPEN:
        local_parstack[local_parsp++] = p;
	break;
      case PAR_CLOSE:
        operand = *pp++; /* number of the slot. */
	regex_store(operand, local_parstack[--local_parsp], p);
	break;
      case BACKREF:
        operand = *pp++; /* number of the slot. */
	if (memcmp(bp, regex_ref(operand), i = regex_ref_len(operand)))
          goto fail;
	bp += i;
	p += i;
	if (i >= REGEX_BLOCKSIZE) regex_set_position(p);
	break;
      case BRANCH:
        operand = *pp++;
        operand2 = *pp++;
	bp1 = bp;
	base1 = buffer_base;
	if (regex_match_(pp, p, local_parstack, &local_parsp)) {
	  /* see if the first branch does the job... */
	  if (regex_match_(pp + operand, rx_match_skip,
                           local_parstack, &local_parsp)) {
	    p = rx_match_skip;
	    goto match;
	      /* NOTE:  this is not really correct, since we might have
	       *   found a longer match if we had taken the other branch,
	       *   but... `vi' does the same. */
	  }
        }
	/* the first branch didn't work, so the second branch has to. */
	pp += operand2;
	if (base1 == buffer_base) bp = bp1; else regex_set_position(p);
	break;
      case FIXREPEAT:
	min = *pp++;
	max = *pp++;
	operand = *pp++;
	operand2 = *pp++;
	for (i = 0; i < min; ++i) {
	  if (!regex_match_(pp, p, local_parstack, &local_parsp)) goto fail;
	  assert(rx_match_skip - p == operand);
	  p = rx_match_skip;
	}
	if (max < 0) max = (long)((u_long)~0 >> 1);
	if (max > min) {
	  long count;
	  long p_rec;
	  for (count = 0, p_rec = p; i < max; ++i) {
	    if (!regex_match_(pp, p, local_parstack, &local_parsp)) break;
	    ++count;
	    assert(rx_match_skip - p == operand);
	    p = rx_match_skip;
	  }
	  pp += operand2;
	  while (count && !rx_error) {
	    if (regex_match_(pp, p, local_parstack, &local_parsp)) {
	      p = rx_match_skip;
	      goto match;
	    }
	    p = p_rec + --count * operand;
	  }
	  regex_set_position(p);
	} else
	  pp += operand2;
	break;
      case REPEAT:
	min = pp[0];
	max = pp[1];
	operand = pp[2];
        pp += 3;
	for (i = 0; i < min; ++i) {
	  if (!regex_match_(pp, p, local_parstack, &local_parsp)) goto fail;
	  p = rx_match_skip;
	  regex_set_position(p);
	}
	if (max < 0) max = rx_maxmatch;
	if (max > min) {
	  long *stack, sp;
	  stack = (long *)malloc((max - min + 1) * sizeof(long));
	  for (sp = 0; max < 0 ? 1 : i < max; ++i) {
	    if (!regex_match_(pp, p, local_parstack, &local_parsp)) break;
	    stack[sp++] = p;
	    p = rx_match_skip;
	  }
	  pp += operand;
	  while (sp && !rx_error) {
	    if (regex_match_(pp, p, local_parstack, &local_parsp)) {
	      p = rx_match_skip;
	      free((char *)stack);
	      goto match;
	    }
	    p = stack[--sp];
	  }
	  regex_set_position(p);
	  free((char *)stack);
	} else
	  pp += operand;
	break;
      case BEGIN_WORD:
        if (!p) break;
        regex_set_position(--p);
	++p, ++bp;
	if (isalnum(bp[-1]) || bp[-1] == '_') goto fail;
        break;
      case END_WORD:
        if (rx_size && p == rx_size) break;
	if (isalnum(bp[0]) || bp[0] == '_') goto fail;
        if (!isalnum(bp[-1]) && bp[-1] != '_') goto fail;
	break;
      case BEGIN_LINE:
        if (!p) break;
	regex_set_position(--p);
	++p, ++bp;
	if (bp[-1] != '\n') goto fail;
	break;
      case END_LINE:
        if (rx_size && p == rx_size) break;
	if (bp[0] != '\n' && bp[0] != '\r') goto fail;
	break;
      case EOF:
        goto fail;
      default:
        abort();
    }
  } /* for */

  goto fail;

match:
  rx_match_skip = p;
  if (parstack) {
    for (i = local_parsp - 1; i >= 0; --i) parstack[i] = local_parstack[i];
    *parsp = local_parsp;
  }
  return 1;

fail:
  return 0;
}
/* regex_match_ */

  int
regex_match(regex, position, replace_str, replace_len, match_len)
  long *regex;        /* pointer to the regex-code to be processed. */
  long position;      /* position in the input stream. */
  char **replace_str;
  long *replace_len;  /* if a match is found at `position',
                       * the replace-string for the match is written to
		       * `*replace_str'/`replace_len'.  the memory for
		       * `*replace_str' is allocated by `regex_match()'
		       * via `malloc()'. */
  long *match_len;    /* if a match is found at `position',
                       * the length of the match is written to
                       * `*match_len'. */
{
  long *pp = regex + *regex;
  int i;
  int zero = 0;

  if (regex_match_(regex + 1, position, 0, &zero)) {
    *match_len = rx_match_skip - position;
    if (!*pp) {
      *replace_str = (char *)malloc(1);
      **replace_str = 0;
      *replace_len = 0;
    } else {
      char *cp;
      long *pp_rec = pp;
      /* store the match to slot 0. */
      regex_store(0, position, rx_match_skip);
      /* check out how long the replace-string will be. */
      for (*replace_len = 0;;) {
	if (*pp == (long)EOX) {
	  ++pp;
	  break;
	}
	switch ((enum regex_e)*pp++) {
	  case STRING:
	    *replace_len += *pp;
	    pp += *pp + 1;
	    break;
	  case CHAR:
	    ++*replace_len;
	    ++pp;
	    break;
	  case BACKREF:
	    *replace_len += regex_ref_len(*pp++);
	    break;
	  default:
	    abort();
	}
      }
      assert(!*pp);
      cp = *replace_str =
        (char *)malloc(*replace_len + !*replace_len);
      for (pp = pp_rec;;) {
	long reflen;
	if (*pp == (long)EOX) break;
	switch ((enum regex_e)*pp++) {
	  case STRING:
            for (i = 0; i < *pp; ++i) cp[i] = pp[i + 1];
	    cp += *pp;
	    pp += *pp + 1;
	    break;
	  case CHAR:
	    *cp++ = *pp++;
	    break;
	  case BACKREF:
	    memcpy(cp, regex_ref(*pp), reflen = regex_ref_len(*pp));
	    cp += reflen;
	    ++pp;
	    break;
	  default:
	    abort();
	}
      }
    }
    return 1;
  }
  return 0;
}
/* regex_match */

  long *
regex_compile(str, replace)
  char *str;
  char *replace;
  /* Compile the regular expression `str' and return a pointer to the
   * compiled regex-code.  If `replace' is non-zero, the string `replace'
   * is interpreted as a replace-string, which may contain `\'-escape
   * sequences including references to parenthesized matches (`\0',
   * `\1', ... `\9'), where `\0' stands for the whole match.
   */
{
# define REGEX_EOF(position) (rx_size ? (position) >= rx_size : 0)
# define EAT_WHITESPACE { while (*cp == ' ' || *cp == '\t') ++cp; }
# define GET_OCT(o, n) {                                                      \
  for ((o) = 0, i = 0; i < (n) && isoct(*cp) && ((o) << 1) >= 0; ++i, ++cp)   \
    (o) *= 8, (o) += *cp - '0'; }
# define GET_HEX(h, n) {                                                      \
  for ((h) = 0, i = 0; i < (n) && ishex(*cp) && ((h) << 1) >= 0; ++i, ++cp)   \
    (h) *= 16, (h) += *cp > '9' ? tolower(*cp) - 'a' + 10 : *cp - '0'; }
# define GET_DEC(d, n) {                                                      \
  for ((d) = 0, i = 0; i < (n) && isdigit(*cp) && ((d) << 1) >= 0; ++i, ++cp) \
    (d) *= 10, (d) += *cp - '0'; }
# define GET_NUMBER(n) {                                                      \
  if (*cp == '0')                                                             \
    if (*++cp == 'x') { ++cp; GET_HEX((n), 32); } else { GET_OCT((n), 32); }  \
  else { GET_DEC((n), 32); } }

  char *cp, *s;

  int pc;
    /* Parentheses counter; number of unmatched parentheses.
     */
  long *par[1024];
    /* Stack of positions of opening parentheses.
     * For `pc > 0', `par[pc]' points to the first regex-command after the
     * `PAR_OPEN'-command that opened the current parentheses-level `pc'.
     * `par[0]' is equal to `regex'.
     */
  long *branch[1024];
    /* Stack of positions of branches.
     * The top element points to the first regex-command in the branch
     * currently generated (in the current parentheses-level `pc').
     */

  /* We need to know the positions of *all* successive `BRANCH'-commands
   * for *all* levels of parentheses.  This means we need a stack of
   * stacks.  The first stack pointer is `pc', the parentheses counter.
   */
  long *branch_n[REGEX_MAX_PARS][REGEX_MAX_BRANCH];
    /* On par-level `pc', `branch_n[pc][x]' points to the `x'th `BRANCH'-
     * command on that level.
     */
  int branch_len[REGEX_MAX_PARS][REGEX_MAX_BRANCH];
    /* On par-level `pc', `branch_len[pc][x]' holds the length of the `x'th
     * `BRANCH'-command on that level.  If `branch_len[pc][x] < 0' the]
     * length of that branch is variable.
     */
  int branch_n_c[REGEX_MAX_PARS];
    /* On par-level `pc' there are `branch_n_c[pc]' `BRANCH'-commands.
     */

# define BRANCH_LEN_INC(x) {                                                  \
    if (branch_len[pc][branch_n_c[pc]] >= 0)                                  \
      branch_len[pc][branch_n_c[pc]] += (x);                                  \
    exp_len = (x);                                                            \
  }

  long ref_len[256];
    /* If we want to know the length of all strings (if unique) matching
     * an expression which contains back-references, we need to store the
     * lengths of all references.
     */
  long *expression;
    /* Pointer to the beginning of the current expression.  This pointer
     * is relevant for processing operators (like `\?', `\*', `\+', ...).
     */
  int exp_len;
    /* length of the current expression.
     */
  int escape;
    /* Set to 1, if the last read character was a '\\', else 0.
     */
  int start;
  int slot;
    /* Number of slots used by pairs of parentheses.  The slot 0 is reserved
     * for the whole expression.
     */
  static long *regex = 0;
  int regex_size = 0;
  const int regex_blocksize = 1 << 16;
  long *pp;
  char escape_char[128];

  int i, j;

  escape_char['a'] = '\a'; escape_char['b'] = '\b'; escape_char['f'] = '\f';
  escape_char['n'] = '\n'; escape_char['r'] = '\r'; escape_char['t'] = '\t';
  escape_char['v'] = '\v';

  /* we don't know yet, how much memory will be needed to store the resulting
   * regex-code, so we allocate `regex_blocksize' bytes in the first place.
   * if it turns out to be insufficient, we simply cancel the compilation,
   * reallocate the double amount of memory and restart from the beginning.
   * the following macro will take care of watching the memory-consumption:
   */
# define CHECK_PP {                                                           \
    if (pp - regex > regex_size * regex_blocksize - 512) goto compile;        \
  }

  if (regex) free((char *)regex);

compile:
  if (regex_size) {
    regex_size <<= 1;
    regex =
      (long *)realloc(regex, regex_size * regex_blocksize * sizeof(long));
  } else
    ++regex_size, regex =
      (long *)malloc(regex_blocksize * sizeof(long));

  par[0] = regex + 1;
  branch[0] = regex + 1;
  branch_n_c[0] = 0;
  branch_len[0][0] = 0;
  pp = regex;
  cp = str;
  expression = 0;
  exp_len = 0;
  escape = 0;
  start = 1;
  pc = 0;
  slot = 1;

  rx_start = -1;
  branch[-1] = regex;

  ++pp; /* leave space for the replace offset */
  while (*cp) {
    switch (*cp++) {
      /* escape character */
      case '\\':
        if (escape) {
	  expression = pp;
	  *pp++ = CHAR;
	  *pp++ = '\\';
	  if (start) rx_start = '\\';
	  BRANCH_LEN_INC(1);
	} else {
	  ++escape;
	  continue;
	}
	break;

      /* simple escapes */
      case 'a': case 'b': case 'f': case 'n': case 'r': case 't': case 'v':
        if (escape) {
	  expression = pp;
	  *pp++ = CHAR;
	  *pp++ = escape_char[(int)cp[-1]];
	  if (start) rx_start = pp[-1];
	  BRANCH_LEN_INC(1);
	} else
	  goto Default;
	break;
	  
      /* octal, hex, decimal escapes */
      case 'o':
        /* The strings `\0', `\1', ... `\9' are interpreted as back
	 * references, therefore octal escape sequences have to be
	 * prefixed with `\o'.
	 */
        if (escape) {
	  int oct;
	  expression = pp;
	  if (*cp == 'o') { /* octal string */
	    long *length;
	    ++cp;
	    *pp++ = STRING;
	    *(length = pp++) = 1;
	    EAT_WHITESPACE;
	    for (;; ++*length) {
	      GET_OCT(oct, 3);
	      if (oct > 255) { rx_error = (int)E_invalid_character; break; }
	      *pp++ = oct;
	      CHECK_PP;
	      if (start) rx_start = pp[-1], start = 0;
	      EAT_WHITESPACE;
	      if (!isoct(*cp)) break;
	    }
	    BRANCH_LEN_INC(*length);
	  } else { /* octal character */
	    GET_OCT(oct, 3);
	    if (oct > 255) { rx_error = (int)E_invalid_character; break; }
	    *pp++ = CHAR;
	    *pp++ = oct;
	    if (start) rx_start = pp[-1];
	    BRANCH_LEN_INC(1);
	  }
	} else
	  goto Default;
	break;
      case 'x':
        if (escape) {
	  int hex;
	  expression = pp;
	  if (*cp == 'x') { /* hex string */
	    long *length;
	    ++cp;
	    *pp++ = STRING;
	    *(length = pp++) = 1;
	    EAT_WHITESPACE;
	    for (;; ++*length) {
	      GET_HEX(hex, 2);
	      *pp++ = hex;
	      CHECK_PP;
	      if (start) rx_start = pp[-1], start = 0;
	      EAT_WHITESPACE;
	      if (!ishex(*cp)) break;
	    }
	    BRANCH_LEN_INC(*length);
	  } else { /* hex character */
	    GET_HEX(hex, 2);
	    *pp++ = (long)CHAR;
	    *pp++ = hex;
	    if (start) rx_start = pp[-1];
	    BRANCH_LEN_INC(1);
	  }
	} else
	  goto Default;
	break;
      case 'd':  /* special: decimal */
        if (escape) {
	  int dec;
	  expression = pp;
	  if (*cp == 'd') { /* decimal string */
	    long *length;
	    ++cp;
	    *pp++ = STRING;
	    *(length = pp++) = 1;
	    EAT_WHITESPACE;
	    for (;; ++*length) {
	      GET_DEC(dec, 3);
	      if (dec > 255) { rx_error = (int)E_invalid_character; break; }
	      CHECK_PP;
	      *pp++ = dec;
	      if (start) rx_start = pp[-1], start = 0;
	      EAT_WHITESPACE;
	      if (!isdigit(*cp)) break;
	    }
	    BRANCH_LEN_INC(*length);
	  } else { /* decimal character */
	    GET_DEC(dec, 3);
	    if (dec > 255) { rx_error = (int)E_invalid_character; break; }
	    *pp++ = CHAR;
	    *pp++ = dec;
	    if (start) rx_start = pp[-1];
	    BRANCH_LEN_INC(1);
	  }
	} else
	  goto Default;
	break;

      /* ranges */
      case '[':
        if ((escape && rx_nomagic) || (!escape && !rx_nomagic)) {
	  u_char any[1024], table[256];
	  int nescape = 0;
	  i = 0;
	  expression = pp;
	  if (*cp == '^')
	    ++cp, *pp++ = ANY_BUT;
	  else
	    *pp++ = ANY_OF;
	  do {
	    switch (*cp++) {
	      case 0:
	        rx_error = (int)E_unmatched_bracket;
		break;
	      case '\\':
	        if (!nescape) { nescape = 1; continue; } else goto Default1;
		break;
	      case '-':
	        if (*cp == ']' || !i)
		  any[i++] = '-';
		else {
		  if (any[i - 1] > *cp) {
		    rx_error = (int)E_invalid_range;
		    break;
		  }
		  for (j = any[i - 1] + 1; j <= *cp; ++j) any[i++] = j;
		  ++cp;
		}
		break;
	      case 'a': case 'b': case 'f': case 'n': case 'r':
	      case 't': case 'v':
		if (nescape)
		  any[i++] = escape_char[(int)cp[-1]];
		else
		  goto Default1;
		break;
	      case '0': case '1': case '2': case '3': case '4':
	      case '5': case '6': case '7':
	        if (nescape) {
		  /* using back references in a range doesn't make sense, so
		   * we treat them as octal characters. */
		  --cp;
		} else
		  goto Default1;
		/* fall through */
	      case 'o':  /* octal character */
	        if (nescape) {
		  int oct;
		  GET_OCT(oct, 3);
		  if (oct > 255) {
                    rx_error = (int)E_invalid_character;
                    break;
                  }
		  any[i++] = oct;
		} else
		  goto Default1;
		break;
	      case 'd':  /* decimal character */
	        if (nescape) {
		  int dec;
		  GET_DEC(dec, 3);
		  if (dec > 255) {
                    rx_error = (int)E_invalid_character;
                    break;
                  }
		  any[i++] = dec;
		} else
		  goto Default1;
		break;
	      case 'x':  /* hex character */
	        if (nescape) {
		  int hex;
		  GET_HEX(hex, 2);
		  any[i++] = hex;
		} else
		  goto Default1;
		break;
	      default: Default1:
	        any[i++] = cp[-1];
	    }
	    if (rx_error) break;
	    nescape = 0;
	  } while (*cp != ']');
	  if (rx_error) break;
	  ++cp;
	  /* sort the list and remove duplicate entries. */
	  memset(table, 0, 256);
	  for (j = 0; j < i; ++j) table[any[j]] = 1;
	  for (i = 0, j = 0; j < 256; ++j) if (table[j]) any[i++] = j;
	  *pp++ = i;
	  for (j = 0; j < i; ++j) *pp++ = any[j];
	  BRANCH_LEN_INC(1);
	} else
	  goto Default;
	break;

      /* parentheses, branches */
      case '(':
        if ((escape && !rx_allmagic) || (!escape && rx_allmagic)) {
	  expression = 0;
	  *pp++ = PAR_OPEN;
	  ++pc;
	  branch[pc] = par[pc] = pp;
	  branch_len[pc][0] = 0;
	  branch_n_c[pc] = 0;
	} else
	  goto Default;
	break;
      case '|':
        if ((escape && !rx_allmagic) || (!escape && rx_allmagic)) {
	  expression = 0;
	  *pp++ = EOX; /* end of branch */
	  /* insert a `BRANCH'-command at `branch[pc]'. */
	  for (i = -1; pp + i >= branch[pc]; --i)
	    pp[i + SIZE_BRANCH] = pp[i];
	  branch[pc][0] = BRANCH;
	  branch[pc][2] = pp - branch[pc];
	  /* store the position of this `BRANCH' command. */
	  branch_n[pc][branch_n_c[pc]++] = branch[pc];
	  branch_len[pc][branch_n_c[pc]] = 0;
	  pp += SIZE_BRANCH;
	  branch[pc] = pp;
	  if (!pc) rx_start = -1;
	} else
	  goto Default;
	break;
      case ')':
        if ((escape && !rx_allmagic) || (!escape && rx_allmagic)) {
	  /* NOTE: if the parenthesized expression is split up into
	   * multiple branches, the last branch is *not* terminated
	   * by an `EOX'. */
	  *pp++ = PAR_CLOSE;
	  *pp++ = slot++;
	  /* first we'll check if all branches have equal length. */
	  j = branch_len[pc][0];
	  if (branch_n_c[pc]) {
	    for (i = 1; i <= branch_n_c[pc]; ++i)
	      if (j != branch_len[pc][i]) { i = 0; break; }
	  } else
	    i = 1;
	  /* fill in the `n'-field (see description of the `BRANCH'-command)
	   * of all `BRANCH'-commands of the current par-level `pc'. */
	  while (branch_n_c[pc]--) {
	    branch_n[pc][branch_n_c[pc]][1] =
	      pp - (branch_n[pc][branch_n_c[pc]] + SIZE_BRANCH + 2);
	  }
	  expression = par[pc] - 1;
	  if (!pc--) {
	    rx_error = (int)E_unmatched_closing_parenthesis;
	    break;
	  }
	  /* if `i' is set, `j' holds the uniqe length of all branches. */
	  if (i) {
	    BRANCH_LEN_INC(j);
	  } else {
	    branch_len[pc][branch_n_c[pc]] = -1;
	    exp_len = -1;
	  }
	  ref_len[slot - 1] = i ? j : -1;
	} else
	  goto Default;
	break;

      /* back references */
      case '0': case '1': case '2': case '3': case '4':
      case '5': case '6': case '7': case '8': case '9':
        if (escape) {
	  expression = pp;
	  *pp++ = BACKREF;
	  *pp++ = cp[-1] - '0';
	  if (ref_len[cp[-1] - '0'] >= 0) {
	    BRANCH_LEN_INC(ref_len[cp[-1] - '0']);
	  } else {
	    branch_len[pc][branch_n_c[pc]] = -1;
	    exp_len = -1;
	  }
	} else
	  goto Default;
        break;
        
      /* repeat operators */
      case '=': /* ... to stay compatible with VIM */
      case '?':
	if ((escape && !rx_allmagic) || (!escape && rx_allmagic)) {
	  if (!expression) {
	    rx_error = (int)E_operator_without_operand;
	    break;
	  }
	  *pp++ = EOX; /* end of expression */
	  /* insert a `REPEAT'-command at `expression'. */
	  for (i = -1; pp + i >= expression; --i)
	    pp[i + SIZE_REPEAT] = pp[i];
	  expression[0] = REPEAT;
	  expression[1] = 0;
	  expression[2] = 1;
	  expression[3] = pp - expression;
	  pp += SIZE_REPEAT;
	  branch_len[pc][branch_n_c[pc]] = -1;
	  expression = 0;
	} else
	  goto Default;
	break;
      case '+':
	if ((escape && !rx_allmagic) || (!escape && rx_allmagic)) {
	  int no_limit = 0;
	  if (!expression) {
	    rx_error = (int)E_operator_without_operand;
	    break;
	  }
	  if (*cp == '+') {
	    if (exp_len < 0) {
	      rx_error = (int)E_operand_with_variable_length;
	      break;
	    }
	    no_limit = 1;
	    ++cp;
	  }
	  *pp++ = EOX; /* end of expression */
	  if (exp_len < 0) {
	    /* insert a `REPEAT'-command at `expression'. */
	    for (i = -1; pp + i >= expression; --i)
	      pp[i + SIZE_REPEAT] = pp[i];
	    expression[0] = REPEAT;
	    expression[1] = 1;
	    expression[2] = -1;
	    expression[3] = pp - expression;
	    pp += SIZE_REPEAT;
	  } else {
	    /* insert a `FIXREPEAT'-command at `expression'. */
	    for (i = -1; pp + i >= expression; --i)
	      pp[i + SIZE_FIXREPEAT] = pp[i];
	    expression[0] = FIXREPEAT;
	    expression[1] = 1;
	    expression[2] = no_limit ? -1 : rx_maxmatch;
	    expression[3] = exp_len;
	    expression[4] = pp - expression;
	    pp += SIZE_FIXREPEAT;
	    exp_len = -1;
	  }
	  branch_len[pc][branch_n_c[pc]] = -1;
	  expression = 0;
	} else
	  goto Default;
	break;
      case '*':
        if ((escape && rx_nomagic) || (!escape && !rx_nomagic)) {
	  int no_limit = 0;
	  if (!expression) {
	    rx_error = (int)E_operator_without_operand;
	    break;
	  }
	  if (*cp == '*') {
	    if (exp_len < 0) {
	      rx_error = (int)E_operand_with_variable_length;
	      break;
	    }
	    no_limit = 1;
	    ++cp;
	  }
	  *pp++ = EOX; /* end of expression */
	  if (exp_len < 0) {
	    /* insert a `REPEAT'-command at `expression'. */
	    for (i = -1; pp + i >= expression; --i)
	      pp[i + SIZE_REPEAT] = pp[i];
	    expression[0] = REPEAT;
	    expression[1] = 0;
	    expression[2] = -1;
	    expression[3] = pp - expression;
	    pp += SIZE_REPEAT;
	  } else {
	    /* insert a `FIXREPEAT'-command at `expression'. */
	    for (i = -1; pp + i >= expression; --i)
	      pp[i + SIZE_FIXREPEAT] = pp[i];
	    expression[0] = FIXREPEAT;
	    expression[1] = 0;
	    expression[2] = no_limit ? -1 : rx_maxmatch;
	    expression[3] = exp_len;
	    expression[4] = pp - expression;
	    pp += SIZE_FIXREPEAT;
	    exp_len = -1;
	  }
	  branch_len[pc][branch_n_c[pc]] = -1;
	  expression = 0;
	} else
	  goto Default;
	break;
      case '{':
	if ((escape && !rx_allmagic) || (!escape && rx_allmagic)) {
	  long min, max;
	  if (!expression) {
	    rx_error = (int)E_operator_without_operand;
	    break;
	  }
	  EAT_WHITESPACE;
	  GET_NUMBER(min);
	  EAT_WHITESPACE;
          if (*cp == '\\') ++cp;
	  if (*cp == '}')
	    max = min;
	  else {
	    if (*cp++ != ',') { rx_error = (int)E_malformed_operator; break; }
	    EAT_WHITESPACE;
	    GET_NUMBER(max);
	    EAT_WHITESPACE;
	  }
          if (*cp == '\\') ++cp;
	  if ((max && max < min) || *cp++ != '}') {
	    rx_error = (int)E_malformed_operator;
	    break;
	  }
	  if (!max) max = exp_len < 0 ? rx_maxmatch : -1;
	  *pp++ = EOX; /* end of expression */
	  if (exp_len < 0) {
	    /* insert a `REPEAT'-command at `expression'. */
	    for (i = -1; pp + i >= expression; --i)
	      pp[i + SIZE_REPEAT] = pp[i];
	    expression[0] = REPEAT;
	    expression[1] = min;
	    expression[2] = max;
	    expression[3] = pp - expression;
	    pp += SIZE_REPEAT;
	  } else {
	    /* insert a `FIXREPEAT'-command at `expression'. */
	    for (i = -1; pp + i >= expression; --i)
	      pp[i + SIZE_FIXREPEAT] = pp[i];
	    expression[0] = FIXREPEAT;
	    expression[1] = min;
	    expression[2] = max;
	    expression[3] = exp_len;
	    expression[4] = pp - expression;
	    pp += SIZE_FIXREPEAT;
	    exp_len = -1;
	  }
	  if (min != max)
	    branch_len[pc][branch_n_c[pc]] = -1;
	  else
	    BRANCH_LEN_INC(min);
	  expression = 0;
	} else
	  goto Default;
	break;

      /* context specifiers */
      case '<':
	if ((escape && !rx_allmagic) || (!escape && rx_allmagic)) {
	  *pp++ = BEGIN_WORD;
	  expression = 0;
	} else
	  goto Default;
	break;
      case '>':
	if ((escape && !rx_allmagic) || (!escape && rx_allmagic)) {
	  *pp++ = END_WORD;
	  expression = 0;
	} else
	  goto Default;
	break;
      case '^':
        if (!escape) {
	  *pp++ = BEGIN_LINE;
	  expression = 0;
	} else
	  goto Default;
	break;
      case '$':
        if (!escape) {
	  *pp++ = END_LINE;
	  expression = 0;
	} else
	  goto Default;
	break;

      /* any character */
      case '.':
        if ((escape && rx_nomagic) || (!escape && !rx_nomagic)) {
	  expression = pp;
	  *pp++ = ANY_CHAR;
	  BRANCH_LEN_INC(1);
	} else
	  goto Default;
	break;
	
      /* single character */
      default: Default:
        expression = pp;
	if (start) rx_start = cp[-1];
        *pp++ = CHAR;
	*pp++ = cp[-1];
	BRANCH_LEN_INC(1);
	break;
    } /* switch */
    start = escape = 0;
    CHECK_PP;
    if (rx_error) break;
  } /* while */

  if (pc) {
    if (!rx_error) rx_error = (int)E_unmatched_opening_parenthesis;
    goto exit_regex_compile;
  }
    
  if (branch_n_c[0]) {
    /* NOTE: if the whole expression is split up into multiple branches, the
     * last branch is *not* terminated by an `EOX'.
     */
    /* fill in the `n'-field (see description of the `BRANCH'-command)
     * of all `BRANCH'-commands. */
    while (branch_n_c[0]--) {
      branch_n[pc][branch_n_c[0]][1] =
	pp - (branch_n[pc][branch_n_c[0]] + SIZE_BRANCH);
    }
  }
  *pp++ = EOX;
  *pp++ = 0;

  *regex = pp - regex; /* set the replace offset */
  if (!replace) {
    *pp++ = 0;
    goto exit_regex_compile;
  }
  /* compile the `replace'-string:  we only need two commands for the
   * replace code:  `STRING' and `BACKREF'.
   */
  cp = replace;
  escape = 0;
  s = (char *)malloc(strlen(replace) + 1);
  j = 0;
  while (*cp) {
    switch (*cp++) {
      /* escape character */
      case '\\':
        if (!escape) {
	  ++escape;
	  continue;
	} else
	  goto Default2;
	break;

      /* simple escapes */
      case 'a': case 'b': case 'f': case 'n': case 'r': case 't': case 'v':
        if (escape) s[j++] = escape_char[(int)cp[-1]]; else goto Default2;
	break;
	  
      /* octal, hex, decimal escapes */
      case 'o':
        /* The strings `\0', `\1', ... `\9' are interpreted as back
	 * references, therefore octal escape sequences have to be
	 * prefixed with `\o'.
	 */
        if (escape) {
	  int oct;
	  if (*cp == 'o') { /* octal string */
	    ++cp;
	    EAT_WHITESPACE;
	    for (;;) {
	      GET_OCT(oct, 3);
	      if (oct > 255) { rx_error = (int)E_invalid_character; break; }
	      s[j++] = (char)oct;
	      EAT_WHITESPACE;
	      if (!isoct(*cp)) { ++cp; break; }
	    }
	  } else { /* octal character */
	    GET_OCT(oct, 3);
	    if (oct > 255) { rx_error = (int)E_invalid_character; break; }
	    s[j++] = (char)oct;
	  }
	} else
	  goto Default2;
	break;
      case 'x':
        if (escape) {
	  int hex;
	  if (*cp == 'x') { /* hex string */
	    ++cp;
	    EAT_WHITESPACE;
	    for (;;) {
	      GET_HEX(hex, 2);
	      s[j++] = (char)hex;
	      EAT_WHITESPACE;
	      if (!ishex(*cp)) { ++cp; break; }
	    }
	  } else { /* hex character */
	    GET_HEX(hex, 2);
	    s[j++] = (char)hex;
	  }
	} else
	  goto Default2;
	break;
      case 'd':
        if (escape) {
	  int dec;
	  if (*cp == 'd') { /* decimal string */
	    ++cp;
	    EAT_WHITESPACE;
	    for (;;) {
	      GET_DEC(dec, 3);
	      if (dec > 255) { rx_error = (int)E_invalid_character; break; }
	      s[j++] = (char)dec;
	      EAT_WHITESPACE;
	      if (!isdigit(*cp)) { ++cp; break; }
	    }
	  } else { /* decimal character */
	    GET_DEC(dec, 3);
	    if (dec > 255) { rx_error = (int)E_invalid_character; break; }
	    s[j++] = (char)dec;
	  }
	} else
	  goto Default2;
	break;

      /* back references */
      case '0': case '1': case '2': case '3': case '4':
      case '5': case '6': case '7': case '8': case '9':
        if (escape) {
	  if (j) {
	    if (pp - regex + j > regex_size * regex_blocksize - 64)
	      goto compile;
	      /* it is sufficient lo leave 64 bytes of extra space here,
	       * because there won't be any `ANY_OF' of `ANY_BUT' commands
	       * in the replace-code. */
	    *pp++ = STRING;
	    *pp++ = j;
	    for (i = 0; i < j; ++i) *pp++ = s[i];
	    j = 0;
	  }
	  *pp++ = BACKREF;
	  *pp++ = cp[-1] - '0';
	} else
	  goto Default2;
	break;

      default: Default2:
        s[j++] = cp[-1];
	break;
    } /* switch */
    escape = 0;
    if (rx_error) break;
    CHECK_PP;
  } /* while */
  if (j) {
    if (pp - regex + j > regex_size * regex_blocksize - 64) goto compile;
    *pp++ = STRING;
    *pp++ = j;
    for (i = 0; i < j; ++i) *pp++ = s[i];
  }
  *pp++ = EOX;
  *pp = 0;

exit_regex_compile:
  return rx_error ? 0 : regex;
}
/* regex_compile */

#if 0
  static void
regex_list_(regex, count, indent, base)
  unsigned long *regex;
  int count;
  int indent;
  int base;
{
  unsigned long *pp = regex;
  int j;

  for (; pp - regex < count;) {
    printf("%3i : ", (pp - regex) + base);
    for (j = 0; j < indent; ++j) putchar(' ');
    switch (*pp++) {
    case ANY_CHAR:
      printf("ANY_CHAR\n");
      break;
    case ANY_OF: 
      printf("ANY_OF <%lu> [", *pp);
      for (j = 0; j < *pp; ++j)
        if (isprint(pp[j + 1]))
          printf("%lu", pp[j + 1]);
        else
          printf("\\x%02lx", pp[j + 1]);
      printf("]\n");
      pp += *pp + 1;
      break;
    case ANY_BUT:
      printf("ANY_BUT <%lu> [", *pp);
      for (j = 0; j < *pp; ++j)
        if (isprint(pp[j + 1]))
          printf("%lu", pp[j + 1]);
        else
          printf("\\x%02lx", pp[j + 1]);
      printf("]\n");
      pp += *pp + 1;
      break;
    case CHAR:
      printf("CHAR ");
      if (isprint(*pp))
        printf("'%lu'\n", *pp);
      else
        printf("'\\x%02lx'\n", *pp);
      ++pp;
      break;
    case STRING:
      printf("STRING <%lu> \"", *pp);
      for (j = 0; j < *pp; ++j)
        if (isprint(pp[j + 1]))
          printf("%lu", pp[j + 1]);
        else
          printf("\\x%02lx", pp[j + 1]);
      pp += *pp + 1;
      printf("\"\n");
      break;
    case PAR_OPEN:
      printf("PAR_OPEN\n");
      break;
    case PAR_CLOSE:
      printf("PAR_CLOSE <slot=%lu>\n", *pp);
      ++pp;
      break;
    case BACKREF:
      printf("BACKREF <slot=%lu>\n", *pp);
      ++pp;
      break;
    case BRANCH:
      printf("BRANCH <%lu> <%lu>\n", pp[0], pp[1]);
      regex_list_(pp + 2, pp[1], indent + 2, base + (pp - regex) + 2);
      regex_list_(pp + 2 + pp[1], pp[0] - pp[1], indent + 2,
                  base + (pp - regex) + 2 + pp[1]);
      pp += 2 + pp[0];
      break;
    case REPEAT:
      printf("REPEAT <min=%lu> <max=%lu> <%lu>\n", pp[0], pp[1], pp[2]);
      regex_list_(pp + 3, pp[2], indent + 2, base + (pp - regex) + 3);
      pp += 3 + pp[2];
      break;
    case FIXREPEAT:
      printf("FIXREPEAT <min=%lu> <max=%lu> <len=%lu> <%lu>\n",
             pp[0], pp[1], pp[2], pp[3]);
      regex_list_(pp + 4, pp[3], indent + 2, base + (pp - regex) + 4);
      pp += 4 + pp[3];
      break;
    case BEGIN_WORD:
      printf("BEGIN_WORD\n");
      break;
    case END_WORD:
      printf("END_WORD\n");
      break;
    case BEGIN_LINE:
      printf("BEGIN_LINE\n");
      break;
    case END_LINE:
      printf("END_LINE\n");
      break;
    case EOF:
      printf("EOF\n");
      break;
    case EOX:
      printf("EOX\n");
      break;
    case 0:
      printf("--\n");
      return;
    default:
      printf("illegal opcode 0x%lx\n", pp[-1]);
      return;
    }
  }
}
/* regex_list_ */
#endif

/* end of regex.c */


/* VIM configuration: (do not delete this line)
 *
 * vim:bk:nodg:efm=%f\:%l\:%m:hid:icon:
 * vim:sw=2:sm:textwidth=79:ul=1024:wrap:
 */