blob: c291a4b99d101586b96d5c14f8350bcd0becbd82 [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),
88 FileMgr(Headers.getFileMgr()), SourceMgr(SM),
Duncan P. N. Exon Smith030d7d62017-03-20 17:58:26 +000089 PCMCache(PCMCache), ScratchBuf(new ScratchBuffer(SourceMgr)),
90 HeaderInfo(Headers), TheModuleLoader(TheModuleLoader),
91 ExternalSource(nullptr), Identifiers(opts, IILookup),
Eugene Zelenko5dc60fe2017-12-04 23:16:21 +000092 PragmaHandlers(new PragmaNamespace(StringRef())), TUKind(TUKind),
93 SkipMainFilePreamble(0, true),
94 CurSubmoduleState(&NullSubmoduleState) {
Daniel Dunbar0c6c9302009-11-11 21:44:21 +000095 OwnsHeaderSearch = OwnsHeaders;
Douglas Gregor83297df2011-09-01 23:39:15 +000096
Douglas Gregor83297df2011-09-01 23:39:15 +000097 // Default to discarding comments.
98 KeepComments = false;
99 KeepMacroComments = false;
100 SuppressIncludeNotFoundError = false;
101
102 // 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();
128
129 // Initialize builtin macros like __LINE__ and friends.
130 RegisterBuiltinMacros();
131
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
150 if (this->PPOpts->GeneratePreamble)
151 PreambleConditionalStack.startRecording();
Argyrios Kyrtzidis3c9aaf12012-06-02 18:08:09 +0000152}
153
154Preprocessor::~Preprocessor() {
155 assert(BacktrackPositions.empty() && "EnableBacktrack/Backtrack imbalance!");
156
Benjamin Kramer329c5962014-03-15 16:40:40 +0000157 IncludeMacroStack.clear();
Argyrios Kyrtzidis3c9aaf12012-06-02 18:08:09 +0000158
Richard Smith73a29662014-07-24 03:25:00 +0000159 // Destroy any macro definitions.
160 while (MacroInfoChain *I = MIChainHead) {
161 MIChainHead = I->Next;
162 I->~MacroInfoChain();
163 }
Argyrios Kyrtzidis3c9aaf12012-06-02 18:08:09 +0000164
165 // Free any cached macro expanders.
Nico Weber5f5b9412014-05-09 18:09:42 +0000166 // This populates MacroArgCache, so all TokenLexers need to be destroyed
167 // before the code below that frees up the MacroArgCache list.
David Blaikie6d5038c2014-08-29 19:36:52 +0000168 std::fill(TokenLexerCache, TokenLexerCache + NumCachedTokenLexers, nullptr);
Nico Weber5f5b9412014-05-09 18:09:42 +0000169 CurTokenLexer.reset();
Argyrios Kyrtzidis3c9aaf12012-06-02 18:08:09 +0000170
171 // Free any cached MacroArgs.
Nico Weber5f5b9412014-05-09 18:09:42 +0000172 for (MacroArgs *ArgList = MacroArgCache; ArgList;)
Argyrios Kyrtzidis3c9aaf12012-06-02 18:08:09 +0000173 ArgList = ArgList->deallocate();
174
Argyrios Kyrtzidis3c9aaf12012-06-02 18:08:09 +0000175 // Delete the header search info, if we own it.
176 if (OwnsHeaderSearch)
177 delete &HeaderInfo;
Argyrios Kyrtzidis3c9aaf12012-06-02 18:08:09 +0000178}
179
Artem Belevichb5bc9232015-09-22 17:23:22 +0000180void Preprocessor::Initialize(const TargetInfo &Target,
181 const TargetInfo *AuxTarget) {
Argyrios Kyrtzidis3c9aaf12012-06-02 18:08:09 +0000182 assert((!this->Target || this->Target == &Target) &&
183 "Invalid override of target information");
184 this->Target = &Target;
Artem Belevichb5bc9232015-09-22 17:23:22 +0000185
186 assert((!this->AuxTarget || this->AuxTarget == AuxTarget) &&
187 "Invalid override of aux target information.");
188 this->AuxTarget = AuxTarget;
189
Argyrios Kyrtzidis3c9aaf12012-06-02 18:08:09 +0000190 // Initialize information about built-ins.
Artem Belevichb5bc9232015-09-22 17:23:22 +0000191 BuiltinInfo.InitializeTarget(Target, AuxTarget);
Douglas Gregor89929282012-01-30 06:01:29 +0000192 HeaderInfo.setTarget(Target);
Douglas Gregor83297df2011-09-01 23:39:15 +0000193}
194
Ted Kremenekeeccb302014-08-27 15:14:15 +0000195void Preprocessor::InitializeForModelFile() {
196 NumEnteredSourceFiles = 0;
197
198 // Reset pragmas
David Blaikie9f0af9d2014-09-15 21:31:42 +0000199 PragmaHandlersBackup = std::move(PragmaHandlers);
Craig Topperbe250302014-09-12 05:19:24 +0000200 PragmaHandlers = llvm::make_unique<PragmaNamespace>(StringRef());
Ted Kremenekeeccb302014-08-27 15:14:15 +0000201 RegisterBuiltinPragmas();
202
203 // Reset PredefinesFileID
204 PredefinesFileID = FileID();
205}
206
207void Preprocessor::FinalizeForModelFile() {
208 NumEnteredSourceFiles = 1;
209
David Blaikie9f0af9d2014-09-15 21:31:42 +0000210 PragmaHandlers = std::move(PragmaHandlersBackup);
Ted Kremenekeeccb302014-08-27 15:14:15 +0000211}
212
Ted Kremeneka5c2c272009-02-12 03:26:59 +0000213void Preprocessor::setPTHManager(PTHManager* pm) {
214 PTH.reset(pm);
Douglas Gregord2eb58a2009-10-16 18:18:30 +0000215 FileMgr.addStatCache(PTH->createStatCache());
Ted Kremeneka5c2c272009-02-12 03:26:59 +0000216}
217
Chris Lattner146762e2007-07-20 16:59:19 +0000218void Preprocessor::DumpToken(const Token &Tok, bool DumpFlags) const {
Benjamin Kramer89b422c2009-08-23 12:08:50 +0000219 llvm::errs() << tok::getTokenName(Tok.getKind()) << " '"
220 << getSpelling(Tok) << "'";
Mike Stump11289f42009-09-09 15:08:12 +0000221
Chris Lattnerd01e2912006-06-18 16:22:51 +0000222 if (!DumpFlags) return;
Mike Stump11289f42009-09-09 15:08:12 +0000223
Benjamin Kramer89b422c2009-08-23 12:08:50 +0000224 llvm::errs() << "\t";
Chris Lattnerd01e2912006-06-18 16:22:51 +0000225 if (Tok.isAtStartOfLine())
Benjamin Kramer89b422c2009-08-23 12:08:50 +0000226 llvm::errs() << " [StartOfLine]";
Chris Lattnerd01e2912006-06-18 16:22:51 +0000227 if (Tok.hasLeadingSpace())
Benjamin Kramer89b422c2009-08-23 12:08:50 +0000228 llvm::errs() << " [LeadingSpace]";
Chris Lattner6e4bf522006-07-27 06:59:25 +0000229 if (Tok.isExpandDisabled())
Benjamin Kramer89b422c2009-08-23 12:08:50 +0000230 llvm::errs() << " [ExpandDisabled]";
Chris Lattnerd01e2912006-06-18 16:22:51 +0000231 if (Tok.needsCleaning()) {
Chris Lattner50b497e2006-06-18 16:32:35 +0000232 const char *Start = SourceMgr.getCharacterData(Tok.getLocation());
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000233 llvm::errs() << " [UnClean='" << StringRef(Start, Tok.getLength())
Benjamin Kramer89b422c2009-08-23 12:08:50 +0000234 << "']";
Chris Lattnerd01e2912006-06-18 16:22:51 +0000235 }
Mike Stump11289f42009-09-09 15:08:12 +0000236
Benjamin Kramer89b422c2009-08-23 12:08:50 +0000237 llvm::errs() << "\tLoc=<";
Chris Lattner615315f2007-12-09 20:31:55 +0000238 DumpLocation(Tok.getLocation());
Benjamin Kramer89b422c2009-08-23 12:08:50 +0000239 llvm::errs() << ">";
Chris Lattner615315f2007-12-09 20:31:55 +0000240}
241
242void Preprocessor::DumpLocation(SourceLocation Loc) const {
Chris Lattnerf1ca7d32009-01-27 07:57:44 +0000243 Loc.dump(SourceMgr);
Chris Lattnerd01e2912006-06-18 16:22:51 +0000244}
245
246void Preprocessor::DumpMacro(const MacroInfo &MI) const {
Benjamin Kramer89b422c2009-08-23 12:08:50 +0000247 llvm::errs() << "MACRO: ";
Chris Lattnerd01e2912006-06-18 16:22:51 +0000248 for (unsigned i = 0, e = MI.getNumTokens(); i != e; ++i) {
249 DumpToken(MI.getReplacementToken(i));
Benjamin Kramer89b422c2009-08-23 12:08:50 +0000250 llvm::errs() << " ";
Chris Lattnerd01e2912006-06-18 16:22:51 +0000251 }
Benjamin Kramer89b422c2009-08-23 12:08:50 +0000252 llvm::errs() << "\n";
Chris Lattnerd01e2912006-06-18 16:22:51 +0000253}
254
Chris Lattner22eb9722006-06-18 05:43:12 +0000255void Preprocessor::PrintStats() {
Benjamin Kramer89b422c2009-08-23 12:08:50 +0000256 llvm::errs() << "\n*** Preprocessor Stats:\n";
257 llvm::errs() << NumDirectives << " directives found:\n";
258 llvm::errs() << " " << NumDefined << " #define.\n";
259 llvm::errs() << " " << NumUndefined << " #undef.\n";
260 llvm::errs() << " #include/#include_next/#import:\n";
261 llvm::errs() << " " << NumEnteredSourceFiles << " source files entered.\n";
262 llvm::errs() << " " << MaxIncludeStackDepth << " max include stack depth\n";
263 llvm::errs() << " " << NumIf << " #if/#ifndef/#ifdef.\n";
264 llvm::errs() << " " << NumElse << " #else/#elif.\n";
265 llvm::errs() << " " << NumEndif << " #endif.\n";
266 llvm::errs() << " " << NumPragma << " #pragma.\n";
267 llvm::errs() << NumSkipped << " #if/#ifndef#ifdef regions skipped\n";
Chris Lattner22eb9722006-06-18 05:43:12 +0000268
Benjamin Kramer89b422c2009-08-23 12:08:50 +0000269 llvm::errs() << NumMacroExpanded << "/" << NumFnMacroExpanded << "/"
Ted Kremeneka0a3e9b2008-01-14 16:44:48 +0000270 << NumBuiltinMacroExpanded << " obj/fn/builtin macros expanded, "
271 << NumFastMacroExpanded << " on the fast path.\n";
Benjamin Kramer89b422c2009-08-23 12:08:50 +0000272 llvm::errs() << (NumFastTokenPaste+NumTokenPaste)
Ted Kremeneka0a3e9b2008-01-14 16:44:48 +0000273 << " token paste (##) operations performed, "
274 << NumFastTokenPaste << " on the fast path.\n";
Alexander Kornienko199cd942012-08-13 10:46:42 +0000275
276 llvm::errs() << "\nPreprocessor Memory: " << getTotalMemory() << "B total";
277
278 llvm::errs() << "\n BumpPtr: " << BP.getTotalMemory();
279 llvm::errs() << "\n Macro Expanded Tokens: "
280 << llvm::capacity_in_bytes(MacroExpandedTokens);
281 llvm::errs() << "\n Predefines Buffer: " << Predefines.capacity();
Richard Smith04765ae2015-05-21 01:20:10 +0000282 // FIXME: List information for all submodules.
283 llvm::errs() << "\n Macros: "
284 << llvm::capacity_in_bytes(CurSubmoduleState->Macros);
Alexander Kornienko199cd942012-08-13 10:46:42 +0000285 llvm::errs() << "\n #pragma push_macro Info: "
286 << llvm::capacity_in_bytes(PragmaPushMacroInfo);
287 llvm::errs() << "\n Poison Reasons: "
288 << llvm::capacity_in_bytes(PoisonReasons);
289 llvm::errs() << "\n Comment Handlers: "
290 << llvm::capacity_in_bytes(CommentHandlers) << "\n";
Chris Lattner22eb9722006-06-18 05:43:12 +0000291}
292
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +0000293Preprocessor::macro_iterator
294Preprocessor::macro_begin(bool IncludeExternalMacros) const {
295 if (IncludeExternalMacros && ExternalSource &&
Douglas Gregor9882a5a2010-01-04 19:18:44 +0000296 !ReadMacrosFromExternalSource) {
297 ReadMacrosFromExternalSource = true;
298 ExternalSource->ReadDefinedMacros();
299 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +0000300
Jordan Rosea46bfa62015-06-24 19:27:02 +0000301 // Make sure we cover all macros in visible modules.
302 for (const ModuleMacro &Macro : ModuleMacros)
303 CurSubmoduleState->Macros.insert(std::make_pair(Macro.II, MacroState()));
304
Richard Smith04765ae2015-05-21 01:20:10 +0000305 return CurSubmoduleState->Macros.begin();
Douglas Gregor9882a5a2010-01-04 19:18:44 +0000306}
307
Argyrios Kyrtzidise379ee32011-06-29 22:20:04 +0000308size_t Preprocessor::getTotalMemory() const {
Ted Kremenek182543a2011-07-26 21:17:24 +0000309 return BP.getTotalMemory()
Ted Kremenek8b77fe72011-07-27 18:41:23 +0000310 + llvm::capacity_in_bytes(MacroExpandedTokens)
Ted Kremenek182543a2011-07-26 21:17:24 +0000311 + Predefines.capacity() /* Predefines buffer. */
Richard Smith04765ae2015-05-21 01:20:10 +0000312 // FIXME: Include sizes from all submodules, and include MacroInfo sizes,
313 // and ModuleMacros.
314 + llvm::capacity_in_bytes(CurSubmoduleState->Macros)
Ted Kremenek8b77fe72011-07-27 18:41:23 +0000315 + llvm::capacity_in_bytes(PragmaPushMacroInfo)
316 + llvm::capacity_in_bytes(PoisonReasons)
317 + llvm::capacity_in_bytes(CommentHandlers);
Argyrios Kyrtzidise379ee32011-06-29 22:20:04 +0000318}
319
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +0000320Preprocessor::macro_iterator
321Preprocessor::macro_end(bool IncludeExternalMacros) const {
322 if (IncludeExternalMacros && ExternalSource &&
Douglas Gregor9882a5a2010-01-04 19:18:44 +0000323 !ReadMacrosFromExternalSource) {
324 ReadMacrosFromExternalSource = true;
325 ExternalSource->ReadDefinedMacros();
326 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +0000327
Richard Smith04765ae2015-05-21 01:20:10 +0000328 return CurSubmoduleState->Macros.end();
Douglas Gregor9882a5a2010-01-04 19:18:44 +0000329}
330
Dmitri Gribenko6743e042012-09-29 11:40:46 +0000331/// \brief Compares macro tokens with a specified token value sequence.
332static bool MacroDefinitionEquals(const MacroInfo *MI,
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000333 ArrayRef<TokenValue> Tokens) {
Dmitri Gribenko6743e042012-09-29 11:40:46 +0000334 return Tokens.size() == MI->getNumTokens() &&
335 std::equal(Tokens.begin(), Tokens.end(), MI->tokens_begin());
336}
337
338StringRef Preprocessor::getLastMacroWithSpelling(
339 SourceLocation Loc,
340 ArrayRef<TokenValue> Tokens) const {
341 SourceLocation BestLocation;
342 StringRef BestSpelling;
343 for (Preprocessor::macro_iterator I = macro_begin(), E = macro_end();
344 I != E; ++I) {
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +0000345 const MacroDirective::DefInfo
Richard Smithb8b2ed62015-04-23 18:18:26 +0000346 Def = I->second.findDirectiveAtLoc(Loc, SourceMgr);
Argyrios Kyrtzidis5c585252015-03-04 16:03:07 +0000347 if (!Def || !Def.getMacroInfo())
348 continue;
349 if (!Def.getMacroInfo()->isObjectLike())
Dmitri Gribenko6743e042012-09-29 11:40:46 +0000350 continue;
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +0000351 if (!MacroDefinitionEquals(Def.getMacroInfo(), Tokens))
Dmitri Gribenko6743e042012-09-29 11:40:46 +0000352 continue;
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +0000353 SourceLocation Location = Def.getLocation();
Dmitri Gribenko6743e042012-09-29 11:40:46 +0000354 // Choose the macro defined latest.
355 if (BestLocation.isInvalid() ||
356 (Location.isValid() &&
357 SourceMgr.isBeforeInTranslationUnit(BestLocation, Location))) {
358 BestLocation = Location;
359 BestSpelling = I->first->getName();
360 }
361 }
362 return BestSpelling;
363}
364
Douglas Gregor8d76cca2012-01-04 06:20:15 +0000365void Preprocessor::recomputeCurLexerKind() {
366 if (CurLexer)
367 CurLexerKind = CLK_Lexer;
368 else if (CurPTHLexer)
369 CurLexerKind = CLK_PTHLexer;
370 else if (CurTokenLexer)
371 CurLexerKind = CLK_TokenLexer;
372 else
373 CurLexerKind = CLK_CachingLexer;
374}
375
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +0000376bool Preprocessor::SetCodeCompletionPoint(const FileEntry *File,
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +0000377 unsigned CompleteLine,
378 unsigned CompleteColumn) {
379 assert(File);
380 assert(CompleteLine && CompleteColumn && "Starts from 1:1");
381 assert(!CodeCompletionFile && "Already set");
382
Douglas Gregor53ad6b92009-12-02 06:49:09 +0000383 using llvm::MemoryBuffer;
384
Douglas Gregor53ad6b92009-12-02 06:49:09 +0000385 // Load the actual file's contents.
Douglas Gregor26266da2010-03-16 19:49:24 +0000386 bool Invalid = false;
387 const MemoryBuffer *Buffer = SourceMgr.getMemoryBufferForFile(File, &Invalid);
388 if (Invalid)
Douglas Gregor53ad6b92009-12-02 06:49:09 +0000389 return true;
390
391 // Find the byte position of the truncation point.
392 const char *Position = Buffer->getBufferStart();
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +0000393 for (unsigned Line = 1; Line < CompleteLine; ++Line) {
Douglas Gregor53ad6b92009-12-02 06:49:09 +0000394 for (; *Position; ++Position) {
395 if (*Position != '\r' && *Position != '\n')
396 continue;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +0000397
Douglas Gregor53ad6b92009-12-02 06:49:09 +0000398 // Eat \r\n or \n\r as a single line.
399 if ((Position[1] == '\r' || Position[1] == '\n') &&
400 Position[0] != Position[1])
401 ++Position;
402 ++Position;
403 break;
404 }
405 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +0000406
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +0000407 Position += CompleteColumn - 1;
Argyrios Kyrtzidisee301f92014-10-18 06:23:50 +0000408
409 // If pointing inside the preamble, adjust the position at the beginning of
410 // the file after the preamble.
411 if (SkipMainFilePreamble.first &&
412 SourceMgr.getFileEntryForID(SourceMgr.getMainFileID()) == File) {
413 if (Position - Buffer->getBufferStart() < SkipMainFilePreamble.first)
414 Position = Buffer->getBufferStart() + SkipMainFilePreamble.first;
415 }
416
Argyrios Kyrtzidise62d6822014-10-18 06:19:36 +0000417 if (Position > Buffer->getBufferEnd())
418 Position = Buffer->getBufferEnd();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +0000419
Argyrios Kyrtzidise62d6822014-10-18 06:19:36 +0000420 CodeCompletionFile = File;
421 CodeCompletionOffset = Position - Buffer->getBufferStart();
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +0000422
Argyrios Kyrtzidise62d6822014-10-18 06:19:36 +0000423 std::unique_ptr<MemoryBuffer> NewBuffer =
424 MemoryBuffer::getNewUninitMemBuffer(Buffer->getBufferSize() + 1,
425 Buffer->getBufferIdentifier());
426 char *NewBuf = const_cast<char*>(NewBuffer->getBufferStart());
427 char *NewPos = std::copy(Buffer->getBufferStart(), Position, NewBuf);
428 *NewPos = '\0';
429 std::copy(Position, Buffer->getBufferEnd(), NewPos+1);
430 SourceMgr.overrideFileContents(File, std::move(NewBuffer));
Douglas Gregor53ad6b92009-12-02 06:49:09 +0000431
432 return false;
433}
434
Douglas Gregor11583702010-08-25 17:04:25 +0000435void Preprocessor::CodeCompleteNaturalLanguage() {
Douglas Gregor11583702010-08-25 17:04:25 +0000436 if (CodeComplete)
437 CodeComplete->CodeCompleteNaturalLanguage();
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +0000438 setCodeCompletionReached();
Douglas Gregor11583702010-08-25 17:04:25 +0000439}
440
Benjamin Kramera197fb62010-02-27 17:05:45 +0000441/// getSpelling - This method is used to get the spelling of a token into a
442/// SmallVector. Note that the returned StringRef may not point to the
443/// supplied buffer if a copy can be avoided.
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000444StringRef Preprocessor::getSpelling(const Token &Tok,
445 SmallVectorImpl<char> &Buffer,
Douglas Gregor7bda4b82010-03-16 05:20:39 +0000446 bool *Invalid) const {
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +0000447 // NOTE: this has to be checked *before* testing for an IdentifierInfo.
Jordan Rose7f43ddd2013-01-24 20:50:46 +0000448 if (Tok.isNot(tok::raw_identifier) && !Tok.hasUCN()) {
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +0000449 // Try the fast path.
450 if (const IdentifierInfo *II = Tok.getIdentifierInfo())
451 return II->getName();
452 }
Benjamin Kramera197fb62010-02-27 17:05:45 +0000453
454 // Resize the buffer if we need to copy into it.
455 if (Tok.needsCleaning())
456 Buffer.resize(Tok.getLength());
457
458 const char *Ptr = Buffer.data();
Douglas Gregor7bda4b82010-03-16 05:20:39 +0000459 unsigned Len = getSpelling(Tok, Ptr, Invalid);
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000460 return StringRef(Ptr, Len);
Benjamin Kramera197fb62010-02-27 17:05:45 +0000461}
462
Chris Lattnerb94ec7b2006-07-14 06:54:10 +0000463/// CreateString - Plop the specified string into a scratch buffer and return a
464/// location for it. If specified, the source location provides a source
465/// location for the token.
Dmitri Gribenkob8e9e752012-09-24 21:07:17 +0000466void Preprocessor::CreateString(StringRef Str, Token &Tok,
Abramo Bagnarae398e602011-10-03 18:39:03 +0000467 SourceLocation ExpansionLocStart,
468 SourceLocation ExpansionLocEnd) {
Dmitri Gribenkob8e9e752012-09-24 21:07:17 +0000469 Tok.setLength(Str.size());
Mike Stump11289f42009-09-09 15:08:12 +0000470
Chris Lattner5a7971e2009-01-26 19:29:26 +0000471 const char *DestPtr;
Dmitri Gribenkob8e9e752012-09-24 21:07:17 +0000472 SourceLocation Loc = ScratchBuf->getToken(Str.data(), Str.size(), DestPtr);
Mike Stump11289f42009-09-09 15:08:12 +0000473
Abramo Bagnarae398e602011-10-03 18:39:03 +0000474 if (ExpansionLocStart.isValid())
475 Loc = SourceMgr.createExpansionLoc(Loc, ExpansionLocStart,
Dmitri Gribenkob8e9e752012-09-24 21:07:17 +0000476 ExpansionLocEnd, Str.size());
Chris Lattner5a7971e2009-01-26 19:29:26 +0000477 Tok.setLocation(Loc);
Mike Stump11289f42009-09-09 15:08:12 +0000478
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +0000479 // If this is a raw identifier or a literal token, set the pointer data.
480 if (Tok.is(tok::raw_identifier))
481 Tok.setRawIdentifierData(DestPtr);
482 else if (Tok.isLiteral())
Chris Lattner5a7971e2009-01-26 19:29:26 +0000483 Tok.setLiteralData(DestPtr);
Chris Lattnerb94ec7b2006-07-14 06:54:10 +0000484}
485
Douglas Gregor2b82c2a2011-12-02 01:47:07 +0000486Module *Preprocessor::getCurrentModule() {
Richard Smithbbcc9f02016-08-26 00:14:38 +0000487 if (!getLangOpts().isCompilingModule())
Craig Topperd2d442c2014-05-17 23:10:59 +0000488 return nullptr;
489
David Blaikiebbafb8a2012-03-11 07:00:24 +0000490 return getHeaderSearchInfo().lookupModule(getLangOpts().CurrentModule);
Douglas Gregor2b82c2a2011-12-02 01:47:07 +0000491}
Chris Lattner8a7003c2007-07-16 06:48:38 +0000492
Chris Lattner1f1b0db2007-10-09 22:10:18 +0000493//===----------------------------------------------------------------------===//
494// Preprocessor Initialization Methods
495//===----------------------------------------------------------------------===//
496
Chris Lattner1f1b0db2007-10-09 22:10:18 +0000497/// EnterMainSourceFile - Enter the specified FileID as the main source file,
Nate Begemanf7c3ff62008-01-07 04:01:26 +0000498/// which implicitly adds the builtin defines etc.
Chris Lattnerfb24a3a2010-04-20 20:35:58 +0000499void Preprocessor::EnterMainSourceFile() {
Chris Lattner9ef847b2009-02-13 19:33:24 +0000500 // We do not allow the preprocessor to reenter the main file. Doing so will
501 // cause FileID's to accumulate information from both runs (e.g. #line
502 // information) and predefined macros aren't guaranteed to be set properly.
503 assert(NumEnteredSourceFiles == 0 && "Cannot reenter the main file!");
Chris Lattnerd32480d2009-01-17 06:22:33 +0000504 FileID MainFileID = SourceMgr.getMainFileID();
Mike Stump11289f42009-09-09 15:08:12 +0000505
Argyrios Kyrtzidis9afd4492012-01-05 21:36:25 +0000506 // If MainFileID is loaded it means we loaded an AST file, no need to enter
507 // a main file.
508 if (!SourceMgr.isLoadedFileID(MainFileID)) {
509 // Enter the main file source buffer.
Craig Topperd2d442c2014-05-17 23:10:59 +0000510 EnterSourceFile(MainFileID, nullptr, SourceLocation());
511
Argyrios Kyrtzidis9afd4492012-01-05 21:36:25 +0000512 // If we've been asked to skip bytes in the main file (e.g., as part of a
513 // precompiled preamble), do so now.
514 if (SkipMainFilePreamble.first > 0)
Cameron Desrochers84fd0642017-09-20 19:03:37 +0000515 CurLexer->SetByteOffset(SkipMainFilePreamble.first,
516 SkipMainFilePreamble.second);
517
Argyrios Kyrtzidis9afd4492012-01-05 21:36:25 +0000518 // Tell the header info that the main file was entered. If the file is later
519 // #imported, it won't be re-entered.
520 if (const FileEntry *FE = SourceMgr.getFileEntryForID(MainFileID))
521 HeaderInfo.IncrementIncludeCount(FE);
522 }
Mike Stump11289f42009-09-09 15:08:12 +0000523
Benjamin Kramerd77adb52009-12-31 15:33:09 +0000524 // Preprocess Predefines to populate the initial preprocessor state.
Rafael Espindolad87f8d72014-08-27 20:03:29 +0000525 std::unique_ptr<llvm::MemoryBuffer> SB =
Chris Lattner58c79342010-04-05 22:42:27 +0000526 llvm::MemoryBuffer::getMemBufferCopy(Predefines, "<built-in>");
Douglas Gregor33551892010-08-26 14:07:34 +0000527 assert(SB && "Cannot create predefined source buffer");
David Blaikie50a5f972014-08-29 07:59:55 +0000528 FileID FID = SourceMgr.createFileID(std::move(SB));
Yaron Keren8b563662015-10-03 10:46:20 +0000529 assert(FID.isValid() && "Could not create FileID for predefines?");
Argyrios Kyrtzidis22c22f52013-02-01 16:36:07 +0000530 setPredefinesFileID(FID);
Mike Stump11289f42009-09-09 15:08:12 +0000531
Chris Lattner1f1b0db2007-10-09 22:10:18 +0000532 // Start parsing the predefines.
Craig Topperd2d442c2014-05-17 23:10:59 +0000533 EnterSourceFile(FID, nullptr, SourceLocation());
Erik Verbruggen795eee92017-07-05 09:44:07 +0000534}
Erik Verbruggenb34c79f2017-05-30 11:54:55 +0000535
Erik Verbruggen795eee92017-07-05 09:44:07 +0000536void Preprocessor::replayPreambleConditionalStack() {
Erik Verbruggenb34c79f2017-05-30 11:54:55 +0000537 // Restore the conditional stack from the preamble, if there is one.
538 if (PreambleConditionalStack.isReplaying()) {
Ilya Biryukovf3150002017-08-21 12:03:08 +0000539 assert(CurPPLexer &&
540 "CurPPLexer is null when calling replayPreambleConditionalStack.");
Erik Verbruggenb34c79f2017-05-30 11:54:55 +0000541 CurPPLexer->setConditionalLevels(PreambleConditionalStack.getStack());
542 PreambleConditionalStack.doneReplaying();
Erik Verbruggen4d1eb2d2017-11-03 09:40:07 +0000543 if (PreambleConditionalStack.reachedEOFWhileSkipping())
544 SkipExcludedConditionalBlock(
545 PreambleConditionalStack.SkipInfo->HashTokenLoc,
546 PreambleConditionalStack.SkipInfo->IfTokenLoc,
547 PreambleConditionalStack.SkipInfo->FoundNonSkipPortion,
548 PreambleConditionalStack.SkipInfo->FoundElse,
549 PreambleConditionalStack.SkipInfo->ElseLoc);
Erik Verbruggenb34c79f2017-05-30 11:54:55 +0000550 }
Chris Lattner1f1b0db2007-10-09 22:10:18 +0000551}
Chris Lattner8a7003c2007-07-16 06:48:38 +0000552
Daniel Dunbarcb9eaf52010-03-23 05:09:10 +0000553void Preprocessor::EndSourceFile() {
554 // Notify the client that we reached the end of the source file.
555 if (Callbacks)
556 Callbacks->EndOfMainFile();
557}
Chris Lattner677757a2006-06-28 05:26:32 +0000558
559//===----------------------------------------------------------------------===//
560// Lexer Event Handling.
561//===----------------------------------------------------------------------===//
562
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +0000563/// LookUpIdentifierInfo - Given a tok::raw_identifier token, look up the
564/// identifier information for the token and install it into the token,
565/// updating the token kind accordingly.
566IdentifierInfo *Preprocessor::LookUpIdentifierInfo(Token &Identifier) const {
Alp Toker2d57cea2014-05-17 04:53:25 +0000567 assert(!Identifier.getRawIdentifier().empty() && "No raw identifier data!");
Mike Stump11289f42009-09-09 15:08:12 +0000568
Chris Lattnercefc7682006-07-08 08:28:12 +0000569 // Look up this token, see if it is a macro, or if it is a language keyword.
570 IdentifierInfo *II;
Jordan Rose7f43ddd2013-01-24 20:50:46 +0000571 if (!Identifier.needsCleaning() && !Identifier.hasUCN()) {
Chris Lattnercefc7682006-07-08 08:28:12 +0000572 // No cleaning needed, just use the characters from the lexed buffer.
Alp Toker2d57cea2014-05-17 04:53:25 +0000573 II = getIdentifierInfo(Identifier.getRawIdentifier());
Chris Lattnercefc7682006-07-08 08:28:12 +0000574 } else {
575 // Cleaning needed, alloca a buffer, clean into it, then use the buffer.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +0000576 SmallString<64> IdentifierBuffer;
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000577 StringRef CleanedStr = getSpelling(Identifier, IdentifierBuffer);
Jordan Rose7f43ddd2013-01-24 20:50:46 +0000578
579 if (Identifier.hasUCN()) {
580 SmallString<64> UCNIdentifierBuffer;
581 expandUCNs(UCNIdentifierBuffer, CleanedStr);
582 II = getIdentifierInfo(UCNIdentifierBuffer);
583 } else {
584 II = getIdentifierInfo(CleanedStr);
585 }
Chris Lattnercefc7682006-07-08 08:28:12 +0000586 }
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +0000587
588 // Update the token info (identifier info and appropriate token kind).
Chris Lattner8c204872006-10-14 05:19:21 +0000589 Identifier.setIdentifierInfo(II);
Erich Keane33c3d8a2017-06-09 16:29:35 +0000590 if (getLangOpts().MSVCCompat && II->isCPlusPlusOperatorKeyword() &&
591 getSourceManager().isInSystemHeader(Identifier.getLocation()))
Eugene Zelenko5dc60fe2017-12-04 23:16:21 +0000592 Identifier.setKind(tok::identifier);
Erich Keane33c3d8a2017-06-09 16:29:35 +0000593 else
594 Identifier.setKind(II->getTokenID());
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +0000595
Chris Lattnercefc7682006-07-08 08:28:12 +0000596 return II;
597}
598
John Wiegley1c0675e2011-04-28 01:08:34 +0000599void Preprocessor::SetPoisonReason(IdentifierInfo *II, unsigned DiagID) {
600 PoisonReasons[II] = DiagID;
601}
602
603void Preprocessor::PoisonSEHIdentifiers(bool Poison) {
604 assert(Ident__exception_code && Ident__exception_info);
605 assert(Ident___exception_code && Ident___exception_info);
606 Ident__exception_code->setIsPoisoned(Poison);
607 Ident___exception_code->setIsPoisoned(Poison);
608 Ident_GetExceptionCode->setIsPoisoned(Poison);
609 Ident__exception_info->setIsPoisoned(Poison);
610 Ident___exception_info->setIsPoisoned(Poison);
611 Ident_GetExceptionInfo->setIsPoisoned(Poison);
612 Ident__abnormal_termination->setIsPoisoned(Poison);
613 Ident___abnormal_termination->setIsPoisoned(Poison);
614 Ident_AbnormalTermination->setIsPoisoned(Poison);
615}
616
617void Preprocessor::HandlePoisonedIdentifier(Token & Identifier) {
618 assert(Identifier.getIdentifierInfo() &&
619 "Can't handle identifiers without identifier info!");
620 llvm::DenseMap<IdentifierInfo*,unsigned>::const_iterator it =
621 PoisonReasons.find(Identifier.getIdentifierInfo());
622 if(it == PoisonReasons.end())
623 Diag(Identifier, diag::err_pp_used_poisoned_id);
624 else
625 Diag(Identifier,it->second) << Identifier.getIdentifierInfo();
626}
Chris Lattnercefc7682006-07-08 08:28:12 +0000627
Richard Smith31d51842015-05-14 04:00:59 +0000628/// \brief Returns a diagnostic message kind for reporting a future keyword as
629/// appropriate for the identifier and specified language.
630static diag::kind getFutureCompatDiagKind(const IdentifierInfo &II,
631 const LangOptions &LangOpts) {
632 assert(II.isFutureCompatKeyword() && "diagnostic should not be needed");
633
634 if (LangOpts.CPlusPlus)
635 return llvm::StringSwitch<diag::kind>(II.getName())
636#define CXX11_KEYWORD(NAME, FLAGS) \
637 .Case(#NAME, diag::warn_cxx11_keyword)
Richard Smith6c74e322017-08-13 21:32:33 +0000638#define CXX2A_KEYWORD(NAME, FLAGS) \
639 .Case(#NAME, diag::warn_cxx2a_keyword)
Richard Smith31d51842015-05-14 04:00:59 +0000640#include "clang/Basic/TokenKinds.def"
641 ;
642
643 llvm_unreachable(
644 "Keyword not known to come from a newer Standard or proposed Standard");
645}
646
Richard Smith3dba7eb2016-08-18 01:16:55 +0000647void Preprocessor::updateOutOfDateIdentifier(IdentifierInfo &II) const {
648 assert(II.isOutOfDate() && "not out of date");
649 getExternalSource()->updateOutOfDateIdentifier(II);
650}
651
Chris Lattner677757a2006-06-28 05:26:32 +0000652/// HandleIdentifier - This callback is invoked when the lexer reads an
653/// identifier. This callback looks up the identifier in the map and/or
654/// potentially macro expands it or turns it into a named token (like 'for').
Chris Lattnerad89ec02009-01-21 07:43:11 +0000655///
656/// Note that callers of this method are guarded by checking the
657/// IdentifierInfo's 'isHandleIdentifierCase' bit. If this method changes, the
658/// IdentifierInfo methods that compute these properties will need to change to
659/// match.
Eli Friedman0834a4b2013-09-19 00:41:32 +0000660bool Preprocessor::HandleIdentifier(Token &Identifier) {
Chris Lattner0f1f5052006-07-20 04:16:23 +0000661 assert(Identifier.getIdentifierInfo() &&
662 "Can't handle identifiers without identifier info!");
Mike Stump11289f42009-09-09 15:08:12 +0000663
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000664 IdentifierInfo &II = *Identifier.getIdentifierInfo();
Chris Lattner677757a2006-06-28 05:26:32 +0000665
Douglas Gregor935bc7a22011-10-27 09:33:13 +0000666 // If the information about this identifier is out of date, update it from
667 // the external source.
Douglas Gregor3f568c12012-06-29 18:27:59 +0000668 // We have to treat __VA_ARGS__ in a special way, since it gets
669 // serialized with isPoisoned = true, but our preprocessor may have
670 // unpoisoned it if we're defining a C99 macro.
Douglas Gregor935bc7a22011-10-27 09:33:13 +0000671 if (II.isOutOfDate()) {
Douglas Gregor3f568c12012-06-29 18:27:59 +0000672 bool CurrentIsPoisoned = false;
Faisal Vali18268422017-10-15 01:26:26 +0000673 const bool IsSpecialVariadicMacro =
674 &II == Ident__VA_ARGS__ || &II == Ident__VA_OPT__;
675 if (IsSpecialVariadicMacro)
676 CurrentIsPoisoned = II.isPoisoned();
Douglas Gregor3f568c12012-06-29 18:27:59 +0000677
Richard Smith3dba7eb2016-08-18 01:16:55 +0000678 updateOutOfDateIdentifier(II);
Douglas Gregor935bc7a22011-10-27 09:33:13 +0000679 Identifier.setKind(II.getTokenID());
Douglas Gregor3f568c12012-06-29 18:27:59 +0000680
Faisal Vali18268422017-10-15 01:26:26 +0000681 if (IsSpecialVariadicMacro)
Douglas Gregor3f568c12012-06-29 18:27:59 +0000682 II.setIsPoisoned(CurrentIsPoisoned);
Douglas Gregor935bc7a22011-10-27 09:33:13 +0000683 }
684
Chris Lattner677757a2006-06-28 05:26:32 +0000685 // If this identifier was poisoned, and if it was not produced from a macro
686 // expansion, emit an error.
Ted Kremeneka2c3c8d2008-11-19 22:43:49 +0000687 if (II.isPoisoned() && CurPPLexer) {
John Wiegley1c0675e2011-04-28 01:08:34 +0000688 HandlePoisonedIdentifier(Identifier);
Chris Lattner8ff71992006-07-06 05:17:39 +0000689 }
Mike Stump11289f42009-09-09 15:08:12 +0000690
Chris Lattner78186052006-07-09 00:45:31 +0000691 // If this is a macro to be expanded, do it.
Richard Smith20e883e2015-04-29 23:20:19 +0000692 if (MacroDefinition MD = getMacroDefinition(&II)) {
693 auto *MI = MD.getMacroInfo();
Richard Smithf5ec2ac2015-04-29 23:40:48 +0000694 assert(MI && "macro definition with no macro info?");
Abramo Bagnara123bec82012-01-01 22:01:04 +0000695 if (!DisableMacroExpansion) {
Richard Smith181879c2012-12-12 02:46:14 +0000696 if (!Identifier.isExpandDisabled() && MI->isEnabled()) {
Eli Friedman0834a4b2013-09-19 00:41:32 +0000697 // C99 6.10.3p10: If the preprocessing token immediately after the
698 // macro name isn't a '(', this macro should not be expanded.
699 if (!MI->isFunctionLike() || isNextPPTokenLParen())
700 return HandleMacroExpandedIdentifier(Identifier, MD);
Chris Lattner6e4bf522006-07-27 06:59:25 +0000701 } else {
702 // C99 6.10.3.4p2 says that a disabled macro may never again be
703 // expanded, even if it's in a context where it could be expanded in the
704 // future.
Chris Lattner146762e2007-07-20 16:59:19 +0000705 Identifier.setFlag(Token::DisableExpand);
Richard Smith181879c2012-12-12 02:46:14 +0000706 if (MI->isObjectLike() || isNextPPTokenLParen())
707 Diag(Identifier, diag::pp_disabled_macro_expansion);
Chris Lattner6e4bf522006-07-27 06:59:25 +0000708 }
709 }
Chris Lattner063400e2006-10-14 19:54:15 +0000710 }
Chris Lattner677757a2006-06-28 05:26:32 +0000711
Richard Smith31d51842015-05-14 04:00:59 +0000712 // If this identifier is a keyword in a newer Standard or proposed Standard,
713 // produce a warning. Don't warn if we're not considering macro expansion,
714 // since this identifier might be the name of a macro.
Richard Smith4dd85d62011-10-11 19:57:52 +0000715 // FIXME: This warning is disabled in cases where it shouldn't be, like
716 // "#define constexpr constexpr", "int constexpr;"
Richard Smith31d51842015-05-14 04:00:59 +0000717 if (II.isFutureCompatKeyword() && !DisableMacroExpansion) {
718 Diag(Identifier, getFutureCompatDiagKind(II, getLangOpts()))
719 << II.getName();
Richard Smith4dd85d62011-10-11 19:57:52 +0000720 // Don't diagnose this keyword again in this translation unit.
Richard Smith31d51842015-05-14 04:00:59 +0000721 II.setIsFutureCompatKeyword(false);
Richard Smith4dd85d62011-10-11 19:57:52 +0000722 }
723
Chris Lattner677757a2006-06-28 05:26:32 +0000724 // If this is an extension token, diagnose its use.
Steve Naroffc84e8b72008-09-02 18:50:17 +0000725 // We avoid diagnosing tokens that originate from macro definitions.
Eli Friedman6bba2ad2009-04-28 03:59:15 +0000726 // FIXME: This warning is disabled in cases where it shouldn't be,
727 // like "#define TY typeof", "TY(1) x".
728 if (II.isExtensionToken() && !DisableMacroExpansion)
Chris Lattner53621a52007-06-13 20:44:40 +0000729 Diag(Identifier, diag::ext_token_used);
Douglas Gregoraf5c4842011-09-07 23:11:54 +0000730
Douglas Gregor594b8c92013-11-07 22:55:02 +0000731 // If this is the 'import' contextual keyword following an '@', note
Ted Kremenekc1e4dd02012-03-01 22:07:04 +0000732 // that the next token indicates a module name.
Douglas Gregor8d76cca2012-01-04 06:20:15 +0000733 //
Douglas Gregorc50d4922012-12-11 22:11:52 +0000734 // Note that we do not treat 'import' as a contextual
Ted Kremenekc1e4dd02012-03-01 22:07:04 +0000735 // keyword when we're in a caching lexer, because caching lexers only get
736 // used in contexts where import declarations are disallowed.
Richard Smith49cc1cc2016-08-18 21:59:42 +0000737 //
738 // Likewise if this is the C++ Modules TS import keyword.
739 if (((LastTokenWasAt && II.isModulesImport()) ||
740 Identifier.is(tok::kw_import)) &&
741 !InMacroArgs && !DisableMacroExpansion &&
742 (getLangOpts().Modules || getLangOpts().DebuggerSupport) &&
Douglas Gregor594b8c92013-11-07 22:55:02 +0000743 CurLexerKind != CLK_CachingLexer) {
Douglas Gregoraf5c4842011-09-07 23:11:54 +0000744 ModuleImportLoc = Identifier.getLocation();
Douglas Gregor1805b8a2011-11-30 04:26:53 +0000745 ModuleImportPath.clear();
746 ModuleImportExpectsIdentifier = true;
Douglas Gregoraf5c4842011-09-07 23:11:54 +0000747 CurLexerKind = CLK_LexAfterModuleImport;
748 }
Eli Friedman0834a4b2013-09-19 00:41:32 +0000749 return true;
Douglas Gregor08142532011-08-26 23:56:07 +0000750}
751
Eli Friedman0834a4b2013-09-19 00:41:32 +0000752void Preprocessor::Lex(Token &Result) {
Yaron Keren716f3a62015-09-29 16:51:08 +0000753 // We loop here until a lex function returns a token; this avoids recursion.
Eli Friedman0834a4b2013-09-19 00:41:32 +0000754 bool ReturnedToken;
755 do {
756 switch (CurLexerKind) {
757 case CLK_Lexer:
758 ReturnedToken = CurLexer->Lex(Result);
759 break;
760 case CLK_PTHLexer:
761 ReturnedToken = CurPTHLexer->Lex(Result);
762 break;
763 case CLK_TokenLexer:
764 ReturnedToken = CurTokenLexer->Lex(Result);
765 break;
766 case CLK_CachingLexer:
767 CachingLex(Result);
768 ReturnedToken = true;
769 break;
770 case CLK_LexAfterModuleImport:
771 LexAfterModuleImport(Result);
772 ReturnedToken = true;
773 break;
774 }
775 } while (!ReturnedToken);
Douglas Gregor594b8c92013-11-07 22:55:02 +0000776
Vassil Vassilev644ea612016-07-27 14:56:59 +0000777 if (Result.is(tok::code_completion))
778 setCodeCompletionIdentifierInfo(Result.getIdentifierInfo());
779
Douglas Gregor594b8c92013-11-07 22:55:02 +0000780 LastTokenWasAt = Result.is(tok::at);
Eli Friedman0834a4b2013-09-19 00:41:32 +0000781}
782
Douglas Gregorda82e702012-01-03 19:32:59 +0000783/// \brief Lex a token following the 'import' contextual keyword.
Douglas Gregor22d09742012-01-03 18:04:46 +0000784///
Douglas Gregoraf5c4842011-09-07 23:11:54 +0000785void Preprocessor::LexAfterModuleImport(Token &Result) {
786 // Figure out what kind of lexer we actually have.
Douglas Gregor8d76cca2012-01-04 06:20:15 +0000787 recomputeCurLexerKind();
Douglas Gregoraf5c4842011-09-07 23:11:54 +0000788
789 // Lex the next token.
790 Lex(Result);
791
Douglas Gregor08142532011-08-26 23:56:07 +0000792 // The token sequence
793 //
Douglas Gregor22d09742012-01-03 18:04:46 +0000794 // import identifier (. identifier)*
795 //
Douglas Gregorda82e702012-01-03 19:32:59 +0000796 // indicates a module import directive. We already saw the 'import'
797 // contextual keyword, so now we're looking for the identifiers.
Douglas Gregor1805b8a2011-11-30 04:26:53 +0000798 if (ModuleImportExpectsIdentifier && Result.getKind() == tok::identifier) {
799 // We expected to see an identifier here, and we did; continue handling
800 // identifiers.
801 ModuleImportPath.push_back(std::make_pair(Result.getIdentifierInfo(),
802 Result.getLocation()));
803 ModuleImportExpectsIdentifier = false;
804 CurLexerKind = CLK_LexAfterModuleImport;
Douglas Gregor08142532011-08-26 23:56:07 +0000805 return;
Douglas Gregor1805b8a2011-11-30 04:26:53 +0000806 }
Douglas Gregor08142532011-08-26 23:56:07 +0000807
Douglas Gregor1805b8a2011-11-30 04:26:53 +0000808 // If we're expecting a '.' or a ';', and we got a '.', then wait until we
Richard Smith49cc1cc2016-08-18 21:59:42 +0000809 // see the next identifier. (We can also see a '[[' that begins an
810 // attribute-specifier-seq here under the C++ Modules TS.)
Douglas Gregor1805b8a2011-11-30 04:26:53 +0000811 if (!ModuleImportExpectsIdentifier && Result.getKind() == tok::period) {
812 ModuleImportExpectsIdentifier = true;
813 CurLexerKind = CLK_LexAfterModuleImport;
814 return;
815 }
816
817 // If we have a non-empty module path, load the named module.
Sean Callanan87596492014-12-09 23:47:56 +0000818 if (!ModuleImportPath.empty()) {
Richard Smithbbcc9f02016-08-26 00:14:38 +0000819 // Under the Modules TS, the dot is just part of the module name, and not
820 // a real hierarachy separator. Flatten such module names now.
821 //
822 // FIXME: Is this the right level to be performing this transformation?
823 std::string FlatModuleName;
824 if (getLangOpts().ModulesTS) {
825 for (auto &Piece : ModuleImportPath) {
826 if (!FlatModuleName.empty())
827 FlatModuleName += ".";
828 FlatModuleName += Piece.first->getName();
829 }
830 SourceLocation FirstPathLoc = ModuleImportPath[0].second;
831 ModuleImportPath.clear();
832 ModuleImportPath.push_back(
833 std::make_pair(getIdentifierInfo(FlatModuleName), FirstPathLoc));
834 }
835
Sean Callanan87596492014-12-09 23:47:56 +0000836 Module *Imported = nullptr;
Richard Smith753e0072015-04-27 23:21:38 +0000837 if (getLangOpts().Modules) {
Sean Callanan87596492014-12-09 23:47:56 +0000838 Imported = TheModuleLoader.loadModule(ModuleImportLoc,
839 ModuleImportPath,
Richard Smith10434f32015-05-02 02:08:26 +0000840 Module::Hidden,
Sean Callanan87596492014-12-09 23:47:56 +0000841 /*IsIncludeDirective=*/false);
Richard Smitha7e2cc62015-05-01 01:53:09 +0000842 if (Imported)
843 makeModuleVisible(Imported, ModuleImportLoc);
Richard Smith753e0072015-04-27 23:21:38 +0000844 }
Sean Callanan87596492014-12-09 23:47:56 +0000845 if (Callbacks && (getLangOpts().Modules || getLangOpts().DebuggerSupport))
Argyrios Kyrtzidis19d78b72012-09-29 01:06:10 +0000846 Callbacks->moduleImport(ModuleImportLoc, ModuleImportPath, Imported);
847 }
Chris Lattner677757a2006-06-28 05:26:32 +0000848}
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000849
Richard Smitha7e2cc62015-05-01 01:53:09 +0000850void Preprocessor::makeModuleVisible(Module *M, SourceLocation Loc) {
Richard Smith04765ae2015-05-21 01:20:10 +0000851 CurSubmoduleState->VisibleModules.setVisible(
Richard Smitha7e2cc62015-05-01 01:53:09 +0000852 M, Loc, [](Module *) {},
853 [&](ArrayRef<Module *> Path, Module *Conflict, StringRef Message) {
854 // FIXME: Include the path in the diagnostic.
855 // FIXME: Include the import location for the conflicting module.
856 Diag(ModuleImportLoc, diag::warn_module_conflict)
857 << Path[0]->getFullModuleName()
858 << Conflict->getFullModuleName()
859 << Message;
860 });
861
862 // Add this module to the imports list of the currently-built submodule.
Richard Smithdbbc5232015-05-14 02:25:44 +0000863 if (!BuildingSubmoduleStack.empty() && M != BuildingSubmoduleStack.back().M)
Richard Smith38477db2015-05-02 00:45:56 +0000864 BuildingSubmoduleStack.back().M->Imports.insert(M);
Richard Smitha7e2cc62015-05-01 01:53:09 +0000865}
866
Andy Gibbs58905d22012-11-17 19:15:38 +0000867bool Preprocessor::FinishLexStringLiteral(Token &Result, std::string &String,
Andy Gibbsa8df57a2012-11-17 19:16:52 +0000868 const char *DiagnosticTag,
Andy Gibbs58905d22012-11-17 19:15:38 +0000869 bool AllowMacroExpansion) {
870 // We need at least one string literal.
871 if (Result.isNot(tok::string_literal)) {
Andy Gibbsa8df57a2012-11-17 19:16:52 +0000872 Diag(Result, diag::err_expected_string_literal)
873 << /*Source='in...'*/0 << DiagnosticTag;
Andy Gibbs58905d22012-11-17 19:15:38 +0000874 return false;
875 }
876
877 // Lex string literal tokens, optionally with macro expansion.
878 SmallVector<Token, 4> StrToks;
879 do {
880 StrToks.push_back(Result);
881
882 if (Result.hasUDSuffix())
883 Diag(Result, diag::err_invalid_string_udl);
884
885 if (AllowMacroExpansion)
886 Lex(Result);
887 else
888 LexUnexpandedToken(Result);
889 } while (Result.is(tok::string_literal));
890
891 // Concatenate and parse the strings.
Craig Topper9d5583e2014-06-26 04:58:39 +0000892 StringLiteralParser Literal(StrToks, *this);
Andy Gibbs58905d22012-11-17 19:15:38 +0000893 assert(Literal.isAscii() && "Didn't allow wide strings in");
894
895 if (Literal.hadError)
896 return false;
897
898 if (Literal.Pascal) {
Andy Gibbsa8df57a2012-11-17 19:16:52 +0000899 Diag(StrToks[0].getLocation(), diag::err_expected_string_literal)
900 << /*Source='in...'*/0 << DiagnosticTag;
Andy Gibbs58905d22012-11-17 19:15:38 +0000901 return false;
902 }
903
904 String = Literal.GetString();
905 return true;
906}
907
Reid Klecknerc0dca6d2014-02-12 23:50:26 +0000908bool Preprocessor::parseSimpleIntegerLiteral(Token &Tok, uint64_t &Value) {
909 assert(Tok.is(tok::numeric_constant));
910 SmallString<8> IntegerBuffer;
911 bool NumberInvalid = false;
912 StringRef Spelling = getSpelling(Tok, IntegerBuffer, &NumberInvalid);
913 if (NumberInvalid)
914 return false;
915 NumericLiteralParser Literal(Spelling, Tok.getLocation(), *this);
916 if (Literal.hadError || !Literal.isIntegerLiteral() || Literal.hasUDSuffix())
917 return false;
918 llvm::APInt APVal(64, 0);
919 if (Literal.GetIntegerValue(APVal))
920 return false;
921 Lex(Tok);
922 Value = APVal.getLimitedValue();
923 return true;
924}
925
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000926void Preprocessor::addCommentHandler(CommentHandler *Handler) {
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000927 assert(Handler && "NULL comment handler");
928 assert(std::find(CommentHandlers.begin(), CommentHandlers.end(), Handler) ==
929 CommentHandlers.end() && "Comment handler already registered");
930 CommentHandlers.push_back(Handler);
931}
932
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000933void Preprocessor::removeCommentHandler(CommentHandler *Handler) {
Eugene Zelenko5dc60fe2017-12-04 23:16:21 +0000934 std::vector<CommentHandler *>::iterator Pos =
935 std::find(CommentHandlers.begin(), CommentHandlers.end(), Handler);
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000936 assert(Pos != CommentHandlers.end() && "Comment handler not registered");
937 CommentHandlers.erase(Pos);
938}
939
Chris Lattner87d02082010-01-18 22:35:47 +0000940bool Preprocessor::HandleComment(Token &result, SourceRange Comment) {
941 bool AnyPendingTokens = false;
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000942 for (std::vector<CommentHandler *>::iterator H = CommentHandlers.begin(),
943 HEnd = CommentHandlers.end();
Chris Lattner87d02082010-01-18 22:35:47 +0000944 H != HEnd; ++H) {
945 if ((*H)->HandleComment(*this, Comment))
946 AnyPendingTokens = true;
947 }
948 if (!AnyPendingTokens || getCommentRetentionState())
949 return false;
950 Lex(result);
951 return true;
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000952}
953
Eugene Zelenko5dc60fe2017-12-04 23:16:21 +0000954ModuleLoader::~ModuleLoader() = default;
Douglas Gregor08142532011-08-26 23:56:07 +0000955
Eugene Zelenko5dc60fe2017-12-04 23:16:21 +0000956CommentHandler::~CommentHandler() = default;
Douglas Gregor7f6d60d2010-03-19 16:15:56 +0000957
Eugene Zelenko5dc60fe2017-12-04 23:16:21 +0000958CodeCompletionHandler::~CodeCompletionHandler() = default;
Douglas Gregor3a7ad252010-08-24 19:08:16 +0000959
Argyrios Kyrtzidisf3d587e2012-12-04 07:27:05 +0000960void Preprocessor::createPreprocessingRecord() {
Douglas Gregor7f6d60d2010-03-19 16:15:56 +0000961 if (Record)
962 return;
963
Argyrios Kyrtzidisf3d587e2012-12-04 07:27:05 +0000964 Record = new PreprocessingRecord(getSourceManager());
Craig Topperb8a70532014-09-10 04:53:53 +0000965 addPPCallbacks(std::unique_ptr<PPCallbacks>(Record));
Douglas Gregor7f6d60d2010-03-19 16:15:56 +0000966}