blob: 70b992170c9ad8428d96df9b6ed59f86c555fc68 [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
56//===----------------------------------------------------------------------===//
Angel Garcia Gomez637d1e62015-10-20 13:23:58 +000057ExternalPreprocessorSource::~ExternalPreprocessorSource() { }
Chris Lattner22eb9722006-06-18 05:43:12 +000058
Dmitri Gribenkof8579502013-01-12 19:30:44 +000059Preprocessor::Preprocessor(IntrusiveRefCntPtr<PreprocessorOptions> PPOpts,
Douglas Gregor1452ff12012-10-24 17:46:57 +000060 DiagnosticsEngine &diags, LangOptions &opts,
Alp Toker96637802014-05-02 03:43:38 +000061 SourceManager &SM, HeaderSearch &Headers,
62 ModuleLoader &TheModuleLoader,
David Blaikie687cd952013-01-16 23:13:36 +000063 IdentifierInfoLookup *IILookup, bool OwnsHeaders,
Alp Toker1ae02f62014-05-02 03:43:30 +000064 TranslationUnitKind TUKind)
Craig Topper4b566922014-06-09 02:04:02 +000065 : PPOpts(PPOpts), Diags(&diags), LangOpts(opts), Target(nullptr),
Artem Belevichb5bc9232015-09-22 17:23:22 +000066 AuxTarget(nullptr), FileMgr(Headers.getFileMgr()), SourceMgr(SM),
67 ScratchBuf(new ScratchBuffer(SourceMgr)), HeaderInfo(Headers),
Craig Topperd2d442c2014-05-17 23:10:59 +000068 TheModuleLoader(TheModuleLoader), ExternalSource(nullptr),
Craig Topperbe250302014-09-12 05:19:24 +000069 Identifiers(opts, IILookup),
70 PragmaHandlers(new PragmaNamespace(StringRef())),
Artem Belevichb5bc9232015-09-22 17:23:22 +000071 IncrementalProcessing(false), TUKind(TUKind), CodeComplete(nullptr),
72 CodeCompletionFile(nullptr), CodeCompletionOffset(0),
73 LastTokenWasAt(false), ModuleImportExpectsIdentifier(false),
74 CodeCompletionReached(0), MainFileDir(nullptr),
75 SkipMainFilePreamble(0, true), CurPPLexer(nullptr), CurDirLookup(nullptr),
76 CurLexerKind(CLK_Lexer), CurSubmodule(nullptr), Callbacks(nullptr),
77 CurSubmoduleState(&NullSubmoduleState), MacroArgCache(nullptr),
78 Record(nullptr), MIChainHead(nullptr), DeserialMIChainHead(nullptr) {
Daniel Dunbar0c6c9302009-11-11 21:44:21 +000079 OwnsHeaderSearch = OwnsHeaders;
Douglas Gregor83297df2011-09-01 23:39:15 +000080
Douglas Gregor83297df2011-09-01 23:39:15 +000081 CounterValue = 0; // __COUNTER__ starts at 0.
82
83 // Clear stats.
84 NumDirectives = NumDefined = NumUndefined = NumPragma = 0;
85 NumIf = NumElse = NumEndif = 0;
86 NumEnteredSourceFiles = 0;
87 NumMacroExpanded = NumFnMacroExpanded = NumBuiltinMacroExpanded = 0;
88 NumFastMacroExpanded = NumTokenPaste = NumFastTokenPaste = 0;
89 MaxIncludeStackDepth = 0;
90 NumSkipped = 0;
91
92 // Default to discarding comments.
93 KeepComments = false;
94 KeepMacroComments = false;
95 SuppressIncludeNotFoundError = false;
96
97 // Macro expansion is enabled.
98 DisableMacroExpansion = false;
David Blaikied5321242012-06-06 18:52:13 +000099 MacroExpansionInDirectivesOverride = false;
Douglas Gregor83297df2011-09-01 23:39:15 +0000100 InMacroArgs = false;
Argyrios Kyrtzidisf1b64c62012-04-03 16:47:40 +0000101 InMacroArgPreExpansion = false;
Douglas Gregor83297df2011-09-01 23:39:15 +0000102 NumCachedTokenLexers = 0;
Jordan Rosede1a2922012-06-08 18:06:21 +0000103 PragmasEnabled = true;
Eric Christopher5e4696d2013-01-16 20:09:36 +0000104 ParsingIfOrElifDirective = false;
Jordan Rose324ec422013-01-31 19:26:01 +0000105 PreprocessedOutput = false;
Jordan Rosede1a2922012-06-08 18:06:21 +0000106
Douglas Gregor83297df2011-09-01 23:39:15 +0000107 CachedLexPos = 0;
Eric Christopher5e4696d2013-01-16 20:09:36 +0000108
Douglas Gregor83297df2011-09-01 23:39:15 +0000109 // We haven't read anything from the external source.
110 ReadMacrosFromExternalSource = false;
111
Douglas Gregor83297df2011-09-01 23:39:15 +0000112 // "Poison" __VA_ARGS__, which can only appear in the expansion of a macro.
113 // This gets unpoisoned where it is allowed.
114 (Ident__VA_ARGS__ = getIdentifierInfo("__VA_ARGS__"))->setIsPoisoned();
115 SetPoisonReason(Ident__VA_ARGS__,diag::ext_pp_bad_vaargs_use);
116
117 // Initialize the pragma handlers.
Douglas Gregor83297df2011-09-01 23:39:15 +0000118 RegisterBuiltinPragmas();
119
120 // Initialize builtin macros like __LINE__ and friends.
121 RegisterBuiltinMacros();
122
David Blaikiebbafb8a2012-03-11 07:00:24 +0000123 if(LangOpts.Borland) {
Douglas Gregor83297df2011-09-01 23:39:15 +0000124 Ident__exception_info = getIdentifierInfo("_exception_info");
125 Ident___exception_info = getIdentifierInfo("__exception_info");
126 Ident_GetExceptionInfo = getIdentifierInfo("GetExceptionInformation");
127 Ident__exception_code = getIdentifierInfo("_exception_code");
128 Ident___exception_code = getIdentifierInfo("__exception_code");
129 Ident_GetExceptionCode = getIdentifierInfo("GetExceptionCode");
130 Ident__abnormal_termination = getIdentifierInfo("_abnormal_termination");
131 Ident___abnormal_termination = getIdentifierInfo("__abnormal_termination");
132 Ident_AbnormalTermination = getIdentifierInfo("AbnormalTermination");
133 } else {
Craig Topperd2d442c2014-05-17 23:10:59 +0000134 Ident__exception_info = Ident__exception_code = nullptr;
135 Ident__abnormal_termination = Ident___exception_info = nullptr;
136 Ident___exception_code = Ident___abnormal_termination = nullptr;
137 Ident_GetExceptionInfo = Ident_GetExceptionCode = nullptr;
138 Ident_AbnormalTermination = nullptr;
Douglas Gregor89929282012-01-30 06:01:29 +0000139 }
Argyrios Kyrtzidis3c9aaf12012-06-02 18:08:09 +0000140}
141
142Preprocessor::~Preprocessor() {
143 assert(BacktrackPositions.empty() && "EnableBacktrack/Backtrack imbalance!");
144
Benjamin Kramer329c5962014-03-15 16:40:40 +0000145 IncludeMacroStack.clear();
Argyrios Kyrtzidis3c9aaf12012-06-02 18:08:09 +0000146
Richard Smith73a29662014-07-24 03:25:00 +0000147 // Destroy any macro definitions.
148 while (MacroInfoChain *I = MIChainHead) {
149 MIChainHead = I->Next;
150 I->~MacroInfoChain();
151 }
Argyrios Kyrtzidis3c9aaf12012-06-02 18:08:09 +0000152
153 // Free any cached macro expanders.
Nico Weber5f5b9412014-05-09 18:09:42 +0000154 // This populates MacroArgCache, so all TokenLexers need to be destroyed
155 // before the code below that frees up the MacroArgCache list.
David Blaikie6d5038c2014-08-29 19:36:52 +0000156 std::fill(TokenLexerCache, TokenLexerCache + NumCachedTokenLexers, nullptr);
Nico Weber5f5b9412014-05-09 18:09:42 +0000157 CurTokenLexer.reset();
Argyrios Kyrtzidis3c9aaf12012-06-02 18:08:09 +0000158
Richard Smith73a29662014-07-24 03:25:00 +0000159 while (DeserializedMacroInfoChain *I = DeserialMIChainHead) {
160 DeserialMIChainHead = I->Next;
161 I->~DeserializedMacroInfoChain();
162 }
Argyrios Kyrtzidisd48b91d2013-04-30 05:05:35 +0000163
Argyrios Kyrtzidis3c9aaf12012-06-02 18:08:09 +0000164 // Free any cached MacroArgs.
Nico Weber5f5b9412014-05-09 18:09:42 +0000165 for (MacroArgs *ArgList = MacroArgCache; ArgList;)
Argyrios Kyrtzidis3c9aaf12012-06-02 18:08:09 +0000166 ArgList = ArgList->deallocate();
167
Argyrios Kyrtzidis3c9aaf12012-06-02 18:08:09 +0000168 // Delete the header search info, if we own it.
169 if (OwnsHeaderSearch)
170 delete &HeaderInfo;
Argyrios Kyrtzidis3c9aaf12012-06-02 18:08:09 +0000171}
172
Artem Belevichb5bc9232015-09-22 17:23:22 +0000173void Preprocessor::Initialize(const TargetInfo &Target,
174 const TargetInfo *AuxTarget) {
Argyrios Kyrtzidis3c9aaf12012-06-02 18:08:09 +0000175 assert((!this->Target || this->Target == &Target) &&
176 "Invalid override of target information");
177 this->Target = &Target;
Artem Belevichb5bc9232015-09-22 17:23:22 +0000178
179 assert((!this->AuxTarget || this->AuxTarget == AuxTarget) &&
180 "Invalid override of aux target information.");
181 this->AuxTarget = AuxTarget;
182
Argyrios Kyrtzidis3c9aaf12012-06-02 18:08:09 +0000183 // Initialize information about built-ins.
Artem Belevichb5bc9232015-09-22 17:23:22 +0000184 BuiltinInfo.InitializeTarget(Target, AuxTarget);
Douglas Gregor89929282012-01-30 06:01:29 +0000185 HeaderInfo.setTarget(Target);
Douglas Gregor83297df2011-09-01 23:39:15 +0000186}
187
Ted Kremenekeeccb302014-08-27 15:14:15 +0000188void Preprocessor::InitializeForModelFile() {
189 NumEnteredSourceFiles = 0;
190
191 // Reset pragmas
David Blaikie9f0af9d2014-09-15 21:31:42 +0000192 PragmaHandlersBackup = std::move(PragmaHandlers);
Craig Topperbe250302014-09-12 05:19:24 +0000193 PragmaHandlers = llvm::make_unique<PragmaNamespace>(StringRef());
Ted Kremenekeeccb302014-08-27 15:14:15 +0000194 RegisterBuiltinPragmas();
195
196 // Reset PredefinesFileID
197 PredefinesFileID = FileID();
198}
199
200void Preprocessor::FinalizeForModelFile() {
201 NumEnteredSourceFiles = 1;
202
David Blaikie9f0af9d2014-09-15 21:31:42 +0000203 PragmaHandlers = std::move(PragmaHandlersBackup);
Ted Kremenekeeccb302014-08-27 15:14:15 +0000204}
205
Ted Kremeneka5c2c272009-02-12 03:26:59 +0000206void Preprocessor::setPTHManager(PTHManager* pm) {
207 PTH.reset(pm);
Douglas Gregord2eb58a2009-10-16 18:18:30 +0000208 FileMgr.addStatCache(PTH->createStatCache());
Ted Kremeneka5c2c272009-02-12 03:26:59 +0000209}
210
Chris Lattner146762e2007-07-20 16:59:19 +0000211void Preprocessor::DumpToken(const Token &Tok, bool DumpFlags) const {
Benjamin Kramer89b422c2009-08-23 12:08:50 +0000212 llvm::errs() << tok::getTokenName(Tok.getKind()) << " '"
213 << getSpelling(Tok) << "'";
Mike Stump11289f42009-09-09 15:08:12 +0000214
Chris Lattnerd01e2912006-06-18 16:22:51 +0000215 if (!DumpFlags) return;
Mike Stump11289f42009-09-09 15:08:12 +0000216
Benjamin Kramer89b422c2009-08-23 12:08:50 +0000217 llvm::errs() << "\t";
Chris Lattnerd01e2912006-06-18 16:22:51 +0000218 if (Tok.isAtStartOfLine())
Benjamin Kramer89b422c2009-08-23 12:08:50 +0000219 llvm::errs() << " [StartOfLine]";
Chris Lattnerd01e2912006-06-18 16:22:51 +0000220 if (Tok.hasLeadingSpace())
Benjamin Kramer89b422c2009-08-23 12:08:50 +0000221 llvm::errs() << " [LeadingSpace]";
Chris Lattner6e4bf522006-07-27 06:59:25 +0000222 if (Tok.isExpandDisabled())
Benjamin Kramer89b422c2009-08-23 12:08:50 +0000223 llvm::errs() << " [ExpandDisabled]";
Chris Lattnerd01e2912006-06-18 16:22:51 +0000224 if (Tok.needsCleaning()) {
Chris Lattner50b497e2006-06-18 16:32:35 +0000225 const char *Start = SourceMgr.getCharacterData(Tok.getLocation());
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000226 llvm::errs() << " [UnClean='" << StringRef(Start, Tok.getLength())
Benjamin Kramer89b422c2009-08-23 12:08:50 +0000227 << "']";
Chris Lattnerd01e2912006-06-18 16:22:51 +0000228 }
Mike Stump11289f42009-09-09 15:08:12 +0000229
Benjamin Kramer89b422c2009-08-23 12:08:50 +0000230 llvm::errs() << "\tLoc=<";
Chris Lattner615315f2007-12-09 20:31:55 +0000231 DumpLocation(Tok.getLocation());
Benjamin Kramer89b422c2009-08-23 12:08:50 +0000232 llvm::errs() << ">";
Chris Lattner615315f2007-12-09 20:31:55 +0000233}
234
235void Preprocessor::DumpLocation(SourceLocation Loc) const {
Chris Lattnerf1ca7d32009-01-27 07:57:44 +0000236 Loc.dump(SourceMgr);
Chris Lattnerd01e2912006-06-18 16:22:51 +0000237}
238
239void Preprocessor::DumpMacro(const MacroInfo &MI) const {
Benjamin Kramer89b422c2009-08-23 12:08:50 +0000240 llvm::errs() << "MACRO: ";
Chris Lattnerd01e2912006-06-18 16:22:51 +0000241 for (unsigned i = 0, e = MI.getNumTokens(); i != e; ++i) {
242 DumpToken(MI.getReplacementToken(i));
Benjamin Kramer89b422c2009-08-23 12:08:50 +0000243 llvm::errs() << " ";
Chris Lattnerd01e2912006-06-18 16:22:51 +0000244 }
Benjamin Kramer89b422c2009-08-23 12:08:50 +0000245 llvm::errs() << "\n";
Chris Lattnerd01e2912006-06-18 16:22:51 +0000246}
247
Chris Lattner22eb9722006-06-18 05:43:12 +0000248void Preprocessor::PrintStats() {
Benjamin Kramer89b422c2009-08-23 12:08:50 +0000249 llvm::errs() << "\n*** Preprocessor Stats:\n";
250 llvm::errs() << NumDirectives << " directives found:\n";
251 llvm::errs() << " " << NumDefined << " #define.\n";
252 llvm::errs() << " " << NumUndefined << " #undef.\n";
253 llvm::errs() << " #include/#include_next/#import:\n";
254 llvm::errs() << " " << NumEnteredSourceFiles << " source files entered.\n";
255 llvm::errs() << " " << MaxIncludeStackDepth << " max include stack depth\n";
256 llvm::errs() << " " << NumIf << " #if/#ifndef/#ifdef.\n";
257 llvm::errs() << " " << NumElse << " #else/#elif.\n";
258 llvm::errs() << " " << NumEndif << " #endif.\n";
259 llvm::errs() << " " << NumPragma << " #pragma.\n";
260 llvm::errs() << NumSkipped << " #if/#ifndef#ifdef regions skipped\n";
Chris Lattner22eb9722006-06-18 05:43:12 +0000261
Benjamin Kramer89b422c2009-08-23 12:08:50 +0000262 llvm::errs() << NumMacroExpanded << "/" << NumFnMacroExpanded << "/"
Ted Kremeneka0a3e9b2008-01-14 16:44:48 +0000263 << NumBuiltinMacroExpanded << " obj/fn/builtin macros expanded, "
264 << NumFastMacroExpanded << " on the fast path.\n";
Benjamin Kramer89b422c2009-08-23 12:08:50 +0000265 llvm::errs() << (NumFastTokenPaste+NumTokenPaste)
Ted Kremeneka0a3e9b2008-01-14 16:44:48 +0000266 << " token paste (##) operations performed, "
267 << NumFastTokenPaste << " on the fast path.\n";
Alexander Kornienko199cd942012-08-13 10:46:42 +0000268
269 llvm::errs() << "\nPreprocessor Memory: " << getTotalMemory() << "B total";
270
271 llvm::errs() << "\n BumpPtr: " << BP.getTotalMemory();
272 llvm::errs() << "\n Macro Expanded Tokens: "
273 << llvm::capacity_in_bytes(MacroExpandedTokens);
274 llvm::errs() << "\n Predefines Buffer: " << Predefines.capacity();
Richard Smith04765ae2015-05-21 01:20:10 +0000275 // FIXME: List information for all submodules.
276 llvm::errs() << "\n Macros: "
277 << llvm::capacity_in_bytes(CurSubmoduleState->Macros);
Alexander Kornienko199cd942012-08-13 10:46:42 +0000278 llvm::errs() << "\n #pragma push_macro Info: "
279 << llvm::capacity_in_bytes(PragmaPushMacroInfo);
280 llvm::errs() << "\n Poison Reasons: "
281 << llvm::capacity_in_bytes(PoisonReasons);
282 llvm::errs() << "\n Comment Handlers: "
283 << llvm::capacity_in_bytes(CommentHandlers) << "\n";
Chris Lattner22eb9722006-06-18 05:43:12 +0000284}
285
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +0000286Preprocessor::macro_iterator
287Preprocessor::macro_begin(bool IncludeExternalMacros) const {
288 if (IncludeExternalMacros && ExternalSource &&
Douglas Gregor9882a5a2010-01-04 19:18:44 +0000289 !ReadMacrosFromExternalSource) {
290 ReadMacrosFromExternalSource = true;
291 ExternalSource->ReadDefinedMacros();
292 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +0000293
Jordan Rosea46bfa62015-06-24 19:27:02 +0000294 // Make sure we cover all macros in visible modules.
295 for (const ModuleMacro &Macro : ModuleMacros)
296 CurSubmoduleState->Macros.insert(std::make_pair(Macro.II, MacroState()));
297
Richard Smith04765ae2015-05-21 01:20:10 +0000298 return CurSubmoduleState->Macros.begin();
Douglas Gregor9882a5a2010-01-04 19:18:44 +0000299}
300
Argyrios Kyrtzidise379ee32011-06-29 22:20:04 +0000301size_t Preprocessor::getTotalMemory() const {
Ted Kremenek182543a2011-07-26 21:17:24 +0000302 return BP.getTotalMemory()
Ted Kremenek8b77fe72011-07-27 18:41:23 +0000303 + llvm::capacity_in_bytes(MacroExpandedTokens)
Ted Kremenek182543a2011-07-26 21:17:24 +0000304 + Predefines.capacity() /* Predefines buffer. */
Richard Smith04765ae2015-05-21 01:20:10 +0000305 // FIXME: Include sizes from all submodules, and include MacroInfo sizes,
306 // and ModuleMacros.
307 + llvm::capacity_in_bytes(CurSubmoduleState->Macros)
Ted Kremenek8b77fe72011-07-27 18:41:23 +0000308 + llvm::capacity_in_bytes(PragmaPushMacroInfo)
309 + llvm::capacity_in_bytes(PoisonReasons)
310 + llvm::capacity_in_bytes(CommentHandlers);
Argyrios Kyrtzidise379ee32011-06-29 22:20:04 +0000311}
312
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +0000313Preprocessor::macro_iterator
314Preprocessor::macro_end(bool IncludeExternalMacros) const {
315 if (IncludeExternalMacros && ExternalSource &&
Douglas Gregor9882a5a2010-01-04 19:18:44 +0000316 !ReadMacrosFromExternalSource) {
317 ReadMacrosFromExternalSource = true;
318 ExternalSource->ReadDefinedMacros();
319 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +0000320
Richard Smith04765ae2015-05-21 01:20:10 +0000321 return CurSubmoduleState->Macros.end();
Douglas Gregor9882a5a2010-01-04 19:18:44 +0000322}
323
Dmitri Gribenko6743e042012-09-29 11:40:46 +0000324/// \brief Compares macro tokens with a specified token value sequence.
325static bool MacroDefinitionEquals(const MacroInfo *MI,
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000326 ArrayRef<TokenValue> Tokens) {
Dmitri Gribenko6743e042012-09-29 11:40:46 +0000327 return Tokens.size() == MI->getNumTokens() &&
328 std::equal(Tokens.begin(), Tokens.end(), MI->tokens_begin());
329}
330
331StringRef Preprocessor::getLastMacroWithSpelling(
332 SourceLocation Loc,
333 ArrayRef<TokenValue> Tokens) const {
334 SourceLocation BestLocation;
335 StringRef BestSpelling;
336 for (Preprocessor::macro_iterator I = macro_begin(), E = macro_end();
337 I != E; ++I) {
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +0000338 const MacroDirective::DefInfo
Richard Smithb8b2ed62015-04-23 18:18:26 +0000339 Def = I->second.findDirectiveAtLoc(Loc, SourceMgr);
Argyrios Kyrtzidis5c585252015-03-04 16:03:07 +0000340 if (!Def || !Def.getMacroInfo())
341 continue;
342 if (!Def.getMacroInfo()->isObjectLike())
Dmitri Gribenko6743e042012-09-29 11:40:46 +0000343 continue;
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +0000344 if (!MacroDefinitionEquals(Def.getMacroInfo(), Tokens))
Dmitri Gribenko6743e042012-09-29 11:40:46 +0000345 continue;
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +0000346 SourceLocation Location = Def.getLocation();
Dmitri Gribenko6743e042012-09-29 11:40:46 +0000347 // Choose the macro defined latest.
348 if (BestLocation.isInvalid() ||
349 (Location.isValid() &&
350 SourceMgr.isBeforeInTranslationUnit(BestLocation, Location))) {
351 BestLocation = Location;
352 BestSpelling = I->first->getName();
353 }
354 }
355 return BestSpelling;
356}
357
Douglas Gregor8d76cca2012-01-04 06:20:15 +0000358void Preprocessor::recomputeCurLexerKind() {
359 if (CurLexer)
360 CurLexerKind = CLK_Lexer;
361 else if (CurPTHLexer)
362 CurLexerKind = CLK_PTHLexer;
363 else if (CurTokenLexer)
364 CurLexerKind = CLK_TokenLexer;
365 else
366 CurLexerKind = CLK_CachingLexer;
367}
368
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +0000369bool Preprocessor::SetCodeCompletionPoint(const FileEntry *File,
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +0000370 unsigned CompleteLine,
371 unsigned CompleteColumn) {
372 assert(File);
373 assert(CompleteLine && CompleteColumn && "Starts from 1:1");
374 assert(!CodeCompletionFile && "Already set");
375
Douglas Gregor53ad6b92009-12-02 06:49:09 +0000376 using llvm::MemoryBuffer;
377
Douglas Gregor53ad6b92009-12-02 06:49:09 +0000378 // Load the actual file's contents.
Douglas Gregor26266da2010-03-16 19:49:24 +0000379 bool Invalid = false;
380 const MemoryBuffer *Buffer = SourceMgr.getMemoryBufferForFile(File, &Invalid);
381 if (Invalid)
Douglas Gregor53ad6b92009-12-02 06:49:09 +0000382 return true;
383
384 // Find the byte position of the truncation point.
385 const char *Position = Buffer->getBufferStart();
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +0000386 for (unsigned Line = 1; Line < CompleteLine; ++Line) {
Douglas Gregor53ad6b92009-12-02 06:49:09 +0000387 for (; *Position; ++Position) {
388 if (*Position != '\r' && *Position != '\n')
389 continue;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +0000390
Douglas Gregor53ad6b92009-12-02 06:49:09 +0000391 // Eat \r\n or \n\r as a single line.
392 if ((Position[1] == '\r' || Position[1] == '\n') &&
393 Position[0] != Position[1])
394 ++Position;
395 ++Position;
396 break;
397 }
398 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +0000399
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +0000400 Position += CompleteColumn - 1;
Argyrios Kyrtzidisee301f92014-10-18 06:23:50 +0000401
402 // If pointing inside the preamble, adjust the position at the beginning of
403 // the file after the preamble.
404 if (SkipMainFilePreamble.first &&
405 SourceMgr.getFileEntryForID(SourceMgr.getMainFileID()) == File) {
406 if (Position - Buffer->getBufferStart() < SkipMainFilePreamble.first)
407 Position = Buffer->getBufferStart() + SkipMainFilePreamble.first;
408 }
409
Argyrios Kyrtzidise62d6822014-10-18 06:19:36 +0000410 if (Position > Buffer->getBufferEnd())
411 Position = Buffer->getBufferEnd();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +0000412
Argyrios Kyrtzidise62d6822014-10-18 06:19:36 +0000413 CodeCompletionFile = File;
414 CodeCompletionOffset = Position - Buffer->getBufferStart();
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +0000415
Argyrios Kyrtzidise62d6822014-10-18 06:19:36 +0000416 std::unique_ptr<MemoryBuffer> NewBuffer =
417 MemoryBuffer::getNewUninitMemBuffer(Buffer->getBufferSize() + 1,
418 Buffer->getBufferIdentifier());
419 char *NewBuf = const_cast<char*>(NewBuffer->getBufferStart());
420 char *NewPos = std::copy(Buffer->getBufferStart(), Position, NewBuf);
421 *NewPos = '\0';
422 std::copy(Position, Buffer->getBufferEnd(), NewPos+1);
423 SourceMgr.overrideFileContents(File, std::move(NewBuffer));
Douglas Gregor53ad6b92009-12-02 06:49:09 +0000424
425 return false;
426}
427
Douglas Gregor11583702010-08-25 17:04:25 +0000428void Preprocessor::CodeCompleteNaturalLanguage() {
Douglas Gregor11583702010-08-25 17:04:25 +0000429 if (CodeComplete)
430 CodeComplete->CodeCompleteNaturalLanguage();
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +0000431 setCodeCompletionReached();
Douglas Gregor11583702010-08-25 17:04:25 +0000432}
433
Benjamin Kramera197fb62010-02-27 17:05:45 +0000434/// getSpelling - This method is used to get the spelling of a token into a
435/// SmallVector. Note that the returned StringRef may not point to the
436/// supplied buffer if a copy can be avoided.
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000437StringRef Preprocessor::getSpelling(const Token &Tok,
438 SmallVectorImpl<char> &Buffer,
Douglas Gregor7bda4b82010-03-16 05:20:39 +0000439 bool *Invalid) const {
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +0000440 // NOTE: this has to be checked *before* testing for an IdentifierInfo.
Jordan Rose7f43ddd2013-01-24 20:50:46 +0000441 if (Tok.isNot(tok::raw_identifier) && !Tok.hasUCN()) {
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +0000442 // Try the fast path.
443 if (const IdentifierInfo *II = Tok.getIdentifierInfo())
444 return II->getName();
445 }
Benjamin Kramera197fb62010-02-27 17:05:45 +0000446
447 // Resize the buffer if we need to copy into it.
448 if (Tok.needsCleaning())
449 Buffer.resize(Tok.getLength());
450
451 const char *Ptr = Buffer.data();
Douglas Gregor7bda4b82010-03-16 05:20:39 +0000452 unsigned Len = getSpelling(Tok, Ptr, Invalid);
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000453 return StringRef(Ptr, Len);
Benjamin Kramera197fb62010-02-27 17:05:45 +0000454}
455
Chris Lattnerb94ec7b2006-07-14 06:54:10 +0000456/// CreateString - Plop the specified string into a scratch buffer and return a
457/// location for it. If specified, the source location provides a source
458/// location for the token.
Dmitri Gribenkob8e9e752012-09-24 21:07:17 +0000459void Preprocessor::CreateString(StringRef Str, Token &Tok,
Abramo Bagnarae398e602011-10-03 18:39:03 +0000460 SourceLocation ExpansionLocStart,
461 SourceLocation ExpansionLocEnd) {
Dmitri Gribenkob8e9e752012-09-24 21:07:17 +0000462 Tok.setLength(Str.size());
Mike Stump11289f42009-09-09 15:08:12 +0000463
Chris Lattner5a7971e2009-01-26 19:29:26 +0000464 const char *DestPtr;
Dmitri Gribenkob8e9e752012-09-24 21:07:17 +0000465 SourceLocation Loc = ScratchBuf->getToken(Str.data(), Str.size(), DestPtr);
Mike Stump11289f42009-09-09 15:08:12 +0000466
Abramo Bagnarae398e602011-10-03 18:39:03 +0000467 if (ExpansionLocStart.isValid())
468 Loc = SourceMgr.createExpansionLoc(Loc, ExpansionLocStart,
Dmitri Gribenkob8e9e752012-09-24 21:07:17 +0000469 ExpansionLocEnd, Str.size());
Chris Lattner5a7971e2009-01-26 19:29:26 +0000470 Tok.setLocation(Loc);
Mike Stump11289f42009-09-09 15:08:12 +0000471
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +0000472 // If this is a raw identifier or a literal token, set the pointer data.
473 if (Tok.is(tok::raw_identifier))
474 Tok.setRawIdentifierData(DestPtr);
475 else if (Tok.isLiteral())
Chris Lattner5a7971e2009-01-26 19:29:26 +0000476 Tok.setLiteralData(DestPtr);
Chris Lattnerb94ec7b2006-07-14 06:54:10 +0000477}
478
Douglas Gregor2b82c2a2011-12-02 01:47:07 +0000479Module *Preprocessor::getCurrentModule() {
Richard Smith7e82e012016-02-19 22:25:36 +0000480 if (!getLangOpts().CompilingModule)
Craig Topperd2d442c2014-05-17 23:10:59 +0000481 return nullptr;
482
David Blaikiebbafb8a2012-03-11 07:00:24 +0000483 return getHeaderSearchInfo().lookupModule(getLangOpts().CurrentModule);
Douglas Gregor2b82c2a2011-12-02 01:47:07 +0000484}
Chris Lattner8a7003c2007-07-16 06:48:38 +0000485
Chris Lattner1f1b0db2007-10-09 22:10:18 +0000486//===----------------------------------------------------------------------===//
487// Preprocessor Initialization Methods
488//===----------------------------------------------------------------------===//
489
Chris Lattner1f1b0db2007-10-09 22:10:18 +0000490
491/// EnterMainSourceFile - Enter the specified FileID as the main source file,
Nate Begemanf7c3ff62008-01-07 04:01:26 +0000492/// which implicitly adds the builtin defines etc.
Chris Lattnerfb24a3a2010-04-20 20:35:58 +0000493void Preprocessor::EnterMainSourceFile() {
Chris Lattner9ef847b2009-02-13 19:33:24 +0000494 // We do not allow the preprocessor to reenter the main file. Doing so will
495 // cause FileID's to accumulate information from both runs (e.g. #line
496 // information) and predefined macros aren't guaranteed to be set properly.
497 assert(NumEnteredSourceFiles == 0 && "Cannot reenter the main file!");
Chris Lattnerd32480d2009-01-17 06:22:33 +0000498 FileID MainFileID = SourceMgr.getMainFileID();
Mike Stump11289f42009-09-09 15:08:12 +0000499
Argyrios Kyrtzidis9afd4492012-01-05 21:36:25 +0000500 // If MainFileID is loaded it means we loaded an AST file, no need to enter
501 // a main file.
502 if (!SourceMgr.isLoadedFileID(MainFileID)) {
503 // Enter the main file source buffer.
Craig Topperd2d442c2014-05-17 23:10:59 +0000504 EnterSourceFile(MainFileID, nullptr, SourceLocation());
505
Argyrios Kyrtzidis9afd4492012-01-05 21:36:25 +0000506 // If we've been asked to skip bytes in the main file (e.g., as part of a
507 // precompiled preamble), do so now.
508 if (SkipMainFilePreamble.first > 0)
509 CurLexer->SkipBytes(SkipMainFilePreamble.first,
510 SkipMainFilePreamble.second);
511
512 // Tell the header info that the main file was entered. If the file is later
513 // #imported, it won't be re-entered.
514 if (const FileEntry *FE = SourceMgr.getFileEntryForID(MainFileID))
515 HeaderInfo.IncrementIncludeCount(FE);
516 }
Mike Stump11289f42009-09-09 15:08:12 +0000517
Benjamin Kramerd77adb52009-12-31 15:33:09 +0000518 // Preprocess Predefines to populate the initial preprocessor state.
Rafael Espindolad87f8d72014-08-27 20:03:29 +0000519 std::unique_ptr<llvm::MemoryBuffer> SB =
Chris Lattner58c79342010-04-05 22:42:27 +0000520 llvm::MemoryBuffer::getMemBufferCopy(Predefines, "<built-in>");
Douglas Gregor33551892010-08-26 14:07:34 +0000521 assert(SB && "Cannot create predefined source buffer");
David Blaikie50a5f972014-08-29 07:59:55 +0000522 FileID FID = SourceMgr.createFileID(std::move(SB));
Yaron Keren8b563662015-10-03 10:46:20 +0000523 assert(FID.isValid() && "Could not create FileID for predefines?");
Argyrios Kyrtzidis22c22f52013-02-01 16:36:07 +0000524 setPredefinesFileID(FID);
Mike Stump11289f42009-09-09 15:08:12 +0000525
Chris Lattner1f1b0db2007-10-09 22:10:18 +0000526 // Start parsing the predefines.
Craig Topperd2d442c2014-05-17 23:10:59 +0000527 EnterSourceFile(FID, nullptr, SourceLocation());
Chris Lattner1f1b0db2007-10-09 22:10:18 +0000528}
Chris Lattner8a7003c2007-07-16 06:48:38 +0000529
Daniel Dunbarcb9eaf52010-03-23 05:09:10 +0000530void Preprocessor::EndSourceFile() {
531 // Notify the client that we reached the end of the source file.
532 if (Callbacks)
533 Callbacks->EndOfMainFile();
534}
Chris Lattner677757a2006-06-28 05:26:32 +0000535
536//===----------------------------------------------------------------------===//
537// Lexer Event Handling.
538//===----------------------------------------------------------------------===//
539
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +0000540/// LookUpIdentifierInfo - Given a tok::raw_identifier token, look up the
541/// identifier information for the token and install it into the token,
542/// updating the token kind accordingly.
543IdentifierInfo *Preprocessor::LookUpIdentifierInfo(Token &Identifier) const {
Alp Toker2d57cea2014-05-17 04:53:25 +0000544 assert(!Identifier.getRawIdentifier().empty() && "No raw identifier data!");
Mike Stump11289f42009-09-09 15:08:12 +0000545
Chris Lattnercefc7682006-07-08 08:28:12 +0000546 // Look up this token, see if it is a macro, or if it is a language keyword.
547 IdentifierInfo *II;
Jordan Rose7f43ddd2013-01-24 20:50:46 +0000548 if (!Identifier.needsCleaning() && !Identifier.hasUCN()) {
Chris Lattnercefc7682006-07-08 08:28:12 +0000549 // No cleaning needed, just use the characters from the lexed buffer.
Alp Toker2d57cea2014-05-17 04:53:25 +0000550 II = getIdentifierInfo(Identifier.getRawIdentifier());
Chris Lattnercefc7682006-07-08 08:28:12 +0000551 } else {
552 // Cleaning needed, alloca a buffer, clean into it, then use the buffer.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +0000553 SmallString<64> IdentifierBuffer;
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000554 StringRef CleanedStr = getSpelling(Identifier, IdentifierBuffer);
Jordan Rose7f43ddd2013-01-24 20:50:46 +0000555
556 if (Identifier.hasUCN()) {
557 SmallString<64> UCNIdentifierBuffer;
558 expandUCNs(UCNIdentifierBuffer, CleanedStr);
559 II = getIdentifierInfo(UCNIdentifierBuffer);
560 } else {
561 II = getIdentifierInfo(CleanedStr);
562 }
Chris Lattnercefc7682006-07-08 08:28:12 +0000563 }
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +0000564
565 // Update the token info (identifier info and appropriate token kind).
Chris Lattner8c204872006-10-14 05:19:21 +0000566 Identifier.setIdentifierInfo(II);
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +0000567 Identifier.setKind(II->getTokenID());
568
Chris Lattnercefc7682006-07-08 08:28:12 +0000569 return II;
570}
571
John Wiegley1c0675e2011-04-28 01:08:34 +0000572void Preprocessor::SetPoisonReason(IdentifierInfo *II, unsigned DiagID) {
573 PoisonReasons[II] = DiagID;
574}
575
576void Preprocessor::PoisonSEHIdentifiers(bool Poison) {
577 assert(Ident__exception_code && Ident__exception_info);
578 assert(Ident___exception_code && Ident___exception_info);
579 Ident__exception_code->setIsPoisoned(Poison);
580 Ident___exception_code->setIsPoisoned(Poison);
581 Ident_GetExceptionCode->setIsPoisoned(Poison);
582 Ident__exception_info->setIsPoisoned(Poison);
583 Ident___exception_info->setIsPoisoned(Poison);
584 Ident_GetExceptionInfo->setIsPoisoned(Poison);
585 Ident__abnormal_termination->setIsPoisoned(Poison);
586 Ident___abnormal_termination->setIsPoisoned(Poison);
587 Ident_AbnormalTermination->setIsPoisoned(Poison);
588}
589
590void Preprocessor::HandlePoisonedIdentifier(Token & Identifier) {
591 assert(Identifier.getIdentifierInfo() &&
592 "Can't handle identifiers without identifier info!");
593 llvm::DenseMap<IdentifierInfo*,unsigned>::const_iterator it =
594 PoisonReasons.find(Identifier.getIdentifierInfo());
595 if(it == PoisonReasons.end())
596 Diag(Identifier, diag::err_pp_used_poisoned_id);
597 else
598 Diag(Identifier,it->second) << Identifier.getIdentifierInfo();
599}
Chris Lattnercefc7682006-07-08 08:28:12 +0000600
Richard Smith31d51842015-05-14 04:00:59 +0000601/// \brief Returns a diagnostic message kind for reporting a future keyword as
602/// appropriate for the identifier and specified language.
603static diag::kind getFutureCompatDiagKind(const IdentifierInfo &II,
604 const LangOptions &LangOpts) {
605 assert(II.isFutureCompatKeyword() && "diagnostic should not be needed");
606
607 if (LangOpts.CPlusPlus)
608 return llvm::StringSwitch<diag::kind>(II.getName())
609#define CXX11_KEYWORD(NAME, FLAGS) \
610 .Case(#NAME, diag::warn_cxx11_keyword)
611#include "clang/Basic/TokenKinds.def"
612 ;
613
614 llvm_unreachable(
615 "Keyword not known to come from a newer Standard or proposed Standard");
616}
617
Chris Lattner677757a2006-06-28 05:26:32 +0000618/// HandleIdentifier - This callback is invoked when the lexer reads an
619/// identifier. This callback looks up the identifier in the map and/or
620/// potentially macro expands it or turns it into a named token (like 'for').
Chris Lattnerad89ec02009-01-21 07:43:11 +0000621///
622/// Note that callers of this method are guarded by checking the
623/// IdentifierInfo's 'isHandleIdentifierCase' bit. If this method changes, the
624/// IdentifierInfo methods that compute these properties will need to change to
625/// match.
Eli Friedman0834a4b2013-09-19 00:41:32 +0000626bool Preprocessor::HandleIdentifier(Token &Identifier) {
Chris Lattner0f1f5052006-07-20 04:16:23 +0000627 assert(Identifier.getIdentifierInfo() &&
628 "Can't handle identifiers without identifier info!");
Mike Stump11289f42009-09-09 15:08:12 +0000629
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000630 IdentifierInfo &II = *Identifier.getIdentifierInfo();
Chris Lattner677757a2006-06-28 05:26:32 +0000631
Douglas Gregor935bc7a22011-10-27 09:33:13 +0000632 // If the information about this identifier is out of date, update it from
633 // the external source.
Douglas Gregor3f568c12012-06-29 18:27:59 +0000634 // We have to treat __VA_ARGS__ in a special way, since it gets
635 // serialized with isPoisoned = true, but our preprocessor may have
636 // unpoisoned it if we're defining a C99 macro.
Douglas Gregor935bc7a22011-10-27 09:33:13 +0000637 if (II.isOutOfDate()) {
Douglas Gregor3f568c12012-06-29 18:27:59 +0000638 bool CurrentIsPoisoned = false;
639 if (&II == Ident__VA_ARGS__)
640 CurrentIsPoisoned = Ident__VA_ARGS__->isPoisoned();
641
Douglas Gregor935bc7a22011-10-27 09:33:13 +0000642 ExternalSource->updateOutOfDateIdentifier(II);
643 Identifier.setKind(II.getTokenID());
Douglas Gregor3f568c12012-06-29 18:27:59 +0000644
645 if (&II == Ident__VA_ARGS__)
646 II.setIsPoisoned(CurrentIsPoisoned);
Douglas Gregor935bc7a22011-10-27 09:33:13 +0000647 }
648
Chris Lattner677757a2006-06-28 05:26:32 +0000649 // If this identifier was poisoned, and if it was not produced from a macro
650 // expansion, emit an error.
Ted Kremeneka2c3c8d2008-11-19 22:43:49 +0000651 if (II.isPoisoned() && CurPPLexer) {
John Wiegley1c0675e2011-04-28 01:08:34 +0000652 HandlePoisonedIdentifier(Identifier);
Chris Lattner8ff71992006-07-06 05:17:39 +0000653 }
Mike Stump11289f42009-09-09 15:08:12 +0000654
Chris Lattner78186052006-07-09 00:45:31 +0000655 // If this is a macro to be expanded, do it.
Richard Smith20e883e2015-04-29 23:20:19 +0000656 if (MacroDefinition MD = getMacroDefinition(&II)) {
657 auto *MI = MD.getMacroInfo();
Richard Smithf5ec2ac2015-04-29 23:40:48 +0000658 assert(MI && "macro definition with no macro info?");
Abramo Bagnara123bec82012-01-01 22:01:04 +0000659 if (!DisableMacroExpansion) {
Richard Smith181879c2012-12-12 02:46:14 +0000660 if (!Identifier.isExpandDisabled() && MI->isEnabled()) {
Eli Friedman0834a4b2013-09-19 00:41:32 +0000661 // C99 6.10.3p10: If the preprocessing token immediately after the
662 // macro name isn't a '(', this macro should not be expanded.
663 if (!MI->isFunctionLike() || isNextPPTokenLParen())
664 return HandleMacroExpandedIdentifier(Identifier, MD);
Chris Lattner6e4bf522006-07-27 06:59:25 +0000665 } else {
666 // C99 6.10.3.4p2 says that a disabled macro may never again be
667 // expanded, even if it's in a context where it could be expanded in the
668 // future.
Chris Lattner146762e2007-07-20 16:59:19 +0000669 Identifier.setFlag(Token::DisableExpand);
Richard Smith181879c2012-12-12 02:46:14 +0000670 if (MI->isObjectLike() || isNextPPTokenLParen())
671 Diag(Identifier, diag::pp_disabled_macro_expansion);
Chris Lattner6e4bf522006-07-27 06:59:25 +0000672 }
673 }
Chris Lattner063400e2006-10-14 19:54:15 +0000674 }
Chris Lattner677757a2006-06-28 05:26:32 +0000675
Richard Smith31d51842015-05-14 04:00:59 +0000676 // If this identifier is a keyword in a newer Standard or proposed Standard,
677 // produce a warning. Don't warn if we're not considering macro expansion,
678 // since this identifier might be the name of a macro.
Richard Smith4dd85d62011-10-11 19:57:52 +0000679 // FIXME: This warning is disabled in cases where it shouldn't be, like
680 // "#define constexpr constexpr", "int constexpr;"
Richard Smith31d51842015-05-14 04:00:59 +0000681 if (II.isFutureCompatKeyword() && !DisableMacroExpansion) {
682 Diag(Identifier, getFutureCompatDiagKind(II, getLangOpts()))
683 << II.getName();
Richard Smith4dd85d62011-10-11 19:57:52 +0000684 // Don't diagnose this keyword again in this translation unit.
Richard Smith31d51842015-05-14 04:00:59 +0000685 II.setIsFutureCompatKeyword(false);
Richard Smith4dd85d62011-10-11 19:57:52 +0000686 }
687
Chris Lattner5b9f4892006-11-21 17:23:33 +0000688 // C++ 2.11p2: If this is an alternative representation of a C++ operator,
689 // then we act as if it is the actual operator and not the textual
690 // representation of it.
Fariborz Jahanian9e42a952010-09-03 17:33:04 +0000691 if (II.isCPlusPlusOperatorKeyword())
Craig Topperd2d442c2014-05-17 23:10:59 +0000692 Identifier.setIdentifierInfo(nullptr);
Chris Lattner5b9f4892006-11-21 17:23:33 +0000693
Chris Lattner677757a2006-06-28 05:26:32 +0000694 // If this is an extension token, diagnose its use.
Steve Naroffc84e8b72008-09-02 18:50:17 +0000695 // We avoid diagnosing tokens that originate from macro definitions.
Eli Friedman6bba2ad2009-04-28 03:59:15 +0000696 // FIXME: This warning is disabled in cases where it shouldn't be,
697 // like "#define TY typeof", "TY(1) x".
698 if (II.isExtensionToken() && !DisableMacroExpansion)
Chris Lattner53621a52007-06-13 20:44:40 +0000699 Diag(Identifier, diag::ext_token_used);
Douglas Gregoraf5c4842011-09-07 23:11:54 +0000700
Douglas Gregor594b8c92013-11-07 22:55:02 +0000701 // If this is the 'import' contextual keyword following an '@', note
Ted Kremenekc1e4dd02012-03-01 22:07:04 +0000702 // that the next token indicates a module name.
Douglas Gregor8d76cca2012-01-04 06:20:15 +0000703 //
Douglas Gregorc50d4922012-12-11 22:11:52 +0000704 // Note that we do not treat 'import' as a contextual
Ted Kremenekc1e4dd02012-03-01 22:07:04 +0000705 // keyword when we're in a caching lexer, because caching lexers only get
706 // used in contexts where import declarations are disallowed.
Douglas Gregor594b8c92013-11-07 22:55:02 +0000707 if (LastTokenWasAt && II.isModulesImport() && !InMacroArgs &&
Sean Callanan87596492014-12-09 23:47:56 +0000708 !DisableMacroExpansion &&
709 (getLangOpts().Modules || getLangOpts().DebuggerSupport) &&
Douglas Gregor594b8c92013-11-07 22:55:02 +0000710 CurLexerKind != CLK_CachingLexer) {
Douglas Gregoraf5c4842011-09-07 23:11:54 +0000711 ModuleImportLoc = Identifier.getLocation();
Douglas Gregor1805b8a2011-11-30 04:26:53 +0000712 ModuleImportPath.clear();
713 ModuleImportExpectsIdentifier = true;
Douglas Gregoraf5c4842011-09-07 23:11:54 +0000714 CurLexerKind = CLK_LexAfterModuleImport;
715 }
Eli Friedman0834a4b2013-09-19 00:41:32 +0000716 return true;
Douglas Gregor08142532011-08-26 23:56:07 +0000717}
718
Eli Friedman0834a4b2013-09-19 00:41:32 +0000719void Preprocessor::Lex(Token &Result) {
Yaron Keren716f3a62015-09-29 16:51:08 +0000720 // We loop here until a lex function returns a token; this avoids recursion.
Eli Friedman0834a4b2013-09-19 00:41:32 +0000721 bool ReturnedToken;
722 do {
723 switch (CurLexerKind) {
724 case CLK_Lexer:
725 ReturnedToken = CurLexer->Lex(Result);
726 break;
727 case CLK_PTHLexer:
728 ReturnedToken = CurPTHLexer->Lex(Result);
729 break;
730 case CLK_TokenLexer:
731 ReturnedToken = CurTokenLexer->Lex(Result);
732 break;
733 case CLK_CachingLexer:
734 CachingLex(Result);
735 ReturnedToken = true;
736 break;
737 case CLK_LexAfterModuleImport:
738 LexAfterModuleImport(Result);
739 ReturnedToken = true;
740 break;
741 }
742 } while (!ReturnedToken);
Douglas Gregor594b8c92013-11-07 22:55:02 +0000743
744 LastTokenWasAt = Result.is(tok::at);
Eli Friedman0834a4b2013-09-19 00:41:32 +0000745}
746
747
Douglas Gregorda82e702012-01-03 19:32:59 +0000748/// \brief Lex a token following the 'import' contextual keyword.
Douglas Gregor22d09742012-01-03 18:04:46 +0000749///
Douglas Gregoraf5c4842011-09-07 23:11:54 +0000750void Preprocessor::LexAfterModuleImport(Token &Result) {
751 // Figure out what kind of lexer we actually have.
Douglas Gregor8d76cca2012-01-04 06:20:15 +0000752 recomputeCurLexerKind();
Douglas Gregoraf5c4842011-09-07 23:11:54 +0000753
754 // Lex the next token.
755 Lex(Result);
756
Douglas Gregor08142532011-08-26 23:56:07 +0000757 // The token sequence
758 //
Douglas Gregor22d09742012-01-03 18:04:46 +0000759 // import identifier (. identifier)*
760 //
Douglas Gregorda82e702012-01-03 19:32:59 +0000761 // indicates a module import directive. We already saw the 'import'
762 // contextual keyword, so now we're looking for the identifiers.
Douglas Gregor1805b8a2011-11-30 04:26:53 +0000763 if (ModuleImportExpectsIdentifier && Result.getKind() == tok::identifier) {
764 // We expected to see an identifier here, and we did; continue handling
765 // identifiers.
766 ModuleImportPath.push_back(std::make_pair(Result.getIdentifierInfo(),
767 Result.getLocation()));
768 ModuleImportExpectsIdentifier = false;
769 CurLexerKind = CLK_LexAfterModuleImport;
Douglas Gregor08142532011-08-26 23:56:07 +0000770 return;
Douglas Gregor1805b8a2011-11-30 04:26:53 +0000771 }
Douglas Gregor08142532011-08-26 23:56:07 +0000772
Douglas Gregor1805b8a2011-11-30 04:26:53 +0000773 // If we're expecting a '.' or a ';', and we got a '.', then wait until we
774 // see the next identifier.
775 if (!ModuleImportExpectsIdentifier && Result.getKind() == tok::period) {
776 ModuleImportExpectsIdentifier = true;
777 CurLexerKind = CLK_LexAfterModuleImport;
778 return;
779 }
780
781 // If we have a non-empty module path, load the named module.
Sean Callanan87596492014-12-09 23:47:56 +0000782 if (!ModuleImportPath.empty()) {
783 Module *Imported = nullptr;
Richard Smith753e0072015-04-27 23:21:38 +0000784 if (getLangOpts().Modules) {
Sean Callanan87596492014-12-09 23:47:56 +0000785 Imported = TheModuleLoader.loadModule(ModuleImportLoc,
786 ModuleImportPath,
Richard Smith10434f32015-05-02 02:08:26 +0000787 Module::Hidden,
Sean Callanan87596492014-12-09 23:47:56 +0000788 /*IsIncludeDirective=*/false);
Richard Smitha7e2cc62015-05-01 01:53:09 +0000789 if (Imported)
790 makeModuleVisible(Imported, ModuleImportLoc);
Richard Smith753e0072015-04-27 23:21:38 +0000791 }
Sean Callanan87596492014-12-09 23:47:56 +0000792 if (Callbacks && (getLangOpts().Modules || getLangOpts().DebuggerSupport))
Argyrios Kyrtzidis19d78b72012-09-29 01:06:10 +0000793 Callbacks->moduleImport(ModuleImportLoc, ModuleImportPath, Imported);
794 }
Chris Lattner677757a2006-06-28 05:26:32 +0000795}
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000796
Richard Smitha7e2cc62015-05-01 01:53:09 +0000797void Preprocessor::makeModuleVisible(Module *M, SourceLocation Loc) {
Richard Smith04765ae2015-05-21 01:20:10 +0000798 CurSubmoduleState->VisibleModules.setVisible(
Richard Smitha7e2cc62015-05-01 01:53:09 +0000799 M, Loc, [](Module *) {},
800 [&](ArrayRef<Module *> Path, Module *Conflict, StringRef Message) {
801 // FIXME: Include the path in the diagnostic.
802 // FIXME: Include the import location for the conflicting module.
803 Diag(ModuleImportLoc, diag::warn_module_conflict)
804 << Path[0]->getFullModuleName()
805 << Conflict->getFullModuleName()
806 << Message;
807 });
808
809 // Add this module to the imports list of the currently-built submodule.
Richard Smithdbbc5232015-05-14 02:25:44 +0000810 if (!BuildingSubmoduleStack.empty() && M != BuildingSubmoduleStack.back().M)
Richard Smith38477db2015-05-02 00:45:56 +0000811 BuildingSubmoduleStack.back().M->Imports.insert(M);
Richard Smitha7e2cc62015-05-01 01:53:09 +0000812}
813
Andy Gibbs58905d22012-11-17 19:15:38 +0000814bool Preprocessor::FinishLexStringLiteral(Token &Result, std::string &String,
Andy Gibbsa8df57a2012-11-17 19:16:52 +0000815 const char *DiagnosticTag,
Andy Gibbs58905d22012-11-17 19:15:38 +0000816 bool AllowMacroExpansion) {
817 // We need at least one string literal.
818 if (Result.isNot(tok::string_literal)) {
Andy Gibbsa8df57a2012-11-17 19:16:52 +0000819 Diag(Result, diag::err_expected_string_literal)
820 << /*Source='in...'*/0 << DiagnosticTag;
Andy Gibbs58905d22012-11-17 19:15:38 +0000821 return false;
822 }
823
824 // Lex string literal tokens, optionally with macro expansion.
825 SmallVector<Token, 4> StrToks;
826 do {
827 StrToks.push_back(Result);
828
829 if (Result.hasUDSuffix())
830 Diag(Result, diag::err_invalid_string_udl);
831
832 if (AllowMacroExpansion)
833 Lex(Result);
834 else
835 LexUnexpandedToken(Result);
836 } while (Result.is(tok::string_literal));
837
838 // Concatenate and parse the strings.
Craig Topper9d5583e2014-06-26 04:58:39 +0000839 StringLiteralParser Literal(StrToks, *this);
Andy Gibbs58905d22012-11-17 19:15:38 +0000840 assert(Literal.isAscii() && "Didn't allow wide strings in");
841
842 if (Literal.hadError)
843 return false;
844
845 if (Literal.Pascal) {
Andy Gibbsa8df57a2012-11-17 19:16:52 +0000846 Diag(StrToks[0].getLocation(), diag::err_expected_string_literal)
847 << /*Source='in...'*/0 << DiagnosticTag;
Andy Gibbs58905d22012-11-17 19:15:38 +0000848 return false;
849 }
850
851 String = Literal.GetString();
852 return true;
853}
854
Reid Klecknerc0dca6d2014-02-12 23:50:26 +0000855bool Preprocessor::parseSimpleIntegerLiteral(Token &Tok, uint64_t &Value) {
856 assert(Tok.is(tok::numeric_constant));
857 SmallString<8> IntegerBuffer;
858 bool NumberInvalid = false;
859 StringRef Spelling = getSpelling(Tok, IntegerBuffer, &NumberInvalid);
860 if (NumberInvalid)
861 return false;
862 NumericLiteralParser Literal(Spelling, Tok.getLocation(), *this);
863 if (Literal.hadError || !Literal.isIntegerLiteral() || Literal.hasUDSuffix())
864 return false;
865 llvm::APInt APVal(64, 0);
866 if (Literal.GetIntegerValue(APVal))
867 return false;
868 Lex(Tok);
869 Value = APVal.getLimitedValue();
870 return true;
871}
872
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000873void Preprocessor::addCommentHandler(CommentHandler *Handler) {
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000874 assert(Handler && "NULL comment handler");
875 assert(std::find(CommentHandlers.begin(), CommentHandlers.end(), Handler) ==
876 CommentHandlers.end() && "Comment handler already registered");
877 CommentHandlers.push_back(Handler);
878}
879
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000880void Preprocessor::removeCommentHandler(CommentHandler *Handler) {
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000881 std::vector<CommentHandler *>::iterator Pos
882 = std::find(CommentHandlers.begin(), CommentHandlers.end(), Handler);
883 assert(Pos != CommentHandlers.end() && "Comment handler not registered");
884 CommentHandlers.erase(Pos);
885}
886
Chris Lattner87d02082010-01-18 22:35:47 +0000887bool Preprocessor::HandleComment(Token &result, SourceRange Comment) {
888 bool AnyPendingTokens = false;
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000889 for (std::vector<CommentHandler *>::iterator H = CommentHandlers.begin(),
890 HEnd = CommentHandlers.end();
Chris Lattner87d02082010-01-18 22:35:47 +0000891 H != HEnd; ++H) {
892 if ((*H)->HandleComment(*this, Comment))
893 AnyPendingTokens = true;
894 }
895 if (!AnyPendingTokens || getCommentRetentionState())
896 return false;
897 Lex(result);
898 return true;
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000899}
900
Angel Garcia Gomez637d1e62015-10-20 13:23:58 +0000901ModuleLoader::~ModuleLoader() { }
Douglas Gregor08142532011-08-26 23:56:07 +0000902
Angel Garcia Gomez637d1e62015-10-20 13:23:58 +0000903CommentHandler::~CommentHandler() { }
Douglas Gregor7f6d60d2010-03-19 16:15:56 +0000904
Angel Garcia Gomez637d1e62015-10-20 13:23:58 +0000905CodeCompletionHandler::~CodeCompletionHandler() { }
Douglas Gregor3a7ad252010-08-24 19:08:16 +0000906
Argyrios Kyrtzidisf3d587e2012-12-04 07:27:05 +0000907void Preprocessor::createPreprocessingRecord() {
Douglas Gregor7f6d60d2010-03-19 16:15:56 +0000908 if (Record)
909 return;
910
Argyrios Kyrtzidisf3d587e2012-12-04 07:27:05 +0000911 Record = new PreprocessingRecord(getSourceManager());
Craig Topperb8a70532014-09-10 04:53:53 +0000912 addPPCallbacks(std::unique_ptr<PPCallbacks>(Record));
Douglas Gregor7f6d60d2010-03-19 16:15:56 +0000913}