blob: c7da41172f88bcaacc7dc193dd592ef13f59e465 [file] [log] [blame]
Eugene Zelenko5dc60fe2017-12-04 23:16:21 +00001//===- Preprocess.cpp - C Language Family Preprocessor Implementation -----===//
Chris Lattner22eb9722006-06-18 05:43:12 +00002//
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"
Eugene Zelenko5dc60fe2017-12-04 23:16:21 +000031#include "clang/Basic/IdentifierTable.h"
32#include "clang/Basic/LLVM.h"
33#include "clang/Basic/LangOptions.h"
34#include "clang/Basic/Module.h"
35#include "clang/Basic/SourceLocation.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000036#include "clang/Basic/SourceManager.h"
37#include "clang/Basic/TargetInfo.h"
38#include "clang/Lex/CodeCompletionHandler.h"
Douglas Gregor9882a5a2010-01-04 19:18:44 +000039#include "clang/Lex/ExternalPreprocessorSource.h"
Chris Lattner07b019a2006-10-22 07:28:56 +000040#include "clang/Lex/HeaderSearch.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000041#include "clang/Lex/LexDiagnostic.h"
Eugene Zelenko5dc60fe2017-12-04 23:16:21 +000042#include "clang/Lex/Lexer.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000043#include "clang/Lex/LiteralSupport.h"
Chandler Carruth5553d0d2014-01-07 11:51:46 +000044#include "clang/Lex/MacroArgs.h"
Chris Lattner22eb9722006-06-18 05:43:12 +000045#include "clang/Lex/MacroInfo.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000046#include "clang/Lex/ModuleLoader.h"
Eugene Zelenko5dc60fe2017-12-04 23:16:21 +000047#include "clang/Lex/PTHLexer.h"
Reid Kleckner738d48d2015-11-02 17:53:55 +000048#include "clang/Lex/PTHManager.h"
Chris Lattnerb8761832006-06-24 21:31:03 +000049#include "clang/Lex/Pragma.h"
Douglas Gregor7f6d60d2010-03-19 16:15:56 +000050#include "clang/Lex/PreprocessingRecord.h"
Eugene Zelenko5dc60fe2017-12-04 23:16:21 +000051#include "clang/Lex/PreprocessorLexer.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000052#include "clang/Lex/PreprocessorOptions.h"
Chris Lattner0b8cfc22006-06-28 06:49:17 +000053#include "clang/Lex/ScratchBuffer.h"
Eugene Zelenko5dc60fe2017-12-04 23:16:21 +000054#include "clang/Lex/Token.h"
55#include "clang/Lex/TokenLexer.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000056#include "llvm/ADT/APInt.h"
Eugene Zelenko5dc60fe2017-12-04 23:16:21 +000057#include "llvm/ADT/ArrayRef.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000058#include "llvm/ADT/DenseMap.h"
Chandler Carruth5553d0d2014-01-07 11:51:46 +000059#include "llvm/ADT/SmallString.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000060#include "llvm/ADT/SmallVector.h"
61#include "llvm/ADT/STLExtras.h"
62#include "llvm/ADT/StringRef.h"
Mehdi Amini9670f842016-07-18 19:02:11 +000063#include "llvm/ADT/StringSwitch.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000064#include "llvm/Support/Capacity.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000065#include "llvm/Support/ErrorHandling.h"
Chris Lattner8a7003c2007-07-16 06:48:38 +000066#include "llvm/Support/MemoryBuffer.h"
Benjamin Kramer89b422c2009-08-23 12:08:50 +000067#include "llvm/Support/raw_ostream.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000068#include <algorithm>
69#include <cassert>
70#include <memory>
71#include <string>
Benjamin Kramercfeacf52016-05-27 14:27:13 +000072#include <utility>
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000073#include <vector>
74
Chris Lattner22eb9722006-06-18 05:43:12 +000075using namespace clang;
76
John Brawn4d79ec72016-08-05 11:01:08 +000077LLVM_INSTANTIATE_REGISTRY(PragmaHandlerRegistry)
NAKAMURA Takumicacd94e2016-04-04 15:30:44 +000078
Eugene Zelenko5dc60fe2017-12-04 23:16:21 +000079ExternalPreprocessorSource::~ExternalPreprocessorSource() = default;
Chris Lattner22eb9722006-06-18 05:43:12 +000080
David Blaikiee3041682017-01-05 19:11:36 +000081Preprocessor::Preprocessor(std::shared_ptr<PreprocessorOptions> PPOpts,
Douglas Gregor1452ff12012-10-24 17:46:57 +000082 DiagnosticsEngine &diags, LangOptions &opts,
Duncan P. N. Exon Smith030d7d62017-03-20 17:58:26 +000083 SourceManager &SM, MemoryBufferCache &PCMCache,
84 HeaderSearch &Headers, ModuleLoader &TheModuleLoader,
David Blaikie687cd952013-01-16 23:13:36 +000085 IdentifierInfoLookup *IILookup, bool OwnsHeaders,
Alp Toker1ae02f62014-05-02 03:43:30 +000086 TranslationUnitKind TUKind)
Eugene Zelenko5dc60fe2017-12-04 23:16:21 +000087 : PPOpts(std::move(PPOpts)), Diags(&diags), LangOpts(opts),
Aaron Ballmand742dc22018-04-16 21:07:08 +000088 FileMgr(Headers.getFileMgr()), SourceMgr(SM), PCMCache(PCMCache),
89 ScratchBuf(new ScratchBuffer(SourceMgr)), HeaderInfo(Headers),
90 TheModuleLoader(TheModuleLoader), ExternalSource(nullptr),
91 // As the language options may have not been loaded yet (when
92 // deserializing an ASTUnit), adding keywords to the identifier table is
93 // deferred to Preprocessor::Initialize().
94 Identifiers(IILookup), PragmaHandlers(new PragmaNamespace(StringRef())),
95 TUKind(TUKind), SkipMainFilePreamble(0, true),
Eugene Zelenko5dc60fe2017-12-04 23:16:21 +000096 CurSubmoduleState(&NullSubmoduleState) {
Daniel Dunbar0c6c9302009-11-11 21:44:21 +000097 OwnsHeaderSearch = OwnsHeaders;
Fangrui Song6907ce22018-07-30 19:24:48 +000098
Douglas Gregor83297df2011-09-01 23:39:15 +000099 // Default to discarding comments.
100 KeepComments = false;
101 KeepMacroComments = false;
102 SuppressIncludeNotFoundError = false;
Fangrui Song6907ce22018-07-30 19:24:48 +0000103
Douglas Gregor83297df2011-09-01 23:39:15 +0000104 // Macro expansion is enabled.
105 DisableMacroExpansion = false;
David Blaikied5321242012-06-06 18:52:13 +0000106 MacroExpansionInDirectivesOverride = false;
Douglas Gregor83297df2011-09-01 23:39:15 +0000107 InMacroArgs = false;
Argyrios Kyrtzidisf1b64c62012-04-03 16:47:40 +0000108 InMacroArgPreExpansion = false;
Douglas Gregor83297df2011-09-01 23:39:15 +0000109 NumCachedTokenLexers = 0;
Jordan Rosede1a2922012-06-08 18:06:21 +0000110 PragmasEnabled = true;
Eric Christopher5e4696d2013-01-16 20:09:36 +0000111 ParsingIfOrElifDirective = false;
Jordan Rose324ec422013-01-31 19:26:01 +0000112 PreprocessedOutput = false;
Jordan Rosede1a2922012-06-08 18:06:21 +0000113
Douglas Gregor83297df2011-09-01 23:39:15 +0000114 // We haven't read anything from the external source.
115 ReadMacrosFromExternalSource = false;
Faisal Vali18268422017-10-15 01:26:26 +0000116
117 // "Poison" __VA_ARGS__, __VA_OPT__ which can only appear in the expansion of
118 // a macro. They get unpoisoned where it is allowed.
Douglas Gregor83297df2011-09-01 23:39:15 +0000119 (Ident__VA_ARGS__ = getIdentifierInfo("__VA_ARGS__"))->setIsPoisoned();
120 SetPoisonReason(Ident__VA_ARGS__,diag::ext_pp_bad_vaargs_use);
Faisal Vali18268422017-10-15 01:26:26 +0000121 if (getLangOpts().CPlusPlus2a) {
122 (Ident__VA_OPT__ = getIdentifierInfo("__VA_OPT__"))->setIsPoisoned();
123 SetPoisonReason(Ident__VA_OPT__,diag::ext_pp_bad_vaopt_use);
124 } else {
125 Ident__VA_OPT__ = nullptr;
126 }
127
Douglas Gregor83297df2011-09-01 23:39:15 +0000128 // Initialize the pragma handlers.
Douglas Gregor83297df2011-09-01 23:39:15 +0000129 RegisterBuiltinPragmas();
Fangrui Song6907ce22018-07-30 19:24:48 +0000130
Douglas Gregor83297df2011-09-01 23:39:15 +0000131 // Initialize builtin macros like __LINE__ and friends.
132 RegisterBuiltinMacros();
Fangrui Song6907ce22018-07-30 19:24:48 +0000133
David Blaikiebbafb8a2012-03-11 07:00:24 +0000134 if(LangOpts.Borland) {
Douglas Gregor83297df2011-09-01 23:39:15 +0000135 Ident__exception_info = getIdentifierInfo("_exception_info");
136 Ident___exception_info = getIdentifierInfo("__exception_info");
137 Ident_GetExceptionInfo = getIdentifierInfo("GetExceptionInformation");
138 Ident__exception_code = getIdentifierInfo("_exception_code");
139 Ident___exception_code = getIdentifierInfo("__exception_code");
140 Ident_GetExceptionCode = getIdentifierInfo("GetExceptionCode");
141 Ident__abnormal_termination = getIdentifierInfo("_abnormal_termination");
142 Ident___abnormal_termination = getIdentifierInfo("__abnormal_termination");
143 Ident_AbnormalTermination = getIdentifierInfo("AbnormalTermination");
144 } else {
Craig Topperd2d442c2014-05-17 23:10:59 +0000145 Ident__exception_info = Ident__exception_code = nullptr;
146 Ident__abnormal_termination = Ident___exception_info = nullptr;
147 Ident___exception_code = Ident___abnormal_termination = nullptr;
148 Ident_GetExceptionInfo = Ident_GetExceptionCode = nullptr;
149 Ident_AbnormalTermination = nullptr;
Douglas Gregor89929282012-01-30 06:01:29 +0000150 }
Erik Verbruggenb34c79f2017-05-30 11:54:55 +0000151
Erich Keane76675de2018-07-05 17:22:13 +0000152 // If using a PCH with a through header, start skipping tokens.
153 if (!this->PPOpts->PCHThroughHeader.empty() &&
154 !this->PPOpts->ImplicitPCHInclude.empty())
155 SkippingUntilPCHThroughHeader = true;
156
Erik Verbruggenb34c79f2017-05-30 11:54:55 +0000157 if (this->PPOpts->GeneratePreamble)
158 PreambleConditionalStack.startRecording();
Argyrios Kyrtzidis3c9aaf12012-06-02 18:08:09 +0000159}
160
161Preprocessor::~Preprocessor() {
162 assert(BacktrackPositions.empty() && "EnableBacktrack/Backtrack imbalance!");
163
Benjamin Kramer329c5962014-03-15 16:40:40 +0000164 IncludeMacroStack.clear();
Argyrios Kyrtzidis3c9aaf12012-06-02 18:08:09 +0000165
Richard Smith73a29662014-07-24 03:25:00 +0000166 // Destroy any macro definitions.
167 while (MacroInfoChain *I = MIChainHead) {
168 MIChainHead = I->Next;
169 I->~MacroInfoChain();
170 }
Argyrios Kyrtzidis3c9aaf12012-06-02 18:08:09 +0000171
172 // Free any cached macro expanders.
Nico Weber5f5b9412014-05-09 18:09:42 +0000173 // This populates MacroArgCache, so all TokenLexers need to be destroyed
174 // before the code below that frees up the MacroArgCache list.
David Blaikie6d5038c2014-08-29 19:36:52 +0000175 std::fill(TokenLexerCache, TokenLexerCache + NumCachedTokenLexers, nullptr);
Nico Weber5f5b9412014-05-09 18:09:42 +0000176 CurTokenLexer.reset();
Argyrios Kyrtzidis3c9aaf12012-06-02 18:08:09 +0000177
178 // Free any cached MacroArgs.
Nico Weber5f5b9412014-05-09 18:09:42 +0000179 for (MacroArgs *ArgList = MacroArgCache; ArgList;)
Argyrios Kyrtzidis3c9aaf12012-06-02 18:08:09 +0000180 ArgList = ArgList->deallocate();
181
Argyrios Kyrtzidis3c9aaf12012-06-02 18:08:09 +0000182 // Delete the header search info, if we own it.
183 if (OwnsHeaderSearch)
184 delete &HeaderInfo;
Argyrios Kyrtzidis3c9aaf12012-06-02 18:08:09 +0000185}
186
Artem Belevichb5bc9232015-09-22 17:23:22 +0000187void Preprocessor::Initialize(const TargetInfo &Target,
188 const TargetInfo *AuxTarget) {
Argyrios Kyrtzidis3c9aaf12012-06-02 18:08:09 +0000189 assert((!this->Target || this->Target == &Target) &&
190 "Invalid override of target information");
191 this->Target = &Target;
Artem Belevichb5bc9232015-09-22 17:23:22 +0000192
193 assert((!this->AuxTarget || this->AuxTarget == AuxTarget) &&
194 "Invalid override of aux target information.");
195 this->AuxTarget = AuxTarget;
196
Argyrios Kyrtzidis3c9aaf12012-06-02 18:08:09 +0000197 // Initialize information about built-ins.
Artem Belevichb5bc9232015-09-22 17:23:22 +0000198 BuiltinInfo.InitializeTarget(Target, AuxTarget);
Douglas Gregor89929282012-01-30 06:01:29 +0000199 HeaderInfo.setTarget(Target);
Aaron Ballmand742dc22018-04-16 21:07:08 +0000200
201 // Populate the identifier table with info about keywords for the current language.
202 Identifiers.AddKeywords(LangOpts);
Douglas Gregor83297df2011-09-01 23:39:15 +0000203}
204
Ted Kremenekeeccb302014-08-27 15:14:15 +0000205void Preprocessor::InitializeForModelFile() {
206 NumEnteredSourceFiles = 0;
207
208 // Reset pragmas
David Blaikie9f0af9d2014-09-15 21:31:42 +0000209 PragmaHandlersBackup = std::move(PragmaHandlers);
Craig Topperbe250302014-09-12 05:19:24 +0000210 PragmaHandlers = llvm::make_unique<PragmaNamespace>(StringRef());
Ted Kremenekeeccb302014-08-27 15:14:15 +0000211 RegisterBuiltinPragmas();
212
213 // Reset PredefinesFileID
214 PredefinesFileID = FileID();
215}
216
217void Preprocessor::FinalizeForModelFile() {
218 NumEnteredSourceFiles = 1;
219
David Blaikie9f0af9d2014-09-15 21:31:42 +0000220 PragmaHandlers = std::move(PragmaHandlersBackup);
Ted Kremenekeeccb302014-08-27 15:14:15 +0000221}
222
Ted Kremeneka5c2c272009-02-12 03:26:59 +0000223void Preprocessor::setPTHManager(PTHManager* pm) {
224 PTH.reset(pm);
Douglas Gregord2eb58a2009-10-16 18:18:30 +0000225 FileMgr.addStatCache(PTH->createStatCache());
Ted Kremeneka5c2c272009-02-12 03:26:59 +0000226}
227
Chris Lattner146762e2007-07-20 16:59:19 +0000228void Preprocessor::DumpToken(const Token &Tok, bool DumpFlags) const {
Benjamin Kramer89b422c2009-08-23 12:08:50 +0000229 llvm::errs() << tok::getTokenName(Tok.getKind()) << " '"
230 << getSpelling(Tok) << "'";
Mike Stump11289f42009-09-09 15:08:12 +0000231
Chris Lattnerd01e2912006-06-18 16:22:51 +0000232 if (!DumpFlags) return;
Mike Stump11289f42009-09-09 15:08:12 +0000233
Benjamin Kramer89b422c2009-08-23 12:08:50 +0000234 llvm::errs() << "\t";
Chris Lattnerd01e2912006-06-18 16:22:51 +0000235 if (Tok.isAtStartOfLine())
Benjamin Kramer89b422c2009-08-23 12:08:50 +0000236 llvm::errs() << " [StartOfLine]";
Chris Lattnerd01e2912006-06-18 16:22:51 +0000237 if (Tok.hasLeadingSpace())
Benjamin Kramer89b422c2009-08-23 12:08:50 +0000238 llvm::errs() << " [LeadingSpace]";
Chris Lattner6e4bf522006-07-27 06:59:25 +0000239 if (Tok.isExpandDisabled())
Benjamin Kramer89b422c2009-08-23 12:08:50 +0000240 llvm::errs() << " [ExpandDisabled]";
Chris Lattnerd01e2912006-06-18 16:22:51 +0000241 if (Tok.needsCleaning()) {
Chris Lattner50b497e2006-06-18 16:32:35 +0000242 const char *Start = SourceMgr.getCharacterData(Tok.getLocation());
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000243 llvm::errs() << " [UnClean='" << StringRef(Start, Tok.getLength())
Benjamin Kramer89b422c2009-08-23 12:08:50 +0000244 << "']";
Chris Lattnerd01e2912006-06-18 16:22:51 +0000245 }
Mike Stump11289f42009-09-09 15:08:12 +0000246
Benjamin Kramer89b422c2009-08-23 12:08:50 +0000247 llvm::errs() << "\tLoc=<";
Chris Lattner615315f2007-12-09 20:31:55 +0000248 DumpLocation(Tok.getLocation());
Benjamin Kramer89b422c2009-08-23 12:08:50 +0000249 llvm::errs() << ">";
Chris Lattner615315f2007-12-09 20:31:55 +0000250}
251
252void Preprocessor::DumpLocation(SourceLocation Loc) const {
Stephen Kelly3124ce72018-08-15 20:32:06 +0000253 Loc.print(llvm::errs(), SourceMgr);
Chris Lattnerd01e2912006-06-18 16:22:51 +0000254}
255
256void Preprocessor::DumpMacro(const MacroInfo &MI) const {
Benjamin Kramer89b422c2009-08-23 12:08:50 +0000257 llvm::errs() << "MACRO: ";
Chris Lattnerd01e2912006-06-18 16:22:51 +0000258 for (unsigned i = 0, e = MI.getNumTokens(); i != e; ++i) {
259 DumpToken(MI.getReplacementToken(i));
Benjamin Kramer89b422c2009-08-23 12:08:50 +0000260 llvm::errs() << " ";
Chris Lattnerd01e2912006-06-18 16:22:51 +0000261 }
Benjamin Kramer89b422c2009-08-23 12:08:50 +0000262 llvm::errs() << "\n";
Chris Lattnerd01e2912006-06-18 16:22:51 +0000263}
264
Chris Lattner22eb9722006-06-18 05:43:12 +0000265void Preprocessor::PrintStats() {
Benjamin Kramer89b422c2009-08-23 12:08:50 +0000266 llvm::errs() << "\n*** Preprocessor Stats:\n";
267 llvm::errs() << NumDirectives << " directives found:\n";
268 llvm::errs() << " " << NumDefined << " #define.\n";
269 llvm::errs() << " " << NumUndefined << " #undef.\n";
270 llvm::errs() << " #include/#include_next/#import:\n";
271 llvm::errs() << " " << NumEnteredSourceFiles << " source files entered.\n";
272 llvm::errs() << " " << MaxIncludeStackDepth << " max include stack depth\n";
273 llvm::errs() << " " << NumIf << " #if/#ifndef/#ifdef.\n";
274 llvm::errs() << " " << NumElse << " #else/#elif.\n";
275 llvm::errs() << " " << NumEndif << " #endif.\n";
276 llvm::errs() << " " << NumPragma << " #pragma.\n";
277 llvm::errs() << NumSkipped << " #if/#ifndef#ifdef regions skipped\n";
Chris Lattner22eb9722006-06-18 05:43:12 +0000278
Benjamin Kramer89b422c2009-08-23 12:08:50 +0000279 llvm::errs() << NumMacroExpanded << "/" << NumFnMacroExpanded << "/"
Ted Kremeneka0a3e9b2008-01-14 16:44:48 +0000280 << NumBuiltinMacroExpanded << " obj/fn/builtin macros expanded, "
281 << NumFastMacroExpanded << " on the fast path.\n";
Benjamin Kramer89b422c2009-08-23 12:08:50 +0000282 llvm::errs() << (NumFastTokenPaste+NumTokenPaste)
Ted Kremeneka0a3e9b2008-01-14 16:44:48 +0000283 << " token paste (##) operations performed, "
284 << NumFastTokenPaste << " on the fast path.\n";
Alexander Kornienko199cd942012-08-13 10:46:42 +0000285
286 llvm::errs() << "\nPreprocessor Memory: " << getTotalMemory() << "B total";
287
288 llvm::errs() << "\n BumpPtr: " << BP.getTotalMemory();
289 llvm::errs() << "\n Macro Expanded Tokens: "
290 << llvm::capacity_in_bytes(MacroExpandedTokens);
291 llvm::errs() << "\n Predefines Buffer: " << Predefines.capacity();
Richard Smith04765ae2015-05-21 01:20:10 +0000292 // FIXME: List information for all submodules.
293 llvm::errs() << "\n Macros: "
294 << llvm::capacity_in_bytes(CurSubmoduleState->Macros);
Alexander Kornienko199cd942012-08-13 10:46:42 +0000295 llvm::errs() << "\n #pragma push_macro Info: "
296 << llvm::capacity_in_bytes(PragmaPushMacroInfo);
297 llvm::errs() << "\n Poison Reasons: "
298 << llvm::capacity_in_bytes(PoisonReasons);
299 llvm::errs() << "\n Comment Handlers: "
300 << llvm::capacity_in_bytes(CommentHandlers) << "\n";
Chris Lattner22eb9722006-06-18 05:43:12 +0000301}
302
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +0000303Preprocessor::macro_iterator
304Preprocessor::macro_begin(bool IncludeExternalMacros) const {
305 if (IncludeExternalMacros && ExternalSource &&
Douglas Gregor9882a5a2010-01-04 19:18:44 +0000306 !ReadMacrosFromExternalSource) {
307 ReadMacrosFromExternalSource = true;
308 ExternalSource->ReadDefinedMacros();
309 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +0000310
Jordan Rosea46bfa62015-06-24 19:27:02 +0000311 // Make sure we cover all macros in visible modules.
312 for (const ModuleMacro &Macro : ModuleMacros)
313 CurSubmoduleState->Macros.insert(std::make_pair(Macro.II, MacroState()));
314
Richard Smith04765ae2015-05-21 01:20:10 +0000315 return CurSubmoduleState->Macros.begin();
Douglas Gregor9882a5a2010-01-04 19:18:44 +0000316}
317
Argyrios Kyrtzidise379ee32011-06-29 22:20:04 +0000318size_t Preprocessor::getTotalMemory() const {
Ted Kremenek182543a2011-07-26 21:17:24 +0000319 return BP.getTotalMemory()
Ted Kremenek8b77fe72011-07-27 18:41:23 +0000320 + llvm::capacity_in_bytes(MacroExpandedTokens)
Ted Kremenek182543a2011-07-26 21:17:24 +0000321 + Predefines.capacity() /* Predefines buffer. */
Richard Smith04765ae2015-05-21 01:20:10 +0000322 // FIXME: Include sizes from all submodules, and include MacroInfo sizes,
323 // and ModuleMacros.
324 + llvm::capacity_in_bytes(CurSubmoduleState->Macros)
Ted Kremenek8b77fe72011-07-27 18:41:23 +0000325 + llvm::capacity_in_bytes(PragmaPushMacroInfo)
326 + llvm::capacity_in_bytes(PoisonReasons)
327 + llvm::capacity_in_bytes(CommentHandlers);
Argyrios Kyrtzidise379ee32011-06-29 22:20:04 +0000328}
329
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +0000330Preprocessor::macro_iterator
331Preprocessor::macro_end(bool IncludeExternalMacros) const {
332 if (IncludeExternalMacros && ExternalSource &&
Douglas Gregor9882a5a2010-01-04 19:18:44 +0000333 !ReadMacrosFromExternalSource) {
334 ReadMacrosFromExternalSource = true;
335 ExternalSource->ReadDefinedMacros();
336 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +0000337
Richard Smith04765ae2015-05-21 01:20:10 +0000338 return CurSubmoduleState->Macros.end();
Douglas Gregor9882a5a2010-01-04 19:18:44 +0000339}
340
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000341/// Compares macro tokens with a specified token value sequence.
Dmitri Gribenko6743e042012-09-29 11:40:46 +0000342static bool MacroDefinitionEquals(const MacroInfo *MI,
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000343 ArrayRef<TokenValue> Tokens) {
Dmitri Gribenko6743e042012-09-29 11:40:46 +0000344 return Tokens.size() == MI->getNumTokens() &&
345 std::equal(Tokens.begin(), Tokens.end(), MI->tokens_begin());
346}
347
348StringRef Preprocessor::getLastMacroWithSpelling(
349 SourceLocation Loc,
350 ArrayRef<TokenValue> Tokens) const {
351 SourceLocation BestLocation;
352 StringRef BestSpelling;
353 for (Preprocessor::macro_iterator I = macro_begin(), E = macro_end();
354 I != E; ++I) {
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +0000355 const MacroDirective::DefInfo
Richard Smithb8b2ed62015-04-23 18:18:26 +0000356 Def = I->second.findDirectiveAtLoc(Loc, SourceMgr);
Argyrios Kyrtzidis5c585252015-03-04 16:03:07 +0000357 if (!Def || !Def.getMacroInfo())
358 continue;
359 if (!Def.getMacroInfo()->isObjectLike())
Dmitri Gribenko6743e042012-09-29 11:40:46 +0000360 continue;
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +0000361 if (!MacroDefinitionEquals(Def.getMacroInfo(), Tokens))
Dmitri Gribenko6743e042012-09-29 11:40:46 +0000362 continue;
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +0000363 SourceLocation Location = Def.getLocation();
Dmitri Gribenko6743e042012-09-29 11:40:46 +0000364 // Choose the macro defined latest.
365 if (BestLocation.isInvalid() ||
366 (Location.isValid() &&
367 SourceMgr.isBeforeInTranslationUnit(BestLocation, Location))) {
368 BestLocation = Location;
369 BestSpelling = I->first->getName();
370 }
371 }
372 return BestSpelling;
373}
374
Douglas Gregor8d76cca2012-01-04 06:20:15 +0000375void Preprocessor::recomputeCurLexerKind() {
376 if (CurLexer)
377 CurLexerKind = CLK_Lexer;
378 else if (CurPTHLexer)
379 CurLexerKind = CLK_PTHLexer;
380 else if (CurTokenLexer)
381 CurLexerKind = CLK_TokenLexer;
Fangrui Song6907ce22018-07-30 19:24:48 +0000382 else
Douglas Gregor8d76cca2012-01-04 06:20:15 +0000383 CurLexerKind = CLK_CachingLexer;
384}
385
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +0000386bool Preprocessor::SetCodeCompletionPoint(const FileEntry *File,
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +0000387 unsigned CompleteLine,
388 unsigned CompleteColumn) {
389 assert(File);
390 assert(CompleteLine && CompleteColumn && "Starts from 1:1");
391 assert(!CodeCompletionFile && "Already set");
392
Douglas Gregor53ad6b92009-12-02 06:49:09 +0000393 using llvm::MemoryBuffer;
394
Douglas Gregor53ad6b92009-12-02 06:49:09 +0000395 // Load the actual file's contents.
Douglas Gregor26266da2010-03-16 19:49:24 +0000396 bool Invalid = false;
397 const MemoryBuffer *Buffer = SourceMgr.getMemoryBufferForFile(File, &Invalid);
398 if (Invalid)
Douglas Gregor53ad6b92009-12-02 06:49:09 +0000399 return true;
400
401 // Find the byte position of the truncation point.
402 const char *Position = Buffer->getBufferStart();
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +0000403 for (unsigned Line = 1; Line < CompleteLine; ++Line) {
Douglas Gregor53ad6b92009-12-02 06:49:09 +0000404 for (; *Position; ++Position) {
405 if (*Position != '\r' && *Position != '\n')
406 continue;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +0000407
Douglas Gregor53ad6b92009-12-02 06:49:09 +0000408 // Eat \r\n or \n\r as a single line.
409 if ((Position[1] == '\r' || Position[1] == '\n') &&
410 Position[0] != Position[1])
411 ++Position;
412 ++Position;
413 break;
414 }
415 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +0000416
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +0000417 Position += CompleteColumn - 1;
Argyrios Kyrtzidisee301f92014-10-18 06:23:50 +0000418
419 // If pointing inside the preamble, adjust the position at the beginning of
420 // the file after the preamble.
421 if (SkipMainFilePreamble.first &&
422 SourceMgr.getFileEntryForID(SourceMgr.getMainFileID()) == File) {
423 if (Position - Buffer->getBufferStart() < SkipMainFilePreamble.first)
424 Position = Buffer->getBufferStart() + SkipMainFilePreamble.first;
425 }
426
Argyrios Kyrtzidise62d6822014-10-18 06:19:36 +0000427 if (Position > Buffer->getBufferEnd())
428 Position = Buffer->getBufferEnd();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +0000429
Argyrios Kyrtzidise62d6822014-10-18 06:19:36 +0000430 CodeCompletionFile = File;
431 CodeCompletionOffset = Position - Buffer->getBufferStart();
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +0000432
Pavel Labathbf8519b2017-12-20 11:34:38 +0000433 auto NewBuffer = llvm::WritableMemoryBuffer::getNewUninitMemBuffer(
434 Buffer->getBufferSize() + 1, Buffer->getBufferIdentifier());
435 char *NewBuf = NewBuffer->getBufferStart();
Argyrios Kyrtzidise62d6822014-10-18 06:19:36 +0000436 char *NewPos = std::copy(Buffer->getBufferStart(), Position, NewBuf);
437 *NewPos = '\0';
438 std::copy(Position, Buffer->getBufferEnd(), NewPos+1);
439 SourceMgr.overrideFileContents(File, std::move(NewBuffer));
Douglas Gregor53ad6b92009-12-02 06:49:09 +0000440
441 return false;
442}
443
Douglas Gregor11583702010-08-25 17:04:25 +0000444void Preprocessor::CodeCompleteNaturalLanguage() {
Douglas Gregor11583702010-08-25 17:04:25 +0000445 if (CodeComplete)
446 CodeComplete->CodeCompleteNaturalLanguage();
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +0000447 setCodeCompletionReached();
Douglas Gregor11583702010-08-25 17:04:25 +0000448}
449
Benjamin Kramera197fb62010-02-27 17:05:45 +0000450/// getSpelling - This method is used to get the spelling of a token into a
451/// SmallVector. Note that the returned StringRef may not point to the
452/// supplied buffer if a copy can be avoided.
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000453StringRef Preprocessor::getSpelling(const Token &Tok,
454 SmallVectorImpl<char> &Buffer,
Douglas Gregor7bda4b82010-03-16 05:20:39 +0000455 bool *Invalid) const {
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +0000456 // NOTE: this has to be checked *before* testing for an IdentifierInfo.
Jordan Rose7f43ddd2013-01-24 20:50:46 +0000457 if (Tok.isNot(tok::raw_identifier) && !Tok.hasUCN()) {
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +0000458 // Try the fast path.
459 if (const IdentifierInfo *II = Tok.getIdentifierInfo())
460 return II->getName();
461 }
Benjamin Kramera197fb62010-02-27 17:05:45 +0000462
463 // Resize the buffer if we need to copy into it.
464 if (Tok.needsCleaning())
465 Buffer.resize(Tok.getLength());
466
467 const char *Ptr = Buffer.data();
Douglas Gregor7bda4b82010-03-16 05:20:39 +0000468 unsigned Len = getSpelling(Tok, Ptr, Invalid);
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000469 return StringRef(Ptr, Len);
Benjamin Kramera197fb62010-02-27 17:05:45 +0000470}
471
Chris Lattnerb94ec7b2006-07-14 06:54:10 +0000472/// CreateString - Plop the specified string into a scratch buffer and return a
473/// location for it. If specified, the source location provides a source
474/// location for the token.
Dmitri Gribenkob8e9e752012-09-24 21:07:17 +0000475void Preprocessor::CreateString(StringRef Str, Token &Tok,
Abramo Bagnarae398e602011-10-03 18:39:03 +0000476 SourceLocation ExpansionLocStart,
477 SourceLocation ExpansionLocEnd) {
Dmitri Gribenkob8e9e752012-09-24 21:07:17 +0000478 Tok.setLength(Str.size());
Mike Stump11289f42009-09-09 15:08:12 +0000479
Chris Lattner5a7971e2009-01-26 19:29:26 +0000480 const char *DestPtr;
Dmitri Gribenkob8e9e752012-09-24 21:07:17 +0000481 SourceLocation Loc = ScratchBuf->getToken(Str.data(), Str.size(), DestPtr);
Mike Stump11289f42009-09-09 15:08:12 +0000482
Abramo Bagnarae398e602011-10-03 18:39:03 +0000483 if (ExpansionLocStart.isValid())
484 Loc = SourceMgr.createExpansionLoc(Loc, ExpansionLocStart,
Dmitri Gribenkob8e9e752012-09-24 21:07:17 +0000485 ExpansionLocEnd, Str.size());
Chris Lattner5a7971e2009-01-26 19:29:26 +0000486 Tok.setLocation(Loc);
Mike Stump11289f42009-09-09 15:08:12 +0000487
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +0000488 // If this is a raw identifier or a literal token, set the pointer data.
489 if (Tok.is(tok::raw_identifier))
490 Tok.setRawIdentifierData(DestPtr);
491 else if (Tok.isLiteral())
Chris Lattner5a7971e2009-01-26 19:29:26 +0000492 Tok.setLiteralData(DestPtr);
Chris Lattnerb94ec7b2006-07-14 06:54:10 +0000493}
494
Richard Smithb5f81712018-04-30 05:25:48 +0000495SourceLocation Preprocessor::SplitToken(SourceLocation Loc, unsigned Length) {
496 auto &SM = getSourceManager();
497 SourceLocation SpellingLoc = SM.getSpellingLoc(Loc);
498 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(SpellingLoc);
499 bool Invalid = false;
500 StringRef Buffer = SM.getBufferData(LocInfo.first, &Invalid);
501 if (Invalid)
502 return SourceLocation();
503
504 // FIXME: We could consider re-using spelling for tokens we see repeatedly.
505 const char *DestPtr;
506 SourceLocation Spelling =
507 ScratchBuf->getToken(Buffer.data() + LocInfo.second, Length, DestPtr);
508 return SM.createTokenSplitLoc(Spelling, Loc, Loc.getLocWithOffset(Length));
509}
510
Douglas Gregor2b82c2a2011-12-02 01:47:07 +0000511Module *Preprocessor::getCurrentModule() {
Richard Smithbbcc9f02016-08-26 00:14:38 +0000512 if (!getLangOpts().isCompilingModule())
Craig Topperd2d442c2014-05-17 23:10:59 +0000513 return nullptr;
514
David Blaikiebbafb8a2012-03-11 07:00:24 +0000515 return getHeaderSearchInfo().lookupModule(getLangOpts().CurrentModule);
Douglas Gregor2b82c2a2011-12-02 01:47:07 +0000516}
Chris Lattner8a7003c2007-07-16 06:48:38 +0000517
Chris Lattner1f1b0db2007-10-09 22:10:18 +0000518//===----------------------------------------------------------------------===//
519// Preprocessor Initialization Methods
520//===----------------------------------------------------------------------===//
521
Chris Lattner1f1b0db2007-10-09 22:10:18 +0000522/// EnterMainSourceFile - Enter the specified FileID as the main source file,
Nate Begemanf7c3ff62008-01-07 04:01:26 +0000523/// which implicitly adds the builtin defines etc.
Chris Lattnerfb24a3a2010-04-20 20:35:58 +0000524void Preprocessor::EnterMainSourceFile() {
Chris Lattner9ef847b2009-02-13 19:33:24 +0000525 // We do not allow the preprocessor to reenter the main file. Doing so will
526 // cause FileID's to accumulate information from both runs (e.g. #line
527 // information) and predefined macros aren't guaranteed to be set properly.
528 assert(NumEnteredSourceFiles == 0 && "Cannot reenter the main file!");
Chris Lattnerd32480d2009-01-17 06:22:33 +0000529 FileID MainFileID = SourceMgr.getMainFileID();
Mike Stump11289f42009-09-09 15:08:12 +0000530
Argyrios Kyrtzidis9afd4492012-01-05 21:36:25 +0000531 // If MainFileID is loaded it means we loaded an AST file, no need to enter
532 // a main file.
533 if (!SourceMgr.isLoadedFileID(MainFileID)) {
534 // Enter the main file source buffer.
Craig Topperd2d442c2014-05-17 23:10:59 +0000535 EnterSourceFile(MainFileID, nullptr, SourceLocation());
536
Argyrios Kyrtzidis9afd4492012-01-05 21:36:25 +0000537 // If we've been asked to skip bytes in the main file (e.g., as part of a
538 // precompiled preamble), do so now.
539 if (SkipMainFilePreamble.first > 0)
Cameron Desrochers84fd0642017-09-20 19:03:37 +0000540 CurLexer->SetByteOffset(SkipMainFilePreamble.first,
541 SkipMainFilePreamble.second);
542
Argyrios Kyrtzidis9afd4492012-01-05 21:36:25 +0000543 // Tell the header info that the main file was entered. If the file is later
544 // #imported, it won't be re-entered.
545 if (const FileEntry *FE = SourceMgr.getFileEntryForID(MainFileID))
546 HeaderInfo.IncrementIncludeCount(FE);
547 }
Mike Stump11289f42009-09-09 15:08:12 +0000548
Benjamin Kramerd77adb52009-12-31 15:33:09 +0000549 // Preprocess Predefines to populate the initial preprocessor state.
Rafael Espindolad87f8d72014-08-27 20:03:29 +0000550 std::unique_ptr<llvm::MemoryBuffer> SB =
Chris Lattner58c79342010-04-05 22:42:27 +0000551 llvm::MemoryBuffer::getMemBufferCopy(Predefines, "<built-in>");
Douglas Gregor33551892010-08-26 14:07:34 +0000552 assert(SB && "Cannot create predefined source buffer");
David Blaikie50a5f972014-08-29 07:59:55 +0000553 FileID FID = SourceMgr.createFileID(std::move(SB));
Yaron Keren8b563662015-10-03 10:46:20 +0000554 assert(FID.isValid() && "Could not create FileID for predefines?");
Argyrios Kyrtzidis22c22f52013-02-01 16:36:07 +0000555 setPredefinesFileID(FID);
Mike Stump11289f42009-09-09 15:08:12 +0000556
Chris Lattner1f1b0db2007-10-09 22:10:18 +0000557 // Start parsing the predefines.
Craig Topperd2d442c2014-05-17 23:10:59 +0000558 EnterSourceFile(FID, nullptr, SourceLocation());
Erich Keane76675de2018-07-05 17:22:13 +0000559
560 if (!PPOpts->PCHThroughHeader.empty()) {
561 // Lookup and save the FileID for the through header. If it isn't found
562 // in the search path, it's a fatal error.
563 const DirectoryLookup *CurDir;
564 const FileEntry *File = LookupFile(
565 SourceLocation(), PPOpts->PCHThroughHeader,
566 /*isAngled=*/false, /*FromDir=*/nullptr, /*FromFile=*/nullptr, CurDir,
567 /*SearchPath=*/nullptr, /*RelativePath=*/nullptr,
568 /*SuggestedModule=*/nullptr, /*IsMapped=*/nullptr);
569 if (!File) {
570 Diag(SourceLocation(), diag::err_pp_through_header_not_found)
571 << PPOpts->PCHThroughHeader;
572 return;
573 }
574 setPCHThroughHeaderFileID(
575 SourceMgr.createFileID(File, SourceLocation(), SrcMgr::C_User));
576 }
577
578 // Skip tokens from the Predefines and if needed the main file.
579 if (usingPCHWithThroughHeader() && SkippingUntilPCHThroughHeader)
580 SkipTokensUntilPCHThroughHeader();
581}
582
583void Preprocessor::setPCHThroughHeaderFileID(FileID FID) {
584 assert(PCHThroughHeaderFileID.isInvalid() &&
585 "PCHThroughHeaderFileID already set!");
586 PCHThroughHeaderFileID = FID;
587}
588
589bool Preprocessor::isPCHThroughHeader(const FileEntry *FE) {
590 assert(PCHThroughHeaderFileID.isValid() &&
591 "Invalid PCH through header FileID");
592 return FE == SourceMgr.getFileEntryForID(PCHThroughHeaderFileID);
593}
594
595bool Preprocessor::creatingPCHWithThroughHeader() {
596 return TUKind == TU_Prefix && !PPOpts->PCHThroughHeader.empty() &&
597 PCHThroughHeaderFileID.isValid();
598}
599
600bool Preprocessor::usingPCHWithThroughHeader() {
601 return TUKind != TU_Prefix && !PPOpts->PCHThroughHeader.empty() &&
602 PCHThroughHeaderFileID.isValid();
603}
604
605/// Skip tokens until after the #include of the through header.
606/// Tokens in the predefines file and the main file may be skipped. If the end
607/// of the predefines file is reached, skipping continues into the main file.
608/// If the end of the main file is reached, it's a fatal error.
609void Preprocessor::SkipTokensUntilPCHThroughHeader() {
610 bool ReachedMainFileEOF = false;
611 Token Tok;
612 while (true) {
613 bool InPredefines = (CurLexer->getFileID() == getPredefinesFileID());
614 CurLexer->Lex(Tok);
615 if (Tok.is(tok::eof) && !InPredefines) {
616 ReachedMainFileEOF = true;
617 break;
618 }
619 if (!SkippingUntilPCHThroughHeader)
620 break;
621 }
622 if (ReachedMainFileEOF)
623 Diag(SourceLocation(), diag::err_pp_through_header_not_seen)
624 << PPOpts->PCHThroughHeader << 1;
Erik Verbruggen795eee92017-07-05 09:44:07 +0000625}
Erik Verbruggenb34c79f2017-05-30 11:54:55 +0000626
Erik Verbruggen795eee92017-07-05 09:44:07 +0000627void Preprocessor::replayPreambleConditionalStack() {
Erik Verbruggenb34c79f2017-05-30 11:54:55 +0000628 // Restore the conditional stack from the preamble, if there is one.
629 if (PreambleConditionalStack.isReplaying()) {
Ilya Biryukovf3150002017-08-21 12:03:08 +0000630 assert(CurPPLexer &&
631 "CurPPLexer is null when calling replayPreambleConditionalStack.");
Erik Verbruggenb34c79f2017-05-30 11:54:55 +0000632 CurPPLexer->setConditionalLevels(PreambleConditionalStack.getStack());
633 PreambleConditionalStack.doneReplaying();
Erik Verbruggen4d1eb2d2017-11-03 09:40:07 +0000634 if (PreambleConditionalStack.reachedEOFWhileSkipping())
635 SkipExcludedConditionalBlock(
636 PreambleConditionalStack.SkipInfo->HashTokenLoc,
637 PreambleConditionalStack.SkipInfo->IfTokenLoc,
638 PreambleConditionalStack.SkipInfo->FoundNonSkipPortion,
639 PreambleConditionalStack.SkipInfo->FoundElse,
640 PreambleConditionalStack.SkipInfo->ElseLoc);
Erik Verbruggenb34c79f2017-05-30 11:54:55 +0000641 }
Chris Lattner1f1b0db2007-10-09 22:10:18 +0000642}
Chris Lattner8a7003c2007-07-16 06:48:38 +0000643
Daniel Dunbarcb9eaf52010-03-23 05:09:10 +0000644void Preprocessor::EndSourceFile() {
645 // Notify the client that we reached the end of the source file.
646 if (Callbacks)
647 Callbacks->EndOfMainFile();
648}
Chris Lattner677757a2006-06-28 05:26:32 +0000649
650//===----------------------------------------------------------------------===//
651// Lexer Event Handling.
652//===----------------------------------------------------------------------===//
653
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +0000654/// LookUpIdentifierInfo - Given a tok::raw_identifier token, look up the
655/// identifier information for the token and install it into the token,
656/// updating the token kind accordingly.
657IdentifierInfo *Preprocessor::LookUpIdentifierInfo(Token &Identifier) const {
Alp Toker2d57cea2014-05-17 04:53:25 +0000658 assert(!Identifier.getRawIdentifier().empty() && "No raw identifier data!");
Mike Stump11289f42009-09-09 15:08:12 +0000659
Chris Lattnercefc7682006-07-08 08:28:12 +0000660 // Look up this token, see if it is a macro, or if it is a language keyword.
661 IdentifierInfo *II;
Jordan Rose7f43ddd2013-01-24 20:50:46 +0000662 if (!Identifier.needsCleaning() && !Identifier.hasUCN()) {
Chris Lattnercefc7682006-07-08 08:28:12 +0000663 // No cleaning needed, just use the characters from the lexed buffer.
Alp Toker2d57cea2014-05-17 04:53:25 +0000664 II = getIdentifierInfo(Identifier.getRawIdentifier());
Chris Lattnercefc7682006-07-08 08:28:12 +0000665 } else {
666 // Cleaning needed, alloca a buffer, clean into it, then use the buffer.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +0000667 SmallString<64> IdentifierBuffer;
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000668 StringRef CleanedStr = getSpelling(Identifier, IdentifierBuffer);
Jordan Rose7f43ddd2013-01-24 20:50:46 +0000669
670 if (Identifier.hasUCN()) {
671 SmallString<64> UCNIdentifierBuffer;
672 expandUCNs(UCNIdentifierBuffer, CleanedStr);
673 II = getIdentifierInfo(UCNIdentifierBuffer);
674 } else {
675 II = getIdentifierInfo(CleanedStr);
676 }
Chris Lattnercefc7682006-07-08 08:28:12 +0000677 }
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +0000678
679 // Update the token info (identifier info and appropriate token kind).
Chris Lattner8c204872006-10-14 05:19:21 +0000680 Identifier.setIdentifierInfo(II);
Erich Keane33c3d8a2017-06-09 16:29:35 +0000681 if (getLangOpts().MSVCCompat && II->isCPlusPlusOperatorKeyword() &&
682 getSourceManager().isInSystemHeader(Identifier.getLocation()))
Eugene Zelenko5dc60fe2017-12-04 23:16:21 +0000683 Identifier.setKind(tok::identifier);
Erich Keane33c3d8a2017-06-09 16:29:35 +0000684 else
685 Identifier.setKind(II->getTokenID());
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +0000686
Chris Lattnercefc7682006-07-08 08:28:12 +0000687 return II;
688}
689
John Wiegley1c0675e2011-04-28 01:08:34 +0000690void Preprocessor::SetPoisonReason(IdentifierInfo *II, unsigned DiagID) {
691 PoisonReasons[II] = DiagID;
692}
693
694void Preprocessor::PoisonSEHIdentifiers(bool Poison) {
695 assert(Ident__exception_code && Ident__exception_info);
696 assert(Ident___exception_code && Ident___exception_info);
697 Ident__exception_code->setIsPoisoned(Poison);
698 Ident___exception_code->setIsPoisoned(Poison);
699 Ident_GetExceptionCode->setIsPoisoned(Poison);
700 Ident__exception_info->setIsPoisoned(Poison);
701 Ident___exception_info->setIsPoisoned(Poison);
702 Ident_GetExceptionInfo->setIsPoisoned(Poison);
703 Ident__abnormal_termination->setIsPoisoned(Poison);
704 Ident___abnormal_termination->setIsPoisoned(Poison);
705 Ident_AbnormalTermination->setIsPoisoned(Poison);
706}
707
708void Preprocessor::HandlePoisonedIdentifier(Token & Identifier) {
709 assert(Identifier.getIdentifierInfo() &&
710 "Can't handle identifiers without identifier info!");
711 llvm::DenseMap<IdentifierInfo*,unsigned>::const_iterator it =
712 PoisonReasons.find(Identifier.getIdentifierInfo());
713 if(it == PoisonReasons.end())
714 Diag(Identifier, diag::err_pp_used_poisoned_id);
715 else
716 Diag(Identifier,it->second) << Identifier.getIdentifierInfo();
717}
Chris Lattnercefc7682006-07-08 08:28:12 +0000718
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000719/// Returns a diagnostic message kind for reporting a future keyword as
Richard Smith31d51842015-05-14 04:00:59 +0000720/// appropriate for the identifier and specified language.
721static diag::kind getFutureCompatDiagKind(const IdentifierInfo &II,
722 const LangOptions &LangOpts) {
723 assert(II.isFutureCompatKeyword() && "diagnostic should not be needed");
724
725 if (LangOpts.CPlusPlus)
726 return llvm::StringSwitch<diag::kind>(II.getName())
727#define CXX11_KEYWORD(NAME, FLAGS) \
728 .Case(#NAME, diag::warn_cxx11_keyword)
Richard Smith6c74e322017-08-13 21:32:33 +0000729#define CXX2A_KEYWORD(NAME, FLAGS) \
730 .Case(#NAME, diag::warn_cxx2a_keyword)
Richard Smith31d51842015-05-14 04:00:59 +0000731#include "clang/Basic/TokenKinds.def"
732 ;
733
734 llvm_unreachable(
735 "Keyword not known to come from a newer Standard or proposed Standard");
736}
737
Richard Smith3dba7eb2016-08-18 01:16:55 +0000738void Preprocessor::updateOutOfDateIdentifier(IdentifierInfo &II) const {
739 assert(II.isOutOfDate() && "not out of date");
740 getExternalSource()->updateOutOfDateIdentifier(II);
741}
742
Chris Lattner677757a2006-06-28 05:26:32 +0000743/// HandleIdentifier - This callback is invoked when the lexer reads an
744/// identifier. This callback looks up the identifier in the map and/or
745/// potentially macro expands it or turns it into a named token (like 'for').
Chris Lattnerad89ec02009-01-21 07:43:11 +0000746///
747/// Note that callers of this method are guarded by checking the
748/// IdentifierInfo's 'isHandleIdentifierCase' bit. If this method changes, the
749/// IdentifierInfo methods that compute these properties will need to change to
750/// match.
Eli Friedman0834a4b2013-09-19 00:41:32 +0000751bool Preprocessor::HandleIdentifier(Token &Identifier) {
Chris Lattner0f1f5052006-07-20 04:16:23 +0000752 assert(Identifier.getIdentifierInfo() &&
753 "Can't handle identifiers without identifier info!");
Mike Stump11289f42009-09-09 15:08:12 +0000754
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000755 IdentifierInfo &II = *Identifier.getIdentifierInfo();
Chris Lattner677757a2006-06-28 05:26:32 +0000756
Douglas Gregor935bc7a22011-10-27 09:33:13 +0000757 // If the information about this identifier is out of date, update it from
758 // the external source.
Douglas Gregor3f568c12012-06-29 18:27:59 +0000759 // We have to treat __VA_ARGS__ in a special way, since it gets
760 // serialized with isPoisoned = true, but our preprocessor may have
761 // unpoisoned it if we're defining a C99 macro.
Douglas Gregor935bc7a22011-10-27 09:33:13 +0000762 if (II.isOutOfDate()) {
Douglas Gregor3f568c12012-06-29 18:27:59 +0000763 bool CurrentIsPoisoned = false;
Faisal Vali18268422017-10-15 01:26:26 +0000764 const bool IsSpecialVariadicMacro =
765 &II == Ident__VA_ARGS__ || &II == Ident__VA_OPT__;
766 if (IsSpecialVariadicMacro)
767 CurrentIsPoisoned = II.isPoisoned();
Douglas Gregor3f568c12012-06-29 18:27:59 +0000768
Richard Smith3dba7eb2016-08-18 01:16:55 +0000769 updateOutOfDateIdentifier(II);
Douglas Gregor935bc7a22011-10-27 09:33:13 +0000770 Identifier.setKind(II.getTokenID());
Douglas Gregor3f568c12012-06-29 18:27:59 +0000771
Faisal Vali18268422017-10-15 01:26:26 +0000772 if (IsSpecialVariadicMacro)
Douglas Gregor3f568c12012-06-29 18:27:59 +0000773 II.setIsPoisoned(CurrentIsPoisoned);
Douglas Gregor935bc7a22011-10-27 09:33:13 +0000774 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000775
Chris Lattner677757a2006-06-28 05:26:32 +0000776 // If this identifier was poisoned, and if it was not produced from a macro
777 // expansion, emit an error.
Ted Kremeneka2c3c8d2008-11-19 22:43:49 +0000778 if (II.isPoisoned() && CurPPLexer) {
John Wiegley1c0675e2011-04-28 01:08:34 +0000779 HandlePoisonedIdentifier(Identifier);
Chris Lattner8ff71992006-07-06 05:17:39 +0000780 }
Mike Stump11289f42009-09-09 15:08:12 +0000781
Chris Lattner78186052006-07-09 00:45:31 +0000782 // If this is a macro to be expanded, do it.
Richard Smith20e883e2015-04-29 23:20:19 +0000783 if (MacroDefinition MD = getMacroDefinition(&II)) {
784 auto *MI = MD.getMacroInfo();
Richard Smithf5ec2ac2015-04-29 23:40:48 +0000785 assert(MI && "macro definition with no macro info?");
Abramo Bagnara123bec82012-01-01 22:01:04 +0000786 if (!DisableMacroExpansion) {
Richard Smith181879c2012-12-12 02:46:14 +0000787 if (!Identifier.isExpandDisabled() && MI->isEnabled()) {
Eli Friedman0834a4b2013-09-19 00:41:32 +0000788 // C99 6.10.3p10: If the preprocessing token immediately after the
789 // macro name isn't a '(', this macro should not be expanded.
790 if (!MI->isFunctionLike() || isNextPPTokenLParen())
791 return HandleMacroExpandedIdentifier(Identifier, MD);
Chris Lattner6e4bf522006-07-27 06:59:25 +0000792 } else {
793 // C99 6.10.3.4p2 says that a disabled macro may never again be
794 // expanded, even if it's in a context where it could be expanded in the
795 // future.
Chris Lattner146762e2007-07-20 16:59:19 +0000796 Identifier.setFlag(Token::DisableExpand);
Richard Smith181879c2012-12-12 02:46:14 +0000797 if (MI->isObjectLike() || isNextPPTokenLParen())
798 Diag(Identifier, diag::pp_disabled_macro_expansion);
Chris Lattner6e4bf522006-07-27 06:59:25 +0000799 }
800 }
Chris Lattner063400e2006-10-14 19:54:15 +0000801 }
Chris Lattner677757a2006-06-28 05:26:32 +0000802
Richard Smith31d51842015-05-14 04:00:59 +0000803 // If this identifier is a keyword in a newer Standard or proposed Standard,
804 // produce a warning. Don't warn if we're not considering macro expansion,
805 // since this identifier might be the name of a macro.
Richard Smith4dd85d62011-10-11 19:57:52 +0000806 // FIXME: This warning is disabled in cases where it shouldn't be, like
807 // "#define constexpr constexpr", "int constexpr;"
Richard Smith31d51842015-05-14 04:00:59 +0000808 if (II.isFutureCompatKeyword() && !DisableMacroExpansion) {
809 Diag(Identifier, getFutureCompatDiagKind(II, getLangOpts()))
810 << II.getName();
Richard Smith4dd85d62011-10-11 19:57:52 +0000811 // Don't diagnose this keyword again in this translation unit.
Richard Smith31d51842015-05-14 04:00:59 +0000812 II.setIsFutureCompatKeyword(false);
Richard Smith4dd85d62011-10-11 19:57:52 +0000813 }
814
Chris Lattner677757a2006-06-28 05:26:32 +0000815 // If this is an extension token, diagnose its use.
Steve Naroffc84e8b72008-09-02 18:50:17 +0000816 // We avoid diagnosing tokens that originate from macro definitions.
Eli Friedman6bba2ad2009-04-28 03:59:15 +0000817 // FIXME: This warning is disabled in cases where it shouldn't be,
818 // like "#define TY typeof", "TY(1) x".
819 if (II.isExtensionToken() && !DisableMacroExpansion)
Chris Lattner53621a52007-06-13 20:44:40 +0000820 Diag(Identifier, diag::ext_token_used);
Fangrui Song6907ce22018-07-30 19:24:48 +0000821
Douglas Gregor594b8c92013-11-07 22:55:02 +0000822 // If this is the 'import' contextual keyword following an '@', note
Ted Kremenekc1e4dd02012-03-01 22:07:04 +0000823 // that the next token indicates a module name.
Douglas Gregor8d76cca2012-01-04 06:20:15 +0000824 //
Douglas Gregorc50d4922012-12-11 22:11:52 +0000825 // Note that we do not treat 'import' as a contextual
Ted Kremenekc1e4dd02012-03-01 22:07:04 +0000826 // keyword when we're in a caching lexer, because caching lexers only get
827 // used in contexts where import declarations are disallowed.
Richard Smith49cc1cc2016-08-18 21:59:42 +0000828 //
829 // Likewise if this is the C++ Modules TS import keyword.
830 if (((LastTokenWasAt && II.isModulesImport()) ||
831 Identifier.is(tok::kw_import)) &&
832 !InMacroArgs && !DisableMacroExpansion &&
833 (getLangOpts().Modules || getLangOpts().DebuggerSupport) &&
Douglas Gregor594b8c92013-11-07 22:55:02 +0000834 CurLexerKind != CLK_CachingLexer) {
Douglas Gregoraf5c4842011-09-07 23:11:54 +0000835 ModuleImportLoc = Identifier.getLocation();
Douglas Gregor1805b8a2011-11-30 04:26:53 +0000836 ModuleImportPath.clear();
837 ModuleImportExpectsIdentifier = true;
Douglas Gregoraf5c4842011-09-07 23:11:54 +0000838 CurLexerKind = CLK_LexAfterModuleImport;
839 }
Eli Friedman0834a4b2013-09-19 00:41:32 +0000840 return true;
Douglas Gregor08142532011-08-26 23:56:07 +0000841}
842
Eli Friedman0834a4b2013-09-19 00:41:32 +0000843void Preprocessor::Lex(Token &Result) {
Yaron Keren716f3a62015-09-29 16:51:08 +0000844 // We loop here until a lex function returns a token; this avoids recursion.
Eli Friedman0834a4b2013-09-19 00:41:32 +0000845 bool ReturnedToken;
846 do {
847 switch (CurLexerKind) {
848 case CLK_Lexer:
849 ReturnedToken = CurLexer->Lex(Result);
850 break;
851 case CLK_PTHLexer:
852 ReturnedToken = CurPTHLexer->Lex(Result);
853 break;
854 case CLK_TokenLexer:
855 ReturnedToken = CurTokenLexer->Lex(Result);
856 break;
857 case CLK_CachingLexer:
858 CachingLex(Result);
859 ReturnedToken = true;
860 break;
861 case CLK_LexAfterModuleImport:
862 LexAfterModuleImport(Result);
863 ReturnedToken = true;
864 break;
865 }
866 } while (!ReturnedToken);
Douglas Gregor594b8c92013-11-07 22:55:02 +0000867
Ilya Biryukovb8f231a2018-01-22 17:18:28 +0000868 if (Result.is(tok::code_completion) && Result.getIdentifierInfo()) {
869 // Remember the identifier before code completion token.
Vassil Vassilev644ea612016-07-27 14:56:59 +0000870 setCodeCompletionIdentifierInfo(Result.getIdentifierInfo());
Kadir Cetinkaya9b9c2742018-08-13 08:13:35 +0000871 setCodeCompletionTokenRange(Result.getLocation(), Result.getEndLoc());
Ilya Biryukovb8f231a2018-01-22 17:18:28 +0000872 // Set IdenfitierInfo to null to avoid confusing code that handles both
873 // identifiers and completion tokens.
874 Result.setIdentifierInfo(nullptr);
875 }
Vassil Vassilev644ea612016-07-27 14:56:59 +0000876
Douglas Gregor594b8c92013-11-07 22:55:02 +0000877 LastTokenWasAt = Result.is(tok::at);
Eli Friedman0834a4b2013-09-19 00:41:32 +0000878}
879
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000880/// Lex a token following the 'import' contextual keyword.
Douglas Gregor22d09742012-01-03 18:04:46 +0000881///
Douglas Gregoraf5c4842011-09-07 23:11:54 +0000882void Preprocessor::LexAfterModuleImport(Token &Result) {
883 // Figure out what kind of lexer we actually have.
Douglas Gregor8d76cca2012-01-04 06:20:15 +0000884 recomputeCurLexerKind();
Fangrui Song6907ce22018-07-30 19:24:48 +0000885
Douglas Gregoraf5c4842011-09-07 23:11:54 +0000886 // Lex the next token.
887 Lex(Result);
888
Fangrui Song6907ce22018-07-30 19:24:48 +0000889 // The token sequence
Douglas Gregor08142532011-08-26 23:56:07 +0000890 //
Douglas Gregor22d09742012-01-03 18:04:46 +0000891 // import identifier (. identifier)*
892 //
Fangrui Song6907ce22018-07-30 19:24:48 +0000893 // indicates a module import directive. We already saw the 'import'
Douglas Gregorda82e702012-01-03 19:32:59 +0000894 // contextual keyword, so now we're looking for the identifiers.
Douglas Gregor1805b8a2011-11-30 04:26:53 +0000895 if (ModuleImportExpectsIdentifier && Result.getKind() == tok::identifier) {
896 // We expected to see an identifier here, and we did; continue handling
897 // identifiers.
898 ModuleImportPath.push_back(std::make_pair(Result.getIdentifierInfo(),
899 Result.getLocation()));
900 ModuleImportExpectsIdentifier = false;
901 CurLexerKind = CLK_LexAfterModuleImport;
Douglas Gregor08142532011-08-26 23:56:07 +0000902 return;
Douglas Gregor1805b8a2011-11-30 04:26:53 +0000903 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000904
Douglas Gregor1805b8a2011-11-30 04:26:53 +0000905 // If we're expecting a '.' or a ';', and we got a '.', then wait until we
Richard Smith49cc1cc2016-08-18 21:59:42 +0000906 // see the next identifier. (We can also see a '[[' that begins an
907 // attribute-specifier-seq here under the C++ Modules TS.)
Douglas Gregor1805b8a2011-11-30 04:26:53 +0000908 if (!ModuleImportExpectsIdentifier && Result.getKind() == tok::period) {
909 ModuleImportExpectsIdentifier = true;
910 CurLexerKind = CLK_LexAfterModuleImport;
911 return;
912 }
913
914 // If we have a non-empty module path, load the named module.
Sean Callanan87596492014-12-09 23:47:56 +0000915 if (!ModuleImportPath.empty()) {
Richard Smithbbcc9f02016-08-26 00:14:38 +0000916 // Under the Modules TS, the dot is just part of the module name, and not
917 // a real hierarachy separator. Flatten such module names now.
918 //
919 // FIXME: Is this the right level to be performing this transformation?
920 std::string FlatModuleName;
921 if (getLangOpts().ModulesTS) {
922 for (auto &Piece : ModuleImportPath) {
923 if (!FlatModuleName.empty())
924 FlatModuleName += ".";
925 FlatModuleName += Piece.first->getName();
926 }
927 SourceLocation FirstPathLoc = ModuleImportPath[0].second;
928 ModuleImportPath.clear();
929 ModuleImportPath.push_back(
930 std::make_pair(getIdentifierInfo(FlatModuleName), FirstPathLoc));
931 }
932
Sean Callanan87596492014-12-09 23:47:56 +0000933 Module *Imported = nullptr;
Richard Smith753e0072015-04-27 23:21:38 +0000934 if (getLangOpts().Modules) {
Sean Callanan87596492014-12-09 23:47:56 +0000935 Imported = TheModuleLoader.loadModule(ModuleImportLoc,
936 ModuleImportPath,
Richard Smith10434f32015-05-02 02:08:26 +0000937 Module::Hidden,
Sean Callanan87596492014-12-09 23:47:56 +0000938 /*IsIncludeDirective=*/false);
Richard Smitha7e2cc62015-05-01 01:53:09 +0000939 if (Imported)
940 makeModuleVisible(Imported, ModuleImportLoc);
Richard Smith753e0072015-04-27 23:21:38 +0000941 }
Sean Callanan87596492014-12-09 23:47:56 +0000942 if (Callbacks && (getLangOpts().Modules || getLangOpts().DebuggerSupport))
Argyrios Kyrtzidis19d78b72012-09-29 01:06:10 +0000943 Callbacks->moduleImport(ModuleImportLoc, ModuleImportPath, Imported);
944 }
Chris Lattner677757a2006-06-28 05:26:32 +0000945}
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000946
Richard Smitha7e2cc62015-05-01 01:53:09 +0000947void Preprocessor::makeModuleVisible(Module *M, SourceLocation Loc) {
Richard Smith04765ae2015-05-21 01:20:10 +0000948 CurSubmoduleState->VisibleModules.setVisible(
Richard Smitha7e2cc62015-05-01 01:53:09 +0000949 M, Loc, [](Module *) {},
950 [&](ArrayRef<Module *> Path, Module *Conflict, StringRef Message) {
951 // FIXME: Include the path in the diagnostic.
952 // FIXME: Include the import location for the conflicting module.
953 Diag(ModuleImportLoc, diag::warn_module_conflict)
954 << Path[0]->getFullModuleName()
955 << Conflict->getFullModuleName()
956 << Message;
957 });
958
959 // Add this module to the imports list of the currently-built submodule.
Richard Smithdbbc5232015-05-14 02:25:44 +0000960 if (!BuildingSubmoduleStack.empty() && M != BuildingSubmoduleStack.back().M)
Richard Smith38477db2015-05-02 00:45:56 +0000961 BuildingSubmoduleStack.back().M->Imports.insert(M);
Richard Smitha7e2cc62015-05-01 01:53:09 +0000962}
963
Andy Gibbs58905d22012-11-17 19:15:38 +0000964bool Preprocessor::FinishLexStringLiteral(Token &Result, std::string &String,
Andy Gibbsa8df57a2012-11-17 19:16:52 +0000965 const char *DiagnosticTag,
Andy Gibbs58905d22012-11-17 19:15:38 +0000966 bool AllowMacroExpansion) {
967 // We need at least one string literal.
968 if (Result.isNot(tok::string_literal)) {
Andy Gibbsa8df57a2012-11-17 19:16:52 +0000969 Diag(Result, diag::err_expected_string_literal)
970 << /*Source='in...'*/0 << DiagnosticTag;
Andy Gibbs58905d22012-11-17 19:15:38 +0000971 return false;
972 }
973
974 // Lex string literal tokens, optionally with macro expansion.
975 SmallVector<Token, 4> StrToks;
976 do {
977 StrToks.push_back(Result);
978
979 if (Result.hasUDSuffix())
980 Diag(Result, diag::err_invalid_string_udl);
981
982 if (AllowMacroExpansion)
983 Lex(Result);
984 else
985 LexUnexpandedToken(Result);
986 } while (Result.is(tok::string_literal));
987
988 // Concatenate and parse the strings.
Craig Topper9d5583e2014-06-26 04:58:39 +0000989 StringLiteralParser Literal(StrToks, *this);
Andy Gibbs58905d22012-11-17 19:15:38 +0000990 assert(Literal.isAscii() && "Didn't allow wide strings in");
991
992 if (Literal.hadError)
993 return false;
994
995 if (Literal.Pascal) {
Andy Gibbsa8df57a2012-11-17 19:16:52 +0000996 Diag(StrToks[0].getLocation(), diag::err_expected_string_literal)
997 << /*Source='in...'*/0 << DiagnosticTag;
Andy Gibbs58905d22012-11-17 19:15:38 +0000998 return false;
999 }
1000
1001 String = Literal.GetString();
1002 return true;
1003}
1004
Reid Klecknerc0dca6d2014-02-12 23:50:26 +00001005bool Preprocessor::parseSimpleIntegerLiteral(Token &Tok, uint64_t &Value) {
1006 assert(Tok.is(tok::numeric_constant));
1007 SmallString<8> IntegerBuffer;
1008 bool NumberInvalid = false;
1009 StringRef Spelling = getSpelling(Tok, IntegerBuffer, &NumberInvalid);
1010 if (NumberInvalid)
1011 return false;
1012 NumericLiteralParser Literal(Spelling, Tok.getLocation(), *this);
1013 if (Literal.hadError || !Literal.isIntegerLiteral() || Literal.hasUDSuffix())
1014 return false;
1015 llvm::APInt APVal(64, 0);
1016 if (Literal.GetIntegerValue(APVal))
1017 return false;
1018 Lex(Tok);
1019 Value = APVal.getLimitedValue();
1020 return true;
1021}
1022
Dmitri Gribenkoaab83832012-06-20 00:34:58 +00001023void Preprocessor::addCommentHandler(CommentHandler *Handler) {
Douglas Gregorc6d5edd2009-07-02 17:08:52 +00001024 assert(Handler && "NULL comment handler");
1025 assert(std::find(CommentHandlers.begin(), CommentHandlers.end(), Handler) ==
1026 CommentHandlers.end() && "Comment handler already registered");
1027 CommentHandlers.push_back(Handler);
1028}
1029
Dmitri Gribenkoaab83832012-06-20 00:34:58 +00001030void Preprocessor::removeCommentHandler(CommentHandler *Handler) {
Eugene Zelenko5dc60fe2017-12-04 23:16:21 +00001031 std::vector<CommentHandler *>::iterator Pos =
1032 std::find(CommentHandlers.begin(), CommentHandlers.end(), Handler);
Douglas Gregorc6d5edd2009-07-02 17:08:52 +00001033 assert(Pos != CommentHandlers.end() && "Comment handler not registered");
1034 CommentHandlers.erase(Pos);
1035}
1036
Chris Lattner87d02082010-01-18 22:35:47 +00001037bool Preprocessor::HandleComment(Token &result, SourceRange Comment) {
1038 bool AnyPendingTokens = false;
Douglas Gregorc6d5edd2009-07-02 17:08:52 +00001039 for (std::vector<CommentHandler *>::iterator H = CommentHandlers.begin(),
1040 HEnd = CommentHandlers.end();
Chris Lattner87d02082010-01-18 22:35:47 +00001041 H != HEnd; ++H) {
1042 if ((*H)->HandleComment(*this, Comment))
1043 AnyPendingTokens = true;
1044 }
1045 if (!AnyPendingTokens || getCommentRetentionState())
1046 return false;
1047 Lex(result);
1048 return true;
Douglas Gregorc6d5edd2009-07-02 17:08:52 +00001049}
1050
Eugene Zelenko5dc60fe2017-12-04 23:16:21 +00001051ModuleLoader::~ModuleLoader() = default;
Douglas Gregor08142532011-08-26 23:56:07 +00001052
Eugene Zelenko5dc60fe2017-12-04 23:16:21 +00001053CommentHandler::~CommentHandler() = default;
Douglas Gregor7f6d60d2010-03-19 16:15:56 +00001054
Eugene Zelenko5dc60fe2017-12-04 23:16:21 +00001055CodeCompletionHandler::~CodeCompletionHandler() = default;
Douglas Gregor3a7ad252010-08-24 19:08:16 +00001056
Argyrios Kyrtzidisf3d587e2012-12-04 07:27:05 +00001057void Preprocessor::createPreprocessingRecord() {
Douglas Gregor7f6d60d2010-03-19 16:15:56 +00001058 if (Record)
1059 return;
Fangrui Song6907ce22018-07-30 19:24:48 +00001060
Argyrios Kyrtzidisf3d587e2012-12-04 07:27:05 +00001061 Record = new PreprocessingRecord(getSourceManager());
Craig Topperb8a70532014-09-10 04:53:53 +00001062 addPPCallbacks(std::unique_ptr<PPCallbacks>(Record));
Douglas Gregor7f6d60d2010-03-19 16:15:56 +00001063}