blob: ae28fc01e26a3478532ff6b60998bde9027300c9 [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"
Chandler Carruth3a022472012-12-04 09:13:33 +000029#include "clang/Basic/FileManager.h"
30#include "clang/Basic/SourceManager.h"
31#include "clang/Basic/TargetInfo.h"
32#include "clang/Lex/CodeCompletionHandler.h"
Douglas Gregor9882a5a2010-01-04 19:18:44 +000033#include "clang/Lex/ExternalPreprocessorSource.h"
Chris Lattner07b019a2006-10-22 07:28:56 +000034#include "clang/Lex/HeaderSearch.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000035#include "clang/Lex/LexDiagnostic.h"
36#include "clang/Lex/LiteralSupport.h"
Chandler Carruth5553d0d2014-01-07 11:51:46 +000037#include "clang/Lex/MacroArgs.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"
Jordan Rose7f43ddd2013-01-24 20:50:46 +000045#include "llvm/ADT/STLExtras.h"
Chandler Carruth5553d0d2014-01-07 11:51:46 +000046#include "llvm/ADT/SmallString.h"
Jordan Rose7f43ddd2013-01-24 20:50:46 +000047#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,
Alp Toker1ae02f62014-05-02 03:43:30 +000059 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,
Alp Toker1ae02f62014-05-02 03:43:30 +000062 TranslationUnitKind TUKind)
63 : PPOpts(PPOpts), Diags(&diags), LangOpts(opts), Target(0),
David Blaikie687cd952013-01-16 23:13:36 +000064 FileMgr(Headers.getFileMgr()), SourceMgr(SM), HeaderInfo(Headers),
65 TheModuleLoader(TheModuleLoader), ExternalSource(0),
Alp Toker23aa35322014-05-02 03:43:21 +000066 Identifiers(opts, IILookup), IncrementalProcessing(false),
Argyrios Kyrtzidise1974dc2014-03-07 07:47:58 +000067 TUKind(TUKind),
David Blaikief157e902013-01-16 23:18:16 +000068 CodeComplete(0), CodeCompletionFile(0), CodeCompletionOffset(0),
Douglas Gregor594b8c92013-11-07 22:55:02 +000069 LastTokenWasAt(false), ModuleImportExpectsIdentifier(false),
David Blaikief157e902013-01-16 23:18:16 +000070 CodeCompletionReached(0), SkipMainFilePreamble(0, true), CurPPLexer(0),
Richard Smith67294e22014-01-31 20:47:44 +000071 CurDirLookup(0), CurLexerKind(CLK_Lexer), CurSubmodule(0),
Richard Smith34f30512013-11-23 04:06:09 +000072 Callbacks(0), MacroArgCache(0), Record(0), MIChainHead(0), MICache(0),
Argyrios Kyrtzidisd48b91d2013-04-30 05:05:35 +000073 DeserialMIChainHead(0) {
Daniel Dunbar0c6c9302009-11-11 21:44:21 +000074 OwnsHeaderSearch = OwnsHeaders;
Douglas Gregor83297df2011-09-01 23:39:15 +000075
76 ScratchBuf = new ScratchBuffer(SourceMgr);
77 CounterValue = 0; // __COUNTER__ starts at 0.
78
79 // Clear stats.
80 NumDirectives = NumDefined = NumUndefined = NumPragma = 0;
81 NumIf = NumElse = NumEndif = 0;
82 NumEnteredSourceFiles = 0;
83 NumMacroExpanded = NumFnMacroExpanded = NumBuiltinMacroExpanded = 0;
84 NumFastMacroExpanded = NumTokenPaste = NumFastTokenPaste = 0;
85 MaxIncludeStackDepth = 0;
86 NumSkipped = 0;
87
88 // Default to discarding comments.
89 KeepComments = false;
90 KeepMacroComments = false;
91 SuppressIncludeNotFoundError = false;
92
93 // Macro expansion is enabled.
94 DisableMacroExpansion = false;
David Blaikied5321242012-06-06 18:52:13 +000095 MacroExpansionInDirectivesOverride = false;
Douglas Gregor83297df2011-09-01 23:39:15 +000096 InMacroArgs = false;
Argyrios Kyrtzidisf1b64c62012-04-03 16:47:40 +000097 InMacroArgPreExpansion = false;
Douglas Gregor83297df2011-09-01 23:39:15 +000098 NumCachedTokenLexers = 0;
Jordan Rosede1a2922012-06-08 18:06:21 +000099 PragmasEnabled = true;
Eric Christopher5e4696d2013-01-16 20:09:36 +0000100 ParsingIfOrElifDirective = false;
Jordan Rose324ec422013-01-31 19:26:01 +0000101 PreprocessedOutput = false;
Jordan Rosede1a2922012-06-08 18:06:21 +0000102
Douglas Gregor83297df2011-09-01 23:39:15 +0000103 CachedLexPos = 0;
Eric Christopher5e4696d2013-01-16 20:09:36 +0000104
Douglas Gregor83297df2011-09-01 23:39:15 +0000105 // We haven't read anything from the external source.
106 ReadMacrosFromExternalSource = false;
107
Douglas Gregor83297df2011-09-01 23:39:15 +0000108 // "Poison" __VA_ARGS__, which can only appear in the expansion of a macro.
109 // This gets unpoisoned where it is allowed.
110 (Ident__VA_ARGS__ = getIdentifierInfo("__VA_ARGS__"))->setIsPoisoned();
111 SetPoisonReason(Ident__VA_ARGS__,diag::ext_pp_bad_vaargs_use);
112
113 // Initialize the pragma handlers.
114 PragmaHandlers = new PragmaNamespace(StringRef());
115 RegisterBuiltinPragmas();
116
117 // Initialize builtin macros like __LINE__ and friends.
118 RegisterBuiltinMacros();
119
David Blaikiebbafb8a2012-03-11 07:00:24 +0000120 if(LangOpts.Borland) {
Douglas Gregor83297df2011-09-01 23:39:15 +0000121 Ident__exception_info = getIdentifierInfo("_exception_info");
122 Ident___exception_info = getIdentifierInfo("__exception_info");
123 Ident_GetExceptionInfo = getIdentifierInfo("GetExceptionInformation");
124 Ident__exception_code = getIdentifierInfo("_exception_code");
125 Ident___exception_code = getIdentifierInfo("__exception_code");
126 Ident_GetExceptionCode = getIdentifierInfo("GetExceptionCode");
127 Ident__abnormal_termination = getIdentifierInfo("_abnormal_termination");
128 Ident___abnormal_termination = getIdentifierInfo("__abnormal_termination");
129 Ident_AbnormalTermination = getIdentifierInfo("AbnormalTermination");
130 } else {
131 Ident__exception_info = Ident__exception_code = Ident__abnormal_termination = 0;
132 Ident___exception_info = Ident___exception_code = Ident___abnormal_termination = 0;
133 Ident_GetExceptionInfo = Ident_GetExceptionCode = Ident_AbnormalTermination = 0;
Douglas Gregor89929282012-01-30 06:01:29 +0000134 }
Argyrios Kyrtzidis3c9aaf12012-06-02 18:08:09 +0000135}
136
137Preprocessor::~Preprocessor() {
138 assert(BacktrackPositions.empty() && "EnableBacktrack/Backtrack imbalance!");
139
Benjamin Kramer329c5962014-03-15 16:40:40 +0000140 IncludeMacroStack.clear();
Argyrios Kyrtzidis3c9aaf12012-06-02 18:08:09 +0000141
142 // Free any macro definitions.
143 for (MacroInfoChain *I = MIChainHead ; I ; I = I->Next)
144 I->MI.Destroy();
145
146 // Free any cached macro expanders.
147 for (unsigned i = 0, e = NumCachedTokenLexers; i != e; ++i)
148 delete TokenLexerCache[i];
149
Argyrios Kyrtzidisd48b91d2013-04-30 05:05:35 +0000150 for (DeserializedMacroInfoChain *I = DeserialMIChainHead ; I ; I = I->Next)
151 I->MI.Destroy();
152
Argyrios Kyrtzidis3c9aaf12012-06-02 18:08:09 +0000153 // Free any cached MacroArgs.
154 for (MacroArgs *ArgList = MacroArgCache; ArgList; )
155 ArgList = ArgList->deallocate();
156
157 // Release pragma information.
158 delete PragmaHandlers;
159
160 // Delete the scratch buffer info.
161 delete ScratchBuf;
162
163 // Delete the header search info, if we own it.
164 if (OwnsHeaderSearch)
165 delete &HeaderInfo;
166
167 delete Callbacks;
168}
169
170void Preprocessor::Initialize(const TargetInfo &Target) {
171 assert((!this->Target || this->Target == &Target) &&
172 "Invalid override of target information");
173 this->Target = &Target;
Douglas Gregor89929282012-01-30 06:01:29 +0000174
Argyrios Kyrtzidis3c9aaf12012-06-02 18:08:09 +0000175 // Initialize information about built-ins.
176 BuiltinInfo.InitializeTarget(Target);
Douglas Gregor89929282012-01-30 06:01:29 +0000177 HeaderInfo.setTarget(Target);
Douglas Gregor83297df2011-09-01 23:39:15 +0000178}
179
Ted Kremeneka5c2c272009-02-12 03:26:59 +0000180void Preprocessor::setPTHManager(PTHManager* pm) {
181 PTH.reset(pm);
Douglas Gregord2eb58a2009-10-16 18:18:30 +0000182 FileMgr.addStatCache(PTH->createStatCache());
Ted Kremeneka5c2c272009-02-12 03:26:59 +0000183}
184
Chris Lattner146762e2007-07-20 16:59:19 +0000185void Preprocessor::DumpToken(const Token &Tok, bool DumpFlags) const {
Benjamin Kramer89b422c2009-08-23 12:08:50 +0000186 llvm::errs() << tok::getTokenName(Tok.getKind()) << " '"
187 << getSpelling(Tok) << "'";
Mike Stump11289f42009-09-09 15:08:12 +0000188
Chris Lattnerd01e2912006-06-18 16:22:51 +0000189 if (!DumpFlags) return;
Mike Stump11289f42009-09-09 15:08:12 +0000190
Benjamin Kramer89b422c2009-08-23 12:08:50 +0000191 llvm::errs() << "\t";
Chris Lattnerd01e2912006-06-18 16:22:51 +0000192 if (Tok.isAtStartOfLine())
Benjamin Kramer89b422c2009-08-23 12:08:50 +0000193 llvm::errs() << " [StartOfLine]";
Chris Lattnerd01e2912006-06-18 16:22:51 +0000194 if (Tok.hasLeadingSpace())
Benjamin Kramer89b422c2009-08-23 12:08:50 +0000195 llvm::errs() << " [LeadingSpace]";
Chris Lattner6e4bf522006-07-27 06:59:25 +0000196 if (Tok.isExpandDisabled())
Benjamin Kramer89b422c2009-08-23 12:08:50 +0000197 llvm::errs() << " [ExpandDisabled]";
Chris Lattnerd01e2912006-06-18 16:22:51 +0000198 if (Tok.needsCleaning()) {
Chris Lattner50b497e2006-06-18 16:32:35 +0000199 const char *Start = SourceMgr.getCharacterData(Tok.getLocation());
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000200 llvm::errs() << " [UnClean='" << StringRef(Start, Tok.getLength())
Benjamin Kramer89b422c2009-08-23 12:08:50 +0000201 << "']";
Chris Lattnerd01e2912006-06-18 16:22:51 +0000202 }
Mike Stump11289f42009-09-09 15:08:12 +0000203
Benjamin Kramer89b422c2009-08-23 12:08:50 +0000204 llvm::errs() << "\tLoc=<";
Chris Lattner615315f2007-12-09 20:31:55 +0000205 DumpLocation(Tok.getLocation());
Benjamin Kramer89b422c2009-08-23 12:08:50 +0000206 llvm::errs() << ">";
Chris Lattner615315f2007-12-09 20:31:55 +0000207}
208
209void Preprocessor::DumpLocation(SourceLocation Loc) const {
Chris Lattnerf1ca7d32009-01-27 07:57:44 +0000210 Loc.dump(SourceMgr);
Chris Lattnerd01e2912006-06-18 16:22:51 +0000211}
212
213void Preprocessor::DumpMacro(const MacroInfo &MI) const {
Benjamin Kramer89b422c2009-08-23 12:08:50 +0000214 llvm::errs() << "MACRO: ";
Chris Lattnerd01e2912006-06-18 16:22:51 +0000215 for (unsigned i = 0, e = MI.getNumTokens(); i != e; ++i) {
216 DumpToken(MI.getReplacementToken(i));
Benjamin Kramer89b422c2009-08-23 12:08:50 +0000217 llvm::errs() << " ";
Chris Lattnerd01e2912006-06-18 16:22:51 +0000218 }
Benjamin Kramer89b422c2009-08-23 12:08:50 +0000219 llvm::errs() << "\n";
Chris Lattnerd01e2912006-06-18 16:22:51 +0000220}
221
Chris Lattner22eb9722006-06-18 05:43:12 +0000222void Preprocessor::PrintStats() {
Benjamin Kramer89b422c2009-08-23 12:08:50 +0000223 llvm::errs() << "\n*** Preprocessor Stats:\n";
224 llvm::errs() << NumDirectives << " directives found:\n";
225 llvm::errs() << " " << NumDefined << " #define.\n";
226 llvm::errs() << " " << NumUndefined << " #undef.\n";
227 llvm::errs() << " #include/#include_next/#import:\n";
228 llvm::errs() << " " << NumEnteredSourceFiles << " source files entered.\n";
229 llvm::errs() << " " << MaxIncludeStackDepth << " max include stack depth\n";
230 llvm::errs() << " " << NumIf << " #if/#ifndef/#ifdef.\n";
231 llvm::errs() << " " << NumElse << " #else/#elif.\n";
232 llvm::errs() << " " << NumEndif << " #endif.\n";
233 llvm::errs() << " " << NumPragma << " #pragma.\n";
234 llvm::errs() << NumSkipped << " #if/#ifndef#ifdef regions skipped\n";
Chris Lattner22eb9722006-06-18 05:43:12 +0000235
Benjamin Kramer89b422c2009-08-23 12:08:50 +0000236 llvm::errs() << NumMacroExpanded << "/" << NumFnMacroExpanded << "/"
Ted Kremeneka0a3e9b2008-01-14 16:44:48 +0000237 << NumBuiltinMacroExpanded << " obj/fn/builtin macros expanded, "
238 << NumFastMacroExpanded << " on the fast path.\n";
Benjamin Kramer89b422c2009-08-23 12:08:50 +0000239 llvm::errs() << (NumFastTokenPaste+NumTokenPaste)
Ted Kremeneka0a3e9b2008-01-14 16:44:48 +0000240 << " token paste (##) operations performed, "
241 << NumFastTokenPaste << " on the fast path.\n";
Alexander Kornienko199cd942012-08-13 10:46:42 +0000242
243 llvm::errs() << "\nPreprocessor Memory: " << getTotalMemory() << "B total";
244
245 llvm::errs() << "\n BumpPtr: " << BP.getTotalMemory();
246 llvm::errs() << "\n Macro Expanded Tokens: "
247 << llvm::capacity_in_bytes(MacroExpandedTokens);
248 llvm::errs() << "\n Predefines Buffer: " << Predefines.capacity();
249 llvm::errs() << "\n Macros: " << llvm::capacity_in_bytes(Macros);
250 llvm::errs() << "\n #pragma push_macro Info: "
251 << llvm::capacity_in_bytes(PragmaPushMacroInfo);
252 llvm::errs() << "\n Poison Reasons: "
253 << llvm::capacity_in_bytes(PoisonReasons);
254 llvm::errs() << "\n Comment Handlers: "
255 << llvm::capacity_in_bytes(CommentHandlers) << "\n";
Chris Lattner22eb9722006-06-18 05:43:12 +0000256}
257
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +0000258Preprocessor::macro_iterator
259Preprocessor::macro_begin(bool IncludeExternalMacros) const {
260 if (IncludeExternalMacros && ExternalSource &&
Douglas Gregor9882a5a2010-01-04 19:18:44 +0000261 !ReadMacrosFromExternalSource) {
262 ReadMacrosFromExternalSource = true;
263 ExternalSource->ReadDefinedMacros();
264 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +0000265
266 return Macros.begin();
Douglas Gregor9882a5a2010-01-04 19:18:44 +0000267}
268
Argyrios Kyrtzidise379ee32011-06-29 22:20:04 +0000269size_t Preprocessor::getTotalMemory() const {
Ted Kremenek182543a2011-07-26 21:17:24 +0000270 return BP.getTotalMemory()
Ted Kremenek8b77fe72011-07-27 18:41:23 +0000271 + llvm::capacity_in_bytes(MacroExpandedTokens)
Ted Kremenek182543a2011-07-26 21:17:24 +0000272 + Predefines.capacity() /* Predefines buffer. */
Ted Kremenek8b77fe72011-07-27 18:41:23 +0000273 + llvm::capacity_in_bytes(Macros)
274 + llvm::capacity_in_bytes(PragmaPushMacroInfo)
275 + llvm::capacity_in_bytes(PoisonReasons)
276 + llvm::capacity_in_bytes(CommentHandlers);
Argyrios Kyrtzidise379ee32011-06-29 22:20:04 +0000277}
278
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +0000279Preprocessor::macro_iterator
280Preprocessor::macro_end(bool IncludeExternalMacros) const {
281 if (IncludeExternalMacros && ExternalSource &&
Douglas Gregor9882a5a2010-01-04 19:18:44 +0000282 !ReadMacrosFromExternalSource) {
283 ReadMacrosFromExternalSource = true;
284 ExternalSource->ReadDefinedMacros();
285 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +0000286
287 return Macros.end();
Douglas Gregor9882a5a2010-01-04 19:18:44 +0000288}
289
Dmitri Gribenko6743e042012-09-29 11:40:46 +0000290/// \brief Compares macro tokens with a specified token value sequence.
291static bool MacroDefinitionEquals(const MacroInfo *MI,
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000292 ArrayRef<TokenValue> Tokens) {
Dmitri Gribenko6743e042012-09-29 11:40:46 +0000293 return Tokens.size() == MI->getNumTokens() &&
294 std::equal(Tokens.begin(), Tokens.end(), MI->tokens_begin());
295}
296
297StringRef Preprocessor::getLastMacroWithSpelling(
298 SourceLocation Loc,
299 ArrayRef<TokenValue> Tokens) const {
300 SourceLocation BestLocation;
301 StringRef BestSpelling;
302 for (Preprocessor::macro_iterator I = macro_begin(), E = macro_end();
303 I != E; ++I) {
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +0000304 if (!I->second->getMacroInfo()->isObjectLike())
Dmitri Gribenko6743e042012-09-29 11:40:46 +0000305 continue;
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +0000306 const MacroDirective::DefInfo
307 Def = I->second->findDirectiveAtLoc(Loc, SourceMgr);
308 if (!Def)
Dmitri Gribenko6743e042012-09-29 11:40:46 +0000309 continue;
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +0000310 if (!MacroDefinitionEquals(Def.getMacroInfo(), Tokens))
Dmitri Gribenko6743e042012-09-29 11:40:46 +0000311 continue;
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +0000312 SourceLocation Location = Def.getLocation();
Dmitri Gribenko6743e042012-09-29 11:40:46 +0000313 // Choose the macro defined latest.
314 if (BestLocation.isInvalid() ||
315 (Location.isValid() &&
316 SourceMgr.isBeforeInTranslationUnit(BestLocation, Location))) {
317 BestLocation = Location;
318 BestSpelling = I->first->getName();
319 }
320 }
321 return BestSpelling;
322}
323
Douglas Gregor8d76cca2012-01-04 06:20:15 +0000324void Preprocessor::recomputeCurLexerKind() {
325 if (CurLexer)
326 CurLexerKind = CLK_Lexer;
327 else if (CurPTHLexer)
328 CurLexerKind = CLK_PTHLexer;
329 else if (CurTokenLexer)
330 CurLexerKind = CLK_TokenLexer;
331 else
332 CurLexerKind = CLK_CachingLexer;
333}
334
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +0000335bool Preprocessor::SetCodeCompletionPoint(const FileEntry *File,
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +0000336 unsigned CompleteLine,
337 unsigned CompleteColumn) {
338 assert(File);
339 assert(CompleteLine && CompleteColumn && "Starts from 1:1");
340 assert(!CodeCompletionFile && "Already set");
341
Douglas Gregor53ad6b92009-12-02 06:49:09 +0000342 using llvm::MemoryBuffer;
343
Douglas Gregor53ad6b92009-12-02 06:49:09 +0000344 // Load the actual file's contents.
Douglas Gregor26266da2010-03-16 19:49:24 +0000345 bool Invalid = false;
346 const MemoryBuffer *Buffer = SourceMgr.getMemoryBufferForFile(File, &Invalid);
347 if (Invalid)
Douglas Gregor53ad6b92009-12-02 06:49:09 +0000348 return true;
349
350 // Find the byte position of the truncation point.
351 const char *Position = Buffer->getBufferStart();
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +0000352 for (unsigned Line = 1; Line < CompleteLine; ++Line) {
Douglas Gregor53ad6b92009-12-02 06:49:09 +0000353 for (; *Position; ++Position) {
354 if (*Position != '\r' && *Position != '\n')
355 continue;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +0000356
Douglas Gregor53ad6b92009-12-02 06:49:09 +0000357 // Eat \r\n or \n\r as a single line.
358 if ((Position[1] == '\r' || Position[1] == '\n') &&
359 Position[0] != Position[1])
360 ++Position;
361 ++Position;
362 break;
363 }
364 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +0000365
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +0000366 Position += CompleteColumn - 1;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +0000367
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +0000368 // Insert '\0' at the code-completion point.
Douglas Gregor9291ab62009-12-08 21:45:46 +0000369 if (Position < Buffer->getBufferEnd()) {
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +0000370 CodeCompletionFile = File;
371 CodeCompletionOffset = Position - Buffer->getBufferStart();
372
373 MemoryBuffer *NewBuffer =
374 MemoryBuffer::getNewUninitMemBuffer(Buffer->getBufferSize() + 1,
375 Buffer->getBufferIdentifier());
Benjamin Kramer60053cf2011-09-04 20:26:28 +0000376 char *NewBuf = const_cast<char*>(NewBuffer->getBufferStart());
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +0000377 char *NewPos = std::copy(Buffer->getBufferStart(), Position, NewBuf);
378 *NewPos = '\0';
379 std::copy(Position, Buffer->getBufferEnd(), NewPos+1);
380 SourceMgr.overrideFileContents(File, NewBuffer);
Douglas Gregor53ad6b92009-12-02 06:49:09 +0000381 }
382
383 return false;
384}
385
Douglas Gregor11583702010-08-25 17:04:25 +0000386void Preprocessor::CodeCompleteNaturalLanguage() {
Douglas Gregor11583702010-08-25 17:04:25 +0000387 if (CodeComplete)
388 CodeComplete->CodeCompleteNaturalLanguage();
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +0000389 setCodeCompletionReached();
Douglas Gregor11583702010-08-25 17:04:25 +0000390}
391
Benjamin Kramera197fb62010-02-27 17:05:45 +0000392/// getSpelling - This method is used to get the spelling of a token into a
393/// SmallVector. Note that the returned StringRef may not point to the
394/// supplied buffer if a copy can be avoided.
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000395StringRef Preprocessor::getSpelling(const Token &Tok,
396 SmallVectorImpl<char> &Buffer,
Douglas Gregor7bda4b82010-03-16 05:20:39 +0000397 bool *Invalid) const {
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +0000398 // NOTE: this has to be checked *before* testing for an IdentifierInfo.
Jordan Rose7f43ddd2013-01-24 20:50:46 +0000399 if (Tok.isNot(tok::raw_identifier) && !Tok.hasUCN()) {
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +0000400 // Try the fast path.
401 if (const IdentifierInfo *II = Tok.getIdentifierInfo())
402 return II->getName();
403 }
Benjamin Kramera197fb62010-02-27 17:05:45 +0000404
405 // Resize the buffer if we need to copy into it.
406 if (Tok.needsCleaning())
407 Buffer.resize(Tok.getLength());
408
409 const char *Ptr = Buffer.data();
Douglas Gregor7bda4b82010-03-16 05:20:39 +0000410 unsigned Len = getSpelling(Tok, Ptr, Invalid);
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000411 return StringRef(Ptr, Len);
Benjamin Kramera197fb62010-02-27 17:05:45 +0000412}
413
Chris Lattnerb94ec7b2006-07-14 06:54:10 +0000414/// CreateString - Plop the specified string into a scratch buffer and return a
415/// location for it. If specified, the source location provides a source
416/// location for the token.
Dmitri Gribenkob8e9e752012-09-24 21:07:17 +0000417void Preprocessor::CreateString(StringRef Str, Token &Tok,
Abramo Bagnarae398e602011-10-03 18:39:03 +0000418 SourceLocation ExpansionLocStart,
419 SourceLocation ExpansionLocEnd) {
Dmitri Gribenkob8e9e752012-09-24 21:07:17 +0000420 Tok.setLength(Str.size());
Mike Stump11289f42009-09-09 15:08:12 +0000421
Chris Lattner5a7971e2009-01-26 19:29:26 +0000422 const char *DestPtr;
Dmitri Gribenkob8e9e752012-09-24 21:07:17 +0000423 SourceLocation Loc = ScratchBuf->getToken(Str.data(), Str.size(), DestPtr);
Mike Stump11289f42009-09-09 15:08:12 +0000424
Abramo Bagnarae398e602011-10-03 18:39:03 +0000425 if (ExpansionLocStart.isValid())
426 Loc = SourceMgr.createExpansionLoc(Loc, ExpansionLocStart,
Dmitri Gribenkob8e9e752012-09-24 21:07:17 +0000427 ExpansionLocEnd, Str.size());
Chris Lattner5a7971e2009-01-26 19:29:26 +0000428 Tok.setLocation(Loc);
Mike Stump11289f42009-09-09 15:08:12 +0000429
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +0000430 // If this is a raw identifier or a literal token, set the pointer data.
431 if (Tok.is(tok::raw_identifier))
432 Tok.setRawIdentifierData(DestPtr);
433 else if (Tok.isLiteral())
Chris Lattner5a7971e2009-01-26 19:29:26 +0000434 Tok.setLiteralData(DestPtr);
Chris Lattnerb94ec7b2006-07-14 06:54:10 +0000435}
436
Douglas Gregor2b82c2a2011-12-02 01:47:07 +0000437Module *Preprocessor::getCurrentModule() {
David Blaikiebbafb8a2012-03-11 07:00:24 +0000438 if (getLangOpts().CurrentModule.empty())
Douglas Gregor2b82c2a2011-12-02 01:47:07 +0000439 return 0;
440
David Blaikiebbafb8a2012-03-11 07:00:24 +0000441 return getHeaderSearchInfo().lookupModule(getLangOpts().CurrentModule);
Douglas Gregor2b82c2a2011-12-02 01:47:07 +0000442}
Chris Lattner8a7003c2007-07-16 06:48:38 +0000443
Chris Lattner1f1b0db2007-10-09 22:10:18 +0000444//===----------------------------------------------------------------------===//
445// Preprocessor Initialization Methods
446//===----------------------------------------------------------------------===//
447
Chris Lattner1f1b0db2007-10-09 22:10:18 +0000448
449/// EnterMainSourceFile - Enter the specified FileID as the main source file,
Nate Begemanf7c3ff62008-01-07 04:01:26 +0000450/// which implicitly adds the builtin defines etc.
Chris Lattnerfb24a3a2010-04-20 20:35:58 +0000451void Preprocessor::EnterMainSourceFile() {
Chris Lattner9ef847b2009-02-13 19:33:24 +0000452 // We do not allow the preprocessor to reenter the main file. Doing so will
453 // cause FileID's to accumulate information from both runs (e.g. #line
454 // information) and predefined macros aren't guaranteed to be set properly.
455 assert(NumEnteredSourceFiles == 0 && "Cannot reenter the main file!");
Chris Lattnerd32480d2009-01-17 06:22:33 +0000456 FileID MainFileID = SourceMgr.getMainFileID();
Mike Stump11289f42009-09-09 15:08:12 +0000457
Argyrios Kyrtzidis9afd4492012-01-05 21:36:25 +0000458 // If MainFileID is loaded it means we loaded an AST file, no need to enter
459 // a main file.
460 if (!SourceMgr.isLoadedFileID(MainFileID)) {
461 // Enter the main file source buffer.
462 EnterSourceFile(MainFileID, 0, SourceLocation());
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000463
Argyrios Kyrtzidis9afd4492012-01-05 21:36:25 +0000464 // If we've been asked to skip bytes in the main file (e.g., as part of a
465 // precompiled preamble), do so now.
466 if (SkipMainFilePreamble.first > 0)
467 CurLexer->SkipBytes(SkipMainFilePreamble.first,
468 SkipMainFilePreamble.second);
469
470 // Tell the header info that the main file was entered. If the file is later
471 // #imported, it won't be re-entered.
472 if (const FileEntry *FE = SourceMgr.getFileEntryForID(MainFileID))
473 HeaderInfo.IncrementIncludeCount(FE);
474 }
Mike Stump11289f42009-09-09 15:08:12 +0000475
Benjamin Kramerd77adb52009-12-31 15:33:09 +0000476 // Preprocess Predefines to populate the initial preprocessor state.
Mike Stump11289f42009-09-09 15:08:12 +0000477 llvm::MemoryBuffer *SB =
Chris Lattner58c79342010-04-05 22:42:27 +0000478 llvm::MemoryBuffer::getMemBufferCopy(Predefines, "<built-in>");
Douglas Gregor33551892010-08-26 14:07:34 +0000479 assert(SB && "Cannot create predefined source buffer");
Meador Ingecdc00572012-06-19 18:17:30 +0000480 FileID FID = SourceMgr.createFileIDForMemBuffer(SB);
Chris Lattnerd32480d2009-01-17 06:22:33 +0000481 assert(!FID.isInvalid() && "Could not create FileID for predefines?");
Argyrios Kyrtzidis22c22f52013-02-01 16:36:07 +0000482 setPredefinesFileID(FID);
Mike Stump11289f42009-09-09 15:08:12 +0000483
Chris Lattner1f1b0db2007-10-09 22:10:18 +0000484 // Start parsing the predefines.
Chris Lattnerfb24a3a2010-04-20 20:35:58 +0000485 EnterSourceFile(FID, 0, SourceLocation());
Chris Lattner1f1b0db2007-10-09 22:10:18 +0000486}
Chris Lattner8a7003c2007-07-16 06:48:38 +0000487
Daniel Dunbarcb9eaf52010-03-23 05:09:10 +0000488void Preprocessor::EndSourceFile() {
489 // Notify the client that we reached the end of the source file.
490 if (Callbacks)
491 Callbacks->EndOfMainFile();
492}
Chris Lattner677757a2006-06-28 05:26:32 +0000493
494//===----------------------------------------------------------------------===//
495// Lexer Event Handling.
496//===----------------------------------------------------------------------===//
497
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +0000498/// LookUpIdentifierInfo - Given a tok::raw_identifier token, look up the
499/// identifier information for the token and install it into the token,
500/// updating the token kind accordingly.
501IdentifierInfo *Preprocessor::LookUpIdentifierInfo(Token &Identifier) const {
502 assert(Identifier.getRawIdentifierData() != 0 && "No raw identifier data!");
Mike Stump11289f42009-09-09 15:08:12 +0000503
Chris Lattnercefc7682006-07-08 08:28:12 +0000504 // Look up this token, see if it is a macro, or if it is a language keyword.
505 IdentifierInfo *II;
Jordan Rose7f43ddd2013-01-24 20:50:46 +0000506 if (!Identifier.needsCleaning() && !Identifier.hasUCN()) {
Chris Lattnercefc7682006-07-08 08:28:12 +0000507 // No cleaning needed, just use the characters from the lexed buffer.
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000508 II = getIdentifierInfo(StringRef(Identifier.getRawIdentifierData(),
Jordan Rose7f43ddd2013-01-24 20:50:46 +0000509 Identifier.getLength()));
Chris Lattnercefc7682006-07-08 08:28:12 +0000510 } else {
511 // Cleaning needed, alloca a buffer, clean into it, then use the buffer.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +0000512 SmallString<64> IdentifierBuffer;
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000513 StringRef CleanedStr = getSpelling(Identifier, IdentifierBuffer);
Jordan Rose7f43ddd2013-01-24 20:50:46 +0000514
515 if (Identifier.hasUCN()) {
516 SmallString<64> UCNIdentifierBuffer;
517 expandUCNs(UCNIdentifierBuffer, CleanedStr);
518 II = getIdentifierInfo(UCNIdentifierBuffer);
519 } else {
520 II = getIdentifierInfo(CleanedStr);
521 }
Chris Lattnercefc7682006-07-08 08:28:12 +0000522 }
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +0000523
524 // Update the token info (identifier info and appropriate token kind).
Chris Lattner8c204872006-10-14 05:19:21 +0000525 Identifier.setIdentifierInfo(II);
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +0000526 Identifier.setKind(II->getTokenID());
527
Chris Lattnercefc7682006-07-08 08:28:12 +0000528 return II;
529}
530
John Wiegley1c0675e2011-04-28 01:08:34 +0000531void Preprocessor::SetPoisonReason(IdentifierInfo *II, unsigned DiagID) {
532 PoisonReasons[II] = DiagID;
533}
534
535void Preprocessor::PoisonSEHIdentifiers(bool Poison) {
536 assert(Ident__exception_code && Ident__exception_info);
537 assert(Ident___exception_code && Ident___exception_info);
538 Ident__exception_code->setIsPoisoned(Poison);
539 Ident___exception_code->setIsPoisoned(Poison);
540 Ident_GetExceptionCode->setIsPoisoned(Poison);
541 Ident__exception_info->setIsPoisoned(Poison);
542 Ident___exception_info->setIsPoisoned(Poison);
543 Ident_GetExceptionInfo->setIsPoisoned(Poison);
544 Ident__abnormal_termination->setIsPoisoned(Poison);
545 Ident___abnormal_termination->setIsPoisoned(Poison);
546 Ident_AbnormalTermination->setIsPoisoned(Poison);
547}
548
549void Preprocessor::HandlePoisonedIdentifier(Token & Identifier) {
550 assert(Identifier.getIdentifierInfo() &&
551 "Can't handle identifiers without identifier info!");
552 llvm::DenseMap<IdentifierInfo*,unsigned>::const_iterator it =
553 PoisonReasons.find(Identifier.getIdentifierInfo());
554 if(it == PoisonReasons.end())
555 Diag(Identifier, diag::err_pp_used_poisoned_id);
556 else
557 Diag(Identifier,it->second) << Identifier.getIdentifierInfo();
558}
Chris Lattnercefc7682006-07-08 08:28:12 +0000559
Chris Lattner677757a2006-06-28 05:26:32 +0000560/// HandleIdentifier - This callback is invoked when the lexer reads an
561/// identifier. This callback looks up the identifier in the map and/or
562/// potentially macro expands it or turns it into a named token (like 'for').
Chris Lattnerad89ec02009-01-21 07:43:11 +0000563///
564/// Note that callers of this method are guarded by checking the
565/// IdentifierInfo's 'isHandleIdentifierCase' bit. If this method changes, the
566/// IdentifierInfo methods that compute these properties will need to change to
567/// match.
Eli Friedman0834a4b2013-09-19 00:41:32 +0000568bool Preprocessor::HandleIdentifier(Token &Identifier) {
Chris Lattner0f1f5052006-07-20 04:16:23 +0000569 assert(Identifier.getIdentifierInfo() &&
570 "Can't handle identifiers without identifier info!");
Mike Stump11289f42009-09-09 15:08:12 +0000571
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000572 IdentifierInfo &II = *Identifier.getIdentifierInfo();
Chris Lattner677757a2006-06-28 05:26:32 +0000573
Douglas Gregor935bc7a22011-10-27 09:33:13 +0000574 // If the information about this identifier is out of date, update it from
575 // the external source.
Douglas Gregor3f568c12012-06-29 18:27:59 +0000576 // We have to treat __VA_ARGS__ in a special way, since it gets
577 // serialized with isPoisoned = true, but our preprocessor may have
578 // unpoisoned it if we're defining a C99 macro.
Douglas Gregor935bc7a22011-10-27 09:33:13 +0000579 if (II.isOutOfDate()) {
Douglas Gregor3f568c12012-06-29 18:27:59 +0000580 bool CurrentIsPoisoned = false;
581 if (&II == Ident__VA_ARGS__)
582 CurrentIsPoisoned = Ident__VA_ARGS__->isPoisoned();
583
Douglas Gregor935bc7a22011-10-27 09:33:13 +0000584 ExternalSource->updateOutOfDateIdentifier(II);
585 Identifier.setKind(II.getTokenID());
Douglas Gregor3f568c12012-06-29 18:27:59 +0000586
587 if (&II == Ident__VA_ARGS__)
588 II.setIsPoisoned(CurrentIsPoisoned);
Douglas Gregor935bc7a22011-10-27 09:33:13 +0000589 }
590
Chris Lattner677757a2006-06-28 05:26:32 +0000591 // If this identifier was poisoned, and if it was not produced from a macro
592 // expansion, emit an error.
Ted Kremeneka2c3c8d2008-11-19 22:43:49 +0000593 if (II.isPoisoned() && CurPPLexer) {
John Wiegley1c0675e2011-04-28 01:08:34 +0000594 HandlePoisonedIdentifier(Identifier);
Chris Lattner8ff71992006-07-06 05:17:39 +0000595 }
Mike Stump11289f42009-09-09 15:08:12 +0000596
Chris Lattner78186052006-07-09 00:45:31 +0000597 // If this is a macro to be expanded, do it.
Argyrios Kyrtzidisfead64b2013-02-24 00:05:14 +0000598 if (MacroDirective *MD = getMacroDirective(&II)) {
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +0000599 MacroInfo *MI = MD->getMacroInfo();
Abramo Bagnara123bec82012-01-01 22:01:04 +0000600 if (!DisableMacroExpansion) {
Richard Smith181879c2012-12-12 02:46:14 +0000601 if (!Identifier.isExpandDisabled() && MI->isEnabled()) {
Eli Friedman0834a4b2013-09-19 00:41:32 +0000602 // C99 6.10.3p10: If the preprocessing token immediately after the
603 // macro name isn't a '(', this macro should not be expanded.
604 if (!MI->isFunctionLike() || isNextPPTokenLParen())
605 return HandleMacroExpandedIdentifier(Identifier, MD);
Chris Lattner6e4bf522006-07-27 06:59:25 +0000606 } else {
607 // C99 6.10.3.4p2 says that a disabled macro may never again be
608 // expanded, even if it's in a context where it could be expanded in the
609 // future.
Chris Lattner146762e2007-07-20 16:59:19 +0000610 Identifier.setFlag(Token::DisableExpand);
Richard Smith181879c2012-12-12 02:46:14 +0000611 if (MI->isObjectLike() || isNextPPTokenLParen())
612 Diag(Identifier, diag::pp_disabled_macro_expansion);
Chris Lattner6e4bf522006-07-27 06:59:25 +0000613 }
614 }
Chris Lattner063400e2006-10-14 19:54:15 +0000615 }
Chris Lattner677757a2006-06-28 05:26:32 +0000616
Richard Smith4dd85d62011-10-11 19:57:52 +0000617 // If this identifier is a keyword in C++11, produce a warning. Don't warn if
618 // we're not considering macro expansion, since this identifier might be the
619 // name of a macro.
620 // FIXME: This warning is disabled in cases where it shouldn't be, like
621 // "#define constexpr constexpr", "int constexpr;"
Alp Toker7d2fea22014-02-24 04:35:58 +0000622 if (II.isCXX11CompatKeyword() && !DisableMacroExpansion) {
Richard Smith4dd85d62011-10-11 19:57:52 +0000623 Diag(Identifier, diag::warn_cxx11_keyword) << II.getName();
624 // Don't diagnose this keyword again in this translation unit.
625 II.setIsCXX11CompatKeyword(false);
626 }
627
Chris Lattner5b9f4892006-11-21 17:23:33 +0000628 // C++ 2.11p2: If this is an alternative representation of a C++ operator,
629 // then we act as if it is the actual operator and not the textual
630 // representation of it.
Fariborz Jahanian9e42a952010-09-03 17:33:04 +0000631 if (II.isCPlusPlusOperatorKeyword())
Chris Lattner5b9f4892006-11-21 17:23:33 +0000632 Identifier.setIdentifierInfo(0);
633
Chris Lattner677757a2006-06-28 05:26:32 +0000634 // If this is an extension token, diagnose its use.
Steve Naroffc84e8b72008-09-02 18:50:17 +0000635 // We avoid diagnosing tokens that originate from macro definitions.
Eli Friedman6bba2ad2009-04-28 03:59:15 +0000636 // FIXME: This warning is disabled in cases where it shouldn't be,
637 // like "#define TY typeof", "TY(1) x".
638 if (II.isExtensionToken() && !DisableMacroExpansion)
Chris Lattner53621a52007-06-13 20:44:40 +0000639 Diag(Identifier, diag::ext_token_used);
Douglas Gregoraf5c4842011-09-07 23:11:54 +0000640
Douglas Gregor594b8c92013-11-07 22:55:02 +0000641 // If this is the 'import' contextual keyword following an '@', note
Ted Kremenekc1e4dd02012-03-01 22:07:04 +0000642 // that the next token indicates a module name.
Douglas Gregor8d76cca2012-01-04 06:20:15 +0000643 //
Douglas Gregorc50d4922012-12-11 22:11:52 +0000644 // Note that we do not treat 'import' as a contextual
Ted Kremenekc1e4dd02012-03-01 22:07:04 +0000645 // keyword when we're in a caching lexer, because caching lexers only get
646 // used in contexts where import declarations are disallowed.
Douglas Gregor594b8c92013-11-07 22:55:02 +0000647 if (LastTokenWasAt && II.isModulesImport() && !InMacroArgs &&
648 !DisableMacroExpansion && getLangOpts().Modules &&
649 CurLexerKind != CLK_CachingLexer) {
Douglas Gregoraf5c4842011-09-07 23:11:54 +0000650 ModuleImportLoc = Identifier.getLocation();
Douglas Gregor1805b8a2011-11-30 04:26:53 +0000651 ModuleImportPath.clear();
652 ModuleImportExpectsIdentifier = true;
Douglas Gregoraf5c4842011-09-07 23:11:54 +0000653 CurLexerKind = CLK_LexAfterModuleImport;
654 }
Eli Friedman0834a4b2013-09-19 00:41:32 +0000655 return true;
Douglas Gregor08142532011-08-26 23:56:07 +0000656}
657
Eli Friedman0834a4b2013-09-19 00:41:32 +0000658void Preprocessor::Lex(Token &Result) {
659 // We loop here until a lex function retuns a token; this avoids recursion.
660 bool ReturnedToken;
661 do {
662 switch (CurLexerKind) {
663 case CLK_Lexer:
664 ReturnedToken = CurLexer->Lex(Result);
665 break;
666 case CLK_PTHLexer:
667 ReturnedToken = CurPTHLexer->Lex(Result);
668 break;
669 case CLK_TokenLexer:
670 ReturnedToken = CurTokenLexer->Lex(Result);
671 break;
672 case CLK_CachingLexer:
673 CachingLex(Result);
674 ReturnedToken = true;
675 break;
676 case CLK_LexAfterModuleImport:
677 LexAfterModuleImport(Result);
678 ReturnedToken = true;
679 break;
680 }
681 } while (!ReturnedToken);
Douglas Gregor594b8c92013-11-07 22:55:02 +0000682
683 LastTokenWasAt = Result.is(tok::at);
Eli Friedman0834a4b2013-09-19 00:41:32 +0000684}
685
686
Douglas Gregorda82e702012-01-03 19:32:59 +0000687/// \brief Lex a token following the 'import' contextual keyword.
Douglas Gregor22d09742012-01-03 18:04:46 +0000688///
Douglas Gregoraf5c4842011-09-07 23:11:54 +0000689void Preprocessor::LexAfterModuleImport(Token &Result) {
690 // Figure out what kind of lexer we actually have.
Douglas Gregor8d76cca2012-01-04 06:20:15 +0000691 recomputeCurLexerKind();
Douglas Gregoraf5c4842011-09-07 23:11:54 +0000692
693 // Lex the next token.
694 Lex(Result);
695
Douglas Gregor08142532011-08-26 23:56:07 +0000696 // The token sequence
697 //
Douglas Gregor22d09742012-01-03 18:04:46 +0000698 // import identifier (. identifier)*
699 //
Douglas Gregorda82e702012-01-03 19:32:59 +0000700 // indicates a module import directive. We already saw the 'import'
701 // contextual keyword, so now we're looking for the identifiers.
Douglas Gregor1805b8a2011-11-30 04:26:53 +0000702 if (ModuleImportExpectsIdentifier && Result.getKind() == tok::identifier) {
703 // We expected to see an identifier here, and we did; continue handling
704 // identifiers.
705 ModuleImportPath.push_back(std::make_pair(Result.getIdentifierInfo(),
706 Result.getLocation()));
707 ModuleImportExpectsIdentifier = false;
708 CurLexerKind = CLK_LexAfterModuleImport;
Douglas Gregor08142532011-08-26 23:56:07 +0000709 return;
Douglas Gregor1805b8a2011-11-30 04:26:53 +0000710 }
Douglas Gregor08142532011-08-26 23:56:07 +0000711
Douglas Gregor1805b8a2011-11-30 04:26:53 +0000712 // If we're expecting a '.' or a ';', and we got a '.', then wait until we
713 // see the next identifier.
714 if (!ModuleImportExpectsIdentifier && Result.getKind() == tok::period) {
715 ModuleImportExpectsIdentifier = true;
716 CurLexerKind = CLK_LexAfterModuleImport;
717 return;
718 }
719
720 // If we have a non-empty module path, load the named module.
Daniel Jasper07e6c402013-08-05 20:26:17 +0000721 if (!ModuleImportPath.empty() && getLangOpts().Modules) {
Argyrios Kyrtzidis19d78b72012-09-29 01:06:10 +0000722 Module *Imported = TheModuleLoader.loadModule(ModuleImportLoc,
723 ModuleImportPath,
724 Module::MacrosVisible,
725 /*IsIncludeDirective=*/false);
726 if (Callbacks)
727 Callbacks->moduleImport(ModuleImportLoc, ModuleImportPath, Imported);
728 }
Chris Lattner677757a2006-06-28 05:26:32 +0000729}
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000730
Andy Gibbs58905d22012-11-17 19:15:38 +0000731bool Preprocessor::FinishLexStringLiteral(Token &Result, std::string &String,
Andy Gibbsa8df57a2012-11-17 19:16:52 +0000732 const char *DiagnosticTag,
Andy Gibbs58905d22012-11-17 19:15:38 +0000733 bool AllowMacroExpansion) {
734 // We need at least one string literal.
735 if (Result.isNot(tok::string_literal)) {
Andy Gibbsa8df57a2012-11-17 19:16:52 +0000736 Diag(Result, diag::err_expected_string_literal)
737 << /*Source='in...'*/0 << DiagnosticTag;
Andy Gibbs58905d22012-11-17 19:15:38 +0000738 return false;
739 }
740
741 // Lex string literal tokens, optionally with macro expansion.
742 SmallVector<Token, 4> StrToks;
743 do {
744 StrToks.push_back(Result);
745
746 if (Result.hasUDSuffix())
747 Diag(Result, diag::err_invalid_string_udl);
748
749 if (AllowMacroExpansion)
750 Lex(Result);
751 else
752 LexUnexpandedToken(Result);
753 } while (Result.is(tok::string_literal));
754
755 // Concatenate and parse the strings.
756 StringLiteralParser Literal(&StrToks[0], StrToks.size(), *this);
757 assert(Literal.isAscii() && "Didn't allow wide strings in");
758
759 if (Literal.hadError)
760 return false;
761
762 if (Literal.Pascal) {
Andy Gibbsa8df57a2012-11-17 19:16:52 +0000763 Diag(StrToks[0].getLocation(), diag::err_expected_string_literal)
764 << /*Source='in...'*/0 << DiagnosticTag;
Andy Gibbs58905d22012-11-17 19:15:38 +0000765 return false;
766 }
767
768 String = Literal.GetString();
769 return true;
770}
771
Reid Klecknerc0dca6d2014-02-12 23:50:26 +0000772bool Preprocessor::parseSimpleIntegerLiteral(Token &Tok, uint64_t &Value) {
773 assert(Tok.is(tok::numeric_constant));
774 SmallString<8> IntegerBuffer;
775 bool NumberInvalid = false;
776 StringRef Spelling = getSpelling(Tok, IntegerBuffer, &NumberInvalid);
777 if (NumberInvalid)
778 return false;
779 NumericLiteralParser Literal(Spelling, Tok.getLocation(), *this);
780 if (Literal.hadError || !Literal.isIntegerLiteral() || Literal.hasUDSuffix())
781 return false;
782 llvm::APInt APVal(64, 0);
783 if (Literal.GetIntegerValue(APVal))
784 return false;
785 Lex(Tok);
786 Value = APVal.getLimitedValue();
787 return true;
788}
789
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000790void Preprocessor::addCommentHandler(CommentHandler *Handler) {
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000791 assert(Handler && "NULL comment handler");
792 assert(std::find(CommentHandlers.begin(), CommentHandlers.end(), Handler) ==
793 CommentHandlers.end() && "Comment handler already registered");
794 CommentHandlers.push_back(Handler);
795}
796
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000797void Preprocessor::removeCommentHandler(CommentHandler *Handler) {
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000798 std::vector<CommentHandler *>::iterator Pos
799 = std::find(CommentHandlers.begin(), CommentHandlers.end(), Handler);
800 assert(Pos != CommentHandlers.end() && "Comment handler not registered");
801 CommentHandlers.erase(Pos);
802}
803
Chris Lattner87d02082010-01-18 22:35:47 +0000804bool Preprocessor::HandleComment(Token &result, SourceRange Comment) {
805 bool AnyPendingTokens = false;
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000806 for (std::vector<CommentHandler *>::iterator H = CommentHandlers.begin(),
807 HEnd = CommentHandlers.end();
Chris Lattner87d02082010-01-18 22:35:47 +0000808 H != HEnd; ++H) {
809 if ((*H)->HandleComment(*this, Comment))
810 AnyPendingTokens = true;
811 }
812 if (!AnyPendingTokens || getCommentRetentionState())
813 return false;
814 Lex(result);
815 return true;
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000816}
817
Douglas Gregor08142532011-08-26 23:56:07 +0000818ModuleLoader::~ModuleLoader() { }
819
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000820CommentHandler::~CommentHandler() { }
Douglas Gregor7f6d60d2010-03-19 16:15:56 +0000821
Douglas Gregor3a7ad252010-08-24 19:08:16 +0000822CodeCompletionHandler::~CodeCompletionHandler() { }
823
Argyrios Kyrtzidisf3d587e2012-12-04 07:27:05 +0000824void Preprocessor::createPreprocessingRecord() {
Douglas Gregor7f6d60d2010-03-19 16:15:56 +0000825 if (Record)
826 return;
827
Argyrios Kyrtzidisf3d587e2012-12-04 07:27:05 +0000828 Record = new PreprocessingRecord(getSourceManager());
Douglas Gregor7dc87222010-03-19 17:12:43 +0000829 addPPCallbacks(Record);
Douglas Gregor7f6d60d2010-03-19 16:15:56 +0000830}