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