Clang Project

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