This repository has been archived by the owner on Nov 15, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlexer.c
125 lines (90 loc) · 2.22 KB
/
lexer.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
121
122
123
124
125
#include <assert.h>
#include <ctype.h>
#include <stdlib.h>
#include <string.h>
#include "buffer.h"
char* lexer_getalphanum(buffer_t* buffer)
{
// Char size is 1o => number max length = 1 * LEXEM_SIZE
// '+ 1' is the reserved place for the '\0' character (end of string)
char* string = malloc(LEXEM_SIZE + 1);
assert(string != NULL);
char* index = string;
buf_lock(buffer);
char c = buf_getchar_after_blank(buffer);
// Check if start with alphabetic character
if (!buf_eof_strict(buffer) && (isalpha(c) || c == '_'))
{
do
{
// TODO: Throws when lexel size is too long
assert(index < string + LEXEM_SIZE);
*index = c;
index++;
c = buf_getchar(buffer);
}
while (!buf_eof_strict(buffer) && (isalnum(c) || c == '_'));
}
assert(index < string + LEXEM_SIZE + 1);
*index = '\0';
buf_rollback_and_unlock(buffer, 1);
return string;
}
char* lexer_getalphanum_rollback(buffer_t* buffer)
{
char* string = malloc(LEXEM_SIZE + 1);
assert(string != NULL);
char* index = string;
buf_lock(buffer);
char c = buf_getchar_after_blank(buffer);
if (!buf_eof_strict(buffer) && (isalpha(c) || c == '_'))
{
do
{
// TODO: Throws when lexel size is too long
assert(index < string + LEXEM_SIZE);
*index = c;
index++;
c = buf_getchar(buffer);
}
while (!buf_eof_strict(buffer) && (isalnum(c) || c == '_'));
}
assert(index < string + LEXEM_SIZE + 1);
*index = '\0';
buf_rollback_and_unlock(buffer, index - string + 1);
return string;
}
long lexer_getnumber(buffer_t* buffer)
{
char* string = malloc(LEXEM_SIZE + 1);
assert(string != NULL);
char* index = string;
buf_lock(buffer);
char c = buf_getchar_after_blank(buffer);
if (!buf_eof_strict(buffer))
{
if (c == '-')
{
*index = c;
index++;
c = buf_getchar(buffer);
}
else if (!isdigit(c)) {
// TODO: Throws an error when unexpected character
}
while (!buf_eof_strict(buffer) && isdigit(c))
{
// TODO: Throws when lexel size is too long
assert(index < string + LEXEM_SIZE);
*index = c;
index++;
c = buf_getchar(buffer);
}
}
assert(index < string + LEXEM_SIZE + 1);
*index = '\0';
buf_rollback_and_unlock(buffer, 1);
long number = strtol(string, NULL, 10);
free(string);
return number;
}