Lichen

Annotated translator.py

543:b7334adb7dec
2017-02-04 Paul Boddie Handle situations where a global accidentally refers to a built-in module.
paul@113 1
#!/usr/bin/env python
paul@113 2
paul@113 3
"""
paul@113 4
Translate programs.
paul@113 5
paul@482 6
Copyright (C) 2015, 2016, 2017 Paul Boddie <paul@boddie.org.uk>
paul@113 7
paul@113 8
This program is free software; you can redistribute it and/or modify it under
paul@113 9
the terms of the GNU General Public License as published by the Free Software
paul@113 10
Foundation; either version 3 of the License, or (at your option) any later
paul@113 11
version.
paul@113 12
paul@113 13
This program is distributed in the hope that it will be useful, but WITHOUT
paul@113 14
ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
paul@113 15
FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more
paul@113 16
details.
paul@113 17
paul@113 18
You should have received a copy of the GNU General Public License along with
paul@113 19
this program.  If not, see <http://www.gnu.org/licenses/>.
paul@113 20
"""
paul@113 21
paul@491 22
from common import CommonModule, CommonOutput, InstructionSequence, \
paul@538 23
                   first, get_builtin_class, init_item, predefined_constants
paul@523 24
from encoders import encode_access_instruction, \
paul@430 25
                     encode_function_pointer, encode_literal_constant, \
paul@430 26
                     encode_literal_instantiator, encode_instantiator_pointer, \
paul@491 27
                     encode_instructions, \
paul@430 28
                     encode_path, encode_symbol, encode_type_attribute, \
paul@430 29
                     is_type_attribute
paul@113 30
from os.path import exists, join
paul@113 31
from os import makedirs
paul@314 32
from referencing import Reference
paul@482 33
from StringIO import StringIO
paul@113 34
import compiler
paul@113 35
import results
paul@113 36
paul@113 37
class Translator(CommonOutput):
paul@113 38
paul@113 39
    "A program translator."
paul@113 40
paul@113 41
    def __init__(self, importer, deducer, optimiser, output):
paul@113 42
        self.importer = importer
paul@113 43
        self.deducer = deducer
paul@113 44
        self.optimiser = optimiser
paul@113 45
        self.output = output
paul@482 46
        self.modules = {}
paul@113 47
paul@113 48
    def to_output(self):
paul@113 49
        output = join(self.output, "src")
paul@113 50
paul@113 51
        if not exists(output):
paul@113 52
            makedirs(output)
paul@113 53
paul@113 54
        self.check_output()
paul@113 55
paul@113 56
        for module in self.importer.modules.values():
paul@354 57
            parts = module.name.split(".")
paul@354 58
            if parts[0] != "native":
paul@161 59
                tm = TranslatedModule(module.name, self.importer, self.deducer, self.optimiser)
paul@161 60
                tm.translate(module.filename, join(output, "%s.c" % module.name))
paul@482 61
                self.modules[module.name] = tm 
paul@113 62
paul@113 63
# Classes representing intermediate translation results.
paul@113 64
paul@113 65
class TranslationResult:
paul@113 66
paul@113 67
    "An abstract translation result mix-in."
paul@113 68
paul@234 69
    def get_accessor_kinds(self):
paul@234 70
        return None
paul@113 71
paul@144 72
class ReturnRef(TranslationResult):
paul@144 73
paul@144 74
    "Indicates usage of a return statement."
paul@144 75
paul@144 76
    pass
paul@144 77
paul@113 78
class Expression(results.Result, TranslationResult):
paul@113 79
paul@113 80
    "A general expression."
paul@113 81
paul@113 82
    def __init__(self, s):
paul@113 83
        self.s = s
paul@113 84
    def __str__(self):
paul@113 85
        return self.s
paul@113 86
    def __repr__(self):
paul@113 87
        return "Expression(%r)" % self.s
paul@113 88
paul@113 89
class TrResolvedNameRef(results.ResolvedNameRef, TranslationResult):
paul@113 90
paul@113 91
    "A reference to a name in the translation."
paul@113 92
paul@208 93
    def __init__(self, name, ref, expr=None, parameter=None):
paul@208 94
        results.ResolvedNameRef.__init__(self, name, ref, expr)
paul@208 95
        self.parameter = parameter
paul@208 96
paul@113 97
    def __str__(self):
paul@113 98
paul@113 99
        "Return an output representation of the referenced name."
paul@113 100
paul@113 101
        # For sources, any identified static origin will be constant and thus
paul@113 102
        # usable directly. For targets, no constant should be assigned and thus
paul@113 103
        # the alias (or any plain name) will be used.
paul@113 104
paul@137 105
        ref = self.static()
paul@137 106
        origin = ref and self.get_origin()
paul@137 107
        static_name = origin and encode_path(origin)
paul@149 108
paul@149 109
        # Determine whether a qualified name is involved.
paul@149 110
paul@338 111
        t = (not self.is_constant_alias() and self.get_name() or self.name).rsplit(".", 1)
paul@149 112
        parent = len(t) > 1 and t[0] or None
paul@338 113
        attrname = t[-1] and encode_path(t[-1])
paul@113 114
paul@113 115
        # Assignments.
paul@113 116
paul@113 117
        if self.expr:
paul@113 118
paul@113 119
            # Eliminate assignments between constants.
paul@113 120
paul@196 121
            if ref and isinstance(self.expr, results.ResolvedNameRef) and self.expr.static():
paul@113 122
                return ""
paul@149 123
paul@149 124
            # Qualified names must be converted into parent-relative assignments.
paul@149 125
paul@149 126
            elif parent:
paul@149 127
                return "__store_via_object(&%s, %s, %s)" % (
paul@149 128
                    encode_path(parent), encode_symbol("pos", attrname), self.expr)
paul@149 129
paul@149 130
            # All other assignments involve the names as they were given.
paul@149 131
paul@113 132
            else:
paul@208 133
                return "(%s%s) = %s" % (self.parameter and "*" or "", attrname, self.expr)
paul@113 134
paul@113 135
        # Expressions.
paul@113 136
paul@137 137
        elif static_name:
paul@137 138
            parent = ref.parent()
paul@141 139
            context = ref.has_kind("<function>") and encode_path(parent) or None
paul@477 140
            return "((__attr) {.context=%s, .value=&%s})" % (context and "&%s" % context or "0", static_name)
paul@137 141
paul@152 142
        # Qualified names must be converted into parent-relative accesses.
paul@152 143
paul@152 144
        elif parent:
paul@152 145
            return "__load_via_object(&%s, %s)" % (
paul@152 146
                encode_path(parent), encode_symbol("pos", attrname))
paul@152 147
paul@152 148
        # All other accesses involve the names as they were given.
paul@152 149
paul@113 150
        else:
paul@208 151
            return "(%s%s)" % (self.parameter and "*" or "", attrname)
paul@113 152
paul@113 153
class TrConstantValueRef(results.ConstantValueRef, TranslationResult):
paul@113 154
paul@113 155
    "A constant value reference in the translation."
paul@113 156
paul@113 157
    def __str__(self):
paul@136 158
        return encode_literal_constant(self.number)
paul@113 159
paul@113 160
class TrLiteralSequenceRef(results.LiteralSequenceRef, TranslationResult):
paul@113 161
paul@113 162
    "A reference representing a sequence of values."
paul@113 163
paul@113 164
    def __str__(self):
paul@113 165
        return str(self.node)
paul@113 166
paul@317 167
class TrInstanceRef(results.InstanceRef, TranslationResult):
paul@317 168
paul@317 169
    "A reference representing instantiation of a class."
paul@317 170
paul@317 171
    def __init__(self, ref, expr):
paul@317 172
paul@317 173
        """
paul@317 174
        Initialise the reference with 'ref' indicating the nature of the
paul@317 175
        reference and 'expr' being an expression used to create the instance.
paul@317 176
        """
paul@317 177
paul@317 178
        results.InstanceRef.__init__(self, ref)
paul@317 179
        self.expr = expr
paul@317 180
paul@317 181
    def __str__(self):
paul@317 182
        return self.expr
paul@317 183
paul@317 184
    def __repr__(self):
paul@317 185
        return "TrResolvedInstanceRef(%r, %r)" % (self.ref, self.expr)
paul@317 186
paul@491 187
class AttrResult(Expression, TranslationResult, InstructionSequence):
paul@113 188
paul@113 189
    "A translation result for an attribute access."
paul@113 190
paul@491 191
    def __init__(self, instructions, refs, accessor_kinds):
paul@491 192
        InstructionSequence.__init__(self, instructions)
paul@113 193
        self.refs = refs
paul@234 194
        self.accessor_kinds = accessor_kinds
paul@113 195
paul@113 196
    def get_origin(self):
paul@113 197
        return self.refs and len(self.refs) == 1 and first(self.refs).get_origin()
paul@113 198
paul@118 199
    def has_kind(self, kinds):
paul@118 200
        if not self.refs:
paul@118 201
            return False
paul@118 202
        for ref in self.refs:
paul@118 203
            if ref.has_kind(kinds):
paul@118 204
                return True
paul@118 205
        return False
paul@118 206
paul@234 207
    def get_accessor_kinds(self):
paul@234 208
        return self.accessor_kinds
paul@234 209
paul@491 210
    def __str__(self):
paul@491 211
        return encode_instructions(self.instructions)
paul@491 212
paul@113 213
    def __repr__(self):
paul@491 214
        return "AttrResult(%r, %r, %r)" % (self.instructions, self.refs, self.accessor_kinds)
paul@491 215
paul@498 216
class InvocationResult(Expression, TranslationResult, InstructionSequence):
paul@498 217
paul@498 218
    "A translation result for an invocation."
paul@498 219
paul@498 220
    def __init__(self, instructions):
paul@498 221
        InstructionSequence.__init__(self, instructions)
paul@498 222
paul@498 223
    def __str__(self):
paul@498 224
        return encode_instructions(self.instructions)
paul@498 225
paul@498 226
    def __repr__(self):
paul@498 227
        return "InvocationResult(%r)" % self.instructions
paul@498 228
paul@498 229
class InstantiationResult(InvocationResult, TrInstanceRef):
paul@498 230
paul@498 231
    "An instantiation result acting like an invocation result."
paul@498 232
paul@498 233
    def __init__(self, ref, instructions):
paul@498 234
        results.InstanceRef.__init__(self, ref)
paul@498 235
        InvocationResult.__init__(self, instructions)
paul@498 236
paul@498 237
    def __repr__(self):
paul@498 238
        return "InstantiationResult(%r, %r)" % (self.ref, self.instructions)
paul@498 239
paul@491 240
class PredefinedConstantRef(Expression, TranslationResult):
paul@113 241
paul@113 242
    "A predefined constant reference."
paul@113 243
paul@399 244
    def __init__(self, value, expr=None):
paul@113 245
        self.value = value
paul@399 246
        self.expr = expr
paul@113 247
paul@113 248
    def __str__(self):
paul@399 249
paul@399 250
        # Eliminate predefined constant assignments.
paul@399 251
paul@399 252
        if self.expr:
paul@399 253
            return ""
paul@399 254
paul@399 255
        # Generate the specific constants.
paul@399 256
paul@136 257
        if self.value in ("False", "True"):
paul@158 258
            return encode_path("__builtins__.boolean.%s" % self.value)
paul@136 259
        elif self.value == "None":
paul@136 260
            return encode_path("__builtins__.none.%s" % self.value)
paul@136 261
        elif self.value == "NotImplemented":
paul@136 262
            return encode_path("__builtins__.notimplemented.%s" % self.value)
paul@136 263
        else:
paul@136 264
            return self.value
paul@113 265
paul@113 266
    def __repr__(self):
paul@113 267
        return "PredefinedConstantRef(%r)" % self.value
paul@113 268
paul@141 269
class BooleanResult(Expression, TranslationResult):
paul@141 270
paul@141 271
    "A expression producing a boolean result."
paul@141 272
paul@141 273
    def __str__(self):
paul@141 274
        return "__builtins___bool_bool(%s)" % self.s
paul@141 275
paul@141 276
    def __repr__(self):
paul@141 277
        return "BooleanResult(%r)" % self.s
paul@141 278
paul@113 279
def make_expression(expr):
paul@113 280
paul@113 281
    "Make a new expression from the existing 'expr'."
paul@113 282
paul@113 283
    if isinstance(expr, results.Result):
paul@113 284
        return expr
paul@113 285
    else:
paul@113 286
        return Expression(str(expr))
paul@113 287
paul@113 288
# The actual translation process itself.
paul@113 289
paul@113 290
class TranslatedModule(CommonModule):
paul@113 291
paul@113 292
    "A module translator."
paul@113 293
paul@113 294
    def __init__(self, name, importer, deducer, optimiser):
paul@113 295
        CommonModule.__init__(self, name, importer)
paul@113 296
        self.deducer = deducer
paul@113 297
        self.optimiser = optimiser
paul@113 298
paul@113 299
        # Output stream.
paul@113 300
paul@482 301
        self.out_toplevel = self.out = None
paul@113 302
        self.indent = 0
paul@113 303
        self.tabstop = "    "
paul@113 304
paul@113 305
        # Recorded namespaces.
paul@113 306
paul@113 307
        self.namespaces = []
paul@113 308
        self.in_conditional = False
paul@113 309
paul@144 310
        # Exception raising adjustments.
paul@144 311
paul@144 312
        self.in_try_finally = False
paul@189 313
        self.in_try_except = False
paul@144 314
paul@237 315
        # Attribute access and accessor counting.
paul@113 316
paul@113 317
        self.attr_accesses = {}
paul@237 318
        self.attr_accessors = {}
paul@113 319
paul@482 320
        # Special variable usage.
paul@482 321
paul@482 322
        self.temp_usage = {}
paul@482 323
paul@113 324
    def __repr__(self):
paul@113 325
        return "TranslatedModule(%r, %r)" % (self.name, self.importer)
paul@113 326
paul@113 327
    def translate(self, filename, output_filename):
paul@113 328
paul@113 329
        """
paul@113 330
        Parse the file having the given 'filename', writing the translation to
paul@113 331
        the given 'output_filename'.
paul@113 332
        """
paul@113 333
paul@113 334
        self.parse_file(filename)
paul@113 335
paul@113 336
        # Collect function namespaces for separate processing.
paul@113 337
paul@113 338
        self.record_namespaces(self.astnode)
paul@113 339
paul@113 340
        # Reset the lambda naming (in order to obtain the same names again) and
paul@113 341
        # translate the program.
paul@113 342
paul@113 343
        self.reset_lambdas()
paul@113 344
paul@482 345
        self.out_toplevel = self.out = open(output_filename, "w")
paul@113 346
        try:
paul@128 347
            self.start_output()
paul@128 348
paul@113 349
            # Process namespaces, writing the translation.
paul@113 350
paul@113 351
            for path, node in self.namespaces:
paul@113 352
                self.process_namespace(path, node)
paul@113 353
paul@113 354
            # Process the module namespace including class namespaces.
paul@113 355
paul@113 356
            self.process_namespace([], self.astnode)
paul@113 357
paul@113 358
        finally:
paul@113 359
            self.out.close()
paul@113 360
paul@113 361
    def have_object(self):
paul@113 362
paul@113 363
        "Return whether a namespace is a recorded object."
paul@113 364
paul@113 365
        return self.importer.objects.get(self.get_namespace_path())
paul@113 366
paul@156 367
    def get_builtin_class(self, name):
paul@156 368
paul@156 369
        "Return a reference to the actual object providing 'name'."
paul@156 370
paul@538 371
        return self.importer.get_object(get_builtin_class(name))
paul@156 372
paul@156 373
    def is_method(self, path):
paul@156 374
paul@156 375
        "Return whether 'path' is a method."
paul@156 376
paul@113 377
        class_name, method_name = path.rsplit(".", 1)
paul@267 378
        return self.importer.classes.has_key(class_name) and class_name or None
paul@113 379
paul@208 380
    def in_method(self):
paul@208 381
paul@208 382
        "Return whether the current namespace provides a method."
paul@208 383
paul@208 384
        return self.in_function and self.is_method(self.get_namespace_path())
paul@208 385
paul@113 386
    # Namespace recording.
paul@113 387
paul@113 388
    def record_namespaces(self, node):
paul@113 389
paul@113 390
        "Process the program structure 'node', recording namespaces."
paul@113 391
paul@113 392
        for n in node.getChildNodes():
paul@113 393
            self.record_namespaces_in_node(n)
paul@113 394
paul@113 395
    def record_namespaces_in_node(self, node):
paul@113 396
paul@113 397
        "Process the program structure 'node', recording namespaces."
paul@113 398
paul@113 399
        # Function namespaces within modules, classes and other functions.
paul@113 400
        # Functions appearing within conditional statements are given arbitrary
paul@113 401
        # names.
paul@113 402
paul@113 403
        if isinstance(node, compiler.ast.Function):
paul@113 404
            self.record_function_node(node, (self.in_conditional or self.in_function) and self.get_lambda_name() or node.name)
paul@113 405
paul@113 406
        elif isinstance(node, compiler.ast.Lambda):
paul@113 407
            self.record_function_node(node, self.get_lambda_name())
paul@113 408
paul@113 409
        # Classes are visited, but may be ignored if inside functions.
paul@113 410
paul@113 411
        elif isinstance(node, compiler.ast.Class):
paul@113 412
            self.enter_namespace(node.name)
paul@113 413
            if self.have_object():
paul@113 414
                self.record_namespaces(node)
paul@113 415
            self.exit_namespace()
paul@113 416
paul@113 417
        # Conditional nodes are tracked so that function definitions may be
paul@113 418
        # handled. Since "for" loops are converted to "while" loops, they are
paul@113 419
        # included here.
paul@113 420
paul@113 421
        elif isinstance(node, (compiler.ast.For, compiler.ast.If, compiler.ast.While)):
paul@113 422
            in_conditional = self.in_conditional
paul@113 423
            self.in_conditional = True
paul@113 424
            self.record_namespaces(node)
paul@113 425
            self.in_conditional = in_conditional
paul@113 426
paul@113 427
        # All other nodes are processed depth-first.
paul@113 428
paul@113 429
        else:
paul@113 430
            self.record_namespaces(node)
paul@113 431
paul@113 432
    def record_function_node(self, n, name):
paul@113 433
paul@113 434
        """
paul@113 435
        Record the given function, lambda, if expression or list comprehension
paul@113 436
        node 'n' with the given 'name'.
paul@113 437
        """
paul@113 438
paul@113 439
        self.in_function = True
paul@113 440
        self.enter_namespace(name)
paul@113 441
paul@113 442
        if self.have_object():
paul@113 443
paul@113 444
            # Record the namespace path and the node itself.
paul@113 445
paul@113 446
            self.namespaces.append((self.namespace_path[:], n))
paul@113 447
            self.record_namespaces_in_node(n.code)
paul@113 448
paul@113 449
        self.exit_namespace()
paul@113 450
        self.in_function = False
paul@113 451
paul@113 452
    # Constant referencing.
paul@113 453
paul@405 454
    def get_literal_instance(self, n, name=None):
paul@113 455
paul@113 456
        """
paul@405 457
        For node 'n', return a reference for the type of the given 'name', or if
paul@405 458
        'name' is not specified, deduce the type from the value.
paul@113 459
        """
paul@113 460
paul@366 461
        # Handle stray None constants (Sliceobj seems to produce them).
paul@366 462
paul@405 463
        if name is None and n.value is None:
paul@366 464
            return self.process_name_node(compiler.ast.Name("None"))
paul@366 465
paul@113 466
        if name in ("dict", "list", "tuple"):
paul@405 467
            ref = self.get_builtin_class(name)
paul@113 468
            return self.process_literal_sequence_node(n, name, ref, TrLiteralSequenceRef)
paul@113 469
        else:
paul@537 470
            value, typename, encoding = self.get_constant_value(n.value, n.literals)
paul@538 471
            ref = self.get_builtin_class(typename)
paul@397 472
            value_type = ref.get_origin()
paul@397 473
paul@113 474
            path = self.get_namespace_path()
paul@406 475
paul@406 476
            # Obtain the local numbering of the constant and thus the
paul@406 477
            # locally-qualified name.
paul@406 478
paul@406 479
            local_number = self.importer.all_constants[path][(value, value_type, encoding)]
paul@113 480
            constant_name = "$c%d" % local_number
paul@113 481
            objpath = self.get_object_path(constant_name)
paul@406 482
paul@406 483
            # Obtain the unique identifier for the constant.
paul@406 484
paul@113 485
            number = self.optimiser.constant_numbers[objpath]
paul@394 486
            return TrConstantValueRef(constant_name, ref.instance_of(), value, number)
paul@113 487
paul@113 488
    # Namespace translation.
paul@113 489
paul@113 490
    def process_namespace(self, path, node):
paul@113 491
paul@113 492
        """
paul@113 493
        Process the namespace for the given 'path' defined by the given 'node'.
paul@113 494
        """
paul@113 495
paul@113 496
        self.namespace_path = path
paul@113 497
paul@113 498
        if isinstance(node, (compiler.ast.Function, compiler.ast.Lambda)):
paul@113 499
            self.in_function = True
paul@113 500
            self.process_function_body_node(node)
paul@113 501
        else:
paul@113 502
            self.in_function = False
paul@192 503
            self.function_target = 0
paul@113 504
            self.start_module()
paul@113 505
            self.process_structure(node)
paul@113 506
            self.end_module()
paul@113 507
paul@113 508
    def process_structure(self, node):
paul@113 509
paul@113 510
        "Process the given 'node' or result."
paul@113 511
paul@144 512
        # Handle processing requests on results.
paul@144 513
paul@113 514
        if isinstance(node, results.Result):
paul@113 515
            return node
paul@144 516
paul@144 517
        # Handle processing requests on nodes.
paul@144 518
paul@113 519
        else:
paul@144 520
            l = CommonModule.process_structure(self, node)
paul@144 521
paul@144 522
            # Return indications of return statement usage.
paul@144 523
paul@144 524
            if l and isinstance(l[-1], ReturnRef):
paul@144 525
                return l[-1]
paul@144 526
            else:
paul@144 527
                return None
paul@113 528
paul@113 529
    def process_structure_node(self, n):
paul@113 530
paul@113 531
        "Process the individual node 'n'."
paul@113 532
paul@113 533
        # Plain statements emit their expressions.
paul@113 534
paul@113 535
        if isinstance(n, compiler.ast.Discard):
paul@113 536
            expr = self.process_structure_node(n.expr)
paul@113 537
            self.statement(expr)
paul@113 538
paul@314 539
        # Module import declarations.
paul@314 540
paul@314 541
        elif isinstance(n, compiler.ast.From):
paul@314 542
            self.process_from_node(n)
paul@314 543
paul@113 544
        # Nodes using operator module functions.
paul@113 545
paul@113 546
        elif isinstance(n, compiler.ast.Operator):
paul@113 547
            return self.process_operator_node(n)
paul@113 548
paul@113 549
        elif isinstance(n, compiler.ast.AugAssign):
paul@113 550
            self.process_augassign_node(n)
paul@113 551
paul@113 552
        elif isinstance(n, compiler.ast.Compare):
paul@113 553
            return self.process_compare_node(n)
paul@113 554
paul@113 555
        elif isinstance(n, compiler.ast.Slice):
paul@113 556
            return self.process_slice_node(n)
paul@113 557
paul@113 558
        elif isinstance(n, compiler.ast.Sliceobj):
paul@113 559
            return self.process_sliceobj_node(n)
paul@113 560
paul@113 561
        elif isinstance(n, compiler.ast.Subscript):
paul@113 562
            return self.process_subscript_node(n)
paul@113 563
paul@113 564
        # Classes are visited, but may be ignored if inside functions.
paul@113 565
paul@113 566
        elif isinstance(n, compiler.ast.Class):
paul@113 567
            self.process_class_node(n)
paul@113 568
paul@113 569
        # Functions within namespaces have any dynamic defaults initialised.
paul@113 570
paul@113 571
        elif isinstance(n, compiler.ast.Function):
paul@113 572
            self.process_function_node(n)
paul@113 573
paul@113 574
        # Lambdas are replaced with references to separately-generated
paul@113 575
        # functions.
paul@113 576
paul@113 577
        elif isinstance(n, compiler.ast.Lambda):
paul@113 578
            return self.process_lambda_node(n)
paul@113 579
paul@113 580
        # Assignments.
paul@113 581
paul@113 582
        elif isinstance(n, compiler.ast.Assign):
paul@113 583
paul@113 584
            # Handle each assignment node.
paul@113 585
paul@113 586
            for node in n.nodes:
paul@113 587
                self.process_assignment_node(node, n.expr)
paul@113 588
paul@113 589
        # Accesses.
paul@113 590
paul@113 591
        elif isinstance(n, compiler.ast.Getattr):
paul@113 592
            return self.process_attribute_access(n)
paul@113 593
paul@113 594
        # Names.
paul@113 595
paul@113 596
        elif isinstance(n, compiler.ast.Name):
paul@113 597
            return self.process_name_node(n)
paul@113 598
paul@113 599
        # Loops and conditionals.
paul@113 600
paul@113 601
        elif isinstance(n, compiler.ast.For):
paul@113 602
            self.process_for_node(n)
paul@113 603
paul@113 604
        elif isinstance(n, compiler.ast.While):
paul@113 605
            self.process_while_node(n)
paul@113 606
paul@113 607
        elif isinstance(n, compiler.ast.If):
paul@113 608
            self.process_if_node(n)
paul@113 609
paul@113 610
        elif isinstance(n, (compiler.ast.And, compiler.ast.Or)):
paul@113 611
            return self.process_logical_node(n)
paul@113 612
paul@113 613
        elif isinstance(n, compiler.ast.Not):
paul@113 614
            return self.process_not_node(n)
paul@113 615
paul@113 616
        # Exception control-flow tracking.
paul@113 617
paul@113 618
        elif isinstance(n, compiler.ast.TryExcept):
paul@113 619
            self.process_try_node(n)
paul@113 620
paul@113 621
        elif isinstance(n, compiler.ast.TryFinally):
paul@113 622
            self.process_try_finally_node(n)
paul@113 623
paul@113 624
        # Control-flow modification statements.
paul@113 625
paul@113 626
        elif isinstance(n, compiler.ast.Break):
paul@128 627
            self.writestmt("break;")
paul@113 628
paul@113 629
        elif isinstance(n, compiler.ast.Continue):
paul@128 630
            self.writestmt("continue;")
paul@113 631
paul@144 632
        elif isinstance(n, compiler.ast.Raise):
paul@144 633
            self.process_raise_node(n)
paul@144 634
paul@113 635
        elif isinstance(n, compiler.ast.Return):
paul@144 636
            return self.process_return_node(n)
paul@113 637
paul@173 638
        # Print statements.
paul@173 639
paul@173 640
        elif isinstance(n, (compiler.ast.Print, compiler.ast.Printnl)):
paul@173 641
            self.statement(self.process_print_node(n))
paul@173 642
paul@113 643
        # Invocations.
paul@113 644
paul@113 645
        elif isinstance(n, compiler.ast.CallFunc):
paul@113 646
            return self.process_invocation_node(n)
paul@113 647
paul@113 648
        elif isinstance(n, compiler.ast.Keyword):
paul@113 649
            return self.process_structure_node(n.expr)
paul@113 650
paul@113 651
        # Constant usage.
paul@113 652
paul@113 653
        elif isinstance(n, compiler.ast.Const):
paul@405 654
            return self.get_literal_instance(n)
paul@113 655
paul@113 656
        elif isinstance(n, compiler.ast.Dict):
paul@113 657
            return self.get_literal_instance(n, "dict")
paul@113 658
paul@113 659
        elif isinstance(n, compiler.ast.List):
paul@113 660
            return self.get_literal_instance(n, "list")
paul@113 661
paul@113 662
        elif isinstance(n, compiler.ast.Tuple):
paul@113 663
            return self.get_literal_instance(n, "tuple")
paul@113 664
paul@113 665
        # All other nodes are processed depth-first.
paul@113 666
paul@113 667
        else:
paul@144 668
            return self.process_structure(n)
paul@113 669
paul@113 670
    def process_assignment_node(self, n, expr):
paul@113 671
paul@113 672
        "Process the individual node 'n' to be assigned the contents of 'expr'."
paul@113 673
paul@113 674
        # Names and attributes are assigned the entire expression.
paul@113 675
paul@113 676
        if isinstance(n, compiler.ast.AssName):
paul@113 677
            name_ref = self.process_name_node(n, self.process_structure_node(expr))
paul@113 678
            self.statement(name_ref)
paul@113 679
paul@238 680
            # Employ guards after assignments if required.
paul@238 681
paul@238 682
            if expr and name_ref.is_name():
paul@238 683
                self.generate_guard(name_ref.name)
paul@238 684
paul@113 685
        elif isinstance(n, compiler.ast.AssAttr):
paul@124 686
            in_assignment = self.in_assignment
paul@124 687
            self.in_assignment = self.process_structure_node(expr)
paul@124 688
            self.statement(self.process_attribute_access(n))
paul@124 689
            self.in_assignment = in_assignment
paul@113 690
paul@113 691
        # Lists and tuples are matched against the expression and their
paul@113 692
        # items assigned to expression items.
paul@113 693
paul@113 694
        elif isinstance(n, (compiler.ast.AssList, compiler.ast.AssTuple)):
paul@113 695
            self.process_assignment_node_items(n, expr)
paul@113 696
paul@113 697
        # Slices and subscripts are permitted within assignment nodes.
paul@113 698
paul@113 699
        elif isinstance(n, compiler.ast.Slice):
paul@113 700
            self.statement(self.process_slice_node(n, expr))
paul@113 701
paul@113 702
        elif isinstance(n, compiler.ast.Subscript):
paul@113 703
            self.statement(self.process_subscript_node(n, expr))
paul@113 704
paul@124 705
    def process_attribute_access(self, n):
paul@113 706
paul@368 707
        "Process the given attribute access node 'n'."
paul@113 708
paul@113 709
        # Obtain any completed chain and return the reference to it.
paul@113 710
paul@113 711
        attr_expr = self.process_attribute_chain(n)
paul@113 712
        if self.have_access_expression(n):
paul@113 713
            return attr_expr
paul@113 714
paul@113 715
        # Where the start of the chain of attributes has been reached, process
paul@113 716
        # the complete access.
paul@113 717
paul@113 718
        name_ref = attr_expr and attr_expr.is_name() and attr_expr
paul@152 719
        name = name_ref and self.get_name_for_tracking(name_ref.name, name_ref and name_ref.final()) or None
paul@113 720
paul@113 721
        location = self.get_access_location(name)
paul@113 722
        refs = self.get_referenced_attributes(location)
paul@113 723
paul@113 724
        # Generate access instructions.
paul@113 725
paul@113 726
        subs = {
paul@491 727
            "<expr>" : attr_expr,
paul@491 728
            "<assexpr>" : self.in_assignment,
paul@482 729
            }
paul@482 730
paul@482 731
        temp_subs = {
paul@113 732
            "<context>" : "__tmp_context",
paul@113 733
            "<accessor>" : "__tmp_value",
paul@368 734
            "<target_accessor>" : "__tmp_target_value",
paul@482 735
            "<set_accessor>" : "__tmp_value",
paul@482 736
            "<set_target_accessor>" : "__tmp_target_value",
paul@113 737
            }
paul@113 738
paul@482 739
        op_subs = {
paul@482 740
            "<set_accessor>" : "__set_accessor",
paul@482 741
            "<set_target_accessor>" : "__set_target_accessor",
paul@482 742
            }
paul@482 743
paul@482 744
        subs.update(temp_subs)
paul@482 745
        subs.update(op_subs)
paul@482 746
paul@113 747
        output = []
paul@482 748
        substituted = set()
paul@482 749
paul@482 750
        # Obtain encoded versions of each instruction, accumulating temporary
paul@482 751
        # variables.
paul@113 752
paul@113 753
        for instruction in self.optimiser.access_instructions[location]:
paul@482 754
            encoded, _substituted = encode_access_instruction(instruction, subs)
paul@482 755
            output.append(encoded)
paul@482 756
            substituted.update(_substituted)
paul@482 757
paul@482 758
        # Record temporary name usage.
paul@482 759
paul@482 760
        for sub in substituted:
paul@482 761
            if temp_subs.has_key(sub):
paul@482 762
                self.record_temp(temp_subs[sub])
paul@482 763
paul@113 764
        del self.attrs[0]
paul@491 765
        return AttrResult(output, refs, self.get_accessor_kinds(location))
paul@113 766
paul@113 767
    def get_referenced_attributes(self, location):
paul@113 768
paul@113 769
        """
paul@113 770
        Convert 'location' to the form used by the deducer and retrieve any
paul@113 771
        identified attribute.
paul@113 772
        """
paul@113 773
paul@113 774
        access_location = self.deducer.const_accesses.get(location)
paul@113 775
        refs = []
paul@113 776
        for attrtype, objpath, attr in self.deducer.referenced_attrs[access_location or location]:
paul@113 777
            refs.append(attr)
paul@113 778
        return refs
paul@113 779
paul@234 780
    def get_accessor_kinds(self, location):
paul@234 781
paul@234 782
        "Return the accessor kinds for 'location'."
paul@234 783
paul@234 784
        return self.optimiser.accessor_kinds[location]
paul@234 785
paul@113 786
    def get_access_location(self, name):
paul@113 787
paul@113 788
        """
paul@113 789
        Using the current namespace and the given 'name', return the access
paul@113 790
        location.
paul@113 791
        """
paul@113 792
paul@113 793
        path = self.get_path_for_access()
paul@113 794
paul@113 795
        # Get the location used by the deducer and optimiser and find any
paul@113 796
        # recorded access.
paul@113 797
paul@113 798
        attrnames = ".".join(self.attrs)
paul@113 799
        access_number = self.get_access_number(path, name, attrnames)
paul@113 800
        self.update_access_number(path, name, attrnames)
paul@113 801
        return (path, name, attrnames, access_number)
paul@113 802
paul@113 803
    def get_access_number(self, path, name, attrnames):
paul@113 804
        access = name, attrnames
paul@113 805
        if self.attr_accesses.has_key(path) and self.attr_accesses[path].has_key(access):
paul@113 806
            return self.attr_accesses[path][access]
paul@113 807
        else:
paul@113 808
            return 0
paul@113 809
paul@113 810
    def update_access_number(self, path, name, attrnames):
paul@113 811
        access = name, attrnames
paul@113 812
        if name:
paul@113 813
            init_item(self.attr_accesses, path, dict)
paul@144 814
            init_item(self.attr_accesses[path], access, lambda: 0)
paul@144 815
            self.attr_accesses[path][access] += 1
paul@113 816
paul@237 817
    def get_accessor_location(self, name):
paul@237 818
paul@237 819
        """
paul@237 820
        Using the current namespace and the given 'name', return the accessor
paul@237 821
        location.
paul@237 822
        """
paul@237 823
paul@237 824
        path = self.get_path_for_access()
paul@237 825
paul@237 826
        # Get the location used by the deducer and optimiser and find any
paul@237 827
        # recorded accessor.
paul@237 828
paul@237 829
        access_number = self.get_accessor_number(path, name)
paul@237 830
        self.update_accessor_number(path, name)
paul@237 831
        return (path, name, None, access_number)
paul@237 832
paul@237 833
    def get_accessor_number(self, path, name):
paul@237 834
        if self.attr_accessors.has_key(path) and self.attr_accessors[path].has_key(name):
paul@237 835
            return self.attr_accessors[path][name]
paul@237 836
        else:
paul@237 837
            return 0
paul@237 838
paul@237 839
    def update_accessor_number(self, path, name):
paul@237 840
        if name:
paul@237 841
            init_item(self.attr_accessors, path, dict)
paul@237 842
            init_item(self.attr_accessors[path], name, lambda: 0)
paul@237 843
            self.attr_accessors[path][name] += 1
paul@237 844
paul@113 845
    def process_class_node(self, n):
paul@113 846
paul@113 847
        "Process the given class node 'n'."
paul@113 848
paul@320 849
        class_name = self.get_object_path(n.name)
paul@320 850
paul@320 851
        # Where a class is set conditionally or where the name may refer to
paul@320 852
        # different values, assign the name.
paul@320 853
paul@320 854
        ref = self.importer.identify(class_name)
paul@320 855
paul@320 856
        if not ref.static():
paul@320 857
            self.process_assignment_for_object(
paul@477 858
                n.name, make_expression("((__attr) {.context=0, .value=&%s})" %
paul@320 859
                    encode_path(class_name)))
paul@320 860
paul@113 861
        self.enter_namespace(n.name)
paul@113 862
paul@113 863
        if self.have_object():
paul@113 864
            self.write_comment("Class: %s" % class_name)
paul@113 865
paul@257 866
            self.initialise_inherited_members(class_name)
paul@257 867
paul@113 868
            self.process_structure(n)
paul@257 869
            self.write_comment("End class: %s" % class_name)
paul@113 870
paul@113 871
        self.exit_namespace()
paul@113 872
paul@257 873
    def initialise_inherited_members(self, class_name):
paul@257 874
paul@257 875
        "Initialise members of 'class_name' inherited from its ancestors."
paul@257 876
paul@257 877
        for name, path in self.importer.all_class_attrs[class_name].items():
paul@257 878
            target = "%s.%s" % (class_name, name)
paul@257 879
paul@257 880
            # Ignore attributes with definitions.
paul@257 881
paul@257 882
            ref = self.importer.identify(target)
paul@257 883
            if ref:
paul@257 884
                continue
paul@257 885
paul@320 886
            # Ignore special type attributes.
paul@320 887
paul@320 888
            if is_type_attribute(name):
paul@320 889
                continue
paul@320 890
paul@257 891
            # Reference inherited attributes.
paul@257 892
paul@257 893
            ref = self.importer.identify(path)
paul@257 894
            if ref and not ref.static():
paul@257 895
                parent, attrname = path.rsplit(".", 1)
paul@257 896
paul@257 897
                self.writestmt("__store_via_object(&%s, %s, __load_via_object(&%s, %s));" % (
paul@257 898
                    encode_path(class_name), encode_symbol("pos", name),
paul@257 899
                    encode_path(parent), encode_symbol("pos", attrname)
paul@257 900
                    ))
paul@257 901
paul@314 902
    def process_from_node(self, n):
paul@314 903
paul@314 904
        "Process the given node 'n', importing from another module."
paul@314 905
paul@314 906
        path = self.get_namespace_path()
paul@314 907
paul@314 908
        # Attempt to obtain the referenced objects.
paul@314 909
paul@314 910
        for name, alias in n.names:
paul@314 911
            if name == "*":
paul@314 912
                raise InspectError("Only explicitly specified names can be imported from modules.", path, n)
paul@314 913
paul@314 914
            # Obtain the path of the assigned name.
paul@314 915
paul@314 916
            objpath = self.get_object_path(alias or name)
paul@314 917
paul@314 918
            # Obtain the identity of the name.
paul@314 919
paul@314 920
            ref = self.importer.identify(objpath)
paul@314 921
paul@314 922
            # Where the name is not static, assign the value.
paul@314 923
paul@314 924
            if ref and not ref.static() and ref.get_name():
paul@314 925
                self.writestmt("%s;" % 
paul@314 926
                    TrResolvedNameRef(alias or name, Reference("<var>", None, objpath),
paul@314 927
                                      expr=TrResolvedNameRef(name, ref)))
paul@314 928
paul@113 929
    def process_function_body_node(self, n):
paul@113 930
paul@113 931
        """
paul@113 932
        Process the given function, lambda, if expression or list comprehension
paul@113 933
        node 'n', generating the body.
paul@113 934
        """
paul@113 935
paul@113 936
        function_name = self.get_namespace_path()
paul@113 937
        self.start_function(function_name)
paul@113 938
paul@113 939
        # Process the function body.
paul@113 940
paul@113 941
        in_conditional = self.in_conditional
paul@113 942
        self.in_conditional = False
paul@192 943
        self.function_target = 0
paul@113 944
paul@237 945
        # Process any guards defined for the parameters.
paul@237 946
paul@237 947
        for name in self.importer.function_parameters.get(function_name):
paul@238 948
            self.generate_guard(name)
paul@237 949
paul@237 950
        # Produce the body and any additional return statement.
paul@237 951
paul@144 952
        expr = self.process_structure_node(n.code) or PredefinedConstantRef("None")
paul@144 953
        if not isinstance(expr, ReturnRef):
paul@128 954
            self.writestmt("return %s;" % expr)
paul@113 955
paul@113 956
        self.in_conditional = in_conditional
paul@113 957
paul@144 958
        self.end_function(function_name)
paul@113 959
paul@238 960
    def generate_guard(self, name):
paul@238 961
paul@238 962
        """
paul@238 963
        Get the accessor details for 'name', found in the current namespace, and
paul@238 964
        generate any guards defined for it.
paul@238 965
        """
paul@238 966
paul@238 967
        # Obtain the location, keeping track of assignment versions.
paul@238 968
paul@238 969
        location = self.get_accessor_location(name)
paul@238 970
        test = self.deducer.accessor_guard_tests.get(location)
paul@238 971
paul@238 972
        # Generate any guard from the deduced information.
paul@238 973
paul@238 974
        if test:
paul@238 975
            guard, guard_type = test
paul@238 976
paul@238 977
            if guard == "specific":
paul@238 978
                ref = first(self.deducer.accessor_all_types[location])
paul@238 979
                argstr = "&%s" % encode_path(ref.get_origin())
paul@238 980
            elif guard == "common":
paul@238 981
                ref = first(self.deducer.accessor_all_general_types[location])
paul@238 982
                typeattr = encode_type_attribute(ref.get_origin())
paul@238 983
                argstr = "%s, %s" % (encode_symbol("pos", typeattr), encode_symbol("code", typeattr))
paul@238 984
            else:
paul@238 985
                return
paul@238 986
paul@257 987
            # Produce an appropriate access to an attribute's value.
paul@257 988
paul@257 989
            parameters = self.importer.function_parameters.get(self.get_namespace_path())
paul@257 990
            if parameters and name in parameters:
paul@257 991
                name_to_value = "%s->value" % name
paul@257 992
            else:
paul@257 993
                name_to_value = "%s.value" % name
paul@257 994
paul@238 995
            # Write a test that raises a TypeError upon failure.
paul@238 996
paul@257 997
            self.writestmt("if (!__test_%s_%s(%s, %s)) __raise_type_error();" % (
paul@257 998
                guard, guard_type, name_to_value, argstr))
paul@238 999
paul@113 1000
    def process_function_node(self, n):
paul@113 1001
paul@113 1002
        """
paul@113 1003
        Process the given function, lambda, if expression or list comprehension
paul@113 1004
        node 'n', generating any initialisation statements.
paul@113 1005
        """
paul@113 1006
paul@113 1007
        # Where a function is declared conditionally, use a separate name for
paul@113 1008
        # the definition, and assign the definition to the stated name.
paul@113 1009
paul@196 1010
        original_name = n.name
paul@196 1011
paul@113 1012
        if self.in_conditional or self.in_function:
paul@113 1013
            name = self.get_lambda_name()
paul@113 1014
        else:
paul@113 1015
            name = n.name
paul@113 1016
paul@196 1017
        objpath = self.get_object_path(name)
paul@196 1018
paul@113 1019
        # Obtain details of the defaults.
paul@113 1020
paul@285 1021
        defaults = self.process_function_defaults(n, name, objpath)
paul@113 1022
        if defaults:
paul@113 1023
            for default in defaults:
paul@113 1024
                self.writeline("%s;" % default)
paul@113 1025
paul@196 1026
        # Where a function is set conditionally or where the name may refer to
paul@196 1027
        # different values, assign the name.
paul@196 1028
paul@196 1029
        ref = self.importer.identify(objpath)
paul@113 1030
paul@196 1031
        if self.in_conditional or self.in_function:
paul@320 1032
            self.process_assignment_for_object(original_name, compiler.ast.Name(name))
paul@196 1033
        elif not ref.static():
paul@267 1034
            context = self.is_method(objpath)
paul@267 1035
paul@320 1036
            self.process_assignment_for_object(original_name,
paul@477 1037
                make_expression("((__attr) {.context=%s, .value=&%s})" % (
paul@267 1038
                    context and "&%s" % encode_path(context) or "0",
paul@267 1039
                    encode_path(objpath))))
paul@113 1040
paul@285 1041
    def process_function_defaults(self, n, name, objpath, instance_name=None):
paul@113 1042
paul@113 1043
        """
paul@113 1044
        Process the given function or lambda node 'n', initialising defaults
paul@113 1045
        that are dynamically set. The given 'name' indicates the name of the
paul@285 1046
        function. The given 'objpath' indicates the origin of the function.
paul@285 1047
        The given 'instance_name' indicates the name of any separate instance
paul@285 1048
        of the function created to hold the defaults.
paul@113 1049
paul@113 1050
        Return a list of operations setting defaults on a function instance.
paul@113 1051
        """
paul@113 1052
paul@113 1053
        function_name = self.get_object_path(name)
paul@113 1054
        function_defaults = self.importer.function_defaults.get(function_name)
paul@113 1055
        if not function_defaults:
paul@113 1056
            return None
paul@113 1057
paul@113 1058
        # Determine whether any unidentified defaults are involved.
paul@113 1059
paul@285 1060
        for argname, default in function_defaults:
paul@285 1061
            if not default.static():
paul@285 1062
                break
paul@285 1063
        else:
paul@113 1064
            return None
paul@113 1065
paul@285 1066
        # Handle bound methods.
paul@285 1067
paul@285 1068
        if not instance_name:
paul@523 1069
            instance_name = "&%s" % encode_path(objpath)
paul@285 1070
paul@113 1071
        # Where defaults are involved but cannot be identified, obtain a new
paul@113 1072
        # instance of the lambda and populate the defaults.
paul@113 1073
paul@113 1074
        defaults = []
paul@113 1075
paul@113 1076
        # Join the original defaults with the inspected defaults.
paul@113 1077
paul@113 1078
        original_defaults = [(argname, default) for (argname, default) in compiler.ast.get_defaults(n) if default]
paul@113 1079
paul@113 1080
        for i, (original, inspected) in enumerate(map(None, original_defaults, function_defaults)):
paul@113 1081
paul@113 1082
            # Obtain any reference for the default.
paul@113 1083
paul@113 1084
            if original:
paul@113 1085
                argname, default = original
paul@113 1086
                name_ref = self.process_structure_node(default)
paul@113 1087
            elif inspected:
paul@113 1088
                argname, default = inspected
paul@113 1089
                name_ref = TrResolvedNameRef(argname, default)
paul@113 1090
            else:
paul@113 1091
                continue
paul@113 1092
paul@338 1093
            # Generate default initialisers except when constants are employed.
paul@338 1094
            # Constants should be used when populating the function structures.
paul@338 1095
paul@338 1096
            if name_ref and not isinstance(name_ref, TrConstantValueRef):
paul@285 1097
                defaults.append("__SETDEFAULT(%s, %s, %s)" % (instance_name, i, name_ref))
paul@113 1098
paul@113 1099
        return defaults
paul@113 1100
paul@113 1101
    def process_if_node(self, n):
paul@113 1102
paul@113 1103
        """
paul@113 1104
        Process the given "if" node 'n'.
paul@113 1105
        """
paul@113 1106
paul@113 1107
        first = True
paul@113 1108
        for test, body in n.tests:
paul@113 1109
            test_ref = self.process_structure_node(test)
paul@113 1110
            self.start_if(first, test_ref)
paul@113 1111
paul@113 1112
            in_conditional = self.in_conditional
paul@113 1113
            self.in_conditional = True
paul@113 1114
            self.process_structure_node(body)
paul@113 1115
            self.in_conditional = in_conditional
paul@113 1116
paul@113 1117
            self.end_if()
paul@113 1118
            first = False
paul@113 1119
paul@113 1120
        if n.else_:
paul@113 1121
            self.start_else()
paul@113 1122
            self.process_structure_node(n.else_)
paul@113 1123
            self.end_else()
paul@113 1124
paul@113 1125
    def process_invocation_node(self, n):
paul@113 1126
paul@113 1127
        "Process the given invocation node 'n'."
paul@113 1128
paul@113 1129
        expr = self.process_structure_node(n.node)
paul@113 1130
        objpath = expr.get_origin()
paul@118 1131
        target = None
paul@407 1132
        target_structure = None
paul@242 1133
        function = None
paul@317 1134
        instantiation = False
paul@159 1135
        literal_instantiation = False
paul@312 1136
        context_required = True
paul@113 1137
paul@113 1138
        # Obtain details of the callable.
paul@113 1139
paul@159 1140
        # Literals may be instantiated specially.
paul@159 1141
paul@159 1142
        if expr.is_name() and expr.name.startswith("$L") and objpath:
paul@317 1143
            instantiation = literal_instantiation = objpath
paul@159 1144
            parameters = None
paul@159 1145
            target = encode_literal_instantiator(objpath)
paul@312 1146
            context_required = False
paul@159 1147
paul@159 1148
        # Identified targets employ function pointers directly.
paul@159 1149
paul@159 1150
        elif objpath:
paul@113 1151
            parameters = self.importer.function_parameters.get(objpath)
paul@234 1152
paul@234 1153
            # Class invocation involves instantiators.
paul@234 1154
paul@118 1155
            if expr.has_kind("<class>"):
paul@317 1156
                instantiation = objpath
paul@118 1157
                target = encode_instantiator_pointer(objpath)
paul@540 1158
                init_ref = self.importer.all_class_attrs[objpath]["__init__"]
paul@540 1159
                target_structure = "&%s" % encode_path(init_ref)
paul@312 1160
                context_required = False
paul@234 1161
paul@234 1162
            # Only plain functions and bound methods employ function pointers.
paul@234 1163
paul@118 1164
            elif expr.has_kind("<function>"):
paul@242 1165
                function = objpath
paul@234 1166
paul@234 1167
                # Test for functions and methods.
paul@234 1168
paul@407 1169
                context_required = self.is_method(objpath)
paul@234 1170
                accessor_kinds = expr.get_accessor_kinds()
paul@312 1171
                instance_accessor = accessor_kinds and \
paul@312 1172
                                    len(accessor_kinds) == 1 and \
paul@312 1173
                                    first(accessor_kinds) == "<instance>"
paul@234 1174
paul@407 1175
                # Only identify certain bound methods or functions.
paul@407 1176
paul@407 1177
                if not context_required or instance_accessor:
paul@234 1178
                    target = encode_function_pointer(objpath)
paul@407 1179
paul@407 1180
                # Access bound method defaults even if it is not clear whether
paul@407 1181
                # the accessor is appropriate.
paul@407 1182
paul@523 1183
                target_structure = "&%s" % encode_path(objpath)
paul@312 1184
paul@159 1185
        # Other targets are retrieved at run-time.
paul@159 1186
paul@113 1187
        else:
paul@113 1188
            parameters = None
paul@113 1189
paul@122 1190
        # Arguments are presented in a temporary frame array with any context
paul@312 1191
        # always being the first argument. Where it would be unused, it may be
paul@312 1192
        # set to null.
paul@122 1193
paul@312 1194
        if context_required:
paul@482 1195
            self.record_temp("__tmp_targets")
paul@312 1196
            args = ["__CONTEXT_AS_VALUE(__tmp_targets[%d])" % self.function_target]
paul@312 1197
        else:
paul@477 1198
            args = ["__NULL"]
paul@312 1199
paul@122 1200
        args += [None] * (not parameters and len(n.args) or parameters and len(parameters) or 0)
paul@122 1201
        kwcodes = []
paul@122 1202
        kwargs = []
paul@122 1203
paul@192 1204
        # Any invocations in the arguments will store target details in a
paul@192 1205
        # different location.
paul@192 1206
paul@192 1207
        self.function_target += 1
paul@192 1208
paul@122 1209
        for i, arg in enumerate(n.args):
paul@122 1210
            argexpr = self.process_structure_node(arg)
paul@122 1211
paul@122 1212
            # Store a keyword argument, either in the argument list or
paul@122 1213
            # in a separate keyword argument list for subsequent lookup.
paul@122 1214
paul@122 1215
            if isinstance(arg, compiler.ast.Keyword):
paul@113 1216
paul@122 1217
                # With knowledge of the target, store the keyword
paul@122 1218
                # argument directly.
paul@122 1219
paul@122 1220
                if parameters:
paul@373 1221
                    try:
paul@373 1222
                        argnum = parameters.index(arg.name)
paul@373 1223
                    except ValueError:
paul@373 1224
                        raise TranslateError("Argument %s is not recognised." % arg.name,
paul@373 1225
                                             self.get_namespace_path(), n)
paul@122 1226
                    args[argnum+1] = str(argexpr)
paul@122 1227
paul@122 1228
                # Otherwise, store the details in a separate collection.
paul@122 1229
paul@122 1230
                else:
paul@122 1231
                    kwargs.append(str(argexpr))
paul@122 1232
                    kwcodes.append("{%s, %s}" % (
paul@122 1233
                        encode_symbol("ppos", arg.name),
paul@122 1234
                        encode_symbol("pcode", arg.name)))
paul@122 1235
paul@312 1236
            # Store non-keyword arguments in the argument list, rejecting
paul@312 1237
            # superfluous arguments.
paul@312 1238
paul@122 1239
            else:
paul@225 1240
                try:
paul@225 1241
                    args[i+1] = str(argexpr)
paul@225 1242
                except IndexError:
paul@225 1243
                    raise TranslateError("Too many arguments specified.",
paul@225 1244
                                         self.get_namespace_path(), n)
paul@113 1245
paul@192 1246
        # Reference the current target again.
paul@192 1247
paul@192 1248
        self.function_target -= 1
paul@192 1249
paul@113 1250
        # Defaults are added to the frame where arguments are missing.
paul@113 1251
paul@122 1252
        if parameters:
paul@122 1253
            function_defaults = self.importer.function_defaults.get(objpath)
paul@122 1254
            if function_defaults:
paul@122 1255
paul@122 1256
                # Visit each default and set any missing arguments.
paul@149 1257
                # Use the target structure to obtain defaults, as opposed to the
paul@149 1258
                # actual function involved.
paul@122 1259
paul@122 1260
                for i, (argname, default) in enumerate(function_defaults):
paul@122 1261
                    argnum = parameters.index(argname)
paul@122 1262
                    if not args[argnum+1]:
paul@285 1263
                        args[argnum+1] = "__GETDEFAULT(%s, %d)" % (target_structure, i)
paul@149 1264
paul@173 1265
        # Test for missing arguments.
paul@173 1266
paul@173 1267
        if None in args:
paul@173 1268
            raise TranslateError("Not all arguments supplied.",
paul@173 1269
                                 self.get_namespace_path(), n)
paul@173 1270
paul@149 1271
        # Encode the arguments.
paul@122 1272
paul@122 1273
        argstr = "__ARGS(%s)" % ", ".join(args)
paul@122 1274
        kwargstr = kwargs and ("__ARGS(%s)" % ", ".join(kwargs)) or "0"
paul@122 1275
        kwcodestr = kwcodes and ("__KWARGS(%s)" % ", ".join(kwcodes)) or "0"
paul@122 1276
paul@159 1277
        # Where literal instantiation is occurring, add an argument indicating
paul@159 1278
        # the number of values.
paul@159 1279
paul@159 1280
        if literal_instantiation:
paul@159 1281
            argstr += ", %d" % (len(args) - 1)
paul@159 1282
paul@156 1283
        # First, the invocation expression is presented.
paul@113 1284
paul@156 1285
        stages = []
paul@156 1286
paul@156 1287
        # Without a known specific callable, the expression provides the target.
paul@118 1288
paul@312 1289
        if not target or context_required:
paul@482 1290
            self.record_temp("__tmp_targets")
paul@312 1291
            stages.append("__tmp_targets[%d] = %s" % (self.function_target, expr))
paul@156 1292
paul@156 1293
        # Any specific callable is then obtained.
paul@156 1294
paul@163 1295
        if target:
paul@156 1296
            stages.append(target)
paul@484 1297
paul@484 1298
        # Methods accessed via unidentified accessors are obtained. 
paul@484 1299
paul@242 1300
        elif function:
paul@482 1301
            self.record_temp("__tmp_targets")
paul@523 1302
paul@523 1303
            if context_required:
paul@523 1304
                stages.append("__get_function(__tmp_targets[%d])" % self.function_target)
paul@523 1305
            else:
paul@523 1306
                stages.append("__load_via_object(__tmp_targets[%d].value, %s).fn" % (
paul@523 1307
                    self.function_target, encode_symbol("pos", "__fn__")))
paul@122 1308
paul@122 1309
        # With a known target, the function is obtained directly and called.
paul@484 1310
        # By putting the invocation at the end of the final element in the
paul@484 1311
        # instruction sequence (the stages), the result becomes the result of
paul@484 1312
        # the sequence. Moreover, the parameters become part of the sequence
paul@484 1313
        # and thereby participate in a guaranteed evaluation order.
paul@122 1314
paul@242 1315
        if target or function:
paul@498 1316
            stages[-1] += "(%s)" % argstr
paul@498 1317
            if instantiation:
paul@498 1318
                return InstantiationResult(instantiation, stages)
paul@498 1319
            else:
paul@498 1320
                return InvocationResult(stages)
paul@113 1321
paul@122 1322
        # With unknown targets, the generic invocation function is applied to
paul@122 1323
        # the callable and argument collections.
paul@113 1324
paul@122 1325
        else:
paul@482 1326
            self.record_temp("__tmp_targets")
paul@498 1327
            stages.append("__invoke(\n__tmp_targets[%d],\n%d, %d, %s, %s,\n%d, %s\n)" % (
paul@192 1328
                self.function_target,
paul@156 1329
                self.always_callable and 1 or 0,
paul@122 1330
                len(kwargs), kwcodestr, kwargstr,
paul@498 1331
                len(args), argstr))
paul@498 1332
            return InvocationResult(stages)
paul@113 1333
paul@113 1334
    def always_callable(self, refs):
paul@113 1335
paul@113 1336
        "Determine whether all 'refs' are callable."
paul@113 1337
paul@113 1338
        for ref in refs:
paul@113 1339
            if not ref.static():
paul@113 1340
                return False
paul@113 1341
            else:
paul@113 1342
                origin = ref.final()
paul@113 1343
                if not self.importer.get_attribute(origin, "__fn__"):
paul@113 1344
                    return False
paul@113 1345
        return True
paul@113 1346
paul@113 1347
    def need_default_arguments(self, objpath, nargs):
paul@113 1348
paul@113 1349
        """
paul@113 1350
        Return whether any default arguments are needed when invoking the object
paul@113 1351
        given by 'objpath'.
paul@113 1352
        """
paul@113 1353
paul@113 1354
        parameters = self.importer.function_parameters.get(objpath)
paul@113 1355
        return nargs < len(parameters)
paul@113 1356
paul@113 1357
    def process_lambda_node(self, n):
paul@113 1358
paul@113 1359
        "Process the given lambda node 'n'."
paul@113 1360
paul@113 1361
        name = self.get_lambda_name()
paul@113 1362
        function_name = self.get_object_path(name)
paul@113 1363
paul@285 1364
        defaults = self.process_function_defaults(n, name, function_name, "__tmp_value")
paul@149 1365
paul@149 1366
        # Without defaults, produce an attribute referring to the function.
paul@149 1367
paul@113 1368
        if not defaults:
paul@477 1369
            return make_expression("((__attr) {.context=0, .value=&%s})" % encode_path(function_name))
paul@149 1370
paul@149 1371
        # With defaults, copy the function structure and set the defaults on the
paul@149 1372
        # copy.
paul@149 1373
paul@113 1374
        else:
paul@482 1375
            self.record_temp("__tmp_value")
paul@477 1376
            return make_expression("(__tmp_value = __COPY(&%s, sizeof(%s)), %s, (__attr) {.context=0, .value=__tmp_value})" % (
paul@151 1377
                encode_path(function_name),
paul@151 1378
                encode_symbol("obj", function_name),
paul@151 1379
                ", ".join(defaults)))
paul@113 1380
paul@113 1381
    def process_logical_node(self, n):
paul@113 1382
paul@141 1383
        """
paul@141 1384
        Process the given operator node 'n'.
paul@141 1385
paul@141 1386
        Convert ... to ...
paul@141 1387
paul@141 1388
        <a> and <b>
paul@141 1389
        (__tmp_result = <a>, !__BOOL(__tmp_result)) ? __tmp_result : <b>
paul@141 1390
paul@141 1391
        <a> or <b>
paul@141 1392
        (__tmp_result = <a>, __BOOL(__tmp_result)) ? __tmp_result : <b>
paul@141 1393
        """
paul@113 1394
paul@482 1395
        self.record_temp("__tmp_result")
paul@482 1396
paul@113 1397
        if isinstance(n, compiler.ast.And):
paul@141 1398
            op = "!"
paul@113 1399
        else:
paul@141 1400
            op = ""
paul@141 1401
paul@141 1402
        results = []
paul@113 1403
paul@141 1404
        for node in n.nodes[:-1]:
paul@141 1405
            expr = self.process_structure_node(node)
paul@141 1406
            results.append("(__tmp_result = %s, %s__BOOL(__tmp_result)) ? __tmp_result : " % (expr, op))
paul@113 1407
paul@141 1408
        expr = self.process_structure_node(n.nodes[-1])
paul@141 1409
        results.append(str(expr))
paul@141 1410
paul@141 1411
        return make_expression("(%s)" % "".join(results))
paul@113 1412
paul@113 1413
    def process_name_node(self, n, expr=None):
paul@113 1414
paul@113 1415
        "Process the given name node 'n' with the optional assignment 'expr'."
paul@113 1416
paul@113 1417
        # Determine whether the name refers to a static external entity.
paul@113 1418
paul@113 1419
        if n.name in predefined_constants:
paul@399 1420
            return PredefinedConstantRef(n.name, expr)
paul@113 1421
paul@173 1422
        # Convert literal references, operator function names, and print
paul@173 1423
        # function names to references.
paul@113 1424
paul@173 1425
        elif n.name.startswith("$L") or n.name.startswith("$op") or \
paul@173 1426
             n.name.startswith("$print"):
paul@423 1427
paul@423 1428
            ref, paths = self.importer.get_module(self.name).special[n.name]
paul@113 1429
            return TrResolvedNameRef(n.name, ref)
paul@113 1430
paul@113 1431
        # Get the appropriate name for the name reference, using the same method
paul@113 1432
        # as in the inspector.
paul@113 1433
paul@250 1434
        path = self.get_namespace_path()
paul@250 1435
        objpath = self.get_object_path(n.name)
paul@250 1436
paul@250 1437
        # Determine any assigned globals.
paul@250 1438
paul@250 1439
        globals = self.importer.get_module(self.name).scope_globals.get(path)
paul@250 1440
        if globals and n.name in globals:
paul@250 1441
            objpath = self.get_global_path(n.name)
paul@113 1442
paul@113 1443
        # Get the static identity of the name.
paul@113 1444
paul@250 1445
        ref = self.importer.identify(objpath)
paul@152 1446
        if ref and not ref.get_name():
paul@250 1447
            ref = ref.alias(objpath)
paul@113 1448
paul@113 1449
        # Obtain any resolved names for non-assignment names.
paul@113 1450
paul@113 1451
        if not expr and not ref and self.in_function:
paul@250 1452
            locals = self.importer.function_locals.get(path)
paul@113 1453
            ref = locals and locals.get(n.name)
paul@113 1454
paul@208 1455
        # Determine whether the name refers to a parameter. The generation of
paul@208 1456
        # parameter references is different from other names.
paul@208 1457
paul@250 1458
        parameters = self.importer.function_parameters.get(path)
paul@208 1459
        parameter = n.name == "self" and self.in_method() or \
paul@208 1460
                    parameters and n.name in parameters
paul@208 1461
paul@113 1462
        # Qualified names are used for resolved static references or for
paul@113 1463
        # static namespace members. The reference should be configured to return
paul@113 1464
        # such names.
paul@113 1465
paul@208 1466
        return TrResolvedNameRef(n.name, ref, expr=expr, parameter=parameter)
paul@113 1467
paul@113 1468
    def process_not_node(self, n):
paul@113 1469
paul@113 1470
        "Process the given operator node 'n'."
paul@113 1471
paul@144 1472
        return make_expression("(__BOOL(%s) ? %s : %s)" %
paul@149 1473
            (self.process_structure_node(n.expr), PredefinedConstantRef("False"),
paul@149 1474
            PredefinedConstantRef("True")))
paul@144 1475
paul@144 1476
    def process_raise_node(self, n):
paul@144 1477
paul@144 1478
        "Process the given raise node 'n'."
paul@144 1479
paul@144 1480
        # NOTE: Determine which raise statement variants should be permitted.
paul@144 1481
paul@176 1482
        if n.expr1:
paul@467 1483
paul@467 1484
            # Names with accompanying arguments are treated like invocations.
paul@467 1485
paul@467 1486
            if n.expr2:
paul@467 1487
                call = compiler.ast.CallFunc(n.expr1, [n.expr2])
paul@467 1488
                exc = self.process_structure_node(call)
paul@467 1489
                self.writestmt("__Raise(%s);" % exc)
paul@317 1490
paul@317 1491
            # Raise instances, testing the kind at run-time if necessary and
paul@317 1492
            # instantiating any non-instance.
paul@317 1493
paul@317 1494
            else:
paul@467 1495
                exc = self.process_structure_node(n.expr1)
paul@467 1496
paul@467 1497
                if isinstance(exc, TrInstanceRef):
paul@467 1498
                    self.writestmt("__Raise(%s);" % exc)
paul@467 1499
                else:
paul@467 1500
                    self.writestmt("__Raise(__ensure_instance(%s));" % exc)
paul@176 1501
        else:
paul@346 1502
            self.writestmt("__Throw(__tmp_exc);")
paul@144 1503
paul@144 1504
    def process_return_node(self, n):
paul@144 1505
paul@144 1506
        "Process the given return node 'n'."
paul@144 1507
paul@144 1508
        expr = self.process_structure_node(n.value) or PredefinedConstantRef("None")
paul@189 1509
        if self.in_try_finally or self.in_try_except:
paul@144 1510
            self.writestmt("__Return(%s);" % expr)
paul@144 1511
        else:
paul@144 1512
            self.writestmt("return %s;" % expr)
paul@144 1513
paul@144 1514
        return ReturnRef()
paul@113 1515
paul@113 1516
    def process_try_node(self, n):
paul@113 1517
paul@113 1518
        """
paul@113 1519
        Process the given "try...except" node 'n'.
paul@113 1520
        """
paul@113 1521
paul@189 1522
        in_try_except = self.in_try_except
paul@189 1523
        self.in_try_except = True
paul@189 1524
paul@144 1525
        # Use macros to implement exception handling.
paul@113 1526
paul@144 1527
        self.writestmt("__Try")
paul@113 1528
        self.writeline("{")
paul@113 1529
        self.indent += 1
paul@113 1530
        self.process_structure_node(n.body)
paul@144 1531
paul@144 1532
        # Put the else statement in another try block that handles any raised
paul@144 1533
        # exceptions and converts them to exceptions that will not be handled by
paul@144 1534
        # the main handling block.
paul@144 1535
paul@144 1536
        if n.else_:
paul@144 1537
            self.writestmt("__Try")
paul@144 1538
            self.writeline("{")
paul@144 1539
            self.indent += 1
paul@144 1540
            self.process_structure_node(n.else_)
paul@144 1541
            self.indent -= 1
paul@144 1542
            self.writeline("}")
paul@144 1543
            self.writeline("__Catch (__tmp_exc)")
paul@144 1544
            self.writeline("{")
paul@144 1545
            self.indent += 1
paul@144 1546
            self.writeline("if (__tmp_exc.raising) __RaiseElse(__tmp_exc.arg);")
paul@191 1547
            self.writeline("else if (__tmp_exc.completing) __Throw(__tmp_exc);")
paul@144 1548
            self.indent -= 1
paul@144 1549
            self.writeline("}")
paul@144 1550
paul@144 1551
        # Complete the try block and enter the finally block, if appropriate.
paul@144 1552
paul@144 1553
        if self.in_try_finally:
paul@144 1554
            self.writestmt("__Complete;")
paul@144 1555
paul@113 1556
        self.indent -= 1
paul@113 1557
        self.writeline("}")
paul@113 1558
paul@189 1559
        self.in_try_except = in_try_except
paul@189 1560
paul@144 1561
        # Handlers are tests within a common handler block.
paul@144 1562
paul@144 1563
        self.writeline("__Catch (__tmp_exc)")
paul@144 1564
        self.writeline("{")
paul@144 1565
        self.indent += 1
paul@144 1566
paul@189 1567
        # Introduce an if statement to handle the completion of a try block.
paul@189 1568
paul@189 1569
        self.process_try_completion()
paul@189 1570
paul@144 1571
        # Handle exceptions in else blocks converted to __RaiseElse, converting
paul@144 1572
        # them back to normal exceptions.
paul@144 1573
paul@144 1574
        if n.else_:
paul@189 1575
            self.writeline("else if (__tmp_exc.raising_else) __Raise(__tmp_exc.arg);")
paul@144 1576
paul@144 1577
        # Exception handling.
paul@144 1578
paul@113 1579
        for name, var, handler in n.handlers:
paul@144 1580
paul@144 1581
            # Test for specific exceptions.
paul@144 1582
paul@113 1583
            if name is not None:
paul@113 1584
                name_ref = self.process_structure_node(name)
paul@462 1585
                self.writeline("else if (__ISINSTANCE(__tmp_exc.arg, %s))" % name_ref)
paul@144 1586
            else:
paul@189 1587
                self.writeline("else if (1)")
paul@113 1588
paul@113 1589
            self.writeline("{")
paul@113 1590
            self.indent += 1
paul@113 1591
paul@113 1592
            # Establish the local for the handler.
paul@113 1593
paul@113 1594
            if var is not None:
paul@261 1595
                self.writestmt("%s;" % self.process_name_node(var, make_expression("__tmp_exc.arg")))
paul@113 1596
paul@113 1597
            if handler is not None:
paul@113 1598
                self.process_structure_node(handler)
paul@113 1599
paul@113 1600
            self.indent -= 1
paul@113 1601
            self.writeline("}")
paul@113 1602
paul@144 1603
        # Re-raise unhandled exceptions.
paul@144 1604
paul@189 1605
        self.writeline("else __Throw(__tmp_exc);")
paul@144 1606
paul@144 1607
        # End the handler block.
paul@144 1608
paul@144 1609
        self.indent -= 1
paul@144 1610
        self.writeline("}")
paul@113 1611
paul@113 1612
    def process_try_finally_node(self, n):
paul@113 1613
paul@113 1614
        """
paul@113 1615
        Process the given "try...finally" node 'n'.
paul@113 1616
        """
paul@113 1617
paul@144 1618
        in_try_finally = self.in_try_finally
paul@144 1619
        self.in_try_finally = True
paul@113 1620
paul@144 1621
        # Use macros to implement exception handling.
paul@144 1622
paul@144 1623
        self.writestmt("__Try")
paul@113 1624
        self.writeline("{")
paul@113 1625
        self.indent += 1
paul@113 1626
        self.process_structure_node(n.body)
paul@113 1627
        self.indent -= 1
paul@113 1628
        self.writeline("}")
paul@144 1629
paul@144 1630
        self.in_try_finally = in_try_finally
paul@144 1631
paul@144 1632
        # Finally clauses handle special exceptions.
paul@144 1633
paul@144 1634
        self.writeline("__Catch (__tmp_exc)")
paul@113 1635
        self.writeline("{")
paul@113 1636
        self.indent += 1
paul@113 1637
        self.process_structure_node(n.final)
paul@144 1638
paul@189 1639
        # Introduce an if statement to handle the completion of a try block.
paul@189 1640
paul@189 1641
        self.process_try_completion()
paul@189 1642
        self.writeline("else __Throw(__tmp_exc);")
paul@189 1643
paul@189 1644
        self.indent -= 1
paul@189 1645
        self.writeline("}")
paul@189 1646
paul@189 1647
    def process_try_completion(self):
paul@189 1648
paul@189 1649
        "Generate a test for the completion of a try block."
paul@144 1650
paul@144 1651
        self.writestmt("if (__tmp_exc.completing)")
paul@144 1652
        self.writeline("{")
paul@144 1653
        self.indent += 1
paul@189 1654
paul@316 1655
        # Do not return anything at the module level.
paul@316 1656
paul@316 1657
        if self.get_namespace_path() != self.name:
paul@189 1658
paul@316 1659
            # Only use the normal return statement if no surrounding try blocks
paul@316 1660
            # apply.
paul@316 1661
paul@316 1662
            if not self.in_try_finally and not self.in_try_except:
paul@316 1663
                self.writeline("if (!__ISNULL(__tmp_exc.arg)) return __tmp_exc.arg;")
paul@316 1664
            else:
paul@316 1665
                self.writeline("if (!__ISNULL(__tmp_exc.arg)) __Throw(__tmp_exc);")
paul@144 1666
paul@113 1667
        self.indent -= 1
paul@113 1668
        self.writeline("}")
paul@113 1669
paul@113 1670
    def process_while_node(self, n):
paul@113 1671
paul@113 1672
        "Process the given while node 'n'."
paul@113 1673
paul@113 1674
        self.writeline("while (1)")
paul@113 1675
        self.writeline("{")
paul@113 1676
        self.indent += 1
paul@113 1677
        test = self.process_structure_node(n.test)
paul@113 1678
paul@113 1679
        # Emit the loop termination condition unless "while <true value>" is
paul@113 1680
        # indicated.
paul@113 1681
paul@113 1682
        if not (isinstance(test, PredefinedConstantRef) and test.value):
paul@113 1683
paul@113 1684
            # NOTE: This needs to evaluate whether the operand is true or false
paul@113 1685
            # NOTE: according to Python rules.
paul@113 1686
paul@144 1687
            self.writeline("if (!__BOOL(%s))" % test)
paul@113 1688
            self.writeline("{")
paul@113 1689
            self.indent += 1
paul@113 1690
            if n.else_:
paul@113 1691
                self.process_structure_node(n.else_)
paul@128 1692
            self.writestmt("break;")
paul@113 1693
            self.indent -= 1
paul@113 1694
            self.writeline("}")
paul@113 1695
paul@113 1696
        in_conditional = self.in_conditional
paul@113 1697
        self.in_conditional = True
paul@113 1698
        self.process_structure_node(n.body)
paul@113 1699
        self.in_conditional = in_conditional
paul@113 1700
paul@113 1701
        self.indent -= 1
paul@113 1702
        self.writeline("}")
paul@113 1703
paul@482 1704
    # Special variable usage.
paul@482 1705
paul@482 1706
    def record_temp(self, name):
paul@482 1707
paul@482 1708
        """
paul@482 1709
        Record the use of the temporary 'name' in the current namespace. At the
paul@482 1710
        class or module level, the temporary name is associated with the module,
paul@482 1711
        since the variable will then be allocated in the module's own main
paul@482 1712
        program.
paul@482 1713
        """
paul@482 1714
paul@482 1715
        if self.in_function:
paul@482 1716
            path = self.get_namespace_path()
paul@482 1717
        else:
paul@482 1718
            path = self.name
paul@482 1719
paul@482 1720
        init_item(self.temp_usage, path, set)
paul@482 1721
        self.temp_usage[path].add(name)
paul@482 1722
paul@482 1723
    def uses_temp(self, path, name):
paul@482 1724
paul@482 1725
        """
paul@482 1726
        Return whether the given namespace 'path' employs a temporary variable
paul@482 1727
        with the given 'name'. Note that 'path' should only be a module or a
paul@482 1728
        function or method, not a class.
paul@482 1729
        """
paul@482 1730
paul@482 1731
        return self.temp_usage.has_key(path) and name in self.temp_usage[path]
paul@482 1732
paul@113 1733
    # Output generation.
paul@113 1734
paul@128 1735
    def start_output(self):
paul@159 1736
paul@159 1737
        "Write the declarations at the top of each source file."
paul@159 1738
paul@128 1739
        print >>self.out, """\
paul@128 1740
#include "types.h"
paul@144 1741
#include "exceptions.h"
paul@128 1742
#include "ops.h"
paul@128 1743
#include "progconsts.h"
paul@128 1744
#include "progops.h"
paul@128 1745
#include "progtypes.h"
paul@137 1746
#include "main.h"
paul@128 1747
"""
paul@128 1748
paul@482 1749
    def start_unit(self):
paul@482 1750
paul@482 1751
        "Record output within a generated function for later use."
paul@482 1752
paul@482 1753
        self.out = StringIO()
paul@482 1754
paul@482 1755
    def end_unit(self, name):
paul@482 1756
paul@482 1757
        "Add declarations and generated code."
paul@482 1758
paul@482 1759
        # Restore the output stream.
paul@482 1760
paul@482 1761
        out = self.out
paul@482 1762
        self.out = self.out_toplevel
paul@482 1763
paul@482 1764
        self.write_temporaries(name)
paul@482 1765
        out.seek(0)
paul@482 1766
        self.out.write(out.read())
paul@482 1767
paul@482 1768
        self.indent -= 1
paul@482 1769
        print >>self.out, "}"
paul@482 1770
paul@113 1771
    def start_module(self):
paul@159 1772
paul@159 1773
        "Write the start of each module's main function."
paul@159 1774
paul@113 1775
        print >>self.out, "void __main_%s()" % encode_path(self.name)
paul@113 1776
        print >>self.out, "{"
paul@113 1777
        self.indent += 1
paul@482 1778
        self.start_unit()
paul@113 1779
paul@113 1780
    def end_module(self):
paul@159 1781
paul@159 1782
        "End each module by closing its main function."
paul@159 1783
paul@482 1784
        self.end_unit(self.name)
paul@113 1785
paul@113 1786
    def start_function(self, name):
paul@159 1787
paul@159 1788
        "Start the function having the given 'name'."
paul@159 1789
paul@113 1790
        print >>self.out, "__attr %s(__attr __args[])" % encode_function_pointer(name)
paul@113 1791
        print >>self.out, "{"
paul@113 1792
        self.indent += 1
paul@113 1793
paul@113 1794
        # Obtain local names from parameters.
paul@113 1795
paul@113 1796
        parameters = self.importer.function_parameters[name]
paul@144 1797
        locals = self.importer.function_locals[name].keys()
paul@113 1798
        names = []
paul@113 1799
paul@113 1800
        for n in locals:
paul@113 1801
paul@113 1802
            # Filter out special names and parameters. Note that self is a local
paul@113 1803
            # regardless of whether it originally appeared in the parameters or
paul@113 1804
            # not.
paul@113 1805
paul@113 1806
            if n.startswith("$l") or n in parameters or n == "self":
paul@113 1807
                continue
paul@113 1808
            names.append(encode_path(n))
paul@113 1809
paul@113 1810
        # Emit required local names.
paul@113 1811
paul@113 1812
        if names:
paul@113 1813
            names.sort()
paul@113 1814
            self.writeline("__attr %s;" % ", ".join(names))
paul@113 1815
paul@208 1816
        self.write_parameters(name)
paul@482 1817
        self.start_unit()
paul@144 1818
paul@144 1819
    def end_function(self, name):
paul@159 1820
paul@159 1821
        "End the function having the given 'name'."
paul@159 1822
paul@482 1823
        self.end_unit(name)
paul@144 1824
        print >>self.out
paul@144 1825
paul@482 1826
    def write_temporaries(self, name):
paul@482 1827
paul@482 1828
        "Write temporary storage employed by 'name'."
paul@482 1829
paul@482 1830
        # Provide space for the given number of targets.
paul@482 1831
paul@482 1832
        if self.uses_temp(name, "__tmp_targets"):
paul@482 1833
            targets = self.importer.function_targets.get(name)
paul@482 1834
            self.writeline("__attr __tmp_targets[%d];" % targets)
paul@482 1835
paul@482 1836
        # Add temporary variable usage details.
paul@482 1837
paul@482 1838
        if self.uses_temp(name, "__tmp_context"):
paul@482 1839
            self.writeline("__ref __tmp_context;")
paul@482 1840
        if self.uses_temp(name, "__tmp_value"):
paul@482 1841
            self.writeline("__ref __tmp_value;")
paul@482 1842
        if self.uses_temp(name, "__tmp_target_value"):
paul@482 1843
            self.writeline("__ref __tmp_target_value;")
paul@482 1844
        if self.uses_temp(name, "__tmp_result"):
paul@482 1845
            self.writeline("__attr __tmp_result;")
paul@479 1846
paul@479 1847
        module = self.importer.get_module(self.name)
paul@482 1848
paul@482 1849
        if name in module.exception_namespaces:
paul@479 1850
            self.writeline("__exc __tmp_exc;")
paul@149 1851
paul@208 1852
    def write_parameters(self, name):
paul@159 1853
paul@159 1854
        """
paul@159 1855
        For the function having the given 'name', write definitions of
paul@208 1856
        parameters found in the arguments array.
paul@159 1857
        """
paul@159 1858
paul@144 1859
        parameters = self.importer.function_parameters[name]
paul@144 1860
paul@113 1861
        # Generate any self reference.
paul@113 1862
paul@156 1863
        if self.is_method(name):
paul@208 1864
            self.writeline("__attr * const self = &__args[0];")
paul@113 1865
paul@113 1866
        # Generate aliases for the parameters.
paul@113 1867
paul@113 1868
        for i, parameter in enumerate(parameters):
paul@208 1869
            self.writeline("__attr * const %s = &__args[%d];" % (encode_path(parameter), i+1))
paul@113 1870
paul@113 1871
    def start_if(self, first, test_ref):
paul@144 1872
        self.writestmt("%sif (__BOOL(%s))" % (not first and "else " or "", test_ref))
paul@113 1873
        self.writeline("{")
paul@113 1874
        self.indent += 1
paul@113 1875
paul@113 1876
    def end_if(self):
paul@113 1877
        self.indent -= 1
paul@113 1878
        self.writeline("}")
paul@113 1879
paul@113 1880
    def start_else(self):
paul@113 1881
        self.writeline("else")
paul@113 1882
        self.writeline("{")
paul@113 1883
        self.indent += 1
paul@113 1884
paul@113 1885
    def end_else(self):
paul@113 1886
        self.indent -= 1
paul@113 1887
        self.writeline("}")
paul@113 1888
paul@113 1889
    def statement(self, expr):
paul@113 1890
        # NOTE: Should never be None.
paul@113 1891
        if not expr:
paul@128 1892
            self.writestmt("...;")
paul@113 1893
        s = str(expr)
paul@113 1894
        if s:
paul@128 1895
            self.writestmt("%s;" % s)
paul@113 1896
paul@113 1897
    def statements(self, results):
paul@113 1898
        for result in results:
paul@113 1899
            self.statement(result)
paul@113 1900
paul@159 1901
    def writeline(self, s):
paul@159 1902
        print >>self.out, "%s%s" % (self.pad(), self.indenttext(s, self.indent + 1))
paul@159 1903
paul@159 1904
    def writestmt(self, s):
paul@159 1905
        print >>self.out
paul@159 1906
        self.writeline(s)
paul@159 1907
paul@159 1908
    def write_comment(self, s):
paul@159 1909
        self.writestmt("/* %s */" % s)
paul@159 1910
paul@113 1911
    def pad(self, extra=0):
paul@113 1912
        return (self.indent + extra) * self.tabstop
paul@113 1913
paul@113 1914
    def indenttext(self, s, levels):
paul@116 1915
        lines = s.split("\n")
paul@116 1916
        out = [lines[0]]
paul@116 1917
        for line in lines[1:]:
paul@116 1918
            out.append(levels * self.tabstop + line)
paul@116 1919
            if line.endswith("("):
paul@116 1920
                levels += 1
paul@122 1921
            elif line.startswith(")"):
paul@116 1922
                levels -= 1
paul@116 1923
        return "\n".join(out)
paul@113 1924
paul@113 1925
# vim: tabstop=4 expandtab shiftwidth=4