Debian Codegraph @

extensions/Scribunto/includes/Engines/LuaCommon/lualib/ustring/ustring.lua

raw symbols SCIP
1 local ustring = {}
2
3 -- Copy these, just in case
4 local S = {
5 byte = string.byte,
6 char = string.char,
7 len = string.len,
8 sub = string.sub,
9 find = string.find,
10 match = string.match,
11 gmatch = string.gmatch,
12 gsub = string.gsub,
13 format = string.format,
14 }
15
16 ---- Configuration ----
17 -- To limit the length of strings or patterns processed, set these
18 ustring.maxStringLength = math.huge
19 ustring.maxPatternLength = math.huge
20
21 ---- Utility functions ----
22
23 local function checkType( name, argidx, arg, expecttype, nilok )
24 if arg == nil and nilok then
25 return
26 end
27 if type( arg ) ~= expecttype then
28 local msg = S.format( "bad argument #%d to '%s' (%s expected, got %s)",
29 argidx, name, expecttype, type( arg )
30 )
31 error( msg, 3 )
32 end
33 end
34
35 local function checkString( name, s )
36 if type( s ) == 'number' then
37 s = tostring( s )
38 end
39 if type( s ) ~= 'string' then
40 local msg = S.format( "bad argument #1 to '%s' (string expected, got %s)",
41 name, type( s )
42 )
43 error( msg, 3 )
44 end
45 if S.len( s ) > ustring.maxStringLength then
46 local msg = S.format( "bad argument #1 to '%s' (string is longer than %d bytes)",
47 name, ustring.maxStringLength
48 )
49 error( msg, 3 )
50 end
51 end
52
53 local function checkPattern( name, pattern )
54 if type( pattern ) == 'number' then
55 pattern = tostring( pattern )
56 end
57 if type( pattern ) ~= 'string' then
58 local msg = S.format( "bad argument #2 to '%s' (string expected, got %s)",
59 name, type( pattern )
60 )
61 error( msg, 3 )
62 end
63 if S.len( pattern ) > ustring.maxPatternLength then
64 local msg = S.format( "bad argument #2 to '%s' (pattern is longer than %d bytes)",
65 name, ustring.maxPatternLength
66 )
67 error( msg, 3 )
68 end
69 end
70
71 -- A private helper that splits a string into codepoints, and also collects the
72 -- starting position of each character and the total length in codepoints.
73 --
74 -- @param s string utf8-encoded string to decode
75 -- @return table
76 local function utf8_explode( s )
77 local ret = {
78 len = 0,
79 codepoints = {},
80 bytepos = {},
81 }
82
83 local i = 1
84 local l = S.len( s )
85 local cp, b, b2, trail
86 local min
87 while i <= l do
88 b = S.byte( s, i )
89 if b < 0x80 then
90 -- 1-byte code point, 00-7F
91 cp = b
92 trail = 0
93 min = 0
94 elseif b < 0xc2 then
95 -- Either a non-initial code point (invalid here) or
96 -- an overlong encoding for a 1-byte code point
97 return nil
98 elseif b < 0xe0 then
99 -- 2-byte code point, C2-DF
100 trail = 1
101 cp = b - 0xc0
102 min = 0x80
103 elseif b < 0xf0 then
104 -- 3-byte code point, E0-EF
105 trail = 2
106 cp = b - 0xe0
107 min = 0x800
108 elseif b < 0xf4 then
109 -- 4-byte code point, F0-F3
110 trail = 3
111 cp = b - 0xf0
112 min = 0x10000
113 elseif b == 0xf4 then
114 -- 4-byte code point, F4
115 -- Make sure it doesn't decode to over U+10FFFF
116 if S.byte( s, i + 1 ) > 0x8f then
117 return nil
118 end
119 trail = 3
120 cp = 4
121 min = 0x100000
122 else
123 -- Code point over U+10FFFF, or invalid byte
124 return nil
125 end
126
127 -- Check subsequent bytes for multibyte code points
128 for j = i + 1, i + trail do
129 b = S.byte( s, j )
130 if not b or b < 0x80 or b > 0xbf then
131 return nil
132 end
133 cp = cp * 0x40 + b - 0x80
134 end
135 if cp < min then
136 -- Overlong encoding
137 return nil
138 end
139
140 ret.codepoints[#ret.codepoints + 1] = cp
141 ret.bytepos[#ret.bytepos + 1] = i
142 ret.len = ret.len + 1
143 i = i + 1 + trail
144 end
145
146 -- Two past the end (for sub with empty string)
147 ret.bytepos[#ret.bytepos + 1] = l + 1
148 ret.bytepos[#ret.bytepos + 1] = l + 1
149
150 return ret
151 end
152
153 -- A private helper that finds the character offset for a byte offset.
154 --
155 -- @param cps table from utf8_explode
156 -- @param i int byte offset
157 -- @return int
158 local function cpoffset( cps, i )
159 local min, max, p = 0, cps.len + 1
160 if i == 0 then
161 return 0
162 end
163 while min + 1 < max do
164 p = math.floor( ( min + max ) / 2 ) + 1
165 if cps.bytepos[p] <= i then
166 min = p - 1
167 end
168 if cps.bytepos[p] >= i then
169 max = p - 1
170 end
171 end
172 return min + 1
173 end
174
175 ---- Trivial functions ----
176 -- These functions are the same as the standard string versions
177
178 ustring.byte = string.byte
179 ustring.format = string.format
180 ustring.rep = string.rep
181
182 ---- Non-trivial functions ----
183 -- These functions actually have to be UTF-8 aware
184
185
186 -- Determine if a string is valid UTF-8
187 --
188 -- @param s string
189 -- @return boolean
190 function ustring.isutf8( s )
191 checkString( 'isutf8', s )
192 return utf8_explode( s ) ~= nil
193 end
194
195 -- Return the byte offset of a character in a string
196 --
197 -- @param s string
198 -- @param l int codepoint number [default 1]
199 -- @param i int starting byte offset [default 1]
200 -- @return int|nil
201 function ustring.byteoffset( s, l, i )
202 checkString( 'byteoffset', s )
203 checkType( 'byteoffset', 2, l, 'number', true )
204 checkType( 'byteoffset', 3, i, 'number', true )
205 local cps = utf8_explode( s )
206 if cps == nil then
207 error( "bad argument #1 for 'byteoffset' (string is not UTF-8)", 2 )
208 end
209
210 i = i or 1
211 if i < 0 then
212 i = S.len( s ) + i + 1
213 end
214 if i < 1 or i > S.len( s ) then
215 return nil
216 end
217 local p = cpoffset( cps, i )
218 if l > 0 and cps.bytepos[p] == i then
219 l = l - 1
220 end
221 if p + l > cps.len then
222 return nil
223 end
224 return cps.bytepos[p + l]
225 end
226
227 -- Return codepoints from a string
228 --
229 -- @see string.byte
230 -- @param s string
231 -- @param i int Starting character [default 1]
232 -- @param j int Ending character [default i]
233 -- @return int* Zero or more codepoints
234 function ustring.codepoint( s, i, j )
235 checkString( 'codepoint', s )
236 checkType( 'codepoint', 2, i, 'number', true )
237 checkType( 'codepoint', 3, j, 'number', true )
238 local cps = utf8_explode( s )
239 if cps == nil then
240 error( "bad argument #1 for 'codepoint' (string is not UTF-8)", 2 )
241 end
242 i = i or 1
243 if i < 0 then
244 i = cps.len + i + 1
245 end
246 j = j or i
247 if j < 0 then
248 j = cps.len + j + 1
249 end
250 if j < i then
251 return -- empty result set
252 end
253 i = math.max( 1, math.min( i, cps.len + 1 ) )
254 j = math.max( 1, math.min( j, cps.len + 1 ) )
255 return unpack( cps.codepoints, i, j )
256 end
257
258 -- Return an iterator over the codepoint (as integers)
259 -- for cp in ustring.gcodepoint( s ) do ... end
260 --
261 -- @param s string
262 -- @param i int Starting character [default 1]
263 -- @param j int Ending character [default -1]
264 -- @return function
265 -- @return nil
266 -- @return nil
267 function ustring.gcodepoint( s, i, j )
268 checkString( 'gcodepoint', s )
269 checkType( 'gcodepoint', 2, i, 'number', true )
270 checkType( 'gcodepoint', 3, j, 'number', true )
271 local cps = utf8_explode( s )
272 if cps == nil then
273 error( "bad argument #1 for 'gcodepoint' (string is not UTF-8)", 2 )
274 end
275 i = i or 1
276 if i < 0 then
277 i = cps.len + i + 1
278 end
279 j = j or -1
280 if j < 0 then
281 j = cps.len + j + 1
282 end
283 if j < i then
284 return function ()
285 return nil
286 end
287 end
288 i = math.max( 1, math.min( i, cps.len + 1 ) )
289 j = math.max( 1, math.min( j, cps.len + 1 ) )
290 return function ()
291 if i <= j then
292 local ret = cps.codepoints[i]
293 i = i + 1
294 return ret
295 end
296 return nil
297 end
298 end
299
300 -- Convert codepoints to a string
301 --
302 -- @see string.char
303 -- @param ... int List of codepoints
304 -- @return string
305 local function internalChar( t, s, e )
306 local ret = {}
307 for i = s, e do
308 local v = t[i]
309 if type( v ) ~= 'number' then
310 checkType( 'char', i, v, 'number' )
311 end
312 v = math.floor( v )
313 if v < 0 or v > 0x10ffff then
314 error( S.format( "bad argument #%d to 'char' (value out of range)", i ), 2 )
315 elseif v < 0x80 then
316 ret[#ret + 1] = v
317 elseif v < 0x800 then
318 ret[#ret + 1] = 0xc0 + math.floor( v / 0x40 ) % 0x20
319 ret[#ret + 1] = 0x80 + v % 0x40
320 elseif v < 0x10000 then
321 ret[#ret + 1] = 0xe0 + math.floor( v / 0x1000 ) % 0x10
322 ret[#ret + 1] = 0x80 + math.floor( v / 0x40 ) % 0x40
323 ret[#ret + 1] = 0x80 + v % 0x40
324 else
325 ret[#ret + 1] = 0xf0 + math.floor( v / 0x40000 ) % 0x08
326 ret[#ret + 1] = 0x80 + math.floor( v / 0x1000 ) % 0x40
327 ret[#ret + 1] = 0x80 + math.floor( v / 0x40 ) % 0x40
328 ret[#ret + 1] = 0x80 + v % 0x40
329 end
330 end
331 return S.char( unpack( ret ) )
332 end
333 function ustring.char( ... )
334 return internalChar( { ... }, 1, select( '#', ... ) )
335 end
336
337 -- Return the length of a string in codepoints, or
338 -- nil if the string is not valid UTF-8.
339 --
340 -- @see string.len
341 -- @param string
342 -- @return int|nil
343 function ustring.len( s )
344 checkString( 'len', s )
345 local cps = utf8_explode( s )
346 if cps == nil then
347 return nil
348 else
349 return cps.len
350 end
351 end
352
353 -- Private function to return a substring of a string
354 --
355 -- @param s string
356 -- @param cps table Exploded string
357 -- @param i int Starting character [default 1]
358 -- @param j int Ending character [default -1]
359 -- @return string
360 local function sub( s, cps, i, j )
361 return S.sub( s, cps.bytepos[i], cps.bytepos[j+1] - 1 )
362 end
363
364 -- Return a substring of a string
365 --
366 -- @see string.sub
367 -- @param s string
368 -- @param i int Starting character [default 1]
369 -- @param j int Ending character [default -1]
370 -- @return string
371 function ustring.sub( s, i, j )
372 checkString( 'sub', s )
373 checkType( 'sub', 2, i, 'number', true )
374 checkType( 'sub', 3, j, 'number', true )
375 local cps = utf8_explode( s )
376 if cps == nil then
377 error( "bad argument #1 for 'sub' (string is not UTF-8)", 2 )
378 end
379 i = i or 1
380 if i < 0 then
381 i = cps.len + i + 1
382 end
383 j = j or -1
384 if j < 0 then
385 j = cps.len + j + 1
386 end
387 if j < i then
388 return ''
389 end
390 i = math.max( 1, math.min( i, cps.len + 1 ) )
391 j = math.max( 1, math.min( j, cps.len + 1 ) )
392 return sub( s, cps, i, j )
393 end
394
395 ---- Table-driven functions ----
396 -- These functions load a conversion table when called
397
398 -- Convert a string to uppercase
399 --
400 -- @see string.upper
401 -- @param s string
402 -- @return string
403 function ustring.upper( s )
404 checkString( 'upper', s )
405 local map = require 'ustring/upper';
406 local ret = S.gsub( s, '([^\128-\191][\128-\191]*)', map )
407 return ret
408 end
409
410 -- Convert a string to lowercase
411 --
412 -- @see string.lower
413 -- @param s string
414 -- @return string
415 function ustring.lower( s )
416 checkString( 'lower', s )
417 local map = require 'ustring/lower';
418 local ret = S.gsub( s, '([^\128-\191][\128-\191]*)', map )
419 return ret
420 end
421
422 ---- Pattern functions ----
423 -- Ugh. Just ugh.
424
425 -- Cache for character sets (e.g. [a-z])
426 local charset_cache = {}
427 setmetatable( charset_cache, { __weak = 'kv' } )
428
429 -- Private function to find a pattern in a string
430 -- Yes, this basically reimplements the whole of Lua's pattern matching, in
431 -- Lua.
432 --
433 -- @see ustring.find
434 -- @param s string
435 -- @param cps table Exploded string
436 -- @param rawpat string Pattern
437 -- @param pattern table Exploded pattern
438 -- @param init int Starting index
439 -- @param noAnchor boolean True to ignore '^'
440 -- @return int starting index of the match
441 -- @return int ending index of the match
442 -- @return string|int* captures
443 local function find( s, cps, rawpat, pattern, init, noAnchor )
444 local charsets = require 'ustring/charsets'
445 local anchor = false
446 local ncapt, captures
447 local captparen = {}
448
449 -- Extract the value of a capture from the
450 -- upvalues ncapt and capture.
451 local function getcapt( n, err, errl )
452 if n > ncapt then
453 error( err, errl + 1 )
454 elseif type( captures[n] ) == 'table' then
455 if captures[n][2] == '' then
456 error( err, errl + 1 )
457 end
458 return sub( s, cps, captures[n][1], captures[n][2] ), captures[n][2] - captures[n][1] + 1
459 else
460 return captures[n], math.floor( math.log10( captures[n] ) ) + 1
461 end
462 end
463
464 local match, match_charset, parse_charset
465
466 -- Main matching function. Uses tail recursion where possible.
467 -- Returns the position of the character after the match, and updates the
468 -- upvalues ncapt and captures.
469 match = function ( sp, pp )
470 local c = pattern.codepoints[pp]
471 if c == 0x28 then -- '(': starts capture group
472 ncapt = ncapt + 1
473 captparen[ncapt] = pp
474 local ret
475 if pattern.codepoints[pp + 1] == 0x29 then -- ')': Pattern is '()', capture position
476 captures[ncapt] = sp
477 ret = match( sp, pp + 2 )
478 else
479 -- Start capture group
480 captures[ncapt] = { sp, '' }
481 ret = match( sp, pp + 1 )
482 end
483 if ret then
484 return ret
485 else
486 -- Failed, rollback
487 ncapt = ncapt - 1
488 return nil
489 end
490 elseif c == 0x29 then -- ')': ends capture group, pop current capture index from stack
491 for n = ncapt, 1, -1 do
492 if type( captures[n] ) == 'table' and captures[n][2] == '' then
493 captures[n][2] = sp - 1
494 local ret = match( sp, pp + 1 )
495 if ret then
496 return ret
497 else
498 -- Failed, rollback
499 captures[n][2] = ''
500 return nil
501 end
502 end
503 end
504 error( 'Unmatched close-paren at pattern character ' .. pp, 3 )
505 elseif c == 0x5b then -- '[': starts character set
506 return match_charset( sp, parse_charset( pp ) )
507 elseif c == 0x5d then -- ']'
508 error( 'Unmatched close-bracket at pattern character ' .. pp, 3 )
509 elseif c == 0x25 then -- '%'
510 c = pattern.codepoints[pp + 1]
511 if charsets[c] then -- A character set like '%a'
512 return match_charset( sp, pp + 2, charsets[c] )
513 elseif c == 0x62 then -- '%b': balanced delimiter match
514 local d1 = pattern.codepoints[pp + 2]
515 local d2 = pattern.codepoints[pp + 3]
516 if not d1 or not d2 then
517 error( 'malformed pattern (missing arguments to \'%b\')', 3 )
518 end
519 if cps.codepoints[sp] ~= d1 then
520 return nil
521 end
522 sp = sp + 1
523 local ct = 1
524 while true do
525 c = cps.codepoints[sp]
526 sp = sp + 1
527 if not c then
528 return nil
529 elseif c == d2 then
530 if ct == 1 then
531 return match( sp, pp + 4 )
532 end
533 ct = ct - 1
534 elseif c == d1 then
535 ct = ct + 1
536 end
537 end
538 elseif c == 0x66 then -- '%f': frontier pattern match
539 if pattern.codepoints[pp + 2] ~= 0x5b then
540 error( 'missing \'[\' after %f in pattern at pattern character ' .. pp, 3 )
541 end
542 local pp, charset = parse_charset( pp + 2 )
543 local c1 = cps.codepoints[sp - 1] or 0
544 local c2 = cps.codepoints[sp] or 0
545 if not charset[c1] and charset[c2] then
546 return match( sp, pp )
547 else
548 return nil
549 end
550 elseif c >= 0x30 and c <= 0x39 then -- '%0' to '%9': backreference
551 local m, l = getcapt( c - 0x30, 'invalid capture index %' .. c .. ' at pattern character ' .. pp, 3 )
552 local ep = math.min( cps.len + 1, sp + l )
553 if sub( s, cps, sp, ep - 1 ) == m then
554 return match( ep, pp + 2 )
555 else
556 return nil
557 end
558 elseif not c then -- percent at the end of the pattern
559 error( 'malformed pattern (ends with \'%\')', 3 )
560 else -- something else, treat as a literal
561 return match_charset( sp, pp + 2, { [c] = 1 } )
562 end
563 elseif c == 0x2e then -- '.': match anything
564 if not charset_cache['.'] then
565 local t = {}
566 setmetatable( t, { __index = function ( t, k ) return k end } )
567 charset_cache['.'] = { 1, t }
568 end
569 return match_charset( sp, pp + 1, charset_cache['.'][2] )
570 elseif c == nil then -- end of pattern
571 return sp
572 elseif c == 0x24 and pattern.len == pp then -- '$': assert end of string
573 return ( sp == cps.len + 1 ) and sp or nil
574 else
575 -- Any other character matches itself
576 return match_charset( sp, pp + 1, { [c] = 1 } )
577 end
578 end
579
580 -- Parse a bracketed character set (e.g. [a-z])
581 -- Returns the position after the set and a table holding the matching characters
582 parse_charset = function ( pp )
583 local _, ep
584 local epp = pattern.bytepos[pp] + 1
585 if S.sub( rawpat, epp, epp ) == '^' then
586 epp = epp + 1
587 end
588 if S.sub( rawpat, epp, epp ) == ']' then
589 -- Lua's string module effectively does this
590 epp = epp + 1
591 end
592 repeat
593 _, ep = S.find( rawpat, ']', epp, true )
594 if not ep then
595 error( 'Missing close-bracket for character set beginning at pattern character ' .. pp, 3 )
596 end
597 epp = ep + 1
598 until S.byte( rawpat, ep - 1 ) ~= 0x25 or S.byte( rawpat, ep - 2 ) == 0x25
599 local key = S.sub( rawpat, pattern.bytepos[pp], ep )
600 if charset_cache[key] then
601 local pl, cs = unpack( charset_cache[key] )
602 return pp + pl, cs
603 end
604
605 local p0 = pp
606 local cs = {}
607 local csrefs = { cs }
608 local invert = false
609 pp = pp + 1
610 if pattern.codepoints[pp] == 0x5e then -- '^'
611 invert = true
612 pp = pp + 1
613 end
614 local first = true
615 while true do
616 local c = pattern.codepoints[pp]
617 if not first and c == 0x5d then -- closing ']'
618 pp = pp + 1
619 break
620 elseif c == 0x25 then -- '%'
621 c = pattern.codepoints[pp + 1]
622 if charsets[c] then
623 csrefs[#csrefs + 1] = charsets[c]
624 else
625 cs[c] = 1
626 end
627 pp = pp + 2
628 elseif pattern.codepoints[pp + 1] == 0x2d and pattern.codepoints[pp + 2] and pattern.codepoints[pp + 2] ~= 0x5d then -- '-' followed by another char (not ']'), it's a range
629 for i = c, pattern.codepoints[pp + 2] do
630 cs[i] = 1
631 end
632 pp = pp + 3
633 elseif not c then -- Should never get here, but Just In Case...
634 error( 'Missing close-bracket', 3 )
635 else
636 cs[c] = 1
637 pp = pp + 1
638 end
639 first = false
640 end
641
642 local ret
643 if not csrefs[2] then
644 if not invert then
645 -- If there's only the one charset table, we can use it directly
646 ret = cs
647 else
648 -- Simple invert
649 ret = {}
650 setmetatable( ret, { __index = function ( t, k ) return k and not cs[k] end } )
651 end
652 else
653 -- Ok, we have to iterate over multiple charset tables
654 ret = {}
655 setmetatable( ret, { __index = function ( t, k )
656 if not k then
657 return nil
658 end
659 for i = 1, #csrefs do
660 if csrefs[i][k] then
661 return not invert
662 end
663 end
664 return invert
665 end } )
666 end
667
668 charset_cache[key] = { pp - p0, ret }
669 return pp, ret
670 end
671
672 -- Match a character set table with optional quantifier, followed by
673 -- the rest of the pattern.
674 -- Returns same as 'match' above.
675 match_charset = function ( sp, pp, charset )
676 local q = pattern.codepoints[pp]
677 if q == 0x2a then -- '*', 0 or more matches
678 pp = pp + 1
679 local i = 0
680 while charset[cps.codepoints[sp + i]] do
681 i = i + 1
682 end
683 while i >= 0 do
684 local ret = match( sp + i, pp )
685 if ret then
686 return ret
687 end
688 i = i - 1
689 end
690 return nil
691 elseif q == 0x2b then -- '+', 1 or more matches
692 pp = pp + 1
693 local i = 0
694 while charset[cps.codepoints[sp + i]] do
695 i = i + 1
696 end
697 while i > 0 do
698 local ret = match( sp + i, pp )
699 if ret then
700 return ret
701 end
702 i = i - 1
703 end
704 return nil
705 elseif q == 0x2d then -- '-', 0 or more matches non-greedy
706 pp = pp + 1
707 while true do
708 local ret = match( sp, pp )
709 if ret then
710 return ret
711 end
712 if not charset[cps.codepoints[sp]] then
713 return nil
714 end
715 sp = sp + 1
716 end
717 elseif q == 0x3f then -- '?', 0 or 1 match
718 pp = pp + 1
719 if charset[cps.codepoints[sp]] then
720 local ret = match( sp + 1, pp )
721 if ret then
722 return ret
723 end
724 end
725 return match( sp, pp )
726 else -- no suffix, must match 1
727 if charset[cps.codepoints[sp]] then
728 return match( sp + 1, pp )
729 else
730 return nil
731 end
732 end
733 end
734
735 init = init or 1
736 if init < 0 then
737 init = cps.len + init + 1
738 end
739 init = math.max( 1, math.min( init, cps.len + 1 ) )
740
741 -- Here is the actual match loop. It just calls 'match' on successive
742 -- starting positions (or not, if the pattern is anchored) until it finds a
743 -- match.
744 local sp = init
745 local pp = 1
746 if not noAnchor and pattern.codepoints[1] == 0x5e then -- '^': Pattern is anchored
747 anchor = true
748 pp = 2
749 end
750
751 repeat
752 ncapt, captures = 0, {}
753 local ep = match( sp, pp )
754 if ep then
755 for i = 1, ncapt do
756 captures[i] = getcapt( i, 'Unclosed capture beginning at pattern character ' .. captparen[i], 2 )
757 end
758 return sp, ep - 1, unpack( captures )
759 end
760 sp = sp + 1
761 until anchor or sp > cps.len + 1
762 return nil
763 end
764
765 -- Private function to decide if a pattern looks simple enough to use
766 -- Lua's built-in string library. The following make a pattern not simple:
767 -- * If it contains any bytes over 0x7f. We could skip these if they're not
768 -- inside brackets and aren't followed by quantifiers and aren't part of a
769 -- '%b', but that's too complicated to check.
770 -- * If it contains a negated character set.
771 -- * If it contains "%a" or any of the other %-prefixed character sets except %z.
772 -- * If it contains a '.' not followed by '*', '+', '-'. A bare '.' or '.?'
773 -- matches a partial UTF-8 character, but the others will happily enough
774 -- match a whole UTF-8 character thinking it's 2, 3 or 4.
775 -- * If it contains position-captures.
776 -- * If it matches the empty string
777 --
778 -- @param string pattern
779 -- @return boolean
780 local function patternIsSimple( pattern )
781 local findWithPcall = function ( ... )
782 local ok, ret = pcall( S.find, ... )
783 return ok and ret
784 end
785
786 return not (
787 S.find( pattern, '[\128-\255]' ) or
788 S.find( pattern, '%[%^' ) or
789 S.find( pattern, '%%[acdlpsuwxACDLPSUWXZ]' ) or
790 S.find( pattern, '%.[^*+-]' ) or S.find( pattern, '%.$' ) or
791 S.find( pattern, '()', 1, true ) or
792 pattern == '' or findWithPcall( '', pattern )
793 )
794 end
795
796 -- Find a pattern in a string
797 --
798 -- This works just like string.find, with the following changes:
799 -- * Everything works on UTF-8 characters rather than bytes
800 -- * Character classes are redefined in terms of Unicode properties:
801 -- * %a - Letter
802 -- * %c - Control
803 -- * %d - Decimal Number
804 -- * %l - Lower case letter
805 -- * %p - Punctuation
806 -- * %s - Separator, plus HT, LF, FF, CR, and VT
807 -- * %u - Upper case letter
808 -- * %w - Letter or Decimal Number
809 -- * %x - [0-9A-Fa-f0-9A-Fa-f]
810 --
811 -- @see string.find
812 -- @param s string
813 -- @param pattern string Pattern
814 -- @param init int Starting index
815 -- @param plain boolean Literal match, no pattern matching
816 -- @return int starting index of the match
817 -- @return int ending index of the match
818 -- @return string|int* captures
819 function ustring.find( s, pattern, init, plain )
820 checkString( 'find', s )
821 checkPattern( 'find', pattern )
822 checkType( 'find', 3, init, 'number', true )
823 checkType( 'find', 4, plain, 'boolean', true )
824 local cps = utf8_explode( s )
825 if cps == nil then
826 error( "bad argument #1 for 'find' (string is not UTF-8)", 2 )
827 end
828 local pat = utf8_explode( pattern )
829 if pat == nil then
830 error( "bad argument #2 for 'find' (string is not UTF-8)", 2 )
831 end
832
833 if plain or patternIsSimple( pattern ) then
834 if init and init > cps.len + 1 then
835 init = cps.len + 1
836 end
837 local m
838 if plain then
839 m = { true, S.find( s, pattern, cps.bytepos[init], plain ) }
840 else
841 m = { pcall( S.find, s, pattern, cps.bytepos[init], plain ) }
842 end
843 if m[1] then
844 if m[2] then
845 m[2] = cpoffset( cps, m[2] )
846 m[3] = cpoffset( cps, m[3] )
847 end
848 return unpack( m, 2 )
849 end
850 end
851
852 return find( s, cps, pattern, pat, init )
853 end
854
855 -- Match a string against a pattern
856 --
857 -- @see ustring.find
858 -- @see string.match
859 -- @param s string
860 -- @param pattern string
861 -- @param init int Starting offset for match
862 -- @return string|int* captures, or the whole match if there are none
863 function ustring.match( s, pattern, init )
864 checkString( 'match', s )
865 checkPattern( 'match', pattern )
866 checkType( 'match', 3, init, 'number', true )
867 local cps = utf8_explode( s )
868 if cps == nil then
869 error( "bad argument #1 for 'match' (string is not UTF-8)", 2 )
870 end
871 local pat = utf8_explode( pattern )
872 if pat == nil then
873 error( "bad argument #2 for 'match' (string is not UTF-8)", 2 )
874 end
875
876 if patternIsSimple( pattern ) then
877 local ret = { pcall( S.match, s, pattern, cps.bytepos[init] ) }
878 if ret[1] then
879 return unpack( ret, 2 )
880 end
881 end
882
883 local m = { find( s, cps, pattern, pat, init ) }
884 if not m[1] then
885 return nil
886 end
887 if m[3] then
888 return unpack( m, 3 )
889 end
890 return sub( s, cps, m[1], m[2] )
891 end
892
893 -- Return an iterator function over the matches for a pattern
894 --
895 -- @see ustring.find
896 -- @see string.gmatch
897 -- @param s string
898 -- @param pattern string
899 -- @return function
900 -- @return nil
901 -- @return nil
902 function ustring.gmatch( s, pattern )
903 checkString( 'gmatch', s )
904 checkPattern( 'gmatch', pattern )
905 if patternIsSimple( pattern ) then
906 local ret = { pcall( S.gmatch, s, pattern ) }
907 if ret[1] then
908 return unpack( ret, 2 )
909 end
910 end
911
912 local cps = utf8_explode( s )
913 if cps == nil then
914 error( "bad argument #1 for 'gmatch' (string is not UTF-8)", 2 )
915 end
916 local pat = utf8_explode( pattern )
917 if pat == nil then
918 error( "bad argument #2 for 'gmatch' (string is not UTF-8)", 2 )
919 end
920 local init = 1
921
922 return function ()
923 local m = { find( s, cps, pattern, pat, init, true ) }
924 if not m[1] then
925 return nil
926 end
927 init = m[2] + 1
928 if m[3] then
929 return unpack( m, 3 )
930 end
931 return sub( s, cps, m[1], m[2] )
932 end
933 end
934
935 -- Replace pattern matches in a string
936 --
937 -- @see ustring.find
938 -- @see string.gsub
939 -- @param s string
940 -- @param pattern string
941 -- @param repl string|function|table
942 -- @param int n
943 -- @return string
944 -- @return int
945 function ustring.gsub( s, pattern, repl, n )
946 checkString( 'gsub', s )
947 checkPattern( 'gsub', pattern )
948 checkType( 'gsub', 4, n, 'number', true )
949 if patternIsSimple( pattern ) then
950 local ret = { pcall( S.gsub, s, pattern, repl, n ) }
951 if ret[1] then
952 return unpack( ret, 2 )
953 end
954 end
955
956 if n == nil then
957 n = 1e100
958 end
959 if n < 1 then
960 -- No replacement
961 return s, 0
962 end
963
964 local cps = utf8_explode( s )
965 if cps == nil then
966 error( "bad argument #1 for 'gsub' (string is not UTF-8)", 2 )
967 end
968 local pat = utf8_explode( pattern )
969 if pat == nil then
970 error( "bad argument #2 for 'gsub' (string is not UTF-8)", 2 )
971 end
972
973 if pat.codepoints[1] == 0x5e then -- '^': Pattern is anchored
974 -- There can be only the one match, so make that explicit
975 n = 1
976 end
977
978 local tp
979 if type( repl ) == 'function' then
980 tp = 1
981 elseif type( repl ) == 'table' then
982 tp = 2
983 elseif type( repl ) == 'string' then
984 tp = 3
985 elseif type( repl ) == 'number' then
986 repl = tostring( repl )
987 tp = 3
988 else
989 checkType( 'gsub', 3, repl, 'function or table or string' )
990 end
991
992 local init = 1
993 local ct = 0
994 local ret = {}
995 local zeroAdjustment = 0
996 repeat
997 local m = { find( s, cps, pattern, pat, init + zeroAdjustment ) }
998 if not m[1] then
999 break
1000 end
1001 if init < m[1] then
1002 ret[#ret + 1] = sub( s, cps, init, m[1] - 1 )
1003 end
1004 local mm = sub( s, cps, m[1], m[2] )
1005
1006 -- This simplifies the code for the function and table cases (tp == 1 and tp == 2) when there are
1007 -- no captures in the pattern. As documented it would be incorrect for the string case by making
1008 -- %1 act like %0 instead of raising an "invalid capture index" error, but Lua in fact does
1009 -- exactly that for string.gsub.
1010 if #m < 3 then
1011 m[3] = mm
1012 end
1013
1014 local val, valType
1015 if tp == 1 then
1016 val = repl( unpack( m, 3 ) )
1017 elseif tp == 2 then
1018 val = repl[m[3]]
1019 elseif tp == 3 then
1020 if ct == 0 and #m < 11 then
1021 local ss = S.gsub( repl, '%%[%%0-' .. ( #m - 2 ) .. ']', 'x' )
1022 ss = S.match( ss, '%%[0-9]' )
1023 if ss then
1024 error( 'invalid capture index ' .. ss .. ' in replacement string', 2 )
1025 end
1026 end
1027 local t = {
1028 ["%0"] = mm,
1029 ["%1"] = m[3],
1030 ["%2"] = m[4],
1031 ["%3"] = m[5],
1032 ["%4"] = m[6],
1033 ["%5"] = m[7],
1034 ["%6"] = m[8],
1035 ["%7"] = m[9],
1036 ["%8"] = m[10],
1037 ["%9"] = m[11],
1038 ["%%"] = "%"
1039 }
1040 val = S.gsub( repl, '%%[%%0-9]', t )
1041 end
1042 valType = type( val )
1043 if valType ~= 'nil' and valType ~= 'string' and valType ~= 'number' then
1044 error( 'invalid replacement value (a ' .. valType .. ')', 2 )
1045 end
1046 ret[#ret + 1] = val or mm
1047 init = m[2] + 1
1048 ct = ct + 1
1049 zeroAdjustment = m[2] < m[1] and 1 or 0
1050 until init > cps.len or ct >= n
1051 if init <= cps.len then
1052 ret[#ret + 1] = sub( s, cps, init, cps.len )
1053 end
1054 return table.concat( ret ), ct
1055 end
1056
1057 ---- Unicode Normalization ----
1058 -- These functions load a conversion table when called
1059
1060 local function internalDecompose( cps, decomp )
1061 local cp = {}
1062 local normal = require 'ustring/normalization-data'
1063
1064 -- Decompose into cp, using the lookup table and logic for hangul
1065 for i = 1, cps.len do
1066 local c = cps.codepoints[i]
1067 local m = decomp[c]
1068 if m then
1069 for j = 0, #m do
1070 cp[#cp + 1] = m[j]
1071 end
1072 else
1073 cp[#cp + 1] = c
1074 end
1075 end
1076
1077 -- Now sort combiners by class
1078 local i, l = 1, #cp
1079 while i < l do
1080 local cc1 = normal.combclass[cp[i]]
1081 local cc2 = normal.combclass[cp[i+1]]
1082 if cc1 and cc2 and cc1 > cc2 then
1083 cp[i], cp[i+1] = cp[i+1], cp[i]
1084 if i > 1 then
1085 i = i - 1
1086 else
1087 i = i + 1
1088 end
1089 else
1090 i = i + 1
1091 end
1092 end
1093
1094 return cp, 1, l
1095 end
1096
1097 local function internalCompose( cp, _, l )
1098 local normal = require 'ustring/normalization-data'
1099
1100 -- Since NFD->NFC can never expand a character sequence, we can do this
1101 -- in-place.
1102 local comp = normal.comp[cp[1]]
1103 local sc = 1
1104 local j = 1
1105 local lastclass = 0
1106 for i = 2, l do
1107 local c = cp[i]
1108 local ccc = normal.combclass[c]
1109 if ccc then
1110 -- Trying a combiner with the starter
1111 if comp and lastclass < ccc and comp[c] then
1112 -- Yes!
1113 c = comp[c]
1114 cp[sc] = c
1115 comp = normal.comp[c]
1116 else
1117 -- No, copy it to the right place for output
1118 j = j + 1
1119 cp[j] = c
1120 lastclass = ccc
1121 end
1122 elseif comp and lastclass == 0 and comp[c] then
1123 -- Combining two adjacent starters
1124 c = comp[c]
1125 cp[sc] = c
1126 comp = normal.comp[c]
1127 else
1128 -- New starter, doesn't combine
1129 j = j + 1
1130 cp[j] = c
1131 comp = normal.comp[c]
1132 sc = j
1133 lastclass = 0
1134 end
1135 end
1136
1137 return cp, 1, j
1138 end
1139
1140 -- Normalize a string to NFC
1141 --
1142 -- Based on MediaWiki's UtfNormal class. Returns nil if the string is not valid
1143 -- UTF-8.
1144 --
1145 -- @param s string
1146 -- @return string|nil
1147 function ustring.toNFC( s )
1148 checkString( 'toNFC', s )
1149
1150 -- ASCII is always NFC
1151 if not S.find( s, '[\128-\255]' ) then
1152 return s
1153 end
1154
1155 local cps = utf8_explode( s )
1156 if cps == nil then
1157 return nil
1158 end
1159 local normal = require 'ustring/normalization-data'
1160
1161 -- First, scan through to see if the string is definitely already NFC
1162 local ok = true
1163 for i = 1, cps.len do
1164 local c = cps.codepoints[i]
1165 if normal.check[c] then
1166 ok = false
1167 break
1168 end
1169 end
1170 if ok then
1171 return s
1172 end
1173
1174 -- Next, expand to NFD then recompose
1175 return internalChar( internalCompose( internalDecompose( cps, normal.decomp ) ) )
1176 end
1177
1178 -- Normalize a string to NFD
1179 --
1180 -- Based on MediaWiki's UtfNormal class. Returns nil if the string is not valid
1181 -- UTF-8.
1182 --
1183 -- @param s string
1184 -- @return string|nil
1185 function ustring.toNFD( s )
1186 checkString( 'toNFD', s )
1187
1188 -- ASCII is always NFD
1189 if not S.find( s, '[\128-\255]' ) then
1190 return s
1191 end
1192
1193 local cps = utf8_explode( s )
1194 if cps == nil then
1195 return nil
1196 end
1197
1198 local normal = require 'ustring/normalization-data'
1199 return internalChar( internalDecompose( cps, normal.decomp ) )
1200 end
1201
1202 -- Normalize a string to NFKC
1203 --
1204 -- Based on MediaWiki's UtfNormal class. Returns nil if the string is not valid
1205 -- UTF-8.
1206 --
1207 -- @param s string
1208 -- @return string|nil
1209 function ustring.toNFKC( s )
1210 checkString( 'toNFKC', s )
1211
1212 -- ASCII is always NFKC
1213 if not S.find( s, '[\128-\255]' ) then
1214 return s
1215 end
1216
1217 local cps = utf8_explode( s )
1218 if cps == nil then
1219 return nil
1220 end
1221 local normal = require 'ustring/normalization-data'
1222
1223 -- Next, expand to NFKD then recompose
1224 return internalChar( internalCompose( internalDecompose( cps, normal.decompK ) ) )
1225 end
1226
1227 -- Normalize a string to NFKD
1228 --
1229 -- Based on MediaWiki's UtfNormal class. Returns nil if the string is not valid
1230 -- UTF-8.
1231 --
1232 -- @param s string
1233 -- @return string|nil
1234 function ustring.toNFKD( s )
1235 checkString( 'toNFKD', s )
1236
1237 -- ASCII is always NFKD
1238 if not S.find( s, '[\128-\255]' ) then
1239 return s
1240 end
1241
1242 local cps = utf8_explode( s )
1243 if cps == nil then
1244 return nil
1245 end
1246
1247 local normal = require 'ustring/normalization-data'
1248 return internalChar( internalDecompose( cps, normal.decompK ) )
1249 end
1250
1251 return ustring