This repository has been archived by the owner on Jul 27, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
SymbolTable.c
92 lines (85 loc) · 1.81 KB
/
SymbolTable.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
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "SymbolTable.h"
SymTab* mkSymTab() {
SymTab* l = (SymTab*) malloc(sizeof(SymTab));
l->head = 0;
l->length = 0;
l->last = 0;
l->scopeLevel = 0;
return l;
}
Variable* mkVariable(int type, double data, char* name, int scopeLevel) {
Variable* v = (Variable*) malloc(sizeof(Variable));
v->type = type;
v->data = data;
v->name = name;
v->scopeLevel = scopeLevel;
return v;
}
Node* mkNode(Node* prev, Variable* data, Node* next) {
Node* n = (Node*) malloc(sizeof(Node));
n->prev = prev;
n->data = data;
n->next = next;
return n;
}
void storeVar(SymTab* l, Variable* data) {
//printf("STORING %s: %g\n", data->name, data->data);
Node* n = mkNode(0, data, 0);
if(l->length == 0) {
l->head = n;
l->last = n;
}
else {
Node* tmp = l->last;
tmp->next = n;
l->last = n;
n->prev = tmp;
}
l->length++;
}
Variable* lookupVariable(SymTab* l, char* varName) {
Node* n = l->last;
Node* target = 0;
while(n != 0) {
if(strcmp(n->data->name, varName) == 0) {
return n->data;
}
n = n->prev;
}
return NULL;
}
void enterScope(SymTab* s) {
s->scopeLevel+=1;
}
void leaveScope(SymTab* s) {
Node* n = s->head;
while(n != 0 && n->data->scopeLevel < s->scopeLevel) {
n = n->next;
}
n->prev->next = 0;
s->last = n->prev;
while(n != 0) {
Node* tmp = n;
n = n->next;
free(tmp);
}
s->scopeLevel--;
}
/*
int main() {
printf("Testing Symbol Table....\n");
int n = 5;
int a = 6;
int x = 20;
SymTab* s = mkSymTab();
storeVar(s, mkVariable(1, &n, "test", s->scopeLevel));
enterScope(s);
storeVar(s, mkVariable(1, &a, "test", s->scopeLevel));
storeVar(s, mkVariable(1, &x, "test2", s->scopeLevel));
printf("%d\n", *((int *) (lookupVariable(s, "test")->data)));
printf("%d\n", *((int *) (lookupVariable(s, "test2")->data)));
leaveScope(s);
}*/