pp-engine.cpp 31.7 KB
Newer Older
con's avatar
con committed
1
2
3
4
5
6
7
8
/***************************************************************************
**
** This file is part of Qt Creator
**
** Copyright (c) 2008 Nokia Corporation and/or its subsidiary(-ies).
**
** Contact:  Qt Software Information (qt-info@nokia.com)
**
9
10
11
**
** Non-Open Source Usage
**
con's avatar
con committed
12
13
14
** Licensees may use this file in accordance with the Qt Beta Version
** License Agreement, Agreement version 2.2 provided with the Software or,
** alternatively, in accordance with the terms contained in a written
15
16
17
18
** agreement between you and Nokia.
**
** GNU General Public License Usage
**
con's avatar
con committed
19
20
21
22
23
24
25
26
27
28
** Alternatively, this file may be used under the terms of the GNU General
** Public License versions 2.0 or 3.0 as published by the Free Software
** Foundation and appearing in the file LICENSE.GPL included in the packaging
** of this file.  Please review the following information to ensure GNU
** General Public Licensing requirements will be met:
**
** http://www.fsf.org/licensing/licenses/info/GPLv2.html and
** http://www.gnu.org/copyleft/gpl.html.
**
** In addition, as a special exception, Nokia gives you certain additional
29
** rights. These rights are described in the Nokia Qt GPL Exception
30
** version 1.3, included in the file GPL_EXCEPTION.txt in this package.
31
32
**
***************************************************************************/
con's avatar
con committed
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
/*
  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"
hjk's avatar
hjk committed
54

con's avatar
con committed
55
56
57
#include <Lexer.h>
#include <Token.h>
#include <QtDebug>
58
#include <algorithm>
con's avatar
con committed
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

using namespace CPlusPlus;

namespace {

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:
    ExpressionEvaluator(Environment *env)
        : env(env), _lex(0)
    { }

    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;
        const QByteArray spell = tokenSpell();
        if (spell.size() != 7)
            return false;
        return spell == "defined";
    }

    QByteArray tokenSpell() const
    {
        const QByteArray text = QByteArray::fromRawData(source.constData() + (*_lex)->offset,
                                                        (*_lex)->length);
        return text;
    }

    bool process_expression()
    { return process_constant_expression(); }

    bool process_primary()
    {
        if ((*_lex)->is(T_INT_LITERAL)) {
167
168
169
170
171
172
173
174
175
            int base = 10;
            const QByteArray spell = tokenSpell();
            if (spell.at(0) == '0') {
                if (spell.size() > 1 && (spell.at(1) == 'x' || spell.at(1) == 'X'))
                    base = 16;
                else
                    base = 8;
            }
            _value.set_long(tokenSpell().toLong(0, base));
con's avatar
con committed
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
            ++(*_lex);
            return true;
        } else if (isTokenDefined()) {
            ++(*_lex);
            if ((*_lex)->is(T_IDENTIFIER)) {
                _value.set_long(env->resolve(tokenSpell()) != 0);
                ++(*_lex);
                return true;
            } else if ((*_lex)->is(T_LPAREN)) {
                ++(*_lex);
                if ((*_lex)->is(T_IDENTIFIER)) {
                    _value.set_long(env->resolve(tokenSpell()) != 0);
                    ++(*_lex);
                    if ((*_lex)->is(T_RPAREN)) {
                        ++(*_lex);
                        return true;
                    }
                }
                return false;
            }
            return true;
        } else if ((*_lex)->is(T_IDENTIFIER)) {
            _value.set_long(0);
            ++(*_lex);
            return true;
        } else if ((*_lex)->is(T_MINUS)) {
            ++(*_lex);
            process_primary();
            _value.set_long(- _value.l);
            return true;
        } else if ((*_lex)->is(T_PLUS)) {
            ++(*_lex);
            process_primary();
            return true;
        } else if ((*_lex)->is(T_EXCLAIM)) {
            ++(*_lex);
            process_primary();
            _value.set_long(_value.is_zero());
            return true;
        } else if ((*_lex)->is(T_LPAREN)) {
            ++(*_lex);
            process_expression();
            if ((*_lex)->is(T_RPAREN))
                ++(*_lex);
            return true;
        }

        return false;
    }

    bool process_multiplicative()
    {
        process_primary();

        while ((*_lex)->is(T_STAR) || (*_lex)->is(T_SLASH) || (*_lex)->is(T_PERCENT)) {
            const Token op = *(*_lex);
            ++(*_lex);

            const Value left = _value;
            process_primary();

            if (op.is(T_STAR)) {
                _value = left * _value;
            } else if (op.is(T_SLASH)) {
                if (_value.is_zero())
                    _value.set_long(0);
                else
                    _value = left / _value;
            } else if (op.is(T_PERCENT)) {
                if (_value.is_zero())
                    _value.set_long(0);
                else
                    _value = left % _value;
            }
        }

        return true;
    }

    bool process_additive()
    {
        process_multiplicative();

        while ((*_lex)->is(T_PLUS) || (*_lex)->is(T_MINUS)) {
            const Token op = *(*_lex);
            ++(*_lex);

            const Value left = _value;
            process_multiplicative();

            if (op.is(T_PLUS))
                _value = left + _value;
            else if (op.is(T_MINUS))
                _value = left - _value;
        }

        return true;
    }

    bool process_shift()
    {
        process_additive();

        while ((*_lex)->is(T_MINUS_MINUS) || (*_lex)->is(T_GREATER_GREATER)) {
            const Token op = *(*_lex);
            ++(*_lex);

            const Value left = _value;
            process_additive();

            if (op.is(T_MINUS_MINUS))
                _value = left << _value;
            else if (op.is(T_GREATER_GREATER))
                _value = left >> _value;
        }

        return true;
    }

    bool process_relational()
    {
        process_shift();

        while ((*_lex)->is(T_LESS)    || (*_lex)->is(T_LESS_EQUAL) ||
               (*_lex)->is(T_GREATER) || (*_lex)->is(T_GREATER_EQUAL)) {
            const Token op = *(*_lex);
            ++(*_lex);

            const Value left = _value;
            process_shift();

            if (op.is(T_LESS))
                _value = left < _value;
            else if (op.is(T_LESS_EQUAL))
                _value = left <= _value;
            else if (op.is(T_GREATER))
                _value = left > _value;
            else if (op.is(T_GREATER_EQUAL))
                _value = left >= _value;
        }

        return true;
    }

    bool process_equality()
    {
        process_relational();

        while ((*_lex)->is(T_EXCLAIM_EQUAL) || (*_lex)->is(T_EQUAL_EQUAL)) {
            const Token op = *(*_lex);
            ++(*_lex);

            const Value left = _value;
            process_relational();

            if (op.is(T_EXCLAIM_EQUAL))
                _value = left != _value;
            else if (op.is(T_EQUAL_EQUAL))
                _value = left == _value;
        }

        return true;
    }

    bool process_and()
    {
        process_equality();

        while ((*_lex)->is(T_AMPER)) {
            const Token op = *(*_lex);
            ++(*_lex);

            const Value left = _value;
            process_equality();

            _value = left & _value;
        }

        return true;
    }

    bool process_xor()
    {
        process_and();

        while ((*_lex)->is(T_CARET)) {
            const Token op = *(*_lex);
            ++(*_lex);

            const Value left = _value;
            process_and();

            _value = left ^ _value;
        }

        return true;
    }

    bool process_or()
    {
        process_xor();

378
        while ((*_lex)->is(T_PIPE)) {
con's avatar
con committed
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
            const Token op = *(*_lex);
            ++(*_lex);

            const Value left = _value;
            process_xor();

            _value = left | _value;
        }

        return true;
    }

    bool process_logical_and()
    {
        process_or();

        while ((*_lex)->is(T_AMPER_AMPER)) {
            const Token op = *(*_lex);
            ++(*_lex);

            const Value left = _value;
            process_or();

            _value = left && _value;
        }

        return true;
    }

    bool process_logical_or()
    {
        process_logical_and();

        while ((*_lex)->is(T_PIPE_PIPE)) {
            const Token op = *(*_lex);
            ++(*_lex);

            const Value left = _value;
            process_logical_and();

            _value = left || _value;
        }

        return true;
    }

    bool process_constant_expression()
    {
        process_logical_or();
        const Value cond = _value;
        if ((*_lex)->is(T_QUESTION)) {
            ++(*_lex);
            process_constant_expression();
            Value left = _value, right;
            if ((*_lex)->is(T_COLON)) {
                ++(*_lex);
                process_constant_expression();
                right = _value;
            }
            _value = ! cond.is_zero() ? left : right;
        }

        return true;
    }

private:
    Environment *env;
    QByteArray source;
    RangeLexer *_lex;
    Value _value;
};

} // end of anonymous namespace


454
Preprocessor::Preprocessor(Client *client, Environment &env)
con's avatar
con committed
455
456
457
458
459
460
461
    : client(client),
      env(env),
      expand(env)
{
    resetIfLevel ();
}

462
void Preprocessor::pushState(const State &s)
con's avatar
con committed
463
464
465
466
467
468
469
{
    _savedStates.append(state());
    _source = s.source;
    _tokens = s.tokens;
    _dot = s.dot;
}

470
Preprocessor::State Preprocessor::state() const
con's avatar
con committed
471
472
473
474
475
476
477
478
{
    State state;
    state.source = _source;
    state.tokens = _tokens;
    state.dot = _dot;
    return state;
}

479
void Preprocessor::popState()
con's avatar
con committed
480
481
482
483
484
485
486
487
{
    const State &state = _savedStates.last();
    _source = state.source;
    _tokens = state.tokens;
    _dot = state.dot;
    _savedStates.removeLast();
}

488
void Preprocessor::operator () (const QByteArray &filename,
con's avatar
con committed
489
490
491
                      const QByteArray &source,
                      QByteArray *result)
{
Roberto Raggi's avatar
Roberto Raggi committed
492
493
    const QByteArray previousFile = env.currentFile;
    env.currentFile = filename;
con's avatar
con committed
494
495
496

    operator () (source, result);

Roberto Raggi's avatar
Roberto Raggi committed
497
    env.currentFile = previousFile;
con's avatar
con committed
498
499
}

500
Preprocessor::State Preprocessor::createStateFromSource(const QByteArray &source) const
con's avatar
con committed
501
502
503
504
505
506
507
508
509
510
511
512
513
514
{
    State state;
    state.source = source;
    Lexer lex(state.source.constBegin(), state.source.constEnd());
    lex.setScanKeywords(false);
    Token tok;
    do {
        lex(&tok);
        state.tokens.append(tok);
    } while (tok.isNot(T_EOF_SYMBOL));
    state.dot = state.tokens.constBegin();
    return state;
}

515
void Preprocessor::operator()(const QByteArray &source, QByteArray *result)
con's avatar
con committed
516
517
518
519
520
521
522
523
524
{
    pushState(createStateFromSource(source));

    const unsigned previousCurrentLine = env.currentLine;
    env.currentLine = 0;

    while (true) {
        if (env.currentLine != _dot->lineno) {
            if (env.currentLine > _dot->lineno) {
525
                result->append("\n# ");
con's avatar
con committed
526
527
528
                result->append(QByteArray::number(_dot->lineno));
                result->append(' ');
                result->append('"');
Roberto Raggi's avatar
Roberto Raggi committed
529
                result->append(env.currentFile);
con's avatar
con committed
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
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
                result->append('"');
                result->append('\n');
            } else {
                for (unsigned i = env.currentLine; i < _dot->lineno; ++i)
                    result->append('\n');
            }
            env.currentLine = _dot->lineno;
        }

        if (_dot->is(T_EOF_SYMBOL)) {
            break;
        } else if (_dot->is(T_POUND) && (! _dot->joined && _dot->newline)) {
            TokenIterator start = _dot;
            do {
                ++_dot;
            } while (_dot->isNot(T_EOF_SYMBOL) && (_dot->joined || ! _dot->newline));

            //qDebug() << QByteArray(first + beginPP.offset,
                                   //tokens.last().end() - beginPP.offset);

            const bool skippingBlocks = _skipping[iflevel];

            processDirective(start, _dot);

            if (client && skippingBlocks != _skipping[iflevel]) {
                unsigned offset = start->offset;
                if (_skipping[iflevel]) {
                    if (_dot->newline)
                        ++offset;
                    client->startSkippingBlocks(offset);
                } else {
                    if (offset)
                        --offset;
                    client->stopSkippingBlocks(offset);
                }
            }
        } else if (skipping()) {
            do {
                ++_dot;
            } while (_dot->isNot(T_EOF_SYMBOL) && (_dot->joined || ! _dot->newline));
        } else {
            if (_dot->joined)
                result->append("\\\n");
            else if (_dot->whitespace)
                result->append(' ');

            if (_dot->isNot(T_IDENTIFIER)) {
                result->append(tokenSpell(*_dot));
                ++_dot;
            } else {
                const TokenIterator identifierToken = _dot;
                ++_dot; // skip T_IDENTIFIER

                const QByteArray spell = tokenSpell(*identifierToken);
                if (env.isBuiltinMacro(spell)) {
585
586
587
588
589
590
                    const Macro trivial;

                    if (client)
                        client->startExpandingMacro(identifierToken->offset,
                                                    trivial, spell);

con's avatar
con committed
591
                    expand(spell.constBegin(), spell.constEnd(), result);
592
593
594
595

                    if (client)
                        client->stopExpandingMacro(_dot->offset, trivial);

con's avatar
con committed
596
597
598
599
600
601
602
                    continue;
                }

                Macro *m = env.resolve(spell);
                if (! m) {
                    result->append(spell);
                } else {
603
                    if (! m->isFunctionLike()) {
con's avatar
con committed
604
                        if (_dot->isNot(T_LPAREN)) {
605
606
607
608
                            if (client)
                                client->startExpandingMacro(identifierToken->offset,
                                                            *m, spell);

609
610
611
                            m->setHidden(true);
                            expand(m->definition(), result);
                            m->setHidden(false);
Roberto Raggi's avatar
Roberto Raggi committed
612

613
614
615
                            if (client)
                                client->stopExpandingMacro(_dot->offset, *m);

con's avatar
con committed
616
617
618
                            continue;
                        } else {
                            QByteArray tmp;
619
620
621
622

                            if (client)
                                client->startExpandingMacro(identifierToken->offset,
                                                            *m, spell);
623
624
625
                            m->setHidden(true);
                            expand(m->definition(), &tmp);
                            m->setHidden(false);
Roberto Raggi's avatar
Roberto Raggi committed
626

627
628
629
                            if (client)
                                client->stopExpandingMacro(_dot->offset, *m);

con's avatar
con committed
630
631
632
633
634
635
                            m = 0; // reset the active the macro

                            pushState(createStateFromSource(tmp));
                            if (_dot->is(T_IDENTIFIER)) {
                                const QByteArray id = tokenSpell(*_dot);
                                Macro *macro = env.resolve(id);
636
                                if (macro && macro->isFunctionLike())
con's avatar
con committed
637
638
639
640
641
642
643
644
645
646
647
648
649
650
                                    m = macro;
                            }
                            popState();

                            if (! m) {
                                result->append(tmp);
                                continue;
                            }
                        }
                    }

                    // collect the actual arguments
                    if (_dot->isNot(T_LPAREN)) {
                        // ### warnng expected T_LPAREN
651
                        result->append(m->name());
con's avatar
con committed
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
                        continue;
                    }

                    int count = 0;
                    while (_dot->isNot(T_EOF_SYMBOL)) {
                        if (_dot->is(T_LPAREN))
                            ++count;
                        else if (_dot->is(T_RPAREN)) {
                            if (! --count)
                                break;
                        }
                        ++_dot;
                    }
                    if (_dot->isNot(T_RPAREN)) {
                        // ### warning expected T_RPAREN
                    } else {
                        const char *beginOfText = startOfToken(*identifierToken);
                        const char *endOfText = endOfToken(*_dot);
                        ++_dot; // skip T_RPAREN
671
672
673
674
675
676
677
678
679
680

                        if (client) {
                            const QByteArray text =
                                    QByteArray::fromRawData(beginOfText,
                                                            endOfText - beginOfText);

                            client->startExpandingMacro(identifierToken->offset,
                                                        *m, text);
                        }

con's avatar
con committed
681
                        expand(beginOfText, endOfText, result);
682
683
684

                        if (client)
                            client->stopExpandingMacro(_dot->offset, *m);
con's avatar
con committed
685
686
687
688
689
690
691
692
693
694
                    }
                }
            }
        }
    }

    popState();
    env.currentLine = previousCurrentLine;
}

695
const char *Preprocessor::startOfToken(const Token &token) const
con's avatar
con committed
696
697
{ return _source.constBegin() + token.begin(); }

698
const char *Preprocessor::endOfToken(const Token &token) const
con's avatar
con committed
699
700
{ return _source.constBegin() + token.end(); }

701
QByteArray Preprocessor::tokenSpell(const Token &token) const
con's avatar
con committed
702
703
704
705
706
707
{
    const QByteArray text = QByteArray::fromRawData(_source.constBegin() + token.offset,
                                                    token.length);
    return text;
}

708
QByteArray Preprocessor::tokenText(const Token &token) const
con's avatar
con committed
709
710
711
712
713
714
{
    const QByteArray text(_source.constBegin() + token.offset,
                          token.length);
    return text;
}

715
void Preprocessor::processDirective(TokenIterator firstToken, TokenIterator lastToken)
con's avatar
con committed
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
{
    RangeLexer tk(firstToken, lastToken);
    ++tk; // skip T_POUND

    if (tk->is(T_IDENTIFIER)) {
        const QByteArray directive = tokenSpell(*tk);
        switch (PP_DIRECTIVE_TYPE d = classifyDirective(directive)) {
        case PP_DEFINE:
            if (! skipping())
                processDefine(firstToken, lastToken);
            break;

        case PP_INCLUDE:
        case PP_INCLUDE_NEXT:
            if (! skipping())
                processInclude(d == PP_INCLUDE_NEXT, firstToken, lastToken);
            break;

        case PP_UNDEF:
            if (! skipping())
                processUndef(firstToken, lastToken);
            break;

        case PP_ELIF:
            processElif(firstToken, lastToken);
            break;

        case PP_ELSE:
            processElse(firstToken, lastToken);
            break;

        case PP_ENDIF:
            processEndif(firstToken, lastToken);
            break;

        case PP_IF:
            processIf(firstToken, lastToken);
            break;

        case PP_IFDEF:
        case PP_IFNDEF:
            processIfdef(d == PP_IFNDEF, firstToken, lastToken);
            break;

        default:
            break;
        } // switch
    }
}

766
QVector<Token> Preprocessor::tokenize(const QByteArray &text) const
con's avatar
con committed
767
768
769
770
771
772
773
774
775
776
777
778
{
    QVector<Token> tokens;
    Lexer lex(text.constBegin(), text.constEnd());
    lex.setScanKeywords(false);
    Token tk;
    do {
        lex(&tk);
        tokens.append(tk);
    } while (tk.isNot(T_EOF_SYMBOL));
    return tokens;
}

779
void Preprocessor::processInclude(bool skipCurentPath,
con's avatar
con committed
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
                        TokenIterator firstToken, TokenIterator lastToken,
                        bool acceptMacros)
{
    RangeLexer tk(firstToken, lastToken);
    ++tk; // skip T_POUND
    ++tk; // skip `include|nclude_next'

    if (acceptMacros && tk->is(T_IDENTIFIER)) {
#if 0
        QByteArray name;
        name.reserve(256);
        MacroExpander expandInclude(env);
        expandInclude(startOfToken(tokens.at(2)),
                      startOfToken(tokens.last()),
                      &name);
        const QByteArray previousSource = switchSource(name);
        //processInclude(skipCurentPath, tokenize(name), /*accept macros=*/ false);
        (void) switchSource(previousSource);
#endif
    } else if (tk->is(T_LESS)) {
        TokenIterator start = tk.dot();
        for (; tk->isNot(T_EOF_SYMBOL); ++tk) {
            if (tk->is(T_GREATER))
                break;
        }
        const char *beginOfPath = endOfToken(*start);
        const char *endOfPath = startOfToken(*tk);
        const QByteArray path = QByteArray::fromRawData(beginOfPath,
                                                        endOfPath - beginOfPath);

        QString fn = QString::fromUtf8(path.constData(), path.length());

        if (client)
813
            client->sourceNeeded(fn, Client::IncludeGlobal, firstToken->lineno);
con's avatar
con committed
814
815
816
817
818
819
820
821
822
823
824
825
    } else if (tk->is(T_ANGLE_STRING_LITERAL) || tk->is(T_STRING_LITERAL)) {
        const QByteArray spell = tokenSpell(*tk);
        const char *beginOfPath = spell.constBegin();
        const char *endOfPath = spell.constEnd();
        const char quote = *beginOfPath;
        if (beginOfPath + 1 != endOfPath && ((quote == '"' && endOfPath[-1] == '"') ||
                                             (quote == '<' && endOfPath[-1] == '>'))) {
            const QByteArray path = QByteArray::fromRawData(beginOfPath + 1,
                                                            spell.length() - 2);
            QString fn = QString::fromUtf8(path.constData(), path.length());

            if (client)
826
                client->sourceNeeded(fn, Client::IncludeLocal, firstToken->lineno);
con's avatar
con committed
827
828
829
830
        }
    }
}

831
void Preprocessor::processDefine(TokenIterator firstToken, TokenIterator lastToken)
con's avatar
con committed
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
{
    RangeLexer tk(firstToken, lastToken);

    if (tk.size() < 3)
        return; // nothing to do

    ++tk; // skip T_POUND
    ++tk; // skip T_DEFINE

    if (tk->isNot(T_IDENTIFIER)) {
        // ### warning expected an `identifier'
        return;
    }

    Macro macro;
847
848
849
    macro.setFileName(env.currentFile);
    macro.setLine(env.currentLine);
    macro.setName(tokenText(*tk));
con's avatar
con committed
850
851
852
853
    ++tk; // skip T_IDENTIFIER

    if (tk->is(T_LPAREN) && ! tk->whitespace) {
        // a function-like macro definition
854
        macro.setFunctionLike(true);
con's avatar
con committed
855
856
857

        ++tk; // skip T_LPAREN
        if (tk->is(T_IDENTIFIER)) {
858
            macro.addFormal(tokenText(*tk));
con's avatar
con committed
859
860
861
862
863
            ++tk; // skip T_IDENTIFIER
            while (tk->is(T_COMMA)) {
                ++tk;// skip T_COMMA
                if (tk->isNot(T_IDENTIFIER))
                    break;
864
                macro.addFormal(tokenText(*tk));
con's avatar
con committed
865
866
867
868
869
                ++tk; // skip T_IDENTIFIER
            }
        }

        if (tk->is(T_DOT_DOT_DOT)) {
870
            macro.setVariadic(true);
con's avatar
con committed
871
872
873
874
875
876
877
878
879
880
881
            ++tk; // skip T_DOT_DOT_DOT
        }

        if (tk->isNot(T_RPAREN)) {
            // ### warning expected `)'
            return;
        }

        ++tk; // skip T_RPAREN
    }

882
883
884
885
886
887
888
889
890
891
892
893
894
    if (isQtReservedWord(macro.name())) {
        QByteArray macroId = macro.name();

        if (macro.isFunctionLike()) {
            macroId += '(';
            bool fst = true;
            foreach (const QByteArray formal, macro.formals()) {
                if (! fst)
                    macroId += ", ";
                fst = false;
                macroId += formal;
            }
            macroId += ')';
con's avatar
con committed
895
896
        }

897
898
        macro.setDefinition(macroId);
    } else {
899
        // ### make me fast!
con's avatar
con committed
900
901
        const char *startOfDefinition = startOfToken(*tk);
        const char *endOfDefinition = startOfToken(*lastToken);
902
903
904
905
906
        QByteArray definition(startOfDefinition,
                              endOfDefinition - startOfDefinition);
        definition.replace("\\\n", " ");
        definition.replace('\n', ' ');
        macro.setDefinition(definition.trimmed());
con's avatar
con committed
907
908
909
910
    }

    env.bind(macro);

Roberto Raggi's avatar
Roberto Raggi committed
911
912
    if (client)
        client->macroAdded(macro);
con's avatar
con committed
913
914
}

915
void Preprocessor::processIf(TokenIterator firstToken, TokenIterator lastToken)
con's avatar
con committed
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
941
{
    RangeLexer tk(firstToken, lastToken);

    ++tk; // skip T_POUND
    ++tk; // skipt `if'

    if (testIfLevel()) {
        const char *first = startOfToken(*tk);
        const char *last = startOfToken(*lastToken);

        MacroExpander expandCondition (env);
        QByteArray condition;
        condition.reserve(256);
        expandCondition(first, last, &condition);

        QVector<Token> tokens = tokenize(condition);

        const Value result = evalExpression(tokens.constBegin(),
                                            tokens.constEnd() - 1,
                                            condition);

        _true_test[iflevel] = ! result.is_zero ();
        _skipping[iflevel]  =   result.is_zero ();
    }
}

942
void Preprocessor::processElse(TokenIterator firstToken, TokenIterator lastToken)
con's avatar
con committed
943
944
945
946
947
948
949
950
951
952
953
954
{
    RangeLexer tk(firstToken, lastToken);

    if (iflevel == 0 && !skipping ()) {
        // std::cerr << "*** WARNING #else without #if" << std::endl;
    } else if (iflevel > 0 && _skipping[iflevel - 1]) {
        _skipping[iflevel] = true;
    } else {
        _skipping[iflevel] = _true_test[iflevel];
    }
}

955
void Preprocessor::processElif(TokenIterator firstToken, TokenIterator lastToken)
con's avatar
con committed
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
{
    RangeLexer tk(firstToken, lastToken);
    ++tk; // skip T_POUND
    ++tk; // skipt `elif'

    if (! (iflevel > 0)) {
        // std::cerr << "*** WARNING: " << __FILE__ << __LINE__ << std::endl;
    } else if (iflevel == 0 && !skipping()) {
        // std::cerr << "*** WARNING #else without #if" << std::endl;
    } else if (!_true_test[iflevel] && !_skipping[iflevel - 1]) {
        const Value result = evalExpression(tk.dot(), lastToken, _source);
        _true_test[iflevel] = ! result.is_zero ();
        _skipping[iflevel]  =   result.is_zero ();
    } else {
        _skipping[iflevel] = true;
    }
}

974
void Preprocessor::processEndif(TokenIterator, TokenIterator)
con's avatar
con committed
975
976
977
978
979
980
981
982
983
984
985
{
    if (iflevel == 0 && !skipping()) {
        // std::cerr << "*** WARNING #endif without #if" << std::endl;
    } else {
        _skipping[iflevel] = false;
        _true_test[iflevel] = false;

        --iflevel;
    }
}

986
void Preprocessor::processIfdef(bool checkUndefined,
con's avatar
con committed
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
                      TokenIterator firstToken, TokenIterator lastToken)
{
    RangeLexer tk(firstToken, lastToken);

    ++tk; // skip T_POUND
    ++tk; // skip `ifdef'
    if (testIfLevel()) {
        if (tk->is(T_IDENTIFIER)) {
            const QByteArray macroName = tokenSpell(*tk);
            bool value = env.resolve(macroName) != 0 || env.isBuiltinMacro(macroName);

            if (checkUndefined)
                value = ! value;