write LEX file
This commit is contained in:
@@ -1,43 +1,79 @@
|
||||
# ------------------------------------------------------------
|
||||
# triplalex.py
|
||||
#
|
||||
# tokenizer for the TRIPLA parser
|
||||
# Tokenizer for the TRIPLA parser
|
||||
# ------------------------------------------------------------
|
||||
|
||||
import ply.lex as lex
|
||||
|
||||
|
||||
reserved = {
|
||||
'while' : 'WHILE',
|
||||
'do' : 'DO',
|
||||
'let': 'LET',
|
||||
'in': 'IN',
|
||||
'if': 'IF',
|
||||
'then': 'THEN',
|
||||
'else': 'ELSE',
|
||||
'while': 'WHILE',
|
||||
'do': 'DO',
|
||||
'true': 'TRUE',
|
||||
'false': 'FALSE'
|
||||
}
|
||||
|
||||
# List of token names. This is always required
|
||||
tokens = [
|
||||
'ID',
|
||||
'CONST',
|
||||
'LBRACE', 'RBRACE'
|
||||
]+list(reserved.values())
|
||||
'AOP',
|
||||
'RELOP',
|
||||
'LOP',
|
||||
'ASSIGN',
|
||||
'LPAREN', 'RPAREN',
|
||||
'LBRACE', 'RBRACE',
|
||||
'COMMA',
|
||||
'SEMICOLON',
|
||||
] + list(reserved.values())
|
||||
|
||||
# Regular expression rules for simple tokens
|
||||
t_LBRACE = r'\{'
|
||||
t_RBRACE = r'\}'
|
||||
t_WHILE = r'while'
|
||||
t_DO = r'do'
|
||||
# Simple tokens
|
||||
t_LPAREN = r'\('
|
||||
t_RPAREN = r'\)'
|
||||
t_LBRACE = r'\{'
|
||||
t_RBRACE = r'\}'
|
||||
t_COMMA = r','
|
||||
t_SEMICOLON = r';'
|
||||
t_ASSIGN = r'='
|
||||
|
||||
# A regular expression rule with some action code
|
||||
# Arithmetic operators
|
||||
t_AOP = r'\+|\-|\*|/'
|
||||
|
||||
# Comparison operators
|
||||
t_RELOP = r'<=|>=|==|!=|<|>'
|
||||
|
||||
# Logical operators
|
||||
t_LOP = r'\|\||&&|==|!='
|
||||
|
||||
# IDs
|
||||
def t_ID(t):
|
||||
r'[A-Za-z_][A-Za-z0-9_]*'
|
||||
t.type = reserved.get(t.value, 'ID')
|
||||
return t
|
||||
|
||||
# Constants
|
||||
def t_CONST(t):
|
||||
r'\d+'
|
||||
r'0|[1-9][0-9]*'
|
||||
t.value = int(t.value)
|
||||
return t
|
||||
|
||||
# Define a rule so we can track line numbers
|
||||
# Linebreaks
|
||||
def t_newline(t):
|
||||
r'\n+'
|
||||
t.lexer.lineno += len(t.value)
|
||||
|
||||
# A string containing ignored characters (spaces and tabs)
|
||||
# Ignore whitespace
|
||||
t_ignore = ' \t'
|
||||
|
||||
# Error handling rule
|
||||
# Comments
|
||||
def t_comment(t):
|
||||
r'//.*'
|
||||
pass
|
||||
|
||||
# Error handling
|
||||
def t_error(t):
|
||||
print("Illegal character '%s'" % t.value[0])
|
||||
t.lexer.skip(1)
|
||||
|
||||
Reference in New Issue
Block a user