-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathsymtab.c
executable file
·88 lines (73 loc) · 1.73 KB
/
symtab.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
#include "symtab.h"
#include "list.h"
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
static struct symnode* make_symnode(char* name, AST* node)
{
struct symnode* temp = (struct symnode*)malloc(sizeof(struct symnode*));
temp->name = name;
temp->node = node;
return temp;
}
static struct symtab* make_symtab()
{
struct symtab* temp = (struct symtab*)malloc(sizeof(struct symtab*));
temp->prevscope = NULL;
temp->head = NULL;
temp->tail = NULL;
return temp;
}
struct symtab* enterscope(struct symtab* cur)
{
struct symtab* temp = make_symtab();
temp->prevscope = cur;
return temp;
}
struct symtab* exitscope(struct symtab* cur)
{
if (cur != NULL)
cur = cur->prevscope;
return cur;
}
struct AST* lookup(struct symtab* cur, char* name)
{
while (cur != NULL)
{
struct AST* var = probe(cur, name);
if (var != NULL)
return var;
cur = cur->prevscope;
}
return NULL;
}
struct AST* probe(struct symtab* cur, char* name)
{
for (struct symnode* tmp = cur->head; tmp != NULL; tmp = tmp->next)
{
if (strcmp(tmp->name, name) == 0)
return tmp->node;
}
return NULL;
}
struct symtab* add_symbol(struct symtab* cur, char* name, struct AST* ast)
{
/*struct AST* var = probe(cur, name);
if (var != NULL)
{
fprintf(stderr, "%s\n", "error: predefined variable in the same scope");
return cur;
}*/
struct symnode* temp= make_symnode(name, ast);
if(cur->tail == NULL || cur->head == NULL)
{
cur->head = cur->tail = temp;
}
else
{
cur->tail->next = temp;
temp->prev = cur->tail;
cur->tail = temp;
}
return cur;
}