blob: 56eabf41ffe121e6f105e7b4d978c5696fc46bbc [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)
63 : PPOpts(PPOpts), Diags(&diags), LangOpts(opts), Target(0),
David Blaikie687cd952013-01-16 23:13:36 +000064 FileMgr(Headers.getFileMgr()), SourceMgr(SM), HeaderInfo(Headers),
65 TheModuleLoader(TheModuleLoader), ExternalSource(0),
Alp Toker96637802014-05-02 03:43:38 +000066 Identifiers(opts, IILookup), IncrementalProcessing(false), TUKind(TUKind),
David Blaikief157e902013-01-16 23:18:16 +000067 CodeComplete(0), CodeCompletionFile(0), CodeCompletionOffset(0),
Douglas Gregor594b8c92013-11-07 22:55:02 +000068 LastTokenWasAt(false), ModuleImportExpectsIdentifier(false),
David Blaikief157e902013-01-16 23:18:16 +000069 CodeCompletionReached(0), SkipMainFilePreamble(0, true), CurPPLexer(0),
Alp Toker96637802014-05-02 03:43:38 +000070 CurDirLookup(0), CurLexerKind(CLK_Lexer), CurSubmodule(0), Callbacks(0),
71 MacroArgCache(0), Record(0), MIChainHead(0), MICache(0),
Argyrios Kyrtzidisd48b91d2013-04-30 05:05:35 +000072 DeserialMIChainHead(0) {
Daniel Dunbar0c6c9302009-11-11 21:44:21 +000073 OwnsHeaderSearch = OwnsHeaders;
Douglas Gregor83297df2011-09-01 23:39:15 +000074
75 ScratchBuf = new ScratchBuffer(SourceMgr);
76 CounterValue = 0; // __COUNTER__ starts at 0.
77
78 // Clear stats.
79 NumDirectives = NumDefined = NumUndefined = NumPragma = 0;
80 NumIf = NumElse = NumEndif = 0;
81 NumEnteredSourceFiles = 0;
82 NumMacroExpanded = NumFnMacroExpanded = NumBuiltinMacroExpanded = 0;
83 NumFastMacroExpanded = NumTokenPaste = NumFastTokenPaste = 0;
84 MaxIncludeStackDepth = 0;
85 NumSkipped = 0;
86
87 // Default to discarding comments.
88 KeepComments = false;
89 KeepMacroComments = false;
90 SuppressIncludeNotFoundError = false;
91
92 // Macro expansion is enabled.
93 DisableMacroExpansion = false;
David Blaikied5321242012-06-06 18:52:13 +000094 MacroExpansionInDirectivesOverride = false;
Douglas Gregor83297df2011-09-01 23:39:15 +000095 InMacroArgs = false;
Argyrios Kyrtzidisf1b64c62012-04-03 16:47:40 +000096 InMacroArgPreExpansion = false;
Douglas Gregor83297df2011-09-01 23:39:15 +000097 NumCachedTokenLexers = 0;
Jordan Rosede1a2922012-06-08 18:06:21 +000098 PragmasEnabled = true;
Eric Christopher5e4696d2013-01-16 20:09:36 +000099 ParsingIfOrElifDirective = false;
Jordan Rose324ec422013-01-31 19:26:01 +0000100 PreprocessedOutput = false;
Jordan Rosede1a2922012-06-08 18:06:21 +0000101
Douglas Gregor83297df2011-09-01 23:39:15 +0000102 CachedLexPos = 0;
Eric Christopher5e4696d2013-01-16 20:09:36 +0000103
Douglas Gregor83297df2011-09-01 23:39:15 +0000104 // We haven't read anything from the external source.
105 ReadMacrosFromExternalSource = false;
106
Douglas Gregor83297df2011-09-01 23:39:15 +0000107 // "Poison" __VA_ARGS__, which can only appear in the expansion of a macro.
108 // This gets unpoisoned where it is allowed.
109 (Ident__VA_ARGS__ = getIdentifierInfo("__VA_ARGS__"))->setIsPoisoned();
110 SetPoisonReason(Ident__VA_ARGS__,diag::ext_pp_bad_vaargs_use);
111
112 // Initialize the pragma handlers.
113 PragmaHandlers = new PragmaNamespace(StringRef());
114 RegisterBuiltinPragmas();
115
116 // Initialize builtin macros like __LINE__ and friends.
117 RegisterBuiltinMacros();
118
David Blaikiebbafb8a2012-03-11 07:00:24 +0000119 if(LangOpts.Borland) {
Douglas Gregor83297df2011-09-01 23:39:15 +0000120 Ident__exception_info = getIdentifierInfo("_exception_info");
121 Ident___exception_info = getIdentifierInfo("__exception_info");
122 Ident_GetExceptionInfo = getIdentifierInfo("GetExceptionInformation");
123 Ident__exception_code = getIdentifierInfo("_exception_code");
124 Ident___exception_code = getIdentifierInfo("__exception_code");
125 Ident_GetExceptionCode = getIdentifierInfo("GetExceptionCode");
126 Ident__abnormal_termination = getIdentifierInfo("_abnormal_termination");
127 Ident___abnormal_termination = getIdentifierInfo("__abnormal_termination");
128 Ident_AbnormalTermination = getIdentifierInfo("AbnormalTermination");
129 } else {
130 Ident__exception_info = Ident__exception_code = Ident__abnormal_termination = 0;
131 Ident___exception_info = Ident___exception_code = Ident___abnormal_termination = 0;
132 Ident_GetExceptionInfo = Ident_GetExceptionCode = Ident_AbnormalTermination = 0;
Douglas Gregor89929282012-01-30 06:01:29 +0000133 }
Argyrios Kyrtzidis3c9aaf12012-06-02 18:08:09 +0000134}
135
136Preprocessor::~Preprocessor() {
137 assert(BacktrackPositions.empty() && "EnableBacktrack/Backtrack imbalance!");
138
Benjamin Kramer329c5962014-03-15 16:40:40 +0000139 IncludeMacroStack.clear();
Argyrios Kyrtzidis3c9aaf12012-06-02 18:08:09 +0000140
141 // Free any macro definitions.
142 for (MacroInfoChain *I = MIChainHead ; I ; I = I->Next)
143 I->MI.Destroy();
144
145 // Free any cached macro expanders.
146 for (unsigned i = 0, e = NumCachedTokenLexers; i != e; ++i)
147 delete TokenLexerCache[i];
148
Argyrios Kyrtzidisd48b91d2013-04-30 05:05:35 +0000149 for (DeserializedMacroInfoChain *I = DeserialMIChainHead ; I ; I = I->Next)
150 I->MI.Destroy();
151
Argyrios Kyrtzidis3c9aaf12012-06-02 18:08:09 +0000152 // Free any cached MacroArgs.
153 for (MacroArgs *ArgList = MacroArgCache; ArgList; )
154 ArgList = ArgList->deallocate();
155
156 // Release pragma information.
157 delete PragmaHandlers;
158
159 // Delete the scratch buffer info.
160 delete ScratchBuf;
161
162 // Delete the header search info, if we own it.
163 if (OwnsHeaderSearch)
164 delete &HeaderInfo;
165
166 delete Callbacks;
167}
168
169void Preprocessor::Initialize(const TargetInfo &Target) {
170 assert((!this->Target || this->Target == &Target) &&
171 "Invalid override of target information");
172 this->Target = &Target;
Douglas Gregor89929282012-01-30 06:01:29 +0000173
Argyrios Kyrtzidis3c9aaf12012-06-02 18:08:09 +0000174 // Initialize information about built-ins.
175 BuiltinInfo.InitializeTarget(Target);
Douglas Gregor89929282012-01-30 06:01:29 +0000176 HeaderInfo.setTarget(Target);
Douglas Gregor83297df2011-09-01 23:39:15 +0000177}
178
Ted Kremeneka5c2c272009-02-12 03:26:59 +0000179void Preprocessor::setPTHManager(PTHManager* pm) {
180 PTH.reset(pm);
Douglas Gregord2eb58a2009-10-16 18:18:30 +0000181 FileMgr.addStatCache(PTH->createStatCache());
Ted Kremeneka5c2c272009-02-12 03:26:59 +0000182}
183
Chris Lattner146762e2007-07-20 16:59:19 +0000184void Preprocessor::DumpToken(const Token &Tok, bool DumpFlags) const {
Benjamin Kramer89b422c2009-08-23 12:08:50 +0000185 llvm::errs() << tok::getTokenName(Tok.getKind()) << " '"
186 << getSpelling(Tok) << "'";
Mike Stump11289f42009-09-09 15:08:12 +0000187
Chris Lattnerd01e2912006-06-18 16:22:51 +0000188 if (!DumpFlags) return;
Mike Stump11289f42009-09-09 15:08:12 +0000189
Benjamin Kramer89b422c2009-08-23 12:08:50 +0000190 llvm::errs() << "\t";
Chris Lattnerd01e2912006-06-18 16:22:51 +0000191 if (Tok.isAtStartOfLine())
Benjamin Kramer89b422c2009-08-23 12:08:50 +0000192 llvm::errs() << " [StartOfLine]";
Chris Lattnerd01e2912006-06-18 16:22:51 +0000193 if (Tok.hasLeadingSpace())
Benjamin Kramer89b422c2009-08-23 12:08:50 +0000194 llvm::errs() << " [LeadingSpace]";
Chris Lattner6e4bf522006-07-27 06:59:25 +0000195 if (Tok.isExpandDisabled())
Benjamin Kramer89b422c2009-08-23 12:08:50 +0000196 llvm::errs() << " [ExpandDisabled]";
Chris Lattnerd01e2912006-06-18 16:22:51 +0000197 if (Tok.needsCleaning()) {
Chris Lattner50b497e2006-06-18 16:32:35 +0000198 const char *Start = SourceMgr.getCharacterData(Tok.getLocation());
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000199 llvm::errs() << " [UnClean='" << StringRef(Start, Tok.getLength())
Benjamin Kramer89b422c2009-08-23 12:08:50 +0000200 << "']";
Chris Lattnerd01e2912006-06-18 16:22:51 +0000201 }
Mike Stump11289f42009-09-09 15:08:12 +0000202
Benjamin Kramer89b422c2009-08-23 12:08:50 +0000203 llvm::errs() << "\tLoc=<";
Chris Lattner615315f2007-12-09 20:31:55 +0000204 DumpLocation(Tok.getLocation());
Benjamin Kramer89b422c2009-08-23 12:08:50 +0000205 llvm::errs() << ">";
Chris Lattner615315f2007-12-09 20:31:55 +0000206}
207
208void Preprocessor::DumpLocation(SourceLocation Loc) const {
Chris Lattnerf1ca7d32009-01-27 07:57:44 +0000209 Loc.dump(SourceMgr);
Chris Lattnerd01e2912006-06-18 16:22:51 +0000210}
211
212void Preprocessor::DumpMacro(const MacroInfo &MI) const {
Benjamin Kramer89b422c2009-08-23 12:08:50 +0000213 llvm::errs() << "MACRO: ";
Chris Lattnerd01e2912006-06-18 16:22:51 +0000214 for (unsigned i = 0, e = MI.getNumTokens(); i != e; ++i) {
215 DumpToken(MI.getReplacementToken(i));
Benjamin Kramer89b422c2009-08-23 12:08:50 +0000216 llvm::errs() << " ";
Chris Lattnerd01e2912006-06-18 16:22:51 +0000217 }
Benjamin Kramer89b422c2009-08-23 12:08:50 +0000218 llvm::errs() << "\n";
Chris Lattnerd01e2912006-06-18 16:22:51 +0000219}
220
Chris Lattner22eb9722006-06-18 05:43:12 +0000221void Preprocessor::PrintStats() {
Benjamin Kramer89b422c2009-08-23 12:08:50 +0000222 llvm::errs() << "\n*** Preprocessor Stats:\n";
223 llvm::errs() << NumDirectives << " directives found:\n";
224 llvm::errs() << " " << NumDefined << " #define.\n";
225 llvm::errs() << " " << NumUndefined << " #undef.\n";
226 llvm::errs() << " #include/#include_next/#import:\n";
227 llvm::errs() << " " << NumEnteredSourceFiles << " source files entered.\n";
228 llvm::errs() << " " << MaxIncludeStackDepth << " max include stack depth\n";
229 llvm::errs() << " " << NumIf << " #if/#ifndef/#ifdef.\n";
230 llvm::errs() << " " << NumElse << " #else/#elif.\n";
231 llvm::errs() << " " << NumEndif << " #endif.\n";
232 llvm::errs() << " " << NumPragma << " #pragma.\n";
233 llvm::errs() << NumSkipped << " #if/#ifndef#ifdef regions skipped\n";
Chris Lattner22eb9722006-06-18 05:43:12 +0000234
Benjamin Kramer89b422c2009-08-23 12:08:50 +0000235 llvm::errs() << NumMacroExpanded << "/" << NumFnMacroExpanded << "/"
Ted Kremeneka0a3e9b2008-01-14 16:44:48 +0000236 << NumBuiltinMacroExpanded << " obj/fn/builtin macros expanded, "
237 << NumFastMacroExpanded << " on the fast path.\n";
Benjamin Kramer89b422c2009-08-23 12:08:50 +0000238 llvm::errs() << (NumFastTokenPaste+NumTokenPaste)
Ted Kremeneka0a3e9b2008-01-14 16:44:48 +0000239 << " token paste (##) operations performed, "
240 << NumFastTokenPaste << " on the fast path.\n";
Alexander Kornienko199cd942012-08-13 10:46:42 +0000241
242 llvm::errs() << "\nPreprocessor Memory: " << getTotalMemory() << "B total";
243
244 llvm::errs() << "\n BumpPtr: " << BP.getTotalMemory();
245 llvm::errs() << "\n Macro Expanded Tokens: "
246 << llvm::capacity_in_bytes(MacroExpandedTokens);
247 llvm::errs() << "\n Predefines Buffer: " << Predefines.capacity();
248 llvm::errs() << "\n Macros: " << llvm::capacity_in_bytes(Macros);
249 llvm::errs() << "\n #pragma push_macro Info: "
250 << llvm::capacity_in_bytes(PragmaPushMacroInfo);
251 llvm::errs() << "\n Poison Reasons: "
252 << llvm::capacity_in_bytes(PoisonReasons);
253 llvm::errs() << "\n Comment Handlers: "
254 << llvm::capacity_in_bytes(CommentHandlers) << "\n";
Chris Lattner22eb9722006-06-18 05:43:12 +0000255}
256
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +0000257Preprocessor::macro_iterator
258Preprocessor::macro_begin(bool IncludeExternalMacros) const {
259 if (IncludeExternalMacros && ExternalSource &&
Douglas Gregor9882a5a2010-01-04 19:18:44 +0000260 !ReadMacrosFromExternalSource) {
261 ReadMacrosFromExternalSource = true;
262 ExternalSource->ReadDefinedMacros();
263 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +0000264
265 return Macros.begin();
Douglas Gregor9882a5a2010-01-04 19:18:44 +0000266}
267
Argyrios Kyrtzidise379ee32011-06-29 22:20:04 +0000268size_t Preprocessor::getTotalMemory() const {
Ted Kremenek182543a2011-07-26 21:17:24 +0000269 return BP.getTotalMemory()
Ted Kremenek8b77fe72011-07-27 18:41:23 +0000270 + llvm::capacity_in_bytes(MacroExpandedTokens)
Ted Kremenek182543a2011-07-26 21:17:24 +0000271 + Predefines.capacity() /* Predefines buffer. */
Ted Kremenek8b77fe72011-07-27 18:41:23 +0000272 + llvm::capacity_in_bytes(Macros)
273 + llvm::capacity_in_bytes(PragmaPushMacroInfo)
274 + llvm::capacity_in_bytes(PoisonReasons)
275 + llvm::capacity_in_bytes(CommentHandlers);
Argyrios Kyrtzidise379ee32011-06-29 22:20:04 +0000276}
277
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +0000278Preprocessor::macro_iterator
279Preprocessor::macro_end(bool IncludeExternalMacros) const {
280 if (IncludeExternalMacros && ExternalSource &&
Douglas Gregor9882a5a2010-01-04 19:18:44 +0000281 !ReadMacrosFromExternalSource) {
282 ReadMacrosFromExternalSource = true;
283 ExternalSource->ReadDefinedMacros();
284 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +0000285
286 return Macros.end();
Douglas Gregor9882a5a2010-01-04 19:18:44 +0000287}
288
Dmitri Gribenko6743e042012-09-29 11:40:46 +0000289/// \brief Compares macro tokens with a specified token value sequence.
290static bool MacroDefinitionEquals(const MacroInfo *MI,
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000291 ArrayRef<TokenValue> Tokens) {
Dmitri Gribenko6743e042012-09-29 11:40:46 +0000292 return Tokens.size() == MI->getNumTokens() &&
293 std::equal(Tokens.begin(), Tokens.end(), MI->tokens_begin());
294}
295
296StringRef Preprocessor::getLastMacroWithSpelling(
297 SourceLocation Loc,
298 ArrayRef<TokenValue> Tokens) const {
299 SourceLocation BestLocation;
300 StringRef BestSpelling;
301 for (Preprocessor::macro_iterator I = macro_begin(), E = macro_end();
302 I != E; ++I) {
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +0000303 if (!I->second->getMacroInfo()->isObjectLike())
Dmitri Gribenko6743e042012-09-29 11:40:46 +0000304 continue;
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +0000305 const MacroDirective::DefInfo
306 Def = I->second->findDirectiveAtLoc(Loc, SourceMgr);
307 if (!Def)
Dmitri Gribenko6743e042012-09-29 11:40:46 +0000308 continue;
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +0000309 if (!MacroDefinitionEquals(Def.getMacroInfo(), Tokens))
Dmitri Gribenko6743e042012-09-29 11:40:46 +0000310 continue;
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +0000311 SourceLocation Location = Def.getLocation();
Dmitri Gribenko6743e042012-09-29 11:40:46 +0000312 // Choose the macro defined latest.
313 if (BestLocation.isInvalid() ||
314 (Location.isValid() &&
315 SourceMgr.isBeforeInTranslationUnit(BestLocation, Location))) {
316 BestLocation = Location;
317 BestSpelling = I->first->getName();
318 }
319 }
320 return BestSpelling;
321}
322
Douglas Gregor8d76cca2012-01-04 06:20:15 +0000323void Preprocessor::recomputeCurLexerKind() {
324 if (CurLexer)
325 CurLexerKind = CLK_Lexer;
326 else if (CurPTHLexer)
327 CurLexerKind = CLK_PTHLexer;
328 else if (CurTokenLexer)
329 CurLexerKind = CLK_TokenLexer;
330 else
331 CurLexerKind = CLK_CachingLexer;
332}
333
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +0000334bool Preprocessor::SetCodeCompletionPoint(const FileEntry *File,
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +0000335 unsigned CompleteLine,
336 unsigned CompleteColumn) {
337 assert(File);
338 assert(CompleteLine && CompleteColumn && "Starts from 1:1");
339 assert(!CodeCompletionFile && "Already set");
340
Douglas Gregor53ad6b92009-12-02 06:49:09 +0000341 using llvm::MemoryBuffer;
342
Douglas Gregor53ad6b92009-12-02 06:49:09 +0000343 // Load the actual file's contents.
Douglas Gregor26266da2010-03-16 19:49:24 +0000344 bool Invalid = false;
345 const MemoryBuffer *Buffer = SourceMgr.getMemoryBufferForFile(File, &Invalid);
346 if (Invalid)
Douglas Gregor53ad6b92009-12-02 06:49:09 +0000347 return true;
348
349 // Find the byte position of the truncation point.
350 const char *Position = Buffer->getBufferStart();
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +0000351 for (unsigned Line = 1; Line < CompleteLine; ++Line) {
Douglas Gregor53ad6b92009-12-02 06:49:09 +0000352 for (; *Position; ++Position) {
353 if (*Position != '\r' && *Position != '\n')
354 continue;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +0000355
Douglas Gregor53ad6b92009-12-02 06:49:09 +0000356 // Eat \r\n or \n\r as a single line.
357 if ((Position[1] == '\r' || Position[1] == '\n') &&
358 Position[0] != Position[1])
359 ++Position;
360 ++Position;
361 break;
362 }
363 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +0000364
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +0000365 Position += CompleteColumn - 1;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +0000366
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +0000367 // Insert '\0' at the code-completion point.
Douglas Gregor9291ab62009-12-08 21:45:46 +0000368 if (Position < Buffer->getBufferEnd()) {
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +0000369 CodeCompletionFile = File;
370 CodeCompletionOffset = Position - Buffer->getBufferStart();
371
372 MemoryBuffer *NewBuffer =
373 MemoryBuffer::getNewUninitMemBuffer(Buffer->getBufferSize() + 1,
374 Buffer->getBufferIdentifier());
Benjamin Kramer60053cf2011-09-04 20:26:28 +0000375 char *NewBuf = const_cast<char*>(NewBuffer->getBufferStart());
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +0000376 char *NewPos = std::copy(Buffer->getBufferStart(), Position, NewBuf);
377 *NewPos = '\0';
378 std::copy(Position, Buffer->getBufferEnd(), NewPos+1);
379 SourceMgr.overrideFileContents(File, NewBuffer);
Douglas Gregor53ad6b92009-12-02 06:49:09 +0000380 }
381
382 return false;
383}
384
Douglas Gregor11583702010-08-25 17:04:25 +0000385void Preprocessor::CodeCompleteNaturalLanguage() {
Douglas Gregor11583702010-08-25 17:04:25 +0000386 if (CodeComplete)
387 CodeComplete->CodeCompleteNaturalLanguage();
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +0000388 setCodeCompletionReached();
Douglas Gregor11583702010-08-25 17:04:25 +0000389}
390
Benjamin Kramera197fb62010-02-27 17:05:45 +0000391/// getSpelling - This method is used to get the spelling of a token into a
392/// SmallVector. Note that the returned StringRef may not point to the
393/// supplied buffer if a copy can be avoided.
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000394StringRef Preprocessor::getSpelling(const Token &Tok,
395 SmallVectorImpl<char> &Buffer,
Douglas Gregor7bda4b82010-03-16 05:20:39 +0000396 bool *Invalid) const {
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +0000397 // NOTE: this has to be checked *before* testing for an IdentifierInfo.
Jordan Rose7f43ddd2013-01-24 20:50:46 +0000398 if (Tok.isNot(tok::raw_identifier) && !Tok.hasUCN()) {
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +0000399 // Try the fast path.
400 if (const IdentifierInfo *II = Tok.getIdentifierInfo())
401 return II->getName();
402 }
Benjamin Kramera197fb62010-02-27 17:05:45 +0000403
404 // Resize the buffer if we need to copy into it.
405 if (Tok.needsCleaning())
406 Buffer.resize(Tok.getLength());
407
408 const char *Ptr = Buffer.data();
Douglas Gregor7bda4b82010-03-16 05:20:39 +0000409 unsigned Len = getSpelling(Tok, Ptr, Invalid);
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000410 return StringRef(Ptr, Len);
Benjamin Kramera197fb62010-02-27 17:05:45 +0000411}
412
Chris Lattnerb94ec7b2006-07-14 06:54:10 +0000413/// CreateString - Plop the specified string into a scratch buffer and return a
414/// location for it. If specified, the source location provides a source
415/// location for the token.
Dmitri Gribenkob8e9e752012-09-24 21:07:17 +0000416void Preprocessor::CreateString(StringRef Str, Token &Tok,
Abramo Bagnarae398e602011-10-03 18:39:03 +0000417 SourceLocation ExpansionLocStart,
418 SourceLocation ExpansionLocEnd) {
Dmitri Gribenkob8e9e752012-09-24 21:07:17 +0000419 Tok.setLength(Str.size());
Mike Stump11289f42009-09-09 15:08:12 +0000420
Chris Lattner5a7971e2009-01-26 19:29:26 +0000421 const char *DestPtr;
Dmitri Gribenkob8e9e752012-09-24 21:07:17 +0000422 SourceLocation Loc = ScratchBuf->getToken(Str.data(), Str.size(), DestPtr);
Mike Stump11289f42009-09-09 15:08:12 +0000423
Abramo Bagnarae398e602011-10-03 18:39:03 +0000424 if (ExpansionLocStart.isValid())
425 Loc = SourceMgr.createExpansionLoc(Loc, ExpansionLocStart,
Dmitri Gribenkob8e9e752012-09-24 21:07:17 +0000426 ExpansionLocEnd, Str.size());
Chris Lattner5a7971e2009-01-26 19:29:26 +0000427 Tok.setLocation(Loc);
Mike Stump11289f42009-09-09 15:08:12 +0000428
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +0000429 // If this is a raw identifier or a literal token, set the pointer data.
430 if (Tok.is(tok::raw_identifier))
431 Tok.setRawIdentifierData(DestPtr);
432 else if (Tok.isLiteral())
Chris Lattner5a7971e2009-01-26 19:29:26 +0000433 Tok.setLiteralData(DestPtr);
Chris Lattnerb94ec7b2006-07-14 06:54:10 +0000434}
435
Douglas Gregor2b82c2a2011-12-02 01:47:07 +0000436Module *Preprocessor::getCurrentModule() {
David Blaikiebbafb8a2012-03-11 07:00:24 +0000437 if (getLangOpts().CurrentModule.empty())
Douglas Gregor2b82c2a2011-12-02 01:47:07 +0000438 return 0;
439
David Blaikiebbafb8a2012-03-11 07:00:24 +0000440 return getHeaderSearchInfo().lookupModule(getLangOpts().CurrentModule);
Douglas Gregor2b82c2a2011-12-02 01:47:07 +0000441}
Chris Lattner8a7003c2007-07-16 06:48:38 +0000442
Chris Lattner1f1b0db2007-10-09 22:10:18 +0000443//===----------------------------------------------------------------------===//
444// Preprocessor Initialization Methods
445//===----------------------------------------------------------------------===//
446
Chris Lattner1f1b0db2007-10-09 22:10:18 +0000447
448/// EnterMainSourceFile - Enter the specified FileID as the main source file,
Nate Begemanf7c3ff62008-01-07 04:01:26 +0000449/// which implicitly adds the builtin defines etc.
Chris Lattnerfb24a3a2010-04-20 20:35:58 +0000450void Preprocessor::EnterMainSourceFile() {
Chris Lattner9ef847b2009-02-13 19:33:24 +0000451 // We do not allow the preprocessor to reenter the main file. Doing so will
452 // cause FileID's to accumulate information from both runs (e.g. #line
453 // information) and predefined macros aren't guaranteed to be set properly.
454 assert(NumEnteredSourceFiles == 0 && "Cannot reenter the main file!");
Chris Lattnerd32480d2009-01-17 06:22:33 +0000455 FileID MainFileID = SourceMgr.getMainFileID();
Mike Stump11289f42009-09-09 15:08:12 +0000456
Argyrios Kyrtzidis9afd4492012-01-05 21:36:25 +0000457 // If MainFileID is loaded it means we loaded an AST file, no need to enter
458 // a main file.
459 if (!SourceMgr.isLoadedFileID(MainFileID)) {
460 // Enter the main file source buffer.
461 EnterSourceFile(MainFileID, 0, SourceLocation());
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000462
Argyrios Kyrtzidis9afd4492012-01-05 21:36:25 +0000463 // If we've been asked to skip bytes in the main file (e.g., as part of a
464 // precompiled preamble), do so now.
465 if (SkipMainFilePreamble.first > 0)
466 CurLexer->SkipBytes(SkipMainFilePreamble.first,
467 SkipMainFilePreamble.second);
468
469 // Tell the header info that the main file was entered. If the file is later
470 // #imported, it won't be re-entered.
471 if (const FileEntry *FE = SourceMgr.getFileEntryForID(MainFileID))
472 HeaderInfo.IncrementIncludeCount(FE);
473 }
Mike Stump11289f42009-09-09 15:08:12 +0000474
Benjamin Kramerd77adb52009-12-31 15:33:09 +0000475 // Preprocess Predefines to populate the initial preprocessor state.
Mike Stump11289f42009-09-09 15:08:12 +0000476 llvm::MemoryBuffer *SB =
Chris Lattner58c79342010-04-05 22:42:27 +0000477 llvm::MemoryBuffer::getMemBufferCopy(Predefines, "<built-in>");
Douglas Gregor33551892010-08-26 14:07:34 +0000478 assert(SB && "Cannot create predefined source buffer");
Meador Ingecdc00572012-06-19 18:17:30 +0000479 FileID FID = SourceMgr.createFileIDForMemBuffer(SB);
Chris Lattnerd32480d2009-01-17 06:22:33 +0000480 assert(!FID.isInvalid() && "Could not create FileID for predefines?");
Argyrios Kyrtzidis22c22f52013-02-01 16:36:07 +0000481 setPredefinesFileID(FID);
Mike Stump11289f42009-09-09 15:08:12 +0000482
Chris Lattner1f1b0db2007-10-09 22:10:18 +0000483 // Start parsing the predefines.
Chris Lattnerfb24a3a2010-04-20 20:35:58 +0000484 EnterSourceFile(FID, 0, SourceLocation());
Chris Lattner1f1b0db2007-10-09 22:10:18 +0000485}
Chris Lattner8a7003c2007-07-16 06:48:38 +0000486
Daniel Dunbarcb9eaf52010-03-23 05:09:10 +0000487void Preprocessor::EndSourceFile() {
488 // Notify the client that we reached the end of the source file.
489 if (Callbacks)
490 Callbacks->EndOfMainFile();
491}
Chris Lattner677757a2006-06-28 05:26:32 +0000492
493//===----------------------------------------------------------------------===//
494// Lexer Event Handling.
495//===----------------------------------------------------------------------===//
496
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +0000497/// LookUpIdentifierInfo - Given a tok::raw_identifier token, look up the
498/// identifier information for the token and install it into the token,
499/// updating the token kind accordingly.
500IdentifierInfo *Preprocessor::LookUpIdentifierInfo(Token &Identifier) const {
501 assert(Identifier.getRawIdentifierData() != 0 && "No raw identifier data!");
Mike Stump11289f42009-09-09 15:08:12 +0000502
Chris Lattnercefc7682006-07-08 08:28:12 +0000503 // Look up this token, see if it is a macro, or if it is a language keyword.
504 IdentifierInfo *II;
Jordan Rose7f43ddd2013-01-24 20:50:46 +0000505 if (!Identifier.needsCleaning() && !Identifier.hasUCN()) {
Chris Lattnercefc7682006-07-08 08:28:12 +0000506 // No cleaning needed, just use the characters from the lexed buffer.
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000507 II = getIdentifierInfo(StringRef(Identifier.getRawIdentifierData(),
Jordan Rose7f43ddd2013-01-24 20:50:46 +0000508 Identifier.getLength()));
Chris Lattnercefc7682006-07-08 08:28:12 +0000509 } else {
510 // Cleaning needed, alloca a buffer, clean into it, then use the buffer.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +0000511 SmallString<64> IdentifierBuffer;
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000512 StringRef CleanedStr = getSpelling(Identifier, IdentifierBuffer);
Jordan Rose7f43ddd2013-01-24 20:50:46 +0000513
514 if (Identifier.hasUCN()) {
515 SmallString<64> UCNIdentifierBuffer;
516 expandUCNs(UCNIdentifierBuffer, CleanedStr);
517 II = getIdentifierInfo(UCNIdentifierBuffer);
518 } else {
519 II = getIdentifierInfo(CleanedStr);
520 }
Chris Lattnercefc7682006-07-08 08:28:12 +0000521 }
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +0000522
523 // Update the token info (identifier info and appropriate token kind).
Chris Lattner8c204872006-10-14 05:19:21 +0000524 Identifier.setIdentifierInfo(II);
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +0000525 Identifier.setKind(II->getTokenID());
526
Chris Lattnercefc7682006-07-08 08:28:12 +0000527 return II;
528}
529
John Wiegley1c0675e2011-04-28 01:08:34 +0000530void Preprocessor::SetPoisonReason(IdentifierInfo *II, unsigned DiagID) {
531 PoisonReasons[II] = DiagID;
532}
533
534void Preprocessor::PoisonSEHIdentifiers(bool Poison) {
535 assert(Ident__exception_code && Ident__exception_info);
536 assert(Ident___exception_code && Ident___exception_info);
537 Ident__exception_code->setIsPoisoned(Poison);
538 Ident___exception_code->setIsPoisoned(Poison);
539 Ident_GetExceptionCode->setIsPoisoned(Poison);
540 Ident__exception_info->setIsPoisoned(Poison);
541 Ident___exception_info->setIsPoisoned(Poison);
542 Ident_GetExceptionInfo->setIsPoisoned(Poison);
543 Ident__abnormal_termination->setIsPoisoned(Poison);
544 Ident___abnormal_termination->setIsPoisoned(Poison);
545 Ident_AbnormalTermination->setIsPoisoned(Poison);
546}
547
548void Preprocessor::HandlePoisonedIdentifier(Token & Identifier) {
549 assert(Identifier.getIdentifierInfo() &&
550 "Can't handle identifiers without identifier info!");
551 llvm::DenseMap<IdentifierInfo*,unsigned>::const_iterator it =
552 PoisonReasons.find(Identifier.getIdentifierInfo());
553 if(it == PoisonReasons.end())
554 Diag(Identifier, diag::err_pp_used_poisoned_id);
555 else
556 Diag(Identifier,it->second) << Identifier.getIdentifierInfo();
557}
Chris Lattnercefc7682006-07-08 08:28:12 +0000558
Chris Lattner677757a2006-06-28 05:26:32 +0000559/// HandleIdentifier - This callback is invoked when the lexer reads an
560/// identifier. This callback looks up the identifier in the map and/or
561/// potentially macro expands it or turns it into a named token (like 'for').
Chris Lattnerad89ec02009-01-21 07:43:11 +0000562///
563/// Note that callers of this method are guarded by checking the
564/// IdentifierInfo's 'isHandleIdentifierCase' bit. If this method changes, the
565/// IdentifierInfo methods that compute these properties will need to change to
566/// match.
Eli Friedman0834a4b2013-09-19 00:41:32 +0000567bool Preprocessor::HandleIdentifier(Token &Identifier) {
Chris Lattner0f1f5052006-07-20 04:16:23 +0000568 assert(Identifier.getIdentifierInfo() &&
569 "Can't handle identifiers without identifier info!");
Mike Stump11289f42009-09-09 15:08:12 +0000570
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000571 IdentifierInfo &II = *Identifier.getIdentifierInfo();
Chris Lattner677757a2006-06-28 05:26:32 +0000572
Douglas Gregor935bc7a22011-10-27 09:33:13 +0000573 // If the information about this identifier is out of date, update it from
574 // the external source.
Douglas Gregor3f568c12012-06-29 18:27:59 +0000575 // We have to treat __VA_ARGS__ in a special way, since it gets
576 // serialized with isPoisoned = true, but our preprocessor may have
577 // unpoisoned it if we're defining a C99 macro.
Douglas Gregor935bc7a22011-10-27 09:33:13 +0000578 if (II.isOutOfDate()) {
Douglas Gregor3f568c12012-06-29 18:27:59 +0000579 bool CurrentIsPoisoned = false;
580 if (&II == Ident__VA_ARGS__)
581 CurrentIsPoisoned = Ident__VA_ARGS__->isPoisoned();
582
Douglas Gregor935bc7a22011-10-27 09:33:13 +0000583 ExternalSource->updateOutOfDateIdentifier(II);
584 Identifier.setKind(II.getTokenID());
Douglas Gregor3f568c12012-06-29 18:27:59 +0000585
586 if (&II == Ident__VA_ARGS__)
587 II.setIsPoisoned(CurrentIsPoisoned);
Douglas Gregor935bc7a22011-10-27 09:33:13 +0000588 }
589
Chris Lattner677757a2006-06-28 05:26:32 +0000590 // If this identifier was poisoned, and if it was not produced from a macro
591 // expansion, emit an error.
Ted Kremeneka2c3c8d2008-11-19 22:43:49 +0000592 if (II.isPoisoned() && CurPPLexer) {
John Wiegley1c0675e2011-04-28 01:08:34 +0000593 HandlePoisonedIdentifier(Identifier);
Chris Lattner8ff71992006-07-06 05:17:39 +0000594 }
Mike Stump11289f42009-09-09 15:08:12 +0000595
Chris Lattner78186052006-07-09 00:45:31 +0000596 // If this is a macro to be expanded, do it.
Argyrios Kyrtzidisfead64b2013-02-24 00:05:14 +0000597 if (MacroDirective *MD = getMacroDirective(&II)) {
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +0000598 MacroInfo *MI = MD->getMacroInfo();
Abramo Bagnara123bec82012-01-01 22:01:04 +0000599 if (!DisableMacroExpansion) {
Richard Smith181879c2012-12-12 02:46:14 +0000600 if (!Identifier.isExpandDisabled() && MI->isEnabled()) {
Eli Friedman0834a4b2013-09-19 00:41:32 +0000601 // C99 6.10.3p10: If the preprocessing token immediately after the
602 // macro name isn't a '(', this macro should not be expanded.
603 if (!MI->isFunctionLike() || isNextPPTokenLParen())
604 return HandleMacroExpandedIdentifier(Identifier, MD);
Chris Lattner6e4bf522006-07-27 06:59:25 +0000605 } else {
606 // C99 6.10.3.4p2 says that a disabled macro may never again be
607 // expanded, even if it's in a context where it could be expanded in the
608 // future.
Chris Lattner146762e2007-07-20 16:59:19 +0000609 Identifier.setFlag(Token::DisableExpand);
Richard Smith181879c2012-12-12 02:46:14 +0000610 if (MI->isObjectLike() || isNextPPTokenLParen())
611 Diag(Identifier, diag::pp_disabled_macro_expansion);
Chris Lattner6e4bf522006-07-27 06:59:25 +0000612 }
613 }
Chris Lattner063400e2006-10-14 19:54:15 +0000614 }
Chris Lattner677757a2006-06-28 05:26:32 +0000615
Richard Smith4dd85d62011-10-11 19:57:52 +0000616 // If this identifier is a keyword in C++11, produce a warning. Don't warn if
617 // we're not considering macro expansion, since this identifier might be the
618 // name of a macro.
619 // FIXME: This warning is disabled in cases where it shouldn't be, like
620 // "#define constexpr constexpr", "int constexpr;"
Alp Toker7d2fea22014-02-24 04:35:58 +0000621 if (II.isCXX11CompatKeyword() && !DisableMacroExpansion) {
Richard Smith4dd85d62011-10-11 19:57:52 +0000622 Diag(Identifier, diag::warn_cxx11_keyword) << II.getName();
623 // Don't diagnose this keyword again in this translation unit.
624 II.setIsCXX11CompatKeyword(false);
625 }
626
Chris Lattner5b9f4892006-11-21 17:23:33 +0000627 // C++ 2.11p2: If this is an alternative representation of a C++ operator,
628 // then we act as if it is the actual operator and not the textual
629 // representation of it.
Fariborz Jahanian9e42a952010-09-03 17:33:04 +0000630 if (II.isCPlusPlusOperatorKeyword())
Chris Lattner5b9f4892006-11-21 17:23:33 +0000631 Identifier.setIdentifierInfo(0);
632
Chris Lattner677757a2006-06-28 05:26:32 +0000633 // If this is an extension token, diagnose its use.
Steve Naroffc84e8b72008-09-02 18:50:17 +0000634 // We avoid diagnosing tokens that originate from macro definitions.
Eli Friedman6bba2ad2009-04-28 03:59:15 +0000635 // FIXME: This warning is disabled in cases where it shouldn't be,
636 // like "#define TY typeof", "TY(1) x".
637 if (II.isExtensionToken() && !DisableMacroExpansion)
Chris Lattner53621a52007-06-13 20:44:40 +0000638 Diag(Identifier, diag::ext_token_used);
Douglas Gregoraf5c4842011-09-07 23:11:54 +0000639
Douglas Gregor594b8c92013-11-07 22:55:02 +0000640 // If this is the 'import' contextual keyword following an '@', note
Ted Kremenekc1e4dd02012-03-01 22:07:04 +0000641 // that the next token indicates a module name.
Douglas Gregor8d76cca2012-01-04 06:20:15 +0000642 //
Douglas Gregorc50d4922012-12-11 22:11:52 +0000643 // Note that we do not treat 'import' as a contextual
Ted Kremenekc1e4dd02012-03-01 22:07:04 +0000644 // keyword when we're in a caching lexer, because caching lexers only get
645 // used in contexts where import declarations are disallowed.
Douglas Gregor594b8c92013-11-07 22:55:02 +0000646 if (LastTokenWasAt && II.isModulesImport() && !InMacroArgs &&
647 !DisableMacroExpansion && getLangOpts().Modules &&
648 CurLexerKind != CLK_CachingLexer) {
Douglas Gregoraf5c4842011-09-07 23:11:54 +0000649 ModuleImportLoc = Identifier.getLocation();
Douglas Gregor1805b8a2011-11-30 04:26:53 +0000650 ModuleImportPath.clear();
651 ModuleImportExpectsIdentifier = true;
Douglas Gregoraf5c4842011-09-07 23:11:54 +0000652 CurLexerKind = CLK_LexAfterModuleImport;
653 }
Eli Friedman0834a4b2013-09-19 00:41:32 +0000654 return true;
Douglas Gregor08142532011-08-26 23:56:07 +0000655}
656
Eli Friedman0834a4b2013-09-19 00:41:32 +0000657void Preprocessor::Lex(Token &Result) {
658 // We loop here until a lex function retuns a token; this avoids recursion.
659 bool ReturnedToken;
660 do {
661 switch (CurLexerKind) {
662 case CLK_Lexer:
663 ReturnedToken = CurLexer->Lex(Result);
664 break;
665 case CLK_PTHLexer:
666 ReturnedToken = CurPTHLexer->Lex(Result);
667 break;
668 case CLK_TokenLexer:
669 ReturnedToken = CurTokenLexer->Lex(Result);
670 break;
671 case CLK_CachingLexer:
672 CachingLex(Result);
673 ReturnedToken = true;
674 break;
675 case CLK_LexAfterModuleImport:
676 LexAfterModuleImport(Result);
677 ReturnedToken = true;
678 break;
679 }
680 } while (!ReturnedToken);
Douglas Gregor594b8c92013-11-07 22:55:02 +0000681
682 LastTokenWasAt = Result.is(tok::at);
Eli Friedman0834a4b2013-09-19 00:41:32 +0000683}
684
685
Douglas Gregorda82e702012-01-03 19:32:59 +0000686/// \brief Lex a token following the 'import' contextual keyword.
Douglas Gregor22d09742012-01-03 18:04:46 +0000687///
Douglas Gregoraf5c4842011-09-07 23:11:54 +0000688void Preprocessor::LexAfterModuleImport(Token &Result) {
689 // Figure out what kind of lexer we actually have.
Douglas Gregor8d76cca2012-01-04 06:20:15 +0000690 recomputeCurLexerKind();
Douglas Gregoraf5c4842011-09-07 23:11:54 +0000691
692 // Lex the next token.
693 Lex(Result);
694
Douglas Gregor08142532011-08-26 23:56:07 +0000695 // The token sequence
696 //
Douglas Gregor22d09742012-01-03 18:04:46 +0000697 // import identifier (. identifier)*
698 //
Douglas Gregorda82e702012-01-03 19:32:59 +0000699 // indicates a module import directive. We already saw the 'import'
700 // contextual keyword, so now we're looking for the identifiers.
Douglas Gregor1805b8a2011-11-30 04:26:53 +0000701 if (ModuleImportExpectsIdentifier && Result.getKind() == tok::identifier) {
702 // We expected to see an identifier here, and we did; continue handling
703 // identifiers.
704 ModuleImportPath.push_back(std::make_pair(Result.getIdentifierInfo(),
705 Result.getLocation()));
706 ModuleImportExpectsIdentifier = false;
707 CurLexerKind = CLK_LexAfterModuleImport;
Douglas Gregor08142532011-08-26 23:56:07 +0000708 return;
Douglas Gregor1805b8a2011-11-30 04:26:53 +0000709 }
Douglas Gregor08142532011-08-26 23:56:07 +0000710
Douglas Gregor1805b8a2011-11-30 04:26:53 +0000711 // If we're expecting a '.' or a ';', and we got a '.', then wait until we
712 // see the next identifier.
713 if (!ModuleImportExpectsIdentifier && Result.getKind() == tok::period) {
714 ModuleImportExpectsIdentifier = true;
715 CurLexerKind = CLK_LexAfterModuleImport;
716 return;
717 }
718
719 // If we have a non-empty module path, load the named module.
Daniel Jasper07e6c402013-08-05 20:26:17 +0000720 if (!ModuleImportPath.empty() && getLangOpts().Modules) {
Argyrios Kyrtzidis19d78b72012-09-29 01:06:10 +0000721 Module *Imported = TheModuleLoader.loadModule(ModuleImportLoc,
722 ModuleImportPath,
723 Module::MacrosVisible,
724 /*IsIncludeDirective=*/false);
725 if (Callbacks)
726 Callbacks->moduleImport(ModuleImportLoc, ModuleImportPath, Imported);
727 }
Chris Lattner677757a2006-06-28 05:26:32 +0000728}
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000729
Andy Gibbs58905d22012-11-17 19:15:38 +0000730bool Preprocessor::FinishLexStringLiteral(Token &Result, std::string &String,
Andy Gibbsa8df57a2012-11-17 19:16:52 +0000731 const char *DiagnosticTag,
Andy Gibbs58905d22012-11-17 19:15:38 +0000732 bool AllowMacroExpansion) {
733 // We need at least one string literal.
734 if (Result.isNot(tok::string_literal)) {
Andy Gibbsa8df57a2012-11-17 19:16:52 +0000735 Diag(Result, diag::err_expected_string_literal)
736 << /*Source='in...'*/0 << DiagnosticTag;
Andy Gibbs58905d22012-11-17 19:15:38 +0000737 return false;
738 }
739
740 // Lex string literal tokens, optionally with macro expansion.
741 SmallVector<Token, 4> StrToks;
742 do {
743 StrToks.push_back(Result);
744
745 if (Result.hasUDSuffix())
746 Diag(Result, diag::err_invalid_string_udl);
747
748 if (AllowMacroExpansion)
749 Lex(Result);
750 else
751 LexUnexpandedToken(Result);
752 } while (Result.is(tok::string_literal));
753
754 // Concatenate and parse the strings.
755 StringLiteralParser Literal(&StrToks[0], StrToks.size(), *this);
756 assert(Literal.isAscii() && "Didn't allow wide strings in");
757
758 if (Literal.hadError)
759 return false;
760
761 if (Literal.Pascal) {
Andy Gibbsa8df57a2012-11-17 19:16:52 +0000762 Diag(StrToks[0].getLocation(), diag::err_expected_string_literal)
763 << /*Source='in...'*/0 << DiagnosticTag;
Andy Gibbs58905d22012-11-17 19:15:38 +0000764 return false;
765 }
766
767 String = Literal.GetString();
768 return true;
769}
770
Reid Klecknerc0dca6d2014-02-12 23:50:26 +0000771bool Preprocessor::parseSimpleIntegerLiteral(Token &Tok, uint64_t &Value) {
772 assert(Tok.is(tok::numeric_constant));
773 SmallString<8> IntegerBuffer;
774 bool NumberInvalid = false;
775 StringRef Spelling = getSpelling(Tok, IntegerBuffer, &NumberInvalid);
776 if (NumberInvalid)
777 return false;
778 NumericLiteralParser Literal(Spelling, Tok.getLocation(), *this);
779 if (Literal.hadError || !Literal.isIntegerLiteral() || Literal.hasUDSuffix())
780 return false;
781 llvm::APInt APVal(64, 0);
782 if (Literal.GetIntegerValue(APVal))
783 return false;
784 Lex(Tok);
785 Value = APVal.getLimitedValue();
786 return true;
787}
788
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000789void Preprocessor::addCommentHandler(CommentHandler *Handler) {
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000790 assert(Handler && "NULL comment handler");
791 assert(std::find(CommentHandlers.begin(), CommentHandlers.end(), Handler) ==
792 CommentHandlers.end() && "Comment handler already registered");
793 CommentHandlers.push_back(Handler);
794}
795
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000796void Preprocessor::removeCommentHandler(CommentHandler *Handler) {
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000797 std::vector<CommentHandler *>::iterator Pos
798 = std::find(CommentHandlers.begin(), CommentHandlers.end(), Handler);
799 assert(Pos != CommentHandlers.end() && "Comment handler not registered");
800 CommentHandlers.erase(Pos);
801}
802
Chris Lattner87d02082010-01-18 22:35:47 +0000803bool Preprocessor::HandleComment(Token &result, SourceRange Comment) {
804 bool AnyPendingTokens = false;
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000805 for (std::vector<CommentHandler *>::iterator H = CommentHandlers.begin(),
806 HEnd = CommentHandlers.end();
Chris Lattner87d02082010-01-18 22:35:47 +0000807 H != HEnd; ++H) {
808 if ((*H)->HandleComment(*this, Comment))
809 AnyPendingTokens = true;
810 }
811 if (!AnyPendingTokens || getCommentRetentionState())
812 return false;
813 Lex(result);
814 return true;
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000815}
816
Douglas Gregor08142532011-08-26 23:56:07 +0000817ModuleLoader::~ModuleLoader() { }
818
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000819CommentHandler::~CommentHandler() { }
Douglas Gregor7f6d60d2010-03-19 16:15:56 +0000820
Douglas Gregor3a7ad252010-08-24 19:08:16 +0000821CodeCompletionHandler::~CodeCompletionHandler() { }
822
Argyrios Kyrtzidisf3d587e2012-12-04 07:27:05 +0000823void Preprocessor::createPreprocessingRecord() {
Douglas Gregor7f6d60d2010-03-19 16:15:56 +0000824 if (Record)
825 return;
826
Argyrios Kyrtzidisf3d587e2012-12-04 07:27:05 +0000827 Record = new PreprocessingRecord(getSourceManager());
Douglas Gregor7dc87222010-03-19 17:12:43 +0000828 addPPCallbacks(Record);
Douglas Gregor7f6d60d2010-03-19 16:15:56 +0000829}