blob: 158d0eca2789da85cedb6bce9c3379ce4886feed [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 }
Erik Verbruggenb34c79f2017-05-30 11:54:55 +0000153
154 if (this->PPOpts->GeneratePreamble)
155 PreambleConditionalStack.startRecording();
Argyrios Kyrtzidis3c9aaf12012-06-02 18:08:09 +0000156}
157
158Preprocessor::~Preprocessor() {
159 assert(BacktrackPositions.empty() && "EnableBacktrack/Backtrack imbalance!");
160
Benjamin Kramer329c5962014-03-15 16:40:40 +0000161 IncludeMacroStack.clear();
Argyrios Kyrtzidis3c9aaf12012-06-02 18:08:09 +0000162
Richard Smith73a29662014-07-24 03:25:00 +0000163 // Destroy any macro definitions.
164 while (MacroInfoChain *I = MIChainHead) {
165 MIChainHead = I->Next;
166 I->~MacroInfoChain();
167 }
Argyrios Kyrtzidis3c9aaf12012-06-02 18:08:09 +0000168
169 // Free any cached macro expanders.
Nico Weber5f5b9412014-05-09 18:09:42 +0000170 // This populates MacroArgCache, so all TokenLexers need to be destroyed
171 // before the code below that frees up the MacroArgCache list.
David Blaikie6d5038c2014-08-29 19:36:52 +0000172 std::fill(TokenLexerCache, TokenLexerCache + NumCachedTokenLexers, nullptr);
Nico Weber5f5b9412014-05-09 18:09:42 +0000173 CurTokenLexer.reset();
Argyrios Kyrtzidis3c9aaf12012-06-02 18:08:09 +0000174
175 // Free any cached MacroArgs.
Nico Weber5f5b9412014-05-09 18:09:42 +0000176 for (MacroArgs *ArgList = MacroArgCache; ArgList;)
Argyrios Kyrtzidis3c9aaf12012-06-02 18:08:09 +0000177 ArgList = ArgList->deallocate();
178
Argyrios Kyrtzidis3c9aaf12012-06-02 18:08:09 +0000179 // Delete the header search info, if we own it.
180 if (OwnsHeaderSearch)
181 delete &HeaderInfo;
Argyrios Kyrtzidis3c9aaf12012-06-02 18:08:09 +0000182}
183
Artem Belevichb5bc9232015-09-22 17:23:22 +0000184void Preprocessor::Initialize(const TargetInfo &Target,
185 const TargetInfo *AuxTarget) {
Argyrios Kyrtzidis3c9aaf12012-06-02 18:08:09 +0000186 assert((!this->Target || this->Target == &Target) &&
187 "Invalid override of target information");
188 this->Target = &Target;
Artem Belevichb5bc9232015-09-22 17:23:22 +0000189
190 assert((!this->AuxTarget || this->AuxTarget == AuxTarget) &&
191 "Invalid override of aux target information.");
192 this->AuxTarget = AuxTarget;
193
Argyrios Kyrtzidis3c9aaf12012-06-02 18:08:09 +0000194 // Initialize information about built-ins.
Artem Belevichb5bc9232015-09-22 17:23:22 +0000195 BuiltinInfo.InitializeTarget(Target, AuxTarget);
Douglas Gregor89929282012-01-30 06:01:29 +0000196 HeaderInfo.setTarget(Target);
Douglas Gregor83297df2011-09-01 23:39:15 +0000197}
198
Ted Kremenekeeccb302014-08-27 15:14:15 +0000199void Preprocessor::InitializeForModelFile() {
200 NumEnteredSourceFiles = 0;
201
202 // Reset pragmas
David Blaikie9f0af9d2014-09-15 21:31:42 +0000203 PragmaHandlersBackup = std::move(PragmaHandlers);
Craig Topperbe250302014-09-12 05:19:24 +0000204 PragmaHandlers = llvm::make_unique<PragmaNamespace>(StringRef());
Ted Kremenekeeccb302014-08-27 15:14:15 +0000205 RegisterBuiltinPragmas();
206
207 // Reset PredefinesFileID
208 PredefinesFileID = FileID();
209}
210
211void Preprocessor::FinalizeForModelFile() {
212 NumEnteredSourceFiles = 1;
213
David Blaikie9f0af9d2014-09-15 21:31:42 +0000214 PragmaHandlers = std::move(PragmaHandlersBackup);
Ted Kremenekeeccb302014-08-27 15:14:15 +0000215}
216
Ted Kremeneka5c2c272009-02-12 03:26:59 +0000217void Preprocessor::setPTHManager(PTHManager* pm) {
218 PTH.reset(pm);
Douglas Gregord2eb58a2009-10-16 18:18:30 +0000219 FileMgr.addStatCache(PTH->createStatCache());
Ted Kremeneka5c2c272009-02-12 03:26:59 +0000220}
221
Chris Lattner146762e2007-07-20 16:59:19 +0000222void Preprocessor::DumpToken(const Token &Tok, bool DumpFlags) const {
Benjamin Kramer89b422c2009-08-23 12:08:50 +0000223 llvm::errs() << tok::getTokenName(Tok.getKind()) << " '"
224 << getSpelling(Tok) << "'";
Mike Stump11289f42009-09-09 15:08:12 +0000225
Chris Lattnerd01e2912006-06-18 16:22:51 +0000226 if (!DumpFlags) return;
Mike Stump11289f42009-09-09 15:08:12 +0000227
Benjamin Kramer89b422c2009-08-23 12:08:50 +0000228 llvm::errs() << "\t";
Chris Lattnerd01e2912006-06-18 16:22:51 +0000229 if (Tok.isAtStartOfLine())
Benjamin Kramer89b422c2009-08-23 12:08:50 +0000230 llvm::errs() << " [StartOfLine]";
Chris Lattnerd01e2912006-06-18 16:22:51 +0000231 if (Tok.hasLeadingSpace())
Benjamin Kramer89b422c2009-08-23 12:08:50 +0000232 llvm::errs() << " [LeadingSpace]";
Chris Lattner6e4bf522006-07-27 06:59:25 +0000233 if (Tok.isExpandDisabled())
Benjamin Kramer89b422c2009-08-23 12:08:50 +0000234 llvm::errs() << " [ExpandDisabled]";
Chris Lattnerd01e2912006-06-18 16:22:51 +0000235 if (Tok.needsCleaning()) {
Chris Lattner50b497e2006-06-18 16:32:35 +0000236 const char *Start = SourceMgr.getCharacterData(Tok.getLocation());
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000237 llvm::errs() << " [UnClean='" << StringRef(Start, Tok.getLength())
Benjamin Kramer89b422c2009-08-23 12:08:50 +0000238 << "']";
Chris Lattnerd01e2912006-06-18 16:22:51 +0000239 }
Mike Stump11289f42009-09-09 15:08:12 +0000240
Benjamin Kramer89b422c2009-08-23 12:08:50 +0000241 llvm::errs() << "\tLoc=<";
Chris Lattner615315f2007-12-09 20:31:55 +0000242 DumpLocation(Tok.getLocation());
Benjamin Kramer89b422c2009-08-23 12:08:50 +0000243 llvm::errs() << ">";
Chris Lattner615315f2007-12-09 20:31:55 +0000244}
245
246void Preprocessor::DumpLocation(SourceLocation Loc) const {
Chris Lattnerf1ca7d32009-01-27 07:57:44 +0000247 Loc.dump(SourceMgr);
Chris Lattnerd01e2912006-06-18 16:22:51 +0000248}
249
250void Preprocessor::DumpMacro(const MacroInfo &MI) const {
Benjamin Kramer89b422c2009-08-23 12:08:50 +0000251 llvm::errs() << "MACRO: ";
Chris Lattnerd01e2912006-06-18 16:22:51 +0000252 for (unsigned i = 0, e = MI.getNumTokens(); i != e; ++i) {
253 DumpToken(MI.getReplacementToken(i));
Benjamin Kramer89b422c2009-08-23 12:08:50 +0000254 llvm::errs() << " ";
Chris Lattnerd01e2912006-06-18 16:22:51 +0000255 }
Benjamin Kramer89b422c2009-08-23 12:08:50 +0000256 llvm::errs() << "\n";
Chris Lattnerd01e2912006-06-18 16:22:51 +0000257}
258
Chris Lattner22eb9722006-06-18 05:43:12 +0000259void Preprocessor::PrintStats() {
Benjamin Kramer89b422c2009-08-23 12:08:50 +0000260 llvm::errs() << "\n*** Preprocessor Stats:\n";
261 llvm::errs() << NumDirectives << " directives found:\n";
262 llvm::errs() << " " << NumDefined << " #define.\n";
263 llvm::errs() << " " << NumUndefined << " #undef.\n";
264 llvm::errs() << " #include/#include_next/#import:\n";
265 llvm::errs() << " " << NumEnteredSourceFiles << " source files entered.\n";
266 llvm::errs() << " " << MaxIncludeStackDepth << " max include stack depth\n";
267 llvm::errs() << " " << NumIf << " #if/#ifndef/#ifdef.\n";
268 llvm::errs() << " " << NumElse << " #else/#elif.\n";
269 llvm::errs() << " " << NumEndif << " #endif.\n";
270 llvm::errs() << " " << NumPragma << " #pragma.\n";
271 llvm::errs() << NumSkipped << " #if/#ifndef#ifdef regions skipped\n";
Chris Lattner22eb9722006-06-18 05:43:12 +0000272
Benjamin Kramer89b422c2009-08-23 12:08:50 +0000273 llvm::errs() << NumMacroExpanded << "/" << NumFnMacroExpanded << "/"
Ted Kremeneka0a3e9b2008-01-14 16:44:48 +0000274 << NumBuiltinMacroExpanded << " obj/fn/builtin macros expanded, "
275 << NumFastMacroExpanded << " on the fast path.\n";
Benjamin Kramer89b422c2009-08-23 12:08:50 +0000276 llvm::errs() << (NumFastTokenPaste+NumTokenPaste)
Ted Kremeneka0a3e9b2008-01-14 16:44:48 +0000277 << " token paste (##) operations performed, "
278 << NumFastTokenPaste << " on the fast path.\n";
Alexander Kornienko199cd942012-08-13 10:46:42 +0000279
280 llvm::errs() << "\nPreprocessor Memory: " << getTotalMemory() << "B total";
281
282 llvm::errs() << "\n BumpPtr: " << BP.getTotalMemory();
283 llvm::errs() << "\n Macro Expanded Tokens: "
284 << llvm::capacity_in_bytes(MacroExpandedTokens);
285 llvm::errs() << "\n Predefines Buffer: " << Predefines.capacity();
Richard Smith04765ae2015-05-21 01:20:10 +0000286 // FIXME: List information for all submodules.
287 llvm::errs() << "\n Macros: "
288 << llvm::capacity_in_bytes(CurSubmoduleState->Macros);
Alexander Kornienko199cd942012-08-13 10:46:42 +0000289 llvm::errs() << "\n #pragma push_macro Info: "
290 << llvm::capacity_in_bytes(PragmaPushMacroInfo);
291 llvm::errs() << "\n Poison Reasons: "
292 << llvm::capacity_in_bytes(PoisonReasons);
293 llvm::errs() << "\n Comment Handlers: "
294 << llvm::capacity_in_bytes(CommentHandlers) << "\n";
Chris Lattner22eb9722006-06-18 05:43:12 +0000295}
296
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +0000297Preprocessor::macro_iterator
298Preprocessor::macro_begin(bool IncludeExternalMacros) const {
299 if (IncludeExternalMacros && ExternalSource &&
Douglas Gregor9882a5a2010-01-04 19:18:44 +0000300 !ReadMacrosFromExternalSource) {
301 ReadMacrosFromExternalSource = true;
302 ExternalSource->ReadDefinedMacros();
303 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +0000304
Jordan Rosea46bfa62015-06-24 19:27:02 +0000305 // Make sure we cover all macros in visible modules.
306 for (const ModuleMacro &Macro : ModuleMacros)
307 CurSubmoduleState->Macros.insert(std::make_pair(Macro.II, MacroState()));
308
Richard Smith04765ae2015-05-21 01:20:10 +0000309 return CurSubmoduleState->Macros.begin();
Douglas Gregor9882a5a2010-01-04 19:18:44 +0000310}
311
Argyrios Kyrtzidise379ee32011-06-29 22:20:04 +0000312size_t Preprocessor::getTotalMemory() const {
Ted Kremenek182543a2011-07-26 21:17:24 +0000313 return BP.getTotalMemory()
Ted Kremenek8b77fe72011-07-27 18:41:23 +0000314 + llvm::capacity_in_bytes(MacroExpandedTokens)
Ted Kremenek182543a2011-07-26 21:17:24 +0000315 + Predefines.capacity() /* Predefines buffer. */
Richard Smith04765ae2015-05-21 01:20:10 +0000316 // FIXME: Include sizes from all submodules, and include MacroInfo sizes,
317 // and ModuleMacros.
318 + llvm::capacity_in_bytes(CurSubmoduleState->Macros)
Ted Kremenek8b77fe72011-07-27 18:41:23 +0000319 + llvm::capacity_in_bytes(PragmaPushMacroInfo)
320 + llvm::capacity_in_bytes(PoisonReasons)
321 + llvm::capacity_in_bytes(CommentHandlers);
Argyrios Kyrtzidise379ee32011-06-29 22:20:04 +0000322}
323
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +0000324Preprocessor::macro_iterator
325Preprocessor::macro_end(bool IncludeExternalMacros) const {
326 if (IncludeExternalMacros && ExternalSource &&
Douglas Gregor9882a5a2010-01-04 19:18:44 +0000327 !ReadMacrosFromExternalSource) {
328 ReadMacrosFromExternalSource = true;
329 ExternalSource->ReadDefinedMacros();
330 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +0000331
Richard Smith04765ae2015-05-21 01:20:10 +0000332 return CurSubmoduleState->Macros.end();
Douglas Gregor9882a5a2010-01-04 19:18:44 +0000333}
334
Dmitri Gribenko6743e042012-09-29 11:40:46 +0000335/// \brief Compares macro tokens with a specified token value sequence.
336static bool MacroDefinitionEquals(const MacroInfo *MI,
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000337 ArrayRef<TokenValue> Tokens) {
Dmitri Gribenko6743e042012-09-29 11:40:46 +0000338 return Tokens.size() == MI->getNumTokens() &&
339 std::equal(Tokens.begin(), Tokens.end(), MI->tokens_begin());
340}
341
342StringRef Preprocessor::getLastMacroWithSpelling(
343 SourceLocation Loc,
344 ArrayRef<TokenValue> Tokens) const {
345 SourceLocation BestLocation;
346 StringRef BestSpelling;
347 for (Preprocessor::macro_iterator I = macro_begin(), E = macro_end();
348 I != E; ++I) {
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +0000349 const MacroDirective::DefInfo
Richard Smithb8b2ed62015-04-23 18:18:26 +0000350 Def = I->second.findDirectiveAtLoc(Loc, SourceMgr);
Argyrios Kyrtzidis5c585252015-03-04 16:03:07 +0000351 if (!Def || !Def.getMacroInfo())
352 continue;
353 if (!Def.getMacroInfo()->isObjectLike())
Dmitri Gribenko6743e042012-09-29 11:40:46 +0000354 continue;
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +0000355 if (!MacroDefinitionEquals(Def.getMacroInfo(), Tokens))
Dmitri Gribenko6743e042012-09-29 11:40:46 +0000356 continue;
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +0000357 SourceLocation Location = Def.getLocation();
Dmitri Gribenko6743e042012-09-29 11:40:46 +0000358 // Choose the macro defined latest.
359 if (BestLocation.isInvalid() ||
360 (Location.isValid() &&
361 SourceMgr.isBeforeInTranslationUnit(BestLocation, Location))) {
362 BestLocation = Location;
363 BestSpelling = I->first->getName();
364 }
365 }
366 return BestSpelling;
367}
368
Douglas Gregor8d76cca2012-01-04 06:20:15 +0000369void Preprocessor::recomputeCurLexerKind() {
370 if (CurLexer)
371 CurLexerKind = CLK_Lexer;
372 else if (CurPTHLexer)
373 CurLexerKind = CLK_PTHLexer;
374 else if (CurTokenLexer)
375 CurLexerKind = CLK_TokenLexer;
376 else
377 CurLexerKind = CLK_CachingLexer;
378}
379
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +0000380bool Preprocessor::SetCodeCompletionPoint(const FileEntry *File,
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +0000381 unsigned CompleteLine,
382 unsigned CompleteColumn) {
383 assert(File);
384 assert(CompleteLine && CompleteColumn && "Starts from 1:1");
385 assert(!CodeCompletionFile && "Already set");
386
Douglas Gregor53ad6b92009-12-02 06:49:09 +0000387 using llvm::MemoryBuffer;
388
Douglas Gregor53ad6b92009-12-02 06:49:09 +0000389 // Load the actual file's contents.
Douglas Gregor26266da2010-03-16 19:49:24 +0000390 bool Invalid = false;
391 const MemoryBuffer *Buffer = SourceMgr.getMemoryBufferForFile(File, &Invalid);
392 if (Invalid)
Douglas Gregor53ad6b92009-12-02 06:49:09 +0000393 return true;
394
395 // Find the byte position of the truncation point.
396 const char *Position = Buffer->getBufferStart();
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +0000397 for (unsigned Line = 1; Line < CompleteLine; ++Line) {
Douglas Gregor53ad6b92009-12-02 06:49:09 +0000398 for (; *Position; ++Position) {
399 if (*Position != '\r' && *Position != '\n')
400 continue;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +0000401
Douglas Gregor53ad6b92009-12-02 06:49:09 +0000402 // Eat \r\n or \n\r as a single line.
403 if ((Position[1] == '\r' || Position[1] == '\n') &&
404 Position[0] != Position[1])
405 ++Position;
406 ++Position;
407 break;
408 }
409 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +0000410
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +0000411 Position += CompleteColumn - 1;
Argyrios Kyrtzidisee301f92014-10-18 06:23:50 +0000412
413 // If pointing inside the preamble, adjust the position at the beginning of
414 // the file after the preamble.
415 if (SkipMainFilePreamble.first &&
416 SourceMgr.getFileEntryForID(SourceMgr.getMainFileID()) == File) {
417 if (Position - Buffer->getBufferStart() < SkipMainFilePreamble.first)
418 Position = Buffer->getBufferStart() + SkipMainFilePreamble.first;
419 }
420
Argyrios Kyrtzidise62d6822014-10-18 06:19:36 +0000421 if (Position > Buffer->getBufferEnd())
422 Position = Buffer->getBufferEnd();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +0000423
Argyrios Kyrtzidise62d6822014-10-18 06:19:36 +0000424 CodeCompletionFile = File;
425 CodeCompletionOffset = Position - Buffer->getBufferStart();
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +0000426
Argyrios Kyrtzidise62d6822014-10-18 06:19:36 +0000427 std::unique_ptr<MemoryBuffer> NewBuffer =
428 MemoryBuffer::getNewUninitMemBuffer(Buffer->getBufferSize() + 1,
429 Buffer->getBufferIdentifier());
430 char *NewBuf = const_cast<char*>(NewBuffer->getBufferStart());
431 char *NewPos = std::copy(Buffer->getBufferStart(), Position, NewBuf);
432 *NewPos = '\0';
433 std::copy(Position, Buffer->getBufferEnd(), NewPos+1);
434 SourceMgr.overrideFileContents(File, std::move(NewBuffer));
Douglas Gregor53ad6b92009-12-02 06:49:09 +0000435
436 return false;
437}
438
Douglas Gregor11583702010-08-25 17:04:25 +0000439void Preprocessor::CodeCompleteNaturalLanguage() {
Douglas Gregor11583702010-08-25 17:04:25 +0000440 if (CodeComplete)
441 CodeComplete->CodeCompleteNaturalLanguage();
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +0000442 setCodeCompletionReached();
Douglas Gregor11583702010-08-25 17:04:25 +0000443}
444
Benjamin Kramera197fb62010-02-27 17:05:45 +0000445/// getSpelling - This method is used to get the spelling of a token into a
446/// SmallVector. Note that the returned StringRef may not point to the
447/// supplied buffer if a copy can be avoided.
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000448StringRef Preprocessor::getSpelling(const Token &Tok,
449 SmallVectorImpl<char> &Buffer,
Douglas Gregor7bda4b82010-03-16 05:20:39 +0000450 bool *Invalid) const {
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +0000451 // NOTE: this has to be checked *before* testing for an IdentifierInfo.
Jordan Rose7f43ddd2013-01-24 20:50:46 +0000452 if (Tok.isNot(tok::raw_identifier) && !Tok.hasUCN()) {
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +0000453 // Try the fast path.
454 if (const IdentifierInfo *II = Tok.getIdentifierInfo())
455 return II->getName();
456 }
Benjamin Kramera197fb62010-02-27 17:05:45 +0000457
458 // Resize the buffer if we need to copy into it.
459 if (Tok.needsCleaning())
460 Buffer.resize(Tok.getLength());
461
462 const char *Ptr = Buffer.data();
Douglas Gregor7bda4b82010-03-16 05:20:39 +0000463 unsigned Len = getSpelling(Tok, Ptr, Invalid);
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000464 return StringRef(Ptr, Len);
Benjamin Kramera197fb62010-02-27 17:05:45 +0000465}
466
Chris Lattnerb94ec7b2006-07-14 06:54:10 +0000467/// CreateString - Plop the specified string into a scratch buffer and return a
468/// location for it. If specified, the source location provides a source
469/// location for the token.
Dmitri Gribenkob8e9e752012-09-24 21:07:17 +0000470void Preprocessor::CreateString(StringRef Str, Token &Tok,
Abramo Bagnarae398e602011-10-03 18:39:03 +0000471 SourceLocation ExpansionLocStart,
472 SourceLocation ExpansionLocEnd) {
Dmitri Gribenkob8e9e752012-09-24 21:07:17 +0000473 Tok.setLength(Str.size());
Mike Stump11289f42009-09-09 15:08:12 +0000474
Chris Lattner5a7971e2009-01-26 19:29:26 +0000475 const char *DestPtr;
Dmitri Gribenkob8e9e752012-09-24 21:07:17 +0000476 SourceLocation Loc = ScratchBuf->getToken(Str.data(), Str.size(), DestPtr);
Mike Stump11289f42009-09-09 15:08:12 +0000477
Abramo Bagnarae398e602011-10-03 18:39:03 +0000478 if (ExpansionLocStart.isValid())
479 Loc = SourceMgr.createExpansionLoc(Loc, ExpansionLocStart,
Dmitri Gribenkob8e9e752012-09-24 21:07:17 +0000480 ExpansionLocEnd, Str.size());
Chris Lattner5a7971e2009-01-26 19:29:26 +0000481 Tok.setLocation(Loc);
Mike Stump11289f42009-09-09 15:08:12 +0000482
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +0000483 // If this is a raw identifier or a literal token, set the pointer data.
484 if (Tok.is(tok::raw_identifier))
485 Tok.setRawIdentifierData(DestPtr);
486 else if (Tok.isLiteral())
Chris Lattner5a7971e2009-01-26 19:29:26 +0000487 Tok.setLiteralData(DestPtr);
Chris Lattnerb94ec7b2006-07-14 06:54:10 +0000488}
489
Douglas Gregor2b82c2a2011-12-02 01:47:07 +0000490Module *Preprocessor::getCurrentModule() {
Richard Smithbbcc9f02016-08-26 00:14:38 +0000491 if (!getLangOpts().isCompilingModule())
Craig Topperd2d442c2014-05-17 23:10:59 +0000492 return nullptr;
493
David Blaikiebbafb8a2012-03-11 07:00:24 +0000494 return getHeaderSearchInfo().lookupModule(getLangOpts().CurrentModule);
Douglas Gregor2b82c2a2011-12-02 01:47:07 +0000495}
Chris Lattner8a7003c2007-07-16 06:48:38 +0000496
Chris Lattner1f1b0db2007-10-09 22:10:18 +0000497//===----------------------------------------------------------------------===//
498// Preprocessor Initialization Methods
499//===----------------------------------------------------------------------===//
500
Chris Lattner1f1b0db2007-10-09 22:10:18 +0000501/// EnterMainSourceFile - Enter the specified FileID as the main source file,
Nate Begemanf7c3ff62008-01-07 04:01:26 +0000502/// which implicitly adds the builtin defines etc.
Chris Lattnerfb24a3a2010-04-20 20:35:58 +0000503void Preprocessor::EnterMainSourceFile() {
Chris Lattner9ef847b2009-02-13 19:33:24 +0000504 // We do not allow the preprocessor to reenter the main file. Doing so will
505 // cause FileID's to accumulate information from both runs (e.g. #line
506 // information) and predefined macros aren't guaranteed to be set properly.
507 assert(NumEnteredSourceFiles == 0 && "Cannot reenter the main file!");
Chris Lattnerd32480d2009-01-17 06:22:33 +0000508 FileID MainFileID = SourceMgr.getMainFileID();
Mike Stump11289f42009-09-09 15:08:12 +0000509
Argyrios Kyrtzidis9afd4492012-01-05 21:36:25 +0000510 // If MainFileID is loaded it means we loaded an AST file, no need to enter
511 // a main file.
512 if (!SourceMgr.isLoadedFileID(MainFileID)) {
513 // Enter the main file source buffer.
Craig Topperd2d442c2014-05-17 23:10:59 +0000514 EnterSourceFile(MainFileID, nullptr, SourceLocation());
515
Argyrios Kyrtzidis9afd4492012-01-05 21:36:25 +0000516 // If we've been asked to skip bytes in the main file (e.g., as part of a
517 // precompiled preamble), do so now.
518 if (SkipMainFilePreamble.first > 0)
519 CurLexer->SkipBytes(SkipMainFilePreamble.first,
520 SkipMainFilePreamble.second);
521
522 // Tell the header info that the main file was entered. If the file is later
523 // #imported, it won't be re-entered.
524 if (const FileEntry *FE = SourceMgr.getFileEntryForID(MainFileID))
525 HeaderInfo.IncrementIncludeCount(FE);
526 }
Mike Stump11289f42009-09-09 15:08:12 +0000527
Benjamin Kramerd77adb52009-12-31 15:33:09 +0000528 // Preprocess Predefines to populate the initial preprocessor state.
Rafael Espindolad87f8d72014-08-27 20:03:29 +0000529 std::unique_ptr<llvm::MemoryBuffer> SB =
Chris Lattner58c79342010-04-05 22:42:27 +0000530 llvm::MemoryBuffer::getMemBufferCopy(Predefines, "<built-in>");
Douglas Gregor33551892010-08-26 14:07:34 +0000531 assert(SB && "Cannot create predefined source buffer");
David Blaikie50a5f972014-08-29 07:59:55 +0000532 FileID FID = SourceMgr.createFileID(std::move(SB));
Yaron Keren8b563662015-10-03 10:46:20 +0000533 assert(FID.isValid() && "Could not create FileID for predefines?");
Argyrios Kyrtzidis22c22f52013-02-01 16:36:07 +0000534 setPredefinesFileID(FID);
Mike Stump11289f42009-09-09 15:08:12 +0000535
Chris Lattner1f1b0db2007-10-09 22:10:18 +0000536 // Start parsing the predefines.
Craig Topperd2d442c2014-05-17 23:10:59 +0000537 EnterSourceFile(FID, nullptr, SourceLocation());
Erik Verbruggen795eee92017-07-05 09:44:07 +0000538}
Erik Verbruggenb34c79f2017-05-30 11:54:55 +0000539
Erik Verbruggen795eee92017-07-05 09:44:07 +0000540void Preprocessor::replayPreambleConditionalStack() {
Erik Verbruggenb34c79f2017-05-30 11:54:55 +0000541 // Restore the conditional stack from the preamble, if there is one.
542 if (PreambleConditionalStack.isReplaying()) {
543 CurPPLexer->setConditionalLevels(PreambleConditionalStack.getStack());
544 PreambleConditionalStack.doneReplaying();
545 }
Chris Lattner1f1b0db2007-10-09 22:10:18 +0000546}
Chris Lattner8a7003c2007-07-16 06:48:38 +0000547
Daniel Dunbarcb9eaf52010-03-23 05:09:10 +0000548void Preprocessor::EndSourceFile() {
549 // Notify the client that we reached the end of the source file.
550 if (Callbacks)
551 Callbacks->EndOfMainFile();
552}
Chris Lattner677757a2006-06-28 05:26:32 +0000553
554//===----------------------------------------------------------------------===//
555// Lexer Event Handling.
556//===----------------------------------------------------------------------===//
557
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +0000558/// LookUpIdentifierInfo - Given a tok::raw_identifier token, look up the
559/// identifier information for the token and install it into the token,
560/// updating the token kind accordingly.
561IdentifierInfo *Preprocessor::LookUpIdentifierInfo(Token &Identifier) const {
Alp Toker2d57cea2014-05-17 04:53:25 +0000562 assert(!Identifier.getRawIdentifier().empty() && "No raw identifier data!");
Mike Stump11289f42009-09-09 15:08:12 +0000563
Chris Lattnercefc7682006-07-08 08:28:12 +0000564 // Look up this token, see if it is a macro, or if it is a language keyword.
565 IdentifierInfo *II;
Jordan Rose7f43ddd2013-01-24 20:50:46 +0000566 if (!Identifier.needsCleaning() && !Identifier.hasUCN()) {
Chris Lattnercefc7682006-07-08 08:28:12 +0000567 // No cleaning needed, just use the characters from the lexed buffer.
Alp Toker2d57cea2014-05-17 04:53:25 +0000568 II = getIdentifierInfo(Identifier.getRawIdentifier());
Chris Lattnercefc7682006-07-08 08:28:12 +0000569 } else {
570 // Cleaning needed, alloca a buffer, clean into it, then use the buffer.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +0000571 SmallString<64> IdentifierBuffer;
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000572 StringRef CleanedStr = getSpelling(Identifier, IdentifierBuffer);
Jordan Rose7f43ddd2013-01-24 20:50:46 +0000573
574 if (Identifier.hasUCN()) {
575 SmallString<64> UCNIdentifierBuffer;
576 expandUCNs(UCNIdentifierBuffer, CleanedStr);
577 II = getIdentifierInfo(UCNIdentifierBuffer);
578 } else {
579 II = getIdentifierInfo(CleanedStr);
580 }
Chris Lattnercefc7682006-07-08 08:28:12 +0000581 }
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +0000582
583 // Update the token info (identifier info and appropriate token kind).
Chris Lattner8c204872006-10-14 05:19:21 +0000584 Identifier.setIdentifierInfo(II);
Erich Keane33c3d8a2017-06-09 16:29:35 +0000585 if (getLangOpts().MSVCCompat && II->isCPlusPlusOperatorKeyword() &&
586 getSourceManager().isInSystemHeader(Identifier.getLocation()))
587 Identifier.setKind(clang::tok::identifier);
588 else
589 Identifier.setKind(II->getTokenID());
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +0000590
Chris Lattnercefc7682006-07-08 08:28:12 +0000591 return II;
592}
593
John Wiegley1c0675e2011-04-28 01:08:34 +0000594void Preprocessor::SetPoisonReason(IdentifierInfo *II, unsigned DiagID) {
595 PoisonReasons[II] = DiagID;
596}
597
598void Preprocessor::PoisonSEHIdentifiers(bool Poison) {
599 assert(Ident__exception_code && Ident__exception_info);
600 assert(Ident___exception_code && Ident___exception_info);
601 Ident__exception_code->setIsPoisoned(Poison);
602 Ident___exception_code->setIsPoisoned(Poison);
603 Ident_GetExceptionCode->setIsPoisoned(Poison);
604 Ident__exception_info->setIsPoisoned(Poison);
605 Ident___exception_info->setIsPoisoned(Poison);
606 Ident_GetExceptionInfo->setIsPoisoned(Poison);
607 Ident__abnormal_termination->setIsPoisoned(Poison);
608 Ident___abnormal_termination->setIsPoisoned(Poison);
609 Ident_AbnormalTermination->setIsPoisoned(Poison);
610}
611
612void Preprocessor::HandlePoisonedIdentifier(Token & Identifier) {
613 assert(Identifier.getIdentifierInfo() &&
614 "Can't handle identifiers without identifier info!");
615 llvm::DenseMap<IdentifierInfo*,unsigned>::const_iterator it =
616 PoisonReasons.find(Identifier.getIdentifierInfo());
617 if(it == PoisonReasons.end())
618 Diag(Identifier, diag::err_pp_used_poisoned_id);
619 else
620 Diag(Identifier,it->second) << Identifier.getIdentifierInfo();
621}
Chris Lattnercefc7682006-07-08 08:28:12 +0000622
Richard Smith31d51842015-05-14 04:00:59 +0000623/// \brief Returns a diagnostic message kind for reporting a future keyword as
624/// appropriate for the identifier and specified language.
625static diag::kind getFutureCompatDiagKind(const IdentifierInfo &II,
626 const LangOptions &LangOpts) {
627 assert(II.isFutureCompatKeyword() && "diagnostic should not be needed");
628
629 if (LangOpts.CPlusPlus)
630 return llvm::StringSwitch<diag::kind>(II.getName())
631#define CXX11_KEYWORD(NAME, FLAGS) \
632 .Case(#NAME, diag::warn_cxx11_keyword)
Richard Smith6c74e322017-08-13 21:32:33 +0000633#define CXX2A_KEYWORD(NAME, FLAGS) \
634 .Case(#NAME, diag::warn_cxx2a_keyword)
Richard Smith31d51842015-05-14 04:00:59 +0000635#include "clang/Basic/TokenKinds.def"
636 ;
637
638 llvm_unreachable(
639 "Keyword not known to come from a newer Standard or proposed Standard");
640}
641
Richard Smith3dba7eb2016-08-18 01:16:55 +0000642void Preprocessor::updateOutOfDateIdentifier(IdentifierInfo &II) const {
643 assert(II.isOutOfDate() && "not out of date");
644 getExternalSource()->updateOutOfDateIdentifier(II);
645}
646
Chris Lattner677757a2006-06-28 05:26:32 +0000647/// HandleIdentifier - This callback is invoked when the lexer reads an
648/// identifier. This callback looks up the identifier in the map and/or
649/// potentially macro expands it or turns it into a named token (like 'for').
Chris Lattnerad89ec02009-01-21 07:43:11 +0000650///
651/// Note that callers of this method are guarded by checking the
652/// IdentifierInfo's 'isHandleIdentifierCase' bit. If this method changes, the
653/// IdentifierInfo methods that compute these properties will need to change to
654/// match.
Eli Friedman0834a4b2013-09-19 00:41:32 +0000655bool Preprocessor::HandleIdentifier(Token &Identifier) {
Chris Lattner0f1f5052006-07-20 04:16:23 +0000656 assert(Identifier.getIdentifierInfo() &&
657 "Can't handle identifiers without identifier info!");
Mike Stump11289f42009-09-09 15:08:12 +0000658
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000659 IdentifierInfo &II = *Identifier.getIdentifierInfo();
Chris Lattner677757a2006-06-28 05:26:32 +0000660
Douglas Gregor935bc7a22011-10-27 09:33:13 +0000661 // If the information about this identifier is out of date, update it from
662 // the external source.
Douglas Gregor3f568c12012-06-29 18:27:59 +0000663 // We have to treat __VA_ARGS__ in a special way, since it gets
664 // serialized with isPoisoned = true, but our preprocessor may have
665 // unpoisoned it if we're defining a C99 macro.
Douglas Gregor935bc7a22011-10-27 09:33:13 +0000666 if (II.isOutOfDate()) {
Douglas Gregor3f568c12012-06-29 18:27:59 +0000667 bool CurrentIsPoisoned = false;
668 if (&II == Ident__VA_ARGS__)
669 CurrentIsPoisoned = Ident__VA_ARGS__->isPoisoned();
670
Richard Smith3dba7eb2016-08-18 01:16:55 +0000671 updateOutOfDateIdentifier(II);
Douglas Gregor935bc7a22011-10-27 09:33:13 +0000672 Identifier.setKind(II.getTokenID());
Douglas Gregor3f568c12012-06-29 18:27:59 +0000673
674 if (&II == Ident__VA_ARGS__)
675 II.setIsPoisoned(CurrentIsPoisoned);
Douglas Gregor935bc7a22011-10-27 09:33:13 +0000676 }
677
Chris Lattner677757a2006-06-28 05:26:32 +0000678 // If this identifier was poisoned, and if it was not produced from a macro
679 // expansion, emit an error.
Ted Kremeneka2c3c8d2008-11-19 22:43:49 +0000680 if (II.isPoisoned() && CurPPLexer) {
John Wiegley1c0675e2011-04-28 01:08:34 +0000681 HandlePoisonedIdentifier(Identifier);
Chris Lattner8ff71992006-07-06 05:17:39 +0000682 }
Mike Stump11289f42009-09-09 15:08:12 +0000683
Chris Lattner78186052006-07-09 00:45:31 +0000684 // If this is a macro to be expanded, do it.
Richard Smith20e883e2015-04-29 23:20:19 +0000685 if (MacroDefinition MD = getMacroDefinition(&II)) {
686 auto *MI = MD.getMacroInfo();
Richard Smithf5ec2ac2015-04-29 23:40:48 +0000687 assert(MI && "macro definition with no macro info?");
Abramo Bagnara123bec82012-01-01 22:01:04 +0000688 if (!DisableMacroExpansion) {
Richard Smith181879c2012-12-12 02:46:14 +0000689 if (!Identifier.isExpandDisabled() && MI->isEnabled()) {
Eli Friedman0834a4b2013-09-19 00:41:32 +0000690 // C99 6.10.3p10: If the preprocessing token immediately after the
691 // macro name isn't a '(', this macro should not be expanded.
692 if (!MI->isFunctionLike() || isNextPPTokenLParen())
693 return HandleMacroExpandedIdentifier(Identifier, MD);
Chris Lattner6e4bf522006-07-27 06:59:25 +0000694 } else {
695 // C99 6.10.3.4p2 says that a disabled macro may never again be
696 // expanded, even if it's in a context where it could be expanded in the
697 // future.
Chris Lattner146762e2007-07-20 16:59:19 +0000698 Identifier.setFlag(Token::DisableExpand);
Richard Smith181879c2012-12-12 02:46:14 +0000699 if (MI->isObjectLike() || isNextPPTokenLParen())
700 Diag(Identifier, diag::pp_disabled_macro_expansion);
Chris Lattner6e4bf522006-07-27 06:59:25 +0000701 }
702 }
Chris Lattner063400e2006-10-14 19:54:15 +0000703 }
Chris Lattner677757a2006-06-28 05:26:32 +0000704
Richard Smith31d51842015-05-14 04:00:59 +0000705 // If this identifier is a keyword in a newer Standard or proposed Standard,
706 // produce a warning. Don't warn if we're not considering macro expansion,
707 // since this identifier might be the name of a macro.
Richard Smith4dd85d62011-10-11 19:57:52 +0000708 // FIXME: This warning is disabled in cases where it shouldn't be, like
709 // "#define constexpr constexpr", "int constexpr;"
Richard Smith31d51842015-05-14 04:00:59 +0000710 if (II.isFutureCompatKeyword() && !DisableMacroExpansion) {
711 Diag(Identifier, getFutureCompatDiagKind(II, getLangOpts()))
712 << II.getName();
Richard Smith4dd85d62011-10-11 19:57:52 +0000713 // Don't diagnose this keyword again in this translation unit.
Richard Smith31d51842015-05-14 04:00:59 +0000714 II.setIsFutureCompatKeyword(false);
Richard Smith4dd85d62011-10-11 19:57:52 +0000715 }
716
Chris Lattner677757a2006-06-28 05:26:32 +0000717 // If this is an extension token, diagnose its use.
Steve Naroffc84e8b72008-09-02 18:50:17 +0000718 // We avoid diagnosing tokens that originate from macro definitions.
Eli Friedman6bba2ad2009-04-28 03:59:15 +0000719 // FIXME: This warning is disabled in cases where it shouldn't be,
720 // like "#define TY typeof", "TY(1) x".
721 if (II.isExtensionToken() && !DisableMacroExpansion)
Chris Lattner53621a52007-06-13 20:44:40 +0000722 Diag(Identifier, diag::ext_token_used);
Douglas Gregoraf5c4842011-09-07 23:11:54 +0000723
Douglas Gregor594b8c92013-11-07 22:55:02 +0000724 // If this is the 'import' contextual keyword following an '@', note
Ted Kremenekc1e4dd02012-03-01 22:07:04 +0000725 // that the next token indicates a module name.
Douglas Gregor8d76cca2012-01-04 06:20:15 +0000726 //
Douglas Gregorc50d4922012-12-11 22:11:52 +0000727 // Note that we do not treat 'import' as a contextual
Ted Kremenekc1e4dd02012-03-01 22:07:04 +0000728 // keyword when we're in a caching lexer, because caching lexers only get
729 // used in contexts where import declarations are disallowed.
Richard Smith49cc1cc2016-08-18 21:59:42 +0000730 //
731 // Likewise if this is the C++ Modules TS import keyword.
732 if (((LastTokenWasAt && II.isModulesImport()) ||
733 Identifier.is(tok::kw_import)) &&
734 !InMacroArgs && !DisableMacroExpansion &&
735 (getLangOpts().Modules || getLangOpts().DebuggerSupport) &&
Douglas Gregor594b8c92013-11-07 22:55:02 +0000736 CurLexerKind != CLK_CachingLexer) {
Douglas Gregoraf5c4842011-09-07 23:11:54 +0000737 ModuleImportLoc = Identifier.getLocation();
Douglas Gregor1805b8a2011-11-30 04:26:53 +0000738 ModuleImportPath.clear();
739 ModuleImportExpectsIdentifier = true;
Douglas Gregoraf5c4842011-09-07 23:11:54 +0000740 CurLexerKind = CLK_LexAfterModuleImport;
741 }
Eli Friedman0834a4b2013-09-19 00:41:32 +0000742 return true;
Douglas Gregor08142532011-08-26 23:56:07 +0000743}
744
Eli Friedman0834a4b2013-09-19 00:41:32 +0000745void Preprocessor::Lex(Token &Result) {
Yaron Keren716f3a62015-09-29 16:51:08 +0000746 // We loop here until a lex function returns a token; this avoids recursion.
Eli Friedman0834a4b2013-09-19 00:41:32 +0000747 bool ReturnedToken;
748 do {
749 switch (CurLexerKind) {
750 case CLK_Lexer:
751 ReturnedToken = CurLexer->Lex(Result);
752 break;
753 case CLK_PTHLexer:
754 ReturnedToken = CurPTHLexer->Lex(Result);
755 break;
756 case CLK_TokenLexer:
757 ReturnedToken = CurTokenLexer->Lex(Result);
758 break;
759 case CLK_CachingLexer:
760 CachingLex(Result);
761 ReturnedToken = true;
762 break;
763 case CLK_LexAfterModuleImport:
764 LexAfterModuleImport(Result);
765 ReturnedToken = true;
766 break;
767 }
768 } while (!ReturnedToken);
Douglas Gregor594b8c92013-11-07 22:55:02 +0000769
Vassil Vassilev644ea612016-07-27 14:56:59 +0000770 if (Result.is(tok::code_completion))
771 setCodeCompletionIdentifierInfo(Result.getIdentifierInfo());
772
Douglas Gregor594b8c92013-11-07 22:55:02 +0000773 LastTokenWasAt = Result.is(tok::at);
Eli Friedman0834a4b2013-09-19 00:41:32 +0000774}
775
Douglas Gregorda82e702012-01-03 19:32:59 +0000776/// \brief Lex a token following the 'import' contextual keyword.
Douglas Gregor22d09742012-01-03 18:04:46 +0000777///
Douglas Gregoraf5c4842011-09-07 23:11:54 +0000778void Preprocessor::LexAfterModuleImport(Token &Result) {
779 // Figure out what kind of lexer we actually have.
Douglas Gregor8d76cca2012-01-04 06:20:15 +0000780 recomputeCurLexerKind();
Douglas Gregoraf5c4842011-09-07 23:11:54 +0000781
782 // Lex the next token.
783 Lex(Result);
784
Douglas Gregor08142532011-08-26 23:56:07 +0000785 // The token sequence
786 //
Douglas Gregor22d09742012-01-03 18:04:46 +0000787 // import identifier (. identifier)*
788 //
Douglas Gregorda82e702012-01-03 19:32:59 +0000789 // indicates a module import directive. We already saw the 'import'
790 // contextual keyword, so now we're looking for the identifiers.
Douglas Gregor1805b8a2011-11-30 04:26:53 +0000791 if (ModuleImportExpectsIdentifier && Result.getKind() == tok::identifier) {
792 // We expected to see an identifier here, and we did; continue handling
793 // identifiers.
794 ModuleImportPath.push_back(std::make_pair(Result.getIdentifierInfo(),
795 Result.getLocation()));
796 ModuleImportExpectsIdentifier = false;
797 CurLexerKind = CLK_LexAfterModuleImport;
Douglas Gregor08142532011-08-26 23:56:07 +0000798 return;
Douglas Gregor1805b8a2011-11-30 04:26:53 +0000799 }
Douglas Gregor08142532011-08-26 23:56:07 +0000800
Douglas Gregor1805b8a2011-11-30 04:26:53 +0000801 // If we're expecting a '.' or a ';', and we got a '.', then wait until we
Richard Smith49cc1cc2016-08-18 21:59:42 +0000802 // see the next identifier. (We can also see a '[[' that begins an
803 // attribute-specifier-seq here under the C++ Modules TS.)
Douglas Gregor1805b8a2011-11-30 04:26:53 +0000804 if (!ModuleImportExpectsIdentifier && Result.getKind() == tok::period) {
805 ModuleImportExpectsIdentifier = true;
806 CurLexerKind = CLK_LexAfterModuleImport;
807 return;
808 }
809
810 // If we have a non-empty module path, load the named module.
Sean Callanan87596492014-12-09 23:47:56 +0000811 if (!ModuleImportPath.empty()) {
Richard Smithbbcc9f02016-08-26 00:14:38 +0000812 // Under the Modules TS, the dot is just part of the module name, and not
813 // a real hierarachy separator. Flatten such module names now.
814 //
815 // FIXME: Is this the right level to be performing this transformation?
816 std::string FlatModuleName;
817 if (getLangOpts().ModulesTS) {
818 for (auto &Piece : ModuleImportPath) {
819 if (!FlatModuleName.empty())
820 FlatModuleName += ".";
821 FlatModuleName += Piece.first->getName();
822 }
823 SourceLocation FirstPathLoc = ModuleImportPath[0].second;
824 ModuleImportPath.clear();
825 ModuleImportPath.push_back(
826 std::make_pair(getIdentifierInfo(FlatModuleName), FirstPathLoc));
827 }
828
Sean Callanan87596492014-12-09 23:47:56 +0000829 Module *Imported = nullptr;
Richard Smith753e0072015-04-27 23:21:38 +0000830 if (getLangOpts().Modules) {
Sean Callanan87596492014-12-09 23:47:56 +0000831 Imported = TheModuleLoader.loadModule(ModuleImportLoc,
832 ModuleImportPath,
Richard Smith10434f32015-05-02 02:08:26 +0000833 Module::Hidden,
Sean Callanan87596492014-12-09 23:47:56 +0000834 /*IsIncludeDirective=*/false);
Richard Smitha7e2cc62015-05-01 01:53:09 +0000835 if (Imported)
836 makeModuleVisible(Imported, ModuleImportLoc);
Richard Smith753e0072015-04-27 23:21:38 +0000837 }
Sean Callanan87596492014-12-09 23:47:56 +0000838 if (Callbacks && (getLangOpts().Modules || getLangOpts().DebuggerSupport))
Argyrios Kyrtzidis19d78b72012-09-29 01:06:10 +0000839 Callbacks->moduleImport(ModuleImportLoc, ModuleImportPath, Imported);
840 }
Chris Lattner677757a2006-06-28 05:26:32 +0000841}
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000842
Richard Smitha7e2cc62015-05-01 01:53:09 +0000843void Preprocessor::makeModuleVisible(Module *M, SourceLocation Loc) {
Richard Smith04765ae2015-05-21 01:20:10 +0000844 CurSubmoduleState->VisibleModules.setVisible(
Richard Smitha7e2cc62015-05-01 01:53:09 +0000845 M, Loc, [](Module *) {},
846 [&](ArrayRef<Module *> Path, Module *Conflict, StringRef Message) {
847 // FIXME: Include the path in the diagnostic.
848 // FIXME: Include the import location for the conflicting module.
849 Diag(ModuleImportLoc, diag::warn_module_conflict)
850 << Path[0]->getFullModuleName()
851 << Conflict->getFullModuleName()
852 << Message;
853 });
854
855 // Add this module to the imports list of the currently-built submodule.
Richard Smithdbbc5232015-05-14 02:25:44 +0000856 if (!BuildingSubmoduleStack.empty() && M != BuildingSubmoduleStack.back().M)
Richard Smith38477db2015-05-02 00:45:56 +0000857 BuildingSubmoduleStack.back().M->Imports.insert(M);
Richard Smitha7e2cc62015-05-01 01:53:09 +0000858}
859
Andy Gibbs58905d22012-11-17 19:15:38 +0000860bool Preprocessor::FinishLexStringLiteral(Token &Result, std::string &String,
Andy Gibbsa8df57a2012-11-17 19:16:52 +0000861 const char *DiagnosticTag,
Andy Gibbs58905d22012-11-17 19:15:38 +0000862 bool AllowMacroExpansion) {
863 // We need at least one string literal.
864 if (Result.isNot(tok::string_literal)) {
Andy Gibbsa8df57a2012-11-17 19:16:52 +0000865 Diag(Result, diag::err_expected_string_literal)
866 << /*Source='in...'*/0 << DiagnosticTag;
Andy Gibbs58905d22012-11-17 19:15:38 +0000867 return false;
868 }
869
870 // Lex string literal tokens, optionally with macro expansion.
871 SmallVector<Token, 4> StrToks;
872 do {
873 StrToks.push_back(Result);
874
875 if (Result.hasUDSuffix())
876 Diag(Result, diag::err_invalid_string_udl);
877
878 if (AllowMacroExpansion)
879 Lex(Result);
880 else
881 LexUnexpandedToken(Result);
882 } while (Result.is(tok::string_literal));
883
884 // Concatenate and parse the strings.
Craig Topper9d5583e2014-06-26 04:58:39 +0000885 StringLiteralParser Literal(StrToks, *this);
Andy Gibbs58905d22012-11-17 19:15:38 +0000886 assert(Literal.isAscii() && "Didn't allow wide strings in");
887
888 if (Literal.hadError)
889 return false;
890
891 if (Literal.Pascal) {
Andy Gibbsa8df57a2012-11-17 19:16:52 +0000892 Diag(StrToks[0].getLocation(), diag::err_expected_string_literal)
893 << /*Source='in...'*/0 << DiagnosticTag;
Andy Gibbs58905d22012-11-17 19:15:38 +0000894 return false;
895 }
896
897 String = Literal.GetString();
898 return true;
899}
900
Reid Klecknerc0dca6d2014-02-12 23:50:26 +0000901bool Preprocessor::parseSimpleIntegerLiteral(Token &Tok, uint64_t &Value) {
902 assert(Tok.is(tok::numeric_constant));
903 SmallString<8> IntegerBuffer;
904 bool NumberInvalid = false;
905 StringRef Spelling = getSpelling(Tok, IntegerBuffer, &NumberInvalid);
906 if (NumberInvalid)
907 return false;
908 NumericLiteralParser Literal(Spelling, Tok.getLocation(), *this);
909 if (Literal.hadError || !Literal.isIntegerLiteral() || Literal.hasUDSuffix())
910 return false;
911 llvm::APInt APVal(64, 0);
912 if (Literal.GetIntegerValue(APVal))
913 return false;
914 Lex(Tok);
915 Value = APVal.getLimitedValue();
916 return true;
917}
918
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000919void Preprocessor::addCommentHandler(CommentHandler *Handler) {
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000920 assert(Handler && "NULL comment handler");
921 assert(std::find(CommentHandlers.begin(), CommentHandlers.end(), Handler) ==
922 CommentHandlers.end() && "Comment handler already registered");
923 CommentHandlers.push_back(Handler);
924}
925
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000926void Preprocessor::removeCommentHandler(CommentHandler *Handler) {
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000927 std::vector<CommentHandler *>::iterator Pos
928 = std::find(CommentHandlers.begin(), CommentHandlers.end(), Handler);
929 assert(Pos != CommentHandlers.end() && "Comment handler not registered");
930 CommentHandlers.erase(Pos);
931}
932
Chris Lattner87d02082010-01-18 22:35:47 +0000933bool Preprocessor::HandleComment(Token &result, SourceRange Comment) {
934 bool AnyPendingTokens = false;
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000935 for (std::vector<CommentHandler *>::iterator H = CommentHandlers.begin(),
936 HEnd = CommentHandlers.end();
Chris Lattner87d02082010-01-18 22:35:47 +0000937 H != HEnd; ++H) {
938 if ((*H)->HandleComment(*this, Comment))
939 AnyPendingTokens = true;
940 }
941 if (!AnyPendingTokens || getCommentRetentionState())
942 return false;
943 Lex(result);
944 return true;
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000945}
946
Angel Garcia Gomez637d1e62015-10-20 13:23:58 +0000947ModuleLoader::~ModuleLoader() { }
Douglas Gregor08142532011-08-26 23:56:07 +0000948
Angel Garcia Gomez637d1e62015-10-20 13:23:58 +0000949CommentHandler::~CommentHandler() { }
Douglas Gregor7f6d60d2010-03-19 16:15:56 +0000950
Angel Garcia Gomez637d1e62015-10-20 13:23:58 +0000951CodeCompletionHandler::~CodeCompletionHandler() { }
Douglas Gregor3a7ad252010-08-24 19:08:16 +0000952
Argyrios Kyrtzidisf3d587e2012-12-04 07:27:05 +0000953void Preprocessor::createPreprocessingRecord() {
Douglas Gregor7f6d60d2010-03-19 16:15:56 +0000954 if (Record)
955 return;
956
Argyrios Kyrtzidisf3d587e2012-12-04 07:27:05 +0000957 Record = new PreprocessingRecord(getSourceManager());
Craig Topperb8a70532014-09-10 04:53:53 +0000958 addPPCallbacks(std::unique_ptr<PPCallbacks>(Record));
Douglas Gregor7f6d60d2010-03-19 16:15:56 +0000959}