blob: 3654ba080d47c49c9b3b0038d20d6451af3f8ee7 [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"
Jordan Rose7f43ddd2013-01-24 20:50:46 +000046#include "llvm/ADT/STLExtras.h"
Chandler Carruth5553d0d2014-01-07 11:51:46 +000047#include "llvm/ADT/SmallString.h"
Jordan Rose7f43ddd2013-01-24 20:50:46 +000048#include "llvm/ADT/StringExtras.h"
Mehdi Amini9670f842016-07-18 19:02:11 +000049#include "llvm/ADT/StringSwitch.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"
Benjamin Kramercfeacf52016-05-27 14:27:13 +000054#include <utility>
Chris Lattner22eb9722006-06-18 05:43:12 +000055using namespace clang;
56
NAKAMURA Takumicacd94e2016-04-04 15:30:44 +000057template class llvm::Registry<clang::PragmaHandler>;
58
Chris Lattner22eb9722006-06-18 05:43:12 +000059//===----------------------------------------------------------------------===//
Angel Garcia Gomez637d1e62015-10-20 13:23:58 +000060ExternalPreprocessorSource::~ExternalPreprocessorSource() { }
Chris Lattner22eb9722006-06-18 05:43:12 +000061
Dmitri Gribenkof8579502013-01-12 19:30:44 +000062Preprocessor::Preprocessor(IntrusiveRefCntPtr<PreprocessorOptions> PPOpts,
Douglas Gregor1452ff12012-10-24 17:46:57 +000063 DiagnosticsEngine &diags, LangOptions &opts,
Alp Toker96637802014-05-02 03:43:38 +000064 SourceManager &SM, HeaderSearch &Headers,
65 ModuleLoader &TheModuleLoader,
David Blaikie687cd952013-01-16 23:13:36 +000066 IdentifierInfoLookup *IILookup, bool OwnsHeaders,
Alp Toker1ae02f62014-05-02 03:43:30 +000067 TranslationUnitKind TUKind)
Benjamin Kramercfeacf52016-05-27 14:27:13 +000068 : PPOpts(std::move(PPOpts)), Diags(&diags), LangOpts(opts), Target(nullptr),
Artem Belevichb5bc9232015-09-22 17:23:22 +000069 AuxTarget(nullptr), FileMgr(Headers.getFileMgr()), SourceMgr(SM),
70 ScratchBuf(new ScratchBuffer(SourceMgr)), HeaderInfo(Headers),
Craig Topperd2d442c2014-05-17 23:10:59 +000071 TheModuleLoader(TheModuleLoader), ExternalSource(nullptr),
Craig Topperbe250302014-09-12 05:19:24 +000072 Identifiers(opts, IILookup),
73 PragmaHandlers(new PragmaNamespace(StringRef())),
Artem Belevichb5bc9232015-09-22 17:23:22 +000074 IncrementalProcessing(false), TUKind(TUKind), CodeComplete(nullptr),
75 CodeCompletionFile(nullptr), CodeCompletionOffset(0),
76 LastTokenWasAt(false), ModuleImportExpectsIdentifier(false),
77 CodeCompletionReached(0), MainFileDir(nullptr),
78 SkipMainFilePreamble(0, true), CurPPLexer(nullptr), CurDirLookup(nullptr),
79 CurLexerKind(CLK_Lexer), CurSubmodule(nullptr), Callbacks(nullptr),
80 CurSubmoduleState(&NullSubmoduleState), MacroArgCache(nullptr),
81 Record(nullptr), MIChainHead(nullptr), DeserialMIChainHead(nullptr) {
Daniel Dunbar0c6c9302009-11-11 21:44:21 +000082 OwnsHeaderSearch = OwnsHeaders;
Douglas Gregor83297df2011-09-01 23:39:15 +000083
Douglas Gregor83297df2011-09-01 23:39:15 +000084 CounterValue = 0; // __COUNTER__ starts at 0.
85
86 // Clear stats.
87 NumDirectives = NumDefined = NumUndefined = NumPragma = 0;
88 NumIf = NumElse = NumEndif = 0;
89 NumEnteredSourceFiles = 0;
90 NumMacroExpanded = NumFnMacroExpanded = NumBuiltinMacroExpanded = 0;
91 NumFastMacroExpanded = NumTokenPaste = NumFastTokenPaste = 0;
92 MaxIncludeStackDepth = 0;
93 NumSkipped = 0;
94
95 // Default to discarding comments.
96 KeepComments = false;
97 KeepMacroComments = false;
98 SuppressIncludeNotFoundError = false;
99
100 // Macro expansion is enabled.
101 DisableMacroExpansion = false;
David Blaikied5321242012-06-06 18:52:13 +0000102 MacroExpansionInDirectivesOverride = false;
Douglas Gregor83297df2011-09-01 23:39:15 +0000103 InMacroArgs = false;
Argyrios Kyrtzidisf1b64c62012-04-03 16:47:40 +0000104 InMacroArgPreExpansion = false;
Douglas Gregor83297df2011-09-01 23:39:15 +0000105 NumCachedTokenLexers = 0;
Jordan Rosede1a2922012-06-08 18:06:21 +0000106 PragmasEnabled = true;
Eric Christopher5e4696d2013-01-16 20:09:36 +0000107 ParsingIfOrElifDirective = false;
Jordan Rose324ec422013-01-31 19:26:01 +0000108 PreprocessedOutput = false;
Jordan Rosede1a2922012-06-08 18:06:21 +0000109
Douglas Gregor83297df2011-09-01 23:39:15 +0000110 CachedLexPos = 0;
Eric Christopher5e4696d2013-01-16 20:09:36 +0000111
Douglas Gregor83297df2011-09-01 23:39:15 +0000112 // We haven't read anything from the external source.
113 ReadMacrosFromExternalSource = false;
114
Douglas Gregor83297df2011-09-01 23:39:15 +0000115 // "Poison" __VA_ARGS__, which can only appear in the expansion of a macro.
116 // This gets unpoisoned where it is allowed.
117 (Ident__VA_ARGS__ = getIdentifierInfo("__VA_ARGS__"))->setIsPoisoned();
118 SetPoisonReason(Ident__VA_ARGS__,diag::ext_pp_bad_vaargs_use);
119
120 // Initialize the pragma handlers.
Douglas Gregor83297df2011-09-01 23:39:15 +0000121 RegisterBuiltinPragmas();
122
123 // Initialize builtin macros like __LINE__ and friends.
124 RegisterBuiltinMacros();
125
David Blaikiebbafb8a2012-03-11 07:00:24 +0000126 if(LangOpts.Borland) {
Douglas Gregor83297df2011-09-01 23:39:15 +0000127 Ident__exception_info = getIdentifierInfo("_exception_info");
128 Ident___exception_info = getIdentifierInfo("__exception_info");
129 Ident_GetExceptionInfo = getIdentifierInfo("GetExceptionInformation");
130 Ident__exception_code = getIdentifierInfo("_exception_code");
131 Ident___exception_code = getIdentifierInfo("__exception_code");
132 Ident_GetExceptionCode = getIdentifierInfo("GetExceptionCode");
133 Ident__abnormal_termination = getIdentifierInfo("_abnormal_termination");
134 Ident___abnormal_termination = getIdentifierInfo("__abnormal_termination");
135 Ident_AbnormalTermination = getIdentifierInfo("AbnormalTermination");
136 } else {
Craig Topperd2d442c2014-05-17 23:10:59 +0000137 Ident__exception_info = Ident__exception_code = nullptr;
138 Ident__abnormal_termination = Ident___exception_info = nullptr;
139 Ident___exception_code = Ident___abnormal_termination = nullptr;
140 Ident_GetExceptionInfo = Ident_GetExceptionCode = nullptr;
141 Ident_AbnormalTermination = nullptr;
Douglas Gregor89929282012-01-30 06:01:29 +0000142 }
Argyrios Kyrtzidis3c9aaf12012-06-02 18:08:09 +0000143}
144
145Preprocessor::~Preprocessor() {
146 assert(BacktrackPositions.empty() && "EnableBacktrack/Backtrack imbalance!");
147
Benjamin Kramer329c5962014-03-15 16:40:40 +0000148 IncludeMacroStack.clear();
Argyrios Kyrtzidis3c9aaf12012-06-02 18:08:09 +0000149
Richard Smith73a29662014-07-24 03:25:00 +0000150 // Destroy any macro definitions.
151 while (MacroInfoChain *I = MIChainHead) {
152 MIChainHead = I->Next;
153 I->~MacroInfoChain();
154 }
Argyrios Kyrtzidis3c9aaf12012-06-02 18:08:09 +0000155
156 // Free any cached macro expanders.
Nico Weber5f5b9412014-05-09 18:09:42 +0000157 // This populates MacroArgCache, so all TokenLexers need to be destroyed
158 // before the code below that frees up the MacroArgCache list.
David Blaikie6d5038c2014-08-29 19:36:52 +0000159 std::fill(TokenLexerCache, TokenLexerCache + NumCachedTokenLexers, nullptr);
Nico Weber5f5b9412014-05-09 18:09:42 +0000160 CurTokenLexer.reset();
Argyrios Kyrtzidis3c9aaf12012-06-02 18:08:09 +0000161
Richard Smith73a29662014-07-24 03:25:00 +0000162 while (DeserializedMacroInfoChain *I = DeserialMIChainHead) {
163 DeserialMIChainHead = I->Next;
164 I->~DeserializedMacroInfoChain();
165 }
Argyrios Kyrtzidisd48b91d2013-04-30 05:05:35 +0000166
Argyrios Kyrtzidis3c9aaf12012-06-02 18:08:09 +0000167 // Free any cached MacroArgs.
Nico Weber5f5b9412014-05-09 18:09:42 +0000168 for (MacroArgs *ArgList = MacroArgCache; ArgList;)
Argyrios Kyrtzidis3c9aaf12012-06-02 18:08:09 +0000169 ArgList = ArgList->deallocate();
170
Argyrios Kyrtzidis3c9aaf12012-06-02 18:08:09 +0000171 // Delete the header search info, if we own it.
172 if (OwnsHeaderSearch)
173 delete &HeaderInfo;
Argyrios Kyrtzidis3c9aaf12012-06-02 18:08:09 +0000174}
175
Artem Belevichb5bc9232015-09-22 17:23:22 +0000176void Preprocessor::Initialize(const TargetInfo &Target,
177 const TargetInfo *AuxTarget) {
Argyrios Kyrtzidis3c9aaf12012-06-02 18:08:09 +0000178 assert((!this->Target || this->Target == &Target) &&
179 "Invalid override of target information");
180 this->Target = &Target;
Artem Belevichb5bc9232015-09-22 17:23:22 +0000181
182 assert((!this->AuxTarget || this->AuxTarget == AuxTarget) &&
183 "Invalid override of aux target information.");
184 this->AuxTarget = AuxTarget;
185
Argyrios Kyrtzidis3c9aaf12012-06-02 18:08:09 +0000186 // Initialize information about built-ins.
Artem Belevichb5bc9232015-09-22 17:23:22 +0000187 BuiltinInfo.InitializeTarget(Target, AuxTarget);
Douglas Gregor89929282012-01-30 06:01:29 +0000188 HeaderInfo.setTarget(Target);
Douglas Gregor83297df2011-09-01 23:39:15 +0000189}
190
Ted Kremenekeeccb302014-08-27 15:14:15 +0000191void Preprocessor::InitializeForModelFile() {
192 NumEnteredSourceFiles = 0;
193
194 // Reset pragmas
David Blaikie9f0af9d2014-09-15 21:31:42 +0000195 PragmaHandlersBackup = std::move(PragmaHandlers);
Craig Topperbe250302014-09-12 05:19:24 +0000196 PragmaHandlers = llvm::make_unique<PragmaNamespace>(StringRef());
Ted Kremenekeeccb302014-08-27 15:14:15 +0000197 RegisterBuiltinPragmas();
198
199 // Reset PredefinesFileID
200 PredefinesFileID = FileID();
201}
202
203void Preprocessor::FinalizeForModelFile() {
204 NumEnteredSourceFiles = 1;
205
David Blaikie9f0af9d2014-09-15 21:31:42 +0000206 PragmaHandlers = std::move(PragmaHandlersBackup);
Ted Kremenekeeccb302014-08-27 15:14:15 +0000207}
208
Ted Kremeneka5c2c272009-02-12 03:26:59 +0000209void Preprocessor::setPTHManager(PTHManager* pm) {
210 PTH.reset(pm);
Douglas Gregord2eb58a2009-10-16 18:18:30 +0000211 FileMgr.addStatCache(PTH->createStatCache());
Ted Kremeneka5c2c272009-02-12 03:26:59 +0000212}
213
Chris Lattner146762e2007-07-20 16:59:19 +0000214void Preprocessor::DumpToken(const Token &Tok, bool DumpFlags) const {
Benjamin Kramer89b422c2009-08-23 12:08:50 +0000215 llvm::errs() << tok::getTokenName(Tok.getKind()) << " '"
216 << getSpelling(Tok) << "'";
Mike Stump11289f42009-09-09 15:08:12 +0000217
Chris Lattnerd01e2912006-06-18 16:22:51 +0000218 if (!DumpFlags) return;
Mike Stump11289f42009-09-09 15:08:12 +0000219
Benjamin Kramer89b422c2009-08-23 12:08:50 +0000220 llvm::errs() << "\t";
Chris Lattnerd01e2912006-06-18 16:22:51 +0000221 if (Tok.isAtStartOfLine())
Benjamin Kramer89b422c2009-08-23 12:08:50 +0000222 llvm::errs() << " [StartOfLine]";
Chris Lattnerd01e2912006-06-18 16:22:51 +0000223 if (Tok.hasLeadingSpace())
Benjamin Kramer89b422c2009-08-23 12:08:50 +0000224 llvm::errs() << " [LeadingSpace]";
Chris Lattner6e4bf522006-07-27 06:59:25 +0000225 if (Tok.isExpandDisabled())
Benjamin Kramer89b422c2009-08-23 12:08:50 +0000226 llvm::errs() << " [ExpandDisabled]";
Chris Lattnerd01e2912006-06-18 16:22:51 +0000227 if (Tok.needsCleaning()) {
Chris Lattner50b497e2006-06-18 16:32:35 +0000228 const char *Start = SourceMgr.getCharacterData(Tok.getLocation());
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000229 llvm::errs() << " [UnClean='" << StringRef(Start, Tok.getLength())
Benjamin Kramer89b422c2009-08-23 12:08:50 +0000230 << "']";
Chris Lattnerd01e2912006-06-18 16:22:51 +0000231 }
Mike Stump11289f42009-09-09 15:08:12 +0000232
Benjamin Kramer89b422c2009-08-23 12:08:50 +0000233 llvm::errs() << "\tLoc=<";
Chris Lattner615315f2007-12-09 20:31:55 +0000234 DumpLocation(Tok.getLocation());
Benjamin Kramer89b422c2009-08-23 12:08:50 +0000235 llvm::errs() << ">";
Chris Lattner615315f2007-12-09 20:31:55 +0000236}
237
238void Preprocessor::DumpLocation(SourceLocation Loc) const {
Chris Lattnerf1ca7d32009-01-27 07:57:44 +0000239 Loc.dump(SourceMgr);
Chris Lattnerd01e2912006-06-18 16:22:51 +0000240}
241
242void Preprocessor::DumpMacro(const MacroInfo &MI) const {
Benjamin Kramer89b422c2009-08-23 12:08:50 +0000243 llvm::errs() << "MACRO: ";
Chris Lattnerd01e2912006-06-18 16:22:51 +0000244 for (unsigned i = 0, e = MI.getNumTokens(); i != e; ++i) {
245 DumpToken(MI.getReplacementToken(i));
Benjamin Kramer89b422c2009-08-23 12:08:50 +0000246 llvm::errs() << " ";
Chris Lattnerd01e2912006-06-18 16:22:51 +0000247 }
Benjamin Kramer89b422c2009-08-23 12:08:50 +0000248 llvm::errs() << "\n";
Chris Lattnerd01e2912006-06-18 16:22:51 +0000249}
250
Chris Lattner22eb9722006-06-18 05:43:12 +0000251void Preprocessor::PrintStats() {
Benjamin Kramer89b422c2009-08-23 12:08:50 +0000252 llvm::errs() << "\n*** Preprocessor Stats:\n";
253 llvm::errs() << NumDirectives << " directives found:\n";
254 llvm::errs() << " " << NumDefined << " #define.\n";
255 llvm::errs() << " " << NumUndefined << " #undef.\n";
256 llvm::errs() << " #include/#include_next/#import:\n";
257 llvm::errs() << " " << NumEnteredSourceFiles << " source files entered.\n";
258 llvm::errs() << " " << MaxIncludeStackDepth << " max include stack depth\n";
259 llvm::errs() << " " << NumIf << " #if/#ifndef/#ifdef.\n";
260 llvm::errs() << " " << NumElse << " #else/#elif.\n";
261 llvm::errs() << " " << NumEndif << " #endif.\n";
262 llvm::errs() << " " << NumPragma << " #pragma.\n";
263 llvm::errs() << NumSkipped << " #if/#ifndef#ifdef regions skipped\n";
Chris Lattner22eb9722006-06-18 05:43:12 +0000264
Benjamin Kramer89b422c2009-08-23 12:08:50 +0000265 llvm::errs() << NumMacroExpanded << "/" << NumFnMacroExpanded << "/"
Ted Kremeneka0a3e9b2008-01-14 16:44:48 +0000266 << NumBuiltinMacroExpanded << " obj/fn/builtin macros expanded, "
267 << NumFastMacroExpanded << " on the fast path.\n";
Benjamin Kramer89b422c2009-08-23 12:08:50 +0000268 llvm::errs() << (NumFastTokenPaste+NumTokenPaste)
Ted Kremeneka0a3e9b2008-01-14 16:44:48 +0000269 << " token paste (##) operations performed, "
270 << NumFastTokenPaste << " on the fast path.\n";
Alexander Kornienko199cd942012-08-13 10:46:42 +0000271
272 llvm::errs() << "\nPreprocessor Memory: " << getTotalMemory() << "B total";
273
274 llvm::errs() << "\n BumpPtr: " << BP.getTotalMemory();
275 llvm::errs() << "\n Macro Expanded Tokens: "
276 << llvm::capacity_in_bytes(MacroExpandedTokens);
277 llvm::errs() << "\n Predefines Buffer: " << Predefines.capacity();
Richard Smith04765ae2015-05-21 01:20:10 +0000278 // FIXME: List information for all submodules.
279 llvm::errs() << "\n Macros: "
280 << llvm::capacity_in_bytes(CurSubmoduleState->Macros);
Alexander Kornienko199cd942012-08-13 10:46:42 +0000281 llvm::errs() << "\n #pragma push_macro Info: "
282 << llvm::capacity_in_bytes(PragmaPushMacroInfo);
283 llvm::errs() << "\n Poison Reasons: "
284 << llvm::capacity_in_bytes(PoisonReasons);
285 llvm::errs() << "\n Comment Handlers: "
286 << llvm::capacity_in_bytes(CommentHandlers) << "\n";
Chris Lattner22eb9722006-06-18 05:43:12 +0000287}
288
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +0000289Preprocessor::macro_iterator
290Preprocessor::macro_begin(bool IncludeExternalMacros) const {
291 if (IncludeExternalMacros && ExternalSource &&
Douglas Gregor9882a5a2010-01-04 19:18:44 +0000292 !ReadMacrosFromExternalSource) {
293 ReadMacrosFromExternalSource = true;
294 ExternalSource->ReadDefinedMacros();
295 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +0000296
Jordan Rosea46bfa62015-06-24 19:27:02 +0000297 // Make sure we cover all macros in visible modules.
298 for (const ModuleMacro &Macro : ModuleMacros)
299 CurSubmoduleState->Macros.insert(std::make_pair(Macro.II, MacroState()));
300
Richard Smith04765ae2015-05-21 01:20:10 +0000301 return CurSubmoduleState->Macros.begin();
Douglas Gregor9882a5a2010-01-04 19:18:44 +0000302}
303
Argyrios Kyrtzidise379ee32011-06-29 22:20:04 +0000304size_t Preprocessor::getTotalMemory() const {
Ted Kremenek182543a2011-07-26 21:17:24 +0000305 return BP.getTotalMemory()
Ted Kremenek8b77fe72011-07-27 18:41:23 +0000306 + llvm::capacity_in_bytes(MacroExpandedTokens)
Ted Kremenek182543a2011-07-26 21:17:24 +0000307 + Predefines.capacity() /* Predefines buffer. */
Richard Smith04765ae2015-05-21 01:20:10 +0000308 // FIXME: Include sizes from all submodules, and include MacroInfo sizes,
309 // and ModuleMacros.
310 + llvm::capacity_in_bytes(CurSubmoduleState->Macros)
Ted Kremenek8b77fe72011-07-27 18:41:23 +0000311 + llvm::capacity_in_bytes(PragmaPushMacroInfo)
312 + llvm::capacity_in_bytes(PoisonReasons)
313 + llvm::capacity_in_bytes(CommentHandlers);
Argyrios Kyrtzidise379ee32011-06-29 22:20:04 +0000314}
315
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +0000316Preprocessor::macro_iterator
317Preprocessor::macro_end(bool IncludeExternalMacros) const {
318 if (IncludeExternalMacros && ExternalSource &&
Douglas Gregor9882a5a2010-01-04 19:18:44 +0000319 !ReadMacrosFromExternalSource) {
320 ReadMacrosFromExternalSource = true;
321 ExternalSource->ReadDefinedMacros();
322 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +0000323
Richard Smith04765ae2015-05-21 01:20:10 +0000324 return CurSubmoduleState->Macros.end();
Douglas Gregor9882a5a2010-01-04 19:18:44 +0000325}
326
Dmitri Gribenko6743e042012-09-29 11:40:46 +0000327/// \brief Compares macro tokens with a specified token value sequence.
328static bool MacroDefinitionEquals(const MacroInfo *MI,
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000329 ArrayRef<TokenValue> Tokens) {
Dmitri Gribenko6743e042012-09-29 11:40:46 +0000330 return Tokens.size() == MI->getNumTokens() &&
331 std::equal(Tokens.begin(), Tokens.end(), MI->tokens_begin());
332}
333
334StringRef Preprocessor::getLastMacroWithSpelling(
335 SourceLocation Loc,
336 ArrayRef<TokenValue> Tokens) const {
337 SourceLocation BestLocation;
338 StringRef BestSpelling;
339 for (Preprocessor::macro_iterator I = macro_begin(), E = macro_end();
340 I != E; ++I) {
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +0000341 const MacroDirective::DefInfo
Richard Smithb8b2ed62015-04-23 18:18:26 +0000342 Def = I->second.findDirectiveAtLoc(Loc, SourceMgr);
Argyrios Kyrtzidis5c585252015-03-04 16:03:07 +0000343 if (!Def || !Def.getMacroInfo())
344 continue;
345 if (!Def.getMacroInfo()->isObjectLike())
Dmitri Gribenko6743e042012-09-29 11:40:46 +0000346 continue;
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +0000347 if (!MacroDefinitionEquals(Def.getMacroInfo(), Tokens))
Dmitri Gribenko6743e042012-09-29 11:40:46 +0000348 continue;
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +0000349 SourceLocation Location = Def.getLocation();
Dmitri Gribenko6743e042012-09-29 11:40:46 +0000350 // Choose the macro defined latest.
351 if (BestLocation.isInvalid() ||
352 (Location.isValid() &&
353 SourceMgr.isBeforeInTranslationUnit(BestLocation, Location))) {
354 BestLocation = Location;
355 BestSpelling = I->first->getName();
356 }
357 }
358 return BestSpelling;
359}
360
Douglas Gregor8d76cca2012-01-04 06:20:15 +0000361void Preprocessor::recomputeCurLexerKind() {
362 if (CurLexer)
363 CurLexerKind = CLK_Lexer;
364 else if (CurPTHLexer)
365 CurLexerKind = CLK_PTHLexer;
366 else if (CurTokenLexer)
367 CurLexerKind = CLK_TokenLexer;
368 else
369 CurLexerKind = CLK_CachingLexer;
370}
371
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +0000372bool Preprocessor::SetCodeCompletionPoint(const FileEntry *File,
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +0000373 unsigned CompleteLine,
374 unsigned CompleteColumn) {
375 assert(File);
376 assert(CompleteLine && CompleteColumn && "Starts from 1:1");
377 assert(!CodeCompletionFile && "Already set");
378
Douglas Gregor53ad6b92009-12-02 06:49:09 +0000379 using llvm::MemoryBuffer;
380
Douglas Gregor53ad6b92009-12-02 06:49:09 +0000381 // Load the actual file's contents.
Douglas Gregor26266da2010-03-16 19:49:24 +0000382 bool Invalid = false;
383 const MemoryBuffer *Buffer = SourceMgr.getMemoryBufferForFile(File, &Invalid);
384 if (Invalid)
Douglas Gregor53ad6b92009-12-02 06:49:09 +0000385 return true;
386
387 // Find the byte position of the truncation point.
388 const char *Position = Buffer->getBufferStart();
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +0000389 for (unsigned Line = 1; Line < CompleteLine; ++Line) {
Douglas Gregor53ad6b92009-12-02 06:49:09 +0000390 for (; *Position; ++Position) {
391 if (*Position != '\r' && *Position != '\n')
392 continue;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +0000393
Douglas Gregor53ad6b92009-12-02 06:49:09 +0000394 // Eat \r\n or \n\r as a single line.
395 if ((Position[1] == '\r' || Position[1] == '\n') &&
396 Position[0] != Position[1])
397 ++Position;
398 ++Position;
399 break;
400 }
401 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +0000402
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +0000403 Position += CompleteColumn - 1;
Argyrios Kyrtzidisee301f92014-10-18 06:23:50 +0000404
405 // If pointing inside the preamble, adjust the position at the beginning of
406 // the file after the preamble.
407 if (SkipMainFilePreamble.first &&
408 SourceMgr.getFileEntryForID(SourceMgr.getMainFileID()) == File) {
409 if (Position - Buffer->getBufferStart() < SkipMainFilePreamble.first)
410 Position = Buffer->getBufferStart() + SkipMainFilePreamble.first;
411 }
412
Argyrios Kyrtzidise62d6822014-10-18 06:19:36 +0000413 if (Position > Buffer->getBufferEnd())
414 Position = Buffer->getBufferEnd();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +0000415
Argyrios Kyrtzidise62d6822014-10-18 06:19:36 +0000416 CodeCompletionFile = File;
417 CodeCompletionOffset = Position - Buffer->getBufferStart();
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +0000418
Argyrios Kyrtzidise62d6822014-10-18 06:19:36 +0000419 std::unique_ptr<MemoryBuffer> NewBuffer =
420 MemoryBuffer::getNewUninitMemBuffer(Buffer->getBufferSize() + 1,
421 Buffer->getBufferIdentifier());
422 char *NewBuf = const_cast<char*>(NewBuffer->getBufferStart());
423 char *NewPos = std::copy(Buffer->getBufferStart(), Position, NewBuf);
424 *NewPos = '\0';
425 std::copy(Position, Buffer->getBufferEnd(), NewPos+1);
426 SourceMgr.overrideFileContents(File, std::move(NewBuffer));
Douglas Gregor53ad6b92009-12-02 06:49:09 +0000427
428 return false;
429}
430
Douglas Gregor11583702010-08-25 17:04:25 +0000431void Preprocessor::CodeCompleteNaturalLanguage() {
Douglas Gregor11583702010-08-25 17:04:25 +0000432 if (CodeComplete)
433 CodeComplete->CodeCompleteNaturalLanguage();
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +0000434 setCodeCompletionReached();
Douglas Gregor11583702010-08-25 17:04:25 +0000435}
436
Benjamin Kramera197fb62010-02-27 17:05:45 +0000437/// getSpelling - This method is used to get the spelling of a token into a
438/// SmallVector. Note that the returned StringRef may not point to the
439/// supplied buffer if a copy can be avoided.
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000440StringRef Preprocessor::getSpelling(const Token &Tok,
441 SmallVectorImpl<char> &Buffer,
Douglas Gregor7bda4b82010-03-16 05:20:39 +0000442 bool *Invalid) const {
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +0000443 // NOTE: this has to be checked *before* testing for an IdentifierInfo.
Jordan Rose7f43ddd2013-01-24 20:50:46 +0000444 if (Tok.isNot(tok::raw_identifier) && !Tok.hasUCN()) {
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +0000445 // Try the fast path.
446 if (const IdentifierInfo *II = Tok.getIdentifierInfo())
447 return II->getName();
448 }
Benjamin Kramera197fb62010-02-27 17:05:45 +0000449
450 // Resize the buffer if we need to copy into it.
451 if (Tok.needsCleaning())
452 Buffer.resize(Tok.getLength());
453
454 const char *Ptr = Buffer.data();
Douglas Gregor7bda4b82010-03-16 05:20:39 +0000455 unsigned Len = getSpelling(Tok, Ptr, Invalid);
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000456 return StringRef(Ptr, Len);
Benjamin Kramera197fb62010-02-27 17:05:45 +0000457}
458
Chris Lattnerb94ec7b2006-07-14 06:54:10 +0000459/// CreateString - Plop the specified string into a scratch buffer and return a
460/// location for it. If specified, the source location provides a source
461/// location for the token.
Dmitri Gribenkob8e9e752012-09-24 21:07:17 +0000462void Preprocessor::CreateString(StringRef Str, Token &Tok,
Abramo Bagnarae398e602011-10-03 18:39:03 +0000463 SourceLocation ExpansionLocStart,
464 SourceLocation ExpansionLocEnd) {
Dmitri Gribenkob8e9e752012-09-24 21:07:17 +0000465 Tok.setLength(Str.size());
Mike Stump11289f42009-09-09 15:08:12 +0000466
Chris Lattner5a7971e2009-01-26 19:29:26 +0000467 const char *DestPtr;
Dmitri Gribenkob8e9e752012-09-24 21:07:17 +0000468 SourceLocation Loc = ScratchBuf->getToken(Str.data(), Str.size(), DestPtr);
Mike Stump11289f42009-09-09 15:08:12 +0000469
Abramo Bagnarae398e602011-10-03 18:39:03 +0000470 if (ExpansionLocStart.isValid())
471 Loc = SourceMgr.createExpansionLoc(Loc, ExpansionLocStart,
Dmitri Gribenkob8e9e752012-09-24 21:07:17 +0000472 ExpansionLocEnd, Str.size());
Chris Lattner5a7971e2009-01-26 19:29:26 +0000473 Tok.setLocation(Loc);
Mike Stump11289f42009-09-09 15:08:12 +0000474
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +0000475 // If this is a raw identifier or a literal token, set the pointer data.
476 if (Tok.is(tok::raw_identifier))
477 Tok.setRawIdentifierData(DestPtr);
478 else if (Tok.isLiteral())
Chris Lattner5a7971e2009-01-26 19:29:26 +0000479 Tok.setLiteralData(DestPtr);
Chris Lattnerb94ec7b2006-07-14 06:54:10 +0000480}
481
Douglas Gregor2b82c2a2011-12-02 01:47:07 +0000482Module *Preprocessor::getCurrentModule() {
Richard Smith7e82e012016-02-19 22:25:36 +0000483 if (!getLangOpts().CompilingModule)
Craig Topperd2d442c2014-05-17 23:10:59 +0000484 return nullptr;
485
David Blaikiebbafb8a2012-03-11 07:00:24 +0000486 return getHeaderSearchInfo().lookupModule(getLangOpts().CurrentModule);
Douglas Gregor2b82c2a2011-12-02 01:47:07 +0000487}
Chris Lattner8a7003c2007-07-16 06:48:38 +0000488
Chris Lattner1f1b0db2007-10-09 22:10:18 +0000489//===----------------------------------------------------------------------===//
490// Preprocessor Initialization Methods
491//===----------------------------------------------------------------------===//
492
Chris Lattner1f1b0db2007-10-09 22:10:18 +0000493
494/// EnterMainSourceFile - Enter the specified FileID as the main source file,
Nate Begemanf7c3ff62008-01-07 04:01:26 +0000495/// which implicitly adds the builtin defines etc.
Chris Lattnerfb24a3a2010-04-20 20:35:58 +0000496void Preprocessor::EnterMainSourceFile() {
Chris Lattner9ef847b2009-02-13 19:33:24 +0000497 // We do not allow the preprocessor to reenter the main file. Doing so will
498 // cause FileID's to accumulate information from both runs (e.g. #line
499 // information) and predefined macros aren't guaranteed to be set properly.
500 assert(NumEnteredSourceFiles == 0 && "Cannot reenter the main file!");
Chris Lattnerd32480d2009-01-17 06:22:33 +0000501 FileID MainFileID = SourceMgr.getMainFileID();
Mike Stump11289f42009-09-09 15:08:12 +0000502
Argyrios Kyrtzidis9afd4492012-01-05 21:36:25 +0000503 // If MainFileID is loaded it means we loaded an AST file, no need to enter
504 // a main file.
505 if (!SourceMgr.isLoadedFileID(MainFileID)) {
506 // Enter the main file source buffer.
Craig Topperd2d442c2014-05-17 23:10:59 +0000507 EnterSourceFile(MainFileID, nullptr, SourceLocation());
508
Argyrios Kyrtzidis9afd4492012-01-05 21:36:25 +0000509 // If we've been asked to skip bytes in the main file (e.g., as part of a
510 // precompiled preamble), do so now.
511 if (SkipMainFilePreamble.first > 0)
512 CurLexer->SkipBytes(SkipMainFilePreamble.first,
513 SkipMainFilePreamble.second);
514
515 // Tell the header info that the main file was entered. If the file is later
516 // #imported, it won't be re-entered.
517 if (const FileEntry *FE = SourceMgr.getFileEntryForID(MainFileID))
518 HeaderInfo.IncrementIncludeCount(FE);
519 }
Mike Stump11289f42009-09-09 15:08:12 +0000520
Benjamin Kramerd77adb52009-12-31 15:33:09 +0000521 // Preprocess Predefines to populate the initial preprocessor state.
Rafael Espindolad87f8d72014-08-27 20:03:29 +0000522 std::unique_ptr<llvm::MemoryBuffer> SB =
Chris Lattner58c79342010-04-05 22:42:27 +0000523 llvm::MemoryBuffer::getMemBufferCopy(Predefines, "<built-in>");
Douglas Gregor33551892010-08-26 14:07:34 +0000524 assert(SB && "Cannot create predefined source buffer");
David Blaikie50a5f972014-08-29 07:59:55 +0000525 FileID FID = SourceMgr.createFileID(std::move(SB));
Yaron Keren8b563662015-10-03 10:46:20 +0000526 assert(FID.isValid() && "Could not create FileID for predefines?");
Argyrios Kyrtzidis22c22f52013-02-01 16:36:07 +0000527 setPredefinesFileID(FID);
Mike Stump11289f42009-09-09 15:08:12 +0000528
Chris Lattner1f1b0db2007-10-09 22:10:18 +0000529 // Start parsing the predefines.
Craig Topperd2d442c2014-05-17 23:10:59 +0000530 EnterSourceFile(FID, nullptr, SourceLocation());
Chris Lattner1f1b0db2007-10-09 22:10:18 +0000531}
Chris Lattner8a7003c2007-07-16 06:48:38 +0000532
Daniel Dunbarcb9eaf52010-03-23 05:09:10 +0000533void Preprocessor::EndSourceFile() {
534 // Notify the client that we reached the end of the source file.
535 if (Callbacks)
536 Callbacks->EndOfMainFile();
537}
Chris Lattner677757a2006-06-28 05:26:32 +0000538
539//===----------------------------------------------------------------------===//
540// Lexer Event Handling.
541//===----------------------------------------------------------------------===//
542
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +0000543/// LookUpIdentifierInfo - Given a tok::raw_identifier token, look up the
544/// identifier information for the token and install it into the token,
545/// updating the token kind accordingly.
546IdentifierInfo *Preprocessor::LookUpIdentifierInfo(Token &Identifier) const {
Alp Toker2d57cea2014-05-17 04:53:25 +0000547 assert(!Identifier.getRawIdentifier().empty() && "No raw identifier data!");
Mike Stump11289f42009-09-09 15:08:12 +0000548
Chris Lattnercefc7682006-07-08 08:28:12 +0000549 // Look up this token, see if it is a macro, or if it is a language keyword.
550 IdentifierInfo *II;
Jordan Rose7f43ddd2013-01-24 20:50:46 +0000551 if (!Identifier.needsCleaning() && !Identifier.hasUCN()) {
Chris Lattnercefc7682006-07-08 08:28:12 +0000552 // No cleaning needed, just use the characters from the lexed buffer.
Alp Toker2d57cea2014-05-17 04:53:25 +0000553 II = getIdentifierInfo(Identifier.getRawIdentifier());
Chris Lattnercefc7682006-07-08 08:28:12 +0000554 } else {
555 // Cleaning needed, alloca a buffer, clean into it, then use the buffer.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +0000556 SmallString<64> IdentifierBuffer;
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000557 StringRef CleanedStr = getSpelling(Identifier, IdentifierBuffer);
Jordan Rose7f43ddd2013-01-24 20:50:46 +0000558
559 if (Identifier.hasUCN()) {
560 SmallString<64> UCNIdentifierBuffer;
561 expandUCNs(UCNIdentifierBuffer, CleanedStr);
562 II = getIdentifierInfo(UCNIdentifierBuffer);
563 } else {
564 II = getIdentifierInfo(CleanedStr);
565 }
Chris Lattnercefc7682006-07-08 08:28:12 +0000566 }
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +0000567
568 // Update the token info (identifier info and appropriate token kind).
Chris Lattner8c204872006-10-14 05:19:21 +0000569 Identifier.setIdentifierInfo(II);
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +0000570 Identifier.setKind(II->getTokenID());
571
Chris Lattnercefc7682006-07-08 08:28:12 +0000572 return II;
573}
574
John Wiegley1c0675e2011-04-28 01:08:34 +0000575void Preprocessor::SetPoisonReason(IdentifierInfo *II, unsigned DiagID) {
576 PoisonReasons[II] = DiagID;
577}
578
579void Preprocessor::PoisonSEHIdentifiers(bool Poison) {
580 assert(Ident__exception_code && Ident__exception_info);
581 assert(Ident___exception_code && Ident___exception_info);
582 Ident__exception_code->setIsPoisoned(Poison);
583 Ident___exception_code->setIsPoisoned(Poison);
584 Ident_GetExceptionCode->setIsPoisoned(Poison);
585 Ident__exception_info->setIsPoisoned(Poison);
586 Ident___exception_info->setIsPoisoned(Poison);
587 Ident_GetExceptionInfo->setIsPoisoned(Poison);
588 Ident__abnormal_termination->setIsPoisoned(Poison);
589 Ident___abnormal_termination->setIsPoisoned(Poison);
590 Ident_AbnormalTermination->setIsPoisoned(Poison);
591}
592
593void Preprocessor::HandlePoisonedIdentifier(Token & Identifier) {
594 assert(Identifier.getIdentifierInfo() &&
595 "Can't handle identifiers without identifier info!");
596 llvm::DenseMap<IdentifierInfo*,unsigned>::const_iterator it =
597 PoisonReasons.find(Identifier.getIdentifierInfo());
598 if(it == PoisonReasons.end())
599 Diag(Identifier, diag::err_pp_used_poisoned_id);
600 else
601 Diag(Identifier,it->second) << Identifier.getIdentifierInfo();
602}
Chris Lattnercefc7682006-07-08 08:28:12 +0000603
Richard Smith31d51842015-05-14 04:00:59 +0000604/// \brief Returns a diagnostic message kind for reporting a future keyword as
605/// appropriate for the identifier and specified language.
606static diag::kind getFutureCompatDiagKind(const IdentifierInfo &II,
607 const LangOptions &LangOpts) {
608 assert(II.isFutureCompatKeyword() && "diagnostic should not be needed");
609
610 if (LangOpts.CPlusPlus)
611 return llvm::StringSwitch<diag::kind>(II.getName())
612#define CXX11_KEYWORD(NAME, FLAGS) \
613 .Case(#NAME, diag::warn_cxx11_keyword)
614#include "clang/Basic/TokenKinds.def"
615 ;
616
617 llvm_unreachable(
618 "Keyword not known to come from a newer Standard or proposed Standard");
619}
620
Chris Lattner677757a2006-06-28 05:26:32 +0000621/// HandleIdentifier - This callback is invoked when the lexer reads an
622/// identifier. This callback looks up the identifier in the map and/or
623/// potentially macro expands it or turns it into a named token (like 'for').
Chris Lattnerad89ec02009-01-21 07:43:11 +0000624///
625/// Note that callers of this method are guarded by checking the
626/// IdentifierInfo's 'isHandleIdentifierCase' bit. If this method changes, the
627/// IdentifierInfo methods that compute these properties will need to change to
628/// match.
Eli Friedman0834a4b2013-09-19 00:41:32 +0000629bool Preprocessor::HandleIdentifier(Token &Identifier) {
Chris Lattner0f1f5052006-07-20 04:16:23 +0000630 assert(Identifier.getIdentifierInfo() &&
631 "Can't handle identifiers without identifier info!");
Mike Stump11289f42009-09-09 15:08:12 +0000632
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000633 IdentifierInfo &II = *Identifier.getIdentifierInfo();
Chris Lattner677757a2006-06-28 05:26:32 +0000634
Douglas Gregor935bc7a22011-10-27 09:33:13 +0000635 // If the information about this identifier is out of date, update it from
636 // the external source.
Douglas Gregor3f568c12012-06-29 18:27:59 +0000637 // We have to treat __VA_ARGS__ in a special way, since it gets
638 // serialized with isPoisoned = true, but our preprocessor may have
639 // unpoisoned it if we're defining a C99 macro.
Douglas Gregor935bc7a22011-10-27 09:33:13 +0000640 if (II.isOutOfDate()) {
Douglas Gregor3f568c12012-06-29 18:27:59 +0000641 bool CurrentIsPoisoned = false;
642 if (&II == Ident__VA_ARGS__)
643 CurrentIsPoisoned = Ident__VA_ARGS__->isPoisoned();
644
Douglas Gregor935bc7a22011-10-27 09:33:13 +0000645 ExternalSource->updateOutOfDateIdentifier(II);
646 Identifier.setKind(II.getTokenID());
Douglas Gregor3f568c12012-06-29 18:27:59 +0000647
648 if (&II == Ident__VA_ARGS__)
649 II.setIsPoisoned(CurrentIsPoisoned);
Douglas Gregor935bc7a22011-10-27 09:33:13 +0000650 }
651
Chris Lattner677757a2006-06-28 05:26:32 +0000652 // If this identifier was poisoned, and if it was not produced from a macro
653 // expansion, emit an error.
Ted Kremeneka2c3c8d2008-11-19 22:43:49 +0000654 if (II.isPoisoned() && CurPPLexer) {
John Wiegley1c0675e2011-04-28 01:08:34 +0000655 HandlePoisonedIdentifier(Identifier);
Chris Lattner8ff71992006-07-06 05:17:39 +0000656 }
Mike Stump11289f42009-09-09 15:08:12 +0000657
Chris Lattner78186052006-07-09 00:45:31 +0000658 // If this is a macro to be expanded, do it.
Richard Smith20e883e2015-04-29 23:20:19 +0000659 if (MacroDefinition MD = getMacroDefinition(&II)) {
660 auto *MI = MD.getMacroInfo();
Richard Smithf5ec2ac2015-04-29 23:40:48 +0000661 assert(MI && "macro definition with no macro info?");
Abramo Bagnara123bec82012-01-01 22:01:04 +0000662 if (!DisableMacroExpansion) {
Richard Smith181879c2012-12-12 02:46:14 +0000663 if (!Identifier.isExpandDisabled() && MI->isEnabled()) {
Eli Friedman0834a4b2013-09-19 00:41:32 +0000664 // C99 6.10.3p10: If the preprocessing token immediately after the
665 // macro name isn't a '(', this macro should not be expanded.
666 if (!MI->isFunctionLike() || isNextPPTokenLParen())
667 return HandleMacroExpandedIdentifier(Identifier, MD);
Chris Lattner6e4bf522006-07-27 06:59:25 +0000668 } else {
669 // C99 6.10.3.4p2 says that a disabled macro may never again be
670 // expanded, even if it's in a context where it could be expanded in the
671 // future.
Chris Lattner146762e2007-07-20 16:59:19 +0000672 Identifier.setFlag(Token::DisableExpand);
Richard Smith181879c2012-12-12 02:46:14 +0000673 if (MI->isObjectLike() || isNextPPTokenLParen())
674 Diag(Identifier, diag::pp_disabled_macro_expansion);
Chris Lattner6e4bf522006-07-27 06:59:25 +0000675 }
676 }
Chris Lattner063400e2006-10-14 19:54:15 +0000677 }
Chris Lattner677757a2006-06-28 05:26:32 +0000678
Richard Smith31d51842015-05-14 04:00:59 +0000679 // If this identifier is a keyword in a newer Standard or proposed Standard,
680 // produce a warning. Don't warn if we're not considering macro expansion,
681 // since this identifier might be the name of a macro.
Richard Smith4dd85d62011-10-11 19:57:52 +0000682 // FIXME: This warning is disabled in cases where it shouldn't be, like
683 // "#define constexpr constexpr", "int constexpr;"
Richard Smith31d51842015-05-14 04:00:59 +0000684 if (II.isFutureCompatKeyword() && !DisableMacroExpansion) {
685 Diag(Identifier, getFutureCompatDiagKind(II, getLangOpts()))
686 << II.getName();
Richard Smith4dd85d62011-10-11 19:57:52 +0000687 // Don't diagnose this keyword again in this translation unit.
Richard Smith31d51842015-05-14 04:00:59 +0000688 II.setIsFutureCompatKeyword(false);
Richard Smith4dd85d62011-10-11 19:57:52 +0000689 }
690
Chris Lattner5b9f4892006-11-21 17:23:33 +0000691 // C++ 2.11p2: If this is an alternative representation of a C++ operator,
692 // then we act as if it is the actual operator and not the textual
693 // representation of it.
Fariborz Jahanian9e42a952010-09-03 17:33:04 +0000694 if (II.isCPlusPlusOperatorKeyword())
Craig Topperd2d442c2014-05-17 23:10:59 +0000695 Identifier.setIdentifierInfo(nullptr);
Chris Lattner5b9f4892006-11-21 17:23:33 +0000696
Chris Lattner677757a2006-06-28 05:26:32 +0000697 // If this is an extension token, diagnose its use.
Steve Naroffc84e8b72008-09-02 18:50:17 +0000698 // We avoid diagnosing tokens that originate from macro definitions.
Eli Friedman6bba2ad2009-04-28 03:59:15 +0000699 // FIXME: This warning is disabled in cases where it shouldn't be,
700 // like "#define TY typeof", "TY(1) x".
701 if (II.isExtensionToken() && !DisableMacroExpansion)
Chris Lattner53621a52007-06-13 20:44:40 +0000702 Diag(Identifier, diag::ext_token_used);
Douglas Gregoraf5c4842011-09-07 23:11:54 +0000703
Douglas Gregor594b8c92013-11-07 22:55:02 +0000704 // If this is the 'import' contextual keyword following an '@', note
Ted Kremenekc1e4dd02012-03-01 22:07:04 +0000705 // that the next token indicates a module name.
Douglas Gregor8d76cca2012-01-04 06:20:15 +0000706 //
Douglas Gregorc50d4922012-12-11 22:11:52 +0000707 // Note that we do not treat 'import' as a contextual
Ted Kremenekc1e4dd02012-03-01 22:07:04 +0000708 // keyword when we're in a caching lexer, because caching lexers only get
709 // used in contexts where import declarations are disallowed.
Douglas Gregor594b8c92013-11-07 22:55:02 +0000710 if (LastTokenWasAt && II.isModulesImport() && !InMacroArgs &&
Sean Callanan87596492014-12-09 23:47:56 +0000711 !DisableMacroExpansion &&
712 (getLangOpts().Modules || getLangOpts().DebuggerSupport) &&
Douglas Gregor594b8c92013-11-07 22:55:02 +0000713 CurLexerKind != CLK_CachingLexer) {
Douglas Gregoraf5c4842011-09-07 23:11:54 +0000714 ModuleImportLoc = Identifier.getLocation();
Douglas Gregor1805b8a2011-11-30 04:26:53 +0000715 ModuleImportPath.clear();
716 ModuleImportExpectsIdentifier = true;
Douglas Gregoraf5c4842011-09-07 23:11:54 +0000717 CurLexerKind = CLK_LexAfterModuleImport;
718 }
Eli Friedman0834a4b2013-09-19 00:41:32 +0000719 return true;
Douglas Gregor08142532011-08-26 23:56:07 +0000720}
721
Eli Friedman0834a4b2013-09-19 00:41:32 +0000722void Preprocessor::Lex(Token &Result) {
Yaron Keren716f3a62015-09-29 16:51:08 +0000723 // We loop here until a lex function returns a token; this avoids recursion.
Eli Friedman0834a4b2013-09-19 00:41:32 +0000724 bool ReturnedToken;
725 do {
726 switch (CurLexerKind) {
727 case CLK_Lexer:
728 ReturnedToken = CurLexer->Lex(Result);
729 break;
730 case CLK_PTHLexer:
731 ReturnedToken = CurPTHLexer->Lex(Result);
732 break;
733 case CLK_TokenLexer:
734 ReturnedToken = CurTokenLexer->Lex(Result);
735 break;
736 case CLK_CachingLexer:
737 CachingLex(Result);
738 ReturnedToken = true;
739 break;
740 case CLK_LexAfterModuleImport:
741 LexAfterModuleImport(Result);
742 ReturnedToken = true;
743 break;
744 }
745 } while (!ReturnedToken);
Douglas Gregor594b8c92013-11-07 22:55:02 +0000746
747 LastTokenWasAt = Result.is(tok::at);
Eli Friedman0834a4b2013-09-19 00:41:32 +0000748}
749
750
Douglas Gregorda82e702012-01-03 19:32:59 +0000751/// \brief Lex a token following the 'import' contextual keyword.
Douglas Gregor22d09742012-01-03 18:04:46 +0000752///
Douglas Gregoraf5c4842011-09-07 23:11:54 +0000753void Preprocessor::LexAfterModuleImport(Token &Result) {
754 // Figure out what kind of lexer we actually have.
Douglas Gregor8d76cca2012-01-04 06:20:15 +0000755 recomputeCurLexerKind();
Douglas Gregoraf5c4842011-09-07 23:11:54 +0000756
757 // Lex the next token.
758 Lex(Result);
759
Douglas Gregor08142532011-08-26 23:56:07 +0000760 // The token sequence
761 //
Douglas Gregor22d09742012-01-03 18:04:46 +0000762 // import identifier (. identifier)*
763 //
Douglas Gregorda82e702012-01-03 19:32:59 +0000764 // indicates a module import directive. We already saw the 'import'
765 // contextual keyword, so now we're looking for the identifiers.
Douglas Gregor1805b8a2011-11-30 04:26:53 +0000766 if (ModuleImportExpectsIdentifier && Result.getKind() == tok::identifier) {
767 // We expected to see an identifier here, and we did; continue handling
768 // identifiers.
769 ModuleImportPath.push_back(std::make_pair(Result.getIdentifierInfo(),
770 Result.getLocation()));
771 ModuleImportExpectsIdentifier = false;
772 CurLexerKind = CLK_LexAfterModuleImport;
Douglas Gregor08142532011-08-26 23:56:07 +0000773 return;
Douglas Gregor1805b8a2011-11-30 04:26:53 +0000774 }
Douglas Gregor08142532011-08-26 23:56:07 +0000775
Douglas Gregor1805b8a2011-11-30 04:26:53 +0000776 // If we're expecting a '.' or a ';', and we got a '.', then wait until we
777 // see the next identifier.
778 if (!ModuleImportExpectsIdentifier && Result.getKind() == tok::period) {
779 ModuleImportExpectsIdentifier = true;
780 CurLexerKind = CLK_LexAfterModuleImport;
781 return;
782 }
783
784 // If we have a non-empty module path, load the named module.
Sean Callanan87596492014-12-09 23:47:56 +0000785 if (!ModuleImportPath.empty()) {
786 Module *Imported = nullptr;
Richard Smith753e0072015-04-27 23:21:38 +0000787 if (getLangOpts().Modules) {
Sean Callanan87596492014-12-09 23:47:56 +0000788 Imported = TheModuleLoader.loadModule(ModuleImportLoc,
789 ModuleImportPath,
Richard Smith10434f32015-05-02 02:08:26 +0000790 Module::Hidden,
Sean Callanan87596492014-12-09 23:47:56 +0000791 /*IsIncludeDirective=*/false);
Richard Smitha7e2cc62015-05-01 01:53:09 +0000792 if (Imported)
793 makeModuleVisible(Imported, ModuleImportLoc);
Richard Smith753e0072015-04-27 23:21:38 +0000794 }
Sean Callanan87596492014-12-09 23:47:56 +0000795 if (Callbacks && (getLangOpts().Modules || getLangOpts().DebuggerSupport))
Argyrios Kyrtzidis19d78b72012-09-29 01:06:10 +0000796 Callbacks->moduleImport(ModuleImportLoc, ModuleImportPath, Imported);
797 }
Chris Lattner677757a2006-06-28 05:26:32 +0000798}
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000799
Richard Smitha7e2cc62015-05-01 01:53:09 +0000800void Preprocessor::makeModuleVisible(Module *M, SourceLocation Loc) {
Richard Smith04765ae2015-05-21 01:20:10 +0000801 CurSubmoduleState->VisibleModules.setVisible(
Richard Smitha7e2cc62015-05-01 01:53:09 +0000802 M, Loc, [](Module *) {},
803 [&](ArrayRef<Module *> Path, Module *Conflict, StringRef Message) {
804 // FIXME: Include the path in the diagnostic.
805 // FIXME: Include the import location for the conflicting module.
806 Diag(ModuleImportLoc, diag::warn_module_conflict)
807 << Path[0]->getFullModuleName()
808 << Conflict->getFullModuleName()
809 << Message;
810 });
811
812 // Add this module to the imports list of the currently-built submodule.
Richard Smithdbbc5232015-05-14 02:25:44 +0000813 if (!BuildingSubmoduleStack.empty() && M != BuildingSubmoduleStack.back().M)
Richard Smith38477db2015-05-02 00:45:56 +0000814 BuildingSubmoduleStack.back().M->Imports.insert(M);
Richard Smitha7e2cc62015-05-01 01:53:09 +0000815}
816
Andy Gibbs58905d22012-11-17 19:15:38 +0000817bool Preprocessor::FinishLexStringLiteral(Token &Result, std::string &String,
Andy Gibbsa8df57a2012-11-17 19:16:52 +0000818 const char *DiagnosticTag,
Andy Gibbs58905d22012-11-17 19:15:38 +0000819 bool AllowMacroExpansion) {
820 // We need at least one string literal.
821 if (Result.isNot(tok::string_literal)) {
Andy Gibbsa8df57a2012-11-17 19:16:52 +0000822 Diag(Result, diag::err_expected_string_literal)
823 << /*Source='in...'*/0 << DiagnosticTag;
Andy Gibbs58905d22012-11-17 19:15:38 +0000824 return false;
825 }
826
827 // Lex string literal tokens, optionally with macro expansion.
828 SmallVector<Token, 4> StrToks;
829 do {
830 StrToks.push_back(Result);
831
832 if (Result.hasUDSuffix())
833 Diag(Result, diag::err_invalid_string_udl);
834
835 if (AllowMacroExpansion)
836 Lex(Result);
837 else
838 LexUnexpandedToken(Result);
839 } while (Result.is(tok::string_literal));
840
841 // Concatenate and parse the strings.
Craig Topper9d5583e2014-06-26 04:58:39 +0000842 StringLiteralParser Literal(StrToks, *this);
Andy Gibbs58905d22012-11-17 19:15:38 +0000843 assert(Literal.isAscii() && "Didn't allow wide strings in");
844
845 if (Literal.hadError)
846 return false;
847
848 if (Literal.Pascal) {
Andy Gibbsa8df57a2012-11-17 19:16:52 +0000849 Diag(StrToks[0].getLocation(), diag::err_expected_string_literal)
850 << /*Source='in...'*/0 << DiagnosticTag;
Andy Gibbs58905d22012-11-17 19:15:38 +0000851 return false;
852 }
853
854 String = Literal.GetString();
855 return true;
856}
857
Reid Klecknerc0dca6d2014-02-12 23:50:26 +0000858bool Preprocessor::parseSimpleIntegerLiteral(Token &Tok, uint64_t &Value) {
859 assert(Tok.is(tok::numeric_constant));
860 SmallString<8> IntegerBuffer;
861 bool NumberInvalid = false;
862 StringRef Spelling = getSpelling(Tok, IntegerBuffer, &NumberInvalid);
863 if (NumberInvalid)
864 return false;
865 NumericLiteralParser Literal(Spelling, Tok.getLocation(), *this);
866 if (Literal.hadError || !Literal.isIntegerLiteral() || Literal.hasUDSuffix())
867 return false;
868 llvm::APInt APVal(64, 0);
869 if (Literal.GetIntegerValue(APVal))
870 return false;
871 Lex(Tok);
872 Value = APVal.getLimitedValue();
873 return true;
874}
875
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000876void Preprocessor::addCommentHandler(CommentHandler *Handler) {
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000877 assert(Handler && "NULL comment handler");
878 assert(std::find(CommentHandlers.begin(), CommentHandlers.end(), Handler) ==
879 CommentHandlers.end() && "Comment handler already registered");
880 CommentHandlers.push_back(Handler);
881}
882
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000883void Preprocessor::removeCommentHandler(CommentHandler *Handler) {
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000884 std::vector<CommentHandler *>::iterator Pos
885 = std::find(CommentHandlers.begin(), CommentHandlers.end(), Handler);
886 assert(Pos != CommentHandlers.end() && "Comment handler not registered");
887 CommentHandlers.erase(Pos);
888}
889
Chris Lattner87d02082010-01-18 22:35:47 +0000890bool Preprocessor::HandleComment(Token &result, SourceRange Comment) {
891 bool AnyPendingTokens = false;
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000892 for (std::vector<CommentHandler *>::iterator H = CommentHandlers.begin(),
893 HEnd = CommentHandlers.end();
Chris Lattner87d02082010-01-18 22:35:47 +0000894 H != HEnd; ++H) {
895 if ((*H)->HandleComment(*this, Comment))
896 AnyPendingTokens = true;
897 }
898 if (!AnyPendingTokens || getCommentRetentionState())
899 return false;
900 Lex(result);
901 return true;
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000902}
903
Angel Garcia Gomez637d1e62015-10-20 13:23:58 +0000904ModuleLoader::~ModuleLoader() { }
Douglas Gregor08142532011-08-26 23:56:07 +0000905
Angel Garcia Gomez637d1e62015-10-20 13:23:58 +0000906CommentHandler::~CommentHandler() { }
Douglas Gregor7f6d60d2010-03-19 16:15:56 +0000907
Angel Garcia Gomez637d1e62015-10-20 13:23:58 +0000908CodeCompletionHandler::~CodeCompletionHandler() { }
Douglas Gregor3a7ad252010-08-24 19:08:16 +0000909
Argyrios Kyrtzidisf3d587e2012-12-04 07:27:05 +0000910void Preprocessor::createPreprocessingRecord() {
Douglas Gregor7f6d60d2010-03-19 16:15:56 +0000911 if (Record)
912 return;
913
Argyrios Kyrtzidisf3d587e2012-12-04 07:27:05 +0000914 Record = new PreprocessingRecord(getSourceManager());
Craig Topperb8a70532014-09-10 04:53:53 +0000915 addPPCallbacks(std::unique_ptr<PPCallbacks>(Record));
Douglas Gregor7f6d60d2010-03-19 16:15:56 +0000916}