1 //===--- PPLexerChange.cpp - Handle changing lexers in the preprocessor ---===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements pieces of the Preprocessor interface that manage the
11 // current lexer stack.
13 //===----------------------------------------------------------------------===//
15 #include "clang/Lex/Preprocessor.h"
16 #include "clang/Basic/FileManager.h"
17 #include "clang/Basic/SourceManager.h"
18 #include "clang/Lex/HeaderSearch.h"
19 #include "clang/Lex/LexDiagnostic.h"
20 #include "clang/Lex/MacroInfo.h"
21 #include "llvm/ADT/StringSwitch.h"
22 #include "llvm/Support/FileSystem.h"
23 #include "llvm/Support/MemoryBuffer.h"
24 #include "llvm/Support/PathV2.h"
25 using namespace clang;
27 PPCallbacks::~PPCallbacks() {}
29 //===----------------------------------------------------------------------===//
30 // Miscellaneous Methods.
31 //===----------------------------------------------------------------------===//
33 /// isInPrimaryFile - Return true if we're in the top-level file, not in a
34 /// \#include. This looks through macro expansions and active _Pragma lexers.
35 bool Preprocessor::isInPrimaryFile() const {
37 return IncludeMacroStack.empty();
39 // If there are any stacked lexers, we're in a #include.
40 assert(IsFileLexer(IncludeMacroStack[0]) &&
41 "Top level include stack isn't our primary lexer?");
42 for (unsigned i = 1, e = IncludeMacroStack.size(); i != e; ++i)
43 if (IsFileLexer(IncludeMacroStack[i]))
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.
51 PreprocessorLexer *Preprocessor::getCurrentFileLexer() const {
55 // Look for a stacked lexer.
56 for (unsigned i = IncludeMacroStack.size(); i != 0; --i) {
57 const IncludeStackInfo& ISI = IncludeMacroStack[i-1];
59 return ISI.ThePPLexer;
65 //===----------------------------------------------------------------------===//
66 // Methods for Entering and Callbacks for leaving various contexts
67 //===----------------------------------------------------------------------===//
69 /// EnterSourceFile - Add a source file to the top of the include stack and
70 /// start lexing tokens from it instead of the current buffer.
71 void Preprocessor::EnterSourceFile(FileID FID, const DirectoryLookup *CurDir,
73 assert(CurTokenLexer == 0 && "Cannot #include a file inside a macro!");
74 ++NumEnteredSourceFiles;
76 if (MaxIncludeStackDepth < IncludeMacroStack.size())
77 MaxIncludeStackDepth = IncludeMacroStack.size();
80 if (PTHLexer *PL = PTH->CreateLexer(FID)) {
81 EnterSourceFileWithPTH(PL, CurDir);
86 // Get the MemoryBuffer for this FID, if it fails, we fail.
88 const llvm::MemoryBuffer *InputFile =
89 getSourceManager().getBuffer(FID, Loc, &Invalid);
91 SourceLocation FileStart = SourceMgr.getLocForStartOfFile(FID);
92 Diag(Loc, diag::err_pp_error_opening_file)
93 << std::string(SourceMgr.getBufferName(FileStart)) << "";
97 if (isCodeCompletionEnabled() &&
98 SourceMgr.getFileEntryForID(FID) == CodeCompletionFile) {
99 CodeCompletionFileLoc = SourceMgr.getLocForStartOfFile(FID);
101 CodeCompletionFileLoc.getLocWithOffset(CodeCompletionOffset);
104 EnterSourceFileWithLexer(new Lexer(FID, InputFile, *this), CurDir);
108 /// EnterSourceFileWithLexer - Add a source file to the top of the include stack
109 /// and start lexing tokens from it instead of the current buffer.
110 void Preprocessor::EnterSourceFileWithLexer(Lexer *TheLexer,
111 const DirectoryLookup *CurDir) {
113 // Add the current lexer to the include stack.
114 if (CurPPLexer || CurTokenLexer)
115 PushIncludeMacroStack();
117 CurLexer.reset(TheLexer);
118 CurPPLexer = TheLexer;
119 CurDirLookup = CurDir;
120 if (CurLexerKind != CLK_LexAfterModuleImport)
121 CurLexerKind = CLK_Lexer;
123 // Notify the client, if desired, that we are in a new source file.
124 if (Callbacks && !CurLexer->Is_PragmaLexer) {
125 SrcMgr::CharacteristicKind FileType =
126 SourceMgr.getFileCharacteristic(CurLexer->getFileLoc());
128 Callbacks->FileChanged(CurLexer->getFileLoc(),
129 PPCallbacks::EnterFile, FileType);
133 /// EnterSourceFileWithPTH - Add a source file to the top of the include stack
134 /// and start getting tokens from it using the PTH cache.
135 void Preprocessor::EnterSourceFileWithPTH(PTHLexer *PL,
136 const DirectoryLookup *CurDir) {
138 if (CurPPLexer || CurTokenLexer)
139 PushIncludeMacroStack();
141 CurDirLookup = CurDir;
142 CurPTHLexer.reset(PL);
143 CurPPLexer = CurPTHLexer.get();
144 if (CurLexerKind != CLK_LexAfterModuleImport)
145 CurLexerKind = CLK_PTHLexer;
147 // Notify the client, if desired, that we are in a new source file.
149 FileID FID = CurPPLexer->getFileID();
150 SourceLocation EnterLoc = SourceMgr.getLocForStartOfFile(FID);
151 SrcMgr::CharacteristicKind FileType =
152 SourceMgr.getFileCharacteristic(EnterLoc);
153 Callbacks->FileChanged(EnterLoc, PPCallbacks::EnterFile, FileType);
157 /// EnterMacro - Add a Macro to the top of the include stack and start lexing
158 /// tokens from it instead of the current buffer.
159 void Preprocessor::EnterMacro(Token &Tok, SourceLocation ILEnd,
160 MacroInfo *Macro, MacroArgs *Args) {
161 TokenLexer *TokLexer;
162 if (NumCachedTokenLexers == 0) {
163 TokLexer = new TokenLexer(Tok, ILEnd, Macro, Args, *this);
165 TokLexer = TokenLexerCache[--NumCachedTokenLexers];
166 TokLexer->Init(Tok, ILEnd, Macro, Args);
169 PushIncludeMacroStack();
171 CurTokenLexer.reset(TokLexer);
172 if (CurLexerKind != CLK_LexAfterModuleImport)
173 CurLexerKind = CLK_TokenLexer;
176 /// EnterTokenStream - Add a "macro" context to the top of the include stack,
177 /// which will cause the lexer to start returning the specified tokens.
179 /// If DisableMacroExpansion is true, tokens lexed from the token stream will
180 /// not be subject to further macro expansion. Otherwise, these tokens will
181 /// be re-macro-expanded when/if expansion is enabled.
183 /// If OwnsTokens is false, this method assumes that the specified stream of
184 /// tokens has a permanent owner somewhere, so they do not need to be copied.
185 /// If it is true, it assumes the array of tokens is allocated with new[] and
188 void Preprocessor::EnterTokenStream(const Token *Toks, unsigned NumToks,
189 bool DisableMacroExpansion,
191 // Create a macro expander to expand from the specified token stream.
192 TokenLexer *TokLexer;
193 if (NumCachedTokenLexers == 0) {
194 TokLexer = new TokenLexer(Toks, NumToks, DisableMacroExpansion,
197 TokLexer = TokenLexerCache[--NumCachedTokenLexers];
198 TokLexer->Init(Toks, NumToks, DisableMacroExpansion, OwnsTokens);
201 // Save our current state.
202 PushIncludeMacroStack();
204 CurTokenLexer.reset(TokLexer);
205 if (CurLexerKind != CLK_LexAfterModuleImport)
206 CurLexerKind = CLK_TokenLexer;
209 /// \brief Compute the relative path that names the given file relative to
210 /// the given directory.
211 static void computeRelativePath(FileManager &FM, const DirectoryEntry *Dir,
212 const FileEntry *File,
213 SmallString<128> &Result) {
216 StringRef FilePath = File->getDir()->getName();
217 StringRef Path = FilePath;
218 while (!Path.empty()) {
219 if (const DirectoryEntry *CurDir = FM.getDirectory(Path)) {
221 Result = FilePath.substr(Path.size());
222 llvm::sys::path::append(Result,
223 llvm::sys::path::filename(File->getName()));
228 Path = llvm::sys::path::parent_path(Path);
231 Result = File->getName();
234 /// HandleEndOfFile - This callback is invoked when the lexer hits the end of
235 /// the current file. This either returns the EOF token or pops a level off
236 /// the include stack and keeps going.
237 bool Preprocessor::HandleEndOfFile(Token &Result, bool isEndOfMacro) {
238 assert(!CurTokenLexer &&
239 "Ending a file when currently in a macro!");
241 // See if this file had a controlling macro.
242 if (CurPPLexer) { // Not ending a macro, ignore it.
243 if (const IdentifierInfo *ControllingMacro =
244 CurPPLexer->MIOpt.GetControllingMacroAtEndOfFile()) {
245 // Okay, this has a controlling macro, remember in HeaderFileInfo.
246 if (const FileEntry *FE =
247 SourceMgr.getFileEntryForID(CurPPLexer->getFileID()))
248 HeaderInfo.SetFileControllingMacro(FE, ControllingMacro);
252 // Complain about reaching a true EOF within arc_cf_code_audited.
253 // We don't want to complain about reaching the end of a macro
254 // instantiation or a _Pragma.
255 if (PragmaARCCFCodeAuditedLoc.isValid() &&
256 !isEndOfMacro && !(CurLexer && CurLexer->Is_PragmaLexer)) {
257 Diag(PragmaARCCFCodeAuditedLoc, diag::err_pp_eof_in_arc_cf_code_audited);
259 // Recover by leaving immediately.
260 PragmaARCCFCodeAuditedLoc = SourceLocation();
263 // If this is a #include'd file, pop it off the include stack and continue
264 // lexing the #includer file.
265 if (!IncludeMacroStack.empty()) {
267 // If we lexed the code-completion file, act as if we reached EOF.
268 if (isCodeCompletionEnabled() && CurPPLexer &&
269 SourceMgr.getLocForStartOfFile(CurPPLexer->getFileID()) ==
270 CodeCompletionFileLoc) {
273 CurLexer->FormTokenWithChars(Result, CurLexer->BufferEnd, tok::eof);
276 assert(CurPTHLexer && "Got EOF but no current lexer set!");
277 CurPTHLexer->getEOF(Result);
285 if (!isEndOfMacro && CurPPLexer &&
286 SourceMgr.getIncludeLoc(CurPPLexer->getFileID()).isValid()) {
287 // Notify SourceManager to record the number of FileIDs that were created
288 // during lexing of the #include'd file.
290 SourceMgr.local_sloc_entry_size() -
291 CurPPLexer->getInitialNumSLocEntries() + 1/*#include'd file*/;
292 SourceMgr.setNumCreatedFIDsForFileID(CurPPLexer->getFileID(), NumFIDs);
296 if (Callbacks && !isEndOfMacro && CurPPLexer)
297 ExitedFID = CurPPLexer->getFileID();
299 // We're done with the #included file.
300 RemoveTopOfLexerStack();
302 // Notify the client, if desired, that we are in a new source file.
303 if (Callbacks && !isEndOfMacro && CurPPLexer) {
304 SrcMgr::CharacteristicKind FileType =
305 SourceMgr.getFileCharacteristic(CurPPLexer->getSourceLocation());
306 Callbacks->FileChanged(CurPPLexer->getSourceLocation(),
307 PPCallbacks::ExitFile, FileType, ExitedFID);
310 // Client should lex another token.
314 // If the file ends with a newline, form the EOF token on the newline itself,
315 // rather than "on the line following it", which doesn't exist. This makes
316 // diagnostics relating to the end of file include the last file that the user
317 // actually typed, which is goodness.
319 const char *EndPos = CurLexer->BufferEnd;
320 if (EndPos != CurLexer->BufferStart &&
321 (EndPos[-1] == '\n' || EndPos[-1] == '\r')) {
324 // Handle \n\r and \r\n:
325 if (EndPos != CurLexer->BufferStart &&
326 (EndPos[-1] == '\n' || EndPos[-1] == '\r') &&
327 EndPos[-1] != EndPos[0])
332 CurLexer->BufferPtr = EndPos;
333 CurLexer->FormTokenWithChars(Result, EndPos, tok::eof);
335 if (isCodeCompletionEnabled()) {
336 // Inserting the code-completion point increases the source buffer by 1,
337 // but the main FileID was created before inserting the point.
338 // Compensate by reducing the EOF location by 1, otherwise the location
339 // will point to the next FileID.
340 // FIXME: This is hacky, the code-completion point should probably be
341 // inserted before the main FileID is created.
342 if (CurLexer->getFileLoc() == CodeCompletionFileLoc)
343 Result.setLocation(Result.getLocation().getLocWithOffset(-1));
346 if (!isIncrementalProcessingEnabled())
347 // We're done with lexing.
350 assert(CurPTHLexer && "Got EOF but no current lexer set!");
351 CurPTHLexer->getEOF(Result);
355 if (!isIncrementalProcessingEnabled())
358 // This is the end of the top-level file. 'WarnUnusedMacroLocs' has collected
359 // all macro locations that we need to warn because they are not used.
360 for (WarnUnusedMacroLocsTy::iterator
361 I=WarnUnusedMacroLocs.begin(), E=WarnUnusedMacroLocs.end(); I!=E; ++I)
362 Diag(*I, diag::pp_macro_not_used);
364 // If we are building a module that has an umbrella header, make sure that
365 // each of the headers within the directory covered by the umbrella header
366 // was actually included by the umbrella header.
367 if (Module *Mod = getCurrentModule()) {
368 if (Mod->getUmbrellaHeader()) {
369 SourceLocation StartLoc
370 = SourceMgr.getLocForStartOfFile(SourceMgr.getMainFileID());
372 if (getDiagnostics().getDiagnosticLevel(
373 diag::warn_uncovered_module_header,
374 StartLoc) != DiagnosticsEngine::Ignored) {
375 ModuleMap &ModMap = getHeaderSearchInfo().getModuleMap();
376 typedef llvm::sys::fs::recursive_directory_iterator
377 recursive_directory_iterator;
378 const DirectoryEntry *Dir = Mod->getUmbrellaDir();
380 for (recursive_directory_iterator Entry(Dir->getName(), EC), End;
381 Entry != End && !EC; Entry.increment(EC)) {
382 using llvm::StringSwitch;
384 // Check whether this entry has an extension typically associated with
386 if (!StringSwitch<bool>(llvm::sys::path::extension(Entry->path()))
387 .Cases(".h", ".H", ".hh", ".hpp", true)
391 if (const FileEntry *Header = getFileManager().getFile(Entry->path()))
392 if (!getSourceManager().hasFileInfo(Header)) {
393 if (!ModMap.isHeaderInUnavailableModule(Header)) {
394 // Find the relative path that would access this header.
395 SmallString<128> RelativePath;
396 computeRelativePath(FileMgr, Dir, Header, RelativePath);
397 Diag(StartLoc, diag::warn_uncovered_module_header)
398 << Mod->getFullModuleName() << RelativePath;
409 /// HandleEndOfTokenLexer - This callback is invoked when the current TokenLexer
410 /// hits the end of its token stream.
411 bool Preprocessor::HandleEndOfTokenLexer(Token &Result) {
412 assert(CurTokenLexer && !CurPPLexer &&
413 "Ending a macro when currently in a #include file!");
415 if (!MacroExpandingLexersStack.empty() &&
416 MacroExpandingLexersStack.back().first == CurTokenLexer.get())
417 removeCachedMacroExpandedTokensOfLastLexer();
419 // Delete or cache the now-dead macro expander.
420 if (NumCachedTokenLexers == TokenLexerCacheSize)
421 CurTokenLexer.reset();
423 TokenLexerCache[NumCachedTokenLexers++] = CurTokenLexer.take();
425 // Handle this like a #include file being popped off the stack.
426 return HandleEndOfFile(Result, true);
429 /// RemoveTopOfLexerStack - Pop the current lexer/macro exp off the top of the
430 /// lexer stack. This should only be used in situations where the current
431 /// state of the top-of-stack lexer is unknown.
432 void Preprocessor::RemoveTopOfLexerStack() {
433 assert(!IncludeMacroStack.empty() && "Ran out of stack entries to load");
436 // Delete or cache the now-dead macro expander.
437 if (NumCachedTokenLexers == TokenLexerCacheSize)
438 CurTokenLexer.reset();
440 TokenLexerCache[NumCachedTokenLexers++] = CurTokenLexer.take();
443 PopIncludeMacroStack();
446 /// HandleMicrosoftCommentPaste - When the macro expander pastes together a
447 /// comment (/##/) in microsoft mode, this method handles updating the current
448 /// state, returning the token on the next source line.
449 void Preprocessor::HandleMicrosoftCommentPaste(Token &Tok) {
450 assert(CurTokenLexer && !CurPPLexer &&
451 "Pasted comment can only be formed from macro");
453 // We handle this by scanning for the closest real lexer, switching it to
454 // raw mode and preprocessor mode. This will cause it to return \n as an
455 // explicit EOD token.
456 PreprocessorLexer *FoundLexer = 0;
457 bool LexerWasInPPMode = false;
458 for (unsigned i = 0, e = IncludeMacroStack.size(); i != e; ++i) {
459 IncludeStackInfo &ISI = *(IncludeMacroStack.end()-i-1);
460 if (ISI.ThePPLexer == 0) continue; // Scan for a real lexer.
462 // Once we find a real lexer, mark it as raw mode (disabling macro
463 // expansions) and preprocessor mode (return EOD). We know that the lexer
464 // was *not* in raw mode before, because the macro that the comment came
465 // from was expanded. However, it could have already been in preprocessor
466 // mode (#if COMMENT) in which case we have to return it to that mode and
468 FoundLexer = ISI.ThePPLexer;
469 FoundLexer->LexingRawMode = true;
470 LexerWasInPPMode = FoundLexer->ParsingPreprocessorDirective;
471 FoundLexer->ParsingPreprocessorDirective = true;
475 // Okay, we either found and switched over the lexer, or we didn't find a
476 // lexer. In either case, finish off the macro the comment came from, getting
478 if (!HandleEndOfTokenLexer(Tok)) Lex(Tok);
480 // Discarding comments as long as we don't have EOF or EOD. This 'comments
481 // out' the rest of the line, including any tokens that came from other macros
482 // that were active, as in:
483 // #define submacro a COMMENT b
485 // which should lex to 'a' only: 'b' and 'c' should be removed.
486 while (Tok.isNot(tok::eod) && Tok.isNot(tok::eof))
489 // If we got an eod token, then we successfully found the end of the line.
490 if (Tok.is(tok::eod)) {
491 assert(FoundLexer && "Can't get end of line without an active lexer");
492 // Restore the lexer back to normal mode instead of raw mode.
493 FoundLexer->LexingRawMode = false;
495 // If the lexer was already in preprocessor mode, just return the EOD token
496 // to finish the preprocessor line.
497 if (LexerWasInPPMode) return;
499 // Otherwise, switch out of PP mode and return the next lexed token.
500 FoundLexer->ParsingPreprocessorDirective = false;
504 // If we got an EOF token, then we reached the end of the token stream but
505 // didn't find an explicit \n. This can only happen if there was no lexer
506 // active (an active lexer would return EOD at EOF if there was no \n in
507 // preprocessor directive mode), so just return EOF as our token.
508 assert(!FoundLexer && "Lexer should return EOD before EOF in PP mode");