This repository has been archived by the owner on Sep 18, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2
/
symbol.c
113 lines (105 loc) · 2.36 KB
/
symbol.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
/*
* File: symbol.c
* Contains functions to handle the symbol table
*/
#include "lc3asm.h"
/*
* The symbol table is implemented as a linked list, with each node as the "symbol" structure
*/
/*
*
* name: append_symtable
* Add a new symbol entry into the symbol table (the linked list).
* No duplicate is inserted; the function firstpass() generates an error if a duplicate label is found
*
*/
void append_symtable(symbol **symtable, char *label, int addr)
{
if (*symtable == NULL)
{
*symtable = (symbol *)malloc(sizeof(symbol));
if (*symtable == NULL)
{
return;
}
strcpy((*symtable)->label, label);
(*symtable)->addr = addr;
(*symtable)->next = NULL;
}
else
{
append_symtable(&((*symtable)->next), label, addr);
}
}
/*
*
* name: search_table
* Search the table for a given label and return the associated address
*
*/
int search_table(symbol *symtable, char *label)
{
if (symtable == NULL)
{
return -1;
}
if (strcmp(symtable->label, label) == 0)
{
return symtable->addr;
}
else
{
return search_table(symtable->next, label);
}
}
/*
*
* name: write_symfile
* Writes the symbol table to the .sym output file pointed to by a member of the files structure
*
*/
void write_symfile(symbol *symtable, files *f)
{
fprintf(f->symfile, "-------------------------------------------\n");
fprintf(f->symfile, " SYMBOL | ADDRESS \n");
fprintf(f->symfile, "-------------------------------------------\n");
symbol *n;
n = symtable;
while (n != NULL)
{
fprintf(f->symfile, "%-21s x%X\n", n->label, n->addr);
n = n->next;
}
fprintf(f->symfile, "-------------------------------------------\n");
}
/*
*
* name: destroy_symtable
* Frees memory associated with the symbol table linked list pointed to by "symtable"
*
*/
void destroy_symtable(symbol *symtable)
{
if (symtable == NULL)
{
return;
}
symbol *prev, *curr, *tmp;
prev = curr = symtable;
while (curr->next != NULL)
{
prev = curr;
curr = curr->next;
}
tmp = curr;
free(curr);
if (tmp == symtable)
{
symtable = NULL;
}
else
{
prev->next = NULL;
destroy_symtable(symtable);
}
}