1 /* nfa - NFA construction routines */
3 /* Copyright (c) 1990 The Regents of the University of California. */
4 /* All rights reserved. */
6 /* This code is derived from software contributed to Berkeley by */
9 /* The United States Government has rights in this work pursuant */
10 /* to contract no. DE-AC03-76SF00098 between the United States */
11 /* Department of Energy and the University of California. */
13 /* This file is part of flex. */
15 /* Redistribution and use in source and binary forms, with or without */
16 /* modification, are permitted provided that the following conditions */
19 /* 1. Redistributions of source code must retain the above copyright */
20 /* notice, this list of conditions and the following disclaimer. */
21 /* 2. Redistributions in binary form must reproduce the above copyright */
22 /* notice, this list of conditions and the following disclaimer in the */
23 /* documentation and/or other materials provided with the distribution. */
25 /* Neither the name of the University nor the names of its contributors */
26 /* may be used to endorse or promote products derived from this software */
27 /* without specific prior written permission. */
29 /* THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR */
30 /* IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED */
31 /* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR */
37 /* declare functions that have forward references */
40 void mkxtion(int, int);
43 /* add_accept - add an accepting state to a machine
45 * accepting_number becomes mach's accepting number.
48 void add_accept (int mach, int accepting_number)
50 /* Hang the accepting number off an epsilon state. if it is associated
51 * with a state that has a non-epsilon out-transition, then the state
52 * will accept BEFORE it makes that transition, i.e., one character
56 if (transchar[finalst[mach]] == SYM_EPSILON)
57 accptnum[finalst[mach]] = accepting_number;
60 int astate = mkstate (SYM_EPSILON);
62 accptnum[astate] = accepting_number;
63 (void) link_machines (mach, astate);
68 /* copysingl - make a given number of copies of a singleton machine
72 * newsng = copysingl( singl, num );
74 * newsng - a new singleton composed of num copies of singl
75 * singl - a singleton machine
76 * num - the number of copies of singl to be present in newsng
79 int copysingl (int singl, int num)
83 copy = mkstate (SYM_EPSILON);
85 for (i = 1; i <= num; ++i)
86 copy = link_machines (copy, dupmachine (singl));
92 /* dumpnfa - debugging routine to write out an nfa */
94 void dumpnfa (int state1)
96 int sym, tsp1, tsp2, anum, ns;
100 ("\n\n********** beginning dump of nfa with start state %d\n"),
103 /* We probably should loop starting at firstst[state1] and going to
104 * lastst[state1], but they're not maintained properly when we "or"
105 * all of the rules together. So we use our knowledge that the machine
106 * starts at state 1 and ends at lastnfa.
109 /* for ( ns = firstst[state1]; ns <= lastst[state1]; ++ns ) */
110 for (ns = 1; ns <= lastnfa; ++ns) {
111 fprintf (stderr, _("state # %4d\t"), ns);
118 fprintf (stderr, "%3d: %4d, %4d", sym, tsp1, tsp2);
121 fprintf (stderr, " [%d]", anum);
123 fprintf (stderr, "\n");
126 fprintf (stderr, _("********** end of dump\n"));
130 /* dupmachine - make a duplicate of a given machine
134 * copy = dupmachine( mach );
136 * copy - holds duplicate of mach
137 * mach - machine to be duplicated
139 * note that the copy of mach is NOT an exact duplicate; rather, all the
140 * transition states values are adjusted so that the copy is self-contained,
141 * as the original should have been.
143 * also note that the original MUST be contiguous, with its low and high
144 * states accessible by the arrays firstst and lastst
147 int dupmachine (int mach)
149 int i, init, state_offset;
151 int last = lastst[mach];
153 for (i = firstst[mach]; i <= last; ++i) {
154 state = mkstate (transchar[i]);
156 if (trans1[i] != NO_TRANSITION) {
157 mkxtion (finalst[state], trans1[i] + state - i);
159 if (transchar[i] == SYM_EPSILON &&
160 trans2[i] != NO_TRANSITION)
161 mkxtion (finalst[state],
162 trans2[i] + state - i);
165 accptnum[state] = accptnum[i];
169 flexfatal (_("empty machine in dupmachine()"));
171 state_offset = state - i + 1;
173 init = mach + state_offset;
174 firstst[init] = firstst[mach] + state_offset;
175 finalst[init] = finalst[mach] + state_offset;
176 lastst[init] = lastst[mach] + state_offset;
182 /* finish_rule - finish up the processing for a rule
184 * An accepting number is added to the given machine. If variable_trail_rule
185 * is true then the rule has trailing context and both the head and trail
186 * are variable size. Otherwise if headcnt or trailcnt is non-zero then
187 * the machine recognizes a pattern with trailing context and headcnt is
188 * the number of characters in the matched part of the pattern, or zero
189 * if the matched part has variable length. trailcnt is the number of
190 * trailing context characters in the pattern, or zero if the trailing
191 * context has variable length.
194 void finish_rule (int mach, int variable_trail_rule, int headcnt, int trailcnt,
197 char action_text[MAXLINE];
199 add_accept (mach, num_rules);
201 /* We did this in new_rule(), but it often gets the wrong
202 * number because we do it before we start parsing the current rule.
204 rule_linenum[num_rules] = linenum;
206 /* If this is a continued action, then the line-number has already
207 * been updated, giving us the wrong number.
209 if (continued_action)
210 --rule_linenum[num_rules];
213 /* If the previous rule was continued action, then we inherit the
214 * previous newline flag, possibly overriding the current one.
216 if (pcont_act && rule_has_nl[num_rules - 1])
217 rule_has_nl[num_rules] = true;
219 snprintf (action_text, sizeof(action_text), "case %d:\n", num_rules);
220 add_action (action_text);
221 if (rule_has_nl[num_rules]) {
222 snprintf (action_text, sizeof(action_text), "/* rule %d can match eol */\n",
224 add_action (action_text);
228 if (variable_trail_rule) {
229 rule_type[num_rules] = RULE_VARIABLE;
231 if (performance_report > 0)
234 ("Variable trailing context rule at line %d\n"),
235 rule_linenum[num_rules]);
237 variable_trailing_context_rules = true;
241 rule_type[num_rules] = RULE_NORMAL;
243 if (headcnt > 0 || trailcnt > 0) {
244 /* Do trailing context magic to not match the trailing
247 char *scanner_cp = "YY_G(yy_c_buf_p) = yy_cp";
248 char *scanner_bp = "yy_bp";
251 ("*yy_cp = YY_G(yy_hold_char); /* undo effects of setting up yytext */\n");
254 if (rule_has_nl[num_rules]) {
255 snprintf (action_text, sizeof(action_text),
256 "YY_LINENO_REWIND_TO(%s + %d);\n", scanner_bp, headcnt);
257 add_action (action_text);
259 snprintf (action_text, sizeof(action_text), "%s = %s + %d;\n",
260 scanner_cp, scanner_bp, headcnt);
261 add_action (action_text);
265 if (rule_has_nl[num_rules]) {
266 snprintf (action_text, sizeof(action_text),
267 "YY_LINENO_REWIND_TO(yy_cp - %d);\n", trailcnt);
268 add_action (action_text);
271 snprintf (action_text, sizeof(action_text), "%s -= %d;\n",
272 scanner_cp, trailcnt);
273 add_action (action_text);
277 ("YY_DO_BEFORE_ACTION; /* set up yytext again */\n");
281 /* Okay, in the action code at this point yytext and yyleng have
282 * their proper final values for this rule, so here's the point
283 * to do any user action. But don't do it for continued actions,
284 * as that'll result in multiple YY_RULE_SETUP's.
286 if (!continued_action)
287 add_action ("YY_RULE_SETUP\n");
289 line_directive_out(NULL, 1);
294 /* link_machines - connect two machines together
298 * new = link_machines( first, last );
300 * new - a machine constructed by connecting first to last
301 * first - the machine whose successor is to be last
302 * last - the machine whose predecessor is to be first
304 * note: this routine concatenates the machine first with the machine
305 * last to produce a machine new which will pattern-match first first
306 * and then last, and will fail if either of the sub-patterns fails.
307 * FIRST is set to new by the operation. last is unmolested.
310 int link_machines (int first, int last)
315 else if (last == NIL)
319 mkxtion (finalst[first], last);
320 finalst[first] = finalst[last];
321 lastst[first] = MAX (lastst[first], lastst[last]);
322 firstst[first] = MIN (firstst[first], firstst[last]);
329 /* mark_beginning_as_normal - mark each "beginning" state in a machine
330 * as being a "normal" (i.e., not trailing context-
333 * The "beginning" states are the epsilon closure of the first state
336 void mark_beginning_as_normal (int mach)
338 switch (state_type[mach]) {
340 /* Oh, we've already visited here. */
343 case STATE_TRAILING_CONTEXT:
344 state_type[mach] = STATE_NORMAL;
346 if (transchar[mach] == SYM_EPSILON) {
347 if (trans1[mach] != NO_TRANSITION)
348 mark_beginning_as_normal (trans1[mach]);
350 if (trans2[mach] != NO_TRANSITION)
351 mark_beginning_as_normal (trans2[mach]);
357 ("bad state type in mark_beginning_as_normal()"));
363 /* mkbranch - make a machine that branches to two machines
367 * branch = mkbranch( first, second );
369 * branch - a machine which matches either first's pattern or second's
370 * first, second - machines whose patterns are to be or'ed (the | operator)
372 * Note that first and second are NEITHER destroyed by the operation. Also,
373 * the resulting machine CANNOT be used with any other "mk" operation except
374 * more mkbranch's. Compare with mkor()
377 int mkbranch (int first, int second)
381 if (first == NO_TRANSITION)
384 else if (second == NO_TRANSITION)
387 eps = mkstate (SYM_EPSILON);
389 mkxtion (eps, first);
390 mkxtion (eps, second);
396 /* mkclos - convert a machine into a closure
399 * new = mkclos( state );
401 * new - a new state which matches the closure of "state"
404 int mkclos (int state)
406 return mkopt (mkposcl (state));
410 /* mkopt - make a machine optional
414 * new = mkopt( mach );
416 * new - a machine which optionally matches whatever mach matched
417 * mach - the machine to make optional
420 * 1. mach must be the last machine created
421 * 2. mach is destroyed by the call
428 if (!SUPER_FREE_EPSILON (finalst[mach])) {
429 eps = mkstate (SYM_EPSILON);
430 mach = link_machines (mach, eps);
433 /* Can't skimp on the following if FREE_EPSILON(mach) is true because
434 * some state interior to "mach" might point back to the beginning
437 eps = mkstate (SYM_EPSILON);
438 mach = link_machines (eps, mach);
440 mkxtion (mach, finalst[mach]);
446 /* mkor - make a machine that matches either one of two machines
450 * new = mkor( first, second );
452 * new - a machine which matches either first's pattern or second's
453 * first, second - machines whose patterns are to be or'ed (the | operator)
455 * note that first and second are both destroyed by the operation
456 * the code is rather convoluted because an attempt is made to minimize
457 * the number of epsilon states needed
460 int mkor (int first, int second)
467 else if (second == NIL)
471 /* See comment in mkopt() about why we can't use the first
472 * state of "first" or "second" if they satisfy "FREE_EPSILON".
474 eps = mkstate (SYM_EPSILON);
476 first = link_machines (eps, first);
478 mkxtion (first, second);
480 if (SUPER_FREE_EPSILON (finalst[first]) &&
481 accptnum[finalst[first]] == NIL) {
482 orend = finalst[first];
483 mkxtion (finalst[second], orend);
486 else if (SUPER_FREE_EPSILON (finalst[second]) &&
487 accptnum[finalst[second]] == NIL) {
488 orend = finalst[second];
489 mkxtion (finalst[first], orend);
493 eps = mkstate (SYM_EPSILON);
495 first = link_machines (first, eps);
496 orend = finalst[first];
498 mkxtion (finalst[second], orend);
502 finalst[first] = orend;
507 /* mkposcl - convert a machine into a positive closure
510 * new = mkposcl( state );
512 * new - a machine matching the positive closure of "state"
515 int mkposcl (int state)
519 if (SUPER_FREE_EPSILON (finalst[state])) {
520 mkxtion (finalst[state], state);
525 eps = mkstate (SYM_EPSILON);
526 mkxtion (eps, state);
527 return link_machines (state, eps);
532 /* mkrep - make a replicated machine
535 * new = mkrep( mach, lb, ub );
537 * new - a machine that matches whatever "mach" matched from "lb"
538 * number of times to "ub" number of times
541 * if "ub" is INFINITE_REPEAT then "new" matches "lb" or more occurrences of "mach"
544 int mkrep (int mach, int lb, int ub)
546 int base_mach, tail, copy, i;
548 base_mach = copysingl (mach, lb - 1);
550 if (ub == INFINITE_REPEAT) {
551 copy = dupmachine (mach);
552 mach = link_machines (mach,
553 link_machines (base_mach,
558 tail = mkstate (SYM_EPSILON);
560 for (i = lb; i < ub; ++i) {
561 copy = dupmachine (mach);
562 tail = mkopt (link_machines (copy, tail));
567 link_machines (base_mach, tail));
574 /* mkstate - create a state with a transition on a given symbol
578 * state = mkstate( sym );
580 * state - a new state matching sym
581 * sym - the symbol the new state is to have an out-transition on
583 * note that this routine makes new states in ascending order through the
584 * state array (and increments LASTNFA accordingly). The routine DUPMACHINE
585 * relies on machines being made in ascending order and that they are
586 * CONTIGUOUS. Change it and you will have to rewrite DUPMACHINE (kludge
587 * that it admittedly is)
590 int mkstate (int sym)
592 if (++lastnfa >= current_mns) {
593 if ((current_mns += MNS_INCREMENT) >= maximum_mns)
595 ("input rules are too complicated (>= %d NFA states)"),
600 firstst = reallocate_integer_array (firstst, current_mns);
601 lastst = reallocate_integer_array (lastst, current_mns);
602 finalst = reallocate_integer_array (finalst, current_mns);
604 reallocate_integer_array (transchar, current_mns);
605 trans1 = reallocate_integer_array (trans1, current_mns);
606 trans2 = reallocate_integer_array (trans2, current_mns);
608 reallocate_integer_array (accptnum, current_mns);
610 reallocate_integer_array (assoc_rule, current_mns);
612 reallocate_integer_array (state_type, current_mns);
615 firstst[lastnfa] = lastnfa;
616 finalst[lastnfa] = lastnfa;
617 lastst[lastnfa] = lastnfa;
618 transchar[lastnfa] = sym;
619 trans1[lastnfa] = NO_TRANSITION;
620 trans2[lastnfa] = NO_TRANSITION;
621 accptnum[lastnfa] = NIL;
622 assoc_rule[lastnfa] = num_rules;
623 state_type[lastnfa] = current_state_type;
625 /* Fix up equivalence classes base on this transition. Note that any
626 * character which has its own transition gets its own equivalence
627 * class. Thus only characters which are only in character classes
628 * have a chance at being in the same equivalence class. E.g. "a|b"
629 * puts 'a' and 'b' into two different equivalence classes. "[ab]"
630 * puts them in the same equivalence class (barring other differences
631 * elsewhere in the input).
635 /* We don't have to update the equivalence classes since
636 * that was already done when the ccl was created for the
641 else if (sym == SYM_EPSILON)
648 /* Map NUL's to csize. */
649 mkechar (sym ? sym : csize, nextecm, ecgroup);
656 /* mkxtion - make a transition from one state to another
660 * mkxtion( statefrom, stateto );
662 * statefrom - the state from which the transition is to be made
663 * stateto - the state to which the transition is to be made
666 void mkxtion (int statefrom, int stateto)
668 if (trans1[statefrom] == NO_TRANSITION)
669 trans1[statefrom] = stateto;
671 else if ((transchar[statefrom] != SYM_EPSILON) ||
672 (trans2[statefrom] != NO_TRANSITION))
673 flexfatal (_("found too many transitions in mkxtion()"));
675 else { /* second out-transition for an epsilon state */
677 trans2[statefrom] = stateto;
681 /* new_rule - initialize for a new rule */
685 if (++num_rules >= current_max_rules) {
687 current_max_rules += MAX_RULES_INCREMENT;
688 rule_type = reallocate_integer_array (rule_type,
690 rule_linenum = reallocate_integer_array (rule_linenum,
692 rule_useful = reallocate_integer_array (rule_useful,
694 rule_has_nl = reallocate_bool_array (rule_has_nl,
698 if (num_rules > MAX_RULE)
699 lerr (_("too many rules (> %d)!"), MAX_RULE);
701 rule_linenum[num_rules] = linenum;
702 rule_useful[num_rules] = false;
703 rule_has_nl[num_rules] = false;