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