1 """
2 utility functions for asteval
3
4 Matthew Newville <newville@cars.uchicago.edu>,
5 The University of Chicago
6 """
7 from __future__ import division, print_function
8 import ast
9 from sys import exc_info
10
11
12 FROM_PY = ('ArithmeticError', 'AssertionError', 'AttributeError',
13 'BaseException', 'BufferError', 'BytesWarning',
14 'DeprecationWarning', 'EOFError', 'EnvironmentError',
15 'Exception', 'False', 'FloatingPointError', 'GeneratorExit',
16 'IOError', 'ImportError', 'ImportWarning', 'IndentationError',
17 'IndexError', 'KeyError', 'KeyboardInterrupt', 'LookupError',
18 'MemoryError', 'NameError', 'None', 'NotImplemented',
19 'NotImplementedError', 'OSError', 'OverflowError',
20 'ReferenceError', 'RuntimeError', 'RuntimeWarning',
21 'StopIteration', 'SyntaxError', 'SyntaxWarning', 'SystemError',
22 'SystemExit', 'True', 'TypeError', 'UnboundLocalError',
23 'UnicodeDecodeError', 'UnicodeEncodeError', 'UnicodeError',
24 'UnicodeTranslateError', 'UnicodeWarning', 'ValueError',
25 'Warning', 'ZeroDivisionError', 'abs', 'all', 'any', 'bin',
26 'bool', 'bytearray', 'bytes', 'chr', 'complex', 'delattr',
27 'dict', 'dir', 'divmod', 'enumerate', 'filter', 'float',
28 'format', 'frozenset', 'getattr', 'hasattr', 'hash', 'hex',
29 'id', 'int', 'isinstance', 'len', 'list', 'map', 'max', 'min',
30 'oct', 'open', 'ord', 'pow', 'property', 'range', 'repr',
31 'reversed', 'round', 'set', 'setattr', 'slice', 'sorted', 'str',
32 'sum', 'tuple', 'type', 'zip')
33
34
35 FROM_MATH = ('acos', 'acosh', 'asin', 'asinh', 'atan', 'atan2', 'atanh',
36 'ceil', 'copysign', 'cos', 'cosh', 'degrees', 'e', 'exp',
37 'fabs', 'factorial', 'floor', 'fmod', 'frexp', 'fsum',
38 'hypot', 'isinf', 'isnan', 'ldexp', 'log', 'log10', 'log1p',
39 'modf', 'pi', 'pow', 'radians', 'sin', 'sinh', 'sqrt', 'tan',
40 'tanh', 'trunc')
41
42
43 FROM_NUMPY = ('Inf', 'NAN', 'abs', 'absolute', 'add', 'alen', 'all',
44 'allclose', 'alltrue', 'alterdot', 'amax', 'amin', 'angle',
45 'any', 'append', 'apply_along_axis', 'apply_over_axes',
46 'arange', 'arccos', 'arccosh', 'arcsin', 'arcsinh', 'arctan',
47 'arctan2', 'arctanh', 'argmax', 'argmin', 'argsort',
48 'argwhere', 'around', 'array', 'array2string', 'array_equal',
49 'array_equiv', 'array_repr', 'array_split', 'array_str',
50 'asanyarray', 'asarray', 'asarray_chkfinite',
51 'ascontiguousarray', 'asfarray', 'asfortranarray',
52 'asmatrix', 'asscalar', 'atleast_1d', 'atleast_2d',
53 'atleast_3d', 'average', 'bartlett', 'base_repr', 'bench',
54 'binary_repr', 'bincount', 'bitwise_and', 'bitwise_not',
55 'bitwise_or', 'bitwise_xor', 'blackman', 'bmat', 'bool',
56 'bool8', 'broadcast', 'broadcast_arrays', 'byte',
57 'byte_bounds', 'bytes_', 'c_', 'can_cast', 'cast', 'cdouble',
58 'ceil', 'cfloat', 'char', 'character', 'chararray', 'choose',
59 'clip', 'clongdouble', 'clongfloat', 'column_stack',
60 'common_type', 'compare_chararrays', 'compat', 'complex',
61 'complex128', 'complex64', 'complex_', 'complexfloating',
62 'compress', 'concatenate', 'conj', 'conjugate', 'convolve',
63 'copy', 'copysign', 'core', 'corrcoef', 'correlate', 'cos',
64 'cosh', 'cov', 'cross', 'csingle', 'ctypeslib', 'cumprod',
65 'cumproduct', 'cumsum', 'datetime_data', 'deg2rad',
66 'degrees', 'delete', 'diag', 'diag_indices',
67 'diag_indices_from', 'diagflat', 'diagonal', 'diff',
68 'digitize', 'disp', 'divide', 'dot', 'double', 'dsplit',
69 'dstack', 'dtype', 'e', 'ediff1d', 'emath', 'empty',
70 'empty_like', 'equal', 'exp', 'exp2', 'expand_dims', 'expm1',
71 'extract', 'eye', 'fabs', 'fft', 'fill_diagonal',
72 'find_common_type', 'finfo', 'fix', 'flatiter',
73 'flatnonzero', 'flexible', 'fliplr', 'flipud', 'float',
74 'float32', 'float64', 'float_', 'floating', 'floor',
75 'floor_divide', 'fmax', 'fmin', 'fmod', 'format_parser',
76 'frexp', 'frombuffer', 'fromfile', 'fromfunction',
77 'fromiter', 'frompyfunc', 'fromregex', 'fromstring', 'fv',
78 'generic', 'genfromtxt', 'getbufsize', 'geterr',
79 'geterrcall', 'geterrobj', 'gradient', 'greater',
80 'greater_equal', 'hamming', 'hanning', 'histogram',
81 'histogram2d', 'histogramdd', 'hsplit', 'hstack', 'hypot',
82 'i0', 'identity', 'iinfo', 'imag', 'in1d', 'index_exp',
83 'indices', 'inexact', 'inf', 'info', 'infty', 'inner',
84 'insert', 'int', 'int0', 'int16', 'int32', 'int64', 'int8',
85 'int_', 'int_asbuffer', 'intc', 'integer', 'interp',
86 'intersect1d', 'intp', 'invert', 'ipmt', 'irr', 'iscomplex',
87 'iscomplexobj', 'isfinite', 'isfortran', 'isinf', 'isnan',
88 'isneginf', 'isposinf', 'isreal', 'isrealobj', 'isscalar',
89 'issctype', 'issubclass_', 'issubdtype', 'issubsctype',
90 'iterable', 'ix_', 'kaiser', 'kron', 'ldexp', 'left_shift',
91 'less', 'less_equal', 'lexsort', 'lib', 'linalg', 'linspace',
92 'little_endian', 'load', 'loads', 'loadtxt', 'log', 'log10',
93 'log1p', 'log2', 'logaddexp', 'logaddexp2', 'logical_and',
94 'logical_not', 'logical_or', 'logical_xor', 'logspace',
95 'long', 'longcomplex', 'longdouble', 'longfloat', 'longlong',
96 'lookfor', 'ma', 'mafromtxt', 'mask_indices', 'mat', 'math',
97 'matrix', 'matrixlib', 'max', 'maximum', 'maximum_sctype',
98 'may_share_memory', 'mean', 'median', 'memmap', 'meshgrid',
99 'mgrid', 'min', 'minimum', 'mintypecode', 'mirr', 'mod',
100 'modf', 'msort', 'multiply', 'nan', 'nan_to_num',
101 'nanargmax', 'nanargmin', 'nanmax', 'nanmin', 'nansum',
102 'nbytes', 'ndarray', 'ndenumerate', 'ndfromtxt', 'ndim',
103 'ndindex', 'negative', 'newaxis', 'nextafter', 'nonzero',
104 'not_equal', 'nper', 'npv', 'number', 'obj2sctype', 'object',
105 'object0', 'object_', 'ogrid', 'ones', 'ones_like', 'outer',
106 'packbits', 'percentile', 'pi', 'piecewise', 'pkgload',
107 'place', 'pmt', 'poly', 'poly1d', 'polyadd', 'polyder',
108 'polydiv', 'polyfit', 'polyint', 'polymul', 'polynomial',
109 'polysub', 'polyval', 'power', 'ppmt', 'prod', 'product',
110 'ptp', 'put', 'putmask', 'pv', 'r_', 'rad2deg', 'radians',
111 'random', 'rank', 'rate', 'ravel', 'real', 'real_if_close',
112 'rec', 'recarray', 'recfromcsv', 'recfromtxt', 'reciprocal',
113 'record', 'remainder', 'repeat', 'require', 'reshape',
114 'resize', 'restoredot', 'right_shift', 'rint', 'roll',
115 'rollaxis', 'roots', 'rot90', 'round', 'round_', 'row_stack',
116 's_', 'safe_eval', 'save', 'savetxt', 'savez', 'sctype2char',
117 'sctypeDict', 'sctypeNA', 'sctypes', 'searchsorted',
118 'select', 'setbufsize', 'setdiff1d', 'seterr', 'setxor1d',
119 'shape', 'short', 'sign', 'signbit', 'signedinteger', 'sin',
120 'sinc', 'single', 'singlecomplex', 'sinh', 'size',
121 'sometrue', 'sort', 'sort_complex', 'source', 'spacing',
122 'split', 'sqrt', 'square', 'squeeze', 'std', 'str', 'str_',
123 'subtract', 'sum', 'swapaxes', 'take', 'tan', 'tanh',
124 'tensordot', 'test', 'testing', 'tile', 'trace', 'transpose',
125 'trapz', 'tri', 'tril', 'tril_indices', 'tril_indices_from',
126 'trim_zeros', 'triu', 'triu_indices', 'triu_indices_from',
127 'true_divide', 'trunc', 'typeDict', 'typeNA', 'typecodes',
128 'typename', 'ubyte', 'ufunc', 'uint', 'uint0', 'uint16',
129 'uint32', 'uint64', 'uint8', 'uintc', 'uintp', 'ulonglong',
130 'union1d', 'unique', 'unravel_index', 'unsignedinteger',
131 'unwrap', 'ushort', 'vander', 'var', 'vdot', 'vectorize',
132 'version', 'void', 'void0', 'vsplit', 'vstack', 'where',
133 'who', 'zeros', 'zeros_like')
134
135 NUMPY_RENAMES = {'ln':'log', 'asin':'arcsin', 'acos':'arccos',
136 'atan':'arctan', 'atan2':'arctan2', 'atanh':'arctanh',
137 'acosh':'arccosh', 'asinh':'arcsinh'}
138
140 "basic exception handler"
141 - def __init__(self, node, exc=None, msg='', expr=None, lineno=None):
142 self.node = node
143 self.expr = expr
144 self.msg = msg
145 self.exc = exc
146 self.lineno = lineno
147 self.exc_info = exc_info()
148 if self.exc is None and self.exc_info[0] is not None:
149 self.exc = self.exc_info[0]
150 if self.msg is '' and self.exc_info[1] is not None:
151 self.msg = self.exc_info[1]
152
154 "retrieve error data"
155 col_offset = -1
156 if self.node is not None:
157 try:
158 col_offset = self.node.col_offset
159 except AttributeError:
160 pass
161 try:
162 exc_name = self.exc.__name__
163 except AttributeError:
164 exc_name = str(self.exc)
165 if exc_name in (None, 'None'):
166 exc_name = 'UnknownError'
167
168 out = [" %s" % self.expr]
169 if col_offset > 0:
170 out.append(" %s^^^" % ((col_offset)*' '))
171 out.append(str(self.msg))
172 return (exc_name, '\n'.join(out))
173
175 """find all symbol names used by a parsed node"""
177 self.names = []
178 ast.NodeVisitor.__init__(self)
179
181 nodename = node.__class__.__name__.lower()
182 if nodename == 'name':
183 if (node.ctx.__class__ == ast.Load and
184 node.id not in self.names):
185 self.names.append(node.id)
186 ast.NodeVisitor.generic_visit(self, node)
187