1f4a2713aSLionel Sambuc //===--- PPLexerChange.cpp - Handle changing lexers in the preprocessor ---===//
2f4a2713aSLionel Sambuc //
3f4a2713aSLionel Sambuc // The LLVM Compiler Infrastructure
4f4a2713aSLionel Sambuc //
5f4a2713aSLionel Sambuc // This file is distributed under the University of Illinois Open Source
6f4a2713aSLionel Sambuc // License. See LICENSE.TXT for details.
7f4a2713aSLionel Sambuc //
8f4a2713aSLionel Sambuc //===----------------------------------------------------------------------===//
9f4a2713aSLionel Sambuc //
10f4a2713aSLionel Sambuc // This file implements pieces of the Preprocessor interface that manage the
11f4a2713aSLionel Sambuc // current lexer stack.
12f4a2713aSLionel Sambuc //
13f4a2713aSLionel Sambuc //===----------------------------------------------------------------------===//
14f4a2713aSLionel Sambuc
15f4a2713aSLionel Sambuc #include "clang/Lex/Preprocessor.h"
16f4a2713aSLionel Sambuc #include "clang/Basic/FileManager.h"
17f4a2713aSLionel Sambuc #include "clang/Basic/SourceManager.h"
18f4a2713aSLionel Sambuc #include "clang/Lex/HeaderSearch.h"
19f4a2713aSLionel Sambuc #include "clang/Lex/LexDiagnostic.h"
20f4a2713aSLionel Sambuc #include "clang/Lex/MacroInfo.h"
21f4a2713aSLionel Sambuc #include "llvm/ADT/StringSwitch.h"
22f4a2713aSLionel Sambuc #include "llvm/Support/FileSystem.h"
23f4a2713aSLionel Sambuc #include "llvm/Support/MemoryBuffer.h"
24f4a2713aSLionel Sambuc #include "llvm/Support/Path.h"
25f4a2713aSLionel Sambuc using namespace clang;
26f4a2713aSLionel Sambuc
~PPCallbacks()27f4a2713aSLionel Sambuc PPCallbacks::~PPCallbacks() {}
28f4a2713aSLionel Sambuc
29f4a2713aSLionel Sambuc //===----------------------------------------------------------------------===//
30f4a2713aSLionel Sambuc // Miscellaneous Methods.
31f4a2713aSLionel Sambuc //===----------------------------------------------------------------------===//
32f4a2713aSLionel Sambuc
33f4a2713aSLionel Sambuc /// isInPrimaryFile - Return true if we're in the top-level file, not in a
34f4a2713aSLionel Sambuc /// \#include. This looks through macro expansions and active _Pragma lexers.
isInPrimaryFile() const35f4a2713aSLionel Sambuc bool Preprocessor::isInPrimaryFile() const {
36f4a2713aSLionel Sambuc if (IsFileLexer())
37f4a2713aSLionel Sambuc return IncludeMacroStack.empty();
38f4a2713aSLionel Sambuc
39f4a2713aSLionel Sambuc // If there are any stacked lexers, we're in a #include.
40f4a2713aSLionel Sambuc assert(IsFileLexer(IncludeMacroStack[0]) &&
41f4a2713aSLionel Sambuc "Top level include stack isn't our primary lexer?");
42f4a2713aSLionel Sambuc for (unsigned i = 1, e = IncludeMacroStack.size(); i != e; ++i)
43f4a2713aSLionel Sambuc if (IsFileLexer(IncludeMacroStack[i]))
44f4a2713aSLionel Sambuc return false;
45f4a2713aSLionel Sambuc return true;
46f4a2713aSLionel Sambuc }
47f4a2713aSLionel Sambuc
48f4a2713aSLionel Sambuc /// getCurrentLexer - Return the current file lexer being lexed from. Note
49f4a2713aSLionel Sambuc /// that this ignores any potentially active macro expansions and _Pragma
50f4a2713aSLionel Sambuc /// expansions going on at the time.
getCurrentFileLexer() const51f4a2713aSLionel Sambuc PreprocessorLexer *Preprocessor::getCurrentFileLexer() const {
52f4a2713aSLionel Sambuc if (IsFileLexer())
53f4a2713aSLionel Sambuc return CurPPLexer;
54f4a2713aSLionel Sambuc
55f4a2713aSLionel Sambuc // Look for a stacked lexer.
56f4a2713aSLionel Sambuc for (unsigned i = IncludeMacroStack.size(); i != 0; --i) {
57f4a2713aSLionel Sambuc const IncludeStackInfo& ISI = IncludeMacroStack[i-1];
58f4a2713aSLionel Sambuc if (IsFileLexer(ISI))
59f4a2713aSLionel Sambuc return ISI.ThePPLexer;
60f4a2713aSLionel Sambuc }
61*0a6a1f1dSLionel Sambuc return nullptr;
62f4a2713aSLionel Sambuc }
63f4a2713aSLionel Sambuc
64f4a2713aSLionel Sambuc
65f4a2713aSLionel Sambuc //===----------------------------------------------------------------------===//
66f4a2713aSLionel Sambuc // Methods for Entering and Callbacks for leaving various contexts
67f4a2713aSLionel Sambuc //===----------------------------------------------------------------------===//
68f4a2713aSLionel Sambuc
69f4a2713aSLionel Sambuc /// EnterSourceFile - Add a source file to the top of the include stack and
70f4a2713aSLionel Sambuc /// start lexing tokens from it instead of the current buffer.
EnterSourceFile(FileID FID,const DirectoryLookup * CurDir,SourceLocation Loc)71*0a6a1f1dSLionel Sambuc bool Preprocessor::EnterSourceFile(FileID FID, const DirectoryLookup *CurDir,
72f4a2713aSLionel Sambuc SourceLocation Loc) {
73f4a2713aSLionel Sambuc assert(!CurTokenLexer && "Cannot #include a file inside a macro!");
74f4a2713aSLionel Sambuc ++NumEnteredSourceFiles;
75f4a2713aSLionel Sambuc
76f4a2713aSLionel Sambuc if (MaxIncludeStackDepth < IncludeMacroStack.size())
77f4a2713aSLionel Sambuc MaxIncludeStackDepth = IncludeMacroStack.size();
78f4a2713aSLionel Sambuc
79f4a2713aSLionel Sambuc if (PTH) {
80f4a2713aSLionel Sambuc if (PTHLexer *PL = PTH->CreateLexer(FID)) {
81f4a2713aSLionel Sambuc EnterSourceFileWithPTH(PL, CurDir);
82*0a6a1f1dSLionel Sambuc return false;
83f4a2713aSLionel Sambuc }
84f4a2713aSLionel Sambuc }
85f4a2713aSLionel Sambuc
86f4a2713aSLionel Sambuc // Get the MemoryBuffer for this FID, if it fails, we fail.
87f4a2713aSLionel Sambuc bool Invalid = false;
88f4a2713aSLionel Sambuc const llvm::MemoryBuffer *InputFile =
89f4a2713aSLionel Sambuc getSourceManager().getBuffer(FID, Loc, &Invalid);
90f4a2713aSLionel Sambuc if (Invalid) {
91f4a2713aSLionel Sambuc SourceLocation FileStart = SourceMgr.getLocForStartOfFile(FID);
92f4a2713aSLionel Sambuc Diag(Loc, diag::err_pp_error_opening_file)
93f4a2713aSLionel Sambuc << std::string(SourceMgr.getBufferName(FileStart)) << "";
94*0a6a1f1dSLionel Sambuc return true;
95f4a2713aSLionel Sambuc }
96f4a2713aSLionel Sambuc
97f4a2713aSLionel Sambuc if (isCodeCompletionEnabled() &&
98f4a2713aSLionel Sambuc SourceMgr.getFileEntryForID(FID) == CodeCompletionFile) {
99f4a2713aSLionel Sambuc CodeCompletionFileLoc = SourceMgr.getLocForStartOfFile(FID);
100f4a2713aSLionel Sambuc CodeCompletionLoc =
101f4a2713aSLionel Sambuc CodeCompletionFileLoc.getLocWithOffset(CodeCompletionOffset);
102f4a2713aSLionel Sambuc }
103f4a2713aSLionel Sambuc
104f4a2713aSLionel Sambuc EnterSourceFileWithLexer(new Lexer(FID, InputFile, *this), CurDir);
105*0a6a1f1dSLionel Sambuc return false;
106f4a2713aSLionel Sambuc }
107f4a2713aSLionel Sambuc
108f4a2713aSLionel Sambuc /// EnterSourceFileWithLexer - Add a source file to the top of the include stack
109f4a2713aSLionel Sambuc /// and start lexing tokens from it instead of the current buffer.
EnterSourceFileWithLexer(Lexer * TheLexer,const DirectoryLookup * CurDir)110f4a2713aSLionel Sambuc void Preprocessor::EnterSourceFileWithLexer(Lexer *TheLexer,
111f4a2713aSLionel Sambuc const DirectoryLookup *CurDir) {
112f4a2713aSLionel Sambuc
113f4a2713aSLionel Sambuc // Add the current lexer to the include stack.
114f4a2713aSLionel Sambuc if (CurPPLexer || CurTokenLexer)
115f4a2713aSLionel Sambuc PushIncludeMacroStack();
116f4a2713aSLionel Sambuc
117f4a2713aSLionel Sambuc CurLexer.reset(TheLexer);
118f4a2713aSLionel Sambuc CurPPLexer = TheLexer;
119f4a2713aSLionel Sambuc CurDirLookup = CurDir;
120*0a6a1f1dSLionel Sambuc CurSubmodule = nullptr;
121f4a2713aSLionel Sambuc if (CurLexerKind != CLK_LexAfterModuleImport)
122f4a2713aSLionel Sambuc CurLexerKind = CLK_Lexer;
123f4a2713aSLionel Sambuc
124f4a2713aSLionel Sambuc // Notify the client, if desired, that we are in a new source file.
125f4a2713aSLionel Sambuc if (Callbacks && !CurLexer->Is_PragmaLexer) {
126f4a2713aSLionel Sambuc SrcMgr::CharacteristicKind FileType =
127f4a2713aSLionel Sambuc SourceMgr.getFileCharacteristic(CurLexer->getFileLoc());
128f4a2713aSLionel Sambuc
129f4a2713aSLionel Sambuc Callbacks->FileChanged(CurLexer->getFileLoc(),
130f4a2713aSLionel Sambuc PPCallbacks::EnterFile, FileType);
131f4a2713aSLionel Sambuc }
132f4a2713aSLionel Sambuc }
133f4a2713aSLionel Sambuc
134f4a2713aSLionel Sambuc /// EnterSourceFileWithPTH - Add a source file to the top of the include stack
135f4a2713aSLionel Sambuc /// and start getting tokens from it using the PTH cache.
EnterSourceFileWithPTH(PTHLexer * PL,const DirectoryLookup * CurDir)136f4a2713aSLionel Sambuc void Preprocessor::EnterSourceFileWithPTH(PTHLexer *PL,
137f4a2713aSLionel Sambuc const DirectoryLookup *CurDir) {
138f4a2713aSLionel Sambuc
139f4a2713aSLionel Sambuc if (CurPPLexer || CurTokenLexer)
140f4a2713aSLionel Sambuc PushIncludeMacroStack();
141f4a2713aSLionel Sambuc
142f4a2713aSLionel Sambuc CurDirLookup = CurDir;
143f4a2713aSLionel Sambuc CurPTHLexer.reset(PL);
144f4a2713aSLionel Sambuc CurPPLexer = CurPTHLexer.get();
145*0a6a1f1dSLionel Sambuc CurSubmodule = nullptr;
146f4a2713aSLionel Sambuc if (CurLexerKind != CLK_LexAfterModuleImport)
147f4a2713aSLionel Sambuc CurLexerKind = CLK_PTHLexer;
148f4a2713aSLionel Sambuc
149f4a2713aSLionel Sambuc // Notify the client, if desired, that we are in a new source file.
150f4a2713aSLionel Sambuc if (Callbacks) {
151f4a2713aSLionel Sambuc FileID FID = CurPPLexer->getFileID();
152f4a2713aSLionel Sambuc SourceLocation EnterLoc = SourceMgr.getLocForStartOfFile(FID);
153f4a2713aSLionel Sambuc SrcMgr::CharacteristicKind FileType =
154f4a2713aSLionel Sambuc SourceMgr.getFileCharacteristic(EnterLoc);
155f4a2713aSLionel Sambuc Callbacks->FileChanged(EnterLoc, PPCallbacks::EnterFile, FileType);
156f4a2713aSLionel Sambuc }
157f4a2713aSLionel Sambuc }
158f4a2713aSLionel Sambuc
159f4a2713aSLionel Sambuc /// EnterMacro - Add a Macro to the top of the include stack and start lexing
160f4a2713aSLionel Sambuc /// tokens from it instead of the current buffer.
EnterMacro(Token & Tok,SourceLocation ILEnd,MacroInfo * Macro,MacroArgs * Args)161f4a2713aSLionel Sambuc void Preprocessor::EnterMacro(Token &Tok, SourceLocation ILEnd,
162f4a2713aSLionel Sambuc MacroInfo *Macro, MacroArgs *Args) {
163*0a6a1f1dSLionel Sambuc std::unique_ptr<TokenLexer> TokLexer;
164f4a2713aSLionel Sambuc if (NumCachedTokenLexers == 0) {
165*0a6a1f1dSLionel Sambuc TokLexer = llvm::make_unique<TokenLexer>(Tok, ILEnd, Macro, Args, *this);
166f4a2713aSLionel Sambuc } else {
167*0a6a1f1dSLionel Sambuc TokLexer = std::move(TokenLexerCache[--NumCachedTokenLexers]);
168f4a2713aSLionel Sambuc TokLexer->Init(Tok, ILEnd, Macro, Args);
169f4a2713aSLionel Sambuc }
170f4a2713aSLionel Sambuc
171f4a2713aSLionel Sambuc PushIncludeMacroStack();
172*0a6a1f1dSLionel Sambuc CurDirLookup = nullptr;
173*0a6a1f1dSLionel Sambuc CurTokenLexer = std::move(TokLexer);
174f4a2713aSLionel Sambuc if (CurLexerKind != CLK_LexAfterModuleImport)
175f4a2713aSLionel Sambuc CurLexerKind = CLK_TokenLexer;
176f4a2713aSLionel Sambuc }
177f4a2713aSLionel Sambuc
178f4a2713aSLionel Sambuc /// EnterTokenStream - Add a "macro" context to the top of the include stack,
179f4a2713aSLionel Sambuc /// which will cause the lexer to start returning the specified tokens.
180f4a2713aSLionel Sambuc ///
181f4a2713aSLionel Sambuc /// If DisableMacroExpansion is true, tokens lexed from the token stream will
182f4a2713aSLionel Sambuc /// not be subject to further macro expansion. Otherwise, these tokens will
183f4a2713aSLionel Sambuc /// be re-macro-expanded when/if expansion is enabled.
184f4a2713aSLionel Sambuc ///
185f4a2713aSLionel Sambuc /// If OwnsTokens is false, this method assumes that the specified stream of
186f4a2713aSLionel Sambuc /// tokens has a permanent owner somewhere, so they do not need to be copied.
187f4a2713aSLionel Sambuc /// If it is true, it assumes the array of tokens is allocated with new[] and
188f4a2713aSLionel Sambuc /// must be freed.
189f4a2713aSLionel Sambuc ///
EnterTokenStream(const Token * Toks,unsigned NumToks,bool DisableMacroExpansion,bool OwnsTokens)190f4a2713aSLionel Sambuc void Preprocessor::EnterTokenStream(const Token *Toks, unsigned NumToks,
191f4a2713aSLionel Sambuc bool DisableMacroExpansion,
192f4a2713aSLionel Sambuc bool OwnsTokens) {
193*0a6a1f1dSLionel Sambuc if (CurLexerKind == CLK_CachingLexer) {
194*0a6a1f1dSLionel Sambuc if (CachedLexPos < CachedTokens.size()) {
195*0a6a1f1dSLionel Sambuc // We're entering tokens into the middle of our cached token stream. We
196*0a6a1f1dSLionel Sambuc // can't represent that, so just insert the tokens into the buffer.
197*0a6a1f1dSLionel Sambuc CachedTokens.insert(CachedTokens.begin() + CachedLexPos,
198*0a6a1f1dSLionel Sambuc Toks, Toks + NumToks);
199*0a6a1f1dSLionel Sambuc if (OwnsTokens)
200*0a6a1f1dSLionel Sambuc delete [] Toks;
201*0a6a1f1dSLionel Sambuc return;
202*0a6a1f1dSLionel Sambuc }
203*0a6a1f1dSLionel Sambuc
204*0a6a1f1dSLionel Sambuc // New tokens are at the end of the cached token sequnece; insert the
205*0a6a1f1dSLionel Sambuc // token stream underneath the caching lexer.
206*0a6a1f1dSLionel Sambuc ExitCachingLexMode();
207*0a6a1f1dSLionel Sambuc EnterTokenStream(Toks, NumToks, DisableMacroExpansion, OwnsTokens);
208*0a6a1f1dSLionel Sambuc EnterCachingLexMode();
209*0a6a1f1dSLionel Sambuc return;
210*0a6a1f1dSLionel Sambuc }
211*0a6a1f1dSLionel Sambuc
212f4a2713aSLionel Sambuc // Create a macro expander to expand from the specified token stream.
213*0a6a1f1dSLionel Sambuc std::unique_ptr<TokenLexer> TokLexer;
214f4a2713aSLionel Sambuc if (NumCachedTokenLexers == 0) {
215*0a6a1f1dSLionel Sambuc TokLexer = llvm::make_unique<TokenLexer>(
216*0a6a1f1dSLionel Sambuc Toks, NumToks, DisableMacroExpansion, OwnsTokens, *this);
217f4a2713aSLionel Sambuc } else {
218*0a6a1f1dSLionel Sambuc TokLexer = std::move(TokenLexerCache[--NumCachedTokenLexers]);
219f4a2713aSLionel Sambuc TokLexer->Init(Toks, NumToks, DisableMacroExpansion, OwnsTokens);
220f4a2713aSLionel Sambuc }
221f4a2713aSLionel Sambuc
222f4a2713aSLionel Sambuc // Save our current state.
223f4a2713aSLionel Sambuc PushIncludeMacroStack();
224*0a6a1f1dSLionel Sambuc CurDirLookup = nullptr;
225*0a6a1f1dSLionel Sambuc CurTokenLexer = std::move(TokLexer);
226f4a2713aSLionel Sambuc if (CurLexerKind != CLK_LexAfterModuleImport)
227f4a2713aSLionel Sambuc CurLexerKind = CLK_TokenLexer;
228f4a2713aSLionel Sambuc }
229f4a2713aSLionel Sambuc
230f4a2713aSLionel Sambuc /// \brief Compute the relative path that names the given file relative to
231f4a2713aSLionel Sambuc /// the given directory.
computeRelativePath(FileManager & FM,const DirectoryEntry * Dir,const FileEntry * File,SmallString<128> & Result)232f4a2713aSLionel Sambuc static void computeRelativePath(FileManager &FM, const DirectoryEntry *Dir,
233f4a2713aSLionel Sambuc const FileEntry *File,
234f4a2713aSLionel Sambuc SmallString<128> &Result) {
235f4a2713aSLionel Sambuc Result.clear();
236f4a2713aSLionel Sambuc
237f4a2713aSLionel Sambuc StringRef FilePath = File->getDir()->getName();
238f4a2713aSLionel Sambuc StringRef Path = FilePath;
239f4a2713aSLionel Sambuc while (!Path.empty()) {
240f4a2713aSLionel Sambuc if (const DirectoryEntry *CurDir = FM.getDirectory(Path)) {
241f4a2713aSLionel Sambuc if (CurDir == Dir) {
242f4a2713aSLionel Sambuc Result = FilePath.substr(Path.size());
243f4a2713aSLionel Sambuc llvm::sys::path::append(Result,
244f4a2713aSLionel Sambuc llvm::sys::path::filename(File->getName()));
245f4a2713aSLionel Sambuc return;
246f4a2713aSLionel Sambuc }
247f4a2713aSLionel Sambuc }
248f4a2713aSLionel Sambuc
249f4a2713aSLionel Sambuc Path = llvm::sys::path::parent_path(Path);
250f4a2713aSLionel Sambuc }
251f4a2713aSLionel Sambuc
252f4a2713aSLionel Sambuc Result = File->getName();
253f4a2713aSLionel Sambuc }
254f4a2713aSLionel Sambuc
PropagateLineStartLeadingSpaceInfo(Token & Result)255f4a2713aSLionel Sambuc void Preprocessor::PropagateLineStartLeadingSpaceInfo(Token &Result) {
256f4a2713aSLionel Sambuc if (CurTokenLexer) {
257f4a2713aSLionel Sambuc CurTokenLexer->PropagateLineStartLeadingSpaceInfo(Result);
258f4a2713aSLionel Sambuc return;
259f4a2713aSLionel Sambuc }
260f4a2713aSLionel Sambuc if (CurLexer) {
261f4a2713aSLionel Sambuc CurLexer->PropagateLineStartLeadingSpaceInfo(Result);
262f4a2713aSLionel Sambuc return;
263f4a2713aSLionel Sambuc }
264f4a2713aSLionel Sambuc // FIXME: Handle other kinds of lexers? It generally shouldn't matter,
265f4a2713aSLionel Sambuc // but it might if they're empty?
266f4a2713aSLionel Sambuc }
267f4a2713aSLionel Sambuc
268*0a6a1f1dSLionel Sambuc /// \brief Determine the location to use as the end of the buffer for a lexer.
269*0a6a1f1dSLionel Sambuc ///
270*0a6a1f1dSLionel Sambuc /// If the file ends with a newline, form the EOF token on the newline itself,
271*0a6a1f1dSLionel Sambuc /// rather than "on the line following it", which doesn't exist. This makes
272*0a6a1f1dSLionel Sambuc /// diagnostics relating to the end of file include the last file that the user
273*0a6a1f1dSLionel Sambuc /// actually typed, which is goodness.
getCurLexerEndPos()274*0a6a1f1dSLionel Sambuc const char *Preprocessor::getCurLexerEndPos() {
275*0a6a1f1dSLionel Sambuc const char *EndPos = CurLexer->BufferEnd;
276*0a6a1f1dSLionel Sambuc if (EndPos != CurLexer->BufferStart &&
277*0a6a1f1dSLionel Sambuc (EndPos[-1] == '\n' || EndPos[-1] == '\r')) {
278*0a6a1f1dSLionel Sambuc --EndPos;
279*0a6a1f1dSLionel Sambuc
280*0a6a1f1dSLionel Sambuc // Handle \n\r and \r\n:
281*0a6a1f1dSLionel Sambuc if (EndPos != CurLexer->BufferStart &&
282*0a6a1f1dSLionel Sambuc (EndPos[-1] == '\n' || EndPos[-1] == '\r') &&
283*0a6a1f1dSLionel Sambuc EndPos[-1] != EndPos[0])
284*0a6a1f1dSLionel Sambuc --EndPos;
285*0a6a1f1dSLionel Sambuc }
286*0a6a1f1dSLionel Sambuc
287*0a6a1f1dSLionel Sambuc return EndPos;
288*0a6a1f1dSLionel Sambuc }
289*0a6a1f1dSLionel Sambuc
290*0a6a1f1dSLionel Sambuc
291f4a2713aSLionel Sambuc /// HandleEndOfFile - This callback is invoked when the lexer hits the end of
292f4a2713aSLionel Sambuc /// the current file. This either returns the EOF token or pops a level off
293f4a2713aSLionel Sambuc /// the include stack and keeps going.
HandleEndOfFile(Token & Result,bool isEndOfMacro)294f4a2713aSLionel Sambuc bool Preprocessor::HandleEndOfFile(Token &Result, bool isEndOfMacro) {
295f4a2713aSLionel Sambuc assert(!CurTokenLexer &&
296f4a2713aSLionel Sambuc "Ending a file when currently in a macro!");
297f4a2713aSLionel Sambuc
298f4a2713aSLionel Sambuc // See if this file had a controlling macro.
299f4a2713aSLionel Sambuc if (CurPPLexer) { // Not ending a macro, ignore it.
300f4a2713aSLionel Sambuc if (const IdentifierInfo *ControllingMacro =
301f4a2713aSLionel Sambuc CurPPLexer->MIOpt.GetControllingMacroAtEndOfFile()) {
302f4a2713aSLionel Sambuc // Okay, this has a controlling macro, remember in HeaderFileInfo.
303f4a2713aSLionel Sambuc if (const FileEntry *FE =
304f4a2713aSLionel Sambuc SourceMgr.getFileEntryForID(CurPPLexer->getFileID())) {
305f4a2713aSLionel Sambuc HeaderInfo.SetFileControllingMacro(FE, ControllingMacro);
306*0a6a1f1dSLionel Sambuc if (MacroInfo *MI =
307*0a6a1f1dSLionel Sambuc getMacroInfo(const_cast<IdentifierInfo*>(ControllingMacro))) {
308*0a6a1f1dSLionel Sambuc MI->UsedForHeaderGuard = true;
309*0a6a1f1dSLionel Sambuc }
310f4a2713aSLionel Sambuc if (const IdentifierInfo *DefinedMacro =
311f4a2713aSLionel Sambuc CurPPLexer->MIOpt.GetDefinedMacro()) {
312f4a2713aSLionel Sambuc if (!ControllingMacro->hasMacroDefinition() &&
313f4a2713aSLionel Sambuc DefinedMacro != ControllingMacro &&
314f4a2713aSLionel Sambuc HeaderInfo.FirstTimeLexingFile(FE)) {
315f4a2713aSLionel Sambuc
316f4a2713aSLionel Sambuc // If the edit distance between the two macros is more than 50%,
317f4a2713aSLionel Sambuc // DefinedMacro may not be header guard, or can be header guard of
318f4a2713aSLionel Sambuc // another header file. Therefore, it maybe defining something
319f4a2713aSLionel Sambuc // completely different. This can be observed in the wild when
320f4a2713aSLionel Sambuc // handling feature macros or header guards in different files.
321f4a2713aSLionel Sambuc
322f4a2713aSLionel Sambuc const StringRef ControllingMacroName = ControllingMacro->getName();
323f4a2713aSLionel Sambuc const StringRef DefinedMacroName = DefinedMacro->getName();
324f4a2713aSLionel Sambuc const size_t MaxHalfLength = std::max(ControllingMacroName.size(),
325f4a2713aSLionel Sambuc DefinedMacroName.size()) / 2;
326f4a2713aSLionel Sambuc const unsigned ED = ControllingMacroName.edit_distance(
327f4a2713aSLionel Sambuc DefinedMacroName, true, MaxHalfLength);
328f4a2713aSLionel Sambuc if (ED <= MaxHalfLength) {
329f4a2713aSLionel Sambuc // Emit a warning for a bad header guard.
330f4a2713aSLionel Sambuc Diag(CurPPLexer->MIOpt.GetMacroLocation(),
331f4a2713aSLionel Sambuc diag::warn_header_guard)
332f4a2713aSLionel Sambuc << CurPPLexer->MIOpt.GetMacroLocation() << ControllingMacro;
333f4a2713aSLionel Sambuc Diag(CurPPLexer->MIOpt.GetDefinedLocation(),
334f4a2713aSLionel Sambuc diag::note_header_guard)
335f4a2713aSLionel Sambuc << CurPPLexer->MIOpt.GetDefinedLocation() << DefinedMacro
336f4a2713aSLionel Sambuc << ControllingMacro
337f4a2713aSLionel Sambuc << FixItHint::CreateReplacement(
338f4a2713aSLionel Sambuc CurPPLexer->MIOpt.GetDefinedLocation(),
339f4a2713aSLionel Sambuc ControllingMacro->getName());
340f4a2713aSLionel Sambuc }
341f4a2713aSLionel Sambuc }
342f4a2713aSLionel Sambuc }
343f4a2713aSLionel Sambuc }
344f4a2713aSLionel Sambuc }
345f4a2713aSLionel Sambuc }
346f4a2713aSLionel Sambuc
347f4a2713aSLionel Sambuc // Complain about reaching a true EOF within arc_cf_code_audited.
348f4a2713aSLionel Sambuc // We don't want to complain about reaching the end of a macro
349f4a2713aSLionel Sambuc // instantiation or a _Pragma.
350f4a2713aSLionel Sambuc if (PragmaARCCFCodeAuditedLoc.isValid() &&
351f4a2713aSLionel Sambuc !isEndOfMacro && !(CurLexer && CurLexer->Is_PragmaLexer)) {
352f4a2713aSLionel Sambuc Diag(PragmaARCCFCodeAuditedLoc, diag::err_pp_eof_in_arc_cf_code_audited);
353f4a2713aSLionel Sambuc
354f4a2713aSLionel Sambuc // Recover by leaving immediately.
355f4a2713aSLionel Sambuc PragmaARCCFCodeAuditedLoc = SourceLocation();
356f4a2713aSLionel Sambuc }
357f4a2713aSLionel Sambuc
358f4a2713aSLionel Sambuc // If this is a #include'd file, pop it off the include stack and continue
359f4a2713aSLionel Sambuc // lexing the #includer file.
360f4a2713aSLionel Sambuc if (!IncludeMacroStack.empty()) {
361f4a2713aSLionel Sambuc
362f4a2713aSLionel Sambuc // If we lexed the code-completion file, act as if we reached EOF.
363f4a2713aSLionel Sambuc if (isCodeCompletionEnabled() && CurPPLexer &&
364f4a2713aSLionel Sambuc SourceMgr.getLocForStartOfFile(CurPPLexer->getFileID()) ==
365f4a2713aSLionel Sambuc CodeCompletionFileLoc) {
366f4a2713aSLionel Sambuc if (CurLexer) {
367f4a2713aSLionel Sambuc Result.startToken();
368f4a2713aSLionel Sambuc CurLexer->FormTokenWithChars(Result, CurLexer->BufferEnd, tok::eof);
369f4a2713aSLionel Sambuc CurLexer.reset();
370f4a2713aSLionel Sambuc } else {
371f4a2713aSLionel Sambuc assert(CurPTHLexer && "Got EOF but no current lexer set!");
372f4a2713aSLionel Sambuc CurPTHLexer->getEOF(Result);
373f4a2713aSLionel Sambuc CurPTHLexer.reset();
374f4a2713aSLionel Sambuc }
375f4a2713aSLionel Sambuc
376*0a6a1f1dSLionel Sambuc CurPPLexer = nullptr;
377f4a2713aSLionel Sambuc return true;
378f4a2713aSLionel Sambuc }
379f4a2713aSLionel Sambuc
380f4a2713aSLionel Sambuc if (!isEndOfMacro && CurPPLexer &&
381f4a2713aSLionel Sambuc SourceMgr.getIncludeLoc(CurPPLexer->getFileID()).isValid()) {
382f4a2713aSLionel Sambuc // Notify SourceManager to record the number of FileIDs that were created
383f4a2713aSLionel Sambuc // during lexing of the #include'd file.
384f4a2713aSLionel Sambuc unsigned NumFIDs =
385f4a2713aSLionel Sambuc SourceMgr.local_sloc_entry_size() -
386f4a2713aSLionel Sambuc CurPPLexer->getInitialNumSLocEntries() + 1/*#include'd file*/;
387f4a2713aSLionel Sambuc SourceMgr.setNumCreatedFIDsForFileID(CurPPLexer->getFileID(), NumFIDs);
388f4a2713aSLionel Sambuc }
389f4a2713aSLionel Sambuc
390f4a2713aSLionel Sambuc FileID ExitedFID;
391f4a2713aSLionel Sambuc if (Callbacks && !isEndOfMacro && CurPPLexer)
392f4a2713aSLionel Sambuc ExitedFID = CurPPLexer->getFileID();
393f4a2713aSLionel Sambuc
394*0a6a1f1dSLionel Sambuc bool LeavingSubmodule = CurSubmodule && CurLexer;
395*0a6a1f1dSLionel Sambuc if (LeavingSubmodule) {
396*0a6a1f1dSLionel Sambuc // Notify the parser that we've left the module.
397*0a6a1f1dSLionel Sambuc const char *EndPos = getCurLexerEndPos();
398*0a6a1f1dSLionel Sambuc Result.startToken();
399*0a6a1f1dSLionel Sambuc CurLexer->BufferPtr = EndPos;
400*0a6a1f1dSLionel Sambuc CurLexer->FormTokenWithChars(Result, EndPos, tok::annot_module_end);
401*0a6a1f1dSLionel Sambuc Result.setAnnotationEndLoc(Result.getLocation());
402*0a6a1f1dSLionel Sambuc Result.setAnnotationValue(CurSubmodule);
403*0a6a1f1dSLionel Sambuc }
404*0a6a1f1dSLionel Sambuc
405f4a2713aSLionel Sambuc // We're done with the #included file.
406f4a2713aSLionel Sambuc RemoveTopOfLexerStack();
407f4a2713aSLionel Sambuc
408f4a2713aSLionel Sambuc // Propagate info about start-of-line/leading white-space/etc.
409f4a2713aSLionel Sambuc PropagateLineStartLeadingSpaceInfo(Result);
410f4a2713aSLionel Sambuc
411f4a2713aSLionel Sambuc // Notify the client, if desired, that we are in a new source file.
412f4a2713aSLionel Sambuc if (Callbacks && !isEndOfMacro && CurPPLexer) {
413f4a2713aSLionel Sambuc SrcMgr::CharacteristicKind FileType =
414f4a2713aSLionel Sambuc SourceMgr.getFileCharacteristic(CurPPLexer->getSourceLocation());
415f4a2713aSLionel Sambuc Callbacks->FileChanged(CurPPLexer->getSourceLocation(),
416f4a2713aSLionel Sambuc PPCallbacks::ExitFile, FileType, ExitedFID);
417f4a2713aSLionel Sambuc }
418f4a2713aSLionel Sambuc
419*0a6a1f1dSLionel Sambuc // Client should lex another token unless we generated an EOM.
420*0a6a1f1dSLionel Sambuc return LeavingSubmodule;
421f4a2713aSLionel Sambuc }
422f4a2713aSLionel Sambuc
423*0a6a1f1dSLionel Sambuc // If this is the end of the main file, form an EOF token.
424f4a2713aSLionel Sambuc if (CurLexer) {
425*0a6a1f1dSLionel Sambuc const char *EndPos = getCurLexerEndPos();
426f4a2713aSLionel Sambuc Result.startToken();
427f4a2713aSLionel Sambuc CurLexer->BufferPtr = EndPos;
428f4a2713aSLionel Sambuc CurLexer->FormTokenWithChars(Result, EndPos, tok::eof);
429f4a2713aSLionel Sambuc
430f4a2713aSLionel Sambuc if (isCodeCompletionEnabled()) {
431f4a2713aSLionel Sambuc // Inserting the code-completion point increases the source buffer by 1,
432f4a2713aSLionel Sambuc // but the main FileID was created before inserting the point.
433f4a2713aSLionel Sambuc // Compensate by reducing the EOF location by 1, otherwise the location
434f4a2713aSLionel Sambuc // will point to the next FileID.
435f4a2713aSLionel Sambuc // FIXME: This is hacky, the code-completion point should probably be
436f4a2713aSLionel Sambuc // inserted before the main FileID is created.
437f4a2713aSLionel Sambuc if (CurLexer->getFileLoc() == CodeCompletionFileLoc)
438f4a2713aSLionel Sambuc Result.setLocation(Result.getLocation().getLocWithOffset(-1));
439f4a2713aSLionel Sambuc }
440f4a2713aSLionel Sambuc
441f4a2713aSLionel Sambuc if (!isIncrementalProcessingEnabled())
442f4a2713aSLionel Sambuc // We're done with lexing.
443f4a2713aSLionel Sambuc CurLexer.reset();
444f4a2713aSLionel Sambuc } else {
445f4a2713aSLionel Sambuc assert(CurPTHLexer && "Got EOF but no current lexer set!");
446f4a2713aSLionel Sambuc CurPTHLexer->getEOF(Result);
447f4a2713aSLionel Sambuc CurPTHLexer.reset();
448f4a2713aSLionel Sambuc }
449f4a2713aSLionel Sambuc
450f4a2713aSLionel Sambuc if (!isIncrementalProcessingEnabled())
451*0a6a1f1dSLionel Sambuc CurPPLexer = nullptr;
452f4a2713aSLionel Sambuc
453*0a6a1f1dSLionel Sambuc if (TUKind == TU_Complete) {
454*0a6a1f1dSLionel Sambuc // This is the end of the top-level file. 'WarnUnusedMacroLocs' has
455*0a6a1f1dSLionel Sambuc // collected all macro locations that we need to warn because they are not
456*0a6a1f1dSLionel Sambuc // used.
457f4a2713aSLionel Sambuc for (WarnUnusedMacroLocsTy::iterator
458*0a6a1f1dSLionel Sambuc I=WarnUnusedMacroLocs.begin(), E=WarnUnusedMacroLocs.end();
459*0a6a1f1dSLionel Sambuc I!=E; ++I)
460f4a2713aSLionel Sambuc Diag(*I, diag::pp_macro_not_used);
461*0a6a1f1dSLionel Sambuc }
462f4a2713aSLionel Sambuc
463f4a2713aSLionel Sambuc // If we are building a module that has an umbrella header, make sure that
464f4a2713aSLionel Sambuc // each of the headers within the directory covered by the umbrella header
465f4a2713aSLionel Sambuc // was actually included by the umbrella header.
466f4a2713aSLionel Sambuc if (Module *Mod = getCurrentModule()) {
467f4a2713aSLionel Sambuc if (Mod->getUmbrellaHeader()) {
468f4a2713aSLionel Sambuc SourceLocation StartLoc
469f4a2713aSLionel Sambuc = SourceMgr.getLocForStartOfFile(SourceMgr.getMainFileID());
470f4a2713aSLionel Sambuc
471*0a6a1f1dSLionel Sambuc if (!getDiagnostics().isIgnored(diag::warn_uncovered_module_header,
472*0a6a1f1dSLionel Sambuc StartLoc)) {
473f4a2713aSLionel Sambuc ModuleMap &ModMap = getHeaderSearchInfo().getModuleMap();
474f4a2713aSLionel Sambuc const DirectoryEntry *Dir = Mod->getUmbrellaDir();
475*0a6a1f1dSLionel Sambuc vfs::FileSystem &FS = *FileMgr.getVirtualFileSystem();
476*0a6a1f1dSLionel Sambuc std::error_code EC;
477*0a6a1f1dSLionel Sambuc for (vfs::recursive_directory_iterator Entry(FS, Dir->getName(), EC), End;
478f4a2713aSLionel Sambuc Entry != End && !EC; Entry.increment(EC)) {
479f4a2713aSLionel Sambuc using llvm::StringSwitch;
480f4a2713aSLionel Sambuc
481f4a2713aSLionel Sambuc // Check whether this entry has an extension typically associated with
482f4a2713aSLionel Sambuc // headers.
483*0a6a1f1dSLionel Sambuc if (!StringSwitch<bool>(llvm::sys::path::extension(Entry->getName()))
484f4a2713aSLionel Sambuc .Cases(".h", ".H", ".hh", ".hpp", true)
485f4a2713aSLionel Sambuc .Default(false))
486f4a2713aSLionel Sambuc continue;
487f4a2713aSLionel Sambuc
488*0a6a1f1dSLionel Sambuc if (const FileEntry *Header =
489*0a6a1f1dSLionel Sambuc getFileManager().getFile(Entry->getName()))
490f4a2713aSLionel Sambuc if (!getSourceManager().hasFileInfo(Header)) {
491f4a2713aSLionel Sambuc if (!ModMap.isHeaderInUnavailableModule(Header)) {
492f4a2713aSLionel Sambuc // Find the relative path that would access this header.
493f4a2713aSLionel Sambuc SmallString<128> RelativePath;
494f4a2713aSLionel Sambuc computeRelativePath(FileMgr, Dir, Header, RelativePath);
495f4a2713aSLionel Sambuc Diag(StartLoc, diag::warn_uncovered_module_header)
496f4a2713aSLionel Sambuc << Mod->getFullModuleName() << RelativePath;
497f4a2713aSLionel Sambuc }
498f4a2713aSLionel Sambuc }
499f4a2713aSLionel Sambuc }
500f4a2713aSLionel Sambuc }
501f4a2713aSLionel Sambuc }
502f4a2713aSLionel Sambuc }
503f4a2713aSLionel Sambuc
504f4a2713aSLionel Sambuc return true;
505f4a2713aSLionel Sambuc }
506f4a2713aSLionel Sambuc
507f4a2713aSLionel Sambuc /// HandleEndOfTokenLexer - This callback is invoked when the current TokenLexer
508f4a2713aSLionel Sambuc /// hits the end of its token stream.
HandleEndOfTokenLexer(Token & Result)509f4a2713aSLionel Sambuc bool Preprocessor::HandleEndOfTokenLexer(Token &Result) {
510f4a2713aSLionel Sambuc assert(CurTokenLexer && !CurPPLexer &&
511f4a2713aSLionel Sambuc "Ending a macro when currently in a #include file!");
512f4a2713aSLionel Sambuc
513f4a2713aSLionel Sambuc if (!MacroExpandingLexersStack.empty() &&
514f4a2713aSLionel Sambuc MacroExpandingLexersStack.back().first == CurTokenLexer.get())
515f4a2713aSLionel Sambuc removeCachedMacroExpandedTokensOfLastLexer();
516f4a2713aSLionel Sambuc
517f4a2713aSLionel Sambuc // Delete or cache the now-dead macro expander.
518f4a2713aSLionel Sambuc if (NumCachedTokenLexers == TokenLexerCacheSize)
519f4a2713aSLionel Sambuc CurTokenLexer.reset();
520f4a2713aSLionel Sambuc else
521*0a6a1f1dSLionel Sambuc TokenLexerCache[NumCachedTokenLexers++] = std::move(CurTokenLexer);
522f4a2713aSLionel Sambuc
523f4a2713aSLionel Sambuc // Handle this like a #include file being popped off the stack.
524f4a2713aSLionel Sambuc return HandleEndOfFile(Result, true);
525f4a2713aSLionel Sambuc }
526f4a2713aSLionel Sambuc
527f4a2713aSLionel Sambuc /// RemoveTopOfLexerStack - Pop the current lexer/macro exp off the top of the
528f4a2713aSLionel Sambuc /// lexer stack. This should only be used in situations where the current
529f4a2713aSLionel Sambuc /// state of the top-of-stack lexer is unknown.
RemoveTopOfLexerStack()530f4a2713aSLionel Sambuc void Preprocessor::RemoveTopOfLexerStack() {
531f4a2713aSLionel Sambuc assert(!IncludeMacroStack.empty() && "Ran out of stack entries to load");
532f4a2713aSLionel Sambuc
533f4a2713aSLionel Sambuc if (CurTokenLexer) {
534f4a2713aSLionel Sambuc // Delete or cache the now-dead macro expander.
535f4a2713aSLionel Sambuc if (NumCachedTokenLexers == TokenLexerCacheSize)
536f4a2713aSLionel Sambuc CurTokenLexer.reset();
537f4a2713aSLionel Sambuc else
538*0a6a1f1dSLionel Sambuc TokenLexerCache[NumCachedTokenLexers++] = std::move(CurTokenLexer);
539f4a2713aSLionel Sambuc }
540f4a2713aSLionel Sambuc
541f4a2713aSLionel Sambuc PopIncludeMacroStack();
542f4a2713aSLionel Sambuc }
543f4a2713aSLionel Sambuc
544f4a2713aSLionel Sambuc /// HandleMicrosoftCommentPaste - When the macro expander pastes together a
545f4a2713aSLionel Sambuc /// comment (/##/) in microsoft mode, this method handles updating the current
546f4a2713aSLionel Sambuc /// state, returning the token on the next source line.
HandleMicrosoftCommentPaste(Token & Tok)547f4a2713aSLionel Sambuc void Preprocessor::HandleMicrosoftCommentPaste(Token &Tok) {
548f4a2713aSLionel Sambuc assert(CurTokenLexer && !CurPPLexer &&
549f4a2713aSLionel Sambuc "Pasted comment can only be formed from macro");
550f4a2713aSLionel Sambuc
551f4a2713aSLionel Sambuc // We handle this by scanning for the closest real lexer, switching it to
552f4a2713aSLionel Sambuc // raw mode and preprocessor mode. This will cause it to return \n as an
553f4a2713aSLionel Sambuc // explicit EOD token.
554*0a6a1f1dSLionel Sambuc PreprocessorLexer *FoundLexer = nullptr;
555f4a2713aSLionel Sambuc bool LexerWasInPPMode = false;
556f4a2713aSLionel Sambuc for (unsigned i = 0, e = IncludeMacroStack.size(); i != e; ++i) {
557f4a2713aSLionel Sambuc IncludeStackInfo &ISI = *(IncludeMacroStack.end()-i-1);
558*0a6a1f1dSLionel Sambuc if (ISI.ThePPLexer == nullptr) continue; // Scan for a real lexer.
559f4a2713aSLionel Sambuc
560f4a2713aSLionel Sambuc // Once we find a real lexer, mark it as raw mode (disabling macro
561f4a2713aSLionel Sambuc // expansions) and preprocessor mode (return EOD). We know that the lexer
562f4a2713aSLionel Sambuc // was *not* in raw mode before, because the macro that the comment came
563f4a2713aSLionel Sambuc // from was expanded. However, it could have already been in preprocessor
564f4a2713aSLionel Sambuc // mode (#if COMMENT) in which case we have to return it to that mode and
565f4a2713aSLionel Sambuc // return EOD.
566f4a2713aSLionel Sambuc FoundLexer = ISI.ThePPLexer;
567f4a2713aSLionel Sambuc FoundLexer->LexingRawMode = true;
568f4a2713aSLionel Sambuc LexerWasInPPMode = FoundLexer->ParsingPreprocessorDirective;
569f4a2713aSLionel Sambuc FoundLexer->ParsingPreprocessorDirective = true;
570f4a2713aSLionel Sambuc break;
571f4a2713aSLionel Sambuc }
572f4a2713aSLionel Sambuc
573f4a2713aSLionel Sambuc // Okay, we either found and switched over the lexer, or we didn't find a
574f4a2713aSLionel Sambuc // lexer. In either case, finish off the macro the comment came from, getting
575f4a2713aSLionel Sambuc // the next token.
576f4a2713aSLionel Sambuc if (!HandleEndOfTokenLexer(Tok)) Lex(Tok);
577f4a2713aSLionel Sambuc
578f4a2713aSLionel Sambuc // Discarding comments as long as we don't have EOF or EOD. This 'comments
579f4a2713aSLionel Sambuc // out' the rest of the line, including any tokens that came from other macros
580f4a2713aSLionel Sambuc // that were active, as in:
581f4a2713aSLionel Sambuc // #define submacro a COMMENT b
582f4a2713aSLionel Sambuc // submacro c
583f4a2713aSLionel Sambuc // which should lex to 'a' only: 'b' and 'c' should be removed.
584f4a2713aSLionel Sambuc while (Tok.isNot(tok::eod) && Tok.isNot(tok::eof))
585f4a2713aSLionel Sambuc Lex(Tok);
586f4a2713aSLionel Sambuc
587f4a2713aSLionel Sambuc // If we got an eod token, then we successfully found the end of the line.
588f4a2713aSLionel Sambuc if (Tok.is(tok::eod)) {
589f4a2713aSLionel Sambuc assert(FoundLexer && "Can't get end of line without an active lexer");
590f4a2713aSLionel Sambuc // Restore the lexer back to normal mode instead of raw mode.
591f4a2713aSLionel Sambuc FoundLexer->LexingRawMode = false;
592f4a2713aSLionel Sambuc
593f4a2713aSLionel Sambuc // If the lexer was already in preprocessor mode, just return the EOD token
594f4a2713aSLionel Sambuc // to finish the preprocessor line.
595f4a2713aSLionel Sambuc if (LexerWasInPPMode) return;
596f4a2713aSLionel Sambuc
597f4a2713aSLionel Sambuc // Otherwise, switch out of PP mode and return the next lexed token.
598f4a2713aSLionel Sambuc FoundLexer->ParsingPreprocessorDirective = false;
599f4a2713aSLionel Sambuc return Lex(Tok);
600f4a2713aSLionel Sambuc }
601f4a2713aSLionel Sambuc
602f4a2713aSLionel Sambuc // If we got an EOF token, then we reached the end of the token stream but
603f4a2713aSLionel Sambuc // didn't find an explicit \n. This can only happen if there was no lexer
604f4a2713aSLionel Sambuc // active (an active lexer would return EOD at EOF if there was no \n in
605f4a2713aSLionel Sambuc // preprocessor directive mode), so just return EOF as our token.
606f4a2713aSLionel Sambuc assert(!FoundLexer && "Lexer should return EOD before EOF in PP mode");
607f4a2713aSLionel Sambuc }
608