blob: 949cd632620e09152a7245db48db3f9701f63f72 [file] [log] [blame]
Chris Lattner8c32b1a2008-03-09 04:10:46 +00001//===--- PPLexerChange.cpp - Handle changing lexers in the preprocessor ---===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements pieces of the Preprocessor interface that manage the
11// current lexer stack.
12//
13//===----------------------------------------------------------------------===//
14
15#include "clang/Lex/Preprocessor.h"
Douglas Gregoraa93a872011-10-17 15:32:29 +000016#include "clang/Basic/FileManager.h"
Chris Lattner8c32b1a2008-03-09 04:10:46 +000017#include "clang/Basic/SourceManager.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000018#include "clang/Lex/HeaderSearch.h"
19#include "clang/Lex/LexDiagnostic.h"
20#include "clang/Lex/MacroInfo.h"
21#include "llvm/ADT/StringSwitch.h"
Douglas Gregor585ec932011-12-23 00:23:59 +000022#include "llvm/Support/FileSystem.h"
Ted Kremenek15ba2af2008-11-20 07:56:33 +000023#include "llvm/Support/MemoryBuffer.h"
Rafael Espindola8229d222013-06-11 22:15:02 +000024#include "llvm/Support/Path.h"
Chris Lattner8c32b1a2008-03-09 04:10:46 +000025using namespace clang;
26
Ted Kremenek4b391082008-11-18 01:33:13 +000027PPCallbacks::~PPCallbacks() {}
Chris Lattner8c32b1a2008-03-09 04:10:46 +000028
29//===----------------------------------------------------------------------===//
Chris Lattner6b884502008-03-10 06:06:04 +000030// Miscellaneous Methods.
Chris Lattner8c32b1a2008-03-09 04:10:46 +000031//===----------------------------------------------------------------------===//
32
Chris Lattner8c32b1a2008-03-09 04:10:46 +000033/// isInPrimaryFile - Return true if we're in the top-level file, not in a
James Dennett1a5f9002012-06-22 05:36:05 +000034/// \#include. This looks through macro expansions and active _Pragma lexers.
Chris Lattner8c32b1a2008-03-09 04:10:46 +000035bool Preprocessor::isInPrimaryFile() const {
Ted Kremenek81d24e12008-11-20 16:19:53 +000036 if (IsFileLexer())
Chris Lattner8c32b1a2008-03-09 04:10:46 +000037 return IncludeMacroStack.empty();
Mike Stump1eb44332009-09-09 15:08:12 +000038
Chris Lattner8c32b1a2008-03-09 04:10:46 +000039 // If there are any stacked lexers, we're in a #include.
Ted Kremenek81d24e12008-11-20 16:19:53 +000040 assert(IsFileLexer(IncludeMacroStack[0]) &&
Chris Lattner8c32b1a2008-03-09 04:10:46 +000041 "Top level include stack isn't our primary lexer?");
42 for (unsigned i = 1, e = IncludeMacroStack.size(); i != e; ++i)
Ted Kremenek81d24e12008-11-20 16:19:53 +000043 if (IsFileLexer(IncludeMacroStack[i]))
Chris Lattner8c32b1a2008-03-09 04:10:46 +000044 return false;
45 return true;
46}
47
48/// getCurrentLexer - Return the current file lexer being lexed from. Note
49/// that this ignores any potentially active macro expansions and _Pragma
50/// expansions going on at the time.
Ted Kremenek68e48e42008-11-20 01:49:44 +000051PreprocessorLexer *Preprocessor::getCurrentFileLexer() const {
Ted Kremenek81d24e12008-11-20 16:19:53 +000052 if (IsFileLexer())
Ted Kremenek68e48e42008-11-20 01:49:44 +000053 return CurPPLexer;
Mike Stump1eb44332009-09-09 15:08:12 +000054
Chris Lattner8c32b1a2008-03-09 04:10:46 +000055 // Look for a stacked lexer.
56 for (unsigned i = IncludeMacroStack.size(); i != 0; --i) {
Ted Kremenek68e48e42008-11-20 01:49:44 +000057 const IncludeStackInfo& ISI = IncludeMacroStack[i-1];
Ted Kremenek81d24e12008-11-20 16:19:53 +000058 if (IsFileLexer(ISI))
Ted Kremenek68e48e42008-11-20 01:49:44 +000059 return ISI.ThePPLexer;
Chris Lattner8c32b1a2008-03-09 04:10:46 +000060 }
61 return 0;
62}
63
Chris Lattner6b884502008-03-10 06:06:04 +000064
65//===----------------------------------------------------------------------===//
66// Methods for Entering and Callbacks for leaving various contexts
67//===----------------------------------------------------------------------===//
Chris Lattner8c32b1a2008-03-09 04:10:46 +000068
69/// EnterSourceFile - Add a source file to the top of the include stack and
Nuno Lopese7f2cbd2009-11-29 17:07:16 +000070/// start lexing tokens from it instead of the current buffer.
Stephen Hines651f13c2014-04-23 16:59:28 -070071bool Preprocessor::EnterSourceFile(FileID FID, const DirectoryLookup *CurDir,
Chris Lattnere127a0d2010-04-20 20:35:58 +000072 SourceLocation Loc) {
David Blaikie7247c882013-05-15 07:37:26 +000073 assert(!CurTokenLexer && "Cannot #include a file inside a macro!");
Chris Lattner8c32b1a2008-03-09 04:10:46 +000074 ++NumEnteredSourceFiles;
Mike Stump1eb44332009-09-09 15:08:12 +000075
Chris Lattner8c32b1a2008-03-09 04:10:46 +000076 if (MaxIncludeStackDepth < IncludeMacroStack.size())
77 MaxIncludeStackDepth = IncludeMacroStack.size();
78
Ted Kremenek6137dc92008-12-02 19:46:31 +000079 if (PTH) {
Chris Lattner6e290142009-11-30 04:18:44 +000080 if (PTHLexer *PL = PTH->CreateLexer(FID)) {
81 EnterSourceFileWithPTH(PL, CurDir);
Stephen Hines651f13c2014-04-23 16:59:28 -070082 return false;
Chris Lattner6e290142009-11-30 04:18:44 +000083 }
Ted Kremenek6137dc92008-12-02 19:46:31 +000084 }
Chris Lattner6e290142009-11-30 04:18:44 +000085
86 // Get the MemoryBuffer for this FID, if it fails, we fail.
Douglas Gregoraae58b02010-03-16 20:01:30 +000087 bool Invalid = false;
Chris Lattnere127a0d2010-04-20 20:35:58 +000088 const llvm::MemoryBuffer *InputFile =
89 getSourceManager().getBuffer(FID, Loc, &Invalid);
90 if (Invalid) {
91 SourceLocation FileStart = SourceMgr.getLocForStartOfFile(FID);
92 Diag(Loc, diag::err_pp_error_opening_file)
93 << std::string(SourceMgr.getBufferName(FileStart)) << "";
Stephen Hines651f13c2014-04-23 16:59:28 -070094 return true;
Chris Lattnere127a0d2010-04-20 20:35:58 +000095 }
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +000096
97 if (isCodeCompletionEnabled() &&
98 SourceMgr.getFileEntryForID(FID) == CodeCompletionFile) {
99 CodeCompletionFileLoc = SourceMgr.getLocForStartOfFile(FID);
100 CodeCompletionLoc =
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +0000101 CodeCompletionFileLoc.getLocWithOffset(CodeCompletionOffset);
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +0000102 }
103
Chris Lattner6e290142009-11-30 04:18:44 +0000104 EnterSourceFileWithLexer(new Lexer(FID, InputFile, *this), CurDir);
Stephen Hines651f13c2014-04-23 16:59:28 -0700105 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000106}
Chris Lattner72181832008-09-26 20:12:23 +0000107
Ted Kremenek6137dc92008-12-02 19:46:31 +0000108/// EnterSourceFileWithLexer - Add a source file to the top of the include stack
109/// and start lexing tokens from it instead of the current buffer.
Mike Stump1eb44332009-09-09 15:08:12 +0000110void Preprocessor::EnterSourceFileWithLexer(Lexer *TheLexer,
Chris Lattner8c32b1a2008-03-09 04:10:46 +0000111 const DirectoryLookup *CurDir) {
Mike Stump1eb44332009-09-09 15:08:12 +0000112
Chris Lattner8c32b1a2008-03-09 04:10:46 +0000113 // Add the current lexer to the include stack.
Ted Kremenek41938c82008-11-19 21:57:25 +0000114 if (CurPPLexer || CurTokenLexer)
Ted Kremeneked04c4c2008-11-13 16:51:03 +0000115 PushIncludeMacroStack();
116
Ted Kremenekcaaa7df2008-11-13 17:11:24 +0000117 CurLexer.reset(TheLexer);
Ted Kremenek9c1b7502008-11-18 00:12:49 +0000118 CurPPLexer = TheLexer;
Chris Lattner8c32b1a2008-03-09 04:10:46 +0000119 CurDirLookup = CurDir;
Stephen Hines651f13c2014-04-23 16:59:28 -0700120 CurSubmodule = 0;
Douglas Gregorb8db7cd2011-09-07 23:11:54 +0000121 if (CurLexerKind != CLK_LexAfterModuleImport)
122 CurLexerKind = CLK_Lexer;
123
Chris Lattner8c32b1a2008-03-09 04:10:46 +0000124 // Notify the client, if desired, that we are in a new source file.
125 if (Callbacks && !CurLexer->Is_PragmaLexer) {
Chris Lattner9d728512008-10-27 01:19:25 +0000126 SrcMgr::CharacteristicKind FileType =
Chris Lattner0b9e7362008-09-26 21:18:42 +0000127 SourceMgr.getFileCharacteristic(CurLexer->getFileLoc());
Mike Stump1eb44332009-09-09 15:08:12 +0000128
Chris Lattner8c32b1a2008-03-09 04:10:46 +0000129 Callbacks->FileChanged(CurLexer->getFileLoc(),
130 PPCallbacks::EnterFile, FileType);
131 }
132}
133
Ted Kremenek6137dc92008-12-02 19:46:31 +0000134/// EnterSourceFileWithPTH - Add a source file to the top of the include stack
135/// and start getting tokens from it using the PTH cache.
Mike Stump1eb44332009-09-09 15:08:12 +0000136void Preprocessor::EnterSourceFileWithPTH(PTHLexer *PL,
Ted Kremenek6137dc92008-12-02 19:46:31 +0000137 const DirectoryLookup *CurDir) {
Mike Stump1eb44332009-09-09 15:08:12 +0000138
Ted Kremenek6137dc92008-12-02 19:46:31 +0000139 if (CurPPLexer || CurTokenLexer)
140 PushIncludeMacroStack();
Chris Lattner8c32b1a2008-03-09 04:10:46 +0000141
Ted Kremenek6137dc92008-12-02 19:46:31 +0000142 CurDirLookup = CurDir;
143 CurPTHLexer.reset(PL);
144 CurPPLexer = CurPTHLexer.get();
Stephen Hines651f13c2014-04-23 16:59:28 -0700145 CurSubmodule = 0;
Douglas Gregorb8db7cd2011-09-07 23:11:54 +0000146 if (CurLexerKind != CLK_LexAfterModuleImport)
147 CurLexerKind = CLK_PTHLexer;
148
Ted Kremenek6137dc92008-12-02 19:46:31 +0000149 // Notify the client, if desired, that we are in a new source file.
150 if (Callbacks) {
Chris Lattner2b2453a2009-01-17 06:22:33 +0000151 FileID FID = CurPPLexer->getFileID();
Chris Lattner8c61b532009-01-19 08:01:53 +0000152 SourceLocation EnterLoc = SourceMgr.getLocForStartOfFile(FID);
153 SrcMgr::CharacteristicKind FileType =
154 SourceMgr.getFileCharacteristic(EnterLoc);
155 Callbacks->FileChanged(EnterLoc, PPCallbacks::EnterFile, FileType);
Ted Kremenek6137dc92008-12-02 19:46:31 +0000156 }
157}
Chris Lattner8c32b1a2008-03-09 04:10:46 +0000158
159/// EnterMacro - Add a Macro to the top of the include stack and start lexing
160/// tokens from it instead of the current buffer.
Chris Lattnere7fb4842009-02-15 20:52:18 +0000161void Preprocessor::EnterMacro(Token &Tok, SourceLocation ILEnd,
Richard Smithc30981a2012-08-30 13:38:46 +0000162 MacroInfo *Macro, MacroArgs *Args) {
Argyrios Kyrtzidisbb06b502012-12-22 04:48:10 +0000163 TokenLexer *TokLexer;
164 if (NumCachedTokenLexers == 0) {
165 TokLexer = new TokenLexer(Tok, ILEnd, Macro, Args, *this);
166 } else {
167 TokLexer = TokenLexerCache[--NumCachedTokenLexers];
168 TokLexer->Init(Tok, ILEnd, Macro, Args);
169 }
170
Ted Kremeneked04c4c2008-11-13 16:51:03 +0000171 PushIncludeMacroStack();
Chris Lattner8c32b1a2008-03-09 04:10:46 +0000172 CurDirLookup = 0;
Argyrios Kyrtzidisbb06b502012-12-22 04:48:10 +0000173 CurTokenLexer.reset(TokLexer);
Douglas Gregorb8db7cd2011-09-07 23:11:54 +0000174 if (CurLexerKind != CLK_LexAfterModuleImport)
175 CurLexerKind = CLK_TokenLexer;
Chris Lattner8c32b1a2008-03-09 04:10:46 +0000176}
177
178/// EnterTokenStream - Add a "macro" context to the top of the include stack,
Chris Lattner6b884502008-03-10 06:06:04 +0000179/// which will cause the lexer to start returning the specified tokens.
180///
181/// If DisableMacroExpansion is true, tokens lexed from the token stream will
182/// not be subject to further macro expansion. Otherwise, these tokens will
183/// be re-macro-expanded when/if expansion is enabled.
184///
185/// If OwnsTokens is false, this method assumes that the specified stream of
186/// tokens has a permanent owner somewhere, so they do not need to be copied.
187/// If it is true, it assumes the array of tokens is allocated with new[] and
188/// must be freed.
189///
190void Preprocessor::EnterTokenStream(const Token *Toks, unsigned NumToks,
191 bool DisableMacroExpansion,
192 bool OwnsTokens) {
Argyrios Kyrtzidisbb06b502012-12-22 04:48:10 +0000193 // Create a macro expander to expand from the specified token stream.
194 TokenLexer *TokLexer;
195 if (NumCachedTokenLexers == 0) {
196 TokLexer = new TokenLexer(Toks, NumToks, DisableMacroExpansion,
197 OwnsTokens, *this);
198 } else {
199 TokLexer = TokenLexerCache[--NumCachedTokenLexers];
200 TokLexer->Init(Toks, NumToks, DisableMacroExpansion, OwnsTokens);
201 }
202
Chris Lattner8c32b1a2008-03-09 04:10:46 +0000203 // Save our current state.
Ted Kremeneked04c4c2008-11-13 16:51:03 +0000204 PushIncludeMacroStack();
Chris Lattner8c32b1a2008-03-09 04:10:46 +0000205 CurDirLookup = 0;
Argyrios Kyrtzidisbb06b502012-12-22 04:48:10 +0000206 CurTokenLexer.reset(TokLexer);
Douglas Gregorb8db7cd2011-09-07 23:11:54 +0000207 if (CurLexerKind != CLK_LexAfterModuleImport)
208 CurLexerKind = CLK_TokenLexer;
Chris Lattner8c32b1a2008-03-09 04:10:46 +0000209}
210
Douglas Gregor585ec932011-12-23 00:23:59 +0000211/// \brief Compute the relative path that names the given file relative to
212/// the given directory.
213static void computeRelativePath(FileManager &FM, const DirectoryEntry *Dir,
214 const FileEntry *File,
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +0000215 SmallString<128> &Result) {
Douglas Gregor585ec932011-12-23 00:23:59 +0000216 Result.clear();
217
218 StringRef FilePath = File->getDir()->getName();
219 StringRef Path = FilePath;
220 while (!Path.empty()) {
221 if (const DirectoryEntry *CurDir = FM.getDirectory(Path)) {
222 if (CurDir == Dir) {
223 Result = FilePath.substr(Path.size());
224 llvm::sys::path::append(Result,
225 llvm::sys::path::filename(File->getName()));
226 return;
227 }
228 }
229
230 Path = llvm::sys::path::parent_path(Path);
231 }
232
233 Result = File->getName();
234}
235
Eli Friedmand2f93082013-09-19 00:41:32 +0000236void Preprocessor::PropagateLineStartLeadingSpaceInfo(Token &Result) {
237 if (CurTokenLexer) {
238 CurTokenLexer->PropagateLineStartLeadingSpaceInfo(Result);
239 return;
240 }
241 if (CurLexer) {
242 CurLexer->PropagateLineStartLeadingSpaceInfo(Result);
243 return;
244 }
245 // FIXME: Handle other kinds of lexers? It generally shouldn't matter,
246 // but it might if they're empty?
247}
248
Stephen Hines651f13c2014-04-23 16:59:28 -0700249/// \brief Determine the location to use as the end of the buffer for a lexer.
250///
251/// If the file ends with a newline, form the EOF token on the newline itself,
252/// rather than "on the line following it", which doesn't exist. This makes
253/// diagnostics relating to the end of file include the last file that the user
254/// actually typed, which is goodness.
255const char *Preprocessor::getCurLexerEndPos() {
256 const char *EndPos = CurLexer->BufferEnd;
257 if (EndPos != CurLexer->BufferStart &&
258 (EndPos[-1] == '\n' || EndPos[-1] == '\r')) {
259 --EndPos;
260
261 // Handle \n\r and \r\n:
262 if (EndPos != CurLexer->BufferStart &&
263 (EndPos[-1] == '\n' || EndPos[-1] == '\r') &&
264 EndPos[-1] != EndPos[0])
265 --EndPos;
266 }
267
268 return EndPos;
269}
270
271
Chris Lattner8c32b1a2008-03-09 04:10:46 +0000272/// HandleEndOfFile - This callback is invoked when the lexer hits the end of
273/// the current file. This either returns the EOF token or pops a level off
274/// the include stack and keeps going.
275bool Preprocessor::HandleEndOfFile(Token &Result, bool isEndOfMacro) {
276 assert(!CurTokenLexer &&
277 "Ending a file when currently in a macro!");
Mike Stump1eb44332009-09-09 15:08:12 +0000278
Chris Lattner8c32b1a2008-03-09 04:10:46 +0000279 // See if this file had a controlling macro.
Ted Kremenek1a531572008-11-19 22:43:49 +0000280 if (CurPPLexer) { // Not ending a macro, ignore it.
Mike Stump1eb44332009-09-09 15:08:12 +0000281 if (const IdentifierInfo *ControllingMacro =
Ted Kremenek1a531572008-11-19 22:43:49 +0000282 CurPPLexer->MIOpt.GetControllingMacroAtEndOfFile()) {
Steve Naroff83d63c72009-04-24 20:03:17 +0000283 // Okay, this has a controlling macro, remember in HeaderFileInfo.
Mike Stump1eb44332009-09-09 15:08:12 +0000284 if (const FileEntry *FE =
Richard Trieu671538e2013-06-12 21:20:57 +0000285 SourceMgr.getFileEntryForID(CurPPLexer->getFileID())) {
Chris Lattner8c32b1a2008-03-09 04:10:46 +0000286 HeaderInfo.SetFileControllingMacro(FE, ControllingMacro);
Richard Trieu671538e2013-06-12 21:20:57 +0000287 if (const IdentifierInfo *DefinedMacro =
288 CurPPLexer->MIOpt.GetDefinedMacro()) {
289 if (!ControllingMacro->hasMacroDefinition() &&
290 DefinedMacro != ControllingMacro &&
291 HeaderInfo.FirstTimeLexingFile(FE)) {
Ismail Pazarbasi223e7a82013-10-12 23:17:37 +0000292
293 // If the edit distance between the two macros is more than 50%,
294 // DefinedMacro may not be header guard, or can be header guard of
295 // another header file. Therefore, it maybe defining something
296 // completely different. This can be observed in the wild when
297 // handling feature macros or header guards in different files.
298
299 const StringRef ControllingMacroName = ControllingMacro->getName();
300 const StringRef DefinedMacroName = DefinedMacro->getName();
301 const size_t MaxHalfLength = std::max(ControllingMacroName.size(),
302 DefinedMacroName.size()) / 2;
303 const unsigned ED = ControllingMacroName.edit_distance(
304 DefinedMacroName, true, MaxHalfLength);
305 if (ED <= MaxHalfLength) {
306 // Emit a warning for a bad header guard.
307 Diag(CurPPLexer->MIOpt.GetMacroLocation(),
308 diag::warn_header_guard)
309 << CurPPLexer->MIOpt.GetMacroLocation() << ControllingMacro;
310 Diag(CurPPLexer->MIOpt.GetDefinedLocation(),
311 diag::note_header_guard)
312 << CurPPLexer->MIOpt.GetDefinedLocation() << DefinedMacro
313 << ControllingMacro
314 << FixItHint::CreateReplacement(
315 CurPPLexer->MIOpt.GetDefinedLocation(),
316 ControllingMacro->getName());
317 }
Richard Trieu671538e2013-06-12 21:20:57 +0000318 }
319 }
320 }
Chris Lattner8c32b1a2008-03-09 04:10:46 +0000321 }
322 }
Mike Stump1eb44332009-09-09 15:08:12 +0000323
John McCall3eff3212011-10-18 00:44:04 +0000324 // Complain about reaching a true EOF within arc_cf_code_audited.
325 // We don't want to complain about reaching the end of a macro
326 // instantiation or a _Pragma.
327 if (PragmaARCCFCodeAuditedLoc.isValid() &&
John McCalld80d90d2011-10-18 01:36:41 +0000328 !isEndOfMacro && !(CurLexer && CurLexer->Is_PragmaLexer)) {
John McCall8dfac0b2011-09-30 05:12:12 +0000329 Diag(PragmaARCCFCodeAuditedLoc, diag::err_pp_eof_in_arc_cf_code_audited);
330
331 // Recover by leaving immediately.
332 PragmaARCCFCodeAuditedLoc = SourceLocation();
333 }
334
Chris Lattner8c32b1a2008-03-09 04:10:46 +0000335 // If this is a #include'd file, pop it off the include stack and continue
336 // lexing the #includer file.
337 if (!IncludeMacroStack.empty()) {
Argyrios Kyrtzidis7d100872011-09-04 03:32:15 +0000338
339 // If we lexed the code-completion file, act as if we reached EOF.
340 if (isCodeCompletionEnabled() && CurPPLexer &&
341 SourceMgr.getLocForStartOfFile(CurPPLexer->getFileID()) ==
342 CodeCompletionFileLoc) {
343 if (CurLexer) {
344 Result.startToken();
345 CurLexer->FormTokenWithChars(Result, CurLexer->BufferEnd, tok::eof);
346 CurLexer.reset();
347 } else {
348 assert(CurPTHLexer && "Got EOF but no current lexer set!");
349 CurPTHLexer->getEOF(Result);
350 CurPTHLexer.reset();
351 }
352
353 CurPPLexer = 0;
354 return true;
355 }
356
Argyrios Kyrtzidisd9d2b672011-08-21 23:33:04 +0000357 if (!isEndOfMacro && CurPPLexer &&
358 SourceMgr.getIncludeLoc(CurPPLexer->getFileID()).isValid()) {
359 // Notify SourceManager to record the number of FileIDs that were created
360 // during lexing of the #include'd file.
361 unsigned NumFIDs =
362 SourceMgr.local_sloc_entry_size() -
363 CurPPLexer->getInitialNumSLocEntries() + 1/*#include'd file*/;
364 SourceMgr.setNumCreatedFIDsForFileID(CurPPLexer->getFileID(), NumFIDs);
365 }
366
Argyrios Kyrtzidisc892c5f2011-10-11 17:29:44 +0000367 FileID ExitedFID;
368 if (Callbacks && !isEndOfMacro && CurPPLexer)
369 ExitedFID = CurPPLexer->getFileID();
Stephen Hines651f13c2014-04-23 16:59:28 -0700370
371 bool LeavingSubmodule = CurSubmodule && CurLexer;
372 if (LeavingSubmodule) {
373 // Notify the parser that we've left the module.
374 const char *EndPos = getCurLexerEndPos();
375 Result.startToken();
376 CurLexer->BufferPtr = EndPos;
377 CurLexer->FormTokenWithChars(Result, EndPos, tok::annot_module_end);
378 Result.setAnnotationEndLoc(Result.getLocation());
379 Result.setAnnotationValue(CurSubmodule);
380 }
381
Chris Lattner8c32b1a2008-03-09 04:10:46 +0000382 // We're done with the #included file.
383 RemoveTopOfLexerStack();
384
Eli Friedmand2f93082013-09-19 00:41:32 +0000385 // Propagate info about start-of-line/leading white-space/etc.
386 PropagateLineStartLeadingSpaceInfo(Result);
387
Chris Lattner8c32b1a2008-03-09 04:10:46 +0000388 // Notify the client, if desired, that we are in a new source file.
Ted Kremenek1a531572008-11-19 22:43:49 +0000389 if (Callbacks && !isEndOfMacro && CurPPLexer) {
Chris Lattner9d728512008-10-27 01:19:25 +0000390 SrcMgr::CharacteristicKind FileType =
Chris Lattner8c61b532009-01-19 08:01:53 +0000391 SourceMgr.getFileCharacteristic(CurPPLexer->getSourceLocation());
392 Callbacks->FileChanged(CurPPLexer->getSourceLocation(),
Argyrios Kyrtzidisc892c5f2011-10-11 17:29:44 +0000393 PPCallbacks::ExitFile, FileType, ExitedFID);
Chris Lattner8c32b1a2008-03-09 04:10:46 +0000394 }
395
Stephen Hines651f13c2014-04-23 16:59:28 -0700396 // Client should lex another token unless we generated an EOM.
397 return LeavingSubmodule;
Chris Lattner8c32b1a2008-03-09 04:10:46 +0000398 }
399
Stephen Hines651f13c2014-04-23 16:59:28 -0700400 // If this is the end of the main file, form an EOF token.
Ted Kremenek1a531572008-11-19 22:43:49 +0000401 if (CurLexer) {
Stephen Hines651f13c2014-04-23 16:59:28 -0700402 const char *EndPos = getCurLexerEndPos();
Ted Kremenek1a531572008-11-19 22:43:49 +0000403 Result.startToken();
404 CurLexer->BufferPtr = EndPos;
405 CurLexer->FormTokenWithChars(Result, EndPos, tok::eof);
Mike Stump1eb44332009-09-09 15:08:12 +0000406
Argyrios Kyrtzidisbb06b502012-12-22 04:48:10 +0000407 if (isCodeCompletionEnabled()) {
408 // Inserting the code-completion point increases the source buffer by 1,
409 // but the main FileID was created before inserting the point.
410 // Compensate by reducing the EOF location by 1, otherwise the location
411 // will point to the next FileID.
412 // FIXME: This is hacky, the code-completion point should probably be
413 // inserted before the main FileID is created.
414 if (CurLexer->getFileLoc() == CodeCompletionFileLoc)
415 Result.setLocation(Result.getLocation().getLocWithOffset(-1));
416 }
417
Axel Naumanne55329d2012-03-16 10:40:17 +0000418 if (!isIncrementalProcessingEnabled())
419 // We're done with lexing.
420 CurLexer.reset();
Chris Lattner67116082009-02-13 23:06:48 +0000421 } else {
422 assert(CurPTHLexer && "Got EOF but no current lexer set!");
Ted Kremenek59d08cb2008-12-23 19:24:24 +0000423 CurPTHLexer->getEOF(Result);
Ted Kremenek1a531572008-11-19 22:43:49 +0000424 CurPTHLexer.reset();
Chris Lattner8c32b1a2008-03-09 04:10:46 +0000425 }
Axel Naumanne55329d2012-03-16 10:40:17 +0000426
427 if (!isIncrementalProcessingEnabled())
428 CurPPLexer = 0;
Chris Lattner8c32b1a2008-03-09 04:10:46 +0000429
Stephen Hines651f13c2014-04-23 16:59:28 -0700430 if (TUKind == TU_Complete) {
431 // This is the end of the top-level file. 'WarnUnusedMacroLocs' has
432 // collected all macro locations that we need to warn because they are not
433 // used.
434 for (WarnUnusedMacroLocsTy::iterator
435 I=WarnUnusedMacroLocs.begin(), E=WarnUnusedMacroLocs.end();
436 I!=E; ++I)
437 Diag(*I, diag::pp_macro_not_used);
438 }
Daniel Dunbardbd82092010-03-23 05:09:10 +0000439
Douglas Gregor585ec932011-12-23 00:23:59 +0000440 // If we are building a module that has an umbrella header, make sure that
441 // each of the headers within the directory covered by the umbrella header
442 // was actually included by the umbrella header.
443 if (Module *Mod = getCurrentModule()) {
444 if (Mod->getUmbrellaHeader()) {
445 SourceLocation StartLoc
446 = SourceMgr.getLocForStartOfFile(SourceMgr.getMainFileID());
447
448 if (getDiagnostics().getDiagnosticLevel(
449 diag::warn_uncovered_module_header,
450 StartLoc) != DiagnosticsEngine::Ignored) {
Douglas Gregor51f564f2011-12-31 04:05:44 +0000451 ModuleMap &ModMap = getHeaderSearchInfo().getModuleMap();
Douglas Gregor224bfee2011-12-23 00:27:08 +0000452 typedef llvm::sys::fs::recursive_directory_iterator
Douglas Gregor585ec932011-12-23 00:23:59 +0000453 recursive_directory_iterator;
454 const DirectoryEntry *Dir = Mod->getUmbrellaDir();
455 llvm::error_code EC;
456 for (recursive_directory_iterator Entry(Dir->getName(), EC), End;
457 Entry != End && !EC; Entry.increment(EC)) {
458 using llvm::StringSwitch;
459
Douglas Gregor51f564f2011-12-31 04:05:44 +0000460 // Check whether this entry has an extension typically associated with
Douglas Gregor585ec932011-12-23 00:23:59 +0000461 // headers.
462 if (!StringSwitch<bool>(llvm::sys::path::extension(Entry->path()))
Douglas Gregor51f564f2011-12-31 04:05:44 +0000463 .Cases(".h", ".H", ".hh", ".hpp", true)
464 .Default(false))
Douglas Gregor585ec932011-12-23 00:23:59 +0000465 continue;
466
467 if (const FileEntry *Header = getFileManager().getFile(Entry->path()))
468 if (!getSourceManager().hasFileInfo(Header)) {
Douglas Gregor51f564f2011-12-31 04:05:44 +0000469 if (!ModMap.isHeaderInUnavailableModule(Header)) {
470 // Find the relative path that would access this header.
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +0000471 SmallString<128> RelativePath;
Douglas Gregor51f564f2011-12-31 04:05:44 +0000472 computeRelativePath(FileMgr, Dir, Header, RelativePath);
473 Diag(StartLoc, diag::warn_uncovered_module_header)
Douglas Gregorc9c39072013-01-04 18:58:28 +0000474 << Mod->getFullModuleName() << RelativePath;
Douglas Gregor51f564f2011-12-31 04:05:44 +0000475 }
Douglas Gregor585ec932011-12-23 00:23:59 +0000476 }
477 }
478 }
479 }
Douglas Gregor58ea48d2013-05-20 13:49:41 +0000480
481 // Check whether there are any headers that were included, but not
482 // mentioned at all in the module map. Such headers
483 SourceLocation StartLoc
484 = SourceMgr.getLocForStartOfFile(SourceMgr.getMainFileID());
485 if (getDiagnostics().getDiagnosticLevel(diag::warn_forgotten_module_header,
486 StartLoc)
487 != DiagnosticsEngine::Ignored) {
488 ModuleMap &ModMap = getHeaderSearchInfo().getModuleMap();
489 for (unsigned I = 0, N = SourceMgr.local_sloc_entry_size(); I != N; ++I) {
490 // We only care about file entries.
491 const SrcMgr::SLocEntry &Entry = SourceMgr.getLocalSLocEntry(I);
492 if (!Entry.isFile())
493 continue;
494
495 // Dig out the actual file.
496 const FileEntry *File = Entry.getFile().getContentCache()->OrigEntry;
497 if (!File)
498 continue;
499
500 // If it's not part of a module and not unknown, complain.
501 if (!ModMap.findModuleForHeader(File) &&
502 !ModMap.isHeaderInUnavailableModule(File)) {
503 Diag(StartLoc, diag::warn_forgotten_module_header)
504 << File->getName() << Mod->getFullModuleName();
505 }
506 }
507 }
Douglas Gregor585ec932011-12-23 00:23:59 +0000508 }
Douglas Gregor58ea48d2013-05-20 13:49:41 +0000509
Chris Lattner8c32b1a2008-03-09 04:10:46 +0000510 return true;
511}
512
513/// HandleEndOfTokenLexer - This callback is invoked when the current TokenLexer
514/// hits the end of its token stream.
515bool Preprocessor::HandleEndOfTokenLexer(Token &Result) {
Ted Kremenek1a531572008-11-19 22:43:49 +0000516 assert(CurTokenLexer && !CurPPLexer &&
Chris Lattner8c32b1a2008-03-09 04:10:46 +0000517 "Ending a macro when currently in a #include file!");
518
Argyrios Kyrtzidis5b3284a2011-06-29 22:20:11 +0000519 if (!MacroExpandingLexersStack.empty() &&
520 MacroExpandingLexersStack.back().first == CurTokenLexer.get())
521 removeCachedMacroExpandedTokensOfLastLexer();
522
Chris Lattner8c32b1a2008-03-09 04:10:46 +0000523 // Delete or cache the now-dead macro expander.
524 if (NumCachedTokenLexers == TokenLexerCacheSize)
Ted Kremenekcaaa7df2008-11-13 17:11:24 +0000525 CurTokenLexer.reset();
Chris Lattner8c32b1a2008-03-09 04:10:46 +0000526 else
Stephen Hines651f13c2014-04-23 16:59:28 -0700527 TokenLexerCache[NumCachedTokenLexers++] = CurTokenLexer.release();
Chris Lattner8c32b1a2008-03-09 04:10:46 +0000528
529 // Handle this like a #include file being popped off the stack.
Chris Lattner8c32b1a2008-03-09 04:10:46 +0000530 return HandleEndOfFile(Result, true);
531}
532
533/// RemoveTopOfLexerStack - Pop the current lexer/macro exp off the top of the
534/// lexer stack. This should only be used in situations where the current
535/// state of the top-of-stack lexer is unknown.
536void Preprocessor::RemoveTopOfLexerStack() {
537 assert(!IncludeMacroStack.empty() && "Ran out of stack entries to load");
Mike Stump1eb44332009-09-09 15:08:12 +0000538
Chris Lattner8c32b1a2008-03-09 04:10:46 +0000539 if (CurTokenLexer) {
540 // Delete or cache the now-dead macro expander.
541 if (NumCachedTokenLexers == TokenLexerCacheSize)
Ted Kremenekcaaa7df2008-11-13 17:11:24 +0000542 CurTokenLexer.reset();
Chris Lattner8c32b1a2008-03-09 04:10:46 +0000543 else
Stephen Hines651f13c2014-04-23 16:59:28 -0700544 TokenLexerCache[NumCachedTokenLexers++] = CurTokenLexer.release();
Mike Stump1eb44332009-09-09 15:08:12 +0000545 }
546
Ted Kremeneked04c4c2008-11-13 16:51:03 +0000547 PopIncludeMacroStack();
Chris Lattner8c32b1a2008-03-09 04:10:46 +0000548}
549
550/// HandleMicrosoftCommentPaste - When the macro expander pastes together a
551/// comment (/##/) in microsoft mode, this method handles updating the current
552/// state, returning the token on the next source line.
553void Preprocessor::HandleMicrosoftCommentPaste(Token &Tok) {
Ted Kremenek1a531572008-11-19 22:43:49 +0000554 assert(CurTokenLexer && !CurPPLexer &&
Chris Lattner8c32b1a2008-03-09 04:10:46 +0000555 "Pasted comment can only be formed from macro");
Mike Stump1eb44332009-09-09 15:08:12 +0000556
Chris Lattner8c32b1a2008-03-09 04:10:46 +0000557 // We handle this by scanning for the closest real lexer, switching it to
558 // raw mode and preprocessor mode. This will cause it to return \n as an
Peter Collingbourne84021552011-02-28 02:37:51 +0000559 // explicit EOD token.
Ted Kremenek1a531572008-11-19 22:43:49 +0000560 PreprocessorLexer *FoundLexer = 0;
Chris Lattner8c32b1a2008-03-09 04:10:46 +0000561 bool LexerWasInPPMode = false;
562 for (unsigned i = 0, e = IncludeMacroStack.size(); i != e; ++i) {
563 IncludeStackInfo &ISI = *(IncludeMacroStack.end()-i-1);
Ted Kremenek1a531572008-11-19 22:43:49 +0000564 if (ISI.ThePPLexer == 0) continue; // Scan for a real lexer.
Mike Stump1eb44332009-09-09 15:08:12 +0000565
Chris Lattner8c32b1a2008-03-09 04:10:46 +0000566 // Once we find a real lexer, mark it as raw mode (disabling macro
Peter Collingbourne84021552011-02-28 02:37:51 +0000567 // expansions) and preprocessor mode (return EOD). We know that the lexer
Chris Lattner8c32b1a2008-03-09 04:10:46 +0000568 // was *not* in raw mode before, because the macro that the comment came
569 // from was expanded. However, it could have already been in preprocessor
570 // mode (#if COMMENT) in which case we have to return it to that mode and
Peter Collingbourne84021552011-02-28 02:37:51 +0000571 // return EOD.
Ted Kremenek1a531572008-11-19 22:43:49 +0000572 FoundLexer = ISI.ThePPLexer;
Chris Lattner8c32b1a2008-03-09 04:10:46 +0000573 FoundLexer->LexingRawMode = true;
574 LexerWasInPPMode = FoundLexer->ParsingPreprocessorDirective;
575 FoundLexer->ParsingPreprocessorDirective = true;
576 break;
577 }
Mike Stump1eb44332009-09-09 15:08:12 +0000578
Chris Lattner8c32b1a2008-03-09 04:10:46 +0000579 // Okay, we either found and switched over the lexer, or we didn't find a
580 // lexer. In either case, finish off the macro the comment came from, getting
581 // the next token.
582 if (!HandleEndOfTokenLexer(Tok)) Lex(Tok);
Mike Stump1eb44332009-09-09 15:08:12 +0000583
Peter Collingbourne84021552011-02-28 02:37:51 +0000584 // Discarding comments as long as we don't have EOF or EOD. This 'comments
Chris Lattner8c32b1a2008-03-09 04:10:46 +0000585 // out' the rest of the line, including any tokens that came from other macros
586 // that were active, as in:
587 // #define submacro a COMMENT b
588 // submacro c
589 // which should lex to 'a' only: 'b' and 'c' should be removed.
Peter Collingbourne84021552011-02-28 02:37:51 +0000590 while (Tok.isNot(tok::eod) && Tok.isNot(tok::eof))
Chris Lattner8c32b1a2008-03-09 04:10:46 +0000591 Lex(Tok);
Mike Stump1eb44332009-09-09 15:08:12 +0000592
Peter Collingbourne84021552011-02-28 02:37:51 +0000593 // If we got an eod token, then we successfully found the end of the line.
594 if (Tok.is(tok::eod)) {
Chris Lattner8c32b1a2008-03-09 04:10:46 +0000595 assert(FoundLexer && "Can't get end of line without an active lexer");
596 // Restore the lexer back to normal mode instead of raw mode.
597 FoundLexer->LexingRawMode = false;
Mike Stump1eb44332009-09-09 15:08:12 +0000598
Peter Collingbourne84021552011-02-28 02:37:51 +0000599 // If the lexer was already in preprocessor mode, just return the EOD token
Chris Lattner8c32b1a2008-03-09 04:10:46 +0000600 // to finish the preprocessor line.
601 if (LexerWasInPPMode) return;
Mike Stump1eb44332009-09-09 15:08:12 +0000602
Chris Lattner8c32b1a2008-03-09 04:10:46 +0000603 // Otherwise, switch out of PP mode and return the next lexed token.
604 FoundLexer->ParsingPreprocessorDirective = false;
605 return Lex(Tok);
606 }
Mike Stump1eb44332009-09-09 15:08:12 +0000607
Chris Lattner8c32b1a2008-03-09 04:10:46 +0000608 // If we got an EOF token, then we reached the end of the token stream but
609 // didn't find an explicit \n. This can only happen if there was no lexer
Peter Collingbourne84021552011-02-28 02:37:51 +0000610 // active (an active lexer would return EOD at EOF if there was no \n in
Chris Lattner8c32b1a2008-03-09 04:10:46 +0000611 // preprocessor directive mode), so just return EOF as our token.
Peter Collingbourne84021552011-02-28 02:37:51 +0000612 assert(!FoundLexer && "Lexer should return EOD before EOF in PP mode");
Chris Lattner8c32b1a2008-03-09 04:10:46 +0000613}