File size: 11,012 Bytes
53ce2f5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
import re

class FormulaError(Exception):
    pass

class FormulaSyntaxError(Exception):
    pass

COORD_RE = re.compile(r'^([A-Za-z]+)([0-9]+)$')

def normalize_coord(coord):
    if not isinstance(coord, str):
        raise FormulaSyntaxError('invalid coord')
    m = COORD_RE.match(coord.strip())
    if not m:
        raise FormulaSyntaxError('invalid coord: ' + repr(coord))
    letters = m.group(1).upper()
    row = int(m.group(2))
    if row < 1 or not letters:
        raise FormulaSyntaxError('invalid coord: ' + repr(coord))
    return f'{letters}{row}'

def _tokens(expr):
    if not isinstance(expr, str):
        raise FormulaSyntaxError('expr must be string')
    i = 0
    n = len(expr)
    while i < n:
        c = expr[i]
        if c in ' \t\r\n':
            i += 1
            continue
        if c.isdigit() or (c == '.' and i + 1 < n and expr[i+1].isdigit()):
            j = i
            while j < n and (expr[j].isdigit() or expr[j] == '.'):
                j += 1
            s = expr[i:j]
            if s.count('.') > 1:
                raise FormulaSyntaxError('invalid number: ' + s)
            try:
                float(s)
            except ValueError:
                raise FormulaSyntaxError('invalid number: ' + s)
            yield ('NUM', s)
            i = j
            continue
        if c.isalpha() or c == '_':
            j = i
            while j < n and (expr[j].isalnum() or expr[j] == '_'):
                j += 1
            yield ('NAME', expr[i:j])
            i = j
            continue
        two = expr[i:i+2]
        if two in ('==', '!=', '<=', '>='):
            yield (two, two)
            i += 2
            continue
        if c in '+-*/^<>(),:':
            yield (c, c)
            i += 1
            continue
        raise FormulaSyntaxError('unexpected char at ' + str(i) + ': ' + c)

class Node:
    pass

class Num(Node):
    def __init__(self, value):
        self.value = value

class Cell(Node):
    def __init__(self, coord):
        self.coord = coord

class Range(Node):
    def __init__(self, top_left, bottom_right):
        self.top_left = top_left
        self.bottom_right = bottom_right

class Unary(Node):
    def __init__(self, op, operand):
        self.op = op
        self.operand = operand

class Bin(Node):
    def __init__(self, op, left, right):
        self.op = op
        self.left = left
        self.right = right

class Call(Node):
    def __init__(self, name, args):
        self.name = name.upper()
        self.args = args

def coord_parts(coord):
    m = COORD_RE.match(normalize_coord(coord))
    letters = m.group(1).upper()
    row = int(m.group(2))
    col = 0
    for ch in letters:
        col = col * 26 + (ord(ch) - ord('A') + 1)
    return col, row

def coord_from_parts(col, row):
    letters = ''
    c = col
    while c > 0:
        c, r = divmod(c - 1, 26)
        letters = chr(r + ord('A')) + letters
    return f'{letters}{row}'

def coords_in_range(a, b):
    c1, r1 = coord_parts(a)
    c2, r2 = coord_parts(b)
    left, right = min(c1, c2), max(c1, c2)
    top, bottom = min(r1, r2), max(r1, r2)
    for r in range(top, bottom + 1):
        for c in range(left, right + 1):
            yield coord_from_parts(c, r)

def parse_formula(expr):
    if not isinstance(expr, str) or not expr.strip():
        raise FormulaSyntaxError('empty formula')
    toks = list(_tokens(expr))
    return Parser(toks).parse_formula()

class Parser:
    def __init__(self, toks):
        self.toks = toks
        self.i = 0
    def peek(self):
        return self.toks[self.i] if self.i < len(self.toks) else (None, None)
    def next(self):
        t = self.peek()
        self.i += 1
        return t
    def expect(self, kind):
        t = self.next()
        if t[0] != kind:
            raise FormulaSyntaxError(f'expected {kind}, got {t}')
        return t
    def parse_formula(self):
        node = self.parse_comparison()
        if self.i != len(self.toks):
            raise FormulaSyntaxError('unexpected trailing input')
        return node
    def parse_comparison(self):
        left = self.parse_additive()
        t = self.peek()
        if t[0] in ('==', '!=', '<', '<=', '>', '>='):
            op = self.next()[0]
            right = self.parse_additive()
            if self.peek()[0] in ('==', '!=', '<', '<=', '>', '>='):
                raise FormulaSyntaxError('comparisons do not chain')
            return Bin(op, left, right)
        return left
    def parse_additive(self):
        left = self.parse_multiplicative()
        while self.peek()[0] in ('+', '-'):
            op = self.next()[0]
            right = self.parse_multiplicative()
            left = Bin(op, left, right)
        return left
    def parse_multiplicative(self):
        left = self.parse_unary()
        while self.peek()[0] in ('*', '/'):
            op = self.next()[0]
            right = self.parse_unary()
            left = Bin(op, left, right)
        return left
    def parse_unary(self):
        if self.peek()[0] in ('+', '-'):
            op = self.next()[0]
            operand = self.parse_unary()
            return Unary(op, operand)
        return self.parse_power()
    def parse_power(self):
        left = self.parse_atom()
        if self.peek()[0] == '^':
            self.next()
            right = self.parse_unary()
            return Bin('^', left, right)
        return left
    def parse_atom(self):
        t = self.next()
        kind, value = t
        if kind == 'NUM':
            return Num(float(value))
        if kind == 'NAME':
            if COORD_RE.match(value):
                coord = normalize_coord(value)
                if self.peek()[0] == ':':
                    self.next()
                    t2 = self.next()
                    if t2[0] != 'NAME' or not COORD_RE.match(t2[1]):
                        raise FormulaSyntaxError('expected range endpoint')
                    end = normalize_coord(t2[1])
                    return Range(coord, end)
                return Cell(coord)
            name = value.upper()
            if self.peek()[0] != '(':
                raise FormulaSyntaxError('unknown bare identifier: ' + value)
            return self.parse_call(name)
        if kind == '(':
            node = self.parse_comparison()
            self.expect(')')
            return node
        raise FormulaSyntaxError('unexpected token ' + str(t))
    def parse_call(self, name):
        self.expect('(')
        args = []
        if self.peek()[0] == ')':
            raise FormulaSyntaxError('empty call')
        while True:
            args.append(self.parse_comparison())
            if self.peek()[0] == ',':
                self.next()
                if self.peek()[0] == ')':
                    raise FormulaSyntaxError('trailing comma in call')
                continue
            self.expect(')')
            break
        allowed = {'SUM', 'AVG', 'MIN', 'MAX', 'COUNT', 'IF'}
        if name not in allowed:
            raise FormulaSyntaxError('unknown function: ' + name)
        if name == 'IF' and len(args) != 3:
            raise FormulaSyntaxError('IF requires 3 args')
        if name != 'IF' and len(args) < 1:
            raise FormulaSyntaxError(name + ' requires >=1 arg')
        return Call(name, args)

def collect_refs(node):
    refs = set()
    def visit(n):
        if isinstance(n, Cell):
            refs.add(n.coord)
        elif isinstance(n, Range):
            for c in coords_in_range(n.top_left, n.bottom_right):
                refs.add(c)
        elif isinstance(n, Unary):
            visit(n.operand)
        elif isinstance(n, Bin):
            visit(n.left)
            visit(n.right)
        elif isinstance(n, Call):
            for a in n.args:
                visit(a)
        elif isinstance(n, Num):
            pass
        else:
            raise FormulaSyntaxError('unknown AST node')
    visit(node)
    return refs

def _eval(node, get_val, is_populated):
    if isinstance(node, Num):
        return node.value
    if isinstance(node, Cell):
        return get_val(node.coord)
    if isinstance(node, Unary):
        v = _eval(node.operand, get_val, is_populated)
        return v if node.op == '+' else -v
    if isinstance(node, Bin):
        op = node.op
        if op in ('==', '!=', '<', '<=', '>', '>='):
            l = _eval(node.left, get_val, is_populated)
            r = _eval(node.right, get_val, is_populated)
            if op == '==': return 1.0 if l == r else 0.0
            if op == '!=': return 0.0 if l == r else 1.0
            if op == '<': return 1.0 if l < r else 0.0
            if op == '<=': return 1.0 if l <= r else 0.0
            if op == '>': return 1.0 if l > r else 0.0
            if op == '>=': return 1.0 if l >= r else 0.0
        l = _eval(node.left, get_val, is_populated)
        r = _eval(node.right, get_val, is_populated)
        if op == '+': return l + r
        if op == '-': return l - r
        if op == '*': return l * r
        if op == '/':
            if r == 0:
                raise FormulaError('div by zero')
            return l / r
        if op == '^':
            return l ** r
        raise FormulaSyntaxError('unknown op ' + op)
    if isinstance(node, Call):
        name = node.name
        if name == 'IF':
            cond = _eval(node.args[0], get_val, is_populated)
            if cond != 0:
                return _eval(node.args[1], get_val, is_populated)
            return _eval(node.args[2], get_val, is_populated)
        values = []
        for arg in node.args:
            if isinstance(arg, Range):
                for c in coords_in_range(arg.top_left, arg.bottom_right):
                    if not is_populated(c):
                        continue
                    values.append(get_val(c))
            else:
                v = _eval(arg, get_val, is_populated)
                values.append(v)
        if name == 'SUM':
            return sum(values)
        if name == 'COUNT':
            return float(len(values))
        if name == 'AVG':
            if not values:
                raise FormulaError('AVG over 0 values')
            return sum(values) / len(values)
        if name == 'MIN':
            if not values:
                raise FormulaError('MIN over 0 values')
            return min(values)
        if name == 'MAX':
            if not values:
                raise FormulaError('MAX over 0 values')
            return max(values)
        raise FormulaSyntaxError('unknown function ' + name)
    raise FormulaSyntaxError('unknown AST node')

def eval_formula(node, get_val, is_populated):
    if isinstance(node, Range):
        return float(sum(_eval_range(node, get_val, is_populated)))
    return _eval(node, get_val, is_populated)

def _eval_range(range_node, get_val, is_populated):
    vals = []
    for c in coords_in_range(range_node.top_left, range_node.bottom_right):
        if not is_populated(c):
            continue
        vals.append(get_val(c))
    return vals