-
Notifications
You must be signed in to change notification settings - Fork 1
/
calltrace.py
273 lines (232 loc) · 8.37 KB
/
calltrace.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
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
"""Log function call details"""
from __future__ import print_function
from misc import wrap_import
wrap_import()
from sys import stderr
from functions import (WrapperFunction, Function)
from contextlib import contextmanager
import inspect
from types import (
FunctionType, MethodType, BuiltinFunctionType, BuiltinMethodType,
ModuleType, GeneratorType, InstanceType, ClassType,
)
import reprlib
import time
import operator
class traced(WrapperFunction):
def __init__(self, func, abbrev=set()):
WrapperFunction.__init__(self, func)
self.abbrev = abbrev
def __call__(self, *args, **kw):
start()
print_call(custrepr(self.__wrapped__), args, kw, self.abbrev)
start_time = time.monotonic()
with trace_exc(abbrev=self.abbrev):
ret = self.__wrapped__(*args, **kw)
period = _format_si(time.monotonic() - start_time, 3)
result()
line("-> {} after {}s", optrepr(ret, "return" in self.abbrev), period)
return ret
def __repr__(self):
return "{}({})".format(
self.__class__.__name__, custrepr(self.__wrapped__))
class tracer(Function):
def __init__(self, name, abbrev=()):
Function.__init__(self, name)
self.abbrev = abbrev
def __call__(self, *pos, **kw):
start()
print_call(self.__name__, pos, kw, abbrev=self.abbrev)
line("")
@contextmanager
def checkpoint(text, abbrev=()):
start()
stderr.write(text)
start_time = time.monotonic()
with trace_exc(abbrev=abbrev):
yield
period = time.monotonic() - start_time
result()
line("{}s", _format_si(period, 3), period)
@contextmanager
def trace_exc(abbrev=()):
global indent
stderr.flush()
indent += 1
start = time.monotonic()
try:
yield
except BaseException as exc:
period = _format_si(time.monotonic() - start, 3)
result()
line("raise {} after {}s", optrepr(exc, "raise" in abbrev), period)
raise
def result():
global indent
indent -= 1
if midline:
stderr.write(" ")
else:
margin()
def print_call(func, pos=(), kw=dict(), abbrev=()):
print(func, end="(", file=stderr)
for (k, v) in enumerate(pos):
if k:
stderr.write(", ")
stderr.write(optrepr(v, k in abbrev))
comma = pos
for (k, v) in kw.items():
if comma:
stderr.write(", ")
stderr.write("{}={}".format(k, optrepr(v, k in abbrev)))
comma = True
stderr.write(")")
def optrepr(v, abbrev=False):
if abbrev:
return "..."
else:
return custrepr(v)
def custrepr(obj):
return Repr().repr(obj)
class OrderedSubclasses(dict):
"""Adds a "subclasses" list in topological order to each value"""
def __init__(self, universe):
self.universe = universe
self.superclasses = set()
for cls in self.universe:
self[cls]
def __missing__(self, cls):
self.superclasses.add(cls)
subclasses = list()
for subclass in self.universe:
if subclass == cls or not issubclass(subclass, cls):
continue
if subclass in self.superclasses:
raise ValueError("{!r} is both a subclass and a superclass "
"of {!r}".format(subclass, cls))
existing = set(subclasses)
for subclass in self[subclass]:
if subclass not in existing:
subclasses.append(subclass)
self.superclasses.remove(cls)
subclasses.append(cls)
self[cls] = subclasses
return subclasses
class Repr(reprlib.Repr):
def __init__(self, *pos, **kw):
reprlib.Repr.__init__(self, *pos, **kw)
self.maxother = max(self.maxother, 80)
if InstanceType is not object:
# "maxstring" used for "old-style" instances
self.maxstring = max(self.maxstring, 80)
def repr1(self, obj, level):
"""See if a custom repr() is provided that overrides the object's
repr()"""
self.level = level
for base in inspect.getmro(getattr(obj, "__class__", type(obj))):
# Check for subclasses of the object's base class, so that a
# custom representation of a virtual base class not in the MRO
# has priority over a common concrete base class's representation
for subclass in self.subclasses.get(base, ()):
if isinstance(obj, subclass):
return self.classes[subclass](self, obj)
# Let an object's specialised repr() have priority over custom
# representations for more basic classes
if vars(base).get("__repr__"):
return reprlib.Repr.repr1(self, obj, level)
if isinstance(obj, InstanceType):
return self.obj(obj)
return reprlib.Repr.repr1(self, obj, level)
def recurse(self, obj):
return self.repr1(obj, self.level - 1)
classes = dict()
def obj(self, obj):
"""Mimic object representation printed by the garbage collector"""
return "<{} 0x{:X}>".format(self.recurse(obj.__class__), id(obj))
classes[object] = obj
def named(self, obj):
name = getattr(obj, "__qualname__", obj.__name__)
if False:
module = getattr(obj, "__module__", None)
if module is not None:
name = "{}.{}".format(module, name)
return name
classes[FunctionType] = named
classes[type] = named
classes[ClassType] = named
def method(self, method):
binding = method.__self__ or getattr(method, "im_class", None)
if binding:
return "{}.{}".format(
self.recurse(binding), method.__func__.__name__)
else:
return self.recurse(method.__func__)
classes[MethodType] = method
def builtin(self, builtin):
binding = builtin.__self__
# Built-in functions tend to set __self__ to their module
if binding and (not isinstance(binding, ModuleType) or
binding.__name__ != builtin.__module__):
return "{}.{}".format(self.recurse(binding), builtin.__name__)
else:
return self.named(builtin)
classes[BuiltinFunctionType] = builtin
classes[BuiltinMethodType] = builtin
def generator(self, gen):
return "<{} 0x{:X}>".format(self.named(gen), id(gen))
classes[GeneratorType] = generator
def memory(self, view):
nbytes = getattr(view, "nbytes", None)
if nbytes is None: # Python < 3
nbytes = reduce(operator.mul, view.shape, 1) * view.itemsize
access = "readonly" if view.readonly else "writable"
return "<memory 0x{:X} {} len={}>".format(id(view), access, nbytes)
classes[memoryview] = memory
subclasses = OrderedSubclasses(classes.keys())
indent = 0
midline = False
def start():
if midline:
line("")
margin()
def line(format_string, *pos, **kw):
global midline
print(format_string.format(*pos, **kw), file=stderr)
midline = False
def margin():
global midline
for _ in range(indent):
stderr.write(" ")
midline = True
def _format_si(number, ndigits):
'''
format_si(0, 3) -> "0.00 " # Only leading zero; significant digits
format_si(10150, 3) -> "10.2 k" # Round half up to even
format_si(222500, 3) -> "222 k" # Half down to even; no decimal point
format_si(0.99949, 3) -> "999 m" # Prefer more accurate rounding
format_si(1.380648813e-23, 3) -> "1.38e-23 " # Extreme value
'''
scientific = "{:.{}e}".format(number, ndigits - 1)
[significand, exponent] = scientific.rsplit("e", 2)
[prefix, scaled_exp] = divmod(int(exponent), 3)
significand = significand.replace(".", "", 1)
if significand.startswith("-"):
digits_start = 1
else:
digits_start = 0
dec_pos = digits_start + 1 + scaled_exp
fraction = significand[dec_pos:]
if fraction:
fraction = "." + fraction
if prefix:
if prefix < 0:
prefixes = "mµnpfazy"
prefix = -prefix
else:
prefixes = "kMGTPEZY"
if prefix > len(prefixes):
return scientific + " "
prefix = prefixes[prefix - 1]
else:
prefix = ""
return "{}{} {}".format(significand[:dec_pos], fraction, prefix)