summaryrefslogtreecommitdiffstats
path: root/src/qdoc/parameters.cpp
blob: 6e9c2dd9e04a378af89e8485f8c9a9d148551cff (plain)
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
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
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
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
/****************************************************************************
**
** Copyright (C) 2016 The Qt Company Ltd.
** Contact: https://www.qt.io/licensing/
**
** This file is part of the tools applications of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:GPL-EXCEPT$
** 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 The Qt Company. For licensing terms
** and conditions see https://www.qt.io/terms-conditions. For further
** information use the contact form at https://www.qt.io/contact-us.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3 as published by the Free Software
** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
** included in the packaging of this file. Please review the following
** information to ensure the GNU General Public License requirements will
** be met: https://www.gnu.org/licenses/gpl-3.0.html.
**
** $QT_END_LICENSE$
**
****************************************************************************/

#include "parameters.h"
#include "tokenizer.h"
#include "codechunk.h"
#include "generator.h"

QT_BEGIN_NAMESPACE

QRegExp Parameters::varComment_("/\\*\\s*([a-zA-Z_0-9]+)\\s*\\*/");

/*!
  \class Parameter
  \brief The Parameter class describes one function parameter.

  A parameter can be a function parameter or a macro parameter.
  It has a name, a data type, and an optional default value.
  These are all stored as strings so they can be compared with
  a parameter in a function signature to find a match.
 */

/*!
  \fn Parameter::Parameter(const QString &type, const QString &name, const QString &defaultValue)

  Constructs the parameter from the \a type, the optional \a name,
  and the optional \a defaultValue.
 */

/*!
  Reconstructs the text signature for the parameter and returns
  it. If \a includeValue is true and there is a default value,
  the default value is appended with '='.
 */
QString Parameter::signature(bool includeValue) const
{
    QString p = type_;
    if (!p.endsWith(QChar('*')) && !p.endsWith(QChar('&')) && !p.endsWith(QChar(' ')))
        p += QLatin1Char(' ');
    p += name_;
    if (includeValue && !defaultValue_.isEmpty())
        p += " = " + defaultValue_;
    return p;
}

/*!
  \class Parameters

  \brief A class for parsing and managing a function parameter list

  The constructor is passed a string that is the text inside the
  parentheses of a function declaration. The constructor parses
  the parameter list into a vector of class Parameter.

  The Parameters object is then used in function searches to find
  the correct function node given the function name and the signature
  of its parameters.
 */

Parameters::Parameters()
  : valid_(true), privateSignal_(false), tok_(0), tokenizer_(0)
{
    // nothing.
}

Parameters::Parameters(const QString &signature)
    : valid_(true), privateSignal_(false), tok_(0), tokenizer_(0)
{
    if (!signature.isEmpty()) {
        if (!parse(signature)) {
            parameters_.clear();
            valid_ = false;
        }
    }
}

/*!
  Get the next token from the string being parsed and store
  it in the token variable.
 */
void Parameters::readToken()
{
    tok_ = tokenizer_->getToken();
}

/*!
  Return the current lexeme from the string being parsed.
 */
QString Parameters::lexeme()
{
    return tokenizer_->lexeme();
}

/*!
  Return the previous lexeme read from the string being parsed.
 */
QString Parameters::previousLexeme()
{
    return tokenizer_->previousLexeme();
}

/*!
  If the current token is \a target, read the next token and
  return \c true. Otherwise, return false without reading the
  next token.
 */
bool Parameters::match(int target)
{
    if (tok_ == target) {
        readToken();
        return true;
    }
    return false;
}

/*!
  Match a template clause in angle brackets, append it to the
  \a type, and return \c true. If there is no template clause,
  or if an error is detected, return \c false.
 */
void Parameters::matchTemplateAngles(CodeChunk &type)
{
    if (tok_ == Tok_LeftAngle) {
        int leftAngleDepth = 0;
        int parenAndBraceDepth = 0;
        do {
            if (tok_ == Tok_LeftAngle) {
                leftAngleDepth++;
            }
            else if (tok_ == Tok_RightAngle) {
                leftAngleDepth--;
            }
            else if (tok_ == Tok_LeftParen || tok_ == Tok_LeftBrace) {
                ++parenAndBraceDepth;
            }
            else if (tok_ == Tok_RightParen || tok_ == Tok_RightBrace) {
                if (--parenAndBraceDepth < 0)
                    return;
            }
            type.append(lexeme());
            readToken();
        } while (leftAngleDepth > 0 && tok_ != Tok_Eoi);
    }
}

/*!
  Uses the current tokenizer to parse the \a name and \a type
  of the parameter.
 */
bool Parameters::matchTypeAndName(CodeChunk &type, QString &name, bool qProp)
{
    /*
      This code is really hard to follow... sorry. The loop is there to match
      Alpha::Beta::Gamma::...::Omega.
    */
    for (;;) {
        bool virgin = true;

        if (tok_ != Tok_Ident) {
            /*
              There is special processing for 'Foo::operator int()'
              and such elsewhere. This is the only case where we
              return something with a trailing gulbrandsen ('Foo::').
            */
            if (tok_ == Tok_operator)
                return true;

            /*
              People may write 'const unsigned short' or
              'short unsigned const' or any other permutation.
            */
            while (match(Tok_const) || match(Tok_volatile))
                type.append(previousLexeme());
            QString pending;
            while (tok_ == Tok_signed || tok_ == Tok_int || tok_ == Tok_unsigned ||
                   tok_ == Tok_short || tok_ == Tok_long || tok_ == Tok_int64) {
                if (tok_ == Tok_signed)
                    pending = lexeme();
                else {
                    if (tok_ == Tok_unsigned && !pending.isEmpty())
                        type.append(pending);
                    pending.clear();
                    type.append(lexeme());
                }
                readToken();
                virgin = false;
            }
            if (!pending.isEmpty()) {
                type.append(pending);
                pending.clear();
            }
            while (match(Tok_const) || match(Tok_volatile))
                type.append(previousLexeme());

            if (match(Tok_Tilde))
                type.append(previousLexeme());
        }

        if (virgin) {
            if (match(Tok_Ident)) {
                /*
                  This is a hack until we replace this "parser"
                  with the real one used in Qt Creator.
                  Is it still needed? mws 11/12/2018
                 */
                if (lexeme() == "(" &&
                    ((previousLexeme() == "QT_PREPEND_NAMESPACE") || (previousLexeme() == "NS"))) {
                    readToken();
                    readToken();
                    type.append(previousLexeme());
                    readToken();
                }
                else
                    type.append(previousLexeme());
            }
            else if (match(Tok_void) || match(Tok_int) || match(Tok_char) ||
                     match(Tok_double) || match(Tok_Ellipsis)) {
                type.append(previousLexeme());
            }
            else {
                return false;
            }
        }
        else if (match(Tok_int) || match(Tok_char) || match(Tok_double)) {
            type.append(previousLexeme());
        }

        matchTemplateAngles(type);

        while (match(Tok_const) || match(Tok_volatile))
            type.append(previousLexeme());

        if (match(Tok_Gulbrandsen))
            type.append(previousLexeme());
        else
            break;
    }

    while (match(Tok_Ampersand) || match(Tok_Aster) || match(Tok_const) ||
           match(Tok_Caret) || match(Tok_Ellipsis))
        type.append(previousLexeme());

    if (match(Tok_LeftParenAster)) {
        /*
          A function pointer. This would be rather hard to handle without a
          tokenizer hack, because a type can be followed with a left parenthesis
          in some cases (e.g., 'operator int()'). The tokenizer recognizes '(*'
          as a single token.
        */
        type.append(" "); // force a space after the type
        type.append(previousLexeme());
        type.appendHotspot();
        if (match(Tok_Ident))
            name = previousLexeme();
        if (!match(Tok_RightParen))
            return false;
        type.append(previousLexeme());
        if (!match(Tok_LeftParen))
            return false;
        type.append(previousLexeme());

        /* parse the parameters. Ignore the parameter name from the type */
        while (tok_ != Tok_RightParen && tok_ != Tok_Eoi) {
            QString dummy;
            if (!matchTypeAndName(type, dummy))
                return false;
            if (match(Tok_Comma))
                type.append(previousLexeme());
        }
        if (!match(Tok_RightParen))
            return false;
        type.append(previousLexeme());
    }
    else {
        /*
          The common case: Look for an optional identifier, then for
          some array brackets.
        */
        type.appendHotspot();

        if (match(Tok_Ident)) {
            name = previousLexeme();
        }
        else if (match(Tok_Comment)) {
            /*
              A neat hack: Commented-out parameter names are
              recognized by qdoc. It's impossible to illustrate
              here inside a C-style comment, because it requires
              an asterslash. It's also impossible to illustrate
              inside a C++-style comment, because the explanation
              does not fit on one line.
            */
            if (varComment_.exactMatch(previousLexeme()))
                name = varComment_.cap(1);
        }
        else if (match(Tok_LeftParen)) {
            name = "(";
            while (tok_ != Tok_RightParen && tok_ != Tok_Eoi) {
                name.append(lexeme());
                readToken();
            }
            name.append(")");
            readToken();
            if (match(Tok_LeftBracket)) {
                name.append("[");
                while (tok_ != Tok_RightBracket && tok_ != Tok_Eoi) {
                    name.append(lexeme());
                    readToken();
                }
                name.append("]");
                readToken();
            }
        }
        else if (qProp && (match(Tok_default) || match(Tok_final) || match(Tok_override))) {
            // Hack to make 'default', 'final' and 'override'  work again in Q_PROPERTY
            name = previousLexeme();
        }

        if (tok_ == Tok_LeftBracket) {
            int bracketDepth0 = tokenizer_->bracketDepth();
            while ((tokenizer_->bracketDepth() >= bracketDepth0 &&
                    tok_ != Tok_Eoi) ||
                   tok_ == Tok_RightBracket) {
                type.append(lexeme());
                readToken();
            }
        }
    }
    return true;
}

/*!
  Parse the next function parameter, if there is one, and
  append it to the internal parameter vector. Return true
  if a parameter is parsed correctly. Otherwise return false.
 */
bool Parameters::matchParameter()
{
    if (match(Tok_QPrivateSignal)) {
        privateSignal_ = true;
        return true;
    }

    CodeChunk chunk;
    QString name;
    if (!matchTypeAndName(chunk, name))
        return false;
    QString type = chunk.toString();
    QString defaultValue;
    match(Tok_Comment);
    if (match(Tok_Equal)) {
        chunk.clear();
        int pdepth = tokenizer_->parenDepth();
        while (tokenizer_->parenDepth() >= pdepth &&
               (tok_ != Tok_Comma || (tokenizer_->parenDepth() > pdepth)) &&
               tok_ != Tok_Eoi) {
            chunk.append(lexeme());
            readToken();
        }
        defaultValue = chunk.toString();
    }
    append(type, name, defaultValue);
    return true;
}

/*!
  This function uses a Tokenizer to parse the \a signature,
  which is a comma-separated list of parameter declarations.
  If an error is detected, the Parameters object is cleared
  and \c false is returned. Otherwise \c true is returned.
 */
bool Parameters::parse(const QString &signature)
{
    Tokenizer *outerTokenizer = tokenizer_;
    int outerTok = tok_;

    QByteArray latin1 = signature.toLatin1();
    Tokenizer stringTokenizer(Location(), latin1);
    stringTokenizer.setParsingFnOrMacro(true);
    tokenizer_ = &stringTokenizer;

    readToken();
    do {
        if (!matchParameter()) {
            parameters_.clear();
            valid_ = false;
            break;
        }
    } while (match(Tok_Comma));

    tokenizer_ = outerTokenizer;
    tok_ = outerTok;
    return valid_;
}

/*!
  Append a Parameter constructed from \a type, \a name, and \a value
  to the parameter vector.
 */
void Parameters::append(const QString &type, const QString &name, const QString &value)
{
    parameters_.append(Parameter(type, name, value));
}

/*!
  Returns the list of reconstructed parameters. If \a includeValues
  is true, the default values are included, if any are present.
 */
QString Parameters::signature(bool includeValues) const
{
    QString result;
    if (parameters_.size() > 0) {
        for (int i = 0; i < parameters_.size(); i++) {
            if (i > 0)
                result += ", ";
            result += parameters_.at(i).signature(includeValues);
        }
    }
    return result;
}

/*!
  Returns the signature of all the parameters with all the
  spaces and commas removed. It is unintelligible, but that
  is what the caller wants.

  If \a names is true, the parameter names are included. If
  \a values is true, the default values are included.
 */
QString Parameters::rawSignature(bool names, bool values) const
{
    QString raw;
    foreach (const Parameter &parameter, parameters_) {
        raw += parameter.type();
        if (names)
            raw += parameter.name();
        if (values)
            raw += parameter.defaultValue();
    }
    return raw;
}

/*!
  Parse the parameter \a signature by splitting the string,
  and store the individual parameters in the parameter vector.

  This method of parsing the parameter signature probably
  doesn't work for all cases. Investigate doing using the
  more robust way in parse().
 */
void Parameters::set(const QString &signature)
{
    clear();
    if (!signature.isEmpty()) {
        QStringList commaSplit = signature.split(',');
        parameters_.resize(commaSplit.size() + 1);
        for (int i = 0; i < commaSplit.size(); i++) {
            QStringList blankSplit = commaSplit[i].split(' ');
            QString pName = blankSplit.last();
            blankSplit.removeLast();
            QString pType;
            if (blankSplit.size() > 1)
                pType = blankSplit.join(' ');
            if (pType.isEmpty() && pName == QLatin1String("..."))
                qSwap(pType, pName);
            else {
                int i = 0;
                while (i < pName.length() && !pName.at(i).isLetter())
                    i++;
                if (i > 0) {
                    pType += QChar(' ') + pName.left(i);
                    pName = pName.mid(i);
                }
            }
            parameters_[i].set(pType, pName);
        }
    }
}

/*!
  Insert all the parameter names into names.
 */
void Parameters::getNames(QSet<QString> &names) const
{
    foreach (const Parameter &parameter, parameters_) {
        if (!parameter.name().isEmpty())
            names.insert(parameter.name());
    }
}

/*!
  Construct a list of the parameter types and append it to
  \a out. \a out is not cleared first.
 */
void Parameters::getTypeList(QString &out) const
{
    if (count() > 0) {
        for (int i = 0; i < count(); ++i) {
            if (i > 0)
                out += ", ";
            out += parameters_.at(i).type();
        }
    }
}

/*!
  Construct a list of the parameter type/name pairs and
  append it to \a out. \a out is not cleared first.
*/
void Parameters::getTypeAndNameList(QString &out) const
{
    if (count() > 0) {
        for (int i = 0; i < count(); ++i) {
            if (i != 0)
                out += ", ";
            const Parameter &p = parameters_.at(i);
            out += p.type();
            if (out[out.size() - 1].isLetterOrNumber())
                out += QLatin1Char(' ');
            out += p.name();
        }
    }
}

/*!
  Returns true if \a parameters contains the same parameter
  signature as this.
 */
bool Parameters::match(const Parameters &parameters) const
{
    if (count() != parameters.count())
        return false;
    if (count() == 0)
        return true;
    for (int i = 0; i < count(); i++) {
        if (parameters.at(i).type() != parameters_.at(i).type())
            return false;
    }
    return true;
}

QT_END_NAMESPACE