Lexer.cpp 138 KB

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