astgen.py 9.28 KB
Newer Older
1 2 3 4 5 6 7 8
"""Generate ast module from specification

This script generates the ast module from a simple specification,
which makes it easy to accomodate changes in the grammar.  This
approach would be quite reasonable if the grammar changed often.
Instead, it is rather complex to generate the appropriate code.  And
the Node interface has changed more often than the grammar.
"""
9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33

import fileinput
import getopt
import re
import sys
from StringIO import StringIO

SPEC = "ast.txt"
COMMA = ", "

def load_boilerplate(file):
    f = open(file)
    buf = f.read()
    f.close()
    i = buf.find('### ''PROLOGUE')
    j = buf.find('### ''EPILOGUE')
    pro = buf[i+12:j].strip()
    epi = buf[j+12:].strip()
    return pro, epi

def strip_default(arg):
    """Return the argname from an 'arg = default' string"""
    i = arg.find('=')
    if i == -1:
        return arg
34 35 36 37 38 39 40
    t = arg[:i].strip()
    return t

P_NODE = 1
P_OTHER = 2
P_NESTED = 3
P_NONE = 4
41 42 43 44 45 46 47

class NodeInfo:
    """Each instance describes a specific AST node"""
    def __init__(self, name, args):
        self.name = name
        self.args = args.strip()
        self.argnames = self.get_argnames()
48
        self.argprops = self.get_argprops()
49 50 51 52 53 54 55 56 57 58 59 60 61
        self.nargs = len(self.argnames)
        self.init = []

    def get_argnames(self):
        if '(' in self.args:
            i = self.args.find('(')
            j = self.args.rfind(')')
            args = self.args[i+1:j]
        else:
            args = self.args
        return [strip_default(arg.strip())
                for arg in args.split(',') if arg]

62 63 64 65 66 67 68 69 70 71 72 73
    def get_argprops(self):
        """Each argument can have a property like '*' or '!'

        XXX This method modifies the argnames in place!
        """
        d = {}
        hardest_arg = P_NODE
        for i in range(len(self.argnames)):
            arg = self.argnames[i]
            if arg.endswith('*'):
                arg = self.argnames[i] = arg[:-1]
                d[arg] = P_OTHER
74
                hardest_arg = max(hardest_arg, P_OTHER)
75 76 77
            elif arg.endswith('!'):
                arg = self.argnames[i] = arg[:-1]
                d[arg] = P_NESTED
78
                hardest_arg = max(hardest_arg, P_NESTED)
79 80 81
            elif arg.endswith('&'):
                arg = self.argnames[i] = arg[:-1]
                d[arg] = P_NONE
82
                hardest_arg = max(hardest_arg, P_NONE)
83 84 85 86 87 88 89 90
            else:
                d[arg] = P_NODE
        self.hardest_arg = hardest_arg

        if hardest_arg > P_NODE:
            self.args = self.args.replace('*', '')
            self.args = self.args.replace('!', '')
            self.args = self.args.replace('&', '')
91

92 93
        return d

94 95 96 97
    def gen_source(self):
        buf = StringIO()
        print >> buf, "class %s(Node):" % self.name
        self._gen_init(buf)
98
        print >> buf
99
        self._gen_getChildren(buf)
100 101 102
        print >> buf
        self._gen_getChildNodes(buf)
        print >> buf
103 104 105 106 107
        self._gen_repr(buf)
        buf.seek(0, 0)
        return buf.read()

    def _gen_init(self, buf):
108 109 110 111
        if self.args:
            print >> buf, "    def __init__(self, %s, lineno=None):" % self.args
        else:
            print >> buf, "    def __init__(self, lineno=None):"
112 113 114
        if self.argnames:
            for name in self.argnames:
                print >> buf, "        self.%s = %s" % (name, name)
115
        print >> buf, "        self.lineno = lineno"
116 117 118 119 120
        # Copy the lines in self.init, indented four spaces.  The rstrip()
        # business is to get rid of the four spaces if line happens to be
        # empty, so that reindent.py is happy with the output.
        for line in self.init:
            print >> buf, ("    " + line).rstrip()
121 122

    def _gen_getChildren(self, buf):
123 124 125
        print >> buf, "    def getChildren(self):"
        if len(self.argnames) == 0:
            print >> buf, "        return ()"
126
        else:
127 128 129 130 131 132 133 134
            if self.hardest_arg < P_NESTED:
                clist = COMMA.join(["self.%s" % c
                                    for c in self.argnames])
                if self.nargs == 1:
                    print >> buf, "        return %s," % clist
                else:
                    print >> buf, "        return %s" % clist
            else:
135 136 137 138 139 140 141 142 143 144 145 146
                if len(self.argnames) == 1:
                    print >> buf, "        return tuple(flatten(self.%s))" % self.argnames[0]
                else:
                    print >> buf, "        children = []"
                    template = "        children.%s(%sself.%s%s)"
                    for name in self.argnames:
                        if self.argprops[name] == P_NESTED:
                            print >> buf, template % ("extend", "flatten(",
                                                      name, ")")
                        else:
                            print >> buf, template % ("append", "", name, "")
                    print >> buf, "        return tuple(children)"
147 148 149 150

    def _gen_getChildNodes(self, buf):
        print >> buf, "    def getChildNodes(self):"
        if len(self.argnames) == 0:
151
            print >> buf, "        return ()"
152 153 154 155 156 157 158 159 160 161 162 163
        else:
            if self.hardest_arg < P_NESTED:
                clist = ["self.%s" % c
                         for c in self.argnames
                         if self.argprops[c] == P_NODE]
                if len(clist) == 0:
                    print >> buf, "        return ()"
                elif len(clist) == 1:
                    print >> buf, "        return %s," % clist[0]
                else:
                    print >> buf, "        return %s" % COMMA.join(clist)
            else:
164 165
                print >> buf, "        nodelist = []"
                template = "        nodelist.%s(%sself.%s%s)"
166 167
                for name in self.argnames:
                    if self.argprops[name] == P_NONE:
168
                        tmp = ("        if self.%s is not None:\n"
169
                               "            nodelist.append(self.%s)")
170 171 172 173 174 175
                        print >> buf, tmp % (name, name)
                    elif self.argprops[name] == P_NESTED:
                        print >> buf, template % ("extend", "flatten_nodes(",
                                                  name, ")")
                    elif self.argprops[name] == P_NODE:
                        print >> buf, template % ("append", "", name, "")
176
                print >> buf, "        return tuple(nodelist)"
177 178 179 180 181

    def _gen_repr(self, buf):
        print >> buf, "    def __repr__(self):"
        if self.argnames:
            fmt = COMMA.join(["%s"] * self.nargs)
182 183
            if '(' in self.args:
                fmt = '(%s)' % fmt
184 185 186 187 188 189 190 191 192 193 194 195 196 197 198
            vals = ["repr(self.%s)" % name for name in self.argnames]
            vals = COMMA.join(vals)
            if self.nargs == 1:
                vals = vals + ","
            print >> buf, '        return "%s(%s)" %% (%s)' % \
                  (self.name, fmt, vals)
        else:
            print >> buf, '        return "%s()"' % self.name

rx_init = re.compile('init\((.*)\):')

def parse_spec(file):
    classes = {}
    cur = None
    for line in fileinput.input(file):
199 200
        if line.strip().startswith('#'):
            continue
201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217
        mo = rx_init.search(line)
        if mo is None:
            if cur is None:
                # a normal entry
                try:
                    name, args = line.split(':')
                except ValueError:
                    continue
                classes[name] = NodeInfo(name, args)
                cur = None
            else:
                # some code for the __init__ method
                cur.init.append(line)
        else:
            # some extra code for a Node's __init__ method
            name = mo.group(1)
            cur = classes[name]
218
    return sorted(classes.values(), key=lambda n: n.name)
219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235

def main():
    prologue, epilogue = load_boilerplate(sys.argv[-1])
    print prologue
    print
    classes = parse_spec(SPEC)
    for info in classes:
        print info.gen_source()
    print epilogue

if __name__ == "__main__":
    main()
    sys.exit(0)

### PROLOGUE
"""Python abstract syntax node definitions

236
This file is automatically generated by Tools/compiler/astgen.py
237 238 239
"""
from consts import CO_VARARGS, CO_VARKEYWORDS

240
def flatten(seq):
241
    l = []
242
    for elt in seq:
243
        t = type(elt)
244
        if t is tuple or t is list:
245 246 247 248 249 250
            for elt2 in flatten(elt):
                l.append(elt2)
        else:
            l.append(elt)
    return l

251 252
def flatten_nodes(seq):
    return [n for n in flatten(seq) if isinstance(n, Node)]
253

254 255
nodes = {}

256 257
class Node:
    """Abstract base class for ast nodes."""
258
    def getChildren(self):
259
        pass # implemented by subclasses
260 261 262 263 264
    def __iter__(self):
        for n in self.getChildren():
            yield n
    def asList(self): # for backwards compatibility
        return self.getChildren()
265
    def getChildNodes(self):
266
        pass # implemented by subclasses
267 268

class EmptyNode(Node):
269
    pass
270

271 272 273 274 275 276 277 278 279 280 281 282 283 284 285
class Expression(Node):
    # Expression is an artificial node class to support "eval"
    nodes["expression"] = "Expression"
    def __init__(self, node):
        self.node = node

    def getChildren(self):
        return self.node,

    def getChildNodes(self):
        return self.node,

    def __repr__(self):
        return "Expression(%s)" % (repr(self.node))

286
### EPILOGUE
287 288
for name, obj in globals().items():
    if isinstance(obj, type) and issubclass(obj, Node):
Tim Peters's avatar
Tim Peters committed
289
        nodes[name.lower()] = obj