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