src: remove some warnings and do some cleaning
[nit.git] / src / interpreter / debugger.nit
1 # This file is part of NIT ( http://www.nitlanguage.org ).
2 #
3 # Copyright 2013 Lucas Bajolet <lucas.bajolet@gmail.com>
4 #
5 # Licensed under the Apache License, Version 2.0 (the "License");
6 # you may not use this file except in compliance with the License.
7 # You may obtain a copy of the License at
8 #
9 # http://www.apache.org/licenses/LICENSE-2.0
10 #
11 # Unless required by applicable law or agreed to in writing, software
12 # distributed under the License is distributed on an "AS IS" BASIS,
13 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 # See the License for the specific language governing permissions and
15 # limitations under the License.
16
17 # Debugging of a nit program using the NaiveInterpreter
18 module debugger
19
20 import breakpoint
21 intrude import naive_interpreter
22 import nitx
23 intrude import semantize::local_var_init
24 intrude import semantize::scope
25 intrude import toolcontext
26 private import parser_util
27
28 redef class Model
29 # Cleans the model to remove a module and what it defines when semantic analysis fails on injected code
30 private fun try_remove_module(m: MModule): Bool
31 do
32 var index = -1
33 for i in [0 .. mmodules.length[ do
34 if mmodules[i] == m then
35 index = i
36 break
37 end
38 end
39 if index == -1 then return false
40 var mmodule = mmodules[index]
41 mmodules.remove_at(index)
42 for classdef in mmodule.mclassdefs do
43 var mclass = classdef.mclass
44 for i in [0 .. mclass.mclassdefs.length[ do
45 if mclass.mclassdefs[i] == classdef then
46 index = i
47 break
48 end
49 end
50 mclass.mclassdefs.remove_at(index)
51 var propdefs = classdef.mpropdefs
52 for propdef in propdefs do
53 var prop = propdef.mproperty
54 for i in [0..prop.mpropdefs.length[ do
55 if prop.mpropdefs[i] == propdef then
56 index = i
57 break
58 end
59 end
60 prop.mpropdefs.remove_at(index)
61 end
62 end
63 return true
64 end
65 end
66
67 redef class ScopeVisitor
68
69 redef init(toolcontext)
70 do
71 super
72 if toolcontext.dbg != null then
73 var localvars = toolcontext.dbg.frame.map
74 for i in localvars.keys do
75 scopes.first.variables[i.to_s] = i
76 end
77 end
78 end
79
80 end
81
82 redef class LocalVarInitVisitor
83 redef fun mark_is_unset(node: AExpr, variable: nullable Variable)
84 do
85 super
86 if toolcontext.dbg != null then
87 var varname = variable.to_s
88 var instmap = toolcontext.dbg.frame.map
89 for i in instmap.keys do
90 if i.to_s == varname then
91 mark_is_set(node, variable)
92 end
93 end
94 end
95 end
96
97 end
98
99 redef class ToolContext
100 private var dbg: nullable Debugger = null
101
102 private var had_error: Bool = false
103
104 redef fun check_errors
105 do
106 if dbg == null then
107 super
108 else
109 if messages.length > 0 then
110 message_sorter.sort(messages)
111
112 for m in messages do
113 if m.text.search("Warning") == null then had_error = true
114 sys.stderr.write("{m.to_color_string}\n")
115 end
116 end
117
118 messages.clear
119 end
120 end
121
122 # -d
123 var opt_debugger_mode = new OptionBool("Launches the target program with the debugger attached to it", "-d")
124 # -c
125 var opt_debugger_autorun = new OptionBool("Launches the target program with the interpreter, such as when the program fails, the debugging prompt is summoned", "-c")
126
127 redef init
128 do
129 super
130 self.option_context.add_option(self.opt_debugger_mode)
131 self.option_context.add_option(self.opt_debugger_autorun)
132 end
133 end
134
135 redef class ModelBuilder
136 # Execute the program from the entry point (Sys::main) of the `mainmodule`
137 # `arguments` are the command-line arguments in order
138 # REQUIRE that:
139 # 1. the AST is fully loaded.
140 # 2. the model is fully built.
141 # 3. the instructions are fully analysed.
142 fun run_debugger(mainmodule: MModule, arguments: Array[String])
143 do
144 var time0 = get_time
145 self.toolcontext.info("*** START INTERPRETING ***", 1)
146
147 var interpreter = new Debugger(self, mainmodule, arguments)
148
149 interpreter.start(mainmodule)
150
151 var time1 = get_time
152 self.toolcontext.info("*** END INTERPRETING: {time1-time0} ***", 2)
153 end
154
155 fun run_debugger_autorun(mainmodule: MModule, arguments: Array[String])
156 do
157 var time0 = get_time
158 self.toolcontext.info("*** START INTERPRETING ***", 1)
159
160 var interpreter = new Debugger(self, mainmodule, arguments)
161 interpreter.autocontinue = true
162
163 interpreter.start(mainmodule)
164
165 var time1 = get_time
166 self.toolcontext.info("*** END INTERPRETING: {time1-time0} ***", 2)
167 end
168 end
169
170 # The class extending `NaiveInterpreter` by adding debugging methods
171 class Debugger
172 super NaiveInterpreter
173
174 # Keeps the frame count in memory to find when to stop
175 # and launch the command prompt after a step out call
176 var step_stack_count = 1
177
178 # Triggers a step over an instruction in a nit program
179 var stop_after_step_over_trigger = true
180
181 # Triggers a step out of an instruction
182 var stop_after_step_out_trigger= false
183
184 # Triggers a step in a instruction (enters a function
185 # if the instruction is a function call)
186 var step_in_trigger = false
187
188 # HashMap containing the breakpoints bound to a file
189 var breakpoints = new HashMap[String, HashSet[Breakpoint]]
190
191 # Contains the current file
192 var curr_file = ""
193
194 # Aliases hashmap (maps an alias to a variable name)
195 var aliases = new HashMap[String, String]
196
197 # Set containing all the traced variables and their related frame
198 private var traces = new HashSet[TraceObject]
199
200 # Map containing all the positions for the positions of the arguments traced
201 # In a function call
202 private var fun_call_arguments_positions = new HashMap[Int, TraceObject]
203
204 # Triggers the remapping of a trace object in the local context after a function call
205 var aftermath = false
206
207 # Used to prevent the case when the body of the function called is empty
208 # If it is not, then, the remapping won't be happening
209 var frame_count_aftermath = 1
210
211 # Auto continues the execution until the end or until an error is encountered
212 var autocontinue = false
213
214 #######################################################################
215 ## Execution of statement function ##
216 #######################################################################
217
218 # Main loop, every call to a debug command is done here
219 redef fun stmt(n: nullable AExpr)
220 do
221 if n == null then return
222
223 var frame = self.frame
224 var old = frame.current_node
225 frame.current_node = n
226
227 if sys.stdin.poll_in then process_debug_command(gets)
228
229 if not self.autocontinue then
230 if not n isa ABlockExpr then
231 steps_fun_call(n)
232
233 breakpoint_check(n)
234
235 check_funcall_and_traced_args(n)
236
237 remap(n)
238
239 check_if_vars_are_traced(n)
240 end
241 end
242
243 n.stmt(self)
244 frame.current_node = old
245 end
246
247 # Does the same as an usual send, except it will modify the call chain on the first call when injecting code at Runtime using the debugger.
248 # Instead of creating a pristine Frame, it will copy the actual values of the frame, and re-inject them after execution in the current context.
249 fun rt_send(mproperty: MMethod, args: Array[Instance]): nullable Instance
250 do
251 var recv = args.first
252 var mtype = recv.mtype
253 var ret = send_commons(mproperty, args, mtype)
254 if ret != null then return ret
255 var propdef = mproperty.lookup_first_definition(self.mainmodule, mtype)
256 return self.rt_call(propdef, args)
257 end
258
259 # Same as a regular call but for a runtime injected module
260 #
261 fun rt_call(mpropdef: MMethodDef, args: Array[Instance]): nullable Instance
262 do
263 args = call_commons(mpropdef, args)
264 return rt_call_without_varargs(mpropdef, args)
265 end
266
267 # Common code to call and this function
268 #
269 # Call only executes the variadic part, this avoids
270 # double encapsulation of variadic parameters into an Array
271 fun rt_call_without_varargs(mpropdef: MMethodDef, args: Array[Instance]): nullable Instance
272 do
273 if self.modelbuilder.toolcontext.opt_discover_call_trace.value and not self.discover_call_trace.has(mpropdef) then
274 self.discover_call_trace.add mpropdef
275 self.debug("Discovered {mpropdef}")
276 end
277 assert args.length == mpropdef.msignature.arity + 1 else debug("Invalid arity for {mpropdef}. {args.length} arguments given.")
278
279 # Look for the AST node that implements the property
280 var mproperty = mpropdef.mproperty
281 if self.modelbuilder.mpropdef2npropdef.has_key(mpropdef) then
282 var npropdef = self.modelbuilder.mpropdef2npropdef[mpropdef]
283 self.parameter_check(npropdef, mpropdef, args)
284 if npropdef isa AMethPropdef then
285 return npropdef.rt_call(self, mpropdef, args)
286 else
287 print "Error, invalid propdef to call at runtime !"
288 return null
289 end
290 else if mproperty.name == "init" then
291 var nclassdef = self.modelbuilder.mclassdef2nclassdef[mpropdef.mclassdef]
292 self.parameter_check(nclassdef, mpropdef, args)
293 return nclassdef.call(self, mpropdef, args)
294 else
295 fatal("Fatal Error: method {mpropdef} not found in the AST")
296 abort
297 end
298 end
299
300 # Evaluates dynamically a snippet of Nit code
301 # `nit_code` : Nit code to be executed
302 fun eval(nit_code: String)
303 do
304 var local_toolctx = modelbuilder.toolcontext
305 local_toolctx.dbg = self
306 var e = local_toolctx.parse_something(nit_code)
307 if e isa ABlockExpr then
308 nit_code = "module rt_module\n" + nit_code
309 e = local_toolctx.parse_something(nit_code)
310 end
311 if e isa AExpr then
312 nit_code = "module rt_module\nprint " + nit_code
313 e = local_toolctx.parse_something(nit_code)
314 end
315 if e isa AModule then
316 local_toolctx.had_error = false
317 modelbuilder.load_rt_module(self.mainmodule, e, "rt_module")
318 local_toolctx.run_phases([e])
319 if local_toolctx.had_error then
320 modelbuilder.model.try_remove_module(e.mmodule.as(not null))
321 local_toolctx.dbg = null
322 return
323 end
324 var mmod = e.mmodule
325 if mmod != null then
326 self.mainmodule = mmod
327 var sys_type = mmod.sys_type
328 if sys_type == null then
329 print "Fatal error, cannot find Class Sys !\nAborting"
330 abort
331 end
332 var mobj = new MutableInstance(sys_type)
333 init_instance(mobj)
334 var initprop = mmod.try_get_primitive_method("init", sys_type.mclass)
335 if initprop != null then
336 self.send(initprop, [mobj])
337 end
338 var mainprop = mmod.try_get_primitive_method("run", sys_type.mclass) or else
339 mmod.try_get_primitive_method("main", sys_type.mclass)
340 if mainprop != null then
341 self.rt_send(mainprop, [mobj])
342 end
343 else
344 print "Error while loading_rt_module"
345 end
346 else
347 print "Error when parsing, e = {e.class_name}"
348 end
349 local_toolctx.dbg = null
350 end
351
352 # Encpasulates the behaviour for step over/out
353 private fun steps_fun_call(n: AExpr)
354 do
355 if self.stop_after_step_over_trigger then
356 if self.frames.length <= self.step_stack_count then
357 n.debug("Execute stmt {n.to_s}")
358 while read_cmd do end
359 end
360 else if self.stop_after_step_out_trigger then
361 if frames.length < self.step_stack_count then
362 n.debug("Execute stmt {n.to_s}")
363 while read_cmd do end
364 end
365 else if step_in_trigger then
366 n.debug("Execute stmt {n.to_s}")
367 while read_cmd do end
368 end
369 end
370
371 # Checks if a breakpoint is encountered, and launches the debugging prompt if true
372 private fun breakpoint_check(n: AExpr)
373 do
374 var currFileNameSplit = self.frame.current_node.location.file.filename.to_s.split_with("/")
375
376 self.curr_file = currFileNameSplit[currFileNameSplit.length-1]
377
378 var breakpoint = find_breakpoint(curr_file, n.location.line_start)
379
380 if breakpoints.keys.has(curr_file) and breakpoint != null then
381
382 breakpoint.check_in
383
384 if not breakpoint.is_valid
385 then
386 remove_breakpoint(curr_file, n.location.line_start)
387 end
388
389 n.debug("Execute stmt {n.to_s}")
390 while read_cmd do end
391 end
392 end
393
394 # Check if a variable of current expression is traced
395 # Then prints and/or breaks for command prompt
396 private fun check_if_vars_are_traced(n: AExpr)
397 do
398 var identifiers_in_instruction = get_identifiers_in_current_instruction(n.location.text)
399
400 for i in identifiers_in_instruction do
401 for j in self.traces do
402 if j.is_variable_traced_in_frame(i, frame) then
403 n.debug("Traced variable {i} used")
404 if j.break_on_encounter then while read_cmd do end
405 break
406 end
407 end
408 end
409 end
410
411 # Function remapping all the traced objects to match their name in the local context
412 private fun remap(n: AExpr)
413 do
414 if self.aftermath then
415
416 # Trace every argument variable pre-specified
417 if self.frame_count_aftermath < frames.length and fun_call_arguments_positions.length > 0 then
418
419 var ids_in_fun_def = get_identifiers_in_current_instruction(get_function_arguments(frame.mpropdef.location.text))
420
421 for i in fun_call_arguments_positions.keys do
422 self.fun_call_arguments_positions[i].add_frame_variable(frame, ids_in_fun_def[i])
423 end
424 end
425
426 self.aftermath = false
427 end
428 end
429
430 # If the current instruction is a function call
431 # We analyse its signature and the position of traced arguments if the call
432 # For future remapping when inside the function
433 private fun check_funcall_and_traced_args(n: AExpr) do
434 # If we have a function call, we need to see if any of the arguments is traced (including the caller)
435 # if it is, next time we face an instruction, we'll trace the local version on the traced variable in the next frame
436 if n isa ACallExpr then
437 self.aftermath = true
438 self.frame_count_aftermath = frames.length
439 fun_call_arguments_positions.clear
440 var fun_arguments = get_identifiers_in_current_instruction(get_function_arguments(n.location.text))
441
442 for i in self.traces do
443 for j in [0 .. fun_arguments.length - 1] do
444 if i.is_variable_traced_in_frame(fun_arguments[j],frame) then
445 fun_call_arguments_positions[j] = i
446 end
447 end
448 end
449 end
450 end
451
452 #######################################################################
453 ## Processing commands functions ##
454 #######################################################################
455
456 fun read_cmd: Bool
457 do
458 printn "> "
459 return process_debug_command(gets)
460 end
461
462 # Takes a user command as a parameter
463 #
464 # Returns a boolean value, representing whether or not to
465 # continue reading commands from the console input
466 fun process_debug_command(command:String): Bool
467 do
468 # Step-out command
469 if command == "finish"
470 then
471 return step_out
472 # Step-in command
473 else if command == "s"
474 then
475 return step_in
476 # Step-over command
477 else if command == "n" then
478 return step_over
479 # Opens a new NitIndex prompt on current model
480 else if command == "nitx" then
481 new NitIndex.with_infos(modelbuilder, self.mainmodule).prompt
482 return true
483 # Continues execution until the end
484 else if command == "c" then
485 return continue_exec
486 else if command == "nit" then
487 printn "$~> "
488 command = gets
489 var nit_buf = new FlatBuffer
490 while not command == ":q" do
491 nit_buf.append(command)
492 nit_buf.append("\n")
493 printn "$~> "
494 command = gets
495 end
496 step_in
497 eval(nit_buf.to_s)
498 else if command == "quit" then
499 exit(0)
500 else if command == "abort" then
501 print stack_trace
502 exit(0)
503 else
504 var parts_of_command = command.split_with(' ')
505 # Shows the value of a variable in the current frame
506 if parts_of_command[0] == "p" or parts_of_command[0] == "print" then
507 print_command(parts_of_command)
508 # Places a breakpoint on line x of file y
509 else if parts_of_command[0] == "break" or parts_of_command[0] == "b"
510 then
511 process_place_break_fun(parts_of_command)
512 # Places a temporary breakpoint on line x of file y
513 else if parts_of_command[0] == "tbreak" and (parts_of_command.length == 2 or parts_of_command.length == 3)
514 then
515 process_place_tbreak_fun(parts_of_command)
516 # Removes a breakpoint on line x of file y
517 else if parts_of_command[0] == "d" or parts_of_command[0] == "delete" then
518 process_remove_break_fun(parts_of_command)
519 # Sets an alias for a variable
520 else if parts_of_command.length == 3 and parts_of_command[1] == "as"
521 then
522 add_alias(parts_of_command[0], parts_of_command[2])
523 # Modifies the value of a variable in the current frame
524 else if parts_of_command.length >= 3 and parts_of_command[1] == "=" then
525 process_mod_function(parts_of_command)
526 # Traces the modifications on a variable
527 else if parts_of_command.length >= 2 and parts_of_command[0] == "trace" then
528 process_trace_command(parts_of_command)
529 # Untraces the modifications on a variable
530 else if parts_of_command.length == 2 and parts_of_command[0] == "untrace" then
531 process_untrace_command(parts_of_command)
532 else
533 print "Unknown command \"{command}\""
534 end
535 end
536 return true
537 end
538
539 #######################################################################
540 ## Processing specific command functions ##
541 #######################################################################
542
543 # Sets the flags to step-over an instruction in the current file
544 fun step_over: Bool
545 do
546 self.step_stack_count = frames.length
547 self.stop_after_step_over_trigger = true
548 self.stop_after_step_out_trigger = false
549 self.step_in_trigger = false
550 return false
551 end
552
553 #Sets the flags to step-out of a function
554 fun step_out: Bool
555 do
556 self.stop_after_step_over_trigger = false
557 self.stop_after_step_out_trigger = true
558 self.step_in_trigger = false
559 self.step_stack_count = frames.length
560 return false
561 end
562
563 # Sets the flags to step-in an instruction
564 fun step_in: Bool
565 do
566 self.step_in_trigger = true
567 self.stop_after_step_over_trigger = false
568 self.stop_after_step_out_trigger = false
569 return false
570 end
571
572 # Sets the flags to continue execution
573 fun continue_exec: Bool
574 do
575 self.stop_after_step_over_trigger = false
576 self.stop_after_step_out_trigger = false
577 self.step_in_trigger = false
578 return false
579 end
580
581 # Prints the demanded variable in the command
582 #
583 # The name of the variable in in position 1 of the array 'parts_of_command'
584 fun print_command(parts_of_command: Array[String])
585 do
586 if parts_of_command[1] == "*" then
587 var map_of_instances = frame.map
588
589 var self_var = seek_variable("self", frame)
590 print "self: {self_var.to_s}"
591
592 for instance in map_of_instances.keys do
593 print "{instance.to_s}: {map_of_instances[instance].to_s}"
594 end
595 else if parts_of_command[1] == "stack" then
596 print self.stack_trace
597 else if parts_of_command[1].chars.has('[') and parts_of_command[1].chars.has(']') then
598 process_array_command(parts_of_command)
599 else
600 var instance = seek_variable(get_real_variable_name(parts_of_command[1]), frame)
601
602 if instance != null
603 then
604 print_instance(instance)
605 else
606 print "Cannot find variable {parts_of_command[1]}"
607 end
608 end
609 end
610
611 # Processes the input string to know where to put a breakpoint
612 fun process_place_break_fun(parts_of_command: Array[String])
613 do
614 var bp = get_breakpoint_from_command(parts_of_command)
615 if bp != null then
616 place_breakpoint(bp)
617 end
618 end
619
620 # Returns a breakpoint containing the informations stored in the command
621 fun get_breakpoint_from_command(parts_of_command: Array[String]): nullable Breakpoint
622 do
623 if parts_of_command[1].is_numeric then
624 return new Breakpoint(parts_of_command[1].to_i, curr_file)
625 else if parts_of_command.length >= 3 and parts_of_command[2].is_numeric then
626 return new Breakpoint(parts_of_command[2].to_i, parts_of_command[1])
627 else
628 return null
629 end
630 end
631
632 # Processes the command of removing a breakpoint on specified line and file
633 fun process_remove_break_fun(parts_of_command: Array[String])
634 do
635 if parts_of_command[1].is_numeric then
636 remove_breakpoint(self.curr_file, parts_of_command[1].to_i)
637 else if parts_of_command.length >= 3 and parts_of_command[2].is_numeric then
638 remove_breakpoint(parts_of_command[1], parts_of_command[2].to_i)
639 end
640 end
641
642 # Processes an array print command
643 fun process_array_command(parts_of_command: Array[String])
644 do
645 var index_of_first_brace = parts_of_command[1].chars.index_of('[')
646 var variable_name = get_real_variable_name(parts_of_command[1].substring(0,index_of_first_brace))
647 var braces = parts_of_command[1].substring_from(index_of_first_brace)
648
649 var indexes = remove_braces(braces)
650
651 var index_array = new Array[Array[Int]]
652
653 if indexes != null then
654 for index in indexes do
655 var temp_indexes_array = process_index(index)
656 if temp_indexes_array != null then
657 index_array.push(temp_indexes_array)
658 #print index_array.last
659 end
660 end
661 end
662
663 var instance = seek_variable(variable_name, frame)
664
665 if instance != null then
666 print_nested_collection(instance, index_array, 0, variable_name, "")
667 else
668 print "Cannot find variable {variable_name}"
669 end
670 end
671
672 # Processes the modification function to modify a variable dynamically
673 #
674 # Command of type variable = value
675 fun process_mod_function(parts_of_command: Array[String])
676 do
677 parts_of_command[0] = get_real_variable_name(parts_of_command[0])
678 var parts_of_variable = parts_of_command[0].split_with(".")
679
680 if parts_of_variable.length > 1 then
681 var last_part = parts_of_variable.pop
682 var first_part = parts_of_command[0].substring(0,parts_of_command[0].length - last_part.length - 1)
683 var papa = seek_variable(first_part, frame)
684
685 if papa != null and papa isa MutableInstance then
686 var attribute = get_attribute_in_mutable_instance(papa, last_part)
687
688 if attribute != null then
689 modify_argument_of_complex_type(papa, attribute, parts_of_command[2])
690 end
691 end
692 else
693 var target = seek_variable(parts_of_variable[0], frame)
694 if target != null then
695 modify_in_frame(target, parts_of_command[2])
696 end
697 end
698 end
699
700 # Processes the untrace variable command
701 #
702 # Command pattern : "untrace variable"
703 fun process_untrace_command(parts_of_command: Array[String])
704 do
705 var variable_name = get_real_variable_name(parts_of_command[1])
706 if untrace_variable(variable_name) then
707 print "Untraced variable {parts_of_command[1]}"
708 else
709 print "{parts_of_command[1]} is not traced"
710 end
711 end
712
713 # Processes the trace variable command
714 #
715 # Command pattern : "trace variable [break/print]"
716 fun process_trace_command(parts_of_command: Array[String])
717 do
718 var variable_name = get_real_variable_name(parts_of_command[1])
719 var breaker:Bool
720
721 if seek_variable(variable_name, frame) == null then
722 print "Cannot find a variable called {parts_of_command[1]}"
723 return
724 end
725
726 if parts_of_command.length == 3 then
727 if parts_of_command[2] == "break" then
728 breaker = true
729 else
730 breaker = false
731 end
732 else
733 breaker = false
734 end
735
736 trace_variable(variable_name, breaker)
737
738 print "Successfully tracing {parts_of_command[1]}"
739 end
740
741 #######################################################################
742 ## Trace Management functions ##
743 #######################################################################
744
745 # Effectively untraces the variable called *variable_name*
746 #
747 # Returns true if the variable exists, false otherwise
748 private fun untrace_variable(variable_name: String): Bool
749 do
750 var to_remove: nullable TraceObject = null
751 for i in self.traces do
752 if i.is_variable_traced_in_frame(variable_name, frame) then
753 to_remove = i
754 end
755 end
756
757 if to_remove != null then
758 self.traces.remove(to_remove)
759 return true
760 else
761 return false
762 end
763 end
764
765 # Effectively traces the variable *variable_name* either in print or break mode depending on the value of breaker (break if true, print if false)
766 #
767 private fun trace_variable(variable_name: String, breaker: Bool)
768 do
769 for i in self.traces do
770 if i.is_variable_traced_in_frame(variable_name, frame) then
771 print "This variable is already traced"
772 return
773 end
774 end
775
776 var trace_object: TraceObject
777
778 if breaker then
779 trace_object = new TraceObject(true)
780 else
781 trace_object = new TraceObject(false)
782 end
783
784 # We trace the current variable found for the current frame
785 trace_object.add_frame_variable(self.frame, variable_name)
786
787 var position_of_variable_in_arguments = get_position_of_variable_in_arguments(frame, variable_name)
788
789 # Start parsing the frames starting with the parent of the current one, until the highest
790 # When the variable traced is declared locally, the loop stops
791 for i in [1 .. frames.length-1] do
792
793 # If the variable was reported to be an argument of the previous frame
794 if position_of_variable_in_arguments != -1 then
795
796 var local_name = get_identifiers_in_current_instruction(get_function_arguments(frames[i].current_node.location.text))[position_of_variable_in_arguments]
797
798 position_of_variable_in_arguments = get_position_of_variable_in_arguments(frames[i], local_name)
799
800 trace_object.add_frame_variable(frames[i], local_name)
801 else
802 break
803 end
804 end
805
806 self.traces.add(trace_object)
807 end
808
809 # If the variable *variable_name* is an argument of the function being executed in the frame *frame*
810 # The function returns its position in the arguments
811 # Else, it returns -1
812 private fun get_position_of_variable_in_arguments(frame: Frame, variable_name: String): Int
813 do
814 var identifiers = get_identifiers_in_current_instruction(get_function_arguments(frame.mpropdef.location.text))
815 for i in [0 .. identifiers.length-1] do
816 # If the current traced variable is an argument of the current function, we trace its parent (at least)
817 if identifiers[i] == variable_name then return i
818 end
819 return -1
820 end
821
822 # Gets all the identifiers of an instruction (uses the rules of Nit as of Mar 05 2013)
823 #
824 fun get_identifiers_in_current_instruction(instruction: Text): Array[String]
825 do
826 var result_array = new Array[String]
827 var instruction_buffer = new FlatBuffer
828
829 var trigger_char_escape = false
830 var trigger_string_escape = false
831
832 for i in instruction.chars do
833 if trigger_char_escape then
834 if i == '\'' then trigger_char_escape = false
835 else if trigger_string_escape then
836 if i == '{' then
837 trigger_string_escape = false
838 else if i == '\"' then trigger_string_escape = false
839 else
840 if i.is_alphanumeric or i == '_' then
841 instruction_buffer.add(i)
842 else if i == '.' then
843 if instruction_buffer.is_numeric or (instruction_buffer.chars[0] >= 'A' and instruction_buffer.chars[0] <= 'Z') then
844 instruction_buffer.clear
845 else
846 result_array.push(instruction_buffer.to_s)
847 instruction_buffer.add(i)
848 end
849 else if i == '\'' then
850 trigger_char_escape = true
851 else if i == '\"' then
852 trigger_string_escape = true
853 else if i == '}' then
854 trigger_string_escape = true
855 else
856 if instruction_buffer.length > 0 and not instruction_buffer.is_numeric and not (instruction_buffer.chars[0] >= 'A' and instruction_buffer.chars[0] <= 'Z') then result_array.push(instruction_buffer.to_s)
857 instruction_buffer.clear
858 end
859 end
860 end
861
862 if instruction_buffer.length > 0 and not instruction_buffer.is_numeric and not (instruction_buffer.chars[0] >= 'A' and instruction_buffer.chars[0] <= 'Z') then result_array.push(instruction_buffer.to_s)
863
864 return result_array
865 end
866
867 # Takes a function call or declaration and strips all but the arguments
868 #
869 fun get_function_arguments(function: Text): String
870 do
871 var buf = new FlatBuffer
872 var trigger_copy = false
873
874 for i in function.chars do
875 if i == ')' then break
876 if trigger_copy then buf.add(i)
877 if i == '(' then trigger_copy = true
878 end
879
880 return buf.to_s
881 end
882
883 #######################################################################
884 ## Alias management functions ##
885 #######################################################################
886
887 # Adds a new alias to the tables
888 fun add_alias(var_represented: String, alias: String)
889 do
890 self.aliases[alias] = var_represented
891 end
892
893 # Gets the real name of a variable hidden by an alias
894 fun get_variable_name_by_alias(alias: String): nullable String
895 do
896 if self.aliases.keys.has(alias) then
897 return self.aliases[alias]
898 end
899
900 return null
901 end
902
903 # Gets the variable named by name, whether it is an alias or not
904 fun get_real_variable_name(name: String): String
905 do
906 var explode_string = name.split_with(".")
907 var final_string = new FlatBuffer
908 for i in explode_string do
909 var alias_resolved = get_variable_name_by_alias(i)
910 if alias_resolved != null then
911 final_string.append(get_real_variable_name(alias_resolved))
912 else
913 final_string.append(i)
914 end
915 final_string.append(".")
916 end
917
918 return final_string.substring(0,final_string.length-1).to_s
919 end
920
921 #######################################################################
922 ## Print functions ##
923 #######################################################################
924
925 # Prints an object instance and its attributes if it has some
926 #
927 # If it is a primitive type, its value is directly printed
928 fun print_instance(instance: Instance)
929 do
930 if instance isa MutableInstance then
931 print "\{"
932 print "\ttype : {instance},"
933
934 printn("\t")
935
936 print instance.attributes.join(",\n\t"," : ")
937
938 print "\}"
939 else
940 print "{instance}"
941 end
942 end
943
944 # Prints the attributes demanded in a SequenceRead
945 # Used recursively to print nested collections
946 fun print_nested_collection(instance: Instance, indexes: Array[Array[Int]], depth: Int, variable_name: String, depth_string: String)
947 do
948 var collection: nullable SequenceRead[Object] = null
949 var real_collection_length: nullable Int = null
950
951 if instance isa MutableInstance then
952 real_collection_length = get_collection_instance_real_length(instance)
953 collection = get_primary_collection(instance)
954 end
955
956 if collection != null and real_collection_length != null then
957 for i in indexes[depth] do
958 if i >= 0 and i < real_collection_length then
959 if depth == indexes.length-1 then
960 print "{variable_name}{depth_string}[{i}] = {collection[i]}"
961 else
962 var item_i = collection[i]
963
964 if item_i isa MutableInstance then
965 print_nested_collection(item_i, indexes, depth+1, variable_name, depth_string+"[{i}]")
966 else
967 print "The item at {variable_name}{depth_string}[{i}] is not a collection"
968 print item_i
969 end
970 end
971 else
972 print "Out of bounds exception : i = {i} and collection_length = {real_collection_length.to_s}"
973
974 if i < 0 then
975 continue
976 else if i >= real_collection_length then
977 break
978 end
979 end
980 end
981 else
982 if collection == null then
983 print "Cannot find {variable_name}{depth_string}"
984 else if real_collection_length != null then
985 print "Cannot find attribute length in {instance}"
986 else
987 print "Unknown error."
988 abort
989 end
990 end
991 end
992
993 #######################################################################
994 ## Variable Exploration functions ##
995 #######################################################################
996
997 # Seeks a variable from the current frame called 'variable_path', can introspect complex objects using function get_variable_in_mutable_instance
998 private fun seek_variable(variable_path: String, frame: Frame): nullable Instance
999 do
1000 var full_variable = variable_path.split_with(".")
1001
1002 var full_variable_iterator = full_variable.iterator
1003
1004 var first_instance = get_variable_in_frame(full_variable_iterator.item, frame)
1005
1006 if first_instance == null then return null
1007
1008 if full_variable.length <= 1 then return first_instance
1009
1010 full_variable_iterator.next
1011
1012 if not (first_instance isa MutableInstance and full_variable_iterator.is_ok) then return null
1013
1014 return get_variable_in_mutable_instance(first_instance, full_variable_iterator)
1015 end
1016
1017 # Gets a variable 'variable_name' contained in the frame 'frame'
1018 private fun get_variable_in_frame(variable_name: String, frame: Frame): nullable Instance
1019 do
1020 if variable_name == "self" then
1021 if frame.arguments.length >= 1 then return frame.arguments.first
1022 end
1023
1024 var map_of_instances = frame.map
1025
1026 for key in map_of_instances.keys do
1027 if key.to_s == variable_name then
1028 return map_of_instances[key]
1029 end
1030 end
1031
1032 return null
1033 end
1034
1035 # Gets an attribute 'attribute_name' contained in variable 'variable'
1036 fun get_attribute_in_mutable_instance(variable: MutableInstance, attribute_name: String): nullable MAttribute
1037 do
1038 var map_of_attributes = variable.attributes
1039
1040 for key in map_of_attributes.keys do
1041 if key.to_s.substring_from(1) == attribute_name then
1042 return key
1043 end
1044 end
1045
1046 return null
1047 end
1048
1049 # Recursive function, returns the variable described by 'total_chain'
1050 fun get_variable_in_mutable_instance(variable: MutableInstance, iterator: Iterator[String]): nullable Instance
1051 do
1052 var attribute = get_attribute_in_mutable_instance(variable, iterator.item)
1053
1054 if attribute == null then return null
1055
1056 iterator.next
1057
1058 if iterator.is_ok then
1059 var new_variable = variable.attributes[attribute]
1060 if new_variable isa MutableInstance then
1061 return get_variable_in_mutable_instance(new_variable, iterator)
1062 else
1063 return null
1064 end
1065 else
1066 return variable.attributes[attribute]
1067 end
1068 end
1069
1070 #######################################################################
1071 ## Array exploring functions ##
1072 #######################################################################
1073
1074 # Gets the length of a collection
1075 # Used by the debugger, else if we call Collection.length, it returns the capacity instead
1076 fun get_collection_instance_real_length(collection: MutableInstance): nullable Int
1077 do
1078 var collection_length_attribute = get_attribute_in_mutable_instance(collection, "length")
1079
1080 if collection_length_attribute != null then
1081 var primitive_length_instance = collection.attributes[collection_length_attribute]
1082 if primitive_length_instance isa PrimitiveInstance[Int] then
1083 return primitive_length_instance.val
1084 end
1085 end
1086
1087 return null
1088 end
1089
1090 # Processes the indexes of a print array call
1091 # Returns an array containing all the indexes demanded
1092 fun process_index(index_string: String): nullable Array[Int]
1093 do
1094 var from_end_index = index_string.chars.index_of('.')
1095 var to_start_index = index_string.chars.last_index_of('.')
1096
1097 if from_end_index != -1 and to_start_index != -1 then
1098 var index_from_string = index_string.substring(0,from_end_index)
1099 var index_to_string = index_string.substring_from(to_start_index+1)
1100
1101 if index_from_string.is_numeric and index_to_string.is_numeric then
1102 var result_array = new Array[Int]
1103
1104 var index_from = index_from_string.to_i
1105 var index_to = index_to_string.to_i
1106
1107 for i in [index_from..index_to] do
1108 result_array.push(i)
1109 end
1110
1111 return result_array
1112 end
1113 else
1114 if index_string.is_numeric
1115 then
1116 var result_array = new Array[Int]
1117
1118 result_array.push(index_string.to_i)
1119
1120 return result_array
1121 else
1122 return null
1123 end
1124 end
1125
1126 return null
1127 end
1128
1129 # Gets a collection in a MutableInstance
1130 fun get_primary_collection(container: MutableInstance): nullable SequenceRead[Object]
1131 do
1132 var items_of_array = get_attribute_in_mutable_instance(container, "items")
1133 if items_of_array != null then
1134 var array = container.attributes[items_of_array]
1135
1136 if array isa PrimitiveInstance[Object] then
1137 var sequenceRead_final = array.val
1138 if sequenceRead_final isa SequenceRead[Object] then
1139 return sequenceRead_final
1140 end
1141 end
1142 end
1143
1144 return null
1145 end
1146
1147 # Removes the braces '[' ']' in a print array command
1148 # Returns an array containing their content
1149 fun remove_braces(braces: String): nullable Array[String]
1150 do
1151 var buffer = new FlatBuffer
1152
1153 var result_array = new Array[String]
1154
1155 var number_of_opening_brackets = 0
1156 var number_of_closing_brackets = 0
1157
1158 var last_was_opening_bracket = false
1159
1160 for i in braces.chars do
1161 if i == '[' then
1162 if last_was_opening_bracket then
1163 return null
1164 end
1165
1166 number_of_opening_brackets += 1
1167 last_was_opening_bracket = true
1168 else if i == ']' then
1169 if not last_was_opening_bracket then
1170 return null
1171 end
1172
1173 result_array.push(buffer.to_s)
1174 buffer.clear
1175 number_of_closing_brackets += 1
1176 last_was_opening_bracket = false
1177 else if i.is_numeric or i == '.' then
1178 buffer.append(i.to_s)
1179 else if not i == ' ' then
1180 return null
1181 end
1182 end
1183
1184 if number_of_opening_brackets != number_of_closing_brackets then
1185 return null
1186 end
1187
1188 return result_array
1189 end
1190
1191 #######################################################################
1192 ## Breakpoint placing functions ##
1193 #######################################################################
1194
1195 # Places a breakpoint on line 'line_to_break' for file 'file_to_break'
1196 fun place_breakpoint(breakpoint: Breakpoint)
1197 do
1198 if not self.breakpoints.keys.has(breakpoint.file) then
1199 self.breakpoints[breakpoint.file] = new HashSet[Breakpoint]
1200 end
1201 if find_breakpoint(breakpoint.file, breakpoint.line) == null then
1202 self.breakpoints[breakpoint.file].add(breakpoint)
1203 print "Breakpoint added on line {breakpoint.line} for file {breakpoint.file}"
1204 else
1205 print "Breakpoint already present on line {breakpoint.line} for file {breakpoint.file}"
1206 end
1207 end
1208
1209 #Places a breakpoint that will trigger once and be destroyed afterwards
1210 fun process_place_tbreak_fun(parts_of_command: Array[String])
1211 do
1212 var bp = get_breakpoint_from_command(parts_of_command)
1213 if bp != null
1214 then
1215 bp.set_max_breaks(1)
1216 place_breakpoint(bp)
1217 end
1218 end
1219
1220 #######################################################################
1221 ## Breakpoint removing functions ##
1222 #######################################################################
1223
1224 # Removes a breakpoint on line 'line_to_break' for file 'file_to_break'
1225 fun remove_breakpoint(file_to_break: String, line_to_break: Int)
1226 do
1227 if self.breakpoints.keys.has(file_to_break) then
1228 var bp = find_breakpoint(file_to_break, line_to_break)
1229
1230 if bp != null then
1231 self.breakpoints[file_to_break].remove(bp)
1232 print "Breakpoint removed on line {line_to_break} for file {file_to_break}"
1233 return
1234 end
1235 end
1236
1237 print "No breakpoint existing on line {line_to_break} for file {file_to_break}"
1238 end
1239
1240 #######################################################################
1241 ## Breakpoint searching functions ##
1242 #######################################################################
1243
1244 # Finds a breakpoint for 'file' and 'line' in the class HashMap
1245 fun find_breakpoint(file: String, line: Int): nullable Breakpoint
1246 do
1247 if self.breakpoints.keys.has(file)
1248 then
1249 for i in self.breakpoints[file]
1250 do
1251 if i.line == line
1252 then
1253 return i
1254 end
1255 end
1256 end
1257
1258 return null
1259 end
1260
1261 #######################################################################
1262 ## Runtime modification functions ##
1263 #######################################################################
1264
1265 # Modifies the value of a variable contained in a frame
1266 fun modify_in_frame(variable: Instance, value: String)
1267 do
1268 var new_variable = get_variable_of_type_with_value(variable.mtype.to_s, value)
1269 if new_variable != null
1270 then
1271 var keys = frame.map.keys
1272 for key in keys
1273 do
1274 if frame.map[key] == variable
1275 then
1276 frame.map[key] = new_variable
1277 end
1278 end
1279 end
1280 end
1281
1282 # Modifies the value of a variable contained in a MutableInstance
1283 fun modify_argument_of_complex_type(papa: MutableInstance, attribute: MAttribute, value: String)
1284 do
1285 var final_variable = papa.attributes[attribute]
1286 var type_of_variable = final_variable.mtype.to_s
1287 var new_variable = get_variable_of_type_with_value(type_of_variable, value)
1288 if new_variable != null
1289 then
1290 papa.attributes[attribute] = new_variable
1291 end
1292 end
1293
1294 #######################################################################
1295 ## Variable generator functions ##
1296 #######################################################################
1297
1298 # Returns a new variable of the type 'type_of_variable' with a value of 'value'
1299 fun get_variable_of_type_with_value(type_of_variable: String, value: String): nullable Instance
1300 do
1301 if type_of_variable == "Int" then
1302 return get_int(value)
1303 else if type_of_variable == "Float" then
1304 return get_float(value)
1305 else if type_of_variable == "Bool" then
1306 return get_bool(value)
1307 else if type_of_variable == "Char" then
1308 return get_char(value)
1309 end
1310
1311 return null
1312 end
1313
1314 # Returns a new int instance with value 'value'
1315 fun get_int(value: String): nullable Instance
1316 do
1317 if value.is_numeric then
1318 return int_instance(value.to_i)
1319 else
1320 return null
1321 end
1322 end
1323
1324 # Returns a new float instance with value 'value'
1325 fun get_float(value:String): nullable Instance
1326 do
1327 if value.is_numeric then
1328 return float_instance(value.to_f)
1329 else
1330 return null
1331 end
1332 end
1333
1334 # Returns a new char instance with value 'value'
1335 fun get_char(value: String): nullable Instance
1336 do
1337 if value.length >= 1 then
1338 return char_instance(value.chars[0])
1339 else
1340 return null
1341 end
1342 end
1343
1344 # Returns a new bool instance with value 'value'
1345 fun get_bool(value: String): nullable Instance
1346 do
1347 if value.to_lower == "true" then
1348 return self.true_instance
1349 else if value.to_lower == "false" then
1350 return self.false_instance
1351 else
1352 print "Invalid value, a boolean must be set at \"true\" or \"false\""
1353 return null
1354 end
1355 end
1356
1357 end
1358
1359 redef class AMethPropdef
1360
1361 # Same as call except it will copy local variables of the parent frame to the frame defined in this call.
1362 # Not supposed to be used by anyone else than the Debugger.
1363 private fun rt_call(v: Debugger, mpropdef: MMethodDef, args: Array[Instance]): nullable Instance
1364 do
1365 var f = new Frame(self, self.mpropdef.as(not null), args)
1366 var curr_instances = v.frame.map
1367 for i in curr_instances.keys do
1368 f.map[i] = curr_instances[i]
1369 end
1370 call_commons(v,mpropdef,args,f)
1371 var currFra = v.frames.shift
1372 for i in curr_instances.keys do
1373 if currFra.map.keys.has(i) then
1374 curr_instances[i] = currFra.map[i]
1375 end
1376 end
1377 if v.returnmark == f then
1378 v.returnmark = null
1379 var res = v.escapevalue
1380 v.escapevalue = null
1381 return res
1382 end
1383 return null
1384
1385 end
1386 end
1387
1388 # Traces the modifications of an object linked to a certain frame
1389 private class TraceObject
1390
1391 # Map of the local names bound to a frame
1392 var trace_map: HashMap[Frame, String]
1393 # Decides if breaking or printing statement when the variable is encountered
1394 var break_on_encounter: Bool
1395
1396 init(break_on_encounter: Bool)
1397 do
1398 trace_map = new HashMap[Frame, String]
1399 self.break_on_encounter = break_on_encounter
1400 end
1401
1402 # Adds the local alias for a variable and the frame bound to it
1403 fun add_frame_variable(frame: Frame, variable_name: String)
1404 do
1405 self.trace_map[frame] = variable_name
1406 end
1407
1408 # Checks if the prompted variable is traced in the specified frame
1409 fun is_variable_traced_in_frame(variable_name: String, frame: Frame): Bool
1410 do
1411 if self.trace_map.has_key(frame) then
1412 if self.trace_map[frame] == variable_name then
1413 return true
1414 end
1415 end
1416
1417 return false
1418 end
1419
1420 end
1421
1422 redef class ANode
1423
1424 # Breaks automatically when encountering an error
1425 # Permits the injunction of commands before crashing
1426 redef fun fatal(v: NaiveInterpreter, message: String)
1427 do
1428 if v isa Debugger then
1429 print "An error was encountered, the program will stop now."
1430 self.debug(message)
1431 while v.process_debug_command(gets) do end
1432 end
1433
1434 super
1435 end
1436 end