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