Module:User:Surjection/manualfeed

From Wiktionary, the free dictionary
Jump to navigation Jump to search

This is a private module sandbox of Surjection, for their own experimentation. Items in this module may be added and removed at Surjection's discretion; do not rely on this module's stability.


local export = {}

local function created_in_error(reason)
	return "{{d|Created in error}} <!-- " .. reason .. " -->"
end

local function consume_now(x, c)
	local t = mw.ustring.sub(x, 1, #c)
	if t ~= c then error("Expected '" .. c .. "'") end
	return mw.ustring.sub(x, #c + 1)
end

local function consume(x, c)
	return consume_now(mw.ustring.gsub(x, "^%s+", ""), c)
end

local function parse_string(x)
	x = mw.ustring.gsub(x, "^%s+", "")
	local q = mw.ustring.sub(x, 1, 1)
	if q ~= '"' and q ~= "'" then
		error('Invalid quote')
	end
	
	local s = ""
	local i = 2
	while true do
		local i0, i1 = mw.ustring.find(x, "[\\" .. q .. "]", i)
		if not i0 then error("Unterminated string") end
		local n = mw.ustring.sub(x, i0, i1)
		s = s .. mw.ustring.sub(x, i, i0 - 1)
		if n == q then
			i = i1 + 1
			break
		elseif n == "\\" then
			n = mw.ustring.sub(x, i1 + 1, i1 + 1)
			if n == "\\" then
				s = s .. "\\"
			elseif n == "n" then
				s = s .. "\n"
			elseif n == q then
				s = s .. q
			else
				error("Unrecognized escape (symbol '" .. n .. "')")
			end
			i = i1 + 2
		else
			i = i1 + 1
		end
	end
	
	return s, mw.ustring.sub(x, i)
end

local function parse_tuple(x)
	local a, b
	x = consume(x, "(")
	a, x = parse_string(x)
	x = consume(x, ",")
	b, x = parse_string(x)
	x = consume(x, ")")
	return { a, b }
end

function export.feed(frame)
	local t = frame.args[1]
	if not t then return created_in_error("no |1=") end
	local ok, r = pcall(function () return parse_tuple(t) end)
	if not ok then return created_in_error("invalid tuple: " .. r) end
	t = r
	if not t then return created_in_error("invalid tuple") end
	if t[1] ~= mw.title.getCurrentTitle().text and not frame.args['t'] then return created_in_error("title mismatch") end
	return t[2]
end

return export