aboutsummaryrefslogtreecommitdiff
path: root/contrib/llvm/tools/lldb/source/Plugins/ExpressionParser/Go/gen_go_ast.py
blob: 05b589a9976cb1723814dc8157d981eb851a978b (plain) (blame)
1
2
3
4
5
6
7
8
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
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
import StringIO

def addNodes():
    addNode("ArrayType", "Expr", "len", "Expr", "elt", "Expr")
    addNode("AssignStmt", "Stmt", "lhs", "[]Expr", "rhs", "[]Expr", "define", "bool")
    addNode("BadDecl", "Decl")
    addNode("BadExpr", "Expr")
    addNode("BadStmt", "Stmt")
    addNode("BasicLit", "Expr", "value", "Token")
    addNode("BinaryExpr", "Expr", "x", "Expr", "y", "Expr", "op", "TokenType")
    addNode("BlockStmt", "Stmt", "list", "[]Stmt")
    addNode("Ident", "Expr", "name", "Token")
    addNode("BranchStmt", "Stmt", "label", "Ident", "tok", "TokenType")
    addNode("CallExpr", "Expr", "fun", "Expr", "args", "[]Expr", "ellipsis", "bool")
    addNode("CaseClause", "Stmt", "list", "[]Expr", "body", "[]Stmt")
    addNode("ChanType", "Expr", "dir", "ChanDir", "value", "Expr")
    addNode("CommClause", "Stmt", "comm", "Stmt", "body", "[]Stmt")
    addNode("CompositeLit", "Expr", "type", "Expr", "elts", "[]Expr")
    addNode("DeclStmt", "Stmt", "decl", "Decl")
    addNode("DeferStmt", "Stmt", "call", "CallExpr")
    addNode("Ellipsis", "Expr", "elt", "Expr")
    addNode("EmptyStmt", "Stmt")
    addNode("ExprStmt", "Stmt", "x", "Expr")
    addNode("Field", "Node", "names", "[]Ident", "type", "Expr", "tag", "BasicLit")
    addNode("FieldList", "Node", "list", "[]Field")
    addNode("ForStmt", "Stmt", "init", "Stmt", "cond", "Expr", "post", "Stmt", "body", "BlockStmt")
    addNode("FuncType", "Expr", "params", "FieldList", "results", "FieldList")
    addNode("FuncDecl", "Decl", "recv", "FieldList", "name", "Ident", "type", "FuncType", "body", "BlockStmt")
    addNode("FuncLit", "Expr", "type", "FuncType", "body", "BlockStmt")
    addNode("GenDecl", "Decl", "tok", "TokenType", "specs", "[]Spec")
    addNode("GoStmt", "Stmt", "call", "CallExpr")
    addNode("IfStmt", "Stmt", "init", "Stmt", "cond", "Expr", "body", "BlockStmt", "els", "Stmt")
    addNode("ImportSpec", "Spec", "name", "Ident", "path", "BasicLit")
    addNode("IncDecStmt", "Stmt", "x", "Expr", "tok", "TokenType")
    addNode("IndexExpr", "Expr", "x", "Expr", "index", "Expr")
    addNode("InterfaceType", "Expr", "methods", "FieldList")
    addNode("KeyValueExpr", "Expr", "key", "Expr", "value", "Expr")
    addNode("LabeledStmt", "Stmt", "label", "Ident", "stmt", "Stmt")
    addNode("MapType", "Expr", "key", "Expr", "value", "Expr")
    addNode("ParenExpr", "Expr", "x", "Expr")
    addNode("RangeStmt", "Stmt", "key", "Expr", "value", "Expr", "define", "bool", "x", "Expr", "body", "BlockStmt")
    addNode("ReturnStmt", "Stmt", "results", "[]Expr")
    addNode("SelectStmt", "Stmt", "body", "BlockStmt")
    addNode("SelectorExpr", "Expr", "x", "Expr", "sel", "Ident")
    addNode("SendStmt", "Stmt", "chan", "Expr", "value", "Expr")
    addNode("SliceExpr", "Expr", "x", "Expr", "low", "Expr", "high", "Expr", "max", "Expr", "slice3", "bool")
    addNode("StarExpr", "Expr", "x", "Expr")
    addNode("StructType", "Expr", "fields", "FieldList")
    addNode("SwitchStmt", "Stmt", "init", "Stmt", "tag", "Expr", "body", "BlockStmt")
    addNode("TypeAssertExpr", "Expr", "x", "Expr", "type", "Expr")
    addNode("TypeSpec", "Spec", "name", "Ident", "type", "Expr")
    addNode("TypeSwitchStmt", "Stmt", "init", "Stmt", "assign", "Stmt", "body", "BlockStmt")
    addNode("UnaryExpr", "Expr", "op", "TokenType", "x", "Expr")
    addNode("ValueSpec", "Spec", "names", "[]Ident", "type", "Expr", "values", "[]Expr")
    addParent("Decl", "Node")
    addParent("Expr", "Node")
    addParent("Spec", "Node")
    addParent("Stmt", "Node")


class Member(object):
    def __init__(self, name, typename):
        self.title = name.title()
        self.sname = name
        self.mname = 'm_' + name
        self.is_list = typename.startswith("[]")
        self.is_value = isValueType(typename)
        if self.is_value:
            self.argtype = typename
            self.mtype = typename
        elif self.is_list:
            self.argtype = 'GoAST' + typename[2:]
            self.mtype = 'std::vector<std::unique_ptr<%s> >' % self.argtype
        else:
            self.argtype = 'GoAST' + typename
            self.mtype = 'std::unique_ptr<%s>' % self.argtype
            self.mname = self.mname + '_up'
    

kinds = {}
parentClasses = StringIO.StringIO()
childClasses = StringIO.StringIO()
walker = StringIO.StringIO()

def startClass(name, parent, out):
    out.write("""
class GoAST%s : public GoAST%s
{
  public:
""" % (name, parent))

def endClass(name, out):
    out.write("""
    %(name)s(const %(name)s &) = delete;
    const %(name)s &operator=(const %(name)s &) = delete;
};
""" % {'name': 'GoAST' + name})

def addNode(name, parent, *children):
    startClass(name, parent, childClasses)
    l = kinds.setdefault(parent, [])
    l.append(name)
    children = createMembers(name, children)
    addConstructor(name, parent, children)
    childClasses.write("""
    const char *
    GetKindName() const override
    {
        return "%(name)s";
    }

    static bool
    classof(const GoASTNode *n)
    {
        return n->GetKind() == e%(name)s;
    }
    """ % {'name':name})
    addChildren(name, children)
    endClass(name, childClasses)

def isValueType(typename):
    if typename[0].islower():
        return True
    if typename[0].isupper():
        return typename.startswith('Token') or typename == 'ChanDir'
    return False


def createMembers(name, children):
    l = len(children)
    if (l % 2) != 0:
        raise Exception("Invalid children for %s: %s" % (name, children))
    return [Member(children[i], children[i + 1]) for i in xrange(0, l, 2)]


def addConstructor(name, parent, children):
    for c in children:
        if c.is_list:
            children = [x for x in children if x.is_value]
            break
    childClasses.write('    ')
    if len(children) == 1:
        childClasses.write('explicit ')
    childClasses.write('GoAST%s(' % name)
    for i in xrange(len(children)):
        if i > 0:
            childClasses.write(', ')

        c = children[i]
        if c.is_value:
            childClasses.write(c.argtype)
            childClasses.write(' ')
        else:
            childClasses.write('%s *' % c.argtype)
        childClasses.write(c.sname)
    childClasses.write(') : GoAST%s(e%s)' % (parent, name))
    for c in children:
        childClasses.write(', ')
        childClasses.write('%(mname)s(%(sname)s)' % c.__dict__)
    childClasses.write(""" {}
    ~GoAST%s() override = default;
""" % name)

    
def addChildren(name, children):
    if len(children) == 0:
        return
    walker.write("""
    case e%(n)s:
        {
            GoAST%(n)s *n = llvm::cast<GoAST%(n)s>(this);
            (void)n;""" % {'n':name})
    for c in children:
        if c.is_list:
            childClasses.write("""
    size_t
    Num%(title)s() const
    {
        return %(mname)s.size();
    }
    const %(argtype)s *
    Get%(title)s(int i) const
    {
        return %(mname)s[i].get();
    }
    void
    Add%(title)s(%(argtype)s *%(sname)s)
    {
        %(mname)s.push_back(std::unique_ptr<%(argtype)s>(%(sname)s));
    }
""" % c.__dict__)
            walker.write("""
            for (auto& e : n->%s) { v(e.get()); }""" % c.mname)
        else:
            const = ''
            get = ''
            set = ''
            t = c.argtype
            if isValueType(t):
                set = '%(mname)s = %(sname)s' % c.__dict__
                t = t + ' '
            else:
                t = t + ' *'
                const = 'const '
                get = '.get()'
                set = '%(mname)s.reset(%(sname)s)' % c.__dict__
                walker.write("""
            v(n->%s.get());""" % c.mname)
            childClasses.write("""
    %(const)s%(type)s
    Get%(title)s() const
    {
        return %(mname)s%(get)s;
    }
    void
    Set%(title)s(%(type)s%(sname)s)
    {
        %(set)s;
    }
""" % {'const':const, 'title': c.title, 'sname': c.sname, 'get': get, 'set': set, 'type': t, 'mname': c.mname})
    childClasses.write('\n  private:\n    friend class GoASTNode;\n')
    walker.write("""
            return;
        }""")
    for c in children:
        childClasses.write('    %s %s;\n' %(c.mtype, c.mname))
    

def addParent(name, parent):
    startClass(name, parent, parentClasses)
    l = kinds[name]
    minName = l[0]
    maxName = l[-1]
    parentClasses.write("""    template <typename R, typename V> R Visit(V *v) const;

    static bool
    classof(const GoASTNode *n)
    {
        return n->GetKind() >= e%s && n->GetKind() <= e%s;
    }

  protected:
    explicit GoAST%s(NodeKind kind) : GoASTNode(kind) { }
  private:
""" % (minName, maxName, name))
    endClass(name, parentClasses)
    
addNodes()

print """//===-- GoAST.h -------------------------------------------------*- C++ -*-===//
//
//                     The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//

// DO NOT EDIT.
// Generated by gen_go_ast.py

#ifndef liblldb_GoAST_h
#define liblldb_GoAST_h

#include "lldb/lldb-forward.h"
#include "lldb/lldb-private.h"
#include "llvm/Support/Casting.h"
#include "Plugins/ExpressionParser/Go/GoLexer.h"

namespace lldb_private
{

class GoASTNode
{
  public:
    typedef GoLexer::TokenType TokenType;
    typedef GoLexer::Token Token;
    enum ChanDir
    {
        eChanBidir,
        eChanSend,
        eChanRecv,
    };
    enum NodeKind
    {"""
for l in kinds.itervalues():
    for x in l:
        print "        e%s," % x
print """    };

    virtual ~GoASTNode() = default;

    NodeKind
    GetKind() const
    {
        return m_kind;
    }

    virtual const char *GetKindName() const = 0;

    template <typename V> void WalkChildren(V &v);

  protected:
    explicit GoASTNode(NodeKind kind) : m_kind(kind) { }

  private:
    const NodeKind m_kind;
    
    GoASTNode(const GoASTNode &) = delete;
    const GoASTNode &operator=(const GoASTNode &) = delete;
};
"""


print parentClasses.getvalue()
print childClasses.getvalue()

for k, l in kinds.iteritems():
    if k == 'Node':
        continue
    print """
template <typename R, typename V>
R GoAST%s::Visit(V* v) const
{
    switch(GetKind())
    {""" % k
    for subtype in l:
        print """    case e%(n)s:
        return v->Visit%(n)s(llvm::cast<const GoAST%(n)s>(this));""" % {'n':subtype}

    print """    default:
        assert(false && "Invalid kind");
    }
}"""

print """
template <typename V>
void GoASTNode::WalkChildren(V &v)
{
    switch (m_kind)
    {
"""
print walker.getvalue()
print"""
        case eEmptyStmt:
        case eBadDecl:
        case eBadExpr:
        case eBadStmt:
          break;
    }
}

}  // namespace lldb_private

#endif
"""