blob: dce8c1efda23d477652d24a81e54784fd842a460 [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"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000046#include "llvm/ADT/APInt.h"
47#include "llvm/ADT/DenseMap.h"
Chandler Carruth5553d0d2014-01-07 11:51:46 +000048#include "llvm/ADT/SmallString.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000049#include "llvm/ADT/SmallVector.h"
50#include "llvm/ADT/STLExtras.h"
51#include "llvm/ADT/StringRef.h"
Mehdi Amini9670f842016-07-18 19:02:11 +000052#include "llvm/ADT/StringSwitch.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000053#include "llvm/Support/Capacity.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000054#include "llvm/Support/ErrorHandling.h"
Chris Lattner8a7003c2007-07-16 06:48:38 +000055#include "llvm/Support/MemoryBuffer.h"
Benjamin Kramer89b422c2009-08-23 12:08:50 +000056#include "llvm/Support/raw_ostream.h"
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000057#include <algorithm>
58#include <cassert>
59#include <memory>
60#include <string>
Benjamin Kramercfeacf52016-05-27 14:27:13 +000061#include <utility>
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000062#include <vector>
63
Chris Lattner22eb9722006-06-18 05:43:12 +000064using namespace clang;
65
John Brawn4d79ec72016-08-05 11:01:08 +000066LLVM_INSTANTIATE_REGISTRY(PragmaHandlerRegistry)
NAKAMURA Takumicacd94e2016-04-04 15:30:44 +000067
Chris Lattner22eb9722006-06-18 05:43:12 +000068//===----------------------------------------------------------------------===//
Angel Garcia Gomez637d1e62015-10-20 13:23:58 +000069ExternalPreprocessorSource::~ExternalPreprocessorSource() { }
Chris Lattner22eb9722006-06-18 05:43:12 +000070
David Blaikiee3041682017-01-05 19:11:36 +000071Preprocessor::Preprocessor(std::shared_ptr<PreprocessorOptions> PPOpts,
Douglas Gregor1452ff12012-10-24 17:46:57 +000072 DiagnosticsEngine &diags, LangOptions &opts,
Duncan P. N. Exon Smith030d7d62017-03-20 17:58:26 +000073 SourceManager &SM, MemoryBufferCache &PCMCache,
74 HeaderSearch &Headers, ModuleLoader &TheModuleLoader,
David Blaikie687cd952013-01-16 23:13:36 +000075 IdentifierInfoLookup *IILookup, bool OwnsHeaders,
Alp Toker1ae02f62014-05-02 03:43:30 +000076 TranslationUnitKind TUKind)
Benjamin Kramercfeacf52016-05-27 14:27:13 +000077 : PPOpts(std::move(PPOpts)), Diags(&diags), LangOpts(opts), Target(nullptr),
Artem Belevichb5bc9232015-09-22 17:23:22 +000078 AuxTarget(nullptr), FileMgr(Headers.getFileMgr()), SourceMgr(SM),
Duncan P. N. Exon Smith030d7d62017-03-20 17:58:26 +000079 PCMCache(PCMCache), ScratchBuf(new ScratchBuffer(SourceMgr)),
80 HeaderInfo(Headers), TheModuleLoader(TheModuleLoader),
81 ExternalSource(nullptr), Identifiers(opts, IILookup),
Craig Topperbe250302014-09-12 05:19:24 +000082 PragmaHandlers(new PragmaNamespace(StringRef())),
Artem Belevichb5bc9232015-09-22 17:23:22 +000083 IncrementalProcessing(false), TUKind(TUKind), CodeComplete(nullptr),
84 CodeCompletionFile(nullptr), CodeCompletionOffset(0),
85 LastTokenWasAt(false), ModuleImportExpectsIdentifier(false),
Eugene Zelenkoe95e7d52016-09-07 21:53:17 +000086 CodeCompletionReached(false), CodeCompletionII(nullptr),
87 MainFileDir(nullptr), SkipMainFilePreamble(0, true), CurPPLexer(nullptr),
Richard Smithd1386302017-05-04 00:29:54 +000088 CurDirLookup(nullptr), CurLexerKind(CLK_Lexer),
89 CurLexerSubmodule(nullptr), Callbacks(nullptr),
90 CurSubmoduleState(&NullSubmoduleState), MacroArgCache(nullptr),
Richard Smith3f6dd7a2017-05-12 23:40:52 +000091 Record(nullptr), MIChainHead(nullptr) {
Daniel Dunbar0c6c9302009-11-11 21:44:21 +000092 OwnsHeaderSearch = OwnsHeaders;
Douglas Gregor83297df2011-09-01 23:39:15 +000093
Douglas Gregor83297df2011-09-01 23:39:15 +000094 CounterValue = 0; // __COUNTER__ starts at 0.
95
96 // Clear stats.
97 NumDirectives = NumDefined = NumUndefined = NumPragma = 0;
98 NumIf = NumElse = NumEndif = 0;
99 NumEnteredSourceFiles = 0;
100 NumMacroExpanded = NumFnMacroExpanded = NumBuiltinMacroExpanded = 0;
101 NumFastMacroExpanded = NumTokenPaste = NumFastTokenPaste = 0;
102 MaxIncludeStackDepth = 0;
103 NumSkipped = 0;
104
105 // Default to discarding comments.
106 KeepComments = false;
107 KeepMacroComments = false;
108 SuppressIncludeNotFoundError = false;
109
110 // Macro expansion is enabled.
111 DisableMacroExpansion = false;
David Blaikied5321242012-06-06 18:52:13 +0000112 MacroExpansionInDirectivesOverride = false;
Douglas Gregor83297df2011-09-01 23:39:15 +0000113 InMacroArgs = false;
Argyrios Kyrtzidisf1b64c62012-04-03 16:47:40 +0000114 InMacroArgPreExpansion = false;
Douglas Gregor83297df2011-09-01 23:39:15 +0000115 NumCachedTokenLexers = 0;
Jordan Rosede1a2922012-06-08 18:06:21 +0000116 PragmasEnabled = true;
Eric Christopher5e4696d2013-01-16 20:09:36 +0000117 ParsingIfOrElifDirective = false;
Jordan Rose324ec422013-01-31 19:26:01 +0000118 PreprocessedOutput = false;
Jordan Rosede1a2922012-06-08 18:06:21 +0000119
Douglas Gregor83297df2011-09-01 23:39:15 +0000120 CachedLexPos = 0;
Eric Christopher5e4696d2013-01-16 20:09:36 +0000121
Douglas Gregor83297df2011-09-01 23:39:15 +0000122 // We haven't read anything from the external source.
123 ReadMacrosFromExternalSource = false;
124
Douglas Gregor83297df2011-09-01 23:39:15 +0000125 // "Poison" __VA_ARGS__, which can only appear in the expansion of a macro.
126 // This gets unpoisoned where it is allowed.
127 (Ident__VA_ARGS__ = getIdentifierInfo("__VA_ARGS__"))->setIsPoisoned();
128 SetPoisonReason(Ident__VA_ARGS__,diag::ext_pp_bad_vaargs_use);
129
130 // Initialize the pragma handlers.
Douglas Gregor83297df2011-09-01 23:39:15 +0000131 RegisterBuiltinPragmas();
132
133 // Initialize builtin macros like __LINE__ and friends.
134 RegisterBuiltinMacros();
135
David Blaikiebbafb8a2012-03-11 07:00:24 +0000136 if(LangOpts.Borland) {
Douglas Gregor83297df2011-09-01 23:39:15 +0000137 Ident__exception_info = getIdentifierInfo("_exception_info");
138 Ident___exception_info = getIdentifierInfo("__exception_info");
139 Ident_GetExceptionInfo = getIdentifierInfo("GetExceptionInformation");
140 Ident__exception_code = getIdentifierInfo("_exception_code");
141 Ident___exception_code = getIdentifierInfo("__exception_code");
142 Ident_GetExceptionCode = getIdentifierInfo("GetExceptionCode");
143 Ident__abnormal_termination = getIdentifierInfo("_abnormal_termination");
144 Ident___abnormal_termination = getIdentifierInfo("__abnormal_termination");
145 Ident_AbnormalTermination = getIdentifierInfo("AbnormalTermination");
146 } else {
Craig Topperd2d442c2014-05-17 23:10:59 +0000147 Ident__exception_info = Ident__exception_code = nullptr;
148 Ident__abnormal_termination = Ident___exception_info = nullptr;
149 Ident___exception_code = Ident___abnormal_termination = nullptr;
150 Ident_GetExceptionInfo = Ident_GetExceptionCode = nullptr;
151 Ident_AbnormalTermination = nullptr;
Douglas Gregor89929282012-01-30 06:01:29 +0000152 }
Argyrios Kyrtzidis3c9aaf12012-06-02 18:08:09 +0000153}
154
155Preprocessor::~Preprocessor() {
156 assert(BacktrackPositions.empty() && "EnableBacktrack/Backtrack imbalance!");
157
Benjamin Kramer329c5962014-03-15 16:40:40 +0000158 IncludeMacroStack.clear();
Argyrios Kyrtzidis3c9aaf12012-06-02 18:08:09 +0000159
Richard Smith73a29662014-07-24 03:25:00 +0000160 // Destroy any macro definitions.
161 while (MacroInfoChain *I = MIChainHead) {
162 MIChainHead = I->Next;
163 I->~MacroInfoChain();
164 }
Argyrios Kyrtzidis3c9aaf12012-06-02 18:08:09 +0000165
166 // Free any cached macro expanders.
Nico Weber5f5b9412014-05-09 18:09:42 +0000167 // This populates MacroArgCache, so all TokenLexers need to be destroyed
168 // before the code below that frees up the MacroArgCache list.
David Blaikie6d5038c2014-08-29 19:36:52 +0000169 std::fill(TokenLexerCache, TokenLexerCache + NumCachedTokenLexers, nullptr);
Nico Weber5f5b9412014-05-09 18:09:42 +0000170 CurTokenLexer.reset();
Argyrios Kyrtzidis3c9aaf12012-06-02 18:08:09 +0000171
172 // Free any cached MacroArgs.
Nico Weber5f5b9412014-05-09 18:09:42 +0000173 for (MacroArgs *ArgList = MacroArgCache; ArgList;)
Argyrios Kyrtzidis3c9aaf12012-06-02 18:08:09 +0000174 ArgList = ArgList->deallocate();
175
Argyrios Kyrtzidis3c9aaf12012-06-02 18:08:09 +0000176 // Delete the header search info, if we own it.
177 if (OwnsHeaderSearch)
178 delete &HeaderInfo;
Argyrios Kyrtzidis3c9aaf12012-06-02 18:08:09 +0000179}
180
Artem Belevichb5bc9232015-09-22 17:23:22 +0000181void Preprocessor::Initialize(const TargetInfo &Target,
182 const TargetInfo *AuxTarget) {
Argyrios Kyrtzidis3c9aaf12012-06-02 18:08:09 +0000183 assert((!this->Target || this->Target == &Target) &&
184 "Invalid override of target information");
185 this->Target = &Target;
Artem Belevichb5bc9232015-09-22 17:23:22 +0000186
187 assert((!this->AuxTarget || this->AuxTarget == AuxTarget) &&
188 "Invalid override of aux target information.");
189 this->AuxTarget = AuxTarget;
190
Argyrios Kyrtzidis3c9aaf12012-06-02 18:08:09 +0000191 // Initialize information about built-ins.
Artem Belevichb5bc9232015-09-22 17:23:22 +0000192 BuiltinInfo.InitializeTarget(Target, AuxTarget);
Douglas Gregor89929282012-01-30 06:01:29 +0000193 HeaderInfo.setTarget(Target);
Douglas Gregor83297df2011-09-01 23:39:15 +0000194}
195
Ted Kremenekeeccb302014-08-27 15:14:15 +0000196void Preprocessor::InitializeForModelFile() {
197 NumEnteredSourceFiles = 0;
198
199 // Reset pragmas
David Blaikie9f0af9d2014-09-15 21:31:42 +0000200 PragmaHandlersBackup = std::move(PragmaHandlers);
Craig Topperbe250302014-09-12 05:19:24 +0000201 PragmaHandlers = llvm::make_unique<PragmaNamespace>(StringRef());
Ted Kremenekeeccb302014-08-27 15:14:15 +0000202 RegisterBuiltinPragmas();
203
204 // Reset PredefinesFileID
205 PredefinesFileID = FileID();
206}
207
208void Preprocessor::FinalizeForModelFile() {
209 NumEnteredSourceFiles = 1;
210
David Blaikie9f0af9d2014-09-15 21:31:42 +0000211 PragmaHandlers = std::move(PragmaHandlersBackup);
Ted Kremenekeeccb302014-08-27 15:14:15 +0000212}
213
Ted Kremeneka5c2c272009-02-12 03:26:59 +0000214void Preprocessor::setPTHManager(PTHManager* pm) {
215 PTH.reset(pm);
Douglas Gregord2eb58a2009-10-16 18:18:30 +0000216 FileMgr.addStatCache(PTH->createStatCache());
Ted Kremeneka5c2c272009-02-12 03:26:59 +0000217}
218
Chris Lattner146762e2007-07-20 16:59:19 +0000219void Preprocessor::DumpToken(const Token &Tok, bool DumpFlags) const {
Benjamin Kramer89b422c2009-08-23 12:08:50 +0000220 llvm::errs() << tok::getTokenName(Tok.getKind()) << " '"
221 << getSpelling(Tok) << "'";
Mike Stump11289f42009-09-09 15:08:12 +0000222
Chris Lattnerd01e2912006-06-18 16:22:51 +0000223 if (!DumpFlags) return;
Mike Stump11289f42009-09-09 15:08:12 +0000224
Benjamin Kramer89b422c2009-08-23 12:08:50 +0000225 llvm::errs() << "\t";
Chris Lattnerd01e2912006-06-18 16:22:51 +0000226 if (Tok.isAtStartOfLine())
Benjamin Kramer89b422c2009-08-23 12:08:50 +0000227 llvm::errs() << " [StartOfLine]";
Chris Lattnerd01e2912006-06-18 16:22:51 +0000228 if (Tok.hasLeadingSpace())
Benjamin Kramer89b422c2009-08-23 12:08:50 +0000229 llvm::errs() << " [LeadingSpace]";
Chris Lattner6e4bf522006-07-27 06:59:25 +0000230 if (Tok.isExpandDisabled())
Benjamin Kramer89b422c2009-08-23 12:08:50 +0000231 llvm::errs() << " [ExpandDisabled]";
Chris Lattnerd01e2912006-06-18 16:22:51 +0000232 if (Tok.needsCleaning()) {
Chris Lattner50b497e2006-06-18 16:32:35 +0000233 const char *Start = SourceMgr.getCharacterData(Tok.getLocation());
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000234 llvm::errs() << " [UnClean='" << StringRef(Start, Tok.getLength())
Benjamin Kramer89b422c2009-08-23 12:08:50 +0000235 << "']";
Chris Lattnerd01e2912006-06-18 16:22:51 +0000236 }
Mike Stump11289f42009-09-09 15:08:12 +0000237
Benjamin Kramer89b422c2009-08-23 12:08:50 +0000238 llvm::errs() << "\tLoc=<";
Chris Lattner615315f2007-12-09 20:31:55 +0000239 DumpLocation(Tok.getLocation());
Benjamin Kramer89b422c2009-08-23 12:08:50 +0000240 llvm::errs() << ">";
Chris Lattner615315f2007-12-09 20:31:55 +0000241}
242
243void Preprocessor::DumpLocation(SourceLocation Loc) const {
Chris Lattnerf1ca7d32009-01-27 07:57:44 +0000244 Loc.dump(SourceMgr);
Chris Lattnerd01e2912006-06-18 16:22:51 +0000245}
246
247void Preprocessor::DumpMacro(const MacroInfo &MI) const {
Benjamin Kramer89b422c2009-08-23 12:08:50 +0000248 llvm::errs() << "MACRO: ";
Chris Lattnerd01e2912006-06-18 16:22:51 +0000249 for (unsigned i = 0, e = MI.getNumTokens(); i != e; ++i) {
250 DumpToken(MI.getReplacementToken(i));
Benjamin Kramer89b422c2009-08-23 12:08:50 +0000251 llvm::errs() << " ";
Chris Lattnerd01e2912006-06-18 16:22:51 +0000252 }
Benjamin Kramer89b422c2009-08-23 12:08:50 +0000253 llvm::errs() << "\n";
Chris Lattnerd01e2912006-06-18 16:22:51 +0000254}
255
Chris Lattner22eb9722006-06-18 05:43:12 +0000256void Preprocessor::PrintStats() {
Benjamin Kramer89b422c2009-08-23 12:08:50 +0000257 llvm::errs() << "\n*** Preprocessor Stats:\n";
258 llvm::errs() << NumDirectives << " directives found:\n";
259 llvm::errs() << " " << NumDefined << " #define.\n";
260 llvm::errs() << " " << NumUndefined << " #undef.\n";
261 llvm::errs() << " #include/#include_next/#import:\n";
262 llvm::errs() << " " << NumEnteredSourceFiles << " source files entered.\n";
263 llvm::errs() << " " << MaxIncludeStackDepth << " max include stack depth\n";
264 llvm::errs() << " " << NumIf << " #if/#ifndef/#ifdef.\n";
265 llvm::errs() << " " << NumElse << " #else/#elif.\n";
266 llvm::errs() << " " << NumEndif << " #endif.\n";
267 llvm::errs() << " " << NumPragma << " #pragma.\n";
268 llvm::errs() << NumSkipped << " #if/#ifndef#ifdef regions skipped\n";
Chris Lattner22eb9722006-06-18 05:43:12 +0000269
Benjamin Kramer89b422c2009-08-23 12:08:50 +0000270 llvm::errs() << NumMacroExpanded << "/" << NumFnMacroExpanded << "/"
Ted Kremeneka0a3e9b2008-01-14 16:44:48 +0000271 << NumBuiltinMacroExpanded << " obj/fn/builtin macros expanded, "
272 << NumFastMacroExpanded << " on the fast path.\n";
Benjamin Kramer89b422c2009-08-23 12:08:50 +0000273 llvm::errs() << (NumFastTokenPaste+NumTokenPaste)
Ted Kremeneka0a3e9b2008-01-14 16:44:48 +0000274 << " token paste (##) operations performed, "
275 << NumFastTokenPaste << " on the fast path.\n";
Alexander Kornienko199cd942012-08-13 10:46:42 +0000276
277 llvm::errs() << "\nPreprocessor Memory: " << getTotalMemory() << "B total";
278
279 llvm::errs() << "\n BumpPtr: " << BP.getTotalMemory();
280 llvm::errs() << "\n Macro Expanded Tokens: "
281 << llvm::capacity_in_bytes(MacroExpandedTokens);
282 llvm::errs() << "\n Predefines Buffer: " << Predefines.capacity();
Richard Smith04765ae2015-05-21 01:20:10 +0000283 // FIXME: List information for all submodules.
284 llvm::errs() << "\n Macros: "
285 << llvm::capacity_in_bytes(CurSubmoduleState->Macros);
Alexander Kornienko199cd942012-08-13 10:46:42 +0000286 llvm::errs() << "\n #pragma push_macro Info: "
287 << llvm::capacity_in_bytes(PragmaPushMacroInfo);
288 llvm::errs() << "\n Poison Reasons: "
289 << llvm::capacity_in_bytes(PoisonReasons);
290 llvm::errs() << "\n Comment Handlers: "
291 << llvm::capacity_in_bytes(CommentHandlers) << "\n";
Chris Lattner22eb9722006-06-18 05:43:12 +0000292}
293
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +0000294Preprocessor::macro_iterator
295Preprocessor::macro_begin(bool IncludeExternalMacros) const {
296 if (IncludeExternalMacros && ExternalSource &&
Douglas Gregor9882a5a2010-01-04 19:18:44 +0000297 !ReadMacrosFromExternalSource) {
298 ReadMacrosFromExternalSource = true;
299 ExternalSource->ReadDefinedMacros();
300 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +0000301
Jordan Rosea46bfa62015-06-24 19:27:02 +0000302 // Make sure we cover all macros in visible modules.
303 for (const ModuleMacro &Macro : ModuleMacros)
304 CurSubmoduleState->Macros.insert(std::make_pair(Macro.II, MacroState()));
305
Richard Smith04765ae2015-05-21 01:20:10 +0000306 return CurSubmoduleState->Macros.begin();
Douglas Gregor9882a5a2010-01-04 19:18:44 +0000307}
308
Argyrios Kyrtzidise379ee32011-06-29 22:20:04 +0000309size_t Preprocessor::getTotalMemory() const {
Ted Kremenek182543a2011-07-26 21:17:24 +0000310 return BP.getTotalMemory()
Ted Kremenek8b77fe72011-07-27 18:41:23 +0000311 + llvm::capacity_in_bytes(MacroExpandedTokens)
Ted Kremenek182543a2011-07-26 21:17:24 +0000312 + Predefines.capacity() /* Predefines buffer. */
Richard Smith04765ae2015-05-21 01:20:10 +0000313 // FIXME: Include sizes from all submodules, and include MacroInfo sizes,
314 // and ModuleMacros.
315 + llvm::capacity_in_bytes(CurSubmoduleState->Macros)
Ted Kremenek8b77fe72011-07-27 18:41:23 +0000316 + llvm::capacity_in_bytes(PragmaPushMacroInfo)
317 + llvm::capacity_in_bytes(PoisonReasons)
318 + llvm::capacity_in_bytes(CommentHandlers);
Argyrios Kyrtzidise379ee32011-06-29 22:20:04 +0000319}
320
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +0000321Preprocessor::macro_iterator
322Preprocessor::macro_end(bool IncludeExternalMacros) const {
323 if (IncludeExternalMacros && ExternalSource &&
Douglas Gregor9882a5a2010-01-04 19:18:44 +0000324 !ReadMacrosFromExternalSource) {
325 ReadMacrosFromExternalSource = true;
326 ExternalSource->ReadDefinedMacros();
327 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +0000328
Richard Smith04765ae2015-05-21 01:20:10 +0000329 return CurSubmoduleState->Macros.end();
Douglas Gregor9882a5a2010-01-04 19:18:44 +0000330}
331
Dmitri Gribenko6743e042012-09-29 11:40:46 +0000332/// \brief Compares macro tokens with a specified token value sequence.
333static bool MacroDefinitionEquals(const MacroInfo *MI,
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000334 ArrayRef<TokenValue> Tokens) {
Dmitri Gribenko6743e042012-09-29 11:40:46 +0000335 return Tokens.size() == MI->getNumTokens() &&
336 std::equal(Tokens.begin(), Tokens.end(), MI->tokens_begin());
337}
338
339StringRef Preprocessor::getLastMacroWithSpelling(
340 SourceLocation Loc,
341 ArrayRef<TokenValue> Tokens) const {
342 SourceLocation BestLocation;
343 StringRef BestSpelling;
344 for (Preprocessor::macro_iterator I = macro_begin(), E = macro_end();
345 I != E; ++I) {
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +0000346 const MacroDirective::DefInfo
Richard Smithb8b2ed62015-04-23 18:18:26 +0000347 Def = I->second.findDirectiveAtLoc(Loc, SourceMgr);
Argyrios Kyrtzidis5c585252015-03-04 16:03:07 +0000348 if (!Def || !Def.getMacroInfo())
349 continue;
350 if (!Def.getMacroInfo()->isObjectLike())
Dmitri Gribenko6743e042012-09-29 11:40:46 +0000351 continue;
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +0000352 if (!MacroDefinitionEquals(Def.getMacroInfo(), Tokens))
Dmitri Gribenko6743e042012-09-29 11:40:46 +0000353 continue;
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +0000354 SourceLocation Location = Def.getLocation();
Dmitri Gribenko6743e042012-09-29 11:40:46 +0000355 // Choose the macro defined latest.
356 if (BestLocation.isInvalid() ||
357 (Location.isValid() &&
358 SourceMgr.isBeforeInTranslationUnit(BestLocation, Location))) {
359 BestLocation = Location;
360 BestSpelling = I->first->getName();
361 }
362 }
363 return BestSpelling;
364}
365
Douglas Gregor8d76cca2012-01-04 06:20:15 +0000366void Preprocessor::recomputeCurLexerKind() {
367 if (CurLexer)
368 CurLexerKind = CLK_Lexer;
369 else if (CurPTHLexer)
370 CurLexerKind = CLK_PTHLexer;
371 else if (CurTokenLexer)
372 CurLexerKind = CLK_TokenLexer;
373 else
374 CurLexerKind = CLK_CachingLexer;
375}
376
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +0000377bool Preprocessor::SetCodeCompletionPoint(const FileEntry *File,
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +0000378 unsigned CompleteLine,
379 unsigned CompleteColumn) {
380 assert(File);
381 assert(CompleteLine && CompleteColumn && "Starts from 1:1");
382 assert(!CodeCompletionFile && "Already set");
383
Douglas Gregor53ad6b92009-12-02 06:49:09 +0000384 using llvm::MemoryBuffer;
385
Douglas Gregor53ad6b92009-12-02 06:49:09 +0000386 // Load the actual file's contents.
Douglas Gregor26266da2010-03-16 19:49:24 +0000387 bool Invalid = false;
388 const MemoryBuffer *Buffer = SourceMgr.getMemoryBufferForFile(File, &Invalid);
389 if (Invalid)
Douglas Gregor53ad6b92009-12-02 06:49:09 +0000390 return true;
391
392 // Find the byte position of the truncation point.
393 const char *Position = Buffer->getBufferStart();
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +0000394 for (unsigned Line = 1; Line < CompleteLine; ++Line) {
Douglas Gregor53ad6b92009-12-02 06:49:09 +0000395 for (; *Position; ++Position) {
396 if (*Position != '\r' && *Position != '\n')
397 continue;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +0000398
Douglas Gregor53ad6b92009-12-02 06:49:09 +0000399 // Eat \r\n or \n\r as a single line.
400 if ((Position[1] == '\r' || Position[1] == '\n') &&
401 Position[0] != Position[1])
402 ++Position;
403 ++Position;
404 break;
405 }
406 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +0000407
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +0000408 Position += CompleteColumn - 1;
Argyrios Kyrtzidisee301f92014-10-18 06:23:50 +0000409
410 // If pointing inside the preamble, adjust the position at the beginning of
411 // the file after the preamble.
412 if (SkipMainFilePreamble.first &&
413 SourceMgr.getFileEntryForID(SourceMgr.getMainFileID()) == File) {
414 if (Position - Buffer->getBufferStart() < SkipMainFilePreamble.first)
415 Position = Buffer->getBufferStart() + SkipMainFilePreamble.first;
416 }
417
Argyrios Kyrtzidise62d6822014-10-18 06:19:36 +0000418 if (Position > Buffer->getBufferEnd())
419 Position = Buffer->getBufferEnd();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +0000420
Argyrios Kyrtzidise62d6822014-10-18 06:19:36 +0000421 CodeCompletionFile = File;
422 CodeCompletionOffset = Position - Buffer->getBufferStart();
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +0000423
Argyrios Kyrtzidise62d6822014-10-18 06:19:36 +0000424 std::unique_ptr<MemoryBuffer> NewBuffer =
425 MemoryBuffer::getNewUninitMemBuffer(Buffer->getBufferSize() + 1,
426 Buffer->getBufferIdentifier());
427 char *NewBuf = const_cast<char*>(NewBuffer->getBufferStart());
428 char *NewPos = std::copy(Buffer->getBufferStart(), Position, NewBuf);
429 *NewPos = '\0';
430 std::copy(Position, Buffer->getBufferEnd(), NewPos+1);
431 SourceMgr.overrideFileContents(File, std::move(NewBuffer));
Douglas Gregor53ad6b92009-12-02 06:49:09 +0000432
433 return false;
434}
435
Douglas Gregor11583702010-08-25 17:04:25 +0000436void Preprocessor::CodeCompleteNaturalLanguage() {
Douglas Gregor11583702010-08-25 17:04:25 +0000437 if (CodeComplete)
438 CodeComplete->CodeCompleteNaturalLanguage();
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +0000439 setCodeCompletionReached();
Douglas Gregor11583702010-08-25 17:04:25 +0000440}
441
Benjamin Kramera197fb62010-02-27 17:05:45 +0000442/// getSpelling - This method is used to get the spelling of a token into a
443/// SmallVector. Note that the returned StringRef may not point to the
444/// supplied buffer if a copy can be avoided.
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000445StringRef Preprocessor::getSpelling(const Token &Tok,
446 SmallVectorImpl<char> &Buffer,
Douglas Gregor7bda4b82010-03-16 05:20:39 +0000447 bool *Invalid) const {
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +0000448 // NOTE: this has to be checked *before* testing for an IdentifierInfo.
Jordan Rose7f43ddd2013-01-24 20:50:46 +0000449 if (Tok.isNot(tok::raw_identifier) && !Tok.hasUCN()) {
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +0000450 // Try the fast path.
451 if (const IdentifierInfo *II = Tok.getIdentifierInfo())
452 return II->getName();
453 }
Benjamin Kramera197fb62010-02-27 17:05:45 +0000454
455 // Resize the buffer if we need to copy into it.
456 if (Tok.needsCleaning())
457 Buffer.resize(Tok.getLength());
458
459 const char *Ptr = Buffer.data();
Douglas Gregor7bda4b82010-03-16 05:20:39 +0000460 unsigned Len = getSpelling(Tok, Ptr, Invalid);
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000461 return StringRef(Ptr, Len);
Benjamin Kramera197fb62010-02-27 17:05:45 +0000462}
463
Chris Lattnerb94ec7b2006-07-14 06:54:10 +0000464/// CreateString - Plop the specified string into a scratch buffer and return a
465/// location for it. If specified, the source location provides a source
466/// location for the token.
Dmitri Gribenkob8e9e752012-09-24 21:07:17 +0000467void Preprocessor::CreateString(StringRef Str, Token &Tok,
Abramo Bagnarae398e602011-10-03 18:39:03 +0000468 SourceLocation ExpansionLocStart,
469 SourceLocation ExpansionLocEnd) {
Dmitri Gribenkob8e9e752012-09-24 21:07:17 +0000470 Tok.setLength(Str.size());
Mike Stump11289f42009-09-09 15:08:12 +0000471
Chris Lattner5a7971e2009-01-26 19:29:26 +0000472 const char *DestPtr;
Dmitri Gribenkob8e9e752012-09-24 21:07:17 +0000473 SourceLocation Loc = ScratchBuf->getToken(Str.data(), Str.size(), DestPtr);
Mike Stump11289f42009-09-09 15:08:12 +0000474
Abramo Bagnarae398e602011-10-03 18:39:03 +0000475 if (ExpansionLocStart.isValid())
476 Loc = SourceMgr.createExpansionLoc(Loc, ExpansionLocStart,
Dmitri Gribenkob8e9e752012-09-24 21:07:17 +0000477 ExpansionLocEnd, Str.size());
Chris Lattner5a7971e2009-01-26 19:29:26 +0000478 Tok.setLocation(Loc);
Mike Stump11289f42009-09-09 15:08:12 +0000479
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +0000480 // If this is a raw identifier or a literal token, set the pointer data.
481 if (Tok.is(tok::raw_identifier))
482 Tok.setRawIdentifierData(DestPtr);
483 else if (Tok.isLiteral())
Chris Lattner5a7971e2009-01-26 19:29:26 +0000484 Tok.setLiteralData(DestPtr);
Chris Lattnerb94ec7b2006-07-14 06:54:10 +0000485}
486
Douglas Gregor2b82c2a2011-12-02 01:47:07 +0000487Module *Preprocessor::getCurrentModule() {
Richard Smithbbcc9f02016-08-26 00:14:38 +0000488 if (!getLangOpts().isCompilingModule())
Craig Topperd2d442c2014-05-17 23:10:59 +0000489 return nullptr;
490
David Blaikiebbafb8a2012-03-11 07:00:24 +0000491 return getHeaderSearchInfo().lookupModule(getLangOpts().CurrentModule);
Douglas Gregor2b82c2a2011-12-02 01:47:07 +0000492}
Chris Lattner8a7003c2007-07-16 06:48:38 +0000493
Chris Lattner1f1b0db2007-10-09 22:10:18 +0000494//===----------------------------------------------------------------------===//
495// Preprocessor Initialization Methods
496//===----------------------------------------------------------------------===//
497
Chris Lattner1f1b0db2007-10-09 22:10:18 +0000498/// EnterMainSourceFile - Enter the specified FileID as the main source file,
Nate Begemanf7c3ff62008-01-07 04:01:26 +0000499/// which implicitly adds the builtin defines etc.
Chris Lattnerfb24a3a2010-04-20 20:35:58 +0000500void Preprocessor::EnterMainSourceFile() {
Chris Lattner9ef847b2009-02-13 19:33:24 +0000501 // We do not allow the preprocessor to reenter the main file. Doing so will
502 // cause FileID's to accumulate information from both runs (e.g. #line
503 // information) and predefined macros aren't guaranteed to be set properly.
504 assert(NumEnteredSourceFiles == 0 && "Cannot reenter the main file!");
Chris Lattnerd32480d2009-01-17 06:22:33 +0000505 FileID MainFileID = SourceMgr.getMainFileID();
Mike Stump11289f42009-09-09 15:08:12 +0000506
Argyrios Kyrtzidis9afd4492012-01-05 21:36:25 +0000507 // If MainFileID is loaded it means we loaded an AST file, no need to enter
508 // a main file.
509 if (!SourceMgr.isLoadedFileID(MainFileID)) {
510 // Enter the main file source buffer.
Craig Topperd2d442c2014-05-17 23:10:59 +0000511 EnterSourceFile(MainFileID, nullptr, SourceLocation());
512
Argyrios Kyrtzidis9afd4492012-01-05 21:36:25 +0000513 // If we've been asked to skip bytes in the main file (e.g., as part of a
514 // precompiled preamble), do so now.
515 if (SkipMainFilePreamble.first > 0)
516 CurLexer->SkipBytes(SkipMainFilePreamble.first,
517 SkipMainFilePreamble.second);
518
519 // Tell the header info that the main file was entered. If the file is later
520 // #imported, it won't be re-entered.
521 if (const FileEntry *FE = SourceMgr.getFileEntryForID(MainFileID))
522 HeaderInfo.IncrementIncludeCount(FE);
523 }
Mike Stump11289f42009-09-09 15:08:12 +0000524
Benjamin Kramerd77adb52009-12-31 15:33:09 +0000525 // Preprocess Predefines to populate the initial preprocessor state.
Rafael Espindolad87f8d72014-08-27 20:03:29 +0000526 std::unique_ptr<llvm::MemoryBuffer> SB =
Chris Lattner58c79342010-04-05 22:42:27 +0000527 llvm::MemoryBuffer::getMemBufferCopy(Predefines, "<built-in>");
Douglas Gregor33551892010-08-26 14:07:34 +0000528 assert(SB && "Cannot create predefined source buffer");
David Blaikie50a5f972014-08-29 07:59:55 +0000529 FileID FID = SourceMgr.createFileID(std::move(SB));
Yaron Keren8b563662015-10-03 10:46:20 +0000530 assert(FID.isValid() && "Could not create FileID for predefines?");
Argyrios Kyrtzidis22c22f52013-02-01 16:36:07 +0000531 setPredefinesFileID(FID);
Mike Stump11289f42009-09-09 15:08:12 +0000532
Chris Lattner1f1b0db2007-10-09 22:10:18 +0000533 // Start parsing the predefines.
Craig Topperd2d442c2014-05-17 23:10:59 +0000534 EnterSourceFile(FID, nullptr, SourceLocation());
Chris Lattner1f1b0db2007-10-09 22:10:18 +0000535}
Chris Lattner8a7003c2007-07-16 06:48:38 +0000536
Daniel Dunbarcb9eaf52010-03-23 05:09:10 +0000537void Preprocessor::EndSourceFile() {
538 // Notify the client that we reached the end of the source file.
539 if (Callbacks)
540 Callbacks->EndOfMainFile();
541}
Chris Lattner677757a2006-06-28 05:26:32 +0000542
543//===----------------------------------------------------------------------===//
544// Lexer Event Handling.
545//===----------------------------------------------------------------------===//
546
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +0000547/// LookUpIdentifierInfo - Given a tok::raw_identifier token, look up the
548/// identifier information for the token and install it into the token,
549/// updating the token kind accordingly.
550IdentifierInfo *Preprocessor::LookUpIdentifierInfo(Token &Identifier) const {
Alp Toker2d57cea2014-05-17 04:53:25 +0000551 assert(!Identifier.getRawIdentifier().empty() && "No raw identifier data!");
Mike Stump11289f42009-09-09 15:08:12 +0000552
Chris Lattnercefc7682006-07-08 08:28:12 +0000553 // Look up this token, see if it is a macro, or if it is a language keyword.
554 IdentifierInfo *II;
Jordan Rose7f43ddd2013-01-24 20:50:46 +0000555 if (!Identifier.needsCleaning() && !Identifier.hasUCN()) {
Chris Lattnercefc7682006-07-08 08:28:12 +0000556 // No cleaning needed, just use the characters from the lexed buffer.
Alp Toker2d57cea2014-05-17 04:53:25 +0000557 II = getIdentifierInfo(Identifier.getRawIdentifier());
Chris Lattnercefc7682006-07-08 08:28:12 +0000558 } else {
559 // Cleaning needed, alloca a buffer, clean into it, then use the buffer.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +0000560 SmallString<64> IdentifierBuffer;
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000561 StringRef CleanedStr = getSpelling(Identifier, IdentifierBuffer);
Jordan Rose7f43ddd2013-01-24 20:50:46 +0000562
563 if (Identifier.hasUCN()) {
564 SmallString<64> UCNIdentifierBuffer;
565 expandUCNs(UCNIdentifierBuffer, CleanedStr);
566 II = getIdentifierInfo(UCNIdentifierBuffer);
567 } else {
568 II = getIdentifierInfo(CleanedStr);
569 }
Chris Lattnercefc7682006-07-08 08:28:12 +0000570 }
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +0000571
572 // Update the token info (identifier info and appropriate token kind).
Chris Lattner8c204872006-10-14 05:19:21 +0000573 Identifier.setIdentifierInfo(II);
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +0000574 Identifier.setKind(II->getTokenID());
575
Chris Lattnercefc7682006-07-08 08:28:12 +0000576 return II;
577}
578
John Wiegley1c0675e2011-04-28 01:08:34 +0000579void Preprocessor::SetPoisonReason(IdentifierInfo *II, unsigned DiagID) {
580 PoisonReasons[II] = DiagID;
581}
582
583void Preprocessor::PoisonSEHIdentifiers(bool Poison) {
584 assert(Ident__exception_code && Ident__exception_info);
585 assert(Ident___exception_code && Ident___exception_info);
586 Ident__exception_code->setIsPoisoned(Poison);
587 Ident___exception_code->setIsPoisoned(Poison);
588 Ident_GetExceptionCode->setIsPoisoned(Poison);
589 Ident__exception_info->setIsPoisoned(Poison);
590 Ident___exception_info->setIsPoisoned(Poison);
591 Ident_GetExceptionInfo->setIsPoisoned(Poison);
592 Ident__abnormal_termination->setIsPoisoned(Poison);
593 Ident___abnormal_termination->setIsPoisoned(Poison);
594 Ident_AbnormalTermination->setIsPoisoned(Poison);
595}
596
597void Preprocessor::HandlePoisonedIdentifier(Token & Identifier) {
598 assert(Identifier.getIdentifierInfo() &&
599 "Can't handle identifiers without identifier info!");
600 llvm::DenseMap<IdentifierInfo*,unsigned>::const_iterator it =
601 PoisonReasons.find(Identifier.getIdentifierInfo());
602 if(it == PoisonReasons.end())
603 Diag(Identifier, diag::err_pp_used_poisoned_id);
604 else
605 Diag(Identifier,it->second) << Identifier.getIdentifierInfo();
606}
Chris Lattnercefc7682006-07-08 08:28:12 +0000607
Richard Smith31d51842015-05-14 04:00:59 +0000608/// \brief Returns a diagnostic message kind for reporting a future keyword as
609/// appropriate for the identifier and specified language.
610static diag::kind getFutureCompatDiagKind(const IdentifierInfo &II,
611 const LangOptions &LangOpts) {
612 assert(II.isFutureCompatKeyword() && "diagnostic should not be needed");
613
614 if (LangOpts.CPlusPlus)
615 return llvm::StringSwitch<diag::kind>(II.getName())
616#define CXX11_KEYWORD(NAME, FLAGS) \
617 .Case(#NAME, diag::warn_cxx11_keyword)
618#include "clang/Basic/TokenKinds.def"
619 ;
620
621 llvm_unreachable(
622 "Keyword not known to come from a newer Standard or proposed Standard");
623}
624
Richard Smith3dba7eb2016-08-18 01:16:55 +0000625void Preprocessor::updateOutOfDateIdentifier(IdentifierInfo &II) const {
626 assert(II.isOutOfDate() && "not out of date");
627 getExternalSource()->updateOutOfDateIdentifier(II);
628}
629
Chris Lattner677757a2006-06-28 05:26:32 +0000630/// HandleIdentifier - This callback is invoked when the lexer reads an
631/// identifier. This callback looks up the identifier in the map and/or
632/// potentially macro expands it or turns it into a named token (like 'for').
Chris Lattnerad89ec02009-01-21 07:43:11 +0000633///
634/// Note that callers of this method are guarded by checking the
635/// IdentifierInfo's 'isHandleIdentifierCase' bit. If this method changes, the
636/// IdentifierInfo methods that compute these properties will need to change to
637/// match.
Eli Friedman0834a4b2013-09-19 00:41:32 +0000638bool Preprocessor::HandleIdentifier(Token &Identifier) {
Chris Lattner0f1f5052006-07-20 04:16:23 +0000639 assert(Identifier.getIdentifierInfo() &&
640 "Can't handle identifiers without identifier info!");
Mike Stump11289f42009-09-09 15:08:12 +0000641
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000642 IdentifierInfo &II = *Identifier.getIdentifierInfo();
Chris Lattner677757a2006-06-28 05:26:32 +0000643
Douglas Gregor935bc7a22011-10-27 09:33:13 +0000644 // If the information about this identifier is out of date, update it from
645 // the external source.
Douglas Gregor3f568c12012-06-29 18:27:59 +0000646 // We have to treat __VA_ARGS__ in a special way, since it gets
647 // serialized with isPoisoned = true, but our preprocessor may have
648 // unpoisoned it if we're defining a C99 macro.
Douglas Gregor935bc7a22011-10-27 09:33:13 +0000649 if (II.isOutOfDate()) {
Douglas Gregor3f568c12012-06-29 18:27:59 +0000650 bool CurrentIsPoisoned = false;
651 if (&II == Ident__VA_ARGS__)
652 CurrentIsPoisoned = Ident__VA_ARGS__->isPoisoned();
653
Richard Smith3dba7eb2016-08-18 01:16:55 +0000654 updateOutOfDateIdentifier(II);
Douglas Gregor935bc7a22011-10-27 09:33:13 +0000655 Identifier.setKind(II.getTokenID());
Douglas Gregor3f568c12012-06-29 18:27:59 +0000656
657 if (&II == Ident__VA_ARGS__)
658 II.setIsPoisoned(CurrentIsPoisoned);
Douglas Gregor935bc7a22011-10-27 09:33:13 +0000659 }
660
Chris Lattner677757a2006-06-28 05:26:32 +0000661 // If this identifier was poisoned, and if it was not produced from a macro
662 // expansion, emit an error.
Ted Kremeneka2c3c8d2008-11-19 22:43:49 +0000663 if (II.isPoisoned() && CurPPLexer) {
John Wiegley1c0675e2011-04-28 01:08:34 +0000664 HandlePoisonedIdentifier(Identifier);
Chris Lattner8ff71992006-07-06 05:17:39 +0000665 }
Mike Stump11289f42009-09-09 15:08:12 +0000666
Chris Lattner78186052006-07-09 00:45:31 +0000667 // If this is a macro to be expanded, do it.
Richard Smith20e883e2015-04-29 23:20:19 +0000668 if (MacroDefinition MD = getMacroDefinition(&II)) {
669 auto *MI = MD.getMacroInfo();
Richard Smithf5ec2ac2015-04-29 23:40:48 +0000670 assert(MI && "macro definition with no macro info?");
Abramo Bagnara123bec82012-01-01 22:01:04 +0000671 if (!DisableMacroExpansion) {
Richard Smith181879c2012-12-12 02:46:14 +0000672 if (!Identifier.isExpandDisabled() && MI->isEnabled()) {
Eli Friedman0834a4b2013-09-19 00:41:32 +0000673 // C99 6.10.3p10: If the preprocessing token immediately after the
674 // macro name isn't a '(', this macro should not be expanded.
675 if (!MI->isFunctionLike() || isNextPPTokenLParen())
676 return HandleMacroExpandedIdentifier(Identifier, MD);
Chris Lattner6e4bf522006-07-27 06:59:25 +0000677 } else {
678 // C99 6.10.3.4p2 says that a disabled macro may never again be
679 // expanded, even if it's in a context where it could be expanded in the
680 // future.
Chris Lattner146762e2007-07-20 16:59:19 +0000681 Identifier.setFlag(Token::DisableExpand);
Richard Smith181879c2012-12-12 02:46:14 +0000682 if (MI->isObjectLike() || isNextPPTokenLParen())
683 Diag(Identifier, diag::pp_disabled_macro_expansion);
Chris Lattner6e4bf522006-07-27 06:59:25 +0000684 }
685 }
Chris Lattner063400e2006-10-14 19:54:15 +0000686 }
Chris Lattner677757a2006-06-28 05:26:32 +0000687
Richard Smith31d51842015-05-14 04:00:59 +0000688 // If this identifier is a keyword in a newer Standard or proposed Standard,
689 // produce a warning. Don't warn if we're not considering macro expansion,
690 // since this identifier might be the name of a macro.
Richard Smith4dd85d62011-10-11 19:57:52 +0000691 // FIXME: This warning is disabled in cases where it shouldn't be, like
692 // "#define constexpr constexpr", "int constexpr;"
Richard Smith31d51842015-05-14 04:00:59 +0000693 if (II.isFutureCompatKeyword() && !DisableMacroExpansion) {
694 Diag(Identifier, getFutureCompatDiagKind(II, getLangOpts()))
695 << II.getName();
Richard Smith4dd85d62011-10-11 19:57:52 +0000696 // Don't diagnose this keyword again in this translation unit.
Richard Smith31d51842015-05-14 04:00:59 +0000697 II.setIsFutureCompatKeyword(false);
Richard Smith4dd85d62011-10-11 19:57:52 +0000698 }
699
Chris Lattner5b9f4892006-11-21 17:23:33 +0000700 // C++ 2.11p2: If this is an alternative representation of a C++ operator,
701 // then we act as if it is the actual operator and not the textual
702 // representation of it.
Fariborz Jahanian9e42a952010-09-03 17:33:04 +0000703 if (II.isCPlusPlusOperatorKeyword())
Craig Topperd2d442c2014-05-17 23:10:59 +0000704 Identifier.setIdentifierInfo(nullptr);
Chris Lattner5b9f4892006-11-21 17:23:33 +0000705
Chris Lattner677757a2006-06-28 05:26:32 +0000706 // If this is an extension token, diagnose its use.
Steve Naroffc84e8b72008-09-02 18:50:17 +0000707 // We avoid diagnosing tokens that originate from macro definitions.
Eli Friedman6bba2ad2009-04-28 03:59:15 +0000708 // FIXME: This warning is disabled in cases where it shouldn't be,
709 // like "#define TY typeof", "TY(1) x".
710 if (II.isExtensionToken() && !DisableMacroExpansion)
Chris Lattner53621a52007-06-13 20:44:40 +0000711 Diag(Identifier, diag::ext_token_used);
Douglas Gregoraf5c4842011-09-07 23:11:54 +0000712
Douglas Gregor594b8c92013-11-07 22:55:02 +0000713 // If this is the 'import' contextual keyword following an '@', note
Ted Kremenekc1e4dd02012-03-01 22:07:04 +0000714 // that the next token indicates a module name.
Douglas Gregor8d76cca2012-01-04 06:20:15 +0000715 //
Douglas Gregorc50d4922012-12-11 22:11:52 +0000716 // Note that we do not treat 'import' as a contextual
Ted Kremenekc1e4dd02012-03-01 22:07:04 +0000717 // keyword when we're in a caching lexer, because caching lexers only get
718 // used in contexts where import declarations are disallowed.
Richard Smith49cc1cc2016-08-18 21:59:42 +0000719 //
720 // Likewise if this is the C++ Modules TS import keyword.
721 if (((LastTokenWasAt && II.isModulesImport()) ||
722 Identifier.is(tok::kw_import)) &&
723 !InMacroArgs && !DisableMacroExpansion &&
724 (getLangOpts().Modules || getLangOpts().DebuggerSupport) &&
Douglas Gregor594b8c92013-11-07 22:55:02 +0000725 CurLexerKind != CLK_CachingLexer) {
Douglas Gregoraf5c4842011-09-07 23:11:54 +0000726 ModuleImportLoc = Identifier.getLocation();
Douglas Gregor1805b8a2011-11-30 04:26:53 +0000727 ModuleImportPath.clear();
728 ModuleImportExpectsIdentifier = true;
Douglas Gregoraf5c4842011-09-07 23:11:54 +0000729 CurLexerKind = CLK_LexAfterModuleImport;
730 }
Eli Friedman0834a4b2013-09-19 00:41:32 +0000731 return true;
Douglas Gregor08142532011-08-26 23:56:07 +0000732}
733
Eli Friedman0834a4b2013-09-19 00:41:32 +0000734void Preprocessor::Lex(Token &Result) {
Yaron Keren716f3a62015-09-29 16:51:08 +0000735 // We loop here until a lex function returns a token; this avoids recursion.
Eli Friedman0834a4b2013-09-19 00:41:32 +0000736 bool ReturnedToken;
737 do {
738 switch (CurLexerKind) {
739 case CLK_Lexer:
740 ReturnedToken = CurLexer->Lex(Result);
741 break;
742 case CLK_PTHLexer:
743 ReturnedToken = CurPTHLexer->Lex(Result);
744 break;
745 case CLK_TokenLexer:
746 ReturnedToken = CurTokenLexer->Lex(Result);
747 break;
748 case CLK_CachingLexer:
749 CachingLex(Result);
750 ReturnedToken = true;
751 break;
752 case CLK_LexAfterModuleImport:
753 LexAfterModuleImport(Result);
754 ReturnedToken = true;
755 break;
756 }
757 } while (!ReturnedToken);
Douglas Gregor594b8c92013-11-07 22:55:02 +0000758
Vassil Vassilev644ea612016-07-27 14:56:59 +0000759 if (Result.is(tok::code_completion))
760 setCodeCompletionIdentifierInfo(Result.getIdentifierInfo());
761
Douglas Gregor594b8c92013-11-07 22:55:02 +0000762 LastTokenWasAt = Result.is(tok::at);
Eli Friedman0834a4b2013-09-19 00:41:32 +0000763}
764
Douglas Gregorda82e702012-01-03 19:32:59 +0000765/// \brief Lex a token following the 'import' contextual keyword.
Douglas Gregor22d09742012-01-03 18:04:46 +0000766///
Douglas Gregoraf5c4842011-09-07 23:11:54 +0000767void Preprocessor::LexAfterModuleImport(Token &Result) {
768 // Figure out what kind of lexer we actually have.
Douglas Gregor8d76cca2012-01-04 06:20:15 +0000769 recomputeCurLexerKind();
Douglas Gregoraf5c4842011-09-07 23:11:54 +0000770
771 // Lex the next token.
772 Lex(Result);
773
Douglas Gregor08142532011-08-26 23:56:07 +0000774 // The token sequence
775 //
Douglas Gregor22d09742012-01-03 18:04:46 +0000776 // import identifier (. identifier)*
777 //
Douglas Gregorda82e702012-01-03 19:32:59 +0000778 // indicates a module import directive. We already saw the 'import'
779 // contextual keyword, so now we're looking for the identifiers.
Douglas Gregor1805b8a2011-11-30 04:26:53 +0000780 if (ModuleImportExpectsIdentifier && Result.getKind() == tok::identifier) {
781 // We expected to see an identifier here, and we did; continue handling
782 // identifiers.
783 ModuleImportPath.push_back(std::make_pair(Result.getIdentifierInfo(),
784 Result.getLocation()));
785 ModuleImportExpectsIdentifier = false;
786 CurLexerKind = CLK_LexAfterModuleImport;
Douglas Gregor08142532011-08-26 23:56:07 +0000787 return;
Douglas Gregor1805b8a2011-11-30 04:26:53 +0000788 }
Douglas Gregor08142532011-08-26 23:56:07 +0000789
Douglas Gregor1805b8a2011-11-30 04:26:53 +0000790 // If we're expecting a '.' or a ';', and we got a '.', then wait until we
Richard Smith49cc1cc2016-08-18 21:59:42 +0000791 // see the next identifier. (We can also see a '[[' that begins an
792 // attribute-specifier-seq here under the C++ Modules TS.)
Douglas Gregor1805b8a2011-11-30 04:26:53 +0000793 if (!ModuleImportExpectsIdentifier && Result.getKind() == tok::period) {
794 ModuleImportExpectsIdentifier = true;
795 CurLexerKind = CLK_LexAfterModuleImport;
796 return;
797 }
798
799 // If we have a non-empty module path, load the named module.
Sean Callanan87596492014-12-09 23:47:56 +0000800 if (!ModuleImportPath.empty()) {
Richard Smithbbcc9f02016-08-26 00:14:38 +0000801 // Under the Modules TS, the dot is just part of the module name, and not
802 // a real hierarachy separator. Flatten such module names now.
803 //
804 // FIXME: Is this the right level to be performing this transformation?
805 std::string FlatModuleName;
806 if (getLangOpts().ModulesTS) {
807 for (auto &Piece : ModuleImportPath) {
808 if (!FlatModuleName.empty())
809 FlatModuleName += ".";
810 FlatModuleName += Piece.first->getName();
811 }
812 SourceLocation FirstPathLoc = ModuleImportPath[0].second;
813 ModuleImportPath.clear();
814 ModuleImportPath.push_back(
815 std::make_pair(getIdentifierInfo(FlatModuleName), FirstPathLoc));
816 }
817
Sean Callanan87596492014-12-09 23:47:56 +0000818 Module *Imported = nullptr;
Richard Smith753e0072015-04-27 23:21:38 +0000819 if (getLangOpts().Modules) {
Sean Callanan87596492014-12-09 23:47:56 +0000820 Imported = TheModuleLoader.loadModule(ModuleImportLoc,
821 ModuleImportPath,
Richard Smith10434f32015-05-02 02:08:26 +0000822 Module::Hidden,
Sean Callanan87596492014-12-09 23:47:56 +0000823 /*IsIncludeDirective=*/false);
Richard Smitha7e2cc62015-05-01 01:53:09 +0000824 if (Imported)
825 makeModuleVisible(Imported, ModuleImportLoc);
Richard Smith753e0072015-04-27 23:21:38 +0000826 }
Sean Callanan87596492014-12-09 23:47:56 +0000827 if (Callbacks && (getLangOpts().Modules || getLangOpts().DebuggerSupport))
Argyrios Kyrtzidis19d78b72012-09-29 01:06:10 +0000828 Callbacks->moduleImport(ModuleImportLoc, ModuleImportPath, Imported);
829 }
Chris Lattner677757a2006-06-28 05:26:32 +0000830}
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000831
Richard Smitha7e2cc62015-05-01 01:53:09 +0000832void Preprocessor::makeModuleVisible(Module *M, SourceLocation Loc) {
Richard Smith04765ae2015-05-21 01:20:10 +0000833 CurSubmoduleState->VisibleModules.setVisible(
Richard Smitha7e2cc62015-05-01 01:53:09 +0000834 M, Loc, [](Module *) {},
835 [&](ArrayRef<Module *> Path, Module *Conflict, StringRef Message) {
836 // FIXME: Include the path in the diagnostic.
837 // FIXME: Include the import location for the conflicting module.
838 Diag(ModuleImportLoc, diag::warn_module_conflict)
839 << Path[0]->getFullModuleName()
840 << Conflict->getFullModuleName()
841 << Message;
842 });
843
844 // Add this module to the imports list of the currently-built submodule.
Richard Smithdbbc5232015-05-14 02:25:44 +0000845 if (!BuildingSubmoduleStack.empty() && M != BuildingSubmoduleStack.back().M)
Richard Smith38477db2015-05-02 00:45:56 +0000846 BuildingSubmoduleStack.back().M->Imports.insert(M);
Richard Smitha7e2cc62015-05-01 01:53:09 +0000847}
848
Andy Gibbs58905d22012-11-17 19:15:38 +0000849bool Preprocessor::FinishLexStringLiteral(Token &Result, std::string &String,
Andy Gibbsa8df57a2012-11-17 19:16:52 +0000850 const char *DiagnosticTag,
Andy Gibbs58905d22012-11-17 19:15:38 +0000851 bool AllowMacroExpansion) {
852 // We need at least one string literal.
853 if (Result.isNot(tok::string_literal)) {
Andy Gibbsa8df57a2012-11-17 19:16:52 +0000854 Diag(Result, diag::err_expected_string_literal)
855 << /*Source='in...'*/0 << DiagnosticTag;
Andy Gibbs58905d22012-11-17 19:15:38 +0000856 return false;
857 }
858
859 // Lex string literal tokens, optionally with macro expansion.
860 SmallVector<Token, 4> StrToks;
861 do {
862 StrToks.push_back(Result);
863
864 if (Result.hasUDSuffix())
865 Diag(Result, diag::err_invalid_string_udl);
866
867 if (AllowMacroExpansion)
868 Lex(Result);
869 else
870 LexUnexpandedToken(Result);
871 } while (Result.is(tok::string_literal));
872
873 // Concatenate and parse the strings.
Craig Topper9d5583e2014-06-26 04:58:39 +0000874 StringLiteralParser Literal(StrToks, *this);
Andy Gibbs58905d22012-11-17 19:15:38 +0000875 assert(Literal.isAscii() && "Didn't allow wide strings in");
876
877 if (Literal.hadError)
878 return false;
879
880 if (Literal.Pascal) {
Andy Gibbsa8df57a2012-11-17 19:16:52 +0000881 Diag(StrToks[0].getLocation(), diag::err_expected_string_literal)
882 << /*Source='in...'*/0 << DiagnosticTag;
Andy Gibbs58905d22012-11-17 19:15:38 +0000883 return false;
884 }
885
886 String = Literal.GetString();
887 return true;
888}
889
Reid Klecknerc0dca6d2014-02-12 23:50:26 +0000890bool Preprocessor::parseSimpleIntegerLiteral(Token &Tok, uint64_t &Value) {
891 assert(Tok.is(tok::numeric_constant));
892 SmallString<8> IntegerBuffer;
893 bool NumberInvalid = false;
894 StringRef Spelling = getSpelling(Tok, IntegerBuffer, &NumberInvalid);
895 if (NumberInvalid)
896 return false;
897 NumericLiteralParser Literal(Spelling, Tok.getLocation(), *this);
898 if (Literal.hadError || !Literal.isIntegerLiteral() || Literal.hasUDSuffix())
899 return false;
900 llvm::APInt APVal(64, 0);
901 if (Literal.GetIntegerValue(APVal))
902 return false;
903 Lex(Tok);
904 Value = APVal.getLimitedValue();
905 return true;
906}
907
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000908void Preprocessor::addCommentHandler(CommentHandler *Handler) {
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000909 assert(Handler && "NULL comment handler");
910 assert(std::find(CommentHandlers.begin(), CommentHandlers.end(), Handler) ==
911 CommentHandlers.end() && "Comment handler already registered");
912 CommentHandlers.push_back(Handler);
913}
914
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000915void Preprocessor::removeCommentHandler(CommentHandler *Handler) {
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000916 std::vector<CommentHandler *>::iterator Pos
917 = std::find(CommentHandlers.begin(), CommentHandlers.end(), Handler);
918 assert(Pos != CommentHandlers.end() && "Comment handler not registered");
919 CommentHandlers.erase(Pos);
920}
921
Chris Lattner87d02082010-01-18 22:35:47 +0000922bool Preprocessor::HandleComment(Token &result, SourceRange Comment) {
923 bool AnyPendingTokens = false;
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000924 for (std::vector<CommentHandler *>::iterator H = CommentHandlers.begin(),
925 HEnd = CommentHandlers.end();
Chris Lattner87d02082010-01-18 22:35:47 +0000926 H != HEnd; ++H) {
927 if ((*H)->HandleComment(*this, Comment))
928 AnyPendingTokens = true;
929 }
930 if (!AnyPendingTokens || getCommentRetentionState())
931 return false;
932 Lex(result);
933 return true;
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000934}
935
Angel Garcia Gomez637d1e62015-10-20 13:23:58 +0000936ModuleLoader::~ModuleLoader() { }
Douglas Gregor08142532011-08-26 23:56:07 +0000937
Angel Garcia Gomez637d1e62015-10-20 13:23:58 +0000938CommentHandler::~CommentHandler() { }
Douglas Gregor7f6d60d2010-03-19 16:15:56 +0000939
Angel Garcia Gomez637d1e62015-10-20 13:23:58 +0000940CodeCompletionHandler::~CodeCompletionHandler() { }
Douglas Gregor3a7ad252010-08-24 19:08:16 +0000941
Argyrios Kyrtzidisf3d587e2012-12-04 07:27:05 +0000942void Preprocessor::createPreprocessingRecord() {
Douglas Gregor7f6d60d2010-03-19 16:15:56 +0000943 if (Record)
944 return;
945
Argyrios Kyrtzidisf3d587e2012-12-04 07:27:05 +0000946 Record = new PreprocessingRecord(getSourceManager());
Craig Topperb8a70532014-09-10 04:53:53 +0000947 addPPCallbacks(std::unique_ptr<PPCallbacks>(Record));
Douglas Gregor7f6d60d2010-03-19 16:15:56 +0000948}