blob: 1e54ab372516e1891932d361ca586abde9936d11 [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,
Douglas Gregor83297df2011-09-01 23:39:15 +000059 const TargetInfo *target, SourceManager &SM,
Douglas Gregor08142532011-08-26 23:56:07 +000060 HeaderSearch &Headers, ModuleLoader &TheModuleLoader,
David Blaikie687cd952013-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 Blaikief157e902013-01-16 23:18:16 +000066 Identifiers(opts, IILookup), IncrementalProcessing(IncrProcessing),
67 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),
Richard Smith67294e22014-01-31 20:47:44 +000070 CurDirLookup(0), CurLexerKind(CLK_Lexer), CurSubmodule(0),
Richard Smith34f30512013-11-23 04:06:09 +000071 Callbacks(0), 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 if (!DelayInitialization) {
136 assert(Target && "Must provide target information for PP initialization");
137 Initialize(*Target);
138 }
139}
140
141Preprocessor::~Preprocessor() {
142 assert(BacktrackPositions.empty() && "EnableBacktrack/Backtrack imbalance!");
143
144 while (!IncludeMacroStack.empty()) {
145 delete IncludeMacroStack.back().TheLexer;
146 delete IncludeMacroStack.back().TheTokenLexer;
147 IncludeMacroStack.pop_back();
148 }
149
150 // Free any macro definitions.
151 for (MacroInfoChain *I = MIChainHead ; I ; I = I->Next)
152 I->MI.Destroy();
153
154 // Free any cached macro expanders.
155 for (unsigned i = 0, e = NumCachedTokenLexers; i != e; ++i)
156 delete TokenLexerCache[i];
157
Argyrios Kyrtzidisd48b91d2013-04-30 05:05:35 +0000158 for (DeserializedMacroInfoChain *I = DeserialMIChainHead ; I ; I = I->Next)
159 I->MI.Destroy();
160
Argyrios Kyrtzidis3c9aaf12012-06-02 18:08:09 +0000161 // Free any cached MacroArgs.
162 for (MacroArgs *ArgList = MacroArgCache; ArgList; )
163 ArgList = ArgList->deallocate();
164
165 // Release pragma information.
166 delete PragmaHandlers;
167
168 // Delete the scratch buffer info.
169 delete ScratchBuf;
170
171 // Delete the header search info, if we own it.
172 if (OwnsHeaderSearch)
173 delete &HeaderInfo;
174
175 delete Callbacks;
176}
177
178void Preprocessor::Initialize(const TargetInfo &Target) {
179 assert((!this->Target || this->Target == &Target) &&
180 "Invalid override of target information");
181 this->Target = &Target;
Douglas Gregor89929282012-01-30 06:01:29 +0000182
Argyrios Kyrtzidis3c9aaf12012-06-02 18:08:09 +0000183 // Initialize information about built-ins.
184 BuiltinInfo.InitializeTarget(Target);
Douglas Gregor89929282012-01-30 06:01:29 +0000185 HeaderInfo.setTarget(Target);
Douglas Gregor83297df2011-09-01 23:39:15 +0000186}
187
Ted Kremeneka5c2c272009-02-12 03:26:59 +0000188void Preprocessor::setPTHManager(PTHManager* pm) {
189 PTH.reset(pm);
Douglas Gregord2eb58a2009-10-16 18:18:30 +0000190 FileMgr.addStatCache(PTH->createStatCache());
Ted Kremeneka5c2c272009-02-12 03:26:59 +0000191}
192
Chris Lattner146762e2007-07-20 16:59:19 +0000193void Preprocessor::DumpToken(const Token &Tok, bool DumpFlags) const {
Benjamin Kramer89b422c2009-08-23 12:08:50 +0000194 llvm::errs() << tok::getTokenName(Tok.getKind()) << " '"
195 << getSpelling(Tok) << "'";
Mike Stump11289f42009-09-09 15:08:12 +0000196
Chris Lattnerd01e2912006-06-18 16:22:51 +0000197 if (!DumpFlags) return;
Mike Stump11289f42009-09-09 15:08:12 +0000198
Benjamin Kramer89b422c2009-08-23 12:08:50 +0000199 llvm::errs() << "\t";
Chris Lattnerd01e2912006-06-18 16:22:51 +0000200 if (Tok.isAtStartOfLine())
Benjamin Kramer89b422c2009-08-23 12:08:50 +0000201 llvm::errs() << " [StartOfLine]";
Chris Lattnerd01e2912006-06-18 16:22:51 +0000202 if (Tok.hasLeadingSpace())
Benjamin Kramer89b422c2009-08-23 12:08:50 +0000203 llvm::errs() << " [LeadingSpace]";
Chris Lattner6e4bf522006-07-27 06:59:25 +0000204 if (Tok.isExpandDisabled())
Benjamin Kramer89b422c2009-08-23 12:08:50 +0000205 llvm::errs() << " [ExpandDisabled]";
Chris Lattnerd01e2912006-06-18 16:22:51 +0000206 if (Tok.needsCleaning()) {
Chris Lattner50b497e2006-06-18 16:32:35 +0000207 const char *Start = SourceMgr.getCharacterData(Tok.getLocation());
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000208 llvm::errs() << " [UnClean='" << StringRef(Start, Tok.getLength())
Benjamin Kramer89b422c2009-08-23 12:08:50 +0000209 << "']";
Chris Lattnerd01e2912006-06-18 16:22:51 +0000210 }
Mike Stump11289f42009-09-09 15:08:12 +0000211
Benjamin Kramer89b422c2009-08-23 12:08:50 +0000212 llvm::errs() << "\tLoc=<";
Chris Lattner615315f2007-12-09 20:31:55 +0000213 DumpLocation(Tok.getLocation());
Benjamin Kramer89b422c2009-08-23 12:08:50 +0000214 llvm::errs() << ">";
Chris Lattner615315f2007-12-09 20:31:55 +0000215}
216
217void Preprocessor::DumpLocation(SourceLocation Loc) const {
Chris Lattnerf1ca7d32009-01-27 07:57:44 +0000218 Loc.dump(SourceMgr);
Chris Lattnerd01e2912006-06-18 16:22:51 +0000219}
220
221void Preprocessor::DumpMacro(const MacroInfo &MI) const {
Benjamin Kramer89b422c2009-08-23 12:08:50 +0000222 llvm::errs() << "MACRO: ";
Chris Lattnerd01e2912006-06-18 16:22:51 +0000223 for (unsigned i = 0, e = MI.getNumTokens(); i != e; ++i) {
224 DumpToken(MI.getReplacementToken(i));
Benjamin Kramer89b422c2009-08-23 12:08:50 +0000225 llvm::errs() << " ";
Chris Lattnerd01e2912006-06-18 16:22:51 +0000226 }
Benjamin Kramer89b422c2009-08-23 12:08:50 +0000227 llvm::errs() << "\n";
Chris Lattnerd01e2912006-06-18 16:22:51 +0000228}
229
Chris Lattner22eb9722006-06-18 05:43:12 +0000230void Preprocessor::PrintStats() {
Benjamin Kramer89b422c2009-08-23 12:08:50 +0000231 llvm::errs() << "\n*** Preprocessor Stats:\n";
232 llvm::errs() << NumDirectives << " directives found:\n";
233 llvm::errs() << " " << NumDefined << " #define.\n";
234 llvm::errs() << " " << NumUndefined << " #undef.\n";
235 llvm::errs() << " #include/#include_next/#import:\n";
236 llvm::errs() << " " << NumEnteredSourceFiles << " source files entered.\n";
237 llvm::errs() << " " << MaxIncludeStackDepth << " max include stack depth\n";
238 llvm::errs() << " " << NumIf << " #if/#ifndef/#ifdef.\n";
239 llvm::errs() << " " << NumElse << " #else/#elif.\n";
240 llvm::errs() << " " << NumEndif << " #endif.\n";
241 llvm::errs() << " " << NumPragma << " #pragma.\n";
242 llvm::errs() << NumSkipped << " #if/#ifndef#ifdef regions skipped\n";
Chris Lattner22eb9722006-06-18 05:43:12 +0000243
Benjamin Kramer89b422c2009-08-23 12:08:50 +0000244 llvm::errs() << NumMacroExpanded << "/" << NumFnMacroExpanded << "/"
Ted Kremeneka0a3e9b2008-01-14 16:44:48 +0000245 << NumBuiltinMacroExpanded << " obj/fn/builtin macros expanded, "
246 << NumFastMacroExpanded << " on the fast path.\n";
Benjamin Kramer89b422c2009-08-23 12:08:50 +0000247 llvm::errs() << (NumFastTokenPaste+NumTokenPaste)
Ted Kremeneka0a3e9b2008-01-14 16:44:48 +0000248 << " token paste (##) operations performed, "
249 << NumFastTokenPaste << " on the fast path.\n";
Alexander Kornienko199cd942012-08-13 10:46:42 +0000250
251 llvm::errs() << "\nPreprocessor Memory: " << getTotalMemory() << "B total";
252
253 llvm::errs() << "\n BumpPtr: " << BP.getTotalMemory();
254 llvm::errs() << "\n Macro Expanded Tokens: "
255 << llvm::capacity_in_bytes(MacroExpandedTokens);
256 llvm::errs() << "\n Predefines Buffer: " << Predefines.capacity();
257 llvm::errs() << "\n Macros: " << llvm::capacity_in_bytes(Macros);
258 llvm::errs() << "\n #pragma push_macro Info: "
259 << llvm::capacity_in_bytes(PragmaPushMacroInfo);
260 llvm::errs() << "\n Poison Reasons: "
261 << llvm::capacity_in_bytes(PoisonReasons);
262 llvm::errs() << "\n Comment Handlers: "
263 << llvm::capacity_in_bytes(CommentHandlers) << "\n";
Chris Lattner22eb9722006-06-18 05:43:12 +0000264}
265
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +0000266Preprocessor::macro_iterator
267Preprocessor::macro_begin(bool IncludeExternalMacros) const {
268 if (IncludeExternalMacros && ExternalSource &&
Douglas Gregor9882a5a2010-01-04 19:18:44 +0000269 !ReadMacrosFromExternalSource) {
270 ReadMacrosFromExternalSource = true;
271 ExternalSource->ReadDefinedMacros();
272 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +0000273
274 return Macros.begin();
Douglas Gregor9882a5a2010-01-04 19:18:44 +0000275}
276
Argyrios Kyrtzidise379ee32011-06-29 22:20:04 +0000277size_t Preprocessor::getTotalMemory() const {
Ted Kremenek182543a2011-07-26 21:17:24 +0000278 return BP.getTotalMemory()
Ted Kremenek8b77fe72011-07-27 18:41:23 +0000279 + llvm::capacity_in_bytes(MacroExpandedTokens)
Ted Kremenek182543a2011-07-26 21:17:24 +0000280 + Predefines.capacity() /* Predefines buffer. */
Ted Kremenek8b77fe72011-07-27 18:41:23 +0000281 + llvm::capacity_in_bytes(Macros)
282 + llvm::capacity_in_bytes(PragmaPushMacroInfo)
283 + llvm::capacity_in_bytes(PoisonReasons)
284 + llvm::capacity_in_bytes(CommentHandlers);
Argyrios Kyrtzidise379ee32011-06-29 22:20:04 +0000285}
286
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +0000287Preprocessor::macro_iterator
288Preprocessor::macro_end(bool IncludeExternalMacros) const {
289 if (IncludeExternalMacros && ExternalSource &&
Douglas Gregor9882a5a2010-01-04 19:18:44 +0000290 !ReadMacrosFromExternalSource) {
291 ReadMacrosFromExternalSource = true;
292 ExternalSource->ReadDefinedMacros();
293 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +0000294
295 return Macros.end();
Douglas Gregor9882a5a2010-01-04 19:18:44 +0000296}
297
Dmitri Gribenko6743e042012-09-29 11:40:46 +0000298/// \brief Compares macro tokens with a specified token value sequence.
299static bool MacroDefinitionEquals(const MacroInfo *MI,
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000300 ArrayRef<TokenValue> Tokens) {
Dmitri Gribenko6743e042012-09-29 11:40:46 +0000301 return Tokens.size() == MI->getNumTokens() &&
302 std::equal(Tokens.begin(), Tokens.end(), MI->tokens_begin());
303}
304
305StringRef Preprocessor::getLastMacroWithSpelling(
306 SourceLocation Loc,
307 ArrayRef<TokenValue> Tokens) const {
308 SourceLocation BestLocation;
309 StringRef BestSpelling;
310 for (Preprocessor::macro_iterator I = macro_begin(), E = macro_end();
311 I != E; ++I) {
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +0000312 if (!I->second->getMacroInfo()->isObjectLike())
Dmitri Gribenko6743e042012-09-29 11:40:46 +0000313 continue;
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +0000314 const MacroDirective::DefInfo
315 Def = I->second->findDirectiveAtLoc(Loc, SourceMgr);
316 if (!Def)
Dmitri Gribenko6743e042012-09-29 11:40:46 +0000317 continue;
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +0000318 if (!MacroDefinitionEquals(Def.getMacroInfo(), Tokens))
Dmitri Gribenko6743e042012-09-29 11:40:46 +0000319 continue;
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +0000320 SourceLocation Location = Def.getLocation();
Dmitri Gribenko6743e042012-09-29 11:40:46 +0000321 // Choose the macro defined latest.
322 if (BestLocation.isInvalid() ||
323 (Location.isValid() &&
324 SourceMgr.isBeforeInTranslationUnit(BestLocation, Location))) {
325 BestLocation = Location;
326 BestSpelling = I->first->getName();
327 }
328 }
329 return BestSpelling;
330}
331
Douglas Gregor8d76cca2012-01-04 06:20:15 +0000332void Preprocessor::recomputeCurLexerKind() {
333 if (CurLexer)
334 CurLexerKind = CLK_Lexer;
335 else if (CurPTHLexer)
336 CurLexerKind = CLK_PTHLexer;
337 else if (CurTokenLexer)
338 CurLexerKind = CLK_TokenLexer;
339 else
340 CurLexerKind = CLK_CachingLexer;
341}
342
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +0000343bool Preprocessor::SetCodeCompletionPoint(const FileEntry *File,
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +0000344 unsigned CompleteLine,
345 unsigned CompleteColumn) {
346 assert(File);
347 assert(CompleteLine && CompleteColumn && "Starts from 1:1");
348 assert(!CodeCompletionFile && "Already set");
349
Douglas Gregor53ad6b92009-12-02 06:49:09 +0000350 using llvm::MemoryBuffer;
351
Douglas Gregor53ad6b92009-12-02 06:49:09 +0000352 // Load the actual file's contents.
Douglas Gregor26266da2010-03-16 19:49:24 +0000353 bool Invalid = false;
354 const MemoryBuffer *Buffer = SourceMgr.getMemoryBufferForFile(File, &Invalid);
355 if (Invalid)
Douglas Gregor53ad6b92009-12-02 06:49:09 +0000356 return true;
357
358 // Find the byte position of the truncation point.
359 const char *Position = Buffer->getBufferStart();
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +0000360 for (unsigned Line = 1; Line < CompleteLine; ++Line) {
Douglas Gregor53ad6b92009-12-02 06:49:09 +0000361 for (; *Position; ++Position) {
362 if (*Position != '\r' && *Position != '\n')
363 continue;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +0000364
Douglas Gregor53ad6b92009-12-02 06:49:09 +0000365 // Eat \r\n or \n\r as a single line.
366 if ((Position[1] == '\r' || Position[1] == '\n') &&
367 Position[0] != Position[1])
368 ++Position;
369 ++Position;
370 break;
371 }
372 }
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +0000373
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +0000374 Position += CompleteColumn - 1;
Kovarththanan Rajaratnamba2c6522010-03-13 10:17:05 +0000375
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +0000376 // Insert '\0' at the code-completion point.
Douglas Gregor9291ab62009-12-08 21:45:46 +0000377 if (Position < Buffer->getBufferEnd()) {
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +0000378 CodeCompletionFile = File;
379 CodeCompletionOffset = Position - Buffer->getBufferStart();
380
381 MemoryBuffer *NewBuffer =
382 MemoryBuffer::getNewUninitMemBuffer(Buffer->getBufferSize() + 1,
383 Buffer->getBufferIdentifier());
Benjamin Kramer60053cf2011-09-04 20:26:28 +0000384 char *NewBuf = const_cast<char*>(NewBuffer->getBufferStart());
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +0000385 char *NewPos = std::copy(Buffer->getBufferStart(), Position, NewBuf);
386 *NewPos = '\0';
387 std::copy(Position, Buffer->getBufferEnd(), NewPos+1);
388 SourceMgr.overrideFileContents(File, NewBuffer);
Douglas Gregor53ad6b92009-12-02 06:49:09 +0000389 }
390
391 return false;
392}
393
Douglas Gregor11583702010-08-25 17:04:25 +0000394void Preprocessor::CodeCompleteNaturalLanguage() {
Douglas Gregor11583702010-08-25 17:04:25 +0000395 if (CodeComplete)
396 CodeComplete->CodeCompleteNaturalLanguage();
Argyrios Kyrtzidis5cec2ae2011-09-04 03:32:15 +0000397 setCodeCompletionReached();
Douglas Gregor11583702010-08-25 17:04:25 +0000398}
399
Benjamin Kramera197fb62010-02-27 17:05:45 +0000400/// getSpelling - This method is used to get the spelling of a token into a
401/// SmallVector. Note that the returned StringRef may not point to the
402/// supplied buffer if a copy can be avoided.
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000403StringRef Preprocessor::getSpelling(const Token &Tok,
404 SmallVectorImpl<char> &Buffer,
Douglas Gregor7bda4b82010-03-16 05:20:39 +0000405 bool *Invalid) const {
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +0000406 // NOTE: this has to be checked *before* testing for an IdentifierInfo.
Jordan Rose7f43ddd2013-01-24 20:50:46 +0000407 if (Tok.isNot(tok::raw_identifier) && !Tok.hasUCN()) {
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +0000408 // Try the fast path.
409 if (const IdentifierInfo *II = Tok.getIdentifierInfo())
410 return II->getName();
411 }
Benjamin Kramera197fb62010-02-27 17:05:45 +0000412
413 // Resize the buffer if we need to copy into it.
414 if (Tok.needsCleaning())
415 Buffer.resize(Tok.getLength());
416
417 const char *Ptr = Buffer.data();
Douglas Gregor7bda4b82010-03-16 05:20:39 +0000418 unsigned Len = getSpelling(Tok, Ptr, Invalid);
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000419 return StringRef(Ptr, Len);
Benjamin Kramera197fb62010-02-27 17:05:45 +0000420}
421
Chris Lattnerb94ec7b2006-07-14 06:54:10 +0000422/// CreateString - Plop the specified string into a scratch buffer and return a
423/// location for it. If specified, the source location provides a source
424/// location for the token.
Dmitri Gribenkob8e9e752012-09-24 21:07:17 +0000425void Preprocessor::CreateString(StringRef Str, Token &Tok,
Abramo Bagnarae398e602011-10-03 18:39:03 +0000426 SourceLocation ExpansionLocStart,
427 SourceLocation ExpansionLocEnd) {
Dmitri Gribenkob8e9e752012-09-24 21:07:17 +0000428 Tok.setLength(Str.size());
Mike Stump11289f42009-09-09 15:08:12 +0000429
Chris Lattner5a7971e2009-01-26 19:29:26 +0000430 const char *DestPtr;
Dmitri Gribenkob8e9e752012-09-24 21:07:17 +0000431 SourceLocation Loc = ScratchBuf->getToken(Str.data(), Str.size(), DestPtr);
Mike Stump11289f42009-09-09 15:08:12 +0000432
Abramo Bagnarae398e602011-10-03 18:39:03 +0000433 if (ExpansionLocStart.isValid())
434 Loc = SourceMgr.createExpansionLoc(Loc, ExpansionLocStart,
Dmitri Gribenkob8e9e752012-09-24 21:07:17 +0000435 ExpansionLocEnd, Str.size());
Chris Lattner5a7971e2009-01-26 19:29:26 +0000436 Tok.setLocation(Loc);
Mike Stump11289f42009-09-09 15:08:12 +0000437
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +0000438 // If this is a raw identifier or a literal token, set the pointer data.
439 if (Tok.is(tok::raw_identifier))
440 Tok.setRawIdentifierData(DestPtr);
441 else if (Tok.isLiteral())
Chris Lattner5a7971e2009-01-26 19:29:26 +0000442 Tok.setLiteralData(DestPtr);
Chris Lattnerb94ec7b2006-07-14 06:54:10 +0000443}
444
Douglas Gregor2b82c2a2011-12-02 01:47:07 +0000445Module *Preprocessor::getCurrentModule() {
David Blaikiebbafb8a2012-03-11 07:00:24 +0000446 if (getLangOpts().CurrentModule.empty())
Douglas Gregor2b82c2a2011-12-02 01:47:07 +0000447 return 0;
448
David Blaikiebbafb8a2012-03-11 07:00:24 +0000449 return getHeaderSearchInfo().lookupModule(getLangOpts().CurrentModule);
Douglas Gregor2b82c2a2011-12-02 01:47:07 +0000450}
Chris Lattner8a7003c2007-07-16 06:48:38 +0000451
Chris Lattner1f1b0db2007-10-09 22:10:18 +0000452//===----------------------------------------------------------------------===//
453// Preprocessor Initialization Methods
454//===----------------------------------------------------------------------===//
455
Chris Lattner1f1b0db2007-10-09 22:10:18 +0000456
457/// EnterMainSourceFile - Enter the specified FileID as the main source file,
Nate Begemanf7c3ff62008-01-07 04:01:26 +0000458/// which implicitly adds the builtin defines etc.
Chris Lattnerfb24a3a2010-04-20 20:35:58 +0000459void Preprocessor::EnterMainSourceFile() {
Chris Lattner9ef847b2009-02-13 19:33:24 +0000460 // We do not allow the preprocessor to reenter the main file. Doing so will
461 // cause FileID's to accumulate information from both runs (e.g. #line
462 // information) and predefined macros aren't guaranteed to be set properly.
463 assert(NumEnteredSourceFiles == 0 && "Cannot reenter the main file!");
Chris Lattnerd32480d2009-01-17 06:22:33 +0000464 FileID MainFileID = SourceMgr.getMainFileID();
Mike Stump11289f42009-09-09 15:08:12 +0000465
Argyrios Kyrtzidis9afd4492012-01-05 21:36:25 +0000466 // If MainFileID is loaded it means we loaded an AST file, no need to enter
467 // a main file.
468 if (!SourceMgr.isLoadedFileID(MainFileID)) {
469 // Enter the main file source buffer.
470 EnterSourceFile(MainFileID, 0, SourceLocation());
Douglas Gregor3f4bea02010-07-26 21:36:20 +0000471
Argyrios Kyrtzidis9afd4492012-01-05 21:36:25 +0000472 // If we've been asked to skip bytes in the main file (e.g., as part of a
473 // precompiled preamble), do so now.
474 if (SkipMainFilePreamble.first > 0)
475 CurLexer->SkipBytes(SkipMainFilePreamble.first,
476 SkipMainFilePreamble.second);
477
478 // Tell the header info that the main file was entered. If the file is later
479 // #imported, it won't be re-entered.
480 if (const FileEntry *FE = SourceMgr.getFileEntryForID(MainFileID))
481 HeaderInfo.IncrementIncludeCount(FE);
482 }
Mike Stump11289f42009-09-09 15:08:12 +0000483
Benjamin Kramerd77adb52009-12-31 15:33:09 +0000484 // Preprocess Predefines to populate the initial preprocessor state.
Mike Stump11289f42009-09-09 15:08:12 +0000485 llvm::MemoryBuffer *SB =
Chris Lattner58c79342010-04-05 22:42:27 +0000486 llvm::MemoryBuffer::getMemBufferCopy(Predefines, "<built-in>");
Douglas Gregor33551892010-08-26 14:07:34 +0000487 assert(SB && "Cannot create predefined source buffer");
Meador Ingecdc00572012-06-19 18:17:30 +0000488 FileID FID = SourceMgr.createFileIDForMemBuffer(SB);
Chris Lattnerd32480d2009-01-17 06:22:33 +0000489 assert(!FID.isInvalid() && "Could not create FileID for predefines?");
Argyrios Kyrtzidis22c22f52013-02-01 16:36:07 +0000490 setPredefinesFileID(FID);
Mike Stump11289f42009-09-09 15:08:12 +0000491
Chris Lattner1f1b0db2007-10-09 22:10:18 +0000492 // Start parsing the predefines.
Chris Lattnerfb24a3a2010-04-20 20:35:58 +0000493 EnterSourceFile(FID, 0, SourceLocation());
Chris Lattner1f1b0db2007-10-09 22:10:18 +0000494}
Chris Lattner8a7003c2007-07-16 06:48:38 +0000495
Daniel Dunbarcb9eaf52010-03-23 05:09:10 +0000496void Preprocessor::EndSourceFile() {
497 // Notify the client that we reached the end of the source file.
498 if (Callbacks)
499 Callbacks->EndOfMainFile();
500}
Chris Lattner677757a2006-06-28 05:26:32 +0000501
502//===----------------------------------------------------------------------===//
503// Lexer Event Handling.
504//===----------------------------------------------------------------------===//
505
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +0000506/// LookUpIdentifierInfo - Given a tok::raw_identifier token, look up the
507/// identifier information for the token and install it into the token,
508/// updating the token kind accordingly.
509IdentifierInfo *Preprocessor::LookUpIdentifierInfo(Token &Identifier) const {
510 assert(Identifier.getRawIdentifierData() != 0 && "No raw identifier data!");
Mike Stump11289f42009-09-09 15:08:12 +0000511
Chris Lattnercefc7682006-07-08 08:28:12 +0000512 // Look up this token, see if it is a macro, or if it is a language keyword.
513 IdentifierInfo *II;
Jordan Rose7f43ddd2013-01-24 20:50:46 +0000514 if (!Identifier.needsCleaning() && !Identifier.hasUCN()) {
Chris Lattnercefc7682006-07-08 08:28:12 +0000515 // No cleaning needed, just use the characters from the lexed buffer.
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000516 II = getIdentifierInfo(StringRef(Identifier.getRawIdentifierData(),
Jordan Rose7f43ddd2013-01-24 20:50:46 +0000517 Identifier.getLength()));
Chris Lattnercefc7682006-07-08 08:28:12 +0000518 } else {
519 // Cleaning needed, alloca a buffer, clean into it, then use the buffer.
Dylan Noblesmith2c1dd272012-02-05 02:13:05 +0000520 SmallString<64> IdentifierBuffer;
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000521 StringRef CleanedStr = getSpelling(Identifier, IdentifierBuffer);
Jordan Rose7f43ddd2013-01-24 20:50:46 +0000522
523 if (Identifier.hasUCN()) {
524 SmallString<64> UCNIdentifierBuffer;
525 expandUCNs(UCNIdentifierBuffer, CleanedStr);
526 II = getIdentifierInfo(UCNIdentifierBuffer);
527 } else {
528 II = getIdentifierInfo(CleanedStr);
529 }
Chris Lattnercefc7682006-07-08 08:28:12 +0000530 }
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +0000531
532 // Update the token info (identifier info and appropriate token kind).
Chris Lattner8c204872006-10-14 05:19:21 +0000533 Identifier.setIdentifierInfo(II);
Abramo Bagnaraea4f7c72010-12-22 08:23:18 +0000534 Identifier.setKind(II->getTokenID());
535
Chris Lattnercefc7682006-07-08 08:28:12 +0000536 return II;
537}
538
John Wiegley1c0675e2011-04-28 01:08:34 +0000539void Preprocessor::SetPoisonReason(IdentifierInfo *II, unsigned DiagID) {
540 PoisonReasons[II] = DiagID;
541}
542
543void Preprocessor::PoisonSEHIdentifiers(bool Poison) {
544 assert(Ident__exception_code && Ident__exception_info);
545 assert(Ident___exception_code && Ident___exception_info);
546 Ident__exception_code->setIsPoisoned(Poison);
547 Ident___exception_code->setIsPoisoned(Poison);
548 Ident_GetExceptionCode->setIsPoisoned(Poison);
549 Ident__exception_info->setIsPoisoned(Poison);
550 Ident___exception_info->setIsPoisoned(Poison);
551 Ident_GetExceptionInfo->setIsPoisoned(Poison);
552 Ident__abnormal_termination->setIsPoisoned(Poison);
553 Ident___abnormal_termination->setIsPoisoned(Poison);
554 Ident_AbnormalTermination->setIsPoisoned(Poison);
555}
556
557void Preprocessor::HandlePoisonedIdentifier(Token & Identifier) {
558 assert(Identifier.getIdentifierInfo() &&
559 "Can't handle identifiers without identifier info!");
560 llvm::DenseMap<IdentifierInfo*,unsigned>::const_iterator it =
561 PoisonReasons.find(Identifier.getIdentifierInfo());
562 if(it == PoisonReasons.end())
563 Diag(Identifier, diag::err_pp_used_poisoned_id);
564 else
565 Diag(Identifier,it->second) << Identifier.getIdentifierInfo();
566}
Chris Lattnercefc7682006-07-08 08:28:12 +0000567
Chris Lattner677757a2006-06-28 05:26:32 +0000568/// HandleIdentifier - This callback is invoked when the lexer reads an
569/// identifier. This callback looks up the identifier in the map and/or
570/// potentially macro expands it or turns it into a named token (like 'for').
Chris Lattnerad89ec02009-01-21 07:43:11 +0000571///
572/// Note that callers of this method are guarded by checking the
573/// IdentifierInfo's 'isHandleIdentifierCase' bit. If this method changes, the
574/// IdentifierInfo methods that compute these properties will need to change to
575/// match.
Eli Friedman0834a4b2013-09-19 00:41:32 +0000576bool Preprocessor::HandleIdentifier(Token &Identifier) {
Chris Lattner0f1f5052006-07-20 04:16:23 +0000577 assert(Identifier.getIdentifierInfo() &&
578 "Can't handle identifiers without identifier info!");
Mike Stump11289f42009-09-09 15:08:12 +0000579
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000580 IdentifierInfo &II = *Identifier.getIdentifierInfo();
Chris Lattner677757a2006-06-28 05:26:32 +0000581
Douglas Gregor935bc7a22011-10-27 09:33:13 +0000582 // If the information about this identifier is out of date, update it from
583 // the external source.
Douglas Gregor3f568c12012-06-29 18:27:59 +0000584 // We have to treat __VA_ARGS__ in a special way, since it gets
585 // serialized with isPoisoned = true, but our preprocessor may have
586 // unpoisoned it if we're defining a C99 macro.
Douglas Gregor935bc7a22011-10-27 09:33:13 +0000587 if (II.isOutOfDate()) {
Douglas Gregor3f568c12012-06-29 18:27:59 +0000588 bool CurrentIsPoisoned = false;
589 if (&II == Ident__VA_ARGS__)
590 CurrentIsPoisoned = Ident__VA_ARGS__->isPoisoned();
591
Douglas Gregor935bc7a22011-10-27 09:33:13 +0000592 ExternalSource->updateOutOfDateIdentifier(II);
593 Identifier.setKind(II.getTokenID());
Douglas Gregor3f568c12012-06-29 18:27:59 +0000594
595 if (&II == Ident__VA_ARGS__)
596 II.setIsPoisoned(CurrentIsPoisoned);
Douglas Gregor935bc7a22011-10-27 09:33:13 +0000597 }
598
Chris Lattner677757a2006-06-28 05:26:32 +0000599 // If this identifier was poisoned, and if it was not produced from a macro
600 // expansion, emit an error.
Ted Kremeneka2c3c8d2008-11-19 22:43:49 +0000601 if (II.isPoisoned() && CurPPLexer) {
John Wiegley1c0675e2011-04-28 01:08:34 +0000602 HandlePoisonedIdentifier(Identifier);
Chris Lattner8ff71992006-07-06 05:17:39 +0000603 }
Mike Stump11289f42009-09-09 15:08:12 +0000604
Chris Lattner78186052006-07-09 00:45:31 +0000605 // If this is a macro to be expanded, do it.
Argyrios Kyrtzidisfead64b2013-02-24 00:05:14 +0000606 if (MacroDirective *MD = getMacroDirective(&II)) {
Argyrios Kyrtzidisb6210df2013-03-26 17:17:01 +0000607 MacroInfo *MI = MD->getMacroInfo();
Abramo Bagnara123bec82012-01-01 22:01:04 +0000608 if (!DisableMacroExpansion) {
Richard Smith181879c2012-12-12 02:46:14 +0000609 if (!Identifier.isExpandDisabled() && MI->isEnabled()) {
Eli Friedman0834a4b2013-09-19 00:41:32 +0000610 // C99 6.10.3p10: If the preprocessing token immediately after the
611 // macro name isn't a '(', this macro should not be expanded.
612 if (!MI->isFunctionLike() || isNextPPTokenLParen())
613 return HandleMacroExpandedIdentifier(Identifier, MD);
Chris Lattner6e4bf522006-07-27 06:59:25 +0000614 } else {
615 // C99 6.10.3.4p2 says that a disabled macro may never again be
616 // expanded, even if it's in a context where it could be expanded in the
617 // future.
Chris Lattner146762e2007-07-20 16:59:19 +0000618 Identifier.setFlag(Token::DisableExpand);
Richard Smith181879c2012-12-12 02:46:14 +0000619 if (MI->isObjectLike() || isNextPPTokenLParen())
620 Diag(Identifier, diag::pp_disabled_macro_expansion);
Chris Lattner6e4bf522006-07-27 06:59:25 +0000621 }
622 }
Chris Lattner063400e2006-10-14 19:54:15 +0000623 }
Chris Lattner677757a2006-06-28 05:26:32 +0000624
Richard Smith4dd85d62011-10-11 19:57:52 +0000625 // If this identifier is a keyword in C++11, produce a warning. Don't warn if
626 // we're not considering macro expansion, since this identifier might be the
627 // name of a macro.
628 // FIXME: This warning is disabled in cases where it shouldn't be, like
629 // "#define constexpr constexpr", "int constexpr;"
630 if (II.isCXX11CompatKeyword() & !DisableMacroExpansion) {
631 Diag(Identifier, diag::warn_cxx11_keyword) << II.getName();
632 // Don't diagnose this keyword again in this translation unit.
633 II.setIsCXX11CompatKeyword(false);
634 }
635
Chris Lattner5b9f4892006-11-21 17:23:33 +0000636 // C++ 2.11p2: If this is an alternative representation of a C++ operator,
637 // then we act as if it is the actual operator and not the textual
638 // representation of it.
Fariborz Jahanian9e42a952010-09-03 17:33:04 +0000639 if (II.isCPlusPlusOperatorKeyword())
Chris Lattner5b9f4892006-11-21 17:23:33 +0000640 Identifier.setIdentifierInfo(0);
641
Chris Lattner677757a2006-06-28 05:26:32 +0000642 // If this is an extension token, diagnose its use.
Steve Naroffc84e8b72008-09-02 18:50:17 +0000643 // We avoid diagnosing tokens that originate from macro definitions.
Eli Friedman6bba2ad2009-04-28 03:59:15 +0000644 // FIXME: This warning is disabled in cases where it shouldn't be,
645 // like "#define TY typeof", "TY(1) x".
646 if (II.isExtensionToken() && !DisableMacroExpansion)
Chris Lattner53621a52007-06-13 20:44:40 +0000647 Diag(Identifier, diag::ext_token_used);
Douglas Gregoraf5c4842011-09-07 23:11:54 +0000648
Douglas Gregor594b8c92013-11-07 22:55:02 +0000649 // If this is the 'import' contextual keyword following an '@', note
Ted Kremenekc1e4dd02012-03-01 22:07:04 +0000650 // that the next token indicates a module name.
Douglas Gregor8d76cca2012-01-04 06:20:15 +0000651 //
Douglas Gregorc50d4922012-12-11 22:11:52 +0000652 // Note that we do not treat 'import' as a contextual
Ted Kremenekc1e4dd02012-03-01 22:07:04 +0000653 // keyword when we're in a caching lexer, because caching lexers only get
654 // used in contexts where import declarations are disallowed.
Douglas Gregor594b8c92013-11-07 22:55:02 +0000655 if (LastTokenWasAt && II.isModulesImport() && !InMacroArgs &&
656 !DisableMacroExpansion && getLangOpts().Modules &&
657 CurLexerKind != CLK_CachingLexer) {
Douglas Gregoraf5c4842011-09-07 23:11:54 +0000658 ModuleImportLoc = Identifier.getLocation();
Douglas Gregor1805b8a2011-11-30 04:26:53 +0000659 ModuleImportPath.clear();
660 ModuleImportExpectsIdentifier = true;
Douglas Gregoraf5c4842011-09-07 23:11:54 +0000661 CurLexerKind = CLK_LexAfterModuleImport;
662 }
Eli Friedman0834a4b2013-09-19 00:41:32 +0000663 return true;
Douglas Gregor08142532011-08-26 23:56:07 +0000664}
665
Eli Friedman0834a4b2013-09-19 00:41:32 +0000666void Preprocessor::Lex(Token &Result) {
667 // We loop here until a lex function retuns a token; this avoids recursion.
668 bool ReturnedToken;
669 do {
670 switch (CurLexerKind) {
671 case CLK_Lexer:
672 ReturnedToken = CurLexer->Lex(Result);
673 break;
674 case CLK_PTHLexer:
675 ReturnedToken = CurPTHLexer->Lex(Result);
676 break;
677 case CLK_TokenLexer:
678 ReturnedToken = CurTokenLexer->Lex(Result);
679 break;
680 case CLK_CachingLexer:
681 CachingLex(Result);
682 ReturnedToken = true;
683 break;
684 case CLK_LexAfterModuleImport:
685 LexAfterModuleImport(Result);
686 ReturnedToken = true;
687 break;
688 }
689 } while (!ReturnedToken);
Douglas Gregor594b8c92013-11-07 22:55:02 +0000690
691 LastTokenWasAt = Result.is(tok::at);
Eli Friedman0834a4b2013-09-19 00:41:32 +0000692}
693
694
Douglas Gregorda82e702012-01-03 19:32:59 +0000695/// \brief Lex a token following the 'import' contextual keyword.
Douglas Gregor22d09742012-01-03 18:04:46 +0000696///
Douglas Gregoraf5c4842011-09-07 23:11:54 +0000697void Preprocessor::LexAfterModuleImport(Token &Result) {
698 // Figure out what kind of lexer we actually have.
Douglas Gregor8d76cca2012-01-04 06:20:15 +0000699 recomputeCurLexerKind();
Douglas Gregoraf5c4842011-09-07 23:11:54 +0000700
701 // Lex the next token.
702 Lex(Result);
703
Douglas Gregor08142532011-08-26 23:56:07 +0000704 // The token sequence
705 //
Douglas Gregor22d09742012-01-03 18:04:46 +0000706 // import identifier (. identifier)*
707 //
Douglas Gregorda82e702012-01-03 19:32:59 +0000708 // indicates a module import directive. We already saw the 'import'
709 // contextual keyword, so now we're looking for the identifiers.
Douglas Gregor1805b8a2011-11-30 04:26:53 +0000710 if (ModuleImportExpectsIdentifier && Result.getKind() == tok::identifier) {
711 // We expected to see an identifier here, and we did; continue handling
712 // identifiers.
713 ModuleImportPath.push_back(std::make_pair(Result.getIdentifierInfo(),
714 Result.getLocation()));
715 ModuleImportExpectsIdentifier = false;
716 CurLexerKind = CLK_LexAfterModuleImport;
Douglas Gregor08142532011-08-26 23:56:07 +0000717 return;
Douglas Gregor1805b8a2011-11-30 04:26:53 +0000718 }
Douglas Gregor08142532011-08-26 23:56:07 +0000719
Douglas Gregor1805b8a2011-11-30 04:26:53 +0000720 // If we're expecting a '.' or a ';', and we got a '.', then wait until we
721 // see the next identifier.
722 if (!ModuleImportExpectsIdentifier && Result.getKind() == tok::period) {
723 ModuleImportExpectsIdentifier = true;
724 CurLexerKind = CLK_LexAfterModuleImport;
725 return;
726 }
727
728 // If we have a non-empty module path, load the named module.
Daniel Jasper07e6c402013-08-05 20:26:17 +0000729 if (!ModuleImportPath.empty() && getLangOpts().Modules) {
Argyrios Kyrtzidis19d78b72012-09-29 01:06:10 +0000730 Module *Imported = TheModuleLoader.loadModule(ModuleImportLoc,
731 ModuleImportPath,
732 Module::MacrosVisible,
733 /*IsIncludeDirective=*/false);
734 if (Callbacks)
735 Callbacks->moduleImport(ModuleImportLoc, ModuleImportPath, Imported);
736 }
Chris Lattner677757a2006-06-28 05:26:32 +0000737}
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000738
Andy Gibbs58905d22012-11-17 19:15:38 +0000739bool Preprocessor::FinishLexStringLiteral(Token &Result, std::string &String,
Andy Gibbsa8df57a2012-11-17 19:16:52 +0000740 const char *DiagnosticTag,
Andy Gibbs58905d22012-11-17 19:15:38 +0000741 bool AllowMacroExpansion) {
742 // We need at least one string literal.
743 if (Result.isNot(tok::string_literal)) {
Andy Gibbsa8df57a2012-11-17 19:16:52 +0000744 Diag(Result, diag::err_expected_string_literal)
745 << /*Source='in...'*/0 << DiagnosticTag;
Andy Gibbs58905d22012-11-17 19:15:38 +0000746 return false;
747 }
748
749 // Lex string literal tokens, optionally with macro expansion.
750 SmallVector<Token, 4> StrToks;
751 do {
752 StrToks.push_back(Result);
753
754 if (Result.hasUDSuffix())
755 Diag(Result, diag::err_invalid_string_udl);
756
757 if (AllowMacroExpansion)
758 Lex(Result);
759 else
760 LexUnexpandedToken(Result);
761 } while (Result.is(tok::string_literal));
762
763 // Concatenate and parse the strings.
764 StringLiteralParser Literal(&StrToks[0], StrToks.size(), *this);
765 assert(Literal.isAscii() && "Didn't allow wide strings in");
766
767 if (Literal.hadError)
768 return false;
769
770 if (Literal.Pascal) {
Andy Gibbsa8df57a2012-11-17 19:16:52 +0000771 Diag(StrToks[0].getLocation(), diag::err_expected_string_literal)
772 << /*Source='in...'*/0 << DiagnosticTag;
Andy Gibbs58905d22012-11-17 19:15:38 +0000773 return false;
774 }
775
776 String = Literal.GetString();
777 return true;
778}
779
Reid Klecknerc0dca6d2014-02-12 23:50:26 +0000780bool Preprocessor::parseSimpleIntegerLiteral(Token &Tok, uint64_t &Value) {
781 assert(Tok.is(tok::numeric_constant));
782 SmallString<8> IntegerBuffer;
783 bool NumberInvalid = false;
784 StringRef Spelling = getSpelling(Tok, IntegerBuffer, &NumberInvalid);
785 if (NumberInvalid)
786 return false;
787 NumericLiteralParser Literal(Spelling, Tok.getLocation(), *this);
788 if (Literal.hadError || !Literal.isIntegerLiteral() || Literal.hasUDSuffix())
789 return false;
790 llvm::APInt APVal(64, 0);
791 if (Literal.GetIntegerValue(APVal))
792 return false;
793 Lex(Tok);
794 Value = APVal.getLimitedValue();
795 return true;
796}
797
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000798void Preprocessor::addCommentHandler(CommentHandler *Handler) {
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000799 assert(Handler && "NULL comment handler");
800 assert(std::find(CommentHandlers.begin(), CommentHandlers.end(), Handler) ==
801 CommentHandlers.end() && "Comment handler already registered");
802 CommentHandlers.push_back(Handler);
803}
804
Dmitri Gribenkoaab83832012-06-20 00:34:58 +0000805void Preprocessor::removeCommentHandler(CommentHandler *Handler) {
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000806 std::vector<CommentHandler *>::iterator Pos
807 = std::find(CommentHandlers.begin(), CommentHandlers.end(), Handler);
808 assert(Pos != CommentHandlers.end() && "Comment handler not registered");
809 CommentHandlers.erase(Pos);
810}
811
Chris Lattner87d02082010-01-18 22:35:47 +0000812bool Preprocessor::HandleComment(Token &result, SourceRange Comment) {
813 bool AnyPendingTokens = false;
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000814 for (std::vector<CommentHandler *>::iterator H = CommentHandlers.begin(),
815 HEnd = CommentHandlers.end();
Chris Lattner87d02082010-01-18 22:35:47 +0000816 H != HEnd; ++H) {
817 if ((*H)->HandleComment(*this, Comment))
818 AnyPendingTokens = true;
819 }
820 if (!AnyPendingTokens || getCommentRetentionState())
821 return false;
822 Lex(result);
823 return true;
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000824}
825
Douglas Gregor08142532011-08-26 23:56:07 +0000826ModuleLoader::~ModuleLoader() { }
827
Douglas Gregorc6d5edd2009-07-02 17:08:52 +0000828CommentHandler::~CommentHandler() { }
Douglas Gregor7f6d60d2010-03-19 16:15:56 +0000829
Douglas Gregor3a7ad252010-08-24 19:08:16 +0000830CodeCompletionHandler::~CodeCompletionHandler() { }
831
Argyrios Kyrtzidisf3d587e2012-12-04 07:27:05 +0000832void Preprocessor::createPreprocessingRecord() {
Douglas Gregor7f6d60d2010-03-19 16:15:56 +0000833 if (Record)
834 return;
835
Argyrios Kyrtzidisf3d587e2012-12-04 07:27:05 +0000836 Record = new PreprocessingRecord(getSourceManager());
Douglas Gregor7dc87222010-03-19 17:12:43 +0000837 addPPCallbacks(Record);
Douglas Gregor7f6d60d2010-03-19 16:15:56 +0000838}