arith a bit

This commit is contained in:
Christoph J. Scherr 2023-12-17 18:50:39 +01:00
parent 1c4377b4cb
commit d0e98e54ce
2 changed files with 83 additions and 0 deletions

3
.gitignore vendored Normal file
View File

@ -0,0 +1,3 @@
src/__pycache__
src/parser.out
src/parsetab.py

80
src/arithmetic.py Normal file
View File

@ -0,0 +1,80 @@
import ply.yacc
import ply.lex
# scanner
tokens = [
'NUMBER',
'EXP'
]
literals = ['+', '*', '(', ')']
t_ignore = '\n\t '
def t_error(t):
print(f"error: '{t}'")
def t_NUMBER(t):
r'0|[1-9][0-9]*'
t.value = int(t.value)
return t
def t_EXP(t):
r'\*\*'
pass
lexer = ply.lex.lex()
# parser
start = 'start'
def p_start(p):
"start : expr"
print(p[1])
def p_expr_sum(p):
"expr : expr '+' prod"
p[0] = p[1] + p[3]
return p
def p_expr_prod(p):
"expr : prod"
p[0] = p[1]
return p
def p_prod_prod(p):
"prod : prod '*' pow"
p[0] = p[1] * p[3]
return p
def p_prod_pow(p):
"prod : pow"
p[0] = p[1]
return p
def p_pow_exp(p):
"pow : fac EXP pow"
p[0] = p[1] ** p[3]
return p
def p_pow_fac(p):
"pow : fac"
p[0] = p[1]
return p
def p_fac_inner(p):
"fac : '(' expr ')'"
p[0] = p[2]
return p
def p_fac_num(p):
"fac : NUMBER"
p[0] = int(p[1])
return p
parser = ply.yacc.yacc()
while True:
s = input('calc> ')
ply.yacc.parse(s)
if s == '':
break