LiteralSupport.cpp 64 KB

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