pp-engine.cpp 62.6 KB
Newer Older
1 2
/**************************************************************************
**
con's avatar
con committed
3 4
** This file is part of Qt Creator
**
hjk's avatar
hjk committed
5
** Copyright (c) 2012 Nokia Corporation and/or its subsidiary(-ies).
con's avatar
con committed
6
**
Eike Ziller's avatar
Eike Ziller committed
7
** Contact: http://www.qt-project.org/
con's avatar
con committed
8
**
9
**
10
** GNU Lesser General Public License Usage
11
**
hjk's avatar
hjk committed
12 13 14 15 16 17
** 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.
18
**
con's avatar
con committed
19
** In addition, as a special exception, Nokia gives you certain additional
hjk's avatar
hjk committed
20
** rights. These rights are described in the Nokia Qt LGPL Exception
con's avatar
con committed
21 22
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
hjk's avatar
hjk committed
23 24 25 26 27
** Other Usage
**
** Alternatively, this file may be used in accordance with the terms and
** conditions contained in a signed written agreement between you and Nokia.
**
con's avatar
con committed
28
**
29
**************************************************************************/
con's avatar
con committed
30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50
/*
  Copyright 2005 Roberto Raggi <roberto@kdevelop.org>

  Permission to use, copy, modify, distribute, and sell this software and its
  documentation for any purpose is hereby granted without fee, provided that
  the above copyright notice appear in all copies and that both that
  copyright notice and this permission notice appear in supporting
  documentation.

  The above copyright notice and this permission notice shall be included in
  all copies or substantial portions of the Software.

  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.  IN NO EVENT SHALL THE
  KDEVELOP TEAM BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
  AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
  CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/

#include "pp.h"
51
#include "pp-cctype.h"
hjk's avatar
hjk committed
52

53
#include <Control.h>
con's avatar
con committed
54 55
#include <Lexer.h>
#include <Token.h>
56
#include <Literals.h>
57
#include <cctype>
58

hjk's avatar
hjk committed
59
#include <QDebug>
60
#include <QList>
61 62
#include <QDate>
#include <QTime>
63 64 65 66
#include <QPair>

#include <list>
#include <algorithm>
67 68 69 70 71 72 73

#define NO_DEBUG

#ifndef NO_DEBUG
#  include <iostream>
#endif // NO_DEBUG

74 75
#include <deque>

76 77
namespace {
enum {
78
    MAX_TOKEN_EXPANSION_COUNT = 5000,
79
    MAX_TOKEN_BUFFER_DEPTH = 16000 // for when macros are using some kind of right-folding, this is the list of "delayed" buffers waiting to be expanded after the current one.
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
};
}

namespace {
template<typename _T>
class ScopedSwap
{
    _T oldValue;
    _T &ref;

public:
    ScopedSwap(_T &var, _T newValue)
        : oldValue(newValue)
        , ref(var)
    {
        std::swap(ref, oldValue);
    }

    ~ScopedSwap()
    {
        std::swap(ref, oldValue);
    }
};
typedef ScopedSwap<bool> ScopedBoolSwap;
typedef ScopedSwap<unsigned> ScopedUnsignedSwap;
} // anonymous namespace
con's avatar
con committed
106

Roberto Raggi's avatar
Roberto Raggi committed
107 108
namespace CPlusPlus {

109 110 111
namespace Internal {
struct TokenBuffer
{
112
    std::deque<PPToken> tokens;
113 114 115
    const Macro *macro;
    TokenBuffer *next;

116 117
    TokenBuffer(const PPToken *start, const PPToken *end, const Macro *macro, TokenBuffer *next)
        : tokens(start, end), macro(macro), next(next)
118 119
    {}

120 121 122 123
    bool isBlocked(const Macro *macro) const {
        if (!macro)
            return false;

124
        for (const TokenBuffer *it = this; it; it = it->next)
125
            if (it->macro == macro && it->macro->name() == macro->name())
126 127 128 129 130
                return true;
        return false;
    }
};

Roberto Raggi's avatar
Roberto Raggi committed
131 132 133 134
struct Value
{
    enum Kind {
        Kind_Long,
135
        Kind_ULong
Roberto Raggi's avatar
Roberto Raggi committed
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
    };

    Kind kind;

    union {
        long l;
        unsigned long ul;
    };


    Value()
        : kind(Kind_Long), l(0)
    { }

    inline bool is_ulong () const
    { return kind == Kind_ULong; }

    inline void set_ulong (unsigned long v)
    {
        ul = v;
        kind = Kind_ULong;
    }

    inline void set_long (long v)
    {
        l = v;
        kind = Kind_Long;
    }

    inline bool is_zero () const
    { return l == 0; }

#define PP_DEFINE_BIN_OP(name, op) \
    inline Value operator op(const Value &other) const \
    { \
        Value v = *this; \
        if (v.is_ulong () || other.is_ulong ()) \
            v.set_ulong (v.ul op other.ul); \
        else \
            v.set_long (v.l op other.l); \
        return v; \
    }

    PP_DEFINE_BIN_OP(op_add, +)
    PP_DEFINE_BIN_OP(op_sub, -)
    PP_DEFINE_BIN_OP(op_mult, *)
    PP_DEFINE_BIN_OP(op_div, /)
    PP_DEFINE_BIN_OP(op_mod, %)
    PP_DEFINE_BIN_OP(op_lhs, <<)
    PP_DEFINE_BIN_OP(op_rhs, >>)
    PP_DEFINE_BIN_OP(op_lt, <)
    PP_DEFINE_BIN_OP(op_gt, >)
    PP_DEFINE_BIN_OP(op_le, <=)
    PP_DEFINE_BIN_OP(op_ge, >=)
    PP_DEFINE_BIN_OP(op_eq, ==)
    PP_DEFINE_BIN_OP(op_ne, !=)
    PP_DEFINE_BIN_OP(op_bit_and, &)
    PP_DEFINE_BIN_OP(op_bit_or, |)
    PP_DEFINE_BIN_OP(op_bit_xor, ^)
    PP_DEFINE_BIN_OP(op_and, &&)
    PP_DEFINE_BIN_OP(op_or, ||)

#undef PP_DEFINE_BIN_OP
};

201
} // namespace Internal
202
} // namespace CPlusPlus
Roberto Raggi's avatar
Roberto Raggi committed
203

con's avatar
con committed
204
using namespace CPlusPlus;
205
using namespace CPlusPlus::Internal;
Roberto Raggi's avatar
Roberto Raggi committed
206

con's avatar
con committed
207 208
namespace {

209
inline bool isContinuationToken(const PPToken &tk)
210 211 212 213
{
    return tk.isNot(T_EOF_SYMBOL) && (! tk.newline() || tk.joined());
}

214 215 216 217 218
Macro *macroDefinition(const ByteArrayRef &name,
                       unsigned offset,
                       unsigned line,
                       Environment *env,
                       Client *client)
Christian Kamm's avatar
Christian Kamm committed
219 220 221 222
{
    Macro *m = env->resolve(name);
    if (client) {
        if (m)
223
            client->passedMacroDefinitionCheck(offset, line, *m);
Christian Kamm's avatar
Christian Kamm committed
224 225 226
        else
            client->failedMacroDefinitionCheck(offset, name);
    }
227
    return m;
Christian Kamm's avatar
Christian Kamm committed
228 229
}

con's avatar
con committed
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
class RangeLexer
{
    const Token *first;
    const Token *last;
    Token trivial;

public:
    inline RangeLexer(const Token *first, const Token *last)
        : first(first), last(last)
    {
        // WARN: `last' must be a valid iterator.
        trivial.offset = last->offset;
    }

    inline operator bool() const
    { return first != last; }

    inline bool isValid() const
    { return first != last; }

    inline int size() const
    { return std::distance(first, last); }

    inline const Token *dot() const
    { return first; }

    inline const Token &operator*() const
    {
        if (first != last)
            return *first;

        return trivial;
    }

    inline const Token *operator->() const
    {
        if (first != last)
            return first;

        return &trivial;
    }

    inline RangeLexer &operator++()
    {
        ++first;
        return *this;
    }
};

class ExpressionEvaluator
{
    ExpressionEvaluator(const ExpressionEvaluator &other);
    void operator = (const ExpressionEvaluator &other);

public:
Christian Kamm's avatar
Christian Kamm committed
285 286
    ExpressionEvaluator(Client *client, Environment *env)
        : client(client), env(env), _lex(0)
con's avatar
con committed
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
    { }

    Value operator()(const Token *firstToken, const Token *lastToken,
                     const QByteArray &source)
    {
        this->source = source;
        const Value previousValue = switchValue(Value());
        RangeLexer tmp(firstToken, lastToken);
        RangeLexer *previousLex = _lex;
        _lex = &tmp;
        process_expression();
        _lex = previousLex;
        return switchValue(previousValue);
    }

protected:
    Value switchValue(const Value &value)
    {
        Value previousValue = _value;
        _value = value;
        return previousValue;
    }

    bool isTokenDefined() const
    {
        if ((*_lex)->isNot(T_IDENTIFIER))
            return false;
314
        const ByteArrayRef spell = tokenSpell();
con's avatar
con committed
315 316 317 318 319
        if (spell.size() != 7)
            return false;
        return spell == "defined";
    }

320 321 322 323 324 325 326 327 328 329
    const char *tokenPosition() const
    {
        return source.constData() + (*_lex)->offset;
    }

    int tokenLength() const
    {
        return (*_lex)->f.length;
    }

330
    ByteArrayRef tokenSpell() const
con's avatar
con committed
331
    {
332
        return ByteArrayRef(tokenPosition(), tokenLength());
con's avatar
con committed
333 334
    }

335 336
    inline void process_expression()
    { process_constant_expression(); }
con's avatar
con committed
337

338
    void process_primary()
con's avatar
con committed
339
    {
340
        if ((*_lex)->is(T_NUMERIC_LITERAL)) {
341 342 343 344
            const char *spell = tokenPosition();
            int len = tokenLength();
            while (len) {
                const char ch = spell[len - 1];
345

346
                if (! (ch == 'u' || ch == 'U' || ch == 'l' || ch == 'L'))
347
                    break;
348
                --len;
349 350
            }

351 352 353
            const char *end = spell + len;
            char *vend = const_cast<char *>(end);
            _value.set_long(strtol(spell, &vend, 0));
con's avatar
con committed
354 355 356 357
            ++(*_lex);
        } else if (isTokenDefined()) {
            ++(*_lex);
            if ((*_lex)->is(T_IDENTIFIER)) {
358 359 360 361
                _value.set_long(macroDefinition(tokenSpell(),
                                                (*_lex)->offset,
                                                (*_lex)->lineno, env, client)
                                != 0);
con's avatar
con committed
362 363 364 365
                ++(*_lex);
            } else if ((*_lex)->is(T_LPAREN)) {
                ++(*_lex);
                if ((*_lex)->is(T_IDENTIFIER)) {
366 367 368 369 370
                    _value.set_long(macroDefinition(tokenSpell(),
                                                    (*_lex)->offset,
                                                    (*_lex)->lineno,
                                                    env, client)
                                    != 0);
con's avatar
con committed
371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386
                    ++(*_lex);
                    if ((*_lex)->is(T_RPAREN)) {
                        ++(*_lex);
                    }
                }
            }
        } else if ((*_lex)->is(T_IDENTIFIER)) {
            _value.set_long(0);
            ++(*_lex);
        } else if ((*_lex)->is(T_MINUS)) {
            ++(*_lex);
            process_primary();
            _value.set_long(- _value.l);
        } else if ((*_lex)->is(T_PLUS)) {
            ++(*_lex);
            process_primary();
Roberto Raggi's avatar
Roberto Raggi committed
387 388 389 390
        } else if ((*_lex)->is(T_TILDE)) {
            ++(*_lex);
            process_primary();
            _value.set_long(~ _value.l);
con's avatar
con committed
391 392 393 394 395 396 397 398 399 400 401 402
        } else if ((*_lex)->is(T_EXCLAIM)) {
            ++(*_lex);
            process_primary();
            _value.set_long(_value.is_zero());
        } else if ((*_lex)->is(T_LPAREN)) {
            ++(*_lex);
            process_expression();
            if ((*_lex)->is(T_RPAREN))
                ++(*_lex);
        }
    }

403
    Value process_expression_with_operator_precedence(const Value &lhs, int minPrecedence)
con's avatar
con committed
404
    {
405
        Value result = lhs;
con's avatar
con committed
406

407 408 409
        while (precedence((*_lex)->kind()) >= minPrecedence) {
            const int oper = (*_lex)->kind();
            const int operPrecedence = precedence(oper);
con's avatar
con committed
410 411
            ++(*_lex);
            process_primary();
412
            Value rhs = _value;
con's avatar
con committed
413

414
            for (int LA_token_kind = (*_lex)->kind(), LA_precedence = precedence(LA_token_kind);
415
                    LA_precedence > operPrecedence && isBinaryOperator(LA_token_kind);
416 417
                    LA_token_kind = (*_lex)->kind(), LA_precedence = precedence(LA_token_kind)) {
                rhs = process_expression_with_operator_precedence(rhs, LA_precedence);
con's avatar
con committed
418 419
            }

420
            result = evaluate_expression(oper, result, rhs);
con's avatar
con committed
421 422
        }

423
        return result;
con's avatar
con committed
424 425
    }

426
    void process_constant_expression()
con's avatar
con committed
427
    {
428 429
        process_primary();
        _value = process_expression_with_operator_precedence(_value, precedence(T_PIPE_PIPE));
con's avatar
con committed
430

431 432
        if ((*_lex)->is(T_QUESTION)) {
            const Value cond = _value;
con's avatar
con committed
433
            ++(*_lex);
434 435 436 437 438 439 440 441
            process_constant_expression();
            Value left = _value, right;
            if ((*_lex)->is(T_COLON)) {
                ++(*_lex);
                process_constant_expression();
                right = _value;
            }
            _value = ! cond.is_zero() ? left : right;
con's avatar
con committed
442 443 444
        }
    }

445 446
private:
    inline int precedence(int tokenKind) const
con's avatar
con committed
447
    {
448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469
        switch (tokenKind) {
        case T_PIPE_PIPE:       return 0;
        case T_AMPER_AMPER:     return 1;
        case T_PIPE:            return 2;
        case T_CARET:           return 3;
        case T_AMPER:           return 4;
        case T_EQUAL_EQUAL:
        case T_EXCLAIM_EQUAL:   return 5;
        case T_GREATER:
        case T_LESS:
        case T_LESS_EQUAL:
        case T_GREATER_EQUAL:   return 6;
        case T_LESS_LESS:
        case T_GREATER_GREATER: return 7;
        case T_PLUS:
        case T_MINUS:           return 8;
        case T_STAR:
        case T_SLASH:
        case T_PERCENT:         return 9;

        default:
            return -1;
con's avatar
con committed
470 471 472
        }
    }

473
    static inline bool isBinaryOperator(int tokenKind)
con's avatar
con committed
474
    {
475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494
        switch (tokenKind) {
        case T_PIPE_PIPE:
        case T_AMPER_AMPER:
        case T_PIPE:
        case T_CARET:
        case T_AMPER:
        case T_EQUAL_EQUAL:
        case T_EXCLAIM_EQUAL:
        case T_GREATER:
        case T_LESS:
        case T_LESS_EQUAL:
        case T_GREATER_EQUAL:
        case T_LESS_LESS:
        case T_GREATER_GREATER:
        case T_PLUS:
        case T_MINUS:
        case T_STAR:
        case T_SLASH:
        case T_PERCENT:
            return true;
con's avatar
con committed
495

496 497
        default:
            return false;
con's avatar
con committed
498 499 500
        }
    }

501
    static inline Value evaluate_expression(int tokenKind, const Value &lhs, const Value &rhs)
con's avatar
con committed
502
    {
503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524
        switch (tokenKind) {
        case T_PIPE_PIPE:       return lhs || rhs;
        case T_AMPER_AMPER:     return lhs && rhs;
        case T_PIPE:            return lhs | rhs;
        case T_CARET:           return lhs ^ rhs;
        case T_AMPER:           return lhs & rhs;
        case T_EQUAL_EQUAL:     return lhs == rhs;
        case T_EXCLAIM_EQUAL:   return lhs != rhs;
        case T_GREATER:         return lhs > rhs;
        case T_LESS:            return lhs < rhs;
        case T_LESS_EQUAL:      return lhs <= rhs;
        case T_GREATER_EQUAL:   return lhs >= rhs;
        case T_LESS_LESS:       return lhs << rhs;
        case T_GREATER_GREATER: return lhs >> rhs;
        case T_PLUS:            return lhs + rhs;
        case T_MINUS:           return lhs - rhs;
        case T_STAR:            return lhs * rhs;
        case T_SLASH:           return rhs.is_zero() ? Value() : lhs / rhs;
        case T_PERCENT:         return rhs.is_zero() ? Value() : lhs % rhs;

        default:
            return Value();
con's avatar
con committed
525 526 527 528
        }
    }

private:
Christian Kamm's avatar
Christian Kamm committed
529
    Client *client;
con's avatar
con committed
530 531 532 533 534 535 536 537
    Environment *env;
    QByteArray source;
    RangeLexer *_lex;
    Value _value;
};

} // end of anonymous namespace

538 539 540 541 542 543
Preprocessor::State::State()
    : m_lexer(0)
    , m_skipping(MAX_LEVEL)
    , m_trueTest(MAX_LEVEL)
    , m_ifLevel(0)
    , m_tokenBuffer(0)
544
    , m_tokenBufferDepth(0)
545 546
    , m_inPreprocessorDirective(false)
    , m_result(0)
547
    , m_markExpandedTokens(true)
548 549
    , m_noLines(false)
    , m_inCondition(false)
550
    , m_offsetRef(0)
551 552
    , m_lineRef(1)
    , m_expansionStatus(NotExpanding)
con's avatar
con committed
553
{
554 555
    m_skipping[m_ifLevel] = false;
    m_trueTest[m_ifLevel] = false;
556 557

    m_expansionResult.reserve(256);
con's avatar
con committed
558 559
}

Erik Verbruggen's avatar
Erik Verbruggen committed
560
//#define COMPRESS_TOKEN_BUFFER
561 562 563 564 565 566 567 568 569 570 571
void Preprocessor::State::pushTokenBuffer(const PPToken *start, const PPToken *end, const Macro *macro)
{
    if (m_tokenBufferDepth <= MAX_TOKEN_BUFFER_DEPTH) {
#ifdef COMPRESS_TOKEN_BUFFER
        // This does not work correctly for boost's preprocessor library, or that library exposes a bug in the code.
        if (macro || !m_tokenBuffer) {
            m_tokenBuffer = new TokenBuffer(start, end, macro, m_tokenBuffer);
            ++m_tokenBufferDepth;
        } else {
            m_tokenBuffer->tokens.insert(m_tokenBuffer->tokens.begin(), start, end);
        }
Erik Verbruggen's avatar
Erik Verbruggen committed
572 573 574 575
        unsigned tkCount = 0;
        for (TokenBuffer *it = m_tokenBuffer; it; it = m_tokenBuffer->next)
            tkCount += it->tokens.size();
        qDebug()<<"New depth:" << m_tokenBufferDepth << "with total token count:" << tkCount;
576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591
#else
        m_tokenBuffer = new TokenBuffer(start, end, macro, m_tokenBuffer);
        ++m_tokenBufferDepth;
#endif
    }
}

void Preprocessor::State::popTokenBuffer()
{
    TokenBuffer *r = m_tokenBuffer;
    m_tokenBuffer = m_tokenBuffer->next;
    delete r;

    if (m_tokenBufferDepth)
        --m_tokenBufferDepth;
}
592 593 594 595

Preprocessor::Preprocessor(Client *client, Environment *env)
    : m_client(client)
    , m_env(env)
596
    , m_expandFunctionlikeMacros(true)
597
    , m_keepComments(false)
con's avatar
con committed
598 599 600
{
}

601
QByteArray Preprocessor::run(const QString &fileName, const QString &source)
602
{
603
    return run(fileName, source.toLatin1());
604 605
}

606 607 608 609
QByteArray Preprocessor::run(const QString &fileName,
                             const QByteArray &source,
                             bool noLines,
                             bool markGeneratedTokens)
610
{
611 612
    m_scratchBuffer.clear();

613
    QByteArray preprocessed;
614
    preprocess(fileName, source, &preprocessed, noLines, markGeneratedTokens, false);
615 616 617
    return preprocessed;
}

618
bool Preprocessor::expandFunctionlikeMacros() const
619
{
620
    return m_expandFunctionlikeMacros;
621 622
}

623
void Preprocessor::setExpandFunctionlikeMacros(bool expandMacros)
624
{
625
    m_expandFunctionlikeMacros = expandMacros;
626 627
}

628 629
bool Preprocessor::keepComments() const
{
630
    return m_keepComments;
631 632 633 634
}

void Preprocessor::setKeepComments(bool keepComments)
{
635
    m_keepComments = keepComments;
636 637
}

638
void Preprocessor::generateOutputLineMarker(unsigned lineno)
639
{
640 641 642 643 644 645 646 647 648
    maybeStartOutputLine();
    QByteArray marker;
    marker.reserve(64);
    marker.append("# ");
    marker.append(QByteArray::number(lineno));
    marker.append(" \"");
    marker.append(m_env->currentFileUtf8);
    marker.append("\"\n");
    writeOutput(marker);
649 650
}

651
void Preprocessor::handleDefined(PPToken *tk)
652
{
653
    ScopedBoolSwap s(m_state.m_inPreprocessorDirective, true);
654 655 656 657 658 659 660
    unsigned lineno = tk->lineno;
    lex(tk); // consume "defined" token
    bool lparenSeen = tk->is(T_LPAREN);
    if (lparenSeen)
        lex(tk); // consume "(" token
    if (tk->isNot(T_IDENTIFIER))
        //### TODO: generate error message
661
        return;
662 663 664 665 666 667 668 669 670 671
    PPToken idToken = *tk;
    do {
        lex(tk);
        if (tk->isNot(T_POUND_POUND))
            break;
        lex(tk);
        if (tk->is(T_IDENTIFIER))
            idToken = generateConcatenated(idToken, *tk);
        else
            break;
672
    } while (isContinuationToken(*tk));
673

674 675 676 677 678 679

    if (lparenSeen && tk->is(T_RPAREN))
        lex(tk);

    pushToken(tk);

680 681 682
    QByteArray result(1, '0');
    if (m_env->resolve(idToken.asByteArrayRef()))
        result[0] = '1';
683
    *tk = generateToken(T_NUMERIC_LITERAL, result.constData(), result.size(), lineno, false);
684 685
}

686
void Preprocessor::pushToken(Preprocessor::PPToken *tk)
687
{
688
    const PPToken currentTokenBuffer[] = { *tk };
689
    m_state.pushTokenBuffer(currentTokenBuffer, currentTokenBuffer + 1, 0);
690
}
691

692 693 694 695 696
void Preprocessor::lex(PPToken *tk)
{
_Lagain:
    if (m_state.m_tokenBuffer) {
        if (m_state.m_tokenBuffer->tokens.empty()) {
697
            m_state.popTokenBuffer();
698 699 700 701 702 703 704 705
            goto _Lagain;
        }
        *tk = m_state.m_tokenBuffer->tokens.front();
        m_state.m_tokenBuffer->tokens.pop_front();
    } else {
        tk->setSource(m_state.m_source);
        m_state.m_lexer->scan(tk);
    }
706

707 708 709
    // Adjust token's line number in order to take into account the environment reference.
    tk->lineno += m_state.m_lineRef - 1;

710 711 712 713 714 715 716 717 718
_Lclassify:
    if (! m_state.m_inPreprocessorDirective) {
        if (tk->newline() && tk->is(T_POUND)) {
            handlePreprocessorDirective(tk);
            goto _Lclassify;
        } else if (tk->newline() && skipping()) {
            ScopedBoolSwap s(m_state.m_inPreprocessorDirective, true);
            do {
                lex(tk);
719
            } while (isContinuationToken(*tk));
720 721
            goto _Lclassify;
        } else if (tk->is(T_IDENTIFIER) && !isQtReservedWord(tk->asByteArrayRef())) {
Leandro Melo's avatar
Leandro Melo committed
722
            if (m_state.m_inCondition && tk->asByteArrayRef() == "defined") {
723
                handleDefined(tk);
Leandro Melo's avatar
Leandro Melo committed
724
            } else {
725 726
                synchronizeOutputLines(*tk);
                if (handleIdentifier(tk))
Leandro Melo's avatar
Leandro Melo committed
727 728
                    goto _Lagain;
            }
729 730 731 732
        }
    }
}

733
void Preprocessor::skipPreprocesorDirective(PPToken *tk)
734
{
735 736
    ScopedBoolSwap s(m_state.m_inPreprocessorDirective, true);

737
    while (isContinuationToken(*tk)) {
738
        lex(tk);
739 740 741
    }
}

742
bool Preprocessor::handleIdentifier(PPToken *tk)
743
{
744 745 746 747 748 749 750 751 752
    ScopedBoolSwap s(m_state.m_inPreprocessorDirective, true);

    static const QByteArray ppLine("__LINE__");
    static const QByteArray ppFile("__FILE__");
    static const QByteArray ppDate("__DATE__");
    static const QByteArray ppTime("__TIME__");

    ByteArrayRef macroNameRef = tk->asByteArrayRef();

753 754 755
    if (macroNameRef.size() == 8
            && macroNameRef[0] == '_'
            && macroNameRef[1] == '_') {
756 757 758
        PPToken newTk;
        if (macroNameRef == ppLine) {
            QByteArray txt = QByteArray::number(tk->lineno);
759
            newTk = generateToken(T_STRING_LITERAL, txt.constData(), txt.size(), tk->lineno, false);
760 761 762
        } else if (macroNameRef == ppFile) {
            QByteArray txt;
            txt.append('"');
763
            txt.append(m_env->currentFileUtf8);
764
            txt.append('"');
765
            newTk = generateToken(T_STRING_LITERAL, txt.constData(), txt.size(), tk->lineno, false);
766 767 768 769 770
        } else if (macroNameRef == ppDate) {
            QByteArray txt;
            txt.append('"');
            txt.append(QDate::currentDate().toString().toUtf8());
            txt.append('"');
771
            newTk = generateToken(T_STRING_LITERAL, txt.constData(), txt.size(), tk->lineno, false);
772 773 774 775 776
        } else if (macroNameRef == ppTime) {
            QByteArray txt;
            txt.append('"');
            txt.append(QTime::currentTime().toString().toUtf8());
            txt.append('"');
777
            newTk = generateToken(T_STRING_LITERAL, txt.constData(), txt.size(), tk->lineno, false);
778 779
        }

780 781
        if (newTk.hasSource()) {
            newTk.f.newline = tk->newline();
782 783 784
            newTk.f.whitespace = tk->whitespace();
            *tk = newTk;
            return false;
785 786 787
        }
    }

788
    Macro *macro = m_env->resolve(macroNameRef);
789
    if (!macro
790
            || (tk->expanded()
791 792
                && m_state.m_tokenBuffer
                && m_state.m_tokenBuffer->isBlocked(macro))) {
793
        return false;
794
    }
795
//    qDebug() << "expanding" << macro->name() << "on line" << tk->lineno;
796

797
    // Keep track the of the macro identifier token.
798
    PPToken idTk = *tk;
799 800 801 802 803 804 805

    // Expanded tokens which are not generated ones preserve the original line number from
    // their corresponding argument in macro substitution. For expanded tokens which are
    // generated, this information must be taken from somewhere else. What we do is to keep
    // a "reference" line initialize set to the line where expansion happens.
    unsigned baseLine = idTk.lineno;

806
    QVector<PPToken> body = macro->definitionTokens();
807

808 809 810 811
    // Withing nested expansion we might reach a previously added marker token. In this case,
    // we need to move it from its current possition to outside the nesting.
    PPToken oldMarkerTk;

812
    if (macro->isFunctionLike()) {
813 814 815
        if (!expandFunctionlikeMacros())
            return false;

816 817
        // Collect individual tokens that form the macro arguments.
        QVector<QVector<PPToken> > allArgTks;
818 819
        bool hasArgs = collectActualArguments(tk, &allArgTks);

820 821 822 823 824 825 826 827 828 829 830
        // Check whether collecting arguments failed due to a previously added marker
        // that goot nested in a sequence of expansions. If so, store it and try again.
        if (!hasArgs
                && !tk->hasSource()
                && m_state.m_markExpandedTokens
                && (m_state.m_expansionStatus == Expanding
                    || m_state.m_expansionStatus == ReadyForExpansion)) {
            oldMarkerTk = *tk;
            hasArgs = collectActualArguments(tk, &allArgTks);
        }

831 832 833 834 835 836 837 838 839 840 841
        // Check for matching parameter/argument count.
        bool hasMatchingArgs = false;
        if (hasArgs) {
            const int expectedArgCount = macro->formals().size();
            const int actualArgCount = allArgTks.size();
            if (expectedArgCount == actualArgCount
                    || (macro->isVariadic() && actualArgCount > expectedArgCount - 1)
                    // Handle '#define foo()' when invoked as 'foo()'
                    || (expectedArgCount == 0
                        && actualArgCount == 1
                        && allArgTks.at(0).isEmpty())) {
842
                hasMatchingArgs = true;
843 844 845 846 847
            }
        }

        if (!hasArgs || !hasMatchingArgs) {
            //### TODO: error message
848
            pushToken(tk);
849 850 851
            // If a previous marker was found, make sure to put it back.
            if (oldMarkerTk.f.length)
                pushToken(&oldMarkerTk);
852
            *tk = idTk;
853
            return false;
854
        }
855

856 857
        if (m_client && !idTk.generated()) {
            // Bundle each token sequence into a macro argument "reference" for notification.
858 859
            // Even empty ones, which are not necessarily important on its own, but for the matter
            // of couting their number - such as in foo(,)
860 861 862
            QVector<MacroArgumentReference> argRefs;
            for (int i = 0; i < allArgTks.size(); ++i) {
                const QVector<PPToken> &argTks = allArgTks.at(i);
863 864 865 866 867 868 869 870 871
                if (argTks.isEmpty()) {
                    argRefs.push_back(MacroArgumentReference());
                } else {

                    argRefs.push_back(MacroArgumentReference(
                                          m_state.m_offsetRef + argTks.first().begin(),
                                          argTks.last().begin() + argTks.last().length()
                                            - argTks.first().begin()));
                }
872 873
            }

874 875 876
            m_client->startExpandingMacro(m_state.m_offsetRef + idTk.offset,
                                          idTk.lineno,
                                          *macro,
Leandro Melo's avatar
Leandro Melo committed
877
                                          argRefs);
878 879
        }

880 881
        if (!handleFunctionLikeMacro(tk, macro, body, allArgTks, baseLine)) {
            if (m_client && !idTk.expanded())
882 883 884 885
                m_client->stopExpandingMacro(idTk.offset, *macro);
            return false;
        }
    } else if (m_client && !idTk.generated()) {
886
        m_client->startExpandingMacro(m_state.m_offsetRef + idTk.offset, idTk.lineno, *macro);
887
    }
888

889
    if (body.isEmpty()) {
890 891 892 893 894 895 896 897 898 899 900 901 902 903
        if (m_state.m_markExpandedTokens
                && (m_state.m_expansionStatus == NotExpanding
                    || m_state.m_expansionStatus == JustFinishedExpansion)) {
            // This is not the most beautiful approach but it's quite reasonable. What we do here
            // is to create a fake identifier token which is only composed by whitespaces. It's
            // also not marked as expanded so it it can be treated as a regular token.
            QByteArray content(idTk.f.length + computeDistance(idTk), ' ');
            PPToken fakeIdentifier = generateToken(T_IDENTIFIER,
                                                   content.constData(), content.length(),
                                                   idTk.lineno, false, false);
            fakeIdentifier.f.whitespace = true;
            fakeIdentifier.f.expanded = false;
            fakeIdentifier.f.generated = false;
            body.push_back(fakeIdentifier);
904
        }
905
    } else {
906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940
        // The first body token replaces the macro invocation so its whitespace and
        // newline info is replicated.
        PPToken &bodyTk = body[0];
        bodyTk.f.whitespace = idTk.f.whitespace;
        bodyTk.f.newline = idTk.f.newline;

        // Expansions are tracked from a "top-level" basis. This means that each expansion
        // section in the output corresponds to a direct use of a macro (either object-like
        // or function-like) in the source code and all its recurring expansions - they are
        // surrounded by two marker tokens, one at the begin and the other at the end.
        // For instance, the following code will generate 3 expansions in total, but the
        // output will aggregate the tokens in only 2 expansion sections.
        //  - The first corresponds to BAR expanding to FOO and then FOO expanding to T o;
        //  - The second corresponds to FOO expanding to T o;
        //
        // #define FOO(T, o) T o;
        // #define BAR(T, o) FOO(T, o)
        // BAR(Test, x) FOO(Test, y)
        if (m_state.m_markExpandedTokens) {
            if (m_state.m_expansionStatus == NotExpanding
                    || m_state.m_expansionStatus == JustFinishedExpansion) {
                PPToken marker;
                marker.f.expanded = true;
                marker.f.length = idTk.f.length;
                marker.offset = idTk.offset;
                marker.lineno = idTk.lineno;
                body.prepend(marker);
                body.append(marker);
                m_state.m_expansionStatus = ReadyForExpansion;
            } else if (oldMarkerTk.f.length
                       && (m_state.m_expansionStatus == ReadyForExpansion
                           || m_state.m_expansionStatus == Expanding)) {
                body.append(oldMarkerTk);
            }
        }
941
    }
942

943
    m_state.pushTokenBuffer(body.begin(), body.end(), macro);
944

945 946
    if (m_client && !idTk.generated())
        m_client->stopExpandingMacro(idTk.offset, *macro);
947 948

    return true;
949 950
}

951 952 953
bool Preprocessor::handleFunctionLikeMacro(PPToken *tk,
                                           const Macro *macro,
                                           QVector<PPToken> &body,
954 955
                                           const QVector<QVector<PPToken> > &actuals,
                                           unsigned baseLine)
con's avatar
con committed
956
{
957
    QVector<PPToken> expanded;
958
    expanded.reserve(MAX_TOKEN_EXPANSION_COUNT);
959 960 961 962

    const size_t bodySize = body.size();
    for (size_t i = 0; i < bodySize && expanded.size() < MAX_TOKEN_EXPANSION_COUNT;
            ++i) {
963
        int expandedSize = expanded.size();
964
        PPToken bodyTk = body.at(i);
965

966 967
        if (bodyTk.is(T_IDENTIFIER)) {
            const ByteArrayRef id = bodyTk.asByteArrayRef();
968 969 970 971
            const QVector<QByteArray> &formals = macro->formals();
            int j = 0;
            for (; j < formals.size() && expanded.size() < MAX_TOKEN_EXPANSION_COUNT; ++j) {
                if (formals[j] == id) {
972
                    QVector<PPToken> actualsForThisParam = actuals.at(j);
973 974 975
                    unsigned lineno = baseLine;

                    // Collect variadic arguments
976
                    if (id == "__VA_ARGS__" || (macro->isVariadic() && j + 1 == formals.size())) {
977
                        for (int k = j + 1; k < actuals.size(); ++k) {
978 979
                            actualsForThisParam.append(generateToken(T_COMMA, ",", 1, lineno, true));
                            actualsForThisParam += actuals.at(k);
980
                        }
981
                    }
Roberto Raggi's avatar
Roberto Raggi committed
982

983 984 985 986 987 988 989
                    const int actualsSize = actualsForThisParam.size();

                    if (i > 0 && body[i - 1].is(T_POUND)) {
                        QByteArray enclosedString;
                        enclosedString.reserve(256);

                        for (int i = 0; i < actualsSize; ++i) {
990 991 992 993
                            const PPToken &t = actualsForThisParam.at(i);
                            if (i == 0)
                                lineno = t.lineno;
                            else if (t.whitespace())
994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015
                                enclosedString.append(' ');
                            enclosedString.append(t.tokenStart(), t.length());
                        }
                        enclosedString.replace("\\", "\\\\");
                        enclosedString.replace("\"", "\\\"");

                        expanded.push_back(generateToken(T_STRING_LITERAL,
                                                         enclosedString.constData(),
                                                         enclosedString.size(),
                                                         lineno, true));
                    } else {
                        for (int k = 0; k < actualsSize; ++k) {
                            // Mark the actual tokens (which are the replaced version of the
                            // body's one) as expanded. For the first token we replicate the
                            // body's whitespace info.
                            PPToken actual = actualsForThisParam.at(k);
                            actual.f.expanded = true;
                            if (k == 0)
                                actual.f.whitespace = bodyTk.whitespace();
                            expanded += actual;
                            if (k == actualsSize - 1)
                                lineno = actual.lineno;
1016 1017
                        }
                    }
1018 1019 1020 1021

                    // Get a better (more up-to-date) value for the base line.
                    baseLine = lineno;

1022
                    break;
1023
                }
con's avatar
con committed
1024 1025
            }

1026 1027 1028 1029 1030 1031 1032 1033 1034 1035
            if (j == formals.size()) {
                // No formal macro parameter for this identifier in the body.
                bodyTk.f.generated = true;
                bodyTk.lineno = baseLine;
                expanded.push_back(bodyTk);
            }
        } else if (bodyTk.isNot(T_POUND) && bodyTk.isNot(T_POUND_POUND)) {
            bodyTk.f.generated = true;
            bodyTk.lineno = baseLine;
            expanded.push_back(bodyTk);
1036
        }
Roberto Raggi's avatar
Roberto Raggi committed
1037

1038 1039 1040 1041 1042 1043 1044 1045 1046
        if (i > 1 && body[i - 1].is(T_POUND_POUND)) {
            if (expandedSize < 1 || expanded.size() == expandedSize) //### TODO: [cpp.concat] placemarkers
                continue;
            const PPToken &leftTk = expanded[expandedSize - 1];
            const PPToken &rightTk = expanded[expandedSize];
            expanded[expandedSize - 1] = generateConcatenated(leftTk, rightTk);
            expanded.remove(expandedSize);
        }
    }
Roberto Raggi's avatar
Roberto Raggi committed
1047

1048
    // The "new" body.
1049
    body = expanded;
1050
    body.squeeze();
1051 1052 1053 1054

    // Next token to be lexed after the expansion.
    pushToken(tk);

1055
    return true;
con's avatar
con committed
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