C++: Core changes in preprocessing

Summary of most relevant items:

- Preprocessor output format change. No more gen true/false. Instead
  a more intuitive and natural expansion (like from a real compiler) is
  performed directly corresponding to the macro invocation. Notice that
  information about the generated tokens is not lost, because it's now
  embedded in the expansion section header (in terms of lines and columns
  as explained in the code). In addition the location on where the macro
  expansion happens is also documented for future use.

- Fix line control directives and associated token line numbers.
  This was not detected in tests cases because some of them were
  actually wrong: Within expansions the line information was being
  considered as originally computed in the macro definition, while
  the desired and expected for Creator's reporting mechanism (just
  like regular compilers) is the line from the expanded version
  of the tokens.

- Do not allow for eager expansion. This was previously being done
  inside define directives. However, it's not allowed and might
  lead to incorrect results, since the argument substitution should
  only happen upon the macro invocation (and following nested ones).
  At least GCC and clang are consistent with that. See test case
  tst_Preprocessor:dont_eagerly_expand for a detailed explanation.

- Revive the 'expanded' token flag. This is used to mark every token
  that originates from a macro expansion. Notice, however, that
  expanded tokens are not necessarily generated tokens (although
  every generated token is a expanded token). Expanded tokens that
  are not generated are those which are still considered by our
  code model features, since they are visible on the editor. The
  translation unit is smart enough to calculate line/column position
  for such tokens based on the information from the expansion section
  header.

- How expansions are tracked has also changed. Now, we simply add
  two surrounding marker tokens to each "top-level" expansion
  sequence. There is an enumeration that control expansion states.
  Also, no "previous" token is kept around.

- Preprocessor client methods suffered a change in signature so
  they now receive the line number of the action in question as
  a paramater. Previously such line could be retrieved by the client
  implementation by accessing the environment line. However, this
  is not reliable because we try to avoid synchronization of the
  output/environment lines in order to avoid unnecessary output,
  while expanding macros or handling preprocessor directives.

- Although macros are not expanded during define directives (as
  mentioned above) the preprocessor client is now "notified"
  when it sees a macro. This is to allow usage tracking.

- Other small stuff.

This is all in one patch because the fixes are a consequence
of the change in preprocessing control.

Change-Id: I8f4c6e6366f37756ec65d0a93b79f72a3ac4ed50
Reviewed-by: Roberto Raggi <roberto.raggi@nokia.com>
This commit is contained in:
Leandro Melo
2012-06-20 15:22:02 +02:00
parent e99c139352
commit d6ccffc06c
32 changed files with 1140 additions and 442 deletions

View File

@@ -321,13 +321,29 @@ public:
public:
struct Flags {
// The token kind.
unsigned kind : 8;
// The token starts a new line.
unsigned newline : 1;
// The token is preceeded by whitespace(s).
unsigned whitespace : 1;
// The token is joined with the previous one.
unsigned joined : 1;
// The token originates from a macro expansion.
unsigned expanded : 1;
// The token originates from a macro expansion and does not correspond to an
// argument that went through substitution. Notice the example:
//
// #define FOO(a, b) a + b;
// FOO(1, 2)
//
// After preprocessing we would expect the following tokens: 1 + 2;
// Tokens '1', '+', '2', and ';' are all expanded. However only tokens '+' and ';'
// are generated.
unsigned generated : 1;
// Unused...
unsigned pad : 3;
// The token lenght.
unsigned length : 16;
};
union {

View File

@@ -27,8 +27,10 @@
#include "Literals.h"
#include "DiagnosticClient.h"
#include <stack>
#include <vector>
#include <cstdarg>
#include <algorithm>
#include <utility>
#ifdef _MSC_VER
# define va_copy(dst, src) ((dst) = (src))
@@ -176,27 +178,84 @@ void TranslationUnit::tokenize()
pushPreprocessorLine(0, 1, fileId());
const Identifier *lineId = control()->identifier("line");
const Identifier *genId = control()->identifier("gen");
const Identifier *expansionId = control()->identifier("expansion");
const Identifier *beginId = control()->identifier("begin");
const Identifier *endId = control()->identifier("end");
// We need to track information about the expanded tokens. A vector with an addition
// explicit index control is used instead of queue mainly for performance reasons.
std::vector<std::pair<unsigned, unsigned> > lineColumn;
unsigned lineColumnIdx = 0;
bool generated = false;
Token tk;
do {
lex(&tk);
_Lrecognize:
_Lrecognize:
if (tk.is(T_POUND) && tk.newline()) {
unsigned offset = tk.offset;
lex(&tk);
if (! tk.f.newline && tk.is(T_IDENTIFIER) && tk.identifier == genId) {
// it's a gen directive.
if (! tk.f.newline && tk.is(T_IDENTIFIER) && tk.identifier == expansionId) {
// It's an expansion mark.
lex(&tk);
if (! tk.f.newline && tk.is(T_TRUE)) {
lex(&tk);
generated = true;
} else {
generated = false;
if (!tk.f.newline && tk.is(T_IDENTIFIER)) {
if (tk.identifier == beginId) {
// Start of a macro expansion section.
lex(&tk);
// Gather where the expansion happens and its length.
unsigned macroOffset = static_cast<unsigned>(strtoul(tk.spell(), 0, 0));
lex(&tk);
lex(&tk); // Skip the separating comma
unsigned macroLength = static_cast<unsigned>(strtoul(tk.spell(), 0, 0));
lex(&tk);
// NOTE: We are currently not using the macro offset and length. They
// are kept here for now because of future use.
Q_UNUSED(macroOffset)
Q_UNUSED(macroLength)
// Now we need to gather the real line and columns from the upcoming
// tokens. But notice this is only relevant for tokens which are expanded
// but not generated.
while (tk.isNot(T_EOF_SYMBOL) && !tk.f.newline) {
// When we get a ~ it means there's a number of generated tokens
// following. Otherwise, we have actual data.
if (tk.is(T_TILDE)) {
lex(&tk);
// Get the total number of generated tokens and specifiy "null"
// information for them.
unsigned totalGenerated =
static_cast<unsigned>(strtoul(tk.spell(), 0, 0));
const std::size_t previousSize = lineColumn.size();
lineColumn.resize(previousSize + totalGenerated);
std::fill(lineColumn.begin() + previousSize,
lineColumn.end(),
std::make_pair(0, 0));
lex(&tk);
} else if (tk.is(T_NUMERIC_LITERAL)) {
unsigned line = static_cast<unsigned>(strtoul(tk.spell(), 0, 0));
lex(&tk);
lex(&tk); // Skip the separating colon
unsigned column = static_cast<unsigned>(strtoul(tk.spell(), 0, 0));
// Store line and column for this non-generated token.
lineColumn.push_back(std::make_pair(line, column));
lex(&tk);
}
}
} else if (tk.identifier == endId) {
// End of a macro expansion.
lineColumn.clear();
lineColumnIdx = 0;
lex(&tk);
}
}
} else {
if (! tk.f.newline && tk.is(T_IDENTIFIER) && tk.identifier == lineId)
@@ -211,9 +270,9 @@ void TranslationUnit::tokenize()
lex(&tk);
}
}
while (tk.isNot(T_EOF_SYMBOL) && ! tk.f.newline)
lex(&tk);
}
while (tk.isNot(T_EOF_SYMBOL) && ! tk.f.newline)
lex(&tk);
goto _Lrecognize;
} else if (tk.f.kind == T_LBRACE) {
braces.push(_tokens->size());
@@ -225,7 +284,24 @@ void TranslationUnit::tokenize()
_comments->push_back(tk);
continue; // comments are not in the regular token stream
}
tk.f.generated = generated;
bool currentExpanded = false;
bool currentGenerated = false;
if (!lineColumn.empty() && lineColumnIdx < lineColumn.size()) {
currentExpanded = true;
const std::pair<unsigned, unsigned> &p = lineColumn[lineColumnIdx];
if (p.first)
_expandedLineColumn.insert(std::make_pair(tk.offset, p));
else
currentGenerated = true;
++lineColumnIdx;
}
tk.f.expanded = currentExpanded;
tk.f.generated = currentGenerated;
_tokens->push_back(tk);
} while (tk.f.kind);
@@ -355,12 +431,32 @@ void TranslationUnit::getPosition(unsigned tokenOffset,
unsigned *column,
const StringLiteral **fileName) const
{
unsigned lineNumber = findLineNumber(tokenOffset);
unsigned columnNumber = findColumnNumber(tokenOffset, lineNumber);
const PPLine ppLine = findPreprocessorLine(tokenOffset);
unsigned lineNumber = 0;
unsigned columnNumber = 0;
const StringLiteral *file = 0;
lineNumber -= findLineNumber(ppLine.offset) + 1;
lineNumber += ppLine.line;
// If this token is expanded we already have the information directly from the expansion
// section header. Otherwise, we need to calculate it.
std::map<unsigned, std::pair<unsigned, unsigned> >::const_iterator it =
_expandedLineColumn.find(tokenOffset);
if (it != _expandedLineColumn.end()) {
lineNumber = it->second.first;
columnNumber = it->second.second + 1;
file = _fileId;
} else {
// Identify line within the entire translation unit.
lineNumber = findLineNumber(tokenOffset);
// Identify column.
columnNumber = findColumnNumber(tokenOffset, lineNumber);
// Adjust the line in regards to the preprocessing markers.
const PPLine ppLine = findPreprocessorLine(tokenOffset);
lineNumber -= findLineNumber(ppLine.offset) + 1;
lineNumber += ppLine.line;
file = ppLine.fileName;
}
if (line)
*line = lineNumber;
@@ -369,7 +465,7 @@ void TranslationUnit::getPosition(unsigned tokenOffset,
*column = columnNumber;
if (fileName)
*fileName = ppLine.fileName;
*fileName = file;
}
bool TranslationUnit::blockErrors(bool block)

View File

@@ -27,7 +27,7 @@
#include "DiagnosticClient.h"
#include <cstdio>
#include <vector>
#include <map>
namespace CPlusPlus {
@@ -170,6 +170,7 @@ private:
std::vector<Token> *_comments;
std::vector<unsigned> _lineOffsets;
std::vector<PPLine> _ppLines;
std::map<unsigned, std::pair<unsigned, unsigned> > _expandedLineColumn; // TODO: Replace this for a hash
MemoryPool *_pool;
AST *_ast;
TranslationUnit *_previousTranslationUnit;

View File

@@ -60,7 +60,7 @@ QByteArray FastPreprocessor::run(QString fileName, const QString &source)
return preprocessed;
}
void FastPreprocessor::sourceNeeded(QString &fileName, IncludeType, unsigned)
void FastPreprocessor::sourceNeeded(unsigned, QString &fileName, IncludeType)
{ mergeEnvironment(fileName); }
void FastPreprocessor::mergeEnvironment(const QString &fileName)

View File

@@ -59,18 +59,19 @@ public:
QByteArray run(QString fileName, const QString &source);
// CPlusPlus::Client
virtual void sourceNeeded(QString &fileName, IncludeType, unsigned);
virtual void sourceNeeded(unsigned, QString &fileName, IncludeType);
virtual void macroAdded(const Macro &) {}
virtual void passedMacroDefinitionCheck(unsigned, const Macro &) {}
virtual void passedMacroDefinitionCheck(unsigned, unsigned, const Macro &) {}
virtual void failedMacroDefinitionCheck(unsigned, const ByteArrayRef &) {}
virtual void startExpandingMacro(unsigned,
const Macro &,
const ByteArrayRef &,
const QVector<MacroArgumentReference> &) {}
virtual void notifyMacroReference(unsigned, unsigned, const Macro &) {}
virtual void startExpandingMacro(unsigned,
unsigned,
const Macro &,
const QVector<MacroArgumentReference> &) {}
virtual void stopExpandingMacro(unsigned, const Macro &) {}
virtual void startSkippingBlocks(unsigned) {}

View File

@@ -23,10 +23,10 @@ int ByteArrayRef::count(char ch) const
return num;
}
void Internal::PPToken::squeeze()
void Internal::PPToken::squeezeSource()
{
if (isValid()) {
m_src = m_src.mid(offset, length());
if (hasSource()) {
m_src = m_src.mid(offset, f.length);
m_src.squeeze();
offset = 0;
}

View File

@@ -96,6 +96,11 @@ public:
const QByteArray &source() const
{ return m_src; }
bool hasSource() const
{ return !m_src.isEmpty(); }
void squeezeSource();
const char *bufferStart() const
{ return m_src.constData(); }
@@ -105,11 +110,6 @@ public:
ByteArrayRef asByteArrayRef() const
{ return ByteArrayRef(&m_src, offset, length()); }
bool isValid() const
{ return !m_src.isEmpty(); }
void squeeze();
private:
QByteArray m_src;
};

View File

@@ -80,24 +80,23 @@ public:
virtual void macroAdded(const Macro &macro) = 0;
virtual void passedMacroDefinitionCheck(unsigned offset, const Macro &macro) = 0;
virtual void passedMacroDefinitionCheck(unsigned offset, unsigned line, const Macro &macro) = 0;
virtual void failedMacroDefinitionCheck(unsigned offset, const ByteArrayRef &name) = 0;
virtual void notifyMacroReference(unsigned offset, unsigned line, const Macro &macro) = 0;
virtual void startExpandingMacro(unsigned offset,
unsigned line,
const Macro &macro,
const ByteArrayRef &originalText,
const QVector<MacroArgumentReference> &actuals
= QVector<MacroArgumentReference>()) = 0;
virtual void stopExpandingMacro(unsigned offset,
const Macro &macro) = 0;
virtual void stopExpandingMacro(unsigned offset, const Macro &macro) = 0;
/// Start skipping from the given offset.
virtual void startSkippingBlocks(unsigned offset) = 0;
virtual void stopSkippingBlocks(unsigned offset) = 0;
virtual void sourceNeeded(QString &fileName, IncludeType mode,
unsigned line) = 0; // ### FIX the signature.
virtual void sourceNeeded(unsigned line, QString &fileName, IncludeType mode) = 0;
};
} // namespace CPlusPlus

View File

@@ -95,6 +95,7 @@ private:
public:
QString currentFile;
QByteArray currentFileUtf8;
unsigned currentLine;
bool hideNext;

File diff suppressed because it is too large Load Diff

View File

@@ -60,6 +60,7 @@
#include <QVector>
#include <QBitArray>
#include <QByteArray>
#include <QPair>
namespace CPlusPlus {
@@ -92,10 +93,17 @@ private:
void preprocess(const QString &filename,
const QByteArray &source,
QByteArray *result, bool noLines, bool markGeneratedTokens, bool inCondition,
unsigned offsetRef = 0, unsigned envLineRef = 1);
unsigned offsetRef = 0, unsigned lineRef = 1);
enum { MAX_LEVEL = 512 };
enum ExpansionStatus {
NotExpanding,
ReadyForExpansion,
Expanding,
JustFinishedExpansion
};
struct State {
State();
@@ -114,14 +122,17 @@ private:
bool m_inPreprocessorDirective;
QByteArray *m_result;
bool m_markGeneratedTokens;
bool m_markExpandedTokens;
bool m_noLines;
bool m_inCondition;
bool m_inDefine;
unsigned m_offsetRef;
unsigned m_envLineRef;
unsigned m_lineRef;
ExpansionStatus m_expansionStatus;
QByteArray m_expansionResult;
QVector<QPair<unsigned, unsigned> > m_expandedTokensInfo;
};
void handleDefined(PPToken *tk);
@@ -129,9 +140,11 @@ private:
void lex(PPToken *tk);
void skipPreprocesorDirective(PPToken *tk);
bool handleIdentifier(PPToken *tk);
bool handleFunctionLikeMacro(PPToken *tk, const Macro *macro, QVector<PPToken> &body,
bool addWhitespaceMarker,
const QVector<QVector<PPToken> > &actuals);
bool handleFunctionLikeMacro(PPToken *tk,
const Macro *macro,
QVector<PPToken> &body,
const QVector<QVector<PPToken> > &actuals,
unsigned lineRef);
bool skipping() const
{ return m_state.m_skipping[m_state.m_ifLevel]; }
@@ -155,30 +168,28 @@ private:
static bool isQtReservedWord(const ByteArrayRef &name);
inline bool atStartOfOutputLine() const
{ return (m_state.m_result && !m_state.m_result->isEmpty()) ? m_state.m_result->end()[-1] == '\n' : true; }
void trackExpansionCycles(PPToken *tk);
inline void startNewOutputLine() const
{
if (m_state.m_result && !m_state.m_result->isEmpty() && m_state.m_result->end()[-1] != '\n')
out('\n');
}
template <class T>
void writeOutput(const T &t);
void writeOutput(const ByteArrayRef &ref);
bool atStartOfOutputLine() const;
void maybeStartOutputLine();
void generateOutputLineMarker(unsigned lineno);
void synchronizeOutputLines(const PPToken &tk, bool forceLine = false);
void removeTrailingOutputLines();
void genLine(unsigned lineno, const QByteArray &fileName) const;
const QByteArray *currentOutputBuffer() const;
QByteArray *currentOutputBuffer();
inline void out(const QByteArray &text) const
{ if (m_state.m_result) m_state.m_result->append(text); }
void enforceSpacing(const PPToken &tk, bool forceSpacing = false);
static std::size_t computeDistance(const PPToken &tk, bool forceTillLine = false);
inline void out(char ch) const
{ if (m_state.m_result) m_state.m_result->append(ch); }
inline void out(const char *s) const
{ if (m_state.m_result) m_state.m_result->append(s); }
inline void out(const ByteArrayRef &ref) const
{ if (m_state.m_result) m_state.m_result->append(ref.start(), ref.length()); }
PPToken generateToken(enum Kind kind, const char *content, int len, unsigned lineno, bool addQuotes);
PPToken generateToken(enum Kind kind,
const char *content, int length,
unsigned lineno,
bool addQuotes,
bool addToControl = true);
PPToken generateConcatenated(const PPToken &leftTk, const PPToken &rightTk);
void startSkippingBlocks(const PPToken &tk) const;

View File

@@ -340,7 +340,7 @@ public:
void CppPreprocessor::run(const QString &fileName)
{
QString absoluteFilePath = fileName;
sourceNeeded(absoluteFilePath, IncludeGlobal, /*line = */ 0);
sourceNeeded(0, absoluteFilePath, IncludeGlobal);
}
void CppPreprocessor::resetEnvironment()
@@ -499,12 +499,12 @@ void CppPreprocessor::macroAdded(const Macro &macro)
m_currentDoc->appendMacro(macro);
}
void CppPreprocessor::passedMacroDefinitionCheck(unsigned offset, const Macro &macro)
void CppPreprocessor::passedMacroDefinitionCheck(unsigned offset, unsigned line, const Macro &macro)
{
if (! m_currentDoc)
return;
m_currentDoc->addMacroUse(macro, offset, macro.name().length(), env.currentLine,
m_currentDoc->addMacroUse(macro, offset, macro.name().length(), line,
QVector<MacroArgumentReference>());
}
@@ -516,15 +516,23 @@ void CppPreprocessor::failedMacroDefinitionCheck(unsigned offset, const ByteArra
m_currentDoc->addUndefinedMacroUse(QByteArray(name.start(), name.size()), offset);
}
void CppPreprocessor::startExpandingMacro(unsigned offset,
void CppPreprocessor::notifyMacroReference(unsigned offset, unsigned line, const Macro &macro)
{
if (! m_currentDoc)
return;
m_currentDoc->addMacroUse(macro, offset, macro.name().length(), line,
QVector<MacroArgumentReference>());
}
void CppPreprocessor::startExpandingMacro(unsigned offset, unsigned line,
const Macro &macro,
const ByteArrayRef &originalText,
const QVector<MacroArgumentReference> &actuals)
{
if (! m_currentDoc)
return;
m_currentDoc->addMacroUse(macro, offset, originalText.length(), env.currentLine, actuals);
m_currentDoc->addMacroUse(macro, offset, macro.name().length(), line, actuals);
}
void CppPreprocessor::stopExpandingMacro(unsigned, const Macro &)
@@ -573,7 +581,7 @@ void CppPreprocessor::stopSkippingBlocks(unsigned offset)
m_currentDoc->stopSkippingBlocks(offset);
}
void CppPreprocessor::sourceNeeded(QString &fileName, IncludeType type, unsigned line)
void CppPreprocessor::sourceNeeded(unsigned line, QString &fileName, IncludeType type)
{
if (fileName.isEmpty())
return;
@@ -590,7 +598,7 @@ void CppPreprocessor::sourceNeeded(QString &fileName, IncludeType type, unsigned
Document::DiagnosticMessage d(Document::DiagnosticMessage::Warning,
m_currentDoc->fileName(),
env.currentLine, /*column = */ 0,
line, /*column = */ 0,
msg);
m_currentDoc->addDiagnosticMessage(d);

View File

@@ -300,17 +300,19 @@ protected:
void mergeEnvironment(CPlusPlus::Document::Ptr doc);
virtual void macroAdded(const CPlusPlus::Macro &macro);
virtual void passedMacroDefinitionCheck(unsigned offset, const CPlusPlus::Macro &macro);
virtual void passedMacroDefinitionCheck(unsigned offset, unsigned line,
const CPlusPlus::Macro &macro);
virtual void failedMacroDefinitionCheck(unsigned offset, const CPlusPlus::ByteArrayRef &name);
virtual void notifyMacroReference(unsigned offset, unsigned line,
const CPlusPlus::Macro &macro);
virtual void startExpandingMacro(unsigned offset,
unsigned line,
const CPlusPlus::Macro &macro,
const CPlusPlus::ByteArrayRef &originalText,
const QVector<CPlusPlus::MacroArgumentReference> &actuals);
virtual void stopExpandingMacro(unsigned offset, const CPlusPlus::Macro &macro);
virtual void startSkippingBlocks(unsigned offset);
virtual void stopSkippingBlocks(unsigned offset);
virtual void sourceNeeded(QString &fileName, IncludeType type,
unsigned line);
virtual void sourceNeeded(unsigned line, QString &fileName, IncludeType type);
private:
#ifndef ICHECK_BUILD

View File

@@ -1,32 +1,15 @@
# 1 "data/empty-macro.2.cpp"
# 6 "data/empty-macro.2.cpp"
class Test {
private:
Test
#gen true
# 3 "data/empty-macro.2.cpp"
(const
#gen false
# 8 "data/empty-macro.2.cpp"
Test
#gen true
# 3 "data/empty-macro.2.cpp"
&);
#gen false
# 8 "data/empty-macro.2.cpp"
Test
#gen true
# 4 "data/empty-macro.2.cpp"
&operator=(const
#gen false
# 8 "data/empty-macro.2.cpp"
Test
#gen true
# 4 "data/empty-macro.2.cpp"
&);
#gen false
# expansion begin 182,14 8:19 ~2 8:19 ~3 8:19 ~5 8:19 ~3
Test(const Test &); Test &operator=(const Test &);
# expansion end
# 10 "data/empty-macro.2.cpp"
public:
Test();
};

View File

@@ -3,3 +3,11 @@
class EMPTY_MACRO Foo {
};
class EMPTY_MACRO Foo2 {
};
class EMPTY_MACRO Foo3 {
};
class EMPTY_MACRO Foo3 {
};

View File

@@ -4,3 +4,11 @@
class Foo {
};
class Foo2 {
};
class Foo3 {
};
class Foo3 {
};

View File

@@ -1,15 +1,18 @@
# 1 "data/identifier-expansion.1.cpp"
#gen true
# 1 "data/identifier-expansion.1.cpp"
test test
#gen false
# expansion begin 19,4 ~1
test
# expansion end
# expansion begin 24,4 ~1
test
# expansion end
# 3 "data/identifier-expansion.1.cpp"
;
void
#gen true
# 1 "data/identifier-expansion.1.cpp"
# expansion begin 36,4 ~1
test
#gen false
# expansion end
# 5 "data/identifier-expansion.1.cpp"
();

View File

@@ -1,15 +1,19 @@
# 1 "data/identifier-expansion.2.cpp"
#gen true
# 1 "data/identifier-expansion.2.cpp"
test test
#gen false
# expansion begin 45,12 ~1
test
# expansion end
# expansion begin 58,4 ~1
test
# expansion end
# 4 "data/identifier-expansion.2.cpp"
;
void
#gen true
# 1 "data/identifier-expansion.2.cpp"
# expansion begin 70,12 ~1
test
#gen false
# expansion end
# 6 "data/identifier-expansion.2.cpp"
();

View File

@@ -2,13 +2,20 @@
V(ADD) \
V(SUB)
#define OTHER_FOR_EACH(V) \
V(DIV) \
V(MUL)
#define DECLARE_INSTR(op) #op,
#define DECLARE_OP_INSTR(op) op_##op,
enum op_code {
FOR_EACH_INSTR(DECLARE_OP_INSTR)
OTHER_FOR_EACH(DECLARE_OP_INSTR)
};
static const char *names[] = {
FOR_EACH_INSTR(DECLARE_INSTR)
OTHER_FOR_EACH(DECLARE_INSTR)
};

View File

@@ -1,24 +1,22 @@
# 1 "data/identifier-expansion.3.cpp"
# 8 "data/identifier-expansion.3.cpp"
# 12 "data/identifier-expansion.3.cpp"
enum op_code {
#gen true
# 6 "data/identifier-expansion.3.cpp"
# expansion begin 195,14 ~4
op_ADD, op_SUB,
#gen false
# 10 "data/identifier-expansion.3.cpp"
# expansion end
# expansion begin 232,14 ~4
op_DIV, op_MUL,
# expansion end
# 15 "data/identifier-expansion.3.cpp"
};
static const char *names[] = {
#gen true
# 2 "data/identifier-expansion.3.cpp"
"ADD"
,
# 3 "data/identifier-expansion.3.cpp"
"SUB"
,
#gen false
# 14 "data/identifier-expansion.3.cpp"
# expansion begin 301,14 ~4
"ADD", "SUB",
# expansion end
# expansion begin 331,14 ~4
"DIV", "MUL",
# expansion end
# 21 "data/identifier-expansion.3.cpp"
};

View File

@@ -5,5 +5,9 @@
void baz()
{
int aaa;
aaa;
# expansion begin 88,4 7:9
aaa
# expansion end
# 7 "data/identifier-expansion.4.cpp"
;
}

View File

@@ -1,2 +1 @@
# 1 "data/identifier-expansion.5.cpp"
# 9 "data/identifier-expansion.5.cpp"

View File

@@ -1,8 +1,12 @@
# 1 "data/macro-test.cpp"
# 7 "data/macro-test.cpp"
void thisFunctionIsEnabled();
# 21 "data/macro-test.cpp"
void thisFunctionIsEnabled2();
# 31 "data/macro-test.cpp"
void thisFunctionIsEnabled3();
# 37 "data/macro-test.cpp"

View File

@@ -3,8 +3,7 @@
A:
#gen true
# 1 "data/macro_expand.c"
# expansion begin 32,1 ~1
Y
#gen false
# expansion end
# 5 "data/macro_expand.c"

View File

@@ -1,7 +1,7 @@
# 1 "data/macro_expand_1.cpp"
#gen true
# 1 "data/macro_expand_1.cpp"
class
#gen false
# expansion begin 33,13 ~1 2:14
class QString
# expansion end
# 2 "data/macro_expand_1.cpp"
QString;
;

View File

@@ -63,4 +63,3 @@ Write in C, write in C,
Write in C, yeah, write in C.
The government loves ADA,
Write in C.

View File

@@ -0,0 +1,26 @@
void hey(int a) {
int b = a + 10;
b;
}
class hello
{
public:
bool doit() { return true; }
bool dothat();
void run();
};
bool hello::dothat()
{
bool should = true;
if (should) {
int i = 10;
while (i > 0) {
run();
--i;
}
}
return false;
}

View File

@@ -1,8 +1,10 @@
# 1 "data/poundpound.1.cpp"
struct QQ {};
#gen true
# 3 "data/poundpound.1.cpp"
# expansion begin 50,2 ~4
typedef QQ PPCC;
#gen false
# expansion end
# 7 "data/poundpound.1.cpp"
typedef PPCC RR;

View File

@@ -1,7 +1,11 @@
# 1 "data/recursive.1.cpp"
#gen true
# 1 "data/recursive.1.cpp"
# expansion begin 25,1 ~1
b
a
#gen false
# expansion end
# expansion begin 27,1 ~1
a
# expansion end
# 6 "data/recursive.1.cpp"

View File

@@ -1,5 +1,8 @@
# 1 "data/reserved.1.cpp"
# 5 "data/reserved.1.cpp"
int f() {
foreach (QString &s, QStringList()) {
doSomething();

View File

@@ -3,11 +3,19 @@ include(../shared/shared.pri)
SOURCES += tst_preprocessor.cpp
OTHER_FILES = \
data/noPP.1.cpp data/noPP.1.errors.txt \
data/identifier-expansion.1.cpp data/identifier-expansion.1.out.cpp data/identifier-expansion.1.errors.txt \
data/identifier-expansion.2.cpp data/identifier-expansion.2.out.cpp data/identifier-expansion.2.errors.txt \
data/identifier-expansion.3.cpp data/identifier-expansion.3.out.cpp data/identifier-expansion.3.errors.txt \
data/identifier-expansion.4.cpp data/identifier-expansion.4.out.cpp data/identifier-expansion.4.errors.txt \
data/reserved.1.cpp data/reserved.1.out.cpp data/reserved.1.errors.txt \
data/macro_expand.c data/macro_expand.out.c data/macro_expand.errors.txt \
data/empty-macro.cpp data/empty-macro.out.cpp
data/noPP.1.cpp \
data/noPP.2.cpp \
data/identifier-expansion.1.cpp data/identifier-expansion.1.out.cpp \
data/identifier-expansion.2.cpp data/identifier-expansion.2.out.cpp \
data/identifier-expansion.3.cpp data/identifier-expansion.3.out.cpp \
data/identifier-expansion.4.cpp data/identifier-expansion.4.out.cpp \
data/identifier-expansion.5.cpp data/identifier-expansion.5.out.cpp \
data/reserved.1.cpp data/reserved.1.out.cpp \
data/recursive.1.cpp data/recursive.1.out.cpp \
data/macro_expand.c data/macro_expand.out.c \
data/macro_expand_1.cpp data/macro_expand_1.out.cpp \
data/macro-test.cpp data/macro-test.out.cpp \
data/poundpound.1.cpp data/poundpound.1.out.cpp \
data/empty-macro.cpp data/empty-macro.out.cpp \
data/empty-macro.2.cpp data/empty-macro.2.out.cpp \
data/macro_pounder_fn.c

View File

@@ -114,18 +114,26 @@ public:
m_definedMacrosLine.append(macro.line());
}
virtual void passedMacroDefinitionCheck(unsigned /*offset*/, const Macro &/*macro*/) {}
virtual void passedMacroDefinitionCheck(unsigned /*offset*/,
unsigned /*line*/,
const Macro &/*macro*/) {}
virtual void failedMacroDefinitionCheck(unsigned /*offset*/, const ByteArrayRef &/*name*/) {}
virtual void notifyMacroReference(unsigned offset, unsigned line, const Macro &macro)
{
m_macroUsesLine[macro.name()].append(line);
m_expandedMacrosOffset.append(offset);
}
virtual void startExpandingMacro(unsigned offset,
unsigned line,
const Macro &macro,
const ByteArrayRef &originalText,
const QVector<MacroArgumentReference> &actuals
= QVector<MacroArgumentReference>())
{
m_expandedMacros.append(QByteArray(originalText.start(), originalText.length()));
m_expandedMacros.append(macro.name());
m_expandedMacrosOffset.append(offset);
m_macroUsesLine[macro.name()].append(m_env->currentLine);
m_macroUsesLine[macro.name()].append(line);
m_macroArgsCount.append(actuals.size());
}
@@ -137,8 +145,7 @@ public:
virtual void stopSkippingBlocks(unsigned offset)
{ m_skippedBlocks.last().end = offset; }
virtual void sourceNeeded(QString &includedFileName, IncludeType mode,
unsigned line)
virtual void sourceNeeded(unsigned line, QString &includedFileName, IncludeType mode)
{
#if 1
m_recordedIncludes.append(Include(includedFileName, mode, line));
@@ -300,15 +307,14 @@ protected:
}
static QString simplified(QByteArray buf);
private /* not corrected yet */:
void macro_definition_lineno();
private:
void compare_input_output();
private slots:
void defined();
void defined_data();
void va_args();
void named_va_args();
void defined();
void defined_data();
void empty_macro_args();
void macro_args_count();
void invalid_param_count();
@@ -318,14 +324,18 @@ private slots:
void macro_arguments_notificatin();
void unfinished_function_like_macro_call();
void nasty_macro_expansion();
void tstst();
void test_file_builtin();
void glib_attribute();
void builtin__FILE__();
void blockSkipping();
void includes_1();
void dont_eagerly_expand();
void dont_eagerly_expand_data();
void comparisons_data();
void comparisons();
void comments_within();
void comments_within_data();
void multitokens_argument();
void multitokens_argument_data();
};
// Remove all #... lines, and 'simplify' string, to allow easily comparing the result
@@ -534,38 +544,72 @@ void tst_Preprocessor::macro_uses_lines()
<< buffer.lastIndexOf("ENABLE(LESS)"));
}
void tst_Preprocessor::macro_definition_lineno()
void tst_Preprocessor::multitokens_argument_data()
{
Client *client = 0; // no client.
Environment env;
Preprocessor preprocess(client, &env);
QByteArray preprocessed = preprocess.run(QLatin1String("<stdin>"),
QByteArray("#define foo(ARGS) int f(ARGS)\n"
"foo(int a);\n"));
QVERIFY(preprocessed.contains("#gen true\n# 2 \"<stdin>\"\nint f"));
QTest::addColumn<QByteArray>("input");
QTest::addColumn<QByteArray>("output");
preprocessed = preprocess.run(QLatin1String("<stdin>"),
QByteArray("#define foo(ARGS) int f(ARGS)\n"
"foo(int a)\n"
";\n"));
QVERIFY(preprocessed.contains("#gen true\n# 2 \"<stdin>\"\nint f"));
QByteArray original;
QByteArray expected;
preprocessed = preprocess.run(QLatin1String("<stdin>"),
QByteArray("#define foo(ARGS) int f(ARGS)\n"
"foo(int \n"
" a);\n"));
QVERIFY(preprocessed.contains("#gen true\n# 2 \"<stdin>\"\nint f"));
original =
"#define foo(ARGS) int f(ARGS)\n"
"foo(int a);\n";
expected =
"# 1 \"<stdin>\"\n"
"\n"
"# expansion begin 30,3 ~3 2:4 2:8 ~1\n"
"int f(int a)\n"
"# expansion end\n"
"# 2 \"<stdin>\"\n"
" ;\n";
QTest::newRow("case 1") << original << expected;
preprocessed = preprocess.run(QLatin1String("<stdin>"),
QByteArray("#define foo int f\n"
"foo;\n"));
QVERIFY(preprocessed.contains("#gen true\n# 2 \"<stdin>\"\nint f"));
original =
"#define foo(ARGS) int f(ARGS)\n"
"foo(int \n"
" a);\n";
expected =
"# 1 \"<stdin>\"\n"
"\n"
"# expansion begin 30,3 ~3 2:4 3:4 ~1\n"
"int f(int a)\n"
"# expansion end\n"
"# 3 \"<stdin>\"\n"
" ;\n";
QTest::newRow("case 2") << original << expected;
preprocessed = preprocess.run(QLatin1String("<stdin>"),
QByteArray("#define foo int f\n"
"foo\n"
";\n"));
QVERIFY(preprocessed.contains("#gen true\n# 2 \"<stdin>\"\nint f"));
original =
"#define foo(ARGS) int f(ARGS)\n"
"foo(int a = 0);\n";
expected =
"# 1 \"<stdin>\"\n"
"\n"
"# expansion begin 30,3 ~3 2:4 2:8 2:10 2:12 ~1\n"
"int f(int a = 0)\n"
"# expansion end\n"
"# 2 \"<stdin>\"\n"
" ;\n";
QTest::newRow("case 3") << original << expected;
original =
"#define foo(X) int f(X = 0)\n"
"foo(int \n"
" a);\n";
expected =
"# 1 \"<stdin>\"\n"
"\n"
"# expansion begin 28,3 ~3 2:4 3:4 ~3\n"
"int f(int a = 0)\n"
"# expansion end\n"
"# 3 \"<stdin>\"\n"
" ;\n";
QTest::newRow("case 4") << original << expected;
}
void tst_Preprocessor::multitokens_argument()
{
compare_input_output();
}
void tst_Preprocessor::objmacro_expanding_as_fnmacro_notification()
@@ -608,9 +652,17 @@ void tst_Preprocessor::unfinished_function_like_macro_call()
Preprocessor preprocess(client, &env);
QByteArray preprocessed = preprocess.run(QLatin1String("<stdin>"),
QByteArray("\n#define foo(a,b) a + b"
"\nfoo(1, 2\n"));
QByteArray expected__("# 1 \"<stdin>\"\n\n\n 1\n#gen true\n# 2 \"<stdin>\"\n+\n#gen false\n# 3 \"<stdin>\"\n 2\n");
QByteArray("\n"
"#define foo(a,b) a + b\n"
"foo(1, 2\n"));
QByteArray expected__("# 1 \"<stdin>\"\n"
"\n"
"\n"
"# expansion begin 24,3 3:4 ~1 3:7\n"
"1 + 2\n"
"# expansion end\n"
"# 4 \"<stdin>\"\n");
// DUMP_OUTPUT(preprocessed);
QCOMPARE(preprocessed, expected__);
}
@@ -668,12 +720,10 @@ void tst_Preprocessor::nasty_macro_expansion()
QVERIFY(!preprocessed.contains("FIELD32"));
}
void tst_Preprocessor::tstst()
void tst_Preprocessor::glib_attribute()
{
Client *client = 0; // no client.
Environment env;
Preprocessor preprocess(client, &env);
Preprocessor preprocess(0, &env);
QByteArray preprocessed = preprocess.run(
QLatin1String("<stdin>"),
QByteArray("\n"
@@ -681,15 +731,14 @@ void tst_Preprocessor::tstst()
"namespace std _GLIBCXX_VISIBILITY(default) {\n"
"}\n"
));
const QByteArray result____ ="# 1 \"<stdin>\"\n\n\n"
const QByteArray result____ =
"# 1 \"<stdin>\"\n"
"\n"
"\n"
"namespace std\n"
"#gen true\n"
"# 2 \"<stdin>\"\n"
"__attribute__ ((__visibility__ (\n"
"\"default\"\n"
"# 2 \"<stdin>\"\n"
")))\n"
"#gen false\n"
"# expansion begin 85,19 ~9\n"
"__attribute__ ((__visibility__ (\"default\")))\n"
"# expansion end\n"
"# 3 \"<stdin>\"\n"
" {\n"
"}\n";
@@ -698,7 +747,7 @@ void tst_Preprocessor::tstst()
QCOMPARE(preprocessed, result____);
}
void tst_Preprocessor::test_file_builtin()
void tst_Preprocessor::builtin__FILE__()
{
Client *client = 0; // no client.
Environment env;
@@ -710,13 +759,8 @@ void tst_Preprocessor::test_file_builtin()
));
const QByteArray result____ =
"# 1 \"some-file.c\"\n"
"const char *f =\n"
"#gen true\n"
"# 1 \"some-file.c\"\n"
"\"some-file.c\"\n"
"#gen false\n"
"# 2 \"some-file.c\"\n"
;
"const char *f = \"some-file.c\"\n";
QCOMPARE(preprocessed, result____);
}
@@ -727,6 +771,7 @@ void tst_Preprocessor::comparisons_data()
QTest::addColumn<QString>("errorfile");
QTest::newRow("do nothing") << "noPP.1.cpp" << "noPP.1.cpp" << "";
QTest::newRow("no PP 2") << "noPP.2.cpp" << "noPP.2.cpp" << "";
QTest::newRow("identifier-expansion 1")
<< "identifier-expansion.1.cpp" << "identifier-expansion.1.out.cpp" << "";
QTest::newRow("identifier-expansion 2")
@@ -766,6 +811,7 @@ void tst_Preprocessor::comparisons()
QByteArray errors;
QByteArray preprocessed = preprocess(infile, &errors, infile == outfile);
// DUMP_OUTPUT(preprocessed);
if (!outfile.isEmpty()) {
@@ -976,6 +1022,176 @@ void tst_Preprocessor::defined_data()
"#endif\n";
}
void tst_Preprocessor::dont_eagerly_expand_data()
{
QTest::addColumn<QByteArray>("input");
QTest::addColumn<QByteArray>("output");
QByteArray original;
QByteArray expected;
// Expansion must be processed upon invocation of the macro. Therefore a particular
// identifier within a define must not be expanded (in the case it matches an
// already known macro) during the processor directive handling, but only when
// it's actually "used". Naturally, if it's still not replaced after an invocation
// it should then be expanded. This is consistent with clang and gcc for example.
original = "#define T int\n"
"#define FOO(T) T\n"
"FOO(double)\n";
expected =
"# 1 \"<stdin>\"\n"
"\n"
"\n"
"# expansion begin 31,3 3:4\n"
"double\n"
"# expansion end\n"
"# 4 \"<stdin>\"\n";
QTest::newRow("case 1") << original << expected;
original = "#define T int\n"
"#define FOO(X) T\n"
"FOO(double)\n";
expected =
"# 1 \"<stdin>\"\n"
"\n"
"\n"
"# expansion begin 31,3 ~1\n"
"int\n"
"# expansion end\n"
"# 4 \"<stdin>\"\n";
QTest::newRow("case 2") << original << expected;
}
void tst_Preprocessor::dont_eagerly_expand()
{
compare_input_output();
}
void tst_Preprocessor::comments_within()
{
compare_input_output();
}
void tst_Preprocessor::comments_within_data()
{
QTest::addColumn<QByteArray>("input");
QTest::addColumn<QByteArray>("output");
QByteArray original;
QByteArray expected;
original = "#define FOO int x;\n"
"\n"
" // comment\n"
" // comment\n"
" // comment\n"
" // comment\n"
"FOO\n"
"x = 10\n";
expected =
"# 1 \"<stdin>\"\n"
"\n"
"\n"
"\n"
"\n"
"\n"
"\n"
"# expansion begin 76,3 ~3\n"
"int x;\n"
"# expansion end\n"
"# 8 \"<stdin>\"\n"
"x = 10\n";
QTest::newRow("case 1") << original << expected;
original = "#define FOO int x;\n"
"\n"
" /* comment\n"
" comment\n"
" comment\n"
" comment */\n"
"FOO\n"
"x = 10\n";
expected =
"# 1 \"<stdin>\"\n"
"\n"
"\n"
"\n"
"\n"
"\n"
"\n"
"# expansion begin 79,3 ~3\n"
"int x;\n"
"# expansion end\n"
"# 8 \"<stdin>\"\n"
"x = 10\n";
QTest::newRow("case 2") << original << expected;
original = "#define FOO int x;\n"
"\n"
" // comment\n"
" // comment\n"
" // comment\n"
" // comment\n"
"FOO\n"
"// test\n"
"// test again\n"
"x = 10\n";
expected =
"# 1 \"<stdin>\"\n"
"\n"
"\n"
"\n"
"\n"
"\n"
"\n"
"# expansion begin 76,3 ~3\n"
"int x;\n"
"# expansion end\n"
"# 10 \"<stdin>\"\n"
"x = 10\n";
QTest::newRow("case 3") << original << expected;
original = "#define FOO int x;\n"
"\n"
" /* comment\n"
" comment\n"
" comment\n"
" comment */\n"
"FOO\n"
"/* \n"
"*/\n"
"x = 10\n";
expected =
"# 1 \"<stdin>\"\n"
"\n"
"\n"
"\n"
"\n"
"\n"
"\n"
"# expansion begin 79,3 ~3\n"
"int x;\n"
"# expansion end\n"
"# 10 \"<stdin>\"\n"
"x = 10\n";
QTest::newRow("case 4") << original << expected;
}
void tst_Preprocessor::compare_input_output()
{
QFETCH(QByteArray, input);
QFETCH(QByteArray, output);
Environment env;
Preprocessor preprocess(0, &env);
QByteArray prep = preprocess.run(QLatin1String("<stdin>"), input);
QCOMPARE(output, prep);
}
QTEST_APPLESS_MAIN(tst_Preprocessor)
#include "tst_preprocessor.moc"