Pragma.cpp 64 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914
  1. //===- Pragma.cpp - Pragma registration and handling ----------------------===//
  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. // This file implements the PragmaHandler/PragmaTable interfaces and implements
  10. // pragma related methods of the Preprocessor class.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "clang/Lex/Pragma.h"
  14. #include "clang/Basic/Diagnostic.h"
  15. #include "clang/Basic/FileManager.h"
  16. #include "clang/Basic/IdentifierTable.h"
  17. #include "clang/Basic/LLVM.h"
  18. #include "clang/Basic/LangOptions.h"
  19. #include "clang/Basic/Module.h"
  20. #include "clang/Basic/SourceLocation.h"
  21. #include "clang/Basic/SourceManager.h"
  22. #include "clang/Basic/TokenKinds.h"
  23. #include "clang/Lex/HeaderSearch.h"
  24. #include "clang/Lex/LexDiagnostic.h"
  25. #include "clang/Lex/Lexer.h"
  26. #include "clang/Lex/LiteralSupport.h"
  27. #include "clang/Lex/MacroInfo.h"
  28. #include "clang/Lex/ModuleLoader.h"
  29. #include "clang/Lex/PPCallbacks.h"
  30. #include "clang/Lex/Preprocessor.h"
  31. #include "clang/Lex/PreprocessorLexer.h"
  32. #include "clang/Lex/Token.h"
  33. #include "clang/Lex/TokenLexer.h"
  34. #include "llvm/ADT/ArrayRef.h"
  35. #include "llvm/ADT/DenseMap.h"
  36. #include "llvm/ADT/STLExtras.h"
  37. #include "llvm/ADT/SmallString.h"
  38. #include "llvm/ADT/SmallVector.h"
  39. #include "llvm/ADT/StringSwitch.h"
  40. #include "llvm/ADT/StringRef.h"
  41. #include "llvm/Support/CrashRecoveryContext.h"
  42. #include "llvm/Support/Compiler.h"
  43. #include "llvm/Support/ErrorHandling.h"
  44. #include <algorithm>
  45. #include <cassert>
  46. #include <cstddef>
  47. #include <cstdint>
  48. #include <limits>
  49. #include <string>
  50. #include <utility>
  51. #include <vector>
  52. using namespace clang;
  53. // Out-of-line destructor to provide a home for the class.
  54. PragmaHandler::~PragmaHandler() = default;
  55. //===----------------------------------------------------------------------===//
  56. // EmptyPragmaHandler Implementation.
  57. //===----------------------------------------------------------------------===//
  58. EmptyPragmaHandler::EmptyPragmaHandler(StringRef Name) : PragmaHandler(Name) {}
  59. void EmptyPragmaHandler::HandlePragma(Preprocessor &PP,
  60. PragmaIntroducer Introducer,
  61. Token &FirstToken) {}
  62. //===----------------------------------------------------------------------===//
  63. // PragmaNamespace Implementation.
  64. //===----------------------------------------------------------------------===//
  65. PragmaNamespace::~PragmaNamespace() {
  66. llvm::DeleteContainerSeconds(Handlers);
  67. }
  68. /// FindHandler - Check to see if there is already a handler for the
  69. /// specified name. If not, return the handler for the null identifier if it
  70. /// exists, otherwise return null. If IgnoreNull is true (the default) then
  71. /// the null handler isn't returned on failure to match.
  72. PragmaHandler *PragmaNamespace::FindHandler(StringRef Name,
  73. bool IgnoreNull) const {
  74. if (PragmaHandler *Handler = Handlers.lookup(Name))
  75. return Handler;
  76. return IgnoreNull ? nullptr : Handlers.lookup(StringRef());
  77. }
  78. void PragmaNamespace::AddPragma(PragmaHandler *Handler) {
  79. assert(!Handlers.lookup(Handler->getName()) &&
  80. "A handler with this name is already registered in this namespace");
  81. Handlers[Handler->getName()] = Handler;
  82. }
  83. void PragmaNamespace::RemovePragmaHandler(PragmaHandler *Handler) {
  84. assert(Handlers.lookup(Handler->getName()) &&
  85. "Handler not registered in this namespace");
  86. Handlers.erase(Handler->getName());
  87. }
  88. void PragmaNamespace::HandlePragma(Preprocessor &PP,
  89. PragmaIntroducer Introducer, Token &Tok) {
  90. // Read the 'namespace' that the directive is in, e.g. STDC. Do not macro
  91. // expand it, the user can have a STDC #define, that should not affect this.
  92. PP.LexUnexpandedToken(Tok);
  93. // Get the handler for this token. If there is no handler, ignore the pragma.
  94. PragmaHandler *Handler
  95. = FindHandler(Tok.getIdentifierInfo() ? Tok.getIdentifierInfo()->getName()
  96. : StringRef(),
  97. /*IgnoreNull=*/false);
  98. if (!Handler) {
  99. PP.Diag(Tok, diag::warn_pragma_ignored);
  100. return;
  101. }
  102. // Otherwise, pass it down.
  103. Handler->HandlePragma(PP, Introducer, Tok);
  104. }
  105. //===----------------------------------------------------------------------===//
  106. // Preprocessor Pragma Directive Handling.
  107. //===----------------------------------------------------------------------===//
  108. namespace {
  109. // TokenCollector provides the option to collect tokens that were "read"
  110. // and return them to the stream to be read later.
  111. // Currently used when reading _Pragma/__pragma directives.
  112. struct TokenCollector {
  113. Preprocessor &Self;
  114. bool Collect;
  115. SmallVector<Token, 3> Tokens;
  116. Token &Tok;
  117. void lex() {
  118. if (Collect)
  119. Tokens.push_back(Tok);
  120. Self.Lex(Tok);
  121. }
  122. void revert() {
  123. assert(Collect && "did not collect tokens");
  124. assert(!Tokens.empty() && "collected unexpected number of tokens");
  125. // Push the ( "string" ) tokens into the token stream.
  126. auto Toks = std::make_unique<Token[]>(Tokens.size());
  127. std::copy(Tokens.begin() + 1, Tokens.end(), Toks.get());
  128. Toks[Tokens.size() - 1] = Tok;
  129. Self.EnterTokenStream(std::move(Toks), Tokens.size(),
  130. /*DisableMacroExpansion*/ true,
  131. /*IsReinject*/ true);
  132. // ... and return the pragma token unchanged.
  133. Tok = *Tokens.begin();
  134. }
  135. };
  136. } // namespace
  137. /// HandlePragmaDirective - The "\#pragma" directive has been parsed. Lex the
  138. /// rest of the pragma, passing it to the registered pragma handlers.
  139. void Preprocessor::HandlePragmaDirective(PragmaIntroducer Introducer) {
  140. if (Callbacks)
  141. Callbacks->PragmaDirective(Introducer.Loc, Introducer.Kind);
  142. if (!PragmasEnabled)
  143. return;
  144. ++NumPragma;
  145. // Invoke the first level of pragma handlers which reads the namespace id.
  146. Token Tok;
  147. PragmaHandlers->HandlePragma(*this, Introducer, Tok);
  148. // If the pragma handler didn't read the rest of the line, consume it now.
  149. if ((CurTokenLexer && CurTokenLexer->isParsingPreprocessorDirective())
  150. || (CurPPLexer && CurPPLexer->ParsingPreprocessorDirective))
  151. DiscardUntilEndOfDirective();
  152. }
  153. /// Handle_Pragma - Read a _Pragma directive, slice it up, process it, then
  154. /// return the first token after the directive. The _Pragma token has just
  155. /// been read into 'Tok'.
  156. void Preprocessor::Handle_Pragma(Token &Tok) {
  157. // C11 6.10.3.4/3:
  158. // all pragma unary operator expressions within [a completely
  159. // macro-replaced preprocessing token sequence] are [...] processed [after
  160. // rescanning is complete]
  161. //
  162. // This means that we execute _Pragma operators in two cases:
  163. //
  164. // 1) on token sequences that would otherwise be produced as the output of
  165. // phase 4 of preprocessing, and
  166. // 2) on token sequences formed as the macro-replaced token sequence of a
  167. // macro argument
  168. //
  169. // Case #2 appears to be a wording bug: only _Pragmas that would survive to
  170. // the end of phase 4 should actually be executed. Discussion on the WG14
  171. // mailing list suggests that a _Pragma operator is notionally checked early,
  172. // but only pragmas that survive to the end of phase 4 should be executed.
  173. //
  174. // In Case #2, we check the syntax now, but then put the tokens back into the
  175. // token stream for later consumption.
  176. TokenCollector Toks = {*this, InMacroArgPreExpansion, {}, Tok};
  177. // Remember the pragma token location.
  178. SourceLocation PragmaLoc = Tok.getLocation();
  179. // Read the '('.
  180. Toks.lex();
  181. if (Tok.isNot(tok::l_paren)) {
  182. Diag(PragmaLoc, diag::err__Pragma_malformed);
  183. return;
  184. }
  185. // Read the '"..."'.
  186. Toks.lex();
  187. if (!tok::isStringLiteral(Tok.getKind())) {
  188. Diag(PragmaLoc, diag::err__Pragma_malformed);
  189. // Skip bad tokens, and the ')', if present.
  190. if (Tok.isNot(tok::r_paren) && Tok.isNot(tok::eof))
  191. Lex(Tok);
  192. while (Tok.isNot(tok::r_paren) &&
  193. !Tok.isAtStartOfLine() &&
  194. Tok.isNot(tok::eof))
  195. Lex(Tok);
  196. if (Tok.is(tok::r_paren))
  197. Lex(Tok);
  198. return;
  199. }
  200. if (Tok.hasUDSuffix()) {
  201. Diag(Tok, diag::err_invalid_string_udl);
  202. // Skip this token, and the ')', if present.
  203. Lex(Tok);
  204. if (Tok.is(tok::r_paren))
  205. Lex(Tok);
  206. return;
  207. }
  208. // Remember the string.
  209. Token StrTok = Tok;
  210. // Read the ')'.
  211. Toks.lex();
  212. if (Tok.isNot(tok::r_paren)) {
  213. Diag(PragmaLoc, diag::err__Pragma_malformed);
  214. return;
  215. }
  216. // If we're expanding a macro argument, put the tokens back.
  217. if (InMacroArgPreExpansion) {
  218. Toks.revert();
  219. return;
  220. }
  221. SourceLocation RParenLoc = Tok.getLocation();
  222. std::string StrVal = getSpelling(StrTok);
  223. // The _Pragma is lexically sound. Destringize according to C11 6.10.9.1:
  224. // "The string literal is destringized by deleting any encoding prefix,
  225. // deleting the leading and trailing double-quotes, replacing each escape
  226. // sequence \" by a double-quote, and replacing each escape sequence \\ by a
  227. // single backslash."
  228. if (StrVal[0] == 'L' || StrVal[0] == 'U' ||
  229. (StrVal[0] == 'u' && StrVal[1] != '8'))
  230. StrVal.erase(StrVal.begin());
  231. else if (StrVal[0] == 'u')
  232. StrVal.erase(StrVal.begin(), StrVal.begin() + 2);
  233. if (StrVal[0] == 'R') {
  234. // FIXME: C++11 does not specify how to handle raw-string-literals here.
  235. // We strip off the 'R', the quotes, the d-char-sequences, and the parens.
  236. assert(StrVal[1] == '"' && StrVal[StrVal.size() - 1] == '"' &&
  237. "Invalid raw string token!");
  238. // Measure the length of the d-char-sequence.
  239. unsigned NumDChars = 0;
  240. while (StrVal[2 + NumDChars] != '(') {
  241. assert(NumDChars < (StrVal.size() - 5) / 2 &&
  242. "Invalid raw string token!");
  243. ++NumDChars;
  244. }
  245. assert(StrVal[StrVal.size() - 2 - NumDChars] == ')');
  246. // Remove 'R " d-char-sequence' and 'd-char-sequence "'. We'll replace the
  247. // parens below.
  248. StrVal.erase(0, 2 + NumDChars);
  249. StrVal.erase(StrVal.size() - 1 - NumDChars);
  250. } else {
  251. assert(StrVal[0] == '"' && StrVal[StrVal.size()-1] == '"' &&
  252. "Invalid string token!");
  253. // Remove escaped quotes and escapes.
  254. unsigned ResultPos = 1;
  255. for (size_t i = 1, e = StrVal.size() - 1; i != e; ++i) {
  256. // Skip escapes. \\ -> '\' and \" -> '"'.
  257. if (StrVal[i] == '\\' && i + 1 < e &&
  258. (StrVal[i + 1] == '\\' || StrVal[i + 1] == '"'))
  259. ++i;
  260. StrVal[ResultPos++] = StrVal[i];
  261. }
  262. StrVal.erase(StrVal.begin() + ResultPos, StrVal.end() - 1);
  263. }
  264. // Remove the front quote, replacing it with a space, so that the pragma
  265. // contents appear to have a space before them.
  266. StrVal[0] = ' ';
  267. // Replace the terminating quote with a \n.
  268. StrVal[StrVal.size()-1] = '\n';
  269. // Plop the string (including the newline and trailing null) into a buffer
  270. // where we can lex it.
  271. Token TmpTok;
  272. TmpTok.startToken();
  273. CreateString(StrVal, TmpTok);
  274. SourceLocation TokLoc = TmpTok.getLocation();
  275. // Make and enter a lexer object so that we lex and expand the tokens just
  276. // like any others.
  277. Lexer *TL = Lexer::Create_PragmaLexer(TokLoc, PragmaLoc, RParenLoc,
  278. StrVal.size(), *this);
  279. EnterSourceFileWithLexer(TL, nullptr);
  280. // With everything set up, lex this as a #pragma directive.
  281. HandlePragmaDirective({PIK__Pragma, PragmaLoc});
  282. // Finally, return whatever came after the pragma directive.
  283. return Lex(Tok);
  284. }
  285. /// HandleMicrosoft__pragma - Like Handle_Pragma except the pragma text
  286. /// is not enclosed within a string literal.
  287. void Preprocessor::HandleMicrosoft__pragma(Token &Tok) {
  288. // During macro pre-expansion, check the syntax now but put the tokens back
  289. // into the token stream for later consumption. Same as Handle_Pragma.
  290. TokenCollector Toks = {*this, InMacroArgPreExpansion, {}, Tok};
  291. // Remember the pragma token location.
  292. SourceLocation PragmaLoc = Tok.getLocation();
  293. // Read the '('.
  294. Toks.lex();
  295. if (Tok.isNot(tok::l_paren)) {
  296. Diag(PragmaLoc, diag::err__Pragma_malformed);
  297. return;
  298. }
  299. // Get the tokens enclosed within the __pragma(), as well as the final ')'.
  300. SmallVector<Token, 32> PragmaToks;
  301. int NumParens = 0;
  302. Toks.lex();
  303. while (Tok.isNot(tok::eof)) {
  304. PragmaToks.push_back(Tok);
  305. if (Tok.is(tok::l_paren))
  306. NumParens++;
  307. else if (Tok.is(tok::r_paren) && NumParens-- == 0)
  308. break;
  309. Toks.lex();
  310. }
  311. if (Tok.is(tok::eof)) {
  312. Diag(PragmaLoc, diag::err_unterminated___pragma);
  313. return;
  314. }
  315. // If we're expanding a macro argument, put the tokens back.
  316. if (InMacroArgPreExpansion) {
  317. Toks.revert();
  318. return;
  319. }
  320. PragmaToks.front().setFlag(Token::LeadingSpace);
  321. // Replace the ')' with an EOD to mark the end of the pragma.
  322. PragmaToks.back().setKind(tok::eod);
  323. Token *TokArray = new Token[PragmaToks.size()];
  324. std::copy(PragmaToks.begin(), PragmaToks.end(), TokArray);
  325. // Push the tokens onto the stack.
  326. EnterTokenStream(TokArray, PragmaToks.size(), true, true,
  327. /*IsReinject*/ false);
  328. // With everything set up, lex this as a #pragma directive.
  329. HandlePragmaDirective({PIK___pragma, PragmaLoc});
  330. // Finally, return whatever came after the pragma directive.
  331. return Lex(Tok);
  332. }
  333. /// HandlePragmaOnce - Handle \#pragma once. OnceTok is the 'once'.
  334. void Preprocessor::HandlePragmaOnce(Token &OnceTok) {
  335. // Don't honor the 'once' when handling the primary source file, unless
  336. // this is a prefix to a TU, which indicates we're generating a PCH file, or
  337. // when the main file is a header (e.g. when -xc-header is provided on the
  338. // commandline).
  339. if (isInPrimaryFile() && TUKind != TU_Prefix && !getLangOpts().IsHeaderFile) {
  340. Diag(OnceTok, diag::pp_pragma_once_in_main_file);
  341. return;
  342. }
  343. // Get the current file lexer we're looking at. Ignore _Pragma 'files' etc.
  344. // Mark the file as a once-only file now.
  345. HeaderInfo.MarkFileIncludeOnce(getCurrentFileLexer()->getFileEntry());
  346. }
  347. void Preprocessor::HandlePragmaMark() {
  348. assert(CurPPLexer && "No current lexer?");
  349. CurLexer->ReadToEndOfLine();
  350. }
  351. /// HandlePragmaPoison - Handle \#pragma GCC poison. PoisonTok is the 'poison'.
  352. void Preprocessor::HandlePragmaPoison() {
  353. Token Tok;
  354. while (true) {
  355. // Read the next token to poison. While doing this, pretend that we are
  356. // skipping while reading the identifier to poison.
  357. // This avoids errors on code like:
  358. // #pragma GCC poison X
  359. // #pragma GCC poison X
  360. if (CurPPLexer) CurPPLexer->LexingRawMode = true;
  361. LexUnexpandedToken(Tok);
  362. if (CurPPLexer) CurPPLexer->LexingRawMode = false;
  363. // If we reached the end of line, we're done.
  364. if (Tok.is(tok::eod)) return;
  365. // Can only poison identifiers.
  366. if (Tok.isNot(tok::raw_identifier)) {
  367. Diag(Tok, diag::err_pp_invalid_poison);
  368. return;
  369. }
  370. // Look up the identifier info for the token. We disabled identifier lookup
  371. // by saying we're skipping contents, so we need to do this manually.
  372. IdentifierInfo *II = LookUpIdentifierInfo(Tok);
  373. // Already poisoned.
  374. if (II->isPoisoned()) continue;
  375. // If this is a macro identifier, emit a warning.
  376. if (isMacroDefined(II))
  377. Diag(Tok, diag::pp_poisoning_existing_macro);
  378. // Finally, poison it!
  379. II->setIsPoisoned();
  380. if (II->isFromAST())
  381. II->setChangedSinceDeserialization();
  382. }
  383. }
  384. /// HandlePragmaSystemHeader - Implement \#pragma GCC system_header. We know
  385. /// that the whole directive has been parsed.
  386. void Preprocessor::HandlePragmaSystemHeader(Token &SysHeaderTok) {
  387. if (isInPrimaryFile()) {
  388. Diag(SysHeaderTok, diag::pp_pragma_sysheader_in_main_file);
  389. return;
  390. }
  391. // Get the current file lexer we're looking at. Ignore _Pragma 'files' etc.
  392. PreprocessorLexer *TheLexer = getCurrentFileLexer();
  393. // Mark the file as a system header.
  394. HeaderInfo.MarkFileSystemHeader(TheLexer->getFileEntry());
  395. PresumedLoc PLoc = SourceMgr.getPresumedLoc(SysHeaderTok.getLocation());
  396. if (PLoc.isInvalid())
  397. return;
  398. unsigned FilenameID = SourceMgr.getLineTableFilenameID(PLoc.getFilename());
  399. // Notify the client, if desired, that we are in a new source file.
  400. if (Callbacks)
  401. Callbacks->FileChanged(SysHeaderTok.getLocation(),
  402. PPCallbacks::SystemHeaderPragma, SrcMgr::C_System);
  403. // Emit a line marker. This will change any source locations from this point
  404. // forward to realize they are in a system header.
  405. // Create a line note with this information.
  406. SourceMgr.AddLineNote(SysHeaderTok.getLocation(), PLoc.getLine() + 1,
  407. FilenameID, /*IsEntry=*/false, /*IsExit=*/false,
  408. SrcMgr::C_System);
  409. }
  410. /// HandlePragmaDependency - Handle \#pragma GCC dependency "foo" blah.
  411. void Preprocessor::HandlePragmaDependency(Token &DependencyTok) {
  412. Token FilenameTok;
  413. if (LexHeaderName(FilenameTok, /*AllowConcatenation*/false))
  414. return;
  415. // If the next token wasn't a header-name, diagnose the error.
  416. if (FilenameTok.isNot(tok::header_name)) {
  417. Diag(FilenameTok.getLocation(), diag::err_pp_expects_filename);
  418. return;
  419. }
  420. // Reserve a buffer to get the spelling.
  421. SmallString<128> FilenameBuffer;
  422. bool Invalid = false;
  423. StringRef Filename = getSpelling(FilenameTok, FilenameBuffer, &Invalid);
  424. if (Invalid)
  425. return;
  426. bool isAngled =
  427. GetIncludeFilenameSpelling(FilenameTok.getLocation(), Filename);
  428. // If GetIncludeFilenameSpelling set the start ptr to null, there was an
  429. // error.
  430. if (Filename.empty())
  431. return;
  432. // Search include directories for this file.
  433. const DirectoryLookup *CurDir;
  434. Optional<FileEntryRef> File =
  435. LookupFile(FilenameTok.getLocation(), Filename, isAngled, nullptr,
  436. nullptr, CurDir, nullptr, nullptr, nullptr, nullptr, nullptr);
  437. if (!File) {
  438. if (!SuppressIncludeNotFoundError)
  439. Diag(FilenameTok, diag::err_pp_file_not_found) << Filename;
  440. return;
  441. }
  442. const FileEntry *CurFile = getCurrentFileLexer()->getFileEntry();
  443. // If this file is older than the file it depends on, emit a diagnostic.
  444. if (CurFile && CurFile->getModificationTime() < File->getModificationTime()) {
  445. // Lex tokens at the end of the message and include them in the message.
  446. std::string Message;
  447. Lex(DependencyTok);
  448. while (DependencyTok.isNot(tok::eod)) {
  449. Message += getSpelling(DependencyTok) + " ";
  450. Lex(DependencyTok);
  451. }
  452. // Remove the trailing ' ' if present.
  453. if (!Message.empty())
  454. Message.erase(Message.end()-1);
  455. Diag(FilenameTok, diag::pp_out_of_date_dependency) << Message;
  456. }
  457. }
  458. /// ParsePragmaPushOrPopMacro - Handle parsing of pragma push_macro/pop_macro.
  459. /// Return the IdentifierInfo* associated with the macro to push or pop.
  460. IdentifierInfo *Preprocessor::ParsePragmaPushOrPopMacro(Token &Tok) {
  461. // Remember the pragma token location.
  462. Token PragmaTok = Tok;
  463. // Read the '('.
  464. Lex(Tok);
  465. if (Tok.isNot(tok::l_paren)) {
  466. Diag(PragmaTok.getLocation(), diag::err_pragma_push_pop_macro_malformed)
  467. << getSpelling(PragmaTok);
  468. return nullptr;
  469. }
  470. // Read the macro name string.
  471. Lex(Tok);
  472. if (Tok.isNot(tok::string_literal)) {
  473. Diag(PragmaTok.getLocation(), diag::err_pragma_push_pop_macro_malformed)
  474. << getSpelling(PragmaTok);
  475. return nullptr;
  476. }
  477. if (Tok.hasUDSuffix()) {
  478. Diag(Tok, diag::err_invalid_string_udl);
  479. return nullptr;
  480. }
  481. // Remember the macro string.
  482. std::string StrVal = getSpelling(Tok);
  483. // Read the ')'.
  484. Lex(Tok);
  485. if (Tok.isNot(tok::r_paren)) {
  486. Diag(PragmaTok.getLocation(), diag::err_pragma_push_pop_macro_malformed)
  487. << getSpelling(PragmaTok);
  488. return nullptr;
  489. }
  490. assert(StrVal[0] == '"' && StrVal[StrVal.size()-1] == '"' &&
  491. "Invalid string token!");
  492. // Create a Token from the string.
  493. Token MacroTok;
  494. MacroTok.startToken();
  495. MacroTok.setKind(tok::raw_identifier);
  496. CreateString(StringRef(&StrVal[1], StrVal.size() - 2), MacroTok);
  497. // Get the IdentifierInfo of MacroToPushTok.
  498. return LookUpIdentifierInfo(MacroTok);
  499. }
  500. /// Handle \#pragma push_macro.
  501. ///
  502. /// The syntax is:
  503. /// \code
  504. /// #pragma push_macro("macro")
  505. /// \endcode
  506. void Preprocessor::HandlePragmaPushMacro(Token &PushMacroTok) {
  507. // Parse the pragma directive and get the macro IdentifierInfo*.
  508. IdentifierInfo *IdentInfo = ParsePragmaPushOrPopMacro(PushMacroTok);
  509. if (!IdentInfo) return;
  510. // Get the MacroInfo associated with IdentInfo.
  511. MacroInfo *MI = getMacroInfo(IdentInfo);
  512. if (MI) {
  513. // Allow the original MacroInfo to be redefined later.
  514. MI->setIsAllowRedefinitionsWithoutWarning(true);
  515. }
  516. // Push the cloned MacroInfo so we can retrieve it later.
  517. PragmaPushMacroInfo[IdentInfo].push_back(MI);
  518. }
  519. /// Handle \#pragma pop_macro.
  520. ///
  521. /// The syntax is:
  522. /// \code
  523. /// #pragma pop_macro("macro")
  524. /// \endcode
  525. void Preprocessor::HandlePragmaPopMacro(Token &PopMacroTok) {
  526. SourceLocation MessageLoc = PopMacroTok.getLocation();
  527. // Parse the pragma directive and get the macro IdentifierInfo*.
  528. IdentifierInfo *IdentInfo = ParsePragmaPushOrPopMacro(PopMacroTok);
  529. if (!IdentInfo) return;
  530. // Find the vector<MacroInfo*> associated with the macro.
  531. llvm::DenseMap<IdentifierInfo *, std::vector<MacroInfo *>>::iterator iter =
  532. PragmaPushMacroInfo.find(IdentInfo);
  533. if (iter != PragmaPushMacroInfo.end()) {
  534. // Forget the MacroInfo currently associated with IdentInfo.
  535. if (MacroInfo *MI = getMacroInfo(IdentInfo)) {
  536. if (MI->isWarnIfUnused())
  537. WarnUnusedMacroLocs.erase(MI->getDefinitionLoc());
  538. appendMacroDirective(IdentInfo, AllocateUndefMacroDirective(MessageLoc));
  539. }
  540. // Get the MacroInfo we want to reinstall.
  541. MacroInfo *MacroToReInstall = iter->second.back();
  542. if (MacroToReInstall)
  543. // Reinstall the previously pushed macro.
  544. appendDefMacroDirective(IdentInfo, MacroToReInstall, MessageLoc);
  545. // Pop PragmaPushMacroInfo stack.
  546. iter->second.pop_back();
  547. if (iter->second.empty())
  548. PragmaPushMacroInfo.erase(iter);
  549. } else {
  550. Diag(MessageLoc, diag::warn_pragma_pop_macro_no_push)
  551. << IdentInfo->getName();
  552. }
  553. }
  554. void Preprocessor::HandlePragmaIncludeAlias(Token &Tok) {
  555. // We will either get a quoted filename or a bracketed filename, and we
  556. // have to track which we got. The first filename is the source name,
  557. // and the second name is the mapped filename. If the first is quoted,
  558. // the second must be as well (cannot mix and match quotes and brackets).
  559. // Get the open paren
  560. Lex(Tok);
  561. if (Tok.isNot(tok::l_paren)) {
  562. Diag(Tok, diag::warn_pragma_include_alias_expected) << "(";
  563. return;
  564. }
  565. // We expect either a quoted string literal, or a bracketed name
  566. Token SourceFilenameTok;
  567. if (LexHeaderName(SourceFilenameTok))
  568. return;
  569. StringRef SourceFileName;
  570. SmallString<128> FileNameBuffer;
  571. if (SourceFilenameTok.is(tok::header_name)) {
  572. SourceFileName = getSpelling(SourceFilenameTok, FileNameBuffer);
  573. } else {
  574. Diag(Tok, diag::warn_pragma_include_alias_expected_filename);
  575. return;
  576. }
  577. FileNameBuffer.clear();
  578. // Now we expect a comma, followed by another include name
  579. Lex(Tok);
  580. if (Tok.isNot(tok::comma)) {
  581. Diag(Tok, diag::warn_pragma_include_alias_expected) << ",";
  582. return;
  583. }
  584. Token ReplaceFilenameTok;
  585. if (LexHeaderName(ReplaceFilenameTok))
  586. return;
  587. StringRef ReplaceFileName;
  588. if (ReplaceFilenameTok.is(tok::header_name)) {
  589. ReplaceFileName = getSpelling(ReplaceFilenameTok, FileNameBuffer);
  590. } else {
  591. Diag(Tok, diag::warn_pragma_include_alias_expected_filename);
  592. return;
  593. }
  594. // Finally, we expect the closing paren
  595. Lex(Tok);
  596. if (Tok.isNot(tok::r_paren)) {
  597. Diag(Tok, diag::warn_pragma_include_alias_expected) << ")";
  598. return;
  599. }
  600. // Now that we have the source and target filenames, we need to make sure
  601. // they're both of the same type (angled vs non-angled)
  602. StringRef OriginalSource = SourceFileName;
  603. bool SourceIsAngled =
  604. GetIncludeFilenameSpelling(SourceFilenameTok.getLocation(),
  605. SourceFileName);
  606. bool ReplaceIsAngled =
  607. GetIncludeFilenameSpelling(ReplaceFilenameTok.getLocation(),
  608. ReplaceFileName);
  609. if (!SourceFileName.empty() && !ReplaceFileName.empty() &&
  610. (SourceIsAngled != ReplaceIsAngled)) {
  611. unsigned int DiagID;
  612. if (SourceIsAngled)
  613. DiagID = diag::warn_pragma_include_alias_mismatch_angle;
  614. else
  615. DiagID = diag::warn_pragma_include_alias_mismatch_quote;
  616. Diag(SourceFilenameTok.getLocation(), DiagID)
  617. << SourceFileName
  618. << ReplaceFileName;
  619. return;
  620. }
  621. // Now we can let the include handler know about this mapping
  622. getHeaderSearchInfo().AddIncludeAlias(OriginalSource, ReplaceFileName);
  623. }
  624. // Lex a component of a module name: either an identifier or a string literal;
  625. // for components that can be expressed both ways, the two forms are equivalent.
  626. static bool LexModuleNameComponent(
  627. Preprocessor &PP, Token &Tok,
  628. std::pair<IdentifierInfo *, SourceLocation> &ModuleNameComponent,
  629. bool First) {
  630. PP.LexUnexpandedToken(Tok);
  631. if (Tok.is(tok::string_literal) && !Tok.hasUDSuffix()) {
  632. StringLiteralParser Literal(Tok, PP);
  633. if (Literal.hadError)
  634. return true;
  635. ModuleNameComponent = std::make_pair(
  636. PP.getIdentifierInfo(Literal.GetString()), Tok.getLocation());
  637. } else if (!Tok.isAnnotation() && Tok.getIdentifierInfo()) {
  638. ModuleNameComponent =
  639. std::make_pair(Tok.getIdentifierInfo(), Tok.getLocation());
  640. } else {
  641. PP.Diag(Tok.getLocation(), diag::err_pp_expected_module_name) << First;
  642. return true;
  643. }
  644. return false;
  645. }
  646. static bool LexModuleName(
  647. Preprocessor &PP, Token &Tok,
  648. llvm::SmallVectorImpl<std::pair<IdentifierInfo *, SourceLocation>>
  649. &ModuleName) {
  650. while (true) {
  651. std::pair<IdentifierInfo*, SourceLocation> NameComponent;
  652. if (LexModuleNameComponent(PP, Tok, NameComponent, ModuleName.empty()))
  653. return true;
  654. ModuleName.push_back(NameComponent);
  655. PP.LexUnexpandedToken(Tok);
  656. if (Tok.isNot(tok::period))
  657. return false;
  658. }
  659. }
  660. void Preprocessor::HandlePragmaModuleBuild(Token &Tok) {
  661. SourceLocation Loc = Tok.getLocation();
  662. std::pair<IdentifierInfo *, SourceLocation> ModuleNameLoc;
  663. if (LexModuleNameComponent(*this, Tok, ModuleNameLoc, true))
  664. return;
  665. IdentifierInfo *ModuleName = ModuleNameLoc.first;
  666. LexUnexpandedToken(Tok);
  667. if (Tok.isNot(tok::eod)) {
  668. Diag(Tok, diag::ext_pp_extra_tokens_at_eol) << "pragma";
  669. DiscardUntilEndOfDirective();
  670. }
  671. CurLexer->LexingRawMode = true;
  672. auto TryConsumeIdentifier = [&](StringRef Ident) -> bool {
  673. if (Tok.getKind() != tok::raw_identifier ||
  674. Tok.getRawIdentifier() != Ident)
  675. return false;
  676. CurLexer->Lex(Tok);
  677. return true;
  678. };
  679. // Scan forward looking for the end of the module.
  680. const char *Start = CurLexer->getBufferLocation();
  681. const char *End = nullptr;
  682. unsigned NestingLevel = 1;
  683. while (true) {
  684. End = CurLexer->getBufferLocation();
  685. CurLexer->Lex(Tok);
  686. if (Tok.is(tok::eof)) {
  687. Diag(Loc, diag::err_pp_module_build_missing_end);
  688. break;
  689. }
  690. if (Tok.isNot(tok::hash) || !Tok.isAtStartOfLine()) {
  691. // Token was part of module; keep going.
  692. continue;
  693. }
  694. // We hit something directive-shaped; check to see if this is the end
  695. // of the module build.
  696. CurLexer->ParsingPreprocessorDirective = true;
  697. CurLexer->Lex(Tok);
  698. if (TryConsumeIdentifier("pragma") && TryConsumeIdentifier("clang") &&
  699. TryConsumeIdentifier("module")) {
  700. if (TryConsumeIdentifier("build"))
  701. // #pragma clang module build -> entering a nested module build.
  702. ++NestingLevel;
  703. else if (TryConsumeIdentifier("endbuild")) {
  704. // #pragma clang module endbuild -> leaving a module build.
  705. if (--NestingLevel == 0)
  706. break;
  707. }
  708. // We should either be looking at the EOD or more of the current directive
  709. // preceding the EOD. Either way we can ignore this token and keep going.
  710. assert(Tok.getKind() != tok::eof && "missing EOD before EOF");
  711. }
  712. }
  713. CurLexer->LexingRawMode = false;
  714. // Load the extracted text as a preprocessed module.
  715. assert(CurLexer->getBuffer().begin() <= Start &&
  716. Start <= CurLexer->getBuffer().end() &&
  717. CurLexer->getBuffer().begin() <= End &&
  718. End <= CurLexer->getBuffer().end() &&
  719. "module source range not contained within same file buffer");
  720. TheModuleLoader.loadModuleFromSource(Loc, ModuleName->getName(),
  721. StringRef(Start, End - Start));
  722. }
  723. void Preprocessor::HandlePragmaHdrstop(Token &Tok) {
  724. Lex(Tok);
  725. if (Tok.is(tok::l_paren)) {
  726. Diag(Tok.getLocation(), diag::warn_pp_hdrstop_filename_ignored);
  727. std::string FileName;
  728. if (!LexStringLiteral(Tok, FileName, "pragma hdrstop", false))
  729. return;
  730. if (Tok.isNot(tok::r_paren)) {
  731. Diag(Tok, diag::err_expected) << tok::r_paren;
  732. return;
  733. }
  734. Lex(Tok);
  735. }
  736. if (Tok.isNot(tok::eod))
  737. Diag(Tok.getLocation(), diag::ext_pp_extra_tokens_at_eol)
  738. << "pragma hdrstop";
  739. if (creatingPCHWithPragmaHdrStop() &&
  740. SourceMgr.isInMainFile(Tok.getLocation())) {
  741. assert(CurLexer && "no lexer for #pragma hdrstop processing");
  742. Token &Result = Tok;
  743. Result.startToken();
  744. CurLexer->FormTokenWithChars(Result, CurLexer->BufferEnd, tok::eof);
  745. CurLexer->cutOffLexing();
  746. }
  747. if (usingPCHWithPragmaHdrStop())
  748. SkippingUntilPragmaHdrStop = false;
  749. }
  750. /// AddPragmaHandler - Add the specified pragma handler to the preprocessor.
  751. /// If 'Namespace' is non-null, then it is a token required to exist on the
  752. /// pragma line before the pragma string starts, e.g. "STDC" or "GCC".
  753. void Preprocessor::AddPragmaHandler(StringRef Namespace,
  754. PragmaHandler *Handler) {
  755. PragmaNamespace *InsertNS = PragmaHandlers.get();
  756. // If this is specified to be in a namespace, step down into it.
  757. if (!Namespace.empty()) {
  758. // If there is already a pragma handler with the name of this namespace,
  759. // we either have an error (directive with the same name as a namespace) or
  760. // we already have the namespace to insert into.
  761. if (PragmaHandler *Existing = PragmaHandlers->FindHandler(Namespace)) {
  762. InsertNS = Existing->getIfNamespace();
  763. assert(InsertNS != nullptr && "Cannot have a pragma namespace and pragma"
  764. " handler with the same name!");
  765. } else {
  766. // Otherwise, this namespace doesn't exist yet, create and insert the
  767. // handler for it.
  768. InsertNS = new PragmaNamespace(Namespace);
  769. PragmaHandlers->AddPragma(InsertNS);
  770. }
  771. }
  772. // Check to make sure we don't already have a pragma for this identifier.
  773. assert(!InsertNS->FindHandler(Handler->getName()) &&
  774. "Pragma handler already exists for this identifier!");
  775. InsertNS->AddPragma(Handler);
  776. }
  777. /// RemovePragmaHandler - Remove the specific pragma handler from the
  778. /// preprocessor. If \arg Namespace is non-null, then it should be the
  779. /// namespace that \arg Handler was added to. It is an error to remove
  780. /// a handler that has not been registered.
  781. void Preprocessor::RemovePragmaHandler(StringRef Namespace,
  782. PragmaHandler *Handler) {
  783. PragmaNamespace *NS = PragmaHandlers.get();
  784. // If this is specified to be in a namespace, step down into it.
  785. if (!Namespace.empty()) {
  786. PragmaHandler *Existing = PragmaHandlers->FindHandler(Namespace);
  787. assert(Existing && "Namespace containing handler does not exist!");
  788. NS = Existing->getIfNamespace();
  789. assert(NS && "Invalid namespace, registered as a regular pragma handler!");
  790. }
  791. NS->RemovePragmaHandler(Handler);
  792. // If this is a non-default namespace and it is now empty, remove it.
  793. if (NS != PragmaHandlers.get() && NS->IsEmpty()) {
  794. PragmaHandlers->RemovePragmaHandler(NS);
  795. delete NS;
  796. }
  797. }
  798. bool Preprocessor::LexOnOffSwitch(tok::OnOffSwitch &Result) {
  799. Token Tok;
  800. LexUnexpandedToken(Tok);
  801. if (Tok.isNot(tok::identifier)) {
  802. Diag(Tok, diag::ext_on_off_switch_syntax);
  803. return true;
  804. }
  805. IdentifierInfo *II = Tok.getIdentifierInfo();
  806. if (II->isStr("ON"))
  807. Result = tok::OOS_ON;
  808. else if (II->isStr("OFF"))
  809. Result = tok::OOS_OFF;
  810. else if (II->isStr("DEFAULT"))
  811. Result = tok::OOS_DEFAULT;
  812. else {
  813. Diag(Tok, diag::ext_on_off_switch_syntax);
  814. return true;
  815. }
  816. // Verify that this is followed by EOD.
  817. LexUnexpandedToken(Tok);
  818. if (Tok.isNot(tok::eod))
  819. Diag(Tok, diag::ext_pragma_syntax_eod);
  820. return false;
  821. }
  822. namespace {
  823. /// PragmaOnceHandler - "\#pragma once" marks the file as atomically included.
  824. struct PragmaOnceHandler : public PragmaHandler {
  825. PragmaOnceHandler() : PragmaHandler("once") {}
  826. void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
  827. Token &OnceTok) override {
  828. PP.CheckEndOfDirective("pragma once");
  829. PP.HandlePragmaOnce(OnceTok);
  830. }
  831. };
  832. /// PragmaMarkHandler - "\#pragma mark ..." is ignored by the compiler, and the
  833. /// rest of the line is not lexed.
  834. struct PragmaMarkHandler : public PragmaHandler {
  835. PragmaMarkHandler() : PragmaHandler("mark") {}
  836. void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
  837. Token &MarkTok) override {
  838. PP.HandlePragmaMark();
  839. }
  840. };
  841. /// PragmaPoisonHandler - "\#pragma poison x" marks x as not usable.
  842. struct PragmaPoisonHandler : public PragmaHandler {
  843. PragmaPoisonHandler() : PragmaHandler("poison") {}
  844. void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
  845. Token &PoisonTok) override {
  846. PP.HandlePragmaPoison();
  847. }
  848. };
  849. /// PragmaSystemHeaderHandler - "\#pragma system_header" marks the current file
  850. /// as a system header, which silences warnings in it.
  851. struct PragmaSystemHeaderHandler : public PragmaHandler {
  852. PragmaSystemHeaderHandler() : PragmaHandler("system_header") {}
  853. void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
  854. Token &SHToken) override {
  855. PP.HandlePragmaSystemHeader(SHToken);
  856. PP.CheckEndOfDirective("pragma");
  857. }
  858. };
  859. struct PragmaDependencyHandler : public PragmaHandler {
  860. PragmaDependencyHandler() : PragmaHandler("dependency") {}
  861. void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
  862. Token &DepToken) override {
  863. PP.HandlePragmaDependency(DepToken);
  864. }
  865. };
  866. struct PragmaDebugHandler : public PragmaHandler {
  867. PragmaDebugHandler() : PragmaHandler("__debug") {}
  868. void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
  869. Token &DebugToken) override {
  870. Token Tok;
  871. PP.LexUnexpandedToken(Tok);
  872. if (Tok.isNot(tok::identifier)) {
  873. PP.Diag(Tok, diag::warn_pragma_diagnostic_invalid);
  874. return;
  875. }
  876. IdentifierInfo *II = Tok.getIdentifierInfo();
  877. if (II->isStr("assert")) {
  878. llvm_unreachable("This is an assertion!");
  879. } else if (II->isStr("crash")) {
  880. LLVM_BUILTIN_TRAP;
  881. } else if (II->isStr("parser_crash")) {
  882. Token Crasher;
  883. Crasher.startToken();
  884. Crasher.setKind(tok::annot_pragma_parser_crash);
  885. Crasher.setAnnotationRange(SourceRange(Tok.getLocation()));
  886. PP.EnterToken(Crasher, /*IsReinject*/false);
  887. } else if (II->isStr("dump")) {
  888. Token Identifier;
  889. PP.LexUnexpandedToken(Identifier);
  890. if (auto *DumpII = Identifier.getIdentifierInfo()) {
  891. Token DumpAnnot;
  892. DumpAnnot.startToken();
  893. DumpAnnot.setKind(tok::annot_pragma_dump);
  894. DumpAnnot.setAnnotationRange(
  895. SourceRange(Tok.getLocation(), Identifier.getLocation()));
  896. DumpAnnot.setAnnotationValue(DumpII);
  897. PP.DiscardUntilEndOfDirective();
  898. PP.EnterToken(DumpAnnot, /*IsReinject*/false);
  899. } else {
  900. PP.Diag(Identifier, diag::warn_pragma_debug_missing_argument)
  901. << II->getName();
  902. }
  903. } else if (II->isStr("diag_mapping")) {
  904. Token DiagName;
  905. PP.LexUnexpandedToken(DiagName);
  906. if (DiagName.is(tok::eod))
  907. PP.getDiagnostics().dump();
  908. else if (DiagName.is(tok::string_literal) && !DiagName.hasUDSuffix()) {
  909. StringLiteralParser Literal(DiagName, PP);
  910. if (Literal.hadError)
  911. return;
  912. PP.getDiagnostics().dump(Literal.GetString());
  913. } else {
  914. PP.Diag(DiagName, diag::warn_pragma_debug_missing_argument)
  915. << II->getName();
  916. }
  917. } else if (II->isStr("llvm_fatal_error")) {
  918. llvm::report_fatal_error("#pragma clang __debug llvm_fatal_error");
  919. } else if (II->isStr("llvm_unreachable")) {
  920. llvm_unreachable("#pragma clang __debug llvm_unreachable");
  921. } else if (II->isStr("macro")) {
  922. Token MacroName;
  923. PP.LexUnexpandedToken(MacroName);
  924. auto *MacroII = MacroName.getIdentifierInfo();
  925. if (MacroII)
  926. PP.dumpMacroInfo(MacroII);
  927. else
  928. PP.Diag(MacroName, diag::warn_pragma_debug_missing_argument)
  929. << II->getName();
  930. } else if (II->isStr("module_map")) {
  931. llvm::SmallVector<std::pair<IdentifierInfo *, SourceLocation>, 8>
  932. ModuleName;
  933. if (LexModuleName(PP, Tok, ModuleName))
  934. return;
  935. ModuleMap &MM = PP.getHeaderSearchInfo().getModuleMap();
  936. Module *M = nullptr;
  937. for (auto IIAndLoc : ModuleName) {
  938. M = MM.lookupModuleQualified(IIAndLoc.first->getName(), M);
  939. if (!M) {
  940. PP.Diag(IIAndLoc.second, diag::warn_pragma_debug_unknown_module)
  941. << IIAndLoc.first;
  942. return;
  943. }
  944. }
  945. M->dump();
  946. } else if (II->isStr("overflow_stack")) {
  947. DebugOverflowStack();
  948. } else if (II->isStr("handle_crash")) {
  949. llvm::CrashRecoveryContext *CRC =llvm::CrashRecoveryContext::GetCurrent();
  950. if (CRC)
  951. CRC->HandleCrash();
  952. } else if (II->isStr("captured")) {
  953. HandleCaptured(PP);
  954. } else {
  955. PP.Diag(Tok, diag::warn_pragma_debug_unexpected_command)
  956. << II->getName();
  957. }
  958. PPCallbacks *Callbacks = PP.getPPCallbacks();
  959. if (Callbacks)
  960. Callbacks->PragmaDebug(Tok.getLocation(), II->getName());
  961. }
  962. void HandleCaptured(Preprocessor &PP) {
  963. Token Tok;
  964. PP.LexUnexpandedToken(Tok);
  965. if (Tok.isNot(tok::eod)) {
  966. PP.Diag(Tok, diag::ext_pp_extra_tokens_at_eol)
  967. << "pragma clang __debug captured";
  968. return;
  969. }
  970. SourceLocation NameLoc = Tok.getLocation();
  971. MutableArrayRef<Token> Toks(
  972. PP.getPreprocessorAllocator().Allocate<Token>(1), 1);
  973. Toks[0].startToken();
  974. Toks[0].setKind(tok::annot_pragma_captured);
  975. Toks[0].setLocation(NameLoc);
  976. PP.EnterTokenStream(Toks, /*DisableMacroExpansion=*/true,
  977. /*IsReinject=*/false);
  978. }
  979. // Disable MSVC warning about runtime stack overflow.
  980. #ifdef _MSC_VER
  981. #pragma warning(disable : 4717)
  982. #endif
  983. static void DebugOverflowStack(void (*P)() = nullptr) {
  984. void (*volatile Self)(void(*P)()) = DebugOverflowStack;
  985. Self(reinterpret_cast<void(*)()>(Self));
  986. }
  987. #ifdef _MSC_VER
  988. #pragma warning(default : 4717)
  989. #endif
  990. };
  991. /// PragmaDiagnosticHandler - e.g. '\#pragma GCC diagnostic ignored "-Wformat"'
  992. struct PragmaDiagnosticHandler : public PragmaHandler {
  993. private:
  994. const char *Namespace;
  995. public:
  996. explicit PragmaDiagnosticHandler(const char *NS)
  997. : PragmaHandler("diagnostic"), Namespace(NS) {}
  998. void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
  999. Token &DiagToken) override {
  1000. SourceLocation DiagLoc = DiagToken.getLocation();
  1001. Token Tok;
  1002. PP.LexUnexpandedToken(Tok);
  1003. if (Tok.isNot(tok::identifier)) {
  1004. PP.Diag(Tok, diag::warn_pragma_diagnostic_invalid);
  1005. return;
  1006. }
  1007. IdentifierInfo *II = Tok.getIdentifierInfo();
  1008. PPCallbacks *Callbacks = PP.getPPCallbacks();
  1009. if (II->isStr("pop")) {
  1010. if (!PP.getDiagnostics().popMappings(DiagLoc))
  1011. PP.Diag(Tok, diag::warn_pragma_diagnostic_cannot_pop);
  1012. else if (Callbacks)
  1013. Callbacks->PragmaDiagnosticPop(DiagLoc, Namespace);
  1014. return;
  1015. } else if (II->isStr("push")) {
  1016. PP.getDiagnostics().pushMappings(DiagLoc);
  1017. if (Callbacks)
  1018. Callbacks->PragmaDiagnosticPush(DiagLoc, Namespace);
  1019. return;
  1020. }
  1021. diag::Severity SV = llvm::StringSwitch<diag::Severity>(II->getName())
  1022. .Case("ignored", diag::Severity::Ignored)
  1023. .Case("warning", diag::Severity::Warning)
  1024. .Case("error", diag::Severity::Error)
  1025. .Case("fatal", diag::Severity::Fatal)
  1026. .Default(diag::Severity());
  1027. if (SV == diag::Severity()) {
  1028. PP.Diag(Tok, diag::warn_pragma_diagnostic_invalid);
  1029. return;
  1030. }
  1031. PP.LexUnexpandedToken(Tok);
  1032. SourceLocation StringLoc = Tok.getLocation();
  1033. std::string WarningName;
  1034. if (!PP.FinishLexStringLiteral(Tok, WarningName, "pragma diagnostic",
  1035. /*AllowMacroExpansion=*/false))
  1036. return;
  1037. if (Tok.isNot(tok::eod)) {
  1038. PP.Diag(Tok.getLocation(), diag::warn_pragma_diagnostic_invalid_token);
  1039. return;
  1040. }
  1041. if (WarningName.size() < 3 || WarningName[0] != '-' ||
  1042. (WarningName[1] != 'W' && WarningName[1] != 'R')) {
  1043. PP.Diag(StringLoc, diag::warn_pragma_diagnostic_invalid_option);
  1044. return;
  1045. }
  1046. diag::Flavor Flavor = WarningName[1] == 'W' ? diag::Flavor::WarningOrError
  1047. : diag::Flavor::Remark;
  1048. StringRef Group = StringRef(WarningName).substr(2);
  1049. bool unknownDiag = false;
  1050. if (Group == "everything") {
  1051. // Special handling for pragma clang diagnostic ... "-Weverything".
  1052. // There is no formal group named "everything", so there has to be a
  1053. // special case for it.
  1054. PP.getDiagnostics().setSeverityForAll(Flavor, SV, DiagLoc);
  1055. } else
  1056. unknownDiag = PP.getDiagnostics().setSeverityForGroup(Flavor, Group, SV,
  1057. DiagLoc);
  1058. if (unknownDiag)
  1059. PP.Diag(StringLoc, diag::warn_pragma_diagnostic_unknown_warning)
  1060. << WarningName;
  1061. else if (Callbacks)
  1062. Callbacks->PragmaDiagnostic(DiagLoc, Namespace, SV, WarningName);
  1063. }
  1064. };
  1065. /// "\#pragma hdrstop [<header-name-string>]"
  1066. struct PragmaHdrstopHandler : public PragmaHandler {
  1067. PragmaHdrstopHandler() : PragmaHandler("hdrstop") {}
  1068. void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
  1069. Token &DepToken) override {
  1070. PP.HandlePragmaHdrstop(DepToken);
  1071. }
  1072. };
  1073. /// "\#pragma warning(...)". MSVC's diagnostics do not map cleanly to clang's
  1074. /// diagnostics, so we don't really implement this pragma. We parse it and
  1075. /// ignore it to avoid -Wunknown-pragma warnings.
  1076. struct PragmaWarningHandler : public PragmaHandler {
  1077. PragmaWarningHandler() : PragmaHandler("warning") {}
  1078. void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
  1079. Token &Tok) override {
  1080. // Parse things like:
  1081. // warning(push, 1)
  1082. // warning(pop)
  1083. // warning(disable : 1 2 3 ; error : 4 5 6 ; suppress : 7 8 9)
  1084. SourceLocation DiagLoc = Tok.getLocation();
  1085. PPCallbacks *Callbacks = PP.getPPCallbacks();
  1086. PP.Lex(Tok);
  1087. if (Tok.isNot(tok::l_paren)) {
  1088. PP.Diag(Tok, diag::warn_pragma_warning_expected) << "(";
  1089. return;
  1090. }
  1091. PP.Lex(Tok);
  1092. IdentifierInfo *II = Tok.getIdentifierInfo();
  1093. if (II && II->isStr("push")) {
  1094. // #pragma warning( push[ ,n ] )
  1095. int Level = -1;
  1096. PP.Lex(Tok);
  1097. if (Tok.is(tok::comma)) {
  1098. PP.Lex(Tok);
  1099. uint64_t Value;
  1100. if (Tok.is(tok::numeric_constant) &&
  1101. PP.parseSimpleIntegerLiteral(Tok, Value))
  1102. Level = int(Value);
  1103. if (Level < 0 || Level > 4) {
  1104. PP.Diag(Tok, diag::warn_pragma_warning_push_level);
  1105. return;
  1106. }
  1107. }
  1108. if (Callbacks)
  1109. Callbacks->PragmaWarningPush(DiagLoc, Level);
  1110. } else if (II && II->isStr("pop")) {
  1111. // #pragma warning( pop )
  1112. PP.Lex(Tok);
  1113. if (Callbacks)
  1114. Callbacks->PragmaWarningPop(DiagLoc);
  1115. } else {
  1116. // #pragma warning( warning-specifier : warning-number-list
  1117. // [; warning-specifier : warning-number-list...] )
  1118. while (true) {
  1119. II = Tok.getIdentifierInfo();
  1120. if (!II && !Tok.is(tok::numeric_constant)) {
  1121. PP.Diag(Tok, diag::warn_pragma_warning_spec_invalid);
  1122. return;
  1123. }
  1124. // Figure out which warning specifier this is.
  1125. bool SpecifierValid;
  1126. StringRef Specifier;
  1127. llvm::SmallString<1> SpecifierBuf;
  1128. if (II) {
  1129. Specifier = II->getName();
  1130. SpecifierValid = llvm::StringSwitch<bool>(Specifier)
  1131. .Cases("default", "disable", "error", "once",
  1132. "suppress", true)
  1133. .Default(false);
  1134. // If we read a correct specifier, snatch next token (that should be
  1135. // ":", checked later).
  1136. if (SpecifierValid)
  1137. PP.Lex(Tok);
  1138. } else {
  1139. // Token is a numeric constant. It should be either 1, 2, 3 or 4.
  1140. uint64_t Value;
  1141. Specifier = PP.getSpelling(Tok, SpecifierBuf);
  1142. if (PP.parseSimpleIntegerLiteral(Tok, Value)) {
  1143. SpecifierValid = (Value >= 1) && (Value <= 4);
  1144. } else
  1145. SpecifierValid = false;
  1146. // Next token already snatched by parseSimpleIntegerLiteral.
  1147. }
  1148. if (!SpecifierValid) {
  1149. PP.Diag(Tok, diag::warn_pragma_warning_spec_invalid);
  1150. return;
  1151. }
  1152. if (Tok.isNot(tok::colon)) {
  1153. PP.Diag(Tok, diag::warn_pragma_warning_expected) << ":";
  1154. return;
  1155. }
  1156. // Collect the warning ids.
  1157. SmallVector<int, 4> Ids;
  1158. PP.Lex(Tok);
  1159. while (Tok.is(tok::numeric_constant)) {
  1160. uint64_t Value;
  1161. if (!PP.parseSimpleIntegerLiteral(Tok, Value) || Value == 0 ||
  1162. Value > std::numeric_limits<int>::max()) {
  1163. PP.Diag(Tok, diag::warn_pragma_warning_expected_number);
  1164. return;
  1165. }
  1166. Ids.push_back(int(Value));
  1167. }
  1168. if (Callbacks)
  1169. Callbacks->PragmaWarning(DiagLoc, Specifier, Ids);
  1170. // Parse the next specifier if there is a semicolon.
  1171. if (Tok.isNot(tok::semi))
  1172. break;
  1173. PP.Lex(Tok);
  1174. }
  1175. }
  1176. if (Tok.isNot(tok::r_paren)) {
  1177. PP.Diag(Tok, diag::warn_pragma_warning_expected) << ")";
  1178. return;
  1179. }
  1180. PP.Lex(Tok);
  1181. if (Tok.isNot(tok::eod))
  1182. PP.Diag(Tok, diag::ext_pp_extra_tokens_at_eol) << "pragma warning";
  1183. }
  1184. };
  1185. /// "\#pragma execution_character_set(...)". MSVC supports this pragma only
  1186. /// for "UTF-8". We parse it and ignore it if UTF-8 is provided and warn
  1187. /// otherwise to avoid -Wunknown-pragma warnings.
  1188. struct PragmaExecCharsetHandler : public PragmaHandler {
  1189. PragmaExecCharsetHandler() : PragmaHandler("execution_character_set") {}
  1190. void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
  1191. Token &Tok) override {
  1192. // Parse things like:
  1193. // execution_character_set(push, "UTF-8")
  1194. // execution_character_set(pop)
  1195. SourceLocation DiagLoc = Tok.getLocation();
  1196. PPCallbacks *Callbacks = PP.getPPCallbacks();
  1197. PP.Lex(Tok);
  1198. if (Tok.isNot(tok::l_paren)) {
  1199. PP.Diag(Tok, diag::warn_pragma_exec_charset_expected) << "(";
  1200. return;
  1201. }
  1202. PP.Lex(Tok);
  1203. IdentifierInfo *II = Tok.getIdentifierInfo();
  1204. if (II && II->isStr("push")) {
  1205. // #pragma execution_character_set( push[ , string ] )
  1206. PP.Lex(Tok);
  1207. if (Tok.is(tok::comma)) {
  1208. PP.Lex(Tok);
  1209. std::string ExecCharset;
  1210. if (!PP.FinishLexStringLiteral(Tok, ExecCharset,
  1211. "pragma execution_character_set",
  1212. /*AllowMacroExpansion=*/false))
  1213. return;
  1214. // MSVC supports either of these, but nothing else.
  1215. if (ExecCharset != "UTF-8" && ExecCharset != "utf-8") {
  1216. PP.Diag(Tok, diag::warn_pragma_exec_charset_push_invalid) << ExecCharset;
  1217. return;
  1218. }
  1219. }
  1220. if (Callbacks)
  1221. Callbacks->PragmaExecCharsetPush(DiagLoc, "UTF-8");
  1222. } else if (II && II->isStr("pop")) {
  1223. // #pragma execution_character_set( pop )
  1224. PP.Lex(Tok);
  1225. if (Callbacks)
  1226. Callbacks->PragmaExecCharsetPop(DiagLoc);
  1227. } else {
  1228. PP.Diag(Tok, diag::warn_pragma_exec_charset_spec_invalid);
  1229. return;
  1230. }
  1231. if (Tok.isNot(tok::r_paren)) {
  1232. PP.Diag(Tok, diag::warn_pragma_exec_charset_expected) << ")";
  1233. return;
  1234. }
  1235. PP.Lex(Tok);
  1236. if (Tok.isNot(tok::eod))
  1237. PP.Diag(Tok, diag::ext_pp_extra_tokens_at_eol) << "pragma execution_character_set";
  1238. }
  1239. };
  1240. /// PragmaIncludeAliasHandler - "\#pragma include_alias("...")".
  1241. struct PragmaIncludeAliasHandler : public PragmaHandler {
  1242. PragmaIncludeAliasHandler() : PragmaHandler("include_alias") {}
  1243. void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
  1244. Token &IncludeAliasTok) override {
  1245. PP.HandlePragmaIncludeAlias(IncludeAliasTok);
  1246. }
  1247. };
  1248. /// PragmaMessageHandler - Handle the microsoft and gcc \#pragma message
  1249. /// extension. The syntax is:
  1250. /// \code
  1251. /// #pragma message(string)
  1252. /// \endcode
  1253. /// OR, in GCC mode:
  1254. /// \code
  1255. /// #pragma message string
  1256. /// \endcode
  1257. /// string is a string, which is fully macro expanded, and permits string
  1258. /// concatenation, embedded escape characters, etc... See MSDN for more details.
  1259. /// Also handles \#pragma GCC warning and \#pragma GCC error which take the same
  1260. /// form as \#pragma message.
  1261. struct PragmaMessageHandler : public PragmaHandler {
  1262. private:
  1263. const PPCallbacks::PragmaMessageKind Kind;
  1264. const StringRef Namespace;
  1265. static const char* PragmaKind(PPCallbacks::PragmaMessageKind Kind,
  1266. bool PragmaNameOnly = false) {
  1267. switch (Kind) {
  1268. case PPCallbacks::PMK_Message:
  1269. return PragmaNameOnly ? "message" : "pragma message";
  1270. case PPCallbacks::PMK_Warning:
  1271. return PragmaNameOnly ? "warning" : "pragma warning";
  1272. case PPCallbacks::PMK_Error:
  1273. return PragmaNameOnly ? "error" : "pragma error";
  1274. }
  1275. llvm_unreachable("Unknown PragmaMessageKind!");
  1276. }
  1277. public:
  1278. PragmaMessageHandler(PPCallbacks::PragmaMessageKind Kind,
  1279. StringRef Namespace = StringRef())
  1280. : PragmaHandler(PragmaKind(Kind, true)), Kind(Kind),
  1281. Namespace(Namespace) {}
  1282. void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
  1283. Token &Tok) override {
  1284. SourceLocation MessageLoc = Tok.getLocation();
  1285. PP.Lex(Tok);
  1286. bool ExpectClosingParen = false;
  1287. switch (Tok.getKind()) {
  1288. case tok::l_paren:
  1289. // We have a MSVC style pragma message.
  1290. ExpectClosingParen = true;
  1291. // Read the string.
  1292. PP.Lex(Tok);
  1293. break;
  1294. case tok::string_literal:
  1295. // We have a GCC style pragma message, and we just read the string.
  1296. break;
  1297. default:
  1298. PP.Diag(MessageLoc, diag::err_pragma_message_malformed) << Kind;
  1299. return;
  1300. }
  1301. std::string MessageString;
  1302. if (!PP.FinishLexStringLiteral(Tok, MessageString, PragmaKind(Kind),
  1303. /*AllowMacroExpansion=*/true))
  1304. return;
  1305. if (ExpectClosingParen) {
  1306. if (Tok.isNot(tok::r_paren)) {
  1307. PP.Diag(Tok.getLocation(), diag::err_pragma_message_malformed) << Kind;
  1308. return;
  1309. }
  1310. PP.Lex(Tok); // eat the r_paren.
  1311. }
  1312. if (Tok.isNot(tok::eod)) {
  1313. PP.Diag(Tok.getLocation(), diag::err_pragma_message_malformed) << Kind;
  1314. return;
  1315. }
  1316. // Output the message.
  1317. PP.Diag(MessageLoc, (Kind == PPCallbacks::PMK_Error)
  1318. ? diag::err_pragma_message
  1319. : diag::warn_pragma_message) << MessageString;
  1320. // If the pragma is lexically sound, notify any interested PPCallbacks.
  1321. if (PPCallbacks *Callbacks = PP.getPPCallbacks())
  1322. Callbacks->PragmaMessage(MessageLoc, Namespace, Kind, MessageString);
  1323. }
  1324. };
  1325. /// Handle the clang \#pragma module import extension. The syntax is:
  1326. /// \code
  1327. /// #pragma clang module import some.module.name
  1328. /// \endcode
  1329. struct PragmaModuleImportHandler : public PragmaHandler {
  1330. PragmaModuleImportHandler() : PragmaHandler("import") {}
  1331. void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
  1332. Token &Tok) override {
  1333. SourceLocation ImportLoc = Tok.getLocation();
  1334. // Read the module name.
  1335. llvm::SmallVector<std::pair<IdentifierInfo *, SourceLocation>, 8>
  1336. ModuleName;
  1337. if (LexModuleName(PP, Tok, ModuleName))
  1338. return;
  1339. if (Tok.isNot(tok::eod))
  1340. PP.Diag(Tok, diag::ext_pp_extra_tokens_at_eol) << "pragma";
  1341. // If we have a non-empty module path, load the named module.
  1342. Module *Imported =
  1343. PP.getModuleLoader().loadModule(ImportLoc, ModuleName, Module::Hidden,
  1344. /*IsInclusionDirective=*/false);
  1345. if (!Imported)
  1346. return;
  1347. PP.makeModuleVisible(Imported, ImportLoc);
  1348. PP.EnterAnnotationToken(SourceRange(ImportLoc, ModuleName.back().second),
  1349. tok::annot_module_include, Imported);
  1350. if (auto *CB = PP.getPPCallbacks())
  1351. CB->moduleImport(ImportLoc, ModuleName, Imported);
  1352. }
  1353. };
  1354. /// Handle the clang \#pragma module begin extension. The syntax is:
  1355. /// \code
  1356. /// #pragma clang module begin some.module.name
  1357. /// ...
  1358. /// #pragma clang module end
  1359. /// \endcode
  1360. struct PragmaModuleBeginHandler : public PragmaHandler {
  1361. PragmaModuleBeginHandler() : PragmaHandler("begin") {}
  1362. void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
  1363. Token &Tok) override {
  1364. SourceLocation BeginLoc = Tok.getLocation();
  1365. // Read the module name.
  1366. llvm::SmallVector<std::pair<IdentifierInfo *, SourceLocation>, 8>
  1367. ModuleName;
  1368. if (LexModuleName(PP, Tok, ModuleName))
  1369. return;
  1370. if (Tok.isNot(tok::eod))
  1371. PP.Diag(Tok, diag::ext_pp_extra_tokens_at_eol) << "pragma";
  1372. // We can only enter submodules of the current module.
  1373. StringRef Current = PP.getLangOpts().CurrentModule;
  1374. if (ModuleName.front().first->getName() != Current) {
  1375. PP.Diag(ModuleName.front().second, diag::err_pp_module_begin_wrong_module)
  1376. << ModuleName.front().first << (ModuleName.size() > 1)
  1377. << Current.empty() << Current;
  1378. return;
  1379. }
  1380. // Find the module we're entering. We require that a module map for it
  1381. // be loaded or implicitly loadable.
  1382. auto &HSI = PP.getHeaderSearchInfo();
  1383. Module *M = HSI.lookupModule(Current);
  1384. if (!M) {
  1385. PP.Diag(ModuleName.front().second,
  1386. diag::err_pp_module_begin_no_module_map) << Current;
  1387. return;
  1388. }
  1389. for (unsigned I = 1; I != ModuleName.size(); ++I) {
  1390. auto *NewM = M->findOrInferSubmodule(ModuleName[I].first->getName());
  1391. if (!NewM) {
  1392. PP.Diag(ModuleName[I].second, diag::err_pp_module_begin_no_submodule)
  1393. << M->getFullModuleName() << ModuleName[I].first;
  1394. return;
  1395. }
  1396. M = NewM;
  1397. }
  1398. // If the module isn't available, it doesn't make sense to enter it.
  1399. if (Preprocessor::checkModuleIsAvailable(
  1400. PP.getLangOpts(), PP.getTargetInfo(), PP.getDiagnostics(), M)) {
  1401. PP.Diag(BeginLoc, diag::note_pp_module_begin_here)
  1402. << M->getTopLevelModuleName();
  1403. return;
  1404. }
  1405. // Enter the scope of the submodule.
  1406. PP.EnterSubmodule(M, BeginLoc, /*ForPragma*/true);
  1407. PP.EnterAnnotationToken(SourceRange(BeginLoc, ModuleName.back().second),
  1408. tok::annot_module_begin, M);
  1409. }
  1410. };
  1411. /// Handle the clang \#pragma module end extension.
  1412. struct PragmaModuleEndHandler : public PragmaHandler {
  1413. PragmaModuleEndHandler() : PragmaHandler("end") {}
  1414. void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
  1415. Token &Tok) override {
  1416. SourceLocation Loc = Tok.getLocation();
  1417. PP.LexUnexpandedToken(Tok);
  1418. if (Tok.isNot(tok::eod))
  1419. PP.Diag(Tok, diag::ext_pp_extra_tokens_at_eol) << "pragma";
  1420. Module *M = PP.LeaveSubmodule(/*ForPragma*/true);
  1421. if (M)
  1422. PP.EnterAnnotationToken(SourceRange(Loc), tok::annot_module_end, M);
  1423. else
  1424. PP.Diag(Loc, diag::err_pp_module_end_without_module_begin);
  1425. }
  1426. };
  1427. /// Handle the clang \#pragma module build extension.
  1428. struct PragmaModuleBuildHandler : public PragmaHandler {
  1429. PragmaModuleBuildHandler() : PragmaHandler("build") {}
  1430. void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
  1431. Token &Tok) override {
  1432. PP.HandlePragmaModuleBuild(Tok);
  1433. }
  1434. };
  1435. /// Handle the clang \#pragma module load extension.
  1436. struct PragmaModuleLoadHandler : public PragmaHandler {
  1437. PragmaModuleLoadHandler() : PragmaHandler("load") {}
  1438. void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
  1439. Token &Tok) override {
  1440. SourceLocation Loc = Tok.getLocation();
  1441. // Read the module name.
  1442. llvm::SmallVector<std::pair<IdentifierInfo *, SourceLocation>, 8>
  1443. ModuleName;
  1444. if (LexModuleName(PP, Tok, ModuleName))
  1445. return;
  1446. if (Tok.isNot(tok::eod))
  1447. PP.Diag(Tok, diag::ext_pp_extra_tokens_at_eol) << "pragma";
  1448. // Load the module, don't make it visible.
  1449. PP.getModuleLoader().loadModule(Loc, ModuleName, Module::Hidden,
  1450. /*IsInclusionDirective=*/false);
  1451. }
  1452. };
  1453. /// PragmaPushMacroHandler - "\#pragma push_macro" saves the value of the
  1454. /// macro on the top of the stack.
  1455. struct PragmaPushMacroHandler : public PragmaHandler {
  1456. PragmaPushMacroHandler() : PragmaHandler("push_macro") {}
  1457. void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
  1458. Token &PushMacroTok) override {
  1459. PP.HandlePragmaPushMacro(PushMacroTok);
  1460. }
  1461. };
  1462. /// PragmaPopMacroHandler - "\#pragma pop_macro" sets the value of the
  1463. /// macro to the value on the top of the stack.
  1464. struct PragmaPopMacroHandler : public PragmaHandler {
  1465. PragmaPopMacroHandler() : PragmaHandler("pop_macro") {}
  1466. void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
  1467. Token &PopMacroTok) override {
  1468. PP.HandlePragmaPopMacro(PopMacroTok);
  1469. }
  1470. };
  1471. /// PragmaARCCFCodeAuditedHandler -
  1472. /// \#pragma clang arc_cf_code_audited begin/end
  1473. struct PragmaARCCFCodeAuditedHandler : public PragmaHandler {
  1474. PragmaARCCFCodeAuditedHandler() : PragmaHandler("arc_cf_code_audited") {}
  1475. void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
  1476. Token &NameTok) override {
  1477. SourceLocation Loc = NameTok.getLocation();
  1478. bool IsBegin;
  1479. Token Tok;
  1480. // Lex the 'begin' or 'end'.
  1481. PP.LexUnexpandedToken(Tok);
  1482. const IdentifierInfo *BeginEnd = Tok.getIdentifierInfo();
  1483. if (BeginEnd && BeginEnd->isStr("begin")) {
  1484. IsBegin = true;
  1485. } else if (BeginEnd && BeginEnd->isStr("end")) {
  1486. IsBegin = false;
  1487. } else {
  1488. PP.Diag(Tok.getLocation(), diag::err_pp_arc_cf_code_audited_syntax);
  1489. return;
  1490. }
  1491. // Verify that this is followed by EOD.
  1492. PP.LexUnexpandedToken(Tok);
  1493. if (Tok.isNot(tok::eod))
  1494. PP.Diag(Tok, diag::ext_pp_extra_tokens_at_eol) << "pragma";
  1495. // The start location of the active audit.
  1496. SourceLocation BeginLoc = PP.getPragmaARCCFCodeAuditedInfo().second;
  1497. // The start location we want after processing this.
  1498. SourceLocation NewLoc;
  1499. if (IsBegin) {
  1500. // Complain about attempts to re-enter an audit.
  1501. if (BeginLoc.isValid()) {
  1502. PP.Diag(Loc, diag::err_pp_double_begin_of_arc_cf_code_audited);
  1503. PP.Diag(BeginLoc, diag::note_pragma_entered_here);
  1504. }
  1505. NewLoc = Loc;
  1506. } else {
  1507. // Complain about attempts to leave an audit that doesn't exist.
  1508. if (!BeginLoc.isValid()) {
  1509. PP.Diag(Loc, diag::err_pp_unmatched_end_of_arc_cf_code_audited);
  1510. return;
  1511. }
  1512. NewLoc = SourceLocation();
  1513. }
  1514. PP.setPragmaARCCFCodeAuditedInfo(NameTok.getIdentifierInfo(), NewLoc);
  1515. }
  1516. };
  1517. /// PragmaAssumeNonNullHandler -
  1518. /// \#pragma clang assume_nonnull begin/end
  1519. struct PragmaAssumeNonNullHandler : public PragmaHandler {
  1520. PragmaAssumeNonNullHandler() : PragmaHandler("assume_nonnull") {}
  1521. void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
  1522. Token &NameTok) override {
  1523. SourceLocation Loc = NameTok.getLocation();
  1524. bool IsBegin;
  1525. Token Tok;
  1526. // Lex the 'begin' or 'end'.
  1527. PP.LexUnexpandedToken(Tok);
  1528. const IdentifierInfo *BeginEnd = Tok.getIdentifierInfo();
  1529. if (BeginEnd && BeginEnd->isStr("begin")) {
  1530. IsBegin = true;
  1531. } else if (BeginEnd && BeginEnd->isStr("end")) {
  1532. IsBegin = false;
  1533. } else {
  1534. PP.Diag(Tok.getLocation(), diag::err_pp_assume_nonnull_syntax);
  1535. return;
  1536. }
  1537. // Verify that this is followed by EOD.
  1538. PP.LexUnexpandedToken(Tok);
  1539. if (Tok.isNot(tok::eod))
  1540. PP.Diag(Tok, diag::ext_pp_extra_tokens_at_eol) << "pragma";
  1541. // The start location of the active audit.
  1542. SourceLocation BeginLoc = PP.getPragmaAssumeNonNullLoc();
  1543. // The start location we want after processing this.
  1544. SourceLocation NewLoc;
  1545. PPCallbacks *Callbacks = PP.getPPCallbacks();
  1546. if (IsBegin) {
  1547. // Complain about attempts to re-enter an audit.
  1548. if (BeginLoc.isValid()) {
  1549. PP.Diag(Loc, diag::err_pp_double_begin_of_assume_nonnull);
  1550. PP.Diag(BeginLoc, diag::note_pragma_entered_here);
  1551. }
  1552. NewLoc = Loc;
  1553. if (Callbacks)
  1554. Callbacks->PragmaAssumeNonNullBegin(NewLoc);
  1555. } else {
  1556. // Complain about attempts to leave an audit that doesn't exist.
  1557. if (!BeginLoc.isValid()) {
  1558. PP.Diag(Loc, diag::err_pp_unmatched_end_of_assume_nonnull);
  1559. return;
  1560. }
  1561. NewLoc = SourceLocation();
  1562. if (Callbacks)
  1563. Callbacks->PragmaAssumeNonNullEnd(NewLoc);
  1564. }
  1565. PP.setPragmaAssumeNonNullLoc(NewLoc);
  1566. }
  1567. };
  1568. /// Handle "\#pragma region [...]"
  1569. ///
  1570. /// The syntax is
  1571. /// \code
  1572. /// #pragma region [optional name]
  1573. /// #pragma endregion [optional comment]
  1574. /// \endcode
  1575. ///
  1576. /// \note This is
  1577. /// <a href="http://msdn.microsoft.com/en-us/library/b6xkz944(v=vs.80).aspx">editor-only</a>
  1578. /// pragma, just skipped by compiler.
  1579. struct PragmaRegionHandler : public PragmaHandler {
  1580. PragmaRegionHandler(const char *pragma) : PragmaHandler(pragma) {}
  1581. void HandlePragma(Preprocessor &PP, PragmaIntroducer Introducer,
  1582. Token &NameTok) override {
  1583. // #pragma region: endregion matches can be verified
  1584. // __pragma(region): no sense, but ignored by msvc
  1585. // _Pragma is not valid for MSVC, but there isn't any point
  1586. // to handle a _Pragma differently.
  1587. }
  1588. };
  1589. } // namespace
  1590. /// RegisterBuiltinPragmas - Install the standard preprocessor pragmas:
  1591. /// \#pragma GCC poison/system_header/dependency and \#pragma once.
  1592. void Preprocessor::RegisterBuiltinPragmas() {
  1593. AddPragmaHandler(new PragmaOnceHandler());
  1594. AddPragmaHandler(new PragmaMarkHandler());
  1595. AddPragmaHandler(new PragmaPushMacroHandler());
  1596. AddPragmaHandler(new PragmaPopMacroHandler());
  1597. AddPragmaHandler(new PragmaMessageHandler(PPCallbacks::PMK_Message));
  1598. // #pragma GCC ...
  1599. AddPragmaHandler("GCC", new PragmaPoisonHandler());
  1600. AddPragmaHandler("GCC", new PragmaSystemHeaderHandler());
  1601. AddPragmaHandler("GCC", new PragmaDependencyHandler());
  1602. AddPragmaHandler("GCC", new PragmaDiagnosticHandler("GCC"));
  1603. AddPragmaHandler("GCC", new PragmaMessageHandler(PPCallbacks::PMK_Warning,
  1604. "GCC"));
  1605. AddPragmaHandler("GCC", new PragmaMessageHandler(PPCallbacks::PMK_Error,
  1606. "GCC"));
  1607. // #pragma clang ...
  1608. AddPragmaHandler("clang", new PragmaPoisonHandler());
  1609. AddPragmaHandler("clang", new PragmaSystemHeaderHandler());
  1610. AddPragmaHandler("clang", new PragmaDebugHandler());
  1611. AddPragmaHandler("clang", new PragmaDependencyHandler());
  1612. AddPragmaHandler("clang", new PragmaDiagnosticHandler("clang"));
  1613. AddPragmaHandler("clang", new PragmaARCCFCodeAuditedHandler());
  1614. AddPragmaHandler("clang", new PragmaAssumeNonNullHandler());
  1615. // #pragma clang module ...
  1616. auto *ModuleHandler = new PragmaNamespace("module");
  1617. AddPragmaHandler("clang", ModuleHandler);
  1618. ModuleHandler->AddPragma(new PragmaModuleImportHandler());
  1619. ModuleHandler->AddPragma(new PragmaModuleBeginHandler());
  1620. ModuleHandler->AddPragma(new PragmaModuleEndHandler());
  1621. ModuleHandler->AddPragma(new PragmaModuleBuildHandler());
  1622. ModuleHandler->AddPragma(new PragmaModuleLoadHandler());
  1623. // Add region pragmas.
  1624. AddPragmaHandler(new PragmaRegionHandler("region"));
  1625. AddPragmaHandler(new PragmaRegionHandler("endregion"));
  1626. // MS extensions.
  1627. if (LangOpts.MicrosoftExt) {
  1628. AddPragmaHandler(new PragmaWarningHandler());
  1629. AddPragmaHandler(new PragmaExecCharsetHandler());
  1630. AddPragmaHandler(new PragmaIncludeAliasHandler());
  1631. AddPragmaHandler(new PragmaHdrstopHandler());
  1632. }
  1633. // Pragmas added by plugins
  1634. for (PragmaHandlerRegistry::iterator it = PragmaHandlerRegistry::begin(),
  1635. ie = PragmaHandlerRegistry::end();
  1636. it != ie; ++it) {
  1637. AddPragmaHandler(it->instantiate().release());
  1638. }
  1639. }
  1640. /// Ignore all pragmas, useful for modes such as -Eonly which would otherwise
  1641. /// warn about those pragmas being unknown.
  1642. void Preprocessor::IgnorePragmas() {
  1643. AddPragmaHandler(new EmptyPragmaHandler());
  1644. // Also ignore all pragmas in all namespaces created
  1645. // in Preprocessor::RegisterBuiltinPragmas().
  1646. AddPragmaHandler("GCC", new EmptyPragmaHandler());
  1647. AddPragmaHandler("clang", new EmptyPragmaHandler());
  1648. }