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