Lexer.cpp 133 KB

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