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 are permitted provided
15 * that: (1) source distributions retain this entire copyright notice and
16 * comment, and (2) distributions including binaries display the following
17 * acknowledgement: ``This product includes software developed by the
18 * University of California, Berkeley and its contributors'' in the
19 * documentation or other materials provided with the distribution and in
20 * all advertising materials mentioning features or use of this software.
21 * Neither the name of the University nor the names of its contributors may
22 * be used to endorse or promote products derived from this software without
23 * 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 $ */
30 /* $FreeBSD: src/usr.bin/lex/dfa.c,v 1.5 1999/10/27 07:56:43 obrien Exp $ */
35 /* declare functions that have forward references */
37 void dump_associated_rules PROTO((FILE*, int));
38 void dump_transitions PROTO((FILE*, int[]));
39 void sympartition PROTO((int[], int, int[], int[]));
40 int symfollowset PROTO((int[], int, int, int[]));
43 /* check_for_backing_up - check a DFA state for backing up
46 * void check_for_backing_up( int ds, int state[numecs] );
48 * ds is the number of the state to check and state[] is its out-transitions,
49 * indexed by equivalence class.
52 void check_for_backing_up( ds, state )
56 if ( (reject && ! dfaacc[ds].dfaacc_set) ||
57 (! reject && ! dfaacc[ds].dfaacc_state) )
58 { /* state is non-accepting */
61 if ( backing_up_report )
63 fprintf( backing_up_file,
64 _( "State #%d is non-accepting -\n" ), ds );
66 /* identify the state */
67 dump_associated_rules( backing_up_file, ds );
69 /* Now identify it further using the out- and
72 dump_transitions( backing_up_file, state );
74 putc( '\n', backing_up_file );
80 /* check_trailing_context - check to see if NFA state set constitutes
81 * "dangerous" trailing context
84 * void check_trailing_context( int nfa_states[num_states+1], int num_states,
85 * int accset[nacc+1], int nacc );
88 * Trailing context is "dangerous" if both the head and the trailing
89 * part are of variable size \and/ there's a DFA state which contains
90 * both an accepting state for the head part of the rule and NFA states
91 * which occur after the beginning of the trailing context.
93 * When such a rule is matched, it's impossible to tell if having been
94 * in the DFA state indicates the beginning of the trailing context or
95 * further-along scanning of the pattern. In these cases, a warning
98 * nfa_states[1 .. num_states] is the list of NFA states in the DFA.
99 * accset[1 .. nacc] is the list of accepting numbers for the DFA state.
102 void check_trailing_context( nfa_states, num_states, accset, nacc )
103 int *nfa_states, num_states;
109 for ( i = 1; i <= num_states; ++i )
111 int ns = nfa_states[i];
112 register int type = state_type[ns];
113 register int ar = assoc_rule[ns];
115 if ( type == STATE_NORMAL || rule_type[ar] != RULE_VARIABLE )
119 else if ( type == STATE_TRAILING_CONTEXT )
121 /* Potential trouble. Scan set of accepting numbers
122 * for the one marking the end of the "head". We
123 * assume that this looping will be fairly cheap
124 * since it's rare that an accepting number set
127 for ( j = 1; j <= nacc; ++j )
128 if ( accset[j] & YY_TRAILING_HEAD_MASK )
131 _( "dangerous trailing context" ),
140 /* dump_associated_rules - list the rules associated with a DFA state
142 * Goes through the set of NFA states associated with the DFA and
143 * extracts the first MAX_ASSOC_RULES unique rules, sorts them,
144 * and writes a report to the given file.
147 void dump_associated_rules( file, ds )
152 register int num_associated_rules = 0;
153 int rule_set[MAX_ASSOC_RULES + 1];
155 int size = dfasiz[ds];
157 for ( i = 1; i <= size; ++i )
159 register int rule_num = rule_linenum[assoc_rule[dset[i]]];
161 for ( j = 1; j <= num_associated_rules; ++j )
162 if ( rule_num == rule_set[j] )
165 if ( j > num_associated_rules )
167 if ( num_associated_rules < MAX_ASSOC_RULES )
168 rule_set[++num_associated_rules] = rule_num;
172 bubble( rule_set, num_associated_rules );
174 fprintf( file, _( " associated rule line numbers:" ) );
176 for ( i = 1; i <= num_associated_rules; ++i )
181 fprintf( file, "\t%d", rule_set[i] );
188 /* dump_transitions - list the transitions associated with a DFA state
191 * dump_transitions( FILE *file, int state[numecs] );
193 * Goes through the set of out-transitions and lists them in human-readable
194 * form (i.e., not as equivalence classes); also lists jam transitions
195 * (i.e., all those which are not out-transitions, plus EOF). The dump
196 * is done to the given file.
199 void dump_transitions( file, state )
204 int out_char_set[CSIZE];
206 for ( i = 0; i < csize; ++i )
208 ec = ABS( ecgroup[i] );
209 out_char_set[i] = state[ec];
212 fprintf( file, _( " out-transitions: " ) );
214 list_character_set( file, out_char_set );
216 /* now invert the members of the set to get the jam transitions */
217 for ( i = 0; i < csize; ++i )
218 out_char_set[i] = ! out_char_set[i];
220 fprintf( file, _( "\n jam-transitions: EOF " ) );
222 list_character_set( file, out_char_set );
228 /* epsclosure - construct the epsilon closure of a set of ndfa states
231 * int *epsclosure( int t[num_states], int *numstates_addr,
232 * int accset[num_rules+1], int *nacc_addr,
233 * int *hashval_addr );
236 * The epsilon closure is the set of all states reachable by an arbitrary
237 * number of epsilon transitions, which themselves do not have epsilon
238 * transitions going out, unioned with the set of states which have non-null
239 * accepting numbers. t is an array of size numstates of nfa state numbers.
240 * Upon return, t holds the epsilon closure and *numstates_addr is updated.
241 * accset holds a list of the accepting numbers, and the size of accset is
242 * given by *nacc_addr. t may be subjected to reallocation if it is not
243 * large enough to hold the epsilon closure.
245 * hashval is the hash value for the dfa corresponding to the state set.
248 int *epsclosure( t, ns_addr, accset, nacc_addr, hv_addr )
249 int *t, *ns_addr, accset[], *nacc_addr, *hv_addr;
251 register int stkpos, ns, tsp;
252 int numstates = *ns_addr, nacc, hashval, transsym, nfaccnum;
254 static int did_stk_init = false, *stk;
256 #define MARK_STATE(state) \
257 trans1[state] = trans1[state] - MARKER_DIFFERENCE;
259 #define IS_MARKED(state) (trans1[state] < 0)
261 #define UNMARK_STATE(state) \
262 trans1[state] = trans1[state] + MARKER_DIFFERENCE;
264 #define CHECK_ACCEPT(state) \
266 nfaccnum = accptnum[state]; \
267 if ( nfaccnum != NIL ) \
268 accset[++nacc] = nfaccnum; \
271 #define DO_REALLOCATION \
273 current_max_dfa_size += MAX_DFA_SIZE_INCREMENT; \
275 t = reallocate_integer_array( t, current_max_dfa_size ); \
276 stk = reallocate_integer_array( stk, current_max_dfa_size ); \
279 #define PUT_ON_STACK(state) \
281 if ( ++stkend >= current_max_dfa_size ) \
283 stk[stkend] = state; \
287 #define ADD_STATE(state) \
289 if ( ++numstates >= current_max_dfa_size ) \
291 t[numstates] = state; \
295 #define STACK_STATE(state) \
297 PUT_ON_STACK(state) \
298 CHECK_ACCEPT(state) \
299 if ( nfaccnum != NIL || transchar[state] != SYM_EPSILON ) \
304 if ( ! did_stk_init )
306 stk = allocate_integer_array( current_max_dfa_size );
310 nacc = stkend = hashval = 0;
312 for ( nstate = 1; nstate <= numstates; ++nstate )
316 /* The state could be marked if we've already pushed it onto
319 if ( ! IS_MARKED(ns) )
327 for ( stkpos = 1; stkpos <= stkend; ++stkpos )
330 transsym = transchar[ns];
332 if ( transsym == SYM_EPSILON )
334 tsp = trans1[ns] + MARKER_DIFFERENCE;
336 if ( tsp != NO_TRANSITION )
338 if ( ! IS_MARKED(tsp) )
343 if ( tsp != NO_TRANSITION && ! IS_MARKED(tsp) )
349 /* Clear out "visit" markers. */
351 for ( stkpos = 1; stkpos <= stkend; ++stkpos )
353 if ( IS_MARKED(stk[stkpos]) )
354 UNMARK_STATE(stk[stkpos])
357 _( "consistency check failed in epsclosure()" ) );
360 *ns_addr = numstates;
368 /* increase_max_dfas - increase the maximum number of DFAs */
370 void increase_max_dfas()
372 current_max_dfas += MAX_DFAS_INCREMENT;
376 base = reallocate_integer_array( base, current_max_dfas );
377 def = reallocate_integer_array( def, current_max_dfas );
378 dfasiz = reallocate_integer_array( dfasiz, current_max_dfas );
379 accsiz = reallocate_integer_array( accsiz, current_max_dfas );
380 dhash = reallocate_integer_array( dhash, current_max_dfas );
381 dss = reallocate_int_ptr_array( dss, current_max_dfas );
382 dfaacc = reallocate_dfaacc_union( dfaacc, current_max_dfas );
386 reallocate_integer_array( nultrans, current_max_dfas );
390 /* ntod - convert an ndfa to a dfa
392 * Creates the dfa corresponding to the ndfa we've constructed. The
393 * dfa starts out in state #1.
398 int *accset, ds, nacc, newds;
399 int sym, hashval, numstates, dsize;
400 int num_full_table_rows; /* used only for -f */
402 int targptr, totaltrans, i, comstate, comfreq, targ;
403 int symlist[CSIZE + 1];
404 int num_start_states;
405 int todo_head, todo_next;
407 /* Note that the following are indexed by *equivalence classes*
408 * and not by characters. Since equivalence classes are indexed
409 * beginning with 1, even if the scanner accepts NUL's, this
410 * means that (since every character is potentially in its own
411 * equivalence class) these arrays must have room for indices
412 * from 1 to CSIZE, so their size must be CSIZE + 1.
414 int duplist[CSIZE + 1], state[CSIZE + 1];
415 int targfreq[CSIZE + 1], targstate[CSIZE + 1];
417 accset = allocate_integer_array( num_rules + 1 );
418 nset = allocate_integer_array( current_max_dfa_size );
420 /* The "todo" queue is represented by the head, which is the DFA
421 * state currently being processed, and the "next", which is the
422 * next DFA state number available (not in use). We depend on the
423 * fact that snstods() returns DFA's \in increasing order/, and thus
424 * need only know the bounds of the dfas to be processed.
426 todo_head = todo_next = 0;
428 for ( i = 0; i <= csize; ++i )
434 for ( i = 0; i <= num_rules; ++i )
440 fputs( _( "\n\nDFA Dump:\n\n" ), stderr );
445 /* Check to see whether we should build a separate table for
446 * transitions on NUL characters. We don't do this for full-speed
447 * (-F) scanners, since for them we don't have a simple state
448 * number lying around with which to index the table. We also
449 * don't bother doing it for scanners unless (1) NUL is in its own
450 * equivalence class (indicated by a positive value of
451 * ecgroup[NUL]), (2) NUL's equivalence class is the last
452 * equivalence class, and (3) the number of equivalence classes is
453 * the same as the number of characters. This latter case comes
454 * about when useecs is false or when it's true but every character
455 * still manages to land in its own class (unlikely, but it's
456 * cheap to check for). If all these things are true then the
457 * character code needed to represent NUL's equivalence class for
458 * indexing the tables is going to take one more bit than the
459 * number of characters, and therefore we won't be assured of
460 * being able to fit it into a YY_CHAR variable. This rules out
461 * storing the transitions in a compressed table, since the code
462 * for interpreting them uses a YY_CHAR variable (perhaps it
463 * should just use an integer, though; this is worth pondering ...
466 * Finally, for full tables, we want the number of entries in the
467 * table to be a power of two so the array references go fast (it
468 * will just take a shift to compute the major index). If
469 * encoding NUL's transitions in the table will spoil this, we
470 * give it its own table (note that this will be the case if we're
471 * not using equivalence classes).
474 /* Note that the test for ecgroup[0] == numecs below accomplishes
475 * both (1) and (2) above
477 if ( ! fullspd && ecgroup[0] == numecs )
479 /* NUL is alone in its equivalence class, which is the
482 int use_NUL_table = (numecs == csize);
484 if ( fulltbl && ! use_NUL_table )
486 /* We still may want to use the table if numecs
491 for ( power_of_two = 1; power_of_two <= csize;
493 if ( numecs == power_of_two )
495 use_NUL_table = true;
501 nultrans = allocate_integer_array( current_max_dfas );
503 /* From now on, nultrans != nil indicates that we're
504 * saving null transitions for later, separate encoding.
511 for ( i = 0; i <= numecs; ++i )
514 place_state( state, 0, 0 );
515 dfaacc[0].dfaacc_state = 0;
521 /* We won't be including NUL's transitions in the
522 * table, so build it for entries from 0 .. numecs - 1.
524 num_full_table_rows = numecs;
527 /* Take into account the fact that we'll be including
528 * the NUL entries in the transition table. Build it
531 num_full_table_rows = numecs + 1;
533 /* Unless -Ca, declare it "short" because it's a real
534 * long-shot that that won't be large enough.
536 out_str_dec( "static yyconst %s yy_nxt[][%d] =\n {\n",
537 /* '}' so vi doesn't get too confused */
538 long_align ? "long" : "short", num_full_table_rows );
542 /* Generate 0 entries for state #0. */
543 for ( i = 0; i < num_full_table_rows; ++i )
550 /* Create the first states. */
552 num_start_states = lastsc * 2;
554 for ( i = 1; i <= num_start_states; ++i )
558 /* For each start condition, make one state for the case when
559 * we're at the beginning of the line (the '^' operator) and
560 * one for the case when we're not.
563 nset[numstates] = scset[(i / 2) + 1];
566 mkbranch( scbol[i / 2], scset[i / 2] );
568 nset = epsclosure( nset, &numstates, accset, &nacc, &hashval );
570 if ( snstods( nset, numstates, accset, nacc, hashval, &ds ) )
576 if ( variable_trailing_context_rules && nacc > 0 )
577 check_trailing_context( nset, numstates,
584 if ( ! snstods( nset, 0, accset, 0, 0, &end_of_buffer_state ) )
586 _( "could not create unique end-of-buffer state" ) );
593 while ( todo_head < todo_next )
598 for ( i = 1; i <= numecs; ++i )
607 fprintf( stderr, _( "state # %d:\n" ), ds );
609 sympartition( dset, dsize, symlist, duplist );
611 for ( sym = 1; sym <= numecs; ++sym )
617 if ( duplist[sym] == NIL )
619 /* Symbol has unique out-transitions. */
620 numstates = symfollowset( dset, dsize,
622 nset = epsclosure( nset, &numstates,
623 accset, &nacc, &hashval );
625 if ( snstods( nset, numstates, accset,
626 nacc, hashval, &newds ) )
628 totnst = totnst + numstates;
633 variable_trailing_context_rules &&
635 check_trailing_context(
643 fprintf( stderr, "\t%d\t%d\n",
646 targfreq[++targptr] = 1;
647 targstate[targptr] = newds;
653 /* sym's equivalence class has the same
654 * transitions as duplist(sym)'s
657 targ = state[duplist[sym]];
661 fprintf( stderr, "\t%d\t%d\n",
664 /* Update frequency count for
669 while ( targstate[++i] != targ )
681 if ( caseins && ! useecs )
685 for ( i = 'A', j = 'a'; i <= 'Z'; ++i, ++j )
687 if ( state[i] == 0 && state[j] != 0 )
688 /* We're adding a transition. */
691 else if ( state[i] != 0 && state[j] == 0 )
692 /* We're taking away a transition. */
699 numsnpairs += totaltrans;
701 if ( ds > num_start_states )
702 check_for_backing_up( ds, state );
706 nultrans[ds] = state[NUL_ec];
707 state[NUL_ec] = 0; /* remove transition */
714 /* Supply array's 0-element. */
715 if ( ds == end_of_buffer_state )
716 mk2data( -end_of_buffer_state );
718 mk2data( end_of_buffer_state );
720 for ( i = 1; i < num_full_table_rows; ++i )
721 /* Jams are marked by negative of state
724 mk2data( state[i] ? state[i] : -ds );
731 place_state( state, ds, totaltrans );
733 else if ( ds == end_of_buffer_state )
734 /* Special case this state to make sure it does what
735 * it's supposed to, i.e., jam on end-of-buffer.
737 stack1( ds, 0, 0, JAMSTATE );
739 else /* normal, compressed state */
741 /* Determine which destination state is the most
742 * common, and how many transitions to it there are.
748 for ( i = 1; i <= targptr; ++i )
749 if ( targfreq[i] > comfreq )
751 comfreq = targfreq[i];
752 comstate = targstate[i];
755 bldtbl( state, ds, totaltrans, comstate, comfreq );
762 else if ( ! fullspd )
764 cmptmps(); /* create compressed template entries */
766 /* Create tables for all the states with only one
771 mk1tbl( onestate[onesp], onesym[onesp], onenext[onesp],
779 flex_free( (void *) accset );
780 flex_free( (void *) nset );
784 /* snstods - converts a set of ndfa states into a dfa state
787 * is_new_state = snstods( int sns[numstates], int numstates,
788 * int accset[num_rules+1], int nacc,
789 * int hashval, int *newds_addr );
791 * On return, the dfa state number is in newds.
794 int snstods( sns, numstates, accset, nacc, hashval, newds_addr )
795 int sns[], numstates, accset[], nacc, hashval, *newds_addr;
801 for ( i = 1; i <= lastdfa; ++i )
802 if ( hashval == dhash[i] )
804 if ( numstates == dfasiz[i] )
810 /* We sort the states in sns so we
811 * can compare it to oldsns quickly.
812 * We use bubble because there probably
813 * aren't very many states.
815 bubble( sns, numstates );
819 for ( j = 1; j <= numstates; ++j )
820 if ( sns[j] != oldsns[j] )
837 /* Make a new dfa. */
839 if ( ++lastdfa >= current_max_dfas )
844 dss[newds] = allocate_integer_array( numstates + 1 );
846 /* If we haven't already sorted the states in sns, we do so now,
847 * so that future comparisons with it can be made quickly.
851 bubble( sns, numstates );
853 for ( i = 1; i <= numstates; ++i )
854 dss[newds][i] = sns[i];
856 dfasiz[newds] = numstates;
857 dhash[newds] = hashval;
862 dfaacc[newds].dfaacc_set = (int *) 0;
864 dfaacc[newds].dfaacc_state = 0;
871 /* We sort the accepting set in increasing order so the
872 * disambiguating rule that the first rule listed is considered
873 * match in the event of ties will work. We use a bubble
874 * sort since the list is probably quite small.
877 bubble( accset, nacc );
879 dfaacc[newds].dfaacc_set = allocate_integer_array( nacc + 1 );
881 /* Save the accepting set for later */
882 for ( i = 1; i <= nacc; ++i )
884 dfaacc[newds].dfaacc_set[i] = accset[i];
886 if ( accset[i] <= num_rules )
887 /* Who knows, perhaps a REJECT can yield
890 rule_useful[accset[i]] = true;
893 accsiz[newds] = nacc;
898 /* Find lowest numbered rule so the disambiguating rule
903 for ( i = 1; i <= nacc; ++i )
907 dfaacc[newds].dfaacc_state = j;
909 if ( j <= num_rules )
910 rule_useful[j] = true;
919 /* symfollowset - follow the symbol transitions one step
922 * numstates = symfollowset( int ds[current_max_dfa_size], int dsize,
923 * int transsym, int nset[current_max_dfa_size] );
926 int symfollowset( ds, dsize, transsym, nset )
927 int ds[], dsize, transsym, nset[];
929 int ns, tsp, sym, i, j, lenccl, ch, numstates, ccllist;
933 for ( i = 1; i <= dsize; ++i )
934 { /* for each nfa state ns in the state set of ds */
940 { /* it's a character class */
942 ccllist = cclmap[sym];
943 lenccl = ccllen[sym];
947 for ( j = 0; j < lenccl; ++j )
949 /* Loop through negated character
952 ch = ccltbl[ccllist + j];
958 /* Transsym isn't in negated
963 else if ( ch == transsym )
964 /* next 2 */ goto bottom;
967 /* Didn't find transsym in ccl. */
968 nset[++numstates] = tsp;
972 for ( j = 0; j < lenccl; ++j )
974 ch = ccltbl[ccllist + j];
981 else if ( ch == transsym )
983 nset[++numstates] = tsp;
989 else if ( sym >= 'A' && sym <= 'Z' && caseins )
991 _( "consistency check failed in symfollowset" ) );
993 else if ( sym == SYM_EPSILON )
997 else if ( ABS( ecgroup[sym] ) == transsym )
998 nset[++numstates] = tsp;
1007 /* sympartition - partition characters with same out-transitions
1010 * sympartition( int ds[current_max_dfa_size], int numstates,
1011 * int symlist[numecs], int duplist[numecs] );
1014 void sympartition( ds, numstates, symlist, duplist )
1015 int ds[], numstates;
1016 int symlist[], duplist[];
1018 int tch, i, j, k, ns, dupfwd[CSIZE + 1], lenccl, cclp, ich;
1020 /* Partitioning is done by creating equivalence classes for those
1021 * characters which have out-transitions from the given state. Thus
1022 * we are really creating equivalence classes of equivalence classes.
1025 for ( i = 1; i <= numecs; ++i )
1026 { /* initialize equivalence class list */
1032 dupfwd[numecs] = NIL;
1034 for ( i = 1; i <= numstates; ++i )
1037 tch = transchar[ns];
1039 if ( tch != SYM_EPSILON )
1041 if ( tch < -lastccl || tch >= csize )
1044 _( "bad transition character detected in sympartition()" ) );
1048 { /* character transition */
1049 int ec = ecgroup[tch];
1051 mkechar( ec, dupfwd, duplist );
1056 { /* character class */
1059 lenccl = ccllen[tch];
1061 mkeccl( ccltbl + cclp, lenccl, dupfwd,
1062 duplist, numecs, NUL_ec );
1068 for ( k = 0; k < lenccl; ++k )
1070 ich = ccltbl[cclp + k];
1075 for ( ++j; j < ich; ++j )
1079 for ( ++j; j <= numecs; ++j )
1084 for ( k = 0; k < lenccl; ++k )
1086 ich = ccltbl[cclp + k];