summaryrefslogtreecommitdiffstats
path: root/daemon/lua/krprint.lua
blob: dd25a9b4983428fb7845410bedbdbebe73cee636 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
-- SPDX-License-Identifier: GPL-3.0-or-later
local base_class = {
	cur_indent = 0,
}

-- shared constructor: use as serializer_class:new()
function base_class.new(class, on_unrepresentable)
	on_unrepresentable = on_unrepresentable or 'comment'
	if on_unrepresentable ~= 'comment'
		and on_unrepresentable ~= 'error' then
		error('unsupported val2expr on_unrepresentable option '
			.. tostring(on_unrepresentable))
	end
	local inst = {}
	inst.on_unrepresentable = on_unrepresentable
	inst.done = {}
	inst.tab_key_path = {}
	setmetatable(inst, class.__inst_mt)
	return inst
end

-- format comment with leading/ending whitespace if needed
function base_class.format_note(_, note, ws_prefix, ws_suffix)
	if note == nil then
		return ''
	else
		return string.format('%s--[[ %s ]]%s',
			ws_prefix or '', note, ws_suffix or '')
	end
end

function base_class.indent_head(self)
	return string.rep(' ', self.cur_indent)
end

function base_class.indent_inc(self)
	self.cur_indent = self.cur_indent + self.indent_step
end

function base_class.indent_dec(self)
	self.cur_indent = self.cur_indent - self.indent_step
end

function base_class._fallback(self, val)
	if self.on_unrepresentable == 'comment' then
		return 'nil', string.format('missing %s', val)
	elseif self.on_unrepresentable == 'error' then
		local key_path_msg
		if #self.tab_key_path > 0 then
			local str_key_path = {}
			for _, key in ipairs(self.tab_key_path) do
				table.insert(str_key_path,
					string.format('%s %s', type(key), self:string(tostring(key))))
			end
			local key_path = '[' .. table.concat(str_key_path, '][') .. ']'
			key_path_msg = string.format(' (found at [%s])', key_path)
		else
			key_path_msg = ''
		end
		error(string.format('cannot serialize type %s%s', type(val), key_path_msg), 2)
	end
end

function base_class.val2expr(self, val)
	local val_type = type(val)
	local val_repr = self[val_type]
	if val_repr then
		return val_repr(self, val)
	else
		return self:_fallback(val)
	end
end

-- "nil" is a Lua keyword so assignment below is workaround to create
-- function base_class.nil(self, val)
base_class['nil'] = function(_, val)
	assert(type(val) == 'nil')
	return 'nil'
end

function base_class.number(_, val)
	assert(type(val) == 'number')
	if val == math.huge then
		return 'math.huge'
	elseif val == -math.huge then
		return '-math.huge'
	elseif tostring(val) == 'nan' then
		return 'tonumber(\'nan\')'
	else
		return string.format("%.60f", val)
	end
end

function base_class.char_is_printable(_, c)
	-- ASCII (from space to ~) and not ' or \
	return (c >= 0x20 and c < 0x7f)
		and c ~= 0x27 and c ~= 0x5C
end

function base_class.string(self, val)
	assert(type(val) == 'string')
	local chars = {'\''}
	for i = 1, #val do
		local c = string.byte(val, i)
		if self:char_is_printable(c) then
			table.insert(chars, string.char(c))
		else
			table.insert(chars, string.format('\\%03d', c))
		end
	end
	table.insert(chars, '\'')
	return table.concat(chars)
end

function base_class.boolean(_, val)
	assert(type(val) == 'boolean')
	return tostring(val)
end

local function ordered_iter(unordered_tt)
	local keys = {}
	for k in pairs(unordered_tt) do
		table.insert(keys, k)
	end
	table.sort(keys,
		function (a, b)
			if type(a) ~= type(b) then
				return type(a) < type(b)
			end
			if type(a) == 'number' then
				return a < b
			else
				return tostring(a) < tostring(b)
			end
		end)
	local i = 0
	return function()
		i = i + 1
		if keys[i] ~= nil then
			return keys[i], unordered_tt[keys[i]]
		end
	end
end

function base_class.table(self, tab)
	assert(type(tab) == 'table')
	if self.done[tab] then
		error('cyclic reference', 0)
	end
	self.done[tab] = true

	local items = {'{'}
	local previdx = 0
	self:indent_inc()
	for idx, val in ordered_iter(tab) do
		local errors, valok, valexpr, valnote, idxok, idxexpr, idxnote
		errors = {}
		-- push current index onto key path stack to make it available to sub-printers
		table.insert(self.tab_key_path, idx)

		valok, valexpr, valnote = pcall(self.val2expr, self, val)
		if not valok then
			table.insert(errors, string.format('value: %s', valexpr))
		end

		local addidx
		if previdx and type(idx) == 'number' and idx - 1 == previdx then
			-- monotonic sequence, do not print key
			previdx = idx
			addidx = false
		else
			-- end of monotonic sequence
			-- from now on print keys as well
			previdx = nil
			addidx = true
		end

		if addidx then
			idxok, idxexpr, idxnote = pcall(self.val2expr, self, idx)
			if not idxok or idxexpr == 'nil' then
				table.insert(errors, string.format('key: not serializable', idxexpr))
			end
		end

		local item = ''
		if #errors == 0 then
			-- finally serialize one [key=]?value expression
			local indent = self:indent_head()
			local note
			if addidx then
				note = self:format_note(idxnote, nil, self.key_val_sep)
				item = string.format('%s%s[%s]%s=%s',
					indent, note,
					idxexpr, self.key_val_sep, self.key_val_sep)
				indent = ''
			end
			note = self:format_note(valnote, nil, self.item_sep)
			item = item .. string.format('%s%s%s,', indent, note, valexpr)
		else
			local errmsg = string.format('cannot print %s = %s (%s)',
				self:string(tostring(idx)),
				self:string(tostring(val)),
				table.concat(errors, ', '))
			if self.on_unrepresentable == 'error' then
				error(errmsg, 0)
			else
				errmsg = string.format('--[[ missing %s ]]', errmsg)
				item = errmsg
			end
		end
		table.insert(items, item)
		table.remove(self.tab_key_path) -- pop current index from key path stack
	end  -- one key+value
	self:indent_dec()
	table.insert(items, self:indent_head() .. '}')
	return table.concat(items, self.item_sep), string.format('%s follows', tab)
end

-- machine readable variant, cannot represent all types and repeated references to a table
local serializer_class = {
	indent_step = 0,
	item_sep = ' ',
	key_val_sep = ' ',
	__inst_mt = {}
}
-- inheritance form base class (for :new())
setmetatable(serializer_class, { __index = base_class })
-- class instances with following metatable inherit all class members
serializer_class.__inst_mt.__index = serializer_class

local function static_serializer(val, on_unrepresentable)
	local inst = serializer_class:new(on_unrepresentable)
	local expr, note = inst:val2expr(val)
	return string.format('%s%s', inst:format_note(note, nil, inst.item_sep), expr)
	end

-- human friendly variant, not stable and not intended for machine consumption
local pprinter_class = {
	indent_step = 4,
	item_sep = '\n',
	key_val_sep = ' ',
	__inst_mt = {},
}

-- should be always empty because pretty-printer has fallback for all types
function pprinter_class.format_note()
	return ''
end

function pprinter_class._fallback(self, val)
	if self.on_unrepresentable == 'error' then
		base_class._fallback(self, val)
	end
	return tostring(val)
end

function pprinter_class.char_is_printable(_, c)
	-- ASCII (from space to ~) + tab or newline
	-- and not ' or \
	return ((c >= 0x20 and c < 0x7f)
		or c == 0x09 or c == 0x0A)
		and c ~= 0x27 and c ~= 0x5C
end

-- "function" is a Lua keyword so assignment below is workaround to create
-- function pprinter_class.function(self, f)
pprinter_class['function'] = function(self, f)
-- thanks to AnandA777 from StackOverflow! Function funcsign is adapted version of
-- https://stackoverflow.com/questions/51095022/inspect-function-signature-in-lua-5-1
	assert(type(f) == 'function', "bad argument #1 to 'funcsign' (function expected)")
	local debuginfo = debug.getinfo(f)
	local func_args = {}
	local args_str
	if debuginfo.what == 'C' then  -- names N/A
		args_str = '(?)'
		goto add_name
	end

	pcall(function()
		local oldhook
		local delay = 2
		local function hook()
			delay = delay - 1
			if delay == 0 then  -- call this only for the introspected function
				-- stack depth 2 is the introspected function
				for i = 1, debuginfo.nparams do
					local k = debug.getlocal(2, i)
					table.insert(func_args, k)
				end
				if debuginfo.isvararg then
					table.insert(func_args, "...")
				end
				debug.sethook(oldhook)
				error('aborting the call to introspected function')
			end
		end
		oldhook = debug.sethook(hook, "c")  -- invoke hook() on function call
		f(unpack({}))  -- huh?
	end)
	args_str = "(" .. table.concat(func_args, ", ") .. ")"
	::add_name::
	local name
	if #self.tab_key_path > 0 then
		name = string.format('function %s', self.tab_key_path[#self.tab_key_path])
	else
		name = 'function '
	end
	return string.format('%s%s: %s', name, args_str, string.sub(tostring(f), 11))
end

-- default tostring method is better suited for human-intended output
function pprinter_class.number(_, number)
	return tostring(number)
end

local function deserialize_lua(serial)
	assert(type(serial) == 'string')
	local deserial_func = loadstring('return ' .. serial)
	if type(deserial_func) ~= 'function' then
		panic('input is not a valid Lua expression')
	end
	return deserial_func()
end

setmetatable(pprinter_class, { __index = base_class })
pprinter_class.__inst_mt.__index = pprinter_class

local function static_pprint(val, on_unrepresentable)
	local inst = pprinter_class:new(on_unrepresentable)
	local expr, note = inst:val2expr(val)
	return string.format('%s%s', inst:format_note(note, nil, inst.item_sep), expr)
end

local M = {
	serialize_lua = static_serializer,
	deserialize_lua = deserialize_lua,
	pprint = static_pprint
}

return M