blob: e189a9da818e9bbaa3ad833e51c2dff92f29412b [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"
Douglas Gregor6aa52ec2011-08-26 23:56:07 +000038#include "clang/Lex/ModuleLoader.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000039#include "clang/Basic/SourceManager.h"
Ted Kremenek337edcd2009-02-12 03:26:59 +000040#include "clang/Basic/FileManager.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000041#include "clang/Basic/TargetInfo.h"
Chris Lattner2db78dd2008-10-05 20:40:30 +000042#include "llvm/ADT/APFloat.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000043#include "llvm/ADT/SmallVector.h"
Chris Lattner97ba77c2007-07-16 06:48:38 +000044#include "llvm/Support/MemoryBuffer.h"
Benjamin Kramer6cb7c1a2009-08-23 12:08:50 +000045#include "llvm/Support/raw_ostream.h"
Ted Kremenek67485092011-07-27 18:41:23 +000046#include "llvm/Support/Capacity.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000047using namespace clang;
48
49//===----------------------------------------------------------------------===//
Douglas Gregor88a35862010-01-04 19:18:44 +000050ExternalPreprocessorSource::~ExternalPreprocessorSource() { }
Reid Spencer5f016e22007-07-11 17:01:13 +000051
Douglas Gregor3e3cd932011-09-01 20:23:19 +000052Preprocessor::Preprocessor(Diagnostic &diags, LangOptions &opts,
Douglas Gregor998b3d32011-09-01 23:39:15 +000053 const TargetInfo *target, SourceManager &SM,
Douglas Gregor6aa52ec2011-08-26 23:56:07 +000054 HeaderSearch &Headers, ModuleLoader &TheModuleLoader,
Daniel Dunbar5814e652009-11-11 21:44:21 +000055 IdentifierInfoLookup* IILookup,
Douglas Gregor998b3d32011-09-01 23:39:15 +000056 bool OwnsHeaders,
57 bool DelayInitialization)
Chris Lattner836040f2009-03-13 21:17:43 +000058 : Diags(&diags), Features(opts), Target(target),FileMgr(Headers.getFileMgr()),
Douglas Gregor6aa52ec2011-08-26 23:56:07 +000059 SourceMgr(SM), HeaderInfo(Headers), TheModuleLoader(TheModuleLoader),
60 ExternalSource(0),
Douglas Gregor998b3d32011-09-01 23:39:15 +000061 Identifiers(opts, IILookup), CodeComplete(0),
Douglas Gregorf44e8542010-08-24 19:08:16 +000062 CodeCompletionFile(0), SkipMainFilePreamble(0, true), CurPPLexer(0),
Ted Kremenek9714a232010-10-19 22:15:20 +000063 CurDirLookup(0), Callbacks(0), MacroArgCache(0), Record(0), MIChainHead(0),
Douglas Gregor998b3d32011-09-01 23:39:15 +000064 MICache(0)
65{
Daniel Dunbar5814e652009-11-11 21:44:21 +000066 OwnsHeaderSearch = OwnsHeaders;
Douglas Gregor998b3d32011-09-01 23:39:15 +000067
68 if (!DelayInitialization) {
69 assert(Target && "Must provide target information for PP initialization");
70 Initialize(*Target);
John Wiegley28bbe4b2011-04-28 01:08:34 +000071 }
Reid Spencer5f016e22007-07-11 17:01:13 +000072}
73
74Preprocessor::~Preprocessor() {
Argyrios Kyrtzidis2174a4f2008-08-23 12:12:06 +000075 assert(BacktrackPositions.empty() && "EnableBacktrack/Backtrack imbalance!");
Argyrios Kyrtzidis5b3284a2011-06-29 22:20:11 +000076 assert(MacroExpandingLexersStack.empty() && MacroExpandedTokens.empty() &&
77 "Preprocessor::HandleEndOfTokenLexer should have cleared those");
Argyrios Kyrtzidis2174a4f2008-08-23 12:12:06 +000078
Reid Spencer5f016e22007-07-11 17:01:13 +000079 while (!IncludeMacroStack.empty()) {
80 delete IncludeMacroStack.back().TheLexer;
Chris Lattner6cfe7592008-03-09 02:26:03 +000081 delete IncludeMacroStack.back().TheTokenLexer;
Reid Spencer5f016e22007-07-11 17:01:13 +000082 IncludeMacroStack.pop_back();
83 }
Chris Lattnercc1a8752007-10-07 08:44:20 +000084
85 // Free any macro definitions.
Ted Kremenek2a6b03a2010-10-19 21:30:11 +000086 for (MacroInfoChain *I = MIChainHead ; I ; I = I->Next)
Ted Kremenekaf8fa252010-10-19 18:16:54 +000087 I->MI.Destroy();
Mike Stump1eb44332009-09-09 15:08:12 +000088
Chris Lattner9594acf2007-07-15 00:25:26 +000089 // Free any cached macro expanders.
Chris Lattner6cfe7592008-03-09 02:26:03 +000090 for (unsigned i = 0, e = NumCachedTokenLexers; i != e; ++i)
91 delete TokenLexerCache[i];
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +000092
Chris Lattner23f77e52009-12-15 01:51:03 +000093 // Free any cached MacroArgs.
94 for (MacroArgs *ArgList = MacroArgCache; ArgList; )
95 ArgList = ArgList->deallocate();
Mike Stump1eb44332009-09-09 15:08:12 +000096
Reid Spencer5f016e22007-07-11 17:01:13 +000097 // Release pragma information.
98 delete PragmaHandlers;
99
100 // Delete the scratch buffer info.
101 delete ScratchBuf;
Chris Lattnereb50ed82008-03-14 06:07:05 +0000102
Daniel Dunbar5814e652009-11-11 21:44:21 +0000103 // Delete the header search info, if we own it.
104 if (OwnsHeaderSearch)
105 delete &HeaderInfo;
106
Chris Lattnereb50ed82008-03-14 06:07:05 +0000107 delete Callbacks;
Reid Spencer5f016e22007-07-11 17:01:13 +0000108}
109
Douglas Gregor998b3d32011-09-01 23:39:15 +0000110void Preprocessor::Initialize(const TargetInfo &Target) {
111 assert((!this->Target || this->Target == &Target) &&
112 "Invalid override of target information");
113 this->Target = &Target;
114
115 // Initialize information about built-ins.
116 BuiltinInfo.InitializeTarget(Target);
117
118 ScratchBuf = new ScratchBuffer(SourceMgr);
119 CounterValue = 0; // __COUNTER__ starts at 0.
120
121 // Clear stats.
122 NumDirectives = NumDefined = NumUndefined = NumPragma = 0;
123 NumIf = NumElse = NumEndif = 0;
124 NumEnteredSourceFiles = 0;
125 NumMacroExpanded = NumFnMacroExpanded = NumBuiltinMacroExpanded = 0;
126 NumFastMacroExpanded = NumTokenPaste = NumFastTokenPaste = 0;
127 MaxIncludeStackDepth = 0;
128 NumSkipped = 0;
129
130 // Default to discarding comments.
131 KeepComments = false;
132 KeepMacroComments = false;
133 SuppressIncludeNotFoundError = false;
134
135 // Macro expansion is enabled.
136 DisableMacroExpansion = false;
137 InMacroArgs = false;
138 NumCachedTokenLexers = 0;
139
140 CachedLexPos = 0;
141
142 // We haven't read anything from the external source.
143 ReadMacrosFromExternalSource = false;
144
145 LexDepth = 0;
146
147 // "Poison" __VA_ARGS__, which can only appear in the expansion of a macro.
148 // This gets unpoisoned where it is allowed.
149 (Ident__VA_ARGS__ = getIdentifierInfo("__VA_ARGS__"))->setIsPoisoned();
150 SetPoisonReason(Ident__VA_ARGS__,diag::ext_pp_bad_vaargs_use);
151
152 // Initialize the pragma handlers.
153 PragmaHandlers = new PragmaNamespace(StringRef());
154 RegisterBuiltinPragmas();
155
156 // Initialize builtin macros like __LINE__ and friends.
157 RegisterBuiltinMacros();
158
159 if(Features.Borland) {
160 Ident__exception_info = getIdentifierInfo("_exception_info");
161 Ident___exception_info = getIdentifierInfo("__exception_info");
162 Ident_GetExceptionInfo = getIdentifierInfo("GetExceptionInformation");
163 Ident__exception_code = getIdentifierInfo("_exception_code");
164 Ident___exception_code = getIdentifierInfo("__exception_code");
165 Ident_GetExceptionCode = getIdentifierInfo("GetExceptionCode");
166 Ident__abnormal_termination = getIdentifierInfo("_abnormal_termination");
167 Ident___abnormal_termination = getIdentifierInfo("__abnormal_termination");
168 Ident_AbnormalTermination = getIdentifierInfo("AbnormalTermination");
169 } else {
170 Ident__exception_info = Ident__exception_code = Ident__abnormal_termination = 0;
171 Ident___exception_info = Ident___exception_code = Ident___abnormal_termination = 0;
172 Ident_GetExceptionInfo = Ident_GetExceptionCode = Ident_AbnormalTermination = 0;
173 }
174}
175
Ted Kremenek337edcd2009-02-12 03:26:59 +0000176void Preprocessor::setPTHManager(PTHManager* pm) {
177 PTH.reset(pm);
Douglas Gregor52e71082009-10-16 18:18:30 +0000178 FileMgr.addStatCache(PTH->createStatCache());
Ted Kremenek337edcd2009-02-12 03:26:59 +0000179}
180
Chris Lattnerd2177732007-07-20 16:59:19 +0000181void Preprocessor::DumpToken(const Token &Tok, bool DumpFlags) const {
Benjamin Kramer6cb7c1a2009-08-23 12:08:50 +0000182 llvm::errs() << tok::getTokenName(Tok.getKind()) << " '"
183 << getSpelling(Tok) << "'";
Mike Stump1eb44332009-09-09 15:08:12 +0000184
Reid Spencer5f016e22007-07-11 17:01:13 +0000185 if (!DumpFlags) return;
Mike Stump1eb44332009-09-09 15:08:12 +0000186
Benjamin Kramer6cb7c1a2009-08-23 12:08:50 +0000187 llvm::errs() << "\t";
Reid Spencer5f016e22007-07-11 17:01:13 +0000188 if (Tok.isAtStartOfLine())
Benjamin Kramer6cb7c1a2009-08-23 12:08:50 +0000189 llvm::errs() << " [StartOfLine]";
Reid Spencer5f016e22007-07-11 17:01:13 +0000190 if (Tok.hasLeadingSpace())
Benjamin Kramer6cb7c1a2009-08-23 12:08:50 +0000191 llvm::errs() << " [LeadingSpace]";
Reid Spencer5f016e22007-07-11 17:01:13 +0000192 if (Tok.isExpandDisabled())
Benjamin Kramer6cb7c1a2009-08-23 12:08:50 +0000193 llvm::errs() << " [ExpandDisabled]";
Reid Spencer5f016e22007-07-11 17:01:13 +0000194 if (Tok.needsCleaning()) {
195 const char *Start = SourceMgr.getCharacterData(Tok.getLocation());
Chris Lattner5f9e2722011-07-23 10:55:15 +0000196 llvm::errs() << " [UnClean='" << StringRef(Start, Tok.getLength())
Benjamin Kramer6cb7c1a2009-08-23 12:08:50 +0000197 << "']";
Reid Spencer5f016e22007-07-11 17:01:13 +0000198 }
Mike Stump1eb44332009-09-09 15:08:12 +0000199
Benjamin Kramer6cb7c1a2009-08-23 12:08:50 +0000200 llvm::errs() << "\tLoc=<";
Chris Lattnerc3d8d572007-12-09 20:31:55 +0000201 DumpLocation(Tok.getLocation());
Benjamin Kramer6cb7c1a2009-08-23 12:08:50 +0000202 llvm::errs() << ">";
Chris Lattnerc3d8d572007-12-09 20:31:55 +0000203}
204
205void Preprocessor::DumpLocation(SourceLocation Loc) const {
Chris Lattnerb9c3f962009-01-27 07:57:44 +0000206 Loc.dump(SourceMgr);
Reid Spencer5f016e22007-07-11 17:01:13 +0000207}
208
209void Preprocessor::DumpMacro(const MacroInfo &MI) const {
Benjamin Kramer6cb7c1a2009-08-23 12:08:50 +0000210 llvm::errs() << "MACRO: ";
Reid Spencer5f016e22007-07-11 17:01:13 +0000211 for (unsigned i = 0, e = MI.getNumTokens(); i != e; ++i) {
212 DumpToken(MI.getReplacementToken(i));
Benjamin Kramer6cb7c1a2009-08-23 12:08:50 +0000213 llvm::errs() << " ";
Reid Spencer5f016e22007-07-11 17:01:13 +0000214 }
Benjamin Kramer6cb7c1a2009-08-23 12:08:50 +0000215 llvm::errs() << "\n";
Reid Spencer5f016e22007-07-11 17:01:13 +0000216}
217
218void Preprocessor::PrintStats() {
Benjamin Kramer6cb7c1a2009-08-23 12:08:50 +0000219 llvm::errs() << "\n*** Preprocessor Stats:\n";
220 llvm::errs() << NumDirectives << " directives found:\n";
221 llvm::errs() << " " << NumDefined << " #define.\n";
222 llvm::errs() << " " << NumUndefined << " #undef.\n";
223 llvm::errs() << " #include/#include_next/#import:\n";
224 llvm::errs() << " " << NumEnteredSourceFiles << " source files entered.\n";
225 llvm::errs() << " " << MaxIncludeStackDepth << " max include stack depth\n";
226 llvm::errs() << " " << NumIf << " #if/#ifndef/#ifdef.\n";
227 llvm::errs() << " " << NumElse << " #else/#elif.\n";
228 llvm::errs() << " " << NumEndif << " #endif.\n";
229 llvm::errs() << " " << NumPragma << " #pragma.\n";
230 llvm::errs() << NumSkipped << " #if/#ifndef#ifdef regions skipped\n";
Reid Spencer5f016e22007-07-11 17:01:13 +0000231
Benjamin Kramer6cb7c1a2009-08-23 12:08:50 +0000232 llvm::errs() << NumMacroExpanded << "/" << NumFnMacroExpanded << "/"
Ted Kremenekbdd30c22008-01-14 16:44:48 +0000233 << NumBuiltinMacroExpanded << " obj/fn/builtin macros expanded, "
234 << NumFastMacroExpanded << " on the fast path.\n";
Benjamin Kramer6cb7c1a2009-08-23 12:08:50 +0000235 llvm::errs() << (NumFastTokenPaste+NumTokenPaste)
Ted Kremenekbdd30c22008-01-14 16:44:48 +0000236 << " token paste (##) operations performed, "
237 << NumFastTokenPaste << " on the fast path.\n";
Reid Spencer5f016e22007-07-11 17:01:13 +0000238}
239
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +0000240Preprocessor::macro_iterator
241Preprocessor::macro_begin(bool IncludeExternalMacros) const {
242 if (IncludeExternalMacros && ExternalSource &&
Douglas Gregor88a35862010-01-04 19:18:44 +0000243 !ReadMacrosFromExternalSource) {
244 ReadMacrosFromExternalSource = true;
245 ExternalSource->ReadDefinedMacros();
246 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +0000247
248 return Macros.begin();
Douglas Gregor88a35862010-01-04 19:18:44 +0000249}
250
Argyrios Kyrtzidisc5c5e922011-06-29 22:20:04 +0000251size_t Preprocessor::getTotalMemory() const {
Ted Kremenek91d1bd62011-07-26 21:17:24 +0000252 return BP.getTotalMemory()
Ted Kremenek67485092011-07-27 18:41:23 +0000253 + llvm::capacity_in_bytes(MacroExpandedTokens)
Ted Kremenek91d1bd62011-07-26 21:17:24 +0000254 + Predefines.capacity() /* Predefines buffer. */
Ted Kremenek67485092011-07-27 18:41:23 +0000255 + llvm::capacity_in_bytes(Macros)
256 + llvm::capacity_in_bytes(PragmaPushMacroInfo)
257 + llvm::capacity_in_bytes(PoisonReasons)
258 + llvm::capacity_in_bytes(CommentHandlers);
Argyrios Kyrtzidisc5c5e922011-06-29 22:20:04 +0000259}
260
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +0000261Preprocessor::macro_iterator
262Preprocessor::macro_end(bool IncludeExternalMacros) const {
263 if (IncludeExternalMacros && ExternalSource &&
Douglas Gregor88a35862010-01-04 19:18:44 +0000264 !ReadMacrosFromExternalSource) {
265 ReadMacrosFromExternalSource = true;
266 ExternalSource->ReadDefinedMacros();
267 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +0000268
269 return Macros.end();
Douglas Gregor88a35862010-01-04 19:18:44 +0000270}
271
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +0000272bool Preprocessor::SetCodeCompletionPoint(const FileEntry *File,
273 unsigned TruncateAtLine,
Douglas Gregor29684422009-12-02 06:49:09 +0000274 unsigned TruncateAtColumn) {
275 using llvm::MemoryBuffer;
276
277 CodeCompletionFile = File;
278
279 // Okay to clear out the code-completion point by passing NULL.
280 if (!CodeCompletionFile)
281 return false;
282
283 // Load the actual file's contents.
Douglas Gregoraa38c3d2010-03-16 19:49:24 +0000284 bool Invalid = false;
285 const MemoryBuffer *Buffer = SourceMgr.getMemoryBufferForFile(File, &Invalid);
286 if (Invalid)
Douglas Gregor29684422009-12-02 06:49:09 +0000287 return true;
288
289 // Find the byte position of the truncation point.
290 const char *Position = Buffer->getBufferStart();
291 for (unsigned Line = 1; Line < TruncateAtLine; ++Line) {
292 for (; *Position; ++Position) {
293 if (*Position != '\r' && *Position != '\n')
294 continue;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +0000295
Douglas Gregor29684422009-12-02 06:49:09 +0000296 // Eat \r\n or \n\r as a single line.
297 if ((Position[1] == '\r' || Position[1] == '\n') &&
298 Position[0] != Position[1])
299 ++Position;
300 ++Position;
301 break;
302 }
303 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +0000304
Douglas Gregorb760fe82009-12-08 21:45:46 +0000305 Position += TruncateAtColumn - 1;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +0000306
Douglas Gregor29684422009-12-02 06:49:09 +0000307 // Truncate the buffer.
Douglas Gregorb760fe82009-12-08 21:45:46 +0000308 if (Position < Buffer->getBufferEnd()) {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000309 StringRef Data(Buffer->getBufferStart(),
Chris Lattnera0a270c2010-04-05 22:42:27 +0000310 Position-Buffer->getBufferStart());
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +0000311 MemoryBuffer *TruncatedBuffer
Chris Lattnera0a270c2010-04-05 22:42:27 +0000312 = MemoryBuffer::getMemBufferCopy(Data, Buffer->getBufferIdentifier());
Douglas Gregor29684422009-12-02 06:49:09 +0000313 SourceMgr.overrideFileContents(File, TruncatedBuffer);
314 }
315
316 return false;
317}
318
Douglas Gregor109ae732009-12-03 17:05:59 +0000319bool Preprocessor::isCodeCompletionFile(SourceLocation FileLoc) const {
Douglas Gregor29684422009-12-02 06:49:09 +0000320 return CodeCompletionFile && FileLoc.isFileID() &&
321 SourceMgr.getFileEntryForID(SourceMgr.getFileID(FileLoc))
322 == CodeCompletionFile;
323}
324
Douglas Gregor55817af2010-08-25 17:04:25 +0000325void Preprocessor::CodeCompleteNaturalLanguage() {
326 SetCodeCompletionPoint(0, 0, 0);
327 getDiagnostics().setSuppressAllDiagnostics(true);
328 if (CodeComplete)
329 CodeComplete->CodeCompleteNaturalLanguage();
330}
331
Benjamin Kramer51f5fe32010-02-27 17:05:45 +0000332/// getSpelling - This method is used to get the spelling of a token into a
333/// SmallVector. Note that the returned StringRef may not point to the
334/// supplied buffer if a copy can be avoided.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000335StringRef Preprocessor::getSpelling(const Token &Tok,
336 SmallVectorImpl<char> &Buffer,
Douglas Gregor50f6af72010-03-16 05:20:39 +0000337 bool *Invalid) const {
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +0000338 // NOTE: this has to be checked *before* testing for an IdentifierInfo.
339 if (Tok.isNot(tok::raw_identifier)) {
340 // Try the fast path.
341 if (const IdentifierInfo *II = Tok.getIdentifierInfo())
342 return II->getName();
343 }
Benjamin Kramer51f5fe32010-02-27 17:05:45 +0000344
345 // Resize the buffer if we need to copy into it.
346 if (Tok.needsCleaning())
347 Buffer.resize(Tok.getLength());
348
349 const char *Ptr = Buffer.data();
Douglas Gregor50f6af72010-03-16 05:20:39 +0000350 unsigned Len = getSpelling(Tok, Ptr, Invalid);
Chris Lattner5f9e2722011-07-23 10:55:15 +0000351 return StringRef(Ptr, Len);
Benjamin Kramer51f5fe32010-02-27 17:05:45 +0000352}
353
Reid Spencer5f016e22007-07-11 17:01:13 +0000354/// CreateString - Plop the specified string into a scratch buffer and return a
355/// location for it. If specified, the source location provides a source
356/// location for the token.
Chris Lattner47246be2009-01-26 19:29:26 +0000357void Preprocessor::CreateString(const char *Buf, unsigned Len, Token &Tok,
Chandler Carruth9e5bb852011-07-14 08:20:46 +0000358 SourceLocation ExpansionLoc) {
Chris Lattner47246be2009-01-26 19:29:26 +0000359 Tok.setLength(Len);
Mike Stump1eb44332009-09-09 15:08:12 +0000360
Chris Lattner47246be2009-01-26 19:29:26 +0000361 const char *DestPtr;
362 SourceLocation Loc = ScratchBuf->getToken(Buf, Len, DestPtr);
Mike Stump1eb44332009-09-09 15:08:12 +0000363
Chandler Carruth9e5bb852011-07-14 08:20:46 +0000364 if (ExpansionLoc.isValid())
Chandler Carruthbf340e42011-07-26 03:03:05 +0000365 Loc = SourceMgr.createExpansionLoc(Loc, ExpansionLoc, ExpansionLoc, Len);
Chris Lattner47246be2009-01-26 19:29:26 +0000366 Tok.setLocation(Loc);
Mike Stump1eb44332009-09-09 15:08:12 +0000367
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +0000368 // If this is a raw identifier or a literal token, set the pointer data.
369 if (Tok.is(tok::raw_identifier))
370 Tok.setRawIdentifierData(DestPtr);
371 else if (Tok.isLiteral())
Chris Lattner47246be2009-01-26 19:29:26 +0000372 Tok.setLiteralData(DestPtr);
Reid Spencer5f016e22007-07-11 17:01:13 +0000373}
374
375
Chris Lattner97ba77c2007-07-16 06:48:38 +0000376
Chris Lattner53b0dab2007-10-09 22:10:18 +0000377//===----------------------------------------------------------------------===//
378// Preprocessor Initialization Methods
379//===----------------------------------------------------------------------===//
380
Chris Lattner53b0dab2007-10-09 22:10:18 +0000381
382/// EnterMainSourceFile - Enter the specified FileID as the main source file,
Nate Begeman6b616022008-01-07 04:01:26 +0000383/// which implicitly adds the builtin defines etc.
Chris Lattnere127a0d2010-04-20 20:35:58 +0000384void Preprocessor::EnterMainSourceFile() {
Chris Lattner05db4272009-02-13 19:33:24 +0000385 // We do not allow the preprocessor to reenter the main file. Doing so will
386 // cause FileID's to accumulate information from both runs (e.g. #line
387 // information) and predefined macros aren't guaranteed to be set properly.
388 assert(NumEnteredSourceFiles == 0 && "Cannot reenter the main file!");
Chris Lattner2b2453a2009-01-17 06:22:33 +0000389 FileID MainFileID = SourceMgr.getMainFileID();
Mike Stump1eb44332009-09-09 15:08:12 +0000390
Chris Lattner53b0dab2007-10-09 22:10:18 +0000391 // Enter the main file source buffer.
Chris Lattnere127a0d2010-04-20 20:35:58 +0000392 EnterSourceFile(MainFileID, 0, SourceLocation());
Mike Stump1eb44332009-09-09 15:08:12 +0000393
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000394 // If we've been asked to skip bytes in the main file (e.g., as part of a
395 // precompiled preamble), do so now.
396 if (SkipMainFilePreamble.first > 0)
397 CurLexer->SkipBytes(SkipMainFilePreamble.first,
398 SkipMainFilePreamble.second);
399
Chris Lattnerb2832982007-11-15 19:07:47 +0000400 // Tell the header info that the main file was entered. If the file is later
401 // #imported, it won't be re-entered.
Chris Lattner2b2453a2009-01-17 06:22:33 +0000402 if (const FileEntry *FE = SourceMgr.getFileEntryForID(MainFileID))
Chris Lattnerb2832982007-11-15 19:07:47 +0000403 HeaderInfo.IncrementIncludeCount(FE);
Mike Stump1eb44332009-09-09 15:08:12 +0000404
Benjamin Kramerffd6e392009-12-31 15:33:09 +0000405 // Preprocess Predefines to populate the initial preprocessor state.
Mike Stump1eb44332009-09-09 15:08:12 +0000406 llvm::MemoryBuffer *SB =
Chris Lattnera0a270c2010-04-05 22:42:27 +0000407 llvm::MemoryBuffer::getMemBufferCopy(Predefines, "<built-in>");
Douglas Gregor043266b2010-08-26 14:07:34 +0000408 assert(SB && "Cannot create predefined source buffer");
Chris Lattner2b2453a2009-01-17 06:22:33 +0000409 FileID FID = SourceMgr.createFileIDForMemBuffer(SB);
410 assert(!FID.isInvalid() && "Could not create FileID for predefines?");
Mike Stump1eb44332009-09-09 15:08:12 +0000411
Chris Lattner53b0dab2007-10-09 22:10:18 +0000412 // Start parsing the predefines.
Chris Lattnere127a0d2010-04-20 20:35:58 +0000413 EnterSourceFile(FID, 0, SourceLocation());
Chris Lattner53b0dab2007-10-09 22:10:18 +0000414}
Chris Lattner97ba77c2007-07-16 06:48:38 +0000415
Daniel Dunbardbd82092010-03-23 05:09:10 +0000416void Preprocessor::EndSourceFile() {
417 // Notify the client that we reached the end of the source file.
418 if (Callbacks)
419 Callbacks->EndOfMainFile();
420}
Reid Spencer5f016e22007-07-11 17:01:13 +0000421
422//===----------------------------------------------------------------------===//
423// Lexer Event Handling.
424//===----------------------------------------------------------------------===//
425
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +0000426/// LookUpIdentifierInfo - Given a tok::raw_identifier token, look up the
427/// identifier information for the token and install it into the token,
428/// updating the token kind accordingly.
429IdentifierInfo *Preprocessor::LookUpIdentifierInfo(Token &Identifier) const {
430 assert(Identifier.getRawIdentifierData() != 0 && "No raw identifier data!");
Mike Stump1eb44332009-09-09 15:08:12 +0000431
Reid Spencer5f016e22007-07-11 17:01:13 +0000432 // Look up this token, see if it is a macro, or if it is a language keyword.
433 IdentifierInfo *II;
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +0000434 if (!Identifier.needsCleaning()) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000435 // No cleaning needed, just use the characters from the lexed buffer.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000436 II = getIdentifierInfo(StringRef(Identifier.getRawIdentifierData(),
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +0000437 Identifier.getLength()));
Reid Spencer5f016e22007-07-11 17:01:13 +0000438 } else {
439 // Cleaning needed, alloca a buffer, clean into it, then use the buffer.
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +0000440 llvm::SmallString<64> IdentifierBuffer;
Chris Lattner5f9e2722011-07-23 10:55:15 +0000441 StringRef CleanedStr = getSpelling(Identifier, IdentifierBuffer);
Benjamin Kramerddeea562010-02-27 13:44:12 +0000442 II = getIdentifierInfo(CleanedStr);
Reid Spencer5f016e22007-07-11 17:01:13 +0000443 }
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +0000444
445 // Update the token info (identifier info and appropriate token kind).
Reid Spencer5f016e22007-07-11 17:01:13 +0000446 Identifier.setIdentifierInfo(II);
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +0000447 Identifier.setKind(II->getTokenID());
448
Reid Spencer5f016e22007-07-11 17:01:13 +0000449 return II;
450}
451
John Wiegley28bbe4b2011-04-28 01:08:34 +0000452void Preprocessor::SetPoisonReason(IdentifierInfo *II, unsigned DiagID) {
453 PoisonReasons[II] = DiagID;
454}
455
456void Preprocessor::PoisonSEHIdentifiers(bool Poison) {
457 assert(Ident__exception_code && Ident__exception_info);
458 assert(Ident___exception_code && Ident___exception_info);
459 Ident__exception_code->setIsPoisoned(Poison);
460 Ident___exception_code->setIsPoisoned(Poison);
461 Ident_GetExceptionCode->setIsPoisoned(Poison);
462 Ident__exception_info->setIsPoisoned(Poison);
463 Ident___exception_info->setIsPoisoned(Poison);
464 Ident_GetExceptionInfo->setIsPoisoned(Poison);
465 Ident__abnormal_termination->setIsPoisoned(Poison);
466 Ident___abnormal_termination->setIsPoisoned(Poison);
467 Ident_AbnormalTermination->setIsPoisoned(Poison);
468}
469
470void Preprocessor::HandlePoisonedIdentifier(Token & Identifier) {
471 assert(Identifier.getIdentifierInfo() &&
472 "Can't handle identifiers without identifier info!");
473 llvm::DenseMap<IdentifierInfo*,unsigned>::const_iterator it =
474 PoisonReasons.find(Identifier.getIdentifierInfo());
475 if(it == PoisonReasons.end())
476 Diag(Identifier, diag::err_pp_used_poisoned_id);
477 else
478 Diag(Identifier,it->second) << Identifier.getIdentifierInfo();
479}
Reid Spencer5f016e22007-07-11 17:01:13 +0000480
481/// HandleIdentifier - This callback is invoked when the lexer reads an
482/// identifier. This callback looks up the identifier in the map and/or
483/// potentially macro expands it or turns it into a named token (like 'for').
Chris Lattner6a170eb2009-01-21 07:43:11 +0000484///
485/// Note that callers of this method are guarded by checking the
486/// IdentifierInfo's 'isHandleIdentifierCase' bit. If this method changes, the
487/// IdentifierInfo methods that compute these properties will need to change to
488/// match.
Chris Lattnerd2177732007-07-20 16:59:19 +0000489void Preprocessor::HandleIdentifier(Token &Identifier) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000490 assert(Identifier.getIdentifierInfo() &&
491 "Can't handle identifiers without identifier info!");
Mike Stump1eb44332009-09-09 15:08:12 +0000492
Reid Spencer5f016e22007-07-11 17:01:13 +0000493 IdentifierInfo &II = *Identifier.getIdentifierInfo();
494
495 // If this identifier was poisoned, and if it was not produced from a macro
496 // expansion, emit an error.
Ted Kremenek1a531572008-11-19 22:43:49 +0000497 if (II.isPoisoned() && CurPPLexer) {
John Wiegley28bbe4b2011-04-28 01:08:34 +0000498 HandlePoisonedIdentifier(Identifier);
Reid Spencer5f016e22007-07-11 17:01:13 +0000499 }
Mike Stump1eb44332009-09-09 15:08:12 +0000500
Reid Spencer5f016e22007-07-11 17:01:13 +0000501 // If this is a macro to be expanded, do it.
Chris Lattnercc1a8752007-10-07 08:44:20 +0000502 if (MacroInfo *MI = getMacroInfo(&II)) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000503 if (!DisableMacroExpansion && !Identifier.isExpandDisabled()) {
504 if (MI->isEnabled()) {
505 if (!HandleMacroExpandedIdentifier(Identifier, MI))
Douglas Gregor6be16fe2011-08-27 06:37:51 +0000506 return;
Reid Spencer5f016e22007-07-11 17:01:13 +0000507 } else {
508 // C99 6.10.3.4p2 says that a disabled macro may never again be
509 // expanded, even if it's in a context where it could be expanded in the
510 // future.
Chris Lattnerd2177732007-07-20 16:59:19 +0000511 Identifier.setFlag(Token::DisableExpand);
Reid Spencer5f016e22007-07-11 17:01:13 +0000512 }
513 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000514 }
515
516 // C++ 2.11p2: If this is an alternative representation of a C++ operator,
517 // then we act as if it is the actual operator and not the textual
518 // representation of it.
Fariborz Jahanianafbc6812010-09-03 17:33:04 +0000519 if (II.isCPlusPlusOperatorKeyword())
Reid Spencer5f016e22007-07-11 17:01:13 +0000520 Identifier.setIdentifierInfo(0);
521
Reid Spencer5f016e22007-07-11 17:01:13 +0000522 // If this is an extension token, diagnose its use.
Steve Naroffb4eaf9c2008-09-02 18:50:17 +0000523 // We avoid diagnosing tokens that originate from macro definitions.
Eli Friedman2962f4d2009-04-28 03:59:15 +0000524 // FIXME: This warning is disabled in cases where it shouldn't be,
525 // like "#define TY typeof", "TY(1) x".
526 if (II.isExtensionToken() && !DisableMacroExpansion)
Reid Spencer5f016e22007-07-11 17:01:13 +0000527 Diag(Identifier, diag::ext_token_used);
Douglas Gregor6aa52ec2011-08-26 23:56:07 +0000528}
529
530void Preprocessor::HandleModuleImport(Token &Import) {
531 // The token sequence
532 //
Douglas Gregor65030af2011-08-31 18:19:09 +0000533 // __import_module__ identifier
Douglas Gregor6aa52ec2011-08-26 23:56:07 +0000534 //
535 // indicates a module import directive. We load the module and then
536 // leave the token sequence for the parser.
537 Token ModuleNameTok = LookAhead(0);
538 if (ModuleNameTok.getKind() != tok::identifier)
539 return;
540
541 (void)TheModuleLoader.loadModule(Import.getLocation(),
542 *ModuleNameTok.getIdentifierInfo(),
543 ModuleNameTok.getLocation());
544
Douglas Gregor65030af2011-08-31 18:19:09 +0000545 // FIXME: Transmogrify __import_module__ into some kind of AST-only
546 // __import_module__ that is not recognized by the preprocessor but is
547 // recognized by the parser. It would also be useful to stash the ModuleKey
548 // somewhere, so we don't try to load the module twice.
Reid Spencer5f016e22007-07-11 17:01:13 +0000549}
Douglas Gregor2e222532009-07-02 17:08:52 +0000550
551void Preprocessor::AddCommentHandler(CommentHandler *Handler) {
552 assert(Handler && "NULL comment handler");
553 assert(std::find(CommentHandlers.begin(), CommentHandlers.end(), Handler) ==
554 CommentHandlers.end() && "Comment handler already registered");
555 CommentHandlers.push_back(Handler);
556}
557
558void Preprocessor::RemoveCommentHandler(CommentHandler *Handler) {
559 std::vector<CommentHandler *>::iterator Pos
560 = std::find(CommentHandlers.begin(), CommentHandlers.end(), Handler);
561 assert(Pos != CommentHandlers.end() && "Comment handler not registered");
562 CommentHandlers.erase(Pos);
563}
564
Chris Lattner046c2272010-01-18 22:35:47 +0000565bool Preprocessor::HandleComment(Token &result, SourceRange Comment) {
566 bool AnyPendingTokens = false;
Douglas Gregor2e222532009-07-02 17:08:52 +0000567 for (std::vector<CommentHandler *>::iterator H = CommentHandlers.begin(),
568 HEnd = CommentHandlers.end();
Chris Lattner046c2272010-01-18 22:35:47 +0000569 H != HEnd; ++H) {
570 if ((*H)->HandleComment(*this, Comment))
571 AnyPendingTokens = true;
572 }
573 if (!AnyPendingTokens || getCommentRetentionState())
574 return false;
575 Lex(result);
576 return true;
Douglas Gregor2e222532009-07-02 17:08:52 +0000577}
578
Douglas Gregor6aa52ec2011-08-26 23:56:07 +0000579ModuleLoader::~ModuleLoader() { }
580
Douglas Gregor2e222532009-07-02 17:08:52 +0000581CommentHandler::~CommentHandler() { }
Douglas Gregor94dc8f62010-03-19 16:15:56 +0000582
Douglas Gregorf44e8542010-08-24 19:08:16 +0000583CodeCompletionHandler::~CodeCompletionHandler() { }
584
Douglas Gregordca8ee82011-05-06 16:33:08 +0000585void Preprocessor::createPreprocessingRecord(
Chandler Carruth9e5bb852011-07-14 08:20:46 +0000586 bool IncludeNestedMacroExpansions) {
Douglas Gregor94dc8f62010-03-19 16:15:56 +0000587 if (Record)
588 return;
589
Chandler Carruth9e5bb852011-07-14 08:20:46 +0000590 Record = new PreprocessingRecord(IncludeNestedMacroExpansions);
Douglas Gregorb9e1b752010-03-19 17:12:43 +0000591 addPPCallbacks(Record);
Douglas Gregor94dc8f62010-03-19 16:15:56 +0000592}