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