paul@0 | 1 | #!/usr/bin/env python |
paul@0 | 2 | |
paul@0 | 3 | """ |
paul@0 | 4 | Common functions. |
paul@0 | 5 | |
paul@0 | 6 | Copyright (C) 2007, 2008, 2009, 2010, 2011, 2012, 2013, |
paul@508 | 7 | 2014, 2015, 2016, 2017 Paul Boddie <paul@boddie.org.uk> |
paul@0 | 8 | |
paul@0 | 9 | This program is free software; you can redistribute it and/or modify it under |
paul@0 | 10 | the terms of the GNU General Public License as published by the Free Software |
paul@0 | 11 | Foundation; either version 3 of the License, or (at your option) any later |
paul@0 | 12 | version. |
paul@0 | 13 | |
paul@0 | 14 | This program is distributed in the hope that it will be useful, but WITHOUT |
paul@0 | 15 | ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS |
paul@0 | 16 | FOR A PARTICULAR PURPOSE. See the GNU General Public License for more |
paul@0 | 17 | details. |
paul@0 | 18 | |
paul@0 | 19 | You should have received a copy of the GNU General Public License along with |
paul@0 | 20 | this program. If not, see <http://www.gnu.org/licenses/>. |
paul@0 | 21 | """ |
paul@0 | 22 | |
paul@512 | 23 | from compiler.transformer import Transformer |
paul@430 | 24 | from errors import InspectError |
paul@0 | 25 | from os import listdir, makedirs, remove |
paul@609 | 26 | from os.path import exists, getmtime, isdir, join, split |
paul@11 | 27 | from results import ConstantValueRef, LiteralSequenceRef, NameRef |
paul@405 | 28 | import compiler.ast |
paul@0 | 29 | |
paul@0 | 30 | class CommonOutput: |
paul@0 | 31 | |
paul@0 | 32 | "Common output functionality." |
paul@0 | 33 | |
paul@0 | 34 | def check_output(self): |
paul@0 | 35 | |
paul@0 | 36 | "Check the existing output and remove it if irrelevant." |
paul@0 | 37 | |
paul@0 | 38 | if not exists(self.output): |
paul@0 | 39 | makedirs(self.output) |
paul@0 | 40 | |
paul@0 | 41 | details = self.importer.get_cache_details() |
paul@0 | 42 | recorded_details = self.get_output_details() |
paul@0 | 43 | |
paul@0 | 44 | if recorded_details != details: |
paul@0 | 45 | self.remove_output() |
paul@0 | 46 | |
paul@0 | 47 | writefile(self.get_output_details_filename(), details) |
paul@0 | 48 | |
paul@0 | 49 | def get_output_details_filename(self): |
paul@0 | 50 | |
paul@0 | 51 | "Return the output details filename." |
paul@0 | 52 | |
paul@0 | 53 | return join(self.output, "$details") |
paul@0 | 54 | |
paul@0 | 55 | def get_output_details(self): |
paul@0 | 56 | |
paul@0 | 57 | "Return details of the existing output." |
paul@0 | 58 | |
paul@0 | 59 | details_filename = self.get_output_details_filename() |
paul@0 | 60 | |
paul@0 | 61 | if not exists(details_filename): |
paul@0 | 62 | return None |
paul@0 | 63 | else: |
paul@0 | 64 | return readfile(details_filename) |
paul@0 | 65 | |
paul@0 | 66 | def remove_output(self, dirname=None): |
paul@0 | 67 | |
paul@0 | 68 | "Remove the output." |
paul@0 | 69 | |
paul@0 | 70 | dirname = dirname or self.output |
paul@0 | 71 | |
paul@0 | 72 | for filename in listdir(dirname): |
paul@0 | 73 | path = join(dirname, filename) |
paul@0 | 74 | if isdir(path): |
paul@0 | 75 | self.remove_output(path) |
paul@0 | 76 | else: |
paul@0 | 77 | remove(path) |
paul@0 | 78 | |
paul@609 | 79 | def copy(source, target, only_if_newer=True): |
paul@609 | 80 | |
paul@609 | 81 | "Copy a text file from 'source' to 'target'." |
paul@609 | 82 | |
paul@609 | 83 | if isdir(target): |
paul@609 | 84 | target = join(target, split(source)[-1]) |
paul@609 | 85 | |
paul@609 | 86 | if only_if_newer and not is_newer(source, target): |
paul@609 | 87 | return |
paul@609 | 88 | |
paul@609 | 89 | infile = open(source) |
paul@609 | 90 | outfile = open(target, "w") |
paul@609 | 91 | |
paul@609 | 92 | try: |
paul@609 | 93 | outfile.write(infile.read()) |
paul@609 | 94 | finally: |
paul@609 | 95 | outfile.close() |
paul@609 | 96 | infile.close() |
paul@609 | 97 | |
paul@609 | 98 | def is_newer(source, target): |
paul@609 | 99 | |
paul@609 | 100 | "Return whether 'source' is newer than 'target'." |
paul@609 | 101 | |
paul@609 | 102 | if exists(target): |
paul@609 | 103 | target_mtime = getmtime(target) |
paul@609 | 104 | source_mtime = getmtime(source) |
paul@609 | 105 | return source_mtime > target_mtime |
paul@609 | 106 | |
paul@609 | 107 | return True |
paul@609 | 108 | |
paul@0 | 109 | class CommonModule: |
paul@0 | 110 | |
paul@0 | 111 | "A common module representation." |
paul@0 | 112 | |
paul@0 | 113 | def __init__(self, name, importer): |
paul@0 | 114 | |
paul@0 | 115 | """ |
paul@0 | 116 | Initialise this module with the given 'name' and an 'importer' which is |
paul@0 | 117 | used to provide access to other modules when required. |
paul@0 | 118 | """ |
paul@0 | 119 | |
paul@0 | 120 | self.name = name |
paul@0 | 121 | self.importer = importer |
paul@0 | 122 | self.filename = None |
paul@0 | 123 | |
paul@0 | 124 | # Inspection-related attributes. |
paul@0 | 125 | |
paul@0 | 126 | self.astnode = None |
paul@405 | 127 | self.encoding = None |
paul@0 | 128 | self.iterators = {} |
paul@0 | 129 | self.temp = {} |
paul@0 | 130 | self.lambdas = {} |
paul@0 | 131 | |
paul@0 | 132 | # Constants, literals and values. |
paul@0 | 133 | |
paul@0 | 134 | self.constants = {} |
paul@0 | 135 | self.constant_values = {} |
paul@0 | 136 | self.literals = {} |
paul@0 | 137 | self.literal_types = {} |
paul@0 | 138 | |
paul@0 | 139 | # Nested namespaces. |
paul@0 | 140 | |
paul@0 | 141 | self.namespace_path = [] |
paul@0 | 142 | self.in_function = False |
paul@0 | 143 | |
paul@124 | 144 | # Retain the assignment value expression and track invocations. |
paul@124 | 145 | |
paul@124 | 146 | self.in_assignment = None |
paul@553 | 147 | self.in_invocation = None |
paul@124 | 148 | |
paul@124 | 149 | # Attribute chain state management. |
paul@0 | 150 | |
paul@0 | 151 | self.attrs = [] |
paul@124 | 152 | self.chain_assignment = [] |
paul@124 | 153 | self.chain_invocation = [] |
paul@0 | 154 | |
paul@0 | 155 | def __repr__(self): |
paul@0 | 156 | return "CommonModule(%r, %r)" % (self.name, self.importer) |
paul@0 | 157 | |
paul@0 | 158 | def parse_file(self, filename): |
paul@0 | 159 | |
paul@0 | 160 | "Parse the file with the given 'filename', initialising attributes." |
paul@0 | 161 | |
paul@0 | 162 | self.filename = filename |
paul@405 | 163 | |
paul@405 | 164 | # Use the Transformer directly to obtain encoding information. |
paul@405 | 165 | |
paul@405 | 166 | t = Transformer() |
paul@405 | 167 | f = open(filename) |
paul@405 | 168 | |
paul@405 | 169 | try: |
paul@405 | 170 | self.astnode = t.parsesuite(f.read() + "\n") |
paul@405 | 171 | self.encoding = t.encoding |
paul@405 | 172 | finally: |
paul@405 | 173 | f.close() |
paul@0 | 174 | |
paul@0 | 175 | # Module-relative naming. |
paul@0 | 176 | |
paul@0 | 177 | def get_global_path(self, name): |
paul@0 | 178 | return "%s.%s" % (self.name, name) |
paul@0 | 179 | |
paul@0 | 180 | def get_namespace_path(self): |
paul@0 | 181 | return ".".join([self.name] + self.namespace_path) |
paul@0 | 182 | |
paul@0 | 183 | def get_object_path(self, name): |
paul@0 | 184 | return ".".join([self.name] + self.namespace_path + [name]) |
paul@0 | 185 | |
paul@0 | 186 | def get_parent_path(self): |
paul@0 | 187 | return ".".join([self.name] + self.namespace_path[:-1]) |
paul@0 | 188 | |
paul@0 | 189 | # Namespace management. |
paul@0 | 190 | |
paul@0 | 191 | def enter_namespace(self, name): |
paul@0 | 192 | |
paul@0 | 193 | "Enter the namespace having the given 'name'." |
paul@0 | 194 | |
paul@0 | 195 | self.namespace_path.append(name) |
paul@0 | 196 | |
paul@0 | 197 | def exit_namespace(self): |
paul@0 | 198 | |
paul@0 | 199 | "Exit the current namespace." |
paul@0 | 200 | |
paul@0 | 201 | self.namespace_path.pop() |
paul@0 | 202 | |
paul@0 | 203 | # Constant reference naming. |
paul@0 | 204 | |
paul@406 | 205 | def get_constant_name(self, value, value_type, encoding=None): |
paul@0 | 206 | |
paul@397 | 207 | """ |
paul@397 | 208 | Add a new constant to the current namespace for 'value' with |
paul@397 | 209 | 'value_type'. |
paul@397 | 210 | """ |
paul@0 | 211 | |
paul@0 | 212 | path = self.get_namespace_path() |
paul@0 | 213 | init_item(self.constants, path, dict) |
paul@406 | 214 | return "$c%d" % add_counter_item(self.constants[path], (value, value_type, encoding)) |
paul@0 | 215 | |
paul@0 | 216 | # Literal reference naming. |
paul@0 | 217 | |
paul@0 | 218 | def get_literal_name(self): |
paul@0 | 219 | |
paul@0 | 220 | "Add a new literal to the current namespace." |
paul@0 | 221 | |
paul@0 | 222 | path = self.get_namespace_path() |
paul@0 | 223 | init_item(self.literals, path, lambda: 0) |
paul@0 | 224 | return "$C%d" % self.literals[path] |
paul@0 | 225 | |
paul@0 | 226 | def next_literal(self): |
paul@0 | 227 | self.literals[self.get_namespace_path()] += 1 |
paul@0 | 228 | |
paul@0 | 229 | # Temporary iterator naming. |
paul@0 | 230 | |
paul@0 | 231 | def get_iterator_path(self): |
paul@0 | 232 | return self.in_function and self.get_namespace_path() or self.name |
paul@0 | 233 | |
paul@0 | 234 | def get_iterator_name(self): |
paul@0 | 235 | path = self.get_iterator_path() |
paul@0 | 236 | init_item(self.iterators, path, lambda: 0) |
paul@0 | 237 | return "$i%d" % self.iterators[path] |
paul@0 | 238 | |
paul@0 | 239 | def next_iterator(self): |
paul@0 | 240 | self.iterators[self.get_iterator_path()] += 1 |
paul@0 | 241 | |
paul@0 | 242 | # Temporary variable naming. |
paul@0 | 243 | |
paul@0 | 244 | def get_temporary_name(self): |
paul@0 | 245 | path = self.get_namespace_path() |
paul@0 | 246 | init_item(self.temp, path, lambda: 0) |
paul@0 | 247 | return "$t%d" % self.temp[path] |
paul@0 | 248 | |
paul@0 | 249 | def next_temporary(self): |
paul@0 | 250 | self.temp[self.get_namespace_path()] += 1 |
paul@0 | 251 | |
paul@0 | 252 | # Arbitrary function naming. |
paul@0 | 253 | |
paul@0 | 254 | def get_lambda_name(self): |
paul@0 | 255 | path = self.get_namespace_path() |
paul@0 | 256 | init_item(self.lambdas, path, lambda: 0) |
paul@0 | 257 | name = "$l%d" % self.lambdas[path] |
paul@0 | 258 | self.lambdas[path] += 1 |
paul@0 | 259 | return name |
paul@0 | 260 | |
paul@0 | 261 | def reset_lambdas(self): |
paul@0 | 262 | self.lambdas = {} |
paul@0 | 263 | |
paul@0 | 264 | # Constant and literal recording. |
paul@0 | 265 | |
paul@537 | 266 | def get_constant_value(self, value, literals=None): |
paul@394 | 267 | |
paul@406 | 268 | """ |
paul@406 | 269 | Encode the 'value' if appropriate, returning a value, a typename and any |
paul@406 | 270 | encoding. |
paul@406 | 271 | """ |
paul@394 | 272 | |
paul@394 | 273 | if isinstance(value, unicode): |
paul@406 | 274 | return value.encode("utf-8"), "unicode", self.encoding |
paul@405 | 275 | |
paul@405 | 276 | # Attempt to convert plain strings to text. |
paul@405 | 277 | |
paul@405 | 278 | elif isinstance(value, str) and self.encoding: |
paul@513 | 279 | try: |
paul@537 | 280 | return get_string_details(literals, self.encoding) |
paul@513 | 281 | except UnicodeDecodeError: |
paul@513 | 282 | pass |
paul@405 | 283 | |
paul@406 | 284 | return value, value.__class__.__name__, None |
paul@394 | 285 | |
paul@406 | 286 | def get_constant_reference(self, ref, value, encoding=None): |
paul@0 | 287 | |
paul@406 | 288 | """ |
paul@406 | 289 | Return a constant reference for the given 'ref' type and 'value', with |
paul@406 | 290 | the optional 'encoding' applying to text values. |
paul@406 | 291 | """ |
paul@0 | 292 | |
paul@406 | 293 | constant_name = self.get_constant_name(value, ref.get_origin(), encoding) |
paul@0 | 294 | |
paul@0 | 295 | # Return a reference for the constant. |
paul@0 | 296 | |
paul@0 | 297 | objpath = self.get_object_path(constant_name) |
paul@338 | 298 | name_ref = ConstantValueRef(constant_name, ref.instance_of(objpath), value) |
paul@0 | 299 | |
paul@0 | 300 | # Record the value and type for the constant. |
paul@0 | 301 | |
paul@406 | 302 | self._reserve_constant(objpath, name_ref.value, name_ref.get_origin(), encoding) |
paul@0 | 303 | return name_ref |
paul@0 | 304 | |
paul@406 | 305 | def reserve_constant(self, objpath, value, origin, encoding=None): |
paul@251 | 306 | |
paul@251 | 307 | """ |
paul@251 | 308 | Reserve a constant within 'objpath' with the given 'value' and having a |
paul@406 | 309 | type with the given 'origin', with the optional 'encoding' applying to |
paul@406 | 310 | text values. |
paul@251 | 311 | """ |
paul@251 | 312 | |
paul@397 | 313 | constant_name = self.get_constant_name(value, origin) |
paul@251 | 314 | objpath = self.get_object_path(constant_name) |
paul@406 | 315 | self._reserve_constant(objpath, value, origin, encoding) |
paul@251 | 316 | |
paul@406 | 317 | def _reserve_constant(self, objpath, value, origin, encoding): |
paul@251 | 318 | |
paul@406 | 319 | """ |
paul@406 | 320 | Store a constant for 'objpath' with the given 'value' and 'origin', with |
paul@406 | 321 | the optional 'encoding' applying to text values. |
paul@406 | 322 | """ |
paul@251 | 323 | |
paul@406 | 324 | self.constant_values[objpath] = value, origin, encoding |
paul@251 | 325 | |
paul@0 | 326 | def get_literal_reference(self, name, ref, items, cls): |
paul@0 | 327 | |
paul@11 | 328 | """ |
paul@11 | 329 | Return a literal reference for the given type 'name', literal 'ref', |
paul@11 | 330 | node 'items' and employing the given 'cls' as the class of the returned |
paul@11 | 331 | reference object. |
paul@11 | 332 | """ |
paul@11 | 333 | |
paul@0 | 334 | # Construct an invocation using the items as arguments. |
paul@0 | 335 | |
paul@0 | 336 | typename = "$L%s" % name |
paul@0 | 337 | |
paul@0 | 338 | invocation = compiler.ast.CallFunc( |
paul@0 | 339 | compiler.ast.Name(typename), |
paul@0 | 340 | items |
paul@0 | 341 | ) |
paul@0 | 342 | |
paul@0 | 343 | # Get a name for the actual literal. |
paul@0 | 344 | |
paul@0 | 345 | instname = self.get_literal_name() |
paul@0 | 346 | self.next_literal() |
paul@0 | 347 | |
paul@0 | 348 | # Record the type for the literal. |
paul@0 | 349 | |
paul@0 | 350 | objpath = self.get_object_path(instname) |
paul@0 | 351 | self.literal_types[objpath] = ref.get_origin() |
paul@0 | 352 | |
paul@0 | 353 | # Return a wrapper for the invocation exposing the items. |
paul@0 | 354 | |
paul@0 | 355 | return cls( |
paul@0 | 356 | instname, |
paul@0 | 357 | ref.instance_of(), |
paul@0 | 358 | self.process_structure_node(invocation), |
paul@0 | 359 | invocation.args |
paul@0 | 360 | ) |
paul@0 | 361 | |
paul@0 | 362 | # Node handling. |
paul@0 | 363 | |
paul@0 | 364 | def process_structure(self, node): |
paul@0 | 365 | |
paul@0 | 366 | """ |
paul@0 | 367 | Within the given 'node', process the program structure. |
paul@0 | 368 | |
paul@0 | 369 | During inspection, this will process global declarations, adjusting the |
paul@0 | 370 | module namespace, and import statements, building a module dependency |
paul@0 | 371 | hierarchy. |
paul@0 | 372 | |
paul@0 | 373 | During translation, this will consult deduced program information and |
paul@0 | 374 | output translated code. |
paul@0 | 375 | """ |
paul@0 | 376 | |
paul@0 | 377 | l = [] |
paul@0 | 378 | for n in node.getChildNodes(): |
paul@0 | 379 | l.append(self.process_structure_node(n)) |
paul@0 | 380 | return l |
paul@0 | 381 | |
paul@0 | 382 | def process_augassign_node(self, n): |
paul@0 | 383 | |
paul@0 | 384 | "Process the given augmented assignment node 'n'." |
paul@0 | 385 | |
paul@0 | 386 | op = operator_functions[n.op] |
paul@0 | 387 | |
paul@0 | 388 | if isinstance(n.node, compiler.ast.Getattr): |
paul@0 | 389 | target = compiler.ast.AssAttr(n.node.expr, n.node.attrname, "OP_ASSIGN") |
paul@0 | 390 | elif isinstance(n.node, compiler.ast.Name): |
paul@0 | 391 | target = compiler.ast.AssName(n.node.name, "OP_ASSIGN") |
paul@0 | 392 | else: |
paul@0 | 393 | target = n.node |
paul@0 | 394 | |
paul@0 | 395 | assignment = compiler.ast.Assign( |
paul@0 | 396 | [target], |
paul@0 | 397 | compiler.ast.CallFunc( |
paul@0 | 398 | compiler.ast.Name("$op%s" % op), |
paul@0 | 399 | [n.node, n.expr])) |
paul@0 | 400 | |
paul@0 | 401 | return self.process_structure_node(assignment) |
paul@0 | 402 | |
paul@320 | 403 | def process_assignment_for_object(self, original_name, source): |
paul@0 | 404 | |
paul@0 | 405 | """ |
paul@0 | 406 | Return an assignment operation making 'original_name' refer to the given |
paul@196 | 407 | 'source'. |
paul@0 | 408 | """ |
paul@0 | 409 | |
paul@0 | 410 | assignment = compiler.ast.Assign( |
paul@0 | 411 | [compiler.ast.AssName(original_name, "OP_ASSIGN")], |
paul@196 | 412 | source |
paul@0 | 413 | ) |
paul@0 | 414 | |
paul@0 | 415 | return self.process_structure_node(assignment) |
paul@0 | 416 | |
paul@0 | 417 | def process_assignment_node_items(self, n, expr): |
paul@0 | 418 | |
paul@0 | 419 | """ |
paul@0 | 420 | Process the given assignment node 'n' whose children are to be assigned |
paul@0 | 421 | items of 'expr'. |
paul@0 | 422 | """ |
paul@0 | 423 | |
paul@0 | 424 | name_ref = self.process_structure_node(expr) |
paul@0 | 425 | |
paul@509 | 426 | # Either unpack the items and present them directly to each assignment |
paul@509 | 427 | # node. |
paul@509 | 428 | |
paul@509 | 429 | if isinstance(name_ref, LiteralSequenceRef) and \ |
paul@509 | 430 | self.process_literal_sequence_items(n, name_ref): |
paul@0 | 431 | |
paul@509 | 432 | pass |
paul@509 | 433 | |
paul@509 | 434 | # Or have the assignment nodes access each item via the sequence API. |
paul@509 | 435 | |
paul@509 | 436 | else: |
paul@509 | 437 | self.process_assignment_node_items_by_position(n, expr, name_ref) |
paul@0 | 438 | |
paul@0 | 439 | def process_assignment_node_items_by_position(self, n, expr, name_ref): |
paul@0 | 440 | |
paul@0 | 441 | """ |
paul@0 | 442 | Process the given sequence assignment node 'n', converting the node to |
paul@0 | 443 | the separate assignment of each target using positional access on a |
paul@0 | 444 | temporary variable representing the sequence. Use 'expr' as the assigned |
paul@0 | 445 | value and 'name_ref' as the reference providing any existing temporary |
paul@0 | 446 | variable. |
paul@0 | 447 | """ |
paul@0 | 448 | |
paul@0 | 449 | assignments = [] |
paul@0 | 450 | |
paul@508 | 451 | # Employ existing names to access the sequence. |
paul@508 | 452 | # Literal sequences do not provide names of accessible objects. |
paul@508 | 453 | |
paul@508 | 454 | if isinstance(name_ref, NameRef) and not isinstance(name_ref, LiteralSequenceRef): |
paul@0 | 455 | temp = name_ref.name |
paul@508 | 456 | |
paul@508 | 457 | # For other expressions, create a temporary name to reference the items. |
paul@508 | 458 | |
paul@0 | 459 | else: |
paul@0 | 460 | temp = self.get_temporary_name() |
paul@0 | 461 | self.next_temporary() |
paul@0 | 462 | |
paul@0 | 463 | assignments.append( |
paul@0 | 464 | compiler.ast.Assign([compiler.ast.AssName(temp, "OP_ASSIGN")], expr) |
paul@0 | 465 | ) |
paul@0 | 466 | |
paul@508 | 467 | # Assign the items to the target nodes. |
paul@508 | 468 | |
paul@0 | 469 | for i, node in enumerate(n.nodes): |
paul@0 | 470 | assignments.append( |
paul@0 | 471 | compiler.ast.Assign([node], compiler.ast.Subscript( |
paul@395 | 472 | compiler.ast.Name(temp), "OP_APPLY", [compiler.ast.Const(i, str(i))])) |
paul@0 | 473 | ) |
paul@0 | 474 | |
paul@0 | 475 | return self.process_structure_node(compiler.ast.Stmt(assignments)) |
paul@0 | 476 | |
paul@0 | 477 | def process_literal_sequence_items(self, n, name_ref): |
paul@0 | 478 | |
paul@0 | 479 | """ |
paul@0 | 480 | Process the given assignment node 'n', obtaining from the given |
paul@0 | 481 | 'name_ref' the items to be assigned to the assignment targets. |
paul@509 | 482 | |
paul@509 | 483 | Return whether this method was able to process the assignment node as |
paul@509 | 484 | a sequence of direct assignments. |
paul@0 | 485 | """ |
paul@0 | 486 | |
paul@0 | 487 | if len(n.nodes) == len(name_ref.items): |
paul@509 | 488 | assigned_names, count = get_names_from_nodes(n.nodes) |
paul@509 | 489 | accessed_names, _count = get_names_from_nodes(name_ref.items) |
paul@509 | 490 | |
paul@509 | 491 | # Only assign directly between items if all assigned names are |
paul@509 | 492 | # plain names (not attribute assignments), and if the assigned names |
paul@509 | 493 | # do not appear in the accessed names. |
paul@509 | 494 | |
paul@509 | 495 | if len(assigned_names) == count and \ |
paul@509 | 496 | not assigned_names.intersection(accessed_names): |
paul@509 | 497 | |
paul@509 | 498 | for node, item in zip(n.nodes, name_ref.items): |
paul@509 | 499 | self.process_assignment_node(node, item) |
paul@509 | 500 | |
paul@509 | 501 | return True |
paul@509 | 502 | |
paul@509 | 503 | # Otherwise, use the position-based mechanism to obtain values. |
paul@509 | 504 | |
paul@509 | 505 | else: |
paul@509 | 506 | return False |
paul@0 | 507 | else: |
paul@0 | 508 | raise InspectError("In %s, item assignment needing %d items is given %d items." % ( |
paul@0 | 509 | self.get_namespace_path(), len(n.nodes), len(name_ref.items))) |
paul@0 | 510 | |
paul@0 | 511 | def process_compare_node(self, n): |
paul@0 | 512 | |
paul@0 | 513 | """ |
paul@0 | 514 | Process the given comparison node 'n', converting an operator sequence |
paul@0 | 515 | from... |
paul@0 | 516 | |
paul@0 | 517 | <expr1> <op1> <expr2> <op2> <expr3> |
paul@0 | 518 | |
paul@0 | 519 | ...to... |
paul@0 | 520 | |
paul@0 | 521 | <op1>(<expr1>, <expr2>) and <op2>(<expr2>, <expr3>) |
paul@0 | 522 | """ |
paul@0 | 523 | |
paul@0 | 524 | invocations = [] |
paul@0 | 525 | last = n.expr |
paul@0 | 526 | |
paul@0 | 527 | for op, op_node in n.ops: |
paul@0 | 528 | op = operator_functions.get(op) |
paul@0 | 529 | |
paul@0 | 530 | invocations.append(compiler.ast.CallFunc( |
paul@0 | 531 | compiler.ast.Name("$op%s" % op), |
paul@0 | 532 | [last, op_node])) |
paul@0 | 533 | |
paul@0 | 534 | last = op_node |
paul@0 | 535 | |
paul@0 | 536 | if len(invocations) > 1: |
paul@0 | 537 | result = compiler.ast.And(invocations) |
paul@0 | 538 | else: |
paul@0 | 539 | result = invocations[0] |
paul@0 | 540 | |
paul@0 | 541 | return self.process_structure_node(result) |
paul@0 | 542 | |
paul@0 | 543 | def process_dict_node(self, node): |
paul@0 | 544 | |
paul@0 | 545 | """ |
paul@0 | 546 | Process the given dictionary 'node', returning a list of (key, value) |
paul@0 | 547 | tuples. |
paul@0 | 548 | """ |
paul@0 | 549 | |
paul@0 | 550 | l = [] |
paul@0 | 551 | for key, value in node.items: |
paul@0 | 552 | l.append(( |
paul@0 | 553 | self.process_structure_node(key), |
paul@0 | 554 | self.process_structure_node(value))) |
paul@0 | 555 | return l |
paul@0 | 556 | |
paul@0 | 557 | def process_for_node(self, n): |
paul@0 | 558 | |
paul@0 | 559 | """ |
paul@0 | 560 | Generate attribute accesses for {n.list}.__iter__ and the next method on |
paul@0 | 561 | the iterator, producing a replacement node for the original. |
paul@0 | 562 | """ |
paul@0 | 563 | |
paul@0 | 564 | node = compiler.ast.Stmt([ |
paul@0 | 565 | |
paul@533 | 566 | # <next> = {n.list}.__iter__().next |
paul@0 | 567 | |
paul@0 | 568 | compiler.ast.Assign( |
paul@0 | 569 | [compiler.ast.AssName(self.get_iterator_name(), "OP_ASSIGN")], |
paul@533 | 570 | compiler.ast.Getattr( |
paul@533 | 571 | compiler.ast.CallFunc( |
paul@533 | 572 | compiler.ast.Getattr(n.list, "__iter__"), |
paul@533 | 573 | [] |
paul@533 | 574 | ), "next")), |
paul@0 | 575 | |
paul@0 | 576 | # try: |
paul@0 | 577 | # while True: |
paul@533 | 578 | # <var>... = <next>() |
paul@0 | 579 | # ... |
paul@0 | 580 | # except StopIteration: |
paul@0 | 581 | # pass |
paul@0 | 582 | |
paul@0 | 583 | compiler.ast.TryExcept( |
paul@0 | 584 | compiler.ast.While( |
paul@0 | 585 | compiler.ast.Name("True"), |
paul@0 | 586 | compiler.ast.Stmt([ |
paul@0 | 587 | compiler.ast.Assign( |
paul@0 | 588 | [n.assign], |
paul@0 | 589 | compiler.ast.CallFunc( |
paul@533 | 590 | compiler.ast.Name(self.get_iterator_name()), |
paul@0 | 591 | [] |
paul@0 | 592 | )), |
paul@0 | 593 | n.body]), |
paul@0 | 594 | None), |
paul@0 | 595 | [(compiler.ast.Name("StopIteration"), None, compiler.ast.Stmt([compiler.ast.Pass()]))], |
paul@0 | 596 | None) |
paul@0 | 597 | ]) |
paul@0 | 598 | |
paul@0 | 599 | self.next_iterator() |
paul@0 | 600 | self.process_structure_node(node) |
paul@0 | 601 | |
paul@0 | 602 | def process_literal_sequence_node(self, n, name, ref, cls): |
paul@0 | 603 | |
paul@0 | 604 | """ |
paul@0 | 605 | Process the given literal sequence node 'n' as a function invocation, |
paul@0 | 606 | with 'name' indicating the type of the sequence, and 'ref' being a |
paul@0 | 607 | reference to the type. The 'cls' is used to instantiate a suitable name |
paul@0 | 608 | reference. |
paul@0 | 609 | """ |
paul@0 | 610 | |
paul@0 | 611 | if name == "dict": |
paul@0 | 612 | items = [] |
paul@0 | 613 | for key, value in n.items: |
paul@0 | 614 | items.append(compiler.ast.Tuple([key, value])) |
paul@0 | 615 | else: # name in ("list", "tuple"): |
paul@0 | 616 | items = n.nodes |
paul@0 | 617 | |
paul@0 | 618 | return self.get_literal_reference(name, ref, items, cls) |
paul@0 | 619 | |
paul@0 | 620 | def process_operator_node(self, n): |
paul@0 | 621 | |
paul@0 | 622 | """ |
paul@0 | 623 | Process the given operator node 'n' as an operator function invocation. |
paul@0 | 624 | """ |
paul@0 | 625 | |
paul@0 | 626 | op = operator_functions[n.__class__.__name__] |
paul@0 | 627 | invocation = compiler.ast.CallFunc( |
paul@0 | 628 | compiler.ast.Name("$op%s" % op), |
paul@0 | 629 | list(n.getChildNodes()) |
paul@0 | 630 | ) |
paul@0 | 631 | return self.process_structure_node(invocation) |
paul@0 | 632 | |
paul@173 | 633 | def process_print_node(self, n): |
paul@173 | 634 | |
paul@173 | 635 | """ |
paul@173 | 636 | Process the given print node 'n' as an invocation on a stream of the |
paul@173 | 637 | form... |
paul@173 | 638 | |
paul@173 | 639 | $print(dest, args, nl) |
paul@173 | 640 | |
paul@173 | 641 | The special function name will be translated elsewhere. |
paul@173 | 642 | """ |
paul@173 | 643 | |
paul@173 | 644 | nl = isinstance(n, compiler.ast.Printnl) |
paul@173 | 645 | invocation = compiler.ast.CallFunc( |
paul@173 | 646 | compiler.ast.Name("$print"), |
paul@173 | 647 | [n.dest or compiler.ast.Name("None"), |
paul@173 | 648 | compiler.ast.List(list(n.nodes)), |
paul@359 | 649 | nl and compiler.ast.Name("True") or compiler.ast.Name("False")] |
paul@173 | 650 | ) |
paul@173 | 651 | return self.process_structure_node(invocation) |
paul@173 | 652 | |
paul@0 | 653 | def process_slice_node(self, n, expr=None): |
paul@0 | 654 | |
paul@0 | 655 | """ |
paul@0 | 656 | Process the given slice node 'n' as an operator function invocation. |
paul@0 | 657 | """ |
paul@0 | 658 | |
paul@548 | 659 | if n.flags == "OP_ASSIGN": op = "setslice" |
paul@548 | 660 | elif n.flags == "OP_DELETE": op = "delslice" |
paul@548 | 661 | else: op = "getslice" |
paul@548 | 662 | |
paul@0 | 663 | invocation = compiler.ast.CallFunc( |
paul@0 | 664 | compiler.ast.Name("$op%s" % op), |
paul@0 | 665 | [n.expr, n.lower or compiler.ast.Name("None"), n.upper or compiler.ast.Name("None")] + |
paul@0 | 666 | (expr and [expr] or []) |
paul@0 | 667 | ) |
paul@548 | 668 | |
paul@548 | 669 | # Fix parse tree structure. |
paul@548 | 670 | |
paul@548 | 671 | if op == "delslice": |
paul@548 | 672 | invocation = compiler.ast.Discard(invocation) |
paul@548 | 673 | |
paul@0 | 674 | return self.process_structure_node(invocation) |
paul@0 | 675 | |
paul@0 | 676 | def process_sliceobj_node(self, n): |
paul@0 | 677 | |
paul@0 | 678 | """ |
paul@0 | 679 | Process the given slice object node 'n' as a slice constructor. |
paul@0 | 680 | """ |
paul@0 | 681 | |
paul@0 | 682 | op = "slice" |
paul@0 | 683 | invocation = compiler.ast.CallFunc( |
paul@0 | 684 | compiler.ast.Name("$op%s" % op), |
paul@0 | 685 | n.nodes |
paul@0 | 686 | ) |
paul@0 | 687 | return self.process_structure_node(invocation) |
paul@0 | 688 | |
paul@0 | 689 | def process_subscript_node(self, n, expr=None): |
paul@0 | 690 | |
paul@0 | 691 | """ |
paul@0 | 692 | Process the given subscript node 'n' as an operator function invocation. |
paul@0 | 693 | """ |
paul@0 | 694 | |
paul@548 | 695 | if n.flags == "OP_ASSIGN": op = "setitem" |
paul@548 | 696 | elif n.flags == "OP_DELETE": op = "delitem" |
paul@548 | 697 | else: op = "getitem" |
paul@548 | 698 | |
paul@0 | 699 | invocation = compiler.ast.CallFunc( |
paul@0 | 700 | compiler.ast.Name("$op%s" % op), |
paul@0 | 701 | [n.expr] + list(n.subs) + (expr and [expr] or []) |
paul@0 | 702 | ) |
paul@548 | 703 | |
paul@548 | 704 | # Fix parse tree structure. |
paul@548 | 705 | |
paul@548 | 706 | if op == "delitem": |
paul@548 | 707 | invocation = compiler.ast.Discard(invocation) |
paul@548 | 708 | |
paul@0 | 709 | return self.process_structure_node(invocation) |
paul@0 | 710 | |
paul@0 | 711 | def process_attribute_chain(self, n): |
paul@0 | 712 | |
paul@0 | 713 | """ |
paul@0 | 714 | Process the given attribute access node 'n'. Return a reference |
paul@0 | 715 | describing the expression. |
paul@0 | 716 | """ |
paul@0 | 717 | |
paul@0 | 718 | # AssAttr/Getattr are nested with the outermost access being the last |
paul@0 | 719 | # access in any chain. |
paul@0 | 720 | |
paul@0 | 721 | self.attrs.insert(0, n.attrname) |
paul@0 | 722 | attrs = self.attrs |
paul@0 | 723 | |
paul@0 | 724 | # Break attribute chains where non-access nodes are found. |
paul@0 | 725 | |
paul@0 | 726 | if not self.have_access_expression(n): |
paul@110 | 727 | self.reset_attribute_chain() |
paul@0 | 728 | |
paul@0 | 729 | # Descend into the expression, extending backwards any existing chain, |
paul@0 | 730 | # or building another for the expression. |
paul@0 | 731 | |
paul@0 | 732 | name_ref = self.process_structure_node(n.expr) |
paul@0 | 733 | |
paul@0 | 734 | # Restore chain information applying to this node. |
paul@0 | 735 | |
paul@110 | 736 | if not self.have_access_expression(n): |
paul@110 | 737 | self.restore_attribute_chain(attrs) |
paul@0 | 738 | |
paul@0 | 739 | # Return immediately if the expression was another access and thus a |
paul@0 | 740 | # continuation backwards along the chain. The above processing will |
paul@0 | 741 | # have followed the chain all the way to its conclusion. |
paul@0 | 742 | |
paul@0 | 743 | if self.have_access_expression(n): |
paul@0 | 744 | del self.attrs[0] |
paul@0 | 745 | |
paul@0 | 746 | return name_ref |
paul@0 | 747 | |
paul@124 | 748 | # Attribute chain handling. |
paul@124 | 749 | |
paul@110 | 750 | def reset_attribute_chain(self): |
paul@110 | 751 | |
paul@110 | 752 | "Reset the attribute chain for a subexpression of an attribute access." |
paul@110 | 753 | |
paul@110 | 754 | self.attrs = [] |
paul@124 | 755 | self.chain_assignment.append(self.in_assignment) |
paul@124 | 756 | self.chain_invocation.append(self.in_invocation) |
paul@124 | 757 | self.in_assignment = None |
paul@553 | 758 | self.in_invocation = None |
paul@110 | 759 | |
paul@110 | 760 | def restore_attribute_chain(self, attrs): |
paul@110 | 761 | |
paul@110 | 762 | "Restore the attribute chain for an attribute access." |
paul@110 | 763 | |
paul@110 | 764 | self.attrs = attrs |
paul@124 | 765 | self.in_assignment = self.chain_assignment.pop() |
paul@124 | 766 | self.in_invocation = self.chain_invocation.pop() |
paul@110 | 767 | |
paul@0 | 768 | def have_access_expression(self, node): |
paul@0 | 769 | |
paul@0 | 770 | "Return whether the expression associated with 'node' is Getattr." |
paul@0 | 771 | |
paul@0 | 772 | return isinstance(node.expr, compiler.ast.Getattr) |
paul@0 | 773 | |
paul@603 | 774 | def get_name_for_tracking(self, name, name_ref=None): |
paul@0 | 775 | |
paul@0 | 776 | """ |
paul@0 | 777 | Return the name to be used for attribute usage observations involving |
paul@603 | 778 | the given 'name' in the current namespace. |
paul@603 | 779 | |
paul@603 | 780 | If the name is being used outside a function, and if 'name_ref' is |
paul@603 | 781 | given, a path featuring the name in the global namespace is returned |
paul@605 | 782 | where 'name_ref' indicates a global. Otherwise, a path computed using |
paul@603 | 783 | the current namespace and the given name is returned. |
paul@0 | 784 | |
paul@0 | 785 | The intention of this method is to provide a suitably-qualified name |
paul@0 | 786 | that can be tracked across namespaces. Where globals are being |
paul@0 | 787 | referenced in class namespaces, they should be referenced using their |
paul@0 | 788 | path within the module, not using a path within each class. |
paul@0 | 789 | |
paul@0 | 790 | It may not be possible to identify a global within a function at the |
paul@0 | 791 | time of inspection (since a global may appear later in a file). |
paul@0 | 792 | Consequently, globals are identified by their local name rather than |
paul@0 | 793 | their module-qualified path. |
paul@0 | 794 | """ |
paul@0 | 795 | |
paul@0 | 796 | # For functions, use the appropriate local names. |
paul@0 | 797 | |
paul@0 | 798 | if self.in_function: |
paul@0 | 799 | return name |
paul@0 | 800 | |
paul@603 | 801 | # For global names outside functions, use a global name. |
paul@597 | 802 | |
paul@603 | 803 | elif name_ref and name_ref.is_global_name(): |
paul@603 | 804 | return self.get_global_path(name) |
paul@0 | 805 | |
paul@152 | 806 | # Otherwise, establish a name in the current namespace. |
paul@0 | 807 | |
paul@0 | 808 | else: |
paul@0 | 809 | return self.get_object_path(name) |
paul@0 | 810 | |
paul@0 | 811 | def get_path_for_access(self): |
paul@0 | 812 | |
paul@0 | 813 | "Outside functions, register accesses at the module level." |
paul@0 | 814 | |
paul@0 | 815 | if not self.in_function: |
paul@0 | 816 | return self.name |
paul@0 | 817 | else: |
paul@0 | 818 | return self.get_namespace_path() |
paul@0 | 819 | |
paul@0 | 820 | def get_module_name(self, node): |
paul@0 | 821 | |
paul@0 | 822 | """ |
paul@0 | 823 | Using the given From 'node' in this module, calculate any relative import |
paul@0 | 824 | information, returning a tuple containing a module to import along with any |
paul@0 | 825 | names to import based on the node's name information. |
paul@0 | 826 | |
paul@0 | 827 | Where the returned module is given as None, whole module imports should |
paul@0 | 828 | be performed for the returned modules using the returned names. |
paul@0 | 829 | """ |
paul@0 | 830 | |
paul@0 | 831 | # Absolute import. |
paul@0 | 832 | |
paul@0 | 833 | if node.level == 0: |
paul@0 | 834 | return node.modname, node.names |
paul@0 | 835 | |
paul@0 | 836 | # Relative to an ancestor of this module. |
paul@0 | 837 | |
paul@0 | 838 | else: |
paul@0 | 839 | path = self.name.split(".") |
paul@0 | 840 | level = node.level |
paul@0 | 841 | |
paul@0 | 842 | # Relative imports treat package roots as submodules. |
paul@0 | 843 | |
paul@0 | 844 | if split(self.filename)[-1] == "__init__.py": |
paul@0 | 845 | level -= 1 |
paul@0 | 846 | |
paul@0 | 847 | if level > len(path): |
paul@0 | 848 | raise InspectError("Relative import %r involves too many levels up from module %r" % ( |
paul@0 | 849 | ("%s%s" % ("." * node.level, node.modname or "")), self.name)) |
paul@0 | 850 | |
paul@0 | 851 | basename = ".".join(path[:len(path)-level]) |
paul@0 | 852 | |
paul@0 | 853 | # Name imports from a module. |
paul@0 | 854 | |
paul@0 | 855 | if node.modname: |
paul@0 | 856 | return "%s.%s" % (basename, node.modname), node.names |
paul@0 | 857 | |
paul@0 | 858 | # Relative whole module imports. |
paul@0 | 859 | |
paul@0 | 860 | else: |
paul@0 | 861 | return basename, node.names |
paul@0 | 862 | |
paul@0 | 863 | def get_argnames(args): |
paul@0 | 864 | |
paul@0 | 865 | """ |
paul@0 | 866 | Return a list of all names provided by 'args'. Since tuples may be |
paul@0 | 867 | employed, the arguments are traversed depth-first. |
paul@0 | 868 | """ |
paul@0 | 869 | |
paul@0 | 870 | l = [] |
paul@0 | 871 | for arg in args: |
paul@0 | 872 | if isinstance(arg, tuple): |
paul@0 | 873 | l += get_argnames(arg) |
paul@0 | 874 | else: |
paul@0 | 875 | l.append(arg) |
paul@0 | 876 | return l |
paul@0 | 877 | |
paul@509 | 878 | def get_names_from_nodes(nodes): |
paul@509 | 879 | |
paul@509 | 880 | """ |
paul@509 | 881 | Return the names employed in the given 'nodes' along with the number of |
paul@509 | 882 | nodes excluding sequences. |
paul@509 | 883 | """ |
paul@509 | 884 | |
paul@509 | 885 | names = set() |
paul@509 | 886 | count = 0 |
paul@509 | 887 | |
paul@509 | 888 | for node in nodes: |
paul@509 | 889 | |
paul@509 | 890 | # Add names and count them. |
paul@509 | 891 | |
paul@509 | 892 | if isinstance(node, (compiler.ast.AssName, compiler.ast.Name)): |
paul@509 | 893 | names.add(node.name) |
paul@509 | 894 | count += 1 |
paul@509 | 895 | |
paul@509 | 896 | # Add names from sequences and incorporate their counts. |
paul@509 | 897 | |
paul@509 | 898 | elif isinstance(node, (compiler.ast.AssList, compiler.ast.AssTuple, |
paul@509 | 899 | compiler.ast.List, compiler.ast.Set, |
paul@509 | 900 | compiler.ast.Tuple)): |
paul@509 | 901 | _names, _count = get_names_from_nodes(node.nodes) |
paul@509 | 902 | names.update(_names) |
paul@509 | 903 | count += _count |
paul@509 | 904 | |
paul@509 | 905 | # Count non-name, non-sequence nodes. |
paul@509 | 906 | |
paul@509 | 907 | else: |
paul@509 | 908 | count += 1 |
paul@509 | 909 | |
paul@509 | 910 | return names, count |
paul@509 | 911 | |
paul@491 | 912 | # Result classes. |
paul@491 | 913 | |
paul@491 | 914 | class InstructionSequence: |
paul@491 | 915 | |
paul@491 | 916 | "A generic sequence of instructions." |
paul@491 | 917 | |
paul@491 | 918 | def __init__(self, instructions): |
paul@491 | 919 | self.instructions = instructions |
paul@491 | 920 | |
paul@491 | 921 | def get_value_instruction(self): |
paul@491 | 922 | return self.instructions[-1] |
paul@491 | 923 | |
paul@491 | 924 | def get_init_instructions(self): |
paul@491 | 925 | return self.instructions[:-1] |
paul@491 | 926 | |
paul@0 | 927 | # Dictionary utilities. |
paul@0 | 928 | |
paul@0 | 929 | def init_item(d, key, fn): |
paul@0 | 930 | |
paul@0 | 931 | """ |
paul@0 | 932 | Add to 'd' an entry for 'key' using the callable 'fn' to make an initial |
paul@0 | 933 | value where no entry already exists. |
paul@0 | 934 | """ |
paul@0 | 935 | |
paul@0 | 936 | if not d.has_key(key): |
paul@0 | 937 | d[key] = fn() |
paul@0 | 938 | return d[key] |
paul@0 | 939 | |
paul@0 | 940 | def dict_for_keys(d, keys): |
paul@0 | 941 | |
paul@0 | 942 | "Return a new dictionary containing entries from 'd' for the given 'keys'." |
paul@0 | 943 | |
paul@0 | 944 | nd = {} |
paul@0 | 945 | for key in keys: |
paul@0 | 946 | if d.has_key(key): |
paul@0 | 947 | nd[key] = d[key] |
paul@0 | 948 | return nd |
paul@0 | 949 | |
paul@0 | 950 | def make_key(s): |
paul@0 | 951 | |
paul@0 | 952 | "Make sequence 's' into a tuple-based key, first sorting its contents." |
paul@0 | 953 | |
paul@0 | 954 | l = list(s) |
paul@0 | 955 | l.sort() |
paul@0 | 956 | return tuple(l) |
paul@0 | 957 | |
paul@0 | 958 | def add_counter_item(d, key): |
paul@0 | 959 | |
paul@0 | 960 | """ |
paul@0 | 961 | Make a mapping in 'd' for 'key' to the number of keys added before it, thus |
paul@0 | 962 | maintaining a mapping of keys to their order of insertion. |
paul@0 | 963 | """ |
paul@0 | 964 | |
paul@0 | 965 | if not d.has_key(key): |
paul@0 | 966 | d[key] = len(d.keys()) |
paul@0 | 967 | return d[key] |
paul@0 | 968 | |
paul@0 | 969 | def remove_items(d1, d2): |
paul@0 | 970 | |
paul@0 | 971 | "Remove from 'd1' all items from 'd2'." |
paul@0 | 972 | |
paul@0 | 973 | for key in d2.keys(): |
paul@0 | 974 | if d1.has_key(key): |
paul@0 | 975 | del d1[key] |
paul@0 | 976 | |
paul@0 | 977 | # Set utilities. |
paul@0 | 978 | |
paul@0 | 979 | def first(s): |
paul@0 | 980 | return list(s)[0] |
paul@0 | 981 | |
paul@0 | 982 | def same(s1, s2): |
paul@0 | 983 | return set(s1) == set(s2) |
paul@0 | 984 | |
paul@0 | 985 | # General input/output. |
paul@0 | 986 | |
paul@0 | 987 | def readfile(filename): |
paul@0 | 988 | |
paul@0 | 989 | "Return the contents of 'filename'." |
paul@0 | 990 | |
paul@0 | 991 | f = open(filename) |
paul@0 | 992 | try: |
paul@0 | 993 | return f.read() |
paul@0 | 994 | finally: |
paul@0 | 995 | f.close() |
paul@0 | 996 | |
paul@0 | 997 | def writefile(filename, s): |
paul@0 | 998 | |
paul@0 | 999 | "Write to 'filename' the string 's'." |
paul@0 | 1000 | |
paul@0 | 1001 | f = open(filename, "w") |
paul@0 | 1002 | try: |
paul@0 | 1003 | f.write(s) |
paul@0 | 1004 | finally: |
paul@0 | 1005 | f.close() |
paul@0 | 1006 | |
paul@0 | 1007 | # General encoding. |
paul@0 | 1008 | |
paul@0 | 1009 | def sorted_output(x): |
paul@0 | 1010 | |
paul@0 | 1011 | "Sort sequence 'x' and return a string with commas separating the values." |
paul@0 | 1012 | |
paul@0 | 1013 | x = map(str, x) |
paul@0 | 1014 | x.sort() |
paul@0 | 1015 | return ", ".join(x) |
paul@0 | 1016 | |
paul@537 | 1017 | def get_string_details(literals, encoding): |
paul@512 | 1018 | |
paul@512 | 1019 | """ |
paul@537 | 1020 | Determine whether 'literals' represent Unicode strings or byte strings, |
paul@537 | 1021 | using 'encoding' to reproduce byte sequences. |
paul@537 | 1022 | |
paul@537 | 1023 | Each literal is the full program representation including prefix and quotes |
paul@537 | 1024 | recoded by the parser to UTF-8. Thus, any literal found to represent a byte |
paul@537 | 1025 | string needs to be translated back to its original encoding. |
paul@537 | 1026 | |
paul@537 | 1027 | Return a single encoded literal value, a type name, and the original |
paul@537 | 1028 | encoding as a tuple. |
paul@537 | 1029 | """ |
paul@537 | 1030 | |
paul@537 | 1031 | typename = "unicode" |
paul@537 | 1032 | |
paul@537 | 1033 | l = [] |
paul@537 | 1034 | |
paul@537 | 1035 | for s in literals: |
paul@537 | 1036 | out, _typename = get_literal_details(s) |
paul@537 | 1037 | if _typename == "str": |
paul@537 | 1038 | typename = "str" |
paul@537 | 1039 | l.append(out) |
paul@537 | 1040 | |
paul@537 | 1041 | out = "".join(l) |
paul@537 | 1042 | |
paul@537 | 1043 | # For Unicode values, convert to the UTF-8 program representation. |
paul@537 | 1044 | |
paul@537 | 1045 | if typename == "unicode": |
paul@537 | 1046 | return out.encode("utf-8"), typename, encoding |
paul@537 | 1047 | |
paul@537 | 1048 | # For byte string values, convert back to the original encoding. |
paul@537 | 1049 | |
paul@537 | 1050 | else: |
paul@537 | 1051 | return out.encode(encoding), typename, encoding |
paul@537 | 1052 | |
paul@537 | 1053 | def get_literal_details(s): |
paul@537 | 1054 | |
paul@537 | 1055 | """ |
paul@537 | 1056 | Determine whether 's' represents a Unicode string or a byte string, where |
paul@537 | 1057 | 's' contains the full program representation of a literal including prefix |
paul@537 | 1058 | and quotes, recoded by the parser to UTF-8. |
paul@512 | 1059 | |
paul@512 | 1060 | Find and convert Unicode values starting with <backslash>u or <backslash>U, |
paul@512 | 1061 | and byte or Unicode values starting with <backslash><octal digit> or |
paul@512 | 1062 | <backslash>x. |
paul@512 | 1063 | |
paul@512 | 1064 | Literals prefixed with "u" cause <backslash><octal digit> and <backslash>x |
paul@512 | 1065 | to be considered as Unicode values. Otherwise, they produce byte values and |
paul@512 | 1066 | cause unprefixed strings to be considered as byte strings. |
paul@512 | 1067 | |
paul@512 | 1068 | Literals prefixed with "r" do not have their backslash-encoded values |
paul@512 | 1069 | converted unless also prefixed with "u", in which case only the above value |
paul@512 | 1070 | formats are converted, not any of the other special sequences for things |
paul@512 | 1071 | like newlines. |
paul@512 | 1072 | |
paul@537 | 1073 | Return the literal value as a Unicode object together with the appropriate |
paul@537 | 1074 | type name in a tuple. |
paul@512 | 1075 | """ |
paul@512 | 1076 | |
paul@512 | 1077 | l = [] |
paul@512 | 1078 | |
paul@512 | 1079 | # Identify the quote character and use it to identify the prefix. |
paul@512 | 1080 | |
paul@512 | 1081 | quote_type = s[-1] |
paul@512 | 1082 | prefix_end = s.find(quote_type) |
paul@512 | 1083 | prefix = s[:prefix_end].lower() |
paul@512 | 1084 | |
paul@512 | 1085 | if prefix not in ("", "b", "br", "r", "u", "ur"): |
paul@512 | 1086 | raise ValueError, "String literal does not have a supported prefix: %s" % s |
paul@512 | 1087 | |
paul@513 | 1088 | if "b" in prefix: |
paul@513 | 1089 | typename = "str" |
paul@513 | 1090 | else: |
paul@513 | 1091 | typename = "unicode" |
paul@513 | 1092 | |
paul@512 | 1093 | # Identify triple quotes or single quotes. |
paul@512 | 1094 | |
paul@512 | 1095 | if len(s) >= 6 and s[-2] == quote_type and s[-3] == quote_type: |
paul@512 | 1096 | quote = s[prefix_end:prefix_end+3] |
paul@512 | 1097 | current = prefix_end + 3 |
paul@512 | 1098 | end = len(s) - 3 |
paul@512 | 1099 | else: |
paul@512 | 1100 | quote = s[prefix_end] |
paul@512 | 1101 | current = prefix_end + 1 |
paul@512 | 1102 | end = len(s) - 1 |
paul@512 | 1103 | |
paul@512 | 1104 | # Conversions of some quoted values. |
paul@512 | 1105 | |
paul@512 | 1106 | searches = { |
paul@512 | 1107 | "u" : (6, 16), |
paul@512 | 1108 | "U" : (10, 16), |
paul@512 | 1109 | "x" : (4, 16), |
paul@512 | 1110 | } |
paul@512 | 1111 | |
paul@512 | 1112 | octal_digits = map(str, range(0, 8)) |
paul@512 | 1113 | |
paul@512 | 1114 | # Translations of some quoted values. |
paul@512 | 1115 | |
paul@512 | 1116 | escaped = { |
paul@512 | 1117 | "\\" : "\\", "'" : "'", '"' : '"', |
paul@512 | 1118 | "a" : "\a", "b" : "\b", "f" : "\f", |
paul@512 | 1119 | "n" : "\n", "r" : "\r", "t" : "\t", |
paul@512 | 1120 | } |
paul@512 | 1121 | |
paul@512 | 1122 | while current < end: |
paul@512 | 1123 | |
paul@512 | 1124 | # Look for quoted values. |
paul@512 | 1125 | |
paul@512 | 1126 | index = s.find("\\", current) |
paul@512 | 1127 | if index == -1 or index + 1 == end: |
paul@512 | 1128 | l.append(s[current:end]) |
paul@512 | 1129 | break |
paul@512 | 1130 | |
paul@512 | 1131 | # Add the preceding text. |
paul@512 | 1132 | |
paul@512 | 1133 | l.append(s[current:index]) |
paul@512 | 1134 | |
paul@512 | 1135 | # Handle quoted text. |
paul@512 | 1136 | |
paul@512 | 1137 | term = s[index+1] |
paul@512 | 1138 | |
paul@512 | 1139 | # Add Unicode values. Where a string is u-prefixed, even \o and \x |
paul@512 | 1140 | # produce Unicode values. |
paul@512 | 1141 | |
paul@513 | 1142 | if typename == "unicode" and ( |
paul@513 | 1143 | term in ("u", "U") or |
paul@513 | 1144 | "u" in prefix and (term == "x" or term in octal_digits)): |
paul@512 | 1145 | |
paul@512 | 1146 | needed, base = searches.get(term, (4, 8)) |
paul@512 | 1147 | value = convert_quoted_value(s, index, needed, end, base, unichr) |
paul@512 | 1148 | l.append(value) |
paul@512 | 1149 | current = index + needed |
paul@512 | 1150 | |
paul@512 | 1151 | # Add raw byte values, changing the string type. |
paul@512 | 1152 | |
paul@512 | 1153 | elif "r" not in prefix and ( |
paul@512 | 1154 | term == "x" or term in octal_digits): |
paul@512 | 1155 | |
paul@512 | 1156 | needed, base = searches.get(term, (4, 8)) |
paul@512 | 1157 | value = convert_quoted_value(s, index, needed, end, base, chr) |
paul@512 | 1158 | l.append(value) |
paul@512 | 1159 | typename = "str" |
paul@512 | 1160 | current = index + needed |
paul@512 | 1161 | |
paul@512 | 1162 | # Add other escaped values. |
paul@512 | 1163 | |
paul@512 | 1164 | elif "r" not in prefix and escaped.has_key(term): |
paul@512 | 1165 | l.append(escaped[term]) |
paul@512 | 1166 | current = index + 2 |
paul@512 | 1167 | |
paul@512 | 1168 | # Add other text as found. |
paul@512 | 1169 | |
paul@512 | 1170 | else: |
paul@512 | 1171 | l.append(s[index:index+2]) |
paul@512 | 1172 | current = index + 2 |
paul@512 | 1173 | |
paul@537 | 1174 | # Collect the components into a single Unicode object. Since the literal |
paul@537 | 1175 | # text was already in UTF-8 form, interpret plain strings as UTF-8 |
paul@537 | 1176 | # sequences. |
paul@512 | 1177 | |
paul@537 | 1178 | out = [] |
paul@512 | 1179 | |
paul@537 | 1180 | for value in l: |
paul@537 | 1181 | if isinstance(value, unicode): |
paul@537 | 1182 | out.append(value) |
paul@537 | 1183 | else: |
paul@537 | 1184 | out.append(unicode(value, "utf-8")) |
paul@512 | 1185 | |
paul@537 | 1186 | return "".join(out), typename |
paul@512 | 1187 | |
paul@512 | 1188 | def convert_quoted_value(s, index, needed, end, base, fn): |
paul@512 | 1189 | |
paul@512 | 1190 | """ |
paul@512 | 1191 | Interpret a quoted value in 's' at 'index' with the given 'needed' number of |
paul@512 | 1192 | positions, and with the given 'end' indicating the first position after the |
paul@512 | 1193 | end of the actual string content. |
paul@512 | 1194 | |
paul@512 | 1195 | Use 'base' as the numerical base when interpreting the value, and use 'fn' |
paul@512 | 1196 | to convert the value to an appropriate type. |
paul@512 | 1197 | """ |
paul@512 | 1198 | |
paul@512 | 1199 | s = s[index:min(index+needed, end)] |
paul@512 | 1200 | |
paul@512 | 1201 | # Not a complete occurrence. |
paul@512 | 1202 | |
paul@512 | 1203 | if len(s) < needed: |
paul@512 | 1204 | return s |
paul@512 | 1205 | |
paul@512 | 1206 | # Test for a well-formed value. |
paul@512 | 1207 | |
paul@512 | 1208 | try: |
paul@512 | 1209 | first = base == 8 and 1 or 2 |
paul@512 | 1210 | value = int(s[first:needed], base) |
paul@512 | 1211 | except ValueError: |
paul@512 | 1212 | return s |
paul@512 | 1213 | else: |
paul@512 | 1214 | return fn(value) |
paul@512 | 1215 | |
paul@0 | 1216 | # Attribute chain decoding. |
paul@0 | 1217 | |
paul@0 | 1218 | def get_attrnames(attrnames): |
paul@11 | 1219 | |
paul@11 | 1220 | """ |
paul@11 | 1221 | Split the qualified attribute chain 'attrnames' into its components, |
paul@11 | 1222 | handling special attributes starting with "#" that indicate type |
paul@11 | 1223 | conformance. |
paul@11 | 1224 | """ |
paul@11 | 1225 | |
paul@0 | 1226 | if attrnames.startswith("#"): |
paul@0 | 1227 | return [attrnames] |
paul@0 | 1228 | else: |
paul@0 | 1229 | return attrnames.split(".") |
paul@0 | 1230 | |
paul@0 | 1231 | def get_attrname_from_location(location): |
paul@11 | 1232 | |
paul@11 | 1233 | """ |
paul@11 | 1234 | Extract the first attribute from the attribute names employed in a |
paul@11 | 1235 | 'location'. |
paul@11 | 1236 | """ |
paul@11 | 1237 | |
paul@0 | 1238 | path, name, attrnames, access = location |
paul@91 | 1239 | if not attrnames: |
paul@91 | 1240 | return attrnames |
paul@0 | 1241 | return get_attrnames(attrnames)[0] |
paul@0 | 1242 | |
paul@85 | 1243 | def get_name_path(path, name): |
paul@85 | 1244 | |
paul@85 | 1245 | "Return a suitable qualified name from the given 'path' and 'name'." |
paul@85 | 1246 | |
paul@85 | 1247 | if "." in name: |
paul@85 | 1248 | return name |
paul@85 | 1249 | else: |
paul@85 | 1250 | return "%s.%s" % (path, name) |
paul@85 | 1251 | |
paul@90 | 1252 | # Usage-related functions. |
paul@89 | 1253 | |
paul@89 | 1254 | def get_types_for_usage(attrnames, objects): |
paul@89 | 1255 | |
paul@89 | 1256 | """ |
paul@89 | 1257 | Identify the types that can support the given 'attrnames', using the |
paul@89 | 1258 | given 'objects' as the catalogue of type details. |
paul@89 | 1259 | """ |
paul@89 | 1260 | |
paul@89 | 1261 | types = [] |
paul@89 | 1262 | for name, _attrnames in objects.items(): |
paul@89 | 1263 | if set(attrnames).issubset(_attrnames): |
paul@89 | 1264 | types.append(name) |
paul@89 | 1265 | return types |
paul@89 | 1266 | |
paul@90 | 1267 | def get_invoked_attributes(usage): |
paul@90 | 1268 | |
paul@90 | 1269 | "Obtain invoked attribute from the given 'usage'." |
paul@90 | 1270 | |
paul@90 | 1271 | invoked = [] |
paul@90 | 1272 | if usage: |
paul@107 | 1273 | for attrname, invocation, assignment in usage: |
paul@90 | 1274 | if invocation: |
paul@90 | 1275 | invoked.append(attrname) |
paul@90 | 1276 | return invoked |
paul@90 | 1277 | |
paul@107 | 1278 | def get_assigned_attributes(usage): |
paul@107 | 1279 | |
paul@107 | 1280 | "Obtain assigned attribute from the given 'usage'." |
paul@107 | 1281 | |
paul@107 | 1282 | assigned = [] |
paul@107 | 1283 | if usage: |
paul@107 | 1284 | for attrname, invocation, assignment in usage: |
paul@107 | 1285 | if assignment: |
paul@107 | 1286 | assigned.append(attrname) |
paul@107 | 1287 | return assigned |
paul@107 | 1288 | |
paul@366 | 1289 | # Type and module functions. |
paul@538 | 1290 | # NOTE: This makes assumptions about the __builtins__ structure. |
paul@366 | 1291 | |
paul@366 | 1292 | def get_builtin_module(name): |
paul@366 | 1293 | |
paul@366 | 1294 | "Return the module name containing the given type 'name'." |
paul@366 | 1295 | |
paul@394 | 1296 | if name == "string": |
paul@538 | 1297 | modname = "str" |
paul@394 | 1298 | elif name == "utf8string": |
paul@538 | 1299 | modname = "unicode" |
paul@394 | 1300 | elif name == "NoneType": |
paul@538 | 1301 | modname = "none" |
paul@394 | 1302 | else: |
paul@538 | 1303 | modname = name |
paul@538 | 1304 | |
paul@538 | 1305 | return "__builtins__.%s" % modname |
paul@366 | 1306 | |
paul@366 | 1307 | def get_builtin_type(name): |
paul@366 | 1308 | |
paul@366 | 1309 | "Return the type name provided by the given Python value 'name'." |
paul@366 | 1310 | |
paul@394 | 1311 | if name == "str": |
paul@394 | 1312 | return "string" |
paul@394 | 1313 | elif name == "unicode": |
paul@394 | 1314 | return "utf8string" |
paul@394 | 1315 | else: |
paul@394 | 1316 | return name |
paul@366 | 1317 | |
paul@538 | 1318 | def get_builtin_class(name): |
paul@538 | 1319 | |
paul@538 | 1320 | "Return the full name of the built-in class having the given 'name'." |
paul@538 | 1321 | |
paul@538 | 1322 | typename = get_builtin_type(name) |
paul@538 | 1323 | module = get_builtin_module(typename) |
paul@538 | 1324 | return "%s.%s" % (module, typename) |
paul@538 | 1325 | |
paul@0 | 1326 | # Useful data. |
paul@0 | 1327 | |
paul@11 | 1328 | predefined_constants = "False", "None", "NotImplemented", "True" |
paul@0 | 1329 | |
paul@0 | 1330 | operator_functions = { |
paul@0 | 1331 | |
paul@0 | 1332 | # Fundamental operations. |
paul@0 | 1333 | |
paul@0 | 1334 | "is" : "is_", |
paul@0 | 1335 | "is not" : "is_not", |
paul@0 | 1336 | |
paul@0 | 1337 | # Binary operations. |
paul@0 | 1338 | |
paul@0 | 1339 | "in" : "in_", |
paul@0 | 1340 | "not in" : "not_in", |
paul@0 | 1341 | "Add" : "add", |
paul@0 | 1342 | "Bitand" : "and_", |
paul@0 | 1343 | "Bitor" : "or_", |
paul@0 | 1344 | "Bitxor" : "xor", |
paul@0 | 1345 | "Div" : "div", |
paul@0 | 1346 | "FloorDiv" : "floordiv", |
paul@0 | 1347 | "LeftShift" : "lshift", |
paul@0 | 1348 | "Mod" : "mod", |
paul@0 | 1349 | "Mul" : "mul", |
paul@0 | 1350 | "Power" : "pow", |
paul@0 | 1351 | "RightShift" : "rshift", |
paul@0 | 1352 | "Sub" : "sub", |
paul@0 | 1353 | |
paul@0 | 1354 | # Unary operations. |
paul@0 | 1355 | |
paul@0 | 1356 | "Invert" : "invert", |
paul@0 | 1357 | "UnaryAdd" : "pos", |
paul@0 | 1358 | "UnarySub" : "neg", |
paul@0 | 1359 | |
paul@0 | 1360 | # Augmented assignment. |
paul@0 | 1361 | |
paul@0 | 1362 | "+=" : "iadd", |
paul@0 | 1363 | "-=" : "isub", |
paul@0 | 1364 | "*=" : "imul", |
paul@0 | 1365 | "/=" : "idiv", |
paul@0 | 1366 | "//=" : "ifloordiv", |
paul@0 | 1367 | "%=" : "imod", |
paul@0 | 1368 | "**=" : "ipow", |
paul@0 | 1369 | "<<=" : "ilshift", |
paul@0 | 1370 | ">>=" : "irshift", |
paul@0 | 1371 | "&=" : "iand", |
paul@0 | 1372 | "^=" : "ixor", |
paul@0 | 1373 | "|=" : "ior", |
paul@0 | 1374 | |
paul@0 | 1375 | # Comparisons. |
paul@0 | 1376 | |
paul@0 | 1377 | "==" : "eq", |
paul@0 | 1378 | "!=" : "ne", |
paul@0 | 1379 | "<" : "lt", |
paul@0 | 1380 | "<=" : "le", |
paul@0 | 1381 | ">=" : "ge", |
paul@0 | 1382 | ">" : "gt", |
paul@0 | 1383 | } |
paul@0 | 1384 | |
paul@0 | 1385 | # vim: tabstop=4 expandtab shiftwidth=4 |