eric6/DebugClients/Python/coverage/pytracer.py

changeset 6942
2602857055c5
parent 6219
d6c795b5ce33
child 7427
362cd1b6f81a
equal deleted inserted replaced
6941:f99d60d6b59b 6942:2602857055c5
1 # Licensed under the Apache License: http://www.apache.org/licenses/LICENSE-2.0
2 # For details: https://bitbucket.org/ned/coveragepy/src/default/NOTICE.txt
3
4 """Raw data collector for coverage.py."""
5
6 import atexit
7 import dis
8 import sys
9
10 from coverage import env
11
12 # We need the YIELD_VALUE opcode below, in a comparison-friendly form.
13 YIELD_VALUE = dis.opmap['YIELD_VALUE']
14 if env.PY2:
15 YIELD_VALUE = chr(YIELD_VALUE)
16
17
18 class PyTracer(object):
19 """Python implementation of the raw data tracer."""
20
21 # Because of poor implementations of trace-function-manipulating tools,
22 # the Python trace function must be kept very simple. In particular, there
23 # must be only one function ever set as the trace function, both through
24 # sys.settrace, and as the return value from the trace function. Put
25 # another way, the trace function must always return itself. It cannot
26 # swap in other functions, or return None to avoid tracing a particular
27 # frame.
28 #
29 # The trace manipulator that introduced this restriction is DecoratorTools,
30 # which sets a trace function, and then later restores the pre-existing one
31 # by calling sys.settrace with a function it found in the current frame.
32 #
33 # Systems that use DecoratorTools (or similar trace manipulations) must use
34 # PyTracer to get accurate results. The command-line --timid argument is
35 # used to force the use of this tracer.
36
37 def __init__(self):
38 # Attributes set from the collector:
39 self.data = None
40 self.trace_arcs = False
41 self.should_trace = None
42 self.should_trace_cache = None
43 self.warn = None
44 # The threading module to use, if any.
45 self.threading = None
46
47 self.cur_file_dict = None
48 self.last_line = 0 # int, but uninitialized.
49 self.cur_file_name = None
50
51 self.data_stack = []
52 self.last_exc_back = None
53 self.last_exc_firstlineno = 0
54 self.thread = None
55 self.stopped = False
56 self._activity = False
57
58 self.in_atexit = False
59 # On exit, self.in_atexit = True
60 atexit.register(setattr, self, 'in_atexit', True)
61
62 def __repr__(self):
63 return "<PyTracer at {0}: {1} lines in {2} files>".format(
64 id(self),
65 sum(len(v) for v in self.data.values()),
66 len(self.data),
67 )
68
69 def log(self, marker, *args):
70 """For hard-core logging of what this tracer is doing."""
71 with open("/tmp/debug_trace.txt", "a") as f:
72 f.write("{} {:x}.{:x}[{}] {:x} {}\n".format(
73 marker,
74 id(self),
75 self.thread.ident,
76 len(self.data_stack),
77 self.threading.currentThread().ident,
78 " ".join(map(str, args))
79 ))
80
81 def _trace(self, frame, event, arg_unused):
82 """The trace function passed to sys.settrace."""
83
84 #self.log(":", frame.f_code.co_filename, frame.f_lineno, event)
85
86 if (self.stopped and sys.gettrace() == self._trace):
87 # The PyTrace.stop() method has been called, possibly by another
88 # thread, let's deactivate ourselves now.
89 #self.log("X", frame.f_code.co_filename, frame.f_lineno)
90 sys.settrace(None)
91 return None
92
93 if self.last_exc_back:
94 if frame == self.last_exc_back:
95 # Someone forgot a return event.
96 if self.trace_arcs and self.cur_file_dict:
97 pair = (self.last_line, -self.last_exc_firstlineno)
98 self.cur_file_dict[pair] = None
99 self.cur_file_dict, self.cur_file_name, self.last_line = self.data_stack.pop()
100 self.last_exc_back = None
101
102 if event == 'call':
103 # Entering a new function context. Decide if we should trace
104 # in this file.
105 self._activity = True
106 self.data_stack.append((self.cur_file_dict, self.cur_file_name, self.last_line))
107 filename = frame.f_code.co_filename
108 self.cur_file_name = filename
109 disp = self.should_trace_cache.get(filename)
110 if disp is None:
111 disp = self.should_trace(filename, frame)
112 self.should_trace_cache[filename] = disp
113
114 self.cur_file_dict = None
115 if disp.trace:
116 tracename = disp.source_filename
117 if tracename not in self.data:
118 self.data[tracename] = {}
119 self.cur_file_dict = self.data[tracename]
120 # The call event is really a "start frame" event, and happens for
121 # function calls and re-entering generators. The f_lasti field is
122 # -1 for calls, and a real offset for generators. Use <0 as the
123 # line number for calls, and the real line number for generators.
124 if getattr(frame, 'f_lasti', -1) < 0:
125 self.last_line = -frame.f_code.co_firstlineno
126 else:
127 self.last_line = frame.f_lineno
128 elif event == 'line':
129 # Record an executed line.
130 if self.cur_file_dict is not None:
131 lineno = frame.f_lineno
132 #if frame.f_code.co_filename != self.cur_file_name:
133 # self.log("*", frame.f_code.co_filename, self.cur_file_name, lineno)
134 if self.trace_arcs:
135 self.cur_file_dict[(self.last_line, lineno)] = None
136 else:
137 self.cur_file_dict[lineno] = None
138 self.last_line = lineno
139 elif event == 'return':
140 if self.trace_arcs and self.cur_file_dict:
141 # Record an arc leaving the function, but beware that a
142 # "return" event might just mean yielding from a generator.
143 # Jython seems to have an empty co_code, so just assume return.
144 code = frame.f_code.co_code
145 if (not code) or code[frame.f_lasti] != YIELD_VALUE:
146 first = frame.f_code.co_firstlineno
147 self.cur_file_dict[(self.last_line, -first)] = None
148 # Leaving this function, pop the filename stack.
149 self.cur_file_dict, self.cur_file_name, self.last_line = self.data_stack.pop()
150 elif event == 'exception':
151 self.last_exc_back = frame.f_back
152 self.last_exc_firstlineno = frame.f_code.co_firstlineno
153 return self._trace
154
155 def start(self):
156 """Start this Tracer.
157
158 Return a Python function suitable for use with sys.settrace().
159
160 """
161 self.stopped = False
162 if self.threading:
163 if self.thread is None:
164 self.thread = self.threading.currentThread()
165 else:
166 if self.thread.ident != self.threading.currentThread().ident:
167 # Re-starting from a different thread!? Don't set the trace
168 # function, but we are marked as running again, so maybe it
169 # will be ok?
170 #self.log("~", "starting on different threads")
171 return self._trace
172
173 sys.settrace(self._trace)
174 return self._trace
175
176 def stop(self):
177 """Stop this Tracer."""
178 # Get the activate tracer callback before setting the stop flag to be
179 # able to detect if the tracer was changed prior to stopping it.
180 tf = sys.gettrace()
181
182 # Set the stop flag. The actual call to sys.settrace(None) will happen
183 # in the self._trace callback itself to make sure to call it from the
184 # right thread.
185 self.stopped = True
186
187 if self.threading and self.thread.ident != self.threading.currentThread().ident:
188 # Called on a different thread than started us: we can't unhook
189 # ourselves, but we've set the flag that we should stop, so we
190 # won't do any more tracing.
191 #self.log("~", "stopping on different threads")
192 return
193
194 if self.warn:
195 # PyPy clears the trace function before running atexit functions,
196 # so don't warn if we are in atexit on PyPy and the trace function
197 # has changed to None.
198 dont_warn = (env.PYPY and env.PYPYVERSION >= (5, 4) and self.in_atexit and tf is None)
199 if (not dont_warn) and tf != self._trace:
200 self.warn(
201 "Trace function changed, measurement is likely wrong: %r" % (tf,),
202 slug="trace-changed",
203 )
204
205 def activity(self):
206 """Has there been any activity?"""
207 return self._activity
208
209 def reset_activity(self):
210 """Reset the activity() flag."""
211 self._activity = False
212
213 def get_stats(self):
214 """Return a dictionary of statistics, or None."""
215 return None

eric ide

mercurial