2024-03-26 19:02:54 +00:00
|
|
|
import sly
|
|
|
|
|
|
|
|
class Lexer(sly.Lexer):
|
|
|
|
# define token types
|
|
|
|
tokens = {
|
|
|
|
# Keyworkds
|
|
|
|
BREAK, CASE, DEFAULT, ELSE, FLOAT,
|
|
|
|
IF, INPUT, INT, OUTPUT, SWITCH, WHILE,
|
|
|
|
# Operators
|
|
|
|
RELOP, ADDOP, MULOP, OR, AND, NOT, CAST,
|
|
|
|
# misc
|
|
|
|
ID, NUM
|
|
|
|
}
|
|
|
|
ignore = ' \t'
|
|
|
|
literals = { '(', ')', '{', '}', ',', ':', ';', '=' }
|
|
|
|
|
|
|
|
# define each token
|
2024-03-27 15:44:35 +00:00
|
|
|
RELOP = r'(==|!=|<=|>=|>|<)'
|
2024-03-26 19:02:54 +00:00
|
|
|
ADDOP = r'(\+|-)'
|
|
|
|
MULOP = r'(\*|/)'
|
2024-03-27 15:44:35 +00:00
|
|
|
OR = r'\|\|'
|
|
|
|
AND = r'&&'
|
|
|
|
NOT = r'!'
|
2024-03-26 19:02:54 +00:00
|
|
|
CAST = r'static_cast<(int|float)>'
|
|
|
|
|
|
|
|
ID = r'[a-zA-Z][a-zA-Z0-9]*'
|
|
|
|
NUM = r'[0-9]+(\.[0-9]*)?'
|
|
|
|
|
|
|
|
# define keywords on ID
|
|
|
|
ID['break'] = BREAK
|
|
|
|
ID['case'] = CASE
|
|
|
|
ID['default'] = DEFAULT
|
|
|
|
ID['else'] = ELSE
|
|
|
|
ID['float'] = FLOAT
|
|
|
|
ID['if'] = IF
|
|
|
|
ID['input'] = INPUT
|
|
|
|
ID['int'] = INT
|
|
|
|
ID['output'] = OUTPUT
|
|
|
|
ID['switch'] = SWITCH
|
|
|
|
ID['while'] = WHILE
|
|
|
|
|
|
|
|
@_(r'\n+')
|
|
|
|
def newline(self, t):
|
|
|
|
self.lineno += t.value.count('\n')
|
|
|
|
|
|
|
|
def error(self, t):
|
2024-04-04 06:56:28 +00:00
|
|
|
print(f"Error at line {self.lineno}: Unexpected character {t.value[0]}")
|
2024-03-26 19:02:54 +00:00
|
|
|
self.index += 1
|