Return the source code of given AST. Args: node: The code to compile, as an AST object. indentation: The string to use for indentation. include_encoding_marker: Bool, thether to include a comment on the first line to explicitly specify UTF-8 encoding. Returns: code: The s
(node, indentation=' ', include_encoding_marker=True)
| 38 | |
| 39 | |
| 40 | def ast_to_source(node, indentation=' ', include_encoding_marker=True): |
| 41 | """Return the source code of given AST. |
| 42 | |
| 43 | Args: |
| 44 | node: The code to compile, as an AST object. |
| 45 | indentation: The string to use for indentation. |
| 46 | include_encoding_marker: Bool, thether to include a comment on the first |
| 47 | line to explicitly specify UTF-8 encoding. |
| 48 | |
| 49 | Returns: |
| 50 | code: The source code generated from the AST object |
| 51 | source_mapping: A mapping between the user and AutoGraph generated code. |
| 52 | """ |
| 53 | if not isinstance(node, (list, tuple)): |
| 54 | node = (node,) |
| 55 | generator = astor.code_gen.SourceGenerator(indentation, False, |
| 56 | astor.string_repr.pretty_string) |
| 57 | |
| 58 | for n in node: |
| 59 | if isinstance(n, gast.AST): |
| 60 | n = gast.gast_to_ast(n) |
| 61 | generator.visit(n) |
| 62 | generator.result.append('\n') |
| 63 | |
| 64 | # In some versions of Python, literals may appear as actual values. This |
| 65 | # ensures everything is string. |
| 66 | code = ''.join(map(str, generator.result)) |
| 67 | |
| 68 | # Strip leading blank lines. |
| 69 | code_lines = code.split('\n') |
| 70 | trimmed_code_lines = [] |
| 71 | for l in code_lines: |
| 72 | if l.rstrip() or trimmed_code_lines: |
| 73 | trimmed_code_lines.append(l) |
| 74 | code = '\n'.join(trimmed_code_lines) |
| 75 | |
| 76 | # Work around the reference cycle generated by astor. |
| 77 | # See https://github.com/berkerpeksag/astor/blob/55dd323f7d8d696610c703c0296763c567685c31/astor/code_gen.py#L162 # pylint:disable=line-too-long |
| 78 | # Reference cycles are quite disliked by TensorFlow's tests. |
| 79 | if hasattr(generator, 'write'): |
| 80 | generator.write = None |
| 81 | del generator |
| 82 | |
| 83 | if include_encoding_marker: |
| 84 | code = '# coding=utf-8\n' + code |
| 85 | |
| 86 | return code |
| 87 | |
| 88 | |
| 89 | def source_to_entity(source, delete_on_exit): |
no test coverage detected