blob: db3479e8f3eba71ef8edc99bbc24b1bd3aad4824 [file] [log] [blame]
Chris Lattner22eb9722006-06-18 05:43:12 +00001//===--- Preprocess.cpp - C Language Family Preprocessor Implementation ---===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner5b12ab82007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattner22eb9722006-06-18 05:43:12 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the Preprocessor interface.
11//
12//===----------------------------------------------------------------------===//
13//
Chris Lattner22eb9722006-06-18 05:43:12 +000014// Options to support:
15// -H - Print the name of each header file used.
Chris Lattner1630c3c2009-02-06 06:45:26 +000016// -d[DNI] - Dump various things.
Chris Lattner22eb9722006-06-18 05:43:12 +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//
Chris Lattner22eb9722006-06-18 05:43:12 +000026//===----------------------------------------------------------------------===//
27
28#include "clang/Lex/Preprocessor.h"
Chris Lattnerd19564b2009-12-15 01:51:03 +000029#include "MacroArgs.h"
Douglas Gregor9882a5a2010-01-04 19:18:44 +000030#include "clang/Lex/ExternalPreprocessorSource.h"
Chris Lattner07b019a2006-10-22 07:28:56 +000031#include "clang/Lex/HeaderSearch.h"
Chris Lattner22eb9722006-06-18 05:43:12 +000032#include "clang/Lex/MacroInfo.h"
Chris Lattnerb8761832006-06-24 21:31:03 +000033#include "clang/Lex/Pragma.h"
Douglas Gregor7f6d60d2010-03-19 16:15:56 +000034#include "clang/Lex/PreprocessingRecord.h"
Chris Lattner0b8cfc22006-06-28 06:49:17 +000035#include "clang/Lex/ScratchBuffer.h"
Chris Lattner60f36222009-01-29 05:15:15 +000036#include "clang/Lex/LexDiagnostic.h"
Douglas Gregor3a7ad252010-08-24 19:08:16 +000037#include "clang/Lex/CodeCompletionHandler.h"
Douglas Gregor08142532011-08-26 23:56:07 +000038#include "clang/Lex/ModuleLoader.h"
Chris Lattner22eb9722006-06-18 05:43:12 +000039#include "clang/Basic/SourceManager.h"
Ted Kremeneka5c2c272009-02-12 03:26:59 +000040#include "clang/Basic/FileManager.h"
Chris Lattner81278c62006-10-14 19:03:49 +000041#include "clang/Basic/TargetInfo.h"
Chris Lattner5cd83512008-10-05 20:40:30 +000042#include "llvm/ADT/APFloat.h"
Chris Lattner7a4af3b2006-07-26 06:26:52 +000043#include "llvm/ADT/SmallVector.h"
Chris Lattner8a7003c2007-07-16 06:48:38 +000044#include "llvm/Support/MemoryBuffer.h"
Benjamin Kramer89b422c2009-08-23 12:08:50 +000045#include "llvm/Support/raw_ostream.h"
Ted Kremenek8b77fe72011-07-27 18:41:23 +000046#include "llvm/Support/Capacity.h"
Chris Lattner22eb9722006-06-18 05:43:12 +000047using namespace clang;
48
49//===----------------------------------------------------------------------===//
Douglas Gregor9882a5a2010-01-04 19:18:44 +000050ExternalPreprocessorSource::~ExternalPreprocessorSource() { }
Chris Lattner22eb9722006-06-18 05:43:12 +000051
Douglas Gregor7018d5b2011-09-01 20:23:19 +000052Preprocessor::Preprocessor(Diagnostic &diags, LangOptions &opts,
Douglas Gregor83297df2011-09-01 23:39:15 +000053 const TargetInfo *target, SourceManager &SM,
Douglas Gregor08142532011-08-26 23:56:07 +000054 HeaderSearch &Headers, ModuleLoader &TheModuleLoader,
Daniel Dunbar0c6c9302009-11-11 21:44:21 +000055 IdentifierInfoLookup* IILookup,
Douglas Gregor83297df2011-09-01 23:39:15 +000056 bool OwnsHeaders,
57 bool DelayInitialization)
Chris Lattner83aba002009-03-13 21:17:43 +000058 : Diags(&diags), Features(opts), Target(target),FileMgr(Headers.getFileMgr()),
Douglas Gregor08142532011-08-26 23:56:07 +000059 SourceMgr(SM), HeaderInfo(Headers), TheModuleLoader(TheModuleLoader),
60 ExternalSource(0),
Douglas Gregor83297df2011-09-01 23:39:15 +000061 Identifiers(opts, IILookup), CodeComplete(0),
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +000062 CodeCompletionFile(0), CodeCompletionOffset(0), CodeCompletionReached(0),
63 SkipMainFilePreamble(0, true), CurPPLexer(0),
Ted Kremenekc8456f82010-10-19 22:15:20 +000064 CurDirLookup(0), Callbacks(0), MacroArgCache(0), Record(0), MIChainHead(0),
Douglas Gregor83297df2011-09-01 23:39:15 +000065 MICache(0)
66{
Daniel Dunbar0c6c9302009-11-11 21:44:21 +000067 OwnsHeaderSearch = OwnsHeaders;
Douglas Gregor83297df2011-09-01 23:39:15 +000068
69 if (!DelayInitialization) {
70 assert(Target && "Must provide target information for PP initialization");
71 Initialize(*Target);
John Wiegley1c0675e2011-04-28 01:08:34 +000072 }
Chris Lattner22eb9722006-06-18 05:43:12 +000073}
74
75Preprocessor::~Preprocessor() {
Argyrios Kyrtzidis5d240d02008-08-23 12:12:06 +000076 assert(BacktrackPositions.empty() && "EnableBacktrack/Backtrack imbalance!");
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +000077 assert(((MacroExpandingLexersStack.empty() && MacroExpandedTokens.empty()) ||
78 isCodeCompletionReached()) &&
Argyrios Kyrtzidis8cc04592011-06-29 22:20:11 +000079 "Preprocessor::HandleEndOfTokenLexer should have cleared those");
Argyrios Kyrtzidis5d240d02008-08-23 12:12:06 +000080
Chris Lattner69772b02006-07-02 20:34:39 +000081 while (!IncludeMacroStack.empty()) {
82 delete IncludeMacroStack.back().TheLexer;
Chris Lattner285c0c12008-03-09 02:26:03 +000083 delete IncludeMacroStack.back().TheTokenLexer;
Chris Lattner69772b02006-07-02 20:34:39 +000084 IncludeMacroStack.pop_back();
Chris Lattner22eb9722006-06-18 05:43:12 +000085 }
Chris Lattnerc43ddc82007-10-07 08:44:20 +000086
87 // Free any macro definitions.
Ted Kremenekb865f7e2010-10-19 21:30:11 +000088 for (MacroInfoChain *I = MIChainHead ; I ; I = I->Next)
Ted Kremenek1f1e4bd2010-10-19 18:16:54 +000089 I->MI.Destroy();
Mike Stump11289f42009-09-09 15:08:12 +000090
Chris Lattnerc02c4ab2007-07-15 00:25:26 +000091 // Free any cached macro expanders.
Chris Lattner285c0c12008-03-09 02:26:03 +000092 for (unsigned i = 0, e = NumCachedTokenLexers; i != e; ++i)
93 delete TokenLexerCache[i];
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +000094
Chris Lattnerd19564b2009-12-15 01:51:03 +000095 // Free any cached MacroArgs.
96 for (MacroArgs *ArgList = MacroArgCache; ArgList; )
97 ArgList = ArgList->deallocate();
Mike Stump11289f42009-09-09 15:08:12 +000098
Chris Lattnerb8761832006-06-24 21:31:03 +000099 // Release pragma information.
100 delete PragmaHandlers;
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000101
102 // Delete the scratch buffer info.
103 delete ScratchBuf;
Chris Lattner22192932008-03-14 06:07:05 +0000104
Daniel Dunbar0c6c9302009-11-11 21:44:21 +0000105 // Delete the header search info, if we own it.
106 if (OwnsHeaderSearch)
107 delete &HeaderInfo;
108
Chris Lattner22192932008-03-14 06:07:05 +0000109 delete Callbacks;
Chris Lattner22eb9722006-06-18 05:43:12 +0000110}
111
Douglas Gregor83297df2011-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
Douglas Gregor83297df2011-09-01 23:39:15 +0000147 // "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 Kremeneka5c2c272009-02-12 03:26:59 +0000176void Preprocessor::setPTHManager(PTHManager* pm) {
177 PTH.reset(pm);
Douglas Gregord2eb58a2009-10-16 18:18:30 +0000178 FileMgr.addStatCache(PTH->createStatCache());
Ted Kremeneka5c2c272009-02-12 03:26:59 +0000179}
180
Chris Lattner146762e2007-07-20 16:59:19 +0000181void Preprocessor::DumpToken(const Token &Tok, bool DumpFlags) const {
Benjamin Kramer89b422c2009-08-23 12:08:50 +0000182 llvm::errs() << tok::getTokenName(Tok.getKind()) << " '"
183 << getSpelling(Tok) << "'";
Mike Stump11289f42009-09-09 15:08:12 +0000184
Chris Lattnerd01e2912006-06-18 16:22:51 +0000185 if (!DumpFlags) return;
Mike Stump11289f42009-09-09 15:08:12 +0000186
Benjamin Kramer89b422c2009-08-23 12:08:50 +0000187 llvm::errs() << "\t";
Chris Lattnerd01e2912006-06-18 16:22:51 +0000188 if (Tok.isAtStartOfLine())
Benjamin Kramer89b422c2009-08-23 12:08:50 +0000189 llvm::errs() << " [StartOfLine]";
Chris Lattnerd01e2912006-06-18 16:22:51 +0000190 if (Tok.hasLeadingSpace())
Benjamin Kramer89b422c2009-08-23 12:08:50 +0000191 llvm::errs() << " [LeadingSpace]";
Chris Lattner6e4bf522006-07-27 06:59:25 +0000192 if (Tok.isExpandDisabled())
Benjamin Kramer89b422c2009-08-23 12:08:50 +0000193 llvm::errs() << " [ExpandDisabled]";
Chris Lattnerd01e2912006-06-18 16:22:51 +0000194 if (Tok.needsCleaning()) {
Chris Lattner50b497e2006-06-18 16:32:35 +0000195 const char *Start = SourceMgr.getCharacterData(Tok.getLocation());
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000196 llvm::errs() << " [UnClean='" << StringRef(Start, Tok.getLength())
Benjamin Kramer89b422c2009-08-23 12:08:50 +0000197 << "']";
Chris Lattnerd01e2912006-06-18 16:22:51 +0000198 }
Mike Stump11289f42009-09-09 15:08:12 +0000199
Benjamin Kramer89b422c2009-08-23 12:08:50 +0000200 llvm::errs() << "\tLoc=<";
Chris Lattner615315f2007-12-09 20:31:55 +0000201 DumpLocation(Tok.getLocation());
Benjamin Kramer89b422c2009-08-23 12:08:50 +0000202 llvm::errs() << ">";
Chris Lattner615315f2007-12-09 20:31:55 +0000203}
204
205void Preprocessor::DumpLocation(SourceLocation Loc) const {
Chris Lattnerf1ca7d32009-01-27 07:57:44 +0000206 Loc.dump(SourceMgr);
Chris Lattnerd01e2912006-06-18 16:22:51 +0000207}
208
209void Preprocessor::DumpMacro(const MacroInfo &MI) const {
Benjamin Kramer89b422c2009-08-23 12:08:50 +0000210 llvm::errs() << "MACRO: ";
Chris Lattnerd01e2912006-06-18 16:22:51 +0000211 for (unsigned i = 0, e = MI.getNumTokens(); i != e; ++i) {
212 DumpToken(MI.getReplacementToken(i));
Benjamin Kramer89b422c2009-08-23 12:08:50 +0000213 llvm::errs() << " ";
Chris Lattnerd01e2912006-06-18 16:22:51 +0000214 }
Benjamin Kramer89b422c2009-08-23 12:08:50 +0000215 llvm::errs() << "\n";
Chris Lattnerd01e2912006-06-18 16:22:51 +0000216}
217
Chris Lattner22eb9722006-06-18 05:43:12 +0000218void Preprocessor::PrintStats() {
Benjamin Kramer89b422c2009-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";
Chris Lattner22eb9722006-06-18 05:43:12 +0000231
Benjamin Kramer89b422c2009-08-23 12:08:50 +0000232 llvm::errs() << NumMacroExpanded << "/" << NumFnMacroExpanded << "/"
Ted Kremeneka0a3e9b2008-01-14 16:44:48 +0000233 << NumBuiltinMacroExpanded << " obj/fn/builtin macros expanded, "
234 << NumFastMacroExpanded << " on the fast path.\n";
Benjamin Kramer89b422c2009-08-23 12:08:50 +0000235 llvm::errs() << (NumFastTokenPaste+NumTokenPaste)
Ted Kremeneka0a3e9b2008-01-14 16:44:48 +0000236 << " token paste (##) operations performed, "
237 << NumFastTokenPaste << " on the fast path.\n";
Chris Lattner22eb9722006-06-18 05:43:12 +0000238}
239
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +0000240Preprocessor::macro_iterator
241Preprocessor::macro_begin(bool IncludeExternalMacros) const {
242 if (IncludeExternalMacros && ExternalSource &&
Douglas Gregor9882a5a2010-01-04 19:18:44 +0000243 !ReadMacrosFromExternalSource) {
244 ReadMacrosFromExternalSource = true;
245 ExternalSource->ReadDefinedMacros();
246 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +0000247
248 return Macros.begin();
Douglas Gregor9882a5a2010-01-04 19:18:44 +0000249}
250
Argyrios Kyrtzidise379ee32011-06-29 22:20:04 +0000251size_t Preprocessor::getTotalMemory() const {
Ted Kremenek182543a2011-07-26 21:17:24 +0000252 return BP.getTotalMemory()
Ted Kremenek8b77fe72011-07-27 18:41:23 +0000253 + llvm::capacity_in_bytes(MacroExpandedTokens)
Ted Kremenek182543a2011-07-26 21:17:24 +0000254 + Predefines.capacity() /* Predefines buffer. */
Ted Kremenek8b77fe72011-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 Kyrtzidise379ee32011-06-29 22:20:04 +0000259}
260
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +0000261Preprocessor::macro_iterator
262Preprocessor::macro_end(bool IncludeExternalMacros) const {
263 if (IncludeExternalMacros && ExternalSource &&
Douglas Gregor9882a5a2010-01-04 19:18:44 +0000264 !ReadMacrosFromExternalSource) {
265 ReadMacrosFromExternalSource = true;
266 ExternalSource->ReadDefinedMacros();
267 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +0000268
269 return Macros.end();
Douglas Gregor9882a5a2010-01-04 19:18:44 +0000270}
271
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +0000272bool Preprocessor::SetCodeCompletionPoint(const FileEntry *File,
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +0000273 unsigned CompleteLine,
274 unsigned CompleteColumn) {
275 assert(File);
276 assert(CompleteLine && CompleteColumn && "Starts from 1:1");
277 assert(!CodeCompletionFile && "Already set");
278
Douglas Gregor53ad6b92009-12-02 06:49:09 +0000279 using llvm::MemoryBuffer;
280
Douglas Gregor53ad6b92009-12-02 06:49:09 +0000281 // Load the actual file's contents.
Douglas Gregor26266da2010-03-16 19:49:24 +0000282 bool Invalid = false;
283 const MemoryBuffer *Buffer = SourceMgr.getMemoryBufferForFile(File, &Invalid);
284 if (Invalid)
Douglas Gregor53ad6b92009-12-02 06:49:09 +0000285 return true;
286
287 // Find the byte position of the truncation point.
288 const char *Position = Buffer->getBufferStart();
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +0000289 for (unsigned Line = 1; Line < CompleteLine; ++Line) {
Douglas Gregor53ad6b92009-12-02 06:49:09 +0000290 for (; *Position; ++Position) {
291 if (*Position != '\r' && *Position != '\n')
292 continue;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +0000293
Douglas Gregor53ad6b92009-12-02 06:49:09 +0000294 // Eat \r\n or \n\r as a single line.
295 if ((Position[1] == '\r' || Position[1] == '\n') &&
296 Position[0] != Position[1])
297 ++Position;
298 ++Position;
299 break;
300 }
301 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +0000302
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +0000303 Position += CompleteColumn - 1;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +0000304
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +0000305 // Insert '\0' at the code-completion point.
Douglas Gregor9291ab62009-12-08 21:45:46 +0000306 if (Position < Buffer->getBufferEnd()) {
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +0000307 CodeCompletionFile = File;
308 CodeCompletionOffset = Position - Buffer->getBufferStart();
309
310 MemoryBuffer *NewBuffer =
311 MemoryBuffer::getNewUninitMemBuffer(Buffer->getBufferSize() + 1,
312 Buffer->getBufferIdentifier());
Benjamin Kramer60053cf2011-09-04 20:26:28 +0000313 char *NewBuf = const_cast<char*>(NewBuffer->getBufferStart());
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +0000314 char *NewPos = std::copy(Buffer->getBufferStart(), Position, NewBuf);
315 *NewPos = '\0';
316 std::copy(Position, Buffer->getBufferEnd(), NewPos+1);
317 SourceMgr.overrideFileContents(File, NewBuffer);
Douglas Gregor53ad6b92009-12-02 06:49:09 +0000318 }
319
320 return false;
321}
322
Douglas Gregor11583702010-08-25 17:04:25 +0000323void Preprocessor::CodeCompleteNaturalLanguage() {
Douglas Gregor11583702010-08-25 17:04:25 +0000324 if (CodeComplete)
325 CodeComplete->CodeCompleteNaturalLanguage();
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +0000326 setCodeCompletionReached();
Douglas Gregor11583702010-08-25 17:04:25 +0000327}
328
Benjamin Kramera197fb62010-02-27 17:05:45 +0000329/// getSpelling - This method is used to get the spelling of a token into a
330/// SmallVector. Note that the returned StringRef may not point to the
331/// supplied buffer if a copy can be avoided.
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000332StringRef Preprocessor::getSpelling(const Token &Tok,
333 SmallVectorImpl<char> &Buffer,
Douglas Gregor7bda4b82010-03-16 05:20:39 +0000334 bool *Invalid) const {
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +0000335 // NOTE: this has to be checked *before* testing for an IdentifierInfo.
336 if (Tok.isNot(tok::raw_identifier)) {
337 // Try the fast path.
338 if (const IdentifierInfo *II = Tok.getIdentifierInfo())
339 return II->getName();
340 }
Benjamin Kramera197fb62010-02-27 17:05:45 +0000341
342 // Resize the buffer if we need to copy into it.
343 if (Tok.needsCleaning())
344 Buffer.resize(Tok.getLength());
345
346 const char *Ptr = Buffer.data();
Douglas Gregor7bda4b82010-03-16 05:20:39 +0000347 unsigned Len = getSpelling(Tok, Ptr, Invalid);
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000348 return StringRef(Ptr, Len);
Benjamin Kramera197fb62010-02-27 17:05:45 +0000349}
350
Chris Lattnerb94ec7b2006-07-14 06:54:10 +0000351/// CreateString - Plop the specified string into a scratch buffer and return a
352/// location for it. If specified, the source location provides a source
353/// location for the token.
Chris Lattner5a7971e2009-01-26 19:29:26 +0000354void Preprocessor::CreateString(const char *Buf, unsigned Len, Token &Tok,
Chandler Carrutha88a22182011-07-14 08:20:46 +0000355 SourceLocation ExpansionLoc) {
Chris Lattner5a7971e2009-01-26 19:29:26 +0000356 Tok.setLength(Len);
Mike Stump11289f42009-09-09 15:08:12 +0000357
Chris Lattner5a7971e2009-01-26 19:29:26 +0000358 const char *DestPtr;
359 SourceLocation Loc = ScratchBuf->getToken(Buf, Len, DestPtr);
Mike Stump11289f42009-09-09 15:08:12 +0000360
Chandler Carrutha88a22182011-07-14 08:20:46 +0000361 if (ExpansionLoc.isValid())
Chandler Carruth115b0772011-07-26 03:03:05 +0000362 Loc = SourceMgr.createExpansionLoc(Loc, ExpansionLoc, ExpansionLoc, Len);
Chris Lattner5a7971e2009-01-26 19:29:26 +0000363 Tok.setLocation(Loc);
Mike Stump11289f42009-09-09 15:08:12 +0000364
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +0000365 // If this is a raw identifier or a literal token, set the pointer data.
366 if (Tok.is(tok::raw_identifier))
367 Tok.setRawIdentifierData(DestPtr);
368 else if (Tok.isLiteral())
Chris Lattner5a7971e2009-01-26 19:29:26 +0000369 Tok.setLiteralData(DestPtr);
Chris Lattnerb94ec7b2006-07-14 06:54:10 +0000370}
371
372
Chris Lattner8a7003c2007-07-16 06:48:38 +0000373
Chris Lattner1f1b0db2007-10-09 22:10:18 +0000374//===----------------------------------------------------------------------===//
375// Preprocessor Initialization Methods
376//===----------------------------------------------------------------------===//
377
Chris Lattner1f1b0db2007-10-09 22:10:18 +0000378
379/// EnterMainSourceFile - Enter the specified FileID as the main source file,
Nate Begemanf7c3ff62008-01-07 04:01:26 +0000380/// which implicitly adds the builtin defines etc.
Chris Lattnerfb24a3a2010-04-20 20:35:58 +0000381void Preprocessor::EnterMainSourceFile() {
Chris Lattner9ef847b2009-02-13 19:33:24 +0000382 // We do not allow the preprocessor to reenter the main file. Doing so will
383 // cause FileID's to accumulate information from both runs (e.g. #line
384 // information) and predefined macros aren't guaranteed to be set properly.
385 assert(NumEnteredSourceFiles == 0 && "Cannot reenter the main file!");
Chris Lattnerd32480d2009-01-17 06:22:33 +0000386 FileID MainFileID = SourceMgr.getMainFileID();
Mike Stump11289f42009-09-09 15:08:12 +0000387
Chris Lattner1f1b0db2007-10-09 22:10:18 +0000388 // Enter the main file source buffer.
Chris Lattnerfb24a3a2010-04-20 20:35:58 +0000389 EnterSourceFile(MainFileID, 0, SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +0000390
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000391 // If we've been asked to skip bytes in the main file (e.g., as part of a
392 // precompiled preamble), do so now.
393 if (SkipMainFilePreamble.first > 0)
394 CurLexer->SkipBytes(SkipMainFilePreamble.first,
395 SkipMainFilePreamble.second);
396
Chris Lattner609d4132007-11-15 19:07:47 +0000397 // Tell the header info that the main file was entered. If the file is later
398 // #imported, it won't be re-entered.
Chris Lattnerd32480d2009-01-17 06:22:33 +0000399 if (const FileEntry *FE = SourceMgr.getFileEntryForID(MainFileID))
Chris Lattner609d4132007-11-15 19:07:47 +0000400 HeaderInfo.IncrementIncludeCount(FE);
Mike Stump11289f42009-09-09 15:08:12 +0000401
Benjamin Kramerd77adb52009-12-31 15:33:09 +0000402 // Preprocess Predefines to populate the initial preprocessor state.
Mike Stump11289f42009-09-09 15:08:12 +0000403 llvm::MemoryBuffer *SB =
Chris Lattner58c79342010-04-05 22:42:27 +0000404 llvm::MemoryBuffer::getMemBufferCopy(Predefines, "<built-in>");
Douglas Gregor33551892010-08-26 14:07:34 +0000405 assert(SB && "Cannot create predefined source buffer");
Chris Lattnerd32480d2009-01-17 06:22:33 +0000406 FileID FID = SourceMgr.createFileIDForMemBuffer(SB);
407 assert(!FID.isInvalid() && "Could not create FileID for predefines?");
Mike Stump11289f42009-09-09 15:08:12 +0000408
Chris Lattner1f1b0db2007-10-09 22:10:18 +0000409 // Start parsing the predefines.
Chris Lattnerfb24a3a2010-04-20 20:35:58 +0000410 EnterSourceFile(FID, 0, SourceLocation());
Chris Lattner1f1b0db2007-10-09 22:10:18 +0000411}
Chris Lattner8a7003c2007-07-16 06:48:38 +0000412
Daniel Dunbarcb9eaf52010-03-23 05:09:10 +0000413void Preprocessor::EndSourceFile() {
414 // Notify the client that we reached the end of the source file.
415 if (Callbacks)
416 Callbacks->EndOfMainFile();
417}
Chris Lattner677757a2006-06-28 05:26:32 +0000418
419//===----------------------------------------------------------------------===//
420// Lexer Event Handling.
421//===----------------------------------------------------------------------===//
422
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +0000423/// LookUpIdentifierInfo - Given a tok::raw_identifier token, look up the
424/// identifier information for the token and install it into the token,
425/// updating the token kind accordingly.
426IdentifierInfo *Preprocessor::LookUpIdentifierInfo(Token &Identifier) const {
427 assert(Identifier.getRawIdentifierData() != 0 && "No raw identifier data!");
Mike Stump11289f42009-09-09 15:08:12 +0000428
Chris Lattnercefc7682006-07-08 08:28:12 +0000429 // Look up this token, see if it is a macro, or if it is a language keyword.
430 IdentifierInfo *II;
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +0000431 if (!Identifier.needsCleaning()) {
Chris Lattnercefc7682006-07-08 08:28:12 +0000432 // No cleaning needed, just use the characters from the lexed buffer.
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000433 II = getIdentifierInfo(StringRef(Identifier.getRawIdentifierData(),
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +0000434 Identifier.getLength()));
Chris Lattnercefc7682006-07-08 08:28:12 +0000435 } else {
436 // Cleaning needed, alloca a buffer, clean into it, then use the buffer.
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +0000437 llvm::SmallString<64> IdentifierBuffer;
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000438 StringRef CleanedStr = getSpelling(Identifier, IdentifierBuffer);
Benjamin Kramer0a1abd42010-02-27 13:44:12 +0000439 II = getIdentifierInfo(CleanedStr);
Chris Lattnercefc7682006-07-08 08:28:12 +0000440 }
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +0000441
442 // Update the token info (identifier info and appropriate token kind).
Chris Lattner8c204872006-10-14 05:19:21 +0000443 Identifier.setIdentifierInfo(II);
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +0000444 Identifier.setKind(II->getTokenID());
445
Chris Lattnercefc7682006-07-08 08:28:12 +0000446 return II;
447}
448
John Wiegley1c0675e2011-04-28 01:08:34 +0000449void Preprocessor::SetPoisonReason(IdentifierInfo *II, unsigned DiagID) {
450 PoisonReasons[II] = DiagID;
451}
452
453void Preprocessor::PoisonSEHIdentifiers(bool Poison) {
454 assert(Ident__exception_code && Ident__exception_info);
455 assert(Ident___exception_code && Ident___exception_info);
456 Ident__exception_code->setIsPoisoned(Poison);
457 Ident___exception_code->setIsPoisoned(Poison);
458 Ident_GetExceptionCode->setIsPoisoned(Poison);
459 Ident__exception_info->setIsPoisoned(Poison);
460 Ident___exception_info->setIsPoisoned(Poison);
461 Ident_GetExceptionInfo->setIsPoisoned(Poison);
462 Ident__abnormal_termination->setIsPoisoned(Poison);
463 Ident___abnormal_termination->setIsPoisoned(Poison);
464 Ident_AbnormalTermination->setIsPoisoned(Poison);
465}
466
467void Preprocessor::HandlePoisonedIdentifier(Token & Identifier) {
468 assert(Identifier.getIdentifierInfo() &&
469 "Can't handle identifiers without identifier info!");
470 llvm::DenseMap<IdentifierInfo*,unsigned>::const_iterator it =
471 PoisonReasons.find(Identifier.getIdentifierInfo());
472 if(it == PoisonReasons.end())
473 Diag(Identifier, diag::err_pp_used_poisoned_id);
474 else
475 Diag(Identifier,it->second) << Identifier.getIdentifierInfo();
476}
Chris Lattnercefc7682006-07-08 08:28:12 +0000477
Chris Lattner677757a2006-06-28 05:26:32 +0000478/// HandleIdentifier - This callback is invoked when the lexer reads an
479/// identifier. This callback looks up the identifier in the map and/or
480/// potentially macro expands it or turns it into a named token (like 'for').
Chris Lattnerad89ec02009-01-21 07:43:11 +0000481///
482/// Note that callers of this method are guarded by checking the
483/// IdentifierInfo's 'isHandleIdentifierCase' bit. If this method changes, the
484/// IdentifierInfo methods that compute these properties will need to change to
485/// match.
Chris Lattner146762e2007-07-20 16:59:19 +0000486void Preprocessor::HandleIdentifier(Token &Identifier) {
Chris Lattner0f1f5052006-07-20 04:16:23 +0000487 assert(Identifier.getIdentifierInfo() &&
488 "Can't handle identifiers without identifier info!");
Mike Stump11289f42009-09-09 15:08:12 +0000489
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000490 IdentifierInfo &II = *Identifier.getIdentifierInfo();
Chris Lattner677757a2006-06-28 05:26:32 +0000491
492 // If this identifier was poisoned, and if it was not produced from a macro
493 // expansion, emit an error.
Ted Kremeneka2c3c8d2008-11-19 22:43:49 +0000494 if (II.isPoisoned() && CurPPLexer) {
John Wiegley1c0675e2011-04-28 01:08:34 +0000495 HandlePoisonedIdentifier(Identifier);
Chris Lattner8ff71992006-07-06 05:17:39 +0000496 }
Mike Stump11289f42009-09-09 15:08:12 +0000497
Chris Lattner78186052006-07-09 00:45:31 +0000498 // If this is a macro to be expanded, do it.
Chris Lattnerc43ddc82007-10-07 08:44:20 +0000499 if (MacroInfo *MI = getMacroInfo(&II)) {
Chris Lattner6e4bf522006-07-27 06:59:25 +0000500 if (!DisableMacroExpansion && !Identifier.isExpandDisabled()) {
501 if (MI->isEnabled()) {
502 if (!HandleMacroExpandedIdentifier(Identifier, MI))
Douglas Gregord90c3c92011-08-27 06:37:51 +0000503 return;
Chris Lattner6e4bf522006-07-27 06:59:25 +0000504 } else {
505 // C99 6.10.3.4p2 says that a disabled macro may never again be
506 // expanded, even if it's in a context where it could be expanded in the
507 // future.
Chris Lattner146762e2007-07-20 16:59:19 +0000508 Identifier.setFlag(Token::DisableExpand);
Chris Lattner6e4bf522006-07-27 06:59:25 +0000509 }
510 }
Chris Lattner063400e2006-10-14 19:54:15 +0000511 }
Chris Lattner677757a2006-06-28 05:26:32 +0000512
Chris Lattner5b9f4892006-11-21 17:23:33 +0000513 // C++ 2.11p2: If this is an alternative representation of a C++ operator,
514 // then we act as if it is the actual operator and not the textual
515 // representation of it.
Fariborz Jahanian9e42a952010-09-03 17:33:04 +0000516 if (II.isCPlusPlusOperatorKeyword())
Chris Lattner5b9f4892006-11-21 17:23:33 +0000517 Identifier.setIdentifierInfo(0);
518
Chris Lattner677757a2006-06-28 05:26:32 +0000519 // If this is an extension token, diagnose its use.
Steve Naroffc84e8b72008-09-02 18:50:17 +0000520 // We avoid diagnosing tokens that originate from macro definitions.
Eli Friedman6bba2ad2009-04-28 03:59:15 +0000521 // FIXME: This warning is disabled in cases where it shouldn't be,
522 // like "#define TY typeof", "TY(1) x".
523 if (II.isExtensionToken() && !DisableMacroExpansion)
Chris Lattner53621a52007-06-13 20:44:40 +0000524 Diag(Identifier, diag::ext_token_used);
Douglas Gregoraf5c4842011-09-07 23:11:54 +0000525
526 // If this is the '__import_module__' keyword, note that the next token
527 // indicates a module name.
528 if (II.getTokenID() == tok::kw___import_module__ &&
529 !InMacroArgs && !DisableMacroExpansion) {
530 ModuleImportLoc = Identifier.getLocation();
531 CurLexerKind = CLK_LexAfterModuleImport;
532 }
Douglas Gregor08142532011-08-26 23:56:07 +0000533}
534
Douglas Gregoraf5c4842011-09-07 23:11:54 +0000535/// \brief Lex a token following the __import_module__ keyword.
536void Preprocessor::LexAfterModuleImport(Token &Result) {
537 // Figure out what kind of lexer we actually have.
538 if (CurLexer)
539 CurLexerKind = CLK_Lexer;
540 else if (CurPTHLexer)
541 CurLexerKind = CLK_PTHLexer;
542 else if (CurTokenLexer)
543 CurLexerKind = CLK_TokenLexer;
544 else
545 CurLexerKind = CLK_CachingLexer;
546
547 // Lex the next token.
548 Lex(Result);
549
Douglas Gregor08142532011-08-26 23:56:07 +0000550 // The token sequence
551 //
Douglas Gregorca975892011-08-31 18:19:09 +0000552 // __import_module__ identifier
Douglas Gregor08142532011-08-26 23:56:07 +0000553 //
Douglas Gregoraf5c4842011-09-07 23:11:54 +0000554 // indicates a module import directive. We already saw the __import_module__
555 // keyword, so now we're looking for the identifier.
556 if (Result.getKind() != tok::identifier)
Douglas Gregor08142532011-08-26 23:56:07 +0000557 return;
558
Douglas Gregoraf5c4842011-09-07 23:11:54 +0000559 // Load the module.
560 (void)TheModuleLoader.loadModule(ModuleImportLoc,
561 *Result.getIdentifierInfo(),
562 Result.getLocation());
Chris Lattner677757a2006-06-28 05:26:32 +0000563}
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000564
565void Preprocessor::AddCommentHandler(CommentHandler *Handler) {
566 assert(Handler && "NULL comment handler");
567 assert(std::find(CommentHandlers.begin(), CommentHandlers.end(), Handler) ==
568 CommentHandlers.end() && "Comment handler already registered");
569 CommentHandlers.push_back(Handler);
570}
571
572void Preprocessor::RemoveCommentHandler(CommentHandler *Handler) {
573 std::vector<CommentHandler *>::iterator Pos
574 = std::find(CommentHandlers.begin(), CommentHandlers.end(), Handler);
575 assert(Pos != CommentHandlers.end() && "Comment handler not registered");
576 CommentHandlers.erase(Pos);
577}
578
Chris Lattner87d02082010-01-18 22:35:47 +0000579bool Preprocessor::HandleComment(Token &result, SourceRange Comment) {
580 bool AnyPendingTokens = false;
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000581 for (std::vector<CommentHandler *>::iterator H = CommentHandlers.begin(),
582 HEnd = CommentHandlers.end();
Chris Lattner87d02082010-01-18 22:35:47 +0000583 H != HEnd; ++H) {
584 if ((*H)->HandleComment(*this, Comment))
585 AnyPendingTokens = true;
586 }
587 if (!AnyPendingTokens || getCommentRetentionState())
588 return false;
589 Lex(result);
590 return true;
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000591}
592
Douglas Gregor08142532011-08-26 23:56:07 +0000593ModuleLoader::~ModuleLoader() { }
594
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000595CommentHandler::~CommentHandler() { }
Douglas Gregor7f6d60d2010-03-19 16:15:56 +0000596
Douglas Gregor3a7ad252010-08-24 19:08:16 +0000597CodeCompletionHandler::~CodeCompletionHandler() { }
598
Douglas Gregor998caea2011-05-06 16:33:08 +0000599void Preprocessor::createPreprocessingRecord(
Chandler Carrutha88a22182011-07-14 08:20:46 +0000600 bool IncludeNestedMacroExpansions) {
Douglas Gregor7f6d60d2010-03-19 16:15:56 +0000601 if (Record)
602 return;
603
Chandler Carrutha88a22182011-07-14 08:20:46 +0000604 Record = new PreprocessingRecord(IncludeNestedMacroExpansions);
Douglas Gregor7dc87222010-03-19 17:12:43 +0000605 addPPCallbacks(Record);
Douglas Gregor7f6d60d2010-03-19 16:15:56 +0000606}