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