-
Notifications
You must be signed in to change notification settings - Fork 0
/
scope.c
57 lines (53 loc) · 1.42 KB
/
scope.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
#include "scope.h"
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
Scope* createScope()
{
Scope* s = malloc(sizeof(Scope));
//4 bytes for the old stack pointer (0)
//4 bytes for the return address (-4)
s->scope_size = 8;
s->argument_size = 0;
s->argument_registers = 0;
s->hashmap = create_hashmap();
s->parent = NULL;
return s;
}
void addArgument(Scope* s, char* varName, VariableLocation varLocation, int registerNumber)
{
if(getVariableScope(s, varName) != NULL)
return;
Variable* v = malloc(sizeof(Variable));
v->varName = varName;
v->location = varLocation;
if(v->location == stack)
{
v->position.stackOffset = s->argument_size;
s->argument_size += 4;
}
else
{
v->position.registerNumber = registerNumber;
s->argument_registers++;
}
addKeyValue(s->hashmap, varName, v);
}
void addLocalVariable(Scope* s, char* varName)
{
if(getVariableScope(s, varName) != NULL)
return;
s->scope_size += 4;
Variable* v = malloc(sizeof(Variable));
v->varName = varName;
v->location = stack;
v->position.stackOffset = -s->scope_size;
addKeyValue(s->hashmap, varName, v);
}
Variable* getVariableScope(Scope* s, char* varName)
{
Variable* v = (Variable*)getKeyValue(s->hashmap, varName);
if(v == NULL && s->parent != NULL)
return getVariableScope(s->parent, varName);
return v;
}