Updated link in README file.
[Hack-Assembler.git] / symbol.c
blobd5f5c107d7a69aa5b60caea1e09bdb6b47e0cedc
1 #include <stdio.h>
2 #include <string.h>
3 #include <stdlib.h>
5 #include "error.h"
6 #include "parse.h"
7 #include "symbol.h"
9 struct symbol_hash symbol_hash[HASH_SIZE];
11 int ram_address = 16;
12 int rom_address = 0;
14 void inc_rom_address()
16 ++rom_address;
19 int get_rom_address()
21 return rom_address;
24 int get_ram_address()
26 return ram_address;
29 void print_hash()
31 int i = 0;
32 printf("---------- HASH TABLE ----------\n");
33 printf("Position\tAdd\tName\n");
34 while(i < HASH_SIZE)
36 if(symbol_hash[i].name[0] != '\0')
38 printf("HASH: %d\t%d\t%s\n", i, symbol_hash[i].address, symbol_hash[i].name);
40 ++i;
44 int hash(char symbol[])
46 int hash = 0;
47 int i = 0;
48 while(symbol[i] != '\0')
50 hash += symbol[i];
51 ++i;
53 hash = hash % HASH_SIZE;
54 return hash;
57 int add_entry(char symbol[], int address)
59 int hash_val;
60 hash_val = hash(symbol);
61 if(symbol_hash[hash_val].name[0] == '\0') /* no entry at this location yet */
63 strcpy(symbol_hash[hash_val].name, symbol);
64 if(address < 0)
66 symbol_hash[hash_val].address = ram_address++;
67 } else {
68 symbol_hash[hash_val].address = address;
70 return 1;
71 } else { /* hash alreay used */
73 /* compare value of symbol here with input of function */
74 /* this could be a repeat hash */
75 if(strcmp(symbol_hash[hash_val].name, symbol) == 0) { return 1; }
77 if(next_hash_space() != -1)
79 strcpy(symbol_hash[hash_val].name, symbol);
80 if(address < 0)
82 symbol_hash[hash_val].address = ram_address++;
83 } else {
84 symbol_hash[hash_val].address = address;
86 return 1;
87 } else {
88 print_hash();
89 int i = find_line_num();
90 line_notification(i);
91 exit_error(13, "Symbol table full");
94 return 0;
97 int next_hash_space()
99 int i = -1;
102 ++i;
103 } while (symbol_hash[i].name[0] != '\0' && i < HASH_SIZE);
105 if(symbol_hash[i].name[0] == '\0')
107 return i;
108 } else {
109 return -1;
113 int get_address(char symbol[])
115 int hash_val, i = 0, j = 0;
116 hash_val = hash(symbol);
117 if(symbol_hash[hash_val].name != NULL)
119 return symbol_hash[hash_val].address;
120 } else {
122 could not find hash -- loop through strings
123 for length of symbol_hash looking for a match
125 while(strcmp(symbol_hash[i].name, symbol) != 0 && j < HASH_SIZE)
127 if(i == HASH_SIZE){ i = 0; } else { ++i; }
128 ++j;
130 if(strcmp(symbol_hash[i].name, symbol) == 0)
132 return symbol_hash[i].address;
135 return -1;