-
Notifications
You must be signed in to change notification settings - Fork 0
/
common.py
63 lines (53 loc) · 1.62 KB
/
common.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
"""
This file contains important information for the calculator.
"""
from collections import namedtuple, OrderedDict
from enum import Enum
Token = namedtuple('Token', ('name', 'value'))
RuleMatch = namedtuple('RuleMatch', ('name', 'matched'))
token_map = OrderedDict((
(r'\d+(?:\.\d+)?', 'NUM'),
(r'sqrt', 'OPR'),
(r'exp', 'OPR'),
(r'[a-zA-Z_]+', 'IDT'),
(r'=', 'EQL'),
(r'\+', 'ADD'),
(r'-', 'ADD'),
(r'\*\*', 'POW'),
(r'\*', 'MUL'),
(r'\/', 'MUL'),
(r'%', 'MUL'),
(r'\^', 'POW'),
(r'\(', 'LPA'),
(r'\)', 'RPA'),
(r'\[', 'LBR'),
(r'\]', 'RBR'),
(r'\,', 'CMA'),
(r'\|', 'PPE')
))
remove = ('EQL', 'LPA', 'RPA', 'LBR', 'RBR', 'CMA', 'PPE')
rules_map = OrderedDict((
('idt', ('IDT EQL add', 'mat')),
('mat', ('LBR mbd RBR', 'add')),
('mbd', ('mrw PPE mbd', 'mrw', 'add')),
('mrw', ('add CMA mrw', 'add')),
('add', ('mul ADD add', 'mui', 'mul')),
('mui', ('pow mul',)),
('mul', ('pow MUL mul', 'pow')),
('pow', ('opr POW pow', 'opr')),
('opr', ('OPR LPA add RPA', 'neg')),
('neg', ('ADD num', 'ADD opr', 'num')),
('num', ('NUM', 'IDT', 'LPA add RPA')),
))
left_assoc = {
'ADD': 'add',
'MUL': 'mul',
}
class Type(Enum):
Number = 0
Matrix = 1
Value = namedtuple('Value', ('type', 'value'))
value_map = {
'NUM': Type.Number,
'MAT': Type.Matrix
}