-
Notifications
You must be signed in to change notification settings - Fork 69
/
Copy pathlutf8lib.c
2226 lines (2040 loc) · 70.8 KB
/
lutf8lib.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/* vim: set ft=c nu et sw=2 fdc=2 fdm=syntax : */
#define LUA_LIB
#include <lua.h>
#include <lauxlib.h>
#include <lualib.h>
#include <assert.h>
#include <string.h>
#include <stdint.h>
#include <limits.h>
#include <stdlib.h>
#include "unidata.h"
/* UTF-8 string operations */
#define UTF8_BUFFSZ 8
#define UTF8_MAX 0x7FFFFFFFu
#define UTF8_MAXCP 0x10FFFFu
#define iscont(p) ((*(p) & 0xC0) == 0x80)
#define CAST(tp,expr) ((tp)(expr))
#ifndef LUA_QL
# define LUA_QL(x) "'" x "'"
#endif
static int utf8_invalid (utfint ch)
{ return (ch > UTF8_MAXCP || (0xD800u <= ch && ch <= 0xDFFFu)); }
static size_t utf8_encode (char *buff, utfint x) {
int n = 1; /* number of bytes put in buffer (backwards) */
lua_assert(x <= UTF8_MAX);
if (x < 0x80) /* ascii? */
buff[UTF8_BUFFSZ - 1] = x & 0x7F;
else { /* need continuation bytes */
utfint mfb = 0x3f; /* maximum that fits in first byte */
do { /* add continuation bytes */
buff[UTF8_BUFFSZ - (n++)] = 0x80 | (x & 0x3f);
x >>= 6; /* remove added bits */
mfb >>= 1; /* now there is one less bit available in first byte */
} while (x > mfb); /* still needs continuation byte? */
buff[UTF8_BUFFSZ - n] = ((~mfb << 1) | x) & 0xFF; /* add first byte */
}
return n;
}
static const char *utf8_decode (const char *s, utfint *val, int strict) {
static const utfint limits[] =
{~0u, 0x80u, 0x800u, 0x10000u, 0x200000u, 0x4000000u};
unsigned int c = (unsigned char)s[0];
utfint res = 0; /* final result */
if (c < 0x80) /* ascii? */
res = c;
else {
int count = 0; /* to count number of continuation bytes */
for (; c & 0x40; c <<= 1) { /* while it needs continuation bytes... */
unsigned int cc = (unsigned char)s[++count]; /* read next byte */
if ((cc & 0xC0) != 0x80) /* not a continuation byte? */
return NULL; /* invalid byte sequence */
res = (res << 6) | (cc & 0x3F); /* add lower 6 bits from cont. byte */
}
res |= ((utfint)(c & 0x7F) << (count * 5)); /* add first byte */
if (count > 5 || res > UTF8_MAX || res < limits[count])
return NULL; /* invalid byte sequence */
s += count; /* skip continuation bytes read */
}
if (strict) {
/* check for invalid code points; too large or surrogates */
if (res > UTF8_MAXCP || (0xD800u <= res && res <= 0xDFFFu))
return NULL;
}
if (val) *val = res;
return s + 1; /* +1 to include first byte */
}
static const char *utf8_prev (const char *s, const char *e) {
while (s < e && iscont(e - 1)) --e;
return s < e ? e - 1 : s;
}
static const char *utf8_next (const char *s, const char *e) {
while (s < e && iscont(s + 1)) ++s;
return s < e ? s + 1 : e;
}
static size_t utf8_length (const char *s, const char *e) {
size_t i;
for (i = 0; s < e; ++i)
s = utf8_next(s, e);
return i;
}
static const char *utf8_offset (const char *s, const char *e, lua_Integer offset, lua_Integer idx) {
const char *p = s + offset - 1;
if (idx >= 0) {
while (p < e && idx > 0)
p = utf8_next(p, e), --idx;
return idx == 0 ? p : NULL;
} else {
while (s < p && idx < 0)
p = utf8_prev(s, p), ++idx;
return idx == 0 ? p : NULL;
}
}
static const char *utf8_relat (const char *s, const char *e, int idx) {
return idx >= 0 ?
utf8_offset(s, e, 1, idx - 1) :
utf8_offset(s, e, e-s+1, idx);
}
static int utf8_range(const char *s, const char *e, lua_Integer *i, lua_Integer *j) {
const char *ps = utf8_relat(s, e, CAST(int, *i));
const char *pe = utf8_relat(s, e, CAST(int, *j));
*i = (ps ? ps : (*i > 0 ? e : s)) - s;
*j = (pe ? utf8_next(pe, e) : (*j > 0 ? e : s)) - s;
return *i < *j;
}
/* Indexed by top nibble of first byte in code unit */
static uint8_t utf8_code_unit_len[] = {
1, 1, 1, 1, 1, 1, 1, 1, -1, -1, -1, -1, 2, 2, 3, 4
};
/* Return pointer to first invalid UTF-8 sequence in 's', or NULL if valid */
static const char *utf8_invalid_offset(const char *s, const char *e) {
while (s < e) {
uint8_t c = *s;
if (c >= 0x80) {
/* c < 0xC0 means a continuation byte, but we are not in the middle of a multi-byte code unit
* c >= 0xC0 && c < 0xC2 means an overlong 2-byte code unit
* c >= 0xF8 means a 5-byte or 6-byte code unit, which is illegal, or else illegal byte 0xFE/0xFF
* c >= 0xF5 && c < 0xF8 means a 4-byte code unit encoding invalid codepoint > U+10FFFF */
if (c < 0xC2 || c >= 0xF5)
return s;
uint8_t needed_bytes = utf8_code_unit_len[c >> 4];
if (e - s < needed_bytes)
return s; /* String is truncated */
uint8_t c2 = *(s+1);
if ((c2 & 0xC0) != 0x80)
return s; /* 2nd byte of code unit is not a continuation byte */
if (needed_bytes >= 3) {
uint8_t c3 = *(s+2);
if ((c3 & 0xC0) != 0x80)
return s; /* 3rd byte of code unit is not a continuation byte */
if (needed_bytes == 3) {
if (c == 0xE0 && c2 < 0xA0)
return s; /* Overlong 3-byte code unit */
if (c == 0xED && c2 >= 0xA0)
return s; /* Reserved codepoint from U+D800-U+DFFF */
} else {
uint8_t c4 = *(s+3);
if ((c4 & 0xC0) != 0x80)
return s; /* 4th byte of code unit is not a continuation byte */
if (c == 0xF0 && c2 < 0x90)
return s; /* Overlong 4-byte code unit */
if (c == 0xF4 && c2 >= 0x90)
return s; /* Illegal codepoint > U+10FFFF */
}
}
s += needed_bytes;
} else {
s++;
}
}
return NULL;
}
/* Unicode character categories */
#define table_size(t) (sizeof(t)/sizeof((t)[0]))
#define utf8_categories(X) \
X('a', alpha) \
X('c', cntrl) \
X('d', digit) \
X('l', lower) \
X('p', punct) \
X('s', space) \
X('t', compose) \
X('u', upper) \
X('x', xdigit)
#define utf8_converters(X) \
X(lower) \
X(upper) \
X(title) \
X(fold)
static int find_in_range (range_table *t, size_t size, utfint ch) {
size_t begin, end;
begin = 0;
end = size;
while (begin < end) {
size_t mid = (begin + end) / 2;
if (t[mid].last < ch)
begin = mid + 1;
else if (t[mid].first > ch)
end = mid;
else
return (ch - t[mid].first) % t[mid].step == 0;
}
return 0;
}
static int convert_char (conv_table *t, size_t size, utfint ch) {
size_t begin, end;
begin = 0;
end = size;
while (begin < end) {
size_t mid = (begin + end) / 2;
if (t[mid].last < ch)
begin = mid + 1;
else if (t[mid].first > ch)
end = mid;
else if ((ch - t[mid].first) % t[mid].step == 0)
return ch + t[mid].offset;
else
return ch;
}
return ch;
}
/* Normalization */
static int lookup_canon_cls (utfint ch) {
/* The first codepoint with canonicalization class != 0 is U+0300 COMBINING GRAVE ACCENT */
if (ch < 0x300) {
return 0;
}
size_t begin = 0, end = table_size(nfc_combining_table);
while (begin < end) {
size_t mid = (begin + end) / 2;
if (nfc_combining_table[mid].last < ch)
begin = mid + 1;
else if (nfc_combining_table[mid].first > ch)
end = mid;
else
return nfc_combining_table[mid].canon_cls;
}
return 0;
}
static nfc_table *nfc_quickcheck (utfint ch) {
/* The first character which needs to be checked for possible NFC violations
* is U+0300 COMBINING GRAVE ACCENT */
if (ch < 0x300) {
return NULL;
}
size_t begin = 0, end = table_size(nfc_quickcheck_table);
while (begin < end) {
size_t mid = (begin + end) / 2;
utfint found = nfc_quickcheck_table[mid].cp;
if (found < ch)
begin = mid + 1;
else if (found > ch)
end = mid;
else
return &nfc_quickcheck_table[mid];
}
return NULL;
}
static int nfc_combine (utfint cp1, utfint cp2, utfint *dest) {
size_t begin = 0, end = table_size(nfc_composite_table);
unsigned int hash = (cp1 * 213) + cp2;
while (begin < end) {
size_t mid = (begin + end) / 2;
utfint val = nfc_composite_table[mid].hash;
if (val < hash) {
begin = mid + 1;
} else if (val > hash) {
end = mid;
} else if (nfc_composite_table[mid].cp1 == cp1 && nfc_composite_table[mid].cp2 == cp2) {
if (dest)
*dest = nfc_composite_table[mid].dest;
return 1;
} else {
return 0;
}
}
return 0;
}
static decompose_table *nfc_decompose (utfint ch) {
size_t begin = 0, end = table_size(nfc_decompose_table);
while (begin < end) {
size_t mid = (begin + end) / 2;
utfint found = nfc_decompose_table[mid].cp;
if (found < ch)
begin = mid + 1;
else if (found > ch)
end = mid;
else
return &nfc_decompose_table[mid];
}
return NULL;
}
static int nfc_check (utfint ch, nfc_table *entry, utfint starter, unsigned int canon_cls, unsigned int prev_canon_cls) {
int reason = entry->reason;
if (reason == REASON_MUST_CONVERT_1 || reason == REASON_MUST_CONVERT_2) {
/* This codepoint has a different, canonical form, so this string is not NFC */
return 0;
} else if (reason == REASON_STARTER_CAN_COMBINE) {
/* It is possible that this 'starter' codepoint should have been combined with the
* preceding 'starter' codepoint; if so, this string is not NFC */
if (!prev_canon_cls && nfc_combine(starter, ch, NULL)) {
/* These codepoints should have been combined */
return 0;
}
} else if (reason == REASON_COMBINING_MARK) {
/* Combining mark; check if it should have been combined with preceding starter codepoint */
if (canon_cls <= prev_canon_cls) {
return 1;
}
if (nfc_combine(starter, ch, NULL)) {
/* Yes, they should have been combined. This string is not NFC */
return 0;
}
/* Could it be that preceding 'starter' codepoint is already combined, but with a
* combining mark which is out of order with this one? */
decompose_table *decomp = nfc_decompose(starter);
if (decomp) {
if (decomp->canon_cls2 > canon_cls && nfc_combine(decomp->to1, ch, NULL)) {
return 0;
} else {
decompose_table *decomp2 = nfc_decompose(decomp->to1);
if (decomp2 && decomp2->canon_cls2 > canon_cls && nfc_combine(decomp2->to1, ch, NULL)) {
return 0;
}
}
}
} else if (reason == REASON_JAMO_VOWEL) {
if (!prev_canon_cls && starter >= 0x1100 && starter <= 0x1112) {
/* Preceding codepoint was a leading jamo; they should have been combined */
return 0;
}
} else if (reason == REASON_JAMO_TRAILING) {
if (!prev_canon_cls && starter >= 0xAC00 && starter <= 0xD7A3) {
/* Preceding codepoint was a precomposed Hangul syllable; check if it had no trailing jamo */
if ((starter - 0xAC00) % 28 == 0) {
/* It didn't have a trailing jamo, so this trailing jamo should have been combined */
return 0;
}
}
}
return 1;
}
static void merge_combining_marks (uint32_t *src1, uint32_t *src2, uint32_t *dest, size_t size1, size_t size2) {
while (size1 && size2) {
if ((*src1 & 0xFF) > (*src2 & 0xFF)) {
*dest++ = *src2++;
size2--;
} else {
*dest++ = *src1++;
size1--;
}
}
while (size1) {
*dest++ = *src1++;
size1--;
}
while (size2) {
*dest++ = *src2++;
size2--;
}
}
static void stable_sort_combining_marks (uint32_t *vector, uint32_t *scratch, size_t size) {
/* We need to use a stable sort for sorting combining marks which are in the wrong order
* when doing NFC normalization; bottom-up merge sort is fast and stable */
size_t limit = size - 1;
for (unsigned int i = 0; i < limit; i += 2) {
if ((vector[i] & 0xFF) > (vector[i+1] & 0xFF)) {
uint32_t temp = vector[i];
vector[i] = vector[i+1];
vector[i+1] = temp;
}
}
if (size <= 2)
return;
uint32_t *src = vector, *dest = scratch;
unsigned int runsize = 2; /* Every consecutive slice of this size is sorted */
while (runsize < size) {
unsigned int blocksize = runsize * 2; /* We will now sort slices of this size */
limit = size & ~(blocksize - 1);
for (unsigned int i = 0; i < limit; i += blocksize)
merge_combining_marks(&src[i], &src[i+runsize], &dest[i], runsize, runsize);
if (size - limit > runsize) {
merge_combining_marks(&src[limit], &src[limit+runsize], &dest[limit], runsize, size - limit - runsize);
} else {
memcpy(&dest[limit], &src[limit], (size - limit) * sizeof(uint32_t));
}
/* After each series of (progressively larger) merges, we swap src & dest to
* avoid memcpy'ing the partially sorted results from dest back into src */
uint32_t *temp = src; src = dest; dest = temp;
runsize = blocksize;
}
if (dest == vector) {
/* Since src & dest are swapped on each iteration of the above loop,
* this actually means the last buffer which was written into
* was 'scratch' */
memcpy(vector, scratch, size * sizeof(uint32_t));
}
}
/* Shuffle item `i` up or down to get it into the right position */
static void stable_insert_combining_mark (uint32_t *vector, size_t vec_size, unsigned int i)
{
unsigned int item = vector[i];
unsigned int canon_cls = item & 0xFF;
if (i > 0) {
if (canon_cls < (vector[i-1] & 0xFF)) {
do {
vector[i] = vector[i-1];
i--;
} while (i > 0 && canon_cls < (vector[i-1] & 0xFF));
vector[i] = item;
return;
}
}
if (i < vec_size-1) {
if (canon_cls > (vector[i+1] & 0xFF)) {
do {
vector[i] = vector[i+1];
i++;
} while (i < vec_size-1 && canon_cls > (vector[i+1] & 0xFF));
vector[i] = item;
return;
}
}
}
static void add_utf8char (luaL_Buffer *b, utfint ch);
static inline void grow_vector_if_needed (uint32_t **vector, uint32_t *onstack, size_t *size, size_t needed)
{
size_t current_size = *size;
if (needed >= current_size) {
size_t new_size = current_size * 2; /* `needed` is never bigger than `current_size * 2` */
uint32_t *new_vector = malloc(new_size * sizeof(uint32_t));
memcpy(new_vector, *vector, current_size * sizeof(uint32_t));
*size = new_size;
if (*vector != onstack)
free(*vector);
*vector = new_vector;
}
}
static void string_to_nfc (lua_State *L, luaL_Buffer *buff, const char *s, const char *e)
{
/* Converting a string to Normal Form C involves:
* 1) Ensuring that codepoints with "built-in" accents are used whenever possible
* rather than separate codepoints for a base character and combining mark
* 2) Where combining marks must be used, putting them into canonical order
* 3) Converting some deprecated codepoints to the recommended variant
* 4) Ensuring that Korean Hangul are represented as precomposed syllable
* codepoints whenever possible, rather than sequences of Jamo codepoints
*
* (Combining marks are accents which appear on top of or below the preceding
* character. Starter codepoints are the base characters which combining marks can
* 'combine' with. Almost all codepoints are starters, including all the Latin alphabet.
* Every Unicode codepoint has a numeric 'canonicalization class'; starters have class = 0.
* Combining marks must be sorted in order of their canonicalization class. Since the
* canonicalization class numbers are not unique, the sort must be stable.)
*
* When converting to NFC, the largest scope which we need to work on at once
* consists of a 'starter' codepoint and either 1 or more ensuing combining marks,
* OR else a directly following starter codepoint.
*
* As we walk through the string, whenever we pass by a complete sequence of starter +
* combining marks or starter + starter, we process that sequence to see if it is NFC or not.
* If it is, we memcpy the bytes verbatim into the output buffer. If it is not, then we
* convert the codepoints to NFC and then emit those codepoints as UTF-8 bytes. */
utfint starter = -1, ch; /* 'starter' is last starter codepoint seen */
const char *to_copy = s; /* pointer to next bytes we might need to memcpy into output buffer */
unsigned int prev_canon_cls = 0, canon_cls = 0;
int fixedup = 0; /* has the sequence currently under consideration been modified to make it NFC? */
/* Temporary storage for a sequence of consecutive combining marks
* In the vast majority of cases, this small on-stack array will provide enough
* space; if not, we will switch to a malloc'd buffer */
uint32_t onstack[8];
size_t vec_size = 0, vec_max = sizeof(onstack)/sizeof(uint32_t);
uint32_t *vector = onstack;
while (s < e) {
const char *new_s = utf8_decode(s, &ch, 1);
if (new_s == NULL) {
if (vector != onstack)
free(vector);
lua_pushstring(L, "string is not valid UTF-8");
lua_error(L);
}
unsigned int canon_cls = lookup_canon_cls(ch);
if (!canon_cls) {
/* This is a starter codepoint */
nfc_table *entry = nfc_quickcheck(ch);
/* But in rare cases, a deprecated 'starter' codepoint may convert
* to combining marks instead!
* Why, oh why, did the Unicode Consortium do this?? */
if (entry && entry->reason == REASON_MUST_CONVERT_2) {
utfint conv1 = entry->data1;
unsigned int canon_cls1 = lookup_canon_cls(conv1);
if (canon_cls1) {
utfint conv2 = entry->data2;
unsigned int canon_cls2 = lookup_canon_cls(conv2);
grow_vector_if_needed(&vector, onstack, &vec_max, vec_size + 2);
vector[vec_size++] = (conv1 << 8) | (canon_cls1 & 0xFF);
vector[vec_size++] = (conv2 << 8) | (canon_cls2 & 0xFF);
s = new_s;
prev_canon_cls = canon_cls2;
fixedup = 1;
continue;
}
}
/* Handle preceding starter and optional sequence of combining marks which may have followed it */
if (prev_canon_cls) {
/* Before this starter, there was a sequence of combining marks.
* Check those over and emit output to 'buff' */
process_combining_marks:
/* Check if accumulated combining marks were in correct order */
for (unsigned int i = 1; i < vec_size; i++) {
if ((vector[i-1] & 0xFF) > (vector[i] & 0xFF)) {
/* Order is incorrect, we need to sort */
uint32_t *scratch = malloc(vec_size * sizeof(uint32_t));
stable_sort_combining_marks(vector, scratch, vec_size);
free(scratch);
fixedup = 1;
break;
}
}
/* Check if any of those combining marks are in violation of NFC */
unsigned int i = 0;
while (i < vec_size) {
utfint combine_mark = vector[i] >> 8;
nfc_table *mark_entry = nfc_quickcheck(combine_mark);
if (mark_entry) {
if (mark_entry->reason == REASON_MUST_CONVERT_1) {
/* This combining mark must be converted to a different one */
vector[i] = (mark_entry->data1 << 8) | mark_entry->data2;
fixedup = 1;
continue;
} else if (mark_entry->reason == REASON_MUST_CONVERT_2) {
/* This combining mark must be converted to two others */
grow_vector_if_needed(&vector, onstack, &vec_max, vec_size + 1);
memmove(&vector[i+2], &vector[i+1], sizeof(uint32_t) * (vec_size - i - 1));
vector[i] = (mark_entry->data1 << 8) | lookup_canon_cls(mark_entry->data1);
vector[i+1] = (mark_entry->data2 << 8) | lookup_canon_cls(mark_entry->data2);
vec_size++;
fixedup = 1;
continue;
} else if (mark_entry->reason == REASON_COMBINING_MARK) {
unsigned int mark_canon_cls = vector[i] & 0xFF;
if (i == 0 || mark_canon_cls > (vector[i-1] & 0xFF)) {
if (nfc_combine(starter, combine_mark, &starter)) {
/* This combining mark must be combined with preceding starter */
vec_size--;
memmove(&vector[i], &vector[i+1], sizeof(uint32_t) * (vec_size - i)); /* Remove element i */
fixedup = 1;
continue;
}
decompose_table *decomp = nfc_decompose(starter);
if (decomp) {
if (decomp->canon_cls2 > mark_canon_cls && nfc_combine(decomp->to1, combine_mark, &starter)) {
/* The preceding starter already included an accent, but when represented as a combining
* mark, that accent has a HIGHER canonicalization class than this one
* Further, this one is able to combine with the same base character
* In other words, the base character was wrongly combined with a "lower-priority"
* combining mark; fix that up */
unsigned int class2 = lookup_canon_cls(decomp->to2);
memmove(&vector[1], &vector[0], sizeof(uint32_t) * i);
vector[0] = (decomp->to2 << 8) | class2;
stable_insert_combining_mark(vector, vec_size, 0);
fixedup = 1;
continue;
} else {
decompose_table *decomp2 = nfc_decompose(decomp->to1);
if (decomp2 && decomp2->canon_cls2 > mark_canon_cls && nfc_combine(decomp2->to1, combine_mark, &starter)) {
grow_vector_if_needed(&vector, onstack, &vec_max, vec_size + 1);
memmove(&vector[i+2], &vector[i+1], sizeof(uint32_t) * (vec_size - i - 1));
memmove(&vector[2], &vector[0], sizeof(uint32_t) * i);
vector[0] = (decomp2->to2 << 8) | lookup_canon_cls(decomp2->to2);
vector[1] = (decomp->to2 << 8) | lookup_canon_cls(decomp->to2);
vec_size++;
stable_insert_combining_mark(vector, vec_size, 1);
stable_insert_combining_mark(vector, vec_size, 0);
fixedup = 1;
continue;
}
}
}
}
}
}
i++;
}
if (fixedup) {
/* The preceding starter/combining mark sequence was bad; convert fixed-up codepoints
* to UTF-8 bytes */
if (starter != -1)
add_utf8char(buff, starter);
for (unsigned int i = 0; i < vec_size; i++)
add_utf8char(buff, vector[i] >> 8);
} else {
/* The preceding starter/combining mark sequence was good; copy raw bytes to output */
luaL_addlstring(buff, to_copy, s - to_copy);
}
if (s >= e) {
/* We jumped in to the middle of the main loop to finish processing trailing
* combining marks... we are actually done now */
if (vector != onstack)
free(vector);
return;
}
vec_size = 0; /* Clear vector of combining marks in readiness for next such sequence */
fixedup = 0;
} else if (starter != -1) {
/* This starter was preceded immediately by another starter
* Check if this one should combine with it */
fixedup = 0;
if (entry) {
if (entry->reason == REASON_STARTER_CAN_COMBINE && nfc_combine(starter, ch, &ch)) {
fixedup = 1;
} else if (entry->reason == REASON_JAMO_VOWEL && starter >= 0x1100 && starter <= 0x1112) {
ch = 0xAC00 + ((starter - 0x1100) * 588) + ((ch - 0x1161) * 28);
fixedup = 1;
} else if (entry->reason == REASON_JAMO_TRAILING) {
if (starter >= 0xAC00 && starter <= 0xD7A3 && (starter - 0xAC00) % 28 == 0) {
ch = starter + ch - 0x11A7;
fixedup = 1;
}
}
}
if (!fixedup)
add_utf8char(buff, starter); /* Emit previous starter to output */
}
starter = ch;
to_copy = s;
/* We are finished processing the preceding starter and optional sequence of combining marks
* Now check if this (possibly deprecated) starter needs to be converted to a canonical variant */
if (entry) {
if (entry->reason == REASON_MUST_CONVERT_1) {
starter = entry->data1;
fixedup = 1;
} else if (entry->reason == REASON_MUST_CONVERT_2) {
utfint conv1 = entry->data1;
utfint conv2 = entry->data2;
/* It's possible that 'ch' might convert to two other codepoints,
* where the 2nd one is a combining mark */
unsigned int canon_cls2 = lookup_canon_cls(conv2);
if (canon_cls2) {
/* It's possible that the 1st resulting codepoint may need to be
* split again into more codepoints */
nfc_table *conv_entry = nfc_quickcheck(conv1);
if (conv_entry && conv_entry->reason == REASON_MUST_CONVERT_2) {
utfint conv3 = conv2;
unsigned int canon_cls3 = canon_cls2;
conv1 = conv_entry->data1;
conv2 = conv_entry->data2;
canon_cls2 = lookup_canon_cls(conv2);
if (canon_cls2) {
starter = conv1;
vector[0] = (conv2 << 8) | canon_cls2;
vector[1] = (conv3 << 8) | canon_cls3;
vec_size = 2;
} else {
add_utf8char(buff, conv1);
starter = conv2;
vector[0] = (conv3 << 8) | canon_cls3;
vec_size = 1;
}
canon_cls = canon_cls3;
} else {
starter = conv1;
vector[0] = (conv2 << 8) | canon_cls2;
vec_size = 1;
canon_cls = canon_cls2;
}
} else {
add_utf8char(buff, conv1);
starter = conv2;
}
fixedup = 1;
}
}
} else {
/* Accumulate combining marks in vector */
grow_vector_if_needed(&vector, onstack, &vec_max, vec_size + 1);
vector[vec_size++] = (ch << 8) | (canon_cls & 0xFF);
}
s = new_s;
prev_canon_cls = canon_cls;
}
if (vec_size)
goto process_combining_marks; /* Finish processing trailing combining marks */
if (starter != -1)
add_utf8char(buff, starter);
if (vector != onstack)
free(vector);
}
/* Grapheme cluster support */
static int hangul_type (utfint ch) {
/* The first Hangul codepoint is U+1100 */
if (ch < 0x1100) {
return 0;
}
size_t begin = 0, end = table_size(hangul_table);
while (begin < end) {
size_t mid = (begin + end) / 2;
if (hangul_table[mid].last < ch)
begin = mid + 1;
else if (hangul_table[mid].first > ch)
end = mid;
else
return hangul_table[mid].type;
}
return 0;
}
static int indic_conjunct_type (utfint ch) {
/* The first Indic conjunct codepoint is U+0300 */
if (ch < 0x300) {
return 0;
}
size_t begin = 0, end = table_size(indic_table);
while (begin < end) {
size_t mid = (begin + end) / 2;
if (indic_table[mid].last < ch)
begin = mid + 1;
else if (indic_table[mid].first > ch)
end = mid;
else
return indic_table[mid].type;
}
return 0;
}
#define define_category(cls, name) static int utf8_is##name (utfint ch)\
{ return find_in_range(name##_table, table_size(name##_table), ch); }
#define define_converter(name) static utfint utf8_to##name (utfint ch) \
{ return convert_char(to##name##_table, table_size(to##name##_table), ch); }
utf8_categories(define_category)
utf8_converters(define_converter)
#undef define_category
#undef define_converter
static int utf8_isgraph (utfint ch) {
if (find_in_range(space_table, table_size(space_table), ch))
return 0;
if (find_in_range(graph_table, table_size(graph_table), ch))
return 1;
if (find_in_range(compose_table, table_size(compose_table), ch))
return 1;
return 0;
}
static int utf8_isalnum (utfint ch) {
if (find_in_range(alpha_table, table_size(alpha_table), ch))
return 1;
if (find_in_range(alnum_extend_table, table_size(alnum_extend_table), ch))
return 1;
return 0;
}
static int utf8_width (utfint ch, int ambi_is_single) {
if (find_in_range(doublewidth_table, table_size(doublewidth_table), ch))
return 2;
if (find_in_range(ambiwidth_table, table_size(ambiwidth_table), ch))
return ambi_is_single ? 1 : 2;
if (find_in_range(compose_table, table_size(compose_table), ch))
return 0;
if (find_in_range(unprintable_table, table_size(unprintable_table), ch))
return 0;
return 1;
}
/* string module compatible interface */
static int typeerror (lua_State *L, int idx, const char *tname)
{ return luaL_error(L, "%s expected, got %s", tname, luaL_typename(L, idx)); }
static const char *check_utf8 (lua_State *L, int idx, const char **end) {
size_t len;
const char *s = luaL_checklstring(L, idx, &len);
if (end) *end = s+len;
return s;
}
static const char *to_utf8 (lua_State *L, int idx, const char **end) {
size_t len;
const char *s = lua_tolstring(L, idx, &len);
if (end) *end = s+len;
return s;
}
static const char *utf8_safe_decode (lua_State *L, const char *p, utfint *pval) {
p = utf8_decode(p, pval, 0);
if (p == NULL) luaL_error(L, "invalid UTF-8 code");
return p;
}
static void add_utf8char (luaL_Buffer *b, utfint ch) {
char buff[UTF8_BUFFSZ];
size_t n = utf8_encode(buff, ch);
luaL_addlstring(b, buff+UTF8_BUFFSZ-n, n);
}
static lua_Integer byte_relat (lua_Integer pos, size_t len) {
if (pos >= 0) return pos;
else if (0u - (size_t)pos > len) return 0;
else return (lua_Integer)len + pos + 1;
}
static int Lutf8_len (lua_State *L) {
size_t len, n;
const char *s = luaL_checklstring(L, 1, &len), *p, *e;
lua_Integer posi = byte_relat(luaL_optinteger(L, 2, 1), len);
lua_Integer pose = byte_relat(luaL_optinteger(L, 3, -1), len);
int lax = lua_toboolean(L, 4);
luaL_argcheck(L, 1 <= posi && --posi <= (lua_Integer)len, 2,
"initial position out of string");
luaL_argcheck(L, --pose < (lua_Integer)len, 3,
"final position out of string");
for (n = 0, p=s+posi, e=s+pose+1; p < e; ++n) {
if (lax)
p = utf8_next(p, e);
else {
utfint ch;
const char *np = utf8_decode(p, &ch, !lax);
if (np == NULL || utf8_invalid(ch)) {
lua_pushnil(L);
lua_pushinteger(L, p - s + 1);
return 2;
}
p = np;
}
}
lua_pushinteger(L, n);
return 1;
}
static int Lutf8_sub (lua_State *L) {
const char *e, *s = check_utf8(L, 1, &e);
lua_Integer posi = luaL_checkinteger(L, 2);
lua_Integer pose = luaL_optinteger(L, 3, -1);
if (utf8_range(s, e, &posi, &pose))
lua_pushlstring(L, s+posi, pose-posi);
else
lua_pushliteral(L, "");
return 1;
}
static int Lutf8_reverse (lua_State *L) {
luaL_Buffer b;
const char *prev, *pprev, *ends, *e, *s = check_utf8(L, 1, &e);
(void) ends;
int lax = lua_toboolean(L, 2);
luaL_buffinit(L, &b);
if (lax) {
for (prev = e; s < prev; e = prev) {
prev = utf8_prev(s, prev);
luaL_addlstring(&b, prev, e-prev);
}
} else {
for (prev = e; s < prev; prev = pprev) {
utfint code = 0;
ends = utf8_safe_decode(L, pprev = utf8_prev(s, prev), &code);
assert(ends == prev);
if (utf8_invalid(code))
return luaL_error(L, "invalid UTF-8 code");
if (!utf8_iscompose(code)) {
luaL_addlstring(&b, pprev, e-pprev);
e = pprev;
}
}
}
luaL_pushresult(&b);
return 1;
}
static int Lutf8_byte (lua_State *L) {
size_t n = 0;
const char *e, *s = check_utf8(L, 1, &e);
lua_Integer posi = luaL_optinteger(L, 2, 1);
lua_Integer pose = luaL_optinteger(L, 3, posi);
if (utf8_range(s, e, &posi, &pose)) {
for (e = s + pose, s = s + posi; s < e; ++n) {
utfint ch = 0;
s = utf8_safe_decode(L, s, &ch);
lua_pushinteger(L, ch);
}
}
return CAST(int, n);
}
static int Lutf8_codepoint (lua_State *L) {
const char *e, *s = check_utf8(L, 1, &e);
size_t len = e-s;
lua_Integer posi = byte_relat(luaL_optinteger(L, 2, 1), len);
lua_Integer pose = byte_relat(luaL_optinteger(L, 3, posi), len);
int lax = lua_toboolean(L, 4);
int n;
const char *se;
luaL_argcheck(L, posi >= 1, 2, "out of range");
luaL_argcheck(L, pose <= (lua_Integer)len, 3, "out of range");
if (posi > pose) return 0; /* empty interval; return no values */
if (pose - posi >= INT_MAX) /* (lua_Integer -> int) overflow? */
return luaL_error(L, "string slice too long");
n = (int)(pose - posi + 1);
luaL_checkstack(L, n, "string slice too long");
n = 0; /* count the number of returns */
se = s + pose; /* string end */
for (n = 0, s += posi - 1; s < se;) {
utfint code = 0;
s = utf8_safe_decode(L, s, &code);
if (!lax && utf8_invalid(code))
return luaL_error(L, "invalid UTF-8 code");
lua_pushinteger(L, code);
n++;
}
return n;
}
static int Lutf8_char (lua_State *L) {
int i, n = lua_gettop(L); /* number of arguments */
luaL_Buffer b;
luaL_buffinit(L, &b);
for (i = 1; i <= n; ++i) {
lua_Integer code = luaL_checkinteger(L, i);
luaL_argcheck(L, code <= UTF8_MAXCP, i, "value out of range");
add_utf8char(&b, CAST(utfint, code));
}
luaL_pushresult(&b);
return 1;
}
#define bind_converter(name) \
static int Lutf8_##name (lua_State *L) { \
int t = lua_type(L, 1); \
if (t == LUA_TNUMBER) \
lua_pushinteger(L, utf8_to##name(CAST(utfint, lua_tointeger(L, 1)))); \
else if (t == LUA_TSTRING) { \
luaL_Buffer b; \
const char *e, *s = to_utf8(L, 1, &e); \
luaL_buffinit(L, &b); \
while (s < e) { \
utfint ch = 0; \
s = utf8_safe_decode(L, s, &ch); \
add_utf8char(&b, utf8_to##name(ch)); \
} \
luaL_pushresult(&b); \
} \
else return typeerror(L, 1, "number/string"); \
return 1; \
}
utf8_converters(bind_converter)
#undef bind_converter
/* unicode extra interface */