paul@113 | 1 | #!/usr/bin/env python |
paul@113 | 2 | |
paul@113 | 3 | """ |
paul@113 | 4 | Translate programs. |
paul@113 | 5 | |
paul@113 | 6 | Copyright (C) 2015, 2016 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@113 | 22 | from common import * |
paul@113 | 23 | from encoders import * |
paul@113 | 24 | from os.path import exists, join |
paul@113 | 25 | from os import makedirs |
paul@113 | 26 | import compiler |
paul@113 | 27 | import results |
paul@113 | 28 | |
paul@113 | 29 | class Translator(CommonOutput): |
paul@113 | 30 | |
paul@113 | 31 | "A program translator." |
paul@113 | 32 | |
paul@113 | 33 | def __init__(self, importer, deducer, optimiser, output): |
paul@113 | 34 | self.importer = importer |
paul@113 | 35 | self.deducer = deducer |
paul@113 | 36 | self.optimiser = optimiser |
paul@113 | 37 | self.output = output |
paul@113 | 38 | |
paul@113 | 39 | def to_output(self): |
paul@113 | 40 | output = join(self.output, "src") |
paul@113 | 41 | |
paul@113 | 42 | if not exists(output): |
paul@113 | 43 | makedirs(output) |
paul@113 | 44 | |
paul@113 | 45 | self.check_output() |
paul@113 | 46 | |
paul@113 | 47 | for module in self.importer.modules.values(): |
paul@113 | 48 | tm = TranslatedModule(module.name, self.importer, self.deducer, self.optimiser) |
paul@113 | 49 | tm.translate(module.filename, join(output, "%s.c" % module.name)) |
paul@113 | 50 | |
paul@113 | 51 | # Classes representing intermediate translation results. |
paul@113 | 52 | |
paul@113 | 53 | class TranslationResult: |
paul@113 | 54 | |
paul@113 | 55 | "An abstract translation result mix-in." |
paul@113 | 56 | |
paul@113 | 57 | pass |
paul@113 | 58 | |
paul@144 | 59 | class ReturnRef(TranslationResult): |
paul@144 | 60 | |
paul@144 | 61 | "Indicates usage of a return statement." |
paul@144 | 62 | |
paul@144 | 63 | pass |
paul@144 | 64 | |
paul@113 | 65 | class Expression(results.Result, TranslationResult): |
paul@113 | 66 | |
paul@113 | 67 | "A general expression." |
paul@113 | 68 | |
paul@113 | 69 | def __init__(self, s): |
paul@113 | 70 | self.s = s |
paul@113 | 71 | def __str__(self): |
paul@113 | 72 | return self.s |
paul@113 | 73 | def __repr__(self): |
paul@113 | 74 | return "Expression(%r)" % self.s |
paul@113 | 75 | |
paul@113 | 76 | class TrResolvedNameRef(results.ResolvedNameRef, TranslationResult): |
paul@113 | 77 | |
paul@113 | 78 | "A reference to a name in the translation." |
paul@113 | 79 | |
paul@113 | 80 | def __str__(self): |
paul@113 | 81 | |
paul@113 | 82 | "Return an output representation of the referenced name." |
paul@113 | 83 | |
paul@113 | 84 | # For sources, any identified static origin will be constant and thus |
paul@113 | 85 | # usable directly. For targets, no constant should be assigned and thus |
paul@113 | 86 | # the alias (or any plain name) will be used. |
paul@113 | 87 | |
paul@137 | 88 | ref = self.static() |
paul@137 | 89 | origin = ref and self.get_origin() |
paul@137 | 90 | static_name = origin and encode_path(origin) |
paul@149 | 91 | |
paul@149 | 92 | # Determine whether a qualified name is involved. |
paul@149 | 93 | |
paul@149 | 94 | t = (self.expr and self.get_name() or self.name).rsplit(".", 1) |
paul@149 | 95 | parent = len(t) > 1 and t[0] or None |
paul@149 | 96 | attrname = encode_path(t[-1]) |
paul@113 | 97 | |
paul@113 | 98 | # Assignments. |
paul@113 | 99 | |
paul@113 | 100 | if self.expr: |
paul@113 | 101 | |
paul@113 | 102 | # Eliminate assignments between constants. |
paul@113 | 103 | |
paul@113 | 104 | if self.static() and isinstance(self.expr, results.ResolvedNameRef) and self.expr.static(): |
paul@113 | 105 | return "" |
paul@149 | 106 | |
paul@149 | 107 | # Qualified names must be converted into parent-relative assignments. |
paul@149 | 108 | |
paul@149 | 109 | elif parent: |
paul@149 | 110 | return "__store_via_object(&%s, %s, %s)" % ( |
paul@149 | 111 | encode_path(parent), encode_symbol("pos", attrname), self.expr) |
paul@149 | 112 | |
paul@149 | 113 | # All other assignments involve the names as they were given. |
paul@149 | 114 | |
paul@113 | 115 | else: |
paul@149 | 116 | return "%s = %s" % (attrname, self.expr) |
paul@113 | 117 | |
paul@113 | 118 | # Expressions. |
paul@113 | 119 | |
paul@137 | 120 | elif static_name: |
paul@137 | 121 | parent = ref.parent() |
paul@141 | 122 | context = ref.has_kind("<function>") and encode_path(parent) or None |
paul@144 | 123 | return "((__attr) {%s, &%s})" % (context and "&%s" % context or "0", static_name) |
paul@137 | 124 | |
paul@113 | 125 | else: |
paul@149 | 126 | return attrname |
paul@113 | 127 | |
paul@113 | 128 | class TrConstantValueRef(results.ConstantValueRef, TranslationResult): |
paul@113 | 129 | |
paul@113 | 130 | "A constant value reference in the translation." |
paul@113 | 131 | |
paul@113 | 132 | def __str__(self): |
paul@136 | 133 | return encode_literal_constant(self.number) |
paul@113 | 134 | |
paul@113 | 135 | class TrLiteralSequenceRef(results.LiteralSequenceRef, TranslationResult): |
paul@113 | 136 | |
paul@113 | 137 | "A reference representing a sequence of values." |
paul@113 | 138 | |
paul@113 | 139 | def __str__(self): |
paul@113 | 140 | return str(self.node) |
paul@113 | 141 | |
paul@113 | 142 | class AttrResult(Expression, TranslationResult): |
paul@113 | 143 | |
paul@113 | 144 | "A translation result for an attribute access." |
paul@113 | 145 | |
paul@113 | 146 | def __init__(self, s, refs): |
paul@113 | 147 | Expression.__init__(self, s) |
paul@113 | 148 | self.refs = refs |
paul@113 | 149 | |
paul@113 | 150 | def get_origin(self): |
paul@113 | 151 | return self.refs and len(self.refs) == 1 and first(self.refs).get_origin() |
paul@113 | 152 | |
paul@118 | 153 | def has_kind(self, kinds): |
paul@118 | 154 | if not self.refs: |
paul@118 | 155 | return False |
paul@118 | 156 | for ref in self.refs: |
paul@118 | 157 | if ref.has_kind(kinds): |
paul@118 | 158 | return True |
paul@118 | 159 | return False |
paul@118 | 160 | |
paul@113 | 161 | def __repr__(self): |
paul@136 | 162 | return "AttrResult(%r, %r)" % (self.s, self.get_origin()) |
paul@113 | 163 | |
paul@113 | 164 | class PredefinedConstantRef(AttrResult): |
paul@113 | 165 | |
paul@113 | 166 | "A predefined constant reference." |
paul@113 | 167 | |
paul@113 | 168 | def __init__(self, value): |
paul@113 | 169 | self.value = value |
paul@113 | 170 | |
paul@113 | 171 | def __str__(self): |
paul@136 | 172 | if self.value in ("False", "True"): |
paul@136 | 173 | return encode_path("__builtins__.bool.%s" % self.value) |
paul@136 | 174 | elif self.value == "None": |
paul@136 | 175 | return encode_path("__builtins__.none.%s" % self.value) |
paul@136 | 176 | elif self.value == "NotImplemented": |
paul@136 | 177 | return encode_path("__builtins__.notimplemented.%s" % self.value) |
paul@136 | 178 | else: |
paul@136 | 179 | return self.value |
paul@113 | 180 | |
paul@113 | 181 | def __repr__(self): |
paul@113 | 182 | return "PredefinedConstantRef(%r)" % self.value |
paul@113 | 183 | |
paul@141 | 184 | class BooleanResult(Expression, TranslationResult): |
paul@141 | 185 | |
paul@141 | 186 | "A expression producing a boolean result." |
paul@141 | 187 | |
paul@141 | 188 | def __str__(self): |
paul@141 | 189 | return "__builtins___bool_bool(%s)" % self.s |
paul@141 | 190 | |
paul@141 | 191 | def __repr__(self): |
paul@141 | 192 | return "BooleanResult(%r)" % self.s |
paul@141 | 193 | |
paul@113 | 194 | def make_expression(expr): |
paul@113 | 195 | |
paul@113 | 196 | "Make a new expression from the existing 'expr'." |
paul@113 | 197 | |
paul@113 | 198 | if isinstance(expr, results.Result): |
paul@113 | 199 | return expr |
paul@113 | 200 | else: |
paul@113 | 201 | return Expression(str(expr)) |
paul@113 | 202 | |
paul@113 | 203 | # The actual translation process itself. |
paul@113 | 204 | |
paul@113 | 205 | class TranslatedModule(CommonModule): |
paul@113 | 206 | |
paul@113 | 207 | "A module translator." |
paul@113 | 208 | |
paul@113 | 209 | def __init__(self, name, importer, deducer, optimiser): |
paul@113 | 210 | CommonModule.__init__(self, name, importer) |
paul@113 | 211 | self.deducer = deducer |
paul@113 | 212 | self.optimiser = optimiser |
paul@113 | 213 | |
paul@113 | 214 | # Output stream. |
paul@113 | 215 | |
paul@113 | 216 | self.out = None |
paul@113 | 217 | self.indent = 0 |
paul@113 | 218 | self.tabstop = " " |
paul@113 | 219 | |
paul@113 | 220 | # Recorded namespaces. |
paul@113 | 221 | |
paul@113 | 222 | self.namespaces = [] |
paul@113 | 223 | self.in_conditional = False |
paul@113 | 224 | |
paul@144 | 225 | # Exception raising adjustments. |
paul@144 | 226 | |
paul@144 | 227 | self.in_try_finally = False |
paul@144 | 228 | |
paul@113 | 229 | # Attribute access counting. |
paul@113 | 230 | |
paul@113 | 231 | self.attr_accesses = {} |
paul@113 | 232 | |
paul@113 | 233 | def __repr__(self): |
paul@113 | 234 | return "TranslatedModule(%r, %r)" % (self.name, self.importer) |
paul@113 | 235 | |
paul@113 | 236 | def translate(self, filename, output_filename): |
paul@113 | 237 | |
paul@113 | 238 | """ |
paul@113 | 239 | Parse the file having the given 'filename', writing the translation to |
paul@113 | 240 | the given 'output_filename'. |
paul@113 | 241 | """ |
paul@113 | 242 | |
paul@113 | 243 | self.parse_file(filename) |
paul@113 | 244 | |
paul@113 | 245 | # Collect function namespaces for separate processing. |
paul@113 | 246 | |
paul@113 | 247 | self.record_namespaces(self.astnode) |
paul@113 | 248 | |
paul@113 | 249 | # Reset the lambda naming (in order to obtain the same names again) and |
paul@113 | 250 | # translate the program. |
paul@113 | 251 | |
paul@113 | 252 | self.reset_lambdas() |
paul@113 | 253 | |
paul@113 | 254 | self.out = open(output_filename, "w") |
paul@113 | 255 | try: |
paul@128 | 256 | self.start_output() |
paul@128 | 257 | |
paul@113 | 258 | # Process namespaces, writing the translation. |
paul@113 | 259 | |
paul@113 | 260 | for path, node in self.namespaces: |
paul@113 | 261 | self.process_namespace(path, node) |
paul@113 | 262 | |
paul@113 | 263 | # Process the module namespace including class namespaces. |
paul@113 | 264 | |
paul@113 | 265 | self.process_namespace([], self.astnode) |
paul@113 | 266 | |
paul@113 | 267 | finally: |
paul@113 | 268 | self.out.close() |
paul@113 | 269 | |
paul@113 | 270 | def have_object(self): |
paul@113 | 271 | |
paul@113 | 272 | "Return whether a namespace is a recorded object." |
paul@113 | 273 | |
paul@113 | 274 | return self.importer.objects.get(self.get_namespace_path()) |
paul@113 | 275 | |
paul@113 | 276 | def get_builtin(self, name): |
paul@113 | 277 | return self.importer.get_object("__builtins__.%s" % name) |
paul@113 | 278 | |
paul@113 | 279 | def in_method(self, path): |
paul@113 | 280 | class_name, method_name = path.rsplit(".", 1) |
paul@113 | 281 | return self.importer.classes.has_key(class_name) and class_name |
paul@113 | 282 | |
paul@113 | 283 | # Namespace recording. |
paul@113 | 284 | |
paul@113 | 285 | def record_namespaces(self, node): |
paul@113 | 286 | |
paul@113 | 287 | "Process the program structure 'node', recording namespaces." |
paul@113 | 288 | |
paul@113 | 289 | for n in node.getChildNodes(): |
paul@113 | 290 | self.record_namespaces_in_node(n) |
paul@113 | 291 | |
paul@113 | 292 | def record_namespaces_in_node(self, node): |
paul@113 | 293 | |
paul@113 | 294 | "Process the program structure 'node', recording namespaces." |
paul@113 | 295 | |
paul@113 | 296 | # Function namespaces within modules, classes and other functions. |
paul@113 | 297 | # Functions appearing within conditional statements are given arbitrary |
paul@113 | 298 | # names. |
paul@113 | 299 | |
paul@113 | 300 | if isinstance(node, compiler.ast.Function): |
paul@113 | 301 | self.record_function_node(node, (self.in_conditional or self.in_function) and self.get_lambda_name() or node.name) |
paul@113 | 302 | |
paul@113 | 303 | elif isinstance(node, compiler.ast.Lambda): |
paul@113 | 304 | self.record_function_node(node, self.get_lambda_name()) |
paul@113 | 305 | |
paul@113 | 306 | # Classes are visited, but may be ignored if inside functions. |
paul@113 | 307 | |
paul@113 | 308 | elif isinstance(node, compiler.ast.Class): |
paul@113 | 309 | self.enter_namespace(node.name) |
paul@113 | 310 | if self.have_object(): |
paul@113 | 311 | self.record_namespaces(node) |
paul@113 | 312 | self.exit_namespace() |
paul@113 | 313 | |
paul@113 | 314 | # Conditional nodes are tracked so that function definitions may be |
paul@113 | 315 | # handled. Since "for" loops are converted to "while" loops, they are |
paul@113 | 316 | # included here. |
paul@113 | 317 | |
paul@113 | 318 | elif isinstance(node, (compiler.ast.For, compiler.ast.If, compiler.ast.While)): |
paul@113 | 319 | in_conditional = self.in_conditional |
paul@113 | 320 | self.in_conditional = True |
paul@113 | 321 | self.record_namespaces(node) |
paul@113 | 322 | self.in_conditional = in_conditional |
paul@113 | 323 | |
paul@113 | 324 | # All other nodes are processed depth-first. |
paul@113 | 325 | |
paul@113 | 326 | else: |
paul@113 | 327 | self.record_namespaces(node) |
paul@113 | 328 | |
paul@113 | 329 | def record_function_node(self, n, name): |
paul@113 | 330 | |
paul@113 | 331 | """ |
paul@113 | 332 | Record the given function, lambda, if expression or list comprehension |
paul@113 | 333 | node 'n' with the given 'name'. |
paul@113 | 334 | """ |
paul@113 | 335 | |
paul@113 | 336 | self.in_function = True |
paul@113 | 337 | self.enter_namespace(name) |
paul@113 | 338 | |
paul@113 | 339 | if self.have_object(): |
paul@113 | 340 | |
paul@113 | 341 | # Record the namespace path and the node itself. |
paul@113 | 342 | |
paul@113 | 343 | self.namespaces.append((self.namespace_path[:], n)) |
paul@113 | 344 | self.record_namespaces_in_node(n.code) |
paul@113 | 345 | |
paul@113 | 346 | self.exit_namespace() |
paul@113 | 347 | self.in_function = False |
paul@113 | 348 | |
paul@113 | 349 | # Constant referencing. |
paul@113 | 350 | |
paul@113 | 351 | def get_literal_instance(self, n, name): |
paul@113 | 352 | |
paul@113 | 353 | """ |
paul@113 | 354 | For node 'n', return a reference for the type of the given 'name'. |
paul@113 | 355 | """ |
paul@113 | 356 | |
paul@113 | 357 | ref = self.get_builtin(name) |
paul@113 | 358 | |
paul@113 | 359 | if name in ("dict", "list", "tuple"): |
paul@113 | 360 | return self.process_literal_sequence_node(n, name, ref, TrLiteralSequenceRef) |
paul@113 | 361 | else: |
paul@113 | 362 | path = self.get_namespace_path() |
paul@113 | 363 | local_number = self.importer.all_constants[path][n.value] |
paul@113 | 364 | constant_name = "$c%d" % local_number |
paul@113 | 365 | objpath = self.get_object_path(constant_name) |
paul@113 | 366 | number = self.optimiser.constant_numbers[objpath] |
paul@113 | 367 | return TrConstantValueRef(constant_name, ref.instance_of(), n.value, number) |
paul@113 | 368 | |
paul@113 | 369 | # Namespace translation. |
paul@113 | 370 | |
paul@113 | 371 | def process_namespace(self, path, node): |
paul@113 | 372 | |
paul@113 | 373 | """ |
paul@113 | 374 | Process the namespace for the given 'path' defined by the given 'node'. |
paul@113 | 375 | """ |
paul@113 | 376 | |
paul@113 | 377 | self.namespace_path = path |
paul@113 | 378 | |
paul@113 | 379 | if isinstance(node, (compiler.ast.Function, compiler.ast.Lambda)): |
paul@113 | 380 | self.in_function = True |
paul@113 | 381 | self.process_function_body_node(node) |
paul@113 | 382 | else: |
paul@113 | 383 | self.in_function = False |
paul@113 | 384 | self.start_module() |
paul@113 | 385 | self.process_structure(node) |
paul@113 | 386 | self.end_module() |
paul@113 | 387 | |
paul@113 | 388 | def process_structure(self, node): |
paul@113 | 389 | |
paul@113 | 390 | "Process the given 'node' or result." |
paul@113 | 391 | |
paul@144 | 392 | # Handle processing requests on results. |
paul@144 | 393 | |
paul@113 | 394 | if isinstance(node, results.Result): |
paul@113 | 395 | return node |
paul@144 | 396 | |
paul@144 | 397 | # Handle processing requests on nodes. |
paul@144 | 398 | |
paul@113 | 399 | else: |
paul@144 | 400 | l = CommonModule.process_structure(self, node) |
paul@144 | 401 | |
paul@144 | 402 | # Return indications of return statement usage. |
paul@144 | 403 | |
paul@144 | 404 | if l and isinstance(l[-1], ReturnRef): |
paul@144 | 405 | return l[-1] |
paul@144 | 406 | else: |
paul@144 | 407 | return None |
paul@113 | 408 | |
paul@113 | 409 | def process_structure_node(self, n): |
paul@113 | 410 | |
paul@113 | 411 | "Process the individual node 'n'." |
paul@113 | 412 | |
paul@113 | 413 | # Plain statements emit their expressions. |
paul@113 | 414 | |
paul@113 | 415 | if isinstance(n, compiler.ast.Discard): |
paul@113 | 416 | expr = self.process_structure_node(n.expr) |
paul@113 | 417 | self.statement(expr) |
paul@113 | 418 | |
paul@113 | 419 | # Nodes using operator module functions. |
paul@113 | 420 | |
paul@113 | 421 | elif isinstance(n, compiler.ast.Operator): |
paul@113 | 422 | return self.process_operator_node(n) |
paul@113 | 423 | |
paul@113 | 424 | elif isinstance(n, compiler.ast.AugAssign): |
paul@113 | 425 | self.process_augassign_node(n) |
paul@113 | 426 | |
paul@113 | 427 | elif isinstance(n, compiler.ast.Compare): |
paul@113 | 428 | return self.process_compare_node(n) |
paul@113 | 429 | |
paul@113 | 430 | elif isinstance(n, compiler.ast.Slice): |
paul@113 | 431 | return self.process_slice_node(n) |
paul@113 | 432 | |
paul@113 | 433 | elif isinstance(n, compiler.ast.Sliceobj): |
paul@113 | 434 | return self.process_sliceobj_node(n) |
paul@113 | 435 | |
paul@113 | 436 | elif isinstance(n, compiler.ast.Subscript): |
paul@113 | 437 | return self.process_subscript_node(n) |
paul@113 | 438 | |
paul@113 | 439 | # Classes are visited, but may be ignored if inside functions. |
paul@113 | 440 | |
paul@113 | 441 | elif isinstance(n, compiler.ast.Class): |
paul@113 | 442 | self.process_class_node(n) |
paul@113 | 443 | |
paul@113 | 444 | # Functions within namespaces have any dynamic defaults initialised. |
paul@113 | 445 | |
paul@113 | 446 | elif isinstance(n, compiler.ast.Function): |
paul@113 | 447 | self.process_function_node(n) |
paul@113 | 448 | |
paul@113 | 449 | # Lambdas are replaced with references to separately-generated |
paul@113 | 450 | # functions. |
paul@113 | 451 | |
paul@113 | 452 | elif isinstance(n, compiler.ast.Lambda): |
paul@113 | 453 | return self.process_lambda_node(n) |
paul@113 | 454 | |
paul@113 | 455 | # Assignments. |
paul@113 | 456 | |
paul@113 | 457 | elif isinstance(n, compiler.ast.Assign): |
paul@113 | 458 | |
paul@113 | 459 | # Handle each assignment node. |
paul@113 | 460 | |
paul@113 | 461 | for node in n.nodes: |
paul@113 | 462 | self.process_assignment_node(node, n.expr) |
paul@113 | 463 | |
paul@113 | 464 | # Assignments within non-Assign nodes. |
paul@113 | 465 | # NOTE: Cover all possible nodes employing these. |
paul@113 | 466 | |
paul@113 | 467 | elif isinstance(n, compiler.ast.AssName): |
paul@113 | 468 | self.process_assignment_node(n, compiler.ast.Name("$temp")) |
paul@113 | 469 | |
paul@113 | 470 | elif isinstance(n, compiler.ast.AssAttr): |
paul@113 | 471 | self.process_attribute_access(n) |
paul@113 | 472 | |
paul@113 | 473 | # Accesses. |
paul@113 | 474 | |
paul@113 | 475 | elif isinstance(n, compiler.ast.Getattr): |
paul@113 | 476 | return self.process_attribute_access(n) |
paul@113 | 477 | |
paul@113 | 478 | # Names. |
paul@113 | 479 | |
paul@113 | 480 | elif isinstance(n, compiler.ast.Name): |
paul@113 | 481 | return self.process_name_node(n) |
paul@113 | 482 | |
paul@113 | 483 | # Loops and conditionals. |
paul@113 | 484 | |
paul@113 | 485 | elif isinstance(n, compiler.ast.For): |
paul@113 | 486 | self.process_for_node(n) |
paul@113 | 487 | |
paul@113 | 488 | elif isinstance(n, compiler.ast.While): |
paul@113 | 489 | self.process_while_node(n) |
paul@113 | 490 | |
paul@113 | 491 | elif isinstance(n, compiler.ast.If): |
paul@113 | 492 | self.process_if_node(n) |
paul@113 | 493 | |
paul@113 | 494 | elif isinstance(n, (compiler.ast.And, compiler.ast.Or)): |
paul@113 | 495 | return self.process_logical_node(n) |
paul@113 | 496 | |
paul@113 | 497 | elif isinstance(n, compiler.ast.Not): |
paul@113 | 498 | return self.process_not_node(n) |
paul@113 | 499 | |
paul@113 | 500 | # Exception control-flow tracking. |
paul@113 | 501 | |
paul@113 | 502 | elif isinstance(n, compiler.ast.TryExcept): |
paul@113 | 503 | self.process_try_node(n) |
paul@113 | 504 | |
paul@113 | 505 | elif isinstance(n, compiler.ast.TryFinally): |
paul@113 | 506 | self.process_try_finally_node(n) |
paul@113 | 507 | |
paul@113 | 508 | # Control-flow modification statements. |
paul@113 | 509 | |
paul@113 | 510 | elif isinstance(n, compiler.ast.Break): |
paul@128 | 511 | self.writestmt("break;") |
paul@113 | 512 | |
paul@113 | 513 | elif isinstance(n, compiler.ast.Continue): |
paul@128 | 514 | self.writestmt("continue;") |
paul@113 | 515 | |
paul@144 | 516 | elif isinstance(n, compiler.ast.Raise): |
paul@144 | 517 | self.process_raise_node(n) |
paul@144 | 518 | |
paul@113 | 519 | elif isinstance(n, compiler.ast.Return): |
paul@144 | 520 | return self.process_return_node(n) |
paul@113 | 521 | |
paul@113 | 522 | # Invocations. |
paul@113 | 523 | |
paul@113 | 524 | elif isinstance(n, compiler.ast.CallFunc): |
paul@113 | 525 | return self.process_invocation_node(n) |
paul@113 | 526 | |
paul@113 | 527 | elif isinstance(n, compiler.ast.Keyword): |
paul@113 | 528 | return self.process_structure_node(n.expr) |
paul@113 | 529 | |
paul@113 | 530 | # Constant usage. |
paul@113 | 531 | |
paul@113 | 532 | elif isinstance(n, compiler.ast.Const): |
paul@113 | 533 | return self.get_literal_instance(n, n.value.__class__.__name__) |
paul@113 | 534 | |
paul@113 | 535 | elif isinstance(n, compiler.ast.Dict): |
paul@113 | 536 | return self.get_literal_instance(n, "dict") |
paul@113 | 537 | |
paul@113 | 538 | elif isinstance(n, compiler.ast.List): |
paul@113 | 539 | return self.get_literal_instance(n, "list") |
paul@113 | 540 | |
paul@113 | 541 | elif isinstance(n, compiler.ast.Tuple): |
paul@113 | 542 | return self.get_literal_instance(n, "tuple") |
paul@113 | 543 | |
paul@113 | 544 | # All other nodes are processed depth-first. |
paul@113 | 545 | |
paul@113 | 546 | else: |
paul@144 | 547 | return self.process_structure(n) |
paul@113 | 548 | |
paul@113 | 549 | def process_assignment_node(self, n, expr): |
paul@113 | 550 | |
paul@113 | 551 | "Process the individual node 'n' to be assigned the contents of 'expr'." |
paul@113 | 552 | |
paul@113 | 553 | # Names and attributes are assigned the entire expression. |
paul@113 | 554 | |
paul@113 | 555 | if isinstance(n, compiler.ast.AssName): |
paul@113 | 556 | name_ref = self.process_name_node(n, self.process_structure_node(expr)) |
paul@113 | 557 | self.statement(name_ref) |
paul@113 | 558 | |
paul@113 | 559 | elif isinstance(n, compiler.ast.AssAttr): |
paul@124 | 560 | in_assignment = self.in_assignment |
paul@124 | 561 | self.in_assignment = self.process_structure_node(expr) |
paul@124 | 562 | self.statement(self.process_attribute_access(n)) |
paul@124 | 563 | self.in_assignment = in_assignment |
paul@113 | 564 | |
paul@113 | 565 | # Lists and tuples are matched against the expression and their |
paul@113 | 566 | # items assigned to expression items. |
paul@113 | 567 | |
paul@113 | 568 | elif isinstance(n, (compiler.ast.AssList, compiler.ast.AssTuple)): |
paul@113 | 569 | self.process_assignment_node_items(n, expr) |
paul@113 | 570 | |
paul@113 | 571 | # Slices and subscripts are permitted within assignment nodes. |
paul@113 | 572 | |
paul@113 | 573 | elif isinstance(n, compiler.ast.Slice): |
paul@113 | 574 | self.statement(self.process_slice_node(n, expr)) |
paul@113 | 575 | |
paul@113 | 576 | elif isinstance(n, compiler.ast.Subscript): |
paul@113 | 577 | self.statement(self.process_subscript_node(n, expr)) |
paul@113 | 578 | |
paul@124 | 579 | def process_attribute_access(self, n): |
paul@113 | 580 | |
paul@113 | 581 | """ |
paul@113 | 582 | Process the given attribute access node 'n'. |
paul@113 | 583 | |
paul@113 | 584 | Where a name is provided, a single access should be recorded |
paul@113 | 585 | involving potentially many attributes, thus providing a path to an |
paul@113 | 586 | object. The remaining attributes are then accessed dynamically. |
paul@113 | 587 | The remaining accesses could be deduced and computed, but they would |
paul@113 | 588 | also need to be tested. |
paul@113 | 589 | |
paul@113 | 590 | Where no name is provided, potentially many accesses should be |
paul@113 | 591 | recorded, one per attribute name. These could be used to provide |
paul@113 | 592 | computed accesses, but the accessors would need to be tested in each |
paul@113 | 593 | case. |
paul@113 | 594 | """ |
paul@113 | 595 | |
paul@113 | 596 | # Obtain any completed chain and return the reference to it. |
paul@113 | 597 | |
paul@113 | 598 | attr_expr = self.process_attribute_chain(n) |
paul@113 | 599 | if self.have_access_expression(n): |
paul@113 | 600 | return attr_expr |
paul@113 | 601 | |
paul@113 | 602 | # Where the start of the chain of attributes has been reached, process |
paul@113 | 603 | # the complete access. |
paul@113 | 604 | |
paul@113 | 605 | name_ref = attr_expr and attr_expr.is_name() and attr_expr |
paul@113 | 606 | name = name_ref and name_ref.name or None |
paul@113 | 607 | |
paul@113 | 608 | location = self.get_access_location(name) |
paul@113 | 609 | refs = self.get_referenced_attributes(location) |
paul@113 | 610 | |
paul@113 | 611 | # Generate access instructions. |
paul@113 | 612 | |
paul@113 | 613 | subs = { |
paul@113 | 614 | "<expr>" : str(attr_expr), |
paul@124 | 615 | "<assexpr>" : str(self.in_assignment), |
paul@113 | 616 | "<context>" : "__tmp_context", |
paul@113 | 617 | "<accessor>" : "__tmp_value", |
paul@113 | 618 | } |
paul@113 | 619 | |
paul@113 | 620 | output = [] |
paul@113 | 621 | |
paul@113 | 622 | for instruction in self.optimiser.access_instructions[location]: |
paul@113 | 623 | output.append(encode_access_instruction(instruction, subs)) |
paul@113 | 624 | |
paul@128 | 625 | if len(output) == 1: |
paul@128 | 626 | out = output[0] |
paul@128 | 627 | else: |
paul@128 | 628 | out = "(\n%s\n)" % ",\n".join(output) |
paul@113 | 629 | |
paul@113 | 630 | del self.attrs[0] |
paul@113 | 631 | return AttrResult(out, refs) |
paul@113 | 632 | |
paul@113 | 633 | def get_referenced_attributes(self, location): |
paul@113 | 634 | |
paul@113 | 635 | """ |
paul@113 | 636 | Convert 'location' to the form used by the deducer and retrieve any |
paul@113 | 637 | identified attribute. |
paul@113 | 638 | """ |
paul@113 | 639 | |
paul@113 | 640 | access_location = self.deducer.const_accesses.get(location) |
paul@113 | 641 | refs = [] |
paul@113 | 642 | for attrtype, objpath, attr in self.deducer.referenced_attrs[access_location or location]: |
paul@113 | 643 | refs.append(attr) |
paul@113 | 644 | return refs |
paul@113 | 645 | |
paul@113 | 646 | def get_access_location(self, name): |
paul@113 | 647 | |
paul@113 | 648 | """ |
paul@113 | 649 | Using the current namespace and the given 'name', return the access |
paul@113 | 650 | location. |
paul@113 | 651 | """ |
paul@113 | 652 | |
paul@113 | 653 | path = self.get_path_for_access() |
paul@113 | 654 | |
paul@113 | 655 | # Get the location used by the deducer and optimiser and find any |
paul@113 | 656 | # recorded access. |
paul@113 | 657 | |
paul@113 | 658 | attrnames = ".".join(self.attrs) |
paul@113 | 659 | access_number = self.get_access_number(path, name, attrnames) |
paul@113 | 660 | self.update_access_number(path, name, attrnames) |
paul@113 | 661 | return (path, name, attrnames, access_number) |
paul@113 | 662 | |
paul@113 | 663 | def get_access_number(self, path, name, attrnames): |
paul@113 | 664 | access = name, attrnames |
paul@113 | 665 | if self.attr_accesses.has_key(path) and self.attr_accesses[path].has_key(access): |
paul@113 | 666 | return self.attr_accesses[path][access] |
paul@113 | 667 | else: |
paul@113 | 668 | return 0 |
paul@113 | 669 | |
paul@113 | 670 | def update_access_number(self, path, name, attrnames): |
paul@113 | 671 | access = name, attrnames |
paul@113 | 672 | if name: |
paul@113 | 673 | init_item(self.attr_accesses, path, dict) |
paul@144 | 674 | init_item(self.attr_accesses[path], access, lambda: 0) |
paul@144 | 675 | self.attr_accesses[path][access] += 1 |
paul@113 | 676 | |
paul@113 | 677 | def process_class_node(self, n): |
paul@113 | 678 | |
paul@113 | 679 | "Process the given class node 'n'." |
paul@113 | 680 | |
paul@113 | 681 | self.enter_namespace(n.name) |
paul@113 | 682 | |
paul@113 | 683 | if self.have_object(): |
paul@113 | 684 | class_name = self.get_namespace_path() |
paul@113 | 685 | self.write_comment("Class: %s" % class_name) |
paul@113 | 686 | |
paul@113 | 687 | self.process_structure(n) |
paul@113 | 688 | |
paul@113 | 689 | self.exit_namespace() |
paul@113 | 690 | |
paul@113 | 691 | def process_function_body_node(self, n): |
paul@113 | 692 | |
paul@113 | 693 | """ |
paul@113 | 694 | Process the given function, lambda, if expression or list comprehension |
paul@113 | 695 | node 'n', generating the body. |
paul@113 | 696 | """ |
paul@113 | 697 | |
paul@113 | 698 | function_name = self.get_namespace_path() |
paul@113 | 699 | self.start_function(function_name) |
paul@113 | 700 | |
paul@113 | 701 | # Process the function body. |
paul@113 | 702 | |
paul@113 | 703 | in_conditional = self.in_conditional |
paul@113 | 704 | self.in_conditional = False |
paul@113 | 705 | |
paul@144 | 706 | expr = self.process_structure_node(n.code) or PredefinedConstantRef("None") |
paul@144 | 707 | if not isinstance(expr, ReturnRef): |
paul@128 | 708 | self.writestmt("return %s;" % expr) |
paul@113 | 709 | |
paul@113 | 710 | self.in_conditional = in_conditional |
paul@113 | 711 | |
paul@144 | 712 | self.end_function(function_name) |
paul@113 | 713 | |
paul@113 | 714 | def process_function_node(self, n): |
paul@113 | 715 | |
paul@113 | 716 | """ |
paul@113 | 717 | Process the given function, lambda, if expression or list comprehension |
paul@113 | 718 | node 'n', generating any initialisation statements. |
paul@113 | 719 | """ |
paul@113 | 720 | |
paul@113 | 721 | # Where a function is declared conditionally, use a separate name for |
paul@113 | 722 | # the definition, and assign the definition to the stated name. |
paul@113 | 723 | |
paul@113 | 724 | if self.in_conditional or self.in_function: |
paul@113 | 725 | original_name = n.name |
paul@113 | 726 | name = self.get_lambda_name() |
paul@113 | 727 | else: |
paul@113 | 728 | original_name = None |
paul@113 | 729 | name = n.name |
paul@113 | 730 | |
paul@113 | 731 | # Obtain details of the defaults. |
paul@113 | 732 | |
paul@149 | 733 | defaults = self.process_function_defaults(n, name, "&%s" % self.get_object_path(name)) |
paul@113 | 734 | if defaults: |
paul@113 | 735 | for default in defaults: |
paul@113 | 736 | self.writeline("%s;" % default) |
paul@113 | 737 | |
paul@113 | 738 | # Where a function is set conditionally, assign the name. |
paul@113 | 739 | |
paul@113 | 740 | if original_name: |
paul@113 | 741 | self.process_assignment_for_function(original_name, name) |
paul@113 | 742 | |
paul@113 | 743 | def process_function_defaults(self, n, name, instance_name): |
paul@113 | 744 | |
paul@113 | 745 | """ |
paul@113 | 746 | Process the given function or lambda node 'n', initialising defaults |
paul@113 | 747 | that are dynamically set. The given 'name' indicates the name of the |
paul@113 | 748 | function. The given 'instance_name' indicates the name of any separate |
paul@113 | 749 | instance of the function created to hold the defaults. |
paul@113 | 750 | |
paul@113 | 751 | Return a list of operations setting defaults on a function instance. |
paul@113 | 752 | """ |
paul@113 | 753 | |
paul@113 | 754 | function_name = self.get_object_path(name) |
paul@113 | 755 | function_defaults = self.importer.function_defaults.get(function_name) |
paul@113 | 756 | if not function_defaults: |
paul@113 | 757 | return None |
paul@113 | 758 | |
paul@113 | 759 | # Determine whether any unidentified defaults are involved. |
paul@113 | 760 | |
paul@113 | 761 | need_defaults = [argname for argname, default in function_defaults if default.has_kind("<var>")] |
paul@113 | 762 | if not need_defaults: |
paul@113 | 763 | return None |
paul@113 | 764 | |
paul@113 | 765 | # Where defaults are involved but cannot be identified, obtain a new |
paul@113 | 766 | # instance of the lambda and populate the defaults. |
paul@113 | 767 | |
paul@113 | 768 | defaults = [] |
paul@113 | 769 | |
paul@113 | 770 | # Join the original defaults with the inspected defaults. |
paul@113 | 771 | |
paul@113 | 772 | original_defaults = [(argname, default) for (argname, default) in compiler.ast.get_defaults(n) if default] |
paul@113 | 773 | |
paul@113 | 774 | for i, (original, inspected) in enumerate(map(None, original_defaults, function_defaults)): |
paul@113 | 775 | |
paul@113 | 776 | # Obtain any reference for the default. |
paul@113 | 777 | |
paul@113 | 778 | if original: |
paul@113 | 779 | argname, default = original |
paul@113 | 780 | name_ref = self.process_structure_node(default) |
paul@113 | 781 | elif inspected: |
paul@113 | 782 | argname, default = inspected |
paul@113 | 783 | name_ref = TrResolvedNameRef(argname, default) |
paul@113 | 784 | else: |
paul@113 | 785 | continue |
paul@113 | 786 | |
paul@113 | 787 | if name_ref: |
paul@149 | 788 | defaults.append("__SETDEFAULT(%s, %s, %s)" % (encode_path(instance_name), i, name_ref)) |
paul@113 | 789 | |
paul@113 | 790 | return defaults |
paul@113 | 791 | |
paul@113 | 792 | def process_if_node(self, n): |
paul@113 | 793 | |
paul@113 | 794 | """ |
paul@113 | 795 | Process the given "if" node 'n'. |
paul@113 | 796 | """ |
paul@113 | 797 | |
paul@113 | 798 | first = True |
paul@113 | 799 | for test, body in n.tests: |
paul@113 | 800 | test_ref = self.process_structure_node(test) |
paul@113 | 801 | self.start_if(first, test_ref) |
paul@113 | 802 | |
paul@113 | 803 | in_conditional = self.in_conditional |
paul@113 | 804 | self.in_conditional = True |
paul@113 | 805 | self.process_structure_node(body) |
paul@113 | 806 | self.in_conditional = in_conditional |
paul@113 | 807 | |
paul@113 | 808 | self.end_if() |
paul@113 | 809 | first = False |
paul@113 | 810 | |
paul@113 | 811 | if n.else_: |
paul@113 | 812 | self.start_else() |
paul@113 | 813 | self.process_structure_node(n.else_) |
paul@113 | 814 | self.end_else() |
paul@113 | 815 | |
paul@113 | 816 | def process_invocation_node(self, n): |
paul@113 | 817 | |
paul@113 | 818 | "Process the given invocation node 'n'." |
paul@113 | 819 | |
paul@113 | 820 | expr = self.process_structure_node(n.node) |
paul@113 | 821 | objpath = expr.get_origin() |
paul@118 | 822 | target = None |
paul@113 | 823 | |
paul@113 | 824 | # Obtain details of the callable. |
paul@113 | 825 | |
paul@113 | 826 | if objpath: |
paul@113 | 827 | parameters = self.importer.function_parameters.get(objpath) |
paul@118 | 828 | if expr.has_kind("<class>"): |
paul@118 | 829 | target = encode_instantiator_pointer(objpath) |
paul@149 | 830 | target_structure = encode_initialiser_pointer(objpath) |
paul@118 | 831 | elif expr.has_kind("<function>"): |
paul@118 | 832 | target = encode_function_pointer(objpath) |
paul@149 | 833 | target_structure = encode_path(objpath) |
paul@113 | 834 | else: |
paul@113 | 835 | parameters = None |
paul@113 | 836 | |
paul@113 | 837 | stages = [] |
paul@113 | 838 | |
paul@122 | 839 | # First, the invocation target is presented. |
paul@113 | 840 | |
paul@113 | 841 | stages.append("__tmp_target = %s" % expr) |
paul@122 | 842 | |
paul@122 | 843 | # Arguments are presented in a temporary frame array with any context |
paul@122 | 844 | # always being the first argument (although it may be set to null for |
paul@122 | 845 | # invocations where it would be unused). |
paul@122 | 846 | |
paul@122 | 847 | args = ["__CONTEXT_AS_VALUE(__tmp_target)"] |
paul@122 | 848 | args += [None] * (not parameters and len(n.args) or parameters and len(parameters) or 0) |
paul@122 | 849 | kwcodes = [] |
paul@122 | 850 | kwargs = [] |
paul@122 | 851 | |
paul@122 | 852 | for i, arg in enumerate(n.args): |
paul@122 | 853 | argexpr = self.process_structure_node(arg) |
paul@122 | 854 | |
paul@122 | 855 | # Store a keyword argument, either in the argument list or |
paul@122 | 856 | # in a separate keyword argument list for subsequent lookup. |
paul@122 | 857 | |
paul@122 | 858 | if isinstance(arg, compiler.ast.Keyword): |
paul@113 | 859 | |
paul@122 | 860 | # With knowledge of the target, store the keyword |
paul@122 | 861 | # argument directly. |
paul@122 | 862 | |
paul@122 | 863 | if parameters: |
paul@122 | 864 | argnum = parameters.index(arg.name) |
paul@122 | 865 | args[argnum+1] = str(argexpr) |
paul@122 | 866 | |
paul@122 | 867 | # Otherwise, store the details in a separate collection. |
paul@122 | 868 | |
paul@122 | 869 | else: |
paul@122 | 870 | kwargs.append(str(argexpr)) |
paul@122 | 871 | kwcodes.append("{%s, %s}" % ( |
paul@122 | 872 | encode_symbol("ppos", arg.name), |
paul@122 | 873 | encode_symbol("pcode", arg.name))) |
paul@122 | 874 | |
paul@122 | 875 | else: |
paul@122 | 876 | args[i+1] = str(argexpr) |
paul@113 | 877 | |
paul@113 | 878 | # Defaults are added to the frame where arguments are missing. |
paul@113 | 879 | |
paul@122 | 880 | if parameters: |
paul@122 | 881 | function_defaults = self.importer.function_defaults.get(objpath) |
paul@122 | 882 | if function_defaults: |
paul@122 | 883 | |
paul@122 | 884 | # Visit each default and set any missing arguments. |
paul@149 | 885 | # Use the target structure to obtain defaults, as opposed to the |
paul@149 | 886 | # actual function involved. |
paul@122 | 887 | |
paul@122 | 888 | for i, (argname, default) in enumerate(function_defaults): |
paul@122 | 889 | argnum = parameters.index(argname) |
paul@122 | 890 | if not args[argnum+1]: |
paul@149 | 891 | args[argnum+1] = "__GETDEFAULT(&%s, %d)" % (target_structure, i) |
paul@149 | 892 | |
paul@149 | 893 | # Encode the arguments. |
paul@122 | 894 | |
paul@122 | 895 | argstr = "__ARGS(%s)" % ", ".join(args) |
paul@122 | 896 | kwargstr = kwargs and ("__ARGS(%s)" % ", ".join(kwargs)) or "0" |
paul@122 | 897 | kwcodestr = kwcodes and ("__KWARGS(%s)" % ", ".join(kwcodes)) or "0" |
paul@122 | 898 | |
paul@122 | 899 | # The callable is then obtained. |
paul@113 | 900 | |
paul@118 | 901 | if target: |
paul@136 | 902 | callable = target |
paul@118 | 903 | |
paul@118 | 904 | elif self.always_callable: |
paul@138 | 905 | callable = "__load_via_object(__tmp_target.value, %s)" % \ |
paul@113 | 906 | encode_symbol("pos", "__fn__") |
paul@113 | 907 | else: |
paul@138 | 908 | callable = "__check_and_load_via_object(__tmp_target.value, %s, %s)" % ( |
paul@113 | 909 | encode_symbol("pos", "__fn__"), encode_symbol("code", "__fn__")) |
paul@113 | 910 | |
paul@122 | 911 | stages.append(callable) |
paul@122 | 912 | |
paul@122 | 913 | # With a known target, the function is obtained directly and called. |
paul@122 | 914 | |
paul@122 | 915 | if target: |
paul@136 | 916 | output = "(\n%s\n)(%s)" % (",\n".join(stages), argstr) |
paul@113 | 917 | |
paul@122 | 918 | # With unknown targets, the generic invocation function is applied to |
paul@122 | 919 | # the callable and argument collections. |
paul@113 | 920 | |
paul@122 | 921 | else: |
paul@122 | 922 | output = "__invoke(\n(\n%s\n),\n%d, %s, %s,\n%d, %s\n)" % ( |
paul@122 | 923 | ",\n".join(stages), |
paul@122 | 924 | len(kwargs), kwcodestr, kwargstr, |
paul@122 | 925 | len(args), argstr) |
paul@122 | 926 | |
paul@122 | 927 | return make_expression(output) |
paul@113 | 928 | |
paul@113 | 929 | def always_callable(self, refs): |
paul@113 | 930 | |
paul@113 | 931 | "Determine whether all 'refs' are callable." |
paul@113 | 932 | |
paul@113 | 933 | for ref in refs: |
paul@113 | 934 | if not ref.static(): |
paul@113 | 935 | return False |
paul@113 | 936 | else: |
paul@113 | 937 | origin = ref.final() |
paul@113 | 938 | if not self.importer.get_attribute(origin, "__fn__"): |
paul@113 | 939 | return False |
paul@113 | 940 | return True |
paul@113 | 941 | |
paul@113 | 942 | def need_default_arguments(self, objpath, nargs): |
paul@113 | 943 | |
paul@113 | 944 | """ |
paul@113 | 945 | Return whether any default arguments are needed when invoking the object |
paul@113 | 946 | given by 'objpath'. |
paul@113 | 947 | """ |
paul@113 | 948 | |
paul@113 | 949 | parameters = self.importer.function_parameters.get(objpath) |
paul@113 | 950 | return nargs < len(parameters) |
paul@113 | 951 | |
paul@113 | 952 | def process_lambda_node(self, n): |
paul@113 | 953 | |
paul@113 | 954 | "Process the given lambda node 'n'." |
paul@113 | 955 | |
paul@113 | 956 | name = self.get_lambda_name() |
paul@113 | 957 | function_name = self.get_object_path(name) |
paul@113 | 958 | |
paul@149 | 959 | defaults = self.process_function_defaults(n, name, "__tmp_result") |
paul@149 | 960 | |
paul@149 | 961 | # Without defaults, produce an attribute referring to the function. |
paul@149 | 962 | |
paul@113 | 963 | if not defaults: |
paul@149 | 964 | return make_expression("((__attr) {0, &%s})" % encode_path(function_name)) |
paul@149 | 965 | |
paul@149 | 966 | # With defaults, copy the function structure and set the defaults on the |
paul@149 | 967 | # copy. |
paul@149 | 968 | |
paul@113 | 969 | else: |
paul@113 | 970 | return make_expression("(__COPY(%s, __tmp), %s)" % (encode_path(function_name), ", ".join(defaults))) |
paul@113 | 971 | |
paul@113 | 972 | def process_logical_node(self, n): |
paul@113 | 973 | |
paul@141 | 974 | """ |
paul@141 | 975 | Process the given operator node 'n'. |
paul@141 | 976 | |
paul@141 | 977 | Convert ... to ... |
paul@141 | 978 | |
paul@141 | 979 | <a> and <b> |
paul@141 | 980 | (__tmp_result = <a>, !__BOOL(__tmp_result)) ? __tmp_result : <b> |
paul@141 | 981 | |
paul@141 | 982 | <a> or <b> |
paul@141 | 983 | (__tmp_result = <a>, __BOOL(__tmp_result)) ? __tmp_result : <b> |
paul@141 | 984 | """ |
paul@113 | 985 | |
paul@113 | 986 | if isinstance(n, compiler.ast.And): |
paul@141 | 987 | op = "!" |
paul@113 | 988 | else: |
paul@141 | 989 | op = "" |
paul@141 | 990 | |
paul@141 | 991 | results = [] |
paul@113 | 992 | |
paul@141 | 993 | for node in n.nodes[:-1]: |
paul@141 | 994 | expr = self.process_structure_node(node) |
paul@141 | 995 | results.append("(__tmp_result = %s, %s__BOOL(__tmp_result)) ? __tmp_result : " % (expr, op)) |
paul@113 | 996 | |
paul@141 | 997 | expr = self.process_structure_node(n.nodes[-1]) |
paul@141 | 998 | results.append(str(expr)) |
paul@141 | 999 | |
paul@141 | 1000 | return make_expression("(%s)" % "".join(results)) |
paul@113 | 1001 | |
paul@113 | 1002 | def process_name_node(self, n, expr=None): |
paul@113 | 1003 | |
paul@113 | 1004 | "Process the given name node 'n' with the optional assignment 'expr'." |
paul@113 | 1005 | |
paul@113 | 1006 | # Determine whether the name refers to a static external entity. |
paul@113 | 1007 | |
paul@113 | 1008 | if n.name in predefined_constants: |
paul@113 | 1009 | return PredefinedConstantRef(n.name) |
paul@113 | 1010 | |
paul@113 | 1011 | # Convert literal references. |
paul@113 | 1012 | |
paul@113 | 1013 | elif n.name.startswith("$L"): |
paul@113 | 1014 | literal_name = n.name[len("$L"):] |
paul@113 | 1015 | ref = self.importer.get_object("__builtins__.%s" % literal_name) |
paul@113 | 1016 | return TrResolvedNameRef(n.name, ref) |
paul@113 | 1017 | |
paul@113 | 1018 | # Convert operator function names to references. |
paul@113 | 1019 | |
paul@113 | 1020 | elif n.name.startswith("$op"): |
paul@136 | 1021 | ref = self.importer.get_module(self.name).special.get(n.name) |
paul@113 | 1022 | return TrResolvedNameRef(n.name, ref) |
paul@113 | 1023 | |
paul@113 | 1024 | # Get the appropriate name for the name reference, using the same method |
paul@113 | 1025 | # as in the inspector. |
paul@113 | 1026 | |
paul@113 | 1027 | path = self.get_object_path(n.name) |
paul@113 | 1028 | ref = self.importer.get_object(path) |
paul@113 | 1029 | name = self.get_name_for_tracking(n.name, ref and ref.final()) |
paul@113 | 1030 | |
paul@113 | 1031 | # Get the static identity of the name. |
paul@113 | 1032 | |
paul@113 | 1033 | ref = self.importer.identify(path) |
paul@113 | 1034 | |
paul@113 | 1035 | # Obtain any resolved names for non-assignment names. |
paul@113 | 1036 | |
paul@113 | 1037 | if not expr and not ref and self.in_function: |
paul@113 | 1038 | locals = self.importer.function_locals.get(self.get_namespace_path()) |
paul@113 | 1039 | ref = locals and locals.get(n.name) |
paul@113 | 1040 | |
paul@113 | 1041 | # Qualified names are used for resolved static references or for |
paul@113 | 1042 | # static namespace members. The reference should be configured to return |
paul@113 | 1043 | # such names. |
paul@113 | 1044 | |
paul@113 | 1045 | return TrResolvedNameRef(name, ref, expr=expr) |
paul@113 | 1046 | |
paul@113 | 1047 | def process_not_node(self, n): |
paul@113 | 1048 | |
paul@113 | 1049 | "Process the given operator node 'n'." |
paul@113 | 1050 | |
paul@144 | 1051 | return make_expression("(__BOOL(%s) ? %s : %s)" % |
paul@149 | 1052 | (self.process_structure_node(n.expr), PredefinedConstantRef("False"), |
paul@149 | 1053 | PredefinedConstantRef("True"))) |
paul@144 | 1054 | |
paul@144 | 1055 | def process_raise_node(self, n): |
paul@144 | 1056 | |
paul@144 | 1057 | "Process the given raise node 'n'." |
paul@144 | 1058 | |
paul@144 | 1059 | # NOTE: Determine which raise statement variants should be permitted. |
paul@144 | 1060 | |
paul@144 | 1061 | self.writestmt("__Raise(%s);" % self.process_structure_node(n.expr1)) |
paul@144 | 1062 | |
paul@144 | 1063 | def process_return_node(self, n): |
paul@144 | 1064 | |
paul@144 | 1065 | "Process the given return node 'n'." |
paul@144 | 1066 | |
paul@144 | 1067 | expr = self.process_structure_node(n.value) or PredefinedConstantRef("None") |
paul@144 | 1068 | if self.in_try_finally: |
paul@144 | 1069 | self.writestmt("__Return(%s);" % expr) |
paul@144 | 1070 | else: |
paul@144 | 1071 | self.writestmt("return %s;" % expr) |
paul@144 | 1072 | |
paul@144 | 1073 | return ReturnRef() |
paul@113 | 1074 | |
paul@113 | 1075 | def process_try_node(self, n): |
paul@113 | 1076 | |
paul@113 | 1077 | """ |
paul@113 | 1078 | Process the given "try...except" node 'n'. |
paul@113 | 1079 | """ |
paul@113 | 1080 | |
paul@144 | 1081 | # Use macros to implement exception handling. |
paul@113 | 1082 | |
paul@144 | 1083 | self.writestmt("__Try") |
paul@113 | 1084 | self.writeline("{") |
paul@113 | 1085 | self.indent += 1 |
paul@113 | 1086 | self.process_structure_node(n.body) |
paul@144 | 1087 | |
paul@144 | 1088 | # Put the else statement in another try block that handles any raised |
paul@144 | 1089 | # exceptions and converts them to exceptions that will not be handled by |
paul@144 | 1090 | # the main handling block. |
paul@144 | 1091 | |
paul@144 | 1092 | if n.else_: |
paul@144 | 1093 | self.writestmt("__Try") |
paul@144 | 1094 | self.writeline("{") |
paul@144 | 1095 | self.indent += 1 |
paul@144 | 1096 | self.process_structure_node(n.else_) |
paul@144 | 1097 | self.indent -= 1 |
paul@144 | 1098 | self.writeline("}") |
paul@144 | 1099 | self.writeline("__Catch (__tmp_exc)") |
paul@144 | 1100 | self.writeline("{") |
paul@144 | 1101 | self.indent += 1 |
paul@144 | 1102 | self.writeline("if (__tmp_exc.raising) __RaiseElse(__tmp_exc.arg);") |
paul@144 | 1103 | self.indent -= 1 |
paul@144 | 1104 | self.writeline("}") |
paul@144 | 1105 | |
paul@144 | 1106 | # Complete the try block and enter the finally block, if appropriate. |
paul@144 | 1107 | |
paul@144 | 1108 | if self.in_try_finally: |
paul@144 | 1109 | self.writestmt("__Complete;") |
paul@144 | 1110 | |
paul@113 | 1111 | self.indent -= 1 |
paul@113 | 1112 | self.writeline("}") |
paul@113 | 1113 | |
paul@144 | 1114 | # Handlers are tests within a common handler block. |
paul@144 | 1115 | |
paul@144 | 1116 | self.writeline("__Catch (__tmp_exc)") |
paul@144 | 1117 | self.writeline("{") |
paul@144 | 1118 | self.indent += 1 |
paul@144 | 1119 | |
paul@144 | 1120 | # Handle exceptions in else blocks converted to __RaiseElse, converting |
paul@144 | 1121 | # them back to normal exceptions. |
paul@144 | 1122 | |
paul@144 | 1123 | else_str = "" |
paul@144 | 1124 | |
paul@144 | 1125 | if n.else_: |
paul@144 | 1126 | self.writeline("if (__tmp_exc.raising_else) __Raise(__tmp_exc.arg);") |
paul@144 | 1127 | else_str = "else " |
paul@144 | 1128 | |
paul@144 | 1129 | # Handle the completion of try blocks or the execution of return |
paul@144 | 1130 | # statements where finally blocks apply. |
paul@144 | 1131 | |
paul@144 | 1132 | if self.in_try_finally: |
paul@144 | 1133 | self.writeline("%sif (__tmp_exc.completing) __Throw(__tmp_exc);" % else_str) |
paul@144 | 1134 | else_str = "else " |
paul@144 | 1135 | |
paul@144 | 1136 | # Exception handling. |
paul@144 | 1137 | |
paul@113 | 1138 | for name, var, handler in n.handlers: |
paul@144 | 1139 | |
paul@144 | 1140 | # Test for specific exceptions. |
paul@144 | 1141 | |
paul@113 | 1142 | if name is not None: |
paul@113 | 1143 | name_ref = self.process_structure_node(name) |
paul@144 | 1144 | self.writeline("%sif (__BOOL(__fn_native__isinstance((__attr[]) {__tmp_exc.arg, %s})))" % (else_str, name_ref)) |
paul@144 | 1145 | else: |
paul@144 | 1146 | self.writeline("%sif (1)" % else_str) |
paul@144 | 1147 | else_str = "else " |
paul@113 | 1148 | |
paul@113 | 1149 | self.writeline("{") |
paul@113 | 1150 | self.indent += 1 |
paul@113 | 1151 | |
paul@113 | 1152 | # Establish the local for the handler. |
paul@113 | 1153 | |
paul@113 | 1154 | if var is not None: |
paul@144 | 1155 | var_ref = self.process_name_node(var, make_expression("__tmp_exc")) |
paul@113 | 1156 | |
paul@113 | 1157 | if handler is not None: |
paul@113 | 1158 | self.process_structure_node(handler) |
paul@113 | 1159 | |
paul@113 | 1160 | self.indent -= 1 |
paul@113 | 1161 | self.writeline("}") |
paul@113 | 1162 | |
paul@144 | 1163 | # Re-raise unhandled exceptions. |
paul@144 | 1164 | |
paul@144 | 1165 | self.writeline("%s__Throw(__tmp_exc);" % else_str) |
paul@144 | 1166 | |
paul@144 | 1167 | # End the handler block. |
paul@144 | 1168 | |
paul@144 | 1169 | self.indent -= 1 |
paul@144 | 1170 | self.writeline("}") |
paul@113 | 1171 | |
paul@113 | 1172 | def process_try_finally_node(self, n): |
paul@113 | 1173 | |
paul@113 | 1174 | """ |
paul@113 | 1175 | Process the given "try...finally" node 'n'. |
paul@113 | 1176 | """ |
paul@113 | 1177 | |
paul@144 | 1178 | in_try_finally = self.in_try_finally |
paul@144 | 1179 | self.in_try_finally = True |
paul@113 | 1180 | |
paul@144 | 1181 | # Use macros to implement exception handling. |
paul@144 | 1182 | |
paul@144 | 1183 | self.writestmt("__Try") |
paul@113 | 1184 | self.writeline("{") |
paul@113 | 1185 | self.indent += 1 |
paul@113 | 1186 | self.process_structure_node(n.body) |
paul@113 | 1187 | self.indent -= 1 |
paul@113 | 1188 | self.writeline("}") |
paul@144 | 1189 | |
paul@144 | 1190 | self.in_try_finally = in_try_finally |
paul@144 | 1191 | |
paul@144 | 1192 | # Finally clauses handle special exceptions. |
paul@144 | 1193 | |
paul@144 | 1194 | self.writeline("__Catch (__tmp_exc)") |
paul@113 | 1195 | self.writeline("{") |
paul@113 | 1196 | self.indent += 1 |
paul@113 | 1197 | self.process_structure_node(n.final) |
paul@144 | 1198 | |
paul@144 | 1199 | # Test for the completion of a try block. |
paul@144 | 1200 | |
paul@144 | 1201 | self.writestmt("if (__tmp_exc.completing)") |
paul@144 | 1202 | self.writeline("{") |
paul@144 | 1203 | self.indent += 1 |
paul@144 | 1204 | self.writeline("if (!__ISNULL(__tmp_exc.arg)) return __tmp_exc.arg;") |
paul@144 | 1205 | self.indent -= 1 |
paul@144 | 1206 | self.writeline("}") |
paul@144 | 1207 | self.writeline("else __Throw(__tmp_exc);") |
paul@144 | 1208 | |
paul@113 | 1209 | self.indent -= 1 |
paul@113 | 1210 | self.writeline("}") |
paul@113 | 1211 | |
paul@113 | 1212 | def process_while_node(self, n): |
paul@113 | 1213 | |
paul@113 | 1214 | "Process the given while node 'n'." |
paul@113 | 1215 | |
paul@113 | 1216 | self.writeline("while (1)") |
paul@113 | 1217 | self.writeline("{") |
paul@113 | 1218 | self.indent += 1 |
paul@113 | 1219 | test = self.process_structure_node(n.test) |
paul@113 | 1220 | |
paul@113 | 1221 | # Emit the loop termination condition unless "while <true value>" is |
paul@113 | 1222 | # indicated. |
paul@113 | 1223 | |
paul@113 | 1224 | if not (isinstance(test, PredefinedConstantRef) and test.value): |
paul@113 | 1225 | |
paul@113 | 1226 | # NOTE: This needs to evaluate whether the operand is true or false |
paul@113 | 1227 | # NOTE: according to Python rules. |
paul@113 | 1228 | |
paul@144 | 1229 | self.writeline("if (!__BOOL(%s))" % test) |
paul@113 | 1230 | self.writeline("{") |
paul@113 | 1231 | self.indent += 1 |
paul@113 | 1232 | if n.else_: |
paul@113 | 1233 | self.process_structure_node(n.else_) |
paul@128 | 1234 | self.writestmt("break;") |
paul@113 | 1235 | self.indent -= 1 |
paul@113 | 1236 | self.writeline("}") |
paul@113 | 1237 | |
paul@113 | 1238 | in_conditional = self.in_conditional |
paul@113 | 1239 | self.in_conditional = True |
paul@113 | 1240 | self.process_structure_node(n.body) |
paul@113 | 1241 | self.in_conditional = in_conditional |
paul@113 | 1242 | |
paul@113 | 1243 | self.indent -= 1 |
paul@113 | 1244 | self.writeline("}") |
paul@113 | 1245 | |
paul@113 | 1246 | # Output generation. |
paul@113 | 1247 | |
paul@128 | 1248 | def start_output(self): |
paul@128 | 1249 | print >>self.out, """\ |
paul@128 | 1250 | #include "types.h" |
paul@144 | 1251 | #include "exceptions.h" |
paul@128 | 1252 | #include "ops.h" |
paul@128 | 1253 | #include "progconsts.h" |
paul@128 | 1254 | #include "progops.h" |
paul@128 | 1255 | #include "progtypes.h" |
paul@137 | 1256 | #include "main.h" |
paul@128 | 1257 | """ |
paul@128 | 1258 | |
paul@113 | 1259 | def start_module(self): |
paul@113 | 1260 | print >>self.out, "void __main_%s()" % encode_path(self.name) |
paul@113 | 1261 | print >>self.out, "{" |
paul@113 | 1262 | self.indent += 1 |
paul@149 | 1263 | self.write_temporaries() |
paul@113 | 1264 | |
paul@113 | 1265 | def end_module(self): |
paul@113 | 1266 | self.indent -= 1 |
paul@144 | 1267 | print >>self.out, "}" |
paul@113 | 1268 | |
paul@113 | 1269 | def start_function(self, name): |
paul@113 | 1270 | print >>self.out, "__attr %s(__attr __args[])" % encode_function_pointer(name) |
paul@113 | 1271 | print >>self.out, "{" |
paul@113 | 1272 | self.indent += 1 |
paul@149 | 1273 | self.write_temporaries() |
paul@113 | 1274 | |
paul@113 | 1275 | # Obtain local names from parameters. |
paul@113 | 1276 | |
paul@113 | 1277 | parameters = self.importer.function_parameters[name] |
paul@144 | 1278 | locals = self.importer.function_locals[name].keys() |
paul@113 | 1279 | names = [] |
paul@113 | 1280 | |
paul@113 | 1281 | for n in locals: |
paul@113 | 1282 | |
paul@113 | 1283 | # Filter out special names and parameters. Note that self is a local |
paul@113 | 1284 | # regardless of whether it originally appeared in the parameters or |
paul@113 | 1285 | # not. |
paul@113 | 1286 | |
paul@113 | 1287 | if n.startswith("$l") or n in parameters or n == "self": |
paul@113 | 1288 | continue |
paul@113 | 1289 | names.append(encode_path(n)) |
paul@113 | 1290 | |
paul@113 | 1291 | # Emit required local names. |
paul@113 | 1292 | |
paul@113 | 1293 | if names: |
paul@113 | 1294 | names.sort() |
paul@113 | 1295 | self.writeline("__attr %s;" % ", ".join(names)) |
paul@113 | 1296 | |
paul@144 | 1297 | self.write_parameters(name, True) |
paul@144 | 1298 | |
paul@144 | 1299 | def end_function(self, name): |
paul@144 | 1300 | self.write_parameters(name, False) |
paul@144 | 1301 | self.indent -= 1 |
paul@144 | 1302 | print >>self.out, "}" |
paul@144 | 1303 | print >>self.out |
paul@144 | 1304 | |
paul@149 | 1305 | def write_temporaries(self): |
paul@149 | 1306 | self.writeline("__ref __tmp_context, __tmp_value;") |
paul@149 | 1307 | self.writeline("__attr __tmp_target, __tmp_result;") |
paul@149 | 1308 | self.writeline("__exc __tmp_exc;") |
paul@149 | 1309 | |
paul@144 | 1310 | def write_parameters(self, name, define=True): |
paul@144 | 1311 | parameters = self.importer.function_parameters[name] |
paul@144 | 1312 | |
paul@113 | 1313 | # Generate any self reference. |
paul@113 | 1314 | |
paul@113 | 1315 | if self.in_method(name): |
paul@144 | 1316 | if define: |
paul@144 | 1317 | self.writeline("#define self (__args[0])") |
paul@144 | 1318 | else: |
paul@144 | 1319 | self.writeline("#undef self") |
paul@113 | 1320 | |
paul@113 | 1321 | # Generate aliases for the parameters. |
paul@113 | 1322 | |
paul@113 | 1323 | for i, parameter in enumerate(parameters): |
paul@144 | 1324 | if define: |
paul@144 | 1325 | self.writeline("#define %s (__args[%d])" % (encode_path(parameter), i+1)) |
paul@144 | 1326 | else: |
paul@144 | 1327 | self.writeline("#undef %s" % encode_path(parameter)) |
paul@113 | 1328 | |
paul@113 | 1329 | def start_if(self, first, test_ref): |
paul@144 | 1330 | self.writestmt("%sif (__BOOL(%s))" % (not first and "else " or "", test_ref)) |
paul@113 | 1331 | self.writeline("{") |
paul@113 | 1332 | self.indent += 1 |
paul@113 | 1333 | |
paul@113 | 1334 | def end_if(self): |
paul@113 | 1335 | self.indent -= 1 |
paul@113 | 1336 | self.writeline("}") |
paul@113 | 1337 | |
paul@113 | 1338 | def start_else(self): |
paul@113 | 1339 | self.writeline("else") |
paul@113 | 1340 | self.writeline("{") |
paul@113 | 1341 | self.indent += 1 |
paul@113 | 1342 | |
paul@113 | 1343 | def end_else(self): |
paul@113 | 1344 | self.indent -= 1 |
paul@113 | 1345 | self.writeline("}") |
paul@113 | 1346 | |
paul@113 | 1347 | def statement(self, expr): |
paul@113 | 1348 | # NOTE: Should never be None. |
paul@113 | 1349 | if not expr: |
paul@128 | 1350 | self.writestmt("...;") |
paul@113 | 1351 | s = str(expr) |
paul@113 | 1352 | if s: |
paul@128 | 1353 | self.writestmt("%s;" % s) |
paul@113 | 1354 | |
paul@113 | 1355 | def statements(self, results): |
paul@113 | 1356 | for result in results: |
paul@113 | 1357 | self.statement(result) |
paul@113 | 1358 | |
paul@113 | 1359 | def pad(self, extra=0): |
paul@113 | 1360 | return (self.indent + extra) * self.tabstop |
paul@113 | 1361 | |
paul@113 | 1362 | def indenttext(self, s, levels): |
paul@116 | 1363 | lines = s.split("\n") |
paul@116 | 1364 | out = [lines[0]] |
paul@116 | 1365 | for line in lines[1:]: |
paul@116 | 1366 | out.append(levels * self.tabstop + line) |
paul@116 | 1367 | if line.endswith("("): |
paul@116 | 1368 | levels += 1 |
paul@122 | 1369 | elif line.startswith(")"): |
paul@116 | 1370 | levels -= 1 |
paul@116 | 1371 | return "\n".join(out) |
paul@113 | 1372 | |
paul@113 | 1373 | def writeline(self, s): |
paul@113 | 1374 | print >>self.out, "%s%s" % (self.pad(), self.indenttext(s, self.indent + 1)) |
paul@113 | 1375 | |
paul@128 | 1376 | def writestmt(self, s): |
paul@128 | 1377 | print >>self.out |
paul@128 | 1378 | self.writeline(s) |
paul@128 | 1379 | |
paul@113 | 1380 | def write_comment(self, s): |
paul@128 | 1381 | self.writestmt("/* %s */" % s) |
paul@113 | 1382 | |
paul@113 | 1383 | # vim: tabstop=4 expandtab shiftwidth=4 |