LiteralSupport.cpp 70 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120
  1. //===--- LiteralSupport.cpp - Code to parse and process literals ----------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // This file implements the NumericLiteralParser, CharLiteralParser, and
  10. // StringLiteralParser interfaces.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "clang/Lex/LiteralSupport.h"
  14. #include "clang/Basic/CharInfo.h"
  15. #include "clang/Basic/LangOptions.h"
  16. #include "clang/Basic/SourceLocation.h"
  17. #include "clang/Basic/TargetInfo.h"
  18. #include "clang/Lex/LexDiagnostic.h"
  19. #include "clang/Lex/Lexer.h"
  20. #include "clang/Lex/Preprocessor.h"
  21. #include "clang/Lex/Token.h"
  22. #include "llvm/ADT/APInt.h"
  23. #include "llvm/ADT/SmallVector.h"
  24. #include "llvm/ADT/StringExtras.h"
  25. #include "llvm/ADT/StringSwitch.h"
  26. #include "llvm/Support/ConvertUTF.h"
  27. #include "llvm/Support/Error.h"
  28. #include "llvm/Support/ErrorHandling.h"
  29. #include <algorithm>
  30. #include <cassert>
  31. #include <cstddef>
  32. #include <cstdint>
  33. #include <cstring>
  34. #include <string>
  35. using namespace clang;
  36. static unsigned getCharWidth(tok::TokenKind kind, const TargetInfo &Target) {
  37. switch (kind) {
  38. default: llvm_unreachable("Unknown token type!");
  39. case tok::char_constant:
  40. case tok::string_literal:
  41. case tok::utf8_char_constant:
  42. case tok::utf8_string_literal:
  43. return Target.getCharWidth();
  44. case tok::wide_char_constant:
  45. case tok::wide_string_literal:
  46. return Target.getWCharWidth();
  47. case tok::utf16_char_constant:
  48. case tok::utf16_string_literal:
  49. return Target.getChar16Width();
  50. case tok::utf32_char_constant:
  51. case tok::utf32_string_literal:
  52. return Target.getChar32Width();
  53. }
  54. }
  55. static CharSourceRange MakeCharSourceRange(const LangOptions &Features,
  56. FullSourceLoc TokLoc,
  57. const char *TokBegin,
  58. const char *TokRangeBegin,
  59. const char *TokRangeEnd) {
  60. SourceLocation Begin =
  61. Lexer::AdvanceToTokenCharacter(TokLoc, TokRangeBegin - TokBegin,
  62. TokLoc.getManager(), Features);
  63. SourceLocation End =
  64. Lexer::AdvanceToTokenCharacter(Begin, TokRangeEnd - TokRangeBegin,
  65. TokLoc.getManager(), Features);
  66. return CharSourceRange::getCharRange(Begin, End);
  67. }
  68. /// Produce a diagnostic highlighting some portion of a literal.
  69. ///
  70. /// Emits the diagnostic \p DiagID, highlighting the range of characters from
  71. /// \p TokRangeBegin (inclusive) to \p TokRangeEnd (exclusive), which must be
  72. /// a substring of a spelling buffer for the token beginning at \p TokBegin.
  73. static DiagnosticBuilder Diag(DiagnosticsEngine *Diags,
  74. const LangOptions &Features, FullSourceLoc TokLoc,
  75. const char *TokBegin, const char *TokRangeBegin,
  76. const char *TokRangeEnd, unsigned DiagID) {
  77. SourceLocation Begin =
  78. Lexer::AdvanceToTokenCharacter(TokLoc, TokRangeBegin - TokBegin,
  79. TokLoc.getManager(), Features);
  80. return Diags->Report(Begin, DiagID) <<
  81. MakeCharSourceRange(Features, TokLoc, TokBegin, TokRangeBegin, TokRangeEnd);
  82. }
  83. /// ProcessCharEscape - Parse a standard C escape sequence, which can occur in
  84. /// either a character or a string literal.
  85. static unsigned ProcessCharEscape(const char *ThisTokBegin,
  86. const char *&ThisTokBuf,
  87. const char *ThisTokEnd, bool &HadError,
  88. FullSourceLoc Loc, unsigned CharWidth,
  89. DiagnosticsEngine *Diags,
  90. const LangOptions &Features) {
  91. const char *EscapeBegin = ThisTokBuf;
  92. bool Delimited = false;
  93. bool EndDelimiterFound = false;
  94. // Skip the '\' char.
  95. ++ThisTokBuf;
  96. // We know that this character can't be off the end of the buffer, because
  97. // that would have been \", which would not have been the end of string.
  98. unsigned ResultChar = *ThisTokBuf++;
  99. switch (ResultChar) {
  100. // These map to themselves.
  101. case '\\': case '\'': case '"': case '?': break;
  102. // These have fixed mappings.
  103. case 'a':
  104. // TODO: K&R: the meaning of '\\a' is different in traditional C
  105. ResultChar = 7;
  106. break;
  107. case 'b':
  108. ResultChar = 8;
  109. break;
  110. case 'e':
  111. if (Diags)
  112. Diag(Diags, Features, Loc, ThisTokBegin, EscapeBegin, ThisTokBuf,
  113. diag::ext_nonstandard_escape) << "e";
  114. ResultChar = 27;
  115. break;
  116. case 'E':
  117. if (Diags)
  118. Diag(Diags, Features, Loc, ThisTokBegin, EscapeBegin, ThisTokBuf,
  119. diag::ext_nonstandard_escape) << "E";
  120. ResultChar = 27;
  121. break;
  122. case 'f':
  123. ResultChar = 12;
  124. break;
  125. case 'n':
  126. ResultChar = 10;
  127. break;
  128. case 'r':
  129. ResultChar = 13;
  130. break;
  131. case 't':
  132. ResultChar = 9;
  133. break;
  134. case 'v':
  135. ResultChar = 11;
  136. break;
  137. case 'x': { // Hex escape.
  138. ResultChar = 0;
  139. if (ThisTokBuf != ThisTokEnd && *ThisTokBuf == '{') {
  140. Delimited = true;
  141. ThisTokBuf++;
  142. if (*ThisTokBuf == '}') {
  143. Diag(Diags, Features, Loc, ThisTokBegin, EscapeBegin, ThisTokBuf,
  144. diag::err_delimited_escape_empty);
  145. return ResultChar;
  146. }
  147. } else if (ThisTokBuf == ThisTokEnd || !isHexDigit(*ThisTokBuf)) {
  148. if (Diags)
  149. Diag(Diags, Features, Loc, ThisTokBegin, EscapeBegin, ThisTokBuf,
  150. diag::err_hex_escape_no_digits) << "x";
  151. return ResultChar;
  152. }
  153. // Hex escapes are a maximal series of hex digits.
  154. bool Overflow = false;
  155. for (; ThisTokBuf != ThisTokEnd; ++ThisTokBuf) {
  156. if (Delimited && *ThisTokBuf == '}') {
  157. ThisTokBuf++;
  158. EndDelimiterFound = true;
  159. break;
  160. }
  161. int CharVal = llvm::hexDigitValue(*ThisTokBuf);
  162. if (CharVal == -1) {
  163. // Non delimited hex escape sequences stop at the first non-hex digit.
  164. if (!Delimited)
  165. break;
  166. HadError = true;
  167. if (Diags)
  168. Diag(Diags, Features, Loc, ThisTokBegin, EscapeBegin, ThisTokBuf,
  169. diag::err_delimited_escape_invalid)
  170. << StringRef(ThisTokBuf, 1);
  171. continue;
  172. }
  173. // About to shift out a digit?
  174. if (ResultChar & 0xF0000000)
  175. Overflow = true;
  176. ResultChar <<= 4;
  177. ResultChar |= CharVal;
  178. }
  179. // See if any bits will be truncated when evaluated as a character.
  180. if (CharWidth != 32 && (ResultChar >> CharWidth) != 0) {
  181. Overflow = true;
  182. ResultChar &= ~0U >> (32-CharWidth);
  183. }
  184. // Check for overflow.
  185. if (!HadError && Overflow) { // Too many digits to fit in
  186. HadError = true;
  187. if (Diags)
  188. Diag(Diags, Features, Loc, ThisTokBegin, EscapeBegin, ThisTokBuf,
  189. diag::err_escape_too_large)
  190. << 0;
  191. }
  192. break;
  193. }
  194. case '0': case '1': case '2': case '3':
  195. case '4': case '5': case '6': case '7': {
  196. // Octal escapes.
  197. --ThisTokBuf;
  198. ResultChar = 0;
  199. // Octal escapes are a series of octal digits with maximum length 3.
  200. // "\0123" is a two digit sequence equal to "\012" "3".
  201. unsigned NumDigits = 0;
  202. do {
  203. ResultChar <<= 3;
  204. ResultChar |= *ThisTokBuf++ - '0';
  205. ++NumDigits;
  206. } while (ThisTokBuf != ThisTokEnd && NumDigits < 3 &&
  207. ThisTokBuf[0] >= '0' && ThisTokBuf[0] <= '7');
  208. // Check for overflow. Reject '\777', but not L'\777'.
  209. if (CharWidth != 32 && (ResultChar >> CharWidth) != 0) {
  210. if (Diags)
  211. Diag(Diags, Features, Loc, ThisTokBegin, EscapeBegin, ThisTokBuf,
  212. diag::err_escape_too_large) << 1;
  213. ResultChar &= ~0U >> (32-CharWidth);
  214. }
  215. break;
  216. }
  217. case 'o': {
  218. bool Overflow = false;
  219. if (ThisTokBuf == ThisTokEnd || *ThisTokBuf != '{') {
  220. HadError = true;
  221. if (Diags)
  222. Diag(Diags, Features, Loc, ThisTokBegin, EscapeBegin, ThisTokBuf,
  223. diag::err_delimited_escape_missing_brace);
  224. break;
  225. }
  226. ResultChar = 0;
  227. Delimited = true;
  228. ++ThisTokBuf;
  229. if (*ThisTokBuf == '}') {
  230. Diag(Diags, Features, Loc, ThisTokBegin, EscapeBegin, ThisTokBuf,
  231. diag::err_delimited_escape_empty);
  232. return ResultChar;
  233. }
  234. while (ThisTokBuf != ThisTokEnd) {
  235. if (*ThisTokBuf == '}') {
  236. EndDelimiterFound = true;
  237. ThisTokBuf++;
  238. break;
  239. }
  240. if (*ThisTokBuf < '0' || *ThisTokBuf > '7') {
  241. HadError = true;
  242. if (Diags)
  243. Diag(Diags, Features, Loc, ThisTokBegin, EscapeBegin, ThisTokBuf,
  244. diag::err_delimited_escape_invalid)
  245. << StringRef(ThisTokBuf, 1);
  246. ThisTokBuf++;
  247. continue;
  248. }
  249. if (ResultChar & 0x020000000)
  250. Overflow = true;
  251. ResultChar <<= 3;
  252. ResultChar |= *ThisTokBuf++ - '0';
  253. }
  254. // Check for overflow. Reject '\777', but not L'\777'.
  255. if (!HadError &&
  256. (Overflow || (CharWidth != 32 && (ResultChar >> CharWidth) != 0))) {
  257. HadError = true;
  258. if (Diags)
  259. Diag(Diags, Features, Loc, ThisTokBegin, EscapeBegin, ThisTokBuf,
  260. diag::err_escape_too_large)
  261. << 1;
  262. ResultChar &= ~0U >> (32 - CharWidth);
  263. }
  264. break;
  265. }
  266. // Otherwise, these are not valid escapes.
  267. case '(': case '{': case '[': case '%':
  268. // GCC accepts these as extensions. We warn about them as such though.
  269. if (Diags)
  270. Diag(Diags, Features, Loc, ThisTokBegin, EscapeBegin, ThisTokBuf,
  271. diag::ext_nonstandard_escape)
  272. << std::string(1, ResultChar);
  273. break;
  274. default:
  275. if (!Diags)
  276. break;
  277. if (isPrintable(ResultChar))
  278. Diag(Diags, Features, Loc, ThisTokBegin, EscapeBegin, ThisTokBuf,
  279. diag::ext_unknown_escape)
  280. << std::string(1, ResultChar);
  281. else
  282. Diag(Diags, Features, Loc, ThisTokBegin, EscapeBegin, ThisTokBuf,
  283. diag::ext_unknown_escape)
  284. << "x" + llvm::utohexstr(ResultChar);
  285. break;
  286. }
  287. if (Delimited && Diags) {
  288. if (!EndDelimiterFound)
  289. Diag(Diags, Features, Loc, ThisTokBegin, EscapeBegin, ThisTokBuf,
  290. diag::err_expected)
  291. << tok::r_brace;
  292. else if (!HadError) {
  293. Diag(Diags, Features, Loc, ThisTokBegin, EscapeBegin, ThisTokBuf,
  294. diag::ext_delimited_escape_sequence);
  295. }
  296. }
  297. return ResultChar;
  298. }
  299. static void appendCodePoint(unsigned Codepoint,
  300. llvm::SmallVectorImpl<char> &Str) {
  301. char ResultBuf[4];
  302. char *ResultPtr = ResultBuf;
  303. bool Res = llvm::ConvertCodePointToUTF8(Codepoint, ResultPtr);
  304. (void)Res;
  305. assert(Res && "Unexpected conversion failure");
  306. Str.append(ResultBuf, ResultPtr);
  307. }
  308. void clang::expandUCNs(SmallVectorImpl<char> &Buf, StringRef Input) {
  309. for (StringRef::iterator I = Input.begin(), E = Input.end(); I != E; ++I) {
  310. if (*I != '\\') {
  311. Buf.push_back(*I);
  312. continue;
  313. }
  314. ++I;
  315. char Kind = *I;
  316. ++I;
  317. assert(Kind == 'u' || Kind == 'U');
  318. uint32_t CodePoint = 0;
  319. if (Kind == 'u' && *I == '{') {
  320. for (++I; *I != '}'; ++I) {
  321. unsigned Value = llvm::hexDigitValue(*I);
  322. assert(Value != -1U);
  323. CodePoint <<= 4;
  324. CodePoint += Value;
  325. }
  326. appendCodePoint(CodePoint, Buf);
  327. continue;
  328. }
  329. unsigned NumHexDigits;
  330. if (Kind == 'u')
  331. NumHexDigits = 4;
  332. else
  333. NumHexDigits = 8;
  334. assert(I + NumHexDigits <= E);
  335. for (; NumHexDigits != 0; ++I, --NumHexDigits) {
  336. unsigned Value = llvm::hexDigitValue(*I);
  337. assert(Value != -1U);
  338. CodePoint <<= 4;
  339. CodePoint += Value;
  340. }
  341. appendCodePoint(CodePoint, Buf);
  342. --I;
  343. }
  344. }
  345. /// ProcessUCNEscape - Read the Universal Character Name, check constraints and
  346. /// return the UTF32.
  347. static bool ProcessUCNEscape(const char *ThisTokBegin, const char *&ThisTokBuf,
  348. const char *ThisTokEnd,
  349. uint32_t &UcnVal, unsigned short &UcnLen,
  350. FullSourceLoc Loc, DiagnosticsEngine *Diags,
  351. const LangOptions &Features,
  352. bool in_char_string_literal = false) {
  353. const char *UcnBegin = ThisTokBuf;
  354. // Skip the '\u' char's.
  355. ThisTokBuf += 2;
  356. bool Delimited = false;
  357. bool EndDelimiterFound = false;
  358. bool HasError = false;
  359. if (UcnBegin[1] == 'u' && in_char_string_literal &&
  360. ThisTokBuf != ThisTokEnd && *ThisTokBuf == '{') {
  361. Delimited = true;
  362. ThisTokBuf++;
  363. } else if (ThisTokBuf == ThisTokEnd || !isHexDigit(*ThisTokBuf)) {
  364. if (Diags)
  365. Diag(Diags, Features, Loc, ThisTokBegin, UcnBegin, ThisTokBuf,
  366. diag::err_hex_escape_no_digits) << StringRef(&ThisTokBuf[-1], 1);
  367. return false;
  368. }
  369. UcnLen = (ThisTokBuf[-1] == 'u' ? 4 : 8);
  370. bool Overflow = false;
  371. unsigned short Count = 0;
  372. for (; ThisTokBuf != ThisTokEnd && (Delimited || Count != UcnLen);
  373. ++ThisTokBuf) {
  374. if (Delimited && *ThisTokBuf == '}') {
  375. ++ThisTokBuf;
  376. EndDelimiterFound = true;
  377. break;
  378. }
  379. int CharVal = llvm::hexDigitValue(*ThisTokBuf);
  380. if (CharVal == -1) {
  381. HasError = true;
  382. if (!Delimited)
  383. break;
  384. if (Diags) {
  385. Diag(Diags, Features, Loc, ThisTokBegin, UcnBegin, ThisTokBuf,
  386. diag::err_delimited_escape_invalid)
  387. << StringRef(ThisTokBuf, 1);
  388. }
  389. Count++;
  390. continue;
  391. }
  392. if (UcnVal & 0xF0000000) {
  393. Overflow = true;
  394. continue;
  395. }
  396. UcnVal <<= 4;
  397. UcnVal |= CharVal;
  398. Count++;
  399. }
  400. if (Overflow) {
  401. if (Diags)
  402. Diag(Diags, Features, Loc, ThisTokBegin, UcnBegin, ThisTokBuf,
  403. diag::err_escape_too_large)
  404. << 0;
  405. return false;
  406. }
  407. if (Delimited && !EndDelimiterFound) {
  408. if (Diags) {
  409. Diag(Diags, Features, Loc, ThisTokBegin, UcnBegin, ThisTokBuf,
  410. diag::err_expected)
  411. << tok::r_brace;
  412. }
  413. return false;
  414. }
  415. // If we didn't consume the proper number of digits, there is a problem.
  416. if (Count == 0 || (!Delimited && Count != UcnLen)) {
  417. if (Diags)
  418. Diag(Diags, Features, Loc, ThisTokBegin, UcnBegin, ThisTokBuf,
  419. Delimited ? diag::err_delimited_escape_empty
  420. : diag::err_ucn_escape_incomplete);
  421. return false;
  422. }
  423. if (HasError)
  424. return false;
  425. // Check UCN constraints (C99 6.4.3p2) [C++11 lex.charset p2]
  426. if ((0xD800 <= UcnVal && UcnVal <= 0xDFFF) || // surrogate codepoints
  427. UcnVal > 0x10FFFF) { // maximum legal UTF32 value
  428. if (Diags)
  429. Diag(Diags, Features, Loc, ThisTokBegin, UcnBegin, ThisTokBuf,
  430. diag::err_ucn_escape_invalid);
  431. return false;
  432. }
  433. // C++11 allows UCNs that refer to control characters and basic source
  434. // characters inside character and string literals
  435. if (UcnVal < 0xa0 &&
  436. (UcnVal != 0x24 && UcnVal != 0x40 && UcnVal != 0x60)) { // $, @, `
  437. bool IsError = (!Features.CPlusPlus11 || !in_char_string_literal);
  438. if (Diags) {
  439. char BasicSCSChar = UcnVal;
  440. if (UcnVal >= 0x20 && UcnVal < 0x7f)
  441. Diag(Diags, Features, Loc, ThisTokBegin, UcnBegin, ThisTokBuf,
  442. IsError ? diag::err_ucn_escape_basic_scs :
  443. diag::warn_cxx98_compat_literal_ucn_escape_basic_scs)
  444. << StringRef(&BasicSCSChar, 1);
  445. else
  446. Diag(Diags, Features, Loc, ThisTokBegin, UcnBegin, ThisTokBuf,
  447. IsError ? diag::err_ucn_control_character :
  448. diag::warn_cxx98_compat_literal_ucn_control_character);
  449. }
  450. if (IsError)
  451. return false;
  452. }
  453. if (!Features.CPlusPlus && !Features.C99 && Diags)
  454. Diag(Diags, Features, Loc, ThisTokBegin, UcnBegin, ThisTokBuf,
  455. diag::warn_ucn_not_valid_in_c89_literal);
  456. if (Delimited && Diags)
  457. Diag(Diags, Features, Loc, ThisTokBegin, UcnBegin, ThisTokBuf,
  458. diag::ext_delimited_escape_sequence);
  459. return true;
  460. }
  461. /// MeasureUCNEscape - Determine the number of bytes within the resulting string
  462. /// which this UCN will occupy.
  463. static int MeasureUCNEscape(const char *ThisTokBegin, const char *&ThisTokBuf,
  464. const char *ThisTokEnd, unsigned CharByteWidth,
  465. const LangOptions &Features, bool &HadError) {
  466. // UTF-32: 4 bytes per escape.
  467. if (CharByteWidth == 4)
  468. return 4;
  469. uint32_t UcnVal = 0;
  470. unsigned short UcnLen = 0;
  471. FullSourceLoc Loc;
  472. if (!ProcessUCNEscape(ThisTokBegin, ThisTokBuf, ThisTokEnd, UcnVal,
  473. UcnLen, Loc, nullptr, Features, true)) {
  474. HadError = true;
  475. return 0;
  476. }
  477. // UTF-16: 2 bytes for BMP, 4 bytes otherwise.
  478. if (CharByteWidth == 2)
  479. return UcnVal <= 0xFFFF ? 2 : 4;
  480. // UTF-8.
  481. if (UcnVal < 0x80)
  482. return 1;
  483. if (UcnVal < 0x800)
  484. return 2;
  485. if (UcnVal < 0x10000)
  486. return 3;
  487. return 4;
  488. }
  489. /// EncodeUCNEscape - Read the Universal Character Name, check constraints and
  490. /// convert the UTF32 to UTF8 or UTF16. This is a subroutine of
  491. /// StringLiteralParser. When we decide to implement UCN's for identifiers,
  492. /// we will likely rework our support for UCN's.
  493. static void EncodeUCNEscape(const char *ThisTokBegin, const char *&ThisTokBuf,
  494. const char *ThisTokEnd,
  495. char *&ResultBuf, bool &HadError,
  496. FullSourceLoc Loc, unsigned CharByteWidth,
  497. DiagnosticsEngine *Diags,
  498. const LangOptions &Features) {
  499. typedef uint32_t UTF32;
  500. UTF32 UcnVal = 0;
  501. unsigned short UcnLen = 0;
  502. if (!ProcessUCNEscape(ThisTokBegin, ThisTokBuf, ThisTokEnd, UcnVal, UcnLen,
  503. Loc, Diags, Features, true)) {
  504. HadError = true;
  505. return;
  506. }
  507. assert((CharByteWidth == 1 || CharByteWidth == 2 || CharByteWidth == 4) &&
  508. "only character widths of 1, 2, or 4 bytes supported");
  509. (void)UcnLen;
  510. assert((UcnLen== 4 || UcnLen== 8) && "only ucn length of 4 or 8 supported");
  511. if (CharByteWidth == 4) {
  512. // FIXME: Make the type of the result buffer correct instead of
  513. // using reinterpret_cast.
  514. llvm::UTF32 *ResultPtr = reinterpret_cast<llvm::UTF32*>(ResultBuf);
  515. *ResultPtr = UcnVal;
  516. ResultBuf += 4;
  517. return;
  518. }
  519. if (CharByteWidth == 2) {
  520. // FIXME: Make the type of the result buffer correct instead of
  521. // using reinterpret_cast.
  522. llvm::UTF16 *ResultPtr = reinterpret_cast<llvm::UTF16*>(ResultBuf);
  523. if (UcnVal <= (UTF32)0xFFFF) {
  524. *ResultPtr = UcnVal;
  525. ResultBuf += 2;
  526. return;
  527. }
  528. // Convert to UTF16.
  529. UcnVal -= 0x10000;
  530. *ResultPtr = 0xD800 + (UcnVal >> 10);
  531. *(ResultPtr+1) = 0xDC00 + (UcnVal & 0x3FF);
  532. ResultBuf += 4;
  533. return;
  534. }
  535. assert(CharByteWidth == 1 && "UTF-8 encoding is only for 1 byte characters");
  536. // Now that we've parsed/checked the UCN, we convert from UTF32->UTF8.
  537. // The conversion below was inspired by:
  538. // http://www.unicode.org/Public/PROGRAMS/CVTUTF/ConvertUTF.c
  539. // First, we determine how many bytes the result will require.
  540. typedef uint8_t UTF8;
  541. unsigned short bytesToWrite = 0;
  542. if (UcnVal < (UTF32)0x80)
  543. bytesToWrite = 1;
  544. else if (UcnVal < (UTF32)0x800)
  545. bytesToWrite = 2;
  546. else if (UcnVal < (UTF32)0x10000)
  547. bytesToWrite = 3;
  548. else
  549. bytesToWrite = 4;
  550. const unsigned byteMask = 0xBF;
  551. const unsigned byteMark = 0x80;
  552. // Once the bits are split out into bytes of UTF8, this is a mask OR-ed
  553. // into the first byte, depending on how many bytes follow.
  554. static const UTF8 firstByteMark[5] = {
  555. 0x00, 0x00, 0xC0, 0xE0, 0xF0
  556. };
  557. // Finally, we write the bytes into ResultBuf.
  558. ResultBuf += bytesToWrite;
  559. switch (bytesToWrite) { // note: everything falls through.
  560. case 4:
  561. *--ResultBuf = (UTF8)((UcnVal | byteMark) & byteMask); UcnVal >>= 6;
  562. LLVM_FALLTHROUGH;
  563. case 3:
  564. *--ResultBuf = (UTF8)((UcnVal | byteMark) & byteMask); UcnVal >>= 6;
  565. LLVM_FALLTHROUGH;
  566. case 2:
  567. *--ResultBuf = (UTF8)((UcnVal | byteMark) & byteMask); UcnVal >>= 6;
  568. LLVM_FALLTHROUGH;
  569. case 1:
  570. *--ResultBuf = (UTF8) (UcnVal | firstByteMark[bytesToWrite]);
  571. }
  572. // Update the buffer.
  573. ResultBuf += bytesToWrite;
  574. }
  575. /// integer-constant: [C99 6.4.4.1]
  576. /// decimal-constant integer-suffix
  577. /// octal-constant integer-suffix
  578. /// hexadecimal-constant integer-suffix
  579. /// binary-literal integer-suffix [GNU, C++1y]
  580. /// user-defined-integer-literal: [C++11 lex.ext]
  581. /// decimal-literal ud-suffix
  582. /// octal-literal ud-suffix
  583. /// hexadecimal-literal ud-suffix
  584. /// binary-literal ud-suffix [GNU, C++1y]
  585. /// decimal-constant:
  586. /// nonzero-digit
  587. /// decimal-constant digit
  588. /// octal-constant:
  589. /// 0
  590. /// octal-constant octal-digit
  591. /// hexadecimal-constant:
  592. /// hexadecimal-prefix hexadecimal-digit
  593. /// hexadecimal-constant hexadecimal-digit
  594. /// hexadecimal-prefix: one of
  595. /// 0x 0X
  596. /// binary-literal:
  597. /// 0b binary-digit
  598. /// 0B binary-digit
  599. /// binary-literal binary-digit
  600. /// integer-suffix:
  601. /// unsigned-suffix [long-suffix]
  602. /// unsigned-suffix [long-long-suffix]
  603. /// long-suffix [unsigned-suffix]
  604. /// long-long-suffix [unsigned-sufix]
  605. /// nonzero-digit:
  606. /// 1 2 3 4 5 6 7 8 9
  607. /// octal-digit:
  608. /// 0 1 2 3 4 5 6 7
  609. /// hexadecimal-digit:
  610. /// 0 1 2 3 4 5 6 7 8 9
  611. /// a b c d e f
  612. /// A B C D E F
  613. /// binary-digit:
  614. /// 0
  615. /// 1
  616. /// unsigned-suffix: one of
  617. /// u U
  618. /// long-suffix: one of
  619. /// l L
  620. /// long-long-suffix: one of
  621. /// ll LL
  622. ///
  623. /// floating-constant: [C99 6.4.4.2]
  624. /// TODO: add rules...
  625. ///
  626. NumericLiteralParser::NumericLiteralParser(StringRef TokSpelling,
  627. SourceLocation TokLoc,
  628. const SourceManager &SM,
  629. const LangOptions &LangOpts,
  630. const TargetInfo &Target,
  631. DiagnosticsEngine &Diags)
  632. : SM(SM), LangOpts(LangOpts), Diags(Diags),
  633. ThisTokBegin(TokSpelling.begin()), ThisTokEnd(TokSpelling.end()) {
  634. s = DigitsBegin = ThisTokBegin;
  635. saw_exponent = false;
  636. saw_period = false;
  637. saw_ud_suffix = false;
  638. saw_fixed_point_suffix = false;
  639. isLong = false;
  640. isUnsigned = false;
  641. isLongLong = false;
  642. isSizeT = false;
  643. isHalf = false;
  644. isFloat = false;
  645. isImaginary = false;
  646. isFloat16 = false;
  647. isFloat128 = false;
  648. MicrosoftInteger = 0;
  649. isFract = false;
  650. isAccum = false;
  651. hadError = false;
  652. // This routine assumes that the range begin/end matches the regex for integer
  653. // and FP constants (specifically, the 'pp-number' regex), and assumes that
  654. // the byte at "*end" is both valid and not part of the regex. Because of
  655. // this, it doesn't have to check for 'overscan' in various places.
  656. if (isPreprocessingNumberBody(*ThisTokEnd)) {
  657. Diags.Report(TokLoc, diag::err_lexing_numeric);
  658. hadError = true;
  659. return;
  660. }
  661. if (*s == '0') { // parse radix
  662. ParseNumberStartingWithZero(TokLoc);
  663. if (hadError)
  664. return;
  665. } else { // the first digit is non-zero
  666. radix = 10;
  667. s = SkipDigits(s);
  668. if (s == ThisTokEnd) {
  669. // Done.
  670. } else {
  671. ParseDecimalOrOctalCommon(TokLoc);
  672. if (hadError)
  673. return;
  674. }
  675. }
  676. SuffixBegin = s;
  677. checkSeparator(TokLoc, s, CSK_AfterDigits);
  678. // Initial scan to lookahead for fixed point suffix.
  679. if (LangOpts.FixedPoint) {
  680. for (const char *c = s; c != ThisTokEnd; ++c) {
  681. if (*c == 'r' || *c == 'k' || *c == 'R' || *c == 'K') {
  682. saw_fixed_point_suffix = true;
  683. break;
  684. }
  685. }
  686. }
  687. // Parse the suffix. At this point we can classify whether we have an FP or
  688. // integer constant.
  689. bool isFixedPointConstant = isFixedPointLiteral();
  690. bool isFPConstant = isFloatingLiteral();
  691. bool HasSize = false;
  692. // Loop over all of the characters of the suffix. If we see something bad,
  693. // we break out of the loop.
  694. for (; s != ThisTokEnd; ++s) {
  695. switch (*s) {
  696. case 'R':
  697. case 'r':
  698. if (!LangOpts.FixedPoint)
  699. break;
  700. if (isFract || isAccum) break;
  701. if (!(saw_period || saw_exponent)) break;
  702. isFract = true;
  703. continue;
  704. case 'K':
  705. case 'k':
  706. if (!LangOpts.FixedPoint)
  707. break;
  708. if (isFract || isAccum) break;
  709. if (!(saw_period || saw_exponent)) break;
  710. isAccum = true;
  711. continue;
  712. case 'h': // FP Suffix for "half".
  713. case 'H':
  714. // OpenCL Extension v1.2 s9.5 - h or H suffix for half type.
  715. if (!(LangOpts.Half || LangOpts.FixedPoint))
  716. break;
  717. if (isIntegerLiteral()) break; // Error for integer constant.
  718. if (HasSize)
  719. break;
  720. HasSize = true;
  721. isHalf = true;
  722. continue; // Success.
  723. case 'f': // FP Suffix for "float"
  724. case 'F':
  725. if (!isFPConstant) break; // Error for integer constant.
  726. if (HasSize)
  727. break;
  728. HasSize = true;
  729. // CUDA host and device may have different _Float16 support, therefore
  730. // allows f16 literals to avoid false alarm.
  731. // ToDo: more precise check for CUDA.
  732. if ((Target.hasFloat16Type() || LangOpts.CUDA) && s + 2 < ThisTokEnd &&
  733. s[1] == '1' && s[2] == '6') {
  734. s += 2; // success, eat up 2 characters.
  735. isFloat16 = true;
  736. continue;
  737. }
  738. isFloat = true;
  739. continue; // Success.
  740. case 'q': // FP Suffix for "__float128"
  741. case 'Q':
  742. if (!isFPConstant) break; // Error for integer constant.
  743. if (HasSize)
  744. break;
  745. HasSize = true;
  746. isFloat128 = true;
  747. continue; // Success.
  748. case 'u':
  749. case 'U':
  750. if (isFPConstant) break; // Error for floating constant.
  751. if (isUnsigned) break; // Cannot be repeated.
  752. isUnsigned = true;
  753. continue; // Success.
  754. case 'l':
  755. case 'L':
  756. if (HasSize)
  757. break;
  758. HasSize = true;
  759. // Check for long long. The L's need to be adjacent and the same case.
  760. if (s[1] == s[0]) {
  761. assert(s + 1 < ThisTokEnd && "didn't maximally munch?");
  762. if (isFPConstant) break; // long long invalid for floats.
  763. isLongLong = true;
  764. ++s; // Eat both of them.
  765. } else {
  766. isLong = true;
  767. }
  768. continue; // Success.
  769. case 'z':
  770. case 'Z':
  771. if (isFPConstant)
  772. break; // Invalid for floats.
  773. if (HasSize)
  774. break;
  775. HasSize = true;
  776. isSizeT = true;
  777. continue;
  778. case 'i':
  779. case 'I':
  780. if (LangOpts.MicrosoftExt && !isFPConstant) {
  781. // Allow i8, i16, i32, and i64. First, look ahead and check if
  782. // suffixes are Microsoft integers and not the imaginary unit.
  783. uint8_t Bits = 0;
  784. size_t ToSkip = 0;
  785. switch (s[1]) {
  786. case '8': // i8 suffix
  787. Bits = 8;
  788. ToSkip = 2;
  789. break;
  790. case '1':
  791. if (s[2] == '6') { // i16 suffix
  792. Bits = 16;
  793. ToSkip = 3;
  794. }
  795. break;
  796. case '3':
  797. if (s[2] == '2') { // i32 suffix
  798. Bits = 32;
  799. ToSkip = 3;
  800. }
  801. break;
  802. case '6':
  803. if (s[2] == '4') { // i64 suffix
  804. Bits = 64;
  805. ToSkip = 3;
  806. }
  807. break;
  808. default:
  809. break;
  810. }
  811. if (Bits) {
  812. if (HasSize)
  813. break;
  814. HasSize = true;
  815. MicrosoftInteger = Bits;
  816. s += ToSkip;
  817. assert(s <= ThisTokEnd && "didn't maximally munch?");
  818. break;
  819. }
  820. }
  821. LLVM_FALLTHROUGH;
  822. case 'j':
  823. case 'J':
  824. if (isImaginary) break; // Cannot be repeated.
  825. isImaginary = true;
  826. continue; // Success.
  827. }
  828. // If we reached here, there was an error or a ud-suffix.
  829. break;
  830. }
  831. // "i", "if", and "il" are user-defined suffixes in C++1y.
  832. if (s != ThisTokEnd || isImaginary) {
  833. // FIXME: Don't bother expanding UCNs if !tok.hasUCN().
  834. expandUCNs(UDSuffixBuf, StringRef(SuffixBegin, ThisTokEnd - SuffixBegin));
  835. if (isValidUDSuffix(LangOpts, UDSuffixBuf)) {
  836. if (!isImaginary) {
  837. // Any suffix pieces we might have parsed are actually part of the
  838. // ud-suffix.
  839. isLong = false;
  840. isUnsigned = false;
  841. isLongLong = false;
  842. isSizeT = false;
  843. isFloat = false;
  844. isFloat16 = false;
  845. isHalf = false;
  846. isImaginary = false;
  847. MicrosoftInteger = 0;
  848. saw_fixed_point_suffix = false;
  849. isFract = false;
  850. isAccum = false;
  851. }
  852. saw_ud_suffix = true;
  853. return;
  854. }
  855. if (s != ThisTokEnd) {
  856. // Report an error if there are any.
  857. Diags.Report(Lexer::AdvanceToTokenCharacter(
  858. TokLoc, SuffixBegin - ThisTokBegin, SM, LangOpts),
  859. diag::err_invalid_suffix_constant)
  860. << StringRef(SuffixBegin, ThisTokEnd - SuffixBegin)
  861. << (isFixedPointConstant ? 2 : isFPConstant);
  862. hadError = true;
  863. }
  864. }
  865. if (!hadError && saw_fixed_point_suffix) {
  866. assert(isFract || isAccum);
  867. }
  868. }
  869. /// ParseDecimalOrOctalCommon - This method is called for decimal or octal
  870. /// numbers. It issues an error for illegal digits, and handles floating point
  871. /// parsing. If it detects a floating point number, the radix is set to 10.
  872. void NumericLiteralParser::ParseDecimalOrOctalCommon(SourceLocation TokLoc){
  873. assert((radix == 8 || radix == 10) && "Unexpected radix");
  874. // If we have a hex digit other than 'e' (which denotes a FP exponent) then
  875. // the code is using an incorrect base.
  876. if (isHexDigit(*s) && *s != 'e' && *s != 'E' &&
  877. !isValidUDSuffix(LangOpts, StringRef(s, ThisTokEnd - s))) {
  878. Diags.Report(
  879. Lexer::AdvanceToTokenCharacter(TokLoc, s - ThisTokBegin, SM, LangOpts),
  880. diag::err_invalid_digit)
  881. << StringRef(s, 1) << (radix == 8 ? 1 : 0);
  882. hadError = true;
  883. return;
  884. }
  885. if (*s == '.') {
  886. checkSeparator(TokLoc, s, CSK_AfterDigits);
  887. s++;
  888. radix = 10;
  889. saw_period = true;
  890. checkSeparator(TokLoc, s, CSK_BeforeDigits);
  891. s = SkipDigits(s); // Skip suffix.
  892. }
  893. if (*s == 'e' || *s == 'E') { // exponent
  894. checkSeparator(TokLoc, s, CSK_AfterDigits);
  895. const char *Exponent = s;
  896. s++;
  897. radix = 10;
  898. saw_exponent = true;
  899. if (s != ThisTokEnd && (*s == '+' || *s == '-')) s++; // sign
  900. const char *first_non_digit = SkipDigits(s);
  901. if (containsDigits(s, first_non_digit)) {
  902. checkSeparator(TokLoc, s, CSK_BeforeDigits);
  903. s = first_non_digit;
  904. } else {
  905. if (!hadError) {
  906. Diags.Report(Lexer::AdvanceToTokenCharacter(
  907. TokLoc, Exponent - ThisTokBegin, SM, LangOpts),
  908. diag::err_exponent_has_no_digits);
  909. hadError = true;
  910. }
  911. return;
  912. }
  913. }
  914. }
  915. /// Determine whether a suffix is a valid ud-suffix. We avoid treating reserved
  916. /// suffixes as ud-suffixes, because the diagnostic experience is better if we
  917. /// treat it as an invalid suffix.
  918. bool NumericLiteralParser::isValidUDSuffix(const LangOptions &LangOpts,
  919. StringRef Suffix) {
  920. if (!LangOpts.CPlusPlus11 || Suffix.empty())
  921. return false;
  922. // By C++11 [lex.ext]p10, ud-suffixes starting with an '_' are always valid.
  923. if (Suffix[0] == '_')
  924. return true;
  925. // In C++11, there are no library suffixes.
  926. if (!LangOpts.CPlusPlus14)
  927. return false;
  928. // In C++14, "s", "h", "min", "ms", "us", and "ns" are used in the library.
  929. // Per tweaked N3660, "il", "i", and "if" are also used in the library.
  930. // In C++2a "d" and "y" are used in the library.
  931. return llvm::StringSwitch<bool>(Suffix)
  932. .Cases("h", "min", "s", true)
  933. .Cases("ms", "us", "ns", true)
  934. .Cases("il", "i", "if", true)
  935. .Cases("d", "y", LangOpts.CPlusPlus20)
  936. .Default(false);
  937. }
  938. void NumericLiteralParser::checkSeparator(SourceLocation TokLoc,
  939. const char *Pos,
  940. CheckSeparatorKind IsAfterDigits) {
  941. if (IsAfterDigits == CSK_AfterDigits) {
  942. if (Pos == ThisTokBegin)
  943. return;
  944. --Pos;
  945. } else if (Pos == ThisTokEnd)
  946. return;
  947. if (isDigitSeparator(*Pos)) {
  948. Diags.Report(Lexer::AdvanceToTokenCharacter(TokLoc, Pos - ThisTokBegin, SM,
  949. LangOpts),
  950. diag::err_digit_separator_not_between_digits)
  951. << IsAfterDigits;
  952. hadError = true;
  953. }
  954. }
  955. /// ParseNumberStartingWithZero - This method is called when the first character
  956. /// of the number is found to be a zero. This means it is either an octal
  957. /// number (like '04') or a hex number ('0x123a') a binary number ('0b1010') or
  958. /// a floating point number (01239.123e4). Eat the prefix, determining the
  959. /// radix etc.
  960. void NumericLiteralParser::ParseNumberStartingWithZero(SourceLocation TokLoc) {
  961. assert(s[0] == '0' && "Invalid method call");
  962. s++;
  963. int c1 = s[0];
  964. // Handle a hex number like 0x1234.
  965. if ((c1 == 'x' || c1 == 'X') && (isHexDigit(s[1]) || s[1] == '.')) {
  966. s++;
  967. assert(s < ThisTokEnd && "didn't maximally munch?");
  968. radix = 16;
  969. DigitsBegin = s;
  970. s = SkipHexDigits(s);
  971. bool HasSignificandDigits = containsDigits(DigitsBegin, s);
  972. if (s == ThisTokEnd) {
  973. // Done.
  974. } else if (*s == '.') {
  975. s++;
  976. saw_period = true;
  977. const char *floatDigitsBegin = s;
  978. s = SkipHexDigits(s);
  979. if (containsDigits(floatDigitsBegin, s))
  980. HasSignificandDigits = true;
  981. if (HasSignificandDigits)
  982. checkSeparator(TokLoc, floatDigitsBegin, CSK_BeforeDigits);
  983. }
  984. if (!HasSignificandDigits) {
  985. Diags.Report(Lexer::AdvanceToTokenCharacter(TokLoc, s - ThisTokBegin, SM,
  986. LangOpts),
  987. diag::err_hex_constant_requires)
  988. << LangOpts.CPlusPlus << 1;
  989. hadError = true;
  990. return;
  991. }
  992. // A binary exponent can appear with or with a '.'. If dotted, the
  993. // binary exponent is required.
  994. if (*s == 'p' || *s == 'P') {
  995. checkSeparator(TokLoc, s, CSK_AfterDigits);
  996. const char *Exponent = s;
  997. s++;
  998. saw_exponent = true;
  999. if (s != ThisTokEnd && (*s == '+' || *s == '-')) s++; // sign
  1000. const char *first_non_digit = SkipDigits(s);
  1001. if (!containsDigits(s, first_non_digit)) {
  1002. if (!hadError) {
  1003. Diags.Report(Lexer::AdvanceToTokenCharacter(
  1004. TokLoc, Exponent - ThisTokBegin, SM, LangOpts),
  1005. diag::err_exponent_has_no_digits);
  1006. hadError = true;
  1007. }
  1008. return;
  1009. }
  1010. checkSeparator(TokLoc, s, CSK_BeforeDigits);
  1011. s = first_non_digit;
  1012. if (!LangOpts.HexFloats)
  1013. Diags.Report(TokLoc, LangOpts.CPlusPlus
  1014. ? diag::ext_hex_literal_invalid
  1015. : diag::ext_hex_constant_invalid);
  1016. else if (LangOpts.CPlusPlus17)
  1017. Diags.Report(TokLoc, diag::warn_cxx17_hex_literal);
  1018. } else if (saw_period) {
  1019. Diags.Report(Lexer::AdvanceToTokenCharacter(TokLoc, s - ThisTokBegin, SM,
  1020. LangOpts),
  1021. diag::err_hex_constant_requires)
  1022. << LangOpts.CPlusPlus << 0;
  1023. hadError = true;
  1024. }
  1025. return;
  1026. }
  1027. // Handle simple binary numbers 0b01010
  1028. if ((c1 == 'b' || c1 == 'B') && (s[1] == '0' || s[1] == '1')) {
  1029. // 0b101010 is a C++1y / GCC extension.
  1030. Diags.Report(TokLoc, LangOpts.CPlusPlus14
  1031. ? diag::warn_cxx11_compat_binary_literal
  1032. : LangOpts.CPlusPlus ? diag::ext_binary_literal_cxx14
  1033. : diag::ext_binary_literal);
  1034. ++s;
  1035. assert(s < ThisTokEnd && "didn't maximally munch?");
  1036. radix = 2;
  1037. DigitsBegin = s;
  1038. s = SkipBinaryDigits(s);
  1039. if (s == ThisTokEnd) {
  1040. // Done.
  1041. } else if (isHexDigit(*s) &&
  1042. !isValidUDSuffix(LangOpts, StringRef(s, ThisTokEnd - s))) {
  1043. Diags.Report(Lexer::AdvanceToTokenCharacter(TokLoc, s - ThisTokBegin, SM,
  1044. LangOpts),
  1045. diag::err_invalid_digit)
  1046. << StringRef(s, 1) << 2;
  1047. hadError = true;
  1048. }
  1049. // Other suffixes will be diagnosed by the caller.
  1050. return;
  1051. }
  1052. // For now, the radix is set to 8. If we discover that we have a
  1053. // floating point constant, the radix will change to 10. Octal floating
  1054. // point constants are not permitted (only decimal and hexadecimal).
  1055. radix = 8;
  1056. DigitsBegin = s;
  1057. s = SkipOctalDigits(s);
  1058. if (s == ThisTokEnd)
  1059. return; // Done, simple octal number like 01234
  1060. // If we have some other non-octal digit that *is* a decimal digit, see if
  1061. // this is part of a floating point number like 094.123 or 09e1.
  1062. if (isDigit(*s)) {
  1063. const char *EndDecimal = SkipDigits(s);
  1064. if (EndDecimal[0] == '.' || EndDecimal[0] == 'e' || EndDecimal[0] == 'E') {
  1065. s = EndDecimal;
  1066. radix = 10;
  1067. }
  1068. }
  1069. ParseDecimalOrOctalCommon(TokLoc);
  1070. }
  1071. static bool alwaysFitsInto64Bits(unsigned Radix, unsigned NumDigits) {
  1072. switch (Radix) {
  1073. case 2:
  1074. return NumDigits <= 64;
  1075. case 8:
  1076. return NumDigits <= 64 / 3; // Digits are groups of 3 bits.
  1077. case 10:
  1078. return NumDigits <= 19; // floor(log10(2^64))
  1079. case 16:
  1080. return NumDigits <= 64 / 4; // Digits are groups of 4 bits.
  1081. default:
  1082. llvm_unreachable("impossible Radix");
  1083. }
  1084. }
  1085. /// GetIntegerValue - Convert this numeric literal value to an APInt that
  1086. /// matches Val's input width. If there is an overflow, set Val to the low bits
  1087. /// of the result and return true. Otherwise, return false.
  1088. bool NumericLiteralParser::GetIntegerValue(llvm::APInt &Val) {
  1089. // Fast path: Compute a conservative bound on the maximum number of
  1090. // bits per digit in this radix. If we can't possibly overflow a
  1091. // uint64 based on that bound then do the simple conversion to
  1092. // integer. This avoids the expensive overflow checking below, and
  1093. // handles the common cases that matter (small decimal integers and
  1094. // hex/octal values which don't overflow).
  1095. const unsigned NumDigits = SuffixBegin - DigitsBegin;
  1096. if (alwaysFitsInto64Bits(radix, NumDigits)) {
  1097. uint64_t N = 0;
  1098. for (const char *Ptr = DigitsBegin; Ptr != SuffixBegin; ++Ptr)
  1099. if (!isDigitSeparator(*Ptr))
  1100. N = N * radix + llvm::hexDigitValue(*Ptr);
  1101. // This will truncate the value to Val's input width. Simply check
  1102. // for overflow by comparing.
  1103. Val = N;
  1104. return Val.getZExtValue() != N;
  1105. }
  1106. Val = 0;
  1107. const char *Ptr = DigitsBegin;
  1108. llvm::APInt RadixVal(Val.getBitWidth(), radix);
  1109. llvm::APInt CharVal(Val.getBitWidth(), 0);
  1110. llvm::APInt OldVal = Val;
  1111. bool OverflowOccurred = false;
  1112. while (Ptr < SuffixBegin) {
  1113. if (isDigitSeparator(*Ptr)) {
  1114. ++Ptr;
  1115. continue;
  1116. }
  1117. unsigned C = llvm::hexDigitValue(*Ptr++);
  1118. // If this letter is out of bound for this radix, reject it.
  1119. assert(C < radix && "NumericLiteralParser ctor should have rejected this");
  1120. CharVal = C;
  1121. // Add the digit to the value in the appropriate radix. If adding in digits
  1122. // made the value smaller, then this overflowed.
  1123. OldVal = Val;
  1124. // Multiply by radix, did overflow occur on the multiply?
  1125. Val *= RadixVal;
  1126. OverflowOccurred |= Val.udiv(RadixVal) != OldVal;
  1127. // Add value, did overflow occur on the value?
  1128. // (a + b) ult b <=> overflow
  1129. Val += CharVal;
  1130. OverflowOccurred |= Val.ult(CharVal);
  1131. }
  1132. return OverflowOccurred;
  1133. }
  1134. llvm::APFloat::opStatus
  1135. NumericLiteralParser::GetFloatValue(llvm::APFloat &Result) {
  1136. using llvm::APFloat;
  1137. unsigned n = std::min(SuffixBegin - ThisTokBegin, ThisTokEnd - ThisTokBegin);
  1138. llvm::SmallString<16> Buffer;
  1139. StringRef Str(ThisTokBegin, n);
  1140. if (Str.contains('\'')) {
  1141. Buffer.reserve(n);
  1142. std::remove_copy_if(Str.begin(), Str.end(), std::back_inserter(Buffer),
  1143. &isDigitSeparator);
  1144. Str = Buffer;
  1145. }
  1146. auto StatusOrErr =
  1147. Result.convertFromString(Str, APFloat::rmNearestTiesToEven);
  1148. assert(StatusOrErr && "Invalid floating point representation");
  1149. return !errorToBool(StatusOrErr.takeError()) ? *StatusOrErr
  1150. : APFloat::opInvalidOp;
  1151. }
  1152. static inline bool IsExponentPart(char c) {
  1153. return c == 'p' || c == 'P' || c == 'e' || c == 'E';
  1154. }
  1155. bool NumericLiteralParser::GetFixedPointValue(llvm::APInt &StoreVal, unsigned Scale) {
  1156. assert(radix == 16 || radix == 10);
  1157. // Find how many digits are needed to store the whole literal.
  1158. unsigned NumDigits = SuffixBegin - DigitsBegin;
  1159. if (saw_period) --NumDigits;
  1160. // Initial scan of the exponent if it exists
  1161. bool ExpOverflowOccurred = false;
  1162. bool NegativeExponent = false;
  1163. const char *ExponentBegin;
  1164. uint64_t Exponent = 0;
  1165. int64_t BaseShift = 0;
  1166. if (saw_exponent) {
  1167. const char *Ptr = DigitsBegin;
  1168. while (!IsExponentPart(*Ptr)) ++Ptr;
  1169. ExponentBegin = Ptr;
  1170. ++Ptr;
  1171. NegativeExponent = *Ptr == '-';
  1172. if (NegativeExponent) ++Ptr;
  1173. unsigned NumExpDigits = SuffixBegin - Ptr;
  1174. if (alwaysFitsInto64Bits(radix, NumExpDigits)) {
  1175. llvm::StringRef ExpStr(Ptr, NumExpDigits);
  1176. llvm::APInt ExpInt(/*numBits=*/64, ExpStr, /*radix=*/10);
  1177. Exponent = ExpInt.getZExtValue();
  1178. } else {
  1179. ExpOverflowOccurred = true;
  1180. }
  1181. if (NegativeExponent) BaseShift -= Exponent;
  1182. else BaseShift += Exponent;
  1183. }
  1184. // Number of bits needed for decimal literal is
  1185. // ceil(NumDigits * log2(10)) Integral part
  1186. // + Scale Fractional part
  1187. // + ceil(Exponent * log2(10)) Exponent
  1188. // --------------------------------------------------
  1189. // ceil((NumDigits + Exponent) * log2(10)) + Scale
  1190. //
  1191. // But for simplicity in handling integers, we can round up log2(10) to 4,
  1192. // making:
  1193. // 4 * (NumDigits + Exponent) + Scale
  1194. //
  1195. // Number of digits needed for hexadecimal literal is
  1196. // 4 * NumDigits Integral part
  1197. // + Scale Fractional part
  1198. // + Exponent Exponent
  1199. // --------------------------------------------------
  1200. // (4 * NumDigits) + Scale + Exponent
  1201. uint64_t NumBitsNeeded;
  1202. if (radix == 10)
  1203. NumBitsNeeded = 4 * (NumDigits + Exponent) + Scale;
  1204. else
  1205. NumBitsNeeded = 4 * NumDigits + Exponent + Scale;
  1206. if (NumBitsNeeded > std::numeric_limits<unsigned>::max())
  1207. ExpOverflowOccurred = true;
  1208. llvm::APInt Val(static_cast<unsigned>(NumBitsNeeded), 0, /*isSigned=*/false);
  1209. bool FoundDecimal = false;
  1210. int64_t FractBaseShift = 0;
  1211. const char *End = saw_exponent ? ExponentBegin : SuffixBegin;
  1212. for (const char *Ptr = DigitsBegin; Ptr < End; ++Ptr) {
  1213. if (*Ptr == '.') {
  1214. FoundDecimal = true;
  1215. continue;
  1216. }
  1217. // Normal reading of an integer
  1218. unsigned C = llvm::hexDigitValue(*Ptr);
  1219. assert(C < radix && "NumericLiteralParser ctor should have rejected this");
  1220. Val *= radix;
  1221. Val += C;
  1222. if (FoundDecimal)
  1223. // Keep track of how much we will need to adjust this value by from the
  1224. // number of digits past the radix point.
  1225. --FractBaseShift;
  1226. }
  1227. // For a radix of 16, we will be multiplying by 2 instead of 16.
  1228. if (radix == 16) FractBaseShift *= 4;
  1229. BaseShift += FractBaseShift;
  1230. Val <<= Scale;
  1231. uint64_t Base = (radix == 16) ? 2 : 10;
  1232. if (BaseShift > 0) {
  1233. for (int64_t i = 0; i < BaseShift; ++i) {
  1234. Val *= Base;
  1235. }
  1236. } else if (BaseShift < 0) {
  1237. for (int64_t i = BaseShift; i < 0 && !Val.isZero(); ++i)
  1238. Val = Val.udiv(Base);
  1239. }
  1240. bool IntOverflowOccurred = false;
  1241. auto MaxVal = llvm::APInt::getMaxValue(StoreVal.getBitWidth());
  1242. if (Val.getBitWidth() > StoreVal.getBitWidth()) {
  1243. IntOverflowOccurred |= Val.ugt(MaxVal.zext(Val.getBitWidth()));
  1244. StoreVal = Val.trunc(StoreVal.getBitWidth());
  1245. } else if (Val.getBitWidth() < StoreVal.getBitWidth()) {
  1246. IntOverflowOccurred |= Val.zext(MaxVal.getBitWidth()).ugt(MaxVal);
  1247. StoreVal = Val.zext(StoreVal.getBitWidth());
  1248. } else {
  1249. StoreVal = Val;
  1250. }
  1251. return IntOverflowOccurred || ExpOverflowOccurred;
  1252. }
  1253. /// \verbatim
  1254. /// user-defined-character-literal: [C++11 lex.ext]
  1255. /// character-literal ud-suffix
  1256. /// ud-suffix:
  1257. /// identifier
  1258. /// character-literal: [C++11 lex.ccon]
  1259. /// ' c-char-sequence '
  1260. /// u' c-char-sequence '
  1261. /// U' c-char-sequence '
  1262. /// L' c-char-sequence '
  1263. /// u8' c-char-sequence ' [C++1z lex.ccon]
  1264. /// c-char-sequence:
  1265. /// c-char
  1266. /// c-char-sequence c-char
  1267. /// c-char:
  1268. /// any member of the source character set except the single-quote ',
  1269. /// backslash \, or new-line character
  1270. /// escape-sequence
  1271. /// universal-character-name
  1272. /// escape-sequence:
  1273. /// simple-escape-sequence
  1274. /// octal-escape-sequence
  1275. /// hexadecimal-escape-sequence
  1276. /// simple-escape-sequence:
  1277. /// one of \' \" \? \\ \a \b \f \n \r \t \v
  1278. /// octal-escape-sequence:
  1279. /// \ octal-digit
  1280. /// \ octal-digit octal-digit
  1281. /// \ octal-digit octal-digit octal-digit
  1282. /// hexadecimal-escape-sequence:
  1283. /// \x hexadecimal-digit
  1284. /// hexadecimal-escape-sequence hexadecimal-digit
  1285. /// universal-character-name: [C++11 lex.charset]
  1286. /// \u hex-quad
  1287. /// \U hex-quad hex-quad
  1288. /// hex-quad:
  1289. /// hex-digit hex-digit hex-digit hex-digit
  1290. /// \endverbatim
  1291. ///
  1292. CharLiteralParser::CharLiteralParser(const char *begin, const char *end,
  1293. SourceLocation Loc, Preprocessor &PP,
  1294. tok::TokenKind kind) {
  1295. // At this point we know that the character matches the regex "(L|u|U)?'.*'".
  1296. HadError = false;
  1297. Kind = kind;
  1298. const char *TokBegin = begin;
  1299. // Skip over wide character determinant.
  1300. if (Kind != tok::char_constant)
  1301. ++begin;
  1302. if (Kind == tok::utf8_char_constant)
  1303. ++begin;
  1304. // Skip over the entry quote.
  1305. if (begin[0] != '\'') {
  1306. PP.Diag(Loc, diag::err_lexing_char);
  1307. HadError = true;
  1308. return;
  1309. }
  1310. ++begin;
  1311. // Remove an optional ud-suffix.
  1312. if (end[-1] != '\'') {
  1313. const char *UDSuffixEnd = end;
  1314. do {
  1315. --end;
  1316. } while (end[-1] != '\'');
  1317. // FIXME: Don't bother with this if !tok.hasUCN().
  1318. expandUCNs(UDSuffixBuf, StringRef(end, UDSuffixEnd - end));
  1319. UDSuffixOffset = end - TokBegin;
  1320. }
  1321. // Trim the ending quote.
  1322. assert(end != begin && "Invalid token lexed");
  1323. --end;
  1324. // FIXME: The "Value" is an uint64_t so we can handle char literals of
  1325. // up to 64-bits.
  1326. // FIXME: This extensively assumes that 'char' is 8-bits.
  1327. assert(PP.getTargetInfo().getCharWidth() == 8 &&
  1328. "Assumes char is 8 bits");
  1329. assert(PP.getTargetInfo().getIntWidth() <= 64 &&
  1330. (PP.getTargetInfo().getIntWidth() & 7) == 0 &&
  1331. "Assumes sizeof(int) on target is <= 64 and a multiple of char");
  1332. assert(PP.getTargetInfo().getWCharWidth() <= 64 &&
  1333. "Assumes sizeof(wchar) on target is <= 64");
  1334. SmallVector<uint32_t, 4> codepoint_buffer;
  1335. codepoint_buffer.resize(end - begin);
  1336. uint32_t *buffer_begin = &codepoint_buffer.front();
  1337. uint32_t *buffer_end = buffer_begin + codepoint_buffer.size();
  1338. // Unicode escapes representing characters that cannot be correctly
  1339. // represented in a single code unit are disallowed in character literals
  1340. // by this implementation.
  1341. uint32_t largest_character_for_kind;
  1342. if (tok::wide_char_constant == Kind) {
  1343. largest_character_for_kind =
  1344. 0xFFFFFFFFu >> (32-PP.getTargetInfo().getWCharWidth());
  1345. } else if (tok::utf8_char_constant == Kind) {
  1346. largest_character_for_kind = 0x7F;
  1347. } else if (tok::utf16_char_constant == Kind) {
  1348. largest_character_for_kind = 0xFFFF;
  1349. } else if (tok::utf32_char_constant == Kind) {
  1350. largest_character_for_kind = 0x10FFFF;
  1351. } else {
  1352. largest_character_for_kind = 0x7Fu;
  1353. }
  1354. while (begin != end) {
  1355. // Is this a span of non-escape characters?
  1356. if (begin[0] != '\\') {
  1357. char const *start = begin;
  1358. do {
  1359. ++begin;
  1360. } while (begin != end && *begin != '\\');
  1361. char const *tmp_in_start = start;
  1362. uint32_t *tmp_out_start = buffer_begin;
  1363. llvm::ConversionResult res =
  1364. llvm::ConvertUTF8toUTF32(reinterpret_cast<llvm::UTF8 const **>(&start),
  1365. reinterpret_cast<llvm::UTF8 const *>(begin),
  1366. &buffer_begin, buffer_end, llvm::strictConversion);
  1367. if (res != llvm::conversionOK) {
  1368. // If we see bad encoding for unprefixed character literals, warn and
  1369. // simply copy the byte values, for compatibility with gcc and
  1370. // older versions of clang.
  1371. bool NoErrorOnBadEncoding = isAscii();
  1372. unsigned Msg = diag::err_bad_character_encoding;
  1373. if (NoErrorOnBadEncoding)
  1374. Msg = diag::warn_bad_character_encoding;
  1375. PP.Diag(Loc, Msg);
  1376. if (NoErrorOnBadEncoding) {
  1377. start = tmp_in_start;
  1378. buffer_begin = tmp_out_start;
  1379. for (; start != begin; ++start, ++buffer_begin)
  1380. *buffer_begin = static_cast<uint8_t>(*start);
  1381. } else {
  1382. HadError = true;
  1383. }
  1384. } else {
  1385. for (; tmp_out_start < buffer_begin; ++tmp_out_start) {
  1386. if (*tmp_out_start > largest_character_for_kind) {
  1387. HadError = true;
  1388. PP.Diag(Loc, diag::err_character_too_large);
  1389. }
  1390. }
  1391. }
  1392. continue;
  1393. }
  1394. // Is this a Universal Character Name escape?
  1395. if (begin[1] == 'u' || begin[1] == 'U') {
  1396. unsigned short UcnLen = 0;
  1397. if (!ProcessUCNEscape(TokBegin, begin, end, *buffer_begin, UcnLen,
  1398. FullSourceLoc(Loc, PP.getSourceManager()),
  1399. &PP.getDiagnostics(), PP.getLangOpts(), true)) {
  1400. HadError = true;
  1401. } else if (*buffer_begin > largest_character_for_kind) {
  1402. HadError = true;
  1403. PP.Diag(Loc, diag::err_character_too_large);
  1404. }
  1405. ++buffer_begin;
  1406. continue;
  1407. }
  1408. unsigned CharWidth = getCharWidth(Kind, PP.getTargetInfo());
  1409. uint64_t result =
  1410. ProcessCharEscape(TokBegin, begin, end, HadError,
  1411. FullSourceLoc(Loc,PP.getSourceManager()),
  1412. CharWidth, &PP.getDiagnostics(), PP.getLangOpts());
  1413. *buffer_begin++ = result;
  1414. }
  1415. unsigned NumCharsSoFar = buffer_begin - &codepoint_buffer.front();
  1416. if (NumCharsSoFar > 1) {
  1417. if (isAscii() && NumCharsSoFar == 4)
  1418. PP.Diag(Loc, diag::warn_four_char_character_literal);
  1419. else if (isAscii())
  1420. PP.Diag(Loc, diag::warn_multichar_character_literal);
  1421. else {
  1422. PP.Diag(Loc, diag::err_multichar_character_literal) << (isWide() ? 0 : 1);
  1423. HadError = true;
  1424. }
  1425. IsMultiChar = true;
  1426. } else {
  1427. IsMultiChar = false;
  1428. }
  1429. llvm::APInt LitVal(PP.getTargetInfo().getIntWidth(), 0);
  1430. // Narrow character literals act as though their value is concatenated
  1431. // in this implementation, but warn on overflow.
  1432. bool multi_char_too_long = false;
  1433. if (isAscii() && isMultiChar()) {
  1434. LitVal = 0;
  1435. for (size_t i = 0; i < NumCharsSoFar; ++i) {
  1436. // check for enough leading zeros to shift into
  1437. multi_char_too_long |= (LitVal.countLeadingZeros() < 8);
  1438. LitVal <<= 8;
  1439. LitVal = LitVal + (codepoint_buffer[i] & 0xFF);
  1440. }
  1441. } else if (NumCharsSoFar > 0) {
  1442. // otherwise just take the last character
  1443. LitVal = buffer_begin[-1];
  1444. }
  1445. if (!HadError && multi_char_too_long) {
  1446. PP.Diag(Loc, diag::warn_char_constant_too_large);
  1447. }
  1448. // Transfer the value from APInt to uint64_t
  1449. Value = LitVal.getZExtValue();
  1450. // If this is a single narrow character, sign extend it (e.g. '\xFF' is "-1")
  1451. // if 'char' is signed for this target (C99 6.4.4.4p10). Note that multiple
  1452. // character constants are not sign extended in the this implementation:
  1453. // '\xFF\xFF' = 65536 and '\x0\xFF' = 255, which matches GCC.
  1454. if (isAscii() && NumCharsSoFar == 1 && (Value & 128) &&
  1455. PP.getLangOpts().CharIsSigned)
  1456. Value = (signed char)Value;
  1457. }
  1458. /// \verbatim
  1459. /// string-literal: [C++0x lex.string]
  1460. /// encoding-prefix " [s-char-sequence] "
  1461. /// encoding-prefix R raw-string
  1462. /// encoding-prefix:
  1463. /// u8
  1464. /// u
  1465. /// U
  1466. /// L
  1467. /// s-char-sequence:
  1468. /// s-char
  1469. /// s-char-sequence s-char
  1470. /// s-char:
  1471. /// any member of the source character set except the double-quote ",
  1472. /// backslash \, or new-line character
  1473. /// escape-sequence
  1474. /// universal-character-name
  1475. /// raw-string:
  1476. /// " d-char-sequence ( r-char-sequence ) d-char-sequence "
  1477. /// r-char-sequence:
  1478. /// r-char
  1479. /// r-char-sequence r-char
  1480. /// r-char:
  1481. /// any member of the source character set, except a right parenthesis )
  1482. /// followed by the initial d-char-sequence (which may be empty)
  1483. /// followed by a double quote ".
  1484. /// d-char-sequence:
  1485. /// d-char
  1486. /// d-char-sequence d-char
  1487. /// d-char:
  1488. /// any member of the basic source character set except:
  1489. /// space, the left parenthesis (, the right parenthesis ),
  1490. /// the backslash \, and the control characters representing horizontal
  1491. /// tab, vertical tab, form feed, and newline.
  1492. /// escape-sequence: [C++0x lex.ccon]
  1493. /// simple-escape-sequence
  1494. /// octal-escape-sequence
  1495. /// hexadecimal-escape-sequence
  1496. /// simple-escape-sequence:
  1497. /// one of \' \" \? \\ \a \b \f \n \r \t \v
  1498. /// octal-escape-sequence:
  1499. /// \ octal-digit
  1500. /// \ octal-digit octal-digit
  1501. /// \ octal-digit octal-digit octal-digit
  1502. /// hexadecimal-escape-sequence:
  1503. /// \x hexadecimal-digit
  1504. /// hexadecimal-escape-sequence hexadecimal-digit
  1505. /// universal-character-name:
  1506. /// \u hex-quad
  1507. /// \U hex-quad hex-quad
  1508. /// hex-quad:
  1509. /// hex-digit hex-digit hex-digit hex-digit
  1510. /// \endverbatim
  1511. ///
  1512. StringLiteralParser::
  1513. StringLiteralParser(ArrayRef<Token> StringToks,
  1514. Preprocessor &PP)
  1515. : SM(PP.getSourceManager()), Features(PP.getLangOpts()),
  1516. Target(PP.getTargetInfo()), Diags(&PP.getDiagnostics()),
  1517. MaxTokenLength(0), SizeBound(0), CharByteWidth(0), Kind(tok::unknown),
  1518. ResultPtr(ResultBuf.data()), hadError(false), Pascal(false) {
  1519. init(StringToks);
  1520. }
  1521. void StringLiteralParser::init(ArrayRef<Token> StringToks){
  1522. // The literal token may have come from an invalid source location (e.g. due
  1523. // to a PCH error), in which case the token length will be 0.
  1524. if (StringToks.empty() || StringToks[0].getLength() < 2)
  1525. return DiagnoseLexingError(SourceLocation());
  1526. // Scan all of the string portions, remember the max individual token length,
  1527. // computing a bound on the concatenated string length, and see whether any
  1528. // piece is a wide-string. If any of the string portions is a wide-string
  1529. // literal, the result is a wide-string literal [C99 6.4.5p4].
  1530. assert(!StringToks.empty() && "expected at least one token");
  1531. MaxTokenLength = StringToks[0].getLength();
  1532. assert(StringToks[0].getLength() >= 2 && "literal token is invalid!");
  1533. SizeBound = StringToks[0].getLength()-2; // -2 for "".
  1534. Kind = StringToks[0].getKind();
  1535. hadError = false;
  1536. // Implement Translation Phase #6: concatenation of string literals
  1537. /// (C99 5.1.1.2p1). The common case is only one string fragment.
  1538. for (unsigned i = 1; i != StringToks.size(); ++i) {
  1539. if (StringToks[i].getLength() < 2)
  1540. return DiagnoseLexingError(StringToks[i].getLocation());
  1541. // The string could be shorter than this if it needs cleaning, but this is a
  1542. // reasonable bound, which is all we need.
  1543. assert(StringToks[i].getLength() >= 2 && "literal token is invalid!");
  1544. SizeBound += StringToks[i].getLength()-2; // -2 for "".
  1545. // Remember maximum string piece length.
  1546. if (StringToks[i].getLength() > MaxTokenLength)
  1547. MaxTokenLength = StringToks[i].getLength();
  1548. // Remember if we see any wide or utf-8/16/32 strings.
  1549. // Also check for illegal concatenations.
  1550. if (StringToks[i].isNot(Kind) && StringToks[i].isNot(tok::string_literal)) {
  1551. if (isAscii()) {
  1552. Kind = StringToks[i].getKind();
  1553. } else {
  1554. if (Diags)
  1555. Diags->Report(StringToks[i].getLocation(),
  1556. diag::err_unsupported_string_concat);
  1557. hadError = true;
  1558. }
  1559. }
  1560. }
  1561. // Include space for the null terminator.
  1562. ++SizeBound;
  1563. // TODO: K&R warning: "traditional C rejects string constant concatenation"
  1564. // Get the width in bytes of char/wchar_t/char16_t/char32_t
  1565. CharByteWidth = getCharWidth(Kind, Target);
  1566. assert((CharByteWidth & 7) == 0 && "Assumes character size is byte multiple");
  1567. CharByteWidth /= 8;
  1568. // The output buffer size needs to be large enough to hold wide characters.
  1569. // This is a worst-case assumption which basically corresponds to L"" "long".
  1570. SizeBound *= CharByteWidth;
  1571. // Size the temporary buffer to hold the result string data.
  1572. ResultBuf.resize(SizeBound);
  1573. // Likewise, but for each string piece.
  1574. SmallString<512> TokenBuf;
  1575. TokenBuf.resize(MaxTokenLength);
  1576. // Loop over all the strings, getting their spelling, and expanding them to
  1577. // wide strings as appropriate.
  1578. ResultPtr = &ResultBuf[0]; // Next byte to fill in.
  1579. Pascal = false;
  1580. SourceLocation UDSuffixTokLoc;
  1581. for (unsigned i = 0, e = StringToks.size(); i != e; ++i) {
  1582. const char *ThisTokBuf = &TokenBuf[0];
  1583. // Get the spelling of the token, which eliminates trigraphs, etc. We know
  1584. // that ThisTokBuf points to a buffer that is big enough for the whole token
  1585. // and 'spelled' tokens can only shrink.
  1586. bool StringInvalid = false;
  1587. unsigned ThisTokLen =
  1588. Lexer::getSpelling(StringToks[i], ThisTokBuf, SM, Features,
  1589. &StringInvalid);
  1590. if (StringInvalid)
  1591. return DiagnoseLexingError(StringToks[i].getLocation());
  1592. const char *ThisTokBegin = ThisTokBuf;
  1593. const char *ThisTokEnd = ThisTokBuf+ThisTokLen;
  1594. // Remove an optional ud-suffix.
  1595. if (ThisTokEnd[-1] != '"') {
  1596. const char *UDSuffixEnd = ThisTokEnd;
  1597. do {
  1598. --ThisTokEnd;
  1599. } while (ThisTokEnd[-1] != '"');
  1600. StringRef UDSuffix(ThisTokEnd, UDSuffixEnd - ThisTokEnd);
  1601. if (UDSuffixBuf.empty()) {
  1602. if (StringToks[i].hasUCN())
  1603. expandUCNs(UDSuffixBuf, UDSuffix);
  1604. else
  1605. UDSuffixBuf.assign(UDSuffix);
  1606. UDSuffixToken = i;
  1607. UDSuffixOffset = ThisTokEnd - ThisTokBuf;
  1608. UDSuffixTokLoc = StringToks[i].getLocation();
  1609. } else {
  1610. SmallString<32> ExpandedUDSuffix;
  1611. if (StringToks[i].hasUCN()) {
  1612. expandUCNs(ExpandedUDSuffix, UDSuffix);
  1613. UDSuffix = ExpandedUDSuffix;
  1614. }
  1615. // C++11 [lex.ext]p8: At the end of phase 6, if a string literal is the
  1616. // result of a concatenation involving at least one user-defined-string-
  1617. // literal, all the participating user-defined-string-literals shall
  1618. // have the same ud-suffix.
  1619. if (UDSuffixBuf != UDSuffix) {
  1620. if (Diags) {
  1621. SourceLocation TokLoc = StringToks[i].getLocation();
  1622. Diags->Report(TokLoc, diag::err_string_concat_mixed_suffix)
  1623. << UDSuffixBuf << UDSuffix
  1624. << SourceRange(UDSuffixTokLoc, UDSuffixTokLoc)
  1625. << SourceRange(TokLoc, TokLoc);
  1626. }
  1627. hadError = true;
  1628. }
  1629. }
  1630. }
  1631. // Strip the end quote.
  1632. --ThisTokEnd;
  1633. // TODO: Input character set mapping support.
  1634. // Skip marker for wide or unicode strings.
  1635. if (ThisTokBuf[0] == 'L' || ThisTokBuf[0] == 'u' || ThisTokBuf[0] == 'U') {
  1636. ++ThisTokBuf;
  1637. // Skip 8 of u8 marker for utf8 strings.
  1638. if (ThisTokBuf[0] == '8')
  1639. ++ThisTokBuf;
  1640. }
  1641. // Check for raw string
  1642. if (ThisTokBuf[0] == 'R') {
  1643. if (ThisTokBuf[1] != '"') {
  1644. // The file may have come from PCH and then changed after loading the
  1645. // PCH; Fail gracefully.
  1646. return DiagnoseLexingError(StringToks[i].getLocation());
  1647. }
  1648. ThisTokBuf += 2; // skip R"
  1649. // C++11 [lex.string]p2: A `d-char-sequence` shall consist of at most 16
  1650. // characters.
  1651. constexpr unsigned MaxRawStrDelimLen = 16;
  1652. const char *Prefix = ThisTokBuf;
  1653. while (static_cast<unsigned>(ThisTokBuf - Prefix) < MaxRawStrDelimLen &&
  1654. ThisTokBuf[0] != '(')
  1655. ++ThisTokBuf;
  1656. if (ThisTokBuf[0] != '(')
  1657. return DiagnoseLexingError(StringToks[i].getLocation());
  1658. ++ThisTokBuf; // skip '('
  1659. // Remove same number of characters from the end
  1660. ThisTokEnd -= ThisTokBuf - Prefix;
  1661. if (ThisTokEnd < ThisTokBuf)
  1662. return DiagnoseLexingError(StringToks[i].getLocation());
  1663. // C++14 [lex.string]p4: A source-file new-line in a raw string literal
  1664. // results in a new-line in the resulting execution string-literal.
  1665. StringRef RemainingTokenSpan(ThisTokBuf, ThisTokEnd - ThisTokBuf);
  1666. while (!RemainingTokenSpan.empty()) {
  1667. // Split the string literal on \r\n boundaries.
  1668. size_t CRLFPos = RemainingTokenSpan.find("\r\n");
  1669. StringRef BeforeCRLF = RemainingTokenSpan.substr(0, CRLFPos);
  1670. StringRef AfterCRLF = RemainingTokenSpan.substr(CRLFPos);
  1671. // Copy everything before the \r\n sequence into the string literal.
  1672. if (CopyStringFragment(StringToks[i], ThisTokBegin, BeforeCRLF))
  1673. hadError = true;
  1674. // Point into the \n inside the \r\n sequence and operate on the
  1675. // remaining portion of the literal.
  1676. RemainingTokenSpan = AfterCRLF.substr(1);
  1677. }
  1678. } else {
  1679. if (ThisTokBuf[0] != '"') {
  1680. // The file may have come from PCH and then changed after loading the
  1681. // PCH; Fail gracefully.
  1682. return DiagnoseLexingError(StringToks[i].getLocation());
  1683. }
  1684. ++ThisTokBuf; // skip "
  1685. // Check if this is a pascal string
  1686. if (Features.PascalStrings && ThisTokBuf + 1 != ThisTokEnd &&
  1687. ThisTokBuf[0] == '\\' && ThisTokBuf[1] == 'p') {
  1688. // If the \p sequence is found in the first token, we have a pascal string
  1689. // Otherwise, if we already have a pascal string, ignore the first \p
  1690. if (i == 0) {
  1691. ++ThisTokBuf;
  1692. Pascal = true;
  1693. } else if (Pascal)
  1694. ThisTokBuf += 2;
  1695. }
  1696. while (ThisTokBuf != ThisTokEnd) {
  1697. // Is this a span of non-escape characters?
  1698. if (ThisTokBuf[0] != '\\') {
  1699. const char *InStart = ThisTokBuf;
  1700. do {
  1701. ++ThisTokBuf;
  1702. } while (ThisTokBuf != ThisTokEnd && ThisTokBuf[0] != '\\');
  1703. // Copy the character span over.
  1704. if (CopyStringFragment(StringToks[i], ThisTokBegin,
  1705. StringRef(InStart, ThisTokBuf - InStart)))
  1706. hadError = true;
  1707. continue;
  1708. }
  1709. // Is this a Universal Character Name escape?
  1710. if (ThisTokBuf[1] == 'u' || ThisTokBuf[1] == 'U') {
  1711. EncodeUCNEscape(ThisTokBegin, ThisTokBuf, ThisTokEnd,
  1712. ResultPtr, hadError,
  1713. FullSourceLoc(StringToks[i].getLocation(), SM),
  1714. CharByteWidth, Diags, Features);
  1715. continue;
  1716. }
  1717. // Otherwise, this is a non-UCN escape character. Process it.
  1718. unsigned ResultChar =
  1719. ProcessCharEscape(ThisTokBegin, ThisTokBuf, ThisTokEnd, hadError,
  1720. FullSourceLoc(StringToks[i].getLocation(), SM),
  1721. CharByteWidth*8, Diags, Features);
  1722. if (CharByteWidth == 4) {
  1723. // FIXME: Make the type of the result buffer correct instead of
  1724. // using reinterpret_cast.
  1725. llvm::UTF32 *ResultWidePtr = reinterpret_cast<llvm::UTF32*>(ResultPtr);
  1726. *ResultWidePtr = ResultChar;
  1727. ResultPtr += 4;
  1728. } else if (CharByteWidth == 2) {
  1729. // FIXME: Make the type of the result buffer correct instead of
  1730. // using reinterpret_cast.
  1731. llvm::UTF16 *ResultWidePtr = reinterpret_cast<llvm::UTF16*>(ResultPtr);
  1732. *ResultWidePtr = ResultChar & 0xFFFF;
  1733. ResultPtr += 2;
  1734. } else {
  1735. assert(CharByteWidth == 1 && "Unexpected char width");
  1736. *ResultPtr++ = ResultChar & 0xFF;
  1737. }
  1738. }
  1739. }
  1740. }
  1741. if (Pascal) {
  1742. if (CharByteWidth == 4) {
  1743. // FIXME: Make the type of the result buffer correct instead of
  1744. // using reinterpret_cast.
  1745. llvm::UTF32 *ResultWidePtr = reinterpret_cast<llvm::UTF32*>(ResultBuf.data());
  1746. ResultWidePtr[0] = GetNumStringChars() - 1;
  1747. } else if (CharByteWidth == 2) {
  1748. // FIXME: Make the type of the result buffer correct instead of
  1749. // using reinterpret_cast.
  1750. llvm::UTF16 *ResultWidePtr = reinterpret_cast<llvm::UTF16*>(ResultBuf.data());
  1751. ResultWidePtr[0] = GetNumStringChars() - 1;
  1752. } else {
  1753. assert(CharByteWidth == 1 && "Unexpected char width");
  1754. ResultBuf[0] = GetNumStringChars() - 1;
  1755. }
  1756. // Verify that pascal strings aren't too large.
  1757. if (GetStringLength() > 256) {
  1758. if (Diags)
  1759. Diags->Report(StringToks.front().getLocation(),
  1760. diag::err_pascal_string_too_long)
  1761. << SourceRange(StringToks.front().getLocation(),
  1762. StringToks.back().getLocation());
  1763. hadError = true;
  1764. return;
  1765. }
  1766. } else if (Diags) {
  1767. // Complain if this string literal has too many characters.
  1768. unsigned MaxChars = Features.CPlusPlus? 65536 : Features.C99 ? 4095 : 509;
  1769. if (GetNumStringChars() > MaxChars)
  1770. Diags->Report(StringToks.front().getLocation(),
  1771. diag::ext_string_too_long)
  1772. << GetNumStringChars() << MaxChars
  1773. << (Features.CPlusPlus ? 2 : Features.C99 ? 1 : 0)
  1774. << SourceRange(StringToks.front().getLocation(),
  1775. StringToks.back().getLocation());
  1776. }
  1777. }
  1778. static const char *resyncUTF8(const char *Err, const char *End) {
  1779. if (Err == End)
  1780. return End;
  1781. End = Err + std::min<unsigned>(llvm::getNumBytesForUTF8(*Err), End-Err);
  1782. while (++Err != End && (*Err & 0xC0) == 0x80)
  1783. ;
  1784. return Err;
  1785. }
  1786. /// This function copies from Fragment, which is a sequence of bytes
  1787. /// within Tok's contents (which begin at TokBegin) into ResultPtr.
  1788. /// Performs widening for multi-byte characters.
  1789. bool StringLiteralParser::CopyStringFragment(const Token &Tok,
  1790. const char *TokBegin,
  1791. StringRef Fragment) {
  1792. const llvm::UTF8 *ErrorPtrTmp;
  1793. if (ConvertUTF8toWide(CharByteWidth, Fragment, ResultPtr, ErrorPtrTmp))
  1794. return false;
  1795. // If we see bad encoding for unprefixed string literals, warn and
  1796. // simply copy the byte values, for compatibility with gcc and older
  1797. // versions of clang.
  1798. bool NoErrorOnBadEncoding = isAscii();
  1799. if (NoErrorOnBadEncoding) {
  1800. memcpy(ResultPtr, Fragment.data(), Fragment.size());
  1801. ResultPtr += Fragment.size();
  1802. }
  1803. if (Diags) {
  1804. const char *ErrorPtr = reinterpret_cast<const char *>(ErrorPtrTmp);
  1805. FullSourceLoc SourceLoc(Tok.getLocation(), SM);
  1806. const DiagnosticBuilder &Builder =
  1807. Diag(Diags, Features, SourceLoc, TokBegin,
  1808. ErrorPtr, resyncUTF8(ErrorPtr, Fragment.end()),
  1809. NoErrorOnBadEncoding ? diag::warn_bad_string_encoding
  1810. : diag::err_bad_string_encoding);
  1811. const char *NextStart = resyncUTF8(ErrorPtr, Fragment.end());
  1812. StringRef NextFragment(NextStart, Fragment.end()-NextStart);
  1813. // Decode into a dummy buffer.
  1814. SmallString<512> Dummy;
  1815. Dummy.reserve(Fragment.size() * CharByteWidth);
  1816. char *Ptr = Dummy.data();
  1817. while (!ConvertUTF8toWide(CharByteWidth, NextFragment, Ptr, ErrorPtrTmp)) {
  1818. const char *ErrorPtr = reinterpret_cast<const char *>(ErrorPtrTmp);
  1819. NextStart = resyncUTF8(ErrorPtr, Fragment.end());
  1820. Builder << MakeCharSourceRange(Features, SourceLoc, TokBegin,
  1821. ErrorPtr, NextStart);
  1822. NextFragment = StringRef(NextStart, Fragment.end()-NextStart);
  1823. }
  1824. }
  1825. return !NoErrorOnBadEncoding;
  1826. }
  1827. void StringLiteralParser::DiagnoseLexingError(SourceLocation Loc) {
  1828. hadError = true;
  1829. if (Diags)
  1830. Diags->Report(Loc, diag::err_lexing_string);
  1831. }
  1832. /// getOffsetOfStringByte - This function returns the offset of the
  1833. /// specified byte of the string data represented by Token. This handles
  1834. /// advancing over escape sequences in the string.
  1835. unsigned StringLiteralParser::getOffsetOfStringByte(const Token &Tok,
  1836. unsigned ByteNo) const {
  1837. // Get the spelling of the token.
  1838. SmallString<32> SpellingBuffer;
  1839. SpellingBuffer.resize(Tok.getLength());
  1840. bool StringInvalid = false;
  1841. const char *SpellingPtr = &SpellingBuffer[0];
  1842. unsigned TokLen = Lexer::getSpelling(Tok, SpellingPtr, SM, Features,
  1843. &StringInvalid);
  1844. if (StringInvalid)
  1845. return 0;
  1846. const char *SpellingStart = SpellingPtr;
  1847. const char *SpellingEnd = SpellingPtr+TokLen;
  1848. // Handle UTF-8 strings just like narrow strings.
  1849. if (SpellingPtr[0] == 'u' && SpellingPtr[1] == '8')
  1850. SpellingPtr += 2;
  1851. assert(SpellingPtr[0] != 'L' && SpellingPtr[0] != 'u' &&
  1852. SpellingPtr[0] != 'U' && "Doesn't handle wide or utf strings yet");
  1853. // For raw string literals, this is easy.
  1854. if (SpellingPtr[0] == 'R') {
  1855. assert(SpellingPtr[1] == '"' && "Should be a raw string literal!");
  1856. // Skip 'R"'.
  1857. SpellingPtr += 2;
  1858. while (*SpellingPtr != '(') {
  1859. ++SpellingPtr;
  1860. assert(SpellingPtr < SpellingEnd && "Missing ( for raw string literal");
  1861. }
  1862. // Skip '('.
  1863. ++SpellingPtr;
  1864. return SpellingPtr - SpellingStart + ByteNo;
  1865. }
  1866. // Skip over the leading quote
  1867. assert(SpellingPtr[0] == '"' && "Should be a string literal!");
  1868. ++SpellingPtr;
  1869. // Skip over bytes until we find the offset we're looking for.
  1870. while (ByteNo) {
  1871. assert(SpellingPtr < SpellingEnd && "Didn't find byte offset!");
  1872. // Step over non-escapes simply.
  1873. if (*SpellingPtr != '\\') {
  1874. ++SpellingPtr;
  1875. --ByteNo;
  1876. continue;
  1877. }
  1878. // Otherwise, this is an escape character. Advance over it.
  1879. bool HadError = false;
  1880. if (SpellingPtr[1] == 'u' || SpellingPtr[1] == 'U') {
  1881. const char *EscapePtr = SpellingPtr;
  1882. unsigned Len = MeasureUCNEscape(SpellingStart, SpellingPtr, SpellingEnd,
  1883. 1, Features, HadError);
  1884. if (Len > ByteNo) {
  1885. // ByteNo is somewhere within the escape sequence.
  1886. SpellingPtr = EscapePtr;
  1887. break;
  1888. }
  1889. ByteNo -= Len;
  1890. } else {
  1891. ProcessCharEscape(SpellingStart, SpellingPtr, SpellingEnd, HadError,
  1892. FullSourceLoc(Tok.getLocation(), SM),
  1893. CharByteWidth*8, Diags, Features);
  1894. --ByteNo;
  1895. }
  1896. assert(!HadError && "This method isn't valid on erroneous strings");
  1897. }
  1898. return SpellingPtr-SpellingStart;
  1899. }
  1900. /// Determine whether a suffix is a valid ud-suffix. We avoid treating reserved
  1901. /// suffixes as ud-suffixes, because the diagnostic experience is better if we
  1902. /// treat it as an invalid suffix.
  1903. bool StringLiteralParser::isValidUDSuffix(const LangOptions &LangOpts,
  1904. StringRef Suffix) {
  1905. return NumericLiteralParser::isValidUDSuffix(LangOpts, Suffix) ||
  1906. Suffix == "sv";
  1907. }