1 /* dfa - DFA 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 /* Redistribution and use in source and binary forms, with or without */
14 /* modification, are permitted provided that the following conditions */
17 /* 1. Redistributions of source code must retain the above copyright */
18 /* notice, this list of conditions and the following disclaimer. */
19 /* 2. Redistributions in binary form must reproduce the above copyright */
20 /* notice, this list of conditions and the following disclaimer in the */
21 /* documentation and/or other materials provided with the distribution. */
23 /* Neither the name of the University nor the names of its contributors */
24 /* may be used to endorse or promote products derived from this software */
25 /* without specific prior written permission. */
27 /* THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR */
28 /* IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED */
29 /* WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR */
35 /* declare functions that have forward references */
37 void dump_associated_rules(FILE *, int);
38 void dump_transitions(FILE *, int[]);
39 void sympartition(int[], int, int[], int[]);
40 int symfollowset(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 (int ds, int state[])
54 if ((reject && !dfaacc[ds].dfaacc_set) || (!reject && !dfaacc[ds].dfaacc_state)) { /* state is non-accepting */
57 if (backing_up_report) {
58 fprintf (backing_up_file,
59 _("State #%d is non-accepting -\n"), ds);
61 /* identify the state */
62 dump_associated_rules (backing_up_file, ds);
64 /* Now identify it further using the out- and
67 dump_transitions (backing_up_file, state);
69 putc ('\n', backing_up_file);
75 /* check_trailing_context - check to see if NFA state set constitutes
76 * "dangerous" trailing context
79 * void check_trailing_context( int nfa_states[num_states+1], int num_states,
80 * int accset[nacc+1], int nacc );
83 * Trailing context is "dangerous" if both the head and the trailing
84 * part are of variable size \and/ there's a DFA state which contains
85 * both an accepting state for the head part of the rule and NFA states
86 * which occur after the beginning of the trailing context.
88 * When such a rule is matched, it's impossible to tell if having been
89 * in the DFA state indicates the beginning of the trailing context or
90 * further-along scanning of the pattern. In these cases, a warning
93 * nfa_states[1 .. num_states] is the list of NFA states in the DFA.
94 * accset[1 .. nacc] is the list of accepting numbers for the DFA state.
97 void check_trailing_context (int *nfa_states, int num_states, int *accset, int nacc)
101 for (i = 1; i <= num_states; ++i) {
102 int ns = nfa_states[i];
103 int type = state_type[ns];
104 int ar = assoc_rule[ns];
106 if (type == STATE_NORMAL || rule_type[ar] != RULE_VARIABLE) { /* do nothing */
109 else if (type == STATE_TRAILING_CONTEXT) {
110 /* Potential trouble. Scan set of accepting numbers
111 * for the one marking the end of the "head". We
112 * assume that this looping will be fairly cheap
113 * since it's rare that an accepting number set
116 for (j = 1; j <= nacc; ++j)
117 if (accset[j] & YY_TRAILING_HEAD_MASK) {
119 ("dangerous trailing context"),
128 /* dump_associated_rules - list the rules associated with a DFA state
130 * Goes through the set of NFA states associated with the DFA and
131 * extracts the first MAX_ASSOC_RULES unique rules, sorts them,
132 * and writes a report to the given file.
135 void dump_associated_rules (FILE *file, int ds)
138 int num_associated_rules = 0;
139 int rule_set[MAX_ASSOC_RULES + 1];
141 int size = dfasiz[ds];
143 for (i = 1; i <= size; ++i) {
144 int rule_num = rule_linenum[assoc_rule[dset[i]]];
146 for (j = 1; j <= num_associated_rules; ++j)
147 if (rule_num == rule_set[j])
150 if (j > num_associated_rules) { /* new rule */
151 if (num_associated_rules < MAX_ASSOC_RULES)
152 rule_set[++num_associated_rules] =
157 qsort (&rule_set [1], (size_t) num_associated_rules, sizeof (rule_set [1]), intcmp);
159 fprintf (file, _(" associated rule line numbers:"));
161 for (i = 1; i <= num_associated_rules; ++i) {
165 fprintf (file, "\t%d", rule_set[i]);
172 /* dump_transitions - list the transitions associated with a DFA state
175 * dump_transitions( FILE *file, int state[numecs] );
177 * Goes through the set of out-transitions and lists them in human-readable
178 * form (i.e., not as equivalence classes); also lists jam transitions
179 * (i.e., all those which are not out-transitions, plus EOF). The dump
180 * is done to the given file.
183 void dump_transitions (FILE *file, int state[])
186 int out_char_set[CSIZE];
188 for (i = 0; i < csize; ++i) {
189 ec = ABS (ecgroup[i]);
190 out_char_set[i] = state[ec];
193 fprintf (file, _(" out-transitions: "));
195 list_character_set (file, out_char_set);
197 /* now invert the members of the set to get the jam transitions */
198 for (i = 0; i < csize; ++i)
199 out_char_set[i] = !out_char_set[i];
201 fprintf (file, _("\n jam-transitions: EOF "));
203 list_character_set (file, out_char_set);
209 /* epsclosure - construct the epsilon closure of a set of ndfa states
212 * int *epsclosure( int t[num_states], int *numstates_addr,
213 * int accset[num_rules+1], int *nacc_addr,
214 * int *hashval_addr );
217 * The epsilon closure is the set of all states reachable by an arbitrary
218 * number of epsilon transitions, which themselves do not have epsilon
219 * transitions going out, unioned with the set of states which have non-null
220 * accepting numbers. t is an array of size numstates of nfa state numbers.
221 * Upon return, t holds the epsilon closure and *numstates_addr is updated.
222 * accset holds a list of the accepting numbers, and the size of accset is
223 * given by *nacc_addr. t may be subjected to reallocation if it is not
224 * large enough to hold the epsilon closure.
226 * hashval is the hash value for the dfa corresponding to the state set.
229 int *epsclosure (int *t, int *ns_addr, int accset[], int *nacc_addr, int *hv_addr)
232 int numstates = *ns_addr, nacc, hashval, transsym, nfaccnum;
234 static int did_stk_init = false, *stk;
236 #define MARK_STATE(state) \
237 do{ trans1[state] = trans1[state] - MARKER_DIFFERENCE;} while(0)
239 #define IS_MARKED(state) (trans1[state] < 0)
241 #define UNMARK_STATE(state) \
242 do{ trans1[state] = trans1[state] + MARKER_DIFFERENCE;} while(0)
244 #define CHECK_ACCEPT(state) \
246 nfaccnum = accptnum[state]; \
247 if ( nfaccnum != NIL ) \
248 accset[++nacc] = nfaccnum; \
251 #define DO_REALLOCATION() \
253 current_max_dfa_size += MAX_DFA_SIZE_INCREMENT; \
255 t = reallocate_integer_array( t, current_max_dfa_size ); \
256 stk = reallocate_integer_array( stk, current_max_dfa_size ); \
259 #define PUT_ON_STACK(state) \
261 if ( ++stkend >= current_max_dfa_size ) \
263 stk[stkend] = state; \
267 #define ADD_STATE(state) \
269 if ( ++numstates >= current_max_dfa_size ) \
271 t[numstates] = state; \
275 #define STACK_STATE(state) \
277 PUT_ON_STACK(state); \
278 CHECK_ACCEPT(state); \
279 if ( nfaccnum != NIL || transchar[state] != SYM_EPSILON ) \
285 stk = allocate_integer_array (current_max_dfa_size);
289 nacc = stkend = hashval = 0;
291 for (nstate = 1; nstate <= numstates; ++nstate) {
294 /* The state could be marked if we've already pushed it onto
297 if (!IS_MARKED (ns)) {
304 for (stkpos = 1; stkpos <= stkend; ++stkpos) {
306 transsym = transchar[ns];
308 if (transsym == SYM_EPSILON) {
309 tsp = trans1[ns] + MARKER_DIFFERENCE;
311 if (tsp != NO_TRANSITION) {
312 if (!IS_MARKED (tsp))
317 if (tsp != NO_TRANSITION
324 /* Clear out "visit" markers. */
326 for (stkpos = 1; stkpos <= stkend; ++stkpos) {
327 if (IS_MARKED (stk[stkpos]))
328 UNMARK_STATE (stk[stkpos]);
331 ("consistency check failed in epsclosure()"));
334 *ns_addr = numstates;
342 /* increase_max_dfas - increase the maximum number of DFAs */
344 void increase_max_dfas (void)
346 current_max_dfas += MAX_DFAS_INCREMENT;
350 base = reallocate_integer_array (base, current_max_dfas);
351 def = reallocate_integer_array (def, current_max_dfas);
352 dfasiz = reallocate_integer_array (dfasiz, current_max_dfas);
353 accsiz = reallocate_integer_array (accsiz, current_max_dfas);
354 dhash = reallocate_integer_array (dhash, current_max_dfas);
355 dss = reallocate_int_ptr_array (dss, current_max_dfas);
356 dfaacc = reallocate_dfaacc_union (dfaacc, current_max_dfas);
360 reallocate_integer_array (nultrans,
365 /* ntod - convert an ndfa to a dfa
367 * Creates the dfa corresponding to the ndfa we've constructed. The
368 * dfa starts out in state #1.
373 int *accset, ds, nacc, newds;
374 int sym, hashval, numstates, dsize;
375 int num_full_table_rows=0; /* used only for -f */
377 int targptr, totaltrans, i, comstate, comfreq, targ;
378 int symlist[CSIZE + 1];
379 int num_start_states;
380 int todo_head, todo_next;
382 struct yytbl_data *yynxt_tbl = 0;
383 flex_int32_t *yynxt_data = 0, yynxt_curr = 0;
385 /* Note that the following are indexed by *equivalence classes*
386 * and not by characters. Since equivalence classes are indexed
387 * beginning with 1, even if the scanner accepts NUL's, this
388 * means that (since every character is potentially in its own
389 * equivalence class) these arrays must have room for indices
390 * from 1 to CSIZE, so their size must be CSIZE + 1.
392 int duplist[CSIZE + 1], state[CSIZE + 1];
393 int targfreq[CSIZE + 1] = {0}, targstate[CSIZE + 1];
395 /* accset needs to be large enough to hold all of the rules present
396 * in the input, *plus* their YY_TRAILING_HEAD_MASK variants.
398 accset = allocate_integer_array ((num_rules + 1) * 2);
399 nset = allocate_integer_array (current_max_dfa_size);
401 /* The "todo" queue is represented by the head, which is the DFA
402 * state currently being processed, and the "next", which is the
403 * next DFA state number available (not in use). We depend on the
404 * fact that snstods() returns DFA's \in increasing order/, and thus
405 * need only know the bounds of the dfas to be processed.
407 todo_head = todo_next = 0;
409 for (i = 0; i <= csize; ++i) {
414 for (i = 0; i <= num_rules; ++i)
419 fputs (_("\n\nDFA Dump:\n\n"), stderr);
424 /* Check to see whether we should build a separate table for
425 * transitions on NUL characters. We don't do this for full-speed
426 * (-F) scanners, since for them we don't have a simple state
427 * number lying around with which to index the table. We also
428 * don't bother doing it for scanners unless (1) NUL is in its own
429 * equivalence class (indicated by a positive value of
430 * ecgroup[NUL]), (2) NUL's equivalence class is the last
431 * equivalence class, and (3) the number of equivalence classes is
432 * the same as the number of characters. This latter case comes
433 * about when useecs is false or when it's true but every character
434 * still manages to land in its own class (unlikely, but it's
435 * cheap to check for). If all these things are true then the
436 * character code needed to represent NUL's equivalence class for
437 * indexing the tables is going to take one more bit than the
438 * number of characters, and therefore we won't be assured of
439 * being able to fit it into a YY_CHAR variable. This rules out
440 * storing the transitions in a compressed table, since the code
441 * for interpreting them uses a YY_CHAR variable (perhaps it
442 * should just use an integer, though; this is worth pondering ...
445 * Finally, for full tables, we want the number of entries in the
446 * table to be a power of two so the array references go fast (it
447 * will just take a shift to compute the major index). If
448 * encoding NUL's transitions in the table will spoil this, we
449 * give it its own table (note that this will be the case if we're
450 * not using equivalence classes).
453 /* Note that the test for ecgroup[0] == numecs below accomplishes
454 * both (1) and (2) above
456 if (!fullspd && ecgroup[0] == numecs) {
457 /* NUL is alone in its equivalence class, which is the
460 int use_NUL_table = (numecs == csize);
462 if (fulltbl && !use_NUL_table) {
463 /* We still may want to use the table if numecs
466 if (numecs <= csize && is_power_of_2(numecs)) {
467 use_NUL_table = true;
473 allocate_integer_array (current_max_dfas);
475 /* From now on, nultrans != nil indicates that we're
476 * saving null transitions for later, separate encoding.
482 for (i = 0; i <= numecs; ++i)
485 place_state (state, 0, 0);
486 dfaacc[0].dfaacc_state = 0;
491 /* We won't be including NUL's transitions in the
492 * table, so build it for entries from 0 .. numecs - 1.
494 num_full_table_rows = numecs;
497 /* Take into account the fact that we'll be including
498 * the NUL entries in the transition table. Build it
501 num_full_table_rows = numecs + 1;
503 /* Begin generating yy_nxt[][]
504 * This spans the entire LONG function.
505 * This table is tricky because we don't know how big it will be.
506 * So we'll have to realloc() on the way...
507 * we'll wait until we can calculate yynxt_tbl->td_hilen.
509 yynxt_tbl = calloc(1, sizeof (struct yytbl_data));
511 yytbl_data_init (yynxt_tbl, YYTD_ID_NXT);
512 yynxt_tbl->td_hilen = 1;
513 yynxt_tbl->td_lolen = (flex_uint32_t) num_full_table_rows;
514 yynxt_tbl->td_data = yynxt_data =
515 calloc(yynxt_tbl->td_lolen *
517 sizeof (flex_int32_t));
520 buf_prints (&yydmap_buf,
521 "\t{YYTD_ID_NXT, (void**)&yy_nxt, sizeof(%s)},\n",
522 long_align ? "flex_int32_t" : "flex_int16_t");
524 /* Unless -Ca, declare it "short" because it's a real
525 * long-shot that that won't be large enough.
529 ("static const %s yy_nxt[][%d] =\n {\n",
530 long_align ? "flex_int32_t" : "flex_int16_t",
531 num_full_table_rows);
533 out_dec ("#undef YY_NXT_LOLEN\n#define YY_NXT_LOLEN (%d)\n", num_full_table_rows);
534 out_str ("static const %s *yy_nxt =0;\n",
535 long_align ? "flex_int32_t" : "flex_int16_t");
542 /* Generate 0 entries for state #0. */
543 for (i = 0; i < num_full_table_rows; ++i) {
545 yynxt_data[yynxt_curr++] = 0;
553 /* Create the first states. */
555 num_start_states = lastsc * 2;
557 for (i = 1; i <= num_start_states; ++i) {
560 /* For each start condition, make one state for the case when
561 * we're at the beginning of the line (the '^' operator) and
562 * one for the case when we're not.
565 nset[numstates] = scset[(i / 2) + 1];
568 mkbranch (scbol[i / 2], scset[i / 2]);
570 nset = epsclosure (nset, &numstates, accset, &nacc,
573 if (snstods (nset, numstates, accset, nacc, hashval, &ds)) {
578 if (variable_trailing_context_rules && nacc > 0)
579 check_trailing_context (nset, numstates,
585 if (!snstods (nset, 0, accset, 0, 0, &end_of_buffer_state))
587 ("could not create unique end-of-buffer state"));
595 while (todo_head < todo_next) {
599 for (i = 1; i <= numecs; ++i)
608 fprintf (stderr, _("state # %d:\n"), ds);
610 sympartition (dset, dsize, symlist, duplist);
612 for (sym = 1; sym <= numecs; ++sym) {
616 if (duplist[sym] == NIL) {
617 /* Symbol has unique out-transitions. */
619 symfollowset (dset, dsize,
621 nset = epsclosure (nset,
627 (nset, numstates, accset, nacc,
634 if (variable_trailing_context_rules && nacc > 0)
635 check_trailing_context
649 targfreq[++targptr] = 1;
650 targstate[targptr] = newds;
655 /* sym's equivalence class has the same
656 * transitions as duplist(sym)'s
659 targ = state[duplist[sym]];
667 /* Update frequency count for
672 while (targstate[++i] != targ) ;
684 numsnpairs += totaltrans;
686 if (ds > num_start_states)
687 check_for_backing_up (ds, state);
690 nultrans[ds] = state[NUL_ec];
691 state[NUL_ec] = 0; /* remove transition */
696 /* Each time we hit here, it's another td_hilen, so we realloc. */
697 yynxt_tbl->td_hilen++;
698 yynxt_tbl->td_data = yynxt_data =
700 yynxt_tbl->td_hilen *
701 yynxt_tbl->td_lolen *
702 sizeof (flex_int32_t));
708 /* Supply array's 0-element. */
709 if (ds == end_of_buffer_state) {
710 mk2data (-end_of_buffer_state);
711 yynxt_data[yynxt_curr++] =
712 -end_of_buffer_state;
715 mk2data (end_of_buffer_state);
716 yynxt_data[yynxt_curr++] =
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);
725 yynxt_data[yynxt_curr++] =
726 state[i] ? state[i] : -ds;
735 place_state (state, ds, totaltrans);
737 else if (ds == end_of_buffer_state)
738 /* Special case this state to make sure it does what
739 * it's supposed to, i.e., jam on end-of-buffer.
741 stack1 (ds, 0, 0, JAMSTATE);
743 else { /* normal, compressed state */
745 /* Determine which destination state is the most
746 * common, and how many transitions to it there are.
752 for (i = 1; i <= targptr; ++i)
753 if (targfreq[i] > comfreq) {
754 comfreq = targfreq[i];
755 comstate = targstate[i];
758 bldtbl (state, ds, totaltrans, comstate, comfreq);
765 yytbl_data_compress (yynxt_tbl);
766 if (yytbl_data_fwrite (&tableswr, yynxt_tbl) < 0)
768 ("Could not write yynxt_tbl[][]"));
771 yytbl_data_destroy (yynxt_tbl);
777 cmptmps (); /* create compressed template entries */
779 /* Create tables for all the states with only one
783 mk1tbl (onestate[onesp], onesym[onesp],
784 onenext[onesp], onedef[onesp]);
796 /* snstods - converts a set of ndfa states into a dfa state
799 * is_new_state = snstods( int sns[numstates], int numstates,
800 * int accset[num_rules+1], int nacc,
801 * int hashval, int *newds_addr );
803 * On return, the dfa state number is in newds.
806 int snstods (int sns[], int numstates, int accset[], int nacc, int hashval, int *newds_addr)
812 for (i = 1; i <= lastdfa; ++i)
813 if (hashval == dhash[i]) {
814 if (numstates == dfasiz[i]) {
818 /* We sort the states in sns so we
819 * can compare it to oldsns quickly.
821 qsort (&sns [1], (size_t) numstates, sizeof (sns [1]), intcmp);
825 for (j = 1; j <= numstates; ++j)
826 if (sns[j] != oldsns[j])
842 /* Make a new dfa. */
844 if (++lastdfa >= current_max_dfas)
845 increase_max_dfas ();
849 dss[newds] = allocate_integer_array (numstates + 1);
851 /* If we haven't already sorted the states in sns, we do so now,
852 * so that future comparisons with it can be made quickly.
856 qsort (&sns [1], (size_t) numstates, sizeof (sns [1]), intcmp);
858 for (i = 1; i <= numstates; ++i)
859 dss[newds][i] = sns[i];
861 dfasiz[newds] = numstates;
862 dhash[newds] = hashval;
866 dfaacc[newds].dfaacc_set = NULL;
868 dfaacc[newds].dfaacc_state = 0;
874 /* We sort the accepting set in increasing order so the
875 * disambiguating rule that the first rule listed is considered
876 * match in the event of ties will work.
879 qsort (&accset [1], (size_t) nacc, sizeof (accset [1]), intcmp);
881 dfaacc[newds].dfaacc_set =
882 allocate_integer_array (nacc + 1);
884 /* Save the accepting set for later */
885 for (i = 1; i <= nacc; ++i) {
886 dfaacc[newds].dfaacc_set[i] = accset[i];
888 if (accset[i] <= num_rules)
889 /* Who knows, perhaps a REJECT can yield
892 rule_useful[accset[i]] = true;
895 accsiz[newds] = nacc;
899 /* Find lowest numbered rule so the disambiguating rule
904 for (i = 1; i <= nacc; ++i)
908 dfaacc[newds].dfaacc_state = j;
911 rule_useful[j] = true;
920 /* symfollowset - follow the symbol transitions one step
923 * numstates = symfollowset( int ds[current_max_dfa_size], int dsize,
924 * int transsym, int nset[current_max_dfa_size] );
927 int symfollowset (int ds[], int dsize, int transsym, int nset[])
929 int ns, tsp, sym, i, j, lenccl, ch, numstates, ccllist;
933 for (i = 1; i <= dsize; ++i) { /* for each nfa state ns in the state set of ds */
938 if (sym < 0) { /* it's a character class */
940 ccllist = cclmap[sym];
941 lenccl = ccllen[sym];
944 for (j = 0; j < lenccl; ++j) {
945 /* Loop through negated character
948 ch = ccltbl[ccllist + j];
954 /* Transsym isn't in negated
959 else if (ch == transsym)
964 /* Didn't find transsym in ccl. */
965 nset[++numstates] = tsp;
969 for (j = 0; j < lenccl; ++j) {
970 ch = ccltbl[ccllist + j];
977 else if (ch == transsym) {
978 nset[++numstates] = tsp;
984 else if (sym == SYM_EPSILON) { /* do nothing */
987 else if (ABS (ecgroup[sym]) == transsym)
988 nset[++numstates] = tsp;
997 /* sympartition - partition characters with same out-transitions
1000 * sympartition( int ds[current_max_dfa_size], int numstates,
1001 * int symlist[numecs], int duplist[numecs] );
1004 void sympartition (int ds[], int numstates, int symlist[], int duplist[])
1006 int tch, i, j, k, ns, dupfwd[CSIZE + 1], lenccl, cclp, ich;
1008 /* Partitioning is done by creating equivalence classes for those
1009 * characters which have out-transitions from the given state. Thus
1010 * we are really creating equivalence classes of equivalence classes.
1013 for (i = 1; i <= numecs; ++i) { /* initialize equivalence class list */
1019 dupfwd[numecs] = NIL;
1021 for (i = 1; i <= numstates; ++i) {
1023 tch = transchar[ns];
1025 if (tch != SYM_EPSILON) {
1026 if (tch < -lastccl || tch >= csize) {
1028 ("bad transition character detected in sympartition()"));
1031 if (tch >= 0) { /* character transition */
1032 int ec = ecgroup[tch];
1034 mkechar (ec, dupfwd, duplist);
1038 else { /* character class */
1041 lenccl = ccllen[tch];
1043 mkeccl (ccltbl + cclp, lenccl, dupfwd,
1044 duplist, numecs, NUL_ec);
1049 for (k = 0; k < lenccl; ++k) {
1050 ich = ccltbl[cclp + k];
1055 for (++j; j < ich; ++j)
1059 for (++j; j <= numecs; ++j)
1064 for (k = 0; k < lenccl; ++k) {
1065 ich = ccltbl[cclp + k];