-
Notifications
You must be signed in to change notification settings - Fork 0
/
token.c
48 lines (42 loc) · 1.28 KB
/
token.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
#include "token.h"
#include "operator/unary_operator.h"
#include "operator/binary_operator.h"
#include "my_libc/_string.h"
#include <stdlib.h>
static bool is_operator(Token* self);
static int apply_as_operator(Token* self, OperandStack* operands, int* error);
static void delete(Token* self);
Token* new_token(char* value)
{
Token* self = malloc(sizeof (Token));
char* _value = malloc(_strlen(value) + 1);
_strcpy(_value, value);
self->value = _value;
self->next = NULL;
self->isOperator = &is_operator;
self->applyAsOperator = &apply_as_operator;
self->delete = &delete;
return self;
}
bool is_operator(Token* self)
{
return char_is_operator(self->value[0]);
}
int apply_as_operator(Token* self, OperandStack* operands, int* error)
{
Operator* operator = get_operator_from_sign(self->value[0]);
if (operator->isUnary) {
UnaryOperator* unary_operator = (UnaryOperator*) operator;
return unary_operator->apply(operands->pop(operands));
} else {
BinaryOperator* binary_operator = (BinaryOperator*) operator;
int right = operands->pop(operands);
int left = operands->pop(operands);
return binary_operator->apply(left, right, error);
}
}
void delete(Token* self)
{
free(self->value);
free(self);
}