blob: d33d9c513da9cf88e6cf1ce5073d6e0739ef859c [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),
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +000062 CodeCompletionFile(0), CodeCompletionOffset(0), CodeCompletionReached(0),
63 SkipMainFilePreamble(0, true), CurPPLexer(0),
Ted Kremenek9714a232010-10-19 22:15:20 +000064 CurDirLookup(0), Callbacks(0), MacroArgCache(0), Record(0), MIChainHead(0),
Douglas Gregor998b3d32011-09-01 23:39:15 +000065 MICache(0)
66{
Daniel Dunbar5814e652009-11-11 21:44:21 +000067 OwnsHeaderSearch = OwnsHeaders;
Douglas Gregor998b3d32011-09-01 23:39:15 +000068
69 if (!DelayInitialization) {
70 assert(Target && "Must provide target information for PP initialization");
71 Initialize(*Target);
John Wiegley28bbe4b2011-04-28 01:08:34 +000072 }
Reid Spencer5f016e22007-07-11 17:01:13 +000073}
74
75Preprocessor::~Preprocessor() {
Argyrios Kyrtzidis2174a4f2008-08-23 12:12:06 +000076 assert(BacktrackPositions.empty() && "EnableBacktrack/Backtrack imbalance!");
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +000077 assert(((MacroExpandingLexersStack.empty() && MacroExpandedTokens.empty()) ||
78 isCodeCompletionReached()) &&
Argyrios Kyrtzidis5b3284a2011-06-29 22:20:11 +000079 "Preprocessor::HandleEndOfTokenLexer should have cleared those");
Argyrios Kyrtzidis2174a4f2008-08-23 12:12:06 +000080
Reid Spencer5f016e22007-07-11 17:01:13 +000081 while (!IncludeMacroStack.empty()) {
82 delete IncludeMacroStack.back().TheLexer;
Chris Lattner6cfe7592008-03-09 02:26:03 +000083 delete IncludeMacroStack.back().TheTokenLexer;
Reid Spencer5f016e22007-07-11 17:01:13 +000084 IncludeMacroStack.pop_back();
85 }
Chris Lattnercc1a8752007-10-07 08:44:20 +000086
87 // Free any macro definitions.
Ted Kremenek2a6b03a2010-10-19 21:30:11 +000088 for (MacroInfoChain *I = MIChainHead ; I ; I = I->Next)
Ted Kremenekaf8fa252010-10-19 18:16:54 +000089 I->MI.Destroy();
Mike Stump1eb44332009-09-09 15:08:12 +000090
Chris Lattner9594acf2007-07-15 00:25:26 +000091 // Free any cached macro expanders.
Chris Lattner6cfe7592008-03-09 02:26:03 +000092 for (unsigned i = 0, e = NumCachedTokenLexers; i != e; ++i)
93 delete TokenLexerCache[i];
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +000094
Chris Lattner23f77e52009-12-15 01:51:03 +000095 // Free any cached MacroArgs.
96 for (MacroArgs *ArgList = MacroArgCache; ArgList; )
97 ArgList = ArgList->deallocate();
Mike Stump1eb44332009-09-09 15:08:12 +000098
Reid Spencer5f016e22007-07-11 17:01:13 +000099 // Release pragma information.
100 delete PragmaHandlers;
101
102 // Delete the scratch buffer info.
103 delete ScratchBuf;
Chris Lattnereb50ed82008-03-14 06:07:05 +0000104
Daniel Dunbar5814e652009-11-11 21:44:21 +0000105 // Delete the header search info, if we own it.
106 if (OwnsHeaderSearch)
107 delete &HeaderInfo;
108
Chris Lattnereb50ed82008-03-14 06:07:05 +0000109 delete Callbacks;
Reid Spencer5f016e22007-07-11 17:01:13 +0000110}
111
Douglas Gregor998b3d32011-09-01 23:39:15 +0000112void Preprocessor::Initialize(const TargetInfo &Target) {
113 assert((!this->Target || this->Target == &Target) &&
114 "Invalid override of target information");
115 this->Target = &Target;
116
117 // Initialize information about built-ins.
118 BuiltinInfo.InitializeTarget(Target);
119
120 ScratchBuf = new ScratchBuffer(SourceMgr);
121 CounterValue = 0; // __COUNTER__ starts at 0.
122
123 // Clear stats.
124 NumDirectives = NumDefined = NumUndefined = NumPragma = 0;
125 NumIf = NumElse = NumEndif = 0;
126 NumEnteredSourceFiles = 0;
127 NumMacroExpanded = NumFnMacroExpanded = NumBuiltinMacroExpanded = 0;
128 NumFastMacroExpanded = NumTokenPaste = NumFastTokenPaste = 0;
129 MaxIncludeStackDepth = 0;
130 NumSkipped = 0;
131
132 // Default to discarding comments.
133 KeepComments = false;
134 KeepMacroComments = false;
135 SuppressIncludeNotFoundError = false;
136
137 // Macro expansion is enabled.
138 DisableMacroExpansion = false;
139 InMacroArgs = false;
140 NumCachedTokenLexers = 0;
141
142 CachedLexPos = 0;
143
144 // We haven't read anything from the external source.
145 ReadMacrosFromExternalSource = false;
146
147 LexDepth = 0;
148
149 // "Poison" __VA_ARGS__, which can only appear in the expansion of a macro.
150 // This gets unpoisoned where it is allowed.
151 (Ident__VA_ARGS__ = getIdentifierInfo("__VA_ARGS__"))->setIsPoisoned();
152 SetPoisonReason(Ident__VA_ARGS__,diag::ext_pp_bad_vaargs_use);
153
154 // Initialize the pragma handlers.
155 PragmaHandlers = new PragmaNamespace(StringRef());
156 RegisterBuiltinPragmas();
157
158 // Initialize builtin macros like __LINE__ and friends.
159 RegisterBuiltinMacros();
160
161 if(Features.Borland) {
162 Ident__exception_info = getIdentifierInfo("_exception_info");
163 Ident___exception_info = getIdentifierInfo("__exception_info");
164 Ident_GetExceptionInfo = getIdentifierInfo("GetExceptionInformation");
165 Ident__exception_code = getIdentifierInfo("_exception_code");
166 Ident___exception_code = getIdentifierInfo("__exception_code");
167 Ident_GetExceptionCode = getIdentifierInfo("GetExceptionCode");
168 Ident__abnormal_termination = getIdentifierInfo("_abnormal_termination");
169 Ident___abnormal_termination = getIdentifierInfo("__abnormal_termination");
170 Ident_AbnormalTermination = getIdentifierInfo("AbnormalTermination");
171 } else {
172 Ident__exception_info = Ident__exception_code = Ident__abnormal_termination = 0;
173 Ident___exception_info = Ident___exception_code = Ident___abnormal_termination = 0;
174 Ident_GetExceptionInfo = Ident_GetExceptionCode = Ident_AbnormalTermination = 0;
175 }
176}
177
Ted Kremenek337edcd2009-02-12 03:26:59 +0000178void Preprocessor::setPTHManager(PTHManager* pm) {
179 PTH.reset(pm);
Douglas Gregor52e71082009-10-16 18:18:30 +0000180 FileMgr.addStatCache(PTH->createStatCache());
Ted Kremenek337edcd2009-02-12 03:26:59 +0000181}
182
Chris Lattnerd2177732007-07-20 16:59:19 +0000183void Preprocessor::DumpToken(const Token &Tok, bool DumpFlags) const {
Benjamin Kramer6cb7c1a2009-08-23 12:08:50 +0000184 llvm::errs() << tok::getTokenName(Tok.getKind()) << " '"
185 << getSpelling(Tok) << "'";
Mike Stump1eb44332009-09-09 15:08:12 +0000186
Reid Spencer5f016e22007-07-11 17:01:13 +0000187 if (!DumpFlags) return;
Mike Stump1eb44332009-09-09 15:08:12 +0000188
Benjamin Kramer6cb7c1a2009-08-23 12:08:50 +0000189 llvm::errs() << "\t";
Reid Spencer5f016e22007-07-11 17:01:13 +0000190 if (Tok.isAtStartOfLine())
Benjamin Kramer6cb7c1a2009-08-23 12:08:50 +0000191 llvm::errs() << " [StartOfLine]";
Reid Spencer5f016e22007-07-11 17:01:13 +0000192 if (Tok.hasLeadingSpace())
Benjamin Kramer6cb7c1a2009-08-23 12:08:50 +0000193 llvm::errs() << " [LeadingSpace]";
Reid Spencer5f016e22007-07-11 17:01:13 +0000194 if (Tok.isExpandDisabled())
Benjamin Kramer6cb7c1a2009-08-23 12:08:50 +0000195 llvm::errs() << " [ExpandDisabled]";
Reid Spencer5f016e22007-07-11 17:01:13 +0000196 if (Tok.needsCleaning()) {
197 const char *Start = SourceMgr.getCharacterData(Tok.getLocation());
Chris Lattner5f9e2722011-07-23 10:55:15 +0000198 llvm::errs() << " [UnClean='" << StringRef(Start, Tok.getLength())
Benjamin Kramer6cb7c1a2009-08-23 12:08:50 +0000199 << "']";
Reid Spencer5f016e22007-07-11 17:01:13 +0000200 }
Mike Stump1eb44332009-09-09 15:08:12 +0000201
Benjamin Kramer6cb7c1a2009-08-23 12:08:50 +0000202 llvm::errs() << "\tLoc=<";
Chris Lattnerc3d8d572007-12-09 20:31:55 +0000203 DumpLocation(Tok.getLocation());
Benjamin Kramer6cb7c1a2009-08-23 12:08:50 +0000204 llvm::errs() << ">";
Chris Lattnerc3d8d572007-12-09 20:31:55 +0000205}
206
207void Preprocessor::DumpLocation(SourceLocation Loc) const {
Chris Lattnerb9c3f962009-01-27 07:57:44 +0000208 Loc.dump(SourceMgr);
Reid Spencer5f016e22007-07-11 17:01:13 +0000209}
210
211void Preprocessor::DumpMacro(const MacroInfo &MI) const {
Benjamin Kramer6cb7c1a2009-08-23 12:08:50 +0000212 llvm::errs() << "MACRO: ";
Reid Spencer5f016e22007-07-11 17:01:13 +0000213 for (unsigned i = 0, e = MI.getNumTokens(); i != e; ++i) {
214 DumpToken(MI.getReplacementToken(i));
Benjamin Kramer6cb7c1a2009-08-23 12:08:50 +0000215 llvm::errs() << " ";
Reid Spencer5f016e22007-07-11 17:01:13 +0000216 }
Benjamin Kramer6cb7c1a2009-08-23 12:08:50 +0000217 llvm::errs() << "\n";
Reid Spencer5f016e22007-07-11 17:01:13 +0000218}
219
220void Preprocessor::PrintStats() {
Benjamin Kramer6cb7c1a2009-08-23 12:08:50 +0000221 llvm::errs() << "\n*** Preprocessor Stats:\n";
222 llvm::errs() << NumDirectives << " directives found:\n";
223 llvm::errs() << " " << NumDefined << " #define.\n";
224 llvm::errs() << " " << NumUndefined << " #undef.\n";
225 llvm::errs() << " #include/#include_next/#import:\n";
226 llvm::errs() << " " << NumEnteredSourceFiles << " source files entered.\n";
227 llvm::errs() << " " << MaxIncludeStackDepth << " max include stack depth\n";
228 llvm::errs() << " " << NumIf << " #if/#ifndef/#ifdef.\n";
229 llvm::errs() << " " << NumElse << " #else/#elif.\n";
230 llvm::errs() << " " << NumEndif << " #endif.\n";
231 llvm::errs() << " " << NumPragma << " #pragma.\n";
232 llvm::errs() << NumSkipped << " #if/#ifndef#ifdef regions skipped\n";
Reid Spencer5f016e22007-07-11 17:01:13 +0000233
Benjamin Kramer6cb7c1a2009-08-23 12:08:50 +0000234 llvm::errs() << NumMacroExpanded << "/" << NumFnMacroExpanded << "/"
Ted Kremenekbdd30c22008-01-14 16:44:48 +0000235 << NumBuiltinMacroExpanded << " obj/fn/builtin macros expanded, "
236 << NumFastMacroExpanded << " on the fast path.\n";
Benjamin Kramer6cb7c1a2009-08-23 12:08:50 +0000237 llvm::errs() << (NumFastTokenPaste+NumTokenPaste)
Ted Kremenekbdd30c22008-01-14 16:44:48 +0000238 << " token paste (##) operations performed, "
239 << NumFastTokenPaste << " on the fast path.\n";
Reid Spencer5f016e22007-07-11 17:01:13 +0000240}
241
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +0000242Preprocessor::macro_iterator
243Preprocessor::macro_begin(bool IncludeExternalMacros) const {
244 if (IncludeExternalMacros && ExternalSource &&
Douglas Gregor88a35862010-01-04 19:18:44 +0000245 !ReadMacrosFromExternalSource) {
246 ReadMacrosFromExternalSource = true;
247 ExternalSource->ReadDefinedMacros();
248 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +0000249
250 return Macros.begin();
Douglas Gregor88a35862010-01-04 19:18:44 +0000251}
252
Argyrios Kyrtzidisc5c5e922011-06-29 22:20:04 +0000253size_t Preprocessor::getTotalMemory() const {
Ted Kremenek91d1bd62011-07-26 21:17:24 +0000254 return BP.getTotalMemory()
Ted Kremenek67485092011-07-27 18:41:23 +0000255 + llvm::capacity_in_bytes(MacroExpandedTokens)
Ted Kremenek91d1bd62011-07-26 21:17:24 +0000256 + Predefines.capacity() /* Predefines buffer. */
Ted Kremenek67485092011-07-27 18:41:23 +0000257 + llvm::capacity_in_bytes(Macros)
258 + llvm::capacity_in_bytes(PragmaPushMacroInfo)
259 + llvm::capacity_in_bytes(PoisonReasons)
260 + llvm::capacity_in_bytes(CommentHandlers);
Argyrios Kyrtzidisc5c5e922011-06-29 22:20:04 +0000261}
262
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +0000263Preprocessor::macro_iterator
264Preprocessor::macro_end(bool IncludeExternalMacros) const {
265 if (IncludeExternalMacros && ExternalSource &&
Douglas Gregor88a35862010-01-04 19:18:44 +0000266 !ReadMacrosFromExternalSource) {
267 ReadMacrosFromExternalSource = true;
268 ExternalSource->ReadDefinedMacros();
269 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +0000270
271 return Macros.end();
Douglas Gregor88a35862010-01-04 19:18:44 +0000272}
273
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +0000274bool Preprocessor::SetCodeCompletionPoint(const FileEntry *File,
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +0000275 unsigned CompleteLine,
276 unsigned CompleteColumn) {
277 assert(File);
278 assert(CompleteLine && CompleteColumn && "Starts from 1:1");
279 assert(!CodeCompletionFile && "Already set");
280
Douglas Gregor29684422009-12-02 06:49:09 +0000281 using llvm::MemoryBuffer;
282
Douglas Gregor29684422009-12-02 06:49:09 +0000283 // 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();
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +0000291 for (unsigned Line = 1; Line < CompleteLine; ++Line) {
Douglas Gregor29684422009-12-02 06:49:09 +0000292 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
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +0000305 Position += CompleteColumn - 1;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +0000306
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +0000307 // Insert '\0' at the code-completion point.
Douglas Gregorb760fe82009-12-08 21:45:46 +0000308 if (Position < Buffer->getBufferEnd()) {
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +0000309 CodeCompletionFile = File;
310 CodeCompletionOffset = Position - Buffer->getBufferStart();
311
312 MemoryBuffer *NewBuffer =
313 MemoryBuffer::getNewUninitMemBuffer(Buffer->getBufferSize() + 1,
314 Buffer->getBufferIdentifier());
Benjamin Kramer41a50a92011-09-04 20:26:28 +0000315 char *NewBuf = const_cast<char*>(NewBuffer->getBufferStart());
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +0000316 char *NewPos = std::copy(Buffer->getBufferStart(), Position, NewBuf);
317 *NewPos = '\0';
318 std::copy(Position, Buffer->getBufferEnd(), NewPos+1);
319 SourceMgr.overrideFileContents(File, NewBuffer);
Douglas Gregor29684422009-12-02 06:49:09 +0000320 }
321
322 return false;
323}
324
Douglas Gregor55817af2010-08-25 17:04:25 +0000325void Preprocessor::CodeCompleteNaturalLanguage() {
Douglas Gregor55817af2010-08-25 17:04:25 +0000326 if (CodeComplete)
327 CodeComplete->CodeCompleteNaturalLanguage();
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +0000328 setCodeCompletionReached();
Douglas Gregor55817af2010-08-25 17:04:25 +0000329}
330
Benjamin Kramer51f5fe32010-02-27 17:05:45 +0000331/// getSpelling - This method is used to get the spelling of a token into a
332/// SmallVector. Note that the returned StringRef may not point to the
333/// supplied buffer if a copy can be avoided.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000334StringRef Preprocessor::getSpelling(const Token &Tok,
335 SmallVectorImpl<char> &Buffer,
Douglas Gregor50f6af72010-03-16 05:20:39 +0000336 bool *Invalid) const {
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +0000337 // NOTE: this has to be checked *before* testing for an IdentifierInfo.
338 if (Tok.isNot(tok::raw_identifier)) {
339 // Try the fast path.
340 if (const IdentifierInfo *II = Tok.getIdentifierInfo())
341 return II->getName();
342 }
Benjamin Kramer51f5fe32010-02-27 17:05:45 +0000343
344 // Resize the buffer if we need to copy into it.
345 if (Tok.needsCleaning())
346 Buffer.resize(Tok.getLength());
347
348 const char *Ptr = Buffer.data();
Douglas Gregor50f6af72010-03-16 05:20:39 +0000349 unsigned Len = getSpelling(Tok, Ptr, Invalid);
Chris Lattner5f9e2722011-07-23 10:55:15 +0000350 return StringRef(Ptr, Len);
Benjamin Kramer51f5fe32010-02-27 17:05:45 +0000351}
352
Reid Spencer5f016e22007-07-11 17:01:13 +0000353/// CreateString - Plop the specified string into a scratch buffer and return a
354/// location for it. If specified, the source location provides a source
355/// location for the token.
Chris Lattner47246be2009-01-26 19:29:26 +0000356void Preprocessor::CreateString(const char *Buf, unsigned Len, Token &Tok,
Chandler Carruth9e5bb852011-07-14 08:20:46 +0000357 SourceLocation ExpansionLoc) {
Chris Lattner47246be2009-01-26 19:29:26 +0000358 Tok.setLength(Len);
Mike Stump1eb44332009-09-09 15:08:12 +0000359
Chris Lattner47246be2009-01-26 19:29:26 +0000360 const char *DestPtr;
361 SourceLocation Loc = ScratchBuf->getToken(Buf, Len, DestPtr);
Mike Stump1eb44332009-09-09 15:08:12 +0000362
Chandler Carruth9e5bb852011-07-14 08:20:46 +0000363 if (ExpansionLoc.isValid())
Chandler Carruthbf340e42011-07-26 03:03:05 +0000364 Loc = SourceMgr.createExpansionLoc(Loc, ExpansionLoc, ExpansionLoc, Len);
Chris Lattner47246be2009-01-26 19:29:26 +0000365 Tok.setLocation(Loc);
Mike Stump1eb44332009-09-09 15:08:12 +0000366
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +0000367 // If this is a raw identifier or a literal token, set the pointer data.
368 if (Tok.is(tok::raw_identifier))
369 Tok.setRawIdentifierData(DestPtr);
370 else if (Tok.isLiteral())
Chris Lattner47246be2009-01-26 19:29:26 +0000371 Tok.setLiteralData(DestPtr);
Reid Spencer5f016e22007-07-11 17:01:13 +0000372}
373
374
Chris Lattner97ba77c2007-07-16 06:48:38 +0000375
Chris Lattner53b0dab2007-10-09 22:10:18 +0000376//===----------------------------------------------------------------------===//
377// Preprocessor Initialization Methods
378//===----------------------------------------------------------------------===//
379
Chris Lattner53b0dab2007-10-09 22:10:18 +0000380
381/// EnterMainSourceFile - Enter the specified FileID as the main source file,
Nate Begeman6b616022008-01-07 04:01:26 +0000382/// which implicitly adds the builtin defines etc.
Chris Lattnere127a0d2010-04-20 20:35:58 +0000383void Preprocessor::EnterMainSourceFile() {
Chris Lattner05db4272009-02-13 19:33:24 +0000384 // We do not allow the preprocessor to reenter the main file. Doing so will
385 // cause FileID's to accumulate information from both runs (e.g. #line
386 // information) and predefined macros aren't guaranteed to be set properly.
387 assert(NumEnteredSourceFiles == 0 && "Cannot reenter the main file!");
Chris Lattner2b2453a2009-01-17 06:22:33 +0000388 FileID MainFileID = SourceMgr.getMainFileID();
Mike Stump1eb44332009-09-09 15:08:12 +0000389
Chris Lattner53b0dab2007-10-09 22:10:18 +0000390 // Enter the main file source buffer.
Chris Lattnere127a0d2010-04-20 20:35:58 +0000391 EnterSourceFile(MainFileID, 0, SourceLocation());
Mike Stump1eb44332009-09-09 15:08:12 +0000392
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000393 // If we've been asked to skip bytes in the main file (e.g., as part of a
394 // precompiled preamble), do so now.
395 if (SkipMainFilePreamble.first > 0)
396 CurLexer->SkipBytes(SkipMainFilePreamble.first,
397 SkipMainFilePreamble.second);
398
Chris Lattnerb2832982007-11-15 19:07:47 +0000399 // Tell the header info that the main file was entered. If the file is later
400 // #imported, it won't be re-entered.
Chris Lattner2b2453a2009-01-17 06:22:33 +0000401 if (const FileEntry *FE = SourceMgr.getFileEntryForID(MainFileID))
Chris Lattnerb2832982007-11-15 19:07:47 +0000402 HeaderInfo.IncrementIncludeCount(FE);
Mike Stump1eb44332009-09-09 15:08:12 +0000403
Benjamin Kramerffd6e392009-12-31 15:33:09 +0000404 // Preprocess Predefines to populate the initial preprocessor state.
Mike Stump1eb44332009-09-09 15:08:12 +0000405 llvm::MemoryBuffer *SB =
Chris Lattnera0a270c2010-04-05 22:42:27 +0000406 llvm::MemoryBuffer::getMemBufferCopy(Predefines, "<built-in>");
Douglas Gregor043266b2010-08-26 14:07:34 +0000407 assert(SB && "Cannot create predefined source buffer");
Chris Lattner2b2453a2009-01-17 06:22:33 +0000408 FileID FID = SourceMgr.createFileIDForMemBuffer(SB);
409 assert(!FID.isInvalid() && "Could not create FileID for predefines?");
Mike Stump1eb44332009-09-09 15:08:12 +0000410
Chris Lattner53b0dab2007-10-09 22:10:18 +0000411 // Start parsing the predefines.
Chris Lattnere127a0d2010-04-20 20:35:58 +0000412 EnterSourceFile(FID, 0, SourceLocation());
Chris Lattner53b0dab2007-10-09 22:10:18 +0000413}
Chris Lattner97ba77c2007-07-16 06:48:38 +0000414
Daniel Dunbardbd82092010-03-23 05:09:10 +0000415void Preprocessor::EndSourceFile() {
416 // Notify the client that we reached the end of the source file.
417 if (Callbacks)
418 Callbacks->EndOfMainFile();
419}
Reid Spencer5f016e22007-07-11 17:01:13 +0000420
421//===----------------------------------------------------------------------===//
422// Lexer Event Handling.
423//===----------------------------------------------------------------------===//
424
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +0000425/// LookUpIdentifierInfo - Given a tok::raw_identifier token, look up the
426/// identifier information for the token and install it into the token,
427/// updating the token kind accordingly.
428IdentifierInfo *Preprocessor::LookUpIdentifierInfo(Token &Identifier) const {
429 assert(Identifier.getRawIdentifierData() != 0 && "No raw identifier data!");
Mike Stump1eb44332009-09-09 15:08:12 +0000430
Reid Spencer5f016e22007-07-11 17:01:13 +0000431 // Look up this token, see if it is a macro, or if it is a language keyword.
432 IdentifierInfo *II;
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +0000433 if (!Identifier.needsCleaning()) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000434 // No cleaning needed, just use the characters from the lexed buffer.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000435 II = getIdentifierInfo(StringRef(Identifier.getRawIdentifierData(),
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +0000436 Identifier.getLength()));
Reid Spencer5f016e22007-07-11 17:01:13 +0000437 } else {
438 // Cleaning needed, alloca a buffer, clean into it, then use the buffer.
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +0000439 llvm::SmallString<64> IdentifierBuffer;
Chris Lattner5f9e2722011-07-23 10:55:15 +0000440 StringRef CleanedStr = getSpelling(Identifier, IdentifierBuffer);
Benjamin Kramerddeea562010-02-27 13:44:12 +0000441 II = getIdentifierInfo(CleanedStr);
Reid Spencer5f016e22007-07-11 17:01:13 +0000442 }
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +0000443
444 // Update the token info (identifier info and appropriate token kind).
Reid Spencer5f016e22007-07-11 17:01:13 +0000445 Identifier.setIdentifierInfo(II);
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +0000446 Identifier.setKind(II->getTokenID());
447
Reid Spencer5f016e22007-07-11 17:01:13 +0000448 return II;
449}
450
John Wiegley28bbe4b2011-04-28 01:08:34 +0000451void Preprocessor::SetPoisonReason(IdentifierInfo *II, unsigned DiagID) {
452 PoisonReasons[II] = DiagID;
453}
454
455void Preprocessor::PoisonSEHIdentifiers(bool Poison) {
456 assert(Ident__exception_code && Ident__exception_info);
457 assert(Ident___exception_code && Ident___exception_info);
458 Ident__exception_code->setIsPoisoned(Poison);
459 Ident___exception_code->setIsPoisoned(Poison);
460 Ident_GetExceptionCode->setIsPoisoned(Poison);
461 Ident__exception_info->setIsPoisoned(Poison);
462 Ident___exception_info->setIsPoisoned(Poison);
463 Ident_GetExceptionInfo->setIsPoisoned(Poison);
464 Ident__abnormal_termination->setIsPoisoned(Poison);
465 Ident___abnormal_termination->setIsPoisoned(Poison);
466 Ident_AbnormalTermination->setIsPoisoned(Poison);
467}
468
469void Preprocessor::HandlePoisonedIdentifier(Token & Identifier) {
470 assert(Identifier.getIdentifierInfo() &&
471 "Can't handle identifiers without identifier info!");
472 llvm::DenseMap<IdentifierInfo*,unsigned>::const_iterator it =
473 PoisonReasons.find(Identifier.getIdentifierInfo());
474 if(it == PoisonReasons.end())
475 Diag(Identifier, diag::err_pp_used_poisoned_id);
476 else
477 Diag(Identifier,it->second) << Identifier.getIdentifierInfo();
478}
Reid Spencer5f016e22007-07-11 17:01:13 +0000479
480/// HandleIdentifier - This callback is invoked when the lexer reads an
481/// identifier. This callback looks up the identifier in the map and/or
482/// potentially macro expands it or turns it into a named token (like 'for').
Chris Lattner6a170eb2009-01-21 07:43:11 +0000483///
484/// Note that callers of this method are guarded by checking the
485/// IdentifierInfo's 'isHandleIdentifierCase' bit. If this method changes, the
486/// IdentifierInfo methods that compute these properties will need to change to
487/// match.
Chris Lattnerd2177732007-07-20 16:59:19 +0000488void Preprocessor::HandleIdentifier(Token &Identifier) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000489 assert(Identifier.getIdentifierInfo() &&
490 "Can't handle identifiers without identifier info!");
Mike Stump1eb44332009-09-09 15:08:12 +0000491
Reid Spencer5f016e22007-07-11 17:01:13 +0000492 IdentifierInfo &II = *Identifier.getIdentifierInfo();
493
494 // If this identifier was poisoned, and if it was not produced from a macro
495 // expansion, emit an error.
Ted Kremenek1a531572008-11-19 22:43:49 +0000496 if (II.isPoisoned() && CurPPLexer) {
John Wiegley28bbe4b2011-04-28 01:08:34 +0000497 HandlePoisonedIdentifier(Identifier);
Reid Spencer5f016e22007-07-11 17:01:13 +0000498 }
Mike Stump1eb44332009-09-09 15:08:12 +0000499
Reid Spencer5f016e22007-07-11 17:01:13 +0000500 // If this is a macro to be expanded, do it.
Chris Lattnercc1a8752007-10-07 08:44:20 +0000501 if (MacroInfo *MI = getMacroInfo(&II)) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000502 if (!DisableMacroExpansion && !Identifier.isExpandDisabled()) {
503 if (MI->isEnabled()) {
504 if (!HandleMacroExpandedIdentifier(Identifier, MI))
Douglas Gregor6be16fe2011-08-27 06:37:51 +0000505 return;
Reid Spencer5f016e22007-07-11 17:01:13 +0000506 } else {
507 // C99 6.10.3.4p2 says that a disabled macro may never again be
508 // expanded, even if it's in a context where it could be expanded in the
509 // future.
Chris Lattnerd2177732007-07-20 16:59:19 +0000510 Identifier.setFlag(Token::DisableExpand);
Reid Spencer5f016e22007-07-11 17:01:13 +0000511 }
512 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000513 }
514
515 // C++ 2.11p2: If this is an alternative representation of a C++ operator,
516 // then we act as if it is the actual operator and not the textual
517 // representation of it.
Fariborz Jahanianafbc6812010-09-03 17:33:04 +0000518 if (II.isCPlusPlusOperatorKeyword())
Reid Spencer5f016e22007-07-11 17:01:13 +0000519 Identifier.setIdentifierInfo(0);
520
Reid Spencer5f016e22007-07-11 17:01:13 +0000521 // If this is an extension token, diagnose its use.
Steve Naroffb4eaf9c2008-09-02 18:50:17 +0000522 // We avoid diagnosing tokens that originate from macro definitions.
Eli Friedman2962f4d2009-04-28 03:59:15 +0000523 // FIXME: This warning is disabled in cases where it shouldn't be,
524 // like "#define TY typeof", "TY(1) x".
525 if (II.isExtensionToken() && !DisableMacroExpansion)
Reid Spencer5f016e22007-07-11 17:01:13 +0000526 Diag(Identifier, diag::ext_token_used);
Douglas Gregor6aa52ec2011-08-26 23:56:07 +0000527}
528
529void Preprocessor::HandleModuleImport(Token &Import) {
530 // The token sequence
531 //
Douglas Gregor65030af2011-08-31 18:19:09 +0000532 // __import_module__ identifier
Douglas Gregor6aa52ec2011-08-26 23:56:07 +0000533 //
534 // indicates a module import directive. We load the module and then
535 // leave the token sequence for the parser.
536 Token ModuleNameTok = LookAhead(0);
537 if (ModuleNameTok.getKind() != tok::identifier)
538 return;
539
540 (void)TheModuleLoader.loadModule(Import.getLocation(),
541 *ModuleNameTok.getIdentifierInfo(),
542 ModuleNameTok.getLocation());
543
Douglas Gregor65030af2011-08-31 18:19:09 +0000544 // FIXME: Transmogrify __import_module__ into some kind of AST-only
545 // __import_module__ that is not recognized by the preprocessor but is
546 // recognized by the parser. It would also be useful to stash the ModuleKey
547 // somewhere, so we don't try to load the module twice.
Reid Spencer5f016e22007-07-11 17:01:13 +0000548}
Douglas Gregor2e222532009-07-02 17:08:52 +0000549
550void Preprocessor::AddCommentHandler(CommentHandler *Handler) {
551 assert(Handler && "NULL comment handler");
552 assert(std::find(CommentHandlers.begin(), CommentHandlers.end(), Handler) ==
553 CommentHandlers.end() && "Comment handler already registered");
554 CommentHandlers.push_back(Handler);
555}
556
557void Preprocessor::RemoveCommentHandler(CommentHandler *Handler) {
558 std::vector<CommentHandler *>::iterator Pos
559 = std::find(CommentHandlers.begin(), CommentHandlers.end(), Handler);
560 assert(Pos != CommentHandlers.end() && "Comment handler not registered");
561 CommentHandlers.erase(Pos);
562}
563
Chris Lattner046c2272010-01-18 22:35:47 +0000564bool Preprocessor::HandleComment(Token &result, SourceRange Comment) {
565 bool AnyPendingTokens = false;
Douglas Gregor2e222532009-07-02 17:08:52 +0000566 for (std::vector<CommentHandler *>::iterator H = CommentHandlers.begin(),
567 HEnd = CommentHandlers.end();
Chris Lattner046c2272010-01-18 22:35:47 +0000568 H != HEnd; ++H) {
569 if ((*H)->HandleComment(*this, Comment))
570 AnyPendingTokens = true;
571 }
572 if (!AnyPendingTokens || getCommentRetentionState())
573 return false;
574 Lex(result);
575 return true;
Douglas Gregor2e222532009-07-02 17:08:52 +0000576}
577
Douglas Gregor6aa52ec2011-08-26 23:56:07 +0000578ModuleLoader::~ModuleLoader() { }
579
Douglas Gregor2e222532009-07-02 17:08:52 +0000580CommentHandler::~CommentHandler() { }
Douglas Gregor94dc8f62010-03-19 16:15:56 +0000581
Douglas Gregorf44e8542010-08-24 19:08:16 +0000582CodeCompletionHandler::~CodeCompletionHandler() { }
583
Douglas Gregordca8ee82011-05-06 16:33:08 +0000584void Preprocessor::createPreprocessingRecord(
Chandler Carruth9e5bb852011-07-14 08:20:46 +0000585 bool IncludeNestedMacroExpansions) {
Douglas Gregor94dc8f62010-03-19 16:15:56 +0000586 if (Record)
587 return;
588
Chandler Carruth9e5bb852011-07-14 08:20:46 +0000589 Record = new PreprocessingRecord(IncludeNestedMacroExpansions);
Douglas Gregorb9e1b752010-03-19 17:12:43 +0000590 addPPCallbacks(Record);
Douglas Gregor94dc8f62010-03-19 16:15:56 +0000591}