$ pip install ply
lex.py
import ply.lex as lex
tokens = (
# Literals
'ID',
# Function
'PUT', 'EXIT',
)
# Identifiers at var
t_ID = r'(?!put|exit)[A-Za-z_][A-Za-z0-9_]*'
# Function
t_PUT = r'put'
t_EXIT = r'exit'
# space is ignore
# space and tab is ignore
t_ignore = ' \t'
# comment
t_ignore_COMMENT = r'\#.*'
# error handling
def t_error(t):
print("Illegal characters'%s'" % t.value[0])
t.lexer.skip(1)
#
lex.lex(debug=0)
The code created below is shown
yacc.py
import ply.yacc as yacc
from lex import tokens
import sys
names = {}
# var (id)
def p_expr_id(p):
'expr : ID'
try:
p[0] = names[p[1]]
except LookupError:
print('Undefine var name %s' %p)
p[0] = 0
# exit function
def p_exit(p):
'expr : EXIT'
print('See You!')
sys.exit()
# empty
def p_empty(p):
'empty :'
pass
# syntax error
def p_error(p):
print ('Syntax error in input %s' %p)
parser = yacc.yacc()
# Debug
def parse(data, debug=0):
return yacc.parse(data, debug=debug)
if __name__ == '__main__':
while True:
try:
s = input('>>> ')
except EOFError:
break
if not s:
continue
result = parser.parse(s)
print (result)
Actually, I defined a variable, but I can't do anything at the moment All you can do is try the exit function
Execution
$ python yacc.py
>>> exit
See You!
$
Somehow it became a screen like that and I got out with exit The explanation has become rough towards the end
I made an original language "PPAPScript" that imaged PPAP (Penpainappoappopen) with Python, [ryo-ma](http: / /qiita.com/ryo-ma).
Recommended Posts