util.debug: Further fix to display locals in extended tracebacks
[prosody.git] / util / debug.lua
1 -- Variables ending with these names will not
2 -- have their values printed ('password' includes
3 -- 'new_password', etc.)
4 local censored_names = {
5         password = true;
6         passwd = true;
7         pass = true;
8         pwd = true;
9 };
10 local optimal_line_length = 65;
11
12 local termcolours = require "util.termcolours";
13 local getstring = termcolours.getstring;
14 local styles;
15 do
16         _ = termcolours.getstyle;
17         styles = {
18                 boundary_padding = _("bright");
19                 filename         = _("bright", "blue");
20                 level_num        = _("green");
21                 funcname         = _("yellow");
22                 location         = _("yellow");
23         };
24 end
25 module("debugx", package.seeall);
26
27 function get_locals_table(thread, level)
28         if not thread then
29                 level = level + 1; -- Skip this function itself
30         end
31         local locals = {};
32         for local_num = 1, math.huge do
33                 local name, value = debug.getlocal(thread, level, local_num);
34                 if not name then break; end
35                 table.insert(locals, { name = name, value = value });
36         end
37         return locals;
38 end
39
40 function get_upvalues_table(func)
41         local upvalues = {};
42         if func then
43                 for upvalue_num = 1, math.huge do
44                         local name, value = debug.getupvalue(func, upvalue_num);
45                         if not name then break; end
46                         table.insert(upvalues, { name = name, value = value });
47                 end
48         end
49         return upvalues;
50 end
51
52 function string_from_var_table(var_table, max_line_len, indent_str)
53         local var_string = {};
54         local col_pos = 0;
55         max_line_len = max_line_len or math.huge;
56         indent_str = "\n"..(indent_str or "");
57         for _, var in ipairs(var_table) do
58                 local name, value = var.name, var.value;
59                 if name:sub(1,1) ~= "(" then
60                         if type(value) == "string" then
61                                 if censored_names[name:match("%a+$")] then
62                                         value = "<hidden>";
63                                 else
64                                         value = ("%q"):format(value);
65                                 end
66                         else
67                                 value = tostring(value);
68                         end
69                         if #value > max_line_len then
70                                 value = value:sub(1, max_line_len-3).."…";
71                         end
72                         local str = ("%s = %s"):format(name, tostring(value));
73                         col_pos = col_pos + #str;
74                         if col_pos > max_line_len then
75                                 table.insert(var_string, indent_str);
76                                 col_pos = 0;
77                         end
78                         table.insert(var_string, str);
79                 end
80         end
81         if #var_string == 0 then
82                 return nil;
83         else
84                 return "{ "..table.concat(var_string, ", "):gsub(indent_str..", ", indent_str).." }";
85         end
86 end
87
88 function get_traceback_table(thread, start_level)
89         local levels = {};
90         for level = start_level, math.huge do
91                 local info;
92                 if thread then
93                         info = debug.getinfo(thread, level);
94                 else
95                         info = debug.getinfo(level+1);
96                 end
97                 if not info then break; end
98
99                 levels[(level-start_level)+1] = {
100                         level = level;
101                         info = info;
102                         locals = get_locals_table(thread, level+(thread and 0 or 1));
103                         upvalues = get_upvalues_table(info.func);
104                 };
105         end
106         return levels;
107 end
108
109 function traceback(...)
110         local ok, ret = pcall(_traceback, ...);
111         if not ok then
112                 return "Error in error handling: "..ret;
113         end
114         return ret;
115 end
116
117 local function build_source_boundary_marker(last_source_desc)
118         local padding = string.rep("-", math.floor(((optimal_line_length - 6) - #last_source_desc)/2));
119         return getstring(styles.boundary_padding, "v"..padding).." "..getstring(styles.filename, last_source_desc).." "..getstring(styles.boundary_padding, padding..(#last_source_desc%2==0 and "-v" or "v "));
120 end
121
122 function _traceback(thread, message, level)
123
124         -- Lua manual says: debug.traceback ([thread,] [message [, level]])
125         -- I fathom this to mean one of:
126         -- ()
127         -- (thread)
128         -- (message, level)
129         -- (thread, message, level)
130
131         if thread == nil then -- Defaults
132                 thread, message, level = coroutine.running(), message, level;
133         elseif type(thread) == "string" then
134                 thread, message, level = coroutine.running(), thread, message;
135         elseif type(thread) ~= "thread" then
136                 return nil; -- debug.traceback() does this
137         end
138
139         level = level or 0;
140
141         message = message and (message.."\n") or "";
142
143         -- +3 counts for this function, and the pcall() and wrapper above us, the +1... I don't know.
144         local levels = get_traceback_table(thread, level+(thread == nil and 4 or 0));
145
146         local last_source_desc;
147
148         local lines = {};
149         for nlevel, level in ipairs(levels) do
150                 local info = level.info;
151                 local line = "...";
152                 local func_type = info.namewhat.." ";
153                 local source_desc = (info.short_src == "[C]" and "C code") or info.short_src or "Unknown";
154                 if func_type == " " then func_type = ""; end;
155                 if info.short_src == "[C]" then
156                         line = "[ C ] "..func_type.."C function "..getstring(styles.location, (info.name and ("%q"):format(info.name) or "(unknown name)"));
157                 elseif info.what == "main" then
158                         line = "[Lua] "..getstring(styles.location, info.short_src.." line "..info.currentline);
159                 else
160                         local name = info.name or " ";
161                         if name ~= " " then
162                                 name = ("%q"):format(name);
163                         end
164                         if func_type == "global " or func_type == "local " then
165                                 func_type = func_type.."function ";
166                         end
167                         line = "[Lua] "..getstring(styles.location, info.short_src.." line "..info.currentline).." in "..func_type..getstring(styles.funcname, name).." (defined on line "..info.linedefined..")";
168                 end
169                 if source_desc ~= last_source_desc then -- Venturing into a new source, add marker for previous
170                         last_source_desc = source_desc;
171                         table.insert(lines, "\t "..build_source_boundary_marker(last_source_desc));
172                 end
173                 nlevel = nlevel-1;
174                 table.insert(lines, "\t"..(nlevel==0 and ">" or " ")..getstring(styles.level_num, "("..nlevel..") ")..line);
175                 local npadding = (" "):rep(#tostring(nlevel));
176                 if level.locals then
177                         local locals_str = string_from_var_table(level.locals, optimal_line_length, "\t            "..npadding);
178                         if locals_str then
179                                 table.insert(lines, "\t    "..npadding.."Locals: "..locals_str);
180                         end
181                 end
182                 local upvalues_str = string_from_var_table(level.upvalues, optimal_line_length, "\t            "..npadding);
183                 if upvalues_str then
184                         table.insert(lines, "\t    "..npadding.."Upvals: "..upvalues_str);
185                 end
186         end
187
188 --      table.insert(lines, "\t "..build_source_boundary_marker(last_source_desc));
189
190         return message.."stack traceback:\n"..table.concat(lines, "\n");
191 end
192
193 function use()
194         debug.traceback = traceback;
195 end
196
197 return _M;