blob: d85df38ea711bb01a6fe4e022fea3ed3f59cd43e [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"
Chandler Carruth55fc8732012-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 Gregor88a35862010-01-04 19:18:44 +000033#include "clang/Lex/ExternalPreprocessorSource.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000034#include "clang/Lex/HeaderSearch.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000035#include "clang/Lex/LexDiagnostic.h"
36#include "clang/Lex/LiteralSupport.h"
Stephen Hines651f13c2014-04-23 16:59:28 -070037#include "clang/Lex/MacroArgs.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"
Jordan Rosec7629d92013-01-24 20:50:46 +000045#include "llvm/ADT/STLExtras.h"
Stephen Hines651f13c2014-04-23 16:59:28 -070046#include "llvm/ADT/SmallString.h"
Jordan Rosec7629d92013-01-24 20:50:46 +000047#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,
Stephen Hines651f13c2014-04-23 16:59:28 -070062 bool DelayInitialization, bool IncrProcessing,
63 TranslationUnitKind TUKind)
David Blaikie49446062013-01-16 23:13:36 +000064 : PPOpts(PPOpts), Diags(&diags), LangOpts(opts), Target(target),
65 FileMgr(Headers.getFileMgr()), SourceMgr(SM), HeaderInfo(Headers),
66 TheModuleLoader(TheModuleLoader), ExternalSource(0),
David Blaikie0a3cbd02013-01-16 23:18:16 +000067 Identifiers(opts, IILookup), IncrementalProcessing(IncrProcessing),
Stephen Hines651f13c2014-04-23 16:59:28 -070068 TUKind(TUKind),
David Blaikie0a3cbd02013-01-16 23:18:16 +000069 CodeComplete(0), CodeCompletionFile(0), CodeCompletionOffset(0),
Douglas Gregora5ba7b42013-11-07 22:55:02 +000070 LastTokenWasAt(false), ModuleImportExpectsIdentifier(false),
David Blaikie0a3cbd02013-01-16 23:18:16 +000071 CodeCompletionReached(0), SkipMainFilePreamble(0, true), CurPPLexer(0),
Stephen Hines651f13c2014-04-23 16:59:28 -070072 CurDirLookup(0), CurLexerKind(CLK_Lexer), CurSubmodule(0),
73 Callbacks(0), MacroArgCache(0), Record(0), MIChainHead(0), MICache(0),
Argyrios Kyrtzidis3e25b992013-04-30 05:05:35 +000074 DeserialMIChainHead(0) {
Daniel Dunbar5814e652009-11-11 21:44:21 +000075 OwnsHeaderSearch = OwnsHeaders;
Douglas Gregor998b3d32011-09-01 23:39:15 +000076
77 ScratchBuf = new ScratchBuffer(SourceMgr);
78 CounterValue = 0; // __COUNTER__ starts at 0.
79
80 // Clear stats.
81 NumDirectives = NumDefined = NumUndefined = NumPragma = 0;
82 NumIf = NumElse = NumEndif = 0;
83 NumEnteredSourceFiles = 0;
84 NumMacroExpanded = NumFnMacroExpanded = NumBuiltinMacroExpanded = 0;
85 NumFastMacroExpanded = NumTokenPaste = NumFastTokenPaste = 0;
86 MaxIncludeStackDepth = 0;
87 NumSkipped = 0;
88
89 // Default to discarding comments.
90 KeepComments = false;
91 KeepMacroComments = false;
92 SuppressIncludeNotFoundError = false;
93
94 // Macro expansion is enabled.
95 DisableMacroExpansion = false;
David Blaikie8c0b3782012-06-06 18:52:13 +000096 MacroExpansionInDirectivesOverride = false;
Douglas Gregor998b3d32011-09-01 23:39:15 +000097 InMacroArgs = false;
Argyrios Kyrtzidis14e64552012-04-03 16:47:40 +000098 InMacroArgPreExpansion = false;
Douglas Gregor998b3d32011-09-01 23:39:15 +000099 NumCachedTokenLexers = 0;
Jordan Rose6fe6a492012-06-08 18:06:21 +0000100 PragmasEnabled = true;
Eric Christopher214ea9d2013-01-16 20:09:36 +0000101 ParsingIfOrElifDirective = false;
Jordan Rose98b21b92013-01-31 19:26:01 +0000102 PreprocessedOutput = false;
Jordan Rose6fe6a492012-06-08 18:06:21 +0000103
Douglas Gregor998b3d32011-09-01 23:39:15 +0000104 CachedLexPos = 0;
Eric Christopher214ea9d2013-01-16 20:09:36 +0000105
Douglas Gregor998b3d32011-09-01 23:39:15 +0000106 // We haven't read anything from the external source.
107 ReadMacrosFromExternalSource = false;
108
Douglas Gregor998b3d32011-09-01 23:39:15 +0000109 // "Poison" __VA_ARGS__, which can only appear in the expansion of a macro.
110 // This gets unpoisoned where it is allowed.
111 (Ident__VA_ARGS__ = getIdentifierInfo("__VA_ARGS__"))->setIsPoisoned();
112 SetPoisonReason(Ident__VA_ARGS__,diag::ext_pp_bad_vaargs_use);
113
114 // Initialize the pragma handlers.
115 PragmaHandlers = new PragmaNamespace(StringRef());
116 RegisterBuiltinPragmas();
117
118 // Initialize builtin macros like __LINE__ and friends.
119 RegisterBuiltinMacros();
120
David Blaikie4e4d0842012-03-11 07:00:24 +0000121 if(LangOpts.Borland) {
Douglas Gregor998b3d32011-09-01 23:39:15 +0000122 Ident__exception_info = getIdentifierInfo("_exception_info");
123 Ident___exception_info = getIdentifierInfo("__exception_info");
124 Ident_GetExceptionInfo = getIdentifierInfo("GetExceptionInformation");
125 Ident__exception_code = getIdentifierInfo("_exception_code");
126 Ident___exception_code = getIdentifierInfo("__exception_code");
127 Ident_GetExceptionCode = getIdentifierInfo("GetExceptionCode");
128 Ident__abnormal_termination = getIdentifierInfo("_abnormal_termination");
129 Ident___abnormal_termination = getIdentifierInfo("__abnormal_termination");
130 Ident_AbnormalTermination = getIdentifierInfo("AbnormalTermination");
131 } else {
132 Ident__exception_info = Ident__exception_code = Ident__abnormal_termination = 0;
133 Ident___exception_info = Ident___exception_code = Ident___abnormal_termination = 0;
134 Ident_GetExceptionInfo = Ident_GetExceptionCode = Ident_AbnormalTermination = 0;
Douglas Gregordc58aa72012-01-30 06:01:29 +0000135 }
Argyrios Kyrtzidis25c25962012-06-02 18:08:09 +0000136
137 if (!DelayInitialization) {
138 assert(Target && "Must provide target information for PP initialization");
139 Initialize(*Target);
140 }
141}
142
143Preprocessor::~Preprocessor() {
144 assert(BacktrackPositions.empty() && "EnableBacktrack/Backtrack imbalance!");
145
Stephen Hines651f13c2014-04-23 16:59:28 -0700146 IncludeMacroStack.clear();
Argyrios Kyrtzidis25c25962012-06-02 18:08:09 +0000147
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
Argyrios Kyrtzidis3e25b992013-04-30 05:05:35 +0000156 for (DeserializedMacroInfoChain *I = DeserialMIChainHead ; I ; I = I->Next)
157 I->MI.Destroy();
158
Argyrios Kyrtzidis25c25962012-06-02 18:08:09 +0000159 // Free any cached MacroArgs.
160 for (MacroArgs *ArgList = MacroArgCache; ArgList; )
161 ArgList = ArgList->deallocate();
162
163 // Release pragma information.
164 delete PragmaHandlers;
165
166 // Delete the scratch buffer info.
167 delete ScratchBuf;
168
169 // Delete the header search info, if we own it.
170 if (OwnsHeaderSearch)
171 delete &HeaderInfo;
172
173 delete Callbacks;
174}
175
176void Preprocessor::Initialize(const TargetInfo &Target) {
177 assert((!this->Target || this->Target == &Target) &&
178 "Invalid override of target information");
179 this->Target = &Target;
Douglas Gregordc58aa72012-01-30 06:01:29 +0000180
Argyrios Kyrtzidis25c25962012-06-02 18:08:09 +0000181 // Initialize information about built-ins.
182 BuiltinInfo.InitializeTarget(Target);
Douglas Gregordc58aa72012-01-30 06:01:29 +0000183 HeaderInfo.setTarget(Target);
Douglas Gregor998b3d32011-09-01 23:39:15 +0000184}
185
Ted Kremenek337edcd2009-02-12 03:26:59 +0000186void Preprocessor::setPTHManager(PTHManager* pm) {
187 PTH.reset(pm);
Douglas Gregor52e71082009-10-16 18:18:30 +0000188 FileMgr.addStatCache(PTH->createStatCache());
Ted Kremenek337edcd2009-02-12 03:26:59 +0000189}
190
Chris Lattnerd2177732007-07-20 16:59:19 +0000191void Preprocessor::DumpToken(const Token &Tok, bool DumpFlags) const {
Benjamin Kramer6cb7c1a2009-08-23 12:08:50 +0000192 llvm::errs() << tok::getTokenName(Tok.getKind()) << " '"
193 << getSpelling(Tok) << "'";
Mike Stump1eb44332009-09-09 15:08:12 +0000194
Reid Spencer5f016e22007-07-11 17:01:13 +0000195 if (!DumpFlags) return;
Mike Stump1eb44332009-09-09 15:08:12 +0000196
Benjamin Kramer6cb7c1a2009-08-23 12:08:50 +0000197 llvm::errs() << "\t";
Reid Spencer5f016e22007-07-11 17:01:13 +0000198 if (Tok.isAtStartOfLine())
Benjamin Kramer6cb7c1a2009-08-23 12:08:50 +0000199 llvm::errs() << " [StartOfLine]";
Reid Spencer5f016e22007-07-11 17:01:13 +0000200 if (Tok.hasLeadingSpace())
Benjamin Kramer6cb7c1a2009-08-23 12:08:50 +0000201 llvm::errs() << " [LeadingSpace]";
Reid Spencer5f016e22007-07-11 17:01:13 +0000202 if (Tok.isExpandDisabled())
Benjamin Kramer6cb7c1a2009-08-23 12:08:50 +0000203 llvm::errs() << " [ExpandDisabled]";
Reid Spencer5f016e22007-07-11 17:01:13 +0000204 if (Tok.needsCleaning()) {
205 const char *Start = SourceMgr.getCharacterData(Tok.getLocation());
Chris Lattner5f9e2722011-07-23 10:55:15 +0000206 llvm::errs() << " [UnClean='" << StringRef(Start, Tok.getLength())
Benjamin Kramer6cb7c1a2009-08-23 12:08:50 +0000207 << "']";
Reid Spencer5f016e22007-07-11 17:01:13 +0000208 }
Mike Stump1eb44332009-09-09 15:08:12 +0000209
Benjamin Kramer6cb7c1a2009-08-23 12:08:50 +0000210 llvm::errs() << "\tLoc=<";
Chris Lattnerc3d8d572007-12-09 20:31:55 +0000211 DumpLocation(Tok.getLocation());
Benjamin Kramer6cb7c1a2009-08-23 12:08:50 +0000212 llvm::errs() << ">";
Chris Lattnerc3d8d572007-12-09 20:31:55 +0000213}
214
215void Preprocessor::DumpLocation(SourceLocation Loc) const {
Chris Lattnerb9c3f962009-01-27 07:57:44 +0000216 Loc.dump(SourceMgr);
Reid Spencer5f016e22007-07-11 17:01:13 +0000217}
218
219void Preprocessor::DumpMacro(const MacroInfo &MI) const {
Benjamin Kramer6cb7c1a2009-08-23 12:08:50 +0000220 llvm::errs() << "MACRO: ";
Reid Spencer5f016e22007-07-11 17:01:13 +0000221 for (unsigned i = 0, e = MI.getNumTokens(); i != e; ++i) {
222 DumpToken(MI.getReplacementToken(i));
Benjamin Kramer6cb7c1a2009-08-23 12:08:50 +0000223 llvm::errs() << " ";
Reid Spencer5f016e22007-07-11 17:01:13 +0000224 }
Benjamin Kramer6cb7c1a2009-08-23 12:08:50 +0000225 llvm::errs() << "\n";
Reid Spencer5f016e22007-07-11 17:01:13 +0000226}
227
228void Preprocessor::PrintStats() {
Benjamin Kramer6cb7c1a2009-08-23 12:08:50 +0000229 llvm::errs() << "\n*** Preprocessor Stats:\n";
230 llvm::errs() << NumDirectives << " directives found:\n";
231 llvm::errs() << " " << NumDefined << " #define.\n";
232 llvm::errs() << " " << NumUndefined << " #undef.\n";
233 llvm::errs() << " #include/#include_next/#import:\n";
234 llvm::errs() << " " << NumEnteredSourceFiles << " source files entered.\n";
235 llvm::errs() << " " << MaxIncludeStackDepth << " max include stack depth\n";
236 llvm::errs() << " " << NumIf << " #if/#ifndef/#ifdef.\n";
237 llvm::errs() << " " << NumElse << " #else/#elif.\n";
238 llvm::errs() << " " << NumEndif << " #endif.\n";
239 llvm::errs() << " " << NumPragma << " #pragma.\n";
240 llvm::errs() << NumSkipped << " #if/#ifndef#ifdef regions skipped\n";
Reid Spencer5f016e22007-07-11 17:01:13 +0000241
Benjamin Kramer6cb7c1a2009-08-23 12:08:50 +0000242 llvm::errs() << NumMacroExpanded << "/" << NumFnMacroExpanded << "/"
Ted Kremenekbdd30c22008-01-14 16:44:48 +0000243 << NumBuiltinMacroExpanded << " obj/fn/builtin macros expanded, "
244 << NumFastMacroExpanded << " on the fast path.\n";
Benjamin Kramer6cb7c1a2009-08-23 12:08:50 +0000245 llvm::errs() << (NumFastTokenPaste+NumTokenPaste)
Ted Kremenekbdd30c22008-01-14 16:44:48 +0000246 << " token paste (##) operations performed, "
247 << NumFastTokenPaste << " on the fast path.\n";
Alexander Kornienkocd6df662012-08-13 10:46:42 +0000248
249 llvm::errs() << "\nPreprocessor Memory: " << getTotalMemory() << "B total";
250
251 llvm::errs() << "\n BumpPtr: " << BP.getTotalMemory();
252 llvm::errs() << "\n Macro Expanded Tokens: "
253 << llvm::capacity_in_bytes(MacroExpandedTokens);
254 llvm::errs() << "\n Predefines Buffer: " << Predefines.capacity();
255 llvm::errs() << "\n Macros: " << llvm::capacity_in_bytes(Macros);
256 llvm::errs() << "\n #pragma push_macro Info: "
257 << llvm::capacity_in_bytes(PragmaPushMacroInfo);
258 llvm::errs() << "\n Poison Reasons: "
259 << llvm::capacity_in_bytes(PoisonReasons);
260 llvm::errs() << "\n Comment Handlers: "
261 << llvm::capacity_in_bytes(CommentHandlers) << "\n";
Reid Spencer5f016e22007-07-11 17:01:13 +0000262}
263
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +0000264Preprocessor::macro_iterator
265Preprocessor::macro_begin(bool IncludeExternalMacros) const {
266 if (IncludeExternalMacros && ExternalSource &&
Douglas Gregor88a35862010-01-04 19:18:44 +0000267 !ReadMacrosFromExternalSource) {
268 ReadMacrosFromExternalSource = true;
269 ExternalSource->ReadDefinedMacros();
270 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +0000271
272 return Macros.begin();
Douglas Gregor88a35862010-01-04 19:18:44 +0000273}
274
Argyrios Kyrtzidisc5c5e922011-06-29 22:20:04 +0000275size_t Preprocessor::getTotalMemory() const {
Ted Kremenek91d1bd62011-07-26 21:17:24 +0000276 return BP.getTotalMemory()
Ted Kremenek67485092011-07-27 18:41:23 +0000277 + llvm::capacity_in_bytes(MacroExpandedTokens)
Ted Kremenek91d1bd62011-07-26 21:17:24 +0000278 + Predefines.capacity() /* Predefines buffer. */
Ted Kremenek67485092011-07-27 18:41:23 +0000279 + llvm::capacity_in_bytes(Macros)
280 + llvm::capacity_in_bytes(PragmaPushMacroInfo)
281 + llvm::capacity_in_bytes(PoisonReasons)
282 + llvm::capacity_in_bytes(CommentHandlers);
Argyrios Kyrtzidisc5c5e922011-06-29 22:20:04 +0000283}
284
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +0000285Preprocessor::macro_iterator
286Preprocessor::macro_end(bool IncludeExternalMacros) const {
287 if (IncludeExternalMacros && ExternalSource &&
Douglas Gregor88a35862010-01-04 19:18:44 +0000288 !ReadMacrosFromExternalSource) {
289 ReadMacrosFromExternalSource = true;
290 ExternalSource->ReadDefinedMacros();
291 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +0000292
293 return Macros.end();
Douglas Gregor88a35862010-01-04 19:18:44 +0000294}
295
Dmitri Gribenko19523542012-09-29 11:40:46 +0000296/// \brief Compares macro tokens with a specified token value sequence.
297static bool MacroDefinitionEquals(const MacroInfo *MI,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +0000298 ArrayRef<TokenValue> Tokens) {
Dmitri Gribenko19523542012-09-29 11:40:46 +0000299 return Tokens.size() == MI->getNumTokens() &&
300 std::equal(Tokens.begin(), Tokens.end(), MI->tokens_begin());
301}
302
303StringRef Preprocessor::getLastMacroWithSpelling(
304 SourceLocation Loc,
305 ArrayRef<TokenValue> Tokens) const {
306 SourceLocation BestLocation;
307 StringRef BestSpelling;
308 for (Preprocessor::macro_iterator I = macro_begin(), E = macro_end();
309 I != E; ++I) {
Argyrios Kyrtzidisc56fff72013-03-26 17:17:01 +0000310 if (!I->second->getMacroInfo()->isObjectLike())
Dmitri Gribenko19523542012-09-29 11:40:46 +0000311 continue;
Argyrios Kyrtzidisc56fff72013-03-26 17:17:01 +0000312 const MacroDirective::DefInfo
313 Def = I->second->findDirectiveAtLoc(Loc, SourceMgr);
314 if (!Def)
Dmitri Gribenko19523542012-09-29 11:40:46 +0000315 continue;
Argyrios Kyrtzidisc56fff72013-03-26 17:17:01 +0000316 if (!MacroDefinitionEquals(Def.getMacroInfo(), Tokens))
Dmitri Gribenko19523542012-09-29 11:40:46 +0000317 continue;
Argyrios Kyrtzidisc56fff72013-03-26 17:17:01 +0000318 SourceLocation Location = Def.getLocation();
Dmitri Gribenko19523542012-09-29 11:40:46 +0000319 // Choose the macro defined latest.
320 if (BestLocation.isInvalid() ||
321 (Location.isValid() &&
322 SourceMgr.isBeforeInTranslationUnit(BestLocation, Location))) {
323 BestLocation = Location;
324 BestSpelling = I->first->getName();
325 }
326 }
327 return BestSpelling;
328}
329
Douglas Gregord6aba062012-01-04 06:20:15 +0000330void Preprocessor::recomputeCurLexerKind() {
331 if (CurLexer)
332 CurLexerKind = CLK_Lexer;
333 else if (CurPTHLexer)
334 CurLexerKind = CLK_PTHLexer;
335 else if (CurTokenLexer)
336 CurLexerKind = CLK_TokenLexer;
337 else
338 CurLexerKind = CLK_CachingLexer;
339}
340
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +0000341bool Preprocessor::SetCodeCompletionPoint(const FileEntry *File,
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +0000342 unsigned CompleteLine,
343 unsigned CompleteColumn) {
344 assert(File);
345 assert(CompleteLine && CompleteColumn && "Starts from 1:1");
346 assert(!CodeCompletionFile && "Already set");
347
Douglas Gregor29684422009-12-02 06:49:09 +0000348 using llvm::MemoryBuffer;
349
Douglas Gregor29684422009-12-02 06:49:09 +0000350 // Load the actual file's contents.
Douglas Gregoraa38c3d2010-03-16 19:49:24 +0000351 bool Invalid = false;
352 const MemoryBuffer *Buffer = SourceMgr.getMemoryBufferForFile(File, &Invalid);
353 if (Invalid)
Douglas Gregor29684422009-12-02 06:49:09 +0000354 return true;
355
356 // Find the byte position of the truncation point.
357 const char *Position = Buffer->getBufferStart();
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +0000358 for (unsigned Line = 1; Line < CompleteLine; ++Line) {
Douglas Gregor29684422009-12-02 06:49:09 +0000359 for (; *Position; ++Position) {
360 if (*Position != '\r' && *Position != '\n')
361 continue;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +0000362
Douglas Gregor29684422009-12-02 06:49:09 +0000363 // Eat \r\n or \n\r as a single line.
364 if ((Position[1] == '\r' || Position[1] == '\n') &&
365 Position[0] != Position[1])
366 ++Position;
367 ++Position;
368 break;
369 }
370 }
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +0000371
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +0000372 Position += CompleteColumn - 1;
Kovarththanan Rajaratnam19357542010-03-13 10:17:05 +0000373
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +0000374 // Insert '\0' at the code-completion point.
Douglas Gregorb760fe82009-12-08 21:45:46 +0000375 if (Position < Buffer->getBufferEnd()) {
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +0000376 CodeCompletionFile = File;
377 CodeCompletionOffset = Position - Buffer->getBufferStart();
378
379 MemoryBuffer *NewBuffer =
380 MemoryBuffer::getNewUninitMemBuffer(Buffer->getBufferSize() + 1,
381 Buffer->getBufferIdentifier());
Benjamin Kramer41a50a92011-09-04 20:26:28 +0000382 char *NewBuf = const_cast<char*>(NewBuffer->getBufferStart());
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +0000383 char *NewPos = std::copy(Buffer->getBufferStart(), Position, NewBuf);
384 *NewPos = '\0';
385 std::copy(Position, Buffer->getBufferEnd(), NewPos+1);
386 SourceMgr.overrideFileContents(File, NewBuffer);
Douglas Gregor29684422009-12-02 06:49:09 +0000387 }
388
389 return false;
390}
391
Douglas Gregor55817af2010-08-25 17:04:25 +0000392void Preprocessor::CodeCompleteNaturalLanguage() {
Douglas Gregor55817af2010-08-25 17:04:25 +0000393 if (CodeComplete)
394 CodeComplete->CodeCompleteNaturalLanguage();
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +0000395 setCodeCompletionReached();
Douglas Gregor55817af2010-08-25 17:04:25 +0000396}
397
Benjamin Kramer51f5fe32010-02-27 17:05:45 +0000398/// getSpelling - This method is used to get the spelling of a token into a
399/// SmallVector. Note that the returned StringRef may not point to the
400/// supplied buffer if a copy can be avoided.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000401StringRef Preprocessor::getSpelling(const Token &Tok,
402 SmallVectorImpl<char> &Buffer,
Douglas Gregor50f6af72010-03-16 05:20:39 +0000403 bool *Invalid) const {
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +0000404 // NOTE: this has to be checked *before* testing for an IdentifierInfo.
Jordan Rosec7629d92013-01-24 20:50:46 +0000405 if (Tok.isNot(tok::raw_identifier) && !Tok.hasUCN()) {
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +0000406 // Try the fast path.
407 if (const IdentifierInfo *II = Tok.getIdentifierInfo())
408 return II->getName();
409 }
Benjamin Kramer51f5fe32010-02-27 17:05:45 +0000410
411 // Resize the buffer if we need to copy into it.
412 if (Tok.needsCleaning())
413 Buffer.resize(Tok.getLength());
414
415 const char *Ptr = Buffer.data();
Douglas Gregor50f6af72010-03-16 05:20:39 +0000416 unsigned Len = getSpelling(Tok, Ptr, Invalid);
Chris Lattner5f9e2722011-07-23 10:55:15 +0000417 return StringRef(Ptr, Len);
Benjamin Kramer51f5fe32010-02-27 17:05:45 +0000418}
419
Reid Spencer5f016e22007-07-11 17:01:13 +0000420/// CreateString - Plop the specified string into a scratch buffer and return a
421/// location for it. If specified, the source location provides a source
422/// location for the token.
Dmitri Gribenko374b3832012-09-24 21:07:17 +0000423void Preprocessor::CreateString(StringRef Str, Token &Tok,
Abramo Bagnaraa08529c2011-10-03 18:39:03 +0000424 SourceLocation ExpansionLocStart,
425 SourceLocation ExpansionLocEnd) {
Dmitri Gribenko374b3832012-09-24 21:07:17 +0000426 Tok.setLength(Str.size());
Mike Stump1eb44332009-09-09 15:08:12 +0000427
Chris Lattner47246be2009-01-26 19:29:26 +0000428 const char *DestPtr;
Dmitri Gribenko374b3832012-09-24 21:07:17 +0000429 SourceLocation Loc = ScratchBuf->getToken(Str.data(), Str.size(), DestPtr);
Mike Stump1eb44332009-09-09 15:08:12 +0000430
Abramo Bagnaraa08529c2011-10-03 18:39:03 +0000431 if (ExpansionLocStart.isValid())
432 Loc = SourceMgr.createExpansionLoc(Loc, ExpansionLocStart,
Dmitri Gribenko374b3832012-09-24 21:07:17 +0000433 ExpansionLocEnd, Str.size());
Chris Lattner47246be2009-01-26 19:29:26 +0000434 Tok.setLocation(Loc);
Mike Stump1eb44332009-09-09 15:08:12 +0000435
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +0000436 // If this is a raw identifier or a literal token, set the pointer data.
437 if (Tok.is(tok::raw_identifier))
438 Tok.setRawIdentifierData(DestPtr);
439 else if (Tok.isLiteral())
Chris Lattner47246be2009-01-26 19:29:26 +0000440 Tok.setLiteralData(DestPtr);
Reid Spencer5f016e22007-07-11 17:01:13 +0000441}
442
Douglas Gregor90db2602011-12-02 01:47:07 +0000443Module *Preprocessor::getCurrentModule() {
David Blaikie4e4d0842012-03-11 07:00:24 +0000444 if (getLangOpts().CurrentModule.empty())
Douglas Gregor90db2602011-12-02 01:47:07 +0000445 return 0;
446
David Blaikie4e4d0842012-03-11 07:00:24 +0000447 return getHeaderSearchInfo().lookupModule(getLangOpts().CurrentModule);
Douglas Gregor90db2602011-12-02 01:47:07 +0000448}
Chris Lattner97ba77c2007-07-16 06:48:38 +0000449
Chris Lattner53b0dab2007-10-09 22:10:18 +0000450//===----------------------------------------------------------------------===//
451// Preprocessor Initialization Methods
452//===----------------------------------------------------------------------===//
453
Chris Lattner53b0dab2007-10-09 22:10:18 +0000454
455/// EnterMainSourceFile - Enter the specified FileID as the main source file,
Nate Begeman6b616022008-01-07 04:01:26 +0000456/// which implicitly adds the builtin defines etc.
Chris Lattnere127a0d2010-04-20 20:35:58 +0000457void Preprocessor::EnterMainSourceFile() {
Chris Lattner05db4272009-02-13 19:33:24 +0000458 // We do not allow the preprocessor to reenter the main file. Doing so will
459 // cause FileID's to accumulate information from both runs (e.g. #line
460 // information) and predefined macros aren't guaranteed to be set properly.
461 assert(NumEnteredSourceFiles == 0 && "Cannot reenter the main file!");
Chris Lattner2b2453a2009-01-17 06:22:33 +0000462 FileID MainFileID = SourceMgr.getMainFileID();
Mike Stump1eb44332009-09-09 15:08:12 +0000463
Argyrios Kyrtzidisb8c879a2012-01-05 21:36:25 +0000464 // If MainFileID is loaded it means we loaded an AST file, no need to enter
465 // a main file.
466 if (!SourceMgr.isLoadedFileID(MainFileID)) {
467 // Enter the main file source buffer.
468 EnterSourceFile(MainFileID, 0, SourceLocation());
Douglas Gregorf4f6c9d2010-07-26 21:36:20 +0000469
Argyrios Kyrtzidisb8c879a2012-01-05 21:36:25 +0000470 // If we've been asked to skip bytes in the main file (e.g., as part of a
471 // precompiled preamble), do so now.
472 if (SkipMainFilePreamble.first > 0)
473 CurLexer->SkipBytes(SkipMainFilePreamble.first,
474 SkipMainFilePreamble.second);
475
476 // Tell the header info that the main file was entered. If the file is later
477 // #imported, it won't be re-entered.
478 if (const FileEntry *FE = SourceMgr.getFileEntryForID(MainFileID))
479 HeaderInfo.IncrementIncludeCount(FE);
480 }
Mike Stump1eb44332009-09-09 15:08:12 +0000481
Benjamin Kramerffd6e392009-12-31 15:33:09 +0000482 // Preprocess Predefines to populate the initial preprocessor state.
Mike Stump1eb44332009-09-09 15:08:12 +0000483 llvm::MemoryBuffer *SB =
Chris Lattnera0a270c2010-04-05 22:42:27 +0000484 llvm::MemoryBuffer::getMemBufferCopy(Predefines, "<built-in>");
Douglas Gregor043266b2010-08-26 14:07:34 +0000485 assert(SB && "Cannot create predefined source buffer");
Meador Inge9416d422012-06-19 18:17:30 +0000486 FileID FID = SourceMgr.createFileIDForMemBuffer(SB);
Chris Lattner2b2453a2009-01-17 06:22:33 +0000487 assert(!FID.isInvalid() && "Could not create FileID for predefines?");
Argyrios Kyrtzidis95d912c2013-02-01 16:36:07 +0000488 setPredefinesFileID(FID);
Mike Stump1eb44332009-09-09 15:08:12 +0000489
Chris Lattner53b0dab2007-10-09 22:10:18 +0000490 // Start parsing the predefines.
Chris Lattnere127a0d2010-04-20 20:35:58 +0000491 EnterSourceFile(FID, 0, SourceLocation());
Chris Lattner53b0dab2007-10-09 22:10:18 +0000492}
Chris Lattner97ba77c2007-07-16 06:48:38 +0000493
Daniel Dunbardbd82092010-03-23 05:09:10 +0000494void Preprocessor::EndSourceFile() {
495 // Notify the client that we reached the end of the source file.
496 if (Callbacks)
497 Callbacks->EndOfMainFile();
498}
Reid Spencer5f016e22007-07-11 17:01:13 +0000499
500//===----------------------------------------------------------------------===//
501// Lexer Event Handling.
502//===----------------------------------------------------------------------===//
503
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +0000504/// LookUpIdentifierInfo - Given a tok::raw_identifier token, look up the
505/// identifier information for the token and install it into the token,
506/// updating the token kind accordingly.
507IdentifierInfo *Preprocessor::LookUpIdentifierInfo(Token &Identifier) const {
508 assert(Identifier.getRawIdentifierData() != 0 && "No raw identifier data!");
Mike Stump1eb44332009-09-09 15:08:12 +0000509
Reid Spencer5f016e22007-07-11 17:01:13 +0000510 // Look up this token, see if it is a macro, or if it is a language keyword.
511 IdentifierInfo *II;
Jordan Rosec7629d92013-01-24 20:50:46 +0000512 if (!Identifier.needsCleaning() && !Identifier.hasUCN()) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000513 // No cleaning needed, just use the characters from the lexed buffer.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000514 II = getIdentifierInfo(StringRef(Identifier.getRawIdentifierData(),
Jordan Rosec7629d92013-01-24 20:50:46 +0000515 Identifier.getLength()));
Reid Spencer5f016e22007-07-11 17:01:13 +0000516 } else {
517 // Cleaning needed, alloca a buffer, clean into it, then use the buffer.
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +0000518 SmallString<64> IdentifierBuffer;
Chris Lattner5f9e2722011-07-23 10:55:15 +0000519 StringRef CleanedStr = getSpelling(Identifier, IdentifierBuffer);
Jordan Rosec7629d92013-01-24 20:50:46 +0000520
521 if (Identifier.hasUCN()) {
522 SmallString<64> UCNIdentifierBuffer;
523 expandUCNs(UCNIdentifierBuffer, CleanedStr);
524 II = getIdentifierInfo(UCNIdentifierBuffer);
525 } else {
526 II = getIdentifierInfo(CleanedStr);
527 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000528 }
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +0000529
530 // Update the token info (identifier info and appropriate token kind).
Reid Spencer5f016e22007-07-11 17:01:13 +0000531 Identifier.setIdentifierInfo(II);
Abramo Bagnarac4bf2b92010-12-22 08:23:18 +0000532 Identifier.setKind(II->getTokenID());
533
Reid Spencer5f016e22007-07-11 17:01:13 +0000534 return II;
535}
536
John Wiegley28bbe4b2011-04-28 01:08:34 +0000537void Preprocessor::SetPoisonReason(IdentifierInfo *II, unsigned DiagID) {
538 PoisonReasons[II] = DiagID;
539}
540
541void Preprocessor::PoisonSEHIdentifiers(bool Poison) {
542 assert(Ident__exception_code && Ident__exception_info);
543 assert(Ident___exception_code && Ident___exception_info);
544 Ident__exception_code->setIsPoisoned(Poison);
545 Ident___exception_code->setIsPoisoned(Poison);
546 Ident_GetExceptionCode->setIsPoisoned(Poison);
547 Ident__exception_info->setIsPoisoned(Poison);
548 Ident___exception_info->setIsPoisoned(Poison);
549 Ident_GetExceptionInfo->setIsPoisoned(Poison);
550 Ident__abnormal_termination->setIsPoisoned(Poison);
551 Ident___abnormal_termination->setIsPoisoned(Poison);
552 Ident_AbnormalTermination->setIsPoisoned(Poison);
553}
554
555void Preprocessor::HandlePoisonedIdentifier(Token & Identifier) {
556 assert(Identifier.getIdentifierInfo() &&
557 "Can't handle identifiers without identifier info!");
558 llvm::DenseMap<IdentifierInfo*,unsigned>::const_iterator it =
559 PoisonReasons.find(Identifier.getIdentifierInfo());
560 if(it == PoisonReasons.end())
561 Diag(Identifier, diag::err_pp_used_poisoned_id);
562 else
563 Diag(Identifier,it->second) << Identifier.getIdentifierInfo();
564}
Reid Spencer5f016e22007-07-11 17:01:13 +0000565
566/// HandleIdentifier - This callback is invoked when the lexer reads an
567/// identifier. This callback looks up the identifier in the map and/or
568/// potentially macro expands it or turns it into a named token (like 'for').
Chris Lattner6a170eb2009-01-21 07:43:11 +0000569///
570/// Note that callers of this method are guarded by checking the
571/// IdentifierInfo's 'isHandleIdentifierCase' bit. If this method changes, the
572/// IdentifierInfo methods that compute these properties will need to change to
573/// match.
Eli Friedmand2f93082013-09-19 00:41:32 +0000574bool Preprocessor::HandleIdentifier(Token &Identifier) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000575 assert(Identifier.getIdentifierInfo() &&
576 "Can't handle identifiers without identifier info!");
Mike Stump1eb44332009-09-09 15:08:12 +0000577
Reid Spencer5f016e22007-07-11 17:01:13 +0000578 IdentifierInfo &II = *Identifier.getIdentifierInfo();
579
Douglas Gregoreee242f2011-10-27 09:33:13 +0000580 // If the information about this identifier is out of date, update it from
581 // the external source.
Douglas Gregor193f91b2012-06-29 18:27:59 +0000582 // We have to treat __VA_ARGS__ in a special way, since it gets
583 // serialized with isPoisoned = true, but our preprocessor may have
584 // unpoisoned it if we're defining a C99 macro.
Douglas Gregoreee242f2011-10-27 09:33:13 +0000585 if (II.isOutOfDate()) {
Douglas Gregor193f91b2012-06-29 18:27:59 +0000586 bool CurrentIsPoisoned = false;
587 if (&II == Ident__VA_ARGS__)
588 CurrentIsPoisoned = Ident__VA_ARGS__->isPoisoned();
589
Douglas Gregoreee242f2011-10-27 09:33:13 +0000590 ExternalSource->updateOutOfDateIdentifier(II);
591 Identifier.setKind(II.getTokenID());
Douglas Gregor193f91b2012-06-29 18:27:59 +0000592
593 if (&II == Ident__VA_ARGS__)
594 II.setIsPoisoned(CurrentIsPoisoned);
Douglas Gregoreee242f2011-10-27 09:33:13 +0000595 }
596
Reid Spencer5f016e22007-07-11 17:01:13 +0000597 // If this identifier was poisoned, and if it was not produced from a macro
598 // expansion, emit an error.
Ted Kremenek1a531572008-11-19 22:43:49 +0000599 if (II.isPoisoned() && CurPPLexer) {
John Wiegley28bbe4b2011-04-28 01:08:34 +0000600 HandlePoisonedIdentifier(Identifier);
Reid Spencer5f016e22007-07-11 17:01:13 +0000601 }
Mike Stump1eb44332009-09-09 15:08:12 +0000602
Reid Spencer5f016e22007-07-11 17:01:13 +0000603 // If this is a macro to be expanded, do it.
Argyrios Kyrtzidisc5159782013-02-24 00:05:14 +0000604 if (MacroDirective *MD = getMacroDirective(&II)) {
Argyrios Kyrtzidisc56fff72013-03-26 17:17:01 +0000605 MacroInfo *MI = MD->getMacroInfo();
Abramo Bagnara163ada82012-01-01 22:01:04 +0000606 if (!DisableMacroExpansion) {
Richard Smith1fbf6fb2012-12-12 02:46:14 +0000607 if (!Identifier.isExpandDisabled() && MI->isEnabled()) {
Eli Friedmand2f93082013-09-19 00:41:32 +0000608 // C99 6.10.3p10: If the preprocessing token immediately after the
609 // macro name isn't a '(', this macro should not be expanded.
610 if (!MI->isFunctionLike() || isNextPPTokenLParen())
611 return HandleMacroExpandedIdentifier(Identifier, MD);
Reid Spencer5f016e22007-07-11 17:01:13 +0000612 } else {
613 // C99 6.10.3.4p2 says that a disabled macro may never again be
614 // expanded, even if it's in a context where it could be expanded in the
615 // future.
Chris Lattnerd2177732007-07-20 16:59:19 +0000616 Identifier.setFlag(Token::DisableExpand);
Richard Smith1fbf6fb2012-12-12 02:46:14 +0000617 if (MI->isObjectLike() || isNextPPTokenLParen())
618 Diag(Identifier, diag::pp_disabled_macro_expansion);
Reid Spencer5f016e22007-07-11 17:01:13 +0000619 }
620 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000621 }
622
Richard Smith98d86b92011-10-11 19:57:52 +0000623 // If this identifier is a keyword in C++11, produce a warning. Don't warn if
624 // we're not considering macro expansion, since this identifier might be the
625 // name of a macro.
626 // FIXME: This warning is disabled in cases where it shouldn't be, like
627 // "#define constexpr constexpr", "int constexpr;"
Stephen Hines651f13c2014-04-23 16:59:28 -0700628 if (II.isCXX11CompatKeyword() && !DisableMacroExpansion) {
Richard Smith98d86b92011-10-11 19:57:52 +0000629 Diag(Identifier, diag::warn_cxx11_keyword) << II.getName();
630 // Don't diagnose this keyword again in this translation unit.
631 II.setIsCXX11CompatKeyword(false);
632 }
633
Reid Spencer5f016e22007-07-11 17:01:13 +0000634 // C++ 2.11p2: If this is an alternative representation of a C++ operator,
635 // then we act as if it is the actual operator and not the textual
636 // representation of it.
Fariborz Jahanianafbc6812010-09-03 17:33:04 +0000637 if (II.isCPlusPlusOperatorKeyword())
Reid Spencer5f016e22007-07-11 17:01:13 +0000638 Identifier.setIdentifierInfo(0);
639
Reid Spencer5f016e22007-07-11 17:01:13 +0000640 // If this is an extension token, diagnose its use.
Steve Naroffb4eaf9c2008-09-02 18:50:17 +0000641 // We avoid diagnosing tokens that originate from macro definitions.
Eli Friedman2962f4d2009-04-28 03:59:15 +0000642 // FIXME: This warning is disabled in cases where it shouldn't be,
643 // like "#define TY typeof", "TY(1) x".
644 if (II.isExtensionToken() && !DisableMacroExpansion)
Reid Spencer5f016e22007-07-11 17:01:13 +0000645 Diag(Identifier, diag::ext_token_used);
Douglas Gregorb8db7cd2011-09-07 23:11:54 +0000646
Douglas Gregora5ba7b42013-11-07 22:55:02 +0000647 // If this is the 'import' contextual keyword following an '@', note
Ted Kremenek32ad2ee2012-03-01 22:07:04 +0000648 // that the next token indicates a module name.
Douglas Gregord6aba062012-01-04 06:20:15 +0000649 //
Douglas Gregor1b257af2012-12-11 22:11:52 +0000650 // Note that we do not treat 'import' as a contextual
Ted Kremenek32ad2ee2012-03-01 22:07:04 +0000651 // keyword when we're in a caching lexer, because caching lexers only get
652 // used in contexts where import declarations are disallowed.
Douglas Gregora5ba7b42013-11-07 22:55:02 +0000653 if (LastTokenWasAt && II.isModulesImport() && !InMacroArgs &&
654 !DisableMacroExpansion && getLangOpts().Modules &&
655 CurLexerKind != CLK_CachingLexer) {
Douglas Gregorb8db7cd2011-09-07 23:11:54 +0000656 ModuleImportLoc = Identifier.getLocation();
Douglas Gregorb514c792011-11-30 04:26:53 +0000657 ModuleImportPath.clear();
658 ModuleImportExpectsIdentifier = true;
Douglas Gregorb8db7cd2011-09-07 23:11:54 +0000659 CurLexerKind = CLK_LexAfterModuleImport;
660 }
Eli Friedmand2f93082013-09-19 00:41:32 +0000661 return true;
Douglas Gregor6aa52ec2011-08-26 23:56:07 +0000662}
663
Eli Friedmand2f93082013-09-19 00:41:32 +0000664void Preprocessor::Lex(Token &Result) {
665 // We loop here until a lex function retuns a token; this avoids recursion.
666 bool ReturnedToken;
667 do {
668 switch (CurLexerKind) {
669 case CLK_Lexer:
670 ReturnedToken = CurLexer->Lex(Result);
671 break;
672 case CLK_PTHLexer:
673 ReturnedToken = CurPTHLexer->Lex(Result);
674 break;
675 case CLK_TokenLexer:
676 ReturnedToken = CurTokenLexer->Lex(Result);
677 break;
678 case CLK_CachingLexer:
679 CachingLex(Result);
680 ReturnedToken = true;
681 break;
682 case CLK_LexAfterModuleImport:
683 LexAfterModuleImport(Result);
684 ReturnedToken = true;
685 break;
686 }
687 } while (!ReturnedToken);
Douglas Gregora5ba7b42013-11-07 22:55:02 +0000688
689 LastTokenWasAt = Result.is(tok::at);
Eli Friedmand2f93082013-09-19 00:41:32 +0000690}
691
692
Douglas Gregorc13a34b2012-01-03 19:32:59 +0000693/// \brief Lex a token following the 'import' contextual keyword.
Douglas Gregor5948ae12012-01-03 18:04:46 +0000694///
Douglas Gregorb8db7cd2011-09-07 23:11:54 +0000695void Preprocessor::LexAfterModuleImport(Token &Result) {
696 // Figure out what kind of lexer we actually have.
Douglas Gregord6aba062012-01-04 06:20:15 +0000697 recomputeCurLexerKind();
Douglas Gregorb8db7cd2011-09-07 23:11:54 +0000698
699 // Lex the next token.
700 Lex(Result);
701
Douglas Gregor6aa52ec2011-08-26 23:56:07 +0000702 // The token sequence
703 //
Douglas Gregor5948ae12012-01-03 18:04:46 +0000704 // import identifier (. identifier)*
705 //
Douglas Gregorc13a34b2012-01-03 19:32:59 +0000706 // indicates a module import directive. We already saw the 'import'
707 // contextual keyword, so now we're looking for the identifiers.
Douglas Gregorb514c792011-11-30 04:26:53 +0000708 if (ModuleImportExpectsIdentifier && Result.getKind() == tok::identifier) {
709 // We expected to see an identifier here, and we did; continue handling
710 // identifiers.
711 ModuleImportPath.push_back(std::make_pair(Result.getIdentifierInfo(),
712 Result.getLocation()));
713 ModuleImportExpectsIdentifier = false;
714 CurLexerKind = CLK_LexAfterModuleImport;
Douglas Gregor6aa52ec2011-08-26 23:56:07 +0000715 return;
Douglas Gregorb514c792011-11-30 04:26:53 +0000716 }
Douglas Gregor6aa52ec2011-08-26 23:56:07 +0000717
Douglas Gregorb514c792011-11-30 04:26:53 +0000718 // If we're expecting a '.' or a ';', and we got a '.', then wait until we
719 // see the next identifier.
720 if (!ModuleImportExpectsIdentifier && Result.getKind() == tok::period) {
721 ModuleImportExpectsIdentifier = true;
722 CurLexerKind = CLK_LexAfterModuleImport;
723 return;
724 }
725
726 // If we have a non-empty module path, load the named module.
Daniel Jasper056ec122013-08-05 20:26:17 +0000727 if (!ModuleImportPath.empty() && getLangOpts().Modules) {
Argyrios Kyrtzidisf8afcff2012-09-29 01:06:10 +0000728 Module *Imported = TheModuleLoader.loadModule(ModuleImportLoc,
729 ModuleImportPath,
730 Module::MacrosVisible,
731 /*IsIncludeDirective=*/false);
732 if (Callbacks)
733 Callbacks->moduleImport(ModuleImportLoc, ModuleImportPath, Imported);
734 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000735}
Douglas Gregor2e222532009-07-02 17:08:52 +0000736
Andy Gibbs02a17682012-11-17 19:15:38 +0000737bool Preprocessor::FinishLexStringLiteral(Token &Result, std::string &String,
Andy Gibbs97f84612012-11-17 19:16:52 +0000738 const char *DiagnosticTag,
Andy Gibbs02a17682012-11-17 19:15:38 +0000739 bool AllowMacroExpansion) {
740 // We need at least one string literal.
741 if (Result.isNot(tok::string_literal)) {
Andy Gibbs97f84612012-11-17 19:16:52 +0000742 Diag(Result, diag::err_expected_string_literal)
743 << /*Source='in...'*/0 << DiagnosticTag;
Andy Gibbs02a17682012-11-17 19:15:38 +0000744 return false;
745 }
746
747 // Lex string literal tokens, optionally with macro expansion.
748 SmallVector<Token, 4> StrToks;
749 do {
750 StrToks.push_back(Result);
751
752 if (Result.hasUDSuffix())
753 Diag(Result, diag::err_invalid_string_udl);
754
755 if (AllowMacroExpansion)
756 Lex(Result);
757 else
758 LexUnexpandedToken(Result);
759 } while (Result.is(tok::string_literal));
760
761 // Concatenate and parse the strings.
762 StringLiteralParser Literal(&StrToks[0], StrToks.size(), *this);
763 assert(Literal.isAscii() && "Didn't allow wide strings in");
764
765 if (Literal.hadError)
766 return false;
767
768 if (Literal.Pascal) {
Andy Gibbs97f84612012-11-17 19:16:52 +0000769 Diag(StrToks[0].getLocation(), diag::err_expected_string_literal)
770 << /*Source='in...'*/0 << DiagnosticTag;
Andy Gibbs02a17682012-11-17 19:15:38 +0000771 return false;
772 }
773
774 String = Literal.GetString();
775 return true;
776}
777
Stephen Hines651f13c2014-04-23 16:59:28 -0700778bool Preprocessor::parseSimpleIntegerLiteral(Token &Tok, uint64_t &Value) {
779 assert(Tok.is(tok::numeric_constant));
780 SmallString<8> IntegerBuffer;
781 bool NumberInvalid = false;
782 StringRef Spelling = getSpelling(Tok, IntegerBuffer, &NumberInvalid);
783 if (NumberInvalid)
784 return false;
785 NumericLiteralParser Literal(Spelling, Tok.getLocation(), *this);
786 if (Literal.hadError || !Literal.isIntegerLiteral() || Literal.hasUDSuffix())
787 return false;
788 llvm::APInt APVal(64, 0);
789 if (Literal.GetIntegerValue(APVal))
790 return false;
791 Lex(Tok);
792 Value = APVal.getLimitedValue();
793 return true;
794}
795
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +0000796void Preprocessor::addCommentHandler(CommentHandler *Handler) {
Douglas Gregor2e222532009-07-02 17:08:52 +0000797 assert(Handler && "NULL comment handler");
798 assert(std::find(CommentHandlers.begin(), CommentHandlers.end(), Handler) ==
799 CommentHandlers.end() && "Comment handler already registered");
800 CommentHandlers.push_back(Handler);
801}
802
Dmitri Gribenkoaa0cd852012-06-20 00:34:58 +0000803void Preprocessor::removeCommentHandler(CommentHandler *Handler) {
Douglas Gregor2e222532009-07-02 17:08:52 +0000804 std::vector<CommentHandler *>::iterator Pos
805 = std::find(CommentHandlers.begin(), CommentHandlers.end(), Handler);
806 assert(Pos != CommentHandlers.end() && "Comment handler not registered");
807 CommentHandlers.erase(Pos);
808}
809
Chris Lattner046c2272010-01-18 22:35:47 +0000810bool Preprocessor::HandleComment(Token &result, SourceRange Comment) {
811 bool AnyPendingTokens = false;
Douglas Gregor2e222532009-07-02 17:08:52 +0000812 for (std::vector<CommentHandler *>::iterator H = CommentHandlers.begin(),
813 HEnd = CommentHandlers.end();
Chris Lattner046c2272010-01-18 22:35:47 +0000814 H != HEnd; ++H) {
815 if ((*H)->HandleComment(*this, Comment))
816 AnyPendingTokens = true;
817 }
818 if (!AnyPendingTokens || getCommentRetentionState())
819 return false;
820 Lex(result);
821 return true;
Douglas Gregor2e222532009-07-02 17:08:52 +0000822}
823
Douglas Gregor6aa52ec2011-08-26 23:56:07 +0000824ModuleLoader::~ModuleLoader() { }
825
Douglas Gregor2e222532009-07-02 17:08:52 +0000826CommentHandler::~CommentHandler() { }
Douglas Gregor94dc8f62010-03-19 16:15:56 +0000827
Douglas Gregorf44e8542010-08-24 19:08:16 +0000828CodeCompletionHandler::~CodeCompletionHandler() { }
829
Argyrios Kyrtzidis37ed1272012-12-04 07:27:05 +0000830void Preprocessor::createPreprocessingRecord() {
Douglas Gregor94dc8f62010-03-19 16:15:56 +0000831 if (Record)
832 return;
833
Argyrios Kyrtzidis37ed1272012-12-04 07:27:05 +0000834 Record = new PreprocessingRecord(getSourceManager());
Douglas Gregorb9e1b752010-03-19 17:12:43 +0000835 addPPCallbacks(Record);
Douglas Gregor94dc8f62010-03-19 16:15:56 +0000836}