blob: fdc18f878180ab80b15362930237d898f0018b45 [file] [log] [blame]
Chris Lattner22eb9722006-06-18 05:43:12 +00001//===--- Preprocess.cpp - C Language Family Preprocessor Implementation ---===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner5b12ab82007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattner22eb9722006-06-18 05:43:12 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the Preprocessor interface.
11//
12//===----------------------------------------------------------------------===//
13//
Chris Lattner22eb9722006-06-18 05:43:12 +000014// Options to support:
15// -H - Print the name of each header file used.
Chris Lattner1630c3c2009-02-06 06:45:26 +000016// -d[DNI] - Dump various things.
Chris Lattner22eb9722006-06-18 05:43:12 +000017// -fworking-directory - #line's with preprocessor's working dir.
18// -fpreprocessed
19// -dependency-file,-M,-MM,-MF,-MG,-MP,-MT,-MQ,-MD,-MMD
20// -W*
21// -w
22//
23// Messages to emit:
24// "Multiple include guards may be useful for:\n"
25//
Chris Lattner22eb9722006-06-18 05:43:12 +000026//===----------------------------------------------------------------------===//
27
28#include "clang/Lex/Preprocessor.h"
Chris Lattnerd19564b2009-12-15 01:51:03 +000029#include "MacroArgs.h"
Douglas Gregor9882a5a2010-01-04 19:18:44 +000030#include "clang/Lex/ExternalPreprocessorSource.h"
Chris Lattner07b019a2006-10-22 07:28:56 +000031#include "clang/Lex/HeaderSearch.h"
Chris Lattner22eb9722006-06-18 05:43:12 +000032#include "clang/Lex/MacroInfo.h"
Chris Lattnerb8761832006-06-24 21:31:03 +000033#include "clang/Lex/Pragma.h"
Douglas Gregor7f6d60d2010-03-19 16:15:56 +000034#include "clang/Lex/PreprocessingRecord.h"
Chris Lattner0b8cfc22006-06-28 06:49:17 +000035#include "clang/Lex/ScratchBuffer.h"
Chris Lattner60f36222009-01-29 05:15:15 +000036#include "clang/Lex/LexDiagnostic.h"
Douglas Gregor3a7ad252010-08-24 19:08:16 +000037#include "clang/Lex/CodeCompletionHandler.h"
Chris Lattner22eb9722006-06-18 05:43:12 +000038#include "clang/Basic/SourceManager.h"
Ted Kremeneka5c2c272009-02-12 03:26:59 +000039#include "clang/Basic/FileManager.h"
Chris Lattner81278c62006-10-14 19:03:49 +000040#include "clang/Basic/TargetInfo.h"
Chris Lattner5cd83512008-10-05 20:40:30 +000041#include "llvm/ADT/APFloat.h"
Chris Lattner7a4af3b2006-07-26 06:26:52 +000042#include "llvm/ADT/SmallVector.h"
Chris Lattner8a7003c2007-07-16 06:48:38 +000043#include "llvm/Support/MemoryBuffer.h"
Benjamin Kramer89b422c2009-08-23 12:08:50 +000044#include "llvm/Support/raw_ostream.h"
Chris Lattner22eb9722006-06-18 05:43:12 +000045using namespace clang;
46
47//===----------------------------------------------------------------------===//
Douglas Gregor9882a5a2010-01-04 19:18:44 +000048ExternalPreprocessorSource::~ExternalPreprocessorSource() { }
Chris Lattner22eb9722006-06-18 05:43:12 +000049
Chris Lattner02dffbd2006-10-14 07:50:21 +000050Preprocessor::Preprocessor(Diagnostic &diags, const LangOptions &opts,
Daniel Dunbar1b444192009-11-13 05:51:54 +000051 const TargetInfo &target, SourceManager &SM,
Ted Kremeneka705b042009-01-15 18:47:46 +000052 HeaderSearch &Headers,
Daniel Dunbar0c6c9302009-11-11 21:44:21 +000053 IdentifierInfoLookup* IILookup,
54 bool OwnsHeaders)
Chris Lattner83aba002009-03-13 21:17:43 +000055 : Diags(&diags), Features(opts), Target(target),FileMgr(Headers.getFileMgr()),
Chris Lattner5159f612010-11-23 08:35:12 +000056 SourceMgr(SM),
Argyrios Kyrtzidis71731d62010-11-03 22:45:23 +000057 HeaderInfo(Headers), ExternalSource(0),
Douglas Gregor3a7ad252010-08-24 19:08:16 +000058 Identifiers(opts, IILookup), BuiltinInfo(Target), CodeComplete(0),
59 CodeCompletionFile(0), SkipMainFilePreamble(0, true), CurPPLexer(0),
Ted Kremenekc8456f82010-10-19 22:15:20 +000060 CurDirLookup(0), Callbacks(0), MacroArgCache(0), Record(0), MIChainHead(0),
61 MICache(0) {
Chris Lattner0b8cfc22006-06-28 06:49:17 +000062 ScratchBuf = new ScratchBuffer(SourceMgr);
Chris Lattner0af3ba12009-04-13 01:29:17 +000063 CounterValue = 0; // __COUNTER__ starts at 0.
Daniel Dunbar0c6c9302009-11-11 21:44:21 +000064 OwnsHeaderSearch = OwnsHeaders;
Mike Stump11289f42009-09-09 15:08:12 +000065
Chris Lattner22eb9722006-06-18 05:43:12 +000066 // Clear stats.
Chris Lattner59a9ebd2006-10-18 05:34:33 +000067 NumDirectives = NumDefined = NumUndefined = NumPragma = 0;
Chris Lattner22eb9722006-06-18 05:43:12 +000068 NumIf = NumElse = NumEndif = 0;
Chris Lattner78186052006-07-09 00:45:31 +000069 NumEnteredSourceFiles = 0;
70 NumMacroExpanded = NumFnMacroExpanded = NumBuiltinMacroExpanded = 0;
Chris Lattner510ab612006-07-20 04:47:30 +000071 NumFastMacroExpanded = NumTokenPaste = NumFastTokenPaste = 0;
Mike Stump11289f42009-09-09 15:08:12 +000072 MaxIncludeStackDepth = 0;
Chris Lattner22eb9722006-06-18 05:43:12 +000073 NumSkipped = 0;
Chris Lattnerb352e3e2006-11-21 06:17:10 +000074
75 // Default to discarding comments.
76 KeepComments = false;
77 KeepMacroComments = false;
Mike Stump11289f42009-09-09 15:08:12 +000078
Chris Lattner22eb9722006-06-18 05:43:12 +000079 // Macro expansion is enabled.
80 DisableMacroExpansion = false;
Chris Lattneree8760b2006-07-15 07:42:55 +000081 InMacroArgs = false;
Chris Lattner285c0c12008-03-09 02:26:03 +000082 NumCachedTokenLexers = 0;
Chris Lattner0c885f52006-06-21 06:50:18 +000083
Argyrios Kyrtzidisb3dd1e02008-08-10 13:15:22 +000084 CachedLexPos = 0;
85
Douglas Gregor9882a5a2010-01-04 19:18:44 +000086 // We haven't read anything from the external source.
87 ReadMacrosFromExternalSource = false;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +000088
Chris Lattner8ff71992006-07-06 05:17:39 +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 Wiegley1c0675e2011-04-28 01:08:34 +000092 SetPoisonReason(Ident__VA_ARGS__,diag::ext_pp_bad_vaargs_use);
Mike Stump11289f42009-09-09 15:08:12 +000093
Chris Lattnerb8761832006-06-24 21:31:03 +000094 // Initialize the pragma handlers.
Argyrios Kyrtzidis36745fd2010-07-13 09:07:17 +000095 PragmaHandlers = new PragmaNamespace(llvm::StringRef());
Chris Lattnerb8761832006-06-24 21:31:03 +000096 RegisterBuiltinPragmas();
Mike Stump11289f42009-09-09 15:08:12 +000097
Chris Lattner677757a2006-06-28 05:26:32 +000098 // Initialize builtin macros like __LINE__ and friends.
99 RegisterBuiltinMacros();
John Wiegley1c0675e2011-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
Chris Lattner22eb9722006-06-18 05:43:12 +0000117}
118
119Preprocessor::~Preprocessor() {
Argyrios Kyrtzidis5d240d02008-08-23 12:12:06 +0000120 assert(BacktrackPositions.empty() && "EnableBacktrack/Backtrack imbalance!");
121
Chris Lattner69772b02006-07-02 20:34:39 +0000122 while (!IncludeMacroStack.empty()) {
123 delete IncludeMacroStack.back().TheLexer;
Chris Lattner285c0c12008-03-09 02:26:03 +0000124 delete IncludeMacroStack.back().TheTokenLexer;
Chris Lattner69772b02006-07-02 20:34:39 +0000125 IncludeMacroStack.pop_back();
Chris Lattner22eb9722006-06-18 05:43:12 +0000126 }
Chris Lattnerc43ddc82007-10-07 08:44:20 +0000127
128 // Free any macro definitions.
Ted Kremenekb865f7e2010-10-19 21:30:11 +0000129 for (MacroInfoChain *I = MIChainHead ; I ; I = I->Next)
Ted Kremenek1f1e4bd2010-10-19 18:16:54 +0000130 I->MI.Destroy();
Mike Stump11289f42009-09-09 15:08:12 +0000131
Chris Lattnerc02c4ab2007-07-15 00:25:26 +0000132 // Free any cached macro expanders.
Chris Lattner285c0c12008-03-09 02:26:03 +0000133 for (unsigned i = 0, e = NumCachedTokenLexers; i != e; ++i)
134 delete TokenLexerCache[i];
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +0000135
Chris Lattnerd19564b2009-12-15 01:51:03 +0000136 // Free any cached MacroArgs.
137 for (MacroArgs *ArgList = MacroArgCache; ArgList; )
138 ArgList = ArgList->deallocate();
Mike Stump11289f42009-09-09 15:08:12 +0000139
Chris Lattnerb8761832006-06-24 21:31:03 +0000140 // Release pragma information.
141 delete PragmaHandlers;
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000142
143 // Delete the scratch buffer info.
144 delete ScratchBuf;
Chris Lattner22192932008-03-14 06:07:05 +0000145
Daniel Dunbar0c6c9302009-11-11 21:44:21 +0000146 // Delete the header search info, if we own it.
147 if (OwnsHeaderSearch)
148 delete &HeaderInfo;
149
Chris Lattner22192932008-03-14 06:07:05 +0000150 delete Callbacks;
Chris Lattner22eb9722006-06-18 05:43:12 +0000151}
152
Ted Kremeneka5c2c272009-02-12 03:26:59 +0000153void Preprocessor::setPTHManager(PTHManager* pm) {
154 PTH.reset(pm);
Douglas Gregord2eb58a2009-10-16 18:18:30 +0000155 FileMgr.addStatCache(PTH->createStatCache());
Ted Kremeneka5c2c272009-02-12 03:26:59 +0000156}
157
Chris Lattner146762e2007-07-20 16:59:19 +0000158void Preprocessor::DumpToken(const Token &Tok, bool DumpFlags) const {
Benjamin Kramer89b422c2009-08-23 12:08:50 +0000159 llvm::errs() << tok::getTokenName(Tok.getKind()) << " '"
160 << getSpelling(Tok) << "'";
Mike Stump11289f42009-09-09 15:08:12 +0000161
Chris Lattnerd01e2912006-06-18 16:22:51 +0000162 if (!DumpFlags) return;
Mike Stump11289f42009-09-09 15:08:12 +0000163
Benjamin Kramer89b422c2009-08-23 12:08:50 +0000164 llvm::errs() << "\t";
Chris Lattnerd01e2912006-06-18 16:22:51 +0000165 if (Tok.isAtStartOfLine())
Benjamin Kramer89b422c2009-08-23 12:08:50 +0000166 llvm::errs() << " [StartOfLine]";
Chris Lattnerd01e2912006-06-18 16:22:51 +0000167 if (Tok.hasLeadingSpace())
Benjamin Kramer89b422c2009-08-23 12:08:50 +0000168 llvm::errs() << " [LeadingSpace]";
Chris Lattner6e4bf522006-07-27 06:59:25 +0000169 if (Tok.isExpandDisabled())
Benjamin Kramer89b422c2009-08-23 12:08:50 +0000170 llvm::errs() << " [ExpandDisabled]";
Chris Lattnerd01e2912006-06-18 16:22:51 +0000171 if (Tok.needsCleaning()) {
Chris Lattner50b497e2006-06-18 16:32:35 +0000172 const char *Start = SourceMgr.getCharacterData(Tok.getLocation());
Benjamin Kramere8394df2010-08-11 14:47:12 +0000173 llvm::errs() << " [UnClean='" << llvm::StringRef(Start, Tok.getLength())
Benjamin Kramer89b422c2009-08-23 12:08:50 +0000174 << "']";
Chris Lattnerd01e2912006-06-18 16:22:51 +0000175 }
Mike Stump11289f42009-09-09 15:08:12 +0000176
Benjamin Kramer89b422c2009-08-23 12:08:50 +0000177 llvm::errs() << "\tLoc=<";
Chris Lattner615315f2007-12-09 20:31:55 +0000178 DumpLocation(Tok.getLocation());
Benjamin Kramer89b422c2009-08-23 12:08:50 +0000179 llvm::errs() << ">";
Chris Lattner615315f2007-12-09 20:31:55 +0000180}
181
182void Preprocessor::DumpLocation(SourceLocation Loc) const {
Chris Lattnerf1ca7d32009-01-27 07:57:44 +0000183 Loc.dump(SourceMgr);
Chris Lattnerd01e2912006-06-18 16:22:51 +0000184}
185
186void Preprocessor::DumpMacro(const MacroInfo &MI) const {
Benjamin Kramer89b422c2009-08-23 12:08:50 +0000187 llvm::errs() << "MACRO: ";
Chris Lattnerd01e2912006-06-18 16:22:51 +0000188 for (unsigned i = 0, e = MI.getNumTokens(); i != e; ++i) {
189 DumpToken(MI.getReplacementToken(i));
Benjamin Kramer89b422c2009-08-23 12:08:50 +0000190 llvm::errs() << " ";
Chris Lattnerd01e2912006-06-18 16:22:51 +0000191 }
Benjamin Kramer89b422c2009-08-23 12:08:50 +0000192 llvm::errs() << "\n";
Chris Lattnerd01e2912006-06-18 16:22:51 +0000193}
194
Chris Lattner22eb9722006-06-18 05:43:12 +0000195void Preprocessor::PrintStats() {
Benjamin Kramer89b422c2009-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";
Chris Lattner22eb9722006-06-18 05:43:12 +0000208
Benjamin Kramer89b422c2009-08-23 12:08:50 +0000209 llvm::errs() << NumMacroExpanded << "/" << NumFnMacroExpanded << "/"
Ted Kremeneka0a3e9b2008-01-14 16:44:48 +0000210 << NumBuiltinMacroExpanded << " obj/fn/builtin macros expanded, "
211 << NumFastMacroExpanded << " on the fast path.\n";
Benjamin Kramer89b422c2009-08-23 12:08:50 +0000212 llvm::errs() << (NumFastTokenPaste+NumTokenPaste)
Ted Kremeneka0a3e9b2008-01-14 16:44:48 +0000213 << " token paste (##) operations performed, "
214 << NumFastTokenPaste << " on the fast path.\n";
Chris Lattner22eb9722006-06-18 05:43:12 +0000215}
216
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +0000217Preprocessor::macro_iterator
218Preprocessor::macro_begin(bool IncludeExternalMacros) const {
219 if (IncludeExternalMacros && ExternalSource &&
Douglas Gregor9882a5a2010-01-04 19:18:44 +0000220 !ReadMacrosFromExternalSource) {
221 ReadMacrosFromExternalSource = true;
222 ExternalSource->ReadDefinedMacros();
223 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +0000224
225 return Macros.begin();
Douglas Gregor9882a5a2010-01-04 19:18:44 +0000226}
227
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +0000228Preprocessor::macro_iterator
229Preprocessor::macro_end(bool IncludeExternalMacros) const {
230 if (IncludeExternalMacros && ExternalSource &&
Douglas Gregor9882a5a2010-01-04 19:18:44 +0000231 !ReadMacrosFromExternalSource) {
232 ReadMacrosFromExternalSource = true;
233 ExternalSource->ReadDefinedMacros();
234 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +0000235
236 return Macros.end();
Douglas Gregor9882a5a2010-01-04 19:18:44 +0000237}
238
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +0000239bool Preprocessor::SetCodeCompletionPoint(const FileEntry *File,
240 unsigned TruncateAtLine,
Douglas Gregor53ad6b92009-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 Gregor26266da2010-03-16 19:49:24 +0000251 bool Invalid = false;
252 const MemoryBuffer *Buffer = SourceMgr.getMemoryBufferForFile(File, &Invalid);
253 if (Invalid)
Douglas Gregor53ad6b92009-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 Rajaratnamba2c6522010-03-13 10:17:05 +0000262
Douglas Gregor53ad6b92009-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 Rajaratnamba2c6522010-03-13 10:17:05 +0000271
Douglas Gregor9291ab62009-12-08 21:45:46 +0000272 Position += TruncateAtColumn - 1;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +0000273
Douglas Gregor53ad6b92009-12-02 06:49:09 +0000274 // Truncate the buffer.
Douglas Gregor9291ab62009-12-08 21:45:46 +0000275 if (Position < Buffer->getBufferEnd()) {
Chris Lattner58c79342010-04-05 22:42:27 +0000276 llvm::StringRef Data(Buffer->getBufferStart(),
277 Position-Buffer->getBufferStart());
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +0000278 MemoryBuffer *TruncatedBuffer
Chris Lattner58c79342010-04-05 22:42:27 +0000279 = MemoryBuffer::getMemBufferCopy(Data, Buffer->getBufferIdentifier());
Douglas Gregor53ad6b92009-12-02 06:49:09 +0000280 SourceMgr.overrideFileContents(File, TruncatedBuffer);
281 }
282
283 return false;
284}
285
Douglas Gregor5f498832009-12-03 17:05:59 +0000286bool Preprocessor::isCodeCompletionFile(SourceLocation FileLoc) const {
Douglas Gregor53ad6b92009-12-02 06:49:09 +0000287 return CodeCompletionFile && FileLoc.isFileID() &&
288 SourceMgr.getFileEntryForID(SourceMgr.getFileID(FileLoc))
289 == CodeCompletionFile;
290}
291
Douglas Gregor11583702010-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 Kramera197fb62010-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 Gregor7bda4b82010-03-16 05:20:39 +0000303 llvm::SmallVectorImpl<char> &Buffer,
304 bool *Invalid) const {
Abramo Bagnaraea4f7c72010-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 Kramera197fb62010-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 Gregor7bda4b82010-03-16 05:20:39 +0000317 unsigned Len = getSpelling(Tok, Ptr, Invalid);
Benjamin Kramera197fb62010-02-27 17:05:45 +0000318 return llvm::StringRef(Ptr, Len);
319}
320
Chris Lattnerb94ec7b2006-07-14 06:54:10 +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 Lattner5a7971e2009-01-26 19:29:26 +0000324void Preprocessor::CreateString(const char *Buf, unsigned Len, Token &Tok,
325 SourceLocation InstantiationLoc) {
326 Tok.setLength(Len);
Mike Stump11289f42009-09-09 15:08:12 +0000327
Chris Lattner5a7971e2009-01-26 19:29:26 +0000328 const char *DestPtr;
329 SourceLocation Loc = ScratchBuf->getToken(Buf, Len, DestPtr);
Mike Stump11289f42009-09-09 15:08:12 +0000330
Chris Lattner5a7971e2009-01-26 19:29:26 +0000331 if (InstantiationLoc.isValid())
Chris Lattner9dc9c202009-02-15 20:52:18 +0000332 Loc = SourceMgr.createInstantiationLoc(Loc, InstantiationLoc,
333 InstantiationLoc, Len);
Chris Lattner5a7971e2009-01-26 19:29:26 +0000334 Tok.setLocation(Loc);
Mike Stump11289f42009-09-09 15:08:12 +0000335
Abramo Bagnaraea4f7c72010-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 Lattner5a7971e2009-01-26 19:29:26 +0000340 Tok.setLiteralData(DestPtr);
Chris Lattnerb94ec7b2006-07-14 06:54:10 +0000341}
342
343
Chris Lattner8a7003c2007-07-16 06:48:38 +0000344
Chris Lattner1f1b0db2007-10-09 22:10:18 +0000345//===----------------------------------------------------------------------===//
346// Preprocessor Initialization Methods
347//===----------------------------------------------------------------------===//
348
Chris Lattner1f1b0db2007-10-09 22:10:18 +0000349
350/// EnterMainSourceFile - Enter the specified FileID as the main source file,
Nate Begemanf7c3ff62008-01-07 04:01:26 +0000351/// which implicitly adds the builtin defines etc.
Chris Lattnerfb24a3a2010-04-20 20:35:58 +0000352void Preprocessor::EnterMainSourceFile() {
Chris Lattner9ef847b2009-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 Lattnerd32480d2009-01-17 06:22:33 +0000357 FileID MainFileID = SourceMgr.getMainFileID();
Mike Stump11289f42009-09-09 15:08:12 +0000358
Chris Lattner1f1b0db2007-10-09 22:10:18 +0000359 // Enter the main file source buffer.
Chris Lattnerfb24a3a2010-04-20 20:35:58 +0000360 EnterSourceFile(MainFileID, 0, SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +0000361
Douglas Gregor3f4bea02010-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 Lattner609d4132007-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 Lattnerd32480d2009-01-17 06:22:33 +0000370 if (const FileEntry *FE = SourceMgr.getFileEntryForID(MainFileID))
Chris Lattner609d4132007-11-15 19:07:47 +0000371 HeaderInfo.IncrementIncludeCount(FE);
Mike Stump11289f42009-09-09 15:08:12 +0000372
Benjamin Kramerd77adb52009-12-31 15:33:09 +0000373 // Preprocess Predefines to populate the initial preprocessor state.
Mike Stump11289f42009-09-09 15:08:12 +0000374 llvm::MemoryBuffer *SB =
Chris Lattner58c79342010-04-05 22:42:27 +0000375 llvm::MemoryBuffer::getMemBufferCopy(Predefines, "<built-in>");
Douglas Gregor33551892010-08-26 14:07:34 +0000376 assert(SB && "Cannot create predefined source buffer");
Chris Lattnerd32480d2009-01-17 06:22:33 +0000377 FileID FID = SourceMgr.createFileIDForMemBuffer(SB);
378 assert(!FID.isInvalid() && "Could not create FileID for predefines?");
Mike Stump11289f42009-09-09 15:08:12 +0000379
Chris Lattner1f1b0db2007-10-09 22:10:18 +0000380 // Start parsing the predefines.
Chris Lattnerfb24a3a2010-04-20 20:35:58 +0000381 EnterSourceFile(FID, 0, SourceLocation());
Chris Lattner1f1b0db2007-10-09 22:10:18 +0000382}
Chris Lattner8a7003c2007-07-16 06:48:38 +0000383
Daniel Dunbarcb9eaf52010-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}
Chris Lattner677757a2006-06-28 05:26:32 +0000389
390//===----------------------------------------------------------------------===//
391// Lexer Event Handling.
392//===----------------------------------------------------------------------===//
393
Abramo Bagnaraea4f7c72010-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 Stump11289f42009-09-09 15:08:12 +0000399
Chris Lattnercefc7682006-07-08 08:28:12 +0000400 // Look up this token, see if it is a macro, or if it is a language keyword.
401 IdentifierInfo *II;
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +0000402 if (!Identifier.needsCleaning()) {
Chris Lattnercefc7682006-07-08 08:28:12 +0000403 // No cleaning needed, just use the characters from the lexed buffer.
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +0000404 II = getIdentifierInfo(llvm::StringRef(Identifier.getRawIdentifierData(),
405 Identifier.getLength()));
Chris Lattnercefc7682006-07-08 08:28:12 +0000406 } else {
407 // Cleaning needed, alloca a buffer, clean into it, then use the buffer.
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +0000408 llvm::SmallString<64> IdentifierBuffer;
Benjamin Kramer0a1abd42010-02-27 13:44:12 +0000409 llvm::StringRef CleanedStr = getSpelling(Identifier, IdentifierBuffer);
410 II = getIdentifierInfo(CleanedStr);
Chris Lattnercefc7682006-07-08 08:28:12 +0000411 }
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +0000412
413 // Update the token info (identifier info and appropriate token kind).
Chris Lattner8c204872006-10-14 05:19:21 +0000414 Identifier.setIdentifierInfo(II);
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +0000415 Identifier.setKind(II->getTokenID());
416
Chris Lattnercefc7682006-07-08 08:28:12 +0000417 return II;
418}
419
John Wiegley1c0675e2011-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}
Chris Lattnercefc7682006-07-08 08:28:12 +0000448
Chris Lattner677757a2006-06-28 05:26:32 +0000449/// 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 Lattnerad89ec02009-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 Lattner146762e2007-07-20 16:59:19 +0000457void Preprocessor::HandleIdentifier(Token &Identifier) {
Chris Lattner0f1f5052006-07-20 04:16:23 +0000458 assert(Identifier.getIdentifierInfo() &&
459 "Can't handle identifiers without identifier info!");
Mike Stump11289f42009-09-09 15:08:12 +0000460
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000461 IdentifierInfo &II = *Identifier.getIdentifierInfo();
Chris Lattner677757a2006-06-28 05:26:32 +0000462
463 // If this identifier was poisoned, and if it was not produced from a macro
464 // expansion, emit an error.
Ted Kremeneka2c3c8d2008-11-19 22:43:49 +0000465 if (II.isPoisoned() && CurPPLexer) {
John Wiegley1c0675e2011-04-28 01:08:34 +0000466 HandlePoisonedIdentifier(Identifier);
Chris Lattner8ff71992006-07-06 05:17:39 +0000467 }
Mike Stump11289f42009-09-09 15:08:12 +0000468
Chris Lattner78186052006-07-09 00:45:31 +0000469 // If this is a macro to be expanded, do it.
Chris Lattnerc43ddc82007-10-07 08:44:20 +0000470 if (MacroInfo *MI = getMacroInfo(&II)) {
Chris Lattner6e4bf522006-07-27 06:59:25 +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 Lattner146762e2007-07-20 16:59:19 +0000479 Identifier.setFlag(Token::DisableExpand);
Chris Lattner6e4bf522006-07-27 06:59:25 +0000480 }
481 }
Chris Lattner063400e2006-10-14 19:54:15 +0000482 }
Chris Lattner677757a2006-06-28 05:26:32 +0000483
Chris Lattner5b9f4892006-11-21 17:23:33 +0000484 // 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 Jahanian9e42a952010-09-03 17:33:04 +0000487 if (II.isCPlusPlusOperatorKeyword())
Chris Lattner5b9f4892006-11-21 17:23:33 +0000488 Identifier.setIdentifierInfo(0);
489
Chris Lattner677757a2006-06-28 05:26:32 +0000490 // If this is an extension token, diagnose its use.
Steve Naroffc84e8b72008-09-02 18:50:17 +0000491 // We avoid diagnosing tokens that originate from macro definitions.
Eli Friedman6bba2ad2009-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)
Chris Lattner53621a52007-06-13 20:44:40 +0000495 Diag(Identifier, diag::ext_token_used);
Chris Lattner677757a2006-06-28 05:26:32 +0000496}
Douglas Gregorc6d5edd2009-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 Lattner87d02082010-01-18 22:35:47 +0000512bool Preprocessor::HandleComment(Token &result, SourceRange Comment) {
513 bool AnyPendingTokens = false;
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000514 for (std::vector<CommentHandler *>::iterator H = CommentHandlers.begin(),
515 HEnd = CommentHandlers.end();
Chris Lattner87d02082010-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 Gregorc6d5edd2009-07-02 17:08:52 +0000524}
525
526CommentHandler::~CommentHandler() { }
Douglas Gregor7f6d60d2010-03-19 16:15:56 +0000527
Douglas Gregor3a7ad252010-08-24 19:08:16 +0000528CodeCompletionHandler::~CodeCompletionHandler() { }
529
Douglas Gregor998caea2011-05-06 16:33:08 +0000530void Preprocessor::createPreprocessingRecord(
531 bool IncludeNestedMacroInstantiations) {
Douglas Gregor7f6d60d2010-03-19 16:15:56 +0000532 if (Record)
533 return;
534
Douglas Gregor998caea2011-05-06 16:33:08 +0000535 Record = new PreprocessingRecord(IncludeNestedMacroInstantiations);
Douglas Gregor7dc87222010-03-19 17:12:43 +0000536 addPPCallbacks(Record);
Douglas Gregor7f6d60d2010-03-19 16:15:56 +0000537}