parsetreenodes.cpp 116 KB
Newer Older
hjk's avatar
hjk committed
1
/****************************************************************************
2
**
3
** Copyright (C) 2014 Digia Plc and/or its subsidiary(-ies).
hjk's avatar
hjk committed
4
** Contact: http://www.qt-project.org/legal
5
**
hjk's avatar
hjk committed
6
** This file is part of Qt Creator.
7
**
hjk's avatar
hjk committed
8
9
10
11
12
13
14
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Digia.  For licensing terms and
** conditions see http://qt.digia.com/licensing.  For further information
** use the contact form at http://qt.digia.com/contact-us.
15
16
**
** GNU Lesser General Public License Usage
hjk's avatar
hjk committed
17
18
19
20
21
22
23
24
25
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Digia gives you certain additional
** rights.  These rights are described in the Digia Qt LGPL Exception
26
27
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
hjk's avatar
hjk committed
28
****************************************************************************/
29

30
31
32
33
#include "parsetreenodes.h"

#include "demanglerexceptions.h"

34
#include <iostream>
35
#include <cctype>
36
37
#include <cstring>

38
39
40
#define PEEK() (parseState()->peek())
#define ADVANCE() (parseState()->advance())

41
#define PARSE_RULE_AND_ADD_RESULT_AS_CHILD_TO_NODE(NodeType, parseState, parentNode) \
42
    do { \
43
        ParseTreeNode::parseRule<NodeType>(parseState); \
44
        DEMANGLER_ASSERT(parseState->stackElementCount() > 0); \
45
        DEMANGLER_ASSERT(parseState->stackTop().dynamicCast<NodeType>()); \
46
47
        if (parentNode) \
            (parentNode)->addChild(parseState->popFromStack()); \
48
49
    } while (0)

50
51
52
53
54
55
56
57
#define PARSE_RULE_AND_ADD_RESULT_AS_CHILD_TO_THIS(NodeType, parseState) \
    do { \
        ParseTreeNode::parseRule<NodeType>(parseState); \
        DEMANGLER_ASSERT(parseState->stackElementCount() > 0); \
        DEMANGLER_ASSERT(parseState->stackTop().dynamicCast<NodeType>()); \
        addChild(parseState->popFromStack()); \
    } while (0)

58
59

#define PARSE_RULE_AND_ADD_RESULT_AS_CHILD(nodeType) \
60
    PARSE_RULE_AND_ADD_RESULT_AS_CHILD_TO_THIS(nodeType, parseState())
61
#define CHILD_AT(obj, index) obj->childAt(index, QLatin1String(Q_FUNC_INFO), QLatin1String(__FILE__), __LINE__)
62
#define MY_CHILD_AT(index) CHILD_AT(this, index)
63
#define CHILD_TO_BYTEARRAY(index) MY_CHILD_AT(index)->toByteArray()
64
65
66
67

namespace Debugger {
namespace Internal {

68
69
70
template<int base> static int getNonNegativeNumber(GlobalParseState *parseState)
{
    ParseTreeNode::parseRule<NonNegativeNumberNode<base> >(parseState);
hjk's avatar
hjk committed
71
    const typename NonNegativeNumberNode<base>::Ptr numberNode
72
73
74
75
76
            = DEMANGLER_CAST(NonNegativeNumberNode<base>, parseState->popFromStack());
    const int value = static_cast<int>(numberNode->number());
    return value;
}

77
78
79
80
81
ParseTreeNode::ParseTreeNode(const ParseTreeNode &other) : m_parseState(other.m_parseState)
{
    foreach (const ParseTreeNode::Ptr &child, other.m_children)
        addChild(child->clone());
}
82

83
84
85
86
ParseTreeNode::~ParseTreeNode()
{
}

87
ParseTreeNode::Ptr ParseTreeNode::childAt(int i, const QString &func, const QString &file,
88
89
90
91
92
93
94
95
96
97
        int line) const
{
    if (i < 0 || i >= m_children.count())
        throw InternalDemanglerException(func, file, line);
    return m_children.at(i);
}

QByteArray ParseTreeNode::pasteAllChildren() const
{
    QByteArray repr;
98
    foreach (const ParseTreeNode::Ptr &node, m_children)
99
100
101
102
        repr += node->toByteArray();
    return repr;
}

103
104
105
106
107
108
109
110
111
112
113
114
115
void ParseTreeNode::print(int indentation) const
{
    for (int i = 0; i < indentation; ++i)
        std::cerr << ' ';
    std::cerr << description().data() << std::endl;
    foreach (const ParseTreeNode::Ptr &n, m_children)
        n->print(indentation + 2);
}

QByteArray ParseTreeNode::bool2String(bool b) const
{
    return b ? "true" : "false";
}
116
117
118
119
120
121

bool ArrayTypeNode::mangledRepresentationStartsWith(char c)
{
    return c == 'A';
}

122
123
124
/*
 * <array-type> ::= A <number> _ <type>
 *              ::= A [<expression>] _ <type>
125
 * Note that <expression> can also start with a number, so we have to do a non-constant look-ahead.
126
127
128
129
130
131
 */
void ArrayTypeNode::parse()
{
    if (!ArrayTypeNode::mangledRepresentationStartsWith(ADVANCE()))
        throw ParseException(QString::fromLatin1("Invalid array-type"));

132
133
134
135
136
137
138
139
140
141
142
    bool isNumber = NonNegativeNumberNode<10>::mangledRepresentationStartsWith(PEEK());
    int i = 1;
    while (isNumber) {
        const char next = parseState()->peek(i);
        if (next == '_')
            break;
        if (!std::isdigit(parseState()->peek(i)))
            isNumber = false;
        ++i;
    }
    if (isNumber)
143
        PARSE_RULE_AND_ADD_RESULT_AS_CHILD(NonNegativeNumberNode<10>);
144
    else if (ExpressionNode::mangledRepresentationStartsWith(PEEK()))
145
146
147
148
149
150
151
152
        PARSE_RULE_AND_ADD_RESULT_AS_CHILD(ExpressionNode);

    if (ADVANCE() != '_')
        throw ParseException(QString::fromLatin1("Invalid array-type"));

    PARSE_RULE_AND_ADD_RESULT_AS_CHILD(TypeNode);
}

153
154
QByteArray ArrayTypeNode::toByteArray() const
{
155
156
    // Note: This is not used for things like "reference to array", which need to
    // combine the child nodes in a different way at a higher level.
157
158
159
160
    return CHILD_TO_BYTEARRAY(1) + '[' + CHILD_TO_BYTEARRAY(0) + ']';
}


161
162
163
164
165
166
167
168
169
170
BareFunctionTypeNode::BareFunctionTypeNode(GlobalParseState *parseState)
        : ParseTreeNode(parseState), m_hasReturnType(false)
{
}

BareFunctionTypeNode::BareFunctionTypeNode(const BareFunctionTypeNode &other)
        : ParseTreeNode(other), m_hasReturnType(other.hasReturnType())
{
}

171
172
173
174
175
bool BareFunctionTypeNode::mangledRepresentationStartsWith(char c)
{
    return TypeNode::mangledRepresentationStartsWith(c);
}

176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
/* <bare-function-type> ::= <type>+ */
void BareFunctionTypeNode::parse()
{
   /*
    * The following is verbatim from the spec:
    * Whether the mangling of a function type includes the return type depends on the context
    * and the nature of the function. The rules for deciding whether the return type is included
    * are:
    *     (1) Template functions (names or types) have return types encoded, with the exceptions
    *         listed below.
    *     (2) Function types not appearing as part of a function name mangling, e.g. parameters,
    *         pointer types, etc., have return type encoded, with the exceptions listed below.
    *     (3) Non-template function names do not have return types encoded.
    * The exceptions mentioned in (1) and (2) above, for which the return type is never included,
    * are constructors, destructors and conversion operator functions, e.g. operator int.
    */
192
193
    const EncodingNode::Ptr encodingNode = parseState()->stackElementAt(parseState()
            ->stackElementCount() - 2).dynamicCast<EncodingNode>();
194
    if (encodingNode) { // Case 1: Function name.
195
        const NameNode::Ptr nameNode = DEMANGLER_CAST(NameNode, CHILD_AT(encodingNode, 0));
196
197
198
199
200
201
202
203
204
205
206
207
        m_hasReturnType = nameNode->isTemplate()
                && !nameNode->isConstructorOrDestructorOrConversionOperator();
    } else {            // Case 2: function type.
        // TODO: What do the exceptions look like for this case?
        m_hasReturnType = true;
    }

    do
        PARSE_RULE_AND_ADD_RESULT_AS_CHILD(TypeNode);
    while (TypeNode::mangledRepresentationStartsWith(PEEK()));
}

208
209
210
211
212
213
214
215
216
217
QByteArray BareFunctionTypeNode::description() const
{
    QByteArray desc = "BareFunctionType";
    if (m_hasReturnType)
        desc += "[with return type]";
    else
        desc += "[without return type]";
    return desc;
}

218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
QByteArray BareFunctionTypeNode::toByteArray() const
{
    // This is only the parameter list, including parentheses. Where the return type is placed
    // must be decided at a higher level.
    QByteArray repr = "(";
    for (int i = m_hasReturnType ? 1 : 0; i < childCount(); ++i) {
        const QByteArray paramRepr = CHILD_TO_BYTEARRAY(i);
        if (paramRepr != "void")
            repr += paramRepr;
        if (i < childCount() - 1)
            repr += ", ";
    }
    return repr += ')';
}


234
235
236
237
238
BuiltinTypeNode::BuiltinTypeNode(const BuiltinTypeNode &other)
        : ParseTreeNode(other), m_type(other.type())
{
}

239
240
bool BuiltinTypeNode::mangledRepresentationStartsWith(char c)
{
241
    return std::strchr("vwbcahstijlmxynofgedzDu", c);
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
/*
 * <builtin-type> ::= v # void
 *                ::= w  # wchar_t
 *                ::= b  # bool
 *                ::= c  # char
 *                ::= a  # signed char
 *                ::= h  # unsigned char
 *                ::= s  # short
 *                ::= t  # unsigned short
 *                ::= i  # int
 *                ::= j  # unsigned int
 *                ::= l  # long
 *                ::= m  # unsigned long
 *                ::= x  # long long, __int64
 *                ::= y  # unsigned long long, __int64
 *                ::= n  # __int128
 *                ::= o  # unsigned __int128
 *                ::= f  # float
 *                ::= d  # double
 *                ::= e  # long double, __float80
 *                ::= g  # __float128
 *                ::= z  # ellipsis
 *                ::= Dd # IEEE 754r decimal floating point (64 bits)
 *                ::= De # IEEE 754r decimal floating point (128 bits)
 *                ::= Df # IEEE 754r decimal floating point (32 bits)
 *                ::= Dh # IEEE 754r half-precision floating point (16 bits)
 *                ::= Di # char32_t
 *                ::= Ds # char16_t
272
273
 *                ::= Da # auto (in dependent new-expressions)
 *                ::= Dn # std::nullptr_t (i.e., decltype(nullptr))
274
275
276
277
278
279
 *                ::= u <source-name>    # vendor extended type
 */
void BuiltinTypeNode::parse()
{
    const char next = ADVANCE();
    if (next == 'u') {
280
        m_type = VendorType;
281
        PARSE_RULE_AND_ADD_RESULT_AS_CHILD(SourceNameNode);
282
        parseState()->addSubstitution(parseState()->stackTop());
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
        return;
    }

    switch (next) {
    case 'v': m_type = VoidType; break;
    case 'w': m_type = WCharType; break;
    case 'b': m_type = BoolType; break;
    case 'c': m_type = PlainCharType; break;
    case 'a': m_type = SignedCharType; break;
    case 'h': m_type = UnsignedCharType; break;
    case 's': m_type = SignedShortType; break;
    case 't': m_type = UnsignedShortType; break;
    case 'i': m_type = SignedIntType; break;
    case 'j': m_type = UnsignedIntType; break;
    case 'l': m_type = SignedLongType; break;
    case 'm': m_type = UnsignedLongType; break;
    case 'x': m_type = SignedLongLongType; break;
    case 'y': m_type = UnsignedLongLongType; break;
    case 'n': m_type = SignedInt128Type; break;
    case 'o': m_type = UnsignedInt128Type; break;
    case 'f': m_type = FloatType; break;
    case 'd': m_type = DoubleType; break;
    case 'e': m_type = LongDoubleType; break;
    case 'g': m_type = Float128Type; break;
    case 'z': m_type = EllipsisType; break;
    case 'D':
        switch (ADVANCE()) {
        case 'd':
            m_type = DecimalFloatingType64;
312
            break;
313
314
315
316
317
318
319
320
321
322
        case 'e':
            m_type = DecimalFloatingType128;
            break;
        case 'f':
            m_type = DecimalFloatingType32;
            break;
        case 'h':
            m_type = DecimalFloatingType16; break;
        case 'i': m_type = Char32Type; break;
        case 's': m_type = Char16Type; break;
323
324
        case 'a': m_type = AutoType; break;
        case 'n': m_type = NullPtrType; break;
325
        default: throw ParseException(QString::fromLatin1("Invalid built-in type"));
326
        }
327
328
329
        break;
    default:
        DEMANGLER_ASSERT(false);
330
331
332
    }
}

333
334
335
336
337
QByteArray BuiltinTypeNode::description() const
{
    return "BuiltinType[" + toByteArray() + ']';
}

338
339
QByteArray BuiltinTypeNode::toByteArray() const
{
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
    switch (m_type) {
    case VoidType: return "void";
    case WCharType: return "wchar_t";
    case BoolType: return "bool";
    case PlainCharType: return "char";
    case SignedCharType: return "signed char";
    case UnsignedCharType: return "unsigned char";
    case SignedShortType: return "signed short";
    case UnsignedShortType: return "unsigned short";
    case SignedIntType: return "int";
    case UnsignedIntType: return "unsigned int";
    case SignedLongType: return "long";
    case UnsignedLongType: return "unsigned long";
    case SignedLongLongType: return "long long";
    case UnsignedLongLongType: return "unsigned long long";
    case SignedInt128Type: return "__int128";
    case UnsignedInt128Type: return "unsigned __int128";
    case FloatType: return "float";
    case DoubleType: return "double";
    case LongDoubleType: return "long double";
    case Float128Type: return "__float128";
    case EllipsisType: return "...";
    case DecimalFloatingType16: return "[IEEE 754r half-precision floating point]";
    case DecimalFloatingType32: return "[IEEE 754r decimal floating point (32 bits)]";
    case DecimalFloatingType64: return "[IEEE 754r decimal floating point (64 bits)]";
    case DecimalFloatingType128: return "[IEEE 754r decimal floating point (128 bits)]";
    case Char32Type: return "char32_t";
    case Char16Type: return "char16_t";
368
369
    case AutoType: return "auto";
    case NullPtrType: return "std::nullptr_t";
370
371
372
373
374
    case VendorType: return CHILD_TO_BYTEARRAY(0);
    }

    DEMANGLER_ASSERT(false);
    return QByteArray();
375
376
377
}


378
bool CallOffsetRule::mangledRepresentationStartsWith(char c)
379
380
381
382
{
    return c == 'h' || c == 'v';
}

383
384
385
386
/*
 * <call-offset> ::= h <nv-offset> _
 *               ::= v <v-offset> _
 */
387
void CallOffsetRule::parse(GlobalParseState *parseState)
388
{
389
    const ParseTreeNode::Ptr parentNode = parseState->stackTop();
390
391
392
    switch (parseState->advance()) {
    case 'h': PARSE_RULE_AND_ADD_RESULT_AS_CHILD_TO_NODE(NvOffsetNode, parseState, parentNode); break;
    case 'v': PARSE_RULE_AND_ADD_RESULT_AS_CHILD_TO_NODE(VOffsetNode, parseState, parentNode); break;
393
394
    default: DEMANGLER_ASSERT(false);
    }
395
    if (parseState->advance() != '_')
396
397
398
        throw ParseException(QString::fromLatin1("Invalid call-offset"));
}

399
bool ClassEnumTypeRule::mangledRepresentationStartsWith(char c)
400
401
402
403
404
405
{
    /*
     * The first set of <class-enum-type> is much smaller than
     * the grammar claims.
     * firstSetClassEnumType = firstSetName;
     */
406
     return NonNegativeNumberNode<10>::mangledRepresentationStartsWith(c)
407
408
409
             || c == 'N' || c == 'D' || c == 'Z';
}

410
/* <class-enum-type> ::= <name> */
411
void ClassEnumTypeRule::parse(GlobalParseState *parseState)
412
{
413
    PARSE_RULE_AND_ADD_RESULT_AS_CHILD_TO_NODE(NameNode, parseState, parseState->stackTop());
414
415
416
}


417
bool DiscriminatorRule::mangledRepresentationStartsWith(char c)
418
419
420
421
{
    return c == '_';
}

422
423
424
425
426
/*
 *
 * <discriminator> := _ <non-negative number>      # when number < 10
 *                 := __ <non-negative number> _   # when number >= 10
 */
427
void DiscriminatorRule::parse(GlobalParseState *parseState)
428
{
429
    if (parseState->advance() != '_')
430
        throw ParseException(QString::fromLatin1("Invalid discriminator"));
431
432
433
434
435
    bool ge10 = false;
    if (parseState->peek() == '_') {
        ge10 = true;
        parseState->advance();
    }
436
    const ParseTreeNode::Ptr parentNode = parseState->stackTop();
437
    PARSE_RULE_AND_ADD_RESULT_AS_CHILD_TO_NODE(NonNegativeNumberNode<10>, parseState, parentNode);
438
    const NonNegativeNumberNode<10>::Ptr number
439
440
441
442
443
            = DEMANGLER_CAST(NonNegativeNumberNode<10>, CHILD_AT(parentNode, parentNode->childCount() - 1));
    if ((ge10 && number->number() < 10) || (!ge10 && number->number() >= 10))
        throw ParseException(QString::fromLatin1("Invalid discriminator"));
    if (ge10 && parseState->advance() != '_')
        throw ParseException(QString::fromLatin1("Invalid discriminator"));
444
445
446
}


447
448
449
450
451
452
453
CtorDtorNameNode::CtorDtorNameNode(const CtorDtorNameNode &other)
        : ParseTreeNode(other),
          m_isDestructor(other.m_isDestructor),
          m_representation(other.m_representation)
{
}

454
455
456
457
458
bool CtorDtorNameNode::mangledRepresentationStartsWith(char c)
{
    return c == 'C' || c == 'D';
}

459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
/*
 * <ctor-dtor-name> ::= C1      # complete object constructor
 *                  ::= C2      # base object constructor
 *                  ::= C3      # complete object allocating constructor
 *                  ::= D0      # deleting destructor
 *                  ::= D1      # complete object destructor
 *                  ::= D2      # base object destructor
 */
void CtorDtorNameNode::parse()
{
    switch (ADVANCE()) {
    case 'C':
        switch (ADVANCE()) {
        case '1': case '2': case '3': m_isDestructor = false; break;
        default: throw ParseException(QString::fromLatin1("Invalid ctor-dtor-name"));
        }
        break;
    case 'D':
        switch (ADVANCE()) {
        case '0': case '1': case '2': m_isDestructor = true; break;
        default: throw ParseException(QString::fromLatin1("Invalid ctor-dtor-name"));
        }
        break;
    default:
        throw ParseException(QString::fromLatin1("Invalid ctor-dtor-name"));
    }

486
487
488
489
490
491
492
    m_representation = parseState()->substitutionAt(parseState()->substitutionCount() - 1)->toByteArray();
}

QByteArray CtorDtorNameNode::description() const
{
    return "CtorDtor[isDestructor:" + bool2String(m_isDestructor)
            + ";repr=" + m_representation + ']';
493
494
}

495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
QByteArray CtorDtorNameNode::toByteArray() const
{
    QByteArray repr = m_representation;
    const int templateArgStart = repr.indexOf('<');
    if (templateArgStart != -1)
        repr.truncate(templateArgStart);
    const int prefixEnd = repr.lastIndexOf("::");
    if (prefixEnd != -1)
        repr.remove(0, prefixEnd + 2);
    if (m_isDestructor)
        repr.prepend('~');
    return repr;
}


510
511
512
513
514
515
516
517
518
519
CvQualifiersNode::CvQualifiersNode(GlobalParseState *parseState)
        : ParseTreeNode(parseState), m_hasConst(false), m_hasVolatile(false)
{
}

CvQualifiersNode::CvQualifiersNode(const CvQualifiersNode &other)
        : ParseTreeNode(other), m_hasConst(other.m_hasConst), m_hasVolatile(other.m_hasVolatile)
{
}

520
521
522
523
524
bool CvQualifiersNode::mangledRepresentationStartsWith(char c)
{
    return c == 'K' || c == 'V' || c == 'r';
}

525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
/*  <CV-qualifiers> ::= [r] [V] [K] 	# restrict (C99), volatile, const */
void CvQualifiersNode::parse()
{
    while (true) {
        if (PEEK() == 'V') {
            if (hasQualifiers())
                throw ParseException(QLatin1String("Invalid qualifiers: unexpected 'volatile'"));
            m_hasVolatile = true;
            ADVANCE();
        } else if (PEEK() == 'K') {
            if (m_hasConst)
                throw ParseException(QLatin1String("Invalid qualifiers: 'const' appears twice"));
            m_hasConst = true;
            ADVANCE();
        } else {
            break;
        }
    }
}

545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
QByteArray CvQualifiersNode::toByteArray() const
{
    QByteArray repr;
    if (m_hasConst)
        repr = "const";
    if (m_hasVolatile) {
        if (m_hasConst)
            repr +=' ';
        repr += "volatile";
    }
    return repr;
}


bool EncodingNode::mangledRepresentationStartsWith(char c)
{
    return NameNode::mangledRepresentationStartsWith(c)
            || SpecialNameNode::mangledRepresentationStartsWith(c);
}

565
566
567
568
569
570
571
572
573
574
575
576
/*
 * <encoding> ::= <name> <bare-function-type>
 *            ::= <name>
 *            ::= <special-name>
 */
void EncodingNode::parse()
{
    const char next = PEEK();
    if (NameNode::mangledRepresentationStartsWith(next)) {
        PARSE_RULE_AND_ADD_RESULT_AS_CHILD(NameNode);
        if (BareFunctionTypeNode::mangledRepresentationStartsWith(PEEK()))
            PARSE_RULE_AND_ADD_RESULT_AS_CHILD(BareFunctionTypeNode);
577
        parseState()->addSubstitution(parseState()->stackTop());
578
579
580
581
582
583
584
    } else if (SpecialNameNode::mangledRepresentationStartsWith(next)) {
        PARSE_RULE_AND_ADD_RESULT_AS_CHILD(SpecialNameNode);
    } else {
        throw ParseException(QString::fromLatin1("Invalid encoding"));
    }
}

585
586
587
588
589
QByteArray EncodingNode::toByteArray() const
{
    if (childCount() == 1)
        return CHILD_TO_BYTEARRAY(0);

590
591
592
593
    const ParseTreeNode::Ptr firstChild = MY_CHILD_AT(0);
    const NameNode::Ptr nameNode = firstChild.dynamicCast<NameNode>();
    const CvQualifiersNode::Ptr cvQualifiersNode
            = nameNode ? nameNode->cvQualifiers() : CvQualifiersNode::Ptr();
594
595

    QByteArray repr;
596
    const BareFunctionTypeNode::Ptr funcNode = DEMANGLER_CAST(BareFunctionTypeNode, MY_CHILD_AT(1));
597
    if (funcNode->hasReturnType())
598
        repr = CHILD_AT(funcNode, 0)->toByteArray() + ' ';
599
600
    if (cvQualifiersNode && cvQualifiersNode->hasQualifiers()) {
        return repr + firstChild->toByteArray() + funcNode->toByteArray() + ' '
601
602
            + cvQualifiersNode->toByteArray();
    }
603
    return repr + firstChild->toByteArray() + funcNode->toByteArray();
604
605
606
}


607
608
609
610
611
612
613
614
615
616
ExpressionNode::ExpressionNode(GlobalParseState *parseState)
        : ParseTreeNode(parseState), m_type(OtherType), m_globalNamespace(false)
{
}

ExpressionNode::ExpressionNode(const ExpressionNode &other)
        : ParseTreeNode(other), m_type(other.m_type), m_globalNamespace(other.m_globalNamespace)
{
}

617
618
619
620
bool ExpressionNode::mangledRepresentationStartsWith(char c)
{
    return OperatorNameNode::mangledRepresentationStartsWith(c)
            || TemplateParamNode::mangledRepresentationStartsWith(c)
621
            || FunctionParamNode::mangledRepresentationStartsWith(c)
622
            || ExprPrimaryNode::mangledRepresentationStartsWith(c)
623
624
            || UnresolvedNameNode::mangledRepresentationStartsWith(c)
            || c == 'c' || c == 's' || c == 'a' || c == 'd' || c == 't';
625
626
}

627
628
629
630
/*
 * <expression> ::= <operator-name> <expression>
 *              ::= <operator-name> <expression> <expression>
 *              ::= <operator-name> <expression> <expression> <expression>
631
632
 *              ::= cl <expression>+ E                            # call
 *              ::= cv <type> expression                          # conversion with one argument
633
 *              ::= cv <type> _ <expression>* E # conversion with a different number of arguments
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
 *              ::= [gs] nw <expression>* _ <type> E              # new (expr-list) type
 *              ::= [gs] nw <expression>* _ <type> <initializer>  # new (expr-list) type (init)
 *              ::= [gs] na <expression>* _ <type> E              # new[] (expr-list) type
 *              ::= [gs] na <expression>* _ <type> <initializer>  # new[] (expr-list) type (init)
 *              ::= [gs] dl <expression>                          # delete expression
 *              ::= [gs] da <expression>                          # delete[] expression
 *              ::= pp_ <expression>                              # prefix ++
 *              ::= mm_ <expression>                              # prefix --
 *              ::= ti <type>                                     # typeid (type)
 *              ::= te <expression>                               # typeid (expression)
 *              ::= dc <type> <expression>                        # dynamic_cast<type> (expression)
 *              ::= sc <type> <expression>                        # static_cast<type> (expression)
 *              ::= cc <type> <expression>                        # const_cast<type> (expression)
 *              ::= rc <type> <expression>                        # reinterpret_cast<type> (expression)
 *              ::= st <type>                                     # sizeof (a type)
 *              ::= at <type>                                     # alignof (a type)
650
651
 *              ::= <template-param>
 *              ::= <function-param>
652
653
654
655
656
657
658
659
660
661
 *              ::= dt <expression> <unresolved-name>             # expr.name
 *              ::= pt <expression> <unresolved-name>             # expr->name
 *              ::= ds <expression> <expression>                  # expr.*expr
 *              ::= sZ <template-param>                           # size of a parameter pack
 *              ::= sp <expression>                               # pack expansion
 *              ::= sZ <function-param>                           # size of a function parameter pack
 *              ::= tw <expression>                               # throw expression
 *              ::= tr                                            # throw with no operand (rethrow)
 *              ::= <unresolved-name>                             # f(p), N::f(p), ::f(p),
 *                                                                # freestanding dependent name (e.g., T::x),
662
663
664
665
666
667
 *              ::= <expr-primary>
 */
void ExpressionNode::parse()
{
   /*
    * Some of the terminals in the productions of <expression>
668
669
670
    * also appear in the productions of <operator-name>. The direct
    * productions have higher precedence and are checked first to prevent
    * erroneous parsing by the operator rule.
671
672
673
674
    */
    QByteArray str = parseState()->readAhead(2);
    if (str == "cl") {
        parseState()->advance(2);
675
        do
676
            PARSE_RULE_AND_ADD_RESULT_AS_CHILD(ExpressionNode);
677
        while (ExpressionNode::mangledRepresentationStartsWith(PEEK()));
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
        if (ADVANCE() != 'E')
            throw ParseException(QString::fromLatin1("Invalid expression"));
    } else if (str == "cv") {
        m_type = ConversionType;
        parseState()->advance(2);
        PARSE_RULE_AND_ADD_RESULT_AS_CHILD(TypeNode);
        if (PEEK() == '_') {
            ADVANCE();
            while (ExpressionNode::mangledRepresentationStartsWith(PEEK()))
                PARSE_RULE_AND_ADD_RESULT_AS_CHILD(ExpressionNode);
            if (ADVANCE() != 'E')
                throw ParseException(QString::fromLatin1("Invalid expression"));
        } else {
            PARSE_RULE_AND_ADD_RESULT_AS_CHILD(ExpressionNode);
        }
693
694
695
696
697
698
699
700
701
702
703
    } else if (str == "nw" || str == "na"
               || parseState()->readAhead(4) == "gsnw" || parseState()->readAhead(4) == "gsna") {
        if (str == "gs") {
            m_globalNamespace = true;
            parseState()->advance(2);
        }
        m_type = parseState()->readAhead(2) == "nw" ? NewType : ArrayNewType;
        parseState()->advance(2);
        while (ExpressionNode::mangledRepresentationStartsWith(PEEK()))
            PARSE_RULE_AND_ADD_RESULT_AS_CHILD(ExpressionNode);
        if (ADVANCE() != '_')
704
            throw ParseException(QLatin1String("Invalid expression"));
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
        PARSE_RULE_AND_ADD_RESULT_AS_CHILD(TypeNode);
        if (PEEK() == 'E')
            ADVANCE();
        else
            PARSE_RULE_AND_ADD_RESULT_AS_CHILD(InitializerNode);
    } else if (str == "dl" || str == "da" || parseState()->readAhead(4) == "gsdl"
               || parseState()->readAhead(4) == "gsda") {
        if (str == "gs") {
            m_globalNamespace = true;
            parseState()->advance(2);
        }
        m_type = parseState()->readAhead(2) == "dl" ? DeleteType : ArrayDeleteType;
        PARSE_RULE_AND_ADD_RESULT_AS_CHILD(ExpressionNode);
    } else if (parseState()->readAhead(3) == "pp_") {
        m_type = PrefixIncrementType;
        parseState()->advance(3);
        PARSE_RULE_AND_ADD_RESULT_AS_CHILD(ExpressionNode);
    } else if (parseState()->readAhead(3) == "mm_") {
        m_type = PrefixDecrementType;
        parseState()->advance(3);
        PARSE_RULE_AND_ADD_RESULT_AS_CHILD(ExpressionNode);
    } else if (str == "ti") {
        m_type = TypeIdTypeType;
        parseState()->advance(2);
        PARSE_RULE_AND_ADD_RESULT_AS_CHILD(TypeNode);
    } else if (str == "te") {
        m_type = TypeIdExpressionType;
        parseState()->advance(2);
        PARSE_RULE_AND_ADD_RESULT_AS_CHILD(ExpressionNode);
    } else if (str == "dc" || str == "sc" || str == "cc" || str == "rc") {
        m_type = str == "dc" ? DynamicCastType : str == "sc" ? StaticCastType : str == "cc"
                ? ConstCastType : ReinterpretCastType;
        parseState()->advance(2);
        PARSE_RULE_AND_ADD_RESULT_AS_CHILD(TypeNode);
        PARSE_RULE_AND_ADD_RESULT_AS_CHILD(ExpressionNode);
740
741
742
743
744
745
746
747
748
749
    } else if (str == "st") {
        m_type = SizeofType;
        parseState()->advance(2);
        PARSE_RULE_AND_ADD_RESULT_AS_CHILD(TypeNode);
    } else if (str == "at") {
        m_type = AlignofType;
        parseState()->advance(2);
        PARSE_RULE_AND_ADD_RESULT_AS_CHILD(TypeNode);
    } else if (str == "sZ") {
        m_type = ParameterPackSizeType;
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
        parseState()->advance(2);
        if (TemplateParamNode::mangledRepresentationStartsWith(PEEK()))
            PARSE_RULE_AND_ADD_RESULT_AS_CHILD(TemplateParamNode);
        else
            PARSE_RULE_AND_ADD_RESULT_AS_CHILD(FunctionParamNode);
    } else if (str == "dt") {
        m_type = MemberAccessType;
        parseState()->advance(2);
        PARSE_RULE_AND_ADD_RESULT_AS_CHILD(ExpressionNode);
        PARSE_RULE_AND_ADD_RESULT_AS_CHILD(UnresolvedNameNode);
    } else if (str == "pt") {
        m_type = PointerMemberAccessType;
        parseState()->advance(2);
        PARSE_RULE_AND_ADD_RESULT_AS_CHILD(ExpressionNode);
        PARSE_RULE_AND_ADD_RESULT_AS_CHILD(UnresolvedNameNode);
    } else if (str == "ds") {
        m_type = MemberDerefType;
        parseState()->advance(2);
        PARSE_RULE_AND_ADD_RESULT_AS_CHILD(ExpressionNode);
        PARSE_RULE_AND_ADD_RESULT_AS_CHILD(ExpressionNode);
    } else if (str == "ps") {
        m_type = PackExpansionType;
        parseState()->advance(2);
        PARSE_RULE_AND_ADD_RESULT_AS_CHILD(ExpressionNode);
    } else if (str == "tw") {
        m_type = ThrowType;
        parseState()->advance(2);
        PARSE_RULE_AND_ADD_RESULT_AS_CHILD(ExpressionNode);
    } else if (str == "tr") {
        m_type = RethrowType;
780
781
    } else {
        const char next = PEEK();
782
783
        if (OperatorNameNode::mangledRepresentationStartsWith(next) && str != "dn" && str != "on"
                && str != "gs" && str != "sr") {
784
785
            m_type = OperatorType;
            PARSE_RULE_AND_ADD_RESULT_AS_CHILD(OperatorNameNode);
786
            const OperatorNameNode::Ptr opNode
787
788
789
790
791
792
793
                    = DEMANGLER_CAST(OperatorNameNode, MY_CHILD_AT(childCount() - 1));

            int expressionCount;
            switch (opNode->type()) {
            case OperatorNameNode::TernaryType:
                expressionCount = 3;
                break;
794
795
796
797
798
            case OperatorNameNode::ArrayNewType: case OperatorNameNode::BinaryPlusType:
            case OperatorNameNode::BinaryMinusType: case OperatorNameNode::MultType:
            case OperatorNameNode::DivType: case OperatorNameNode::ModuloType:
            case OperatorNameNode::BitwiseAndType: case OperatorNameNode::BitwiseOrType:
            case OperatorNameNode::XorType: case OperatorNameNode::AssignType:
799
800
            case OperatorNameNode::IncrementAndAssignType:
            case OperatorNameNode::DecrementAndAssignType:
801
            case OperatorNameNode::MultAndAssignType: case OperatorNameNode::DivAndAssignType:
802
803
804
            case OperatorNameNode::ModuloAndAssignType:
            case OperatorNameNode::BitwiseAndAndAssignType:
            case OperatorNameNode::BitwiseOrAndAssignType:
805
806
807
808
809
810
811
812
            case OperatorNameNode::XorAndAssignType: case OperatorNameNode::LeftShiftType:
            case OperatorNameNode::RightShiftType: case OperatorNameNode::LeftShiftAndAssignType:
            case OperatorNameNode::RightShiftAndAssignType: case OperatorNameNode::EqualsType:
            case OperatorNameNode::NotEqualsType: case OperatorNameNode::LessType:
            case OperatorNameNode::GreaterType: case OperatorNameNode::LessEqualType:
            case OperatorNameNode::GreaterEqualType: case OperatorNameNode::LogicalAndType:
            case OperatorNameNode::LogicalOrType: case OperatorNameNode::CommaType:
            case OperatorNameNode::ArrowStarType: case OperatorNameNode::ArrowType:
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
            case OperatorNameNode::IndexType:
                expressionCount = 2;
                break;
            default:
                expressionCount = 1;
            }

            for (int i = 0; i < expressionCount; ++i)
                PARSE_RULE_AND_ADD_RESULT_AS_CHILD(ExpressionNode);
        } else if (TemplateParamNode::mangledRepresentationStartsWith(next)) {
            PARSE_RULE_AND_ADD_RESULT_AS_CHILD(TemplateParamNode);
        } else if (FunctionParamNode::mangledRepresentationStartsWith(next)) {
            PARSE_RULE_AND_ADD_RESULT_AS_CHILD(FunctionParamNode);
        } else if (ExprPrimaryNode::mangledRepresentationStartsWith(next)) {
            PARSE_RULE_AND_ADD_RESULT_AS_CHILD(ExprPrimaryNode);
828
829
        } else if (UnresolvedNameNode::mangledRepresentationStartsWith(next)) {
            PARSE_RULE_AND_ADD_RESULT_AS_CHILD(UnresolvedNameNode);
830
831
832
833
834
835
        } else {
            throw ParseException(QString::fromLatin1("Invalid expression"));
        }
    }
}

836
837
838
839
840
841
QByteArray ExpressionNode::description() const
{
    return "Expression[global:" + bool2String(m_globalNamespace)
            + ";type:" + QByteArray::number(m_type) + ']';
}

842
843
844
845
846
847
848
849
850
851
852
QByteArray ExpressionNode::toByteArray() const
{
    QByteArray repr;

    switch (m_type) {
    case ConversionType:
        repr = CHILD_TO_BYTEARRAY(0) + '(';
        for (int i = 1; i < childCount(); ++i)
            repr += CHILD_TO_BYTEARRAY(i);
        repr += ')';
        break;
853
854
855
856
857
858
859
860
861
862
863
864
865
    case NewType: case ArrayNewType: {
        if (m_globalNamespace)
            repr += "::";
        repr += "new";
        if (m_type == ArrayNewType)
            repr += "[]";
        repr += ' ';

        // TODO: I don't understand what the first expression list means. Putting it into
        // parentheses for now.
        QByteArray exprList;
        int i = 0;
        for (; i < childCount(); ++i) {
866
            if (!MY_CHILD_AT(i).dynamicCast<ExpressionNode>())
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
                break;
            if (i > 0)
                repr += ", ";
            repr += CHILD_TO_BYTEARRAY(i);
        }
        if (i > 0)
            repr.append('(').append(exprList).append(')');

        repr += CHILD_TO_BYTEARRAY(i++); // <type>
        if (i < childCount())
            repr += CHILD_TO_BYTEARRAY(i); // <initializer>
        break;
    }
    case DeleteType: case ArrayDeleteType:
        if (m_globalNamespace)
            repr += "::";
        repr += "delete";
        if (m_type == ArrayDeleteType)
            repr += "[]";
        repr.append(' ').append(CHILD_TO_BYTEARRAY(0));
        break;
    case PrefixIncrementType:
        repr.append("++").append(CHILD_TO_BYTEARRAY(0));
        break;
    case PrefixDecrementType:
        repr.append("--").append(CHILD_TO_BYTEARRAY(0));
        break;
    case TypeIdTypeType: case TypeIdExpressionType:
        repr.append("typeid(").append(CHILD_TO_BYTEARRAY(0)).append(')');
        break;
    case DynamicCastType: case StaticCastType: case ConstCastType: case ReinterpretCastType:
        if (m_type == DynamicCastType)
            repr += "dynamic";
        else if (m_type == StaticCastType)
            repr += "static";
        else if (m_type == ConstCastType)
            repr += "const";
        else
            repr += "reinterpret";
        repr.append("_cast<").append(CHILD_TO_BYTEARRAY(0)).append(">(")
                .append(CHILD_TO_BYTEARRAY(1)).append(')');
        break;
909
910
911
912
913
914
    case SizeofType:
        repr = "sizeof(" + CHILD_TO_BYTEARRAY(0) + ')';
        break;
    case AlignofType:
        repr = "alignof(" + CHILD_TO_BYTEARRAY(0) + ')';
        break;
915
916
917
918
919
920
921
922
923
    case MemberAccessType:
        repr.append(CHILD_TO_BYTEARRAY(0)).append('.').append(CHILD_TO_BYTEARRAY(1));
        break;
    case PointerMemberAccessType:
        repr.append(CHILD_TO_BYTEARRAY(0)).append("->").append(CHILD_TO_BYTEARRAY(1));
        break;
    case MemberDerefType:
        repr.append(CHILD_TO_BYTEARRAY(0)).append(".*").append(CHILD_TO_BYTEARRAY(1));
        break;
924
    case ParameterPackSizeType:
925
        repr = "sizeof...(" + CHILD_TO_BYTEARRAY(0) + ')';
926
927
        break;
    case PackExpansionType:
928
        repr = CHILD_TO_BYTEARRAY(0) + "...";
929
930
931
932
933
934
935
        break;
    case ThrowType:
        repr.append("throw ").append(CHILD_TO_BYTEARRAY(0));
        break;
    case RethrowType:
        repr.append("throw");
        break;
936
    case OperatorType: {
937
        const OperatorNameNode::Ptr opNode = DEMANGLER_CAST(OperatorNameNode, MY_CHILD_AT(0));
938
        switch (opNode->type()) {
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
        case OperatorNameNode::CallType:
            repr = CHILD_TO_BYTEARRAY(1) + opNode->toByteArray();
            break;
        case OperatorNameNode::SizeofExprType: case OperatorNameNode::AlignofExprType:
            repr = opNode->toByteArray() + '(' + CHILD_TO_BYTEARRAY(1) + ')';
            break;
        case OperatorNameNode::ArrayNewType:
            repr = "new " + CHILD_TO_BYTEARRAY(1) + '[' + CHILD_TO_BYTEARRAY(2) + ']';
            break;
        case OperatorNameNode::IndexType:
            repr = CHILD_TO_BYTEARRAY(1) + '[' + CHILD_TO_BYTEARRAY(2) + ']';
            break;
        case OperatorNameNode::TernaryType:
            repr = CHILD_TO_BYTEARRAY(1) + " ? " + CHILD_TO_BYTEARRAY(2) + " : " + CHILD_TO_BYTEARRAY(3);
            break;
        case OperatorNameNode::ArrowStarType: case OperatorNameNode::ArrowType:
            repr = CHILD_TO_BYTEARRAY(1) + opNode->toByteArray() + CHILD_TO_BYTEARRAY(2);
            break;
        case OperatorNameNode::BinaryPlusType:
        case OperatorNameNode::BinaryMinusType:
        case OperatorNameNode::MultType:
        case OperatorNameNode::DivType:
        case OperatorNameNode::ModuloType:
        case OperatorNameNode::BitwiseAndType:
        case OperatorNameNode::BitwiseOrType:
        case OperatorNameNode::XorType:
        case OperatorNameNode::AssignType:
        case OperatorNameNode::IncrementAndAssignType:
        case OperatorNameNode::DecrementAndAssignType:
        case OperatorNameNode::MultAndAssignType:
        case OperatorNameNode::DivAndAssignType:
        case OperatorNameNode::ModuloAndAssignType:
        case OperatorNameNode::BitwiseAndAndAssignType:
        case OperatorNameNode::BitwiseOrAndAssignType:
        case OperatorNameNode::XorAndAssignType:
        case OperatorNameNode::LeftShiftType:
        case OperatorNameNode::RightShiftType:
        case OperatorNameNode::LeftShiftAndAssignType:
        case OperatorNameNode::RightShiftAndAssignType:
        case OperatorNameNode::EqualsType:
        case OperatorNameNode::NotEqualsType:
        case OperatorNameNode::LessType:
        case OperatorNameNode::GreaterType:
        case OperatorNameNode::LessEqualType:
        case OperatorNameNode::GreaterEqualType:
        case OperatorNameNode::LogicalAndType:
        case OperatorNameNode::LogicalOrType:
        case OperatorNameNode::CommaType:
            repr = CHILD_TO_BYTEARRAY(1) + ' ' + opNode->toByteArray() + ' ' + CHILD_TO_BYTEARRAY(2);
            break;
        case OperatorNameNode::NewType:
        case OperatorNameNode::DeleteType:
        case OperatorNameNode::ArrayDeleteType:
            repr = opNode->toByteArray() + ' ' + CHILD_TO_BYTEARRAY(1);
            break;
        default: // Other unary Operators;
            repr = opNode->toByteArray() + CHILD_TO_BYTEARRAY(1);
        }
        break;
    }
    case OtherType:
        repr = pasteAllChildren();
    }

    return repr;
}


1007
1008
1009
1010
1011
OperatorNameNode::OperatorNameNode(const OperatorNameNode &other)
        : ParseTreeNode(other), m_type(other.m_type)
{
}

1012
1013
1014
1015
1016
bool OperatorNameNode::mangledRepresentationStartsWith(char c)
{
    return strchr("ndpacmroelgiqsv", c);
}

1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
/*
 * <operator-name> ::= nw       # new
 *                 ::= na        # new[]
 *                 ::= dl        # delete
 *                 ::= da        # delete[]
 *                 ::= ps        # + (unary)
 *                 ::= ng        # - (unary)
 *                 ::= ad        # & (unary)
 *                 ::= de        # * (unary)
 *                 ::= co        # ~
 *                 ::= pl        # +
 *                 ::= mi        # -
 *                 ::= ml        # *
 *                 ::= dv        # /
 *                 ::= rm        # %
 *                 ::= an        # &
 *                 ::= or        # |
 *                 ::= eo        # ^
 *                 ::= aS        # =
 *                 ::= pL        # +=
 *                 ::= mI        # -=
 *                 ::= mL        # *=
 *                 ::= dV        # /=
 *                 ::= rM        # %=
 *                 ::= aN        # &=
 *                 ::= oR        # |=
 *                 ::= eO        # ^=
 *                 ::= ls        # <<
 *                 ::= rs        # >>
 *                 ::= lS        # <<=
 *                 ::= rS        # >>=
 *                 ::= eq        # ==
 *                 ::= ne        # !=
 *                 ::= lt        # <
 *                 ::= gt        # >
 *                 ::= le        # <=
 *                 ::= ge        # >=
 *                 ::= nt        # !
 *                 ::= aa        # &&
 *                 ::= oo        # ||
 *                 ::= pp        # ++
 *                 ::= mm        # --
 *                 ::= cm        # ,
 *                 ::= pm        # ->*
 *                 ::= pt        # ->
 *                 ::= cl        # ()
 *                 ::= ix        # []
 *                 ::= qu        # ?
 *                 ::= st        # sizeof (a type)
 *                 ::= sz        # sizeof (an expression)
 *                 ::= at        # alignof (a type)
 *                 ::= az        # alignof (an expression)
 *                 ::= cv <type> # (cast)
 *                 ::= v <digit> <source-name>   # vendor extended operator
 */
void OperatorNameNode::parse()
{
    if (PEEK() == 'v') {
        m_type = VendorType;
        ADVANCE();
        const int digit = ADVANCE();
        if (!std::isdigit(digit))
            throw ParseException(QString::fromLatin1("Invalid digit"));
        // Throw away digit for now; we don't know what to do with it anyway.
        PARSE_RULE_AND_ADD_RESULT_AS_CHILD(SourceNameNode);
    } else {
        const QByteArray id = parseState()->readAhead(2);
        parseState()->advance(2);
        if (id == "cv") {
            m_type = CastType;
            PARSE_RULE_AND_ADD_RESULT_AS_CHILD(TypeNode);
        } else if (id == "nw") {
            m_type = NewType;
        } else if (id == "na") {
            m_type = ArrayNewType;
        } else if (id == "dl") {
            m_type = DeleteType;
        } else if (id == "da") {
            m_type = ArrayDeleteType;
        } else if (id == "ps") {
            m_type = UnaryPlusType;
        } else if (id == "ng") {
            m_type = UnaryMinusType;
        } else if (id == "ad") {
            m_type = UnaryAmpersandType;
        } else if (id == "de") {
            m_type = UnaryStarType;
        } else if (id == "co") {
            m_type = BitwiseNotType;
        } else if (id == "pl") {
            m_type = BinaryPlusType;
        } else if (id == "mi") {
            m_type = BinaryMinusType;
        } else if (id == "ml") {
            m_type = MultType;
        } else if (id == "dv") {
            m_type = DivType;
        } else if (id == "rm") {
            m_type = ModuloType;
        } else if (id == "an") {
            m_type = BitwiseAndType;
        } else if (id == "or") {
            m_type = BitwiseOrType;
        } else if (id == "eo") {
            m_type = XorType;
        } else if (id == "aS") {
            m_type = AssignType;
        } else if (id == "pL") {
            m_type = IncrementAndAssignType;
        } else if (id == "mI") {
            m_type = DecrementAndAssignType;
        } else if (id == "mL") {
            m_type = MultAndAssignType;
        } else if (id == "dV") {
            m_type = DivAndAssignType;
        } else if (id == "rM") {
            m_type = ModuloAndAssignType;
        } else if (id == "aN") {
            m_type = BitwiseAndAndAssignType;
        } else if (id == "oR") {
            m_type = BitwiseOrAndAssignType;
        } else if (id == "eO") {
            m_type = XorAndAssignType;
        } else if (id == "ls") {
            m_type = LeftShiftType;
        } else if (id == "rs") {
            m_type = RightShiftType;
        } else if (id == "lS") {
            m_type = LeftShiftAndAssignType;
        } else if (id == "rS") {
            m_type = RightShiftAndAssignType;
        } else if (id == "eq") {
            m_type = EqualsType;
        } else if (id == "ne") {
            m_type = NotEqualsType;
        } else if (id == "lt") {
            m_type = LessType;
        } else if (id == "gt") {
            m_type = GreaterType;
        } else if (id == "le") {
            m_type = LessEqualType;
        } else if (id == "ge") {
            m_type = GreaterEqualType;
        } else if (id == "nt") {
            m_type = LogicalNotType;
        } else if (id == "aa") {
            m_type = LogicalAndType;
        } else if (id == "oo") {
            m_type = LogicalOrType;
        } else if (id == "pp") {
            m_type = IncrementType;
        } else if (id == "mm") {
            m_type = DecrementType;
        } else if (id == "cm") {
            m_type = CommaType;
        } else if (id == "pm") {
            m_type = ArrowStarType;
        } else if (id == "pt") {
            m_type = ArrowType;
        } else if (id == "cl") {
            m_type = CallType;
        } else if (id == "ix") {
            m_type = IndexType;
        } else if (id == "qu") {
            m_type = TernaryType;
        } else if (id == "st") {
            m_type = SizeofTypeType;
        } else if (id == "sz") {
            m_type = SizeofExprType;
        } else if (id == "at") {
            m_type = AlignofTypeType;
        } else if (id == "az") {
            m_type = AlignofExprType;
        } else {
1191
            throw ParseException(QString::fromLatin1("Invalid operator encoding \"%1\"")
1192
1193
1194
1195
1196
                    .arg(QString::fromLocal8Bit(id)));
        }
    }
}

1197
1198
1199
1200
1201
QByteArray OperatorNameNode::description() const
{
    return "OperatorName[type:" + toByteArray() + ']';
}

1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
QByteArray OperatorNameNode::toByteArray() const
{
    switch (m_type) {
    case NewType: return "new";
    case ArrayNewType: return "new[]";
    case DeleteType: return "delete";
    case ArrayDeleteType: return "delete[]";
    case UnaryPlusType: case BinaryPlusType: return "+";
    case UnaryMinusType: case BinaryMinusType: return "-";
    case UnaryAmpersandType: case BitwiseAndType: return "&";
    case UnaryStarType: case MultType: return "*";
    case BitwiseNotType: return "~";
    case DivType: return "/";
    case ModuloType: return "%";
    case BitwiseOrType: return "|";
    case XorType: return "^";
    case AssignType: return "=";
    case IncrementAndAssignType: return "+=";
    case DecrementAndAssignType: return "-=";
    case MultAndAssignType: return "*=";
    case DivAndAssignType: return "/=";
    case ModuloAndAssignType: return "%=";
    case BitwiseAndAndAssignType: return "&=";
    case BitwiseOrAndAssignType: return "|=";
    case XorAndAssignType: return "^=";
    case LeftShiftType: return "<<";
    case RightShiftType: return ">>";
    case LeftShiftAndAssignType: return "<<=";
    case RightShiftAndAssignType: return ">>=";
    case EqualsType: return "==";
    case NotEqualsType: return "!=";
    case LessType: return "<";
    case GreaterType: return ">";
    case LessEqualType: return "<=";
    case GreaterEqualType: return ">=";
    case LogicalNotType: return "!";
    case LogicalAndType: return "&&";
    case LogicalOrType: return "||";
    case IncrementType: return "++";
    case DecrementType: return "--";
    case CommaType: return ",";
    case ArrowStarType: return "->*";
    case ArrowType: return "->";
    case CallType: return "()";
    case IndexType: return "[]";
    case TernaryType: return "?";
    case SizeofTypeType: case SizeofExprType: return "sizeof";
    case AlignofTypeType: case AlignofExprType: return "alignof";
    case CastType: return ' ' + CHILD_TO_BYTEARRAY(0);
    case VendorType: return "[vendor extended operator]";
    }

    DEMANGLER_ASSERT(false);
    return QByteArray();
}

1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268

ExprPrimaryNode::ExprPrimaryNode(GlobalParseState *parseState)
        : ParseTreeNode(parseState), m_isNullPtr(false)
{
}

ExprPrimaryNode::ExprPrimaryNode(const ExprPrimaryNode &other)
        : ParseTreeNode(other), m_suffix(other.m_suffix), m_isNullPtr(other.m_isNullPtr)
{
}

1269
1270
1271
1272
1273
bool ExprPrimaryNode::mangledRepresentationStartsWith(char c)
{
    return c == 'L';
}

1274
1275
1276
/*
 * <expr-primary> ::= L <type> <number> E            # integer literal
 *                ::= L <type> <float> E             # floating literal
1277
1278
1279
 *                ::= L <string type>                # string literal
 *                ::= L <nullptr type> E             # nullptr literal (i.e., "LDnE")
 *                ::= L <type> <real-part float> _ <imag-part float> E   # complex floating point literal (C 2000)
1280
 *                ::= L <mangled-name> E             # external name
1281
 * Note that we ignore C 2000 features.
1282
1283
1284
1285
1286
 */
void ExprPrimaryNode::parse()
{
    if (!ExprPrimaryNode::mangledRepresentationStartsWith(ADVANCE()))
        throw ParseException(QString::fromLatin1("Invalid primary expression"));
1287
    bool needsSuffix = true;
1288
1289
    const char next = PEEK();
    if (TypeNode::mangledRepresentationStartsWith(next)) {
1290
1291
1292
1293
        const ParseTreeNode::Ptr topLevelTypeNode = parseRule<TypeNode>(parseState());
        const BuiltinTypeNode::Ptr typeNode = topLevelTypeNode->childCount() == 0
                ? BuiltinTypeNode::Ptr()
                : CHILD_AT(topLevelTypeNode, 0).dynamicCast<BuiltinTypeNode>();
1294
1295
1296
        if (!typeNode)
            throw ParseException(QLatin1String("Invalid type in expr-primary"));

1297
        switch (typeNode->type()) {
1298
        case BuiltinTypeNode::UnsignedShortType:
1299
        case BuiltinTypeNode::UnsignedIntType:
1300
1301
1302
1303
1304
            m_suffix = "U"; // Fall-through.
        case BuiltinTypeNode::SignedShortType:
        case BuiltinTypeNode::SignedIntType:
            PARSE_RULE_AND_ADD_RESULT_AS_CHILD(NumberNode);
            break;
1305
        case BuiltinTypeNode::UnsignedLongType:
1306
1307
1308
            m_suffix = "U"; // Fall-through.
        case BuiltinTypeNode::SignedLongType:
            m_suffix = "L";
1309
1310
            PARSE_RULE_AND_ADD_RESULT_AS_CHILD(NumberNode);
            break;
1311
1312
1313
1314
1315
1316
1317
1318
1319
        case BuiltinTypeNode::UnsignedLongLongType:
            m_suffix = "U"; // Fall-through.
        case BuiltinTypeNode::SignedLongLongType:
            m_suffix = "LL";
            PARSE_RULE_AND_ADD_RESULT_AS_CHILD(NumberNode);
            break;
        case BuiltinTypeNode::FloatType:
            m_suffix = "f"; // Fall-through.
        case BuiltinTypeNode::DoubleType:
1320
1321
            PARSE_RULE_AND_ADD_RESULT_AS_CHILD(FloatValueNode);
            break;
1322
1323
1324
1325
1326
        case BuiltinTypeNode::NullPtrType:
            m_isNullPtr = true;
            break;
        case BuiltinTypeNode::PlainCharType: case BuiltinTypeNode::WCharType:
        case BuiltinTypeNode::Char16Type: case BuiltinTypeNode::Char32Type:
1327
            needsSuffix = false;
1328
            break; // string type
1329
1330
1331
        default:
            throw ParseException(QString::fromLatin1("Invalid type in expr-primary"));
        }
1332
        parseState()->popFromStack(); // No need to keep the type node in the tree.
1333
    } else if (MangledNameRule::mangledRepresentationStartsWith(next)) {
1334
        MangledNameRule::parse(parseState(), parseState()->stackTop());
1335
1336
1337
    } else {
        throw ParseException(QString::fromLatin1("Invalid expr-primary"));
    }
1338
    if (needsSuffix && ADVANCE() != 'E')
1339
1340
1341
        throw ParseException(QString::fromLatin1("Invalid expr-primary"));
}

1342
1343
1344
1345
1346
QByteArray ExprPrimaryNode::description() const
{
    return "ExprPrimary[m_suffix:" + m_suffix + ";m_isNullPtr:" + bool2String(m_isNullPtr) + ']';
}

1347
1348
QByteArray ExprPrimaryNode::toByteArray() const
{
1349
1350
1351
    if (m_isNullPtr)
        return "nullptr";
    return CHILD_TO_BYTEARRAY(0) + m_suffix;
1352
1353
}

1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364

FunctionTypeNode::FunctionTypeNode(GlobalParseState *parseState)
        : ParseTreeNode(parseState), m_isExternC(false)
{
}

FunctionTypeNode::FunctionTypeNode(const FunctionTypeNode &other)
        : ParseTreeNode(other), m_isExternC(other.isExternC())
{
}

1365
1366
1367
1368
1369
bool FunctionTypeNode::mangledRepresentationStartsWith(char c)
{
    return c == 'F';
}

1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
/* <function-type> ::= F [Y] <bare-function-type> E */
void FunctionTypeNode::parse()
{
    if (!mangledRepresentationStartsWith(ADVANCE()))
        throw ParseException(QString::fromLatin1("Invalid function type"));

    if (PEEK() == 'Y') {
        ADVANCE();
        m_isExternC = true;
    }

    PARSE_RULE_AND_ADD_RESULT_AS_CHILD(BareFunctionTypeNode);
    if (ADVANCE() != 'E')
        throw ParseException(QString::fromLatin1("Invalid function type"));
}

1386
1387
1388
1389
1390
QByteArray FunctionTypeNode::description() const
{
    return "FunctionType[isExternC:" + bool2String(m_isExternC) + ']';
}

1391
1392
1393
1394
1395
1396
QByteArray FunctionTypeNode::toByteArray() const
{
    return QByteArray(); // Not enough knowledge here to generate a string representation.
}


1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
LocalNameNode::LocalNameNode(GlobalParseState *parseState)
        : ParseTreeNode(parseState), m_isStringLiteral(false), m_isDefaultArg(false)
{
}

LocalNameNode::LocalNameNode(const LocalNameNode &other)
        : ParseTreeNode(other),
          m_isStringLiteral(other.m_isStringLiteral),
          m_isDefaultArg(other.m_isDefaultArg)
{
}

1409
1410
1411
1412
1413
bool LocalNameNode::mangledRepresentationStartsWith(char c)
{
    return c == 'Z';
}

1414
1415
1416
/*
 * <local-name> := Z <encoding> E <name> [<discriminator>]
 *              := Z <encoding> E s [<discriminator>]
1417
 *              := Z <encoding> Ed [ <non-negative number> ] _ <name>
1418
1419
 *
 * Note that <name> can start with 's', so we need to do read-ahead.
1420
1421
 * Also, <name> can start with 'd' (via <operator-name>).
 * The last rule is for member functions with default closure type arguments.
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
 */
void LocalNameNode::parse()
{
    if (!mangledRepresentationStartsWith(ADVANCE()))
        throw ParseException(QString::fromLatin1("Invalid local-name"));

    PARSE_RULE_AND_ADD_RESULT_AS_CHILD(EncodingNode);

    if (ADVANCE() != 'E')
        throw ParseException(QString::fromLatin1("Invalid local-name"));

    QByteArray str = parseState()->readAhead(2);
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
    const char next = PEEK();
    if (next == 'd' && str != "dl" && str != "da" && str != "de" && str != "dv" && str != "dV") {
        m_isDefaultArg = true;
        ADVANCE();
        if (NonNegativeNumberNode<10>::mangledRepresentationStartsWith(PEEK()))
            PARSE_RULE_AND_ADD_RESULT_AS_CHILD(NonNegativeNumberNode<10>);
        if (ADVANCE() != '_')
            throw ParseException(QString::fromLatin1("Invalid local-name"));
        PARSE_RULE_AND_ADD_RESULT_AS_CHILD(NameNode);
    } else if (str == "sp" || str == "sr" || str == "st" || str == "sz" || str == "sZ"
1444
1445
1446
1447
1448
1449
1450
1451
            || (next != 's' && NameNode::mangledRepresentationStartsWith(next))) {
        PARSE_RULE_AND_ADD_RESULT_AS_CHILD(NameNode);
    } else if (next == 's') {
        m_isStringLiteral = true;
        ADVANCE();
    } else {
        throw ParseException(QString::fromLatin1("Invalid local-name"));
    }
1452
    if (DiscriminatorRule::mangledRepresentationStartsWith(PEEK()))
1453
1454
1455
1456
1457
1458
1459
        DiscriminatorRule::parse(parseState());
}

QByteArray LocalNameNode::description() const
{
    return "LocalName[isStringLiteral:" + bool2String(m_isStringLiteral) + ";isDefaultArg:"
            + bool2String(m_isDefaultArg) + ']';
1460
1461
}

1462
1463
1464
1465
QByteArray LocalNameNode::toByteArray() const
{
    QByteArray name;
    bool hasDiscriminator;
1466
    if (m_isDefaultArg) {
1467
1468
        const ParseTreeNode::Ptr encodingNode = MY_CHILD_AT(0);
        const BareFunctionTypeNode::Ptr funcNode
1469
1470
1471
                = DEMANGLER_CAST(BareFunctionTypeNode, CHILD_AT(encodingNode, 1));
        const int functionParamCount
                = funcNode->hasReturnType() ? funcNode->childCount() - 1 : funcNode->childCount();
1472
        const NonNegativeNumberNode<10>::Ptr numberNode
1473
                = MY_CHILD_AT(1).dynamicCast<NonNegativeNumberNode<10> >();
1474
1475
1476
1477
1478
1479
1480
1481

        // "_" means last argument, "n" means (n+1)th to last.
        // Note that c++filt in binutils 2.22 does this wrong.
        const int argNumber = functionParamCount - (numberNode ? numberNode->number() + 1 : 0);

        name = encodingNode->toByteArray();
        name.append("::{default arg#").append(QByteArray::number(argNumber)).append("}::")
                .append(MY_CHILD_AT(childCount() - 1)->toByteArray());
1482
        hasDiscriminator = false;
1483
1484
    } else if (m_isStringLiteral) {
        name = CHILD_TO_BYTEARRAY(0) + "::{string literal}";
1485
1486
1487
1488
1489
1490
        hasDiscriminator = childCount() == 2;
    } else {
        name = CHILD_TO_BYTEARRAY(0) + "::" + CHILD_TO_BYTEARRAY(1);
        hasDiscriminator = childCount() == 3;
    }
    if (hasDiscriminator) {
1491
1492
1493
1494
        // TODO: Does this information serve any purpose? Names seem to demangle fine without printing anything here.
//        const QByteArray discriminator = MY_CHILD_AT(childCount() - 1)->toByteArray();
//        const int rawDiscriminatorValue = discriminator.toInt();
//        name += " (occurrence number " + QByteArray::number(rawDiscriminatorValue - 2) + ')';
1495
1496
1497
1498
    }
    return name;
}

1499
1500
bool LocalNameNode::isTemplate() const
{
1501
    if (childCount() == 1 || MY_CHILD_AT(1).dynamicCast<NonNegativeNumberNode<10> >())
1502
1503
1504
1505
1506
1507
        return false;
    return DEMANGLER_CAST(NameNode, MY_CHILD_AT(1))->isTemplate();
}

bool LocalNameNode::isConstructorOrDestructorOrConversionOperator() const
{
1508
    if (childCount() == 1 || MY_CHILD_AT(1).dynamicCast<NonNegativeNumberNode<10> >())
1509
1510
1511
1512
        return false;
    return DEMANGLER_CAST(NameNode, MY_CHILD_AT(1))->isConstructorOrDestructorOrConversionOperator();
}

1513
CvQualifiersNode::Ptr LocalNameNode::cvQualifiers() const
1514
1515
{
    if (m_isDefaultArg)
1516
1517
1518
1519
        return DEMANGLER_CAST(NameNode, MY_CHILD_AT(childCount() - 1))->cvQualifiers();
    if (childCount() == 1 || MY_CHILD_AT(1).dynamicCast<NonNegativeNumberNode<10> >())
        return CvQualifiersNode::Ptr();
    return DEMANGLER_CAST(NameNode, MY_CHILD_AT(1))->cvQualifiers();
1520
1521
}

1522

1523
bool MangledNameRule::mangledRepresentationStartsWith(char c)
1524
1525
1526
1527
{
    return c == '_';
}

1528
1529
1530
1531
1532
1533
/*
 * Grammar: http://www.codesourcery.com/public/cxx-abi/abi.html#mangling
 * The grammar as given there is not LL(k), so a number of transformations
 * were necessary, which we will document at the respective parsing function.
 * <mangled-name> ::= _Z <encoding>
 */
1534
void MangledNameRule::parse(GlobalParseState *parseState, const ParseTreeNode::Ptr &parentNode)
1535
{
1536
1537
    parseState->advance(2);
    PARSE_RULE_AND_ADD_RESULT_AS_CHILD_TO_NODE(EncodingNode, parseState, parentNode);
1538
1539
1540
}


1541
1542
1543
1544
1545
SourceNameNode::SourceNameNode(const SourceNameNode &other)
        : ParseTreeNode(other), m_name(other.m_name)
{
}

1546
1547
1548
1549
1550
bool SourceNameNode::mangledRepresentationStartsWith(char c)
{
    return strchr("123456789", c);
}

1551
1552
1553
1554
1555
1556
1557
1558
/* <source-name> ::= <number> <identifier> */
void SourceNameNode::parse()
{
    const int idLen = getNonNegativeNumber<10>(parseState());
    m_name = parseState()->readAhead(idLen);
    parseState()->advance(idLen);
}