blob: 94490bdf3fbfeb46bb0f155f422ecf6109c43557 [file] [log] [blame]
Eugene Zelenko5dc60fe2017-12-04 23:16:21 +00001//===- Preprocess.cpp - C Language Family Preprocessor Implementation -----===//
Chris Lattner22eb9722006-06-18 05:43:12 +00002//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner5b12ab82007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattner22eb9722006-06-18 05:43:12 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the Preprocessor interface.
11//
12//===----------------------------------------------------------------------===//
13//
Chris Lattner22eb9722006-06-18 05:43:12 +000014// Options to support:
15// -H - Print the name of each header file used.
Chris Lattner1630c3c2009-02-06 06:45:26 +000016// -d[DNI] - Dump various things.
Chris Lattner22eb9722006-06-18 05:43:12 +000017// -fworking-directory - #line's with preprocessor's working dir.
18// -fpreprocessed
19// -dependency-file,-M,-MM,-MF,-MG,-MP,-MT,-MQ,-MD,-MMD
20// -W*
21// -w
22//
23// Messages to emit:
24// "Multiple include guards may be useful for:\n"
25//
Chris Lattner22eb9722006-06-18 05:43:12 +000026//===----------------------------------------------------------------------===//
27
28#include "clang/Lex/Preprocessor.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000029#include "clang/Basic/FileManager.h"
David Blaikie23430cc2014-08-11 21:29:24 +000030#include "clang/Basic/FileSystemStatCache.h"
Eugene Zelenko5dc60fe2017-12-04 23:16:21 +000031#include "clang/Basic/IdentifierTable.h"
32#include "clang/Basic/LLVM.h"
33#include "clang/Basic/LangOptions.h"
34#include "clang/Basic/Module.h"
35#include "clang/Basic/SourceLocation.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000036#include "clang/Basic/SourceManager.h"
37#include "clang/Basic/TargetInfo.h"
38#include "clang/Lex/CodeCompletionHandler.h"
Douglas Gregor9882a5a2010-01-04 19:18:44 +000039#include "clang/Lex/ExternalPreprocessorSource.h"
Chris Lattner07b019a2006-10-22 07:28:56 +000040#include "clang/Lex/HeaderSearch.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000041#include "clang/Lex/LexDiagnostic.h"
Eugene Zelenko5dc60fe2017-12-04 23:16:21 +000042#include "clang/Lex/Lexer.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000043#include "clang/Lex/LiteralSupport.h"
Chandler Carruth5553d0d2014-01-07 11:51:46 +000044#include "clang/Lex/MacroArgs.h"
Chris Lattner22eb9722006-06-18 05:43:12 +000045#include "clang/Lex/MacroInfo.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000046#include "clang/Lex/ModuleLoader.h"
Eugene Zelenko5dc60fe2017-12-04 23:16:21 +000047#include "clang/Lex/PTHLexer.h"
Reid Kleckner738d48d2015-11-02 17:53:55 +000048#include "clang/Lex/PTHManager.h"
Chris Lattnerb8761832006-06-24 21:31:03 +000049#include "clang/Lex/Pragma.h"
Douglas Gregor7f6d60d2010-03-19 16:15:56 +000050#include "clang/Lex/PreprocessingRecord.h"
Eugene Zelenko5dc60fe2017-12-04 23:16:21 +000051#include "clang/Lex/PreprocessorLexer.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000052#include "clang/Lex/PreprocessorOptions.h"
Chris Lattner0b8cfc22006-06-28 06:49:17 +000053#include "clang/Lex/ScratchBuffer.h"
Eugene Zelenko5dc60fe2017-12-04 23:16:21 +000054#include "clang/Lex/Token.h"
55#include "clang/Lex/TokenLexer.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000056#include "llvm/ADT/APInt.h"
Eugene Zelenko5dc60fe2017-12-04 23:16:21 +000057#include "llvm/ADT/ArrayRef.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000058#include "llvm/ADT/DenseMap.h"
Chandler Carruth5553d0d2014-01-07 11:51:46 +000059#include "llvm/ADT/SmallString.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000060#include "llvm/ADT/SmallVector.h"
61#include "llvm/ADT/STLExtras.h"
62#include "llvm/ADT/StringRef.h"
Mehdi Amini9670f842016-07-18 19:02:11 +000063#include "llvm/ADT/StringSwitch.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000064#include "llvm/Support/Capacity.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000065#include "llvm/Support/ErrorHandling.h"
Chris Lattner8a7003c2007-07-16 06:48:38 +000066#include "llvm/Support/MemoryBuffer.h"
Benjamin Kramer89b422c2009-08-23 12:08:50 +000067#include "llvm/Support/raw_ostream.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000068#include <algorithm>
69#include <cassert>
70#include <memory>
71#include <string>
Benjamin Kramercfeacf52016-05-27 14:27:13 +000072#include <utility>
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000073#include <vector>
74
Chris Lattner22eb9722006-06-18 05:43:12 +000075using namespace clang;
76
John Brawn4d79ec72016-08-05 11:01:08 +000077LLVM_INSTANTIATE_REGISTRY(PragmaHandlerRegistry)
NAKAMURA Takumicacd94e2016-04-04 15:30:44 +000078
Eugene Zelenko5dc60fe2017-12-04 23:16:21 +000079ExternalPreprocessorSource::~ExternalPreprocessorSource() = default;
Chris Lattner22eb9722006-06-18 05:43:12 +000080
David Blaikiee3041682017-01-05 19:11:36 +000081Preprocessor::Preprocessor(std::shared_ptr<PreprocessorOptions> PPOpts,
Douglas Gregor1452ff12012-10-24 17:46:57 +000082 DiagnosticsEngine &diags, LangOptions &opts,
Duncan P. N. Exon Smith030d7d62017-03-20 17:58:26 +000083 SourceManager &SM, MemoryBufferCache &PCMCache,
84 HeaderSearch &Headers, ModuleLoader &TheModuleLoader,
David Blaikie687cd952013-01-16 23:13:36 +000085 IdentifierInfoLookup *IILookup, bool OwnsHeaders,
Alp Toker1ae02f62014-05-02 03:43:30 +000086 TranslationUnitKind TUKind)
Eugene Zelenko5dc60fe2017-12-04 23:16:21 +000087 : PPOpts(std::move(PPOpts)), Diags(&diags), LangOpts(opts),
Aaron Ballmand742dc22018-04-16 21:07:08 +000088 FileMgr(Headers.getFileMgr()), SourceMgr(SM), PCMCache(PCMCache),
89 ScratchBuf(new ScratchBuffer(SourceMgr)), HeaderInfo(Headers),
90 TheModuleLoader(TheModuleLoader), ExternalSource(nullptr),
91 // As the language options may have not been loaded yet (when
92 // deserializing an ASTUnit), adding keywords to the identifier table is
93 // deferred to Preprocessor::Initialize().
94 Identifiers(IILookup), PragmaHandlers(new PragmaNamespace(StringRef())),
95 TUKind(TUKind), SkipMainFilePreamble(0, true),
Eugene Zelenko5dc60fe2017-12-04 23:16:21 +000096 CurSubmoduleState(&NullSubmoduleState) {
Daniel Dunbar0c6c9302009-11-11 21:44:21 +000097 OwnsHeaderSearch = OwnsHeaders;
Douglas Gregor83297df2011-09-01 23:39:15 +000098
Douglas Gregor83297df2011-09-01 23:39:15 +000099 // Default to discarding comments.
100 KeepComments = false;
101 KeepMacroComments = false;
102 SuppressIncludeNotFoundError = false;
103
104 // Macro expansion is enabled.
105 DisableMacroExpansion = false;
David Blaikied5321242012-06-06 18:52:13 +0000106 MacroExpansionInDirectivesOverride = false;
Douglas Gregor83297df2011-09-01 23:39:15 +0000107 InMacroArgs = false;
Argyrios Kyrtzidisf1b64c62012-04-03 16:47:40 +0000108 InMacroArgPreExpansion = false;
Douglas Gregor83297df2011-09-01 23:39:15 +0000109 NumCachedTokenLexers = 0;
Jordan Rosede1a2922012-06-08 18:06:21 +0000110 PragmasEnabled = true;
Eric Christopher5e4696d2013-01-16 20:09:36 +0000111 ParsingIfOrElifDirective = false;
Jordan Rose324ec422013-01-31 19:26:01 +0000112 PreprocessedOutput = false;
Jordan Rosede1a2922012-06-08 18:06:21 +0000113
Douglas Gregor83297df2011-09-01 23:39:15 +0000114 // We haven't read anything from the external source.
115 ReadMacrosFromExternalSource = false;
Faisal Vali18268422017-10-15 01:26:26 +0000116
117 // "Poison" __VA_ARGS__, __VA_OPT__ which can only appear in the expansion of
118 // a macro. They get unpoisoned where it is allowed.
Douglas Gregor83297df2011-09-01 23:39:15 +0000119 (Ident__VA_ARGS__ = getIdentifierInfo("__VA_ARGS__"))->setIsPoisoned();
120 SetPoisonReason(Ident__VA_ARGS__,diag::ext_pp_bad_vaargs_use);
Faisal Vali18268422017-10-15 01:26:26 +0000121 if (getLangOpts().CPlusPlus2a) {
122 (Ident__VA_OPT__ = getIdentifierInfo("__VA_OPT__"))->setIsPoisoned();
123 SetPoisonReason(Ident__VA_OPT__,diag::ext_pp_bad_vaopt_use);
124 } else {
125 Ident__VA_OPT__ = nullptr;
126 }
127
Douglas Gregor83297df2011-09-01 23:39:15 +0000128 // Initialize the pragma handlers.
Douglas Gregor83297df2011-09-01 23:39:15 +0000129 RegisterBuiltinPragmas();
130
131 // Initialize builtin macros like __LINE__ and friends.
132 RegisterBuiltinMacros();
133
David Blaikiebbafb8a2012-03-11 07:00:24 +0000134 if(LangOpts.Borland) {
Douglas Gregor83297df2011-09-01 23:39:15 +0000135 Ident__exception_info = getIdentifierInfo("_exception_info");
136 Ident___exception_info = getIdentifierInfo("__exception_info");
137 Ident_GetExceptionInfo = getIdentifierInfo("GetExceptionInformation");
138 Ident__exception_code = getIdentifierInfo("_exception_code");
139 Ident___exception_code = getIdentifierInfo("__exception_code");
140 Ident_GetExceptionCode = getIdentifierInfo("GetExceptionCode");
141 Ident__abnormal_termination = getIdentifierInfo("_abnormal_termination");
142 Ident___abnormal_termination = getIdentifierInfo("__abnormal_termination");
143 Ident_AbnormalTermination = getIdentifierInfo("AbnormalTermination");
144 } else {
Craig Topperd2d442c2014-05-17 23:10:59 +0000145 Ident__exception_info = Ident__exception_code = nullptr;
146 Ident__abnormal_termination = Ident___exception_info = nullptr;
147 Ident___exception_code = Ident___abnormal_termination = nullptr;
148 Ident_GetExceptionInfo = Ident_GetExceptionCode = nullptr;
149 Ident_AbnormalTermination = nullptr;
Douglas Gregor89929282012-01-30 06:01:29 +0000150 }
Erik Verbruggenb34c79f2017-05-30 11:54:55 +0000151
152 if (this->PPOpts->GeneratePreamble)
153 PreambleConditionalStack.startRecording();
Argyrios Kyrtzidis3c9aaf12012-06-02 18:08:09 +0000154}
155
156Preprocessor::~Preprocessor() {
157 assert(BacktrackPositions.empty() && "EnableBacktrack/Backtrack imbalance!");
158
Benjamin Kramer329c5962014-03-15 16:40:40 +0000159 IncludeMacroStack.clear();
Argyrios Kyrtzidis3c9aaf12012-06-02 18:08:09 +0000160
Richard Smith73a29662014-07-24 03:25:00 +0000161 // Destroy any macro definitions.
162 while (MacroInfoChain *I = MIChainHead) {
163 MIChainHead = I->Next;
164 I->~MacroInfoChain();
165 }
Argyrios Kyrtzidis3c9aaf12012-06-02 18:08:09 +0000166
167 // Free any cached macro expanders.
Nico Weber5f5b9412014-05-09 18:09:42 +0000168 // This populates MacroArgCache, so all TokenLexers need to be destroyed
169 // before the code below that frees up the MacroArgCache list.
David Blaikie6d5038c2014-08-29 19:36:52 +0000170 std::fill(TokenLexerCache, TokenLexerCache + NumCachedTokenLexers, nullptr);
Nico Weber5f5b9412014-05-09 18:09:42 +0000171 CurTokenLexer.reset();
Argyrios Kyrtzidis3c9aaf12012-06-02 18:08:09 +0000172
173 // Free any cached MacroArgs.
Nico Weber5f5b9412014-05-09 18:09:42 +0000174 for (MacroArgs *ArgList = MacroArgCache; ArgList;)
Argyrios Kyrtzidis3c9aaf12012-06-02 18:08:09 +0000175 ArgList = ArgList->deallocate();
176
Argyrios Kyrtzidis3c9aaf12012-06-02 18:08:09 +0000177 // Delete the header search info, if we own it.
178 if (OwnsHeaderSearch)
179 delete &HeaderInfo;
Argyrios Kyrtzidis3c9aaf12012-06-02 18:08:09 +0000180}
181
Artem Belevichb5bc9232015-09-22 17:23:22 +0000182void Preprocessor::Initialize(const TargetInfo &Target,
183 const TargetInfo *AuxTarget) {
Argyrios Kyrtzidis3c9aaf12012-06-02 18:08:09 +0000184 assert((!this->Target || this->Target == &Target) &&
185 "Invalid override of target information");
186 this->Target = &Target;
Artem Belevichb5bc9232015-09-22 17:23:22 +0000187
188 assert((!this->AuxTarget || this->AuxTarget == AuxTarget) &&
189 "Invalid override of aux target information.");
190 this->AuxTarget = AuxTarget;
191
Argyrios Kyrtzidis3c9aaf12012-06-02 18:08:09 +0000192 // Initialize information about built-ins.
Artem Belevichb5bc9232015-09-22 17:23:22 +0000193 BuiltinInfo.InitializeTarget(Target, AuxTarget);
Douglas Gregor89929282012-01-30 06:01:29 +0000194 HeaderInfo.setTarget(Target);
Aaron Ballmand742dc22018-04-16 21:07:08 +0000195
196 // Populate the identifier table with info about keywords for the current language.
197 Identifiers.AddKeywords(LangOpts);
Douglas Gregor83297df2011-09-01 23:39:15 +0000198}
199
Ted Kremenekeeccb302014-08-27 15:14:15 +0000200void Preprocessor::InitializeForModelFile() {
201 NumEnteredSourceFiles = 0;
202
203 // Reset pragmas
David Blaikie9f0af9d2014-09-15 21:31:42 +0000204 PragmaHandlersBackup = std::move(PragmaHandlers);
Craig Topperbe250302014-09-12 05:19:24 +0000205 PragmaHandlers = llvm::make_unique<PragmaNamespace>(StringRef());
Ted Kremenekeeccb302014-08-27 15:14:15 +0000206 RegisterBuiltinPragmas();
207
208 // Reset PredefinesFileID
209 PredefinesFileID = FileID();
210}
211
212void Preprocessor::FinalizeForModelFile() {
213 NumEnteredSourceFiles = 1;
214
David Blaikie9f0af9d2014-09-15 21:31:42 +0000215 PragmaHandlers = std::move(PragmaHandlersBackup);
Ted Kremenekeeccb302014-08-27 15:14:15 +0000216}
217
Ted Kremeneka5c2c272009-02-12 03:26:59 +0000218void Preprocessor::setPTHManager(PTHManager* pm) {
219 PTH.reset(pm);
Douglas Gregord2eb58a2009-10-16 18:18:30 +0000220 FileMgr.addStatCache(PTH->createStatCache());
Ted Kremeneka5c2c272009-02-12 03:26:59 +0000221}
222
Chris Lattner146762e2007-07-20 16:59:19 +0000223void Preprocessor::DumpToken(const Token &Tok, bool DumpFlags) const {
Benjamin Kramer89b422c2009-08-23 12:08:50 +0000224 llvm::errs() << tok::getTokenName(Tok.getKind()) << " '"
225 << getSpelling(Tok) << "'";
Mike Stump11289f42009-09-09 15:08:12 +0000226
Chris Lattnerd01e2912006-06-18 16:22:51 +0000227 if (!DumpFlags) return;
Mike Stump11289f42009-09-09 15:08:12 +0000228
Benjamin Kramer89b422c2009-08-23 12:08:50 +0000229 llvm::errs() << "\t";
Chris Lattnerd01e2912006-06-18 16:22:51 +0000230 if (Tok.isAtStartOfLine())
Benjamin Kramer89b422c2009-08-23 12:08:50 +0000231 llvm::errs() << " [StartOfLine]";
Chris Lattnerd01e2912006-06-18 16:22:51 +0000232 if (Tok.hasLeadingSpace())
Benjamin Kramer89b422c2009-08-23 12:08:50 +0000233 llvm::errs() << " [LeadingSpace]";
Chris Lattner6e4bf522006-07-27 06:59:25 +0000234 if (Tok.isExpandDisabled())
Benjamin Kramer89b422c2009-08-23 12:08:50 +0000235 llvm::errs() << " [ExpandDisabled]";
Chris Lattnerd01e2912006-06-18 16:22:51 +0000236 if (Tok.needsCleaning()) {
Chris Lattner50b497e2006-06-18 16:32:35 +0000237 const char *Start = SourceMgr.getCharacterData(Tok.getLocation());
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000238 llvm::errs() << " [UnClean='" << StringRef(Start, Tok.getLength())
Benjamin Kramer89b422c2009-08-23 12:08:50 +0000239 << "']";
Chris Lattnerd01e2912006-06-18 16:22:51 +0000240 }
Mike Stump11289f42009-09-09 15:08:12 +0000241
Benjamin Kramer89b422c2009-08-23 12:08:50 +0000242 llvm::errs() << "\tLoc=<";
Chris Lattner615315f2007-12-09 20:31:55 +0000243 DumpLocation(Tok.getLocation());
Benjamin Kramer89b422c2009-08-23 12:08:50 +0000244 llvm::errs() << ">";
Chris Lattner615315f2007-12-09 20:31:55 +0000245}
246
247void Preprocessor::DumpLocation(SourceLocation Loc) const {
Chris Lattnerf1ca7d32009-01-27 07:57:44 +0000248 Loc.dump(SourceMgr);
Chris Lattnerd01e2912006-06-18 16:22:51 +0000249}
250
251void Preprocessor::DumpMacro(const MacroInfo &MI) const {
Benjamin Kramer89b422c2009-08-23 12:08:50 +0000252 llvm::errs() << "MACRO: ";
Chris Lattnerd01e2912006-06-18 16:22:51 +0000253 for (unsigned i = 0, e = MI.getNumTokens(); i != e; ++i) {
254 DumpToken(MI.getReplacementToken(i));
Benjamin Kramer89b422c2009-08-23 12:08:50 +0000255 llvm::errs() << " ";
Chris Lattnerd01e2912006-06-18 16:22:51 +0000256 }
Benjamin Kramer89b422c2009-08-23 12:08:50 +0000257 llvm::errs() << "\n";
Chris Lattnerd01e2912006-06-18 16:22:51 +0000258}
259
Chris Lattner22eb9722006-06-18 05:43:12 +0000260void Preprocessor::PrintStats() {
Benjamin Kramer89b422c2009-08-23 12:08:50 +0000261 llvm::errs() << "\n*** Preprocessor Stats:\n";
262 llvm::errs() << NumDirectives << " directives found:\n";
263 llvm::errs() << " " << NumDefined << " #define.\n";
264 llvm::errs() << " " << NumUndefined << " #undef.\n";
265 llvm::errs() << " #include/#include_next/#import:\n";
266 llvm::errs() << " " << NumEnteredSourceFiles << " source files entered.\n";
267 llvm::errs() << " " << MaxIncludeStackDepth << " max include stack depth\n";
268 llvm::errs() << " " << NumIf << " #if/#ifndef/#ifdef.\n";
269 llvm::errs() << " " << NumElse << " #else/#elif.\n";
270 llvm::errs() << " " << NumEndif << " #endif.\n";
271 llvm::errs() << " " << NumPragma << " #pragma.\n";
272 llvm::errs() << NumSkipped << " #if/#ifndef#ifdef regions skipped\n";
Chris Lattner22eb9722006-06-18 05:43:12 +0000273
Benjamin Kramer89b422c2009-08-23 12:08:50 +0000274 llvm::errs() << NumMacroExpanded << "/" << NumFnMacroExpanded << "/"
Ted Kremeneka0a3e9b2008-01-14 16:44:48 +0000275 << NumBuiltinMacroExpanded << " obj/fn/builtin macros expanded, "
276 << NumFastMacroExpanded << " on the fast path.\n";
Benjamin Kramer89b422c2009-08-23 12:08:50 +0000277 llvm::errs() << (NumFastTokenPaste+NumTokenPaste)
Ted Kremeneka0a3e9b2008-01-14 16:44:48 +0000278 << " token paste (##) operations performed, "
279 << NumFastTokenPaste << " on the fast path.\n";
Alexander Kornienko199cd942012-08-13 10:46:42 +0000280
281 llvm::errs() << "\nPreprocessor Memory: " << getTotalMemory() << "B total";
282
283 llvm::errs() << "\n BumpPtr: " << BP.getTotalMemory();
284 llvm::errs() << "\n Macro Expanded Tokens: "
285 << llvm::capacity_in_bytes(MacroExpandedTokens);
286 llvm::errs() << "\n Predefines Buffer: " << Predefines.capacity();
Richard Smith04765ae2015-05-21 01:20:10 +0000287 // FIXME: List information for all submodules.
288 llvm::errs() << "\n Macros: "
289 << llvm::capacity_in_bytes(CurSubmoduleState->Macros);
Alexander Kornienko199cd942012-08-13 10:46:42 +0000290 llvm::errs() << "\n #pragma push_macro Info: "
291 << llvm::capacity_in_bytes(PragmaPushMacroInfo);
292 llvm::errs() << "\n Poison Reasons: "
293 << llvm::capacity_in_bytes(PoisonReasons);
294 llvm::errs() << "\n Comment Handlers: "
295 << llvm::capacity_in_bytes(CommentHandlers) << "\n";
Chris Lattner22eb9722006-06-18 05:43:12 +0000296}
297
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +0000298Preprocessor::macro_iterator
299Preprocessor::macro_begin(bool IncludeExternalMacros) const {
300 if (IncludeExternalMacros && ExternalSource &&
Douglas Gregor9882a5a2010-01-04 19:18:44 +0000301 !ReadMacrosFromExternalSource) {
302 ReadMacrosFromExternalSource = true;
303 ExternalSource->ReadDefinedMacros();
304 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +0000305
Jordan Rosea46bfa62015-06-24 19:27:02 +0000306 // Make sure we cover all macros in visible modules.
307 for (const ModuleMacro &Macro : ModuleMacros)
308 CurSubmoduleState->Macros.insert(std::make_pair(Macro.II, MacroState()));
309
Richard Smith04765ae2015-05-21 01:20:10 +0000310 return CurSubmoduleState->Macros.begin();
Douglas Gregor9882a5a2010-01-04 19:18:44 +0000311}
312
Argyrios Kyrtzidise379ee32011-06-29 22:20:04 +0000313size_t Preprocessor::getTotalMemory() const {
Ted Kremenek182543a2011-07-26 21:17:24 +0000314 return BP.getTotalMemory()
Ted Kremenek8b77fe72011-07-27 18:41:23 +0000315 + llvm::capacity_in_bytes(MacroExpandedTokens)
Ted Kremenek182543a2011-07-26 21:17:24 +0000316 + Predefines.capacity() /* Predefines buffer. */
Richard Smith04765ae2015-05-21 01:20:10 +0000317 // FIXME: Include sizes from all submodules, and include MacroInfo sizes,
318 // and ModuleMacros.
319 + llvm::capacity_in_bytes(CurSubmoduleState->Macros)
Ted Kremenek8b77fe72011-07-27 18:41:23 +0000320 + llvm::capacity_in_bytes(PragmaPushMacroInfo)
321 + llvm::capacity_in_bytes(PoisonReasons)
322 + llvm::capacity_in_bytes(CommentHandlers);
Argyrios Kyrtzidise379ee32011-06-29 22:20:04 +0000323}
324
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +0000325Preprocessor::macro_iterator
326Preprocessor::macro_end(bool IncludeExternalMacros) const {
327 if (IncludeExternalMacros && ExternalSource &&
Douglas Gregor9882a5a2010-01-04 19:18:44 +0000328 !ReadMacrosFromExternalSource) {
329 ReadMacrosFromExternalSource = true;
330 ExternalSource->ReadDefinedMacros();
331 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +0000332
Richard Smith04765ae2015-05-21 01:20:10 +0000333 return CurSubmoduleState->Macros.end();
Douglas Gregor9882a5a2010-01-04 19:18:44 +0000334}
335
Dmitri Gribenko6743e042012-09-29 11:40:46 +0000336/// \brief Compares macro tokens with a specified token value sequence.
337static bool MacroDefinitionEquals(const MacroInfo *MI,
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000338 ArrayRef<TokenValue> Tokens) {
Dmitri Gribenko6743e042012-09-29 11:40:46 +0000339 return Tokens.size() == MI->getNumTokens() &&
340 std::equal(Tokens.begin(), Tokens.end(), MI->tokens_begin());
341}
342
343StringRef Preprocessor::getLastMacroWithSpelling(
344 SourceLocation Loc,
345 ArrayRef<TokenValue> Tokens) const {
346 SourceLocation BestLocation;
347 StringRef BestSpelling;
348 for (Preprocessor::macro_iterator I = macro_begin(), E = macro_end();
349 I != E; ++I) {
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +0000350 const MacroDirective::DefInfo
Richard Smithb8b2ed62015-04-23 18:18:26 +0000351 Def = I->second.findDirectiveAtLoc(Loc, SourceMgr);
Argyrios Kyrtzidis5c585252015-03-04 16:03:07 +0000352 if (!Def || !Def.getMacroInfo())
353 continue;
354 if (!Def.getMacroInfo()->isObjectLike())
Dmitri Gribenko6743e042012-09-29 11:40:46 +0000355 continue;
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +0000356 if (!MacroDefinitionEquals(Def.getMacroInfo(), Tokens))
Dmitri Gribenko6743e042012-09-29 11:40:46 +0000357 continue;
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +0000358 SourceLocation Location = Def.getLocation();
Dmitri Gribenko6743e042012-09-29 11:40:46 +0000359 // Choose the macro defined latest.
360 if (BestLocation.isInvalid() ||
361 (Location.isValid() &&
362 SourceMgr.isBeforeInTranslationUnit(BestLocation, Location))) {
363 BestLocation = Location;
364 BestSpelling = I->first->getName();
365 }
366 }
367 return BestSpelling;
368}
369
Douglas Gregor8d76cca2012-01-04 06:20:15 +0000370void Preprocessor::recomputeCurLexerKind() {
371 if (CurLexer)
372 CurLexerKind = CLK_Lexer;
373 else if (CurPTHLexer)
374 CurLexerKind = CLK_PTHLexer;
375 else if (CurTokenLexer)
376 CurLexerKind = CLK_TokenLexer;
377 else
378 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
Douglas Gregor11583702010-08-25 17:04:25 +0000439void Preprocessor::CodeCompleteNaturalLanguage() {
Douglas Gregor11583702010-08-25 17:04:25 +0000440 if (CodeComplete)
441 CodeComplete->CodeCompleteNaturalLanguage();
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +0000442 setCodeCompletionReached();
Douglas Gregor11583702010-08-25 17:04:25 +0000443}
444
Benjamin Kramera197fb62010-02-27 17:05:45 +0000445/// getSpelling - This method is used to get the spelling of a token into a
446/// SmallVector. Note that the returned StringRef may not point to the
447/// supplied buffer if a copy can be avoided.
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000448StringRef Preprocessor::getSpelling(const Token &Tok,
449 SmallVectorImpl<char> &Buffer,
Douglas Gregor7bda4b82010-03-16 05:20:39 +0000450 bool *Invalid) const {
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +0000451 // NOTE: this has to be checked *before* testing for an IdentifierInfo.
Jordan Rose7f43ddd2013-01-24 20:50:46 +0000452 if (Tok.isNot(tok::raw_identifier) && !Tok.hasUCN()) {
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +0000453 // Try the fast path.
454 if (const IdentifierInfo *II = Tok.getIdentifierInfo())
455 return II->getName();
456 }
Benjamin Kramera197fb62010-02-27 17:05:45 +0000457
458 // Resize the buffer if we need to copy into it.
459 if (Tok.needsCleaning())
460 Buffer.resize(Tok.getLength());
461
462 const char *Ptr = Buffer.data();
Douglas Gregor7bda4b82010-03-16 05:20:39 +0000463 unsigned Len = getSpelling(Tok, Ptr, Invalid);
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000464 return StringRef(Ptr, Len);
Benjamin Kramera197fb62010-02-27 17:05:45 +0000465}
466
Chris Lattnerb94ec7b2006-07-14 06:54:10 +0000467/// CreateString - Plop the specified string into a scratch buffer and return a
468/// location for it. If specified, the source location provides a source
469/// location for the token.
Dmitri Gribenkob8e9e752012-09-24 21:07:17 +0000470void Preprocessor::CreateString(StringRef Str, Token &Tok,
Abramo Bagnarae398e602011-10-03 18:39:03 +0000471 SourceLocation ExpansionLocStart,
472 SourceLocation ExpansionLocEnd) {
Dmitri Gribenkob8e9e752012-09-24 21:07:17 +0000473 Tok.setLength(Str.size());
Mike Stump11289f42009-09-09 15:08:12 +0000474
Chris Lattner5a7971e2009-01-26 19:29:26 +0000475 const char *DestPtr;
Dmitri Gribenkob8e9e752012-09-24 21:07:17 +0000476 SourceLocation Loc = ScratchBuf->getToken(Str.data(), Str.size(), DestPtr);
Mike Stump11289f42009-09-09 15:08:12 +0000477
Abramo Bagnarae398e602011-10-03 18:39:03 +0000478 if (ExpansionLocStart.isValid())
479 Loc = SourceMgr.createExpansionLoc(Loc, ExpansionLocStart,
Dmitri Gribenkob8e9e752012-09-24 21:07:17 +0000480 ExpansionLocEnd, Str.size());
Chris Lattner5a7971e2009-01-26 19:29:26 +0000481 Tok.setLocation(Loc);
Mike Stump11289f42009-09-09 15:08:12 +0000482
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +0000483 // If this is a raw identifier or a literal token, set the pointer data.
484 if (Tok.is(tok::raw_identifier))
485 Tok.setRawIdentifierData(DestPtr);
486 else if (Tok.isLiteral())
Chris Lattner5a7971e2009-01-26 19:29:26 +0000487 Tok.setLiteralData(DestPtr);
Chris Lattnerb94ec7b2006-07-14 06:54:10 +0000488}
489
Richard Smithb5f81712018-04-30 05:25:48 +0000490SourceLocation Preprocessor::SplitToken(SourceLocation Loc, unsigned Length) {
491 auto &SM = getSourceManager();
492 SourceLocation SpellingLoc = SM.getSpellingLoc(Loc);
493 std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(SpellingLoc);
494 bool Invalid = false;
495 StringRef Buffer = SM.getBufferData(LocInfo.first, &Invalid);
496 if (Invalid)
497 return SourceLocation();
498
499 // FIXME: We could consider re-using spelling for tokens we see repeatedly.
500 const char *DestPtr;
501 SourceLocation Spelling =
502 ScratchBuf->getToken(Buffer.data() + LocInfo.second, Length, DestPtr);
503 return SM.createTokenSplitLoc(Spelling, Loc, Loc.getLocWithOffset(Length));
504}
505
Douglas Gregor2b82c2a2011-12-02 01:47:07 +0000506Module *Preprocessor::getCurrentModule() {
Richard Smithbbcc9f02016-08-26 00:14:38 +0000507 if (!getLangOpts().isCompilingModule())
Craig Topperd2d442c2014-05-17 23:10:59 +0000508 return nullptr;
509
David Blaikiebbafb8a2012-03-11 07:00:24 +0000510 return getHeaderSearchInfo().lookupModule(getLangOpts().CurrentModule);
Douglas Gregor2b82c2a2011-12-02 01:47:07 +0000511}
Chris Lattner8a7003c2007-07-16 06:48:38 +0000512
Chris Lattner1f1b0db2007-10-09 22:10:18 +0000513//===----------------------------------------------------------------------===//
514// Preprocessor Initialization Methods
515//===----------------------------------------------------------------------===//
516
Chris Lattner1f1b0db2007-10-09 22:10:18 +0000517/// EnterMainSourceFile - Enter the specified FileID as the main source file,
Nate Begemanf7c3ff62008-01-07 04:01:26 +0000518/// which implicitly adds the builtin defines etc.
Chris Lattnerfb24a3a2010-04-20 20:35:58 +0000519void Preprocessor::EnterMainSourceFile() {
Chris Lattner9ef847b2009-02-13 19:33:24 +0000520 // We do not allow the preprocessor to reenter the main file. Doing so will
521 // cause FileID's to accumulate information from both runs (e.g. #line
522 // information) and predefined macros aren't guaranteed to be set properly.
523 assert(NumEnteredSourceFiles == 0 && "Cannot reenter the main file!");
Chris Lattnerd32480d2009-01-17 06:22:33 +0000524 FileID MainFileID = SourceMgr.getMainFileID();
Mike Stump11289f42009-09-09 15:08:12 +0000525
Argyrios Kyrtzidis9afd4492012-01-05 21:36:25 +0000526 // If MainFileID is loaded it means we loaded an AST file, no need to enter
527 // a main file.
528 if (!SourceMgr.isLoadedFileID(MainFileID)) {
529 // Enter the main file source buffer.
Craig Topperd2d442c2014-05-17 23:10:59 +0000530 EnterSourceFile(MainFileID, nullptr, SourceLocation());
531
Argyrios Kyrtzidis9afd4492012-01-05 21:36:25 +0000532 // If we've been asked to skip bytes in the main file (e.g., as part of a
533 // precompiled preamble), do so now.
534 if (SkipMainFilePreamble.first > 0)
Cameron Desrochers84fd0642017-09-20 19:03:37 +0000535 CurLexer->SetByteOffset(SkipMainFilePreamble.first,
536 SkipMainFilePreamble.second);
537
Argyrios Kyrtzidis9afd4492012-01-05 21:36:25 +0000538 // Tell the header info that the main file was entered. If the file is later
539 // #imported, it won't be re-entered.
540 if (const FileEntry *FE = SourceMgr.getFileEntryForID(MainFileID))
541 HeaderInfo.IncrementIncludeCount(FE);
542 }
Mike Stump11289f42009-09-09 15:08:12 +0000543
Benjamin Kramerd77adb52009-12-31 15:33:09 +0000544 // Preprocess Predefines to populate the initial preprocessor state.
Rafael Espindolad87f8d72014-08-27 20:03:29 +0000545 std::unique_ptr<llvm::MemoryBuffer> SB =
Chris Lattner58c79342010-04-05 22:42:27 +0000546 llvm::MemoryBuffer::getMemBufferCopy(Predefines, "<built-in>");
Douglas Gregor33551892010-08-26 14:07:34 +0000547 assert(SB && "Cannot create predefined source buffer");
David Blaikie50a5f972014-08-29 07:59:55 +0000548 FileID FID = SourceMgr.createFileID(std::move(SB));
Yaron Keren8b563662015-10-03 10:46:20 +0000549 assert(FID.isValid() && "Could not create FileID for predefines?");
Argyrios Kyrtzidis22c22f52013-02-01 16:36:07 +0000550 setPredefinesFileID(FID);
Mike Stump11289f42009-09-09 15:08:12 +0000551
Chris Lattner1f1b0db2007-10-09 22:10:18 +0000552 // Start parsing the predefines.
Craig Topperd2d442c2014-05-17 23:10:59 +0000553 EnterSourceFile(FID, nullptr, SourceLocation());
Erik Verbruggen795eee92017-07-05 09:44:07 +0000554}
Erik Verbruggenb34c79f2017-05-30 11:54:55 +0000555
Erik Verbruggen795eee92017-07-05 09:44:07 +0000556void Preprocessor::replayPreambleConditionalStack() {
Erik Verbruggenb34c79f2017-05-30 11:54:55 +0000557 // Restore the conditional stack from the preamble, if there is one.
558 if (PreambleConditionalStack.isReplaying()) {
Ilya Biryukovf3150002017-08-21 12:03:08 +0000559 assert(CurPPLexer &&
560 "CurPPLexer is null when calling replayPreambleConditionalStack.");
Erik Verbruggenb34c79f2017-05-30 11:54:55 +0000561 CurPPLexer->setConditionalLevels(PreambleConditionalStack.getStack());
562 PreambleConditionalStack.doneReplaying();
Erik Verbruggen4d1eb2d2017-11-03 09:40:07 +0000563 if (PreambleConditionalStack.reachedEOFWhileSkipping())
564 SkipExcludedConditionalBlock(
565 PreambleConditionalStack.SkipInfo->HashTokenLoc,
566 PreambleConditionalStack.SkipInfo->IfTokenLoc,
567 PreambleConditionalStack.SkipInfo->FoundNonSkipPortion,
568 PreambleConditionalStack.SkipInfo->FoundElse,
569 PreambleConditionalStack.SkipInfo->ElseLoc);
Erik Verbruggenb34c79f2017-05-30 11:54:55 +0000570 }
Chris Lattner1f1b0db2007-10-09 22:10:18 +0000571}
Chris Lattner8a7003c2007-07-16 06:48:38 +0000572
Daniel Dunbarcb9eaf52010-03-23 05:09:10 +0000573void Preprocessor::EndSourceFile() {
574 // Notify the client that we reached the end of the source file.
575 if (Callbacks)
576 Callbacks->EndOfMainFile();
577}
Chris Lattner677757a2006-06-28 05:26:32 +0000578
579//===----------------------------------------------------------------------===//
580// Lexer Event Handling.
581//===----------------------------------------------------------------------===//
582
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +0000583/// LookUpIdentifierInfo - Given a tok::raw_identifier token, look up the
584/// identifier information for the token and install it into the token,
585/// updating the token kind accordingly.
586IdentifierInfo *Preprocessor::LookUpIdentifierInfo(Token &Identifier) const {
Alp Toker2d57cea2014-05-17 04:53:25 +0000587 assert(!Identifier.getRawIdentifier().empty() && "No raw identifier data!");
Mike Stump11289f42009-09-09 15:08:12 +0000588
Chris Lattnercefc7682006-07-08 08:28:12 +0000589 // Look up this token, see if it is a macro, or if it is a language keyword.
590 IdentifierInfo *II;
Jordan Rose7f43ddd2013-01-24 20:50:46 +0000591 if (!Identifier.needsCleaning() && !Identifier.hasUCN()) {
Chris Lattnercefc7682006-07-08 08:28:12 +0000592 // No cleaning needed, just use the characters from the lexed buffer.
Alp Toker2d57cea2014-05-17 04:53:25 +0000593 II = getIdentifierInfo(Identifier.getRawIdentifier());
Chris Lattnercefc7682006-07-08 08:28:12 +0000594 } else {
595 // Cleaning needed, alloca a buffer, clean into it, then use the buffer.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +0000596 SmallString<64> IdentifierBuffer;
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000597 StringRef CleanedStr = getSpelling(Identifier, IdentifierBuffer);
Jordan Rose7f43ddd2013-01-24 20:50:46 +0000598
599 if (Identifier.hasUCN()) {
600 SmallString<64> UCNIdentifierBuffer;
601 expandUCNs(UCNIdentifierBuffer, CleanedStr);
602 II = getIdentifierInfo(UCNIdentifierBuffer);
603 } else {
604 II = getIdentifierInfo(CleanedStr);
605 }
Chris Lattnercefc7682006-07-08 08:28:12 +0000606 }
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +0000607
608 // Update the token info (identifier info and appropriate token kind).
Chris Lattner8c204872006-10-14 05:19:21 +0000609 Identifier.setIdentifierInfo(II);
Erich Keane33c3d8a2017-06-09 16:29:35 +0000610 if (getLangOpts().MSVCCompat && II->isCPlusPlusOperatorKeyword() &&
611 getSourceManager().isInSystemHeader(Identifier.getLocation()))
Eugene Zelenko5dc60fe2017-12-04 23:16:21 +0000612 Identifier.setKind(tok::identifier);
Erich Keane33c3d8a2017-06-09 16:29:35 +0000613 else
614 Identifier.setKind(II->getTokenID());
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +0000615
Chris Lattnercefc7682006-07-08 08:28:12 +0000616 return II;
617}
618
John Wiegley1c0675e2011-04-28 01:08:34 +0000619void Preprocessor::SetPoisonReason(IdentifierInfo *II, unsigned DiagID) {
620 PoisonReasons[II] = DiagID;
621}
622
623void Preprocessor::PoisonSEHIdentifiers(bool Poison) {
624 assert(Ident__exception_code && Ident__exception_info);
625 assert(Ident___exception_code && Ident___exception_info);
626 Ident__exception_code->setIsPoisoned(Poison);
627 Ident___exception_code->setIsPoisoned(Poison);
628 Ident_GetExceptionCode->setIsPoisoned(Poison);
629 Ident__exception_info->setIsPoisoned(Poison);
630 Ident___exception_info->setIsPoisoned(Poison);
631 Ident_GetExceptionInfo->setIsPoisoned(Poison);
632 Ident__abnormal_termination->setIsPoisoned(Poison);
633 Ident___abnormal_termination->setIsPoisoned(Poison);
634 Ident_AbnormalTermination->setIsPoisoned(Poison);
635}
636
637void Preprocessor::HandlePoisonedIdentifier(Token & Identifier) {
638 assert(Identifier.getIdentifierInfo() &&
639 "Can't handle identifiers without identifier info!");
640 llvm::DenseMap<IdentifierInfo*,unsigned>::const_iterator it =
641 PoisonReasons.find(Identifier.getIdentifierInfo());
642 if(it == PoisonReasons.end())
643 Diag(Identifier, diag::err_pp_used_poisoned_id);
644 else
645 Diag(Identifier,it->second) << Identifier.getIdentifierInfo();
646}
Chris Lattnercefc7682006-07-08 08:28:12 +0000647
Richard Smith31d51842015-05-14 04:00:59 +0000648/// \brief Returns a diagnostic message kind for reporting a future keyword as
649/// appropriate for the identifier and specified language.
650static diag::kind getFutureCompatDiagKind(const IdentifierInfo &II,
651 const LangOptions &LangOpts) {
652 assert(II.isFutureCompatKeyword() && "diagnostic should not be needed");
653
654 if (LangOpts.CPlusPlus)
655 return llvm::StringSwitch<diag::kind>(II.getName())
656#define CXX11_KEYWORD(NAME, FLAGS) \
657 .Case(#NAME, diag::warn_cxx11_keyword)
Richard Smith6c74e322017-08-13 21:32:33 +0000658#define CXX2A_KEYWORD(NAME, FLAGS) \
659 .Case(#NAME, diag::warn_cxx2a_keyword)
Richard Smith31d51842015-05-14 04:00:59 +0000660#include "clang/Basic/TokenKinds.def"
661 ;
662
663 llvm_unreachable(
664 "Keyword not known to come from a newer Standard or proposed Standard");
665}
666
Richard Smith3dba7eb2016-08-18 01:16:55 +0000667void Preprocessor::updateOutOfDateIdentifier(IdentifierInfo &II) const {
668 assert(II.isOutOfDate() && "not out of date");
669 getExternalSource()->updateOutOfDateIdentifier(II);
670}
671
Chris Lattner677757a2006-06-28 05:26:32 +0000672/// HandleIdentifier - This callback is invoked when the lexer reads an
673/// identifier. This callback looks up the identifier in the map and/or
674/// potentially macro expands it or turns it into a named token (like 'for').
Chris Lattnerad89ec02009-01-21 07:43:11 +0000675///
676/// Note that callers of this method are guarded by checking the
677/// IdentifierInfo's 'isHandleIdentifierCase' bit. If this method changes, the
678/// IdentifierInfo methods that compute these properties will need to change to
679/// match.
Eli Friedman0834a4b2013-09-19 00:41:32 +0000680bool Preprocessor::HandleIdentifier(Token &Identifier) {
Chris Lattner0f1f5052006-07-20 04:16:23 +0000681 assert(Identifier.getIdentifierInfo() &&
682 "Can't handle identifiers without identifier info!");
Mike Stump11289f42009-09-09 15:08:12 +0000683
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000684 IdentifierInfo &II = *Identifier.getIdentifierInfo();
Chris Lattner677757a2006-06-28 05:26:32 +0000685
Douglas Gregor935bc7a22011-10-27 09:33:13 +0000686 // If the information about this identifier is out of date, update it from
687 // the external source.
Douglas Gregor3f568c12012-06-29 18:27:59 +0000688 // We have to treat __VA_ARGS__ in a special way, since it gets
689 // serialized with isPoisoned = true, but our preprocessor may have
690 // unpoisoned it if we're defining a C99 macro.
Douglas Gregor935bc7a22011-10-27 09:33:13 +0000691 if (II.isOutOfDate()) {
Douglas Gregor3f568c12012-06-29 18:27:59 +0000692 bool CurrentIsPoisoned = false;
Faisal Vali18268422017-10-15 01:26:26 +0000693 const bool IsSpecialVariadicMacro =
694 &II == Ident__VA_ARGS__ || &II == Ident__VA_OPT__;
695 if (IsSpecialVariadicMacro)
696 CurrentIsPoisoned = II.isPoisoned();
Douglas Gregor3f568c12012-06-29 18:27:59 +0000697
Richard Smith3dba7eb2016-08-18 01:16:55 +0000698 updateOutOfDateIdentifier(II);
Douglas Gregor935bc7a22011-10-27 09:33:13 +0000699 Identifier.setKind(II.getTokenID());
Douglas Gregor3f568c12012-06-29 18:27:59 +0000700
Faisal Vali18268422017-10-15 01:26:26 +0000701 if (IsSpecialVariadicMacro)
Douglas Gregor3f568c12012-06-29 18:27:59 +0000702 II.setIsPoisoned(CurrentIsPoisoned);
Douglas Gregor935bc7a22011-10-27 09:33:13 +0000703 }
704
Chris Lattner677757a2006-06-28 05:26:32 +0000705 // If this identifier was poisoned, and if it was not produced from a macro
706 // expansion, emit an error.
Ted Kremeneka2c3c8d2008-11-19 22:43:49 +0000707 if (II.isPoisoned() && CurPPLexer) {
John Wiegley1c0675e2011-04-28 01:08:34 +0000708 HandlePoisonedIdentifier(Identifier);
Chris Lattner8ff71992006-07-06 05:17:39 +0000709 }
Mike Stump11289f42009-09-09 15:08:12 +0000710
Chris Lattner78186052006-07-09 00:45:31 +0000711 // If this is a macro to be expanded, do it.
Richard Smith20e883e2015-04-29 23:20:19 +0000712 if (MacroDefinition MD = getMacroDefinition(&II)) {
713 auto *MI = MD.getMacroInfo();
Richard Smithf5ec2ac2015-04-29 23:40:48 +0000714 assert(MI && "macro definition with no macro info?");
Abramo Bagnara123bec82012-01-01 22:01:04 +0000715 if (!DisableMacroExpansion) {
Richard Smith181879c2012-12-12 02:46:14 +0000716 if (!Identifier.isExpandDisabled() && MI->isEnabled()) {
Eli Friedman0834a4b2013-09-19 00:41:32 +0000717 // C99 6.10.3p10: If the preprocessing token immediately after the
718 // macro name isn't a '(', this macro should not be expanded.
719 if (!MI->isFunctionLike() || isNextPPTokenLParen())
720 return HandleMacroExpandedIdentifier(Identifier, MD);
Chris Lattner6e4bf522006-07-27 06:59:25 +0000721 } else {
722 // C99 6.10.3.4p2 says that a disabled macro may never again be
723 // expanded, even if it's in a context where it could be expanded in the
724 // future.
Chris Lattner146762e2007-07-20 16:59:19 +0000725 Identifier.setFlag(Token::DisableExpand);
Richard Smith181879c2012-12-12 02:46:14 +0000726 if (MI->isObjectLike() || isNextPPTokenLParen())
727 Diag(Identifier, diag::pp_disabled_macro_expansion);
Chris Lattner6e4bf522006-07-27 06:59:25 +0000728 }
729 }
Chris Lattner063400e2006-10-14 19:54:15 +0000730 }
Chris Lattner677757a2006-06-28 05:26:32 +0000731
Richard Smith31d51842015-05-14 04:00:59 +0000732 // If this identifier is a keyword in a newer Standard or proposed Standard,
733 // produce a warning. Don't warn if we're not considering macro expansion,
734 // since this identifier might be the name of a macro.
Richard Smith4dd85d62011-10-11 19:57:52 +0000735 // FIXME: This warning is disabled in cases where it shouldn't be, like
736 // "#define constexpr constexpr", "int constexpr;"
Richard Smith31d51842015-05-14 04:00:59 +0000737 if (II.isFutureCompatKeyword() && !DisableMacroExpansion) {
738 Diag(Identifier, getFutureCompatDiagKind(II, getLangOpts()))
739 << II.getName();
Richard Smith4dd85d62011-10-11 19:57:52 +0000740 // Don't diagnose this keyword again in this translation unit.
Richard Smith31d51842015-05-14 04:00:59 +0000741 II.setIsFutureCompatKeyword(false);
Richard Smith4dd85d62011-10-11 19:57:52 +0000742 }
743
Chris Lattner677757a2006-06-28 05:26:32 +0000744 // If this is an extension token, diagnose its use.
Steve Naroffc84e8b72008-09-02 18:50:17 +0000745 // We avoid diagnosing tokens that originate from macro definitions.
Eli Friedman6bba2ad2009-04-28 03:59:15 +0000746 // FIXME: This warning is disabled in cases where it shouldn't be,
747 // like "#define TY typeof", "TY(1) x".
748 if (II.isExtensionToken() && !DisableMacroExpansion)
Chris Lattner53621a52007-06-13 20:44:40 +0000749 Diag(Identifier, diag::ext_token_used);
Douglas Gregoraf5c4842011-09-07 23:11:54 +0000750
Douglas Gregor594b8c92013-11-07 22:55:02 +0000751 // If this is the 'import' contextual keyword following an '@', note
Ted Kremenekc1e4dd02012-03-01 22:07:04 +0000752 // that the next token indicates a module name.
Douglas Gregor8d76cca2012-01-04 06:20:15 +0000753 //
Douglas Gregorc50d4922012-12-11 22:11:52 +0000754 // Note that we do not treat 'import' as a contextual
Ted Kremenekc1e4dd02012-03-01 22:07:04 +0000755 // keyword when we're in a caching lexer, because caching lexers only get
756 // used in contexts where import declarations are disallowed.
Richard Smith49cc1cc2016-08-18 21:59:42 +0000757 //
758 // Likewise if this is the C++ Modules TS import keyword.
759 if (((LastTokenWasAt && II.isModulesImport()) ||
760 Identifier.is(tok::kw_import)) &&
761 !InMacroArgs && !DisableMacroExpansion &&
762 (getLangOpts().Modules || getLangOpts().DebuggerSupport) &&
Douglas Gregor594b8c92013-11-07 22:55:02 +0000763 CurLexerKind != CLK_CachingLexer) {
Douglas Gregoraf5c4842011-09-07 23:11:54 +0000764 ModuleImportLoc = Identifier.getLocation();
Douglas Gregor1805b8a2011-11-30 04:26:53 +0000765 ModuleImportPath.clear();
766 ModuleImportExpectsIdentifier = true;
Douglas Gregoraf5c4842011-09-07 23:11:54 +0000767 CurLexerKind = CLK_LexAfterModuleImport;
768 }
Eli Friedman0834a4b2013-09-19 00:41:32 +0000769 return true;
Douglas Gregor08142532011-08-26 23:56:07 +0000770}
771
Eli Friedman0834a4b2013-09-19 00:41:32 +0000772void Preprocessor::Lex(Token &Result) {
Yaron Keren716f3a62015-09-29 16:51:08 +0000773 // We loop here until a lex function returns a token; this avoids recursion.
Eli Friedman0834a4b2013-09-19 00:41:32 +0000774 bool ReturnedToken;
775 do {
776 switch (CurLexerKind) {
777 case CLK_Lexer:
778 ReturnedToken = CurLexer->Lex(Result);
779 break;
780 case CLK_PTHLexer:
781 ReturnedToken = CurPTHLexer->Lex(Result);
782 break;
783 case CLK_TokenLexer:
784 ReturnedToken = CurTokenLexer->Lex(Result);
785 break;
786 case CLK_CachingLexer:
787 CachingLex(Result);
788 ReturnedToken = true;
789 break;
790 case CLK_LexAfterModuleImport:
791 LexAfterModuleImport(Result);
792 ReturnedToken = true;
793 break;
794 }
795 } while (!ReturnedToken);
Douglas Gregor594b8c92013-11-07 22:55:02 +0000796
Ilya Biryukovb8f231a2018-01-22 17:18:28 +0000797 if (Result.is(tok::code_completion) && Result.getIdentifierInfo()) {
798 // Remember the identifier before code completion token.
Vassil Vassilev644ea612016-07-27 14:56:59 +0000799 setCodeCompletionIdentifierInfo(Result.getIdentifierInfo());
Ilya Biryukovb8f231a2018-01-22 17:18:28 +0000800 // Set IdenfitierInfo to null to avoid confusing code that handles both
801 // identifiers and completion tokens.
802 Result.setIdentifierInfo(nullptr);
803 }
Vassil Vassilev644ea612016-07-27 14:56:59 +0000804
Douglas Gregor594b8c92013-11-07 22:55:02 +0000805 LastTokenWasAt = Result.is(tok::at);
Eli Friedman0834a4b2013-09-19 00:41:32 +0000806}
807
Douglas Gregorda82e702012-01-03 19:32:59 +0000808/// \brief Lex a token following the 'import' contextual keyword.
Douglas Gregor22d09742012-01-03 18:04:46 +0000809///
Douglas Gregoraf5c4842011-09-07 23:11:54 +0000810void Preprocessor::LexAfterModuleImport(Token &Result) {
811 // Figure out what kind of lexer we actually have.
Douglas Gregor8d76cca2012-01-04 06:20:15 +0000812 recomputeCurLexerKind();
Douglas Gregoraf5c4842011-09-07 23:11:54 +0000813
814 // Lex the next token.
815 Lex(Result);
816
Douglas Gregor08142532011-08-26 23:56:07 +0000817 // The token sequence
818 //
Douglas Gregor22d09742012-01-03 18:04:46 +0000819 // import identifier (. identifier)*
820 //
Douglas Gregorda82e702012-01-03 19:32:59 +0000821 // indicates a module import directive. We already saw the 'import'
822 // contextual keyword, so now we're looking for the identifiers.
Douglas Gregor1805b8a2011-11-30 04:26:53 +0000823 if (ModuleImportExpectsIdentifier && Result.getKind() == tok::identifier) {
824 // We expected to see an identifier here, and we did; continue handling
825 // identifiers.
826 ModuleImportPath.push_back(std::make_pair(Result.getIdentifierInfo(),
827 Result.getLocation()));
828 ModuleImportExpectsIdentifier = false;
829 CurLexerKind = CLK_LexAfterModuleImport;
Douglas Gregor08142532011-08-26 23:56:07 +0000830 return;
Douglas Gregor1805b8a2011-11-30 04:26:53 +0000831 }
Douglas Gregor08142532011-08-26 23:56:07 +0000832
Douglas Gregor1805b8a2011-11-30 04:26:53 +0000833 // If we're expecting a '.' or a ';', and we got a '.', then wait until we
Richard Smith49cc1cc2016-08-18 21:59:42 +0000834 // see the next identifier. (We can also see a '[[' that begins an
835 // attribute-specifier-seq here under the C++ Modules TS.)
Douglas Gregor1805b8a2011-11-30 04:26:53 +0000836 if (!ModuleImportExpectsIdentifier && Result.getKind() == tok::period) {
837 ModuleImportExpectsIdentifier = true;
838 CurLexerKind = CLK_LexAfterModuleImport;
839 return;
840 }
841
842 // If we have a non-empty module path, load the named module.
Sean Callanan87596492014-12-09 23:47:56 +0000843 if (!ModuleImportPath.empty()) {
Richard Smithbbcc9f02016-08-26 00:14:38 +0000844 // Under the Modules TS, the dot is just part of the module name, and not
845 // a real hierarachy separator. Flatten such module names now.
846 //
847 // FIXME: Is this the right level to be performing this transformation?
848 std::string FlatModuleName;
849 if (getLangOpts().ModulesTS) {
850 for (auto &Piece : ModuleImportPath) {
851 if (!FlatModuleName.empty())
852 FlatModuleName += ".";
853 FlatModuleName += Piece.first->getName();
854 }
855 SourceLocation FirstPathLoc = ModuleImportPath[0].second;
856 ModuleImportPath.clear();
857 ModuleImportPath.push_back(
858 std::make_pair(getIdentifierInfo(FlatModuleName), FirstPathLoc));
859 }
860
Sean Callanan87596492014-12-09 23:47:56 +0000861 Module *Imported = nullptr;
Richard Smith753e0072015-04-27 23:21:38 +0000862 if (getLangOpts().Modules) {
Sean Callanan87596492014-12-09 23:47:56 +0000863 Imported = TheModuleLoader.loadModule(ModuleImportLoc,
864 ModuleImportPath,
Richard Smith10434f32015-05-02 02:08:26 +0000865 Module::Hidden,
Sean Callanan87596492014-12-09 23:47:56 +0000866 /*IsIncludeDirective=*/false);
Richard Smitha7e2cc62015-05-01 01:53:09 +0000867 if (Imported)
868 makeModuleVisible(Imported, ModuleImportLoc);
Richard Smith753e0072015-04-27 23:21:38 +0000869 }
Sean Callanan87596492014-12-09 23:47:56 +0000870 if (Callbacks && (getLangOpts().Modules || getLangOpts().DebuggerSupport))
Argyrios Kyrtzidis19d78b72012-09-29 01:06:10 +0000871 Callbacks->moduleImport(ModuleImportLoc, ModuleImportPath, Imported);
872 }
Chris Lattner677757a2006-06-28 05:26:32 +0000873}
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000874
Richard Smitha7e2cc62015-05-01 01:53:09 +0000875void Preprocessor::makeModuleVisible(Module *M, SourceLocation Loc) {
Richard Smith04765ae2015-05-21 01:20:10 +0000876 CurSubmoduleState->VisibleModules.setVisible(
Richard Smitha7e2cc62015-05-01 01:53:09 +0000877 M, Loc, [](Module *) {},
878 [&](ArrayRef<Module *> Path, Module *Conflict, StringRef Message) {
879 // FIXME: Include the path in the diagnostic.
880 // FIXME: Include the import location for the conflicting module.
881 Diag(ModuleImportLoc, diag::warn_module_conflict)
882 << Path[0]->getFullModuleName()
883 << Conflict->getFullModuleName()
884 << Message;
885 });
886
887 // Add this module to the imports list of the currently-built submodule.
Richard Smithdbbc5232015-05-14 02:25:44 +0000888 if (!BuildingSubmoduleStack.empty() && M != BuildingSubmoduleStack.back().M)
Richard Smith38477db2015-05-02 00:45:56 +0000889 BuildingSubmoduleStack.back().M->Imports.insert(M);
Richard Smitha7e2cc62015-05-01 01:53:09 +0000890}
891
Andy Gibbs58905d22012-11-17 19:15:38 +0000892bool Preprocessor::FinishLexStringLiteral(Token &Result, std::string &String,
Andy Gibbsa8df57a2012-11-17 19:16:52 +0000893 const char *DiagnosticTag,
Andy Gibbs58905d22012-11-17 19:15:38 +0000894 bool AllowMacroExpansion) {
895 // We need at least one string literal.
896 if (Result.isNot(tok::string_literal)) {
Andy Gibbsa8df57a2012-11-17 19:16:52 +0000897 Diag(Result, diag::err_expected_string_literal)
898 << /*Source='in...'*/0 << DiagnosticTag;
Andy Gibbs58905d22012-11-17 19:15:38 +0000899 return false;
900 }
901
902 // Lex string literal tokens, optionally with macro expansion.
903 SmallVector<Token, 4> StrToks;
904 do {
905 StrToks.push_back(Result);
906
907 if (Result.hasUDSuffix())
908 Diag(Result, diag::err_invalid_string_udl);
909
910 if (AllowMacroExpansion)
911 Lex(Result);
912 else
913 LexUnexpandedToken(Result);
914 } while (Result.is(tok::string_literal));
915
916 // Concatenate and parse the strings.
Craig Topper9d5583e2014-06-26 04:58:39 +0000917 StringLiteralParser Literal(StrToks, *this);
Andy Gibbs58905d22012-11-17 19:15:38 +0000918 assert(Literal.isAscii() && "Didn't allow wide strings in");
919
920 if (Literal.hadError)
921 return false;
922
923 if (Literal.Pascal) {
Andy Gibbsa8df57a2012-11-17 19:16:52 +0000924 Diag(StrToks[0].getLocation(), diag::err_expected_string_literal)
925 << /*Source='in...'*/0 << DiagnosticTag;
Andy Gibbs58905d22012-11-17 19:15:38 +0000926 return false;
927 }
928
929 String = Literal.GetString();
930 return true;
931}
932
Reid Klecknerc0dca6d2014-02-12 23:50:26 +0000933bool Preprocessor::parseSimpleIntegerLiteral(Token &Tok, uint64_t &Value) {
934 assert(Tok.is(tok::numeric_constant));
935 SmallString<8> IntegerBuffer;
936 bool NumberInvalid = false;
937 StringRef Spelling = getSpelling(Tok, IntegerBuffer, &NumberInvalid);
938 if (NumberInvalid)
939 return false;
940 NumericLiteralParser Literal(Spelling, Tok.getLocation(), *this);
941 if (Literal.hadError || !Literal.isIntegerLiteral() || Literal.hasUDSuffix())
942 return false;
943 llvm::APInt APVal(64, 0);
944 if (Literal.GetIntegerValue(APVal))
945 return false;
946 Lex(Tok);
947 Value = APVal.getLimitedValue();
948 return true;
949}
950
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000951void Preprocessor::addCommentHandler(CommentHandler *Handler) {
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000952 assert(Handler && "NULL comment handler");
953 assert(std::find(CommentHandlers.begin(), CommentHandlers.end(), Handler) ==
954 CommentHandlers.end() && "Comment handler already registered");
955 CommentHandlers.push_back(Handler);
956}
957
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000958void Preprocessor::removeCommentHandler(CommentHandler *Handler) {
Eugene Zelenko5dc60fe2017-12-04 23:16:21 +0000959 std::vector<CommentHandler *>::iterator Pos =
960 std::find(CommentHandlers.begin(), CommentHandlers.end(), Handler);
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000961 assert(Pos != CommentHandlers.end() && "Comment handler not registered");
962 CommentHandlers.erase(Pos);
963}
964
Chris Lattner87d02082010-01-18 22:35:47 +0000965bool Preprocessor::HandleComment(Token &result, SourceRange Comment) {
966 bool AnyPendingTokens = false;
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000967 for (std::vector<CommentHandler *>::iterator H = CommentHandlers.begin(),
968 HEnd = CommentHandlers.end();
Chris Lattner87d02082010-01-18 22:35:47 +0000969 H != HEnd; ++H) {
970 if ((*H)->HandleComment(*this, Comment))
971 AnyPendingTokens = true;
972 }
973 if (!AnyPendingTokens || getCommentRetentionState())
974 return false;
975 Lex(result);
976 return true;
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000977}
978
Eugene Zelenko5dc60fe2017-12-04 23:16:21 +0000979ModuleLoader::~ModuleLoader() = default;
Douglas Gregor08142532011-08-26 23:56:07 +0000980
Eugene Zelenko5dc60fe2017-12-04 23:16:21 +0000981CommentHandler::~CommentHandler() = default;
Douglas Gregor7f6d60d2010-03-19 16:15:56 +0000982
Eugene Zelenko5dc60fe2017-12-04 23:16:21 +0000983CodeCompletionHandler::~CodeCompletionHandler() = default;
Douglas Gregor3a7ad252010-08-24 19:08:16 +0000984
Argyrios Kyrtzidisf3d587e2012-12-04 07:27:05 +0000985void Preprocessor::createPreprocessingRecord() {
Douglas Gregor7f6d60d2010-03-19 16:15:56 +0000986 if (Record)
987 return;
988
Argyrios Kyrtzidisf3d587e2012-12-04 07:27:05 +0000989 Record = new PreprocessingRecord(getSourceManager());
Craig Topperb8a70532014-09-10 04:53:53 +0000990 addPPCallbacks(std::unique_ptr<PPCallbacks>(Record));
Douglas Gregor7f6d60d2010-03-19 16:15:56 +0000991}