1 /* dfa - DFA construction routines */
4 * Copyright (c) 1990 The Regents of the University of California.
7 * This code is derived from software contributed to Berkeley by
10 * The United States Government has rights in this work pursuant
11 * to contract no. DE-AC03-76SF00098 between the United States
12 * Department of Energy and the University of California.
14 * Redistribution and use in source and binary forms with or without
15 * modification are permitted provided that: (1) source distributions retain
16 * this entire copyright notice and comment, and (2) distributions including
17 * binaries display the following acknowledgement: ``This product includes
18 * software developed by the University of California, Berkeley and its
19 * contributors'' in the documentation or other materials provided with the
20 * distribution and in all advertising materials mentioning features or use
21 * of this software. Neither the name of the University nor the names of
22 * its contributors may be used to endorse or promote products derived from
23 * this software without specific prior written permission.
24 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR IMPLIED
25 * WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTIES OF
26 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
29 /* $Header: /home/daffy/u0/vern/flex/RCS/dfa.c,v 2.26 95/04/20 13:53:14 vern Exp $ */
34 /* declare functions that have forward references */
36 void dump_associated_rules PROTO((FILE*, int));
37 void dump_transitions PROTO((FILE*, int[]));
38 void sympartition PROTO((int[], int, int[], int[]));
39 int symfollowset PROTO((int[], int, int, int[]));
42 /* check_for_backing_up - check a DFA state for backing up
45 * void check_for_backing_up( int ds, int state[numecs] );
47 * ds is the number of the state to check and state[] is its out-transitions,
48 * indexed by equivalence class.
51 void check_for_backing_up( ds, state )
55 if ( (reject && ! dfaacc[ds].dfaacc_set) ||
56 (! reject && ! dfaacc[ds].dfaacc_state) )
57 { /* state is non-accepting */
60 if ( backing_up_report )
62 fprintf( backing_up_file,
63 _( "State #%d is non-accepting -\n" ), ds );
65 /* identify the state */
66 dump_associated_rules( backing_up_file, ds );
68 /* Now identify it further using the out- and
71 dump_transitions( backing_up_file, state );
73 putc( '\n', backing_up_file );
79 /* check_trailing_context - check to see if NFA state set constitutes
80 * "dangerous" trailing context
83 * void check_trailing_context( int nfa_states[num_states+1], int num_states,
84 * int accset[nacc+1], int nacc );
87 * Trailing context is "dangerous" if both the head and the trailing
88 * part are of variable size \and/ there's a DFA state which contains
89 * both an accepting state for the head part of the rule and NFA states
90 * which occur after the beginning of the trailing context.
92 * When such a rule is matched, it's impossible to tell if having been
93 * in the DFA state indicates the beginning of the trailing context or
94 * further-along scanning of the pattern. In these cases, a warning
97 * nfa_states[1 .. num_states] is the list of NFA states in the DFA.
98 * accset[1 .. nacc] is the list of accepting numbers for the DFA state.
101 void check_trailing_context( nfa_states, num_states, accset, nacc )
102 int *nfa_states, num_states;
108 for ( i = 1; i <= num_states; ++i )
110 int ns = nfa_states[i];
111 register int type = state_type[ns];
112 register int ar = assoc_rule[ns];
114 if ( type == STATE_NORMAL || rule_type[ar] != RULE_VARIABLE )
118 else if ( type == STATE_TRAILING_CONTEXT )
120 /* Potential trouble. Scan set of accepting numbers
121 * for the one marking the end of the "head". We
122 * assume that this looping will be fairly cheap
123 * since it's rare that an accepting number set
126 for ( j = 1; j <= nacc; ++j )
127 if ( accset[j] & YY_TRAILING_HEAD_MASK )
130 _( "dangerous trailing context" ),
139 /* dump_associated_rules - list the rules associated with a DFA state
141 * Goes through the set of NFA states associated with the DFA and
142 * extracts the first MAX_ASSOC_RULES unique rules, sorts them,
143 * and writes a report to the given file.
146 void dump_associated_rules( file, ds )
151 register int num_associated_rules = 0;
152 int rule_set[MAX_ASSOC_RULES + 1];
154 int size = dfasiz[ds];
156 for ( i = 1; i <= size; ++i )
158 register int rule_num = rule_linenum[assoc_rule[dset[i]]];
160 for ( j = 1; j <= num_associated_rules; ++j )
161 if ( rule_num == rule_set[j] )
164 if ( j > num_associated_rules )
166 if ( num_associated_rules < MAX_ASSOC_RULES )
167 rule_set[++num_associated_rules] = rule_num;
171 bubble( rule_set, num_associated_rules );
173 fprintf( file, _( " associated rule line numbers:" ) );
175 for ( i = 1; i <= num_associated_rules; ++i )
180 fprintf( file, "\t%d", rule_set[i] );
187 /* dump_transitions - list the transitions associated with a DFA state
190 * dump_transitions( FILE *file, int state[numecs] );
192 * Goes through the set of out-transitions and lists them in human-readable
193 * form (i.e., not as equivalence classes); also lists jam transitions
194 * (i.e., all those which are not out-transitions, plus EOF). The dump
195 * is done to the given file.
198 void dump_transitions( file, state )
203 int out_char_set[CSIZE];
205 for ( i = 0; i < csize; ++i )
207 ec = ABS( ecgroup[i] );
208 out_char_set[i] = state[ec];
211 fprintf( file, _( " out-transitions: " ) );
213 list_character_set( file, out_char_set );
215 /* now invert the members of the set to get the jam transitions */
216 for ( i = 0; i < csize; ++i )
217 out_char_set[i] = ! out_char_set[i];
219 fprintf( file, _( "\n jam-transitions: EOF " ) );
221 list_character_set( file, out_char_set );
227 /* epsclosure - construct the epsilon closure of a set of ndfa states
230 * int *epsclosure( int t[num_states], int *numstates_addr,
231 * int accset[num_rules+1], int *nacc_addr,
232 * int *hashval_addr );
235 * The epsilon closure is the set of all states reachable by an arbitrary
236 * number of epsilon transitions, which themselves do not have epsilon
237 * transitions going out, unioned with the set of states which have non-null
238 * accepting numbers. t is an array of size numstates of nfa state numbers.
239 * Upon return, t holds the epsilon closure and *numstates_addr is updated.
240 * accset holds a list of the accepting numbers, and the size of accset is
241 * given by *nacc_addr. t may be subjected to reallocation if it is not
242 * large enough to hold the epsilon closure.
244 * hashval is the hash value for the dfa corresponding to the state set.
247 int *epsclosure( t, ns_addr, accset, nacc_addr, hv_addr )
248 int *t, *ns_addr, accset[], *nacc_addr, *hv_addr;
250 register int stkpos, ns, tsp;
251 int numstates = *ns_addr, nacc, hashval, transsym, nfaccnum;
253 static int did_stk_init = false, *stk;
255 #define MARK_STATE(state) \
256 trans1[state] = trans1[state] - MARKER_DIFFERENCE;
258 #define IS_MARKED(state) (trans1[state] < 0)
260 #define UNMARK_STATE(state) \
261 trans1[state] = trans1[state] + MARKER_DIFFERENCE;
263 #define CHECK_ACCEPT(state) \
265 nfaccnum = accptnum[state]; \
266 if ( nfaccnum != NIL ) \
267 accset[++nacc] = nfaccnum; \
270 #define DO_REALLOCATION \
272 current_max_dfa_size += MAX_DFA_SIZE_INCREMENT; \
274 t = reallocate_integer_array( t, current_max_dfa_size ); \
275 stk = reallocate_integer_array( stk, current_max_dfa_size ); \
278 #define PUT_ON_STACK(state) \
280 if ( ++stkend >= current_max_dfa_size ) \
282 stk[stkend] = state; \
286 #define ADD_STATE(state) \
288 if ( ++numstates >= current_max_dfa_size ) \
290 t[numstates] = state; \
294 #define STACK_STATE(state) \
296 PUT_ON_STACK(state) \
297 CHECK_ACCEPT(state) \
298 if ( nfaccnum != NIL || transchar[state] != SYM_EPSILON ) \
303 if ( ! did_stk_init )
305 stk = allocate_integer_array( current_max_dfa_size );
309 nacc = stkend = hashval = 0;
311 for ( nstate = 1; nstate <= numstates; ++nstate )
315 /* The state could be marked if we've already pushed it onto
318 if ( ! IS_MARKED(ns) )
326 for ( stkpos = 1; stkpos <= stkend; ++stkpos )
329 transsym = transchar[ns];
331 if ( transsym == SYM_EPSILON )
333 tsp = trans1[ns] + MARKER_DIFFERENCE;
335 if ( tsp != NO_TRANSITION )
337 if ( ! IS_MARKED(tsp) )
342 if ( tsp != NO_TRANSITION && ! IS_MARKED(tsp) )
348 /* Clear out "visit" markers. */
350 for ( stkpos = 1; stkpos <= stkend; ++stkpos )
352 if ( IS_MARKED(stk[stkpos]) )
353 UNMARK_STATE(stk[stkpos])
356 _( "consistency check failed in epsclosure()" ) );
359 *ns_addr = numstates;
367 /* increase_max_dfas - increase the maximum number of DFAs */
369 void increase_max_dfas()
371 current_max_dfas += MAX_DFAS_INCREMENT;
375 base = reallocate_integer_array( base, current_max_dfas );
376 def = reallocate_integer_array( def, current_max_dfas );
377 dfasiz = reallocate_integer_array( dfasiz, current_max_dfas );
378 accsiz = reallocate_integer_array( accsiz, current_max_dfas );
379 dhash = reallocate_integer_array( dhash, current_max_dfas );
380 dss = reallocate_int_ptr_array( dss, current_max_dfas );
381 dfaacc = reallocate_dfaacc_union( dfaacc, current_max_dfas );
385 reallocate_integer_array( nultrans, current_max_dfas );
389 /* ntod - convert an ndfa to a dfa
391 * Creates the dfa corresponding to the ndfa we've constructed. The
392 * dfa starts out in state #1.
397 int *accset, ds, nacc, newds;
398 int sym, hashval, numstates, dsize;
399 int num_full_table_rows; /* used only for -f */
401 int targptr, totaltrans, i, comstate, comfreq, targ;
402 int symlist[CSIZE + 1];
403 int num_start_states;
404 int todo_head, todo_next;
406 /* Note that the following are indexed by *equivalence classes*
407 * and not by characters. Since equivalence classes are indexed
408 * beginning with 1, even if the scanner accepts NUL's, this
409 * means that (since every character is potentially in its own
410 * equivalence class) these arrays must have room for indices
411 * from 1 to CSIZE, so their size must be CSIZE + 1.
413 int duplist[CSIZE + 1], state[CSIZE + 1];
414 int targfreq[CSIZE + 1], targstate[CSIZE + 1];
416 accset = allocate_integer_array( num_rules + 1 );
417 nset = allocate_integer_array( current_max_dfa_size );
419 /* The "todo" queue is represented by the head, which is the DFA
420 * state currently being processed, and the "next", which is the
421 * next DFA state number available (not in use). We depend on the
422 * fact that snstods() returns DFA's \in increasing order/, and thus
423 * need only know the bounds of the dfas to be processed.
425 todo_head = todo_next = 0;
427 for ( i = 0; i <= csize; ++i )
433 for ( i = 0; i <= num_rules; ++i )
439 fputs( _( "\n\nDFA Dump:\n\n" ), stderr );
444 /* Check to see whether we should build a separate table for
445 * transitions on NUL characters. We don't do this for full-speed
446 * (-F) scanners, since for them we don't have a simple state
447 * number lying around with which to index the table. We also
448 * don't bother doing it for scanners unless (1) NUL is in its own
449 * equivalence class (indicated by a positive value of
450 * ecgroup[NUL]), (2) NUL's equivalence class is the last
451 * equivalence class, and (3) the number of equivalence classes is
452 * the same as the number of characters. This latter case comes
453 * about when useecs is false or when it's true but every character
454 * still manages to land in its own class (unlikely, but it's
455 * cheap to check for). If all these things are true then the
456 * character code needed to represent NUL's equivalence class for
457 * indexing the tables is going to take one more bit than the
458 * number of characters, and therefore we won't be assured of
459 * being able to fit it into a YY_CHAR variable. This rules out
460 * storing the transitions in a compressed table, since the code
461 * for interpreting them uses a YY_CHAR variable (perhaps it
462 * should just use an integer, though; this is worth pondering ...
465 * Finally, for full tables, we want the number of entries in the
466 * table to be a power of two so the array references go fast (it
467 * will just take a shift to compute the major index). If
468 * encoding NUL's transitions in the table will spoil this, we
469 * give it its own table (note that this will be the case if we're
470 * not using equivalence classes).
473 /* Note that the test for ecgroup[0] == numecs below accomplishes
474 * both (1) and (2) above
476 if ( ! fullspd && ecgroup[0] == numecs )
478 /* NUL is alone in its equivalence class, which is the
481 int use_NUL_table = (numecs == csize);
483 if ( fulltbl && ! use_NUL_table )
485 /* We still may want to use the table if numecs
490 for ( power_of_two = 1; power_of_two <= csize;
492 if ( numecs == power_of_two )
494 use_NUL_table = true;
500 nultrans = allocate_integer_array( current_max_dfas );
502 /* From now on, nultrans != nil indicates that we're
503 * saving null transitions for later, separate encoding.
510 for ( i = 0; i <= numecs; ++i )
513 place_state( state, 0, 0 );
514 dfaacc[0].dfaacc_state = 0;
520 /* We won't be including NUL's transitions in the
521 * table, so build it for entries from 0 .. numecs - 1.
523 num_full_table_rows = numecs;
526 /* Take into account the fact that we'll be including
527 * the NUL entries in the transition table. Build it
530 num_full_table_rows = numecs + 1;
532 /* Unless -Ca, declare it "short" because it's a real
533 * long-shot that that won't be large enough.
535 out_str_dec( "static yyconst %s yy_nxt[][%d] =\n {\n",
536 /* '}' so vi doesn't get too confused */
537 long_align ? "long" : "short", num_full_table_rows );
541 /* Generate 0 entries for state #0. */
542 for ( i = 0; i < num_full_table_rows; ++i )
549 /* Create the first states. */
551 num_start_states = lastsc * 2;
553 for ( i = 1; i <= num_start_states; ++i )
557 /* For each start condition, make one state for the case when
558 * we're at the beginning of the line (the '^' operator) and
559 * one for the case when we're not.
562 nset[numstates] = scset[(i / 2) + 1];
565 mkbranch( scbol[i / 2], scset[i / 2] );
567 nset = epsclosure( nset, &numstates, accset, &nacc, &hashval );
569 if ( snstods( nset, numstates, accset, nacc, hashval, &ds ) )
575 if ( variable_trailing_context_rules && nacc > 0 )
576 check_trailing_context( nset, numstates,
583 if ( ! snstods( nset, 0, accset, 0, 0, &end_of_buffer_state ) )
585 _( "could not create unique end-of-buffer state" ) );
592 while ( todo_head < todo_next )
597 for ( i = 1; i <= numecs; ++i )
606 fprintf( stderr, _( "state # %d:\n" ), ds );
608 sympartition( dset, dsize, symlist, duplist );
610 for ( sym = 1; sym <= numecs; ++sym )
616 if ( duplist[sym] == NIL )
618 /* Symbol has unique out-transitions. */
619 numstates = symfollowset( dset, dsize,
621 nset = epsclosure( nset, &numstates,
622 accset, &nacc, &hashval );
624 if ( snstods( nset, numstates, accset,
625 nacc, hashval, &newds ) )
627 totnst = totnst + numstates;
632 variable_trailing_context_rules &&
634 check_trailing_context(
642 fprintf( stderr, "\t%d\t%d\n",
645 targfreq[++targptr] = 1;
646 targstate[targptr] = newds;
652 /* sym's equivalence class has the same
653 * transitions as duplist(sym)'s
656 targ = state[duplist[sym]];
660 fprintf( stderr, "\t%d\t%d\n",
663 /* Update frequency count for
668 while ( targstate[++i] != targ )
680 if ( caseins && ! useecs )
684 for ( i = 'A', j = 'a'; i <= 'Z'; ++i, ++j )
686 if ( state[i] == 0 && state[j] != 0 )
687 /* We're adding a transition. */
690 else if ( state[i] != 0 && state[j] == 0 )
691 /* We're taking away a transition. */
698 numsnpairs += totaltrans;
700 if ( ds > num_start_states )
701 check_for_backing_up( ds, state );
705 nultrans[ds] = state[NUL_ec];
706 state[NUL_ec] = 0; /* remove transition */
713 /* Supply array's 0-element. */
714 if ( ds == end_of_buffer_state )
715 mk2data( -end_of_buffer_state );
717 mk2data( end_of_buffer_state );
719 for ( i = 1; i < num_full_table_rows; ++i )
720 /* Jams are marked by negative of state
723 mk2data( state[i] ? state[i] : -ds );
730 place_state( state, ds, totaltrans );
732 else if ( ds == end_of_buffer_state )
733 /* Special case this state to make sure it does what
734 * it's supposed to, i.e., jam on end-of-buffer.
736 stack1( ds, 0, 0, JAMSTATE );
738 else /* normal, compressed state */
740 /* Determine which destination state is the most
741 * common, and how many transitions to it there are.
747 for ( i = 1; i <= targptr; ++i )
748 if ( targfreq[i] > comfreq )
750 comfreq = targfreq[i];
751 comstate = targstate[i];
754 bldtbl( state, ds, totaltrans, comstate, comfreq );
761 else if ( ! fullspd )
763 cmptmps(); /* create compressed template entries */
765 /* Create tables for all the states with only one
770 mk1tbl( onestate[onesp], onesym[onesp], onenext[onesp],
778 flex_free( (void *) accset );
779 flex_free( (void *) nset );
783 /* snstods - converts a set of ndfa states into a dfa state
786 * is_new_state = snstods( int sns[numstates], int numstates,
787 * int accset[num_rules+1], int nacc,
788 * int hashval, int *newds_addr );
790 * On return, the dfa state number is in newds.
793 int snstods( sns, numstates, accset, nacc, hashval, newds_addr )
794 int sns[], numstates, accset[], nacc, hashval, *newds_addr;
800 for ( i = 1; i <= lastdfa; ++i )
801 if ( hashval == dhash[i] )
803 if ( numstates == dfasiz[i] )
809 /* We sort the states in sns so we
810 * can compare it to oldsns quickly.
811 * We use bubble because there probably
812 * aren't very many states.
814 bubble( sns, numstates );
818 for ( j = 1; j <= numstates; ++j )
819 if ( sns[j] != oldsns[j] )
836 /* Make a new dfa. */
838 if ( ++lastdfa >= current_max_dfas )
843 dss[newds] = allocate_integer_array( numstates + 1 );
845 /* If we haven't already sorted the states in sns, we do so now,
846 * so that future comparisons with it can be made quickly.
850 bubble( sns, numstates );
852 for ( i = 1; i <= numstates; ++i )
853 dss[newds][i] = sns[i];
855 dfasiz[newds] = numstates;
856 dhash[newds] = hashval;
861 dfaacc[newds].dfaacc_set = (int *) 0;
863 dfaacc[newds].dfaacc_state = 0;
870 /* We sort the accepting set in increasing order so the
871 * disambiguating rule that the first rule listed is considered
872 * match in the event of ties will work. We use a bubble
873 * sort since the list is probably quite small.
876 bubble( accset, nacc );
878 dfaacc[newds].dfaacc_set = allocate_integer_array( nacc + 1 );
880 /* Save the accepting set for later */
881 for ( i = 1; i <= nacc; ++i )
883 dfaacc[newds].dfaacc_set[i] = accset[i];
885 if ( accset[i] <= num_rules )
886 /* Who knows, perhaps a REJECT can yield
889 rule_useful[accset[i]] = true;
892 accsiz[newds] = nacc;
897 /* Find lowest numbered rule so the disambiguating rule
902 for ( i = 1; i <= nacc; ++i )
906 dfaacc[newds].dfaacc_state = j;
908 if ( j <= num_rules )
909 rule_useful[j] = true;
918 /* symfollowset - follow the symbol transitions one step
921 * numstates = symfollowset( int ds[current_max_dfa_size], int dsize,
922 * int transsym, int nset[current_max_dfa_size] );
925 int symfollowset( ds, dsize, transsym, nset )
926 int ds[], dsize, transsym, nset[];
928 int ns, tsp, sym, i, j, lenccl, ch, numstates, ccllist;
932 for ( i = 1; i <= dsize; ++i )
933 { /* for each nfa state ns in the state set of ds */
939 { /* it's a character class */
941 ccllist = cclmap[sym];
942 lenccl = ccllen[sym];
946 for ( j = 0; j < lenccl; ++j )
948 /* Loop through negated character
951 ch = ccltbl[ccllist + j];
957 /* Transsym isn't in negated
962 else if ( ch == transsym )
963 /* next 2 */ goto bottom;
966 /* Didn't find transsym in ccl. */
967 nset[++numstates] = tsp;
971 for ( j = 0; j < lenccl; ++j )
973 ch = ccltbl[ccllist + j];
980 else if ( ch == transsym )
982 nset[++numstates] = tsp;
988 else if ( sym >= 'A' && sym <= 'Z' && caseins )
990 _( "consistency check failed in symfollowset" ) );
992 else if ( sym == SYM_EPSILON )
996 else if ( ABS( ecgroup[sym] ) == transsym )
997 nset[++numstates] = tsp;
1006 /* sympartition - partition characters with same out-transitions
1009 * sympartition( int ds[current_max_dfa_size], int numstates,
1010 * int symlist[numecs], int duplist[numecs] );
1013 void sympartition( ds, numstates, symlist, duplist )
1014 int ds[], numstates;
1015 int symlist[], duplist[];
1017 int tch, i, j, k, ns, dupfwd[CSIZE + 1], lenccl, cclp, ich;
1019 /* Partitioning is done by creating equivalence classes for those
1020 * characters which have out-transitions from the given state. Thus
1021 * we are really creating equivalence classes of equivalence classes.
1024 for ( i = 1; i <= numecs; ++i )
1025 { /* initialize equivalence class list */
1031 dupfwd[numecs] = NIL;
1033 for ( i = 1; i <= numstates; ++i )
1036 tch = transchar[ns];
1038 if ( tch != SYM_EPSILON )
1040 if ( tch < -lastccl || tch >= csize )
1043 _( "bad transition character detected in sympartition()" ) );
1047 { /* character transition */
1048 int ec = ecgroup[tch];
1050 mkechar( ec, dupfwd, duplist );
1055 { /* character class */
1058 lenccl = ccllen[tch];
1060 mkeccl( ccltbl + cclp, lenccl, dupfwd,
1061 duplist, numecs, NUL_ec );
1067 for ( k = 0; k < lenccl; ++k )
1069 ich = ccltbl[cclp + k];
1074 for ( ++j; j < ich; ++j )
1078 for ( ++j; j <= numecs; ++j )
1083 for ( k = 0; k < lenccl; ++k )
1085 ich = ccltbl[cclp + k];