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