TranslationUnit.cpp 15.4 KB
Newer Older
1
/**************************************************************************
con's avatar
con committed
2
3
4
**
** This file is part of Qt Creator
**
hjk's avatar
hjk committed
5
** Copyright (c) 2010 Nokia Corporation and/or its subsidiary(-ies).
con's avatar
con committed
6
**
7
** Contact: Nokia Corporation (qt-info@nokia.com)
con's avatar
con committed
8
**
9
** Commercial Usage
10
**
11
12
13
14
** Licensees holding valid Qt Commercial licenses may use this file in
** accordance with the Qt Commercial License Agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and Nokia.
15
**
16
** GNU Lesser General Public License Usage
17
**
18
19
20
21
22
23
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
24
**
25
** If you are unsure which license is appropriate for your use, please
hjk's avatar
hjk committed
26
** contact the sales department at http://qt.nokia.com/contact.
con's avatar
con committed
27
**
28
**************************************************************************/
con's avatar
con committed
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
// Copyright (c) 2008 Roberto Raggi <roberto.raggi@gmail.com>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// 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
// AUTHORS OR COPYRIGHT HOLDERS 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 "TranslationUnit.h"
#include "Control.h"
#include "Parser.h"
#include "Lexer.h"
#include "MemoryPool.h"
#include "AST.h"
#include "Literals.h"
#include "DiagnosticClient.h"
#include <stack>
#include <cstdarg>
#include <algorithm>

Roberto Raggi's avatar
Roberto Raggi committed
61
using namespace CPlusPlus;
con's avatar
con committed
62

Roberto Raggi's avatar
Roberto Raggi committed
63
TranslationUnit::TranslationUnit(Control *control, const StringLiteral *fileId)
con's avatar
con committed
64
65
66
67
68
69
70
71
    : _control(control),
      _fileId(fileId),
      _firstSourceChar(0),
      _lastSourceChar(0),
      _pool(0),
      _ast(0),
      _flags(0)
{
72
    _tokens = new std::vector<Token>();
con's avatar
con committed
73
74
75
76
77
78
79
80
81
82
83
84
    _previousTranslationUnit = control->switchTranslationUnit(this);
    _pool = new MemoryPool();
}

TranslationUnit::~TranslationUnit()
{
    (void) _control->switchTranslationUnit(_previousTranslationUnit);
    delete _tokens;
    delete _pool;
}

bool TranslationUnit::qtMocRunEnabled() const
85
{ return f._qtMocRunEnabled; }
con's avatar
con committed
86
87

void TranslationUnit::setQtMocRunEnabled(bool onoff)
88
{ f._qtMocRunEnabled = onoff; }
con's avatar
con committed
89

90
91
92
93
94
95
bool TranslationUnit::cxx0xEnabled() const
{ return f._cxx0xEnabled; }

void TranslationUnit::setCxxOxEnabled(bool onoff)
{ f._cxx0xEnabled = onoff; }

Roberto Raggi's avatar
Roberto Raggi committed
96
bool TranslationUnit::objCEnabled() const
97
{ return f._objCEnabled; }
Roberto Raggi's avatar
Roberto Raggi committed
98
99

void TranslationUnit::setObjCEnabled(bool onoff)
100
{ f._objCEnabled = onoff; }
Roberto Raggi's avatar
Roberto Raggi committed
101

con's avatar
con committed
102
103
104
Control *TranslationUnit::control() const
{ return _control; }

Roberto Raggi's avatar
Roberto Raggi committed
105
const StringLiteral *TranslationUnit::fileId() const
con's avatar
con committed
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
{ return _fileId; }

const char *TranslationUnit::fileName() const
{ return _fileId->chars(); }

unsigned TranslationUnit::fileNameLength() const
{ return _fileId->size(); }

const char *TranslationUnit::firstSourceChar() const
{ return _firstSourceChar; }

const char *TranslationUnit::lastSourceChar() const
{ return _lastSourceChar; }

unsigned TranslationUnit::sourceLength() const
{ return _lastSourceChar - _firstSourceChar; }

void TranslationUnit::setSource(const char *source, unsigned size)
{
    _firstSourceChar = source;
    _lastSourceChar = source + size;
}

unsigned TranslationUnit::tokenCount() const
{ return _tokens->size(); }

const Token &TranslationUnit::tokenAt(unsigned index) const
{ return _tokens->at(index); }

int TranslationUnit::tokenKind(unsigned index) const
136
{ return _tokens->at(index).f.kind; }
con's avatar
con committed
137

138
139
140
141
142
143
144
145
const char *TranslationUnit::spell(unsigned index) const
{
    if (! index)
        return 0;

    return _tokens->at(index).spell();
}

Roberto Raggi's avatar
Roberto Raggi committed
146
const Identifier *TranslationUnit::identifier(unsigned index) const
con's avatar
con committed
147
148
{ return _tokens->at(index).identifier; }

Roberto Raggi's avatar
Roberto Raggi committed
149
const Literal *TranslationUnit::literal(unsigned index) const
con's avatar
con committed
150
151
{ return _tokens->at(index).literal; }

Roberto Raggi's avatar
Roberto Raggi committed
152
const StringLiteral *TranslationUnit::stringLiteral(unsigned index) const
con's avatar
con committed
153
154
{ return _tokens->at(index).string; }

Roberto Raggi's avatar
Roberto Raggi committed
155
const NumericLiteral *TranslationUnit::numericLiteral(unsigned index) const
con's avatar
con committed
156
157
158
159
160
161
162
163
{ return _tokens->at(index).number; }

unsigned TranslationUnit::matchingBrace(unsigned index) const
{ return _tokens->at(index).close_brace; }

MemoryPool *TranslationUnit::memoryPool() const
{ return _pool; }

164
AST *TranslationUnit::ast() const
con's avatar
con committed
165
166
167
{ return _ast; }

bool TranslationUnit::isTokenized() const
168
{ return f._tokenized; }
con's avatar
con committed
169
170

bool TranslationUnit::isParsed() const
171
{ return f._parsed; }
con's avatar
con committed
172
173
174
175
176
177

void TranslationUnit::tokenize()
{
    if (isTokenized())
        return;

178
    f._tokenized = true;
con's avatar
con committed
179
180

    Lexer lex(this);
181
    lex.setQtMocRunEnabled(f._qtMocRunEnabled);
182
    lex.setCxxOxEnabled(f._cxx0xEnabled);
183
    lex.setObjCEnabled(f._objCEnabled);
con's avatar
con committed
184
185
186
187
188
189
190

    std::stack<unsigned> braces;
    _tokens->push_back(Token()); // the first token needs to be invalid!

    pushLineOffset(0);
    pushPreprocessorLine(0, 1, fileId());

Roberto Raggi's avatar
Roberto Raggi committed
191
192
    const Identifier *lineId   = control()->findOrInsertIdentifier("line");
    const Identifier *genId    = control()->findOrInsertIdentifier("gen");
con's avatar
con committed
193

194
    bool generated = false;
con's avatar
con committed
195
196
197
198
199
200
201
202
    Token tk;
    do {
        lex(&tk);

      _Lrecognize:
        if (tk.is(T_POUND)) {
            unsigned offset = tk.offset;
            lex(&tk);
203

204
            if (! tk.f.newline && tk.is(T_IDENTIFIER) && tk.identifier == genId) {
205
                // it's a gen directive.
con's avatar
con committed
206
                lex(&tk);
207

208
                if (! tk.f.newline && tk.is(T_TRUE)) {
209
210
211
212
213
214
                    lex(&tk);
                    generated = true;
                } else {
                    generated = false;
                }
            } else {
215
                if (! tk.f.newline && tk.is(T_IDENTIFIER) && tk.identifier == lineId)
216
                    lex(&tk);
217
                if (! tk.f.newline && tk.is(T_NUMERIC_LITERAL)) {
218
                    unsigned line = (unsigned) strtoul(tk.spell(), 0, 0);
con's avatar
con committed
219
                    lex(&tk);
220
                    if (! tk.f.newline && tk.is(T_STRING_LITERAL)) {
Roberto Raggi's avatar
Roberto Raggi committed
221
222
                        const StringLiteral *fileName = control()->findOrInsertStringLiteral(tk.string->chars(),
                                                                                             tk.string->size());
223
224
225
                        pushPreprocessorLine(offset, line, fileName);
                        lex(&tk);
                    }
con's avatar
con committed
226
227
                }
            }
228
            while (tk.isNot(T_EOF_SYMBOL) && ! tk.f.newline)
con's avatar
con committed
229
230
                lex(&tk);
            goto _Lrecognize;
231
        } else if (tk.f.kind == T_LBRACE) {
con's avatar
con committed
232
            braces.push(_tokens->size());
233
        } else if (tk.f.kind == T_RBRACE && ! braces.empty()) {
con's avatar
con committed
234
235
236
237
            const unsigned open_brace_index = braces.top();
            braces.pop();
            (*_tokens)[open_brace_index].close_brace = _tokens->size();
        }
238
        tk.f.generated = generated;
con's avatar
con committed
239
        _tokens->push_back(tk);
240
    } while (tk.f.kind);
con's avatar
con committed
241
242
243
244
245
246
247
248

    for (; ! braces.empty(); braces.pop()) {
        unsigned open_brace_index = braces.top();
        (*_tokens)[open_brace_index].close_brace = _tokens->size();
    }
}

bool TranslationUnit::skipFunctionBody() const
249
{ return f._skipFunctionBody; }
con's avatar
con committed
250
251

void TranslationUnit::setSkipFunctionBody(bool skipFunctionBody)
252
{ f._skipFunctionBody = skipFunctionBody; }
con's avatar
con committed
253

254
bool TranslationUnit::parse(ParseMode mode)
con's avatar
con committed
255
256
{
    if (isParsed())
257
        return false;
con's avatar
con committed
258
259
260
261

    if (! isTokenized())
        tokenize();

262
263
    f._parsed = true;

con's avatar
con committed
264
    Parser parser(this);
265
    parser.setQtMocRunEnabled(f._qtMocRunEnabled);
266
    parser.setCxxOxEnabled(f._cxx0xEnabled);
267
    parser.setObjCEnabled(f._objCEnabled);
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289

    bool parsed = false;

    switch (mode) {
    case ParseTranlationUnit: {
        TranslationUnitAST *node = 0;
        parsed = parser.parseTranslationUnit(node);
        _ast = node;
    } break;

    case ParseDeclaration: {
        DeclarationAST *node = 0;
        parsed = parser.parseDeclaration(node);
        _ast = node;
    } break;

    case ParseExpression: {
        ExpressionAST *node = 0;
        parsed = parser.parseExpression(node);
        _ast = node;
    } break;

290
291
292
293
294
295
    case ParseDeclarator: {
        DeclaratorAST *node = 0;
        parsed = parser.parseDeclarator(node);
        _ast = node;
    } break;

296
297
298
299
300
301
302
303
304
305
306
    case ParseStatement: {
        StatementAST *node = 0;
        parsed = parser.parseStatement(node);
        _ast = node;
    } break;

    default:
        break;
    } // switch

    return parsed;
con's avatar
con committed
307
308
309
310
311
312
313
}

void TranslationUnit::pushLineOffset(unsigned offset)
{ _lineOffsets.push_back(offset); }

void TranslationUnit::pushPreprocessorLine(unsigned offset,
                                           unsigned line,
Roberto Raggi's avatar
Roberto Raggi committed
314
                                           const StringLiteral *fileName)
con's avatar
con committed
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
{ _ppLines.push_back(PPLine(offset, line, fileName)); }

unsigned TranslationUnit::findLineNumber(unsigned offset) const
{
    std::vector<unsigned>::const_iterator it =
        std::lower_bound(_lineOffsets.begin(), _lineOffsets.end(), offset);

    if (it != _lineOffsets.begin())
        --it;

    return it - _lineOffsets.begin();
}

TranslationUnit::PPLine TranslationUnit::findPreprocessorLine(unsigned offset) const
{
    std::vector<PPLine>::const_iterator it =
        std::lower_bound(_ppLines.begin(), _ppLines.end(), PPLine(offset));

    if (it != _ppLines.begin())
        --it;

    return *it;
}

unsigned TranslationUnit::findColumnNumber(unsigned offset, unsigned lineNumber) const
{
    if (! offset)
        return 0;

    return offset - _lineOffsets[lineNumber];
}

void TranslationUnit::getTokenPosition(unsigned index,
                                       unsigned *line,
                                       unsigned *column,
Roberto Raggi's avatar
Roberto Raggi committed
350
                                       const StringLiteral **fileName) const
con's avatar
con committed
351
352
{ return getPosition(tokenAt(index).offset, line, column, fileName); }

Roberto Raggi's avatar
Roberto Raggi committed
353
354
void TranslationUnit::getTokenStartPosition(unsigned index, unsigned *line,
                                            unsigned *column,
Roberto Raggi's avatar
Roberto Raggi committed
355
                                            const StringLiteral **fileName) const
Roberto Raggi's avatar
Roberto Raggi committed
356
357
358
359
{ return getPosition(tokenAt(index).begin(), line, column, fileName); }

void TranslationUnit::getTokenEndPosition(unsigned index, unsigned *line,
                                          unsigned *column,
Roberto Raggi's avatar
Roberto Raggi committed
360
                                          const StringLiteral **fileName) const
Roberto Raggi's avatar
Roberto Raggi committed
361
362
{ return getPosition(tokenAt(index).end(), line, column, fileName); }

con's avatar
con committed
363
364
365
void TranslationUnit::getPosition(unsigned tokenOffset,
                                  unsigned *line,
                                  unsigned *column,
Roberto Raggi's avatar
Roberto Raggi committed
366
                                  const StringLiteral **fileName) const
con's avatar
con committed
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
{
    unsigned lineNumber = findLineNumber(tokenOffset);
    unsigned columnNumber = findColumnNumber(tokenOffset, lineNumber);
    const PPLine ppLine = findPreprocessorLine(tokenOffset);

    lineNumber -= findLineNumber(ppLine.offset) + 1;
    lineNumber += ppLine.line;

    if (line)
        *line = lineNumber;

    if (column)
        *column = columnNumber;

    if (fileName)
       *fileName = ppLine.fileName;
}

bool TranslationUnit::blockErrors(bool block)
{
387
388
    bool previous = f._blockErrors;
    f._blockErrors = block;
con's avatar
con committed
389
390
391
392
393
    return previous;
}

void TranslationUnit::warning(unsigned index, const char *format, ...)
{
394
    if (f._blockErrors)
con's avatar
con committed
395
396
397
398
399
        return;

    index = std::min(index, tokenCount() - 1);

    unsigned line = 0, column = 0;
Roberto Raggi's avatar
Roberto Raggi committed
400
    const StringLiteral *fileName = 0;
con's avatar
con committed
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
    getTokenPosition(index, &line, &column, &fileName);

    if (DiagnosticClient *client = control()->diagnosticClient()) {
        va_list args;
        va_start(args, format);
        client->report(DiagnosticClient::Warning, fileName, line, column,
                       format, args);
        va_end(args);
    } else {
        fprintf(stderr, "%s:%d: ", fileName->chars(), line);
        fprintf(stderr, "warning: ");

        va_list args;
        va_start(args, format);
        vfprintf(stderr, format, args);
        va_end(args);
        fputc('\n', stderr);

        showErrorLine(index, column, stderr);
    }
}

void TranslationUnit::error(unsigned index, const char *format, ...)
{
425
    if (f._blockErrors)
con's avatar
con committed
426
427
428
429
430
        return;

    index = std::min(index, tokenCount() - 1);

    unsigned line = 0, column = 0;
Roberto Raggi's avatar
Roberto Raggi committed
431
    const StringLiteral *fileName = 0;
con's avatar
con committed
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
    getTokenPosition(index, &line, &column, &fileName);

    if (DiagnosticClient *client = control()->diagnosticClient()) {
        va_list args;
        va_start(args, format);
        client->report(DiagnosticClient::Error, fileName, line, column,
                       format, args);
        va_end(args);
    } else {
        fprintf(stderr, "%s:%d: ", fileName->chars(), line);
        fprintf(stderr, "error: ");

        va_list args;
        va_start(args, format);
        vfprintf(stderr, format, args);
        va_end(args);
        fputc('\n', stderr);

        showErrorLine(index, column, stderr);
    }
}

void TranslationUnit::fatal(unsigned index, const char *format, ...)
{
456
    if (f._blockErrors)
con's avatar
con committed
457
458
459
460
461
        return;

    index = std::min(index, tokenCount() - 1);

    unsigned line = 0, column = 0;
Roberto Raggi's avatar
Roberto Raggi committed
462
    const StringLiteral *fileName = 0;
con's avatar
con committed
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
    getTokenPosition(index, &line, &column, &fileName);

    if (DiagnosticClient *client = control()->diagnosticClient()) {
        va_list args;
        va_start(args, format);
        client->report(DiagnosticClient::Fatal, fileName, line, column,
                       format, args);
        va_end(args);
    } else {
        fprintf(stderr, "%s:%d: ", fileName->chars(), line);
        fprintf(stderr, "fatal: ");

        va_list args;
        va_start(args, format);
        vfprintf(stderr, format, args);
        va_end(args);
        fputc('\n', stderr);

        showErrorLine(index, column, stderr);
    }

    exit(EXIT_FAILURE);
}

487
488
489
490
491
492
unsigned TranslationUnit::findPreviousLineOffset(unsigned tokenIndex) const
{
    unsigned lineOffset = _lineOffsets[findLineNumber(_tokens->at(tokenIndex).offset)];
    return lineOffset;
}

con's avatar
con committed
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
void TranslationUnit::showErrorLine(unsigned index, unsigned column, FILE *out)
{
    unsigned lineOffset = _lineOffsets[findLineNumber(_tokens->at(index).offset)];
    for (const char *cp = _firstSourceChar + lineOffset + 1; *cp && *cp != '\n'; ++cp) {
        fputc(*cp, out);
    }
    fputc('\n', out);

    const char *end = _firstSourceChar + lineOffset + 1 + column - 1;
    for (const char *cp = _firstSourceChar + lineOffset + 1; cp != end; ++cp) {
        if (*cp != '\t')
            fputc(' ', out);
        else
            fputc('\t', out);
    }
    fputc('^', out);
    fputc('\n', out);
}

void TranslationUnit::resetAST()
{
    delete _pool;
    _pool = 0;
Roberto Raggi's avatar
Roberto Raggi committed
516
    _ast = 0;
con's avatar
con committed
517
518
519
520
521
522
523
524
525
}

void TranslationUnit::release()
{
    resetAST();
    delete _tokens;
    _tokens = 0;
}

Roberto Raggi's avatar
Roberto Raggi committed
526