/*****************************************************************/
/**                                                             **/
/**             (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 "symtab.h"
#include "misc.h"

/*
 *      --------------------
 *       hash_table members
 *      --------------------
 */

hash_table::hash_table( int siz )
{
  size      = siz;
  fillcount = 0;
  fillimit  = siz/HASHTAB_EXPANSION;
  contents  = NewThings(symbol_element *,siz);

  for (int i=0; i<siz; i++) contents[i] = NULL;
}


int  hash_table::hashfun( char *key, int tabsize )

     /* Calculate the index that the arg hashes to in a table
      * of the given size */
{
  int  len;
  int  modval;
  long x1, x2, x3, x4, x5, x6;


  /* an odd modulus is better than an even one */
  
  modval = (tabsize%2 == 0) ? tabsize-1 : tabsize;
  
  /* determine what index we hash to */

  switch (len = strlen(key)) {

  case 0:
    return 0;

  case 1:
    return ( LongAndOdd(key[0]) * 29 ) % modval;

  case 2:
    x1 = ( LongAndOdd(key[0]) * 11 );
    x2 = ( LongAndOdd(key[1]) * 3 ) % modval;
    x3 = ( LongAndOdd(key[len-1]) * 5 );
    x4 = ( LongAndOdd(key[len-2]) * 7 ) % modval;
    return (((x1*x2)%modval) + ((x3*x4)%modval)) % modval;

  default:
    x1 = ( LongAndOdd(key[0]) * 7 );
    x2 = ( LongAndOdd(key[1]) * 13 ) % modval;
    x3 = ( LongAndOdd(key[len-1]) * 11 );
    x4 = ( LongAndOdd(key[len-2]) * 3 ) % modval;
    x5 = ( LongAndOdd(key[2]) * 5 );
    x6 = ( LongAndOdd(key[len-3]) * 17 ) % modval;
    return (((x1*x6)%modval) + ((x3*x5)%modval) + ((x4*x2)%modval)) % modval;
  }
}


void hash_table::hashit( symbol_element  *entry, 
			 symbol_element **table, 
			 int              tabsize )

     /* this is the routine to actually fill in an entry in the
      * table. It assumes that expansion is already taken care of.
      * Since it is used both for expansion and normal operation, we 
      * must pass it the "table" rather than using this->contents. */
{
  int   index;
  int   start;
  char *key;

  if (entry == NULL) {
    report_error("internal error",
		 "(non-fatal): tried to hash a NULL entry",
		 NULL);
    return;
  }
  if ((key = entry->get_name()) == NULL) {
    report_error("internal error",
		 "(non-fatal): tried to hash a NULL key",
		 NULL);
    return;
  }

  start = hashfun(key,tabsize);
  index = start;
  while (table[index] != NULL) {
    if ((index = (index+1)%tabsize) == start) {
      BUG_CHECK("a hash_table failed to expand, and filled up");
    }
  }
  table[index] = entry;
}


void hash_table::add( symbol_element *entry )
{
  int              new_size;
  symbol_element **new_contents;

  /* Expand the table if we have to. This is not as expensive as it
   * appears. Because of the exponential growth (multiplier at each
   * expansion), the number of hashes into the table is amortized 
   * linear in the size of the table. */

  if (fillcount > fillimit) {

    new_size     = size*HASHTAB_EXPANSION;
    new_contents = NewThings(symbol_element *,new_size);
    
    /* need to initialize this new memory */
 
    for (int j=0; j<new_size; j++) new_contents[j] = NULL;

    /* rehash all the entries into the bigger table */

    for (int i=0; i<size; i++) {
      if (contents[i] != NULL) {
	hashit( contents[i], new_contents, new_size );
      }
    }

    /* make the new table current, fillcount stays the same, of course.
     * Notice that we only delete "contents", we don't loop through and
     * delete all the individual symbol_element's, because they are all still
     * in use - they are pointed to by new_contents */

    FreeThings(contents);

    contents = new_contents;
    size     = new_size;
    fillimit = new_size/HASHTAB_EXPANSION;
  }

  /* add the entry to the table */

  hashit(entry,contents,size);
  fillcount++;
}


symbol_element *hash_table::lookup( char *key )

     /* looks for the given key in the table, returns NULL if 
      * not found */
{
  int   index;

  /* find the hash index */

  index = hashfun(key,size);

  /* check that index, and subsequent non-empty entries until found
   * or an empty entry is seen */

  while (contents[index] != NULL) {
    if (strcmp(contents[index]->get_name(),key) == 0)
      return contents[index];
    else
      index = (index+1)%size;
  }
  return NULL;
}


symbol_element *hash_table::swap_in( symbol_element *old_elem, 
				     symbol_element *new_elem )
{
  for (int i=0; i<size; i++) {
    if (contents[i] == old_elem) {
      contents[i] = new_elem;
      return old_elem;
    }
  }
  return NULL;
}


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

void hash_table::dump()
{
  char           *iname;
  char           *none_string;
  symbol_element *dups;

  none_string = "<none>";

  printf("------------------\n");
  printf(" size:      %6d\n",size);
  printf(" fillcount: %6d\n",fillcount);
  printf(" fillimit:  %6d\n",fillimit);
  printf("------------------\n");
  for (int i=0; i<size; i++) {
    if (contents[i] == NULL) continue;

    iname = (contents[i]->get_interf() != NULL) ? 
      contents[i]->get_interf()->get_name() : none_string;

    printf(" %6d: key: %12s   Interface: %12s   kind: %s\n",
	   i,
	   contents[i]->get_name(),
	   iname,
	   (NameOfSymKind(contents[i]->get_kind())));
    
    /* show any duplicates that may be chained to this one */

    for ( dups =  (symbol_element *) (contents[i]->get_tlptr());
	  dups != NULL;
	  dups =  (symbol_element *) (dups->get_tlptr()) )
      {
	iname = (dups->get_interf() != NULL) ?
	  dups->get_interf()->get_name() : "<none>";

	printf("--dup--> key: %12s Interface: %12s kind: %s\n",
	       dups->get_name(),
	       iname,
	       (NameOfSymKind(dups->get_kind())));
      }

  }
  printf("------------------\n"); }


/*
 * --------------------
 * symbol_table members
 * --------------------
 */


/* Using hash_tables, the symbol_table is now straightforward. It is
 * simply a chain of hash_table's, one per current active scope, used
 * as a stack. We use HashLink's to chain the hash_table's */

symbol_table::~symbol_table()
     
     /* free up everything (that needs it) */

{
  HashLink *tracer;
  HashLink *tmp;
  
  tracer = contents;
  while(tracer != NULL) {
    if (tracer->kind == SCOP_STD) {
      tracer->contents->purge();
      delete (tracer->contents);
    }
    tmp = tracer->prev;
    delete tracer;
    tracer = tmp;
  } 
}

void symbol_table::open_scope()

     /* start a new standard scope table at the front of the chain. */

{
  HashLink *newlink;
    
  /* first put a fresh link in the chain */

  newlink          = new HashLink(SCOP_STD);
  newlink->prev    = contents;
  newlink->symlist = NULL;
  contents         = newlink;
  scope_level++;

  /* now, fill in the link appropriately. This is the standard case, 
   * a new C scope. Create a new hash_table for this scope, and free 
   * it when we close. */
  
  switch (scope_level) {
  case 0:
    newlink->contents = new hash_table(SYMTAB_SIZE_FILE);
    return;
  case 1:
    newlink->contents = new hash_table(SYMTAB_SIZE_FUNCTION);
    return;
  default:
    newlink->contents = new hash_table(SYMTAB_SIZE_INNER);
    return;
  }
}

void symbol_table::attach_scope( ScopeKind sk, symbol_list *info )

     /* Bring the "external" information into scope. It's a list of
      * names or operations from an interface_element - for when we
      * enter a give, accept, or an operation stmt... */

{
  HashLink *newlink;
    
  /* first put a fresh link in the chain */

  newlink           = new HashLink(sk);
  newlink->prev     = contents;
  newlink->contents = NULL;
  contents          = newlink;
  scope_level++;

  /* now, fill in the link appropriately */

  switch (sk) {
  case SCOP_OPS:
  case SCOP_NAMES:
    {
      newlink->symlist = info;
      return;
    }
  case SCOP_STD:
    {
      BUG_CHECK("tried to attach_scope() a SCOP_STD");
    }
  case SCOP_UNKNOWN:
    {
      BUG_CHECK("opened UNKNOWN scope.");
    }
  }
}

void symbol_table::close_scope()

     /* pop the current scope, freeing memory if needed */ 
{
  HashLink *prev;

  if (contents == NULL) {
    report_error("internal error",
		 "(non-fatal): Closed non-existent scope",
		 NULL);
    return;
  }
  prev = contents->prev;

  if (contents->kind == SCOP_STD) {
    contents->contents->purge();
    delete contents->contents;
  }
  delete contents;

  contents = prev;
  
  if (scope_level-- <= SCOPLEV_UNKNOWN)
    report_error("internal error",
		 "(non-fatal): scope_level corrupted",
		 NULL);
}
  
void symbol_table::add( symbol_element *entry ) 
{
  symbol_element *oldentry;

  /* for the moment, do safety checks, we can #ifdef them out later */

  if (entry->get_kind() == SYM_OP || entry->get_kind() == SYM_NAME) {
    report_error("internal error",
		 "can't add() SYM_OP or SYM_NAME to symbol_table.\n %s not added",
		 entry->get_name());
    return;
  }
  if (contents == NULL) {
    BUG_CHECK("tried to symbol_table::add() while no scope was active");
  }
  if (contents->kind != SCOP_STD) {
    BUG_CHECK("tried to symbol_table::add() to a non-SCOP_STD");
  }
  if (contents->contents == NULL) {
    BUG_CHECK("no hash_table for current scope in symbol_table");
  }

  /* Now do a lookup to see if there is any kind of multiple-decl
   * logic needed */

  if ((oldentry = lookup(entry->get_name())) == NULL) {
    
    /* easy. just add this entry. */
    
    contents->contents->add((symbol_element *)entry);
    return;
  }

  /* Need to handle multiple decls, there are alot of cases. First,
   * decide wether we're currently at global scope, or an inner scope */

  if (scope_level == SCOPLEV_GLOBAL) {

    /* we are adding a multiple decl at global scope - only SYM_TYPE's may
     * be plural, more than one SYM_TYPEDEF, SYM_IDENT, SYM_INTER, or
     * SYM_INST is an error (becase they all produce a C global in the
     * vars/typedefName name space). NOTE: no call to hash_table::add()
     * will be made - the new entry is going to end up on a "treelink"
     * chain. */

    if (entry->get_kind() != SYM_TYPE) {

      /* do this plurality check. We will always ensure that the C symbol
       * (SYM_TYPEDEF, SYM_IDENT, SYM_INTER, or SYM_INST) is first in
       * the list, when present. This way, if the identifer is redeclared
       * in an inner scope later, we can point to all the non-C symbols by
       * simply skipping the first one, if it's a C symbol. This provides
       * normal C scoping, and keeps Elros types visible everywhere. */
      
      if (oldentry->get_kind() != SYM_TYPE) {
/***********   check this out later ***************
	report_error("error 29",
		     "%s is already a %s - redeclaration ignored",
		     entry->get_name(),
		     NameOfSymKind(oldentry->get_kind()));
****************************************************/
	return;
      }
      
      /* plurality check passes, add this entry at the front of the
       * list, for the reasons just given above. To do so, we use
       * the swap_in() member of hash_table. First, make the new entry
       * point to the old one (since the new one is the new head of the
       * list). Then swap the new one into the old one's place in the
       * hash table. Recall that we are at global scope, so we just use
       * the "contents" pointer */

      entry->set_tlptr(oldentry);
      switch( contents->kind ) {
      case SCOP_STD:
	{
	  if ( last_look->contents->swap_in(oldentry,entry) == NULL ) {
	   report_error("internal error",
			"hash_table corruption found in symbol_table.\n       Troublesome symbol: %s\n",
			oldentry->get_name());
	    exit(1);
	  }
	  return;
	}
      case SCOP_OPS:
      case SCOP_NAMES:
      case SCOP_UNKNOWN:
	{
	  BUG_CHECK("Global scope is not SCOP_STD !?");
	}
      }
    }
    else {
      
      /* we are adding another SYM_TYPE, no checks needed. We simply
       * chain this entry after the existing one. We can't put
       * it right in front because we might then displace an entry for
       * a C-symbol (see the code above for details). */

      entry->    set_tlptr( oldentry->get_tlptr() );
      oldentry-> set_tlptr( entry );
    }
  }
  else {

    /* we are not at global scope - therefore we can only add C symbols
     * (SYM_TYPEDEF, SYM_IDENT, SYM_INTER, or SYM_INST). */

    if (entry->get_kind() == SYM_TYPE) {
      report_error("internal error",
	           "Tried to add SYM_TYPE at non-global scope: %s",
		    entry->get_name());
      return;
    }

    /* The C symbol we are adding masks other C symbols, as per the
     * scoping rules of C. However, Elros SYM_TYPE's are not masked, and
     * if they exist, this new entry's duplicates field (tlptr) must point to
     * them (masking the C symbols). SYM_OP's and SYM_NAME's are a 
     * separate issue, the duplicates mechanism ignores these scopes
     * because they are external to the symbol table and modifying them
     * would need even more bookeeping, so we need to make a new call
     * to check for multiple decls, and ignore OP's and NAME's
     *
     * The trade off is that lookups, and the callers of the symbol
     * table routines need to be a little smarter - they must be aware
     * of these two independent mechansims [ External info (OP's and NAME's)
     * vs. the duplicate (tlptr) mechanism which ignores external info ] */

    if ((oldentry=lookup(entry->get_name(), SMASK_STD)) == NULL) {
      
      /* easy. there are no C duplicates after all. */
   
      contents->contents->add((symbol_element *)entry);
      return;
    }

    if (oldentry->get_kind() == SYM_TYPE) {
      
      /* An Elros type, but no previous C symbols, this new entry 
       * points to it, and all its duplicates... */

      entry->set_tlptr( oldentry );
    }
    else if (oldentry->get_tlptr() != NULL) {

      /* A previous C entry, with duplicates of it already, this new 
       * entry points to the duplicates, but masks the C symbol */
	 
      entry->set_tlptr( oldentry->get_tlptr() );
    }
    else {
      
      /* There is no true duplication. We are simply masking an outer
       * C symbol. This call is redundant, but here for "completeness",
       * it gets inlined, anyway */

     entry->set_tlptr( NULL );
    }

    /* now add this entry to the symbol_table at the current innermost
     * scope */

    contents->contents->add((symbol_element *)entry);
  } 
}


void symbol_table::add_ident( char *nam )
    {
      symbol_element *entry = new symbol_element;
      entry->set_kind(SYM_IDENT);
      entry->set_name(nam);
      add(entry);
    }

void symbol_table::add_inter( char *nam )
    {
      symbol_element *entry = new symbol_element;
      entry->set_kind(SYM_INTER);
      entry->set_name(nam);
      add(entry);
    }

void symbol_table::add_typedef( char *nam )
    {
      symbol_element *entry = new symbol_element;
      entry->set_kind(SYM_TYPEDEF);
      entry->set_name(nam);
      add(entry);
    }

void symbol_table::add_type( char *nam, interface_element *ifc )
    {
      symbol_element *entry = new symbol_element;
      entry->set_kind(SYM_TYPE);
      entry->set_name(nam);
      entry->set_interf(ifc);
      add(entry);
    }

void symbol_table::add_inst( char *nam, interface_element *ifc )
    {
      symbol_element *entry = new symbol_element;
      entry->set_kind(SYM_INST);
      entry->set_name(nam);
      entry->set_interf(ifc);
      add(entry);
    }

  
symbol_element *symbol_table::lookup_driver( char      *name, 
	                                     HashLink  *start,
	                                     int        mask ) 
{
  int op_seen;
  int name_seen;

  hash_table     *htable;
  symbol_list    *slist;
  HashLink       *tracer;
  symbol_element *result;


  op_seen   = FALSE;
  name_seen = FALSE;

  /* loop up through the chain of hash_table's, looking for the
   * desired symbol. Cresolve indicates that a C symbol is desired,
   * only look at SCOP_STD if set */
  
  for (tracer = start; tracer != NULL; tracer = tracer->prev) {

    /* An inner SCOP_OPS, causes outer ones to go out of scope - only
     * the innermost give's interface's ops are in scope at any time */

    if (tracer->kind == SCOP_OPS) {
      if (op_seen)
	continue;
      else
	op_seen = TRUE;
    }

    /* two name scopes is not legal - that would imply an operation call
     * nested inside another */
    
    if (tracer->kind == SCOP_NAMES) {
      if (name_seen)
	printf(" Warning: two NAMES scopes currently active !?\n");
      else if (op_seen) {
	printf(" Warning: SCOP_OPS subordinate to SCOP_NAMES !?\n");
      }
      else
	name_seen = TRUE;
    }
    
    /* depending on the type of this scope, the information is in
     * one of two forms: hash_table, symbol_list. As for C resolve,
     * it's sufficeint just use standard_lookup as is, because the
     * C symbol always heads the tlptr chains in the hash_tables -
     * ( see symbol_table::add() if you have no idea what I'm talking
     *   about ) */

    switch(tracer->kind) {
    case SCOP_STD:
      {
	/* are we even looking for such symbols ? */

	if ((mask & SMASK_STD) == 0) continue;

	/* Yes, we are. */

	if ((htable = tracer->contents) != NULL) {
	  if ((result = standard_lookup(name,htable,mask)) == NULL) {
	    continue;
	  }
	  else {

	    if (mask == SMASK_IDENT && 
			     result->get_kind() != SYM_IDENT)
		return NULL;   /* found wrong kind of symbol */
	    if (mask == SMASK_TYPEDEF && 
			   result->get_kind() != SYM_TYPEDEF)
		return NULL;   /* found wrong kind of symbol */
	    if (mask == SMASK_INST && 
			      result->get_kind() != SYM_INST)
		return NULL;   /* found wrong kind of symbol */
	    if (mask == SMASK_INTER && 
			     result->get_kind() != SYM_INTER)
		return NULL;   /* found wrong kind of symbol */
	    if (mask == SMASK_TYPE && 
			      result->get_kind() != SYM_TYPE)
		return NULL;   /* found wrong kind of symbol */

	    /* need to set last_look - see symbol_table::add() */

	    last_look = tracer;
	    return result;
	  }
	}
	else {
	  BUG_CHECK("a SCOP_STD is missing its hash_table");
	}
      }
    case SCOP_OPS:
    case SCOP_NAMES:
      {
	/* are we even looking for such symbols ? */

	if ((mask & SMASK_NONSTD) == 0) continue;

	/* Yes. we are. */

	if ((slist = tracer->symlist) != NULL) {
	  if ((result = external_lookup(name,slist,mask)) == NULL) {
	    continue;
	  }
	  else {

	    /* need to set last_look - see symbol_table::add() */

	    last_look = tracer;
	    return result;
	  }
	}
	else continue;  /* a NULL list of names is fine */
      }
    case SCOP_UNKNOWN:
      {
	BUG_CHECK("found SCOP_UNKNOWN in lookup_driver()");
      }
    }
  }
  return NULL;   /* didn't find any such symbol */
}


symbol_element *symbol_table::standard_lookup(char       *name, 
					      hash_table *htable,
					      int         mask)

{
  SymKind         kind;
  symbol_element *result;

  if ((result=htable->lookup(name)) == NULL) 
    return NULL;
  else {

    /* we have the desired symbol, Since we're a SCOP_STD it can't
     * be a SYM_OP or a SYM_NAME */

    switch( kind = result->get_kind() ) {

    case SYM_IDENT:
    case SYM_INTER:
    case SYM_INST:
    case SYM_TYPEDEF:
      {
	/* If any C symbols are sought for, we return the first one we
	 * find, wether it's the right kind or not. lookup_driver has
	 * the job checking the mask. The reason that we can't just 
	 * return NULL if we see a SYM_IDENT when a SYM_TYPEDEF is wanted,
	 * is that doing so breaks the usual C scoping rules - the 
	 * SYM_IDENT masks the SYM_TYPEDEF - in C, you don't just keep
	 * going until you find what you want... */

	if ((mask & SMASK_C) != 0) 
	  return result;
	else {
	  
	  /* If instead, a SYM_TYPE is sought for, it will be chained to
	   * this C symbol that we've just found (if it exists) */

	  if ((mask & SYM_TYPE) != 0)
	    return (symbol_element *)(result->get_tlptr());
	  else
	    return NULL;
	}
      }
    case SYM_TYPE:
      {
	if ((mask & SMASK_TYPE) != 0) 
	  return result;
	else 
	  return NULL;
      }
    case SYM_OP:
    case SYM_NAME:
      {
        report_error("internal error",
	             "bad kind in standard_lookup for %s",
		     name);
	exit(1);
      }
    case SYM_UNKNOWN:
      {
        report_error("internal error",
	             "unknown symbol in symbol_table: %s",
		     name);
	exit(1);
      }
    }
  }
  return (0); /* won't get here, but this makes g++ happy */
}


symbol_element *symbol_table::external_lookup(char        *name, 
					      symbol_list *slist,
					      int          mask)
{
  link           *linkptr;
  SymKind         kind;
  symbol_element *result;
  
  if ((slist->search(name,linkptr)) == 0) 
    return NULL;
  else {

    result = (symbol_element *) linkptr;

    /* we have the desired symbol, Since we're not SCOP_STD it must
     * be a SYM_OP or a SYM_NAME */

    switch( kind = result->get_kind() ) {

    case SYM_IDENT:
    case SYM_INTER:
    case SYM_INST:
    case SYM_TYPEDEF:
    case SYM_TYPE:
      {
        report_error("internal error",
	             "found a C symbol in a non-C scope: %s\n",
		     name);
	exit(1);
      }
    case SYM_OP:
      {
	if ((mask & SMASK_OP) != 0)
	  return result;
	else
	  return NULL;
      }
    case SYM_NAME:
      {
	if ((mask & SMASK_NAME) != 0)
	  return result;
	else
	  return NULL;
      }
    case SYM_UNKNOWN:
        report_error("internal error",
	             "unknown symbol in symbol_table: %s",
		     result->get_name());
        exit(1);
    }
  }

  /* Added for g++ */
  return NULL;
}


void symbol_table::dump()
{
  printf("========================================================\n");
  printf(" scope_level: %d\n\n",scope_level);
  for (HashLink *tracer=contents; tracer != NULL; tracer=tracer->prev) {
    switch(tracer->kind) {
    case SCOP_STD:
      printf(" === Standard Scope ===\n\n");
      break;
    case SCOP_OPS:
      printf(" === Scope Of Operations ===\n\n");
      break;
    case SCOP_NAMES:
      printf(" === Scope Of Names ===\n\n");
      break;
    case SCOP_UNKNOWN:
      printf(" === UNKNOWN Scope ===\n\n");
      break;
    }
    if (tracer->contents == NULL) {
      printf("  < this scope has no hash_table >\n");
    }
    else {
      tracer->contents->dump();
    }
    printf("\n");
  }
  printf("========================================================\n");
}


    
