Ejemplo n.º 1
0
def translate(path_or_text, initial_indent=0):
    """This performs the translation from Python to Diet Python. It
	takes in Python code (assuming the string to be a file path, falling
	back to treating it as Python code if it is not a valid path) and
	emits Diet Python code."""
    # See if the given string is a valid path
    if os.path.exists(path_or_text):
        # If so then open it and read the file contents into in_text
        infile = open(path_or_text, "r")
        in_text = "\n".join([line for line in infile.readlines()])
        infile.close()
        # Otherwise take the string contents to be in_text
    else:
        in_text = path_or_text

        # Wrap in try/except to give understandable error messages (PyMeta's
        # are full of obscure implementation details)
    try:
        # Get an Abstract Syntax Tree for the contents of in_text
        tree = parse(in_text)

        # Transform the Python AST into a Diet Python AST
        diet_tree = apply(tree)
        # print str(tree)
        # print str(diet_tree)

        # Generate (Diet) Python code to match the transformed tree
        from python_rewriter.base import grammar

        matcher = grammar([diet_tree])
        diet_code, err = matcher.apply("thing", initial_indent)

        # print str(tree)
        # print
        # print str(diet_tree)
        # print

        return diet_code

    except Exception, e:
        sys.stderr.write(str(e) + "\n")
        sys.stderr.write("Unable to translate.\n")
        sys.exit(1)
Ejemplo n.º 2
0
def translate(path_or_text, initial_indent=0):
    """This performs the translation from Python to Diet Python. It
	takes in Python code (assuming the string to be a file path, falling
	back to treating it as Python code if it is not a valid path) and
	emits Diet Python code."""
    # See if the given string is a valid path
    if os.path.exists(path_or_text):
        # If so then open it and read the file contents into in_text
        infile = open(path_or_text, 'r')
        in_text = '\n'.join([line for line in infile.readlines()])
        infile.close()
    # Otherwise take the string contents to be in_text
    else:
        in_text = path_or_text

    # Wrap in try/except to give understandable error messages (PyMeta's
    # are full of obscure implementation details)
    try:
        # Get an Abstract Syntax Tree for the contents of in_text
        tree = parse(in_text)

        # Transform the Python AST into a Diet Python AST
        diet_tree = apply(tree)
        #print str(tree)
        #print str(diet_tree)

        # Generate (Diet) Python code to match the transformed tree
        from python_rewriter.base import grammar
        matcher = grammar([diet_tree])
        diet_code, err = matcher.apply('thing', initial_indent)

        #print str(tree)
        #print
        #print str(diet_tree)
        #print

        return diet_code

    except Exception, e:
        sys.stderr.write(str(e) + '\n')
        sys.stderr.write('Unable to translate.\n')
        sys.exit(1)
Ejemplo n.º 3
0
def annotate(path_or_text, initial_indent=0):
	"""This performs the translation from annotated Python to normal
	Python. It takes in annotated Python code (assuming the string to be
	a file path, falling back to treating it as raw code if it is not a
	valid path) and emits Python code."""
	# See if the given string is a valid path
	if os.path.exists(path_or_text):
		# If so then open it and read the file contents into in_text
		infile = open(path_or_text, 'r')
		in_text = '\n'.join([line for line in infile.readlines()])
		infile.close()
	# Otherwise take the string contents to be in_text
	else:
		in_text = path_or_text

	# Wrap in try/except to give understandable error messages (PyMeta's
	# are full of obscure implementation details)
	try:
		# Get an Abstract Syntax Tree for the contents of in_text
		tree = parse(in_text)

		# Transform the Python AST into a Diet Python AST
		annotated_tree = tree.ann()

		#print str(tree)
		#print str(diet_tree)

		# Generate (Diet) Python code to match the transformed tree
		annotated_code = annotated_tree.rec(initial_indent)

		print str(tree)
		print
		print str(annotated_tree)
		print

		print annotated_code

	except Exception, e:
		sys.stderr.write(str(e)+'\n')
		sys.stderr.write('Unable to annotate.\n')
		sys.exit(1)
Ejemplo n.º 4
0
            type({}),
            type(None),
            type(True),
            type(False),
            type(Ellipsis),
            type(1)
    ]:
        return list
    else:
        to_return = []
        for lst in map(get_units, tree.asList()):
            to_return = to_return + lst
        return list + to_return


tree = parse(''.join(open('reasoner.py', 'r').readlines()))
print str(tree)
print '#########################'
print str(get_units(tree, []))

#def add(arg):
#	"""Runs transformations on the argument. If the argument has a trans
#	method, that is run; if it is a list, apply is mapped to the list;
#	if it is a "type" (None, str, etc.) then that is returned unchanged.
#	"""
#	if type(arg) in [type('string'), type(0), type(None)]:
#		return arg
#	elif type(arg) == type([0,1]):
#		return map(apply, arg)
#	elif type(arg) == type((0,1)):
#		return tuple(map(apply, arg))
Ejemplo n.º 5
0
	(functions, classes, modules, etc.)."""
	if tree.__class__ in [Function, Class, Module]:
		to_return = []
		for lst in map(get_units, tree.asList()):
			to_return = to_return + lst
		return list+[tree]+to_return
	elif type(tree) in [type(''), type((1,2,3)), type([]), type({}),
		type(None), type(True), type(False), type(Ellipsis), type(1)]:
		return list
	else:
		to_return = []
		for lst in map(get_units, tree.asList()):
			to_return = to_return + lst
		return list+to_return

tree = parse(''.join(open('reasoner.py', 'r').readlines()))
print str(tree)
print '#########################'
print str(get_units(tree, []))

#def add(arg):
#	"""Runs transformations on the argument. If the argument has a trans
#	method, that is run; if it is a list, apply is mapped to the list;
#	if it is a "type" (None, str, etc.) then that is returned unchanged.
#	"""
#	if type(arg) in [type('string'), type(0), type(None)]:
#		return arg
#	elif type(arg) == type([0,1]):
#		return map(apply, arg)
#	elif type(arg) == type((0,1)):
#		return tuple(map(apply, arg))