PPDirectives.cpp 73 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056
  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. // This file implements # directive processing for the Preprocessor.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "clang/Lex/Preprocessor.h"
  14. #include "clang/Lex/LiteralSupport.h"
  15. #include "clang/Lex/HeaderSearch.h"
  16. #include "clang/Lex/MacroInfo.h"
  17. #include "clang/Lex/LexDiagnostic.h"
  18. #include "clang/Lex/CodeCompletionHandler.h"
  19. #include "clang/Lex/ModuleLoader.h"
  20. #include "clang/Lex/Pragma.h"
  21. #include "clang/Basic/FileManager.h"
  22. #include "clang/Basic/SourceManager.h"
  23. #include "llvm/ADT/APInt.h"
  24. #include "llvm/Support/ErrorHandling.h"
  25. using namespace clang;
  26. //===----------------------------------------------------------------------===//
  27. // Utility Methods for Preprocessor Directive Handling.
  28. //===----------------------------------------------------------------------===//
  29. MacroInfo *Preprocessor::AllocateMacroInfo() {
  30. MacroInfoChain *MIChain;
  31. if (MICache) {
  32. MIChain = MICache;
  33. MICache = MICache->Next;
  34. }
  35. else {
  36. MIChain = BP.Allocate<MacroInfoChain>();
  37. }
  38. MIChain->Next = MIChainHead;
  39. MIChain->Prev = 0;
  40. if (MIChainHead)
  41. MIChainHead->Prev = MIChain;
  42. MIChainHead = MIChain;
  43. return &(MIChain->MI);
  44. }
  45. MacroInfo *Preprocessor::AllocateMacroInfo(SourceLocation L) {
  46. MacroInfo *MI = AllocateMacroInfo();
  47. new (MI) MacroInfo(L);
  48. return MI;
  49. }
  50. MacroInfo *Preprocessor::CloneMacroInfo(const MacroInfo &MacroToClone) {
  51. MacroInfo *MI = AllocateMacroInfo();
  52. new (MI) MacroInfo(MacroToClone, BP);
  53. return MI;
  54. }
  55. /// ReleaseMacroInfo - Release the specified MacroInfo. This memory will
  56. /// be reused for allocating new MacroInfo objects.
  57. void Preprocessor::ReleaseMacroInfo(MacroInfo *MI) {
  58. MacroInfoChain *MIChain = (MacroInfoChain*) MI;
  59. if (MacroInfoChain *Prev = MIChain->Prev) {
  60. MacroInfoChain *Next = MIChain->Next;
  61. Prev->Next = Next;
  62. if (Next)
  63. Next->Prev = Prev;
  64. }
  65. else {
  66. assert(MIChainHead == MIChain);
  67. MIChainHead = MIChain->Next;
  68. MIChainHead->Prev = 0;
  69. }
  70. MIChain->Next = MICache;
  71. MICache = MIChain;
  72. MI->Destroy();
  73. }
  74. /// DiscardUntilEndOfDirective - Read and discard all tokens remaining on the
  75. /// current line until the tok::eod token is found.
  76. void Preprocessor::DiscardUntilEndOfDirective() {
  77. Token Tmp;
  78. do {
  79. LexUnexpandedToken(Tmp);
  80. assert(Tmp.isNot(tok::eof) && "EOF seen while discarding directive tokens");
  81. } while (Tmp.isNot(tok::eod));
  82. }
  83. /// ReadMacroName - Lex and validate a macro name, which occurs after a
  84. /// #define or #undef. This sets the token kind to eod and discards the rest
  85. /// of the macro line if the macro name is invalid. isDefineUndef is 1 if
  86. /// this is due to a a #define, 2 if #undef directive, 0 if it is something
  87. /// else (e.g. #ifdef).
  88. void Preprocessor::ReadMacroName(Token &MacroNameTok, char isDefineUndef) {
  89. // Read the token, don't allow macro expansion on it.
  90. LexUnexpandedToken(MacroNameTok);
  91. if (MacroNameTok.is(tok::code_completion)) {
  92. if (CodeComplete)
  93. CodeComplete->CodeCompleteMacroName(isDefineUndef == 1);
  94. setCodeCompletionReached();
  95. LexUnexpandedToken(MacroNameTok);
  96. }
  97. // Missing macro name?
  98. if (MacroNameTok.is(tok::eod)) {
  99. Diag(MacroNameTok, diag::err_pp_missing_macro_name);
  100. return;
  101. }
  102. IdentifierInfo *II = MacroNameTok.getIdentifierInfo();
  103. if (II == 0) {
  104. bool Invalid = false;
  105. std::string Spelling = getSpelling(MacroNameTok, &Invalid);
  106. if (Invalid)
  107. return;
  108. const IdentifierInfo &Info = Identifiers.get(Spelling);
  109. // Allow #defining |and| and friends in microsoft mode.
  110. if (Info.isCPlusPlusOperatorKeyword() && getLangOpts().MicrosoftMode) {
  111. MacroNameTok.setIdentifierInfo(getIdentifierInfo(Spelling));
  112. return;
  113. }
  114. if (Info.isCPlusPlusOperatorKeyword())
  115. // C++ 2.5p2: Alternative tokens behave the same as its primary token
  116. // except for their spellings.
  117. Diag(MacroNameTok, diag::err_pp_operator_used_as_macro_name) << Spelling;
  118. else
  119. Diag(MacroNameTok, diag::err_pp_macro_not_identifier);
  120. // Fall through on error.
  121. } else if (isDefineUndef && II->getPPKeywordID() == tok::pp_defined) {
  122. // Error if defining "defined": C99 6.10.8.4.
  123. Diag(MacroNameTok, diag::err_defined_macro_name);
  124. } else if (isDefineUndef && II->hasMacroDefinition() &&
  125. getMacroInfo(II)->isBuiltinMacro()) {
  126. // Error if defining "__LINE__" and other builtins: C99 6.10.8.4.
  127. if (isDefineUndef == 1)
  128. Diag(MacroNameTok, diag::pp_redef_builtin_macro);
  129. else
  130. Diag(MacroNameTok, diag::pp_undef_builtin_macro);
  131. } else {
  132. // Okay, we got a good identifier node. Return it.
  133. return;
  134. }
  135. // Invalid macro name, read and discard the rest of the line. Then set the
  136. // token kind to tok::eod.
  137. MacroNameTok.setKind(tok::eod);
  138. return DiscardUntilEndOfDirective();
  139. }
  140. /// CheckEndOfDirective - Ensure that the next token is a tok::eod token. If
  141. /// not, emit a diagnostic and consume up until the eod. If EnableMacros is
  142. /// true, then we consider macros that expand to zero tokens as being ok.
  143. void Preprocessor::CheckEndOfDirective(const char *DirType, bool EnableMacros) {
  144. Token Tmp;
  145. // Lex unexpanded tokens for most directives: macros might expand to zero
  146. // tokens, causing us to miss diagnosing invalid lines. Some directives (like
  147. // #line) allow empty macros.
  148. if (EnableMacros)
  149. Lex(Tmp);
  150. else
  151. LexUnexpandedToken(Tmp);
  152. // There should be no tokens after the directive, but we allow them as an
  153. // extension.
  154. while (Tmp.is(tok::comment)) // Skip comments in -C mode.
  155. LexUnexpandedToken(Tmp);
  156. if (Tmp.isNot(tok::eod)) {
  157. // Add a fixit in GNU/C99/C++ mode. Don't offer a fixit for strict-C89,
  158. // or if this is a macro-style preprocessing directive, because it is more
  159. // trouble than it is worth to insert /**/ and check that there is no /**/
  160. // in the range also.
  161. FixItHint Hint;
  162. if ((LangOpts.GNUMode || LangOpts.C99 || LangOpts.CPlusPlus) &&
  163. !CurTokenLexer)
  164. Hint = FixItHint::CreateInsertion(Tmp.getLocation(),"//");
  165. Diag(Tmp, diag::ext_pp_extra_tokens_at_eol) << DirType << Hint;
  166. DiscardUntilEndOfDirective();
  167. }
  168. }
  169. /// SkipExcludedConditionalBlock - We just read a #if or related directive and
  170. /// decided that the subsequent tokens are in the #if'd out portion of the
  171. /// file. Lex the rest of the file, until we see an #endif. If
  172. /// FoundNonSkipPortion is true, then we have already emitted code for part of
  173. /// this #if directive, so #else/#elif blocks should never be entered. If ElseOk
  174. /// is true, then #else directives are ok, if not, then we have already seen one
  175. /// so a #else directive is a duplicate. When this returns, the caller can lex
  176. /// the first valid token.
  177. void Preprocessor::SkipExcludedConditionalBlock(SourceLocation IfTokenLoc,
  178. bool FoundNonSkipPortion,
  179. bool FoundElse,
  180. SourceLocation ElseLoc) {
  181. ++NumSkipped;
  182. assert(CurTokenLexer == 0 && CurPPLexer && "Lexing a macro, not a file?");
  183. CurPPLexer->pushConditionalLevel(IfTokenLoc, /*isSkipping*/false,
  184. FoundNonSkipPortion, FoundElse);
  185. if (CurPTHLexer) {
  186. PTHSkipExcludedConditionalBlock();
  187. return;
  188. }
  189. // Enter raw mode to disable identifier lookup (and thus macro expansion),
  190. // disabling warnings, etc.
  191. CurPPLexer->LexingRawMode = true;
  192. Token Tok;
  193. while (1) {
  194. CurLexer->Lex(Tok);
  195. if (Tok.is(tok::code_completion)) {
  196. if (CodeComplete)
  197. CodeComplete->CodeCompleteInConditionalExclusion();
  198. setCodeCompletionReached();
  199. continue;
  200. }
  201. // If this is the end of the buffer, we have an error.
  202. if (Tok.is(tok::eof)) {
  203. // Emit errors for each unterminated conditional on the stack, including
  204. // the current one.
  205. while (!CurPPLexer->ConditionalStack.empty()) {
  206. if (CurLexer->getFileLoc() != CodeCompletionFileLoc)
  207. Diag(CurPPLexer->ConditionalStack.back().IfLoc,
  208. diag::err_pp_unterminated_conditional);
  209. CurPPLexer->ConditionalStack.pop_back();
  210. }
  211. // Just return and let the caller lex after this #include.
  212. break;
  213. }
  214. // If this token is not a preprocessor directive, just skip it.
  215. if (Tok.isNot(tok::hash) || !Tok.isAtStartOfLine())
  216. continue;
  217. // We just parsed a # character at the start of a line, so we're in
  218. // directive mode. Tell the lexer this so any newlines we see will be
  219. // converted into an EOD token (this terminates the macro).
  220. CurPPLexer->ParsingPreprocessorDirective = true;
  221. if (CurLexer) CurLexer->SetCommentRetentionState(false);
  222. // Read the next token, the directive flavor.
  223. LexUnexpandedToken(Tok);
  224. // If this isn't an identifier directive (e.g. is "# 1\n" or "#\n", or
  225. // something bogus), skip it.
  226. if (Tok.isNot(tok::raw_identifier)) {
  227. CurPPLexer->ParsingPreprocessorDirective = false;
  228. // Restore comment saving mode.
  229. if (CurLexer) CurLexer->SetCommentRetentionState(KeepComments);
  230. continue;
  231. }
  232. // If the first letter isn't i or e, it isn't intesting to us. We know that
  233. // this is safe in the face of spelling differences, because there is no way
  234. // to spell an i/e in a strange way that is another letter. Skipping this
  235. // allows us to avoid looking up the identifier info for #define/#undef and
  236. // other common directives.
  237. const char *RawCharData = Tok.getRawIdentifierData();
  238. char FirstChar = RawCharData[0];
  239. if (FirstChar >= 'a' && FirstChar <= 'z' &&
  240. FirstChar != 'i' && FirstChar != 'e') {
  241. CurPPLexer->ParsingPreprocessorDirective = false;
  242. // Restore comment saving mode.
  243. if (CurLexer) CurLexer->SetCommentRetentionState(KeepComments);
  244. continue;
  245. }
  246. // Get the identifier name without trigraphs or embedded newlines. Note
  247. // that we can't use Tok.getIdentifierInfo() because its lookup is disabled
  248. // when skipping.
  249. char DirectiveBuf[20];
  250. StringRef Directive;
  251. if (!Tok.needsCleaning() && Tok.getLength() < 20) {
  252. Directive = StringRef(RawCharData, Tok.getLength());
  253. } else {
  254. std::string DirectiveStr = getSpelling(Tok);
  255. unsigned IdLen = DirectiveStr.size();
  256. if (IdLen >= 20) {
  257. CurPPLexer->ParsingPreprocessorDirective = false;
  258. // Restore comment saving mode.
  259. if (CurLexer) CurLexer->SetCommentRetentionState(KeepComments);
  260. continue;
  261. }
  262. memcpy(DirectiveBuf, &DirectiveStr[0], IdLen);
  263. Directive = StringRef(DirectiveBuf, IdLen);
  264. }
  265. if (Directive.startswith("if")) {
  266. StringRef Sub = Directive.substr(2);
  267. if (Sub.empty() || // "if"
  268. Sub == "def" || // "ifdef"
  269. Sub == "ndef") { // "ifndef"
  270. // We know the entire #if/#ifdef/#ifndef block will be skipped, don't
  271. // bother parsing the condition.
  272. DiscardUntilEndOfDirective();
  273. CurPPLexer->pushConditionalLevel(Tok.getLocation(), /*wasskipping*/true,
  274. /*foundnonskip*/false,
  275. /*foundelse*/false);
  276. }
  277. } else if (Directive[0] == 'e') {
  278. StringRef Sub = Directive.substr(1);
  279. if (Sub == "ndif") { // "endif"
  280. CheckEndOfDirective("endif");
  281. PPConditionalInfo CondInfo;
  282. CondInfo.WasSkipping = true; // Silence bogus warning.
  283. bool InCond = CurPPLexer->popConditionalLevel(CondInfo);
  284. (void)InCond; // Silence warning in no-asserts mode.
  285. assert(!InCond && "Can't be skipping if not in a conditional!");
  286. // If we popped the outermost skipping block, we're done skipping!
  287. if (!CondInfo.WasSkipping) {
  288. if (Callbacks)
  289. Callbacks->Endif(Tok.getLocation(), CondInfo.IfLoc);
  290. break;
  291. }
  292. } else if (Sub == "lse") { // "else".
  293. // #else directive in a skipping conditional. If not in some other
  294. // skipping conditional, and if #else hasn't already been seen, enter it
  295. // as a non-skipping conditional.
  296. PPConditionalInfo &CondInfo = CurPPLexer->peekConditionalLevel();
  297. // If this is a #else with a #else before it, report the error.
  298. if (CondInfo.FoundElse) Diag(Tok, diag::pp_err_else_after_else);
  299. // Note that we've seen a #else in this conditional.
  300. CondInfo.FoundElse = true;
  301. // If the conditional is at the top level, and the #if block wasn't
  302. // entered, enter the #else block now.
  303. if (!CondInfo.WasSkipping && !CondInfo.FoundNonSkip) {
  304. CondInfo.FoundNonSkip = true;
  305. CheckEndOfDirective("else");
  306. if (Callbacks)
  307. Callbacks->Else(Tok.getLocation(), CondInfo.IfLoc);
  308. break;
  309. } else {
  310. DiscardUntilEndOfDirective(); // C99 6.10p4.
  311. }
  312. } else if (Sub == "lif") { // "elif".
  313. PPConditionalInfo &CondInfo = CurPPLexer->peekConditionalLevel();
  314. bool ShouldEnter;
  315. const SourceLocation ConditionalBegin = CurPPLexer->getSourceLocation();
  316. // If this is in a skipping block or if we're already handled this #if
  317. // block, don't bother parsing the condition.
  318. if (CondInfo.WasSkipping || CondInfo.FoundNonSkip) {
  319. DiscardUntilEndOfDirective();
  320. ShouldEnter = false;
  321. } else {
  322. // Restore the value of LexingRawMode so that identifiers are
  323. // looked up, etc, inside the #elif expression.
  324. assert(CurPPLexer->LexingRawMode && "We have to be skipping here!");
  325. CurPPLexer->LexingRawMode = false;
  326. IdentifierInfo *IfNDefMacro = 0;
  327. ShouldEnter = EvaluateDirectiveExpression(IfNDefMacro);
  328. CurPPLexer->LexingRawMode = true;
  329. }
  330. const SourceLocation ConditionalEnd = CurPPLexer->getSourceLocation();
  331. // If this is a #elif with a #else before it, report the error.
  332. if (CondInfo.FoundElse) Diag(Tok, diag::pp_err_elif_after_else);
  333. // If this condition is true, enter it!
  334. if (ShouldEnter) {
  335. CondInfo.FoundNonSkip = true;
  336. if (Callbacks)
  337. Callbacks->Elif(Tok.getLocation(),
  338. SourceRange(ConditionalBegin, ConditionalEnd),
  339. CondInfo.IfLoc);
  340. break;
  341. }
  342. }
  343. }
  344. CurPPLexer->ParsingPreprocessorDirective = false;
  345. // Restore comment saving mode.
  346. if (CurLexer) CurLexer->SetCommentRetentionState(KeepComments);
  347. }
  348. // Finally, if we are out of the conditional (saw an #endif or ran off the end
  349. // of the file, just stop skipping and return to lexing whatever came after
  350. // the #if block.
  351. CurPPLexer->LexingRawMode = false;
  352. if (Callbacks) {
  353. SourceLocation BeginLoc = ElseLoc.isValid() ? ElseLoc : IfTokenLoc;
  354. Callbacks->SourceRangeSkipped(SourceRange(BeginLoc, Tok.getLocation()));
  355. }
  356. }
  357. void Preprocessor::PTHSkipExcludedConditionalBlock() {
  358. while (1) {
  359. assert(CurPTHLexer);
  360. assert(CurPTHLexer->LexingRawMode == false);
  361. // Skip to the next '#else', '#elif', or #endif.
  362. if (CurPTHLexer->SkipBlock()) {
  363. // We have reached an #endif. Both the '#' and 'endif' tokens
  364. // have been consumed by the PTHLexer. Just pop off the condition level.
  365. PPConditionalInfo CondInfo;
  366. bool InCond = CurPTHLexer->popConditionalLevel(CondInfo);
  367. (void)InCond; // Silence warning in no-asserts mode.
  368. assert(!InCond && "Can't be skipping if not in a conditional!");
  369. break;
  370. }
  371. // We have reached a '#else' or '#elif'. Lex the next token to get
  372. // the directive flavor.
  373. Token Tok;
  374. LexUnexpandedToken(Tok);
  375. // We can actually look up the IdentifierInfo here since we aren't in
  376. // raw mode.
  377. tok::PPKeywordKind K = Tok.getIdentifierInfo()->getPPKeywordID();
  378. if (K == tok::pp_else) {
  379. // #else: Enter the else condition. We aren't in a nested condition
  380. // since we skip those. We're always in the one matching the last
  381. // blocked we skipped.
  382. PPConditionalInfo &CondInfo = CurPTHLexer->peekConditionalLevel();
  383. // Note that we've seen a #else in this conditional.
  384. CondInfo.FoundElse = true;
  385. // If the #if block wasn't entered then enter the #else block now.
  386. if (!CondInfo.FoundNonSkip) {
  387. CondInfo.FoundNonSkip = true;
  388. // Scan until the eod token.
  389. CurPTHLexer->ParsingPreprocessorDirective = true;
  390. DiscardUntilEndOfDirective();
  391. CurPTHLexer->ParsingPreprocessorDirective = false;
  392. break;
  393. }
  394. // Otherwise skip this block.
  395. continue;
  396. }
  397. assert(K == tok::pp_elif);
  398. PPConditionalInfo &CondInfo = CurPTHLexer->peekConditionalLevel();
  399. // If this is a #elif with a #else before it, report the error.
  400. if (CondInfo.FoundElse)
  401. 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. We just skip this block.
  404. if (CondInfo.FoundNonSkip)
  405. continue;
  406. // Evaluate the condition of the #elif.
  407. IdentifierInfo *IfNDefMacro = 0;
  408. CurPTHLexer->ParsingPreprocessorDirective = true;
  409. bool ShouldEnter = EvaluateDirectiveExpression(IfNDefMacro);
  410. CurPTHLexer->ParsingPreprocessorDirective = false;
  411. // If this condition is true, enter it!
  412. if (ShouldEnter) {
  413. CondInfo.FoundNonSkip = true;
  414. break;
  415. }
  416. // Otherwise, skip this block and go to the next one.
  417. continue;
  418. }
  419. }
  420. /// LookupFile - Given a "foo" or <foo> reference, look up the indicated file,
  421. /// return null on failure. isAngled indicates whether the file reference is
  422. /// for system #include's or not (i.e. using <> instead of "").
  423. const FileEntry *Preprocessor::LookupFile(
  424. StringRef Filename,
  425. bool isAngled,
  426. const DirectoryLookup *FromDir,
  427. const DirectoryLookup *&CurDir,
  428. SmallVectorImpl<char> *SearchPath,
  429. SmallVectorImpl<char> *RelativePath,
  430. Module **SuggestedModule,
  431. bool SkipCache) {
  432. // If the header lookup mechanism may be relative to the current file, pass in
  433. // info about where the current file is.
  434. const FileEntry *CurFileEnt = 0;
  435. if (!FromDir) {
  436. FileID FID = getCurrentFileLexer()->getFileID();
  437. CurFileEnt = SourceMgr.getFileEntryForID(FID);
  438. // If there is no file entry associated with this file, it must be the
  439. // predefines buffer. Any other file is not lexed with a normal lexer, so
  440. // it won't be scanned for preprocessor directives. If we have the
  441. // predefines buffer, resolve #include references (which come from the
  442. // -include command line argument) as if they came from the main file, this
  443. // affects file lookup etc.
  444. if (CurFileEnt == 0) {
  445. FID = SourceMgr.getMainFileID();
  446. CurFileEnt = SourceMgr.getFileEntryForID(FID);
  447. }
  448. }
  449. // Do a standard file entry lookup.
  450. CurDir = CurDirLookup;
  451. const FileEntry *FE = HeaderInfo.LookupFile(
  452. Filename, isAngled, FromDir, CurDir, CurFileEnt,
  453. SearchPath, RelativePath, SuggestedModule, SkipCache);
  454. if (FE) return FE;
  455. // Otherwise, see if this is a subframework header. If so, this is relative
  456. // to one of the headers on the #include stack. Walk the list of the current
  457. // headers on the #include stack and pass them to HeaderInfo.
  458. // FIXME: SuggestedModule!
  459. if (IsFileLexer()) {
  460. if ((CurFileEnt = SourceMgr.getFileEntryForID(CurPPLexer->getFileID())))
  461. if ((FE = HeaderInfo.LookupSubframeworkHeader(Filename, CurFileEnt,
  462. SearchPath, RelativePath)))
  463. return FE;
  464. }
  465. for (unsigned i = 0, e = IncludeMacroStack.size(); i != e; ++i) {
  466. IncludeStackInfo &ISEntry = IncludeMacroStack[e-i-1];
  467. if (IsFileLexer(ISEntry)) {
  468. if ((CurFileEnt =
  469. SourceMgr.getFileEntryForID(ISEntry.ThePPLexer->getFileID())))
  470. if ((FE = HeaderInfo.LookupSubframeworkHeader(
  471. Filename, CurFileEnt, SearchPath, RelativePath)))
  472. return FE;
  473. }
  474. }
  475. // Otherwise, we really couldn't find the file.
  476. return 0;
  477. }
  478. //===----------------------------------------------------------------------===//
  479. // Preprocessor Directive Handling.
  480. //===----------------------------------------------------------------------===//
  481. /// HandleDirective - This callback is invoked when the lexer sees a # token
  482. /// at the start of a line. This consumes the directive, modifies the
  483. /// lexer/preprocessor state, and advances the lexer(s) so that the next token
  484. /// read is the correct one.
  485. void Preprocessor::HandleDirective(Token &Result) {
  486. // FIXME: Traditional: # with whitespace before it not recognized by K&R?
  487. // We just parsed a # character at the start of a line, so we're in directive
  488. // mode. Tell the lexer this so any newlines we see will be converted into an
  489. // EOD token (which terminates the directive).
  490. CurPPLexer->ParsingPreprocessorDirective = true;
  491. ++NumDirectives;
  492. // We are about to read a token. For the multiple-include optimization FA to
  493. // work, we have to remember if we had read any tokens *before* this
  494. // pp-directive.
  495. bool ReadAnyTokensBeforeDirective =CurPPLexer->MIOpt.getHasReadAnyTokensVal();
  496. // Save the '#' token in case we need to return it later.
  497. Token SavedHash = Result;
  498. // Read the next token, the directive flavor. This isn't expanded due to
  499. // C99 6.10.3p8.
  500. LexUnexpandedToken(Result);
  501. // C99 6.10.3p11: Is this preprocessor directive in macro invocation? e.g.:
  502. // #define A(x) #x
  503. // A(abc
  504. // #warning blah
  505. // def)
  506. // If so, the user is relying on undefined behavior, emit a diagnostic. Do
  507. // not support this for #include-like directives, since that can result in
  508. // terrible diagnostics, and does not work in GCC.
  509. if (InMacroArgs) {
  510. if (IdentifierInfo *II = Result.getIdentifierInfo()) {
  511. switch (II->getPPKeywordID()) {
  512. case tok::pp_include:
  513. case tok::pp_import:
  514. case tok::pp_include_next:
  515. case tok::pp___include_macros:
  516. Diag(Result, diag::err_embedded_include) << II->getName();
  517. DiscardUntilEndOfDirective();
  518. return;
  519. default:
  520. break;
  521. }
  522. }
  523. Diag(Result, diag::ext_embedded_directive);
  524. }
  525. TryAgain:
  526. switch (Result.getKind()) {
  527. case tok::eod:
  528. return; // null directive.
  529. case tok::comment:
  530. // Handle stuff like "# /*foo*/ define X" in -E -C mode.
  531. LexUnexpandedToken(Result);
  532. goto TryAgain;
  533. case tok::code_completion:
  534. if (CodeComplete)
  535. CodeComplete->CodeCompleteDirective(
  536. CurPPLexer->getConditionalStackDepth() > 0);
  537. setCodeCompletionReached();
  538. return;
  539. case tok::numeric_constant: // # 7 GNU line marker directive.
  540. if (getLangOpts().AsmPreprocessor)
  541. break; // # 4 is not a preprocessor directive in .S files.
  542. return HandleDigitDirective(Result);
  543. default:
  544. IdentifierInfo *II = Result.getIdentifierInfo();
  545. if (II == 0) break; // Not an identifier.
  546. // Ask what the preprocessor keyword ID is.
  547. switch (II->getPPKeywordID()) {
  548. default: break;
  549. // C99 6.10.1 - Conditional Inclusion.
  550. case tok::pp_if:
  551. return HandleIfDirective(Result, ReadAnyTokensBeforeDirective);
  552. case tok::pp_ifdef:
  553. return HandleIfdefDirective(Result, false, true/*not valid for miopt*/);
  554. case tok::pp_ifndef:
  555. return HandleIfdefDirective(Result, true, ReadAnyTokensBeforeDirective);
  556. case tok::pp_elif:
  557. return HandleElifDirective(Result);
  558. case tok::pp_else:
  559. return HandleElseDirective(Result);
  560. case tok::pp_endif:
  561. return HandleEndifDirective(Result);
  562. // C99 6.10.2 - Source File Inclusion.
  563. case tok::pp_include:
  564. // Handle #include.
  565. return HandleIncludeDirective(SavedHash.getLocation(), Result);
  566. case tok::pp___include_macros:
  567. // Handle -imacros.
  568. return HandleIncludeMacrosDirective(SavedHash.getLocation(), Result);
  569. // C99 6.10.3 - Macro Replacement.
  570. case tok::pp_define:
  571. return HandleDefineDirective(Result);
  572. case tok::pp_undef:
  573. return HandleUndefDirective(Result);
  574. // C99 6.10.4 - Line Control.
  575. case tok::pp_line:
  576. return HandleLineDirective(Result);
  577. // C99 6.10.5 - Error Directive.
  578. case tok::pp_error:
  579. return HandleUserDiagnosticDirective(Result, false);
  580. // C99 6.10.6 - Pragma Directive.
  581. case tok::pp_pragma:
  582. return HandlePragmaDirective(PIK_HashPragma);
  583. // GNU Extensions.
  584. case tok::pp_import:
  585. return HandleImportDirective(SavedHash.getLocation(), Result);
  586. case tok::pp_include_next:
  587. return HandleIncludeNextDirective(SavedHash.getLocation(), Result);
  588. case tok::pp_warning:
  589. Diag(Result, diag::ext_pp_warning_directive);
  590. return HandleUserDiagnosticDirective(Result, true);
  591. case tok::pp_ident:
  592. return HandleIdentSCCSDirective(Result);
  593. case tok::pp_sccs:
  594. return HandleIdentSCCSDirective(Result);
  595. case tok::pp_assert:
  596. //isExtension = true; // FIXME: implement #assert
  597. break;
  598. case tok::pp_unassert:
  599. //isExtension = true; // FIXME: implement #unassert
  600. break;
  601. case tok::pp___public_macro:
  602. if (getLangOpts().Modules)
  603. return HandleMacroPublicDirective(Result);
  604. break;
  605. case tok::pp___private_macro:
  606. if (getLangOpts().Modules)
  607. return HandleMacroPrivateDirective(Result);
  608. break;
  609. }
  610. break;
  611. }
  612. // If this is a .S file, treat unknown # directives as non-preprocessor
  613. // directives. This is important because # may be a comment or introduce
  614. // various pseudo-ops. Just return the # token and push back the following
  615. // token to be lexed next time.
  616. if (getLangOpts().AsmPreprocessor) {
  617. Token *Toks = new Token[2];
  618. // Return the # and the token after it.
  619. Toks[0] = SavedHash;
  620. Toks[1] = Result;
  621. // If the second token is a hashhash token, then we need to translate it to
  622. // unknown so the token lexer doesn't try to perform token pasting.
  623. if (Result.is(tok::hashhash))
  624. Toks[1].setKind(tok::unknown);
  625. // Enter this token stream so that we re-lex the tokens. Make sure to
  626. // enable macro expansion, in case the token after the # is an identifier
  627. // that is expanded.
  628. EnterTokenStream(Toks, 2, false, true);
  629. return;
  630. }
  631. // If we reached here, the preprocessing token is not valid!
  632. Diag(Result, diag::err_pp_invalid_directive);
  633. // Read the rest of the PP line.
  634. DiscardUntilEndOfDirective();
  635. // Okay, we're done parsing the directive.
  636. }
  637. /// GetLineValue - Convert a numeric token into an unsigned value, emitting
  638. /// Diagnostic DiagID if it is invalid, and returning the value in Val.
  639. static bool GetLineValue(Token &DigitTok, unsigned &Val,
  640. unsigned DiagID, Preprocessor &PP) {
  641. if (DigitTok.isNot(tok::numeric_constant)) {
  642. PP.Diag(DigitTok, DiagID);
  643. if (DigitTok.isNot(tok::eod))
  644. PP.DiscardUntilEndOfDirective();
  645. return true;
  646. }
  647. SmallString<64> IntegerBuffer;
  648. IntegerBuffer.resize(DigitTok.getLength());
  649. const char *DigitTokBegin = &IntegerBuffer[0];
  650. bool Invalid = false;
  651. unsigned ActualLength = PP.getSpelling(DigitTok, DigitTokBegin, &Invalid);
  652. if (Invalid)
  653. return true;
  654. // Verify that we have a simple digit-sequence, and compute the value. This
  655. // is always a simple digit string computed in decimal, so we do this manually
  656. // here.
  657. Val = 0;
  658. for (unsigned i = 0; i != ActualLength; ++i) {
  659. if (!isdigit(DigitTokBegin[i])) {
  660. PP.Diag(PP.AdvanceToTokenCharacter(DigitTok.getLocation(), i),
  661. diag::err_pp_line_digit_sequence);
  662. PP.DiscardUntilEndOfDirective();
  663. return true;
  664. }
  665. unsigned NextVal = Val*10+(DigitTokBegin[i]-'0');
  666. if (NextVal < Val) { // overflow.
  667. PP.Diag(DigitTok, DiagID);
  668. PP.DiscardUntilEndOfDirective();
  669. return true;
  670. }
  671. Val = NextVal;
  672. }
  673. // Reject 0, this is needed both by #line numbers and flags.
  674. if (Val == 0) {
  675. PP.Diag(DigitTok, DiagID);
  676. PP.DiscardUntilEndOfDirective();
  677. return true;
  678. }
  679. if (DigitTokBegin[0] == '0')
  680. PP.Diag(DigitTok.getLocation(), diag::warn_pp_line_decimal);
  681. return false;
  682. }
  683. /// HandleLineDirective - Handle #line directive: C99 6.10.4. The two
  684. /// acceptable forms are:
  685. /// # line digit-sequence
  686. /// # line digit-sequence "s-char-sequence"
  687. void Preprocessor::HandleLineDirective(Token &Tok) {
  688. // Read the line # and string argument. Per C99 6.10.4p5, these tokens are
  689. // expanded.
  690. Token DigitTok;
  691. Lex(DigitTok);
  692. // Validate the number and convert it to an unsigned.
  693. unsigned LineNo;
  694. if (GetLineValue(DigitTok, LineNo, diag::err_pp_line_requires_integer,*this))
  695. return;
  696. // Enforce C99 6.10.4p3: "The digit sequence shall not specify ... a
  697. // number greater than 2147483647". C90 requires that the line # be <= 32767.
  698. unsigned LineLimit = 32768U;
  699. if (LangOpts.C99 || LangOpts.CPlusPlus0x)
  700. LineLimit = 2147483648U;
  701. if (LineNo >= LineLimit)
  702. Diag(DigitTok, diag::ext_pp_line_too_big) << LineLimit;
  703. else if (LangOpts.CPlusPlus0x && LineNo >= 32768U)
  704. Diag(DigitTok, diag::warn_cxx98_compat_pp_line_too_big);
  705. int FilenameID = -1;
  706. Token StrTok;
  707. Lex(StrTok);
  708. // If the StrTok is "eod", then it wasn't present. Otherwise, it must be a
  709. // string followed by eod.
  710. if (StrTok.is(tok::eod))
  711. ; // ok
  712. else if (StrTok.isNot(tok::string_literal)) {
  713. Diag(StrTok, diag::err_pp_line_invalid_filename);
  714. return DiscardUntilEndOfDirective();
  715. } else if (StrTok.hasUDSuffix()) {
  716. Diag(StrTok, diag::err_invalid_string_udl);
  717. return DiscardUntilEndOfDirective();
  718. } else {
  719. // Parse and validate the string, converting it into a unique ID.
  720. StringLiteralParser Literal(&StrTok, 1, *this);
  721. assert(Literal.isAscii() && "Didn't allow wide strings in");
  722. if (Literal.hadError)
  723. return DiscardUntilEndOfDirective();
  724. if (Literal.Pascal) {
  725. Diag(StrTok, diag::err_pp_linemarker_invalid_filename);
  726. return DiscardUntilEndOfDirective();
  727. }
  728. FilenameID = SourceMgr.getLineTableFilenameID(Literal.GetString());
  729. // Verify that there is nothing after the string, other than EOD. Because
  730. // of C99 6.10.4p5, macros that expand to empty tokens are ok.
  731. CheckEndOfDirective("line", true);
  732. }
  733. SourceMgr.AddLineNote(DigitTok.getLocation(), LineNo, FilenameID);
  734. if (Callbacks)
  735. Callbacks->FileChanged(CurPPLexer->getSourceLocation(),
  736. PPCallbacks::RenameFile,
  737. SrcMgr::C_User);
  738. }
  739. /// ReadLineMarkerFlags - Parse and validate any flags at the end of a GNU line
  740. /// marker directive.
  741. static bool ReadLineMarkerFlags(bool &IsFileEntry, bool &IsFileExit,
  742. bool &IsSystemHeader, bool &IsExternCHeader,
  743. Preprocessor &PP) {
  744. unsigned FlagVal;
  745. Token FlagTok;
  746. PP.Lex(FlagTok);
  747. if (FlagTok.is(tok::eod)) return false;
  748. if (GetLineValue(FlagTok, FlagVal, diag::err_pp_linemarker_invalid_flag, PP))
  749. return true;
  750. if (FlagVal == 1) {
  751. IsFileEntry = true;
  752. PP.Lex(FlagTok);
  753. if (FlagTok.is(tok::eod)) return false;
  754. if (GetLineValue(FlagTok, FlagVal, diag::err_pp_linemarker_invalid_flag,PP))
  755. return true;
  756. } else if (FlagVal == 2) {
  757. IsFileExit = true;
  758. SourceManager &SM = PP.getSourceManager();
  759. // If we are leaving the current presumed file, check to make sure the
  760. // presumed include stack isn't empty!
  761. FileID CurFileID =
  762. SM.getDecomposedExpansionLoc(FlagTok.getLocation()).first;
  763. PresumedLoc PLoc = SM.getPresumedLoc(FlagTok.getLocation());
  764. if (PLoc.isInvalid())
  765. return true;
  766. // If there is no include loc (main file) or if the include loc is in a
  767. // different physical file, then we aren't in a "1" line marker flag region.
  768. SourceLocation IncLoc = PLoc.getIncludeLoc();
  769. if (IncLoc.isInvalid() ||
  770. SM.getDecomposedExpansionLoc(IncLoc).first != CurFileID) {
  771. PP.Diag(FlagTok, diag::err_pp_linemarker_invalid_pop);
  772. PP.DiscardUntilEndOfDirective();
  773. return true;
  774. }
  775. PP.Lex(FlagTok);
  776. if (FlagTok.is(tok::eod)) return false;
  777. if (GetLineValue(FlagTok, FlagVal, diag::err_pp_linemarker_invalid_flag,PP))
  778. return true;
  779. }
  780. // We must have 3 if there are still flags.
  781. if (FlagVal != 3) {
  782. PP.Diag(FlagTok, diag::err_pp_linemarker_invalid_flag);
  783. PP.DiscardUntilEndOfDirective();
  784. return true;
  785. }
  786. IsSystemHeader = true;
  787. PP.Lex(FlagTok);
  788. if (FlagTok.is(tok::eod)) return false;
  789. if (GetLineValue(FlagTok, FlagVal, diag::err_pp_linemarker_invalid_flag, PP))
  790. return true;
  791. // We must have 4 if there is yet another flag.
  792. if (FlagVal != 4) {
  793. PP.Diag(FlagTok, diag::err_pp_linemarker_invalid_flag);
  794. PP.DiscardUntilEndOfDirective();
  795. return true;
  796. }
  797. IsExternCHeader = true;
  798. PP.Lex(FlagTok);
  799. if (FlagTok.is(tok::eod)) return false;
  800. // There are no more valid flags here.
  801. PP.Diag(FlagTok, diag::err_pp_linemarker_invalid_flag);
  802. PP.DiscardUntilEndOfDirective();
  803. return true;
  804. }
  805. /// HandleDigitDirective - Handle a GNU line marker directive, whose syntax is
  806. /// one of the following forms:
  807. ///
  808. /// # 42
  809. /// # 42 "file" ('1' | '2')?
  810. /// # 42 "file" ('1' | '2')? '3' '4'?
  811. ///
  812. void Preprocessor::HandleDigitDirective(Token &DigitTok) {
  813. // Validate the number and convert it to an unsigned. GNU does not have a
  814. // line # limit other than it fit in 32-bits.
  815. unsigned LineNo;
  816. if (GetLineValue(DigitTok, LineNo, diag::err_pp_linemarker_requires_integer,
  817. *this))
  818. return;
  819. Token StrTok;
  820. Lex(StrTok);
  821. bool IsFileEntry = false, IsFileExit = false;
  822. bool IsSystemHeader = false, IsExternCHeader = false;
  823. int FilenameID = -1;
  824. // If the StrTok is "eod", then it wasn't present. Otherwise, it must be a
  825. // string followed by eod.
  826. if (StrTok.is(tok::eod))
  827. ; // ok
  828. else if (StrTok.isNot(tok::string_literal)) {
  829. Diag(StrTok, diag::err_pp_linemarker_invalid_filename);
  830. return DiscardUntilEndOfDirective();
  831. } else if (StrTok.hasUDSuffix()) {
  832. Diag(StrTok, diag::err_invalid_string_udl);
  833. return DiscardUntilEndOfDirective();
  834. } else {
  835. // Parse and validate the string, converting it into a unique ID.
  836. StringLiteralParser Literal(&StrTok, 1, *this);
  837. assert(Literal.isAscii() && "Didn't allow wide strings in");
  838. if (Literal.hadError)
  839. return DiscardUntilEndOfDirective();
  840. if (Literal.Pascal) {
  841. Diag(StrTok, diag::err_pp_linemarker_invalid_filename);
  842. return DiscardUntilEndOfDirective();
  843. }
  844. FilenameID = SourceMgr.getLineTableFilenameID(Literal.GetString());
  845. // If a filename was present, read any flags that are present.
  846. if (ReadLineMarkerFlags(IsFileEntry, IsFileExit,
  847. IsSystemHeader, IsExternCHeader, *this))
  848. return;
  849. }
  850. // Create a line note with this information.
  851. SourceMgr.AddLineNote(DigitTok.getLocation(), LineNo, FilenameID,
  852. IsFileEntry, IsFileExit,
  853. IsSystemHeader, IsExternCHeader);
  854. // If the preprocessor has callbacks installed, notify them of the #line
  855. // change. This is used so that the line marker comes out in -E mode for
  856. // example.
  857. if (Callbacks) {
  858. PPCallbacks::FileChangeReason Reason = PPCallbacks::RenameFile;
  859. if (IsFileEntry)
  860. Reason = PPCallbacks::EnterFile;
  861. else if (IsFileExit)
  862. Reason = PPCallbacks::ExitFile;
  863. SrcMgr::CharacteristicKind FileKind = SrcMgr::C_User;
  864. if (IsExternCHeader)
  865. FileKind = SrcMgr::C_ExternCSystem;
  866. else if (IsSystemHeader)
  867. FileKind = SrcMgr::C_System;
  868. Callbacks->FileChanged(CurPPLexer->getSourceLocation(), Reason, FileKind);
  869. }
  870. }
  871. /// HandleUserDiagnosticDirective - Handle a #warning or #error directive.
  872. ///
  873. void Preprocessor::HandleUserDiagnosticDirective(Token &Tok,
  874. bool isWarning) {
  875. // PTH doesn't emit #warning or #error directives.
  876. if (CurPTHLexer)
  877. return CurPTHLexer->DiscardToEndOfLine();
  878. // Read the rest of the line raw. We do this because we don't want macros
  879. // to be expanded and we don't require that the tokens be valid preprocessing
  880. // tokens. For example, this is allowed: "#warning ` 'foo". GCC does
  881. // collapse multiple consequtive white space between tokens, but this isn't
  882. // specified by the standard.
  883. std::string Message = CurLexer->ReadToEndOfLine();
  884. // Find the first non-whitespace character, so that we can make the
  885. // diagnostic more succinct.
  886. StringRef Msg(Message);
  887. size_t i = Msg.find_first_not_of(' ');
  888. if (i < Msg.size())
  889. Msg = Msg.substr(i);
  890. if (isWarning)
  891. Diag(Tok, diag::pp_hash_warning) << Msg;
  892. else
  893. Diag(Tok, diag::err_pp_hash_error) << Msg;
  894. }
  895. /// HandleIdentSCCSDirective - Handle a #ident/#sccs directive.
  896. ///
  897. void Preprocessor::HandleIdentSCCSDirective(Token &Tok) {
  898. // Yes, this directive is an extension.
  899. Diag(Tok, diag::ext_pp_ident_directive);
  900. // Read the string argument.
  901. Token StrTok;
  902. Lex(StrTok);
  903. // If the token kind isn't a string, it's a malformed directive.
  904. if (StrTok.isNot(tok::string_literal) &&
  905. StrTok.isNot(tok::wide_string_literal)) {
  906. Diag(StrTok, diag::err_pp_malformed_ident);
  907. if (StrTok.isNot(tok::eod))
  908. DiscardUntilEndOfDirective();
  909. return;
  910. }
  911. if (StrTok.hasUDSuffix()) {
  912. Diag(StrTok, diag::err_invalid_string_udl);
  913. return DiscardUntilEndOfDirective();
  914. }
  915. // Verify that there is nothing after the string, other than EOD.
  916. CheckEndOfDirective("ident");
  917. if (Callbacks) {
  918. bool Invalid = false;
  919. std::string Str = getSpelling(StrTok, &Invalid);
  920. if (!Invalid)
  921. Callbacks->Ident(Tok.getLocation(), Str);
  922. }
  923. }
  924. /// \brief Handle a #public directive.
  925. void Preprocessor::HandleMacroPublicDirective(Token &Tok) {
  926. Token MacroNameTok;
  927. ReadMacroName(MacroNameTok, 2);
  928. // Error reading macro name? If so, diagnostic already issued.
  929. if (MacroNameTok.is(tok::eod))
  930. return;
  931. // Check to see if this is the last token on the #__public_macro line.
  932. CheckEndOfDirective("__public_macro");
  933. // Okay, we finally have a valid identifier to undef.
  934. MacroInfo *MI = getMacroInfo(MacroNameTok.getIdentifierInfo());
  935. // If the macro is not defined, this is an error.
  936. if (MI == 0) {
  937. Diag(MacroNameTok, diag::err_pp_visibility_non_macro)
  938. << MacroNameTok.getIdentifierInfo();
  939. return;
  940. }
  941. // Note that this macro has now been exported.
  942. MI->setVisibility(/*IsPublic=*/true, MacroNameTok.getLocation());
  943. // If this macro definition came from a PCH file, mark it
  944. // as having changed since serialization.
  945. if (MI->isFromAST())
  946. MI->setChangedAfterLoad();
  947. }
  948. /// \brief Handle a #private directive.
  949. void Preprocessor::HandleMacroPrivateDirective(Token &Tok) {
  950. Token MacroNameTok;
  951. ReadMacroName(MacroNameTok, 2);
  952. // Error reading macro name? If so, diagnostic already issued.
  953. if (MacroNameTok.is(tok::eod))
  954. return;
  955. // Check to see if this is the last token on the #__private_macro line.
  956. CheckEndOfDirective("__private_macro");
  957. // Okay, we finally have a valid identifier to undef.
  958. MacroInfo *MI = getMacroInfo(MacroNameTok.getIdentifierInfo());
  959. // If the macro is not defined, this is an error.
  960. if (MI == 0) {
  961. Diag(MacroNameTok, diag::err_pp_visibility_non_macro)
  962. << MacroNameTok.getIdentifierInfo();
  963. return;
  964. }
  965. // Note that this macro has now been marked private.
  966. MI->setVisibility(/*IsPublic=*/false, MacroNameTok.getLocation());
  967. // If this macro definition came from a PCH file, mark it
  968. // as having changed since serialization.
  969. if (MI->isFromAST())
  970. MI->setChangedAfterLoad();
  971. }
  972. //===----------------------------------------------------------------------===//
  973. // Preprocessor Include Directive Handling.
  974. //===----------------------------------------------------------------------===//
  975. /// GetIncludeFilenameSpelling - Turn the specified lexer token into a fully
  976. /// checked and spelled filename, e.g. as an operand of #include. This returns
  977. /// true if the input filename was in <>'s or false if it were in ""'s. The
  978. /// caller is expected to provide a buffer that is large enough to hold the
  979. /// spelling of the filename, but is also expected to handle the case when
  980. /// this method decides to use a different buffer.
  981. bool Preprocessor::GetIncludeFilenameSpelling(SourceLocation Loc,
  982. StringRef &Buffer) {
  983. // Get the text form of the filename.
  984. assert(!Buffer.empty() && "Can't have tokens with empty spellings!");
  985. // Make sure the filename is <x> or "x".
  986. bool isAngled;
  987. if (Buffer[0] == '<') {
  988. if (Buffer.back() != '>') {
  989. Diag(Loc, diag::err_pp_expects_filename);
  990. Buffer = StringRef();
  991. return true;
  992. }
  993. isAngled = true;
  994. } else if (Buffer[0] == '"') {
  995. if (Buffer.back() != '"') {
  996. Diag(Loc, diag::err_pp_expects_filename);
  997. Buffer = StringRef();
  998. return true;
  999. }
  1000. isAngled = false;
  1001. } else {
  1002. Diag(Loc, diag::err_pp_expects_filename);
  1003. Buffer = StringRef();
  1004. return true;
  1005. }
  1006. // Diagnose #include "" as invalid.
  1007. if (Buffer.size() <= 2) {
  1008. Diag(Loc, diag::err_pp_empty_filename);
  1009. Buffer = StringRef();
  1010. return true;
  1011. }
  1012. // Skip the brackets.
  1013. Buffer = Buffer.substr(1, Buffer.size()-2);
  1014. return isAngled;
  1015. }
  1016. /// ConcatenateIncludeName - Handle cases where the #include name is expanded
  1017. /// from a macro as multiple tokens, which need to be glued together. This
  1018. /// occurs for code like:
  1019. /// #define FOO <a/b.h>
  1020. /// #include FOO
  1021. /// because in this case, "<a/b.h>" is returned as 7 tokens, not one.
  1022. ///
  1023. /// This code concatenates and consumes tokens up to the '>' token. It returns
  1024. /// false if the > was found, otherwise it returns true if it finds and consumes
  1025. /// the EOD marker.
  1026. bool Preprocessor::ConcatenateIncludeName(
  1027. SmallString<128> &FilenameBuffer,
  1028. SourceLocation &End) {
  1029. Token CurTok;
  1030. Lex(CurTok);
  1031. while (CurTok.isNot(tok::eod)) {
  1032. End = CurTok.getLocation();
  1033. // FIXME: Provide code completion for #includes.
  1034. if (CurTok.is(tok::code_completion)) {
  1035. setCodeCompletionReached();
  1036. Lex(CurTok);
  1037. continue;
  1038. }
  1039. // Append the spelling of this token to the buffer. If there was a space
  1040. // before it, add it now.
  1041. if (CurTok.hasLeadingSpace())
  1042. FilenameBuffer.push_back(' ');
  1043. // Get the spelling of the token, directly into FilenameBuffer if possible.
  1044. unsigned PreAppendSize = FilenameBuffer.size();
  1045. FilenameBuffer.resize(PreAppendSize+CurTok.getLength());
  1046. const char *BufPtr = &FilenameBuffer[PreAppendSize];
  1047. unsigned ActualLen = getSpelling(CurTok, BufPtr);
  1048. // If the token was spelled somewhere else, copy it into FilenameBuffer.
  1049. if (BufPtr != &FilenameBuffer[PreAppendSize])
  1050. memcpy(&FilenameBuffer[PreAppendSize], BufPtr, ActualLen);
  1051. // Resize FilenameBuffer to the correct size.
  1052. if (CurTok.getLength() != ActualLen)
  1053. FilenameBuffer.resize(PreAppendSize+ActualLen);
  1054. // If we found the '>' marker, return success.
  1055. if (CurTok.is(tok::greater))
  1056. return false;
  1057. Lex(CurTok);
  1058. }
  1059. // If we hit the eod marker, emit an error and return true so that the caller
  1060. // knows the EOD has been read.
  1061. Diag(CurTok.getLocation(), diag::err_pp_expects_filename);
  1062. return true;
  1063. }
  1064. /// HandleIncludeDirective - The "#include" tokens have just been read, read the
  1065. /// file to be included from the lexer, then include it! This is a common
  1066. /// routine with functionality shared between #include, #include_next and
  1067. /// #import. LookupFrom is set when this is a #include_next directive, it
  1068. /// specifies the file to start searching from.
  1069. void Preprocessor::HandleIncludeDirective(SourceLocation HashLoc,
  1070. Token &IncludeTok,
  1071. const DirectoryLookup *LookupFrom,
  1072. bool isImport) {
  1073. Token FilenameTok;
  1074. CurPPLexer->LexIncludeFilename(FilenameTok);
  1075. // Reserve a buffer to get the spelling.
  1076. SmallString<128> FilenameBuffer;
  1077. StringRef Filename;
  1078. SourceLocation End;
  1079. SourceLocation CharEnd; // the end of this directive, in characters
  1080. switch (FilenameTok.getKind()) {
  1081. case tok::eod:
  1082. // If the token kind is EOD, the error has already been diagnosed.
  1083. return;
  1084. case tok::angle_string_literal:
  1085. case tok::string_literal:
  1086. Filename = getSpelling(FilenameTok, FilenameBuffer);
  1087. End = FilenameTok.getLocation();
  1088. CharEnd = End.getLocWithOffset(Filename.size());
  1089. break;
  1090. case tok::less:
  1091. // This could be a <foo/bar.h> file coming from a macro expansion. In this
  1092. // case, glue the tokens together into FilenameBuffer and interpret those.
  1093. FilenameBuffer.push_back('<');
  1094. if (ConcatenateIncludeName(FilenameBuffer, End))
  1095. return; // Found <eod> but no ">"? Diagnostic already emitted.
  1096. Filename = FilenameBuffer.str();
  1097. CharEnd = getLocForEndOfToken(End);
  1098. break;
  1099. default:
  1100. Diag(FilenameTok.getLocation(), diag::err_pp_expects_filename);
  1101. DiscardUntilEndOfDirective();
  1102. return;
  1103. }
  1104. StringRef OriginalFilename = Filename;
  1105. bool isAngled =
  1106. GetIncludeFilenameSpelling(FilenameTok.getLocation(), Filename);
  1107. // If GetIncludeFilenameSpelling set the start ptr to null, there was an
  1108. // error.
  1109. if (Filename.empty()) {
  1110. DiscardUntilEndOfDirective();
  1111. return;
  1112. }
  1113. // Verify that there is nothing after the filename, other than EOD. Note that
  1114. // we allow macros that expand to nothing after the filename, because this
  1115. // falls into the category of "#include pp-tokens new-line" specified in
  1116. // C99 6.10.2p4.
  1117. CheckEndOfDirective(IncludeTok.getIdentifierInfo()->getNameStart(), true);
  1118. // Check that we don't have infinite #include recursion.
  1119. if (IncludeMacroStack.size() == MaxAllowedIncludeStackDepth-1) {
  1120. Diag(FilenameTok, diag::err_pp_include_too_deep);
  1121. return;
  1122. }
  1123. // Complain about attempts to #include files in an audit pragma.
  1124. if (PragmaARCCFCodeAuditedLoc.isValid()) {
  1125. Diag(HashLoc, diag::err_pp_include_in_arc_cf_code_audited);
  1126. Diag(PragmaARCCFCodeAuditedLoc, diag::note_pragma_entered_here);
  1127. // Immediately leave the pragma.
  1128. PragmaARCCFCodeAuditedLoc = SourceLocation();
  1129. }
  1130. if (HeaderInfo.HasIncludeAliasMap()) {
  1131. // Map the filename with the brackets still attached. If the name doesn't
  1132. // map to anything, fall back on the filename we've already gotten the
  1133. // spelling for.
  1134. StringRef NewName = HeaderInfo.MapHeaderToIncludeAlias(OriginalFilename);
  1135. if (!NewName.empty())
  1136. Filename = NewName;
  1137. }
  1138. // Search include directories.
  1139. const DirectoryLookup *CurDir;
  1140. SmallString<1024> SearchPath;
  1141. SmallString<1024> RelativePath;
  1142. // We get the raw path only if we have 'Callbacks' to which we later pass
  1143. // the path.
  1144. Module *SuggestedModule = 0;
  1145. const FileEntry *File = LookupFile(
  1146. Filename, isAngled, LookupFrom, CurDir,
  1147. Callbacks ? &SearchPath : NULL, Callbacks ? &RelativePath : NULL,
  1148. getLangOpts().Modules? &SuggestedModule : 0);
  1149. if (Callbacks) {
  1150. if (!File) {
  1151. // Give the clients a chance to recover.
  1152. SmallString<128> RecoveryPath;
  1153. if (Callbacks->FileNotFound(Filename, RecoveryPath)) {
  1154. if (const DirectoryEntry *DE = FileMgr.getDirectory(RecoveryPath)) {
  1155. // Add the recovery path to the list of search paths.
  1156. DirectoryLookup DL(DE, SrcMgr::C_User, true, false);
  1157. HeaderInfo.AddSearchPath(DL, isAngled);
  1158. // Try the lookup again, skipping the cache.
  1159. File = LookupFile(Filename, isAngled, LookupFrom, CurDir, 0, 0,
  1160. getLangOpts().Modules? &SuggestedModule : 0,
  1161. /*SkipCache*/true);
  1162. }
  1163. }
  1164. }
  1165. // Notify the callback object that we've seen an inclusion directive.
  1166. Callbacks->InclusionDirective(HashLoc, IncludeTok, Filename, isAngled, File,
  1167. End, SearchPath, RelativePath);
  1168. }
  1169. if (File == 0) {
  1170. if (!SuppressIncludeNotFoundError)
  1171. Diag(FilenameTok, diag::err_pp_file_not_found) << Filename;
  1172. return;
  1173. }
  1174. // If we are supposed to import a module rather than including the header,
  1175. // do so now.
  1176. if (SuggestedModule) {
  1177. // Compute the module access path corresponding to this module.
  1178. // FIXME: Should we have a second loadModule() overload to avoid this
  1179. // extra lookup step?
  1180. llvm::SmallVector<std::pair<IdentifierInfo *, SourceLocation>, 2> Path;
  1181. for (Module *Mod = SuggestedModule; Mod; Mod = Mod->Parent)
  1182. Path.push_back(std::make_pair(getIdentifierInfo(Mod->Name),
  1183. FilenameTok.getLocation()));
  1184. std::reverse(Path.begin(), Path.end());
  1185. // Warn that we're replacing the include/import with a module import.
  1186. SmallString<128> PathString;
  1187. for (unsigned I = 0, N = Path.size(); I != N; ++I) {
  1188. if (I)
  1189. PathString += '.';
  1190. PathString += Path[I].first->getName();
  1191. }
  1192. int IncludeKind = 0;
  1193. switch (IncludeTok.getIdentifierInfo()->getPPKeywordID()) {
  1194. case tok::pp_include:
  1195. IncludeKind = 0;
  1196. break;
  1197. case tok::pp_import:
  1198. IncludeKind = 1;
  1199. break;
  1200. case tok::pp_include_next:
  1201. IncludeKind = 2;
  1202. break;
  1203. case tok::pp___include_macros:
  1204. IncludeKind = 3;
  1205. break;
  1206. default:
  1207. llvm_unreachable("unknown include directive kind");
  1208. }
  1209. // Determine whether we are actually building the module that this
  1210. // include directive maps to.
  1211. bool BuildingImportedModule
  1212. = Path[0].first->getName() == getLangOpts().CurrentModule;
  1213. if (!BuildingImportedModule && getLangOpts().ObjC2) {
  1214. // If we're not building the imported module, warn that we're going
  1215. // to automatically turn this inclusion directive into a module import.
  1216. // We only do this in Objective-C, where we have a module-import syntax.
  1217. CharSourceRange ReplaceRange(SourceRange(HashLoc, CharEnd),
  1218. /*IsTokenRange=*/false);
  1219. Diag(HashLoc, diag::warn_auto_module_import)
  1220. << IncludeKind << PathString
  1221. << FixItHint::CreateReplacement(ReplaceRange,
  1222. "@__experimental_modules_import " + PathString.str().str() + ";");
  1223. }
  1224. // Load the module.
  1225. // If this was an #__include_macros directive, only make macros visible.
  1226. Module::NameVisibilityKind Visibility
  1227. = (IncludeKind == 3)? Module::MacrosVisible : Module::AllVisible;
  1228. Module *Imported
  1229. = TheModuleLoader.loadModule(IncludeTok.getLocation(), Path, Visibility,
  1230. /*IsIncludeDirective=*/true);
  1231. // If this header isn't part of the module we're building, we're done.
  1232. if (!BuildingImportedModule && Imported)
  1233. return;
  1234. }
  1235. // The #included file will be considered to be a system header if either it is
  1236. // in a system include directory, or if the #includer is a system include
  1237. // header.
  1238. SrcMgr::CharacteristicKind FileCharacter =
  1239. std::max(HeaderInfo.getFileDirFlavor(File),
  1240. SourceMgr.getFileCharacteristic(FilenameTok.getLocation()));
  1241. // Ask HeaderInfo if we should enter this #include file. If not, #including
  1242. // this file will have no effect.
  1243. if (!HeaderInfo.ShouldEnterIncludeFile(File, isImport)) {
  1244. if (Callbacks)
  1245. Callbacks->FileSkipped(*File, FilenameTok, FileCharacter);
  1246. return;
  1247. }
  1248. // Look up the file, create a File ID for it.
  1249. FileID FID = SourceMgr.createFileID(File, FilenameTok.getLocation(),
  1250. FileCharacter);
  1251. assert(!FID.isInvalid() && "Expected valid file ID");
  1252. // Finally, if all is good, enter the new file!
  1253. EnterSourceFile(FID, CurDir, FilenameTok.getLocation());
  1254. }
  1255. /// HandleIncludeNextDirective - Implements #include_next.
  1256. ///
  1257. void Preprocessor::HandleIncludeNextDirective(SourceLocation HashLoc,
  1258. Token &IncludeNextTok) {
  1259. Diag(IncludeNextTok, diag::ext_pp_include_next_directive);
  1260. // #include_next is like #include, except that we start searching after
  1261. // the current found directory. If we can't do this, issue a
  1262. // diagnostic.
  1263. const DirectoryLookup *Lookup = CurDirLookup;
  1264. if (isInPrimaryFile()) {
  1265. Lookup = 0;
  1266. Diag(IncludeNextTok, diag::pp_include_next_in_primary);
  1267. } else if (Lookup == 0) {
  1268. Diag(IncludeNextTok, diag::pp_include_next_absolute_path);
  1269. } else {
  1270. // Start looking up in the next directory.
  1271. ++Lookup;
  1272. }
  1273. return HandleIncludeDirective(HashLoc, IncludeNextTok, Lookup);
  1274. }
  1275. /// HandleImportDirective - Implements #import.
  1276. ///
  1277. void Preprocessor::HandleImportDirective(SourceLocation HashLoc,
  1278. Token &ImportTok) {
  1279. if (!LangOpts.ObjC1) // #import is standard for ObjC.
  1280. Diag(ImportTok, diag::ext_pp_import_directive);
  1281. return HandleIncludeDirective(HashLoc, ImportTok, 0, true);
  1282. }
  1283. /// HandleIncludeMacrosDirective - The -imacros command line option turns into a
  1284. /// pseudo directive in the predefines buffer. This handles it by sucking all
  1285. /// tokens through the preprocessor and discarding them (only keeping the side
  1286. /// effects on the preprocessor).
  1287. void Preprocessor::HandleIncludeMacrosDirective(SourceLocation HashLoc,
  1288. Token &IncludeMacrosTok) {
  1289. // This directive should only occur in the predefines buffer. If not, emit an
  1290. // error and reject it.
  1291. SourceLocation Loc = IncludeMacrosTok.getLocation();
  1292. if (strcmp(SourceMgr.getBufferName(Loc), "<built-in>") != 0) {
  1293. Diag(IncludeMacrosTok.getLocation(),
  1294. diag::pp_include_macros_out_of_predefines);
  1295. DiscardUntilEndOfDirective();
  1296. return;
  1297. }
  1298. // Treat this as a normal #include for checking purposes. If this is
  1299. // successful, it will push a new lexer onto the include stack.
  1300. HandleIncludeDirective(HashLoc, IncludeMacrosTok, 0, false);
  1301. Token TmpTok;
  1302. do {
  1303. Lex(TmpTok);
  1304. assert(TmpTok.isNot(tok::eof) && "Didn't find end of -imacros!");
  1305. } while (TmpTok.isNot(tok::hashhash));
  1306. }
  1307. //===----------------------------------------------------------------------===//
  1308. // Preprocessor Macro Directive Handling.
  1309. //===----------------------------------------------------------------------===//
  1310. /// ReadMacroDefinitionArgList - The ( starting an argument list of a macro
  1311. /// definition has just been read. Lex the rest of the arguments and the
  1312. /// closing ), updating MI with what we learn. Return true if an error occurs
  1313. /// parsing the arg list.
  1314. bool Preprocessor::ReadMacroDefinitionArgList(MacroInfo *MI) {
  1315. SmallVector<IdentifierInfo*, 32> Arguments;
  1316. Token Tok;
  1317. while (1) {
  1318. LexUnexpandedToken(Tok);
  1319. switch (Tok.getKind()) {
  1320. case tok::r_paren:
  1321. // Found the end of the argument list.
  1322. if (Arguments.empty()) // #define FOO()
  1323. return false;
  1324. // Otherwise we have #define FOO(A,)
  1325. Diag(Tok, diag::err_pp_expected_ident_in_arg_list);
  1326. return true;
  1327. case tok::ellipsis: // #define X(... -> C99 varargs
  1328. if (!LangOpts.C99)
  1329. Diag(Tok, LangOpts.CPlusPlus0x ?
  1330. diag::warn_cxx98_compat_variadic_macro :
  1331. diag::ext_variadic_macro);
  1332. // Lex the token after the identifier.
  1333. LexUnexpandedToken(Tok);
  1334. if (Tok.isNot(tok::r_paren)) {
  1335. Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
  1336. return true;
  1337. }
  1338. // Add the __VA_ARGS__ identifier as an argument.
  1339. Arguments.push_back(Ident__VA_ARGS__);
  1340. MI->setIsC99Varargs();
  1341. MI->setArgumentList(&Arguments[0], Arguments.size(), BP);
  1342. return false;
  1343. case tok::eod: // #define X(
  1344. Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
  1345. return true;
  1346. default:
  1347. // Handle keywords and identifiers here to accept things like
  1348. // #define Foo(for) for.
  1349. IdentifierInfo *II = Tok.getIdentifierInfo();
  1350. if (II == 0) {
  1351. // #define X(1
  1352. Diag(Tok, diag::err_pp_invalid_tok_in_arg_list);
  1353. return true;
  1354. }
  1355. // If this is already used as an argument, it is used multiple times (e.g.
  1356. // #define X(A,A.
  1357. if (std::find(Arguments.begin(), Arguments.end(), II) !=
  1358. Arguments.end()) { // C99 6.10.3p6
  1359. Diag(Tok, diag::err_pp_duplicate_name_in_arg_list) << II;
  1360. return true;
  1361. }
  1362. // Add the argument to the macro info.
  1363. Arguments.push_back(II);
  1364. // Lex the token after the identifier.
  1365. LexUnexpandedToken(Tok);
  1366. switch (Tok.getKind()) {
  1367. default: // #define X(A B
  1368. Diag(Tok, diag::err_pp_expected_comma_in_arg_list);
  1369. return true;
  1370. case tok::r_paren: // #define X(A)
  1371. MI->setArgumentList(&Arguments[0], Arguments.size(), BP);
  1372. return false;
  1373. case tok::comma: // #define X(A,
  1374. break;
  1375. case tok::ellipsis: // #define X(A... -> GCC extension
  1376. // Diagnose extension.
  1377. Diag(Tok, diag::ext_named_variadic_macro);
  1378. // Lex the token after the identifier.
  1379. LexUnexpandedToken(Tok);
  1380. if (Tok.isNot(tok::r_paren)) {
  1381. Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
  1382. return true;
  1383. }
  1384. MI->setIsGNUVarargs();
  1385. MI->setArgumentList(&Arguments[0], Arguments.size(), BP);
  1386. return false;
  1387. }
  1388. }
  1389. }
  1390. }
  1391. /// HandleDefineDirective - Implements #define. This consumes the entire macro
  1392. /// line then lets the caller lex the next real token.
  1393. void Preprocessor::HandleDefineDirective(Token &DefineTok) {
  1394. ++NumDefined;
  1395. Token MacroNameTok;
  1396. ReadMacroName(MacroNameTok, 1);
  1397. // Error reading macro name? If so, diagnostic already issued.
  1398. if (MacroNameTok.is(tok::eod))
  1399. return;
  1400. Token LastTok = MacroNameTok;
  1401. // If we are supposed to keep comments in #defines, reenable comment saving
  1402. // mode.
  1403. if (CurLexer) CurLexer->SetCommentRetentionState(KeepMacroComments);
  1404. // Create the new macro.
  1405. MacroInfo *MI = AllocateMacroInfo(MacroNameTok.getLocation());
  1406. Token Tok;
  1407. LexUnexpandedToken(Tok);
  1408. // If this is a function-like macro definition, parse the argument list,
  1409. // marking each of the identifiers as being used as macro arguments. Also,
  1410. // check other constraints on the first token of the macro body.
  1411. if (Tok.is(tok::eod)) {
  1412. // If there is no body to this macro, we have no special handling here.
  1413. } else if (Tok.hasLeadingSpace()) {
  1414. // This is a normal token with leading space. Clear the leading space
  1415. // marker on the first token to get proper expansion.
  1416. Tok.clearFlag(Token::LeadingSpace);
  1417. } else if (Tok.is(tok::l_paren)) {
  1418. // This is a function-like macro definition. Read the argument list.
  1419. MI->setIsFunctionLike();
  1420. if (ReadMacroDefinitionArgList(MI)) {
  1421. // Forget about MI.
  1422. ReleaseMacroInfo(MI);
  1423. // Throw away the rest of the line.
  1424. if (CurPPLexer->ParsingPreprocessorDirective)
  1425. DiscardUntilEndOfDirective();
  1426. return;
  1427. }
  1428. // If this is a definition of a variadic C99 function-like macro, not using
  1429. // the GNU named varargs extension, enabled __VA_ARGS__.
  1430. // "Poison" __VA_ARGS__, which can only appear in the expansion of a macro.
  1431. // This gets unpoisoned where it is allowed.
  1432. assert(Ident__VA_ARGS__->isPoisoned() && "__VA_ARGS__ should be poisoned!");
  1433. if (MI->isC99Varargs())
  1434. Ident__VA_ARGS__->setIsPoisoned(false);
  1435. // Read the first token after the arg list for down below.
  1436. LexUnexpandedToken(Tok);
  1437. } else if (LangOpts.C99 || LangOpts.CPlusPlus0x) {
  1438. // C99 requires whitespace between the macro definition and the body. Emit
  1439. // a diagnostic for something like "#define X+".
  1440. Diag(Tok, diag::ext_c99_whitespace_required_after_macro_name);
  1441. } else {
  1442. // C90 6.8 TC1 says: "In the definition of an object-like macro, if the
  1443. // first character of a replacement list is not a character required by
  1444. // subclause 5.2.1, then there shall be white-space separation between the
  1445. // identifier and the replacement list.". 5.2.1 lists this set:
  1446. // "A-Za-z0-9!"#%&'()*+,_./:;<=>?[\]^_{|}~" as well as whitespace, which
  1447. // is irrelevant here.
  1448. bool isInvalid = false;
  1449. if (Tok.is(tok::at)) // @ is not in the list above.
  1450. isInvalid = true;
  1451. else if (Tok.is(tok::unknown)) {
  1452. // If we have an unknown token, it is something strange like "`". Since
  1453. // all of valid characters would have lexed into a single character
  1454. // token of some sort, we know this is not a valid case.
  1455. isInvalid = true;
  1456. }
  1457. if (isInvalid)
  1458. Diag(Tok, diag::ext_missing_whitespace_after_macro_name);
  1459. else
  1460. Diag(Tok, diag::warn_missing_whitespace_after_macro_name);
  1461. }
  1462. if (!Tok.is(tok::eod))
  1463. LastTok = Tok;
  1464. // Read the rest of the macro body.
  1465. if (MI->isObjectLike()) {
  1466. // Object-like macros are very simple, just read their body.
  1467. while (Tok.isNot(tok::eod)) {
  1468. LastTok = Tok;
  1469. MI->AddTokenToBody(Tok);
  1470. // Get the next token of the macro.
  1471. LexUnexpandedToken(Tok);
  1472. }
  1473. } else {
  1474. // Otherwise, read the body of a function-like macro. While we are at it,
  1475. // check C99 6.10.3.2p1: ensure that # operators are followed by macro
  1476. // parameters in function-like macro expansions.
  1477. while (Tok.isNot(tok::eod)) {
  1478. LastTok = Tok;
  1479. if (Tok.isNot(tok::hash)) {
  1480. MI->AddTokenToBody(Tok);
  1481. // Get the next token of the macro.
  1482. LexUnexpandedToken(Tok);
  1483. continue;
  1484. }
  1485. // Get the next token of the macro.
  1486. LexUnexpandedToken(Tok);
  1487. // Check for a valid macro arg identifier.
  1488. if (Tok.getIdentifierInfo() == 0 ||
  1489. MI->getArgumentNum(Tok.getIdentifierInfo()) == -1) {
  1490. // If this is assembler-with-cpp mode, we accept random gibberish after
  1491. // the '#' because '#' is often a comment character. However, change
  1492. // the kind of the token to tok::unknown so that the preprocessor isn't
  1493. // confused.
  1494. if (getLangOpts().AsmPreprocessor && Tok.isNot(tok::eod)) {
  1495. LastTok.setKind(tok::unknown);
  1496. } else {
  1497. Diag(Tok, diag::err_pp_stringize_not_parameter);
  1498. ReleaseMacroInfo(MI);
  1499. // Disable __VA_ARGS__ again.
  1500. Ident__VA_ARGS__->setIsPoisoned(true);
  1501. return;
  1502. }
  1503. }
  1504. // Things look ok, add the '#' and param name tokens to the macro.
  1505. MI->AddTokenToBody(LastTok);
  1506. MI->AddTokenToBody(Tok);
  1507. LastTok = Tok;
  1508. // Get the next token of the macro.
  1509. LexUnexpandedToken(Tok);
  1510. }
  1511. }
  1512. // Disable __VA_ARGS__ again.
  1513. Ident__VA_ARGS__->setIsPoisoned(true);
  1514. // Check that there is no paste (##) operator at the beginning or end of the
  1515. // replacement list.
  1516. unsigned NumTokens = MI->getNumTokens();
  1517. if (NumTokens != 0) {
  1518. if (MI->getReplacementToken(0).is(tok::hashhash)) {
  1519. Diag(MI->getReplacementToken(0), diag::err_paste_at_start);
  1520. ReleaseMacroInfo(MI);
  1521. return;
  1522. }
  1523. if (MI->getReplacementToken(NumTokens-1).is(tok::hashhash)) {
  1524. Diag(MI->getReplacementToken(NumTokens-1), diag::err_paste_at_end);
  1525. ReleaseMacroInfo(MI);
  1526. return;
  1527. }
  1528. }
  1529. MI->setDefinitionEndLoc(LastTok.getLocation());
  1530. // Finally, if this identifier already had a macro defined for it, verify that
  1531. // the macro bodies are identical and free the old definition.
  1532. if (MacroInfo *OtherMI = getMacroInfo(MacroNameTok.getIdentifierInfo())) {
  1533. // It is very common for system headers to have tons of macro redefinitions
  1534. // and for warnings to be disabled in system headers. If this is the case,
  1535. // then don't bother calling MacroInfo::isIdenticalTo.
  1536. if (!getDiagnostics().getSuppressSystemWarnings() ||
  1537. !SourceMgr.isInSystemHeader(DefineTok.getLocation())) {
  1538. if (!OtherMI->isUsed() && OtherMI->isWarnIfUnused())
  1539. Diag(OtherMI->getDefinitionLoc(), diag::pp_macro_not_used);
  1540. // Macros must be identical. This means all tokens and whitespace
  1541. // separation must be the same. C99 6.10.3.2.
  1542. if (!OtherMI->isAllowRedefinitionsWithoutWarning() &&
  1543. !MI->isIdenticalTo(*OtherMI, *this)) {
  1544. Diag(MI->getDefinitionLoc(), diag::ext_pp_macro_redef)
  1545. << MacroNameTok.getIdentifierInfo();
  1546. Diag(OtherMI->getDefinitionLoc(), diag::note_previous_definition);
  1547. }
  1548. }
  1549. if (OtherMI->isWarnIfUnused())
  1550. WarnUnusedMacroLocs.erase(OtherMI->getDefinitionLoc());
  1551. ReleaseMacroInfo(OtherMI);
  1552. }
  1553. setMacroInfo(MacroNameTok.getIdentifierInfo(), MI);
  1554. assert(!MI->isUsed());
  1555. // If we need warning for not using the macro, add its location in the
  1556. // warn-because-unused-macro set. If it gets used it will be removed from set.
  1557. if (isInPrimaryFile() && // don't warn for include'd macros.
  1558. Diags->getDiagnosticLevel(diag::pp_macro_not_used,
  1559. MI->getDefinitionLoc()) != DiagnosticsEngine::Ignored) {
  1560. MI->setIsWarnIfUnused(true);
  1561. WarnUnusedMacroLocs.insert(MI->getDefinitionLoc());
  1562. }
  1563. // If the callbacks want to know, tell them about the macro definition.
  1564. if (Callbacks)
  1565. Callbacks->MacroDefined(MacroNameTok, MI);
  1566. }
  1567. /// HandleUndefDirective - Implements #undef.
  1568. ///
  1569. void Preprocessor::HandleUndefDirective(Token &UndefTok) {
  1570. ++NumUndefined;
  1571. Token MacroNameTok;
  1572. ReadMacroName(MacroNameTok, 2);
  1573. // Error reading macro name? If so, diagnostic already issued.
  1574. if (MacroNameTok.is(tok::eod))
  1575. return;
  1576. // Check to see if this is the last token on the #undef line.
  1577. CheckEndOfDirective("undef");
  1578. // Okay, we finally have a valid identifier to undef.
  1579. MacroInfo *MI = getMacroInfo(MacroNameTok.getIdentifierInfo());
  1580. // If the macro is not defined, this is a noop undef, just return.
  1581. if (MI == 0) return;
  1582. if (!MI->isUsed() && MI->isWarnIfUnused())
  1583. Diag(MI->getDefinitionLoc(), diag::pp_macro_not_used);
  1584. // If the callbacks want to know, tell them about the macro #undef.
  1585. if (Callbacks)
  1586. Callbacks->MacroUndefined(MacroNameTok, MI);
  1587. if (MI->isWarnIfUnused())
  1588. WarnUnusedMacroLocs.erase(MI->getDefinitionLoc());
  1589. // Free macro definition.
  1590. ReleaseMacroInfo(MI);
  1591. setMacroInfo(MacroNameTok.getIdentifierInfo(), 0);
  1592. }
  1593. //===----------------------------------------------------------------------===//
  1594. // Preprocessor Conditional Directive Handling.
  1595. //===----------------------------------------------------------------------===//
  1596. /// HandleIfdefDirective - Implements the #ifdef/#ifndef directive. isIfndef is
  1597. /// true when this is a #ifndef directive. ReadAnyTokensBeforeDirective is true
  1598. /// if any tokens have been returned or pp-directives activated before this
  1599. /// #ifndef has been lexed.
  1600. ///
  1601. void Preprocessor::HandleIfdefDirective(Token &Result, bool isIfndef,
  1602. bool ReadAnyTokensBeforeDirective) {
  1603. ++NumIf;
  1604. Token DirectiveTok = Result;
  1605. Token MacroNameTok;
  1606. ReadMacroName(MacroNameTok);
  1607. // Error reading macro name? If so, diagnostic already issued.
  1608. if (MacroNameTok.is(tok::eod)) {
  1609. // Skip code until we get to #endif. This helps with recovery by not
  1610. // emitting an error when the #endif is reached.
  1611. SkipExcludedConditionalBlock(DirectiveTok.getLocation(),
  1612. /*Foundnonskip*/false, /*FoundElse*/false);
  1613. return;
  1614. }
  1615. // Check to see if this is the last token on the #if[n]def line.
  1616. CheckEndOfDirective(isIfndef ? "ifndef" : "ifdef");
  1617. IdentifierInfo *MII = MacroNameTok.getIdentifierInfo();
  1618. MacroInfo *MI = getMacroInfo(MII);
  1619. if (CurPPLexer->getConditionalStackDepth() == 0) {
  1620. // If the start of a top-level #ifdef and if the macro is not defined,
  1621. // inform MIOpt that this might be the start of a proper include guard.
  1622. // Otherwise it is some other form of unknown conditional which we can't
  1623. // handle.
  1624. if (!ReadAnyTokensBeforeDirective && MI == 0) {
  1625. assert(isIfndef && "#ifdef shouldn't reach here");
  1626. CurPPLexer->MIOpt.EnterTopLevelIFNDEF(MII);
  1627. } else
  1628. CurPPLexer->MIOpt.EnterTopLevelConditional();
  1629. }
  1630. // If there is a macro, process it.
  1631. if (MI) // Mark it used.
  1632. markMacroAsUsed(MI);
  1633. if (Callbacks) {
  1634. if (isIfndef)
  1635. Callbacks->Ifndef(DirectiveTok.getLocation(), MacroNameTok);
  1636. else
  1637. Callbacks->Ifdef(DirectiveTok.getLocation(), MacroNameTok);
  1638. }
  1639. // Should we include the stuff contained by this directive?
  1640. if (!MI == isIfndef) {
  1641. // Yes, remember that we are inside a conditional, then lex the next token.
  1642. CurPPLexer->pushConditionalLevel(DirectiveTok.getLocation(),
  1643. /*wasskip*/false, /*foundnonskip*/true,
  1644. /*foundelse*/false);
  1645. } else {
  1646. // No, skip the contents of this block.
  1647. SkipExcludedConditionalBlock(DirectiveTok.getLocation(),
  1648. /*Foundnonskip*/false,
  1649. /*FoundElse*/false);
  1650. }
  1651. }
  1652. /// HandleIfDirective - Implements the #if directive.
  1653. ///
  1654. void Preprocessor::HandleIfDirective(Token &IfToken,
  1655. bool ReadAnyTokensBeforeDirective) {
  1656. ++NumIf;
  1657. // Parse and evaluate the conditional expression.
  1658. IdentifierInfo *IfNDefMacro = 0;
  1659. const SourceLocation ConditionalBegin = CurPPLexer->getSourceLocation();
  1660. const bool ConditionalTrue = EvaluateDirectiveExpression(IfNDefMacro);
  1661. const SourceLocation ConditionalEnd = CurPPLexer->getSourceLocation();
  1662. // If this condition is equivalent to #ifndef X, and if this is the first
  1663. // directive seen, handle it for the multiple-include optimization.
  1664. if (CurPPLexer->getConditionalStackDepth() == 0) {
  1665. if (!ReadAnyTokensBeforeDirective && IfNDefMacro && ConditionalTrue)
  1666. CurPPLexer->MIOpt.EnterTopLevelIFNDEF(IfNDefMacro);
  1667. else
  1668. CurPPLexer->MIOpt.EnterTopLevelConditional();
  1669. }
  1670. if (Callbacks)
  1671. Callbacks->If(IfToken.getLocation(),
  1672. SourceRange(ConditionalBegin, ConditionalEnd));
  1673. // Should we include the stuff contained by this directive?
  1674. if (ConditionalTrue) {
  1675. // Yes, remember that we are inside a conditional, then lex the next token.
  1676. CurPPLexer->pushConditionalLevel(IfToken.getLocation(), /*wasskip*/false,
  1677. /*foundnonskip*/true, /*foundelse*/false);
  1678. } else {
  1679. // No, skip the contents of this block.
  1680. SkipExcludedConditionalBlock(IfToken.getLocation(), /*Foundnonskip*/false,
  1681. /*FoundElse*/false);
  1682. }
  1683. }
  1684. /// HandleEndifDirective - Implements the #endif directive.
  1685. ///
  1686. void Preprocessor::HandleEndifDirective(Token &EndifToken) {
  1687. ++NumEndif;
  1688. // Check that this is the whole directive.
  1689. CheckEndOfDirective("endif");
  1690. PPConditionalInfo CondInfo;
  1691. if (CurPPLexer->popConditionalLevel(CondInfo)) {
  1692. // No conditionals on the stack: this is an #endif without an #if.
  1693. Diag(EndifToken, diag::err_pp_endif_without_if);
  1694. return;
  1695. }
  1696. // If this the end of a top-level #endif, inform MIOpt.
  1697. if (CurPPLexer->getConditionalStackDepth() == 0)
  1698. CurPPLexer->MIOpt.ExitTopLevelConditional();
  1699. assert(!CondInfo.WasSkipping && !CurPPLexer->LexingRawMode &&
  1700. "This code should only be reachable in the non-skipping case!");
  1701. if (Callbacks)
  1702. Callbacks->Endif(EndifToken.getLocation(), CondInfo.IfLoc);
  1703. }
  1704. /// HandleElseDirective - Implements the #else directive.
  1705. ///
  1706. void Preprocessor::HandleElseDirective(Token &Result) {
  1707. ++NumElse;
  1708. // #else directive in a non-skipping conditional... start skipping.
  1709. CheckEndOfDirective("else");
  1710. PPConditionalInfo CI;
  1711. if (CurPPLexer->popConditionalLevel(CI)) {
  1712. Diag(Result, diag::pp_err_else_without_if);
  1713. return;
  1714. }
  1715. // If this is a top-level #else, inform the MIOpt.
  1716. if (CurPPLexer->getConditionalStackDepth() == 0)
  1717. CurPPLexer->MIOpt.EnterTopLevelConditional();
  1718. // If this is a #else with a #else before it, report the error.
  1719. if (CI.FoundElse) Diag(Result, diag::pp_err_else_after_else);
  1720. if (Callbacks)
  1721. Callbacks->Else(Result.getLocation(), CI.IfLoc);
  1722. // Finally, skip the rest of the contents of this block.
  1723. SkipExcludedConditionalBlock(CI.IfLoc, /*Foundnonskip*/true,
  1724. /*FoundElse*/true, Result.getLocation());
  1725. }
  1726. /// HandleElifDirective - Implements the #elif directive.
  1727. ///
  1728. void Preprocessor::HandleElifDirective(Token &ElifToken) {
  1729. ++NumElse;
  1730. // #elif directive in a non-skipping conditional... start skipping.
  1731. // We don't care what the condition is, because we will always skip it (since
  1732. // the block immediately before it was included).
  1733. const SourceLocation ConditionalBegin = CurPPLexer->getSourceLocation();
  1734. DiscardUntilEndOfDirective();
  1735. const SourceLocation ConditionalEnd = CurPPLexer->getSourceLocation();
  1736. PPConditionalInfo CI;
  1737. if (CurPPLexer->popConditionalLevel(CI)) {
  1738. Diag(ElifToken, diag::pp_err_elif_without_if);
  1739. return;
  1740. }
  1741. // If this is a top-level #elif, inform the MIOpt.
  1742. if (CurPPLexer->getConditionalStackDepth() == 0)
  1743. CurPPLexer->MIOpt.EnterTopLevelConditional();
  1744. // If this is a #elif with a #else before it, report the error.
  1745. if (CI.FoundElse) Diag(ElifToken, diag::pp_err_elif_after_else);
  1746. if (Callbacks)
  1747. Callbacks->Elif(ElifToken.getLocation(),
  1748. SourceRange(ConditionalBegin, ConditionalEnd), CI.IfLoc);
  1749. // Finally, skip the rest of the contents of this block.
  1750. SkipExcludedConditionalBlock(CI.IfLoc, /*Foundnonskip*/true,
  1751. /*FoundElse*/CI.FoundElse,
  1752. ElifToken.getLocation());
  1753. }