forked from FAUniv/clidebugger
-
Notifications
You must be signed in to change notification settings - Fork 0
/
debugger.lua
1746 lines (1487 loc) · 52.5 KB
/
debugger.lua
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
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
--{{{ history
--15/03/06 DCN Created based on RemDebug
--28/04/06 DCN Update for Lua 5.1
--01/06/06 DCN Fix command argument parsing
-- Add step/over N facility
-- Add trace lines facility
--05/06/06 DCN Add trace call/return facility
--06/06/06 DCN Make it behave when stepping through the creation of a coroutine
--06/06/06 DCN Integrate the simple debugger into the main one
--07/06/06 DCN Provide facility to step into coroutines
--13/06/06 DCN Fix bug that caused the function environment to get corrupted with the global one
--14/06/06 DCN Allow 'sloppy' file names when setting breakpoints
--04/08/06 DCN Allow for no space after command name
--11/08/06 DCN Use io.write not print
--30/08/06 DCN Allow access to array elements in 'dump'
--10/10/06 DCN Default to breakfile for all commands that require a filename and give '-'
--06/12/06 DCN Allow for punctuation characters in DUMP variable names
--03/01/07 DCN Add pause on/off facility
--19/06/07 DCN Allow for duff commands being typed in the debugger (thanks to [email protected])
-- Allow for case sensitive file systems (thanks to [email protected])
--04/08/09 DCN Add optional line count param to pause
--05/08/09 DCN Reset the debug hook in Pause() even if we think we're started
--30/09/09 DCN Re-jig to not use co-routines (makes debugging co-routines awkward)
--01/10/09 DCN Add ability to break on reaching any line in a file
--24/07/13 TWW Added code for emulating setfenv/getfenv in Lua 5.2 as per
-- http://lua-users.org/lists/lua-l/2010-06/msg00313.html
--25/07/13 TWW Copied Alex Parrill's fix for errors when tracing back across a C frame
-- (https://github.com/ColonelThirtyTwo/clidebugger, 26/01/12)
--25/07/13 DCN Allow for windows and unix file name conventions in has_breakpoint
--26/07/13 DCN Allow for \ being interpreted as an escape inside a [] pattern in 5.2
--10/02/14 CS Readline support
--}}}
--{{{ description
--A simple command line debug system for Lua written by Dave Nichols of
--Match-IT Limited. It's public domain software. Do with it as you wish.
--This debugger was inspired by:
-- RemDebug 1.0 Beta
-- Copyright Kepler Project 2005 (http://www.keplerproject.org/remdebug)
--Usage:
-- require('debugger') --load the debug library
-- pause(message) --start/resume a debug session
--An assert() failure will also invoke the debugger.
--}}}
local IsWindows = string.find(string.lower(os.getenv('OS') or ''),'^windows')
local coro_debugger
local events = { BREAK = 1, WATCH = 2, STEP = 3, SET = 4 }
local breakpoints = {}
local watches = {}
local step_into = false
local step_over = false
local step_lines = 0
local step_level = {main=0}
local stack_level = {main=0}
local trace_level = {main=0}
local trace_calls = false
local trace_returns = false
local trace_lines = false
local ret_file, ret_line, ret_name
local current_thread = 'main'
local started = false
local pause_off = false
local _g = _G
local cocreate, cowrap = coroutine.create, coroutine.wrap
local pausemsg = 'pause'
-- readline support if libclidebugger.so is available,
-- color support if running in a terminal, and
-- command shortcut support if the terminal is supported
local libreadline, readline, saveline, rlbinds = {}
local prompt = ">> "
local color = {
["black"] = '',
["white"] = '',
["green"] = '',
["blue" ] = '',
["red" ] = '',
["reset"] = ''
}
if pcall(function() libreadline = require('libclidebugger') end) then
readline = libreadline.readline
saveline = libreadline.add_history
if libreadline.isatty(io.stdout) then
color = {
["black"] = '\27[1;30m',
["white"] = '\27[1;37m',
["green"] = '\27[1;32m',
["blue" ] = '\27[1;34m',
["red" ] = '\27[1;31m',
["reset"] = '\27[0m'
}
prompt = libreadline.rlpsi .. color.blue .. libreadline.rlpei ..
prompt ..
libreadline.rlpsi .. color.reset .. libreadline.rlpei ..
'\0'
libreadline.setprompt(prompt)
if string.find(os.getenv("TERM"), "^[u]?rxvt") then
rlbinds = {
["help" ] = {["key"]="F1", ["rlbinding"]='"\\e[11~": "help\\n"'},
["step" ] = {["key"]="F7", ["rlbinding"]='"\\e[18~": "step\\n"'},
["dump" ] = {["key"]="ALT+F7", ["rlbinding"]='"\\e\\e[18~": "dump \\t"'},
["over" ] = {["key"]="F8", ["rlbinding"]='"\\e[19~": "over\\n"'},
["out" ] = {["key"]="SHIFT+F8", ["rlbinding"]='"\\e[32~": "out\\n"'},
["eval" ] = {["key"]="ALT+F8", ["rlbinding"]='"\\e\\e[19~": "eval \\t"'},
["listb"] = {["key"]="CTRL+F8", ["rlbinding"]='"\\e[19^": "listb\\n"'},
["run" ] = {["key"]="F9", ["rlbinding"]='"\\e[20~": "run\\n"'},
["show" ] = {["key"]="CTRL+RET", ["rlbinding"]='"\\eQ1;32~": "show\\n"'}
}
for _, v in pairs(rlbinds) do
libreadline.bindkey(v["rlbinding"])
end
end
end
else
readline = function(prompt)
io.write(prompt)
return io.read("*line")
end
saveline = function(s) end
end
--{{{ make Lua 5.2 compatible
if not setfenv then -- Lua 5.2
--[[
As far as I can see, the only missing detail of these functions (except
for occasional bugs) to achieve 100% compatibility is the case of
'getfenv' over a function that does not have an _ENV variable (that is,
it uses no globals).
We could use a weak table to keep the environments of these functions
when set by setfenv, but that still misses the case of a function
without _ENV that was not subjected to setfenv.
-- Roberto
]]--
setfenv = setfenv or function(f, t)
f = (type(f) == 'function' and f or debug.getinfo(f + 1, 'f').func)
local name
local up = 0
repeat
up = up + 1
name = debug.getupvalue(f, up)
until name == '_ENV' or name == nil
if name then
debug.upvaluejoin(f, up, function() return name end, 1) -- use unique upvalue
debug.setupvalue(f, up, t)
end
end
getfenv = getfenv or function(f)
f = (type(f) == 'function' and f or debug.getinfo(f + 1, 'f').func)
local name, val
local up = 0
repeat
up = up + 1
name, val = debug.getupvalue(f, up)
until name == '_ENV' or name == nil
return val
end
end
--}}}
--{{{ local hints -- command help
--The format in here is name=summary|description
local hints = {
pause = [[
pause(msg[,lines][,force]) -- start/resume a debugger session|
This can only be used in your code or from the console as a means to
start/resume a debug session.
If msg is given that is shown when the session starts/resumes. Useful to
give a context if you've instrumented your code with pause() statements.
If lines is given, the script pauses after that many lines, else it pauses
immediately.
If force is true, the pause function is honoured even if poff has been used.
This is useful when in an interactive console session to regain debugger
control.
]],
poff = [[
poff -- turn off pause() command|
This causes all pause() commands to be ignored. This is useful if you have
instrumented your code in a busy loop and want to continue normal execution
with no further interruption.
]],
pon = [[
pon -- turn on pause() command|
This re-instates honouring the pause() commands you may have instrumented
your code with.
]],
setb = [[
setb [line file] -- set a breakpoint to line/file|, line 0 means 'any'
If file is omitted or is "-" the breakpoint is set at the file for the
currently set level (see "set"). Execution pauses when this line is about
to be executed and the debugger session is re-activated.
The file can be given as the fully qualified name, partially qualified or
just the file name. E.g. if file is set as "myfile.lua", then whenever
execution reaches any file that ends with "myfile.lua" it will pause. If
no extension is given, any extension will do.
If the line is given as 0, then reaching any line in the file will do.
]],
delb = [[
delb [line file] -- removes a breakpoint|
If file is omitted or is "-" the breakpoint is removed for the file of the
currently set level (see "set").
]],
delallb = [[
delallb -- removes all breakpoints|
]],
setw = [[
setw <exp> -- adds a new watch expression|
The expression is evaluated before each line is executed. If the expression
yields true then execution is paused and the debugger session re-activated.
The expression is executed in the context of the line about to be executed.
]],
delw = [[
delw <index> -- removes the watch expression at index|
The index is that returned when the watch expression was set by setw.
]],
delallw = [[
delallw -- removes all watch expressions|
]],
run = [[
run -- run until next breakpoint or watch expression|
]],
step = [[
step [N] -- run next N lines, stepping into function calls|
If N is omitted, use 1.
]],
over = [[
over [N] -- run next N lines, stepping over function calls|
If N is omitted, use 1.
]],
out = [[
out [N] -- run until stepped out of N functions|
If N is omitted, use 1.
If you are inside a function, using "out 1" will run until you return
from that function to the caller.
]],
gotoo = [[
gotoo [line file] -- step to line in file|
This is equivalent to 'setb line file', followed by 'run', followed
by 'delb line file'.
]],
listb = [[
listb -- lists breakpoints|
]],
listw = [[
listw -- lists watch expressions|
]],
set = [[
set [level] -- set context to stack level, omitted=show|
If level is omitted it just prints the current level set.
This sets the current context to the level given. This affects the
context used for several other functions (e.g. vars). The possible
levels are those shown by trace.
]],
vars = [[
vars [depth] -- list context locals to depth, omitted=1|
If depth is omitted then uses 1.
Use a depth of 0 for the maximum.
Lists all non-nil local variables and all non-nil upvalues in the
currently set context. For variables that are tables, lists all fields
to the given depth.
]],
fenv = [[
fenv [depth] -- list context function env to depth, omitted=1|
If depth is omitted then uses 1.
Use a depth of 0 for the maximum.
Lists all function environment variables in the currently set context.
For variables that are tables, lists all fields to the given depth.
]],
glob = [[
glob [depth] -- list globals to depth, omitted=1|
If depth is omitted then uses 1.
Use a depth of 0 for the maximum.
Lists all global variables.
For variables that are tables, lists all fields to the given depth.
]],
ups = [[
ups -- list all the upvalue names|
These names will also be in the "vars" list unless their value is nil.
This provides a means to identify which vars are upvalues and which are
locals. If a name is both an upvalue and a local, the local value takes
precedance.
]],
locs = [[
locs -- list all the locals names|
These names will also be in the "vars" list unless their value is nil.
This provides a means to identify which vars are upvalues and which are
locals. If a name is both an upvalue and a local, the local value takes
precedance.
]],
dump = [[
dump <var> [depth] -- dump all fields of variable to depth|
If depth is omitted then uses 1.
Use a depth of 0 for the maximum.
Prints the value of <var> in the currently set context level. If <var>
is a table, lists all fields to the given depth. <var> can be just a
name, or name.field or name.# to any depth, e.g. t.1.f accesses field
'f' in array element 1 in table 't'.
Can also be called from a script as dump(var,depth). Therefore it is
a global function and thus visible with 'glob'.
]],
tron = [[
tron [crl] -- turn trace on for (c)alls, (r)eturns, (l)ines|
If no parameter is given then tracing is turned off.
When tracing is turned on a line is printed to the console for each
debug 'event' selected. c=function calls, r=function returns, l=lines.
]],
trace = [[
trace -- dumps a stack trace|
Format is [level] = file,line,name
The level is a candidate for use by the 'set' command.
]],
info = [[
info -- dumps the complete debug info captured|
Only useful as a diagnostic aid for the debugger itself. This information
can be HUGE as it dumps all variables to the maximum depth, so be careful.
]],
show = [[
show line file X Y -- show X lines before and Y after line in file|
If line is omitted or is '-' then the current set context line is used.
If file is omitted or is '-' then the current set context file is used.
If file is not fully qualified and cannot be opened as specified, then
a search for the file in the package[path] is performed using the usual
"require" searching rules. If no file extension is given, .lua is used.
Prints the lines from the source file around the given line.
]],
exit = [[
exit -- exits debugger, re-start it using pause()|
]],
help = [[
help [command] -- show this list or help for command|
]],
eval = [[
eval <statement> -- execute a statement in the current context|
The statement can be anything that is legal in the context, including
assignments. Such assignments affect the context and will be in force
immediately. Any results returned are printed. Use '=' as a short-hand
for 'return', e.g. "=func(arg)" will call 'func' with 'arg' and print
the results, and "=var" will just print the value of 'var'.
]],
what = [[
what <func> -- show where <func> is defined (if known)|
]],
}
--}}}
-- This function is called back by libclidebugger's do_completion() which is
-- itself called back by the readline library in order to complete input.
if package.loaded.libclidebugger then
libreadline._set(
function (word, line, startpos, endpos)
local matches = {}
-- Helper function registering possible completion words, verifying matches
local function add(value)
value = tostring(value)
if value:match("^" .. word) then matches[#matches + 1] = value end
end
-- Append type-indicating character to an identifier
local function postfix(value)
local t = type(value)
if t == 'function' or (getmetatable(value) or {}).__call then return '('
elseif t == 'table' and #value > 0 then return '['
elseif t == 'table' then return '.'
else return ' '
end
end
-- Add completions for debugger commands
local function add_command_list(str)
for c, _ in pairs(hints) do add(c .. ' ') end
end
-- Add completions for the execution environment's entries
local function add_eval_env(what)
local eval_env = __getevalenv__()
for k in pairs(eval_env.__LOCALS__) do
-- The type of locals cannot be easily inferred here, so no postfix() call.
-- Alike, local functions will not become completion candidates for the 'what' command.
-- In order to do so, __LOCALS__ must be enriched with type information.
-- Another option is to find and use the respective local's "stackframe", see, e.g., the 'set' command.
if what ~= "funconly" then
add(eval_env.__LOCALS__[k])
end
end
for k in pairs(eval_env.__UPVALUES__) do
if what == "funconly" then
if type(eval_env.__UPVALUES__[k]) == 'function' or (getmetatable(eval_env.__UPVALUES__[k]) or {}).__call then
add(eval_env.__UPVALUES__[k])
end
else
if eval_env.__UPVALUES__[k] == "_ENV" then add("_ENV.")
else add(eval_env.__UPVALUES__[k] .. postfix(_ENV[eval_env.__UPVALUES__[k]])) end
end
end
for k in pairs(eval_env.__GLOBALS__) do
if k ~= "__getevalenv__" and k ~= "__gettraceinfo__" then
if what == "funconly" then
if type(eval_env.__GLOBALS__[k]) == 'function' or (getmetatable(eval_env.__GLOBALS__[k]) or {}).__call then
add(k)
end
else
add(k .. postfix(eval_env.__GLOBALS__[k]))
end
end
end
end
-- Add completions for the stack level used in 'set' command
local function add_stack_level()
io.write('\n')
for level, ar in ipairs(__gettraceinfo__()) do
io.write('['..level..']\t'..(ar.name or ar.what)..' in '..ar.short_src..':'..ar.currentline..'\n')
add(level)
end
if #matches < 2 then libreadline.redisplay() end
end
-- Add completions for the list of watches
local function add_watch_index()
io.write('\n')
for i, v in pairs(watches) do
io.write("Watch exp. " .. i .. ": " .. v.exp..'\n')
add(i)
end
if #matches < 2 then libreadline.redisplay() end
end
-- Simplify the input line, by removing
-- literal strings,
-- full table constructors, and
-- balanced groups of parentheses.
-- Returns
-- the sub-expression preceding the word,
-- the separator item ( '.', ':', '[', '(' ), and
-- the current string in case of an unfinished string literal.
local function simplify_expression(expr)
-- Replace annoying sequences \' and \" inside literal strings
expr = expr:gsub("\\(['\"])", function (c)
return string.format("\\%03d", string.byte(c))
end)
local curstring
-- Remove (finished and unfinished) literal strings
while true do
local idx1, _, equals = expr:find("%[(=*)%[")
local idx2, _, sign = expr:find("(['\"])")
if idx1 == nil and idx2 == nil then
break
end
local idx, startpat, endpat
if (idx1 or math.huge) < (idx2 or math.huge) then
idx, startpat, endpat = idx1, "%[" .. equals .. "%[", "%]" .. equals .. "%]"
else
idx, startpat, endpat = idx2, sign, sign
end
if expr:sub(idx):find("^" .. startpat .. ".-" .. endpat) then
expr = expr:gsub(startpat .. "(.-)" .. endpat, " STRING ")
else
expr = expr:gsub(startpat .. "(.*)", function (str)
curstring = str
return "(CURSTRING "
end)
end
end
expr = expr:gsub("%b()"," PAREN ") -- Remove groups of parentheses
expr = expr:gsub("%b{}"," TABLE ") -- Remove table constructors
-- Avoid two consecutive words without operator
expr = expr:gsub("(%w)%s+(%w)","%1|%2")
expr = expr:gsub("%s+", "") -- Remove now useless spaces
-- This main regular expression looks for table indexes and function calls.
return curstring, expr:match("([%.%w%[%]_]-)([:%.%[%(])" .. word .. "$")
end
-- Main completion dispatcher function
local function complete_command(linetoken, currentwordnr, dbgcommand)
if dbgcommand == nil then
add_command_list()
else
if dbgcommand == "delb" then
for i, v in pairs(breakpoints) do
for ii, vv in pairs(v) do
add(i..' '..ii)
end
end
elseif dbgcommand == "setb" or dbgcommand == "gotoo" then
if currentwordnr == 2 then matches = {"0", "1", "2", "..."}
elseif currentwordnr > 2 then libreadline.filecompl() end
elseif dbgcommand == "setw" or dbgcommand == "eval" or dbgcommand == "dump" then
str, expr, sep = simplify_expression(line:sub(6, endpos))
if expr and expr ~= "" then
local token = loadstring("return " .. expr)
if token then
token = token()
local ttoken = type(token)
if ttoken == 'table' and (sep == '.' or sep == ':') then
for k, v in pairs(token) do
if type(k) == 'string' and (sep ~= ':' or type(v) == "function") then
add(k..postfix(v))
end
end
elseif sep == '[' and ttoken == 'table' then
for k in pairs(token) do
if type(k) == 'number' then
add(k .. "]")
end
end
if word ~= "" then add_eval_env() end
end
end
end
if #matches == 0 then add_eval_env() end
elseif dbgcommand == "set" then
if currentwordnr == 2 then add_stack_level() end
elseif dbgcommand == "delw" then
if currentwordnr == 2 then add_watch_index() end
elseif dbgcommand == "tron" then
if currentwordnr == 2 then matches = {'c', 'r', 'l'} end
elseif dbgcommand == "show" then
if currentwordnr == 2 then matches = {'0', '1', '2', '3', '-'}
elseif currentwordnr > 2 then libreadline.filecompl() end
elseif dbgcommand == "help" then
if currentwordnr == 2 then add_command_list() end
elseif dbgcommand == "what" then
if currentwordnr == 2 then add_eval_env("funconly") end
end
end
end
libreadline.luacompl()
local dbgcommand = nil
local linetoken = {}
line = line:find('^%s*$') and '' or line:match('^%s*(.*%S)')
for token in line:gmatch('%S+') do
linetoken[#linetoken+1] = token
if dbgcommand == nil and hints[token] then dbgcommand = token end
end
complete_command(linetoken, (#word == 0 and #linetoken+1 or #linetoken), dbgcommand)
return matches
end
)
end
--{{{ local function getinfo(level,field)
--like debug.getinfo but copes with no activation record at the given level
--and knows how to get 'field'. 'field' can be the name of any of the
--activation record fields or any of the 'what' names or nil for everything.
--only valid when using the stack level to get info, not a function name.
local function getinfo(level,field)
level = level + 1 --to get to the same relative level as the caller
if not field then return debug.getinfo(level) end
local what
if field == 'name' or field == 'namewhat' then
what = 'n'
elseif field == 'what' or field == 'source' or field == 'linedefined' or field == 'lastlinedefined' or field == 'short_src' then
what = 'S'
elseif field == 'currentline' then
what = 'l'
elseif field == 'nups' then
what = 'u'
elseif field == 'func' then
what = 'f'
else
return debug.getinfo(level,field)
end
local ar = debug.getinfo(level,what)
if ar then return ar[field] else return nil end
end
--}}}
--{{{ local function indented( level, ... )
local function indented( level, ... )
io.write( string.rep(' ',level), table.concat({...}), '\n' )
end
--}}}
--{{{ local function dumpval( level, name, value, limit )
local dumpvisited
local function dumpval( level, name, value, limit )
local index
if type(name) == 'number' then
index = string.format('[%d] = ',name)
elseif type(name) == 'string'
and (name == '__VARSLEVEL__' or name == '__ENVIRONMENT__' or name == '__GLOBALS__' or name == '__UPVALUES__' or name == '__LOCALS__') then
--ignore these, they are debugger generated
return
elseif type(name) == 'string' and string.find(name,'^[_%a][_.%w]*$') then
index = name ..' = '
else
index = string.format('[%q] = ',tostring(name))
end
if type(value) == 'table' then
if dumpvisited[value] then
indented( level, index, string.format('ref%q;',dumpvisited[value]) )
else
dumpvisited[value] = tostring(value)
if (limit or 0) > 0 and level+1 >= limit then
indented( level, index, dumpvisited[value] )
else
indented( level, index, '{ -- ', dumpvisited[value] )
for n,v in pairs(value) do
dumpval( level+1, n, v, limit )
end
indented( level, '};' )
end
end
else
if type(value) == 'string' then
if string.len(value) > 40 then
indented( level, index, '[[', value, ']];' )
else
indented( level, index, string.format('%q',value), ';' )
end
else
indented( level, index, tostring(value), ';' )
end
end
end
--}}}
--{{{ local function dumpvar( value, limit, name )
local function dumpvar( value, limit, name )
dumpvisited = {}
dumpval( 0, name or tostring(value), value, limit )
end
--}}}
--{{{ local function show(breakfile,breakline,file,line,before,after)
-- show +/-N lines of a file around line M highlighting the current breakpoint line if any
local function show(breakfile,breakline,file,line,before,after)
local function basename(filename)
return IsWindows
and string.gsub(filename, '[^\\]*\\', '')
or string.gsub(filename, '[^/]*/', '')
end
line = tonumber(line or 1)
before = tonumber(before or 10)
after = tonumber(after or before)
breakfile = basename(breakfile)
if not string.find(file, '%.') then file = file..'.lua' end
local f = io.open(file, 'r')
if not f then
-- look for a matching file in the package path
local path = package.path or LUA_PATH or ''
for c in string.gmatch(path, "[^;]+") do
local c = string.gsub(c, "%?%.lua", file)
f = io.open(c, 'r')
if f then
file = c
break
end
end
if not f then
io.write('Cannot find '..file..'\n')
return
end
end
local _, _, code = f:read(0)
if code == 21 then
io.write(file..' is a directory!\n')
f:close()
return
end
file = basename(file)
local i = 0
for l in f:lines() do
i = i + 1
if i >= (line-before) then
if i > (line+after) then break end
if i == breakline and file == breakfile then
io.write(color.black..i..color.green..'***\t'..color.reset..l..'\n')
else
io.write(color.black..i..color.reset..'\t'..l..'\n')
end
end
end
f:close()
end
--}}}
--{{{ local function tracestack(l)
local function gi( i )
return function() i=i+1 return debug.getinfo(i),i end
end
local function gl( level, j )
return function() j=j+1 return debug.getlocal( level, j ) end
end
local function gu( func, k )
return function() k=k+1 return debug.getupvalue( func, k ) end
end
local traceinfo
-- return the local traceinfo to use it in readline completion
function __gettraceinfo__()
return traceinfo
end
local function tracestack(l)
local l = l + 1 --NB: +1 to get level relative to caller
traceinfo = {}
traceinfo.pausemsg = pausemsg
for ar,i in gi(l) do
table.insert( traceinfo, ar )
if ar.what ~= 'C' then
local names = {}
local values = {}
for n,v in gl(i,0) do
if string.sub(n,1,1) ~= '(' then --ignore internal control variables
table.insert( names, n )
table.insert( values, v )
end
end
if #names > 0 then
ar.lnames = names
ar.lvalues = values
end
end
if ar.func then
local names = {}
local values = {}
for n,v in gu(ar.func,0) do
if string.sub(n,1,1) ~= '(' then --ignore internal control variables
table.insert( names, n )
table.insert( values, v )
end
end
if #names > 0 then
ar.unames = names
ar.uvalues = values
end
end
end
end
--}}}
--{{{ local function trace()
local function trace(set)
local mark
for level,ar in ipairs(traceinfo) do
if level == set then
mark = color.green..'***'..color.reset
else
mark = ''
end
io.write('['..level..']'..mark..'\t'..(ar.name or ar.what)..' in '..ar.short_src..':'..ar.currentline..'\n')
end
end
--}}}
--{{{ local function info()
local function info() dumpvar( traceinfo, 0, 'traceinfo' ) end
--}}}
--{{{ local function set_breakpoint(file, line, once)
local function set_breakpoint(file, line, once)
if not breakpoints[line] then
breakpoints[line] = {}
end
if once then
breakpoints[line][file] = 1
else
breakpoints[line][file] = true
end
end
--}}}
--{{{ local function remove_breakpoint(file, line)
local function remove_breakpoint(file, line)
if breakpoints[line] then
breakpoints[line][file] = nil
end
end
--}}}
--{{{ local function has_breakpoint(file, line)
--allow for 'sloppy' file names
--search for file and all variations walking up its directory hierachy
--ditto for the file with no extension
--a breakpoint can be permenant or once only, if once only its removed
--after detection here, these are used for temporary breakpoints in the
--debugger loop when executing the 'gotoo' command
--a breakpoint on line 0 of a file means any line in that file
local function has_breakpoint(file, line)
local isLine = breakpoints[line]
local isZero = breakpoints[0]
if not isLine and not isZero then return false end
local noext = string.gsub(file,"(%..-)$",'',1)
if noext == file then noext = nil end
while file do
if isLine and isLine[file] then
if isLine[file] == 1 then isLine[file] = nil end
return true
end
if isZero and isZero[file] then
if isZero[file] == 1 then isZero[file] = nil end
return true
end
if IsWindows then
file = string.match(file,"[:/\\](.+)$")
else
file = string.match(file,"[:/](.+)$")
end
end
while noext do
if isLine and isLine[noext] then
if isLine[noext] == 1 then isLine[noext] = nil end
return true
end
if isZero and isZero[noext] then
if isZero[noext] == 1 then isZero[noext] = nil end
return true
end
if IsWindows then
noext = string.match(noext,"[:/\\](.+)$")
else
noext = string.match(noext,"[:/](.+)$")
end
end
return false
end
--}}}
--{{{ local function capture_vars(ref,level,line)
local function capture_vars(ref,level,line)
--get vars, file and line for the given level relative to debug_hook offset by ref
local lvl = ref + level --NB: This includes an offset of +1 for the call to here
--{{{ capture variables
local ar = debug.getinfo(lvl, "f")
if not ar then return {},'?',0 end
local vars = {__UPVALUES__={}, __LOCALS__={}}
local i
local func = ar.func
if func then
i = 1
while true do
local name, value = debug.getupvalue(func, i)
if not name then break end
if string.sub(name,1,1) ~= '(' then --NB: ignoring internal control variables
vars[name] = value
vars.__UPVALUES__[i] = name
end
i = i + 1
end
vars.__ENVIRONMENT__ = getfenv(func)
end
vars.__GLOBALS__ = getfenv(0)
i = 1
while true do
local name, value = debug.getlocal(lvl, i)
if not name then break end
if string.sub(name,1,1) ~= '(' then --NB: ignoring internal control variables
vars[name] = value
vars.__LOCALS__[i] = name
end
i = i + 1
end
vars.__VARSLEVEL__ = level
if func then
--NB: Do not do this until finished filling the vars table
setmetatable(vars, { __index = getfenv(func), __newindex = getfenv(func) })
end
--NB: Do not read or write the vars table anymore else the metatable functions will get invoked!
--}}}
local file = getinfo(lvl, "source")
if string.find(file, "@") == 1 then
file = string.sub(file, 2)
end
if IsWindows then file = string.lower(file) end
if not line then
line = getinfo(lvl, "currentline")
end
return vars,file,line
end
--}}}
--{{{ local function restore_vars(ref,vars)
local function restore_vars(ref,vars)
if type(vars) ~= 'table' then return end