File: matheval.py

package info (click to toggle)
treeline 3.1.5-1.1
  • links: PTS
  • area: main
  • in suites: trixie
  • size: 6,508 kB
  • sloc: python: 20,489; javascript: 998; makefile: 54
file content (629 lines) | stat: -rw-r--r-- 21,625 bytes parent folder | download | duplicates (3)
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
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
#!/usr/bin/env python3

#******************************************************************************
# matheval.py, provides a safe eval of mathematical expressions
#
# TreeLine, an information storage program
# Copyright (C) 2020, Douglas W. Bell
#
# This is free software; you can redistribute it and/or modify it under the
# terms of the GNU General Public License, either Version 2 or any later
# version.  This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY.  See the included LICENSE file for details.
#******************************************************************************

import re
import ast
import enum
import datetime
import builtins
import fieldformat
import gennumber
from math import *

_nowDateString = 'Now_Date'
_nowTimeString = 'Now_Time'
_nowDateTimeString = 'Now_Date_Time'


def sum(*args):
    """Override the builtin sum function to handle multiple arguments.

    Arguments:
        *args -- lists of numbers or individual numbers
    """
    fullList = []
    for arg in args:
        if hasattr(arg, 'extend'):
            fullList.extend(arg)
        else:
            fullList.append(arg)
    return builtins.sum(fullList)

def max(*args):
    """Override the builtin max function to expand list arguments.

    Arguments:
        *args -- lists of numbers or individual numbers
    """
    fullList = []
    for arg in args:
        if hasattr(arg, 'extend'):
            fullList.extend(arg)
        else:
            fullList.append(arg)
    if not fullList:
        return 0
    return builtins.max(fullList)

def min(*args):
    """Override the builtin min function to expand list arguments.

    Arguments:
        *args -- lists of numbers or individual numbers
    """
    fullList = []
    for arg in args:
        if hasattr(arg, 'extend'):
            fullList.extend(arg)
        else:
            fullList.append(arg)
    if not fullList:
        return 0
    return builtins.min(fullList)

def mean(*args):
    """Added function to calculate the arithmetic average.

    Arguments:
        *args -- lists of numbers or individual numbers
    """
    fullList = []
    for arg in args:
        if hasattr(arg, 'extend'):
            fullList.extend(arg)
        else:
            fullList.append(arg)
    if not fullList:
        return 0
    return builtins.sum(fullList) / len(fullList)

# don't use pow() function from math library
pow = builtins.pow

def startswith(text, firstText):
    """Added compare function, returns true if text starts with firstText.

    Arguments:
        text -- the string to check
        firstText -- the starting text
    """
    return str(text).startswith(str(firstText))

def endswith(text, firstText):
    """Added compare function, returns true if text ends with firstText.

    Arguments:
        text -- the string to check
        firstText -- the ending text
    """
    return str(text).endswith(str(firstText))

def contains(text, innerText):
    """Added compare function, returns true if text contains innerText.

    Arguments:
        text -- the string to check
        innerText -- the inside text
    """
    return str(innerText) in str(text)

def join(sep, *args):
    """Added text function to combine strings.

    Arguments:
        sep -- the separator string
        *args -- lists of strings or individual strings to combine
    """
    fullList = []
    for arg in args:
        if hasattr(arg, 'extend'):
            fullList.extend(arg)
        else:
            fullList.append(arg)
    return sep.join([str(i) for i in fullList if str(i)])

def upper(text):
    """Added text function for upper case.

    Arguments:
        text -- the string to modify
    """
    return str(text).upper()

def lower(text):
    """Added text function for lower case.

    Arguments:
        text -- the string to modify
    """
    return str(text).lower()

def replace(text, oldText, newText):
    """Added text function to replace strings.

    Arguments:
        text -- the string to modify
        oldText -- the string to be replaced
        newText -- the replacement string
    """
    return str(text).replace(str(oldText), str(newText))


_fieldSplitRe = re.compile(r'{\*(\*|\$|&|#|\b)([\w_\-.]+)\*}')

class MathEquation:
    """Class to parse, check, store and evaluate a Math field equation.
    """
    def __init__(self, eqnText=''):
        """Initialize the MathEquation.

        Arguments:
            eqnText -- the text of an equation to be parsed
        """
        self.fieldRefs = []
        self.formattedEqnText = ''
        self.parseEquation(eqnText)

    def equationText(self):
        """Return the text representation of the equation.
        """
        fieldNames = ['{{*{0}{1}*}}'.format(ref.tagPrefix, ref.fieldName) for
                      ref in self.fieldRefs]
        return self.formattedEqnText.format(*fieldNames)

    def validate(self):
        """Check if the equation is valid (or empty).

        Use ones as fake input and use ast to verify legality.
        Raises a ValueError if the equation is not valid.
        """
        if not self.formattedEqnText:
            return
        inputs = [ref.testValue for ref in self.fieldRefs]
        checker = SafeEvalChecker()
        try:
            eqn = self.formattedEqnText.format(*inputs)
        except IndexError:
            raise ValueError(_('Illegal "{}" characters'))
        except KeyError:
            raise ValueError(_('Invalid field modifiers'))
        checker.check(eqn)
        try:
            result = eval(eqn)
            if isinstance(result, list):
                raise TypeError('list result not allowed')
        except NameError as err:
            raise ValueError(err)
        except TypeError as err:
            if 'list' in str(err) and '&' in [ref.tagPrefix for ref in
                                              self.fieldRefs]:
                msg = _('Child references must be combined in a function')
                raise ValueError(msg)
        except ZeroDivisionError:
            pass

    def equationValue(self, eqnNode, resultType, zeroValue=0, noMarkup=True):
        """Return a value for the equation in the given node.

        Return None if references are invalid.
        Raise a ValueError for illegal math operations.
        Arguments:
            eqnNode -- the node containing the equation to evaluate
            resultType -- the result type from fieldformat
            zeroValue -- the value to use for blanks
            noMarkup -- if true, remove html markup
        """
        zeroBlanks = eqnNode.treeStructureRef().mathZeroBlanks
        checker = SafeEvalChecker()
        inputs = []
        for ref in self.fieldRefs:
            inp = ref.referenceValue(eqnNode, zeroBlanks, zeroValue, noMarkup)
            if inp == None and not zeroBlanks:
                return None
            if (resultType == fieldformat.MathResult.number and
                hasattr(inp, 'format')):
                try:
                    checker.check(inp)
                    inp = eval(inp)
                except Exception:
                    inp = repr(inp)
            else:
                inp = repr(inp)
            inputs.append(inp)
        eqn = self.formattedEqnText.format(*inputs)
        try:
            return eval(eqn)
        except Exception as err:
            raise ValueError(err)

    def parseEquation(self, eqnText):
        """Replace the stored equation by parsing the given text.

        Creates formatted equation text and a list of field references.
        Arguments:
            eqnText -- the text of an equation to be parsed
        """
        self.fieldRefs = []
        self.formattedEqnText = _fieldSplitRe.sub(self._replFunc, eqnText)

    def _replFunc(self, matchObj):
        """Adds a field ref for each field match from the parser.

        Returns a string format placeholder as the replacement text.
        Arguments:
            matchObj -- the field match object
        """
        fieldRefType = matchObj.group(1)
        fieldRefName = matchObj.group(2)
        fieldRefSelector = {'': EquationFieldRef, '*': EquationParentRef,
                            '$': EquationRootRef, '&': EquationChildRef,
                            '#': EquationChildCountRef}
        fieldRef = fieldRefSelector[fieldRefType](fieldRefName)
        self.fieldRefs.append(fieldRef)
        return '{}'


# recursive equation ref eval directions
EvalDir = enum.IntEnum('EvalDir', 'downward upward optional')


class EquationFieldRef:
    """Class to store and eval individual field references in a Math equation.

    This base class handles references within the same node.
    """
    tagPrefix = ''
    testValue = 1
    evalDirection = EvalDir.optional
    def __init__(self, fieldName):
        """Initialize the field references.

        Arguments:
            fieldName -- the name of the referenced field
        """
        self.fieldName = fieldName
        self.eqnNodeTypeName = ''
        self.eqnFieldName = ''

    def referenceValue(self, eqnNode, zeroBlanks=True, zeroValue=0,
                       noMarkup=True):
        """Return the value of the field referenced in a given node.

        Return None if blank or doesn't exist and not zeroBlanks,
        raise a ValueError if it isn't a number.
        Arguments:
            eqnNode -- the node containing the equation to evaluate
            zeroBlanks -- replace blank fields with zeroValue if True
            zeroValue -- the value to use for blanks
            noMarkup -- if true, remove html markup
        """
        try:
            return (eqnNode.formatRef.fieldDict[self.fieldName].
                    mathValue(eqnNode, zeroBlanks, noMarkup))
        except KeyError:
            if self.fieldName == _nowDateString:
                return (datetime.date.today() -
                        fieldformat.DateField.refDate).days
            elif self.fieldName == _nowTimeString:
                now = datetime.datetime.combine(fieldformat.DateField.refDate,
                                                datetime.datetime.now().time())
                ref = datetime.datetime.combine(fieldformat.DateField.refDate,
                                                fieldformat.TimeField.refTime)
                return (now - ref).seconds
            elif self.fieldName == _nowDateTimeString:
                return (datetime.datetime.now() -
                        fieldformat.DateTimeField.refDateTime).total_seconds()
            return zeroValue if zeroBlanks else None

    def dependentEqnNodes(self, refNode):
        """Return a list of equation node(s) that reference the given node.

        Arguments:
            refNode -- the node containing the referenced field
        """
        if refNode.formatRef.name == self.eqnNodeTypeName:
            return [refNode]
        return []


class EquationParentRef(EquationFieldRef):
    """Class to store and eval parent field references in a Math equation.
    """
    tagPrefix = '*'
    testValue = 1
    evalDirection = EvalDir.downward

    def referenceValue(self, eqnNode, zeroBlanks=True, zeroValue=0,
                       noMarkup=True):
        """Return the parent field value referenced from a given node.

        Return None if blank or doesn't exist and not zeroBlanks,
        raise a ValueError if it isn't a number.
        Arguments:
            eqnNode -- the node containing the equation to evaluate
            zeroBlanks -- replace blank fields with zeroValue if True
            zeroValue -- the value to use for blanks
            noMarkup -- if true, remove html markup
        """
        node = eqnNode.spotByNumber(0).parentSpot.nodeRef
        if not node.formatRef:
            return zeroValue if zeroBlanks else None
        try:
            return (node.formatRef.fieldDict[self.fieldName].
                    mathValue(node, zeroBlanks, noMarkup))
        except KeyError:
            return zeroValue if zeroBlanks else None

    def dependentEqnNodes(self, refNode):
        """Return a list of equation node(s) that reference the given node.

        Arguments:
            refNode -- the node containing the referenced field
        """
        return [node for node in refNode.childList if
                node.formatRef.name == self.eqnNodeTypeName]


class EquationRootRef(EquationFieldRef):
    """Class to store and eval root node field references in a Math equation.
    """
    tagPrefix = '$'
    testValue = 1
    evalDirection = EvalDir.downward

    def referenceValue(self, eqnNode, zeroBlanks=True, zeroValue=0,
                       noMarkup=True):
        """Return the root field value referenced from a given node.

        Return None if blank or doesn't exist and not zeroBlanks,
        raise a ValueError if it isn't a number.
        Arguments:
            eqnNode -- the node containing the equation to evaluate
            zeroBlanks -- replace blank fields with zeroValue if True
            zeroValue -- the value to use for blanks
            noMarkup -- if true, remove html markup
        """
        node = eqnNode.spotByNumber(0).spotChain()[0].nodeRef
        try:
            return (node.formatRef.fieldDict[self.fieldName].
                    mathValue(node, zeroBlanks, noMarkup))
        except KeyError:
            return zeroValue if zeroBlanks else None

    def dependentEqnNodes(self, refNode):
        """Return a list of equation node(s) that reference the given node.

        Arguments:
            refNode -- the node containing the referenced field
        """
        if 1 not in {len(spot.spotChain()) for spot in refNode.spotRefs}:
            # not a root node
            return []
        refs = [node for node in refNode.descendantGen() if
                node.formatRef.name == self.eqnNodeTypeName]
        if refs and refs[0] is refNode:
            refs = refs[1:]
        return refs


class EquationChildRef(EquationFieldRef):
    """Class to store and eval child field references in a Math equation.
    """
    tagPrefix = '&'
    testValue = [1]
    evalDirection = EvalDir.upward

    def referenceValue(self, eqnNode, zeroBlanks=True, zeroValue=0,
                       noMarkup=True):
        """Return a list with child field values referenced from a given node.

        Return None if there are blanks and zeroBlanks is false,
        raise a ValueError if any aren't a number.
        Arguments:
            eqnNode -- the node containing the equation to evaluate
            zeroBlanks -- replace blank fields with zeroValue if True
            zeroValue -- the value to use for blanks
        """
        result = []
        for node in eqnNode.childList:
            try:
                num = (node.formatRef.fieldDict[self.fieldName].
                       mathValue(node, zeroBlanks, noMarkup))
                if num == None:
                    return None
                result.append(num)
            except KeyError:
                if not zeroBlanks:
                    return None
        if not result:
            result = [zeroValue]
        return result

    def dependentEqnNodes(self, refNode):
        """Return a list of equation node(s) that reference the given node.

        Arguments:
            refNode -- the node containing the referenced field
        """
        node = refNode.spotByNumber(0).parentSpot.nodeRef
        if node.formatRef and node.formatRef.name == self.eqnNodeTypeName:
            return [node]
        return []


class EquationChildCountRef(EquationFieldRef):
    """Class to store and eval child count references in a Math equation.
    """
    tagPrefix = '#'
    testValue = 1
    evalDirection = EvalDir.optional

    def referenceValue(self, eqnNode, zeroBlanks=True, zeroValue=0,
                       noMarkup=True):
        """Return the child count referenced from the given node.

        Arguments:
            eqnNode -- the node containing the equation to evaluate
            zeroBlanks -- replace blank fields with zeroValue if True
            zeroValue -- the value to use for blanks
            noMarkup -- if true, remove html markup
        """
        return len(eqnNode.childList)

    def dependentEqnNodes(self, refNode):
        """Return a list of equation node(s) that reference the given node.

        Arguments:
            refNode -- the node containing the referenced field
        """
        node = refNode.spotByNumber(0).parentSpot.nodeRef
        if node and node.formatRef.name == self.eqnNodeTypeName:
            return [node]
        return []


class RecursiveEqnRef:
    """Class to store a references to other equations in a tree structure.

    Resolves sequence and direction of global evaluations.
    """
    recursiveRefDict = {}
    def __init__(self, eqnTypeName, eqnField):
        """Initialize the RecursiveEquationRef.

        Arguments:
            eqnTypeName -- the type format name contining the equation field
            eqnField -- the field with the equation to eval for other eqn refs
        """
        self.eqnTypeName = eqnTypeName
        self.eqnField = eqnField
        self.evalSequence = 0
        self.evalDirection = EvalDir.optional

    def setPriorities(self, visitedFields=None):
        """Recursively set sequence and direction for evaluation.

        Arguments:
            visitedFields -- set of used eqn field names to check circular refs
        """
        if self.evalSequence != 0:
            return
        if visitedFields == None:
            visitedFields = set()
        visitedFields = visitedFields.copy()
        visitedFields.add(self.eqnField.name)
        self.evalSequence = 1
        for fieldRef in self.eqnField.equation.fieldRefs:
            if (fieldRef.fieldName in visitedFields and
                fieldRef.tagPrefix != '#' and
                (self.eqnField.name != fieldRef.fieldName or
                 fieldRef.evalDirection == EvalDir.optional)):
                raise CircularMathError()
            for eqnRef in self.recursiveRefDict.get(fieldRef.fieldName, []):
                eqnRef.setPriorities(visitedFields)
                if eqnRef.evalSequence >= self.evalSequence:
                    self.evalDirection = fieldRef.evalDirection
                    self.evalSequence = eqnRef.evalSequence
                    if (self.evalDirection != eqnRef.evalDirection or
                        self.evalDirection == EvalDir.optional):
                        self.evalSequence += 1

    def __lt__(self, other):
        """Use sequence and direction as comparison keys for sorting.

        Arguments:
            other -- the equation ref to compare
        """
        return ((self.evalSequence, self.evalDirection) <
                (other.evalSequence, other.evalDirection))


class CircularMathError(Exception):
    """Exception raised when circular references are found in math fields.
    """
    pass


allowedFunctions = set(['abs', 'float', 'int', 'len', 'max', 'min', 'pow',
                        'round', 'sum', 'mean',
                        'ceil', 'fabs', 'factorial', 'floor', 'fmod', 'fsum',
                        'trunc', 'exp', 'log', 'log10', 'pow', 'sqrt',
                        'acos', 'asin', 'atan', 'cos', 'sin', 'tan', 'hypot',
                        'degrees', 'radians', 'pi', 'e',
                        'startswith', 'endswith', 'contains',
                        'join', 'upper', 'lower', 'replace'])

allowedNodeTypes = set(['Module', 'Expr', 'Name', 'NameConstant', 'Constant',
                        'Load', 'IfExp', 'Compare', 'Num', 'Str', 'Tuple',
                        'List', 'BinOp', 'UnaryOp', 'Add', 'Sub', 'Mult',
                        'Div', 'Mod', 'Pow', 'FloorDiv', 'Invert', 'Not',
                        'UAdd', 'USub', 'Eq', 'NotEq', 'Lt', 'LtE', 'Gt',
                        'GtE', 'Is', 'IsNot', 'In', 'NotIn', 'BoolOp',
                        'And', 'Or'])


class SafeEvalChecker(ast.NodeVisitor):
    """Class to check that only safe functions are used in an eval expression.

    Raises a ValueError if unsafe or non-numeric operations are present.
    Ref. stackoverflow.com questions 10661079 and 12523516
    """

    def check(self, expr):
        """Check the given expression for non-numeric operations.

        Arguments:
            expr -- the expression string to check
        """
        try:
            tree = ast.parse(expr)
        except SyntaxError:
            raise ValueError(_('Illegal syntax in equation'))
        self.visit(tree)

    def visit_Call(self, node):
        """Check for allowed functions only.

        Arguments:
            node -- the ast node being checked
        """
        if node.func.id in allowedFunctions:
            super().generic_visit(node)
        else:
            raise ValueError(_('Illegal function present: {0}').
                             format(node.func.id))

    def generic_visit(self, node):
        """Check for allowed node types and operators.

        Arguments:
            node -- the ast node being checked
        """
        if type(node).__name__ in allowedNodeTypes:
            super().generic_visit(node)
        else:
            raise ValueError(_('Illegal object type or operator: {0}').
                             format(type(node).__name__))


if __name__ == '__main__':
    checker = SafeEvalChecker()
    try:
        print('Enter expression: ')
        expr = input()
        checker.check(expr)
    except ValueError as err:
        print(err)
    else:
        print(eval(expr))