LiteralSupport.cpp 64 KB

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