blob: b420c6cd1d289db0bcc4da98466a5fe9f48de356 [file] [log] [blame]
Reid Spencer5f016e22007-07-11 17:01:13 +00001//===--- Preprocess.cpp - C Language Family Preprocessor Implementation ---===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Reid Spencer5f016e22007-07-11 17:01:13 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the Preprocessor interface.
11//
12//===----------------------------------------------------------------------===//
13//
14// Options to support:
15// -H - Print the name of each header file used.
Chris Lattnerf73903a2009-02-06 06:45:26 +000016// -d[DNI] - Dump various things.
Reid Spencer5f016e22007-07-11 17:01:13 +000017// -fworking-directory - #line's with preprocessor's working dir.
18// -fpreprocessed
19// -dependency-file,-M,-MM,-MF,-MG,-MP,-MT,-MQ,-MD,-MMD
20// -W*
21// -w
22//
23// Messages to emit:
24// "Multiple include guards may be useful for:\n"
25//
26//===----------------------------------------------------------------------===//
27
28#include "clang/Lex/Preprocessor.h"
Chris Lattner23f77e52009-12-15 01:51:03 +000029#include "MacroArgs.h"
Douglas Gregor88a35862010-01-04 19:18:44 +000030#include "clang/Lex/ExternalPreprocessorSource.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000031#include "clang/Lex/HeaderSearch.h"
32#include "clang/Lex/MacroInfo.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000033#include "clang/Lex/Pragma.h"
Douglas Gregor94dc8f62010-03-19 16:15:56 +000034#include "clang/Lex/PreprocessingRecord.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000035#include "clang/Lex/ScratchBuffer.h"
Chris Lattner500d3292009-01-29 05:15:15 +000036#include "clang/Lex/LexDiagnostic.h"
Douglas Gregorf44e8542010-08-24 19:08:16 +000037#include "clang/Lex/CodeCompletionHandler.h"
Douglas Gregor6aa52ec2011-08-26 23:56:07 +000038#include "clang/Lex/ModuleLoader.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000039#include "clang/Basic/SourceManager.h"
Ted Kremenek337edcd2009-02-12 03:26:59 +000040#include "clang/Basic/FileManager.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000041#include "clang/Basic/TargetInfo.h"
Chris Lattner2db78dd2008-10-05 20:40:30 +000042#include "llvm/ADT/APFloat.h"
Benjamin Kramer8fe83e12012-02-04 13:45:25 +000043#include "llvm/ADT/SmallString.h"
Chris Lattner97ba77c2007-07-16 06:48:38 +000044#include "llvm/Support/MemoryBuffer.h"
Benjamin Kramer6cb7c1a2009-08-23 12:08:50 +000045#include "llvm/Support/raw_ostream.h"
Ted Kremenek67485092011-07-27 18:41:23 +000046#include "llvm/Support/Capacity.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000047using namespace clang;
48
49//===----------------------------------------------------------------------===//
Douglas Gregor88a35862010-01-04 19:18:44 +000050ExternalPreprocessorSource::~ExternalPreprocessorSource() { }
Reid Spencer5f016e22007-07-11 17:01:13 +000051
David Blaikied6471f72011-09-25 23:23:43 +000052Preprocessor::Preprocessor(DiagnosticsEngine &diags, LangOptions &opts,
Douglas Gregor998b3d32011-09-01 23:39:15 +000053 const TargetInfo *target, SourceManager &SM,
Douglas Gregor6aa52ec2011-08-26 23:56:07 +000054 HeaderSearch &Headers, ModuleLoader &TheModuleLoader,
Daniel Dunbar5814e652009-11-11 21:44:21 +000055 IdentifierInfoLookup* IILookup,
Douglas Gregor998b3d32011-09-01 23:39:15 +000056 bool OwnsHeaders,
Axel Naumanne55329d2012-03-16 10:40:17 +000057 bool DelayInitialization,
58 bool IncrProcessing)
David Blaikie4e4d0842012-03-11 07:00:24 +000059 : Diags(&diags), LangOpts(opts), Target(target),FileMgr(Headers.getFileMgr()),
Douglas Gregor6aa52ec2011-08-26 23:56:07 +000060 SourceMgr(SM), HeaderInfo(Headers), TheModuleLoader(TheModuleLoader),
Axel Naumanne55329d2012-03-16 10:40:17 +000061 ExternalSource(0), Identifiers(opts, IILookup),
62 IncrementalProcessing(IncrProcessing), CodeComplete(0),
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +000063 CodeCompletionFile(0), CodeCompletionOffset(0), CodeCompletionReached(0),
64 SkipMainFilePreamble(0, true), CurPPLexer(0),
Zhongxing Xu7e7b5032011-09-26 03:37:43 +000065 CurDirLookup(0), CurLexerKind(CLK_Lexer), Callbacks(0), MacroArgCache(0),
66 Record(0), MIChainHead(0), MICache(0)
Douglas Gregor998b3d32011-09-01 23:39:15 +000067{
Daniel Dunbar5814e652009-11-11 21:44:21 +000068 OwnsHeaderSearch = OwnsHeaders;
Douglas Gregor998b3d32011-09-01 23:39:15 +000069
70 ScratchBuf = new ScratchBuffer(SourceMgr);
71 CounterValue = 0; // __COUNTER__ starts at 0.
72
73 // Clear stats.
74 NumDirectives = NumDefined = NumUndefined = NumPragma = 0;
75 NumIf = NumElse = NumEndif = 0;
76 NumEnteredSourceFiles = 0;
77 NumMacroExpanded = NumFnMacroExpanded = NumBuiltinMacroExpanded = 0;
78 NumFastMacroExpanded = NumTokenPaste = NumFastTokenPaste = 0;
79 MaxIncludeStackDepth = 0;
80 NumSkipped = 0;
81
82 // Default to discarding comments.
83 KeepComments = false;
84 KeepMacroComments = false;
85 SuppressIncludeNotFoundError = false;
86
87 // Macro expansion is enabled.
88 DisableMacroExpansion = false;
David Blaikie8c0b3782012-06-06 18:52:13 +000089 MacroExpansionInDirectivesOverride = false;
Douglas Gregor998b3d32011-09-01 23:39:15 +000090 InMacroArgs = false;
Argyrios Kyrtzidis14e64552012-04-03 16:47:40 +000091 InMacroArgPreExpansion = false;
Douglas Gregor998b3d32011-09-01 23:39:15 +000092 NumCachedTokenLexers = 0;
Jordan Rose6fe6a492012-06-08 18:06:21 +000093 PragmasEnabled = true;
94
Douglas Gregor998b3d32011-09-01 23:39:15 +000095 CachedLexPos = 0;
96
97 // We haven't read anything from the external source.
98 ReadMacrosFromExternalSource = false;
99
Douglas Gregor998b3d32011-09-01 23:39:15 +0000100 // "Poison" __VA_ARGS__, which can only appear in the expansion of a macro.
101 // This gets unpoisoned where it is allowed.
102 (Ident__VA_ARGS__ = getIdentifierInfo("__VA_ARGS__"))->setIsPoisoned();
103 SetPoisonReason(Ident__VA_ARGS__,diag::ext_pp_bad_vaargs_use);
104
105 // Initialize the pragma handlers.
106 PragmaHandlers = new PragmaNamespace(StringRef());
107 RegisterBuiltinPragmas();
108
109 // Initialize builtin macros like __LINE__ and friends.
110 RegisterBuiltinMacros();
111
David Blaikie4e4d0842012-03-11 07:00:24 +0000112 if(LangOpts.Borland) {
Douglas Gregor998b3d32011-09-01 23:39:15 +0000113 Ident__exception_info = getIdentifierInfo("_exception_info");
114 Ident___exception_info = getIdentifierInfo("__exception_info");
115 Ident_GetExceptionInfo = getIdentifierInfo("GetExceptionInformation");
116 Ident__exception_code = getIdentifierInfo("_exception_code");
117 Ident___exception_code = getIdentifierInfo("__exception_code");
118 Ident_GetExceptionCode = getIdentifierInfo("GetExceptionCode");
119 Ident__abnormal_termination = getIdentifierInfo("_abnormal_termination");
120 Ident___abnormal_termination = getIdentifierInfo("__abnormal_termination");
121 Ident_AbnormalTermination = getIdentifierInfo("AbnormalTermination");
122 } else {
123 Ident__exception_info = Ident__exception_code = Ident__abnormal_termination = 0;
124 Ident___exception_info = Ident___exception_code = Ident___abnormal_termination = 0;
125 Ident_GetExceptionInfo = Ident_GetExceptionCode = Ident_AbnormalTermination = 0;
Douglas Gregordc58aa72012-01-30 06:01:29 +0000126 }
Argyrios Kyrtzidis25c25962012-06-02 18:08:09 +0000127
128 if (!DelayInitialization) {
129 assert(Target && "Must provide target information for PP initialization");
130 Initialize(*Target);
131 }
132}
133
134Preprocessor::~Preprocessor() {
135 assert(BacktrackPositions.empty() && "EnableBacktrack/Backtrack imbalance!");
136
137 while (!IncludeMacroStack.empty()) {
138 delete IncludeMacroStack.back().TheLexer;
139 delete IncludeMacroStack.back().TheTokenLexer;
140 IncludeMacroStack.pop_back();
141 }
142
143 // Free any macro definitions.
144 for (MacroInfoChain *I = MIChainHead ; I ; I = I->Next)
145 I->MI.Destroy();
146
147 // Free any cached macro expanders.
148 for (unsigned i = 0, e = NumCachedTokenLexers; i != e; ++i)
149 delete TokenLexerCache[i];
150
151 // Free any cached MacroArgs.
152 for (MacroArgs *ArgList = MacroArgCache; ArgList; )
153 ArgList = ArgList->deallocate();
154
155 // Release pragma information.
156 delete PragmaHandlers;
157
158 // Delete the scratch buffer info.
159 delete ScratchBuf;
160
161 // Delete the header search info, if we own it.
162 if (OwnsHeaderSearch)
163 delete &HeaderInfo;
164
165 delete Callbacks;
166}
167
168void Preprocessor::Initialize(const TargetInfo &Target) {
169 assert((!this->Target || this->Target == &Target) &&
170 "Invalid override of target information");
171 this->Target = &Target;
Douglas Gregordc58aa72012-01-30 06:01:29 +0000172
Argyrios Kyrtzidis25c25962012-06-02 18:08:09 +0000173 // Initialize information about built-ins.
174 BuiltinInfo.InitializeTarget(Target);
Douglas Gregordc58aa72012-01-30 06:01:29 +0000175 HeaderInfo.setTarget(Target);
Douglas Gregor998b3d32011-09-01 23:39:15 +0000176}
177
Ted Kremenek337edcd2009-02-12 03:26:59 +0000178void Preprocessor::setPTHManager(PTHManager* pm) {
179 PTH.reset(pm);
Douglas Gregor52e71082009-10-16 18:18:30 +0000180 FileMgr.addStatCache(PTH->createStatCache());
Ted Kremenek337edcd2009-02-12 03:26:59 +0000181}
182
Chris Lattnerd2177732007-07-20 16:59:19 +0000183void Preprocessor::DumpToken(const Token &Tok, bool DumpFlags) const {
Benjamin Kramer6cb7c1a2009-08-23 12:08:50 +0000184 llvm::errs() << tok::getTokenName(Tok.getKind()) << " '"
185 << getSpelling(Tok) << "'";
Mike Stump1eb44332009-09-09 15:08:12 +0000186
Reid Spencer5f016e22007-07-11 17:01:13 +0000187 if (!DumpFlags) return;
Mike Stump1eb44332009-09-09 15:08:12 +0000188
Benjamin Kramer6cb7c1a2009-08-23 12:08:50 +0000189 llvm::errs() << "\t";
Reid Spencer5f016e22007-07-11 17:01:13 +0000190 if (Tok.isAtStartOfLine())
Benjamin Kramer6cb7c1a2009-08-23 12:08:50 +0000191 llvm::errs() << " [StartOfLine]";
Reid Spencer5f016e22007-07-11 17:01:13 +0000192 if (Tok.hasLeadingSpace())
Benjamin Kramer6cb7c1a2009-08-23 12:08:50 +0000193 llvm::errs() << " [LeadingSpace]";
Reid Spencer5f016e22007-07-11 17:01:13 +0000194 if (Tok.isExpandDisabled())
Benjamin Kramer6cb7c1a2009-08-23 12:08:50 +0000195 llvm::errs() << " [ExpandDisabled]";
Reid Spencer5f016e22007-07-11 17:01:13 +0000196 if (Tok.needsCleaning()) {
197 const char *Start = SourceMgr.getCharacterData(Tok.getLocation());
Chris Lattner5f9e2722011-07-23 10:55:15 +0000198 llvm::errs() << " [UnClean='" << StringRef(Start, Tok.getLength())
Benjamin Kramer6cb7c1a2009-08-23 12:08:50 +0000199 << "']";
Reid Spencer5f016e22007-07-11 17:01:13 +0000200 }
Mike Stump1eb44332009-09-09 15:08:12 +0000201
Benjamin Kramer6cb7c1a2009-08-23 12:08:50 +0000202 llvm::errs() << "\tLoc=<";
Chris Lattnerc3d8d572007-12-09 20:31:55 +0000203 DumpLocation(Tok.getLocation());
Benjamin Kramer6cb7c1a2009-08-23 12:08:50 +0000204 llvm::errs() << ">";
Chris Lattnerc3d8d572007-12-09 20:31:55 +0000205}
206
207void Preprocessor::DumpLocation(SourceLocation Loc) const {
Chris Lattnerb9c3f962009-01-27 07:57:44 +0000208 Loc.dump(SourceMgr);
Reid Spencer5f016e22007-07-11 17:01:13 +0000209}
210
211void Preprocessor::DumpMacro(const MacroInfo &MI) const {
Benjamin Kramer6cb7c1a2009-08-23 12:08:50 +0000212 llvm::errs() << "MACRO: ";
Reid Spencer5f016e22007-07-11 17:01:13 +0000213 for (unsigned i = 0, e = MI.getNumTokens(); i != e; ++i) {
214 DumpToken(MI.getReplacementToken(i));
Benjamin Kramer6cb7c1a2009-08-23 12:08:50 +0000215 llvm::errs() << " ";
Reid Spencer5f016e22007-07-11 17:01:13 +0000216 }
Benjamin Kramer6cb7c1a2009-08-23 12:08:50 +0000217 llvm::errs() << "\n";
Reid Spencer5f016e22007-07-11 17:01:13 +0000218}
219
220void Preprocessor::PrintStats() {
Benjamin Kramer6cb7c1a2009-08-23 12:08:50 +0000221 llvm::errs() << "\n*** Preprocessor Stats:\n";
222 llvm::errs() << NumDirectives << " directives found:\n";
223 llvm::errs() << " " << NumDefined << " #define.\n";
224 llvm::errs() << " " << NumUndefined << " #undef.\n";
225 llvm::errs() << " #include/#include_next/#import:\n";
226 llvm::errs() << " " << NumEnteredSourceFiles << " source files entered.\n";
227 llvm::errs() << " " << MaxIncludeStackDepth << " max include stack depth\n";
228 llvm::errs() << " " << NumIf << " #if/#ifndef/#ifdef.\n";
229 llvm::errs() << " " << NumElse << " #else/#elif.\n";
230 llvm::errs() << " " << NumEndif << " #endif.\n";
231 llvm::errs() << " " << NumPragma << " #pragma.\n";
232 llvm::errs() << NumSkipped << " #if/#ifndef#ifdef regions skipped\n";
Reid Spencer5f016e22007-07-11 17:01:13 +0000233
Benjamin Kramer6cb7c1a2009-08-23 12:08:50 +0000234 llvm::errs() << NumMacroExpanded << "/" << NumFnMacroExpanded << "/"
Ted Kremenekbdd30c22008-01-14 16:44:48 +0000235 << NumBuiltinMacroExpanded << " obj/fn/builtin macros expanded, "
236 << NumFastMacroExpanded << " on the fast path.\n";
Benjamin Kramer6cb7c1a2009-08-23 12:08:50 +0000237 llvm::errs() << (NumFastTokenPaste+NumTokenPaste)
Ted Kremenekbdd30c22008-01-14 16:44:48 +0000238 << " token paste (##) operations performed, "
239 << NumFastTokenPaste << " on the fast path.\n";
Reid Spencer5f016e22007-07-11 17:01:13 +0000240}
241
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +0000242Preprocessor::macro_iterator
243Preprocessor::macro_begin(bool IncludeExternalMacros) const {
244 if (IncludeExternalMacros && ExternalSource &&
Douglas Gregor88a35862010-01-04 19:18:44 +0000245 !ReadMacrosFromExternalSource) {
246 ReadMacrosFromExternalSource = true;
247 ExternalSource->ReadDefinedMacros();
248 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +0000249
250 return Macros.begin();
Douglas Gregor88a35862010-01-04 19:18:44 +0000251}
252
Argyrios Kyrtzidisc5c5e922011-06-29 22:20:04 +0000253size_t Preprocessor::getTotalMemory() const {
Ted Kremenek91d1bd62011-07-26 21:17:24 +0000254 return BP.getTotalMemory()
Ted Kremenek67485092011-07-27 18:41:23 +0000255 + llvm::capacity_in_bytes(MacroExpandedTokens)
Ted Kremenek91d1bd62011-07-26 21:17:24 +0000256 + Predefines.capacity() /* Predefines buffer. */
Ted Kremenek67485092011-07-27 18:41:23 +0000257 + llvm::capacity_in_bytes(Macros)
258 + llvm::capacity_in_bytes(PragmaPushMacroInfo)
259 + llvm::capacity_in_bytes(PoisonReasons)
260 + llvm::capacity_in_bytes(CommentHandlers);
Argyrios Kyrtzidisc5c5e922011-06-29 22:20:04 +0000261}
262
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +0000263Preprocessor::macro_iterator
264Preprocessor::macro_end(bool IncludeExternalMacros) const {
265 if (IncludeExternalMacros && ExternalSource &&
Douglas Gregor88a35862010-01-04 19:18:44 +0000266 !ReadMacrosFromExternalSource) {
267 ReadMacrosFromExternalSource = true;
268 ExternalSource->ReadDefinedMacros();
269 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +0000270
271 return Macros.end();
Douglas Gregor88a35862010-01-04 19:18:44 +0000272}
273
Douglas Gregord6aba062012-01-04 06:20:15 +0000274void Preprocessor::recomputeCurLexerKind() {
275 if (CurLexer)
276 CurLexerKind = CLK_Lexer;
277 else if (CurPTHLexer)
278 CurLexerKind = CLK_PTHLexer;
279 else if (CurTokenLexer)
280 CurLexerKind = CLK_TokenLexer;
281 else
282 CurLexerKind = CLK_CachingLexer;
283}
284
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +0000285bool Preprocessor::SetCodeCompletionPoint(const FileEntry *File,
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +0000286 unsigned CompleteLine,
287 unsigned CompleteColumn) {
288 assert(File);
289 assert(CompleteLine && CompleteColumn && "Starts from 1:1");
290 assert(!CodeCompletionFile && "Already set");
291
Douglas Gregor29684422009-12-02 06:49:09 +0000292 using llvm::MemoryBuffer;
293
Douglas Gregor29684422009-12-02 06:49:09 +0000294 // Load the actual file's contents.
Douglas Gregoraa38c3d2010-03-16 19:49:24 +0000295 bool Invalid = false;
296 const MemoryBuffer *Buffer = SourceMgr.getMemoryBufferForFile(File, &Invalid);
297 if (Invalid)
Douglas Gregor29684422009-12-02 06:49:09 +0000298 return true;
299
300 // Find the byte position of the truncation point.
301 const char *Position = Buffer->getBufferStart();
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +0000302 for (unsigned Line = 1; Line < CompleteLine; ++Line) {
Douglas Gregor29684422009-12-02 06:49:09 +0000303 for (; *Position; ++Position) {
304 if (*Position != '\r' && *Position != '\n')
305 continue;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +0000306
Douglas Gregor29684422009-12-02 06:49:09 +0000307 // Eat \r\n or \n\r as a single line.
308 if ((Position[1] == '\r' || Position[1] == '\n') &&
309 Position[0] != Position[1])
310 ++Position;
311 ++Position;
312 break;
313 }
314 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +0000315
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +0000316 Position += CompleteColumn - 1;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +0000317
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +0000318 // Insert '\0' at the code-completion point.
Douglas Gregorb760fe82009-12-08 21:45:46 +0000319 if (Position < Buffer->getBufferEnd()) {
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +0000320 CodeCompletionFile = File;
321 CodeCompletionOffset = Position - Buffer->getBufferStart();
322
323 MemoryBuffer *NewBuffer =
324 MemoryBuffer::getNewUninitMemBuffer(Buffer->getBufferSize() + 1,
325 Buffer->getBufferIdentifier());
Benjamin Kramer41a50a92011-09-04 20:26:28 +0000326 char *NewBuf = const_cast<char*>(NewBuffer->getBufferStart());
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +0000327 char *NewPos = std::copy(Buffer->getBufferStart(), Position, NewBuf);
328 *NewPos = '\0';
329 std::copy(Position, Buffer->getBufferEnd(), NewPos+1);
330 SourceMgr.overrideFileContents(File, NewBuffer);
Douglas Gregor29684422009-12-02 06:49:09 +0000331 }
332
333 return false;
334}
335
Douglas Gregor55817af2010-08-25 17:04:25 +0000336void Preprocessor::CodeCompleteNaturalLanguage() {
Douglas Gregor55817af2010-08-25 17:04:25 +0000337 if (CodeComplete)
338 CodeComplete->CodeCompleteNaturalLanguage();
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +0000339 setCodeCompletionReached();
Douglas Gregor55817af2010-08-25 17:04:25 +0000340}
341
Benjamin Kramer51f5fe32010-02-27 17:05:45 +0000342/// getSpelling - This method is used to get the spelling of a token into a
343/// SmallVector. Note that the returned StringRef may not point to the
344/// supplied buffer if a copy can be avoided.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000345StringRef Preprocessor::getSpelling(const Token &Tok,
346 SmallVectorImpl<char> &Buffer,
Douglas Gregor50f6af72010-03-16 05:20:39 +0000347 bool *Invalid) const {
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +0000348 // NOTE: this has to be checked *before* testing for an IdentifierInfo.
349 if (Tok.isNot(tok::raw_identifier)) {
350 // Try the fast path.
351 if (const IdentifierInfo *II = Tok.getIdentifierInfo())
352 return II->getName();
353 }
Benjamin Kramer51f5fe32010-02-27 17:05:45 +0000354
355 // Resize the buffer if we need to copy into it.
356 if (Tok.needsCleaning())
357 Buffer.resize(Tok.getLength());
358
359 const char *Ptr = Buffer.data();
Douglas Gregor50f6af72010-03-16 05:20:39 +0000360 unsigned Len = getSpelling(Tok, Ptr, Invalid);
Chris Lattner5f9e2722011-07-23 10:55:15 +0000361 return StringRef(Ptr, Len);
Benjamin Kramer51f5fe32010-02-27 17:05:45 +0000362}
363
Reid Spencer5f016e22007-07-11 17:01:13 +0000364/// CreateString - Plop the specified string into a scratch buffer and return a
365/// location for it. If specified, the source location provides a source
366/// location for the token.
Chris Lattner47246be2009-01-26 19:29:26 +0000367void Preprocessor::CreateString(const char *Buf, unsigned Len, Token &Tok,
Abramo Bagnaraa08529c2011-10-03 18:39:03 +0000368 SourceLocation ExpansionLocStart,
369 SourceLocation ExpansionLocEnd) {
Chris Lattner47246be2009-01-26 19:29:26 +0000370 Tok.setLength(Len);
Mike Stump1eb44332009-09-09 15:08:12 +0000371
Chris Lattner47246be2009-01-26 19:29:26 +0000372 const char *DestPtr;
373 SourceLocation Loc = ScratchBuf->getToken(Buf, Len, DestPtr);
Mike Stump1eb44332009-09-09 15:08:12 +0000374
Abramo Bagnaraa08529c2011-10-03 18:39:03 +0000375 if (ExpansionLocStart.isValid())
376 Loc = SourceMgr.createExpansionLoc(Loc, ExpansionLocStart,
377 ExpansionLocEnd, Len);
Chris Lattner47246be2009-01-26 19:29:26 +0000378 Tok.setLocation(Loc);
Mike Stump1eb44332009-09-09 15:08:12 +0000379
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +0000380 // If this is a raw identifier or a literal token, set the pointer data.
381 if (Tok.is(tok::raw_identifier))
382 Tok.setRawIdentifierData(DestPtr);
383 else if (Tok.isLiteral())
Chris Lattner47246be2009-01-26 19:29:26 +0000384 Tok.setLiteralData(DestPtr);
Reid Spencer5f016e22007-07-11 17:01:13 +0000385}
386
Douglas Gregor90db2602011-12-02 01:47:07 +0000387Module *Preprocessor::getCurrentModule() {
David Blaikie4e4d0842012-03-11 07:00:24 +0000388 if (getLangOpts().CurrentModule.empty())
Douglas Gregor90db2602011-12-02 01:47:07 +0000389 return 0;
390
David Blaikie4e4d0842012-03-11 07:00:24 +0000391 return getHeaderSearchInfo().lookupModule(getLangOpts().CurrentModule);
Douglas Gregor90db2602011-12-02 01:47:07 +0000392}
Chris Lattner97ba77c2007-07-16 06:48:38 +0000393
Chris Lattner53b0dab2007-10-09 22:10:18 +0000394//===----------------------------------------------------------------------===//
395// Preprocessor Initialization Methods
396//===----------------------------------------------------------------------===//
397
Chris Lattner53b0dab2007-10-09 22:10:18 +0000398
399/// EnterMainSourceFile - Enter the specified FileID as the main source file,
Nate Begeman6b616022008-01-07 04:01:26 +0000400/// which implicitly adds the builtin defines etc.
Chris Lattnere127a0d2010-04-20 20:35:58 +0000401void Preprocessor::EnterMainSourceFile() {
Chris Lattner05db4272009-02-13 19:33:24 +0000402 // We do not allow the preprocessor to reenter the main file. Doing so will
403 // cause FileID's to accumulate information from both runs (e.g. #line
404 // information) and predefined macros aren't guaranteed to be set properly.
405 assert(NumEnteredSourceFiles == 0 && "Cannot reenter the main file!");
Chris Lattner2b2453a2009-01-17 06:22:33 +0000406 FileID MainFileID = SourceMgr.getMainFileID();
Mike Stump1eb44332009-09-09 15:08:12 +0000407
Argyrios Kyrtzidisb8c879a2012-01-05 21:36:25 +0000408 // If MainFileID is loaded it means we loaded an AST file, no need to enter
409 // a main file.
410 if (!SourceMgr.isLoadedFileID(MainFileID)) {
411 // Enter the main file source buffer.
412 EnterSourceFile(MainFileID, 0, SourceLocation());
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000413
Argyrios Kyrtzidisb8c879a2012-01-05 21:36:25 +0000414 // If we've been asked to skip bytes in the main file (e.g., as part of a
415 // precompiled preamble), do so now.
416 if (SkipMainFilePreamble.first > 0)
417 CurLexer->SkipBytes(SkipMainFilePreamble.first,
418 SkipMainFilePreamble.second);
419
420 // Tell the header info that the main file was entered. If the file is later
421 // #imported, it won't be re-entered.
422 if (const FileEntry *FE = SourceMgr.getFileEntryForID(MainFileID))
423 HeaderInfo.IncrementIncludeCount(FE);
424 }
Mike Stump1eb44332009-09-09 15:08:12 +0000425
Benjamin Kramerffd6e392009-12-31 15:33:09 +0000426 // Preprocess Predefines to populate the initial preprocessor state.
Mike Stump1eb44332009-09-09 15:08:12 +0000427 llvm::MemoryBuffer *SB =
Chris Lattnera0a270c2010-04-05 22:42:27 +0000428 llvm::MemoryBuffer::getMemBufferCopy(Predefines, "<built-in>");
Douglas Gregor043266b2010-08-26 14:07:34 +0000429 assert(SB && "Cannot create predefined source buffer");
Jordan Rosed73ef132012-06-06 17:25:21 +0000430 FileID FID = SourceMgr.createPredefinesFileIDForMemBuffer(SB);
Chris Lattner2b2453a2009-01-17 06:22:33 +0000431 assert(!FID.isInvalid() && "Could not create FileID for predefines?");
Mike Stump1eb44332009-09-09 15:08:12 +0000432
Chris Lattner53b0dab2007-10-09 22:10:18 +0000433 // Start parsing the predefines.
Chris Lattnere127a0d2010-04-20 20:35:58 +0000434 EnterSourceFile(FID, 0, SourceLocation());
Chris Lattner53b0dab2007-10-09 22:10:18 +0000435}
Chris Lattner97ba77c2007-07-16 06:48:38 +0000436
Daniel Dunbardbd82092010-03-23 05:09:10 +0000437void Preprocessor::EndSourceFile() {
438 // Notify the client that we reached the end of the source file.
439 if (Callbacks)
440 Callbacks->EndOfMainFile();
441}
Reid Spencer5f016e22007-07-11 17:01:13 +0000442
443//===----------------------------------------------------------------------===//
444// Lexer Event Handling.
445//===----------------------------------------------------------------------===//
446
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +0000447/// LookUpIdentifierInfo - Given a tok::raw_identifier token, look up the
448/// identifier information for the token and install it into the token,
449/// updating the token kind accordingly.
450IdentifierInfo *Preprocessor::LookUpIdentifierInfo(Token &Identifier) const {
451 assert(Identifier.getRawIdentifierData() != 0 && "No raw identifier data!");
Mike Stump1eb44332009-09-09 15:08:12 +0000452
Reid Spencer5f016e22007-07-11 17:01:13 +0000453 // Look up this token, see if it is a macro, or if it is a language keyword.
454 IdentifierInfo *II;
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +0000455 if (!Identifier.needsCleaning()) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000456 // No cleaning needed, just use the characters from the lexed buffer.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000457 II = getIdentifierInfo(StringRef(Identifier.getRawIdentifierData(),
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +0000458 Identifier.getLength()));
Reid Spencer5f016e22007-07-11 17:01:13 +0000459 } else {
460 // Cleaning needed, alloca a buffer, clean into it, then use the buffer.
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +0000461 SmallString<64> IdentifierBuffer;
Chris Lattner5f9e2722011-07-23 10:55:15 +0000462 StringRef CleanedStr = getSpelling(Identifier, IdentifierBuffer);
Benjamin Kramerddeea562010-02-27 13:44:12 +0000463 II = getIdentifierInfo(CleanedStr);
Reid Spencer5f016e22007-07-11 17:01:13 +0000464 }
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +0000465
466 // Update the token info (identifier info and appropriate token kind).
Reid Spencer5f016e22007-07-11 17:01:13 +0000467 Identifier.setIdentifierInfo(II);
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +0000468 Identifier.setKind(II->getTokenID());
469
Reid Spencer5f016e22007-07-11 17:01:13 +0000470 return II;
471}
472
John Wiegley28bbe4b2011-04-28 01:08:34 +0000473void Preprocessor::SetPoisonReason(IdentifierInfo *II, unsigned DiagID) {
474 PoisonReasons[II] = DiagID;
475}
476
477void Preprocessor::PoisonSEHIdentifiers(bool Poison) {
478 assert(Ident__exception_code && Ident__exception_info);
479 assert(Ident___exception_code && Ident___exception_info);
480 Ident__exception_code->setIsPoisoned(Poison);
481 Ident___exception_code->setIsPoisoned(Poison);
482 Ident_GetExceptionCode->setIsPoisoned(Poison);
483 Ident__exception_info->setIsPoisoned(Poison);
484 Ident___exception_info->setIsPoisoned(Poison);
485 Ident_GetExceptionInfo->setIsPoisoned(Poison);
486 Ident__abnormal_termination->setIsPoisoned(Poison);
487 Ident___abnormal_termination->setIsPoisoned(Poison);
488 Ident_AbnormalTermination->setIsPoisoned(Poison);
489}
490
491void Preprocessor::HandlePoisonedIdentifier(Token & Identifier) {
492 assert(Identifier.getIdentifierInfo() &&
493 "Can't handle identifiers without identifier info!");
494 llvm::DenseMap<IdentifierInfo*,unsigned>::const_iterator it =
495 PoisonReasons.find(Identifier.getIdentifierInfo());
496 if(it == PoisonReasons.end())
497 Diag(Identifier, diag::err_pp_used_poisoned_id);
498 else
499 Diag(Identifier,it->second) << Identifier.getIdentifierInfo();
500}
Reid Spencer5f016e22007-07-11 17:01:13 +0000501
502/// HandleIdentifier - This callback is invoked when the lexer reads an
503/// identifier. This callback looks up the identifier in the map and/or
504/// potentially macro expands it or turns it into a named token (like 'for').
Chris Lattner6a170eb2009-01-21 07:43:11 +0000505///
506/// Note that callers of this method are guarded by checking the
507/// IdentifierInfo's 'isHandleIdentifierCase' bit. If this method changes, the
508/// IdentifierInfo methods that compute these properties will need to change to
509/// match.
Chris Lattnerd2177732007-07-20 16:59:19 +0000510void Preprocessor::HandleIdentifier(Token &Identifier) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000511 assert(Identifier.getIdentifierInfo() &&
512 "Can't handle identifiers without identifier info!");
Mike Stump1eb44332009-09-09 15:08:12 +0000513
Reid Spencer5f016e22007-07-11 17:01:13 +0000514 IdentifierInfo &II = *Identifier.getIdentifierInfo();
515
Douglas Gregoreee242f2011-10-27 09:33:13 +0000516 // If the information about this identifier is out of date, update it from
517 // the external source.
518 if (II.isOutOfDate()) {
519 ExternalSource->updateOutOfDateIdentifier(II);
520 Identifier.setKind(II.getTokenID());
521 }
522
Reid Spencer5f016e22007-07-11 17:01:13 +0000523 // If this identifier was poisoned, and if it was not produced from a macro
524 // expansion, emit an error.
Ted Kremenek1a531572008-11-19 22:43:49 +0000525 if (II.isPoisoned() && CurPPLexer) {
John Wiegley28bbe4b2011-04-28 01:08:34 +0000526 HandlePoisonedIdentifier(Identifier);
Reid Spencer5f016e22007-07-11 17:01:13 +0000527 }
Mike Stump1eb44332009-09-09 15:08:12 +0000528
Reid Spencer5f016e22007-07-11 17:01:13 +0000529 // If this is a macro to be expanded, do it.
Chris Lattnercc1a8752007-10-07 08:44:20 +0000530 if (MacroInfo *MI = getMacroInfo(&II)) {
Abramo Bagnara163ada82012-01-01 22:01:04 +0000531 if (!DisableMacroExpansion) {
532 if (Identifier.isExpandDisabled()) {
533 Diag(Identifier, diag::pp_disabled_macro_expansion);
534 } else if (MI->isEnabled()) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000535 if (!HandleMacroExpandedIdentifier(Identifier, MI))
Douglas Gregor6be16fe2011-08-27 06:37:51 +0000536 return;
Reid Spencer5f016e22007-07-11 17:01:13 +0000537 } else {
538 // C99 6.10.3.4p2 says that a disabled macro may never again be
539 // expanded, even if it's in a context where it could be expanded in the
540 // future.
Chris Lattnerd2177732007-07-20 16:59:19 +0000541 Identifier.setFlag(Token::DisableExpand);
Abramo Bagnara163ada82012-01-01 22:01:04 +0000542 Diag(Identifier, diag::pp_disabled_macro_expansion);
Reid Spencer5f016e22007-07-11 17:01:13 +0000543 }
544 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000545 }
546
Richard Smith98d86b92011-10-11 19:57:52 +0000547 // If this identifier is a keyword in C++11, produce a warning. Don't warn if
548 // we're not considering macro expansion, since this identifier might be the
549 // name of a macro.
550 // FIXME: This warning is disabled in cases where it shouldn't be, like
551 // "#define constexpr constexpr", "int constexpr;"
552 if (II.isCXX11CompatKeyword() & !DisableMacroExpansion) {
553 Diag(Identifier, diag::warn_cxx11_keyword) << II.getName();
554 // Don't diagnose this keyword again in this translation unit.
555 II.setIsCXX11CompatKeyword(false);
556 }
557
Reid Spencer5f016e22007-07-11 17:01:13 +0000558 // C++ 2.11p2: If this is an alternative representation of a C++ operator,
559 // then we act as if it is the actual operator and not the textual
560 // representation of it.
Fariborz Jahanianafbc6812010-09-03 17:33:04 +0000561 if (II.isCPlusPlusOperatorKeyword())
Reid Spencer5f016e22007-07-11 17:01:13 +0000562 Identifier.setIdentifierInfo(0);
563
Reid Spencer5f016e22007-07-11 17:01:13 +0000564 // If this is an extension token, diagnose its use.
Steve Naroffb4eaf9c2008-09-02 18:50:17 +0000565 // We avoid diagnosing tokens that originate from macro definitions.
Eli Friedman2962f4d2009-04-28 03:59:15 +0000566 // FIXME: This warning is disabled in cases where it shouldn't be,
567 // like "#define TY typeof", "TY(1) x".
568 if (II.isExtensionToken() && !DisableMacroExpansion)
Reid Spencer5f016e22007-07-11 17:01:13 +0000569 Diag(Identifier, diag::ext_token_used);
Douglas Gregorb8db7cd2011-09-07 23:11:54 +0000570
Ted Kremenek32ad2ee2012-03-01 22:07:04 +0000571 // If this is the '__experimental_modules_import' contextual keyword, note
572 // that the next token indicates a module name.
Douglas Gregord6aba062012-01-04 06:20:15 +0000573 //
Ted Kremenek32ad2ee2012-03-01 22:07:04 +0000574 // Note that we do not treat '__experimental_modules_import' as a contextual
575 // keyword when we're in a caching lexer, because caching lexers only get
576 // used in contexts where import declarations are disallowed.
577 if (II.isModulesImport() && !InMacroArgs && !DisableMacroExpansion &&
David Blaikie4e4d0842012-03-11 07:00:24 +0000578 getLangOpts().Modules && CurLexerKind != CLK_CachingLexer) {
Douglas Gregorb8db7cd2011-09-07 23:11:54 +0000579 ModuleImportLoc = Identifier.getLocation();
Douglas Gregorb514c792011-11-30 04:26:53 +0000580 ModuleImportPath.clear();
581 ModuleImportExpectsIdentifier = true;
Douglas Gregorb8db7cd2011-09-07 23:11:54 +0000582 CurLexerKind = CLK_LexAfterModuleImport;
583 }
Douglas Gregor6aa52ec2011-08-26 23:56:07 +0000584}
585
Douglas Gregorc13a34b2012-01-03 19:32:59 +0000586/// \brief Lex a token following the 'import' contextual keyword.
Douglas Gregor5948ae12012-01-03 18:04:46 +0000587///
Douglas Gregorb8db7cd2011-09-07 23:11:54 +0000588void Preprocessor::LexAfterModuleImport(Token &Result) {
589 // Figure out what kind of lexer we actually have.
Douglas Gregord6aba062012-01-04 06:20:15 +0000590 recomputeCurLexerKind();
Douglas Gregorb8db7cd2011-09-07 23:11:54 +0000591
592 // Lex the next token.
593 Lex(Result);
594
Douglas Gregor6aa52ec2011-08-26 23:56:07 +0000595 // The token sequence
596 //
Douglas Gregor5948ae12012-01-03 18:04:46 +0000597 // import identifier (. identifier)*
598 //
Douglas Gregorc13a34b2012-01-03 19:32:59 +0000599 // indicates a module import directive. We already saw the 'import'
600 // contextual keyword, so now we're looking for the identifiers.
Douglas Gregorb514c792011-11-30 04:26:53 +0000601 if (ModuleImportExpectsIdentifier && Result.getKind() == tok::identifier) {
602 // We expected to see an identifier here, and we did; continue handling
603 // identifiers.
604 ModuleImportPath.push_back(std::make_pair(Result.getIdentifierInfo(),
605 Result.getLocation()));
606 ModuleImportExpectsIdentifier = false;
607 CurLexerKind = CLK_LexAfterModuleImport;
Douglas Gregor6aa52ec2011-08-26 23:56:07 +0000608 return;
Douglas Gregorb514c792011-11-30 04:26:53 +0000609 }
Douglas Gregor6aa52ec2011-08-26 23:56:07 +0000610
Douglas Gregorb514c792011-11-30 04:26:53 +0000611 // If we're expecting a '.' or a ';', and we got a '.', then wait until we
612 // see the next identifier.
613 if (!ModuleImportExpectsIdentifier && Result.getKind() == tok::period) {
614 ModuleImportExpectsIdentifier = true;
615 CurLexerKind = CLK_LexAfterModuleImport;
616 return;
617 }
618
619 // If we have a non-empty module path, load the named module.
620 if (!ModuleImportPath.empty())
Douglas Gregor5e356932011-12-01 17:11:21 +0000621 (void)TheModuleLoader.loadModule(ModuleImportLoc, ModuleImportPath,
Douglas Gregor93ebfa62011-12-02 23:42:12 +0000622 Module::MacrosVisible,
623 /*IsIncludeDirective=*/false);
Reid Spencer5f016e22007-07-11 17:01:13 +0000624}
Douglas Gregor2e222532009-07-02 17:08:52 +0000625
626void Preprocessor::AddCommentHandler(CommentHandler *Handler) {
627 assert(Handler && "NULL comment handler");
628 assert(std::find(CommentHandlers.begin(), CommentHandlers.end(), Handler) ==
629 CommentHandlers.end() && "Comment handler already registered");
630 CommentHandlers.push_back(Handler);
631}
632
633void Preprocessor::RemoveCommentHandler(CommentHandler *Handler) {
634 std::vector<CommentHandler *>::iterator Pos
635 = std::find(CommentHandlers.begin(), CommentHandlers.end(), Handler);
636 assert(Pos != CommentHandlers.end() && "Comment handler not registered");
637 CommentHandlers.erase(Pos);
638}
639
Chris Lattner046c2272010-01-18 22:35:47 +0000640bool Preprocessor::HandleComment(Token &result, SourceRange Comment) {
641 bool AnyPendingTokens = false;
Douglas Gregor2e222532009-07-02 17:08:52 +0000642 for (std::vector<CommentHandler *>::iterator H = CommentHandlers.begin(),
643 HEnd = CommentHandlers.end();
Chris Lattner046c2272010-01-18 22:35:47 +0000644 H != HEnd; ++H) {
645 if ((*H)->HandleComment(*this, Comment))
646 AnyPendingTokens = true;
647 }
648 if (!AnyPendingTokens || getCommentRetentionState())
649 return false;
650 Lex(result);
651 return true;
Douglas Gregor2e222532009-07-02 17:08:52 +0000652}
653
Douglas Gregor6aa52ec2011-08-26 23:56:07 +0000654ModuleLoader::~ModuleLoader() { }
655
Douglas Gregor2e222532009-07-02 17:08:52 +0000656CommentHandler::~CommentHandler() { }
Douglas Gregor94dc8f62010-03-19 16:15:56 +0000657
Douglas Gregorf44e8542010-08-24 19:08:16 +0000658CodeCompletionHandler::~CodeCompletionHandler() { }
659
Argyrios Kyrtzidisc6c54522012-03-05 05:48:17 +0000660void Preprocessor::createPreprocessingRecord(bool RecordConditionalDirectives) {
Douglas Gregor94dc8f62010-03-19 16:15:56 +0000661 if (Record)
662 return;
663
Argyrios Kyrtzidisc6c54522012-03-05 05:48:17 +0000664 Record = new PreprocessingRecord(getSourceManager(),
665 RecordConditionalDirectives);
Douglas Gregorb9e1b752010-03-19 17:12:43 +0000666 addPPCallbacks(Record);
Douglas Gregor94dc8f62010-03-19 16:15:56 +0000667}