-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathtable.h
More file actions
106 lines (87 loc) · 2.67 KB
/
table.h
File metadata and controls
106 lines (87 loc) · 2.67 KB
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
#ifndef TABLE_H
#define TABLE_H
#include <stdbool.h>
#define MAX_SYMBOLS 100
struct symbol {
char* name;
int value;
char* str_value;
bool is_string;
};
struct symbol* find_symbol(const char* name);
void declare_symbol_with_number(const char* name, int value);
void declare_symbol_with_string(const char* name, const char* value);
void declare_symbol_empty(const char* name);
void set_symbol_number(const char* name, int value);
void set_symbol_string(const char* name, const char* value);
void print_table(void);
#endif
// --- Implementation ---
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
static struct symbol symbol_table[MAX_SYMBOLS];
static int symbol_count = 0;
struct symbol* find_symbol(const char* name) {
for (int i = 0; i < symbol_count; ++i) {
if (strcmp(symbol_table[i].name, name) == 0)
return &symbol_table[i];
}
return NULL;
}
static struct symbol* create_symbol(const char* name) {
if (find_symbol(name)) {
fprintf(stderr, "Multiple declaration of variable %s\n", name);
exit(1);
}
if (symbol_count >= MAX_SYMBOLS) {
fprintf(stderr, "Symbol table full\n");
exit(1);
}
symbol_table[symbol_count].name = strdup(name);
symbol_table[symbol_count].value = 0;
symbol_table[symbol_count].str_value = NULL;
symbol_table[symbol_count].is_string = false;
return &symbol_table[symbol_count++];
}
void declare_symbol_with_number(const char* name, int value) {
struct symbol* s = create_symbol(name);
s->value = value;
s->is_string = false;
}
void declare_symbol_with_string(const char* name, const char* value) {
struct symbol* s = create_symbol(name);
s->str_value = strdup(value);
s->is_string = true;
}
void declare_symbol_empty(const char* name) {
create_symbol(name);
}
void set_symbol_number(const char* name, int value) {
struct symbol* s = find_symbol(name);
if (!s) {
s = create_symbol(name);
}
s->value = value;
s->is_string = false;
}
void set_symbol_string(const char* name, const char* value) {
struct symbol* s = find_symbol(name);
if (!s) {
s = create_symbol(name);
}
if (s->str_value) free(s->str_value);
s->str_value = strdup(value);
s->is_string = true;
}
void print_table(void) {
printf("---- Symbol Table ----\n");
for (int i = 0; i < symbol_count; i++) {
if (symbol_table[i].is_string && symbol_table[i].str_value) {
printf("%s = \"%s\"\n", symbol_table[i].name, symbol_table[i].str_value);
} else {
printf("%s = %d\n", symbol_table[i].name, symbol_table[i].value);
}
}
printf("-----------------------\n");
}