home *** CD-ROM | disk | FTP | other *** search
/ InfoMagic Source Code 1993 July / THE_SOURCE_CODE_CD_ROM.iso / gnu / cperf-2.1 / src / keylist.c < prev    next >
Encoding:
C/C++ Source or Header  |  1989-11-11  |  33.7 KB  |  1,034 lines

  1. /* Routines for building, ordering, and printing the keyword list.
  2.    Copyright (C) 1989 Free Software Foundation, Inc.
  3.    written by Douglas C. Schmidt (schmidt@ics.uci.edu)
  4.  
  5. This file is part of GNU GPERF.
  6.  
  7. GNU GPERF is free software; you can redistribute it and/or modify
  8. it under the terms of the GNU General Public License as published by
  9. the Free Software Foundation; either version 1, or (at your option)
  10. any later version.
  11.  
  12. GNU GPERF is distributed in the hope that it will be useful,
  13. but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  15. GNU General Public License for more details.
  16.  
  17. You should have received a copy of the GNU General Public License
  18. along with GNU GPERF; see the file COPYING.  If not, write to
  19. the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.  */
  20.  
  21. #include <assert.h>
  22. #include <stdio.h>
  23. #include "options.h"
  24. #include "readline.h"
  25. #include "keylist.h"
  26. #include "hashtable.h"
  27. #include "stderr.h"
  28. #ifdef sparc
  29. #include <alloca.h>
  30. #endif
  31.  
  32. /* Current release version. */
  33. extern char *version_string;
  34.  
  35. /* See comments in perfect.cc. */
  36. extern int occurrences[ALPHABET_SIZE]; 
  37.  
  38. /* Ditto. */
  39. extern int asso_values[ALPHABET_SIZE];
  40.  
  41. /* Used in function reorder, below. */
  42. static bool determined[ALPHABET_SIZE]; 
  43.  
  44. /* Default type for generated code. */
  45. static char *default_array_type = "char *";
  46.  
  47. /* Generated function ``in_word_set'' default return type. */
  48. static char *default_return_type = "char *";
  49.  
  50. /* Largest positive integer value. */
  51. #define MAX_INT ((~(unsigned)0)>>1)
  52.  
  53. /* Most negative integer value. */
  54. #define NEG_MAX_INT ((~(unsigned)0)^((~(unsigned)0)>>1))
  55.  
  56. /* Maximum value an unsigned char can take. */
  57. #define MAX_UNSIGNED_CHAR 256
  58.  
  59. /* Maximum value an unsigned short can take. */
  60. #define MAX_UNSIGNED_SHORT 65536
  61.  
  62. /* Make the hash table 5 times larger than the number of keyword entries. */
  63. #define TABLE_MULTIPLE 5
  64.  
  65. /* Efficiently returns the least power of two greater than or equal to X! */
  66. #define POW(X) ((!X)?1:(X-=1,X|=X>>1,X|=X>>2,X|=X>>4,X|=X>>8,X|=X>>16,(++X)))
  67.  
  68. /* How wide the printed field width must be to contain the maximum hash value. */
  69. static int field_width = 2;
  70.  
  71. /* Globally visible KEY_LIST object. */
  72.  
  73. KEY_LIST key_list;
  74.  
  75. /* Gathers the input stream into a buffer until one of two things occur:
  76.  
  77.    1. We read a '%' followed by a '%'
  78.    2. We read a '%' followed by a '}'
  79.  
  80.    The first symbolizes the beginning of the keyword list proper,
  81.    The second symbolizes the end of the C source code to be generated
  82.    verbatim in the output file.
  83.  
  84.    I assume that the keys are separated from the optional preceding struct
  85.    declaration by a consecutive % followed by either % or } starting in 
  86.    the first column. The code below uses an expandible buffer to scan off 
  87.    and return a pointer to all the code (if any) appearing before the delimiter. */
  88.  
  89. static char *
  90. get_special_input (delimiter)
  91.      char delimiter;
  92.   char *xmalloc ();
  93.   int size  = 80;
  94.   char *buf = xmalloc (size);
  95.   int c, i;
  96.  
  97.   for (i = 0; (c = getchar ()) != EOF; i++)
  98.     {
  99.       if (c == '%')
  100.         {
  101.           if ((c = getchar ()) == delimiter)
  102.             {
  103.         
  104.               while ((c = getchar ()) != '\n')
  105.                 ; /* Discard newline. */
  106.               
  107.               if (i == 0)
  108.                 return "";
  109.               else
  110.                 {
  111.                   buf[delimiter == '%' && buf[i - 2] == ';' ? i - 2 : i - 1] = '\0';
  112.                   return buf;
  113.                 }
  114.             }
  115.           else
  116.             ungetc (c, stdin);
  117.         }
  118.       else if (i >= size) /* Yikes, time to grow the buffer! */
  119.         { 
  120.           char *temp = xmalloc (size *= 2);
  121.           int j;
  122.           
  123.           for (j = 0; j < i; j++)
  124.             temp[j] = buf[j];
  125.           
  126.           free (buf);
  127.           buf = temp;
  128.         }
  129.       buf[i] = c;
  130.     }
  131.   
  132.   return NULL;        /* Problem here. */
  133. }
  134.  
  135. /* Stores any C text that must be included verbatim into the 
  136.    generated code output. */
  137.  
  138. static char *
  139. save_include_src ()
  140. {
  141.   int c;
  142.   
  143.   if ((c = getchar ()) != '%')
  144.     {
  145.       ungetc (c, stdin);
  146.       return "";
  147.     }
  148.   else if ((c = getchar ()) != '{')
  149.     report_error ("internal error, %c != '{' on line %d in file %s%a", c, __LINE__, __FILE__);
  150.     /*NOT REACHED*/
  151.   else 
  152.     return get_special_input ('}');
  153. }
  154.  
  155. /* strcspn - find length of initial segment of s consisting entirely
  156.    of characters not from reject (borrowed from Henry Spencer's
  157.    ANSI string package). */
  158.  
  159. static int
  160. strcspn (s, reject)
  161.      char *s;
  162.      char *reject;
  163. {
  164.   char *scan;
  165.   char *rej_scan;
  166.   int   count = 0;
  167.  
  168.   for (scan = s; *scan; scan++) 
  169.     {
  170.  
  171.       for (rej_scan = reject; *rej_scan;) 
  172.         if (*scan == *rej_scan++)
  173.           return count;
  174.  
  175.       count++;
  176.     }
  177.  
  178.   return count;
  179. }
  180.  
  181. /* Determines from the input file whether the user wants to build a table
  182.    from a user-defined struct, or whether the user is content to simply
  183.    use the default array of keys. */
  184.  
  185. static char *
  186. get_array_type ()
  187. {
  188.   return get_special_input ('%');
  189. }  
  190.   
  191. /* Sets up the Return_Type, the Struct_Tag type and the Array_Type
  192.    based upon various user Options. */
  193.  
  194. static void 
  195. set_output_types ()
  196. {
  197.   char *xmalloc ();
  198.   
  199.   if (OPTION_ENABLED (option, TYPE) && !(key_list.array_type = get_array_type ()))
  200.     return;                     /* Something's wrong, bug we'll catch it later on.... */
  201.   else if (OPTION_ENABLED (option, TYPE))        /* Yow, we've got a user-defined type... */
  202.     {    
  203.       int struct_tag_length = strcspn (key_list.array_type, "{\n\0");
  204.       
  205.       if (OPTION_ENABLED (option, POINTER))      /* And it must return a pointer... */
  206.         {    
  207.           key_list.return_type = xmalloc (struct_tag_length + 2);
  208.           strncpy (key_list.return_type, key_list.array_type, struct_tag_length);
  209.           key_list.return_type[struct_tag_length] = '\0';
  210.           strcat (key_list.return_type, "*");
  211.         }
  212.       
  213.       key_list.struct_tag = (char *) xmalloc (struct_tag_length + 1);
  214.       strncpy (key_list.struct_tag, key_list.array_type, struct_tag_length);
  215.       key_list.struct_tag[struct_tag_length] = '\0';
  216.     }  
  217.   else if (OPTION_ENABLED (option, POINTER))     /* Return a char *. */
  218.     key_list.return_type = default_array_type;
  219. }
  220.  
  221. /* Reads in all keys from standard input and creates a linked list pointed
  222.    to by Head.  This list is then quickly checked for ``links,'' i.e.,
  223.    unhashable elements possessing identical key sets and lengths. */
  224.  
  225. void 
  226. read_keys ()
  227. {
  228.   char     *ptr;
  229.   
  230.   key_list.include_src = save_include_src ();
  231.   set_output_types ();
  232.  
  233.   /* Oops, problem with the input file. */  
  234.   if (! (ptr = read_line ())) 
  235.     report_error ("No words in input file, did you forget\
  236.  to prepend %s or use -t accidentally?\n%a", "%%");
  237.  
  238.   /* Read in all the keywords from the input file. */
  239.   else 
  240.     {                      
  241.       LIST_NODE *temp, *trail;
  242.       char *delimiter = GET_DELIMITER (option); 
  243.  
  244.       for (temp = key_list.head = make_list_node (ptr, strcspn (ptr, delimiter));
  245.            (ptr = read_line ()) && strcmp (ptr, "%%");
  246.            key_list.total_keys++, temp = temp->next)
  247.         temp->next = make_list_node (ptr, strcspn (ptr, delimiter));
  248.       
  249.       /* See if any additional C code is included at end of this file. */
  250.       if (ptr)
  251.         key_list.additional_code = TRUE;
  252.       {
  253.         /* If this becomes TRUE we've got a link. */
  254.         bool       link = FALSE;  
  255.  
  256.         /* Make large hash table for efficiency. */
  257.         int table_size = (key_list.list_len = key_list.total_keys) * TABLE_MULTIPLE;
  258.         
  259.         /* By allocating the memory here we save on dynamic allocation overhead. 
  260.            Table must be a power of 2 for the hash function scheme to work. */
  261.         LIST_NODE **table = (LIST_NODE **) alloca (POW (table_size) * sizeof (LIST_NODE *));
  262.  
  263.         hash_table_init (table, table_size);
  264.  
  265.         /* Test whether there are any links and also set the maximum length of
  266.           an identifier in the keyword list. */
  267.       
  268.         for (temp = key_list.head, trail = NULL; temp; temp = temp->next)
  269.           {
  270.             LIST_NODE *ptr = retrieve (temp, OPTION_ENABLED (option, NOLENGTH));
  271.           
  272.             /* Check for links.  We deal with these by building an equivalence class
  273.               of all duplicate values (i.e., links) so that only 1 keyword is
  274.                 representative of the entire collection.  This *greatly* simplifies
  275.                   processing during later stages of the program. */
  276.  
  277.             if (ptr)              
  278.               {                   
  279.                 key_list.list_len--;
  280.                 trail->next = temp->next;
  281.                 temp->link  = ptr->link;
  282.                 ptr->link   = temp;
  283.                 link        = TRUE;
  284.  
  285.                 /* Complain if user hasn't enabled the duplicate option. */
  286.                 if (!OPTION_ENABLED (option, DUP))
  287.                   fprintf (stderr, "Key link: \"%s\" = \"%s\", with key set \"%s\".\n", 
  288.                   temp->key, ptr->key, temp->char_set);
  289.                 else if (OPTION_ENABLED (option, DEBUG))
  290.                   fprintf (stderr, "Key link: \"%s\" = \"%s\", with key set \"%s\".\n", 
  291.                   temp->key, ptr->key, temp->char_set);
  292.               }
  293.             else
  294.               trail = temp;
  295.             
  296.             /* Update minimum and maximum keyword length, if needed. */
  297.             if (temp->length > key_list.max_key_len) 
  298.               key_list.max_key_len = temp->length;
  299.             if (temp->length < key_list.min_key_len) 
  300.               key_list.min_key_len = temp->length;
  301.           }
  302.  
  303.         /* Free up the dynamic memory used in the hash table. */
  304.         hash_table_destroy ();
  305.  
  306.         /* Exit program if links exists and option[DUP] not set, since we can't continue safely. */
  307.         if (link) 
  308.           report_error (OPTION_ENABLED (option, DUP)
  309.                         ? "Some input keys have identical hash values, examine output carefully...\n"
  310.                         : "Some input keys have identical hash values,\ntry different key positions or use option -D.\n%a");
  311.       }
  312.       if (OPTION_ENABLED (option, ALLCHARS))
  313.         SET_CHARSET_SIZE (option, key_list.max_key_len);
  314.     }
  315. }
  316.  
  317. /* Recursively merges two sorted lists together to form one sorted list. The
  318.    ordering criteria is by frequency of occurrence of elements in the key set
  319.    or by the hash value.  This is a kludge, but permits nice sharing of
  320.    almost identical code without incurring the overhead of a function
  321.    call comparison. */
  322.   
  323. static LIST_NODE *
  324. merge (list1, list2)
  325.      LIST_NODE *list1;
  326.      LIST_NODE *list2;
  327. {
  328.   if (!list1)
  329.     return list2;
  330.   else if (!list2)
  331.     return list1;
  332.   else if (key_list.occurrence_sort && list1->occurrence < list2->occurrence
  333.            || key_list.hash_sort && list1->hash_value > list2->hash_value)
  334.     {
  335.       list2->next = merge (list2->next, list1);
  336.       return list2;
  337.     }
  338.   else
  339.     {
  340.       list1->next = merge (list1->next, list2);
  341.       return list1;
  342.     }
  343. }
  344.  
  345. /* Applies the merge sort algorithm to recursively sort the key list by
  346.    frequency of occurrence of elements in the key set. */
  347.   
  348. static LIST_NODE *
  349. merge_sort (head)
  350.      LIST_NODE *head;
  351.   if (!head || !head->next)
  352.     return head;
  353.   else
  354.     {
  355.       LIST_NODE *middle = head;
  356.       LIST_NODE *temp   = head->next->next;
  357.     
  358.       while (temp)
  359.         {
  360.           temp   = temp->next;
  361.           middle = middle->next;
  362.           if (temp)
  363.             temp = temp->next;
  364.         } 
  365.     
  366.       temp         = middle->next;
  367.       middle->next = NULL;
  368.       return merge (merge_sort (head), merge_sort (temp));
  369.     }   
  370. }
  371.  
  372. /* Returns the frequency of occurrence of elements in the key set. */
  373.  
  374. static int 
  375. get_occurrence (ptr)
  376.      LIST_NODE *ptr;
  377. {
  378.   int   value = 0;
  379.   char *temp;
  380.  
  381.   for (temp = ptr->char_set; *temp; temp++)
  382.     value += occurrences[*temp];
  383.   
  384.   return value;
  385. }
  386.  
  387. /* Enables the index location of all key set elements that are now 
  388.    determined. */
  389.   
  390. static void 
  391. set_determined (ptr)
  392.      LIST_NODE *ptr;
  393. {
  394.   char *temp;
  395.   
  396.   for (temp = ptr->char_set; *temp; temp++)
  397.     determined[*temp] = TRUE;
  398.   
  399. }
  400.  
  401. /* Returns TRUE if PTR's key set is already completely determined. */
  402.  
  403. static bool 
  404. already_determined (ptr)
  405.      LIST_NODE *ptr;
  406. {
  407.   bool  is_determined = TRUE;
  408.   char *temp;
  409.  
  410.   for (temp = ptr->char_set; is_determined && *temp; temp++)
  411.     is_determined = determined[*temp];
  412.   
  413.   return is_determined;
  414. }
  415.  
  416. /* Reorders the table by first sorting the list so that frequently occuring 
  417.    keys appear first, and then the list is reorded so that keys whose values 
  418.    are already determined will be placed towards the front of the list.  This
  419.    helps prune the search time by handling inevitable collisions early in the
  420.    search process.  See Cichelli's paper from Jan 1980 JACM for details.... */
  421.  
  422. void 
  423. reorder ()
  424. {
  425.   LIST_NODE *ptr;
  426.  
  427.   for (ptr = key_list.head; ptr; ptr = ptr->next)
  428.     ptr->occurrence = get_occurrence (ptr);
  429.   
  430.   key_list.hash_sort       = FALSE;
  431.   key_list.occurrence_sort = TRUE;
  432.   
  433.   for (ptr = key_list.head = merge_sort (key_list.head); ptr->next; ptr = ptr->next)
  434.     {
  435.       set_determined (ptr);
  436.     
  437.       if (already_determined (ptr->next))
  438.         continue;
  439.       else
  440.         {
  441.           LIST_NODE *trail_ptr = ptr->next;
  442.           LIST_NODE *run_ptr   = trail_ptr->next;
  443.       
  444.           for (; run_ptr; run_ptr = trail_ptr->next)
  445.             {
  446.         
  447.               if (already_determined (run_ptr))
  448.                 {
  449.                   trail_ptr->next = run_ptr->next;
  450.                   run_ptr->next   = ptr->next;
  451.                   ptr = ptr->next = run_ptr;
  452.                 }
  453.               else
  454.                 trail_ptr = run_ptr;
  455.             }
  456.         }
  457.     }     
  458. }
  459.  
  460. /* Determines the maximum and minimum hash values.  One notable feature is 
  461.    Ira Pohl's optimal algorithm to calculate both the maximum and minimum
  462.    items in a list in O(3n/2) time (faster than the O (2n) method). 
  463.    Returns the maximum hash value encountered. */
  464.   
  465. static int 
  466. print_min_max ()
  467. {
  468.   int          min_hash_value;
  469.   int          max_hash_value;
  470.   LIST_NODE   *temp;
  471.   
  472.   if (ODD (key_list.list_len)) /* Pre-process first item, list now has an even length. */
  473.     {              
  474.       min_hash_value  = max_hash_value = key_list.head->hash_value;
  475.       temp            = key_list.head->next;
  476.     }
  477.   else /* List is already even length, no extra work necessary. */
  478.     {                      
  479.       min_hash_value = MAX_INT;
  480.       max_hash_value = NEG_MAX_INT;
  481.       temp           = key_list.head;
  482.     }
  483.   
  484.   for ( ; temp; temp = temp->next) /* Find max and min in optimal o(3n/2) time. */
  485.     { 
  486.       static int i;
  487.       int key_2, key_1 = temp->hash_value;
  488.       temp  = temp->next;
  489.       key_2 = temp->hash_value;
  490.       i++;
  491.       
  492.       if (key_1 < key_2)
  493.         {
  494.           if (key_1 < min_hash_value)
  495.             min_hash_value = key_1;
  496.           if (key_2 > max_hash_value)
  497.             max_hash_value = key_2;
  498.         }
  499.       else
  500.         {
  501.           if (key_2 < min_hash_value)
  502.             min_hash_value = key_2;
  503.           if (key_1 > max_hash_value)
  504.             max_hash_value = key_1;
  505.         }
  506.   }
  507.   
  508.   printf ("\n#define MIN_WORD_LENGTH %d\n#define MAX_WORD_LENGTH %d\
  509. \n#define MIN_HASH_VALUE %d\n#define MAX_HASH_VALUE %d\
  510. \n/*\n%5d keywords\n%5d is the maximum key range\n*/\n\n",
  511.           key_list.min_key_len == MAX_INT ? key_list.max_key_len : key_list.min_key_len,
  512.           key_list.max_key_len, min_hash_value, max_hash_value,
  513.           key_list.total_keys, (max_hash_value - min_hash_value + 1));
  514.   return max_hash_value;
  515. }
  516.  
  517. /* Generates the output using a C switch.  This trades increased search
  518.    time for decreased table space (potentially *much* less space for
  519.    sparse tables). It the user has specified their own struct in the
  520.    keyword file *and* they enable the POINTER option we have extra work to
  521.    do.  The solution here is to maintain a local static array of user
  522.    defined struct's, as with the Print_Lookup_Function.  Then we use for
  523.    switch statements to perform a strcmp or strncmp, returning 0 if the str 
  524.    fails to match, and otherwise returning a pointer to appropriate index
  525.    location in the local static array. */
  526.  
  527. static void 
  528. print_switch ()
  529. {
  530.   char      *comp_buffer;
  531.   LIST_NODE *curr                     = key_list.head;
  532.   int        pointer_and_type_enabled = OPTION_ENABLED (option, POINTER) && OPTION_ENABLED (option, TYPE);
  533.   int        total_switches           = GET_TOTAL_SWITCHES (option);
  534.   int        switch_size              = keyword_list_length () / total_switches;
  535.  
  536.   if (pointer_and_type_enabled)
  537.     {
  538.       comp_buffer = (char *) alloca (strlen ("*str == *resword->%s && !strncmp (str + 1, resword->%s + 1, len - 1)")
  539.                                      + 2 * strlen (GET_KEY_NAME (option)) + 1);
  540.       sprintf (comp_buffer, OPTION_ENABLED (option, COMP)
  541.                ? "*str == *resword->%s && !strncmp (str + 1, resword->%s + 1, len - 1)"
  542.                : "*str == *resword->%s && !strcmp (str + 1, resword->%s + 1)",
  543.                GET_KEY_NAME (option), GET_KEY_NAME (option));
  544.     }
  545.   else
  546.     comp_buffer = OPTION_ENABLED (option, COMP) 
  547.       ? "*str == *resword && !strncmp (str + 1, resword + 1, len - 1)" 
  548.       : "*str == *resword && !strcmp (str + 1, resword + 1)";
  549.  
  550.   printf ("  if (len <= MAX_WORD_LENGTH && len >= MIN_WORD_LENGTH)\n    {\n\
  551.       register int key = %s (str, len);\n\n\
  552.       if (key <= MAX_HASH_VALUE && key >= MIN_HASH_VALUE)\n        {\n", GET_HASH_NAME (option));
  553.   
  554.   /* Properly deal with user's who request multiple switch statements. */
  555.  
  556.   while (curr)
  557.     {
  558.       LIST_NODE *temp              = curr;
  559.       int        lowest_case_value = curr->hash_value;
  560.       int        number_of_cases   = 0;
  561.  
  562.       /* Figure out a good cut point to end this switch. */
  563.  
  564.       for (; temp && ++number_of_cases < switch_size; temp = temp->next)
  565.         if (temp->next && temp->hash_value == temp->next->hash_value)
  566.           while (temp->next && temp->hash_value == temp->next->hash_value)
  567.             temp = temp->next;
  568.  
  569.       if (temp)
  570.         printf ("          if (key <= %d)\n            {\n", temp->hash_value);
  571.       else
  572.         printf ("            {\n");
  573.  
  574.       /* Output each keyword as part of a switch statement indexed by hash value. */
  575.       
  576.       if (OPTION_ENABLED (option, POINTER) || OPTION_ENABLED (option, DUP))
  577.         {
  578.           int i = 0;
  579.  
  580.           printf ("              %s%s *resword; %s\n\n",
  581.                   OPTION_ENABLED (option, CONST) ? "const " : "",
  582.                   pointer_and_type_enabled ? key_list.struct_tag : "char", 
  583.                   OPTION_ENABLED (option, LENTABLE) && !OPTION_ENABLED (option, DUP) ? "int key_len;" : "");
  584.           printf ("              switch (key - %d)\n                {\n", lowest_case_value);
  585.  
  586.           for (temp = curr; temp && ++i <= number_of_cases; temp = temp->next)
  587.             {
  588.               printf ("                case %*d:", field_width, temp->hash_value - lowest_case_value);
  589.               if (OPTION_ENABLED (option, DEBUG))
  590.                 printf (" /* hash value = %4d, keyword = \"%s\" */", temp->hash_value, temp->key);
  591.               putchar ('\n');
  592.  
  593.               /* Handle `natural links,' i.e., those that occur statically. */
  594.  
  595.               if (temp->link)
  596.                 {
  597.                   LIST_NODE *links;
  598.  
  599.                   for (links = temp; links; links = links->link)
  600.                     {
  601.                       if (pointer_and_type_enabled)
  602.                         printf ("                  resword = &wordlist[%d];\n", links->index);
  603.                       else
  604.                         printf ("                  resword = \"%s\";\n", links->key); 
  605.                       printf ("                  if (%s) return resword;\n", comp_buffer);
  606.                     }
  607.                 }
  608.               /* Handle unresolved duplicate hash values.  These are guaranteed
  609.                 to be adjacent since we sorted the keyword list by increasing
  610.                   hash values. */
  611.               if (temp->next && temp->hash_value == temp->next->hash_value)
  612.                 {
  613.  
  614.                   for ( ; temp->next && temp->hash_value == temp->next->hash_value;
  615.                        temp = temp->next)
  616.                     {
  617.                       if (pointer_and_type_enabled)
  618.                         printf ("                  resword = &wordlist[%d];\n", temp->index);
  619.                       else
  620.                         printf ("                  resword = \"%s\";\n", temp->key);
  621.                       printf ("                  if (%s) return resword;\n", comp_buffer);
  622.                     }
  623.                   if (pointer_and_type_enabled)
  624.                     printf ("                  resword = &wordlist[%d];\n", temp->index);
  625.                   else
  626.                     printf ("                  resword = \"%s\";\n", temp->key);
  627.                   printf ("                  return %s ? resword : 0;\n", comp_buffer);
  628.                 }
  629.               else if (temp->link)
  630.                 printf ("                  return 0;\n");
  631.               else
  632.                 {
  633.                   if (pointer_and_type_enabled)
  634.                     printf ("                  resword = &wordlist[%d];", temp->index);
  635.                   else 
  636.                     printf ("                  resword = \"%s\";", temp->key);
  637.                   if (OPTION_ENABLED (option, LENTABLE) && !OPTION_ENABLED (option, DUP))
  638.                     printf (" key_len = %d;", temp->length);
  639.                   printf (" break;\n");
  640.                 }
  641.             }
  642.           printf ("                default: return 0;\n                }\n");
  643.           printf (OPTION_ENABLED (option, LENTABLE) && !OPTION_ENABLED (option, DUP)
  644.                   ? "              if (len == key_len && %s)\n                return resword;\n"
  645.                   : "              if (%s)\n                return resword;\n", comp_buffer);
  646.           printf ("              return 0;\n            }\n");
  647.           curr = temp;
  648.         }
  649.       else                          /* Nothing special required here. */
  650.         {                        
  651.           int i = 0;
  652.           printf ("              char *s;\n\n              switch (key - %d)\n                {\n",
  653.                   lowest_case_value);
  654.       
  655.           for (temp = curr; temp && ++i <= number_of_cases; temp = temp->next)
  656.             if (OPTION_ENABLED (option, LENTABLE))
  657.               printf ("                case %*d: if (len == %d) s = \"%s\"; else return 0; break;\n",
  658.                       field_width, temp->hash_value - lowest_case_value, 
  659.                       temp->length, temp->key);
  660.             else
  661.               printf ("                case %*d: s = \"%s\"; break;\n",
  662.                       field_width, temp->hash_value - lowest_case_value, temp->key);
  663.                       
  664.           printf ("                default: return 0;\n                }\n              ");
  665.           printf ("return *s == *str && !%s;\n            }\n",
  666.                   OPTION_ENABLED (option, COMP) 
  667.                   ? "strncmp (s + 1, str + 1, len - 1)" : "strcmp (s + 1, str + 1)");
  668.           curr = temp;
  669.         }
  670.     }
  671.   printf ("         }\n    }\n  return 0;\n}\n");
  672. }
  673.  
  674. /* Prints out a table of keyword lengths, for use with the 
  675.    comparison code in generated function ``in_word_set.'' */
  676.  
  677. static void 
  678. print_keylength_table ()
  679. {
  680.   int        max_column = 15;
  681.   int        index      = 0;
  682.   int        column     = 0;
  683.   char      *indent     = OPTION_ENABLED (option, GLOBAL) ? "" : "  ";
  684.   LIST_NODE *temp;
  685.  
  686.   if (!OPTION_ENABLED (option, DUP) && !OPTION_ENABLED (option, SWITCH)) 
  687.     {
  688.       printf ("\n%sstatic %sunsigned %s lengthtable[] =\n%s%s{\n    ",
  689.               indent, OPTION_ENABLED (option, CONST) ? "const " : "",
  690.               key_list.max_key_len < MAX_UNSIGNED_CHAR ? "char" :
  691.               (key_list.max_key_len < MAX_UNSIGNED_SHORT ? "short" : "long"),
  692.               indent, indent);
  693.   
  694.       for (temp = key_list.head; temp; temp = temp->next, index++)
  695.         {
  696.     
  697.           if (index < temp->hash_value)
  698.             {
  699.       
  700.               for ( ; index < temp->hash_value; index++)
  701.                 printf ("%3d%s", 0, ++column % (max_column - 1) ? "," : ",\n    ");
  702.             }
  703.     
  704.           printf ("%3d%s", temp->length, ++column % (max_column - 1 ) ? "," : ",\n    ");
  705.         }
  706.   
  707.       printf ("\n%s%s};\n\n", indent, indent);
  708.     }
  709. }
  710.  
  711. /* Prints out the array containing the key words for the Perfect
  712.    hash function. */
  713.   
  714. static void 
  715. print_keyword_table ()
  716. {
  717.   char      *l_brace      = *key_list.head->rest ? "{" : "";
  718.   char      *r_brace      = *key_list.head->rest ? "}," : "";
  719.   int        doing_switch = OPTION_ENABLED (option, SWITCH);
  720.   char      *indent       = OPTION_ENABLED (option, GLOBAL) ? "" : "  ";
  721.   int        index        = 0;
  722.   LIST_NODE *temp;
  723.  
  724.   printf ("\n%sstatic %s%s wordlist[] =\n%s%s{\n", 
  725.           indent, OPTION_ENABLED (option, CONST) ? "const " : "",
  726.           key_list.struct_tag, indent, indent);
  727.   
  728.   /* Generate an array of reserved words at appropriate locations. */
  729.   
  730.     for (temp = key_list.head; temp; temp = temp->next, index++)
  731.         {
  732.             temp->index = index;
  733.  
  734.             if (!doing_switch && index < temp->hash_value)
  735.                 {
  736.                     int column;
  737.  
  738.                     printf ("      ");
  739.       
  740.                     for (column = 1; index < temp->hash_value; index++, column++)
  741.                         printf ("%s\"\",%s %s", l_brace, r_brace, column % 9 ? "" : "\n      ");
  742.       
  743.                     if (column % 10)
  744.                         printf ("\n");
  745.                     else 
  746.                         {
  747.                             printf ("%s\"%s\", %s%s\n", l_brace, temp->key, temp->rest, r_brace);
  748.                             continue;
  749.                         }
  750.                 }
  751.  
  752.             printf ("      %s\"%s\", %s%s\n", l_brace, temp->key, temp->rest, r_brace);
  753.  
  754.             /* Deal with links specially. */
  755.             if (temp->link)
  756.                 {
  757.                     LIST_NODE *links;
  758.  
  759.                     for (links = temp->link; links; links = links->link)
  760.                         {
  761.                             links->index = ++index;
  762.                             printf ("      %s\"%s\", %s%s\n", l_brace, links->key, links->rest, r_brace);
  763.                         }
  764.                 }
  765.  
  766.         }
  767.  
  768.   printf ("%s%s};\n\n", indent, indent);
  769. }
  770.  
  771. /* Generates C code for the hash function that returns the
  772.    proper encoding for each key word. */
  773.  
  774. static void 
  775. print_hash_function (max_hash_value)
  776.      int max_hash_value;
  777. {
  778.   int max_column = 10;
  779.   int count       = max_hash_value;
  780.  
  781.   /* Calculate maximum number of digits required for MAX_HASH_VALUE. */
  782.  
  783.   while ((count /= 10) > 0)
  784.     field_width++;
  785.  
  786.   if (OPTION_ENABLED (option, GNU))
  787.     printf ("#ifdef __GNUC__\ninline\n#endif\n");
  788.   
  789.   printf (OPTION_ENABLED (option, ANSI) 
  790.           ? "static int\n%s (register const char *str, register int len)\n{\n  static %sunsigned %s hash_table[] =\n    {"
  791.           : "static int\n%s (str, len)\n     register char *str;\n     register unsigned int  len;\n{\n  static %sunsigned %s hash_table[] =\n    {",
  792.           GET_HASH_NAME (option), OPTION_ENABLED (option, CONST) ? "const " : "",
  793.           max_hash_value < MAX_UNSIGNED_CHAR 
  794.           ? "char" : (max_hash_value < MAX_UNSIGNED_SHORT ? "short" : "int"));
  795.   
  796.   for (count = 0; count < ALPHABET_SIZE; ++count)
  797.     {
  798.       if (!(count % max_column))
  799.         printf ("\n    ");
  800.       
  801.       printf ("%*d,", field_width, occurrences[count] ? asso_values[count] : max_hash_value);
  802.     }
  803.   
  804.   /* Optimize special case of ``-k 1,$'' */
  805.   if (OPTION_ENABLED (option, DEFAULTCHARS)) 
  806.     printf ("\n    };\n  return %s + hash_table[str[len - 1]] + hash_table[str[0]];\n}\n\n",
  807.             OPTION_ENABLED (option, NOLENGTH) ? "0" : "len");
  808.   else
  809.     {
  810.       int key_pos;
  811.  
  812.       RESET (option);
  813.  
  814.       /* Get first (also highest) key position. */
  815.       key_pos = GET (option); 
  816.       
  817.       /* We can perform additional optimizations here. */
  818.       if (!OPTION_ENABLED (option, ALLCHARS) && key_pos <= key_list.min_key_len) 
  819.         { 
  820.           printf ("\n  };\n  return %s", OPTION_ENABLED (option, NOLENGTH) ? "0" : "len");
  821.           
  822.           for ( ; key_pos != EOS && key_pos != WORD_END; key_pos = GET (option))
  823.             printf (" + hash_table[str[%d]]", key_pos - 1);
  824.            
  825.           printf ("%s;\n}\n\n", key_pos == WORD_END ? " + hash_table[str[len - 1]]" : "");
  826.         }
  827.  
  828.       /* We've got to use the correct, but brute force, technique. */
  829.       else 
  830.         {                    
  831.           printf ("\n    };\n  register int hval = %s;\n\n  switch (%s)\n    {\n      default:\n",
  832.                   OPTION_ENABLED (option, NOLENGTH) 
  833.                   ? "0" : "len", OPTION_ENABLED (option, NOLENGTH) ? "len" : "hval");
  834.           
  835.           /* User wants *all* characters considered in hash. */
  836.           if (OPTION_ENABLED (option, ALLCHARS)) 
  837.             { 
  838.               int i;
  839.  
  840.               for (i = key_list.max_key_len; i > 0; i--)
  841.                 printf ("      case %d:\n        hval += hash_table[str[%d]];\n", i, i - 1);
  842.               
  843.               printf ("    }\n  return hval;\n}\n\n");
  844.             }
  845.           else /* do the hard part... */
  846.             {                
  847.               count = key_pos + 1;
  848.               
  849.               do
  850.                 {
  851.                   
  852.                   while (--count > key_pos)
  853.                     printf ("      case %d:\n", count);
  854.                   
  855.                   printf ("      case %d:\n        hval += hash_table[str[%d]];\n", 
  856.                           key_pos, key_pos - 1);
  857.                 }
  858.               while ((key_pos = GET (option)) != EOS && key_pos != WORD_END);
  859.               
  860.               printf ("    }\n  return hval%s ;\n}\n\n", key_pos == WORD_END 
  861.                       ? " + hash_table[str[len - 1]]" : "");
  862.           }
  863.       }
  864.   }
  865. }
  866.  
  867. /* Generates C code to perform the keyword lookup. */
  868.  
  869. static void 
  870. print_lookup_function ()
  871.   printf ("  if (len <= MAX_WORD_LENGTH && len >= MIN_WORD_LENGTH)\n    {\n\
  872.       register int key = %s (str, len);\n\n\
  873.       if (key <= MAX_HASH_VALUE && key >= MIN_HASH_VALUE)\n        {\n\
  874.           register %schar *s = wordlist[key]", 
  875.           GET_HASH_NAME (option), OPTION_ENABLED (option, CONST) ? "const " : "");
  876.   if (key_list.array_type != default_array_type)
  877.     printf (".%s", GET_KEY_NAME (option));
  878.  
  879.   printf (";\n\n          if (%s*s == *str && !%s)\n            return %s",
  880.           OPTION_ENABLED (option, LENTABLE) ? "len == lengthtable[key]\n              && " : "",
  881.           OPTION_ENABLED (option, COMP) ? "strncmp (str + 1, s + 1, len - 1)" : "strcmp (str + 1, s + 1)",
  882.           OPTION_ENABLED (option, TYPE) && OPTION_ENABLED (option, POINTER) ? "&wordlist[key]" : "s");
  883.   printf (";\n        }\n    }\n  return 0;\n}\n");
  884. }
  885.  
  886. /* Generates the hash function and the key word recognizer function
  887.    based upon the user's Options. */
  888.  
  889. void 
  890. print_output ()
  891. {
  892.   int global_table = OPTION_ENABLED (option, GLOBAL);
  893.  
  894.   printf ("%s\n", key_list.include_src);
  895.   
  896.   /* Potentially output type declaration now, reference it later on.... */
  897.   if (OPTION_ENABLED (option, TYPE) && !OPTION_ENABLED (option, NOTYPE)) 
  898.     printf ("%s;\n", key_list.array_type);
  899.   
  900.   print_hash_function (print_min_max ());
  901.   
  902.   if (global_table)
  903.     if (OPTION_ENABLED (option, SWITCH))
  904.       {
  905.         if (OPTION_ENABLED (option, LENTABLE) && OPTION_ENABLED (option, DUP))
  906.           print_keylength_table ();
  907.         if (OPTION_ENABLED (option, POINTER) && OPTION_ENABLED (option, TYPE))
  908.           print_keyword_table ();
  909.       }
  910.     else
  911.       {
  912.         if (OPTION_ENABLED (option, LENTABLE))
  913.           print_keylength_table ();
  914.         print_keyword_table ();
  915.       }
  916.   /* Use the inline keyword to remove function overhead. */
  917.   if (OPTION_ENABLED (option, GNU)) 
  918.     printf ("#ifdef __GNUC__\ninline\n#endif\n");
  919.   
  920.   /* Use ANSI function prototypes. */
  921.   printf (OPTION_ENABLED (option, ANSI)
  922.           ? "%s%s\n%s (register const char *str, register int len)\n{\n"
  923.           : "%s%s\n%s (str, len)\n     register char *str;\n     register unsigned int len;\n{\n", 
  924.             OPTION_ENABLED (option, CONST) ? "const " : "", 
  925.             key_list.return_type, GET_FUNCTION_NAME (option));
  926.   
  927.   /* Use the switch in place of lookup table. */
  928.   if (OPTION_ENABLED (option, SWITCH))
  929.     {               
  930.       if (!global_table)
  931.         {
  932.           if (OPTION_ENABLED (option, LENTABLE) && OPTION_ENABLED (option, DUP))
  933.             print_keylength_table ();
  934.           if (OPTION_ENABLED (option, POINTER) && OPTION_ENABLED (option, TYPE)) 
  935.             print_keyword_table ();
  936.         }
  937.       print_switch ();
  938.     }
  939.   else                /* Use the lookup table, in place of switch. */
  940.     {           
  941.       if (!global_table)
  942.         {
  943.           if (OPTION_ENABLED (option, LENTABLE))
  944.             print_keylength_table ();
  945.           print_keyword_table ();
  946.         }
  947.       print_lookup_function ();
  948.     }
  949.  
  950.   if (key_list.additional_code)
  951.     {
  952.       int c;
  953.  
  954.       while ((c = getchar ()) != EOF)
  955.         putchar (c);
  956.     }
  957.   fflush (stdout);
  958. }
  959.  
  960. /* Sorts the keys by hash value. */
  961.  
  962. void 
  963. sort ()
  964.   key_list.hash_sort       = TRUE;
  965.   key_list.occurrence_sort = FALSE;
  966.   
  967.   key_list.head = merge_sort (key_list.head);
  968. }
  969.  
  970. /* Dumps the key list to stderr stream. */
  971.  
  972. static void 
  973. dump () 
  974. {      
  975.   LIST_NODE *ptr;
  976.  
  977.   fprintf (stderr, "\nList contents are:\n(hash value, key length, index, key set, key):\n");
  978.   
  979.   for (ptr = key_list.head; ptr; ptr = ptr->next)
  980.     fprintf (stderr, "%7d,%7d,%6d, %s, %s\n",
  981.              ptr->hash_value, ptr->length, ptr->index,
  982.              ptr->char_set, ptr->key);
  983. }
  984.  
  985. /* Simple-minded constructor action here... */
  986.  
  987. void
  988. key_list_init ()
  989. {   
  990.   key_list.total_keys      = 1;
  991.   key_list.max_key_len     = NEG_MAX_INT;
  992.   key_list.min_key_len     = MAX_INT;
  993.   key_list.return_type     = default_return_type;
  994.   key_list.array_type      = key_list.struct_tag  = default_array_type;
  995.   key_list.head            = NULL;
  996.   key_list.additional_code = FALSE;
  997. }
  998.  
  999. /* Returns the length of entire key list. */
  1000.  
  1001. int 
  1002. keyword_list_length () 
  1003.   return key_list.list_len;
  1004. }
  1005.  
  1006. /* Returns length of longest key read. */
  1007.  
  1008. int 
  1009. max_key_length ()
  1010.   return key_list.max_key_len;
  1011. }
  1012.  
  1013. /* DESTRUCTOR dumps diagnostics during debugging. */
  1014.  
  1015. void
  1016. key_list_destroy () 
  1017.   if (OPTION_ENABLED (option, DEBUG))
  1018.     {
  1019.       fprintf (stderr, "\nDumping key list information:\ntotal unique keywords = %d\
  1020. \ntotal keywords = %d\nmaximum key length = %d.\n", 
  1021.                     key_list.list_len, key_list.total_keys, key_list.max_key_len);
  1022.       dump ();
  1023.       fprintf (stderr, "End dumping list.\n\n");
  1024.     }
  1025. }
  1026.  
  1027.