Debian Codegraph @

texk/web2c/luatexdir/slnunicode/slnunico.c

raw
1 /*
2 * Selene Unicode/UTF-8
3 * This additions
4 * Copyright (c) 2005 Malete Partner, Berlin, [email protected]
5 * Available under "Lua 5.0 license", see http://www.lua.org/license.html#5
6 * $Id: slnunico.c,v 1.5 2006/07/26 17:20:04 paul Exp $
7 *
8 * contains code from
9 ** lstrlib.c,v 1.109 2004/12/01 15:46:06 roberto Exp
10 ** Standard library for string operations and pattern-matching
11 ** See Copyright Notice in lua.h
12 *
13 * uses the udata table and a couple of expressions from Tcl 8.4.x UTF-8
14 * which comes with the following license.terms:
15
16 This software is copyrighted by the Regents of the University of
17 California, Sun Microsystems, Inc., Scriptics Corporation, ActiveState
18 Corporation and other parties. The following terms apply to all files
19 associated with the software unless explicitly disclaimed in
20 individual files.
21
22 The authors hereby grant permission to use, copy, modify, distribute,
23 and license this software and its documentation for any purpose, provided
24 that existing copyright notices are retained in all copies and that this
25 notice is included verbatim in any distributions. No written agreement,
26 license, or royalty fee is required for any of the authorized uses.
27 Modifications to this software may be copyrighted by their authors
28 and need not follow the licensing terms described here, provided that
29 the new terms are clearly indicated on the first page of each file where
30 they apply.
31
32 IN NO EVENT SHALL THE AUTHORS OR DISTRIBUTORS BE LIABLE TO ANY PARTY
33 FOR DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES
34 ARISING OUT OF THE USE OF THIS SOFTWARE, ITS DOCUMENTATION, OR ANY
35 DERIVATIVES THEREOF, EVEN IF THE AUTHORS HAVE BEEN ADVISED OF THE
36 POSSIBILITY OF SUCH DAMAGE.
37
38 THE AUTHORS AND DISTRIBUTORS SPECIFICALLY DISCLAIM ANY WARRANTIES,
39 INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY,
40 FITNESS FOR A PARTICULAR PURPOSE, AND NON-INFRINGEMENT. THIS SOFTWARE
41 IS PROVIDED ON AN "AS IS" BASIS, AND THE AUTHORS AND DISTRIBUTORS HAVE
42 NO OBLIGATION TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR
43 MODIFICATIONS.
44
45 GOVERNMENT USE: If you are acquiring this software on behalf of the
46 U.S. government, the Government shall have only "Restricted Rights"
47 in the software and related documentation as defined in the Federal
48 Acquisition Regulations (FARs) in Clause 52.227.19 (c) (2). If you
49 are acquiring the software on behalf of the Department of Defense, the
50 software shall be classified as "Commercial Computer Software" and the
51 Government shall have only "Restricted Rights" as defined in Clause
52 252.227-7013 (c) (1) of DFARs. Notwithstanding the foregoing, the
53 authors grant the U.S. Government and others acting in its behalf
54 permission to use and distribute the software in accordance with the
55 terms specified in this license.
56
57 (end of Tcl license terms)
58 */
59
60 /*
61 According to http://ietf.org/rfc/rfc3629.txt we support up to 4-byte
62 (21 bit) sequences encoding the UTF-16 reachable 0-0x10FFFF.
63 Any byte not part of a 2-4 byte sequence in that range decodes to itself.
64 Ill formed (non-shortest) "C0 80" will be decoded as two code points C0 and 80,
65 not code point 0; see security considerations in the RFC.
66 However, UTF-16 surrogates (D800-DFFF) are accepted.
67
68 See http://www.unicode.org/reports/tr29/#Grapheme_Cluster_Boundaries
69 for default grapheme clusters.
70 Lazy westerners we are (and lacking the Hangul_Syllable_Type data),
71 we care for base char + Grapheme_Extend, but not for Hangul syllable sequences.
72
73 For http://unicode.org/Public/UNIDATA/UCD.html#Grapheme_Extend
74 we use Mn (NON_SPACING_MARK) + Me (ENCLOSING_MARK),
75 ignoring the 18 mostly south asian Other_Grapheme_Extend (16 Mc, 2 Cf) from
76 http://www.unicode.org/Public/UNIDATA/PropList.txt
77 */
78
79 #include <ctype.h>
80 #include <stddef.h>
81 #include <stdio.h>
82 #include <stdlib.h>
83 #include <string.h>
84 #include <stdint.h>
85
86 #define lstrlib_c
87 #define LUA_LIB
88
89 #include "lua.h"
90
91 #ifdef LuajitTeX
92 #include "lua/lauxlib_bridge.h"
93 #else
94 #include "lauxlib.h"
95 #endif
96 #include "lualib.h"
97
98 #ifndef SLN_UNICODENAME /* unless set it luaconf */
99 # define SLN_UNICODENAME "unicode"
100 #endif
101
102 #define LUA_MAXCAPTURES 32
103 #if defined(LUA_USELONGLONG)
104
105 #define LUA_INTFRMLEN "ll"
106 #define LUA_INTFRM_T long long
107
108 #else
109
110 #define LUA_INTFRMLEN "l"
111 #define LUA_INTFRM_T long
112
113 #endif
114
115 /*
116 UTF-8 Bit Distribution pag 103 Unicode 5.0
117 First byte Lenght
118 00..7f 1 byte
119 c0..df 2 bytes
120 e0..ef 3 bytes
121 f0..f7 4 bytes
122 */
123 #define U8_LENGTH(c) ((unsigned char)(c)<=0x7f ? 1 : ((unsigned char)(c)<=0xdf ? 2 : ((unsigned char)(c)<=0xef ? 3 : ((unsigned char)(c)<=0xf7 ? 4:-1))))
124
125 #include "slnudata.c"
126 #define charinfo(c) (~0xFFFF&(c) ? 0 : GetUniCharInfo(c)) /* BMP only */
127 #define charcat(c) (UNICODE_CATEGORY_MASK & charinfo(c))
128 #define Grapheme_Extend(code) \
129 (1 & (((1<<NON_SPACING_MARK)|(1<<ENCLOSING_MARK)) >> charcat(code)))
130
131 enum { /* operation modes */
132 MODE_ASCII, /* single byte 7bit */
133 MODE_LATIN, /* single byte 8859-1 */
134 MODE_UTF8, /* UTF-8 by code points */
135 MODE_GRAPH /* UTF-8 by grapheme clusters */
136 #define MODE_MBYTE(mode) (~1&(mode))
137 };
138
139
140 /* macro to `unsign' a character */
141 #define uchar(c) ((unsigned char)(c))
142
143 typedef const unsigned char cuc; /* it's just toooo long :) */
144
145
146 static void utf8_enco (luaL_Buffer *b, unsigned c)
147 {
148 if (0x80 > c) {
149 luaL_addchar(b, c);
150 return;
151 }
152 if (0x800 > c)
153 luaL_addchar(b, 0xC0|(c>>6));
154 else {
155 if (0x10000 > c)
156 luaL_addchar(b, 0xE0|(c>>12));
157 else {
158 luaL_addchar(b, 0xF0|(c>>18));
159 luaL_addchar(b, 0x80|(0x3F&(c>>12)));
160 }
161 luaL_addchar(b, 0x80|(0x3F&(c>>6)));
162 }
163 luaL_addchar(b, 0x80|(0x3F&c));
164 } /* utf8_enco */
165
166
167 /* end must be > *pp */
168 static unsigned utf8_deco (const char **pp, const char *end)
169 {
170 register cuc *p = (cuc*)*pp, * const e = (cuc*)end;
171 unsigned first = *p, code;
172
173 *pp = (const char*)++p; /* eat one */
174 /* check ASCII, dangling cont., non-shortest or not continued */
175 if (0xC2 > first || e == p || 0x80 != (0xC0&*p)) return first;
176 code = 0x3F&*p++; /* save 1st cont. */
177 /* check 2 byte (5+6 = 11 bit) sequence up to 0x7FF */
178 if (0xE0 > first) { /* any >= C2 is valid */
179 code |= (0x1F&first)<<6;
180 goto seq;
181 }
182 if (e != p && 0x80 == (0xC0&*p)) { /* is continued */
183 code = code<<6 | (0x3F&*p++); /* save 2nd */
184 if (0xF0 > first) { /* 3 byte (4+6+6 = 16 bit) seq -- want 2nd cont. */
185 if ( 0xF800&(code |= (0x0F&first)<<12) /* >0x7FF: not non-shortest */
186 /* && 0xD800 != (0xD800 & code) -- nah, let surrogates pass */
187 )
188 goto seq;
189 } else if (e != p && 0x80 == (0xC0&*p) /* check 3rd */
190 /* catch 0xF4 < first and other out-of-bounds */
191 /* TH: add the 256 out-of-range glyphs in 'plane 18' */
192 && 0x110100 > (code = (0x0F&first)<<18 | code<<6 | (0x3F&*p++))
193 && 0xFFFF < code /* not a 16 bitty */
194 )
195 goto seq;
196 }
197 return first;
198 seq:
199 *pp = (const char*)p;
200 return code;
201 } /* utf8_deco */
202
203
204 /* reverse decode before pp > start */
205 static unsigned utf8_oced (const char **pp, const char *start)
206 {
207 register cuc *p = (cuc*)*pp, * const s = (cuc*)start;
208 unsigned last = *--p, code;
209
210 *pp = (const char*)p; /* eat one */
211 /* check non-continuer or at the edge */
212 if (0x80 != (0xC0&last) || s == p) return last;
213 code = 0x3F&last; /* save last cont. */
214 if (0xC0 == (0xE0&*--p)) { /* preceeded by 2 byte seq starter */
215 if (0xC2 <= *p) { code |= (0x1F&*p)<<6; goto seq; }
216 } else if (0x80 == (0xC0&*p) && s<p) {
217 code |= (0x3F&*p)<<6;
218 if (0xE0 == (0xF0&*--p)) { /* 3 byte starter */
219 if (0xF800&(code |= (0x0F&*p)<<12)) goto seq;
220 } else if (0x80 == (0xC0&*p) && s<=--p /* valid 4 byte ? */
221 /* TH: add the 256 out-of-range glyphs in 'plane 18' */
222 && 0x110100 > (code |= (0x0F&*p)<<18 | (0x3F&p[1])<<12)
223 && 0xFFFF < code
224 )
225 goto seq;
226 }
227 return last;
228 seq:
229 *pp = (const char*)p;
230 return code;
231 } /* utf8_oced */
232
233
234 /* skip over Grapheme_Extend codes */
235 static void utf8_graphext (const char **pp, const char *end)
236 {
237 const char *p = *pp;
238 for (; p < end; *pp=p) {
239 unsigned code = utf8_deco(&p, end);
240 if (!Grapheme_Extend(code)) break;
241 }
242 } /* utf8_graphext */
243
244
245 static int utf8_count (const char **pp, int bytes, int graph, int max)
246 {
247 const char *const end = *pp+bytes;
248 int count = 0;
249 while (*pp < end && count != max) {
250 unsigned code = utf8_deco(pp, end);
251 count++;
252 if (!graph) continue;
253 if (Grapheme_Extend(code) && 1<count) count--; /* uncount */
254 }
255 if (graph && count == max) /* gather more extending */
256 utf8_graphext(pp, end);
257 return count;
258 } /* utf8_count */
259
260
261
262 static int unic_len (lua_State *L) {
263 size_t l;
264 const char *s = luaL_checklstring(L, 1, &l);
265 int mode = lua_tointeger(L, lua_upvalueindex(1));
266 if (MODE_MBYTE(mode)) l = (size_t)utf8_count(&s, l, mode-2, -1);
267 lua_pushinteger(L, l);
268 return 1;
269 }
270
271
272 static ptrdiff_t posrelat (ptrdiff_t pos, size_t len) {
273 /* relative string position: negative means back from end */
274 return (pos>=0) ? pos : (ptrdiff_t)len+pos+1;
275 }
276
277
278 static int unic_sub (lua_State *L) {
279 size_t l;
280 const char *s = luaL_checklstring(L, 1, &l), *p, *e=s+l;
281 ptrdiff_t start = luaL_checkinteger(L, 2);
282 ptrdiff_t end = luaL_optinteger(L, 3, -1);
283 int mode = lua_tointeger(L, lua_upvalueindex(1));
284
285 if (MODE_MBYTE(mode)) { p=s; l = (size_t)utf8_count(&p, l, mode-2, -1); }
286 start = posrelat(start, l);
287 end = posrelat(end, l);
288 if (start < 1) start = 1;
289 if (end > (ptrdiff_t)l) end = (ptrdiff_t)l;
290 if (start > end)
291 lua_pushliteral(L, "");
292 else {
293 l = end - --start; /* #units */
294 if (!(MODE_MBYTE(mode))) /* single byte */
295 s += start;
296 else {
297 if (start) utf8_count(&s, e-s, mode-2, start); /* skip */
298 p = s;
299 utf8_count(&p, e-p, mode-2, l);
300 l = p-s;
301 }
302 lua_pushlstring(L, s, l);
303 }
304 return 1;
305 }
306
307
308 static int str_reverse (lua_State *L) { /* TODO? whatfor? */
309 size_t l;
310 luaL_Buffer b;
311 const char *s = luaL_checklstring(L, 1, &l), *p = s+l, *q;
312 int mode = lua_tointeger(L, lua_upvalueindex(1)), mb = MODE_MBYTE(mode);
313
314 luaL_buffinit(L, &b);
315 if (!mb)
316 while (s < p--) luaL_addchar(&b, *p);
317 else {
318 unsigned code;
319 while (s < p) {
320 q = p;
321 code = utf8_oced(&p, s);
322 if (MODE_GRAPH == mode)
323 while (Grapheme_Extend(code) && p>s) code = utf8_oced(&p, s);
324 luaL_addlstring(&b, p, q-p);
325 }
326 }
327 luaL_pushresult(&b);
328 return 1;
329 }
330
331
332
333 static int unic_lower (lua_State *L) {
334 size_t l;
335 luaL_Buffer b;
336 const char *s = luaL_checklstring(L, 1, &l), * const e=s+l;
337 int mode = lua_tointeger(L, lua_upvalueindex(1)), mb = MODE_MBYTE(mode);
338 luaL_buffinit(L, &b);
339 while (s < e) {
340 unsigned c = mb ? utf8_deco(&s, e) : uchar(*s++);
341 int info = charinfo(c);
342 if (GetCaseType(info)&0x02 && (mode || !(0x80&c))) c += GetDelta(info);
343 if (mb) utf8_enco(&b, c); else luaL_addchar(&b, c);
344 }
345 luaL_pushresult(&b);
346 return 1;
347 }
348
349
350 static int unic_upper (lua_State *L) {
351 size_t l;
352 luaL_Buffer b;
353 const char *s = luaL_checklstring(L, 1, &l), * const e=s+l;
354 int mode = lua_tointeger(L, lua_upvalueindex(1)), mb = MODE_MBYTE(mode);
355 luaL_buffinit(L, &b);
356 while (s < e) {
357 unsigned c = mb ? utf8_deco(&s, e) : uchar(*s++);
358 int info = charinfo(c);
359 if (GetCaseType(info)&0x04 && (mode || !(0x80&c))) c -= GetDelta(info);
360 if (mb) utf8_enco(&b, c); else luaL_addchar(&b, c);
361 }
362 luaL_pushresult(&b);
363 return 1;
364 }
365
366
367 static int str_rep (lua_State *L) {
368 size_t l;
369 luaL_Buffer b;
370 const char *s = luaL_checklstring(L, 1, &l);
371 int n = luaL_checkint(L, 2);
372 luaL_buffinit(L, &b);
373 while (n-- > 0)
374 luaL_addlstring(&b, s, l);
375 luaL_pushresult(&b);
376 return 1;
377 }
378
379
380 static int unic_byte (lua_State *L) {
381 size_t l;
382 ptrdiff_t posi, pose;
383 const char *s = luaL_checklstring(L, 1, &l), *p, *e=s+l;
384 int n, mode = lua_tointeger(L, lua_upvalueindex(1)), mb = MODE_MBYTE(mode);
385
386 if (mb) { p=s; l = (size_t)utf8_count(&p, l, mode-2, -1); }
387 posi = posrelat(luaL_optinteger(L, 2, 1), l);
388 pose = posrelat(luaL_optinteger(L, 3, posi), l);
389 if (posi <= 0) posi = 1;
390 if ((size_t)pose > l) pose = l;
391 if (0 >= (n = pose - --posi)) return 0; /* empty interval */
392 if (!mb)
393 e = (s += posi) + n;
394 else {
395 if (posi) utf8_count(&s, e-s, mode-2, posi); /* skip */
396 p=s;
397 utf8_count(&p, e-s, mode-2, n);
398 e=p;
399 }
400 /* byte count is upper bound on #elements */
401 luaL_checkstack(L, e-s, "string slice too long");
402 for (n=0; s<e; n++)
403 lua_pushinteger(L, mb ? utf8_deco(&s, e) : uchar(*s++));
404 return n;
405 }
406
407
408 static int unic_char (lua_State *L) {
409 int i, n = lua_gettop(L); /* number of arguments */
410 int mode = lua_tointeger(L, lua_upvalueindex(1)), mb = MODE_MBYTE(mode);
411 /* TH: add the 256 out-of-range glyphs in 'plane 18' */
412 unsigned lim = mb ? 0x110100 : 0x100;
413
414 luaL_Buffer b;
415 luaL_buffinit(L, &b);
416 for (i=1; i<=n; i++) {
417 unsigned c = luaL_checkint(L, i);
418 luaL_argcheck(L, lim > c, i, "invalid value");
419 if (mb) utf8_enco(&b, c); else luaL_addchar(&b, c);
420 }
421 luaL_pushresult(&b);
422 return 1;
423 }
424
425
426 static int writer (lua_State *L, const void* b, size_t size, void* B) {
427 (void)L;
428 luaL_addlstring((luaL_Buffer*) B, (const char *)b, size);
429 return 0;
430 }
431
432
433 static int str_dump (lua_State *L) {
434 luaL_Buffer b;
435 luaL_checktype(L, 1, LUA_TFUNCTION);
436 lua_settop(L, 1);
437 luaL_buffinit(L,&b);
438 #if defined(LuajitTeX)
439 if (lua_dump(L, writer, &b) != 0)
440 #else
441 #if LUA_VERSION_NUM == 503
442 if (lua_dump(L, writer, &b,0) != 0)
443 #else
444 if (lua_dump(L, writer, &b) != 0)
445 #endif
446 #endif
447 luaL_error(L, "unable to dump given function");
448 luaL_pushresult(&b);
449 return 1;
450 }
451
452
453
454 /*
455 ** {======================================================
456 ** PATTERN MATCHING
457 ** =======================================================
458 * find/gfind(_aux) -> match, push_captures
459 * gsub -> match, add_s (-> push_captures)
460 * push_captures, add_s -> push_onecapture
461 * match ->
462 * start/end_capture -> match,
463 * match_capture, matchbalance, classend -> -,
464 * min/max_expand -> match, singlematch
465 * singlematch -> matchbracketclass, match_class,
466 * matchbracketclass -> match_class -> -,
467 */
468
469
470 #define CAP_UNFINISHED (-1)
471 #define CAP_POSITION (-2)
472
473 typedef struct MatchState {
474 const char *src_init; /* init of source string */
475 const char *src_end; /* end (`\0') of source string */
476 lua_State *L;
477 int level; /* total number of captures (finished or unfinished) */
478 int mode;
479 int mb;
480 struct {
481 const char *init;
482 ptrdiff_t len;
483 } capture[LUA_MAXCAPTURES];
484 } MatchState;
485
486
487 #define L_ESC '%'
488 #define SPECIALS "^$*+?.([%-"
489
490
491 static int check_capture (MatchState *ms, int l) {
492 l -= '1';
493 if (l < 0 || l >= ms->level || ms->capture[l].len == CAP_UNFINISHED)
494 return luaL_error(ms->L, "invalid capture index");
495 return l;
496 }
497
498
499 static int capture_to_close (MatchState *ms)
500 {
501 int level = ms->level;
502 for (level--; level>=0; level--)
503 if (ms->capture[level].len == CAP_UNFINISHED) return level;
504 return luaL_error(ms->L, "invalid pattern capture");
505 }
506
507
508 static const char *classend (MatchState *ms, const char *p)
509 {
510 switch (*p) {
511 case L_ESC:
512 if (!*++p) luaL_error(ms->L, "malformed pattern (ends with " LUA_QL("%%") ")");
513 break;
514 case '[':
515 /* if (*p == '^') p++; -- no effect */
516 do { /* look for a `]' */
517 if (!*p) luaL_error(ms->L, "malformed pattern (missing " LUA_QL("]") ")");
518 if (L_ESC == *(p++) && *p) p++; /* skip escapes (e.g. `%]') */
519 } while (']' != *p);
520 break;
521 default:
522 if (!ms->mb) break;
523 utf8_deco(&p, p+4);
524 return p;
525 }
526 return p+1;
527 } /* classend */
528
529
530 /*
531 * The following macros are used for fast character category tests. The
532 * x_BITS values are shifted right by the category value to determine whether
533 * the given category is included in the set.
534 */
535
536 #define LETTER_BITS ((1 << UPPERCASE_LETTER) | (1 << LOWERCASE_LETTER) \
537 | (1 << TITLECASE_LETTER) | (1 << MODIFIER_LETTER) | (1 << OTHER_LETTER))
538
539 #define DIGIT_BITS (1 << DECIMAL_DIGIT_NUMBER)
540
541 #define NUMBER_BITS (1 << DECIMAL_DIGIT_NUMBER) \
542 | (1 << LETTER_NUMBER) | (1 << OTHER_NUMBER)
543
544 #define SPACE_BITS ((1 << SPACE_SEPARATOR) | (1 << LINE_SEPARATOR) \
545 | (1 << PARAGRAPH_SEPARATOR))
546
547 #define CONNECTOR_BITS (1 << CONNECTOR_PUNCTUATION)
548
549 #define PUNCT_BITS ((1 << CONNECTOR_PUNCTUATION) | \
550 (1 << DASH_PUNCTUATION) | (1 << OPEN_PUNCTUATION) | \
551 (1 << CLOSE_PUNCTUATION) | (1 << INITIAL_QUOTE_PUNCTUATION) | \
552 (1 << FINAL_QUOTE_PUNCTUATION) | (1 << OTHER_PUNCTUATION))
553
554
555 /* character c matches class cl. undefined for cl not ascii */
556 static int match_class (int c, int cl, int mode)
557 {
558 int msk, res;
559 switch (0x20|cl /*tolower*/) {
560 case 'a' : msk = LETTER_BITS; break;
561 case 'c' : msk = 1<<CONTROL; break;
562 case 'x' : /* hexdigits */
563 if (0x40==(~0x3f&c)/*64-127*/ && 1&(0x7e/*a-f*/>>(0x1f&c))) goto matched;
564 case 'd' : msk = 1<<DECIMAL_DIGIT_NUMBER; mode=0;/* ASCII only */ break;
565 case 'l' : msk = 1<<LOWERCASE_LETTER; break;
566 case 'n' : msk = NUMBER_BITS; break; /* new */
567 case 'p' : msk = PUNCT_BITS; break;
568 case 's' :
569 #define STDSPACE /* standard "space" controls 9-13 */ \
570 (1<<9/*TAB*/|1<<10/*LF*/|1<<11/*VT*/|1<<12/*FF*/|1<<13/*CR*/)
571 if (!(~0x1f & c) && 1&(STDSPACE >> c)) goto matched;
572 msk = SPACE_BITS;
573 break;
574 case 'u' : msk = 1<<UPPERCASE_LETTER; break;
575 /*
576 this is not compatible to lua 5.1, where %w is just a letter or a digit
577 case 'w' : msk = LETTER_BITS|NUMBER_BITS|CONNECTOR_BITS; break;
578 */
579 case 'w' : msk = LETTER_BITS|NUMBER_BITS; break;
580 case 'z' : if (!c) goto matched; msk = 0; break;
581 default: return cl == c;
582 }
583 res = 1 & (msk >> charcat(c));
584 if (!mode && 0x80&c) res = 0;
585 if (0) {
586 matched:
587 res = 1;
588 }
589 return 0x20&cl /*islower*/ ? res : !res;
590 } /* match_class */
591
592
593 /* decode single byte or UTF-8 seq; advance *s */
594 static unsigned deco (const MatchState *ms, const char **s, const char *e)
595 {
596 return ms->mb ? utf8_deco(s, e) : *(unsigned char*)(*s)++;
597 }
598
599 /* s must be < ms->src_end, p < ep */
600 static const char *singlematch (const MatchState *ms,
601 const char *s, const char *p, const char *ep)
602 {
603 int neg = 0;
604 unsigned c1, c2;
605 unsigned c;
606 #ifdef OPTIMIZE_SIZE
607 c = deco(ms, &s, ms->src_end);
608 #else
609 if (!ms->mb || !(0x80&*s))
610 c = *(unsigned char*)s++;
611 else
612 c = utf8_deco(&s, ms->src_end);
613 #endif
614
615 switch (*p) {
616 case L_ESC:
617 if (match_class(c, uchar(p[1]), ms->mode)) {
618 case '.': /* the all class */
619 #ifndef OPTIMIZE_SIZE
620 if (MODE_GRAPH != ms->mode) return s; /* common fast path */
621 #endif
622 goto matched_class;
623 }
624 s = 0;
625 break;
626 default:
627 #ifdef OPTIMIZE_SIZE
628 c1 = deco(ms, &p, ep);
629 #else
630 if (!ms->mb || !(0x80&*p))
631 c1 = *(unsigned char*)p++;
632 else
633 c1 = utf8_deco(&p, ep);
634 #endif
635 if (c != c1) s = 0;
636 break;
637 case '[': /* matchbracketclass */
638 ep--; /* now on the ']' */
639 if ((neg = '^' == *++p)) p++; /* skip the `^' */
640 while (p < ep) {
641 if (*p == L_ESC) {
642 if (match_class(c, uchar(*++p), ms->mode)) goto matched_class_in_brack;
643 p++;
644 continue;
645 }
646 c1 = deco(ms, &p, ep);
647 /* in lua-5.1 and 5.1.1 a trailing '-' is allowed
648 dynasm.lua relies on this
649 */
650 if ( ep <= p + 1 || '-' != *p ) {
651 const char *op = p, *es;
652 if (MODE_GRAPH == ms->mode) utf8_graphext(&p, ep);
653 if (c != c1) continue;
654 if (MODE_GRAPH != ms->mode) goto matched;
655 /* comp grapheme extension */
656 es = s;
657 utf8_graphext(&es, ms->src_end);
658 if (es-s == p-op && (es==s || !memcmp(s, op, es-s))) goto matched;
659 continue;
660
661 }
662 ++p;
663 /* range c1-c2 -- no extend support in range bounds... */
664 /* if (ep == ++p) break; see above */ /* bugger - trailing dash */
665 c2 = deco(ms, &p, ep);
666 if (c2 < c1) { unsigned swap=c1; c1=c2; c2=swap; }
667 if (c1 <= c && c <= c2) goto matched_class_in_brack; /* ...but extend match */
668 }
669 /* not matched */
670 neg = !neg;
671 matched:
672 if (neg) s = 0;
673 /* matchbracketclass */
674 }
675 return s;
676 matched_class_in_brack: /* matched %something or range in [] */
677 if (neg)
678 s = 0;
679 else {
680 matched_class: /* matched %something or . */
681 if (MODE_GRAPH == ms->mode) utf8_graphext(&s, ms->src_end);
682 }
683 return s;
684 }
685
686
687 static const char *match (MatchState *ms, const char *s, const char *p);
688
689
690 static const char *matchbalance (MatchState *ms, const char *s,
691 const char *p) {
692 if (*p == 0 || *(p+1) == 0)
693 luaL_error(ms->L, "unbalanced pattern");
694 if (*s != *p) return NULL;
695 else {
696 int b = *p;
697 int e = *(p+1);
698 int cont = 1;
699 while (++s < ms->src_end) {
700 if (*s == e) {
701 if (--cont == 0) return s+1;
702 }
703 else if (*s == b) cont++;
704 }
705 }
706 return NULL; /* string ends out of balance */
707 }
708
709
710 static const char *max_expand (MatchState *ms,
711 const char *s, const char *p, const char *ep)
712 {
713 const char *sp = s, *es;
714 while (sp<ms->src_end && (es = singlematch(ms, sp, p, ep)))
715 sp = es;
716 /* keeps trying to match with the maximum repetitions */
717 while (sp>=s) {
718 const char *res = match(ms, sp, ep+1);
719 if (res || sp==s) return res;
720 if (!ms->mb)
721 sp--; /* else didn't match; reduce 1 repetition to try again */
722 else {
723 unsigned code = utf8_oced(&sp, s);
724 if (MODE_GRAPH == ms->mode)
725 while (Grapheme_Extend(code) && sp>s) code = utf8_oced(&sp, s);
726 }
727 }
728 return NULL;
729 }
730
731
732 static const char *min_expand (MatchState *ms,
733 const char *s, const char *p, const char *ep)
734 {
735 do {
736 const char *res = match(ms, s, ep+1);
737 if (res) return res;
738 if (s >= ms->src_end) break;
739 } while ((s = singlematch(ms, s, p, ep))); /* try with one more repetition */
740 return NULL;
741 }
742
743
744 static const char *start_capture (MatchState *ms, const char *s,
745 const char *p, int what) {
746 const char *res;
747 int level = ms->level;
748 if (level >= LUA_MAXCAPTURES) luaL_error(ms->L, "too many captures");
749 ms->capture[level].init = s;
750 ms->capture[level].len = what;
751 ms->level = level+1;
752 if ((res=match(ms, s, p)) == NULL) /* match failed? */
753 ms->level--; /* undo capture */
754 return res;
755 }
756
757
758 static const char *end_capture (MatchState *ms, const char *s,
759 const char *p) {
760 int l = capture_to_close(ms);
761 const char *res;
762 ms->capture[l].len = s - ms->capture[l].init; /* close capture */
763 if ((res = match(ms, s, p)) == NULL) /* match failed? */
764 ms->capture[l].len = CAP_UNFINISHED; /* undo capture */
765 return res;
766 }
767
768
769 static const char *match_capture (MatchState *ms, const char *s, int l) {
770 size_t len;
771 l = check_capture(ms, l);
772 len = ms->capture[l].len;
773 if ((size_t)(ms->src_end-s) >= len &&
774 memcmp(ms->capture[l].init, s, len) == 0)
775 return s+len;
776 else return NULL;
777 }
778
779
780 static const char *match (MatchState *ms, const char *s, const char *p) {
781 init: /* using goto's to optimize tail recursion */
782 switch (*p) {
783 case '(': { /* start capture */
784 if (*(p+1) == ')') /* position capture? */
785 return start_capture(ms, s, p+2, CAP_POSITION);
786 else
787 return start_capture(ms, s, p+1, CAP_UNFINISHED);
788 }
789 case ')': { /* end capture */
790 return end_capture(ms, s, p+1);
791 }
792 case L_ESC: {
793 switch (*(p+1)) {
794 case 'b': { /* balanced string? */
795 s = matchbalance(ms, s, p+2);
796 if (s == NULL) return NULL;
797 p+=4; goto init; /* else return match(ms, s, p+4); */
798 }
799 #if 0 /* TODO */
800 case 'f': { /* frontier? */
801 const char *ep; char previous;
802 p += 2;
803 if (*p != '[')
804 luaL_error(ms->L, "missing " LUA_QL("[") " after "
805 LUA_QL("%%f") " in pattern" );
806 luaL_error(ms->L, "missing `[' after `%%f' in pattern");
807 ep = classend(ms, p); /* points to what is next */
808 /* with UTF-8, getting the previous is more complicated */
809 previous = (s == ms->src_init) ? '\0' : *(s-1);
810 /* use singlematch to apply all necessary magic */
811 if (singlematch(uchar(previous), p, ep-1) ||
812 !singlematch(uchar(*s), p, ep-1)) return NULL;
813 p=ep; goto init; /* else return match(ms, s, ep); */
814 }
815 #endif
816 default: {
817 if (isdigit(uchar(*(p+1)))) { /* capture results (%0-%9)? */
818 s = match_capture(ms, s, uchar(*(p+1)));
819 if (s == NULL) return NULL;
820 p+=2; goto init; /* else return match(ms, s, p+2) */
821 }
822 goto dflt; /* case default */
823 }
824 }
825 }
826 case '\0': { /* end of pattern */
827 return s; /* match succeeded */
828 }
829 case '$': {
830 if (*(p+1) == '\0') /* is the `$' the last char in pattern? */
831 return (s == ms->src_end) ? s : NULL; /* check end of string */
832 else goto dflt; /* ??? */
833 }
834 default: dflt: { /* it is a pattern item */
835 const char *ep = classend(ms, p); /* points to what is next */
836 const char *es = 0;
837 if (s < ms->src_end) es = singlematch(ms, s, p, ep);
838 switch (*ep) {
839 case '?': { /* optional */
840 const char *res;
841 if (es && (res=match(ms, es, ep+1))) return res;
842 p=ep+1; goto init; /* else return match(ms, s, ep+1); */
843 }
844 case '*': { /* 0 or more repetitions */
845 return max_expand(ms, s, p, ep);
846 }
847 case '+': { /* 1 or more repetitions */
848 return (es ? max_expand(ms, es, p, ep) : NULL);
849 }
850 case '-': { /* 0 or more repetitions (minimum) */
851 return min_expand(ms, s, p, ep);
852 }
853 default: {
854 if (!es) return NULL;
855 s=es; p=ep; goto init; /* else return match(ms, s+1, ep); */
856 }
857 }
858 }
859 }
860 }
861
862
863
864 static const char *lmemfind (const char *s1, size_t l1,
865 const char *s2, size_t l2) {
866 if (l2 == 0) return s1; /* empty strings are everywhere */
867 else if (l2 > l1) return NULL; /* avoids a negative `l1' */
868 else {
869 const char *init; /* to search for a `*s2' inside `s1' */
870 l2--; /* 1st char will be checked by `memchr' */
871 l1 = l1-l2; /* `s2' cannot be found after that */
872 while (l1 > 0 && (init = (const char *)memchr(s1, *s2, l1)) != NULL) {
873 init++; /* 1st char is already checked */
874 if (memcmp(init, s2+1, l2) == 0)
875 return init-1;
876 else { /* correct `l1' and `s1' to try again */
877 l1 -= init-s1;
878 s1 = init;
879 }
880 }
881 return NULL; /* not found */
882 }
883 }
884
885
886 static void push_onecapture (MatchState *ms, int i, const char *s,
887 const char *e )
888 {
889 if (i >= ms->level) {
890 if (i == 0) /* ms->level == 0, too */
891 lua_pushlstring(ms->L, s, e - s); /* add whole match */
892 else
893 luaL_error(ms->L, "invalid capture index");
894 }
895 else {
896 ptrdiff_t l = ms->capture[i].len;
897 if (l == CAP_UNFINISHED) luaL_error(ms->L, "unfinished capture");
898 if (l == CAP_POSITION)
899 lua_pushinteger(ms->L, ms->capture[i].init - ms->src_init + 1);
900 else
901 lua_pushlstring(ms->L, ms->capture[i].init, l);
902 }
903 }
904
905
906 static int push_captures (MatchState *ms, const char *s, const char *e) {
907 int i;
908 int nlevels = (ms->level == 0 && s) ? 1 : ms->level;
909 luaL_checkstack(ms->L, nlevels, "too many captures");
910 for ( i = 0; i < nlevels; i++ )
911 push_onecapture( ms, i, s, e );
912 return nlevels; /* number of strings pushed */
913 }
914
915
916 static int unic_find_aux (lua_State *L, int find) {
917 size_t l1, l2;
918 const char *s = luaL_checklstring(L, 1, &l1);
919 const char *p = luaL_checklstring(L, 2, &l2);
920 ptrdiff_t init = posrelat(luaL_optinteger(L, 3, 1), l1) - 1;
921 if (init < 0) init = 0;
922 else if ((size_t)(init) > l1) init = (ptrdiff_t)l1;
923 if (find && (lua_toboolean(L, 4) || /* explicit request? */
924 strpbrk(p, SPECIALS) == NULL)) { /* or no special characters? */
925 /* do a plain search */
926 const char *s2 = lmemfind(s+init, l1-init, p, l2);
927 if (s2) {
928 lua_pushinteger(L, s2-s+1);
929 lua_pushinteger(L, s2-s+l2);
930 return 2;
931 }
932 }
933 else {
934 MatchState ms;
935 int anchor = (*p == '^') ? (p++, 1) : 0;
936 const char *s1=s+init;
937 unsigned char u8_lenght = U8_LENGTH( (unsigned char)s[0] );
938 ms.L = L;
939 ms.src_init = s;
940 ms.src_end = s+l1;
941 ms.mode = lua_tointeger(L, lua_upvalueindex(1));
942 ms.mb = MODE_MBYTE(ms.mode);
943
944
945 /* LS/HH : patch for tracker issue 869, concerning "%s" match of à; the old code */
946 /* increments by 1 on a failure and can end up in the middle of an utf sequence */
947 /* so this was a major bug. */
948
949 do {
950 const char *res;
951 ms.level = 0;
952 if ((res=match(&ms, s1, p)) != NULL) {
953 if (find) {
954 lua_pushinteger(L, s1-s+1); /* start */
955 lua_pushinteger(L, res-s); /* end */
956 return push_captures(&ms, NULL, 0) + 2;
957 } else
958 return push_captures(&ms, s1, res);
959 }
960 s1 = s1 + (ms.mode > MODE_LATIN ? U8_LENGTH( uchar(s1[0])) : 1) ;
961 } while (s1 < ms.src_end && !anchor);
962 }
963 lua_pushnil(L); /* not found */
964 return 1;
965 }
966
967 static int unic_find (lua_State *L) {
968 return unic_find_aux(L, 1);
969 }
970
971
972 static int unic_match (lua_State *L) {
973 return unic_find_aux(L, 0);
974 }
975
976
977
978 static int gmatch_aux (lua_State *L) {
979 MatchState ms;
980 size_t ls;
981 const char *s = lua_tolstring(L, lua_upvalueindex(1), &ls);
982 const char *p = lua_tostring(L, lua_upvalueindex(2));
983 const char *src;
984 ms.L = L;
985 ms.src_init = s;
986 ms.src_end = s+ls;
987 ms.mode = lua_tointeger(L, lua_upvalueindex(4));
988 ms.mb = MODE_MBYTE(ms.mode);
989 for (src = s + (size_t)lua_tointeger(L, lua_upvalueindex(3));
990 src <= ms.src_end;
991 src++)
992 {
993 const char *e;
994 ms.level = 0;
995 if ((e = match(&ms, src, p)) != NULL) {
996 lua_Integer newstart = e-s;
997 if (e == src) newstart++; /* empty match? go at least one position */
998 lua_pushinteger(L, newstart);
999 lua_replace(L, lua_upvalueindex(3));
1000 return push_captures(&ms, src, e);
1001 }
1002 }
1003 return 0; /* not found */
1004 }
1005
1006
1007
1008 static int gmatch (lua_State *L) {
1009 luaL_checkstring(L, 1);
1010 luaL_checkstring(L, 2);
1011 lua_settop(L, 2);
1012 lua_pushinteger(L, 0);
1013 lua_pushinteger(L, lua_upvalueindex(1));
1014 lua_pushcclosure(L, gmatch_aux, 4);
1015 return 1;
1016 }
1017
1018 static int gfind_nodef (lua_State *L) {
1019 return luaL_error(L, LUA_QL("string.gfind") " was renamed to "
1020 LUA_QL("string.gmatch"));
1021 }
1022
1023
1024 static void add_s (MatchState *ms, luaL_Buffer *b,
1025 const char *s, const char *e)
1026 {
1027 size_t l, i;
1028 const char *news = lua_tolstring(ms->L, 3, &l);
1029 for (i = 0; i < l; i++) {
1030 if (news[i] != L_ESC)
1031 luaL_addchar(b, news[i]);
1032 else {
1033 i++; /* skip ESC */
1034 if (!isdigit(uchar(news[i])))
1035 luaL_addchar(b, news[i]);
1036 else if (news[i] == '0')
1037 luaL_addlstring(b, s, e - s);
1038 else {
1039 push_onecapture(ms, news[i] - '1', s, e);
1040 luaL_addvalue(b); /* add capture to accumulated result */
1041 }
1042 }
1043 }
1044 }
1045
1046 static void add_value (MatchState *ms, luaL_Buffer *b, const char *s,
1047 const char *e)
1048 {
1049 lua_State *L = ms->L;
1050 switch (lua_type(L, 3)) {
1051 case LUA_TNUMBER:
1052 case LUA_TSTRING: {
1053 add_s(ms, b, s, e);
1054 return;
1055 }
1056 case LUA_TFUNCTION: {
1057 int n;
1058 lua_pushvalue(L, 3);
1059 n = push_captures(ms, s, e);
1060 lua_call(L, n, 1);
1061 break;
1062 }
1063 case LUA_TTABLE: {
1064 push_onecapture(ms, 0, s, e);
1065 lua_gettable(L, 3);
1066 break;
1067 }
1068 default: {
1069 luaL_argerror(L, 3, "string/function/table expected");
1070 return;
1071 }
1072 }
1073 if (!lua_toboolean(L, -1)) { /* nil or false? */
1074 lua_pop(L, 1);
1075 lua_pushlstring(L, s, e - s); /* keep original text */
1076 }
1077 else if (!lua_isstring(L, -1))
1078 luaL_error(L, "invalid replacement value (a %s)", luaL_typename(L, -1));
1079 luaL_addvalue(b); /* add result to accumulator */
1080 }
1081
1082 static int unic_gsub (lua_State *L) {
1083 size_t srcl;
1084 const char *src = luaL_checklstring(L, 1, &srcl);
1085 const char *p = luaL_checkstring(L, 2);
1086 int max_s = luaL_optint(L, 4, srcl+1);
1087 int anchor = (*p == '^') ? (p++, 1) : 0;
1088 int n = 0;
1089 MatchState ms;
1090 luaL_Buffer b;
1091 luaL_buffinit(L, &b);
1092 ms.L = L;
1093 ms.src_init = src;
1094 ms.src_end = src+srcl;
1095 ms.mode = lua_tointeger(L, lua_upvalueindex(1));
1096 ms.mb = MODE_MBYTE(ms.mode);
1097 while (n < max_s) {
1098 const char *e;
1099 ms.level = 0;
1100 e = match(&ms, src, p);
1101 if (e) {
1102 n++;
1103 add_value(&ms, &b, src, e);
1104 }
1105 if (e && e>src) /* non empty match? */
1106 src = e; /* skip it */
1107 else if (src < ms.src_end)
1108 luaL_addchar(&b, *src++);
1109 else break;
1110 if (anchor) break;
1111 }
1112 luaL_addlstring(&b, src, ms.src_end-src);
1113 luaL_pushresult(&b);
1114 lua_pushinteger(L, n); /* number of substitutions */
1115 return 2;
1116 }
1117
1118 /* }====================================================== */
1119
1120
1121 /* maximum size of each formatted item (> len(format('%99.99f', -1e308))) */
1122 #define MAX_ITEM 512
1123 /* valid flags in a format specification */
1124 #define FLAGS "-+ #0"
1125 /*
1126 ** maximum size of each format specification (such as '%-099.99d')
1127 ** (+10 accounts for %99.99x plus margin of error)
1128 */
1129 #define MAX_FORMAT (sizeof(FLAGS) + sizeof(LUA_INTFRMLEN) + 10)
1130
1131
1132 static void addquoted (lua_State *L, luaL_Buffer *b, int arg) {
1133 size_t l;
1134 const char *s = luaL_checklstring(L, arg, &l);
1135 luaL_addchar(b, '"');
1136 while (l--) {
1137 switch (*s) {
1138 case '"': case '\\': case '\n': {
1139 luaL_addchar(b, '\\');
1140 luaL_addchar(b, *s);
1141 break;
1142 }
1143 case '\r': {
1144 luaL_addlstring(b, "\\r", 2);
1145 break;
1146 }
1147 case '\0': {
1148 luaL_addlstring(b, "\\000", 4);
1149 break;
1150 }
1151 default: {
1152 luaL_addchar(b, *s);
1153 break;
1154 }
1155 }
1156 s++;
1157 }
1158 luaL_addchar(b, '"');
1159 }
1160
1161
1162 static const char *scanformat (lua_State *L, const char *strfrmt, char *form,
1163 int *hasprecision)
1164 {
1165 const char *p = strfrmt;
1166 while (strchr(FLAGS, *p)) p++; /* skip flags */
1167 if ((size_t)(p - strfrmt) >= sizeof(FLAGS))
1168 luaL_error(L, "invalid format (repeated flags)");
1169 if (isdigit(uchar(*p))) p++; /* skip width */
1170 if (isdigit(uchar(*p))) p++; /* (2 digits at most) */
1171 if (*p == '.') {
1172 p++;
1173 *hasprecision = 1;
1174 if (isdigit(uchar(*p))) p++; /* skip precision */
1175 if (isdigit(uchar(*p))) p++; /* (2 digits at most) */
1176 }
1177 if (isdigit(uchar(*p)))
1178 luaL_error(L, "invalid format (width or precision too long)");
1179 form[0] = L_ESC;
1180 strncpy(form+1, strfrmt, p-strfrmt+1);
1181 form[p-strfrmt+2] = 0;
1182 return p;
1183 }
1184
1185 static void addintlen (char *form) {
1186 size_t l = strlen(form);
1187 char spec = form[l - 1];
1188 strcpy(form + l - 1, LUA_INTFRMLEN);
1189 form[l + sizeof(LUA_INTFRMLEN) - 2] = spec;
1190 form[l + sizeof(LUA_INTFRMLEN) - 1] = '\0';
1191 }
1192
1193 static int str_format (lua_State *L) {
1194 int arg = 1;
1195 size_t sfl;
1196 const char *strfrmt = luaL_checklstring(L, arg, &sfl);
1197 const char *strfrmt_end = strfrmt+sfl;
1198 luaL_Buffer b;
1199 luaL_buffinit(L, &b);
1200 while (strfrmt < strfrmt_end) {
1201 if (*strfrmt != L_ESC)
1202 luaL_addchar(&b, *strfrmt++);
1203 else if (*++strfrmt == L_ESC)
1204 luaL_addchar(&b, *strfrmt++); /* %% */
1205 else { /* format item */
1206 char form[MAX_FORMAT]; /* to store the format (`%...') */
1207 char buff[MAX_ITEM]; /* to store the formatted item */
1208 int hasprecision = 0;
1209 arg++;
1210 strfrmt = scanformat(L, strfrmt, form, &hasprecision);
1211 switch (*strfrmt++) {
1212 case 'c': {
1213 #ifdef LUA_USE_SNPRINTF
1214 snprintf( buff, MAX_ITEM, form,
1215 (int) luaL_checknumber( L, arg ) );
1216 #else
1217 sprintf(buff, form, (int) luaL_checknumber( L, arg ) );
1218 #endif
1219 break;
1220 }
1221 case 'd': case 'i': {
1222 addintlen( form );
1223 #ifdef LUA_USE_SNPRINTF
1224 snprintf( buff, MAX_ITEM, form,
1225 (LUA_INTFRM_T) luaL_checknumber(L, arg) );
1226 #else
1227 sprintf(buff, form,
1228 (LUA_INTFRM_T) luaL_checknumber(L, arg) );
1229 #endif
1230 break;
1231 }
1232 case 'o': case 'u': case 'x': case 'X': {
1233 addintlen( form );
1234 #ifdef LUA_USE_SNPRINTF
1235 snprintf(buff, MAX_ITEM, form,
1236 (unsigned LUA_INTFRM_T) luaL_checknumber(L, arg) );
1237 #else
1238 sprintf(buff, form,
1239 (unsigned LUA_INTFRM_T) luaL_checknumber(L, arg) );
1240 #endif
1241 break;
1242 }
1243 case 'e': case 'E': case 'f':
1244 case 'g': case 'G': {
1245 #ifndef LUA_NUMBER_DOUBLE
1246 luaL_argerror( L, 1, "double formatting not supported" );
1247 #else
1248 # ifdef __dietlibc__
1249 # warning "double formatting is broken in dietlibc"
1250 # endif
1251 # ifdef LUA_USE_SNPRINTF
1252 snprintf(buff, MAX_ITEM, form,
1253 (double) luaL_checknumber(L, arg) );
1254 # else
1255 sprintf(buff, form, (double) luaL_checknumber(L, arg) );
1256 # endif
1257 #endif
1258 break;
1259 }
1260 case 'q': {
1261 addquoted(L, &b, arg);
1262 continue; /* skip the `addsize' at the end */
1263 }
1264 case 's': {
1265 size_t l;
1266 const char *s = luaL_checklstring(L, arg, &l);
1267 if (!hasprecision && l >= 100) {
1268 /* no precision and string is too long to be formatted;
1269 keep original string */
1270 lua_pushvalue(L, arg);
1271 luaL_addvalue(&b);
1272 continue; /* skip the `addsize' at the end */
1273 }
1274 else {
1275 #ifdef LUA_USE_SNPRINTF
1276 snprintf(buff, MAX_ITEM, form, s);
1277 #else
1278 sprintf(buff, form, s);
1279 #endif
1280 break;
1281 }
1282 }
1283 default: { /* also treat cases `pnLlh' */
1284 return luaL_error(L, "invalid option " LUA_QL("%%%c") " to "
1285 LUA_QL("format"), *(strfrmt - 1));
1286 }
1287 }
1288 luaL_addlstring(&b, buff, strlen(buff));
1289 }
1290 }
1291 luaL_pushresult(&b);
1292 return 1;
1293 }
1294
1295 #ifdef WANT_EXT_MATCH
1296 static struct { const char *k; int v; } unicflags[] = {
1297 { "ASCII", MODE_ASCII }
1298 ,{ "LATIN", MODE_LATIN }
1299 ,{ "UTF8", MODE_UTF8 }
1300 ,{ "GRAPH", MODE_GRAPH }
1301 };
1302 #define unicflags_sz ( sizeof( unicflags ) / sizeof( unicflags[0] ) )
1303
1304 /*
1305 allow direkt match calls from c
1306 */
1307 int ext_uni_match ( void *state, const char *s, size_t n,
1308 const char *p, int init, int mode )
1309 {
1310 lua_State *L = state;
1311 MatchState ms;
1312 int anchor = (*p == '^') ? (p++, 1) : 0;
1313 const char *s1;
1314 int i = posrelat( init, n ) - 1;
1315 if (i < 0) i = 0;
1316 else if ((size_t)(i) > n) i = (ptrdiff_t)n;
1317 s1 = s + i;
1318 ms.L = L;
1319 ms.src_init = s;
1320 ms.src_end = s + n;
1321 ms.mode = mode;
1322 ms.mb = MODE_MBYTE(mode);
1323 do {
1324 const char *res;
1325 ms.level = 0;
1326 if ( ( res=match(&ms, s1, p)) != NULL )
1327 return 1;
1328 } while ( s1++ < ms.src_end && !anchor );
1329 return 0;
1330 }
1331 #endif
1332
1333 static const luaL_Reg uniclib[] = {
1334 {"byte", unic_byte}, /* no cluster ! */
1335 {"char", unic_char},
1336 {"dump", str_dump},
1337 {"find", unic_find}, /* cluster */
1338 {"format", str_format},
1339 {"gfind", gfind_nodef},
1340 {"gmatch", gmatch}, /* cluster */
1341 {"gsub", unic_gsub}, /* cluster */
1342 {"len", unic_len}, /* cluster/byte opt. */
1343 {"lower", unic_lower},
1344 {"match", unic_match}, /* cluster */
1345 {"rep", str_rep},
1346 {"reverse", str_reverse},
1347 {"sub", unic_sub}, /* cluster/byte opt. */
1348 {"upper", unic_upper},
1349 {NULL, NULL}
1350 };
1351
1352 #if defined( SLNUNICODE_AS_STRING ) && defined( STRING_WITH_METAT )
1353 static void createmetatable (lua_State *L) {
1354 lua_newtable(L); /* create metatable for strings */
1355 lua_pushliteral(L, ""); /* dummy string */
1356 lua_pushvalue(L, -2);
1357 lua_setmetatable(L, -2); /* set string metatable */
1358 lua_pop(L, 1); /* pop dummy string */
1359 lua_pushvalue(L, -2); /* string library... */
1360 lua_setfield(L, -2, "__index"); /* ...is the __index metamethod */
1361 lua_pop(L, 1); /* pop metatable */
1362 }
1363 #endif
1364
1365 /*
1366 ** Open string library
1367 */
1368 LUALIB_API int luaopen_unicode (lua_State *L) {
1369 /* register unicode itself so require("unicode") works */
1370 luaL_openlib(L, SLN_UNICODENAME,
1371 uniclib + (sizeof uniclib/sizeof uniclib[0] - 1), 0); /* empty func list */
1372 lua_pop(L, 1);
1373 lua_getglobal(L,SLN_UNICODENAME);
1374 lua_newtable(L);
1375 lua_pushinteger(L, MODE_ASCII);
1376 luaL_setfuncs(L, uniclib, 1);
1377 lua_setfield(L, -2, "ascii");
1378
1379 lua_newtable(L);
1380 lua_pushinteger(L, MODE_LATIN);
1381 luaL_setfuncs(L, uniclib, 1);
1382 lua_setfield(L, -2, "latin1");
1383
1384 lua_newtable(L);
1385 lua_pushinteger(L, MODE_GRAPH);
1386 luaL_setfuncs(L, uniclib, 1);
1387 lua_setfield(L, -2, "grapheme");
1388
1389 lua_newtable(L);
1390 lua_pushinteger(L, MODE_UTF8);
1391 luaL_setfuncs(L, uniclib, 1);
1392 lua_setfield(L, -2, "utf8");
1393
1394 #ifdef WANT_EXT_MATCH
1395 {
1396 unsigned i;
1397 const char *ln = SLN_UNICODENAME ".mode";
1398 luaL_findtable( L, LUA_REGISTRYINDEX, "_LOADED", 1 );
1399 lua_getfield( L, -1, ln );
1400 if ( !lua_istable(L, -1 ) ) {
1401 lua_pop( L, 1 );
1402 if ( luaL_findtable( L, LUA_GLOBALSINDEX, ln, unicflags_sz ) )
1403 luaL_error( L, "name conflict for module " LUA_QS, ln );
1404 lua_pushvalue( L, -1 );
1405 lua_setfield( L, -3, ln );
1406 }
1407 lua_remove( L, -2 );
1408 for( i = 0; unicflags_sz > i; ++i ) {
1409 lua_pushnumber( L, unicflags[i].v );
1410 lua_setfield( L, -2, unicflags[i].k );
1411 }
1412 }
1413 #endif
1414 return 1;
1415 }
1416