1 //===--- PPDirectives.cpp - Directive Handling for Preprocessor -----------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 ///
9 /// \file
10 /// Implements # directive processing for the Preprocessor.
11 ///
12 //===----------------------------------------------------------------------===//
13 
14 #include "clang/Basic/CharInfo.h"
15 #include "clang/Basic/FileManager.h"
16 #include "clang/Basic/IdentifierTable.h"
17 #include "clang/Basic/LangOptions.h"
18 #include "clang/Basic/Module.h"
19 #include "clang/Basic/SourceLocation.h"
20 #include "clang/Basic/SourceManager.h"
21 #include "clang/Basic/TokenKinds.h"
22 #include "clang/Lex/CodeCompletionHandler.h"
23 #include "clang/Lex/HeaderSearch.h"
24 #include "clang/Lex/LexDiagnostic.h"
25 #include "clang/Lex/LiteralSupport.h"
26 #include "clang/Lex/MacroInfo.h"
27 #include "clang/Lex/ModuleLoader.h"
28 #include "clang/Lex/ModuleMap.h"
29 #include "clang/Lex/PPCallbacks.h"
30 #include "clang/Lex/Pragma.h"
31 #include "clang/Lex/Preprocessor.h"
32 #include "clang/Lex/PreprocessorOptions.h"
33 #include "clang/Lex/Token.h"
34 #include "clang/Lex/VariadicMacroSupport.h"
35 #include "llvm/ADT/ArrayRef.h"
36 #include "llvm/ADT/ScopeExit.h"
37 #include "llvm/ADT/SmallString.h"
38 #include "llvm/ADT/SmallVector.h"
39 #include "llvm/ADT/STLExtras.h"
40 #include "llvm/ADT/StringSwitch.h"
41 #include "llvm/ADT/StringRef.h"
42 #include "llvm/Support/AlignOf.h"
43 #include "llvm/Support/ErrorHandling.h"
44 #include "llvm/Support/Path.h"
45 #include <algorithm>
46 #include <cassert>
47 #include <cstring>
48 #include <new>
49 #include <string>
50 #include <utility>
51 
52 using namespace clang;
53 
54 //===----------------------------------------------------------------------===//
55 // Utility Methods for Preprocessor Directive Handling.
56 //===----------------------------------------------------------------------===//
57 
58 MacroInfo *Preprocessor::AllocateMacroInfo(SourceLocation L) {
59   auto *MIChain = new (BP) MacroInfoChain{L, MIChainHead};
60   MIChainHead = MIChain;
61   return &MIChain->MI;
62 }
63 
64 DefMacroDirective *Preprocessor::AllocateDefMacroDirective(MacroInfo *MI,
65                                                            SourceLocation Loc) {
66   return new (BP) DefMacroDirective(MI, Loc);
67 }
68 
69 UndefMacroDirective *
70 Preprocessor::AllocateUndefMacroDirective(SourceLocation UndefLoc) {
71   return new (BP) UndefMacroDirective(UndefLoc);
72 }
73 
74 VisibilityMacroDirective *
75 Preprocessor::AllocateVisibilityMacroDirective(SourceLocation Loc,
76                                                bool isPublic) {
77   return new (BP) VisibilityMacroDirective(Loc, isPublic);
78 }
79 
80 /// Read and discard all tokens remaining on the current line until
81 /// the tok::eod token is found.
82 SourceRange Preprocessor::DiscardUntilEndOfDirective() {
83   Token Tmp;
84   SourceRange Res;
85 
86   LexUnexpandedToken(Tmp);
87   Res.setBegin(Tmp.getLocation());
88   while (Tmp.isNot(tok::eod)) {
89     assert(Tmp.isNot(tok::eof) && "EOF seen while discarding directive tokens");
90     LexUnexpandedToken(Tmp);
91   }
92   Res.setEnd(Tmp.getLocation());
93   return Res;
94 }
95 
96 /// Enumerates possible cases of #define/#undef a reserved identifier.
97 enum MacroDiag {
98   MD_NoWarn,        //> Not a reserved identifier
99   MD_KeywordDef,    //> Macro hides keyword, enabled by default
100   MD_ReservedMacro  //> #define of #undef reserved id, disabled by default
101 };
102 
103 /// Enumerates possible %select values for the pp_err_elif_after_else and
104 /// pp_err_elif_without_if diagnostics.
105 enum PPElifDiag {
106   PED_Elif,
107   PED_Elifdef,
108   PED_Elifndef
109 };
110 
111 // The -fmodule-name option tells the compiler to textually include headers in
112 // the specified module, meaning clang won't build the specified module. This is
113 // useful in a number of situations, for instance, when building a library that
114 // vends a module map, one might want to avoid hitting intermediate build
115 // products containimg the module map or avoid finding the system installed
116 // modulemap for that library.
117 static bool isForModuleBuilding(Module *M, StringRef CurrentModule,
118                                 StringRef ModuleName) {
119   StringRef TopLevelName = M->getTopLevelModuleName();
120 
121   // When building framework Foo, we wanna make sure that Foo *and* Foo_Private
122   // are textually included and no modules are built for both.
123   if (M->getTopLevelModule()->IsFramework && CurrentModule == ModuleName &&
124       !CurrentModule.endswith("_Private") && TopLevelName.endswith("_Private"))
125     TopLevelName = TopLevelName.drop_back(8);
126 
127   return TopLevelName == CurrentModule;
128 }
129 
130 static MacroDiag shouldWarnOnMacroDef(Preprocessor &PP, IdentifierInfo *II) {
131   const LangOptions &Lang = PP.getLangOpts();
132   if (isReservedInAllContexts(II->isReserved(Lang))) {
133     // list from:
134     // - https://gcc.gnu.org/onlinedocs/libstdc++/manual/using_macros.html
135     // - https://docs.microsoft.com/en-us/cpp/c-runtime-library/security-features-in-the-crt?view=msvc-160
136     // - man 7 feature_test_macros
137     // The list must be sorted for correct binary search.
138     static constexpr StringRef ReservedMacro[] = {
139         "_ATFILE_SOURCE",
140         "_BSD_SOURCE",
141         "_CRT_NONSTDC_NO_WARNINGS",
142         "_CRT_SECURE_CPP_OVERLOAD_STANDARD_NAMES",
143         "_CRT_SECURE_NO_WARNINGS",
144         "_FILE_OFFSET_BITS",
145         "_FORTIFY_SOURCE",
146         "_GLIBCXX_ASSERTIONS",
147         "_GLIBCXX_CONCEPT_CHECKS",
148         "_GLIBCXX_DEBUG",
149         "_GLIBCXX_DEBUG_PEDANTIC",
150         "_GLIBCXX_PARALLEL",
151         "_GLIBCXX_PARALLEL_ASSERTIONS",
152         "_GLIBCXX_SANITIZE_VECTOR",
153         "_GLIBCXX_USE_CXX11_ABI",
154         "_GLIBCXX_USE_DEPRECATED",
155         "_GNU_SOURCE",
156         "_ISOC11_SOURCE",
157         "_ISOC95_SOURCE",
158         "_ISOC99_SOURCE",
159         "_LARGEFILE64_SOURCE",
160         "_POSIX_C_SOURCE",
161         "_REENTRANT",
162         "_SVID_SOURCE",
163         "_THREAD_SAFE",
164         "_XOPEN_SOURCE",
165         "_XOPEN_SOURCE_EXTENDED",
166         "__STDCPP_WANT_MATH_SPEC_FUNCS__",
167         "__STDC_FORMAT_MACROS",
168     };
169     if (std::binary_search(std::begin(ReservedMacro), std::end(ReservedMacro),
170                            II->getName()))
171       return MD_NoWarn;
172 
173     return MD_ReservedMacro;
174   }
175   StringRef Text = II->getName();
176   if (II->isKeyword(Lang))
177     return MD_KeywordDef;
178   if (Lang.CPlusPlus11 && (Text.equals("override") || Text.equals("final")))
179     return MD_KeywordDef;
180   return MD_NoWarn;
181 }
182 
183 static MacroDiag shouldWarnOnMacroUndef(Preprocessor &PP, IdentifierInfo *II) {
184   const LangOptions &Lang = PP.getLangOpts();
185   // Do not warn on keyword undef.  It is generally harmless and widely used.
186   if (isReservedInAllContexts(II->isReserved(Lang)))
187     return MD_ReservedMacro;
188   return MD_NoWarn;
189 }
190 
191 // Return true if we want to issue a diagnostic by default if we
192 // encounter this name in a #include with the wrong case. For now,
193 // this includes the standard C and C++ headers, Posix headers,
194 // and Boost headers. Improper case for these #includes is a
195 // potential portability issue.
196 static bool warnByDefaultOnWrongCase(StringRef Include) {
197   // If the first component of the path is "boost", treat this like a standard header
198   // for the purposes of diagnostics.
199   if (::llvm::sys::path::begin(Include)->equals_insensitive("boost"))
200     return true;
201 
202   // "condition_variable" is the longest standard header name at 18 characters.
203   // If the include file name is longer than that, it can't be a standard header.
204   static const size_t MaxStdHeaderNameLen = 18u;
205   if (Include.size() > MaxStdHeaderNameLen)
206     return false;
207 
208   // Lowercase and normalize the search string.
209   SmallString<32> LowerInclude{Include};
210   for (char &Ch : LowerInclude) {
211     // In the ASCII range?
212     if (static_cast<unsigned char>(Ch) > 0x7f)
213       return false; // Can't be a standard header
214     // ASCII lowercase:
215     if (Ch >= 'A' && Ch <= 'Z')
216       Ch += 'a' - 'A';
217     // Normalize path separators for comparison purposes.
218     else if (::llvm::sys::path::is_separator(Ch))
219       Ch = '/';
220   }
221 
222   // The standard C/C++ and Posix headers
223   return llvm::StringSwitch<bool>(LowerInclude)
224     // C library headers
225     .Cases("assert.h", "complex.h", "ctype.h", "errno.h", "fenv.h", true)
226     .Cases("float.h", "inttypes.h", "iso646.h", "limits.h", "locale.h", true)
227     .Cases("math.h", "setjmp.h", "signal.h", "stdalign.h", "stdarg.h", true)
228     .Cases("stdatomic.h", "stdbool.h", "stddef.h", "stdint.h", "stdio.h", true)
229     .Cases("stdlib.h", "stdnoreturn.h", "string.h", "tgmath.h", "threads.h", true)
230     .Cases("time.h", "uchar.h", "wchar.h", "wctype.h", true)
231 
232     // C++ headers for C library facilities
233     .Cases("cassert", "ccomplex", "cctype", "cerrno", "cfenv", true)
234     .Cases("cfloat", "cinttypes", "ciso646", "climits", "clocale", true)
235     .Cases("cmath", "csetjmp", "csignal", "cstdalign", "cstdarg", true)
236     .Cases("cstdbool", "cstddef", "cstdint", "cstdio", "cstdlib", true)
237     .Cases("cstring", "ctgmath", "ctime", "cuchar", "cwchar", true)
238     .Case("cwctype", true)
239 
240     // C++ library headers
241     .Cases("algorithm", "fstream", "list", "regex", "thread", true)
242     .Cases("array", "functional", "locale", "scoped_allocator", "tuple", true)
243     .Cases("atomic", "future", "map", "set", "type_traits", true)
244     .Cases("bitset", "initializer_list", "memory", "shared_mutex", "typeindex", true)
245     .Cases("chrono", "iomanip", "mutex", "sstream", "typeinfo", true)
246     .Cases("codecvt", "ios", "new", "stack", "unordered_map", true)
247     .Cases("complex", "iosfwd", "numeric", "stdexcept", "unordered_set", true)
248     .Cases("condition_variable", "iostream", "ostream", "streambuf", "utility", true)
249     .Cases("deque", "istream", "queue", "string", "valarray", true)
250     .Cases("exception", "iterator", "random", "strstream", "vector", true)
251     .Cases("forward_list", "limits", "ratio", "system_error", true)
252 
253     // POSIX headers (which aren't also C headers)
254     .Cases("aio.h", "arpa/inet.h", "cpio.h", "dirent.h", "dlfcn.h", true)
255     .Cases("fcntl.h", "fmtmsg.h", "fnmatch.h", "ftw.h", "glob.h", true)
256     .Cases("grp.h", "iconv.h", "langinfo.h", "libgen.h", "monetary.h", true)
257     .Cases("mqueue.h", "ndbm.h", "net/if.h", "netdb.h", "netinet/in.h", true)
258     .Cases("netinet/tcp.h", "nl_types.h", "poll.h", "pthread.h", "pwd.h", true)
259     .Cases("regex.h", "sched.h", "search.h", "semaphore.h", "spawn.h", true)
260     .Cases("strings.h", "stropts.h", "sys/ipc.h", "sys/mman.h", "sys/msg.h", true)
261     .Cases("sys/resource.h", "sys/select.h",  "sys/sem.h", "sys/shm.h", "sys/socket.h", true)
262     .Cases("sys/stat.h", "sys/statvfs.h", "sys/time.h", "sys/times.h", "sys/types.h", true)
263     .Cases("sys/uio.h", "sys/un.h", "sys/utsname.h", "sys/wait.h", "syslog.h", true)
264     .Cases("tar.h", "termios.h", "trace.h", "ulimit.h", true)
265     .Cases("unistd.h", "utime.h", "utmpx.h", "wordexp.h", true)
266     .Default(false);
267 }
268 
269 /// Find a similar string in `Candidates`.
270 ///
271 /// \param LHS a string for a similar string in `Candidates`
272 ///
273 /// \param Candidates the candidates to find a similar string.
274 ///
275 /// \returns a similar string if exists. If no similar string exists,
276 /// returns None.
277 static Optional<StringRef> findSimilarStr(
278     StringRef LHS, const std::vector<StringRef> &Candidates) {
279   // We need to check if `Candidates` has the exact case-insensitive string
280   // because the Levenshtein distance match does not care about it.
281   for (StringRef C : Candidates) {
282     if (LHS.equals_insensitive(C)) {
283       return C;
284     }
285   }
286 
287   // Keep going with the Levenshtein distance match.
288   // If the LHS size is less than 3, use the LHS size minus 1 and if not,
289   // use the LHS size divided by 3.
290   size_t Length = LHS.size();
291   size_t MaxDist = Length < 3 ? Length - 1 : Length / 3;
292 
293   Optional<std::pair<StringRef, size_t>> SimilarStr = None;
294   for (StringRef C : Candidates) {
295     size_t CurDist = LHS.edit_distance(C, true);
296     if (CurDist <= MaxDist) {
297       if (!SimilarStr.hasValue()) {
298         // The first similar string found.
299         SimilarStr = {C, CurDist};
300       } else if (CurDist < SimilarStr->second) {
301         // More similar string found.
302         SimilarStr = {C, CurDist};
303       }
304     }
305   }
306 
307   if (SimilarStr.hasValue()) {
308     return SimilarStr->first;
309   } else {
310     return None;
311   }
312 }
313 
314 bool Preprocessor::CheckMacroName(Token &MacroNameTok, MacroUse isDefineUndef,
315                                   bool *ShadowFlag) {
316   // Missing macro name?
317   if (MacroNameTok.is(tok::eod))
318     return Diag(MacroNameTok, diag::err_pp_missing_macro_name);
319 
320   IdentifierInfo *II = MacroNameTok.getIdentifierInfo();
321   if (!II)
322     return Diag(MacroNameTok, diag::err_pp_macro_not_identifier);
323 
324   if (II->isCPlusPlusOperatorKeyword()) {
325     // C++ 2.5p2: Alternative tokens behave the same as its primary token
326     // except for their spellings.
327     Diag(MacroNameTok, getLangOpts().MicrosoftExt
328                            ? diag::ext_pp_operator_used_as_macro_name
329                            : diag::err_pp_operator_used_as_macro_name)
330         << II << MacroNameTok.getKind();
331     // Allow #defining |and| and friends for Microsoft compatibility or
332     // recovery when legacy C headers are included in C++.
333   }
334 
335   if ((isDefineUndef != MU_Other) && II->getPPKeywordID() == tok::pp_defined) {
336     // Error if defining "defined": C99 6.10.8/4, C++ [cpp.predefined]p4.
337     return Diag(MacroNameTok, diag::err_defined_macro_name);
338   }
339 
340   if (isDefineUndef == MU_Undef) {
341     auto *MI = getMacroInfo(II);
342     if (MI && MI->isBuiltinMacro()) {
343       // Warn if undefining "__LINE__" and other builtins, per C99 6.10.8/4
344       // and C++ [cpp.predefined]p4], but allow it as an extension.
345       Diag(MacroNameTok, diag::ext_pp_undef_builtin_macro);
346     }
347   }
348 
349   // If defining/undefining reserved identifier or a keyword, we need to issue
350   // a warning.
351   SourceLocation MacroNameLoc = MacroNameTok.getLocation();
352   if (ShadowFlag)
353     *ShadowFlag = false;
354   if (!SourceMgr.isInSystemHeader(MacroNameLoc) &&
355       (SourceMgr.getBufferName(MacroNameLoc) != "<built-in>")) {
356     MacroDiag D = MD_NoWarn;
357     if (isDefineUndef == MU_Define) {
358       D = shouldWarnOnMacroDef(*this, II);
359     }
360     else if (isDefineUndef == MU_Undef)
361       D = shouldWarnOnMacroUndef(*this, II);
362     if (D == MD_KeywordDef) {
363       // We do not want to warn on some patterns widely used in configuration
364       // scripts.  This requires analyzing next tokens, so do not issue warnings
365       // now, only inform caller.
366       if (ShadowFlag)
367         *ShadowFlag = true;
368     }
369     if (D == MD_ReservedMacro)
370       Diag(MacroNameTok, diag::warn_pp_macro_is_reserved_id);
371   }
372 
373   // Okay, we got a good identifier.
374   return false;
375 }
376 
377 /// Lex and validate a macro name, which occurs after a
378 /// \#define or \#undef.
379 ///
380 /// This sets the token kind to eod and discards the rest of the macro line if
381 /// the macro name is invalid.
382 ///
383 /// \param MacroNameTok Token that is expected to be a macro name.
384 /// \param isDefineUndef Context in which macro is used.
385 /// \param ShadowFlag Points to a flag that is set if macro shadows a keyword.
386 void Preprocessor::ReadMacroName(Token &MacroNameTok, MacroUse isDefineUndef,
387                                  bool *ShadowFlag) {
388   // Read the token, don't allow macro expansion on it.
389   LexUnexpandedToken(MacroNameTok);
390 
391   if (MacroNameTok.is(tok::code_completion)) {
392     if (CodeComplete)
393       CodeComplete->CodeCompleteMacroName(isDefineUndef == MU_Define);
394     setCodeCompletionReached();
395     LexUnexpandedToken(MacroNameTok);
396   }
397 
398   if (!CheckMacroName(MacroNameTok, isDefineUndef, ShadowFlag))
399     return;
400 
401   // Invalid macro name, read and discard the rest of the line and set the
402   // token kind to tok::eod if necessary.
403   if (MacroNameTok.isNot(tok::eod)) {
404     MacroNameTok.setKind(tok::eod);
405     DiscardUntilEndOfDirective();
406   }
407 }
408 
409 /// Ensure that the next token is a tok::eod token.
410 ///
411 /// If not, emit a diagnostic and consume up until the eod.  If EnableMacros is
412 /// true, then we consider macros that expand to zero tokens as being ok.
413 ///
414 /// Returns the location of the end of the directive.
415 SourceLocation Preprocessor::CheckEndOfDirective(const char *DirType,
416                                                  bool EnableMacros) {
417   Token Tmp;
418   // Lex unexpanded tokens for most directives: macros might expand to zero
419   // tokens, causing us to miss diagnosing invalid lines.  Some directives (like
420   // #line) allow empty macros.
421   if (EnableMacros)
422     Lex(Tmp);
423   else
424     LexUnexpandedToken(Tmp);
425 
426   // There should be no tokens after the directive, but we allow them as an
427   // extension.
428   while (Tmp.is(tok::comment))  // Skip comments in -C mode.
429     LexUnexpandedToken(Tmp);
430 
431   if (Tmp.is(tok::eod))
432     return Tmp.getLocation();
433 
434   // Add a fixit in GNU/C99/C++ mode.  Don't offer a fixit for strict-C89,
435   // or if this is a macro-style preprocessing directive, because it is more
436   // trouble than it is worth to insert /**/ and check that there is no /**/
437   // in the range also.
438   FixItHint Hint;
439   if ((LangOpts.GNUMode || LangOpts.C99 || LangOpts.CPlusPlus) &&
440       !CurTokenLexer)
441     Hint = FixItHint::CreateInsertion(Tmp.getLocation(),"//");
442   Diag(Tmp, diag::ext_pp_extra_tokens_at_eol) << DirType << Hint;
443   return DiscardUntilEndOfDirective().getEnd();
444 }
445 
446 void Preprocessor::SuggestTypoedDirective(const Token &Tok,
447                                           StringRef Directive,
448                                           const SourceLocation &EndLoc) const {
449   // If this is a `.S` file, treat unknown # directives as non-preprocessor
450   // directives.
451   if (getLangOpts().AsmPreprocessor) return;
452 
453   std::vector<StringRef> Candidates = {
454       "if", "ifdef", "ifndef", "elif", "else", "endif"
455   };
456   if (LangOpts.C2x || LangOpts.CPlusPlus2b)
457     Candidates.insert(Candidates.end(), {"elifdef", "elifndef"});
458 
459   if (Optional<StringRef> Sugg = findSimilarStr(Directive, Candidates)) {
460     CharSourceRange DirectiveRange =
461         CharSourceRange::getCharRange(Tok.getLocation(), EndLoc);
462     std::string SuggValue = Sugg.getValue().str();
463 
464     auto Hint = FixItHint::CreateReplacement(DirectiveRange, "#" + SuggValue);
465     Diag(Tok, diag::warn_pp_invalid_directive) << 1 << SuggValue << Hint;
466   }
467 }
468 
469 /// SkipExcludedConditionalBlock - We just read a \#if or related directive and
470 /// decided that the subsequent tokens are in the \#if'd out portion of the
471 /// file.  Lex the rest of the file, until we see an \#endif.  If
472 /// FoundNonSkipPortion is true, then we have already emitted code for part of
473 /// this \#if directive, so \#else/\#elif blocks should never be entered.
474 /// If ElseOk is true, then \#else directives are ok, if not, then we have
475 /// already seen one so a \#else directive is a duplicate.  When this returns,
476 /// the caller can lex the first valid token.
477 void Preprocessor::SkipExcludedConditionalBlock(SourceLocation HashTokenLoc,
478                                                 SourceLocation IfTokenLoc,
479                                                 bool FoundNonSkipPortion,
480                                                 bool FoundElse,
481                                                 SourceLocation ElseLoc) {
482   ++NumSkipped;
483   assert(!CurTokenLexer && CurPPLexer && "Lexing a macro, not a file?");
484 
485   if (PreambleConditionalStack.reachedEOFWhileSkipping())
486     PreambleConditionalStack.clearSkipInfo();
487   else
488     CurPPLexer->pushConditionalLevel(IfTokenLoc, /*isSkipping*/ false,
489                                      FoundNonSkipPortion, FoundElse);
490 
491   // Enter raw mode to disable identifier lookup (and thus macro expansion),
492   // disabling warnings, etc.
493   CurPPLexer->LexingRawMode = true;
494   Token Tok;
495   SourceLocation endLoc;
496   while (true) {
497     if (CurLexer->isDependencyDirectivesLexer()) {
498       CurLexer->LexDependencyDirectiveTokenWhileSkipping(Tok);
499     } else {
500       while (true) {
501         CurLexer->Lex(Tok);
502 
503         if (Tok.is(tok::code_completion)) {
504           setCodeCompletionReached();
505           if (CodeComplete)
506             CodeComplete->CodeCompleteInConditionalExclusion();
507           continue;
508         }
509 
510         // If this is the end of the buffer, we have an error.
511         if (Tok.is(tok::eof)) {
512           // We don't emit errors for unterminated conditionals here,
513           // Lexer::LexEndOfFile can do that properly.
514           // Just return and let the caller lex after this #include.
515           if (PreambleConditionalStack.isRecording())
516             PreambleConditionalStack.SkipInfo.emplace(HashTokenLoc, IfTokenLoc,
517                                                       FoundNonSkipPortion,
518                                                       FoundElse, ElseLoc);
519           break;
520         }
521 
522         // If this token is not a preprocessor directive, just skip it.
523         if (Tok.isNot(tok::hash) || !Tok.isAtStartOfLine())
524           continue;
525 
526         break;
527       }
528     }
529     if (Tok.is(tok::eof))
530       break;
531 
532     // We just parsed a # character at the start of a line, so we're in
533     // directive mode.  Tell the lexer this so any newlines we see will be
534     // converted into an EOD token (this terminates the macro).
535     CurPPLexer->ParsingPreprocessorDirective = true;
536     if (CurLexer) CurLexer->SetKeepWhitespaceMode(false);
537 
538 
539     // Read the next token, the directive flavor.
540     LexUnexpandedToken(Tok);
541 
542     // If this isn't an identifier directive (e.g. is "# 1\n" or "#\n", or
543     // something bogus), skip it.
544     if (Tok.isNot(tok::raw_identifier)) {
545       CurPPLexer->ParsingPreprocessorDirective = false;
546       // Restore comment saving mode.
547       if (CurLexer) CurLexer->resetExtendedTokenMode();
548       continue;
549     }
550 
551     // If the first letter isn't i or e, it isn't intesting to us.  We know that
552     // this is safe in the face of spelling differences, because there is no way
553     // to spell an i/e in a strange way that is another letter.  Skipping this
554     // allows us to avoid looking up the identifier info for #define/#undef and
555     // other common directives.
556     StringRef RI = Tok.getRawIdentifier();
557 
558     char FirstChar = RI[0];
559     if (FirstChar >= 'a' && FirstChar <= 'z' &&
560         FirstChar != 'i' && FirstChar != 'e') {
561       CurPPLexer->ParsingPreprocessorDirective = false;
562       // Restore comment saving mode.
563       if (CurLexer) CurLexer->resetExtendedTokenMode();
564       continue;
565     }
566 
567     // Get the identifier name without trigraphs or embedded newlines.  Note
568     // that we can't use Tok.getIdentifierInfo() because its lookup is disabled
569     // when skipping.
570     char DirectiveBuf[20];
571     StringRef Directive;
572     if (!Tok.needsCleaning() && RI.size() < 20) {
573       Directive = RI;
574     } else {
575       std::string DirectiveStr = getSpelling(Tok);
576       size_t IdLen = DirectiveStr.size();
577       if (IdLen >= 20) {
578         CurPPLexer->ParsingPreprocessorDirective = false;
579         // Restore comment saving mode.
580         if (CurLexer) CurLexer->resetExtendedTokenMode();
581         continue;
582       }
583       memcpy(DirectiveBuf, &DirectiveStr[0], IdLen);
584       Directive = StringRef(DirectiveBuf, IdLen);
585     }
586 
587     if (Directive.startswith("if")) {
588       StringRef Sub = Directive.substr(2);
589       if (Sub.empty() ||   // "if"
590           Sub == "def" ||   // "ifdef"
591           Sub == "ndef") {  // "ifndef"
592         // We know the entire #if/#ifdef/#ifndef block will be skipped, don't
593         // bother parsing the condition.
594         DiscardUntilEndOfDirective();
595         CurPPLexer->pushConditionalLevel(Tok.getLocation(), /*wasskipping*/true,
596                                        /*foundnonskip*/false,
597                                        /*foundelse*/false);
598       } else {
599         SuggestTypoedDirective(Tok, Directive, endLoc);
600       }
601     } else if (Directive[0] == 'e') {
602       StringRef Sub = Directive.substr(1);
603       if (Sub == "ndif") {  // "endif"
604         PPConditionalInfo CondInfo;
605         CondInfo.WasSkipping = true; // Silence bogus warning.
606         bool InCond = CurPPLexer->popConditionalLevel(CondInfo);
607         (void)InCond;  // Silence warning in no-asserts mode.
608         assert(!InCond && "Can't be skipping if not in a conditional!");
609 
610         // If we popped the outermost skipping block, we're done skipping!
611         if (!CondInfo.WasSkipping) {
612           // Restore the value of LexingRawMode so that trailing comments
613           // are handled correctly, if we've reached the outermost block.
614           CurPPLexer->LexingRawMode = false;
615           endLoc = CheckEndOfDirective("endif");
616           CurPPLexer->LexingRawMode = true;
617           if (Callbacks)
618             Callbacks->Endif(Tok.getLocation(), CondInfo.IfLoc);
619           break;
620         } else {
621           DiscardUntilEndOfDirective();
622         }
623       } else if (Sub == "lse") { // "else".
624         // #else directive in a skipping conditional.  If not in some other
625         // skipping conditional, and if #else hasn't already been seen, enter it
626         // as a non-skipping conditional.
627         PPConditionalInfo &CondInfo = CurPPLexer->peekConditionalLevel();
628 
629         // If this is a #else with a #else before it, report the error.
630         if (CondInfo.FoundElse)
631           Diag(Tok, diag::pp_err_else_after_else);
632 
633         // Note that we've seen a #else in this conditional.
634         CondInfo.FoundElse = true;
635 
636         // If the conditional is at the top level, and the #if block wasn't
637         // entered, enter the #else block now.
638         if (!CondInfo.WasSkipping && !CondInfo.FoundNonSkip) {
639           CondInfo.FoundNonSkip = true;
640           // Restore the value of LexingRawMode so that trailing comments
641           // are handled correctly.
642           CurPPLexer->LexingRawMode = false;
643           endLoc = CheckEndOfDirective("else");
644           CurPPLexer->LexingRawMode = true;
645           if (Callbacks)
646             Callbacks->Else(Tok.getLocation(), CondInfo.IfLoc);
647           break;
648         } else {
649           DiscardUntilEndOfDirective();  // C99 6.10p4.
650         }
651       } else if (Sub == "lif") {  // "elif".
652         PPConditionalInfo &CondInfo = CurPPLexer->peekConditionalLevel();
653 
654         // If this is a #elif with a #else before it, report the error.
655         if (CondInfo.FoundElse)
656           Diag(Tok, diag::pp_err_elif_after_else) << PED_Elif;
657 
658         // If this is in a skipping block or if we're already handled this #if
659         // block, don't bother parsing the condition.
660         if (CondInfo.WasSkipping || CondInfo.FoundNonSkip) {
661           // FIXME: We should probably do at least some minimal parsing of the
662           // condition to verify that it is well-formed. The current state
663           // allows #elif* directives with completely malformed (or missing)
664           // conditions.
665           DiscardUntilEndOfDirective();
666         } else {
667           // Restore the value of LexingRawMode so that identifiers are
668           // looked up, etc, inside the #elif expression.
669           assert(CurPPLexer->LexingRawMode && "We have to be skipping here!");
670           CurPPLexer->LexingRawMode = false;
671           IdentifierInfo *IfNDefMacro = nullptr;
672           DirectiveEvalResult DER = EvaluateDirectiveExpression(IfNDefMacro);
673           // Stop if Lexer became invalid after hitting code completion token.
674           if (!CurPPLexer)
675             return;
676           const bool CondValue = DER.Conditional;
677           CurPPLexer->LexingRawMode = true;
678           if (Callbacks) {
679             Callbacks->Elif(
680                 Tok.getLocation(), DER.ExprRange,
681                 (CondValue ? PPCallbacks::CVK_True : PPCallbacks::CVK_False),
682                 CondInfo.IfLoc);
683           }
684           // If this condition is true, enter it!
685           if (CondValue) {
686             CondInfo.FoundNonSkip = true;
687             break;
688           }
689         }
690       } else if (Sub == "lifdef" ||  // "elifdef"
691                  Sub == "lifndef") { // "elifndef"
692         bool IsElifDef = Sub == "lifdef";
693         PPConditionalInfo &CondInfo = CurPPLexer->peekConditionalLevel();
694         Token DirectiveToken = Tok;
695 
696         // Warn if using `#elifdef` & `#elifndef` in not C2x & C++2b mode even
697         // if this branch is in a skipping block.
698         unsigned DiagID;
699         if (LangOpts.CPlusPlus)
700           DiagID = LangOpts.CPlusPlus2b ? diag::warn_cxx2b_compat_pp_directive
701                                         : diag::ext_cxx2b_pp_directive;
702         else
703           DiagID = LangOpts.C2x ? diag::warn_c2x_compat_pp_directive
704                                 : diag::ext_c2x_pp_directive;
705         Diag(Tok, DiagID) << (IsElifDef ? PED_Elifdef : PED_Elifndef);
706 
707         // If this is a #elif with a #else before it, report the error.
708         if (CondInfo.FoundElse)
709           Diag(Tok, diag::pp_err_elif_after_else)
710               << (IsElifDef ? PED_Elifdef : PED_Elifndef);
711 
712         // If this is in a skipping block or if we're already handled this #if
713         // block, don't bother parsing the condition.
714         if (CondInfo.WasSkipping || CondInfo.FoundNonSkip) {
715           // FIXME: We should probably do at least some minimal parsing of the
716           // condition to verify that it is well-formed. The current state
717           // allows #elif* directives with completely malformed (or missing)
718           // conditions.
719           DiscardUntilEndOfDirective();
720         } else {
721           // Restore the value of LexingRawMode so that identifiers are
722           // looked up, etc, inside the #elif[n]def expression.
723           assert(CurPPLexer->LexingRawMode && "We have to be skipping here!");
724           CurPPLexer->LexingRawMode = false;
725           Token MacroNameTok;
726           ReadMacroName(MacroNameTok);
727           CurPPLexer->LexingRawMode = true;
728 
729           // If the macro name token is tok::eod, there was an error that was
730           // already reported.
731           if (MacroNameTok.is(tok::eod)) {
732             // Skip code until we get to #endif.  This helps with recovery by
733             // not emitting an error when the #endif is reached.
734             continue;
735           }
736 
737           emitMacroExpansionWarnings(MacroNameTok);
738 
739           CheckEndOfDirective(IsElifDef ? "elifdef" : "elifndef");
740 
741           IdentifierInfo *MII = MacroNameTok.getIdentifierInfo();
742           auto MD = getMacroDefinition(MII);
743           MacroInfo *MI = MD.getMacroInfo();
744 
745           if (Callbacks) {
746             if (IsElifDef) {
747               Callbacks->Elifdef(DirectiveToken.getLocation(), MacroNameTok,
748                                  MD);
749             } else {
750               Callbacks->Elifndef(DirectiveToken.getLocation(), MacroNameTok,
751                                   MD);
752             }
753           }
754           // If this condition is true, enter it!
755           if (static_cast<bool>(MI) == IsElifDef) {
756             CondInfo.FoundNonSkip = true;
757             break;
758           }
759         }
760       } else {
761         SuggestTypoedDirective(Tok, Directive, endLoc);
762       }
763     } else {
764       SuggestTypoedDirective(Tok, Directive, endLoc);
765     }
766 
767     CurPPLexer->ParsingPreprocessorDirective = false;
768     // Restore comment saving mode.
769     if (CurLexer) CurLexer->resetExtendedTokenMode();
770   }
771 
772   // Finally, if we are out of the conditional (saw an #endif or ran off the end
773   // of the file, just stop skipping and return to lexing whatever came after
774   // the #if block.
775   CurPPLexer->LexingRawMode = false;
776 
777   // The last skipped range isn't actually skipped yet if it's truncated
778   // by the end of the preamble; we'll resume parsing after the preamble.
779   if (Callbacks && (Tok.isNot(tok::eof) || !isRecordingPreamble()))
780     Callbacks->SourceRangeSkipped(
781         SourceRange(HashTokenLoc, endLoc.isValid()
782                                       ? endLoc
783                                       : CurPPLexer->getSourceLocation()),
784         Tok.getLocation());
785 }
786 
787 Module *Preprocessor::getModuleForLocation(SourceLocation Loc) {
788   if (!SourceMgr.isInMainFile(Loc)) {
789     // Try to determine the module of the include directive.
790     // FIXME: Look into directly passing the FileEntry from LookupFile instead.
791     FileID IDOfIncl = SourceMgr.getFileID(SourceMgr.getExpansionLoc(Loc));
792     if (const FileEntry *EntryOfIncl = SourceMgr.getFileEntryForID(IDOfIncl)) {
793       // The include comes from an included file.
794       return HeaderInfo.getModuleMap()
795           .findModuleForHeader(EntryOfIncl)
796           .getModule();
797     }
798   }
799 
800   // This is either in the main file or not in a file at all. It belongs
801   // to the current module, if there is one.
802   return getLangOpts().CurrentModule.empty()
803              ? nullptr
804              : HeaderInfo.lookupModule(getLangOpts().CurrentModule, Loc);
805 }
806 
807 const FileEntry *
808 Preprocessor::getHeaderToIncludeForDiagnostics(SourceLocation IncLoc,
809                                                SourceLocation Loc) {
810   Module *IncM = getModuleForLocation(IncLoc);
811 
812   // Walk up through the include stack, looking through textual headers of M
813   // until we hit a non-textual header that we can #include. (We assume textual
814   // headers of a module with non-textual headers aren't meant to be used to
815   // import entities from the module.)
816   auto &SM = getSourceManager();
817   while (!Loc.isInvalid() && !SM.isInMainFile(Loc)) {
818     auto ID = SM.getFileID(SM.getExpansionLoc(Loc));
819     auto *FE = SM.getFileEntryForID(ID);
820     if (!FE)
821       break;
822 
823     // We want to find all possible modules that might contain this header, so
824     // search all enclosing directories for module maps and load them.
825     HeaderInfo.hasModuleMap(FE->getName(), /*Root*/ nullptr,
826                             SourceMgr.isInSystemHeader(Loc));
827 
828     bool InPrivateHeader = false;
829     for (auto Header : HeaderInfo.findAllModulesForHeader(FE)) {
830       if (!Header.isAccessibleFrom(IncM)) {
831         // It's in a private header; we can't #include it.
832         // FIXME: If there's a public header in some module that re-exports it,
833         // then we could suggest including that, but it's not clear that's the
834         // expected way to make this entity visible.
835         InPrivateHeader = true;
836         continue;
837       }
838 
839       // We'll suggest including textual headers below if they're
840       // include-guarded.
841       if (Header.getRole() & ModuleMap::TextualHeader)
842         continue;
843 
844       // If we have a module import syntax, we shouldn't include a header to
845       // make a particular module visible. Let the caller know they should
846       // suggest an import instead.
847       if (getLangOpts().ObjC || getLangOpts().CPlusPlusModules ||
848           getLangOpts().ModulesTS)
849         return nullptr;
850 
851       // If this is an accessible, non-textual header of M's top-level module
852       // that transitively includes the given location and makes the
853       // corresponding module visible, this is the thing to #include.
854       return FE;
855     }
856 
857     // FIXME: If we're bailing out due to a private header, we shouldn't suggest
858     // an import either.
859     if (InPrivateHeader)
860       return nullptr;
861 
862     // If the header is includable and has an include guard, assume the
863     // intended way to expose its contents is by #include, not by importing a
864     // module that transitively includes it.
865     if (getHeaderSearchInfo().isFileMultipleIncludeGuarded(FE))
866       return FE;
867 
868     Loc = SM.getIncludeLoc(ID);
869   }
870 
871   return nullptr;
872 }
873 
874 Optional<FileEntryRef> Preprocessor::LookupFile(
875     SourceLocation FilenameLoc, StringRef Filename, bool isAngled,
876     ConstSearchDirIterator FromDir, const FileEntry *FromFile,
877     ConstSearchDirIterator *CurDirArg, SmallVectorImpl<char> *SearchPath,
878     SmallVectorImpl<char> *RelativePath,
879     ModuleMap::KnownHeader *SuggestedModule, bool *IsMapped,
880     bool *IsFrameworkFound, bool SkipCache) {
881   ConstSearchDirIterator CurDirLocal = nullptr;
882   ConstSearchDirIterator &CurDir = CurDirArg ? *CurDirArg : CurDirLocal;
883 
884   Module *RequestingModule = getModuleForLocation(FilenameLoc);
885   bool RequestingModuleIsModuleInterface = !SourceMgr.isInMainFile(FilenameLoc);
886 
887   // If the header lookup mechanism may be relative to the current inclusion
888   // stack, record the parent #includes.
889   SmallVector<std::pair<const FileEntry *, const DirectoryEntry *>, 16>
890       Includers;
891   bool BuildSystemModule = false;
892   if (!FromDir && !FromFile) {
893     FileID FID = getCurrentFileLexer()->getFileID();
894     const FileEntry *FileEnt = SourceMgr.getFileEntryForID(FID);
895 
896     // If there is no file entry associated with this file, it must be the
897     // predefines buffer or the module includes buffer. Any other file is not
898     // lexed with a normal lexer, so it won't be scanned for preprocessor
899     // directives.
900     //
901     // If we have the predefines buffer, resolve #include references (which come
902     // from the -include command line argument) from the current working
903     // directory instead of relative to the main file.
904     //
905     // If we have the module includes buffer, resolve #include references (which
906     // come from header declarations in the module map) relative to the module
907     // map file.
908     if (!FileEnt) {
909       if (FID == SourceMgr.getMainFileID() && MainFileDir) {
910         Includers.push_back(std::make_pair(nullptr, MainFileDir));
911         BuildSystemModule = getCurrentModule()->IsSystem;
912       } else if ((FileEnt =
913                     SourceMgr.getFileEntryForID(SourceMgr.getMainFileID())))
914         Includers.push_back(std::make_pair(FileEnt, *FileMgr.getDirectory(".")));
915     } else {
916       Includers.push_back(std::make_pair(FileEnt, FileEnt->getDir()));
917     }
918 
919     // MSVC searches the current include stack from top to bottom for
920     // headers included by quoted include directives.
921     // See: http://msdn.microsoft.com/en-us/library/36k2cdd4.aspx
922     if (LangOpts.MSVCCompat && !isAngled) {
923       for (IncludeStackInfo &ISEntry : llvm::reverse(IncludeMacroStack)) {
924         if (IsFileLexer(ISEntry))
925           if ((FileEnt = ISEntry.ThePPLexer->getFileEntry()))
926             Includers.push_back(std::make_pair(FileEnt, FileEnt->getDir()));
927       }
928     }
929   }
930 
931   CurDir = CurDirLookup;
932 
933   if (FromFile) {
934     // We're supposed to start looking from after a particular file. Search
935     // the include path until we find that file or run out of files.
936     ConstSearchDirIterator TmpCurDir = CurDir;
937     ConstSearchDirIterator TmpFromDir = nullptr;
938     while (Optional<FileEntryRef> FE = HeaderInfo.LookupFile(
939                Filename, FilenameLoc, isAngled, TmpFromDir, &TmpCurDir,
940                Includers, SearchPath, RelativePath, RequestingModule,
941                SuggestedModule, /*IsMapped=*/nullptr,
942                /*IsFrameworkFound=*/nullptr, SkipCache)) {
943       // Keep looking as if this file did a #include_next.
944       TmpFromDir = TmpCurDir;
945       ++TmpFromDir;
946       if (&FE->getFileEntry() == FromFile) {
947         // Found it.
948         FromDir = TmpFromDir;
949         CurDir = TmpCurDir;
950         break;
951       }
952     }
953   }
954 
955   // Do a standard file entry lookup.
956   Optional<FileEntryRef> FE = HeaderInfo.LookupFile(
957       Filename, FilenameLoc, isAngled, FromDir, &CurDir, Includers, SearchPath,
958       RelativePath, RequestingModule, SuggestedModule, IsMapped,
959       IsFrameworkFound, SkipCache, BuildSystemModule);
960   if (FE) {
961     if (SuggestedModule && !LangOpts.AsmPreprocessor)
962       HeaderInfo.getModuleMap().diagnoseHeaderInclusion(
963           RequestingModule, RequestingModuleIsModuleInterface, FilenameLoc,
964           Filename, *FE);
965     return FE;
966   }
967 
968   const FileEntry *CurFileEnt;
969   // Otherwise, see if this is a subframework header.  If so, this is relative
970   // to one of the headers on the #include stack.  Walk the list of the current
971   // headers on the #include stack and pass them to HeaderInfo.
972   if (IsFileLexer()) {
973     if ((CurFileEnt = CurPPLexer->getFileEntry())) {
974       if (Optional<FileEntryRef> FE = HeaderInfo.LookupSubframeworkHeader(
975               Filename, CurFileEnt, SearchPath, RelativePath, RequestingModule,
976               SuggestedModule)) {
977         if (SuggestedModule && !LangOpts.AsmPreprocessor)
978           HeaderInfo.getModuleMap().diagnoseHeaderInclusion(
979               RequestingModule, RequestingModuleIsModuleInterface, FilenameLoc,
980               Filename, *FE);
981         return FE;
982       }
983     }
984   }
985 
986   for (IncludeStackInfo &ISEntry : llvm::reverse(IncludeMacroStack)) {
987     if (IsFileLexer(ISEntry)) {
988       if ((CurFileEnt = ISEntry.ThePPLexer->getFileEntry())) {
989         if (Optional<FileEntryRef> FE = HeaderInfo.LookupSubframeworkHeader(
990                 Filename, CurFileEnt, SearchPath, RelativePath,
991                 RequestingModule, SuggestedModule)) {
992           if (SuggestedModule && !LangOpts.AsmPreprocessor)
993             HeaderInfo.getModuleMap().diagnoseHeaderInclusion(
994                 RequestingModule, RequestingModuleIsModuleInterface,
995                 FilenameLoc, Filename, *FE);
996           return FE;
997         }
998       }
999     }
1000   }
1001 
1002   // Otherwise, we really couldn't find the file.
1003   return None;
1004 }
1005 
1006 //===----------------------------------------------------------------------===//
1007 // Preprocessor Directive Handling.
1008 //===----------------------------------------------------------------------===//
1009 
1010 class Preprocessor::ResetMacroExpansionHelper {
1011 public:
1012   ResetMacroExpansionHelper(Preprocessor *pp)
1013     : PP(pp), save(pp->DisableMacroExpansion) {
1014     if (pp->MacroExpansionInDirectivesOverride)
1015       pp->DisableMacroExpansion = false;
1016   }
1017 
1018   ~ResetMacroExpansionHelper() {
1019     PP->DisableMacroExpansion = save;
1020   }
1021 
1022 private:
1023   Preprocessor *PP;
1024   bool save;
1025 };
1026 
1027 /// Process a directive while looking for the through header or a #pragma
1028 /// hdrstop. The following directives are handled:
1029 /// #include (to check if it is the through header)
1030 /// #define (to warn about macros that don't match the PCH)
1031 /// #pragma (to check for pragma hdrstop).
1032 /// All other directives are completely discarded.
1033 void Preprocessor::HandleSkippedDirectiveWhileUsingPCH(Token &Result,
1034                                                        SourceLocation HashLoc) {
1035   if (const IdentifierInfo *II = Result.getIdentifierInfo()) {
1036     if (II->getPPKeywordID() == tok::pp_define) {
1037       return HandleDefineDirective(Result,
1038                                    /*ImmediatelyAfterHeaderGuard=*/false);
1039     }
1040     if (SkippingUntilPCHThroughHeader &&
1041         II->getPPKeywordID() == tok::pp_include) {
1042       return HandleIncludeDirective(HashLoc, Result);
1043     }
1044     if (SkippingUntilPragmaHdrStop && II->getPPKeywordID() == tok::pp_pragma) {
1045       Lex(Result);
1046       auto *II = Result.getIdentifierInfo();
1047       if (II && II->getName() == "hdrstop")
1048         return HandlePragmaHdrstop(Result);
1049     }
1050   }
1051   DiscardUntilEndOfDirective();
1052 }
1053 
1054 /// HandleDirective - This callback is invoked when the lexer sees a # token
1055 /// at the start of a line.  This consumes the directive, modifies the
1056 /// lexer/preprocessor state, and advances the lexer(s) so that the next token
1057 /// read is the correct one.
1058 void Preprocessor::HandleDirective(Token &Result) {
1059   // FIXME: Traditional: # with whitespace before it not recognized by K&R?
1060 
1061   // We just parsed a # character at the start of a line, so we're in directive
1062   // mode.  Tell the lexer this so any newlines we see will be converted into an
1063   // EOD token (which terminates the directive).
1064   CurPPLexer->ParsingPreprocessorDirective = true;
1065   if (CurLexer) CurLexer->SetKeepWhitespaceMode(false);
1066 
1067   bool ImmediatelyAfterTopLevelIfndef =
1068       CurPPLexer->MIOpt.getImmediatelyAfterTopLevelIfndef();
1069   CurPPLexer->MIOpt.resetImmediatelyAfterTopLevelIfndef();
1070 
1071   ++NumDirectives;
1072 
1073   // We are about to read a token.  For the multiple-include optimization FA to
1074   // work, we have to remember if we had read any tokens *before* this
1075   // pp-directive.
1076   bool ReadAnyTokensBeforeDirective =CurPPLexer->MIOpt.getHasReadAnyTokensVal();
1077 
1078   // Save the '#' token in case we need to return it later.
1079   Token SavedHash = Result;
1080 
1081   // Read the next token, the directive flavor.  This isn't expanded due to
1082   // C99 6.10.3p8.
1083   LexUnexpandedToken(Result);
1084 
1085   // C99 6.10.3p11: Is this preprocessor directive in macro invocation?  e.g.:
1086   //   #define A(x) #x
1087   //   A(abc
1088   //     #warning blah
1089   //   def)
1090   // If so, the user is relying on undefined behavior, emit a diagnostic. Do
1091   // not support this for #include-like directives, since that can result in
1092   // terrible diagnostics, and does not work in GCC.
1093   if (InMacroArgs) {
1094     if (IdentifierInfo *II = Result.getIdentifierInfo()) {
1095       switch (II->getPPKeywordID()) {
1096       case tok::pp_include:
1097       case tok::pp_import:
1098       case tok::pp_include_next:
1099       case tok::pp___include_macros:
1100       case tok::pp_pragma:
1101         Diag(Result, diag::err_embedded_directive) << II->getName();
1102         Diag(*ArgMacro, diag::note_macro_expansion_here)
1103             << ArgMacro->getIdentifierInfo();
1104         DiscardUntilEndOfDirective();
1105         return;
1106       default:
1107         break;
1108       }
1109     }
1110     Diag(Result, diag::ext_embedded_directive);
1111   }
1112 
1113   // Temporarily enable macro expansion if set so
1114   // and reset to previous state when returning from this function.
1115   ResetMacroExpansionHelper helper(this);
1116 
1117   if (SkippingUntilPCHThroughHeader || SkippingUntilPragmaHdrStop)
1118     return HandleSkippedDirectiveWhileUsingPCH(Result, SavedHash.getLocation());
1119 
1120   switch (Result.getKind()) {
1121   case tok::eod:
1122     return;   // null directive.
1123   case tok::code_completion:
1124     setCodeCompletionReached();
1125     if (CodeComplete)
1126       CodeComplete->CodeCompleteDirective(
1127                                     CurPPLexer->getConditionalStackDepth() > 0);
1128     return;
1129   case tok::numeric_constant:  // # 7  GNU line marker directive.
1130     if (getLangOpts().AsmPreprocessor)
1131       break;  // # 4 is not a preprocessor directive in .S files.
1132     return HandleDigitDirective(Result);
1133   default:
1134     IdentifierInfo *II = Result.getIdentifierInfo();
1135     if (!II) break; // Not an identifier.
1136 
1137     // Ask what the preprocessor keyword ID is.
1138     switch (II->getPPKeywordID()) {
1139     default: break;
1140     // C99 6.10.1 - Conditional Inclusion.
1141     case tok::pp_if:
1142       return HandleIfDirective(Result, SavedHash, ReadAnyTokensBeforeDirective);
1143     case tok::pp_ifdef:
1144       return HandleIfdefDirective(Result, SavedHash, false,
1145                                   true /*not valid for miopt*/);
1146     case tok::pp_ifndef:
1147       return HandleIfdefDirective(Result, SavedHash, true,
1148                                   ReadAnyTokensBeforeDirective);
1149     case tok::pp_elif:
1150     case tok::pp_elifdef:
1151     case tok::pp_elifndef:
1152       return HandleElifFamilyDirective(Result, SavedHash, II->getPPKeywordID());
1153 
1154     case tok::pp_else:
1155       return HandleElseDirective(Result, SavedHash);
1156     case tok::pp_endif:
1157       return HandleEndifDirective(Result);
1158 
1159     // C99 6.10.2 - Source File Inclusion.
1160     case tok::pp_include:
1161       // Handle #include.
1162       return HandleIncludeDirective(SavedHash.getLocation(), Result);
1163     case tok::pp___include_macros:
1164       // Handle -imacros.
1165       return HandleIncludeMacrosDirective(SavedHash.getLocation(), Result);
1166 
1167     // C99 6.10.3 - Macro Replacement.
1168     case tok::pp_define:
1169       return HandleDefineDirective(Result, ImmediatelyAfterTopLevelIfndef);
1170     case tok::pp_undef:
1171       return HandleUndefDirective();
1172 
1173     // C99 6.10.4 - Line Control.
1174     case tok::pp_line:
1175       return HandleLineDirective();
1176 
1177     // C99 6.10.5 - Error Directive.
1178     case tok::pp_error:
1179       return HandleUserDiagnosticDirective(Result, false);
1180 
1181     // C99 6.10.6 - Pragma Directive.
1182     case tok::pp_pragma:
1183       return HandlePragmaDirective({PIK_HashPragma, SavedHash.getLocation()});
1184 
1185     // GNU Extensions.
1186     case tok::pp_import:
1187       return HandleImportDirective(SavedHash.getLocation(), Result);
1188     case tok::pp_include_next:
1189       return HandleIncludeNextDirective(SavedHash.getLocation(), Result);
1190 
1191     case tok::pp_warning:
1192       Diag(Result, diag::ext_pp_warning_directive);
1193       return HandleUserDiagnosticDirective(Result, true);
1194     case tok::pp_ident:
1195       return HandleIdentSCCSDirective(Result);
1196     case tok::pp_sccs:
1197       return HandleIdentSCCSDirective(Result);
1198     case tok::pp_assert:
1199       //isExtension = true;  // FIXME: implement #assert
1200       break;
1201     case tok::pp_unassert:
1202       //isExtension = true;  // FIXME: implement #unassert
1203       break;
1204 
1205     case tok::pp___public_macro:
1206       if (getLangOpts().Modules || getLangOpts().ModulesLocalVisibility)
1207         return HandleMacroPublicDirective(Result);
1208       break;
1209 
1210     case tok::pp___private_macro:
1211       if (getLangOpts().Modules || getLangOpts().ModulesLocalVisibility)
1212         return HandleMacroPrivateDirective();
1213       break;
1214     }
1215     break;
1216   }
1217 
1218   // If this is a .S file, treat unknown # directives as non-preprocessor
1219   // directives.  This is important because # may be a comment or introduce
1220   // various pseudo-ops.  Just return the # token and push back the following
1221   // token to be lexed next time.
1222   if (getLangOpts().AsmPreprocessor) {
1223     auto Toks = std::make_unique<Token[]>(2);
1224     // Return the # and the token after it.
1225     Toks[0] = SavedHash;
1226     Toks[1] = Result;
1227 
1228     // If the second token is a hashhash token, then we need to translate it to
1229     // unknown so the token lexer doesn't try to perform token pasting.
1230     if (Result.is(tok::hashhash))
1231       Toks[1].setKind(tok::unknown);
1232 
1233     // Enter this token stream so that we re-lex the tokens.  Make sure to
1234     // enable macro expansion, in case the token after the # is an identifier
1235     // that is expanded.
1236     EnterTokenStream(std::move(Toks), 2, false, /*IsReinject*/false);
1237     return;
1238   }
1239 
1240   // If we reached here, the preprocessing token is not valid!
1241   // Start suggesting if a similar directive found.
1242   Diag(Result, diag::err_pp_invalid_directive) << 0;
1243 
1244   // Read the rest of the PP line.
1245   DiscardUntilEndOfDirective();
1246 
1247   // Okay, we're done parsing the directive.
1248 }
1249 
1250 /// GetLineValue - Convert a numeric token into an unsigned value, emitting
1251 /// Diagnostic DiagID if it is invalid, and returning the value in Val.
1252 static bool GetLineValue(Token &DigitTok, unsigned &Val,
1253                          unsigned DiagID, Preprocessor &PP,
1254                          bool IsGNULineDirective=false) {
1255   if (DigitTok.isNot(tok::numeric_constant)) {
1256     PP.Diag(DigitTok, DiagID);
1257 
1258     if (DigitTok.isNot(tok::eod))
1259       PP.DiscardUntilEndOfDirective();
1260     return true;
1261   }
1262 
1263   SmallString<64> IntegerBuffer;
1264   IntegerBuffer.resize(DigitTok.getLength());
1265   const char *DigitTokBegin = &IntegerBuffer[0];
1266   bool Invalid = false;
1267   unsigned ActualLength = PP.getSpelling(DigitTok, DigitTokBegin, &Invalid);
1268   if (Invalid)
1269     return true;
1270 
1271   // Verify that we have a simple digit-sequence, and compute the value.  This
1272   // is always a simple digit string computed in decimal, so we do this manually
1273   // here.
1274   Val = 0;
1275   for (unsigned i = 0; i != ActualLength; ++i) {
1276     // C++1y [lex.fcon]p1:
1277     //   Optional separating single quotes in a digit-sequence are ignored
1278     if (DigitTokBegin[i] == '\'')
1279       continue;
1280 
1281     if (!isDigit(DigitTokBegin[i])) {
1282       PP.Diag(PP.AdvanceToTokenCharacter(DigitTok.getLocation(), i),
1283               diag::err_pp_line_digit_sequence) << IsGNULineDirective;
1284       PP.DiscardUntilEndOfDirective();
1285       return true;
1286     }
1287 
1288     unsigned NextVal = Val*10+(DigitTokBegin[i]-'0');
1289     if (NextVal < Val) { // overflow.
1290       PP.Diag(DigitTok, DiagID);
1291       PP.DiscardUntilEndOfDirective();
1292       return true;
1293     }
1294     Val = NextVal;
1295   }
1296 
1297   if (DigitTokBegin[0] == '0' && Val)
1298     PP.Diag(DigitTok.getLocation(), diag::warn_pp_line_decimal)
1299       << IsGNULineDirective;
1300 
1301   return false;
1302 }
1303 
1304 /// Handle a \#line directive: C99 6.10.4.
1305 ///
1306 /// The two acceptable forms are:
1307 /// \verbatim
1308 ///   # line digit-sequence
1309 ///   # line digit-sequence "s-char-sequence"
1310 /// \endverbatim
1311 void Preprocessor::HandleLineDirective() {
1312   // Read the line # and string argument.  Per C99 6.10.4p5, these tokens are
1313   // expanded.
1314   Token DigitTok;
1315   Lex(DigitTok);
1316 
1317   // Validate the number and convert it to an unsigned.
1318   unsigned LineNo;
1319   if (GetLineValue(DigitTok, LineNo, diag::err_pp_line_requires_integer,*this))
1320     return;
1321 
1322   if (LineNo == 0)
1323     Diag(DigitTok, diag::ext_pp_line_zero);
1324 
1325   // Enforce C99 6.10.4p3: "The digit sequence shall not specify ... a
1326   // number greater than 2147483647".  C90 requires that the line # be <= 32767.
1327   unsigned LineLimit = 32768U;
1328   if (LangOpts.C99 || LangOpts.CPlusPlus11)
1329     LineLimit = 2147483648U;
1330   if (LineNo >= LineLimit)
1331     Diag(DigitTok, diag::ext_pp_line_too_big) << LineLimit;
1332   else if (LangOpts.CPlusPlus11 && LineNo >= 32768U)
1333     Diag(DigitTok, diag::warn_cxx98_compat_pp_line_too_big);
1334 
1335   int FilenameID = -1;
1336   Token StrTok;
1337   Lex(StrTok);
1338 
1339   // If the StrTok is "eod", then it wasn't present.  Otherwise, it must be a
1340   // string followed by eod.
1341   if (StrTok.is(tok::eod))
1342     ; // ok
1343   else if (StrTok.isNot(tok::string_literal)) {
1344     Diag(StrTok, diag::err_pp_line_invalid_filename);
1345     DiscardUntilEndOfDirective();
1346     return;
1347   } else if (StrTok.hasUDSuffix()) {
1348     Diag(StrTok, diag::err_invalid_string_udl);
1349     DiscardUntilEndOfDirective();
1350     return;
1351   } else {
1352     // Parse and validate the string, converting it into a unique ID.
1353     StringLiteralParser Literal(StrTok, *this);
1354     assert(Literal.isAscii() && "Didn't allow wide strings in");
1355     if (Literal.hadError) {
1356       DiscardUntilEndOfDirective();
1357       return;
1358     }
1359     if (Literal.Pascal) {
1360       Diag(StrTok, diag::err_pp_linemarker_invalid_filename);
1361       DiscardUntilEndOfDirective();
1362       return;
1363     }
1364     FilenameID = SourceMgr.getLineTableFilenameID(Literal.GetString());
1365 
1366     // Verify that there is nothing after the string, other than EOD.  Because
1367     // of C99 6.10.4p5, macros that expand to empty tokens are ok.
1368     CheckEndOfDirective("line", true);
1369   }
1370 
1371   // Take the file kind of the file containing the #line directive. #line
1372   // directives are often used for generated sources from the same codebase, so
1373   // the new file should generally be classified the same way as the current
1374   // file. This is visible in GCC's pre-processed output, which rewrites #line
1375   // to GNU line markers.
1376   SrcMgr::CharacteristicKind FileKind =
1377       SourceMgr.getFileCharacteristic(DigitTok.getLocation());
1378 
1379   SourceMgr.AddLineNote(DigitTok.getLocation(), LineNo, FilenameID, false,
1380                         false, FileKind);
1381 
1382   if (Callbacks)
1383     Callbacks->FileChanged(CurPPLexer->getSourceLocation(),
1384                            PPCallbacks::RenameFile, FileKind);
1385 }
1386 
1387 /// ReadLineMarkerFlags - Parse and validate any flags at the end of a GNU line
1388 /// marker directive.
1389 static bool ReadLineMarkerFlags(bool &IsFileEntry, bool &IsFileExit,
1390                                 SrcMgr::CharacteristicKind &FileKind,
1391                                 Preprocessor &PP) {
1392   unsigned FlagVal;
1393   Token FlagTok;
1394   PP.Lex(FlagTok);
1395   if (FlagTok.is(tok::eod)) return false;
1396   if (GetLineValue(FlagTok, FlagVal, diag::err_pp_linemarker_invalid_flag, PP))
1397     return true;
1398 
1399   if (FlagVal == 1) {
1400     IsFileEntry = true;
1401 
1402     PP.Lex(FlagTok);
1403     if (FlagTok.is(tok::eod)) return false;
1404     if (GetLineValue(FlagTok, FlagVal, diag::err_pp_linemarker_invalid_flag,PP))
1405       return true;
1406   } else if (FlagVal == 2) {
1407     IsFileExit = true;
1408 
1409     SourceManager &SM = PP.getSourceManager();
1410     // If we are leaving the current presumed file, check to make sure the
1411     // presumed include stack isn't empty!
1412     FileID CurFileID =
1413       SM.getDecomposedExpansionLoc(FlagTok.getLocation()).first;
1414     PresumedLoc PLoc = SM.getPresumedLoc(FlagTok.getLocation());
1415     if (PLoc.isInvalid())
1416       return true;
1417 
1418     // If there is no include loc (main file) or if the include loc is in a
1419     // different physical file, then we aren't in a "1" line marker flag region.
1420     SourceLocation IncLoc = PLoc.getIncludeLoc();
1421     if (IncLoc.isInvalid() ||
1422         SM.getDecomposedExpansionLoc(IncLoc).first != CurFileID) {
1423       PP.Diag(FlagTok, diag::err_pp_linemarker_invalid_pop);
1424       PP.DiscardUntilEndOfDirective();
1425       return true;
1426     }
1427 
1428     PP.Lex(FlagTok);
1429     if (FlagTok.is(tok::eod)) return false;
1430     if (GetLineValue(FlagTok, FlagVal, diag::err_pp_linemarker_invalid_flag,PP))
1431       return true;
1432   }
1433 
1434   // We must have 3 if there are still flags.
1435   if (FlagVal != 3) {
1436     PP.Diag(FlagTok, diag::err_pp_linemarker_invalid_flag);
1437     PP.DiscardUntilEndOfDirective();
1438     return true;
1439   }
1440 
1441   FileKind = SrcMgr::C_System;
1442 
1443   PP.Lex(FlagTok);
1444   if (FlagTok.is(tok::eod)) return false;
1445   if (GetLineValue(FlagTok, FlagVal, diag::err_pp_linemarker_invalid_flag, PP))
1446     return true;
1447 
1448   // We must have 4 if there is yet another flag.
1449   if (FlagVal != 4) {
1450     PP.Diag(FlagTok, diag::err_pp_linemarker_invalid_flag);
1451     PP.DiscardUntilEndOfDirective();
1452     return true;
1453   }
1454 
1455   FileKind = SrcMgr::C_ExternCSystem;
1456 
1457   PP.Lex(FlagTok);
1458   if (FlagTok.is(tok::eod)) return false;
1459 
1460   // There are no more valid flags here.
1461   PP.Diag(FlagTok, diag::err_pp_linemarker_invalid_flag);
1462   PP.DiscardUntilEndOfDirective();
1463   return true;
1464 }
1465 
1466 /// HandleDigitDirective - Handle a GNU line marker directive, whose syntax is
1467 /// one of the following forms:
1468 ///
1469 ///     # 42
1470 ///     # 42 "file" ('1' | '2')?
1471 ///     # 42 "file" ('1' | '2')? '3' '4'?
1472 ///
1473 void Preprocessor::HandleDigitDirective(Token &DigitTok) {
1474   // Validate the number and convert it to an unsigned.  GNU does not have a
1475   // line # limit other than it fit in 32-bits.
1476   unsigned LineNo;
1477   if (GetLineValue(DigitTok, LineNo, diag::err_pp_linemarker_requires_integer,
1478                    *this, true))
1479     return;
1480 
1481   Token StrTok;
1482   Lex(StrTok);
1483 
1484   bool IsFileEntry = false, IsFileExit = false;
1485   int FilenameID = -1;
1486   SrcMgr::CharacteristicKind FileKind = SrcMgr::C_User;
1487 
1488   // If the StrTok is "eod", then it wasn't present.  Otherwise, it must be a
1489   // string followed by eod.
1490   if (StrTok.is(tok::eod)) {
1491     Diag(StrTok, diag::ext_pp_gnu_line_directive);
1492     // Treat this like "#line NN", which doesn't change file characteristics.
1493     FileKind = SourceMgr.getFileCharacteristic(DigitTok.getLocation());
1494   } else if (StrTok.isNot(tok::string_literal)) {
1495     Diag(StrTok, diag::err_pp_linemarker_invalid_filename);
1496     DiscardUntilEndOfDirective();
1497     return;
1498   } else if (StrTok.hasUDSuffix()) {
1499     Diag(StrTok, diag::err_invalid_string_udl);
1500     DiscardUntilEndOfDirective();
1501     return;
1502   } else {
1503     // Parse and validate the string, converting it into a unique ID.
1504     StringLiteralParser Literal(StrTok, *this);
1505     assert(Literal.isAscii() && "Didn't allow wide strings in");
1506     if (Literal.hadError) {
1507       DiscardUntilEndOfDirective();
1508       return;
1509     }
1510     if (Literal.Pascal) {
1511       Diag(StrTok, diag::err_pp_linemarker_invalid_filename);
1512       DiscardUntilEndOfDirective();
1513       return;
1514     }
1515 
1516     // If a filename was present, read any flags that are present.
1517     if (ReadLineMarkerFlags(IsFileEntry, IsFileExit, FileKind, *this))
1518       return;
1519     if (!SourceMgr.isWrittenInBuiltinFile(DigitTok.getLocation()) &&
1520         !SourceMgr.isWrittenInCommandLineFile(DigitTok.getLocation()))
1521       Diag(StrTok, diag::ext_pp_gnu_line_directive);
1522 
1523     // Exiting to an empty string means pop to the including file, so leave
1524     // FilenameID as -1 in that case.
1525     if (!(IsFileExit && Literal.GetString().empty()))
1526       FilenameID = SourceMgr.getLineTableFilenameID(Literal.GetString());
1527   }
1528 
1529   // Create a line note with this information.
1530   SourceMgr.AddLineNote(DigitTok.getLocation(), LineNo, FilenameID, IsFileEntry,
1531                         IsFileExit, FileKind);
1532 
1533   // If the preprocessor has callbacks installed, notify them of the #line
1534   // change.  This is used so that the line marker comes out in -E mode for
1535   // example.
1536   if (Callbacks) {
1537     PPCallbacks::FileChangeReason Reason = PPCallbacks::RenameFile;
1538     if (IsFileEntry)
1539       Reason = PPCallbacks::EnterFile;
1540     else if (IsFileExit)
1541       Reason = PPCallbacks::ExitFile;
1542 
1543     Callbacks->FileChanged(CurPPLexer->getSourceLocation(), Reason, FileKind);
1544   }
1545 }
1546 
1547 /// HandleUserDiagnosticDirective - Handle a #warning or #error directive.
1548 ///
1549 void Preprocessor::HandleUserDiagnosticDirective(Token &Tok,
1550                                                  bool isWarning) {
1551   // Read the rest of the line raw.  We do this because we don't want macros
1552   // to be expanded and we don't require that the tokens be valid preprocessing
1553   // tokens.  For example, this is allowed: "#warning `   'foo".  GCC does
1554   // collapse multiple consecutive white space between tokens, but this isn't
1555   // specified by the standard.
1556   SmallString<128> Message;
1557   CurLexer->ReadToEndOfLine(&Message);
1558 
1559   // Find the first non-whitespace character, so that we can make the
1560   // diagnostic more succinct.
1561   StringRef Msg = Message.str().ltrim(' ');
1562 
1563   if (isWarning)
1564     Diag(Tok, diag::pp_hash_warning) << Msg;
1565   else
1566     Diag(Tok, diag::err_pp_hash_error) << Msg;
1567 }
1568 
1569 /// HandleIdentSCCSDirective - Handle a #ident/#sccs directive.
1570 ///
1571 void Preprocessor::HandleIdentSCCSDirective(Token &Tok) {
1572   // Yes, this directive is an extension.
1573   Diag(Tok, diag::ext_pp_ident_directive);
1574 
1575   // Read the string argument.
1576   Token StrTok;
1577   Lex(StrTok);
1578 
1579   // If the token kind isn't a string, it's a malformed directive.
1580   if (StrTok.isNot(tok::string_literal) &&
1581       StrTok.isNot(tok::wide_string_literal)) {
1582     Diag(StrTok, diag::err_pp_malformed_ident);
1583     if (StrTok.isNot(tok::eod))
1584       DiscardUntilEndOfDirective();
1585     return;
1586   }
1587 
1588   if (StrTok.hasUDSuffix()) {
1589     Diag(StrTok, diag::err_invalid_string_udl);
1590     DiscardUntilEndOfDirective();
1591     return;
1592   }
1593 
1594   // Verify that there is nothing after the string, other than EOD.
1595   CheckEndOfDirective("ident");
1596 
1597   if (Callbacks) {
1598     bool Invalid = false;
1599     std::string Str = getSpelling(StrTok, &Invalid);
1600     if (!Invalid)
1601       Callbacks->Ident(Tok.getLocation(), Str);
1602   }
1603 }
1604 
1605 /// Handle a #public directive.
1606 void Preprocessor::HandleMacroPublicDirective(Token &Tok) {
1607   Token MacroNameTok;
1608   ReadMacroName(MacroNameTok, MU_Undef);
1609 
1610   // Error reading macro name?  If so, diagnostic already issued.
1611   if (MacroNameTok.is(tok::eod))
1612     return;
1613 
1614   // Check to see if this is the last token on the #__public_macro line.
1615   CheckEndOfDirective("__public_macro");
1616 
1617   IdentifierInfo *II = MacroNameTok.getIdentifierInfo();
1618   // Okay, we finally have a valid identifier to undef.
1619   MacroDirective *MD = getLocalMacroDirective(II);
1620 
1621   // If the macro is not defined, this is an error.
1622   if (!MD) {
1623     Diag(MacroNameTok, diag::err_pp_visibility_non_macro) << II;
1624     return;
1625   }
1626 
1627   // Note that this macro has now been exported.
1628   appendMacroDirective(II, AllocateVisibilityMacroDirective(
1629                                 MacroNameTok.getLocation(), /*isPublic=*/true));
1630 }
1631 
1632 /// Handle a #private directive.
1633 void Preprocessor::HandleMacroPrivateDirective() {
1634   Token MacroNameTok;
1635   ReadMacroName(MacroNameTok, MU_Undef);
1636 
1637   // Error reading macro name?  If so, diagnostic already issued.
1638   if (MacroNameTok.is(tok::eod))
1639     return;
1640 
1641   // Check to see if this is the last token on the #__private_macro line.
1642   CheckEndOfDirective("__private_macro");
1643 
1644   IdentifierInfo *II = MacroNameTok.getIdentifierInfo();
1645   // Okay, we finally have a valid identifier to undef.
1646   MacroDirective *MD = getLocalMacroDirective(II);
1647 
1648   // If the macro is not defined, this is an error.
1649   if (!MD) {
1650     Diag(MacroNameTok, diag::err_pp_visibility_non_macro) << II;
1651     return;
1652   }
1653 
1654   // Note that this macro has now been marked private.
1655   appendMacroDirective(II, AllocateVisibilityMacroDirective(
1656                                MacroNameTok.getLocation(), /*isPublic=*/false));
1657 }
1658 
1659 //===----------------------------------------------------------------------===//
1660 // Preprocessor Include Directive Handling.
1661 //===----------------------------------------------------------------------===//
1662 
1663 /// GetIncludeFilenameSpelling - Turn the specified lexer token into a fully
1664 /// checked and spelled filename, e.g. as an operand of \#include. This returns
1665 /// true if the input filename was in <>'s or false if it were in ""'s.  The
1666 /// caller is expected to provide a buffer that is large enough to hold the
1667 /// spelling of the filename, but is also expected to handle the case when
1668 /// this method decides to use a different buffer.
1669 bool Preprocessor::GetIncludeFilenameSpelling(SourceLocation Loc,
1670                                               StringRef &Buffer) {
1671   // Get the text form of the filename.
1672   assert(!Buffer.empty() && "Can't have tokens with empty spellings!");
1673 
1674   // FIXME: Consider warning on some of the cases described in C11 6.4.7/3 and
1675   // C++20 [lex.header]/2:
1676   //
1677   // If `"`, `'`, `\`, `/*`, or `//` appears in a header-name, then
1678   //   in C: behavior is undefined
1679   //   in C++: program is conditionally-supported with implementation-defined
1680   //           semantics
1681 
1682   // Make sure the filename is <x> or "x".
1683   bool isAngled;
1684   if (Buffer[0] == '<') {
1685     if (Buffer.back() != '>') {
1686       Diag(Loc, diag::err_pp_expects_filename);
1687       Buffer = StringRef();
1688       return true;
1689     }
1690     isAngled = true;
1691   } else if (Buffer[0] == '"') {
1692     if (Buffer.back() != '"') {
1693       Diag(Loc, diag::err_pp_expects_filename);
1694       Buffer = StringRef();
1695       return true;
1696     }
1697     isAngled = false;
1698   } else {
1699     Diag(Loc, diag::err_pp_expects_filename);
1700     Buffer = StringRef();
1701     return true;
1702   }
1703 
1704   // Diagnose #include "" as invalid.
1705   if (Buffer.size() <= 2) {
1706     Diag(Loc, diag::err_pp_empty_filename);
1707     Buffer = StringRef();
1708     return true;
1709   }
1710 
1711   // Skip the brackets.
1712   Buffer = Buffer.substr(1, Buffer.size()-2);
1713   return isAngled;
1714 }
1715 
1716 /// Push a token onto the token stream containing an annotation.
1717 void Preprocessor::EnterAnnotationToken(SourceRange Range,
1718                                         tok::TokenKind Kind,
1719                                         void *AnnotationVal) {
1720   // FIXME: Produce this as the current token directly, rather than
1721   // allocating a new token for it.
1722   auto Tok = std::make_unique<Token[]>(1);
1723   Tok[0].startToken();
1724   Tok[0].setKind(Kind);
1725   Tok[0].setLocation(Range.getBegin());
1726   Tok[0].setAnnotationEndLoc(Range.getEnd());
1727   Tok[0].setAnnotationValue(AnnotationVal);
1728   EnterTokenStream(std::move(Tok), 1, true, /*IsReinject*/ false);
1729 }
1730 
1731 /// Produce a diagnostic informing the user that a #include or similar
1732 /// was implicitly treated as a module import.
1733 static void diagnoseAutoModuleImport(
1734     Preprocessor &PP, SourceLocation HashLoc, Token &IncludeTok,
1735     ArrayRef<std::pair<IdentifierInfo *, SourceLocation>> Path,
1736     SourceLocation PathEnd) {
1737   StringRef ImportKeyword;
1738   if (PP.getLangOpts().ObjC)
1739     ImportKeyword = "@import";
1740   else if (PP.getLangOpts().ModulesTS || PP.getLangOpts().CPlusPlusModules)
1741     ImportKeyword = "import";
1742   else
1743     return; // no import syntax available
1744 
1745   SmallString<128> PathString;
1746   for (size_t I = 0, N = Path.size(); I != N; ++I) {
1747     if (I)
1748       PathString += '.';
1749     PathString += Path[I].first->getName();
1750   }
1751   int IncludeKind = 0;
1752 
1753   switch (IncludeTok.getIdentifierInfo()->getPPKeywordID()) {
1754   case tok::pp_include:
1755     IncludeKind = 0;
1756     break;
1757 
1758   case tok::pp_import:
1759     IncludeKind = 1;
1760     break;
1761 
1762   case tok::pp_include_next:
1763     IncludeKind = 2;
1764     break;
1765 
1766   case tok::pp___include_macros:
1767     IncludeKind = 3;
1768     break;
1769 
1770   default:
1771     llvm_unreachable("unknown include directive kind");
1772   }
1773 
1774   CharSourceRange ReplaceRange(SourceRange(HashLoc, PathEnd),
1775                                /*IsTokenRange=*/false);
1776   PP.Diag(HashLoc, diag::warn_auto_module_import)
1777       << IncludeKind << PathString
1778       << FixItHint::CreateReplacement(
1779              ReplaceRange, (ImportKeyword + " " + PathString + ";").str());
1780 }
1781 
1782 // Given a vector of path components and a string containing the real
1783 // path to the file, build a properly-cased replacement in the vector,
1784 // and return true if the replacement should be suggested.
1785 static bool trySimplifyPath(SmallVectorImpl<StringRef> &Components,
1786                             StringRef RealPathName) {
1787   auto RealPathComponentIter = llvm::sys::path::rbegin(RealPathName);
1788   auto RealPathComponentEnd = llvm::sys::path::rend(RealPathName);
1789   int Cnt = 0;
1790   bool SuggestReplacement = false;
1791   // Below is a best-effort to handle ".." in paths. It is admittedly
1792   // not 100% correct in the presence of symlinks.
1793   for (auto &Component : llvm::reverse(Components)) {
1794     if ("." == Component) {
1795     } else if (".." == Component) {
1796       ++Cnt;
1797     } else if (Cnt) {
1798       --Cnt;
1799     } else if (RealPathComponentIter != RealPathComponentEnd) {
1800       if (Component != *RealPathComponentIter) {
1801         // If these path components differ by more than just case, then we
1802         // may be looking at symlinked paths. Bail on this diagnostic to avoid
1803         // noisy false positives.
1804         SuggestReplacement =
1805             RealPathComponentIter->equals_insensitive(Component);
1806         if (!SuggestReplacement)
1807           break;
1808         Component = *RealPathComponentIter;
1809       }
1810       ++RealPathComponentIter;
1811     }
1812   }
1813   return SuggestReplacement;
1814 }
1815 
1816 bool Preprocessor::checkModuleIsAvailable(const LangOptions &LangOpts,
1817                                           const TargetInfo &TargetInfo,
1818                                           DiagnosticsEngine &Diags, Module *M) {
1819   Module::Requirement Requirement;
1820   Module::UnresolvedHeaderDirective MissingHeader;
1821   Module *ShadowingModule = nullptr;
1822   if (M->isAvailable(LangOpts, TargetInfo, Requirement, MissingHeader,
1823                      ShadowingModule))
1824     return false;
1825 
1826   if (MissingHeader.FileNameLoc.isValid()) {
1827     Diags.Report(MissingHeader.FileNameLoc, diag::err_module_header_missing)
1828         << MissingHeader.IsUmbrella << MissingHeader.FileName;
1829   } else if (ShadowingModule) {
1830     Diags.Report(M->DefinitionLoc, diag::err_module_shadowed) << M->Name;
1831     Diags.Report(ShadowingModule->DefinitionLoc,
1832                  diag::note_previous_definition);
1833   } else {
1834     // FIXME: Track the location at which the requirement was specified, and
1835     // use it here.
1836     Diags.Report(M->DefinitionLoc, diag::err_module_unavailable)
1837         << M->getFullModuleName() << Requirement.second << Requirement.first;
1838   }
1839   return true;
1840 }
1841 
1842 std::pair<ConstSearchDirIterator, const FileEntry *>
1843 Preprocessor::getIncludeNextStart(const Token &IncludeNextTok) const {
1844   // #include_next is like #include, except that we start searching after
1845   // the current found directory.  If we can't do this, issue a
1846   // diagnostic.
1847   ConstSearchDirIterator Lookup = CurDirLookup;
1848   const FileEntry *LookupFromFile = nullptr;
1849 
1850   if (isInPrimaryFile() && LangOpts.IsHeaderFile) {
1851     // If the main file is a header, then it's either for PCH/AST generation,
1852     // or libclang opened it. Either way, handle it as a normal include below
1853     // and do not complain about include_next.
1854   } else if (isInPrimaryFile()) {
1855     Lookup = nullptr;
1856     Diag(IncludeNextTok, diag::pp_include_next_in_primary);
1857   } else if (CurLexerSubmodule) {
1858     // Start looking up in the directory *after* the one in which the current
1859     // file would be found, if any.
1860     assert(CurPPLexer && "#include_next directive in macro?");
1861     LookupFromFile = CurPPLexer->getFileEntry();
1862     Lookup = nullptr;
1863   } else if (!Lookup) {
1864     // The current file was not found by walking the include path. Either it
1865     // is the primary file (handled above), or it was found by absolute path,
1866     // or it was found relative to such a file.
1867     // FIXME: Track enough information so we know which case we're in.
1868     Diag(IncludeNextTok, diag::pp_include_next_absolute_path);
1869   } else {
1870     // Start looking up in the next directory.
1871     ++Lookup;
1872   }
1873 
1874   return {Lookup, LookupFromFile};
1875 }
1876 
1877 /// HandleIncludeDirective - The "\#include" tokens have just been read, read
1878 /// the file to be included from the lexer, then include it!  This is a common
1879 /// routine with functionality shared between \#include, \#include_next and
1880 /// \#import.  LookupFrom is set when this is a \#include_next directive, it
1881 /// specifies the file to start searching from.
1882 void Preprocessor::HandleIncludeDirective(SourceLocation HashLoc,
1883                                           Token &IncludeTok,
1884                                           ConstSearchDirIterator LookupFrom,
1885                                           const FileEntry *LookupFromFile) {
1886   Token FilenameTok;
1887   if (LexHeaderName(FilenameTok))
1888     return;
1889 
1890   if (FilenameTok.isNot(tok::header_name)) {
1891     Diag(FilenameTok.getLocation(), diag::err_pp_expects_filename);
1892     if (FilenameTok.isNot(tok::eod))
1893       DiscardUntilEndOfDirective();
1894     return;
1895   }
1896 
1897   // Verify that there is nothing after the filename, other than EOD.  Note
1898   // that we allow macros that expand to nothing after the filename, because
1899   // this falls into the category of "#include pp-tokens new-line" specified
1900   // in C99 6.10.2p4.
1901   SourceLocation EndLoc =
1902       CheckEndOfDirective(IncludeTok.getIdentifierInfo()->getNameStart(), true);
1903 
1904   auto Action = HandleHeaderIncludeOrImport(HashLoc, IncludeTok, FilenameTok,
1905                                             EndLoc, LookupFrom, LookupFromFile);
1906   switch (Action.Kind) {
1907   case ImportAction::None:
1908   case ImportAction::SkippedModuleImport:
1909     break;
1910   case ImportAction::ModuleBegin:
1911     EnterAnnotationToken(SourceRange(HashLoc, EndLoc),
1912                          tok::annot_module_begin, Action.ModuleForHeader);
1913     break;
1914   case ImportAction::ModuleImport:
1915     EnterAnnotationToken(SourceRange(HashLoc, EndLoc),
1916                          tok::annot_module_include, Action.ModuleForHeader);
1917     break;
1918   case ImportAction::Failure:
1919     assert(TheModuleLoader.HadFatalFailure &&
1920            "This should be an early exit only to a fatal error");
1921     TheModuleLoader.HadFatalFailure = true;
1922     IncludeTok.setKind(tok::eof);
1923     CurLexer->cutOffLexing();
1924     return;
1925   }
1926 }
1927 
1928 Optional<FileEntryRef> Preprocessor::LookupHeaderIncludeOrImport(
1929     ConstSearchDirIterator *CurDir, StringRef &Filename,
1930     SourceLocation FilenameLoc, CharSourceRange FilenameRange,
1931     const Token &FilenameTok, bool &IsFrameworkFound, bool IsImportDecl,
1932     bool &IsMapped, ConstSearchDirIterator LookupFrom,
1933     const FileEntry *LookupFromFile, StringRef &LookupFilename,
1934     SmallVectorImpl<char> &RelativePath, SmallVectorImpl<char> &SearchPath,
1935     ModuleMap::KnownHeader &SuggestedModule, bool isAngled) {
1936   Optional<FileEntryRef> File = LookupFile(
1937       FilenameLoc, LookupFilename,
1938       isAngled, LookupFrom, LookupFromFile, CurDir,
1939       Callbacks ? &SearchPath : nullptr, Callbacks ? &RelativePath : nullptr,
1940       &SuggestedModule, &IsMapped, &IsFrameworkFound);
1941   if (File)
1942     return File;
1943 
1944   if (SuppressIncludeNotFoundError)
1945     return None;
1946 
1947   // If the file could not be located and it was included via angle
1948   // brackets, we can attempt a lookup as though it were a quoted path to
1949   // provide the user with a possible fixit.
1950   if (isAngled) {
1951     Optional<FileEntryRef> File = LookupFile(
1952         FilenameLoc, LookupFilename,
1953         false, LookupFrom, LookupFromFile, CurDir,
1954         Callbacks ? &SearchPath : nullptr, Callbacks ? &RelativePath : nullptr,
1955         &SuggestedModule, &IsMapped,
1956         /*IsFrameworkFound=*/nullptr);
1957     if (File) {
1958       Diag(FilenameTok, diag::err_pp_file_not_found_angled_include_not_fatal)
1959           << Filename << IsImportDecl
1960           << FixItHint::CreateReplacement(FilenameRange,
1961                                           "\"" + Filename.str() + "\"");
1962       return File;
1963     }
1964   }
1965 
1966   // Check for likely typos due to leading or trailing non-isAlphanumeric
1967   // characters
1968   StringRef OriginalFilename = Filename;
1969   if (LangOpts.SpellChecking) {
1970     // A heuristic to correct a typo file name by removing leading and
1971     // trailing non-isAlphanumeric characters.
1972     auto CorrectTypoFilename = [](llvm::StringRef Filename) {
1973       Filename = Filename.drop_until(isAlphanumeric);
1974       while (!Filename.empty() && !isAlphanumeric(Filename.back())) {
1975         Filename = Filename.drop_back();
1976       }
1977       return Filename;
1978     };
1979     StringRef TypoCorrectionName = CorrectTypoFilename(Filename);
1980     StringRef TypoCorrectionLookupName = CorrectTypoFilename(LookupFilename);
1981 
1982     Optional<FileEntryRef> File = LookupFile(
1983         FilenameLoc, TypoCorrectionLookupName, isAngled, LookupFrom, LookupFromFile,
1984         CurDir, Callbacks ? &SearchPath : nullptr,
1985         Callbacks ? &RelativePath : nullptr, &SuggestedModule, &IsMapped,
1986         /*IsFrameworkFound=*/nullptr);
1987     if (File) {
1988       auto Hint =
1989           isAngled ? FixItHint::CreateReplacement(
1990                          FilenameRange, "<" + TypoCorrectionName.str() + ">")
1991                    : FixItHint::CreateReplacement(
1992                          FilenameRange, "\"" + TypoCorrectionName.str() + "\"");
1993       Diag(FilenameTok, diag::err_pp_file_not_found_typo_not_fatal)
1994           << OriginalFilename << TypoCorrectionName << Hint;
1995       // We found the file, so set the Filename to the name after typo
1996       // correction.
1997       Filename = TypoCorrectionName;
1998       LookupFilename = TypoCorrectionLookupName;
1999       return File;
2000     }
2001   }
2002 
2003   // If the file is still not found, just go with the vanilla diagnostic
2004   assert(!File.hasValue() && "expected missing file");
2005   Diag(FilenameTok, diag::err_pp_file_not_found)
2006       << OriginalFilename << FilenameRange;
2007   if (IsFrameworkFound) {
2008     size_t SlashPos = OriginalFilename.find('/');
2009     assert(SlashPos != StringRef::npos &&
2010            "Include with framework name should have '/' in the filename");
2011     StringRef FrameworkName = OriginalFilename.substr(0, SlashPos);
2012     FrameworkCacheEntry &CacheEntry =
2013         HeaderInfo.LookupFrameworkCache(FrameworkName);
2014     assert(CacheEntry.Directory && "Found framework should be in cache");
2015     Diag(FilenameTok, diag::note_pp_framework_without_header)
2016         << OriginalFilename.substr(SlashPos + 1) << FrameworkName
2017         << CacheEntry.Directory->getName();
2018   }
2019 
2020   return None;
2021 }
2022 
2023 /// Handle either a #include-like directive or an import declaration that names
2024 /// a header file.
2025 ///
2026 /// \param HashLoc The location of the '#' token for an include, or
2027 ///        SourceLocation() for an import declaration.
2028 /// \param IncludeTok The include / include_next / import token.
2029 /// \param FilenameTok The header-name token.
2030 /// \param EndLoc The location at which any imported macros become visible.
2031 /// \param LookupFrom For #include_next, the starting directory for the
2032 ///        directory lookup.
2033 /// \param LookupFromFile For #include_next, the starting file for the directory
2034 ///        lookup.
2035 Preprocessor::ImportAction Preprocessor::HandleHeaderIncludeOrImport(
2036     SourceLocation HashLoc, Token &IncludeTok, Token &FilenameTok,
2037     SourceLocation EndLoc, ConstSearchDirIterator LookupFrom,
2038     const FileEntry *LookupFromFile) {
2039   SmallString<128> FilenameBuffer;
2040   StringRef Filename = getSpelling(FilenameTok, FilenameBuffer);
2041   SourceLocation CharEnd = FilenameTok.getEndLoc();
2042 
2043   CharSourceRange FilenameRange
2044     = CharSourceRange::getCharRange(FilenameTok.getLocation(), CharEnd);
2045   StringRef OriginalFilename = Filename;
2046   bool isAngled =
2047     GetIncludeFilenameSpelling(FilenameTok.getLocation(), Filename);
2048 
2049   // If GetIncludeFilenameSpelling set the start ptr to null, there was an
2050   // error.
2051   if (Filename.empty())
2052     return {ImportAction::None};
2053 
2054   bool IsImportDecl = HashLoc.isInvalid();
2055   SourceLocation StartLoc = IsImportDecl ? IncludeTok.getLocation() : HashLoc;
2056 
2057   // Complain about attempts to #include files in an audit pragma.
2058   if (PragmaARCCFCodeAuditedInfo.second.isValid()) {
2059     Diag(StartLoc, diag::err_pp_include_in_arc_cf_code_audited) << IsImportDecl;
2060     Diag(PragmaARCCFCodeAuditedInfo.second, diag::note_pragma_entered_here);
2061 
2062     // Immediately leave the pragma.
2063     PragmaARCCFCodeAuditedInfo = {nullptr, SourceLocation()};
2064   }
2065 
2066   // Complain about attempts to #include files in an assume-nonnull pragma.
2067   if (PragmaAssumeNonNullLoc.isValid()) {
2068     Diag(StartLoc, diag::err_pp_include_in_assume_nonnull) << IsImportDecl;
2069     Diag(PragmaAssumeNonNullLoc, diag::note_pragma_entered_here);
2070 
2071     // Immediately leave the pragma.
2072     PragmaAssumeNonNullLoc = SourceLocation();
2073   }
2074 
2075   if (HeaderInfo.HasIncludeAliasMap()) {
2076     // Map the filename with the brackets still attached.  If the name doesn't
2077     // map to anything, fall back on the filename we've already gotten the
2078     // spelling for.
2079     StringRef NewName = HeaderInfo.MapHeaderToIncludeAlias(OriginalFilename);
2080     if (!NewName.empty())
2081       Filename = NewName;
2082   }
2083 
2084   // Search include directories.
2085   bool IsMapped = false;
2086   bool IsFrameworkFound = false;
2087   ConstSearchDirIterator CurDir = nullptr;
2088   SmallString<1024> SearchPath;
2089   SmallString<1024> RelativePath;
2090   // We get the raw path only if we have 'Callbacks' to which we later pass
2091   // the path.
2092   ModuleMap::KnownHeader SuggestedModule;
2093   SourceLocation FilenameLoc = FilenameTok.getLocation();
2094   StringRef LookupFilename = Filename;
2095 
2096   // Normalize slashes when compiling with -fms-extensions on non-Windows. This
2097   // is unnecessary on Windows since the filesystem there handles backslashes.
2098   SmallString<128> NormalizedPath;
2099   llvm::sys::path::Style BackslashStyle = llvm::sys::path::Style::native;
2100   if (is_style_posix(BackslashStyle) && LangOpts.MicrosoftExt) {
2101     NormalizedPath = Filename.str();
2102     llvm::sys::path::native(NormalizedPath);
2103     LookupFilename = NormalizedPath;
2104     BackslashStyle = llvm::sys::path::Style::windows;
2105   }
2106 
2107   Optional<FileEntryRef> File = LookupHeaderIncludeOrImport(
2108       &CurDir, Filename, FilenameLoc, FilenameRange, FilenameTok,
2109       IsFrameworkFound, IsImportDecl, IsMapped, LookupFrom, LookupFromFile,
2110       LookupFilename, RelativePath, SearchPath, SuggestedModule, isAngled);
2111 
2112   if (usingPCHWithThroughHeader() && SkippingUntilPCHThroughHeader) {
2113     if (File && isPCHThroughHeader(&File->getFileEntry()))
2114       SkippingUntilPCHThroughHeader = false;
2115     return {ImportAction::None};
2116   }
2117 
2118   // Should we enter the source file? Set to Skip if either the source file is
2119   // known to have no effect beyond its effect on module visibility -- that is,
2120   // if it's got an include guard that is already defined, set to Import if it
2121   // is a modular header we've already built and should import.
2122   enum { Enter, Import, Skip, IncludeLimitReached } Action = Enter;
2123 
2124   if (PPOpts->SingleFileParseMode)
2125     Action = IncludeLimitReached;
2126 
2127   // If we've reached the max allowed include depth, it is usually due to an
2128   // include cycle. Don't enter already processed files again as it can lead to
2129   // reaching the max allowed include depth again.
2130   if (Action == Enter && HasReachedMaxIncludeDepth && File &&
2131       alreadyIncluded(*File))
2132     Action = IncludeLimitReached;
2133 
2134   // Determine whether we should try to import the module for this #include, if
2135   // there is one. Don't do so if precompiled module support is disabled or we
2136   // are processing this module textually (because we're building the module).
2137   if (Action == Enter && File && SuggestedModule && getLangOpts().Modules &&
2138       !isForModuleBuilding(SuggestedModule.getModule(),
2139                            getLangOpts().CurrentModule,
2140                            getLangOpts().ModuleName)) {
2141     // If this include corresponds to a module but that module is
2142     // unavailable, diagnose the situation and bail out.
2143     // FIXME: Remove this; loadModule does the same check (but produces
2144     // slightly worse diagnostics).
2145     if (checkModuleIsAvailable(getLangOpts(), getTargetInfo(), getDiagnostics(),
2146                                SuggestedModule.getModule())) {
2147       Diag(FilenameTok.getLocation(),
2148            diag::note_implicit_top_level_module_import_here)
2149           << SuggestedModule.getModule()->getTopLevelModuleName();
2150       return {ImportAction::None};
2151     }
2152 
2153     // Compute the module access path corresponding to this module.
2154     // FIXME: Should we have a second loadModule() overload to avoid this
2155     // extra lookup step?
2156     SmallVector<std::pair<IdentifierInfo *, SourceLocation>, 2> Path;
2157     for (Module *Mod = SuggestedModule.getModule(); Mod; Mod = Mod->Parent)
2158       Path.push_back(std::make_pair(getIdentifierInfo(Mod->Name),
2159                                     FilenameTok.getLocation()));
2160     std::reverse(Path.begin(), Path.end());
2161 
2162     // Warn that we're replacing the include/import with a module import.
2163     if (!IsImportDecl)
2164       diagnoseAutoModuleImport(*this, StartLoc, IncludeTok, Path, CharEnd);
2165 
2166     // Load the module to import its macros. We'll make the declarations
2167     // visible when the parser gets here.
2168     // FIXME: Pass SuggestedModule in here rather than converting it to a path
2169     // and making the module loader convert it back again.
2170     ModuleLoadResult Imported = TheModuleLoader.loadModule(
2171         IncludeTok.getLocation(), Path, Module::Hidden,
2172         /*IsInclusionDirective=*/true);
2173     assert((Imported == nullptr || Imported == SuggestedModule.getModule()) &&
2174            "the imported module is different than the suggested one");
2175 
2176     if (Imported) {
2177       Action = Import;
2178     } else if (Imported.isMissingExpected()) {
2179       // We failed to find a submodule that we assumed would exist (because it
2180       // was in the directory of an umbrella header, for instance), but no
2181       // actual module containing it exists (because the umbrella header is
2182       // incomplete).  Treat this as a textual inclusion.
2183       SuggestedModule = ModuleMap::KnownHeader();
2184     } else if (Imported.isConfigMismatch()) {
2185       // On a configuration mismatch, enter the header textually. We still know
2186       // that it's part of the corresponding module.
2187     } else {
2188       // We hit an error processing the import. Bail out.
2189       if (hadModuleLoaderFatalFailure()) {
2190         // With a fatal failure in the module loader, we abort parsing.
2191         Token &Result = IncludeTok;
2192         assert(CurLexer && "#include but no current lexer set!");
2193         Result.startToken();
2194         CurLexer->FormTokenWithChars(Result, CurLexer->BufferEnd, tok::eof);
2195         CurLexer->cutOffLexing();
2196       }
2197       return {ImportAction::None};
2198     }
2199   }
2200 
2201   // The #included file will be considered to be a system header if either it is
2202   // in a system include directory, or if the #includer is a system include
2203   // header.
2204   SrcMgr::CharacteristicKind FileCharacter =
2205       SourceMgr.getFileCharacteristic(FilenameTok.getLocation());
2206   if (File)
2207     FileCharacter = std::max(HeaderInfo.getFileDirFlavor(&File->getFileEntry()),
2208                              FileCharacter);
2209 
2210   // If this is a '#import' or an import-declaration, don't re-enter the file.
2211   //
2212   // FIXME: If we have a suggested module for a '#include', and we've already
2213   // visited this file, don't bother entering it again. We know it has no
2214   // further effect.
2215   bool EnterOnce =
2216       IsImportDecl ||
2217       IncludeTok.getIdentifierInfo()->getPPKeywordID() == tok::pp_import;
2218 
2219   bool IsFirstIncludeOfFile = false;
2220 
2221   // Ask HeaderInfo if we should enter this #include file.  If not, #including
2222   // this file will have no effect.
2223   if (Action == Enter && File &&
2224       !HeaderInfo.ShouldEnterIncludeFile(
2225           *this, &File->getFileEntry(), EnterOnce, getLangOpts().Modules,
2226           SuggestedModule.getModule(), IsFirstIncludeOfFile)) {
2227     // Even if we've already preprocessed this header once and know that we
2228     // don't need to see its contents again, we still need to import it if it's
2229     // modular because we might not have imported it from this submodule before.
2230     //
2231     // FIXME: We don't do this when compiling a PCH because the AST
2232     // serialization layer can't cope with it. This means we get local
2233     // submodule visibility semantics wrong in that case.
2234     Action = (SuggestedModule && !getLangOpts().CompilingPCH) ? Import : Skip;
2235   }
2236 
2237   // Check for circular inclusion of the main file.
2238   // We can't generate a consistent preamble with regard to the conditional
2239   // stack if the main file is included again as due to the preamble bounds
2240   // some directives (e.g. #endif of a header guard) will never be seen.
2241   // Since this will lead to confusing errors, avoid the inclusion.
2242   if (Action == Enter && File && PreambleConditionalStack.isRecording() &&
2243       SourceMgr.isMainFile(File->getFileEntry())) {
2244     Diag(FilenameTok.getLocation(),
2245          diag::err_pp_including_mainfile_in_preamble);
2246     return {ImportAction::None};
2247   }
2248 
2249   if (Callbacks && !IsImportDecl) {
2250     // Notify the callback object that we've seen an inclusion directive.
2251     // FIXME: Use a different callback for a pp-import?
2252     Callbacks->InclusionDirective(HashLoc, IncludeTok, LookupFilename, isAngled,
2253                                   FilenameRange, File, SearchPath, RelativePath,
2254                                   Action == Import ? SuggestedModule.getModule()
2255                                                    : nullptr,
2256                                   FileCharacter);
2257     if (Action == Skip && File)
2258       Callbacks->FileSkipped(*File, FilenameTok, FileCharacter);
2259   }
2260 
2261   if (!File)
2262     return {ImportAction::None};
2263 
2264   // If this is a C++20 pp-import declaration, diagnose if we didn't find any
2265   // module corresponding to the named header.
2266   if (IsImportDecl && !SuggestedModule) {
2267     Diag(FilenameTok, diag::err_header_import_not_header_unit)
2268       << OriginalFilename << File->getName();
2269     return {ImportAction::None};
2270   }
2271 
2272   // Issue a diagnostic if the name of the file on disk has a different case
2273   // than the one we're about to open.
2274   const bool CheckIncludePathPortability =
2275       !IsMapped && !File->getFileEntry().tryGetRealPathName().empty();
2276 
2277   if (CheckIncludePathPortability) {
2278     StringRef Name = LookupFilename;
2279     StringRef NameWithoriginalSlashes = Filename;
2280 #if defined(_WIN32)
2281     // Skip UNC prefix if present. (tryGetRealPathName() always
2282     // returns a path with the prefix skipped.)
2283     bool NameWasUNC = Name.consume_front("\\\\?\\");
2284     NameWithoriginalSlashes.consume_front("\\\\?\\");
2285 #endif
2286     StringRef RealPathName = File->getFileEntry().tryGetRealPathName();
2287     SmallVector<StringRef, 16> Components(llvm::sys::path::begin(Name),
2288                                           llvm::sys::path::end(Name));
2289 #if defined(_WIN32)
2290     // -Wnonportable-include-path is designed to diagnose includes using
2291     // case even on systems with a case-insensitive file system.
2292     // On Windows, RealPathName always starts with an upper-case drive
2293     // letter for absolute paths, but Name might start with either
2294     // case depending on if `cd c:\foo` or `cd C:\foo` was used in the shell.
2295     // ("foo" will always have on-disk case, no matter which case was
2296     // used in the cd command). To not emit this warning solely for
2297     // the drive letter, whose case is dependent on if `cd` is used
2298     // with upper- or lower-case drive letters, always consider the
2299     // given drive letter case as correct for the purpose of this warning.
2300     SmallString<128> FixedDriveRealPath;
2301     if (llvm::sys::path::is_absolute(Name) &&
2302         llvm::sys::path::is_absolute(RealPathName) &&
2303         toLowercase(Name[0]) == toLowercase(RealPathName[0]) &&
2304         isLowercase(Name[0]) != isLowercase(RealPathName[0])) {
2305       assert(Components.size() >= 3 && "should have drive, backslash, name");
2306       assert(Components[0].size() == 2 && "should start with drive");
2307       assert(Components[0][1] == ':' && "should have colon");
2308       FixedDriveRealPath = (Name.substr(0, 1) + RealPathName.substr(1)).str();
2309       RealPathName = FixedDriveRealPath;
2310     }
2311 #endif
2312 
2313     if (trySimplifyPath(Components, RealPathName)) {
2314       SmallString<128> Path;
2315       Path.reserve(Name.size()+2);
2316       Path.push_back(isAngled ? '<' : '"');
2317 
2318       const auto IsSep = [BackslashStyle](char c) {
2319         return llvm::sys::path::is_separator(c, BackslashStyle);
2320       };
2321 
2322       for (auto Component : Components) {
2323         // On POSIX, Components will contain a single '/' as first element
2324         // exactly if Name is an absolute path.
2325         // On Windows, it will contain "C:" followed by '\' for absolute paths.
2326         // The drive letter is optional for absolute paths on Windows, but
2327         // clang currently cannot process absolute paths in #include lines that
2328         // don't have a drive.
2329         // If the first entry in Components is a directory separator,
2330         // then the code at the bottom of this loop that keeps the original
2331         // directory separator style copies it. If the second entry is
2332         // a directory separator (the C:\ case), then that separator already
2333         // got copied when the C: was processed and we want to skip that entry.
2334         if (!(Component.size() == 1 && IsSep(Component[0])))
2335           Path.append(Component);
2336         else if (!Path.empty())
2337           continue;
2338 
2339         // Append the separator(s) the user used, or the close quote
2340         if (Path.size() > NameWithoriginalSlashes.size()) {
2341           Path.push_back(isAngled ? '>' : '"');
2342           continue;
2343         }
2344         assert(IsSep(NameWithoriginalSlashes[Path.size()-1]));
2345         do
2346           Path.push_back(NameWithoriginalSlashes[Path.size()-1]);
2347         while (Path.size() <= NameWithoriginalSlashes.size() &&
2348                IsSep(NameWithoriginalSlashes[Path.size()-1]));
2349       }
2350 
2351 #if defined(_WIN32)
2352       // Restore UNC prefix if it was there.
2353       if (NameWasUNC)
2354         Path = (Path.substr(0, 1) + "\\\\?\\" + Path.substr(1)).str();
2355 #endif
2356 
2357       // For user files and known standard headers, issue a diagnostic.
2358       // For other system headers, don't. They can be controlled separately.
2359       auto DiagId =
2360           (FileCharacter == SrcMgr::C_User || warnByDefaultOnWrongCase(Name))
2361               ? diag::pp_nonportable_path
2362               : diag::pp_nonportable_system_path;
2363       Diag(FilenameTok, DiagId) << Path <<
2364         FixItHint::CreateReplacement(FilenameRange, Path);
2365     }
2366   }
2367 
2368   switch (Action) {
2369   case Skip:
2370     // If we don't need to enter the file, stop now.
2371     if (Module *M = SuggestedModule.getModule())
2372       return {ImportAction::SkippedModuleImport, M};
2373     return {ImportAction::None};
2374 
2375   case IncludeLimitReached:
2376     // If we reached our include limit and don't want to enter any more files,
2377     // don't go any further.
2378     return {ImportAction::None};
2379 
2380   case Import: {
2381     // If this is a module import, make it visible if needed.
2382     Module *M = SuggestedModule.getModule();
2383     assert(M && "no module to import");
2384 
2385     makeModuleVisible(M, EndLoc);
2386 
2387     if (IncludeTok.getIdentifierInfo()->getPPKeywordID() ==
2388         tok::pp___include_macros)
2389       return {ImportAction::None};
2390 
2391     return {ImportAction::ModuleImport, M};
2392   }
2393 
2394   case Enter:
2395     break;
2396   }
2397 
2398   // Check that we don't have infinite #include recursion.
2399   if (IncludeMacroStack.size() == MaxAllowedIncludeStackDepth-1) {
2400     Diag(FilenameTok, diag::err_pp_include_too_deep);
2401     HasReachedMaxIncludeDepth = true;
2402     return {ImportAction::None};
2403   }
2404 
2405   // Look up the file, create a File ID for it.
2406   SourceLocation IncludePos = FilenameTok.getLocation();
2407   // If the filename string was the result of macro expansions, set the include
2408   // position on the file where it will be included and after the expansions.
2409   if (IncludePos.isMacroID())
2410     IncludePos = SourceMgr.getExpansionRange(IncludePos).getEnd();
2411   FileID FID = SourceMgr.createFileID(*File, IncludePos, FileCharacter);
2412   if (!FID.isValid()) {
2413     TheModuleLoader.HadFatalFailure = true;
2414     return ImportAction::Failure;
2415   }
2416 
2417   // If all is good, enter the new file!
2418   if (EnterSourceFile(FID, CurDir, FilenameTok.getLocation(),
2419                       IsFirstIncludeOfFile))
2420     return {ImportAction::None};
2421 
2422   // Determine if we're switching to building a new submodule, and which one.
2423   if (auto *M = SuggestedModule.getModule()) {
2424     if (M->getTopLevelModule()->ShadowingModule) {
2425       // We are building a submodule that belongs to a shadowed module. This
2426       // means we find header files in the shadowed module.
2427       Diag(M->DefinitionLoc, diag::err_module_build_shadowed_submodule)
2428         << M->getFullModuleName();
2429       Diag(M->getTopLevelModule()->ShadowingModule->DefinitionLoc,
2430            diag::note_previous_definition);
2431       return {ImportAction::None};
2432     }
2433     // When building a pch, -fmodule-name tells the compiler to textually
2434     // include headers in the specified module. We are not building the
2435     // specified module.
2436     //
2437     // FIXME: This is the wrong way to handle this. We should produce a PCH
2438     // that behaves the same as the header would behave in a compilation using
2439     // that PCH, which means we should enter the submodule. We need to teach
2440     // the AST serialization layer to deal with the resulting AST.
2441     if (getLangOpts().CompilingPCH &&
2442         isForModuleBuilding(M, getLangOpts().CurrentModule,
2443                             getLangOpts().ModuleName))
2444       return {ImportAction::None};
2445 
2446     assert(!CurLexerSubmodule && "should not have marked this as a module yet");
2447     CurLexerSubmodule = M;
2448 
2449     // Let the macro handling code know that any future macros are within
2450     // the new submodule.
2451     EnterSubmodule(M, EndLoc, /*ForPragma*/false);
2452 
2453     // Let the parser know that any future declarations are within the new
2454     // submodule.
2455     // FIXME: There's no point doing this if we're handling a #__include_macros
2456     // directive.
2457     return {ImportAction::ModuleBegin, M};
2458   }
2459 
2460   assert(!IsImportDecl && "failed to diagnose missing module for import decl");
2461   return {ImportAction::None};
2462 }
2463 
2464 /// HandleIncludeNextDirective - Implements \#include_next.
2465 ///
2466 void Preprocessor::HandleIncludeNextDirective(SourceLocation HashLoc,
2467                                               Token &IncludeNextTok) {
2468   Diag(IncludeNextTok, diag::ext_pp_include_next_directive);
2469 
2470   ConstSearchDirIterator Lookup = nullptr;
2471   const FileEntry *LookupFromFile;
2472   std::tie(Lookup, LookupFromFile) = getIncludeNextStart(IncludeNextTok);
2473 
2474   return HandleIncludeDirective(HashLoc, IncludeNextTok, Lookup,
2475                                 LookupFromFile);
2476 }
2477 
2478 /// HandleMicrosoftImportDirective - Implements \#import for Microsoft Mode
2479 void Preprocessor::HandleMicrosoftImportDirective(Token &Tok) {
2480   // The Microsoft #import directive takes a type library and generates header
2481   // files from it, and includes those.  This is beyond the scope of what clang
2482   // does, so we ignore it and error out.  However, #import can optionally have
2483   // trailing attributes that span multiple lines.  We're going to eat those
2484   // so we can continue processing from there.
2485   Diag(Tok, diag::err_pp_import_directive_ms );
2486 
2487   // Read tokens until we get to the end of the directive.  Note that the
2488   // directive can be split over multiple lines using the backslash character.
2489   DiscardUntilEndOfDirective();
2490 }
2491 
2492 /// HandleImportDirective - Implements \#import.
2493 ///
2494 void Preprocessor::HandleImportDirective(SourceLocation HashLoc,
2495                                          Token &ImportTok) {
2496   if (!LangOpts.ObjC) {  // #import is standard for ObjC.
2497     if (LangOpts.MSVCCompat)
2498       return HandleMicrosoftImportDirective(ImportTok);
2499     Diag(ImportTok, diag::ext_pp_import_directive);
2500   }
2501   return HandleIncludeDirective(HashLoc, ImportTok);
2502 }
2503 
2504 /// HandleIncludeMacrosDirective - The -imacros command line option turns into a
2505 /// pseudo directive in the predefines buffer.  This handles it by sucking all
2506 /// tokens through the preprocessor and discarding them (only keeping the side
2507 /// effects on the preprocessor).
2508 void Preprocessor::HandleIncludeMacrosDirective(SourceLocation HashLoc,
2509                                                 Token &IncludeMacrosTok) {
2510   // This directive should only occur in the predefines buffer.  If not, emit an
2511   // error and reject it.
2512   SourceLocation Loc = IncludeMacrosTok.getLocation();
2513   if (SourceMgr.getBufferName(Loc) != "<built-in>") {
2514     Diag(IncludeMacrosTok.getLocation(),
2515          diag::pp_include_macros_out_of_predefines);
2516     DiscardUntilEndOfDirective();
2517     return;
2518   }
2519 
2520   // Treat this as a normal #include for checking purposes.  If this is
2521   // successful, it will push a new lexer onto the include stack.
2522   HandleIncludeDirective(HashLoc, IncludeMacrosTok);
2523 
2524   Token TmpTok;
2525   do {
2526     Lex(TmpTok);
2527     assert(TmpTok.isNot(tok::eof) && "Didn't find end of -imacros!");
2528   } while (TmpTok.isNot(tok::hashhash));
2529 }
2530 
2531 //===----------------------------------------------------------------------===//
2532 // Preprocessor Macro Directive Handling.
2533 //===----------------------------------------------------------------------===//
2534 
2535 /// ReadMacroParameterList - The ( starting a parameter list of a macro
2536 /// definition has just been read.  Lex the rest of the parameters and the
2537 /// closing ), updating MI with what we learn.  Return true if an error occurs
2538 /// parsing the param list.
2539 bool Preprocessor::ReadMacroParameterList(MacroInfo *MI, Token &Tok) {
2540   SmallVector<IdentifierInfo*, 32> Parameters;
2541 
2542   while (true) {
2543     LexUnexpandedToken(Tok);
2544     switch (Tok.getKind()) {
2545     case tok::r_paren:
2546       // Found the end of the parameter list.
2547       if (Parameters.empty())  // #define FOO()
2548         return false;
2549       // Otherwise we have #define FOO(A,)
2550       Diag(Tok, diag::err_pp_expected_ident_in_arg_list);
2551       return true;
2552     case tok::ellipsis:  // #define X(... -> C99 varargs
2553       if (!LangOpts.C99)
2554         Diag(Tok, LangOpts.CPlusPlus11 ?
2555              diag::warn_cxx98_compat_variadic_macro :
2556              diag::ext_variadic_macro);
2557 
2558       // OpenCL v1.2 s6.9.e: variadic macros are not supported.
2559       if (LangOpts.OpenCL && !LangOpts.OpenCLCPlusPlus) {
2560         Diag(Tok, diag::ext_pp_opencl_variadic_macros);
2561       }
2562 
2563       // Lex the token after the identifier.
2564       LexUnexpandedToken(Tok);
2565       if (Tok.isNot(tok::r_paren)) {
2566         Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
2567         return true;
2568       }
2569       // Add the __VA_ARGS__ identifier as a parameter.
2570       Parameters.push_back(Ident__VA_ARGS__);
2571       MI->setIsC99Varargs();
2572       MI->setParameterList(Parameters, BP);
2573       return false;
2574     case tok::eod:  // #define X(
2575       Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
2576       return true;
2577     default:
2578       // Handle keywords and identifiers here to accept things like
2579       // #define Foo(for) for.
2580       IdentifierInfo *II = Tok.getIdentifierInfo();
2581       if (!II) {
2582         // #define X(1
2583         Diag(Tok, diag::err_pp_invalid_tok_in_arg_list);
2584         return true;
2585       }
2586 
2587       // If this is already used as a parameter, it is used multiple times (e.g.
2588       // #define X(A,A.
2589       if (llvm::is_contained(Parameters, II)) { // C99 6.10.3p6
2590         Diag(Tok, diag::err_pp_duplicate_name_in_arg_list) << II;
2591         return true;
2592       }
2593 
2594       // Add the parameter to the macro info.
2595       Parameters.push_back(II);
2596 
2597       // Lex the token after the identifier.
2598       LexUnexpandedToken(Tok);
2599 
2600       switch (Tok.getKind()) {
2601       default:          // #define X(A B
2602         Diag(Tok, diag::err_pp_expected_comma_in_arg_list);
2603         return true;
2604       case tok::r_paren: // #define X(A)
2605         MI->setParameterList(Parameters, BP);
2606         return false;
2607       case tok::comma:  // #define X(A,
2608         break;
2609       case tok::ellipsis:  // #define X(A... -> GCC extension
2610         // Diagnose extension.
2611         Diag(Tok, diag::ext_named_variadic_macro);
2612 
2613         // Lex the token after the identifier.
2614         LexUnexpandedToken(Tok);
2615         if (Tok.isNot(tok::r_paren)) {
2616           Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
2617           return true;
2618         }
2619 
2620         MI->setIsGNUVarargs();
2621         MI->setParameterList(Parameters, BP);
2622         return false;
2623       }
2624     }
2625   }
2626 }
2627 
2628 static bool isConfigurationPattern(Token &MacroName, MacroInfo *MI,
2629                                    const LangOptions &LOptions) {
2630   if (MI->getNumTokens() == 1) {
2631     const Token &Value = MI->getReplacementToken(0);
2632 
2633     // Macro that is identity, like '#define inline inline' is a valid pattern.
2634     if (MacroName.getKind() == Value.getKind())
2635       return true;
2636 
2637     // Macro that maps a keyword to the same keyword decorated with leading/
2638     // trailing underscores is a valid pattern:
2639     //    #define inline __inline
2640     //    #define inline __inline__
2641     //    #define inline _inline (in MS compatibility mode)
2642     StringRef MacroText = MacroName.getIdentifierInfo()->getName();
2643     if (IdentifierInfo *II = Value.getIdentifierInfo()) {
2644       if (!II->isKeyword(LOptions))
2645         return false;
2646       StringRef ValueText = II->getName();
2647       StringRef TrimmedValue = ValueText;
2648       if (!ValueText.startswith("__")) {
2649         if (ValueText.startswith("_"))
2650           TrimmedValue = TrimmedValue.drop_front(1);
2651         else
2652           return false;
2653       } else {
2654         TrimmedValue = TrimmedValue.drop_front(2);
2655         if (TrimmedValue.endswith("__"))
2656           TrimmedValue = TrimmedValue.drop_back(2);
2657       }
2658       return TrimmedValue.equals(MacroText);
2659     } else {
2660       return false;
2661     }
2662   }
2663 
2664   // #define inline
2665   return MacroName.isOneOf(tok::kw_extern, tok::kw_inline, tok::kw_static,
2666                            tok::kw_const) &&
2667          MI->getNumTokens() == 0;
2668 }
2669 
2670 // ReadOptionalMacroParameterListAndBody - This consumes all (i.e. the
2671 // entire line) of the macro's tokens and adds them to MacroInfo, and while
2672 // doing so performs certain validity checks including (but not limited to):
2673 //   - # (stringization) is followed by a macro parameter
2674 //
2675 //  Returns a nullptr if an invalid sequence of tokens is encountered or returns
2676 //  a pointer to a MacroInfo object.
2677 
2678 MacroInfo *Preprocessor::ReadOptionalMacroParameterListAndBody(
2679     const Token &MacroNameTok, const bool ImmediatelyAfterHeaderGuard) {
2680 
2681   Token LastTok = MacroNameTok;
2682   // Create the new macro.
2683   MacroInfo *const MI = AllocateMacroInfo(MacroNameTok.getLocation());
2684 
2685   Token Tok;
2686   LexUnexpandedToken(Tok);
2687 
2688   // Ensure we consume the rest of the macro body if errors occur.
2689   auto _ = llvm::make_scope_exit([&]() {
2690     // The flag indicates if we are still waiting for 'eod'.
2691     if (CurLexer->ParsingPreprocessorDirective)
2692       DiscardUntilEndOfDirective();
2693   });
2694 
2695   // Used to un-poison and then re-poison identifiers of the __VA_ARGS__ ilk
2696   // within their appropriate context.
2697   VariadicMacroScopeGuard VariadicMacroScopeGuard(*this);
2698 
2699   // If this is a function-like macro definition, parse the argument list,
2700   // marking each of the identifiers as being used as macro arguments.  Also,
2701   // check other constraints on the first token of the macro body.
2702   if (Tok.is(tok::eod)) {
2703     if (ImmediatelyAfterHeaderGuard) {
2704       // Save this macro information since it may part of a header guard.
2705       CurPPLexer->MIOpt.SetDefinedMacro(MacroNameTok.getIdentifierInfo(),
2706                                         MacroNameTok.getLocation());
2707     }
2708     // If there is no body to this macro, we have no special handling here.
2709   } else if (Tok.hasLeadingSpace()) {
2710     // This is a normal token with leading space.  Clear the leading space
2711     // marker on the first token to get proper expansion.
2712     Tok.clearFlag(Token::LeadingSpace);
2713   } else if (Tok.is(tok::l_paren)) {
2714     // This is a function-like macro definition.  Read the argument list.
2715     MI->setIsFunctionLike();
2716     if (ReadMacroParameterList(MI, LastTok))
2717       return nullptr;
2718 
2719     // If this is a definition of an ISO C/C++ variadic function-like macro (not
2720     // using the GNU named varargs extension) inform our variadic scope guard
2721     // which un-poisons and re-poisons certain identifiers (e.g. __VA_ARGS__)
2722     // allowed only within the definition of a variadic macro.
2723 
2724     if (MI->isC99Varargs()) {
2725       VariadicMacroScopeGuard.enterScope();
2726     }
2727 
2728     // Read the first token after the arg list for down below.
2729     LexUnexpandedToken(Tok);
2730   } else if (LangOpts.C99 || LangOpts.CPlusPlus11) {
2731     // C99 requires whitespace between the macro definition and the body.  Emit
2732     // a diagnostic for something like "#define X+".
2733     Diag(Tok, diag::ext_c99_whitespace_required_after_macro_name);
2734   } else {
2735     // C90 6.8 TC1 says: "In the definition of an object-like macro, if the
2736     // first character of a replacement list is not a character required by
2737     // subclause 5.2.1, then there shall be white-space separation between the
2738     // identifier and the replacement list.".  5.2.1 lists this set:
2739     //   "A-Za-z0-9!"#%&'()*+,_./:;<=>?[\]^_{|}~" as well as whitespace, which
2740     // is irrelevant here.
2741     bool isInvalid = false;
2742     if (Tok.is(tok::at)) // @ is not in the list above.
2743       isInvalid = true;
2744     else if (Tok.is(tok::unknown)) {
2745       // If we have an unknown token, it is something strange like "`".  Since
2746       // all of valid characters would have lexed into a single character
2747       // token of some sort, we know this is not a valid case.
2748       isInvalid = true;
2749     }
2750     if (isInvalid)
2751       Diag(Tok, diag::ext_missing_whitespace_after_macro_name);
2752     else
2753       Diag(Tok, diag::warn_missing_whitespace_after_macro_name);
2754   }
2755 
2756   if (!Tok.is(tok::eod))
2757     LastTok = Tok;
2758 
2759   SmallVector<Token, 16> Tokens;
2760 
2761   // Read the rest of the macro body.
2762   if (MI->isObjectLike()) {
2763     // Object-like macros are very simple, just read their body.
2764     while (Tok.isNot(tok::eod)) {
2765       LastTok = Tok;
2766       Tokens.push_back(Tok);
2767       // Get the next token of the macro.
2768       LexUnexpandedToken(Tok);
2769     }
2770   } else {
2771     // Otherwise, read the body of a function-like macro.  While we are at it,
2772     // check C99 6.10.3.2p1: ensure that # operators are followed by macro
2773     // parameters in function-like macro expansions.
2774 
2775     VAOptDefinitionContext VAOCtx(*this);
2776 
2777     while (Tok.isNot(tok::eod)) {
2778       LastTok = Tok;
2779 
2780       if (!Tok.isOneOf(tok::hash, tok::hashat, tok::hashhash)) {
2781         Tokens.push_back(Tok);
2782 
2783         if (VAOCtx.isVAOptToken(Tok)) {
2784           // If we're already within a VAOPT, emit an error.
2785           if (VAOCtx.isInVAOpt()) {
2786             Diag(Tok, diag::err_pp_vaopt_nested_use);
2787             return nullptr;
2788           }
2789           // Ensure VAOPT is followed by a '(' .
2790           LexUnexpandedToken(Tok);
2791           if (Tok.isNot(tok::l_paren)) {
2792             Diag(Tok, diag::err_pp_missing_lparen_in_vaopt_use);
2793             return nullptr;
2794           }
2795           Tokens.push_back(Tok);
2796           VAOCtx.sawVAOptFollowedByOpeningParens(Tok.getLocation());
2797           LexUnexpandedToken(Tok);
2798           if (Tok.is(tok::hashhash)) {
2799             Diag(Tok, diag::err_vaopt_paste_at_start);
2800             return nullptr;
2801           }
2802           continue;
2803         } else if (VAOCtx.isInVAOpt()) {
2804           if (Tok.is(tok::r_paren)) {
2805             if (VAOCtx.sawClosingParen()) {
2806               assert(Tokens.size() >= 3 &&
2807                      "Must have seen at least __VA_OPT__( "
2808                      "and a subsequent tok::r_paren");
2809               if (Tokens[Tokens.size() - 2].is(tok::hashhash)) {
2810                 Diag(Tok, diag::err_vaopt_paste_at_end);
2811                 return nullptr;
2812               }
2813             }
2814           } else if (Tok.is(tok::l_paren)) {
2815             VAOCtx.sawOpeningParen(Tok.getLocation());
2816           }
2817         }
2818         // Get the next token of the macro.
2819         LexUnexpandedToken(Tok);
2820         continue;
2821       }
2822 
2823       // If we're in -traditional mode, then we should ignore stringification
2824       // and token pasting. Mark the tokens as unknown so as not to confuse
2825       // things.
2826       if (getLangOpts().TraditionalCPP) {
2827         Tok.setKind(tok::unknown);
2828         Tokens.push_back(Tok);
2829 
2830         // Get the next token of the macro.
2831         LexUnexpandedToken(Tok);
2832         continue;
2833       }
2834 
2835       if (Tok.is(tok::hashhash)) {
2836         // If we see token pasting, check if it looks like the gcc comma
2837         // pasting extension.  We'll use this information to suppress
2838         // diagnostics later on.
2839 
2840         // Get the next token of the macro.
2841         LexUnexpandedToken(Tok);
2842 
2843         if (Tok.is(tok::eod)) {
2844           Tokens.push_back(LastTok);
2845           break;
2846         }
2847 
2848         if (!Tokens.empty() && Tok.getIdentifierInfo() == Ident__VA_ARGS__ &&
2849             Tokens[Tokens.size() - 1].is(tok::comma))
2850           MI->setHasCommaPasting();
2851 
2852         // Things look ok, add the '##' token to the macro.
2853         Tokens.push_back(LastTok);
2854         continue;
2855       }
2856 
2857       // Our Token is a stringization operator.
2858       // Get the next token of the macro.
2859       LexUnexpandedToken(Tok);
2860 
2861       // Check for a valid macro arg identifier or __VA_OPT__.
2862       if (!VAOCtx.isVAOptToken(Tok) &&
2863           (Tok.getIdentifierInfo() == nullptr ||
2864            MI->getParameterNum(Tok.getIdentifierInfo()) == -1)) {
2865 
2866         // If this is assembler-with-cpp mode, we accept random gibberish after
2867         // the '#' because '#' is often a comment character.  However, change
2868         // the kind of the token to tok::unknown so that the preprocessor isn't
2869         // confused.
2870         if (getLangOpts().AsmPreprocessor && Tok.isNot(tok::eod)) {
2871           LastTok.setKind(tok::unknown);
2872           Tokens.push_back(LastTok);
2873           continue;
2874         } else {
2875           Diag(Tok, diag::err_pp_stringize_not_parameter)
2876             << LastTok.is(tok::hashat);
2877           return nullptr;
2878         }
2879       }
2880 
2881       // Things look ok, add the '#' and param name tokens to the macro.
2882       Tokens.push_back(LastTok);
2883 
2884       // If the token following '#' is VAOPT, let the next iteration handle it
2885       // and check it for correctness, otherwise add the token and prime the
2886       // loop with the next one.
2887       if (!VAOCtx.isVAOptToken(Tok)) {
2888         Tokens.push_back(Tok);
2889         LastTok = Tok;
2890 
2891         // Get the next token of the macro.
2892         LexUnexpandedToken(Tok);
2893       }
2894     }
2895     if (VAOCtx.isInVAOpt()) {
2896       assert(Tok.is(tok::eod) && "Must be at End Of preprocessing Directive");
2897       Diag(Tok, diag::err_pp_expected_after)
2898         << LastTok.getKind() << tok::r_paren;
2899       Diag(VAOCtx.getUnmatchedOpeningParenLoc(), diag::note_matching) << tok::l_paren;
2900       return nullptr;
2901     }
2902   }
2903   MI->setDefinitionEndLoc(LastTok.getLocation());
2904 
2905   MI->setTokens(Tokens, BP);
2906   return MI;
2907 }
2908 /// HandleDefineDirective - Implements \#define.  This consumes the entire macro
2909 /// line then lets the caller lex the next real token.
2910 void Preprocessor::HandleDefineDirective(
2911     Token &DefineTok, const bool ImmediatelyAfterHeaderGuard) {
2912   ++NumDefined;
2913 
2914   Token MacroNameTok;
2915   bool MacroShadowsKeyword;
2916   ReadMacroName(MacroNameTok, MU_Define, &MacroShadowsKeyword);
2917 
2918   // Error reading macro name?  If so, diagnostic already issued.
2919   if (MacroNameTok.is(tok::eod))
2920     return;
2921 
2922   IdentifierInfo *II = MacroNameTok.getIdentifierInfo();
2923   // Issue a final pragma warning if we're defining a macro that was has been
2924   // undefined and is being redefined.
2925   if (!II->hasMacroDefinition() && II->hadMacroDefinition() && II->isFinal())
2926     emitFinalMacroWarning(MacroNameTok, /*IsUndef=*/false);
2927 
2928   // If we are supposed to keep comments in #defines, reenable comment saving
2929   // mode.
2930   if (CurLexer) CurLexer->SetCommentRetentionState(KeepMacroComments);
2931 
2932   MacroInfo *const MI = ReadOptionalMacroParameterListAndBody(
2933       MacroNameTok, ImmediatelyAfterHeaderGuard);
2934 
2935   if (!MI) return;
2936 
2937   if (MacroShadowsKeyword &&
2938       !isConfigurationPattern(MacroNameTok, MI, getLangOpts())) {
2939     Diag(MacroNameTok, diag::warn_pp_macro_hides_keyword);
2940   }
2941   // Check that there is no paste (##) operator at the beginning or end of the
2942   // replacement list.
2943   unsigned NumTokens = MI->getNumTokens();
2944   if (NumTokens != 0) {
2945     if (MI->getReplacementToken(0).is(tok::hashhash)) {
2946       Diag(MI->getReplacementToken(0), diag::err_paste_at_start);
2947       return;
2948     }
2949     if (MI->getReplacementToken(NumTokens-1).is(tok::hashhash)) {
2950       Diag(MI->getReplacementToken(NumTokens-1), diag::err_paste_at_end);
2951       return;
2952     }
2953   }
2954 
2955   // When skipping just warn about macros that do not match.
2956   if (SkippingUntilPCHThroughHeader) {
2957     const MacroInfo *OtherMI = getMacroInfo(MacroNameTok.getIdentifierInfo());
2958     if (!OtherMI || !MI->isIdenticalTo(*OtherMI, *this,
2959                              /*Syntactic=*/LangOpts.MicrosoftExt))
2960       Diag(MI->getDefinitionLoc(), diag::warn_pp_macro_def_mismatch_with_pch)
2961           << MacroNameTok.getIdentifierInfo();
2962     // Issue the diagnostic but allow the change if msvc extensions are enabled
2963     if (!LangOpts.MicrosoftExt)
2964       return;
2965   }
2966 
2967   // Finally, if this identifier already had a macro defined for it, verify that
2968   // the macro bodies are identical, and issue diagnostics if they are not.
2969   if (const MacroInfo *OtherMI=getMacroInfo(MacroNameTok.getIdentifierInfo())) {
2970     // Final macros are hard-mode: they always warn. Even if the bodies are
2971     // identical. Even if they are in system headers. Even if they are things we
2972     // would silently allow in the past.
2973     if (MacroNameTok.getIdentifierInfo()->isFinal())
2974       emitFinalMacroWarning(MacroNameTok, /*IsUndef=*/false);
2975 
2976     // In Objective-C, ignore attempts to directly redefine the builtin
2977     // definitions of the ownership qualifiers.  It's still possible to
2978     // #undef them.
2979     auto isObjCProtectedMacro = [](const IdentifierInfo *II) -> bool {
2980       return II->isStr("__strong") ||
2981              II->isStr("__weak") ||
2982              II->isStr("__unsafe_unretained") ||
2983              II->isStr("__autoreleasing");
2984     };
2985    if (getLangOpts().ObjC &&
2986         SourceMgr.getFileID(OtherMI->getDefinitionLoc())
2987           == getPredefinesFileID() &&
2988         isObjCProtectedMacro(MacroNameTok.getIdentifierInfo())) {
2989       // Warn if it changes the tokens.
2990       if ((!getDiagnostics().getSuppressSystemWarnings() ||
2991            !SourceMgr.isInSystemHeader(DefineTok.getLocation())) &&
2992           !MI->isIdenticalTo(*OtherMI, *this,
2993                              /*Syntactic=*/LangOpts.MicrosoftExt)) {
2994         Diag(MI->getDefinitionLoc(), diag::warn_pp_objc_macro_redef_ignored);
2995       }
2996       assert(!OtherMI->isWarnIfUnused());
2997       return;
2998     }
2999 
3000     // It is very common for system headers to have tons of macro redefinitions
3001     // and for warnings to be disabled in system headers.  If this is the case,
3002     // then don't bother calling MacroInfo::isIdenticalTo.
3003     if (!getDiagnostics().getSuppressSystemWarnings() ||
3004         !SourceMgr.isInSystemHeader(DefineTok.getLocation())) {
3005 
3006       if (!OtherMI->isUsed() && OtherMI->isWarnIfUnused())
3007         Diag(OtherMI->getDefinitionLoc(), diag::pp_macro_not_used);
3008 
3009       // Warn if defining "__LINE__" and other builtins, per C99 6.10.8/4 and
3010       // C++ [cpp.predefined]p4, but allow it as an extension.
3011       if (OtherMI->isBuiltinMacro())
3012         Diag(MacroNameTok, diag::ext_pp_redef_builtin_macro);
3013       // Macros must be identical.  This means all tokens and whitespace
3014       // separation must be the same.  C99 6.10.3p2.
3015       else if (!OtherMI->isAllowRedefinitionsWithoutWarning() &&
3016                !MI->isIdenticalTo(*OtherMI, *this, /*Syntactic=*/LangOpts.MicrosoftExt)) {
3017         Diag(MI->getDefinitionLoc(), diag::ext_pp_macro_redef)
3018           << MacroNameTok.getIdentifierInfo();
3019         Diag(OtherMI->getDefinitionLoc(), diag::note_previous_definition);
3020       }
3021     }
3022     if (OtherMI->isWarnIfUnused())
3023       WarnUnusedMacroLocs.erase(OtherMI->getDefinitionLoc());
3024   }
3025 
3026   DefMacroDirective *MD =
3027       appendDefMacroDirective(MacroNameTok.getIdentifierInfo(), MI);
3028 
3029   assert(!MI->isUsed());
3030   // If we need warning for not using the macro, add its location in the
3031   // warn-because-unused-macro set. If it gets used it will be removed from set.
3032   if (getSourceManager().isInMainFile(MI->getDefinitionLoc()) &&
3033       !Diags->isIgnored(diag::pp_macro_not_used, MI->getDefinitionLoc()) &&
3034       !MacroExpansionInDirectivesOverride &&
3035       getSourceManager().getFileID(MI->getDefinitionLoc()) !=
3036           getPredefinesFileID()) {
3037     MI->setIsWarnIfUnused(true);
3038     WarnUnusedMacroLocs.insert(MI->getDefinitionLoc());
3039   }
3040 
3041   // If the callbacks want to know, tell them about the macro definition.
3042   if (Callbacks)
3043     Callbacks->MacroDefined(MacroNameTok, MD);
3044 
3045   // If we're in MS compatibility mode and the macro being defined is the
3046   // assert macro, implicitly add a macro definition for static_assert to work
3047   // around their broken assert.h header file in C. Only do so if there isn't
3048   // already a static_assert macro defined.
3049   if (!getLangOpts().CPlusPlus && getLangOpts().MSVCCompat &&
3050       MacroNameTok.getIdentifierInfo()->isStr("assert") &&
3051       !isMacroDefined("static_assert")) {
3052     MacroInfo *MI = AllocateMacroInfo(SourceLocation());
3053 
3054     Token Tok;
3055     Tok.startToken();
3056     Tok.setKind(tok::kw__Static_assert);
3057     Tok.setIdentifierInfo(getIdentifierInfo("_Static_assert"));
3058     MI->setTokens({Tok}, BP);
3059     (void)appendDefMacroDirective(getIdentifierInfo("static_assert"), MI);
3060   }
3061 }
3062 
3063 /// HandleUndefDirective - Implements \#undef.
3064 ///
3065 void Preprocessor::HandleUndefDirective() {
3066   ++NumUndefined;
3067 
3068   Token MacroNameTok;
3069   ReadMacroName(MacroNameTok, MU_Undef);
3070 
3071   // Error reading macro name?  If so, diagnostic already issued.
3072   if (MacroNameTok.is(tok::eod))
3073     return;
3074 
3075   // Check to see if this is the last token on the #undef line.
3076   CheckEndOfDirective("undef");
3077 
3078   // Okay, we have a valid identifier to undef.
3079   auto *II = MacroNameTok.getIdentifierInfo();
3080   auto MD = getMacroDefinition(II);
3081   UndefMacroDirective *Undef = nullptr;
3082 
3083   if (II->isFinal())
3084     emitFinalMacroWarning(MacroNameTok, /*IsUndef=*/true);
3085 
3086   // If the macro is not defined, this is a noop undef.
3087   if (const MacroInfo *MI = MD.getMacroInfo()) {
3088     if (!MI->isUsed() && MI->isWarnIfUnused())
3089       Diag(MI->getDefinitionLoc(), diag::pp_macro_not_used);
3090 
3091     if (MI->isWarnIfUnused())
3092       WarnUnusedMacroLocs.erase(MI->getDefinitionLoc());
3093 
3094     Undef = AllocateUndefMacroDirective(MacroNameTok.getLocation());
3095   }
3096 
3097   // If the callbacks want to know, tell them about the macro #undef.
3098   // Note: no matter if the macro was defined or not.
3099   if (Callbacks)
3100     Callbacks->MacroUndefined(MacroNameTok, MD, Undef);
3101 
3102   if (Undef)
3103     appendMacroDirective(II, Undef);
3104 }
3105 
3106 //===----------------------------------------------------------------------===//
3107 // Preprocessor Conditional Directive Handling.
3108 //===----------------------------------------------------------------------===//
3109 
3110 /// HandleIfdefDirective - Implements the \#ifdef/\#ifndef directive.  isIfndef
3111 /// is true when this is a \#ifndef directive.  ReadAnyTokensBeforeDirective is
3112 /// true if any tokens have been returned or pp-directives activated before this
3113 /// \#ifndef has been lexed.
3114 ///
3115 void Preprocessor::HandleIfdefDirective(Token &Result,
3116                                         const Token &HashToken,
3117                                         bool isIfndef,
3118                                         bool ReadAnyTokensBeforeDirective) {
3119   ++NumIf;
3120   Token DirectiveTok = Result;
3121 
3122   Token MacroNameTok;
3123   ReadMacroName(MacroNameTok);
3124 
3125   // Error reading macro name?  If so, diagnostic already issued.
3126   if (MacroNameTok.is(tok::eod)) {
3127     // Skip code until we get to #endif.  This helps with recovery by not
3128     // emitting an error when the #endif is reached.
3129     SkipExcludedConditionalBlock(HashToken.getLocation(),
3130                                  DirectiveTok.getLocation(),
3131                                  /*Foundnonskip*/ false, /*FoundElse*/ false);
3132     return;
3133   }
3134 
3135   emitMacroExpansionWarnings(MacroNameTok);
3136 
3137   // Check to see if this is the last token on the #if[n]def line.
3138   CheckEndOfDirective(isIfndef ? "ifndef" : "ifdef");
3139 
3140   IdentifierInfo *MII = MacroNameTok.getIdentifierInfo();
3141   auto MD = getMacroDefinition(MII);
3142   MacroInfo *MI = MD.getMacroInfo();
3143 
3144   if (CurPPLexer->getConditionalStackDepth() == 0) {
3145     // If the start of a top-level #ifdef and if the macro is not defined,
3146     // inform MIOpt that this might be the start of a proper include guard.
3147     // Otherwise it is some other form of unknown conditional which we can't
3148     // handle.
3149     if (!ReadAnyTokensBeforeDirective && !MI) {
3150       assert(isIfndef && "#ifdef shouldn't reach here");
3151       CurPPLexer->MIOpt.EnterTopLevelIfndef(MII, MacroNameTok.getLocation());
3152     } else
3153       CurPPLexer->MIOpt.EnterTopLevelConditional();
3154   }
3155 
3156   // If there is a macro, process it.
3157   if (MI)  // Mark it used.
3158     markMacroAsUsed(MI);
3159 
3160   if (Callbacks) {
3161     if (isIfndef)
3162       Callbacks->Ifndef(DirectiveTok.getLocation(), MacroNameTok, MD);
3163     else
3164       Callbacks->Ifdef(DirectiveTok.getLocation(), MacroNameTok, MD);
3165   }
3166 
3167   bool RetainExcludedCB = PPOpts->RetainExcludedConditionalBlocks &&
3168     getSourceManager().isInMainFile(DirectiveTok.getLocation());
3169 
3170   // Should we include the stuff contained by this directive?
3171   if (PPOpts->SingleFileParseMode && !MI) {
3172     // In 'single-file-parse mode' undefined identifiers trigger parsing of all
3173     // the directive blocks.
3174     CurPPLexer->pushConditionalLevel(DirectiveTok.getLocation(),
3175                                      /*wasskip*/false, /*foundnonskip*/false,
3176                                      /*foundelse*/false);
3177   } else if (!MI == isIfndef || RetainExcludedCB) {
3178     // Yes, remember that we are inside a conditional, then lex the next token.
3179     CurPPLexer->pushConditionalLevel(DirectiveTok.getLocation(),
3180                                      /*wasskip*/false, /*foundnonskip*/true,
3181                                      /*foundelse*/false);
3182   } else {
3183     // No, skip the contents of this block.
3184     SkipExcludedConditionalBlock(HashToken.getLocation(),
3185                                  DirectiveTok.getLocation(),
3186                                  /*Foundnonskip*/ false,
3187                                  /*FoundElse*/ false);
3188   }
3189 }
3190 
3191 /// HandleIfDirective - Implements the \#if directive.
3192 ///
3193 void Preprocessor::HandleIfDirective(Token &IfToken,
3194                                      const Token &HashToken,
3195                                      bool ReadAnyTokensBeforeDirective) {
3196   ++NumIf;
3197 
3198   // Parse and evaluate the conditional expression.
3199   IdentifierInfo *IfNDefMacro = nullptr;
3200   const DirectiveEvalResult DER = EvaluateDirectiveExpression(IfNDefMacro);
3201   const bool ConditionalTrue = DER.Conditional;
3202   // Lexer might become invalid if we hit code completion point while evaluating
3203   // expression.
3204   if (!CurPPLexer)
3205     return;
3206 
3207   // If this condition is equivalent to #ifndef X, and if this is the first
3208   // directive seen, handle it for the multiple-include optimization.
3209   if (CurPPLexer->getConditionalStackDepth() == 0) {
3210     if (!ReadAnyTokensBeforeDirective && IfNDefMacro && ConditionalTrue)
3211       // FIXME: Pass in the location of the macro name, not the 'if' token.
3212       CurPPLexer->MIOpt.EnterTopLevelIfndef(IfNDefMacro, IfToken.getLocation());
3213     else
3214       CurPPLexer->MIOpt.EnterTopLevelConditional();
3215   }
3216 
3217   if (Callbacks)
3218     Callbacks->If(
3219         IfToken.getLocation(), DER.ExprRange,
3220         (ConditionalTrue ? PPCallbacks::CVK_True : PPCallbacks::CVK_False));
3221 
3222   bool RetainExcludedCB = PPOpts->RetainExcludedConditionalBlocks &&
3223     getSourceManager().isInMainFile(IfToken.getLocation());
3224 
3225   // Should we include the stuff contained by this directive?
3226   if (PPOpts->SingleFileParseMode && DER.IncludedUndefinedIds) {
3227     // In 'single-file-parse mode' undefined identifiers trigger parsing of all
3228     // the directive blocks.
3229     CurPPLexer->pushConditionalLevel(IfToken.getLocation(), /*wasskip*/false,
3230                                      /*foundnonskip*/false, /*foundelse*/false);
3231   } else if (ConditionalTrue || RetainExcludedCB) {
3232     // Yes, remember that we are inside a conditional, then lex the next token.
3233     CurPPLexer->pushConditionalLevel(IfToken.getLocation(), /*wasskip*/false,
3234                                    /*foundnonskip*/true, /*foundelse*/false);
3235   } else {
3236     // No, skip the contents of this block.
3237     SkipExcludedConditionalBlock(HashToken.getLocation(), IfToken.getLocation(),
3238                                  /*Foundnonskip*/ false,
3239                                  /*FoundElse*/ false);
3240   }
3241 }
3242 
3243 /// HandleEndifDirective - Implements the \#endif directive.
3244 ///
3245 void Preprocessor::HandleEndifDirective(Token &EndifToken) {
3246   ++NumEndif;
3247 
3248   // Check that this is the whole directive.
3249   CheckEndOfDirective("endif");
3250 
3251   PPConditionalInfo CondInfo;
3252   if (CurPPLexer->popConditionalLevel(CondInfo)) {
3253     // No conditionals on the stack: this is an #endif without an #if.
3254     Diag(EndifToken, diag::err_pp_endif_without_if);
3255     return;
3256   }
3257 
3258   // If this the end of a top-level #endif, inform MIOpt.
3259   if (CurPPLexer->getConditionalStackDepth() == 0)
3260     CurPPLexer->MIOpt.ExitTopLevelConditional();
3261 
3262   assert(!CondInfo.WasSkipping && !CurPPLexer->LexingRawMode &&
3263          "This code should only be reachable in the non-skipping case!");
3264 
3265   if (Callbacks)
3266     Callbacks->Endif(EndifToken.getLocation(), CondInfo.IfLoc);
3267 }
3268 
3269 /// HandleElseDirective - Implements the \#else directive.
3270 ///
3271 void Preprocessor::HandleElseDirective(Token &Result, const Token &HashToken) {
3272   ++NumElse;
3273 
3274   // #else directive in a non-skipping conditional... start skipping.
3275   CheckEndOfDirective("else");
3276 
3277   PPConditionalInfo CI;
3278   if (CurPPLexer->popConditionalLevel(CI)) {
3279     Diag(Result, diag::pp_err_else_without_if);
3280     return;
3281   }
3282 
3283   // If this is a top-level #else, inform the MIOpt.
3284   if (CurPPLexer->getConditionalStackDepth() == 0)
3285     CurPPLexer->MIOpt.EnterTopLevelConditional();
3286 
3287   // If this is a #else with a #else before it, report the error.
3288   if (CI.FoundElse) Diag(Result, diag::pp_err_else_after_else);
3289 
3290   if (Callbacks)
3291     Callbacks->Else(Result.getLocation(), CI.IfLoc);
3292 
3293   bool RetainExcludedCB = PPOpts->RetainExcludedConditionalBlocks &&
3294     getSourceManager().isInMainFile(Result.getLocation());
3295 
3296   if ((PPOpts->SingleFileParseMode && !CI.FoundNonSkip) || RetainExcludedCB) {
3297     // In 'single-file-parse mode' undefined identifiers trigger parsing of all
3298     // the directive blocks.
3299     CurPPLexer->pushConditionalLevel(CI.IfLoc, /*wasskip*/false,
3300                                      /*foundnonskip*/false, /*foundelse*/true);
3301     return;
3302   }
3303 
3304   // Finally, skip the rest of the contents of this block.
3305   SkipExcludedConditionalBlock(HashToken.getLocation(), CI.IfLoc,
3306                                /*Foundnonskip*/ true,
3307                                /*FoundElse*/ true, Result.getLocation());
3308 }
3309 
3310 /// Implements the \#elif, \#elifdef, and \#elifndef directives.
3311 void Preprocessor::HandleElifFamilyDirective(Token &ElifToken,
3312                                              const Token &HashToken,
3313                                              tok::PPKeywordKind Kind) {
3314   PPElifDiag DirKind = Kind == tok::pp_elif      ? PED_Elif
3315                        : Kind == tok::pp_elifdef ? PED_Elifdef
3316                                                  : PED_Elifndef;
3317   ++NumElse;
3318 
3319   // Warn if using `#elifdef` & `#elifndef` in not C2x & C++2b mode.
3320   switch (DirKind) {
3321   case PED_Elifdef:
3322   case PED_Elifndef:
3323     unsigned DiagID;
3324     if (LangOpts.CPlusPlus)
3325       DiagID = LangOpts.CPlusPlus2b ? diag::warn_cxx2b_compat_pp_directive
3326                                     : diag::ext_cxx2b_pp_directive;
3327     else
3328       DiagID = LangOpts.C2x ? diag::warn_c2x_compat_pp_directive
3329                             : diag::ext_c2x_pp_directive;
3330     Diag(ElifToken, DiagID) << DirKind;
3331     break;
3332   default:
3333     break;
3334   }
3335 
3336   // #elif directive in a non-skipping conditional... start skipping.
3337   // We don't care what the condition is, because we will always skip it (since
3338   // the block immediately before it was included).
3339   SourceRange ConditionRange = DiscardUntilEndOfDirective();
3340 
3341   PPConditionalInfo CI;
3342   if (CurPPLexer->popConditionalLevel(CI)) {
3343     Diag(ElifToken, diag::pp_err_elif_without_if) << DirKind;
3344     return;
3345   }
3346 
3347   // If this is a top-level #elif, inform the MIOpt.
3348   if (CurPPLexer->getConditionalStackDepth() == 0)
3349     CurPPLexer->MIOpt.EnterTopLevelConditional();
3350 
3351   // If this is a #elif with a #else before it, report the error.
3352   if (CI.FoundElse)
3353     Diag(ElifToken, diag::pp_err_elif_after_else) << DirKind;
3354 
3355   if (Callbacks) {
3356     switch (Kind) {
3357     case tok::pp_elif:
3358       Callbacks->Elif(ElifToken.getLocation(), ConditionRange,
3359                       PPCallbacks::CVK_NotEvaluated, CI.IfLoc);
3360       break;
3361     case tok::pp_elifdef:
3362       Callbacks->Elifdef(ElifToken.getLocation(), ConditionRange, CI.IfLoc);
3363       break;
3364     case tok::pp_elifndef:
3365       Callbacks->Elifndef(ElifToken.getLocation(), ConditionRange, CI.IfLoc);
3366       break;
3367     default:
3368       assert(false && "unexpected directive kind");
3369       break;
3370     }
3371   }
3372 
3373   bool RetainExcludedCB = PPOpts->RetainExcludedConditionalBlocks &&
3374     getSourceManager().isInMainFile(ElifToken.getLocation());
3375 
3376   if ((PPOpts->SingleFileParseMode && !CI.FoundNonSkip) || RetainExcludedCB) {
3377     // In 'single-file-parse mode' undefined identifiers trigger parsing of all
3378     // the directive blocks.
3379     CurPPLexer->pushConditionalLevel(ElifToken.getLocation(), /*wasskip*/false,
3380                                      /*foundnonskip*/false, /*foundelse*/false);
3381     return;
3382   }
3383 
3384   // Finally, skip the rest of the contents of this block.
3385   SkipExcludedConditionalBlock(
3386       HashToken.getLocation(), CI.IfLoc, /*Foundnonskip*/ true,
3387       /*FoundElse*/ CI.FoundElse, ElifToken.getLocation());
3388 }
3389