blob: 1d1687d84b9ad537d46c8c0cd749bcd3bb248b5d [file] [log] [blame]
Chris Lattner22eb9722006-06-18 05:43:12 +00001//===--- Preprocess.cpp - C Language Family Preprocessor Implementation ---===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner5b12ab82007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattner22eb9722006-06-18 05:43:12 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the Preprocessor interface.
11//
12//===----------------------------------------------------------------------===//
13//
Chris Lattner22eb9722006-06-18 05:43:12 +000014// Options to support:
15// -H - Print the name of each header file used.
Chris Lattner1630c3c2009-02-06 06:45:26 +000016// -d[DNI] - Dump various things.
Chris Lattner22eb9722006-06-18 05:43:12 +000017// -fworking-directory - #line's with preprocessor's working dir.
18// -fpreprocessed
19// -dependency-file,-M,-MM,-MF,-MG,-MP,-MT,-MQ,-MD,-MMD
20// -W*
21// -w
22//
23// Messages to emit:
24// "Multiple include guards may be useful for:\n"
25//
Chris Lattner22eb9722006-06-18 05:43:12 +000026//===----------------------------------------------------------------------===//
27
28#include "clang/Lex/Preprocessor.h"
Chris Lattnerd19564b2009-12-15 01:51:03 +000029#include "MacroArgs.h"
Douglas Gregor9882a5a2010-01-04 19:18:44 +000030#include "clang/Lex/ExternalPreprocessorSource.h"
Chris Lattner07b019a2006-10-22 07:28:56 +000031#include "clang/Lex/HeaderSearch.h"
Chris Lattner22eb9722006-06-18 05:43:12 +000032#include "clang/Lex/MacroInfo.h"
Chris Lattnerb8761832006-06-24 21:31:03 +000033#include "clang/Lex/Pragma.h"
Douglas Gregor7f6d60d2010-03-19 16:15:56 +000034#include "clang/Lex/PreprocessingRecord.h"
Chris Lattner0b8cfc22006-06-28 06:49:17 +000035#include "clang/Lex/ScratchBuffer.h"
Chris Lattner60f36222009-01-29 05:15:15 +000036#include "clang/Lex/LexDiagnostic.h"
Douglas Gregor3a7ad252010-08-24 19:08:16 +000037#include "clang/Lex/CodeCompletionHandler.h"
Douglas Gregor08142532011-08-26 23:56:07 +000038#include "clang/Lex/ModuleLoader.h"
Chris Lattner22eb9722006-06-18 05:43:12 +000039#include "clang/Basic/SourceManager.h"
Ted Kremeneka5c2c272009-02-12 03:26:59 +000040#include "clang/Basic/FileManager.h"
Chris Lattner81278c62006-10-14 19:03:49 +000041#include "clang/Basic/TargetInfo.h"
Chris Lattner5cd83512008-10-05 20:40:30 +000042#include "llvm/ADT/APFloat.h"
Chris Lattner7a4af3b2006-07-26 06:26:52 +000043#include "llvm/ADT/SmallVector.h"
Chris Lattner8a7003c2007-07-16 06:48:38 +000044#include "llvm/Support/MemoryBuffer.h"
Benjamin Kramer89b422c2009-08-23 12:08:50 +000045#include "llvm/Support/raw_ostream.h"
Ted Kremenek8b77fe72011-07-27 18:41:23 +000046#include "llvm/Support/Capacity.h"
Chris Lattner22eb9722006-06-18 05:43:12 +000047using namespace clang;
48
49//===----------------------------------------------------------------------===//
Douglas Gregor9882a5a2010-01-04 19:18:44 +000050ExternalPreprocessorSource::~ExternalPreprocessorSource() { }
Chris Lattner22eb9722006-06-18 05:43:12 +000051
Chris Lattner02dffbd2006-10-14 07:50:21 +000052Preprocessor::Preprocessor(Diagnostic &diags, const LangOptions &opts,
Daniel Dunbar1b444192009-11-13 05:51:54 +000053 const TargetInfo &target, SourceManager &SM,
Douglas Gregor08142532011-08-26 23:56:07 +000054 HeaderSearch &Headers, ModuleLoader &TheModuleLoader,
Daniel Dunbar0c6c9302009-11-11 21:44:21 +000055 IdentifierInfoLookup* IILookup,
56 bool OwnsHeaders)
Chris Lattner83aba002009-03-13 21:17:43 +000057 : Diags(&diags), Features(opts), Target(target),FileMgr(Headers.getFileMgr()),
Douglas Gregor08142532011-08-26 23:56:07 +000058 SourceMgr(SM), HeaderInfo(Headers), TheModuleLoader(TheModuleLoader),
59 ExternalSource(0),
Douglas Gregor3a7ad252010-08-24 19:08:16 +000060 Identifiers(opts, IILookup), BuiltinInfo(Target), CodeComplete(0),
61 CodeCompletionFile(0), SkipMainFilePreamble(0, true), CurPPLexer(0),
Ted Kremenekc8456f82010-10-19 22:15:20 +000062 CurDirLookup(0), Callbacks(0), MacroArgCache(0), Record(0), MIChainHead(0),
63 MICache(0) {
Chris Lattner0b8cfc22006-06-28 06:49:17 +000064 ScratchBuf = new ScratchBuffer(SourceMgr);
Chris Lattner0af3ba12009-04-13 01:29:17 +000065 CounterValue = 0; // __COUNTER__ starts at 0.
Daniel Dunbar0c6c9302009-11-11 21:44:21 +000066 OwnsHeaderSearch = OwnsHeaders;
Mike Stump11289f42009-09-09 15:08:12 +000067
Chris Lattner22eb9722006-06-18 05:43:12 +000068 // Clear stats.
Chris Lattner59a9ebd2006-10-18 05:34:33 +000069 NumDirectives = NumDefined = NumUndefined = NumPragma = 0;
Chris Lattner22eb9722006-06-18 05:43:12 +000070 NumIf = NumElse = NumEndif = 0;
Chris Lattner78186052006-07-09 00:45:31 +000071 NumEnteredSourceFiles = 0;
72 NumMacroExpanded = NumFnMacroExpanded = NumBuiltinMacroExpanded = 0;
Chris Lattner510ab612006-07-20 04:47:30 +000073 NumFastMacroExpanded = NumTokenPaste = NumFastTokenPaste = 0;
Mike Stump11289f42009-09-09 15:08:12 +000074 MaxIncludeStackDepth = 0;
Chris Lattner22eb9722006-06-18 05:43:12 +000075 NumSkipped = 0;
Chris Lattnerb352e3e2006-11-21 06:17:10 +000076
77 // Default to discarding comments.
78 KeepComments = false;
79 KeepMacroComments = false;
Mike Stump11289f42009-09-09 15:08:12 +000080
Chris Lattner22eb9722006-06-18 05:43:12 +000081 // Macro expansion is enabled.
82 DisableMacroExpansion = false;
Chris Lattneree8760b2006-07-15 07:42:55 +000083 InMacroArgs = false;
Chris Lattner285c0c12008-03-09 02:26:03 +000084 NumCachedTokenLexers = 0;
Chris Lattner0c885f52006-06-21 06:50:18 +000085
Argyrios Kyrtzidisb3dd1e02008-08-10 13:15:22 +000086 CachedLexPos = 0;
87
Douglas Gregor9882a5a2010-01-04 19:18:44 +000088 // We haven't read anything from the external source.
89 ReadMacrosFromExternalSource = false;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +000090
Chris Lattner8ff71992006-07-06 05:17:39 +000091 // "Poison" __VA_ARGS__, which can only appear in the expansion of a macro.
92 // This gets unpoisoned where it is allowed.
93 (Ident__VA_ARGS__ = getIdentifierInfo("__VA_ARGS__"))->setIsPoisoned();
John Wiegley1c0675e2011-04-28 01:08:34 +000094 SetPoisonReason(Ident__VA_ARGS__,diag::ext_pp_bad_vaargs_use);
Mike Stump11289f42009-09-09 15:08:12 +000095
Chris Lattnerb8761832006-06-24 21:31:03 +000096 // Initialize the pragma handlers.
Chris Lattner0e62c1c2011-07-23 10:55:15 +000097 PragmaHandlers = new PragmaNamespace(StringRef());
Chris Lattnerb8761832006-06-24 21:31:03 +000098 RegisterBuiltinPragmas();
Mike Stump11289f42009-09-09 15:08:12 +000099
Chris Lattner677757a2006-06-28 05:26:32 +0000100 // Initialize builtin macros like __LINE__ and friends.
101 RegisterBuiltinMacros();
John Wiegley1c0675e2011-04-28 01:08:34 +0000102
103 if(Features.Borland) {
104 Ident__exception_info = getIdentifierInfo("_exception_info");
105 Ident___exception_info = getIdentifierInfo("__exception_info");
106 Ident_GetExceptionInfo = getIdentifierInfo("GetExceptionInformation");
107 Ident__exception_code = getIdentifierInfo("_exception_code");
108 Ident___exception_code = getIdentifierInfo("__exception_code");
109 Ident_GetExceptionCode = getIdentifierInfo("GetExceptionCode");
110 Ident__abnormal_termination = getIdentifierInfo("_abnormal_termination");
111 Ident___abnormal_termination = getIdentifierInfo("__abnormal_termination");
112 Ident_AbnormalTermination = getIdentifierInfo("AbnormalTermination");
113 } else {
114 Ident__exception_info = Ident__exception_code = Ident__abnormal_termination = 0;
115 Ident___exception_info = Ident___exception_code = Ident___abnormal_termination = 0;
116 Ident_GetExceptionInfo = Ident_GetExceptionCode = Ident_AbnormalTermination = 0;
117 }
118
Chris Lattner22eb9722006-06-18 05:43:12 +0000119}
120
121Preprocessor::~Preprocessor() {
Argyrios Kyrtzidis5d240d02008-08-23 12:12:06 +0000122 assert(BacktrackPositions.empty() && "EnableBacktrack/Backtrack imbalance!");
Argyrios Kyrtzidis8cc04592011-06-29 22:20:11 +0000123 assert(MacroExpandingLexersStack.empty() && MacroExpandedTokens.empty() &&
124 "Preprocessor::HandleEndOfTokenLexer should have cleared those");
Argyrios Kyrtzidis5d240d02008-08-23 12:12:06 +0000125
Chris Lattner69772b02006-07-02 20:34:39 +0000126 while (!IncludeMacroStack.empty()) {
127 delete IncludeMacroStack.back().TheLexer;
Chris Lattner285c0c12008-03-09 02:26:03 +0000128 delete IncludeMacroStack.back().TheTokenLexer;
Chris Lattner69772b02006-07-02 20:34:39 +0000129 IncludeMacroStack.pop_back();
Chris Lattner22eb9722006-06-18 05:43:12 +0000130 }
Chris Lattnerc43ddc82007-10-07 08:44:20 +0000131
132 // Free any macro definitions.
Ted Kremenekb865f7e2010-10-19 21:30:11 +0000133 for (MacroInfoChain *I = MIChainHead ; I ; I = I->Next)
Ted Kremenek1f1e4bd2010-10-19 18:16:54 +0000134 I->MI.Destroy();
Mike Stump11289f42009-09-09 15:08:12 +0000135
Chris Lattnerc02c4ab2007-07-15 00:25:26 +0000136 // Free any cached macro expanders.
Chris Lattner285c0c12008-03-09 02:26:03 +0000137 for (unsigned i = 0, e = NumCachedTokenLexers; i != e; ++i)
138 delete TokenLexerCache[i];
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +0000139
Chris Lattnerd19564b2009-12-15 01:51:03 +0000140 // Free any cached MacroArgs.
141 for (MacroArgs *ArgList = MacroArgCache; ArgList; )
142 ArgList = ArgList->deallocate();
Mike Stump11289f42009-09-09 15:08:12 +0000143
Chris Lattnerb8761832006-06-24 21:31:03 +0000144 // Release pragma information.
145 delete PragmaHandlers;
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000146
147 // Delete the scratch buffer info.
148 delete ScratchBuf;
Chris Lattner22192932008-03-14 06:07:05 +0000149
Daniel Dunbar0c6c9302009-11-11 21:44:21 +0000150 // Delete the header search info, if we own it.
151 if (OwnsHeaderSearch)
152 delete &HeaderInfo;
153
Chris Lattner22192932008-03-14 06:07:05 +0000154 delete Callbacks;
Chris Lattner22eb9722006-06-18 05:43:12 +0000155}
156
Ted Kremeneka5c2c272009-02-12 03:26:59 +0000157void Preprocessor::setPTHManager(PTHManager* pm) {
158 PTH.reset(pm);
Douglas Gregord2eb58a2009-10-16 18:18:30 +0000159 FileMgr.addStatCache(PTH->createStatCache());
Ted Kremeneka5c2c272009-02-12 03:26:59 +0000160}
161
Chris Lattner146762e2007-07-20 16:59:19 +0000162void Preprocessor::DumpToken(const Token &Tok, bool DumpFlags) const {
Benjamin Kramer89b422c2009-08-23 12:08:50 +0000163 llvm::errs() << tok::getTokenName(Tok.getKind()) << " '"
164 << getSpelling(Tok) << "'";
Mike Stump11289f42009-09-09 15:08:12 +0000165
Chris Lattnerd01e2912006-06-18 16:22:51 +0000166 if (!DumpFlags) return;
Mike Stump11289f42009-09-09 15:08:12 +0000167
Benjamin Kramer89b422c2009-08-23 12:08:50 +0000168 llvm::errs() << "\t";
Chris Lattnerd01e2912006-06-18 16:22:51 +0000169 if (Tok.isAtStartOfLine())
Benjamin Kramer89b422c2009-08-23 12:08:50 +0000170 llvm::errs() << " [StartOfLine]";
Chris Lattnerd01e2912006-06-18 16:22:51 +0000171 if (Tok.hasLeadingSpace())
Benjamin Kramer89b422c2009-08-23 12:08:50 +0000172 llvm::errs() << " [LeadingSpace]";
Chris Lattner6e4bf522006-07-27 06:59:25 +0000173 if (Tok.isExpandDisabled())
Benjamin Kramer89b422c2009-08-23 12:08:50 +0000174 llvm::errs() << " [ExpandDisabled]";
Chris Lattnerd01e2912006-06-18 16:22:51 +0000175 if (Tok.needsCleaning()) {
Chris Lattner50b497e2006-06-18 16:32:35 +0000176 const char *Start = SourceMgr.getCharacterData(Tok.getLocation());
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000177 llvm::errs() << " [UnClean='" << StringRef(Start, Tok.getLength())
Benjamin Kramer89b422c2009-08-23 12:08:50 +0000178 << "']";
Chris Lattnerd01e2912006-06-18 16:22:51 +0000179 }
Mike Stump11289f42009-09-09 15:08:12 +0000180
Benjamin Kramer89b422c2009-08-23 12:08:50 +0000181 llvm::errs() << "\tLoc=<";
Chris Lattner615315f2007-12-09 20:31:55 +0000182 DumpLocation(Tok.getLocation());
Benjamin Kramer89b422c2009-08-23 12:08:50 +0000183 llvm::errs() << ">";
Chris Lattner615315f2007-12-09 20:31:55 +0000184}
185
186void Preprocessor::DumpLocation(SourceLocation Loc) const {
Chris Lattnerf1ca7d32009-01-27 07:57:44 +0000187 Loc.dump(SourceMgr);
Chris Lattnerd01e2912006-06-18 16:22:51 +0000188}
189
190void Preprocessor::DumpMacro(const MacroInfo &MI) const {
Benjamin Kramer89b422c2009-08-23 12:08:50 +0000191 llvm::errs() << "MACRO: ";
Chris Lattnerd01e2912006-06-18 16:22:51 +0000192 for (unsigned i = 0, e = MI.getNumTokens(); i != e; ++i) {
193 DumpToken(MI.getReplacementToken(i));
Benjamin Kramer89b422c2009-08-23 12:08:50 +0000194 llvm::errs() << " ";
Chris Lattnerd01e2912006-06-18 16:22:51 +0000195 }
Benjamin Kramer89b422c2009-08-23 12:08:50 +0000196 llvm::errs() << "\n";
Chris Lattnerd01e2912006-06-18 16:22:51 +0000197}
198
Chris Lattner22eb9722006-06-18 05:43:12 +0000199void Preprocessor::PrintStats() {
Benjamin Kramer89b422c2009-08-23 12:08:50 +0000200 llvm::errs() << "\n*** Preprocessor Stats:\n";
201 llvm::errs() << NumDirectives << " directives found:\n";
202 llvm::errs() << " " << NumDefined << " #define.\n";
203 llvm::errs() << " " << NumUndefined << " #undef.\n";
204 llvm::errs() << " #include/#include_next/#import:\n";
205 llvm::errs() << " " << NumEnteredSourceFiles << " source files entered.\n";
206 llvm::errs() << " " << MaxIncludeStackDepth << " max include stack depth\n";
207 llvm::errs() << " " << NumIf << " #if/#ifndef/#ifdef.\n";
208 llvm::errs() << " " << NumElse << " #else/#elif.\n";
209 llvm::errs() << " " << NumEndif << " #endif.\n";
210 llvm::errs() << " " << NumPragma << " #pragma.\n";
211 llvm::errs() << NumSkipped << " #if/#ifndef#ifdef regions skipped\n";
Chris Lattner22eb9722006-06-18 05:43:12 +0000212
Benjamin Kramer89b422c2009-08-23 12:08:50 +0000213 llvm::errs() << NumMacroExpanded << "/" << NumFnMacroExpanded << "/"
Ted Kremeneka0a3e9b2008-01-14 16:44:48 +0000214 << NumBuiltinMacroExpanded << " obj/fn/builtin macros expanded, "
215 << NumFastMacroExpanded << " on the fast path.\n";
Benjamin Kramer89b422c2009-08-23 12:08:50 +0000216 llvm::errs() << (NumFastTokenPaste+NumTokenPaste)
Ted Kremeneka0a3e9b2008-01-14 16:44:48 +0000217 << " token paste (##) operations performed, "
218 << NumFastTokenPaste << " on the fast path.\n";
Chris Lattner22eb9722006-06-18 05:43:12 +0000219}
220
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +0000221Preprocessor::macro_iterator
222Preprocessor::macro_begin(bool IncludeExternalMacros) const {
223 if (IncludeExternalMacros && ExternalSource &&
Douglas Gregor9882a5a2010-01-04 19:18:44 +0000224 !ReadMacrosFromExternalSource) {
225 ReadMacrosFromExternalSource = true;
226 ExternalSource->ReadDefinedMacros();
227 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +0000228
229 return Macros.begin();
Douglas Gregor9882a5a2010-01-04 19:18:44 +0000230}
231
Argyrios Kyrtzidise379ee32011-06-29 22:20:04 +0000232size_t Preprocessor::getTotalMemory() const {
Ted Kremenek182543a2011-07-26 21:17:24 +0000233 return BP.getTotalMemory()
Ted Kremenek8b77fe72011-07-27 18:41:23 +0000234 + llvm::capacity_in_bytes(MacroExpandedTokens)
Ted Kremenek182543a2011-07-26 21:17:24 +0000235 + Predefines.capacity() /* Predefines buffer. */
Ted Kremenek8b77fe72011-07-27 18:41:23 +0000236 + llvm::capacity_in_bytes(Macros)
237 + llvm::capacity_in_bytes(PragmaPushMacroInfo)
238 + llvm::capacity_in_bytes(PoisonReasons)
239 + llvm::capacity_in_bytes(CommentHandlers);
Argyrios Kyrtzidise379ee32011-06-29 22:20:04 +0000240}
241
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +0000242Preprocessor::macro_iterator
243Preprocessor::macro_end(bool IncludeExternalMacros) const {
244 if (IncludeExternalMacros && ExternalSource &&
Douglas Gregor9882a5a2010-01-04 19:18:44 +0000245 !ReadMacrosFromExternalSource) {
246 ReadMacrosFromExternalSource = true;
247 ExternalSource->ReadDefinedMacros();
248 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +0000249
250 return Macros.end();
Douglas Gregor9882a5a2010-01-04 19:18:44 +0000251}
252
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +0000253bool Preprocessor::SetCodeCompletionPoint(const FileEntry *File,
254 unsigned TruncateAtLine,
Douglas Gregor53ad6b92009-12-02 06:49:09 +0000255 unsigned TruncateAtColumn) {
256 using llvm::MemoryBuffer;
257
258 CodeCompletionFile = File;
259
260 // Okay to clear out the code-completion point by passing NULL.
261 if (!CodeCompletionFile)
262 return false;
263
264 // Load the actual file's contents.
Douglas Gregor26266da2010-03-16 19:49:24 +0000265 bool Invalid = false;
266 const MemoryBuffer *Buffer = SourceMgr.getMemoryBufferForFile(File, &Invalid);
267 if (Invalid)
Douglas Gregor53ad6b92009-12-02 06:49:09 +0000268 return true;
269
270 // Find the byte position of the truncation point.
271 const char *Position = Buffer->getBufferStart();
272 for (unsigned Line = 1; Line < TruncateAtLine; ++Line) {
273 for (; *Position; ++Position) {
274 if (*Position != '\r' && *Position != '\n')
275 continue;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +0000276
Douglas Gregor53ad6b92009-12-02 06:49:09 +0000277 // Eat \r\n or \n\r as a single line.
278 if ((Position[1] == '\r' || Position[1] == '\n') &&
279 Position[0] != Position[1])
280 ++Position;
281 ++Position;
282 break;
283 }
284 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +0000285
Douglas Gregor9291ab62009-12-08 21:45:46 +0000286 Position += TruncateAtColumn - 1;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +0000287
Douglas Gregor53ad6b92009-12-02 06:49:09 +0000288 // Truncate the buffer.
Douglas Gregor9291ab62009-12-08 21:45:46 +0000289 if (Position < Buffer->getBufferEnd()) {
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000290 StringRef Data(Buffer->getBufferStart(),
Chris Lattner58c79342010-04-05 22:42:27 +0000291 Position-Buffer->getBufferStart());
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +0000292 MemoryBuffer *TruncatedBuffer
Chris Lattner58c79342010-04-05 22:42:27 +0000293 = MemoryBuffer::getMemBufferCopy(Data, Buffer->getBufferIdentifier());
Douglas Gregor53ad6b92009-12-02 06:49:09 +0000294 SourceMgr.overrideFileContents(File, TruncatedBuffer);
295 }
296
297 return false;
298}
299
Douglas Gregor5f498832009-12-03 17:05:59 +0000300bool Preprocessor::isCodeCompletionFile(SourceLocation FileLoc) const {
Douglas Gregor53ad6b92009-12-02 06:49:09 +0000301 return CodeCompletionFile && FileLoc.isFileID() &&
302 SourceMgr.getFileEntryForID(SourceMgr.getFileID(FileLoc))
303 == CodeCompletionFile;
304}
305
Douglas Gregor11583702010-08-25 17:04:25 +0000306void Preprocessor::CodeCompleteNaturalLanguage() {
307 SetCodeCompletionPoint(0, 0, 0);
308 getDiagnostics().setSuppressAllDiagnostics(true);
309 if (CodeComplete)
310 CodeComplete->CodeCompleteNaturalLanguage();
311}
312
Benjamin Kramera197fb62010-02-27 17:05:45 +0000313/// getSpelling - This method is used to get the spelling of a token into a
314/// SmallVector. Note that the returned StringRef may not point to the
315/// supplied buffer if a copy can be avoided.
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000316StringRef Preprocessor::getSpelling(const Token &Tok,
317 SmallVectorImpl<char> &Buffer,
Douglas Gregor7bda4b82010-03-16 05:20:39 +0000318 bool *Invalid) const {
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +0000319 // NOTE: this has to be checked *before* testing for an IdentifierInfo.
320 if (Tok.isNot(tok::raw_identifier)) {
321 // Try the fast path.
322 if (const IdentifierInfo *II = Tok.getIdentifierInfo())
323 return II->getName();
324 }
Benjamin Kramera197fb62010-02-27 17:05:45 +0000325
326 // Resize the buffer if we need to copy into it.
327 if (Tok.needsCleaning())
328 Buffer.resize(Tok.getLength());
329
330 const char *Ptr = Buffer.data();
Douglas Gregor7bda4b82010-03-16 05:20:39 +0000331 unsigned Len = getSpelling(Tok, Ptr, Invalid);
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000332 return StringRef(Ptr, Len);
Benjamin Kramera197fb62010-02-27 17:05:45 +0000333}
334
Chris Lattnerb94ec7b2006-07-14 06:54:10 +0000335/// CreateString - Plop the specified string into a scratch buffer and return a
336/// location for it. If specified, the source location provides a source
337/// location for the token.
Chris Lattner5a7971e2009-01-26 19:29:26 +0000338void Preprocessor::CreateString(const char *Buf, unsigned Len, Token &Tok,
Chandler Carrutha88a22182011-07-14 08:20:46 +0000339 SourceLocation ExpansionLoc) {
Chris Lattner5a7971e2009-01-26 19:29:26 +0000340 Tok.setLength(Len);
Mike Stump11289f42009-09-09 15:08:12 +0000341
Chris Lattner5a7971e2009-01-26 19:29:26 +0000342 const char *DestPtr;
343 SourceLocation Loc = ScratchBuf->getToken(Buf, Len, DestPtr);
Mike Stump11289f42009-09-09 15:08:12 +0000344
Chandler Carrutha88a22182011-07-14 08:20:46 +0000345 if (ExpansionLoc.isValid())
Chandler Carruth115b0772011-07-26 03:03:05 +0000346 Loc = SourceMgr.createExpansionLoc(Loc, ExpansionLoc, ExpansionLoc, Len);
Chris Lattner5a7971e2009-01-26 19:29:26 +0000347 Tok.setLocation(Loc);
Mike Stump11289f42009-09-09 15:08:12 +0000348
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +0000349 // If this is a raw identifier or a literal token, set the pointer data.
350 if (Tok.is(tok::raw_identifier))
351 Tok.setRawIdentifierData(DestPtr);
352 else if (Tok.isLiteral())
Chris Lattner5a7971e2009-01-26 19:29:26 +0000353 Tok.setLiteralData(DestPtr);
Chris Lattnerb94ec7b2006-07-14 06:54:10 +0000354}
355
356
Chris Lattner8a7003c2007-07-16 06:48:38 +0000357
Chris Lattner1f1b0db2007-10-09 22:10:18 +0000358//===----------------------------------------------------------------------===//
359// Preprocessor Initialization Methods
360//===----------------------------------------------------------------------===//
361
Chris Lattner1f1b0db2007-10-09 22:10:18 +0000362
363/// EnterMainSourceFile - Enter the specified FileID as the main source file,
Nate Begemanf7c3ff62008-01-07 04:01:26 +0000364/// which implicitly adds the builtin defines etc.
Chris Lattnerfb24a3a2010-04-20 20:35:58 +0000365void Preprocessor::EnterMainSourceFile() {
Chris Lattner9ef847b2009-02-13 19:33:24 +0000366 // We do not allow the preprocessor to reenter the main file. Doing so will
367 // cause FileID's to accumulate information from both runs (e.g. #line
368 // information) and predefined macros aren't guaranteed to be set properly.
369 assert(NumEnteredSourceFiles == 0 && "Cannot reenter the main file!");
Chris Lattnerd32480d2009-01-17 06:22:33 +0000370 FileID MainFileID = SourceMgr.getMainFileID();
Mike Stump11289f42009-09-09 15:08:12 +0000371
Chris Lattner1f1b0db2007-10-09 22:10:18 +0000372 // Enter the main file source buffer.
Chris Lattnerfb24a3a2010-04-20 20:35:58 +0000373 EnterSourceFile(MainFileID, 0, SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +0000374
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000375 // If we've been asked to skip bytes in the main file (e.g., as part of a
376 // precompiled preamble), do so now.
377 if (SkipMainFilePreamble.first > 0)
378 CurLexer->SkipBytes(SkipMainFilePreamble.first,
379 SkipMainFilePreamble.second);
380
Chris Lattner609d4132007-11-15 19:07:47 +0000381 // Tell the header info that the main file was entered. If the file is later
382 // #imported, it won't be re-entered.
Chris Lattnerd32480d2009-01-17 06:22:33 +0000383 if (const FileEntry *FE = SourceMgr.getFileEntryForID(MainFileID))
Chris Lattner609d4132007-11-15 19:07:47 +0000384 HeaderInfo.IncrementIncludeCount(FE);
Mike Stump11289f42009-09-09 15:08:12 +0000385
Benjamin Kramerd77adb52009-12-31 15:33:09 +0000386 // Preprocess Predefines to populate the initial preprocessor state.
Mike Stump11289f42009-09-09 15:08:12 +0000387 llvm::MemoryBuffer *SB =
Chris Lattner58c79342010-04-05 22:42:27 +0000388 llvm::MemoryBuffer::getMemBufferCopy(Predefines, "<built-in>");
Douglas Gregor33551892010-08-26 14:07:34 +0000389 assert(SB && "Cannot create predefined source buffer");
Chris Lattnerd32480d2009-01-17 06:22:33 +0000390 FileID FID = SourceMgr.createFileIDForMemBuffer(SB);
391 assert(!FID.isInvalid() && "Could not create FileID for predefines?");
Mike Stump11289f42009-09-09 15:08:12 +0000392
Chris Lattner1f1b0db2007-10-09 22:10:18 +0000393 // Start parsing the predefines.
Chris Lattnerfb24a3a2010-04-20 20:35:58 +0000394 EnterSourceFile(FID, 0, SourceLocation());
Chris Lattner1f1b0db2007-10-09 22:10:18 +0000395}
Chris Lattner8a7003c2007-07-16 06:48:38 +0000396
Daniel Dunbarcb9eaf52010-03-23 05:09:10 +0000397void Preprocessor::EndSourceFile() {
398 // Notify the client that we reached the end of the source file.
399 if (Callbacks)
400 Callbacks->EndOfMainFile();
401}
Chris Lattner677757a2006-06-28 05:26:32 +0000402
403//===----------------------------------------------------------------------===//
404// Lexer Event Handling.
405//===----------------------------------------------------------------------===//
406
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +0000407/// LookUpIdentifierInfo - Given a tok::raw_identifier token, look up the
408/// identifier information for the token and install it into the token,
409/// updating the token kind accordingly.
410IdentifierInfo *Preprocessor::LookUpIdentifierInfo(Token &Identifier) const {
411 assert(Identifier.getRawIdentifierData() != 0 && "No raw identifier data!");
Mike Stump11289f42009-09-09 15:08:12 +0000412
Chris Lattnercefc7682006-07-08 08:28:12 +0000413 // Look up this token, see if it is a macro, or if it is a language keyword.
414 IdentifierInfo *II;
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +0000415 if (!Identifier.needsCleaning()) {
Chris Lattnercefc7682006-07-08 08:28:12 +0000416 // No cleaning needed, just use the characters from the lexed buffer.
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000417 II = getIdentifierInfo(StringRef(Identifier.getRawIdentifierData(),
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +0000418 Identifier.getLength()));
Chris Lattnercefc7682006-07-08 08:28:12 +0000419 } else {
420 // Cleaning needed, alloca a buffer, clean into it, then use the buffer.
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +0000421 llvm::SmallString<64> IdentifierBuffer;
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000422 StringRef CleanedStr = getSpelling(Identifier, IdentifierBuffer);
Benjamin Kramer0a1abd42010-02-27 13:44:12 +0000423 II = getIdentifierInfo(CleanedStr);
Chris Lattnercefc7682006-07-08 08:28:12 +0000424 }
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +0000425
426 // Update the token info (identifier info and appropriate token kind).
Chris Lattner8c204872006-10-14 05:19:21 +0000427 Identifier.setIdentifierInfo(II);
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +0000428 Identifier.setKind(II->getTokenID());
429
Chris Lattnercefc7682006-07-08 08:28:12 +0000430 return II;
431}
432
John Wiegley1c0675e2011-04-28 01:08:34 +0000433void Preprocessor::SetPoisonReason(IdentifierInfo *II, unsigned DiagID) {
434 PoisonReasons[II] = DiagID;
435}
436
437void Preprocessor::PoisonSEHIdentifiers(bool Poison) {
438 assert(Ident__exception_code && Ident__exception_info);
439 assert(Ident___exception_code && Ident___exception_info);
440 Ident__exception_code->setIsPoisoned(Poison);
441 Ident___exception_code->setIsPoisoned(Poison);
442 Ident_GetExceptionCode->setIsPoisoned(Poison);
443 Ident__exception_info->setIsPoisoned(Poison);
444 Ident___exception_info->setIsPoisoned(Poison);
445 Ident_GetExceptionInfo->setIsPoisoned(Poison);
446 Ident__abnormal_termination->setIsPoisoned(Poison);
447 Ident___abnormal_termination->setIsPoisoned(Poison);
448 Ident_AbnormalTermination->setIsPoisoned(Poison);
449}
450
451void Preprocessor::HandlePoisonedIdentifier(Token & Identifier) {
452 assert(Identifier.getIdentifierInfo() &&
453 "Can't handle identifiers without identifier info!");
454 llvm::DenseMap<IdentifierInfo*,unsigned>::const_iterator it =
455 PoisonReasons.find(Identifier.getIdentifierInfo());
456 if(it == PoisonReasons.end())
457 Diag(Identifier, diag::err_pp_used_poisoned_id);
458 else
459 Diag(Identifier,it->second) << Identifier.getIdentifierInfo();
460}
Chris Lattnercefc7682006-07-08 08:28:12 +0000461
Chris Lattner677757a2006-06-28 05:26:32 +0000462/// HandleIdentifier - This callback is invoked when the lexer reads an
463/// identifier. This callback looks up the identifier in the map and/or
464/// potentially macro expands it or turns it into a named token (like 'for').
Chris Lattnerad89ec02009-01-21 07:43:11 +0000465///
466/// Note that callers of this method are guarded by checking the
467/// IdentifierInfo's 'isHandleIdentifierCase' bit. If this method changes, the
468/// IdentifierInfo methods that compute these properties will need to change to
469/// match.
Chris Lattner146762e2007-07-20 16:59:19 +0000470void Preprocessor::HandleIdentifier(Token &Identifier) {
Chris Lattner0f1f5052006-07-20 04:16:23 +0000471 assert(Identifier.getIdentifierInfo() &&
472 "Can't handle identifiers without identifier info!");
Mike Stump11289f42009-09-09 15:08:12 +0000473
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000474 IdentifierInfo &II = *Identifier.getIdentifierInfo();
Chris Lattner677757a2006-06-28 05:26:32 +0000475
476 // If this identifier was poisoned, and if it was not produced from a macro
477 // expansion, emit an error.
Ted Kremeneka2c3c8d2008-11-19 22:43:49 +0000478 if (II.isPoisoned() && CurPPLexer) {
John Wiegley1c0675e2011-04-28 01:08:34 +0000479 HandlePoisonedIdentifier(Identifier);
Chris Lattner8ff71992006-07-06 05:17:39 +0000480 }
Mike Stump11289f42009-09-09 15:08:12 +0000481
Chris Lattner78186052006-07-09 00:45:31 +0000482 // If this is a macro to be expanded, do it.
Chris Lattnerc43ddc82007-10-07 08:44:20 +0000483 if (MacroInfo *MI = getMacroInfo(&II)) {
Chris Lattner6e4bf522006-07-27 06:59:25 +0000484 if (!DisableMacroExpansion && !Identifier.isExpandDisabled()) {
485 if (MI->isEnabled()) {
486 if (!HandleMacroExpandedIdentifier(Identifier, MI))
Douglas Gregor08142532011-08-26 23:56:07 +0000487 goto finish;
Chris Lattner6e4bf522006-07-27 06:59:25 +0000488 } else {
489 // C99 6.10.3.4p2 says that a disabled macro may never again be
490 // expanded, even if it's in a context where it could be expanded in the
491 // future.
Chris Lattner146762e2007-07-20 16:59:19 +0000492 Identifier.setFlag(Token::DisableExpand);
Chris Lattner6e4bf522006-07-27 06:59:25 +0000493 }
494 }
Chris Lattner063400e2006-10-14 19:54:15 +0000495 }
Chris Lattner677757a2006-06-28 05:26:32 +0000496
Chris Lattner5b9f4892006-11-21 17:23:33 +0000497 // C++ 2.11p2: If this is an alternative representation of a C++ operator,
498 // then we act as if it is the actual operator and not the textual
499 // representation of it.
Fariborz Jahanian9e42a952010-09-03 17:33:04 +0000500 if (II.isCPlusPlusOperatorKeyword())
Chris Lattner5b9f4892006-11-21 17:23:33 +0000501 Identifier.setIdentifierInfo(0);
502
Chris Lattner677757a2006-06-28 05:26:32 +0000503 // If this is an extension token, diagnose its use.
Steve Naroffc84e8b72008-09-02 18:50:17 +0000504 // We avoid diagnosing tokens that originate from macro definitions.
Eli Friedman6bba2ad2009-04-28 03:59:15 +0000505 // FIXME: This warning is disabled in cases where it shouldn't be,
506 // like "#define TY typeof", "TY(1) x".
507 if (II.isExtensionToken() && !DisableMacroExpansion)
Chris Lattner53621a52007-06-13 20:44:40 +0000508 Diag(Identifier, diag::ext_token_used);
Douglas Gregor08142532011-08-26 23:56:07 +0000509
510finish:
511 // If we have the start of a module import, handle it now.
512 if (Identifier.is(tok::kw___import__) &&
513 !InMacroArgs && !DisableMacroExpansion)
514 HandleModuleImport(Identifier);
515}
516
517void Preprocessor::HandleModuleImport(Token &Import) {
518 // The token sequence
519 //
520 // __import__ identifier
521 //
522 // indicates a module import directive. We load the module and then
523 // leave the token sequence for the parser.
524 Token ModuleNameTok = LookAhead(0);
525 if (ModuleNameTok.getKind() != tok::identifier)
526 return;
527
528 (void)TheModuleLoader.loadModule(Import.getLocation(),
529 *ModuleNameTok.getIdentifierInfo(),
530 ModuleNameTok.getLocation());
531
532 // FIXME: Transmogrify __import__ into some kind of AST-only __import__ that
533 // is not recognized by the preprocessor but is recognized by the parser.
534 // It would also be useful to stash the ModuleKey somewhere, so we don't try
535 // to load the module twice.
Chris Lattner677757a2006-06-28 05:26:32 +0000536}
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000537
538void Preprocessor::AddCommentHandler(CommentHandler *Handler) {
539 assert(Handler && "NULL comment handler");
540 assert(std::find(CommentHandlers.begin(), CommentHandlers.end(), Handler) ==
541 CommentHandlers.end() && "Comment handler already registered");
542 CommentHandlers.push_back(Handler);
543}
544
545void Preprocessor::RemoveCommentHandler(CommentHandler *Handler) {
546 std::vector<CommentHandler *>::iterator Pos
547 = std::find(CommentHandlers.begin(), CommentHandlers.end(), Handler);
548 assert(Pos != CommentHandlers.end() && "Comment handler not registered");
549 CommentHandlers.erase(Pos);
550}
551
Chris Lattner87d02082010-01-18 22:35:47 +0000552bool Preprocessor::HandleComment(Token &result, SourceRange Comment) {
553 bool AnyPendingTokens = false;
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000554 for (std::vector<CommentHandler *>::iterator H = CommentHandlers.begin(),
555 HEnd = CommentHandlers.end();
Chris Lattner87d02082010-01-18 22:35:47 +0000556 H != HEnd; ++H) {
557 if ((*H)->HandleComment(*this, Comment))
558 AnyPendingTokens = true;
559 }
560 if (!AnyPendingTokens || getCommentRetentionState())
561 return false;
562 Lex(result);
563 return true;
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000564}
565
Douglas Gregor08142532011-08-26 23:56:07 +0000566ModuleLoader::~ModuleLoader() { }
567
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000568CommentHandler::~CommentHandler() { }
Douglas Gregor7f6d60d2010-03-19 16:15:56 +0000569
Douglas Gregor3a7ad252010-08-24 19:08:16 +0000570CodeCompletionHandler::~CodeCompletionHandler() { }
571
Douglas Gregor998caea2011-05-06 16:33:08 +0000572void Preprocessor::createPreprocessingRecord(
Chandler Carrutha88a22182011-07-14 08:20:46 +0000573 bool IncludeNestedMacroExpansions) {
Douglas Gregor7f6d60d2010-03-19 16:15:56 +0000574 if (Record)
575 return;
576
Chandler Carrutha88a22182011-07-14 08:20:46 +0000577 Record = new PreprocessingRecord(IncludeNestedMacroExpansions);
Douglas Gregor7dc87222010-03-19 17:12:43 +0000578 addPPCallbacks(Record);
Douglas Gregor7f6d60d2010-03-19 16:15:56 +0000579}