blob: 51908bdb8789b8c1ec9a433261729bb432b325dc [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
52Preprocessor::Preprocessor(Diagnostic &diags, const LangOptions &opts,
Daniel Dunbar444be732009-11-13 05:51:54 +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,
56 bool OwnsHeaders)
Chris Lattner836040f2009-03-13 21:17:43 +000057 : Diags(&diags), Features(opts), Target(target),FileMgr(Headers.getFileMgr()),
Douglas Gregor6aa52ec2011-08-26 23:56:07 +000058 SourceMgr(SM), HeaderInfo(Headers), TheModuleLoader(TheModuleLoader),
59 ExternalSource(0),
Douglas Gregorf44e8542010-08-24 19:08:16 +000060 Identifiers(opts, IILookup), BuiltinInfo(Target), CodeComplete(0),
61 CodeCompletionFile(0), SkipMainFilePreamble(0, true), CurPPLexer(0),
Ted Kremenek9714a232010-10-19 22:15:20 +000062 CurDirLookup(0), Callbacks(0), MacroArgCache(0), Record(0), MIChainHead(0),
63 MICache(0) {
Reid Spencer5f016e22007-07-11 17:01:13 +000064 ScratchBuf = new ScratchBuffer(SourceMgr);
Chris Lattnerc1f9d822009-04-13 01:29:17 +000065 CounterValue = 0; // __COUNTER__ starts at 0.
Daniel Dunbar5814e652009-11-11 21:44:21 +000066 OwnsHeaderSearch = OwnsHeaders;
Mike Stump1eb44332009-09-09 15:08:12 +000067
Reid Spencer5f016e22007-07-11 17:01:13 +000068 // Clear stats.
69 NumDirectives = NumDefined = NumUndefined = NumPragma = 0;
70 NumIf = NumElse = NumEndif = 0;
71 NumEnteredSourceFiles = 0;
72 NumMacroExpanded = NumFnMacroExpanded = NumBuiltinMacroExpanded = 0;
73 NumFastMacroExpanded = NumTokenPaste = NumFastTokenPaste = 0;
Mike Stump1eb44332009-09-09 15:08:12 +000074 MaxIncludeStackDepth = 0;
Reid Spencer5f016e22007-07-11 17:01:13 +000075 NumSkipped = 0;
76
77 // Default to discarding comments.
78 KeepComments = false;
79 KeepMacroComments = false;
Mike Stump1eb44332009-09-09 15:08:12 +000080
Reid Spencer5f016e22007-07-11 17:01:13 +000081 // Macro expansion is enabled.
82 DisableMacroExpansion = false;
83 InMacroArgs = false;
Chris Lattner6cfe7592008-03-09 02:26:03 +000084 NumCachedTokenLexers = 0;
Reid Spencer5f016e22007-07-11 17:01:13 +000085
Argyrios Kyrtzidis03db1b32008-08-10 13:15:22 +000086 CachedLexPos = 0;
87
Douglas Gregor88a35862010-01-04 19:18:44 +000088 // We haven't read anything from the external source.
89 ReadMacrosFromExternalSource = false;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +000090
Douglas Gregor6be16fe2011-08-27 06:37:51 +000091 LexDepth = 0;
92
Reid Spencer5f016e22007-07-11 17:01:13 +000093 // "Poison" __VA_ARGS__, which can only appear in the expansion of a macro.
94 // This gets unpoisoned where it is allowed.
95 (Ident__VA_ARGS__ = getIdentifierInfo("__VA_ARGS__"))->setIsPoisoned();
John Wiegley28bbe4b2011-04-28 01:08:34 +000096 SetPoisonReason(Ident__VA_ARGS__,diag::ext_pp_bad_vaargs_use);
Mike Stump1eb44332009-09-09 15:08:12 +000097
Reid Spencer5f016e22007-07-11 17:01:13 +000098 // Initialize the pragma handlers.
Chris Lattner5f9e2722011-07-23 10:55:15 +000099 PragmaHandlers = new PragmaNamespace(StringRef());
Reid Spencer5f016e22007-07-11 17:01:13 +0000100 RegisterBuiltinPragmas();
Mike Stump1eb44332009-09-09 15:08:12 +0000101
Reid Spencer5f016e22007-07-11 17:01:13 +0000102 // Initialize builtin macros like __LINE__ and friends.
103 RegisterBuiltinMacros();
John Wiegley28bbe4b2011-04-28 01:08:34 +0000104
105 if(Features.Borland) {
106 Ident__exception_info = getIdentifierInfo("_exception_info");
107 Ident___exception_info = getIdentifierInfo("__exception_info");
108 Ident_GetExceptionInfo = getIdentifierInfo("GetExceptionInformation");
109 Ident__exception_code = getIdentifierInfo("_exception_code");
110 Ident___exception_code = getIdentifierInfo("__exception_code");
111 Ident_GetExceptionCode = getIdentifierInfo("GetExceptionCode");
112 Ident__abnormal_termination = getIdentifierInfo("_abnormal_termination");
113 Ident___abnormal_termination = getIdentifierInfo("__abnormal_termination");
114 Ident_AbnormalTermination = getIdentifierInfo("AbnormalTermination");
115 } else {
116 Ident__exception_info = Ident__exception_code = Ident__abnormal_termination = 0;
117 Ident___exception_info = Ident___exception_code = Ident___abnormal_termination = 0;
118 Ident_GetExceptionInfo = Ident_GetExceptionCode = Ident_AbnormalTermination = 0;
119 }
120
Reid Spencer5f016e22007-07-11 17:01:13 +0000121}
122
123Preprocessor::~Preprocessor() {
Argyrios Kyrtzidis2174a4f2008-08-23 12:12:06 +0000124 assert(BacktrackPositions.empty() && "EnableBacktrack/Backtrack imbalance!");
Argyrios Kyrtzidis5b3284a2011-06-29 22:20:11 +0000125 assert(MacroExpandingLexersStack.empty() && MacroExpandedTokens.empty() &&
126 "Preprocessor::HandleEndOfTokenLexer should have cleared those");
Argyrios Kyrtzidis2174a4f2008-08-23 12:12:06 +0000127
Reid Spencer5f016e22007-07-11 17:01:13 +0000128 while (!IncludeMacroStack.empty()) {
129 delete IncludeMacroStack.back().TheLexer;
Chris Lattner6cfe7592008-03-09 02:26:03 +0000130 delete IncludeMacroStack.back().TheTokenLexer;
Reid Spencer5f016e22007-07-11 17:01:13 +0000131 IncludeMacroStack.pop_back();
132 }
Chris Lattnercc1a8752007-10-07 08:44:20 +0000133
134 // Free any macro definitions.
Ted Kremenek2a6b03a2010-10-19 21:30:11 +0000135 for (MacroInfoChain *I = MIChainHead ; I ; I = I->Next)
Ted Kremenekaf8fa252010-10-19 18:16:54 +0000136 I->MI.Destroy();
Mike Stump1eb44332009-09-09 15:08:12 +0000137
Chris Lattner9594acf2007-07-15 00:25:26 +0000138 // Free any cached macro expanders.
Chris Lattner6cfe7592008-03-09 02:26:03 +0000139 for (unsigned i = 0, e = NumCachedTokenLexers; i != e; ++i)
140 delete TokenLexerCache[i];
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +0000141
Chris Lattner23f77e52009-12-15 01:51:03 +0000142 // Free any cached MacroArgs.
143 for (MacroArgs *ArgList = MacroArgCache; ArgList; )
144 ArgList = ArgList->deallocate();
Mike Stump1eb44332009-09-09 15:08:12 +0000145
Reid Spencer5f016e22007-07-11 17:01:13 +0000146 // Release pragma information.
147 delete PragmaHandlers;
148
149 // Delete the scratch buffer info.
150 delete ScratchBuf;
Chris Lattnereb50ed82008-03-14 06:07:05 +0000151
Daniel Dunbar5814e652009-11-11 21:44:21 +0000152 // Delete the header search info, if we own it.
153 if (OwnsHeaderSearch)
154 delete &HeaderInfo;
155
Chris Lattnereb50ed82008-03-14 06:07:05 +0000156 delete Callbacks;
Reid Spencer5f016e22007-07-11 17:01:13 +0000157}
158
Ted Kremenek337edcd2009-02-12 03:26:59 +0000159void Preprocessor::setPTHManager(PTHManager* pm) {
160 PTH.reset(pm);
Douglas Gregor52e71082009-10-16 18:18:30 +0000161 FileMgr.addStatCache(PTH->createStatCache());
Ted Kremenek337edcd2009-02-12 03:26:59 +0000162}
163
Chris Lattnerd2177732007-07-20 16:59:19 +0000164void Preprocessor::DumpToken(const Token &Tok, bool DumpFlags) const {
Benjamin Kramer6cb7c1a2009-08-23 12:08:50 +0000165 llvm::errs() << tok::getTokenName(Tok.getKind()) << " '"
166 << getSpelling(Tok) << "'";
Mike Stump1eb44332009-09-09 15:08:12 +0000167
Reid Spencer5f016e22007-07-11 17:01:13 +0000168 if (!DumpFlags) return;
Mike Stump1eb44332009-09-09 15:08:12 +0000169
Benjamin Kramer6cb7c1a2009-08-23 12:08:50 +0000170 llvm::errs() << "\t";
Reid Spencer5f016e22007-07-11 17:01:13 +0000171 if (Tok.isAtStartOfLine())
Benjamin Kramer6cb7c1a2009-08-23 12:08:50 +0000172 llvm::errs() << " [StartOfLine]";
Reid Spencer5f016e22007-07-11 17:01:13 +0000173 if (Tok.hasLeadingSpace())
Benjamin Kramer6cb7c1a2009-08-23 12:08:50 +0000174 llvm::errs() << " [LeadingSpace]";
Reid Spencer5f016e22007-07-11 17:01:13 +0000175 if (Tok.isExpandDisabled())
Benjamin Kramer6cb7c1a2009-08-23 12:08:50 +0000176 llvm::errs() << " [ExpandDisabled]";
Reid Spencer5f016e22007-07-11 17:01:13 +0000177 if (Tok.needsCleaning()) {
178 const char *Start = SourceMgr.getCharacterData(Tok.getLocation());
Chris Lattner5f9e2722011-07-23 10:55:15 +0000179 llvm::errs() << " [UnClean='" << StringRef(Start, Tok.getLength())
Benjamin Kramer6cb7c1a2009-08-23 12:08:50 +0000180 << "']";
Reid Spencer5f016e22007-07-11 17:01:13 +0000181 }
Mike Stump1eb44332009-09-09 15:08:12 +0000182
Benjamin Kramer6cb7c1a2009-08-23 12:08:50 +0000183 llvm::errs() << "\tLoc=<";
Chris Lattnerc3d8d572007-12-09 20:31:55 +0000184 DumpLocation(Tok.getLocation());
Benjamin Kramer6cb7c1a2009-08-23 12:08:50 +0000185 llvm::errs() << ">";
Chris Lattnerc3d8d572007-12-09 20:31:55 +0000186}
187
188void Preprocessor::DumpLocation(SourceLocation Loc) const {
Chris Lattnerb9c3f962009-01-27 07:57:44 +0000189 Loc.dump(SourceMgr);
Reid Spencer5f016e22007-07-11 17:01:13 +0000190}
191
192void Preprocessor::DumpMacro(const MacroInfo &MI) const {
Benjamin Kramer6cb7c1a2009-08-23 12:08:50 +0000193 llvm::errs() << "MACRO: ";
Reid Spencer5f016e22007-07-11 17:01:13 +0000194 for (unsigned i = 0, e = MI.getNumTokens(); i != e; ++i) {
195 DumpToken(MI.getReplacementToken(i));
Benjamin Kramer6cb7c1a2009-08-23 12:08:50 +0000196 llvm::errs() << " ";
Reid Spencer5f016e22007-07-11 17:01:13 +0000197 }
Benjamin Kramer6cb7c1a2009-08-23 12:08:50 +0000198 llvm::errs() << "\n";
Reid Spencer5f016e22007-07-11 17:01:13 +0000199}
200
201void Preprocessor::PrintStats() {
Benjamin Kramer6cb7c1a2009-08-23 12:08:50 +0000202 llvm::errs() << "\n*** Preprocessor Stats:\n";
203 llvm::errs() << NumDirectives << " directives found:\n";
204 llvm::errs() << " " << NumDefined << " #define.\n";
205 llvm::errs() << " " << NumUndefined << " #undef.\n";
206 llvm::errs() << " #include/#include_next/#import:\n";
207 llvm::errs() << " " << NumEnteredSourceFiles << " source files entered.\n";
208 llvm::errs() << " " << MaxIncludeStackDepth << " max include stack depth\n";
209 llvm::errs() << " " << NumIf << " #if/#ifndef/#ifdef.\n";
210 llvm::errs() << " " << NumElse << " #else/#elif.\n";
211 llvm::errs() << " " << NumEndif << " #endif.\n";
212 llvm::errs() << " " << NumPragma << " #pragma.\n";
213 llvm::errs() << NumSkipped << " #if/#ifndef#ifdef regions skipped\n";
Reid Spencer5f016e22007-07-11 17:01:13 +0000214
Benjamin Kramer6cb7c1a2009-08-23 12:08:50 +0000215 llvm::errs() << NumMacroExpanded << "/" << NumFnMacroExpanded << "/"
Ted Kremenekbdd30c22008-01-14 16:44:48 +0000216 << NumBuiltinMacroExpanded << " obj/fn/builtin macros expanded, "
217 << NumFastMacroExpanded << " on the fast path.\n";
Benjamin Kramer6cb7c1a2009-08-23 12:08:50 +0000218 llvm::errs() << (NumFastTokenPaste+NumTokenPaste)
Ted Kremenekbdd30c22008-01-14 16:44:48 +0000219 << " token paste (##) operations performed, "
220 << NumFastTokenPaste << " on the fast path.\n";
Reid Spencer5f016e22007-07-11 17:01:13 +0000221}
222
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +0000223Preprocessor::macro_iterator
224Preprocessor::macro_begin(bool IncludeExternalMacros) const {
225 if (IncludeExternalMacros && ExternalSource &&
Douglas Gregor88a35862010-01-04 19:18:44 +0000226 !ReadMacrosFromExternalSource) {
227 ReadMacrosFromExternalSource = true;
228 ExternalSource->ReadDefinedMacros();
229 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +0000230
231 return Macros.begin();
Douglas Gregor88a35862010-01-04 19:18:44 +0000232}
233
Argyrios Kyrtzidisc5c5e922011-06-29 22:20:04 +0000234size_t Preprocessor::getTotalMemory() const {
Ted Kremenek91d1bd62011-07-26 21:17:24 +0000235 return BP.getTotalMemory()
Ted Kremenek67485092011-07-27 18:41:23 +0000236 + llvm::capacity_in_bytes(MacroExpandedTokens)
Ted Kremenek91d1bd62011-07-26 21:17:24 +0000237 + Predefines.capacity() /* Predefines buffer. */
Ted Kremenek67485092011-07-27 18:41:23 +0000238 + llvm::capacity_in_bytes(Macros)
239 + llvm::capacity_in_bytes(PragmaPushMacroInfo)
240 + llvm::capacity_in_bytes(PoisonReasons)
241 + llvm::capacity_in_bytes(CommentHandlers);
Argyrios Kyrtzidisc5c5e922011-06-29 22:20:04 +0000242}
243
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +0000244Preprocessor::macro_iterator
245Preprocessor::macro_end(bool IncludeExternalMacros) const {
246 if (IncludeExternalMacros && ExternalSource &&
Douglas Gregor88a35862010-01-04 19:18:44 +0000247 !ReadMacrosFromExternalSource) {
248 ReadMacrosFromExternalSource = true;
249 ExternalSource->ReadDefinedMacros();
250 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +0000251
252 return Macros.end();
Douglas Gregor88a35862010-01-04 19:18:44 +0000253}
254
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +0000255bool Preprocessor::SetCodeCompletionPoint(const FileEntry *File,
256 unsigned TruncateAtLine,
Douglas Gregor29684422009-12-02 06:49:09 +0000257 unsigned TruncateAtColumn) {
258 using llvm::MemoryBuffer;
259
260 CodeCompletionFile = File;
261
262 // Okay to clear out the code-completion point by passing NULL.
263 if (!CodeCompletionFile)
264 return false;
265
266 // Load the actual file's contents.
Douglas Gregoraa38c3d2010-03-16 19:49:24 +0000267 bool Invalid = false;
268 const MemoryBuffer *Buffer = SourceMgr.getMemoryBufferForFile(File, &Invalid);
269 if (Invalid)
Douglas Gregor29684422009-12-02 06:49:09 +0000270 return true;
271
272 // Find the byte position of the truncation point.
273 const char *Position = Buffer->getBufferStart();
274 for (unsigned Line = 1; Line < TruncateAtLine; ++Line) {
275 for (; *Position; ++Position) {
276 if (*Position != '\r' && *Position != '\n')
277 continue;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +0000278
Douglas Gregor29684422009-12-02 06:49:09 +0000279 // Eat \r\n or \n\r as a single line.
280 if ((Position[1] == '\r' || Position[1] == '\n') &&
281 Position[0] != Position[1])
282 ++Position;
283 ++Position;
284 break;
285 }
286 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +0000287
Douglas Gregorb760fe82009-12-08 21:45:46 +0000288 Position += TruncateAtColumn - 1;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +0000289
Douglas Gregor29684422009-12-02 06:49:09 +0000290 // Truncate the buffer.
Douglas Gregorb760fe82009-12-08 21:45:46 +0000291 if (Position < Buffer->getBufferEnd()) {
Chris Lattner5f9e2722011-07-23 10:55:15 +0000292 StringRef Data(Buffer->getBufferStart(),
Chris Lattnera0a270c2010-04-05 22:42:27 +0000293 Position-Buffer->getBufferStart());
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +0000294 MemoryBuffer *TruncatedBuffer
Chris Lattnera0a270c2010-04-05 22:42:27 +0000295 = MemoryBuffer::getMemBufferCopy(Data, Buffer->getBufferIdentifier());
Douglas Gregor29684422009-12-02 06:49:09 +0000296 SourceMgr.overrideFileContents(File, TruncatedBuffer);
297 }
298
299 return false;
300}
301
Douglas Gregor109ae732009-12-03 17:05:59 +0000302bool Preprocessor::isCodeCompletionFile(SourceLocation FileLoc) const {
Douglas Gregor29684422009-12-02 06:49:09 +0000303 return CodeCompletionFile && FileLoc.isFileID() &&
304 SourceMgr.getFileEntryForID(SourceMgr.getFileID(FileLoc))
305 == CodeCompletionFile;
306}
307
Douglas Gregor55817af2010-08-25 17:04:25 +0000308void Preprocessor::CodeCompleteNaturalLanguage() {
309 SetCodeCompletionPoint(0, 0, 0);
310 getDiagnostics().setSuppressAllDiagnostics(true);
311 if (CodeComplete)
312 CodeComplete->CodeCompleteNaturalLanguage();
313}
314
Benjamin Kramer51f5fe32010-02-27 17:05:45 +0000315/// getSpelling - This method is used to get the spelling of a token into a
316/// SmallVector. Note that the returned StringRef may not point to the
317/// supplied buffer if a copy can be avoided.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000318StringRef Preprocessor::getSpelling(const Token &Tok,
319 SmallVectorImpl<char> &Buffer,
Douglas Gregor50f6af72010-03-16 05:20:39 +0000320 bool *Invalid) const {
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +0000321 // NOTE: this has to be checked *before* testing for an IdentifierInfo.
322 if (Tok.isNot(tok::raw_identifier)) {
323 // Try the fast path.
324 if (const IdentifierInfo *II = Tok.getIdentifierInfo())
325 return II->getName();
326 }
Benjamin Kramer51f5fe32010-02-27 17:05:45 +0000327
328 // Resize the buffer if we need to copy into it.
329 if (Tok.needsCleaning())
330 Buffer.resize(Tok.getLength());
331
332 const char *Ptr = Buffer.data();
Douglas Gregor50f6af72010-03-16 05:20:39 +0000333 unsigned Len = getSpelling(Tok, Ptr, Invalid);
Chris Lattner5f9e2722011-07-23 10:55:15 +0000334 return StringRef(Ptr, Len);
Benjamin Kramer51f5fe32010-02-27 17:05:45 +0000335}
336
Reid Spencer5f016e22007-07-11 17:01:13 +0000337/// CreateString - Plop the specified string into a scratch buffer and return a
338/// location for it. If specified, the source location provides a source
339/// location for the token.
Chris Lattner47246be2009-01-26 19:29:26 +0000340void Preprocessor::CreateString(const char *Buf, unsigned Len, Token &Tok,
Chandler Carruth9e5bb852011-07-14 08:20:46 +0000341 SourceLocation ExpansionLoc) {
Chris Lattner47246be2009-01-26 19:29:26 +0000342 Tok.setLength(Len);
Mike Stump1eb44332009-09-09 15:08:12 +0000343
Chris Lattner47246be2009-01-26 19:29:26 +0000344 const char *DestPtr;
345 SourceLocation Loc = ScratchBuf->getToken(Buf, Len, DestPtr);
Mike Stump1eb44332009-09-09 15:08:12 +0000346
Chandler Carruth9e5bb852011-07-14 08:20:46 +0000347 if (ExpansionLoc.isValid())
Chandler Carruthbf340e42011-07-26 03:03:05 +0000348 Loc = SourceMgr.createExpansionLoc(Loc, ExpansionLoc, ExpansionLoc, Len);
Chris Lattner47246be2009-01-26 19:29:26 +0000349 Tok.setLocation(Loc);
Mike Stump1eb44332009-09-09 15:08:12 +0000350
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +0000351 // If this is a raw identifier or a literal token, set the pointer data.
352 if (Tok.is(tok::raw_identifier))
353 Tok.setRawIdentifierData(DestPtr);
354 else if (Tok.isLiteral())
Chris Lattner47246be2009-01-26 19:29:26 +0000355 Tok.setLiteralData(DestPtr);
Reid Spencer5f016e22007-07-11 17:01:13 +0000356}
357
358
Chris Lattner97ba77c2007-07-16 06:48:38 +0000359
Chris Lattner53b0dab2007-10-09 22:10:18 +0000360//===----------------------------------------------------------------------===//
361// Preprocessor Initialization Methods
362//===----------------------------------------------------------------------===//
363
Chris Lattner53b0dab2007-10-09 22:10:18 +0000364
365/// EnterMainSourceFile - Enter the specified FileID as the main source file,
Nate Begeman6b616022008-01-07 04:01:26 +0000366/// which implicitly adds the builtin defines etc.
Chris Lattnere127a0d2010-04-20 20:35:58 +0000367void Preprocessor::EnterMainSourceFile() {
Chris Lattner05db4272009-02-13 19:33:24 +0000368 // We do not allow the preprocessor to reenter the main file. Doing so will
369 // cause FileID's to accumulate information from both runs (e.g. #line
370 // information) and predefined macros aren't guaranteed to be set properly.
371 assert(NumEnteredSourceFiles == 0 && "Cannot reenter the main file!");
Chris Lattner2b2453a2009-01-17 06:22:33 +0000372 FileID MainFileID = SourceMgr.getMainFileID();
Mike Stump1eb44332009-09-09 15:08:12 +0000373
Chris Lattner53b0dab2007-10-09 22:10:18 +0000374 // Enter the main file source buffer.
Chris Lattnere127a0d2010-04-20 20:35:58 +0000375 EnterSourceFile(MainFileID, 0, SourceLocation());
Mike Stump1eb44332009-09-09 15:08:12 +0000376
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000377 // If we've been asked to skip bytes in the main file (e.g., as part of a
378 // precompiled preamble), do so now.
379 if (SkipMainFilePreamble.first > 0)
380 CurLexer->SkipBytes(SkipMainFilePreamble.first,
381 SkipMainFilePreamble.second);
382
Chris Lattnerb2832982007-11-15 19:07:47 +0000383 // Tell the header info that the main file was entered. If the file is later
384 // #imported, it won't be re-entered.
Chris Lattner2b2453a2009-01-17 06:22:33 +0000385 if (const FileEntry *FE = SourceMgr.getFileEntryForID(MainFileID))
Chris Lattnerb2832982007-11-15 19:07:47 +0000386 HeaderInfo.IncrementIncludeCount(FE);
Mike Stump1eb44332009-09-09 15:08:12 +0000387
Benjamin Kramerffd6e392009-12-31 15:33:09 +0000388 // Preprocess Predefines to populate the initial preprocessor state.
Mike Stump1eb44332009-09-09 15:08:12 +0000389 llvm::MemoryBuffer *SB =
Chris Lattnera0a270c2010-04-05 22:42:27 +0000390 llvm::MemoryBuffer::getMemBufferCopy(Predefines, "<built-in>");
Douglas Gregor043266b2010-08-26 14:07:34 +0000391 assert(SB && "Cannot create predefined source buffer");
Chris Lattner2b2453a2009-01-17 06:22:33 +0000392 FileID FID = SourceMgr.createFileIDForMemBuffer(SB);
393 assert(!FID.isInvalid() && "Could not create FileID for predefines?");
Mike Stump1eb44332009-09-09 15:08:12 +0000394
Chris Lattner53b0dab2007-10-09 22:10:18 +0000395 // Start parsing the predefines.
Chris Lattnere127a0d2010-04-20 20:35:58 +0000396 EnterSourceFile(FID, 0, SourceLocation());
Chris Lattner53b0dab2007-10-09 22:10:18 +0000397}
Chris Lattner97ba77c2007-07-16 06:48:38 +0000398
Daniel Dunbardbd82092010-03-23 05:09:10 +0000399void Preprocessor::EndSourceFile() {
400 // Notify the client that we reached the end of the source file.
401 if (Callbacks)
402 Callbacks->EndOfMainFile();
403}
Reid Spencer5f016e22007-07-11 17:01:13 +0000404
405//===----------------------------------------------------------------------===//
406// Lexer Event Handling.
407//===----------------------------------------------------------------------===//
408
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +0000409/// LookUpIdentifierInfo - Given a tok::raw_identifier token, look up the
410/// identifier information for the token and install it into the token,
411/// updating the token kind accordingly.
412IdentifierInfo *Preprocessor::LookUpIdentifierInfo(Token &Identifier) const {
413 assert(Identifier.getRawIdentifierData() != 0 && "No raw identifier data!");
Mike Stump1eb44332009-09-09 15:08:12 +0000414
Reid Spencer5f016e22007-07-11 17:01:13 +0000415 // Look up this token, see if it is a macro, or if it is a language keyword.
416 IdentifierInfo *II;
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +0000417 if (!Identifier.needsCleaning()) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000418 // No cleaning needed, just use the characters from the lexed buffer.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000419 II = getIdentifierInfo(StringRef(Identifier.getRawIdentifierData(),
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +0000420 Identifier.getLength()));
Reid Spencer5f016e22007-07-11 17:01:13 +0000421 } else {
422 // Cleaning needed, alloca a buffer, clean into it, then use the buffer.
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +0000423 llvm::SmallString<64> IdentifierBuffer;
Chris Lattner5f9e2722011-07-23 10:55:15 +0000424 StringRef CleanedStr = getSpelling(Identifier, IdentifierBuffer);
Benjamin Kramerddeea562010-02-27 13:44:12 +0000425 II = getIdentifierInfo(CleanedStr);
Reid Spencer5f016e22007-07-11 17:01:13 +0000426 }
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +0000427
428 // Update the token info (identifier info and appropriate token kind).
Reid Spencer5f016e22007-07-11 17:01:13 +0000429 Identifier.setIdentifierInfo(II);
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +0000430 Identifier.setKind(II->getTokenID());
431
Reid Spencer5f016e22007-07-11 17:01:13 +0000432 return II;
433}
434
John Wiegley28bbe4b2011-04-28 01:08:34 +0000435void Preprocessor::SetPoisonReason(IdentifierInfo *II, unsigned DiagID) {
436 PoisonReasons[II] = DiagID;
437}
438
439void Preprocessor::PoisonSEHIdentifiers(bool Poison) {
440 assert(Ident__exception_code && Ident__exception_info);
441 assert(Ident___exception_code && Ident___exception_info);
442 Ident__exception_code->setIsPoisoned(Poison);
443 Ident___exception_code->setIsPoisoned(Poison);
444 Ident_GetExceptionCode->setIsPoisoned(Poison);
445 Ident__exception_info->setIsPoisoned(Poison);
446 Ident___exception_info->setIsPoisoned(Poison);
447 Ident_GetExceptionInfo->setIsPoisoned(Poison);
448 Ident__abnormal_termination->setIsPoisoned(Poison);
449 Ident___abnormal_termination->setIsPoisoned(Poison);
450 Ident_AbnormalTermination->setIsPoisoned(Poison);
451}
452
453void Preprocessor::HandlePoisonedIdentifier(Token & Identifier) {
454 assert(Identifier.getIdentifierInfo() &&
455 "Can't handle identifiers without identifier info!");
456 llvm::DenseMap<IdentifierInfo*,unsigned>::const_iterator it =
457 PoisonReasons.find(Identifier.getIdentifierInfo());
458 if(it == PoisonReasons.end())
459 Diag(Identifier, diag::err_pp_used_poisoned_id);
460 else
461 Diag(Identifier,it->second) << Identifier.getIdentifierInfo();
462}
Reid Spencer5f016e22007-07-11 17:01:13 +0000463
464/// HandleIdentifier - This callback is invoked when the lexer reads an
465/// identifier. This callback looks up the identifier in the map and/or
466/// potentially macro expands it or turns it into a named token (like 'for').
Chris Lattner6a170eb2009-01-21 07:43:11 +0000467///
468/// Note that callers of this method are guarded by checking the
469/// IdentifierInfo's 'isHandleIdentifierCase' bit. If this method changes, the
470/// IdentifierInfo methods that compute these properties will need to change to
471/// match.
Chris Lattnerd2177732007-07-20 16:59:19 +0000472void Preprocessor::HandleIdentifier(Token &Identifier) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000473 assert(Identifier.getIdentifierInfo() &&
474 "Can't handle identifiers without identifier info!");
Mike Stump1eb44332009-09-09 15:08:12 +0000475
Reid Spencer5f016e22007-07-11 17:01:13 +0000476 IdentifierInfo &II = *Identifier.getIdentifierInfo();
477
478 // If this identifier was poisoned, and if it was not produced from a macro
479 // expansion, emit an error.
Ted Kremenek1a531572008-11-19 22:43:49 +0000480 if (II.isPoisoned() && CurPPLexer) {
John Wiegley28bbe4b2011-04-28 01:08:34 +0000481 HandlePoisonedIdentifier(Identifier);
Reid Spencer5f016e22007-07-11 17:01:13 +0000482 }
Mike Stump1eb44332009-09-09 15:08:12 +0000483
Reid Spencer5f016e22007-07-11 17:01:13 +0000484 // If this is a macro to be expanded, do it.
Chris Lattnercc1a8752007-10-07 08:44:20 +0000485 if (MacroInfo *MI = getMacroInfo(&II)) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000486 if (!DisableMacroExpansion && !Identifier.isExpandDisabled()) {
487 if (MI->isEnabled()) {
488 if (!HandleMacroExpandedIdentifier(Identifier, MI))
Douglas Gregor6be16fe2011-08-27 06:37:51 +0000489 return;
Reid Spencer5f016e22007-07-11 17:01:13 +0000490 } else {
491 // C99 6.10.3.4p2 says that a disabled macro may never again be
492 // expanded, even if it's in a context where it could be expanded in the
493 // future.
Chris Lattnerd2177732007-07-20 16:59:19 +0000494 Identifier.setFlag(Token::DisableExpand);
Reid Spencer5f016e22007-07-11 17:01:13 +0000495 }
496 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000497 }
498
499 // C++ 2.11p2: If this is an alternative representation of a C++ operator,
500 // then we act as if it is the actual operator and not the textual
501 // representation of it.
Fariborz Jahanianafbc6812010-09-03 17:33:04 +0000502 if (II.isCPlusPlusOperatorKeyword())
Reid Spencer5f016e22007-07-11 17:01:13 +0000503 Identifier.setIdentifierInfo(0);
504
Reid Spencer5f016e22007-07-11 17:01:13 +0000505 // If this is an extension token, diagnose its use.
Steve Naroffb4eaf9c2008-09-02 18:50:17 +0000506 // We avoid diagnosing tokens that originate from macro definitions.
Eli Friedman2962f4d2009-04-28 03:59:15 +0000507 // FIXME: This warning is disabled in cases where it shouldn't be,
508 // like "#define TY typeof", "TY(1) x".
509 if (II.isExtensionToken() && !DisableMacroExpansion)
Reid Spencer5f016e22007-07-11 17:01:13 +0000510 Diag(Identifier, diag::ext_token_used);
Douglas Gregor6aa52ec2011-08-26 23:56:07 +0000511}
512
513void Preprocessor::HandleModuleImport(Token &Import) {
514 // The token sequence
515 //
516 // __import__ identifier
517 //
518 // indicates a module import directive. We load the module and then
519 // leave the token sequence for the parser.
520 Token ModuleNameTok = LookAhead(0);
521 if (ModuleNameTok.getKind() != tok::identifier)
522 return;
523
524 (void)TheModuleLoader.loadModule(Import.getLocation(),
525 *ModuleNameTok.getIdentifierInfo(),
526 ModuleNameTok.getLocation());
527
528 // FIXME: Transmogrify __import__ into some kind of AST-only __import__ that
529 // is not recognized by the preprocessor but is recognized by the parser.
530 // It would also be useful to stash the ModuleKey somewhere, so we don't try
531 // to load the module twice.
Reid Spencer5f016e22007-07-11 17:01:13 +0000532}
Douglas Gregor2e222532009-07-02 17:08:52 +0000533
534void Preprocessor::AddCommentHandler(CommentHandler *Handler) {
535 assert(Handler && "NULL comment handler");
536 assert(std::find(CommentHandlers.begin(), CommentHandlers.end(), Handler) ==
537 CommentHandlers.end() && "Comment handler already registered");
538 CommentHandlers.push_back(Handler);
539}
540
541void Preprocessor::RemoveCommentHandler(CommentHandler *Handler) {
542 std::vector<CommentHandler *>::iterator Pos
543 = std::find(CommentHandlers.begin(), CommentHandlers.end(), Handler);
544 assert(Pos != CommentHandlers.end() && "Comment handler not registered");
545 CommentHandlers.erase(Pos);
546}
547
Chris Lattner046c2272010-01-18 22:35:47 +0000548bool Preprocessor::HandleComment(Token &result, SourceRange Comment) {
549 bool AnyPendingTokens = false;
Douglas Gregor2e222532009-07-02 17:08:52 +0000550 for (std::vector<CommentHandler *>::iterator H = CommentHandlers.begin(),
551 HEnd = CommentHandlers.end();
Chris Lattner046c2272010-01-18 22:35:47 +0000552 H != HEnd; ++H) {
553 if ((*H)->HandleComment(*this, Comment))
554 AnyPendingTokens = true;
555 }
556 if (!AnyPendingTokens || getCommentRetentionState())
557 return false;
558 Lex(result);
559 return true;
Douglas Gregor2e222532009-07-02 17:08:52 +0000560}
561
Douglas Gregor6aa52ec2011-08-26 23:56:07 +0000562ModuleLoader::~ModuleLoader() { }
563
Douglas Gregor2e222532009-07-02 17:08:52 +0000564CommentHandler::~CommentHandler() { }
Douglas Gregor94dc8f62010-03-19 16:15:56 +0000565
Douglas Gregorf44e8542010-08-24 19:08:16 +0000566CodeCompletionHandler::~CodeCompletionHandler() { }
567
Douglas Gregordca8ee82011-05-06 16:33:08 +0000568void Preprocessor::createPreprocessingRecord(
Chandler Carruth9e5bb852011-07-14 08:20:46 +0000569 bool IncludeNestedMacroExpansions) {
Douglas Gregor94dc8f62010-03-19 16:15:56 +0000570 if (Record)
571 return;
572
Chandler Carruth9e5bb852011-07-14 08:20:46 +0000573 Record = new PreprocessingRecord(IncludeNestedMacroExpansions);
Douglas Gregorb9e1b752010-03-19 17:12:43 +0000574 addPPCallbacks(Record);
Douglas Gregor94dc8f62010-03-19 16:15:56 +0000575}