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
|
/* PIA - Lenguajes Modernos de Programación
* FACULTAD DE CIENCIAS FÍSICO MATEMÁTICAS
* Luis Sebastián Martínez Vega - LCC */
#include <string>
#include <cctype>
#include "include/lexer.hpp"
#include "include/exceptions.hpp"
using std::string, std::isalpha, std::isdigit;
Lexer::Lexer(string text): current_token(nil, {}){
setText(text);
}
void Lexer::setText(string text){
this->text = text;
// Inicializamos el lexer.
current_token = nextToken();
var_name = '\0';
}
Token Lexer::getCurrentToken(){
return current_token;
}
bool Lexer::matchFunction(string function_name){
string name = text.substr(current_char, 2);
bool matched = name == function_name;
// Si hubo una coincidencia movemos el puntero.
if(matched)
current_char += 3;
return matched;
}
string Lexer::createNumber(){
string number;
while(isdigit(text[current_char]) && current_char < text.length())
{
number += text[current_char];
++current_char;
}
return number;
}
Token Lexer::match(){
// Probamos las funciones.
if(current_char + 2 < text.length())
{
if(matchFunction("sin"))
return Token(function, "sin");
else if(matchFunction("cos"))
return Token(function, "cos");
else if(matchFunction("tan"))
return Token(function, "tan");
else if(matchFunction("csc"))
return Token(function, "csc");
else if(matchFunction("sec"))
return Token(function, "ctg");
}
if(isdigit(text[current_char]))
return Token(number, createNumber());
if(isalpha(text[current_char]))
{
/* Si es la primera vez que se lee un token variable o
si la variable leída es igual a la anteriormente leída. */
if(var_name == '\0' || var_name == text[current_char])
return Token(variable, string(1, var_name));
// Error, se introdujo una expresión con dos o más variables.
throw LexerException("Encontrada más de una variable.");
}
/* El token actual no es ni una variable, número o función.
Ahora a probar operadores. */
switch(text[current_char])
{
case '+':
++current_char;
return Token(sum, {});
case '-':
++current_char;
return Token(substraction, {});
case '*':
++current_char;
return Token(multiplication, {});
case '/':
++current_char;
return Token(division, {});
case '^':
++current_char;
return Token(power, {});
case '(':
++current_char;
return Token(left_parens, {});
case ')':
++current_char;
return Token(right_parens, {});
default:
throw LexerException("Carácter inválido.");
}
}
Token Lexer::nextToken(){
current_token = match();
return current_token;
}
|