| 1 |
from __future__ import generators |
| 2 |
import sys |
| 3 |
import inspect, tokenize |
| 4 |
import py |
| 5 |
from types import ModuleType |
| 6 |
cpy_compile = compile |
| 7 |
|
| 8 |
try: |
| 9 |
import _ast |
| 10 |
from _ast import PyCF_ONLY_AST as _AST_FLAG |
| 11 |
except ImportError: |
| 12 |
_AST_FLAG = 0 |
| 13 |
_ast = None |
| 14 |
|
| 15 |
|
| 16 |
class Source(object): |
| 17 |
""" a immutable object holding a source code fragment, |
| 18 |
possibly deindenting it. |
| 19 |
""" |
| 20 |
_compilecounter = 0 |
| 21 |
def __init__(self, *parts, **kwargs): |
| 22 |
self.lines = lines = [] |
| 23 |
de = kwargs.get('deindent', True) |
| 24 |
rstrip = kwargs.get('rstrip', True) |
| 25 |
for part in parts: |
| 26 |
if not part: |
| 27 |
partlines = [] |
| 28 |
if isinstance(part, Source): |
| 29 |
partlines = part.lines |
| 30 |
elif isinstance(part, (tuple, list)): |
| 31 |
partlines = [x.rstrip("\n") for x in part] |
| 32 |
elif isinstance(part, py.builtin._basestring): |
| 33 |
partlines = part.split('\n') |
| 34 |
if rstrip: |
| 35 |
while partlines: |
| 36 |
if partlines[-1].strip(): |
| 37 |
break |
| 38 |
partlines.pop() |
| 39 |
else: |
| 40 |
partlines = getsource(part, deindent=de).lines |
| 41 |
if de: |
| 42 |
partlines = deindent(partlines) |
| 43 |
lines.extend(partlines) |
| 44 |
|
| 45 |
def __eq__(self, other): |
| 46 |
try: |
| 47 |
return self.lines == other.lines |
| 48 |
except AttributeError: |
| 49 |
if isinstance(other, str): |
| 50 |
return str(self) == other |
| 51 |
return False |
| 52 |
|
| 53 |
def __getitem__(self, key): |
| 54 |
if isinstance(key, int): |
| 55 |
return self.lines[key] |
| 56 |
else: |
| 57 |
if key.step not in (None, 1): |
| 58 |
raise IndexError("cannot slice a Source with a step") |
| 59 |
return self.__getslice__(key.start, key.stop) |
| 60 |
|
| 61 |
def __len__(self): |
| 62 |
return len(self.lines) |
| 63 |
|
| 64 |
def __getslice__(self, start, end): |
| 65 |
newsource = Source() |
| 66 |
newsource.lines = self.lines[start:end] |
| 67 |
return newsource |
| 68 |
|
| 69 |
def strip(self): |
| 70 |
""" return new source object with trailing |
| 71 |
and leading blank lines removed. |
| 72 |
""" |
| 73 |
start, end = 0, len(self) |
| 74 |
while start < end and not self.lines[start].strip(): |
| 75 |
start += 1 |
| 76 |
while end > start and not self.lines[end-1].strip(): |
| 77 |
end -= 1 |
| 78 |
source = Source() |
| 79 |
source.lines[:] = self.lines[start:end] |
| 80 |
return source |
| 81 |
|
| 82 |
def putaround(self, before='', after='', indent=' ' * 4): |
| 83 |
""" return a copy of the source object with |
| 84 |
'before' and 'after' wrapped around it. |
| 85 |
""" |
| 86 |
before = Source(before) |
| 87 |
after = Source(after) |
| 88 |
newsource = Source() |
| 89 |
lines = [ (indent + line) for line in self.lines] |
| 90 |
newsource.lines = before.lines + lines + after.lines |
| 91 |
return newsource |
| 92 |
|
| 93 |
def indent(self, indent=' ' * 4): |
| 94 |
""" return a copy of the source object with |
| 95 |
all lines indented by the given indent-string. |
| 96 |
""" |
| 97 |
newsource = Source() |
| 98 |
newsource.lines = [(indent+line) for line in self.lines] |
| 99 |
return newsource |
| 100 |
|
| 101 |
def getstatement(self, lineno, assertion=False): |
| 102 |
""" return Source statement which contains the |
| 103 |
given linenumber (counted from 0). |
| 104 |
""" |
| 105 |
start, end = self.getstatementrange(lineno, assertion) |
| 106 |
return self[start:end] |
| 107 |
|
| 108 |
def getstatementrange(self, lineno, assertion=False): |
| 109 |
""" return (start, end) tuple which spans the minimal |
| 110 |
statement region which containing the given lineno. |
| 111 |
""" |
| 112 |
if not (0 <= lineno < len(self)): |
| 113 |
raise IndexError("lineno out of range") |
| 114 |
ast, start, end = getstatementrange_ast(lineno, self) |
| 115 |
return start, end |
| 116 |
|
| 117 |
def deindent(self, offset=None): |
| 118 |
""" return a new source object deindented by offset. |
| 119 |
If offset is None then guess an indentation offset from |
| 120 |
the first non-blank line. Subsequent lines which have a |
| 121 |
lower indentation offset will be copied verbatim as |
| 122 |
they are assumed to be part of multilines. |
| 123 |
""" |
| 124 |
|
| 125 |
|
| 126 |
newsource = Source() |
| 127 |
newsource.lines[:] = deindent(self.lines, offset) |
| 128 |
return newsource |
| 129 |
|
| 130 |
def isparseable(self, deindent=True): |
| 131 |
""" return True if source is parseable, heuristically |
| 132 |
deindenting it by default. |
| 133 |
""" |
| 134 |
try: |
| 135 |
import parser |
| 136 |
except ImportError: |
| 137 |
syntax_checker = lambda x: compile(x, 'asd', 'exec') |
| 138 |
else: |
| 139 |
syntax_checker = parser.suite |
| 140 |
|
| 141 |
if deindent: |
| 142 |
source = str(self.deindent()) |
| 143 |
else: |
| 144 |
source = str(self) |
| 145 |
try: |
| 146 |
|
| 147 |
syntax_checker(source+'\n') |
| 148 |
except KeyboardInterrupt: |
| 149 |
raise |
| 150 |
except Exception: |
| 151 |
return False |
| 152 |
else: |
| 153 |
return True |
| 154 |
|
| 155 |
def __str__(self): |
| 156 |
return "\n".join(self.lines) |
| 157 |
|
| 158 |
def compile(self, filename=None, mode='exec', |
| 159 |
flag=generators.compiler_flag, |
| 160 |
dont_inherit=0, _genframe=None): |
| 161 |
""" return compiled code object. if filename is None |
| 162 |
invent an artificial filename which displays |
| 163 |
the source/line position of the caller frame. |
| 164 |
""" |
| 165 |
if not filename or py.path.local(filename).check(file=0): |
| 166 |
if _genframe is None: |
| 167 |
_genframe = sys._getframe(1) |
| 168 |
fn,lineno = _genframe.f_code.co_filename, _genframe.f_lineno |
| 169 |
base = "<%d-codegen " % self._compilecounter |
| 170 |
self.__class__._compilecounter += 1 |
| 171 |
if not filename: |
| 172 |
filename = base + '%s:%d>' % (fn, lineno) |
| 173 |
else: |
| 174 |
filename = base + '%r %s:%d>' % (filename, fn, lineno) |
| 175 |
source = "\n".join(self.lines) + '\n' |
| 176 |
try: |
| 177 |
co = cpy_compile(source, filename, mode, flag) |
| 178 |
except SyntaxError: |
| 179 |
ex = sys.exc_info()[1] |
| 180 |
|
| 181 |
msglines = self.lines[:ex.lineno] |
| 182 |
if ex.offset: |
| 183 |
msglines.append(" "*ex.offset + '^') |
| 184 |
msglines.append("(code was compiled probably from here: %s)" % filename) |
| 185 |
newex = SyntaxError('\n'.join(msglines)) |
| 186 |
newex.offset = ex.offset |
| 187 |
newex.lineno = ex.lineno |
| 188 |
newex.text = ex.text |
| 189 |
raise newex |
| 190 |
else: |
| 191 |
if flag & _AST_FLAG: |
| 192 |
return co |
| 193 |
lines = [(x + "\n") for x in self.lines] |
| 194 |
if sys.version_info[0] >= 3: |
| 195 |
|
| 196 |
|
| 197 |
|
| 198 |
m = ModuleType("_pycodecompile_pseudo_module") |
| 199 |
py.std.inspect.modulesbyfile[filename] = None |
| 200 |
py.std.sys.modules[None] = m |
| 201 |
m.__loader__ = 1 |
| 202 |
py.std.linecache.cache[filename] = (1, None, lines, filename) |
| 203 |
return co |
| 204 |
|
| 205 |
|
| 206 |
|
| 207 |
|
| 208 |
|
| 209 |
def compile_(source, filename=None, mode='exec', flags= |
| 210 |
generators.compiler_flag, dont_inherit=0): |
| 211 |
""" compile the given source to a raw code object, |
| 212 |
and maintain an internal cache which allows later |
| 213 |
retrieval of the source code for the code object |
| 214 |
and any recursively created code objects. |
| 215 |
""" |
| 216 |
if _ast is not None and isinstance(source, _ast.AST): |
| 217 |
|
| 218 |
return cpy_compile(source, filename, mode, flags, dont_inherit) |
| 219 |
_genframe = sys._getframe(1) |
| 220 |
s = Source(source) |
| 221 |
co = s.compile(filename, mode, flags, _genframe=_genframe) |
| 222 |
return co |
| 223 |
|
| 224 |
|
| 225 |
def getfslineno(obj): |
| 226 |
""" Return source location (path, lineno) for the given object. |
| 227 |
If the source cannot be determined return ("", -1) |
| 228 |
""" |
| 229 |
try: |
| 230 |
code = py.code.Code(obj) |
| 231 |
except TypeError: |
| 232 |
try: |
| 233 |
fn = (py.std.inspect.getsourcefile(obj) or |
| 234 |
py.std.inspect.getfile(obj)) |
| 235 |
except TypeError: |
| 236 |
return "", -1 |
| 237 |
|
| 238 |
fspath = fn and py.path.local(fn) or None |
| 239 |
lineno = -1 |
| 240 |
if fspath: |
| 241 |
try: |
| 242 |
_, lineno = findsource(obj) |
| 243 |
except IOError: |
| 244 |
pass |
| 245 |
else: |
| 246 |
fspath = code.path |
| 247 |
lineno = code.firstlineno |
| 248 |
assert isinstance(lineno, int) |
| 249 |
return fspath, lineno |
| 250 |
|
| 251 |
|
| 252 |
|
| 253 |
|
| 254 |
|
| 255 |
def findsource(obj): |
| 256 |
try: |
| 257 |
sourcelines, lineno = py.std.inspect.findsource(obj) |
| 258 |
except py.builtin._sysex: |
| 259 |
raise |
| 260 |
except: |
| 261 |
return None, -1 |
| 262 |
source = Source() |
| 263 |
source.lines = [line.rstrip() for line in sourcelines] |
| 264 |
return source, lineno |
| 265 |
|
| 266 |
def getsource(obj, **kwargs): |
| 267 |
obj = py.code.getrawcode(obj) |
| 268 |
try: |
| 269 |
strsrc = inspect.getsource(obj) |
| 270 |
except IndentationError: |
| 271 |
strsrc = "\"Buggy python version consider upgrading, cannot get source\"" |
| 272 |
assert isinstance(strsrc, str) |
| 273 |
return Source(strsrc, **kwargs) |
| 274 |
|
| 275 |
def deindent(lines, offset=None): |
| 276 |
if offset is None: |
| 277 |
for line in lines: |
| 278 |
line = line.expandtabs() |
| 279 |
s = line.lstrip() |
| 280 |
if s: |
| 281 |
offset = len(line)-len(s) |
| 282 |
break |
| 283 |
else: |
| 284 |
offset = 0 |
| 285 |
if offset == 0: |
| 286 |
return list(lines) |
| 287 |
newlines = [] |
| 288 |
def readline_generator(lines): |
| 289 |
for line in lines: |
| 290 |
yield line + '\n' |
| 291 |
while True: |
| 292 |
yield '' |
| 293 |
|
| 294 |
it = readline_generator(lines) |
| 295 |
|
| 296 |
try: |
| 297 |
for _, _, (sline, _), (eline, _), _ in tokenize.generate_tokens(lambda: next(it)): |
| 298 |
if sline > len(lines): |
| 299 |
break |
| 300 |
if sline > len(newlines): |
| 301 |
line = lines[sline - 1].expandtabs() |
| 302 |
if line.lstrip() and line[:offset].isspace(): |
| 303 |
line = line[offset:] |
| 304 |
newlines.append(line) |
| 305 |
|
| 306 |
for i in range(sline, eline): |
| 307 |
|
| 308 |
|
| 309 |
newlines.append(lines[i]) |
| 310 |
except (IndentationError, tokenize.TokenError): |
| 311 |
pass |
| 312 |
|
| 313 |
newlines.extend(lines[len(newlines):]) |
| 314 |
return newlines |
| 315 |
|
| 316 |
|
| 317 |
def get_statement_startend(lineno, nodelist): |
| 318 |
from bisect import bisect_right |
| 319 |
|
| 320 |
nextlineno = None |
| 321 |
while 1: |
| 322 |
lineno_list = [x.lineno-1 for x in nodelist] |
| 323 |
|
| 324 |
insert_index = bisect_right(lineno_list, lineno) |
| 325 |
if insert_index >= len(nodelist): |
| 326 |
insert_index -= 1 |
| 327 |
elif lineno < (nodelist[insert_index].lineno - 1) and insert_index > 0: |
| 328 |
insert_index -= 1 |
| 329 |
assert lineno >= (nodelist[insert_index].lineno - 1) |
| 330 |
nextnode = nodelist[insert_index] |
| 331 |
|
| 332 |
try: |
| 333 |
nextlineno = nodelist[insert_index+1].lineno - 1 |
| 334 |
except IndexError: |
| 335 |
pass |
| 336 |
lastnodelist = nodelist |
| 337 |
nodelist = getnodelist(nextnode) |
| 338 |
if not nodelist: |
| 339 |
start, end = nextnode.lineno-1, nextlineno |
| 340 |
start = min(lineno, start) |
| 341 |
assert start <= lineno and (end is None or lineno < end) |
| 342 |
return start, end |
| 343 |
|
| 344 |
def getnodelist(node): |
| 345 |
import _ast |
| 346 |
l = [] |
| 347 |
|
| 348 |
for subname in "test", "type", "body", "handlers", "orelse", "finalbody": |
| 349 |
attr = getattr(node, subname, None) |
| 350 |
if attr is not None: |
| 351 |
if isinstance(attr, list): |
| 352 |
l.extend(attr) |
| 353 |
elif hasattr(attr, "lineno"): |
| 354 |
l.append(attr) |
| 355 |
return l |
| 356 |
|
| 357 |
def getstatementrange_ast(lineno, source, assertion=False, astnode=None): |
| 358 |
if astnode is None: |
| 359 |
content = str(source) |
| 360 |
if sys.version_info < (2,7): |
| 361 |
content += "\n" |
| 362 |
try: |
| 363 |
astnode = compile(content, "source", "exec", 1024) |
| 364 |
except ValueError: |
| 365 |
start, end = getstatementrange_old(lineno, source, assertion) |
| 366 |
return None, start, end |
| 367 |
start, end = get_statement_startend(lineno, getnodelist(astnode)) |
| 368 |
|
| 369 |
|
| 370 |
|
| 371 |
|
| 372 |
|
| 373 |
if end is None: |
| 374 |
end = len(source.lines) |
| 375 |
|
| 376 |
if end > start + 1: |
| 377 |
|
| 378 |
|
| 379 |
block_finder = inspect.BlockFinder() |
| 380 |
|
| 381 |
block_finder.started = source.lines[start][0].isspace() |
| 382 |
it = ((x + "\n") for x in source.lines[start:end]) |
| 383 |
try: |
| 384 |
for tok in tokenize.generate_tokens(lambda: next(it)): |
| 385 |
block_finder.tokeneater(*tok) |
| 386 |
except (inspect.EndOfBlock, IndentationError) as e: |
| 387 |
end = block_finder.last + start |
| 388 |
|
| 389 |
|
| 390 |
|
| 391 |
|
| 392 |
while end: |
| 393 |
line = source.lines[end - 1].lstrip() |
| 394 |
if line.startswith("#"): |
| 395 |
end -= 1 |
| 396 |
else: |
| 397 |
break |
| 398 |
return astnode, start, end |
| 399 |
|
| 400 |
|
| 401 |
def getstatementrange_old(lineno, source, assertion=False): |
| 402 |
""" return (start, end) tuple which spans the minimal |
| 403 |
statement region which containing the given lineno. |
| 404 |
raise an IndexError if no such statementrange can be found. |
| 405 |
""" |
| 406 |
|
| 407 |
|
| 408 |
from codeop import compile_command |
| 409 |
for start in range(lineno, -1, -1): |
| 410 |
if assertion: |
| 411 |
line = source.lines[start] |
| 412 |
|
| 413 |
if 'super' in line and 'self' in line and '__init__' in line: |
| 414 |
raise IndexError("likely a subclass") |
| 415 |
if "assert" not in line and "raise" not in line: |
| 416 |
continue |
| 417 |
trylines = source.lines[start:lineno+1] |
| 418 |
|
| 419 |
|
| 420 |
trylines.insert(0, 'def xxx():') |
| 421 |
trysource = '\n '.join(trylines) |
| 422 |
|
| 423 |
try: |
| 424 |
compile_command(trysource) |
| 425 |
except (SyntaxError, OverflowError, ValueError): |
| 426 |
continue |
| 427 |
|
| 428 |
|
| 429 |
for end in range(lineno+1, len(source)+1): |
| 430 |
trysource = source[start:end] |
| 431 |
if trysource.isparseable(): |
| 432 |
return start, end |
| 433 |
raise SyntaxError("no valid source range around line %d " % (lineno,)) |
| 434 |
|
| 435 |
|