Lexer.cpp 146 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101
  1. //===- Lexer.cpp - C Language Family Lexer --------------------------------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // This file implements the Lexer and Token interfaces.
  10. //
  11. //===----------------------------------------------------------------------===//
  12. #include "clang/Lex/Lexer.h"
  13. #include "UnicodeCharSets.h"
  14. #include "clang/Basic/CharInfo.h"
  15. #include "clang/Basic/Diagnostic.h"
  16. #include "clang/Basic/IdentifierTable.h"
  17. #include "clang/Basic/LLVM.h"
  18. #include "clang/Basic/LangOptions.h"
  19. #include "clang/Basic/SourceLocation.h"
  20. #include "clang/Basic/SourceManager.h"
  21. #include "clang/Basic/TokenKinds.h"
  22. #include "clang/Lex/LexDiagnostic.h"
  23. #include "clang/Lex/LiteralSupport.h"
  24. #include "clang/Lex/MultipleIncludeOpt.h"
  25. #include "clang/Lex/Preprocessor.h"
  26. #include "clang/Lex/PreprocessorOptions.h"
  27. #include "clang/Lex/Token.h"
  28. #include "llvm/ADT/None.h"
  29. #include "llvm/ADT/Optional.h"
  30. #include "llvm/ADT/STLExtras.h"
  31. #include "llvm/ADT/StringExtras.h"
  32. #include "llvm/ADT/StringRef.h"
  33. #include "llvm/ADT/StringSwitch.h"
  34. #include "llvm/Support/Compiler.h"
  35. #include "llvm/Support/ConvertUTF.h"
  36. #include "llvm/Support/MathExtras.h"
  37. #include "llvm/Support/MemoryBufferRef.h"
  38. #include "llvm/Support/NativeFormatting.h"
  39. #include "llvm/Support/UnicodeCharRanges.h"
  40. #include <algorithm>
  41. #include <cassert>
  42. #include <cstddef>
  43. #include <cstdint>
  44. #include <cstring>
  45. #include <string>
  46. #include <tuple>
  47. #include <utility>
  48. using namespace clang;
  49. //===----------------------------------------------------------------------===//
  50. // Token Class Implementation
  51. //===----------------------------------------------------------------------===//
  52. /// isObjCAtKeyword - Return true if we have an ObjC keyword identifier.
  53. bool Token::isObjCAtKeyword(tok::ObjCKeywordKind objcKey) const {
  54. if (isAnnotation())
  55. return false;
  56. if (IdentifierInfo *II = getIdentifierInfo())
  57. return II->getObjCKeywordID() == objcKey;
  58. return false;
  59. }
  60. /// getObjCKeywordID - Return the ObjC keyword kind.
  61. tok::ObjCKeywordKind Token::getObjCKeywordID() const {
  62. if (isAnnotation())
  63. return tok::objc_not_keyword;
  64. IdentifierInfo *specId = getIdentifierInfo();
  65. return specId ? specId->getObjCKeywordID() : tok::objc_not_keyword;
  66. }
  67. //===----------------------------------------------------------------------===//
  68. // Lexer Class Implementation
  69. //===----------------------------------------------------------------------===//
  70. void Lexer::anchor() {}
  71. void Lexer::InitLexer(const char *BufStart, const char *BufPtr,
  72. const char *BufEnd) {
  73. BufferStart = BufStart;
  74. BufferPtr = BufPtr;
  75. BufferEnd = BufEnd;
  76. assert(BufEnd[0] == 0 &&
  77. "We assume that the input buffer has a null character at the end"
  78. " to simplify lexing!");
  79. // Check whether we have a BOM in the beginning of the buffer. If yes - act
  80. // accordingly. Right now we support only UTF-8 with and without BOM, so, just
  81. // skip the UTF-8 BOM if it's present.
  82. if (BufferStart == BufferPtr) {
  83. // Determine the size of the BOM.
  84. StringRef Buf(BufferStart, BufferEnd - BufferStart);
  85. size_t BOMLength = llvm::StringSwitch<size_t>(Buf)
  86. .StartsWith("\xEF\xBB\xBF", 3) // UTF-8 BOM
  87. .Default(0);
  88. // Skip the BOM.
  89. BufferPtr += BOMLength;
  90. }
  91. Is_PragmaLexer = false;
  92. CurrentConflictMarkerState = CMK_None;
  93. // Start of the file is a start of line.
  94. IsAtStartOfLine = true;
  95. IsAtPhysicalStartOfLine = true;
  96. HasLeadingSpace = false;
  97. HasLeadingEmptyMacro = false;
  98. // We are not after parsing a #.
  99. ParsingPreprocessorDirective = false;
  100. // We are not after parsing #include.
  101. ParsingFilename = false;
  102. // We are not in raw mode. Raw mode disables diagnostics and interpretation
  103. // of tokens (e.g. identifiers, thus disabling macro expansion). It is used
  104. // to quickly lex the tokens of the buffer, e.g. when handling a "#if 0" block
  105. // or otherwise skipping over tokens.
  106. LexingRawMode = false;
  107. // Default to not keeping comments.
  108. ExtendedTokenMode = 0;
  109. NewLinePtr = nullptr;
  110. }
  111. /// Lexer constructor - Create a new lexer object for the specified buffer
  112. /// with the specified preprocessor managing the lexing process. This lexer
  113. /// assumes that the associated file buffer and Preprocessor objects will
  114. /// outlive it, so it doesn't take ownership of either of them.
  115. Lexer::Lexer(FileID FID, const llvm::MemoryBufferRef &InputFile,
  116. Preprocessor &PP, bool IsFirstIncludeOfFile)
  117. : PreprocessorLexer(&PP, FID),
  118. FileLoc(PP.getSourceManager().getLocForStartOfFile(FID)),
  119. LangOpts(PP.getLangOpts()), IsFirstTimeLexingFile(IsFirstIncludeOfFile) {
  120. InitLexer(InputFile.getBufferStart(), InputFile.getBufferStart(),
  121. InputFile.getBufferEnd());
  122. resetExtendedTokenMode();
  123. }
  124. /// Lexer constructor - Create a new raw lexer object. This object is only
  125. /// suitable for calls to 'LexFromRawLexer'. This lexer assumes that the text
  126. /// range will outlive it, so it doesn't take ownership of it.
  127. Lexer::Lexer(SourceLocation fileloc, const LangOptions &langOpts,
  128. const char *BufStart, const char *BufPtr, const char *BufEnd,
  129. bool IsFirstIncludeOfFile)
  130. : FileLoc(fileloc), LangOpts(langOpts),
  131. IsFirstTimeLexingFile(IsFirstIncludeOfFile) {
  132. InitLexer(BufStart, BufPtr, BufEnd);
  133. // We *are* in raw mode.
  134. LexingRawMode = true;
  135. }
  136. /// Lexer constructor - Create a new raw lexer object. This object is only
  137. /// suitable for calls to 'LexFromRawLexer'. This lexer assumes that the text
  138. /// range will outlive it, so it doesn't take ownership of it.
  139. Lexer::Lexer(FileID FID, const llvm::MemoryBufferRef &FromFile,
  140. const SourceManager &SM, const LangOptions &langOpts,
  141. bool IsFirstIncludeOfFile)
  142. : Lexer(SM.getLocForStartOfFile(FID), langOpts, FromFile.getBufferStart(),
  143. FromFile.getBufferStart(), FromFile.getBufferEnd(),
  144. IsFirstIncludeOfFile) {}
  145. void Lexer::resetExtendedTokenMode() {
  146. assert(PP && "Cannot reset token mode without a preprocessor");
  147. if (LangOpts.TraditionalCPP)
  148. SetKeepWhitespaceMode(true);
  149. else
  150. SetCommentRetentionState(PP->getCommentRetentionState());
  151. }
  152. /// Create_PragmaLexer: Lexer constructor - Create a new lexer object for
  153. /// _Pragma expansion. This has a variety of magic semantics that this method
  154. /// sets up. It returns a new'd Lexer that must be delete'd when done.
  155. ///
  156. /// On entrance to this routine, TokStartLoc is a macro location which has a
  157. /// spelling loc that indicates the bytes to be lexed for the token and an
  158. /// expansion location that indicates where all lexed tokens should be
  159. /// "expanded from".
  160. ///
  161. /// TODO: It would really be nice to make _Pragma just be a wrapper around a
  162. /// normal lexer that remaps tokens as they fly by. This would require making
  163. /// Preprocessor::Lex virtual. Given that, we could just dump in a magic lexer
  164. /// interface that could handle this stuff. This would pull GetMappedTokenLoc
  165. /// out of the critical path of the lexer!
  166. ///
  167. Lexer *Lexer::Create_PragmaLexer(SourceLocation SpellingLoc,
  168. SourceLocation ExpansionLocStart,
  169. SourceLocation ExpansionLocEnd,
  170. unsigned TokLen, Preprocessor &PP) {
  171. SourceManager &SM = PP.getSourceManager();
  172. // Create the lexer as if we were going to lex the file normally.
  173. FileID SpellingFID = SM.getFileID(SpellingLoc);
  174. llvm::MemoryBufferRef InputFile = SM.getBufferOrFake(SpellingFID);
  175. Lexer *L = new Lexer(SpellingFID, InputFile, PP);
  176. // Now that the lexer is created, change the start/end locations so that we
  177. // just lex the subsection of the file that we want. This is lexing from a
  178. // scratch buffer.
  179. const char *StrData = SM.getCharacterData(SpellingLoc);
  180. L->BufferPtr = StrData;
  181. L->BufferEnd = StrData+TokLen;
  182. assert(L->BufferEnd[0] == 0 && "Buffer is not nul terminated!");
  183. // Set the SourceLocation with the remapping information. This ensures that
  184. // GetMappedTokenLoc will remap the tokens as they are lexed.
  185. L->FileLoc = SM.createExpansionLoc(SM.getLocForStartOfFile(SpellingFID),
  186. ExpansionLocStart,
  187. ExpansionLocEnd, TokLen);
  188. // Ensure that the lexer thinks it is inside a directive, so that end \n will
  189. // return an EOD token.
  190. L->ParsingPreprocessorDirective = true;
  191. // This lexer really is for _Pragma.
  192. L->Is_PragmaLexer = true;
  193. return L;
  194. }
  195. bool Lexer::skipOver(unsigned NumBytes) {
  196. IsAtPhysicalStartOfLine = true;
  197. IsAtStartOfLine = true;
  198. if ((BufferPtr + NumBytes) > BufferEnd)
  199. return true;
  200. BufferPtr += NumBytes;
  201. return false;
  202. }
  203. template <typename T> static void StringifyImpl(T &Str, char Quote) {
  204. typename T::size_type i = 0, e = Str.size();
  205. while (i < e) {
  206. if (Str[i] == '\\' || Str[i] == Quote) {
  207. Str.insert(Str.begin() + i, '\\');
  208. i += 2;
  209. ++e;
  210. } else if (Str[i] == '\n' || Str[i] == '\r') {
  211. // Replace '\r\n' and '\n\r' to '\\' followed by 'n'.
  212. if ((i < e - 1) && (Str[i + 1] == '\n' || Str[i + 1] == '\r') &&
  213. Str[i] != Str[i + 1]) {
  214. Str[i] = '\\';
  215. Str[i + 1] = 'n';
  216. } else {
  217. // Replace '\n' and '\r' to '\\' followed by 'n'.
  218. Str[i] = '\\';
  219. Str.insert(Str.begin() + i + 1, 'n');
  220. ++e;
  221. }
  222. i += 2;
  223. } else
  224. ++i;
  225. }
  226. }
  227. std::string Lexer::Stringify(StringRef Str, bool Charify) {
  228. std::string Result = std::string(Str);
  229. char Quote = Charify ? '\'' : '"';
  230. StringifyImpl(Result, Quote);
  231. return Result;
  232. }
  233. void Lexer::Stringify(SmallVectorImpl<char> &Str) { StringifyImpl(Str, '"'); }
  234. //===----------------------------------------------------------------------===//
  235. // Token Spelling
  236. //===----------------------------------------------------------------------===//
  237. /// Slow case of getSpelling. Extract the characters comprising the
  238. /// spelling of this token from the provided input buffer.
  239. static size_t getSpellingSlow(const Token &Tok, const char *BufPtr,
  240. const LangOptions &LangOpts, char *Spelling) {
  241. assert(Tok.needsCleaning() && "getSpellingSlow called on simple token");
  242. size_t Length = 0;
  243. const char *BufEnd = BufPtr + Tok.getLength();
  244. if (tok::isStringLiteral(Tok.getKind())) {
  245. // Munch the encoding-prefix and opening double-quote.
  246. while (BufPtr < BufEnd) {
  247. unsigned Size;
  248. Spelling[Length++] = Lexer::getCharAndSizeNoWarn(BufPtr, Size, LangOpts);
  249. BufPtr += Size;
  250. if (Spelling[Length - 1] == '"')
  251. break;
  252. }
  253. // Raw string literals need special handling; trigraph expansion and line
  254. // splicing do not occur within their d-char-sequence nor within their
  255. // r-char-sequence.
  256. if (Length >= 2 &&
  257. Spelling[Length - 2] == 'R' && Spelling[Length - 1] == '"') {
  258. // Search backwards from the end of the token to find the matching closing
  259. // quote.
  260. const char *RawEnd = BufEnd;
  261. do --RawEnd; while (*RawEnd != '"');
  262. size_t RawLength = RawEnd - BufPtr + 1;
  263. // Everything between the quotes is included verbatim in the spelling.
  264. memcpy(Spelling + Length, BufPtr, RawLength);
  265. Length += RawLength;
  266. BufPtr += RawLength;
  267. // The rest of the token is lexed normally.
  268. }
  269. }
  270. while (BufPtr < BufEnd) {
  271. unsigned Size;
  272. Spelling[Length++] = Lexer::getCharAndSizeNoWarn(BufPtr, Size, LangOpts);
  273. BufPtr += Size;
  274. }
  275. assert(Length < Tok.getLength() &&
  276. "NeedsCleaning flag set on token that didn't need cleaning!");
  277. return Length;
  278. }
  279. /// getSpelling() - Return the 'spelling' of this token. The spelling of a
  280. /// token are the characters used to represent the token in the source file
  281. /// after trigraph expansion and escaped-newline folding. In particular, this
  282. /// wants to get the true, uncanonicalized, spelling of things like digraphs
  283. /// UCNs, etc.
  284. StringRef Lexer::getSpelling(SourceLocation loc,
  285. SmallVectorImpl<char> &buffer,
  286. const SourceManager &SM,
  287. const LangOptions &options,
  288. bool *invalid) {
  289. // Break down the source location.
  290. std::pair<FileID, unsigned> locInfo = SM.getDecomposedLoc(loc);
  291. // Try to the load the file buffer.
  292. bool invalidTemp = false;
  293. StringRef file = SM.getBufferData(locInfo.first, &invalidTemp);
  294. if (invalidTemp) {
  295. if (invalid) *invalid = true;
  296. return {};
  297. }
  298. const char *tokenBegin = file.data() + locInfo.second;
  299. // Lex from the start of the given location.
  300. Lexer lexer(SM.getLocForStartOfFile(locInfo.first), options,
  301. file.begin(), tokenBegin, file.end());
  302. Token token;
  303. lexer.LexFromRawLexer(token);
  304. unsigned length = token.getLength();
  305. // Common case: no need for cleaning.
  306. if (!token.needsCleaning())
  307. return StringRef(tokenBegin, length);
  308. // Hard case, we need to relex the characters into the string.
  309. buffer.resize(length);
  310. buffer.resize(getSpellingSlow(token, tokenBegin, options, buffer.data()));
  311. return StringRef(buffer.data(), buffer.size());
  312. }
  313. /// getSpelling() - Return the 'spelling' of this token. The spelling of a
  314. /// token are the characters used to represent the token in the source file
  315. /// after trigraph expansion and escaped-newline folding. In particular, this
  316. /// wants to get the true, uncanonicalized, spelling of things like digraphs
  317. /// UCNs, etc.
  318. std::string Lexer::getSpelling(const Token &Tok, const SourceManager &SourceMgr,
  319. const LangOptions &LangOpts, bool *Invalid) {
  320. assert((int)Tok.getLength() >= 0 && "Token character range is bogus!");
  321. bool CharDataInvalid = false;
  322. const char *TokStart = SourceMgr.getCharacterData(Tok.getLocation(),
  323. &CharDataInvalid);
  324. if (Invalid)
  325. *Invalid = CharDataInvalid;
  326. if (CharDataInvalid)
  327. return {};
  328. // If this token contains nothing interesting, return it directly.
  329. if (!Tok.needsCleaning())
  330. return std::string(TokStart, TokStart + Tok.getLength());
  331. std::string Result;
  332. Result.resize(Tok.getLength());
  333. Result.resize(getSpellingSlow(Tok, TokStart, LangOpts, &*Result.begin()));
  334. return Result;
  335. }
  336. /// getSpelling - This method is used to get the spelling of a token into a
  337. /// preallocated buffer, instead of as an std::string. The caller is required
  338. /// to allocate enough space for the token, which is guaranteed to be at least
  339. /// Tok.getLength() bytes long. The actual length of the token is returned.
  340. ///
  341. /// Note that this method may do two possible things: it may either fill in
  342. /// the buffer specified with characters, or it may *change the input pointer*
  343. /// to point to a constant buffer with the data already in it (avoiding a
  344. /// copy). The caller is not allowed to modify the returned buffer pointer
  345. /// if an internal buffer is returned.
  346. unsigned Lexer::getSpelling(const Token &Tok, const char *&Buffer,
  347. const SourceManager &SourceMgr,
  348. const LangOptions &LangOpts, bool *Invalid) {
  349. assert((int)Tok.getLength() >= 0 && "Token character range is bogus!");
  350. const char *TokStart = nullptr;
  351. // NOTE: this has to be checked *before* testing for an IdentifierInfo.
  352. if (Tok.is(tok::raw_identifier))
  353. TokStart = Tok.getRawIdentifier().data();
  354. else if (!Tok.hasUCN()) {
  355. if (const IdentifierInfo *II = Tok.getIdentifierInfo()) {
  356. // Just return the string from the identifier table, which is very quick.
  357. Buffer = II->getNameStart();
  358. return II->getLength();
  359. }
  360. }
  361. // NOTE: this can be checked even after testing for an IdentifierInfo.
  362. if (Tok.isLiteral())
  363. TokStart = Tok.getLiteralData();
  364. if (!TokStart) {
  365. // Compute the start of the token in the input lexer buffer.
  366. bool CharDataInvalid = false;
  367. TokStart = SourceMgr.getCharacterData(Tok.getLocation(), &CharDataInvalid);
  368. if (Invalid)
  369. *Invalid = CharDataInvalid;
  370. if (CharDataInvalid) {
  371. Buffer = "";
  372. return 0;
  373. }
  374. }
  375. // If this token contains nothing interesting, return it directly.
  376. if (!Tok.needsCleaning()) {
  377. Buffer = TokStart;
  378. return Tok.getLength();
  379. }
  380. // Otherwise, hard case, relex the characters into the string.
  381. return getSpellingSlow(Tok, TokStart, LangOpts, const_cast<char*>(Buffer));
  382. }
  383. /// MeasureTokenLength - Relex the token at the specified location and return
  384. /// its length in bytes in the input file. If the token needs cleaning (e.g.
  385. /// includes a trigraph or an escaped newline) then this count includes bytes
  386. /// that are part of that.
  387. unsigned Lexer::MeasureTokenLength(SourceLocation Loc,
  388. const SourceManager &SM,
  389. const LangOptions &LangOpts) {
  390. Token TheTok;
  391. if (getRawToken(Loc, TheTok, SM, LangOpts))
  392. return 0;
  393. return TheTok.getLength();
  394. }
  395. /// Relex the token at the specified location.
  396. /// \returns true if there was a failure, false on success.
  397. bool Lexer::getRawToken(SourceLocation Loc, Token &Result,
  398. const SourceManager &SM,
  399. const LangOptions &LangOpts,
  400. bool IgnoreWhiteSpace) {
  401. // TODO: this could be special cased for common tokens like identifiers, ')',
  402. // etc to make this faster, if it mattered. Just look at StrData[0] to handle
  403. // all obviously single-char tokens. This could use
  404. // Lexer::isObviouslySimpleCharacter for example to handle identifiers or
  405. // something.
  406. // If this comes from a macro expansion, we really do want the macro name, not
  407. // the token this macro expanded to.
  408. Loc = SM.getExpansionLoc(Loc);
  409. std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc);
  410. bool Invalid = false;
  411. StringRef Buffer = SM.getBufferData(LocInfo.first, &Invalid);
  412. if (Invalid)
  413. return true;
  414. const char *StrData = Buffer.data()+LocInfo.second;
  415. if (!IgnoreWhiteSpace && isWhitespace(StrData[0]))
  416. return true;
  417. // Create a lexer starting at the beginning of this token.
  418. Lexer TheLexer(SM.getLocForStartOfFile(LocInfo.first), LangOpts,
  419. Buffer.begin(), StrData, Buffer.end());
  420. TheLexer.SetCommentRetentionState(true);
  421. TheLexer.LexFromRawLexer(Result);
  422. return false;
  423. }
  424. /// Returns the pointer that points to the beginning of line that contains
  425. /// the given offset, or null if the offset if invalid.
  426. static const char *findBeginningOfLine(StringRef Buffer, unsigned Offset) {
  427. const char *BufStart = Buffer.data();
  428. if (Offset >= Buffer.size())
  429. return nullptr;
  430. const char *LexStart = BufStart + Offset;
  431. for (; LexStart != BufStart; --LexStart) {
  432. if (isVerticalWhitespace(LexStart[0]) &&
  433. !Lexer::isNewLineEscaped(BufStart, LexStart)) {
  434. // LexStart should point at first character of logical line.
  435. ++LexStart;
  436. break;
  437. }
  438. }
  439. return LexStart;
  440. }
  441. static SourceLocation getBeginningOfFileToken(SourceLocation Loc,
  442. const SourceManager &SM,
  443. const LangOptions &LangOpts) {
  444. assert(Loc.isFileID());
  445. std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc);
  446. if (LocInfo.first.isInvalid())
  447. return Loc;
  448. bool Invalid = false;
  449. StringRef Buffer = SM.getBufferData(LocInfo.first, &Invalid);
  450. if (Invalid)
  451. return Loc;
  452. // Back up from the current location until we hit the beginning of a line
  453. // (or the buffer). We'll relex from that point.
  454. const char *StrData = Buffer.data() + LocInfo.second;
  455. const char *LexStart = findBeginningOfLine(Buffer, LocInfo.second);
  456. if (!LexStart || LexStart == StrData)
  457. return Loc;
  458. // Create a lexer starting at the beginning of this token.
  459. SourceLocation LexerStartLoc = Loc.getLocWithOffset(-LocInfo.second);
  460. Lexer TheLexer(LexerStartLoc, LangOpts, Buffer.data(), LexStart,
  461. Buffer.end());
  462. TheLexer.SetCommentRetentionState(true);
  463. // Lex tokens until we find the token that contains the source location.
  464. Token TheTok;
  465. do {
  466. TheLexer.LexFromRawLexer(TheTok);
  467. if (TheLexer.getBufferLocation() > StrData) {
  468. // Lexing this token has taken the lexer past the source location we're
  469. // looking for. If the current token encompasses our source location,
  470. // return the beginning of that token.
  471. if (TheLexer.getBufferLocation() - TheTok.getLength() <= StrData)
  472. return TheTok.getLocation();
  473. // We ended up skipping over the source location entirely, which means
  474. // that it points into whitespace. We're done here.
  475. break;
  476. }
  477. } while (TheTok.getKind() != tok::eof);
  478. // We've passed our source location; just return the original source location.
  479. return Loc;
  480. }
  481. SourceLocation Lexer::GetBeginningOfToken(SourceLocation Loc,
  482. const SourceManager &SM,
  483. const LangOptions &LangOpts) {
  484. if (Loc.isFileID())
  485. return getBeginningOfFileToken(Loc, SM, LangOpts);
  486. if (!SM.isMacroArgExpansion(Loc))
  487. return Loc;
  488. SourceLocation FileLoc = SM.getSpellingLoc(Loc);
  489. SourceLocation BeginFileLoc = getBeginningOfFileToken(FileLoc, SM, LangOpts);
  490. std::pair<FileID, unsigned> FileLocInfo = SM.getDecomposedLoc(FileLoc);
  491. std::pair<FileID, unsigned> BeginFileLocInfo =
  492. SM.getDecomposedLoc(BeginFileLoc);
  493. assert(FileLocInfo.first == BeginFileLocInfo.first &&
  494. FileLocInfo.second >= BeginFileLocInfo.second);
  495. return Loc.getLocWithOffset(BeginFileLocInfo.second - FileLocInfo.second);
  496. }
  497. namespace {
  498. enum PreambleDirectiveKind {
  499. PDK_Skipped,
  500. PDK_Unknown
  501. };
  502. } // namespace
  503. PreambleBounds Lexer::ComputePreamble(StringRef Buffer,
  504. const LangOptions &LangOpts,
  505. unsigned MaxLines) {
  506. // Create a lexer starting at the beginning of the file. Note that we use a
  507. // "fake" file source location at offset 1 so that the lexer will track our
  508. // position within the file.
  509. const SourceLocation::UIntTy StartOffset = 1;
  510. SourceLocation FileLoc = SourceLocation::getFromRawEncoding(StartOffset);
  511. Lexer TheLexer(FileLoc, LangOpts, Buffer.begin(), Buffer.begin(),
  512. Buffer.end());
  513. TheLexer.SetCommentRetentionState(true);
  514. bool InPreprocessorDirective = false;
  515. Token TheTok;
  516. SourceLocation ActiveCommentLoc;
  517. unsigned MaxLineOffset = 0;
  518. if (MaxLines) {
  519. const char *CurPtr = Buffer.begin();
  520. unsigned CurLine = 0;
  521. while (CurPtr != Buffer.end()) {
  522. char ch = *CurPtr++;
  523. if (ch == '\n') {
  524. ++CurLine;
  525. if (CurLine == MaxLines)
  526. break;
  527. }
  528. }
  529. if (CurPtr != Buffer.end())
  530. MaxLineOffset = CurPtr - Buffer.begin();
  531. }
  532. do {
  533. TheLexer.LexFromRawLexer(TheTok);
  534. if (InPreprocessorDirective) {
  535. // If we've hit the end of the file, we're done.
  536. if (TheTok.getKind() == tok::eof) {
  537. break;
  538. }
  539. // If we haven't hit the end of the preprocessor directive, skip this
  540. // token.
  541. if (!TheTok.isAtStartOfLine())
  542. continue;
  543. // We've passed the end of the preprocessor directive, and will look
  544. // at this token again below.
  545. InPreprocessorDirective = false;
  546. }
  547. // Keep track of the # of lines in the preamble.
  548. if (TheTok.isAtStartOfLine()) {
  549. unsigned TokOffset = TheTok.getLocation().getRawEncoding() - StartOffset;
  550. // If we were asked to limit the number of lines in the preamble,
  551. // and we're about to exceed that limit, we're done.
  552. if (MaxLineOffset && TokOffset >= MaxLineOffset)
  553. break;
  554. }
  555. // Comments are okay; skip over them.
  556. if (TheTok.getKind() == tok::comment) {
  557. if (ActiveCommentLoc.isInvalid())
  558. ActiveCommentLoc = TheTok.getLocation();
  559. continue;
  560. }
  561. if (TheTok.isAtStartOfLine() && TheTok.getKind() == tok::hash) {
  562. // This is the start of a preprocessor directive.
  563. Token HashTok = TheTok;
  564. InPreprocessorDirective = true;
  565. ActiveCommentLoc = SourceLocation();
  566. // Figure out which directive this is. Since we're lexing raw tokens,
  567. // we don't have an identifier table available. Instead, just look at
  568. // the raw identifier to recognize and categorize preprocessor directives.
  569. TheLexer.LexFromRawLexer(TheTok);
  570. if (TheTok.getKind() == tok::raw_identifier && !TheTok.needsCleaning()) {
  571. StringRef Keyword = TheTok.getRawIdentifier();
  572. PreambleDirectiveKind PDK
  573. = llvm::StringSwitch<PreambleDirectiveKind>(Keyword)
  574. .Case("include", PDK_Skipped)
  575. .Case("__include_macros", PDK_Skipped)
  576. .Case("define", PDK_Skipped)
  577. .Case("undef", PDK_Skipped)
  578. .Case("line", PDK_Skipped)
  579. .Case("error", PDK_Skipped)
  580. .Case("pragma", PDK_Skipped)
  581. .Case("import", PDK_Skipped)
  582. .Case("include_next", PDK_Skipped)
  583. .Case("warning", PDK_Skipped)
  584. .Case("ident", PDK_Skipped)
  585. .Case("sccs", PDK_Skipped)
  586. .Case("assert", PDK_Skipped)
  587. .Case("unassert", PDK_Skipped)
  588. .Case("if", PDK_Skipped)
  589. .Case("ifdef", PDK_Skipped)
  590. .Case("ifndef", PDK_Skipped)
  591. .Case("elif", PDK_Skipped)
  592. .Case("elifdef", PDK_Skipped)
  593. .Case("elifndef", PDK_Skipped)
  594. .Case("else", PDK_Skipped)
  595. .Case("endif", PDK_Skipped)
  596. .Default(PDK_Unknown);
  597. switch (PDK) {
  598. case PDK_Skipped:
  599. continue;
  600. case PDK_Unknown:
  601. // We don't know what this directive is; stop at the '#'.
  602. break;
  603. }
  604. }
  605. // We only end up here if we didn't recognize the preprocessor
  606. // directive or it was one that can't occur in the preamble at this
  607. // point. Roll back the current token to the location of the '#'.
  608. TheTok = HashTok;
  609. }
  610. // We hit a token that we don't recognize as being in the
  611. // "preprocessing only" part of the file, so we're no longer in
  612. // the preamble.
  613. break;
  614. } while (true);
  615. SourceLocation End;
  616. if (ActiveCommentLoc.isValid())
  617. End = ActiveCommentLoc; // don't truncate a decl comment.
  618. else
  619. End = TheTok.getLocation();
  620. return PreambleBounds(End.getRawEncoding() - FileLoc.getRawEncoding(),
  621. TheTok.isAtStartOfLine());
  622. }
  623. unsigned Lexer::getTokenPrefixLength(SourceLocation TokStart, unsigned CharNo,
  624. const SourceManager &SM,
  625. const LangOptions &LangOpts) {
  626. // Figure out how many physical characters away the specified expansion
  627. // character is. This needs to take into consideration newlines and
  628. // trigraphs.
  629. bool Invalid = false;
  630. const char *TokPtr = SM.getCharacterData(TokStart, &Invalid);
  631. // If they request the first char of the token, we're trivially done.
  632. if (Invalid || (CharNo == 0 && Lexer::isObviouslySimpleCharacter(*TokPtr)))
  633. return 0;
  634. unsigned PhysOffset = 0;
  635. // The usual case is that tokens don't contain anything interesting. Skip
  636. // over the uninteresting characters. If a token only consists of simple
  637. // chars, this method is extremely fast.
  638. while (Lexer::isObviouslySimpleCharacter(*TokPtr)) {
  639. if (CharNo == 0)
  640. return PhysOffset;
  641. ++TokPtr;
  642. --CharNo;
  643. ++PhysOffset;
  644. }
  645. // If we have a character that may be a trigraph or escaped newline, use a
  646. // lexer to parse it correctly.
  647. for (; CharNo; --CharNo) {
  648. unsigned Size;
  649. Lexer::getCharAndSizeNoWarn(TokPtr, Size, LangOpts);
  650. TokPtr += Size;
  651. PhysOffset += Size;
  652. }
  653. // Final detail: if we end up on an escaped newline, we want to return the
  654. // location of the actual byte of the token. For example foo\<newline>bar
  655. // advanced by 3 should return the location of b, not of \\. One compounding
  656. // detail of this is that the escape may be made by a trigraph.
  657. if (!Lexer::isObviouslySimpleCharacter(*TokPtr))
  658. PhysOffset += Lexer::SkipEscapedNewLines(TokPtr)-TokPtr;
  659. return PhysOffset;
  660. }
  661. /// Computes the source location just past the end of the
  662. /// token at this source location.
  663. ///
  664. /// This routine can be used to produce a source location that
  665. /// points just past the end of the token referenced by \p Loc, and
  666. /// is generally used when a diagnostic needs to point just after a
  667. /// token where it expected something different that it received. If
  668. /// the returned source location would not be meaningful (e.g., if
  669. /// it points into a macro), this routine returns an invalid
  670. /// source location.
  671. ///
  672. /// \param Offset an offset from the end of the token, where the source
  673. /// location should refer to. The default offset (0) produces a source
  674. /// location pointing just past the end of the token; an offset of 1 produces
  675. /// a source location pointing to the last character in the token, etc.
  676. SourceLocation Lexer::getLocForEndOfToken(SourceLocation Loc, unsigned Offset,
  677. const SourceManager &SM,
  678. const LangOptions &LangOpts) {
  679. if (Loc.isInvalid())
  680. return {};
  681. if (Loc.isMacroID()) {
  682. if (Offset > 0 || !isAtEndOfMacroExpansion(Loc, SM, LangOpts, &Loc))
  683. return {}; // Points inside the macro expansion.
  684. }
  685. unsigned Len = Lexer::MeasureTokenLength(Loc, SM, LangOpts);
  686. if (Len > Offset)
  687. Len = Len - Offset;
  688. else
  689. return Loc;
  690. return Loc.getLocWithOffset(Len);
  691. }
  692. /// Returns true if the given MacroID location points at the first
  693. /// token of the macro expansion.
  694. bool Lexer::isAtStartOfMacroExpansion(SourceLocation loc,
  695. const SourceManager &SM,
  696. const LangOptions &LangOpts,
  697. SourceLocation *MacroBegin) {
  698. assert(loc.isValid() && loc.isMacroID() && "Expected a valid macro loc");
  699. SourceLocation expansionLoc;
  700. if (!SM.isAtStartOfImmediateMacroExpansion(loc, &expansionLoc))
  701. return false;
  702. if (expansionLoc.isFileID()) {
  703. // No other macro expansions, this is the first.
  704. if (MacroBegin)
  705. *MacroBegin = expansionLoc;
  706. return true;
  707. }
  708. return isAtStartOfMacroExpansion(expansionLoc, SM, LangOpts, MacroBegin);
  709. }
  710. /// Returns true if the given MacroID location points at the last
  711. /// token of the macro expansion.
  712. bool Lexer::isAtEndOfMacroExpansion(SourceLocation loc,
  713. const SourceManager &SM,
  714. const LangOptions &LangOpts,
  715. SourceLocation *MacroEnd) {
  716. assert(loc.isValid() && loc.isMacroID() && "Expected a valid macro loc");
  717. SourceLocation spellLoc = SM.getSpellingLoc(loc);
  718. unsigned tokLen = MeasureTokenLength(spellLoc, SM, LangOpts);
  719. if (tokLen == 0)
  720. return false;
  721. SourceLocation afterLoc = loc.getLocWithOffset(tokLen);
  722. SourceLocation expansionLoc;
  723. if (!SM.isAtEndOfImmediateMacroExpansion(afterLoc, &expansionLoc))
  724. return false;
  725. if (expansionLoc.isFileID()) {
  726. // No other macro expansions.
  727. if (MacroEnd)
  728. *MacroEnd = expansionLoc;
  729. return true;
  730. }
  731. return isAtEndOfMacroExpansion(expansionLoc, SM, LangOpts, MacroEnd);
  732. }
  733. static CharSourceRange makeRangeFromFileLocs(CharSourceRange Range,
  734. const SourceManager &SM,
  735. const LangOptions &LangOpts) {
  736. SourceLocation Begin = Range.getBegin();
  737. SourceLocation End = Range.getEnd();
  738. assert(Begin.isFileID() && End.isFileID());
  739. if (Range.isTokenRange()) {
  740. End = Lexer::getLocForEndOfToken(End, 0, SM,LangOpts);
  741. if (End.isInvalid())
  742. return {};
  743. }
  744. // Break down the source locations.
  745. FileID FID;
  746. unsigned BeginOffs;
  747. std::tie(FID, BeginOffs) = SM.getDecomposedLoc(Begin);
  748. if (FID.isInvalid())
  749. return {};
  750. unsigned EndOffs;
  751. if (!SM.isInFileID(End, FID, &EndOffs) ||
  752. BeginOffs > EndOffs)
  753. return {};
  754. return CharSourceRange::getCharRange(Begin, End);
  755. }
  756. // Assumes that `Loc` is in an expansion.
  757. static bool isInExpansionTokenRange(const SourceLocation Loc,
  758. const SourceManager &SM) {
  759. return SM.getSLocEntry(SM.getFileID(Loc))
  760. .getExpansion()
  761. .isExpansionTokenRange();
  762. }
  763. CharSourceRange Lexer::makeFileCharRange(CharSourceRange Range,
  764. const SourceManager &SM,
  765. const LangOptions &LangOpts) {
  766. SourceLocation Begin = Range.getBegin();
  767. SourceLocation End = Range.getEnd();
  768. if (Begin.isInvalid() || End.isInvalid())
  769. return {};
  770. if (Begin.isFileID() && End.isFileID())
  771. return makeRangeFromFileLocs(Range, SM, LangOpts);
  772. if (Begin.isMacroID() && End.isFileID()) {
  773. if (!isAtStartOfMacroExpansion(Begin, SM, LangOpts, &Begin))
  774. return {};
  775. Range.setBegin(Begin);
  776. return makeRangeFromFileLocs(Range, SM, LangOpts);
  777. }
  778. if (Begin.isFileID() && End.isMacroID()) {
  779. if (Range.isTokenRange()) {
  780. if (!isAtEndOfMacroExpansion(End, SM, LangOpts, &End))
  781. return {};
  782. // Use the *original* end, not the expanded one in `End`.
  783. Range.setTokenRange(isInExpansionTokenRange(Range.getEnd(), SM));
  784. } else if (!isAtStartOfMacroExpansion(End, SM, LangOpts, &End))
  785. return {};
  786. Range.setEnd(End);
  787. return makeRangeFromFileLocs(Range, SM, LangOpts);
  788. }
  789. assert(Begin.isMacroID() && End.isMacroID());
  790. SourceLocation MacroBegin, MacroEnd;
  791. if (isAtStartOfMacroExpansion(Begin, SM, LangOpts, &MacroBegin) &&
  792. ((Range.isTokenRange() && isAtEndOfMacroExpansion(End, SM, LangOpts,
  793. &MacroEnd)) ||
  794. (Range.isCharRange() && isAtStartOfMacroExpansion(End, SM, LangOpts,
  795. &MacroEnd)))) {
  796. Range.setBegin(MacroBegin);
  797. Range.setEnd(MacroEnd);
  798. // Use the *original* `End`, not the expanded one in `MacroEnd`.
  799. if (Range.isTokenRange())
  800. Range.setTokenRange(isInExpansionTokenRange(End, SM));
  801. return makeRangeFromFileLocs(Range, SM, LangOpts);
  802. }
  803. bool Invalid = false;
  804. const SrcMgr::SLocEntry &BeginEntry = SM.getSLocEntry(SM.getFileID(Begin),
  805. &Invalid);
  806. if (Invalid)
  807. return {};
  808. if (BeginEntry.getExpansion().isMacroArgExpansion()) {
  809. const SrcMgr::SLocEntry &EndEntry = SM.getSLocEntry(SM.getFileID(End),
  810. &Invalid);
  811. if (Invalid)
  812. return {};
  813. if (EndEntry.getExpansion().isMacroArgExpansion() &&
  814. BeginEntry.getExpansion().getExpansionLocStart() ==
  815. EndEntry.getExpansion().getExpansionLocStart()) {
  816. Range.setBegin(SM.getImmediateSpellingLoc(Begin));
  817. Range.setEnd(SM.getImmediateSpellingLoc(End));
  818. return makeFileCharRange(Range, SM, LangOpts);
  819. }
  820. }
  821. return {};
  822. }
  823. StringRef Lexer::getSourceText(CharSourceRange Range,
  824. const SourceManager &SM,
  825. const LangOptions &LangOpts,
  826. bool *Invalid) {
  827. Range = makeFileCharRange(Range, SM, LangOpts);
  828. if (Range.isInvalid()) {
  829. if (Invalid) *Invalid = true;
  830. return {};
  831. }
  832. // Break down the source location.
  833. std::pair<FileID, unsigned> beginInfo = SM.getDecomposedLoc(Range.getBegin());
  834. if (beginInfo.first.isInvalid()) {
  835. if (Invalid) *Invalid = true;
  836. return {};
  837. }
  838. unsigned EndOffs;
  839. if (!SM.isInFileID(Range.getEnd(), beginInfo.first, &EndOffs) ||
  840. beginInfo.second > EndOffs) {
  841. if (Invalid) *Invalid = true;
  842. return {};
  843. }
  844. // Try to the load the file buffer.
  845. bool invalidTemp = false;
  846. StringRef file = SM.getBufferData(beginInfo.first, &invalidTemp);
  847. if (invalidTemp) {
  848. if (Invalid) *Invalid = true;
  849. return {};
  850. }
  851. if (Invalid) *Invalid = false;
  852. return file.substr(beginInfo.second, EndOffs - beginInfo.second);
  853. }
  854. StringRef Lexer::getImmediateMacroName(SourceLocation Loc,
  855. const SourceManager &SM,
  856. const LangOptions &LangOpts) {
  857. assert(Loc.isMacroID() && "Only reasonable to call this on macros");
  858. // Find the location of the immediate macro expansion.
  859. while (true) {
  860. FileID FID = SM.getFileID(Loc);
  861. const SrcMgr::SLocEntry *E = &SM.getSLocEntry(FID);
  862. const SrcMgr::ExpansionInfo &Expansion = E->getExpansion();
  863. Loc = Expansion.getExpansionLocStart();
  864. if (!Expansion.isMacroArgExpansion())
  865. break;
  866. // For macro arguments we need to check that the argument did not come
  867. // from an inner macro, e.g: "MAC1( MAC2(foo) )"
  868. // Loc points to the argument id of the macro definition, move to the
  869. // macro expansion.
  870. Loc = SM.getImmediateExpansionRange(Loc).getBegin();
  871. SourceLocation SpellLoc = Expansion.getSpellingLoc();
  872. if (SpellLoc.isFileID())
  873. break; // No inner macro.
  874. // If spelling location resides in the same FileID as macro expansion
  875. // location, it means there is no inner macro.
  876. FileID MacroFID = SM.getFileID(Loc);
  877. if (SM.isInFileID(SpellLoc, MacroFID))
  878. break;
  879. // Argument came from inner macro.
  880. Loc = SpellLoc;
  881. }
  882. // Find the spelling location of the start of the non-argument expansion
  883. // range. This is where the macro name was spelled in order to begin
  884. // expanding this macro.
  885. Loc = SM.getSpellingLoc(Loc);
  886. // Dig out the buffer where the macro name was spelled and the extents of the
  887. // name so that we can render it into the expansion note.
  888. std::pair<FileID, unsigned> ExpansionInfo = SM.getDecomposedLoc(Loc);
  889. unsigned MacroTokenLength = Lexer::MeasureTokenLength(Loc, SM, LangOpts);
  890. StringRef ExpansionBuffer = SM.getBufferData(ExpansionInfo.first);
  891. return ExpansionBuffer.substr(ExpansionInfo.second, MacroTokenLength);
  892. }
  893. StringRef Lexer::getImmediateMacroNameForDiagnostics(
  894. SourceLocation Loc, const SourceManager &SM, const LangOptions &LangOpts) {
  895. assert(Loc.isMacroID() && "Only reasonable to call this on macros");
  896. // Walk past macro argument expansions.
  897. while (SM.isMacroArgExpansion(Loc))
  898. Loc = SM.getImmediateExpansionRange(Loc).getBegin();
  899. // If the macro's spelling has no FileID, then it's actually a token paste
  900. // or stringization (or similar) and not a macro at all.
  901. if (!SM.getFileEntryForID(SM.getFileID(SM.getSpellingLoc(Loc))))
  902. return {};
  903. // Find the spelling location of the start of the non-argument expansion
  904. // range. This is where the macro name was spelled in order to begin
  905. // expanding this macro.
  906. Loc = SM.getSpellingLoc(SM.getImmediateExpansionRange(Loc).getBegin());
  907. // Dig out the buffer where the macro name was spelled and the extents of the
  908. // name so that we can render it into the expansion note.
  909. std::pair<FileID, unsigned> ExpansionInfo = SM.getDecomposedLoc(Loc);
  910. unsigned MacroTokenLength = Lexer::MeasureTokenLength(Loc, SM, LangOpts);
  911. StringRef ExpansionBuffer = SM.getBufferData(ExpansionInfo.first);
  912. return ExpansionBuffer.substr(ExpansionInfo.second, MacroTokenLength);
  913. }
  914. bool Lexer::isAsciiIdentifierContinueChar(char c, const LangOptions &LangOpts) {
  915. return isAsciiIdentifierContinue(c, LangOpts.DollarIdents);
  916. }
  917. bool Lexer::isNewLineEscaped(const char *BufferStart, const char *Str) {
  918. assert(isVerticalWhitespace(Str[0]));
  919. if (Str - 1 < BufferStart)
  920. return false;
  921. if ((Str[0] == '\n' && Str[-1] == '\r') ||
  922. (Str[0] == '\r' && Str[-1] == '\n')) {
  923. if (Str - 2 < BufferStart)
  924. return false;
  925. --Str;
  926. }
  927. --Str;
  928. // Rewind to first non-space character:
  929. while (Str > BufferStart && isHorizontalWhitespace(*Str))
  930. --Str;
  931. return *Str == '\\';
  932. }
  933. StringRef Lexer::getIndentationForLine(SourceLocation Loc,
  934. const SourceManager &SM) {
  935. if (Loc.isInvalid() || Loc.isMacroID())
  936. return {};
  937. std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc);
  938. if (LocInfo.first.isInvalid())
  939. return {};
  940. bool Invalid = false;
  941. StringRef Buffer = SM.getBufferData(LocInfo.first, &Invalid);
  942. if (Invalid)
  943. return {};
  944. const char *Line = findBeginningOfLine(Buffer, LocInfo.second);
  945. if (!Line)
  946. return {};
  947. StringRef Rest = Buffer.substr(Line - Buffer.data());
  948. size_t NumWhitespaceChars = Rest.find_first_not_of(" \t");
  949. return NumWhitespaceChars == StringRef::npos
  950. ? ""
  951. : Rest.take_front(NumWhitespaceChars);
  952. }
  953. //===----------------------------------------------------------------------===//
  954. // Diagnostics forwarding code.
  955. //===----------------------------------------------------------------------===//
  956. /// GetMappedTokenLoc - If lexing out of a 'mapped buffer', where we pretend the
  957. /// lexer buffer was all expanded at a single point, perform the mapping.
  958. /// This is currently only used for _Pragma implementation, so it is the slow
  959. /// path of the hot getSourceLocation method. Do not allow it to be inlined.
  960. static LLVM_ATTRIBUTE_NOINLINE SourceLocation GetMappedTokenLoc(
  961. Preprocessor &PP, SourceLocation FileLoc, unsigned CharNo, unsigned TokLen);
  962. static SourceLocation GetMappedTokenLoc(Preprocessor &PP,
  963. SourceLocation FileLoc,
  964. unsigned CharNo, unsigned TokLen) {
  965. assert(FileLoc.isMacroID() && "Must be a macro expansion");
  966. // Otherwise, we're lexing "mapped tokens". This is used for things like
  967. // _Pragma handling. Combine the expansion location of FileLoc with the
  968. // spelling location.
  969. SourceManager &SM = PP.getSourceManager();
  970. // Create a new SLoc which is expanded from Expansion(FileLoc) but whose
  971. // characters come from spelling(FileLoc)+Offset.
  972. SourceLocation SpellingLoc = SM.getSpellingLoc(FileLoc);
  973. SpellingLoc = SpellingLoc.getLocWithOffset(CharNo);
  974. // Figure out the expansion loc range, which is the range covered by the
  975. // original _Pragma(...) sequence.
  976. CharSourceRange II = SM.getImmediateExpansionRange(FileLoc);
  977. return SM.createExpansionLoc(SpellingLoc, II.getBegin(), II.getEnd(), TokLen);
  978. }
  979. /// getSourceLocation - Return a source location identifier for the specified
  980. /// offset in the current file.
  981. SourceLocation Lexer::getSourceLocation(const char *Loc,
  982. unsigned TokLen) const {
  983. assert(Loc >= BufferStart && Loc <= BufferEnd &&
  984. "Location out of range for this buffer!");
  985. // In the normal case, we're just lexing from a simple file buffer, return
  986. // the file id from FileLoc with the offset specified.
  987. unsigned CharNo = Loc-BufferStart;
  988. if (FileLoc.isFileID())
  989. return FileLoc.getLocWithOffset(CharNo);
  990. // Otherwise, this is the _Pragma lexer case, which pretends that all of the
  991. // tokens are lexed from where the _Pragma was defined.
  992. assert(PP && "This doesn't work on raw lexers");
  993. return GetMappedTokenLoc(*PP, FileLoc, CharNo, TokLen);
  994. }
  995. /// Diag - Forwarding function for diagnostics. This translate a source
  996. /// position in the current buffer into a SourceLocation object for rendering.
  997. DiagnosticBuilder Lexer::Diag(const char *Loc, unsigned DiagID) const {
  998. return PP->Diag(getSourceLocation(Loc), DiagID);
  999. }
  1000. //===----------------------------------------------------------------------===//
  1001. // Trigraph and Escaped Newline Handling Code.
  1002. //===----------------------------------------------------------------------===//
  1003. /// GetTrigraphCharForLetter - Given a character that occurs after a ?? pair,
  1004. /// return the decoded trigraph letter it corresponds to, or '\0' if nothing.
  1005. static char GetTrigraphCharForLetter(char Letter) {
  1006. switch (Letter) {
  1007. default: return 0;
  1008. case '=': return '#';
  1009. case ')': return ']';
  1010. case '(': return '[';
  1011. case '!': return '|';
  1012. case '\'': return '^';
  1013. case '>': return '}';
  1014. case '/': return '\\';
  1015. case '<': return '{';
  1016. case '-': return '~';
  1017. }
  1018. }
  1019. /// DecodeTrigraphChar - If the specified character is a legal trigraph when
  1020. /// prefixed with ??, emit a trigraph warning. If trigraphs are enabled,
  1021. /// return the result character. Finally, emit a warning about trigraph use
  1022. /// whether trigraphs are enabled or not.
  1023. static char DecodeTrigraphChar(const char *CP, Lexer *L) {
  1024. char Res = GetTrigraphCharForLetter(*CP);
  1025. if (!Res || !L) return Res;
  1026. if (!L->getLangOpts().Trigraphs) {
  1027. if (!L->isLexingRawMode())
  1028. L->Diag(CP-2, diag::trigraph_ignored);
  1029. return 0;
  1030. }
  1031. if (!L->isLexingRawMode())
  1032. L->Diag(CP-2, diag::trigraph_converted) << StringRef(&Res, 1);
  1033. return Res;
  1034. }
  1035. /// getEscapedNewLineSize - Return the size of the specified escaped newline,
  1036. /// or 0 if it is not an escaped newline. P[-1] is known to be a "\" or a
  1037. /// trigraph equivalent on entry to this function.
  1038. unsigned Lexer::getEscapedNewLineSize(const char *Ptr) {
  1039. unsigned Size = 0;
  1040. while (isWhitespace(Ptr[Size])) {
  1041. ++Size;
  1042. if (Ptr[Size-1] != '\n' && Ptr[Size-1] != '\r')
  1043. continue;
  1044. // If this is a \r\n or \n\r, skip the other half.
  1045. if ((Ptr[Size] == '\r' || Ptr[Size] == '\n') &&
  1046. Ptr[Size-1] != Ptr[Size])
  1047. ++Size;
  1048. return Size;
  1049. }
  1050. // Not an escaped newline, must be a \t or something else.
  1051. return 0;
  1052. }
  1053. /// SkipEscapedNewLines - If P points to an escaped newline (or a series of
  1054. /// them), skip over them and return the first non-escaped-newline found,
  1055. /// otherwise return P.
  1056. const char *Lexer::SkipEscapedNewLines(const char *P) {
  1057. while (true) {
  1058. const char *AfterEscape;
  1059. if (*P == '\\') {
  1060. AfterEscape = P+1;
  1061. } else if (*P == '?') {
  1062. // If not a trigraph for escape, bail out.
  1063. if (P[1] != '?' || P[2] != '/')
  1064. return P;
  1065. // FIXME: Take LangOpts into account; the language might not
  1066. // support trigraphs.
  1067. AfterEscape = P+3;
  1068. } else {
  1069. return P;
  1070. }
  1071. unsigned NewLineSize = Lexer::getEscapedNewLineSize(AfterEscape);
  1072. if (NewLineSize == 0) return P;
  1073. P = AfterEscape+NewLineSize;
  1074. }
  1075. }
  1076. Optional<Token> Lexer::findNextToken(SourceLocation Loc,
  1077. const SourceManager &SM,
  1078. const LangOptions &LangOpts) {
  1079. if (Loc.isMacroID()) {
  1080. if (!Lexer::isAtEndOfMacroExpansion(Loc, SM, LangOpts, &Loc))
  1081. return None;
  1082. }
  1083. Loc = Lexer::getLocForEndOfToken(Loc, 0, SM, LangOpts);
  1084. // Break down the source location.
  1085. std::pair<FileID, unsigned> LocInfo = SM.getDecomposedLoc(Loc);
  1086. // Try to load the file buffer.
  1087. bool InvalidTemp = false;
  1088. StringRef File = SM.getBufferData(LocInfo.first, &InvalidTemp);
  1089. if (InvalidTemp)
  1090. return None;
  1091. const char *TokenBegin = File.data() + LocInfo.second;
  1092. // Lex from the start of the given location.
  1093. Lexer lexer(SM.getLocForStartOfFile(LocInfo.first), LangOpts, File.begin(),
  1094. TokenBegin, File.end());
  1095. // Find the token.
  1096. Token Tok;
  1097. lexer.LexFromRawLexer(Tok);
  1098. return Tok;
  1099. }
  1100. /// Checks that the given token is the first token that occurs after the
  1101. /// given location (this excludes comments and whitespace). Returns the location
  1102. /// immediately after the specified token. If the token is not found or the
  1103. /// location is inside a macro, the returned source location will be invalid.
  1104. SourceLocation Lexer::findLocationAfterToken(
  1105. SourceLocation Loc, tok::TokenKind TKind, const SourceManager &SM,
  1106. const LangOptions &LangOpts, bool SkipTrailingWhitespaceAndNewLine) {
  1107. Optional<Token> Tok = findNextToken(Loc, SM, LangOpts);
  1108. if (!Tok || Tok->isNot(TKind))
  1109. return {};
  1110. SourceLocation TokenLoc = Tok->getLocation();
  1111. // Calculate how much whitespace needs to be skipped if any.
  1112. unsigned NumWhitespaceChars = 0;
  1113. if (SkipTrailingWhitespaceAndNewLine) {
  1114. const char *TokenEnd = SM.getCharacterData(TokenLoc) + Tok->getLength();
  1115. unsigned char C = *TokenEnd;
  1116. while (isHorizontalWhitespace(C)) {
  1117. C = *(++TokenEnd);
  1118. NumWhitespaceChars++;
  1119. }
  1120. // Skip \r, \n, \r\n, or \n\r
  1121. if (C == '\n' || C == '\r') {
  1122. char PrevC = C;
  1123. C = *(++TokenEnd);
  1124. NumWhitespaceChars++;
  1125. if ((C == '\n' || C == '\r') && C != PrevC)
  1126. NumWhitespaceChars++;
  1127. }
  1128. }
  1129. return TokenLoc.getLocWithOffset(Tok->getLength() + NumWhitespaceChars);
  1130. }
  1131. /// getCharAndSizeSlow - Peek a single 'character' from the specified buffer,
  1132. /// get its size, and return it. This is tricky in several cases:
  1133. /// 1. If currently at the start of a trigraph, we warn about the trigraph,
  1134. /// then either return the trigraph (skipping 3 chars) or the '?',
  1135. /// depending on whether trigraphs are enabled or not.
  1136. /// 2. If this is an escaped newline (potentially with whitespace between
  1137. /// the backslash and newline), implicitly skip the newline and return
  1138. /// the char after it.
  1139. ///
  1140. /// This handles the slow/uncommon case of the getCharAndSize method. Here we
  1141. /// know that we can accumulate into Size, and that we have already incremented
  1142. /// Ptr by Size bytes.
  1143. ///
  1144. /// NOTE: When this method is updated, getCharAndSizeSlowNoWarn (below) should
  1145. /// be updated to match.
  1146. char Lexer::getCharAndSizeSlow(const char *Ptr, unsigned &Size,
  1147. Token *Tok) {
  1148. // If we have a slash, look for an escaped newline.
  1149. if (Ptr[0] == '\\') {
  1150. ++Size;
  1151. ++Ptr;
  1152. Slash:
  1153. // Common case, backslash-char where the char is not whitespace.
  1154. if (!isWhitespace(Ptr[0])) return '\\';
  1155. // See if we have optional whitespace characters between the slash and
  1156. // newline.
  1157. if (unsigned EscapedNewLineSize = getEscapedNewLineSize(Ptr)) {
  1158. // Remember that this token needs to be cleaned.
  1159. if (Tok) Tok->setFlag(Token::NeedsCleaning);
  1160. // Warn if there was whitespace between the backslash and newline.
  1161. if (Ptr[0] != '\n' && Ptr[0] != '\r' && Tok && !isLexingRawMode())
  1162. Diag(Ptr, diag::backslash_newline_space);
  1163. // Found backslash<whitespace><newline>. Parse the char after it.
  1164. Size += EscapedNewLineSize;
  1165. Ptr += EscapedNewLineSize;
  1166. // Use slow version to accumulate a correct size field.
  1167. return getCharAndSizeSlow(Ptr, Size, Tok);
  1168. }
  1169. // Otherwise, this is not an escaped newline, just return the slash.
  1170. return '\\';
  1171. }
  1172. // If this is a trigraph, process it.
  1173. if (Ptr[0] == '?' && Ptr[1] == '?') {
  1174. // If this is actually a legal trigraph (not something like "??x"), emit
  1175. // a trigraph warning. If so, and if trigraphs are enabled, return it.
  1176. if (char C = DecodeTrigraphChar(Ptr+2, Tok ? this : nullptr)) {
  1177. // Remember that this token needs to be cleaned.
  1178. if (Tok) Tok->setFlag(Token::NeedsCleaning);
  1179. Ptr += 3;
  1180. Size += 3;
  1181. if (C == '\\') goto Slash;
  1182. return C;
  1183. }
  1184. }
  1185. // If this is neither, return a single character.
  1186. ++Size;
  1187. return *Ptr;
  1188. }
  1189. /// getCharAndSizeSlowNoWarn - Handle the slow/uncommon case of the
  1190. /// getCharAndSizeNoWarn method. Here we know that we can accumulate into Size,
  1191. /// and that we have already incremented Ptr by Size bytes.
  1192. ///
  1193. /// NOTE: When this method is updated, getCharAndSizeSlow (above) should
  1194. /// be updated to match.
  1195. char Lexer::getCharAndSizeSlowNoWarn(const char *Ptr, unsigned &Size,
  1196. const LangOptions &LangOpts) {
  1197. // If we have a slash, look for an escaped newline.
  1198. if (Ptr[0] == '\\') {
  1199. ++Size;
  1200. ++Ptr;
  1201. Slash:
  1202. // Common case, backslash-char where the char is not whitespace.
  1203. if (!isWhitespace(Ptr[0])) return '\\';
  1204. // See if we have optional whitespace characters followed by a newline.
  1205. if (unsigned EscapedNewLineSize = getEscapedNewLineSize(Ptr)) {
  1206. // Found backslash<whitespace><newline>. Parse the char after it.
  1207. Size += EscapedNewLineSize;
  1208. Ptr += EscapedNewLineSize;
  1209. // Use slow version to accumulate a correct size field.
  1210. return getCharAndSizeSlowNoWarn(Ptr, Size, LangOpts);
  1211. }
  1212. // Otherwise, this is not an escaped newline, just return the slash.
  1213. return '\\';
  1214. }
  1215. // If this is a trigraph, process it.
  1216. if (LangOpts.Trigraphs && Ptr[0] == '?' && Ptr[1] == '?') {
  1217. // If this is actually a legal trigraph (not something like "??x"), return
  1218. // it.
  1219. if (char C = GetTrigraphCharForLetter(Ptr[2])) {
  1220. Ptr += 3;
  1221. Size += 3;
  1222. if (C == '\\') goto Slash;
  1223. return C;
  1224. }
  1225. }
  1226. // If this is neither, return a single character.
  1227. ++Size;
  1228. return *Ptr;
  1229. }
  1230. //===----------------------------------------------------------------------===//
  1231. // Helper methods for lexing.
  1232. //===----------------------------------------------------------------------===//
  1233. /// Routine that indiscriminately sets the offset into the source file.
  1234. void Lexer::SetByteOffset(unsigned Offset, bool StartOfLine) {
  1235. BufferPtr = BufferStart + Offset;
  1236. if (BufferPtr > BufferEnd)
  1237. BufferPtr = BufferEnd;
  1238. // FIXME: What exactly does the StartOfLine bit mean? There are two
  1239. // possible meanings for the "start" of the line: the first token on the
  1240. // unexpanded line, or the first token on the expanded line.
  1241. IsAtStartOfLine = StartOfLine;
  1242. IsAtPhysicalStartOfLine = StartOfLine;
  1243. }
  1244. static bool isUnicodeWhitespace(uint32_t Codepoint) {
  1245. static const llvm::sys::UnicodeCharSet UnicodeWhitespaceChars(
  1246. UnicodeWhitespaceCharRanges);
  1247. return UnicodeWhitespaceChars.contains(Codepoint);
  1248. }
  1249. static bool isAllowedIDChar(uint32_t C, const LangOptions &LangOpts) {
  1250. if (LangOpts.AsmPreprocessor) {
  1251. return false;
  1252. } else if (LangOpts.DollarIdents && '$' == C) {
  1253. return true;
  1254. } else if (LangOpts.CPlusPlus) {
  1255. // A non-leading codepoint must have the XID_Continue property.
  1256. // XIDContinueRanges doesn't contains characters also in XIDStartRanges,
  1257. // so we need to check both tables.
  1258. // '_' doesn't have the XID_Continue property but is allowed in C++.
  1259. static const llvm::sys::UnicodeCharSet XIDStartChars(XIDStartRanges);
  1260. static const llvm::sys::UnicodeCharSet XIDContinueChars(XIDContinueRanges);
  1261. return C == '_' || XIDStartChars.contains(C) ||
  1262. XIDContinueChars.contains(C);
  1263. } else if (LangOpts.C11) {
  1264. static const llvm::sys::UnicodeCharSet C11AllowedIDChars(
  1265. C11AllowedIDCharRanges);
  1266. return C11AllowedIDChars.contains(C);
  1267. } else {
  1268. static const llvm::sys::UnicodeCharSet C99AllowedIDChars(
  1269. C99AllowedIDCharRanges);
  1270. return C99AllowedIDChars.contains(C);
  1271. }
  1272. }
  1273. static bool isAllowedInitiallyIDChar(uint32_t C, const LangOptions &LangOpts) {
  1274. if (LangOpts.AsmPreprocessor) {
  1275. return false;
  1276. }
  1277. if (LangOpts.CPlusPlus) {
  1278. static const llvm::sys::UnicodeCharSet XIDStartChars(XIDStartRanges);
  1279. // '_' doesn't have the XID_Start property but is allowed in C++.
  1280. return C == '_' || XIDStartChars.contains(C);
  1281. }
  1282. if (!isAllowedIDChar(C, LangOpts))
  1283. return false;
  1284. if (LangOpts.C11) {
  1285. static const llvm::sys::UnicodeCharSet C11DisallowedInitialIDChars(
  1286. C11DisallowedInitialIDCharRanges);
  1287. return !C11DisallowedInitialIDChars.contains(C);
  1288. }
  1289. static const llvm::sys::UnicodeCharSet C99DisallowedInitialIDChars(
  1290. C99DisallowedInitialIDCharRanges);
  1291. return !C99DisallowedInitialIDChars.contains(C);
  1292. }
  1293. static inline CharSourceRange makeCharRange(Lexer &L, const char *Begin,
  1294. const char *End) {
  1295. return CharSourceRange::getCharRange(L.getSourceLocation(Begin),
  1296. L.getSourceLocation(End));
  1297. }
  1298. static void maybeDiagnoseIDCharCompat(DiagnosticsEngine &Diags, uint32_t C,
  1299. CharSourceRange Range, bool IsFirst) {
  1300. // Check C99 compatibility.
  1301. if (!Diags.isIgnored(diag::warn_c99_compat_unicode_id, Range.getBegin())) {
  1302. enum {
  1303. CannotAppearInIdentifier = 0,
  1304. CannotStartIdentifier
  1305. };
  1306. static const llvm::sys::UnicodeCharSet C99AllowedIDChars(
  1307. C99AllowedIDCharRanges);
  1308. static const llvm::sys::UnicodeCharSet C99DisallowedInitialIDChars(
  1309. C99DisallowedInitialIDCharRanges);
  1310. if (!C99AllowedIDChars.contains(C)) {
  1311. Diags.Report(Range.getBegin(), diag::warn_c99_compat_unicode_id)
  1312. << Range
  1313. << CannotAppearInIdentifier;
  1314. } else if (IsFirst && C99DisallowedInitialIDChars.contains(C)) {
  1315. Diags.Report(Range.getBegin(), diag::warn_c99_compat_unicode_id)
  1316. << Range
  1317. << CannotStartIdentifier;
  1318. }
  1319. }
  1320. }
  1321. /// After encountering UTF-8 character C and interpreting it as an identifier
  1322. /// character, check whether it's a homoglyph for a common non-identifier
  1323. /// source character that is unlikely to be an intentional identifier
  1324. /// character and warn if so.
  1325. static void maybeDiagnoseUTF8Homoglyph(DiagnosticsEngine &Diags, uint32_t C,
  1326. CharSourceRange Range) {
  1327. // FIXME: Handle Unicode quotation marks (smart quotes, fullwidth quotes).
  1328. struct HomoglyphPair {
  1329. uint32_t Character;
  1330. char LooksLike;
  1331. bool operator<(HomoglyphPair R) const { return Character < R.Character; }
  1332. };
  1333. static constexpr HomoglyphPair SortedHomoglyphs[] = {
  1334. {U'\u00ad', 0}, // SOFT HYPHEN
  1335. {U'\u01c3', '!'}, // LATIN LETTER RETROFLEX CLICK
  1336. {U'\u037e', ';'}, // GREEK QUESTION MARK
  1337. {U'\u200b', 0}, // ZERO WIDTH SPACE
  1338. {U'\u200c', 0}, // ZERO WIDTH NON-JOINER
  1339. {U'\u200d', 0}, // ZERO WIDTH JOINER
  1340. {U'\u2060', 0}, // WORD JOINER
  1341. {U'\u2061', 0}, // FUNCTION APPLICATION
  1342. {U'\u2062', 0}, // INVISIBLE TIMES
  1343. {U'\u2063', 0}, // INVISIBLE SEPARATOR
  1344. {U'\u2064', 0}, // INVISIBLE PLUS
  1345. {U'\u2212', '-'}, // MINUS SIGN
  1346. {U'\u2215', '/'}, // DIVISION SLASH
  1347. {U'\u2216', '\\'}, // SET MINUS
  1348. {U'\u2217', '*'}, // ASTERISK OPERATOR
  1349. {U'\u2223', '|'}, // DIVIDES
  1350. {U'\u2227', '^'}, // LOGICAL AND
  1351. {U'\u2236', ':'}, // RATIO
  1352. {U'\u223c', '~'}, // TILDE OPERATOR
  1353. {U'\ua789', ':'}, // MODIFIER LETTER COLON
  1354. {U'\ufeff', 0}, // ZERO WIDTH NO-BREAK SPACE
  1355. {U'\uff01', '!'}, // FULLWIDTH EXCLAMATION MARK
  1356. {U'\uff03', '#'}, // FULLWIDTH NUMBER SIGN
  1357. {U'\uff04', '$'}, // FULLWIDTH DOLLAR SIGN
  1358. {U'\uff05', '%'}, // FULLWIDTH PERCENT SIGN
  1359. {U'\uff06', '&'}, // FULLWIDTH AMPERSAND
  1360. {U'\uff08', '('}, // FULLWIDTH LEFT PARENTHESIS
  1361. {U'\uff09', ')'}, // FULLWIDTH RIGHT PARENTHESIS
  1362. {U'\uff0a', '*'}, // FULLWIDTH ASTERISK
  1363. {U'\uff0b', '+'}, // FULLWIDTH ASTERISK
  1364. {U'\uff0c', ','}, // FULLWIDTH COMMA
  1365. {U'\uff0d', '-'}, // FULLWIDTH HYPHEN-MINUS
  1366. {U'\uff0e', '.'}, // FULLWIDTH FULL STOP
  1367. {U'\uff0f', '/'}, // FULLWIDTH SOLIDUS
  1368. {U'\uff1a', ':'}, // FULLWIDTH COLON
  1369. {U'\uff1b', ';'}, // FULLWIDTH SEMICOLON
  1370. {U'\uff1c', '<'}, // FULLWIDTH LESS-THAN SIGN
  1371. {U'\uff1d', '='}, // FULLWIDTH EQUALS SIGN
  1372. {U'\uff1e', '>'}, // FULLWIDTH GREATER-THAN SIGN
  1373. {U'\uff1f', '?'}, // FULLWIDTH QUESTION MARK
  1374. {U'\uff20', '@'}, // FULLWIDTH COMMERCIAL AT
  1375. {U'\uff3b', '['}, // FULLWIDTH LEFT SQUARE BRACKET
  1376. {U'\uff3c', '\\'}, // FULLWIDTH REVERSE SOLIDUS
  1377. {U'\uff3d', ']'}, // FULLWIDTH RIGHT SQUARE BRACKET
  1378. {U'\uff3e', '^'}, // FULLWIDTH CIRCUMFLEX ACCENT
  1379. {U'\uff5b', '{'}, // FULLWIDTH LEFT CURLY BRACKET
  1380. {U'\uff5c', '|'}, // FULLWIDTH VERTICAL LINE
  1381. {U'\uff5d', '}'}, // FULLWIDTH RIGHT CURLY BRACKET
  1382. {U'\uff5e', '~'}, // FULLWIDTH TILDE
  1383. {0, 0}
  1384. };
  1385. auto Homoglyph =
  1386. std::lower_bound(std::begin(SortedHomoglyphs),
  1387. std::end(SortedHomoglyphs) - 1, HomoglyphPair{C, '\0'});
  1388. if (Homoglyph->Character == C) {
  1389. llvm::SmallString<5> CharBuf;
  1390. {
  1391. llvm::raw_svector_ostream CharOS(CharBuf);
  1392. llvm::write_hex(CharOS, C, llvm::HexPrintStyle::Upper, 4);
  1393. }
  1394. if (Homoglyph->LooksLike) {
  1395. const char LooksLikeStr[] = {Homoglyph->LooksLike, 0};
  1396. Diags.Report(Range.getBegin(), diag::warn_utf8_symbol_homoglyph)
  1397. << Range << CharBuf << LooksLikeStr;
  1398. } else {
  1399. Diags.Report(Range.getBegin(), diag::warn_utf8_symbol_zero_width)
  1400. << Range << CharBuf;
  1401. }
  1402. }
  1403. }
  1404. static void diagnoseInvalidUnicodeCodepointInIdentifier(
  1405. DiagnosticsEngine &Diags, const LangOptions &LangOpts, uint32_t CodePoint,
  1406. CharSourceRange Range, bool IsFirst) {
  1407. if (isASCII(CodePoint))
  1408. return;
  1409. bool IsIDStart = isAllowedInitiallyIDChar(CodePoint, LangOpts);
  1410. bool IsIDContinue = IsIDStart || isAllowedIDChar(CodePoint, LangOpts);
  1411. if ((IsFirst && IsIDStart) || (!IsFirst && IsIDContinue))
  1412. return;
  1413. bool InvalidOnlyAtStart = IsFirst && !IsIDStart && IsIDContinue;
  1414. llvm::SmallString<5> CharBuf;
  1415. llvm::raw_svector_ostream CharOS(CharBuf);
  1416. llvm::write_hex(CharOS, CodePoint, llvm::HexPrintStyle::Upper, 4);
  1417. if (!IsFirst || InvalidOnlyAtStart) {
  1418. Diags.Report(Range.getBegin(), diag::err_character_not_allowed_identifier)
  1419. << Range << CharBuf << int(InvalidOnlyAtStart)
  1420. << FixItHint::CreateRemoval(Range);
  1421. } else {
  1422. Diags.Report(Range.getBegin(), diag::err_character_not_allowed)
  1423. << Range << CharBuf << FixItHint::CreateRemoval(Range);
  1424. }
  1425. }
  1426. bool Lexer::tryConsumeIdentifierUCN(const char *&CurPtr, unsigned Size,
  1427. Token &Result) {
  1428. const char *UCNPtr = CurPtr + Size;
  1429. uint32_t CodePoint = tryReadUCN(UCNPtr, CurPtr, /*Token=*/nullptr);
  1430. if (CodePoint == 0) {
  1431. return false;
  1432. }
  1433. if (!isAllowedIDChar(CodePoint, LangOpts)) {
  1434. if (isASCII(CodePoint) || isUnicodeWhitespace(CodePoint))
  1435. return false;
  1436. if (!isLexingRawMode() && !ParsingPreprocessorDirective &&
  1437. !PP->isPreprocessedOutput())
  1438. diagnoseInvalidUnicodeCodepointInIdentifier(
  1439. PP->getDiagnostics(), LangOpts, CodePoint,
  1440. makeCharRange(*this, CurPtr, UCNPtr),
  1441. /*IsFirst=*/false);
  1442. // We got a unicode codepoint that is neither a space nor a
  1443. // a valid identifier part.
  1444. // Carry on as if the codepoint was valid for recovery purposes.
  1445. } else if (!isLexingRawMode())
  1446. maybeDiagnoseIDCharCompat(PP->getDiagnostics(), CodePoint,
  1447. makeCharRange(*this, CurPtr, UCNPtr),
  1448. /*IsFirst=*/false);
  1449. Result.setFlag(Token::HasUCN);
  1450. if ((UCNPtr - CurPtr == 6 && CurPtr[1] == 'u') ||
  1451. (UCNPtr - CurPtr == 10 && CurPtr[1] == 'U'))
  1452. CurPtr = UCNPtr;
  1453. else
  1454. while (CurPtr != UCNPtr)
  1455. (void)getAndAdvanceChar(CurPtr, Result);
  1456. return true;
  1457. }
  1458. bool Lexer::tryConsumeIdentifierUTF8Char(const char *&CurPtr) {
  1459. const char *UnicodePtr = CurPtr;
  1460. llvm::UTF32 CodePoint;
  1461. llvm::ConversionResult Result =
  1462. llvm::convertUTF8Sequence((const llvm::UTF8 **)&UnicodePtr,
  1463. (const llvm::UTF8 *)BufferEnd,
  1464. &CodePoint,
  1465. llvm::strictConversion);
  1466. if (Result != llvm::conversionOK)
  1467. return false;
  1468. if (!isAllowedIDChar(static_cast<uint32_t>(CodePoint), LangOpts)) {
  1469. if (isASCII(CodePoint) || isUnicodeWhitespace(CodePoint))
  1470. return false;
  1471. if (!isLexingRawMode() && !ParsingPreprocessorDirective &&
  1472. !PP->isPreprocessedOutput())
  1473. diagnoseInvalidUnicodeCodepointInIdentifier(
  1474. PP->getDiagnostics(), LangOpts, CodePoint,
  1475. makeCharRange(*this, CurPtr, UnicodePtr), /*IsFirst=*/false);
  1476. // We got a unicode codepoint that is neither a space nor a
  1477. // a valid identifier part. Carry on as if the codepoint was
  1478. // valid for recovery purposes.
  1479. } else if (!isLexingRawMode()) {
  1480. maybeDiagnoseIDCharCompat(PP->getDiagnostics(), CodePoint,
  1481. makeCharRange(*this, CurPtr, UnicodePtr),
  1482. /*IsFirst=*/false);
  1483. maybeDiagnoseUTF8Homoglyph(PP->getDiagnostics(), CodePoint,
  1484. makeCharRange(*this, CurPtr, UnicodePtr));
  1485. }
  1486. CurPtr = UnicodePtr;
  1487. return true;
  1488. }
  1489. bool Lexer::LexUnicodeIdentifierStart(Token &Result, uint32_t C,
  1490. const char *CurPtr) {
  1491. if (isAllowedInitiallyIDChar(C, LangOpts)) {
  1492. if (!isLexingRawMode() && !ParsingPreprocessorDirective &&
  1493. !PP->isPreprocessedOutput()) {
  1494. maybeDiagnoseIDCharCompat(PP->getDiagnostics(), C,
  1495. makeCharRange(*this, BufferPtr, CurPtr),
  1496. /*IsFirst=*/true);
  1497. maybeDiagnoseUTF8Homoglyph(PP->getDiagnostics(), C,
  1498. makeCharRange(*this, BufferPtr, CurPtr));
  1499. }
  1500. MIOpt.ReadToken();
  1501. return LexIdentifierContinue(Result, CurPtr);
  1502. }
  1503. if (!isLexingRawMode() && !ParsingPreprocessorDirective &&
  1504. !PP->isPreprocessedOutput() && !isASCII(*BufferPtr) &&
  1505. !isAllowedInitiallyIDChar(C, LangOpts) && !isUnicodeWhitespace(C)) {
  1506. // Non-ASCII characters tend to creep into source code unintentionally.
  1507. // Instead of letting the parser complain about the unknown token,
  1508. // just drop the character.
  1509. // Note that we can /only/ do this when the non-ASCII character is actually
  1510. // spelled as Unicode, not written as a UCN. The standard requires that
  1511. // we not throw away any possible preprocessor tokens, but there's a
  1512. // loophole in the mapping of Unicode characters to basic character set
  1513. // characters that allows us to map these particular characters to, say,
  1514. // whitespace.
  1515. diagnoseInvalidUnicodeCodepointInIdentifier(
  1516. PP->getDiagnostics(), LangOpts, C,
  1517. makeCharRange(*this, BufferPtr, CurPtr), /*IsStart*/ true);
  1518. BufferPtr = CurPtr;
  1519. return false;
  1520. }
  1521. // Otherwise, we have an explicit UCN or a character that's unlikely to show
  1522. // up by accident.
  1523. MIOpt.ReadToken();
  1524. FormTokenWithChars(Result, CurPtr, tok::unknown);
  1525. return true;
  1526. }
  1527. bool Lexer::LexIdentifierContinue(Token &Result, const char *CurPtr) {
  1528. // Match [_A-Za-z0-9]*, we have already matched an identifier start.
  1529. while (true) {
  1530. unsigned char C = *CurPtr;
  1531. // Fast path.
  1532. if (isAsciiIdentifierContinue(C)) {
  1533. ++CurPtr;
  1534. continue;
  1535. }
  1536. unsigned Size;
  1537. // Slow path: handle trigraph, unicode codepoints, UCNs.
  1538. C = getCharAndSize(CurPtr, Size);
  1539. if (isAsciiIdentifierContinue(C)) {
  1540. CurPtr = ConsumeChar(CurPtr, Size, Result);
  1541. continue;
  1542. }
  1543. if (C == '$') {
  1544. // If we hit a $ and they are not supported in identifiers, we are done.
  1545. if (!LangOpts.DollarIdents)
  1546. break;
  1547. // Otherwise, emit a diagnostic and continue.
  1548. if (!isLexingRawMode())
  1549. Diag(CurPtr, diag::ext_dollar_in_identifier);
  1550. CurPtr = ConsumeChar(CurPtr, Size, Result);
  1551. continue;
  1552. }
  1553. if (C == '\\' && tryConsumeIdentifierUCN(CurPtr, Size, Result))
  1554. continue;
  1555. if (!isASCII(C) && tryConsumeIdentifierUTF8Char(CurPtr))
  1556. continue;
  1557. // Neither an expected Unicode codepoint nor a UCN.
  1558. break;
  1559. }
  1560. const char *IdStart = BufferPtr;
  1561. FormTokenWithChars(Result, CurPtr, tok::raw_identifier);
  1562. Result.setRawIdentifierData(IdStart);
  1563. // If we are in raw mode, return this identifier raw. There is no need to
  1564. // look up identifier information or attempt to macro expand it.
  1565. if (LexingRawMode)
  1566. return true;
  1567. // Fill in Result.IdentifierInfo and update the token kind,
  1568. // looking up the identifier in the identifier table.
  1569. IdentifierInfo *II = PP->LookUpIdentifierInfo(Result);
  1570. // Note that we have to call PP->LookUpIdentifierInfo() even for code
  1571. // completion, it writes IdentifierInfo into Result, and callers rely on it.
  1572. // If the completion point is at the end of an identifier, we want to treat
  1573. // the identifier as incomplete even if it resolves to a macro or a keyword.
  1574. // This allows e.g. 'class^' to complete to 'classifier'.
  1575. if (isCodeCompletionPoint(CurPtr)) {
  1576. // Return the code-completion token.
  1577. Result.setKind(tok::code_completion);
  1578. // Skip the code-completion char and all immediate identifier characters.
  1579. // This ensures we get consistent behavior when completing at any point in
  1580. // an identifier (i.e. at the start, in the middle, at the end). Note that
  1581. // only simple cases (i.e. [a-zA-Z0-9_]) are supported to keep the code
  1582. // simpler.
  1583. assert(*CurPtr == 0 && "Completion character must be 0");
  1584. ++CurPtr;
  1585. // Note that code completion token is not added as a separate character
  1586. // when the completion point is at the end of the buffer. Therefore, we need
  1587. // to check if the buffer has ended.
  1588. if (CurPtr < BufferEnd) {
  1589. while (isAsciiIdentifierContinue(*CurPtr))
  1590. ++CurPtr;
  1591. }
  1592. BufferPtr = CurPtr;
  1593. return true;
  1594. }
  1595. // Finally, now that we know we have an identifier, pass this off to the
  1596. // preprocessor, which may macro expand it or something.
  1597. if (II->isHandleIdentifierCase())
  1598. return PP->HandleIdentifier(Result);
  1599. return true;
  1600. }
  1601. /// isHexaLiteral - Return true if Start points to a hex constant.
  1602. /// in microsoft mode (where this is supposed to be several different tokens).
  1603. bool Lexer::isHexaLiteral(const char *Start, const LangOptions &LangOpts) {
  1604. unsigned Size;
  1605. char C1 = Lexer::getCharAndSizeNoWarn(Start, Size, LangOpts);
  1606. if (C1 != '0')
  1607. return false;
  1608. char C2 = Lexer::getCharAndSizeNoWarn(Start + Size, Size, LangOpts);
  1609. return (C2 == 'x' || C2 == 'X');
  1610. }
  1611. /// LexNumericConstant - Lex the remainder of a integer or floating point
  1612. /// constant. From[-1] is the first character lexed. Return the end of the
  1613. /// constant.
  1614. bool Lexer::LexNumericConstant(Token &Result, const char *CurPtr) {
  1615. unsigned Size;
  1616. char C = getCharAndSize(CurPtr, Size);
  1617. char PrevCh = 0;
  1618. while (isPreprocessingNumberBody(C)) {
  1619. CurPtr = ConsumeChar(CurPtr, Size, Result);
  1620. PrevCh = C;
  1621. C = getCharAndSize(CurPtr, Size);
  1622. }
  1623. // If we fell out, check for a sign, due to 1e+12. If we have one, continue.
  1624. if ((C == '-' || C == '+') && (PrevCh == 'E' || PrevCh == 'e')) {
  1625. // If we are in Microsoft mode, don't continue if the constant is hex.
  1626. // For example, MSVC will accept the following as 3 tokens: 0x1234567e+1
  1627. if (!LangOpts.MicrosoftExt || !isHexaLiteral(BufferPtr, LangOpts))
  1628. return LexNumericConstant(Result, ConsumeChar(CurPtr, Size, Result));
  1629. }
  1630. // If we have a hex FP constant, continue.
  1631. if ((C == '-' || C == '+') && (PrevCh == 'P' || PrevCh == 'p')) {
  1632. // Outside C99 and C++17, we accept hexadecimal floating point numbers as a
  1633. // not-quite-conforming extension. Only do so if this looks like it's
  1634. // actually meant to be a hexfloat, and not if it has a ud-suffix.
  1635. bool IsHexFloat = true;
  1636. if (!LangOpts.C99) {
  1637. if (!isHexaLiteral(BufferPtr, LangOpts))
  1638. IsHexFloat = false;
  1639. else if (!getLangOpts().CPlusPlus17 &&
  1640. std::find(BufferPtr, CurPtr, '_') != CurPtr)
  1641. IsHexFloat = false;
  1642. }
  1643. if (IsHexFloat)
  1644. return LexNumericConstant(Result, ConsumeChar(CurPtr, Size, Result));
  1645. }
  1646. // If we have a digit separator, continue.
  1647. if (C == '\'' && (getLangOpts().CPlusPlus14 || getLangOpts().C2x)) {
  1648. unsigned NextSize;
  1649. char Next = getCharAndSizeNoWarn(CurPtr + Size, NextSize, getLangOpts());
  1650. if (isAsciiIdentifierContinue(Next)) {
  1651. if (!isLexingRawMode())
  1652. Diag(CurPtr, getLangOpts().CPlusPlus
  1653. ? diag::warn_cxx11_compat_digit_separator
  1654. : diag::warn_c2x_compat_digit_separator);
  1655. CurPtr = ConsumeChar(CurPtr, Size, Result);
  1656. CurPtr = ConsumeChar(CurPtr, NextSize, Result);
  1657. return LexNumericConstant(Result, CurPtr);
  1658. }
  1659. }
  1660. // If we have a UCN or UTF-8 character (perhaps in a ud-suffix), continue.
  1661. if (C == '\\' && tryConsumeIdentifierUCN(CurPtr, Size, Result))
  1662. return LexNumericConstant(Result, CurPtr);
  1663. if (!isASCII(C) && tryConsumeIdentifierUTF8Char(CurPtr))
  1664. return LexNumericConstant(Result, CurPtr);
  1665. // Update the location of token as well as BufferPtr.
  1666. const char *TokStart = BufferPtr;
  1667. FormTokenWithChars(Result, CurPtr, tok::numeric_constant);
  1668. Result.setLiteralData(TokStart);
  1669. return true;
  1670. }
  1671. /// LexUDSuffix - Lex the ud-suffix production for user-defined literal suffixes
  1672. /// in C++11, or warn on a ud-suffix in C++98.
  1673. const char *Lexer::LexUDSuffix(Token &Result, const char *CurPtr,
  1674. bool IsStringLiteral) {
  1675. assert(getLangOpts().CPlusPlus);
  1676. // Maximally munch an identifier.
  1677. unsigned Size;
  1678. char C = getCharAndSize(CurPtr, Size);
  1679. bool Consumed = false;
  1680. if (!isAsciiIdentifierStart(C)) {
  1681. if (C == '\\' && tryConsumeIdentifierUCN(CurPtr, Size, Result))
  1682. Consumed = true;
  1683. else if (!isASCII(C) && tryConsumeIdentifierUTF8Char(CurPtr))
  1684. Consumed = true;
  1685. else
  1686. return CurPtr;
  1687. }
  1688. if (!getLangOpts().CPlusPlus11) {
  1689. if (!isLexingRawMode())
  1690. Diag(CurPtr,
  1691. C == '_' ? diag::warn_cxx11_compat_user_defined_literal
  1692. : diag::warn_cxx11_compat_reserved_user_defined_literal)
  1693. << FixItHint::CreateInsertion(getSourceLocation(CurPtr), " ");
  1694. return CurPtr;
  1695. }
  1696. // C++11 [lex.ext]p10, [usrlit.suffix]p1: A program containing a ud-suffix
  1697. // that does not start with an underscore is ill-formed. As a conforming
  1698. // extension, we treat all such suffixes as if they had whitespace before
  1699. // them. We assume a suffix beginning with a UCN or UTF-8 character is more
  1700. // likely to be a ud-suffix than a macro, however, and accept that.
  1701. if (!Consumed) {
  1702. bool IsUDSuffix = false;
  1703. if (C == '_')
  1704. IsUDSuffix = true;
  1705. else if (IsStringLiteral && getLangOpts().CPlusPlus14) {
  1706. // In C++1y, we need to look ahead a few characters to see if this is a
  1707. // valid suffix for a string literal or a numeric literal (this could be
  1708. // the 'operator""if' defining a numeric literal operator).
  1709. const unsigned MaxStandardSuffixLength = 3;
  1710. char Buffer[MaxStandardSuffixLength] = { C };
  1711. unsigned Consumed = Size;
  1712. unsigned Chars = 1;
  1713. while (true) {
  1714. unsigned NextSize;
  1715. char Next = getCharAndSizeNoWarn(CurPtr + Consumed, NextSize,
  1716. getLangOpts());
  1717. if (!isAsciiIdentifierContinue(Next)) {
  1718. // End of suffix. Check whether this is on the allowed list.
  1719. const StringRef CompleteSuffix(Buffer, Chars);
  1720. IsUDSuffix = StringLiteralParser::isValidUDSuffix(getLangOpts(),
  1721. CompleteSuffix);
  1722. break;
  1723. }
  1724. if (Chars == MaxStandardSuffixLength)
  1725. // Too long: can't be a standard suffix.
  1726. break;
  1727. Buffer[Chars++] = Next;
  1728. Consumed += NextSize;
  1729. }
  1730. }
  1731. if (!IsUDSuffix) {
  1732. if (!isLexingRawMode())
  1733. Diag(CurPtr, getLangOpts().MSVCCompat
  1734. ? diag::ext_ms_reserved_user_defined_literal
  1735. : diag::ext_reserved_user_defined_literal)
  1736. << FixItHint::CreateInsertion(getSourceLocation(CurPtr), " ");
  1737. return CurPtr;
  1738. }
  1739. CurPtr = ConsumeChar(CurPtr, Size, Result);
  1740. }
  1741. Result.setFlag(Token::HasUDSuffix);
  1742. while (true) {
  1743. C = getCharAndSize(CurPtr, Size);
  1744. if (isAsciiIdentifierContinue(C)) {
  1745. CurPtr = ConsumeChar(CurPtr, Size, Result);
  1746. } else if (C == '\\' && tryConsumeIdentifierUCN(CurPtr, Size, Result)) {
  1747. } else if (!isASCII(C) && tryConsumeIdentifierUTF8Char(CurPtr)) {
  1748. } else
  1749. break;
  1750. }
  1751. return CurPtr;
  1752. }
  1753. /// LexStringLiteral - Lex the remainder of a string literal, after having lexed
  1754. /// either " or L" or u8" or u" or U".
  1755. bool Lexer::LexStringLiteral(Token &Result, const char *CurPtr,
  1756. tok::TokenKind Kind) {
  1757. const char *AfterQuote = CurPtr;
  1758. // Does this string contain the \0 character?
  1759. const char *NulCharacter = nullptr;
  1760. if (!isLexingRawMode() &&
  1761. (Kind == tok::utf8_string_literal ||
  1762. Kind == tok::utf16_string_literal ||
  1763. Kind == tok::utf32_string_literal))
  1764. Diag(BufferPtr, getLangOpts().CPlusPlus
  1765. ? diag::warn_cxx98_compat_unicode_literal
  1766. : diag::warn_c99_compat_unicode_literal);
  1767. char C = getAndAdvanceChar(CurPtr, Result);
  1768. while (C != '"') {
  1769. // Skip escaped characters. Escaped newlines will already be processed by
  1770. // getAndAdvanceChar.
  1771. if (C == '\\')
  1772. C = getAndAdvanceChar(CurPtr, Result);
  1773. if (C == '\n' || C == '\r' || // Newline.
  1774. (C == 0 && CurPtr-1 == BufferEnd)) { // End of file.
  1775. if (!isLexingRawMode() && !LangOpts.AsmPreprocessor)
  1776. Diag(BufferPtr, diag::ext_unterminated_char_or_string) << 1;
  1777. FormTokenWithChars(Result, CurPtr-1, tok::unknown);
  1778. return true;
  1779. }
  1780. if (C == 0) {
  1781. if (isCodeCompletionPoint(CurPtr-1)) {
  1782. if (ParsingFilename)
  1783. codeCompleteIncludedFile(AfterQuote, CurPtr - 1, /*IsAngled=*/false);
  1784. else
  1785. PP->CodeCompleteNaturalLanguage();
  1786. FormTokenWithChars(Result, CurPtr - 1, tok::unknown);
  1787. cutOffLexing();
  1788. return true;
  1789. }
  1790. NulCharacter = CurPtr-1;
  1791. }
  1792. C = getAndAdvanceChar(CurPtr, Result);
  1793. }
  1794. // If we are in C++11, lex the optional ud-suffix.
  1795. if (getLangOpts().CPlusPlus)
  1796. CurPtr = LexUDSuffix(Result, CurPtr, true);
  1797. // If a nul character existed in the string, warn about it.
  1798. if (NulCharacter && !isLexingRawMode())
  1799. Diag(NulCharacter, diag::null_in_char_or_string) << 1;
  1800. // Update the location of the token as well as the BufferPtr instance var.
  1801. const char *TokStart = BufferPtr;
  1802. FormTokenWithChars(Result, CurPtr, Kind);
  1803. Result.setLiteralData(TokStart);
  1804. return true;
  1805. }
  1806. /// LexRawStringLiteral - Lex the remainder of a raw string literal, after
  1807. /// having lexed R", LR", u8R", uR", or UR".
  1808. bool Lexer::LexRawStringLiteral(Token &Result, const char *CurPtr,
  1809. tok::TokenKind Kind) {
  1810. // This function doesn't use getAndAdvanceChar because C++0x [lex.pptoken]p3:
  1811. // Between the initial and final double quote characters of the raw string,
  1812. // any transformations performed in phases 1 and 2 (trigraphs,
  1813. // universal-character-names, and line splicing) are reverted.
  1814. if (!isLexingRawMode())
  1815. Diag(BufferPtr, diag::warn_cxx98_compat_raw_string_literal);
  1816. unsigned PrefixLen = 0;
  1817. while (PrefixLen != 16 && isRawStringDelimBody(CurPtr[PrefixLen]))
  1818. ++PrefixLen;
  1819. // If the last character was not a '(', then we didn't lex a valid delimiter.
  1820. if (CurPtr[PrefixLen] != '(') {
  1821. if (!isLexingRawMode()) {
  1822. const char *PrefixEnd = &CurPtr[PrefixLen];
  1823. if (PrefixLen == 16) {
  1824. Diag(PrefixEnd, diag::err_raw_delim_too_long);
  1825. } else {
  1826. Diag(PrefixEnd, diag::err_invalid_char_raw_delim)
  1827. << StringRef(PrefixEnd, 1);
  1828. }
  1829. }
  1830. // Search for the next '"' in hopes of salvaging the lexer. Unfortunately,
  1831. // it's possible the '"' was intended to be part of the raw string, but
  1832. // there's not much we can do about that.
  1833. while (true) {
  1834. char C = *CurPtr++;
  1835. if (C == '"')
  1836. break;
  1837. if (C == 0 && CurPtr-1 == BufferEnd) {
  1838. --CurPtr;
  1839. break;
  1840. }
  1841. }
  1842. FormTokenWithChars(Result, CurPtr, tok::unknown);
  1843. return true;
  1844. }
  1845. // Save prefix and move CurPtr past it
  1846. const char *Prefix = CurPtr;
  1847. CurPtr += PrefixLen + 1; // skip over prefix and '('
  1848. while (true) {
  1849. char C = *CurPtr++;
  1850. if (C == ')') {
  1851. // Check for prefix match and closing quote.
  1852. if (strncmp(CurPtr, Prefix, PrefixLen) == 0 && CurPtr[PrefixLen] == '"') {
  1853. CurPtr += PrefixLen + 1; // skip over prefix and '"'
  1854. break;
  1855. }
  1856. } else if (C == 0 && CurPtr-1 == BufferEnd) { // End of file.
  1857. if (!isLexingRawMode())
  1858. Diag(BufferPtr, diag::err_unterminated_raw_string)
  1859. << StringRef(Prefix, PrefixLen);
  1860. FormTokenWithChars(Result, CurPtr-1, tok::unknown);
  1861. return true;
  1862. }
  1863. }
  1864. // If we are in C++11, lex the optional ud-suffix.
  1865. if (getLangOpts().CPlusPlus)
  1866. CurPtr = LexUDSuffix(Result, CurPtr, true);
  1867. // Update the location of token as well as BufferPtr.
  1868. const char *TokStart = BufferPtr;
  1869. FormTokenWithChars(Result, CurPtr, Kind);
  1870. Result.setLiteralData(TokStart);
  1871. return true;
  1872. }
  1873. /// LexAngledStringLiteral - Lex the remainder of an angled string literal,
  1874. /// after having lexed the '<' character. This is used for #include filenames.
  1875. bool Lexer::LexAngledStringLiteral(Token &Result, const char *CurPtr) {
  1876. // Does this string contain the \0 character?
  1877. const char *NulCharacter = nullptr;
  1878. const char *AfterLessPos = CurPtr;
  1879. char C = getAndAdvanceChar(CurPtr, Result);
  1880. while (C != '>') {
  1881. // Skip escaped characters. Escaped newlines will already be processed by
  1882. // getAndAdvanceChar.
  1883. if (C == '\\')
  1884. C = getAndAdvanceChar(CurPtr, Result);
  1885. if (isVerticalWhitespace(C) || // Newline.
  1886. (C == 0 && (CurPtr - 1 == BufferEnd))) { // End of file.
  1887. // If the filename is unterminated, then it must just be a lone <
  1888. // character. Return this as such.
  1889. FormTokenWithChars(Result, AfterLessPos, tok::less);
  1890. return true;
  1891. }
  1892. if (C == 0) {
  1893. if (isCodeCompletionPoint(CurPtr - 1)) {
  1894. codeCompleteIncludedFile(AfterLessPos, CurPtr - 1, /*IsAngled=*/true);
  1895. cutOffLexing();
  1896. FormTokenWithChars(Result, CurPtr - 1, tok::unknown);
  1897. return true;
  1898. }
  1899. NulCharacter = CurPtr-1;
  1900. }
  1901. C = getAndAdvanceChar(CurPtr, Result);
  1902. }
  1903. // If a nul character existed in the string, warn about it.
  1904. if (NulCharacter && !isLexingRawMode())
  1905. Diag(NulCharacter, diag::null_in_char_or_string) << 1;
  1906. // Update the location of token as well as BufferPtr.
  1907. const char *TokStart = BufferPtr;
  1908. FormTokenWithChars(Result, CurPtr, tok::header_name);
  1909. Result.setLiteralData(TokStart);
  1910. return true;
  1911. }
  1912. void Lexer::codeCompleteIncludedFile(const char *PathStart,
  1913. const char *CompletionPoint,
  1914. bool IsAngled) {
  1915. // Completion only applies to the filename, after the last slash.
  1916. StringRef PartialPath(PathStart, CompletionPoint - PathStart);
  1917. llvm::StringRef SlashChars = LangOpts.MSVCCompat ? "/\\" : "/";
  1918. auto Slash = PartialPath.find_last_of(SlashChars);
  1919. StringRef Dir =
  1920. (Slash == StringRef::npos) ? "" : PartialPath.take_front(Slash);
  1921. const char *StartOfFilename =
  1922. (Slash == StringRef::npos) ? PathStart : PathStart + Slash + 1;
  1923. // Code completion filter range is the filename only, up to completion point.
  1924. PP->setCodeCompletionIdentifierInfo(&PP->getIdentifierTable().get(
  1925. StringRef(StartOfFilename, CompletionPoint - StartOfFilename)));
  1926. // We should replace the characters up to the closing quote or closest slash,
  1927. // if any.
  1928. while (CompletionPoint < BufferEnd) {
  1929. char Next = *(CompletionPoint + 1);
  1930. if (Next == 0 || Next == '\r' || Next == '\n')
  1931. break;
  1932. ++CompletionPoint;
  1933. if (Next == (IsAngled ? '>' : '"'))
  1934. break;
  1935. if (llvm::is_contained(SlashChars, Next))
  1936. break;
  1937. }
  1938. PP->setCodeCompletionTokenRange(
  1939. FileLoc.getLocWithOffset(StartOfFilename - BufferStart),
  1940. FileLoc.getLocWithOffset(CompletionPoint - BufferStart));
  1941. PP->CodeCompleteIncludedFile(Dir, IsAngled);
  1942. }
  1943. /// LexCharConstant - Lex the remainder of a character constant, after having
  1944. /// lexed either ' or L' or u8' or u' or U'.
  1945. bool Lexer::LexCharConstant(Token &Result, const char *CurPtr,
  1946. tok::TokenKind Kind) {
  1947. // Does this character contain the \0 character?
  1948. const char *NulCharacter = nullptr;
  1949. if (!isLexingRawMode()) {
  1950. if (Kind == tok::utf16_char_constant || Kind == tok::utf32_char_constant)
  1951. Diag(BufferPtr, getLangOpts().CPlusPlus
  1952. ? diag::warn_cxx98_compat_unicode_literal
  1953. : diag::warn_c99_compat_unicode_literal);
  1954. else if (Kind == tok::utf8_char_constant)
  1955. Diag(BufferPtr, diag::warn_cxx14_compat_u8_character_literal);
  1956. }
  1957. char C = getAndAdvanceChar(CurPtr, Result);
  1958. if (C == '\'') {
  1959. if (!isLexingRawMode() && !LangOpts.AsmPreprocessor)
  1960. Diag(BufferPtr, diag::ext_empty_character);
  1961. FormTokenWithChars(Result, CurPtr, tok::unknown);
  1962. return true;
  1963. }
  1964. while (C != '\'') {
  1965. // Skip escaped characters.
  1966. if (C == '\\')
  1967. C = getAndAdvanceChar(CurPtr, Result);
  1968. if (C == '\n' || C == '\r' || // Newline.
  1969. (C == 0 && CurPtr-1 == BufferEnd)) { // End of file.
  1970. if (!isLexingRawMode() && !LangOpts.AsmPreprocessor)
  1971. Diag(BufferPtr, diag::ext_unterminated_char_or_string) << 0;
  1972. FormTokenWithChars(Result, CurPtr-1, tok::unknown);
  1973. return true;
  1974. }
  1975. if (C == 0) {
  1976. if (isCodeCompletionPoint(CurPtr-1)) {
  1977. PP->CodeCompleteNaturalLanguage();
  1978. FormTokenWithChars(Result, CurPtr-1, tok::unknown);
  1979. cutOffLexing();
  1980. return true;
  1981. }
  1982. NulCharacter = CurPtr-1;
  1983. }
  1984. C = getAndAdvanceChar(CurPtr, Result);
  1985. }
  1986. // If we are in C++11, lex the optional ud-suffix.
  1987. if (getLangOpts().CPlusPlus)
  1988. CurPtr = LexUDSuffix(Result, CurPtr, false);
  1989. // If a nul character existed in the character, warn about it.
  1990. if (NulCharacter && !isLexingRawMode())
  1991. Diag(NulCharacter, diag::null_in_char_or_string) << 0;
  1992. // Update the location of token as well as BufferPtr.
  1993. const char *TokStart = BufferPtr;
  1994. FormTokenWithChars(Result, CurPtr, Kind);
  1995. Result.setLiteralData(TokStart);
  1996. return true;
  1997. }
  1998. /// SkipWhitespace - Efficiently skip over a series of whitespace characters.
  1999. /// Update BufferPtr to point to the next non-whitespace character and return.
  2000. ///
  2001. /// This method forms a token and returns true if KeepWhitespaceMode is enabled.
  2002. bool Lexer::SkipWhitespace(Token &Result, const char *CurPtr,
  2003. bool &TokAtPhysicalStartOfLine) {
  2004. // Whitespace - Skip it, then return the token after the whitespace.
  2005. bool SawNewline = isVerticalWhitespace(CurPtr[-1]);
  2006. unsigned char Char = *CurPtr;
  2007. const char *lastNewLine = nullptr;
  2008. auto setLastNewLine = [&](const char *Ptr) {
  2009. lastNewLine = Ptr;
  2010. if (!NewLinePtr)
  2011. NewLinePtr = Ptr;
  2012. };
  2013. if (SawNewline)
  2014. setLastNewLine(CurPtr - 1);
  2015. // Skip consecutive spaces efficiently.
  2016. while (true) {
  2017. // Skip horizontal whitespace very aggressively.
  2018. while (isHorizontalWhitespace(Char))
  2019. Char = *++CurPtr;
  2020. // Otherwise if we have something other than whitespace, we're done.
  2021. if (!isVerticalWhitespace(Char))
  2022. break;
  2023. if (ParsingPreprocessorDirective) {
  2024. // End of preprocessor directive line, let LexTokenInternal handle this.
  2025. BufferPtr = CurPtr;
  2026. return false;
  2027. }
  2028. // OK, but handle newline.
  2029. if (*CurPtr == '\n')
  2030. setLastNewLine(CurPtr);
  2031. SawNewline = true;
  2032. Char = *++CurPtr;
  2033. }
  2034. // If the client wants us to return whitespace, return it now.
  2035. if (isKeepWhitespaceMode()) {
  2036. FormTokenWithChars(Result, CurPtr, tok::unknown);
  2037. if (SawNewline) {
  2038. IsAtStartOfLine = true;
  2039. IsAtPhysicalStartOfLine = true;
  2040. }
  2041. // FIXME: The next token will not have LeadingSpace set.
  2042. return true;
  2043. }
  2044. // If this isn't immediately after a newline, there is leading space.
  2045. char PrevChar = CurPtr[-1];
  2046. bool HasLeadingSpace = !isVerticalWhitespace(PrevChar);
  2047. Result.setFlagValue(Token::LeadingSpace, HasLeadingSpace);
  2048. if (SawNewline) {
  2049. Result.setFlag(Token::StartOfLine);
  2050. TokAtPhysicalStartOfLine = true;
  2051. if (NewLinePtr && lastNewLine && NewLinePtr != lastNewLine && PP) {
  2052. if (auto *Handler = PP->getEmptylineHandler())
  2053. Handler->HandleEmptyline(SourceRange(getSourceLocation(NewLinePtr + 1),
  2054. getSourceLocation(lastNewLine)));
  2055. }
  2056. }
  2057. BufferPtr = CurPtr;
  2058. return false;
  2059. }
  2060. /// We have just read the // characters from input. Skip until we find the
  2061. /// newline character that terminates the comment. Then update BufferPtr and
  2062. /// return.
  2063. ///
  2064. /// If we're in KeepCommentMode or any CommentHandler has inserted
  2065. /// some tokens, this will store the first token and return true.
  2066. bool Lexer::SkipLineComment(Token &Result, const char *CurPtr,
  2067. bool &TokAtPhysicalStartOfLine) {
  2068. // If Line comments aren't explicitly enabled for this language, emit an
  2069. // extension warning.
  2070. if (!LangOpts.LineComment) {
  2071. if (!isLexingRawMode()) // There's no PP in raw mode, so can't emit diags.
  2072. Diag(BufferPtr, diag::ext_line_comment);
  2073. // Mark them enabled so we only emit one warning for this translation
  2074. // unit.
  2075. LangOpts.LineComment = true;
  2076. }
  2077. // Scan over the body of the comment. The common case, when scanning, is that
  2078. // the comment contains normal ascii characters with nothing interesting in
  2079. // them. As such, optimize for this case with the inner loop.
  2080. //
  2081. // This loop terminates with CurPtr pointing at the newline (or end of buffer)
  2082. // character that ends the line comment.
  2083. char C;
  2084. while (true) {
  2085. C = *CurPtr;
  2086. // Skip over characters in the fast loop.
  2087. while (C != 0 && // Potentially EOF.
  2088. C != '\n' && C != '\r') // Newline or DOS-style newline.
  2089. C = *++CurPtr;
  2090. const char *NextLine = CurPtr;
  2091. if (C != 0) {
  2092. // We found a newline, see if it's escaped.
  2093. const char *EscapePtr = CurPtr-1;
  2094. bool HasSpace = false;
  2095. while (isHorizontalWhitespace(*EscapePtr)) { // Skip whitespace.
  2096. --EscapePtr;
  2097. HasSpace = true;
  2098. }
  2099. if (*EscapePtr == '\\')
  2100. // Escaped newline.
  2101. CurPtr = EscapePtr;
  2102. else if (EscapePtr[0] == '/' && EscapePtr[-1] == '?' &&
  2103. EscapePtr[-2] == '?' && LangOpts.Trigraphs)
  2104. // Trigraph-escaped newline.
  2105. CurPtr = EscapePtr-2;
  2106. else
  2107. break; // This is a newline, we're done.
  2108. // If there was space between the backslash and newline, warn about it.
  2109. if (HasSpace && !isLexingRawMode())
  2110. Diag(EscapePtr, diag::backslash_newline_space);
  2111. }
  2112. // Otherwise, this is a hard case. Fall back on getAndAdvanceChar to
  2113. // properly decode the character. Read it in raw mode to avoid emitting
  2114. // diagnostics about things like trigraphs. If we see an escaped newline,
  2115. // we'll handle it below.
  2116. const char *OldPtr = CurPtr;
  2117. bool OldRawMode = isLexingRawMode();
  2118. LexingRawMode = true;
  2119. C = getAndAdvanceChar(CurPtr, Result);
  2120. LexingRawMode = OldRawMode;
  2121. // If we only read only one character, then no special handling is needed.
  2122. // We're done and can skip forward to the newline.
  2123. if (C != 0 && CurPtr == OldPtr+1) {
  2124. CurPtr = NextLine;
  2125. break;
  2126. }
  2127. // If we read multiple characters, and one of those characters was a \r or
  2128. // \n, then we had an escaped newline within the comment. Emit diagnostic
  2129. // unless the next line is also a // comment.
  2130. if (CurPtr != OldPtr + 1 && C != '/' &&
  2131. (CurPtr == BufferEnd + 1 || CurPtr[0] != '/')) {
  2132. for (; OldPtr != CurPtr; ++OldPtr)
  2133. if (OldPtr[0] == '\n' || OldPtr[0] == '\r') {
  2134. // Okay, we found a // comment that ends in a newline, if the next
  2135. // line is also a // comment, but has spaces, don't emit a diagnostic.
  2136. if (isWhitespace(C)) {
  2137. const char *ForwardPtr = CurPtr;
  2138. while (isWhitespace(*ForwardPtr)) // Skip whitespace.
  2139. ++ForwardPtr;
  2140. if (ForwardPtr[0] == '/' && ForwardPtr[1] == '/')
  2141. break;
  2142. }
  2143. if (!isLexingRawMode())
  2144. Diag(OldPtr-1, diag::ext_multi_line_line_comment);
  2145. break;
  2146. }
  2147. }
  2148. if (C == '\r' || C == '\n' || CurPtr == BufferEnd + 1) {
  2149. --CurPtr;
  2150. break;
  2151. }
  2152. if (C == '\0' && isCodeCompletionPoint(CurPtr-1)) {
  2153. PP->CodeCompleteNaturalLanguage();
  2154. cutOffLexing();
  2155. return false;
  2156. }
  2157. }
  2158. // Found but did not consume the newline. Notify comment handlers about the
  2159. // comment unless we're in a #if 0 block.
  2160. if (PP && !isLexingRawMode() &&
  2161. PP->HandleComment(Result, SourceRange(getSourceLocation(BufferPtr),
  2162. getSourceLocation(CurPtr)))) {
  2163. BufferPtr = CurPtr;
  2164. return true; // A token has to be returned.
  2165. }
  2166. // If we are returning comments as tokens, return this comment as a token.
  2167. if (inKeepCommentMode())
  2168. return SaveLineComment(Result, CurPtr);
  2169. // If we are inside a preprocessor directive and we see the end of line,
  2170. // return immediately, so that the lexer can return this as an EOD token.
  2171. if (ParsingPreprocessorDirective || CurPtr == BufferEnd) {
  2172. BufferPtr = CurPtr;
  2173. return false;
  2174. }
  2175. // Otherwise, eat the \n character. We don't care if this is a \n\r or
  2176. // \r\n sequence. This is an efficiency hack (because we know the \n can't
  2177. // contribute to another token), it isn't needed for correctness. Note that
  2178. // this is ok even in KeepWhitespaceMode, because we would have returned the
  2179. /// comment above in that mode.
  2180. NewLinePtr = CurPtr++;
  2181. // The next returned token is at the start of the line.
  2182. Result.setFlag(Token::StartOfLine);
  2183. TokAtPhysicalStartOfLine = true;
  2184. // No leading whitespace seen so far.
  2185. Result.clearFlag(Token::LeadingSpace);
  2186. BufferPtr = CurPtr;
  2187. return false;
  2188. }
  2189. /// If in save-comment mode, package up this Line comment in an appropriate
  2190. /// way and return it.
  2191. bool Lexer::SaveLineComment(Token &Result, const char *CurPtr) {
  2192. // If we're not in a preprocessor directive, just return the // comment
  2193. // directly.
  2194. FormTokenWithChars(Result, CurPtr, tok::comment);
  2195. if (!ParsingPreprocessorDirective || LexingRawMode)
  2196. return true;
  2197. // If this Line-style comment is in a macro definition, transmogrify it into
  2198. // a C-style block comment.
  2199. bool Invalid = false;
  2200. std::string Spelling = PP->getSpelling(Result, &Invalid);
  2201. if (Invalid)
  2202. return true;
  2203. assert(Spelling[0] == '/' && Spelling[1] == '/' && "Not line comment?");
  2204. Spelling[1] = '*'; // Change prefix to "/*".
  2205. Spelling += "*/"; // add suffix.
  2206. Result.setKind(tok::comment);
  2207. PP->CreateString(Spelling, Result,
  2208. Result.getLocation(), Result.getLocation());
  2209. return true;
  2210. }
  2211. /// isBlockCommentEndOfEscapedNewLine - Return true if the specified newline
  2212. /// character (either \\n or \\r) is part of an escaped newline sequence. Issue
  2213. /// a diagnostic if so. We know that the newline is inside of a block comment.
  2214. static bool isEndOfBlockCommentWithEscapedNewLine(const char *CurPtr,
  2215. Lexer *L) {
  2216. assert(CurPtr[0] == '\n' || CurPtr[0] == '\r');
  2217. // Position of the first trigraph in the ending sequence.
  2218. const char *TrigraphPos = nullptr;
  2219. // Position of the first whitespace after a '\' in the ending sequence.
  2220. const char *SpacePos = nullptr;
  2221. while (true) {
  2222. // Back up off the newline.
  2223. --CurPtr;
  2224. // If this is a two-character newline sequence, skip the other character.
  2225. if (CurPtr[0] == '\n' || CurPtr[0] == '\r') {
  2226. // \n\n or \r\r -> not escaped newline.
  2227. if (CurPtr[0] == CurPtr[1])
  2228. return false;
  2229. // \n\r or \r\n -> skip the newline.
  2230. --CurPtr;
  2231. }
  2232. // If we have horizontal whitespace, skip over it. We allow whitespace
  2233. // between the slash and newline.
  2234. while (isHorizontalWhitespace(*CurPtr) || *CurPtr == 0) {
  2235. SpacePos = CurPtr;
  2236. --CurPtr;
  2237. }
  2238. // If we have a slash, this is an escaped newline.
  2239. if (*CurPtr == '\\') {
  2240. --CurPtr;
  2241. } else if (CurPtr[0] == '/' && CurPtr[-1] == '?' && CurPtr[-2] == '?') {
  2242. // This is a trigraph encoding of a slash.
  2243. TrigraphPos = CurPtr - 2;
  2244. CurPtr -= 3;
  2245. } else {
  2246. return false;
  2247. }
  2248. // If the character preceding the escaped newline is a '*', then after line
  2249. // splicing we have a '*/' ending the comment.
  2250. if (*CurPtr == '*')
  2251. break;
  2252. if (*CurPtr != '\n' && *CurPtr != '\r')
  2253. return false;
  2254. }
  2255. if (TrigraphPos) {
  2256. // If no trigraphs are enabled, warn that we ignored this trigraph and
  2257. // ignore this * character.
  2258. if (!L->getLangOpts().Trigraphs) {
  2259. if (!L->isLexingRawMode())
  2260. L->Diag(TrigraphPos, diag::trigraph_ignored_block_comment);
  2261. return false;
  2262. }
  2263. if (!L->isLexingRawMode())
  2264. L->Diag(TrigraphPos, diag::trigraph_ends_block_comment);
  2265. }
  2266. // Warn about having an escaped newline between the */ characters.
  2267. if (!L->isLexingRawMode())
  2268. L->Diag(CurPtr + 1, diag::escaped_newline_block_comment_end);
  2269. // If there was space between the backslash and newline, warn about it.
  2270. if (SpacePos && !L->isLexingRawMode())
  2271. L->Diag(SpacePos, diag::backslash_newline_space);
  2272. return true;
  2273. }
  2274. #ifdef __SSE2__
  2275. #include <emmintrin.h>
  2276. #elif __ALTIVEC__
  2277. #include <altivec.h>
  2278. #undef bool
  2279. #endif
  2280. /// We have just read from input the / and * characters that started a comment.
  2281. /// Read until we find the * and / characters that terminate the comment.
  2282. /// Note that we don't bother decoding trigraphs or escaped newlines in block
  2283. /// comments, because they cannot cause the comment to end. The only thing
  2284. /// that can happen is the comment could end with an escaped newline between
  2285. /// the terminating * and /.
  2286. ///
  2287. /// If we're in KeepCommentMode or any CommentHandler has inserted
  2288. /// some tokens, this will store the first token and return true.
  2289. bool Lexer::SkipBlockComment(Token &Result, const char *CurPtr,
  2290. bool &TokAtPhysicalStartOfLine) {
  2291. // Scan one character past where we should, looking for a '/' character. Once
  2292. // we find it, check to see if it was preceded by a *. This common
  2293. // optimization helps people who like to put a lot of * characters in their
  2294. // comments.
  2295. // The first character we get with newlines and trigraphs skipped to handle
  2296. // the degenerate /*/ case below correctly if the * has an escaped newline
  2297. // after it.
  2298. unsigned CharSize;
  2299. unsigned char C = getCharAndSize(CurPtr, CharSize);
  2300. CurPtr += CharSize;
  2301. if (C == 0 && CurPtr == BufferEnd+1) {
  2302. if (!isLexingRawMode())
  2303. Diag(BufferPtr, diag::err_unterminated_block_comment);
  2304. --CurPtr;
  2305. // KeepWhitespaceMode should return this broken comment as a token. Since
  2306. // it isn't a well formed comment, just return it as an 'unknown' token.
  2307. if (isKeepWhitespaceMode()) {
  2308. FormTokenWithChars(Result, CurPtr, tok::unknown);
  2309. return true;
  2310. }
  2311. BufferPtr = CurPtr;
  2312. return false;
  2313. }
  2314. // Check to see if the first character after the '/*' is another /. If so,
  2315. // then this slash does not end the block comment, it is part of it.
  2316. if (C == '/')
  2317. C = *CurPtr++;
  2318. while (true) {
  2319. // Skip over all non-interesting characters until we find end of buffer or a
  2320. // (probably ending) '/' character.
  2321. if (CurPtr + 24 < BufferEnd &&
  2322. // If there is a code-completion point avoid the fast scan because it
  2323. // doesn't check for '\0'.
  2324. !(PP && PP->getCodeCompletionFileLoc() == FileLoc)) {
  2325. // While not aligned to a 16-byte boundary.
  2326. while (C != '/' && ((intptr_t)CurPtr & 0x0F) != 0)
  2327. C = *CurPtr++;
  2328. if (C == '/') goto FoundSlash;
  2329. #ifdef __SSE2__
  2330. __m128i Slashes = _mm_set1_epi8('/');
  2331. while (CurPtr+16 <= BufferEnd) {
  2332. int cmp = _mm_movemask_epi8(_mm_cmpeq_epi8(*(const __m128i*)CurPtr,
  2333. Slashes));
  2334. if (cmp != 0) {
  2335. // Adjust the pointer to point directly after the first slash. It's
  2336. // not necessary to set C here, it will be overwritten at the end of
  2337. // the outer loop.
  2338. CurPtr += llvm::countTrailingZeros<unsigned>(cmp) + 1;
  2339. goto FoundSlash;
  2340. }
  2341. CurPtr += 16;
  2342. }
  2343. #elif __ALTIVEC__
  2344. __vector unsigned char Slashes = {
  2345. '/', '/', '/', '/', '/', '/', '/', '/',
  2346. '/', '/', '/', '/', '/', '/', '/', '/'
  2347. };
  2348. while (CurPtr + 16 <= BufferEnd &&
  2349. !vec_any_eq(*(const __vector unsigned char *)CurPtr, Slashes))
  2350. CurPtr += 16;
  2351. #else
  2352. // Scan for '/' quickly. Many block comments are very large.
  2353. while (CurPtr[0] != '/' &&
  2354. CurPtr[1] != '/' &&
  2355. CurPtr[2] != '/' &&
  2356. CurPtr[3] != '/' &&
  2357. CurPtr+4 < BufferEnd) {
  2358. CurPtr += 4;
  2359. }
  2360. #endif
  2361. // It has to be one of the bytes scanned, increment to it and read one.
  2362. C = *CurPtr++;
  2363. }
  2364. // Loop to scan the remainder.
  2365. while (C != '/' && C != '\0')
  2366. C = *CurPtr++;
  2367. if (C == '/') {
  2368. FoundSlash:
  2369. if (CurPtr[-2] == '*') // We found the final */. We're done!
  2370. break;
  2371. if ((CurPtr[-2] == '\n' || CurPtr[-2] == '\r')) {
  2372. if (isEndOfBlockCommentWithEscapedNewLine(CurPtr-2, this)) {
  2373. // We found the final */, though it had an escaped newline between the
  2374. // * and /. We're done!
  2375. break;
  2376. }
  2377. }
  2378. if (CurPtr[0] == '*' && CurPtr[1] != '/') {
  2379. // If this is a /* inside of the comment, emit a warning. Don't do this
  2380. // if this is a /*/, which will end the comment. This misses cases with
  2381. // embedded escaped newlines, but oh well.
  2382. if (!isLexingRawMode())
  2383. Diag(CurPtr-1, diag::warn_nested_block_comment);
  2384. }
  2385. } else if (C == 0 && CurPtr == BufferEnd+1) {
  2386. if (!isLexingRawMode())
  2387. Diag(BufferPtr, diag::err_unterminated_block_comment);
  2388. // Note: the user probably forgot a */. We could continue immediately
  2389. // after the /*, but this would involve lexing a lot of what really is the
  2390. // comment, which surely would confuse the parser.
  2391. --CurPtr;
  2392. // KeepWhitespaceMode should return this broken comment as a token. Since
  2393. // it isn't a well formed comment, just return it as an 'unknown' token.
  2394. if (isKeepWhitespaceMode()) {
  2395. FormTokenWithChars(Result, CurPtr, tok::unknown);
  2396. return true;
  2397. }
  2398. BufferPtr = CurPtr;
  2399. return false;
  2400. } else if (C == '\0' && isCodeCompletionPoint(CurPtr-1)) {
  2401. PP->CodeCompleteNaturalLanguage();
  2402. cutOffLexing();
  2403. return false;
  2404. }
  2405. C = *CurPtr++;
  2406. }
  2407. // Notify comment handlers about the comment unless we're in a #if 0 block.
  2408. if (PP && !isLexingRawMode() &&
  2409. PP->HandleComment(Result, SourceRange(getSourceLocation(BufferPtr),
  2410. getSourceLocation(CurPtr)))) {
  2411. BufferPtr = CurPtr;
  2412. return true; // A token has to be returned.
  2413. }
  2414. // If we are returning comments as tokens, return this comment as a token.
  2415. if (inKeepCommentMode()) {
  2416. FormTokenWithChars(Result, CurPtr, tok::comment);
  2417. return true;
  2418. }
  2419. // It is common for the tokens immediately after a /**/ comment to be
  2420. // whitespace. Instead of going through the big switch, handle it
  2421. // efficiently now. This is safe even in KeepWhitespaceMode because we would
  2422. // have already returned above with the comment as a token.
  2423. if (isHorizontalWhitespace(*CurPtr)) {
  2424. SkipWhitespace(Result, CurPtr+1, TokAtPhysicalStartOfLine);
  2425. return false;
  2426. }
  2427. // Otherwise, just return so that the next character will be lexed as a token.
  2428. BufferPtr = CurPtr;
  2429. Result.setFlag(Token::LeadingSpace);
  2430. return false;
  2431. }
  2432. //===----------------------------------------------------------------------===//
  2433. // Primary Lexing Entry Points
  2434. //===----------------------------------------------------------------------===//
  2435. /// ReadToEndOfLine - Read the rest of the current preprocessor line as an
  2436. /// uninterpreted string. This switches the lexer out of directive mode.
  2437. void Lexer::ReadToEndOfLine(SmallVectorImpl<char> *Result) {
  2438. assert(ParsingPreprocessorDirective && ParsingFilename == false &&
  2439. "Must be in a preprocessing directive!");
  2440. Token Tmp;
  2441. Tmp.startToken();
  2442. // CurPtr - Cache BufferPtr in an automatic variable.
  2443. const char *CurPtr = BufferPtr;
  2444. while (true) {
  2445. char Char = getAndAdvanceChar(CurPtr, Tmp);
  2446. switch (Char) {
  2447. default:
  2448. if (Result)
  2449. Result->push_back(Char);
  2450. break;
  2451. case 0: // Null.
  2452. // Found end of file?
  2453. if (CurPtr-1 != BufferEnd) {
  2454. if (isCodeCompletionPoint(CurPtr-1)) {
  2455. PP->CodeCompleteNaturalLanguage();
  2456. cutOffLexing();
  2457. return;
  2458. }
  2459. // Nope, normal character, continue.
  2460. if (Result)
  2461. Result->push_back(Char);
  2462. break;
  2463. }
  2464. // FALL THROUGH.
  2465. LLVM_FALLTHROUGH;
  2466. case '\r':
  2467. case '\n':
  2468. // Okay, we found the end of the line. First, back up past the \0, \r, \n.
  2469. assert(CurPtr[-1] == Char && "Trigraphs for newline?");
  2470. BufferPtr = CurPtr-1;
  2471. // Next, lex the character, which should handle the EOD transition.
  2472. Lex(Tmp);
  2473. if (Tmp.is(tok::code_completion)) {
  2474. if (PP)
  2475. PP->CodeCompleteNaturalLanguage();
  2476. Lex(Tmp);
  2477. }
  2478. assert(Tmp.is(tok::eod) && "Unexpected token!");
  2479. // Finally, we're done;
  2480. return;
  2481. }
  2482. }
  2483. }
  2484. /// LexEndOfFile - CurPtr points to the end of this file. Handle this
  2485. /// condition, reporting diagnostics and handling other edge cases as required.
  2486. /// This returns true if Result contains a token, false if PP.Lex should be
  2487. /// called again.
  2488. bool Lexer::LexEndOfFile(Token &Result, const char *CurPtr) {
  2489. // If we hit the end of the file while parsing a preprocessor directive,
  2490. // end the preprocessor directive first. The next token returned will
  2491. // then be the end of file.
  2492. if (ParsingPreprocessorDirective) {
  2493. // Done parsing the "line".
  2494. ParsingPreprocessorDirective = false;
  2495. // Update the location of token as well as BufferPtr.
  2496. FormTokenWithChars(Result, CurPtr, tok::eod);
  2497. // Restore comment saving mode, in case it was disabled for directive.
  2498. if (PP)
  2499. resetExtendedTokenMode();
  2500. return true; // Have a token.
  2501. }
  2502. // If we are in raw mode, return this event as an EOF token. Let the caller
  2503. // that put us in raw mode handle the event.
  2504. if (isLexingRawMode()) {
  2505. Result.startToken();
  2506. BufferPtr = BufferEnd;
  2507. FormTokenWithChars(Result, BufferEnd, tok::eof);
  2508. return true;
  2509. }
  2510. if (PP->isRecordingPreamble() && PP->isInPrimaryFile()) {
  2511. PP->setRecordedPreambleConditionalStack(ConditionalStack);
  2512. // If the preamble cuts off the end of a header guard, consider it guarded.
  2513. // The guard is valid for the preamble content itself, and for tools the
  2514. // most useful answer is "yes, this file has a header guard".
  2515. if (!ConditionalStack.empty())
  2516. MIOpt.ExitTopLevelConditional();
  2517. ConditionalStack.clear();
  2518. }
  2519. // Issue diagnostics for unterminated #if and missing newline.
  2520. // If we are in a #if directive, emit an error.
  2521. while (!ConditionalStack.empty()) {
  2522. if (PP->getCodeCompletionFileLoc() != FileLoc)
  2523. PP->Diag(ConditionalStack.back().IfLoc,
  2524. diag::err_pp_unterminated_conditional);
  2525. ConditionalStack.pop_back();
  2526. }
  2527. SourceLocation EndLoc = getSourceLocation(BufferEnd);
  2528. // C99 5.1.1.2p2: If the file is non-empty and didn't end in a newline, issue
  2529. // a pedwarn.
  2530. if (CurPtr != BufferStart && (CurPtr[-1] != '\n' && CurPtr[-1] != '\r')) {
  2531. DiagnosticsEngine &Diags = PP->getDiagnostics();
  2532. unsigned DiagID;
  2533. if (LangOpts.CPlusPlus11) {
  2534. // C++11 [lex.phases] 2.2 p2
  2535. // Prefer the C++98 pedantic compatibility warning over the generic,
  2536. // non-extension, user-requested "missing newline at EOF" warning.
  2537. if (!Diags.isIgnored(diag::warn_cxx98_compat_no_newline_eof, EndLoc)) {
  2538. DiagID = diag::warn_cxx98_compat_no_newline_eof;
  2539. } else {
  2540. DiagID = diag::warn_no_newline_eof;
  2541. }
  2542. } else {
  2543. DiagID = diag::ext_no_newline_eof;
  2544. }
  2545. Diag(BufferEnd, DiagID)
  2546. << FixItHint::CreateInsertion(EndLoc, "\n");
  2547. }
  2548. BufferPtr = CurPtr;
  2549. // Finally, let the preprocessor handle this.
  2550. return PP->HandleEndOfFile(Result, EndLoc, isPragmaLexer());
  2551. }
  2552. /// isNextPPTokenLParen - Return 1 if the next unexpanded token lexed from
  2553. /// the specified lexer will return a tok::l_paren token, 0 if it is something
  2554. /// else and 2 if there are no more tokens in the buffer controlled by the
  2555. /// lexer.
  2556. unsigned Lexer::isNextPPTokenLParen() {
  2557. assert(!LexingRawMode && "How can we expand a macro from a skipping buffer?");
  2558. // Switch to 'skipping' mode. This will ensure that we can lex a token
  2559. // without emitting diagnostics, disables macro expansion, and will cause EOF
  2560. // to return an EOF token instead of popping the include stack.
  2561. LexingRawMode = true;
  2562. // Save state that can be changed while lexing so that we can restore it.
  2563. const char *TmpBufferPtr = BufferPtr;
  2564. bool inPPDirectiveMode = ParsingPreprocessorDirective;
  2565. bool atStartOfLine = IsAtStartOfLine;
  2566. bool atPhysicalStartOfLine = IsAtPhysicalStartOfLine;
  2567. bool leadingSpace = HasLeadingSpace;
  2568. Token Tok;
  2569. Lex(Tok);
  2570. // Restore state that may have changed.
  2571. BufferPtr = TmpBufferPtr;
  2572. ParsingPreprocessorDirective = inPPDirectiveMode;
  2573. HasLeadingSpace = leadingSpace;
  2574. IsAtStartOfLine = atStartOfLine;
  2575. IsAtPhysicalStartOfLine = atPhysicalStartOfLine;
  2576. // Restore the lexer back to non-skipping mode.
  2577. LexingRawMode = false;
  2578. if (Tok.is(tok::eof))
  2579. return 2;
  2580. return Tok.is(tok::l_paren);
  2581. }
  2582. /// Find the end of a version control conflict marker.
  2583. static const char *FindConflictEnd(const char *CurPtr, const char *BufferEnd,
  2584. ConflictMarkerKind CMK) {
  2585. const char *Terminator = CMK == CMK_Perforce ? "<<<<\n" : ">>>>>>>";
  2586. size_t TermLen = CMK == CMK_Perforce ? 5 : 7;
  2587. auto RestOfBuffer = StringRef(CurPtr, BufferEnd - CurPtr).substr(TermLen);
  2588. size_t Pos = RestOfBuffer.find(Terminator);
  2589. while (Pos != StringRef::npos) {
  2590. // Must occur at start of line.
  2591. if (Pos == 0 ||
  2592. (RestOfBuffer[Pos - 1] != '\r' && RestOfBuffer[Pos - 1] != '\n')) {
  2593. RestOfBuffer = RestOfBuffer.substr(Pos+TermLen);
  2594. Pos = RestOfBuffer.find(Terminator);
  2595. continue;
  2596. }
  2597. return RestOfBuffer.data()+Pos;
  2598. }
  2599. return nullptr;
  2600. }
  2601. /// IsStartOfConflictMarker - If the specified pointer is the start of a version
  2602. /// control conflict marker like '<<<<<<<', recognize it as such, emit an error
  2603. /// and recover nicely. This returns true if it is a conflict marker and false
  2604. /// if not.
  2605. bool Lexer::IsStartOfConflictMarker(const char *CurPtr) {
  2606. // Only a conflict marker if it starts at the beginning of a line.
  2607. if (CurPtr != BufferStart &&
  2608. CurPtr[-1] != '\n' && CurPtr[-1] != '\r')
  2609. return false;
  2610. // Check to see if we have <<<<<<< or >>>>.
  2611. if (!StringRef(CurPtr, BufferEnd - CurPtr).startswith("<<<<<<<") &&
  2612. !StringRef(CurPtr, BufferEnd - CurPtr).startswith(">>>> "))
  2613. return false;
  2614. // If we have a situation where we don't care about conflict markers, ignore
  2615. // it.
  2616. if (CurrentConflictMarkerState || isLexingRawMode())
  2617. return false;
  2618. ConflictMarkerKind Kind = *CurPtr == '<' ? CMK_Normal : CMK_Perforce;
  2619. // Check to see if there is an ending marker somewhere in the buffer at the
  2620. // start of a line to terminate this conflict marker.
  2621. if (FindConflictEnd(CurPtr, BufferEnd, Kind)) {
  2622. // We found a match. We are really in a conflict marker.
  2623. // Diagnose this, and ignore to the end of line.
  2624. Diag(CurPtr, diag::err_conflict_marker);
  2625. CurrentConflictMarkerState = Kind;
  2626. // Skip ahead to the end of line. We know this exists because the
  2627. // end-of-conflict marker starts with \r or \n.
  2628. while (*CurPtr != '\r' && *CurPtr != '\n') {
  2629. assert(CurPtr != BufferEnd && "Didn't find end of line");
  2630. ++CurPtr;
  2631. }
  2632. BufferPtr = CurPtr;
  2633. return true;
  2634. }
  2635. // No end of conflict marker found.
  2636. return false;
  2637. }
  2638. /// HandleEndOfConflictMarker - If this is a '====' or '||||' or '>>>>', or if
  2639. /// it is '<<<<' and the conflict marker started with a '>>>>' marker, then it
  2640. /// is the end of a conflict marker. Handle it by ignoring up until the end of
  2641. /// the line. This returns true if it is a conflict marker and false if not.
  2642. bool Lexer::HandleEndOfConflictMarker(const char *CurPtr) {
  2643. // Only a conflict marker if it starts at the beginning of a line.
  2644. if (CurPtr != BufferStart &&
  2645. CurPtr[-1] != '\n' && CurPtr[-1] != '\r')
  2646. return false;
  2647. // If we have a situation where we don't care about conflict markers, ignore
  2648. // it.
  2649. if (!CurrentConflictMarkerState || isLexingRawMode())
  2650. return false;
  2651. // Check to see if we have the marker (4 characters in a row).
  2652. for (unsigned i = 1; i != 4; ++i)
  2653. if (CurPtr[i] != CurPtr[0])
  2654. return false;
  2655. // If we do have it, search for the end of the conflict marker. This could
  2656. // fail if it got skipped with a '#if 0' or something. Note that CurPtr might
  2657. // be the end of conflict marker.
  2658. if (const char *End = FindConflictEnd(CurPtr, BufferEnd,
  2659. CurrentConflictMarkerState)) {
  2660. CurPtr = End;
  2661. // Skip ahead to the end of line.
  2662. while (CurPtr != BufferEnd && *CurPtr != '\r' && *CurPtr != '\n')
  2663. ++CurPtr;
  2664. BufferPtr = CurPtr;
  2665. // No longer in the conflict marker.
  2666. CurrentConflictMarkerState = CMK_None;
  2667. return true;
  2668. }
  2669. return false;
  2670. }
  2671. static const char *findPlaceholderEnd(const char *CurPtr,
  2672. const char *BufferEnd) {
  2673. if (CurPtr == BufferEnd)
  2674. return nullptr;
  2675. BufferEnd -= 1; // Scan until the second last character.
  2676. for (; CurPtr != BufferEnd; ++CurPtr) {
  2677. if (CurPtr[0] == '#' && CurPtr[1] == '>')
  2678. return CurPtr + 2;
  2679. }
  2680. return nullptr;
  2681. }
  2682. bool Lexer::lexEditorPlaceholder(Token &Result, const char *CurPtr) {
  2683. assert(CurPtr[-1] == '<' && CurPtr[0] == '#' && "Not a placeholder!");
  2684. if (!PP || !PP->getPreprocessorOpts().LexEditorPlaceholders || LexingRawMode)
  2685. return false;
  2686. const char *End = findPlaceholderEnd(CurPtr + 1, BufferEnd);
  2687. if (!End)
  2688. return false;
  2689. const char *Start = CurPtr - 1;
  2690. if (!LangOpts.AllowEditorPlaceholders)
  2691. Diag(Start, diag::err_placeholder_in_source);
  2692. Result.startToken();
  2693. FormTokenWithChars(Result, End, tok::raw_identifier);
  2694. Result.setRawIdentifierData(Start);
  2695. PP->LookUpIdentifierInfo(Result);
  2696. Result.setFlag(Token::IsEditorPlaceholder);
  2697. BufferPtr = End;
  2698. return true;
  2699. }
  2700. bool Lexer::isCodeCompletionPoint(const char *CurPtr) const {
  2701. if (PP && PP->isCodeCompletionEnabled()) {
  2702. SourceLocation Loc = FileLoc.getLocWithOffset(CurPtr-BufferStart);
  2703. return Loc == PP->getCodeCompletionLoc();
  2704. }
  2705. return false;
  2706. }
  2707. uint32_t Lexer::tryReadUCN(const char *&StartPtr, const char *SlashLoc,
  2708. Token *Result) {
  2709. unsigned CharSize;
  2710. char Kind = getCharAndSize(StartPtr, CharSize);
  2711. bool Delimited = false;
  2712. bool FoundEndDelimiter = false;
  2713. unsigned Count = 0;
  2714. bool Diagnose = Result && !isLexingRawMode();
  2715. unsigned NumHexDigits;
  2716. if (Kind == 'u')
  2717. NumHexDigits = 4;
  2718. else if (Kind == 'U')
  2719. NumHexDigits = 8;
  2720. else
  2721. return 0;
  2722. if (!LangOpts.CPlusPlus && !LangOpts.C99) {
  2723. if (Diagnose)
  2724. Diag(SlashLoc, diag::warn_ucn_not_valid_in_c89);
  2725. return 0;
  2726. }
  2727. const char *CurPtr = StartPtr + CharSize;
  2728. const char *KindLoc = &CurPtr[-1];
  2729. uint32_t CodePoint = 0;
  2730. while (Count != NumHexDigits || Delimited) {
  2731. char C = getCharAndSize(CurPtr, CharSize);
  2732. if (!Delimited && C == '{') {
  2733. Delimited = true;
  2734. CurPtr += CharSize;
  2735. continue;
  2736. }
  2737. if (Delimited && C == '}') {
  2738. CurPtr += CharSize;
  2739. FoundEndDelimiter = true;
  2740. break;
  2741. }
  2742. unsigned Value = llvm::hexDigitValue(C);
  2743. if (Value == -1U) {
  2744. if (!Delimited)
  2745. break;
  2746. if (Diagnose)
  2747. Diag(BufferPtr, diag::warn_delimited_ucn_incomplete)
  2748. << StringRef(&C, 1);
  2749. return 0;
  2750. }
  2751. if (CodePoint & 0xF000'0000) {
  2752. if (Diagnose)
  2753. Diag(KindLoc, diag::err_escape_too_large) << 0;
  2754. return 0;
  2755. }
  2756. CodePoint <<= 4;
  2757. CodePoint |= Value;
  2758. CurPtr += CharSize;
  2759. Count++;
  2760. }
  2761. if (Count == 0) {
  2762. if (Diagnose)
  2763. Diag(StartPtr, FoundEndDelimiter ? diag::warn_delimited_ucn_empty
  2764. : diag::warn_ucn_escape_no_digits)
  2765. << StringRef(KindLoc, 1);
  2766. return 0;
  2767. }
  2768. if (!Delimited && Count != NumHexDigits) {
  2769. if (Diagnose) {
  2770. Diag(BufferPtr, diag::warn_ucn_escape_incomplete);
  2771. // If the user wrote \U1234, suggest a fixit to \u.
  2772. if (Count == 4 && NumHexDigits == 8) {
  2773. CharSourceRange URange = makeCharRange(*this, KindLoc, KindLoc + 1);
  2774. Diag(KindLoc, diag::note_ucn_four_not_eight)
  2775. << FixItHint::CreateReplacement(URange, "u");
  2776. }
  2777. }
  2778. return 0;
  2779. }
  2780. if (Delimited && PP) {
  2781. Diag(BufferPtr, diag::ext_delimited_escape_sequence);
  2782. }
  2783. if (Result) {
  2784. Result->setFlag(Token::HasUCN);
  2785. if (CurPtr - StartPtr == (ptrdiff_t)(Count + 2 + (Delimited ? 2 : 0)))
  2786. StartPtr = CurPtr;
  2787. else
  2788. while (StartPtr != CurPtr)
  2789. (void)getAndAdvanceChar(StartPtr, *Result);
  2790. } else {
  2791. StartPtr = CurPtr;
  2792. }
  2793. // Don't apply C family restrictions to UCNs in assembly mode
  2794. if (LangOpts.AsmPreprocessor)
  2795. return CodePoint;
  2796. // C99 6.4.3p2: A universal character name shall not specify a character whose
  2797. // short identifier is less than 00A0 other than 0024 ($), 0040 (@), or
  2798. // 0060 (`), nor one in the range D800 through DFFF inclusive.)
  2799. // C++11 [lex.charset]p2: If the hexadecimal value for a
  2800. // universal-character-name corresponds to a surrogate code point (in the
  2801. // range 0xD800-0xDFFF, inclusive), the program is ill-formed. Additionally,
  2802. // if the hexadecimal value for a universal-character-name outside the
  2803. // c-char-sequence, s-char-sequence, or r-char-sequence of a character or
  2804. // string literal corresponds to a control character (in either of the
  2805. // ranges 0x00-0x1F or 0x7F-0x9F, both inclusive) or to a character in the
  2806. // basic source character set, the program is ill-formed.
  2807. if (CodePoint < 0xA0) {
  2808. if (CodePoint == 0x24 || CodePoint == 0x40 || CodePoint == 0x60)
  2809. return CodePoint;
  2810. // We don't use isLexingRawMode() here because we need to warn about bad
  2811. // UCNs even when skipping preprocessing tokens in a #if block.
  2812. if (Result && PP) {
  2813. if (CodePoint < 0x20 || CodePoint >= 0x7F)
  2814. Diag(BufferPtr, diag::err_ucn_control_character);
  2815. else {
  2816. char C = static_cast<char>(CodePoint);
  2817. Diag(BufferPtr, diag::err_ucn_escape_basic_scs) << StringRef(&C, 1);
  2818. }
  2819. }
  2820. return 0;
  2821. } else if (CodePoint >= 0xD800 && CodePoint <= 0xDFFF) {
  2822. // C++03 allows UCNs representing surrogate characters. C99 and C++11 don't.
  2823. // We don't use isLexingRawMode() here because we need to diagnose bad
  2824. // UCNs even when skipping preprocessing tokens in a #if block.
  2825. if (Result && PP) {
  2826. if (LangOpts.CPlusPlus && !LangOpts.CPlusPlus11)
  2827. Diag(BufferPtr, diag::warn_ucn_escape_surrogate);
  2828. else
  2829. Diag(BufferPtr, diag::err_ucn_escape_invalid);
  2830. }
  2831. return 0;
  2832. }
  2833. return CodePoint;
  2834. }
  2835. bool Lexer::CheckUnicodeWhitespace(Token &Result, uint32_t C,
  2836. const char *CurPtr) {
  2837. if (!isLexingRawMode() && !PP->isPreprocessedOutput() &&
  2838. isUnicodeWhitespace(C)) {
  2839. Diag(BufferPtr, diag::ext_unicode_whitespace)
  2840. << makeCharRange(*this, BufferPtr, CurPtr);
  2841. Result.setFlag(Token::LeadingSpace);
  2842. return true;
  2843. }
  2844. return false;
  2845. }
  2846. void Lexer::PropagateLineStartLeadingSpaceInfo(Token &Result) {
  2847. IsAtStartOfLine = Result.isAtStartOfLine();
  2848. HasLeadingSpace = Result.hasLeadingSpace();
  2849. HasLeadingEmptyMacro = Result.hasLeadingEmptyMacro();
  2850. // Note that this doesn't affect IsAtPhysicalStartOfLine.
  2851. }
  2852. bool Lexer::Lex(Token &Result) {
  2853. // Start a new token.
  2854. Result.startToken();
  2855. // Set up misc whitespace flags for LexTokenInternal.
  2856. if (IsAtStartOfLine) {
  2857. Result.setFlag(Token::StartOfLine);
  2858. IsAtStartOfLine = false;
  2859. }
  2860. if (HasLeadingSpace) {
  2861. Result.setFlag(Token::LeadingSpace);
  2862. HasLeadingSpace = false;
  2863. }
  2864. if (HasLeadingEmptyMacro) {
  2865. Result.setFlag(Token::LeadingEmptyMacro);
  2866. HasLeadingEmptyMacro = false;
  2867. }
  2868. bool atPhysicalStartOfLine = IsAtPhysicalStartOfLine;
  2869. IsAtPhysicalStartOfLine = false;
  2870. bool isRawLex = isLexingRawMode();
  2871. (void) isRawLex;
  2872. bool returnedToken = LexTokenInternal(Result, atPhysicalStartOfLine);
  2873. // (After the LexTokenInternal call, the lexer might be destroyed.)
  2874. assert((returnedToken || !isRawLex) && "Raw lex must succeed");
  2875. return returnedToken;
  2876. }
  2877. /// LexTokenInternal - This implements a simple C family lexer. It is an
  2878. /// extremely performance critical piece of code. This assumes that the buffer
  2879. /// has a null character at the end of the file. This returns a preprocessing
  2880. /// token, not a normal token, as such, it is an internal interface. It assumes
  2881. /// that the Flags of result have been cleared before calling this.
  2882. bool Lexer::LexTokenInternal(Token &Result, bool TokAtPhysicalStartOfLine) {
  2883. LexNextToken:
  2884. // New token, can't need cleaning yet.
  2885. Result.clearFlag(Token::NeedsCleaning);
  2886. Result.setIdentifierInfo(nullptr);
  2887. // CurPtr - Cache BufferPtr in an automatic variable.
  2888. const char *CurPtr = BufferPtr;
  2889. // Small amounts of horizontal whitespace is very common between tokens.
  2890. if (isHorizontalWhitespace(*CurPtr)) {
  2891. do {
  2892. ++CurPtr;
  2893. } while (isHorizontalWhitespace(*CurPtr));
  2894. // If we are keeping whitespace and other tokens, just return what we just
  2895. // skipped. The next lexer invocation will return the token after the
  2896. // whitespace.
  2897. if (isKeepWhitespaceMode()) {
  2898. FormTokenWithChars(Result, CurPtr, tok::unknown);
  2899. // FIXME: The next token will not have LeadingSpace set.
  2900. return true;
  2901. }
  2902. BufferPtr = CurPtr;
  2903. Result.setFlag(Token::LeadingSpace);
  2904. }
  2905. unsigned SizeTmp, SizeTmp2; // Temporaries for use in cases below.
  2906. // Read a character, advancing over it.
  2907. char Char = getAndAdvanceChar(CurPtr, Result);
  2908. tok::TokenKind Kind;
  2909. if (!isVerticalWhitespace(Char))
  2910. NewLinePtr = nullptr;
  2911. switch (Char) {
  2912. case 0: // Null.
  2913. // Found end of file?
  2914. if (CurPtr-1 == BufferEnd)
  2915. return LexEndOfFile(Result, CurPtr-1);
  2916. // Check if we are performing code completion.
  2917. if (isCodeCompletionPoint(CurPtr-1)) {
  2918. // Return the code-completion token.
  2919. Result.startToken();
  2920. FormTokenWithChars(Result, CurPtr, tok::code_completion);
  2921. return true;
  2922. }
  2923. if (!isLexingRawMode())
  2924. Diag(CurPtr-1, diag::null_in_file);
  2925. Result.setFlag(Token::LeadingSpace);
  2926. if (SkipWhitespace(Result, CurPtr, TokAtPhysicalStartOfLine))
  2927. return true; // KeepWhitespaceMode
  2928. // We know the lexer hasn't changed, so just try again with this lexer.
  2929. // (We manually eliminate the tail call to avoid recursion.)
  2930. goto LexNextToken;
  2931. case 26: // DOS & CP/M EOF: "^Z".
  2932. // If we're in Microsoft extensions mode, treat this as end of file.
  2933. if (LangOpts.MicrosoftExt) {
  2934. if (!isLexingRawMode())
  2935. Diag(CurPtr-1, diag::ext_ctrl_z_eof_microsoft);
  2936. return LexEndOfFile(Result, CurPtr-1);
  2937. }
  2938. // If Microsoft extensions are disabled, this is just random garbage.
  2939. Kind = tok::unknown;
  2940. break;
  2941. case '\r':
  2942. if (CurPtr[0] == '\n')
  2943. (void)getAndAdvanceChar(CurPtr, Result);
  2944. LLVM_FALLTHROUGH;
  2945. case '\n':
  2946. // If we are inside a preprocessor directive and we see the end of line,
  2947. // we know we are done with the directive, so return an EOD token.
  2948. if (ParsingPreprocessorDirective) {
  2949. // Done parsing the "line".
  2950. ParsingPreprocessorDirective = false;
  2951. // Restore comment saving mode, in case it was disabled for directive.
  2952. if (PP)
  2953. resetExtendedTokenMode();
  2954. // Since we consumed a newline, we are back at the start of a line.
  2955. IsAtStartOfLine = true;
  2956. IsAtPhysicalStartOfLine = true;
  2957. NewLinePtr = CurPtr - 1;
  2958. Kind = tok::eod;
  2959. break;
  2960. }
  2961. // No leading whitespace seen so far.
  2962. Result.clearFlag(Token::LeadingSpace);
  2963. if (SkipWhitespace(Result, CurPtr, TokAtPhysicalStartOfLine))
  2964. return true; // KeepWhitespaceMode
  2965. // We only saw whitespace, so just try again with this lexer.
  2966. // (We manually eliminate the tail call to avoid recursion.)
  2967. goto LexNextToken;
  2968. case ' ':
  2969. case '\t':
  2970. case '\f':
  2971. case '\v':
  2972. SkipHorizontalWhitespace:
  2973. Result.setFlag(Token::LeadingSpace);
  2974. if (SkipWhitespace(Result, CurPtr, TokAtPhysicalStartOfLine))
  2975. return true; // KeepWhitespaceMode
  2976. SkipIgnoredUnits:
  2977. CurPtr = BufferPtr;
  2978. // If the next token is obviously a // or /* */ comment, skip it efficiently
  2979. // too (without going through the big switch stmt).
  2980. if (CurPtr[0] == '/' && CurPtr[1] == '/' && !inKeepCommentMode() &&
  2981. LangOpts.LineComment &&
  2982. (LangOpts.CPlusPlus || !LangOpts.TraditionalCPP)) {
  2983. if (SkipLineComment(Result, CurPtr+2, TokAtPhysicalStartOfLine))
  2984. return true; // There is a token to return.
  2985. goto SkipIgnoredUnits;
  2986. } else if (CurPtr[0] == '/' && CurPtr[1] == '*' && !inKeepCommentMode()) {
  2987. if (SkipBlockComment(Result, CurPtr+2, TokAtPhysicalStartOfLine))
  2988. return true; // There is a token to return.
  2989. goto SkipIgnoredUnits;
  2990. } else if (isHorizontalWhitespace(*CurPtr)) {
  2991. goto SkipHorizontalWhitespace;
  2992. }
  2993. // We only saw whitespace, so just try again with this lexer.
  2994. // (We manually eliminate the tail call to avoid recursion.)
  2995. goto LexNextToken;
  2996. // C99 6.4.4.1: Integer Constants.
  2997. // C99 6.4.4.2: Floating Constants.
  2998. case '0': case '1': case '2': case '3': case '4':
  2999. case '5': case '6': case '7': case '8': case '9':
  3000. // Notify MIOpt that we read a non-whitespace/non-comment token.
  3001. MIOpt.ReadToken();
  3002. return LexNumericConstant(Result, CurPtr);
  3003. case 'u': // Identifier (uber) or C11/C++11 UTF-8 or UTF-16 string literal
  3004. // Notify MIOpt that we read a non-whitespace/non-comment token.
  3005. MIOpt.ReadToken();
  3006. if (LangOpts.CPlusPlus11 || LangOpts.C11) {
  3007. Char = getCharAndSize(CurPtr, SizeTmp);
  3008. // UTF-16 string literal
  3009. if (Char == '"')
  3010. return LexStringLiteral(Result, ConsumeChar(CurPtr, SizeTmp, Result),
  3011. tok::utf16_string_literal);
  3012. // UTF-16 character constant
  3013. if (Char == '\'')
  3014. return LexCharConstant(Result, ConsumeChar(CurPtr, SizeTmp, Result),
  3015. tok::utf16_char_constant);
  3016. // UTF-16 raw string literal
  3017. if (Char == 'R' && LangOpts.CPlusPlus11 &&
  3018. getCharAndSize(CurPtr + SizeTmp, SizeTmp2) == '"')
  3019. return LexRawStringLiteral(Result,
  3020. ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
  3021. SizeTmp2, Result),
  3022. tok::utf16_string_literal);
  3023. if (Char == '8') {
  3024. char Char2 = getCharAndSize(CurPtr + SizeTmp, SizeTmp2);
  3025. // UTF-8 string literal
  3026. if (Char2 == '"')
  3027. return LexStringLiteral(Result,
  3028. ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
  3029. SizeTmp2, Result),
  3030. tok::utf8_string_literal);
  3031. if (Char2 == '\'' && LangOpts.CPlusPlus17)
  3032. return LexCharConstant(
  3033. Result, ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
  3034. SizeTmp2, Result),
  3035. tok::utf8_char_constant);
  3036. if (Char2 == 'R' && LangOpts.CPlusPlus11) {
  3037. unsigned SizeTmp3;
  3038. char Char3 = getCharAndSize(CurPtr + SizeTmp + SizeTmp2, SizeTmp3);
  3039. // UTF-8 raw string literal
  3040. if (Char3 == '"') {
  3041. return LexRawStringLiteral(Result,
  3042. ConsumeChar(ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
  3043. SizeTmp2, Result),
  3044. SizeTmp3, Result),
  3045. tok::utf8_string_literal);
  3046. }
  3047. }
  3048. }
  3049. }
  3050. // treat u like the start of an identifier.
  3051. return LexIdentifierContinue(Result, CurPtr);
  3052. case 'U': // Identifier (Uber) or C11/C++11 UTF-32 string literal
  3053. // Notify MIOpt that we read a non-whitespace/non-comment token.
  3054. MIOpt.ReadToken();
  3055. if (LangOpts.CPlusPlus11 || LangOpts.C11) {
  3056. Char = getCharAndSize(CurPtr, SizeTmp);
  3057. // UTF-32 string literal
  3058. if (Char == '"')
  3059. return LexStringLiteral(Result, ConsumeChar(CurPtr, SizeTmp, Result),
  3060. tok::utf32_string_literal);
  3061. // UTF-32 character constant
  3062. if (Char == '\'')
  3063. return LexCharConstant(Result, ConsumeChar(CurPtr, SizeTmp, Result),
  3064. tok::utf32_char_constant);
  3065. // UTF-32 raw string literal
  3066. if (Char == 'R' && LangOpts.CPlusPlus11 &&
  3067. getCharAndSize(CurPtr + SizeTmp, SizeTmp2) == '"')
  3068. return LexRawStringLiteral(Result,
  3069. ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
  3070. SizeTmp2, Result),
  3071. tok::utf32_string_literal);
  3072. }
  3073. // treat U like the start of an identifier.
  3074. return LexIdentifierContinue(Result, CurPtr);
  3075. case 'R': // Identifier or C++0x raw string literal
  3076. // Notify MIOpt that we read a non-whitespace/non-comment token.
  3077. MIOpt.ReadToken();
  3078. if (LangOpts.CPlusPlus11) {
  3079. Char = getCharAndSize(CurPtr, SizeTmp);
  3080. if (Char == '"')
  3081. return LexRawStringLiteral(Result,
  3082. ConsumeChar(CurPtr, SizeTmp, Result),
  3083. tok::string_literal);
  3084. }
  3085. // treat R like the start of an identifier.
  3086. return LexIdentifierContinue(Result, CurPtr);
  3087. case 'L': // Identifier (Loony) or wide literal (L'x' or L"xyz").
  3088. // Notify MIOpt that we read a non-whitespace/non-comment token.
  3089. MIOpt.ReadToken();
  3090. Char = getCharAndSize(CurPtr, SizeTmp);
  3091. // Wide string literal.
  3092. if (Char == '"')
  3093. return LexStringLiteral(Result, ConsumeChar(CurPtr, SizeTmp, Result),
  3094. tok::wide_string_literal);
  3095. // Wide raw string literal.
  3096. if (LangOpts.CPlusPlus11 && Char == 'R' &&
  3097. getCharAndSize(CurPtr + SizeTmp, SizeTmp2) == '"')
  3098. return LexRawStringLiteral(Result,
  3099. ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
  3100. SizeTmp2, Result),
  3101. tok::wide_string_literal);
  3102. // Wide character constant.
  3103. if (Char == '\'')
  3104. return LexCharConstant(Result, ConsumeChar(CurPtr, SizeTmp, Result),
  3105. tok::wide_char_constant);
  3106. // FALL THROUGH, treating L like the start of an identifier.
  3107. LLVM_FALLTHROUGH;
  3108. // C99 6.4.2: Identifiers.
  3109. case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': case 'G':
  3110. case 'H': case 'I': case 'J': case 'K': /*'L'*/case 'M': case 'N':
  3111. case 'O': case 'P': case 'Q': /*'R'*/case 'S': case 'T': /*'U'*/
  3112. case 'V': case 'W': case 'X': case 'Y': case 'Z':
  3113. case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': case 'g':
  3114. case 'h': case 'i': case 'j': case 'k': case 'l': case 'm': case 'n':
  3115. case 'o': case 'p': case 'q': case 'r': case 's': case 't': /*'u'*/
  3116. case 'v': case 'w': case 'x': case 'y': case 'z':
  3117. case '_':
  3118. // Notify MIOpt that we read a non-whitespace/non-comment token.
  3119. MIOpt.ReadToken();
  3120. return LexIdentifierContinue(Result, CurPtr);
  3121. case '$': // $ in identifiers.
  3122. if (LangOpts.DollarIdents) {
  3123. if (!isLexingRawMode())
  3124. Diag(CurPtr-1, diag::ext_dollar_in_identifier);
  3125. // Notify MIOpt that we read a non-whitespace/non-comment token.
  3126. MIOpt.ReadToken();
  3127. return LexIdentifierContinue(Result, CurPtr);
  3128. }
  3129. Kind = tok::unknown;
  3130. break;
  3131. // C99 6.4.4: Character Constants.
  3132. case '\'':
  3133. // Notify MIOpt that we read a non-whitespace/non-comment token.
  3134. MIOpt.ReadToken();
  3135. return LexCharConstant(Result, CurPtr, tok::char_constant);
  3136. // C99 6.4.5: String Literals.
  3137. case '"':
  3138. // Notify MIOpt that we read a non-whitespace/non-comment token.
  3139. MIOpt.ReadToken();
  3140. return LexStringLiteral(Result, CurPtr,
  3141. ParsingFilename ? tok::header_name
  3142. : tok::string_literal);
  3143. // C99 6.4.6: Punctuators.
  3144. case '?':
  3145. Kind = tok::question;
  3146. break;
  3147. case '[':
  3148. Kind = tok::l_square;
  3149. break;
  3150. case ']':
  3151. Kind = tok::r_square;
  3152. break;
  3153. case '(':
  3154. Kind = tok::l_paren;
  3155. break;
  3156. case ')':
  3157. Kind = tok::r_paren;
  3158. break;
  3159. case '{':
  3160. Kind = tok::l_brace;
  3161. break;
  3162. case '}':
  3163. Kind = tok::r_brace;
  3164. break;
  3165. case '.':
  3166. Char = getCharAndSize(CurPtr, SizeTmp);
  3167. if (Char >= '0' && Char <= '9') {
  3168. // Notify MIOpt that we read a non-whitespace/non-comment token.
  3169. MIOpt.ReadToken();
  3170. return LexNumericConstant(Result, ConsumeChar(CurPtr, SizeTmp, Result));
  3171. } else if (LangOpts.CPlusPlus && Char == '*') {
  3172. Kind = tok::periodstar;
  3173. CurPtr += SizeTmp;
  3174. } else if (Char == '.' &&
  3175. getCharAndSize(CurPtr+SizeTmp, SizeTmp2) == '.') {
  3176. Kind = tok::ellipsis;
  3177. CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
  3178. SizeTmp2, Result);
  3179. } else {
  3180. Kind = tok::period;
  3181. }
  3182. break;
  3183. case '&':
  3184. Char = getCharAndSize(CurPtr, SizeTmp);
  3185. if (Char == '&') {
  3186. Kind = tok::ampamp;
  3187. CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
  3188. } else if (Char == '=') {
  3189. Kind = tok::ampequal;
  3190. CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
  3191. } else {
  3192. Kind = tok::amp;
  3193. }
  3194. break;
  3195. case '*':
  3196. if (getCharAndSize(CurPtr, SizeTmp) == '=') {
  3197. Kind = tok::starequal;
  3198. CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
  3199. } else {
  3200. Kind = tok::star;
  3201. }
  3202. break;
  3203. case '+':
  3204. Char = getCharAndSize(CurPtr, SizeTmp);
  3205. if (Char == '+') {
  3206. CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
  3207. Kind = tok::plusplus;
  3208. } else if (Char == '=') {
  3209. CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
  3210. Kind = tok::plusequal;
  3211. } else {
  3212. Kind = tok::plus;
  3213. }
  3214. break;
  3215. case '-':
  3216. Char = getCharAndSize(CurPtr, SizeTmp);
  3217. if (Char == '-') { // --
  3218. CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
  3219. Kind = tok::minusminus;
  3220. } else if (Char == '>' && LangOpts.CPlusPlus &&
  3221. getCharAndSize(CurPtr+SizeTmp, SizeTmp2) == '*') { // C++ ->*
  3222. CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
  3223. SizeTmp2, Result);
  3224. Kind = tok::arrowstar;
  3225. } else if (Char == '>') { // ->
  3226. CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
  3227. Kind = tok::arrow;
  3228. } else if (Char == '=') { // -=
  3229. CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
  3230. Kind = tok::minusequal;
  3231. } else {
  3232. Kind = tok::minus;
  3233. }
  3234. break;
  3235. case '~':
  3236. Kind = tok::tilde;
  3237. break;
  3238. case '!':
  3239. if (getCharAndSize(CurPtr, SizeTmp) == '=') {
  3240. Kind = tok::exclaimequal;
  3241. CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
  3242. } else {
  3243. Kind = tok::exclaim;
  3244. }
  3245. break;
  3246. case '/':
  3247. // 6.4.9: Comments
  3248. Char = getCharAndSize(CurPtr, SizeTmp);
  3249. if (Char == '/') { // Line comment.
  3250. // Even if Line comments are disabled (e.g. in C89 mode), we generally
  3251. // want to lex this as a comment. There is one problem with this though,
  3252. // that in one particular corner case, this can change the behavior of the
  3253. // resultant program. For example, In "foo //**/ bar", C89 would lex
  3254. // this as "foo / bar" and languages with Line comments would lex it as
  3255. // "foo". Check to see if the character after the second slash is a '*'.
  3256. // If so, we will lex that as a "/" instead of the start of a comment.
  3257. // However, we never do this if we are just preprocessing.
  3258. bool TreatAsComment = LangOpts.LineComment &&
  3259. (LangOpts.CPlusPlus || !LangOpts.TraditionalCPP);
  3260. if (!TreatAsComment)
  3261. if (!(PP && PP->isPreprocessedOutput()))
  3262. TreatAsComment = getCharAndSize(CurPtr+SizeTmp, SizeTmp2) != '*';
  3263. if (TreatAsComment) {
  3264. if (SkipLineComment(Result, ConsumeChar(CurPtr, SizeTmp, Result),
  3265. TokAtPhysicalStartOfLine))
  3266. return true; // There is a token to return.
  3267. // It is common for the tokens immediately after a // comment to be
  3268. // whitespace (indentation for the next line). Instead of going through
  3269. // the big switch, handle it efficiently now.
  3270. goto SkipIgnoredUnits;
  3271. }
  3272. }
  3273. if (Char == '*') { // /**/ comment.
  3274. if (SkipBlockComment(Result, ConsumeChar(CurPtr, SizeTmp, Result),
  3275. TokAtPhysicalStartOfLine))
  3276. return true; // There is a token to return.
  3277. // We only saw whitespace, so just try again with this lexer.
  3278. // (We manually eliminate the tail call to avoid recursion.)
  3279. goto LexNextToken;
  3280. }
  3281. if (Char == '=') {
  3282. CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
  3283. Kind = tok::slashequal;
  3284. } else {
  3285. Kind = tok::slash;
  3286. }
  3287. break;
  3288. case '%':
  3289. Char = getCharAndSize(CurPtr, SizeTmp);
  3290. if (Char == '=') {
  3291. Kind = tok::percentequal;
  3292. CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
  3293. } else if (LangOpts.Digraphs && Char == '>') {
  3294. Kind = tok::r_brace; // '%>' -> '}'
  3295. CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
  3296. } else if (LangOpts.Digraphs && Char == ':') {
  3297. CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
  3298. Char = getCharAndSize(CurPtr, SizeTmp);
  3299. if (Char == '%' && getCharAndSize(CurPtr+SizeTmp, SizeTmp2) == ':') {
  3300. Kind = tok::hashhash; // '%:%:' -> '##'
  3301. CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
  3302. SizeTmp2, Result);
  3303. } else if (Char == '@' && LangOpts.MicrosoftExt) {// %:@ -> #@ -> Charize
  3304. CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
  3305. if (!isLexingRawMode())
  3306. Diag(BufferPtr, diag::ext_charize_microsoft);
  3307. Kind = tok::hashat;
  3308. } else { // '%:' -> '#'
  3309. // We parsed a # character. If this occurs at the start of the line,
  3310. // it's actually the start of a preprocessing directive. Callback to
  3311. // the preprocessor to handle it.
  3312. // TODO: -fpreprocessed mode??
  3313. if (TokAtPhysicalStartOfLine && !LexingRawMode && !Is_PragmaLexer)
  3314. goto HandleDirective;
  3315. Kind = tok::hash;
  3316. }
  3317. } else {
  3318. Kind = tok::percent;
  3319. }
  3320. break;
  3321. case '<':
  3322. Char = getCharAndSize(CurPtr, SizeTmp);
  3323. if (ParsingFilename) {
  3324. return LexAngledStringLiteral(Result, CurPtr);
  3325. } else if (Char == '<') {
  3326. char After = getCharAndSize(CurPtr+SizeTmp, SizeTmp2);
  3327. if (After == '=') {
  3328. Kind = tok::lesslessequal;
  3329. CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
  3330. SizeTmp2, Result);
  3331. } else if (After == '<' && IsStartOfConflictMarker(CurPtr-1)) {
  3332. // If this is actually a '<<<<<<<' version control conflict marker,
  3333. // recognize it as such and recover nicely.
  3334. goto LexNextToken;
  3335. } else if (After == '<' && HandleEndOfConflictMarker(CurPtr-1)) {
  3336. // If this is '<<<<' and we're in a Perforce-style conflict marker,
  3337. // ignore it.
  3338. goto LexNextToken;
  3339. } else if (LangOpts.CUDA && After == '<') {
  3340. Kind = tok::lesslessless;
  3341. CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
  3342. SizeTmp2, Result);
  3343. } else {
  3344. CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
  3345. Kind = tok::lessless;
  3346. }
  3347. } else if (Char == '=') {
  3348. char After = getCharAndSize(CurPtr+SizeTmp, SizeTmp2);
  3349. if (After == '>') {
  3350. if (getLangOpts().CPlusPlus20) {
  3351. if (!isLexingRawMode())
  3352. Diag(BufferPtr, diag::warn_cxx17_compat_spaceship);
  3353. CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
  3354. SizeTmp2, Result);
  3355. Kind = tok::spaceship;
  3356. break;
  3357. }
  3358. // Suggest adding a space between the '<=' and the '>' to avoid a
  3359. // change in semantics if this turns up in C++ <=17 mode.
  3360. if (getLangOpts().CPlusPlus && !isLexingRawMode()) {
  3361. Diag(BufferPtr, diag::warn_cxx20_compat_spaceship)
  3362. << FixItHint::CreateInsertion(
  3363. getSourceLocation(CurPtr + SizeTmp, SizeTmp2), " ");
  3364. }
  3365. }
  3366. CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
  3367. Kind = tok::lessequal;
  3368. } else if (LangOpts.Digraphs && Char == ':') { // '<:' -> '['
  3369. if (LangOpts.CPlusPlus11 &&
  3370. getCharAndSize(CurPtr + SizeTmp, SizeTmp2) == ':') {
  3371. // C++0x [lex.pptoken]p3:
  3372. // Otherwise, if the next three characters are <:: and the subsequent
  3373. // character is neither : nor >, the < is treated as a preprocessor
  3374. // token by itself and not as the first character of the alternative
  3375. // token <:.
  3376. unsigned SizeTmp3;
  3377. char After = getCharAndSize(CurPtr + SizeTmp + SizeTmp2, SizeTmp3);
  3378. if (After != ':' && After != '>') {
  3379. Kind = tok::less;
  3380. if (!isLexingRawMode())
  3381. Diag(BufferPtr, diag::warn_cxx98_compat_less_colon_colon);
  3382. break;
  3383. }
  3384. }
  3385. CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
  3386. Kind = tok::l_square;
  3387. } else if (LangOpts.Digraphs && Char == '%') { // '<%' -> '{'
  3388. CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
  3389. Kind = tok::l_brace;
  3390. } else if (Char == '#' && /*Not a trigraph*/ SizeTmp == 1 &&
  3391. lexEditorPlaceholder(Result, CurPtr)) {
  3392. return true;
  3393. } else {
  3394. Kind = tok::less;
  3395. }
  3396. break;
  3397. case '>':
  3398. Char = getCharAndSize(CurPtr, SizeTmp);
  3399. if (Char == '=') {
  3400. CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
  3401. Kind = tok::greaterequal;
  3402. } else if (Char == '>') {
  3403. char After = getCharAndSize(CurPtr+SizeTmp, SizeTmp2);
  3404. if (After == '=') {
  3405. CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
  3406. SizeTmp2, Result);
  3407. Kind = tok::greatergreaterequal;
  3408. } else if (After == '>' && IsStartOfConflictMarker(CurPtr-1)) {
  3409. // If this is actually a '>>>>' conflict marker, recognize it as such
  3410. // and recover nicely.
  3411. goto LexNextToken;
  3412. } else if (After == '>' && HandleEndOfConflictMarker(CurPtr-1)) {
  3413. // If this is '>>>>>>>' and we're in a conflict marker, ignore it.
  3414. goto LexNextToken;
  3415. } else if (LangOpts.CUDA && After == '>') {
  3416. Kind = tok::greatergreatergreater;
  3417. CurPtr = ConsumeChar(ConsumeChar(CurPtr, SizeTmp, Result),
  3418. SizeTmp2, Result);
  3419. } else {
  3420. CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
  3421. Kind = tok::greatergreater;
  3422. }
  3423. } else {
  3424. Kind = tok::greater;
  3425. }
  3426. break;
  3427. case '^':
  3428. Char = getCharAndSize(CurPtr, SizeTmp);
  3429. if (Char == '=') {
  3430. CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
  3431. Kind = tok::caretequal;
  3432. } else if (LangOpts.OpenCL && Char == '^') {
  3433. CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
  3434. Kind = tok::caretcaret;
  3435. } else {
  3436. Kind = tok::caret;
  3437. }
  3438. break;
  3439. case '|':
  3440. Char = getCharAndSize(CurPtr, SizeTmp);
  3441. if (Char == '=') {
  3442. Kind = tok::pipeequal;
  3443. CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
  3444. } else if (Char == '|') {
  3445. // If this is '|||||||' and we're in a conflict marker, ignore it.
  3446. if (CurPtr[1] == '|' && HandleEndOfConflictMarker(CurPtr-1))
  3447. goto LexNextToken;
  3448. Kind = tok::pipepipe;
  3449. CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
  3450. } else {
  3451. Kind = tok::pipe;
  3452. }
  3453. break;
  3454. case ':':
  3455. Char = getCharAndSize(CurPtr, SizeTmp);
  3456. if (LangOpts.Digraphs && Char == '>') {
  3457. Kind = tok::r_square; // ':>' -> ']'
  3458. CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
  3459. } else if ((LangOpts.CPlusPlus ||
  3460. LangOpts.DoubleSquareBracketAttributes) &&
  3461. Char == ':') {
  3462. Kind = tok::coloncolon;
  3463. CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
  3464. } else {
  3465. Kind = tok::colon;
  3466. }
  3467. break;
  3468. case ';':
  3469. Kind = tok::semi;
  3470. break;
  3471. case '=':
  3472. Char = getCharAndSize(CurPtr, SizeTmp);
  3473. if (Char == '=') {
  3474. // If this is '====' and we're in a conflict marker, ignore it.
  3475. if (CurPtr[1] == '=' && HandleEndOfConflictMarker(CurPtr-1))
  3476. goto LexNextToken;
  3477. Kind = tok::equalequal;
  3478. CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
  3479. } else {
  3480. Kind = tok::equal;
  3481. }
  3482. break;
  3483. case ',':
  3484. Kind = tok::comma;
  3485. break;
  3486. case '#':
  3487. Char = getCharAndSize(CurPtr, SizeTmp);
  3488. if (Char == '#') {
  3489. Kind = tok::hashhash;
  3490. CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
  3491. } else if (Char == '@' && LangOpts.MicrosoftExt) { // #@ -> Charize
  3492. Kind = tok::hashat;
  3493. if (!isLexingRawMode())
  3494. Diag(BufferPtr, diag::ext_charize_microsoft);
  3495. CurPtr = ConsumeChar(CurPtr, SizeTmp, Result);
  3496. } else {
  3497. // We parsed a # character. If this occurs at the start of the line,
  3498. // it's actually the start of a preprocessing directive. Callback to
  3499. // the preprocessor to handle it.
  3500. // TODO: -fpreprocessed mode??
  3501. if (TokAtPhysicalStartOfLine && !LexingRawMode && !Is_PragmaLexer)
  3502. goto HandleDirective;
  3503. Kind = tok::hash;
  3504. }
  3505. break;
  3506. case '@':
  3507. // Objective C support.
  3508. if (CurPtr[-1] == '@' && LangOpts.ObjC)
  3509. Kind = tok::at;
  3510. else
  3511. Kind = tok::unknown;
  3512. break;
  3513. // UCNs (C99 6.4.3, C++11 [lex.charset]p2)
  3514. case '\\':
  3515. if (!LangOpts.AsmPreprocessor) {
  3516. if (uint32_t CodePoint = tryReadUCN(CurPtr, BufferPtr, &Result)) {
  3517. if (CheckUnicodeWhitespace(Result, CodePoint, CurPtr)) {
  3518. if (SkipWhitespace(Result, CurPtr, TokAtPhysicalStartOfLine))
  3519. return true; // KeepWhitespaceMode
  3520. // We only saw whitespace, so just try again with this lexer.
  3521. // (We manually eliminate the tail call to avoid recursion.)
  3522. goto LexNextToken;
  3523. }
  3524. return LexUnicodeIdentifierStart(Result, CodePoint, CurPtr);
  3525. }
  3526. }
  3527. Kind = tok::unknown;
  3528. break;
  3529. default: {
  3530. if (isASCII(Char)) {
  3531. Kind = tok::unknown;
  3532. break;
  3533. }
  3534. llvm::UTF32 CodePoint;
  3535. // We can't just reset CurPtr to BufferPtr because BufferPtr may point to
  3536. // an escaped newline.
  3537. --CurPtr;
  3538. llvm::ConversionResult Status =
  3539. llvm::convertUTF8Sequence((const llvm::UTF8 **)&CurPtr,
  3540. (const llvm::UTF8 *)BufferEnd,
  3541. &CodePoint,
  3542. llvm::strictConversion);
  3543. if (Status == llvm::conversionOK) {
  3544. if (CheckUnicodeWhitespace(Result, CodePoint, CurPtr)) {
  3545. if (SkipWhitespace(Result, CurPtr, TokAtPhysicalStartOfLine))
  3546. return true; // KeepWhitespaceMode
  3547. // We only saw whitespace, so just try again with this lexer.
  3548. // (We manually eliminate the tail call to avoid recursion.)
  3549. goto LexNextToken;
  3550. }
  3551. return LexUnicodeIdentifierStart(Result, CodePoint, CurPtr);
  3552. }
  3553. if (isLexingRawMode() || ParsingPreprocessorDirective ||
  3554. PP->isPreprocessedOutput()) {
  3555. ++CurPtr;
  3556. Kind = tok::unknown;
  3557. break;
  3558. }
  3559. // Non-ASCII characters tend to creep into source code unintentionally.
  3560. // Instead of letting the parser complain about the unknown token,
  3561. // just diagnose the invalid UTF-8, then drop the character.
  3562. Diag(CurPtr, diag::err_invalid_utf8);
  3563. BufferPtr = CurPtr+1;
  3564. // We're pretending the character didn't exist, so just try again with
  3565. // this lexer.
  3566. // (We manually eliminate the tail call to avoid recursion.)
  3567. goto LexNextToken;
  3568. }
  3569. }
  3570. // Notify MIOpt that we read a non-whitespace/non-comment token.
  3571. MIOpt.ReadToken();
  3572. // Update the location of token as well as BufferPtr.
  3573. FormTokenWithChars(Result, CurPtr, Kind);
  3574. return true;
  3575. HandleDirective:
  3576. // We parsed a # character and it's the start of a preprocessing directive.
  3577. FormTokenWithChars(Result, CurPtr, tok::hash);
  3578. PP->HandleDirective(Result);
  3579. if (PP->hadModuleLoaderFatalFailure()) {
  3580. // With a fatal failure in the module loader, we abort parsing.
  3581. assert(Result.is(tok::eof) && "Preprocessor did not set tok:eof");
  3582. return true;
  3583. }
  3584. // We parsed the directive; lex a token with the new state.
  3585. return false;
  3586. }