/* MasC interpreter/compiler
   (Master Assembly Script Container)
   written by Jared Bruni
   
   After reading Writing Compilers and Interpreters A approach using C++ by Ronald Mak
   and the Dragon Book
   code completly re-written but using concepts teached in this book
*/
// Symbol Table implementation file

#include "symboltable.h"


// initalize the symbol table
void initTable(struct symTbl *stable)
{
	stable->root.next = 0;
	stable->node_count = 0; 
	stable->sym_tab = 0;
	stable->root.str = (char*) malloc (sizeof(char) * strlen("mas") + 1);
	strncpy(stable->root.str, "mas", strlen("mas"));
	stable->root.str[strlen("mas")] = 0;
}
// enter string to the symbol table
struct symNode *Enter(struct symTbl *stable, struct symNode *root, const char *cstr)
{
	struct symNode *head = root;
	while(head != 0)
	{
		if(head->str != 0)
		if(strcmp(head->str, cstr) == 0) {
			return head;
		}
		if(head->next != 0)                
			head = head->next;
		else {

			head->next = (struct symNode*) malloc ( sizeof(struct symNode) );
			head->next->str = (char*) malloc ( sizeof(char) * strlen(cstr) + 1);
			strncpy(head->next->str, cstr,strlen(cstr));
			head->next->str[strlen(cstr)] = 0;
			head->next->next = 0;
			head->next->value = 0;
			return head->next;
		}

	}
	stable->tail = head;
	return head;
}
// search for string in the symbol table
struct symNode *Search(struct symNode *root, const char *str)
{ 
	struct symNode *head = root;
	while(head != 0)
	{
		if(head->str != 0)
			if(strcmp(head->str,str) == 0) 
				return head;
			else
				head = head->next;

	} 

	return head;
}

// print out the symbol table to stdout
void symNode_Print(struct symNode *node)
{
	struct symNode *ptr_node = node;
	while(node != 0) {

		printf("[%s]",node->str);
		if(node->vtype == tVAR_LABEL)
			printf(" label to token [%d]\n", node->line);
		else
			printf("\n");
		node = node->next;

	}
}
// 1 1 1
