Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
print("\n--------MEDIUM-------- (ok)\n")
x = ast.dump(my_ast, annotate_fields=True, include_attributes=False)
print(x)
print("\n--------SHORT-------- (view-only)\n")
x = ast.dump(my_ast, annotate_fields=False, include_attributes=False)
print(x)
print("")
if do_exec: exec(expr)
exit(0)
try:
inline_ast = "set in execfile:"
if sys.version < '3':execfile(ast_file)
else: exec(open(ast_file).read())
try:
source = codegen.to_source(inline_ast)
print(source) # => CODE
except Exception as ex:
print(ex)
my_ast = ast.fix_missing_locations(inline_ast)
code = compile(inline_ast, "out/inline", 'exec')
# if do_exec:
exec(code)
except Exception as e:
raise
def visit(self, node, abort=astor.codegen.SourceGenerator.abort_visit):
if anno.hasanno(node, 'comment'):
comment = anno.getanno(node, 'comment')
# Preprocess the comment to fit to maximum line width of 80 characters
linewidth = 78
if comment['location'] in ('above', 'below'):
comment['text'] = comment['text'][:linewidth]
n_newlines = 1 if self.new_indentation else 2
if comment['location'] == 'above':
self.result.append('\n' * n_newlines)
self.result.append(self.indent_with * self.indentation)
self.result.append('# %s' % comment['text'])
super(SourceWithCommentGenerator, self).visit(node)
elif comment['location'] == 'below':
super(SourceWithCommentGenerator, self).visit(node)
self.result.append('\n')
self.result.append(self.indent_with * self.indentation)
def ast_to_source(node, indentation=' '):
"""Return the source code of given AST."""
if isinstance(node, gast.AST):
node = gast.gast_to_ast(node)
generator = astor.codegen.SourceGenerator(indentation, False,
astor.string_repr.pretty_string)
generator.visit(node)
generator.result.append('\n')
# In some versions of Python, literals may appear as actual values. This
# ensures everything is string.
code = map(str, generator.result)
return astor.source_repr.pretty_source(code).lstrip()
"""Moving between source code and AST."""
from __future__ import absolute_import
import inspect
import textwrap
import astor
import gast
from tangent import annotations as anno
class TangentParseError(SyntaxError):
pass
class SourceWithCommentGenerator(astor.codegen.SourceGenerator):
"""Source code generator that outputs comments."""
def __init__(self, *args, **kwargs):
super(SourceWithCommentGenerator, self).__init__(*args, **kwargs)
self.new_indentation = True
def body(self, statements):
self.new_indentation = True
super(SourceWithCommentGenerator, self).body(statements)
def visit(self, node, abort=astor.codegen.SourceGenerator.abort_visit):
if anno.hasanno(node, 'comment'):
comment = anno.getanno(node, 'comment')
# Preprocess the comment to fit to maximum line width of 80 characters
linewidth = 78
if comment['location'] in ('above', 'below'):
if e.filename is None:
e.filename = filename
exc_info = sys.exc_info()
if exc_info:
self.handle_exception(exc_info, string, tb_override=None)
if self.debug:
import ast
print(ast.dump(code, True, True))
try:
import astor
print(astor.codegen.to_source(code))
except ImportError:
print("Not reversing AST to source as astor was not installed")
runtime = self.runtime()
runtime.loader = self
glob = _new_globals(runtime)
compiled = compile(code, filename, 'exec')
glob['__TK_template_info__'] = TemplateInfo(filename, gen.lnotab_info())
exec(compiled, glob, glob)
template_func = glob['__TK__binder']
return Template(template_func)
def _get_ast(self):
return ast.Return(self.expression._get_ast())
if __name__ == '__main__':
forri = For(Name('a'), [ 1, 2, 3 ])
forri.body += Name('print')(Name('a'))
iffi = If(True)
iffi.body += forri
tree = iffi._get_ast()
print(ast.dump(tree))
import astor
print(astor.codegen.to_source(tree))