Pragma.cpp 74 KB

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