Pragma.cpp 64 KB

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