blob: 53c45dca01f90601125b07a8fe3a1e2f46b3a33a [file] [log] [blame]
Reid Spencer5f016e22007-07-11 17:01:13 +00001//===--- Preprocess.cpp - C Language Family Preprocessor Implementation ---===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Reid Spencer5f016e22007-07-11 17:01:13 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the Preprocessor interface.
11//
12//===----------------------------------------------------------------------===//
13//
14// Options to support:
15// -H - Print the name of each header file used.
Chris Lattnerf73903a2009-02-06 06:45:26 +000016// -d[DNI] - Dump various things.
Reid Spencer5f016e22007-07-11 17:01:13 +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//
26//===----------------------------------------------------------------------===//
27
28#include "clang/Lex/Preprocessor.h"
Chris Lattner23f77e52009-12-15 01:51:03 +000029#include "MacroArgs.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000030#include "clang/Basic/FileManager.h"
31#include "clang/Basic/SourceManager.h"
32#include "clang/Basic/TargetInfo.h"
33#include "clang/Lex/CodeCompletionHandler.h"
Douglas Gregor88a35862010-01-04 19:18:44 +000034#include "clang/Lex/ExternalPreprocessorSource.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000035#include "clang/Lex/HeaderSearch.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000036#include "clang/Lex/LexDiagnostic.h"
37#include "clang/Lex/LiteralSupport.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000038#include "clang/Lex/MacroInfo.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000039#include "clang/Lex/ModuleLoader.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000040#include "clang/Lex/Pragma.h"
Douglas Gregor94dc8f62010-03-19 16:15:56 +000041#include "clang/Lex/PreprocessingRecord.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000042#include "clang/Lex/PreprocessorOptions.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000043#include "clang/Lex/ScratchBuffer.h"
Chris Lattner2db78dd2008-10-05 20:40:30 +000044#include "llvm/ADT/APFloat.h"
Benjamin Kramer8fe83e12012-02-04 13:45:25 +000045#include "llvm/ADT/SmallString.h"
Jordan Rosec7629d92013-01-24 20:50:46 +000046#include "llvm/ADT/STLExtras.h"
47#include "llvm/ADT/StringExtras.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000048#include "llvm/Support/Capacity.h"
Dmitri Gribenkocb5620c2013-01-30 12:06:08 +000049#include "llvm/Support/ConvertUTF.h"
Chris Lattner97ba77c2007-07-16 06:48:38 +000050#include "llvm/Support/MemoryBuffer.h"
Benjamin Kramer6cb7c1a2009-08-23 12:08:50 +000051#include "llvm/Support/raw_ostream.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000052using namespace clang;
53
54//===----------------------------------------------------------------------===//
Douglas Gregor88a35862010-01-04 19:18:44 +000055ExternalPreprocessorSource::~ExternalPreprocessorSource() { }
Reid Spencer5f016e22007-07-11 17:01:13 +000056
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +000057Preprocessor::Preprocessor(IntrusiveRefCntPtr<PreprocessorOptions> PPOpts,
Douglas Gregor36a16492012-10-24 17:46:57 +000058 DiagnosticsEngine &diags, LangOptions &opts,
Douglas Gregor998b3d32011-09-01 23:39:15 +000059 const TargetInfo *target, SourceManager &SM,
Douglas Gregor6aa52ec2011-08-26 23:56:07 +000060 HeaderSearch &Headers, ModuleLoader &TheModuleLoader,
David Blaikie49446062013-01-16 23:13:36 +000061 IdentifierInfoLookup *IILookup, bool OwnsHeaders,
62 bool DelayInitialization, bool IncrProcessing)
63 : PPOpts(PPOpts), Diags(&diags), LangOpts(opts), Target(target),
64 FileMgr(Headers.getFileMgr()), SourceMgr(SM), HeaderInfo(Headers),
65 TheModuleLoader(TheModuleLoader), ExternalSource(0),
David Blaikie0a3cbd02013-01-16 23:18:16 +000066 Identifiers(opts, IILookup), IncrementalProcessing(IncrProcessing),
67 CodeComplete(0), CodeCompletionFile(0), CodeCompletionOffset(0),
68 CodeCompletionReached(0), SkipMainFilePreamble(0, true), CurPPLexer(0),
Argyrios Kyrtzidisd560ce32013-03-27 01:25:24 +000069 CurDirLookup(0), CurLexerKind(CLK_Lexer), Callbacks(0),
David Blaikie0a3cbd02013-01-16 23:18:16 +000070 MacroArgCache(0), Record(0), MIChainHead(0), MICache(0) {
Daniel Dunbar5814e652009-11-11 21:44:21 +000071 OwnsHeaderSearch = OwnsHeaders;
Douglas Gregor998b3d32011-09-01 23:39:15 +000072
73 ScratchBuf = new ScratchBuffer(SourceMgr);
74 CounterValue = 0; // __COUNTER__ starts at 0.
75
76 // Clear stats.
77 NumDirectives = NumDefined = NumUndefined = NumPragma = 0;
78 NumIf = NumElse = NumEndif = 0;
79 NumEnteredSourceFiles = 0;
80 NumMacroExpanded = NumFnMacroExpanded = NumBuiltinMacroExpanded = 0;
81 NumFastMacroExpanded = NumTokenPaste = NumFastTokenPaste = 0;
82 MaxIncludeStackDepth = 0;
83 NumSkipped = 0;
84
85 // Default to discarding comments.
86 KeepComments = false;
87 KeepMacroComments = false;
88 SuppressIncludeNotFoundError = false;
89
90 // Macro expansion is enabled.
91 DisableMacroExpansion = false;
David Blaikie8c0b3782012-06-06 18:52:13 +000092 MacroExpansionInDirectivesOverride = false;
Douglas Gregor998b3d32011-09-01 23:39:15 +000093 InMacroArgs = false;
Argyrios Kyrtzidis14e64552012-04-03 16:47:40 +000094 InMacroArgPreExpansion = false;
Douglas Gregor998b3d32011-09-01 23:39:15 +000095 NumCachedTokenLexers = 0;
Jordan Rose6fe6a492012-06-08 18:06:21 +000096 PragmasEnabled = true;
Eric Christopher214ea9d2013-01-16 20:09:36 +000097 ParsingIfOrElifDirective = false;
Jordan Rose98b21b92013-01-31 19:26:01 +000098 PreprocessedOutput = false;
Jordan Rose6fe6a492012-06-08 18:06:21 +000099
Douglas Gregor998b3d32011-09-01 23:39:15 +0000100 CachedLexPos = 0;
Eric Christopher214ea9d2013-01-16 20:09:36 +0000101
Douglas Gregor998b3d32011-09-01 23:39:15 +0000102 // We haven't read anything from the external source.
103 ReadMacrosFromExternalSource = false;
104
Douglas Gregor998b3d32011-09-01 23:39:15 +0000105 // "Poison" __VA_ARGS__, which can only appear in the expansion of a macro.
106 // This gets unpoisoned where it is allowed.
107 (Ident__VA_ARGS__ = getIdentifierInfo("__VA_ARGS__"))->setIsPoisoned();
108 SetPoisonReason(Ident__VA_ARGS__,diag::ext_pp_bad_vaargs_use);
109
110 // Initialize the pragma handlers.
111 PragmaHandlers = new PragmaNamespace(StringRef());
112 RegisterBuiltinPragmas();
113
114 // Initialize builtin macros like __LINE__ and friends.
115 RegisterBuiltinMacros();
116
David Blaikie4e4d0842012-03-11 07:00:24 +0000117 if(LangOpts.Borland) {
Douglas Gregor998b3d32011-09-01 23:39:15 +0000118 Ident__exception_info = getIdentifierInfo("_exception_info");
119 Ident___exception_info = getIdentifierInfo("__exception_info");
120 Ident_GetExceptionInfo = getIdentifierInfo("GetExceptionInformation");
121 Ident__exception_code = getIdentifierInfo("_exception_code");
122 Ident___exception_code = getIdentifierInfo("__exception_code");
123 Ident_GetExceptionCode = getIdentifierInfo("GetExceptionCode");
124 Ident__abnormal_termination = getIdentifierInfo("_abnormal_termination");
125 Ident___abnormal_termination = getIdentifierInfo("__abnormal_termination");
126 Ident_AbnormalTermination = getIdentifierInfo("AbnormalTermination");
127 } else {
128 Ident__exception_info = Ident__exception_code = Ident__abnormal_termination = 0;
129 Ident___exception_info = Ident___exception_code = Ident___abnormal_termination = 0;
130 Ident_GetExceptionInfo = Ident_GetExceptionCode = Ident_AbnormalTermination = 0;
Douglas Gregordc58aa72012-01-30 06:01:29 +0000131 }
Argyrios Kyrtzidis25c25962012-06-02 18:08:09 +0000132
133 if (!DelayInitialization) {
134 assert(Target && "Must provide target information for PP initialization");
135 Initialize(*Target);
136 }
137}
138
139Preprocessor::~Preprocessor() {
140 assert(BacktrackPositions.empty() && "EnableBacktrack/Backtrack imbalance!");
141
142 while (!IncludeMacroStack.empty()) {
143 delete IncludeMacroStack.back().TheLexer;
144 delete IncludeMacroStack.back().TheTokenLexer;
145 IncludeMacroStack.pop_back();
146 }
147
148 // Free any macro definitions.
149 for (MacroInfoChain *I = MIChainHead ; I ; I = I->Next)
150 I->MI.Destroy();
151
152 // Free any cached macro expanders.
153 for (unsigned i = 0, e = NumCachedTokenLexers; i != e; ++i)
154 delete TokenLexerCache[i];
155
156 // Free any cached MacroArgs.
157 for (MacroArgs *ArgList = MacroArgCache; ArgList; )
158 ArgList = ArgList->deallocate();
159
160 // Release pragma information.
161 delete PragmaHandlers;
162
163 // Delete the scratch buffer info.
164 delete ScratchBuf;
165
166 // Delete the header search info, if we own it.
167 if (OwnsHeaderSearch)
168 delete &HeaderInfo;
169
170 delete Callbacks;
171}
172
173void Preprocessor::Initialize(const TargetInfo &Target) {
174 assert((!this->Target || this->Target == &Target) &&
175 "Invalid override of target information");
176 this->Target = &Target;
Douglas Gregordc58aa72012-01-30 06:01:29 +0000177
Argyrios Kyrtzidis25c25962012-06-02 18:08:09 +0000178 // Initialize information about built-ins.
179 BuiltinInfo.InitializeTarget(Target);
Douglas Gregordc58aa72012-01-30 06:01:29 +0000180 HeaderInfo.setTarget(Target);
Douglas Gregor998b3d32011-09-01 23:39:15 +0000181}
182
Ted Kremenek337edcd2009-02-12 03:26:59 +0000183void Preprocessor::setPTHManager(PTHManager* pm) {
184 PTH.reset(pm);
Douglas Gregor52e71082009-10-16 18:18:30 +0000185 FileMgr.addStatCache(PTH->createStatCache());
Ted Kremenek337edcd2009-02-12 03:26:59 +0000186}
187
Chris Lattnerd2177732007-07-20 16:59:19 +0000188void Preprocessor::DumpToken(const Token &Tok, bool DumpFlags) const {
Benjamin Kramer6cb7c1a2009-08-23 12:08:50 +0000189 llvm::errs() << tok::getTokenName(Tok.getKind()) << " '"
190 << getSpelling(Tok) << "'";
Mike Stump1eb44332009-09-09 15:08:12 +0000191
Reid Spencer5f016e22007-07-11 17:01:13 +0000192 if (!DumpFlags) return;
Mike Stump1eb44332009-09-09 15:08:12 +0000193
Benjamin Kramer6cb7c1a2009-08-23 12:08:50 +0000194 llvm::errs() << "\t";
Reid Spencer5f016e22007-07-11 17:01:13 +0000195 if (Tok.isAtStartOfLine())
Benjamin Kramer6cb7c1a2009-08-23 12:08:50 +0000196 llvm::errs() << " [StartOfLine]";
Reid Spencer5f016e22007-07-11 17:01:13 +0000197 if (Tok.hasLeadingSpace())
Benjamin Kramer6cb7c1a2009-08-23 12:08:50 +0000198 llvm::errs() << " [LeadingSpace]";
Reid Spencer5f016e22007-07-11 17:01:13 +0000199 if (Tok.isExpandDisabled())
Benjamin Kramer6cb7c1a2009-08-23 12:08:50 +0000200 llvm::errs() << " [ExpandDisabled]";
Reid Spencer5f016e22007-07-11 17:01:13 +0000201 if (Tok.needsCleaning()) {
202 const char *Start = SourceMgr.getCharacterData(Tok.getLocation());
Chris Lattner5f9e2722011-07-23 10:55:15 +0000203 llvm::errs() << " [UnClean='" << StringRef(Start, Tok.getLength())
Benjamin Kramer6cb7c1a2009-08-23 12:08:50 +0000204 << "']";
Reid Spencer5f016e22007-07-11 17:01:13 +0000205 }
Mike Stump1eb44332009-09-09 15:08:12 +0000206
Benjamin Kramer6cb7c1a2009-08-23 12:08:50 +0000207 llvm::errs() << "\tLoc=<";
Chris Lattnerc3d8d572007-12-09 20:31:55 +0000208 DumpLocation(Tok.getLocation());
Benjamin Kramer6cb7c1a2009-08-23 12:08:50 +0000209 llvm::errs() << ">";
Chris Lattnerc3d8d572007-12-09 20:31:55 +0000210}
211
212void Preprocessor::DumpLocation(SourceLocation Loc) const {
Chris Lattnerb9c3f962009-01-27 07:57:44 +0000213 Loc.dump(SourceMgr);
Reid Spencer5f016e22007-07-11 17:01:13 +0000214}
215
216void Preprocessor::DumpMacro(const MacroInfo &MI) const {
Benjamin Kramer6cb7c1a2009-08-23 12:08:50 +0000217 llvm::errs() << "MACRO: ";
Reid Spencer5f016e22007-07-11 17:01:13 +0000218 for (unsigned i = 0, e = MI.getNumTokens(); i != e; ++i) {
219 DumpToken(MI.getReplacementToken(i));
Benjamin Kramer6cb7c1a2009-08-23 12:08:50 +0000220 llvm::errs() << " ";
Reid Spencer5f016e22007-07-11 17:01:13 +0000221 }
Benjamin Kramer6cb7c1a2009-08-23 12:08:50 +0000222 llvm::errs() << "\n";
Reid Spencer5f016e22007-07-11 17:01:13 +0000223}
224
225void Preprocessor::PrintStats() {
Benjamin Kramer6cb7c1a2009-08-23 12:08:50 +0000226 llvm::errs() << "\n*** Preprocessor Stats:\n";
227 llvm::errs() << NumDirectives << " directives found:\n";
228 llvm::errs() << " " << NumDefined << " #define.\n";
229 llvm::errs() << " " << NumUndefined << " #undef.\n";
230 llvm::errs() << " #include/#include_next/#import:\n";
231 llvm::errs() << " " << NumEnteredSourceFiles << " source files entered.\n";
232 llvm::errs() << " " << MaxIncludeStackDepth << " max include stack depth\n";
233 llvm::errs() << " " << NumIf << " #if/#ifndef/#ifdef.\n";
234 llvm::errs() << " " << NumElse << " #else/#elif.\n";
235 llvm::errs() << " " << NumEndif << " #endif.\n";
236 llvm::errs() << " " << NumPragma << " #pragma.\n";
237 llvm::errs() << NumSkipped << " #if/#ifndef#ifdef regions skipped\n";
Reid Spencer5f016e22007-07-11 17:01:13 +0000238
Benjamin Kramer6cb7c1a2009-08-23 12:08:50 +0000239 llvm::errs() << NumMacroExpanded << "/" << NumFnMacroExpanded << "/"
Ted Kremenekbdd30c22008-01-14 16:44:48 +0000240 << NumBuiltinMacroExpanded << " obj/fn/builtin macros expanded, "
241 << NumFastMacroExpanded << " on the fast path.\n";
Benjamin Kramer6cb7c1a2009-08-23 12:08:50 +0000242 llvm::errs() << (NumFastTokenPaste+NumTokenPaste)
Ted Kremenekbdd30c22008-01-14 16:44:48 +0000243 << " token paste (##) operations performed, "
244 << NumFastTokenPaste << " on the fast path.\n";
Alexander Kornienkocd6df662012-08-13 10:46:42 +0000245
246 llvm::errs() << "\nPreprocessor Memory: " << getTotalMemory() << "B total";
247
248 llvm::errs() << "\n BumpPtr: " << BP.getTotalMemory();
249 llvm::errs() << "\n Macro Expanded Tokens: "
250 << llvm::capacity_in_bytes(MacroExpandedTokens);
251 llvm::errs() << "\n Predefines Buffer: " << Predefines.capacity();
252 llvm::errs() << "\n Macros: " << llvm::capacity_in_bytes(Macros);
253 llvm::errs() << "\n #pragma push_macro Info: "
254 << llvm::capacity_in_bytes(PragmaPushMacroInfo);
255 llvm::errs() << "\n Poison Reasons: "
256 << llvm::capacity_in_bytes(PoisonReasons);
257 llvm::errs() << "\n Comment Handlers: "
258 << llvm::capacity_in_bytes(CommentHandlers) << "\n";
Reid Spencer5f016e22007-07-11 17:01:13 +0000259}
260
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +0000261Preprocessor::macro_iterator
262Preprocessor::macro_begin(bool IncludeExternalMacros) const {
263 if (IncludeExternalMacros && ExternalSource &&
Douglas Gregor88a35862010-01-04 19:18:44 +0000264 !ReadMacrosFromExternalSource) {
265 ReadMacrosFromExternalSource = true;
266 ExternalSource->ReadDefinedMacros();
267 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +0000268
269 return Macros.begin();
Douglas Gregor88a35862010-01-04 19:18:44 +0000270}
271
Argyrios Kyrtzidisc5c5e922011-06-29 22:20:04 +0000272size_t Preprocessor::getTotalMemory() const {
Ted Kremenek91d1bd62011-07-26 21:17:24 +0000273 return BP.getTotalMemory()
Ted Kremenek67485092011-07-27 18:41:23 +0000274 + llvm::capacity_in_bytes(MacroExpandedTokens)
Ted Kremenek91d1bd62011-07-26 21:17:24 +0000275 + Predefines.capacity() /* Predefines buffer. */
Ted Kremenek67485092011-07-27 18:41:23 +0000276 + llvm::capacity_in_bytes(Macros)
277 + llvm::capacity_in_bytes(PragmaPushMacroInfo)
278 + llvm::capacity_in_bytes(PoisonReasons)
279 + llvm::capacity_in_bytes(CommentHandlers);
Argyrios Kyrtzidisc5c5e922011-06-29 22:20:04 +0000280}
281
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +0000282Preprocessor::macro_iterator
283Preprocessor::macro_end(bool IncludeExternalMacros) const {
284 if (IncludeExternalMacros && ExternalSource &&
Douglas Gregor88a35862010-01-04 19:18:44 +0000285 !ReadMacrosFromExternalSource) {
286 ReadMacrosFromExternalSource = true;
287 ExternalSource->ReadDefinedMacros();
288 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +0000289
290 return Macros.end();
Douglas Gregor88a35862010-01-04 19:18:44 +0000291}
292
Dmitri Gribenko19523542012-09-29 11:40:46 +0000293/// \brief Compares macro tokens with a specified token value sequence.
294static bool MacroDefinitionEquals(const MacroInfo *MI,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +0000295 ArrayRef<TokenValue> Tokens) {
Dmitri Gribenko19523542012-09-29 11:40:46 +0000296 return Tokens.size() == MI->getNumTokens() &&
297 std::equal(Tokens.begin(), Tokens.end(), MI->tokens_begin());
298}
299
300StringRef Preprocessor::getLastMacroWithSpelling(
301 SourceLocation Loc,
302 ArrayRef<TokenValue> Tokens) const {
303 SourceLocation BestLocation;
304 StringRef BestSpelling;
305 for (Preprocessor::macro_iterator I = macro_begin(), E = macro_end();
306 I != E; ++I) {
Argyrios Kyrtzidisc56fff72013-03-26 17:17:01 +0000307 if (!I->second->getMacroInfo()->isObjectLike())
Dmitri Gribenko19523542012-09-29 11:40:46 +0000308 continue;
Argyrios Kyrtzidisc56fff72013-03-26 17:17:01 +0000309 const MacroDirective::DefInfo
310 Def = I->second->findDirectiveAtLoc(Loc, SourceMgr);
311 if (!Def)
Dmitri Gribenko19523542012-09-29 11:40:46 +0000312 continue;
Argyrios Kyrtzidisc56fff72013-03-26 17:17:01 +0000313 if (!MacroDefinitionEquals(Def.getMacroInfo(), Tokens))
Dmitri Gribenko19523542012-09-29 11:40:46 +0000314 continue;
Argyrios Kyrtzidisc56fff72013-03-26 17:17:01 +0000315 SourceLocation Location = Def.getLocation();
Dmitri Gribenko19523542012-09-29 11:40:46 +0000316 // Choose the macro defined latest.
317 if (BestLocation.isInvalid() ||
318 (Location.isValid() &&
319 SourceMgr.isBeforeInTranslationUnit(BestLocation, Location))) {
320 BestLocation = Location;
321 BestSpelling = I->first->getName();
322 }
323 }
324 return BestSpelling;
325}
326
Douglas Gregord6aba062012-01-04 06:20:15 +0000327void Preprocessor::recomputeCurLexerKind() {
328 if (CurLexer)
329 CurLexerKind = CLK_Lexer;
330 else if (CurPTHLexer)
331 CurLexerKind = CLK_PTHLexer;
332 else if (CurTokenLexer)
333 CurLexerKind = CLK_TokenLexer;
334 else
335 CurLexerKind = CLK_CachingLexer;
336}
337
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +0000338bool Preprocessor::SetCodeCompletionPoint(const FileEntry *File,
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +0000339 unsigned CompleteLine,
340 unsigned CompleteColumn) {
341 assert(File);
342 assert(CompleteLine && CompleteColumn && "Starts from 1:1");
343 assert(!CodeCompletionFile && "Already set");
344
Douglas Gregor29684422009-12-02 06:49:09 +0000345 using llvm::MemoryBuffer;
346
Douglas Gregor29684422009-12-02 06:49:09 +0000347 // Load the actual file's contents.
Douglas Gregoraa38c3d2010-03-16 19:49:24 +0000348 bool Invalid = false;
349 const MemoryBuffer *Buffer = SourceMgr.getMemoryBufferForFile(File, &Invalid);
350 if (Invalid)
Douglas Gregor29684422009-12-02 06:49:09 +0000351 return true;
352
353 // Find the byte position of the truncation point.
354 const char *Position = Buffer->getBufferStart();
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +0000355 for (unsigned Line = 1; Line < CompleteLine; ++Line) {
Douglas Gregor29684422009-12-02 06:49:09 +0000356 for (; *Position; ++Position) {
357 if (*Position != '\r' && *Position != '\n')
358 continue;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +0000359
Douglas Gregor29684422009-12-02 06:49:09 +0000360 // Eat \r\n or \n\r as a single line.
361 if ((Position[1] == '\r' || Position[1] == '\n') &&
362 Position[0] != Position[1])
363 ++Position;
364 ++Position;
365 break;
366 }
367 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +0000368
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +0000369 Position += CompleteColumn - 1;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +0000370
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +0000371 // Insert '\0' at the code-completion point.
Douglas Gregorb760fe82009-12-08 21:45:46 +0000372 if (Position < Buffer->getBufferEnd()) {
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +0000373 CodeCompletionFile = File;
374 CodeCompletionOffset = Position - Buffer->getBufferStart();
375
376 MemoryBuffer *NewBuffer =
377 MemoryBuffer::getNewUninitMemBuffer(Buffer->getBufferSize() + 1,
378 Buffer->getBufferIdentifier());
Benjamin Kramer41a50a92011-09-04 20:26:28 +0000379 char *NewBuf = const_cast<char*>(NewBuffer->getBufferStart());
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +0000380 char *NewPos = std::copy(Buffer->getBufferStart(), Position, NewBuf);
381 *NewPos = '\0';
382 std::copy(Position, Buffer->getBufferEnd(), NewPos+1);
383 SourceMgr.overrideFileContents(File, NewBuffer);
Douglas Gregor29684422009-12-02 06:49:09 +0000384 }
385
386 return false;
387}
388
Douglas Gregor55817af2010-08-25 17:04:25 +0000389void Preprocessor::CodeCompleteNaturalLanguage() {
Douglas Gregor55817af2010-08-25 17:04:25 +0000390 if (CodeComplete)
391 CodeComplete->CodeCompleteNaturalLanguage();
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +0000392 setCodeCompletionReached();
Douglas Gregor55817af2010-08-25 17:04:25 +0000393}
394
Benjamin Kramer51f5fe32010-02-27 17:05:45 +0000395/// getSpelling - This method is used to get the spelling of a token into a
396/// SmallVector. Note that the returned StringRef may not point to the
397/// supplied buffer if a copy can be avoided.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000398StringRef Preprocessor::getSpelling(const Token &Tok,
399 SmallVectorImpl<char> &Buffer,
Douglas Gregor50f6af72010-03-16 05:20:39 +0000400 bool *Invalid) const {
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +0000401 // NOTE: this has to be checked *before* testing for an IdentifierInfo.
Jordan Rosec7629d92013-01-24 20:50:46 +0000402 if (Tok.isNot(tok::raw_identifier) && !Tok.hasUCN()) {
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +0000403 // Try the fast path.
404 if (const IdentifierInfo *II = Tok.getIdentifierInfo())
405 return II->getName();
406 }
Benjamin Kramer51f5fe32010-02-27 17:05:45 +0000407
408 // Resize the buffer if we need to copy into it.
409 if (Tok.needsCleaning())
410 Buffer.resize(Tok.getLength());
411
412 const char *Ptr = Buffer.data();
Douglas Gregor50f6af72010-03-16 05:20:39 +0000413 unsigned Len = getSpelling(Tok, Ptr, Invalid);
Chris Lattner5f9e2722011-07-23 10:55:15 +0000414 return StringRef(Ptr, Len);
Benjamin Kramer51f5fe32010-02-27 17:05:45 +0000415}
416
Reid Spencer5f016e22007-07-11 17:01:13 +0000417/// CreateString - Plop the specified string into a scratch buffer and return a
418/// location for it. If specified, the source location provides a source
419/// location for the token.
Dmitri Gribenko374b3832012-09-24 21:07:17 +0000420void Preprocessor::CreateString(StringRef Str, Token &Tok,
Abramo Bagnaraa08529c2011-10-03 18:39:03 +0000421 SourceLocation ExpansionLocStart,
422 SourceLocation ExpansionLocEnd) {
Dmitri Gribenko374b3832012-09-24 21:07:17 +0000423 Tok.setLength(Str.size());
Mike Stump1eb44332009-09-09 15:08:12 +0000424
Chris Lattner47246be2009-01-26 19:29:26 +0000425 const char *DestPtr;
Dmitri Gribenko374b3832012-09-24 21:07:17 +0000426 SourceLocation Loc = ScratchBuf->getToken(Str.data(), Str.size(), DestPtr);
Mike Stump1eb44332009-09-09 15:08:12 +0000427
Abramo Bagnaraa08529c2011-10-03 18:39:03 +0000428 if (ExpansionLocStart.isValid())
429 Loc = SourceMgr.createExpansionLoc(Loc, ExpansionLocStart,
Dmitri Gribenko374b3832012-09-24 21:07:17 +0000430 ExpansionLocEnd, Str.size());
Chris Lattner47246be2009-01-26 19:29:26 +0000431 Tok.setLocation(Loc);
Mike Stump1eb44332009-09-09 15:08:12 +0000432
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +0000433 // If this is a raw identifier or a literal token, set the pointer data.
434 if (Tok.is(tok::raw_identifier))
435 Tok.setRawIdentifierData(DestPtr);
436 else if (Tok.isLiteral())
Chris Lattner47246be2009-01-26 19:29:26 +0000437 Tok.setLiteralData(DestPtr);
Reid Spencer5f016e22007-07-11 17:01:13 +0000438}
439
Douglas Gregor90db2602011-12-02 01:47:07 +0000440Module *Preprocessor::getCurrentModule() {
David Blaikie4e4d0842012-03-11 07:00:24 +0000441 if (getLangOpts().CurrentModule.empty())
Douglas Gregor90db2602011-12-02 01:47:07 +0000442 return 0;
443
David Blaikie4e4d0842012-03-11 07:00:24 +0000444 return getHeaderSearchInfo().lookupModule(getLangOpts().CurrentModule);
Douglas Gregor90db2602011-12-02 01:47:07 +0000445}
Chris Lattner97ba77c2007-07-16 06:48:38 +0000446
Chris Lattner53b0dab2007-10-09 22:10:18 +0000447//===----------------------------------------------------------------------===//
448// Preprocessor Initialization Methods
449//===----------------------------------------------------------------------===//
450
Chris Lattner53b0dab2007-10-09 22:10:18 +0000451
452/// EnterMainSourceFile - Enter the specified FileID as the main source file,
Nate Begeman6b616022008-01-07 04:01:26 +0000453/// which implicitly adds the builtin defines etc.
Chris Lattnere127a0d2010-04-20 20:35:58 +0000454void Preprocessor::EnterMainSourceFile() {
Chris Lattner05db4272009-02-13 19:33:24 +0000455 // We do not allow the preprocessor to reenter the main file. Doing so will
456 // cause FileID's to accumulate information from both runs (e.g. #line
457 // information) and predefined macros aren't guaranteed to be set properly.
458 assert(NumEnteredSourceFiles == 0 && "Cannot reenter the main file!");
Chris Lattner2b2453a2009-01-17 06:22:33 +0000459 FileID MainFileID = SourceMgr.getMainFileID();
Mike Stump1eb44332009-09-09 15:08:12 +0000460
Argyrios Kyrtzidisb8c879a2012-01-05 21:36:25 +0000461 // If MainFileID is loaded it means we loaded an AST file, no need to enter
462 // a main file.
463 if (!SourceMgr.isLoadedFileID(MainFileID)) {
464 // Enter the main file source buffer.
465 EnterSourceFile(MainFileID, 0, SourceLocation());
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000466
Argyrios Kyrtzidisb8c879a2012-01-05 21:36:25 +0000467 // If we've been asked to skip bytes in the main file (e.g., as part of a
468 // precompiled preamble), do so now.
469 if (SkipMainFilePreamble.first > 0)
470 CurLexer->SkipBytes(SkipMainFilePreamble.first,
471 SkipMainFilePreamble.second);
472
473 // Tell the header info that the main file was entered. If the file is later
474 // #imported, it won't be re-entered.
475 if (const FileEntry *FE = SourceMgr.getFileEntryForID(MainFileID))
476 HeaderInfo.IncrementIncludeCount(FE);
477 }
Mike Stump1eb44332009-09-09 15:08:12 +0000478
Benjamin Kramerffd6e392009-12-31 15:33:09 +0000479 // Preprocess Predefines to populate the initial preprocessor state.
Mike Stump1eb44332009-09-09 15:08:12 +0000480 llvm::MemoryBuffer *SB =
Chris Lattnera0a270c2010-04-05 22:42:27 +0000481 llvm::MemoryBuffer::getMemBufferCopy(Predefines, "<built-in>");
Douglas Gregor043266b2010-08-26 14:07:34 +0000482 assert(SB && "Cannot create predefined source buffer");
Meador Inge9416d422012-06-19 18:17:30 +0000483 FileID FID = SourceMgr.createFileIDForMemBuffer(SB);
Chris Lattner2b2453a2009-01-17 06:22:33 +0000484 assert(!FID.isInvalid() && "Could not create FileID for predefines?");
Argyrios Kyrtzidis95d912c2013-02-01 16:36:07 +0000485 setPredefinesFileID(FID);
Mike Stump1eb44332009-09-09 15:08:12 +0000486
Chris Lattner53b0dab2007-10-09 22:10:18 +0000487 // Start parsing the predefines.
Chris Lattnere127a0d2010-04-20 20:35:58 +0000488 EnterSourceFile(FID, 0, SourceLocation());
Chris Lattner53b0dab2007-10-09 22:10:18 +0000489}
Chris Lattner97ba77c2007-07-16 06:48:38 +0000490
Daniel Dunbardbd82092010-03-23 05:09:10 +0000491void Preprocessor::EndSourceFile() {
492 // Notify the client that we reached the end of the source file.
493 if (Callbacks)
494 Callbacks->EndOfMainFile();
495}
Reid Spencer5f016e22007-07-11 17:01:13 +0000496
497//===----------------------------------------------------------------------===//
498// Lexer Event Handling.
499//===----------------------------------------------------------------------===//
500
Jordan Rosec7629d92013-01-24 20:50:46 +0000501static void appendCodePoint(unsigned Codepoint,
502 llvm::SmallVectorImpl<char> &Str) {
503 char ResultBuf[4];
504 char *ResultPtr = ResultBuf;
Dmitri Gribenkocb5620c2013-01-30 12:06:08 +0000505 bool Res = llvm::ConvertCodePointToUTF8(Codepoint, ResultPtr);
Jordan Rosec7629d92013-01-24 20:50:46 +0000506 (void)Res;
507 assert(Res && "Unexpected conversion failure");
508 Str.append(ResultBuf, ResultPtr);
509}
510
511static void expandUCNs(SmallVectorImpl<char> &Buf, StringRef Input) {
512 for (StringRef::iterator I = Input.begin(), E = Input.end(); I != E; ++I) {
513 if (*I != '\\') {
514 Buf.push_back(*I);
515 continue;
516 }
517
518 ++I;
519 assert(*I == 'u' || *I == 'U');
520
521 unsigned NumHexDigits;
522 if (*I == 'u')
523 NumHexDigits = 4;
524 else
525 NumHexDigits = 8;
526
527 assert(I + NumHexDigits <= E);
528
529 uint32_t CodePoint = 0;
530 for (++I; NumHexDigits != 0; ++I, --NumHexDigits) {
531 unsigned Value = llvm::hexDigitValue(*I);
532 assert(Value != -1U);
533
534 CodePoint <<= 4;
535 CodePoint += Value;
536 }
537
538 appendCodePoint(CodePoint, Buf);
539 --I;
540 }
541}
542
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +0000543/// LookUpIdentifierInfo - Given a tok::raw_identifier token, look up the
544/// identifier information for the token and install it into the token,
545/// updating the token kind accordingly.
546IdentifierInfo *Preprocessor::LookUpIdentifierInfo(Token &Identifier) const {
547 assert(Identifier.getRawIdentifierData() != 0 && "No raw identifier data!");
Mike Stump1eb44332009-09-09 15:08:12 +0000548
Reid Spencer5f016e22007-07-11 17:01:13 +0000549 // Look up this token, see if it is a macro, or if it is a language keyword.
550 IdentifierInfo *II;
Jordan Rosec7629d92013-01-24 20:50:46 +0000551 if (!Identifier.needsCleaning() && !Identifier.hasUCN()) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000552 // No cleaning needed, just use the characters from the lexed buffer.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000553 II = getIdentifierInfo(StringRef(Identifier.getRawIdentifierData(),
Jordan Rosec7629d92013-01-24 20:50:46 +0000554 Identifier.getLength()));
Reid Spencer5f016e22007-07-11 17:01:13 +0000555 } else {
556 // Cleaning needed, alloca a buffer, clean into it, then use the buffer.
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +0000557 SmallString<64> IdentifierBuffer;
Chris Lattner5f9e2722011-07-23 10:55:15 +0000558 StringRef CleanedStr = getSpelling(Identifier, IdentifierBuffer);
Jordan Rosec7629d92013-01-24 20:50:46 +0000559
560 if (Identifier.hasUCN()) {
561 SmallString<64> UCNIdentifierBuffer;
562 expandUCNs(UCNIdentifierBuffer, CleanedStr);
563 II = getIdentifierInfo(UCNIdentifierBuffer);
564 } else {
565 II = getIdentifierInfo(CleanedStr);
566 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000567 }
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +0000568
569 // Update the token info (identifier info and appropriate token kind).
Reid Spencer5f016e22007-07-11 17:01:13 +0000570 Identifier.setIdentifierInfo(II);
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +0000571 Identifier.setKind(II->getTokenID());
572
Reid Spencer5f016e22007-07-11 17:01:13 +0000573 return II;
574}
575
John Wiegley28bbe4b2011-04-28 01:08:34 +0000576void Preprocessor::SetPoisonReason(IdentifierInfo *II, unsigned DiagID) {
577 PoisonReasons[II] = DiagID;
578}
579
580void Preprocessor::PoisonSEHIdentifiers(bool Poison) {
581 assert(Ident__exception_code && Ident__exception_info);
582 assert(Ident___exception_code && Ident___exception_info);
583 Ident__exception_code->setIsPoisoned(Poison);
584 Ident___exception_code->setIsPoisoned(Poison);
585 Ident_GetExceptionCode->setIsPoisoned(Poison);
586 Ident__exception_info->setIsPoisoned(Poison);
587 Ident___exception_info->setIsPoisoned(Poison);
588 Ident_GetExceptionInfo->setIsPoisoned(Poison);
589 Ident__abnormal_termination->setIsPoisoned(Poison);
590 Ident___abnormal_termination->setIsPoisoned(Poison);
591 Ident_AbnormalTermination->setIsPoisoned(Poison);
592}
593
594void Preprocessor::HandlePoisonedIdentifier(Token & Identifier) {
595 assert(Identifier.getIdentifierInfo() &&
596 "Can't handle identifiers without identifier info!");
597 llvm::DenseMap<IdentifierInfo*,unsigned>::const_iterator it =
598 PoisonReasons.find(Identifier.getIdentifierInfo());
599 if(it == PoisonReasons.end())
600 Diag(Identifier, diag::err_pp_used_poisoned_id);
601 else
602 Diag(Identifier,it->second) << Identifier.getIdentifierInfo();
603}
Reid Spencer5f016e22007-07-11 17:01:13 +0000604
605/// HandleIdentifier - This callback is invoked when the lexer reads an
606/// identifier. This callback looks up the identifier in the map and/or
607/// potentially macro expands it or turns it into a named token (like 'for').
Chris Lattner6a170eb2009-01-21 07:43:11 +0000608///
609/// Note that callers of this method are guarded by checking the
610/// IdentifierInfo's 'isHandleIdentifierCase' bit. If this method changes, the
611/// IdentifierInfo methods that compute these properties will need to change to
612/// match.
Chris Lattnerd2177732007-07-20 16:59:19 +0000613void Preprocessor::HandleIdentifier(Token &Identifier) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000614 assert(Identifier.getIdentifierInfo() &&
615 "Can't handle identifiers without identifier info!");
Mike Stump1eb44332009-09-09 15:08:12 +0000616
Reid Spencer5f016e22007-07-11 17:01:13 +0000617 IdentifierInfo &II = *Identifier.getIdentifierInfo();
618
Douglas Gregoreee242f2011-10-27 09:33:13 +0000619 // If the information about this identifier is out of date, update it from
620 // the external source.
Douglas Gregor193f91b2012-06-29 18:27:59 +0000621 // We have to treat __VA_ARGS__ in a special way, since it gets
622 // serialized with isPoisoned = true, but our preprocessor may have
623 // unpoisoned it if we're defining a C99 macro.
Douglas Gregoreee242f2011-10-27 09:33:13 +0000624 if (II.isOutOfDate()) {
Douglas Gregor193f91b2012-06-29 18:27:59 +0000625 bool CurrentIsPoisoned = false;
626 if (&II == Ident__VA_ARGS__)
627 CurrentIsPoisoned = Ident__VA_ARGS__->isPoisoned();
628
Douglas Gregoreee242f2011-10-27 09:33:13 +0000629 ExternalSource->updateOutOfDateIdentifier(II);
630 Identifier.setKind(II.getTokenID());
Douglas Gregor193f91b2012-06-29 18:27:59 +0000631
632 if (&II == Ident__VA_ARGS__)
633 II.setIsPoisoned(CurrentIsPoisoned);
Douglas Gregoreee242f2011-10-27 09:33:13 +0000634 }
635
Reid Spencer5f016e22007-07-11 17:01:13 +0000636 // If this identifier was poisoned, and if it was not produced from a macro
637 // expansion, emit an error.
Ted Kremenek1a531572008-11-19 22:43:49 +0000638 if (II.isPoisoned() && CurPPLexer) {
John Wiegley28bbe4b2011-04-28 01:08:34 +0000639 HandlePoisonedIdentifier(Identifier);
Reid Spencer5f016e22007-07-11 17:01:13 +0000640 }
Mike Stump1eb44332009-09-09 15:08:12 +0000641
Reid Spencer5f016e22007-07-11 17:01:13 +0000642 // If this is a macro to be expanded, do it.
Argyrios Kyrtzidisc5159782013-02-24 00:05:14 +0000643 if (MacroDirective *MD = getMacroDirective(&II)) {
Argyrios Kyrtzidisc56fff72013-03-26 17:17:01 +0000644 MacroInfo *MI = MD->getMacroInfo();
Abramo Bagnara163ada82012-01-01 22:01:04 +0000645 if (!DisableMacroExpansion) {
Richard Smith1fbf6fb2012-12-12 02:46:14 +0000646 if (!Identifier.isExpandDisabled() && MI->isEnabled()) {
Argyrios Kyrtzidisc5159782013-02-24 00:05:14 +0000647 if (!HandleMacroExpandedIdentifier(Identifier, MD))
Douglas Gregor6be16fe2011-08-27 06:37:51 +0000648 return;
Reid Spencer5f016e22007-07-11 17:01:13 +0000649 } else {
650 // C99 6.10.3.4p2 says that a disabled macro may never again be
651 // expanded, even if it's in a context where it could be expanded in the
652 // future.
Chris Lattnerd2177732007-07-20 16:59:19 +0000653 Identifier.setFlag(Token::DisableExpand);
Richard Smith1fbf6fb2012-12-12 02:46:14 +0000654 if (MI->isObjectLike() || isNextPPTokenLParen())
655 Diag(Identifier, diag::pp_disabled_macro_expansion);
Reid Spencer5f016e22007-07-11 17:01:13 +0000656 }
657 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000658 }
659
Richard Smith98d86b92011-10-11 19:57:52 +0000660 // If this identifier is a keyword in C++11, produce a warning. Don't warn if
661 // we're not considering macro expansion, since this identifier might be the
662 // name of a macro.
663 // FIXME: This warning is disabled in cases where it shouldn't be, like
664 // "#define constexpr constexpr", "int constexpr;"
665 if (II.isCXX11CompatKeyword() & !DisableMacroExpansion) {
666 Diag(Identifier, diag::warn_cxx11_keyword) << II.getName();
667 // Don't diagnose this keyword again in this translation unit.
668 II.setIsCXX11CompatKeyword(false);
669 }
670
Reid Spencer5f016e22007-07-11 17:01:13 +0000671 // C++ 2.11p2: If this is an alternative representation of a C++ operator,
672 // then we act as if it is the actual operator and not the textual
673 // representation of it.
Fariborz Jahanianafbc6812010-09-03 17:33:04 +0000674 if (II.isCPlusPlusOperatorKeyword())
Reid Spencer5f016e22007-07-11 17:01:13 +0000675 Identifier.setIdentifierInfo(0);
676
Reid Spencer5f016e22007-07-11 17:01:13 +0000677 // If this is an extension token, diagnose its use.
Steve Naroffb4eaf9c2008-09-02 18:50:17 +0000678 // We avoid diagnosing tokens that originate from macro definitions.
Eli Friedman2962f4d2009-04-28 03:59:15 +0000679 // FIXME: This warning is disabled in cases where it shouldn't be,
680 // like "#define TY typeof", "TY(1) x".
681 if (II.isExtensionToken() && !DisableMacroExpansion)
Reid Spencer5f016e22007-07-11 17:01:13 +0000682 Diag(Identifier, diag::ext_token_used);
Douglas Gregorb8db7cd2011-09-07 23:11:54 +0000683
Douglas Gregor1b257af2012-12-11 22:11:52 +0000684 // If this is the 'import' contextual keyword, note
Ted Kremenek32ad2ee2012-03-01 22:07:04 +0000685 // that the next token indicates a module name.
Douglas Gregord6aba062012-01-04 06:20:15 +0000686 //
Douglas Gregor1b257af2012-12-11 22:11:52 +0000687 // Note that we do not treat 'import' as a contextual
Ted Kremenek32ad2ee2012-03-01 22:07:04 +0000688 // keyword when we're in a caching lexer, because caching lexers only get
689 // used in contexts where import declarations are disallowed.
690 if (II.isModulesImport() && !InMacroArgs && !DisableMacroExpansion &&
David Blaikie4e4d0842012-03-11 07:00:24 +0000691 getLangOpts().Modules && CurLexerKind != CLK_CachingLexer) {
Douglas Gregorb8db7cd2011-09-07 23:11:54 +0000692 ModuleImportLoc = Identifier.getLocation();
Douglas Gregorb514c792011-11-30 04:26:53 +0000693 ModuleImportPath.clear();
694 ModuleImportExpectsIdentifier = true;
Douglas Gregorb8db7cd2011-09-07 23:11:54 +0000695 CurLexerKind = CLK_LexAfterModuleImport;
696 }
Douglas Gregor6aa52ec2011-08-26 23:56:07 +0000697}
698
Douglas Gregorc13a34b2012-01-03 19:32:59 +0000699/// \brief Lex a token following the 'import' contextual keyword.
Douglas Gregor5948ae12012-01-03 18:04:46 +0000700///
Douglas Gregorb8db7cd2011-09-07 23:11:54 +0000701void Preprocessor::LexAfterModuleImport(Token &Result) {
702 // Figure out what kind of lexer we actually have.
Douglas Gregord6aba062012-01-04 06:20:15 +0000703 recomputeCurLexerKind();
Douglas Gregorb8db7cd2011-09-07 23:11:54 +0000704
705 // Lex the next token.
706 Lex(Result);
707
Douglas Gregor6aa52ec2011-08-26 23:56:07 +0000708 // The token sequence
709 //
Douglas Gregor5948ae12012-01-03 18:04:46 +0000710 // import identifier (. identifier)*
711 //
Douglas Gregorc13a34b2012-01-03 19:32:59 +0000712 // indicates a module import directive. We already saw the 'import'
713 // contextual keyword, so now we're looking for the identifiers.
Douglas Gregorb514c792011-11-30 04:26:53 +0000714 if (ModuleImportExpectsIdentifier && Result.getKind() == tok::identifier) {
715 // We expected to see an identifier here, and we did; continue handling
716 // identifiers.
717 ModuleImportPath.push_back(std::make_pair(Result.getIdentifierInfo(),
718 Result.getLocation()));
719 ModuleImportExpectsIdentifier = false;
720 CurLexerKind = CLK_LexAfterModuleImport;
Douglas Gregor6aa52ec2011-08-26 23:56:07 +0000721 return;
Douglas Gregorb514c792011-11-30 04:26:53 +0000722 }
Douglas Gregor6aa52ec2011-08-26 23:56:07 +0000723
Douglas Gregorb514c792011-11-30 04:26:53 +0000724 // If we're expecting a '.' or a ';', and we got a '.', then wait until we
725 // see the next identifier.
726 if (!ModuleImportExpectsIdentifier && Result.getKind() == tok::period) {
727 ModuleImportExpectsIdentifier = true;
728 CurLexerKind = CLK_LexAfterModuleImport;
729 return;
730 }
731
732 // If we have a non-empty module path, load the named module.
Argyrios Kyrtzidisf8afcff2012-09-29 01:06:10 +0000733 if (!ModuleImportPath.empty()) {
734 Module *Imported = TheModuleLoader.loadModule(ModuleImportLoc,
735 ModuleImportPath,
736 Module::MacrosVisible,
737 /*IsIncludeDirective=*/false);
738 if (Callbacks)
739 Callbacks->moduleImport(ModuleImportLoc, ModuleImportPath, Imported);
740 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000741}
Douglas Gregor2e222532009-07-02 17:08:52 +0000742
Andy Gibbs02a17682012-11-17 19:15:38 +0000743bool Preprocessor::FinishLexStringLiteral(Token &Result, std::string &String,
Andy Gibbs97f84612012-11-17 19:16:52 +0000744 const char *DiagnosticTag,
Andy Gibbs02a17682012-11-17 19:15:38 +0000745 bool AllowMacroExpansion) {
746 // We need at least one string literal.
747 if (Result.isNot(tok::string_literal)) {
Andy Gibbs97f84612012-11-17 19:16:52 +0000748 Diag(Result, diag::err_expected_string_literal)
749 << /*Source='in...'*/0 << DiagnosticTag;
Andy Gibbs02a17682012-11-17 19:15:38 +0000750 return false;
751 }
752
753 // Lex string literal tokens, optionally with macro expansion.
754 SmallVector<Token, 4> StrToks;
755 do {
756 StrToks.push_back(Result);
757
758 if (Result.hasUDSuffix())
759 Diag(Result, diag::err_invalid_string_udl);
760
761 if (AllowMacroExpansion)
762 Lex(Result);
763 else
764 LexUnexpandedToken(Result);
765 } while (Result.is(tok::string_literal));
766
767 // Concatenate and parse the strings.
768 StringLiteralParser Literal(&StrToks[0], StrToks.size(), *this);
769 assert(Literal.isAscii() && "Didn't allow wide strings in");
770
771 if (Literal.hadError)
772 return false;
773
774 if (Literal.Pascal) {
Andy Gibbs97f84612012-11-17 19:16:52 +0000775 Diag(StrToks[0].getLocation(), diag::err_expected_string_literal)
776 << /*Source='in...'*/0 << DiagnosticTag;
Andy Gibbs02a17682012-11-17 19:15:38 +0000777 return false;
778 }
779
780 String = Literal.GetString();
781 return true;
782}
783
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +0000784void Preprocessor::addCommentHandler(CommentHandler *Handler) {
Douglas Gregor2e222532009-07-02 17:08:52 +0000785 assert(Handler && "NULL comment handler");
786 assert(std::find(CommentHandlers.begin(), CommentHandlers.end(), Handler) ==
787 CommentHandlers.end() && "Comment handler already registered");
788 CommentHandlers.push_back(Handler);
789}
790
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +0000791void Preprocessor::removeCommentHandler(CommentHandler *Handler) {
Douglas Gregor2e222532009-07-02 17:08:52 +0000792 std::vector<CommentHandler *>::iterator Pos
793 = std::find(CommentHandlers.begin(), CommentHandlers.end(), Handler);
794 assert(Pos != CommentHandlers.end() && "Comment handler not registered");
795 CommentHandlers.erase(Pos);
796}
797
Chris Lattner046c2272010-01-18 22:35:47 +0000798bool Preprocessor::HandleComment(Token &result, SourceRange Comment) {
799 bool AnyPendingTokens = false;
Douglas Gregor2e222532009-07-02 17:08:52 +0000800 for (std::vector<CommentHandler *>::iterator H = CommentHandlers.begin(),
801 HEnd = CommentHandlers.end();
Chris Lattner046c2272010-01-18 22:35:47 +0000802 H != HEnd; ++H) {
803 if ((*H)->HandleComment(*this, Comment))
804 AnyPendingTokens = true;
805 }
806 if (!AnyPendingTokens || getCommentRetentionState())
807 return false;
808 Lex(result);
809 return true;
Douglas Gregor2e222532009-07-02 17:08:52 +0000810}
811
Douglas Gregor6aa52ec2011-08-26 23:56:07 +0000812ModuleLoader::~ModuleLoader() { }
813
Douglas Gregor2e222532009-07-02 17:08:52 +0000814CommentHandler::~CommentHandler() { }
Douglas Gregor94dc8f62010-03-19 16:15:56 +0000815
Douglas Gregorf44e8542010-08-24 19:08:16 +0000816CodeCompletionHandler::~CodeCompletionHandler() { }
817
Argyrios Kyrtzidis37ed1272012-12-04 07:27:05 +0000818void Preprocessor::createPreprocessingRecord() {
Douglas Gregor94dc8f62010-03-19 16:15:56 +0000819 if (Record)
820 return;
821
Argyrios Kyrtzidis37ed1272012-12-04 07:27:05 +0000822 Record = new PreprocessingRecord(getSourceManager());
Douglas Gregorb9e1b752010-03-19 17:12:43 +0000823 addPPCallbacks(Record);
Douglas Gregor94dc8f62010-03-19 16:15:56 +0000824}