Lichen

Annotated common.py

600:f92610e27e92
2017-02-19 Paul Boddie Merged changes from the default branch. method-wrapper-for-context
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@553 117
        self.in_invocation = None
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@548 629
        if n.flags == "OP_ASSIGN": op = "setslice"
paul@548 630
        elif n.flags == "OP_DELETE": op = "delslice"
paul@548 631
        else: op = "getslice"
paul@548 632
paul@0 633
        invocation = compiler.ast.CallFunc(
paul@0 634
            compiler.ast.Name("$op%s" % op),
paul@0 635
            [n.expr, n.lower or compiler.ast.Name("None"), n.upper or compiler.ast.Name("None")] +
paul@0 636
                (expr and [expr] or [])
paul@0 637
            )
paul@548 638
paul@548 639
        # Fix parse tree structure.
paul@548 640
paul@548 641
        if op == "delslice":
paul@548 642
            invocation = compiler.ast.Discard(invocation)
paul@548 643
paul@0 644
        return self.process_structure_node(invocation)
paul@0 645
paul@0 646
    def process_sliceobj_node(self, n):
paul@0 647
paul@0 648
        """
paul@0 649
        Process the given slice object node 'n' as a slice constructor.
paul@0 650
        """
paul@0 651
paul@0 652
        op = "slice"
paul@0 653
        invocation = compiler.ast.CallFunc(
paul@0 654
            compiler.ast.Name("$op%s" % op),
paul@0 655
            n.nodes
paul@0 656
            )
paul@0 657
        return self.process_structure_node(invocation)
paul@0 658
paul@0 659
    def process_subscript_node(self, n, expr=None):
paul@0 660
paul@0 661
        """
paul@0 662
        Process the given subscript node 'n' as an operator function invocation.
paul@0 663
        """
paul@0 664
paul@548 665
        if n.flags == "OP_ASSIGN": op = "setitem"
paul@548 666
        elif n.flags == "OP_DELETE": op = "delitem"
paul@548 667
        else: op = "getitem"
paul@548 668
paul@0 669
        invocation = compiler.ast.CallFunc(
paul@0 670
            compiler.ast.Name("$op%s" % op),
paul@0 671
            [n.expr] + list(n.subs) + (expr and [expr] or [])
paul@0 672
            )
paul@548 673
paul@548 674
        # Fix parse tree structure.
paul@548 675
paul@548 676
        if op == "delitem":
paul@548 677
            invocation = compiler.ast.Discard(invocation)
paul@548 678
paul@0 679
        return self.process_structure_node(invocation)
paul@0 680
paul@0 681
    def process_attribute_chain(self, n):
paul@0 682
paul@0 683
        """
paul@0 684
        Process the given attribute access node 'n'. Return a reference
paul@0 685
        describing the expression.
paul@0 686
        """
paul@0 687
paul@0 688
        # AssAttr/Getattr are nested with the outermost access being the last
paul@0 689
        # access in any chain.
paul@0 690
paul@0 691
        self.attrs.insert(0, n.attrname)
paul@0 692
        attrs = self.attrs
paul@0 693
paul@0 694
        # Break attribute chains where non-access nodes are found.
paul@0 695
paul@0 696
        if not self.have_access_expression(n):
paul@110 697
            self.reset_attribute_chain()
paul@0 698
paul@0 699
        # Descend into the expression, extending backwards any existing chain,
paul@0 700
        # or building another for the expression.
paul@0 701
paul@0 702
        name_ref = self.process_structure_node(n.expr)
paul@0 703
paul@0 704
        # Restore chain information applying to this node.
paul@0 705
paul@110 706
        if not self.have_access_expression(n):
paul@110 707
            self.restore_attribute_chain(attrs)
paul@0 708
paul@0 709
        # Return immediately if the expression was another access and thus a
paul@0 710
        # continuation backwards along the chain. The above processing will
paul@0 711
        # have followed the chain all the way to its conclusion.
paul@0 712
paul@0 713
        if self.have_access_expression(n):
paul@0 714
            del self.attrs[0]
paul@0 715
paul@0 716
        return name_ref
paul@0 717
paul@124 718
    # Attribute chain handling.
paul@124 719
paul@110 720
    def reset_attribute_chain(self):
paul@110 721
paul@110 722
        "Reset the attribute chain for a subexpression of an attribute access."
paul@110 723
paul@110 724
        self.attrs = []
paul@124 725
        self.chain_assignment.append(self.in_assignment)
paul@124 726
        self.chain_invocation.append(self.in_invocation)
paul@124 727
        self.in_assignment = None
paul@553 728
        self.in_invocation = None
paul@110 729
paul@110 730
    def restore_attribute_chain(self, attrs):
paul@110 731
paul@110 732
        "Restore the attribute chain for an attribute access."
paul@110 733
paul@110 734
        self.attrs = attrs
paul@124 735
        self.in_assignment = self.chain_assignment.pop()
paul@124 736
        self.in_invocation = self.chain_invocation.pop()
paul@110 737
paul@0 738
    def have_access_expression(self, node):
paul@0 739
paul@0 740
        "Return whether the expression associated with 'node' is Getattr."
paul@0 741
paul@0 742
        return isinstance(node.expr, compiler.ast.Getattr)
paul@0 743
paul@597 744
    def get_name_for_tracking(self, name, ref=None):
paul@0 745
paul@0 746
        """
paul@0 747
        Return the name to be used for attribute usage observations involving
paul@597 748
        the given 'name' in the current namespace. If 'ref' is indicated and
paul@597 749
        the name is being used outside a function, return the origin information
paul@597 750
        from 'ref'; otherwise, return a path computed using the current
paul@597 751
        namespace and the given name.
paul@0 752
paul@0 753
        The intention of this method is to provide a suitably-qualified name
paul@0 754
        that can be tracked across namespaces. Where globals are being
paul@0 755
        referenced in class namespaces, they should be referenced using their
paul@0 756
        path within the module, not using a path within each class.
paul@0 757
paul@0 758
        It may not be possible to identify a global within a function at the
paul@0 759
        time of inspection (since a global may appear later in a file).
paul@0 760
        Consequently, globals are identified by their local name rather than
paul@0 761
        their module-qualified path.
paul@0 762
        """
paul@0 763
paul@0 764
        # For functions, use the appropriate local names.
paul@0 765
paul@0 766
        if self.in_function:
paul@0 767
            return name
paul@0 768
paul@0 769
        # For static namespaces, use the given qualified name.
paul@0 770
paul@597 771
        elif ref and ref.static():
paul@597 772
            return ref.get_origin()
paul@597 773
paul@597 774
        # For non-static objects in static namespaces, use any alias.
paul@597 775
paul@597 776
        elif ref and ref.get_name():
paul@597 777
            return ref.get_name()
paul@0 778
paul@152 779
        # Otherwise, establish a name in the current namespace.
paul@0 780
paul@0 781
        else:
paul@0 782
            return self.get_object_path(name)
paul@0 783
paul@0 784
    def get_path_for_access(self):
paul@0 785
paul@0 786
        "Outside functions, register accesses at the module level."
paul@0 787
paul@0 788
        if not self.in_function:
paul@0 789
            return self.name
paul@0 790
        else:
paul@0 791
            return self.get_namespace_path()
paul@0 792
paul@0 793
    def get_module_name(self, node):
paul@0 794
paul@0 795
        """
paul@0 796
        Using the given From 'node' in this module, calculate any relative import
paul@0 797
        information, returning a tuple containing a module to import along with any
paul@0 798
        names to import based on the node's name information.
paul@0 799
paul@0 800
        Where the returned module is given as None, whole module imports should
paul@0 801
        be performed for the returned modules using the returned names.
paul@0 802
        """
paul@0 803
paul@0 804
        # Absolute import.
paul@0 805
paul@0 806
        if node.level == 0:
paul@0 807
            return node.modname, node.names
paul@0 808
paul@0 809
        # Relative to an ancestor of this module.
paul@0 810
paul@0 811
        else:
paul@0 812
            path = self.name.split(".")
paul@0 813
            level = node.level
paul@0 814
paul@0 815
            # Relative imports treat package roots as submodules.
paul@0 816
paul@0 817
            if split(self.filename)[-1] == "__init__.py":
paul@0 818
                level -= 1
paul@0 819
paul@0 820
            if level > len(path):
paul@0 821
                raise InspectError("Relative import %r involves too many levels up from module %r" % (
paul@0 822
                    ("%s%s" % ("." * node.level, node.modname or "")), self.name))
paul@0 823
paul@0 824
            basename = ".".join(path[:len(path)-level])
paul@0 825
paul@0 826
        # Name imports from a module.
paul@0 827
paul@0 828
        if node.modname:
paul@0 829
            return "%s.%s" % (basename, node.modname), node.names
paul@0 830
paul@0 831
        # Relative whole module imports.
paul@0 832
paul@0 833
        else:
paul@0 834
            return basename, node.names
paul@0 835
paul@0 836
def get_argnames(args):
paul@0 837
paul@0 838
    """
paul@0 839
    Return a list of all names provided by 'args'. Since tuples may be
paul@0 840
    employed, the arguments are traversed depth-first.
paul@0 841
    """
paul@0 842
paul@0 843
    l = []
paul@0 844
    for arg in args:
paul@0 845
        if isinstance(arg, tuple):
paul@0 846
            l += get_argnames(arg)
paul@0 847
        else:
paul@0 848
            l.append(arg)
paul@0 849
    return l
paul@0 850
paul@509 851
def get_names_from_nodes(nodes):
paul@509 852
paul@509 853
    """
paul@509 854
    Return the names employed in the given 'nodes' along with the number of
paul@509 855
    nodes excluding sequences.
paul@509 856
    """
paul@509 857
paul@509 858
    names = set()
paul@509 859
    count = 0
paul@509 860
paul@509 861
    for node in nodes:
paul@509 862
paul@509 863
        # Add names and count them.
paul@509 864
paul@509 865
        if isinstance(node, (compiler.ast.AssName, compiler.ast.Name)):
paul@509 866
            names.add(node.name)
paul@509 867
            count += 1
paul@509 868
paul@509 869
        # Add names from sequences and incorporate their counts.
paul@509 870
paul@509 871
        elif isinstance(node, (compiler.ast.AssList, compiler.ast.AssTuple,
paul@509 872
                               compiler.ast.List, compiler.ast.Set,
paul@509 873
                               compiler.ast.Tuple)):
paul@509 874
            _names, _count = get_names_from_nodes(node.nodes)
paul@509 875
            names.update(_names)
paul@509 876
            count += _count
paul@509 877
paul@509 878
        # Count non-name, non-sequence nodes.
paul@509 879
paul@509 880
        else:
paul@509 881
            count += 1
paul@509 882
paul@509 883
    return names, count
paul@509 884
paul@491 885
# Result classes.
paul@491 886
paul@491 887
class InstructionSequence:
paul@491 888
paul@491 889
    "A generic sequence of instructions."
paul@491 890
paul@491 891
    def __init__(self, instructions):
paul@491 892
        self.instructions = instructions
paul@491 893
paul@491 894
    def get_value_instruction(self):
paul@491 895
        return self.instructions[-1]
paul@491 896
paul@491 897
    def get_init_instructions(self):
paul@491 898
        return self.instructions[:-1]
paul@491 899
paul@0 900
# Dictionary utilities.
paul@0 901
paul@0 902
def init_item(d, key, fn):
paul@0 903
paul@0 904
    """
paul@0 905
    Add to 'd' an entry for 'key' using the callable 'fn' to make an initial
paul@0 906
    value where no entry already exists.
paul@0 907
    """
paul@0 908
paul@0 909
    if not d.has_key(key):
paul@0 910
        d[key] = fn()
paul@0 911
    return d[key]
paul@0 912
paul@0 913
def dict_for_keys(d, keys):
paul@0 914
paul@0 915
    "Return a new dictionary containing entries from 'd' for the given 'keys'."
paul@0 916
paul@0 917
    nd = {}
paul@0 918
    for key in keys:
paul@0 919
        if d.has_key(key):
paul@0 920
            nd[key] = d[key]
paul@0 921
    return nd
paul@0 922
paul@0 923
def make_key(s):
paul@0 924
paul@0 925
    "Make sequence 's' into a tuple-based key, first sorting its contents."
paul@0 926
paul@0 927
    l = list(s)
paul@0 928
    l.sort()
paul@0 929
    return tuple(l)
paul@0 930
paul@0 931
def add_counter_item(d, key):
paul@0 932
paul@0 933
    """
paul@0 934
    Make a mapping in 'd' for 'key' to the number of keys added before it, thus
paul@0 935
    maintaining a mapping of keys to their order of insertion.
paul@0 936
    """
paul@0 937
paul@0 938
    if not d.has_key(key):
paul@0 939
        d[key] = len(d.keys())
paul@0 940
    return d[key] 
paul@0 941
paul@0 942
def remove_items(d1, d2):
paul@0 943
paul@0 944
    "Remove from 'd1' all items from 'd2'."
paul@0 945
paul@0 946
    for key in d2.keys():
paul@0 947
        if d1.has_key(key):
paul@0 948
            del d1[key]
paul@0 949
paul@0 950
# Set utilities.
paul@0 951
paul@0 952
def first(s):
paul@0 953
    return list(s)[0]
paul@0 954
paul@0 955
def same(s1, s2):
paul@0 956
    return set(s1) == set(s2)
paul@0 957
paul@0 958
# General input/output.
paul@0 959
paul@0 960
def readfile(filename):
paul@0 961
paul@0 962
    "Return the contents of 'filename'."
paul@0 963
paul@0 964
    f = open(filename)
paul@0 965
    try:
paul@0 966
        return f.read()
paul@0 967
    finally:
paul@0 968
        f.close()
paul@0 969
paul@0 970
def writefile(filename, s):
paul@0 971
paul@0 972
    "Write to 'filename' the string 's'."
paul@0 973
paul@0 974
    f = open(filename, "w")
paul@0 975
    try:
paul@0 976
        f.write(s)
paul@0 977
    finally:
paul@0 978
        f.close()
paul@0 979
paul@0 980
# General encoding.
paul@0 981
paul@0 982
def sorted_output(x):
paul@0 983
paul@0 984
    "Sort sequence 'x' and return a string with commas separating the values."
paul@0 985
paul@0 986
    x = map(str, x)
paul@0 987
    x.sort()
paul@0 988
    return ", ".join(x)
paul@0 989
paul@537 990
def get_string_details(literals, encoding):
paul@512 991
paul@512 992
    """
paul@537 993
    Determine whether 'literals' represent Unicode strings or byte strings,
paul@537 994
    using 'encoding' to reproduce byte sequences.
paul@537 995
paul@537 996
    Each literal is the full program representation including prefix and quotes
paul@537 997
    recoded by the parser to UTF-8. Thus, any literal found to represent a byte
paul@537 998
    string needs to be translated back to its original encoding.
paul@537 999
paul@537 1000
    Return a single encoded literal value, a type name, and the original
paul@537 1001
    encoding as a tuple.
paul@537 1002
    """
paul@537 1003
paul@537 1004
    typename = "unicode"
paul@537 1005
paul@537 1006
    l = []
paul@537 1007
paul@537 1008
    for s in literals:
paul@537 1009
        out, _typename = get_literal_details(s)
paul@537 1010
        if _typename == "str":
paul@537 1011
            typename = "str"
paul@537 1012
        l.append(out)
paul@537 1013
paul@537 1014
    out = "".join(l)
paul@537 1015
paul@537 1016
    # For Unicode values, convert to the UTF-8 program representation.
paul@537 1017
paul@537 1018
    if typename == "unicode":
paul@537 1019
        return out.encode("utf-8"), typename, encoding
paul@537 1020
paul@537 1021
    # For byte string values, convert back to the original encoding.
paul@537 1022
paul@537 1023
    else:
paul@537 1024
        return out.encode(encoding), typename, encoding
paul@537 1025
paul@537 1026
def get_literal_details(s):
paul@537 1027
paul@537 1028
    """
paul@537 1029
    Determine whether 's' represents a Unicode string or a byte string, where
paul@537 1030
    's' contains the full program representation of a literal including prefix
paul@537 1031
    and quotes, recoded by the parser to UTF-8.
paul@512 1032
paul@512 1033
    Find and convert Unicode values starting with <backslash>u or <backslash>U,
paul@512 1034
    and byte or Unicode values starting with <backslash><octal digit> or
paul@512 1035
    <backslash>x.
paul@512 1036
paul@512 1037
    Literals prefixed with "u" cause <backslash><octal digit> and <backslash>x
paul@512 1038
    to be considered as Unicode values. Otherwise, they produce byte values and
paul@512 1039
    cause unprefixed strings to be considered as byte strings.
paul@512 1040
paul@512 1041
    Literals prefixed with "r" do not have their backslash-encoded values
paul@512 1042
    converted unless also prefixed with "u", in which case only the above value
paul@512 1043
    formats are converted, not any of the other special sequences for things
paul@512 1044
    like newlines.
paul@512 1045
paul@537 1046
    Return the literal value as a Unicode object together with the appropriate
paul@537 1047
    type name in a tuple.
paul@512 1048
    """
paul@512 1049
paul@512 1050
    l = []
paul@512 1051
paul@512 1052
    # Identify the quote character and use it to identify the prefix.
paul@512 1053
paul@512 1054
    quote_type = s[-1]
paul@512 1055
    prefix_end = s.find(quote_type)
paul@512 1056
    prefix = s[:prefix_end].lower()
paul@512 1057
paul@512 1058
    if prefix not in ("", "b", "br", "r", "u", "ur"):
paul@512 1059
        raise ValueError, "String literal does not have a supported prefix: %s" % s
paul@512 1060
paul@513 1061
    if "b" in prefix:
paul@513 1062
        typename = "str"
paul@513 1063
    else:
paul@513 1064
        typename = "unicode"
paul@513 1065
paul@512 1066
    # Identify triple quotes or single quotes.
paul@512 1067
paul@512 1068
    if len(s) >= 6 and s[-2] == quote_type and s[-3] == quote_type:
paul@512 1069
        quote = s[prefix_end:prefix_end+3]
paul@512 1070
        current = prefix_end + 3
paul@512 1071
        end = len(s) - 3
paul@512 1072
    else:
paul@512 1073
        quote = s[prefix_end]
paul@512 1074
        current = prefix_end + 1
paul@512 1075
        end = len(s) - 1
paul@512 1076
paul@512 1077
    # Conversions of some quoted values.
paul@512 1078
paul@512 1079
    searches = {
paul@512 1080
        "u" : (6, 16),
paul@512 1081
        "U" : (10, 16),
paul@512 1082
        "x" : (4, 16),
paul@512 1083
        }
paul@512 1084
paul@512 1085
    octal_digits = map(str, range(0, 8))
paul@512 1086
paul@512 1087
    # Translations of some quoted values.
paul@512 1088
paul@512 1089
    escaped = {
paul@512 1090
        "\\" : "\\", "'" : "'", '"' : '"',
paul@512 1091
        "a" : "\a", "b" : "\b", "f" : "\f",
paul@512 1092
        "n" : "\n", "r" : "\r", "t" : "\t",
paul@512 1093
        }
paul@512 1094
paul@512 1095
    while current < end:
paul@512 1096
paul@512 1097
        # Look for quoted values.
paul@512 1098
paul@512 1099
        index = s.find("\\", current)
paul@512 1100
        if index == -1 or index + 1 == end:
paul@512 1101
            l.append(s[current:end])
paul@512 1102
            break
paul@512 1103
paul@512 1104
        # Add the preceding text.
paul@512 1105
paul@512 1106
        l.append(s[current:index])
paul@512 1107
paul@512 1108
        # Handle quoted text.
paul@512 1109
paul@512 1110
        term = s[index+1]
paul@512 1111
paul@512 1112
        # Add Unicode values. Where a string is u-prefixed, even \o and \x
paul@512 1113
        # produce Unicode values.
paul@512 1114
paul@513 1115
        if typename == "unicode" and (
paul@513 1116
            term in ("u", "U") or 
paul@513 1117
            "u" in prefix and (term == "x" or term in octal_digits)):
paul@512 1118
paul@512 1119
            needed, base = searches.get(term, (4, 8))
paul@512 1120
            value = convert_quoted_value(s, index, needed, end, base, unichr)
paul@512 1121
            l.append(value)
paul@512 1122
            current = index + needed
paul@512 1123
paul@512 1124
        # Add raw byte values, changing the string type.
paul@512 1125
paul@512 1126
        elif "r" not in prefix and (
paul@512 1127
             term == "x" or term in octal_digits):
paul@512 1128
paul@512 1129
            needed, base = searches.get(term, (4, 8))
paul@512 1130
            value = convert_quoted_value(s, index, needed, end, base, chr)
paul@512 1131
            l.append(value)
paul@512 1132
            typename = "str"
paul@512 1133
            current = index + needed
paul@512 1134
paul@512 1135
        # Add other escaped values.
paul@512 1136
paul@512 1137
        elif "r" not in prefix and escaped.has_key(term):
paul@512 1138
            l.append(escaped[term])
paul@512 1139
            current = index + 2
paul@512 1140
paul@512 1141
        # Add other text as found.
paul@512 1142
paul@512 1143
        else:
paul@512 1144
            l.append(s[index:index+2])
paul@512 1145
            current = index + 2
paul@512 1146
paul@537 1147
    # Collect the components into a single Unicode object. Since the literal
paul@537 1148
    # text was already in UTF-8 form, interpret plain strings as UTF-8
paul@537 1149
    # sequences.
paul@512 1150
paul@537 1151
    out = []
paul@512 1152
paul@537 1153
    for value in l:
paul@537 1154
        if isinstance(value, unicode):
paul@537 1155
            out.append(value)
paul@537 1156
        else:
paul@537 1157
            out.append(unicode(value, "utf-8"))
paul@512 1158
paul@537 1159
    return "".join(out), typename
paul@512 1160
paul@512 1161
def convert_quoted_value(s, index, needed, end, base, fn):
paul@512 1162
paul@512 1163
    """
paul@512 1164
    Interpret a quoted value in 's' at 'index' with the given 'needed' number of
paul@512 1165
    positions, and with the given 'end' indicating the first position after the
paul@512 1166
    end of the actual string content.
paul@512 1167
paul@512 1168
    Use 'base' as the numerical base when interpreting the value, and use 'fn'
paul@512 1169
    to convert the value to an appropriate type.
paul@512 1170
    """
paul@512 1171
paul@512 1172
    s = s[index:min(index+needed, end)]
paul@512 1173
paul@512 1174
    # Not a complete occurrence.
paul@512 1175
paul@512 1176
    if len(s) < needed:
paul@512 1177
        return s
paul@512 1178
paul@512 1179
    # Test for a well-formed value.
paul@512 1180
paul@512 1181
    try:
paul@512 1182
        first = base == 8 and 1 or 2
paul@512 1183
        value = int(s[first:needed], base)
paul@512 1184
    except ValueError:
paul@512 1185
        return s
paul@512 1186
    else:
paul@512 1187
        return fn(value)
paul@512 1188
paul@0 1189
# Attribute chain decoding.
paul@0 1190
paul@0 1191
def get_attrnames(attrnames):
paul@11 1192
paul@11 1193
    """
paul@11 1194
    Split the qualified attribute chain 'attrnames' into its components,
paul@11 1195
    handling special attributes starting with "#" that indicate type
paul@11 1196
    conformance.
paul@11 1197
    """
paul@11 1198
paul@0 1199
    if attrnames.startswith("#"):
paul@0 1200
        return [attrnames]
paul@0 1201
    else:
paul@0 1202
        return attrnames.split(".")
paul@0 1203
paul@0 1204
def get_attrname_from_location(location):
paul@11 1205
paul@11 1206
    """
paul@11 1207
    Extract the first attribute from the attribute names employed in a
paul@11 1208
    'location'.
paul@11 1209
    """
paul@11 1210
paul@0 1211
    path, name, attrnames, access = location
paul@91 1212
    if not attrnames:
paul@91 1213
        return attrnames
paul@0 1214
    return get_attrnames(attrnames)[0]
paul@0 1215
paul@85 1216
def get_name_path(path, name):
paul@85 1217
paul@85 1218
    "Return a suitable qualified name from the given 'path' and 'name'."
paul@85 1219
paul@85 1220
    if "." in name:
paul@85 1221
        return name
paul@85 1222
    else:
paul@85 1223
        return "%s.%s" % (path, name)
paul@85 1224
paul@90 1225
# Usage-related functions.
paul@89 1226
paul@89 1227
def get_types_for_usage(attrnames, objects):
paul@89 1228
paul@89 1229
    """
paul@89 1230
    Identify the types that can support the given 'attrnames', using the
paul@89 1231
    given 'objects' as the catalogue of type details.
paul@89 1232
    """
paul@89 1233
paul@89 1234
    types = []
paul@89 1235
    for name, _attrnames in objects.items():
paul@89 1236
        if set(attrnames).issubset(_attrnames):
paul@89 1237
            types.append(name)
paul@89 1238
    return types
paul@89 1239
paul@90 1240
def get_invoked_attributes(usage):
paul@90 1241
paul@90 1242
    "Obtain invoked attribute from the given 'usage'."
paul@90 1243
paul@90 1244
    invoked = []
paul@90 1245
    if usage:
paul@107 1246
        for attrname, invocation, assignment in usage:
paul@90 1247
            if invocation:
paul@90 1248
                invoked.append(attrname)
paul@90 1249
    return invoked
paul@90 1250
paul@107 1251
def get_assigned_attributes(usage):
paul@107 1252
paul@107 1253
    "Obtain assigned attribute from the given 'usage'."
paul@107 1254
paul@107 1255
    assigned = []
paul@107 1256
    if usage:
paul@107 1257
        for attrname, invocation, assignment in usage:
paul@107 1258
            if assignment:
paul@107 1259
                assigned.append(attrname)
paul@107 1260
    return assigned
paul@107 1261
paul@366 1262
# Type and module functions.
paul@538 1263
# NOTE: This makes assumptions about the __builtins__ structure.
paul@366 1264
paul@366 1265
def get_builtin_module(name):
paul@366 1266
paul@366 1267
    "Return the module name containing the given type 'name'."
paul@366 1268
paul@394 1269
    if name == "string":
paul@538 1270
        modname = "str"
paul@394 1271
    elif name == "utf8string":
paul@538 1272
        modname = "unicode"
paul@394 1273
    elif name == "NoneType":
paul@538 1274
        modname = "none"
paul@394 1275
    else:
paul@538 1276
        modname = name
paul@538 1277
paul@538 1278
    return "__builtins__.%s" % modname
paul@366 1279
paul@366 1280
def get_builtin_type(name):
paul@366 1281
paul@366 1282
    "Return the type name provided by the given Python value 'name'."
paul@366 1283
paul@394 1284
    if name == "str":
paul@394 1285
        return "string"
paul@394 1286
    elif name == "unicode":
paul@394 1287
        return "utf8string"
paul@394 1288
    else:
paul@394 1289
        return name
paul@366 1290
paul@538 1291
def get_builtin_class(name):
paul@538 1292
paul@538 1293
    "Return the full name of the built-in class having the given 'name'."
paul@538 1294
paul@538 1295
    typename = get_builtin_type(name)
paul@538 1296
    module = get_builtin_module(typename)
paul@538 1297
    return "%s.%s" % (module, typename)
paul@538 1298
paul@0 1299
# Useful data.
paul@0 1300
paul@11 1301
predefined_constants = "False", "None", "NotImplemented", "True"
paul@0 1302
paul@0 1303
operator_functions = {
paul@0 1304
paul@0 1305
    # Fundamental operations.
paul@0 1306
paul@0 1307
    "is" : "is_",
paul@0 1308
    "is not" : "is_not",
paul@0 1309
paul@0 1310
    # Binary operations.
paul@0 1311
paul@0 1312
    "in" : "in_",
paul@0 1313
    "not in" : "not_in",
paul@0 1314
    "Add" : "add",
paul@0 1315
    "Bitand" : "and_",
paul@0 1316
    "Bitor" : "or_",
paul@0 1317
    "Bitxor" : "xor",
paul@0 1318
    "Div" : "div",
paul@0 1319
    "FloorDiv" : "floordiv",
paul@0 1320
    "LeftShift" : "lshift",
paul@0 1321
    "Mod" : "mod",
paul@0 1322
    "Mul" : "mul",
paul@0 1323
    "Power" : "pow",
paul@0 1324
    "RightShift" : "rshift",
paul@0 1325
    "Sub" : "sub",
paul@0 1326
paul@0 1327
    # Unary operations.
paul@0 1328
paul@0 1329
    "Invert" : "invert",
paul@0 1330
    "UnaryAdd" : "pos",
paul@0 1331
    "UnarySub" : "neg",
paul@0 1332
paul@0 1333
    # Augmented assignment.
paul@0 1334
paul@0 1335
    "+=" : "iadd",
paul@0 1336
    "-=" : "isub",
paul@0 1337
    "*=" : "imul",
paul@0 1338
    "/=" : "idiv",
paul@0 1339
    "//=" : "ifloordiv",
paul@0 1340
    "%=" : "imod",
paul@0 1341
    "**=" : "ipow",
paul@0 1342
    "<<=" : "ilshift",
paul@0 1343
    ">>=" : "irshift",
paul@0 1344
    "&=" : "iand",
paul@0 1345
    "^=" : "ixor",
paul@0 1346
    "|=" : "ior",
paul@0 1347
paul@0 1348
    # Comparisons.
paul@0 1349
paul@0 1350
    "==" : "eq",
paul@0 1351
    "!=" : "ne",
paul@0 1352
    "<" : "lt",
paul@0 1353
    "<=" : "le",
paul@0 1354
    ">=" : "ge",
paul@0 1355
    ">" : "gt",
paul@0 1356
    }
paul@0 1357
paul@0 1358
# vim: tabstop=4 expandtab shiftwidth=4