charset.cc 77 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510
  1. /* CPP Library - charsets
  2. Copyright (C) 1998-2022 Free Software Foundation, Inc.
  3. Broken out of c-lex.cc Apr 2003, adding valid C99 UCN ranges.
  4. This program is free software; you can redistribute it and/or modify it
  5. under the terms of the GNU General Public License as published by the
  6. Free Software Foundation; either version 3, or (at your option) any
  7. later version.
  8. This program is distributed in the hope that it will be useful,
  9. but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. GNU General Public License for more details.
  12. You should have received a copy of the GNU General Public License
  13. along with this program; see the file COPYING3. If not see
  14. <http://www.gnu.org/licenses/>. */
  15. #include "config.h"
  16. #include "system.h"
  17. #include "cpplib.h"
  18. #include "internal.h"
  19. /* Character set handling for C-family languages.
  20. Terminological note: In what follows, "charset" or "character set"
  21. will be taken to mean both an abstract set of characters and an
  22. encoding for that set.
  23. The C99 standard discusses two character sets: source and execution.
  24. The source character set is used for internal processing in translation
  25. phases 1 through 4; the execution character set is used thereafter.
  26. Both are required by 5.2.1.2p1 to be multibyte encodings, not wide
  27. character encodings (see 3.7.2, 3.7.3 for the standardese meanings
  28. of these terms). Furthermore, the "basic character set" (listed in
  29. 5.2.1p3) is to be encoded in each with values one byte wide, and is
  30. to appear in the initial shift state.
  31. It is not explicitly mentioned, but there is also a "wide execution
  32. character set" used to encode wide character constants and wide
  33. string literals; this is supposed to be the result of applying the
  34. standard library function mbstowcs() to an equivalent narrow string
  35. (6.4.5p5). However, the behavior of hexadecimal and octal
  36. \-escapes is at odds with this; they are supposed to be translated
  37. directly to wchar_t values (6.4.4.4p5,6).
  38. The source character set is not necessarily the character set used
  39. to encode physical source files on disk; translation phase 1 converts
  40. from whatever that encoding is to the source character set.
  41. The presence of universal character names in C99 (6.4.3 et seq.)
  42. forces the source character set to be isomorphic to ISO 10646,
  43. that is, Unicode. There is no such constraint on the execution
  44. character set; note also that the conversion from source to
  45. execution character set does not occur for identifiers (5.1.1.2p1#5).
  46. For convenience of implementation, the source character set's
  47. encoding of the basic character set should be identical to the
  48. execution character set OF THE HOST SYSTEM's encoding of the basic
  49. character set, and it should not be a state-dependent encoding.
  50. cpplib uses UTF-8 or UTF-EBCDIC for the source character set,
  51. depending on whether the host is based on ASCII or EBCDIC (see
  52. respectively Unicode section 2.3/ISO10646 Amendment 2, and Unicode
  53. Technical Report #16). With limited exceptions, it relies on the
  54. system library's iconv() primitive to do charset conversion
  55. (specified in SUSv2). */
  56. #if !HAVE_ICONV
  57. /* Make certain that the uses of iconv(), iconv_open(), iconv_close()
  58. below, which are guarded only by if statements with compile-time
  59. constant conditions, do not cause link errors. */
  60. #define iconv_open(x, y) (errno = EINVAL, (iconv_t)-1)
  61. #define iconv(a,b,c,d,e) (errno = EINVAL, (size_t)-1)
  62. #define iconv_close(x) (void)0
  63. #define ICONV_CONST
  64. #endif
  65. #if HOST_CHARSET == HOST_CHARSET_ASCII
  66. #define SOURCE_CHARSET "UTF-8"
  67. #define LAST_POSSIBLY_BASIC_SOURCE_CHAR 0x7e
  68. #elif HOST_CHARSET == HOST_CHARSET_EBCDIC
  69. #define SOURCE_CHARSET "UTF-EBCDIC"
  70. #define LAST_POSSIBLY_BASIC_SOURCE_CHAR 0xFF
  71. #else
  72. #error "Unrecognized basic host character set"
  73. #endif
  74. #ifndef EILSEQ
  75. #define EILSEQ EINVAL
  76. #endif
  77. /* This structure is used for a resizable string buffer throughout. */
  78. /* Don't call it strbuf, as that conflicts with unistd.h on systems
  79. such as DYNIX/ptx where unistd.h includes stropts.h. */
  80. struct _cpp_strbuf
  81. {
  82. uchar *text;
  83. size_t asize;
  84. size_t len;
  85. };
  86. /* This is enough to hold any string that fits on a single 80-column
  87. line, even if iconv quadruples its size (e.g. conversion from
  88. ASCII to UTF-32) rounded up to a power of two. */
  89. #define OUTBUF_BLOCK_SIZE 256
  90. /* Conversions between UTF-8 and UTF-16/32 are implemented by custom
  91. logic. This is because a depressing number of systems lack iconv,
  92. or have have iconv libraries that do not do these conversions, so
  93. we need a fallback implementation for them. To ensure the fallback
  94. doesn't break due to neglect, it is used on all systems.
  95. UTF-32 encoding is nice and simple: a four-byte binary number,
  96. constrained to the range 00000000-7FFFFFFF to avoid questions of
  97. signedness. We do have to cope with big- and little-endian
  98. variants.
  99. UTF-16 encoding uses two-byte binary numbers, again in big- and
  100. little-endian variants, for all values in the 00000000-0000FFFF
  101. range. Values in the 00010000-0010FFFF range are encoded as pairs
  102. of two-byte numbers, called "surrogate pairs": given a number S in
  103. this range, it is mapped to a pair (H, L) as follows:
  104. H = (S - 0x10000) / 0x400 + 0xD800
  105. L = (S - 0x10000) % 0x400 + 0xDC00
  106. Two-byte values in the D800...DFFF range are ill-formed except as a
  107. component of a surrogate pair. Even if the encoding within a
  108. two-byte value is little-endian, the H member of the surrogate pair
  109. comes first.
  110. There is no way to encode values in the 00110000-7FFFFFFF range,
  111. which is not currently a problem as there are no assigned code
  112. points in that range; however, the author expects that it will
  113. eventually become necessary to abandon UTF-16 due to this
  114. limitation. Note also that, because of these pairs, UTF-16 does
  115. not meet the requirements of the C standard for a wide character
  116. encoding (see 3.7.3 and 6.4.4.4p11).
  117. UTF-8 encoding looks like this:
  118. value range encoded as
  119. 00000000-0000007F 0xxxxxxx
  120. 00000080-000007FF 110xxxxx 10xxxxxx
  121. 00000800-0000FFFF 1110xxxx 10xxxxxx 10xxxxxx
  122. 00010000-001FFFFF 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
  123. 00200000-03FFFFFF 111110xx 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx
  124. 04000000-7FFFFFFF 1111110x 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx
  125. Values in the 0000D800 ... 0000DFFF range (surrogates) are invalid,
  126. which means that three-byte sequences ED xx yy, with A0 <= xx <= BF,
  127. never occur. Note also that any value that can be encoded by a
  128. given row of the table can also be encoded by all successive rows,
  129. but this is not done; only the shortest possible encoding for any
  130. given value is valid. For instance, the character 07C0 could be
  131. encoded as any of DF 80, E0 9F 80, F0 80 9F 80, F8 80 80 9F 80, or
  132. FC 80 80 80 9F 80. Only the first is valid.
  133. An implementation note: the transformation from UTF-16 to UTF-8, or
  134. vice versa, is easiest done by using UTF-32 as an intermediary. */
  135. /* Internal primitives which go from an UTF-8 byte stream to native-endian
  136. UTF-32 in a cppchar_t, or vice versa; this avoids an extra marshal/unmarshal
  137. operation in several places below. */
  138. static inline int
  139. one_utf8_to_cppchar (const uchar **inbufp, size_t *inbytesleftp,
  140. cppchar_t *cp)
  141. {
  142. static const uchar masks[6] = { 0x7F, 0x1F, 0x0F, 0x07, 0x03, 0x01 };
  143. static const uchar patns[6] = { 0x00, 0xC0, 0xE0, 0xF0, 0xF8, 0xFC };
  144. cppchar_t c;
  145. const uchar *inbuf = *inbufp;
  146. size_t nbytes, i;
  147. if (*inbytesleftp < 1)
  148. return EINVAL;
  149. c = *inbuf;
  150. if (c < 0x80)
  151. {
  152. *cp = c;
  153. *inbytesleftp -= 1;
  154. *inbufp += 1;
  155. return 0;
  156. }
  157. /* The number of leading 1-bits in the first byte indicates how many
  158. bytes follow. */
  159. for (nbytes = 2; nbytes < 7; nbytes++)
  160. if ((c & ~masks[nbytes-1]) == patns[nbytes-1])
  161. goto found;
  162. return EILSEQ;
  163. found:
  164. if (*inbytesleftp < nbytes)
  165. return EINVAL;
  166. c = (c & masks[nbytes-1]);
  167. inbuf++;
  168. for (i = 1; i < nbytes; i++)
  169. {
  170. cppchar_t n = *inbuf++;
  171. if ((n & 0xC0) != 0x80)
  172. return EILSEQ;
  173. c = ((c << 6) + (n & 0x3F));
  174. }
  175. /* Make sure the shortest possible encoding was used. */
  176. if (c <= 0x7F && nbytes > 1) return EILSEQ;
  177. if (c <= 0x7FF && nbytes > 2) return EILSEQ;
  178. if (c <= 0xFFFF && nbytes > 3) return EILSEQ;
  179. if (c <= 0x1FFFFF && nbytes > 4) return EILSEQ;
  180. if (c <= 0x3FFFFFF && nbytes > 5) return EILSEQ;
  181. /* Make sure the character is valid. */
  182. if (c > 0x7FFFFFFF || (c >= 0xD800 && c <= 0xDFFF)) return EILSEQ;
  183. *cp = c;
  184. *inbufp = inbuf;
  185. *inbytesleftp -= nbytes;
  186. return 0;
  187. }
  188. static inline int
  189. one_cppchar_to_utf8 (cppchar_t c, uchar **outbufp, size_t *outbytesleftp)
  190. {
  191. static const uchar masks[6] = { 0x00, 0xC0, 0xE0, 0xF0, 0xF8, 0xFC };
  192. static const uchar limits[6] = { 0x80, 0xE0, 0xF0, 0xF8, 0xFC, 0xFE };
  193. size_t nbytes;
  194. uchar buf[6], *p = &buf[6];
  195. uchar *outbuf = *outbufp;
  196. nbytes = 1;
  197. if (c < 0x80)
  198. *--p = c;
  199. else
  200. {
  201. do
  202. {
  203. *--p = ((c & 0x3F) | 0x80);
  204. c >>= 6;
  205. nbytes++;
  206. }
  207. while (c >= 0x3F || (c & limits[nbytes-1]));
  208. *--p = (c | masks[nbytes-1]);
  209. }
  210. if (*outbytesleftp < nbytes)
  211. return E2BIG;
  212. while (p < &buf[6])
  213. *outbuf++ = *p++;
  214. *outbytesleftp -= nbytes;
  215. *outbufp = outbuf;
  216. return 0;
  217. }
  218. /* The following four functions transform one character between the two
  219. encodings named in the function name. All have the signature
  220. int (*)(iconv_t bigend, const uchar **inbufp, size_t *inbytesleftp,
  221. uchar **outbufp, size_t *outbytesleftp)
  222. BIGEND must have the value 0 or 1, coerced to (iconv_t); it is
  223. interpreted as a boolean indicating whether big-endian or
  224. little-endian encoding is to be used for the member of the pair
  225. that is not UTF-8.
  226. INBUFP, INBYTESLEFTP, OUTBUFP, OUTBYTESLEFTP work exactly as they
  227. do for iconv.
  228. The return value is either 0 for success, or an errno value for
  229. failure, which may be E2BIG (need more space), EILSEQ (ill-formed
  230. input sequence), ir EINVAL (incomplete input sequence). */
  231. static inline int
  232. one_utf8_to_utf32 (iconv_t bigend, const uchar **inbufp, size_t *inbytesleftp,
  233. uchar **outbufp, size_t *outbytesleftp)
  234. {
  235. uchar *outbuf;
  236. cppchar_t s = 0;
  237. int rval;
  238. /* Check for space first, since we know exactly how much we need. */
  239. if (*outbytesleftp < 4)
  240. return E2BIG;
  241. rval = one_utf8_to_cppchar (inbufp, inbytesleftp, &s);
  242. if (rval)
  243. return rval;
  244. outbuf = *outbufp;
  245. outbuf[bigend ? 3 : 0] = (s & 0x000000FF);
  246. outbuf[bigend ? 2 : 1] = (s & 0x0000FF00) >> 8;
  247. outbuf[bigend ? 1 : 2] = (s & 0x00FF0000) >> 16;
  248. outbuf[bigend ? 0 : 3] = (s & 0xFF000000) >> 24;
  249. *outbufp += 4;
  250. *outbytesleftp -= 4;
  251. return 0;
  252. }
  253. static inline int
  254. one_utf32_to_utf8 (iconv_t bigend, const uchar **inbufp, size_t *inbytesleftp,
  255. uchar **outbufp, size_t *outbytesleftp)
  256. {
  257. cppchar_t s;
  258. int rval;
  259. const uchar *inbuf;
  260. if (*inbytesleftp < 4)
  261. return EINVAL;
  262. inbuf = *inbufp;
  263. s = inbuf[bigend ? 0 : 3] << 24;
  264. s += inbuf[bigend ? 1 : 2] << 16;
  265. s += inbuf[bigend ? 2 : 1] << 8;
  266. s += inbuf[bigend ? 3 : 0];
  267. if (s >= 0x7FFFFFFF || (s >= 0xD800 && s <= 0xDFFF))
  268. return EILSEQ;
  269. rval = one_cppchar_to_utf8 (s, outbufp, outbytesleftp);
  270. if (rval)
  271. return rval;
  272. *inbufp += 4;
  273. *inbytesleftp -= 4;
  274. return 0;
  275. }
  276. static inline int
  277. one_utf8_to_utf16 (iconv_t bigend, const uchar **inbufp, size_t *inbytesleftp,
  278. uchar **outbufp, size_t *outbytesleftp)
  279. {
  280. int rval;
  281. cppchar_t s = 0;
  282. const uchar *save_inbuf = *inbufp;
  283. size_t save_inbytesleft = *inbytesleftp;
  284. uchar *outbuf = *outbufp;
  285. rval = one_utf8_to_cppchar (inbufp, inbytesleftp, &s);
  286. if (rval)
  287. return rval;
  288. if (s > 0x0010FFFF)
  289. {
  290. *inbufp = save_inbuf;
  291. *inbytesleftp = save_inbytesleft;
  292. return EILSEQ;
  293. }
  294. if (s <= 0xFFFF)
  295. {
  296. if (*outbytesleftp < 2)
  297. {
  298. *inbufp = save_inbuf;
  299. *inbytesleftp = save_inbytesleft;
  300. return E2BIG;
  301. }
  302. outbuf[bigend ? 1 : 0] = (s & 0x00FF);
  303. outbuf[bigend ? 0 : 1] = (s & 0xFF00) >> 8;
  304. *outbufp += 2;
  305. *outbytesleftp -= 2;
  306. return 0;
  307. }
  308. else
  309. {
  310. cppchar_t hi, lo;
  311. if (*outbytesleftp < 4)
  312. {
  313. *inbufp = save_inbuf;
  314. *inbytesleftp = save_inbytesleft;
  315. return E2BIG;
  316. }
  317. hi = (s - 0x10000) / 0x400 + 0xD800;
  318. lo = (s - 0x10000) % 0x400 + 0xDC00;
  319. /* Even if we are little-endian, put the high surrogate first.
  320. ??? Matches practice? */
  321. outbuf[bigend ? 1 : 0] = (hi & 0x00FF);
  322. outbuf[bigend ? 0 : 1] = (hi & 0xFF00) >> 8;
  323. outbuf[bigend ? 3 : 2] = (lo & 0x00FF);
  324. outbuf[bigend ? 2 : 3] = (lo & 0xFF00) >> 8;
  325. *outbufp += 4;
  326. *outbytesleftp -= 4;
  327. return 0;
  328. }
  329. }
  330. static inline int
  331. one_utf16_to_utf8 (iconv_t bigend, const uchar **inbufp, size_t *inbytesleftp,
  332. uchar **outbufp, size_t *outbytesleftp)
  333. {
  334. cppchar_t s;
  335. const uchar *inbuf = *inbufp;
  336. int rval;
  337. if (*inbytesleftp < 2)
  338. return EINVAL;
  339. s = inbuf[bigend ? 0 : 1] << 8;
  340. s += inbuf[bigend ? 1 : 0];
  341. /* Low surrogate without immediately preceding high surrogate is invalid. */
  342. if (s >= 0xDC00 && s <= 0xDFFF)
  343. return EILSEQ;
  344. /* High surrogate must have a following low surrogate. */
  345. else if (s >= 0xD800 && s <= 0xDBFF)
  346. {
  347. cppchar_t hi = s, lo;
  348. if (*inbytesleftp < 4)
  349. return EINVAL;
  350. lo = inbuf[bigend ? 2 : 3] << 8;
  351. lo += inbuf[bigend ? 3 : 2];
  352. if (lo < 0xDC00 || lo > 0xDFFF)
  353. return EILSEQ;
  354. s = (hi - 0xD800) * 0x400 + (lo - 0xDC00) + 0x10000;
  355. }
  356. rval = one_cppchar_to_utf8 (s, outbufp, outbytesleftp);
  357. if (rval)
  358. return rval;
  359. /* Success - update the input pointers (one_cppchar_to_utf8 has done
  360. the output pointers for us). */
  361. if (s <= 0xFFFF)
  362. {
  363. *inbufp += 2;
  364. *inbytesleftp -= 2;
  365. }
  366. else
  367. {
  368. *inbufp += 4;
  369. *inbytesleftp -= 4;
  370. }
  371. return 0;
  372. }
  373. /* Helper routine for the next few functions. The 'const' on
  374. one_conversion means that we promise not to modify what function is
  375. pointed to, which lets the inliner see through it. */
  376. static inline bool
  377. conversion_loop (int (*const one_conversion)(iconv_t, const uchar **, size_t *,
  378. uchar **, size_t *),
  379. iconv_t cd, const uchar *from, size_t flen, struct _cpp_strbuf *to)
  380. {
  381. const uchar *inbuf;
  382. uchar *outbuf;
  383. size_t inbytesleft, outbytesleft;
  384. int rval;
  385. inbuf = from;
  386. inbytesleft = flen;
  387. outbuf = to->text + to->len;
  388. outbytesleft = to->asize - to->len;
  389. for (;;)
  390. {
  391. do
  392. rval = one_conversion (cd, &inbuf, &inbytesleft,
  393. &outbuf, &outbytesleft);
  394. while (inbytesleft && !rval);
  395. if (__builtin_expect (inbytesleft == 0, 1))
  396. {
  397. to->len = to->asize - outbytesleft;
  398. return true;
  399. }
  400. if (rval != E2BIG)
  401. {
  402. errno = rval;
  403. return false;
  404. }
  405. outbytesleft += OUTBUF_BLOCK_SIZE;
  406. to->asize += OUTBUF_BLOCK_SIZE;
  407. to->text = XRESIZEVEC (uchar, to->text, to->asize);
  408. outbuf = to->text + to->asize - outbytesleft;
  409. }
  410. }
  411. /* These functions convert entire strings between character sets.
  412. They all have the signature
  413. bool (*)(iconv_t cd, const uchar *from, size_t flen, struct _cpp_strbuf *to);
  414. The input string FROM is converted as specified by the function
  415. name plus the iconv descriptor CD (which may be fake), and the
  416. result appended to TO. On any error, false is returned, otherwise true. */
  417. /* These four use the custom conversion code above. */
  418. static bool
  419. convert_utf8_utf16 (iconv_t cd, const uchar *from, size_t flen,
  420. struct _cpp_strbuf *to)
  421. {
  422. return conversion_loop (one_utf8_to_utf16, cd, from, flen, to);
  423. }
  424. static bool
  425. convert_utf8_utf32 (iconv_t cd, const uchar *from, size_t flen,
  426. struct _cpp_strbuf *to)
  427. {
  428. return conversion_loop (one_utf8_to_utf32, cd, from, flen, to);
  429. }
  430. static bool
  431. convert_utf16_utf8 (iconv_t cd, const uchar *from, size_t flen,
  432. struct _cpp_strbuf *to)
  433. {
  434. return conversion_loop (one_utf16_to_utf8, cd, from, flen, to);
  435. }
  436. static bool
  437. convert_utf32_utf8 (iconv_t cd, const uchar *from, size_t flen,
  438. struct _cpp_strbuf *to)
  439. {
  440. return conversion_loop (one_utf32_to_utf8, cd, from, flen, to);
  441. }
  442. /* Identity conversion, used when we have no alternative. */
  443. static bool
  444. convert_no_conversion (iconv_t cd ATTRIBUTE_UNUSED,
  445. const uchar *from, size_t flen, struct _cpp_strbuf *to)
  446. {
  447. if (to->len + flen > to->asize)
  448. {
  449. to->asize = to->len + flen;
  450. to->asize += to->asize / 4;
  451. to->text = XRESIZEVEC (uchar, to->text, to->asize);
  452. }
  453. memcpy (to->text + to->len, from, flen);
  454. to->len += flen;
  455. return true;
  456. }
  457. /* And this one uses the system iconv primitive. It's a little
  458. different, since iconv's interface is a little different. */
  459. #if HAVE_ICONV
  460. #define CONVERT_ICONV_GROW_BUFFER \
  461. do { \
  462. outbytesleft += OUTBUF_BLOCK_SIZE; \
  463. to->asize += OUTBUF_BLOCK_SIZE; \
  464. to->text = XRESIZEVEC (uchar, to->text, to->asize); \
  465. outbuf = (char *)to->text + to->asize - outbytesleft; \
  466. } while (0)
  467. static bool
  468. convert_using_iconv (iconv_t cd, const uchar *from, size_t flen,
  469. struct _cpp_strbuf *to)
  470. {
  471. ICONV_CONST char *inbuf;
  472. char *outbuf;
  473. size_t inbytesleft, outbytesleft;
  474. /* Reset conversion descriptor and check that it is valid. */
  475. if (iconv (cd, 0, 0, 0, 0) == (size_t)-1)
  476. return false;
  477. inbuf = (ICONV_CONST char *)from;
  478. inbytesleft = flen;
  479. outbuf = (char *)to->text + to->len;
  480. outbytesleft = to->asize - to->len;
  481. for (;;)
  482. {
  483. iconv (cd, &inbuf, &inbytesleft, &outbuf, &outbytesleft);
  484. if (__builtin_expect (inbytesleft == 0, 1))
  485. {
  486. /* Close out any shift states, returning to the initial state. */
  487. if (iconv (cd, 0, 0, &outbuf, &outbytesleft) == (size_t)-1)
  488. {
  489. if (errno != E2BIG)
  490. return false;
  491. CONVERT_ICONV_GROW_BUFFER;
  492. if (iconv (cd, 0, 0, &outbuf, &outbytesleft) == (size_t)-1)
  493. return false;
  494. }
  495. to->len = to->asize - outbytesleft;
  496. return true;
  497. }
  498. if (errno != E2BIG)
  499. return false;
  500. CONVERT_ICONV_GROW_BUFFER;
  501. }
  502. }
  503. #else
  504. #define convert_using_iconv 0 /* prevent undefined symbol error below */
  505. #endif
  506. /* Arrange for the above custom conversion logic to be used automatically
  507. when conversion between a suitable pair of character sets is requested. */
  508. #define APPLY_CONVERSION(CONVERTER, FROM, FLEN, TO) \
  509. CONVERTER.func (CONVERTER.cd, FROM, FLEN, TO)
  510. struct cpp_conversion
  511. {
  512. const char *pair;
  513. convert_f func;
  514. iconv_t fake_cd;
  515. };
  516. static const struct cpp_conversion conversion_tab[] = {
  517. { "UTF-8/UTF-32LE", convert_utf8_utf32, (iconv_t)0 },
  518. { "UTF-8/UTF-32BE", convert_utf8_utf32, (iconv_t)1 },
  519. { "UTF-8/UTF-16LE", convert_utf8_utf16, (iconv_t)0 },
  520. { "UTF-8/UTF-16BE", convert_utf8_utf16, (iconv_t)1 },
  521. { "UTF-32LE/UTF-8", convert_utf32_utf8, (iconv_t)0 },
  522. { "UTF-32BE/UTF-8", convert_utf32_utf8, (iconv_t)1 },
  523. { "UTF-16LE/UTF-8", convert_utf16_utf8, (iconv_t)0 },
  524. { "UTF-16BE/UTF-8", convert_utf16_utf8, (iconv_t)1 },
  525. };
  526. /* Subroutine of cpp_init_iconv: initialize and return a
  527. cset_converter structure for conversion from FROM to TO. If
  528. iconv_open() fails, issue an error and return an identity
  529. converter. Silently return an identity converter if FROM and TO
  530. are identical.
  531. PFILE is only used for generating diagnostics; setting it to NULL
  532. suppresses diagnostics. */
  533. static struct cset_converter
  534. init_iconv_desc (cpp_reader *pfile, const char *to, const char *from)
  535. {
  536. struct cset_converter ret;
  537. char *pair;
  538. size_t i;
  539. ret.to = to;
  540. ret.from = from;
  541. if (!strcasecmp (to, from))
  542. {
  543. ret.func = convert_no_conversion;
  544. ret.cd = (iconv_t) -1;
  545. ret.width = -1;
  546. return ret;
  547. }
  548. pair = (char *) alloca(strlen(to) + strlen(from) + 2);
  549. strcpy(pair, from);
  550. strcat(pair, "/");
  551. strcat(pair, to);
  552. for (i = 0; i < ARRAY_SIZE (conversion_tab); i++)
  553. if (!strcasecmp (pair, conversion_tab[i].pair))
  554. {
  555. ret.func = conversion_tab[i].func;
  556. ret.cd = conversion_tab[i].fake_cd;
  557. ret.width = -1;
  558. return ret;
  559. }
  560. /* No custom converter - try iconv. */
  561. if (HAVE_ICONV)
  562. {
  563. ret.func = convert_using_iconv;
  564. ret.cd = iconv_open (to, from);
  565. ret.width = -1;
  566. if (ret.cd == (iconv_t) -1)
  567. {
  568. if (pfile)
  569. {
  570. if (errno == EINVAL)
  571. cpp_error (pfile, CPP_DL_ERROR, /* FIXME should be DL_SORRY */
  572. "conversion from %s to %s not supported by iconv",
  573. from, to);
  574. else
  575. cpp_errno (pfile, CPP_DL_ERROR, "iconv_open");
  576. }
  577. ret.func = convert_no_conversion;
  578. }
  579. }
  580. else
  581. {
  582. if (pfile)
  583. {
  584. cpp_error (pfile, CPP_DL_ERROR, /* FIXME: should be DL_SORRY */
  585. "no iconv implementation, cannot convert from %s to %s",
  586. from, to);
  587. }
  588. ret.func = convert_no_conversion;
  589. ret.cd = (iconv_t) -1;
  590. ret.width = -1;
  591. }
  592. return ret;
  593. }
  594. /* If charset conversion is requested, initialize iconv(3) descriptors
  595. for conversion from the source character set to the execution
  596. character sets. If iconv is not present in the C library, and
  597. conversion is requested, issue an error. */
  598. void
  599. cpp_init_iconv (cpp_reader *pfile)
  600. {
  601. const char *ncset = CPP_OPTION (pfile, narrow_charset);
  602. const char *wcset = CPP_OPTION (pfile, wide_charset);
  603. const char *default_wcset;
  604. bool be = CPP_OPTION (pfile, bytes_big_endian);
  605. if (CPP_OPTION (pfile, wchar_precision) >= 32)
  606. default_wcset = be ? "UTF-32BE" : "UTF-32LE";
  607. else if (CPP_OPTION (pfile, wchar_precision) >= 16)
  608. default_wcset = be ? "UTF-16BE" : "UTF-16LE";
  609. else
  610. /* This effectively means that wide strings are not supported,
  611. so don't do any conversion at all. */
  612. default_wcset = SOURCE_CHARSET;
  613. if (!ncset)
  614. ncset = SOURCE_CHARSET;
  615. if (!wcset)
  616. wcset = default_wcset;
  617. pfile->narrow_cset_desc = init_iconv_desc (pfile, ncset, SOURCE_CHARSET);
  618. pfile->narrow_cset_desc.width = CPP_OPTION (pfile, char_precision);
  619. pfile->utf8_cset_desc = init_iconv_desc (pfile, "UTF-8", SOURCE_CHARSET);
  620. pfile->utf8_cset_desc.width = CPP_OPTION (pfile, char_precision);
  621. pfile->char16_cset_desc = init_iconv_desc (pfile,
  622. be ? "UTF-16BE" : "UTF-16LE",
  623. SOURCE_CHARSET);
  624. pfile->char16_cset_desc.width = 16;
  625. pfile->char32_cset_desc = init_iconv_desc (pfile,
  626. be ? "UTF-32BE" : "UTF-32LE",
  627. SOURCE_CHARSET);
  628. pfile->char32_cset_desc.width = 32;
  629. pfile->wide_cset_desc = init_iconv_desc (pfile, wcset, SOURCE_CHARSET);
  630. pfile->wide_cset_desc.width = CPP_OPTION (pfile, wchar_precision);
  631. }
  632. /* Destroy iconv(3) descriptors set up by cpp_init_iconv, if necessary. */
  633. void
  634. _cpp_destroy_iconv (cpp_reader *pfile)
  635. {
  636. if (HAVE_ICONV)
  637. {
  638. if (pfile->narrow_cset_desc.func == convert_using_iconv)
  639. iconv_close (pfile->narrow_cset_desc.cd);
  640. if (pfile->utf8_cset_desc.func == convert_using_iconv)
  641. iconv_close (pfile->utf8_cset_desc.cd);
  642. if (pfile->char16_cset_desc.func == convert_using_iconv)
  643. iconv_close (pfile->char16_cset_desc.cd);
  644. if (pfile->char32_cset_desc.func == convert_using_iconv)
  645. iconv_close (pfile->char32_cset_desc.cd);
  646. if (pfile->wide_cset_desc.func == convert_using_iconv)
  647. iconv_close (pfile->wide_cset_desc.cd);
  648. }
  649. }
  650. /* Utility routine for use by a full compiler. C is a character taken
  651. from the *basic* source character set, encoded in the host's
  652. execution encoding. Convert it to (the target's) execution
  653. encoding, and return that value.
  654. Issues an internal error if C's representation in the narrow
  655. execution character set fails to be a single-byte value (C99
  656. 5.2.1p3: "The representation of each member of the source and
  657. execution character sets shall fit in a byte.") May also issue an
  658. internal error if C fails to be a member of the basic source
  659. character set (testing this exactly is too hard, especially when
  660. the host character set is EBCDIC). */
  661. cppchar_t
  662. cpp_host_to_exec_charset (cpp_reader *pfile, cppchar_t c)
  663. {
  664. uchar sbuf[1];
  665. struct _cpp_strbuf tbuf;
  666. /* This test is merely an approximation, but it suffices to catch
  667. the most important thing, which is that we don't get handed a
  668. character outside the unibyte range of the host character set. */
  669. if (c > LAST_POSSIBLY_BASIC_SOURCE_CHAR)
  670. {
  671. cpp_error (pfile, CPP_DL_ICE,
  672. "character 0x%lx is not in the basic source character set\n",
  673. (unsigned long)c);
  674. return 0;
  675. }
  676. /* Being a character in the unibyte range of the host character set,
  677. we can safely splat it into a one-byte buffer and trust that that
  678. is a well-formed string. */
  679. sbuf[0] = c;
  680. /* This should never need to reallocate, but just in case... */
  681. tbuf.asize = 1;
  682. tbuf.text = XNEWVEC (uchar, tbuf.asize);
  683. tbuf.len = 0;
  684. if (!APPLY_CONVERSION (pfile->narrow_cset_desc, sbuf, 1, &tbuf))
  685. {
  686. cpp_errno (pfile, CPP_DL_ICE, "converting to execution character set");
  687. return 0;
  688. }
  689. if (tbuf.len != 1)
  690. {
  691. cpp_error (pfile, CPP_DL_ICE,
  692. "character 0x%lx is not unibyte in execution character set",
  693. (unsigned long)c);
  694. return 0;
  695. }
  696. c = tbuf.text[0];
  697. free(tbuf.text);
  698. return c;
  699. }
  700. /* cpp_substring_ranges's constructor. */
  701. cpp_substring_ranges::cpp_substring_ranges () :
  702. m_ranges (NULL),
  703. m_num_ranges (0),
  704. m_alloc_ranges (8)
  705. {
  706. m_ranges = XNEWVEC (source_range, m_alloc_ranges);
  707. }
  708. /* cpp_substring_ranges's destructor. */
  709. cpp_substring_ranges::~cpp_substring_ranges ()
  710. {
  711. free (m_ranges);
  712. }
  713. /* Add RANGE to the vector of source_range information. */
  714. void
  715. cpp_substring_ranges::add_range (source_range range)
  716. {
  717. if (m_num_ranges >= m_alloc_ranges)
  718. {
  719. m_alloc_ranges *= 2;
  720. m_ranges
  721. = (source_range *)xrealloc (m_ranges,
  722. sizeof (source_range) * m_alloc_ranges);
  723. }
  724. m_ranges[m_num_ranges++] = range;
  725. }
  726. /* Read NUM ranges from LOC_READER, adding them to the vector of source_range
  727. information. */
  728. void
  729. cpp_substring_ranges::add_n_ranges (int num,
  730. cpp_string_location_reader &loc_reader)
  731. {
  732. for (int i = 0; i < num; i++)
  733. add_range (loc_reader.get_next ());
  734. }
  735. /* Utility routine that computes a mask of the form 0000...111... with
  736. WIDTH 1-bits. */
  737. static inline size_t
  738. width_to_mask (size_t width)
  739. {
  740. width = MIN (width, BITS_PER_CPPCHAR_T);
  741. if (width >= CHAR_BIT * sizeof (size_t))
  742. return ~(size_t) 0;
  743. else
  744. return ((size_t) 1 << width) - 1;
  745. }
  746. /* A large table of unicode character information. */
  747. enum {
  748. /* Valid in a C99 identifier? */
  749. C99 = 1,
  750. /* Valid in a C99 identifier, but not as the first character? */
  751. N99 = 2,
  752. /* Valid in a C++ identifier? */
  753. CXX = 4,
  754. /* Valid in a C11/C++11 identifier? */
  755. C11 = 8,
  756. /* Valid in a C11/C++11 identifier, but not as the first character? */
  757. N11 = 16,
  758. /* Valid in a C++23 identifier? */
  759. CXX23 = 32,
  760. /* Valid in a C++23 identifier, but not as the first character? */
  761. NXX23 = 64,
  762. /* NFC representation is not valid in an identifier? */
  763. CID = 128,
  764. /* Might be valid NFC form? */
  765. NFC = 256,
  766. /* Might be valid NFKC form? */
  767. NKC = 512,
  768. /* Certain preceding characters might make it not valid NFC/NKFC form? */
  769. CTX = 1024
  770. };
  771. struct ucnrange {
  772. /* Bitmap of flags above. */
  773. unsigned short flags;
  774. /* Combining class of the character. */
  775. unsigned char combine;
  776. /* Last character in the range described by this entry. */
  777. unsigned int end;
  778. };
  779. #include "ucnid.h"
  780. /* ISO 10646 defines the UCS codespace as the range 0-0x10FFFF inclusive. */
  781. #define UCS_LIMIT 0x10FFFF
  782. /* Returns 1 if C is valid in an identifier, 2 if C is valid except at
  783. the start of an identifier, and 0 if C is not valid in an
  784. identifier. We assume C has already gone through the checks of
  785. _cpp_valid_ucn. Also update NST for C if returning nonzero. The
  786. algorithm is a simple binary search on the table defined in
  787. ucnid.h. */
  788. static int
  789. ucn_valid_in_identifier (cpp_reader *pfile, cppchar_t c,
  790. struct normalize_state *nst)
  791. {
  792. int mn, mx, md;
  793. unsigned short valid_flags, invalid_start_flags;
  794. if (c > UCS_LIMIT)
  795. return 0;
  796. mn = 0;
  797. mx = ARRAY_SIZE (ucnranges) - 1;
  798. while (mx != mn)
  799. {
  800. md = (mn + mx) / 2;
  801. if (c <= ucnranges[md].end)
  802. mx = md;
  803. else
  804. mn = md + 1;
  805. }
  806. /* When -pedantic, we require the character to have been listed by
  807. the standard for the current language. Otherwise, we accept the
  808. union of the acceptable sets for all supported language versions. */
  809. valid_flags = C99 | CXX | C11 | CXX23;
  810. if (CPP_PEDANTIC (pfile))
  811. {
  812. if (CPP_OPTION (pfile, cplusplus))
  813. valid_flags = CXX23;
  814. else if (CPP_OPTION (pfile, c11_identifiers))
  815. valid_flags = C11;
  816. else if (CPP_OPTION (pfile, c99))
  817. valid_flags = C99;
  818. }
  819. if (! (ucnranges[mn].flags & valid_flags))
  820. return 0;
  821. /* Update NST. */
  822. if (ucnranges[mn].combine != 0 && ucnranges[mn].combine < nst->prev_class)
  823. nst->level = normalized_none;
  824. else if (ucnranges[mn].flags & CTX)
  825. {
  826. bool safe;
  827. cppchar_t p = nst->previous;
  828. /* For Hangul, characters in the range AC00-D7A3 are NFC/NFKC,
  829. and are combined algorithmically from a sequence of the form
  830. 1100-1112 1161-1175 11A8-11C2
  831. (if the third is not present, it is treated as 11A7, which is not
  832. really a valid character).
  833. Unfortunately, C99 allows (only) the NFC form, but C++ allows
  834. only the combining characters. */
  835. if (c >= 0x1161 && c <= 0x1175)
  836. safe = p < 0x1100 || p > 0x1112;
  837. else if (c >= 0x11A8 && c <= 0x11C2)
  838. safe = (p < 0xAC00 || p > 0xD7A3 || (p - 0xAC00) % 28 != 0);
  839. else
  840. safe = check_nfc (pfile, c, p);
  841. if (!safe)
  842. {
  843. if ((c >= 0x1161 && c <= 0x1175) || (c >= 0x11A8 && c <= 0x11C2))
  844. nst->level = MAX (nst->level, normalized_identifier_C);
  845. else
  846. nst->level = normalized_none;
  847. }
  848. }
  849. else if (ucnranges[mn].flags & NKC)
  850. ;
  851. else if (ucnranges[mn].flags & NFC)
  852. nst->level = MAX (nst->level, normalized_C);
  853. else if (ucnranges[mn].flags & CID)
  854. nst->level = MAX (nst->level, normalized_identifier_C);
  855. else
  856. nst->level = normalized_none;
  857. if (ucnranges[mn].combine == 0)
  858. nst->previous = c;
  859. nst->prev_class = ucnranges[mn].combine;
  860. if (!CPP_PEDANTIC (pfile))
  861. {
  862. /* If not -pedantic, accept as character that may
  863. begin an identifier a union of characters allowed
  864. at that position in each of the character sets. */
  865. if ((ucnranges[mn].flags & (C99 | N99)) == C99
  866. || (ucnranges[mn].flags & CXX) != 0
  867. || (ucnranges[mn].flags & (C11 | N11)) == C11
  868. || (ucnranges[mn].flags & (CXX23 | NXX23)) == CXX23)
  869. return 1;
  870. return 2;
  871. }
  872. if (CPP_OPTION (pfile, cplusplus))
  873. invalid_start_flags = NXX23;
  874. else if (CPP_OPTION (pfile, c11_identifiers))
  875. invalid_start_flags = N11;
  876. else if (CPP_OPTION (pfile, c99))
  877. invalid_start_flags = N99;
  878. else
  879. invalid_start_flags = 0;
  880. /* In C99, UCN digits may not begin identifiers. In C11 and C++11,
  881. UCN combining characters may not begin identifiers. */
  882. if (ucnranges[mn].flags & invalid_start_flags)
  883. return 2;
  884. return 1;
  885. }
  886. /* [lex.charset]: The character designated by the universal character
  887. name \UNNNNNNNN is that character whose character short name in
  888. ISO/IEC 10646 is NNNNNNNN; the character designated by the
  889. universal character name \uNNNN is that character whose character
  890. short name in ISO/IEC 10646 is 0000NNNN. If the hexadecimal value
  891. for a universal character name corresponds to a surrogate code point
  892. (in the range 0xD800-0xDFFF, inclusive), the program is ill-formed.
  893. Additionally, if the hexadecimal value for a universal-character-name
  894. outside a character or string literal corresponds to a control character
  895. (in either of the ranges 0x00-0x1F or 0x7F-0x9F, both inclusive) or to a
  896. character in the basic source character set, the program is ill-formed.
  897. C99 6.4.3: A universal character name shall not specify a character
  898. whose short identifier is less than 00A0 other than 0024 ($), 0040 (@),
  899. or 0060 (`), nor one in the range D800 through DFFF inclusive.
  900. If the hexadecimal value is larger than the upper bound of the UCS
  901. codespace specified in ISO/IEC 10646, a pedantic warning is issued
  902. in all versions of C and in the C++20 or later versions of C++.
  903. *PSTR must be preceded by "\u" or "\U"; it is assumed that the
  904. buffer end is delimited by a non-hex digit. Returns false if the
  905. UCN has not been consumed, true otherwise.
  906. The value of the UCN, whether valid or invalid, is returned in *CP.
  907. Diagnostics are emitted for invalid values. PSTR is updated to point
  908. one beyond the UCN, or to the syntactically invalid character.
  909. IDENTIFIER_POS is 0 when not in an identifier, 1 for the start of
  910. an identifier, or 2 otherwise.
  911. If LOC_READER is non-NULL, then position information is
  912. read from *LOC_READER and CHAR_RANGE->m_finish is updated accordingly. */
  913. bool
  914. _cpp_valid_ucn (cpp_reader *pfile, const uchar **pstr,
  915. const uchar *limit, int identifier_pos,
  916. struct normalize_state *nst, cppchar_t *cp,
  917. source_range *char_range,
  918. cpp_string_location_reader *loc_reader)
  919. {
  920. cppchar_t result, c;
  921. unsigned int length;
  922. const uchar *str = *pstr;
  923. const uchar *base = str - 2;
  924. if (!CPP_OPTION (pfile, cplusplus) && !CPP_OPTION (pfile, c99))
  925. cpp_error (pfile, CPP_DL_WARNING,
  926. "universal character names are only valid in C++ and C99");
  927. else if (CPP_OPTION (pfile, cpp_warn_c90_c99_compat) > 0
  928. && !CPP_OPTION (pfile, cplusplus))
  929. cpp_error (pfile, CPP_DL_WARNING,
  930. "C99's universal character names are incompatible with C90");
  931. else if (CPP_WTRADITIONAL (pfile) && identifier_pos == 0)
  932. cpp_warning (pfile, CPP_W_TRADITIONAL,
  933. "the meaning of '\\%c' is different in traditional C",
  934. (int) str[-1]);
  935. if (str[-1] == 'u')
  936. length = 4;
  937. else if (str[-1] == 'U')
  938. length = 8;
  939. else
  940. {
  941. cpp_error (pfile, CPP_DL_ICE, "In _cpp_valid_ucn but not a UCN");
  942. length = 4;
  943. }
  944. result = 0;
  945. do
  946. {
  947. c = *str;
  948. if (!ISXDIGIT (c))
  949. break;
  950. str++;
  951. if (loc_reader)
  952. {
  953. gcc_assert (char_range);
  954. char_range->m_finish = loc_reader->get_next ().m_finish;
  955. }
  956. result = (result << 4) + hex_value (c);
  957. }
  958. while (--length && str < limit);
  959. /* Partial UCNs are not valid in strings, but decompose into
  960. multiple tokens in identifiers, so we can't give a helpful
  961. error message in that case. */
  962. if (length && identifier_pos)
  963. {
  964. *cp = 0;
  965. return false;
  966. }
  967. *pstr = str;
  968. if (length)
  969. {
  970. cpp_error (pfile, CPP_DL_ERROR,
  971. "incomplete universal character name %.*s",
  972. (int) (str - base), base);
  973. result = 1;
  974. }
  975. /* The C99 standard permits $, @ and ` to be specified as UCNs. We use
  976. hex escapes so that this also works with EBCDIC hosts.
  977. C++0x permits everything below 0xa0 within literals;
  978. ucn_valid_in_identifier will complain about identifiers. */
  979. else if ((result < 0xa0
  980. && !CPP_OPTION (pfile, cplusplus)
  981. && (result != 0x24 && result != 0x40 && result != 0x60))
  982. || (result & 0x80000000)
  983. || (result >= 0xD800 && result <= 0xDFFF))
  984. {
  985. cpp_error (pfile, CPP_DL_ERROR,
  986. "%.*s is not a valid universal character",
  987. (int) (str - base), base);
  988. result = 1;
  989. }
  990. else if (identifier_pos && result == 0x24
  991. && CPP_OPTION (pfile, dollars_in_ident))
  992. {
  993. if (CPP_OPTION (pfile, warn_dollars) && !pfile->state.skipping)
  994. {
  995. CPP_OPTION (pfile, warn_dollars) = 0;
  996. cpp_error (pfile, CPP_DL_PEDWARN, "'$' in identifier or number");
  997. }
  998. NORMALIZE_STATE_UPDATE_IDNUM (nst, result);
  999. }
  1000. else if (identifier_pos)
  1001. {
  1002. int validity = ucn_valid_in_identifier (pfile, result, nst);
  1003. if (validity == 0)
  1004. cpp_error (pfile, CPP_DL_ERROR,
  1005. "universal character %.*s is not valid in an identifier",
  1006. (int) (str - base), base);
  1007. else if (validity == 2 && identifier_pos == 1)
  1008. cpp_error (pfile, CPP_DL_ERROR,
  1009. "universal character %.*s is not valid at the start of an identifier",
  1010. (int) (str - base), base);
  1011. }
  1012. else if (result > UCS_LIMIT
  1013. && (!CPP_OPTION (pfile, cplusplus)
  1014. || CPP_OPTION (pfile, lang) > CLK_CXX17))
  1015. cpp_error (pfile, CPP_DL_PEDWARN,
  1016. "%.*s is outside the UCS codespace",
  1017. (int) (str - base), base);
  1018. *cp = result;
  1019. return true;
  1020. }
  1021. /* Convert an UCN, pointed to by FROM, to UTF-8 encoding, then translate
  1022. it to the execution character set and write the result into TBUF,
  1023. if TBUF is non-NULL.
  1024. An advanced pointer is returned. Issues all relevant diagnostics.
  1025. If LOC_READER is non-NULL, then RANGES must be non-NULL and CHAR_RANGE
  1026. contains the location of the character so far: location information
  1027. is read from *LOC_READER, and *RANGES is updated accordingly. */
  1028. static const uchar *
  1029. convert_ucn (cpp_reader *pfile, const uchar *from, const uchar *limit,
  1030. struct _cpp_strbuf *tbuf, struct cset_converter cvt,
  1031. source_range char_range,
  1032. cpp_string_location_reader *loc_reader,
  1033. cpp_substring_ranges *ranges)
  1034. {
  1035. cppchar_t ucn;
  1036. uchar buf[6];
  1037. uchar *bufp = buf;
  1038. size_t bytesleft = 6;
  1039. int rval;
  1040. struct normalize_state nst = INITIAL_NORMALIZE_STATE;
  1041. /* loc_reader and ranges must either be both NULL, or both be non-NULL. */
  1042. gcc_assert ((loc_reader != NULL) == (ranges != NULL));
  1043. from++; /* Skip u/U. */
  1044. if (loc_reader)
  1045. /* The u/U is part of the spelling of this character. */
  1046. char_range.m_finish = loc_reader->get_next ().m_finish;
  1047. _cpp_valid_ucn (pfile, &from, limit, 0, &nst,
  1048. &ucn, &char_range, loc_reader);
  1049. rval = one_cppchar_to_utf8 (ucn, &bufp, &bytesleft);
  1050. if (rval)
  1051. {
  1052. errno = rval;
  1053. cpp_errno (pfile, CPP_DL_ERROR,
  1054. "converting UCN to source character set");
  1055. }
  1056. else
  1057. {
  1058. if (tbuf)
  1059. if (!APPLY_CONVERSION (cvt, buf, 6 - bytesleft, tbuf))
  1060. cpp_errno (pfile, CPP_DL_ERROR,
  1061. "converting UCN to execution character set");
  1062. if (loc_reader)
  1063. {
  1064. int num_encoded_bytes = 6 - bytesleft;
  1065. for (int i = 0; i < num_encoded_bytes; i++)
  1066. ranges->add_range (char_range);
  1067. }
  1068. }
  1069. return from;
  1070. }
  1071. /* Performs a similar task as _cpp_valid_ucn, but parses UTF-8-encoded
  1072. extended characters rather than UCNs. If the return value is TRUE, then a
  1073. character was successfully decoded and stored in *CP; *PSTR has been
  1074. updated to point one past the valid UTF-8 sequence. Diagnostics may have
  1075. been emitted if the character parsed is not allowed in the current context.
  1076. If the return value is FALSE, then *PSTR has not been modified and *CP may
  1077. equal 0, to indicate that *PSTR does not form a valid UTF-8 sequence, or it
  1078. may, when processing an identifier in C mode, equal a codepoint that was
  1079. validly encoded but is not allowed to appear in an identifier. In either
  1080. case, no diagnostic is emitted, and the return value of FALSE should cause
  1081. a new token to be formed.
  1082. Unlike _cpp_valid_ucn, this will never be called when lexing a string; only
  1083. a potential identifier, or a CPP_OTHER token. NST is unused in the latter
  1084. case.
  1085. As in _cpp_valid_ucn, IDENTIFIER_POS is 0 when not in an identifier, 1 for
  1086. the start of an identifier, or 2 otherwise. */
  1087. extern bool
  1088. _cpp_valid_utf8 (cpp_reader *pfile,
  1089. const uchar **pstr,
  1090. const uchar *limit,
  1091. int identifier_pos,
  1092. struct normalize_state *nst,
  1093. cppchar_t *cp)
  1094. {
  1095. const uchar *base = *pstr;
  1096. size_t inbytesleft = limit - base;
  1097. if (one_utf8_to_cppchar (pstr, &inbytesleft, cp))
  1098. {
  1099. /* No diagnostic here as this byte will rather become a
  1100. new token. */
  1101. *cp = 0;
  1102. return false;
  1103. }
  1104. if (identifier_pos)
  1105. {
  1106. switch (ucn_valid_in_identifier (pfile, *cp, nst))
  1107. {
  1108. case 0:
  1109. /* In C++, this is an error for invalid character in an identifier
  1110. because logically, the UTF-8 was converted to a UCN during
  1111. translation phase 1 (even though we don't physically do it that
  1112. way). In C, this byte rather becomes grammatically a separate
  1113. token. */
  1114. if (CPP_OPTION (pfile, cplusplus))
  1115. cpp_error (pfile, CPP_DL_ERROR,
  1116. "extended character %.*s is not valid in an identifier",
  1117. (int) (*pstr - base), base);
  1118. else
  1119. {
  1120. *pstr = base;
  1121. return false;
  1122. }
  1123. break;
  1124. case 2:
  1125. if (identifier_pos == 1)
  1126. {
  1127. /* This is treated the same way in C++ or C99 -- lexed as an
  1128. identifier which is then invalid because an identifier is
  1129. not allowed to start with this character. */
  1130. cpp_error (pfile, CPP_DL_ERROR,
  1131. "extended character %.*s is not valid at the start of an identifier",
  1132. (int) (*pstr - base), base);
  1133. }
  1134. break;
  1135. }
  1136. }
  1137. return true;
  1138. }
  1139. /* Subroutine of convert_hex and convert_oct. N is the representation
  1140. in the execution character set of a numeric escape; write it into the
  1141. string buffer TBUF and update the end-of-string pointer therein. WIDE
  1142. is true if it's a wide string that's being assembled in TBUF. This
  1143. function issues no diagnostics and never fails. */
  1144. static void
  1145. emit_numeric_escape (cpp_reader *pfile, cppchar_t n,
  1146. struct _cpp_strbuf *tbuf, struct cset_converter cvt)
  1147. {
  1148. size_t width = cvt.width;
  1149. if (width != CPP_OPTION (pfile, char_precision))
  1150. {
  1151. /* We have to render this into the target byte order, which may not
  1152. be our byte order. */
  1153. bool bigend = CPP_OPTION (pfile, bytes_big_endian);
  1154. size_t cwidth = CPP_OPTION (pfile, char_precision);
  1155. size_t cmask = width_to_mask (cwidth);
  1156. size_t nbwc = width / cwidth;
  1157. size_t i;
  1158. size_t off = tbuf->len;
  1159. cppchar_t c;
  1160. if (tbuf->len + nbwc > tbuf->asize)
  1161. {
  1162. tbuf->asize += OUTBUF_BLOCK_SIZE;
  1163. tbuf->text = XRESIZEVEC (uchar, tbuf->text, tbuf->asize);
  1164. }
  1165. for (i = 0; i < nbwc; i++)
  1166. {
  1167. c = n & cmask;
  1168. n >>= cwidth;
  1169. tbuf->text[off + (bigend ? nbwc - i - 1 : i)] = c;
  1170. }
  1171. tbuf->len += nbwc;
  1172. }
  1173. else
  1174. {
  1175. /* Note: this code does not handle the case where the target
  1176. and host have a different number of bits in a byte. */
  1177. if (tbuf->len + 1 > tbuf->asize)
  1178. {
  1179. tbuf->asize += OUTBUF_BLOCK_SIZE;
  1180. tbuf->text = XRESIZEVEC (uchar, tbuf->text, tbuf->asize);
  1181. }
  1182. tbuf->text[tbuf->len++] = n;
  1183. }
  1184. }
  1185. /* Convert a hexadecimal escape, pointed to by FROM, to the execution
  1186. character set and write it into the string buffer TBUF (if non-NULL).
  1187. Returns an advanced pointer, and issues diagnostics as necessary.
  1188. No character set translation occurs; this routine always produces the
  1189. execution-set character with numeric value equal to the given hex
  1190. number. You can, e.g. generate surrogate pairs this way.
  1191. If LOC_READER is non-NULL, then RANGES must be non-NULL and CHAR_RANGE
  1192. contains the location of the character so far: location information
  1193. is read from *LOC_READER, and *RANGES is updated accordingly. */
  1194. static const uchar *
  1195. convert_hex (cpp_reader *pfile, const uchar *from, const uchar *limit,
  1196. struct _cpp_strbuf *tbuf, struct cset_converter cvt,
  1197. source_range char_range,
  1198. cpp_string_location_reader *loc_reader,
  1199. cpp_substring_ranges *ranges)
  1200. {
  1201. cppchar_t c, n = 0, overflow = 0;
  1202. int digits_found = 0;
  1203. size_t width = cvt.width;
  1204. size_t mask = width_to_mask (width);
  1205. /* loc_reader and ranges must either be both NULL, or both be non-NULL. */
  1206. gcc_assert ((loc_reader != NULL) == (ranges != NULL));
  1207. if (CPP_WTRADITIONAL (pfile))
  1208. cpp_warning (pfile, CPP_W_TRADITIONAL,
  1209. "the meaning of '\\x' is different in traditional C");
  1210. /* Skip 'x'. */
  1211. from++;
  1212. /* The 'x' is part of the spelling of this character. */
  1213. if (loc_reader)
  1214. char_range.m_finish = loc_reader->get_next ().m_finish;
  1215. while (from < limit)
  1216. {
  1217. c = *from;
  1218. if (! hex_p (c))
  1219. break;
  1220. from++;
  1221. if (loc_reader)
  1222. char_range.m_finish = loc_reader->get_next ().m_finish;
  1223. overflow |= n ^ (n << 4 >> 4);
  1224. n = (n << 4) + hex_value (c);
  1225. digits_found = 1;
  1226. }
  1227. if (!digits_found)
  1228. {
  1229. cpp_error (pfile, CPP_DL_ERROR,
  1230. "\\x used with no following hex digits");
  1231. return from;
  1232. }
  1233. if (overflow | (n != (n & mask)))
  1234. {
  1235. cpp_error (pfile, CPP_DL_PEDWARN,
  1236. "hex escape sequence out of range");
  1237. n &= mask;
  1238. }
  1239. if (tbuf)
  1240. emit_numeric_escape (pfile, n, tbuf, cvt);
  1241. if (ranges)
  1242. ranges->add_range (char_range);
  1243. return from;
  1244. }
  1245. /* Convert an octal escape, pointed to by FROM, to the execution
  1246. character set and write it into the string buffer TBUF. Returns an
  1247. advanced pointer, and issues diagnostics as necessary.
  1248. No character set translation occurs; this routine always produces the
  1249. execution-set character with numeric value equal to the given octal
  1250. number.
  1251. If LOC_READER is non-NULL, then RANGES must be non-NULL and CHAR_RANGE
  1252. contains the location of the character so far: location information
  1253. is read from *LOC_READER, and *RANGES is updated accordingly. */
  1254. static const uchar *
  1255. convert_oct (cpp_reader *pfile, const uchar *from, const uchar *limit,
  1256. struct _cpp_strbuf *tbuf, struct cset_converter cvt,
  1257. source_range char_range,
  1258. cpp_string_location_reader *loc_reader,
  1259. cpp_substring_ranges *ranges)
  1260. {
  1261. size_t count = 0;
  1262. cppchar_t c, n = 0;
  1263. size_t width = cvt.width;
  1264. size_t mask = width_to_mask (width);
  1265. /* loc_reader and ranges must either be both NULL, or both be non-NULL. */
  1266. gcc_assert ((loc_reader != NULL) == (ranges != NULL));
  1267. while (from < limit && count++ < 3)
  1268. {
  1269. c = *from;
  1270. if (c < '0' || c > '7')
  1271. break;
  1272. from++;
  1273. if (loc_reader)
  1274. char_range.m_finish = loc_reader->get_next ().m_finish;
  1275. n = (n << 3) + c - '0';
  1276. }
  1277. if (n != (n & mask))
  1278. {
  1279. cpp_error (pfile, CPP_DL_PEDWARN,
  1280. "octal escape sequence out of range");
  1281. n &= mask;
  1282. }
  1283. if (tbuf)
  1284. emit_numeric_escape (pfile, n, tbuf, cvt);
  1285. if (ranges)
  1286. ranges->add_range (char_range);
  1287. return from;
  1288. }
  1289. /* Convert an escape sequence (pointed to by FROM) to its value on
  1290. the target, and to the execution character set. Do not scan past
  1291. LIMIT. Write the converted value into TBUF, if TBUF is non-NULL.
  1292. Returns an advanced pointer. Handles all relevant diagnostics.
  1293. If LOC_READER is non-NULL, then RANGES must be non-NULL: location
  1294. information is read from *LOC_READER, and *RANGES is updated
  1295. accordingly. */
  1296. static const uchar *
  1297. convert_escape (cpp_reader *pfile, const uchar *from, const uchar *limit,
  1298. struct _cpp_strbuf *tbuf, struct cset_converter cvt,
  1299. cpp_string_location_reader *loc_reader,
  1300. cpp_substring_ranges *ranges)
  1301. {
  1302. /* Values of \a \b \e \f \n \r \t \v respectively. */
  1303. #if HOST_CHARSET == HOST_CHARSET_ASCII
  1304. static const uchar charconsts[] = { 7, 8, 27, 12, 10, 13, 9, 11 };
  1305. #elif HOST_CHARSET == HOST_CHARSET_EBCDIC
  1306. static const uchar charconsts[] = { 47, 22, 39, 12, 21, 13, 5, 11 };
  1307. #else
  1308. #error "unknown host character set"
  1309. #endif
  1310. uchar c;
  1311. /* Record the location of the backslash. */
  1312. source_range char_range;
  1313. if (loc_reader)
  1314. char_range = loc_reader->get_next ();
  1315. c = *from;
  1316. switch (c)
  1317. {
  1318. /* UCNs, hex escapes, and octal escapes are processed separately. */
  1319. case 'u': case 'U':
  1320. return convert_ucn (pfile, from, limit, tbuf, cvt,
  1321. char_range, loc_reader, ranges);
  1322. case 'x':
  1323. return convert_hex (pfile, from, limit, tbuf, cvt,
  1324. char_range, loc_reader, ranges);
  1325. case '0': case '1': case '2': case '3':
  1326. case '4': case '5': case '6': case '7':
  1327. return convert_oct (pfile, from, limit, tbuf, cvt,
  1328. char_range, loc_reader, ranges);
  1329. /* Various letter escapes. Get the appropriate host-charset
  1330. value into C. */
  1331. case '\\': case '\'': case '"': case '?': break;
  1332. case '(': case '{': case '[': case '%':
  1333. /* '\(', etc, can be used at the beginning of a line in a long
  1334. string split onto multiple lines with \-newline, to prevent
  1335. Emacs or other text editors from getting confused. '\%' can
  1336. be used to prevent SCCS from mangling printf format strings. */
  1337. if (CPP_PEDANTIC (pfile))
  1338. goto unknown;
  1339. break;
  1340. case 'b': c = charconsts[1]; break;
  1341. case 'f': c = charconsts[3]; break;
  1342. case 'n': c = charconsts[4]; break;
  1343. case 'r': c = charconsts[5]; break;
  1344. case 't': c = charconsts[6]; break;
  1345. case 'v': c = charconsts[7]; break;
  1346. case 'a':
  1347. if (CPP_WTRADITIONAL (pfile))
  1348. cpp_warning (pfile, CPP_W_TRADITIONAL,
  1349. "the meaning of '\\a' is different in traditional C");
  1350. c = charconsts[0];
  1351. break;
  1352. case 'e': case 'E':
  1353. if (CPP_PEDANTIC (pfile))
  1354. cpp_error (pfile, CPP_DL_PEDWARN,
  1355. "non-ISO-standard escape sequence, '\\%c'", (int) c);
  1356. c = charconsts[2];
  1357. break;
  1358. default:
  1359. unknown:
  1360. if (ISGRAPH (c))
  1361. cpp_error (pfile, CPP_DL_PEDWARN,
  1362. "unknown escape sequence: '\\%c'", (int) c);
  1363. else
  1364. {
  1365. encoding_rich_location rich_loc (pfile);
  1366. /* diagnostic.cc does not support "%03o". When it does, this
  1367. code can use %03o directly in the diagnostic again. */
  1368. char buf[32];
  1369. sprintf(buf, "%03o", (int) c);
  1370. cpp_error_at (pfile, CPP_DL_PEDWARN, &rich_loc,
  1371. "unknown escape sequence: '\\%s'", buf);
  1372. }
  1373. }
  1374. if (tbuf)
  1375. /* Now convert what we have to the execution character set. */
  1376. if (!APPLY_CONVERSION (cvt, &c, 1, tbuf))
  1377. cpp_errno (pfile, CPP_DL_ERROR,
  1378. "converting escape sequence to execution character set");
  1379. if (loc_reader)
  1380. {
  1381. char_range.m_finish = loc_reader->get_next ().m_finish;
  1382. ranges->add_range (char_range);
  1383. }
  1384. return from + 1;
  1385. }
  1386. /* TYPE is a token type. The return value is the conversion needed to
  1387. convert from source to execution character set for the given type. */
  1388. static struct cset_converter
  1389. converter_for_type (cpp_reader *pfile, enum cpp_ttype type)
  1390. {
  1391. switch (type)
  1392. {
  1393. default:
  1394. return pfile->narrow_cset_desc;
  1395. case CPP_UTF8CHAR:
  1396. case CPP_UTF8STRING:
  1397. return pfile->utf8_cset_desc;
  1398. case CPP_CHAR16:
  1399. case CPP_STRING16:
  1400. return pfile->char16_cset_desc;
  1401. case CPP_CHAR32:
  1402. case CPP_STRING32:
  1403. return pfile->char32_cset_desc;
  1404. case CPP_WCHAR:
  1405. case CPP_WSTRING:
  1406. return pfile->wide_cset_desc;
  1407. }
  1408. }
  1409. /* FROM is an array of cpp_string structures of length COUNT. These
  1410. are to be converted from the source to the execution character set,
  1411. escape sequences translated, and finally all are to be
  1412. concatenated. WIDE indicates whether or not to produce a wide
  1413. string. If TO is non-NULL, the result is written into TO.
  1414. If LOC_READERS and OUT are non-NULL, then location information
  1415. is read from LOC_READERS (which must be an array of length COUNT),
  1416. and location information is written to *RANGES.
  1417. Returns true for success, false for failure. */
  1418. static bool
  1419. cpp_interpret_string_1 (cpp_reader *pfile, const cpp_string *from, size_t count,
  1420. cpp_string *to, enum cpp_ttype type,
  1421. cpp_string_location_reader *loc_readers,
  1422. cpp_substring_ranges *out)
  1423. {
  1424. struct _cpp_strbuf tbuf;
  1425. const uchar *p, *base, *limit;
  1426. size_t i;
  1427. struct cset_converter cvt = converter_for_type (pfile, type);
  1428. /* loc_readers and out must either be both NULL, or both be non-NULL. */
  1429. gcc_assert ((loc_readers != NULL) == (out != NULL));
  1430. if (to)
  1431. {
  1432. tbuf.asize = MAX (OUTBUF_BLOCK_SIZE, from->len);
  1433. tbuf.text = XNEWVEC (uchar, tbuf.asize);
  1434. tbuf.len = 0;
  1435. }
  1436. cpp_string_location_reader *loc_reader = NULL;
  1437. for (i = 0; i < count; i++)
  1438. {
  1439. if (loc_readers)
  1440. loc_reader = &loc_readers[i];
  1441. p = from[i].text;
  1442. if (*p == 'u')
  1443. {
  1444. p++;
  1445. if (loc_reader)
  1446. loc_reader->get_next ();
  1447. if (*p == '8')
  1448. {
  1449. p++;
  1450. if (loc_reader)
  1451. loc_reader->get_next ();
  1452. }
  1453. }
  1454. else if (*p == 'L' || *p == 'U') p++;
  1455. if (*p == 'R')
  1456. {
  1457. const uchar *prefix;
  1458. /* Skip over 'R"'. */
  1459. p += 2;
  1460. if (loc_reader)
  1461. {
  1462. loc_reader->get_next ();
  1463. loc_reader->get_next ();
  1464. }
  1465. prefix = p;
  1466. while (*p != '(')
  1467. {
  1468. p++;
  1469. if (loc_reader)
  1470. loc_reader->get_next ();
  1471. }
  1472. p++;
  1473. if (loc_reader)
  1474. loc_reader->get_next ();
  1475. limit = from[i].text + from[i].len;
  1476. if (limit >= p + (p - prefix) + 1)
  1477. limit -= (p - prefix) + 1;
  1478. /* Raw strings are all normal characters; these can be fed
  1479. directly to convert_cset. */
  1480. if (to)
  1481. if (!APPLY_CONVERSION (cvt, p, limit - p, &tbuf))
  1482. goto fail;
  1483. if (loc_reader)
  1484. {
  1485. /* If generating source ranges, assume we have a 1:1
  1486. correspondence between bytes in the source encoding and bytes
  1487. in the execution encoding (e.g. if we have a UTF-8 to UTF-8
  1488. conversion), so that this run of bytes in the source file
  1489. corresponds to a run of bytes in the execution string.
  1490. This requirement is guaranteed by an early-reject in
  1491. cpp_interpret_string_ranges. */
  1492. gcc_assert (cvt.func == convert_no_conversion);
  1493. out->add_n_ranges (limit - p, *loc_reader);
  1494. }
  1495. continue;
  1496. }
  1497. /* If we don't now have a leading quote, something has gone wrong.
  1498. This can occur if cpp_interpret_string_ranges is handling a
  1499. stringified macro argument, but should not be possible otherwise. */
  1500. if (*p != '"' && *p != '\'')
  1501. {
  1502. gcc_assert (out != NULL);
  1503. cpp_error (pfile, CPP_DL_ERROR, "missing open quote");
  1504. if (to)
  1505. free (tbuf.text);
  1506. return false;
  1507. }
  1508. /* Skip leading quote. */
  1509. p++;
  1510. if (loc_reader)
  1511. loc_reader->get_next ();
  1512. limit = from[i].text + from[i].len - 1; /* Skip trailing quote. */
  1513. for (;;)
  1514. {
  1515. base = p;
  1516. while (p < limit && *p != '\\')
  1517. p++;
  1518. if (p > base)
  1519. {
  1520. /* We have a run of normal characters; these can be fed
  1521. directly to convert_cset. */
  1522. if (to)
  1523. if (!APPLY_CONVERSION (cvt, base, p - base, &tbuf))
  1524. goto fail;
  1525. /* Similar to above: assumes we have a 1:1 correspondence
  1526. between bytes in the source encoding and bytes in the
  1527. execution encoding. */
  1528. if (loc_reader)
  1529. {
  1530. gcc_assert (cvt.func == convert_no_conversion);
  1531. out->add_n_ranges (p - base, *loc_reader);
  1532. }
  1533. }
  1534. if (p >= limit)
  1535. break;
  1536. struct _cpp_strbuf *tbuf_ptr = to ? &tbuf : NULL;
  1537. p = convert_escape (pfile, p + 1, limit, tbuf_ptr, cvt,
  1538. loc_reader, out);
  1539. }
  1540. }
  1541. if (to)
  1542. {
  1543. /* NUL-terminate the 'to' buffer and translate it to a cpp_string
  1544. structure. */
  1545. emit_numeric_escape (pfile, 0, &tbuf, cvt);
  1546. tbuf.text = XRESIZEVEC (uchar, tbuf.text, tbuf.len);
  1547. to->text = tbuf.text;
  1548. to->len = tbuf.len;
  1549. }
  1550. /* Use the location of the trailing quote as the location of the
  1551. NUL-terminator. */
  1552. if (loc_reader)
  1553. {
  1554. source_range range = loc_reader->get_next ();
  1555. out->add_range (range);
  1556. }
  1557. return true;
  1558. fail:
  1559. cpp_errno (pfile, CPP_DL_ERROR, "converting to execution character set");
  1560. if (to)
  1561. free (tbuf.text);
  1562. return false;
  1563. }
  1564. /* FROM is an array of cpp_string structures of length COUNT. These
  1565. are to be converted from the source to the execution character set,
  1566. escape sequences translated, and finally all are to be
  1567. concatenated. WIDE indicates whether or not to produce a wide
  1568. string. The result is written into TO. Returns true for success,
  1569. false for failure. */
  1570. bool
  1571. cpp_interpret_string (cpp_reader *pfile, const cpp_string *from, size_t count,
  1572. cpp_string *to, enum cpp_ttype type)
  1573. {
  1574. return cpp_interpret_string_1 (pfile, from, count, to, type, NULL, NULL);
  1575. }
  1576. /* A "do nothing" diagnostic-handling callback for use by
  1577. cpp_interpret_string_ranges, so that it can temporarily suppress
  1578. diagnostic-handling. */
  1579. static bool
  1580. noop_diagnostic_cb (cpp_reader *, enum cpp_diagnostic_level,
  1581. enum cpp_warning_reason, rich_location *,
  1582. const char *, va_list *)
  1583. {
  1584. /* no-op. */
  1585. return true;
  1586. }
  1587. /* This function mimics the behavior of cpp_interpret_string, but
  1588. rather than generating a string in the execution character set,
  1589. *OUT is written to with the source code ranges of the characters
  1590. in such a string.
  1591. FROM and LOC_READERS should both be arrays of length COUNT.
  1592. Returns NULL for success, or an error message for failure. */
  1593. const char *
  1594. cpp_interpret_string_ranges (cpp_reader *pfile, const cpp_string *from,
  1595. cpp_string_location_reader *loc_readers,
  1596. size_t count,
  1597. cpp_substring_ranges *out,
  1598. enum cpp_ttype type)
  1599. {
  1600. /* There are a couple of cases in the range-handling in
  1601. cpp_interpret_string_1 that rely on there being a 1:1 correspondence
  1602. between bytes in the source encoding and bytes in the execution
  1603. encoding, so that each byte in the execution string can correspond
  1604. to the location of a byte in the source string.
  1605. This holds for the typical case of a UTF-8 to UTF-8 conversion.
  1606. Enforce this requirement by only attempting to track substring
  1607. locations if we have source encoding == execution encoding.
  1608. This is a stronger condition than we need, since we could e.g.
  1609. have ASCII to EBCDIC (with 1 byte per character before and after),
  1610. but it seems to be a reasonable restriction. */
  1611. struct cset_converter cvt = converter_for_type (pfile, type);
  1612. if (cvt.func != convert_no_conversion)
  1613. return "execution character set != source character set";
  1614. /* For on-demand strings we have already lexed the strings, so there
  1615. should be no diagnostics. However, if we have bogus source location
  1616. data (or stringified macro arguments), the attempt to lex the
  1617. strings could fail with an diagnostic. Temporarily install an
  1618. diagnostic-handler to catch the diagnostic, so that it can lead to this call
  1619. failing, rather than being emitted as a user-visible diagnostic.
  1620. If an diagnostic does occur, we should see it via the return value of
  1621. cpp_interpret_string_1. */
  1622. bool (*saved_diagnostic_handler) (cpp_reader *, enum cpp_diagnostic_level,
  1623. enum cpp_warning_reason, rich_location *,
  1624. const char *, va_list *)
  1625. ATTRIBUTE_FPTR_PRINTF(5,0);
  1626. saved_diagnostic_handler = pfile->cb.diagnostic;
  1627. pfile->cb.diagnostic = noop_diagnostic_cb;
  1628. bool result = cpp_interpret_string_1 (pfile, from, count, NULL, type,
  1629. loc_readers, out);
  1630. /* Restore the saved diagnostic-handler. */
  1631. pfile->cb.diagnostic = saved_diagnostic_handler;
  1632. if (!result)
  1633. return "cpp_interpret_string_1 failed";
  1634. /* Success. */
  1635. return NULL;
  1636. }
  1637. /* Subroutine of do_line and do_linemarker. Convert escape sequences
  1638. in a string, but do not perform character set conversion. */
  1639. bool
  1640. cpp_interpret_string_notranslate (cpp_reader *pfile, const cpp_string *from,
  1641. size_t count, cpp_string *to,
  1642. enum cpp_ttype type ATTRIBUTE_UNUSED)
  1643. {
  1644. struct cset_converter save_narrow_cset_desc = pfile->narrow_cset_desc;
  1645. bool retval;
  1646. pfile->narrow_cset_desc.func = convert_no_conversion;
  1647. pfile->narrow_cset_desc.cd = (iconv_t) -1;
  1648. pfile->narrow_cset_desc.width = CPP_OPTION (pfile, char_precision);
  1649. retval = cpp_interpret_string (pfile, from, count, to, CPP_STRING);
  1650. pfile->narrow_cset_desc = save_narrow_cset_desc;
  1651. return retval;
  1652. }
  1653. /* Subroutine of cpp_interpret_charconst which performs the conversion
  1654. to a number, for narrow strings. STR is the string structure returned
  1655. by cpp_interpret_string. PCHARS_SEEN and UNSIGNEDP are as for
  1656. cpp_interpret_charconst. TYPE is the token type. */
  1657. static cppchar_t
  1658. narrow_str_to_charconst (cpp_reader *pfile, cpp_string str,
  1659. unsigned int *pchars_seen, int *unsignedp,
  1660. enum cpp_ttype type)
  1661. {
  1662. size_t width = CPP_OPTION (pfile, char_precision);
  1663. size_t max_chars = CPP_OPTION (pfile, int_precision) / width;
  1664. size_t mask = width_to_mask (width);
  1665. size_t i;
  1666. cppchar_t result, c;
  1667. bool unsigned_p;
  1668. /* The value of a multi-character character constant, or a
  1669. single-character character constant whose representation in the
  1670. execution character set is more than one byte long, is
  1671. implementation defined. This implementation defines it to be the
  1672. number formed by interpreting the byte sequence in memory as a
  1673. big-endian binary number. If overflow occurs, the high bytes are
  1674. lost, and a warning is issued.
  1675. We don't want to process the NUL terminator handed back by
  1676. cpp_interpret_string. */
  1677. result = 0;
  1678. for (i = 0; i < str.len - 1; i++)
  1679. {
  1680. c = str.text[i] & mask;
  1681. if (width < BITS_PER_CPPCHAR_T)
  1682. result = (result << width) | c;
  1683. else
  1684. result = c;
  1685. }
  1686. if (type == CPP_UTF8CHAR)
  1687. max_chars = 1;
  1688. if (i > max_chars)
  1689. {
  1690. i = max_chars;
  1691. cpp_error (pfile, type == CPP_UTF8CHAR ? CPP_DL_ERROR : CPP_DL_WARNING,
  1692. "character constant too long for its type");
  1693. }
  1694. else if (i > 1 && CPP_OPTION (pfile, warn_multichar))
  1695. cpp_warning (pfile, CPP_W_MULTICHAR, "multi-character character constant");
  1696. /* Multichar constants are of type int and therefore signed. */
  1697. if (i > 1)
  1698. unsigned_p = 0;
  1699. else if (type == CPP_UTF8CHAR && !CPP_OPTION (pfile, cplusplus))
  1700. unsigned_p = 1;
  1701. else
  1702. unsigned_p = CPP_OPTION (pfile, unsigned_char);
  1703. /* Truncate the constant to its natural width, and simultaneously
  1704. sign- or zero-extend to the full width of cppchar_t.
  1705. For single-character constants, the value is WIDTH bits wide.
  1706. For multi-character constants, the value is INT_PRECISION bits wide. */
  1707. if (i > 1)
  1708. width = CPP_OPTION (pfile, int_precision);
  1709. if (width < BITS_PER_CPPCHAR_T)
  1710. {
  1711. mask = ((cppchar_t) 1 << width) - 1;
  1712. if (unsigned_p || !(result & (1 << (width - 1))))
  1713. result &= mask;
  1714. else
  1715. result |= ~mask;
  1716. }
  1717. *pchars_seen = i;
  1718. *unsignedp = unsigned_p;
  1719. return result;
  1720. }
  1721. /* Subroutine of cpp_interpret_charconst which performs the conversion
  1722. to a number, for wide strings. STR is the string structure returned
  1723. by cpp_interpret_string. PCHARS_SEEN and UNSIGNEDP are as for
  1724. cpp_interpret_charconst. TYPE is the token type. */
  1725. static cppchar_t
  1726. wide_str_to_charconst (cpp_reader *pfile, cpp_string str,
  1727. unsigned int *pchars_seen, int *unsignedp,
  1728. enum cpp_ttype type)
  1729. {
  1730. bool bigend = CPP_OPTION (pfile, bytes_big_endian);
  1731. size_t width = converter_for_type (pfile, type).width;
  1732. size_t cwidth = CPP_OPTION (pfile, char_precision);
  1733. size_t mask = width_to_mask (width);
  1734. size_t cmask = width_to_mask (cwidth);
  1735. size_t nbwc = width / cwidth;
  1736. size_t off, i;
  1737. cppchar_t result = 0, c;
  1738. if (str.len <= nbwc)
  1739. {
  1740. /* Error recovery, if no errors have been diagnosed previously,
  1741. there should be at least two wide characters. Empty literals
  1742. are diagnosed earlier and we can get just the zero terminator
  1743. only if there were errors diagnosed during conversion. */
  1744. *pchars_seen = 0;
  1745. *unsignedp = 0;
  1746. return 0;
  1747. }
  1748. /* This is finicky because the string is in the target's byte order,
  1749. which may not be our byte order. Only the last character, ignoring
  1750. the NUL terminator, is relevant. */
  1751. off = str.len - (nbwc * 2);
  1752. result = 0;
  1753. for (i = 0; i < nbwc; i++)
  1754. {
  1755. c = bigend ? str.text[off + i] : str.text[off + nbwc - i - 1];
  1756. result = (result << cwidth) | (c & cmask);
  1757. }
  1758. /* Wide character constants have type wchar_t, and a single
  1759. character exactly fills a wchar_t, so a multi-character wide
  1760. character constant is guaranteed to overflow. */
  1761. if (str.len > nbwc * 2)
  1762. cpp_error (pfile, (CPP_OPTION (pfile, cplusplus)
  1763. && (type == CPP_CHAR16 || type == CPP_CHAR32))
  1764. ? CPP_DL_ERROR : CPP_DL_WARNING,
  1765. "character constant too long for its type");
  1766. /* Truncate the constant to its natural width, and simultaneously
  1767. sign- or zero-extend to the full width of cppchar_t. */
  1768. if (width < BITS_PER_CPPCHAR_T)
  1769. {
  1770. if (type == CPP_CHAR16 || type == CPP_CHAR32
  1771. || CPP_OPTION (pfile, unsigned_wchar)
  1772. || !(result & (1 << (width - 1))))
  1773. result &= mask;
  1774. else
  1775. result |= ~mask;
  1776. }
  1777. if (type == CPP_CHAR16 || type == CPP_CHAR32
  1778. || CPP_OPTION (pfile, unsigned_wchar))
  1779. *unsignedp = 1;
  1780. else
  1781. *unsignedp = 0;
  1782. *pchars_seen = 1;
  1783. return result;
  1784. }
  1785. /* Interpret a (possibly wide) character constant in TOKEN.
  1786. PCHARS_SEEN points to a variable that is filled in with the number
  1787. of characters seen, and UNSIGNEDP to a variable that indicates
  1788. whether the result has signed type. */
  1789. cppchar_t
  1790. cpp_interpret_charconst (cpp_reader *pfile, const cpp_token *token,
  1791. unsigned int *pchars_seen, int *unsignedp)
  1792. {
  1793. cpp_string str = { 0, 0 };
  1794. bool wide = (token->type != CPP_CHAR && token->type != CPP_UTF8CHAR);
  1795. int u8 = 2 * int(token->type == CPP_UTF8CHAR);
  1796. cppchar_t result;
  1797. /* An empty constant will appear as L'', u'', U'', u8'', or '' */
  1798. if (token->val.str.len == (size_t) (2 + wide + u8))
  1799. {
  1800. cpp_error (pfile, CPP_DL_ERROR, "empty character constant");
  1801. *pchars_seen = 0;
  1802. *unsignedp = 0;
  1803. return 0;
  1804. }
  1805. else if (!cpp_interpret_string (pfile, &token->val.str, 1, &str,
  1806. token->type))
  1807. {
  1808. *pchars_seen = 0;
  1809. *unsignedp = 0;
  1810. return 0;
  1811. }
  1812. if (wide)
  1813. result = wide_str_to_charconst (pfile, str, pchars_seen, unsignedp,
  1814. token->type);
  1815. else
  1816. result = narrow_str_to_charconst (pfile, str, pchars_seen, unsignedp,
  1817. token->type);
  1818. if (str.text != token->val.str.text)
  1819. free ((void *)str.text);
  1820. return result;
  1821. }
  1822. /* Convert an identifier denoted by ID and LEN, which might contain
  1823. UCN escapes or UTF-8 multibyte chars, to the source character set,
  1824. either UTF-8 or UTF-EBCDIC. Assumes that the identifier is actually
  1825. a valid identifier. */
  1826. cpp_hashnode *
  1827. _cpp_interpret_identifier (cpp_reader *pfile, const uchar *id, size_t len)
  1828. {
  1829. /* It turns out that a UCN escape always turns into fewer characters
  1830. than the escape itself, so we can allocate a temporary in advance. */
  1831. uchar * buf = (uchar *) alloca (len + 1);
  1832. uchar * bufp = buf;
  1833. size_t idp;
  1834. for (idp = 0; idp < len; idp++)
  1835. if (id[idp] != '\\')
  1836. *bufp++ = id[idp];
  1837. else
  1838. {
  1839. unsigned length = id[idp+1] == 'u' ? 4 : 8;
  1840. cppchar_t value = 0;
  1841. size_t bufleft = len - (bufp - buf);
  1842. int rval;
  1843. idp += 2;
  1844. while (length && idp < len && ISXDIGIT (id[idp]))
  1845. {
  1846. value = (value << 4) + hex_value (id[idp]);
  1847. idp++;
  1848. length--;
  1849. }
  1850. idp--;
  1851. /* Special case for EBCDIC: if the identifier contains
  1852. a '$' specified using a UCN, translate it to EBCDIC. */
  1853. if (value == 0x24)
  1854. {
  1855. *bufp++ = '$';
  1856. continue;
  1857. }
  1858. rval = one_cppchar_to_utf8 (value, &bufp, &bufleft);
  1859. if (rval)
  1860. {
  1861. errno = rval;
  1862. cpp_errno (pfile, CPP_DL_ERROR,
  1863. "converting UCN to source character set");
  1864. break;
  1865. }
  1866. }
  1867. return CPP_HASHNODE (ht_lookup (pfile->hash_table,
  1868. buf, bufp - buf, HT_ALLOC));
  1869. }
  1870. /* Utility to strip a UTF-8 byte order marking from the beginning
  1871. of a buffer. Returns the number of bytes to skip, which currently
  1872. will be either 0 or 3. */
  1873. int
  1874. cpp_check_utf8_bom (const char *data, size_t data_length)
  1875. {
  1876. #if HOST_CHARSET == HOST_CHARSET_ASCII
  1877. const unsigned char *udata = (const unsigned char *) data;
  1878. if (data_length >= 3 && udata[0] == 0xef && udata[1] == 0xbb
  1879. && udata[2] == 0xbf)
  1880. return 3;
  1881. #endif
  1882. return 0;
  1883. }
  1884. /* Convert an input buffer (containing the complete contents of one
  1885. source file) from INPUT_CHARSET to the source character set. INPUT
  1886. points to the input buffer, SIZE is its allocated size, and LEN is
  1887. the length of the meaningful data within the buffer. The
  1888. translated buffer is returned, *ST_SIZE is set to the length of
  1889. the meaningful data within the translated buffer, and *BUFFER_START
  1890. is set to the start of the returned buffer. *BUFFER_START may
  1891. differ from the return value in the case of a BOM or other ignored
  1892. marker information.
  1893. INPUT is expected to have been allocated with xmalloc. This
  1894. function will either set *BUFFER_START to INPUT, or free it and set
  1895. *BUFFER_START to a pointer to another xmalloc-allocated block of
  1896. memory.
  1897. PFILE is only used to generate diagnostics; setting it to NULL suppresses
  1898. diagnostics, and causes a return of NULL if there was any error instead. */
  1899. uchar *
  1900. _cpp_convert_input (cpp_reader *pfile, const char *input_charset,
  1901. uchar *input, size_t size, size_t len,
  1902. const unsigned char **buffer_start, off_t *st_size)
  1903. {
  1904. struct cset_converter input_cset;
  1905. struct _cpp_strbuf to;
  1906. unsigned char *buffer;
  1907. input_cset = init_iconv_desc (pfile, SOURCE_CHARSET, input_charset);
  1908. if (input_cset.func == convert_no_conversion)
  1909. {
  1910. to.text = input;
  1911. to.asize = size;
  1912. to.len = len;
  1913. }
  1914. else
  1915. {
  1916. to.asize = MAX (65536, len);
  1917. to.text = XNEWVEC (uchar, to.asize);
  1918. to.len = 0;
  1919. const bool ok = APPLY_CONVERSION (input_cset, input, len, &to);
  1920. free (input);
  1921. /* Clean up the mess. */
  1922. if (input_cset.func == convert_using_iconv)
  1923. iconv_close (input_cset.cd);
  1924. /* Handle conversion failure. */
  1925. if (!ok)
  1926. {
  1927. if (!pfile)
  1928. {
  1929. XDELETEVEC (to.text);
  1930. *buffer_start = NULL;
  1931. *st_size = 0;
  1932. return NULL;
  1933. }
  1934. cpp_error (pfile, CPP_DL_ERROR, "failure to convert %s to %s",
  1935. input_charset, SOURCE_CHARSET);
  1936. }
  1937. }
  1938. /* Resize buffer if we allocated substantially too much, or if we
  1939. haven't enough space for the \n-terminator or following
  1940. 15 bytes of padding (used to quiet warnings from valgrind or
  1941. Address Sanitizer, when the optimized lexer accesses aligned
  1942. 16-byte memory chunks, including the bytes after the malloced,
  1943. area, and stops lexing on '\n'). */
  1944. if (to.len + 4096 < to.asize || to.len + 16 > to.asize)
  1945. to.text = XRESIZEVEC (uchar, to.text, to.len + 16);
  1946. memset (to.text + to.len, '\0', 16);
  1947. /* If the file is using old-school Mac line endings (\r only),
  1948. terminate with another \r, not an \n, so that we do not mistake
  1949. the \r\n sequence for a single DOS line ending and erroneously
  1950. issue the "No newline at end of file" diagnostic. */
  1951. if (to.len && to.text[to.len - 1] == '\r')
  1952. to.text[to.len] = '\r';
  1953. else
  1954. to.text[to.len] = '\n';
  1955. buffer = to.text;
  1956. *st_size = to.len;
  1957. /* Ignore a UTF-8 BOM if we see one and the source charset is UTF-8. Note
  1958. that glib'c UTF-8 iconv() provider (as of glibc 2.7) does not ignore a
  1959. BOM -- however, even if it did, we would still need this code due
  1960. to the 'convert_no_conversion' case. */
  1961. const int bom_len = cpp_check_utf8_bom ((const char *) to.text, to.len);
  1962. *st_size -= bom_len;
  1963. buffer += bom_len;
  1964. *buffer_start = to.text;
  1965. return buffer;
  1966. }
  1967. /* Decide on the default encoding to assume for input files. */
  1968. const char *
  1969. _cpp_default_encoding (void)
  1970. {
  1971. const char *current_encoding = NULL;
  1972. /* We disable this because the default codeset is 7-bit ASCII on
  1973. most platforms, and this causes conversion failures on every
  1974. file in GCC that happens to have one of the upper 128 characters
  1975. in it -- most likely, as part of the name of a contributor.
  1976. We should definitely recognize in-band markers of file encoding,
  1977. like:
  1978. - the appropriate Unicode byte-order mark (FE FF) to recognize
  1979. UTF16 and UCS4 (in both big-endian and little-endian flavors)
  1980. and UTF8
  1981. - a "#i", "#d", "/ *", "//", " #p" or "#p" (for #pragma) to
  1982. distinguish ASCII and EBCDIC.
  1983. - now we can parse something like "#pragma GCC encoding <xyz>
  1984. on the first line, or even Emacs/VIM's mode line tags (there's
  1985. a problem here in that VIM uses the last line, and Emacs has
  1986. its more elaborate "local variables" convention).
  1987. - investigate whether Java has another common convention, which
  1988. would be friendly to support.
  1989. (Zack Weinberg and Paolo Bonzini, May 20th 2004) */
  1990. #if defined (HAVE_LOCALE_H) && defined (HAVE_LANGINFO_CODESET) && 0
  1991. setlocale (LC_CTYPE, "");
  1992. current_encoding = nl_langinfo (CODESET);
  1993. #endif
  1994. if (current_encoding == NULL || *current_encoding == '\0')
  1995. current_encoding = SOURCE_CHARSET;
  1996. return current_encoding;
  1997. }
  1998. /* Check if the configured input charset requires no conversion, other than
  1999. possibly stripping a UTF-8 BOM. */
  2000. bool cpp_input_conversion_is_trivial (const char *input_charset)
  2001. {
  2002. return !strcasecmp (input_charset, SOURCE_CHARSET);
  2003. }
  2004. /* Implementation of class cpp_string_location_reader. */
  2005. /* Constructor for cpp_string_location_reader. */
  2006. cpp_string_location_reader::
  2007. cpp_string_location_reader (location_t src_loc,
  2008. line_maps *line_table)
  2009. {
  2010. src_loc = get_range_from_loc (line_table, src_loc).m_start;
  2011. /* SRC_LOC might be a macro location. It only makes sense to do
  2012. column-by-column calculations on ordinary maps, so get the
  2013. corresponding location in an ordinary map. */
  2014. m_loc
  2015. = linemap_resolve_location (line_table, src_loc,
  2016. LRK_SPELLING_LOCATION, NULL);
  2017. const line_map_ordinary *map
  2018. = linemap_check_ordinary (linemap_lookup (line_table, m_loc));
  2019. m_offset_per_column = (1 << map->m_range_bits);
  2020. }
  2021. /* Get the range of the next source byte. */
  2022. source_range
  2023. cpp_string_location_reader::get_next ()
  2024. {
  2025. source_range result;
  2026. result.m_start = m_loc;
  2027. result.m_finish = m_loc;
  2028. if (m_loc <= LINE_MAP_MAX_LOCATION_WITH_COLS)
  2029. m_loc += m_offset_per_column;
  2030. return result;
  2031. }
  2032. cpp_display_width_computation::
  2033. cpp_display_width_computation (const char *data, int data_length,
  2034. const cpp_char_column_policy &policy) :
  2035. m_begin (data),
  2036. m_next (m_begin),
  2037. m_bytes_left (data_length),
  2038. m_policy (policy),
  2039. m_display_cols (0)
  2040. {
  2041. gcc_assert (policy.m_tabstop > 0);
  2042. gcc_assert (policy.m_width_cb);
  2043. }
  2044. /* The main implementation function for class cpp_display_width_computation.
  2045. m_next points on entry to the start of the UTF-8 encoding of the next
  2046. character, and is updated to point just after the last byte of the encoding.
  2047. m_bytes_left contains on entry the remaining size of the buffer into which
  2048. m_next points, and this is also updated accordingly. If m_next does not
  2049. point to a valid UTF-8-encoded sequence, then it will be treated as a single
  2050. byte with display width 1. m_cur_display_col is the current display column,
  2051. relative to which tab stops should be expanded. Returns the display width of
  2052. the codepoint just processed.
  2053. If OUT is non-NULL, it is populated. */
  2054. int
  2055. cpp_display_width_computation::process_next_codepoint (cpp_decoded_char *out)
  2056. {
  2057. cppchar_t c;
  2058. int next_width;
  2059. if (out)
  2060. out->m_start_byte = m_next;
  2061. if (*m_next == '\t')
  2062. {
  2063. ++m_next;
  2064. --m_bytes_left;
  2065. next_width = m_policy.m_tabstop - (m_display_cols % m_policy.m_tabstop);
  2066. if (out)
  2067. {
  2068. out->m_ch = '\t';
  2069. out->m_valid_ch = true;
  2070. }
  2071. }
  2072. else if (one_utf8_to_cppchar ((const uchar **) &m_next, &m_bytes_left, &c)
  2073. != 0)
  2074. {
  2075. /* Input is not convertible to UTF-8. This could be fine, e.g. in a
  2076. string literal, so don't complain. Just treat it as if it has a width
  2077. of one. */
  2078. ++m_next;
  2079. --m_bytes_left;
  2080. next_width = m_policy.m_undecoded_byte_width;
  2081. if (out)
  2082. out->m_valid_ch = false;
  2083. }
  2084. else
  2085. {
  2086. /* one_utf8_to_cppchar() has updated m_next and m_bytes_left for us. */
  2087. next_width = m_policy.m_width_cb (c);
  2088. if (out)
  2089. {
  2090. out->m_ch = c;
  2091. out->m_valid_ch = true;
  2092. }
  2093. }
  2094. if (out)
  2095. out->m_next_byte = m_next;
  2096. m_display_cols += next_width;
  2097. return next_width;
  2098. }
  2099. /* Utility to advance the byte stream by the minimum amount needed to consume
  2100. N display columns. Returns the number of display columns that were
  2101. actually skipped. This could be less than N, if there was not enough data,
  2102. or more than N, if the last character to be skipped had a sufficiently large
  2103. display width. */
  2104. int
  2105. cpp_display_width_computation::advance_display_cols (int n)
  2106. {
  2107. const int start = m_display_cols;
  2108. const int target = start + n;
  2109. while (m_display_cols < target && !done ())
  2110. process_next_codepoint (NULL);
  2111. return m_display_cols - start;
  2112. }
  2113. /* For the string of length DATA_LENGTH bytes that begins at DATA, compute
  2114. how many display columns are occupied by the first COLUMN bytes. COLUMN
  2115. may exceed DATA_LENGTH, in which case the phantom bytes at the end are
  2116. treated as if they have display width 1. Tabs are expanded to the next tab
  2117. stop, relative to the start of DATA, and non-printable-ASCII characters
  2118. will be escaped as per POLICY. */
  2119. int
  2120. cpp_byte_column_to_display_column (const char *data, int data_length,
  2121. int column,
  2122. const cpp_char_column_policy &policy)
  2123. {
  2124. const int offset = MAX (0, column - data_length);
  2125. cpp_display_width_computation dw (data, column - offset, policy);
  2126. while (!dw.done ())
  2127. dw.process_next_codepoint (NULL);
  2128. return dw.display_cols_processed () + offset;
  2129. }
  2130. /* For the string of length DATA_LENGTH bytes that begins at DATA, compute
  2131. the least number of bytes that will result in at least DISPLAY_COL display
  2132. columns. The return value may exceed DATA_LENGTH if the entire string does
  2133. not occupy enough display columns. Non-printable-ASCII characters
  2134. will be escaped as per POLICY. */
  2135. int
  2136. cpp_display_column_to_byte_column (const char *data, int data_length,
  2137. int display_col,
  2138. const cpp_char_column_policy &policy)
  2139. {
  2140. cpp_display_width_computation dw (data, data_length, policy);
  2141. const int avail_display = dw.advance_display_cols (display_col);
  2142. return dw.bytes_processed () + MAX (0, display_col - avail_display);
  2143. }
  2144. /* Our own version of wcwidth(). We don't use the actual wcwidth() in glibc,
  2145. because that will inspect the user's locale, and in particular in an ASCII
  2146. locale, it will not return anything useful for extended characters. But GCC
  2147. in other respects (see e.g. _cpp_default_encoding()) behaves as if
  2148. everything is UTF-8. We also make some tweaks that are useful for the way
  2149. GCC needs to use this data, e.g. tabs and other control characters should be
  2150. treated as having width 1. The lookup tables are generated from
  2151. contrib/unicode/gen_wcwidth.py and were made by simply calling glibc
  2152. wcwidth() on all codepoints, then applying the small tweaks. These tables
  2153. are not highly optimized, but for the present purpose of outputting
  2154. diagnostics, they are sufficient. */
  2155. #include "generated_cpp_wcwidth.h"
  2156. int cpp_wcwidth (cppchar_t c)
  2157. {
  2158. if (__builtin_expect (c <= wcwidth_range_ends[0], true))
  2159. return wcwidth_widths[0];
  2160. /* Binary search the tables. */
  2161. int begin = 1;
  2162. static const int end
  2163. = sizeof wcwidth_range_ends / sizeof (*wcwidth_range_ends);
  2164. int len = end - begin;
  2165. do
  2166. {
  2167. int half = len/2;
  2168. int middle = begin + half;
  2169. if (c > wcwidth_range_ends[middle])
  2170. {
  2171. begin = middle + 1;
  2172. len -= half + 1;
  2173. }
  2174. else
  2175. len = half;
  2176. } while (len);
  2177. if (__builtin_expect (begin != end, true))
  2178. return wcwidth_widths[begin];
  2179. return 1;
  2180. }