-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathstack.c
More file actions
116 lines (99 loc) · 2.29 KB
/
Copy pathstack.c
File metadata and controls
116 lines (99 loc) · 2.29 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
107
108
109
110
111
112
113
114
/**
* School project to subject IFJ (Formal Languages and Compilers)
* Compiler implementation of imperative language IFJ18
*
* Module for evaluating expressions and conditions
*
* Author: Ján Vavro
* Login: xvavro05
*/
#include "stack.h"
#include "lex.h"
/**
* Initialisation of stack
* @param stack
*/
void stack_init(t_stack *stack) {
stack->top = NULL;
}
/**
* Push item to stack
* @param stack
* @param symbol item to be pushed
*/
void push(t_stack *stack, int symbol) {
t_stack_item *toBePushed = malloc(sizeof(t_stack_item));
if (toBePushed == NULL) {
return;
}
toBePushed->next = stack->top;
toBePushed->symbol = symbol;
stack->top = toBePushed;
}
/**
* Pop item from the stack
* @param stack
*/
void pop(t_stack *stack) {
if (stack->top != NULL) {
t_stack_item *tmp = stack->top;
stack->top = stack->top->next;
free(tmp);
}
}
/**
* Perform multipop
* @param stack
* @param count count of items to be popped
*/
void multi_pop(t_stack *stack, int count) {
for (int i = count; i > 0; --i) {
pop(stack);
}
}
/**
* @param token
* @return true if token is terminal, false if not
*/
bool is_terminal(int token) {
return (token < MAXTOKEN);
}
/**
* @param stack
* @return first terminal from the stack
*/
t_stack_item *top_term(t_stack *stack) {
t_stack_item *tmp = stack->top;
while (tmp) {
if (is_terminal(tmp->symbol)) {
return tmp;
} else {
tmp = tmp->next;
}
}
return NULL;
}
/**
* Insert item after first terminal in the stack
* @param stack
* @param symbol item to be inserted to the stack
*/
void insert_after_first_terminal(t_stack *stack, int symbol) {
t_stack_item *prev = NULL, *tmp = stack->top;
for (; tmp != NULL; tmp = tmp->next) {
if (is_terminal(tmp->symbol)) {
t_stack_item *toBeInserted = malloc(sizeof(t_stack_item));
if (toBeInserted == NULL) return;
toBeInserted->symbol = symbol;
toBeInserted->next = tmp;
if (prev) {
prev->next = toBeInserted;
} else {
stack->top = toBeInserted;
}
return;
} else { //symbol is not terminal
prev = tmp;
}
}
}