diff --git a/src/wikitextprocessor/lua/_c_locale_string.lua b/src/wikitextprocessor/lua/_c_locale_string.lua new file mode 100644 index 0000000..7bb5cdd --- /dev/null +++ b/src/wikitextprocessor/lua/_c_locale_string.lua @@ -0,0 +1,230 @@ +-- Make Lua's string library independent of the process locale. +-- +-- Lua 5.1 classifies bytes with the C library (isspace(), isalpha(), +-- tolower(), ...) for the pattern classes %a %c %d %l %p %s %u %w %x and for +-- string.lower() and string.upper(). Those functions follow LC_CTYPE, which +-- Python sets from the environment at startup. In a UTF-8 locale macOS +-- counts byte 0xA0 as a space and 0xE0 as a letter, and Windows code-page +-- locales lower-case bytes above 0x7F, so `%s`, `%a` and string.lower() cut +-- or change UTF-8 characters ("à" is C3 A0, "ム" is E3 83 A0) and later +-- mw.ustring calls fail with "string is not UTF-8". MediaWiki's servers, and +-- Linux in any UTF-8 locale, classify only ASCII. +-- +-- Where the C library classifies any byte differently than the C locale +-- does, this replaces those functions with versions that give the C locale's +-- results: patterns are rewritten so that each class becomes an explicit set +-- of bytes, and lower()/upper() change only A-Z and a-z. Elsewhere (Linux in +-- a UTF-8 locale, any system in the C locale) it changes nothing, unless the +-- chunk's argument is true, as in tests. Returns whether it replaced them. + +local always = ... + +local concat = table.concat +local sub = string.sub +local type = type + +local find = string.find +local match = string.match +local gmatch = string.gmatch +local gsub = string.gsub +local lower = string.lower +local upper = string.upper + +-- The members of each class in the C locale, written as set items. The +-- upper-case letters are the complements, which a set cannot negate. +local CLASS_ITEMS = { + a = "A-Za-z", + c = "%z\1-\31\127", + d = "0-9", + l = "a-z", + p = "!-/:-@[-`{-~", + s = "\t-\r ", + u = "A-Z", + w = "0-9A-Za-z", + x = "0-9A-Fa-f", + A = "%z\1-@[-`{-\255", + C = " -~\128-\255", + D = "%z\1-/:-\255", + L = "%z\1-`{-\255", + P = "%z\1- 0-9A-Za-z\127-\255", + S = "%z\1-\8\14-\31!-\255", + U = "%z\1-@[-\255", + W = "%z\1-/:-@[-`{-\255", + X = "%z\1-/:-@G-`g-\255", +} + +-- A class outside a set becomes a set of its own. +local CLASS_SETS = {} +for letter, items in pairs(CLASS_ITEMS) do + CLASS_SETS[letter] = "[" .. items .. "]" +end + +local TO_LOWER = {} +local TO_UPPER = {} +for b = 65, 90 do + TO_LOWER[string.char(b)] = string.char(b + 32) + TO_UPPER[string.char(b + 32)] = string.char(b) +end + +-- True if the C library puts every byte in the classes the C locale puts it +-- in, and changes the case of A-Z and a-z only. +local function follows_c_locale() + local bytes = {} + for b = 0, 255 do + bytes[#bytes + 1] = string.char(b) + end + bytes = concat(bytes) + for letter, set in pairs(CLASS_SETS) do + if gsub(bytes, "%" .. letter, "") ~= gsub(bytes, set, "") then + return false + end + end + return lower(bytes) == gsub(bytes, "[A-Z]", TO_LOWER) + and upper(bytes) == gsub(bytes, "[a-z]", TO_UPPER) +end + +if not always and follows_c_locale() then + return false +end + +-- Rewrites the set that starts at p[i] ("["), reading it the way lstrlib.c +-- does (classEnd() finds its end, matchbracketclass() reads its items). +-- Appends to out and returns the index after the set, or nil when the +-- pattern should be left as it is. +local function translate_set(p, i, out) + local len = #p + local j = i + 1 + if sub(p, j, j) == "^" then + j = j + 1 + end + repeat + if j > len then + return nil -- missing "]": let Lua report the malformed pattern + end + if sub(p, j, j) == "%" then + j = j + 1 + end + j = j + 1 + until sub(p, j, j) == "]" + local ec = j + + local k = i + 1 + if sub(p, k, k) == "^" then + out[#out + 1] = "[^" + k = k + 1 + else + out[#out + 1] = "[" + end + while k < ec do + local c = sub(p, k, k) + if c == "%" then + local d = sub(p, k + 1, k + 1) + out[#out + 1] = CLASS_ITEMS[d] or ("%" .. d) + k = k + 2 + elseif sub(p, k + 1, k + 1) == "-" and k + 2 < ec then + if sub(p, k + 2, k + 2) == "%" then + return nil -- a range ending in "%": too odd to rewrite + end + out[#out + 1] = sub(p, k, k + 2) + k = k + 3 + elseif c == "-" then + -- Escaped, so that it cannot form a range with the last byte + -- of a class written just before it. + out[#out + 1] = "%-" + k = k + 1 + else + out[#out + 1] = c + k = k + 1 + end + end + out[#out + 1] = "]" + return ec + 1 +end + +-- Returns pattern p with every character class written out as bytes. +local function translate(p) + local out = {} + local len = #p + local i = 1 + while i <= len do + local c = sub(p, i, i) + if c == "%" then + local d = sub(p, i + 1, i + 1) + if d == "b" then + out[#out + 1] = sub(p, i, i + 3) -- %bxy: x and y are bytes + i = i + 4 + else + out[#out + 1] = CLASS_SETS[d] or ("%" .. d) + i = i + 2 + end + elseif c == "[" then + i = translate_set(p, i, out) + if i == nil then + return p + end + else + out[#out + 1] = c + i = i + 1 + end + end + return concat(out) +end + +local cache = {} +local cache_size = 0 + +local function c_locale_pattern(p) + if type(p) ~= "string" then + return p -- a number, or an error the original function reports + end + local t = cache[p] + if t == nil then + t = p + if find(p, "%", 1, true) then + t = translate(p) + end + if cache_size >= 10000 then + cache = {} + cache_size = 0 + end + cache[p] = t + cache_size = cache_size + 1 + end + return t +end + +-- String metatables index this same table, so s:find() is covered too. +string.find = function(s, pattern, init, plain) + if plain then + return find(s, pattern, init, plain) + end + return find(s, c_locale_pattern(pattern), init) +end + +string.match = function(s, pattern, init) + return match(s, c_locale_pattern(pattern), init) +end + +string.gmatch = function(s, pattern) + return gmatch(s, c_locale_pattern(pattern)) +end + +string.gsub = function(s, pattern, repl, n) + return gsub(s, c_locale_pattern(pattern), repl, n) +end + +string.lower = function(s) + if type(s) == "string" and find(s, "[\128-\255]") then + return (gsub(s, "[A-Z]", TO_LOWER)) + end + return (lower(s)) +end + +string.upper = function(s) + if type(s) == "string" and find(s, "[\128-\255]") then + return (gsub(s, "[a-z]", TO_UPPER)) + end + return (upper(s)) +end + +return true diff --git a/src/wikitextprocessor/luaexec.py b/src/wikitextprocessor/luaexec.py index 736abe9..5f00b29 100644 --- a/src/wikitextprocessor/luaexec.py +++ b/src/wikitextprocessor/luaexec.py @@ -51,6 +51,10 @@ # Determine which directory our data files are in LUA_DIR = files("wikitextprocessor") / "lua" +# Tests set this to run the wrappers in lua/_c_locale_string.lua also where +# the locale needs none, as on Linux. +ALWAYS_C_LOCALE_STRING = False + def lua_loader(ctx: "Wtp", modname: str) -> Optional[str]: """This function is called from the Lua sandbox to load a Lua module. @@ -335,6 +339,12 @@ def filter_attribute_access( ) set_lua_env_funcs(lua, ctx) + # Give the string library the C locale's character classes if the + # process locale gives it others, as macOS does in a UTF-8 locale (see + # the file's comment). On Linux this changes nothing. + with (LUA_DIR / "_c_locale_string.lua").open(encoding="utf-8") as f: + lua.execute(f.read(), ALWAYS_C_LOCALE_STRING) + # Load Lua sandbox Phase 1. This is a very minimal file that only sets # the Lua loader to our custom loader; we will then use it to load the # bigger phase 2 of the sandbox. This way, most of the sandbox loading diff --git a/tests/test_lua_locale.py b/tests/test_lua_locale.py new file mode 100644 index 0000000..60a0528 --- /dev/null +++ b/tests/test_lua_locale.py @@ -0,0 +1,242 @@ +import locale +import string +from contextlib import contextmanager +from unittest import TestCase, mock + +import lupa.lua51 as lupa + +from wikitextprocessor import Wtp, luaexec +from wikitextprocessor.luaexec import initialize_lua + +# Locales in which some C libraries count bytes above 0x7F as spaces or +# letters, or change their case: macOS in any UTF-8 locale (0xA0 is a space, +# 0xE0 a letter), and single-byte Latin-1 locales (like Windows code pages). +CANDIDATE_LOCALES = [ + "C.UTF-8", + "en_US.UTF-8", + "en_US.ISO8859-1", + "en_US.ISO-8859-1", + "en_US.iso88591", + "de_DE.ISO8859-1", + "de_DE.ISO-8859-1", + "fr_FR.ISO8859-1", +] + +LOCALE_PROBE = r""" +(string.find("\160", "%s") or string.find("\224", "%a") + or string.lower("\201") ~= "\201") and true or false +""" + + +@contextmanager +def misclassifying_locale(): + """Switches LC_CTYPE to a locale in which plain Lua classifies bytes + above 0x7F, if this system has one; yields its name or None.""" + saved = locale.setlocale(locale.LC_CTYPE) + try: + for name in CANDIDATE_LOCALES: + try: + locale.setlocale(locale.LC_CTYPE, name) + except locale.Error: + continue + if lupa.LuaRuntime().eval(LOCALE_PROBE): + yield name + return + locale.setlocale(locale.LC_CTYPE, saved) + yield None + finally: + locale.setlocale(locale.LC_CTYPE, saved) + + +@contextmanager +def c_locale(): + saved = locale.setlocale(locale.LC_CTYPE) + try: + locale.setlocale(locale.LC_CTYPE, "C") + yield + finally: + locale.setlocale(locale.LC_CTYPE, saved) + + +def always_wrapped(): + """Installs the wrappers even where the locale needs none, as on + Linux, so that every system tests them.""" + return mock.patch.object(luaexec, "ALWAYS_C_LOCALE_STRING", True) + + +# How many of the string functions are wrappers written in Lua: 0 or 6. +WRAPPED_FUNCTIONS = r""" +local n = 0 +for _, name in ipairs({"find", "match", "gmatch", "gsub", "lower", "upper"}) do + if debug.getinfo(string[name], "S").what == "Lua" then n = n + 1 end +end +return n +""" + + +# The members of each class in the C locale. +ASCII_CLASSES = { + "a": set(string.ascii_letters), + "c": {chr(b) for b in range(32)} | {"\x7f"}, + "d": set(string.digits), + "l": set(string.ascii_lowercase), + "p": set(string.punctuation), + "s": set(" \t\n\v\f\r"), + "u": set(string.ascii_uppercase), + "w": set(string.ascii_letters + string.digits), + "x": set(string.hexdigits), +} + +CLASS_HITS = r""" +function(pattern) + local hits = {} + for b = 0, 255 do + hits[#hits + 1] = string.find(string.char(b), pattern) and "1" or "0" + end + return table.concat(hits) +end +""" + +CASE_OF_ALL_BYTES = r""" +function(fn) + local all = {} + for b = 0, 255 do all[#all + 1] = string.char(b) end + local changed = {} + for b, c in ipairs({string.byte(string[fn](table.concat(all)), 1, -1)}) do + if c ~= b - 1 then changed[#changed + 1] = string.char(b - 1, c) end + end + return table.concat(changed) +end +""" + + +class TestLuaLocale(TestCase): + def setUp(self): + self.wtp = Wtp() + + def tearDown(self): + self.wtp.close_db_conn() + + def check_c_locale_classes(self): + initialize_lua(self.wtp) + class_hits = self.wtp.lua.eval(CLASS_HITS) + for letter, members in ASCII_CLASSES.items(): + expected = "".join( + "1" if chr(b) in members else "0" for b in range(256) + ) + complement = expected.translate(str.maketrans("01", "10")) + for pattern, want in [ + (f"%{letter}", expected), + (f"[%{letter}]", expected), + (f"[^%{letter}]", complement), + (f"%{letter.upper()}", complement), + (f"[%{letter.upper()}]", complement), + (f"[^%{letter.upper()}]", expected), + ]: + with self.subTest(pattern=pattern): + self.assertEqual(class_hits(pattern), want) + case_changes = self.wtp.lua.eval(CASE_OF_ALL_BYTES) + self.assertEqual( + case_changes("lower"), + "".join(c + c.lower() for c in string.ascii_uppercase), + ) + self.assertEqual( + case_changes("upper"), + "".join(c + c.upper() for c in string.ascii_lowercase), + ) + + def test_c_locale_classes(self): + self.check_c_locale_classes() + + def test_c_locale_classes_always_wrapped(self): + with always_wrapped(): + self.check_c_locale_classes() + self.assertEqual(self.wtp.lua.execute(WRAPPED_FUNCTIONS), 6) + + def test_c_locale_classes_in_misclassifying_locale(self): + with misclassifying_locale() as name: + if name is None: + self.skipTest("no locale here classifies bytes above 0x7F") + self.check_c_locale_classes() + self.assertEqual(self.wtp.lua.execute(WRAPPED_FUNCTIONS), 6) + + def test_no_wrappers_in_c_locale(self): + with c_locale(): + self.check_c_locale_classes() + self.assertEqual(self.wtp.lua.execute(WRAPPED_FUNCTIONS), 0) + + def test_utf8_survives_trim_and_lower(self): + self.check_module_calls() + + def test_utf8_survives_trim_and_lower_always_wrapped(self): + with always_wrapped(): + self.check_module_calls() + + def check_module_calls(self): + # "à" is C3 A0 and "ム" is E3 83 A0: on macOS in a UTF-8 locale, + # `%s` took the A0 byte and mw.text.trim() then failed with + # "string is not UTF-8" (also wikitextprocessor issue #301). + self.wtp.add_page( + "Module:test", + 828, + """ + local export = {} + function export.trim(frame) + local s = frame.args[1]:gsub("^%s+", ""):gsub("%s+$", "") + return mw.text.trim(s) + end + function export.lower(frame) + return mw.text.trim(frame.args[1]:lower()) + end + function export.upper(frame) + return mw.text.trim(frame.args[1]:upper()) + end + function export.words(frame) + local words = {} + for w in frame.args[1]:gmatch("%a+") do + words[#words + 1] = w + end + return table.concat(words, "|") + end + return export + """, + model="Scribunto", + ) + with misclassifying_locale(): + self.wtp.start_page("umanità") + for call, expected in [ + ("trim| umanità ", "umanità"), + ("trim|ム", "ム"), + ("lower|ÉGALITÉ À", "ÉgalitÉ À"), + ("upper|città é", "CITTà é"), + ("words|città à ma", "citt|ma"), + ]: + with self.subTest(call=call): + self.assertEqual( + self.wtp.expand("{{#invoke:test|" + call + "}}"), + expected, + ) + + def test_pattern_rewrite_keeps_other_syntax(self): + with always_wrapped(): + initialize_lua(self.wtp) + find = self.wtp.lua.eval( + "function(s, p) return table.concat({string.find(s, p)}, ',') end" + ) + for subject, pattern, expected in [ + ("a-b", "[%a-]+", "1,3"), # "-" after a class stays literal + ("x(a b)y", "%b()", "2,6"), + ("ab cd", "%f[%a]%a+$", "4,5"), + ("1]x", "[]%d]+", "1,2"), + ("a%b", "%%", "2,2"), + ("aa", "(%a)%1", "1,2,a"), + ("a.b", "a.b", "1,3"), + ("x\t\n", "%s+$", "2,3"), + ]: + with self.subTest(pattern=pattern): + self.assertEqual(find(subject, pattern), expected) + self.assertEqual( + self.wtp.lua.eval('(string.find("a%sb", "%s", 1, true))'), 2 + ) + with self.assertRaisesRegex(lupa.LuaError, "malformed pattern"): + self.wtp.lua.eval('string.find("a", "[%a")')