blob: fdc18f878180ab80b15362930237d898f0018b45 [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"
Reid Spencer5f016e22007-07-11 17:01:13 +000038#include "clang/Basic/SourceManager.h"
Ted Kremenek337edcd2009-02-12 03:26:59 +000039#include "clang/Basic/FileManager.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000040#include "clang/Basic/TargetInfo.h"
Chris Lattner2db78dd2008-10-05 20:40:30 +000041#include "llvm/ADT/APFloat.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000042#include "llvm/ADT/SmallVector.h"
Chris Lattner97ba77c2007-07-16 06:48:38 +000043#include "llvm/Support/MemoryBuffer.h"
Benjamin Kramer6cb7c1a2009-08-23 12:08:50 +000044#include "llvm/Support/raw_ostream.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000045using namespace clang;
46
47//===----------------------------------------------------------------------===//
Douglas Gregor88a35862010-01-04 19:18:44 +000048ExternalPreprocessorSource::~ExternalPreprocessorSource() { }
Reid Spencer5f016e22007-07-11 17:01:13 +000049
50Preprocessor::Preprocessor(Diagnostic &diags, const LangOptions &opts,
Daniel Dunbar444be732009-11-13 05:51:54 +000051 const TargetInfo &target, SourceManager &SM,
Ted Kremenek72b1b152009-01-15 18:47:46 +000052 HeaderSearch &Headers,
Daniel Dunbar5814e652009-11-11 21:44:21 +000053 IdentifierInfoLookup* IILookup,
54 bool OwnsHeaders)
Chris Lattner836040f2009-03-13 21:17:43 +000055 : Diags(&diags), Features(opts), Target(target),FileMgr(Headers.getFileMgr()),
Chris Lattner39b49bc2010-11-23 08:35:12 +000056 SourceMgr(SM),
Argyrios Kyrtzidis389db162010-11-03 22:45:23 +000057 HeaderInfo(Headers), ExternalSource(0),
Douglas Gregorf44e8542010-08-24 19:08:16 +000058 Identifiers(opts, IILookup), BuiltinInfo(Target), CodeComplete(0),
59 CodeCompletionFile(0), SkipMainFilePreamble(0, true), CurPPLexer(0),
Ted Kremenek9714a232010-10-19 22:15:20 +000060 CurDirLookup(0), Callbacks(0), MacroArgCache(0), Record(0), MIChainHead(0),
61 MICache(0) {
Reid Spencer5f016e22007-07-11 17:01:13 +000062 ScratchBuf = new ScratchBuffer(SourceMgr);
Chris Lattnerc1f9d822009-04-13 01:29:17 +000063 CounterValue = 0; // __COUNTER__ starts at 0.
Daniel Dunbar5814e652009-11-11 21:44:21 +000064 OwnsHeaderSearch = OwnsHeaders;
Mike Stump1eb44332009-09-09 15:08:12 +000065
Reid Spencer5f016e22007-07-11 17:01:13 +000066 // Clear stats.
67 NumDirectives = NumDefined = NumUndefined = NumPragma = 0;
68 NumIf = NumElse = NumEndif = 0;
69 NumEnteredSourceFiles = 0;
70 NumMacroExpanded = NumFnMacroExpanded = NumBuiltinMacroExpanded = 0;
71 NumFastMacroExpanded = NumTokenPaste = NumFastTokenPaste = 0;
Mike Stump1eb44332009-09-09 15:08:12 +000072 MaxIncludeStackDepth = 0;
Reid Spencer5f016e22007-07-11 17:01:13 +000073 NumSkipped = 0;
74
75 // Default to discarding comments.
76 KeepComments = false;
77 KeepMacroComments = false;
Mike Stump1eb44332009-09-09 15:08:12 +000078
Reid Spencer5f016e22007-07-11 17:01:13 +000079 // Macro expansion is enabled.
80 DisableMacroExpansion = false;
81 InMacroArgs = false;
Chris Lattner6cfe7592008-03-09 02:26:03 +000082 NumCachedTokenLexers = 0;
Reid Spencer5f016e22007-07-11 17:01:13 +000083
Argyrios Kyrtzidis03db1b32008-08-10 13:15:22 +000084 CachedLexPos = 0;
85
Douglas Gregor88a35862010-01-04 19:18:44 +000086 // We haven't read anything from the external source.
87 ReadMacrosFromExternalSource = false;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +000088
Reid Spencer5f016e22007-07-11 17:01:13 +000089 // "Poison" __VA_ARGS__, which can only appear in the expansion of a macro.
90 // This gets unpoisoned where it is allowed.
91 (Ident__VA_ARGS__ = getIdentifierInfo("__VA_ARGS__"))->setIsPoisoned();
John Wiegley28bbe4b2011-04-28 01:08:34 +000092 SetPoisonReason(Ident__VA_ARGS__,diag::ext_pp_bad_vaargs_use);
Mike Stump1eb44332009-09-09 15:08:12 +000093
Reid Spencer5f016e22007-07-11 17:01:13 +000094 // Initialize the pragma handlers.
Argyrios Kyrtzidis9b36c3f2010-07-13 09:07:17 +000095 PragmaHandlers = new PragmaNamespace(llvm::StringRef());
Reid Spencer5f016e22007-07-11 17:01:13 +000096 RegisterBuiltinPragmas();
Mike Stump1eb44332009-09-09 15:08:12 +000097
Reid Spencer5f016e22007-07-11 17:01:13 +000098 // Initialize builtin macros like __LINE__ and friends.
99 RegisterBuiltinMacros();
John Wiegley28bbe4b2011-04-28 01:08:34 +0000100
101 if(Features.Borland) {
102 Ident__exception_info = getIdentifierInfo("_exception_info");
103 Ident___exception_info = getIdentifierInfo("__exception_info");
104 Ident_GetExceptionInfo = getIdentifierInfo("GetExceptionInformation");
105 Ident__exception_code = getIdentifierInfo("_exception_code");
106 Ident___exception_code = getIdentifierInfo("__exception_code");
107 Ident_GetExceptionCode = getIdentifierInfo("GetExceptionCode");
108 Ident__abnormal_termination = getIdentifierInfo("_abnormal_termination");
109 Ident___abnormal_termination = getIdentifierInfo("__abnormal_termination");
110 Ident_AbnormalTermination = getIdentifierInfo("AbnormalTermination");
111 } else {
112 Ident__exception_info = Ident__exception_code = Ident__abnormal_termination = 0;
113 Ident___exception_info = Ident___exception_code = Ident___abnormal_termination = 0;
114 Ident_GetExceptionInfo = Ident_GetExceptionCode = Ident_AbnormalTermination = 0;
115 }
116
Reid Spencer5f016e22007-07-11 17:01:13 +0000117}
118
119Preprocessor::~Preprocessor() {
Argyrios Kyrtzidis2174a4f2008-08-23 12:12:06 +0000120 assert(BacktrackPositions.empty() && "EnableBacktrack/Backtrack imbalance!");
121
Reid Spencer5f016e22007-07-11 17:01:13 +0000122 while (!IncludeMacroStack.empty()) {
123 delete IncludeMacroStack.back().TheLexer;
Chris Lattner6cfe7592008-03-09 02:26:03 +0000124 delete IncludeMacroStack.back().TheTokenLexer;
Reid Spencer5f016e22007-07-11 17:01:13 +0000125 IncludeMacroStack.pop_back();
126 }
Chris Lattnercc1a8752007-10-07 08:44:20 +0000127
128 // Free any macro definitions.
Ted Kremenek2a6b03a2010-10-19 21:30:11 +0000129 for (MacroInfoChain *I = MIChainHead ; I ; I = I->Next)
Ted Kremenekaf8fa252010-10-19 18:16:54 +0000130 I->MI.Destroy();
Mike Stump1eb44332009-09-09 15:08:12 +0000131
Chris Lattner9594acf2007-07-15 00:25:26 +0000132 // Free any cached macro expanders.
Chris Lattner6cfe7592008-03-09 02:26:03 +0000133 for (unsigned i = 0, e = NumCachedTokenLexers; i != e; ++i)
134 delete TokenLexerCache[i];
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +0000135
Chris Lattner23f77e52009-12-15 01:51:03 +0000136 // Free any cached MacroArgs.
137 for (MacroArgs *ArgList = MacroArgCache; ArgList; )
138 ArgList = ArgList->deallocate();
Mike Stump1eb44332009-09-09 15:08:12 +0000139
Reid Spencer5f016e22007-07-11 17:01:13 +0000140 // Release pragma information.
141 delete PragmaHandlers;
142
143 // Delete the scratch buffer info.
144 delete ScratchBuf;
Chris Lattnereb50ed82008-03-14 06:07:05 +0000145
Daniel Dunbar5814e652009-11-11 21:44:21 +0000146 // Delete the header search info, if we own it.
147 if (OwnsHeaderSearch)
148 delete &HeaderInfo;
149
Chris Lattnereb50ed82008-03-14 06:07:05 +0000150 delete Callbacks;
Reid Spencer5f016e22007-07-11 17:01:13 +0000151}
152
Ted Kremenek337edcd2009-02-12 03:26:59 +0000153void Preprocessor::setPTHManager(PTHManager* pm) {
154 PTH.reset(pm);
Douglas Gregor52e71082009-10-16 18:18:30 +0000155 FileMgr.addStatCache(PTH->createStatCache());
Ted Kremenek337edcd2009-02-12 03:26:59 +0000156}
157
Chris Lattnerd2177732007-07-20 16:59:19 +0000158void Preprocessor::DumpToken(const Token &Tok, bool DumpFlags) const {
Benjamin Kramer6cb7c1a2009-08-23 12:08:50 +0000159 llvm::errs() << tok::getTokenName(Tok.getKind()) << " '"
160 << getSpelling(Tok) << "'";
Mike Stump1eb44332009-09-09 15:08:12 +0000161
Reid Spencer5f016e22007-07-11 17:01:13 +0000162 if (!DumpFlags) return;
Mike Stump1eb44332009-09-09 15:08:12 +0000163
Benjamin Kramer6cb7c1a2009-08-23 12:08:50 +0000164 llvm::errs() << "\t";
Reid Spencer5f016e22007-07-11 17:01:13 +0000165 if (Tok.isAtStartOfLine())
Benjamin Kramer6cb7c1a2009-08-23 12:08:50 +0000166 llvm::errs() << " [StartOfLine]";
Reid Spencer5f016e22007-07-11 17:01:13 +0000167 if (Tok.hasLeadingSpace())
Benjamin Kramer6cb7c1a2009-08-23 12:08:50 +0000168 llvm::errs() << " [LeadingSpace]";
Reid Spencer5f016e22007-07-11 17:01:13 +0000169 if (Tok.isExpandDisabled())
Benjamin Kramer6cb7c1a2009-08-23 12:08:50 +0000170 llvm::errs() << " [ExpandDisabled]";
Reid Spencer5f016e22007-07-11 17:01:13 +0000171 if (Tok.needsCleaning()) {
172 const char *Start = SourceMgr.getCharacterData(Tok.getLocation());
Benjamin Kramer476d8b82010-08-11 14:47:12 +0000173 llvm::errs() << " [UnClean='" << llvm::StringRef(Start, Tok.getLength())
Benjamin Kramer6cb7c1a2009-08-23 12:08:50 +0000174 << "']";
Reid Spencer5f016e22007-07-11 17:01:13 +0000175 }
Mike Stump1eb44332009-09-09 15:08:12 +0000176
Benjamin Kramer6cb7c1a2009-08-23 12:08:50 +0000177 llvm::errs() << "\tLoc=<";
Chris Lattnerc3d8d572007-12-09 20:31:55 +0000178 DumpLocation(Tok.getLocation());
Benjamin Kramer6cb7c1a2009-08-23 12:08:50 +0000179 llvm::errs() << ">";
Chris Lattnerc3d8d572007-12-09 20:31:55 +0000180}
181
182void Preprocessor::DumpLocation(SourceLocation Loc) const {
Chris Lattnerb9c3f962009-01-27 07:57:44 +0000183 Loc.dump(SourceMgr);
Reid Spencer5f016e22007-07-11 17:01:13 +0000184}
185
186void Preprocessor::DumpMacro(const MacroInfo &MI) const {
Benjamin Kramer6cb7c1a2009-08-23 12:08:50 +0000187 llvm::errs() << "MACRO: ";
Reid Spencer5f016e22007-07-11 17:01:13 +0000188 for (unsigned i = 0, e = MI.getNumTokens(); i != e; ++i) {
189 DumpToken(MI.getReplacementToken(i));
Benjamin Kramer6cb7c1a2009-08-23 12:08:50 +0000190 llvm::errs() << " ";
Reid Spencer5f016e22007-07-11 17:01:13 +0000191 }
Benjamin Kramer6cb7c1a2009-08-23 12:08:50 +0000192 llvm::errs() << "\n";
Reid Spencer5f016e22007-07-11 17:01:13 +0000193}
194
195void Preprocessor::PrintStats() {
Benjamin Kramer6cb7c1a2009-08-23 12:08:50 +0000196 llvm::errs() << "\n*** Preprocessor Stats:\n";
197 llvm::errs() << NumDirectives << " directives found:\n";
198 llvm::errs() << " " << NumDefined << " #define.\n";
199 llvm::errs() << " " << NumUndefined << " #undef.\n";
200 llvm::errs() << " #include/#include_next/#import:\n";
201 llvm::errs() << " " << NumEnteredSourceFiles << " source files entered.\n";
202 llvm::errs() << " " << MaxIncludeStackDepth << " max include stack depth\n";
203 llvm::errs() << " " << NumIf << " #if/#ifndef/#ifdef.\n";
204 llvm::errs() << " " << NumElse << " #else/#elif.\n";
205 llvm::errs() << " " << NumEndif << " #endif.\n";
206 llvm::errs() << " " << NumPragma << " #pragma.\n";
207 llvm::errs() << NumSkipped << " #if/#ifndef#ifdef regions skipped\n";
Reid Spencer5f016e22007-07-11 17:01:13 +0000208
Benjamin Kramer6cb7c1a2009-08-23 12:08:50 +0000209 llvm::errs() << NumMacroExpanded << "/" << NumFnMacroExpanded << "/"
Ted Kremenekbdd30c22008-01-14 16:44:48 +0000210 << NumBuiltinMacroExpanded << " obj/fn/builtin macros expanded, "
211 << NumFastMacroExpanded << " on the fast path.\n";
Benjamin Kramer6cb7c1a2009-08-23 12:08:50 +0000212 llvm::errs() << (NumFastTokenPaste+NumTokenPaste)
Ted Kremenekbdd30c22008-01-14 16:44:48 +0000213 << " token paste (##) operations performed, "
214 << NumFastTokenPaste << " on the fast path.\n";
Reid Spencer5f016e22007-07-11 17:01:13 +0000215}
216
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +0000217Preprocessor::macro_iterator
218Preprocessor::macro_begin(bool IncludeExternalMacros) const {
219 if (IncludeExternalMacros && ExternalSource &&
Douglas Gregor88a35862010-01-04 19:18:44 +0000220 !ReadMacrosFromExternalSource) {
221 ReadMacrosFromExternalSource = true;
222 ExternalSource->ReadDefinedMacros();
223 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +0000224
225 return Macros.begin();
Douglas Gregor88a35862010-01-04 19:18:44 +0000226}
227
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +0000228Preprocessor::macro_iterator
229Preprocessor::macro_end(bool IncludeExternalMacros) const {
230 if (IncludeExternalMacros && ExternalSource &&
Douglas Gregor88a35862010-01-04 19:18:44 +0000231 !ReadMacrosFromExternalSource) {
232 ReadMacrosFromExternalSource = true;
233 ExternalSource->ReadDefinedMacros();
234 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +0000235
236 return Macros.end();
Douglas Gregor88a35862010-01-04 19:18:44 +0000237}
238
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +0000239bool Preprocessor::SetCodeCompletionPoint(const FileEntry *File,
240 unsigned TruncateAtLine,
Douglas Gregor29684422009-12-02 06:49:09 +0000241 unsigned TruncateAtColumn) {
242 using llvm::MemoryBuffer;
243
244 CodeCompletionFile = File;
245
246 // Okay to clear out the code-completion point by passing NULL.
247 if (!CodeCompletionFile)
248 return false;
249
250 // Load the actual file's contents.
Douglas Gregoraa38c3d2010-03-16 19:49:24 +0000251 bool Invalid = false;
252 const MemoryBuffer *Buffer = SourceMgr.getMemoryBufferForFile(File, &Invalid);
253 if (Invalid)
Douglas Gregor29684422009-12-02 06:49:09 +0000254 return true;
255
256 // Find the byte position of the truncation point.
257 const char *Position = Buffer->getBufferStart();
258 for (unsigned Line = 1; Line < TruncateAtLine; ++Line) {
259 for (; *Position; ++Position) {
260 if (*Position != '\r' && *Position != '\n')
261 continue;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +0000262
Douglas Gregor29684422009-12-02 06:49:09 +0000263 // Eat \r\n or \n\r as a single line.
264 if ((Position[1] == '\r' || Position[1] == '\n') &&
265 Position[0] != Position[1])
266 ++Position;
267 ++Position;
268 break;
269 }
270 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +0000271
Douglas Gregorb760fe82009-12-08 21:45:46 +0000272 Position += TruncateAtColumn - 1;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +0000273
Douglas Gregor29684422009-12-02 06:49:09 +0000274 // Truncate the buffer.
Douglas Gregorb760fe82009-12-08 21:45:46 +0000275 if (Position < Buffer->getBufferEnd()) {
Chris Lattnera0a270c2010-04-05 22:42:27 +0000276 llvm::StringRef Data(Buffer->getBufferStart(),
277 Position-Buffer->getBufferStart());
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +0000278 MemoryBuffer *TruncatedBuffer
Chris Lattnera0a270c2010-04-05 22:42:27 +0000279 = MemoryBuffer::getMemBufferCopy(Data, Buffer->getBufferIdentifier());
Douglas Gregor29684422009-12-02 06:49:09 +0000280 SourceMgr.overrideFileContents(File, TruncatedBuffer);
281 }
282
283 return false;
284}
285
Douglas Gregor109ae732009-12-03 17:05:59 +0000286bool Preprocessor::isCodeCompletionFile(SourceLocation FileLoc) const {
Douglas Gregor29684422009-12-02 06:49:09 +0000287 return CodeCompletionFile && FileLoc.isFileID() &&
288 SourceMgr.getFileEntryForID(SourceMgr.getFileID(FileLoc))
289 == CodeCompletionFile;
290}
291
Douglas Gregor55817af2010-08-25 17:04:25 +0000292void Preprocessor::CodeCompleteNaturalLanguage() {
293 SetCodeCompletionPoint(0, 0, 0);
294 getDiagnostics().setSuppressAllDiagnostics(true);
295 if (CodeComplete)
296 CodeComplete->CodeCompleteNaturalLanguage();
297}
298
Benjamin Kramer51f5fe32010-02-27 17:05:45 +0000299/// getSpelling - This method is used to get the spelling of a token into a
300/// SmallVector. Note that the returned StringRef may not point to the
301/// supplied buffer if a copy can be avoided.
302llvm::StringRef Preprocessor::getSpelling(const Token &Tok,
Douglas Gregor50f6af72010-03-16 05:20:39 +0000303 llvm::SmallVectorImpl<char> &Buffer,
304 bool *Invalid) const {
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +0000305 // NOTE: this has to be checked *before* testing for an IdentifierInfo.
306 if (Tok.isNot(tok::raw_identifier)) {
307 // Try the fast path.
308 if (const IdentifierInfo *II = Tok.getIdentifierInfo())
309 return II->getName();
310 }
Benjamin Kramer51f5fe32010-02-27 17:05:45 +0000311
312 // Resize the buffer if we need to copy into it.
313 if (Tok.needsCleaning())
314 Buffer.resize(Tok.getLength());
315
316 const char *Ptr = Buffer.data();
Douglas Gregor50f6af72010-03-16 05:20:39 +0000317 unsigned Len = getSpelling(Tok, Ptr, Invalid);
Benjamin Kramer51f5fe32010-02-27 17:05:45 +0000318 return llvm::StringRef(Ptr, Len);
319}
320
Reid Spencer5f016e22007-07-11 17:01:13 +0000321/// CreateString - Plop the specified string into a scratch buffer and return a
322/// location for it. If specified, the source location provides a source
323/// location for the token.
Chris Lattner47246be2009-01-26 19:29:26 +0000324void Preprocessor::CreateString(const char *Buf, unsigned Len, Token &Tok,
325 SourceLocation InstantiationLoc) {
326 Tok.setLength(Len);
Mike Stump1eb44332009-09-09 15:08:12 +0000327
Chris Lattner47246be2009-01-26 19:29:26 +0000328 const char *DestPtr;
329 SourceLocation Loc = ScratchBuf->getToken(Buf, Len, DestPtr);
Mike Stump1eb44332009-09-09 15:08:12 +0000330
Chris Lattner47246be2009-01-26 19:29:26 +0000331 if (InstantiationLoc.isValid())
Chris Lattnere7fb4842009-02-15 20:52:18 +0000332 Loc = SourceMgr.createInstantiationLoc(Loc, InstantiationLoc,
333 InstantiationLoc, Len);
Chris Lattner47246be2009-01-26 19:29:26 +0000334 Tok.setLocation(Loc);
Mike Stump1eb44332009-09-09 15:08:12 +0000335
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +0000336 // If this is a raw identifier or a literal token, set the pointer data.
337 if (Tok.is(tok::raw_identifier))
338 Tok.setRawIdentifierData(DestPtr);
339 else if (Tok.isLiteral())
Chris Lattner47246be2009-01-26 19:29:26 +0000340 Tok.setLiteralData(DestPtr);
Reid Spencer5f016e22007-07-11 17:01:13 +0000341}
342
343
Chris Lattner97ba77c2007-07-16 06:48:38 +0000344
Chris Lattner53b0dab2007-10-09 22:10:18 +0000345//===----------------------------------------------------------------------===//
346// Preprocessor Initialization Methods
347//===----------------------------------------------------------------------===//
348
Chris Lattner53b0dab2007-10-09 22:10:18 +0000349
350/// EnterMainSourceFile - Enter the specified FileID as the main source file,
Nate Begeman6b616022008-01-07 04:01:26 +0000351/// which implicitly adds the builtin defines etc.
Chris Lattnere127a0d2010-04-20 20:35:58 +0000352void Preprocessor::EnterMainSourceFile() {
Chris Lattner05db4272009-02-13 19:33:24 +0000353 // We do not allow the preprocessor to reenter the main file. Doing so will
354 // cause FileID's to accumulate information from both runs (e.g. #line
355 // information) and predefined macros aren't guaranteed to be set properly.
356 assert(NumEnteredSourceFiles == 0 && "Cannot reenter the main file!");
Chris Lattner2b2453a2009-01-17 06:22:33 +0000357 FileID MainFileID = SourceMgr.getMainFileID();
Mike Stump1eb44332009-09-09 15:08:12 +0000358
Chris Lattner53b0dab2007-10-09 22:10:18 +0000359 // Enter the main file source buffer.
Chris Lattnere127a0d2010-04-20 20:35:58 +0000360 EnterSourceFile(MainFileID, 0, SourceLocation());
Mike Stump1eb44332009-09-09 15:08:12 +0000361
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000362 // If we've been asked to skip bytes in the main file (e.g., as part of a
363 // precompiled preamble), do so now.
364 if (SkipMainFilePreamble.first > 0)
365 CurLexer->SkipBytes(SkipMainFilePreamble.first,
366 SkipMainFilePreamble.second);
367
Chris Lattnerb2832982007-11-15 19:07:47 +0000368 // Tell the header info that the main file was entered. If the file is later
369 // #imported, it won't be re-entered.
Chris Lattner2b2453a2009-01-17 06:22:33 +0000370 if (const FileEntry *FE = SourceMgr.getFileEntryForID(MainFileID))
Chris Lattnerb2832982007-11-15 19:07:47 +0000371 HeaderInfo.IncrementIncludeCount(FE);
Mike Stump1eb44332009-09-09 15:08:12 +0000372
Benjamin Kramerffd6e392009-12-31 15:33:09 +0000373 // Preprocess Predefines to populate the initial preprocessor state.
Mike Stump1eb44332009-09-09 15:08:12 +0000374 llvm::MemoryBuffer *SB =
Chris Lattnera0a270c2010-04-05 22:42:27 +0000375 llvm::MemoryBuffer::getMemBufferCopy(Predefines, "<built-in>");
Douglas Gregor043266b2010-08-26 14:07:34 +0000376 assert(SB && "Cannot create predefined source buffer");
Chris Lattner2b2453a2009-01-17 06:22:33 +0000377 FileID FID = SourceMgr.createFileIDForMemBuffer(SB);
378 assert(!FID.isInvalid() && "Could not create FileID for predefines?");
Mike Stump1eb44332009-09-09 15:08:12 +0000379
Chris Lattner53b0dab2007-10-09 22:10:18 +0000380 // Start parsing the predefines.
Chris Lattnere127a0d2010-04-20 20:35:58 +0000381 EnterSourceFile(FID, 0, SourceLocation());
Chris Lattner53b0dab2007-10-09 22:10:18 +0000382}
Chris Lattner97ba77c2007-07-16 06:48:38 +0000383
Daniel Dunbardbd82092010-03-23 05:09:10 +0000384void Preprocessor::EndSourceFile() {
385 // Notify the client that we reached the end of the source file.
386 if (Callbacks)
387 Callbacks->EndOfMainFile();
388}
Reid Spencer5f016e22007-07-11 17:01:13 +0000389
390//===----------------------------------------------------------------------===//
391// Lexer Event Handling.
392//===----------------------------------------------------------------------===//
393
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +0000394/// LookUpIdentifierInfo - Given a tok::raw_identifier token, look up the
395/// identifier information for the token and install it into the token,
396/// updating the token kind accordingly.
397IdentifierInfo *Preprocessor::LookUpIdentifierInfo(Token &Identifier) const {
398 assert(Identifier.getRawIdentifierData() != 0 && "No raw identifier data!");
Mike Stump1eb44332009-09-09 15:08:12 +0000399
Reid Spencer5f016e22007-07-11 17:01:13 +0000400 // Look up this token, see if it is a macro, or if it is a language keyword.
401 IdentifierInfo *II;
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +0000402 if (!Identifier.needsCleaning()) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000403 // No cleaning needed, just use the characters from the lexed buffer.
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +0000404 II = getIdentifierInfo(llvm::StringRef(Identifier.getRawIdentifierData(),
405 Identifier.getLength()));
Reid Spencer5f016e22007-07-11 17:01:13 +0000406 } else {
407 // Cleaning needed, alloca a buffer, clean into it, then use the buffer.
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +0000408 llvm::SmallString<64> IdentifierBuffer;
Benjamin Kramerddeea562010-02-27 13:44:12 +0000409 llvm::StringRef CleanedStr = getSpelling(Identifier, IdentifierBuffer);
410 II = getIdentifierInfo(CleanedStr);
Reid Spencer5f016e22007-07-11 17:01:13 +0000411 }
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +0000412
413 // Update the token info (identifier info and appropriate token kind).
Reid Spencer5f016e22007-07-11 17:01:13 +0000414 Identifier.setIdentifierInfo(II);
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +0000415 Identifier.setKind(II->getTokenID());
416
Reid Spencer5f016e22007-07-11 17:01:13 +0000417 return II;
418}
419
John Wiegley28bbe4b2011-04-28 01:08:34 +0000420void Preprocessor::SetPoisonReason(IdentifierInfo *II, unsigned DiagID) {
421 PoisonReasons[II] = DiagID;
422}
423
424void Preprocessor::PoisonSEHIdentifiers(bool Poison) {
425 assert(Ident__exception_code && Ident__exception_info);
426 assert(Ident___exception_code && Ident___exception_info);
427 Ident__exception_code->setIsPoisoned(Poison);
428 Ident___exception_code->setIsPoisoned(Poison);
429 Ident_GetExceptionCode->setIsPoisoned(Poison);
430 Ident__exception_info->setIsPoisoned(Poison);
431 Ident___exception_info->setIsPoisoned(Poison);
432 Ident_GetExceptionInfo->setIsPoisoned(Poison);
433 Ident__abnormal_termination->setIsPoisoned(Poison);
434 Ident___abnormal_termination->setIsPoisoned(Poison);
435 Ident_AbnormalTermination->setIsPoisoned(Poison);
436}
437
438void Preprocessor::HandlePoisonedIdentifier(Token & Identifier) {
439 assert(Identifier.getIdentifierInfo() &&
440 "Can't handle identifiers without identifier info!");
441 llvm::DenseMap<IdentifierInfo*,unsigned>::const_iterator it =
442 PoisonReasons.find(Identifier.getIdentifierInfo());
443 if(it == PoisonReasons.end())
444 Diag(Identifier, diag::err_pp_used_poisoned_id);
445 else
446 Diag(Identifier,it->second) << Identifier.getIdentifierInfo();
447}
Reid Spencer5f016e22007-07-11 17:01:13 +0000448
449/// HandleIdentifier - This callback is invoked when the lexer reads an
450/// identifier. This callback looks up the identifier in the map and/or
451/// potentially macro expands it or turns it into a named token (like 'for').
Chris Lattner6a170eb2009-01-21 07:43:11 +0000452///
453/// Note that callers of this method are guarded by checking the
454/// IdentifierInfo's 'isHandleIdentifierCase' bit. If this method changes, the
455/// IdentifierInfo methods that compute these properties will need to change to
456/// match.
Chris Lattnerd2177732007-07-20 16:59:19 +0000457void Preprocessor::HandleIdentifier(Token &Identifier) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000458 assert(Identifier.getIdentifierInfo() &&
459 "Can't handle identifiers without identifier info!");
Mike Stump1eb44332009-09-09 15:08:12 +0000460
Reid Spencer5f016e22007-07-11 17:01:13 +0000461 IdentifierInfo &II = *Identifier.getIdentifierInfo();
462
463 // If this identifier was poisoned, and if it was not produced from a macro
464 // expansion, emit an error.
Ted Kremenek1a531572008-11-19 22:43:49 +0000465 if (II.isPoisoned() && CurPPLexer) {
John Wiegley28bbe4b2011-04-28 01:08:34 +0000466 HandlePoisonedIdentifier(Identifier);
Reid Spencer5f016e22007-07-11 17:01:13 +0000467 }
Mike Stump1eb44332009-09-09 15:08:12 +0000468
Reid Spencer5f016e22007-07-11 17:01:13 +0000469 // If this is a macro to be expanded, do it.
Chris Lattnercc1a8752007-10-07 08:44:20 +0000470 if (MacroInfo *MI = getMacroInfo(&II)) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000471 if (!DisableMacroExpansion && !Identifier.isExpandDisabled()) {
472 if (MI->isEnabled()) {
473 if (!HandleMacroExpandedIdentifier(Identifier, MI))
474 return;
475 } else {
476 // C99 6.10.3.4p2 says that a disabled macro may never again be
477 // expanded, even if it's in a context where it could be expanded in the
478 // future.
Chris Lattnerd2177732007-07-20 16:59:19 +0000479 Identifier.setFlag(Token::DisableExpand);
Reid Spencer5f016e22007-07-11 17:01:13 +0000480 }
481 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000482 }
483
484 // C++ 2.11p2: If this is an alternative representation of a C++ operator,
485 // then we act as if it is the actual operator and not the textual
486 // representation of it.
Fariborz Jahanianafbc6812010-09-03 17:33:04 +0000487 if (II.isCPlusPlusOperatorKeyword())
Reid Spencer5f016e22007-07-11 17:01:13 +0000488 Identifier.setIdentifierInfo(0);
489
Reid Spencer5f016e22007-07-11 17:01:13 +0000490 // If this is an extension token, diagnose its use.
Steve Naroffb4eaf9c2008-09-02 18:50:17 +0000491 // We avoid diagnosing tokens that originate from macro definitions.
Eli Friedman2962f4d2009-04-28 03:59:15 +0000492 // FIXME: This warning is disabled in cases where it shouldn't be,
493 // like "#define TY typeof", "TY(1) x".
494 if (II.isExtensionToken() && !DisableMacroExpansion)
Reid Spencer5f016e22007-07-11 17:01:13 +0000495 Diag(Identifier, diag::ext_token_used);
496}
Douglas Gregor2e222532009-07-02 17:08:52 +0000497
498void Preprocessor::AddCommentHandler(CommentHandler *Handler) {
499 assert(Handler && "NULL comment handler");
500 assert(std::find(CommentHandlers.begin(), CommentHandlers.end(), Handler) ==
501 CommentHandlers.end() && "Comment handler already registered");
502 CommentHandlers.push_back(Handler);
503}
504
505void Preprocessor::RemoveCommentHandler(CommentHandler *Handler) {
506 std::vector<CommentHandler *>::iterator Pos
507 = std::find(CommentHandlers.begin(), CommentHandlers.end(), Handler);
508 assert(Pos != CommentHandlers.end() && "Comment handler not registered");
509 CommentHandlers.erase(Pos);
510}
511
Chris Lattner046c2272010-01-18 22:35:47 +0000512bool Preprocessor::HandleComment(Token &result, SourceRange Comment) {
513 bool AnyPendingTokens = false;
Douglas Gregor2e222532009-07-02 17:08:52 +0000514 for (std::vector<CommentHandler *>::iterator H = CommentHandlers.begin(),
515 HEnd = CommentHandlers.end();
Chris Lattner046c2272010-01-18 22:35:47 +0000516 H != HEnd; ++H) {
517 if ((*H)->HandleComment(*this, Comment))
518 AnyPendingTokens = true;
519 }
520 if (!AnyPendingTokens || getCommentRetentionState())
521 return false;
522 Lex(result);
523 return true;
Douglas Gregor2e222532009-07-02 17:08:52 +0000524}
525
526CommentHandler::~CommentHandler() { }
Douglas Gregor94dc8f62010-03-19 16:15:56 +0000527
Douglas Gregorf44e8542010-08-24 19:08:16 +0000528CodeCompletionHandler::~CodeCompletionHandler() { }
529
Douglas Gregordca8ee82011-05-06 16:33:08 +0000530void Preprocessor::createPreprocessingRecord(
531 bool IncludeNestedMacroInstantiations) {
Douglas Gregor94dc8f62010-03-19 16:15:56 +0000532 if (Record)
533 return;
534
Douglas Gregordca8ee82011-05-06 16:33:08 +0000535 Record = new PreprocessingRecord(IncludeNestedMacroInstantiations);
Douglas Gregorb9e1b752010-03-19 17:12:43 +0000536 addPPCallbacks(Record);
Douglas Gregor94dc8f62010-03-19 16:15:56 +0000537}