-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtoken.c
91 lines (72 loc) · 1.54 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
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
#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "list.h"
#include "sesh.h"
#include "token.h"
struct Token {
enum TokenType type;
char *value;
};
/* Write all tokens in list to stdout. */
void Token_print(List_T list)
{
int i;
int length;
Token_T token;
assert(list != NULL);
length = List_get_length(list);
for (i = 0; i < length; i++) {
token = List_get(list, i);
if (token->type == TOKEN_REGULAR)
printf("Token: %s (ordinary)\n", token->value);
else
printf("Token: %s (special)\n", token->value);
}
}
/* Free all of the tokens in list, and the list itself. */
void Token_free(List_T list)
{
int i;
int length;
Token_T token;
assert(list != NULL);
length = List_get_length(list);
for (i = 0; i < length; i++) {
token = List_get(list, i);
free(token->value);
free(token);
}
List_free(list);
}
/* Create and return a new token. */
Token_T Token_new(enum TokenType type, char *value) {
Token_T token;
assert(value != NULL);
token = (Token_T) malloc(sizeof(struct Token));
if (token == NULL) {
perror(program_name);
exit(EXIT_FAILURE);
}
token->type = type;
token->value = (char*) malloc(strlen(value) + 1);
if (token->value == NULL) {
perror(program_name);
exit(EXIT_FAILURE);
}
strcpy(token->value, value);
return token;
}
/* Return token's type. */
enum TokenType Token_get_type(Token_T token)
{
assert(token != NULL);
return token->type;
}
/* Return token's value. */
char *Token_get_value(Token_T token)
{
assert(token != NULL);
return token->value;
}