blob: 81e6f364cfbe8c66684d663451921711f70aedf1 [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"
Argyrios Kyrtzidis37e48ff2013-05-03 22:31:32 +000029#include "clang/Lex/MacroArgs.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000030#include "clang/Basic/FileManager.h"
31#include "clang/Basic/SourceManager.h"
32#include "clang/Basic/TargetInfo.h"
33#include "clang/Lex/CodeCompletionHandler.h"
Douglas Gregor9882a5a2010-01-04 19:18:44 +000034#include "clang/Lex/ExternalPreprocessorSource.h"
Chris Lattner07b019a2006-10-22 07:28:56 +000035#include "clang/Lex/HeaderSearch.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000036#include "clang/Lex/LexDiagnostic.h"
37#include "clang/Lex/LiteralSupport.h"
Chris Lattner22eb9722006-06-18 05:43:12 +000038#include "clang/Lex/MacroInfo.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000039#include "clang/Lex/ModuleLoader.h"
Chris Lattnerb8761832006-06-24 21:31:03 +000040#include "clang/Lex/Pragma.h"
Douglas Gregor7f6d60d2010-03-19 16:15:56 +000041#include "clang/Lex/PreprocessingRecord.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000042#include "clang/Lex/PreprocessorOptions.h"
Chris Lattner0b8cfc22006-06-28 06:49:17 +000043#include "clang/Lex/ScratchBuffer.h"
Chris Lattner5cd83512008-10-05 20:40:30 +000044#include "llvm/ADT/APFloat.h"
Benjamin Kramer49038022012-02-04 13:45:25 +000045#include "llvm/ADT/SmallString.h"
Jordan Rose7f43ddd2013-01-24 20:50:46 +000046#include "llvm/ADT/STLExtras.h"
47#include "llvm/ADT/StringExtras.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000048#include "llvm/Support/Capacity.h"
Dmitri Gribenko9feeef42013-01-30 12:06:08 +000049#include "llvm/Support/ConvertUTF.h"
Chris Lattner8a7003c2007-07-16 06:48:38 +000050#include "llvm/Support/MemoryBuffer.h"
Benjamin Kramer89b422c2009-08-23 12:08:50 +000051#include "llvm/Support/raw_ostream.h"
Chris Lattner22eb9722006-06-18 05:43:12 +000052using namespace clang;
53
54//===----------------------------------------------------------------------===//
Douglas Gregor9882a5a2010-01-04 19:18:44 +000055ExternalPreprocessorSource::~ExternalPreprocessorSource() { }
Chris Lattner22eb9722006-06-18 05:43:12 +000056
Dmitri Gribenkof8579502013-01-12 19:30:44 +000057Preprocessor::Preprocessor(IntrusiveRefCntPtr<PreprocessorOptions> PPOpts,
Douglas Gregor1452ff12012-10-24 17:46:57 +000058 DiagnosticsEngine &diags, LangOptions &opts,
Douglas Gregor83297df2011-09-01 23:39:15 +000059 const TargetInfo *target, SourceManager &SM,
Douglas Gregor08142532011-08-26 23:56:07 +000060 HeaderSearch &Headers, ModuleLoader &TheModuleLoader,
David Blaikie687cd952013-01-16 23:13:36 +000061 IdentifierInfoLookup *IILookup, bool OwnsHeaders,
62 bool DelayInitialization, bool IncrProcessing)
63 : PPOpts(PPOpts), Diags(&diags), LangOpts(opts), Target(target),
64 FileMgr(Headers.getFileMgr()), SourceMgr(SM), HeaderInfo(Headers),
65 TheModuleLoader(TheModuleLoader), ExternalSource(0),
David Blaikief157e902013-01-16 23:18:16 +000066 Identifiers(opts, IILookup), IncrementalProcessing(IncrProcessing),
67 CodeComplete(0), CodeCompletionFile(0), CodeCompletionOffset(0),
68 CodeCompletionReached(0), SkipMainFilePreamble(0, true), CurPPLexer(0),
Argyrios Kyrtzidis6c811412013-03-27 01:25:24 +000069 CurDirLookup(0), CurLexerKind(CLK_Lexer), Callbacks(0),
Argyrios Kyrtzidisd48b91d2013-04-30 05:05:35 +000070 MacroArgCache(0), Record(0), MIChainHead(0), MICache(0),
71 DeserialMIChainHead(0) {
Daniel Dunbar0c6c9302009-11-11 21:44:21 +000072 OwnsHeaderSearch = OwnsHeaders;
Douglas Gregor83297df2011-09-01 23:39:15 +000073
74 ScratchBuf = new ScratchBuffer(SourceMgr);
75 CounterValue = 0; // __COUNTER__ starts at 0.
76
77 // Clear stats.
78 NumDirectives = NumDefined = NumUndefined = NumPragma = 0;
79 NumIf = NumElse = NumEndif = 0;
80 NumEnteredSourceFiles = 0;
81 NumMacroExpanded = NumFnMacroExpanded = NumBuiltinMacroExpanded = 0;
82 NumFastMacroExpanded = NumTokenPaste = NumFastTokenPaste = 0;
83 MaxIncludeStackDepth = 0;
84 NumSkipped = 0;
85
86 // Default to discarding comments.
87 KeepComments = false;
88 KeepMacroComments = false;
89 SuppressIncludeNotFoundError = false;
90
91 // Macro expansion is enabled.
92 DisableMacroExpansion = false;
David Blaikied5321242012-06-06 18:52:13 +000093 MacroExpansionInDirectivesOverride = false;
Douglas Gregor83297df2011-09-01 23:39:15 +000094 InMacroArgs = false;
Argyrios Kyrtzidisf1b64c62012-04-03 16:47:40 +000095 InMacroArgPreExpansion = false;
Douglas Gregor83297df2011-09-01 23:39:15 +000096 NumCachedTokenLexers = 0;
Jordan Rosede1a2922012-06-08 18:06:21 +000097 PragmasEnabled = true;
Eric Christopher5e4696d2013-01-16 20:09:36 +000098 ParsingIfOrElifDirective = false;
Jordan Rose324ec422013-01-31 19:26:01 +000099 PreprocessedOutput = false;
Jordan Rosede1a2922012-06-08 18:06:21 +0000100
Douglas Gregor83297df2011-09-01 23:39:15 +0000101 CachedLexPos = 0;
Eric Christopher5e4696d2013-01-16 20:09:36 +0000102
Douglas Gregor83297df2011-09-01 23:39:15 +0000103 // We haven't read anything from the external source.
104 ReadMacrosFromExternalSource = false;
105
Douglas Gregor83297df2011-09-01 23:39:15 +0000106 // "Poison" __VA_ARGS__, which can only appear in the expansion of a macro.
107 // This gets unpoisoned where it is allowed.
108 (Ident__VA_ARGS__ = getIdentifierInfo("__VA_ARGS__"))->setIsPoisoned();
109 SetPoisonReason(Ident__VA_ARGS__,diag::ext_pp_bad_vaargs_use);
110
111 // Initialize the pragma handlers.
112 PragmaHandlers = new PragmaNamespace(StringRef());
113 RegisterBuiltinPragmas();
114
115 // Initialize builtin macros like __LINE__ and friends.
116 RegisterBuiltinMacros();
117
David Blaikiebbafb8a2012-03-11 07:00:24 +0000118 if(LangOpts.Borland) {
Douglas Gregor83297df2011-09-01 23:39:15 +0000119 Ident__exception_info = getIdentifierInfo("_exception_info");
120 Ident___exception_info = getIdentifierInfo("__exception_info");
121 Ident_GetExceptionInfo = getIdentifierInfo("GetExceptionInformation");
122 Ident__exception_code = getIdentifierInfo("_exception_code");
123 Ident___exception_code = getIdentifierInfo("__exception_code");
124 Ident_GetExceptionCode = getIdentifierInfo("GetExceptionCode");
125 Ident__abnormal_termination = getIdentifierInfo("_abnormal_termination");
126 Ident___abnormal_termination = getIdentifierInfo("__abnormal_termination");
127 Ident_AbnormalTermination = getIdentifierInfo("AbnormalTermination");
128 } else {
129 Ident__exception_info = Ident__exception_code = Ident__abnormal_termination = 0;
130 Ident___exception_info = Ident___exception_code = Ident___abnormal_termination = 0;
131 Ident_GetExceptionInfo = Ident_GetExceptionCode = Ident_AbnormalTermination = 0;
Douglas Gregor89929282012-01-30 06:01:29 +0000132 }
Argyrios Kyrtzidis3c9aaf12012-06-02 18:08:09 +0000133
134 if (!DelayInitialization) {
135 assert(Target && "Must provide target information for PP initialization");
136 Initialize(*Target);
137 }
138}
139
140Preprocessor::~Preprocessor() {
141 assert(BacktrackPositions.empty() && "EnableBacktrack/Backtrack imbalance!");
142
143 while (!IncludeMacroStack.empty()) {
144 delete IncludeMacroStack.back().TheLexer;
145 delete IncludeMacroStack.back().TheTokenLexer;
146 IncludeMacroStack.pop_back();
147 }
148
149 // Free any macro definitions.
150 for (MacroInfoChain *I = MIChainHead ; I ; I = I->Next)
151 I->MI.Destroy();
152
153 // Free any cached macro expanders.
154 for (unsigned i = 0, e = NumCachedTokenLexers; i != e; ++i)
155 delete TokenLexerCache[i];
156
Argyrios Kyrtzidisd48b91d2013-04-30 05:05:35 +0000157 for (DeserializedMacroInfoChain *I = DeserialMIChainHead ; I ; I = I->Next)
158 I->MI.Destroy();
159
Argyrios Kyrtzidis3c9aaf12012-06-02 18:08:09 +0000160 // Free any cached MacroArgs.
161 for (MacroArgs *ArgList = MacroArgCache; ArgList; )
162 ArgList = ArgList->deallocate();
163
164 // Release pragma information.
165 delete PragmaHandlers;
166
167 // Delete the scratch buffer info.
168 delete ScratchBuf;
169
170 // Delete the header search info, if we own it.
171 if (OwnsHeaderSearch)
172 delete &HeaderInfo;
173
174 delete Callbacks;
175}
176
177void Preprocessor::Initialize(const TargetInfo &Target) {
178 assert((!this->Target || this->Target == &Target) &&
179 "Invalid override of target information");
180 this->Target = &Target;
Douglas Gregor89929282012-01-30 06:01:29 +0000181
Argyrios Kyrtzidis3c9aaf12012-06-02 18:08:09 +0000182 // Initialize information about built-ins.
183 BuiltinInfo.InitializeTarget(Target);
Douglas Gregor89929282012-01-30 06:01:29 +0000184 HeaderInfo.setTarget(Target);
Douglas Gregor83297df2011-09-01 23:39:15 +0000185}
186
Ted Kremeneka5c2c272009-02-12 03:26:59 +0000187void Preprocessor::setPTHManager(PTHManager* pm) {
188 PTH.reset(pm);
Douglas Gregord2eb58a2009-10-16 18:18:30 +0000189 FileMgr.addStatCache(PTH->createStatCache());
Ted Kremeneka5c2c272009-02-12 03:26:59 +0000190}
191
Chris Lattner146762e2007-07-20 16:59:19 +0000192void Preprocessor::DumpToken(const Token &Tok, bool DumpFlags) const {
Benjamin Kramer89b422c2009-08-23 12:08:50 +0000193 llvm::errs() << tok::getTokenName(Tok.getKind()) << " '"
194 << getSpelling(Tok) << "'";
Mike Stump11289f42009-09-09 15:08:12 +0000195
Chris Lattnerd01e2912006-06-18 16:22:51 +0000196 if (!DumpFlags) return;
Mike Stump11289f42009-09-09 15:08:12 +0000197
Benjamin Kramer89b422c2009-08-23 12:08:50 +0000198 llvm::errs() << "\t";
Chris Lattnerd01e2912006-06-18 16:22:51 +0000199 if (Tok.isAtStartOfLine())
Benjamin Kramer89b422c2009-08-23 12:08:50 +0000200 llvm::errs() << " [StartOfLine]";
Chris Lattnerd01e2912006-06-18 16:22:51 +0000201 if (Tok.hasLeadingSpace())
Benjamin Kramer89b422c2009-08-23 12:08:50 +0000202 llvm::errs() << " [LeadingSpace]";
Chris Lattner6e4bf522006-07-27 06:59:25 +0000203 if (Tok.isExpandDisabled())
Benjamin Kramer89b422c2009-08-23 12:08:50 +0000204 llvm::errs() << " [ExpandDisabled]";
Chris Lattnerd01e2912006-06-18 16:22:51 +0000205 if (Tok.needsCleaning()) {
Chris Lattner50b497e2006-06-18 16:32:35 +0000206 const char *Start = SourceMgr.getCharacterData(Tok.getLocation());
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000207 llvm::errs() << " [UnClean='" << StringRef(Start, Tok.getLength())
Benjamin Kramer89b422c2009-08-23 12:08:50 +0000208 << "']";
Chris Lattnerd01e2912006-06-18 16:22:51 +0000209 }
Mike Stump11289f42009-09-09 15:08:12 +0000210
Benjamin Kramer89b422c2009-08-23 12:08:50 +0000211 llvm::errs() << "\tLoc=<";
Chris Lattner615315f2007-12-09 20:31:55 +0000212 DumpLocation(Tok.getLocation());
Benjamin Kramer89b422c2009-08-23 12:08:50 +0000213 llvm::errs() << ">";
Chris Lattner615315f2007-12-09 20:31:55 +0000214}
215
216void Preprocessor::DumpLocation(SourceLocation Loc) const {
Chris Lattnerf1ca7d32009-01-27 07:57:44 +0000217 Loc.dump(SourceMgr);
Chris Lattnerd01e2912006-06-18 16:22:51 +0000218}
219
220void Preprocessor::DumpMacro(const MacroInfo &MI) const {
Benjamin Kramer89b422c2009-08-23 12:08:50 +0000221 llvm::errs() << "MACRO: ";
Chris Lattnerd01e2912006-06-18 16:22:51 +0000222 for (unsigned i = 0, e = MI.getNumTokens(); i != e; ++i) {
223 DumpToken(MI.getReplacementToken(i));
Benjamin Kramer89b422c2009-08-23 12:08:50 +0000224 llvm::errs() << " ";
Chris Lattnerd01e2912006-06-18 16:22:51 +0000225 }
Benjamin Kramer89b422c2009-08-23 12:08:50 +0000226 llvm::errs() << "\n";
Chris Lattnerd01e2912006-06-18 16:22:51 +0000227}
228
Chris Lattner22eb9722006-06-18 05:43:12 +0000229void Preprocessor::PrintStats() {
Benjamin Kramer89b422c2009-08-23 12:08:50 +0000230 llvm::errs() << "\n*** Preprocessor Stats:\n";
231 llvm::errs() << NumDirectives << " directives found:\n";
232 llvm::errs() << " " << NumDefined << " #define.\n";
233 llvm::errs() << " " << NumUndefined << " #undef.\n";
234 llvm::errs() << " #include/#include_next/#import:\n";
235 llvm::errs() << " " << NumEnteredSourceFiles << " source files entered.\n";
236 llvm::errs() << " " << MaxIncludeStackDepth << " max include stack depth\n";
237 llvm::errs() << " " << NumIf << " #if/#ifndef/#ifdef.\n";
238 llvm::errs() << " " << NumElse << " #else/#elif.\n";
239 llvm::errs() << " " << NumEndif << " #endif.\n";
240 llvm::errs() << " " << NumPragma << " #pragma.\n";
241 llvm::errs() << NumSkipped << " #if/#ifndef#ifdef regions skipped\n";
Chris Lattner22eb9722006-06-18 05:43:12 +0000242
Benjamin Kramer89b422c2009-08-23 12:08:50 +0000243 llvm::errs() << NumMacroExpanded << "/" << NumFnMacroExpanded << "/"
Ted Kremeneka0a3e9b2008-01-14 16:44:48 +0000244 << NumBuiltinMacroExpanded << " obj/fn/builtin macros expanded, "
245 << NumFastMacroExpanded << " on the fast path.\n";
Benjamin Kramer89b422c2009-08-23 12:08:50 +0000246 llvm::errs() << (NumFastTokenPaste+NumTokenPaste)
Ted Kremeneka0a3e9b2008-01-14 16:44:48 +0000247 << " token paste (##) operations performed, "
248 << NumFastTokenPaste << " on the fast path.\n";
Alexander Kornienko199cd942012-08-13 10:46:42 +0000249
250 llvm::errs() << "\nPreprocessor Memory: " << getTotalMemory() << "B total";
251
252 llvm::errs() << "\n BumpPtr: " << BP.getTotalMemory();
253 llvm::errs() << "\n Macro Expanded Tokens: "
254 << llvm::capacity_in_bytes(MacroExpandedTokens);
255 llvm::errs() << "\n Predefines Buffer: " << Predefines.capacity();
256 llvm::errs() << "\n Macros: " << llvm::capacity_in_bytes(Macros);
257 llvm::errs() << "\n #pragma push_macro Info: "
258 << llvm::capacity_in_bytes(PragmaPushMacroInfo);
259 llvm::errs() << "\n Poison Reasons: "
260 << llvm::capacity_in_bytes(PoisonReasons);
261 llvm::errs() << "\n Comment Handlers: "
262 << llvm::capacity_in_bytes(CommentHandlers) << "\n";
Chris Lattner22eb9722006-06-18 05:43:12 +0000263}
264
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +0000265Preprocessor::macro_iterator
266Preprocessor::macro_begin(bool IncludeExternalMacros) const {
267 if (IncludeExternalMacros && ExternalSource &&
Douglas Gregor9882a5a2010-01-04 19:18:44 +0000268 !ReadMacrosFromExternalSource) {
269 ReadMacrosFromExternalSource = true;
270 ExternalSource->ReadDefinedMacros();
271 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +0000272
273 return Macros.begin();
Douglas Gregor9882a5a2010-01-04 19:18:44 +0000274}
275
Argyrios Kyrtzidise379ee32011-06-29 22:20:04 +0000276size_t Preprocessor::getTotalMemory() const {
Ted Kremenek182543a2011-07-26 21:17:24 +0000277 return BP.getTotalMemory()
Ted Kremenek8b77fe72011-07-27 18:41:23 +0000278 + llvm::capacity_in_bytes(MacroExpandedTokens)
Ted Kremenek182543a2011-07-26 21:17:24 +0000279 + Predefines.capacity() /* Predefines buffer. */
Ted Kremenek8b77fe72011-07-27 18:41:23 +0000280 + llvm::capacity_in_bytes(Macros)
281 + llvm::capacity_in_bytes(PragmaPushMacroInfo)
282 + llvm::capacity_in_bytes(PoisonReasons)
283 + llvm::capacity_in_bytes(CommentHandlers);
Argyrios Kyrtzidise379ee32011-06-29 22:20:04 +0000284}
285
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +0000286Preprocessor::macro_iterator
287Preprocessor::macro_end(bool IncludeExternalMacros) const {
288 if (IncludeExternalMacros && ExternalSource &&
Douglas Gregor9882a5a2010-01-04 19:18:44 +0000289 !ReadMacrosFromExternalSource) {
290 ReadMacrosFromExternalSource = true;
291 ExternalSource->ReadDefinedMacros();
292 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +0000293
294 return Macros.end();
Douglas Gregor9882a5a2010-01-04 19:18:44 +0000295}
296
Dmitri Gribenko6743e042012-09-29 11:40:46 +0000297/// \brief Compares macro tokens with a specified token value sequence.
298static bool MacroDefinitionEquals(const MacroInfo *MI,
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000299 ArrayRef<TokenValue> Tokens) {
Dmitri Gribenko6743e042012-09-29 11:40:46 +0000300 return Tokens.size() == MI->getNumTokens() &&
301 std::equal(Tokens.begin(), Tokens.end(), MI->tokens_begin());
302}
303
304StringRef Preprocessor::getLastMacroWithSpelling(
305 SourceLocation Loc,
306 ArrayRef<TokenValue> Tokens) const {
307 SourceLocation BestLocation;
308 StringRef BestSpelling;
309 for (Preprocessor::macro_iterator I = macro_begin(), E = macro_end();
310 I != E; ++I) {
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +0000311 if (!I->second->getMacroInfo()->isObjectLike())
Dmitri Gribenko6743e042012-09-29 11:40:46 +0000312 continue;
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +0000313 const MacroDirective::DefInfo
314 Def = I->second->findDirectiveAtLoc(Loc, SourceMgr);
315 if (!Def)
Dmitri Gribenko6743e042012-09-29 11:40:46 +0000316 continue;
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +0000317 if (!MacroDefinitionEquals(Def.getMacroInfo(), Tokens))
Dmitri Gribenko6743e042012-09-29 11:40:46 +0000318 continue;
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +0000319 SourceLocation Location = Def.getLocation();
Dmitri Gribenko6743e042012-09-29 11:40:46 +0000320 // Choose the macro defined latest.
321 if (BestLocation.isInvalid() ||
322 (Location.isValid() &&
323 SourceMgr.isBeforeInTranslationUnit(BestLocation, Location))) {
324 BestLocation = Location;
325 BestSpelling = I->first->getName();
326 }
327 }
328 return BestSpelling;
329}
330
Douglas Gregor8d76cca2012-01-04 06:20:15 +0000331void Preprocessor::recomputeCurLexerKind() {
332 if (CurLexer)
333 CurLexerKind = CLK_Lexer;
334 else if (CurPTHLexer)
335 CurLexerKind = CLK_PTHLexer;
336 else if (CurTokenLexer)
337 CurLexerKind = CLK_TokenLexer;
338 else
339 CurLexerKind = CLK_CachingLexer;
340}
341
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +0000342bool Preprocessor::SetCodeCompletionPoint(const FileEntry *File,
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +0000343 unsigned CompleteLine,
344 unsigned CompleteColumn) {
345 assert(File);
346 assert(CompleteLine && CompleteColumn && "Starts from 1:1");
347 assert(!CodeCompletionFile && "Already set");
348
Douglas Gregor53ad6b92009-12-02 06:49:09 +0000349 using llvm::MemoryBuffer;
350
Douglas Gregor53ad6b92009-12-02 06:49:09 +0000351 // Load the actual file's contents.
Douglas Gregor26266da2010-03-16 19:49:24 +0000352 bool Invalid = false;
353 const MemoryBuffer *Buffer = SourceMgr.getMemoryBufferForFile(File, &Invalid);
354 if (Invalid)
Douglas Gregor53ad6b92009-12-02 06:49:09 +0000355 return true;
356
357 // Find the byte position of the truncation point.
358 const char *Position = Buffer->getBufferStart();
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +0000359 for (unsigned Line = 1; Line < CompleteLine; ++Line) {
Douglas Gregor53ad6b92009-12-02 06:49:09 +0000360 for (; *Position; ++Position) {
361 if (*Position != '\r' && *Position != '\n')
362 continue;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +0000363
Douglas Gregor53ad6b92009-12-02 06:49:09 +0000364 // Eat \r\n or \n\r as a single line.
365 if ((Position[1] == '\r' || Position[1] == '\n') &&
366 Position[0] != Position[1])
367 ++Position;
368 ++Position;
369 break;
370 }
371 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +0000372
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +0000373 Position += CompleteColumn - 1;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +0000374
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +0000375 // Insert '\0' at the code-completion point.
Douglas Gregor9291ab62009-12-08 21:45:46 +0000376 if (Position < Buffer->getBufferEnd()) {
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +0000377 CodeCompletionFile = File;
378 CodeCompletionOffset = Position - Buffer->getBufferStart();
379
380 MemoryBuffer *NewBuffer =
381 MemoryBuffer::getNewUninitMemBuffer(Buffer->getBufferSize() + 1,
382 Buffer->getBufferIdentifier());
Benjamin Kramer60053cf2011-09-04 20:26:28 +0000383 char *NewBuf = const_cast<char*>(NewBuffer->getBufferStart());
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +0000384 char *NewPos = std::copy(Buffer->getBufferStart(), Position, NewBuf);
385 *NewPos = '\0';
386 std::copy(Position, Buffer->getBufferEnd(), NewPos+1);
387 SourceMgr.overrideFileContents(File, NewBuffer);
Douglas Gregor53ad6b92009-12-02 06:49:09 +0000388 }
389
390 return false;
391}
392
Douglas Gregor11583702010-08-25 17:04:25 +0000393void Preprocessor::CodeCompleteNaturalLanguage() {
Douglas Gregor11583702010-08-25 17:04:25 +0000394 if (CodeComplete)
395 CodeComplete->CodeCompleteNaturalLanguage();
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +0000396 setCodeCompletionReached();
Douglas Gregor11583702010-08-25 17:04:25 +0000397}
398
Benjamin Kramera197fb62010-02-27 17:05:45 +0000399/// getSpelling - This method is used to get the spelling of a token into a
400/// SmallVector. Note that the returned StringRef may not point to the
401/// supplied buffer if a copy can be avoided.
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000402StringRef Preprocessor::getSpelling(const Token &Tok,
403 SmallVectorImpl<char> &Buffer,
Douglas Gregor7bda4b82010-03-16 05:20:39 +0000404 bool *Invalid) const {
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +0000405 // NOTE: this has to be checked *before* testing for an IdentifierInfo.
Jordan Rose7f43ddd2013-01-24 20:50:46 +0000406 if (Tok.isNot(tok::raw_identifier) && !Tok.hasUCN()) {
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +0000407 // Try the fast path.
408 if (const IdentifierInfo *II = Tok.getIdentifierInfo())
409 return II->getName();
410 }
Benjamin Kramera197fb62010-02-27 17:05:45 +0000411
412 // Resize the buffer if we need to copy into it.
413 if (Tok.needsCleaning())
414 Buffer.resize(Tok.getLength());
415
416 const char *Ptr = Buffer.data();
Douglas Gregor7bda4b82010-03-16 05:20:39 +0000417 unsigned Len = getSpelling(Tok, Ptr, Invalid);
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000418 return StringRef(Ptr, Len);
Benjamin Kramera197fb62010-02-27 17:05:45 +0000419}
420
Chris Lattnerb94ec7b2006-07-14 06:54:10 +0000421/// CreateString - Plop the specified string into a scratch buffer and return a
422/// location for it. If specified, the source location provides a source
423/// location for the token.
Dmitri Gribenkob8e9e752012-09-24 21:07:17 +0000424void Preprocessor::CreateString(StringRef Str, Token &Tok,
Abramo Bagnarae398e602011-10-03 18:39:03 +0000425 SourceLocation ExpansionLocStart,
426 SourceLocation ExpansionLocEnd) {
Dmitri Gribenkob8e9e752012-09-24 21:07:17 +0000427 Tok.setLength(Str.size());
Mike Stump11289f42009-09-09 15:08:12 +0000428
Chris Lattner5a7971e2009-01-26 19:29:26 +0000429 const char *DestPtr;
Dmitri Gribenkob8e9e752012-09-24 21:07:17 +0000430 SourceLocation Loc = ScratchBuf->getToken(Str.data(), Str.size(), DestPtr);
Mike Stump11289f42009-09-09 15:08:12 +0000431
Abramo Bagnarae398e602011-10-03 18:39:03 +0000432 if (ExpansionLocStart.isValid())
433 Loc = SourceMgr.createExpansionLoc(Loc, ExpansionLocStart,
Dmitri Gribenkob8e9e752012-09-24 21:07:17 +0000434 ExpansionLocEnd, Str.size());
Chris Lattner5a7971e2009-01-26 19:29:26 +0000435 Tok.setLocation(Loc);
Mike Stump11289f42009-09-09 15:08:12 +0000436
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +0000437 // If this is a raw identifier or a literal token, set the pointer data.
438 if (Tok.is(tok::raw_identifier))
439 Tok.setRawIdentifierData(DestPtr);
440 else if (Tok.isLiteral())
Chris Lattner5a7971e2009-01-26 19:29:26 +0000441 Tok.setLiteralData(DestPtr);
Chris Lattnerb94ec7b2006-07-14 06:54:10 +0000442}
443
Douglas Gregor2b82c2a2011-12-02 01:47:07 +0000444Module *Preprocessor::getCurrentModule() {
David Blaikiebbafb8a2012-03-11 07:00:24 +0000445 if (getLangOpts().CurrentModule.empty())
Douglas Gregor2b82c2a2011-12-02 01:47:07 +0000446 return 0;
447
David Blaikiebbafb8a2012-03-11 07:00:24 +0000448 return getHeaderSearchInfo().lookupModule(getLangOpts().CurrentModule);
Douglas Gregor2b82c2a2011-12-02 01:47:07 +0000449}
Chris Lattner8a7003c2007-07-16 06:48:38 +0000450
Chris Lattner1f1b0db2007-10-09 22:10:18 +0000451//===----------------------------------------------------------------------===//
452// Preprocessor Initialization Methods
453//===----------------------------------------------------------------------===//
454
Chris Lattner1f1b0db2007-10-09 22:10:18 +0000455
456/// EnterMainSourceFile - Enter the specified FileID as the main source file,
Nate Begemanf7c3ff62008-01-07 04:01:26 +0000457/// which implicitly adds the builtin defines etc.
Chris Lattnerfb24a3a2010-04-20 20:35:58 +0000458void Preprocessor::EnterMainSourceFile() {
Chris Lattner9ef847b2009-02-13 19:33:24 +0000459 // We do not allow the preprocessor to reenter the main file. Doing so will
460 // cause FileID's to accumulate information from both runs (e.g. #line
461 // information) and predefined macros aren't guaranteed to be set properly.
462 assert(NumEnteredSourceFiles == 0 && "Cannot reenter the main file!");
Chris Lattnerd32480d2009-01-17 06:22:33 +0000463 FileID MainFileID = SourceMgr.getMainFileID();
Mike Stump11289f42009-09-09 15:08:12 +0000464
Argyrios Kyrtzidis9afd4492012-01-05 21:36:25 +0000465 // If MainFileID is loaded it means we loaded an AST file, no need to enter
466 // a main file.
467 if (!SourceMgr.isLoadedFileID(MainFileID)) {
468 // Enter the main file source buffer.
469 EnterSourceFile(MainFileID, 0, SourceLocation());
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000470
Argyrios Kyrtzidis9afd4492012-01-05 21:36:25 +0000471 // If we've been asked to skip bytes in the main file (e.g., as part of a
472 // precompiled preamble), do so now.
473 if (SkipMainFilePreamble.first > 0)
474 CurLexer->SkipBytes(SkipMainFilePreamble.first,
475 SkipMainFilePreamble.second);
476
477 // Tell the header info that the main file was entered. If the file is later
478 // #imported, it won't be re-entered.
479 if (const FileEntry *FE = SourceMgr.getFileEntryForID(MainFileID))
480 HeaderInfo.IncrementIncludeCount(FE);
481 }
Mike Stump11289f42009-09-09 15:08:12 +0000482
Benjamin Kramerd77adb52009-12-31 15:33:09 +0000483 // Preprocess Predefines to populate the initial preprocessor state.
Mike Stump11289f42009-09-09 15:08:12 +0000484 llvm::MemoryBuffer *SB =
Chris Lattner58c79342010-04-05 22:42:27 +0000485 llvm::MemoryBuffer::getMemBufferCopy(Predefines, "<built-in>");
Douglas Gregor33551892010-08-26 14:07:34 +0000486 assert(SB && "Cannot create predefined source buffer");
Meador Ingecdc00572012-06-19 18:17:30 +0000487 FileID FID = SourceMgr.createFileIDForMemBuffer(SB);
Chris Lattnerd32480d2009-01-17 06:22:33 +0000488 assert(!FID.isInvalid() && "Could not create FileID for predefines?");
Argyrios Kyrtzidis22c22f52013-02-01 16:36:07 +0000489 setPredefinesFileID(FID);
Mike Stump11289f42009-09-09 15:08:12 +0000490
Chris Lattner1f1b0db2007-10-09 22:10:18 +0000491 // Start parsing the predefines.
Chris Lattnerfb24a3a2010-04-20 20:35:58 +0000492 EnterSourceFile(FID, 0, SourceLocation());
Chris Lattner1f1b0db2007-10-09 22:10:18 +0000493}
Chris Lattner8a7003c2007-07-16 06:48:38 +0000494
Daniel Dunbarcb9eaf52010-03-23 05:09:10 +0000495void Preprocessor::EndSourceFile() {
496 // Notify the client that we reached the end of the source file.
497 if (Callbacks)
498 Callbacks->EndOfMainFile();
499}
Chris Lattner677757a2006-06-28 05:26:32 +0000500
501//===----------------------------------------------------------------------===//
502// Lexer Event Handling.
503//===----------------------------------------------------------------------===//
504
Jordan Rose7f43ddd2013-01-24 20:50:46 +0000505static void appendCodePoint(unsigned Codepoint,
506 llvm::SmallVectorImpl<char> &Str) {
507 char ResultBuf[4];
508 char *ResultPtr = ResultBuf;
Dmitri Gribenko9feeef42013-01-30 12:06:08 +0000509 bool Res = llvm::ConvertCodePointToUTF8(Codepoint, ResultPtr);
Jordan Rose7f43ddd2013-01-24 20:50:46 +0000510 (void)Res;
511 assert(Res && "Unexpected conversion failure");
512 Str.append(ResultBuf, ResultPtr);
513}
514
515static void expandUCNs(SmallVectorImpl<char> &Buf, StringRef Input) {
516 for (StringRef::iterator I = Input.begin(), E = Input.end(); I != E; ++I) {
517 if (*I != '\\') {
518 Buf.push_back(*I);
519 continue;
520 }
521
522 ++I;
523 assert(*I == 'u' || *I == 'U');
524
525 unsigned NumHexDigits;
526 if (*I == 'u')
527 NumHexDigits = 4;
528 else
529 NumHexDigits = 8;
530
531 assert(I + NumHexDigits <= E);
532
533 uint32_t CodePoint = 0;
534 for (++I; NumHexDigits != 0; ++I, --NumHexDigits) {
535 unsigned Value = llvm::hexDigitValue(*I);
536 assert(Value != -1U);
537
538 CodePoint <<= 4;
539 CodePoint += Value;
540 }
541
542 appendCodePoint(CodePoint, Buf);
543 --I;
544 }
545}
546
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +0000547/// LookUpIdentifierInfo - Given a tok::raw_identifier token, look up the
548/// identifier information for the token and install it into the token,
549/// updating the token kind accordingly.
550IdentifierInfo *Preprocessor::LookUpIdentifierInfo(Token &Identifier) const {
551 assert(Identifier.getRawIdentifierData() != 0 && "No raw identifier data!");
Mike Stump11289f42009-09-09 15:08:12 +0000552
Chris Lattnercefc7682006-07-08 08:28:12 +0000553 // Look up this token, see if it is a macro, or if it is a language keyword.
554 IdentifierInfo *II;
Jordan Rose7f43ddd2013-01-24 20:50:46 +0000555 if (!Identifier.needsCleaning() && !Identifier.hasUCN()) {
Chris Lattnercefc7682006-07-08 08:28:12 +0000556 // No cleaning needed, just use the characters from the lexed buffer.
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000557 II = getIdentifierInfo(StringRef(Identifier.getRawIdentifierData(),
Jordan Rose7f43ddd2013-01-24 20:50:46 +0000558 Identifier.getLength()));
Chris Lattnercefc7682006-07-08 08:28:12 +0000559 } else {
560 // Cleaning needed, alloca a buffer, clean into it, then use the buffer.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +0000561 SmallString<64> IdentifierBuffer;
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000562 StringRef CleanedStr = getSpelling(Identifier, IdentifierBuffer);
Jordan Rose7f43ddd2013-01-24 20:50:46 +0000563
564 if (Identifier.hasUCN()) {
565 SmallString<64> UCNIdentifierBuffer;
566 expandUCNs(UCNIdentifierBuffer, CleanedStr);
567 II = getIdentifierInfo(UCNIdentifierBuffer);
568 } else {
569 II = getIdentifierInfo(CleanedStr);
570 }
Chris Lattnercefc7682006-07-08 08:28:12 +0000571 }
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +0000572
573 // Update the token info (identifier info and appropriate token kind).
Chris Lattner8c204872006-10-14 05:19:21 +0000574 Identifier.setIdentifierInfo(II);
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +0000575 Identifier.setKind(II->getTokenID());
576
Chris Lattnercefc7682006-07-08 08:28:12 +0000577 return II;
578}
579
John Wiegley1c0675e2011-04-28 01:08:34 +0000580void Preprocessor::SetPoisonReason(IdentifierInfo *II, unsigned DiagID) {
581 PoisonReasons[II] = DiagID;
582}
583
584void Preprocessor::PoisonSEHIdentifiers(bool Poison) {
585 assert(Ident__exception_code && Ident__exception_info);
586 assert(Ident___exception_code && Ident___exception_info);
587 Ident__exception_code->setIsPoisoned(Poison);
588 Ident___exception_code->setIsPoisoned(Poison);
589 Ident_GetExceptionCode->setIsPoisoned(Poison);
590 Ident__exception_info->setIsPoisoned(Poison);
591 Ident___exception_info->setIsPoisoned(Poison);
592 Ident_GetExceptionInfo->setIsPoisoned(Poison);
593 Ident__abnormal_termination->setIsPoisoned(Poison);
594 Ident___abnormal_termination->setIsPoisoned(Poison);
595 Ident_AbnormalTermination->setIsPoisoned(Poison);
596}
597
598void Preprocessor::HandlePoisonedIdentifier(Token & Identifier) {
599 assert(Identifier.getIdentifierInfo() &&
600 "Can't handle identifiers without identifier info!");
601 llvm::DenseMap<IdentifierInfo*,unsigned>::const_iterator it =
602 PoisonReasons.find(Identifier.getIdentifierInfo());
603 if(it == PoisonReasons.end())
604 Diag(Identifier, diag::err_pp_used_poisoned_id);
605 else
606 Diag(Identifier,it->second) << Identifier.getIdentifierInfo();
607}
Chris Lattnercefc7682006-07-08 08:28:12 +0000608
Chris Lattner677757a2006-06-28 05:26:32 +0000609/// HandleIdentifier - This callback is invoked when the lexer reads an
610/// identifier. This callback looks up the identifier in the map and/or
611/// potentially macro expands it or turns it into a named token (like 'for').
Chris Lattnerad89ec02009-01-21 07:43:11 +0000612///
613/// Note that callers of this method are guarded by checking the
614/// IdentifierInfo's 'isHandleIdentifierCase' bit. If this method changes, the
615/// IdentifierInfo methods that compute these properties will need to change to
616/// match.
Eli Friedman0834a4b2013-09-19 00:41:32 +0000617bool Preprocessor::HandleIdentifier(Token &Identifier) {
Chris Lattner0f1f5052006-07-20 04:16:23 +0000618 assert(Identifier.getIdentifierInfo() &&
619 "Can't handle identifiers without identifier info!");
Mike Stump11289f42009-09-09 15:08:12 +0000620
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000621 IdentifierInfo &II = *Identifier.getIdentifierInfo();
Chris Lattner677757a2006-06-28 05:26:32 +0000622
Douglas Gregor935bc7a22011-10-27 09:33:13 +0000623 // If the information about this identifier is out of date, update it from
624 // the external source.
Douglas Gregor3f568c12012-06-29 18:27:59 +0000625 // We have to treat __VA_ARGS__ in a special way, since it gets
626 // serialized with isPoisoned = true, but our preprocessor may have
627 // unpoisoned it if we're defining a C99 macro.
Douglas Gregor935bc7a22011-10-27 09:33:13 +0000628 if (II.isOutOfDate()) {
Douglas Gregor3f568c12012-06-29 18:27:59 +0000629 bool CurrentIsPoisoned = false;
630 if (&II == Ident__VA_ARGS__)
631 CurrentIsPoisoned = Ident__VA_ARGS__->isPoisoned();
632
Douglas Gregor935bc7a22011-10-27 09:33:13 +0000633 ExternalSource->updateOutOfDateIdentifier(II);
634 Identifier.setKind(II.getTokenID());
Douglas Gregor3f568c12012-06-29 18:27:59 +0000635
636 if (&II == Ident__VA_ARGS__)
637 II.setIsPoisoned(CurrentIsPoisoned);
Douglas Gregor935bc7a22011-10-27 09:33:13 +0000638 }
639
Chris Lattner677757a2006-06-28 05:26:32 +0000640 // If this identifier was poisoned, and if it was not produced from a macro
641 // expansion, emit an error.
Ted Kremeneka2c3c8d2008-11-19 22:43:49 +0000642 if (II.isPoisoned() && CurPPLexer) {
John Wiegley1c0675e2011-04-28 01:08:34 +0000643 HandlePoisonedIdentifier(Identifier);
Chris Lattner8ff71992006-07-06 05:17:39 +0000644 }
Mike Stump11289f42009-09-09 15:08:12 +0000645
Chris Lattner78186052006-07-09 00:45:31 +0000646 // If this is a macro to be expanded, do it.
Argyrios Kyrtzidisfead64b2013-02-24 00:05:14 +0000647 if (MacroDirective *MD = getMacroDirective(&II)) {
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +0000648 MacroInfo *MI = MD->getMacroInfo();
Abramo Bagnara123bec82012-01-01 22:01:04 +0000649 if (!DisableMacroExpansion) {
Richard Smith181879c2012-12-12 02:46:14 +0000650 if (!Identifier.isExpandDisabled() && MI->isEnabled()) {
Eli Friedman0834a4b2013-09-19 00:41:32 +0000651 // C99 6.10.3p10: If the preprocessing token immediately after the
652 // macro name isn't a '(', this macro should not be expanded.
653 if (!MI->isFunctionLike() || isNextPPTokenLParen())
654 return HandleMacroExpandedIdentifier(Identifier, MD);
Chris Lattner6e4bf522006-07-27 06:59:25 +0000655 } else {
656 // C99 6.10.3.4p2 says that a disabled macro may never again be
657 // expanded, even if it's in a context where it could be expanded in the
658 // future.
Chris Lattner146762e2007-07-20 16:59:19 +0000659 Identifier.setFlag(Token::DisableExpand);
Richard Smith181879c2012-12-12 02:46:14 +0000660 if (MI->isObjectLike() || isNextPPTokenLParen())
661 Diag(Identifier, diag::pp_disabled_macro_expansion);
Chris Lattner6e4bf522006-07-27 06:59:25 +0000662 }
663 }
Chris Lattner063400e2006-10-14 19:54:15 +0000664 }
Chris Lattner677757a2006-06-28 05:26:32 +0000665
Richard Smith4dd85d62011-10-11 19:57:52 +0000666 // If this identifier is a keyword in C++11, produce a warning. Don't warn if
667 // we're not considering macro expansion, since this identifier might be the
668 // name of a macro.
669 // FIXME: This warning is disabled in cases where it shouldn't be, like
670 // "#define constexpr constexpr", "int constexpr;"
671 if (II.isCXX11CompatKeyword() & !DisableMacroExpansion) {
672 Diag(Identifier, diag::warn_cxx11_keyword) << II.getName();
673 // Don't diagnose this keyword again in this translation unit.
674 II.setIsCXX11CompatKeyword(false);
675 }
676
Chris Lattner5b9f4892006-11-21 17:23:33 +0000677 // C++ 2.11p2: If this is an alternative representation of a C++ operator,
678 // then we act as if it is the actual operator and not the textual
679 // representation of it.
Fariborz Jahanian9e42a952010-09-03 17:33:04 +0000680 if (II.isCPlusPlusOperatorKeyword())
Chris Lattner5b9f4892006-11-21 17:23:33 +0000681 Identifier.setIdentifierInfo(0);
682
Chris Lattner677757a2006-06-28 05:26:32 +0000683 // If this is an extension token, diagnose its use.
Steve Naroffc84e8b72008-09-02 18:50:17 +0000684 // We avoid diagnosing tokens that originate from macro definitions.
Eli Friedman6bba2ad2009-04-28 03:59:15 +0000685 // FIXME: This warning is disabled in cases where it shouldn't be,
686 // like "#define TY typeof", "TY(1) x".
687 if (II.isExtensionToken() && !DisableMacroExpansion)
Chris Lattner53621a52007-06-13 20:44:40 +0000688 Diag(Identifier, diag::ext_token_used);
Douglas Gregoraf5c4842011-09-07 23:11:54 +0000689
Douglas Gregorc50d4922012-12-11 22:11:52 +0000690 // If this is the 'import' contextual keyword, note
Ted Kremenekc1e4dd02012-03-01 22:07:04 +0000691 // that the next token indicates a module name.
Douglas Gregor8d76cca2012-01-04 06:20:15 +0000692 //
Douglas Gregorc50d4922012-12-11 22:11:52 +0000693 // Note that we do not treat 'import' as a contextual
Ted Kremenekc1e4dd02012-03-01 22:07:04 +0000694 // keyword when we're in a caching lexer, because caching lexers only get
695 // used in contexts where import declarations are disallowed.
696 if (II.isModulesImport() && !InMacroArgs && !DisableMacroExpansion &&
David Blaikiebbafb8a2012-03-11 07:00:24 +0000697 getLangOpts().Modules && CurLexerKind != CLK_CachingLexer) {
Douglas Gregoraf5c4842011-09-07 23:11:54 +0000698 ModuleImportLoc = Identifier.getLocation();
Douglas Gregor1805b8a2011-11-30 04:26:53 +0000699 ModuleImportPath.clear();
700 ModuleImportExpectsIdentifier = true;
Douglas Gregoraf5c4842011-09-07 23:11:54 +0000701 CurLexerKind = CLK_LexAfterModuleImport;
702 }
Eli Friedman0834a4b2013-09-19 00:41:32 +0000703 return true;
Douglas Gregor08142532011-08-26 23:56:07 +0000704}
705
Eli Friedman0834a4b2013-09-19 00:41:32 +0000706void Preprocessor::Lex(Token &Result) {
707 // We loop here until a lex function retuns a token; this avoids recursion.
708 bool ReturnedToken;
709 do {
710 switch (CurLexerKind) {
711 case CLK_Lexer:
712 ReturnedToken = CurLexer->Lex(Result);
713 break;
714 case CLK_PTHLexer:
715 ReturnedToken = CurPTHLexer->Lex(Result);
716 break;
717 case CLK_TokenLexer:
718 ReturnedToken = CurTokenLexer->Lex(Result);
719 break;
720 case CLK_CachingLexer:
721 CachingLex(Result);
722 ReturnedToken = true;
723 break;
724 case CLK_LexAfterModuleImport:
725 LexAfterModuleImport(Result);
726 ReturnedToken = true;
727 break;
728 }
729 } while (!ReturnedToken);
730}
731
732
Douglas Gregorda82e702012-01-03 19:32:59 +0000733/// \brief Lex a token following the 'import' contextual keyword.
Douglas Gregor22d09742012-01-03 18:04:46 +0000734///
Douglas Gregoraf5c4842011-09-07 23:11:54 +0000735void Preprocessor::LexAfterModuleImport(Token &Result) {
736 // Figure out what kind of lexer we actually have.
Douglas Gregor8d76cca2012-01-04 06:20:15 +0000737 recomputeCurLexerKind();
Douglas Gregoraf5c4842011-09-07 23:11:54 +0000738
739 // Lex the next token.
740 Lex(Result);
741
Douglas Gregor08142532011-08-26 23:56:07 +0000742 // The token sequence
743 //
Douglas Gregor22d09742012-01-03 18:04:46 +0000744 // import identifier (. identifier)*
745 //
Douglas Gregorda82e702012-01-03 19:32:59 +0000746 // indicates a module import directive. We already saw the 'import'
747 // contextual keyword, so now we're looking for the identifiers.
Douglas Gregor1805b8a2011-11-30 04:26:53 +0000748 if (ModuleImportExpectsIdentifier && Result.getKind() == tok::identifier) {
749 // We expected to see an identifier here, and we did; continue handling
750 // identifiers.
751 ModuleImportPath.push_back(std::make_pair(Result.getIdentifierInfo(),
752 Result.getLocation()));
753 ModuleImportExpectsIdentifier = false;
754 CurLexerKind = CLK_LexAfterModuleImport;
Douglas Gregor08142532011-08-26 23:56:07 +0000755 return;
Douglas Gregor1805b8a2011-11-30 04:26:53 +0000756 }
Douglas Gregor08142532011-08-26 23:56:07 +0000757
Douglas Gregor1805b8a2011-11-30 04:26:53 +0000758 // If we're expecting a '.' or a ';', and we got a '.', then wait until we
759 // see the next identifier.
760 if (!ModuleImportExpectsIdentifier && Result.getKind() == tok::period) {
761 ModuleImportExpectsIdentifier = true;
762 CurLexerKind = CLK_LexAfterModuleImport;
763 return;
764 }
765
766 // If we have a non-empty module path, load the named module.
Daniel Jasper07e6c402013-08-05 20:26:17 +0000767 if (!ModuleImportPath.empty() && getLangOpts().Modules) {
Argyrios Kyrtzidis19d78b72012-09-29 01:06:10 +0000768 Module *Imported = TheModuleLoader.loadModule(ModuleImportLoc,
769 ModuleImportPath,
770 Module::MacrosVisible,
771 /*IsIncludeDirective=*/false);
772 if (Callbacks)
773 Callbacks->moduleImport(ModuleImportLoc, ModuleImportPath, Imported);
774 }
Chris Lattner677757a2006-06-28 05:26:32 +0000775}
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000776
Andy Gibbs58905d22012-11-17 19:15:38 +0000777bool Preprocessor::FinishLexStringLiteral(Token &Result, std::string &String,
Andy Gibbsa8df57a2012-11-17 19:16:52 +0000778 const char *DiagnosticTag,
Andy Gibbs58905d22012-11-17 19:15:38 +0000779 bool AllowMacroExpansion) {
780 // We need at least one string literal.
781 if (Result.isNot(tok::string_literal)) {
Andy Gibbsa8df57a2012-11-17 19:16:52 +0000782 Diag(Result, diag::err_expected_string_literal)
783 << /*Source='in...'*/0 << DiagnosticTag;
Andy Gibbs58905d22012-11-17 19:15:38 +0000784 return false;
785 }
786
787 // Lex string literal tokens, optionally with macro expansion.
788 SmallVector<Token, 4> StrToks;
789 do {
790 StrToks.push_back(Result);
791
792 if (Result.hasUDSuffix())
793 Diag(Result, diag::err_invalid_string_udl);
794
795 if (AllowMacroExpansion)
796 Lex(Result);
797 else
798 LexUnexpandedToken(Result);
799 } while (Result.is(tok::string_literal));
800
801 // Concatenate and parse the strings.
802 StringLiteralParser Literal(&StrToks[0], StrToks.size(), *this);
803 assert(Literal.isAscii() && "Didn't allow wide strings in");
804
805 if (Literal.hadError)
806 return false;
807
808 if (Literal.Pascal) {
Andy Gibbsa8df57a2012-11-17 19:16:52 +0000809 Diag(StrToks[0].getLocation(), diag::err_expected_string_literal)
810 << /*Source='in...'*/0 << DiagnosticTag;
Andy Gibbs58905d22012-11-17 19:15:38 +0000811 return false;
812 }
813
814 String = Literal.GetString();
815 return true;
816}
817
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000818void Preprocessor::addCommentHandler(CommentHandler *Handler) {
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000819 assert(Handler && "NULL comment handler");
820 assert(std::find(CommentHandlers.begin(), CommentHandlers.end(), Handler) ==
821 CommentHandlers.end() && "Comment handler already registered");
822 CommentHandlers.push_back(Handler);
823}
824
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000825void Preprocessor::removeCommentHandler(CommentHandler *Handler) {
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000826 std::vector<CommentHandler *>::iterator Pos
827 = std::find(CommentHandlers.begin(), CommentHandlers.end(), Handler);
828 assert(Pos != CommentHandlers.end() && "Comment handler not registered");
829 CommentHandlers.erase(Pos);
830}
831
Chris Lattner87d02082010-01-18 22:35:47 +0000832bool Preprocessor::HandleComment(Token &result, SourceRange Comment) {
833 bool AnyPendingTokens = false;
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000834 for (std::vector<CommentHandler *>::iterator H = CommentHandlers.begin(),
835 HEnd = CommentHandlers.end();
Chris Lattner87d02082010-01-18 22:35:47 +0000836 H != HEnd; ++H) {
837 if ((*H)->HandleComment(*this, Comment))
838 AnyPendingTokens = true;
839 }
840 if (!AnyPendingTokens || getCommentRetentionState())
841 return false;
842 Lex(result);
843 return true;
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000844}
845
Douglas Gregor08142532011-08-26 23:56:07 +0000846ModuleLoader::~ModuleLoader() { }
847
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000848CommentHandler::~CommentHandler() { }
Douglas Gregor7f6d60d2010-03-19 16:15:56 +0000849
Douglas Gregor3a7ad252010-08-24 19:08:16 +0000850CodeCompletionHandler::~CodeCompletionHandler() { }
851
Argyrios Kyrtzidisf3d587e2012-12-04 07:27:05 +0000852void Preprocessor::createPreprocessingRecord() {
Douglas Gregor7f6d60d2010-03-19 16:15:56 +0000853 if (Record)
854 return;
855
Argyrios Kyrtzidisf3d587e2012-12-04 07:27:05 +0000856 Record = new PreprocessingRecord(getSourceManager());
Douglas Gregor7dc87222010-03-19 17:12:43 +0000857 addPPCallbacks(Record);
Douglas Gregor7f6d60d2010-03-19 16:15:56 +0000858}