blob: dea7efc7658fecfa8e9b4a8e9aac469920458cbd [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
David Blaikied6471f72011-09-25 23:23:43 +000052Preprocessor::Preprocessor(DiagnosticsEngine &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),
Zhongxing Xu7e7b5032011-09-26 03:37:43 +000064 CurDirLookup(0), CurLexerKind(CLK_Lexer), Callbacks(0), MacroArgCache(0),
65 Record(0), MIChainHead(0), MICache(0)
Douglas Gregor998b3d32011-09-01 23:39:15 +000066{
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!");
77
Reid Spencer5f016e22007-07-11 17:01:13 +000078 while (!IncludeMacroStack.empty()) {
79 delete IncludeMacroStack.back().TheLexer;
Chris Lattner6cfe7592008-03-09 02:26:03 +000080 delete IncludeMacroStack.back().TheTokenLexer;
Reid Spencer5f016e22007-07-11 17:01:13 +000081 IncludeMacroStack.pop_back();
82 }
Chris Lattnercc1a8752007-10-07 08:44:20 +000083
84 // Free any macro definitions.
Ted Kremenek2a6b03a2010-10-19 21:30:11 +000085 for (MacroInfoChain *I = MIChainHead ; I ; I = I->Next)
Ted Kremenekaf8fa252010-10-19 18:16:54 +000086 I->MI.Destroy();
Mike Stump1eb44332009-09-09 15:08:12 +000087
Chris Lattner9594acf2007-07-15 00:25:26 +000088 // Free any cached macro expanders.
Chris Lattner6cfe7592008-03-09 02:26:03 +000089 for (unsigned i = 0, e = NumCachedTokenLexers; i != e; ++i)
90 delete TokenLexerCache[i];
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +000091
Chris Lattner23f77e52009-12-15 01:51:03 +000092 // Free any cached MacroArgs.
93 for (MacroArgs *ArgList = MacroArgCache; ArgList; )
94 ArgList = ArgList->deallocate();
Mike Stump1eb44332009-09-09 15:08:12 +000095
Reid Spencer5f016e22007-07-11 17:01:13 +000096 // Release pragma information.
97 delete PragmaHandlers;
98
99 // Delete the scratch buffer info.
100 delete ScratchBuf;
Chris Lattnereb50ed82008-03-14 06:07:05 +0000101
Daniel Dunbar5814e652009-11-11 21:44:21 +0000102 // Delete the header search info, if we own it.
103 if (OwnsHeaderSearch)
104 delete &HeaderInfo;
105
Chris Lattnereb50ed82008-03-14 06:07:05 +0000106 delete Callbacks;
Reid Spencer5f016e22007-07-11 17:01:13 +0000107}
108
Douglas Gregor998b3d32011-09-01 23:39:15 +0000109void Preprocessor::Initialize(const TargetInfo &Target) {
110 assert((!this->Target || this->Target == &Target) &&
111 "Invalid override of target information");
112 this->Target = &Target;
113
114 // Initialize information about built-ins.
115 BuiltinInfo.InitializeTarget(Target);
116
117 ScratchBuf = new ScratchBuffer(SourceMgr);
118 CounterValue = 0; // __COUNTER__ starts at 0.
119
120 // Clear stats.
121 NumDirectives = NumDefined = NumUndefined = NumPragma = 0;
122 NumIf = NumElse = NumEndif = 0;
123 NumEnteredSourceFiles = 0;
124 NumMacroExpanded = NumFnMacroExpanded = NumBuiltinMacroExpanded = 0;
125 NumFastMacroExpanded = NumTokenPaste = NumFastTokenPaste = 0;
126 MaxIncludeStackDepth = 0;
127 NumSkipped = 0;
128
129 // Default to discarding comments.
130 KeepComments = false;
131 KeepMacroComments = false;
132 SuppressIncludeNotFoundError = false;
Douglas Gregorfba18aa2011-09-15 22:00:41 +0000133 AutoModuleImport = false;
Douglas Gregor998b3d32011-09-01 23:39:15 +0000134
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
Douglas Gregor998b3d32011-09-01 23:39:15 +0000145 // "Poison" __VA_ARGS__, which can only appear in the expansion of a macro.
146 // This gets unpoisoned where it is allowed.
147 (Ident__VA_ARGS__ = getIdentifierInfo("__VA_ARGS__"))->setIsPoisoned();
148 SetPoisonReason(Ident__VA_ARGS__,diag::ext_pp_bad_vaargs_use);
149
150 // Initialize the pragma handlers.
151 PragmaHandlers = new PragmaNamespace(StringRef());
152 RegisterBuiltinPragmas();
153
154 // Initialize builtin macros like __LINE__ and friends.
155 RegisterBuiltinMacros();
156
157 if(Features.Borland) {
158 Ident__exception_info = getIdentifierInfo("_exception_info");
159 Ident___exception_info = getIdentifierInfo("__exception_info");
160 Ident_GetExceptionInfo = getIdentifierInfo("GetExceptionInformation");
161 Ident__exception_code = getIdentifierInfo("_exception_code");
162 Ident___exception_code = getIdentifierInfo("__exception_code");
163 Ident_GetExceptionCode = getIdentifierInfo("GetExceptionCode");
164 Ident__abnormal_termination = getIdentifierInfo("_abnormal_termination");
165 Ident___abnormal_termination = getIdentifierInfo("__abnormal_termination");
166 Ident_AbnormalTermination = getIdentifierInfo("AbnormalTermination");
167 } else {
168 Ident__exception_info = Ident__exception_code = Ident__abnormal_termination = 0;
169 Ident___exception_info = Ident___exception_code = Ident___abnormal_termination = 0;
170 Ident_GetExceptionInfo = Ident_GetExceptionCode = Ident_AbnormalTermination = 0;
171 }
172}
173
Ted Kremenek337edcd2009-02-12 03:26:59 +0000174void Preprocessor::setPTHManager(PTHManager* pm) {
175 PTH.reset(pm);
Douglas Gregor52e71082009-10-16 18:18:30 +0000176 FileMgr.addStatCache(PTH->createStatCache());
Ted Kremenek337edcd2009-02-12 03:26:59 +0000177}
178
Chris Lattnerd2177732007-07-20 16:59:19 +0000179void Preprocessor::DumpToken(const Token &Tok, bool DumpFlags) const {
Benjamin Kramer6cb7c1a2009-08-23 12:08:50 +0000180 llvm::errs() << tok::getTokenName(Tok.getKind()) << " '"
181 << getSpelling(Tok) << "'";
Mike Stump1eb44332009-09-09 15:08:12 +0000182
Reid Spencer5f016e22007-07-11 17:01:13 +0000183 if (!DumpFlags) return;
Mike Stump1eb44332009-09-09 15:08:12 +0000184
Benjamin Kramer6cb7c1a2009-08-23 12:08:50 +0000185 llvm::errs() << "\t";
Reid Spencer5f016e22007-07-11 17:01:13 +0000186 if (Tok.isAtStartOfLine())
Benjamin Kramer6cb7c1a2009-08-23 12:08:50 +0000187 llvm::errs() << " [StartOfLine]";
Reid Spencer5f016e22007-07-11 17:01:13 +0000188 if (Tok.hasLeadingSpace())
Benjamin Kramer6cb7c1a2009-08-23 12:08:50 +0000189 llvm::errs() << " [LeadingSpace]";
Reid Spencer5f016e22007-07-11 17:01:13 +0000190 if (Tok.isExpandDisabled())
Benjamin Kramer6cb7c1a2009-08-23 12:08:50 +0000191 llvm::errs() << " [ExpandDisabled]";
Reid Spencer5f016e22007-07-11 17:01:13 +0000192 if (Tok.needsCleaning()) {
193 const char *Start = SourceMgr.getCharacterData(Tok.getLocation());
Chris Lattner5f9e2722011-07-23 10:55:15 +0000194 llvm::errs() << " [UnClean='" << StringRef(Start, Tok.getLength())
Benjamin Kramer6cb7c1a2009-08-23 12:08:50 +0000195 << "']";
Reid Spencer5f016e22007-07-11 17:01:13 +0000196 }
Mike Stump1eb44332009-09-09 15:08:12 +0000197
Benjamin Kramer6cb7c1a2009-08-23 12:08:50 +0000198 llvm::errs() << "\tLoc=<";
Chris Lattnerc3d8d572007-12-09 20:31:55 +0000199 DumpLocation(Tok.getLocation());
Benjamin Kramer6cb7c1a2009-08-23 12:08:50 +0000200 llvm::errs() << ">";
Chris Lattnerc3d8d572007-12-09 20:31:55 +0000201}
202
203void Preprocessor::DumpLocation(SourceLocation Loc) const {
Chris Lattnerb9c3f962009-01-27 07:57:44 +0000204 Loc.dump(SourceMgr);
Reid Spencer5f016e22007-07-11 17:01:13 +0000205}
206
207void Preprocessor::DumpMacro(const MacroInfo &MI) const {
Benjamin Kramer6cb7c1a2009-08-23 12:08:50 +0000208 llvm::errs() << "MACRO: ";
Reid Spencer5f016e22007-07-11 17:01:13 +0000209 for (unsigned i = 0, e = MI.getNumTokens(); i != e; ++i) {
210 DumpToken(MI.getReplacementToken(i));
Benjamin Kramer6cb7c1a2009-08-23 12:08:50 +0000211 llvm::errs() << " ";
Reid Spencer5f016e22007-07-11 17:01:13 +0000212 }
Benjamin Kramer6cb7c1a2009-08-23 12:08:50 +0000213 llvm::errs() << "\n";
Reid Spencer5f016e22007-07-11 17:01:13 +0000214}
215
216void Preprocessor::PrintStats() {
Benjamin Kramer6cb7c1a2009-08-23 12:08:50 +0000217 llvm::errs() << "\n*** Preprocessor Stats:\n";
218 llvm::errs() << NumDirectives << " directives found:\n";
219 llvm::errs() << " " << NumDefined << " #define.\n";
220 llvm::errs() << " " << NumUndefined << " #undef.\n";
221 llvm::errs() << " #include/#include_next/#import:\n";
222 llvm::errs() << " " << NumEnteredSourceFiles << " source files entered.\n";
223 llvm::errs() << " " << MaxIncludeStackDepth << " max include stack depth\n";
224 llvm::errs() << " " << NumIf << " #if/#ifndef/#ifdef.\n";
225 llvm::errs() << " " << NumElse << " #else/#elif.\n";
226 llvm::errs() << " " << NumEndif << " #endif.\n";
227 llvm::errs() << " " << NumPragma << " #pragma.\n";
228 llvm::errs() << NumSkipped << " #if/#ifndef#ifdef regions skipped\n";
Reid Spencer5f016e22007-07-11 17:01:13 +0000229
Benjamin Kramer6cb7c1a2009-08-23 12:08:50 +0000230 llvm::errs() << NumMacroExpanded << "/" << NumFnMacroExpanded << "/"
Ted Kremenekbdd30c22008-01-14 16:44:48 +0000231 << NumBuiltinMacroExpanded << " obj/fn/builtin macros expanded, "
232 << NumFastMacroExpanded << " on the fast path.\n";
Benjamin Kramer6cb7c1a2009-08-23 12:08:50 +0000233 llvm::errs() << (NumFastTokenPaste+NumTokenPaste)
Ted Kremenekbdd30c22008-01-14 16:44:48 +0000234 << " token paste (##) operations performed, "
235 << NumFastTokenPaste << " on the fast path.\n";
Reid Spencer5f016e22007-07-11 17:01:13 +0000236}
237
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +0000238Preprocessor::macro_iterator
239Preprocessor::macro_begin(bool IncludeExternalMacros) const {
240 if (IncludeExternalMacros && ExternalSource &&
Douglas Gregor88a35862010-01-04 19:18:44 +0000241 !ReadMacrosFromExternalSource) {
242 ReadMacrosFromExternalSource = true;
243 ExternalSource->ReadDefinedMacros();
244 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +0000245
246 return Macros.begin();
Douglas Gregor88a35862010-01-04 19:18:44 +0000247}
248
Argyrios Kyrtzidisc5c5e922011-06-29 22:20:04 +0000249size_t Preprocessor::getTotalMemory() const {
Ted Kremenek91d1bd62011-07-26 21:17:24 +0000250 return BP.getTotalMemory()
Ted Kremenek67485092011-07-27 18:41:23 +0000251 + llvm::capacity_in_bytes(MacroExpandedTokens)
Ted Kremenek91d1bd62011-07-26 21:17:24 +0000252 + Predefines.capacity() /* Predefines buffer. */
Ted Kremenek67485092011-07-27 18:41:23 +0000253 + llvm::capacity_in_bytes(Macros)
254 + llvm::capacity_in_bytes(PragmaPushMacroInfo)
255 + llvm::capacity_in_bytes(PoisonReasons)
256 + llvm::capacity_in_bytes(CommentHandlers);
Argyrios Kyrtzidisc5c5e922011-06-29 22:20:04 +0000257}
258
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +0000259Preprocessor::macro_iterator
260Preprocessor::macro_end(bool IncludeExternalMacros) const {
261 if (IncludeExternalMacros && ExternalSource &&
Douglas Gregor88a35862010-01-04 19:18:44 +0000262 !ReadMacrosFromExternalSource) {
263 ReadMacrosFromExternalSource = true;
264 ExternalSource->ReadDefinedMacros();
265 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +0000266
267 return Macros.end();
Douglas Gregor88a35862010-01-04 19:18:44 +0000268}
269
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +0000270bool Preprocessor::SetCodeCompletionPoint(const FileEntry *File,
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +0000271 unsigned CompleteLine,
272 unsigned CompleteColumn) {
273 assert(File);
274 assert(CompleteLine && CompleteColumn && "Starts from 1:1");
275 assert(!CodeCompletionFile && "Already set");
276
Douglas Gregor29684422009-12-02 06:49:09 +0000277 using llvm::MemoryBuffer;
278
Douglas Gregor29684422009-12-02 06:49:09 +0000279 // Load the actual file's contents.
Douglas Gregoraa38c3d2010-03-16 19:49:24 +0000280 bool Invalid = false;
281 const MemoryBuffer *Buffer = SourceMgr.getMemoryBufferForFile(File, &Invalid);
282 if (Invalid)
Douglas Gregor29684422009-12-02 06:49:09 +0000283 return true;
284
285 // Find the byte position of the truncation point.
286 const char *Position = Buffer->getBufferStart();
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +0000287 for (unsigned Line = 1; Line < CompleteLine; ++Line) {
Douglas Gregor29684422009-12-02 06:49:09 +0000288 for (; *Position; ++Position) {
289 if (*Position != '\r' && *Position != '\n')
290 continue;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +0000291
Douglas Gregor29684422009-12-02 06:49:09 +0000292 // Eat \r\n or \n\r as a single line.
293 if ((Position[1] == '\r' || Position[1] == '\n') &&
294 Position[0] != Position[1])
295 ++Position;
296 ++Position;
297 break;
298 }
299 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +0000300
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +0000301 Position += CompleteColumn - 1;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +0000302
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +0000303 // Insert '\0' at the code-completion point.
Douglas Gregorb760fe82009-12-08 21:45:46 +0000304 if (Position < Buffer->getBufferEnd()) {
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +0000305 CodeCompletionFile = File;
306 CodeCompletionOffset = Position - Buffer->getBufferStart();
307
308 MemoryBuffer *NewBuffer =
309 MemoryBuffer::getNewUninitMemBuffer(Buffer->getBufferSize() + 1,
310 Buffer->getBufferIdentifier());
Benjamin Kramer41a50a92011-09-04 20:26:28 +0000311 char *NewBuf = const_cast<char*>(NewBuffer->getBufferStart());
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +0000312 char *NewPos = std::copy(Buffer->getBufferStart(), Position, NewBuf);
313 *NewPos = '\0';
314 std::copy(Position, Buffer->getBufferEnd(), NewPos+1);
315 SourceMgr.overrideFileContents(File, NewBuffer);
Douglas Gregor29684422009-12-02 06:49:09 +0000316 }
317
318 return false;
319}
320
Douglas Gregor55817af2010-08-25 17:04:25 +0000321void Preprocessor::CodeCompleteNaturalLanguage() {
Douglas Gregor55817af2010-08-25 17:04:25 +0000322 if (CodeComplete)
323 CodeComplete->CodeCompleteNaturalLanguage();
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +0000324 setCodeCompletionReached();
Douglas Gregor55817af2010-08-25 17:04:25 +0000325}
326
Benjamin Kramer51f5fe32010-02-27 17:05:45 +0000327/// getSpelling - This method is used to get the spelling of a token into a
328/// SmallVector. Note that the returned StringRef may not point to the
329/// supplied buffer if a copy can be avoided.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000330StringRef Preprocessor::getSpelling(const Token &Tok,
331 SmallVectorImpl<char> &Buffer,
Douglas Gregor50f6af72010-03-16 05:20:39 +0000332 bool *Invalid) const {
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +0000333 // NOTE: this has to be checked *before* testing for an IdentifierInfo.
334 if (Tok.isNot(tok::raw_identifier)) {
335 // Try the fast path.
336 if (const IdentifierInfo *II = Tok.getIdentifierInfo())
337 return II->getName();
338 }
Benjamin Kramer51f5fe32010-02-27 17:05:45 +0000339
340 // Resize the buffer if we need to copy into it.
341 if (Tok.needsCleaning())
342 Buffer.resize(Tok.getLength());
343
344 const char *Ptr = Buffer.data();
Douglas Gregor50f6af72010-03-16 05:20:39 +0000345 unsigned Len = getSpelling(Tok, Ptr, Invalid);
Chris Lattner5f9e2722011-07-23 10:55:15 +0000346 return StringRef(Ptr, Len);
Benjamin Kramer51f5fe32010-02-27 17:05:45 +0000347}
348
Reid Spencer5f016e22007-07-11 17:01:13 +0000349/// CreateString - Plop the specified string into a scratch buffer and return a
350/// location for it. If specified, the source location provides a source
351/// location for the token.
Chris Lattner47246be2009-01-26 19:29:26 +0000352void Preprocessor::CreateString(const char *Buf, unsigned Len, Token &Tok,
Abramo Bagnaraa08529c2011-10-03 18:39:03 +0000353 SourceLocation ExpansionLocStart,
354 SourceLocation ExpansionLocEnd) {
Chris Lattner47246be2009-01-26 19:29:26 +0000355 Tok.setLength(Len);
Mike Stump1eb44332009-09-09 15:08:12 +0000356
Chris Lattner47246be2009-01-26 19:29:26 +0000357 const char *DestPtr;
358 SourceLocation Loc = ScratchBuf->getToken(Buf, Len, DestPtr);
Mike Stump1eb44332009-09-09 15:08:12 +0000359
Abramo Bagnaraa08529c2011-10-03 18:39:03 +0000360 if (ExpansionLocStart.isValid())
361 Loc = SourceMgr.createExpansionLoc(Loc, ExpansionLocStart,
362 ExpansionLocEnd, Len);
Chris Lattner47246be2009-01-26 19:29:26 +0000363 Tok.setLocation(Loc);
Mike Stump1eb44332009-09-09 15:08:12 +0000364
Abramo Bagnarac4bf2b92010-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 Lattner47246be2009-01-26 19:29:26 +0000369 Tok.setLiteralData(DestPtr);
Reid Spencer5f016e22007-07-11 17:01:13 +0000370}
371
Douglas Gregor90db2602011-12-02 01:47:07 +0000372Module *Preprocessor::getCurrentModule() {
373 if (getLangOptions().CurrentModule.empty())
374 return 0;
375
376 return getHeaderSearchInfo().getModule(getLangOptions().CurrentModule);
377}
Chris Lattner97ba77c2007-07-16 06:48:38 +0000378
Chris Lattner53b0dab2007-10-09 22:10:18 +0000379//===----------------------------------------------------------------------===//
380// Preprocessor Initialization Methods
381//===----------------------------------------------------------------------===//
382
Chris Lattner53b0dab2007-10-09 22:10:18 +0000383
384/// EnterMainSourceFile - Enter the specified FileID as the main source file,
Nate Begeman6b616022008-01-07 04:01:26 +0000385/// which implicitly adds the builtin defines etc.
Chris Lattnere127a0d2010-04-20 20:35:58 +0000386void Preprocessor::EnterMainSourceFile() {
Chris Lattner05db4272009-02-13 19:33:24 +0000387 // We do not allow the preprocessor to reenter the main file. Doing so will
388 // cause FileID's to accumulate information from both runs (e.g. #line
389 // information) and predefined macros aren't guaranteed to be set properly.
390 assert(NumEnteredSourceFiles == 0 && "Cannot reenter the main file!");
Chris Lattner2b2453a2009-01-17 06:22:33 +0000391 FileID MainFileID = SourceMgr.getMainFileID();
Mike Stump1eb44332009-09-09 15:08:12 +0000392
Chris Lattner53b0dab2007-10-09 22:10:18 +0000393 // Enter the main file source buffer.
Chris Lattnere127a0d2010-04-20 20:35:58 +0000394 EnterSourceFile(MainFileID, 0, SourceLocation());
Mike Stump1eb44332009-09-09 15:08:12 +0000395
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000396 // If we've been asked to skip bytes in the main file (e.g., as part of a
397 // precompiled preamble), do so now.
398 if (SkipMainFilePreamble.first > 0)
399 CurLexer->SkipBytes(SkipMainFilePreamble.first,
400 SkipMainFilePreamble.second);
401
Chris Lattnerb2832982007-11-15 19:07:47 +0000402 // Tell the header info that the main file was entered. If the file is later
403 // #imported, it won't be re-entered.
Chris Lattner2b2453a2009-01-17 06:22:33 +0000404 if (const FileEntry *FE = SourceMgr.getFileEntryForID(MainFileID))
Chris Lattnerb2832982007-11-15 19:07:47 +0000405 HeaderInfo.IncrementIncludeCount(FE);
Mike Stump1eb44332009-09-09 15:08:12 +0000406
Benjamin Kramerffd6e392009-12-31 15:33:09 +0000407 // Preprocess Predefines to populate the initial preprocessor state.
Mike Stump1eb44332009-09-09 15:08:12 +0000408 llvm::MemoryBuffer *SB =
Chris Lattnera0a270c2010-04-05 22:42:27 +0000409 llvm::MemoryBuffer::getMemBufferCopy(Predefines, "<built-in>");
Douglas Gregor043266b2010-08-26 14:07:34 +0000410 assert(SB && "Cannot create predefined source buffer");
Chris Lattner2b2453a2009-01-17 06:22:33 +0000411 FileID FID = SourceMgr.createFileIDForMemBuffer(SB);
412 assert(!FID.isInvalid() && "Could not create FileID for predefines?");
Mike Stump1eb44332009-09-09 15:08:12 +0000413
Chris Lattner53b0dab2007-10-09 22:10:18 +0000414 // Start parsing the predefines.
Chris Lattnere127a0d2010-04-20 20:35:58 +0000415 EnterSourceFile(FID, 0, SourceLocation());
Chris Lattner53b0dab2007-10-09 22:10:18 +0000416}
Chris Lattner97ba77c2007-07-16 06:48:38 +0000417
Daniel Dunbardbd82092010-03-23 05:09:10 +0000418void Preprocessor::EndSourceFile() {
419 // Notify the client that we reached the end of the source file.
420 if (Callbacks)
421 Callbacks->EndOfMainFile();
422}
Reid Spencer5f016e22007-07-11 17:01:13 +0000423
424//===----------------------------------------------------------------------===//
425// Lexer Event Handling.
426//===----------------------------------------------------------------------===//
427
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +0000428/// LookUpIdentifierInfo - Given a tok::raw_identifier token, look up the
429/// identifier information for the token and install it into the token,
430/// updating the token kind accordingly.
431IdentifierInfo *Preprocessor::LookUpIdentifierInfo(Token &Identifier) const {
432 assert(Identifier.getRawIdentifierData() != 0 && "No raw identifier data!");
Mike Stump1eb44332009-09-09 15:08:12 +0000433
Reid Spencer5f016e22007-07-11 17:01:13 +0000434 // Look up this token, see if it is a macro, or if it is a language keyword.
435 IdentifierInfo *II;
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +0000436 if (!Identifier.needsCleaning()) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000437 // No cleaning needed, just use the characters from the lexed buffer.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000438 II = getIdentifierInfo(StringRef(Identifier.getRawIdentifierData(),
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +0000439 Identifier.getLength()));
Reid Spencer5f016e22007-07-11 17:01:13 +0000440 } else {
441 // Cleaning needed, alloca a buffer, clean into it, then use the buffer.
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +0000442 llvm::SmallString<64> IdentifierBuffer;
Chris Lattner5f9e2722011-07-23 10:55:15 +0000443 StringRef CleanedStr = getSpelling(Identifier, IdentifierBuffer);
Benjamin Kramerddeea562010-02-27 13:44:12 +0000444 II = getIdentifierInfo(CleanedStr);
Reid Spencer5f016e22007-07-11 17:01:13 +0000445 }
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +0000446
447 // Update the token info (identifier info and appropriate token kind).
Reid Spencer5f016e22007-07-11 17:01:13 +0000448 Identifier.setIdentifierInfo(II);
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +0000449 Identifier.setKind(II->getTokenID());
450
Reid Spencer5f016e22007-07-11 17:01:13 +0000451 return II;
452}
453
John Wiegley28bbe4b2011-04-28 01:08:34 +0000454void Preprocessor::SetPoisonReason(IdentifierInfo *II, unsigned DiagID) {
455 PoisonReasons[II] = DiagID;
456}
457
458void Preprocessor::PoisonSEHIdentifiers(bool Poison) {
459 assert(Ident__exception_code && Ident__exception_info);
460 assert(Ident___exception_code && Ident___exception_info);
461 Ident__exception_code->setIsPoisoned(Poison);
462 Ident___exception_code->setIsPoisoned(Poison);
463 Ident_GetExceptionCode->setIsPoisoned(Poison);
464 Ident__exception_info->setIsPoisoned(Poison);
465 Ident___exception_info->setIsPoisoned(Poison);
466 Ident_GetExceptionInfo->setIsPoisoned(Poison);
467 Ident__abnormal_termination->setIsPoisoned(Poison);
468 Ident___abnormal_termination->setIsPoisoned(Poison);
469 Ident_AbnormalTermination->setIsPoisoned(Poison);
470}
471
472void Preprocessor::HandlePoisonedIdentifier(Token & Identifier) {
473 assert(Identifier.getIdentifierInfo() &&
474 "Can't handle identifiers without identifier info!");
475 llvm::DenseMap<IdentifierInfo*,unsigned>::const_iterator it =
476 PoisonReasons.find(Identifier.getIdentifierInfo());
477 if(it == PoisonReasons.end())
478 Diag(Identifier, diag::err_pp_used_poisoned_id);
479 else
480 Diag(Identifier,it->second) << Identifier.getIdentifierInfo();
481}
Reid Spencer5f016e22007-07-11 17:01:13 +0000482
483/// HandleIdentifier - This callback is invoked when the lexer reads an
484/// identifier. This callback looks up the identifier in the map and/or
485/// potentially macro expands it or turns it into a named token (like 'for').
Chris Lattner6a170eb2009-01-21 07:43:11 +0000486///
487/// Note that callers of this method are guarded by checking the
488/// IdentifierInfo's 'isHandleIdentifierCase' bit. If this method changes, the
489/// IdentifierInfo methods that compute these properties will need to change to
490/// match.
Chris Lattnerd2177732007-07-20 16:59:19 +0000491void Preprocessor::HandleIdentifier(Token &Identifier) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000492 assert(Identifier.getIdentifierInfo() &&
493 "Can't handle identifiers without identifier info!");
Mike Stump1eb44332009-09-09 15:08:12 +0000494
Reid Spencer5f016e22007-07-11 17:01:13 +0000495 IdentifierInfo &II = *Identifier.getIdentifierInfo();
496
Douglas Gregoreee242f2011-10-27 09:33:13 +0000497 // If the information about this identifier is out of date, update it from
498 // the external source.
499 if (II.isOutOfDate()) {
500 ExternalSource->updateOutOfDateIdentifier(II);
501 Identifier.setKind(II.getTokenID());
502 }
503
Reid Spencer5f016e22007-07-11 17:01:13 +0000504 // If this identifier was poisoned, and if it was not produced from a macro
505 // expansion, emit an error.
Ted Kremenek1a531572008-11-19 22:43:49 +0000506 if (II.isPoisoned() && CurPPLexer) {
John Wiegley28bbe4b2011-04-28 01:08:34 +0000507 HandlePoisonedIdentifier(Identifier);
Reid Spencer5f016e22007-07-11 17:01:13 +0000508 }
Mike Stump1eb44332009-09-09 15:08:12 +0000509
Reid Spencer5f016e22007-07-11 17:01:13 +0000510 // If this is a macro to be expanded, do it.
Chris Lattnercc1a8752007-10-07 08:44:20 +0000511 if (MacroInfo *MI = getMacroInfo(&II)) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000512 if (!DisableMacroExpansion && !Identifier.isExpandDisabled()) {
513 if (MI->isEnabled()) {
514 if (!HandleMacroExpandedIdentifier(Identifier, MI))
Douglas Gregor6be16fe2011-08-27 06:37:51 +0000515 return;
Reid Spencer5f016e22007-07-11 17:01:13 +0000516 } else {
517 // C99 6.10.3.4p2 says that a disabled macro may never again be
518 // expanded, even if it's in a context where it could be expanded in the
519 // future.
Chris Lattnerd2177732007-07-20 16:59:19 +0000520 Identifier.setFlag(Token::DisableExpand);
Reid Spencer5f016e22007-07-11 17:01:13 +0000521 }
522 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000523 }
524
Richard Smith98d86b92011-10-11 19:57:52 +0000525 // If this identifier is a keyword in C++11, produce a warning. Don't warn if
526 // we're not considering macro expansion, since this identifier might be the
527 // name of a macro.
528 // FIXME: This warning is disabled in cases where it shouldn't be, like
529 // "#define constexpr constexpr", "int constexpr;"
530 if (II.isCXX11CompatKeyword() & !DisableMacroExpansion) {
531 Diag(Identifier, diag::warn_cxx11_keyword) << II.getName();
532 // Don't diagnose this keyword again in this translation unit.
533 II.setIsCXX11CompatKeyword(false);
534 }
535
Reid Spencer5f016e22007-07-11 17:01:13 +0000536 // C++ 2.11p2: If this is an alternative representation of a C++ operator,
537 // then we act as if it is the actual operator and not the textual
538 // representation of it.
Fariborz Jahanianafbc6812010-09-03 17:33:04 +0000539 if (II.isCPlusPlusOperatorKeyword())
Reid Spencer5f016e22007-07-11 17:01:13 +0000540 Identifier.setIdentifierInfo(0);
541
Reid Spencer5f016e22007-07-11 17:01:13 +0000542 // If this is an extension token, diagnose its use.
Steve Naroffb4eaf9c2008-09-02 18:50:17 +0000543 // We avoid diagnosing tokens that originate from macro definitions.
Eli Friedman2962f4d2009-04-28 03:59:15 +0000544 // FIXME: This warning is disabled in cases where it shouldn't be,
545 // like "#define TY typeof", "TY(1) x".
546 if (II.isExtensionToken() && !DisableMacroExpansion)
Reid Spencer5f016e22007-07-11 17:01:13 +0000547 Diag(Identifier, diag::ext_token_used);
Douglas Gregorb8db7cd2011-09-07 23:11:54 +0000548
549 // If this is the '__import_module__' keyword, note that the next token
550 // indicates a module name.
551 if (II.getTokenID() == tok::kw___import_module__ &&
552 !InMacroArgs && !DisableMacroExpansion) {
553 ModuleImportLoc = Identifier.getLocation();
Douglas Gregorb514c792011-11-30 04:26:53 +0000554 ModuleImportPath.clear();
555 ModuleImportExpectsIdentifier = true;
Douglas Gregorb8db7cd2011-09-07 23:11:54 +0000556 CurLexerKind = CLK_LexAfterModuleImport;
557 }
Douglas Gregor6aa52ec2011-08-26 23:56:07 +0000558}
559
Douglas Gregorb8db7cd2011-09-07 23:11:54 +0000560/// \brief Lex a token following the __import_module__ keyword.
561void Preprocessor::LexAfterModuleImport(Token &Result) {
562 // Figure out what kind of lexer we actually have.
563 if (CurLexer)
564 CurLexerKind = CLK_Lexer;
565 else if (CurPTHLexer)
566 CurLexerKind = CLK_PTHLexer;
567 else if (CurTokenLexer)
568 CurLexerKind = CLK_TokenLexer;
569 else
570 CurLexerKind = CLK_CachingLexer;
571
572 // Lex the next token.
573 Lex(Result);
574
Douglas Gregor6aa52ec2011-08-26 23:56:07 +0000575 // The token sequence
576 //
Douglas Gregorb514c792011-11-30 04:26:53 +0000577 // __import_module__ identifier (. identifier)*
Douglas Gregor6aa52ec2011-08-26 23:56:07 +0000578 //
Douglas Gregorb8db7cd2011-09-07 23:11:54 +0000579 // indicates a module import directive. We already saw the __import_module__
Douglas Gregorb514c792011-11-30 04:26:53 +0000580 // keyword, so now we're looking for the identifiers.
581 if (ModuleImportExpectsIdentifier && Result.getKind() == tok::identifier) {
582 // We expected to see an identifier here, and we did; continue handling
583 // identifiers.
584 ModuleImportPath.push_back(std::make_pair(Result.getIdentifierInfo(),
585 Result.getLocation()));
586 ModuleImportExpectsIdentifier = false;
587 CurLexerKind = CLK_LexAfterModuleImport;
Douglas Gregor6aa52ec2011-08-26 23:56:07 +0000588 return;
Douglas Gregorb514c792011-11-30 04:26:53 +0000589 }
Douglas Gregor6aa52ec2011-08-26 23:56:07 +0000590
Douglas Gregorb514c792011-11-30 04:26:53 +0000591 // If we're expecting a '.' or a ';', and we got a '.', then wait until we
592 // see the next identifier.
593 if (!ModuleImportExpectsIdentifier && Result.getKind() == tok::period) {
594 ModuleImportExpectsIdentifier = true;
595 CurLexerKind = CLK_LexAfterModuleImport;
596 return;
597 }
598
599 // If we have a non-empty module path, load the named module.
600 if (!ModuleImportPath.empty())
Douglas Gregor5e356932011-12-01 17:11:21 +0000601 (void)TheModuleLoader.loadModule(ModuleImportLoc, ModuleImportPath,
Douglas Gregor93ebfa62011-12-02 23:42:12 +0000602 Module::MacrosVisible,
603 /*IsIncludeDirective=*/false);
Reid Spencer5f016e22007-07-11 17:01:13 +0000604}
Douglas Gregor2e222532009-07-02 17:08:52 +0000605
606void Preprocessor::AddCommentHandler(CommentHandler *Handler) {
607 assert(Handler && "NULL comment handler");
608 assert(std::find(CommentHandlers.begin(), CommentHandlers.end(), Handler) ==
609 CommentHandlers.end() && "Comment handler already registered");
610 CommentHandlers.push_back(Handler);
611}
612
613void Preprocessor::RemoveCommentHandler(CommentHandler *Handler) {
614 std::vector<CommentHandler *>::iterator Pos
615 = std::find(CommentHandlers.begin(), CommentHandlers.end(), Handler);
616 assert(Pos != CommentHandlers.end() && "Comment handler not registered");
617 CommentHandlers.erase(Pos);
618}
619
Chris Lattner046c2272010-01-18 22:35:47 +0000620bool Preprocessor::HandleComment(Token &result, SourceRange Comment) {
621 bool AnyPendingTokens = false;
Douglas Gregor2e222532009-07-02 17:08:52 +0000622 for (std::vector<CommentHandler *>::iterator H = CommentHandlers.begin(),
623 HEnd = CommentHandlers.end();
Chris Lattner046c2272010-01-18 22:35:47 +0000624 H != HEnd; ++H) {
625 if ((*H)->HandleComment(*this, Comment))
626 AnyPendingTokens = true;
627 }
628 if (!AnyPendingTokens || getCommentRetentionState())
629 return false;
630 Lex(result);
631 return true;
Douglas Gregor2e222532009-07-02 17:08:52 +0000632}
633
Douglas Gregor6aa52ec2011-08-26 23:56:07 +0000634ModuleLoader::~ModuleLoader() { }
635
Douglas Gregor2e222532009-07-02 17:08:52 +0000636CommentHandler::~CommentHandler() { }
Douglas Gregor94dc8f62010-03-19 16:15:56 +0000637
Douglas Gregorf44e8542010-08-24 19:08:16 +0000638CodeCompletionHandler::~CodeCompletionHandler() { }
639
Douglas Gregordca8ee82011-05-06 16:33:08 +0000640void Preprocessor::createPreprocessingRecord(
Chandler Carruth9e5bb852011-07-14 08:20:46 +0000641 bool IncludeNestedMacroExpansions) {
Douglas Gregor94dc8f62010-03-19 16:15:56 +0000642 if (Record)
643 return;
644
Argyrios Kyrtzidis2dbaca72011-09-19 20:40:25 +0000645 Record = new PreprocessingRecord(getSourceManager(),
646 IncludeNestedMacroExpansions);
Douglas Gregorb9e1b752010-03-19 17:12:43 +0000647 addPPCallbacks(Record);
Douglas Gregor94dc8f62010-03-19 16:15:56 +0000648}