blob: 4a11803aa9547ec05e7eb99964c130c11de31a64 [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"
30#include "clang/Basic/SourceManager.h"
31#include "clang/Basic/TargetInfo.h"
32#include "clang/Lex/CodeCompletionHandler.h"
Douglas Gregor9882a5a2010-01-04 19:18:44 +000033#include "clang/Lex/ExternalPreprocessorSource.h"
Chris Lattner07b019a2006-10-22 07:28:56 +000034#include "clang/Lex/HeaderSearch.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000035#include "clang/Lex/LexDiagnostic.h"
36#include "clang/Lex/LiteralSupport.h"
Chandler Carruth5553d0d2014-01-07 11:51:46 +000037#include "clang/Lex/MacroArgs.h"
Chris Lattner22eb9722006-06-18 05:43:12 +000038#include "clang/Lex/MacroInfo.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000039#include "clang/Lex/ModuleLoader.h"
Chris Lattnerb8761832006-06-24 21:31:03 +000040#include "clang/Lex/Pragma.h"
Douglas Gregor7f6d60d2010-03-19 16:15:56 +000041#include "clang/Lex/PreprocessingRecord.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000042#include "clang/Lex/PreprocessorOptions.h"
Chris Lattner0b8cfc22006-06-28 06:49:17 +000043#include "clang/Lex/ScratchBuffer.h"
Chris Lattner5cd83512008-10-05 20:40:30 +000044#include "llvm/ADT/APFloat.h"
Jordan Rose7f43ddd2013-01-24 20:50:46 +000045#include "llvm/ADT/STLExtras.h"
Chandler Carruth5553d0d2014-01-07 11:51:46 +000046#include "llvm/ADT/SmallString.h"
Jordan Rose7f43ddd2013-01-24 20:50:46 +000047#include "llvm/ADT/StringExtras.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000048#include "llvm/Support/Capacity.h"
Dmitri Gribenko9feeef42013-01-30 12:06:08 +000049#include "llvm/Support/ConvertUTF.h"
Chris Lattner8a7003c2007-07-16 06:48:38 +000050#include "llvm/Support/MemoryBuffer.h"
Benjamin Kramer89b422c2009-08-23 12:08:50 +000051#include "llvm/Support/raw_ostream.h"
Chris Lattner22eb9722006-06-18 05:43:12 +000052using namespace clang;
53
54//===----------------------------------------------------------------------===//
Douglas Gregor9882a5a2010-01-04 19:18:44 +000055ExternalPreprocessorSource::~ExternalPreprocessorSource() { }
Chris Lattner22eb9722006-06-18 05:43:12 +000056
Dmitri Gribenkof8579502013-01-12 19:30:44 +000057Preprocessor::Preprocessor(IntrusiveRefCntPtr<PreprocessorOptions> PPOpts,
Douglas Gregor1452ff12012-10-24 17:46:57 +000058 DiagnosticsEngine &diags, LangOptions &opts,
Alp Toker96637802014-05-02 03:43:38 +000059 SourceManager &SM, HeaderSearch &Headers,
60 ModuleLoader &TheModuleLoader,
David Blaikie687cd952013-01-16 23:13:36 +000061 IdentifierInfoLookup *IILookup, bool OwnsHeaders,
Alp Toker1ae02f62014-05-02 03:43:30 +000062 TranslationUnitKind TUKind)
Craig Topper4b566922014-06-09 02:04:02 +000063 : PPOpts(PPOpts), Diags(&diags), LangOpts(opts), Target(nullptr),
David Blaikie687cd952013-01-16 23:13:36 +000064 FileMgr(Headers.getFileMgr()), SourceMgr(SM), HeaderInfo(Headers),
Craig Topperd2d442c2014-05-17 23:10:59 +000065 TheModuleLoader(TheModuleLoader), ExternalSource(nullptr),
Alp Toker96637802014-05-02 03:43:38 +000066 Identifiers(opts, IILookup), IncrementalProcessing(false), TUKind(TUKind),
Craig Topperd2d442c2014-05-17 23:10:59 +000067 CodeComplete(nullptr), CodeCompletionFile(nullptr),
68 CodeCompletionOffset(0), LastTokenWasAt(false),
69 ModuleImportExpectsIdentifier(false), CodeCompletionReached(0),
70 SkipMainFilePreamble(0, true), CurPPLexer(nullptr),
71 CurDirLookup(nullptr), CurLexerKind(CLK_Lexer), CurSubmodule(nullptr),
72 Callbacks(nullptr), MacroArgCache(nullptr), Record(nullptr),
Craig Topper4b566922014-06-09 02:04:02 +000073 MIChainHead(nullptr), MICache(nullptr), DeserialMIChainHead(nullptr) {
Daniel Dunbar0c6c9302009-11-11 21:44:21 +000074 OwnsHeaderSearch = OwnsHeaders;
Douglas Gregor83297df2011-09-01 23:39:15 +000075
76 ScratchBuf = new ScratchBuffer(SourceMgr);
77 CounterValue = 0; // __COUNTER__ starts at 0.
78
79 // Clear stats.
80 NumDirectives = NumDefined = NumUndefined = NumPragma = 0;
81 NumIf = NumElse = NumEndif = 0;
82 NumEnteredSourceFiles = 0;
83 NumMacroExpanded = NumFnMacroExpanded = NumBuiltinMacroExpanded = 0;
84 NumFastMacroExpanded = NumTokenPaste = NumFastTokenPaste = 0;
85 MaxIncludeStackDepth = 0;
86 NumSkipped = 0;
87
88 // Default to discarding comments.
89 KeepComments = false;
90 KeepMacroComments = false;
91 SuppressIncludeNotFoundError = false;
92
93 // Macro expansion is enabled.
94 DisableMacroExpansion = false;
David Blaikied5321242012-06-06 18:52:13 +000095 MacroExpansionInDirectivesOverride = false;
Douglas Gregor83297df2011-09-01 23:39:15 +000096 InMacroArgs = false;
Argyrios Kyrtzidisf1b64c62012-04-03 16:47:40 +000097 InMacroArgPreExpansion = false;
Douglas Gregor83297df2011-09-01 23:39:15 +000098 NumCachedTokenLexers = 0;
Jordan Rosede1a2922012-06-08 18:06:21 +000099 PragmasEnabled = true;
Eric Christopher5e4696d2013-01-16 20:09:36 +0000100 ParsingIfOrElifDirective = false;
Jordan Rose324ec422013-01-31 19:26:01 +0000101 PreprocessedOutput = false;
Jordan Rosede1a2922012-06-08 18:06:21 +0000102
Douglas Gregor83297df2011-09-01 23:39:15 +0000103 CachedLexPos = 0;
Eric Christopher5e4696d2013-01-16 20:09:36 +0000104
Douglas Gregor83297df2011-09-01 23:39:15 +0000105 // We haven't read anything from the external source.
106 ReadMacrosFromExternalSource = false;
107
Douglas Gregor83297df2011-09-01 23:39:15 +0000108 // "Poison" __VA_ARGS__, which can only appear in the expansion of a macro.
109 // This gets unpoisoned where it is allowed.
110 (Ident__VA_ARGS__ = getIdentifierInfo("__VA_ARGS__"))->setIsPoisoned();
111 SetPoisonReason(Ident__VA_ARGS__,diag::ext_pp_bad_vaargs_use);
112
113 // Initialize the pragma handlers.
114 PragmaHandlers = new PragmaNamespace(StringRef());
115 RegisterBuiltinPragmas();
116
117 // Initialize builtin macros like __LINE__ and friends.
118 RegisterBuiltinMacros();
119
David Blaikiebbafb8a2012-03-11 07:00:24 +0000120 if(LangOpts.Borland) {
Douglas Gregor83297df2011-09-01 23:39:15 +0000121 Ident__exception_info = getIdentifierInfo("_exception_info");
122 Ident___exception_info = getIdentifierInfo("__exception_info");
123 Ident_GetExceptionInfo = getIdentifierInfo("GetExceptionInformation");
124 Ident__exception_code = getIdentifierInfo("_exception_code");
125 Ident___exception_code = getIdentifierInfo("__exception_code");
126 Ident_GetExceptionCode = getIdentifierInfo("GetExceptionCode");
127 Ident__abnormal_termination = getIdentifierInfo("_abnormal_termination");
128 Ident___abnormal_termination = getIdentifierInfo("__abnormal_termination");
129 Ident_AbnormalTermination = getIdentifierInfo("AbnormalTermination");
130 } else {
Craig Topperd2d442c2014-05-17 23:10:59 +0000131 Ident__exception_info = Ident__exception_code = nullptr;
132 Ident__abnormal_termination = Ident___exception_info = nullptr;
133 Ident___exception_code = Ident___abnormal_termination = nullptr;
134 Ident_GetExceptionInfo = Ident_GetExceptionCode = nullptr;
135 Ident_AbnormalTermination = nullptr;
Douglas Gregor89929282012-01-30 06:01:29 +0000136 }
Argyrios Kyrtzidis3c9aaf12012-06-02 18:08:09 +0000137}
138
139Preprocessor::~Preprocessor() {
140 assert(BacktrackPositions.empty() && "EnableBacktrack/Backtrack imbalance!");
141
Benjamin Kramer329c5962014-03-15 16:40:40 +0000142 IncludeMacroStack.clear();
Argyrios Kyrtzidis3c9aaf12012-06-02 18:08:09 +0000143
144 // Free any macro definitions.
145 for (MacroInfoChain *I = MIChainHead ; I ; I = I->Next)
146 I->MI.Destroy();
147
148 // Free any cached macro expanders.
Nico Weber5f5b9412014-05-09 18:09:42 +0000149 // This populates MacroArgCache, so all TokenLexers need to be destroyed
150 // before the code below that frees up the MacroArgCache list.
Argyrios Kyrtzidis3c9aaf12012-06-02 18:08:09 +0000151 for (unsigned i = 0, e = NumCachedTokenLexers; i != e; ++i)
152 delete TokenLexerCache[i];
Nico Weber5f5b9412014-05-09 18:09:42 +0000153 CurTokenLexer.reset();
Argyrios Kyrtzidis3c9aaf12012-06-02 18:08:09 +0000154
Argyrios Kyrtzidisd48b91d2013-04-30 05:05:35 +0000155 for (DeserializedMacroInfoChain *I = DeserialMIChainHead ; I ; I = I->Next)
156 I->MI.Destroy();
157
Argyrios Kyrtzidis3c9aaf12012-06-02 18:08:09 +0000158 // Free any cached MacroArgs.
Nico Weber5f5b9412014-05-09 18:09:42 +0000159 for (MacroArgs *ArgList = MacroArgCache; ArgList;)
Argyrios Kyrtzidis3c9aaf12012-06-02 18:08:09 +0000160 ArgList = ArgList->deallocate();
161
162 // Release pragma information.
163 delete PragmaHandlers;
164
165 // Delete the scratch buffer info.
166 delete ScratchBuf;
167
168 // Delete the header search info, if we own it.
169 if (OwnsHeaderSearch)
170 delete &HeaderInfo;
171
172 delete Callbacks;
173}
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 Kremeneka5c2c272009-02-12 03:26:59 +0000185void Preprocessor::setPTHManager(PTHManager* pm) {
186 PTH.reset(pm);
Douglas Gregord2eb58a2009-10-16 18:18:30 +0000187 FileMgr.addStatCache(PTH->createStatCache());
Ted Kremeneka5c2c272009-02-12 03:26:59 +0000188}
189
Chris Lattner146762e2007-07-20 16:59:19 +0000190void Preprocessor::DumpToken(const Token &Tok, bool DumpFlags) const {
Benjamin Kramer89b422c2009-08-23 12:08:50 +0000191 llvm::errs() << tok::getTokenName(Tok.getKind()) << " '"
192 << getSpelling(Tok) << "'";
Mike Stump11289f42009-09-09 15:08:12 +0000193
Chris Lattnerd01e2912006-06-18 16:22:51 +0000194 if (!DumpFlags) return;
Mike Stump11289f42009-09-09 15:08:12 +0000195
Benjamin Kramer89b422c2009-08-23 12:08:50 +0000196 llvm::errs() << "\t";
Chris Lattnerd01e2912006-06-18 16:22:51 +0000197 if (Tok.isAtStartOfLine())
Benjamin Kramer89b422c2009-08-23 12:08:50 +0000198 llvm::errs() << " [StartOfLine]";
Chris Lattnerd01e2912006-06-18 16:22:51 +0000199 if (Tok.hasLeadingSpace())
Benjamin Kramer89b422c2009-08-23 12:08:50 +0000200 llvm::errs() << " [LeadingSpace]";
Chris Lattner6e4bf522006-07-27 06:59:25 +0000201 if (Tok.isExpandDisabled())
Benjamin Kramer89b422c2009-08-23 12:08:50 +0000202 llvm::errs() << " [ExpandDisabled]";
Chris Lattnerd01e2912006-06-18 16:22:51 +0000203 if (Tok.needsCleaning()) {
Chris Lattner50b497e2006-06-18 16:32:35 +0000204 const char *Start = SourceMgr.getCharacterData(Tok.getLocation());
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000205 llvm::errs() << " [UnClean='" << StringRef(Start, Tok.getLength())
Benjamin Kramer89b422c2009-08-23 12:08:50 +0000206 << "']";
Chris Lattnerd01e2912006-06-18 16:22:51 +0000207 }
Mike Stump11289f42009-09-09 15:08:12 +0000208
Benjamin Kramer89b422c2009-08-23 12:08:50 +0000209 llvm::errs() << "\tLoc=<";
Chris Lattner615315f2007-12-09 20:31:55 +0000210 DumpLocation(Tok.getLocation());
Benjamin Kramer89b422c2009-08-23 12:08:50 +0000211 llvm::errs() << ">";
Chris Lattner615315f2007-12-09 20:31:55 +0000212}
213
214void Preprocessor::DumpLocation(SourceLocation Loc) const {
Chris Lattnerf1ca7d32009-01-27 07:57:44 +0000215 Loc.dump(SourceMgr);
Chris Lattnerd01e2912006-06-18 16:22:51 +0000216}
217
218void Preprocessor::DumpMacro(const MacroInfo &MI) const {
Benjamin Kramer89b422c2009-08-23 12:08:50 +0000219 llvm::errs() << "MACRO: ";
Chris Lattnerd01e2912006-06-18 16:22:51 +0000220 for (unsigned i = 0, e = MI.getNumTokens(); i != e; ++i) {
221 DumpToken(MI.getReplacementToken(i));
Benjamin Kramer89b422c2009-08-23 12:08:50 +0000222 llvm::errs() << " ";
Chris Lattnerd01e2912006-06-18 16:22:51 +0000223 }
Benjamin Kramer89b422c2009-08-23 12:08:50 +0000224 llvm::errs() << "\n";
Chris Lattnerd01e2912006-06-18 16:22:51 +0000225}
226
Chris Lattner22eb9722006-06-18 05:43:12 +0000227void Preprocessor::PrintStats() {
Benjamin Kramer89b422c2009-08-23 12:08:50 +0000228 llvm::errs() << "\n*** Preprocessor Stats:\n";
229 llvm::errs() << NumDirectives << " directives found:\n";
230 llvm::errs() << " " << NumDefined << " #define.\n";
231 llvm::errs() << " " << NumUndefined << " #undef.\n";
232 llvm::errs() << " #include/#include_next/#import:\n";
233 llvm::errs() << " " << NumEnteredSourceFiles << " source files entered.\n";
234 llvm::errs() << " " << MaxIncludeStackDepth << " max include stack depth\n";
235 llvm::errs() << " " << NumIf << " #if/#ifndef/#ifdef.\n";
236 llvm::errs() << " " << NumElse << " #else/#elif.\n";
237 llvm::errs() << " " << NumEndif << " #endif.\n";
238 llvm::errs() << " " << NumPragma << " #pragma.\n";
239 llvm::errs() << NumSkipped << " #if/#ifndef#ifdef regions skipped\n";
Chris Lattner22eb9722006-06-18 05:43:12 +0000240
Benjamin Kramer89b422c2009-08-23 12:08:50 +0000241 llvm::errs() << NumMacroExpanded << "/" << NumFnMacroExpanded << "/"
Ted Kremeneka0a3e9b2008-01-14 16:44:48 +0000242 << NumBuiltinMacroExpanded << " obj/fn/builtin macros expanded, "
243 << NumFastMacroExpanded << " on the fast path.\n";
Benjamin Kramer89b422c2009-08-23 12:08:50 +0000244 llvm::errs() << (NumFastTokenPaste+NumTokenPaste)
Ted Kremeneka0a3e9b2008-01-14 16:44:48 +0000245 << " token paste (##) operations performed, "
246 << NumFastTokenPaste << " on the fast path.\n";
Alexander Kornienko199cd942012-08-13 10:46:42 +0000247
248 llvm::errs() << "\nPreprocessor Memory: " << getTotalMemory() << "B total";
249
250 llvm::errs() << "\n BumpPtr: " << BP.getTotalMemory();
251 llvm::errs() << "\n Macro Expanded Tokens: "
252 << llvm::capacity_in_bytes(MacroExpandedTokens);
253 llvm::errs() << "\n Predefines Buffer: " << Predefines.capacity();
254 llvm::errs() << "\n Macros: " << llvm::capacity_in_bytes(Macros);
255 llvm::errs() << "\n #pragma push_macro Info: "
256 << llvm::capacity_in_bytes(PragmaPushMacroInfo);
257 llvm::errs() << "\n Poison Reasons: "
258 << llvm::capacity_in_bytes(PoisonReasons);
259 llvm::errs() << "\n Comment Handlers: "
260 << llvm::capacity_in_bytes(CommentHandlers) << "\n";
Chris Lattner22eb9722006-06-18 05:43:12 +0000261}
262
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +0000263Preprocessor::macro_iterator
264Preprocessor::macro_begin(bool IncludeExternalMacros) const {
265 if (IncludeExternalMacros && ExternalSource &&
Douglas Gregor9882a5a2010-01-04 19:18:44 +0000266 !ReadMacrosFromExternalSource) {
267 ReadMacrosFromExternalSource = true;
268 ExternalSource->ReadDefinedMacros();
269 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +0000270
271 return Macros.begin();
Douglas Gregor9882a5a2010-01-04 19:18:44 +0000272}
273
Argyrios Kyrtzidise379ee32011-06-29 22:20:04 +0000274size_t Preprocessor::getTotalMemory() const {
Ted Kremenek182543a2011-07-26 21:17:24 +0000275 return BP.getTotalMemory()
Ted Kremenek8b77fe72011-07-27 18:41:23 +0000276 + llvm::capacity_in_bytes(MacroExpandedTokens)
Ted Kremenek182543a2011-07-26 21:17:24 +0000277 + Predefines.capacity() /* Predefines buffer. */
Ted Kremenek8b77fe72011-07-27 18:41:23 +0000278 + llvm::capacity_in_bytes(Macros)
279 + llvm::capacity_in_bytes(PragmaPushMacroInfo)
280 + llvm::capacity_in_bytes(PoisonReasons)
281 + llvm::capacity_in_bytes(CommentHandlers);
Argyrios Kyrtzidise379ee32011-06-29 22:20:04 +0000282}
283
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +0000284Preprocessor::macro_iterator
285Preprocessor::macro_end(bool IncludeExternalMacros) const {
286 if (IncludeExternalMacros && ExternalSource &&
Douglas Gregor9882a5a2010-01-04 19:18:44 +0000287 !ReadMacrosFromExternalSource) {
288 ReadMacrosFromExternalSource = true;
289 ExternalSource->ReadDefinedMacros();
290 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +0000291
292 return Macros.end();
Douglas Gregor9882a5a2010-01-04 19:18:44 +0000293}
294
Dmitri Gribenko6743e042012-09-29 11:40:46 +0000295/// \brief Compares macro tokens with a specified token value sequence.
296static bool MacroDefinitionEquals(const MacroInfo *MI,
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000297 ArrayRef<TokenValue> Tokens) {
Dmitri Gribenko6743e042012-09-29 11:40:46 +0000298 return Tokens.size() == MI->getNumTokens() &&
299 std::equal(Tokens.begin(), Tokens.end(), MI->tokens_begin());
300}
301
302StringRef Preprocessor::getLastMacroWithSpelling(
303 SourceLocation Loc,
304 ArrayRef<TokenValue> Tokens) const {
305 SourceLocation BestLocation;
306 StringRef BestSpelling;
307 for (Preprocessor::macro_iterator I = macro_begin(), E = macro_end();
308 I != E; ++I) {
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +0000309 if (!I->second->getMacroInfo()->isObjectLike())
Dmitri Gribenko6743e042012-09-29 11:40:46 +0000310 continue;
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +0000311 const MacroDirective::DefInfo
312 Def = I->second->findDirectiveAtLoc(Loc, SourceMgr);
313 if (!Def)
Dmitri Gribenko6743e042012-09-29 11:40:46 +0000314 continue;
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +0000315 if (!MacroDefinitionEquals(Def.getMacroInfo(), Tokens))
Dmitri Gribenko6743e042012-09-29 11:40:46 +0000316 continue;
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +0000317 SourceLocation Location = Def.getLocation();
Dmitri Gribenko6743e042012-09-29 11:40:46 +0000318 // Choose the macro defined latest.
319 if (BestLocation.isInvalid() ||
320 (Location.isValid() &&
321 SourceMgr.isBeforeInTranslationUnit(BestLocation, Location))) {
322 BestLocation = Location;
323 BestSpelling = I->first->getName();
324 }
325 }
326 return BestSpelling;
327}
328
Douglas Gregor8d76cca2012-01-04 06:20:15 +0000329void Preprocessor::recomputeCurLexerKind() {
330 if (CurLexer)
331 CurLexerKind = CLK_Lexer;
332 else if (CurPTHLexer)
333 CurLexerKind = CLK_PTHLexer;
334 else if (CurTokenLexer)
335 CurLexerKind = CLK_TokenLexer;
336 else
337 CurLexerKind = CLK_CachingLexer;
338}
339
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +0000340bool Preprocessor::SetCodeCompletionPoint(const FileEntry *File,
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +0000341 unsigned CompleteLine,
342 unsigned CompleteColumn) {
343 assert(File);
344 assert(CompleteLine && CompleteColumn && "Starts from 1:1");
345 assert(!CodeCompletionFile && "Already set");
346
Douglas Gregor53ad6b92009-12-02 06:49:09 +0000347 using llvm::MemoryBuffer;
348
Douglas Gregor53ad6b92009-12-02 06:49:09 +0000349 // Load the actual file's contents.
Douglas Gregor26266da2010-03-16 19:49:24 +0000350 bool Invalid = false;
351 const MemoryBuffer *Buffer = SourceMgr.getMemoryBufferForFile(File, &Invalid);
352 if (Invalid)
Douglas Gregor53ad6b92009-12-02 06:49:09 +0000353 return true;
354
355 // Find the byte position of the truncation point.
356 const char *Position = Buffer->getBufferStart();
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +0000357 for (unsigned Line = 1; Line < CompleteLine; ++Line) {
Douglas Gregor53ad6b92009-12-02 06:49:09 +0000358 for (; *Position; ++Position) {
359 if (*Position != '\r' && *Position != '\n')
360 continue;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +0000361
Douglas Gregor53ad6b92009-12-02 06:49:09 +0000362 // Eat \r\n or \n\r as a single line.
363 if ((Position[1] == '\r' || Position[1] == '\n') &&
364 Position[0] != Position[1])
365 ++Position;
366 ++Position;
367 break;
368 }
369 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +0000370
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +0000371 Position += CompleteColumn - 1;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +0000372
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +0000373 // Insert '\0' at the code-completion point.
Douglas Gregor9291ab62009-12-08 21:45:46 +0000374 if (Position < Buffer->getBufferEnd()) {
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +0000375 CodeCompletionFile = File;
376 CodeCompletionOffset = Position - Buffer->getBufferStart();
377
378 MemoryBuffer *NewBuffer =
379 MemoryBuffer::getNewUninitMemBuffer(Buffer->getBufferSize() + 1,
380 Buffer->getBufferIdentifier());
Benjamin Kramer60053cf2011-09-04 20:26:28 +0000381 char *NewBuf = const_cast<char*>(NewBuffer->getBufferStart());
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +0000382 char *NewPos = std::copy(Buffer->getBufferStart(), Position, NewBuf);
383 *NewPos = '\0';
384 std::copy(Position, Buffer->getBufferEnd(), NewPos+1);
385 SourceMgr.overrideFileContents(File, NewBuffer);
Douglas Gregor53ad6b92009-12-02 06:49:09 +0000386 }
387
388 return false;
389}
390
Douglas Gregor11583702010-08-25 17:04:25 +0000391void Preprocessor::CodeCompleteNaturalLanguage() {
Douglas Gregor11583702010-08-25 17:04:25 +0000392 if (CodeComplete)
393 CodeComplete->CodeCompleteNaturalLanguage();
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +0000394 setCodeCompletionReached();
Douglas Gregor11583702010-08-25 17:04:25 +0000395}
396
Benjamin Kramera197fb62010-02-27 17:05:45 +0000397/// getSpelling - This method is used to get the spelling of a token into a
398/// SmallVector. Note that the returned StringRef may not point to the
399/// supplied buffer if a copy can be avoided.
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000400StringRef Preprocessor::getSpelling(const Token &Tok,
401 SmallVectorImpl<char> &Buffer,
Douglas Gregor7bda4b82010-03-16 05:20:39 +0000402 bool *Invalid) const {
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +0000403 // NOTE: this has to be checked *before* testing for an IdentifierInfo.
Jordan Rose7f43ddd2013-01-24 20:50:46 +0000404 if (Tok.isNot(tok::raw_identifier) && !Tok.hasUCN()) {
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +0000405 // Try the fast path.
406 if (const IdentifierInfo *II = Tok.getIdentifierInfo())
407 return II->getName();
408 }
Benjamin Kramera197fb62010-02-27 17:05:45 +0000409
410 // Resize the buffer if we need to copy into it.
411 if (Tok.needsCleaning())
412 Buffer.resize(Tok.getLength());
413
414 const char *Ptr = Buffer.data();
Douglas Gregor7bda4b82010-03-16 05:20:39 +0000415 unsigned Len = getSpelling(Tok, Ptr, Invalid);
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000416 return StringRef(Ptr, Len);
Benjamin Kramera197fb62010-02-27 17:05:45 +0000417}
418
Chris Lattnerb94ec7b2006-07-14 06:54:10 +0000419/// CreateString - Plop the specified string into a scratch buffer and return a
420/// location for it. If specified, the source location provides a source
421/// location for the token.
Dmitri Gribenkob8e9e752012-09-24 21:07:17 +0000422void Preprocessor::CreateString(StringRef Str, Token &Tok,
Abramo Bagnarae398e602011-10-03 18:39:03 +0000423 SourceLocation ExpansionLocStart,
424 SourceLocation ExpansionLocEnd) {
Dmitri Gribenkob8e9e752012-09-24 21:07:17 +0000425 Tok.setLength(Str.size());
Mike Stump11289f42009-09-09 15:08:12 +0000426
Chris Lattner5a7971e2009-01-26 19:29:26 +0000427 const char *DestPtr;
Dmitri Gribenkob8e9e752012-09-24 21:07:17 +0000428 SourceLocation Loc = ScratchBuf->getToken(Str.data(), Str.size(), DestPtr);
Mike Stump11289f42009-09-09 15:08:12 +0000429
Abramo Bagnarae398e602011-10-03 18:39:03 +0000430 if (ExpansionLocStart.isValid())
431 Loc = SourceMgr.createExpansionLoc(Loc, ExpansionLocStart,
Dmitri Gribenkob8e9e752012-09-24 21:07:17 +0000432 ExpansionLocEnd, Str.size());
Chris Lattner5a7971e2009-01-26 19:29:26 +0000433 Tok.setLocation(Loc);
Mike Stump11289f42009-09-09 15:08:12 +0000434
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +0000435 // If this is a raw identifier or a literal token, set the pointer data.
436 if (Tok.is(tok::raw_identifier))
437 Tok.setRawIdentifierData(DestPtr);
438 else if (Tok.isLiteral())
Chris Lattner5a7971e2009-01-26 19:29:26 +0000439 Tok.setLiteralData(DestPtr);
Chris Lattnerb94ec7b2006-07-14 06:54:10 +0000440}
441
Douglas Gregor2b82c2a2011-12-02 01:47:07 +0000442Module *Preprocessor::getCurrentModule() {
David Blaikiebbafb8a2012-03-11 07:00:24 +0000443 if (getLangOpts().CurrentModule.empty())
Craig Topperd2d442c2014-05-17 23:10:59 +0000444 return nullptr;
445
David Blaikiebbafb8a2012-03-11 07:00:24 +0000446 return getHeaderSearchInfo().lookupModule(getLangOpts().CurrentModule);
Douglas Gregor2b82c2a2011-12-02 01:47:07 +0000447}
Chris Lattner8a7003c2007-07-16 06:48:38 +0000448
Chris Lattner1f1b0db2007-10-09 22:10:18 +0000449//===----------------------------------------------------------------------===//
450// Preprocessor Initialization Methods
451//===----------------------------------------------------------------------===//
452
Chris Lattner1f1b0db2007-10-09 22:10:18 +0000453
454/// EnterMainSourceFile - Enter the specified FileID as the main source file,
Nate Begemanf7c3ff62008-01-07 04:01:26 +0000455/// which implicitly adds the builtin defines etc.
Chris Lattnerfb24a3a2010-04-20 20:35:58 +0000456void Preprocessor::EnterMainSourceFile() {
Chris Lattner9ef847b2009-02-13 19:33:24 +0000457 // We do not allow the preprocessor to reenter the main file. Doing so will
458 // cause FileID's to accumulate information from both runs (e.g. #line
459 // information) and predefined macros aren't guaranteed to be set properly.
460 assert(NumEnteredSourceFiles == 0 && "Cannot reenter the main file!");
Chris Lattnerd32480d2009-01-17 06:22:33 +0000461 FileID MainFileID = SourceMgr.getMainFileID();
Mike Stump11289f42009-09-09 15:08:12 +0000462
Argyrios Kyrtzidis9afd4492012-01-05 21:36:25 +0000463 // If MainFileID is loaded it means we loaded an AST file, no need to enter
464 // a main file.
465 if (!SourceMgr.isLoadedFileID(MainFileID)) {
466 // Enter the main file source buffer.
Craig Topperd2d442c2014-05-17 23:10:59 +0000467 EnterSourceFile(MainFileID, nullptr, SourceLocation());
468
Argyrios Kyrtzidis9afd4492012-01-05 21:36:25 +0000469 // If we've been asked to skip bytes in the main file (e.g., as part of a
470 // precompiled preamble), do so now.
471 if (SkipMainFilePreamble.first > 0)
472 CurLexer->SkipBytes(SkipMainFilePreamble.first,
473 SkipMainFilePreamble.second);
474
475 // Tell the header info that the main file was entered. If the file is later
476 // #imported, it won't be re-entered.
477 if (const FileEntry *FE = SourceMgr.getFileEntryForID(MainFileID))
478 HeaderInfo.IncrementIncludeCount(FE);
479 }
Mike Stump11289f42009-09-09 15:08:12 +0000480
Benjamin Kramerd77adb52009-12-31 15:33:09 +0000481 // Preprocess Predefines to populate the initial preprocessor state.
Mike Stump11289f42009-09-09 15:08:12 +0000482 llvm::MemoryBuffer *SB =
Chris Lattner58c79342010-04-05 22:42:27 +0000483 llvm::MemoryBuffer::getMemBufferCopy(Predefines, "<built-in>");
Douglas Gregor33551892010-08-26 14:07:34 +0000484 assert(SB && "Cannot create predefined source buffer");
Alp Toker6ac2cd02014-05-16 17:23:01 +0000485 FileID FID = SourceMgr.createFileID(SB);
Chris Lattnerd32480d2009-01-17 06:22:33 +0000486 assert(!FID.isInvalid() && "Could not create FileID for predefines?");
Argyrios Kyrtzidis22c22f52013-02-01 16:36:07 +0000487 setPredefinesFileID(FID);
Mike Stump11289f42009-09-09 15:08:12 +0000488
Chris Lattner1f1b0db2007-10-09 22:10:18 +0000489 // Start parsing the predefines.
Craig Topperd2d442c2014-05-17 23:10:59 +0000490 EnterSourceFile(FID, nullptr, SourceLocation());
Chris Lattner1f1b0db2007-10-09 22:10:18 +0000491}
Chris Lattner8a7003c2007-07-16 06:48:38 +0000492
Daniel Dunbarcb9eaf52010-03-23 05:09:10 +0000493void Preprocessor::EndSourceFile() {
494 // Notify the client that we reached the end of the source file.
495 if (Callbacks)
496 Callbacks->EndOfMainFile();
497}
Chris Lattner677757a2006-06-28 05:26:32 +0000498
499//===----------------------------------------------------------------------===//
500// Lexer Event Handling.
501//===----------------------------------------------------------------------===//
502
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +0000503/// LookUpIdentifierInfo - Given a tok::raw_identifier token, look up the
504/// identifier information for the token and install it into the token,
505/// updating the token kind accordingly.
506IdentifierInfo *Preprocessor::LookUpIdentifierInfo(Token &Identifier) const {
Alp Toker2d57cea2014-05-17 04:53:25 +0000507 assert(!Identifier.getRawIdentifier().empty() && "No raw identifier data!");
Mike Stump11289f42009-09-09 15:08:12 +0000508
Chris Lattnercefc7682006-07-08 08:28:12 +0000509 // Look up this token, see if it is a macro, or if it is a language keyword.
510 IdentifierInfo *II;
Jordan Rose7f43ddd2013-01-24 20:50:46 +0000511 if (!Identifier.needsCleaning() && !Identifier.hasUCN()) {
Chris Lattnercefc7682006-07-08 08:28:12 +0000512 // No cleaning needed, just use the characters from the lexed buffer.
Alp Toker2d57cea2014-05-17 04:53:25 +0000513 II = getIdentifierInfo(Identifier.getRawIdentifier());
Chris Lattnercefc7682006-07-08 08:28:12 +0000514 } else {
515 // Cleaning needed, alloca a buffer, clean into it, then use the buffer.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +0000516 SmallString<64> IdentifierBuffer;
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000517 StringRef CleanedStr = getSpelling(Identifier, IdentifierBuffer);
Jordan Rose7f43ddd2013-01-24 20:50:46 +0000518
519 if (Identifier.hasUCN()) {
520 SmallString<64> UCNIdentifierBuffer;
521 expandUCNs(UCNIdentifierBuffer, CleanedStr);
522 II = getIdentifierInfo(UCNIdentifierBuffer);
523 } else {
524 II = getIdentifierInfo(CleanedStr);
525 }
Chris Lattnercefc7682006-07-08 08:28:12 +0000526 }
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +0000527
528 // Update the token info (identifier info and appropriate token kind).
Chris Lattner8c204872006-10-14 05:19:21 +0000529 Identifier.setIdentifierInfo(II);
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +0000530 Identifier.setKind(II->getTokenID());
531
Chris Lattnercefc7682006-07-08 08:28:12 +0000532 return II;
533}
534
John Wiegley1c0675e2011-04-28 01:08:34 +0000535void Preprocessor::SetPoisonReason(IdentifierInfo *II, unsigned DiagID) {
536 PoisonReasons[II] = DiagID;
537}
538
539void Preprocessor::PoisonSEHIdentifiers(bool Poison) {
540 assert(Ident__exception_code && Ident__exception_info);
541 assert(Ident___exception_code && Ident___exception_info);
542 Ident__exception_code->setIsPoisoned(Poison);
543 Ident___exception_code->setIsPoisoned(Poison);
544 Ident_GetExceptionCode->setIsPoisoned(Poison);
545 Ident__exception_info->setIsPoisoned(Poison);
546 Ident___exception_info->setIsPoisoned(Poison);
547 Ident_GetExceptionInfo->setIsPoisoned(Poison);
548 Ident__abnormal_termination->setIsPoisoned(Poison);
549 Ident___abnormal_termination->setIsPoisoned(Poison);
550 Ident_AbnormalTermination->setIsPoisoned(Poison);
551}
552
553void Preprocessor::HandlePoisonedIdentifier(Token & Identifier) {
554 assert(Identifier.getIdentifierInfo() &&
555 "Can't handle identifiers without identifier info!");
556 llvm::DenseMap<IdentifierInfo*,unsigned>::const_iterator it =
557 PoisonReasons.find(Identifier.getIdentifierInfo());
558 if(it == PoisonReasons.end())
559 Diag(Identifier, diag::err_pp_used_poisoned_id);
560 else
561 Diag(Identifier,it->second) << Identifier.getIdentifierInfo();
562}
Chris Lattnercefc7682006-07-08 08:28:12 +0000563
Chris Lattner677757a2006-06-28 05:26:32 +0000564/// HandleIdentifier - This callback is invoked when the lexer reads an
565/// identifier. This callback looks up the identifier in the map and/or
566/// potentially macro expands it or turns it into a named token (like 'for').
Chris Lattnerad89ec02009-01-21 07:43:11 +0000567///
568/// Note that callers of this method are guarded by checking the
569/// IdentifierInfo's 'isHandleIdentifierCase' bit. If this method changes, the
570/// IdentifierInfo methods that compute these properties will need to change to
571/// match.
Eli Friedman0834a4b2013-09-19 00:41:32 +0000572bool Preprocessor::HandleIdentifier(Token &Identifier) {
Chris Lattner0f1f5052006-07-20 04:16:23 +0000573 assert(Identifier.getIdentifierInfo() &&
574 "Can't handle identifiers without identifier info!");
Mike Stump11289f42009-09-09 15:08:12 +0000575
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000576 IdentifierInfo &II = *Identifier.getIdentifierInfo();
Chris Lattner677757a2006-06-28 05:26:32 +0000577
Douglas Gregor935bc7a22011-10-27 09:33:13 +0000578 // If the information about this identifier is out of date, update it from
579 // the external source.
Douglas Gregor3f568c12012-06-29 18:27:59 +0000580 // We have to treat __VA_ARGS__ in a special way, since it gets
581 // serialized with isPoisoned = true, but our preprocessor may have
582 // unpoisoned it if we're defining a C99 macro.
Douglas Gregor935bc7a22011-10-27 09:33:13 +0000583 if (II.isOutOfDate()) {
Douglas Gregor3f568c12012-06-29 18:27:59 +0000584 bool CurrentIsPoisoned = false;
585 if (&II == Ident__VA_ARGS__)
586 CurrentIsPoisoned = Ident__VA_ARGS__->isPoisoned();
587
Douglas Gregor935bc7a22011-10-27 09:33:13 +0000588 ExternalSource->updateOutOfDateIdentifier(II);
589 Identifier.setKind(II.getTokenID());
Douglas Gregor3f568c12012-06-29 18:27:59 +0000590
591 if (&II == Ident__VA_ARGS__)
592 II.setIsPoisoned(CurrentIsPoisoned);
Douglas Gregor935bc7a22011-10-27 09:33:13 +0000593 }
594
Chris Lattner677757a2006-06-28 05:26:32 +0000595 // If this identifier was poisoned, and if it was not produced from a macro
596 // expansion, emit an error.
Ted Kremeneka2c3c8d2008-11-19 22:43:49 +0000597 if (II.isPoisoned() && CurPPLexer) {
John Wiegley1c0675e2011-04-28 01:08:34 +0000598 HandlePoisonedIdentifier(Identifier);
Chris Lattner8ff71992006-07-06 05:17:39 +0000599 }
Mike Stump11289f42009-09-09 15:08:12 +0000600
Chris Lattner78186052006-07-09 00:45:31 +0000601 // If this is a macro to be expanded, do it.
Argyrios Kyrtzidisfead64b2013-02-24 00:05:14 +0000602 if (MacroDirective *MD = getMacroDirective(&II)) {
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +0000603 MacroInfo *MI = MD->getMacroInfo();
Abramo Bagnara123bec82012-01-01 22:01:04 +0000604 if (!DisableMacroExpansion) {
Richard Smith181879c2012-12-12 02:46:14 +0000605 if (!Identifier.isExpandDisabled() && MI->isEnabled()) {
Eli Friedman0834a4b2013-09-19 00:41:32 +0000606 // C99 6.10.3p10: If the preprocessing token immediately after the
607 // macro name isn't a '(', this macro should not be expanded.
608 if (!MI->isFunctionLike() || isNextPPTokenLParen())
609 return HandleMacroExpandedIdentifier(Identifier, MD);
Chris Lattner6e4bf522006-07-27 06:59:25 +0000610 } else {
611 // C99 6.10.3.4p2 says that a disabled macro may never again be
612 // expanded, even if it's in a context where it could be expanded in the
613 // future.
Chris Lattner146762e2007-07-20 16:59:19 +0000614 Identifier.setFlag(Token::DisableExpand);
Richard Smith181879c2012-12-12 02:46:14 +0000615 if (MI->isObjectLike() || isNextPPTokenLParen())
616 Diag(Identifier, diag::pp_disabled_macro_expansion);
Chris Lattner6e4bf522006-07-27 06:59:25 +0000617 }
618 }
Chris Lattner063400e2006-10-14 19:54:15 +0000619 }
Chris Lattner677757a2006-06-28 05:26:32 +0000620
Richard Smith4dd85d62011-10-11 19:57:52 +0000621 // If this identifier is a keyword in C++11, produce a warning. Don't warn if
622 // we're not considering macro expansion, since this identifier might be the
623 // name of a macro.
624 // FIXME: This warning is disabled in cases where it shouldn't be, like
625 // "#define constexpr constexpr", "int constexpr;"
Alp Toker7d2fea22014-02-24 04:35:58 +0000626 if (II.isCXX11CompatKeyword() && !DisableMacroExpansion) {
Richard Smith4dd85d62011-10-11 19:57:52 +0000627 Diag(Identifier, diag::warn_cxx11_keyword) << II.getName();
628 // Don't diagnose this keyword again in this translation unit.
629 II.setIsCXX11CompatKeyword(false);
630 }
631
Chris Lattner5b9f4892006-11-21 17:23:33 +0000632 // C++ 2.11p2: If this is an alternative representation of a C++ operator,
633 // then we act as if it is the actual operator and not the textual
634 // representation of it.
Fariborz Jahanian9e42a952010-09-03 17:33:04 +0000635 if (II.isCPlusPlusOperatorKeyword())
Craig Topperd2d442c2014-05-17 23:10:59 +0000636 Identifier.setIdentifierInfo(nullptr);
Chris Lattner5b9f4892006-11-21 17:23:33 +0000637
Chris Lattner677757a2006-06-28 05:26:32 +0000638 // If this is an extension token, diagnose its use.
Steve Naroffc84e8b72008-09-02 18:50:17 +0000639 // We avoid diagnosing tokens that originate from macro definitions.
Eli Friedman6bba2ad2009-04-28 03:59:15 +0000640 // FIXME: This warning is disabled in cases where it shouldn't be,
641 // like "#define TY typeof", "TY(1) x".
642 if (II.isExtensionToken() && !DisableMacroExpansion)
Chris Lattner53621a52007-06-13 20:44:40 +0000643 Diag(Identifier, diag::ext_token_used);
Douglas Gregoraf5c4842011-09-07 23:11:54 +0000644
Douglas Gregor594b8c92013-11-07 22:55:02 +0000645 // If this is the 'import' contextual keyword following an '@', note
Ted Kremenekc1e4dd02012-03-01 22:07:04 +0000646 // that the next token indicates a module name.
Douglas Gregor8d76cca2012-01-04 06:20:15 +0000647 //
Douglas Gregorc50d4922012-12-11 22:11:52 +0000648 // Note that we do not treat 'import' as a contextual
Ted Kremenekc1e4dd02012-03-01 22:07:04 +0000649 // keyword when we're in a caching lexer, because caching lexers only get
650 // used in contexts where import declarations are disallowed.
Douglas Gregor594b8c92013-11-07 22:55:02 +0000651 if (LastTokenWasAt && II.isModulesImport() && !InMacroArgs &&
652 !DisableMacroExpansion && getLangOpts().Modules &&
653 CurLexerKind != CLK_CachingLexer) {
Douglas Gregoraf5c4842011-09-07 23:11:54 +0000654 ModuleImportLoc = Identifier.getLocation();
Douglas Gregor1805b8a2011-11-30 04:26:53 +0000655 ModuleImportPath.clear();
656 ModuleImportExpectsIdentifier = true;
Douglas Gregoraf5c4842011-09-07 23:11:54 +0000657 CurLexerKind = CLK_LexAfterModuleImport;
658 }
Eli Friedman0834a4b2013-09-19 00:41:32 +0000659 return true;
Douglas Gregor08142532011-08-26 23:56:07 +0000660}
661
Eli Friedman0834a4b2013-09-19 00:41:32 +0000662void Preprocessor::Lex(Token &Result) {
663 // We loop here until a lex function retuns a token; this avoids recursion.
664 bool ReturnedToken;
665 do {
666 switch (CurLexerKind) {
667 case CLK_Lexer:
668 ReturnedToken = CurLexer->Lex(Result);
669 break;
670 case CLK_PTHLexer:
671 ReturnedToken = CurPTHLexer->Lex(Result);
672 break;
673 case CLK_TokenLexer:
674 ReturnedToken = CurTokenLexer->Lex(Result);
675 break;
676 case CLK_CachingLexer:
677 CachingLex(Result);
678 ReturnedToken = true;
679 break;
680 case CLK_LexAfterModuleImport:
681 LexAfterModuleImport(Result);
682 ReturnedToken = true;
683 break;
684 }
685 } while (!ReturnedToken);
Douglas Gregor594b8c92013-11-07 22:55:02 +0000686
687 LastTokenWasAt = Result.is(tok::at);
Eli Friedman0834a4b2013-09-19 00:41:32 +0000688}
689
690
Douglas Gregorda82e702012-01-03 19:32:59 +0000691/// \brief Lex a token following the 'import' contextual keyword.
Douglas Gregor22d09742012-01-03 18:04:46 +0000692///
Douglas Gregoraf5c4842011-09-07 23:11:54 +0000693void Preprocessor::LexAfterModuleImport(Token &Result) {
694 // Figure out what kind of lexer we actually have.
Douglas Gregor8d76cca2012-01-04 06:20:15 +0000695 recomputeCurLexerKind();
Douglas Gregoraf5c4842011-09-07 23:11:54 +0000696
697 // Lex the next token.
698 Lex(Result);
699
Douglas Gregor08142532011-08-26 23:56:07 +0000700 // The token sequence
701 //
Douglas Gregor22d09742012-01-03 18:04:46 +0000702 // import identifier (. identifier)*
703 //
Douglas Gregorda82e702012-01-03 19:32:59 +0000704 // indicates a module import directive. We already saw the 'import'
705 // contextual keyword, so now we're looking for the identifiers.
Douglas Gregor1805b8a2011-11-30 04:26:53 +0000706 if (ModuleImportExpectsIdentifier && Result.getKind() == tok::identifier) {
707 // We expected to see an identifier here, and we did; continue handling
708 // identifiers.
709 ModuleImportPath.push_back(std::make_pair(Result.getIdentifierInfo(),
710 Result.getLocation()));
711 ModuleImportExpectsIdentifier = false;
712 CurLexerKind = CLK_LexAfterModuleImport;
Douglas Gregor08142532011-08-26 23:56:07 +0000713 return;
Douglas Gregor1805b8a2011-11-30 04:26:53 +0000714 }
Douglas Gregor08142532011-08-26 23:56:07 +0000715
Douglas Gregor1805b8a2011-11-30 04:26:53 +0000716 // If we're expecting a '.' or a ';', and we got a '.', then wait until we
717 // see the next identifier.
718 if (!ModuleImportExpectsIdentifier && Result.getKind() == tok::period) {
719 ModuleImportExpectsIdentifier = true;
720 CurLexerKind = CLK_LexAfterModuleImport;
721 return;
722 }
723
724 // If we have a non-empty module path, load the named module.
Daniel Jasper07e6c402013-08-05 20:26:17 +0000725 if (!ModuleImportPath.empty() && getLangOpts().Modules) {
Argyrios Kyrtzidis19d78b72012-09-29 01:06:10 +0000726 Module *Imported = TheModuleLoader.loadModule(ModuleImportLoc,
727 ModuleImportPath,
728 Module::MacrosVisible,
729 /*IsIncludeDirective=*/false);
730 if (Callbacks)
731 Callbacks->moduleImport(ModuleImportLoc, ModuleImportPath, Imported);
732 }
Chris Lattner677757a2006-06-28 05:26:32 +0000733}
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000734
Andy Gibbs58905d22012-11-17 19:15:38 +0000735bool Preprocessor::FinishLexStringLiteral(Token &Result, std::string &String,
Andy Gibbsa8df57a2012-11-17 19:16:52 +0000736 const char *DiagnosticTag,
Andy Gibbs58905d22012-11-17 19:15:38 +0000737 bool AllowMacroExpansion) {
738 // We need at least one string literal.
739 if (Result.isNot(tok::string_literal)) {
Andy Gibbsa8df57a2012-11-17 19:16:52 +0000740 Diag(Result, diag::err_expected_string_literal)
741 << /*Source='in...'*/0 << DiagnosticTag;
Andy Gibbs58905d22012-11-17 19:15:38 +0000742 return false;
743 }
744
745 // Lex string literal tokens, optionally with macro expansion.
746 SmallVector<Token, 4> StrToks;
747 do {
748 StrToks.push_back(Result);
749
750 if (Result.hasUDSuffix())
751 Diag(Result, diag::err_invalid_string_udl);
752
753 if (AllowMacroExpansion)
754 Lex(Result);
755 else
756 LexUnexpandedToken(Result);
757 } while (Result.is(tok::string_literal));
758
759 // Concatenate and parse the strings.
Craig Topper9d5583e2014-06-26 04:58:39 +0000760 StringLiteralParser Literal(StrToks, *this);
Andy Gibbs58905d22012-11-17 19:15:38 +0000761 assert(Literal.isAscii() && "Didn't allow wide strings in");
762
763 if (Literal.hadError)
764 return false;
765
766 if (Literal.Pascal) {
Andy Gibbsa8df57a2012-11-17 19:16:52 +0000767 Diag(StrToks[0].getLocation(), diag::err_expected_string_literal)
768 << /*Source='in...'*/0 << DiagnosticTag;
Andy Gibbs58905d22012-11-17 19:15:38 +0000769 return false;
770 }
771
772 String = Literal.GetString();
773 return true;
774}
775
Reid Klecknerc0dca6d2014-02-12 23:50:26 +0000776bool Preprocessor::parseSimpleIntegerLiteral(Token &Tok, uint64_t &Value) {
777 assert(Tok.is(tok::numeric_constant));
778 SmallString<8> IntegerBuffer;
779 bool NumberInvalid = false;
780 StringRef Spelling = getSpelling(Tok, IntegerBuffer, &NumberInvalid);
781 if (NumberInvalid)
782 return false;
783 NumericLiteralParser Literal(Spelling, Tok.getLocation(), *this);
784 if (Literal.hadError || !Literal.isIntegerLiteral() || Literal.hasUDSuffix())
785 return false;
786 llvm::APInt APVal(64, 0);
787 if (Literal.GetIntegerValue(APVal))
788 return false;
789 Lex(Tok);
790 Value = APVal.getLimitedValue();
791 return true;
792}
793
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000794void Preprocessor::addCommentHandler(CommentHandler *Handler) {
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000795 assert(Handler && "NULL comment handler");
796 assert(std::find(CommentHandlers.begin(), CommentHandlers.end(), Handler) ==
797 CommentHandlers.end() && "Comment handler already registered");
798 CommentHandlers.push_back(Handler);
799}
800
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000801void Preprocessor::removeCommentHandler(CommentHandler *Handler) {
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000802 std::vector<CommentHandler *>::iterator Pos
803 = std::find(CommentHandlers.begin(), CommentHandlers.end(), Handler);
804 assert(Pos != CommentHandlers.end() && "Comment handler not registered");
805 CommentHandlers.erase(Pos);
806}
807
Chris Lattner87d02082010-01-18 22:35:47 +0000808bool Preprocessor::HandleComment(Token &result, SourceRange Comment) {
809 bool AnyPendingTokens = false;
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000810 for (std::vector<CommentHandler *>::iterator H = CommentHandlers.begin(),
811 HEnd = CommentHandlers.end();
Chris Lattner87d02082010-01-18 22:35:47 +0000812 H != HEnd; ++H) {
813 if ((*H)->HandleComment(*this, Comment))
814 AnyPendingTokens = true;
815 }
816 if (!AnyPendingTokens || getCommentRetentionState())
817 return false;
818 Lex(result);
819 return true;
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000820}
821
Douglas Gregor08142532011-08-26 23:56:07 +0000822ModuleLoader::~ModuleLoader() { }
823
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000824CommentHandler::~CommentHandler() { }
Douglas Gregor7f6d60d2010-03-19 16:15:56 +0000825
Douglas Gregor3a7ad252010-08-24 19:08:16 +0000826CodeCompletionHandler::~CodeCompletionHandler() { }
827
Argyrios Kyrtzidisf3d587e2012-12-04 07:27:05 +0000828void Preprocessor::createPreprocessingRecord() {
Douglas Gregor7f6d60d2010-03-19 16:15:56 +0000829 if (Record)
830 return;
831
Argyrios Kyrtzidisf3d587e2012-12-04 07:27:05 +0000832 Record = new PreprocessingRecord(getSourceManager());
Douglas Gregor7dc87222010-03-19 17:12:43 +0000833 addPPCallbacks(Record);
Douglas Gregor7f6d60d2010-03-19 16:15:56 +0000834}