blob: cd00be8adaf1f933d77560d6f1291bd043405423 [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"
Chris Lattnerb8761832006-06-24 21:31:03 +000041#include "clang/Lex/Pragma.h"
Douglas Gregor7f6d60d2010-03-19 16:15:56 +000042#include "clang/Lex/PreprocessingRecord.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000043#include "clang/Lex/PreprocessorOptions.h"
Chris Lattner0b8cfc22006-06-28 06:49:17 +000044#include "clang/Lex/ScratchBuffer.h"
Chris Lattner5cd83512008-10-05 20:40:30 +000045#include "llvm/ADT/APFloat.h"
Jordan Rose7f43ddd2013-01-24 20:50:46 +000046#include "llvm/ADT/STLExtras.h"
Chandler Carruth5553d0d2014-01-07 11:51:46 +000047#include "llvm/ADT/SmallString.h"
Jordan Rose7f43ddd2013-01-24 20:50:46 +000048#include "llvm/ADT/StringExtras.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000049#include "llvm/Support/Capacity.h"
Dmitri Gribenko9feeef42013-01-30 12:06:08 +000050#include "llvm/Support/ConvertUTF.h"
Chris Lattner8a7003c2007-07-16 06:48:38 +000051#include "llvm/Support/MemoryBuffer.h"
Benjamin Kramer89b422c2009-08-23 12:08:50 +000052#include "llvm/Support/raw_ostream.h"
Chris Lattner22eb9722006-06-18 05:43:12 +000053using namespace clang;
54
55//===----------------------------------------------------------------------===//
Douglas Gregor9882a5a2010-01-04 19:18:44 +000056ExternalPreprocessorSource::~ExternalPreprocessorSource() { }
Chris Lattner22eb9722006-06-18 05:43:12 +000057
Dmitri Gribenkof8579502013-01-12 19:30:44 +000058Preprocessor::Preprocessor(IntrusiveRefCntPtr<PreprocessorOptions> PPOpts,
Douglas Gregor1452ff12012-10-24 17:46:57 +000059 DiagnosticsEngine &diags, LangOptions &opts,
Alp Toker96637802014-05-02 03:43:38 +000060 SourceManager &SM, HeaderSearch &Headers,
61 ModuleLoader &TheModuleLoader,
David Blaikie687cd952013-01-16 23:13:36 +000062 IdentifierInfoLookup *IILookup, bool OwnsHeaders,
Alp Toker1ae02f62014-05-02 03:43:30 +000063 TranslationUnitKind TUKind)
Craig Topper4b566922014-06-09 02:04:02 +000064 : PPOpts(PPOpts), Diags(&diags), LangOpts(opts), Target(nullptr),
Craig Topperbe250302014-09-12 05:19:24 +000065 FileMgr(Headers.getFileMgr()), SourceMgr(SM),
66 ScratchBuf(new ScratchBuffer(SourceMgr)),HeaderInfo(Headers),
Craig Topperd2d442c2014-05-17 23:10:59 +000067 TheModuleLoader(TheModuleLoader), ExternalSource(nullptr),
Craig Topperbe250302014-09-12 05:19:24 +000068 Identifiers(opts, IILookup),
69 PragmaHandlers(new PragmaNamespace(StringRef())),
70 IncrementalProcessing(false), TUKind(TUKind),
Craig Topperd2d442c2014-05-17 23:10:59 +000071 CodeComplete(nullptr), CodeCompletionFile(nullptr),
72 CodeCompletionOffset(0), LastTokenWasAt(false),
73 ModuleImportExpectsIdentifier(false), CodeCompletionReached(0),
Richard Smith3c1a41a2014-12-02 00:08:08 +000074 MainFileDir(nullptr), SkipMainFilePreamble(0, true), CurPPLexer(nullptr),
Craig Topperd2d442c2014-05-17 23:10:59 +000075 CurDirLookup(nullptr), CurLexerKind(CLK_Lexer), CurSubmodule(nullptr),
Richard Smith20e883e2015-04-29 23:20:19 +000076 Callbacks(nullptr), MacroArgCache(nullptr), Record(nullptr),
Richard Smithee0c4c12014-07-24 01:13:23 +000077 MIChainHead(nullptr), DeserialMIChainHead(nullptr) {
Daniel Dunbar0c6c9302009-11-11 21:44:21 +000078 OwnsHeaderSearch = OwnsHeaders;
Douglas Gregor83297df2011-09-01 23:39:15 +000079
Douglas Gregor83297df2011-09-01 23:39:15 +000080 CounterValue = 0; // __COUNTER__ starts at 0.
81
82 // Clear stats.
83 NumDirectives = NumDefined = NumUndefined = NumPragma = 0;
84 NumIf = NumElse = NumEndif = 0;
85 NumEnteredSourceFiles = 0;
86 NumMacroExpanded = NumFnMacroExpanded = NumBuiltinMacroExpanded = 0;
87 NumFastMacroExpanded = NumTokenPaste = NumFastTokenPaste = 0;
88 MaxIncludeStackDepth = 0;
89 NumSkipped = 0;
90
91 // Default to discarding comments.
92 KeepComments = false;
93 KeepMacroComments = false;
94 SuppressIncludeNotFoundError = false;
95
96 // Macro expansion is enabled.
97 DisableMacroExpansion = false;
David Blaikied5321242012-06-06 18:52:13 +000098 MacroExpansionInDirectivesOverride = false;
Douglas Gregor83297df2011-09-01 23:39:15 +000099 InMacroArgs = false;
Argyrios Kyrtzidisf1b64c62012-04-03 16:47:40 +0000100 InMacroArgPreExpansion = false;
Douglas Gregor83297df2011-09-01 23:39:15 +0000101 NumCachedTokenLexers = 0;
Jordan Rosede1a2922012-06-08 18:06:21 +0000102 PragmasEnabled = true;
Eric Christopher5e4696d2013-01-16 20:09:36 +0000103 ParsingIfOrElifDirective = false;
Jordan Rose324ec422013-01-31 19:26:01 +0000104 PreprocessedOutput = false;
Jordan Rosede1a2922012-06-08 18:06:21 +0000105
Douglas Gregor83297df2011-09-01 23:39:15 +0000106 CachedLexPos = 0;
Eric Christopher5e4696d2013-01-16 20:09:36 +0000107
Douglas Gregor83297df2011-09-01 23:39:15 +0000108 // We haven't read anything from the external source.
109 ReadMacrosFromExternalSource = false;
Richard Smith20e883e2015-04-29 23:20:19 +0000110 // We might already have some macros from an imported module (via a PCH or
111 // preamble) if modules is enabled.
112 MacroVisibilityGeneration = LangOpts.Modules ? 1 : 0;
Douglas Gregor83297df2011-09-01 23:39:15 +0000113
Douglas Gregor83297df2011-09-01 23:39:15 +0000114 // "Poison" __VA_ARGS__, which can only appear in the expansion of a macro.
115 // This gets unpoisoned where it is allowed.
116 (Ident__VA_ARGS__ = getIdentifierInfo("__VA_ARGS__"))->setIsPoisoned();
117 SetPoisonReason(Ident__VA_ARGS__,diag::ext_pp_bad_vaargs_use);
118
119 // Initialize the pragma handlers.
Douglas Gregor83297df2011-09-01 23:39:15 +0000120 RegisterBuiltinPragmas();
121
122 // Initialize builtin macros like __LINE__ and friends.
123 RegisterBuiltinMacros();
124
David Blaikiebbafb8a2012-03-11 07:00:24 +0000125 if(LangOpts.Borland) {
Douglas Gregor83297df2011-09-01 23:39:15 +0000126 Ident__exception_info = getIdentifierInfo("_exception_info");
127 Ident___exception_info = getIdentifierInfo("__exception_info");
128 Ident_GetExceptionInfo = getIdentifierInfo("GetExceptionInformation");
129 Ident__exception_code = getIdentifierInfo("_exception_code");
130 Ident___exception_code = getIdentifierInfo("__exception_code");
131 Ident_GetExceptionCode = getIdentifierInfo("GetExceptionCode");
132 Ident__abnormal_termination = getIdentifierInfo("_abnormal_termination");
133 Ident___abnormal_termination = getIdentifierInfo("__abnormal_termination");
134 Ident_AbnormalTermination = getIdentifierInfo("AbnormalTermination");
135 } else {
Craig Topperd2d442c2014-05-17 23:10:59 +0000136 Ident__exception_info = Ident__exception_code = nullptr;
137 Ident__abnormal_termination = Ident___exception_info = nullptr;
138 Ident___exception_code = Ident___abnormal_termination = nullptr;
139 Ident_GetExceptionInfo = Ident_GetExceptionCode = nullptr;
140 Ident_AbnormalTermination = nullptr;
Douglas Gregor89929282012-01-30 06:01:29 +0000141 }
Argyrios Kyrtzidis3c9aaf12012-06-02 18:08:09 +0000142}
143
144Preprocessor::~Preprocessor() {
145 assert(BacktrackPositions.empty() && "EnableBacktrack/Backtrack imbalance!");
146
Benjamin Kramer329c5962014-03-15 16:40:40 +0000147 IncludeMacroStack.clear();
Argyrios Kyrtzidis3c9aaf12012-06-02 18:08:09 +0000148
Richard Smith73a29662014-07-24 03:25:00 +0000149 // Destroy any macro definitions.
150 while (MacroInfoChain *I = MIChainHead) {
151 MIChainHead = I->Next;
152 I->~MacroInfoChain();
153 }
Argyrios Kyrtzidis3c9aaf12012-06-02 18:08:09 +0000154
155 // Free any cached macro expanders.
Nico Weber5f5b9412014-05-09 18:09:42 +0000156 // This populates MacroArgCache, so all TokenLexers need to be destroyed
157 // before the code below that frees up the MacroArgCache list.
David Blaikie6d5038c2014-08-29 19:36:52 +0000158 std::fill(TokenLexerCache, TokenLexerCache + NumCachedTokenLexers, nullptr);
Nico Weber5f5b9412014-05-09 18:09:42 +0000159 CurTokenLexer.reset();
Argyrios Kyrtzidis3c9aaf12012-06-02 18:08:09 +0000160
Richard Smith73a29662014-07-24 03:25:00 +0000161 while (DeserializedMacroInfoChain *I = DeserialMIChainHead) {
162 DeserialMIChainHead = I->Next;
163 I->~DeserializedMacroInfoChain();
164 }
Argyrios Kyrtzidisd48b91d2013-04-30 05:05:35 +0000165
Argyrios Kyrtzidis3c9aaf12012-06-02 18:08:09 +0000166 // Free any cached MacroArgs.
Nico Weber5f5b9412014-05-09 18:09:42 +0000167 for (MacroArgs *ArgList = MacroArgCache; ArgList;)
Argyrios Kyrtzidis3c9aaf12012-06-02 18:08:09 +0000168 ArgList = ArgList->deallocate();
169
Argyrios Kyrtzidis3c9aaf12012-06-02 18:08:09 +0000170 // Delete the header search info, if we own it.
171 if (OwnsHeaderSearch)
172 delete &HeaderInfo;
Argyrios Kyrtzidis3c9aaf12012-06-02 18:08:09 +0000173}
174
175void Preprocessor::Initialize(const TargetInfo &Target) {
176 assert((!this->Target || this->Target == &Target) &&
177 "Invalid override of target information");
178 this->Target = &Target;
Douglas Gregor89929282012-01-30 06:01:29 +0000179
Argyrios Kyrtzidis3c9aaf12012-06-02 18:08:09 +0000180 // Initialize information about built-ins.
181 BuiltinInfo.InitializeTarget(Target);
Douglas Gregor89929282012-01-30 06:01:29 +0000182 HeaderInfo.setTarget(Target);
Douglas Gregor83297df2011-09-01 23:39:15 +0000183}
184
Ted Kremenekeeccb302014-08-27 15:14:15 +0000185void Preprocessor::InitializeForModelFile() {
186 NumEnteredSourceFiles = 0;
187
188 // Reset pragmas
David Blaikie9f0af9d2014-09-15 21:31:42 +0000189 PragmaHandlersBackup = std::move(PragmaHandlers);
Craig Topperbe250302014-09-12 05:19:24 +0000190 PragmaHandlers = llvm::make_unique<PragmaNamespace>(StringRef());
Ted Kremenekeeccb302014-08-27 15:14:15 +0000191 RegisterBuiltinPragmas();
192
193 // Reset PredefinesFileID
194 PredefinesFileID = FileID();
195}
196
197void Preprocessor::FinalizeForModelFile() {
198 NumEnteredSourceFiles = 1;
199
David Blaikie9f0af9d2014-09-15 21:31:42 +0000200 PragmaHandlers = std::move(PragmaHandlersBackup);
Ted Kremenekeeccb302014-08-27 15:14:15 +0000201}
202
Ted Kremeneka5c2c272009-02-12 03:26:59 +0000203void Preprocessor::setPTHManager(PTHManager* pm) {
204 PTH.reset(pm);
Douglas Gregord2eb58a2009-10-16 18:18:30 +0000205 FileMgr.addStatCache(PTH->createStatCache());
Ted Kremeneka5c2c272009-02-12 03:26:59 +0000206}
207
Chris Lattner146762e2007-07-20 16:59:19 +0000208void Preprocessor::DumpToken(const Token &Tok, bool DumpFlags) const {
Benjamin Kramer89b422c2009-08-23 12:08:50 +0000209 llvm::errs() << tok::getTokenName(Tok.getKind()) << " '"
210 << getSpelling(Tok) << "'";
Mike Stump11289f42009-09-09 15:08:12 +0000211
Chris Lattnerd01e2912006-06-18 16:22:51 +0000212 if (!DumpFlags) return;
Mike Stump11289f42009-09-09 15:08:12 +0000213
Benjamin Kramer89b422c2009-08-23 12:08:50 +0000214 llvm::errs() << "\t";
Chris Lattnerd01e2912006-06-18 16:22:51 +0000215 if (Tok.isAtStartOfLine())
Benjamin Kramer89b422c2009-08-23 12:08:50 +0000216 llvm::errs() << " [StartOfLine]";
Chris Lattnerd01e2912006-06-18 16:22:51 +0000217 if (Tok.hasLeadingSpace())
Benjamin Kramer89b422c2009-08-23 12:08:50 +0000218 llvm::errs() << " [LeadingSpace]";
Chris Lattner6e4bf522006-07-27 06:59:25 +0000219 if (Tok.isExpandDisabled())
Benjamin Kramer89b422c2009-08-23 12:08:50 +0000220 llvm::errs() << " [ExpandDisabled]";
Chris Lattnerd01e2912006-06-18 16:22:51 +0000221 if (Tok.needsCleaning()) {
Chris Lattner50b497e2006-06-18 16:32:35 +0000222 const char *Start = SourceMgr.getCharacterData(Tok.getLocation());
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000223 llvm::errs() << " [UnClean='" << StringRef(Start, Tok.getLength())
Benjamin Kramer89b422c2009-08-23 12:08:50 +0000224 << "']";
Chris Lattnerd01e2912006-06-18 16:22:51 +0000225 }
Mike Stump11289f42009-09-09 15:08:12 +0000226
Benjamin Kramer89b422c2009-08-23 12:08:50 +0000227 llvm::errs() << "\tLoc=<";
Chris Lattner615315f2007-12-09 20:31:55 +0000228 DumpLocation(Tok.getLocation());
Benjamin Kramer89b422c2009-08-23 12:08:50 +0000229 llvm::errs() << ">";
Chris Lattner615315f2007-12-09 20:31:55 +0000230}
231
232void Preprocessor::DumpLocation(SourceLocation Loc) const {
Chris Lattnerf1ca7d32009-01-27 07:57:44 +0000233 Loc.dump(SourceMgr);
Chris Lattnerd01e2912006-06-18 16:22:51 +0000234}
235
236void Preprocessor::DumpMacro(const MacroInfo &MI) const {
Benjamin Kramer89b422c2009-08-23 12:08:50 +0000237 llvm::errs() << "MACRO: ";
Chris Lattnerd01e2912006-06-18 16:22:51 +0000238 for (unsigned i = 0, e = MI.getNumTokens(); i != e; ++i) {
239 DumpToken(MI.getReplacementToken(i));
Benjamin Kramer89b422c2009-08-23 12:08:50 +0000240 llvm::errs() << " ";
Chris Lattnerd01e2912006-06-18 16:22:51 +0000241 }
Benjamin Kramer89b422c2009-08-23 12:08:50 +0000242 llvm::errs() << "\n";
Chris Lattnerd01e2912006-06-18 16:22:51 +0000243}
244
Chris Lattner22eb9722006-06-18 05:43:12 +0000245void Preprocessor::PrintStats() {
Benjamin Kramer89b422c2009-08-23 12:08:50 +0000246 llvm::errs() << "\n*** Preprocessor Stats:\n";
247 llvm::errs() << NumDirectives << " directives found:\n";
248 llvm::errs() << " " << NumDefined << " #define.\n";
249 llvm::errs() << " " << NumUndefined << " #undef.\n";
250 llvm::errs() << " #include/#include_next/#import:\n";
251 llvm::errs() << " " << NumEnteredSourceFiles << " source files entered.\n";
252 llvm::errs() << " " << MaxIncludeStackDepth << " max include stack depth\n";
253 llvm::errs() << " " << NumIf << " #if/#ifndef/#ifdef.\n";
254 llvm::errs() << " " << NumElse << " #else/#elif.\n";
255 llvm::errs() << " " << NumEndif << " #endif.\n";
256 llvm::errs() << " " << NumPragma << " #pragma.\n";
257 llvm::errs() << NumSkipped << " #if/#ifndef#ifdef regions skipped\n";
Chris Lattner22eb9722006-06-18 05:43:12 +0000258
Benjamin Kramer89b422c2009-08-23 12:08:50 +0000259 llvm::errs() << NumMacroExpanded << "/" << NumFnMacroExpanded << "/"
Ted Kremeneka0a3e9b2008-01-14 16:44:48 +0000260 << NumBuiltinMacroExpanded << " obj/fn/builtin macros expanded, "
261 << NumFastMacroExpanded << " on the fast path.\n";
Benjamin Kramer89b422c2009-08-23 12:08:50 +0000262 llvm::errs() << (NumFastTokenPaste+NumTokenPaste)
Ted Kremeneka0a3e9b2008-01-14 16:44:48 +0000263 << " token paste (##) operations performed, "
264 << NumFastTokenPaste << " on the fast path.\n";
Alexander Kornienko199cd942012-08-13 10:46:42 +0000265
266 llvm::errs() << "\nPreprocessor Memory: " << getTotalMemory() << "B total";
267
268 llvm::errs() << "\n BumpPtr: " << BP.getTotalMemory();
269 llvm::errs() << "\n Macro Expanded Tokens: "
270 << llvm::capacity_in_bytes(MacroExpandedTokens);
271 llvm::errs() << "\n Predefines Buffer: " << Predefines.capacity();
272 llvm::errs() << "\n Macros: " << llvm::capacity_in_bytes(Macros);
273 llvm::errs() << "\n #pragma push_macro Info: "
274 << llvm::capacity_in_bytes(PragmaPushMacroInfo);
275 llvm::errs() << "\n Poison Reasons: "
276 << llvm::capacity_in_bytes(PoisonReasons);
277 llvm::errs() << "\n Comment Handlers: "
278 << llvm::capacity_in_bytes(CommentHandlers) << "\n";
Chris Lattner22eb9722006-06-18 05:43:12 +0000279}
280
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +0000281Preprocessor::macro_iterator
282Preprocessor::macro_begin(bool IncludeExternalMacros) const {
283 if (IncludeExternalMacros && ExternalSource &&
Douglas Gregor9882a5a2010-01-04 19:18:44 +0000284 !ReadMacrosFromExternalSource) {
285 ReadMacrosFromExternalSource = true;
286 ExternalSource->ReadDefinedMacros();
287 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +0000288
289 return Macros.begin();
Douglas Gregor9882a5a2010-01-04 19:18:44 +0000290}
291
Argyrios Kyrtzidise379ee32011-06-29 22:20:04 +0000292size_t Preprocessor::getTotalMemory() const {
Ted Kremenek182543a2011-07-26 21:17:24 +0000293 return BP.getTotalMemory()
Ted Kremenek8b77fe72011-07-27 18:41:23 +0000294 + llvm::capacity_in_bytes(MacroExpandedTokens)
Ted Kremenek182543a2011-07-26 21:17:24 +0000295 + Predefines.capacity() /* Predefines buffer. */
Ted Kremenek8b77fe72011-07-27 18:41:23 +0000296 + llvm::capacity_in_bytes(Macros)
297 + llvm::capacity_in_bytes(PragmaPushMacroInfo)
298 + llvm::capacity_in_bytes(PoisonReasons)
299 + llvm::capacity_in_bytes(CommentHandlers);
Argyrios Kyrtzidise379ee32011-06-29 22:20:04 +0000300}
301
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +0000302Preprocessor::macro_iterator
303Preprocessor::macro_end(bool IncludeExternalMacros) const {
304 if (IncludeExternalMacros && ExternalSource &&
Douglas Gregor9882a5a2010-01-04 19:18:44 +0000305 !ReadMacrosFromExternalSource) {
306 ReadMacrosFromExternalSource = true;
307 ExternalSource->ReadDefinedMacros();
308 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +0000309
310 return Macros.end();
Douglas Gregor9882a5a2010-01-04 19:18:44 +0000311}
312
Dmitri Gribenko6743e042012-09-29 11:40:46 +0000313/// \brief Compares macro tokens with a specified token value sequence.
314static bool MacroDefinitionEquals(const MacroInfo *MI,
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000315 ArrayRef<TokenValue> Tokens) {
Dmitri Gribenko6743e042012-09-29 11:40:46 +0000316 return Tokens.size() == MI->getNumTokens() &&
317 std::equal(Tokens.begin(), Tokens.end(), MI->tokens_begin());
318}
319
320StringRef Preprocessor::getLastMacroWithSpelling(
321 SourceLocation Loc,
322 ArrayRef<TokenValue> Tokens) const {
323 SourceLocation BestLocation;
324 StringRef BestSpelling;
325 for (Preprocessor::macro_iterator I = macro_begin(), E = macro_end();
326 I != E; ++I) {
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +0000327 const MacroDirective::DefInfo
Richard Smithb8b2ed62015-04-23 18:18:26 +0000328 Def = I->second.findDirectiveAtLoc(Loc, SourceMgr);
Argyrios Kyrtzidis5c585252015-03-04 16:03:07 +0000329 if (!Def || !Def.getMacroInfo())
330 continue;
331 if (!Def.getMacroInfo()->isObjectLike())
Dmitri Gribenko6743e042012-09-29 11:40:46 +0000332 continue;
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +0000333 if (!MacroDefinitionEquals(Def.getMacroInfo(), Tokens))
Dmitri Gribenko6743e042012-09-29 11:40:46 +0000334 continue;
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +0000335 SourceLocation Location = Def.getLocation();
Dmitri Gribenko6743e042012-09-29 11:40:46 +0000336 // Choose the macro defined latest.
337 if (BestLocation.isInvalid() ||
338 (Location.isValid() &&
339 SourceMgr.isBeforeInTranslationUnit(BestLocation, Location))) {
340 BestLocation = Location;
341 BestSpelling = I->first->getName();
342 }
343 }
344 return BestSpelling;
345}
346
Douglas Gregor8d76cca2012-01-04 06:20:15 +0000347void Preprocessor::recomputeCurLexerKind() {
348 if (CurLexer)
349 CurLexerKind = CLK_Lexer;
350 else if (CurPTHLexer)
351 CurLexerKind = CLK_PTHLexer;
352 else if (CurTokenLexer)
353 CurLexerKind = CLK_TokenLexer;
354 else
355 CurLexerKind = CLK_CachingLexer;
356}
357
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +0000358bool Preprocessor::SetCodeCompletionPoint(const FileEntry *File,
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +0000359 unsigned CompleteLine,
360 unsigned CompleteColumn) {
361 assert(File);
362 assert(CompleteLine && CompleteColumn && "Starts from 1:1");
363 assert(!CodeCompletionFile && "Already set");
364
Douglas Gregor53ad6b92009-12-02 06:49:09 +0000365 using llvm::MemoryBuffer;
366
Douglas Gregor53ad6b92009-12-02 06:49:09 +0000367 // Load the actual file's contents.
Douglas Gregor26266da2010-03-16 19:49:24 +0000368 bool Invalid = false;
369 const MemoryBuffer *Buffer = SourceMgr.getMemoryBufferForFile(File, &Invalid);
370 if (Invalid)
Douglas Gregor53ad6b92009-12-02 06:49:09 +0000371 return true;
372
373 // Find the byte position of the truncation point.
374 const char *Position = Buffer->getBufferStart();
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +0000375 for (unsigned Line = 1; Line < CompleteLine; ++Line) {
Douglas Gregor53ad6b92009-12-02 06:49:09 +0000376 for (; *Position; ++Position) {
377 if (*Position != '\r' && *Position != '\n')
378 continue;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +0000379
Douglas Gregor53ad6b92009-12-02 06:49:09 +0000380 // Eat \r\n or \n\r as a single line.
381 if ((Position[1] == '\r' || Position[1] == '\n') &&
382 Position[0] != Position[1])
383 ++Position;
384 ++Position;
385 break;
386 }
387 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +0000388
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +0000389 Position += CompleteColumn - 1;
Argyrios Kyrtzidisee301f92014-10-18 06:23:50 +0000390
391 // If pointing inside the preamble, adjust the position at the beginning of
392 // the file after the preamble.
393 if (SkipMainFilePreamble.first &&
394 SourceMgr.getFileEntryForID(SourceMgr.getMainFileID()) == File) {
395 if (Position - Buffer->getBufferStart() < SkipMainFilePreamble.first)
396 Position = Buffer->getBufferStart() + SkipMainFilePreamble.first;
397 }
398
Argyrios Kyrtzidise62d6822014-10-18 06:19:36 +0000399 if (Position > Buffer->getBufferEnd())
400 Position = Buffer->getBufferEnd();
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +0000401
Argyrios Kyrtzidise62d6822014-10-18 06:19:36 +0000402 CodeCompletionFile = File;
403 CodeCompletionOffset = Position - Buffer->getBufferStart();
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +0000404
Argyrios Kyrtzidise62d6822014-10-18 06:19:36 +0000405 std::unique_ptr<MemoryBuffer> NewBuffer =
406 MemoryBuffer::getNewUninitMemBuffer(Buffer->getBufferSize() + 1,
407 Buffer->getBufferIdentifier());
408 char *NewBuf = const_cast<char*>(NewBuffer->getBufferStart());
409 char *NewPos = std::copy(Buffer->getBufferStart(), Position, NewBuf);
410 *NewPos = '\0';
411 std::copy(Position, Buffer->getBufferEnd(), NewPos+1);
412 SourceMgr.overrideFileContents(File, std::move(NewBuffer));
Douglas Gregor53ad6b92009-12-02 06:49:09 +0000413
414 return false;
415}
416
Douglas Gregor11583702010-08-25 17:04:25 +0000417void Preprocessor::CodeCompleteNaturalLanguage() {
Douglas Gregor11583702010-08-25 17:04:25 +0000418 if (CodeComplete)
419 CodeComplete->CodeCompleteNaturalLanguage();
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +0000420 setCodeCompletionReached();
Douglas Gregor11583702010-08-25 17:04:25 +0000421}
422
Benjamin Kramera197fb62010-02-27 17:05:45 +0000423/// getSpelling - This method is used to get the spelling of a token into a
424/// SmallVector. Note that the returned StringRef may not point to the
425/// supplied buffer if a copy can be avoided.
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000426StringRef Preprocessor::getSpelling(const Token &Tok,
427 SmallVectorImpl<char> &Buffer,
Douglas Gregor7bda4b82010-03-16 05:20:39 +0000428 bool *Invalid) const {
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +0000429 // NOTE: this has to be checked *before* testing for an IdentifierInfo.
Jordan Rose7f43ddd2013-01-24 20:50:46 +0000430 if (Tok.isNot(tok::raw_identifier) && !Tok.hasUCN()) {
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +0000431 // Try the fast path.
432 if (const IdentifierInfo *II = Tok.getIdentifierInfo())
433 return II->getName();
434 }
Benjamin Kramera197fb62010-02-27 17:05:45 +0000435
436 // Resize the buffer if we need to copy into it.
437 if (Tok.needsCleaning())
438 Buffer.resize(Tok.getLength());
439
440 const char *Ptr = Buffer.data();
Douglas Gregor7bda4b82010-03-16 05:20:39 +0000441 unsigned Len = getSpelling(Tok, Ptr, Invalid);
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000442 return StringRef(Ptr, Len);
Benjamin Kramera197fb62010-02-27 17:05:45 +0000443}
444
Chris Lattnerb94ec7b2006-07-14 06:54:10 +0000445/// CreateString - Plop the specified string into a scratch buffer and return a
446/// location for it. If specified, the source location provides a source
447/// location for the token.
Dmitri Gribenkob8e9e752012-09-24 21:07:17 +0000448void Preprocessor::CreateString(StringRef Str, Token &Tok,
Abramo Bagnarae398e602011-10-03 18:39:03 +0000449 SourceLocation ExpansionLocStart,
450 SourceLocation ExpansionLocEnd) {
Dmitri Gribenkob8e9e752012-09-24 21:07:17 +0000451 Tok.setLength(Str.size());
Mike Stump11289f42009-09-09 15:08:12 +0000452
Chris Lattner5a7971e2009-01-26 19:29:26 +0000453 const char *DestPtr;
Dmitri Gribenkob8e9e752012-09-24 21:07:17 +0000454 SourceLocation Loc = ScratchBuf->getToken(Str.data(), Str.size(), DestPtr);
Mike Stump11289f42009-09-09 15:08:12 +0000455
Abramo Bagnarae398e602011-10-03 18:39:03 +0000456 if (ExpansionLocStart.isValid())
457 Loc = SourceMgr.createExpansionLoc(Loc, ExpansionLocStart,
Dmitri Gribenkob8e9e752012-09-24 21:07:17 +0000458 ExpansionLocEnd, Str.size());
Chris Lattner5a7971e2009-01-26 19:29:26 +0000459 Tok.setLocation(Loc);
Mike Stump11289f42009-09-09 15:08:12 +0000460
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +0000461 // If this is a raw identifier or a literal token, set the pointer data.
462 if (Tok.is(tok::raw_identifier))
463 Tok.setRawIdentifierData(DestPtr);
464 else if (Tok.isLiteral())
Chris Lattner5a7971e2009-01-26 19:29:26 +0000465 Tok.setLiteralData(DestPtr);
Chris Lattnerb94ec7b2006-07-14 06:54:10 +0000466}
467
Douglas Gregor2b82c2a2011-12-02 01:47:07 +0000468Module *Preprocessor::getCurrentModule() {
David Blaikiebbafb8a2012-03-11 07:00:24 +0000469 if (getLangOpts().CurrentModule.empty())
Craig Topperd2d442c2014-05-17 23:10:59 +0000470 return nullptr;
471
David Blaikiebbafb8a2012-03-11 07:00:24 +0000472 return getHeaderSearchInfo().lookupModule(getLangOpts().CurrentModule);
Douglas Gregor2b82c2a2011-12-02 01:47:07 +0000473}
Chris Lattner8a7003c2007-07-16 06:48:38 +0000474
Chris Lattner1f1b0db2007-10-09 22:10:18 +0000475//===----------------------------------------------------------------------===//
476// Preprocessor Initialization Methods
477//===----------------------------------------------------------------------===//
478
Chris Lattner1f1b0db2007-10-09 22:10:18 +0000479
480/// EnterMainSourceFile - Enter the specified FileID as the main source file,
Nate Begemanf7c3ff62008-01-07 04:01:26 +0000481/// which implicitly adds the builtin defines etc.
Chris Lattnerfb24a3a2010-04-20 20:35:58 +0000482void Preprocessor::EnterMainSourceFile() {
Chris Lattner9ef847b2009-02-13 19:33:24 +0000483 // We do not allow the preprocessor to reenter the main file. Doing so will
484 // cause FileID's to accumulate information from both runs (e.g. #line
485 // information) and predefined macros aren't guaranteed to be set properly.
486 assert(NumEnteredSourceFiles == 0 && "Cannot reenter the main file!");
Chris Lattnerd32480d2009-01-17 06:22:33 +0000487 FileID MainFileID = SourceMgr.getMainFileID();
Mike Stump11289f42009-09-09 15:08:12 +0000488
Argyrios Kyrtzidis9afd4492012-01-05 21:36:25 +0000489 // If MainFileID is loaded it means we loaded an AST file, no need to enter
490 // a main file.
491 if (!SourceMgr.isLoadedFileID(MainFileID)) {
492 // Enter the main file source buffer.
Craig Topperd2d442c2014-05-17 23:10:59 +0000493 EnterSourceFile(MainFileID, nullptr, SourceLocation());
494
Argyrios Kyrtzidis9afd4492012-01-05 21:36:25 +0000495 // If we've been asked to skip bytes in the main file (e.g., as part of a
496 // precompiled preamble), do so now.
497 if (SkipMainFilePreamble.first > 0)
498 CurLexer->SkipBytes(SkipMainFilePreamble.first,
499 SkipMainFilePreamble.second);
500
501 // Tell the header info that the main file was entered. If the file is later
502 // #imported, it won't be re-entered.
503 if (const FileEntry *FE = SourceMgr.getFileEntryForID(MainFileID))
504 HeaderInfo.IncrementIncludeCount(FE);
505 }
Mike Stump11289f42009-09-09 15:08:12 +0000506
Benjamin Kramerd77adb52009-12-31 15:33:09 +0000507 // Preprocess Predefines to populate the initial preprocessor state.
Rafael Espindolad87f8d72014-08-27 20:03:29 +0000508 std::unique_ptr<llvm::MemoryBuffer> SB =
Chris Lattner58c79342010-04-05 22:42:27 +0000509 llvm::MemoryBuffer::getMemBufferCopy(Predefines, "<built-in>");
Douglas Gregor33551892010-08-26 14:07:34 +0000510 assert(SB && "Cannot create predefined source buffer");
David Blaikie50a5f972014-08-29 07:59:55 +0000511 FileID FID = SourceMgr.createFileID(std::move(SB));
Chris Lattnerd32480d2009-01-17 06:22:33 +0000512 assert(!FID.isInvalid() && "Could not create FileID for predefines?");
Argyrios Kyrtzidis22c22f52013-02-01 16:36:07 +0000513 setPredefinesFileID(FID);
Mike Stump11289f42009-09-09 15:08:12 +0000514
Chris Lattner1f1b0db2007-10-09 22:10:18 +0000515 // Start parsing the predefines.
Craig Topperd2d442c2014-05-17 23:10:59 +0000516 EnterSourceFile(FID, nullptr, SourceLocation());
Chris Lattner1f1b0db2007-10-09 22:10:18 +0000517}
Chris Lattner8a7003c2007-07-16 06:48:38 +0000518
Daniel Dunbarcb9eaf52010-03-23 05:09:10 +0000519void Preprocessor::EndSourceFile() {
520 // Notify the client that we reached the end of the source file.
521 if (Callbacks)
522 Callbacks->EndOfMainFile();
523}
Chris Lattner677757a2006-06-28 05:26:32 +0000524
525//===----------------------------------------------------------------------===//
526// Lexer Event Handling.
527//===----------------------------------------------------------------------===//
528
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +0000529/// LookUpIdentifierInfo - Given a tok::raw_identifier token, look up the
530/// identifier information for the token and install it into the token,
531/// updating the token kind accordingly.
532IdentifierInfo *Preprocessor::LookUpIdentifierInfo(Token &Identifier) const {
Alp Toker2d57cea2014-05-17 04:53:25 +0000533 assert(!Identifier.getRawIdentifier().empty() && "No raw identifier data!");
Mike Stump11289f42009-09-09 15:08:12 +0000534
Chris Lattnercefc7682006-07-08 08:28:12 +0000535 // Look up this token, see if it is a macro, or if it is a language keyword.
536 IdentifierInfo *II;
Jordan Rose7f43ddd2013-01-24 20:50:46 +0000537 if (!Identifier.needsCleaning() && !Identifier.hasUCN()) {
Chris Lattnercefc7682006-07-08 08:28:12 +0000538 // No cleaning needed, just use the characters from the lexed buffer.
Alp Toker2d57cea2014-05-17 04:53:25 +0000539 II = getIdentifierInfo(Identifier.getRawIdentifier());
Chris Lattnercefc7682006-07-08 08:28:12 +0000540 } else {
541 // Cleaning needed, alloca a buffer, clean into it, then use the buffer.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +0000542 SmallString<64> IdentifierBuffer;
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000543 StringRef CleanedStr = getSpelling(Identifier, IdentifierBuffer);
Jordan Rose7f43ddd2013-01-24 20:50:46 +0000544
545 if (Identifier.hasUCN()) {
546 SmallString<64> UCNIdentifierBuffer;
547 expandUCNs(UCNIdentifierBuffer, CleanedStr);
548 II = getIdentifierInfo(UCNIdentifierBuffer);
549 } else {
550 II = getIdentifierInfo(CleanedStr);
551 }
Chris Lattnercefc7682006-07-08 08:28:12 +0000552 }
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +0000553
554 // Update the token info (identifier info and appropriate token kind).
Chris Lattner8c204872006-10-14 05:19:21 +0000555 Identifier.setIdentifierInfo(II);
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +0000556 Identifier.setKind(II->getTokenID());
557
Chris Lattnercefc7682006-07-08 08:28:12 +0000558 return II;
559}
560
John Wiegley1c0675e2011-04-28 01:08:34 +0000561void Preprocessor::SetPoisonReason(IdentifierInfo *II, unsigned DiagID) {
562 PoisonReasons[II] = DiagID;
563}
564
565void Preprocessor::PoisonSEHIdentifiers(bool Poison) {
566 assert(Ident__exception_code && Ident__exception_info);
567 assert(Ident___exception_code && Ident___exception_info);
568 Ident__exception_code->setIsPoisoned(Poison);
569 Ident___exception_code->setIsPoisoned(Poison);
570 Ident_GetExceptionCode->setIsPoisoned(Poison);
571 Ident__exception_info->setIsPoisoned(Poison);
572 Ident___exception_info->setIsPoisoned(Poison);
573 Ident_GetExceptionInfo->setIsPoisoned(Poison);
574 Ident__abnormal_termination->setIsPoisoned(Poison);
575 Ident___abnormal_termination->setIsPoisoned(Poison);
576 Ident_AbnormalTermination->setIsPoisoned(Poison);
577}
578
579void Preprocessor::HandlePoisonedIdentifier(Token & Identifier) {
580 assert(Identifier.getIdentifierInfo() &&
581 "Can't handle identifiers without identifier info!");
582 llvm::DenseMap<IdentifierInfo*,unsigned>::const_iterator it =
583 PoisonReasons.find(Identifier.getIdentifierInfo());
584 if(it == PoisonReasons.end())
585 Diag(Identifier, diag::err_pp_used_poisoned_id);
586 else
587 Diag(Identifier,it->second) << Identifier.getIdentifierInfo();
588}
Chris Lattnercefc7682006-07-08 08:28:12 +0000589
Chris Lattner677757a2006-06-28 05:26:32 +0000590/// HandleIdentifier - This callback is invoked when the lexer reads an
591/// identifier. This callback looks up the identifier in the map and/or
592/// potentially macro expands it or turns it into a named token (like 'for').
Chris Lattnerad89ec02009-01-21 07:43:11 +0000593///
594/// Note that callers of this method are guarded by checking the
595/// IdentifierInfo's 'isHandleIdentifierCase' bit. If this method changes, the
596/// IdentifierInfo methods that compute these properties will need to change to
597/// match.
Eli Friedman0834a4b2013-09-19 00:41:32 +0000598bool Preprocessor::HandleIdentifier(Token &Identifier) {
Chris Lattner0f1f5052006-07-20 04:16:23 +0000599 assert(Identifier.getIdentifierInfo() &&
600 "Can't handle identifiers without identifier info!");
Mike Stump11289f42009-09-09 15:08:12 +0000601
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000602 IdentifierInfo &II = *Identifier.getIdentifierInfo();
Chris Lattner677757a2006-06-28 05:26:32 +0000603
Douglas Gregor935bc7a22011-10-27 09:33:13 +0000604 // If the information about this identifier is out of date, update it from
605 // the external source.
Douglas Gregor3f568c12012-06-29 18:27:59 +0000606 // We have to treat __VA_ARGS__ in a special way, since it gets
607 // serialized with isPoisoned = true, but our preprocessor may have
608 // unpoisoned it if we're defining a C99 macro.
Douglas Gregor935bc7a22011-10-27 09:33:13 +0000609 if (II.isOutOfDate()) {
Douglas Gregor3f568c12012-06-29 18:27:59 +0000610 bool CurrentIsPoisoned = false;
611 if (&II == Ident__VA_ARGS__)
612 CurrentIsPoisoned = Ident__VA_ARGS__->isPoisoned();
613
Douglas Gregor935bc7a22011-10-27 09:33:13 +0000614 ExternalSource->updateOutOfDateIdentifier(II);
615 Identifier.setKind(II.getTokenID());
Douglas Gregor3f568c12012-06-29 18:27:59 +0000616
617 if (&II == Ident__VA_ARGS__)
618 II.setIsPoisoned(CurrentIsPoisoned);
Douglas Gregor935bc7a22011-10-27 09:33:13 +0000619 }
620
Chris Lattner677757a2006-06-28 05:26:32 +0000621 // If this identifier was poisoned, and if it was not produced from a macro
622 // expansion, emit an error.
Ted Kremeneka2c3c8d2008-11-19 22:43:49 +0000623 if (II.isPoisoned() && CurPPLexer) {
John Wiegley1c0675e2011-04-28 01:08:34 +0000624 HandlePoisonedIdentifier(Identifier);
Chris Lattner8ff71992006-07-06 05:17:39 +0000625 }
Mike Stump11289f42009-09-09 15:08:12 +0000626
Chris Lattner78186052006-07-09 00:45:31 +0000627 // If this is a macro to be expanded, do it.
Richard Smith20e883e2015-04-29 23:20:19 +0000628 if (MacroDefinition MD = getMacroDefinition(&II)) {
629 auto *MI = MD.getMacroInfo();
Abramo Bagnara123bec82012-01-01 22:01:04 +0000630 if (!DisableMacroExpansion) {
Richard Smith181879c2012-12-12 02:46:14 +0000631 if (!Identifier.isExpandDisabled() && MI->isEnabled()) {
Eli Friedman0834a4b2013-09-19 00:41:32 +0000632 // C99 6.10.3p10: If the preprocessing token immediately after the
633 // macro name isn't a '(', this macro should not be expanded.
634 if (!MI->isFunctionLike() || isNextPPTokenLParen())
635 return HandleMacroExpandedIdentifier(Identifier, MD);
Chris Lattner6e4bf522006-07-27 06:59:25 +0000636 } else {
637 // C99 6.10.3.4p2 says that a disabled macro may never again be
638 // expanded, even if it's in a context where it could be expanded in the
639 // future.
Chris Lattner146762e2007-07-20 16:59:19 +0000640 Identifier.setFlag(Token::DisableExpand);
Richard Smith181879c2012-12-12 02:46:14 +0000641 if (MI->isObjectLike() || isNextPPTokenLParen())
642 Diag(Identifier, diag::pp_disabled_macro_expansion);
Chris Lattner6e4bf522006-07-27 06:59:25 +0000643 }
644 }
Chris Lattner063400e2006-10-14 19:54:15 +0000645 }
Chris Lattner677757a2006-06-28 05:26:32 +0000646
Richard Smith4dd85d62011-10-11 19:57:52 +0000647 // If this identifier is a keyword in C++11, produce a warning. Don't warn if
648 // we're not considering macro expansion, since this identifier might be the
649 // name of a macro.
650 // FIXME: This warning is disabled in cases where it shouldn't be, like
651 // "#define constexpr constexpr", "int constexpr;"
Alp Toker7d2fea22014-02-24 04:35:58 +0000652 if (II.isCXX11CompatKeyword() && !DisableMacroExpansion) {
Richard Smith4dd85d62011-10-11 19:57:52 +0000653 Diag(Identifier, diag::warn_cxx11_keyword) << II.getName();
654 // Don't diagnose this keyword again in this translation unit.
655 II.setIsCXX11CompatKeyword(false);
656 }
657
Chris Lattner5b9f4892006-11-21 17:23:33 +0000658 // C++ 2.11p2: If this is an alternative representation of a C++ operator,
659 // then we act as if it is the actual operator and not the textual
660 // representation of it.
Fariborz Jahanian9e42a952010-09-03 17:33:04 +0000661 if (II.isCPlusPlusOperatorKeyword())
Craig Topperd2d442c2014-05-17 23:10:59 +0000662 Identifier.setIdentifierInfo(nullptr);
Chris Lattner5b9f4892006-11-21 17:23:33 +0000663
Chris Lattner677757a2006-06-28 05:26:32 +0000664 // If this is an extension token, diagnose its use.
Steve Naroffc84e8b72008-09-02 18:50:17 +0000665 // We avoid diagnosing tokens that originate from macro definitions.
Eli Friedman6bba2ad2009-04-28 03:59:15 +0000666 // FIXME: This warning is disabled in cases where it shouldn't be,
667 // like "#define TY typeof", "TY(1) x".
668 if (II.isExtensionToken() && !DisableMacroExpansion)
Chris Lattner53621a52007-06-13 20:44:40 +0000669 Diag(Identifier, diag::ext_token_used);
Douglas Gregoraf5c4842011-09-07 23:11:54 +0000670
Douglas Gregor594b8c92013-11-07 22:55:02 +0000671 // If this is the 'import' contextual keyword following an '@', note
Ted Kremenekc1e4dd02012-03-01 22:07:04 +0000672 // that the next token indicates a module name.
Douglas Gregor8d76cca2012-01-04 06:20:15 +0000673 //
Douglas Gregorc50d4922012-12-11 22:11:52 +0000674 // Note that we do not treat 'import' as a contextual
Ted Kremenekc1e4dd02012-03-01 22:07:04 +0000675 // keyword when we're in a caching lexer, because caching lexers only get
676 // used in contexts where import declarations are disallowed.
Douglas Gregor594b8c92013-11-07 22:55:02 +0000677 if (LastTokenWasAt && II.isModulesImport() && !InMacroArgs &&
Sean Callanan87596492014-12-09 23:47:56 +0000678 !DisableMacroExpansion &&
679 (getLangOpts().Modules || getLangOpts().DebuggerSupport) &&
Douglas Gregor594b8c92013-11-07 22:55:02 +0000680 CurLexerKind != CLK_CachingLexer) {
Douglas Gregoraf5c4842011-09-07 23:11:54 +0000681 ModuleImportLoc = Identifier.getLocation();
Douglas Gregor1805b8a2011-11-30 04:26:53 +0000682 ModuleImportPath.clear();
683 ModuleImportExpectsIdentifier = true;
Douglas Gregoraf5c4842011-09-07 23:11:54 +0000684 CurLexerKind = CLK_LexAfterModuleImport;
685 }
Eli Friedman0834a4b2013-09-19 00:41:32 +0000686 return true;
Douglas Gregor08142532011-08-26 23:56:07 +0000687}
688
Eli Friedman0834a4b2013-09-19 00:41:32 +0000689void Preprocessor::Lex(Token &Result) {
690 // We loop here until a lex function retuns a token; this avoids recursion.
691 bool ReturnedToken;
692 do {
693 switch (CurLexerKind) {
694 case CLK_Lexer:
695 ReturnedToken = CurLexer->Lex(Result);
696 break;
697 case CLK_PTHLexer:
698 ReturnedToken = CurPTHLexer->Lex(Result);
699 break;
700 case CLK_TokenLexer:
701 ReturnedToken = CurTokenLexer->Lex(Result);
702 break;
703 case CLK_CachingLexer:
704 CachingLex(Result);
705 ReturnedToken = true;
706 break;
707 case CLK_LexAfterModuleImport:
708 LexAfterModuleImport(Result);
709 ReturnedToken = true;
710 break;
711 }
712 } while (!ReturnedToken);
Douglas Gregor594b8c92013-11-07 22:55:02 +0000713
714 LastTokenWasAt = Result.is(tok::at);
Eli Friedman0834a4b2013-09-19 00:41:32 +0000715}
716
717
Douglas Gregorda82e702012-01-03 19:32:59 +0000718/// \brief Lex a token following the 'import' contextual keyword.
Douglas Gregor22d09742012-01-03 18:04:46 +0000719///
Douglas Gregoraf5c4842011-09-07 23:11:54 +0000720void Preprocessor::LexAfterModuleImport(Token &Result) {
721 // Figure out what kind of lexer we actually have.
Douglas Gregor8d76cca2012-01-04 06:20:15 +0000722 recomputeCurLexerKind();
Douglas Gregoraf5c4842011-09-07 23:11:54 +0000723
724 // Lex the next token.
725 Lex(Result);
726
Douglas Gregor08142532011-08-26 23:56:07 +0000727 // The token sequence
728 //
Douglas Gregor22d09742012-01-03 18:04:46 +0000729 // import identifier (. identifier)*
730 //
Douglas Gregorda82e702012-01-03 19:32:59 +0000731 // indicates a module import directive. We already saw the 'import'
732 // contextual keyword, so now we're looking for the identifiers.
Douglas Gregor1805b8a2011-11-30 04:26:53 +0000733 if (ModuleImportExpectsIdentifier && Result.getKind() == tok::identifier) {
734 // We expected to see an identifier here, and we did; continue handling
735 // identifiers.
736 ModuleImportPath.push_back(std::make_pair(Result.getIdentifierInfo(),
737 Result.getLocation()));
738 ModuleImportExpectsIdentifier = false;
739 CurLexerKind = CLK_LexAfterModuleImport;
Douglas Gregor08142532011-08-26 23:56:07 +0000740 return;
Douglas Gregor1805b8a2011-11-30 04:26:53 +0000741 }
Douglas Gregor08142532011-08-26 23:56:07 +0000742
Douglas Gregor1805b8a2011-11-30 04:26:53 +0000743 // If we're expecting a '.' or a ';', and we got a '.', then wait until we
744 // see the next identifier.
745 if (!ModuleImportExpectsIdentifier && Result.getKind() == tok::period) {
746 ModuleImportExpectsIdentifier = true;
747 CurLexerKind = CLK_LexAfterModuleImport;
748 return;
749 }
750
751 // If we have a non-empty module path, load the named module.
Sean Callanan87596492014-12-09 23:47:56 +0000752 if (!ModuleImportPath.empty()) {
753 Module *Imported = nullptr;
Richard Smith753e0072015-04-27 23:21:38 +0000754 if (getLangOpts().Modules) {
Sean Callanan87596492014-12-09 23:47:56 +0000755 Imported = TheModuleLoader.loadModule(ModuleImportLoc,
756 ModuleImportPath,
757 Module::MacrosVisible,
758 /*IsIncludeDirective=*/false);
Richard Smith753e0072015-04-27 23:21:38 +0000759 ++MacroVisibilityGeneration;
760 }
Sean Callanan87596492014-12-09 23:47:56 +0000761 if (Callbacks && (getLangOpts().Modules || getLangOpts().DebuggerSupport))
Argyrios Kyrtzidis19d78b72012-09-29 01:06:10 +0000762 Callbacks->moduleImport(ModuleImportLoc, ModuleImportPath, Imported);
763 }
Chris Lattner677757a2006-06-28 05:26:32 +0000764}
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000765
Andy Gibbs58905d22012-11-17 19:15:38 +0000766bool Preprocessor::FinishLexStringLiteral(Token &Result, std::string &String,
Andy Gibbsa8df57a2012-11-17 19:16:52 +0000767 const char *DiagnosticTag,
Andy Gibbs58905d22012-11-17 19:15:38 +0000768 bool AllowMacroExpansion) {
769 // We need at least one string literal.
770 if (Result.isNot(tok::string_literal)) {
Andy Gibbsa8df57a2012-11-17 19:16:52 +0000771 Diag(Result, diag::err_expected_string_literal)
772 << /*Source='in...'*/0 << DiagnosticTag;
Andy Gibbs58905d22012-11-17 19:15:38 +0000773 return false;
774 }
775
776 // Lex string literal tokens, optionally with macro expansion.
777 SmallVector<Token, 4> StrToks;
778 do {
779 StrToks.push_back(Result);
780
781 if (Result.hasUDSuffix())
782 Diag(Result, diag::err_invalid_string_udl);
783
784 if (AllowMacroExpansion)
785 Lex(Result);
786 else
787 LexUnexpandedToken(Result);
788 } while (Result.is(tok::string_literal));
789
790 // Concatenate and parse the strings.
Craig Topper9d5583e2014-06-26 04:58:39 +0000791 StringLiteralParser Literal(StrToks, *this);
Andy Gibbs58905d22012-11-17 19:15:38 +0000792 assert(Literal.isAscii() && "Didn't allow wide strings in");
793
794 if (Literal.hadError)
795 return false;
796
797 if (Literal.Pascal) {
Andy Gibbsa8df57a2012-11-17 19:16:52 +0000798 Diag(StrToks[0].getLocation(), diag::err_expected_string_literal)
799 << /*Source='in...'*/0 << DiagnosticTag;
Andy Gibbs58905d22012-11-17 19:15:38 +0000800 return false;
801 }
802
803 String = Literal.GetString();
804 return true;
805}
806
Reid Klecknerc0dca6d2014-02-12 23:50:26 +0000807bool Preprocessor::parseSimpleIntegerLiteral(Token &Tok, uint64_t &Value) {
808 assert(Tok.is(tok::numeric_constant));
809 SmallString<8> IntegerBuffer;
810 bool NumberInvalid = false;
811 StringRef Spelling = getSpelling(Tok, IntegerBuffer, &NumberInvalid);
812 if (NumberInvalid)
813 return false;
814 NumericLiteralParser Literal(Spelling, Tok.getLocation(), *this);
815 if (Literal.hadError || !Literal.isIntegerLiteral() || Literal.hasUDSuffix())
816 return false;
817 llvm::APInt APVal(64, 0);
818 if (Literal.GetIntegerValue(APVal))
819 return false;
820 Lex(Tok);
821 Value = APVal.getLimitedValue();
822 return true;
823}
824
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000825void Preprocessor::addCommentHandler(CommentHandler *Handler) {
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000826 assert(Handler && "NULL comment handler");
827 assert(std::find(CommentHandlers.begin(), CommentHandlers.end(), Handler) ==
828 CommentHandlers.end() && "Comment handler already registered");
829 CommentHandlers.push_back(Handler);
830}
831
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000832void Preprocessor::removeCommentHandler(CommentHandler *Handler) {
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000833 std::vector<CommentHandler *>::iterator Pos
834 = std::find(CommentHandlers.begin(), CommentHandlers.end(), Handler);
835 assert(Pos != CommentHandlers.end() && "Comment handler not registered");
836 CommentHandlers.erase(Pos);
837}
838
Chris Lattner87d02082010-01-18 22:35:47 +0000839bool Preprocessor::HandleComment(Token &result, SourceRange Comment) {
840 bool AnyPendingTokens = false;
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000841 for (std::vector<CommentHandler *>::iterator H = CommentHandlers.begin(),
842 HEnd = CommentHandlers.end();
Chris Lattner87d02082010-01-18 22:35:47 +0000843 H != HEnd; ++H) {
844 if ((*H)->HandleComment(*this, Comment))
845 AnyPendingTokens = true;
846 }
847 if (!AnyPendingTokens || getCommentRetentionState())
848 return false;
849 Lex(result);
850 return true;
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000851}
852
Douglas Gregor08142532011-08-26 23:56:07 +0000853ModuleLoader::~ModuleLoader() { }
854
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000855CommentHandler::~CommentHandler() { }
Douglas Gregor7f6d60d2010-03-19 16:15:56 +0000856
Douglas Gregor3a7ad252010-08-24 19:08:16 +0000857CodeCompletionHandler::~CodeCompletionHandler() { }
858
Argyrios Kyrtzidisf3d587e2012-12-04 07:27:05 +0000859void Preprocessor::createPreprocessingRecord() {
Douglas Gregor7f6d60d2010-03-19 16:15:56 +0000860 if (Record)
861 return;
862
Argyrios Kyrtzidisf3d587e2012-12-04 07:27:05 +0000863 Record = new PreprocessingRecord(getSourceManager());
Craig Topperb8a70532014-09-10 04:53:53 +0000864 addPPCallbacks(std::unique_ptr<PPCallbacks>(Record));
Douglas Gregor7f6d60d2010-03-19 16:15:56 +0000865}