Debian Codegraph @

samples/calc.py

raw
1 #!/usr/bin/env python3
2 # -*- coding: utf-8 -*-
3
4 """
5 Simple four operations calculator.
6 """
7
8 import operator
9
10 from ptk.lexer import ReLexer, token
11 from ptk.parser import LRParser, left_assoc, production, ParseError
12
13
14 @left_assoc('+', '-')
15 @left_assoc('*', '/')
16 class SimpleCalc(LRParser, ReLexer):
17 def on_start_symbol(self, result):
18 print('== Result:', result)
19
20 # Lexer
21 def ignore(self, char):
22 return char in [' ', '\t']
23
24 @token(r'[1-9][0-9]*')
25 def number(self, tok):
26 tok.value = int(tok.value)
27
28 # Parser
29
30 @production('E -> "-" E<value>', priority='*')
31 def minus(self, value):
32 print('== Neg: - %d' % value)
33 return -value
34
35 @production('E -> "(" E<value> ")"')
36 def paren(self, value):
37 return value
38
39 @production('E -> number<number>')
40 def litteral(self, number):
41 return number
42
43 @production('E -> E<left> "+"<op> E<right>')
44 @production('E -> E<left> "-"<op> E<right>')
45 @production('E -> E<left> "*"<op> E<right>')
46 @production('E -> E<left> "/"<op> E<right>')
47 def binaryop(self, left, op, right):
48 print('Binary operation: %s %s %s' % (left, op, right))
49 return {
50 '+': operator.add,
51 '-': operator.sub,
52 '*': operator.mul,
53 '/': operator.floordiv
54 }[op](left, right)
55
56
57 if __name__ == '__main__':
58 import logging
59 logging.basicConfig(level=logging.WARNING, format='%(asctime)-15s %(levelname)-8s %(name)-15s %(message)s')
60
61 print('Enter an arithmetic expression.')
62
63 parser = SimpleCalc()
64 while True:
65 try:
66 line = input('> ')
67 except (KeyboardInterrupt, EOFError):
68 print()
69 break
70 try:
71 parser.parse(line)
72 except ParseError as exc:
73 print('Parse error: %s' % exc)
74 print('Expected %s' % exc.expecting())