blob: 9a695004c9298e85e9eb606c997ecf120a0387e3 [file] [log] [blame]
Reid Spencer5f016e22007-07-11 17:01:13 +00001//===--- Preprocess.cpp - C Language Family Preprocessor Implementation ---===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Reid Spencer5f016e22007-07-11 17:01:13 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the Preprocessor interface.
11//
12//===----------------------------------------------------------------------===//
13//
14// Options to support:
15// -H - Print the name of each header file used.
Chris Lattnerf73903a2009-02-06 06:45:26 +000016// -d[DNI] - Dump various things.
Reid Spencer5f016e22007-07-11 17:01:13 +000017// -fworking-directory - #line's with preprocessor's working dir.
18// -fpreprocessed
19// -dependency-file,-M,-MM,-MF,-MG,-MP,-MT,-MQ,-MD,-MMD
20// -W*
21// -w
22//
23// Messages to emit:
24// "Multiple include guards may be useful for:\n"
25//
26//===----------------------------------------------------------------------===//
27
28#include "clang/Lex/Preprocessor.h"
Chris Lattner23f77e52009-12-15 01:51:03 +000029#include "MacroArgs.h"
Douglas Gregor88a35862010-01-04 19:18:44 +000030#include "clang/Lex/ExternalPreprocessorSource.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000031#include "clang/Lex/HeaderSearch.h"
32#include "clang/Lex/MacroInfo.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000033#include "clang/Lex/Pragma.h"
Douglas Gregor94dc8f62010-03-19 16:15:56 +000034#include "clang/Lex/PreprocessingRecord.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000035#include "clang/Lex/ScratchBuffer.h"
Chris Lattner500d3292009-01-29 05:15:15 +000036#include "clang/Lex/LexDiagnostic.h"
Douglas Gregorf44e8542010-08-24 19:08:16 +000037#include "clang/Lex/CodeCompletionHandler.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000038#include "clang/Basic/SourceManager.h"
Ted Kremenek337edcd2009-02-12 03:26:59 +000039#include "clang/Basic/FileManager.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000040#include "clang/Basic/TargetInfo.h"
Chris Lattner2db78dd2008-10-05 20:40:30 +000041#include "llvm/ADT/APFloat.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000042#include "llvm/ADT/SmallVector.h"
Chris Lattner97ba77c2007-07-16 06:48:38 +000043#include "llvm/Support/MemoryBuffer.h"
Benjamin Kramer6cb7c1a2009-08-23 12:08:50 +000044#include "llvm/Support/raw_ostream.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000045using namespace clang;
46
47//===----------------------------------------------------------------------===//
Douglas Gregor88a35862010-01-04 19:18:44 +000048ExternalPreprocessorSource::~ExternalPreprocessorSource() { }
Reid Spencer5f016e22007-07-11 17:01:13 +000049
50Preprocessor::Preprocessor(Diagnostic &diags, const LangOptions &opts,
Daniel Dunbar444be732009-11-13 05:51:54 +000051 const TargetInfo &target, SourceManager &SM,
Ted Kremenek72b1b152009-01-15 18:47:46 +000052 HeaderSearch &Headers,
Daniel Dunbar5814e652009-11-11 21:44:21 +000053 IdentifierInfoLookup* IILookup,
54 bool OwnsHeaders)
Chris Lattner836040f2009-03-13 21:17:43 +000055 : Diags(&diags), Features(opts), Target(target),FileMgr(Headers.getFileMgr()),
Douglas Gregor88a35862010-01-04 19:18:44 +000056 SourceMgr(SM), HeaderInfo(Headers), ExternalSource(0),
Douglas Gregorf44e8542010-08-24 19:08:16 +000057 Identifiers(opts, IILookup), BuiltinInfo(Target), CodeComplete(0),
58 CodeCompletionFile(0), SkipMainFilePreamble(0, true), CurPPLexer(0),
Ted Kremenekaf8fa252010-10-19 18:16:54 +000059 CurDirLookup(0), Callbacks(0), MacroArgCache(0), Record(0), MIChainHead(0) {
Reid Spencer5f016e22007-07-11 17:01:13 +000060 ScratchBuf = new ScratchBuffer(SourceMgr);
Chris Lattnerc1f9d822009-04-13 01:29:17 +000061 CounterValue = 0; // __COUNTER__ starts at 0.
Daniel Dunbar5814e652009-11-11 21:44:21 +000062 OwnsHeaderSearch = OwnsHeaders;
Mike Stump1eb44332009-09-09 15:08:12 +000063
Reid Spencer5f016e22007-07-11 17:01:13 +000064 // Clear stats.
65 NumDirectives = NumDefined = NumUndefined = NumPragma = 0;
66 NumIf = NumElse = NumEndif = 0;
67 NumEnteredSourceFiles = 0;
68 NumMacroExpanded = NumFnMacroExpanded = NumBuiltinMacroExpanded = 0;
69 NumFastMacroExpanded = NumTokenPaste = NumFastTokenPaste = 0;
Mike Stump1eb44332009-09-09 15:08:12 +000070 MaxIncludeStackDepth = 0;
Reid Spencer5f016e22007-07-11 17:01:13 +000071 NumSkipped = 0;
72
73 // Default to discarding comments.
74 KeepComments = false;
75 KeepMacroComments = false;
Mike Stump1eb44332009-09-09 15:08:12 +000076
Reid Spencer5f016e22007-07-11 17:01:13 +000077 // Macro expansion is enabled.
78 DisableMacroExpansion = false;
79 InMacroArgs = false;
Chris Lattner6cfe7592008-03-09 02:26:03 +000080 NumCachedTokenLexers = 0;
Reid Spencer5f016e22007-07-11 17:01:13 +000081
Argyrios Kyrtzidis03db1b32008-08-10 13:15:22 +000082 CachedLexPos = 0;
83
Douglas Gregor88a35862010-01-04 19:18:44 +000084 // We haven't read anything from the external source.
85 ReadMacrosFromExternalSource = false;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +000086
Reid Spencer5f016e22007-07-11 17:01:13 +000087 // "Poison" __VA_ARGS__, which can only appear in the expansion of a macro.
88 // This gets unpoisoned where it is allowed.
89 (Ident__VA_ARGS__ = getIdentifierInfo("__VA_ARGS__"))->setIsPoisoned();
Mike Stump1eb44332009-09-09 15:08:12 +000090
Reid Spencer5f016e22007-07-11 17:01:13 +000091 // Initialize the pragma handlers.
Argyrios Kyrtzidis9b36c3f2010-07-13 09:07:17 +000092 PragmaHandlers = new PragmaNamespace(llvm::StringRef());
Reid Spencer5f016e22007-07-11 17:01:13 +000093 RegisterBuiltinPragmas();
Mike Stump1eb44332009-09-09 15:08:12 +000094
Reid Spencer5f016e22007-07-11 17:01:13 +000095 // Initialize builtin macros like __LINE__ and friends.
96 RegisterBuiltinMacros();
97}
98
99Preprocessor::~Preprocessor() {
Argyrios Kyrtzidis2174a4f2008-08-23 12:12:06 +0000100 assert(BacktrackPositions.empty() && "EnableBacktrack/Backtrack imbalance!");
101
Reid Spencer5f016e22007-07-11 17:01:13 +0000102 while (!IncludeMacroStack.empty()) {
103 delete IncludeMacroStack.back().TheLexer;
Chris Lattner6cfe7592008-03-09 02:26:03 +0000104 delete IncludeMacroStack.back().TheTokenLexer;
Reid Spencer5f016e22007-07-11 17:01:13 +0000105 IncludeMacroStack.pop_back();
106 }
Chris Lattnercc1a8752007-10-07 08:44:20 +0000107
108 // Free any macro definitions.
Ted Kremenekaf8fa252010-10-19 18:16:54 +0000109 for (MacroInfoChain *I = MIChainHead ; I ; ) {
110 MacroInfoChain *Next = I->Next;
111 I->MI.Destroy();
112 I = Next;
Ted Kremeneke6a7dab2010-10-19 17:40:53 +0000113 }
Mike Stump1eb44332009-09-09 15:08:12 +0000114
Chris Lattner9594acf2007-07-15 00:25:26 +0000115 // Free any cached macro expanders.
Chris Lattner6cfe7592008-03-09 02:26:03 +0000116 for (unsigned i = 0, e = NumCachedTokenLexers; i != e; ++i)
117 delete TokenLexerCache[i];
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +0000118
Chris Lattner23f77e52009-12-15 01:51:03 +0000119 // Free any cached MacroArgs.
120 for (MacroArgs *ArgList = MacroArgCache; ArgList; )
121 ArgList = ArgList->deallocate();
Mike Stump1eb44332009-09-09 15:08:12 +0000122
Reid Spencer5f016e22007-07-11 17:01:13 +0000123 // Release pragma information.
124 delete PragmaHandlers;
125
126 // Delete the scratch buffer info.
127 delete ScratchBuf;
Chris Lattnereb50ed82008-03-14 06:07:05 +0000128
Daniel Dunbar5814e652009-11-11 21:44:21 +0000129 // Delete the header search info, if we own it.
130 if (OwnsHeaderSearch)
131 delete &HeaderInfo;
132
Chris Lattnereb50ed82008-03-14 06:07:05 +0000133 delete Callbacks;
Reid Spencer5f016e22007-07-11 17:01:13 +0000134}
135
Ted Kremenek337edcd2009-02-12 03:26:59 +0000136void Preprocessor::setPTHManager(PTHManager* pm) {
137 PTH.reset(pm);
Douglas Gregor52e71082009-10-16 18:18:30 +0000138 FileMgr.addStatCache(PTH->createStatCache());
Ted Kremenek337edcd2009-02-12 03:26:59 +0000139}
140
Chris Lattnerd2177732007-07-20 16:59:19 +0000141void Preprocessor::DumpToken(const Token &Tok, bool DumpFlags) const {
Benjamin Kramer6cb7c1a2009-08-23 12:08:50 +0000142 llvm::errs() << tok::getTokenName(Tok.getKind()) << " '"
143 << getSpelling(Tok) << "'";
Mike Stump1eb44332009-09-09 15:08:12 +0000144
Reid Spencer5f016e22007-07-11 17:01:13 +0000145 if (!DumpFlags) return;
Mike Stump1eb44332009-09-09 15:08:12 +0000146
Benjamin Kramer6cb7c1a2009-08-23 12:08:50 +0000147 llvm::errs() << "\t";
Reid Spencer5f016e22007-07-11 17:01:13 +0000148 if (Tok.isAtStartOfLine())
Benjamin Kramer6cb7c1a2009-08-23 12:08:50 +0000149 llvm::errs() << " [StartOfLine]";
Reid Spencer5f016e22007-07-11 17:01:13 +0000150 if (Tok.hasLeadingSpace())
Benjamin Kramer6cb7c1a2009-08-23 12:08:50 +0000151 llvm::errs() << " [LeadingSpace]";
Reid Spencer5f016e22007-07-11 17:01:13 +0000152 if (Tok.isExpandDisabled())
Benjamin Kramer6cb7c1a2009-08-23 12:08:50 +0000153 llvm::errs() << " [ExpandDisabled]";
Reid Spencer5f016e22007-07-11 17:01:13 +0000154 if (Tok.needsCleaning()) {
155 const char *Start = SourceMgr.getCharacterData(Tok.getLocation());
Benjamin Kramer476d8b82010-08-11 14:47:12 +0000156 llvm::errs() << " [UnClean='" << llvm::StringRef(Start, Tok.getLength())
Benjamin Kramer6cb7c1a2009-08-23 12:08:50 +0000157 << "']";
Reid Spencer5f016e22007-07-11 17:01:13 +0000158 }
Mike Stump1eb44332009-09-09 15:08:12 +0000159
Benjamin Kramer6cb7c1a2009-08-23 12:08:50 +0000160 llvm::errs() << "\tLoc=<";
Chris Lattnerc3d8d572007-12-09 20:31:55 +0000161 DumpLocation(Tok.getLocation());
Benjamin Kramer6cb7c1a2009-08-23 12:08:50 +0000162 llvm::errs() << ">";
Chris Lattnerc3d8d572007-12-09 20:31:55 +0000163}
164
165void Preprocessor::DumpLocation(SourceLocation Loc) const {
Chris Lattnerb9c3f962009-01-27 07:57:44 +0000166 Loc.dump(SourceMgr);
Reid Spencer5f016e22007-07-11 17:01:13 +0000167}
168
169void Preprocessor::DumpMacro(const MacroInfo &MI) const {
Benjamin Kramer6cb7c1a2009-08-23 12:08:50 +0000170 llvm::errs() << "MACRO: ";
Reid Spencer5f016e22007-07-11 17:01:13 +0000171 for (unsigned i = 0, e = MI.getNumTokens(); i != e; ++i) {
172 DumpToken(MI.getReplacementToken(i));
Benjamin Kramer6cb7c1a2009-08-23 12:08:50 +0000173 llvm::errs() << " ";
Reid Spencer5f016e22007-07-11 17:01:13 +0000174 }
Benjamin Kramer6cb7c1a2009-08-23 12:08:50 +0000175 llvm::errs() << "\n";
Reid Spencer5f016e22007-07-11 17:01:13 +0000176}
177
178void Preprocessor::PrintStats() {
Benjamin Kramer6cb7c1a2009-08-23 12:08:50 +0000179 llvm::errs() << "\n*** Preprocessor Stats:\n";
180 llvm::errs() << NumDirectives << " directives found:\n";
181 llvm::errs() << " " << NumDefined << " #define.\n";
182 llvm::errs() << " " << NumUndefined << " #undef.\n";
183 llvm::errs() << " #include/#include_next/#import:\n";
184 llvm::errs() << " " << NumEnteredSourceFiles << " source files entered.\n";
185 llvm::errs() << " " << MaxIncludeStackDepth << " max include stack depth\n";
186 llvm::errs() << " " << NumIf << " #if/#ifndef/#ifdef.\n";
187 llvm::errs() << " " << NumElse << " #else/#elif.\n";
188 llvm::errs() << " " << NumEndif << " #endif.\n";
189 llvm::errs() << " " << NumPragma << " #pragma.\n";
190 llvm::errs() << NumSkipped << " #if/#ifndef#ifdef regions skipped\n";
Reid Spencer5f016e22007-07-11 17:01:13 +0000191
Benjamin Kramer6cb7c1a2009-08-23 12:08:50 +0000192 llvm::errs() << NumMacroExpanded << "/" << NumFnMacroExpanded << "/"
Ted Kremenekbdd30c22008-01-14 16:44:48 +0000193 << NumBuiltinMacroExpanded << " obj/fn/builtin macros expanded, "
194 << NumFastMacroExpanded << " on the fast path.\n";
Benjamin Kramer6cb7c1a2009-08-23 12:08:50 +0000195 llvm::errs() << (NumFastTokenPaste+NumTokenPaste)
Ted Kremenekbdd30c22008-01-14 16:44:48 +0000196 << " token paste (##) operations performed, "
197 << NumFastTokenPaste << " on the fast path.\n";
Reid Spencer5f016e22007-07-11 17:01:13 +0000198}
199
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +0000200Preprocessor::macro_iterator
201Preprocessor::macro_begin(bool IncludeExternalMacros) const {
202 if (IncludeExternalMacros && ExternalSource &&
Douglas Gregor88a35862010-01-04 19:18:44 +0000203 !ReadMacrosFromExternalSource) {
204 ReadMacrosFromExternalSource = true;
205 ExternalSource->ReadDefinedMacros();
206 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +0000207
208 return Macros.begin();
Douglas Gregor88a35862010-01-04 19:18:44 +0000209}
210
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +0000211Preprocessor::macro_iterator
212Preprocessor::macro_end(bool IncludeExternalMacros) const {
213 if (IncludeExternalMacros && ExternalSource &&
Douglas Gregor88a35862010-01-04 19:18:44 +0000214 !ReadMacrosFromExternalSource) {
215 ReadMacrosFromExternalSource = true;
216 ExternalSource->ReadDefinedMacros();
217 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +0000218
219 return Macros.end();
Douglas Gregor88a35862010-01-04 19:18:44 +0000220}
221
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +0000222bool Preprocessor::SetCodeCompletionPoint(const FileEntry *File,
223 unsigned TruncateAtLine,
Douglas Gregor29684422009-12-02 06:49:09 +0000224 unsigned TruncateAtColumn) {
225 using llvm::MemoryBuffer;
226
227 CodeCompletionFile = File;
228
229 // Okay to clear out the code-completion point by passing NULL.
230 if (!CodeCompletionFile)
231 return false;
232
233 // Load the actual file's contents.
Douglas Gregoraa38c3d2010-03-16 19:49:24 +0000234 bool Invalid = false;
235 const MemoryBuffer *Buffer = SourceMgr.getMemoryBufferForFile(File, &Invalid);
236 if (Invalid)
Douglas Gregor29684422009-12-02 06:49:09 +0000237 return true;
238
239 // Find the byte position of the truncation point.
240 const char *Position = Buffer->getBufferStart();
241 for (unsigned Line = 1; Line < TruncateAtLine; ++Line) {
242 for (; *Position; ++Position) {
243 if (*Position != '\r' && *Position != '\n')
244 continue;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +0000245
Douglas Gregor29684422009-12-02 06:49:09 +0000246 // Eat \r\n or \n\r as a single line.
247 if ((Position[1] == '\r' || Position[1] == '\n') &&
248 Position[0] != Position[1])
249 ++Position;
250 ++Position;
251 break;
252 }
253 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +0000254
Douglas Gregorb760fe82009-12-08 21:45:46 +0000255 Position += TruncateAtColumn - 1;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +0000256
Douglas Gregor29684422009-12-02 06:49:09 +0000257 // Truncate the buffer.
Douglas Gregorb760fe82009-12-08 21:45:46 +0000258 if (Position < Buffer->getBufferEnd()) {
Chris Lattnera0a270c2010-04-05 22:42:27 +0000259 llvm::StringRef Data(Buffer->getBufferStart(),
260 Position-Buffer->getBufferStart());
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +0000261 MemoryBuffer *TruncatedBuffer
Chris Lattnera0a270c2010-04-05 22:42:27 +0000262 = MemoryBuffer::getMemBufferCopy(Data, Buffer->getBufferIdentifier());
Douglas Gregor29684422009-12-02 06:49:09 +0000263 SourceMgr.overrideFileContents(File, TruncatedBuffer);
264 }
265
266 return false;
267}
268
Douglas Gregor109ae732009-12-03 17:05:59 +0000269bool Preprocessor::isCodeCompletionFile(SourceLocation FileLoc) const {
Douglas Gregor29684422009-12-02 06:49:09 +0000270 return CodeCompletionFile && FileLoc.isFileID() &&
271 SourceMgr.getFileEntryForID(SourceMgr.getFileID(FileLoc))
272 == CodeCompletionFile;
273}
274
Douglas Gregor55817af2010-08-25 17:04:25 +0000275void Preprocessor::CodeCompleteNaturalLanguage() {
276 SetCodeCompletionPoint(0, 0, 0);
277 getDiagnostics().setSuppressAllDiagnostics(true);
278 if (CodeComplete)
279 CodeComplete->CodeCompleteNaturalLanguage();
280}
281
Reid Spencer5f016e22007-07-11 17:01:13 +0000282//===----------------------------------------------------------------------===//
283// Token Spelling
284//===----------------------------------------------------------------------===//
285
Reid Spencer5f016e22007-07-11 17:01:13 +0000286/// getSpelling() - Return the 'spelling' of this token. The spelling of a
287/// token are the characters used to represent the token in the source file
288/// after trigraph expansion and escaped-newline folding. In particular, this
289/// wants to get the true, uncanonicalized, spelling of things like digraphs
290/// UCNs, etc.
Daniel Dunbar0ff10422009-11-14 01:20:48 +0000291std::string Preprocessor::getSpelling(const Token &Tok,
292 const SourceManager &SourceMgr,
Douglas Gregor50f6af72010-03-16 05:20:39 +0000293 const LangOptions &Features,
294 bool *Invalid) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000295 assert((int)Tok.getLength() >= 0 && "Token character range is bogus!");
Ted Kremenek277faca2009-01-27 00:01:05 +0000296
Reid Spencer5f016e22007-07-11 17:01:13 +0000297 // If this token contains nothing interesting, return it directly.
Douglas Gregor50f6af72010-03-16 05:20:39 +0000298 bool CharDataInvalid = false;
299 const char* TokStart = SourceMgr.getCharacterData(Tok.getLocation(),
300 &CharDataInvalid);
301 if (Invalid)
302 *Invalid = CharDataInvalid;
303 if (CharDataInvalid)
304 return std::string();
305
Reid Spencer5f016e22007-07-11 17:01:13 +0000306 if (!Tok.needsCleaning())
307 return std::string(TokStart, TokStart+Tok.getLength());
Mike Stump1eb44332009-09-09 15:08:12 +0000308
Reid Spencer5f016e22007-07-11 17:01:13 +0000309 std::string Result;
310 Result.reserve(Tok.getLength());
Mike Stump1eb44332009-09-09 15:08:12 +0000311
Reid Spencer5f016e22007-07-11 17:01:13 +0000312 // Otherwise, hard case, relex the characters into the string.
313 for (const char *Ptr = TokStart, *End = TokStart+Tok.getLength();
314 Ptr != End; ) {
315 unsigned CharSize;
316 Result.push_back(Lexer::getCharAndSizeNoWarn(Ptr, CharSize, Features));
317 Ptr += CharSize;
318 }
319 assert(Result.size() != unsigned(Tok.getLength()) &&
320 "NeedsCleaning flag set on something that didn't need cleaning!");
321 return Result;
322}
323
Daniel Dunbar0ff10422009-11-14 01:20:48 +0000324/// getSpelling() - Return the 'spelling' of this token. The spelling of a
325/// token are the characters used to represent the token in the source file
326/// after trigraph expansion and escaped-newline folding. In particular, this
327/// wants to get the true, uncanonicalized, spelling of things like digraphs
328/// UCNs, etc.
Douglas Gregor50f6af72010-03-16 05:20:39 +0000329std::string Preprocessor::getSpelling(const Token &Tok, bool *Invalid) const {
330 return getSpelling(Tok, SourceMgr, Features, Invalid);
Daniel Dunbar0ff10422009-11-14 01:20:48 +0000331}
332
Reid Spencer5f016e22007-07-11 17:01:13 +0000333/// getSpelling - This method is used to get the spelling of a token into a
334/// preallocated buffer, instead of as an std::string. The caller is required
335/// to allocate enough space for the token, which is guaranteed to be at least
336/// Tok.getLength() bytes long. The actual length of the token is returned.
337///
338/// Note that this method may do two possible things: it may either fill in
339/// the buffer specified with characters, or it may *change the input pointer*
340/// to point to a constant buffer with the data already in it (avoiding a
341/// copy). The caller is not allowed to modify the returned buffer pointer
342/// if an internal buffer is returned.
Sean Hunt6cf75022010-08-30 17:47:05 +0000343unsigned Preprocessor::getSpelling(const Token &Tok,
344 const char *&Buffer, bool *Invalid) const {
Reid Spencer5f016e22007-07-11 17:01:13 +0000345 assert((int)Tok.getLength() >= 0 && "Token character range is bogus!");
Mike Stump1eb44332009-09-09 15:08:12 +0000346
Reid Spencer5f016e22007-07-11 17:01:13 +0000347 // If this token is an identifier, just return the string from the identifier
348 // table, which is very quick.
349 if (const IdentifierInfo *II = Tok.getIdentifierInfo()) {
Sean Hunt6cf75022010-08-30 17:47:05 +0000350 Buffer = II->getNameStart();
351 return II->getLength();
Reid Spencer5f016e22007-07-11 17:01:13 +0000352 }
Ted Kremenekb70e3da2009-01-08 02:47:16 +0000353
Reid Spencer5f016e22007-07-11 17:01:13 +0000354 // Otherwise, compute the start of the token in the input lexer buffer.
Chris Lattner47246be2009-01-26 19:29:26 +0000355 const char *TokStart = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000356
Chris Lattner47246be2009-01-26 19:29:26 +0000357 if (Tok.isLiteral())
358 TokStart = Tok.getLiteralData();
Mike Stump1eb44332009-09-09 15:08:12 +0000359
Douglas Gregor50f6af72010-03-16 05:20:39 +0000360 if (TokStart == 0) {
361 bool CharDataInvalid = false;
362 TokStart = SourceMgr.getCharacterData(Tok.getLocation(), &CharDataInvalid);
363 if (Invalid)
364 *Invalid = CharDataInvalid;
365 if (CharDataInvalid) {
366 Buffer = "";
367 return 0;
368 }
369 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000370
371 // If this token contains nothing interesting, return it directly.
Sean Hunt6cf75022010-08-30 17:47:05 +0000372 if (!Tok.needsCleaning()) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000373 Buffer = TokStart;
Sean Hunt6cf75022010-08-30 17:47:05 +0000374 return Tok.getLength();
Reid Spencer5f016e22007-07-11 17:01:13 +0000375 }
Mike Stump1eb44332009-09-09 15:08:12 +0000376
Reid Spencer5f016e22007-07-11 17:01:13 +0000377 // Otherwise, hard case, relex the characters into the string.
378 char *OutBuf = const_cast<char*>(Buffer);
Sean Hunt6cf75022010-08-30 17:47:05 +0000379 for (const char *Ptr = TokStart, *End = TokStart+Tok.getLength();
Reid Spencer5f016e22007-07-11 17:01:13 +0000380 Ptr != End; ) {
381 unsigned CharSize;
382 *OutBuf++ = Lexer::getCharAndSizeNoWarn(Ptr, CharSize, Features);
383 Ptr += CharSize;
384 }
Sean Hunt6cf75022010-08-30 17:47:05 +0000385 assert(unsigned(OutBuf-Buffer) != Tok.getLength() &&
Reid Spencer5f016e22007-07-11 17:01:13 +0000386 "NeedsCleaning flag set on something that didn't need cleaning!");
Mike Stump1eb44332009-09-09 15:08:12 +0000387
Reid Spencer5f016e22007-07-11 17:01:13 +0000388 return OutBuf-Buffer;
389}
390
Benjamin Kramer51f5fe32010-02-27 17:05:45 +0000391/// getSpelling - This method is used to get the spelling of a token into a
392/// SmallVector. Note that the returned StringRef may not point to the
393/// supplied buffer if a copy can be avoided.
394llvm::StringRef Preprocessor::getSpelling(const Token &Tok,
Douglas Gregor50f6af72010-03-16 05:20:39 +0000395 llvm::SmallVectorImpl<char> &Buffer,
396 bool *Invalid) const {
Benjamin Kramer51f5fe32010-02-27 17:05:45 +0000397 // Try the fast path.
398 if (const IdentifierInfo *II = Tok.getIdentifierInfo())
399 return II->getName();
400
401 // Resize the buffer if we need to copy into it.
402 if (Tok.needsCleaning())
403 Buffer.resize(Tok.getLength());
404
405 const char *Ptr = Buffer.data();
Douglas Gregor50f6af72010-03-16 05:20:39 +0000406 unsigned Len = getSpelling(Tok, Ptr, Invalid);
Benjamin Kramer51f5fe32010-02-27 17:05:45 +0000407 return llvm::StringRef(Ptr, Len);
408}
409
Reid Spencer5f016e22007-07-11 17:01:13 +0000410/// CreateString - Plop the specified string into a scratch buffer and return a
411/// location for it. If specified, the source location provides a source
412/// location for the token.
Chris Lattner47246be2009-01-26 19:29:26 +0000413void Preprocessor::CreateString(const char *Buf, unsigned Len, Token &Tok,
414 SourceLocation InstantiationLoc) {
415 Tok.setLength(Len);
Mike Stump1eb44332009-09-09 15:08:12 +0000416
Chris Lattner47246be2009-01-26 19:29:26 +0000417 const char *DestPtr;
418 SourceLocation Loc = ScratchBuf->getToken(Buf, Len, DestPtr);
Mike Stump1eb44332009-09-09 15:08:12 +0000419
Chris Lattner47246be2009-01-26 19:29:26 +0000420 if (InstantiationLoc.isValid())
Chris Lattnere7fb4842009-02-15 20:52:18 +0000421 Loc = SourceMgr.createInstantiationLoc(Loc, InstantiationLoc,
422 InstantiationLoc, Len);
Chris Lattner47246be2009-01-26 19:29:26 +0000423 Tok.setLocation(Loc);
Mike Stump1eb44332009-09-09 15:08:12 +0000424
Chris Lattner47246be2009-01-26 19:29:26 +0000425 // If this is a literal token, set the pointer data.
426 if (Tok.isLiteral())
427 Tok.setLiteralData(DestPtr);
Reid Spencer5f016e22007-07-11 17:01:13 +0000428}
429
430
Chris Lattner97ba77c2007-07-16 06:48:38 +0000431/// AdvanceToTokenCharacter - Given a location that specifies the start of a
432/// token, return a new location that specifies a character within the token.
Mike Stump1eb44332009-09-09 15:08:12 +0000433SourceLocation Preprocessor::AdvanceToTokenCharacter(SourceLocation TokStart,
Chris Lattner97ba77c2007-07-16 06:48:38 +0000434 unsigned CharNo) {
Chris Lattnerf7cf85b2009-01-16 07:36:28 +0000435 // Figure out how many physical characters away the specified instantiation
Chris Lattner97ba77c2007-07-16 06:48:38 +0000436 // character is. This needs to take into consideration newlines and
437 // trigraphs.
Douglas Gregora5430162010-03-16 20:46:42 +0000438 bool Invalid = false;
439 const char *TokPtr = SourceMgr.getCharacterData(TokStart, &Invalid);
Mike Stump1eb44332009-09-09 15:08:12 +0000440
Chris Lattner88e25242009-04-18 22:28:58 +0000441 // If they request the first char of the token, we're trivially done.
Douglas Gregora5430162010-03-16 20:46:42 +0000442 if (Invalid || (CharNo == 0 && Lexer::isObviouslySimpleCharacter(*TokPtr)))
Chris Lattner88e25242009-04-18 22:28:58 +0000443 return TokStart;
Mike Stump1eb44332009-09-09 15:08:12 +0000444
Chris Lattner9dc1f532007-07-20 16:37:10 +0000445 unsigned PhysOffset = 0;
Mike Stump1eb44332009-09-09 15:08:12 +0000446
Chris Lattner97ba77c2007-07-16 06:48:38 +0000447 // The usual case is that tokens don't contain anything interesting. Skip
448 // over the uninteresting characters. If a token only consists of simple
449 // chars, this method is extremely fast.
Chris Lattner88e25242009-04-18 22:28:58 +0000450 while (Lexer::isObviouslySimpleCharacter(*TokPtr)) {
451 if (CharNo == 0)
452 return TokStart.getFileLocWithOffset(PhysOffset);
Chris Lattner9dc1f532007-07-20 16:37:10 +0000453 ++TokPtr, --CharNo, ++PhysOffset;
Chris Lattner88e25242009-04-18 22:28:58 +0000454 }
Mike Stump1eb44332009-09-09 15:08:12 +0000455
Chris Lattner28c90ad2009-01-17 07:57:25 +0000456 // If we have a character that may be a trigraph or escaped newline, use a
Chris Lattner97ba77c2007-07-16 06:48:38 +0000457 // lexer to parse it correctly.
Chris Lattner88e25242009-04-18 22:28:58 +0000458 for (; CharNo; --CharNo) {
459 unsigned Size;
460 Lexer::getCharAndSizeNoWarn(TokPtr, Size, Features);
461 TokPtr += Size;
462 PhysOffset += Size;
Chris Lattner97ba77c2007-07-16 06:48:38 +0000463 }
Mike Stump1eb44332009-09-09 15:08:12 +0000464
Chris Lattner88e25242009-04-18 22:28:58 +0000465 // Final detail: if we end up on an escaped newline, we want to return the
466 // location of the actual byte of the token. For example foo\<newline>bar
467 // advanced by 3 should return the location of b, not of \\. One compounding
468 // detail of this is that the escape may be made by a trigraph.
469 if (!Lexer::isObviouslySimpleCharacter(*TokPtr))
Ted Kremenekc0178e92010-01-29 19:38:24 +0000470 PhysOffset += Lexer::SkipEscapedNewLines(TokPtr)-TokPtr;
Mike Stump1eb44332009-09-09 15:08:12 +0000471
Chris Lattner9dc1f532007-07-20 16:37:10 +0000472 return TokStart.getFileLocWithOffset(PhysOffset);
Chris Lattner97ba77c2007-07-16 06:48:38 +0000473}
474
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +0000475SourceLocation Preprocessor::getLocForEndOfToken(SourceLocation Loc,
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000476 unsigned Offset) {
Douglas Gregorb2fb6de2009-02-27 17:53:17 +0000477 if (Loc.isInvalid() || !Loc.isFileID())
478 return SourceLocation();
479
Chris Lattner2c78b872009-04-14 23:22:57 +0000480 unsigned Len = Lexer::MeasureTokenLength(Loc, getSourceManager(), Features);
Douglas Gregor33e9abd2010-01-22 19:49:59 +0000481 if (Len > Offset)
482 Len = Len - Offset;
483 else
484 return Loc;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +0000485
Douglas Gregorb2fb6de2009-02-27 17:53:17 +0000486 return AdvanceToTokenCharacter(Loc, Len);
487}
488
489
Chris Lattner97ba77c2007-07-16 06:48:38 +0000490
Chris Lattner53b0dab2007-10-09 22:10:18 +0000491//===----------------------------------------------------------------------===//
492// Preprocessor Initialization Methods
493//===----------------------------------------------------------------------===//
494
Chris Lattner53b0dab2007-10-09 22:10:18 +0000495
496/// EnterMainSourceFile - Enter the specified FileID as the main source file,
Nate Begeman6b616022008-01-07 04:01:26 +0000497/// which implicitly adds the builtin defines etc.
Chris Lattnere127a0d2010-04-20 20:35:58 +0000498void Preprocessor::EnterMainSourceFile() {
Chris Lattner05db4272009-02-13 19:33:24 +0000499 // We do not allow the preprocessor to reenter the main file. Doing so will
500 // cause FileID's to accumulate information from both runs (e.g. #line
501 // information) and predefined macros aren't guaranteed to be set properly.
502 assert(NumEnteredSourceFiles == 0 && "Cannot reenter the main file!");
Chris Lattner2b2453a2009-01-17 06:22:33 +0000503 FileID MainFileID = SourceMgr.getMainFileID();
Mike Stump1eb44332009-09-09 15:08:12 +0000504
Chris Lattner53b0dab2007-10-09 22:10:18 +0000505 // Enter the main file source buffer.
Chris Lattnere127a0d2010-04-20 20:35:58 +0000506 EnterSourceFile(MainFileID, 0, SourceLocation());
Mike Stump1eb44332009-09-09 15:08:12 +0000507
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000508 // If we've been asked to skip bytes in the main file (e.g., as part of a
509 // precompiled preamble), do so now.
510 if (SkipMainFilePreamble.first > 0)
511 CurLexer->SkipBytes(SkipMainFilePreamble.first,
512 SkipMainFilePreamble.second);
513
Chris Lattnerb2832982007-11-15 19:07:47 +0000514 // Tell the header info that the main file was entered. If the file is later
515 // #imported, it won't be re-entered.
Chris Lattner2b2453a2009-01-17 06:22:33 +0000516 if (const FileEntry *FE = SourceMgr.getFileEntryForID(MainFileID))
Chris Lattnerb2832982007-11-15 19:07:47 +0000517 HeaderInfo.IncrementIncludeCount(FE);
Mike Stump1eb44332009-09-09 15:08:12 +0000518
Benjamin Kramerffd6e392009-12-31 15:33:09 +0000519 // Preprocess Predefines to populate the initial preprocessor state.
Mike Stump1eb44332009-09-09 15:08:12 +0000520 llvm::MemoryBuffer *SB =
Chris Lattnera0a270c2010-04-05 22:42:27 +0000521 llvm::MemoryBuffer::getMemBufferCopy(Predefines, "<built-in>");
Douglas Gregor043266b2010-08-26 14:07:34 +0000522 assert(SB && "Cannot create predefined source buffer");
Chris Lattner2b2453a2009-01-17 06:22:33 +0000523 FileID FID = SourceMgr.createFileIDForMemBuffer(SB);
524 assert(!FID.isInvalid() && "Could not create FileID for predefines?");
Mike Stump1eb44332009-09-09 15:08:12 +0000525
Chris Lattner53b0dab2007-10-09 22:10:18 +0000526 // Start parsing the predefines.
Chris Lattnere127a0d2010-04-20 20:35:58 +0000527 EnterSourceFile(FID, 0, SourceLocation());
Chris Lattner53b0dab2007-10-09 22:10:18 +0000528}
Chris Lattner97ba77c2007-07-16 06:48:38 +0000529
Daniel Dunbardbd82092010-03-23 05:09:10 +0000530void Preprocessor::EndSourceFile() {
531 // Notify the client that we reached the end of the source file.
532 if (Callbacks)
533 Callbacks->EndOfMainFile();
534}
Reid Spencer5f016e22007-07-11 17:01:13 +0000535
536//===----------------------------------------------------------------------===//
537// Lexer Event Handling.
538//===----------------------------------------------------------------------===//
539
540/// LookUpIdentifierInfo - Given a tok::identifier token, look up the
541/// identifier information for the token and install it into the token.
Chris Lattnerd2177732007-07-20 16:59:19 +0000542IdentifierInfo *Preprocessor::LookUpIdentifierInfo(Token &Identifier,
Daniel Dunbarc3222092009-11-05 01:53:52 +0000543 const char *BufPtr) const {
Chris Lattner22f6bbc2007-10-09 18:02:16 +0000544 assert(Identifier.is(tok::identifier) && "Not an identifier!");
Reid Spencer5f016e22007-07-11 17:01:13 +0000545 assert(Identifier.getIdentifierInfo() == 0 && "Identinfo already exists!");
Mike Stump1eb44332009-09-09 15:08:12 +0000546
Reid Spencer5f016e22007-07-11 17:01:13 +0000547 // Look up this token, see if it is a macro, or if it is a language keyword.
548 IdentifierInfo *II;
549 if (BufPtr && !Identifier.needsCleaning()) {
550 // No cleaning needed, just use the characters from the lexed buffer.
Daniel Dunbar3da736c2009-11-05 01:53:39 +0000551 II = getIdentifierInfo(llvm::StringRef(BufPtr, Identifier.getLength()));
Reid Spencer5f016e22007-07-11 17:01:13 +0000552 } else {
553 // Cleaning needed, alloca a buffer, clean into it, then use the buffer.
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +0000554 llvm::SmallString<64> IdentifierBuffer;
Benjamin Kramerddeea562010-02-27 13:44:12 +0000555 llvm::StringRef CleanedStr = getSpelling(Identifier, IdentifierBuffer);
556 II = getIdentifierInfo(CleanedStr);
Reid Spencer5f016e22007-07-11 17:01:13 +0000557 }
558 Identifier.setIdentifierInfo(II);
559 return II;
560}
561
562
563/// HandleIdentifier - This callback is invoked when the lexer reads an
564/// identifier. This callback looks up the identifier in the map and/or
565/// potentially macro expands it or turns it into a named token (like 'for').
Chris Lattner6a170eb2009-01-21 07:43:11 +0000566///
567/// Note that callers of this method are guarded by checking the
568/// IdentifierInfo's 'isHandleIdentifierCase' bit. If this method changes, the
569/// IdentifierInfo methods that compute these properties will need to change to
570/// match.
Chris Lattnerd2177732007-07-20 16:59:19 +0000571void Preprocessor::HandleIdentifier(Token &Identifier) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000572 assert(Identifier.getIdentifierInfo() &&
573 "Can't handle identifiers without identifier info!");
Mike Stump1eb44332009-09-09 15:08:12 +0000574
Reid Spencer5f016e22007-07-11 17:01:13 +0000575 IdentifierInfo &II = *Identifier.getIdentifierInfo();
576
577 // If this identifier was poisoned, and if it was not produced from a macro
578 // expansion, emit an error.
Ted Kremenek1a531572008-11-19 22:43:49 +0000579 if (II.isPoisoned() && CurPPLexer) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000580 if (&II != Ident__VA_ARGS__) // We warn about __VA_ARGS__ with poisoning.
581 Diag(Identifier, diag::err_pp_used_poisoned_id);
582 else
583 Diag(Identifier, diag::ext_pp_bad_vaargs_use);
584 }
Mike Stump1eb44332009-09-09 15:08:12 +0000585
Reid Spencer5f016e22007-07-11 17:01:13 +0000586 // If this is a macro to be expanded, do it.
Chris Lattnercc1a8752007-10-07 08:44:20 +0000587 if (MacroInfo *MI = getMacroInfo(&II)) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000588 if (!DisableMacroExpansion && !Identifier.isExpandDisabled()) {
589 if (MI->isEnabled()) {
590 if (!HandleMacroExpandedIdentifier(Identifier, MI))
591 return;
592 } else {
593 // C99 6.10.3.4p2 says that a disabled macro may never again be
594 // expanded, even if it's in a context where it could be expanded in the
595 // future.
Chris Lattnerd2177732007-07-20 16:59:19 +0000596 Identifier.setFlag(Token::DisableExpand);
Reid Spencer5f016e22007-07-11 17:01:13 +0000597 }
598 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000599 }
600
601 // C++ 2.11p2: If this is an alternative representation of a C++ operator,
602 // then we act as if it is the actual operator and not the textual
603 // representation of it.
Fariborz Jahanianafbc6812010-09-03 17:33:04 +0000604 if (II.isCPlusPlusOperatorKeyword())
Reid Spencer5f016e22007-07-11 17:01:13 +0000605 Identifier.setIdentifierInfo(0);
606
Reid Spencer5f016e22007-07-11 17:01:13 +0000607 // If this is an extension token, diagnose its use.
Steve Naroffb4eaf9c2008-09-02 18:50:17 +0000608 // We avoid diagnosing tokens that originate from macro definitions.
Eli Friedman2962f4d2009-04-28 03:59:15 +0000609 // FIXME: This warning is disabled in cases where it shouldn't be,
610 // like "#define TY typeof", "TY(1) x".
611 if (II.isExtensionToken() && !DisableMacroExpansion)
Reid Spencer5f016e22007-07-11 17:01:13 +0000612 Diag(Identifier, diag::ext_token_used);
613}
Douglas Gregor2e222532009-07-02 17:08:52 +0000614
615void Preprocessor::AddCommentHandler(CommentHandler *Handler) {
616 assert(Handler && "NULL comment handler");
617 assert(std::find(CommentHandlers.begin(), CommentHandlers.end(), Handler) ==
618 CommentHandlers.end() && "Comment handler already registered");
619 CommentHandlers.push_back(Handler);
620}
621
622void Preprocessor::RemoveCommentHandler(CommentHandler *Handler) {
623 std::vector<CommentHandler *>::iterator Pos
624 = std::find(CommentHandlers.begin(), CommentHandlers.end(), Handler);
625 assert(Pos != CommentHandlers.end() && "Comment handler not registered");
626 CommentHandlers.erase(Pos);
627}
628
Chris Lattner046c2272010-01-18 22:35:47 +0000629bool Preprocessor::HandleComment(Token &result, SourceRange Comment) {
630 bool AnyPendingTokens = false;
Douglas Gregor2e222532009-07-02 17:08:52 +0000631 for (std::vector<CommentHandler *>::iterator H = CommentHandlers.begin(),
632 HEnd = CommentHandlers.end();
Chris Lattner046c2272010-01-18 22:35:47 +0000633 H != HEnd; ++H) {
634 if ((*H)->HandleComment(*this, Comment))
635 AnyPendingTokens = true;
636 }
637 if (!AnyPendingTokens || getCommentRetentionState())
638 return false;
639 Lex(result);
640 return true;
Douglas Gregor2e222532009-07-02 17:08:52 +0000641}
642
643CommentHandler::~CommentHandler() { }
Douglas Gregor94dc8f62010-03-19 16:15:56 +0000644
Douglas Gregorf44e8542010-08-24 19:08:16 +0000645CodeCompletionHandler::~CodeCompletionHandler() { }
646
Douglas Gregor94dc8f62010-03-19 16:15:56 +0000647void Preprocessor::createPreprocessingRecord() {
648 if (Record)
649 return;
650
Douglas Gregorb9e1b752010-03-19 17:12:43 +0000651 Record = new PreprocessingRecord;
652 addPPCallbacks(Record);
Douglas Gregor94dc8f62010-03-19 16:15:56 +0000653}