Pragma.cpp 73 KB

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