Lexer.cpp 160 KB

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