-
Notifications
You must be signed in to change notification settings - Fork 11
/
symstack.c
120 lines (88 loc) · 2.02 KB
/
symstack.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
114
115
116
117
118
119
120
/**
* Project: Implementace překladače imperativního jazyka IFJ17.
*
* @brief Stack of symbols implementation.
*
* @author Timotej Halás <[email protected]>
* @author Dominik Harmim <[email protected]>
*/
#include <stdlib.h>
#include "symstack.h"
void symbol_stack_init(Symbol_stack* stack)
{
stack->top = NULL;
}
bool symbol_stack_push(Symbol_stack* stack, Prec_table_symbol_enum symbol, Data_type type)
{
Symbol_stack_item* new_item = (Symbol_stack_item*)malloc(sizeof(Symbol_stack_item));
if (new_item == NULL)
return false;
new_item->symbol = symbol;
new_item->data_type = type;
new_item->next = stack->top;
stack->top = new_item;
return true;
}
bool symbol_stack_pop(Symbol_stack* stack)
{
if (stack->top != NULL)
{
Symbol_stack_item* tmp = stack->top;
stack->top = tmp->next;
free(tmp);
return true;
}
return false;
}
void symbol_stack_pop_count(Symbol_stack* stack, int count)
{
for (int i = 0; i < count; i++)
{
symbol_stack_pop(stack);
}
}
Symbol_stack_item* symbol_stack_top_terminal(Symbol_stack* stack)
{
for (Symbol_stack_item* tmp = stack->top; tmp != NULL; tmp = tmp->next)
{
if (tmp->symbol < STOP)
return tmp;
}
return NULL;
}
bool symbol_stack_insert_after_top_terminal(Symbol_stack* stack, Prec_table_symbol_enum symbol, Data_type type)
{
Symbol_stack_item* prev = NULL;
for (Symbol_stack_item* tmp = stack->top; tmp != NULL; tmp = tmp->next)
{
if (tmp->symbol < STOP)
{
Symbol_stack_item* new_item = (Symbol_stack_item*)malloc(sizeof(Symbol_stack_item));
if (new_item == NULL)
return false;
new_item->symbol = symbol;
new_item->data_type = type;
if (prev == NULL)
{
new_item->next = stack->top;
stack->top = new_item;
}
else
{
new_item->next = prev->next;
prev->next = new_item;
}
return true;
}
prev = tmp;
}
return false;
}
Symbol_stack_item* symbol_stack_top(Symbol_stack* stack)
{
return stack->top;
}
void symbol_stack_free(Symbol_stack* stack)
{
while (symbol_stack_pop(stack));
}