tools/generate_format_spec.lua
changeset 12038 ee94ac51b2dd
child 12041 82f6a0b0a425
equal deleted inserted replaced
12037:161f8268c4b3 12038:ee94ac51b2dd
       
     1 local format = require"util.format".format;
       
     2 local dump = require "util.serialization".new("oneline")
       
     3 local types = {
       
     4 	"nil";
       
     5 	"boolean";
       
     6 	"number";
       
     7 	"string";
       
     8 	"function";
       
     9 	-- "userdata";
       
    10 	"thread";
       
    11 	"table";
       
    12 };
       
    13 local example_values = {
       
    14 	["nil"] = { n = 1; nil };
       
    15 	["boolean"] = { true; false };
       
    16 	["number"] = { 97, -12345, 1.5; 73786976294838206464, math.huge, 2147483647 };
       
    17 	["string"] = { "hello", "foo \1\2\3 bar", "nödåtgärd", string.sub("nödåtgärd", 1, -4) };
       
    18 	["function"] = { function() end };
       
    19 	-- ["userdata"] = {};
       
    20 	["thread"] = { coroutine.create(function() end) };
       
    21 	["table"] = { {} };
       
    22 };
       
    23 local example_strings = setmetatable({
       
    24 	["nil"] = { "nil" };
       
    25 	["function"] = { "function() end" };
       
    26 	["number"] = { "97", "-12345", "1.5"; "73786976294838206464", "math.huge", "2147483647" };
       
    27 	["thread"] = { "coroutine.create(function() end)" };
       
    28 }, { __index = function() return {} end });
       
    29 for _, lua_type in ipairs(types) do
       
    30 	print(string.format("\t\tdescribe(\"%s\", function ()", lua_type));
       
    31 	local examples = example_values[lua_type];
       
    32 	for fmt in ("cdiouxXaAeEfgGqs"):gmatch(".") do
       
    33 		print(string.format("\t\t\tdescribe(\"to %%%s\", function ()", fmt));
       
    34 		print("\t\t\t\tit(\"works\", function ()");
       
    35 		for i=1, examples.n or #examples do
       
    36 			local example = examples[i];
       
    37 			if not tostring(example):match("%w+: 0[xX]%x+") then
       
    38 				print(string.format("\t\t\t\t\tassert.equal(%q, format(%q, %s))", format("%"..fmt, example), "%" .. fmt, example_strings[lua_type][i] or dump(example)));
       
    39 			else
       
    40 				print(string.format("\t\t\t\t\tassert.matches(\"[%s: 0[xX]%%x+]\", format(%q, %s))", lua_type, "%" .. fmt, example_strings[lua_type][i] or dump(example)));
       
    41 			end
       
    42 		end
       
    43 		print("\t\t\t\tend);");
       
    44 		print("\t\t\tend);");
       
    45 		print()
       
    46 	end
       
    47 	print("\t\tend);");
       
    48 	print()
       
    49 end