2012-09-13 15:27:34 +00:00
|
|
|
# mako/ast.py
|
2016-12-16 11:59:19 +00:00
|
|
|
# Copyright (C) 2006-2016 the Mako authors and contributors <see AUTHORS file>
|
2012-09-13 15:27:34 +00:00
|
|
|
#
|
|
|
|
# This module is part of Mako and is released under
|
|
|
|
# the MIT License: http://www.opensource.org/licenses/mit-license.php
|
|
|
|
|
2016-12-16 11:59:19 +00:00
|
|
|
"""utilities for analyzing expressions and blocks of Python
|
2012-09-13 15:27:34 +00:00
|
|
|
code, as well as generating Python from AST nodes"""
|
|
|
|
|
2016-12-16 11:59:19 +00:00
|
|
|
from mako import exceptions, pyparser, compat
|
2012-09-13 15:27:34 +00:00
|
|
|
import re
|
|
|
|
|
2016-12-16 11:59:19 +00:00
|
|
|
|
2012-09-13 15:27:34 +00:00
|
|
|
class PythonCode(object):
|
2016-12-16 11:59:19 +00:00
|
|
|
|
2012-09-13 15:27:34 +00:00
|
|
|
"""represents information about a string containing Python code"""
|
2016-12-16 11:59:19 +00:00
|
|
|
|
2012-09-13 15:27:34 +00:00
|
|
|
def __init__(self, code, **exception_kwargs):
|
|
|
|
self.code = code
|
2016-12-16 11:59:19 +00:00
|
|
|
|
|
|
|
# represents all identifiers which are assigned to at some point in
|
|
|
|
# the code
|
2012-09-13 15:27:34 +00:00
|
|
|
self.declared_identifiers = set()
|
2016-12-16 11:59:19 +00:00
|
|
|
|
|
|
|
# represents all identifiers which are referenced before their
|
|
|
|
# assignment, if any
|
2012-09-13 15:27:34 +00:00
|
|
|
self.undeclared_identifiers = set()
|
|
|
|
|
2016-12-16 11:59:19 +00:00
|
|
|
# note that an identifier can be in both the undeclared and declared
|
|
|
|
# lists.
|
|
|
|
|
|
|
|
# using AST to parse instead of using code.co_varnames,
|
2012-09-13 15:27:34 +00:00
|
|
|
# code.co_names has several advantages:
|
2016-12-16 11:59:19 +00:00
|
|
|
# - we can locate an identifier as "undeclared" even if
|
2012-09-13 15:27:34 +00:00
|
|
|
# its declared later in the same block of code
|
2016-12-16 11:59:19 +00:00
|
|
|
# - AST is less likely to break with version changes
|
2012-09-13 15:27:34 +00:00
|
|
|
# (for example, the behavior of co_names changed a little bit
|
|
|
|
# in python version 2.5)
|
2016-12-16 11:59:19 +00:00
|
|
|
if isinstance(code, compat.string_types):
|
2012-09-13 15:27:34 +00:00
|
|
|
expr = pyparser.parse(code.lstrip(), "exec", **exception_kwargs)
|
|
|
|
else:
|
|
|
|
expr = code
|
|
|
|
|
|
|
|
f = pyparser.FindIdentifiers(self, **exception_kwargs)
|
|
|
|
f.visit(expr)
|
|
|
|
|
2016-12-16 11:59:19 +00:00
|
|
|
|
2012-09-13 15:27:34 +00:00
|
|
|
class ArgumentList(object):
|
2016-12-16 11:59:19 +00:00
|
|
|
|
2012-09-13 15:27:34 +00:00
|
|
|
"""parses a fragment of code as a comma-separated list of expressions"""
|
2016-12-16 11:59:19 +00:00
|
|
|
|
2012-09-13 15:27:34 +00:00
|
|
|
def __init__(self, code, **exception_kwargs):
|
|
|
|
self.codeargs = []
|
|
|
|
self.args = []
|
|
|
|
self.declared_identifiers = set()
|
|
|
|
self.undeclared_identifiers = set()
|
2016-12-16 11:59:19 +00:00
|
|
|
if isinstance(code, compat.string_types):
|
2012-09-13 15:27:34 +00:00
|
|
|
if re.match(r"\S", code) and not re.match(r",\s*$", code):
|
|
|
|
# if theres text and no trailing comma, insure its parsed
|
|
|
|
# as a tuple by adding a trailing comma
|
2016-12-16 11:59:19 +00:00
|
|
|
code += ","
|
2012-09-13 15:27:34 +00:00
|
|
|
expr = pyparser.parse(code, "exec", **exception_kwargs)
|
|
|
|
else:
|
|
|
|
expr = code
|
|
|
|
|
|
|
|
f = pyparser.FindTuple(self, PythonCode, **exception_kwargs)
|
|
|
|
f.visit(expr)
|
2016-12-16 11:59:19 +00:00
|
|
|
|
|
|
|
|
2012-09-13 15:27:34 +00:00
|
|
|
class PythonFragment(PythonCode):
|
2016-12-16 11:59:19 +00:00
|
|
|
|
|
|
|
"""extends PythonCode to provide identifier lookups in partial control
|
|
|
|
statements
|
|
|
|
|
|
|
|
e.g.
|
2012-09-13 15:27:34 +00:00
|
|
|
for x in 5:
|
|
|
|
elif y==9:
|
|
|
|
except (MyException, e):
|
|
|
|
etc.
|
|
|
|
"""
|
2016-12-16 11:59:19 +00:00
|
|
|
|
2012-09-13 15:27:34 +00:00
|
|
|
def __init__(self, code, **exception_kwargs):
|
|
|
|
m = re.match(r'^(\w+)(?:\s+(.*?))?:\s*(#|$)', code.strip(), re.S)
|
|
|
|
if not m:
|
|
|
|
raise exceptions.CompileException(
|
2016-12-16 11:59:19 +00:00
|
|
|
"Fragment '%s' is not a partial control statement" %
|
|
|
|
code, **exception_kwargs)
|
2012-09-13 15:27:34 +00:00
|
|
|
if m.group(3):
|
|
|
|
code = code[:m.start(3)]
|
2016-12-16 11:59:19 +00:00
|
|
|
(keyword, expr) = m.group(1, 2)
|
|
|
|
if keyword in ['for', 'if', 'while']:
|
2012-09-13 15:27:34 +00:00
|
|
|
code = code + "pass"
|
|
|
|
elif keyword == 'try':
|
|
|
|
code = code + "pass\nexcept:pass"
|
|
|
|
elif keyword == 'elif' or keyword == 'else':
|
|
|
|
code = "if False:pass\n" + code + "pass"
|
|
|
|
elif keyword == 'except':
|
|
|
|
code = "try:pass\n" + code + "pass"
|
2016-12-16 11:59:19 +00:00
|
|
|
elif keyword == 'with':
|
|
|
|
code = code + "pass"
|
2012-09-13 15:27:34 +00:00
|
|
|
else:
|
|
|
|
raise exceptions.CompileException(
|
2016-12-16 11:59:19 +00:00
|
|
|
"Unsupported control keyword: '%s'" %
|
|
|
|
keyword, **exception_kwargs)
|
2012-09-13 15:27:34 +00:00
|
|
|
super(PythonFragment, self).__init__(code, **exception_kwargs)
|
2016-12-16 11:59:19 +00:00
|
|
|
|
|
|
|
|
2012-09-13 15:27:34 +00:00
|
|
|
class FunctionDecl(object):
|
2016-12-16 11:59:19 +00:00
|
|
|
|
2012-09-13 15:27:34 +00:00
|
|
|
"""function declaration"""
|
2016-12-16 11:59:19 +00:00
|
|
|
|
2012-09-13 15:27:34 +00:00
|
|
|
def __init__(self, code, allow_kwargs=True, **exception_kwargs):
|
|
|
|
self.code = code
|
|
|
|
expr = pyparser.parse(code, "exec", **exception_kwargs)
|
2016-12-16 11:59:19 +00:00
|
|
|
|
2012-09-13 15:27:34 +00:00
|
|
|
f = pyparser.ParseFunc(self, **exception_kwargs)
|
|
|
|
f.visit(expr)
|
|
|
|
if not hasattr(self, 'funcname'):
|
|
|
|
raise exceptions.CompileException(
|
2016-12-16 11:59:19 +00:00
|
|
|
"Code '%s' is not a function declaration" % code,
|
|
|
|
**exception_kwargs)
|
2012-09-13 15:27:34 +00:00
|
|
|
if not allow_kwargs and self.kwargs:
|
|
|
|
raise exceptions.CompileException(
|
2016-12-16 11:59:19 +00:00
|
|
|
"'**%s' keyword argument not allowed here" %
|
|
|
|
self.kwargnames[-1], **exception_kwargs)
|
|
|
|
|
|
|
|
def get_argument_expressions(self, as_call=False):
|
|
|
|
"""Return the argument declarations of this FunctionDecl as a printable
|
|
|
|
list.
|
|
|
|
|
|
|
|
By default the return value is appropriate for writing in a ``def``;
|
|
|
|
set `as_call` to true to build arguments to be passed to the function
|
|
|
|
instead (assuming locals with the same names as the arguments exist).
|
|
|
|
"""
|
|
|
|
|
2012-09-13 15:27:34 +00:00
|
|
|
namedecls = []
|
2016-12-16 11:59:19 +00:00
|
|
|
|
|
|
|
# Build in reverse order, since defaults and slurpy args come last
|
|
|
|
argnames = self.argnames[::-1]
|
|
|
|
kwargnames = self.kwargnames[::-1]
|
|
|
|
defaults = self.defaults[::-1]
|
|
|
|
kwdefaults = self.kwdefaults[::-1]
|
|
|
|
|
|
|
|
# Named arguments
|
|
|
|
if self.kwargs:
|
|
|
|
namedecls.append("**" + kwargnames.pop(0))
|
|
|
|
|
|
|
|
for name in kwargnames:
|
|
|
|
# Keyword-only arguments must always be used by name, so even if
|
|
|
|
# this is a call, print out `foo=foo`
|
|
|
|
if as_call:
|
|
|
|
namedecls.append("%s=%s" % (name, name))
|
|
|
|
elif kwdefaults:
|
|
|
|
default = kwdefaults.pop(0)
|
|
|
|
if default is None:
|
|
|
|
# The AST always gives kwargs a default, since you can do
|
|
|
|
# `def foo(*, a=1, b, c=3)`
|
|
|
|
namedecls.append(name)
|
|
|
|
else:
|
|
|
|
namedecls.append("%s=%s" % (
|
|
|
|
name, pyparser.ExpressionGenerator(default).value()))
|
2012-09-13 15:27:34 +00:00
|
|
|
else:
|
2016-12-16 11:59:19 +00:00
|
|
|
namedecls.append(name)
|
|
|
|
|
|
|
|
# Positional arguments
|
|
|
|
if self.varargs:
|
|
|
|
namedecls.append("*" + argnames.pop(0))
|
|
|
|
|
|
|
|
for name in argnames:
|
|
|
|
if as_call or not defaults:
|
|
|
|
namedecls.append(name)
|
2012-09-13 15:27:34 +00:00
|
|
|
else:
|
2016-12-16 11:59:19 +00:00
|
|
|
default = defaults.pop(0)
|
|
|
|
namedecls.append("%s=%s" % (
|
|
|
|
name, pyparser.ExpressionGenerator(default).value()))
|
|
|
|
|
|
|
|
namedecls.reverse()
|
2012-09-13 15:27:34 +00:00
|
|
|
return namedecls
|
|
|
|
|
2016-12-16 11:59:19 +00:00
|
|
|
@property
|
|
|
|
def allargnames(self):
|
|
|
|
return tuple(self.argnames) + tuple(self.kwargnames)
|
|
|
|
|
|
|
|
|
2012-09-13 15:27:34 +00:00
|
|
|
class FunctionArgs(FunctionDecl):
|
2016-12-16 11:59:19 +00:00
|
|
|
|
2012-09-13 15:27:34 +00:00
|
|
|
"""the argument portion of a function declaration"""
|
2016-12-16 11:59:19 +00:00
|
|
|
|
2012-09-13 15:27:34 +00:00
|
|
|
def __init__(self, code, **kwargs):
|
2016-12-16 11:59:19 +00:00
|
|
|
super(FunctionArgs, self).__init__("def ANON(%s):pass" % code,
|
|
|
|
**kwargs)
|