unicodedata.c 45 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544
  1. /* ------------------------------------------------------------------------
  2. unicodedata -- Provides access to the Unicode database.
  3. The current version number is reported in the unidata_version constant.
  4. Written by Marc-Andre Lemburg (mal@lemburg.com).
  5. Modified for Python 2.0 by Fredrik Lundh (fredrik@pythonware.com)
  6. Modified by Martin v. Löwis (martin@v.loewis.de)
  7. Copyright (c) Corporation for National Research Initiatives.
  8. ------------------------------------------------------------------------ */
  9. #ifndef Py_BUILD_CORE_BUILTIN
  10. # define Py_BUILD_CORE_MODULE 1
  11. #endif
  12. #define PY_SSIZE_T_CLEAN
  13. #include "Python.h"
  14. #include "pycore_ucnhash.h" // _PyUnicode_Name_CAPI
  15. #include "structmember.h" // PyMemberDef
  16. #include <stdbool.h>
  17. /*[clinic input]
  18. module unicodedata
  19. class unicodedata.UCD 'PreviousDBVersion *' '<not used>'
  20. [clinic start generated code]*/
  21. /*[clinic end generated code: output=da39a3ee5e6b4b0d input=e47113e05924be43]*/
  22. /* character properties */
  23. typedef struct {
  24. const unsigned char category; /* index into
  25. _PyUnicode_CategoryNames */
  26. const unsigned char combining; /* combining class value 0 - 255 */
  27. const unsigned char bidirectional; /* index into
  28. _PyUnicode_BidirectionalNames */
  29. const unsigned char mirrored; /* true if mirrored in bidir mode */
  30. const unsigned char east_asian_width; /* index into
  31. _PyUnicode_EastAsianWidth */
  32. const unsigned char normalization_quick_check; /* see is_normalized() */
  33. } _PyUnicode_DatabaseRecord;
  34. typedef struct change_record {
  35. /* sequence of fields should be the same as in merge_old_version */
  36. const unsigned char bidir_changed;
  37. const unsigned char category_changed;
  38. const unsigned char decimal_changed;
  39. const unsigned char mirrored_changed;
  40. const unsigned char east_asian_width_changed;
  41. const double numeric_changed;
  42. } change_record;
  43. /* data file generated by Tools/unicode/makeunicodedata.py */
  44. #include "unicodedata_db.h"
  45. static const _PyUnicode_DatabaseRecord*
  46. _getrecord_ex(Py_UCS4 code)
  47. {
  48. int index;
  49. if (code >= 0x110000)
  50. index = 0;
  51. else {
  52. index = index1[(code>>SHIFT)];
  53. index = index2[(index<<SHIFT)+(code&((1<<SHIFT)-1))];
  54. }
  55. return &_PyUnicode_Database_Records[index];
  56. }
  57. /* ------------- Previous-version API ------------------------------------- */
  58. typedef struct previous_version {
  59. PyObject_HEAD
  60. const char *name;
  61. const change_record* (*getrecord)(Py_UCS4);
  62. Py_UCS4 (*normalization)(Py_UCS4);
  63. } PreviousDBVersion;
  64. #include "clinic/unicodedata.c.h"
  65. #define get_old_record(self, v) ((((PreviousDBVersion*)self)->getrecord)(v))
  66. static PyMemberDef DB_members[] = {
  67. {"unidata_version", T_STRING, offsetof(PreviousDBVersion, name), READONLY},
  68. {NULL}
  69. };
  70. // Check if self is an unicodedata.UCD instance.
  71. // If self is NULL (when the PyCapsule C API is used), return 0.
  72. // PyModule_Check() is used to avoid having to retrieve the ucd_type.
  73. // See unicodedata_functions comment to the rationale of this macro.
  74. #define UCD_Check(self) (self != NULL && !PyModule_Check(self))
  75. static PyObject*
  76. new_previous_version(PyTypeObject *ucd_type,
  77. const char*name, const change_record* (*getrecord)(Py_UCS4),
  78. Py_UCS4 (*normalization)(Py_UCS4))
  79. {
  80. PreviousDBVersion *self;
  81. self = PyObject_GC_New(PreviousDBVersion, ucd_type);
  82. if (self == NULL)
  83. return NULL;
  84. self->name = name;
  85. self->getrecord = getrecord;
  86. self->normalization = normalization;
  87. PyObject_GC_Track(self);
  88. return (PyObject*)self;
  89. }
  90. /* --- Module API --------------------------------------------------------- */
  91. /*[clinic input]
  92. unicodedata.UCD.decimal
  93. self: self
  94. chr: int(accept={str})
  95. default: object=NULL
  96. /
  97. Converts a Unicode character into its equivalent decimal value.
  98. Returns the decimal value assigned to the character chr as integer.
  99. If no such value is defined, default is returned, or, if not given,
  100. ValueError is raised.
  101. [clinic start generated code]*/
  102. static PyObject *
  103. unicodedata_UCD_decimal_impl(PyObject *self, int chr,
  104. PyObject *default_value)
  105. /*[clinic end generated code: output=be23376e1a185231 input=933f8107993f23d0]*/
  106. {
  107. int have_old = 0;
  108. long rc;
  109. Py_UCS4 c = (Py_UCS4)chr;
  110. if (UCD_Check(self)) {
  111. const change_record *old = get_old_record(self, c);
  112. if (old->category_changed == 0) {
  113. /* unassigned */
  114. have_old = 1;
  115. rc = -1;
  116. }
  117. else if (old->decimal_changed != 0xFF) {
  118. have_old = 1;
  119. rc = old->decimal_changed;
  120. }
  121. }
  122. if (!have_old)
  123. rc = Py_UNICODE_TODECIMAL(c);
  124. if (rc < 0) {
  125. if (default_value == NULL) {
  126. PyErr_SetString(PyExc_ValueError,
  127. "not a decimal");
  128. return NULL;
  129. }
  130. else {
  131. return Py_NewRef(default_value);
  132. }
  133. }
  134. return PyLong_FromLong(rc);
  135. }
  136. /*[clinic input]
  137. unicodedata.UCD.digit
  138. self: self
  139. chr: int(accept={str})
  140. default: object=NULL
  141. /
  142. Converts a Unicode character into its equivalent digit value.
  143. Returns the digit value assigned to the character chr as integer.
  144. If no such value is defined, default is returned, or, if not given,
  145. ValueError is raised.
  146. [clinic start generated code]*/
  147. static PyObject *
  148. unicodedata_UCD_digit_impl(PyObject *self, int chr, PyObject *default_value)
  149. /*[clinic end generated code: output=96e18c950171fd2f input=e27d6e4565cd29f2]*/
  150. {
  151. long rc;
  152. Py_UCS4 c = (Py_UCS4)chr;
  153. rc = Py_UNICODE_TODIGIT(c);
  154. if (rc < 0) {
  155. if (default_value == NULL) {
  156. PyErr_SetString(PyExc_ValueError, "not a digit");
  157. return NULL;
  158. }
  159. else {
  160. return Py_NewRef(default_value);
  161. }
  162. }
  163. return PyLong_FromLong(rc);
  164. }
  165. /*[clinic input]
  166. unicodedata.UCD.numeric
  167. self: self
  168. chr: int(accept={str})
  169. default: object=NULL
  170. /
  171. Converts a Unicode character into its equivalent numeric value.
  172. Returns the numeric value assigned to the character chr as float.
  173. If no such value is defined, default is returned, or, if not given,
  174. ValueError is raised.
  175. [clinic start generated code]*/
  176. static PyObject *
  177. unicodedata_UCD_numeric_impl(PyObject *self, int chr,
  178. PyObject *default_value)
  179. /*[clinic end generated code: output=53ce281fe85b10c4 input=fdf5871a5542893c]*/
  180. {
  181. int have_old = 0;
  182. double rc;
  183. Py_UCS4 c = (Py_UCS4)chr;
  184. if (UCD_Check(self)) {
  185. const change_record *old = get_old_record(self, c);
  186. if (old->category_changed == 0) {
  187. /* unassigned */
  188. have_old = 1;
  189. rc = -1.0;
  190. }
  191. else if (old->decimal_changed != 0xFF) {
  192. have_old = 1;
  193. rc = old->decimal_changed;
  194. }
  195. }
  196. if (!have_old)
  197. rc = Py_UNICODE_TONUMERIC(c);
  198. if (rc == -1.0) {
  199. if (default_value == NULL) {
  200. PyErr_SetString(PyExc_ValueError, "not a numeric character");
  201. return NULL;
  202. }
  203. else {
  204. return Py_NewRef(default_value);
  205. }
  206. }
  207. return PyFloat_FromDouble(rc);
  208. }
  209. /*[clinic input]
  210. unicodedata.UCD.category
  211. self: self
  212. chr: int(accept={str})
  213. /
  214. Returns the general category assigned to the character chr as string.
  215. [clinic start generated code]*/
  216. static PyObject *
  217. unicodedata_UCD_category_impl(PyObject *self, int chr)
  218. /*[clinic end generated code: output=8571539ee2e6783a input=27d6f3d85050bc06]*/
  219. {
  220. int index;
  221. Py_UCS4 c = (Py_UCS4)chr;
  222. index = (int) _getrecord_ex(c)->category;
  223. if (UCD_Check(self)) {
  224. const change_record *old = get_old_record(self, c);
  225. if (old->category_changed != 0xFF)
  226. index = old->category_changed;
  227. }
  228. return PyUnicode_FromString(_PyUnicode_CategoryNames[index]);
  229. }
  230. /*[clinic input]
  231. unicodedata.UCD.bidirectional
  232. self: self
  233. chr: int(accept={str})
  234. /
  235. Returns the bidirectional class assigned to the character chr as string.
  236. If no such value is defined, an empty string is returned.
  237. [clinic start generated code]*/
  238. static PyObject *
  239. unicodedata_UCD_bidirectional_impl(PyObject *self, int chr)
  240. /*[clinic end generated code: output=d36310ce2039bb92 input=b3d8f42cebfcf475]*/
  241. {
  242. int index;
  243. Py_UCS4 c = (Py_UCS4)chr;
  244. index = (int) _getrecord_ex(c)->bidirectional;
  245. if (UCD_Check(self)) {
  246. const change_record *old = get_old_record(self, c);
  247. if (old->category_changed == 0)
  248. index = 0; /* unassigned */
  249. else if (old->bidir_changed != 0xFF)
  250. index = old->bidir_changed;
  251. }
  252. return PyUnicode_FromString(_PyUnicode_BidirectionalNames[index]);
  253. }
  254. /*[clinic input]
  255. unicodedata.UCD.combining -> int
  256. self: self
  257. chr: int(accept={str})
  258. /
  259. Returns the canonical combining class assigned to the character chr as integer.
  260. Returns 0 if no combining class is defined.
  261. [clinic start generated code]*/
  262. static int
  263. unicodedata_UCD_combining_impl(PyObject *self, int chr)
  264. /*[clinic end generated code: output=cad056d0cb6a5920 input=9f2d6b2a95d0a22a]*/
  265. {
  266. int index;
  267. Py_UCS4 c = (Py_UCS4)chr;
  268. index = (int) _getrecord_ex(c)->combining;
  269. if (UCD_Check(self)) {
  270. const change_record *old = get_old_record(self, c);
  271. if (old->category_changed == 0)
  272. index = 0; /* unassigned */
  273. }
  274. return index;
  275. }
  276. /*[clinic input]
  277. unicodedata.UCD.mirrored -> int
  278. self: self
  279. chr: int(accept={str})
  280. /
  281. Returns the mirrored property assigned to the character chr as integer.
  282. Returns 1 if the character has been identified as a "mirrored"
  283. character in bidirectional text, 0 otherwise.
  284. [clinic start generated code]*/
  285. static int
  286. unicodedata_UCD_mirrored_impl(PyObject *self, int chr)
  287. /*[clinic end generated code: output=2532dbf8121b50e6 input=5dd400d351ae6f3b]*/
  288. {
  289. int index;
  290. Py_UCS4 c = (Py_UCS4)chr;
  291. index = (int) _getrecord_ex(c)->mirrored;
  292. if (UCD_Check(self)) {
  293. const change_record *old = get_old_record(self, c);
  294. if (old->category_changed == 0)
  295. index = 0; /* unassigned */
  296. else if (old->mirrored_changed != 0xFF)
  297. index = old->mirrored_changed;
  298. }
  299. return index;
  300. }
  301. /*[clinic input]
  302. unicodedata.UCD.east_asian_width
  303. self: self
  304. chr: int(accept={str})
  305. /
  306. Returns the east asian width assigned to the character chr as string.
  307. [clinic start generated code]*/
  308. static PyObject *
  309. unicodedata_UCD_east_asian_width_impl(PyObject *self, int chr)
  310. /*[clinic end generated code: output=484e8537d9ee8197 input=c4854798aab026e0]*/
  311. {
  312. int index;
  313. Py_UCS4 c = (Py_UCS4)chr;
  314. index = (int) _getrecord_ex(c)->east_asian_width;
  315. if (UCD_Check(self)) {
  316. const change_record *old = get_old_record(self, c);
  317. if (old->category_changed == 0)
  318. index = 0; /* unassigned */
  319. else if (old->east_asian_width_changed != 0xFF)
  320. index = old->east_asian_width_changed;
  321. }
  322. return PyUnicode_FromString(_PyUnicode_EastAsianWidthNames[index]);
  323. }
  324. /*[clinic input]
  325. unicodedata.UCD.decomposition
  326. self: self
  327. chr: int(accept={str})
  328. /
  329. Returns the character decomposition mapping assigned to the character chr as string.
  330. An empty string is returned in case no such mapping is defined.
  331. [clinic start generated code]*/
  332. static PyObject *
  333. unicodedata_UCD_decomposition_impl(PyObject *self, int chr)
  334. /*[clinic end generated code: output=7d699f3ec7565d27 input=e4c12459ad68507b]*/
  335. {
  336. char decomp[256];
  337. int code, index, count;
  338. size_t i;
  339. unsigned int prefix_index;
  340. Py_UCS4 c = (Py_UCS4)chr;
  341. code = (int)c;
  342. if (UCD_Check(self)) {
  343. const change_record *old = get_old_record(self, c);
  344. if (old->category_changed == 0)
  345. return PyUnicode_FromString(""); /* unassigned */
  346. }
  347. if (code < 0 || code >= 0x110000)
  348. index = 0;
  349. else {
  350. index = decomp_index1[(code>>DECOMP_SHIFT)];
  351. index = decomp_index2[(index<<DECOMP_SHIFT)+
  352. (code&((1<<DECOMP_SHIFT)-1))];
  353. }
  354. /* high byte is number of hex bytes (usually one or two), low byte
  355. is prefix code (from*/
  356. count = decomp_data[index] >> 8;
  357. /* XXX: could allocate the PyString up front instead
  358. (strlen(prefix) + 5 * count + 1 bytes) */
  359. /* Based on how index is calculated above and decomp_data is generated
  360. from Tools/unicode/makeunicodedata.py, it should not be possible
  361. to overflow decomp_prefix. */
  362. prefix_index = decomp_data[index] & 255;
  363. assert(prefix_index < Py_ARRAY_LENGTH(decomp_prefix));
  364. /* copy prefix */
  365. i = strlen(decomp_prefix[prefix_index]);
  366. memcpy(decomp, decomp_prefix[prefix_index], i);
  367. while (count-- > 0) {
  368. if (i)
  369. decomp[i++] = ' ';
  370. assert(i < sizeof(decomp));
  371. PyOS_snprintf(decomp + i, sizeof(decomp) - i, "%04X",
  372. decomp_data[++index]);
  373. i += strlen(decomp + i);
  374. }
  375. return PyUnicode_FromStringAndSize(decomp, i);
  376. }
  377. static void
  378. get_decomp_record(PyObject *self, Py_UCS4 code,
  379. int *index, int *prefix, int *count)
  380. {
  381. if (code >= 0x110000) {
  382. *index = 0;
  383. }
  384. else if (UCD_Check(self)
  385. && get_old_record(self, code)->category_changed==0) {
  386. /* unassigned in old version */
  387. *index = 0;
  388. }
  389. else {
  390. *index = decomp_index1[(code>>DECOMP_SHIFT)];
  391. *index = decomp_index2[(*index<<DECOMP_SHIFT)+
  392. (code&((1<<DECOMP_SHIFT)-1))];
  393. }
  394. /* high byte is number of hex bytes (usually one or two), low byte
  395. is prefix code (from*/
  396. *count = decomp_data[*index] >> 8;
  397. *prefix = decomp_data[*index] & 255;
  398. (*index)++;
  399. }
  400. #define SBase 0xAC00
  401. #define LBase 0x1100
  402. #define VBase 0x1161
  403. #define TBase 0x11A7
  404. #define LCount 19
  405. #define VCount 21
  406. #define TCount 28
  407. #define NCount (VCount*TCount)
  408. #define SCount (LCount*NCount)
  409. static PyObject*
  410. nfd_nfkd(PyObject *self, PyObject *input, int k)
  411. {
  412. PyObject *result;
  413. Py_UCS4 *output;
  414. Py_ssize_t i, o, osize;
  415. int kind;
  416. const void *data;
  417. /* Longest decomposition in Unicode 3.2: U+FDFA */
  418. Py_UCS4 stack[20];
  419. Py_ssize_t space, isize;
  420. int index, prefix, count, stackptr;
  421. unsigned char prev, cur;
  422. stackptr = 0;
  423. isize = PyUnicode_GET_LENGTH(input);
  424. space = isize;
  425. /* Overallocate at most 10 characters. */
  426. if (space > 10) {
  427. if (space <= PY_SSIZE_T_MAX - 10)
  428. space += 10;
  429. }
  430. else {
  431. space *= 2;
  432. }
  433. osize = space;
  434. output = PyMem_NEW(Py_UCS4, space);
  435. if (!output) {
  436. PyErr_NoMemory();
  437. return NULL;
  438. }
  439. i = o = 0;
  440. kind = PyUnicode_KIND(input);
  441. data = PyUnicode_DATA(input);
  442. while (i < isize) {
  443. stack[stackptr++] = PyUnicode_READ(kind, data, i++);
  444. while(stackptr) {
  445. Py_UCS4 code = stack[--stackptr];
  446. /* Hangul Decomposition adds three characters in
  447. a single step, so we need at least that much room. */
  448. if (space < 3) {
  449. Py_UCS4 *new_output;
  450. osize += 10;
  451. space += 10;
  452. new_output = PyMem_Realloc(output, osize*sizeof(Py_UCS4));
  453. if (new_output == NULL) {
  454. PyMem_Free(output);
  455. PyErr_NoMemory();
  456. return NULL;
  457. }
  458. output = new_output;
  459. }
  460. /* Hangul Decomposition. */
  461. if (SBase <= code && code < (SBase+SCount)) {
  462. int SIndex = code - SBase;
  463. int L = LBase + SIndex / NCount;
  464. int V = VBase + (SIndex % NCount) / TCount;
  465. int T = TBase + SIndex % TCount;
  466. output[o++] = L;
  467. output[o++] = V;
  468. space -= 2;
  469. if (T != TBase) {
  470. output[o++] = T;
  471. space --;
  472. }
  473. continue;
  474. }
  475. /* normalization changes */
  476. if (UCD_Check(self)) {
  477. Py_UCS4 value = ((PreviousDBVersion*)self)->normalization(code);
  478. if (value != 0) {
  479. stack[stackptr++] = value;
  480. continue;
  481. }
  482. }
  483. /* Other decompositions. */
  484. get_decomp_record(self, code, &index, &prefix, &count);
  485. /* Copy character if it is not decomposable, or has a
  486. compatibility decomposition, but we do NFD. */
  487. if (!count || (prefix && !k)) {
  488. output[o++] = code;
  489. space--;
  490. continue;
  491. }
  492. /* Copy decomposition onto the stack, in reverse
  493. order. */
  494. while(count) {
  495. code = decomp_data[index + (--count)];
  496. stack[stackptr++] = code;
  497. }
  498. }
  499. }
  500. result = PyUnicode_FromKindAndData(PyUnicode_4BYTE_KIND,
  501. output, o);
  502. PyMem_Free(output);
  503. if (!result)
  504. return NULL;
  505. /* result is guaranteed to be ready, as it is compact. */
  506. kind = PyUnicode_KIND(result);
  507. data = PyUnicode_DATA(result);
  508. /* Sort canonically. */
  509. i = 0;
  510. prev = _getrecord_ex(PyUnicode_READ(kind, data, i))->combining;
  511. for (i++; i < PyUnicode_GET_LENGTH(result); i++) {
  512. cur = _getrecord_ex(PyUnicode_READ(kind, data, i))->combining;
  513. if (prev == 0 || cur == 0 || prev <= cur) {
  514. prev = cur;
  515. continue;
  516. }
  517. /* Non-canonical order. Need to switch *i with previous. */
  518. o = i - 1;
  519. while (1) {
  520. Py_UCS4 tmp = PyUnicode_READ(kind, data, o+1);
  521. PyUnicode_WRITE(kind, data, o+1,
  522. PyUnicode_READ(kind, data, o));
  523. PyUnicode_WRITE(kind, data, o, tmp);
  524. o--;
  525. if (o < 0)
  526. break;
  527. prev = _getrecord_ex(PyUnicode_READ(kind, data, o))->combining;
  528. if (prev == 0 || prev <= cur)
  529. break;
  530. }
  531. prev = _getrecord_ex(PyUnicode_READ(kind, data, i))->combining;
  532. }
  533. return result;
  534. }
  535. static int
  536. find_nfc_index(const struct reindex* nfc, Py_UCS4 code)
  537. {
  538. unsigned int index;
  539. for (index = 0; nfc[index].start; index++) {
  540. unsigned int start = nfc[index].start;
  541. if (code < start)
  542. return -1;
  543. if (code <= start + nfc[index].count) {
  544. unsigned int delta = code - start;
  545. return nfc[index].index + delta;
  546. }
  547. }
  548. return -1;
  549. }
  550. static PyObject*
  551. nfc_nfkc(PyObject *self, PyObject *input, int k)
  552. {
  553. PyObject *result;
  554. int kind;
  555. const void *data;
  556. Py_UCS4 *output;
  557. Py_ssize_t i, i1, o, len;
  558. int f,l,index,index1,comb;
  559. Py_UCS4 code;
  560. Py_ssize_t skipped[20];
  561. int cskipped = 0;
  562. result = nfd_nfkd(self, input, k);
  563. if (!result)
  564. return NULL;
  565. /* result will be "ready". */
  566. kind = PyUnicode_KIND(result);
  567. data = PyUnicode_DATA(result);
  568. len = PyUnicode_GET_LENGTH(result);
  569. /* We allocate a buffer for the output.
  570. If we find that we made no changes, we still return
  571. the NFD result. */
  572. output = PyMem_NEW(Py_UCS4, len);
  573. if (!output) {
  574. PyErr_NoMemory();
  575. Py_DECREF(result);
  576. return 0;
  577. }
  578. i = o = 0;
  579. again:
  580. while (i < len) {
  581. for (index = 0; index < cskipped; index++) {
  582. if (skipped[index] == i) {
  583. /* *i character is skipped.
  584. Remove from list. */
  585. skipped[index] = skipped[cskipped-1];
  586. cskipped--;
  587. i++;
  588. goto again; /* continue while */
  589. }
  590. }
  591. /* Hangul Composition. We don't need to check for <LV,T>
  592. pairs, since we always have decomposed data. */
  593. code = PyUnicode_READ(kind, data, i);
  594. if (LBase <= code && code < (LBase+LCount) &&
  595. i + 1 < len &&
  596. VBase <= PyUnicode_READ(kind, data, i+1) &&
  597. PyUnicode_READ(kind, data, i+1) < (VBase+VCount)) {
  598. /* check L character is a modern leading consonant (0x1100 ~ 0x1112)
  599. and V character is a modern vowel (0x1161 ~ 0x1175). */
  600. int LIndex, VIndex;
  601. LIndex = code - LBase;
  602. VIndex = PyUnicode_READ(kind, data, i+1) - VBase;
  603. code = SBase + (LIndex*VCount+VIndex)*TCount;
  604. i+=2;
  605. if (i < len &&
  606. TBase < PyUnicode_READ(kind, data, i) &&
  607. PyUnicode_READ(kind, data, i) < (TBase+TCount)) {
  608. /* check T character is a modern trailing consonant
  609. (0x11A8 ~ 0x11C2). */
  610. code += PyUnicode_READ(kind, data, i)-TBase;
  611. i++;
  612. }
  613. output[o++] = code;
  614. continue;
  615. }
  616. /* code is still input[i] here */
  617. f = find_nfc_index(nfc_first, code);
  618. if (f == -1) {
  619. output[o++] = code;
  620. i++;
  621. continue;
  622. }
  623. /* Find next unblocked character. */
  624. i1 = i+1;
  625. comb = 0;
  626. /* output base character for now; might be updated later. */
  627. output[o] = PyUnicode_READ(kind, data, i);
  628. while (i1 < len) {
  629. Py_UCS4 code1 = PyUnicode_READ(kind, data, i1);
  630. int comb1 = _getrecord_ex(code1)->combining;
  631. if (comb) {
  632. if (comb1 == 0)
  633. break;
  634. if (comb >= comb1) {
  635. /* Character is blocked. */
  636. i1++;
  637. continue;
  638. }
  639. }
  640. l = find_nfc_index(nfc_last, code1);
  641. /* i1 cannot be combined with i. If i1
  642. is a starter, we don't need to look further.
  643. Otherwise, record the combining class. */
  644. if (l == -1) {
  645. not_combinable:
  646. if (comb1 == 0)
  647. break;
  648. comb = comb1;
  649. i1++;
  650. continue;
  651. }
  652. index = f*TOTAL_LAST + l;
  653. index1 = comp_index[index >> COMP_SHIFT];
  654. code = comp_data[(index1<<COMP_SHIFT)+
  655. (index&((1<<COMP_SHIFT)-1))];
  656. if (code == 0)
  657. goto not_combinable;
  658. /* Replace the original character. */
  659. output[o] = code;
  660. /* Mark the second character unused. */
  661. assert(cskipped < 20);
  662. skipped[cskipped++] = i1;
  663. i1++;
  664. f = find_nfc_index(nfc_first, output[o]);
  665. if (f == -1)
  666. break;
  667. }
  668. /* Output character was already written.
  669. Just advance the indices. */
  670. o++; i++;
  671. }
  672. if (o == len) {
  673. /* No changes. Return original string. */
  674. PyMem_Free(output);
  675. return result;
  676. }
  677. Py_DECREF(result);
  678. result = PyUnicode_FromKindAndData(PyUnicode_4BYTE_KIND,
  679. output, o);
  680. PyMem_Free(output);
  681. return result;
  682. }
  683. // This needs to match the logic in makeunicodedata.py
  684. // which constructs the quickcheck data.
  685. typedef enum {YES = 0, MAYBE = 1, NO = 2} QuickcheckResult;
  686. /* Run the Unicode normalization "quickcheck" algorithm.
  687. *
  688. * Return YES or NO if quickcheck determines the input is certainly
  689. * normalized or certainly not, and MAYBE if quickcheck is unable to
  690. * tell.
  691. *
  692. * If `yes_only` is true, then return MAYBE as soon as we determine
  693. * the answer is not YES.
  694. *
  695. * For background and details on the algorithm, see UAX #15:
  696. * https://www.unicode.org/reports/tr15/#Detecting_Normalization_Forms
  697. */
  698. static QuickcheckResult
  699. is_normalized_quickcheck(PyObject *self, PyObject *input, bool nfc, bool k,
  700. bool yes_only)
  701. {
  702. /* UCD 3.2.0 is requested, quickchecks must be disabled. */
  703. if (UCD_Check(self)) {
  704. return MAYBE;
  705. }
  706. if (PyUnicode_IS_ASCII(input)) {
  707. return YES;
  708. }
  709. Py_ssize_t i, len;
  710. int kind;
  711. const void *data;
  712. unsigned char prev_combining = 0;
  713. /* The two quickcheck bits at this shift have type QuickcheckResult. */
  714. int quickcheck_shift = (nfc ? 4 : 0) + (k ? 2 : 0);
  715. QuickcheckResult result = YES; /* certainly normalized, unless we find something */
  716. i = 0;
  717. kind = PyUnicode_KIND(input);
  718. data = PyUnicode_DATA(input);
  719. len = PyUnicode_GET_LENGTH(input);
  720. while (i < len) {
  721. Py_UCS4 ch = PyUnicode_READ(kind, data, i++);
  722. const _PyUnicode_DatabaseRecord *record = _getrecord_ex(ch);
  723. unsigned char combining = record->combining;
  724. if (combining && prev_combining > combining)
  725. return NO; /* non-canonical sort order, not normalized */
  726. prev_combining = combining;
  727. unsigned char quickcheck_whole = record->normalization_quick_check;
  728. if (yes_only) {
  729. if (quickcheck_whole & (3 << quickcheck_shift))
  730. return MAYBE;
  731. } else {
  732. switch ((quickcheck_whole >> quickcheck_shift) & 3) {
  733. case NO:
  734. return NO;
  735. case MAYBE:
  736. result = MAYBE; /* this string might need normalization */
  737. }
  738. }
  739. }
  740. return result;
  741. }
  742. /*[clinic input]
  743. unicodedata.UCD.is_normalized
  744. self: self
  745. form: unicode
  746. unistr as input: unicode
  747. /
  748. Return whether the Unicode string unistr is in the normal form 'form'.
  749. Valid values for form are 'NFC', 'NFKC', 'NFD', and 'NFKD'.
  750. [clinic start generated code]*/
  751. static PyObject *
  752. unicodedata_UCD_is_normalized_impl(PyObject *self, PyObject *form,
  753. PyObject *input)
  754. /*[clinic end generated code: output=11e5a3694e723ca5 input=a544f14cea79e508]*/
  755. {
  756. if (PyUnicode_READY(input) == -1) {
  757. return NULL;
  758. }
  759. if (PyUnicode_GET_LENGTH(input) == 0) {
  760. /* special case empty input strings. */
  761. Py_RETURN_TRUE;
  762. }
  763. PyObject *result;
  764. bool nfc = false;
  765. bool k = false;
  766. QuickcheckResult m;
  767. PyObject *cmp;
  768. int match = 0;
  769. if (PyUnicode_CompareWithASCIIString(form, "NFC") == 0) {
  770. nfc = true;
  771. }
  772. else if (PyUnicode_CompareWithASCIIString(form, "NFKC") == 0) {
  773. nfc = true;
  774. k = true;
  775. }
  776. else if (PyUnicode_CompareWithASCIIString(form, "NFD") == 0) {
  777. /* matches default values for `nfc` and `k` */
  778. }
  779. else if (PyUnicode_CompareWithASCIIString(form, "NFKD") == 0) {
  780. k = true;
  781. }
  782. else {
  783. PyErr_SetString(PyExc_ValueError, "invalid normalization form");
  784. return NULL;
  785. }
  786. m = is_normalized_quickcheck(self, input, nfc, k, false);
  787. if (m == MAYBE) {
  788. cmp = (nfc ? nfc_nfkc : nfd_nfkd)(self, input, k);
  789. if (cmp == NULL) {
  790. return NULL;
  791. }
  792. match = PyUnicode_Compare(input, cmp);
  793. Py_DECREF(cmp);
  794. result = (match == 0) ? Py_True : Py_False;
  795. }
  796. else {
  797. result = (m == YES) ? Py_True : Py_False;
  798. }
  799. return Py_NewRef(result);
  800. }
  801. /*[clinic input]
  802. unicodedata.UCD.normalize
  803. self: self
  804. form: unicode
  805. unistr as input: unicode
  806. /
  807. Return the normal form 'form' for the Unicode string unistr.
  808. Valid values for form are 'NFC', 'NFKC', 'NFD', and 'NFKD'.
  809. [clinic start generated code]*/
  810. static PyObject *
  811. unicodedata_UCD_normalize_impl(PyObject *self, PyObject *form,
  812. PyObject *input)
  813. /*[clinic end generated code: output=05ca4385a2ad6983 input=3a5206c0ad2833fb]*/
  814. {
  815. if (PyUnicode_GET_LENGTH(input) == 0) {
  816. /* Special case empty input strings, since resizing
  817. them later would cause internal errors. */
  818. return Py_NewRef(input);
  819. }
  820. if (PyUnicode_CompareWithASCIIString(form, "NFC") == 0) {
  821. if (is_normalized_quickcheck(self, input,
  822. true, false, true) == YES) {
  823. return Py_NewRef(input);
  824. }
  825. return nfc_nfkc(self, input, 0);
  826. }
  827. if (PyUnicode_CompareWithASCIIString(form, "NFKC") == 0) {
  828. if (is_normalized_quickcheck(self, input,
  829. true, true, true) == YES) {
  830. return Py_NewRef(input);
  831. }
  832. return nfc_nfkc(self, input, 1);
  833. }
  834. if (PyUnicode_CompareWithASCIIString(form, "NFD") == 0) {
  835. if (is_normalized_quickcheck(self, input,
  836. false, false, true) == YES) {
  837. return Py_NewRef(input);
  838. }
  839. return nfd_nfkd(self, input, 0);
  840. }
  841. if (PyUnicode_CompareWithASCIIString(form, "NFKD") == 0) {
  842. if (is_normalized_quickcheck(self, input,
  843. false, true, true) == YES) {
  844. return Py_NewRef(input);
  845. }
  846. return nfd_nfkd(self, input, 1);
  847. }
  848. PyErr_SetString(PyExc_ValueError, "invalid normalization form");
  849. return NULL;
  850. }
  851. /* -------------------------------------------------------------------- */
  852. /* unicode character name tables */
  853. /* data file generated by Tools/unicode/makeunicodedata.py */
  854. #include "unicodename_db.h"
  855. /* -------------------------------------------------------------------- */
  856. /* database code (cut and pasted from the unidb package) */
  857. static unsigned long
  858. _gethash(const char *s, int len, int scale)
  859. {
  860. int i;
  861. unsigned long h = 0;
  862. unsigned long ix;
  863. for (i = 0; i < len; i++) {
  864. h = (h * scale) + (unsigned char) Py_TOUPPER(s[i]);
  865. ix = h & 0xff000000;
  866. if (ix)
  867. h = (h ^ ((ix>>24) & 0xff)) & 0x00ffffff;
  868. }
  869. return h;
  870. }
  871. static const char * const hangul_syllables[][3] = {
  872. { "G", "A", "" },
  873. { "GG", "AE", "G" },
  874. { "N", "YA", "GG" },
  875. { "D", "YAE", "GS" },
  876. { "DD", "EO", "N", },
  877. { "R", "E", "NJ" },
  878. { "M", "YEO", "NH" },
  879. { "B", "YE", "D" },
  880. { "BB", "O", "L" },
  881. { "S", "WA", "LG" },
  882. { "SS", "WAE", "LM" },
  883. { "", "OE", "LB" },
  884. { "J", "YO", "LS" },
  885. { "JJ", "U", "LT" },
  886. { "C", "WEO", "LP" },
  887. { "K", "WE", "LH" },
  888. { "T", "WI", "M" },
  889. { "P", "YU", "B" },
  890. { "H", "EU", "BS" },
  891. { 0, "YI", "S" },
  892. { 0, "I", "SS" },
  893. { 0, 0, "NG" },
  894. { 0, 0, "J" },
  895. { 0, 0, "C" },
  896. { 0, 0, "K" },
  897. { 0, 0, "T" },
  898. { 0, 0, "P" },
  899. { 0, 0, "H" }
  900. };
  901. /* These ranges need to match makeunicodedata.py:cjk_ranges. */
  902. static int
  903. is_unified_ideograph(Py_UCS4 code)
  904. {
  905. return
  906. (0x3400 <= code && code <= 0x4DBF) || /* CJK Ideograph Extension A */
  907. (0x4E00 <= code && code <= 0x9FFF) || /* CJK Ideograph */
  908. (0x20000 <= code && code <= 0x2A6DF) || /* CJK Ideograph Extension B */
  909. (0x2A700 <= code && code <= 0x2B739) || /* CJK Ideograph Extension C */
  910. (0x2B740 <= code && code <= 0x2B81D) || /* CJK Ideograph Extension D */
  911. (0x2B820 <= code && code <= 0x2CEA1) || /* CJK Ideograph Extension E */
  912. (0x2CEB0 <= code && code <= 0x2EBE0) || /* CJK Ideograph Extension F */
  913. (0x30000 <= code && code <= 0x3134A) || /* CJK Ideograph Extension G */
  914. (0x31350 <= code && code <= 0x323AF); /* CJK Ideograph Extension H */
  915. }
  916. /* macros used to determine if the given code point is in the PUA range that
  917. * we are using to store aliases and named sequences */
  918. #define IS_ALIAS(cp) ((cp >= aliases_start) && (cp < aliases_end))
  919. #define IS_NAMED_SEQ(cp) ((cp >= named_sequences_start) && \
  920. (cp < named_sequences_end))
  921. static int
  922. _getucname(PyObject *self,
  923. Py_UCS4 code, char* buffer, int buflen, int with_alias_and_seq)
  924. {
  925. /* Find the name associated with the given code point.
  926. * If with_alias_and_seq is 1, check for names in the Private Use Area 15
  927. * that we are using for aliases and named sequences. */
  928. int offset;
  929. int i;
  930. int word;
  931. const unsigned char* w;
  932. if (code >= 0x110000)
  933. return 0;
  934. /* XXX should we just skip all the code points in the PUAs here? */
  935. if (!with_alias_and_seq && (IS_ALIAS(code) || IS_NAMED_SEQ(code)))
  936. return 0;
  937. if (UCD_Check(self)) {
  938. /* in 3.2.0 there are no aliases and named sequences */
  939. const change_record *old;
  940. if (IS_ALIAS(code) || IS_NAMED_SEQ(code))
  941. return 0;
  942. old = get_old_record(self, code);
  943. if (old->category_changed == 0) {
  944. /* unassigned */
  945. return 0;
  946. }
  947. }
  948. if (SBase <= code && code < SBase+SCount) {
  949. /* Hangul syllable. */
  950. int SIndex = code - SBase;
  951. int L = SIndex / NCount;
  952. int V = (SIndex % NCount) / TCount;
  953. int T = SIndex % TCount;
  954. if (buflen < 27)
  955. /* Worst case: HANGUL SYLLABLE <10chars>. */
  956. return 0;
  957. strcpy(buffer, "HANGUL SYLLABLE ");
  958. buffer += 16;
  959. strcpy(buffer, hangul_syllables[L][0]);
  960. buffer += strlen(hangul_syllables[L][0]);
  961. strcpy(buffer, hangul_syllables[V][1]);
  962. buffer += strlen(hangul_syllables[V][1]);
  963. strcpy(buffer, hangul_syllables[T][2]);
  964. buffer += strlen(hangul_syllables[T][2]);
  965. *buffer = '\0';
  966. return 1;
  967. }
  968. if (is_unified_ideograph(code)) {
  969. if (buflen < 28)
  970. /* Worst case: CJK UNIFIED IDEOGRAPH-20000 */
  971. return 0;
  972. sprintf(buffer, "CJK UNIFIED IDEOGRAPH-%X", code);
  973. return 1;
  974. }
  975. /* get offset into phrasebook */
  976. offset = phrasebook_offset1[(code>>phrasebook_shift)];
  977. offset = phrasebook_offset2[(offset<<phrasebook_shift) +
  978. (code&((1<<phrasebook_shift)-1))];
  979. if (!offset)
  980. return 0;
  981. i = 0;
  982. for (;;) {
  983. /* get word index */
  984. word = phrasebook[offset] - phrasebook_short;
  985. if (word >= 0) {
  986. word = (word << 8) + phrasebook[offset+1];
  987. offset += 2;
  988. } else
  989. word = phrasebook[offset++];
  990. if (i) {
  991. if (i > buflen)
  992. return 0; /* buffer overflow */
  993. buffer[i++] = ' ';
  994. }
  995. /* copy word string from lexicon. the last character in the
  996. word has bit 7 set. the last word in a string ends with
  997. 0x80 */
  998. w = lexicon + lexicon_offset[word];
  999. while (*w < 128) {
  1000. if (i >= buflen)
  1001. return 0; /* buffer overflow */
  1002. buffer[i++] = *w++;
  1003. }
  1004. if (i >= buflen)
  1005. return 0; /* buffer overflow */
  1006. buffer[i++] = *w & 127;
  1007. if (*w == 128)
  1008. break; /* end of word */
  1009. }
  1010. return 1;
  1011. }
  1012. static int
  1013. capi_getucname(Py_UCS4 code,
  1014. char* buffer, int buflen,
  1015. int with_alias_and_seq)
  1016. {
  1017. return _getucname(NULL, code, buffer, buflen, with_alias_and_seq);
  1018. }
  1019. static int
  1020. _cmpname(PyObject *self, int code, const char* name, int namelen)
  1021. {
  1022. /* check if code corresponds to the given name */
  1023. int i;
  1024. char buffer[NAME_MAXLEN+1];
  1025. if (!_getucname(self, code, buffer, NAME_MAXLEN, 1))
  1026. return 0;
  1027. for (i = 0; i < namelen; i++) {
  1028. if (Py_TOUPPER(name[i]) != buffer[i])
  1029. return 0;
  1030. }
  1031. return buffer[namelen] == '\0';
  1032. }
  1033. static void
  1034. find_syllable(const char *str, int *len, int *pos, int count, int column)
  1035. {
  1036. int i, len1;
  1037. *len = -1;
  1038. for (i = 0; i < count; i++) {
  1039. const char *s = hangul_syllables[i][column];
  1040. len1 = Py_SAFE_DOWNCAST(strlen(s), size_t, int);
  1041. if (len1 <= *len)
  1042. continue;
  1043. if (strncmp(str, s, len1) == 0) {
  1044. *len = len1;
  1045. *pos = i;
  1046. }
  1047. }
  1048. if (*len == -1) {
  1049. *len = 0;
  1050. }
  1051. }
  1052. static int
  1053. _check_alias_and_seq(unsigned int cp, Py_UCS4* code, int with_named_seq)
  1054. {
  1055. /* check if named sequences are allowed */
  1056. if (!with_named_seq && IS_NAMED_SEQ(cp))
  1057. return 0;
  1058. /* if the code point is in the PUA range that we use for aliases,
  1059. * convert it to obtain the right code point */
  1060. if (IS_ALIAS(cp))
  1061. *code = name_aliases[cp-aliases_start];
  1062. else
  1063. *code = cp;
  1064. return 1;
  1065. }
  1066. static int
  1067. _getcode(PyObject* self,
  1068. const char* name, int namelen, Py_UCS4* code, int with_named_seq)
  1069. {
  1070. /* Return the code point associated with the given name.
  1071. * Named aliases are resolved too (unless self != NULL (i.e. we are using
  1072. * 3.2.0)). If with_named_seq is 1, returns the PUA code point that we are
  1073. * using for the named sequence, and the caller must then convert it. */
  1074. unsigned int h, v;
  1075. unsigned int mask = code_size-1;
  1076. unsigned int i, incr;
  1077. /* Check for hangul syllables. */
  1078. if (strncmp(name, "HANGUL SYLLABLE ", 16) == 0) {
  1079. int len, L = -1, V = -1, T = -1;
  1080. const char *pos = name + 16;
  1081. find_syllable(pos, &len, &L, LCount, 0);
  1082. pos += len;
  1083. find_syllable(pos, &len, &V, VCount, 1);
  1084. pos += len;
  1085. find_syllable(pos, &len, &T, TCount, 2);
  1086. pos += len;
  1087. if (L != -1 && V != -1 && T != -1 && pos-name == namelen) {
  1088. *code = SBase + (L*VCount+V)*TCount + T;
  1089. return 1;
  1090. }
  1091. /* Otherwise, it's an illegal syllable name. */
  1092. return 0;
  1093. }
  1094. /* Check for unified ideographs. */
  1095. if (strncmp(name, "CJK UNIFIED IDEOGRAPH-", 22) == 0) {
  1096. /* Four or five hexdigits must follow. */
  1097. v = 0;
  1098. name += 22;
  1099. namelen -= 22;
  1100. if (namelen != 4 && namelen != 5)
  1101. return 0;
  1102. while (namelen--) {
  1103. v *= 16;
  1104. if (*name >= '0' && *name <= '9')
  1105. v += *name - '0';
  1106. else if (*name >= 'A' && *name <= 'F')
  1107. v += *name - 'A' + 10;
  1108. else
  1109. return 0;
  1110. name++;
  1111. }
  1112. if (!is_unified_ideograph(v))
  1113. return 0;
  1114. *code = v;
  1115. return 1;
  1116. }
  1117. /* the following is the same as python's dictionary lookup, with
  1118. only minor changes. see the makeunicodedata script for more
  1119. details */
  1120. h = (unsigned int) _gethash(name, namelen, code_magic);
  1121. i = (~h) & mask;
  1122. v = code_hash[i];
  1123. if (!v)
  1124. return 0;
  1125. if (_cmpname(self, v, name, namelen)) {
  1126. return _check_alias_and_seq(v, code, with_named_seq);
  1127. }
  1128. incr = (h ^ (h >> 3)) & mask;
  1129. if (!incr)
  1130. incr = mask;
  1131. for (;;) {
  1132. i = (i + incr) & mask;
  1133. v = code_hash[i];
  1134. if (!v)
  1135. return 0;
  1136. if (_cmpname(self, v, name, namelen)) {
  1137. return _check_alias_and_seq(v, code, with_named_seq);
  1138. }
  1139. incr = incr << 1;
  1140. if (incr > mask)
  1141. incr = incr ^ code_poly;
  1142. }
  1143. }
  1144. static int
  1145. capi_getcode(const char* name, int namelen, Py_UCS4* code,
  1146. int with_named_seq)
  1147. {
  1148. return _getcode(NULL, name, namelen, code, with_named_seq);
  1149. }
  1150. static void
  1151. unicodedata_destroy_capi(PyObject *capsule)
  1152. {
  1153. void *capi = PyCapsule_GetPointer(capsule, PyUnicodeData_CAPSULE_NAME);
  1154. PyMem_Free(capi);
  1155. }
  1156. static PyObject *
  1157. unicodedata_create_capi(void)
  1158. {
  1159. _PyUnicode_Name_CAPI *capi = PyMem_Malloc(sizeof(_PyUnicode_Name_CAPI));
  1160. if (capi == NULL) {
  1161. PyErr_NoMemory();
  1162. return NULL;
  1163. }
  1164. capi->getname = capi_getucname;
  1165. capi->getcode = capi_getcode;
  1166. PyObject *capsule = PyCapsule_New(capi,
  1167. PyUnicodeData_CAPSULE_NAME,
  1168. unicodedata_destroy_capi);
  1169. if (capsule == NULL) {
  1170. PyMem_Free(capi);
  1171. }
  1172. return capsule;
  1173. };
  1174. /* -------------------------------------------------------------------- */
  1175. /* Python bindings */
  1176. /*[clinic input]
  1177. unicodedata.UCD.name
  1178. self: self
  1179. chr: int(accept={str})
  1180. default: object=NULL
  1181. /
  1182. Returns the name assigned to the character chr as a string.
  1183. If no name is defined, default is returned, or, if not given,
  1184. ValueError is raised.
  1185. [clinic start generated code]*/
  1186. static PyObject *
  1187. unicodedata_UCD_name_impl(PyObject *self, int chr, PyObject *default_value)
  1188. /*[clinic end generated code: output=6bbb37a326407707 input=3e0367f534de56d9]*/
  1189. {
  1190. char name[NAME_MAXLEN+1];
  1191. Py_UCS4 c = (Py_UCS4)chr;
  1192. if (!_getucname(self, c, name, NAME_MAXLEN, 0)) {
  1193. if (default_value == NULL) {
  1194. PyErr_SetString(PyExc_ValueError, "no such name");
  1195. return NULL;
  1196. }
  1197. else {
  1198. return Py_NewRef(default_value);
  1199. }
  1200. }
  1201. return PyUnicode_FromString(name);
  1202. }
  1203. /*[clinic input]
  1204. unicodedata.UCD.lookup
  1205. self: self
  1206. name: str(accept={str, robuffer}, zeroes=True)
  1207. /
  1208. Look up character by name.
  1209. If a character with the given name is found, return the
  1210. corresponding character. If not found, KeyError is raised.
  1211. [clinic start generated code]*/
  1212. static PyObject *
  1213. unicodedata_UCD_lookup_impl(PyObject *self, const char *name,
  1214. Py_ssize_t name_length)
  1215. /*[clinic end generated code: output=7f03fc4959b242f6 input=a557be0f8607a0d6]*/
  1216. {
  1217. Py_UCS4 code;
  1218. unsigned int index;
  1219. if (name_length > NAME_MAXLEN) {
  1220. PyErr_SetString(PyExc_KeyError, "name too long");
  1221. return NULL;
  1222. }
  1223. if (!_getcode(self, name, (int)name_length, &code, 1)) {
  1224. PyErr_Format(PyExc_KeyError, "undefined character name '%s'", name);
  1225. return NULL;
  1226. }
  1227. /* check if code is in the PUA range that we use for named sequences
  1228. and convert it */
  1229. if (IS_NAMED_SEQ(code)) {
  1230. index = code-named_sequences_start;
  1231. return PyUnicode_FromKindAndData(PyUnicode_2BYTE_KIND,
  1232. named_sequences[index].seq,
  1233. named_sequences[index].seqlen);
  1234. }
  1235. return PyUnicode_FromOrdinal(code);
  1236. }
  1237. // List of functions used to define module functions *AND* unicodedata.UCD
  1238. // methods. For module functions, self is the module. For UCD methods, self
  1239. // is an UCD instance. The UCD_Check() macro is used to check if self is
  1240. // an UCD instance.
  1241. static PyMethodDef unicodedata_functions[] = {
  1242. UNICODEDATA_UCD_DECIMAL_METHODDEF
  1243. UNICODEDATA_UCD_DIGIT_METHODDEF
  1244. UNICODEDATA_UCD_NUMERIC_METHODDEF
  1245. UNICODEDATA_UCD_CATEGORY_METHODDEF
  1246. UNICODEDATA_UCD_BIDIRECTIONAL_METHODDEF
  1247. UNICODEDATA_UCD_COMBINING_METHODDEF
  1248. UNICODEDATA_UCD_MIRRORED_METHODDEF
  1249. UNICODEDATA_UCD_EAST_ASIAN_WIDTH_METHODDEF
  1250. UNICODEDATA_UCD_DECOMPOSITION_METHODDEF
  1251. UNICODEDATA_UCD_NAME_METHODDEF
  1252. UNICODEDATA_UCD_LOOKUP_METHODDEF
  1253. UNICODEDATA_UCD_IS_NORMALIZED_METHODDEF
  1254. UNICODEDATA_UCD_NORMALIZE_METHODDEF
  1255. {NULL, NULL} /* sentinel */
  1256. };
  1257. static int
  1258. ucd_traverse(PreviousDBVersion *self, visitproc visit, void *arg)
  1259. {
  1260. Py_VISIT(Py_TYPE(self));
  1261. return 0;
  1262. }
  1263. static void
  1264. ucd_dealloc(PreviousDBVersion *self)
  1265. {
  1266. PyTypeObject *tp = Py_TYPE(self);
  1267. PyObject_GC_UnTrack(self);
  1268. PyObject_GC_Del(self);
  1269. Py_DECREF(tp);
  1270. }
  1271. static PyType_Slot ucd_type_slots[] = {
  1272. {Py_tp_dealloc, ucd_dealloc},
  1273. {Py_tp_traverse, ucd_traverse},
  1274. {Py_tp_getattro, PyObject_GenericGetAttr},
  1275. {Py_tp_methods, unicodedata_functions},
  1276. {Py_tp_members, DB_members},
  1277. {0, 0}
  1278. };
  1279. static PyType_Spec ucd_type_spec = {
  1280. .name = "unicodedata.UCD",
  1281. .basicsize = sizeof(PreviousDBVersion),
  1282. .flags = (Py_TPFLAGS_DEFAULT | Py_TPFLAGS_DISALLOW_INSTANTIATION |
  1283. Py_TPFLAGS_HAVE_GC | Py_TPFLAGS_IMMUTABLETYPE),
  1284. .slots = ucd_type_slots
  1285. };
  1286. PyDoc_STRVAR(unicodedata_docstring,
  1287. "This module provides access to the Unicode Character Database which\n\
  1288. defines character properties for all Unicode characters. The data in\n\
  1289. this database is based on the UnicodeData.txt file version\n\
  1290. " UNIDATA_VERSION " which is publicly available from ftp://ftp.unicode.org/.\n\
  1291. \n\
  1292. The module uses the same names and symbols as defined by the\n\
  1293. UnicodeData File Format " UNIDATA_VERSION ".");
  1294. static int
  1295. unicodedata_exec(PyObject *module)
  1296. {
  1297. if (PyModule_AddStringConstant(module, "unidata_version", UNIDATA_VERSION) < 0) {
  1298. return -1;
  1299. }
  1300. PyTypeObject *ucd_type = (PyTypeObject *)PyType_FromSpec(&ucd_type_spec);
  1301. if (ucd_type == NULL) {
  1302. return -1;
  1303. }
  1304. if (PyModule_AddType(module, ucd_type) < 0) {
  1305. Py_DECREF(ucd_type);
  1306. return -1;
  1307. }
  1308. // Unicode database version 3.2.0 used by the IDNA encoding
  1309. PyObject *v;
  1310. v = new_previous_version(ucd_type, "3.2.0",
  1311. get_change_3_2_0, normalization_3_2_0);
  1312. Py_DECREF(ucd_type);
  1313. if (v == NULL) {
  1314. return -1;
  1315. }
  1316. if (PyModule_AddObject(module, "ucd_3_2_0", v) < 0) {
  1317. Py_DECREF(v);
  1318. return -1;
  1319. }
  1320. /* Export C API */
  1321. PyObject *capsule = unicodedata_create_capi();
  1322. if (capsule == NULL) {
  1323. return -1;
  1324. }
  1325. int rc = PyModule_AddObjectRef(module, "_ucnhash_CAPI", capsule);
  1326. Py_DECREF(capsule);
  1327. if (rc < 0) {
  1328. return -1;
  1329. }
  1330. return 0;
  1331. }
  1332. static PyModuleDef_Slot unicodedata_slots[] = {
  1333. {Py_mod_exec, unicodedata_exec},
  1334. {Py_mod_multiple_interpreters, Py_MOD_PER_INTERPRETER_GIL_SUPPORTED},
  1335. {0, NULL}
  1336. };
  1337. static struct PyModuleDef unicodedata_module = {
  1338. PyModuleDef_HEAD_INIT,
  1339. .m_name = "unicodedata",
  1340. .m_doc = unicodedata_docstring,
  1341. .m_size = 0,
  1342. .m_methods = unicodedata_functions,
  1343. .m_slots = unicodedata_slots,
  1344. };
  1345. PyMODINIT_FUNC
  1346. PyInit_unicodedata(void)
  1347. {
  1348. return PyModuleDef_Init(&unicodedata_module);
  1349. }
  1350. /*
  1351. Local variables:
  1352. c-basic-offset: 4
  1353. indent-tabs-mode: nil
  1354. End:
  1355. */