Debian Codegraph @

terps/tads/tads2/regex.c

raw symbols SCIP
1 #ifdef RCSID
2 static char RCSid[] =
3 "$Header: d:/cvsroot/tads/TADS2/regex.c,v 1.3 1999/07/11 00:46:34 MJRoberts Exp $";
4 #endif
5
6 /*
7 * Copyright (c) 1998, 2002 Michael J. Roberts. All Rights Reserved.
8 *
9 * Please see the accompanying license file, LICENSE.TXT, for information
10 * on using and copying this software.
11 */
12 /*
13 Name
14 regex.c - Regular Expression Parser and Recognizer for TADS
15 Function
16 Parses and recognizes regular expressions
17 Notes
18 Regular expression syntax:
19
20 abc|def either abc or def
21 (abc) abc
22 abc+ abc, abcc, abccc, ...
23 abc* ab, abc, abcc, ...
24 abc? ab or abc
25 . any single character
26 abc$ abc at the end of the line
27 ^abc abc at the beginning of the line
28 %^abc literally ^abc
29 [abcx-z] matches a, b, c, x, y, or z
30 [^abcx-z] matches any character except a, b, c, x, y, or z
31 [^]-q] matches any character except ], -, or q
32
33 Note that using ']' or '-' in a character range expression requires
34 special ordering. If ']' is to be used, it must be the first character
35 after the '^', if present, within the brackets. If '-' is to be used,
36 it must be the first character after the '^' and/or ']', if present.
37
38 '%' is used to escape the special characters: | . ( ) * ? + ^ $ % [
39 (We use '%' rather than a backslash because it's less trouble to
40 enter in a TADS string -- a backslash needs to be quoted with another
41 backslash, which is error-prone and hard to read. '%' doesn't need
42 any special quoting in a TADS string, which makes it a lot more
43 readable.)
44
45 In addition, '%' is used to introduce additional special sequences:
46
47 %1 text matching first parenthesized expression
48 %9 text matching ninth parenthesized experssion
49 %< matches at the beginning of a word only
50 %> matches at the end of a word only
51 %w matches any word character
52 %W matches any non-word character
53 %b matches at any word boundary (beginning or end of word)
54 %B matches except at a word boundary
55
56 For the word matching sequences, a word is any sequence of letters and
57 numbers.
58
59 Modified
60 09/06/98 MJRoberts - Creation
61 */
62
63
64 #include <ctype.h>
65 #include <stdio.h>
66 #include <stdlib.h>
67 #include <string.h>
68
69 #include "std.h"
70 #include "mch.h"
71 #include "ler.h"
72 #include "regex.h"
73
74
75 /* ------------------------------------------------------------------------ */
76 /*
77 * A "machine" (i.e., a finite state automaton) is a set of state
78 * transition tuples. A tuple has three elements: the state ID, the ID
79 * of the state that we transition to, and the condition for the
80 * transition. The condition is simply the character that we must match
81 * to make the transition, or a special distinguished symbol "epsilon,"
82 * which refers to a transition with no input character consumed.
83 *
84 * The primitive elements of our machines guarantee that we never have
85 * more than two transitions out of a particular state, so we can
86 * denormalize the representation of a state by storing the two possible
87 * tuples for that state in a single combined tuple. This has the
88 * performance advantage that we can use the state ID as an index into
89 * an array of state tuples.
90 *
91 * A particular machine always has a single initial and single final
92 * (successful) state, so we can define a machine by its initial and
93 * final state ID's.
94 */
95
96 /* the special symbol value for "epsilon" */
97 #define RE_EPSILON '\001'
98
99 /* the special symbol value for a wildcard character */
100 #define RE_WILDCARD '\002'
101
102 /* special symbol values for beginning and end of text */
103 #define RE_TEXT_BEGIN '\003'
104 #define RE_TEXT_END '\004'
105
106 /* special symbol values for start and end of a word */
107 #define RE_WORD_BEGIN '\005'
108 #define RE_WORD_END '\006'
109
110 /* special symbols for word-char and non-word-char */
111 #define RE_WORD_CHAR '\007'
112 #define RE_NON_WORD_CHAR '\010'
113
114 /* special symbols for word-boundary and non-word-boundary */
115 #define RE_WORD_BOUNDARY '\011'
116 #define RE_NON_WORD_BOUNDARY '\012'
117
118 /* special symbol for a character range/exclusion range */
119 #define RE_RANGE '\013'
120 #define RE_RANGE_EXCL '\014'
121
122 /* a range of special symbol values for group matchers */
123 #define RE_GROUP_MATCH_0 '\015'
124 #define RE_GROUP_MATCH_9 (RE_GROUP_MATCH_0 + 9)
125
126
127 /* ------------------------------------------------------------------------ */
128 /*
129 * A machine description. Machines are fully described by their initial
130 * and final state ID's.
131 */
132 typedef struct
133 {
134 /* the machine's initial state */
135 re_state_id init;
136
137 /* the machine's final state */
138 re_state_id final;
139 } re_machine;
140
141
142 /* ------------------------------------------------------------------------ */
143 /*
144 * Initialize the context. The memory for the context structure itself
145 * is allocated and maintained by the caller.
146 */
147 void re_init(re_context *ctx, errcxdef *errctx)
148 {
149 /* save the error context */
150 ctx->errctx = errctx;
151
152 /* no tuple array yet */
153 ctx->tuple_arr = 0;
154 ctx->tuples_alloc = 0;
155
156 /* clear states */
157 ctx->next_state = RE_STATE_FIRST_VALID;
158
159 /* clear groups */
160 ctx->cur_group = 0;
161
162 /* no string buffer yet */
163 ctx->strbuf = 0;
164 }
165
166 /* ------------------------------------------------------------------------ */
167 /*
168 * Reset compiler - clears states and tuples
169 */
170 static void re_reset(re_context *ctx)
171 {
172 int i;
173
174 /* delete any range tables we've allocated */
175 for (i = 0 ; i < ctx->next_state ; ++i)
176 {
177 if (ctx->tuple_arr[i].char_range != 0)
178 {
179 mchfre(ctx->tuple_arr[i].char_range);
180 ctx->tuple_arr[i].char_range = 0;
181 }
182 }
183
184 /* clear states */
185 ctx->next_state = RE_STATE_FIRST_VALID;
186
187 /* clear groups */
188 ctx->cur_group = 0;
189 }
190
191 /* ------------------------------------------------------------------------ */
192 /*
193 * Delete the context - frees structures associated with the context.
194 * Does NOT free the memory used by the context structure itself.
195 */
196 void re_delete(re_context *ctx)
197 {
198 /* reset state */
199 re_reset(ctx);
200
201 /* if we've allocated an array, delete it */
202 if (ctx->tuple_arr != 0)
203 {
204 mchfre(ctx->tuple_arr);
205 ctx->tuple_arr = 0;
206 }
207
208 /* if we allocated a string buffer, delete it */
209 if (ctx->strbuf != 0)
210 {
211 mchfre(ctx->strbuf);
212 ctx->strbuf = 0;
213 }
214 }
215
216 /* ------------------------------------------------------------------------ */
217 /*
218 * Allocate a new state ID
219 */
220 static re_state_id re_alloc_state(re_context *ctx)
221 {
222 /*
223 * If we don't have enough room for another state, expand the array
224 */
225 if (ctx->next_state >= ctx->tuples_alloc)
226 {
227 uint new_alloc;
228
229 /* bump the size by a bit */
230 new_alloc = ctx->tuples_alloc + 100;
231
232 /* allocate or expand the array */
233 if (ctx->tuples_alloc == 0)
234 {
235 /* allocate the initial memory block */
236 ctx->tuple_arr =
237 (re_tuple *)mchalo(ctx->errctx,
238 (new_alloc * sizeof(re_tuple)),
239 "regex");
240 }
241 else
242 {
243 re_tuple *ptr;
244
245 /* allocate a new memory block */
246 ptr = (re_tuple *)mchalo(ctx->errctx,
247 (new_alloc * sizeof(re_tuple)),
248 "regex");
249
250 /* copy the old memory to the new memory */
251 memcpy(ptr, ctx->tuple_arr, ctx->tuples_alloc * sizeof(re_tuple));
252
253 /* free the old block */
254 mchfre(ctx->tuple_arr);
255
256 /* use the new block */
257 ctx->tuple_arr = ptr;
258 }
259
260 /* remember the new allocation size */
261 ctx->tuples_alloc = new_alloc;
262 }
263
264 /* initialize the next state */
265 ctx->tuple_arr[ctx->next_state].next_state_1 = RE_STATE_INVALID;
266 ctx->tuple_arr[ctx->next_state].next_state_2 = RE_STATE_INVALID;
267 ctx->tuple_arr[ctx->next_state].ch = RE_EPSILON;
268 ctx->tuple_arr[ctx->next_state].flags = 0;
269 ctx->tuple_arr[ctx->next_state].char_range = 0;
270
271 /* return the new state's ID */
272 return ctx->next_state++;
273 }
274
275
276 /* ------------------------------------------------------------------------ */
277 /*
278 * Set a transition from a state to a given destination state.
279 */
280 static void re_set_trans(re_context *ctx,
281 re_state_id id, re_state_id dest_id, char ch)
282 {
283 re_tuple *tuple;
284
285 /*
286 * get the tuple containing the transitions for this state ID - the
287 * state ID is the index of the state's transition tuple in the
288 * array
289 */
290 tuple = &ctx->tuple_arr[id];
291
292 /*
293 * If the first state pointer hasn't been set yet, set it to the new
294 * destination. Otherwise, set the second state pointer.
295 *
296 * Only set the character on setting the first state. When setting
297 * the second state, we must assume that the character for the state
298 * has already been set, since any given state can have only one
299 * character setting.
300 */
301 if (tuple->next_state_1 == RE_STATE_INVALID)
302 {
303 /*
304 * set the character ID, unless the state has been marked with a
305 * special flag which indicates that the character value has
306 * another meaning (in particular, a group marker)
307 */
308 if (!(tuple->flags & (RE_STATE_GROUP_BEGIN | RE_STATE_GROUP_END)))
309 tuple->ch = ch;
310
311 /* set the first transition */
312 tuple->next_state_1 = dest_id;
313 }
314 else
315 {
316 /* set only the second transition state - don't set the character */
317 tuple->next_state_2 = dest_id;
318 }
319 }
320
321 /* ------------------------------------------------------------------------ */
322 /*
323 * Initialize a new machine, giving it an initial and final state
324 */
325 static void re_init_machine(re_context *ctx, re_machine *machine)
326 {
327 machine->init = re_alloc_state(ctx);
328 machine->final = re_alloc_state(ctx);
329 }
330
331 /*
332 * Build a character recognizer
333 */
334 static void re_build_char(re_context *ctx, re_machine *machine, char ch)
335 {
336 /* initialize our new machine */
337 re_init_machine(ctx, machine);
338
339 /* allocate a transition tuple for the new state */
340 re_set_trans(ctx, machine->init, machine->final, ch);
341 }
342
343 /*
344 * Build a character range recognizer. 'range' is a 256-bit (32-byte)
345 * bit vector.
346 */
347 static void re_build_char_range(re_context *ctx, re_machine *machine,
348 unsigned char *range, int exclusion)
349 {
350 unsigned char *range_copy;
351
352 /* initialize our new machine */
353 re_init_machine(ctx, machine);
354
355 /* allocate a transition table for the new state */
356 re_set_trans(ctx, machine->init, machine->final,
357 (char)(exclusion ? RE_RANGE_EXCL : RE_RANGE));
358
359 /* allocate a copy of the range bit vector */
360 range_copy = (unsigned char *)mchalo(ctx->errctx, 32, "regex range");
361
362 /* copy the caller's range */
363 memcpy(range_copy, range, 32);
364
365 /* store it in the tuple */
366 ctx->tuple_arr[machine->init].char_range = range_copy;
367 }
368
369
370 /*
371 * Build a group recognizer. This is almost the same as a character
372 * recognizer, but matches a previous group rather than a literal
373 * character.
374 */
375 static void re_build_group_matcher(re_context *ctx,
376 re_machine *machine, int group_num)
377 {
378 /* initialize our new machine */
379 re_init_machine(ctx, machine);
380
381 /*
382 * Allocate a transition tuple for the new state, using the group ID
383 * as the character code. Store the special code for a group
384 * recognizer rather than the normal literal character code.
385 */
386 re_set_trans(ctx, machine->init, machine->final,
387 (char)(group_num + RE_GROUP_MATCH_0));
388 }
389
390
391 /*
392 * Build a concatenation recognizer
393 */
394 static void re_build_concat(re_context *ctx, re_machine *new_machine,
395 re_machine *lhs, re_machine *rhs)
396 {
397 /* initialize the new machine */
398 re_init_machine(ctx, new_machine);
399
400 /*
401 * set up an epsilon transition from the new machine's initial state
402 * to the first submachine's initial state
403 */
404 re_set_trans(ctx, new_machine->init, lhs->init, RE_EPSILON);
405
406 /*
407 * Set up an epsilon transition from the first submachine's final
408 * state to the second submachine's initial state
409 */
410 re_set_trans(ctx, lhs->final, rhs->init, RE_EPSILON);
411
412 /*
413 * Set up an epsilon transition from the second submachine's final
414 * state to our new machine's final state
415 */
416 re_set_trans(ctx, rhs->final, new_machine->final, RE_EPSILON);
417 }
418
419 /*
420 * Build a group machine. sub_machine contains the machine that
421 * expresses the group's contents; we'll fill in new_machine with a
422 * newly-created machine that encloses and marks the group.
423 */
424 static void re_build_group(re_context *ctx, re_machine *new_machine,
425 re_machine *sub_machine, int group_id)
426 {
427 /* initialize the container machine */
428 re_init_machine(ctx, new_machine);
429
430 /*
431 * set up an epsilon transition from the new machine's initial state
432 * into the initial state of the group, and another transition from
433 * the group's final state into the container's final state
434 */
435 re_set_trans(ctx, new_machine->init, sub_machine->init, RE_EPSILON);
436 re_set_trans(ctx, sub_machine->final, new_machine->final, RE_EPSILON);
437
438 /*
439 * Mark the initial and final states of the group machine as being
440 * group markers.
441 */
442 ctx->tuple_arr[new_machine->init].flags |= RE_STATE_GROUP_BEGIN;
443 ctx->tuple_arr[new_machine->final].flags |= RE_STATE_GROUP_END;
444
445 /* store the group ID in the 'ch' member of the start and end states */
446 ctx->tuple_arr[new_machine->init].ch = group_id;
447 ctx->tuple_arr[new_machine->final].ch = group_id;
448 }
449
450 /*
451 * Build an alternation recognizer
452 */
453 static void re_build_alter(re_context *ctx, re_machine *new_machine,
454 re_machine *lhs, re_machine *rhs)
455 {
456 /* initialize the new machine */
457 re_init_machine(ctx, new_machine);
458
459 /*
460 * Set up an epsilon transition from our new machine's initial state
461 * to the initial state of each submachine
462 */
463 re_set_trans(ctx, new_machine->init, lhs->init, RE_EPSILON);
464 re_set_trans(ctx, new_machine->init, rhs->init, RE_EPSILON);
465
466 /*
467 * Set up an epsilon transition from the final state of each
468 * submachine to our final state
469 */
470 re_set_trans(ctx, lhs->final, new_machine->final, RE_EPSILON);
471 re_set_trans(ctx, rhs->final, new_machine->final, RE_EPSILON);
472 }
473
474 /*
475 * Build a closure recognizer
476 */
477 static void re_build_closure(re_context *ctx,
478 re_machine *new_machine, re_machine *sub,
479 char specifier)
480 {
481 /* initialize the new machine */
482 re_init_machine(ctx, new_machine);
483
484 /*
485 * set up an epsilon transition from our initial state to the
486 * submachine's initial state, and from the submachine's final state
487 * to our final state
488 */
489 re_set_trans(ctx, new_machine->init, sub->init, RE_EPSILON);
490 re_set_trans(ctx, sub->final, new_machine->final, RE_EPSILON);
491
492 /*
493 * If this is an unbounded closure ('*' or '+', but not '?'), set up
494 * the loop transition that takes us from the new machine's final
495 * state back to its initial state. We don't do this on the
496 * zero-or-one closure, because we can only match the expression
497 * once.
498 */
499 if (specifier != '?')
500 re_set_trans(ctx, sub->final, sub->init, RE_EPSILON);
501
502 /*
503 * If this is a zero-or-one closure or a zero-or-more closure, set
504 * up an epsilon transition from our initial state to our final
505 * state, since we can skip the entire subexpression. We don't do
506 * this on the one-or-more closure, because we can't skip the
507 * subexpression in this case.
508 */
509 if (specifier != '+')
510 re_set_trans(ctx, new_machine->init, new_machine->final, RE_EPSILON);
511 }
512
513 /*
514 * Build a null machine
515 */
516 static void re_build_null_machine(re_context *ctx, re_machine *machine)
517 {
518 machine->init = machine->final = RE_STATE_INVALID;
519 }
520
521 /* ------------------------------------------------------------------------ */
522 /*
523 * Determine if a machine is null
524 */
525 static int re_is_machine_null(re_context *ctx, re_machine *machine)
526 {
527 return (machine->init == RE_STATE_INVALID);
528 }
529
530
531 /* ------------------------------------------------------------------------ */
532 /*
533 * Concatenate the second machine onto the first machine, replacing the
534 * first machine with the resulting machine. If the first machine is a
535 * null machine (created with re_build_null_machine), we'll simply copy
536 * the second machine into the first.
537 */
538 static void re_concat_onto(re_context *ctx,
539 re_machine *dest, re_machine *rhs)
540 {
541 /* check for a null destination machine */
542 if (re_is_machine_null(ctx, dest))
543 {
544 /*
545 * the first machine is null - simply copy the second machine
546 * onto the first unchanged
547 */
548 *dest = *rhs;
549 }
550 else
551 {
552 re_machine new_machine;
553
554 /* build the concatenated machine */
555 re_build_concat(ctx, &new_machine, dest, rhs);
556
557 /* copy the concatenated machine onto the first machine */
558 *dest = new_machine;
559 }
560 }
561
562 /*
563 * Alternate the second machine onto the first machine, replacing the
564 * first machine with the resulting machine. If the first machine is a
565 * null machine, this simply replaces the first machine with the second
566 * machine. If the second machine is null, this simply leaves the first
567 * machine unchanged.
568 */
569 static void re_alternate_onto(re_context *ctx,
570 re_machine *dest, re_machine *rhs)
571 {
572 /* check to see if the first machine is null */
573 if (re_is_machine_null(ctx, dest))
574 {
575 /*
576 * the first machine is null - simply copy the second machine
577 * onto the first
578 */
579 *dest = *rhs;
580 }
581 else
582 {
583 /*
584 * if the second machine is null, don't do anything; otherwise,
585 * build the alternation
586 */
587 if (!re_is_machine_null(ctx, rhs))
588 {
589 re_machine new_machine;
590
591 /* build the alternation */
592 re_build_alter(ctx, &new_machine, dest, rhs);
593
594 /* replace the first machine with the alternation */
595 *dest = new_machine;
596 }
597 }
598 }
599
600 /* ------------------------------------------------------------------------ */
601 /*
602 * Set a bit in a bit vector.
603 */
604 #define re_set_bit(set, bit) \
605 (((unsigned char *)(set))[(bit) >> 3] |= (1 << ((bit) & 7)))
606
607 /*
608 * Test a bit in a bit vector
609 */
610 #define re_is_bit_set(set, bit) \
611 ((((unsigned char *)(set))[(bit) >> 3] & (1 << ((bit) & 7))) != 0)
612
613 /* ------------------------------------------------------------------------ */
614 /*
615 * Compile an expression
616 */
617 static re_status_t re_compile(re_context *ctx,
618 const char *expr, size_t exprlen,
619 re_machine *result_machine)
620 {
621 re_machine cur_machine;
622 re_machine alter_machine;
623 re_machine new_machine;
624 size_t group_stack_level;
625 struct
626 {
627 re_machine old_cur;
628 re_machine old_alter;
629 int group_id;
630 } group_stack[50];
631
632 /* reset everything */
633 re_reset(ctx);
634
635 /* start out with no current machine and no alternate machine */
636 re_build_null_machine(ctx, &cur_machine);
637 re_build_null_machine(ctx, &alter_machine);
638
639 /* nothing on the stack yet */
640 group_stack_level = 0;
641
642 /* loop until we run out of expression to parse */
643 for ( ; exprlen != 0 ; ++expr, --exprlen)
644 {
645 switch(*expr)
646 {
647 case '^':
648 /*
649 * beginning of line - if we're not at the beginning of the
650 * current expression (i.e., we already have some
651 * concatentations accumulated), treat it as an ordinary
652 * character
653 */
654 if (!re_is_machine_null(ctx, &cur_machine))
655 goto normal_char;
656
657 /* build a new start-of-text recognizer */
658 re_build_char(ctx, &new_machine, RE_TEXT_BEGIN);
659
660 /*
661 * concatenate it onto the string - note that this can't
662 * have any postfix operators
663 */
664 re_concat_onto(ctx, &cur_machine, &new_machine);
665 break;
666
667 case '$':
668 /*
669 * End of line specifier - if there's anything left after
670 * the '$' other than a close parens or alternation
671 * specifier, great it as a normal character
672 */
673 if (exprlen > 1
674 && (*(expr+1) != ')' && *(expr+1) != '|'))
675 goto normal_char;
676
677 /* build a new end-of-text recognizer */
678 re_build_char(ctx, &new_machine, RE_TEXT_END);
679
680 /*
681 * concatenate it onto the string - note that this can't
682 * have any postfix operators
683 */
684 re_concat_onto(ctx, &cur_machine, &new_machine);
685 break;
686
687 case '(':
688 /*
689 * Add a nesting level. Push the current machine and
690 * alternate machines onto the group stack, and clear
691 * everything out for the new group.
692 */
693 if (group_stack_level
694 > sizeof(group_stack)/sizeof(group_stack[0]))
695 {
696 /* we cannot proceed - return an error */
697 return RE_STATUS_GROUP_NESTING_TOO_DEEP;
698 }
699
700 /* save the current state on the stack */
701 group_stack[group_stack_level].old_cur = cur_machine;
702 group_stack[group_stack_level].old_alter = alter_machine;
703
704 /*
705 * Assign the group a group ID - groups are numbered in
706 * order of their opening (left) parentheses, so we want to
707 * assign a group number now. We won't actually need to
708 * know the group number until we get to the matching close
709 * paren, but we need to assign it now, so store it in the
710 * group stack.
711 */
712 group_stack[group_stack_level].group_id = ctx->cur_group;
713
714 /* consume the group number */
715 ctx->cur_group++;
716
717 /* push the level */
718 ++group_stack_level;
719
720 /* start the new group with empty machines */
721 re_build_null_machine(ctx, &cur_machine);
722 re_build_null_machine(ctx, &alter_machine);
723 break;
724
725 case ')':
726 /* if there's nothing on the stack, ignore this */
727 if (group_stack_level == 0)
728 break;
729
730 /* take a level off the stack */
731 --group_stack_level;
732
733 /*
734 * Remove a nesting level. If we have a pending alternate
735 * expression, build the alternation expression. This will
736 * leave the entire group expression in alter_machine,
737 * regardless of whether an alternation was in progress or
738 * not.
739 */
740 re_alternate_onto(ctx, &alter_machine, &cur_machine);
741
742 /*
743 * Create a group machine that encloses the group and marks
744 * it with a group number. We assigned the group number
745 * when we parsed the open paren, so read that group number
746 * from the stack.
747 *
748 * Note that this will leave 'new_machine' with the entire
749 * group machine.
750 */
751 re_build_group(ctx, &new_machine, &alter_machine,
752 group_stack[group_stack_level].group_id);
753
754 /*
755 * Pop the stack - restore the alternation and current
756 * machines that were in progress before the group started.
757 */
758 cur_machine = group_stack[group_stack_level].old_cur;
759 alter_machine = group_stack[group_stack_level].old_alter;
760
761 /*
762 * Check the group expression (in new_machine) for postfix
763 * expressions
764 */
765 goto apply_postfix;
766
767 case '|':
768 /*
769 * Start a new alternation. This ends the current
770 * alternation; if we have a previous pending alternate,
771 * build an alternation machine out of the previous
772 * alternate and the current machine and move that to the
773 * alternate; otherwise, simply move the current machine to
774 * the pending alternate.
775 */
776 re_alternate_onto(ctx, &alter_machine, &cur_machine);
777
778 /*
779 * the alternation starts out with a blank slate, so null
780 * out the current machine
781 */
782 re_build_null_machine(ctx, &cur_machine);
783 break;
784
785 case '%':
786 /*
787 * quoted character - skip the quote mark and see what we
788 * have
789 */
790 ++expr;
791 --exprlen;
792
793 /* check to see if we're at the end of the expression */
794 if (exprlen == 0)
795 {
796 /*
797 * end of the string - ignore it, but undo the extra
798 * increment of the expression index so that we exit the
799 * enclosing loop properly
800 */
801 --expr;
802 ++exprlen;
803 break;
804 }
805
806 /* see what we have */
807 switch(*expr)
808 {
809 case '1':
810 case '2':
811 case '3':
812 case '4':
813 case '5':
814 case '6':
815 case '7':
816 case '8':
817 case '9':
818 /* group match - build a new literal group recognizer */
819 re_build_group_matcher(ctx, &new_machine, (int)(*expr - '1'));
820
821 /* apply any postfix expression to the group recognizer */
822 goto apply_postfix;
823
824 case '<':
825 /* build a beginning-of-word recognizer */
826 re_build_char(ctx, &new_machine, RE_WORD_BEGIN);
827
828 /* it can't be postfixed - just concatenate it */
829 re_concat_onto(ctx, &cur_machine, &new_machine);
830 break;
831
832 case '>':
833 /* build an end-of-word recognizer */
834 re_build_char(ctx, &new_machine, RE_WORD_END);
835
836 /* it can't be postfixed - just concatenate it */
837 re_concat_onto(ctx, &cur_machine, &new_machine);
838 break;
839
840 case 'w':
841 /* word character */
842 re_build_char(ctx, &new_machine, RE_WORD_CHAR);
843 goto apply_postfix;
844
845 case 'W':
846 /* non-word character */
847 re_build_char(ctx, &new_machine, RE_NON_WORD_CHAR);
848 goto apply_postfix;
849
850 case 'b':
851 /* word boundary */
852 re_build_char(ctx, &new_machine, RE_WORD_BOUNDARY);
853
854 /* it can't be postfixed */
855 re_concat_onto(ctx, &cur_machine, &new_machine);
856 break;
857
858 case 'B':
859 /* not a word boundary */
860 re_build_char(ctx, &new_machine, RE_NON_WORD_BOUNDARY);
861
862 /* it can't be postfixed */
863 re_concat_onto(ctx, &cur_machine, &new_machine);
864 break;
865
866 default:
867 /* build a new literal character recognizer */
868 re_build_char(ctx, &new_machine, *expr);
869
870 /* apply any postfix expression to the character */
871 goto apply_postfix;
872 }
873 break;
874
875 case '.':
876 /*
877 * wildcard character - build a single character recognizer
878 * for the special wildcard symbol, then go check it for a
879 * postfix operator
880 */
881 re_build_char(ctx, &new_machine, RE_WILDCARD);
882 goto apply_postfix;
883 break;
884
885 case '[':
886 /* range expression */
887 {
888 int is_exclusive = FALSE;
889 unsigned char set[32];
890
891 /* clear out the set of characters in the range */
892 memset(set, 0, sizeof(set));
893
894 /* first, skip the open bracket */
895 ++expr;
896 --exprlen;
897
898 /* check to see if starts with the exclusion character */
899 if (exprlen != 0 && *expr == '^')
900 {
901 /* skip the exclusion specifier */
902 ++expr;
903 --exprlen;
904
905 /* note it */
906 is_exclusive = TRUE;
907 }
908
909 /*
910 * if the first character is a ']', include it in the
911 * range
912 */
913 if (exprlen != 0 && *expr == ']')
914 {
915 re_set_bit(set, (int)']');
916 ++expr;
917 --exprlen;
918 }
919
920 /*
921 * if the next character is a '-', include it in the
922 * range
923 */
924 if (exprlen != 0 && *expr == '-')
925 {
926 re_set_bit(set, (int)'-');
927 ++expr;
928 --exprlen;
929 }
930
931 /* scan the character set */
932 while (exprlen != 0 && *expr != ']')
933 {
934 int ch;
935
936 /* note this character */
937 ch = (int)(unsigned char)*expr;
938
939 /* set it */
940 re_set_bit(set, ch);
941
942 /* skip this character of the expression */
943 ++expr;
944 --exprlen;
945
946 /* check for a range */
947 if (exprlen != 0 && *expr == '-')
948 {
949 int ch2;
950
951 /* skip the '-' */
952 ++expr;
953 --exprlen;
954 if (exprlen != 0)
955 {
956 /* get the other end of the range */
957 ch2 = (int)(unsigned char)*expr;
958
959 /* skip the second character */
960 ++expr;
961 --exprlen;
962
963 /* if the range is reversed, swap it */
964 if (ch > ch2)
965 {
966 int tmp = ch;
967 ch = ch2;
968 ch2 = tmp;
969 }
970
971 /* fill in the range */
972 for ( ; ch <= ch2 ; ++ch)
973 re_set_bit(set, ch);
974 }
975 }
976 }
977
978 /* create a character range machine */
979 re_build_char_range(ctx, &new_machine, set, is_exclusive);
980
981 /* apply any postfix operator */
982 goto apply_postfix;
983 }
984 break;
985
986 default:
987 normal_char:
988 /*
989 * it's an ordinary character - build a single character
990 * recognizer machine, and then concatenate it onto any
991 * existing machine
992 */
993 re_build_char(ctx, &new_machine, *expr);
994
995 apply_postfix:
996 /*
997 * Check for a postfix operator, and apply it to the machine
998 * in 'new_machine' if present. In any case, concatenate
999 * the 'new_machine' (modified by a postix operator or not)
1000 * to the current machien.
1001 */
1002 if (exprlen > 1)
1003 {
1004 switch(*(expr+1))
1005 {
1006 case '*':
1007 case '+':
1008 case '?':
1009 /*
1010 * We have a postfix closure operator. Build a new
1011 * closure machine out of 'new_machine'.
1012 */
1013 {
1014 re_machine closure_machine;
1015
1016 /* move onto the closure operator */
1017 ++expr;
1018 --exprlen;
1019
1020 /* build the closure machine */
1021 re_build_closure(ctx, &closure_machine,
1022 &new_machine, *expr);
1023
1024 /* replace the original machine with the closure */
1025 new_machine = closure_machine;
1026
1027 /*
1028 * skip any redundant closure symbols, keeping
1029 * only the first one we saw
1030 */
1031 while (exprlen > 1 && (*(expr+1) == '?'
1032 || *(expr+1) == '+'
1033 || *(expr+1) == '*'))
1034 {
1035 ++expr;
1036 --exprlen;
1037 }
1038 }
1039 break;
1040
1041 default:
1042 /* no postfix operator */
1043 break;
1044 }
1045 }
1046
1047 /*
1048 * Concatenate the new machine onto the current machine
1049 * under construction.
1050 */
1051 re_concat_onto(ctx, &cur_machine, &new_machine);
1052 break;
1053 }
1054 }
1055
1056 /* complete any pending alternation */
1057 re_alternate_onto(ctx, &alter_machine, &cur_machine);
1058
1059 /* store the resulting machine in the caller's machine descriptor */
1060 *result_machine = alter_machine;
1061
1062 /* no errors encountered */
1063 return RE_STATUS_SUCCESS;
1064 }
1065
1066
1067 /* ------------------------------------------------------------------------ */
1068 /*
1069 * Pattern recognizer
1070 */
1071
1072 /*
1073 * Note a group position if appropriate
1074 */
1075 static void re_note_group(re_context *ctx, re_group_register *regs,
1076 re_state_id id, const char *p)
1077 {
1078 int group_index;
1079
1080 /*
1081 * Check to see if this is a valid state and it's a group marker -
1082 * if not, there's nothing to do
1083 */
1084 if (id == RE_STATE_INVALID
1085 || !(ctx->tuple_arr[id].flags
1086 & (RE_STATE_GROUP_BEGIN | RE_STATE_GROUP_END))
1087 || (group_index = (int)ctx->tuple_arr[id].ch) >= RE_GROUP_REG_CNT)
1088 return;
1089
1090 /*
1091 * It's a valid group marker - note the appropriate register value
1092 */
1093 if ((ctx->tuple_arr[id].flags & RE_STATE_GROUP_BEGIN) != 0)
1094 regs[group_index].start_ofs = p;
1095 else
1096 regs[group_index].end_ofs = p;
1097 }
1098
1099 /*
1100 * Determine if a character is part of a word. We consider letters and
1101 * numbers to be word characters.
1102 */
1103 static int re_is_word_char(char c)
1104 {
1105 return (isalpha((unsigned char)c) || isdigit((unsigned char)c));
1106 }
1107
1108 /*
1109 * Match a string to a compiled expression. Returns the length of the
1110 * match if successful, or -1 if no match was found.
1111 */
1112 static int re_match(re_context *ctx, const char *entire_str,
1113 const char *str, size_t origlen,
1114 const re_machine *machine, re_group_register *regs)
1115 {
1116 re_state_id cur_state;
1117 const char *p;
1118 size_t curlen;
1119
1120 /* start at the machine's initial state */
1121 cur_state = machine->init;
1122
1123 /* start at the beginning of the string */
1124 p = str;
1125 curlen = origlen;
1126
1127 /* note any group involved in the initial state */
1128 re_note_group(ctx, regs, cur_state, p);
1129
1130 /*
1131 * if we're starting in the final state, immediately return success
1132 * with a zero-length match
1133 */
1134 if (cur_state == machine->final)
1135 {
1136 /* return success with a zero-length match */
1137 return 0;
1138 }
1139
1140 /* run the machine */
1141 for (;;)
1142 {
1143 re_tuple *tuple;
1144
1145 /* get the tuple for this state */
1146 tuple = &ctx->tuple_arr[cur_state];
1147
1148 /* if this is a group state, adjust the group registers */
1149 re_note_group(ctx, regs, cur_state, p);
1150
1151 /* see what kind of state we're in */
1152 if (!(tuple->flags & (RE_STATE_GROUP_BEGIN | RE_STATE_GROUP_END))
1153 && tuple->ch != RE_EPSILON)
1154 {
1155 /*
1156 * This is a character or group recognizer state. If we
1157 * match the character or group, continue on to the next
1158 * state; otherwise, return failure.
1159 */
1160 switch(tuple->ch)
1161 {
1162 case RE_GROUP_MATCH_0:
1163 case RE_GROUP_MATCH_0 + 1:
1164 case RE_GROUP_MATCH_0 + 2:
1165 case RE_GROUP_MATCH_0 + 3:
1166 case RE_GROUP_MATCH_0 + 4:
1167 case RE_GROUP_MATCH_0 + 5:
1168 case RE_GROUP_MATCH_0 + 6:
1169 case RE_GROUP_MATCH_0 + 7:
1170 case RE_GROUP_MATCH_0 + 8:
1171 case RE_GROUP_MATCH_0 + 9:
1172 {
1173 int group_num;
1174 re_group_register *group_reg;
1175 size_t reg_len;
1176
1177 /* it's a group - get the group number */
1178 group_num = tuple->ch - RE_GROUP_MATCH_0;
1179 group_reg = &regs[group_num];
1180
1181 /*
1182 * if this register isn't defined, there's nothing
1183 * to match, so fail
1184 */
1185 if (group_reg->start_ofs == 0 || group_reg->end_ofs == 0)
1186 return -1;
1187
1188 /* calculate the length of the register value */
1189 reg_len = group_reg->end_ofs - group_reg->start_ofs;
1190
1191 /* if we don't have enough left to match, it fails */
1192 if (curlen < reg_len)
1193 return -1;
1194
1195 /* if the string doesn't match exactly, we fail */
1196 if (memcmp(p, group_reg->start_ofs, reg_len) != 0)
1197 return -1;
1198
1199 /*
1200 * It matches exactly - skip the entire length of
1201 * the register in the source string
1202 */
1203 p += reg_len;
1204 curlen -= reg_len;
1205 }
1206 break;
1207
1208 case RE_TEXT_BEGIN:
1209 /*
1210 * Match only the exact beginning of the string - if
1211 * we're anywhere else, this isn't a match. If this
1212 * succeeds, we don't skip any characters.
1213 */
1214 if (p != entire_str)
1215 return -1;
1216 break;
1217
1218 case RE_TEXT_END:
1219 /*
1220 * Match only the exact end of the string - if we're
1221 * anywhere else, this isn't a match. Don't skip any
1222 * characters on success.
1223 */
1224 if (curlen != 0)
1225 return -1;
1226 break;
1227
1228 case RE_WORD_BEGIN:
1229 /*
1230 * if the previous character is a word character, we're
1231 * not at the beginning of a word
1232 */
1233 if (p != entire_str && re_is_word_char(*(p-1)))
1234 return -1;
1235
1236 /*
1237 * if we're at the end of the string, or the current
1238 * character isn't the start of a word, we're not at the
1239 * beginning of a word
1240 */
1241 if (curlen == 0 || !re_is_word_char(*p))
1242 return -1;
1243 break;
1244
1245 case RE_WORD_END:
1246 /*
1247 * if the current character is a word character, we're not
1248 * at the end of a word
1249 */
1250 if (curlen != 0 && re_is_word_char(*p))
1251 return -1;
1252
1253 /*
1254 * if we're at the beginning of the string, or the
1255 * previous character is not a word character, we're not
1256 * at the end of a word
1257 */
1258 if (p == entire_str || !re_is_word_char(*(p-1)))
1259 return -1;
1260 break;
1261
1262 case RE_WORD_CHAR:
1263 /* if it's not a word character, it's a failure */
1264 if (curlen == 0 || !re_is_word_char(*p))
1265 return -1;
1266
1267 /* skip this character of input */
1268 ++p;
1269 --curlen;
1270 break;
1271
1272 case RE_NON_WORD_CHAR:
1273 /* if it's a word character, it's a failure */
1274 if (curlen == 0 || re_is_word_char(*p))
1275 return -1;
1276
1277 /* skip the input */
1278 ++p;
1279 --curlen;
1280 break;
1281
1282 case RE_WORD_BOUNDARY:
1283 case RE_NON_WORD_BOUNDARY:
1284 {
1285 int prev_is_word;
1286 int next_is_word;
1287 int boundary;
1288
1289 /*
1290 * Determine if the previous character is a word
1291 * character -- if we're at the beginning of the
1292 * string, it's obviously not, otherwise check its
1293 * classification
1294 */
1295 prev_is_word = (p != entire_str
1296 && re_is_word_char(*(p-1)));
1297
1298 /* make the same check for the current character */
1299 next_is_word = (curlen != 0
1300 && re_is_word_char(*p));
1301
1302 /*
1303 * Determine if this is a boundary - it is if the
1304 * two states are different
1305 */
1306 boundary = ((prev_is_word != 0) ^ (next_is_word != 0));
1307
1308 /*
1309 * make sure it matches what was desired, and return
1310 * failure if not
1311 */
1312 if ((tuple->ch == RE_WORD_BOUNDARY && !boundary)
1313 || (tuple->ch == RE_NON_WORD_BOUNDARY && boundary))
1314 return -1;
1315 }
1316 break;
1317
1318 case RE_WILDCARD:
1319 /* make sure we have a character to match */
1320 if (curlen == 0)
1321 return -1;
1322
1323 /* skip this character */
1324 ++p;
1325 --curlen;
1326 break;
1327
1328 case RE_RANGE:
1329 case RE_RANGE_EXCL:
1330 {
1331 int match;
1332
1333 /* make sure we have a character to match */
1334 if (curlen == 0)
1335 return -1;
1336
1337 /* see if we match */
1338 match = re_is_bit_set(tuple->char_range,
1339 (int)(unsigned char)*p);
1340
1341 /* make sure we got what we wanted */
1342 if ((tuple->ch == RE_RANGE && !match)
1343 || (tuple->ch == RE_RANGE_EXCL && match))
1344 return -1;
1345
1346 /* skip this character of the input */
1347 ++p;
1348 --curlen;
1349 }
1350 break;
1351
1352 default:
1353 /* make sure we have an exact match */
1354 if (curlen == 0 || tuple->ch != *p)
1355 return -1;
1356
1357 /* skip this character of the input */
1358 ++p;
1359 --curlen;
1360 break;
1361 }
1362
1363 /*
1364 * if we got this far, we were successful - move on to the
1365 * next state
1366 */
1367 cur_state = tuple->next_state_1;
1368 }
1369 else if (tuple->next_state_2 == RE_STATE_INVALID)
1370 {
1371 /*
1372 * We have only one transition, so this state is entirely
1373 * deterministic. Simply move on to the next state.
1374 */
1375 cur_state = tuple->next_state_1;
1376 }
1377 else
1378 {
1379 re_machine sub_machine;
1380 re_group_register regs1[RE_GROUP_REG_CNT];
1381 re_group_register regs2[RE_GROUP_REG_CNT];
1382 int ret1;
1383 int ret2;
1384
1385 /*
1386 * This state has two possible transitions, and we don't
1387 * know which one to take. So, try both, see which one
1388 * works better, and return the result. Try the first
1389 * transition first. Note that each separate attempt must
1390 * use a separate copy of the registers.
1391 */
1392 memcpy(regs1, regs, sizeof(regs1));
1393 sub_machine.init = tuple->next_state_1;
1394 sub_machine.final = machine->final;
1395 ret1 = re_match(ctx, entire_str, p, curlen, &sub_machine, regs1);
1396
1397 /*
1398 * Now try the second transition
1399 */
1400 memcpy(regs2, regs, sizeof(regs2));
1401 sub_machine.init = tuple->next_state_2;
1402 sub_machine.final = machine->final;
1403 ret2 = re_match(ctx, entire_str, p, curlen, &sub_machine, regs2);
1404
1405 /*
1406 * If they both failed, the whole thing failed. Otherwise,
1407 * return the longer of the two, plus the length we
1408 * ourselves matched previously. Note that we return the
1409 * register set from the winning match.
1410 */
1411 if (ret1 < 0 && ret2 < 0)
1412 {
1413 /* they both failed */
1414 return -1;
1415 }
1416 else if (ret1 > ret2)
1417 {
1418 /* use the first register set and result length */
1419 memcpy(regs, regs1, sizeof(regs1));
1420 return ret1 + (p - str);
1421 }
1422 else
1423 {
1424 /* use the second register set and result length */
1425 memcpy(regs, regs2, sizeof(regs2));
1426 return ret2 + (p - str);
1427 }
1428 }
1429
1430 /*
1431 * If we're in the final state, return success
1432 */
1433 if (cur_state == machine->final)
1434 {
1435 /* finish off any group involved in the final state */
1436 re_note_group(ctx, regs, cur_state, p);
1437
1438 /* return the length we matched */
1439 return p - str;
1440 }
1441 }
1442 }
1443
1444 /* ------------------------------------------------------------------------ */
1445 /*
1446 * Search for a regular expression within a string. Returns -1 if the
1447 * string cannot be found, otherwise returns the offset from the start
1448 * of the string to be searched of the start of the first match for the
1449 * pattern.
1450 */
1451 static int re_search(re_context *ctx, const char *str, size_t len,
1452 const re_machine *machine, re_group_register *regs,
1453 int *result_len)
1454 {
1455 int ofs;
1456
1457 /*
1458 * Starting at the first character in the string, search for the
1459 * pattern at each subsequent character until we either find the
1460 * pattern or run out of string to test.
1461 */
1462 for (ofs = 0 ; ofs < (int)len ; ++ofs)
1463 {
1464 int matchlen;
1465
1466 /* check for a match */
1467 matchlen = re_match(ctx, str, str + ofs, len - ofs,
1468 machine, regs);
1469 if (matchlen >= 0)
1470 {
1471 /* we found a match here - return the length and offset */
1472 *result_len = matchlen;
1473 return ofs;
1474 }
1475 }
1476
1477 /* we didn't find a match */
1478 return -1;
1479 }
1480
1481 /* ------------------------------------------------------------------------ */
1482 /*
1483 * Make a copy of a search string in our private buffer.
1484 */
1485 static void re_save_search_str(re_context *ctx, const char *str, size_t len)
1486 {
1487 /* if the string is empty, this is easy */
1488 if (len == 0)
1489 {
1490 /* nothing to store - just save the length and return */
1491 ctx->curlen = 0;
1492 return;
1493 }
1494
1495 /* if the current buffer isn't big enough, allocate a new one */
1496 if (ctx->strbuf == 0 || ctx->strbufsiz < len)
1497 {
1498 /*
1499 * free any previous buffer - its contents are no longer
1500 * important, since we're about to overwrite it with a new
1501 * string
1502 */
1503 if (ctx->strbuf != 0)
1504 mchfre(ctx->strbuf);
1505
1506 /*
1507 * allocate a new buffer; round up to the next 256-byte
1508 * increment to make sure we're not constantly reallocating to
1509 * random sizes
1510 */
1511 ctx->strbufsiz = ((len + 255) & ~255);
1512
1513 /* allocate it */
1514 ctx->strbuf = (char *)mchalo(ctx->errctx, ctx->strbufsiz,
1515 "regex str");
1516 }
1517
1518 /* copy the string */
1519 memcpy(ctx->strbuf, str, len);
1520
1521 /* save the length */
1522 ctx->curlen = len;
1523 }
1524
1525 /* ------------------------------------------------------------------------ */
1526 /*
1527 * Compile an expression and search for a match within the given string.
1528 * Returns the offset of the match, or -1 if no match was found.
1529 */
1530 int re_compile_and_search(re_context *ctx,
1531 const char *pattern, size_t patlen,
1532 const char *searchstr, size_t searchlen,
1533 int *result_len)
1534 {
1535 re_machine machine;
1536
1537 /* compile the expression - return failure if we get an error */
1538 if (re_compile(ctx, pattern, patlen, &machine) != RE_STATUS_SUCCESS)
1539 return -1;
1540
1541 /* save the search string in our internal buffer */
1542 re_save_search_str(ctx, searchstr, searchlen);
1543
1544 /* clear the group registers */
1545 memset(ctx->regs, 0, sizeof(ctx->regs));
1546
1547 /*
1548 * search for the pattern in our copy of the string - use the copy
1549 * so that the group registers stay valid even if the caller
1550 * deallocates the original string after we return
1551 */
1552 return re_search(ctx, ctx->strbuf, ctx->curlen, &machine,
1553 ctx->regs, result_len);
1554 }
1555
1556 /* ------------------------------------------------------------------------ */
1557 /*
1558 * Compile an expression and check for a match. Returns the length of
1559 * the match if we found a match, -1 if we found no match. This is not
1560 * a search function; we merely match the leading substring of the given
1561 * string to the given pattern.
1562 */
1563 int re_compile_and_match(re_context *ctx,
1564 const char *pattern, size_t patlen,
1565 const char *searchstr, size_t searchlen)
1566 {
1567 re_machine machine;
1568
1569 /* compile the expression - return failure if we get an error */
1570 if (re_compile(ctx, pattern, patlen, &machine) != RE_STATUS_SUCCESS)
1571 return FALSE;
1572
1573 /* save the search string in our internal buffer */
1574 re_save_search_str(ctx, searchstr, searchlen);
1575
1576 /* clear the group registers */
1577 memset(ctx->regs, 0, sizeof(ctx->regs));
1578
1579 /* match the string */
1580 return re_match(ctx, ctx->strbuf, ctx->strbuf, ctx->curlen,
1581 &machine, ctx->regs);
1582 }
1583