blob: 656e387cc5c8128a07eac128467f728b5280b2e1 [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"
Chris Lattnerb8761832006-06-24 21:31:03 +000047#include "clang/Lex/Pragma.h"
Douglas Gregor7f6d60d2010-03-19 16:15:56 +000048#include "clang/Lex/PreprocessingRecord.h"
Eugene Zelenko5dc60fe2017-12-04 23:16:21 +000049#include "clang/Lex/PreprocessorLexer.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000050#include "clang/Lex/PreprocessorOptions.h"
Chris Lattner0b8cfc22006-06-28 06:49:17 +000051#include "clang/Lex/ScratchBuffer.h"
Eugene Zelenko5dc60fe2017-12-04 23:16:21 +000052#include "clang/Lex/Token.h"
53#include "clang/Lex/TokenLexer.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000054#include "llvm/ADT/APInt.h"
Eugene Zelenko5dc60fe2017-12-04 23:16:21 +000055#include "llvm/ADT/ArrayRef.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000056#include "llvm/ADT/DenseMap.h"
Chandler Carruth5553d0d2014-01-07 11:51:46 +000057#include "llvm/ADT/SmallString.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000058#include "llvm/ADT/SmallVector.h"
59#include "llvm/ADT/STLExtras.h"
60#include "llvm/ADT/StringRef.h"
Mehdi Amini9670f842016-07-18 19:02:11 +000061#include "llvm/ADT/StringSwitch.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000062#include "llvm/Support/Capacity.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000063#include "llvm/Support/ErrorHandling.h"
Chris Lattner8a7003c2007-07-16 06:48:38 +000064#include "llvm/Support/MemoryBuffer.h"
Benjamin Kramer89b422c2009-08-23 12:08:50 +000065#include "llvm/Support/raw_ostream.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000066#include <algorithm>
67#include <cassert>
68#include <memory>
69#include <string>
Benjamin Kramercfeacf52016-05-27 14:27:13 +000070#include <utility>
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000071#include <vector>
72
Chris Lattner22eb9722006-06-18 05:43:12 +000073using namespace clang;
74
John Brawn4d79ec72016-08-05 11:01:08 +000075LLVM_INSTANTIATE_REGISTRY(PragmaHandlerRegistry)
NAKAMURA Takumicacd94e2016-04-04 15:30:44 +000076
Eugene Zelenko5dc60fe2017-12-04 23:16:21 +000077ExternalPreprocessorSource::~ExternalPreprocessorSource() = default;
Chris Lattner22eb9722006-06-18 05:43:12 +000078
David Blaikiee3041682017-01-05 19:11:36 +000079Preprocessor::Preprocessor(std::shared_ptr<PreprocessorOptions> PPOpts,
Douglas Gregor1452ff12012-10-24 17:46:57 +000080 DiagnosticsEngine &diags, LangOptions &opts,
Duncan P. N. Exon Smith030d7d62017-03-20 17:58:26 +000081 SourceManager &SM, MemoryBufferCache &PCMCache,
82 HeaderSearch &Headers, ModuleLoader &TheModuleLoader,
David Blaikie687cd952013-01-16 23:13:36 +000083 IdentifierInfoLookup *IILookup, bool OwnsHeaders,
Alp Toker1ae02f62014-05-02 03:43:30 +000084 TranslationUnitKind TUKind)
Eugene Zelenko5dc60fe2017-12-04 23:16:21 +000085 : PPOpts(std::move(PPOpts)), Diags(&diags), LangOpts(opts),
Aaron Ballmand742dc22018-04-16 21:07:08 +000086 FileMgr(Headers.getFileMgr()), SourceMgr(SM), PCMCache(PCMCache),
87 ScratchBuf(new ScratchBuffer(SourceMgr)), HeaderInfo(Headers),
88 TheModuleLoader(TheModuleLoader), ExternalSource(nullptr),
89 // As the language options may have not been loaded yet (when
90 // deserializing an ASTUnit), adding keywords to the identifier table is
91 // deferred to Preprocessor::Initialize().
92 Identifiers(IILookup), PragmaHandlers(new PragmaNamespace(StringRef())),
93 TUKind(TUKind), SkipMainFilePreamble(0, true),
Eugene Zelenko5dc60fe2017-12-04 23:16:21 +000094 CurSubmoduleState(&NullSubmoduleState) {
Daniel Dunbar0c6c9302009-11-11 21:44:21 +000095 OwnsHeaderSearch = OwnsHeaders;
Fangrui Song6907ce22018-07-30 19:24:48 +000096
Douglas Gregor83297df2011-09-01 23:39:15 +000097 // Default to discarding comments.
98 KeepComments = false;
99 KeepMacroComments = false;
100 SuppressIncludeNotFoundError = false;
Fangrui Song6907ce22018-07-30 19:24:48 +0000101
Douglas Gregor83297df2011-09-01 23:39:15 +0000102 // Macro expansion is enabled.
103 DisableMacroExpansion = false;
David Blaikied5321242012-06-06 18:52:13 +0000104 MacroExpansionInDirectivesOverride = false;
Douglas Gregor83297df2011-09-01 23:39:15 +0000105 InMacroArgs = false;
Argyrios Kyrtzidisf1b64c62012-04-03 16:47:40 +0000106 InMacroArgPreExpansion = false;
Douglas Gregor83297df2011-09-01 23:39:15 +0000107 NumCachedTokenLexers = 0;
Jordan Rosede1a2922012-06-08 18:06:21 +0000108 PragmasEnabled = true;
Eric Christopher5e4696d2013-01-16 20:09:36 +0000109 ParsingIfOrElifDirective = false;
Jordan Rose324ec422013-01-31 19:26:01 +0000110 PreprocessedOutput = false;
Jordan Rosede1a2922012-06-08 18:06:21 +0000111
Douglas Gregor83297df2011-09-01 23:39:15 +0000112 // We haven't read anything from the external source.
113 ReadMacrosFromExternalSource = false;
Faisal Vali18268422017-10-15 01:26:26 +0000114
115 // "Poison" __VA_ARGS__, __VA_OPT__ which can only appear in the expansion of
116 // a macro. They get unpoisoned where it is allowed.
Douglas Gregor83297df2011-09-01 23:39:15 +0000117 (Ident__VA_ARGS__ = getIdentifierInfo("__VA_ARGS__"))->setIsPoisoned();
118 SetPoisonReason(Ident__VA_ARGS__,diag::ext_pp_bad_vaargs_use);
Faisal Vali18268422017-10-15 01:26:26 +0000119 if (getLangOpts().CPlusPlus2a) {
120 (Ident__VA_OPT__ = getIdentifierInfo("__VA_OPT__"))->setIsPoisoned();
121 SetPoisonReason(Ident__VA_OPT__,diag::ext_pp_bad_vaopt_use);
122 } else {
123 Ident__VA_OPT__ = nullptr;
124 }
125
Douglas Gregor83297df2011-09-01 23:39:15 +0000126 // Initialize the pragma handlers.
Douglas Gregor83297df2011-09-01 23:39:15 +0000127 RegisterBuiltinPragmas();
Fangrui Song6907ce22018-07-30 19:24:48 +0000128
Douglas Gregor83297df2011-09-01 23:39:15 +0000129 // Initialize builtin macros like __LINE__ and friends.
130 RegisterBuiltinMacros();
Fangrui Song6907ce22018-07-30 19:24:48 +0000131
David Blaikiebbafb8a2012-03-11 07:00:24 +0000132 if(LangOpts.Borland) {
Douglas Gregor83297df2011-09-01 23:39:15 +0000133 Ident__exception_info = getIdentifierInfo("_exception_info");
134 Ident___exception_info = getIdentifierInfo("__exception_info");
135 Ident_GetExceptionInfo = getIdentifierInfo("GetExceptionInformation");
136 Ident__exception_code = getIdentifierInfo("_exception_code");
137 Ident___exception_code = getIdentifierInfo("__exception_code");
138 Ident_GetExceptionCode = getIdentifierInfo("GetExceptionCode");
139 Ident__abnormal_termination = getIdentifierInfo("_abnormal_termination");
140 Ident___abnormal_termination = getIdentifierInfo("__abnormal_termination");
141 Ident_AbnormalTermination = getIdentifierInfo("AbnormalTermination");
142 } else {
Craig Topperd2d442c2014-05-17 23:10:59 +0000143 Ident__exception_info = Ident__exception_code = nullptr;
144 Ident__abnormal_termination = Ident___exception_info = nullptr;
145 Ident___exception_code = Ident___abnormal_termination = nullptr;
146 Ident_GetExceptionInfo = Ident_GetExceptionCode = nullptr;
147 Ident_AbnormalTermination = nullptr;
Douglas Gregor89929282012-01-30 06:01:29 +0000148 }
Erik Verbruggenb34c79f2017-05-30 11:54:55 +0000149
Mike Rice58df1af2018-09-11 17:10:44 +0000150 // If using a PCH where a #pragma hdrstop is expected, start skipping tokens.
151 if (usingPCHWithPragmaHdrStop())
152 SkippingUntilPragmaHdrStop = true;
153
Erich Keane76675de2018-07-05 17:22:13 +0000154 // If using a PCH with a through header, start skipping tokens.
155 if (!this->PPOpts->PCHThroughHeader.empty() &&
156 !this->PPOpts->ImplicitPCHInclude.empty())
157 SkippingUntilPCHThroughHeader = true;
158
Erik Verbruggenb34c79f2017-05-30 11:54:55 +0000159 if (this->PPOpts->GeneratePreamble)
160 PreambleConditionalStack.startRecording();
Argyrios Kyrtzidis3c9aaf12012-06-02 18:08:09 +0000161}
162
163Preprocessor::~Preprocessor() {
164 assert(BacktrackPositions.empty() && "EnableBacktrack/Backtrack imbalance!");
165
Benjamin Kramer329c5962014-03-15 16:40:40 +0000166 IncludeMacroStack.clear();
Argyrios Kyrtzidis3c9aaf12012-06-02 18:08:09 +0000167
Richard Smith73a29662014-07-24 03:25:00 +0000168 // Destroy any macro definitions.
169 while (MacroInfoChain *I = MIChainHead) {
170 MIChainHead = I->Next;
171 I->~MacroInfoChain();
172 }
Argyrios Kyrtzidis3c9aaf12012-06-02 18:08:09 +0000173
174 // Free any cached macro expanders.
Nico Weber5f5b9412014-05-09 18:09:42 +0000175 // This populates MacroArgCache, so all TokenLexers need to be destroyed
176 // before the code below that frees up the MacroArgCache list.
David Blaikie6d5038c2014-08-29 19:36:52 +0000177 std::fill(TokenLexerCache, TokenLexerCache + NumCachedTokenLexers, nullptr);
Nico Weber5f5b9412014-05-09 18:09:42 +0000178 CurTokenLexer.reset();
Argyrios Kyrtzidis3c9aaf12012-06-02 18:08:09 +0000179
180 // Free any cached MacroArgs.
Nico Weber5f5b9412014-05-09 18:09:42 +0000181 for (MacroArgs *ArgList = MacroArgCache; ArgList;)
Argyrios Kyrtzidis3c9aaf12012-06-02 18:08:09 +0000182 ArgList = ArgList->deallocate();
183
Argyrios Kyrtzidis3c9aaf12012-06-02 18:08:09 +0000184 // Delete the header search info, if we own it.
185 if (OwnsHeaderSearch)
186 delete &HeaderInfo;
Argyrios Kyrtzidis3c9aaf12012-06-02 18:08:09 +0000187}
188
Artem Belevichb5bc9232015-09-22 17:23:22 +0000189void Preprocessor::Initialize(const TargetInfo &Target,
190 const TargetInfo *AuxTarget) {
Argyrios Kyrtzidis3c9aaf12012-06-02 18:08:09 +0000191 assert((!this->Target || this->Target == &Target) &&
192 "Invalid override of target information");
193 this->Target = &Target;
Artem Belevichb5bc9232015-09-22 17:23:22 +0000194
195 assert((!this->AuxTarget || this->AuxTarget == AuxTarget) &&
196 "Invalid override of aux target information.");
197 this->AuxTarget = AuxTarget;
198
Argyrios Kyrtzidis3c9aaf12012-06-02 18:08:09 +0000199 // Initialize information about built-ins.
Artem Belevichb5bc9232015-09-22 17:23:22 +0000200 BuiltinInfo.InitializeTarget(Target, AuxTarget);
Douglas Gregor89929282012-01-30 06:01:29 +0000201 HeaderInfo.setTarget(Target);
Aaron Ballmand742dc22018-04-16 21:07:08 +0000202
203 // Populate the identifier table with info about keywords for the current language.
204 Identifiers.AddKeywords(LangOpts);
Douglas Gregor83297df2011-09-01 23:39:15 +0000205}
206
Ted Kremenekeeccb302014-08-27 15:14:15 +0000207void Preprocessor::InitializeForModelFile() {
208 NumEnteredSourceFiles = 0;
209
210 // Reset pragmas
David Blaikie9f0af9d2014-09-15 21:31:42 +0000211 PragmaHandlersBackup = std::move(PragmaHandlers);
Craig Topperbe250302014-09-12 05:19:24 +0000212 PragmaHandlers = llvm::make_unique<PragmaNamespace>(StringRef());
Ted Kremenekeeccb302014-08-27 15:14:15 +0000213 RegisterBuiltinPragmas();
214
215 // Reset PredefinesFileID
216 PredefinesFileID = FileID();
217}
218
219void Preprocessor::FinalizeForModelFile() {
220 NumEnteredSourceFiles = 1;
221
David Blaikie9f0af9d2014-09-15 21:31:42 +0000222 PragmaHandlers = std::move(PragmaHandlersBackup);
Ted Kremenekeeccb302014-08-27 15:14:15 +0000223}
224
Chris Lattner146762e2007-07-20 16:59:19 +0000225void Preprocessor::DumpToken(const Token &Tok, bool DumpFlags) const {
Benjamin Kramer89b422c2009-08-23 12:08:50 +0000226 llvm::errs() << tok::getTokenName(Tok.getKind()) << " '"
227 << getSpelling(Tok) << "'";
Mike Stump11289f42009-09-09 15:08:12 +0000228
Chris Lattnerd01e2912006-06-18 16:22:51 +0000229 if (!DumpFlags) return;
Mike Stump11289f42009-09-09 15:08:12 +0000230
Benjamin Kramer89b422c2009-08-23 12:08:50 +0000231 llvm::errs() << "\t";
Chris Lattnerd01e2912006-06-18 16:22:51 +0000232 if (Tok.isAtStartOfLine())
Benjamin Kramer89b422c2009-08-23 12:08:50 +0000233 llvm::errs() << " [StartOfLine]";
Chris Lattnerd01e2912006-06-18 16:22:51 +0000234 if (Tok.hasLeadingSpace())
Benjamin Kramer89b422c2009-08-23 12:08:50 +0000235 llvm::errs() << " [LeadingSpace]";
Chris Lattner6e4bf522006-07-27 06:59:25 +0000236 if (Tok.isExpandDisabled())
Benjamin Kramer89b422c2009-08-23 12:08:50 +0000237 llvm::errs() << " [ExpandDisabled]";
Chris Lattnerd01e2912006-06-18 16:22:51 +0000238 if (Tok.needsCleaning()) {
Chris Lattner50b497e2006-06-18 16:32:35 +0000239 const char *Start = SourceMgr.getCharacterData(Tok.getLocation());
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000240 llvm::errs() << " [UnClean='" << StringRef(Start, Tok.getLength())
Benjamin Kramer89b422c2009-08-23 12:08:50 +0000241 << "']";
Chris Lattnerd01e2912006-06-18 16:22:51 +0000242 }
Mike Stump11289f42009-09-09 15:08:12 +0000243
Benjamin Kramer89b422c2009-08-23 12:08:50 +0000244 llvm::errs() << "\tLoc=<";
Chris Lattner615315f2007-12-09 20:31:55 +0000245 DumpLocation(Tok.getLocation());
Benjamin Kramer89b422c2009-08-23 12:08:50 +0000246 llvm::errs() << ">";
Chris Lattner615315f2007-12-09 20:31:55 +0000247}
248
249void Preprocessor::DumpLocation(SourceLocation Loc) const {
Stephen Kelly3124ce72018-08-15 20:32:06 +0000250 Loc.print(llvm::errs(), SourceMgr);
Chris Lattnerd01e2912006-06-18 16:22:51 +0000251}
252
253void Preprocessor::DumpMacro(const MacroInfo &MI) const {
Benjamin Kramer89b422c2009-08-23 12:08:50 +0000254 llvm::errs() << "MACRO: ";
Chris Lattnerd01e2912006-06-18 16:22:51 +0000255 for (unsigned i = 0, e = MI.getNumTokens(); i != e; ++i) {
256 DumpToken(MI.getReplacementToken(i));
Benjamin Kramer89b422c2009-08-23 12:08:50 +0000257 llvm::errs() << " ";
Chris Lattnerd01e2912006-06-18 16:22:51 +0000258 }
Benjamin Kramer89b422c2009-08-23 12:08:50 +0000259 llvm::errs() << "\n";
Chris Lattnerd01e2912006-06-18 16:22:51 +0000260}
261
Chris Lattner22eb9722006-06-18 05:43:12 +0000262void Preprocessor::PrintStats() {
Benjamin Kramer89b422c2009-08-23 12:08:50 +0000263 llvm::errs() << "\n*** Preprocessor Stats:\n";
264 llvm::errs() << NumDirectives << " directives found:\n";
265 llvm::errs() << " " << NumDefined << " #define.\n";
266 llvm::errs() << " " << NumUndefined << " #undef.\n";
267 llvm::errs() << " #include/#include_next/#import:\n";
268 llvm::errs() << " " << NumEnteredSourceFiles << " source files entered.\n";
269 llvm::errs() << " " << MaxIncludeStackDepth << " max include stack depth\n";
270 llvm::errs() << " " << NumIf << " #if/#ifndef/#ifdef.\n";
271 llvm::errs() << " " << NumElse << " #else/#elif.\n";
272 llvm::errs() << " " << NumEndif << " #endif.\n";
273 llvm::errs() << " " << NumPragma << " #pragma.\n";
274 llvm::errs() << NumSkipped << " #if/#ifndef#ifdef regions skipped\n";
Chris Lattner22eb9722006-06-18 05:43:12 +0000275
Benjamin Kramer89b422c2009-08-23 12:08:50 +0000276 llvm::errs() << NumMacroExpanded << "/" << NumFnMacroExpanded << "/"
Ted Kremeneka0a3e9b2008-01-14 16:44:48 +0000277 << NumBuiltinMacroExpanded << " obj/fn/builtin macros expanded, "
278 << NumFastMacroExpanded << " on the fast path.\n";
Benjamin Kramer89b422c2009-08-23 12:08:50 +0000279 llvm::errs() << (NumFastTokenPaste+NumTokenPaste)
Ted Kremeneka0a3e9b2008-01-14 16:44:48 +0000280 << " token paste (##) operations performed, "
281 << NumFastTokenPaste << " on the fast path.\n";
Alexander Kornienko199cd942012-08-13 10:46:42 +0000282
283 llvm::errs() << "\nPreprocessor Memory: " << getTotalMemory() << "B total";
284
285 llvm::errs() << "\n BumpPtr: " << BP.getTotalMemory();
286 llvm::errs() << "\n Macro Expanded Tokens: "
287 << llvm::capacity_in_bytes(MacroExpandedTokens);
288 llvm::errs() << "\n Predefines Buffer: " << Predefines.capacity();
Richard Smith04765ae2015-05-21 01:20:10 +0000289 // FIXME: List information for all submodules.
290 llvm::errs() << "\n Macros: "
291 << llvm::capacity_in_bytes(CurSubmoduleState->Macros);
Alexander Kornienko199cd942012-08-13 10:46:42 +0000292 llvm::errs() << "\n #pragma push_macro Info: "
293 << llvm::capacity_in_bytes(PragmaPushMacroInfo);
294 llvm::errs() << "\n Poison Reasons: "
295 << llvm::capacity_in_bytes(PoisonReasons);
296 llvm::errs() << "\n Comment Handlers: "
297 << llvm::capacity_in_bytes(CommentHandlers) << "\n";
Chris Lattner22eb9722006-06-18 05:43:12 +0000298}
299
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +0000300Preprocessor::macro_iterator
301Preprocessor::macro_begin(bool IncludeExternalMacros) const {
302 if (IncludeExternalMacros && ExternalSource &&
Douglas Gregor9882a5a2010-01-04 19:18:44 +0000303 !ReadMacrosFromExternalSource) {
304 ReadMacrosFromExternalSource = true;
305 ExternalSource->ReadDefinedMacros();
306 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +0000307
Jordan Rosea46bfa62015-06-24 19:27:02 +0000308 // Make sure we cover all macros in visible modules.
309 for (const ModuleMacro &Macro : ModuleMacros)
310 CurSubmoduleState->Macros.insert(std::make_pair(Macro.II, MacroState()));
311
Richard Smith04765ae2015-05-21 01:20:10 +0000312 return CurSubmoduleState->Macros.begin();
Douglas Gregor9882a5a2010-01-04 19:18:44 +0000313}
314
Argyrios Kyrtzidise379ee32011-06-29 22:20:04 +0000315size_t Preprocessor::getTotalMemory() const {
Ted Kremenek182543a2011-07-26 21:17:24 +0000316 return BP.getTotalMemory()
Ted Kremenek8b77fe72011-07-27 18:41:23 +0000317 + llvm::capacity_in_bytes(MacroExpandedTokens)
Ted Kremenek182543a2011-07-26 21:17:24 +0000318 + Predefines.capacity() /* Predefines buffer. */
Richard Smith04765ae2015-05-21 01:20:10 +0000319 // FIXME: Include sizes from all submodules, and include MacroInfo sizes,
320 // and ModuleMacros.
321 + llvm::capacity_in_bytes(CurSubmoduleState->Macros)
Ted Kremenek8b77fe72011-07-27 18:41:23 +0000322 + llvm::capacity_in_bytes(PragmaPushMacroInfo)
323 + llvm::capacity_in_bytes(PoisonReasons)
324 + llvm::capacity_in_bytes(CommentHandlers);
Argyrios Kyrtzidise379ee32011-06-29 22:20:04 +0000325}
326
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +0000327Preprocessor::macro_iterator
328Preprocessor::macro_end(bool IncludeExternalMacros) const {
329 if (IncludeExternalMacros && ExternalSource &&
Douglas Gregor9882a5a2010-01-04 19:18:44 +0000330 !ReadMacrosFromExternalSource) {
331 ReadMacrosFromExternalSource = true;
332 ExternalSource->ReadDefinedMacros();
333 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +0000334
Richard Smith04765ae2015-05-21 01:20:10 +0000335 return CurSubmoduleState->Macros.end();
Douglas Gregor9882a5a2010-01-04 19:18:44 +0000336}
337
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000338/// Compares macro tokens with a specified token value sequence.
Dmitri Gribenko6743e042012-09-29 11:40:46 +0000339static bool MacroDefinitionEquals(const MacroInfo *MI,
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000340 ArrayRef<TokenValue> Tokens) {
Dmitri Gribenko6743e042012-09-29 11:40:46 +0000341 return Tokens.size() == MI->getNumTokens() &&
342 std::equal(Tokens.begin(), Tokens.end(), MI->tokens_begin());
343}
344
345StringRef Preprocessor::getLastMacroWithSpelling(
346 SourceLocation Loc,
347 ArrayRef<TokenValue> Tokens) const {
348 SourceLocation BestLocation;
349 StringRef BestSpelling;
350 for (Preprocessor::macro_iterator I = macro_begin(), E = macro_end();
351 I != E; ++I) {
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +0000352 const MacroDirective::DefInfo
Richard Smithb8b2ed62015-04-23 18:18:26 +0000353 Def = I->second.findDirectiveAtLoc(Loc, SourceMgr);
Argyrios Kyrtzidis5c585252015-03-04 16:03:07 +0000354 if (!Def || !Def.getMacroInfo())
355 continue;
356 if (!Def.getMacroInfo()->isObjectLike())
Dmitri Gribenko6743e042012-09-29 11:40:46 +0000357 continue;
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +0000358 if (!MacroDefinitionEquals(Def.getMacroInfo(), Tokens))
Dmitri Gribenko6743e042012-09-29 11:40:46 +0000359 continue;
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +0000360 SourceLocation Location = Def.getLocation();
Dmitri Gribenko6743e042012-09-29 11:40:46 +0000361 // Choose the macro defined latest.
362 if (BestLocation.isInvalid() ||
363 (Location.isValid() &&
364 SourceMgr.isBeforeInTranslationUnit(BestLocation, Location))) {
365 BestLocation = Location;
366 BestSpelling = I->first->getName();
367 }
368 }
369 return BestSpelling;
370}
371
Douglas Gregor8d76cca2012-01-04 06:20:15 +0000372void Preprocessor::recomputeCurLexerKind() {
373 if (CurLexer)
374 CurLexerKind = CLK_Lexer;
Douglas Gregor8d76cca2012-01-04 06:20:15 +0000375 else if (CurTokenLexer)
376 CurLexerKind = CLK_TokenLexer;
Fangrui Song6907ce22018-07-30 19:24:48 +0000377 else
Douglas Gregor8d76cca2012-01-04 06:20:15 +0000378 CurLexerKind = CLK_CachingLexer;
379}
380
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +0000381bool Preprocessor::SetCodeCompletionPoint(const FileEntry *File,
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +0000382 unsigned CompleteLine,
383 unsigned CompleteColumn) {
384 assert(File);
385 assert(CompleteLine && CompleteColumn && "Starts from 1:1");
386 assert(!CodeCompletionFile && "Already set");
387
Douglas Gregor53ad6b92009-12-02 06:49:09 +0000388 using llvm::MemoryBuffer;
389
Douglas Gregor53ad6b92009-12-02 06:49:09 +0000390 // Load the actual file's contents.
Douglas Gregor26266da2010-03-16 19:49:24 +0000391 bool Invalid = false;
392 const MemoryBuffer *Buffer = SourceMgr.getMemoryBufferForFile(File, &Invalid);
393 if (Invalid)
Douglas Gregor53ad6b92009-12-02 06:49:09 +0000394 return true;
395
396 // Find the byte position of the truncation point.
397 const char *Position = Buffer->getBufferStart();
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +0000398 for (unsigned Line = 1; Line < CompleteLine; ++Line) {
Douglas Gregor53ad6b92009-12-02 06:49:09 +0000399 for (; *Position; ++Position) {
400 if (*Position != '\r' && *Position != '\n')
401 continue;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +0000402
Douglas Gregor53ad6b92009-12-02 06:49:09 +0000403 // Eat \r\n or \n\r as a single line.
404 if ((Position[1] == '\r' || Position[1] == '\n') &&
405 Position[0] != Position[1])
406 ++Position;
407 ++Position;
408 break;
409 }
410 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +0000411
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +0000412 Position += CompleteColumn - 1;
Argyrios Kyrtzidisee301f92014-10-18 06:23:50 +0000413
414 // If pointing inside the preamble, adjust the position at the beginning of
415 // the file after the preamble.
416 if (SkipMainFilePreamble.first &&
417 SourceMgr.getFileEntryForID(SourceMgr.getMainFileID()) == File) {
418 if (Position - Buffer->getBufferStart() < SkipMainFilePreamble.first)
419 Position = Buffer->getBufferStart() + SkipMainFilePreamble.first;
420 }
421
Argyrios Kyrtzidise62d6822014-10-18 06:19:36 +0000422 if (Position > Buffer->getBufferEnd())
423 Position = Buffer->getBufferEnd();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +0000424
Argyrios Kyrtzidise62d6822014-10-18 06:19:36 +0000425 CodeCompletionFile = File;
426 CodeCompletionOffset = Position - Buffer->getBufferStart();
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +0000427
Pavel Labathbf8519b2017-12-20 11:34:38 +0000428 auto NewBuffer = llvm::WritableMemoryBuffer::getNewUninitMemBuffer(
429 Buffer->getBufferSize() + 1, Buffer->getBufferIdentifier());
430 char *NewBuf = NewBuffer->getBufferStart();
Argyrios Kyrtzidise62d6822014-10-18 06:19:36 +0000431 char *NewPos = std::copy(Buffer->getBufferStart(), Position, NewBuf);
432 *NewPos = '\0';
433 std::copy(Position, Buffer->getBufferEnd(), NewPos+1);
434 SourceMgr.overrideFileContents(File, std::move(NewBuffer));
Douglas Gregor53ad6b92009-12-02 06:49:09 +0000435
436 return false;
437}
438
Sam McCall3d8051a2018-09-18 08:40:41 +0000439void Preprocessor::CodeCompleteIncludedFile(llvm::StringRef Dir,
440 bool IsAngled) {
441 if (CodeComplete)
442 CodeComplete->CodeCompleteIncludedFile(Dir, IsAngled);
443 setCodeCompletionReached();
444}
445
Douglas Gregor11583702010-08-25 17:04:25 +0000446void Preprocessor::CodeCompleteNaturalLanguage() {
Douglas Gregor11583702010-08-25 17:04:25 +0000447 if (CodeComplete)
448 CodeComplete->CodeCompleteNaturalLanguage();
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +0000449 setCodeCompletionReached();
Douglas Gregor11583702010-08-25 17:04:25 +0000450}
451
Benjamin Kramera197fb62010-02-27 17:05:45 +0000452/// getSpelling - This method is used to get the spelling of a token into a
453/// SmallVector. Note that the returned StringRef may not point to the
454/// supplied buffer if a copy can be avoided.
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000455StringRef Preprocessor::getSpelling(const Token &Tok,
456 SmallVectorImpl<char> &Buffer,
Douglas Gregor7bda4b82010-03-16 05:20:39 +0000457 bool *Invalid) const {
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +0000458 // NOTE: this has to be checked *before* testing for an IdentifierInfo.
Jordan Rose7f43ddd2013-01-24 20:50:46 +0000459 if (Tok.isNot(tok::raw_identifier) && !Tok.hasUCN()) {
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +0000460 // Try the fast path.
461 if (const IdentifierInfo *II = Tok.getIdentifierInfo())
462 return II->getName();
463 }
Benjamin Kramera197fb62010-02-27 17:05:45 +0000464
465 // Resize the buffer if we need to copy into it.
466 if (Tok.needsCleaning())
467 Buffer.resize(Tok.getLength());
468
469 const char *Ptr = Buffer.data();
Douglas Gregor7bda4b82010-03-16 05:20:39 +0000470 unsigned Len = getSpelling(Tok, Ptr, Invalid);
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000471 return StringRef(Ptr, Len);
Benjamin Kramera197fb62010-02-27 17:05:45 +0000472}
473
Chris Lattnerb94ec7b2006-07-14 06:54:10 +0000474/// CreateString - Plop the specified string into a scratch buffer and return a
475/// location for it. If specified, the source location provides a source
476/// location for the token.
Dmitri Gribenkob8e9e752012-09-24 21:07:17 +0000477void Preprocessor::CreateString(StringRef Str, Token &Tok,
Abramo Bagnarae398e602011-10-03 18:39:03 +0000478 SourceLocation ExpansionLocStart,
479 SourceLocation ExpansionLocEnd) {
Dmitri Gribenkob8e9e752012-09-24 21:07:17 +0000480 Tok.setLength(Str.size());
Mike Stump11289f42009-09-09 15:08:12 +0000481
Chris Lattner5a7971e2009-01-26 19:29:26 +0000482 const char *DestPtr;
Dmitri Gribenkob8e9e752012-09-24 21:07:17 +0000483 SourceLocation Loc = ScratchBuf->getToken(Str.data(), Str.size(), DestPtr);
Mike Stump11289f42009-09-09 15:08:12 +0000484
Abramo Bagnarae398e602011-10-03 18:39:03 +0000485 if (ExpansionLocStart.isValid())
486 Loc = SourceMgr.createExpansionLoc(Loc, ExpansionLocStart,
Dmitri Gribenkob8e9e752012-09-24 21:07:17 +0000487 ExpansionLocEnd, Str.size());
Chris Lattner5a7971e2009-01-26 19:29:26 +0000488 Tok.setLocation(Loc);
Mike Stump11289f42009-09-09 15:08:12 +0000489
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +0000490 // If this is a raw identifier or a literal token, set the pointer data.
491 if (Tok.is(tok::raw_identifier))
492 Tok.setRawIdentifierData(DestPtr);
493 else if (Tok.isLiteral())
Chris Lattner5a7971e2009-01-26 19:29:26 +0000494 Tok.setLiteralData(DestPtr);
Chris Lattnerb94ec7b2006-07-14 06:54:10 +0000495}
496
Richard Smithb5f81712018-04-30 05:25:48 +0000497SourceLocation Preprocessor::SplitToken(SourceLocation Loc, unsigned Length) {
498 auto &SM = getSourceManager();
499 SourceLocation SpellingLoc = SM.getSpellingLoc(Loc);
500 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(SpellingLoc);
501 bool Invalid = false;
502 StringRef Buffer = SM.getBufferData(LocInfo.first, &Invalid);
503 if (Invalid)
504 return SourceLocation();
505
506 // FIXME: We could consider re-using spelling for tokens we see repeatedly.
507 const char *DestPtr;
508 SourceLocation Spelling =
509 ScratchBuf->getToken(Buffer.data() + LocInfo.second, Length, DestPtr);
510 return SM.createTokenSplitLoc(Spelling, Loc, Loc.getLocWithOffset(Length));
511}
512
Douglas Gregor2b82c2a2011-12-02 01:47:07 +0000513Module *Preprocessor::getCurrentModule() {
Richard Smithbbcc9f02016-08-26 00:14:38 +0000514 if (!getLangOpts().isCompilingModule())
Craig Topperd2d442c2014-05-17 23:10:59 +0000515 return nullptr;
516
David Blaikiebbafb8a2012-03-11 07:00:24 +0000517 return getHeaderSearchInfo().lookupModule(getLangOpts().CurrentModule);
Douglas Gregor2b82c2a2011-12-02 01:47:07 +0000518}
Chris Lattner8a7003c2007-07-16 06:48:38 +0000519
Chris Lattner1f1b0db2007-10-09 22:10:18 +0000520//===----------------------------------------------------------------------===//
521// Preprocessor Initialization Methods
522//===----------------------------------------------------------------------===//
523
Chris Lattner1f1b0db2007-10-09 22:10:18 +0000524/// EnterMainSourceFile - Enter the specified FileID as the main source file,
Nate Begemanf7c3ff62008-01-07 04:01:26 +0000525/// which implicitly adds the builtin defines etc.
Chris Lattnerfb24a3a2010-04-20 20:35:58 +0000526void Preprocessor::EnterMainSourceFile() {
Chris Lattner9ef847b2009-02-13 19:33:24 +0000527 // We do not allow the preprocessor to reenter the main file. Doing so will
528 // cause FileID's to accumulate information from both runs (e.g. #line
529 // information) and predefined macros aren't guaranteed to be set properly.
530 assert(NumEnteredSourceFiles == 0 && "Cannot reenter the main file!");
Chris Lattnerd32480d2009-01-17 06:22:33 +0000531 FileID MainFileID = SourceMgr.getMainFileID();
Mike Stump11289f42009-09-09 15:08:12 +0000532
Argyrios Kyrtzidis9afd4492012-01-05 21:36:25 +0000533 // If MainFileID is loaded it means we loaded an AST file, no need to enter
534 // a main file.
535 if (!SourceMgr.isLoadedFileID(MainFileID)) {
536 // Enter the main file source buffer.
Craig Topperd2d442c2014-05-17 23:10:59 +0000537 EnterSourceFile(MainFileID, nullptr, SourceLocation());
538
Argyrios Kyrtzidis9afd4492012-01-05 21:36:25 +0000539 // If we've been asked to skip bytes in the main file (e.g., as part of a
540 // precompiled preamble), do so now.
541 if (SkipMainFilePreamble.first > 0)
Cameron Desrochers84fd0642017-09-20 19:03:37 +0000542 CurLexer->SetByteOffset(SkipMainFilePreamble.first,
543 SkipMainFilePreamble.second);
544
Argyrios Kyrtzidis9afd4492012-01-05 21:36:25 +0000545 // Tell the header info that the main file was entered. If the file is later
546 // #imported, it won't be re-entered.
547 if (const FileEntry *FE = SourceMgr.getFileEntryForID(MainFileID))
548 HeaderInfo.IncrementIncludeCount(FE);
549 }
Mike Stump11289f42009-09-09 15:08:12 +0000550
Benjamin Kramerd77adb52009-12-31 15:33:09 +0000551 // Preprocess Predefines to populate the initial preprocessor state.
Rafael Espindolad87f8d72014-08-27 20:03:29 +0000552 std::unique_ptr<llvm::MemoryBuffer> SB =
Chris Lattner58c79342010-04-05 22:42:27 +0000553 llvm::MemoryBuffer::getMemBufferCopy(Predefines, "<built-in>");
Douglas Gregor33551892010-08-26 14:07:34 +0000554 assert(SB && "Cannot create predefined source buffer");
David Blaikie50a5f972014-08-29 07:59:55 +0000555 FileID FID = SourceMgr.createFileID(std::move(SB));
Yaron Keren8b563662015-10-03 10:46:20 +0000556 assert(FID.isValid() && "Could not create FileID for predefines?");
Argyrios Kyrtzidis22c22f52013-02-01 16:36:07 +0000557 setPredefinesFileID(FID);
Mike Stump11289f42009-09-09 15:08:12 +0000558
Chris Lattner1f1b0db2007-10-09 22:10:18 +0000559 // Start parsing the predefines.
Craig Topperd2d442c2014-05-17 23:10:59 +0000560 EnterSourceFile(FID, nullptr, SourceLocation());
Erich Keane76675de2018-07-05 17:22:13 +0000561
562 if (!PPOpts->PCHThroughHeader.empty()) {
563 // Lookup and save the FileID for the through header. If it isn't found
564 // in the search path, it's a fatal error.
565 const DirectoryLookup *CurDir;
566 const FileEntry *File = LookupFile(
567 SourceLocation(), PPOpts->PCHThroughHeader,
568 /*isAngled=*/false, /*FromDir=*/nullptr, /*FromFile=*/nullptr, CurDir,
569 /*SearchPath=*/nullptr, /*RelativePath=*/nullptr,
570 /*SuggestedModule=*/nullptr, /*IsMapped=*/nullptr);
571 if (!File) {
572 Diag(SourceLocation(), diag::err_pp_through_header_not_found)
573 << PPOpts->PCHThroughHeader;
574 return;
575 }
576 setPCHThroughHeaderFileID(
577 SourceMgr.createFileID(File, SourceLocation(), SrcMgr::C_User));
578 }
579
580 // Skip tokens from the Predefines and if needed the main file.
Mike Rice58df1af2018-09-11 17:10:44 +0000581 if ((usingPCHWithThroughHeader() && SkippingUntilPCHThroughHeader) ||
582 (usingPCHWithPragmaHdrStop() && SkippingUntilPragmaHdrStop))
583 SkipTokensWhileUsingPCH();
Erich Keane76675de2018-07-05 17:22:13 +0000584}
585
586void Preprocessor::setPCHThroughHeaderFileID(FileID FID) {
587 assert(PCHThroughHeaderFileID.isInvalid() &&
588 "PCHThroughHeaderFileID already set!");
589 PCHThroughHeaderFileID = FID;
590}
591
592bool Preprocessor::isPCHThroughHeader(const FileEntry *FE) {
593 assert(PCHThroughHeaderFileID.isValid() &&
594 "Invalid PCH through header FileID");
595 return FE == SourceMgr.getFileEntryForID(PCHThroughHeaderFileID);
596}
597
598bool Preprocessor::creatingPCHWithThroughHeader() {
599 return TUKind == TU_Prefix && !PPOpts->PCHThroughHeader.empty() &&
600 PCHThroughHeaderFileID.isValid();
601}
602
603bool Preprocessor::usingPCHWithThroughHeader() {
604 return TUKind != TU_Prefix && !PPOpts->PCHThroughHeader.empty() &&
605 PCHThroughHeaderFileID.isValid();
606}
607
Mike Rice58df1af2018-09-11 17:10:44 +0000608bool Preprocessor::creatingPCHWithPragmaHdrStop() {
609 return TUKind == TU_Prefix && PPOpts->PCHWithHdrStop;
610}
611
612bool Preprocessor::usingPCHWithPragmaHdrStop() {
613 return TUKind != TU_Prefix && PPOpts->PCHWithHdrStop;
614}
615
616/// Skip tokens until after the #include of the through header or
617/// until after a #pragma hdrstop is seen. Tokens in the predefines file
618/// and the main file may be skipped. If the end of the predefines file
619/// is reached, skipping continues into the main file. If the end of the
620/// main file is reached, it's a fatal error.
621void Preprocessor::SkipTokensWhileUsingPCH() {
Erich Keane76675de2018-07-05 17:22:13 +0000622 bool ReachedMainFileEOF = false;
Mike Rice58df1af2018-09-11 17:10:44 +0000623 bool UsingPCHThroughHeader = SkippingUntilPCHThroughHeader;
624 bool UsingPragmaHdrStop = SkippingUntilPragmaHdrStop;
Erich Keane76675de2018-07-05 17:22:13 +0000625 Token Tok;
626 while (true) {
627 bool InPredefines = (CurLexer->getFileID() == getPredefinesFileID());
628 CurLexer->Lex(Tok);
629 if (Tok.is(tok::eof) && !InPredefines) {
630 ReachedMainFileEOF = true;
631 break;
632 }
Mike Rice58df1af2018-09-11 17:10:44 +0000633 if (UsingPCHThroughHeader && !SkippingUntilPCHThroughHeader)
634 break;
635 if (UsingPragmaHdrStop && !SkippingUntilPragmaHdrStop)
Erich Keane76675de2018-07-05 17:22:13 +0000636 break;
637 }
Mike Rice58df1af2018-09-11 17:10:44 +0000638 if (ReachedMainFileEOF) {
639 if (UsingPCHThroughHeader)
640 Diag(SourceLocation(), diag::err_pp_through_header_not_seen)
641 << PPOpts->PCHThroughHeader << 1;
642 else if (!PPOpts->PCHWithHdrStopCreate)
643 Diag(SourceLocation(), diag::err_pp_pragma_hdrstop_not_seen);
644 }
Erik Verbruggen795eee92017-07-05 09:44:07 +0000645}
Erik Verbruggenb34c79f2017-05-30 11:54:55 +0000646
Erik Verbruggen795eee92017-07-05 09:44:07 +0000647void Preprocessor::replayPreambleConditionalStack() {
Erik Verbruggenb34c79f2017-05-30 11:54:55 +0000648 // Restore the conditional stack from the preamble, if there is one.
649 if (PreambleConditionalStack.isReplaying()) {
Ilya Biryukovf3150002017-08-21 12:03:08 +0000650 assert(CurPPLexer &&
651 "CurPPLexer is null when calling replayPreambleConditionalStack.");
Erik Verbruggenb34c79f2017-05-30 11:54:55 +0000652 CurPPLexer->setConditionalLevels(PreambleConditionalStack.getStack());
653 PreambleConditionalStack.doneReplaying();
Erik Verbruggen4d1eb2d2017-11-03 09:40:07 +0000654 if (PreambleConditionalStack.reachedEOFWhileSkipping())
655 SkipExcludedConditionalBlock(
656 PreambleConditionalStack.SkipInfo->HashTokenLoc,
657 PreambleConditionalStack.SkipInfo->IfTokenLoc,
658 PreambleConditionalStack.SkipInfo->FoundNonSkipPortion,
659 PreambleConditionalStack.SkipInfo->FoundElse,
660 PreambleConditionalStack.SkipInfo->ElseLoc);
Erik Verbruggenb34c79f2017-05-30 11:54:55 +0000661 }
Chris Lattner1f1b0db2007-10-09 22:10:18 +0000662}
Chris Lattner8a7003c2007-07-16 06:48:38 +0000663
Daniel Dunbarcb9eaf52010-03-23 05:09:10 +0000664void Preprocessor::EndSourceFile() {
665 // Notify the client that we reached the end of the source file.
666 if (Callbacks)
667 Callbacks->EndOfMainFile();
668}
Chris Lattner677757a2006-06-28 05:26:32 +0000669
670//===----------------------------------------------------------------------===//
671// Lexer Event Handling.
672//===----------------------------------------------------------------------===//
673
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +0000674/// LookUpIdentifierInfo - Given a tok::raw_identifier token, look up the
675/// identifier information for the token and install it into the token,
676/// updating the token kind accordingly.
677IdentifierInfo *Preprocessor::LookUpIdentifierInfo(Token &Identifier) const {
Alp Toker2d57cea2014-05-17 04:53:25 +0000678 assert(!Identifier.getRawIdentifier().empty() && "No raw identifier data!");
Mike Stump11289f42009-09-09 15:08:12 +0000679
Chris Lattnercefc7682006-07-08 08:28:12 +0000680 // Look up this token, see if it is a macro, or if it is a language keyword.
681 IdentifierInfo *II;
Jordan Rose7f43ddd2013-01-24 20:50:46 +0000682 if (!Identifier.needsCleaning() && !Identifier.hasUCN()) {
Chris Lattnercefc7682006-07-08 08:28:12 +0000683 // No cleaning needed, just use the characters from the lexed buffer.
Alp Toker2d57cea2014-05-17 04:53:25 +0000684 II = getIdentifierInfo(Identifier.getRawIdentifier());
Chris Lattnercefc7682006-07-08 08:28:12 +0000685 } else {
686 // Cleaning needed, alloca a buffer, clean into it, then use the buffer.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +0000687 SmallString<64> IdentifierBuffer;
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000688 StringRef CleanedStr = getSpelling(Identifier, IdentifierBuffer);
Jordan Rose7f43ddd2013-01-24 20:50:46 +0000689
690 if (Identifier.hasUCN()) {
691 SmallString<64> UCNIdentifierBuffer;
692 expandUCNs(UCNIdentifierBuffer, CleanedStr);
693 II = getIdentifierInfo(UCNIdentifierBuffer);
694 } else {
695 II = getIdentifierInfo(CleanedStr);
696 }
Chris Lattnercefc7682006-07-08 08:28:12 +0000697 }
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +0000698
699 // Update the token info (identifier info and appropriate token kind).
Chris Lattner8c204872006-10-14 05:19:21 +0000700 Identifier.setIdentifierInfo(II);
Erich Keane33c3d8a2017-06-09 16:29:35 +0000701 if (getLangOpts().MSVCCompat && II->isCPlusPlusOperatorKeyword() &&
702 getSourceManager().isInSystemHeader(Identifier.getLocation()))
Eugene Zelenko5dc60fe2017-12-04 23:16:21 +0000703 Identifier.setKind(tok::identifier);
Erich Keane33c3d8a2017-06-09 16:29:35 +0000704 else
705 Identifier.setKind(II->getTokenID());
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +0000706
Chris Lattnercefc7682006-07-08 08:28:12 +0000707 return II;
708}
709
John Wiegley1c0675e2011-04-28 01:08:34 +0000710void Preprocessor::SetPoisonReason(IdentifierInfo *II, unsigned DiagID) {
711 PoisonReasons[II] = DiagID;
712}
713
714void Preprocessor::PoisonSEHIdentifiers(bool Poison) {
715 assert(Ident__exception_code && Ident__exception_info);
716 assert(Ident___exception_code && Ident___exception_info);
717 Ident__exception_code->setIsPoisoned(Poison);
718 Ident___exception_code->setIsPoisoned(Poison);
719 Ident_GetExceptionCode->setIsPoisoned(Poison);
720 Ident__exception_info->setIsPoisoned(Poison);
721 Ident___exception_info->setIsPoisoned(Poison);
722 Ident_GetExceptionInfo->setIsPoisoned(Poison);
723 Ident__abnormal_termination->setIsPoisoned(Poison);
724 Ident___abnormal_termination->setIsPoisoned(Poison);
725 Ident_AbnormalTermination->setIsPoisoned(Poison);
726}
727
728void Preprocessor::HandlePoisonedIdentifier(Token & Identifier) {
729 assert(Identifier.getIdentifierInfo() &&
730 "Can't handle identifiers without identifier info!");
731 llvm::DenseMap<IdentifierInfo*,unsigned>::const_iterator it =
732 PoisonReasons.find(Identifier.getIdentifierInfo());
733 if(it == PoisonReasons.end())
734 Diag(Identifier, diag::err_pp_used_poisoned_id);
735 else
736 Diag(Identifier,it->second) << Identifier.getIdentifierInfo();
737}
Chris Lattnercefc7682006-07-08 08:28:12 +0000738
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000739/// Returns a diagnostic message kind for reporting a future keyword as
Richard Smith31d51842015-05-14 04:00:59 +0000740/// appropriate for the identifier and specified language.
741static diag::kind getFutureCompatDiagKind(const IdentifierInfo &II,
742 const LangOptions &LangOpts) {
743 assert(II.isFutureCompatKeyword() && "diagnostic should not be needed");
744
745 if (LangOpts.CPlusPlus)
746 return llvm::StringSwitch<diag::kind>(II.getName())
747#define CXX11_KEYWORD(NAME, FLAGS) \
748 .Case(#NAME, diag::warn_cxx11_keyword)
Richard Smith6c74e322017-08-13 21:32:33 +0000749#define CXX2A_KEYWORD(NAME, FLAGS) \
750 .Case(#NAME, diag::warn_cxx2a_keyword)
Richard Smith31d51842015-05-14 04:00:59 +0000751#include "clang/Basic/TokenKinds.def"
752 ;
753
754 llvm_unreachable(
755 "Keyword not known to come from a newer Standard or proposed Standard");
756}
757
Richard Smith3dba7eb2016-08-18 01:16:55 +0000758void Preprocessor::updateOutOfDateIdentifier(IdentifierInfo &II) const {
759 assert(II.isOutOfDate() && "not out of date");
760 getExternalSource()->updateOutOfDateIdentifier(II);
761}
762
Chris Lattner677757a2006-06-28 05:26:32 +0000763/// HandleIdentifier - This callback is invoked when the lexer reads an
764/// identifier. This callback looks up the identifier in the map and/or
765/// potentially macro expands it or turns it into a named token (like 'for').
Chris Lattnerad89ec02009-01-21 07:43:11 +0000766///
767/// Note that callers of this method are guarded by checking the
768/// IdentifierInfo's 'isHandleIdentifierCase' bit. If this method changes, the
769/// IdentifierInfo methods that compute these properties will need to change to
770/// match.
Eli Friedman0834a4b2013-09-19 00:41:32 +0000771bool Preprocessor::HandleIdentifier(Token &Identifier) {
Chris Lattner0f1f5052006-07-20 04:16:23 +0000772 assert(Identifier.getIdentifierInfo() &&
773 "Can't handle identifiers without identifier info!");
Mike Stump11289f42009-09-09 15:08:12 +0000774
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000775 IdentifierInfo &II = *Identifier.getIdentifierInfo();
Chris Lattner677757a2006-06-28 05:26:32 +0000776
Douglas Gregor935bc7a22011-10-27 09:33:13 +0000777 // If the information about this identifier is out of date, update it from
778 // the external source.
Douglas Gregor3f568c12012-06-29 18:27:59 +0000779 // We have to treat __VA_ARGS__ in a special way, since it gets
780 // serialized with isPoisoned = true, but our preprocessor may have
781 // unpoisoned it if we're defining a C99 macro.
Douglas Gregor935bc7a22011-10-27 09:33:13 +0000782 if (II.isOutOfDate()) {
Douglas Gregor3f568c12012-06-29 18:27:59 +0000783 bool CurrentIsPoisoned = false;
Faisal Vali18268422017-10-15 01:26:26 +0000784 const bool IsSpecialVariadicMacro =
785 &II == Ident__VA_ARGS__ || &II == Ident__VA_OPT__;
786 if (IsSpecialVariadicMacro)
787 CurrentIsPoisoned = II.isPoisoned();
Douglas Gregor3f568c12012-06-29 18:27:59 +0000788
Richard Smith3dba7eb2016-08-18 01:16:55 +0000789 updateOutOfDateIdentifier(II);
Douglas Gregor935bc7a22011-10-27 09:33:13 +0000790 Identifier.setKind(II.getTokenID());
Douglas Gregor3f568c12012-06-29 18:27:59 +0000791
Faisal Vali18268422017-10-15 01:26:26 +0000792 if (IsSpecialVariadicMacro)
Douglas Gregor3f568c12012-06-29 18:27:59 +0000793 II.setIsPoisoned(CurrentIsPoisoned);
Douglas Gregor935bc7a22011-10-27 09:33:13 +0000794 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000795
Chris Lattner677757a2006-06-28 05:26:32 +0000796 // If this identifier was poisoned, and if it was not produced from a macro
797 // expansion, emit an error.
Ted Kremeneka2c3c8d2008-11-19 22:43:49 +0000798 if (II.isPoisoned() && CurPPLexer) {
John Wiegley1c0675e2011-04-28 01:08:34 +0000799 HandlePoisonedIdentifier(Identifier);
Chris Lattner8ff71992006-07-06 05:17:39 +0000800 }
Mike Stump11289f42009-09-09 15:08:12 +0000801
Chris Lattner78186052006-07-09 00:45:31 +0000802 // If this is a macro to be expanded, do it.
Richard Smith20e883e2015-04-29 23:20:19 +0000803 if (MacroDefinition MD = getMacroDefinition(&II)) {
804 auto *MI = MD.getMacroInfo();
Richard Smithf5ec2ac2015-04-29 23:40:48 +0000805 assert(MI && "macro definition with no macro info?");
Abramo Bagnara123bec82012-01-01 22:01:04 +0000806 if (!DisableMacroExpansion) {
Richard Smith181879c2012-12-12 02:46:14 +0000807 if (!Identifier.isExpandDisabled() && MI->isEnabled()) {
Eli Friedman0834a4b2013-09-19 00:41:32 +0000808 // C99 6.10.3p10: If the preprocessing token immediately after the
809 // macro name isn't a '(', this macro should not be expanded.
810 if (!MI->isFunctionLike() || isNextPPTokenLParen())
811 return HandleMacroExpandedIdentifier(Identifier, MD);
Chris Lattner6e4bf522006-07-27 06:59:25 +0000812 } else {
813 // C99 6.10.3.4p2 says that a disabled macro may never again be
814 // expanded, even if it's in a context where it could be expanded in the
815 // future.
Chris Lattner146762e2007-07-20 16:59:19 +0000816 Identifier.setFlag(Token::DisableExpand);
Richard Smith181879c2012-12-12 02:46:14 +0000817 if (MI->isObjectLike() || isNextPPTokenLParen())
818 Diag(Identifier, diag::pp_disabled_macro_expansion);
Chris Lattner6e4bf522006-07-27 06:59:25 +0000819 }
820 }
Chris Lattner063400e2006-10-14 19:54:15 +0000821 }
Chris Lattner677757a2006-06-28 05:26:32 +0000822
Richard Smith31d51842015-05-14 04:00:59 +0000823 // If this identifier is a keyword in a newer Standard or proposed Standard,
824 // produce a warning. Don't warn if we're not considering macro expansion,
825 // since this identifier might be the name of a macro.
Richard Smith4dd85d62011-10-11 19:57:52 +0000826 // FIXME: This warning is disabled in cases where it shouldn't be, like
827 // "#define constexpr constexpr", "int constexpr;"
Richard Smith31d51842015-05-14 04:00:59 +0000828 if (II.isFutureCompatKeyword() && !DisableMacroExpansion) {
829 Diag(Identifier, getFutureCompatDiagKind(II, getLangOpts()))
830 << II.getName();
Richard Smith4dd85d62011-10-11 19:57:52 +0000831 // Don't diagnose this keyword again in this translation unit.
Richard Smith31d51842015-05-14 04:00:59 +0000832 II.setIsFutureCompatKeyword(false);
Richard Smith4dd85d62011-10-11 19:57:52 +0000833 }
834
Chris Lattner677757a2006-06-28 05:26:32 +0000835 // If this is an extension token, diagnose its use.
Steve Naroffc84e8b72008-09-02 18:50:17 +0000836 // We avoid diagnosing tokens that originate from macro definitions.
Eli Friedman6bba2ad2009-04-28 03:59:15 +0000837 // FIXME: This warning is disabled in cases where it shouldn't be,
838 // like "#define TY typeof", "TY(1) x".
839 if (II.isExtensionToken() && !DisableMacroExpansion)
Chris Lattner53621a52007-06-13 20:44:40 +0000840 Diag(Identifier, diag::ext_token_used);
Fangrui Song6907ce22018-07-30 19:24:48 +0000841
Douglas Gregor594b8c92013-11-07 22:55:02 +0000842 // If this is the 'import' contextual keyword following an '@', note
Ted Kremenekc1e4dd02012-03-01 22:07:04 +0000843 // that the next token indicates a module name.
Douglas Gregor8d76cca2012-01-04 06:20:15 +0000844 //
Douglas Gregorc50d4922012-12-11 22:11:52 +0000845 // Note that we do not treat 'import' as a contextual
Ted Kremenekc1e4dd02012-03-01 22:07:04 +0000846 // keyword when we're in a caching lexer, because caching lexers only get
847 // used in contexts where import declarations are disallowed.
Richard Smith49cc1cc2016-08-18 21:59:42 +0000848 //
849 // Likewise if this is the C++ Modules TS import keyword.
850 if (((LastTokenWasAt && II.isModulesImport()) ||
851 Identifier.is(tok::kw_import)) &&
852 !InMacroArgs && !DisableMacroExpansion &&
853 (getLangOpts().Modules || getLangOpts().DebuggerSupport) &&
Douglas Gregor594b8c92013-11-07 22:55:02 +0000854 CurLexerKind != CLK_CachingLexer) {
Douglas Gregoraf5c4842011-09-07 23:11:54 +0000855 ModuleImportLoc = Identifier.getLocation();
Douglas Gregor1805b8a2011-11-30 04:26:53 +0000856 ModuleImportPath.clear();
857 ModuleImportExpectsIdentifier = true;
Douglas Gregoraf5c4842011-09-07 23:11:54 +0000858 CurLexerKind = CLK_LexAfterModuleImport;
859 }
Eli Friedman0834a4b2013-09-19 00:41:32 +0000860 return true;
Douglas Gregor08142532011-08-26 23:56:07 +0000861}
862
Eli Friedman0834a4b2013-09-19 00:41:32 +0000863void Preprocessor::Lex(Token &Result) {
Yaron Keren716f3a62015-09-29 16:51:08 +0000864 // We loop here until a lex function returns a token; this avoids recursion.
Eli Friedman0834a4b2013-09-19 00:41:32 +0000865 bool ReturnedToken;
866 do {
867 switch (CurLexerKind) {
868 case CLK_Lexer:
869 ReturnedToken = CurLexer->Lex(Result);
870 break;
Eli Friedman0834a4b2013-09-19 00:41:32 +0000871 case CLK_TokenLexer:
872 ReturnedToken = CurTokenLexer->Lex(Result);
873 break;
874 case CLK_CachingLexer:
875 CachingLex(Result);
876 ReturnedToken = true;
877 break;
878 case CLK_LexAfterModuleImport:
879 LexAfterModuleImport(Result);
880 ReturnedToken = true;
881 break;
882 }
883 } while (!ReturnedToken);
Douglas Gregor594b8c92013-11-07 22:55:02 +0000884
Ilya Biryukovb8f231a2018-01-22 17:18:28 +0000885 if (Result.is(tok::code_completion) && Result.getIdentifierInfo()) {
886 // Remember the identifier before code completion token.
Vassil Vassilev644ea612016-07-27 14:56:59 +0000887 setCodeCompletionIdentifierInfo(Result.getIdentifierInfo());
Kadir Cetinkaya9b9c2742018-08-13 08:13:35 +0000888 setCodeCompletionTokenRange(Result.getLocation(), Result.getEndLoc());
Ilya Biryukovb8f231a2018-01-22 17:18:28 +0000889 // Set IdenfitierInfo to null to avoid confusing code that handles both
890 // identifiers and completion tokens.
891 Result.setIdentifierInfo(nullptr);
892 }
Vassil Vassilev644ea612016-07-27 14:56:59 +0000893
Douglas Gregor594b8c92013-11-07 22:55:02 +0000894 LastTokenWasAt = Result.is(tok::at);
Eli Friedman0834a4b2013-09-19 00:41:32 +0000895}
896
Adrian Prantl9fc8faf2018-05-09 01:00:01 +0000897/// Lex a token following the 'import' contextual keyword.
Douglas Gregor22d09742012-01-03 18:04:46 +0000898///
Douglas Gregoraf5c4842011-09-07 23:11:54 +0000899void Preprocessor::LexAfterModuleImport(Token &Result) {
900 // Figure out what kind of lexer we actually have.
Douglas Gregor8d76cca2012-01-04 06:20:15 +0000901 recomputeCurLexerKind();
Fangrui Song6907ce22018-07-30 19:24:48 +0000902
Douglas Gregoraf5c4842011-09-07 23:11:54 +0000903 // Lex the next token.
904 Lex(Result);
905
Fangrui Song6907ce22018-07-30 19:24:48 +0000906 // The token sequence
Douglas Gregor08142532011-08-26 23:56:07 +0000907 //
Douglas Gregor22d09742012-01-03 18:04:46 +0000908 // import identifier (. identifier)*
909 //
Fangrui Song6907ce22018-07-30 19:24:48 +0000910 // indicates a module import directive. We already saw the 'import'
Douglas Gregorda82e702012-01-03 19:32:59 +0000911 // contextual keyword, so now we're looking for the identifiers.
Douglas Gregor1805b8a2011-11-30 04:26:53 +0000912 if (ModuleImportExpectsIdentifier && Result.getKind() == tok::identifier) {
913 // We expected to see an identifier here, and we did; continue handling
914 // identifiers.
915 ModuleImportPath.push_back(std::make_pair(Result.getIdentifierInfo(),
916 Result.getLocation()));
917 ModuleImportExpectsIdentifier = false;
918 CurLexerKind = CLK_LexAfterModuleImport;
Douglas Gregor08142532011-08-26 23:56:07 +0000919 return;
Douglas Gregor1805b8a2011-11-30 04:26:53 +0000920 }
Fangrui Song6907ce22018-07-30 19:24:48 +0000921
Douglas Gregor1805b8a2011-11-30 04:26:53 +0000922 // If we're expecting a '.' or a ';', and we got a '.', then wait until we
Richard Smith49cc1cc2016-08-18 21:59:42 +0000923 // see the next identifier. (We can also see a '[[' that begins an
924 // attribute-specifier-seq here under the C++ Modules TS.)
Douglas Gregor1805b8a2011-11-30 04:26:53 +0000925 if (!ModuleImportExpectsIdentifier && Result.getKind() == tok::period) {
926 ModuleImportExpectsIdentifier = true;
927 CurLexerKind = CLK_LexAfterModuleImport;
928 return;
929 }
930
931 // If we have a non-empty module path, load the named module.
Sean Callanan87596492014-12-09 23:47:56 +0000932 if (!ModuleImportPath.empty()) {
Richard Smithbbcc9f02016-08-26 00:14:38 +0000933 // Under the Modules TS, the dot is just part of the module name, and not
934 // a real hierarachy separator. Flatten such module names now.
935 //
936 // FIXME: Is this the right level to be performing this transformation?
937 std::string FlatModuleName;
938 if (getLangOpts().ModulesTS) {
939 for (auto &Piece : ModuleImportPath) {
940 if (!FlatModuleName.empty())
941 FlatModuleName += ".";
942 FlatModuleName += Piece.first->getName();
943 }
944 SourceLocation FirstPathLoc = ModuleImportPath[0].second;
945 ModuleImportPath.clear();
946 ModuleImportPath.push_back(
947 std::make_pair(getIdentifierInfo(FlatModuleName), FirstPathLoc));
948 }
949
Sean Callanan87596492014-12-09 23:47:56 +0000950 Module *Imported = nullptr;
Richard Smith753e0072015-04-27 23:21:38 +0000951 if (getLangOpts().Modules) {
Sean Callanan87596492014-12-09 23:47:56 +0000952 Imported = TheModuleLoader.loadModule(ModuleImportLoc,
953 ModuleImportPath,
Richard Smith10434f32015-05-02 02:08:26 +0000954 Module::Hidden,
Sean Callanan87596492014-12-09 23:47:56 +0000955 /*IsIncludeDirective=*/false);
Richard Smitha7e2cc62015-05-01 01:53:09 +0000956 if (Imported)
957 makeModuleVisible(Imported, ModuleImportLoc);
Richard Smith753e0072015-04-27 23:21:38 +0000958 }
Sean Callanan87596492014-12-09 23:47:56 +0000959 if (Callbacks && (getLangOpts().Modules || getLangOpts().DebuggerSupport))
Argyrios Kyrtzidis19d78b72012-09-29 01:06:10 +0000960 Callbacks->moduleImport(ModuleImportLoc, ModuleImportPath, Imported);
961 }
Chris Lattner677757a2006-06-28 05:26:32 +0000962}
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000963
Richard Smitha7e2cc62015-05-01 01:53:09 +0000964void Preprocessor::makeModuleVisible(Module *M, SourceLocation Loc) {
Richard Smith04765ae2015-05-21 01:20:10 +0000965 CurSubmoduleState->VisibleModules.setVisible(
Richard Smitha7e2cc62015-05-01 01:53:09 +0000966 M, Loc, [](Module *) {},
967 [&](ArrayRef<Module *> Path, Module *Conflict, StringRef Message) {
968 // FIXME: Include the path in the diagnostic.
969 // FIXME: Include the import location for the conflicting module.
970 Diag(ModuleImportLoc, diag::warn_module_conflict)
971 << Path[0]->getFullModuleName()
972 << Conflict->getFullModuleName()
973 << Message;
974 });
975
976 // Add this module to the imports list of the currently-built submodule.
Richard Smithdbbc5232015-05-14 02:25:44 +0000977 if (!BuildingSubmoduleStack.empty() && M != BuildingSubmoduleStack.back().M)
Richard Smith38477db2015-05-02 00:45:56 +0000978 BuildingSubmoduleStack.back().M->Imports.insert(M);
Richard Smitha7e2cc62015-05-01 01:53:09 +0000979}
980
Andy Gibbs58905d22012-11-17 19:15:38 +0000981bool Preprocessor::FinishLexStringLiteral(Token &Result, std::string &String,
Andy Gibbsa8df57a2012-11-17 19:16:52 +0000982 const char *DiagnosticTag,
Andy Gibbs58905d22012-11-17 19:15:38 +0000983 bool AllowMacroExpansion) {
984 // We need at least one string literal.
985 if (Result.isNot(tok::string_literal)) {
Andy Gibbsa8df57a2012-11-17 19:16:52 +0000986 Diag(Result, diag::err_expected_string_literal)
987 << /*Source='in...'*/0 << DiagnosticTag;
Andy Gibbs58905d22012-11-17 19:15:38 +0000988 return false;
989 }
990
991 // Lex string literal tokens, optionally with macro expansion.
992 SmallVector<Token, 4> StrToks;
993 do {
994 StrToks.push_back(Result);
995
996 if (Result.hasUDSuffix())
997 Diag(Result, diag::err_invalid_string_udl);
998
999 if (AllowMacroExpansion)
1000 Lex(Result);
1001 else
1002 LexUnexpandedToken(Result);
1003 } while (Result.is(tok::string_literal));
1004
1005 // Concatenate and parse the strings.
Craig Topper9d5583e2014-06-26 04:58:39 +00001006 StringLiteralParser Literal(StrToks, *this);
Andy Gibbs58905d22012-11-17 19:15:38 +00001007 assert(Literal.isAscii() && "Didn't allow wide strings in");
1008
1009 if (Literal.hadError)
1010 return false;
1011
1012 if (Literal.Pascal) {
Andy Gibbsa8df57a2012-11-17 19:16:52 +00001013 Diag(StrToks[0].getLocation(), diag::err_expected_string_literal)
1014 << /*Source='in...'*/0 << DiagnosticTag;
Andy Gibbs58905d22012-11-17 19:15:38 +00001015 return false;
1016 }
1017
1018 String = Literal.GetString();
1019 return true;
1020}
1021
Reid Klecknerc0dca6d2014-02-12 23:50:26 +00001022bool Preprocessor::parseSimpleIntegerLiteral(Token &Tok, uint64_t &Value) {
1023 assert(Tok.is(tok::numeric_constant));
1024 SmallString<8> IntegerBuffer;
1025 bool NumberInvalid = false;
1026 StringRef Spelling = getSpelling(Tok, IntegerBuffer, &NumberInvalid);
1027 if (NumberInvalid)
1028 return false;
1029 NumericLiteralParser Literal(Spelling, Tok.getLocation(), *this);
1030 if (Literal.hadError || !Literal.isIntegerLiteral() || Literal.hasUDSuffix())
1031 return false;
1032 llvm::APInt APVal(64, 0);
1033 if (Literal.GetIntegerValue(APVal))
1034 return false;
1035 Lex(Tok);
1036 Value = APVal.getLimitedValue();
1037 return true;
1038}
1039
Dmitri Gribenkoaab83832012-06-20 00:34:58 +00001040void Preprocessor::addCommentHandler(CommentHandler *Handler) {
Douglas Gregorc6d5edd2009-07-02 17:08:52 +00001041 assert(Handler && "NULL comment handler");
1042 assert(std::find(CommentHandlers.begin(), CommentHandlers.end(), Handler) ==
1043 CommentHandlers.end() && "Comment handler already registered");
1044 CommentHandlers.push_back(Handler);
1045}
1046
Dmitri Gribenkoaab83832012-06-20 00:34:58 +00001047void Preprocessor::removeCommentHandler(CommentHandler *Handler) {
Eugene Zelenko5dc60fe2017-12-04 23:16:21 +00001048 std::vector<CommentHandler *>::iterator Pos =
1049 std::find(CommentHandlers.begin(), CommentHandlers.end(), Handler);
Douglas Gregorc6d5edd2009-07-02 17:08:52 +00001050 assert(Pos != CommentHandlers.end() && "Comment handler not registered");
1051 CommentHandlers.erase(Pos);
1052}
1053
Chris Lattner87d02082010-01-18 22:35:47 +00001054bool Preprocessor::HandleComment(Token &result, SourceRange Comment) {
1055 bool AnyPendingTokens = false;
Douglas Gregorc6d5edd2009-07-02 17:08:52 +00001056 for (std::vector<CommentHandler *>::iterator H = CommentHandlers.begin(),
1057 HEnd = CommentHandlers.end();
Chris Lattner87d02082010-01-18 22:35:47 +00001058 H != HEnd; ++H) {
1059 if ((*H)->HandleComment(*this, Comment))
1060 AnyPendingTokens = true;
1061 }
1062 if (!AnyPendingTokens || getCommentRetentionState())
1063 return false;
1064 Lex(result);
1065 return true;
Douglas Gregorc6d5edd2009-07-02 17:08:52 +00001066}
1067
Eugene Zelenko5dc60fe2017-12-04 23:16:21 +00001068ModuleLoader::~ModuleLoader() = default;
Douglas Gregor08142532011-08-26 23:56:07 +00001069
Eugene Zelenko5dc60fe2017-12-04 23:16:21 +00001070CommentHandler::~CommentHandler() = default;
Douglas Gregor7f6d60d2010-03-19 16:15:56 +00001071
Eugene Zelenko5dc60fe2017-12-04 23:16:21 +00001072CodeCompletionHandler::~CodeCompletionHandler() = default;
Douglas Gregor3a7ad252010-08-24 19:08:16 +00001073
Argyrios Kyrtzidisf3d587e2012-12-04 07:27:05 +00001074void Preprocessor::createPreprocessingRecord() {
Douglas Gregor7f6d60d2010-03-19 16:15:56 +00001075 if (Record)
1076 return;
Fangrui Song6907ce22018-07-30 19:24:48 +00001077
Argyrios Kyrtzidisf3d587e2012-12-04 07:27:05 +00001078 Record = new PreprocessingRecord(getSourceManager());
Craig Topperb8a70532014-09-10 04:53:53 +00001079 addPPCallbacks(std::unique_ptr<PPCallbacks>(Record));
Douglas Gregor7f6d60d2010-03-19 16:15:56 +00001080}