PPDirectives.cpp 118 KB

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