blob: 400cdb469d5d79ab404f714887eb154c3709c21b [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"
David Blaikie23430cc2014-08-11 21:29:24 +000030#include "clang/Basic/FileSystemStatCache.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000031#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"
Chandler Carruth5553d0d2014-01-07 11:51:46 +000038#include "clang/Lex/MacroArgs.h"
Chris Lattner22eb9722006-06-18 05:43:12 +000039#include "clang/Lex/MacroInfo.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000040#include "clang/Lex/ModuleLoader.h"
Chris Lattnerb8761832006-06-24 21:31:03 +000041#include "clang/Lex/Pragma.h"
Douglas Gregor7f6d60d2010-03-19 16:15:56 +000042#include "clang/Lex/PreprocessingRecord.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000043#include "clang/Lex/PreprocessorOptions.h"
Chris Lattner0b8cfc22006-06-28 06:49:17 +000044#include "clang/Lex/ScratchBuffer.h"
Chris Lattner5cd83512008-10-05 20:40:30 +000045#include "llvm/ADT/APFloat.h"
Jordan Rose7f43ddd2013-01-24 20:50:46 +000046#include "llvm/ADT/STLExtras.h"
Chandler Carruth5553d0d2014-01-07 11:51:46 +000047#include "llvm/ADT/SmallString.h"
Jordan Rose7f43ddd2013-01-24 20:50:46 +000048#include "llvm/ADT/StringExtras.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000049#include "llvm/Support/Capacity.h"
Dmitri Gribenko9feeef42013-01-30 12:06:08 +000050#include "llvm/Support/ConvertUTF.h"
Chris Lattner8a7003c2007-07-16 06:48:38 +000051#include "llvm/Support/MemoryBuffer.h"
Benjamin Kramer89b422c2009-08-23 12:08:50 +000052#include "llvm/Support/raw_ostream.h"
Chris Lattner22eb9722006-06-18 05:43:12 +000053using namespace clang;
54
55//===----------------------------------------------------------------------===//
Douglas Gregor9882a5a2010-01-04 19:18:44 +000056ExternalPreprocessorSource::~ExternalPreprocessorSource() { }
Chris Lattner22eb9722006-06-18 05:43:12 +000057
Dmitri Gribenkof8579502013-01-12 19:30:44 +000058Preprocessor::Preprocessor(IntrusiveRefCntPtr<PreprocessorOptions> PPOpts,
Douglas Gregor1452ff12012-10-24 17:46:57 +000059 DiagnosticsEngine &diags, LangOptions &opts,
Alp Toker96637802014-05-02 03:43:38 +000060 SourceManager &SM, HeaderSearch &Headers,
61 ModuleLoader &TheModuleLoader,
David Blaikie687cd952013-01-16 23:13:36 +000062 IdentifierInfoLookup *IILookup, bool OwnsHeaders,
Alp Toker1ae02f62014-05-02 03:43:30 +000063 TranslationUnitKind TUKind)
Craig Topper4b566922014-06-09 02:04:02 +000064 : PPOpts(PPOpts), Diags(&diags), LangOpts(opts), Target(nullptr),
Craig Topperbe250302014-09-12 05:19:24 +000065 FileMgr(Headers.getFileMgr()), SourceMgr(SM),
66 ScratchBuf(new ScratchBuffer(SourceMgr)),HeaderInfo(Headers),
Craig Topperd2d442c2014-05-17 23:10:59 +000067 TheModuleLoader(TheModuleLoader), ExternalSource(nullptr),
Craig Topperbe250302014-09-12 05:19:24 +000068 Identifiers(opts, IILookup),
69 PragmaHandlers(new PragmaNamespace(StringRef())),
70 IncrementalProcessing(false), TUKind(TUKind),
Craig Topperd2d442c2014-05-17 23:10:59 +000071 CodeComplete(nullptr), CodeCompletionFile(nullptr),
72 CodeCompletionOffset(0), LastTokenWasAt(false),
73 ModuleImportExpectsIdentifier(false), CodeCompletionReached(0),
74 SkipMainFilePreamble(0, true), CurPPLexer(nullptr),
75 CurDirLookup(nullptr), CurLexerKind(CLK_Lexer), CurSubmodule(nullptr),
76 Callbacks(nullptr), MacroArgCache(nullptr), Record(nullptr),
Richard Smithee0c4c12014-07-24 01:13:23 +000077 MIChainHead(nullptr), DeserialMIChainHead(nullptr) {
Daniel Dunbar0c6c9302009-11-11 21:44:21 +000078 OwnsHeaderSearch = OwnsHeaders;
Douglas Gregor83297df2011-09-01 23:39:15 +000079
Douglas Gregor83297df2011-09-01 23:39:15 +000080 CounterValue = 0; // __COUNTER__ starts at 0.
81
82 // Clear stats.
83 NumDirectives = NumDefined = NumUndefined = NumPragma = 0;
84 NumIf = NumElse = NumEndif = 0;
85 NumEnteredSourceFiles = 0;
86 NumMacroExpanded = NumFnMacroExpanded = NumBuiltinMacroExpanded = 0;
87 NumFastMacroExpanded = NumTokenPaste = NumFastTokenPaste = 0;
88 MaxIncludeStackDepth = 0;
89 NumSkipped = 0;
90
91 // Default to discarding comments.
92 KeepComments = false;
93 KeepMacroComments = false;
94 SuppressIncludeNotFoundError = false;
95
96 // Macro expansion is enabled.
97 DisableMacroExpansion = false;
David Blaikied5321242012-06-06 18:52:13 +000098 MacroExpansionInDirectivesOverride = false;
Douglas Gregor83297df2011-09-01 23:39:15 +000099 InMacroArgs = false;
Argyrios Kyrtzidisf1b64c62012-04-03 16:47:40 +0000100 InMacroArgPreExpansion = false;
Douglas Gregor83297df2011-09-01 23:39:15 +0000101 NumCachedTokenLexers = 0;
Jordan Rosede1a2922012-06-08 18:06:21 +0000102 PragmasEnabled = true;
Eric Christopher5e4696d2013-01-16 20:09:36 +0000103 ParsingIfOrElifDirective = false;
Jordan Rose324ec422013-01-31 19:26:01 +0000104 PreprocessedOutput = false;
Jordan Rosede1a2922012-06-08 18:06:21 +0000105
Douglas Gregor83297df2011-09-01 23:39:15 +0000106 CachedLexPos = 0;
Eric Christopher5e4696d2013-01-16 20:09:36 +0000107
Douglas Gregor83297df2011-09-01 23:39:15 +0000108 // We haven't read anything from the external source.
109 ReadMacrosFromExternalSource = false;
110
Douglas Gregor83297df2011-09-01 23:39:15 +0000111 // "Poison" __VA_ARGS__, which can only appear in the expansion of a macro.
112 // This gets unpoisoned where it is allowed.
113 (Ident__VA_ARGS__ = getIdentifierInfo("__VA_ARGS__"))->setIsPoisoned();
114 SetPoisonReason(Ident__VA_ARGS__,diag::ext_pp_bad_vaargs_use);
115
116 // Initialize the pragma handlers.
Douglas Gregor83297df2011-09-01 23:39:15 +0000117 RegisterBuiltinPragmas();
118
119 // Initialize builtin macros like __LINE__ and friends.
120 RegisterBuiltinMacros();
121
David Blaikiebbafb8a2012-03-11 07:00:24 +0000122 if(LangOpts.Borland) {
Douglas Gregor83297df2011-09-01 23:39:15 +0000123 Ident__exception_info = getIdentifierInfo("_exception_info");
124 Ident___exception_info = getIdentifierInfo("__exception_info");
125 Ident_GetExceptionInfo = getIdentifierInfo("GetExceptionInformation");
126 Ident__exception_code = getIdentifierInfo("_exception_code");
127 Ident___exception_code = getIdentifierInfo("__exception_code");
128 Ident_GetExceptionCode = getIdentifierInfo("GetExceptionCode");
129 Ident__abnormal_termination = getIdentifierInfo("_abnormal_termination");
130 Ident___abnormal_termination = getIdentifierInfo("__abnormal_termination");
131 Ident_AbnormalTermination = getIdentifierInfo("AbnormalTermination");
132 } else {
Craig Topperd2d442c2014-05-17 23:10:59 +0000133 Ident__exception_info = Ident__exception_code = nullptr;
134 Ident__abnormal_termination = Ident___exception_info = nullptr;
135 Ident___exception_code = Ident___abnormal_termination = nullptr;
136 Ident_GetExceptionInfo = Ident_GetExceptionCode = nullptr;
137 Ident_AbnormalTermination = nullptr;
Douglas Gregor89929282012-01-30 06:01:29 +0000138 }
Argyrios Kyrtzidis3c9aaf12012-06-02 18:08:09 +0000139}
140
141Preprocessor::~Preprocessor() {
142 assert(BacktrackPositions.empty() && "EnableBacktrack/Backtrack imbalance!");
143
Benjamin Kramer329c5962014-03-15 16:40:40 +0000144 IncludeMacroStack.clear();
Argyrios Kyrtzidis3c9aaf12012-06-02 18:08:09 +0000145
Richard Smith73a29662014-07-24 03:25:00 +0000146 // Destroy any macro definitions.
147 while (MacroInfoChain *I = MIChainHead) {
148 MIChainHead = I->Next;
149 I->~MacroInfoChain();
150 }
Argyrios Kyrtzidis3c9aaf12012-06-02 18:08:09 +0000151
152 // Free any cached macro expanders.
Nico Weber5f5b9412014-05-09 18:09:42 +0000153 // This populates MacroArgCache, so all TokenLexers need to be destroyed
154 // before the code below that frees up the MacroArgCache list.
David Blaikie6d5038c2014-08-29 19:36:52 +0000155 std::fill(TokenLexerCache, TokenLexerCache + NumCachedTokenLexers, nullptr);
Nico Weber5f5b9412014-05-09 18:09:42 +0000156 CurTokenLexer.reset();
Argyrios Kyrtzidis3c9aaf12012-06-02 18:08:09 +0000157
Richard Smith73a29662014-07-24 03:25:00 +0000158 while (DeserializedMacroInfoChain *I = DeserialMIChainHead) {
159 DeserialMIChainHead = I->Next;
160 I->~DeserializedMacroInfoChain();
161 }
Argyrios Kyrtzidisd48b91d2013-04-30 05:05:35 +0000162
Argyrios Kyrtzidis3c9aaf12012-06-02 18:08:09 +0000163 // Free any cached MacroArgs.
Nico Weber5f5b9412014-05-09 18:09:42 +0000164 for (MacroArgs *ArgList = MacroArgCache; ArgList;)
Argyrios Kyrtzidis3c9aaf12012-06-02 18:08:09 +0000165 ArgList = ArgList->deallocate();
166
Argyrios Kyrtzidis3c9aaf12012-06-02 18:08:09 +0000167 // Delete the header search info, if we own it.
168 if (OwnsHeaderSearch)
169 delete &HeaderInfo;
Argyrios Kyrtzidis3c9aaf12012-06-02 18:08:09 +0000170}
171
172void Preprocessor::Initialize(const TargetInfo &Target) {
173 assert((!this->Target || this->Target == &Target) &&
174 "Invalid override of target information");
175 this->Target = &Target;
Douglas Gregor89929282012-01-30 06:01:29 +0000176
Argyrios Kyrtzidis3c9aaf12012-06-02 18:08:09 +0000177 // Initialize information about built-ins.
178 BuiltinInfo.InitializeTarget(Target);
Douglas Gregor89929282012-01-30 06:01:29 +0000179 HeaderInfo.setTarget(Target);
Douglas Gregor83297df2011-09-01 23:39:15 +0000180}
181
Ted Kremenekeeccb302014-08-27 15:14:15 +0000182void Preprocessor::InitializeForModelFile() {
183 NumEnteredSourceFiles = 0;
184
185 // Reset pragmas
David Blaikie9f0af9d2014-09-15 21:31:42 +0000186 PragmaHandlersBackup = std::move(PragmaHandlers);
Craig Topperbe250302014-09-12 05:19:24 +0000187 PragmaHandlers = llvm::make_unique<PragmaNamespace>(StringRef());
Ted Kremenekeeccb302014-08-27 15:14:15 +0000188 RegisterBuiltinPragmas();
189
190 // Reset PredefinesFileID
191 PredefinesFileID = FileID();
192}
193
194void Preprocessor::FinalizeForModelFile() {
195 NumEnteredSourceFiles = 1;
196
David Blaikie9f0af9d2014-09-15 21:31:42 +0000197 PragmaHandlers = std::move(PragmaHandlersBackup);
Ted Kremenekeeccb302014-08-27 15:14:15 +0000198}
199
Ted Kremeneka5c2c272009-02-12 03:26:59 +0000200void Preprocessor::setPTHManager(PTHManager* pm) {
201 PTH.reset(pm);
Douglas Gregord2eb58a2009-10-16 18:18:30 +0000202 FileMgr.addStatCache(PTH->createStatCache());
Ted Kremeneka5c2c272009-02-12 03:26:59 +0000203}
204
Chris Lattner146762e2007-07-20 16:59:19 +0000205void Preprocessor::DumpToken(const Token &Tok, bool DumpFlags) const {
Benjamin Kramer89b422c2009-08-23 12:08:50 +0000206 llvm::errs() << tok::getTokenName(Tok.getKind()) << " '"
207 << getSpelling(Tok) << "'";
Mike Stump11289f42009-09-09 15:08:12 +0000208
Chris Lattnerd01e2912006-06-18 16:22:51 +0000209 if (!DumpFlags) return;
Mike Stump11289f42009-09-09 15:08:12 +0000210
Benjamin Kramer89b422c2009-08-23 12:08:50 +0000211 llvm::errs() << "\t";
Chris Lattnerd01e2912006-06-18 16:22:51 +0000212 if (Tok.isAtStartOfLine())
Benjamin Kramer89b422c2009-08-23 12:08:50 +0000213 llvm::errs() << " [StartOfLine]";
Chris Lattnerd01e2912006-06-18 16:22:51 +0000214 if (Tok.hasLeadingSpace())
Benjamin Kramer89b422c2009-08-23 12:08:50 +0000215 llvm::errs() << " [LeadingSpace]";
Chris Lattner6e4bf522006-07-27 06:59:25 +0000216 if (Tok.isExpandDisabled())
Benjamin Kramer89b422c2009-08-23 12:08:50 +0000217 llvm::errs() << " [ExpandDisabled]";
Chris Lattnerd01e2912006-06-18 16:22:51 +0000218 if (Tok.needsCleaning()) {
Chris Lattner50b497e2006-06-18 16:32:35 +0000219 const char *Start = SourceMgr.getCharacterData(Tok.getLocation());
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000220 llvm::errs() << " [UnClean='" << StringRef(Start, Tok.getLength())
Benjamin Kramer89b422c2009-08-23 12:08:50 +0000221 << "']";
Chris Lattnerd01e2912006-06-18 16:22:51 +0000222 }
Mike Stump11289f42009-09-09 15:08:12 +0000223
Benjamin Kramer89b422c2009-08-23 12:08:50 +0000224 llvm::errs() << "\tLoc=<";
Chris Lattner615315f2007-12-09 20:31:55 +0000225 DumpLocation(Tok.getLocation());
Benjamin Kramer89b422c2009-08-23 12:08:50 +0000226 llvm::errs() << ">";
Chris Lattner615315f2007-12-09 20:31:55 +0000227}
228
229void Preprocessor::DumpLocation(SourceLocation Loc) const {
Chris Lattnerf1ca7d32009-01-27 07:57:44 +0000230 Loc.dump(SourceMgr);
Chris Lattnerd01e2912006-06-18 16:22:51 +0000231}
232
233void Preprocessor::DumpMacro(const MacroInfo &MI) const {
Benjamin Kramer89b422c2009-08-23 12:08:50 +0000234 llvm::errs() << "MACRO: ";
Chris Lattnerd01e2912006-06-18 16:22:51 +0000235 for (unsigned i = 0, e = MI.getNumTokens(); i != e; ++i) {
236 DumpToken(MI.getReplacementToken(i));
Benjamin Kramer89b422c2009-08-23 12:08:50 +0000237 llvm::errs() << " ";
Chris Lattnerd01e2912006-06-18 16:22:51 +0000238 }
Benjamin Kramer89b422c2009-08-23 12:08:50 +0000239 llvm::errs() << "\n";
Chris Lattnerd01e2912006-06-18 16:22:51 +0000240}
241
Chris Lattner22eb9722006-06-18 05:43:12 +0000242void Preprocessor::PrintStats() {
Benjamin Kramer89b422c2009-08-23 12:08:50 +0000243 llvm::errs() << "\n*** Preprocessor Stats:\n";
244 llvm::errs() << NumDirectives << " directives found:\n";
245 llvm::errs() << " " << NumDefined << " #define.\n";
246 llvm::errs() << " " << NumUndefined << " #undef.\n";
247 llvm::errs() << " #include/#include_next/#import:\n";
248 llvm::errs() << " " << NumEnteredSourceFiles << " source files entered.\n";
249 llvm::errs() << " " << MaxIncludeStackDepth << " max include stack depth\n";
250 llvm::errs() << " " << NumIf << " #if/#ifndef/#ifdef.\n";
251 llvm::errs() << " " << NumElse << " #else/#elif.\n";
252 llvm::errs() << " " << NumEndif << " #endif.\n";
253 llvm::errs() << " " << NumPragma << " #pragma.\n";
254 llvm::errs() << NumSkipped << " #if/#ifndef#ifdef regions skipped\n";
Chris Lattner22eb9722006-06-18 05:43:12 +0000255
Benjamin Kramer89b422c2009-08-23 12:08:50 +0000256 llvm::errs() << NumMacroExpanded << "/" << NumFnMacroExpanded << "/"
Ted Kremeneka0a3e9b2008-01-14 16:44:48 +0000257 << NumBuiltinMacroExpanded << " obj/fn/builtin macros expanded, "
258 << NumFastMacroExpanded << " on the fast path.\n";
Benjamin Kramer89b422c2009-08-23 12:08:50 +0000259 llvm::errs() << (NumFastTokenPaste+NumTokenPaste)
Ted Kremeneka0a3e9b2008-01-14 16:44:48 +0000260 << " token paste (##) operations performed, "
261 << NumFastTokenPaste << " on the fast path.\n";
Alexander Kornienko199cd942012-08-13 10:46:42 +0000262
263 llvm::errs() << "\nPreprocessor Memory: " << getTotalMemory() << "B total";
264
265 llvm::errs() << "\n BumpPtr: " << BP.getTotalMemory();
266 llvm::errs() << "\n Macro Expanded Tokens: "
267 << llvm::capacity_in_bytes(MacroExpandedTokens);
268 llvm::errs() << "\n Predefines Buffer: " << Predefines.capacity();
269 llvm::errs() << "\n Macros: " << llvm::capacity_in_bytes(Macros);
270 llvm::errs() << "\n #pragma push_macro Info: "
271 << llvm::capacity_in_bytes(PragmaPushMacroInfo);
272 llvm::errs() << "\n Poison Reasons: "
273 << llvm::capacity_in_bytes(PoisonReasons);
274 llvm::errs() << "\n Comment Handlers: "
275 << llvm::capacity_in_bytes(CommentHandlers) << "\n";
Chris Lattner22eb9722006-06-18 05:43:12 +0000276}
277
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +0000278Preprocessor::macro_iterator
279Preprocessor::macro_begin(bool IncludeExternalMacros) const {
280 if (IncludeExternalMacros && ExternalSource &&
Douglas Gregor9882a5a2010-01-04 19:18:44 +0000281 !ReadMacrosFromExternalSource) {
282 ReadMacrosFromExternalSource = true;
283 ExternalSource->ReadDefinedMacros();
284 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +0000285
286 return Macros.begin();
Douglas Gregor9882a5a2010-01-04 19:18:44 +0000287}
288
Argyrios Kyrtzidise379ee32011-06-29 22:20:04 +0000289size_t Preprocessor::getTotalMemory() const {
Ted Kremenek182543a2011-07-26 21:17:24 +0000290 return BP.getTotalMemory()
Ted Kremenek8b77fe72011-07-27 18:41:23 +0000291 + llvm::capacity_in_bytes(MacroExpandedTokens)
Ted Kremenek182543a2011-07-26 21:17:24 +0000292 + Predefines.capacity() /* Predefines buffer. */
Ted Kremenek8b77fe72011-07-27 18:41:23 +0000293 + llvm::capacity_in_bytes(Macros)
294 + llvm::capacity_in_bytes(PragmaPushMacroInfo)
295 + llvm::capacity_in_bytes(PoisonReasons)
296 + llvm::capacity_in_bytes(CommentHandlers);
Argyrios Kyrtzidise379ee32011-06-29 22:20:04 +0000297}
298
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +0000299Preprocessor::macro_iterator
300Preprocessor::macro_end(bool IncludeExternalMacros) const {
301 if (IncludeExternalMacros && ExternalSource &&
Douglas Gregor9882a5a2010-01-04 19:18:44 +0000302 !ReadMacrosFromExternalSource) {
303 ReadMacrosFromExternalSource = true;
304 ExternalSource->ReadDefinedMacros();
305 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +0000306
307 return Macros.end();
Douglas Gregor9882a5a2010-01-04 19:18:44 +0000308}
309
Dmitri Gribenko6743e042012-09-29 11:40:46 +0000310/// \brief Compares macro tokens with a specified token value sequence.
311static bool MacroDefinitionEquals(const MacroInfo *MI,
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000312 ArrayRef<TokenValue> Tokens) {
Dmitri Gribenko6743e042012-09-29 11:40:46 +0000313 return Tokens.size() == MI->getNumTokens() &&
314 std::equal(Tokens.begin(), Tokens.end(), MI->tokens_begin());
315}
316
317StringRef Preprocessor::getLastMacroWithSpelling(
318 SourceLocation Loc,
319 ArrayRef<TokenValue> Tokens) const {
320 SourceLocation BestLocation;
321 StringRef BestSpelling;
322 for (Preprocessor::macro_iterator I = macro_begin(), E = macro_end();
323 I != E; ++I) {
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +0000324 if (!I->second->getMacroInfo()->isObjectLike())
Dmitri Gribenko6743e042012-09-29 11:40:46 +0000325 continue;
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +0000326 const MacroDirective::DefInfo
327 Def = I->second->findDirectiveAtLoc(Loc, SourceMgr);
328 if (!Def)
Dmitri Gribenko6743e042012-09-29 11:40:46 +0000329 continue;
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +0000330 if (!MacroDefinitionEquals(Def.getMacroInfo(), Tokens))
Dmitri Gribenko6743e042012-09-29 11:40:46 +0000331 continue;
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +0000332 SourceLocation Location = Def.getLocation();
Dmitri Gribenko6743e042012-09-29 11:40:46 +0000333 // Choose the macro defined latest.
334 if (BestLocation.isInvalid() ||
335 (Location.isValid() &&
336 SourceMgr.isBeforeInTranslationUnit(BestLocation, Location))) {
337 BestLocation = Location;
338 BestSpelling = I->first->getName();
339 }
340 }
341 return BestSpelling;
342}
343
Douglas Gregor8d76cca2012-01-04 06:20:15 +0000344void Preprocessor::recomputeCurLexerKind() {
345 if (CurLexer)
346 CurLexerKind = CLK_Lexer;
347 else if (CurPTHLexer)
348 CurLexerKind = CLK_PTHLexer;
349 else if (CurTokenLexer)
350 CurLexerKind = CLK_TokenLexer;
351 else
352 CurLexerKind = CLK_CachingLexer;
353}
354
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +0000355bool Preprocessor::SetCodeCompletionPoint(const FileEntry *File,
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +0000356 unsigned CompleteLine,
357 unsigned CompleteColumn) {
358 assert(File);
359 assert(CompleteLine && CompleteColumn && "Starts from 1:1");
360 assert(!CodeCompletionFile && "Already set");
361
Douglas Gregor53ad6b92009-12-02 06:49:09 +0000362 using llvm::MemoryBuffer;
363
Douglas Gregor53ad6b92009-12-02 06:49:09 +0000364 // Load the actual file's contents.
Douglas Gregor26266da2010-03-16 19:49:24 +0000365 bool Invalid = false;
366 const MemoryBuffer *Buffer = SourceMgr.getMemoryBufferForFile(File, &Invalid);
367 if (Invalid)
Douglas Gregor53ad6b92009-12-02 06:49:09 +0000368 return true;
369
370 // Find the byte position of the truncation point.
371 const char *Position = Buffer->getBufferStart();
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +0000372 for (unsigned Line = 1; Line < CompleteLine; ++Line) {
Douglas Gregor53ad6b92009-12-02 06:49:09 +0000373 for (; *Position; ++Position) {
374 if (*Position != '\r' && *Position != '\n')
375 continue;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +0000376
Douglas Gregor53ad6b92009-12-02 06:49:09 +0000377 // Eat \r\n or \n\r as a single line.
378 if ((Position[1] == '\r' || Position[1] == '\n') &&
379 Position[0] != Position[1])
380 ++Position;
381 ++Position;
382 break;
383 }
384 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +0000385
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +0000386 Position += CompleteColumn - 1;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +0000387
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +0000388 // Insert '\0' at the code-completion point.
Douglas Gregor9291ab62009-12-08 21:45:46 +0000389 if (Position < Buffer->getBufferEnd()) {
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +0000390 CodeCompletionFile = File;
391 CodeCompletionOffset = Position - Buffer->getBufferStart();
392
Rafael Espindolad87f8d72014-08-27 20:03:29 +0000393 std::unique_ptr<MemoryBuffer> NewBuffer =
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +0000394 MemoryBuffer::getNewUninitMemBuffer(Buffer->getBufferSize() + 1,
395 Buffer->getBufferIdentifier());
Benjamin Kramer60053cf2011-09-04 20:26:28 +0000396 char *NewBuf = const_cast<char*>(NewBuffer->getBufferStart());
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +0000397 char *NewPos = std::copy(Buffer->getBufferStart(), Position, NewBuf);
398 *NewPos = '\0';
399 std::copy(Position, Buffer->getBufferEnd(), NewPos+1);
David Blaikie49cc3182014-08-27 20:54:45 +0000400 SourceMgr.overrideFileContents(File, std::move(NewBuffer));
Douglas Gregor53ad6b92009-12-02 06:49:09 +0000401 }
402
403 return false;
404}
405
Douglas Gregor11583702010-08-25 17:04:25 +0000406void Preprocessor::CodeCompleteNaturalLanguage() {
Douglas Gregor11583702010-08-25 17:04:25 +0000407 if (CodeComplete)
408 CodeComplete->CodeCompleteNaturalLanguage();
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +0000409 setCodeCompletionReached();
Douglas Gregor11583702010-08-25 17:04:25 +0000410}
411
Benjamin Kramera197fb62010-02-27 17:05:45 +0000412/// getSpelling - This method is used to get the spelling of a token into a
413/// SmallVector. Note that the returned StringRef may not point to the
414/// supplied buffer if a copy can be avoided.
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000415StringRef Preprocessor::getSpelling(const Token &Tok,
416 SmallVectorImpl<char> &Buffer,
Douglas Gregor7bda4b82010-03-16 05:20:39 +0000417 bool *Invalid) const {
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +0000418 // NOTE: this has to be checked *before* testing for an IdentifierInfo.
Jordan Rose7f43ddd2013-01-24 20:50:46 +0000419 if (Tok.isNot(tok::raw_identifier) && !Tok.hasUCN()) {
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +0000420 // Try the fast path.
421 if (const IdentifierInfo *II = Tok.getIdentifierInfo())
422 return II->getName();
423 }
Benjamin Kramera197fb62010-02-27 17:05:45 +0000424
425 // Resize the buffer if we need to copy into it.
426 if (Tok.needsCleaning())
427 Buffer.resize(Tok.getLength());
428
429 const char *Ptr = Buffer.data();
Douglas Gregor7bda4b82010-03-16 05:20:39 +0000430 unsigned Len = getSpelling(Tok, Ptr, Invalid);
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000431 return StringRef(Ptr, Len);
Benjamin Kramera197fb62010-02-27 17:05:45 +0000432}
433
Chris Lattnerb94ec7b2006-07-14 06:54:10 +0000434/// CreateString - Plop the specified string into a scratch buffer and return a
435/// location for it. If specified, the source location provides a source
436/// location for the token.
Dmitri Gribenkob8e9e752012-09-24 21:07:17 +0000437void Preprocessor::CreateString(StringRef Str, Token &Tok,
Abramo Bagnarae398e602011-10-03 18:39:03 +0000438 SourceLocation ExpansionLocStart,
439 SourceLocation ExpansionLocEnd) {
Dmitri Gribenkob8e9e752012-09-24 21:07:17 +0000440 Tok.setLength(Str.size());
Mike Stump11289f42009-09-09 15:08:12 +0000441
Chris Lattner5a7971e2009-01-26 19:29:26 +0000442 const char *DestPtr;
Dmitri Gribenkob8e9e752012-09-24 21:07:17 +0000443 SourceLocation Loc = ScratchBuf->getToken(Str.data(), Str.size(), DestPtr);
Mike Stump11289f42009-09-09 15:08:12 +0000444
Abramo Bagnarae398e602011-10-03 18:39:03 +0000445 if (ExpansionLocStart.isValid())
446 Loc = SourceMgr.createExpansionLoc(Loc, ExpansionLocStart,
Dmitri Gribenkob8e9e752012-09-24 21:07:17 +0000447 ExpansionLocEnd, Str.size());
Chris Lattner5a7971e2009-01-26 19:29:26 +0000448 Tok.setLocation(Loc);
Mike Stump11289f42009-09-09 15:08:12 +0000449
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +0000450 // If this is a raw identifier or a literal token, set the pointer data.
451 if (Tok.is(tok::raw_identifier))
452 Tok.setRawIdentifierData(DestPtr);
453 else if (Tok.isLiteral())
Chris Lattner5a7971e2009-01-26 19:29:26 +0000454 Tok.setLiteralData(DestPtr);
Chris Lattnerb94ec7b2006-07-14 06:54:10 +0000455}
456
Douglas Gregor2b82c2a2011-12-02 01:47:07 +0000457Module *Preprocessor::getCurrentModule() {
David Blaikiebbafb8a2012-03-11 07:00:24 +0000458 if (getLangOpts().CurrentModule.empty())
Craig Topperd2d442c2014-05-17 23:10:59 +0000459 return nullptr;
460
David Blaikiebbafb8a2012-03-11 07:00:24 +0000461 return getHeaderSearchInfo().lookupModule(getLangOpts().CurrentModule);
Douglas Gregor2b82c2a2011-12-02 01:47:07 +0000462}
Chris Lattner8a7003c2007-07-16 06:48:38 +0000463
Chris Lattner1f1b0db2007-10-09 22:10:18 +0000464//===----------------------------------------------------------------------===//
465// Preprocessor Initialization Methods
466//===----------------------------------------------------------------------===//
467
Chris Lattner1f1b0db2007-10-09 22:10:18 +0000468
469/// EnterMainSourceFile - Enter the specified FileID as the main source file,
Nate Begemanf7c3ff62008-01-07 04:01:26 +0000470/// which implicitly adds the builtin defines etc.
Chris Lattnerfb24a3a2010-04-20 20:35:58 +0000471void Preprocessor::EnterMainSourceFile() {
Chris Lattner9ef847b2009-02-13 19:33:24 +0000472 // We do not allow the preprocessor to reenter the main file. Doing so will
473 // cause FileID's to accumulate information from both runs (e.g. #line
474 // information) and predefined macros aren't guaranteed to be set properly.
475 assert(NumEnteredSourceFiles == 0 && "Cannot reenter the main file!");
Chris Lattnerd32480d2009-01-17 06:22:33 +0000476 FileID MainFileID = SourceMgr.getMainFileID();
Mike Stump11289f42009-09-09 15:08:12 +0000477
Argyrios Kyrtzidis9afd4492012-01-05 21:36:25 +0000478 // If MainFileID is loaded it means we loaded an AST file, no need to enter
479 // a main file.
480 if (!SourceMgr.isLoadedFileID(MainFileID)) {
481 // Enter the main file source buffer.
Craig Topperd2d442c2014-05-17 23:10:59 +0000482 EnterSourceFile(MainFileID, nullptr, SourceLocation());
483
Argyrios Kyrtzidis9afd4492012-01-05 21:36:25 +0000484 // If we've been asked to skip bytes in the main file (e.g., as part of a
485 // precompiled preamble), do so now.
486 if (SkipMainFilePreamble.first > 0)
487 CurLexer->SkipBytes(SkipMainFilePreamble.first,
488 SkipMainFilePreamble.second);
489
490 // Tell the header info that the main file was entered. If the file is later
491 // #imported, it won't be re-entered.
492 if (const FileEntry *FE = SourceMgr.getFileEntryForID(MainFileID))
493 HeaderInfo.IncrementIncludeCount(FE);
494 }
Mike Stump11289f42009-09-09 15:08:12 +0000495
Benjamin Kramerd77adb52009-12-31 15:33:09 +0000496 // Preprocess Predefines to populate the initial preprocessor state.
Rafael Espindolad87f8d72014-08-27 20:03:29 +0000497 std::unique_ptr<llvm::MemoryBuffer> SB =
Chris Lattner58c79342010-04-05 22:42:27 +0000498 llvm::MemoryBuffer::getMemBufferCopy(Predefines, "<built-in>");
Douglas Gregor33551892010-08-26 14:07:34 +0000499 assert(SB && "Cannot create predefined source buffer");
David Blaikie50a5f972014-08-29 07:59:55 +0000500 FileID FID = SourceMgr.createFileID(std::move(SB));
Chris Lattnerd32480d2009-01-17 06:22:33 +0000501 assert(!FID.isInvalid() && "Could not create FileID for predefines?");
Argyrios Kyrtzidis22c22f52013-02-01 16:36:07 +0000502 setPredefinesFileID(FID);
Mike Stump11289f42009-09-09 15:08:12 +0000503
Chris Lattner1f1b0db2007-10-09 22:10:18 +0000504 // Start parsing the predefines.
Craig Topperd2d442c2014-05-17 23:10:59 +0000505 EnterSourceFile(FID, nullptr, SourceLocation());
Chris Lattner1f1b0db2007-10-09 22:10:18 +0000506}
Chris Lattner8a7003c2007-07-16 06:48:38 +0000507
Daniel Dunbarcb9eaf52010-03-23 05:09:10 +0000508void Preprocessor::EndSourceFile() {
509 // Notify the client that we reached the end of the source file.
510 if (Callbacks)
511 Callbacks->EndOfMainFile();
512}
Chris Lattner677757a2006-06-28 05:26:32 +0000513
514//===----------------------------------------------------------------------===//
515// Lexer Event Handling.
516//===----------------------------------------------------------------------===//
517
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +0000518/// LookUpIdentifierInfo - Given a tok::raw_identifier token, look up the
519/// identifier information for the token and install it into the token,
520/// updating the token kind accordingly.
521IdentifierInfo *Preprocessor::LookUpIdentifierInfo(Token &Identifier) const {
Alp Toker2d57cea2014-05-17 04:53:25 +0000522 assert(!Identifier.getRawIdentifier().empty() && "No raw identifier data!");
Mike Stump11289f42009-09-09 15:08:12 +0000523
Chris Lattnercefc7682006-07-08 08:28:12 +0000524 // Look up this token, see if it is a macro, or if it is a language keyword.
525 IdentifierInfo *II;
Jordan Rose7f43ddd2013-01-24 20:50:46 +0000526 if (!Identifier.needsCleaning() && !Identifier.hasUCN()) {
Chris Lattnercefc7682006-07-08 08:28:12 +0000527 // No cleaning needed, just use the characters from the lexed buffer.
Alp Toker2d57cea2014-05-17 04:53:25 +0000528 II = getIdentifierInfo(Identifier.getRawIdentifier());
Chris Lattnercefc7682006-07-08 08:28:12 +0000529 } else {
530 // Cleaning needed, alloca a buffer, clean into it, then use the buffer.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +0000531 SmallString<64> IdentifierBuffer;
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000532 StringRef CleanedStr = getSpelling(Identifier, IdentifierBuffer);
Jordan Rose7f43ddd2013-01-24 20:50:46 +0000533
534 if (Identifier.hasUCN()) {
535 SmallString<64> UCNIdentifierBuffer;
536 expandUCNs(UCNIdentifierBuffer, CleanedStr);
537 II = getIdentifierInfo(UCNIdentifierBuffer);
538 } else {
539 II = getIdentifierInfo(CleanedStr);
540 }
Chris Lattnercefc7682006-07-08 08:28:12 +0000541 }
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +0000542
543 // Update the token info (identifier info and appropriate token kind).
Chris Lattner8c204872006-10-14 05:19:21 +0000544 Identifier.setIdentifierInfo(II);
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +0000545 Identifier.setKind(II->getTokenID());
546
Chris Lattnercefc7682006-07-08 08:28:12 +0000547 return II;
548}
549
John Wiegley1c0675e2011-04-28 01:08:34 +0000550void Preprocessor::SetPoisonReason(IdentifierInfo *II, unsigned DiagID) {
551 PoisonReasons[II] = DiagID;
552}
553
554void Preprocessor::PoisonSEHIdentifiers(bool Poison) {
555 assert(Ident__exception_code && Ident__exception_info);
556 assert(Ident___exception_code && Ident___exception_info);
557 Ident__exception_code->setIsPoisoned(Poison);
558 Ident___exception_code->setIsPoisoned(Poison);
559 Ident_GetExceptionCode->setIsPoisoned(Poison);
560 Ident__exception_info->setIsPoisoned(Poison);
561 Ident___exception_info->setIsPoisoned(Poison);
562 Ident_GetExceptionInfo->setIsPoisoned(Poison);
563 Ident__abnormal_termination->setIsPoisoned(Poison);
564 Ident___abnormal_termination->setIsPoisoned(Poison);
565 Ident_AbnormalTermination->setIsPoisoned(Poison);
566}
567
568void Preprocessor::HandlePoisonedIdentifier(Token & Identifier) {
569 assert(Identifier.getIdentifierInfo() &&
570 "Can't handle identifiers without identifier info!");
571 llvm::DenseMap<IdentifierInfo*,unsigned>::const_iterator it =
572 PoisonReasons.find(Identifier.getIdentifierInfo());
573 if(it == PoisonReasons.end())
574 Diag(Identifier, diag::err_pp_used_poisoned_id);
575 else
576 Diag(Identifier,it->second) << Identifier.getIdentifierInfo();
577}
Chris Lattnercefc7682006-07-08 08:28:12 +0000578
Chris Lattner677757a2006-06-28 05:26:32 +0000579/// HandleIdentifier - This callback is invoked when the lexer reads an
580/// identifier. This callback looks up the identifier in the map and/or
581/// potentially macro expands it or turns it into a named token (like 'for').
Chris Lattnerad89ec02009-01-21 07:43:11 +0000582///
583/// Note that callers of this method are guarded by checking the
584/// IdentifierInfo's 'isHandleIdentifierCase' bit. If this method changes, the
585/// IdentifierInfo methods that compute these properties will need to change to
586/// match.
Eli Friedman0834a4b2013-09-19 00:41:32 +0000587bool Preprocessor::HandleIdentifier(Token &Identifier) {
Chris Lattner0f1f5052006-07-20 04:16:23 +0000588 assert(Identifier.getIdentifierInfo() &&
589 "Can't handle identifiers without identifier info!");
Mike Stump11289f42009-09-09 15:08:12 +0000590
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000591 IdentifierInfo &II = *Identifier.getIdentifierInfo();
Chris Lattner677757a2006-06-28 05:26:32 +0000592
Douglas Gregor935bc7a22011-10-27 09:33:13 +0000593 // If the information about this identifier is out of date, update it from
594 // the external source.
Douglas Gregor3f568c12012-06-29 18:27:59 +0000595 // We have to treat __VA_ARGS__ in a special way, since it gets
596 // serialized with isPoisoned = true, but our preprocessor may have
597 // unpoisoned it if we're defining a C99 macro.
Douglas Gregor935bc7a22011-10-27 09:33:13 +0000598 if (II.isOutOfDate()) {
Douglas Gregor3f568c12012-06-29 18:27:59 +0000599 bool CurrentIsPoisoned = false;
600 if (&II == Ident__VA_ARGS__)
601 CurrentIsPoisoned = Ident__VA_ARGS__->isPoisoned();
602
Douglas Gregor935bc7a22011-10-27 09:33:13 +0000603 ExternalSource->updateOutOfDateIdentifier(II);
604 Identifier.setKind(II.getTokenID());
Douglas Gregor3f568c12012-06-29 18:27:59 +0000605
606 if (&II == Ident__VA_ARGS__)
607 II.setIsPoisoned(CurrentIsPoisoned);
Douglas Gregor935bc7a22011-10-27 09:33:13 +0000608 }
609
Chris Lattner677757a2006-06-28 05:26:32 +0000610 // If this identifier was poisoned, and if it was not produced from a macro
611 // expansion, emit an error.
Ted Kremeneka2c3c8d2008-11-19 22:43:49 +0000612 if (II.isPoisoned() && CurPPLexer) {
John Wiegley1c0675e2011-04-28 01:08:34 +0000613 HandlePoisonedIdentifier(Identifier);
Chris Lattner8ff71992006-07-06 05:17:39 +0000614 }
Mike Stump11289f42009-09-09 15:08:12 +0000615
Chris Lattner78186052006-07-09 00:45:31 +0000616 // If this is a macro to be expanded, do it.
Argyrios Kyrtzidisfead64b2013-02-24 00:05:14 +0000617 if (MacroDirective *MD = getMacroDirective(&II)) {
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +0000618 MacroInfo *MI = MD->getMacroInfo();
Abramo Bagnara123bec82012-01-01 22:01:04 +0000619 if (!DisableMacroExpansion) {
Richard Smith181879c2012-12-12 02:46:14 +0000620 if (!Identifier.isExpandDisabled() && MI->isEnabled()) {
Eli Friedman0834a4b2013-09-19 00:41:32 +0000621 // C99 6.10.3p10: If the preprocessing token immediately after the
622 // macro name isn't a '(', this macro should not be expanded.
623 if (!MI->isFunctionLike() || isNextPPTokenLParen())
624 return HandleMacroExpandedIdentifier(Identifier, MD);
Chris Lattner6e4bf522006-07-27 06:59:25 +0000625 } else {
626 // C99 6.10.3.4p2 says that a disabled macro may never again be
627 // expanded, even if it's in a context where it could be expanded in the
628 // future.
Chris Lattner146762e2007-07-20 16:59:19 +0000629 Identifier.setFlag(Token::DisableExpand);
Richard Smith181879c2012-12-12 02:46:14 +0000630 if (MI->isObjectLike() || isNextPPTokenLParen())
631 Diag(Identifier, diag::pp_disabled_macro_expansion);
Chris Lattner6e4bf522006-07-27 06:59:25 +0000632 }
633 }
Chris Lattner063400e2006-10-14 19:54:15 +0000634 }
Chris Lattner677757a2006-06-28 05:26:32 +0000635
Richard Smith4dd85d62011-10-11 19:57:52 +0000636 // If this identifier is a keyword in C++11, produce a warning. Don't warn if
637 // we're not considering macro expansion, since this identifier might be the
638 // name of a macro.
639 // FIXME: This warning is disabled in cases where it shouldn't be, like
640 // "#define constexpr constexpr", "int constexpr;"
Alp Toker7d2fea22014-02-24 04:35:58 +0000641 if (II.isCXX11CompatKeyword() && !DisableMacroExpansion) {
Richard Smith4dd85d62011-10-11 19:57:52 +0000642 Diag(Identifier, diag::warn_cxx11_keyword) << II.getName();
643 // Don't diagnose this keyword again in this translation unit.
644 II.setIsCXX11CompatKeyword(false);
645 }
646
Chris Lattner5b9f4892006-11-21 17:23:33 +0000647 // C++ 2.11p2: If this is an alternative representation of a C++ operator,
648 // then we act as if it is the actual operator and not the textual
649 // representation of it.
Fariborz Jahanian9e42a952010-09-03 17:33:04 +0000650 if (II.isCPlusPlusOperatorKeyword())
Craig Topperd2d442c2014-05-17 23:10:59 +0000651 Identifier.setIdentifierInfo(nullptr);
Chris Lattner5b9f4892006-11-21 17:23:33 +0000652
Chris Lattner677757a2006-06-28 05:26:32 +0000653 // If this is an extension token, diagnose its use.
Steve Naroffc84e8b72008-09-02 18:50:17 +0000654 // We avoid diagnosing tokens that originate from macro definitions.
Eli Friedman6bba2ad2009-04-28 03:59:15 +0000655 // FIXME: This warning is disabled in cases where it shouldn't be,
656 // like "#define TY typeof", "TY(1) x".
657 if (II.isExtensionToken() && !DisableMacroExpansion)
Chris Lattner53621a52007-06-13 20:44:40 +0000658 Diag(Identifier, diag::ext_token_used);
Douglas Gregoraf5c4842011-09-07 23:11:54 +0000659
Douglas Gregor594b8c92013-11-07 22:55:02 +0000660 // If this is the 'import' contextual keyword following an '@', note
Ted Kremenekc1e4dd02012-03-01 22:07:04 +0000661 // that the next token indicates a module name.
Douglas Gregor8d76cca2012-01-04 06:20:15 +0000662 //
Douglas Gregorc50d4922012-12-11 22:11:52 +0000663 // Note that we do not treat 'import' as a contextual
Ted Kremenekc1e4dd02012-03-01 22:07:04 +0000664 // keyword when we're in a caching lexer, because caching lexers only get
665 // used in contexts where import declarations are disallowed.
Douglas Gregor594b8c92013-11-07 22:55:02 +0000666 if (LastTokenWasAt && II.isModulesImport() && !InMacroArgs &&
667 !DisableMacroExpansion && getLangOpts().Modules &&
668 CurLexerKind != CLK_CachingLexer) {
Douglas Gregoraf5c4842011-09-07 23:11:54 +0000669 ModuleImportLoc = Identifier.getLocation();
Douglas Gregor1805b8a2011-11-30 04:26:53 +0000670 ModuleImportPath.clear();
671 ModuleImportExpectsIdentifier = true;
Douglas Gregoraf5c4842011-09-07 23:11:54 +0000672 CurLexerKind = CLK_LexAfterModuleImport;
673 }
Eli Friedman0834a4b2013-09-19 00:41:32 +0000674 return true;
Douglas Gregor08142532011-08-26 23:56:07 +0000675}
676
Eli Friedman0834a4b2013-09-19 00:41:32 +0000677void Preprocessor::Lex(Token &Result) {
678 // We loop here until a lex function retuns a token; this avoids recursion.
679 bool ReturnedToken;
680 do {
681 switch (CurLexerKind) {
682 case CLK_Lexer:
683 ReturnedToken = CurLexer->Lex(Result);
684 break;
685 case CLK_PTHLexer:
686 ReturnedToken = CurPTHLexer->Lex(Result);
687 break;
688 case CLK_TokenLexer:
689 ReturnedToken = CurTokenLexer->Lex(Result);
690 break;
691 case CLK_CachingLexer:
692 CachingLex(Result);
693 ReturnedToken = true;
694 break;
695 case CLK_LexAfterModuleImport:
696 LexAfterModuleImport(Result);
697 ReturnedToken = true;
698 break;
699 }
700 } while (!ReturnedToken);
Douglas Gregor594b8c92013-11-07 22:55:02 +0000701
702 LastTokenWasAt = Result.is(tok::at);
Eli Friedman0834a4b2013-09-19 00:41:32 +0000703}
704
705
Douglas Gregorda82e702012-01-03 19:32:59 +0000706/// \brief Lex a token following the 'import' contextual keyword.
Douglas Gregor22d09742012-01-03 18:04:46 +0000707///
Douglas Gregoraf5c4842011-09-07 23:11:54 +0000708void Preprocessor::LexAfterModuleImport(Token &Result) {
709 // Figure out what kind of lexer we actually have.
Douglas Gregor8d76cca2012-01-04 06:20:15 +0000710 recomputeCurLexerKind();
Douglas Gregoraf5c4842011-09-07 23:11:54 +0000711
712 // Lex the next token.
713 Lex(Result);
714
Douglas Gregor08142532011-08-26 23:56:07 +0000715 // The token sequence
716 //
Douglas Gregor22d09742012-01-03 18:04:46 +0000717 // import identifier (. identifier)*
718 //
Douglas Gregorda82e702012-01-03 19:32:59 +0000719 // indicates a module import directive. We already saw the 'import'
720 // contextual keyword, so now we're looking for the identifiers.
Douglas Gregor1805b8a2011-11-30 04:26:53 +0000721 if (ModuleImportExpectsIdentifier && Result.getKind() == tok::identifier) {
722 // We expected to see an identifier here, and we did; continue handling
723 // identifiers.
724 ModuleImportPath.push_back(std::make_pair(Result.getIdentifierInfo(),
725 Result.getLocation()));
726 ModuleImportExpectsIdentifier = false;
727 CurLexerKind = CLK_LexAfterModuleImport;
Douglas Gregor08142532011-08-26 23:56:07 +0000728 return;
Douglas Gregor1805b8a2011-11-30 04:26:53 +0000729 }
Douglas Gregor08142532011-08-26 23:56:07 +0000730
Douglas Gregor1805b8a2011-11-30 04:26:53 +0000731 // If we're expecting a '.' or a ';', and we got a '.', then wait until we
732 // see the next identifier.
733 if (!ModuleImportExpectsIdentifier && Result.getKind() == tok::period) {
734 ModuleImportExpectsIdentifier = true;
735 CurLexerKind = CLK_LexAfterModuleImport;
736 return;
737 }
738
739 // If we have a non-empty module path, load the named module.
Daniel Jasper07e6c402013-08-05 20:26:17 +0000740 if (!ModuleImportPath.empty() && getLangOpts().Modules) {
Argyrios Kyrtzidis19d78b72012-09-29 01:06:10 +0000741 Module *Imported = TheModuleLoader.loadModule(ModuleImportLoc,
742 ModuleImportPath,
743 Module::MacrosVisible,
744 /*IsIncludeDirective=*/false);
745 if (Callbacks)
746 Callbacks->moduleImport(ModuleImportLoc, ModuleImportPath, Imported);
747 }
Chris Lattner677757a2006-06-28 05:26:32 +0000748}
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000749
Andy Gibbs58905d22012-11-17 19:15:38 +0000750bool Preprocessor::FinishLexStringLiteral(Token &Result, std::string &String,
Andy Gibbsa8df57a2012-11-17 19:16:52 +0000751 const char *DiagnosticTag,
Andy Gibbs58905d22012-11-17 19:15:38 +0000752 bool AllowMacroExpansion) {
753 // We need at least one string literal.
754 if (Result.isNot(tok::string_literal)) {
Andy Gibbsa8df57a2012-11-17 19:16:52 +0000755 Diag(Result, diag::err_expected_string_literal)
756 << /*Source='in...'*/0 << DiagnosticTag;
Andy Gibbs58905d22012-11-17 19:15:38 +0000757 return false;
758 }
759
760 // Lex string literal tokens, optionally with macro expansion.
761 SmallVector<Token, 4> StrToks;
762 do {
763 StrToks.push_back(Result);
764
765 if (Result.hasUDSuffix())
766 Diag(Result, diag::err_invalid_string_udl);
767
768 if (AllowMacroExpansion)
769 Lex(Result);
770 else
771 LexUnexpandedToken(Result);
772 } while (Result.is(tok::string_literal));
773
774 // Concatenate and parse the strings.
Craig Topper9d5583e2014-06-26 04:58:39 +0000775 StringLiteralParser Literal(StrToks, *this);
Andy Gibbs58905d22012-11-17 19:15:38 +0000776 assert(Literal.isAscii() && "Didn't allow wide strings in");
777
778 if (Literal.hadError)
779 return false;
780
781 if (Literal.Pascal) {
Andy Gibbsa8df57a2012-11-17 19:16:52 +0000782 Diag(StrToks[0].getLocation(), diag::err_expected_string_literal)
783 << /*Source='in...'*/0 << DiagnosticTag;
Andy Gibbs58905d22012-11-17 19:15:38 +0000784 return false;
785 }
786
787 String = Literal.GetString();
788 return true;
789}
790
Reid Klecknerc0dca6d2014-02-12 23:50:26 +0000791bool Preprocessor::parseSimpleIntegerLiteral(Token &Tok, uint64_t &Value) {
792 assert(Tok.is(tok::numeric_constant));
793 SmallString<8> IntegerBuffer;
794 bool NumberInvalid = false;
795 StringRef Spelling = getSpelling(Tok, IntegerBuffer, &NumberInvalid);
796 if (NumberInvalid)
797 return false;
798 NumericLiteralParser Literal(Spelling, Tok.getLocation(), *this);
799 if (Literal.hadError || !Literal.isIntegerLiteral() || Literal.hasUDSuffix())
800 return false;
801 llvm::APInt APVal(64, 0);
802 if (Literal.GetIntegerValue(APVal))
803 return false;
804 Lex(Tok);
805 Value = APVal.getLimitedValue();
806 return true;
807}
808
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000809void Preprocessor::addCommentHandler(CommentHandler *Handler) {
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000810 assert(Handler && "NULL comment handler");
811 assert(std::find(CommentHandlers.begin(), CommentHandlers.end(), Handler) ==
812 CommentHandlers.end() && "Comment handler already registered");
813 CommentHandlers.push_back(Handler);
814}
815
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000816void Preprocessor::removeCommentHandler(CommentHandler *Handler) {
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000817 std::vector<CommentHandler *>::iterator Pos
818 = std::find(CommentHandlers.begin(), CommentHandlers.end(), Handler);
819 assert(Pos != CommentHandlers.end() && "Comment handler not registered");
820 CommentHandlers.erase(Pos);
821}
822
Chris Lattner87d02082010-01-18 22:35:47 +0000823bool Preprocessor::HandleComment(Token &result, SourceRange Comment) {
824 bool AnyPendingTokens = false;
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000825 for (std::vector<CommentHandler *>::iterator H = CommentHandlers.begin(),
826 HEnd = CommentHandlers.end();
Chris Lattner87d02082010-01-18 22:35:47 +0000827 H != HEnd; ++H) {
828 if ((*H)->HandleComment(*this, Comment))
829 AnyPendingTokens = true;
830 }
831 if (!AnyPendingTokens || getCommentRetentionState())
832 return false;
833 Lex(result);
834 return true;
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000835}
836
Douglas Gregor08142532011-08-26 23:56:07 +0000837ModuleLoader::~ModuleLoader() { }
838
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000839CommentHandler::~CommentHandler() { }
Douglas Gregor7f6d60d2010-03-19 16:15:56 +0000840
Douglas Gregor3a7ad252010-08-24 19:08:16 +0000841CodeCompletionHandler::~CodeCompletionHandler() { }
842
Argyrios Kyrtzidisf3d587e2012-12-04 07:27:05 +0000843void Preprocessor::createPreprocessingRecord() {
Douglas Gregor7f6d60d2010-03-19 16:15:56 +0000844 if (Record)
845 return;
846
Argyrios Kyrtzidisf3d587e2012-12-04 07:27:05 +0000847 Record = new PreprocessingRecord(getSourceManager());
Craig Topperb8a70532014-09-10 04:53:53 +0000848 addPPCallbacks(std::unique_ptr<PPCallbacks>(Record));
Douglas Gregor7f6d60d2010-03-19 16:15:56 +0000849}