PPDirectives.cpp 128 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323
  1. //===--- PPDirectives.cpp - Directive Handling for Preprocessor -----------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. ///
  9. /// \file
  10. /// Implements # directive processing for the Preprocessor.
  11. ///
  12. //===----------------------------------------------------------------------===//
  13. #include "clang/Basic/CharInfo.h"
  14. #include "clang/Basic/FileManager.h"
  15. #include "clang/Basic/IdentifierTable.h"
  16. #include "clang/Basic/LangOptions.h"
  17. #include "clang/Basic/Module.h"
  18. #include "clang/Basic/SourceLocation.h"
  19. #include "clang/Basic/SourceManager.h"
  20. #include "clang/Basic/TokenKinds.h"
  21. #include "clang/Lex/CodeCompletionHandler.h"
  22. #include "clang/Lex/HeaderSearch.h"
  23. #include "clang/Lex/LexDiagnostic.h"
  24. #include "clang/Lex/LiteralSupport.h"
  25. #include "clang/Lex/MacroInfo.h"
  26. #include "clang/Lex/ModuleLoader.h"
  27. #include "clang/Lex/ModuleMap.h"
  28. #include "clang/Lex/PPCallbacks.h"
  29. #include "clang/Lex/Pragma.h"
  30. #include "clang/Lex/Preprocessor.h"
  31. #include "clang/Lex/PreprocessorOptions.h"
  32. #include "clang/Lex/Token.h"
  33. #include "clang/Lex/VariadicMacroSupport.h"
  34. #include "llvm/ADT/ArrayRef.h"
  35. #include "llvm/ADT/ScopeExit.h"
  36. #include "llvm/ADT/SmallString.h"
  37. #include "llvm/ADT/SmallVector.h"
  38. #include "llvm/ADT/STLExtras.h"
  39. #include "llvm/ADT/StringSwitch.h"
  40. #include "llvm/ADT/StringRef.h"
  41. #include "llvm/Support/AlignOf.h"
  42. #include "llvm/Support/ErrorHandling.h"
  43. #include "llvm/Support/Path.h"
  44. #include <algorithm>
  45. #include <cassert>
  46. #include <cstring>
  47. #include <new>
  48. #include <string>
  49. #include <utility>
  50. using namespace clang;
  51. //===----------------------------------------------------------------------===//
  52. // Utility Methods for Preprocessor Directive Handling.
  53. //===----------------------------------------------------------------------===//
  54. MacroInfo *Preprocessor::AllocateMacroInfo(SourceLocation L) {
  55. auto *MIChain = new (BP) MacroInfoChain{L, MIChainHead};
  56. MIChainHead = MIChain;
  57. return &MIChain->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. /// Read and discard all tokens remaining on the current line until
  73. /// the tok::eod token is found.
  74. SourceRange Preprocessor::DiscardUntilEndOfDirective() {
  75. Token Tmp;
  76. SourceRange Res;
  77. LexUnexpandedToken(Tmp);
  78. Res.setBegin(Tmp.getLocation());
  79. while (Tmp.isNot(tok::eod)) {
  80. assert(Tmp.isNot(tok::eof) && "EOF seen while discarding directive tokens");
  81. LexUnexpandedToken(Tmp);
  82. }
  83. Res.setEnd(Tmp.getLocation());
  84. return Res;
  85. }
  86. /// Enumerates possible cases of #define/#undef a reserved identifier.
  87. enum MacroDiag {
  88. MD_NoWarn, //> Not a reserved identifier
  89. MD_KeywordDef, //> Macro hides keyword, enabled by default
  90. MD_ReservedMacro //> #define of #undef reserved id, disabled by default
  91. };
  92. /// Enumerates possible %select values for the pp_err_elif_after_else and
  93. /// pp_err_elif_without_if diagnostics.
  94. enum PPElifDiag {
  95. PED_Elif,
  96. PED_Elifdef,
  97. PED_Elifndef
  98. };
  99. // The -fmodule-name option tells the compiler to textually include headers in
  100. // the specified module, meaning clang won't build the specified module. This is
  101. // useful in a number of situations, for instance, when building a library that
  102. // vends a module map, one might want to avoid hitting intermediate build
  103. // products containimg the module map or avoid finding the system installed
  104. // modulemap for that library.
  105. static bool isForModuleBuilding(Module *M, StringRef CurrentModule,
  106. StringRef ModuleName) {
  107. StringRef TopLevelName = M->getTopLevelModuleName();
  108. // When building framework Foo, we wanna make sure that Foo *and* Foo_Private
  109. // are textually included and no modules are built for both.
  110. if (M->getTopLevelModule()->IsFramework && CurrentModule == ModuleName &&
  111. !CurrentModule.endswith("_Private") && TopLevelName.endswith("_Private"))
  112. TopLevelName = TopLevelName.drop_back(8);
  113. return TopLevelName == CurrentModule;
  114. }
  115. static MacroDiag shouldWarnOnMacroDef(Preprocessor &PP, IdentifierInfo *II) {
  116. const LangOptions &Lang = PP.getLangOpts();
  117. if (isReservedInAllContexts(II->isReserved(Lang))) {
  118. // list from:
  119. // - https://gcc.gnu.org/onlinedocs/libstdc++/manual/using_macros.html
  120. // - https://docs.microsoft.com/en-us/cpp/c-runtime-library/security-features-in-the-crt?view=msvc-160
  121. // - man 7 feature_test_macros
  122. // The list must be sorted for correct binary search.
  123. static constexpr StringRef ReservedMacro[] = {
  124. "_ATFILE_SOURCE",
  125. "_BSD_SOURCE",
  126. "_CRT_NONSTDC_NO_WARNINGS",
  127. "_CRT_SECURE_CPP_OVERLOAD_STANDARD_NAMES",
  128. "_CRT_SECURE_NO_WARNINGS",
  129. "_FILE_OFFSET_BITS",
  130. "_FORTIFY_SOURCE",
  131. "_GLIBCXX_ASSERTIONS",
  132. "_GLIBCXX_CONCEPT_CHECKS",
  133. "_GLIBCXX_DEBUG",
  134. "_GLIBCXX_DEBUG_PEDANTIC",
  135. "_GLIBCXX_PARALLEL",
  136. "_GLIBCXX_PARALLEL_ASSERTIONS",
  137. "_GLIBCXX_SANITIZE_VECTOR",
  138. "_GLIBCXX_USE_CXX11_ABI",
  139. "_GLIBCXX_USE_DEPRECATED",
  140. "_GNU_SOURCE",
  141. "_ISOC11_SOURCE",
  142. "_ISOC95_SOURCE",
  143. "_ISOC99_SOURCE",
  144. "_LARGEFILE64_SOURCE",
  145. "_POSIX_C_SOURCE",
  146. "_REENTRANT",
  147. "_SVID_SOURCE",
  148. "_THREAD_SAFE",
  149. "_XOPEN_SOURCE",
  150. "_XOPEN_SOURCE_EXTENDED",
  151. "__STDCPP_WANT_MATH_SPEC_FUNCS__",
  152. "__STDC_FORMAT_MACROS",
  153. };
  154. if (std::binary_search(std::begin(ReservedMacro), std::end(ReservedMacro),
  155. II->getName()))
  156. return MD_NoWarn;
  157. return MD_ReservedMacro;
  158. }
  159. StringRef Text = II->getName();
  160. if (II->isKeyword(Lang))
  161. return MD_KeywordDef;
  162. if (Lang.CPlusPlus11 && (Text.equals("override") || Text.equals("final")))
  163. return MD_KeywordDef;
  164. return MD_NoWarn;
  165. }
  166. static MacroDiag shouldWarnOnMacroUndef(Preprocessor &PP, IdentifierInfo *II) {
  167. const LangOptions &Lang = PP.getLangOpts();
  168. // Do not warn on keyword undef. It is generally harmless and widely used.
  169. if (isReservedInAllContexts(II->isReserved(Lang)))
  170. return MD_ReservedMacro;
  171. return MD_NoWarn;
  172. }
  173. // Return true if we want to issue a diagnostic by default if we
  174. // encounter this name in a #include with the wrong case. For now,
  175. // this includes the standard C and C++ headers, Posix headers,
  176. // and Boost headers. Improper case for these #includes is a
  177. // potential portability issue.
  178. static bool warnByDefaultOnWrongCase(StringRef Include) {
  179. // If the first component of the path is "boost", treat this like a standard header
  180. // for the purposes of diagnostics.
  181. if (::llvm::sys::path::begin(Include)->equals_insensitive("boost"))
  182. return true;
  183. // "condition_variable" is the longest standard header name at 18 characters.
  184. // If the include file name is longer than that, it can't be a standard header.
  185. static const size_t MaxStdHeaderNameLen = 18u;
  186. if (Include.size() > MaxStdHeaderNameLen)
  187. return false;
  188. // Lowercase and normalize the search string.
  189. SmallString<32> LowerInclude{Include};
  190. for (char &Ch : LowerInclude) {
  191. // In the ASCII range?
  192. if (static_cast<unsigned char>(Ch) > 0x7f)
  193. return false; // Can't be a standard header
  194. // ASCII lowercase:
  195. if (Ch >= 'A' && Ch <= 'Z')
  196. Ch += 'a' - 'A';
  197. // Normalize path separators for comparison purposes.
  198. else if (::llvm::sys::path::is_separator(Ch))
  199. Ch = '/';
  200. }
  201. // The standard C/C++ and Posix headers
  202. return llvm::StringSwitch<bool>(LowerInclude)
  203. // C library headers
  204. .Cases("assert.h", "complex.h", "ctype.h", "errno.h", "fenv.h", true)
  205. .Cases("float.h", "inttypes.h", "iso646.h", "limits.h", "locale.h", true)
  206. .Cases("math.h", "setjmp.h", "signal.h", "stdalign.h", "stdarg.h", true)
  207. .Cases("stdatomic.h", "stdbool.h", "stddef.h", "stdint.h", "stdio.h", true)
  208. .Cases("stdlib.h", "stdnoreturn.h", "string.h", "tgmath.h", "threads.h", true)
  209. .Cases("time.h", "uchar.h", "wchar.h", "wctype.h", true)
  210. // C++ headers for C library facilities
  211. .Cases("cassert", "ccomplex", "cctype", "cerrno", "cfenv", true)
  212. .Cases("cfloat", "cinttypes", "ciso646", "climits", "clocale", true)
  213. .Cases("cmath", "csetjmp", "csignal", "cstdalign", "cstdarg", true)
  214. .Cases("cstdbool", "cstddef", "cstdint", "cstdio", "cstdlib", true)
  215. .Cases("cstring", "ctgmath", "ctime", "cuchar", "cwchar", true)
  216. .Case("cwctype", true)
  217. // C++ library headers
  218. .Cases("algorithm", "fstream", "list", "regex", "thread", true)
  219. .Cases("array", "functional", "locale", "scoped_allocator", "tuple", true)
  220. .Cases("atomic", "future", "map", "set", "type_traits", true)
  221. .Cases("bitset", "initializer_list", "memory", "shared_mutex", "typeindex", true)
  222. .Cases("chrono", "iomanip", "mutex", "sstream", "typeinfo", true)
  223. .Cases("codecvt", "ios", "new", "stack", "unordered_map", true)
  224. .Cases("complex", "iosfwd", "numeric", "stdexcept", "unordered_set", true)
  225. .Cases("condition_variable", "iostream", "ostream", "streambuf", "utility", true)
  226. .Cases("deque", "istream", "queue", "string", "valarray", true)
  227. .Cases("exception", "iterator", "random", "strstream", "vector", true)
  228. .Cases("forward_list", "limits", "ratio", "system_error", true)
  229. // POSIX headers (which aren't also C headers)
  230. .Cases("aio.h", "arpa/inet.h", "cpio.h", "dirent.h", "dlfcn.h", true)
  231. .Cases("fcntl.h", "fmtmsg.h", "fnmatch.h", "ftw.h", "glob.h", true)
  232. .Cases("grp.h", "iconv.h", "langinfo.h", "libgen.h", "monetary.h", true)
  233. .Cases("mqueue.h", "ndbm.h", "net/if.h", "netdb.h", "netinet/in.h", true)
  234. .Cases("netinet/tcp.h", "nl_types.h", "poll.h", "pthread.h", "pwd.h", true)
  235. .Cases("regex.h", "sched.h", "search.h", "semaphore.h", "spawn.h", true)
  236. .Cases("strings.h", "stropts.h", "sys/ipc.h", "sys/mman.h", "sys/msg.h", true)
  237. .Cases("sys/resource.h", "sys/select.h", "sys/sem.h", "sys/shm.h", "sys/socket.h", true)
  238. .Cases("sys/stat.h", "sys/statvfs.h", "sys/time.h", "sys/times.h", "sys/types.h", true)
  239. .Cases("sys/uio.h", "sys/un.h", "sys/utsname.h", "sys/wait.h", "syslog.h", true)
  240. .Cases("tar.h", "termios.h", "trace.h", "ulimit.h", true)
  241. .Cases("unistd.h", "utime.h", "utmpx.h", "wordexp.h", true)
  242. .Default(false);
  243. }
  244. bool Preprocessor::CheckMacroName(Token &MacroNameTok, MacroUse isDefineUndef,
  245. bool *ShadowFlag) {
  246. // Missing macro name?
  247. if (MacroNameTok.is(tok::eod))
  248. return Diag(MacroNameTok, diag::err_pp_missing_macro_name);
  249. IdentifierInfo *II = MacroNameTok.getIdentifierInfo();
  250. if (!II)
  251. return Diag(MacroNameTok, diag::err_pp_macro_not_identifier);
  252. if (II->isCPlusPlusOperatorKeyword()) {
  253. // C++ 2.5p2: Alternative tokens behave the same as its primary token
  254. // except for their spellings.
  255. Diag(MacroNameTok, getLangOpts().MicrosoftExt
  256. ? diag::ext_pp_operator_used_as_macro_name
  257. : diag::err_pp_operator_used_as_macro_name)
  258. << II << MacroNameTok.getKind();
  259. // Allow #defining |and| and friends for Microsoft compatibility or
  260. // recovery when legacy C headers are included in C++.
  261. }
  262. if ((isDefineUndef != MU_Other) && II->getPPKeywordID() == tok::pp_defined) {
  263. // Error if defining "defined": C99 6.10.8/4, C++ [cpp.predefined]p4.
  264. return Diag(MacroNameTok, diag::err_defined_macro_name);
  265. }
  266. if (isDefineUndef == MU_Undef) {
  267. auto *MI = getMacroInfo(II);
  268. if (MI && MI->isBuiltinMacro()) {
  269. // Warn if undefining "__LINE__" and other builtins, per C99 6.10.8/4
  270. // and C++ [cpp.predefined]p4], but allow it as an extension.
  271. Diag(MacroNameTok, diag::ext_pp_undef_builtin_macro);
  272. }
  273. }
  274. // If defining/undefining reserved identifier or a keyword, we need to issue
  275. // a warning.
  276. SourceLocation MacroNameLoc = MacroNameTok.getLocation();
  277. if (ShadowFlag)
  278. *ShadowFlag = false;
  279. if (!SourceMgr.isInSystemHeader(MacroNameLoc) &&
  280. (SourceMgr.getBufferName(MacroNameLoc) != "<built-in>")) {
  281. MacroDiag D = MD_NoWarn;
  282. if (isDefineUndef == MU_Define) {
  283. D = shouldWarnOnMacroDef(*this, II);
  284. }
  285. else if (isDefineUndef == MU_Undef)
  286. D = shouldWarnOnMacroUndef(*this, II);
  287. if (D == MD_KeywordDef) {
  288. // We do not want to warn on some patterns widely used in configuration
  289. // scripts. This requires analyzing next tokens, so do not issue warnings
  290. // now, only inform caller.
  291. if (ShadowFlag)
  292. *ShadowFlag = true;
  293. }
  294. if (D == MD_ReservedMacro)
  295. Diag(MacroNameTok, diag::warn_pp_macro_is_reserved_id);
  296. }
  297. // Okay, we got a good identifier.
  298. return false;
  299. }
  300. /// Lex and validate a macro name, which occurs after a
  301. /// \#define or \#undef.
  302. ///
  303. /// This sets the token kind to eod and discards the rest of the macro line if
  304. /// the macro name is invalid.
  305. ///
  306. /// \param MacroNameTok Token that is expected to be a macro name.
  307. /// \param isDefineUndef Context in which macro is used.
  308. /// \param ShadowFlag Points to a flag that is set if macro shadows a keyword.
  309. void Preprocessor::ReadMacroName(Token &MacroNameTok, MacroUse isDefineUndef,
  310. bool *ShadowFlag) {
  311. // Read the token, don't allow macro expansion on it.
  312. LexUnexpandedToken(MacroNameTok);
  313. if (MacroNameTok.is(tok::code_completion)) {
  314. if (CodeComplete)
  315. CodeComplete->CodeCompleteMacroName(isDefineUndef == MU_Define);
  316. setCodeCompletionReached();
  317. LexUnexpandedToken(MacroNameTok);
  318. }
  319. if (!CheckMacroName(MacroNameTok, isDefineUndef, ShadowFlag))
  320. return;
  321. // Invalid macro name, read and discard the rest of the line and set the
  322. // token kind to tok::eod if necessary.
  323. if (MacroNameTok.isNot(tok::eod)) {
  324. MacroNameTok.setKind(tok::eod);
  325. DiscardUntilEndOfDirective();
  326. }
  327. }
  328. /// Ensure that the next token is a tok::eod token.
  329. ///
  330. /// If not, emit a diagnostic and consume up until the eod. If EnableMacros is
  331. /// true, then we consider macros that expand to zero tokens as being ok.
  332. ///
  333. /// Returns the location of the end of the directive.
  334. SourceLocation Preprocessor::CheckEndOfDirective(const char *DirType,
  335. bool EnableMacros) {
  336. Token Tmp;
  337. // Lex unexpanded tokens for most directives: macros might expand to zero
  338. // tokens, causing us to miss diagnosing invalid lines. Some directives (like
  339. // #line) allow empty macros.
  340. if (EnableMacros)
  341. Lex(Tmp);
  342. else
  343. LexUnexpandedToken(Tmp);
  344. // There should be no tokens after the directive, but we allow them as an
  345. // extension.
  346. while (Tmp.is(tok::comment)) // Skip comments in -C mode.
  347. LexUnexpandedToken(Tmp);
  348. if (Tmp.is(tok::eod))
  349. return Tmp.getLocation();
  350. // Add a fixit in GNU/C99/C++ mode. Don't offer a fixit for strict-C89,
  351. // or if this is a macro-style preprocessing directive, because it is more
  352. // trouble than it is worth to insert /**/ and check that there is no /**/
  353. // in the range also.
  354. FixItHint Hint;
  355. if ((LangOpts.GNUMode || LangOpts.C99 || LangOpts.CPlusPlus) &&
  356. !CurTokenLexer)
  357. Hint = FixItHint::CreateInsertion(Tmp.getLocation(),"//");
  358. Diag(Tmp, diag::ext_pp_extra_tokens_at_eol) << DirType << Hint;
  359. return DiscardUntilEndOfDirective().getEnd();
  360. }
  361. Optional<unsigned> Preprocessor::getSkippedRangeForExcludedConditionalBlock(
  362. SourceLocation HashLoc) {
  363. if (!ExcludedConditionalDirectiveSkipMappings)
  364. return None;
  365. if (!HashLoc.isFileID())
  366. return None;
  367. std::pair<FileID, unsigned> HashFileOffset =
  368. SourceMgr.getDecomposedLoc(HashLoc);
  369. Optional<llvm::MemoryBufferRef> Buf =
  370. SourceMgr.getBufferOrNone(HashFileOffset.first);
  371. if (!Buf)
  372. return None;
  373. auto It =
  374. ExcludedConditionalDirectiveSkipMappings->find(Buf->getBufferStart());
  375. if (It == ExcludedConditionalDirectiveSkipMappings->end())
  376. return None;
  377. const PreprocessorSkippedRangeMapping &SkippedRanges = *It->getSecond();
  378. // Check if the offset of '#' is mapped in the skipped ranges.
  379. auto MappingIt = SkippedRanges.find(HashFileOffset.second);
  380. if (MappingIt == SkippedRanges.end())
  381. return None;
  382. unsigned BytesToSkip = MappingIt->getSecond();
  383. unsigned CurLexerBufferOffset = CurLexer->getCurrentBufferOffset();
  384. assert(CurLexerBufferOffset >= HashFileOffset.second &&
  385. "lexer is before the hash?");
  386. // Take into account the fact that the lexer has already advanced, so the
  387. // number of bytes to skip must be adjusted.
  388. unsigned LengthDiff = CurLexerBufferOffset - HashFileOffset.second;
  389. assert(BytesToSkip >= LengthDiff && "lexer is after the skipped range?");
  390. return BytesToSkip - LengthDiff;
  391. }
  392. /// SkipExcludedConditionalBlock - We just read a \#if or related directive and
  393. /// decided that the subsequent tokens are in the \#if'd out portion of the
  394. /// file. Lex the rest of the file, until we see an \#endif. If
  395. /// FoundNonSkipPortion is true, then we have already emitted code for part of
  396. /// this \#if directive, so \#else/\#elif blocks should never be entered.
  397. /// If ElseOk is true, then \#else directives are ok, if not, then we have
  398. /// already seen one so a \#else directive is a duplicate. When this returns,
  399. /// the caller can lex the first valid token.
  400. void Preprocessor::SkipExcludedConditionalBlock(SourceLocation HashTokenLoc,
  401. SourceLocation IfTokenLoc,
  402. bool FoundNonSkipPortion,
  403. bool FoundElse,
  404. SourceLocation ElseLoc) {
  405. ++NumSkipped;
  406. assert(!CurTokenLexer && CurPPLexer && "Lexing a macro, not a file?");
  407. if (PreambleConditionalStack.reachedEOFWhileSkipping())
  408. PreambleConditionalStack.clearSkipInfo();
  409. else
  410. CurPPLexer->pushConditionalLevel(IfTokenLoc, /*isSkipping*/ false,
  411. FoundNonSkipPortion, FoundElse);
  412. // Enter raw mode to disable identifier lookup (and thus macro expansion),
  413. // disabling warnings, etc.
  414. CurPPLexer->LexingRawMode = true;
  415. Token Tok;
  416. if (auto SkipLength =
  417. getSkippedRangeForExcludedConditionalBlock(HashTokenLoc)) {
  418. // Skip to the next '#endif' / '#else' / '#elif'.
  419. CurLexer->skipOver(*SkipLength);
  420. }
  421. SourceLocation endLoc;
  422. while (true) {
  423. CurLexer->Lex(Tok);
  424. if (Tok.is(tok::code_completion)) {
  425. setCodeCompletionReached();
  426. if (CodeComplete)
  427. CodeComplete->CodeCompleteInConditionalExclusion();
  428. continue;
  429. }
  430. // If this is the end of the buffer, we have an error.
  431. if (Tok.is(tok::eof)) {
  432. // We don't emit errors for unterminated conditionals here,
  433. // Lexer::LexEndOfFile can do that properly.
  434. // Just return and let the caller lex after this #include.
  435. if (PreambleConditionalStack.isRecording())
  436. PreambleConditionalStack.SkipInfo.emplace(
  437. HashTokenLoc, IfTokenLoc, FoundNonSkipPortion, FoundElse, ElseLoc);
  438. break;
  439. }
  440. // If this token is not a preprocessor directive, just skip it.
  441. if (Tok.isNot(tok::hash) || !Tok.isAtStartOfLine())
  442. continue;
  443. // We just parsed a # character at the start of a line, so we're in
  444. // directive mode. Tell the lexer this so any newlines we see will be
  445. // converted into an EOD token (this terminates the macro).
  446. CurPPLexer->ParsingPreprocessorDirective = true;
  447. if (CurLexer) CurLexer->SetKeepWhitespaceMode(false);
  448. // Read the next token, the directive flavor.
  449. LexUnexpandedToken(Tok);
  450. // If this isn't an identifier directive (e.g. is "# 1\n" or "#\n", or
  451. // something bogus), skip it.
  452. if (Tok.isNot(tok::raw_identifier)) {
  453. CurPPLexer->ParsingPreprocessorDirective = false;
  454. // Restore comment saving mode.
  455. if (CurLexer) CurLexer->resetExtendedTokenMode();
  456. continue;
  457. }
  458. // If the first letter isn't i or e, it isn't intesting to us. We know that
  459. // this is safe in the face of spelling differences, because there is no way
  460. // to spell an i/e in a strange way that is another letter. Skipping this
  461. // allows us to avoid looking up the identifier info for #define/#undef and
  462. // other common directives.
  463. StringRef RI = Tok.getRawIdentifier();
  464. char FirstChar = RI[0];
  465. if (FirstChar >= 'a' && FirstChar <= 'z' &&
  466. FirstChar != 'i' && FirstChar != 'e') {
  467. CurPPLexer->ParsingPreprocessorDirective = false;
  468. // Restore comment saving mode.
  469. if (CurLexer) CurLexer->resetExtendedTokenMode();
  470. continue;
  471. }
  472. // Get the identifier name without trigraphs or embedded newlines. Note
  473. // that we can't use Tok.getIdentifierInfo() because its lookup is disabled
  474. // when skipping.
  475. char DirectiveBuf[20];
  476. StringRef Directive;
  477. if (!Tok.needsCleaning() && RI.size() < 20) {
  478. Directive = RI;
  479. } else {
  480. std::string DirectiveStr = getSpelling(Tok);
  481. size_t IdLen = DirectiveStr.size();
  482. if (IdLen >= 20) {
  483. CurPPLexer->ParsingPreprocessorDirective = false;
  484. // Restore comment saving mode.
  485. if (CurLexer) CurLexer->resetExtendedTokenMode();
  486. continue;
  487. }
  488. memcpy(DirectiveBuf, &DirectiveStr[0], IdLen);
  489. Directive = StringRef(DirectiveBuf, IdLen);
  490. }
  491. if (Directive.startswith("if")) {
  492. StringRef Sub = Directive.substr(2);
  493. if (Sub.empty() || // "if"
  494. Sub == "def" || // "ifdef"
  495. Sub == "ndef") { // "ifndef"
  496. // We know the entire #if/#ifdef/#ifndef block will be skipped, don't
  497. // bother parsing the condition.
  498. DiscardUntilEndOfDirective();
  499. CurPPLexer->pushConditionalLevel(Tok.getLocation(), /*wasskipping*/true,
  500. /*foundnonskip*/false,
  501. /*foundelse*/false);
  502. }
  503. } else if (Directive[0] == 'e') {
  504. StringRef Sub = Directive.substr(1);
  505. if (Sub == "ndif") { // "endif"
  506. PPConditionalInfo CondInfo;
  507. CondInfo.WasSkipping = true; // Silence bogus warning.
  508. bool InCond = CurPPLexer->popConditionalLevel(CondInfo);
  509. (void)InCond; // Silence warning in no-asserts mode.
  510. assert(!InCond && "Can't be skipping if not in a conditional!");
  511. // If we popped the outermost skipping block, we're done skipping!
  512. if (!CondInfo.WasSkipping) {
  513. // Restore the value of LexingRawMode so that trailing comments
  514. // are handled correctly, if we've reached the outermost block.
  515. CurPPLexer->LexingRawMode = false;
  516. endLoc = CheckEndOfDirective("endif");
  517. CurPPLexer->LexingRawMode = true;
  518. if (Callbacks)
  519. Callbacks->Endif(Tok.getLocation(), CondInfo.IfLoc);
  520. break;
  521. } else {
  522. DiscardUntilEndOfDirective();
  523. }
  524. } else if (Sub == "lse") { // "else".
  525. // #else directive in a skipping conditional. If not in some other
  526. // skipping conditional, and if #else hasn't already been seen, enter it
  527. // as a non-skipping conditional.
  528. PPConditionalInfo &CondInfo = CurPPLexer->peekConditionalLevel();
  529. // If this is a #else with a #else before it, report the error.
  530. if (CondInfo.FoundElse)
  531. Diag(Tok, diag::pp_err_else_after_else);
  532. // Note that we've seen a #else in this conditional.
  533. CondInfo.FoundElse = true;
  534. // If the conditional is at the top level, and the #if block wasn't
  535. // entered, enter the #else block now.
  536. if (!CondInfo.WasSkipping && !CondInfo.FoundNonSkip) {
  537. CondInfo.FoundNonSkip = true;
  538. // Restore the value of LexingRawMode so that trailing comments
  539. // are handled correctly.
  540. CurPPLexer->LexingRawMode = false;
  541. endLoc = CheckEndOfDirective("else");
  542. CurPPLexer->LexingRawMode = true;
  543. if (Callbacks)
  544. Callbacks->Else(Tok.getLocation(), CondInfo.IfLoc);
  545. break;
  546. } else {
  547. DiscardUntilEndOfDirective(); // C99 6.10p4.
  548. }
  549. } else if (Sub == "lif") { // "elif".
  550. PPConditionalInfo &CondInfo = CurPPLexer->peekConditionalLevel();
  551. // If this is a #elif with a #else before it, report the error.
  552. if (CondInfo.FoundElse)
  553. Diag(Tok, diag::pp_err_elif_after_else) << PED_Elif;
  554. // If this is in a skipping block or if we're already handled this #if
  555. // block, don't bother parsing the condition.
  556. if (CondInfo.WasSkipping || CondInfo.FoundNonSkip) {
  557. // FIXME: We should probably do at least some minimal parsing of the
  558. // condition to verify that it is well-formed. The current state
  559. // allows #elif* directives with completely malformed (or missing)
  560. // conditions.
  561. DiscardUntilEndOfDirective();
  562. } else {
  563. // Restore the value of LexingRawMode so that identifiers are
  564. // looked up, etc, inside the #elif expression.
  565. assert(CurPPLexer->LexingRawMode && "We have to be skipping here!");
  566. CurPPLexer->LexingRawMode = false;
  567. IdentifierInfo *IfNDefMacro = nullptr;
  568. DirectiveEvalResult DER = EvaluateDirectiveExpression(IfNDefMacro);
  569. // Stop if Lexer became invalid after hitting code completion token.
  570. if (!CurPPLexer)
  571. return;
  572. const bool CondValue = DER.Conditional;
  573. CurPPLexer->LexingRawMode = true;
  574. if (Callbacks) {
  575. Callbacks->Elif(
  576. Tok.getLocation(), DER.ExprRange,
  577. (CondValue ? PPCallbacks::CVK_True : PPCallbacks::CVK_False),
  578. CondInfo.IfLoc);
  579. }
  580. // If this condition is true, enter it!
  581. if (CondValue) {
  582. CondInfo.FoundNonSkip = true;
  583. break;
  584. }
  585. }
  586. } else if (Sub == "lifdef" || // "elifdef"
  587. Sub == "lifndef") { // "elifndef"
  588. bool IsElifDef = Sub == "lifdef";
  589. PPConditionalInfo &CondInfo = CurPPLexer->peekConditionalLevel();
  590. Token DirectiveToken = Tok;
  591. // If this is a #elif with a #else before it, report the error.
  592. if (CondInfo.FoundElse)
  593. Diag(Tok, diag::pp_err_elif_after_else)
  594. << (IsElifDef ? PED_Elifdef : PED_Elifndef);
  595. // If this is in a skipping block or if we're already handled this #if
  596. // block, don't bother parsing the condition.
  597. if (CondInfo.WasSkipping || CondInfo.FoundNonSkip) {
  598. // FIXME: We should probably do at least some minimal parsing of the
  599. // condition to verify that it is well-formed. The current state
  600. // allows #elif* directives with completely malformed (or missing)
  601. // conditions.
  602. DiscardUntilEndOfDirective();
  603. } else {
  604. // Restore the value of LexingRawMode so that identifiers are
  605. // looked up, etc, inside the #elif[n]def expression.
  606. assert(CurPPLexer->LexingRawMode && "We have to be skipping here!");
  607. CurPPLexer->LexingRawMode = false;
  608. Token MacroNameTok;
  609. ReadMacroName(MacroNameTok);
  610. CurPPLexer->LexingRawMode = true;
  611. // If the macro name token is tok::eod, there was an error that was
  612. // already reported.
  613. if (MacroNameTok.is(tok::eod)) {
  614. // Skip code until we get to #endif. This helps with recovery by
  615. // not emitting an error when the #endif is reached.
  616. continue;
  617. }
  618. emitMacroExpansionWarnings(MacroNameTok);
  619. CheckEndOfDirective(IsElifDef ? "elifdef" : "elifndef");
  620. IdentifierInfo *MII = MacroNameTok.getIdentifierInfo();
  621. auto MD = getMacroDefinition(MII);
  622. MacroInfo *MI = MD.getMacroInfo();
  623. if (Callbacks) {
  624. if (IsElifDef) {
  625. Callbacks->Elifdef(DirectiveToken.getLocation(), MacroNameTok,
  626. MD);
  627. } else {
  628. Callbacks->Elifndef(DirectiveToken.getLocation(), MacroNameTok,
  629. MD);
  630. }
  631. }
  632. // If this condition is true, enter it!
  633. if (static_cast<bool>(MI) == IsElifDef) {
  634. CondInfo.FoundNonSkip = true;
  635. break;
  636. }
  637. }
  638. }
  639. }
  640. CurPPLexer->ParsingPreprocessorDirective = false;
  641. // Restore comment saving mode.
  642. if (CurLexer) CurLexer->resetExtendedTokenMode();
  643. }
  644. // Finally, if we are out of the conditional (saw an #endif or ran off the end
  645. // of the file, just stop skipping and return to lexing whatever came after
  646. // the #if block.
  647. CurPPLexer->LexingRawMode = false;
  648. // The last skipped range isn't actually skipped yet if it's truncated
  649. // by the end of the preamble; we'll resume parsing after the preamble.
  650. if (Callbacks && (Tok.isNot(tok::eof) || !isRecordingPreamble()))
  651. Callbacks->SourceRangeSkipped(
  652. SourceRange(HashTokenLoc, endLoc.isValid()
  653. ? endLoc
  654. : CurPPLexer->getSourceLocation()),
  655. Tok.getLocation());
  656. }
  657. Module *Preprocessor::getModuleForLocation(SourceLocation Loc) {
  658. if (!SourceMgr.isInMainFile(Loc)) {
  659. // Try to determine the module of the include directive.
  660. // FIXME: Look into directly passing the FileEntry from LookupFile instead.
  661. FileID IDOfIncl = SourceMgr.getFileID(SourceMgr.getExpansionLoc(Loc));
  662. if (const FileEntry *EntryOfIncl = SourceMgr.getFileEntryForID(IDOfIncl)) {
  663. // The include comes from an included file.
  664. return HeaderInfo.getModuleMap()
  665. .findModuleForHeader(EntryOfIncl)
  666. .getModule();
  667. }
  668. }
  669. // This is either in the main file or not in a file at all. It belongs
  670. // to the current module, if there is one.
  671. return getLangOpts().CurrentModule.empty()
  672. ? nullptr
  673. : HeaderInfo.lookupModule(getLangOpts().CurrentModule, Loc);
  674. }
  675. const FileEntry *
  676. Preprocessor::getHeaderToIncludeForDiagnostics(SourceLocation IncLoc,
  677. SourceLocation Loc) {
  678. Module *IncM = getModuleForLocation(IncLoc);
  679. // Walk up through the include stack, looking through textual headers of M
  680. // until we hit a non-textual header that we can #include. (We assume textual
  681. // headers of a module with non-textual headers aren't meant to be used to
  682. // import entities from the module.)
  683. auto &SM = getSourceManager();
  684. while (!Loc.isInvalid() && !SM.isInMainFile(Loc)) {
  685. auto ID = SM.getFileID(SM.getExpansionLoc(Loc));
  686. auto *FE = SM.getFileEntryForID(ID);
  687. if (!FE)
  688. break;
  689. // We want to find all possible modules that might contain this header, so
  690. // search all enclosing directories for module maps and load them.
  691. HeaderInfo.hasModuleMap(FE->getName(), /*Root*/ nullptr,
  692. SourceMgr.isInSystemHeader(Loc));
  693. bool InPrivateHeader = false;
  694. for (auto Header : HeaderInfo.findAllModulesForHeader(FE)) {
  695. if (!Header.isAccessibleFrom(IncM)) {
  696. // It's in a private header; we can't #include it.
  697. // FIXME: If there's a public header in some module that re-exports it,
  698. // then we could suggest including that, but it's not clear that's the
  699. // expected way to make this entity visible.
  700. InPrivateHeader = true;
  701. continue;
  702. }
  703. // We'll suggest including textual headers below if they're
  704. // include-guarded.
  705. if (Header.getRole() & ModuleMap::TextualHeader)
  706. continue;
  707. // If we have a module import syntax, we shouldn't include a header to
  708. // make a particular module visible. Let the caller know they should
  709. // suggest an import instead.
  710. if (getLangOpts().ObjC || getLangOpts().CPlusPlusModules ||
  711. getLangOpts().ModulesTS)
  712. return nullptr;
  713. // If this is an accessible, non-textual header of M's top-level module
  714. // that transitively includes the given location and makes the
  715. // corresponding module visible, this is the thing to #include.
  716. return FE;
  717. }
  718. // FIXME: If we're bailing out due to a private header, we shouldn't suggest
  719. // an import either.
  720. if (InPrivateHeader)
  721. return nullptr;
  722. // If the header is includable and has an include guard, assume the
  723. // intended way to expose its contents is by #include, not by importing a
  724. // module that transitively includes it.
  725. if (getHeaderSearchInfo().isFileMultipleIncludeGuarded(FE))
  726. return FE;
  727. Loc = SM.getIncludeLoc(ID);
  728. }
  729. return nullptr;
  730. }
  731. Optional<FileEntryRef> Preprocessor::LookupFile(
  732. SourceLocation FilenameLoc, StringRef Filename, bool isAngled,
  733. const DirectoryLookup *FromDir, const FileEntry *FromFile,
  734. const DirectoryLookup **CurDirArg, SmallVectorImpl<char> *SearchPath,
  735. SmallVectorImpl<char> *RelativePath,
  736. ModuleMap::KnownHeader *SuggestedModule, bool *IsMapped,
  737. bool *IsFrameworkFound, bool SkipCache) {
  738. const DirectoryLookup *CurDirLocal = nullptr;
  739. const DirectoryLookup *&CurDir = CurDirArg ? *CurDirArg : CurDirLocal;
  740. Module *RequestingModule = getModuleForLocation(FilenameLoc);
  741. bool RequestingModuleIsModuleInterface = !SourceMgr.isInMainFile(FilenameLoc);
  742. // If the header lookup mechanism may be relative to the current inclusion
  743. // stack, record the parent #includes.
  744. SmallVector<std::pair<const FileEntry *, const DirectoryEntry *>, 16>
  745. Includers;
  746. bool BuildSystemModule = false;
  747. if (!FromDir && !FromFile) {
  748. FileID FID = getCurrentFileLexer()->getFileID();
  749. const FileEntry *FileEnt = SourceMgr.getFileEntryForID(FID);
  750. // If there is no file entry associated with this file, it must be the
  751. // predefines buffer or the module includes buffer. Any other file is not
  752. // lexed with a normal lexer, so it won't be scanned for preprocessor
  753. // directives.
  754. //
  755. // If we have the predefines buffer, resolve #include references (which come
  756. // from the -include command line argument) from the current working
  757. // directory instead of relative to the main file.
  758. //
  759. // If we have the module includes buffer, resolve #include references (which
  760. // come from header declarations in the module map) relative to the module
  761. // map file.
  762. if (!FileEnt) {
  763. if (FID == SourceMgr.getMainFileID() && MainFileDir) {
  764. Includers.push_back(std::make_pair(nullptr, MainFileDir));
  765. BuildSystemModule = getCurrentModule()->IsSystem;
  766. } else if ((FileEnt =
  767. SourceMgr.getFileEntryForID(SourceMgr.getMainFileID())))
  768. Includers.push_back(std::make_pair(FileEnt, *FileMgr.getDirectory(".")));
  769. } else {
  770. Includers.push_back(std::make_pair(FileEnt, FileEnt->getDir()));
  771. }
  772. // MSVC searches the current include stack from top to bottom for
  773. // headers included by quoted include directives.
  774. // See: http://msdn.microsoft.com/en-us/library/36k2cdd4.aspx
  775. if (LangOpts.MSVCCompat && !isAngled) {
  776. for (IncludeStackInfo &ISEntry : llvm::reverse(IncludeMacroStack)) {
  777. if (IsFileLexer(ISEntry))
  778. if ((FileEnt = ISEntry.ThePPLexer->getFileEntry()))
  779. Includers.push_back(std::make_pair(FileEnt, FileEnt->getDir()));
  780. }
  781. }
  782. }
  783. CurDir = CurDirLookup;
  784. if (FromFile) {
  785. // We're supposed to start looking from after a particular file. Search
  786. // the include path until we find that file or run out of files.
  787. const DirectoryLookup *TmpCurDir = CurDir;
  788. const DirectoryLookup *TmpFromDir = nullptr;
  789. while (Optional<FileEntryRef> FE = HeaderInfo.LookupFile(
  790. Filename, FilenameLoc, isAngled, TmpFromDir, &TmpCurDir,
  791. Includers, SearchPath, RelativePath, RequestingModule,
  792. SuggestedModule, /*IsMapped=*/nullptr,
  793. /*IsFrameworkFound=*/nullptr, SkipCache)) {
  794. // Keep looking as if this file did a #include_next.
  795. TmpFromDir = TmpCurDir;
  796. ++TmpFromDir;
  797. if (&FE->getFileEntry() == FromFile) {
  798. // Found it.
  799. FromDir = TmpFromDir;
  800. CurDir = TmpCurDir;
  801. break;
  802. }
  803. }
  804. }
  805. // Do a standard file entry lookup.
  806. Optional<FileEntryRef> FE = HeaderInfo.LookupFile(
  807. Filename, FilenameLoc, isAngled, FromDir, &CurDir, Includers, SearchPath,
  808. RelativePath, RequestingModule, SuggestedModule, IsMapped,
  809. IsFrameworkFound, SkipCache, BuildSystemModule);
  810. if (FE) {
  811. if (SuggestedModule && !LangOpts.AsmPreprocessor)
  812. HeaderInfo.getModuleMap().diagnoseHeaderInclusion(
  813. RequestingModule, RequestingModuleIsModuleInterface, FilenameLoc,
  814. Filename, &FE->getFileEntry());
  815. return FE;
  816. }
  817. const FileEntry *CurFileEnt;
  818. // Otherwise, see if this is a subframework header. If so, this is relative
  819. // to one of the headers on the #include stack. Walk the list of the current
  820. // headers on the #include stack and pass them to HeaderInfo.
  821. if (IsFileLexer()) {
  822. if ((CurFileEnt = CurPPLexer->getFileEntry())) {
  823. if (Optional<FileEntryRef> FE = HeaderInfo.LookupSubframeworkHeader(
  824. Filename, CurFileEnt, SearchPath, RelativePath, RequestingModule,
  825. SuggestedModule)) {
  826. if (SuggestedModule && !LangOpts.AsmPreprocessor)
  827. HeaderInfo.getModuleMap().diagnoseHeaderInclusion(
  828. RequestingModule, RequestingModuleIsModuleInterface, FilenameLoc,
  829. Filename, &FE->getFileEntry());
  830. return FE;
  831. }
  832. }
  833. }
  834. for (IncludeStackInfo &ISEntry : llvm::reverse(IncludeMacroStack)) {
  835. if (IsFileLexer(ISEntry)) {
  836. if ((CurFileEnt = ISEntry.ThePPLexer->getFileEntry())) {
  837. if (Optional<FileEntryRef> FE = HeaderInfo.LookupSubframeworkHeader(
  838. Filename, CurFileEnt, SearchPath, RelativePath,
  839. RequestingModule, SuggestedModule)) {
  840. if (SuggestedModule && !LangOpts.AsmPreprocessor)
  841. HeaderInfo.getModuleMap().diagnoseHeaderInclusion(
  842. RequestingModule, RequestingModuleIsModuleInterface,
  843. FilenameLoc, Filename, &FE->getFileEntry());
  844. return FE;
  845. }
  846. }
  847. }
  848. }
  849. // Otherwise, we really couldn't find the file.
  850. return None;
  851. }
  852. //===----------------------------------------------------------------------===//
  853. // Preprocessor Directive Handling.
  854. //===----------------------------------------------------------------------===//
  855. class Preprocessor::ResetMacroExpansionHelper {
  856. public:
  857. ResetMacroExpansionHelper(Preprocessor *pp)
  858. : PP(pp), save(pp->DisableMacroExpansion) {
  859. if (pp->MacroExpansionInDirectivesOverride)
  860. pp->DisableMacroExpansion = false;
  861. }
  862. ~ResetMacroExpansionHelper() {
  863. PP->DisableMacroExpansion = save;
  864. }
  865. private:
  866. Preprocessor *PP;
  867. bool save;
  868. };
  869. /// Process a directive while looking for the through header or a #pragma
  870. /// hdrstop. The following directives are handled:
  871. /// #include (to check if it is the through header)
  872. /// #define (to warn about macros that don't match the PCH)
  873. /// #pragma (to check for pragma hdrstop).
  874. /// All other directives are completely discarded.
  875. void Preprocessor::HandleSkippedDirectiveWhileUsingPCH(Token &Result,
  876. SourceLocation HashLoc) {
  877. if (const IdentifierInfo *II = Result.getIdentifierInfo()) {
  878. if (II->getPPKeywordID() == tok::pp_define) {
  879. return HandleDefineDirective(Result,
  880. /*ImmediatelyAfterHeaderGuard=*/false);
  881. }
  882. if (SkippingUntilPCHThroughHeader &&
  883. II->getPPKeywordID() == tok::pp_include) {
  884. return HandleIncludeDirective(HashLoc, Result);
  885. }
  886. if (SkippingUntilPragmaHdrStop && II->getPPKeywordID() == tok::pp_pragma) {
  887. Lex(Result);
  888. auto *II = Result.getIdentifierInfo();
  889. if (II && II->getName() == "hdrstop")
  890. return HandlePragmaHdrstop(Result);
  891. }
  892. }
  893. DiscardUntilEndOfDirective();
  894. }
  895. /// HandleDirective - This callback is invoked when the lexer sees a # token
  896. /// at the start of a line. This consumes the directive, modifies the
  897. /// lexer/preprocessor state, and advances the lexer(s) so that the next token
  898. /// read is the correct one.
  899. void Preprocessor::HandleDirective(Token &Result) {
  900. // FIXME: Traditional: # with whitespace before it not recognized by K&R?
  901. // We just parsed a # character at the start of a line, so we're in directive
  902. // mode. Tell the lexer this so any newlines we see will be converted into an
  903. // EOD token (which terminates the directive).
  904. CurPPLexer->ParsingPreprocessorDirective = true;
  905. if (CurLexer) CurLexer->SetKeepWhitespaceMode(false);
  906. bool ImmediatelyAfterTopLevelIfndef =
  907. CurPPLexer->MIOpt.getImmediatelyAfterTopLevelIfndef();
  908. CurPPLexer->MIOpt.resetImmediatelyAfterTopLevelIfndef();
  909. ++NumDirectives;
  910. // We are about to read a token. For the multiple-include optimization FA to
  911. // work, we have to remember if we had read any tokens *before* this
  912. // pp-directive.
  913. bool ReadAnyTokensBeforeDirective =CurPPLexer->MIOpt.getHasReadAnyTokensVal();
  914. // Save the '#' token in case we need to return it later.
  915. Token SavedHash = Result;
  916. // Read the next token, the directive flavor. This isn't expanded due to
  917. // C99 6.10.3p8.
  918. LexUnexpandedToken(Result);
  919. // C99 6.10.3p11: Is this preprocessor directive in macro invocation? e.g.:
  920. // #define A(x) #x
  921. // A(abc
  922. // #warning blah
  923. // def)
  924. // If so, the user is relying on undefined behavior, emit a diagnostic. Do
  925. // not support this for #include-like directives, since that can result in
  926. // terrible diagnostics, and does not work in GCC.
  927. if (InMacroArgs) {
  928. if (IdentifierInfo *II = Result.getIdentifierInfo()) {
  929. switch (II->getPPKeywordID()) {
  930. case tok::pp_include:
  931. case tok::pp_import:
  932. case tok::pp_include_next:
  933. case tok::pp___include_macros:
  934. case tok::pp_pragma:
  935. Diag(Result, diag::err_embedded_directive) << II->getName();
  936. Diag(*ArgMacro, diag::note_macro_expansion_here)
  937. << ArgMacro->getIdentifierInfo();
  938. DiscardUntilEndOfDirective();
  939. return;
  940. default:
  941. break;
  942. }
  943. }
  944. Diag(Result, diag::ext_embedded_directive);
  945. }
  946. // Temporarily enable macro expansion if set so
  947. // and reset to previous state when returning from this function.
  948. ResetMacroExpansionHelper helper(this);
  949. if (SkippingUntilPCHThroughHeader || SkippingUntilPragmaHdrStop)
  950. return HandleSkippedDirectiveWhileUsingPCH(Result, SavedHash.getLocation());
  951. switch (Result.getKind()) {
  952. case tok::eod:
  953. return; // null directive.
  954. case tok::code_completion:
  955. setCodeCompletionReached();
  956. if (CodeComplete)
  957. CodeComplete->CodeCompleteDirective(
  958. CurPPLexer->getConditionalStackDepth() > 0);
  959. return;
  960. case tok::numeric_constant: // # 7 GNU line marker directive.
  961. if (getLangOpts().AsmPreprocessor)
  962. break; // # 4 is not a preprocessor directive in .S files.
  963. return HandleDigitDirective(Result);
  964. default:
  965. IdentifierInfo *II = Result.getIdentifierInfo();
  966. if (!II) break; // Not an identifier.
  967. // Ask what the preprocessor keyword ID is.
  968. switch (II->getPPKeywordID()) {
  969. default: break;
  970. // C99 6.10.1 - Conditional Inclusion.
  971. case tok::pp_if:
  972. return HandleIfDirective(Result, SavedHash, ReadAnyTokensBeforeDirective);
  973. case tok::pp_ifdef:
  974. return HandleIfdefDirective(Result, SavedHash, false,
  975. true /*not valid for miopt*/);
  976. case tok::pp_ifndef:
  977. return HandleIfdefDirective(Result, SavedHash, true,
  978. ReadAnyTokensBeforeDirective);
  979. case tok::pp_elif:
  980. case tok::pp_elifdef:
  981. case tok::pp_elifndef:
  982. return HandleElifFamilyDirective(Result, SavedHash, II->getPPKeywordID());
  983. case tok::pp_else:
  984. return HandleElseDirective(Result, SavedHash);
  985. case tok::pp_endif:
  986. return HandleEndifDirective(Result);
  987. // C99 6.10.2 - Source File Inclusion.
  988. case tok::pp_include:
  989. // Handle #include.
  990. return HandleIncludeDirective(SavedHash.getLocation(), Result);
  991. case tok::pp___include_macros:
  992. // Handle -imacros.
  993. return HandleIncludeMacrosDirective(SavedHash.getLocation(), Result);
  994. // C99 6.10.3 - Macro Replacement.
  995. case tok::pp_define:
  996. return HandleDefineDirective(Result, ImmediatelyAfterTopLevelIfndef);
  997. case tok::pp_undef:
  998. return HandleUndefDirective();
  999. // C99 6.10.4 - Line Control.
  1000. case tok::pp_line:
  1001. return HandleLineDirective();
  1002. // C99 6.10.5 - Error Directive.
  1003. case tok::pp_error:
  1004. return HandleUserDiagnosticDirective(Result, false);
  1005. // C99 6.10.6 - Pragma Directive.
  1006. case tok::pp_pragma:
  1007. return HandlePragmaDirective({PIK_HashPragma, SavedHash.getLocation()});
  1008. // GNU Extensions.
  1009. case tok::pp_import:
  1010. return HandleImportDirective(SavedHash.getLocation(), Result);
  1011. case tok::pp_include_next:
  1012. return HandleIncludeNextDirective(SavedHash.getLocation(), Result);
  1013. case tok::pp_warning:
  1014. Diag(Result, diag::ext_pp_warning_directive);
  1015. return HandleUserDiagnosticDirective(Result, true);
  1016. case tok::pp_ident:
  1017. return HandleIdentSCCSDirective(Result);
  1018. case tok::pp_sccs:
  1019. return HandleIdentSCCSDirective(Result);
  1020. case tok::pp_assert:
  1021. //isExtension = true; // FIXME: implement #assert
  1022. break;
  1023. case tok::pp_unassert:
  1024. //isExtension = true; // FIXME: implement #unassert
  1025. break;
  1026. case tok::pp___public_macro:
  1027. if (getLangOpts().Modules || getLangOpts().ModulesLocalVisibility)
  1028. return HandleMacroPublicDirective(Result);
  1029. break;
  1030. case tok::pp___private_macro:
  1031. if (getLangOpts().Modules || getLangOpts().ModulesLocalVisibility)
  1032. return HandleMacroPrivateDirective();
  1033. break;
  1034. }
  1035. break;
  1036. }
  1037. // If this is a .S file, treat unknown # directives as non-preprocessor
  1038. // directives. This is important because # may be a comment or introduce
  1039. // various pseudo-ops. Just return the # token and push back the following
  1040. // token to be lexed next time.
  1041. if (getLangOpts().AsmPreprocessor) {
  1042. auto Toks = std::make_unique<Token[]>(2);
  1043. // Return the # and the token after it.
  1044. Toks[0] = SavedHash;
  1045. Toks[1] = Result;
  1046. // If the second token is a hashhash token, then we need to translate it to
  1047. // unknown so the token lexer doesn't try to perform token pasting.
  1048. if (Result.is(tok::hashhash))
  1049. Toks[1].setKind(tok::unknown);
  1050. // Enter this token stream so that we re-lex the tokens. Make sure to
  1051. // enable macro expansion, in case the token after the # is an identifier
  1052. // that is expanded.
  1053. EnterTokenStream(std::move(Toks), 2, false, /*IsReinject*/false);
  1054. return;
  1055. }
  1056. // If we reached here, the preprocessing token is not valid!
  1057. Diag(Result, diag::err_pp_invalid_directive);
  1058. // Read the rest of the PP line.
  1059. DiscardUntilEndOfDirective();
  1060. // Okay, we're done parsing the directive.
  1061. }
  1062. /// GetLineValue - Convert a numeric token into an unsigned value, emitting
  1063. /// Diagnostic DiagID if it is invalid, and returning the value in Val.
  1064. static bool GetLineValue(Token &DigitTok, unsigned &Val,
  1065. unsigned DiagID, Preprocessor &PP,
  1066. bool IsGNULineDirective=false) {
  1067. if (DigitTok.isNot(tok::numeric_constant)) {
  1068. PP.Diag(DigitTok, DiagID);
  1069. if (DigitTok.isNot(tok::eod))
  1070. PP.DiscardUntilEndOfDirective();
  1071. return true;
  1072. }
  1073. SmallString<64> IntegerBuffer;
  1074. IntegerBuffer.resize(DigitTok.getLength());
  1075. const char *DigitTokBegin = &IntegerBuffer[0];
  1076. bool Invalid = false;
  1077. unsigned ActualLength = PP.getSpelling(DigitTok, DigitTokBegin, &Invalid);
  1078. if (Invalid)
  1079. return true;
  1080. // Verify that we have a simple digit-sequence, and compute the value. This
  1081. // is always a simple digit string computed in decimal, so we do this manually
  1082. // here.
  1083. Val = 0;
  1084. for (unsigned i = 0; i != ActualLength; ++i) {
  1085. // C++1y [lex.fcon]p1:
  1086. // Optional separating single quotes in a digit-sequence are ignored
  1087. if (DigitTokBegin[i] == '\'')
  1088. continue;
  1089. if (!isDigit(DigitTokBegin[i])) {
  1090. PP.Diag(PP.AdvanceToTokenCharacter(DigitTok.getLocation(), i),
  1091. diag::err_pp_line_digit_sequence) << IsGNULineDirective;
  1092. PP.DiscardUntilEndOfDirective();
  1093. return true;
  1094. }
  1095. unsigned NextVal = Val*10+(DigitTokBegin[i]-'0');
  1096. if (NextVal < Val) { // overflow.
  1097. PP.Diag(DigitTok, DiagID);
  1098. PP.DiscardUntilEndOfDirective();
  1099. return true;
  1100. }
  1101. Val = NextVal;
  1102. }
  1103. if (DigitTokBegin[0] == '0' && Val)
  1104. PP.Diag(DigitTok.getLocation(), diag::warn_pp_line_decimal)
  1105. << IsGNULineDirective;
  1106. return false;
  1107. }
  1108. /// Handle a \#line directive: C99 6.10.4.
  1109. ///
  1110. /// The two acceptable forms are:
  1111. /// \verbatim
  1112. /// # line digit-sequence
  1113. /// # line digit-sequence "s-char-sequence"
  1114. /// \endverbatim
  1115. void Preprocessor::HandleLineDirective() {
  1116. // Read the line # and string argument. Per C99 6.10.4p5, these tokens are
  1117. // expanded.
  1118. Token DigitTok;
  1119. Lex(DigitTok);
  1120. // Validate the number and convert it to an unsigned.
  1121. unsigned LineNo;
  1122. if (GetLineValue(DigitTok, LineNo, diag::err_pp_line_requires_integer,*this))
  1123. return;
  1124. if (LineNo == 0)
  1125. Diag(DigitTok, diag::ext_pp_line_zero);
  1126. // Enforce C99 6.10.4p3: "The digit sequence shall not specify ... a
  1127. // number greater than 2147483647". C90 requires that the line # be <= 32767.
  1128. unsigned LineLimit = 32768U;
  1129. if (LangOpts.C99 || LangOpts.CPlusPlus11)
  1130. LineLimit = 2147483648U;
  1131. if (LineNo >= LineLimit)
  1132. Diag(DigitTok, diag::ext_pp_line_too_big) << LineLimit;
  1133. else if (LangOpts.CPlusPlus11 && LineNo >= 32768U)
  1134. Diag(DigitTok, diag::warn_cxx98_compat_pp_line_too_big);
  1135. int FilenameID = -1;
  1136. Token StrTok;
  1137. Lex(StrTok);
  1138. // If the StrTok is "eod", then it wasn't present. Otherwise, it must be a
  1139. // string followed by eod.
  1140. if (StrTok.is(tok::eod))
  1141. ; // ok
  1142. else if (StrTok.isNot(tok::string_literal)) {
  1143. Diag(StrTok, diag::err_pp_line_invalid_filename);
  1144. DiscardUntilEndOfDirective();
  1145. return;
  1146. } else if (StrTok.hasUDSuffix()) {
  1147. Diag(StrTok, diag::err_invalid_string_udl);
  1148. DiscardUntilEndOfDirective();
  1149. return;
  1150. } else {
  1151. // Parse and validate the string, converting it into a unique ID.
  1152. StringLiteralParser Literal(StrTok, *this);
  1153. assert(Literal.isAscii() && "Didn't allow wide strings in");
  1154. if (Literal.hadError) {
  1155. DiscardUntilEndOfDirective();
  1156. return;
  1157. }
  1158. if (Literal.Pascal) {
  1159. Diag(StrTok, diag::err_pp_linemarker_invalid_filename);
  1160. DiscardUntilEndOfDirective();
  1161. return;
  1162. }
  1163. FilenameID = SourceMgr.getLineTableFilenameID(Literal.GetString());
  1164. // Verify that there is nothing after the string, other than EOD. Because
  1165. // of C99 6.10.4p5, macros that expand to empty tokens are ok.
  1166. CheckEndOfDirective("line", true);
  1167. }
  1168. // Take the file kind of the file containing the #line directive. #line
  1169. // directives are often used for generated sources from the same codebase, so
  1170. // the new file should generally be classified the same way as the current
  1171. // file. This is visible in GCC's pre-processed output, which rewrites #line
  1172. // to GNU line markers.
  1173. SrcMgr::CharacteristicKind FileKind =
  1174. SourceMgr.getFileCharacteristic(DigitTok.getLocation());
  1175. SourceMgr.AddLineNote(DigitTok.getLocation(), LineNo, FilenameID, false,
  1176. false, FileKind);
  1177. if (Callbacks)
  1178. Callbacks->FileChanged(CurPPLexer->getSourceLocation(),
  1179. PPCallbacks::RenameFile, FileKind);
  1180. }
  1181. /// ReadLineMarkerFlags - Parse and validate any flags at the end of a GNU line
  1182. /// marker directive.
  1183. static bool ReadLineMarkerFlags(bool &IsFileEntry, bool &IsFileExit,
  1184. SrcMgr::CharacteristicKind &FileKind,
  1185. Preprocessor &PP) {
  1186. unsigned FlagVal;
  1187. Token FlagTok;
  1188. PP.Lex(FlagTok);
  1189. if (FlagTok.is(tok::eod)) return false;
  1190. if (GetLineValue(FlagTok, FlagVal, diag::err_pp_linemarker_invalid_flag, PP))
  1191. return true;
  1192. if (FlagVal == 1) {
  1193. IsFileEntry = true;
  1194. PP.Lex(FlagTok);
  1195. if (FlagTok.is(tok::eod)) return false;
  1196. if (GetLineValue(FlagTok, FlagVal, diag::err_pp_linemarker_invalid_flag,PP))
  1197. return true;
  1198. } else if (FlagVal == 2) {
  1199. IsFileExit = true;
  1200. SourceManager &SM = PP.getSourceManager();
  1201. // If we are leaving the current presumed file, check to make sure the
  1202. // presumed include stack isn't empty!
  1203. FileID CurFileID =
  1204. SM.getDecomposedExpansionLoc(FlagTok.getLocation()).first;
  1205. PresumedLoc PLoc = SM.getPresumedLoc(FlagTok.getLocation());
  1206. if (PLoc.isInvalid())
  1207. return true;
  1208. // If there is no include loc (main file) or if the include loc is in a
  1209. // different physical file, then we aren't in a "1" line marker flag region.
  1210. SourceLocation IncLoc = PLoc.getIncludeLoc();
  1211. if (IncLoc.isInvalid() ||
  1212. SM.getDecomposedExpansionLoc(IncLoc).first != CurFileID) {
  1213. PP.Diag(FlagTok, diag::err_pp_linemarker_invalid_pop);
  1214. PP.DiscardUntilEndOfDirective();
  1215. return true;
  1216. }
  1217. PP.Lex(FlagTok);
  1218. if (FlagTok.is(tok::eod)) return false;
  1219. if (GetLineValue(FlagTok, FlagVal, diag::err_pp_linemarker_invalid_flag,PP))
  1220. return true;
  1221. }
  1222. // We must have 3 if there are still flags.
  1223. if (FlagVal != 3) {
  1224. PP.Diag(FlagTok, diag::err_pp_linemarker_invalid_flag);
  1225. PP.DiscardUntilEndOfDirective();
  1226. return true;
  1227. }
  1228. FileKind = SrcMgr::C_System;
  1229. PP.Lex(FlagTok);
  1230. if (FlagTok.is(tok::eod)) return false;
  1231. if (GetLineValue(FlagTok, FlagVal, diag::err_pp_linemarker_invalid_flag, PP))
  1232. return true;
  1233. // We must have 4 if there is yet another flag.
  1234. if (FlagVal != 4) {
  1235. PP.Diag(FlagTok, diag::err_pp_linemarker_invalid_flag);
  1236. PP.DiscardUntilEndOfDirective();
  1237. return true;
  1238. }
  1239. FileKind = SrcMgr::C_ExternCSystem;
  1240. PP.Lex(FlagTok);
  1241. if (FlagTok.is(tok::eod)) return false;
  1242. // There are no more valid flags here.
  1243. PP.Diag(FlagTok, diag::err_pp_linemarker_invalid_flag);
  1244. PP.DiscardUntilEndOfDirective();
  1245. return true;
  1246. }
  1247. /// HandleDigitDirective - Handle a GNU line marker directive, whose syntax is
  1248. /// one of the following forms:
  1249. ///
  1250. /// # 42
  1251. /// # 42 "file" ('1' | '2')?
  1252. /// # 42 "file" ('1' | '2')? '3' '4'?
  1253. ///
  1254. void Preprocessor::HandleDigitDirective(Token &DigitTok) {
  1255. // Validate the number and convert it to an unsigned. GNU does not have a
  1256. // line # limit other than it fit in 32-bits.
  1257. unsigned LineNo;
  1258. if (GetLineValue(DigitTok, LineNo, diag::err_pp_linemarker_requires_integer,
  1259. *this, true))
  1260. return;
  1261. Token StrTok;
  1262. Lex(StrTok);
  1263. bool IsFileEntry = false, IsFileExit = false;
  1264. int FilenameID = -1;
  1265. SrcMgr::CharacteristicKind FileKind = SrcMgr::C_User;
  1266. // If the StrTok is "eod", then it wasn't present. Otherwise, it must be a
  1267. // string followed by eod.
  1268. if (StrTok.is(tok::eod)) {
  1269. // Treat this like "#line NN", which doesn't change file characteristics.
  1270. FileKind = SourceMgr.getFileCharacteristic(DigitTok.getLocation());
  1271. } else if (StrTok.isNot(tok::string_literal)) {
  1272. Diag(StrTok, diag::err_pp_linemarker_invalid_filename);
  1273. DiscardUntilEndOfDirective();
  1274. return;
  1275. } else if (StrTok.hasUDSuffix()) {
  1276. Diag(StrTok, diag::err_invalid_string_udl);
  1277. DiscardUntilEndOfDirective();
  1278. return;
  1279. } else {
  1280. // Parse and validate the string, converting it into a unique ID.
  1281. StringLiteralParser Literal(StrTok, *this);
  1282. assert(Literal.isAscii() && "Didn't allow wide strings in");
  1283. if (Literal.hadError) {
  1284. DiscardUntilEndOfDirective();
  1285. return;
  1286. }
  1287. if (Literal.Pascal) {
  1288. Diag(StrTok, diag::err_pp_linemarker_invalid_filename);
  1289. DiscardUntilEndOfDirective();
  1290. return;
  1291. }
  1292. // If a filename was present, read any flags that are present.
  1293. if (ReadLineMarkerFlags(IsFileEntry, IsFileExit, FileKind, *this))
  1294. return;
  1295. // Exiting to an empty string means pop to the including file, so leave
  1296. // FilenameID as -1 in that case.
  1297. if (!(IsFileExit && Literal.GetString().empty()))
  1298. FilenameID = SourceMgr.getLineTableFilenameID(Literal.GetString());
  1299. }
  1300. // Create a line note with this information.
  1301. SourceMgr.AddLineNote(DigitTok.getLocation(), LineNo, FilenameID, IsFileEntry,
  1302. IsFileExit, FileKind);
  1303. // If the preprocessor has callbacks installed, notify them of the #line
  1304. // change. This is used so that the line marker comes out in -E mode for
  1305. // example.
  1306. if (Callbacks) {
  1307. PPCallbacks::FileChangeReason Reason = PPCallbacks::RenameFile;
  1308. if (IsFileEntry)
  1309. Reason = PPCallbacks::EnterFile;
  1310. else if (IsFileExit)
  1311. Reason = PPCallbacks::ExitFile;
  1312. Callbacks->FileChanged(CurPPLexer->getSourceLocation(), Reason, FileKind);
  1313. }
  1314. }
  1315. /// HandleUserDiagnosticDirective - Handle a #warning or #error directive.
  1316. ///
  1317. void Preprocessor::HandleUserDiagnosticDirective(Token &Tok,
  1318. bool isWarning) {
  1319. // Read the rest of the line raw. We do this because we don't want macros
  1320. // to be expanded and we don't require that the tokens be valid preprocessing
  1321. // tokens. For example, this is allowed: "#warning ` 'foo". GCC does
  1322. // collapse multiple consecutive white space between tokens, but this isn't
  1323. // specified by the standard.
  1324. SmallString<128> Message;
  1325. CurLexer->ReadToEndOfLine(&Message);
  1326. // Find the first non-whitespace character, so that we can make the
  1327. // diagnostic more succinct.
  1328. StringRef Msg = Message.str().ltrim(' ');
  1329. if (isWarning)
  1330. Diag(Tok, diag::pp_hash_warning) << Msg;
  1331. else
  1332. Diag(Tok, diag::err_pp_hash_error) << Msg;
  1333. }
  1334. /// HandleIdentSCCSDirective - Handle a #ident/#sccs directive.
  1335. ///
  1336. void Preprocessor::HandleIdentSCCSDirective(Token &Tok) {
  1337. // Yes, this directive is an extension.
  1338. Diag(Tok, diag::ext_pp_ident_directive);
  1339. // Read the string argument.
  1340. Token StrTok;
  1341. Lex(StrTok);
  1342. // If the token kind isn't a string, it's a malformed directive.
  1343. if (StrTok.isNot(tok::string_literal) &&
  1344. StrTok.isNot(tok::wide_string_literal)) {
  1345. Diag(StrTok, diag::err_pp_malformed_ident);
  1346. if (StrTok.isNot(tok::eod))
  1347. DiscardUntilEndOfDirective();
  1348. return;
  1349. }
  1350. if (StrTok.hasUDSuffix()) {
  1351. Diag(StrTok, diag::err_invalid_string_udl);
  1352. DiscardUntilEndOfDirective();
  1353. return;
  1354. }
  1355. // Verify that there is nothing after the string, other than EOD.
  1356. CheckEndOfDirective("ident");
  1357. if (Callbacks) {
  1358. bool Invalid = false;
  1359. std::string Str = getSpelling(StrTok, &Invalid);
  1360. if (!Invalid)
  1361. Callbacks->Ident(Tok.getLocation(), Str);
  1362. }
  1363. }
  1364. /// Handle a #public directive.
  1365. void Preprocessor::HandleMacroPublicDirective(Token &Tok) {
  1366. Token MacroNameTok;
  1367. ReadMacroName(MacroNameTok, MU_Undef);
  1368. // Error reading macro name? If so, diagnostic already issued.
  1369. if (MacroNameTok.is(tok::eod))
  1370. return;
  1371. // Check to see if this is the last token on the #__public_macro line.
  1372. CheckEndOfDirective("__public_macro");
  1373. IdentifierInfo *II = MacroNameTok.getIdentifierInfo();
  1374. // Okay, we finally have a valid identifier to undef.
  1375. MacroDirective *MD = getLocalMacroDirective(II);
  1376. // If the macro is not defined, this is an error.
  1377. if (!MD) {
  1378. Diag(MacroNameTok, diag::err_pp_visibility_non_macro) << II;
  1379. return;
  1380. }
  1381. // Note that this macro has now been exported.
  1382. appendMacroDirective(II, AllocateVisibilityMacroDirective(
  1383. MacroNameTok.getLocation(), /*isPublic=*/true));
  1384. }
  1385. /// Handle a #private directive.
  1386. void Preprocessor::HandleMacroPrivateDirective() {
  1387. Token MacroNameTok;
  1388. ReadMacroName(MacroNameTok, MU_Undef);
  1389. // Error reading macro name? If so, diagnostic already issued.
  1390. if (MacroNameTok.is(tok::eod))
  1391. return;
  1392. // Check to see if this is the last token on the #__private_macro line.
  1393. CheckEndOfDirective("__private_macro");
  1394. IdentifierInfo *II = MacroNameTok.getIdentifierInfo();
  1395. // Okay, we finally have a valid identifier to undef.
  1396. MacroDirective *MD = getLocalMacroDirective(II);
  1397. // If the macro is not defined, this is an error.
  1398. if (!MD) {
  1399. Diag(MacroNameTok, diag::err_pp_visibility_non_macro) << II;
  1400. return;
  1401. }
  1402. // Note that this macro has now been marked private.
  1403. appendMacroDirective(II, AllocateVisibilityMacroDirective(
  1404. MacroNameTok.getLocation(), /*isPublic=*/false));
  1405. }
  1406. //===----------------------------------------------------------------------===//
  1407. // Preprocessor Include Directive Handling.
  1408. //===----------------------------------------------------------------------===//
  1409. /// GetIncludeFilenameSpelling - Turn the specified lexer token into a fully
  1410. /// checked and spelled filename, e.g. as an operand of \#include. This returns
  1411. /// true if the input filename was in <>'s or false if it were in ""'s. The
  1412. /// caller is expected to provide a buffer that is large enough to hold the
  1413. /// spelling of the filename, but is also expected to handle the case when
  1414. /// this method decides to use a different buffer.
  1415. bool Preprocessor::GetIncludeFilenameSpelling(SourceLocation Loc,
  1416. StringRef &Buffer) {
  1417. // Get the text form of the filename.
  1418. assert(!Buffer.empty() && "Can't have tokens with empty spellings!");
  1419. // FIXME: Consider warning on some of the cases described in C11 6.4.7/3 and
  1420. // C++20 [lex.header]/2:
  1421. //
  1422. // If `"`, `'`, `\`, `/*`, or `//` appears in a header-name, then
  1423. // in C: behavior is undefined
  1424. // in C++: program is conditionally-supported with implementation-defined
  1425. // semantics
  1426. // Make sure the filename is <x> or "x".
  1427. bool isAngled;
  1428. if (Buffer[0] == '<') {
  1429. if (Buffer.back() != '>') {
  1430. Diag(Loc, diag::err_pp_expects_filename);
  1431. Buffer = StringRef();
  1432. return true;
  1433. }
  1434. isAngled = true;
  1435. } else if (Buffer[0] == '"') {
  1436. if (Buffer.back() != '"') {
  1437. Diag(Loc, diag::err_pp_expects_filename);
  1438. Buffer = StringRef();
  1439. return true;
  1440. }
  1441. isAngled = false;
  1442. } else {
  1443. Diag(Loc, diag::err_pp_expects_filename);
  1444. Buffer = StringRef();
  1445. return true;
  1446. }
  1447. // Diagnose #include "" as invalid.
  1448. if (Buffer.size() <= 2) {
  1449. Diag(Loc, diag::err_pp_empty_filename);
  1450. Buffer = StringRef();
  1451. return true;
  1452. }
  1453. // Skip the brackets.
  1454. Buffer = Buffer.substr(1, Buffer.size()-2);
  1455. return isAngled;
  1456. }
  1457. /// Push a token onto the token stream containing an annotation.
  1458. void Preprocessor::EnterAnnotationToken(SourceRange Range,
  1459. tok::TokenKind Kind,
  1460. void *AnnotationVal) {
  1461. // FIXME: Produce this as the current token directly, rather than
  1462. // allocating a new token for it.
  1463. auto Tok = std::make_unique<Token[]>(1);
  1464. Tok[0].startToken();
  1465. Tok[0].setKind(Kind);
  1466. Tok[0].setLocation(Range.getBegin());
  1467. Tok[0].setAnnotationEndLoc(Range.getEnd());
  1468. Tok[0].setAnnotationValue(AnnotationVal);
  1469. EnterTokenStream(std::move(Tok), 1, true, /*IsReinject*/ false);
  1470. }
  1471. /// Produce a diagnostic informing the user that a #include or similar
  1472. /// was implicitly treated as a module import.
  1473. static void diagnoseAutoModuleImport(
  1474. Preprocessor &PP, SourceLocation HashLoc, Token &IncludeTok,
  1475. ArrayRef<std::pair<IdentifierInfo *, SourceLocation>> Path,
  1476. SourceLocation PathEnd) {
  1477. StringRef ImportKeyword;
  1478. if (PP.getLangOpts().ObjC)
  1479. ImportKeyword = "@import";
  1480. else if (PP.getLangOpts().ModulesTS || PP.getLangOpts().CPlusPlusModules)
  1481. ImportKeyword = "import";
  1482. else
  1483. return; // no import syntax available
  1484. SmallString<128> PathString;
  1485. for (size_t I = 0, N = Path.size(); I != N; ++I) {
  1486. if (I)
  1487. PathString += '.';
  1488. PathString += Path[I].first->getName();
  1489. }
  1490. int IncludeKind = 0;
  1491. switch (IncludeTok.getIdentifierInfo()->getPPKeywordID()) {
  1492. case tok::pp_include:
  1493. IncludeKind = 0;
  1494. break;
  1495. case tok::pp_import:
  1496. IncludeKind = 1;
  1497. break;
  1498. case tok::pp_include_next:
  1499. IncludeKind = 2;
  1500. break;
  1501. case tok::pp___include_macros:
  1502. IncludeKind = 3;
  1503. break;
  1504. default:
  1505. llvm_unreachable("unknown include directive kind");
  1506. }
  1507. CharSourceRange ReplaceRange(SourceRange(HashLoc, PathEnd),
  1508. /*IsTokenRange=*/false);
  1509. PP.Diag(HashLoc, diag::warn_auto_module_import)
  1510. << IncludeKind << PathString
  1511. << FixItHint::CreateReplacement(
  1512. ReplaceRange, (ImportKeyword + " " + PathString + ";").str());
  1513. }
  1514. // Given a vector of path components and a string containing the real
  1515. // path to the file, build a properly-cased replacement in the vector,
  1516. // and return true if the replacement should be suggested.
  1517. static bool trySimplifyPath(SmallVectorImpl<StringRef> &Components,
  1518. StringRef RealPathName) {
  1519. auto RealPathComponentIter = llvm::sys::path::rbegin(RealPathName);
  1520. auto RealPathComponentEnd = llvm::sys::path::rend(RealPathName);
  1521. int Cnt = 0;
  1522. bool SuggestReplacement = false;
  1523. // Below is a best-effort to handle ".." in paths. It is admittedly
  1524. // not 100% correct in the presence of symlinks.
  1525. for (auto &Component : llvm::reverse(Components)) {
  1526. if ("." == Component) {
  1527. } else if (".." == Component) {
  1528. ++Cnt;
  1529. } else if (Cnt) {
  1530. --Cnt;
  1531. } else if (RealPathComponentIter != RealPathComponentEnd) {
  1532. if (Component != *RealPathComponentIter) {
  1533. // If these path components differ by more than just case, then we
  1534. // may be looking at symlinked paths. Bail on this diagnostic to avoid
  1535. // noisy false positives.
  1536. SuggestReplacement =
  1537. RealPathComponentIter->equals_insensitive(Component);
  1538. if (!SuggestReplacement)
  1539. break;
  1540. Component = *RealPathComponentIter;
  1541. }
  1542. ++RealPathComponentIter;
  1543. }
  1544. }
  1545. return SuggestReplacement;
  1546. }
  1547. bool Preprocessor::checkModuleIsAvailable(const LangOptions &LangOpts,
  1548. const TargetInfo &TargetInfo,
  1549. DiagnosticsEngine &Diags, Module *M) {
  1550. Module::Requirement Requirement;
  1551. Module::UnresolvedHeaderDirective MissingHeader;
  1552. Module *ShadowingModule = nullptr;
  1553. if (M->isAvailable(LangOpts, TargetInfo, Requirement, MissingHeader,
  1554. ShadowingModule))
  1555. return false;
  1556. if (MissingHeader.FileNameLoc.isValid()) {
  1557. Diags.Report(MissingHeader.FileNameLoc, diag::err_module_header_missing)
  1558. << MissingHeader.IsUmbrella << MissingHeader.FileName;
  1559. } else if (ShadowingModule) {
  1560. Diags.Report(M->DefinitionLoc, diag::err_module_shadowed) << M->Name;
  1561. Diags.Report(ShadowingModule->DefinitionLoc,
  1562. diag::note_previous_definition);
  1563. } else {
  1564. // FIXME: Track the location at which the requirement was specified, and
  1565. // use it here.
  1566. Diags.Report(M->DefinitionLoc, diag::err_module_unavailable)
  1567. << M->getFullModuleName() << Requirement.second << Requirement.first;
  1568. }
  1569. return true;
  1570. }
  1571. /// HandleIncludeDirective - The "\#include" tokens have just been read, read
  1572. /// the file to be included from the lexer, then include it! This is a common
  1573. /// routine with functionality shared between \#include, \#include_next and
  1574. /// \#import. LookupFrom is set when this is a \#include_next directive, it
  1575. /// specifies the file to start searching from.
  1576. void Preprocessor::HandleIncludeDirective(SourceLocation HashLoc,
  1577. Token &IncludeTok,
  1578. const DirectoryLookup *LookupFrom,
  1579. const FileEntry *LookupFromFile) {
  1580. Token FilenameTok;
  1581. if (LexHeaderName(FilenameTok))
  1582. return;
  1583. if (FilenameTok.isNot(tok::header_name)) {
  1584. Diag(FilenameTok.getLocation(), diag::err_pp_expects_filename);
  1585. if (FilenameTok.isNot(tok::eod))
  1586. DiscardUntilEndOfDirective();
  1587. return;
  1588. }
  1589. // Verify that there is nothing after the filename, other than EOD. Note
  1590. // that we allow macros that expand to nothing after the filename, because
  1591. // this falls into the category of "#include pp-tokens new-line" specified
  1592. // in C99 6.10.2p4.
  1593. SourceLocation EndLoc =
  1594. CheckEndOfDirective(IncludeTok.getIdentifierInfo()->getNameStart(), true);
  1595. auto Action = HandleHeaderIncludeOrImport(HashLoc, IncludeTok, FilenameTok,
  1596. EndLoc, LookupFrom, LookupFromFile);
  1597. switch (Action.Kind) {
  1598. case ImportAction::None:
  1599. case ImportAction::SkippedModuleImport:
  1600. break;
  1601. case ImportAction::ModuleBegin:
  1602. EnterAnnotationToken(SourceRange(HashLoc, EndLoc),
  1603. tok::annot_module_begin, Action.ModuleForHeader);
  1604. break;
  1605. case ImportAction::ModuleImport:
  1606. EnterAnnotationToken(SourceRange(HashLoc, EndLoc),
  1607. tok::annot_module_include, Action.ModuleForHeader);
  1608. break;
  1609. case ImportAction::Failure:
  1610. assert(TheModuleLoader.HadFatalFailure &&
  1611. "This should be an early exit only to a fatal error");
  1612. TheModuleLoader.HadFatalFailure = true;
  1613. IncludeTok.setKind(tok::eof);
  1614. CurLexer->cutOffLexing();
  1615. return;
  1616. }
  1617. }
  1618. Optional<FileEntryRef> Preprocessor::LookupHeaderIncludeOrImport(
  1619. const DirectoryLookup **CurDir, StringRef& Filename,
  1620. SourceLocation FilenameLoc, CharSourceRange FilenameRange,
  1621. const Token &FilenameTok, bool &IsFrameworkFound, bool IsImportDecl,
  1622. bool &IsMapped, const DirectoryLookup *LookupFrom,
  1623. const FileEntry *LookupFromFile, StringRef& LookupFilename,
  1624. SmallVectorImpl<char> &RelativePath, SmallVectorImpl<char> &SearchPath,
  1625. ModuleMap::KnownHeader &SuggestedModule, bool isAngled) {
  1626. Optional<FileEntryRef> File = LookupFile(
  1627. FilenameLoc, LookupFilename,
  1628. isAngled, LookupFrom, LookupFromFile, CurDir,
  1629. Callbacks ? &SearchPath : nullptr, Callbacks ? &RelativePath : nullptr,
  1630. &SuggestedModule, &IsMapped, &IsFrameworkFound);
  1631. if (File)
  1632. return File;
  1633. if (Callbacks) {
  1634. // Give the clients a chance to recover.
  1635. SmallString<128> RecoveryPath;
  1636. if (Callbacks->FileNotFound(Filename, RecoveryPath)) {
  1637. if (auto DE = FileMgr.getOptionalDirectoryRef(RecoveryPath)) {
  1638. // Add the recovery path to the list of search paths.
  1639. DirectoryLookup DL(*DE, SrcMgr::C_User, false);
  1640. HeaderInfo.AddSearchPath(DL, isAngled);
  1641. // Try the lookup again, skipping the cache.
  1642. Optional<FileEntryRef> File = LookupFile(
  1643. FilenameLoc,
  1644. LookupFilename, isAngled,
  1645. LookupFrom, LookupFromFile, CurDir, nullptr, nullptr,
  1646. &SuggestedModule, &IsMapped, /*IsFrameworkFound=*/nullptr,
  1647. /*SkipCache*/ true);
  1648. if (File)
  1649. return File;
  1650. }
  1651. }
  1652. }
  1653. if (SuppressIncludeNotFoundError)
  1654. return None;
  1655. // If the file could not be located and it was included via angle
  1656. // brackets, we can attempt a lookup as though it were a quoted path to
  1657. // provide the user with a possible fixit.
  1658. if (isAngled) {
  1659. Optional<FileEntryRef> File = LookupFile(
  1660. FilenameLoc, LookupFilename,
  1661. false, LookupFrom, LookupFromFile, CurDir,
  1662. Callbacks ? &SearchPath : nullptr, Callbacks ? &RelativePath : nullptr,
  1663. &SuggestedModule, &IsMapped,
  1664. /*IsFrameworkFound=*/nullptr);
  1665. if (File) {
  1666. Diag(FilenameTok, diag::err_pp_file_not_found_angled_include_not_fatal)
  1667. << Filename << IsImportDecl
  1668. << FixItHint::CreateReplacement(FilenameRange,
  1669. "\"" + Filename.str() + "\"");
  1670. return File;
  1671. }
  1672. }
  1673. // Check for likely typos due to leading or trailing non-isAlphanumeric
  1674. // characters
  1675. StringRef OriginalFilename = Filename;
  1676. if (LangOpts.SpellChecking) {
  1677. // A heuristic to correct a typo file name by removing leading and
  1678. // trailing non-isAlphanumeric characters.
  1679. auto CorrectTypoFilename = [](llvm::StringRef Filename) {
  1680. Filename = Filename.drop_until(isAlphanumeric);
  1681. while (!Filename.empty() && !isAlphanumeric(Filename.back())) {
  1682. Filename = Filename.drop_back();
  1683. }
  1684. return Filename;
  1685. };
  1686. StringRef TypoCorrectionName = CorrectTypoFilename(Filename);
  1687. StringRef TypoCorrectionLookupName = CorrectTypoFilename(LookupFilename);
  1688. Optional<FileEntryRef> File = LookupFile(
  1689. FilenameLoc, TypoCorrectionLookupName, isAngled, LookupFrom, LookupFromFile,
  1690. CurDir, Callbacks ? &SearchPath : nullptr,
  1691. Callbacks ? &RelativePath : nullptr, &SuggestedModule, &IsMapped,
  1692. /*IsFrameworkFound=*/nullptr);
  1693. if (File) {
  1694. auto Hint =
  1695. isAngled ? FixItHint::CreateReplacement(
  1696. FilenameRange, "<" + TypoCorrectionName.str() + ">")
  1697. : FixItHint::CreateReplacement(
  1698. FilenameRange, "\"" + TypoCorrectionName.str() + "\"");
  1699. Diag(FilenameTok, diag::err_pp_file_not_found_typo_not_fatal)
  1700. << OriginalFilename << TypoCorrectionName << Hint;
  1701. // We found the file, so set the Filename to the name after typo
  1702. // correction.
  1703. Filename = TypoCorrectionName;
  1704. LookupFilename = TypoCorrectionLookupName;
  1705. return File;
  1706. }
  1707. }
  1708. // If the file is still not found, just go with the vanilla diagnostic
  1709. assert(!File.hasValue() && "expected missing file");
  1710. Diag(FilenameTok, diag::err_pp_file_not_found)
  1711. << OriginalFilename << FilenameRange;
  1712. if (IsFrameworkFound) {
  1713. size_t SlashPos = OriginalFilename.find('/');
  1714. assert(SlashPos != StringRef::npos &&
  1715. "Include with framework name should have '/' in the filename");
  1716. StringRef FrameworkName = OriginalFilename.substr(0, SlashPos);
  1717. FrameworkCacheEntry &CacheEntry =
  1718. HeaderInfo.LookupFrameworkCache(FrameworkName);
  1719. assert(CacheEntry.Directory && "Found framework should be in cache");
  1720. Diag(FilenameTok, diag::note_pp_framework_without_header)
  1721. << OriginalFilename.substr(SlashPos + 1) << FrameworkName
  1722. << CacheEntry.Directory->getName();
  1723. }
  1724. return None;
  1725. }
  1726. /// Handle either a #include-like directive or an import declaration that names
  1727. /// a header file.
  1728. ///
  1729. /// \param HashLoc The location of the '#' token for an include, or
  1730. /// SourceLocation() for an import declaration.
  1731. /// \param IncludeTok The include / include_next / import token.
  1732. /// \param FilenameTok The header-name token.
  1733. /// \param EndLoc The location at which any imported macros become visible.
  1734. /// \param LookupFrom For #include_next, the starting directory for the
  1735. /// directory lookup.
  1736. /// \param LookupFromFile For #include_next, the starting file for the directory
  1737. /// lookup.
  1738. Preprocessor::ImportAction Preprocessor::HandleHeaderIncludeOrImport(
  1739. SourceLocation HashLoc, Token &IncludeTok, Token &FilenameTok,
  1740. SourceLocation EndLoc, const DirectoryLookup *LookupFrom,
  1741. const FileEntry *LookupFromFile) {
  1742. SmallString<128> FilenameBuffer;
  1743. StringRef Filename = getSpelling(FilenameTok, FilenameBuffer);
  1744. SourceLocation CharEnd = FilenameTok.getEndLoc();
  1745. CharSourceRange FilenameRange
  1746. = CharSourceRange::getCharRange(FilenameTok.getLocation(), CharEnd);
  1747. StringRef OriginalFilename = Filename;
  1748. bool isAngled =
  1749. GetIncludeFilenameSpelling(FilenameTok.getLocation(), Filename);
  1750. // If GetIncludeFilenameSpelling set the start ptr to null, there was an
  1751. // error.
  1752. if (Filename.empty())
  1753. return {ImportAction::None};
  1754. bool IsImportDecl = HashLoc.isInvalid();
  1755. SourceLocation StartLoc = IsImportDecl ? IncludeTok.getLocation() : HashLoc;
  1756. // Complain about attempts to #include files in an audit pragma.
  1757. if (PragmaARCCFCodeAuditedInfo.second.isValid()) {
  1758. Diag(StartLoc, diag::err_pp_include_in_arc_cf_code_audited) << IsImportDecl;
  1759. Diag(PragmaARCCFCodeAuditedInfo.second, diag::note_pragma_entered_here);
  1760. // Immediately leave the pragma.
  1761. PragmaARCCFCodeAuditedInfo = {nullptr, SourceLocation()};
  1762. }
  1763. // Complain about attempts to #include files in an assume-nonnull pragma.
  1764. if (PragmaAssumeNonNullLoc.isValid()) {
  1765. Diag(StartLoc, diag::err_pp_include_in_assume_nonnull) << IsImportDecl;
  1766. Diag(PragmaAssumeNonNullLoc, diag::note_pragma_entered_here);
  1767. // Immediately leave the pragma.
  1768. PragmaAssumeNonNullLoc = SourceLocation();
  1769. }
  1770. if (HeaderInfo.HasIncludeAliasMap()) {
  1771. // Map the filename with the brackets still attached. If the name doesn't
  1772. // map to anything, fall back on the filename we've already gotten the
  1773. // spelling for.
  1774. StringRef NewName = HeaderInfo.MapHeaderToIncludeAlias(OriginalFilename);
  1775. if (!NewName.empty())
  1776. Filename = NewName;
  1777. }
  1778. // Search include directories.
  1779. bool IsMapped = false;
  1780. bool IsFrameworkFound = false;
  1781. const DirectoryLookup *CurDir;
  1782. SmallString<1024> SearchPath;
  1783. SmallString<1024> RelativePath;
  1784. // We get the raw path only if we have 'Callbacks' to which we later pass
  1785. // the path.
  1786. ModuleMap::KnownHeader SuggestedModule;
  1787. SourceLocation FilenameLoc = FilenameTok.getLocation();
  1788. StringRef LookupFilename = Filename;
  1789. // Normalize slashes when compiling with -fms-extensions on non-Windows. This
  1790. // is unnecessary on Windows since the filesystem there handles backslashes.
  1791. SmallString<128> NormalizedPath;
  1792. llvm::sys::path::Style BackslashStyle = llvm::sys::path::Style::native;
  1793. if (is_style_posix(BackslashStyle) && LangOpts.MicrosoftExt) {
  1794. NormalizedPath = Filename.str();
  1795. llvm::sys::path::native(NormalizedPath);
  1796. LookupFilename = NormalizedPath;
  1797. BackslashStyle = llvm::sys::path::Style::windows;
  1798. }
  1799. Optional<FileEntryRef> File = LookupHeaderIncludeOrImport(
  1800. &CurDir, Filename, FilenameLoc, FilenameRange, FilenameTok,
  1801. IsFrameworkFound, IsImportDecl, IsMapped, LookupFrom, LookupFromFile,
  1802. LookupFilename, RelativePath, SearchPath, SuggestedModule, isAngled);
  1803. // Record the header's filename for later use.
  1804. if (File)
  1805. CurLexer->addInclude(OriginalFilename, File->getFileEntry(), FilenameLoc);
  1806. if (usingPCHWithThroughHeader() && SkippingUntilPCHThroughHeader) {
  1807. if (File && isPCHThroughHeader(&File->getFileEntry()))
  1808. SkippingUntilPCHThroughHeader = false;
  1809. return {ImportAction::None};
  1810. }
  1811. // Should we enter the source file? Set to Skip if either the source file is
  1812. // known to have no effect beyond its effect on module visibility -- that is,
  1813. // if it's got an include guard that is already defined, set to Import if it
  1814. // is a modular header we've already built and should import.
  1815. enum { Enter, Import, Skip, IncludeLimitReached } Action = Enter;
  1816. if (PPOpts->SingleFileParseMode)
  1817. Action = IncludeLimitReached;
  1818. // If we've reached the max allowed include depth, it is usually due to an
  1819. // include cycle. Don't enter already processed files again as it can lead to
  1820. // reaching the max allowed include depth again.
  1821. if (Action == Enter && HasReachedMaxIncludeDepth && File &&
  1822. alreadyIncluded(*File))
  1823. Action = IncludeLimitReached;
  1824. // Determine whether we should try to import the module for this #include, if
  1825. // there is one. Don't do so if precompiled module support is disabled or we
  1826. // are processing this module textually (because we're building the module).
  1827. if (Action == Enter && File && SuggestedModule && getLangOpts().Modules &&
  1828. !isForModuleBuilding(SuggestedModule.getModule(),
  1829. getLangOpts().CurrentModule,
  1830. getLangOpts().ModuleName)) {
  1831. // If this include corresponds to a module but that module is
  1832. // unavailable, diagnose the situation and bail out.
  1833. // FIXME: Remove this; loadModule does the same check (but produces
  1834. // slightly worse diagnostics).
  1835. if (checkModuleIsAvailable(getLangOpts(), getTargetInfo(), getDiagnostics(),
  1836. SuggestedModule.getModule())) {
  1837. Diag(FilenameTok.getLocation(),
  1838. diag::note_implicit_top_level_module_import_here)
  1839. << SuggestedModule.getModule()->getTopLevelModuleName();
  1840. return {ImportAction::None};
  1841. }
  1842. // Compute the module access path corresponding to this module.
  1843. // FIXME: Should we have a second loadModule() overload to avoid this
  1844. // extra lookup step?
  1845. SmallVector<std::pair<IdentifierInfo *, SourceLocation>, 2> Path;
  1846. for (Module *Mod = SuggestedModule.getModule(); Mod; Mod = Mod->Parent)
  1847. Path.push_back(std::make_pair(getIdentifierInfo(Mod->Name),
  1848. FilenameTok.getLocation()));
  1849. std::reverse(Path.begin(), Path.end());
  1850. // Warn that we're replacing the include/import with a module import.
  1851. if (!IsImportDecl)
  1852. diagnoseAutoModuleImport(*this, StartLoc, IncludeTok, Path, CharEnd);
  1853. // Load the module to import its macros. We'll make the declarations
  1854. // visible when the parser gets here.
  1855. // FIXME: Pass SuggestedModule in here rather than converting it to a path
  1856. // and making the module loader convert it back again.
  1857. ModuleLoadResult Imported = TheModuleLoader.loadModule(
  1858. IncludeTok.getLocation(), Path, Module::Hidden,
  1859. /*IsInclusionDirective=*/true);
  1860. assert((Imported == nullptr || Imported == SuggestedModule.getModule()) &&
  1861. "the imported module is different than the suggested one");
  1862. if (Imported) {
  1863. Action = Import;
  1864. } else if (Imported.isMissingExpected()) {
  1865. // We failed to find a submodule that we assumed would exist (because it
  1866. // was in the directory of an umbrella header, for instance), but no
  1867. // actual module containing it exists (because the umbrella header is
  1868. // incomplete). Treat this as a textual inclusion.
  1869. SuggestedModule = ModuleMap::KnownHeader();
  1870. } else if (Imported.isConfigMismatch()) {
  1871. // On a configuration mismatch, enter the header textually. We still know
  1872. // that it's part of the corresponding module.
  1873. } else {
  1874. // We hit an error processing the import. Bail out.
  1875. if (hadModuleLoaderFatalFailure()) {
  1876. // With a fatal failure in the module loader, we abort parsing.
  1877. Token &Result = IncludeTok;
  1878. assert(CurLexer && "#include but no current lexer set!");
  1879. Result.startToken();
  1880. CurLexer->FormTokenWithChars(Result, CurLexer->BufferEnd, tok::eof);
  1881. CurLexer->cutOffLexing();
  1882. }
  1883. return {ImportAction::None};
  1884. }
  1885. }
  1886. // The #included file will be considered to be a system header if either it is
  1887. // in a system include directory, or if the #includer is a system include
  1888. // header.
  1889. SrcMgr::CharacteristicKind FileCharacter =
  1890. SourceMgr.getFileCharacteristic(FilenameTok.getLocation());
  1891. if (File)
  1892. FileCharacter = std::max(HeaderInfo.getFileDirFlavor(&File->getFileEntry()),
  1893. FileCharacter);
  1894. // If this is a '#import' or an import-declaration, don't re-enter the file.
  1895. //
  1896. // FIXME: If we have a suggested module for a '#include', and we've already
  1897. // visited this file, don't bother entering it again. We know it has no
  1898. // further effect.
  1899. bool EnterOnce =
  1900. IsImportDecl ||
  1901. IncludeTok.getIdentifierInfo()->getPPKeywordID() == tok::pp_import;
  1902. bool IsFirstIncludeOfFile = false;
  1903. // Ask HeaderInfo if we should enter this #include file. If not, #including
  1904. // this file will have no effect.
  1905. if (Action == Enter && File &&
  1906. !HeaderInfo.ShouldEnterIncludeFile(
  1907. *this, &File->getFileEntry(), EnterOnce, getLangOpts().Modules,
  1908. SuggestedModule.getModule(), IsFirstIncludeOfFile)) {
  1909. // Even if we've already preprocessed this header once and know that we
  1910. // don't need to see its contents again, we still need to import it if it's
  1911. // modular because we might not have imported it from this submodule before.
  1912. //
  1913. // FIXME: We don't do this when compiling a PCH because the AST
  1914. // serialization layer can't cope with it. This means we get local
  1915. // submodule visibility semantics wrong in that case.
  1916. Action = (SuggestedModule && !getLangOpts().CompilingPCH) ? Import : Skip;
  1917. }
  1918. // Check for circular inclusion of the main file.
  1919. // We can't generate a consistent preamble with regard to the conditional
  1920. // stack if the main file is included again as due to the preamble bounds
  1921. // some directives (e.g. #endif of a header guard) will never be seen.
  1922. // Since this will lead to confusing errors, avoid the inclusion.
  1923. if (Action == Enter && File && PreambleConditionalStack.isRecording() &&
  1924. SourceMgr.isMainFile(File->getFileEntry())) {
  1925. Diag(FilenameTok.getLocation(),
  1926. diag::err_pp_including_mainfile_in_preamble);
  1927. return {ImportAction::None};
  1928. }
  1929. if (Callbacks && !IsImportDecl) {
  1930. // Notify the callback object that we've seen an inclusion directive.
  1931. // FIXME: Use a different callback for a pp-import?
  1932. Callbacks->InclusionDirective(
  1933. HashLoc, IncludeTok, LookupFilename, isAngled, FilenameRange,
  1934. File ? &File->getFileEntry() : nullptr, SearchPath, RelativePath,
  1935. Action == Import ? SuggestedModule.getModule() : nullptr,
  1936. FileCharacter);
  1937. if (Action == Skip && File)
  1938. Callbacks->FileSkipped(*File, FilenameTok, FileCharacter);
  1939. }
  1940. if (!File)
  1941. return {ImportAction::None};
  1942. // If this is a C++20 pp-import declaration, diagnose if we didn't find any
  1943. // module corresponding to the named header.
  1944. if (IsImportDecl && !SuggestedModule) {
  1945. Diag(FilenameTok, diag::err_header_import_not_header_unit)
  1946. << OriginalFilename << File->getName();
  1947. return {ImportAction::None};
  1948. }
  1949. // Issue a diagnostic if the name of the file on disk has a different case
  1950. // than the one we're about to open.
  1951. const bool CheckIncludePathPortability =
  1952. !LangOpts.CaseInsensitive && !IsMapped && !File->getFileEntry().tryGetRealPathName().empty();
  1953. if (CheckIncludePathPortability) {
  1954. StringRef Name = LookupFilename;
  1955. StringRef NameWithoriginalSlashes = Filename;
  1956. #if defined(_WIN32)
  1957. // Skip UNC prefix if present. (tryGetRealPathName() always
  1958. // returns a path with the prefix skipped.)
  1959. bool NameWasUNC = Name.consume_front("\\\\?\\");
  1960. NameWithoriginalSlashes.consume_front("\\\\?\\");
  1961. #endif
  1962. StringRef RealPathName = File->getFileEntry().tryGetRealPathName();
  1963. SmallVector<StringRef, 16> Components(llvm::sys::path::begin(Name),
  1964. llvm::sys::path::end(Name));
  1965. #if defined(_WIN32)
  1966. // -Wnonportable-include-path is designed to diagnose includes using
  1967. // case even on systems with a case-insensitive file system.
  1968. // On Windows, RealPathName always starts with an upper-case drive
  1969. // letter for absolute paths, but Name might start with either
  1970. // case depending on if `cd c:\foo` or `cd C:\foo` was used in the shell.
  1971. // ("foo" will always have on-disk case, no matter which case was
  1972. // used in the cd command). To not emit this warning solely for
  1973. // the drive letter, whose case is dependent on if `cd` is used
  1974. // with upper- or lower-case drive letters, always consider the
  1975. // given drive letter case as correct for the purpose of this warning.
  1976. SmallString<128> FixedDriveRealPath;
  1977. if (llvm::sys::path::is_absolute(Name) &&
  1978. llvm::sys::path::is_absolute(RealPathName) &&
  1979. toLowercase(Name[0]) == toLowercase(RealPathName[0]) &&
  1980. isLowercase(Name[0]) != isLowercase(RealPathName[0])) {
  1981. assert(Components.size() >= 3 && "should have drive, backslash, name");
  1982. assert(Components[0].size() == 2 && "should start with drive");
  1983. assert(Components[0][1] == ':' && "should have colon");
  1984. FixedDriveRealPath = (Name.substr(0, 1) + RealPathName.substr(1)).str();
  1985. RealPathName = FixedDriveRealPath;
  1986. }
  1987. #endif
  1988. if (trySimplifyPath(Components, RealPathName)) {
  1989. SmallString<128> Path;
  1990. Path.reserve(Name.size()+2);
  1991. Path.push_back(isAngled ? '<' : '"');
  1992. const auto IsSep = [BackslashStyle](char c) {
  1993. return llvm::sys::path::is_separator(c, BackslashStyle);
  1994. };
  1995. for (auto Component : Components) {
  1996. // On POSIX, Components will contain a single '/' as first element
  1997. // exactly if Name is an absolute path.
  1998. // On Windows, it will contain "C:" followed by '\' for absolute paths.
  1999. // The drive letter is optional for absolute paths on Windows, but
  2000. // clang currently cannot process absolute paths in #include lines that
  2001. // don't have a drive.
  2002. // If the first entry in Components is a directory separator,
  2003. // then the code at the bottom of this loop that keeps the original
  2004. // directory separator style copies it. If the second entry is
  2005. // a directory separator (the C:\ case), then that separator already
  2006. // got copied when the C: was processed and we want to skip that entry.
  2007. if (!(Component.size() == 1 && IsSep(Component[0])))
  2008. Path.append(Component);
  2009. else if (!Path.empty())
  2010. continue;
  2011. // Append the separator(s) the user used, or the close quote
  2012. if (Path.size() > NameWithoriginalSlashes.size()) {
  2013. Path.push_back(isAngled ? '>' : '"');
  2014. continue;
  2015. }
  2016. assert(IsSep(NameWithoriginalSlashes[Path.size()-1]));
  2017. do
  2018. Path.push_back(NameWithoriginalSlashes[Path.size()-1]);
  2019. while (Path.size() <= NameWithoriginalSlashes.size() &&
  2020. IsSep(NameWithoriginalSlashes[Path.size()-1]));
  2021. }
  2022. #if defined(_WIN32)
  2023. // Restore UNC prefix if it was there.
  2024. if (NameWasUNC)
  2025. Path = (Path.substr(0, 1) + "\\\\?\\" + Path.substr(1)).str();
  2026. #endif
  2027. // For user files and known standard headers, issue a diagnostic.
  2028. // For other system headers, don't. They can be controlled separately.
  2029. auto DiagId =
  2030. (FileCharacter == SrcMgr::C_User || warnByDefaultOnWrongCase(Name))
  2031. ? diag::pp_nonportable_path
  2032. : diag::pp_nonportable_system_path;
  2033. Diag(FilenameTok, DiagId) << Path <<
  2034. FixItHint::CreateReplacement(FilenameRange, Path);
  2035. }
  2036. }
  2037. switch (Action) {
  2038. case Skip:
  2039. // If we don't need to enter the file, stop now.
  2040. if (Module *M = SuggestedModule.getModule())
  2041. return {ImportAction::SkippedModuleImport, M};
  2042. return {ImportAction::None};
  2043. case IncludeLimitReached:
  2044. // If we reached our include limit and don't want to enter any more files,
  2045. // don't go any further.
  2046. return {ImportAction::None};
  2047. case Import: {
  2048. // If this is a module import, make it visible if needed.
  2049. Module *M = SuggestedModule.getModule();
  2050. assert(M && "no module to import");
  2051. makeModuleVisible(M, EndLoc);
  2052. if (IncludeTok.getIdentifierInfo()->getPPKeywordID() ==
  2053. tok::pp___include_macros)
  2054. return {ImportAction::None};
  2055. return {ImportAction::ModuleImport, M};
  2056. }
  2057. case Enter:
  2058. break;
  2059. }
  2060. // Check that we don't have infinite #include recursion.
  2061. if (IncludeMacroStack.size() == MaxAllowedIncludeStackDepth-1) {
  2062. Diag(FilenameTok, diag::err_pp_include_too_deep);
  2063. HasReachedMaxIncludeDepth = true;
  2064. return {ImportAction::None};
  2065. }
  2066. // Look up the file, create a File ID for it.
  2067. SourceLocation IncludePos = FilenameTok.getLocation();
  2068. // If the filename string was the result of macro expansions, set the include
  2069. // position on the file where it will be included and after the expansions.
  2070. if (IncludePos.isMacroID())
  2071. IncludePos = SourceMgr.getExpansionRange(IncludePos).getEnd();
  2072. FileID FID = SourceMgr.createFileID(*File, IncludePos, FileCharacter);
  2073. if (!FID.isValid()) {
  2074. TheModuleLoader.HadFatalFailure = true;
  2075. return ImportAction::Failure;
  2076. }
  2077. // If all is good, enter the new file!
  2078. if (EnterSourceFile(FID, CurDir, FilenameTok.getLocation(),
  2079. IsFirstIncludeOfFile))
  2080. return {ImportAction::None};
  2081. // Determine if we're switching to building a new submodule, and which one.
  2082. if (auto *M = SuggestedModule.getModule()) {
  2083. if (M->getTopLevelModule()->ShadowingModule) {
  2084. // We are building a submodule that belongs to a shadowed module. This
  2085. // means we find header files in the shadowed module.
  2086. Diag(M->DefinitionLoc, diag::err_module_build_shadowed_submodule)
  2087. << M->getFullModuleName();
  2088. Diag(M->getTopLevelModule()->ShadowingModule->DefinitionLoc,
  2089. diag::note_previous_definition);
  2090. return {ImportAction::None};
  2091. }
  2092. // When building a pch, -fmodule-name tells the compiler to textually
  2093. // include headers in the specified module. We are not building the
  2094. // specified module.
  2095. //
  2096. // FIXME: This is the wrong way to handle this. We should produce a PCH
  2097. // that behaves the same as the header would behave in a compilation using
  2098. // that PCH, which means we should enter the submodule. We need to teach
  2099. // the AST serialization layer to deal with the resulting AST.
  2100. if (getLangOpts().CompilingPCH &&
  2101. isForModuleBuilding(M, getLangOpts().CurrentModule,
  2102. getLangOpts().ModuleName))
  2103. return {ImportAction::None};
  2104. assert(!CurLexerSubmodule && "should not have marked this as a module yet");
  2105. CurLexerSubmodule = M;
  2106. // Let the macro handling code know that any future macros are within
  2107. // the new submodule.
  2108. EnterSubmodule(M, EndLoc, /*ForPragma*/false);
  2109. // Let the parser know that any future declarations are within the new
  2110. // submodule.
  2111. // FIXME: There's no point doing this if we're handling a #__include_macros
  2112. // directive.
  2113. return {ImportAction::ModuleBegin, M};
  2114. }
  2115. assert(!IsImportDecl && "failed to diagnose missing module for import decl");
  2116. return {ImportAction::None};
  2117. }
  2118. /// HandleIncludeNextDirective - Implements \#include_next.
  2119. ///
  2120. void Preprocessor::HandleIncludeNextDirective(SourceLocation HashLoc,
  2121. Token &IncludeNextTok) {
  2122. Diag(IncludeNextTok, diag::ext_pp_include_next_directive);
  2123. // #include_next is like #include, except that we start searching after
  2124. // the current found directory. If we can't do this, issue a
  2125. // diagnostic.
  2126. const DirectoryLookup *Lookup = CurDirLookup;
  2127. const FileEntry *LookupFromFile = nullptr;
  2128. if (isInPrimaryFile() && LangOpts.IsHeaderFile) {
  2129. // If the main file is a header, then it's either for PCH/AST generation,
  2130. // or libclang opened it. Either way, handle it as a normal include below
  2131. // and do not complain about include_next.
  2132. } else if (isInPrimaryFile()) {
  2133. Lookup = nullptr;
  2134. Diag(IncludeNextTok, diag::pp_include_next_in_primary);
  2135. } else if (CurLexerSubmodule) {
  2136. // Start looking up in the directory *after* the one in which the current
  2137. // file would be found, if any.
  2138. assert(CurPPLexer && "#include_next directive in macro?");
  2139. LookupFromFile = CurPPLexer->getFileEntry();
  2140. Lookup = nullptr;
  2141. } else if (!Lookup) {
  2142. // The current file was not found by walking the include path. Either it
  2143. // is the primary file (handled above), or it was found by absolute path,
  2144. // or it was found relative to such a file.
  2145. // FIXME: Track enough information so we know which case we're in.
  2146. Diag(IncludeNextTok, diag::pp_include_next_absolute_path);
  2147. } else {
  2148. // Start looking up in the next directory.
  2149. ++Lookup;
  2150. }
  2151. return HandleIncludeDirective(HashLoc, IncludeNextTok, Lookup,
  2152. LookupFromFile);
  2153. }
  2154. /// HandleMicrosoftImportDirective - Implements \#import for Microsoft Mode
  2155. void Preprocessor::HandleMicrosoftImportDirective(Token &Tok) {
  2156. // The Microsoft #import directive takes a type library and generates header
  2157. // files from it, and includes those. This is beyond the scope of what clang
  2158. // does, so we ignore it and error out. However, #import can optionally have
  2159. // trailing attributes that span multiple lines. We're going to eat those
  2160. // so we can continue processing from there.
  2161. Diag(Tok, diag::err_pp_import_directive_ms );
  2162. // Read tokens until we get to the end of the directive. Note that the
  2163. // directive can be split over multiple lines using the backslash character.
  2164. DiscardUntilEndOfDirective();
  2165. }
  2166. /// HandleImportDirective - Implements \#import.
  2167. ///
  2168. void Preprocessor::HandleImportDirective(SourceLocation HashLoc,
  2169. Token &ImportTok) {
  2170. if (!LangOpts.ObjC) { // #import is standard for ObjC.
  2171. if (LangOpts.MSVCCompat)
  2172. return HandleMicrosoftImportDirective(ImportTok);
  2173. Diag(ImportTok, diag::ext_pp_import_directive);
  2174. }
  2175. return HandleIncludeDirective(HashLoc, ImportTok);
  2176. }
  2177. /// HandleIncludeMacrosDirective - The -imacros command line option turns into a
  2178. /// pseudo directive in the predefines buffer. This handles it by sucking all
  2179. /// tokens through the preprocessor and discarding them (only keeping the side
  2180. /// effects on the preprocessor).
  2181. void Preprocessor::HandleIncludeMacrosDirective(SourceLocation HashLoc,
  2182. Token &IncludeMacrosTok) {
  2183. // This directive should only occur in the predefines buffer. If not, emit an
  2184. // error and reject it.
  2185. SourceLocation Loc = IncludeMacrosTok.getLocation();
  2186. if (SourceMgr.getBufferName(Loc) != "<built-in>") {
  2187. Diag(IncludeMacrosTok.getLocation(),
  2188. diag::pp_include_macros_out_of_predefines);
  2189. DiscardUntilEndOfDirective();
  2190. return;
  2191. }
  2192. // Treat this as a normal #include for checking purposes. If this is
  2193. // successful, it will push a new lexer onto the include stack.
  2194. HandleIncludeDirective(HashLoc, IncludeMacrosTok);
  2195. Token TmpTok;
  2196. do {
  2197. Lex(TmpTok);
  2198. assert(TmpTok.isNot(tok::eof) && "Didn't find end of -imacros!");
  2199. } while (TmpTok.isNot(tok::hashhash));
  2200. }
  2201. //===----------------------------------------------------------------------===//
  2202. // Preprocessor Macro Directive Handling.
  2203. //===----------------------------------------------------------------------===//
  2204. /// ReadMacroParameterList - The ( starting a parameter list of a macro
  2205. /// definition has just been read. Lex the rest of the parameters and the
  2206. /// closing ), updating MI with what we learn. Return true if an error occurs
  2207. /// parsing the param list.
  2208. bool Preprocessor::ReadMacroParameterList(MacroInfo *MI, Token &Tok) {
  2209. SmallVector<IdentifierInfo*, 32> Parameters;
  2210. while (true) {
  2211. LexUnexpandedToken(Tok);
  2212. switch (Tok.getKind()) {
  2213. case tok::r_paren:
  2214. // Found the end of the parameter list.
  2215. if (Parameters.empty()) // #define FOO()
  2216. return false;
  2217. // Otherwise we have #define FOO(A,)
  2218. Diag(Tok, diag::err_pp_expected_ident_in_arg_list);
  2219. return true;
  2220. case tok::ellipsis: // #define X(... -> C99 varargs
  2221. if (!LangOpts.C99)
  2222. Diag(Tok, LangOpts.CPlusPlus11 ?
  2223. diag::warn_cxx98_compat_variadic_macro :
  2224. diag::ext_variadic_macro);
  2225. // OpenCL v1.2 s6.9.e: variadic macros are not supported.
  2226. if (LangOpts.OpenCL && !LangOpts.OpenCLCPlusPlus) {
  2227. Diag(Tok, diag::ext_pp_opencl_variadic_macros);
  2228. }
  2229. // Lex the token after the identifier.
  2230. LexUnexpandedToken(Tok);
  2231. if (Tok.isNot(tok::r_paren)) {
  2232. Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
  2233. return true;
  2234. }
  2235. // Add the __VA_ARGS__ identifier as a parameter.
  2236. Parameters.push_back(Ident__VA_ARGS__);
  2237. MI->setIsC99Varargs();
  2238. MI->setParameterList(Parameters, BP);
  2239. return false;
  2240. case tok::eod: // #define X(
  2241. Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
  2242. return true;
  2243. default:
  2244. // Handle keywords and identifiers here to accept things like
  2245. // #define Foo(for) for.
  2246. IdentifierInfo *II = Tok.getIdentifierInfo();
  2247. if (!II) {
  2248. // #define X(1
  2249. Diag(Tok, diag::err_pp_invalid_tok_in_arg_list);
  2250. return true;
  2251. }
  2252. // If this is already used as a parameter, it is used multiple times (e.g.
  2253. // #define X(A,A.
  2254. if (llvm::is_contained(Parameters, II)) { // C99 6.10.3p6
  2255. Diag(Tok, diag::err_pp_duplicate_name_in_arg_list) << II;
  2256. return true;
  2257. }
  2258. // Add the parameter to the macro info.
  2259. Parameters.push_back(II);
  2260. // Lex the token after the identifier.
  2261. LexUnexpandedToken(Tok);
  2262. switch (Tok.getKind()) {
  2263. default: // #define X(A B
  2264. Diag(Tok, diag::err_pp_expected_comma_in_arg_list);
  2265. return true;
  2266. case tok::r_paren: // #define X(A)
  2267. MI->setParameterList(Parameters, BP);
  2268. return false;
  2269. case tok::comma: // #define X(A,
  2270. break;
  2271. case tok::ellipsis: // #define X(A... -> GCC extension
  2272. // Diagnose extension.
  2273. Diag(Tok, diag::ext_named_variadic_macro);
  2274. // Lex the token after the identifier.
  2275. LexUnexpandedToken(Tok);
  2276. if (Tok.isNot(tok::r_paren)) {
  2277. Diag(Tok, diag::err_pp_missing_rparen_in_macro_def);
  2278. return true;
  2279. }
  2280. MI->setIsGNUVarargs();
  2281. MI->setParameterList(Parameters, BP);
  2282. return false;
  2283. }
  2284. }
  2285. }
  2286. }
  2287. static bool isConfigurationPattern(Token &MacroName, MacroInfo *MI,
  2288. const LangOptions &LOptions) {
  2289. if (MI->getNumTokens() == 1) {
  2290. const Token &Value = MI->getReplacementToken(0);
  2291. // Macro that is identity, like '#define inline inline' is a valid pattern.
  2292. if (MacroName.getKind() == Value.getKind())
  2293. return true;
  2294. // Macro that maps a keyword to the same keyword decorated with leading/
  2295. // trailing underscores is a valid pattern:
  2296. // #define inline __inline
  2297. // #define inline __inline__
  2298. // #define inline _inline (in MS compatibility mode)
  2299. StringRef MacroText = MacroName.getIdentifierInfo()->getName();
  2300. if (IdentifierInfo *II = Value.getIdentifierInfo()) {
  2301. if (!II->isKeyword(LOptions))
  2302. return false;
  2303. StringRef ValueText = II->getName();
  2304. StringRef TrimmedValue = ValueText;
  2305. if (!ValueText.startswith("__")) {
  2306. if (ValueText.startswith("_"))
  2307. TrimmedValue = TrimmedValue.drop_front(1);
  2308. else
  2309. return false;
  2310. } else {
  2311. TrimmedValue = TrimmedValue.drop_front(2);
  2312. if (TrimmedValue.endswith("__"))
  2313. TrimmedValue = TrimmedValue.drop_back(2);
  2314. }
  2315. return TrimmedValue.equals(MacroText);
  2316. } else {
  2317. return false;
  2318. }
  2319. }
  2320. // #define inline
  2321. return MacroName.isOneOf(tok::kw_extern, tok::kw_inline, tok::kw_static,
  2322. tok::kw_const) &&
  2323. MI->getNumTokens() == 0;
  2324. }
  2325. // ReadOptionalMacroParameterListAndBody - This consumes all (i.e. the
  2326. // entire line) of the macro's tokens and adds them to MacroInfo, and while
  2327. // doing so performs certain validity checks including (but not limited to):
  2328. // - # (stringization) is followed by a macro parameter
  2329. //
  2330. // Returns a nullptr if an invalid sequence of tokens is encountered or returns
  2331. // a pointer to a MacroInfo object.
  2332. MacroInfo *Preprocessor::ReadOptionalMacroParameterListAndBody(
  2333. const Token &MacroNameTok, const bool ImmediatelyAfterHeaderGuard) {
  2334. Token LastTok = MacroNameTok;
  2335. // Create the new macro.
  2336. MacroInfo *const MI = AllocateMacroInfo(MacroNameTok.getLocation());
  2337. Token Tok;
  2338. LexUnexpandedToken(Tok);
  2339. // Ensure we consume the rest of the macro body if errors occur.
  2340. auto _ = llvm::make_scope_exit([&]() {
  2341. // The flag indicates if we are still waiting for 'eod'.
  2342. if (CurLexer->ParsingPreprocessorDirective)
  2343. DiscardUntilEndOfDirective();
  2344. });
  2345. // Used to un-poison and then re-poison identifiers of the __VA_ARGS__ ilk
  2346. // within their appropriate context.
  2347. VariadicMacroScopeGuard VariadicMacroScopeGuard(*this);
  2348. // If this is a function-like macro definition, parse the argument list,
  2349. // marking each of the identifiers as being used as macro arguments. Also,
  2350. // check other constraints on the first token of the macro body.
  2351. if (Tok.is(tok::eod)) {
  2352. if (ImmediatelyAfterHeaderGuard) {
  2353. // Save this macro information since it may part of a header guard.
  2354. CurPPLexer->MIOpt.SetDefinedMacro(MacroNameTok.getIdentifierInfo(),
  2355. MacroNameTok.getLocation());
  2356. }
  2357. // If there is no body to this macro, we have no special handling here.
  2358. } else if (Tok.hasLeadingSpace()) {
  2359. // This is a normal token with leading space. Clear the leading space
  2360. // marker on the first token to get proper expansion.
  2361. Tok.clearFlag(Token::LeadingSpace);
  2362. } else if (Tok.is(tok::l_paren)) {
  2363. // This is a function-like macro definition. Read the argument list.
  2364. MI->setIsFunctionLike();
  2365. if (ReadMacroParameterList(MI, LastTok))
  2366. return nullptr;
  2367. // If this is a definition of an ISO C/C++ variadic function-like macro (not
  2368. // using the GNU named varargs extension) inform our variadic scope guard
  2369. // which un-poisons and re-poisons certain identifiers (e.g. __VA_ARGS__)
  2370. // allowed only within the definition of a variadic macro.
  2371. if (MI->isC99Varargs()) {
  2372. VariadicMacroScopeGuard.enterScope();
  2373. }
  2374. // Read the first token after the arg list for down below.
  2375. LexUnexpandedToken(Tok);
  2376. } else if (LangOpts.C99 || LangOpts.CPlusPlus11) {
  2377. // C99 requires whitespace between the macro definition and the body. Emit
  2378. // a diagnostic for something like "#define X+".
  2379. Diag(Tok, diag::ext_c99_whitespace_required_after_macro_name);
  2380. } else {
  2381. // C90 6.8 TC1 says: "In the definition of an object-like macro, if the
  2382. // first character of a replacement list is not a character required by
  2383. // subclause 5.2.1, then there shall be white-space separation between the
  2384. // identifier and the replacement list.". 5.2.1 lists this set:
  2385. // "A-Za-z0-9!"#%&'()*+,_./:;<=>?[\]^_{|}~" as well as whitespace, which
  2386. // is irrelevant here.
  2387. bool isInvalid = false;
  2388. if (Tok.is(tok::at)) // @ is not in the list above.
  2389. isInvalid = true;
  2390. else if (Tok.is(tok::unknown)) {
  2391. // If we have an unknown token, it is something strange like "`". Since
  2392. // all of valid characters would have lexed into a single character
  2393. // token of some sort, we know this is not a valid case.
  2394. isInvalid = true;
  2395. }
  2396. if (isInvalid)
  2397. Diag(Tok, diag::ext_missing_whitespace_after_macro_name);
  2398. else
  2399. Diag(Tok, diag::warn_missing_whitespace_after_macro_name);
  2400. }
  2401. if (!Tok.is(tok::eod))
  2402. LastTok = Tok;
  2403. // Read the rest of the macro body.
  2404. if (MI->isObjectLike()) {
  2405. // Object-like macros are very simple, just read their body.
  2406. while (Tok.isNot(tok::eod)) {
  2407. LastTok = Tok;
  2408. MI->AddTokenToBody(Tok);
  2409. // Get the next token of the macro.
  2410. LexUnexpandedToken(Tok);
  2411. }
  2412. } else {
  2413. // Otherwise, read the body of a function-like macro. While we are at it,
  2414. // check C99 6.10.3.2p1: ensure that # operators are followed by macro
  2415. // parameters in function-like macro expansions.
  2416. VAOptDefinitionContext VAOCtx(*this);
  2417. while (Tok.isNot(tok::eod)) {
  2418. LastTok = Tok;
  2419. if (!Tok.isOneOf(tok::hash, tok::hashat, tok::hashhash)) {
  2420. MI->AddTokenToBody(Tok);
  2421. if (VAOCtx.isVAOptToken(Tok)) {
  2422. // If we're already within a VAOPT, emit an error.
  2423. if (VAOCtx.isInVAOpt()) {
  2424. Diag(Tok, diag::err_pp_vaopt_nested_use);
  2425. return nullptr;
  2426. }
  2427. // Ensure VAOPT is followed by a '(' .
  2428. LexUnexpandedToken(Tok);
  2429. if (Tok.isNot(tok::l_paren)) {
  2430. Diag(Tok, diag::err_pp_missing_lparen_in_vaopt_use);
  2431. return nullptr;
  2432. }
  2433. MI->AddTokenToBody(Tok);
  2434. VAOCtx.sawVAOptFollowedByOpeningParens(Tok.getLocation());
  2435. LexUnexpandedToken(Tok);
  2436. if (Tok.is(tok::hashhash)) {
  2437. Diag(Tok, diag::err_vaopt_paste_at_start);
  2438. return nullptr;
  2439. }
  2440. continue;
  2441. } else if (VAOCtx.isInVAOpt()) {
  2442. if (Tok.is(tok::r_paren)) {
  2443. if (VAOCtx.sawClosingParen()) {
  2444. const unsigned NumTokens = MI->getNumTokens();
  2445. assert(NumTokens >= 3 && "Must have seen at least __VA_OPT__( "
  2446. "and a subsequent tok::r_paren");
  2447. if (MI->getReplacementToken(NumTokens - 2).is(tok::hashhash)) {
  2448. Diag(Tok, diag::err_vaopt_paste_at_end);
  2449. return nullptr;
  2450. }
  2451. }
  2452. } else if (Tok.is(tok::l_paren)) {
  2453. VAOCtx.sawOpeningParen(Tok.getLocation());
  2454. }
  2455. }
  2456. // Get the next token of the macro.
  2457. LexUnexpandedToken(Tok);
  2458. continue;
  2459. }
  2460. // If we're in -traditional mode, then we should ignore stringification
  2461. // and token pasting. Mark the tokens as unknown so as not to confuse
  2462. // things.
  2463. if (getLangOpts().TraditionalCPP) {
  2464. Tok.setKind(tok::unknown);
  2465. MI->AddTokenToBody(Tok);
  2466. // Get the next token of the macro.
  2467. LexUnexpandedToken(Tok);
  2468. continue;
  2469. }
  2470. if (Tok.is(tok::hashhash)) {
  2471. // If we see token pasting, check if it looks like the gcc comma
  2472. // pasting extension. We'll use this information to suppress
  2473. // diagnostics later on.
  2474. // Get the next token of the macro.
  2475. LexUnexpandedToken(Tok);
  2476. if (Tok.is(tok::eod)) {
  2477. MI->AddTokenToBody(LastTok);
  2478. break;
  2479. }
  2480. unsigned NumTokens = MI->getNumTokens();
  2481. if (NumTokens && Tok.getIdentifierInfo() == Ident__VA_ARGS__ &&
  2482. MI->getReplacementToken(NumTokens-1).is(tok::comma))
  2483. MI->setHasCommaPasting();
  2484. // Things look ok, add the '##' token to the macro.
  2485. MI->AddTokenToBody(LastTok);
  2486. continue;
  2487. }
  2488. // Our Token is a stringization operator.
  2489. // Get the next token of the macro.
  2490. LexUnexpandedToken(Tok);
  2491. // Check for a valid macro arg identifier or __VA_OPT__.
  2492. if (!VAOCtx.isVAOptToken(Tok) &&
  2493. (Tok.getIdentifierInfo() == nullptr ||
  2494. MI->getParameterNum(Tok.getIdentifierInfo()) == -1)) {
  2495. // If this is assembler-with-cpp mode, we accept random gibberish after
  2496. // the '#' because '#' is often a comment character. However, change
  2497. // the kind of the token to tok::unknown so that the preprocessor isn't
  2498. // confused.
  2499. if (getLangOpts().AsmPreprocessor && Tok.isNot(tok::eod)) {
  2500. LastTok.setKind(tok::unknown);
  2501. MI->AddTokenToBody(LastTok);
  2502. continue;
  2503. } else {
  2504. Diag(Tok, diag::err_pp_stringize_not_parameter)
  2505. << LastTok.is(tok::hashat);
  2506. return nullptr;
  2507. }
  2508. }
  2509. // Things look ok, add the '#' and param name tokens to the macro.
  2510. MI->AddTokenToBody(LastTok);
  2511. // If the token following '#' is VAOPT, let the next iteration handle it
  2512. // and check it for correctness, otherwise add the token and prime the
  2513. // loop with the next one.
  2514. if (!VAOCtx.isVAOptToken(Tok)) {
  2515. MI->AddTokenToBody(Tok);
  2516. LastTok = Tok;
  2517. // Get the next token of the macro.
  2518. LexUnexpandedToken(Tok);
  2519. }
  2520. }
  2521. if (VAOCtx.isInVAOpt()) {
  2522. assert(Tok.is(tok::eod) && "Must be at End Of preprocessing Directive");
  2523. Diag(Tok, diag::err_pp_expected_after)
  2524. << LastTok.getKind() << tok::r_paren;
  2525. Diag(VAOCtx.getUnmatchedOpeningParenLoc(), diag::note_matching) << tok::l_paren;
  2526. return nullptr;
  2527. }
  2528. }
  2529. MI->setDefinitionEndLoc(LastTok.getLocation());
  2530. return MI;
  2531. }
  2532. /// HandleDefineDirective - Implements \#define. This consumes the entire macro
  2533. /// line then lets the caller lex the next real token.
  2534. void Preprocessor::HandleDefineDirective(
  2535. Token &DefineTok, const bool ImmediatelyAfterHeaderGuard) {
  2536. ++NumDefined;
  2537. Token MacroNameTok;
  2538. bool MacroShadowsKeyword;
  2539. ReadMacroName(MacroNameTok, MU_Define, &MacroShadowsKeyword);
  2540. // Error reading macro name? If so, diagnostic already issued.
  2541. if (MacroNameTok.is(tok::eod))
  2542. return;
  2543. IdentifierInfo *II = MacroNameTok.getIdentifierInfo();
  2544. // Issue a final pragma warning if we're defining a macro that was has been
  2545. // undefined and is being redefined.
  2546. if (!II->hasMacroDefinition() && II->hadMacroDefinition() && II->isFinal())
  2547. emitFinalMacroWarning(MacroNameTok, /*IsUndef=*/false);
  2548. // If we are supposed to keep comments in #defines, reenable comment saving
  2549. // mode.
  2550. if (CurLexer) CurLexer->SetCommentRetentionState(KeepMacroComments);
  2551. MacroInfo *const MI = ReadOptionalMacroParameterListAndBody(
  2552. MacroNameTok, ImmediatelyAfterHeaderGuard);
  2553. if (!MI) return;
  2554. if (MacroShadowsKeyword &&
  2555. !isConfigurationPattern(MacroNameTok, MI, getLangOpts())) {
  2556. Diag(MacroNameTok, diag::warn_pp_macro_hides_keyword);
  2557. }
  2558. // Check that there is no paste (##) operator at the beginning or end of the
  2559. // replacement list.
  2560. unsigned NumTokens = MI->getNumTokens();
  2561. if (NumTokens != 0) {
  2562. if (MI->getReplacementToken(0).is(tok::hashhash)) {
  2563. Diag(MI->getReplacementToken(0), diag::err_paste_at_start);
  2564. return;
  2565. }
  2566. if (MI->getReplacementToken(NumTokens-1).is(tok::hashhash)) {
  2567. Diag(MI->getReplacementToken(NumTokens-1), diag::err_paste_at_end);
  2568. return;
  2569. }
  2570. }
  2571. // When skipping just warn about macros that do not match.
  2572. if (SkippingUntilPCHThroughHeader) {
  2573. const MacroInfo *OtherMI = getMacroInfo(MacroNameTok.getIdentifierInfo());
  2574. if (!OtherMI || !MI->isIdenticalTo(*OtherMI, *this,
  2575. /*Syntactic=*/LangOpts.MicrosoftExt))
  2576. Diag(MI->getDefinitionLoc(), diag::warn_pp_macro_def_mismatch_with_pch)
  2577. << MacroNameTok.getIdentifierInfo();
  2578. // Issue the diagnostic but allow the change if msvc extensions are enabled
  2579. if (!LangOpts.MicrosoftExt)
  2580. return;
  2581. }
  2582. // Finally, if this identifier already had a macro defined for it, verify that
  2583. // the macro bodies are identical, and issue diagnostics if they are not.
  2584. if (const MacroInfo *OtherMI=getMacroInfo(MacroNameTok.getIdentifierInfo())) {
  2585. // Final macros are hard-mode: they always warn. Even if the bodies are
  2586. // identical. Even if they are in system headers. Even if they are things we
  2587. // would silently allow in the past.
  2588. if (MacroNameTok.getIdentifierInfo()->isFinal())
  2589. emitFinalMacroWarning(MacroNameTok, /*IsUndef=*/false);
  2590. // In Objective-C, ignore attempts to directly redefine the builtin
  2591. // definitions of the ownership qualifiers. It's still possible to
  2592. // #undef them.
  2593. auto isObjCProtectedMacro = [](const IdentifierInfo *II) -> bool {
  2594. return II->isStr("__strong") ||
  2595. II->isStr("__weak") ||
  2596. II->isStr("__unsafe_unretained") ||
  2597. II->isStr("__autoreleasing");
  2598. };
  2599. if (getLangOpts().ObjC &&
  2600. SourceMgr.getFileID(OtherMI->getDefinitionLoc())
  2601. == getPredefinesFileID() &&
  2602. isObjCProtectedMacro(MacroNameTok.getIdentifierInfo())) {
  2603. // Warn if it changes the tokens.
  2604. if ((!getDiagnostics().getSuppressSystemWarnings() ||
  2605. !SourceMgr.isInSystemHeader(DefineTok.getLocation())) &&
  2606. !MI->isIdenticalTo(*OtherMI, *this,
  2607. /*Syntactic=*/LangOpts.MicrosoftExt)) {
  2608. Diag(MI->getDefinitionLoc(), diag::warn_pp_objc_macro_redef_ignored);
  2609. }
  2610. assert(!OtherMI->isWarnIfUnused());
  2611. return;
  2612. }
  2613. // It is very common for system headers to have tons of macro redefinitions
  2614. // and for warnings to be disabled in system headers. If this is the case,
  2615. // then don't bother calling MacroInfo::isIdenticalTo.
  2616. if (!getDiagnostics().getSuppressSystemWarnings() ||
  2617. !SourceMgr.isInSystemHeader(DefineTok.getLocation())) {
  2618. if (!OtherMI->isUsed() && OtherMI->isWarnIfUnused())
  2619. Diag(OtherMI->getDefinitionLoc(), diag::pp_macro_not_used);
  2620. // Warn if defining "__LINE__" and other builtins, per C99 6.10.8/4 and
  2621. // C++ [cpp.predefined]p4, but allow it as an extension.
  2622. if (OtherMI->isBuiltinMacro())
  2623. Diag(MacroNameTok, diag::ext_pp_redef_builtin_macro);
  2624. // Macros must be identical. This means all tokens and whitespace
  2625. // separation must be the same. C99 6.10.3p2.
  2626. else if (!OtherMI->isAllowRedefinitionsWithoutWarning() &&
  2627. !MI->isIdenticalTo(*OtherMI, *this, /*Syntactic=*/LangOpts.MicrosoftExt)) {
  2628. Diag(MI->getDefinitionLoc(), diag::ext_pp_macro_redef)
  2629. << MacroNameTok.getIdentifierInfo();
  2630. Diag(OtherMI->getDefinitionLoc(), diag::note_previous_definition);
  2631. }
  2632. }
  2633. if (OtherMI->isWarnIfUnused())
  2634. WarnUnusedMacroLocs.erase(OtherMI->getDefinitionLoc());
  2635. }
  2636. DefMacroDirective *MD =
  2637. appendDefMacroDirective(MacroNameTok.getIdentifierInfo(), MI);
  2638. assert(!MI->isUsed());
  2639. // If we need warning for not using the macro, add its location in the
  2640. // warn-because-unused-macro set. If it gets used it will be removed from set.
  2641. if (getSourceManager().isInMainFile(MI->getDefinitionLoc()) &&
  2642. !Diags->isIgnored(diag::pp_macro_not_used, MI->getDefinitionLoc()) &&
  2643. !MacroExpansionInDirectivesOverride &&
  2644. getSourceManager().getFileID(MI->getDefinitionLoc()) !=
  2645. getPredefinesFileID()) {
  2646. MI->setIsWarnIfUnused(true);
  2647. WarnUnusedMacroLocs.insert(MI->getDefinitionLoc());
  2648. }
  2649. // If the callbacks want to know, tell them about the macro definition.
  2650. if (Callbacks)
  2651. Callbacks->MacroDefined(MacroNameTok, MD);
  2652. // If we're in MS compatibility mode and the macro being defined is the
  2653. // assert macro, implicitly add a macro definition for static_assert to work
  2654. // around their broken assert.h header file in C. Only do so if there isn't
  2655. // already a static_assert macro defined.
  2656. if (!getLangOpts().CPlusPlus && getLangOpts().MSVCCompat &&
  2657. MacroNameTok.getIdentifierInfo()->isStr("assert") &&
  2658. !isMacroDefined("static_assert")) {
  2659. MacroInfo *MI = AllocateMacroInfo(SourceLocation());
  2660. Token Tok;
  2661. Tok.startToken();
  2662. Tok.setKind(tok::kw__Static_assert);
  2663. Tok.setIdentifierInfo(getIdentifierInfo("_Static_assert"));
  2664. MI->AddTokenToBody(Tok);
  2665. (void)appendDefMacroDirective(getIdentifierInfo("static_assert"), MI);
  2666. }
  2667. }
  2668. /// HandleUndefDirective - Implements \#undef.
  2669. ///
  2670. void Preprocessor::HandleUndefDirective() {
  2671. ++NumUndefined;
  2672. Token MacroNameTok;
  2673. ReadMacroName(MacroNameTok, MU_Undef);
  2674. // Error reading macro name? If so, diagnostic already issued.
  2675. if (MacroNameTok.is(tok::eod))
  2676. return;
  2677. // Check to see if this is the last token on the #undef line.
  2678. CheckEndOfDirective("undef");
  2679. // Okay, we have a valid identifier to undef.
  2680. auto *II = MacroNameTok.getIdentifierInfo();
  2681. auto MD = getMacroDefinition(II);
  2682. UndefMacroDirective *Undef = nullptr;
  2683. if (II->isFinal())
  2684. emitFinalMacroWarning(MacroNameTok, /*IsUndef=*/true);
  2685. // If the macro is not defined, this is a noop undef.
  2686. if (const MacroInfo *MI = MD.getMacroInfo()) {
  2687. if (!MI->isUsed() && MI->isWarnIfUnused())
  2688. Diag(MI->getDefinitionLoc(), diag::pp_macro_not_used);
  2689. if (MI->isWarnIfUnused())
  2690. WarnUnusedMacroLocs.erase(MI->getDefinitionLoc());
  2691. Undef = AllocateUndefMacroDirective(MacroNameTok.getLocation());
  2692. }
  2693. // If the callbacks want to know, tell them about the macro #undef.
  2694. // Note: no matter if the macro was defined or not.
  2695. if (Callbacks)
  2696. Callbacks->MacroUndefined(MacroNameTok, MD, Undef);
  2697. if (Undef)
  2698. appendMacroDirective(II, Undef);
  2699. }
  2700. //===----------------------------------------------------------------------===//
  2701. // Preprocessor Conditional Directive Handling.
  2702. //===----------------------------------------------------------------------===//
  2703. /// HandleIfdefDirective - Implements the \#ifdef/\#ifndef directive. isIfndef
  2704. /// is true when this is a \#ifndef directive. ReadAnyTokensBeforeDirective is
  2705. /// true if any tokens have been returned or pp-directives activated before this
  2706. /// \#ifndef has been lexed.
  2707. ///
  2708. void Preprocessor::HandleIfdefDirective(Token &Result,
  2709. const Token &HashToken,
  2710. bool isIfndef,
  2711. bool ReadAnyTokensBeforeDirective) {
  2712. ++NumIf;
  2713. Token DirectiveTok = Result;
  2714. Token MacroNameTok;
  2715. ReadMacroName(MacroNameTok);
  2716. // Error reading macro name? If so, diagnostic already issued.
  2717. if (MacroNameTok.is(tok::eod)) {
  2718. // Skip code until we get to #endif. This helps with recovery by not
  2719. // emitting an error when the #endif is reached.
  2720. SkipExcludedConditionalBlock(HashToken.getLocation(),
  2721. DirectiveTok.getLocation(),
  2722. /*Foundnonskip*/ false, /*FoundElse*/ false);
  2723. return;
  2724. }
  2725. emitMacroExpansionWarnings(MacroNameTok);
  2726. // Check to see if this is the last token on the #if[n]def line.
  2727. CheckEndOfDirective(isIfndef ? "ifndef" : "ifdef");
  2728. IdentifierInfo *MII = MacroNameTok.getIdentifierInfo();
  2729. auto MD = getMacroDefinition(MII);
  2730. MacroInfo *MI = MD.getMacroInfo();
  2731. if (CurPPLexer->getConditionalStackDepth() == 0) {
  2732. // If the start of a top-level #ifdef and if the macro is not defined,
  2733. // inform MIOpt that this might be the start of a proper include guard.
  2734. // Otherwise it is some other form of unknown conditional which we can't
  2735. // handle.
  2736. if (!ReadAnyTokensBeforeDirective && !MI) {
  2737. assert(isIfndef && "#ifdef shouldn't reach here");
  2738. CurPPLexer->MIOpt.EnterTopLevelIfndef(MII, MacroNameTok.getLocation());
  2739. } else
  2740. CurPPLexer->MIOpt.EnterTopLevelConditional();
  2741. }
  2742. // If there is a macro, process it.
  2743. if (MI) // Mark it used.
  2744. markMacroAsUsed(MI);
  2745. if (Callbacks) {
  2746. if (isIfndef)
  2747. Callbacks->Ifndef(DirectiveTok.getLocation(), MacroNameTok, MD);
  2748. else
  2749. Callbacks->Ifdef(DirectiveTok.getLocation(), MacroNameTok, MD);
  2750. }
  2751. bool RetainExcludedCB = PPOpts->RetainExcludedConditionalBlocks &&
  2752. getSourceManager().isInMainFile(DirectiveTok.getLocation());
  2753. // Should we include the stuff contained by this directive?
  2754. if (PPOpts->SingleFileParseMode && !MI) {
  2755. // In 'single-file-parse mode' undefined identifiers trigger parsing of all
  2756. // the directive blocks.
  2757. CurPPLexer->pushConditionalLevel(DirectiveTok.getLocation(),
  2758. /*wasskip*/false, /*foundnonskip*/false,
  2759. /*foundelse*/false);
  2760. } else if (!MI == isIfndef || RetainExcludedCB) {
  2761. // Yes, remember that we are inside a conditional, then lex the next token.
  2762. CurPPLexer->pushConditionalLevel(DirectiveTok.getLocation(),
  2763. /*wasskip*/false, /*foundnonskip*/true,
  2764. /*foundelse*/false);
  2765. } else {
  2766. // No, skip the contents of this block.
  2767. SkipExcludedConditionalBlock(HashToken.getLocation(),
  2768. DirectiveTok.getLocation(),
  2769. /*Foundnonskip*/ false,
  2770. /*FoundElse*/ false);
  2771. }
  2772. }
  2773. /// HandleIfDirective - Implements the \#if directive.
  2774. ///
  2775. void Preprocessor::HandleIfDirective(Token &IfToken,
  2776. const Token &HashToken,
  2777. bool ReadAnyTokensBeforeDirective) {
  2778. ++NumIf;
  2779. // Parse and evaluate the conditional expression.
  2780. IdentifierInfo *IfNDefMacro = nullptr;
  2781. const DirectiveEvalResult DER = EvaluateDirectiveExpression(IfNDefMacro);
  2782. const bool ConditionalTrue = DER.Conditional;
  2783. // Lexer might become invalid if we hit code completion point while evaluating
  2784. // expression.
  2785. if (!CurPPLexer)
  2786. return;
  2787. // If this condition is equivalent to #ifndef X, and if this is the first
  2788. // directive seen, handle it for the multiple-include optimization.
  2789. if (CurPPLexer->getConditionalStackDepth() == 0) {
  2790. if (!ReadAnyTokensBeforeDirective && IfNDefMacro && ConditionalTrue)
  2791. // FIXME: Pass in the location of the macro name, not the 'if' token.
  2792. CurPPLexer->MIOpt.EnterTopLevelIfndef(IfNDefMacro, IfToken.getLocation());
  2793. else
  2794. CurPPLexer->MIOpt.EnterTopLevelConditional();
  2795. }
  2796. if (Callbacks)
  2797. Callbacks->If(
  2798. IfToken.getLocation(), DER.ExprRange,
  2799. (ConditionalTrue ? PPCallbacks::CVK_True : PPCallbacks::CVK_False));
  2800. bool RetainExcludedCB = PPOpts->RetainExcludedConditionalBlocks &&
  2801. getSourceManager().isInMainFile(IfToken.getLocation());
  2802. // Should we include the stuff contained by this directive?
  2803. if (PPOpts->SingleFileParseMode && DER.IncludedUndefinedIds) {
  2804. // In 'single-file-parse mode' undefined identifiers trigger parsing of all
  2805. // the directive blocks.
  2806. CurPPLexer->pushConditionalLevel(IfToken.getLocation(), /*wasskip*/false,
  2807. /*foundnonskip*/false, /*foundelse*/false);
  2808. } else if (ConditionalTrue || RetainExcludedCB) {
  2809. // Yes, remember that we are inside a conditional, then lex the next token.
  2810. CurPPLexer->pushConditionalLevel(IfToken.getLocation(), /*wasskip*/false,
  2811. /*foundnonskip*/true, /*foundelse*/false);
  2812. } else {
  2813. // No, skip the contents of this block.
  2814. SkipExcludedConditionalBlock(HashToken.getLocation(), IfToken.getLocation(),
  2815. /*Foundnonskip*/ false,
  2816. /*FoundElse*/ false);
  2817. }
  2818. }
  2819. /// HandleEndifDirective - Implements the \#endif directive.
  2820. ///
  2821. void Preprocessor::HandleEndifDirective(Token &EndifToken) {
  2822. ++NumEndif;
  2823. // Check that this is the whole directive.
  2824. CheckEndOfDirective("endif");
  2825. PPConditionalInfo CondInfo;
  2826. if (CurPPLexer->popConditionalLevel(CondInfo)) {
  2827. // No conditionals on the stack: this is an #endif without an #if.
  2828. Diag(EndifToken, diag::err_pp_endif_without_if);
  2829. return;
  2830. }
  2831. // If this the end of a top-level #endif, inform MIOpt.
  2832. if (CurPPLexer->getConditionalStackDepth() == 0)
  2833. CurPPLexer->MIOpt.ExitTopLevelConditional();
  2834. assert(!CondInfo.WasSkipping && !CurPPLexer->LexingRawMode &&
  2835. "This code should only be reachable in the non-skipping case!");
  2836. if (Callbacks)
  2837. Callbacks->Endif(EndifToken.getLocation(), CondInfo.IfLoc);
  2838. }
  2839. /// HandleElseDirective - Implements the \#else directive.
  2840. ///
  2841. void Preprocessor::HandleElseDirective(Token &Result, const Token &HashToken) {
  2842. ++NumElse;
  2843. // #else directive in a non-skipping conditional... start skipping.
  2844. CheckEndOfDirective("else");
  2845. PPConditionalInfo CI;
  2846. if (CurPPLexer->popConditionalLevel(CI)) {
  2847. Diag(Result, diag::pp_err_else_without_if);
  2848. return;
  2849. }
  2850. // If this is a top-level #else, inform the MIOpt.
  2851. if (CurPPLexer->getConditionalStackDepth() == 0)
  2852. CurPPLexer->MIOpt.EnterTopLevelConditional();
  2853. // If this is a #else with a #else before it, report the error.
  2854. if (CI.FoundElse) Diag(Result, diag::pp_err_else_after_else);
  2855. if (Callbacks)
  2856. Callbacks->Else(Result.getLocation(), CI.IfLoc);
  2857. bool RetainExcludedCB = PPOpts->RetainExcludedConditionalBlocks &&
  2858. getSourceManager().isInMainFile(Result.getLocation());
  2859. if ((PPOpts->SingleFileParseMode && !CI.FoundNonSkip) || RetainExcludedCB) {
  2860. // In 'single-file-parse mode' undefined identifiers trigger parsing of all
  2861. // the directive blocks.
  2862. CurPPLexer->pushConditionalLevel(CI.IfLoc, /*wasskip*/false,
  2863. /*foundnonskip*/false, /*foundelse*/true);
  2864. return;
  2865. }
  2866. // Finally, skip the rest of the contents of this block.
  2867. SkipExcludedConditionalBlock(HashToken.getLocation(), CI.IfLoc,
  2868. /*Foundnonskip*/ true,
  2869. /*FoundElse*/ true, Result.getLocation());
  2870. }
  2871. /// Implements the \#elif, \#elifdef, and \#elifndef directives.
  2872. void Preprocessor::HandleElifFamilyDirective(Token &ElifToken,
  2873. const Token &HashToken,
  2874. tok::PPKeywordKind Kind) {
  2875. PPElifDiag DirKind = Kind == tok::pp_elif ? PED_Elif
  2876. : Kind == tok::pp_elifdef ? PED_Elifdef
  2877. : PED_Elifndef;
  2878. ++NumElse;
  2879. // #elif directive in a non-skipping conditional... start skipping.
  2880. // We don't care what the condition is, because we will always skip it (since
  2881. // the block immediately before it was included).
  2882. SourceRange ConditionRange = DiscardUntilEndOfDirective();
  2883. PPConditionalInfo CI;
  2884. if (CurPPLexer->popConditionalLevel(CI)) {
  2885. Diag(ElifToken, diag::pp_err_elif_without_if) << DirKind;
  2886. return;
  2887. }
  2888. // If this is a top-level #elif, inform the MIOpt.
  2889. if (CurPPLexer->getConditionalStackDepth() == 0)
  2890. CurPPLexer->MIOpt.EnterTopLevelConditional();
  2891. // If this is a #elif with a #else before it, report the error.
  2892. if (CI.FoundElse)
  2893. Diag(ElifToken, diag::pp_err_elif_after_else) << DirKind;
  2894. if (Callbacks) {
  2895. switch (Kind) {
  2896. case tok::pp_elif:
  2897. Callbacks->Elif(ElifToken.getLocation(), ConditionRange,
  2898. PPCallbacks::CVK_NotEvaluated, CI.IfLoc);
  2899. break;
  2900. case tok::pp_elifdef:
  2901. Callbacks->Elifdef(ElifToken.getLocation(), ConditionRange, CI.IfLoc);
  2902. break;
  2903. case tok::pp_elifndef:
  2904. Callbacks->Elifndef(ElifToken.getLocation(), ConditionRange, CI.IfLoc);
  2905. break;
  2906. default:
  2907. assert(false && "unexpected directive kind");
  2908. break;
  2909. }
  2910. }
  2911. bool RetainExcludedCB = PPOpts->RetainExcludedConditionalBlocks &&
  2912. getSourceManager().isInMainFile(ElifToken.getLocation());
  2913. if ((PPOpts->SingleFileParseMode && !CI.FoundNonSkip) || RetainExcludedCB) {
  2914. // In 'single-file-parse mode' undefined identifiers trigger parsing of all
  2915. // the directive blocks.
  2916. CurPPLexer->pushConditionalLevel(ElifToken.getLocation(), /*wasskip*/false,
  2917. /*foundnonskip*/false, /*foundelse*/false);
  2918. return;
  2919. }
  2920. // Finally, skip the rest of the contents of this block.
  2921. SkipExcludedConditionalBlock(
  2922. HashToken.getLocation(), CI.IfLoc, /*Foundnonskip*/ true,
  2923. /*FoundElse*/ CI.FoundElse, ElifToken.getLocation());
  2924. }