PPDirectives.cpp 92 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533
  1. //===--- PPDirectives.cpp - Directive Handling for Preprocessor -----------===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. ///
  10. /// \file
  11. /// \brief Implements # directive processing for the Preprocessor.
  12. ///
  13. //===----------------------------------------------------------------------===//
  14. #include "clang/Lex/Preprocessor.h"
  15. #include "clang/Basic/FileManager.h"
  16. #include "clang/Basic/SourceManager.h"
  17. #include "clang/Lex/CodeCompletionHandler.h"
  18. #include "clang/Lex/HeaderSearch.h"
  19. #include "clang/Lex/HeaderSearchOptions.h"
  20. #include "clang/Lex/LexDiagnostic.h"
  21. #include "clang/Lex/LiteralSupport.h"
  22. #include "clang/Lex/MacroInfo.h"
  23. #include "clang/Lex/ModuleLoader.h"
  24. #include "clang/Lex/Pragma.h"
  25. #include "llvm/ADT/APInt.h"
  26. #include "llvm/Support/ErrorHandling.h"
  27. #include "llvm/Support/Path.h"
  28. #include "llvm/Support/SaveAndRestore.h"
  29. #include "clang/Lex/PreprocessorOptions.h" // HLSL Change - ignore line directives.
  30. using namespace clang;
  31. //===----------------------------------------------------------------------===//
  32. // Utility Methods for Preprocessor Directive Handling.
  33. //===----------------------------------------------------------------------===//
  34. MacroInfo *Preprocessor::AllocateMacroInfo() {
  35. MacroInfoChain *MIChain = BP.Allocate<MacroInfoChain>();
  36. MIChain->Next = MIChainHead;
  37. MIChainHead = MIChain;
  38. return &MIChain->MI;
  39. }
  40. MacroInfo *Preprocessor::AllocateMacroInfo(SourceLocation L) {
  41. MacroInfo *MI = AllocateMacroInfo();
  42. new (MI) MacroInfo(L);
  43. return MI;
  44. }
  45. MacroInfo *Preprocessor::AllocateDeserializedMacroInfo(SourceLocation L,
  46. unsigned SubModuleID) {
  47. static_assert(llvm::AlignOf<MacroInfo>::Alignment >= sizeof(SubModuleID),
  48. "alignment for MacroInfo is less than the ID");
  49. DeserializedMacroInfoChain *MIChain =
  50. BP.Allocate<DeserializedMacroInfoChain>();
  51. MIChain->Next = DeserialMIChainHead;
  52. DeserialMIChainHead = MIChain;
  53. MacroInfo *MI = &MIChain->MI;
  54. new (MI) MacroInfo(L);
  55. MI->FromASTFile = true;
  56. MI->setOwningModuleID(SubModuleID);
  57. return MI;
  58. }
  59. DefMacroDirective *Preprocessor::AllocateDefMacroDirective(MacroInfo *MI,
  60. SourceLocation Loc) {
  61. return new (BP) DefMacroDirective(MI, Loc);
  62. }
  63. UndefMacroDirective *
  64. Preprocessor::AllocateUndefMacroDirective(SourceLocation UndefLoc) {
  65. return new (BP) UndefMacroDirective(UndefLoc);
  66. }
  67. VisibilityMacroDirective *
  68. Preprocessor::AllocateVisibilityMacroDirective(SourceLocation Loc,
  69. bool isPublic) {
  70. return new (BP) VisibilityMacroDirective(Loc, isPublic);
  71. }
  72. /// \brief Read and discard all tokens remaining on the current line until
  73. /// the tok::eod token is found.
  74. void Preprocessor::DiscardUntilEndOfDirective() {
  75. Token Tmp;
  76. do {
  77. LexUnexpandedToken(Tmp);
  78. assert(Tmp.isNot(tok::eof) && "EOF seen while discarding directive tokens");
  79. } while (Tmp.isNot(tok::eod));
  80. }
  81. /// \brief Enumerates possible cases of #define/#undef a reserved identifier.
  82. enum MacroDiag {
  83. MD_NoWarn, //> Not a reserved identifier
  84. MD_KeywordDef, //> Macro hides keyword, enabled by default
  85. MD_ReservedMacro //> #define of #undef reserved id, disabled by default
  86. };
  87. /// \brief Checks if the specified identifier is reserved in the specified
  88. /// language.
  89. /// This function does not check if the identifier is a keyword.
  90. static bool isReservedId(StringRef Text, const LangOptions &Lang) {
  91. // C++ [macro.names], C11 7.1.3:
  92. // All identifiers that begin with an underscore and either an uppercase
  93. // letter or another underscore are always reserved for any use.
  94. if (Text.size() >= 2 && Text[0] == '_' &&
  95. (isUppercase(Text[1]) || Text[1] == '_'))
  96. return true;
  97. // C++ [global.names]
  98. // Each name that contains a double underscore ... is reserved to the
  99. // implementation for any use.
  100. if (Lang.CPlusPlus) {
  101. if (Text.find("__") != StringRef::npos)
  102. return true;
  103. }
  104. return false;
  105. }
  106. static MacroDiag shouldWarnOnMacroDef(Preprocessor &PP, IdentifierInfo *II) {
  107. const LangOptions &Lang = PP.getLangOpts();
  108. StringRef Text = II->getName();
  109. if (isReservedId(Text, Lang))
  110. return MD_ReservedMacro;
  111. if (II->isKeyword(Lang))
  112. return MD_KeywordDef;
  113. if (Lang.CPlusPlus11 && (Text.equals("override") || Text.equals("final")))
  114. return MD_KeywordDef;
  115. return MD_NoWarn;
  116. }
  117. static MacroDiag shouldWarnOnMacroUndef(Preprocessor &PP, IdentifierInfo *II) {
  118. const LangOptions &Lang = PP.getLangOpts();
  119. StringRef Text = II->getName();
  120. // Do not warn on keyword undef. It is generally harmless and widely used.
  121. if (isReservedId(Text, Lang))
  122. return MD_ReservedMacro;
  123. return MD_NoWarn;
  124. }
  125. bool Preprocessor::CheckMacroName(Token &MacroNameTok, MacroUse isDefineUndef,
  126. bool *ShadowFlag) {
  127. // Missing macro name?
  128. if (MacroNameTok.is(tok::eod))
  129. return Diag(MacroNameTok, diag::err_pp_missing_macro_name);
  130. IdentifierInfo *II = MacroNameTok.getIdentifierInfo();
  131. if (!II) {
  132. bool Invalid = false;
  133. std::string Spelling = getSpelling(MacroNameTok, &Invalid);
  134. if (Invalid)
  135. return Diag(MacroNameTok, diag::err_pp_macro_not_identifier);
  136. II = getIdentifierInfo(Spelling);
  137. if (!II->isCPlusPlusOperatorKeyword() || getLangOpts().HLSL) // HLSL Change: guard against HLSL
  138. return Diag(MacroNameTok, diag::err_pp_macro_not_identifier);
  139. // C++ 2.5p2: Alternative tokens behave the same as its primary token
  140. // except for their spellings.
  141. Diag(MacroNameTok, getLangOpts().MicrosoftExt
  142. ? diag::ext_pp_operator_used_as_macro_name
  143. : diag::err_pp_operator_used_as_macro_name)
  144. << II << MacroNameTok.getKind();
  145. // Allow #defining |and| and friends for Microsoft compatibility or
  146. // recovery when legacy C headers are included in C++.
  147. MacroNameTok.setIdentifierInfo(II);
  148. }
  149. if ((isDefineUndef != MU_Other) && II->getPPKeywordID() == tok::pp_defined) {
  150. // Error if defining "defined": C99 6.10.8/4, C++ [cpp.predefined]p4.
  151. return Diag(MacroNameTok, diag::err_defined_macro_name);
  152. }
  153. if (isDefineUndef == MU_Undef) {
  154. auto *MI = getMacroInfo(II);
  155. if (MI && MI->isBuiltinMacro()) {
  156. // Warn if undefining "__LINE__" and other builtins, per C99 6.10.8/4
  157. // and C++ [cpp.predefined]p4], but allow it as an extension.
  158. Diag(MacroNameTok, diag::ext_pp_undef_builtin_macro);
  159. }
  160. }
  161. // If defining/undefining reserved identifier or a keyword, we need to issue
  162. // a warning.
  163. SourceLocation MacroNameLoc = MacroNameTok.getLocation();
  164. if (ShadowFlag)
  165. *ShadowFlag = false;
  166. if (!SourceMgr.isInSystemHeader(MacroNameLoc) &&
  167. (strcmp(SourceMgr.getBufferName(MacroNameLoc), "<built-in>") != 0)) {
  168. MacroDiag D = MD_NoWarn;
  169. if (isDefineUndef == MU_Define) {
  170. D = shouldWarnOnMacroDef(*this, II);
  171. }
  172. else if (isDefineUndef == MU_Undef)
  173. D = shouldWarnOnMacroUndef(*this, II);
  174. if (D == MD_KeywordDef) {
  175. // We do not want to warn on some patterns widely used in configuration
  176. // scripts. This requires analyzing next tokens, so do not issue warnings
  177. // now, only inform caller.
  178. if (ShadowFlag)
  179. *ShadowFlag = true;
  180. }
  181. if (D == MD_ReservedMacro)
  182. Diag(MacroNameTok, diag::warn_pp_macro_is_reserved_id);
  183. }
  184. // Okay, we got a good identifier.
  185. return false;
  186. }
  187. /// \brief Lex and validate a macro name, which occurs after a
  188. /// \#define or \#undef.
  189. ///
  190. /// This sets the token kind to eod and discards the rest of the macro line if
  191. /// the macro name is invalid.
  192. ///
  193. /// \param MacroNameTok Token that is expected to be a macro name.
  194. /// \param isDefineUndef Context in which macro is used.
  195. /// \param ShadowFlag Points to a flag that is set if macro shadows a keyword.
  196. void Preprocessor::ReadMacroName(Token &MacroNameTok, MacroUse isDefineUndef,
  197. bool *ShadowFlag) {
  198. // Read the token, don't allow macro expansion on it.
  199. LexUnexpandedToken(MacroNameTok);
  200. if (MacroNameTok.is(tok::code_completion)) {
  201. if (CodeComplete)
  202. CodeComplete->CodeCompleteMacroName(isDefineUndef == MU_Define);
  203. setCodeCompletionReached();
  204. LexUnexpandedToken(MacroNameTok);
  205. }
  206. if (!CheckMacroName(MacroNameTok, isDefineUndef, ShadowFlag))
  207. return;
  208. // Invalid macro name, read and discard the rest of the line and set the
  209. // token kind to tok::eod if necessary.
  210. if (MacroNameTok.isNot(tok::eod)) {
  211. MacroNameTok.setKind(tok::eod);
  212. DiscardUntilEndOfDirective();
  213. }
  214. }
  215. /// \brief Ensure that the next token is a tok::eod token.
  216. ///
  217. /// If not, emit a diagnostic and consume up until the eod. If EnableMacros is
  218. /// true, then we consider macros that expand to zero tokens as being ok.
  219. void Preprocessor::CheckEndOfDirective(const char *DirType, bool EnableMacros) {
  220. Token Tmp;
  221. // Lex unexpanded tokens for most directives: macros might expand to zero
  222. // tokens, causing us to miss diagnosing invalid lines. Some directives (like
  223. // #line) allow empty macros.
  224. if (EnableMacros)
  225. Lex(Tmp);
  226. else
  227. LexUnexpandedToken(Tmp);
  228. // There should be no tokens after the directive, but we allow them as an
  229. // extension.
  230. while (Tmp.is(tok::comment)) // Skip comments in -C mode.
  231. LexUnexpandedToken(Tmp);
  232. if (Tmp.isNot(tok::eod)) {
  233. // Add a fixit in GNU/C99/C++ mode. Don't offer a fixit for strict-C89,
  234. // or if this is a macro-style preprocessing directive, because it is more
  235. // trouble than it is worth to insert /**/ and check that there is no /**/
  236. // in the range also.
  237. FixItHint Hint;
  238. if ((LangOpts.GNUMode || LangOpts.C99 || LangOpts.CPlusPlus) &&
  239. !CurTokenLexer)
  240. Hint = FixItHint::CreateInsertion(Tmp.getLocation(),"//");
  241. Diag(Tmp, diag::ext_pp_extra_tokens_at_eol) << DirType << Hint;
  242. DiscardUntilEndOfDirective();
  243. }
  244. }
  245. /// SkipExcludedConditionalBlock - We just read a \#if or related directive and
  246. /// decided that the subsequent tokens are in the \#if'd out portion of the
  247. /// file. Lex the rest of the file, until we see an \#endif. If
  248. /// FoundNonSkipPortion is true, then we have already emitted code for part of
  249. /// this \#if directive, so \#else/\#elif blocks should never be entered.
  250. /// If ElseOk is true, then \#else directives are ok, if not, then we have
  251. /// already seen one so a \#else directive is a duplicate. When this returns,
  252. /// the caller can lex the first valid token.
  253. void Preprocessor::SkipExcludedConditionalBlock(SourceLocation IfTokenLoc,
  254. bool FoundNonSkipPortion,
  255. bool FoundElse,
  256. SourceLocation ElseLoc) {
  257. ++NumSkipped;
  258. assert(!CurTokenLexer && CurPPLexer && "Lexing a macro, not a file?");
  259. CurPPLexer->pushConditionalLevel(IfTokenLoc, /*isSkipping*/false,
  260. FoundNonSkipPortion, FoundElse);
  261. if (CurPTHLexer) {
  262. PTHSkipExcludedConditionalBlock();
  263. return;
  264. }
  265. // Enter raw mode to disable identifier lookup (and thus macro expansion),
  266. // disabling warnings, etc.
  267. CurPPLexer->LexingRawMode = true;
  268. Token Tok;
  269. while (1) {
  270. CurLexer->Lex(Tok);
  271. if (Tok.is(tok::code_completion)) {
  272. if (CodeComplete)
  273. CodeComplete->CodeCompleteInConditionalExclusion();
  274. setCodeCompletionReached();
  275. continue;
  276. }
  277. // If this is the end of the buffer, we have an error.
  278. if (Tok.is(tok::eof)) {
  279. // Emit errors for each unterminated conditional on the stack, including
  280. // the current one.
  281. while (!CurPPLexer->ConditionalStack.empty()) {
  282. if (CurLexer->getFileLoc() != CodeCompletionFileLoc)
  283. Diag(CurPPLexer->ConditionalStack.back().IfLoc,
  284. diag::err_pp_unterminated_conditional);
  285. CurPPLexer->ConditionalStack.pop_back();
  286. }
  287. // Just return and let the caller lex after this #include.
  288. break;
  289. }
  290. // If this token is not a preprocessor directive, just skip it.
  291. if (Tok.isNot(tok::hash) || !Tok.isAtStartOfLine())
  292. continue;
  293. // We just parsed a # character at the start of a line, so we're in
  294. // directive mode. Tell the lexer this so any newlines we see will be
  295. // converted into an EOD token (this terminates the macro).
  296. CurPPLexer->ParsingPreprocessorDirective = true;
  297. if (CurLexer) CurLexer->SetKeepWhitespaceMode(false);
  298. // Read the next token, the directive flavor.
  299. LexUnexpandedToken(Tok);
  300. // If this isn't an identifier directive (e.g. is "# 1\n" or "#\n", or
  301. // something bogus), skip it.
  302. if (Tok.isNot(tok::raw_identifier)) {
  303. CurPPLexer->ParsingPreprocessorDirective = false;
  304. // Restore comment saving mode.
  305. if (CurLexer) CurLexer->resetExtendedTokenMode();
  306. continue;
  307. }
  308. // If the first letter isn't i or e, it isn't intesting to us. We know that
  309. // this is safe in the face of spelling differences, because there is no way
  310. // to spell an i/e in a strange way that is another letter. Skipping this
  311. // allows us to avoid looking up the identifier info for #define/#undef and
  312. // other common directives.
  313. StringRef RI = Tok.getRawIdentifier();
  314. char FirstChar = RI[0];
  315. if (FirstChar >= 'a' && FirstChar <= 'z' &&
  316. FirstChar != 'i' && FirstChar != 'e') {
  317. CurPPLexer->ParsingPreprocessorDirective = false;
  318. // Restore comment saving mode.
  319. if (CurLexer) CurLexer->resetExtendedTokenMode();
  320. continue;
  321. }
  322. // Get the identifier name without trigraphs or embedded newlines. Note
  323. // that we can't use Tok.getIdentifierInfo() because its lookup is disabled
  324. // when skipping.
  325. char DirectiveBuf[20];
  326. StringRef Directive;
  327. if (!Tok.needsCleaning() && RI.size() < 20) {
  328. Directive = RI;
  329. } else {
  330. std::string DirectiveStr = getSpelling(Tok);
  331. unsigned IdLen = DirectiveStr.size();
  332. if (IdLen >= 20) {
  333. CurPPLexer->ParsingPreprocessorDirective = false;
  334. // Restore comment saving mode.
  335. if (CurLexer) CurLexer->resetExtendedTokenMode();
  336. continue;
  337. }
  338. memcpy(DirectiveBuf, &DirectiveStr[0], IdLen);
  339. Directive = StringRef(DirectiveBuf, IdLen);
  340. }
  341. if (Directive.startswith("if")) {
  342. StringRef Sub = Directive.substr(2);
  343. if (Sub.empty() || // "if"
  344. Sub == "def" || // "ifdef"
  345. Sub == "ndef") { // "ifndef"
  346. // We know the entire #if/#ifdef/#ifndef block will be skipped, don't
  347. // bother parsing the condition.
  348. DiscardUntilEndOfDirective();
  349. CurPPLexer->pushConditionalLevel(Tok.getLocation(), /*wasskipping*/true,
  350. /*foundnonskip*/false,
  351. /*foundelse*/false);
  352. }
  353. } else if (Directive[0] == 'e') {
  354. StringRef Sub = Directive.substr(1);
  355. if (Sub == "ndif") { // "endif"
  356. PPConditionalInfo CondInfo;
  357. CondInfo.WasSkipping = true; // Silence bogus warning.
  358. bool InCond = CurPPLexer->popConditionalLevel(CondInfo);
  359. (void)InCond; // Silence warning in no-asserts mode.
  360. assert(!InCond && "Can't be skipping if not in a conditional!");
  361. // If we popped the outermost skipping block, we're done skipping!
  362. if (!CondInfo.WasSkipping) {
  363. // Restore the value of LexingRawMode so that trailing comments
  364. // are handled correctly, if we've reached the outermost block.
  365. CurPPLexer->LexingRawMode = false;
  366. CheckEndOfDirective("endif");
  367. CurPPLexer->LexingRawMode = true;
  368. if (Callbacks)
  369. Callbacks->Endif(Tok.getLocation(), CondInfo.IfLoc);
  370. break;
  371. } else {
  372. DiscardUntilEndOfDirective();
  373. }
  374. } else if (Sub == "lse") { // "else".
  375. // #else directive in a skipping conditional. If not in some other
  376. // skipping conditional, and if #else hasn't already been seen, enter it
  377. // as a non-skipping conditional.
  378. PPConditionalInfo &CondInfo = CurPPLexer->peekConditionalLevel();
  379. // If this is a #else with a #else before it, report the error.
  380. if (CondInfo.FoundElse) Diag(Tok, diag::pp_err_else_after_else);
  381. // Note that we've seen a #else in this conditional.
  382. CondInfo.FoundElse = true;
  383. // If the conditional is at the top level, and the #if block wasn't
  384. // entered, enter the #else block now.
  385. if (!CondInfo.WasSkipping && !CondInfo.FoundNonSkip) {
  386. CondInfo.FoundNonSkip = true;
  387. // Restore the value of LexingRawMode so that trailing comments
  388. // are handled correctly.
  389. CurPPLexer->LexingRawMode = false;
  390. CheckEndOfDirective("else");
  391. CurPPLexer->LexingRawMode = true;
  392. if (Callbacks)
  393. Callbacks->Else(Tok.getLocation(), CondInfo.IfLoc);
  394. break;
  395. } else {
  396. DiscardUntilEndOfDirective(); // C99 6.10p4.
  397. }
  398. } else if (Sub == "lif") { // "elif".
  399. PPConditionalInfo &CondInfo = CurPPLexer->peekConditionalLevel();
  400. // If this is a #elif with a #else before it, report the error.
  401. if (CondInfo.FoundElse) Diag(Tok, diag::pp_err_elif_after_else);
  402. // If this is in a skipping block or if we're already handled this #if
  403. // block, don't bother parsing the condition.
  404. if (CondInfo.WasSkipping || CondInfo.FoundNonSkip) {
  405. DiscardUntilEndOfDirective();
  406. } else {
  407. const SourceLocation CondBegin = CurPPLexer->getSourceLocation();
  408. // Restore the value of LexingRawMode so that identifiers are
  409. // looked up, etc, inside the #elif expression.
  410. assert(CurPPLexer->LexingRawMode && "We have to be skipping here!");
  411. CurPPLexer->LexingRawMode = false;
  412. IdentifierInfo *IfNDefMacro = nullptr;
  413. const bool CondValue = EvaluateDirectiveExpression(IfNDefMacro);
  414. CurPPLexer->LexingRawMode = true;
  415. if (Callbacks) {
  416. const SourceLocation CondEnd = CurPPLexer->getSourceLocation();
  417. Callbacks->Elif(Tok.getLocation(),
  418. SourceRange(CondBegin, CondEnd),
  419. (CondValue ? PPCallbacks::CVK_True : PPCallbacks::CVK_False), CondInfo.IfLoc);
  420. }
  421. // If this condition is true, enter it!
  422. if (CondValue) {
  423. CondInfo.FoundNonSkip = true;
  424. break;
  425. }
  426. }
  427. }
  428. }
  429. CurPPLexer->ParsingPreprocessorDirective = false;
  430. // Restore comment saving mode.
  431. if (CurLexer) CurLexer->resetExtendedTokenMode();
  432. }
  433. // Finally, if we are out of the conditional (saw an #endif or ran off the end
  434. // of the file, just stop skipping and return to lexing whatever came after
  435. // the #if block.
  436. CurPPLexer->LexingRawMode = false;
  437. if (Callbacks) {
  438. SourceLocation BeginLoc = ElseLoc.isValid() ? ElseLoc : IfTokenLoc;
  439. Callbacks->SourceRangeSkipped(SourceRange(BeginLoc, Tok.getLocation()));
  440. }
  441. }
  442. void Preprocessor::PTHSkipExcludedConditionalBlock() {
  443. while (1) {
  444. assert(CurPTHLexer);
  445. assert(CurPTHLexer->LexingRawMode == false);
  446. // Skip to the next '#else', '#elif', or #endif.
  447. if (CurPTHLexer->SkipBlock()) {
  448. // We have reached an #endif. Both the '#' and 'endif' tokens
  449. // have been consumed by the PTHLexer. Just pop off the condition level.
  450. PPConditionalInfo CondInfo;
  451. bool InCond = CurPTHLexer->popConditionalLevel(CondInfo);
  452. (void)InCond; // Silence warning in no-asserts mode.
  453. assert(!InCond && "Can't be skipping if not in a conditional!");
  454. break;
  455. }
  456. // We have reached a '#else' or '#elif'. Lex the next token to get
  457. // the directive flavor.
  458. Token Tok;
  459. LexUnexpandedToken(Tok);
  460. // We can actually look up the IdentifierInfo here since we aren't in
  461. // raw mode.
  462. tok::PPKeywordKind K = Tok.getIdentifierInfo()->getPPKeywordID();
  463. if (K == tok::pp_else) {
  464. // #else: Enter the else condition. We aren't in a nested condition
  465. // since we skip those. We're always in the one matching the last
  466. // blocked we skipped.
  467. PPConditionalInfo &CondInfo = CurPTHLexer->peekConditionalLevel();
  468. // Note that we've seen a #else in this conditional.
  469. CondInfo.FoundElse = true;
  470. // If the #if block wasn't entered then enter the #else block now.
  471. if (!CondInfo.FoundNonSkip) {
  472. CondInfo.FoundNonSkip = true;
  473. // Scan until the eod token.
  474. CurPTHLexer->ParsingPreprocessorDirective = true;
  475. DiscardUntilEndOfDirective();
  476. CurPTHLexer->ParsingPreprocessorDirective = false;
  477. break;
  478. }
  479. // Otherwise skip this block.
  480. continue;
  481. }
  482. assert(K == tok::pp_elif);
  483. PPConditionalInfo &CondInfo = CurPTHLexer->peekConditionalLevel();
  484. // If this is a #elif with a #else before it, report the error.
  485. if (CondInfo.FoundElse)
  486. Diag(Tok, diag::pp_err_elif_after_else);
  487. // If this is in a skipping block or if we're already handled this #if
  488. // block, don't bother parsing the condition. We just skip this block.
  489. if (CondInfo.FoundNonSkip)
  490. continue;
  491. // Evaluate the condition of the #elif.
  492. IdentifierInfo *IfNDefMacro = nullptr;
  493. CurPTHLexer->ParsingPreprocessorDirective = true;
  494. bool ShouldEnter = EvaluateDirectiveExpression(IfNDefMacro);
  495. CurPTHLexer->ParsingPreprocessorDirective = false;
  496. // If this condition is true, enter it!
  497. if (ShouldEnter) {
  498. CondInfo.FoundNonSkip = true;
  499. break;
  500. }
  501. // Otherwise, skip this block and go to the next one.
  502. continue;
  503. }
  504. }
  505. Module *Preprocessor::getModuleForLocation(SourceLocation Loc) {
  506. ModuleMap &ModMap = HeaderInfo.getModuleMap();
  507. if (SourceMgr.isInMainFile(Loc)) {
  508. if (Module *CurMod = getCurrentModule())
  509. return CurMod; // Compiling a module.
  510. return HeaderInfo.getModuleMap().SourceModule; // Compiling a source.
  511. }
  512. // Try to determine the module of the include directive.
  513. // FIXME: Look into directly passing the FileEntry from LookupFile instead.
  514. FileID IDOfIncl = SourceMgr.getFileID(SourceMgr.getExpansionLoc(Loc));
  515. if (const FileEntry *EntryOfIncl = SourceMgr.getFileEntryForID(IDOfIncl)) {
  516. // The include comes from a file.
  517. return ModMap.findModuleForHeader(EntryOfIncl).getModule();
  518. } else {
  519. // The include does not come from a file,
  520. // so it is probably a module compilation.
  521. return getCurrentModule();
  522. }
  523. }
  524. Module *Preprocessor::getModuleContainingLocation(SourceLocation Loc) {
  525. return HeaderInfo.getModuleMap().inferModuleFromLocation(
  526. FullSourceLoc(Loc, SourceMgr));
  527. }
  528. const FileEntry *Preprocessor::LookupFile(
  529. SourceLocation FilenameLoc,
  530. StringRef Filename,
  531. bool isAngled,
  532. const DirectoryLookup *FromDir,
  533. const FileEntry *FromFile,
  534. const DirectoryLookup *&CurDir,
  535. SmallVectorImpl<char> *SearchPath,
  536. SmallVectorImpl<char> *RelativePath,
  537. ModuleMap::KnownHeader *SuggestedModule,
  538. bool SkipCache) {
  539. // If the header lookup mechanism may be relative to the current inclusion
  540. // stack, record the parent #includes.
  541. SmallVector<std::pair<const FileEntry *, const DirectoryEntry *>, 16>
  542. Includers;
  543. if (!FromDir && !FromFile) {
  544. FileID FID = getCurrentFileLexer()->getFileID();
  545. const FileEntry *FileEnt = SourceMgr.getFileEntryForID(FID);
  546. // If there is no file entry associated with this file, it must be the
  547. // predefines buffer or the module includes buffer. Any other file is not
  548. // lexed with a normal lexer, so it won't be scanned for preprocessor
  549. // directives.
  550. //
  551. // If we have the predefines buffer, resolve #include references (which come
  552. // from the -include command line argument) from the current working
  553. // directory instead of relative to the main file.
  554. //
  555. // If we have the module includes buffer, resolve #include references (which
  556. // come from header declarations in the module map) relative to the module
  557. // map file.
  558. if (!FileEnt) {
  559. if (FID == SourceMgr.getMainFileID() && MainFileDir)
  560. Includers.push_back(std::make_pair(nullptr, MainFileDir));
  561. else if ((FileEnt =
  562. SourceMgr.getFileEntryForID(SourceMgr.getMainFileID())))
  563. Includers.push_back(std::make_pair(FileEnt, FileMgr.getDirectory(".")));
  564. } else {
  565. Includers.push_back(std::make_pair(FileEnt, FileEnt->getDir()));
  566. }
  567. // MSVC searches the current include stack from top to bottom for
  568. // headers included by quoted include directives.
  569. // See: http://msdn.microsoft.com/en-us/library/36k2cdd4.aspx
  570. if ((LangOpts.MSVCCompat || LangOpts.HLSL) && !isAngled) { // HLSL Change - use MSVC compat behavior
  571. for (unsigned i = 0, e = IncludeMacroStack.size(); i != e; ++i) {
  572. IncludeStackInfo &ISEntry = IncludeMacroStack[e - i - 1];
  573. if (IsFileLexer(ISEntry))
  574. if ((FileEnt = SourceMgr.getFileEntryForID(
  575. ISEntry.ThePPLexer->getFileID())))
  576. Includers.push_back(std::make_pair(FileEnt, FileEnt->getDir()));
  577. }
  578. }
  579. }
  580. CurDir = CurDirLookup;
  581. if (FromFile) {
  582. // We're supposed to start looking from after a particular file. Search
  583. // the include path until we find that file or run out of files.
  584. const DirectoryLookup *TmpCurDir = CurDir;
  585. const DirectoryLookup *TmpFromDir = nullptr;
  586. while (const FileEntry *FE = HeaderInfo.LookupFile(
  587. Filename, FilenameLoc, isAngled, TmpFromDir, TmpCurDir,
  588. Includers, SearchPath, RelativePath, SuggestedModule,
  589. SkipCache)) {
  590. // Keep looking as if this file did a #include_next.
  591. TmpFromDir = TmpCurDir;
  592. ++TmpFromDir;
  593. if (FE == FromFile) {
  594. // Found it.
  595. FromDir = TmpFromDir;
  596. CurDir = TmpCurDir;
  597. break;
  598. }
  599. }
  600. }
  601. // Do a standard file entry lookup.
  602. const FileEntry *FE = HeaderInfo.LookupFile(
  603. Filename, FilenameLoc, isAngled, FromDir, CurDir, Includers, SearchPath,
  604. RelativePath, SuggestedModule, SkipCache);
  605. if (FE) {
  606. if (SuggestedModule && !LangOpts.AsmPreprocessor)
  607. HeaderInfo.getModuleMap().diagnoseHeaderInclusion(
  608. getModuleForLocation(FilenameLoc), FilenameLoc, Filename, FE);
  609. return FE;
  610. }
  611. const FileEntry *CurFileEnt;
  612. // Otherwise, see if this is a subframework header. If so, this is relative
  613. // to one of the headers on the #include stack. Walk the list of the current
  614. // headers on the #include stack and pass them to HeaderInfo.
  615. if (IsFileLexer()) {
  616. if ((CurFileEnt = SourceMgr.getFileEntryForID(CurPPLexer->getFileID()))) {
  617. if ((FE = HeaderInfo.LookupSubframeworkHeader(Filename, CurFileEnt,
  618. SearchPath, RelativePath,
  619. SuggestedModule))) {
  620. if (SuggestedModule && !LangOpts.AsmPreprocessor)
  621. HeaderInfo.getModuleMap().diagnoseHeaderInclusion(
  622. getModuleForLocation(FilenameLoc), FilenameLoc, Filename, FE);
  623. return FE;
  624. }
  625. }
  626. }
  627. for (unsigned i = 0, e = IncludeMacroStack.size(); i != e; ++i) {
  628. IncludeStackInfo &ISEntry = IncludeMacroStack[e-i-1];
  629. if (IsFileLexer(ISEntry)) {
  630. if ((CurFileEnt =
  631. SourceMgr.getFileEntryForID(ISEntry.ThePPLexer->getFileID()))) {
  632. if ((FE = HeaderInfo.LookupSubframeworkHeader(
  633. Filename, CurFileEnt, SearchPath, RelativePath,
  634. SuggestedModule))) {
  635. if (SuggestedModule && !LangOpts.AsmPreprocessor)
  636. HeaderInfo.getModuleMap().diagnoseHeaderInclusion(
  637. getModuleForLocation(FilenameLoc), FilenameLoc, Filename, FE);
  638. return FE;
  639. }
  640. }
  641. }
  642. }
  643. // Otherwise, we really couldn't find the file.
  644. return nullptr;
  645. }
  646. //===----------------------------------------------------------------------===//
  647. // Preprocessor Directive Handling.
  648. //===----------------------------------------------------------------------===//
  649. class Preprocessor::ResetMacroExpansionHelper {
  650. public:
  651. ResetMacroExpansionHelper(Preprocessor *pp)
  652. : PP(pp), save(pp->DisableMacroExpansion) {
  653. if (pp->MacroExpansionInDirectivesOverride)
  654. pp->DisableMacroExpansion = false;
  655. }
  656. ~ResetMacroExpansionHelper() {
  657. PP->DisableMacroExpansion = save;
  658. }
  659. private:
  660. Preprocessor *PP;
  661. bool save;
  662. };
  663. /// HandleDirective - This callback is invoked when the lexer sees a # token
  664. /// at the start of a line. This consumes the directive, modifies the
  665. /// lexer/preprocessor state, and advances the lexer(s) so that the next token
  666. /// read is the correct one.
  667. void Preprocessor::HandleDirective(Token &Result) {
  668. // FIXME: Traditional: # with whitespace before it not recognized by K&R?
  669. // We just parsed a # character at the start of a line, so we're in directive
  670. // mode. Tell the lexer this so any newlines we see will be converted into an
  671. // EOD token (which terminates the directive).
  672. CurPPLexer->ParsingPreprocessorDirective = true;
  673. if (CurLexer) CurLexer->SetKeepWhitespaceMode(false);
  674. bool ImmediatelyAfterTopLevelIfndef =
  675. CurPPLexer->MIOpt.getImmediatelyAfterTopLevelIfndef();
  676. CurPPLexer->MIOpt.resetImmediatelyAfterTopLevelIfndef();
  677. ++NumDirectives;
  678. // We are about to read a token. For the multiple-include optimization FA to
  679. // work, we have to remember if we had read any tokens *before* this
  680. // pp-directive.
  681. bool ReadAnyTokensBeforeDirective =CurPPLexer->MIOpt.getHasReadAnyTokensVal();
  682. // Save the '#' token in case we need to return it later.
  683. Token SavedHash = Result;
  684. // Read the next token, the directive flavor. This isn't expanded due to
  685. // C99 6.10.3p8.
  686. LexUnexpandedToken(Result);
  687. // C99 6.10.3p11: Is this preprocessor directive in macro invocation? e.g.:
  688. // #define A(x) #x
  689. // A(abc
  690. // #warning blah
  691. // def)
  692. // If so, the user is relying on undefined behavior, emit a diagnostic. Do
  693. // not support this for #include-like directives, since that can result in
  694. // terrible diagnostics, and does not work in GCC.
  695. if (InMacroArgs) {
  696. if (IdentifierInfo *II = Result.getIdentifierInfo()) {
  697. switch (II->getPPKeywordID()) {
  698. case tok::pp_include:
  699. case tok::pp_import:
  700. case tok::pp_include_next:
  701. case tok::pp___include_macros:
  702. case tok::pp_pragma:
  703. Diag(Result, diag::err_embedded_directive) << II->getName();
  704. DiscardUntilEndOfDirective();
  705. return;
  706. default:
  707. break;
  708. }
  709. }
  710. Diag(Result, diag::ext_embedded_directive);
  711. }
  712. // Temporarily enable macro expansion if set so
  713. // and reset to previous state when returning from this function.
  714. ResetMacroExpansionHelper helper(this);
  715. switch (Result.getKind()) {
  716. case tok::eod:
  717. return; // null directive.
  718. case tok::code_completion:
  719. if (CodeComplete)
  720. CodeComplete->CodeCompleteDirective(
  721. CurPPLexer->getConditionalStackDepth() > 0);
  722. setCodeCompletionReached();
  723. return;
  724. case tok::numeric_constant: // # 7 GNU line marker directive.
  725. if (getLangOpts().AsmPreprocessor)
  726. break; // # 4 is not a preprocessor directive in .S files.
  727. return HandleDigitDirective(Result);
  728. default:
  729. IdentifierInfo *II = Result.getIdentifierInfo();
  730. if (!II) break; // Not an identifier.
  731. // Ask what the preprocessor keyword ID is.
  732. switch (II->getPPKeywordID()) {
  733. default: break;
  734. // C99 6.10.1 - Conditional Inclusion.
  735. case tok::pp_if:
  736. return HandleIfDirective(Result, ReadAnyTokensBeforeDirective);
  737. case tok::pp_ifdef:
  738. return HandleIfdefDirective(Result, false, true/*not valid for miopt*/);
  739. case tok::pp_ifndef:
  740. return HandleIfdefDirective(Result, true, ReadAnyTokensBeforeDirective);
  741. case tok::pp_elif:
  742. return HandleElifDirective(Result);
  743. case tok::pp_else:
  744. return HandleElseDirective(Result);
  745. case tok::pp_endif:
  746. return HandleEndifDirective(Result);
  747. // C99 6.10.2 - Source File Inclusion.
  748. case tok::pp_include:
  749. // Handle #include.
  750. return HandleIncludeDirective(SavedHash.getLocation(), Result);
  751. case tok::pp___include_macros:
  752. // Handle -imacros.
  753. return HandleIncludeMacrosDirective(SavedHash.getLocation(), Result);
  754. // C99 6.10.3 - Macro Replacement.
  755. case tok::pp_define:
  756. return HandleDefineDirective(Result, ImmediatelyAfterTopLevelIfndef);
  757. case tok::pp_undef:
  758. return HandleUndefDirective(Result);
  759. // C99 6.10.4 - Line Control.
  760. case tok::pp_line:
  761. return HandleLineDirective(Result);
  762. // C99 6.10.5 - Error Directive.
  763. case tok::pp_error:
  764. return HandleUserDiagnosticDirective(Result, false);
  765. // C99 6.10.6 - Pragma Directive.
  766. case tok::pp_pragma:
  767. return HandlePragmaDirective(SavedHash.getLocation(), PIK_HashPragma);
  768. // GNU Extensions.
  769. case tok::pp_import:
  770. if (getLangOpts().HLSL) break; // HLSL Change - disable #import
  771. return HandleImportDirective(SavedHash.getLocation(), Result);
  772. case tok::pp_include_next:
  773. if (getLangOpts().HLSL) break; // HLSL Change - disable #include_next
  774. return HandleIncludeNextDirective(SavedHash.getLocation(), Result);
  775. case tok::pp_warning:
  776. Diag(Result, diag::ext_pp_warning_directive);
  777. return HandleUserDiagnosticDirective(Result, true);
  778. case tok::pp_ident:
  779. if (getLangOpts().HLSL) break; // HLSL Change - disable #ident
  780. return HandleIdentSCCSDirective(Result);
  781. case tok::pp_sccs:
  782. if (getLangOpts().HLSL) break; // HLSL Change - disable #sccs
  783. return HandleIdentSCCSDirective(Result);
  784. case tok::pp_assert:
  785. //isExtension = true; // FIXME: implement #assert
  786. break;
  787. case tok::pp_unassert:
  788. //isExtension = true; // FIXME: implement #unassert
  789. break;
  790. case tok::pp___public_macro:
  791. if (getLangOpts().Modules)
  792. return HandleMacroPublicDirective(Result);
  793. break;
  794. case tok::pp___private_macro:
  795. if (getLangOpts().Modules)
  796. return HandleMacroPrivateDirective(Result);
  797. break;
  798. }
  799. break;
  800. }
  801. // If this is a .S file, treat unknown # directives as non-preprocessor
  802. // directives. This is important because # may be a comment or introduce
  803. // various pseudo-ops. Just return the # token and push back the following
  804. // token to be lexed next time.
  805. if (getLangOpts().AsmPreprocessor) {
  806. Token *Toks = new Token[2];
  807. // Return the # and the token after it.
  808. Toks[0] = SavedHash;
  809. Toks[1] = Result;
  810. // If the second token is a hashhash token, then we need to translate it to
  811. // unknown so the token lexer doesn't try to perform token pasting.
  812. if (Result.is(tok::hashhash))
  813. Toks[1].setKind(tok::unknown);
  814. // Enter this token stream so that we re-lex the tokens. Make sure to
  815. // enable macro expansion, in case the token after the # is an identifier
  816. // that is expanded.
  817. EnterTokenStream(Toks, 2, false, true);
  818. return;
  819. }
  820. // If we reached here, the preprocessing token is not valid!
  821. Diag(Result, diag::err_pp_invalid_directive);
  822. // Read the rest of the PP line.
  823. DiscardUntilEndOfDirective();
  824. // Okay, we're done parsing the directive.
  825. }
  826. /// GetLineValue - Convert a numeric token into an unsigned value, emitting
  827. /// Diagnostic DiagID if it is invalid, and returning the value in Val.
  828. static bool GetLineValue(Token &DigitTok, unsigned &Val,
  829. unsigned DiagID, Preprocessor &PP,
  830. bool IsGNULineDirective=false) {
  831. if (DigitTok.isNot(tok::numeric_constant)) {
  832. PP.Diag(DigitTok, DiagID);
  833. if (DigitTok.isNot(tok::eod))
  834. PP.DiscardUntilEndOfDirective();
  835. return true;
  836. }
  837. SmallString<64> IntegerBuffer;
  838. IntegerBuffer.resize(DigitTok.getLength());
  839. const char *DigitTokBegin = &IntegerBuffer[0];
  840. bool Invalid = false;
  841. unsigned ActualLength = PP.getSpelling(DigitTok, DigitTokBegin, &Invalid);
  842. if (Invalid)
  843. return true;
  844. // Verify that we have a simple digit-sequence, and compute the value. This
  845. // is always a simple digit string computed in decimal, so we do this manually
  846. // here.
  847. Val = 0;
  848. for (unsigned i = 0; i != ActualLength; ++i) {
  849. // C++1y [lex.fcon]p1:
  850. // Optional separating single quotes in a digit-sequence are ignored
  851. if (DigitTokBegin[i] == '\'')
  852. continue;
  853. if (!isDigit(DigitTokBegin[i])) {
  854. PP.Diag(PP.AdvanceToTokenCharacter(DigitTok.getLocation(), i),
  855. diag::err_pp_line_digit_sequence) << IsGNULineDirective;
  856. PP.DiscardUntilEndOfDirective();
  857. return true;
  858. }
  859. unsigned NextVal = Val*10+(DigitTokBegin[i]-'0');
  860. if (NextVal < Val) { // overflow.
  861. PP.Diag(DigitTok, DiagID);
  862. PP.DiscardUntilEndOfDirective();
  863. return true;
  864. }
  865. Val = NextVal;
  866. }
  867. if (DigitTokBegin[0] == '0' && Val)
  868. PP.Diag(DigitTok.getLocation(), diag::warn_pp_line_decimal)
  869. << IsGNULineDirective;
  870. return false;
  871. }
  872. /// \brief Handle a \#line directive: C99 6.10.4.
  873. ///
  874. /// The two acceptable forms are:
  875. /// \verbatim
  876. /// # line digit-sequence
  877. /// # line digit-sequence "s-char-sequence"
  878. /// \endverbatim
  879. void Preprocessor::HandleLineDirective(Token &Tok) {
  880. // Read the line # and string argument. Per C99 6.10.4p5, these tokens are
  881. // expanded.
  882. Token DigitTok;
  883. Lex(DigitTok);
  884. // Validate the number and convert it to an unsigned.
  885. unsigned LineNo;
  886. if (GetLineValue(DigitTok, LineNo, diag::err_pp_line_requires_integer,*this))
  887. return;
  888. if (LineNo == 0)
  889. Diag(DigitTok, diag::ext_pp_line_zero);
  890. // Enforce C99 6.10.4p3: "The digit sequence shall not specify ... a
  891. // number greater than 2147483647". C90 requires that the line # be <= 32767.
  892. unsigned LineLimit = 32768U;
  893. if (LangOpts.C99 || LangOpts.CPlusPlus11)
  894. LineLimit = 2147483648U;
  895. if (LineNo >= LineLimit)
  896. Diag(DigitTok, diag::ext_pp_line_too_big) << LineLimit;
  897. else if (LangOpts.CPlusPlus11 && LineNo >= 32768U)
  898. Diag(DigitTok, diag::warn_cxx98_compat_pp_line_too_big);
  899. int FilenameID = -1;
  900. Token StrTok;
  901. Lex(StrTok);
  902. // If the StrTok is "eod", then it wasn't present. Otherwise, it must be a
  903. // string followed by eod.
  904. if (StrTok.is(tok::eod))
  905. ; // ok
  906. else if (StrTok.isNot(tok::string_literal)) {
  907. Diag(StrTok, diag::err_pp_line_invalid_filename);
  908. return DiscardUntilEndOfDirective();
  909. } else if (StrTok.hasUDSuffix()) {
  910. Diag(StrTok, diag::err_invalid_string_udl);
  911. return DiscardUntilEndOfDirective();
  912. } else {
  913. // Parse and validate the string, converting it into a unique ID.
  914. StringLiteralParser Literal(StrTok, *this);
  915. assert(Literal.isAscii() && "Didn't allow wide strings in");
  916. if (Literal.hadError)
  917. return DiscardUntilEndOfDirective();
  918. if (Literal.Pascal) {
  919. Diag(StrTok, diag::err_pp_linemarker_invalid_filename);
  920. return DiscardUntilEndOfDirective();
  921. }
  922. FilenameID = SourceMgr.getLineTableFilenameID(Literal.GetString());
  923. // Verify that there is nothing after the string, other than EOD. Because
  924. // of C99 6.10.4p5, macros that expand to empty tokens are ok.
  925. CheckEndOfDirective("line", true);
  926. }
  927. // HLSL Change Begin - ignore line directives.
  928. if (PPOpts->IgnoreLineDirectives)
  929. return;
  930. // HLSL Change End
  931. SourceMgr.AddLineNote(DigitTok.getLocation(), LineNo, FilenameID);
  932. if (Callbacks)
  933. Callbacks->FileChanged(CurPPLexer->getSourceLocation(),
  934. PPCallbacks::RenameFile,
  935. SrcMgr::C_User);
  936. }
  937. /// ReadLineMarkerFlags - Parse and validate any flags at the end of a GNU line
  938. /// marker directive.
  939. static bool ReadLineMarkerFlags(bool &IsFileEntry, bool &IsFileExit,
  940. bool &IsSystemHeader, bool &IsExternCHeader,
  941. Preprocessor &PP) {
  942. unsigned FlagVal;
  943. Token FlagTok;
  944. PP.Lex(FlagTok);
  945. if (FlagTok.is(tok::eod)) return false;
  946. if (GetLineValue(FlagTok, FlagVal, diag::err_pp_linemarker_invalid_flag, PP))
  947. return true;
  948. if (FlagVal == 1) {
  949. IsFileEntry = true;
  950. PP.Lex(FlagTok);
  951. if (FlagTok.is(tok::eod)) return false;
  952. if (GetLineValue(FlagTok, FlagVal, diag::err_pp_linemarker_invalid_flag,PP))
  953. return true;
  954. } else if (FlagVal == 2) {
  955. IsFileExit = true;
  956. SourceManager &SM = PP.getSourceManager();
  957. // If we are leaving the current presumed file, check to make sure the
  958. // presumed include stack isn't empty!
  959. FileID CurFileID =
  960. SM.getDecomposedExpansionLoc(FlagTok.getLocation()).first;
  961. PresumedLoc PLoc = SM.getPresumedLoc(FlagTok.getLocation());
  962. if (PLoc.isInvalid())
  963. return true;
  964. // If there is no include loc (main file) or if the include loc is in a
  965. // different physical file, then we aren't in a "1" line marker flag region.
  966. SourceLocation IncLoc = PLoc.getIncludeLoc();
  967. if (IncLoc.isInvalid() ||
  968. SM.getDecomposedExpansionLoc(IncLoc).first != CurFileID) {
  969. PP.Diag(FlagTok, diag::err_pp_linemarker_invalid_pop);
  970. PP.DiscardUntilEndOfDirective();
  971. return true;
  972. }
  973. PP.Lex(FlagTok);
  974. if (FlagTok.is(tok::eod)) return false;
  975. if (GetLineValue(FlagTok, FlagVal, diag::err_pp_linemarker_invalid_flag,PP))
  976. return true;
  977. }
  978. // We must have 3 if there are still flags.
  979. if (FlagVal != 3) {
  980. PP.Diag(FlagTok, diag::err_pp_linemarker_invalid_flag);
  981. PP.DiscardUntilEndOfDirective();
  982. return true;
  983. }
  984. IsSystemHeader = true;
  985. PP.Lex(FlagTok);
  986. if (FlagTok.is(tok::eod)) return false;
  987. if (GetLineValue(FlagTok, FlagVal, diag::err_pp_linemarker_invalid_flag, PP))
  988. return true;
  989. // We must have 4 if there is yet another flag.
  990. if (FlagVal != 4) {
  991. PP.Diag(FlagTok, diag::err_pp_linemarker_invalid_flag);
  992. PP.DiscardUntilEndOfDirective();
  993. return true;
  994. }
  995. IsExternCHeader = true;
  996. PP.Lex(FlagTok);
  997. if (FlagTok.is(tok::eod)) return false;
  998. // There are no more valid flags here.
  999. PP.Diag(FlagTok, diag::err_pp_linemarker_invalid_flag);
  1000. PP.DiscardUntilEndOfDirective();
  1001. return true;
  1002. }
  1003. /// HandleDigitDirective - Handle a GNU line marker directive, whose syntax is
  1004. /// one of the following forms:
  1005. ///
  1006. /// # 42
  1007. /// # 42 "file" ('1' | '2')?
  1008. /// # 42 "file" ('1' | '2')? '3' '4'?
  1009. ///
  1010. void Preprocessor::HandleDigitDirective(Token &DigitTok) {
  1011. // Validate the number and convert it to an unsigned. GNU does not have a
  1012. // line # limit other than it fit in 32-bits.
  1013. unsigned LineNo;
  1014. if (GetLineValue(DigitTok, LineNo, diag::err_pp_linemarker_requires_integer,
  1015. *this, true))
  1016. return;
  1017. Token StrTok;
  1018. Lex(StrTok);
  1019. bool IsFileEntry = false, IsFileExit = false;
  1020. bool IsSystemHeader = false, IsExternCHeader = false;
  1021. int FilenameID = -1;
  1022. // If the StrTok is "eod", then it wasn't present. Otherwise, it must be a
  1023. // string followed by eod.
  1024. if (StrTok.is(tok::eod))
  1025. ; // ok
  1026. else if (StrTok.isNot(tok::string_literal)) {
  1027. Diag(StrTok, diag::err_pp_linemarker_invalid_filename);
  1028. return DiscardUntilEndOfDirective();
  1029. } else if (StrTok.hasUDSuffix()) {
  1030. Diag(StrTok, diag::err_invalid_string_udl);
  1031. return DiscardUntilEndOfDirective();
  1032. } else {
  1033. // Parse and validate the string, converting it into a unique ID.
  1034. StringLiteralParser Literal(StrTok, *this);
  1035. assert(Literal.isAscii() && "Didn't allow wide strings in");
  1036. if (Literal.hadError)
  1037. return DiscardUntilEndOfDirective();
  1038. if (Literal.Pascal) {
  1039. Diag(StrTok, diag::err_pp_linemarker_invalid_filename);
  1040. return DiscardUntilEndOfDirective();
  1041. }
  1042. FilenameID = SourceMgr.getLineTableFilenameID(Literal.GetString());
  1043. // If a filename was present, read any flags that are present.
  1044. if (ReadLineMarkerFlags(IsFileEntry, IsFileExit,
  1045. IsSystemHeader, IsExternCHeader, *this))
  1046. return;
  1047. }
  1048. // Create a line note with this information.
  1049. SourceMgr.AddLineNote(DigitTok.getLocation(), LineNo, FilenameID,
  1050. IsFileEntry, IsFileExit,
  1051. IsSystemHeader, IsExternCHeader);
  1052. // If the preprocessor has callbacks installed, notify them of the #line
  1053. // change. This is used so that the line marker comes out in -E mode for
  1054. // example.
  1055. if (Callbacks) {
  1056. PPCallbacks::FileChangeReason Reason = PPCallbacks::RenameFile;
  1057. if (IsFileEntry)
  1058. Reason = PPCallbacks::EnterFile;
  1059. else if (IsFileExit)
  1060. Reason = PPCallbacks::ExitFile;
  1061. SrcMgr::CharacteristicKind FileKind = SrcMgr::C_User;
  1062. if (IsExternCHeader)
  1063. FileKind = SrcMgr::C_ExternCSystem;
  1064. else if (IsSystemHeader)
  1065. FileKind = SrcMgr::C_System;
  1066. Callbacks->FileChanged(CurPPLexer->getSourceLocation(), Reason, FileKind);
  1067. }
  1068. }
  1069. /// HandleUserDiagnosticDirective - Handle a #warning or #error directive.
  1070. ///
  1071. void Preprocessor::HandleUserDiagnosticDirective(Token &Tok,
  1072. bool isWarning) {
  1073. // PTH doesn't emit #warning or #error directives.
  1074. if (CurPTHLexer)
  1075. return CurPTHLexer->DiscardToEndOfLine();
  1076. // Read the rest of the line raw. We do this because we don't want macros
  1077. // to be expanded and we don't require that the tokens be valid preprocessing
  1078. // tokens. For example, this is allowed: "#warning ` 'foo". GCC does
  1079. // collapse multiple consequtive white space between tokens, but this isn't
  1080. // specified by the standard.
  1081. SmallString<128> Message;
  1082. CurLexer->ReadToEndOfLine(&Message);
  1083. // Find the first non-whitespace character, so that we can make the
  1084. // diagnostic more succinct.
  1085. StringRef Msg = StringRef(Message).ltrim(" ");
  1086. if (isWarning)
  1087. Diag(Tok, diag::pp_hash_warning) << Msg;
  1088. else
  1089. Diag(Tok, diag::err_pp_hash_error) << Msg;
  1090. }
  1091. /// HandleIdentSCCSDirective - Handle a #ident/#sccs directive.
  1092. ///
  1093. void Preprocessor::HandleIdentSCCSDirective(Token &Tok) {
  1094. // Yes, this directive is an extension.
  1095. Diag(Tok, diag::ext_pp_ident_directive);
  1096. // Read the string argument.
  1097. Token StrTok;
  1098. Lex(StrTok);
  1099. // If the token kind isn't a string, it's a malformed directive.
  1100. if (StrTok.isNot(tok::string_literal) &&
  1101. StrTok.isNot(tok::wide_string_literal)) {
  1102. Diag(StrTok, diag::err_pp_malformed_ident);
  1103. if (StrTok.isNot(tok::eod))
  1104. DiscardUntilEndOfDirective();
  1105. return;
  1106. }
  1107. if (StrTok.hasUDSuffix()) {
  1108. Diag(StrTok, diag::err_invalid_string_udl);
  1109. return DiscardUntilEndOfDirective();
  1110. }
  1111. // Verify that there is nothing after the string, other than EOD.
  1112. CheckEndOfDirective("ident");
  1113. if (Callbacks) {
  1114. bool Invalid = false;
  1115. std::string Str = getSpelling(StrTok, &Invalid);
  1116. if (!Invalid)
  1117. Callbacks->Ident(Tok.getLocation(), Str);
  1118. }
  1119. }
  1120. /// \brief Handle a #public directive.
  1121. void Preprocessor::HandleMacroPublicDirective(Token &Tok) {
  1122. Token MacroNameTok;
  1123. ReadMacroName(MacroNameTok, MU_Undef);
  1124. // Error reading macro name? If so, diagnostic already issued.
  1125. if (MacroNameTok.is(tok::eod))
  1126. return;
  1127. // Check to see if this is the last token on the #__public_macro line.
  1128. CheckEndOfDirective("__public_macro");
  1129. IdentifierInfo *II = MacroNameTok.getIdentifierInfo();
  1130. // Okay, we finally have a valid identifier to undef.
  1131. MacroDirective *MD = getLocalMacroDirective(II);
  1132. // If the macro is not defined, this is an error.
  1133. if (!MD) {
  1134. Diag(MacroNameTok, diag::err_pp_visibility_non_macro) << II;
  1135. return;
  1136. }
  1137. // Note that this macro has now been exported.
  1138. appendMacroDirective(II, AllocateVisibilityMacroDirective(
  1139. MacroNameTok.getLocation(), /*IsPublic=*/true));
  1140. }
  1141. /// \brief Handle a #private directive.
  1142. void Preprocessor::HandleMacroPrivateDirective(Token &Tok) {
  1143. Token MacroNameTok;
  1144. ReadMacroName(MacroNameTok, MU_Undef);
  1145. // Error reading macro name? If so, diagnostic already issued.
  1146. if (MacroNameTok.is(tok::eod))
  1147. return;
  1148. // Check to see if this is the last token on the #__private_macro line.
  1149. CheckEndOfDirective("__private_macro");
  1150. IdentifierInfo *II = MacroNameTok.getIdentifierInfo();
  1151. // Okay, we finally have a valid identifier to undef.
  1152. MacroDirective *MD = getLocalMacroDirective(II);
  1153. // If the macro is not defined, this is an error.
  1154. if (!MD) {
  1155. Diag(MacroNameTok, diag::err_pp_visibility_non_macro) << II;
  1156. return;
  1157. }
  1158. // Note that this macro has now been marked private.
  1159. appendMacroDirective(II, AllocateVisibilityMacroDirective(
  1160. MacroNameTok.getLocation(), /*IsPublic=*/false));
  1161. }
  1162. //===----------------------------------------------------------------------===//
  1163. // Preprocessor Include Directive Handling.
  1164. //===----------------------------------------------------------------------===//
  1165. /// GetIncludeFilenameSpelling - Turn the specified lexer token into a fully
  1166. /// checked and spelled filename, e.g. as an operand of \#include. This returns
  1167. /// true if the input filename was in <>'s or false if it were in ""'s. The
  1168. /// caller is expected to provide a buffer that is large enough to hold the
  1169. /// spelling of the filename, but is also expected to handle the case when
  1170. /// this method decides to use a different buffer.
  1171. bool Preprocessor::GetIncludeFilenameSpelling(SourceLocation Loc,
  1172. StringRef &Buffer) {
  1173. // Get the text form of the filename.
  1174. assert(!Buffer.empty() && "Can't have tokens with empty spellings!");
  1175. // Make sure the filename is <x> or "x".
  1176. bool isAngled;
  1177. if (Buffer[0] == '<') {
  1178. if (Buffer.back() != '>') {
  1179. Diag(Loc, diag::err_pp_expects_filename);
  1180. Buffer = StringRef();
  1181. return true;
  1182. }
  1183. isAngled = true;
  1184. } else if (Buffer[0] == '"') {
  1185. if (Buffer.back() != '"') {
  1186. Diag(Loc, diag::err_pp_expects_filename);
  1187. Buffer = StringRef();
  1188. return true;
  1189. }
  1190. isAngled = false;
  1191. } else {
  1192. Diag(Loc, diag::err_pp_expects_filename);
  1193. Buffer = StringRef();
  1194. return true;
  1195. }
  1196. // Diagnose #include "" as invalid.
  1197. if (Buffer.size() <= 2) {
  1198. Diag(Loc, diag::err_pp_empty_filename);
  1199. Buffer = StringRef();
  1200. return true;
  1201. }
  1202. // Skip the brackets.
  1203. Buffer = Buffer.substr(1, Buffer.size()-2);
  1204. return isAngled;
  1205. }
  1206. // \brief Handle cases where the \#include name is expanded from a macro
  1207. // as multiple tokens, which need to be glued together.
  1208. //
  1209. // This occurs for code like:
  1210. // \code
  1211. // \#define FOO <a/b.h>
  1212. // \#include FOO
  1213. // \endcode
  1214. // because in this case, "<a/b.h>" is returned as 7 tokens, not one.
  1215. //
  1216. // This code concatenates and consumes tokens up to the '>' token. It returns
  1217. // false if the > was found, otherwise it returns true if it finds and consumes
  1218. // the EOD marker.
  1219. bool Preprocessor::ConcatenateIncludeName(SmallString<128> &FilenameBuffer,
  1220. SourceLocation &End) {
  1221. Token CurTok;
  1222. Lex(CurTok);
  1223. while (CurTok.isNot(tok::eod)) {
  1224. End = CurTok.getLocation();
  1225. // FIXME: Provide code completion for #includes.
  1226. if (CurTok.is(tok::code_completion)) {
  1227. setCodeCompletionReached();
  1228. Lex(CurTok);
  1229. continue;
  1230. }
  1231. // Append the spelling of this token to the buffer. If there was a space
  1232. // before it, add it now.
  1233. if (CurTok.hasLeadingSpace())
  1234. FilenameBuffer.push_back(' ');
  1235. // Get the spelling of the token, directly into FilenameBuffer if possible.
  1236. unsigned PreAppendSize = FilenameBuffer.size();
  1237. FilenameBuffer.resize(PreAppendSize+CurTok.getLength());
  1238. const char *BufPtr = &FilenameBuffer[PreAppendSize];
  1239. unsigned ActualLen = getSpelling(CurTok, BufPtr);
  1240. // If the token was spelled somewhere else, copy it into FilenameBuffer.
  1241. if (BufPtr != &FilenameBuffer[PreAppendSize])
  1242. memcpy(&FilenameBuffer[PreAppendSize], BufPtr, ActualLen);
  1243. // Resize FilenameBuffer to the correct size.
  1244. if (CurTok.getLength() != ActualLen)
  1245. FilenameBuffer.resize(PreAppendSize+ActualLen);
  1246. // If we found the '>' marker, return success.
  1247. if (CurTok.is(tok::greater))
  1248. return false;
  1249. Lex(CurTok);
  1250. }
  1251. // If we hit the eod marker, emit an error and return true so that the caller
  1252. // knows the EOD has been read.
  1253. Diag(CurTok.getLocation(), diag::err_pp_expects_filename);
  1254. return true;
  1255. }
  1256. /// \brief Push a token onto the token stream containing an annotation.
  1257. static void EnterAnnotationToken(Preprocessor &PP,
  1258. SourceLocation Begin, SourceLocation End,
  1259. tok::TokenKind Kind, void *AnnotationVal) {
  1260. // FIXME: Produce this as the current token directly, rather than
  1261. // allocating a new token for it.
  1262. Token *Tok = new Token[1];
  1263. Tok[0].startToken();
  1264. Tok[0].setKind(Kind);
  1265. Tok[0].setLocation(Begin);
  1266. Tok[0].setAnnotationEndLoc(End);
  1267. Tok[0].setAnnotationValue(AnnotationVal);
  1268. PP.EnterTokenStream(Tok, 1, true, true);
  1269. }
  1270. /// \brief Produce a diagnostic informing the user that a #include or similar
  1271. /// was implicitly treated as a module import.
  1272. static void diagnoseAutoModuleImport(
  1273. Preprocessor &PP, SourceLocation HashLoc, Token &IncludeTok,
  1274. ArrayRef<std::pair<IdentifierInfo *, SourceLocation>> Path,
  1275. SourceLocation PathEnd) {
  1276. assert(PP.getLangOpts().ObjC2 && "no import syntax available");
  1277. SmallString<128> PathString;
  1278. for (unsigned I = 0, N = Path.size(); I != N; ++I) {
  1279. if (I)
  1280. PathString += '.';
  1281. PathString += Path[I].first->getName();
  1282. }
  1283. int IncludeKind = 0;
  1284. switch (IncludeTok.getIdentifierInfo()->getPPKeywordID()) {
  1285. case tok::pp_include:
  1286. IncludeKind = 0;
  1287. break;
  1288. case tok::pp_import:
  1289. IncludeKind = 1;
  1290. break;
  1291. case tok::pp_include_next:
  1292. IncludeKind = 2;
  1293. break;
  1294. case tok::pp___include_macros:
  1295. IncludeKind = 3;
  1296. break;
  1297. default:
  1298. llvm_unreachable("unknown include directive kind");
  1299. }
  1300. CharSourceRange ReplaceRange(SourceRange(HashLoc, PathEnd),
  1301. /*IsTokenRange=*/false);
  1302. PP.Diag(HashLoc, diag::warn_auto_module_import)
  1303. << IncludeKind << PathString
  1304. << FixItHint::CreateReplacement(ReplaceRange,
  1305. ("@import " + PathString + ";").str());
  1306. }
  1307. /// HandleIncludeDirective - The "\#include" tokens have just been read, read
  1308. /// the file to be included from the lexer, then include it! This is a common
  1309. /// routine with functionality shared between \#include, \#include_next and
  1310. /// \#import. LookupFrom is set when this is a \#include_next directive, it
  1311. /// specifies the file to start searching from.
  1312. void Preprocessor::HandleIncludeDirective(SourceLocation HashLoc,
  1313. Token &IncludeTok,
  1314. const DirectoryLookup *LookupFrom,
  1315. const FileEntry *LookupFromFile,
  1316. bool isImport) {
  1317. Token FilenameTok;
  1318. CurPPLexer->LexIncludeFilename(FilenameTok);
  1319. // Reserve a buffer to get the spelling.
  1320. SmallString<128> FilenameBuffer;
  1321. StringRef Filename;
  1322. SourceLocation End;
  1323. SourceLocation CharEnd; // the end of this directive, in characters
  1324. switch (FilenameTok.getKind()) {
  1325. case tok::eod:
  1326. // If the token kind is EOD, the error has already been diagnosed.
  1327. return;
  1328. case tok::angle_string_literal:
  1329. case tok::string_literal:
  1330. Filename = getSpelling(FilenameTok, FilenameBuffer);
  1331. End = FilenameTok.getLocation();
  1332. CharEnd = End.getLocWithOffset(FilenameTok.getLength());
  1333. break;
  1334. case tok::less:
  1335. // This could be a <foo/bar.h> file coming from a macro expansion. In this
  1336. // case, glue the tokens together into FilenameBuffer and interpret those.
  1337. FilenameBuffer.push_back('<');
  1338. if (ConcatenateIncludeName(FilenameBuffer, End))
  1339. return; // Found <eod> but no ">"? Diagnostic already emitted.
  1340. Filename = FilenameBuffer;
  1341. CharEnd = End.getLocWithOffset(1);
  1342. break;
  1343. default:
  1344. Diag(FilenameTok.getLocation(), diag::err_pp_expects_filename);
  1345. DiscardUntilEndOfDirective();
  1346. return;
  1347. }
  1348. CharSourceRange FilenameRange
  1349. = CharSourceRange::getCharRange(FilenameTok.getLocation(), CharEnd);
  1350. StringRef OriginalFilename = Filename;
  1351. bool isAngled =
  1352. GetIncludeFilenameSpelling(FilenameTok.getLocation(), Filename);
  1353. // If GetIncludeFilenameSpelling set the start ptr to null, there was an
  1354. // error.
  1355. if (Filename.empty()) {
  1356. DiscardUntilEndOfDirective();
  1357. return;
  1358. }
  1359. // Verify that there is nothing after the filename, other than EOD. Note that
  1360. // we allow macros that expand to nothing after the filename, because this
  1361. // falls into the category of "#include pp-tokens new-line" specified in
  1362. // C99 6.10.2p4.
  1363. CheckEndOfDirective(IncludeTok.getIdentifierInfo()->getNameStart(), true);
  1364. // Check that we don't have infinite #include recursion.
  1365. if (IncludeMacroStack.size() == MaxAllowedIncludeStackDepth-1) {
  1366. Diag(FilenameTok, diag::err_pp_include_too_deep);
  1367. return;
  1368. }
  1369. // Complain about attempts to #include files in an audit pragma.
  1370. if (PragmaARCCFCodeAuditedLoc.isValid()) {
  1371. Diag(HashLoc, diag::err_pp_include_in_arc_cf_code_audited);
  1372. Diag(PragmaARCCFCodeAuditedLoc, diag::note_pragma_entered_here);
  1373. // Immediately leave the pragma.
  1374. PragmaARCCFCodeAuditedLoc = SourceLocation();
  1375. }
  1376. // Complain about attempts to #include files in an assume-nonnull pragma.
  1377. if (PragmaAssumeNonNullLoc.isValid()) {
  1378. Diag(HashLoc, diag::err_pp_include_in_assume_nonnull);
  1379. Diag(PragmaAssumeNonNullLoc, diag::note_pragma_entered_here);
  1380. // Immediately leave the pragma.
  1381. PragmaAssumeNonNullLoc = SourceLocation();
  1382. }
  1383. if (HeaderInfo.HasIncludeAliasMap()) {
  1384. // Map the filename with the brackets still attached. If the name doesn't
  1385. // map to anything, fall back on the filename we've already gotten the
  1386. // spelling for.
  1387. StringRef NewName = HeaderInfo.MapHeaderToIncludeAlias(OriginalFilename);
  1388. if (!NewName.empty())
  1389. Filename = NewName;
  1390. }
  1391. // Search include directories.
  1392. const DirectoryLookup *CurDir;
  1393. SmallString<1024> SearchPath;
  1394. SmallString<1024> RelativePath;
  1395. // We get the raw path only if we have 'Callbacks' to which we later pass
  1396. // the path.
  1397. ModuleMap::KnownHeader SuggestedModule;
  1398. SourceLocation FilenameLoc = FilenameTok.getLocation();
  1399. SmallString<128> NormalizedPath;
  1400. if (LangOpts.MSVCCompat || LangOpts.HLSL) { // HLSL Change: use MSVC compat behavior
  1401. NormalizedPath = Filename.str();
  1402. #ifndef LLVM_ON_WIN32
  1403. llvm::sys::path::native(NormalizedPath);
  1404. #endif
  1405. }
  1406. const FileEntry *File = LookupFile(
  1407. FilenameLoc, (LangOpts.MSVCCompat || LangOpts.HLSL) ? NormalizedPath.c_str() : Filename, // HLSL Change: use MSVC compat behavior
  1408. isAngled, LookupFrom, LookupFromFile, CurDir,
  1409. Callbacks ? &SearchPath : nullptr, Callbacks ? &RelativePath : nullptr,
  1410. &SuggestedModule);
  1411. if (!File) {
  1412. if (Callbacks) {
  1413. // Give the clients a chance to recover.
  1414. SmallString<128> RecoveryPath;
  1415. if (Callbacks->FileNotFound(Filename, RecoveryPath)) {
  1416. if (const DirectoryEntry *DE = FileMgr.getDirectory(RecoveryPath)) {
  1417. // Add the recovery path to the list of search paths.
  1418. DirectoryLookup DL(DE, SrcMgr::C_User, false);
  1419. HeaderInfo.AddSearchPath(DL, isAngled);
  1420. // Try the lookup again, skipping the cache.
  1421. File = LookupFile(
  1422. FilenameLoc,
  1423. (LangOpts.MSVCCompat || LangOpts.HLSL) ? NormalizedPath.c_str() : Filename, isAngled, // HLSL Change: use MSVC compat behavior
  1424. LookupFrom, LookupFromFile, CurDir, nullptr, nullptr,
  1425. &SuggestedModule, /*SkipCache*/ true);
  1426. }
  1427. }
  1428. }
  1429. if (!SuppressIncludeNotFoundError) {
  1430. // If the file could not be located and it was included via angle
  1431. // brackets, we can attempt a lookup as though it were a quoted path to
  1432. // provide the user with a possible fixit.
  1433. if (isAngled) {
  1434. File = LookupFile(
  1435. FilenameLoc,
  1436. (LangOpts.MSVCCompat || LangOpts.HLSL) ? NormalizedPath.c_str() : Filename, false, // HLSL Change: use MSVC compat behavior
  1437. LookupFrom, LookupFromFile, CurDir,
  1438. Callbacks ? &SearchPath : nullptr,
  1439. Callbacks ? &RelativePath : nullptr,
  1440. &SuggestedModule);
  1441. if (File) {
  1442. SourceRange Range(FilenameTok.getLocation(), CharEnd);
  1443. Diag(FilenameTok, diag::err_pp_file_not_found_not_fatal) <<
  1444. Filename <<
  1445. FixItHint::CreateReplacement(Range, "\"" + Filename.str() + "\"");
  1446. }
  1447. }
  1448. // If the file is still not found, just go with the vanilla diagnostic
  1449. if (!File)
  1450. Diag(FilenameTok, diag::err_pp_file_not_found) << Filename;
  1451. }
  1452. }
  1453. // Should we enter the source file? Set to false if either the source file is
  1454. // known to have no effect beyond its effect on module visibility -- that is,
  1455. // if it's got an include guard that is already defined or is a modular header
  1456. // we've imported or already built.
  1457. bool ShouldEnter = true;
  1458. // Determine whether we should try to import the module for this #include, if
  1459. // there is one. Don't do so if precompiled module support is disabled or we
  1460. // are processing this module textually (because we're building the module).
  1461. if (File && SuggestedModule && getLangOpts().Modules &&
  1462. SuggestedModule.getModule()->getTopLevelModuleName() !=
  1463. getLangOpts().CurrentModule &&
  1464. SuggestedModule.getModule()->getTopLevelModuleName() !=
  1465. getLangOpts().ImplementationOfModule) {
  1466. // Compute the module access path corresponding to this module.
  1467. // FIXME: Should we have a second loadModule() overload to avoid this
  1468. // extra lookup step?
  1469. SmallVector<std::pair<IdentifierInfo *, SourceLocation>, 2> Path;
  1470. for (Module *Mod = SuggestedModule.getModule(); Mod; Mod = Mod->Parent)
  1471. Path.push_back(std::make_pair(getIdentifierInfo(Mod->Name),
  1472. FilenameTok.getLocation()));
  1473. std::reverse(Path.begin(), Path.end());
  1474. // Warn that we're replacing the include/import with a module import.
  1475. // We only do this in Objective-C, where we have a module-import syntax.
  1476. if (getLangOpts().ObjC2)
  1477. diagnoseAutoModuleImport(*this, HashLoc, IncludeTok, Path, CharEnd);
  1478. // Load the module to import its macros. We'll make the declarations
  1479. // visible when the parser gets here.
  1480. // FIXME: Pass SuggestedModule in here rather than converting it to a path
  1481. // and making the module loader convert it back again.
  1482. ModuleLoadResult Imported = TheModuleLoader.loadModule(
  1483. IncludeTok.getLocation(), Path, Module::Hidden,
  1484. /*IsIncludeDirective=*/true);
  1485. assert((Imported == nullptr || Imported == SuggestedModule.getModule()) &&
  1486. "the imported module is different than the suggested one");
  1487. if (Imported)
  1488. ShouldEnter = false;
  1489. else if (Imported.isMissingExpected()) {
  1490. // We failed to find a submodule that we assumed would exist (because it
  1491. // was in the directory of an umbrella header, for instance), but no
  1492. // actual module exists for it (because the umbrella header is
  1493. // incomplete). Treat this as a textual inclusion.
  1494. SuggestedModule = ModuleMap::KnownHeader();
  1495. } else {
  1496. // We hit an error processing the import. Bail out.
  1497. if (hadModuleLoaderFatalFailure()) {
  1498. // With a fatal failure in the module loader, we abort parsing.
  1499. Token &Result = IncludeTok;
  1500. if (CurLexer) {
  1501. Result.startToken();
  1502. CurLexer->FormTokenWithChars(Result, CurLexer->BufferEnd, tok::eof);
  1503. CurLexer->cutOffLexing();
  1504. } else {
  1505. assert(CurPTHLexer && "#include but no current lexer set!");
  1506. CurPTHLexer->getEOF(Result);
  1507. }
  1508. }
  1509. return;
  1510. }
  1511. }
  1512. if (Callbacks) {
  1513. // Notify the callback object that we've seen an inclusion directive.
  1514. Callbacks->InclusionDirective(
  1515. HashLoc, IncludeTok,
  1516. (LangOpts.MSVCCompat || LangOpts.HLSL) ? NormalizedPath.c_str() : Filename, isAngled, // HLSL Change: use MSVC compat behavior
  1517. FilenameRange, File, SearchPath, RelativePath,
  1518. ShouldEnter ? nullptr : SuggestedModule.getModule());
  1519. }
  1520. if (!File)
  1521. return;
  1522. // The #included file will be considered to be a system header if either it is
  1523. // in a system include directory, or if the #includer is a system include
  1524. // header.
  1525. SrcMgr::CharacteristicKind FileCharacter =
  1526. std::max(HeaderInfo.getFileDirFlavor(File),
  1527. SourceMgr.getFileCharacteristic(FilenameTok.getLocation()));
  1528. // FIXME: If we have a suggested module, and we've already visited this file,
  1529. // don't bother entering it again. We know it has no further effect.
  1530. // Ask HeaderInfo if we should enter this #include file. If not, #including
  1531. // this file will have no effect.
  1532. if (ShouldEnter &&
  1533. !HeaderInfo.ShouldEnterIncludeFile(*this, File, isImport,
  1534. SuggestedModule.getModule())) {
  1535. ShouldEnter = false;
  1536. if (Callbacks)
  1537. Callbacks->FileSkipped(*File, FilenameTok, FileCharacter);
  1538. }
  1539. // If we don't need to enter the file, stop now.
  1540. if (!ShouldEnter) {
  1541. // If this is a module import, make it visible if needed.
  1542. if (auto *M = SuggestedModule.getModule()) {
  1543. makeModuleVisible(M, HashLoc);
  1544. if (IncludeTok.getIdentifierInfo()->getPPKeywordID() !=
  1545. tok::pp___include_macros)
  1546. EnterAnnotationToken(*this, HashLoc, End, tok::annot_module_include, M);
  1547. }
  1548. return;
  1549. }
  1550. // Look up the file, create a File ID for it.
  1551. SourceLocation IncludePos = End;
  1552. // If the filename string was the result of macro expansions, set the include
  1553. // position on the file where it will be included and after the expansions.
  1554. if (IncludePos.isMacroID())
  1555. IncludePos = SourceMgr.getExpansionRange(IncludePos).second;
  1556. FileID FID = SourceMgr.createFileID(File, IncludePos, FileCharacter);
  1557. assert(!FID.isInvalid() && "Expected valid file ID");
  1558. // If all is good, enter the new file!
  1559. if (EnterSourceFile(FID, CurDir, FilenameTok.getLocation()))
  1560. return;
  1561. // Determine if we're switching to building a new submodule, and which one.
  1562. if (auto *M = SuggestedModule.getModule()) {
  1563. assert(!CurSubmodule && "should not have marked this as a module yet");
  1564. CurSubmodule = M;
  1565. // Let the macro handling code know that any future macros are within
  1566. // the new submodule.
  1567. EnterSubmodule(M, HashLoc);
  1568. // Let the parser know that any future declarations are within the new
  1569. // submodule.
  1570. // FIXME: There's no point doing this if we're handling a #__include_macros
  1571. // directive.
  1572. EnterAnnotationToken(*this, HashLoc, End, tok::annot_module_begin, M);
  1573. }
  1574. }
  1575. /// HandleIncludeNextDirective - Implements \#include_next.
  1576. ///
  1577. void Preprocessor::HandleIncludeNextDirective(SourceLocation HashLoc,
  1578. Token &IncludeNextTok) {
  1579. Diag(IncludeNextTok, diag::ext_pp_include_next_directive);
  1580. // #include_next is like #include, except that we start searching after
  1581. // the current found directory. If we can't do this, issue a
  1582. // diagnostic.
  1583. const DirectoryLookup *Lookup = CurDirLookup;
  1584. const FileEntry *LookupFromFile = nullptr;
  1585. if (isInPrimaryFile()) {
  1586. Lookup = nullptr;
  1587. Diag(IncludeNextTok, diag::pp_include_next_in_primary);
  1588. } else if (CurSubmodule) {
  1589. // Start looking up in the directory *after* the one in which the current
  1590. // file would be found, if any.
  1591. assert(CurPPLexer && "#include_next directive in macro?");
  1592. LookupFromFile = CurPPLexer->getFileEntry();
  1593. Lookup = nullptr;
  1594. } else if (!Lookup) {
  1595. Diag(IncludeNextTok, diag::pp_include_next_absolute_path);
  1596. } else {
  1597. // Start looking up in the next directory.
  1598. ++Lookup;
  1599. }
  1600. return HandleIncludeDirective(HashLoc, IncludeNextTok, Lookup,
  1601. LookupFromFile);
  1602. }
  1603. /// HandleMicrosoftImportDirective - Implements \#import for Microsoft Mode
  1604. void Preprocessor::HandleMicrosoftImportDirective(Token &Tok) {
  1605. // The Microsoft #import directive takes a type library and generates header
  1606. // files from it, and includes those. This is beyond the scope of what clang
  1607. // does, so we ignore it and error out. However, #import can optionally have
  1608. // trailing attributes that span multiple lines. We're going to eat those
  1609. // so we can continue processing from there.
  1610. Diag(Tok, diag::err_pp_import_directive_ms );
  1611. // Read tokens until we get to the end of the directive. Note that the
  1612. // directive can be split over multiple lines using the backslash character.
  1613. DiscardUntilEndOfDirective();
  1614. }
  1615. /// HandleImportDirective - Implements \#import.
  1616. ///
  1617. void Preprocessor::HandleImportDirective(SourceLocation HashLoc,
  1618. Token &ImportTok) {
  1619. if (!LangOpts.ObjC1) { // #import is standard for ObjC.
  1620. if (LangOpts.MSVCCompat)
  1621. return HandleMicrosoftImportDirective(ImportTok);
  1622. Diag(ImportTok, diag::ext_pp_import_directive);
  1623. }
  1624. return HandleIncludeDirective(HashLoc, ImportTok, nullptr, nullptr, true);
  1625. }
  1626. /// HandleIncludeMacrosDirective - The -imacros command line option turns into a
  1627. /// pseudo directive in the predefines buffer. This handles it by sucking all
  1628. /// tokens through the preprocessor and discarding them (only keeping the side
  1629. /// effects on the preprocessor).
  1630. void Preprocessor::HandleIncludeMacrosDirective(SourceLocation HashLoc,
  1631. Token &IncludeMacrosTok) {
  1632. // This directive should only occur in the predefines buffer. If not, emit an
  1633. // error and reject it.
  1634. SourceLocation Loc = IncludeMacrosTok.getLocation();
  1635. if (strcmp(SourceMgr.getBufferName(Loc), "<built-in>") != 0) {
  1636. Diag(IncludeMacrosTok.getLocation(),
  1637. diag::pp_include_macros_out_of_predefines);
  1638. DiscardUntilEndOfDirective();
  1639. return;
  1640. }
  1641. // Treat this as a normal #include for checking purposes. If this is
  1642. // successful, it will push a new lexer onto the include stack.
  1643. HandleIncludeDirective(HashLoc, IncludeMacrosTok);
  1644. Token TmpTok;
  1645. do {
  1646. Lex(TmpTok);
  1647. assert(TmpTok.isNot(tok::eof) && "Didn't find end of -imacros!");
  1648. } while (TmpTok.isNot(tok::hashhash));
  1649. }
  1650. //===----------------------------------------------------------------------===//
  1651. // Preprocessor Macro Directive Handling.
  1652. //===----------------------------------------------------------------------===//
  1653. /// ReadMacroDefinitionArgList - The ( starting an argument list of a macro
  1654. /// definition has just been read. Lex the rest of the arguments and the
  1655. /// closing ), updating MI with what we learn. Return true if an error occurs
  1656. /// parsing the arg list.
  1657. bool Preprocessor::ReadMacroDefinitionArgList(MacroInfo *MI, Token &Tok) {
  1658. SmallVector<IdentifierInfo*, 32> Arguments;
  1659. while (1) {
  1660. LexUnexpandedToken(Tok);
  1661. switch (Tok.getKind()) {
  1662. case tok::r_paren:
  1663. // Found the end of the argument list.
  1664. if (Arguments.empty()) // #define FOO()
  1665. return false;
  1666. // Otherwise we have #define FOO(A,)
  1667. Diag(Tok, diag::err_pp_expected_ident_in_arg_list);
  1668. return true;
  1669. case tok::ellipsis: // #define X(... -> C99 varargs
  1670. if (!LangOpts.C99)
  1671. Diag(Tok, LangOpts.CPlusPlus11 ?
  1672. diag::warn_cxx98_compat_variadic_macro :
  1673. diag::ext_variadic_macro);
  1674. // OpenCL v1.2 s6.9.e: variadic macros are not supported.
  1675. if (LangOpts.OpenCL) {
  1676. Diag(Tok, diag::err_pp_opencl_variadic_macros);
  1677. return true;
  1678. }
  1679. // Lex the token after the identifier.
  1680. LexUnexpandedToken(Tok);
  1681. if (Tok.isNot(tok::r_paren)) {
  1682. Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
  1683. return true;
  1684. }
  1685. // Add the __VA_ARGS__ identifier as an argument.
  1686. Arguments.push_back(Ident__VA_ARGS__);
  1687. MI->setIsC99Varargs();
  1688. MI->setArgumentList(&Arguments[0], Arguments.size(), BP);
  1689. return false;
  1690. case tok::eod: // #define X(
  1691. Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
  1692. return true;
  1693. default:
  1694. // Handle keywords and identifiers here to accept things like
  1695. // #define Foo(for) for.
  1696. IdentifierInfo *II = Tok.getIdentifierInfo();
  1697. if (!II) {
  1698. // #define X(1
  1699. Diag(Tok, diag::err_pp_invalid_tok_in_arg_list);
  1700. return true;
  1701. }
  1702. // If this is already used as an argument, it is used multiple times (e.g.
  1703. // #define X(A,A.
  1704. if (std::find(Arguments.begin(), Arguments.end(), II) !=
  1705. Arguments.end()) { // C99 6.10.3p6
  1706. Diag(Tok, diag::err_pp_duplicate_name_in_arg_list) << II;
  1707. return true;
  1708. }
  1709. // Add the argument to the macro info.
  1710. Arguments.push_back(II);
  1711. // Lex the token after the identifier.
  1712. LexUnexpandedToken(Tok);
  1713. switch (Tok.getKind()) {
  1714. default: // #define X(A B
  1715. Diag(Tok, diag::err_pp_expected_comma_in_arg_list);
  1716. return true;
  1717. case tok::r_paren: // #define X(A)
  1718. MI->setArgumentList(&Arguments[0], Arguments.size(), BP);
  1719. return false;
  1720. case tok::comma: // #define X(A,
  1721. break;
  1722. case tok::ellipsis: // #define X(A... -> GCC extension
  1723. // Diagnose extension.
  1724. Diag(Tok, diag::ext_named_variadic_macro);
  1725. // Lex the token after the identifier.
  1726. LexUnexpandedToken(Tok);
  1727. if (Tok.isNot(tok::r_paren)) {
  1728. Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
  1729. return true;
  1730. }
  1731. MI->setIsGNUVarargs();
  1732. MI->setArgumentList(&Arguments[0], Arguments.size(), BP);
  1733. return false;
  1734. }
  1735. }
  1736. }
  1737. }
  1738. static bool isConfigurationPattern(Token &MacroName, MacroInfo *MI,
  1739. const LangOptions &LOptions) {
  1740. if (MI->getNumTokens() == 1) {
  1741. const Token &Value = MI->getReplacementToken(0);
  1742. // Macro that is identity, like '#define inline inline' is a valid pattern.
  1743. if (MacroName.getKind() == Value.getKind())
  1744. return true;
  1745. // Macro that maps a keyword to the same keyword decorated with leading/
  1746. // trailing underscores is a valid pattern:
  1747. // #define inline __inline
  1748. // #define inline __inline__
  1749. // #define inline _inline (in MS compatibility mode)
  1750. StringRef MacroText = MacroName.getIdentifierInfo()->getName();
  1751. if (IdentifierInfo *II = Value.getIdentifierInfo()) {
  1752. if (!II->isKeyword(LOptions))
  1753. return false;
  1754. StringRef ValueText = II->getName();
  1755. StringRef TrimmedValue = ValueText;
  1756. if (!ValueText.startswith("__")) {
  1757. if (ValueText.startswith("_"))
  1758. TrimmedValue = TrimmedValue.drop_front(1);
  1759. else
  1760. return false;
  1761. } else {
  1762. TrimmedValue = TrimmedValue.drop_front(2);
  1763. if (TrimmedValue.endswith("__"))
  1764. TrimmedValue = TrimmedValue.drop_back(2);
  1765. }
  1766. return TrimmedValue.equals(MacroText);
  1767. } else {
  1768. return false;
  1769. }
  1770. }
  1771. // #define inline
  1772. if (MacroName.isOneOf(tok::kw_extern, tok::kw_inline, tok::kw_static,
  1773. tok::kw_const) &&
  1774. MI->getNumTokens() == 0) {
  1775. return true;
  1776. }
  1777. return false;
  1778. }
  1779. /// HandleDefineDirective - Implements \#define. This consumes the entire macro
  1780. /// line then lets the caller lex the next real token.
  1781. void Preprocessor::HandleDefineDirective(Token &DefineTok,
  1782. bool ImmediatelyAfterHeaderGuard) {
  1783. ++NumDefined;
  1784. Token MacroNameTok;
  1785. bool MacroShadowsKeyword;
  1786. ReadMacroName(MacroNameTok, MU_Define, &MacroShadowsKeyword);
  1787. // Error reading macro name? If so, diagnostic already issued.
  1788. if (MacroNameTok.is(tok::eod))
  1789. return;
  1790. Token LastTok = MacroNameTok;
  1791. // If we are supposed to keep comments in #defines, reenable comment saving
  1792. // mode.
  1793. if (CurLexer) CurLexer->SetCommentRetentionState(KeepMacroComments);
  1794. // Create the new macro.
  1795. MacroInfo *MI = AllocateMacroInfo(MacroNameTok.getLocation());
  1796. Token Tok;
  1797. LexUnexpandedToken(Tok);
  1798. // If this is a function-like macro definition, parse the argument list,
  1799. // marking each of the identifiers as being used as macro arguments. Also,
  1800. // check other constraints on the first token of the macro body.
  1801. if (Tok.is(tok::eod)) {
  1802. if (ImmediatelyAfterHeaderGuard) {
  1803. // Save this macro information since it may part of a header guard.
  1804. CurPPLexer->MIOpt.SetDefinedMacro(MacroNameTok.getIdentifierInfo(),
  1805. MacroNameTok.getLocation());
  1806. }
  1807. // If there is no body to this macro, we have no special handling here.
  1808. } else if (Tok.hasLeadingSpace()) {
  1809. // This is a normal token with leading space. Clear the leading space
  1810. // marker on the first token to get proper expansion.
  1811. Tok.clearFlag(Token::LeadingSpace);
  1812. } else if (Tok.is(tok::l_paren)) {
  1813. // This is a function-like macro definition. Read the argument list.
  1814. MI->setIsFunctionLike();
  1815. if (ReadMacroDefinitionArgList(MI, LastTok)) {
  1816. // Throw away the rest of the line.
  1817. if (CurPPLexer->ParsingPreprocessorDirective)
  1818. DiscardUntilEndOfDirective();
  1819. return;
  1820. }
  1821. // If this is a definition of a variadic C99 function-like macro, not using
  1822. // the GNU named varargs extension, enabled __VA_ARGS__.
  1823. // "Poison" __VA_ARGS__, which can only appear in the expansion of a macro.
  1824. // This gets unpoisoned where it is allowed.
  1825. assert(Ident__VA_ARGS__->isPoisoned() && "__VA_ARGS__ should be poisoned!");
  1826. if (MI->isC99Varargs())
  1827. Ident__VA_ARGS__->setIsPoisoned(false);
  1828. // Read the first token after the arg list for down below.
  1829. LexUnexpandedToken(Tok);
  1830. } else if (LangOpts.C99 || LangOpts.CPlusPlus11) {
  1831. // C99 requires whitespace between the macro definition and the body. Emit
  1832. // a diagnostic for something like "#define X+".
  1833. Diag(Tok, diag::ext_c99_whitespace_required_after_macro_name);
  1834. } else {
  1835. // C90 6.8 TC1 says: "In the definition of an object-like macro, if the
  1836. // first character of a replacement list is not a character required by
  1837. // subclause 5.2.1, then there shall be white-space separation between the
  1838. // identifier and the replacement list.". 5.2.1 lists this set:
  1839. // "A-Za-z0-9!"#%&'()*+,_./:;<=>?[\]^_{|}~" as well as whitespace, which
  1840. // is irrelevant here.
  1841. bool isInvalid = false;
  1842. if (Tok.is(tok::at)) // @ is not in the list above.
  1843. isInvalid = true;
  1844. else if (Tok.is(tok::unknown)) {
  1845. // If we have an unknown token, it is something strange like "`". Since
  1846. // all of valid characters would have lexed into a single character
  1847. // token of some sort, we know this is not a valid case.
  1848. isInvalid = true;
  1849. }
  1850. if (isInvalid)
  1851. Diag(Tok, diag::ext_missing_whitespace_after_macro_name);
  1852. else
  1853. Diag(Tok, diag::warn_missing_whitespace_after_macro_name);
  1854. }
  1855. if (!Tok.is(tok::eod))
  1856. LastTok = Tok;
  1857. // Read the rest of the macro body.
  1858. if (MI->isObjectLike()) {
  1859. // Object-like macros are very simple, just read their body.
  1860. while (Tok.isNot(tok::eod)) {
  1861. LastTok = Tok;
  1862. MI->AddTokenToBody(Tok);
  1863. // Get the next token of the macro.
  1864. LexUnexpandedToken(Tok);
  1865. }
  1866. } else {
  1867. // Otherwise, read the body of a function-like macro. While we are at it,
  1868. // check C99 6.10.3.2p1: ensure that # operators are followed by macro
  1869. // parameters in function-like macro expansions.
  1870. while (Tok.isNot(tok::eod)) {
  1871. LastTok = Tok;
  1872. if (Tok.isNot(tok::hash) && Tok.isNot(tok::hashhash)) {
  1873. MI->AddTokenToBody(Tok);
  1874. // Get the next token of the macro.
  1875. LexUnexpandedToken(Tok);
  1876. continue;
  1877. }
  1878. // If we're in -traditional mode, then we should ignore stringification
  1879. // and token pasting. Mark the tokens as unknown so as not to confuse
  1880. // things.
  1881. if (getLangOpts().TraditionalCPP) {
  1882. Tok.setKind(tok::unknown);
  1883. MI->AddTokenToBody(Tok);
  1884. // Get the next token of the macro.
  1885. LexUnexpandedToken(Tok);
  1886. continue;
  1887. }
  1888. if (Tok.is(tok::hashhash)) {
  1889. // If we see token pasting, check if it looks like the gcc comma
  1890. // pasting extension. We'll use this information to suppress
  1891. // diagnostics later on.
  1892. // Get the next token of the macro.
  1893. LexUnexpandedToken(Tok);
  1894. if (Tok.is(tok::eod)) {
  1895. MI->AddTokenToBody(LastTok);
  1896. break;
  1897. }
  1898. unsigned NumTokens = MI->getNumTokens();
  1899. if (NumTokens && Tok.getIdentifierInfo() == Ident__VA_ARGS__ &&
  1900. MI->getReplacementToken(NumTokens-1).is(tok::comma))
  1901. MI->setHasCommaPasting();
  1902. // Things look ok, add the '##' token to the macro.
  1903. MI->AddTokenToBody(LastTok);
  1904. continue;
  1905. }
  1906. // Get the next token of the macro.
  1907. LexUnexpandedToken(Tok);
  1908. // Check for a valid macro arg identifier.
  1909. if (Tok.getIdentifierInfo() == nullptr ||
  1910. MI->getArgumentNum(Tok.getIdentifierInfo()) == -1) {
  1911. // If this is assembler-with-cpp mode, we accept random gibberish after
  1912. // the '#' because '#' is often a comment character. However, change
  1913. // the kind of the token to tok::unknown so that the preprocessor isn't
  1914. // confused.
  1915. if (getLangOpts().AsmPreprocessor && Tok.isNot(tok::eod)) {
  1916. LastTok.setKind(tok::unknown);
  1917. MI->AddTokenToBody(LastTok);
  1918. continue;
  1919. } else {
  1920. Diag(Tok, diag::err_pp_stringize_not_parameter);
  1921. // Disable __VA_ARGS__ again.
  1922. Ident__VA_ARGS__->setIsPoisoned(true);
  1923. return;
  1924. }
  1925. }
  1926. // Things look ok, add the '#' and param name tokens to the macro.
  1927. MI->AddTokenToBody(LastTok);
  1928. MI->AddTokenToBody(Tok);
  1929. LastTok = Tok;
  1930. // Get the next token of the macro.
  1931. LexUnexpandedToken(Tok);
  1932. }
  1933. }
  1934. if (MacroShadowsKeyword &&
  1935. !isConfigurationPattern(MacroNameTok, MI, getLangOpts())) {
  1936. Diag(MacroNameTok, diag::warn_pp_macro_hides_keyword);
  1937. }
  1938. // Disable __VA_ARGS__ again.
  1939. Ident__VA_ARGS__->setIsPoisoned(true);
  1940. // Check that there is no paste (##) operator at the beginning or end of the
  1941. // replacement list.
  1942. unsigned NumTokens = MI->getNumTokens();
  1943. if (NumTokens != 0) {
  1944. if (MI->getReplacementToken(0).is(tok::hashhash)) {
  1945. Diag(MI->getReplacementToken(0), diag::err_paste_at_start);
  1946. return;
  1947. }
  1948. if (MI->getReplacementToken(NumTokens-1).is(tok::hashhash)) {
  1949. Diag(MI->getReplacementToken(NumTokens-1), diag::err_paste_at_end);
  1950. return;
  1951. }
  1952. }
  1953. MI->setDefinitionEndLoc(LastTok.getLocation());
  1954. // Finally, if this identifier already had a macro defined for it, verify that
  1955. // the macro bodies are identical, and issue diagnostics if they are not.
  1956. if (const MacroInfo *OtherMI=getMacroInfo(MacroNameTok.getIdentifierInfo())) {
  1957. // It is very common for system headers to have tons of macro redefinitions
  1958. // and for warnings to be disabled in system headers. If this is the case,
  1959. // then don't bother calling MacroInfo::isIdenticalTo.
  1960. if (!getDiagnostics().getSuppressSystemWarnings() ||
  1961. !SourceMgr.isInSystemHeader(DefineTok.getLocation())) {
  1962. if (!OtherMI->isUsed() && OtherMI->isWarnIfUnused())
  1963. Diag(OtherMI->getDefinitionLoc(), diag::pp_macro_not_used);
  1964. // Warn if defining "__LINE__" and other builtins, per C99 6.10.8/4 and
  1965. // C++ [cpp.predefined]p4, but allow it as an extension.
  1966. if (OtherMI->isBuiltinMacro())
  1967. Diag(MacroNameTok, diag::ext_pp_redef_builtin_macro);
  1968. // Macros must be identical. This means all tokens and whitespace
  1969. // separation must be the same. C99 6.10.3p2.
  1970. else if (!OtherMI->isAllowRedefinitionsWithoutWarning() &&
  1971. !MI->isIdenticalTo(*OtherMI, *this, /*Syntactic=*/LangOpts.MicrosoftExt)) {
  1972. Diag(MI->getDefinitionLoc(), diag::ext_pp_macro_redef)
  1973. << MacroNameTok.getIdentifierInfo();
  1974. Diag(OtherMI->getDefinitionLoc(), diag::note_previous_definition);
  1975. }
  1976. }
  1977. if (OtherMI->isWarnIfUnused())
  1978. WarnUnusedMacroLocs.erase(OtherMI->getDefinitionLoc());
  1979. }
  1980. DefMacroDirective *MD =
  1981. appendDefMacroDirective(MacroNameTok.getIdentifierInfo(), MI);
  1982. assert(!MI->isUsed());
  1983. // If we need warning for not using the macro, add its location in the
  1984. // warn-because-unused-macro set. If it gets used it will be removed from set.
  1985. if (getSourceManager().isInMainFile(MI->getDefinitionLoc()) &&
  1986. !Diags->isIgnored(diag::pp_macro_not_used, MI->getDefinitionLoc())) {
  1987. MI->setIsWarnIfUnused(true);
  1988. WarnUnusedMacroLocs.insert(MI->getDefinitionLoc());
  1989. }
  1990. // If the callbacks want to know, tell them about the macro definition.
  1991. if (Callbacks)
  1992. Callbacks->MacroDefined(MacroNameTok, MD);
  1993. }
  1994. /// HandleUndefDirective - Implements \#undef.
  1995. ///
  1996. void Preprocessor::HandleUndefDirective(Token &UndefTok) {
  1997. ++NumUndefined;
  1998. Token MacroNameTok;
  1999. ReadMacroName(MacroNameTok, MU_Undef);
  2000. // Error reading macro name? If so, diagnostic already issued.
  2001. if (MacroNameTok.is(tok::eod))
  2002. return;
  2003. // Check to see if this is the last token on the #undef line.
  2004. CheckEndOfDirective("undef");
  2005. // Okay, we have a valid identifier to undef.
  2006. auto *II = MacroNameTok.getIdentifierInfo();
  2007. auto MD = getMacroDefinition(II);
  2008. // If the callbacks want to know, tell them about the macro #undef.
  2009. // Note: no matter if the macro was defined or not.
  2010. if (Callbacks)
  2011. Callbacks->MacroUndefined(MacroNameTok, MD);
  2012. // If the macro is not defined, this is a noop undef, just return.
  2013. const MacroInfo *MI = MD.getMacroInfo();
  2014. if (!MI)
  2015. return;
  2016. if (!MI->isUsed() && MI->isWarnIfUnused())
  2017. Diag(MI->getDefinitionLoc(), diag::pp_macro_not_used);
  2018. if (MI->isWarnIfUnused())
  2019. WarnUnusedMacroLocs.erase(MI->getDefinitionLoc());
  2020. appendMacroDirective(MacroNameTok.getIdentifierInfo(),
  2021. AllocateUndefMacroDirective(MacroNameTok.getLocation()));
  2022. }
  2023. //===----------------------------------------------------------------------===//
  2024. // Preprocessor Conditional Directive Handling.
  2025. //===----------------------------------------------------------------------===//
  2026. /// HandleIfdefDirective - Implements the \#ifdef/\#ifndef directive. isIfndef
  2027. /// is true when this is a \#ifndef directive. ReadAnyTokensBeforeDirective is
  2028. /// true if any tokens have been returned or pp-directives activated before this
  2029. /// \#ifndef has been lexed.
  2030. ///
  2031. void Preprocessor::HandleIfdefDirective(Token &Result, bool isIfndef,
  2032. bool ReadAnyTokensBeforeDirective) {
  2033. ++NumIf;
  2034. Token DirectiveTok = Result;
  2035. Token MacroNameTok;
  2036. ReadMacroName(MacroNameTok);
  2037. // Error reading macro name? If so, diagnostic already issued.
  2038. if (MacroNameTok.is(tok::eod)) {
  2039. // Skip code until we get to #endif. This helps with recovery by not
  2040. // emitting an error when the #endif is reached.
  2041. SkipExcludedConditionalBlock(DirectiveTok.getLocation(),
  2042. /*Foundnonskip*/false, /*FoundElse*/false);
  2043. return;
  2044. }
  2045. // Check to see if this is the last token on the #if[n]def line.
  2046. CheckEndOfDirective(isIfndef ? "ifndef" : "ifdef");
  2047. IdentifierInfo *MII = MacroNameTok.getIdentifierInfo();
  2048. auto MD = getMacroDefinition(MII);
  2049. MacroInfo *MI = MD.getMacroInfo();
  2050. if (CurPPLexer->getConditionalStackDepth() == 0) {
  2051. // If the start of a top-level #ifdef and if the macro is not defined,
  2052. // inform MIOpt that this might be the start of a proper include guard.
  2053. // Otherwise it is some other form of unknown conditional which we can't
  2054. // handle.
  2055. if (!ReadAnyTokensBeforeDirective && !MI) {
  2056. assert(isIfndef && "#ifdef shouldn't reach here");
  2057. CurPPLexer->MIOpt.EnterTopLevelIfndef(MII, MacroNameTok.getLocation());
  2058. } else
  2059. CurPPLexer->MIOpt.EnterTopLevelConditional();
  2060. }
  2061. // If there is a macro, process it.
  2062. if (MI) // Mark it used.
  2063. markMacroAsUsed(MI);
  2064. if (Callbacks) {
  2065. if (isIfndef)
  2066. Callbacks->Ifndef(DirectiveTok.getLocation(), MacroNameTok, MD);
  2067. else
  2068. Callbacks->Ifdef(DirectiveTok.getLocation(), MacroNameTok, MD);
  2069. }
  2070. // Should we include the stuff contained by this directive?
  2071. if (!MI == isIfndef) {
  2072. // Yes, remember that we are inside a conditional, then lex the next token.
  2073. CurPPLexer->pushConditionalLevel(DirectiveTok.getLocation(),
  2074. /*wasskip*/false, /*foundnonskip*/true,
  2075. /*foundelse*/false);
  2076. } else {
  2077. // No, skip the contents of this block.
  2078. SkipExcludedConditionalBlock(DirectiveTok.getLocation(),
  2079. /*Foundnonskip*/false,
  2080. /*FoundElse*/false);
  2081. }
  2082. }
  2083. /// HandleIfDirective - Implements the \#if directive.
  2084. ///
  2085. void Preprocessor::HandleIfDirective(Token &IfToken,
  2086. bool ReadAnyTokensBeforeDirective) {
  2087. ++NumIf;
  2088. // Parse and evaluate the conditional expression.
  2089. IdentifierInfo *IfNDefMacro = nullptr;
  2090. const SourceLocation ConditionalBegin = CurPPLexer->getSourceLocation();
  2091. const bool ConditionalTrue = EvaluateDirectiveExpression(IfNDefMacro);
  2092. const SourceLocation ConditionalEnd = CurPPLexer->getSourceLocation();
  2093. // If this condition is equivalent to #ifndef X, and if this is the first
  2094. // directive seen, handle it for the multiple-include optimization.
  2095. if (CurPPLexer->getConditionalStackDepth() == 0) {
  2096. if (!ReadAnyTokensBeforeDirective && IfNDefMacro && ConditionalTrue)
  2097. // FIXME: Pass in the location of the macro name, not the 'if' token.
  2098. CurPPLexer->MIOpt.EnterTopLevelIfndef(IfNDefMacro, IfToken.getLocation());
  2099. else
  2100. CurPPLexer->MIOpt.EnterTopLevelConditional();
  2101. }
  2102. if (Callbacks)
  2103. Callbacks->If(IfToken.getLocation(),
  2104. SourceRange(ConditionalBegin, ConditionalEnd),
  2105. (ConditionalTrue ? PPCallbacks::CVK_True : PPCallbacks::CVK_False));
  2106. // Should we include the stuff contained by this directive?
  2107. if (ConditionalTrue) {
  2108. // Yes, remember that we are inside a conditional, then lex the next token.
  2109. CurPPLexer->pushConditionalLevel(IfToken.getLocation(), /*wasskip*/false,
  2110. /*foundnonskip*/true, /*foundelse*/false);
  2111. } else {
  2112. // No, skip the contents of this block.
  2113. SkipExcludedConditionalBlock(IfToken.getLocation(), /*Foundnonskip*/false,
  2114. /*FoundElse*/false);
  2115. }
  2116. }
  2117. /// HandleEndifDirective - Implements the \#endif directive.
  2118. ///
  2119. void Preprocessor::HandleEndifDirective(Token &EndifToken) {
  2120. ++NumEndif;
  2121. // Check that this is the whole directive.
  2122. CheckEndOfDirective("endif");
  2123. PPConditionalInfo CondInfo;
  2124. if (CurPPLexer->popConditionalLevel(CondInfo)) {
  2125. // No conditionals on the stack: this is an #endif without an #if.
  2126. Diag(EndifToken, diag::err_pp_endif_without_if);
  2127. return;
  2128. }
  2129. // If this the end of a top-level #endif, inform MIOpt.
  2130. if (CurPPLexer->getConditionalStackDepth() == 0)
  2131. CurPPLexer->MIOpt.ExitTopLevelConditional();
  2132. assert(!CondInfo.WasSkipping && !CurPPLexer->LexingRawMode &&
  2133. "This code should only be reachable in the non-skipping case!");
  2134. if (Callbacks)
  2135. Callbacks->Endif(EndifToken.getLocation(), CondInfo.IfLoc);
  2136. }
  2137. /// HandleElseDirective - Implements the \#else directive.
  2138. ///
  2139. void Preprocessor::HandleElseDirective(Token &Result) {
  2140. ++NumElse;
  2141. // #else directive in a non-skipping conditional... start skipping.
  2142. CheckEndOfDirective("else");
  2143. PPConditionalInfo CI;
  2144. if (CurPPLexer->popConditionalLevel(CI)) {
  2145. Diag(Result, diag::pp_err_else_without_if);
  2146. return;
  2147. }
  2148. // If this is a top-level #else, inform the MIOpt.
  2149. if (CurPPLexer->getConditionalStackDepth() == 0)
  2150. CurPPLexer->MIOpt.EnterTopLevelConditional();
  2151. // If this is a #else with a #else before it, report the error.
  2152. if (CI.FoundElse) Diag(Result, diag::pp_err_else_after_else);
  2153. if (Callbacks)
  2154. Callbacks->Else(Result.getLocation(), CI.IfLoc);
  2155. // Finally, skip the rest of the contents of this block.
  2156. SkipExcludedConditionalBlock(CI.IfLoc, /*Foundnonskip*/true,
  2157. /*FoundElse*/true, Result.getLocation());
  2158. }
  2159. /// HandleElifDirective - Implements the \#elif directive.
  2160. ///
  2161. void Preprocessor::HandleElifDirective(Token &ElifToken) {
  2162. ++NumElse;
  2163. // #elif directive in a non-skipping conditional... start skipping.
  2164. // We don't care what the condition is, because we will always skip it (since
  2165. // the block immediately before it was included).
  2166. const SourceLocation ConditionalBegin = CurPPLexer->getSourceLocation();
  2167. DiscardUntilEndOfDirective();
  2168. const SourceLocation ConditionalEnd = CurPPLexer->getSourceLocation();
  2169. PPConditionalInfo CI;
  2170. if (CurPPLexer->popConditionalLevel(CI)) {
  2171. Diag(ElifToken, diag::pp_err_elif_without_if);
  2172. return;
  2173. }
  2174. // If this is a top-level #elif, inform the MIOpt.
  2175. if (CurPPLexer->getConditionalStackDepth() == 0)
  2176. CurPPLexer->MIOpt.EnterTopLevelConditional();
  2177. // If this is a #elif with a #else before it, report the error.
  2178. if (CI.FoundElse) Diag(ElifToken, diag::pp_err_elif_after_else);
  2179. if (Callbacks)
  2180. Callbacks->Elif(ElifToken.getLocation(),
  2181. SourceRange(ConditionalBegin, ConditionalEnd),
  2182. PPCallbacks::CVK_NotEvaluated, CI.IfLoc);
  2183. // Finally, skip the rest of the contents of this block.
  2184. SkipExcludedConditionalBlock(CI.IfLoc, /*Foundnonskip*/true,
  2185. /*FoundElse*/CI.FoundElse,
  2186. ElifToken.getLocation());
  2187. }