Fix wrong meta key in item meta on ItemStack construction
[oweals/minetest.git] / builtin / profiler / instrumentation.lua
1 --Minetest
2 --Copyright (C) 2016 T4im
3 --
4 --This program is free software; you can redistribute it and/or modify
5 --it under the terms of the GNU Lesser General Public License as published by
6 --the Free Software Foundation; either version 2.1 of the License, or
7 --(at your option) any later version.
8 --
9 --This program is distributed in the hope that it will be useful,
10 --but WITHOUT ANY WARRANTY; without even the implied warranty of
11 --MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12 --GNU Lesser General Public License for more details.
13 --
14 --You should have received a copy of the GNU Lesser General Public License along
15 --with this program; if not, write to the Free Software Foundation, Inc.,
16 --51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
17
18 local format, pairs, type = string.format, pairs, type
19 local core, get_current_modname = core, core.get_current_modname
20 local profiler, sampler = ...
21 local instrument_builtin = core.setting_getbool("instrument.builtin") or false
22
23 local register_functions = {
24         register_globalstep = 0,
25         register_playerevent = 0,
26         register_on_placenode = 0,
27         register_on_dignode = 0,
28         register_on_punchnode = 0,
29         register_on_generated = 0,
30         register_on_newplayer = 0,
31         register_on_dieplayer = 0,
32         register_on_respawnplayer = 0,
33         register_on_prejoinplayer = 0,
34         register_on_joinplayer = 0,
35         register_on_leaveplayer = 0,
36         register_on_cheat = 0,
37         register_on_chat_message = 0,
38         register_on_player_receive_fields = 0,
39         register_on_craft = 0,
40         register_craft_predict = 0,
41         register_on_protection_violation = 0,
42         register_on_item_eat = 0,
43         register_on_punchplayer = 0,
44         register_on_player_hpchange = 0,
45 }
46
47 ---
48 -- Create an unique instrument name.
49 -- Generate a missing label with a running index number.
50 --
51 local counts = {}
52 local function generate_name(def)
53         local class, label, func_name = def.class, def.label, def.func_name
54         if label then
55                 if class or func_name then
56                         return format("%s '%s' %s", class or "", label, func_name or ""):trim()
57                 end
58                 return format("%s", label):trim()
59         elseif label == false then
60                 return format("%s", class or func_name):trim()
61         end
62
63         local index_id = def.mod .. (class or func_name)
64         local index = counts[index_id] or 1
65         counts[index_id] = index + 1
66         return format("%s[%d] %s", class or func_name, index, class and func_name or ""):trim()
67 end
68
69 ---
70 -- Keep `measure` and the closure in `instrument` lean, as these, and their
71 -- directly called functions are the overhead that is caused by instrumentation.
72 --
73 local time, log = core.get_us_time, sampler.log
74 local function measure(modname, instrument_name, start, ...)
75         log(modname, instrument_name, time() - start)
76         return ...
77 end
78 --- Automatically instrument a function to measure and log to the sampler.
79 -- def = {
80 --              mod = "",
81 --              class = "",
82 --              func_name = "",
83 --              -- if nil, will create a label based on registration order
84 --              label = "" | false,
85 -- }
86 local function instrument(def)
87         if not def or not def.func then
88                 return
89         end
90         def.mod = def.mod or get_current_modname()
91         local modname = def.mod
92         local instrument_name = generate_name(def)
93         local func = def.func
94
95         if not instrument_builtin and modname == "*builtin*" then
96                 return func
97         end
98
99         return function(...)
100                 -- This tail-call allows passing all return values of `func`
101                 -- also called https://en.wikipedia.org/wiki/Continuation_passing_style
102                 -- Compared to table creation and unpacking it won't lose `nil` returns
103                 -- and is expected to be faster
104                 -- `measure` will be executed after time() and func(...)
105                 return measure(modname, instrument_name, time(), func(...))
106         end
107 end
108
109 local function can_be_called(func)
110         -- It has to be a function or callable table
111         return type(func) == "function" or
112                 ((type(func) == "table" or type(func) == "userdata") and
113                 getmetatable(func) and getmetatable(func).__call)
114 end
115
116 local function assert_can_be_called(func, func_name, level)
117         if not can_be_called(func) then
118                 -- Then throw an *helpful* error, by pointing on our caller instead of us.
119                 error(format("Invalid argument to %s. Expected function-like type instead of '%s'.", func_name, type(func)), level + 1)
120         end
121 end
122
123 ---
124 -- Wraps a registration function `func` in such a way,
125 -- that it will automatically instrument any callback function passed as first argument.
126 --
127 local function instrument_register(func, func_name)
128         local register_name = func_name:gsub("^register_", "", 1)
129         return function(callback, ...)
130                 assert_can_be_called(callback, func_name, 2)
131                 register_functions[func_name] = register_functions[func_name] + 1
132                 return func(instrument {
133                         func = callback,
134                         func_name = register_name
135                 }), ...
136         end
137 end
138
139 local function init_chatcommand()
140         if core.setting_getbool("instrument.chatcommand") or true then
141                 local orig_register_chatcommand = core.register_chatcommand
142                 core.register_chatcommand = function(cmd, def)
143                         def.func = instrument {
144                                 func = def.func,
145                                 label = "/" .. cmd,
146                         }
147                         orig_register_chatcommand(cmd, def)
148                 end
149         end
150 end
151
152 ---
153 -- Start instrumenting selected functions
154 --
155 local function init()
156         local is_set = core.setting_getbool
157         if is_set("instrument.entity") or true then
158                 -- Explicitly declare entity api-methods.
159                 -- Simple iteration would ignore lookup via __index.
160                 local entity_instrumentation = {
161                         "on_activate",
162                         "on_step",
163                         "on_punch",
164                         "rightclick",
165                         "get_staticdata",
166                 }
167                 -- Wrap register_entity() to instrument them on registration.
168                 local orig_register_entity = core.register_entity
169                 core.register_entity = function(name, prototype)
170                         local modname = get_current_modname()
171                         for _, func_name in pairs(entity_instrumentation) do
172                                 prototype[func_name] = instrument {
173                                         func = prototype[func_name],
174                                         mod = modname,
175                                         func_name = func_name,
176                                         label = prototype.label,
177                                 }
178                         end
179                         orig_register_entity(name,prototype)
180                 end
181         end
182
183         if is_set("instrument.abm") or true then
184                 -- Wrap register_abm() to automatically instrument abms.
185                 local orig_register_abm = core.register_abm
186                 core.register_abm = function(spec)
187                         spec.action = instrument {
188                                 func = spec.action,
189                                 class = "ABM",
190                                 label = spec.label,
191                         }
192                         orig_register_abm(spec)
193                 end
194         end
195
196         if is_set("instrument.lbm") or true then
197                 -- Wrap register_lbm() to automatically instrument lbms.
198                 local orig_register_lbm = core.register_lbm
199                 core.register_lbm = function(spec)
200                         spec.action = instrument {
201                                 func = spec.action,
202                                 class = "LBM",
203                                 label = spec.label or spec.name,
204                         }
205                         orig_register_lbm(spec)
206                 end
207         end
208
209         if is_set("instrument.global_callback") or true then
210                 for func_name, _ in pairs(register_functions) do
211                         core[func_name] = instrument_register(core[func_name], func_name)
212                 end
213         end
214
215         if is_set("instrument.profiler") or false then
216                 -- Measure overhead of instrumentation, but keep it down for functions
217                 -- So keep the `return` for better optimization.
218                 profiler.empty_instrument = instrument {
219                         func = function() return end,
220                         mod = "*profiler*",
221                         class = "Instrumentation overhead",
222                         label = false,
223                 }
224         end
225 end
226
227 return {
228         register_functions = register_functions,
229         instrument = instrument,
230         init = init,
231         init_chatcommand = init_chatcommand,
232 }