blob: 297b556015f42448ac0d8305b22c4741cd613d86 [file] [log] [blame]
Chris Lattner22eb9722006-06-18 05:43:12 +00001//===--- Preprocess.cpp - C Language Family Preprocessor Implementation ---===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner5b12ab82007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattner22eb9722006-06-18 05:43:12 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the Preprocessor interface.
11//
12//===----------------------------------------------------------------------===//
13//
Chris Lattner22eb9722006-06-18 05:43:12 +000014// Options to support:
15// -H - Print the name of each header file used.
Chris Lattner1630c3c2009-02-06 06:45:26 +000016// -d[DNI] - Dump various things.
Chris Lattner22eb9722006-06-18 05:43:12 +000017// -fworking-directory - #line's with preprocessor's working dir.
18// -fpreprocessed
19// -dependency-file,-M,-MM,-MF,-MG,-MP,-MT,-MQ,-MD,-MMD
20// -W*
21// -w
22//
23// Messages to emit:
24// "Multiple include guards may be useful for:\n"
25//
Chris Lattner22eb9722006-06-18 05:43:12 +000026//===----------------------------------------------------------------------===//
27
28#include "clang/Lex/Preprocessor.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000029#include "clang/Basic/FileManager.h"
David Blaikie23430cc2014-08-11 21:29:24 +000030#include "clang/Basic/FileSystemStatCache.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000031#include "clang/Basic/SourceManager.h"
32#include "clang/Basic/TargetInfo.h"
33#include "clang/Lex/CodeCompletionHandler.h"
Douglas Gregor9882a5a2010-01-04 19:18:44 +000034#include "clang/Lex/ExternalPreprocessorSource.h"
Chris Lattner07b019a2006-10-22 07:28:56 +000035#include "clang/Lex/HeaderSearch.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000036#include "clang/Lex/LexDiagnostic.h"
37#include "clang/Lex/LiteralSupport.h"
Chandler Carruth5553d0d2014-01-07 11:51:46 +000038#include "clang/Lex/MacroArgs.h"
Chris Lattner22eb9722006-06-18 05:43:12 +000039#include "clang/Lex/MacroInfo.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000040#include "clang/Lex/ModuleLoader.h"
Reid Kleckner738d48d2015-11-02 17:53:55 +000041#include "clang/Lex/PTHManager.h"
Chris Lattnerb8761832006-06-24 21:31:03 +000042#include "clang/Lex/Pragma.h"
Douglas Gregor7f6d60d2010-03-19 16:15:56 +000043#include "clang/Lex/PreprocessingRecord.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000044#include "clang/Lex/PreprocessorOptions.h"
Chris Lattner0b8cfc22006-06-28 06:49:17 +000045#include "clang/Lex/ScratchBuffer.h"
Chris Lattner5cd83512008-10-05 20:40:30 +000046#include "llvm/ADT/APFloat.h"
Jordan Rose7f43ddd2013-01-24 20:50:46 +000047#include "llvm/ADT/STLExtras.h"
Chandler Carruth5553d0d2014-01-07 11:51:46 +000048#include "llvm/ADT/SmallString.h"
Jordan Rose7f43ddd2013-01-24 20:50:46 +000049#include "llvm/ADT/StringExtras.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000050#include "llvm/Support/Capacity.h"
Dmitri Gribenko9feeef42013-01-30 12:06:08 +000051#include "llvm/Support/ConvertUTF.h"
Chris Lattner8a7003c2007-07-16 06:48:38 +000052#include "llvm/Support/MemoryBuffer.h"
Benjamin Kramer89b422c2009-08-23 12:08:50 +000053#include "llvm/Support/raw_ostream.h"
Chris Lattner22eb9722006-06-18 05:43:12 +000054using namespace clang;
55
NAKAMURA Takumicacd94e2016-04-04 15:30:44 +000056template class llvm::Registry<clang::PragmaHandler>;
57
Chris Lattner22eb9722006-06-18 05:43:12 +000058//===----------------------------------------------------------------------===//
Angel Garcia Gomez637d1e62015-10-20 13:23:58 +000059ExternalPreprocessorSource::~ExternalPreprocessorSource() { }
Chris Lattner22eb9722006-06-18 05:43:12 +000060
Dmitri Gribenkof8579502013-01-12 19:30:44 +000061Preprocessor::Preprocessor(IntrusiveRefCntPtr<PreprocessorOptions> PPOpts,
Douglas Gregor1452ff12012-10-24 17:46:57 +000062 DiagnosticsEngine &diags, LangOptions &opts,
Alp Toker96637802014-05-02 03:43:38 +000063 SourceManager &SM, HeaderSearch &Headers,
64 ModuleLoader &TheModuleLoader,
David Blaikie687cd952013-01-16 23:13:36 +000065 IdentifierInfoLookup *IILookup, bool OwnsHeaders,
Alp Toker1ae02f62014-05-02 03:43:30 +000066 TranslationUnitKind TUKind)
Craig Topper4b566922014-06-09 02:04:02 +000067 : PPOpts(PPOpts), Diags(&diags), LangOpts(opts), Target(nullptr),
Artem Belevichb5bc9232015-09-22 17:23:22 +000068 AuxTarget(nullptr), FileMgr(Headers.getFileMgr()), SourceMgr(SM),
69 ScratchBuf(new ScratchBuffer(SourceMgr)), HeaderInfo(Headers),
Craig Topperd2d442c2014-05-17 23:10:59 +000070 TheModuleLoader(TheModuleLoader), ExternalSource(nullptr),
Craig Topperbe250302014-09-12 05:19:24 +000071 Identifiers(opts, IILookup),
72 PragmaHandlers(new PragmaNamespace(StringRef())),
Artem Belevichb5bc9232015-09-22 17:23:22 +000073 IncrementalProcessing(false), TUKind(TUKind), CodeComplete(nullptr),
74 CodeCompletionFile(nullptr), CodeCompletionOffset(0),
75 LastTokenWasAt(false), ModuleImportExpectsIdentifier(false),
76 CodeCompletionReached(0), MainFileDir(nullptr),
77 SkipMainFilePreamble(0, true), CurPPLexer(nullptr), CurDirLookup(nullptr),
78 CurLexerKind(CLK_Lexer), CurSubmodule(nullptr), Callbacks(nullptr),
79 CurSubmoduleState(&NullSubmoduleState), MacroArgCache(nullptr),
80 Record(nullptr), MIChainHead(nullptr), DeserialMIChainHead(nullptr) {
Daniel Dunbar0c6c9302009-11-11 21:44:21 +000081 OwnsHeaderSearch = OwnsHeaders;
Douglas Gregor83297df2011-09-01 23:39:15 +000082
Douglas Gregor83297df2011-09-01 23:39:15 +000083 CounterValue = 0; // __COUNTER__ starts at 0.
84
85 // Clear stats.
86 NumDirectives = NumDefined = NumUndefined = NumPragma = 0;
87 NumIf = NumElse = NumEndif = 0;
88 NumEnteredSourceFiles = 0;
89 NumMacroExpanded = NumFnMacroExpanded = NumBuiltinMacroExpanded = 0;
90 NumFastMacroExpanded = NumTokenPaste = NumFastTokenPaste = 0;
91 MaxIncludeStackDepth = 0;
92 NumSkipped = 0;
93
94 // Default to discarding comments.
95 KeepComments = false;
96 KeepMacroComments = false;
97 SuppressIncludeNotFoundError = false;
98
99 // Macro expansion is enabled.
100 DisableMacroExpansion = false;
David Blaikied5321242012-06-06 18:52:13 +0000101 MacroExpansionInDirectivesOverride = false;
Douglas Gregor83297df2011-09-01 23:39:15 +0000102 InMacroArgs = false;
Argyrios Kyrtzidisf1b64c62012-04-03 16:47:40 +0000103 InMacroArgPreExpansion = false;
Douglas Gregor83297df2011-09-01 23:39:15 +0000104 NumCachedTokenLexers = 0;
Jordan Rosede1a2922012-06-08 18:06:21 +0000105 PragmasEnabled = true;
Eric Christopher5e4696d2013-01-16 20:09:36 +0000106 ParsingIfOrElifDirective = false;
Jordan Rose324ec422013-01-31 19:26:01 +0000107 PreprocessedOutput = false;
Jordan Rosede1a2922012-06-08 18:06:21 +0000108
Douglas Gregor83297df2011-09-01 23:39:15 +0000109 CachedLexPos = 0;
Eric Christopher5e4696d2013-01-16 20:09:36 +0000110
Douglas Gregor83297df2011-09-01 23:39:15 +0000111 // We haven't read anything from the external source.
112 ReadMacrosFromExternalSource = false;
113
Douglas Gregor83297df2011-09-01 23:39:15 +0000114 // "Poison" __VA_ARGS__, which can only appear in the expansion of a macro.
115 // This gets unpoisoned where it is allowed.
116 (Ident__VA_ARGS__ = getIdentifierInfo("__VA_ARGS__"))->setIsPoisoned();
117 SetPoisonReason(Ident__VA_ARGS__,diag::ext_pp_bad_vaargs_use);
118
119 // Initialize the pragma handlers.
Douglas Gregor83297df2011-09-01 23:39:15 +0000120 RegisterBuiltinPragmas();
121
122 // Initialize builtin macros like __LINE__ and friends.
123 RegisterBuiltinMacros();
124
David Blaikiebbafb8a2012-03-11 07:00:24 +0000125 if(LangOpts.Borland) {
Douglas Gregor83297df2011-09-01 23:39:15 +0000126 Ident__exception_info = getIdentifierInfo("_exception_info");
127 Ident___exception_info = getIdentifierInfo("__exception_info");
128 Ident_GetExceptionInfo = getIdentifierInfo("GetExceptionInformation");
129 Ident__exception_code = getIdentifierInfo("_exception_code");
130 Ident___exception_code = getIdentifierInfo("__exception_code");
131 Ident_GetExceptionCode = getIdentifierInfo("GetExceptionCode");
132 Ident__abnormal_termination = getIdentifierInfo("_abnormal_termination");
133 Ident___abnormal_termination = getIdentifierInfo("__abnormal_termination");
134 Ident_AbnormalTermination = getIdentifierInfo("AbnormalTermination");
135 } else {
Craig Topperd2d442c2014-05-17 23:10:59 +0000136 Ident__exception_info = Ident__exception_code = nullptr;
137 Ident__abnormal_termination = Ident___exception_info = nullptr;
138 Ident___exception_code = Ident___abnormal_termination = nullptr;
139 Ident_GetExceptionInfo = Ident_GetExceptionCode = nullptr;
140 Ident_AbnormalTermination = nullptr;
Douglas Gregor89929282012-01-30 06:01:29 +0000141 }
Argyrios Kyrtzidis3c9aaf12012-06-02 18:08:09 +0000142}
143
144Preprocessor::~Preprocessor() {
145 assert(BacktrackPositions.empty() && "EnableBacktrack/Backtrack imbalance!");
146
Benjamin Kramer329c5962014-03-15 16:40:40 +0000147 IncludeMacroStack.clear();
Argyrios Kyrtzidis3c9aaf12012-06-02 18:08:09 +0000148
Richard Smith73a29662014-07-24 03:25:00 +0000149 // Destroy any macro definitions.
150 while (MacroInfoChain *I = MIChainHead) {
151 MIChainHead = I->Next;
152 I->~MacroInfoChain();
153 }
Argyrios Kyrtzidis3c9aaf12012-06-02 18:08:09 +0000154
155 // Free any cached macro expanders.
Nico Weber5f5b9412014-05-09 18:09:42 +0000156 // This populates MacroArgCache, so all TokenLexers need to be destroyed
157 // before the code below that frees up the MacroArgCache list.
David Blaikie6d5038c2014-08-29 19:36:52 +0000158 std::fill(TokenLexerCache, TokenLexerCache + NumCachedTokenLexers, nullptr);
Nico Weber5f5b9412014-05-09 18:09:42 +0000159 CurTokenLexer.reset();
Argyrios Kyrtzidis3c9aaf12012-06-02 18:08:09 +0000160
Richard Smith73a29662014-07-24 03:25:00 +0000161 while (DeserializedMacroInfoChain *I = DeserialMIChainHead) {
162 DeserialMIChainHead = I->Next;
163 I->~DeserializedMacroInfoChain();
164 }
Argyrios Kyrtzidisd48b91d2013-04-30 05:05:35 +0000165
Argyrios Kyrtzidis3c9aaf12012-06-02 18:08:09 +0000166 // Free any cached MacroArgs.
Nico Weber5f5b9412014-05-09 18:09:42 +0000167 for (MacroArgs *ArgList = MacroArgCache; ArgList;)
Argyrios Kyrtzidis3c9aaf12012-06-02 18:08:09 +0000168 ArgList = ArgList->deallocate();
169
Argyrios Kyrtzidis3c9aaf12012-06-02 18:08:09 +0000170 // Delete the header search info, if we own it.
171 if (OwnsHeaderSearch)
172 delete &HeaderInfo;
Argyrios Kyrtzidis3c9aaf12012-06-02 18:08:09 +0000173}
174
Artem Belevichb5bc9232015-09-22 17:23:22 +0000175void Preprocessor::Initialize(const TargetInfo &Target,
176 const TargetInfo *AuxTarget) {
Argyrios Kyrtzidis3c9aaf12012-06-02 18:08:09 +0000177 assert((!this->Target || this->Target == &Target) &&
178 "Invalid override of target information");
179 this->Target = &Target;
Artem Belevichb5bc9232015-09-22 17:23:22 +0000180
181 assert((!this->AuxTarget || this->AuxTarget == AuxTarget) &&
182 "Invalid override of aux target information.");
183 this->AuxTarget = AuxTarget;
184
Argyrios Kyrtzidis3c9aaf12012-06-02 18:08:09 +0000185 // Initialize information about built-ins.
Artem Belevichb5bc9232015-09-22 17:23:22 +0000186 BuiltinInfo.InitializeTarget(Target, AuxTarget);
Douglas Gregor89929282012-01-30 06:01:29 +0000187 HeaderInfo.setTarget(Target);
Douglas Gregor83297df2011-09-01 23:39:15 +0000188}
189
Ted Kremenekeeccb302014-08-27 15:14:15 +0000190void Preprocessor::InitializeForModelFile() {
191 NumEnteredSourceFiles = 0;
192
193 // Reset pragmas
David Blaikie9f0af9d2014-09-15 21:31:42 +0000194 PragmaHandlersBackup = std::move(PragmaHandlers);
Craig Topperbe250302014-09-12 05:19:24 +0000195 PragmaHandlers = llvm::make_unique<PragmaNamespace>(StringRef());
Ted Kremenekeeccb302014-08-27 15:14:15 +0000196 RegisterBuiltinPragmas();
197
198 // Reset PredefinesFileID
199 PredefinesFileID = FileID();
200}
201
202void Preprocessor::FinalizeForModelFile() {
203 NumEnteredSourceFiles = 1;
204
David Blaikie9f0af9d2014-09-15 21:31:42 +0000205 PragmaHandlers = std::move(PragmaHandlersBackup);
Ted Kremenekeeccb302014-08-27 15:14:15 +0000206}
207
Ted Kremeneka5c2c272009-02-12 03:26:59 +0000208void Preprocessor::setPTHManager(PTHManager* pm) {
209 PTH.reset(pm);
Douglas Gregord2eb58a2009-10-16 18:18:30 +0000210 FileMgr.addStatCache(PTH->createStatCache());
Ted Kremeneka5c2c272009-02-12 03:26:59 +0000211}
212
Chris Lattner146762e2007-07-20 16:59:19 +0000213void Preprocessor::DumpToken(const Token &Tok, bool DumpFlags) const {
Benjamin Kramer89b422c2009-08-23 12:08:50 +0000214 llvm::errs() << tok::getTokenName(Tok.getKind()) << " '"
215 << getSpelling(Tok) << "'";
Mike Stump11289f42009-09-09 15:08:12 +0000216
Chris Lattnerd01e2912006-06-18 16:22:51 +0000217 if (!DumpFlags) return;
Mike Stump11289f42009-09-09 15:08:12 +0000218
Benjamin Kramer89b422c2009-08-23 12:08:50 +0000219 llvm::errs() << "\t";
Chris Lattnerd01e2912006-06-18 16:22:51 +0000220 if (Tok.isAtStartOfLine())
Benjamin Kramer89b422c2009-08-23 12:08:50 +0000221 llvm::errs() << " [StartOfLine]";
Chris Lattnerd01e2912006-06-18 16:22:51 +0000222 if (Tok.hasLeadingSpace())
Benjamin Kramer89b422c2009-08-23 12:08:50 +0000223 llvm::errs() << " [LeadingSpace]";
Chris Lattner6e4bf522006-07-27 06:59:25 +0000224 if (Tok.isExpandDisabled())
Benjamin Kramer89b422c2009-08-23 12:08:50 +0000225 llvm::errs() << " [ExpandDisabled]";
Chris Lattnerd01e2912006-06-18 16:22:51 +0000226 if (Tok.needsCleaning()) {
Chris Lattner50b497e2006-06-18 16:32:35 +0000227 const char *Start = SourceMgr.getCharacterData(Tok.getLocation());
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000228 llvm::errs() << " [UnClean='" << StringRef(Start, Tok.getLength())
Benjamin Kramer89b422c2009-08-23 12:08:50 +0000229 << "']";
Chris Lattnerd01e2912006-06-18 16:22:51 +0000230 }
Mike Stump11289f42009-09-09 15:08:12 +0000231
Benjamin Kramer89b422c2009-08-23 12:08:50 +0000232 llvm::errs() << "\tLoc=<";
Chris Lattner615315f2007-12-09 20:31:55 +0000233 DumpLocation(Tok.getLocation());
Benjamin Kramer89b422c2009-08-23 12:08:50 +0000234 llvm::errs() << ">";
Chris Lattner615315f2007-12-09 20:31:55 +0000235}
236
237void Preprocessor::DumpLocation(SourceLocation Loc) const {
Chris Lattnerf1ca7d32009-01-27 07:57:44 +0000238 Loc.dump(SourceMgr);
Chris Lattnerd01e2912006-06-18 16:22:51 +0000239}
240
241void Preprocessor::DumpMacro(const MacroInfo &MI) const {
Benjamin Kramer89b422c2009-08-23 12:08:50 +0000242 llvm::errs() << "MACRO: ";
Chris Lattnerd01e2912006-06-18 16:22:51 +0000243 for (unsigned i = 0, e = MI.getNumTokens(); i != e; ++i) {
244 DumpToken(MI.getReplacementToken(i));
Benjamin Kramer89b422c2009-08-23 12:08:50 +0000245 llvm::errs() << " ";
Chris Lattnerd01e2912006-06-18 16:22:51 +0000246 }
Benjamin Kramer89b422c2009-08-23 12:08:50 +0000247 llvm::errs() << "\n";
Chris Lattnerd01e2912006-06-18 16:22:51 +0000248}
249
Chris Lattner22eb9722006-06-18 05:43:12 +0000250void Preprocessor::PrintStats() {
Benjamin Kramer89b422c2009-08-23 12:08:50 +0000251 llvm::errs() << "\n*** Preprocessor Stats:\n";
252 llvm::errs() << NumDirectives << " directives found:\n";
253 llvm::errs() << " " << NumDefined << " #define.\n";
254 llvm::errs() << " " << NumUndefined << " #undef.\n";
255 llvm::errs() << " #include/#include_next/#import:\n";
256 llvm::errs() << " " << NumEnteredSourceFiles << " source files entered.\n";
257 llvm::errs() << " " << MaxIncludeStackDepth << " max include stack depth\n";
258 llvm::errs() << " " << NumIf << " #if/#ifndef/#ifdef.\n";
259 llvm::errs() << " " << NumElse << " #else/#elif.\n";
260 llvm::errs() << " " << NumEndif << " #endif.\n";
261 llvm::errs() << " " << NumPragma << " #pragma.\n";
262 llvm::errs() << NumSkipped << " #if/#ifndef#ifdef regions skipped\n";
Chris Lattner22eb9722006-06-18 05:43:12 +0000263
Benjamin Kramer89b422c2009-08-23 12:08:50 +0000264 llvm::errs() << NumMacroExpanded << "/" << NumFnMacroExpanded << "/"
Ted Kremeneka0a3e9b2008-01-14 16:44:48 +0000265 << NumBuiltinMacroExpanded << " obj/fn/builtin macros expanded, "
266 << NumFastMacroExpanded << " on the fast path.\n";
Benjamin Kramer89b422c2009-08-23 12:08:50 +0000267 llvm::errs() << (NumFastTokenPaste+NumTokenPaste)
Ted Kremeneka0a3e9b2008-01-14 16:44:48 +0000268 << " token paste (##) operations performed, "
269 << NumFastTokenPaste << " on the fast path.\n";
Alexander Kornienko199cd942012-08-13 10:46:42 +0000270
271 llvm::errs() << "\nPreprocessor Memory: " << getTotalMemory() << "B total";
272
273 llvm::errs() << "\n BumpPtr: " << BP.getTotalMemory();
274 llvm::errs() << "\n Macro Expanded Tokens: "
275 << llvm::capacity_in_bytes(MacroExpandedTokens);
276 llvm::errs() << "\n Predefines Buffer: " << Predefines.capacity();
Richard Smith04765ae2015-05-21 01:20:10 +0000277 // FIXME: List information for all submodules.
278 llvm::errs() << "\n Macros: "
279 << llvm::capacity_in_bytes(CurSubmoduleState->Macros);
Alexander Kornienko199cd942012-08-13 10:46:42 +0000280 llvm::errs() << "\n #pragma push_macro Info: "
281 << llvm::capacity_in_bytes(PragmaPushMacroInfo);
282 llvm::errs() << "\n Poison Reasons: "
283 << llvm::capacity_in_bytes(PoisonReasons);
284 llvm::errs() << "\n Comment Handlers: "
285 << llvm::capacity_in_bytes(CommentHandlers) << "\n";
Chris Lattner22eb9722006-06-18 05:43:12 +0000286}
287
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +0000288Preprocessor::macro_iterator
289Preprocessor::macro_begin(bool IncludeExternalMacros) const {
290 if (IncludeExternalMacros && ExternalSource &&
Douglas Gregor9882a5a2010-01-04 19:18:44 +0000291 !ReadMacrosFromExternalSource) {
292 ReadMacrosFromExternalSource = true;
293 ExternalSource->ReadDefinedMacros();
294 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +0000295
Jordan Rosea46bfa62015-06-24 19:27:02 +0000296 // Make sure we cover all macros in visible modules.
297 for (const ModuleMacro &Macro : ModuleMacros)
298 CurSubmoduleState->Macros.insert(std::make_pair(Macro.II, MacroState()));
299
Richard Smith04765ae2015-05-21 01:20:10 +0000300 return CurSubmoduleState->Macros.begin();
Douglas Gregor9882a5a2010-01-04 19:18:44 +0000301}
302
Argyrios Kyrtzidise379ee32011-06-29 22:20:04 +0000303size_t Preprocessor::getTotalMemory() const {
Ted Kremenek182543a2011-07-26 21:17:24 +0000304 return BP.getTotalMemory()
Ted Kremenek8b77fe72011-07-27 18:41:23 +0000305 + llvm::capacity_in_bytes(MacroExpandedTokens)
Ted Kremenek182543a2011-07-26 21:17:24 +0000306 + Predefines.capacity() /* Predefines buffer. */
Richard Smith04765ae2015-05-21 01:20:10 +0000307 // FIXME: Include sizes from all submodules, and include MacroInfo sizes,
308 // and ModuleMacros.
309 + llvm::capacity_in_bytes(CurSubmoduleState->Macros)
Ted Kremenek8b77fe72011-07-27 18:41:23 +0000310 + llvm::capacity_in_bytes(PragmaPushMacroInfo)
311 + llvm::capacity_in_bytes(PoisonReasons)
312 + llvm::capacity_in_bytes(CommentHandlers);
Argyrios Kyrtzidise379ee32011-06-29 22:20:04 +0000313}
314
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +0000315Preprocessor::macro_iterator
316Preprocessor::macro_end(bool IncludeExternalMacros) const {
317 if (IncludeExternalMacros && ExternalSource &&
Douglas Gregor9882a5a2010-01-04 19:18:44 +0000318 !ReadMacrosFromExternalSource) {
319 ReadMacrosFromExternalSource = true;
320 ExternalSource->ReadDefinedMacros();
321 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +0000322
Richard Smith04765ae2015-05-21 01:20:10 +0000323 return CurSubmoduleState->Macros.end();
Douglas Gregor9882a5a2010-01-04 19:18:44 +0000324}
325
Dmitri Gribenko6743e042012-09-29 11:40:46 +0000326/// \brief Compares macro tokens with a specified token value sequence.
327static bool MacroDefinitionEquals(const MacroInfo *MI,
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000328 ArrayRef<TokenValue> Tokens) {
Dmitri Gribenko6743e042012-09-29 11:40:46 +0000329 return Tokens.size() == MI->getNumTokens() &&
330 std::equal(Tokens.begin(), Tokens.end(), MI->tokens_begin());
331}
332
333StringRef Preprocessor::getLastMacroWithSpelling(
334 SourceLocation Loc,
335 ArrayRef<TokenValue> Tokens) const {
336 SourceLocation BestLocation;
337 StringRef BestSpelling;
338 for (Preprocessor::macro_iterator I = macro_begin(), E = macro_end();
339 I != E; ++I) {
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +0000340 const MacroDirective::DefInfo
Richard Smithb8b2ed62015-04-23 18:18:26 +0000341 Def = I->second.findDirectiveAtLoc(Loc, SourceMgr);
Argyrios Kyrtzidis5c585252015-03-04 16:03:07 +0000342 if (!Def || !Def.getMacroInfo())
343 continue;
344 if (!Def.getMacroInfo()->isObjectLike())
Dmitri Gribenko6743e042012-09-29 11:40:46 +0000345 continue;
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +0000346 if (!MacroDefinitionEquals(Def.getMacroInfo(), Tokens))
Dmitri Gribenko6743e042012-09-29 11:40:46 +0000347 continue;
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +0000348 SourceLocation Location = Def.getLocation();
Dmitri Gribenko6743e042012-09-29 11:40:46 +0000349 // Choose the macro defined latest.
350 if (BestLocation.isInvalid() ||
351 (Location.isValid() &&
352 SourceMgr.isBeforeInTranslationUnit(BestLocation, Location))) {
353 BestLocation = Location;
354 BestSpelling = I->first->getName();
355 }
356 }
357 return BestSpelling;
358}
359
Douglas Gregor8d76cca2012-01-04 06:20:15 +0000360void Preprocessor::recomputeCurLexerKind() {
361 if (CurLexer)
362 CurLexerKind = CLK_Lexer;
363 else if (CurPTHLexer)
364 CurLexerKind = CLK_PTHLexer;
365 else if (CurTokenLexer)
366 CurLexerKind = CLK_TokenLexer;
367 else
368 CurLexerKind = CLK_CachingLexer;
369}
370
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +0000371bool Preprocessor::SetCodeCompletionPoint(const FileEntry *File,
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +0000372 unsigned CompleteLine,
373 unsigned CompleteColumn) {
374 assert(File);
375 assert(CompleteLine && CompleteColumn && "Starts from 1:1");
376 assert(!CodeCompletionFile && "Already set");
377
Douglas Gregor53ad6b92009-12-02 06:49:09 +0000378 using llvm::MemoryBuffer;
379
Douglas Gregor53ad6b92009-12-02 06:49:09 +0000380 // Load the actual file's contents.
Douglas Gregor26266da2010-03-16 19:49:24 +0000381 bool Invalid = false;
382 const MemoryBuffer *Buffer = SourceMgr.getMemoryBufferForFile(File, &Invalid);
383 if (Invalid)
Douglas Gregor53ad6b92009-12-02 06:49:09 +0000384 return true;
385
386 // Find the byte position of the truncation point.
387 const char *Position = Buffer->getBufferStart();
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +0000388 for (unsigned Line = 1; Line < CompleteLine; ++Line) {
Douglas Gregor53ad6b92009-12-02 06:49:09 +0000389 for (; *Position; ++Position) {
390 if (*Position != '\r' && *Position != '\n')
391 continue;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +0000392
Douglas Gregor53ad6b92009-12-02 06:49:09 +0000393 // Eat \r\n or \n\r as a single line.
394 if ((Position[1] == '\r' || Position[1] == '\n') &&
395 Position[0] != Position[1])
396 ++Position;
397 ++Position;
398 break;
399 }
400 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +0000401
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +0000402 Position += CompleteColumn - 1;
Argyrios Kyrtzidisee301f92014-10-18 06:23:50 +0000403
404 // If pointing inside the preamble, adjust the position at the beginning of
405 // the file after the preamble.
406 if (SkipMainFilePreamble.first &&
407 SourceMgr.getFileEntryForID(SourceMgr.getMainFileID()) == File) {
408 if (Position - Buffer->getBufferStart() < SkipMainFilePreamble.first)
409 Position = Buffer->getBufferStart() + SkipMainFilePreamble.first;
410 }
411
Argyrios Kyrtzidise62d6822014-10-18 06:19:36 +0000412 if (Position > Buffer->getBufferEnd())
413 Position = Buffer->getBufferEnd();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +0000414
Argyrios Kyrtzidise62d6822014-10-18 06:19:36 +0000415 CodeCompletionFile = File;
416 CodeCompletionOffset = Position - Buffer->getBufferStart();
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +0000417
Argyrios Kyrtzidise62d6822014-10-18 06:19:36 +0000418 std::unique_ptr<MemoryBuffer> NewBuffer =
419 MemoryBuffer::getNewUninitMemBuffer(Buffer->getBufferSize() + 1,
420 Buffer->getBufferIdentifier());
421 char *NewBuf = const_cast<char*>(NewBuffer->getBufferStart());
422 char *NewPos = std::copy(Buffer->getBufferStart(), Position, NewBuf);
423 *NewPos = '\0';
424 std::copy(Position, Buffer->getBufferEnd(), NewPos+1);
425 SourceMgr.overrideFileContents(File, std::move(NewBuffer));
Douglas Gregor53ad6b92009-12-02 06:49:09 +0000426
427 return false;
428}
429
Douglas Gregor11583702010-08-25 17:04:25 +0000430void Preprocessor::CodeCompleteNaturalLanguage() {
Douglas Gregor11583702010-08-25 17:04:25 +0000431 if (CodeComplete)
432 CodeComplete->CodeCompleteNaturalLanguage();
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +0000433 setCodeCompletionReached();
Douglas Gregor11583702010-08-25 17:04:25 +0000434}
435
Benjamin Kramera197fb62010-02-27 17:05:45 +0000436/// getSpelling - This method is used to get the spelling of a token into a
437/// SmallVector. Note that the returned StringRef may not point to the
438/// supplied buffer if a copy can be avoided.
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000439StringRef Preprocessor::getSpelling(const Token &Tok,
440 SmallVectorImpl<char> &Buffer,
Douglas Gregor7bda4b82010-03-16 05:20:39 +0000441 bool *Invalid) const {
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +0000442 // NOTE: this has to be checked *before* testing for an IdentifierInfo.
Jordan Rose7f43ddd2013-01-24 20:50:46 +0000443 if (Tok.isNot(tok::raw_identifier) && !Tok.hasUCN()) {
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +0000444 // Try the fast path.
445 if (const IdentifierInfo *II = Tok.getIdentifierInfo())
446 return II->getName();
447 }
Benjamin Kramera197fb62010-02-27 17:05:45 +0000448
449 // Resize the buffer if we need to copy into it.
450 if (Tok.needsCleaning())
451 Buffer.resize(Tok.getLength());
452
453 const char *Ptr = Buffer.data();
Douglas Gregor7bda4b82010-03-16 05:20:39 +0000454 unsigned Len = getSpelling(Tok, Ptr, Invalid);
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000455 return StringRef(Ptr, Len);
Benjamin Kramera197fb62010-02-27 17:05:45 +0000456}
457
Chris Lattnerb94ec7b2006-07-14 06:54:10 +0000458/// CreateString - Plop the specified string into a scratch buffer and return a
459/// location for it. If specified, the source location provides a source
460/// location for the token.
Dmitri Gribenkob8e9e752012-09-24 21:07:17 +0000461void Preprocessor::CreateString(StringRef Str, Token &Tok,
Abramo Bagnarae398e602011-10-03 18:39:03 +0000462 SourceLocation ExpansionLocStart,
463 SourceLocation ExpansionLocEnd) {
Dmitri Gribenkob8e9e752012-09-24 21:07:17 +0000464 Tok.setLength(Str.size());
Mike Stump11289f42009-09-09 15:08:12 +0000465
Chris Lattner5a7971e2009-01-26 19:29:26 +0000466 const char *DestPtr;
Dmitri Gribenkob8e9e752012-09-24 21:07:17 +0000467 SourceLocation Loc = ScratchBuf->getToken(Str.data(), Str.size(), DestPtr);
Mike Stump11289f42009-09-09 15:08:12 +0000468
Abramo Bagnarae398e602011-10-03 18:39:03 +0000469 if (ExpansionLocStart.isValid())
470 Loc = SourceMgr.createExpansionLoc(Loc, ExpansionLocStart,
Dmitri Gribenkob8e9e752012-09-24 21:07:17 +0000471 ExpansionLocEnd, Str.size());
Chris Lattner5a7971e2009-01-26 19:29:26 +0000472 Tok.setLocation(Loc);
Mike Stump11289f42009-09-09 15:08:12 +0000473
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +0000474 // If this is a raw identifier or a literal token, set the pointer data.
475 if (Tok.is(tok::raw_identifier))
476 Tok.setRawIdentifierData(DestPtr);
477 else if (Tok.isLiteral())
Chris Lattner5a7971e2009-01-26 19:29:26 +0000478 Tok.setLiteralData(DestPtr);
Chris Lattnerb94ec7b2006-07-14 06:54:10 +0000479}
480
Douglas Gregor2b82c2a2011-12-02 01:47:07 +0000481Module *Preprocessor::getCurrentModule() {
Richard Smith7e82e012016-02-19 22:25:36 +0000482 if (!getLangOpts().CompilingModule)
Craig Topperd2d442c2014-05-17 23:10:59 +0000483 return nullptr;
484
David Blaikiebbafb8a2012-03-11 07:00:24 +0000485 return getHeaderSearchInfo().lookupModule(getLangOpts().CurrentModule);
Douglas Gregor2b82c2a2011-12-02 01:47:07 +0000486}
Chris Lattner8a7003c2007-07-16 06:48:38 +0000487
Chris Lattner1f1b0db2007-10-09 22:10:18 +0000488//===----------------------------------------------------------------------===//
489// Preprocessor Initialization Methods
490//===----------------------------------------------------------------------===//
491
Chris Lattner1f1b0db2007-10-09 22:10:18 +0000492
493/// EnterMainSourceFile - Enter the specified FileID as the main source file,
Nate Begemanf7c3ff62008-01-07 04:01:26 +0000494/// which implicitly adds the builtin defines etc.
Chris Lattnerfb24a3a2010-04-20 20:35:58 +0000495void Preprocessor::EnterMainSourceFile() {
Chris Lattner9ef847b2009-02-13 19:33:24 +0000496 // We do not allow the preprocessor to reenter the main file. Doing so will
497 // cause FileID's to accumulate information from both runs (e.g. #line
498 // information) and predefined macros aren't guaranteed to be set properly.
499 assert(NumEnteredSourceFiles == 0 && "Cannot reenter the main file!");
Chris Lattnerd32480d2009-01-17 06:22:33 +0000500 FileID MainFileID = SourceMgr.getMainFileID();
Mike Stump11289f42009-09-09 15:08:12 +0000501
Argyrios Kyrtzidis9afd4492012-01-05 21:36:25 +0000502 // If MainFileID is loaded it means we loaded an AST file, no need to enter
503 // a main file.
504 if (!SourceMgr.isLoadedFileID(MainFileID)) {
505 // Enter the main file source buffer.
Craig Topperd2d442c2014-05-17 23:10:59 +0000506 EnterSourceFile(MainFileID, nullptr, SourceLocation());
507
Argyrios Kyrtzidis9afd4492012-01-05 21:36:25 +0000508 // If we've been asked to skip bytes in the main file (e.g., as part of a
509 // precompiled preamble), do so now.
510 if (SkipMainFilePreamble.first > 0)
511 CurLexer->SkipBytes(SkipMainFilePreamble.first,
512 SkipMainFilePreamble.second);
513
514 // Tell the header info that the main file was entered. If the file is later
515 // #imported, it won't be re-entered.
516 if (const FileEntry *FE = SourceMgr.getFileEntryForID(MainFileID))
517 HeaderInfo.IncrementIncludeCount(FE);
518 }
Mike Stump11289f42009-09-09 15:08:12 +0000519
Benjamin Kramerd77adb52009-12-31 15:33:09 +0000520 // Preprocess Predefines to populate the initial preprocessor state.
Rafael Espindolad87f8d72014-08-27 20:03:29 +0000521 std::unique_ptr<llvm::MemoryBuffer> SB =
Chris Lattner58c79342010-04-05 22:42:27 +0000522 llvm::MemoryBuffer::getMemBufferCopy(Predefines, "<built-in>");
Douglas Gregor33551892010-08-26 14:07:34 +0000523 assert(SB && "Cannot create predefined source buffer");
David Blaikie50a5f972014-08-29 07:59:55 +0000524 FileID FID = SourceMgr.createFileID(std::move(SB));
Yaron Keren8b563662015-10-03 10:46:20 +0000525 assert(FID.isValid() && "Could not create FileID for predefines?");
Argyrios Kyrtzidis22c22f52013-02-01 16:36:07 +0000526 setPredefinesFileID(FID);
Mike Stump11289f42009-09-09 15:08:12 +0000527
Chris Lattner1f1b0db2007-10-09 22:10:18 +0000528 // Start parsing the predefines.
Craig Topperd2d442c2014-05-17 23:10:59 +0000529 EnterSourceFile(FID, nullptr, SourceLocation());
Chris Lattner1f1b0db2007-10-09 22:10:18 +0000530}
Chris Lattner8a7003c2007-07-16 06:48:38 +0000531
Daniel Dunbarcb9eaf52010-03-23 05:09:10 +0000532void Preprocessor::EndSourceFile() {
533 // Notify the client that we reached the end of the source file.
534 if (Callbacks)
535 Callbacks->EndOfMainFile();
536}
Chris Lattner677757a2006-06-28 05:26:32 +0000537
538//===----------------------------------------------------------------------===//
539// Lexer Event Handling.
540//===----------------------------------------------------------------------===//
541
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +0000542/// LookUpIdentifierInfo - Given a tok::raw_identifier token, look up the
543/// identifier information for the token and install it into the token,
544/// updating the token kind accordingly.
545IdentifierInfo *Preprocessor::LookUpIdentifierInfo(Token &Identifier) const {
Alp Toker2d57cea2014-05-17 04:53:25 +0000546 assert(!Identifier.getRawIdentifier().empty() && "No raw identifier data!");
Mike Stump11289f42009-09-09 15:08:12 +0000547
Chris Lattnercefc7682006-07-08 08:28:12 +0000548 // Look up this token, see if it is a macro, or if it is a language keyword.
549 IdentifierInfo *II;
Jordan Rose7f43ddd2013-01-24 20:50:46 +0000550 if (!Identifier.needsCleaning() && !Identifier.hasUCN()) {
Chris Lattnercefc7682006-07-08 08:28:12 +0000551 // No cleaning needed, just use the characters from the lexed buffer.
Alp Toker2d57cea2014-05-17 04:53:25 +0000552 II = getIdentifierInfo(Identifier.getRawIdentifier());
Chris Lattnercefc7682006-07-08 08:28:12 +0000553 } else {
554 // Cleaning needed, alloca a buffer, clean into it, then use the buffer.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +0000555 SmallString<64> IdentifierBuffer;
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000556 StringRef CleanedStr = getSpelling(Identifier, IdentifierBuffer);
Jordan Rose7f43ddd2013-01-24 20:50:46 +0000557
558 if (Identifier.hasUCN()) {
559 SmallString<64> UCNIdentifierBuffer;
560 expandUCNs(UCNIdentifierBuffer, CleanedStr);
561 II = getIdentifierInfo(UCNIdentifierBuffer);
562 } else {
563 II = getIdentifierInfo(CleanedStr);
564 }
Chris Lattnercefc7682006-07-08 08:28:12 +0000565 }
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +0000566
567 // Update the token info (identifier info and appropriate token kind).
Chris Lattner8c204872006-10-14 05:19:21 +0000568 Identifier.setIdentifierInfo(II);
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +0000569 Identifier.setKind(II->getTokenID());
570
Chris Lattnercefc7682006-07-08 08:28:12 +0000571 return II;
572}
573
John Wiegley1c0675e2011-04-28 01:08:34 +0000574void Preprocessor::SetPoisonReason(IdentifierInfo *II, unsigned DiagID) {
575 PoisonReasons[II] = DiagID;
576}
577
578void Preprocessor::PoisonSEHIdentifiers(bool Poison) {
579 assert(Ident__exception_code && Ident__exception_info);
580 assert(Ident___exception_code && Ident___exception_info);
581 Ident__exception_code->setIsPoisoned(Poison);
582 Ident___exception_code->setIsPoisoned(Poison);
583 Ident_GetExceptionCode->setIsPoisoned(Poison);
584 Ident__exception_info->setIsPoisoned(Poison);
585 Ident___exception_info->setIsPoisoned(Poison);
586 Ident_GetExceptionInfo->setIsPoisoned(Poison);
587 Ident__abnormal_termination->setIsPoisoned(Poison);
588 Ident___abnormal_termination->setIsPoisoned(Poison);
589 Ident_AbnormalTermination->setIsPoisoned(Poison);
590}
591
592void Preprocessor::HandlePoisonedIdentifier(Token & Identifier) {
593 assert(Identifier.getIdentifierInfo() &&
594 "Can't handle identifiers without identifier info!");
595 llvm::DenseMap<IdentifierInfo*,unsigned>::const_iterator it =
596 PoisonReasons.find(Identifier.getIdentifierInfo());
597 if(it == PoisonReasons.end())
598 Diag(Identifier, diag::err_pp_used_poisoned_id);
599 else
600 Diag(Identifier,it->second) << Identifier.getIdentifierInfo();
601}
Chris Lattnercefc7682006-07-08 08:28:12 +0000602
Richard Smith31d51842015-05-14 04:00:59 +0000603/// \brief Returns a diagnostic message kind for reporting a future keyword as
604/// appropriate for the identifier and specified language.
605static diag::kind getFutureCompatDiagKind(const IdentifierInfo &II,
606 const LangOptions &LangOpts) {
607 assert(II.isFutureCompatKeyword() && "diagnostic should not be needed");
608
609 if (LangOpts.CPlusPlus)
610 return llvm::StringSwitch<diag::kind>(II.getName())
611#define CXX11_KEYWORD(NAME, FLAGS) \
612 .Case(#NAME, diag::warn_cxx11_keyword)
613#include "clang/Basic/TokenKinds.def"
614 ;
615
616 llvm_unreachable(
617 "Keyword not known to come from a newer Standard or proposed Standard");
618}
619
Chris Lattner677757a2006-06-28 05:26:32 +0000620/// HandleIdentifier - This callback is invoked when the lexer reads an
621/// identifier. This callback looks up the identifier in the map and/or
622/// potentially macro expands it or turns it into a named token (like 'for').
Chris Lattnerad89ec02009-01-21 07:43:11 +0000623///
624/// Note that callers of this method are guarded by checking the
625/// IdentifierInfo's 'isHandleIdentifierCase' bit. If this method changes, the
626/// IdentifierInfo methods that compute these properties will need to change to
627/// match.
Eli Friedman0834a4b2013-09-19 00:41:32 +0000628bool Preprocessor::HandleIdentifier(Token &Identifier) {
Chris Lattner0f1f5052006-07-20 04:16:23 +0000629 assert(Identifier.getIdentifierInfo() &&
630 "Can't handle identifiers without identifier info!");
Mike Stump11289f42009-09-09 15:08:12 +0000631
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000632 IdentifierInfo &II = *Identifier.getIdentifierInfo();
Chris Lattner677757a2006-06-28 05:26:32 +0000633
Douglas Gregor935bc7a22011-10-27 09:33:13 +0000634 // If the information about this identifier is out of date, update it from
635 // the external source.
Douglas Gregor3f568c12012-06-29 18:27:59 +0000636 // We have to treat __VA_ARGS__ in a special way, since it gets
637 // serialized with isPoisoned = true, but our preprocessor may have
638 // unpoisoned it if we're defining a C99 macro.
Douglas Gregor935bc7a22011-10-27 09:33:13 +0000639 if (II.isOutOfDate()) {
Douglas Gregor3f568c12012-06-29 18:27:59 +0000640 bool CurrentIsPoisoned = false;
641 if (&II == Ident__VA_ARGS__)
642 CurrentIsPoisoned = Ident__VA_ARGS__->isPoisoned();
643
Douglas Gregor935bc7a22011-10-27 09:33:13 +0000644 ExternalSource->updateOutOfDateIdentifier(II);
645 Identifier.setKind(II.getTokenID());
Douglas Gregor3f568c12012-06-29 18:27:59 +0000646
647 if (&II == Ident__VA_ARGS__)
648 II.setIsPoisoned(CurrentIsPoisoned);
Douglas Gregor935bc7a22011-10-27 09:33:13 +0000649 }
650
Chris Lattner677757a2006-06-28 05:26:32 +0000651 // If this identifier was poisoned, and if it was not produced from a macro
652 // expansion, emit an error.
Ted Kremeneka2c3c8d2008-11-19 22:43:49 +0000653 if (II.isPoisoned() && CurPPLexer) {
John Wiegley1c0675e2011-04-28 01:08:34 +0000654 HandlePoisonedIdentifier(Identifier);
Chris Lattner8ff71992006-07-06 05:17:39 +0000655 }
Mike Stump11289f42009-09-09 15:08:12 +0000656
Chris Lattner78186052006-07-09 00:45:31 +0000657 // If this is a macro to be expanded, do it.
Richard Smith20e883e2015-04-29 23:20:19 +0000658 if (MacroDefinition MD = getMacroDefinition(&II)) {
659 auto *MI = MD.getMacroInfo();
Richard Smithf5ec2ac2015-04-29 23:40:48 +0000660 assert(MI && "macro definition with no macro info?");
Abramo Bagnara123bec82012-01-01 22:01:04 +0000661 if (!DisableMacroExpansion) {
Richard Smith181879c2012-12-12 02:46:14 +0000662 if (!Identifier.isExpandDisabled() && MI->isEnabled()) {
Eli Friedman0834a4b2013-09-19 00:41:32 +0000663 // C99 6.10.3p10: If the preprocessing token immediately after the
664 // macro name isn't a '(', this macro should not be expanded.
665 if (!MI->isFunctionLike() || isNextPPTokenLParen())
666 return HandleMacroExpandedIdentifier(Identifier, MD);
Chris Lattner6e4bf522006-07-27 06:59:25 +0000667 } else {
668 // C99 6.10.3.4p2 says that a disabled macro may never again be
669 // expanded, even if it's in a context where it could be expanded in the
670 // future.
Chris Lattner146762e2007-07-20 16:59:19 +0000671 Identifier.setFlag(Token::DisableExpand);
Richard Smith181879c2012-12-12 02:46:14 +0000672 if (MI->isObjectLike() || isNextPPTokenLParen())
673 Diag(Identifier, diag::pp_disabled_macro_expansion);
Chris Lattner6e4bf522006-07-27 06:59:25 +0000674 }
675 }
Chris Lattner063400e2006-10-14 19:54:15 +0000676 }
Chris Lattner677757a2006-06-28 05:26:32 +0000677
Richard Smith31d51842015-05-14 04:00:59 +0000678 // If this identifier is a keyword in a newer Standard or proposed Standard,
679 // produce a warning. Don't warn if we're not considering macro expansion,
680 // since this identifier might be the name of a macro.
Richard Smith4dd85d62011-10-11 19:57:52 +0000681 // FIXME: This warning is disabled in cases where it shouldn't be, like
682 // "#define constexpr constexpr", "int constexpr;"
Richard Smith31d51842015-05-14 04:00:59 +0000683 if (II.isFutureCompatKeyword() && !DisableMacroExpansion) {
684 Diag(Identifier, getFutureCompatDiagKind(II, getLangOpts()))
685 << II.getName();
Richard Smith4dd85d62011-10-11 19:57:52 +0000686 // Don't diagnose this keyword again in this translation unit.
Richard Smith31d51842015-05-14 04:00:59 +0000687 II.setIsFutureCompatKeyword(false);
Richard Smith4dd85d62011-10-11 19:57:52 +0000688 }
689
Chris Lattner5b9f4892006-11-21 17:23:33 +0000690 // C++ 2.11p2: If this is an alternative representation of a C++ operator,
691 // then we act as if it is the actual operator and not the textual
692 // representation of it.
Fariborz Jahanian9e42a952010-09-03 17:33:04 +0000693 if (II.isCPlusPlusOperatorKeyword())
Craig Topperd2d442c2014-05-17 23:10:59 +0000694 Identifier.setIdentifierInfo(nullptr);
Chris Lattner5b9f4892006-11-21 17:23:33 +0000695
Chris Lattner677757a2006-06-28 05:26:32 +0000696 // If this is an extension token, diagnose its use.
Steve Naroffc84e8b72008-09-02 18:50:17 +0000697 // We avoid diagnosing tokens that originate from macro definitions.
Eli Friedman6bba2ad2009-04-28 03:59:15 +0000698 // FIXME: This warning is disabled in cases where it shouldn't be,
699 // like "#define TY typeof", "TY(1) x".
700 if (II.isExtensionToken() && !DisableMacroExpansion)
Chris Lattner53621a52007-06-13 20:44:40 +0000701 Diag(Identifier, diag::ext_token_used);
Douglas Gregoraf5c4842011-09-07 23:11:54 +0000702
Douglas Gregor594b8c92013-11-07 22:55:02 +0000703 // If this is the 'import' contextual keyword following an '@', note
Ted Kremenekc1e4dd02012-03-01 22:07:04 +0000704 // that the next token indicates a module name.
Douglas Gregor8d76cca2012-01-04 06:20:15 +0000705 //
Douglas Gregorc50d4922012-12-11 22:11:52 +0000706 // Note that we do not treat 'import' as a contextual
Ted Kremenekc1e4dd02012-03-01 22:07:04 +0000707 // keyword when we're in a caching lexer, because caching lexers only get
708 // used in contexts where import declarations are disallowed.
Douglas Gregor594b8c92013-11-07 22:55:02 +0000709 if (LastTokenWasAt && II.isModulesImport() && !InMacroArgs &&
Sean Callanan87596492014-12-09 23:47:56 +0000710 !DisableMacroExpansion &&
711 (getLangOpts().Modules || getLangOpts().DebuggerSupport) &&
Douglas Gregor594b8c92013-11-07 22:55:02 +0000712 CurLexerKind != CLK_CachingLexer) {
Douglas Gregoraf5c4842011-09-07 23:11:54 +0000713 ModuleImportLoc = Identifier.getLocation();
Douglas Gregor1805b8a2011-11-30 04:26:53 +0000714 ModuleImportPath.clear();
715 ModuleImportExpectsIdentifier = true;
Douglas Gregoraf5c4842011-09-07 23:11:54 +0000716 CurLexerKind = CLK_LexAfterModuleImport;
717 }
Eli Friedman0834a4b2013-09-19 00:41:32 +0000718 return true;
Douglas Gregor08142532011-08-26 23:56:07 +0000719}
720
Eli Friedman0834a4b2013-09-19 00:41:32 +0000721void Preprocessor::Lex(Token &Result) {
Yaron Keren716f3a62015-09-29 16:51:08 +0000722 // We loop here until a lex function returns a token; this avoids recursion.
Eli Friedman0834a4b2013-09-19 00:41:32 +0000723 bool ReturnedToken;
724 do {
725 switch (CurLexerKind) {
726 case CLK_Lexer:
727 ReturnedToken = CurLexer->Lex(Result);
728 break;
729 case CLK_PTHLexer:
730 ReturnedToken = CurPTHLexer->Lex(Result);
731 break;
732 case CLK_TokenLexer:
733 ReturnedToken = CurTokenLexer->Lex(Result);
734 break;
735 case CLK_CachingLexer:
736 CachingLex(Result);
737 ReturnedToken = true;
738 break;
739 case CLK_LexAfterModuleImport:
740 LexAfterModuleImport(Result);
741 ReturnedToken = true;
742 break;
743 }
744 } while (!ReturnedToken);
Douglas Gregor594b8c92013-11-07 22:55:02 +0000745
746 LastTokenWasAt = Result.is(tok::at);
Eli Friedman0834a4b2013-09-19 00:41:32 +0000747}
748
749
Douglas Gregorda82e702012-01-03 19:32:59 +0000750/// \brief Lex a token following the 'import' contextual keyword.
Douglas Gregor22d09742012-01-03 18:04:46 +0000751///
Douglas Gregoraf5c4842011-09-07 23:11:54 +0000752void Preprocessor::LexAfterModuleImport(Token &Result) {
753 // Figure out what kind of lexer we actually have.
Douglas Gregor8d76cca2012-01-04 06:20:15 +0000754 recomputeCurLexerKind();
Douglas Gregoraf5c4842011-09-07 23:11:54 +0000755
756 // Lex the next token.
757 Lex(Result);
758
Douglas Gregor08142532011-08-26 23:56:07 +0000759 // The token sequence
760 //
Douglas Gregor22d09742012-01-03 18:04:46 +0000761 // import identifier (. identifier)*
762 //
Douglas Gregorda82e702012-01-03 19:32:59 +0000763 // indicates a module import directive. We already saw the 'import'
764 // contextual keyword, so now we're looking for the identifiers.
Douglas Gregor1805b8a2011-11-30 04:26:53 +0000765 if (ModuleImportExpectsIdentifier && Result.getKind() == tok::identifier) {
766 // We expected to see an identifier here, and we did; continue handling
767 // identifiers.
768 ModuleImportPath.push_back(std::make_pair(Result.getIdentifierInfo(),
769 Result.getLocation()));
770 ModuleImportExpectsIdentifier = false;
771 CurLexerKind = CLK_LexAfterModuleImport;
Douglas Gregor08142532011-08-26 23:56:07 +0000772 return;
Douglas Gregor1805b8a2011-11-30 04:26:53 +0000773 }
Douglas Gregor08142532011-08-26 23:56:07 +0000774
Douglas Gregor1805b8a2011-11-30 04:26:53 +0000775 // If we're expecting a '.' or a ';', and we got a '.', then wait until we
776 // see the next identifier.
777 if (!ModuleImportExpectsIdentifier && Result.getKind() == tok::period) {
778 ModuleImportExpectsIdentifier = true;
779 CurLexerKind = CLK_LexAfterModuleImport;
780 return;
781 }
782
783 // If we have a non-empty module path, load the named module.
Sean Callanan87596492014-12-09 23:47:56 +0000784 if (!ModuleImportPath.empty()) {
785 Module *Imported = nullptr;
Richard Smith753e0072015-04-27 23:21:38 +0000786 if (getLangOpts().Modules) {
Sean Callanan87596492014-12-09 23:47:56 +0000787 Imported = TheModuleLoader.loadModule(ModuleImportLoc,
788 ModuleImportPath,
Richard Smith10434f32015-05-02 02:08:26 +0000789 Module::Hidden,
Sean Callanan87596492014-12-09 23:47:56 +0000790 /*IsIncludeDirective=*/false);
Richard Smitha7e2cc62015-05-01 01:53:09 +0000791 if (Imported)
792 makeModuleVisible(Imported, ModuleImportLoc);
Richard Smith753e0072015-04-27 23:21:38 +0000793 }
Sean Callanan87596492014-12-09 23:47:56 +0000794 if (Callbacks && (getLangOpts().Modules || getLangOpts().DebuggerSupport))
Argyrios Kyrtzidis19d78b72012-09-29 01:06:10 +0000795 Callbacks->moduleImport(ModuleImportLoc, ModuleImportPath, Imported);
796 }
Chris Lattner677757a2006-06-28 05:26:32 +0000797}
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000798
Richard Smitha7e2cc62015-05-01 01:53:09 +0000799void Preprocessor::makeModuleVisible(Module *M, SourceLocation Loc) {
Richard Smith04765ae2015-05-21 01:20:10 +0000800 CurSubmoduleState->VisibleModules.setVisible(
Richard Smitha7e2cc62015-05-01 01:53:09 +0000801 M, Loc, [](Module *) {},
802 [&](ArrayRef<Module *> Path, Module *Conflict, StringRef Message) {
803 // FIXME: Include the path in the diagnostic.
804 // FIXME: Include the import location for the conflicting module.
805 Diag(ModuleImportLoc, diag::warn_module_conflict)
806 << Path[0]->getFullModuleName()
807 << Conflict->getFullModuleName()
808 << Message;
809 });
810
811 // Add this module to the imports list of the currently-built submodule.
Richard Smithdbbc5232015-05-14 02:25:44 +0000812 if (!BuildingSubmoduleStack.empty() && M != BuildingSubmoduleStack.back().M)
Richard Smith38477db2015-05-02 00:45:56 +0000813 BuildingSubmoduleStack.back().M->Imports.insert(M);
Richard Smitha7e2cc62015-05-01 01:53:09 +0000814}
815
Andy Gibbs58905d22012-11-17 19:15:38 +0000816bool Preprocessor::FinishLexStringLiteral(Token &Result, std::string &String,
Andy Gibbsa8df57a2012-11-17 19:16:52 +0000817 const char *DiagnosticTag,
Andy Gibbs58905d22012-11-17 19:15:38 +0000818 bool AllowMacroExpansion) {
819 // We need at least one string literal.
820 if (Result.isNot(tok::string_literal)) {
Andy Gibbsa8df57a2012-11-17 19:16:52 +0000821 Diag(Result, diag::err_expected_string_literal)
822 << /*Source='in...'*/0 << DiagnosticTag;
Andy Gibbs58905d22012-11-17 19:15:38 +0000823 return false;
824 }
825
826 // Lex string literal tokens, optionally with macro expansion.
827 SmallVector<Token, 4> StrToks;
828 do {
829 StrToks.push_back(Result);
830
831 if (Result.hasUDSuffix())
832 Diag(Result, diag::err_invalid_string_udl);
833
834 if (AllowMacroExpansion)
835 Lex(Result);
836 else
837 LexUnexpandedToken(Result);
838 } while (Result.is(tok::string_literal));
839
840 // Concatenate and parse the strings.
Craig Topper9d5583e2014-06-26 04:58:39 +0000841 StringLiteralParser Literal(StrToks, *this);
Andy Gibbs58905d22012-11-17 19:15:38 +0000842 assert(Literal.isAscii() && "Didn't allow wide strings in");
843
844 if (Literal.hadError)
845 return false;
846
847 if (Literal.Pascal) {
Andy Gibbsa8df57a2012-11-17 19:16:52 +0000848 Diag(StrToks[0].getLocation(), diag::err_expected_string_literal)
849 << /*Source='in...'*/0 << DiagnosticTag;
Andy Gibbs58905d22012-11-17 19:15:38 +0000850 return false;
851 }
852
853 String = Literal.GetString();
854 return true;
855}
856
Reid Klecknerc0dca6d2014-02-12 23:50:26 +0000857bool Preprocessor::parseSimpleIntegerLiteral(Token &Tok, uint64_t &Value) {
858 assert(Tok.is(tok::numeric_constant));
859 SmallString<8> IntegerBuffer;
860 bool NumberInvalid = false;
861 StringRef Spelling = getSpelling(Tok, IntegerBuffer, &NumberInvalid);
862 if (NumberInvalid)
863 return false;
864 NumericLiteralParser Literal(Spelling, Tok.getLocation(), *this);
865 if (Literal.hadError || !Literal.isIntegerLiteral() || Literal.hasUDSuffix())
866 return false;
867 llvm::APInt APVal(64, 0);
868 if (Literal.GetIntegerValue(APVal))
869 return false;
870 Lex(Tok);
871 Value = APVal.getLimitedValue();
872 return true;
873}
874
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000875void Preprocessor::addCommentHandler(CommentHandler *Handler) {
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000876 assert(Handler && "NULL comment handler");
877 assert(std::find(CommentHandlers.begin(), CommentHandlers.end(), Handler) ==
878 CommentHandlers.end() && "Comment handler already registered");
879 CommentHandlers.push_back(Handler);
880}
881
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000882void Preprocessor::removeCommentHandler(CommentHandler *Handler) {
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000883 std::vector<CommentHandler *>::iterator Pos
884 = std::find(CommentHandlers.begin(), CommentHandlers.end(), Handler);
885 assert(Pos != CommentHandlers.end() && "Comment handler not registered");
886 CommentHandlers.erase(Pos);
887}
888
Chris Lattner87d02082010-01-18 22:35:47 +0000889bool Preprocessor::HandleComment(Token &result, SourceRange Comment) {
890 bool AnyPendingTokens = false;
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000891 for (std::vector<CommentHandler *>::iterator H = CommentHandlers.begin(),
892 HEnd = CommentHandlers.end();
Chris Lattner87d02082010-01-18 22:35:47 +0000893 H != HEnd; ++H) {
894 if ((*H)->HandleComment(*this, Comment))
895 AnyPendingTokens = true;
896 }
897 if (!AnyPendingTokens || getCommentRetentionState())
898 return false;
899 Lex(result);
900 return true;
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000901}
902
Angel Garcia Gomez637d1e62015-10-20 13:23:58 +0000903ModuleLoader::~ModuleLoader() { }
Douglas Gregor08142532011-08-26 23:56:07 +0000904
Angel Garcia Gomez637d1e62015-10-20 13:23:58 +0000905CommentHandler::~CommentHandler() { }
Douglas Gregor7f6d60d2010-03-19 16:15:56 +0000906
Angel Garcia Gomez637d1e62015-10-20 13:23:58 +0000907CodeCompletionHandler::~CodeCompletionHandler() { }
Douglas Gregor3a7ad252010-08-24 19:08:16 +0000908
Argyrios Kyrtzidisf3d587e2012-12-04 07:27:05 +0000909void Preprocessor::createPreprocessingRecord() {
Douglas Gregor7f6d60d2010-03-19 16:15:56 +0000910 if (Record)
911 return;
912
Argyrios Kyrtzidisf3d587e2012-12-04 07:27:05 +0000913 Record = new PreprocessingRecord(getSourceManager());
Craig Topperb8a70532014-09-10 04:53:53 +0000914 addPPCallbacks(std::unique_ptr<PPCallbacks>(Record));
Douglas Gregor7f6d60d2010-03-19 16:15:56 +0000915}