/*****************************************************************/
/**                                                             **/
/**             (C) Copyright 1992 the Regents of the           **/
/**        University of California.  All Rights Reserved.      **/
/**                                                             **/
/**        This work was produced under the sponsorship of      **/
/**         the U.S. Department of Energy.  The Government      **/
/**                retains certain rights therein.              **/
/**                                                             **/
/**                         Written by                          **/
/**         Distributed Programming Environments Project        **/
/**           Computer Software and Networking Division,        **/
/**                   Livermore Computer Center,                **/
/**            Lawrence Livermore National Laboratory           **/
/**                                                             **/
/*****************************************************************/

#include <stdlib.h>
#include <stdio.h>
#include <string.h>

#define _KEYTAB_C 

/* to build the perfect hash testing program define HASHTEST here and
 * compile this file with:
 *   CC -o htest  -I../runtime/include keytab.C */

#undef HASHTEST

#ifdef HASHTEST

#include "keytab.h"
#include "misc.h"
#include "y.tab.h"

#else

#include "decls.h"
#include "keytab.h"
#include "pnode.h"
#include "misc.h"
#include "y.tab.h"

#endif


// A macro used to simplify the hash function as a function of char's

#define LongAndOdd(c) ((long)(((int)(c))*16+1))


/*
 * the members of class fast_hash_table
 */

fast_hash_table::fast_hash_table( int s )
{
  size     = s;
  contents = new (Keyword* [size]);
  for ( int i=0; i<size; i++ ) contents[i] = NULL;
}

fast_hash_table::~fast_hash_table()
{
  for ( int i=0; i<size; i++ ) 
    if (contents[i] != NULL) delete contents[i];
  delete contents;
}

int  fast_hash_table::add( Keyword *key )
{
  int index;

  index = hashval(key->name);
  if (contents[index] != NULL)
    return FALSE;
  else
    contents[index] = key;
  return TRUE;
}

Keyword *fast_hash_table::lookup( char *key )
{
  int index;

  index = hashval(key);
  if (contents[index] == NULL) 
    return NULL;
  else
    return contents[index];
}

int  fast_hash_table::hashval( char *key )

{
  int  len;
  long x1, x2, x3, x4, x5, x6;


  switch (len = strlen(key)) {
  case 0:
    return 0;
  case 1:
    return ( LongAndOdd(key[0]) * 29 ) % size;
  case 2:
    x1 = ( LongAndOdd(key[0]) * 11 );
    x2 = ( LongAndOdd(key[1]) * 3 ) % size;
    x3 = ( LongAndOdd(key[len-1]) * 5 );
    x4 = ( LongAndOdd(key[len-2]) * 7 ) % size;
    return (((x1*x2)%size) + ((x3*x4)%size)) % size;
  default:
    x1 = ( LongAndOdd(key[0]) * 7 );
    x2 = ( LongAndOdd(key[1]) * 13 ) % size;
    x3 = ( LongAndOdd(key[len-1]) * 11 );
    x4 = ( LongAndOdd(key[len-2]) * 3 ) % size;
    x5 = ( LongAndOdd(key[2]) * 5 );
    x6 = ( LongAndOdd(key[len-3]) * 2 ) % size;
    return (((x1*x6)%size) + ((x3*x5)%size) + ((x4*x2)%size)) % size;
  }
}

void fast_hash_table::show()
{
  for (int i=0; i<size; i++) {
    if (contents[i]==NULL) continue;
    printf(" %4d: %s\n",i,contents[i]->name);
  }
}

/* the main table, used during parsing. */

fast_hash_table *Keyword_Table; 


#ifndef HASHTEST

/* these are four routines for checking if a name is a particuar kind
 * of keyword. They may be(come) extraneous in the final parser */

int is_keyword( char *ident )
{
  Keyword *lookup;

  if ((lookup=Keyword_Table->lookup(ident)) == NULL) 
    return 0;
  if (lookup->kind != KEY_ELROS)
    return 0;
  if (strcmp(ident,lookup->name) == 0) {
    return lookup->token;
  }
  return 0;
}


int is_primitive( char *ident, enum abstr_kind *which )
{
  Keyword *lookup;

  if ((lookup=Keyword_Table->lookup(ident)) == NULL) 
    return 0;
  if (lookup->kind != KEY_PRIM)
    return 0;
  if (strcmp(ident,lookup->name) == 0) {
    *which = lookup->akind;
    return lookup->token;
  }
  return 0;
}

int is_ansi_key( char *ident )
{
  Keyword *lookup;

  if ((lookup=Keyword_Table->lookup(ident)) == NULL) 
    return 0;
  if (lookup->kind != KEY_ANSI)
    return 0;
  if (strcmp(ident,lookup->name) == 0) 
    return lookup->token;
  return 0;
}

int is_config_key( char *ident )
{
  Keyword *lookup;

  if (!in_config_file)
    return 0;
  if ((lookup=Keyword_Table->lookup(ident)) == NULL) 
    return 0;
  if (lookup->kind != KEY_CONFIG)
    return 0;
  if (strcmp(ident,lookup->name) == 0) 
    return lookup->token;
  return 0;
}

#endif

/*
 * These are the keyword source lists 
 */

PrimKeytoken prim_table[] = {

     /* reserved word table in alpha order*/

   "BitString",		BITSTRING,           AKIND_BITSTRING, 
   "Boolean",		BOOLEAN,             AKIND_BOOLEAN,
   "Enumerated",	ENUMERATED,          AKIND_ENUMERATED,
   "GeneralString",	GENERALSTRING,       AKIND_GENERALSTRING,
   "GraphicString",	GRAPHICSTRING,       AKIND_GRAPHICSTRING,
   "IA5String",		IA5STRING,           AKIND_IA5STRING,
   "Integer",		INTEGER,             AKIND_INTEGER,
   "Null",		NULLTYPE,            AKIND_NULL,
   "NumericString",	NUMERICSTRING,       AKIND_NUMERICSTRING,
   "ObjectIdentifier",	OBJECTIDENTIFIER,    AKIND_OBJECTIDENTIFIER,
   "OctetString",	OCTETSTRING,         AKIND_OCTETSTRING,
   "PrintableString",	PRINTABLESTRING,     AKIND_PRINTABLESTRING,
   "Real",		REAL,                AKIND_REAL,
   "TeletexString",	TELETEXSTRING,       AKIND_TELETEXSTRING,
   "VideotexString",	VIDEOTEXSTRING,      AKIND_VIDEOTEXSTRING,
   "VisibleString",	VISIBLESTRING,       AKIND_VISIBLESTRING,
   "Any",		ANY,	 	     AKIND_ANY
   };


ElrosKeytoken keyword_table[] = {
 
/* The third field tells whether the word is always a keyword, or
 * just inside an interface spec, non-zero means always.
 * 2 means the next identifier should be an instance id
 * this table is also in alphabetical order 
 */

   "Abort_inst",      ABORTINST,       1,
   "Accept",          ACCEPT,          2,
   "Application",     APPLICATION,     0,
   "Array",	      ARRAY,           0,
   "Autotag",	      AUTOTAG,         0,
   "Call",            CALL,            0,
   "Context",	      CONTEXT,         0,
   "Decode",	      DECODE,          2,
   "Default",         DEFAULT_KEYWORD, 0,
   "DynamicArray",    DYNAMICARRAY,    0,
   "Encode",	      ENCODE,          2,
   "End",	      END,             0,
   "Error",           ERROR_KEYWORD,   0,
   "Exceptions",      EXCEPTION,       1,
   "Explicit",        EXPLICIT,        0,
   "Explicit_tags",   EXPLICIT_TAGS,   0,
   "False",           BOOLEAN_CONST,   0,
   "Flush_inst",      FLUSHINST,       1,
   "Freeable",        FREEABLE,        0,
   "Give",            GIVE,            2,
   "Implicit",	      IMPLICIT,        0,
   "Implicit_tags",   IMPLICIT_TAGS,   0,
   "In",	      IN,              0,
   "InOut",	      INOUT,           0,
   "Interface",	      INTERFACE,       1,
   "Invoke",          INVOKE,          0,
   "Names",	      NAMES,           0,
   "Noautotag",	      NOAUTOTAG,       0,
   "Optional",	      OPTIONAL,        0,
   "On",	      ON,              1,
   "Out",	      OUT,             0,
   "Private",	      PRIVATE,         0,
   "Record",	      RECORD,          0,
   "Reject",          REJECT_KEYWORD,  0,
   "Result",          RESULT,          0,
   "Sequence",	      SEQUENCE,        0,
   "Set",	      SET,             0,
   "True",            BOOLEAN_CONST,   0,
   "Unbind",	      UNBIND,          1,
   "Unfreeable",      UNFREEABLE,      0,
   "Union",           UNION_KEYWORD,   0,
   "Universal",	      UNIVERSAL,       0
   };

Keytoken ansi_keyword_table[] = {

"auto"            , AUTO          ,
"break"	          , BREAK         ,
"case"            , CASE          ,
"char"            , CHAR          ,
"const"           , CONST         ,
"continue"        , CONTINUE      ,
"default"         , DEFAULT       ,
"do"              , DO            ,
"double"          , DOUBLE        ,
"else"            , ELSE          ,
"enum"            , ENUM          ,
"extern"          , EXTERN        ,
"float"           , FLOAT         ,
"for"             , FOR           ,
"goto"            , GOTO          ,
"if"              , IF            ,
"int"             , INT           ,
"long"            , LONG          ,
"register"        , REGISTER      ,
"return"          , RETURN        ,
"short"           , SHORT         ,
"signed"          , SIGNED        ,
"sizeof"          , SIZEOF        ,
"static"          , STATIC        ,
"struct"          , STRUCT        ,
"switch"          , SWITCH        ,
"typedef"         , TYPEDEF       ,
"union"           , UNION         ,
"unsigned"        , UNSIGNED      ,
"void"            , VOID          ,
"volatile"        , VOLATILE      ,
"while"           , WHILE         
};

Keytoken config_keyword_table[] = {

"SENDBUFFERSIZE",    SENDBUFFERSIZE,
"RECEIVEBUFFERSIZE", RECEIVEBUFFERSIZE,
"BIG_ENDIAN",        BIG_ENDIAN,
"LITTLE_ENDIAN",     LITTLE_ENDIAN,
"BIND",              BIND

};


#ifdef  HASHTEST

/* this little section finds the appropriate hash table size for the
 * Keyword_Table. Because the Keyword_Table relies on a perfect hash,
 * it is necessary to find a perfect hash. I choose to do so at 
 * pre-compile time, and then build the parser with the correct table
 * size. Naturally this section is not part of the final parser, it is
 * just a tool that helps you find a perfect hash by compiling hash.c
 * and keytab.c as a complete program. */


main()

{
  for ( int size = 41; size < 20000; size++) {

    printf(" Size %d...\n",size);

    {
      fast_hash_table *Keyword_Table = new fast_hash_table(size);
      Keyword *tmpkey;

      int good = TRUE;

      for (int i=0; i<ANSI_KEYTABSIZE; i++) {
     
	tmpkey        = new Keyword;
	tmpkey->name  = ansi_keyword_table[i].name;
	tmpkey->token = ansi_keyword_table[i].token;

	if (! Keyword_Table->add(tmpkey)) {
	  printf(" Collision on %s \n",tmpkey->name);
	  good = FALSE;
	  break;
	}
      }
      for (i=0; i<CONFIG_KEYTABSIZE; i++) {

	tmpkey        = new Keyword;
	tmpkey->name  = config_keyword_table[i].name;
	tmpkey->token = config_keyword_table[i].token;

	if (! Keyword_Table->add(tmpkey)) {
	  printf(" Collision on %s \n",tmpkey->name);
	  good = FALSE;
	  break;
	}
      }
      for (i=0; i<PRIMITIVE_KEYTABSIZE; i++) {

	tmpkey        = new Keyword;
	tmpkey->name  = prim_table[i].pw_name;
	tmpkey->token = prim_table[i].pw_yylex;
	tmpkey->akind = prim_table[i].pw_primitive;

	if (! Keyword_Table->add(tmpkey)) {
	  printf(" Collision on %s \n",tmpkey->name);
	  good = FALSE;
	  break;
	}
      }
      for (i=0; i<ELROS_KEYTABSIZE; i++) {

	tmpkey        = new Keyword;
	tmpkey->name  = keyword_table[i].kw_name;
	tmpkey->token = keyword_table[i].kw_yylex;
	tmpkey->lflag = keyword_table[i].lang_flg;

	if (! Keyword_Table->add(tmpkey)) {
	  printf(" Collision on %s \n",tmpkey->name);
	  good = FALSE;
	  break;
	}
      }
 
      if (good) {
	printf(" Found.\n");
	Keyword_Table->show();
	exit(0);
      }
      delete Keyword_Table;
    }
  }
}

#endif

