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