eea88202ffc2c1c4ee9073013678d891277a3a1f
[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 "Warning".search_in(m.text, 0) == 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 # Encpasulates the behaviour for step over/out
245 private fun steps_fun_call(n: AExpr)
246 do
247 if self.stop_after_step_over_trigger then
248 if self.frames.length <= self.step_stack_count then
249 n.debug("Execute stmt {n.to_s}")
250 while read_cmd do end
251 end
252 else if self.stop_after_step_out_trigger then
253 if frames.length < self.step_stack_count then
254 n.debug("Execute stmt {n.to_s}")
255 while read_cmd do end
256 end
257 else if step_in_trigger then
258 n.debug("Execute stmt {n.to_s}")
259 while read_cmd do end
260 end
261 end
262
263 # Checks if a breakpoint is encountered, and launches the debugging prompt if true
264 private fun breakpoint_check(n: AExpr)
265 do
266 var currFileNameSplit = self.frame.current_node.location.file.filename.to_s.split_with("/")
267
268 self.curr_file = currFileNameSplit[currFileNameSplit.length-1]
269
270 var breakpoint = find_breakpoint(curr_file, n.location.line_start)
271
272 if breakpoints.keys.has(curr_file) and breakpoint != null then
273
274 breakpoint.check_in
275
276 if not breakpoint.is_valid
277 then
278 remove_breakpoint(curr_file, n.location.line_start)
279 end
280
281 n.debug("Execute stmt {n.to_s}")
282 while read_cmd do end
283 end
284 end
285
286 # Check if a variable of current expression is traced
287 # Then prints and/or breaks for command prompt
288 private fun check_if_vars_are_traced(n: AExpr)
289 do
290 var identifiers_in_instruction = get_identifiers_in_current_instruction(n.location.text)
291
292 for i in identifiers_in_instruction do
293 var variable = seek_variable(i, frame)
294 for j in self.traces do
295 if j.is_variable_traced_in_frame(i, frame) then
296 n.debug("Traced variable {i} used")
297 if j.break_on_encounter then while read_cmd do end
298 break
299 end
300 end
301 end
302 end
303
304 # Function remapping all the traced objects to match their name in the local context
305 private fun remap(n: AExpr)
306 do
307 if self.aftermath then
308
309 # Trace every argument variable pre-specified
310 if self.frame_count_aftermath < frames.length and fun_call_arguments_positions.length > 0 then
311
312 var ids_in_fun_def = get_identifiers_in_current_instruction(get_function_arguments(frame.mpropdef.location.text))
313
314 for i in fun_call_arguments_positions.keys do
315 self.fun_call_arguments_positions[i].add_frame_variable(frame, ids_in_fun_def[i])
316 end
317 end
318
319 self.aftermath = false
320 end
321 end
322
323 # If the current instruction is a function call
324 # We analyse its signature and the position of traced arguments if the call
325 # For future remapping when inside the function
326 private fun check_funcall_and_traced_args(n: AExpr) do
327 # If we have a function call, we need to see if any of the arguments is traced (including the caller)
328 # if it is, next time we face an instruction, we'll trace the local version on the traced variable in the next frame
329 if n isa ACallExpr then
330 self.aftermath = true
331 self.frame_count_aftermath = frames.length
332 fun_call_arguments_positions.clear
333 var fun_arguments = get_identifiers_in_current_instruction(get_function_arguments(n.location.text))
334
335 for i in self.traces do
336 for j in [0 .. fun_arguments.length - 1] do
337 if i.is_variable_traced_in_frame(fun_arguments[j],frame) then
338 fun_call_arguments_positions[j] = i
339 end
340 end
341 end
342 end
343 end
344
345 #######################################################################
346 ## Processing commands functions ##
347 #######################################################################
348
349 fun read_cmd: Bool
350 do
351 printn "> "
352 return process_debug_command(gets)
353 end
354
355 # Takes a user command as a parameter
356 #
357 # Returns a boolean value, representing whether or not to
358 # continue reading commands from the console input
359 fun process_debug_command(command:String): Bool
360 do
361 # For lisibility
362 print "\n"
363
364 # Kills the current program
365 if command == "kill" then
366 abort
367 # Step-out command
368 else if command == "finish"
369 then
370 return step_out
371 # Step-in command
372 else if command == "s"
373 then
374 return step_in
375 # Step-over command
376 else if command == "n" then
377 return step_over
378 # Opens a new NitIndex prompt on current model
379 else if command == "nitx" then
380 new NitIndex.with_infos(modelbuilder, self.mainmodule).prompt
381 return true
382 # Continues execution until the end
383 else if command == "c" then
384 return continue_exec
385 else
386 var parts_of_command = command.split_with(' ')
387 # Shows the value of a variable in the current frame
388 if parts_of_command[0] == "p" or parts_of_command[0] == "print" then
389 print_command(parts_of_command)
390 # Places a breakpoint on line x of file y
391 else if parts_of_command[0] == "break" or parts_of_command[0] == "b"
392 then
393 process_place_break_fun(parts_of_command)
394 # Places a temporary breakpoint on line x of file y
395 else if parts_of_command[0] == "tbreak" and (parts_of_command.length == 2 or parts_of_command.length == 3)
396 then
397 process_place_tbreak_fun(parts_of_command)
398 # Removes a breakpoint on line x of file y
399 else if parts_of_command[0] == "d" or parts_of_command[0] == "delete" then
400 process_remove_break_fun(parts_of_command)
401 # Sets an alias for a variable
402 else if parts_of_command.length == 3 and parts_of_command[1] == "as"
403 then
404 add_alias(parts_of_command[0], parts_of_command[2])
405 # Modifies the value of a variable in the current frame
406 else if parts_of_command.length >= 3 and parts_of_command[1] == "=" then
407 process_mod_function(parts_of_command)
408 # Traces the modifications on a variable
409 else if parts_of_command.length >= 2 and parts_of_command[0] == "trace" then
410 process_trace_command(parts_of_command)
411 # Untraces the modifications on a variable
412 else if parts_of_command.length == 2 and parts_of_command[0] == "untrace" then
413 process_untrace_command(parts_of_command)
414 # Lists all the commands available
415 else
416 list_commands
417 end
418 end
419 return true
420 end
421
422 #######################################################################
423 ## Processing specific command functions ##
424 #######################################################################
425
426 # Sets the flags to step-over an instruction in the current file
427 fun step_over: Bool
428 do
429 self.step_stack_count = frames.length
430 self.stop_after_step_over_trigger = true
431 self.stop_after_step_out_trigger = false
432 self.step_in_trigger = false
433 return false
434 end
435
436 #Sets the flags to step-out of a function
437 fun step_out: Bool
438 do
439 self.stop_after_step_over_trigger = false
440 self.stop_after_step_out_trigger = true
441 self.step_in_trigger = false
442 self.step_stack_count = frames.length
443 return false
444 end
445
446 # Sets the flags to step-in an instruction
447 fun step_in: Bool
448 do
449 self.step_in_trigger = true
450 self.stop_after_step_over_trigger = false
451 self.stop_after_step_out_trigger = false
452 return false
453 end
454
455 # Sets the flags to continue execution
456 fun continue_exec: Bool
457 do
458 self.stop_after_step_over_trigger = false
459 self.stop_after_step_out_trigger = false
460 self.step_in_trigger = false
461 return false
462 end
463
464 # Prints the demanded variable in the command
465 #
466 # The name of the variable in in position 1 of the array 'parts_of_command'
467 fun print_command(parts_of_command: Array[String])
468 do
469 if parts_of_command[1] == "*" then
470 var map_of_instances = frame.map
471
472 var keys = map_of_instances.iterator
473
474 print "Variables collection : \n"
475
476 for instance in map_of_instances.keys do
477 print "Variable {instance.to_s}, Instance {map_of_instances[instance].to_s}"
478 end
479
480 print "\nEnd of current instruction \n"
481 else if parts_of_command[1] == "stack" then
482 print self.stack_trace
483 else if parts_of_command[1].has('[') and parts_of_command[1].has(']') then
484 process_array_command(parts_of_command)
485 else
486 var instance = seek_variable(get_real_variable_name(parts_of_command[1]), frame)
487
488 if instance != null
489 then
490 print_instance(instance)
491 else
492 print "Cannot find variable {parts_of_command[1]}"
493 end
494 end
495 end
496
497 # Processes the input string to know where to put a breakpoint
498 fun process_place_break_fun(parts_of_command: Array[String])
499 do
500 var bp = get_breakpoint_from_command(parts_of_command)
501 if bp != null then
502 place_breakpoint(bp)
503 else
504 list_commands
505 end
506 end
507
508 # Returns a breakpoint containing the informations stored in the command
509 fun get_breakpoint_from_command(parts_of_command: Array[String]): nullable Breakpoint
510 do
511 if parts_of_command[1].is_numeric then
512 return new Breakpoint(parts_of_command[1].to_i, curr_file)
513 else if parts_of_command.length >= 3 and parts_of_command[2].is_numeric then
514 return new Breakpoint(parts_of_command[2].to_i, parts_of_command[1])
515 else
516 return null
517 end
518 end
519
520 # Processes the command of removing a breakpoint on specified line and file
521 fun process_remove_break_fun(parts_of_command: Array[String])
522 do
523 if parts_of_command[1].is_numeric then
524 remove_breakpoint(self.curr_file, parts_of_command[1].to_i)
525 else if parts_of_command.length >= 3 and parts_of_command[2].is_numeric then
526 remove_breakpoint(parts_of_command[1], parts_of_command[2].to_i)
527 else
528 list_commands
529 end
530 end
531
532 # Processes an array print command
533 fun process_array_command(parts_of_command: Array[String])
534 do
535 var index_of_first_brace = parts_of_command[1].index_of('[')
536 var variable_name = get_real_variable_name(parts_of_command[1].substring(0,index_of_first_brace))
537 var braces = parts_of_command[1].substring_from(index_of_first_brace)
538
539 var indexes = remove_braces(braces)
540
541 var index_array = new Array[Array[Int]]
542
543 if indexes != null then
544 for index in indexes do
545 var temp_indexes_array = process_index(index)
546 if temp_indexes_array != null then
547 index_array.push(temp_indexes_array)
548 #print index_array.last
549 end
550 end
551 end
552
553 var instance = seek_variable(variable_name, frame)
554
555 if instance != null then
556 print_nested_collection(instance, index_array, 0, variable_name, "")
557 else
558 print "Cannot find variable {variable_name}"
559 end
560 end
561
562 # Processes the modification function to modify a variable dynamically
563 #
564 # Command of type variable = value
565 fun process_mod_function(parts_of_command: Array[String])
566 do
567 parts_of_command[0] = get_real_variable_name(parts_of_command[0])
568 var parts_of_variable = parts_of_command[0].split_with(".")
569
570 if parts_of_variable.length > 1 then
571 var last_part = parts_of_variable.pop
572 var first_part = parts_of_command[0].substring(0,parts_of_command[0].length - last_part.length - 1)
573 var papa = seek_variable(first_part, frame)
574
575 if papa != null and papa isa MutableInstance then
576 var attribute = get_attribute_in_mutable_instance(papa, last_part)
577
578 if attribute != null then
579 modify_argument_of_complex_type(papa, attribute, parts_of_command[2])
580 end
581 end
582 else
583 var target = seek_variable(parts_of_variable[0], frame)
584 if target != null then
585 modify_in_frame(target, parts_of_command[2])
586 end
587 end
588 end
589
590 # Processes the untrace variable command
591 #
592 # Command pattern : "untrace variable"
593 fun process_untrace_command(parts_of_command: Array[String])
594 do
595 var variable_name = get_real_variable_name(parts_of_command[1])
596 if untrace_variable(variable_name) then
597 print "Untraced variable {parts_of_command[1]}"
598 else
599 print "{parts_of_command[1]} is not traced"
600 end
601 end
602
603 # Processes the trace variable command
604 #
605 # Command pattern : "trace variable [break/print]"
606 fun process_trace_command(parts_of_command: Array[String])
607 do
608 var variable_name = get_real_variable_name(parts_of_command[1])
609 var breaker:Bool
610
611 if seek_variable(variable_name, frame) == null then
612 print "Cannot find a variable called {parts_of_command[1]}"
613 return
614 end
615
616 if parts_of_command.length == 3 then
617 if parts_of_command[2] == "break" then
618 breaker = true
619 else
620 breaker = false
621 end
622 else
623 breaker = false
624 end
625
626 trace_variable(variable_name, breaker)
627
628 print "Successfully tracing {parts_of_command[1]}"
629 end
630
631 #######################################################################
632 ## Trace Management functions ##
633 #######################################################################
634
635 # Effectively untraces the variable called *variable_name*
636 #
637 # Returns true if the variable exists, false otherwise
638 private fun untrace_variable(variable_name: String): Bool
639 do
640 var to_remove: nullable TraceObject = null
641 for i in self.traces do
642 if i.is_variable_traced_in_frame(variable_name, frame) then
643 to_remove = i
644 end
645 end
646
647 if to_remove != null then
648 self.traces.remove(to_remove)
649 return true
650 else
651 return false
652 end
653 end
654
655 # Effectively traces the variable *variable_name* either in print or break mode depending on the value of breaker (break if true, print if false)
656 #
657 private fun trace_variable(variable_name: String, breaker: Bool)
658 do
659 for i in self.traces do
660 if i.is_variable_traced_in_frame(variable_name, frame) then
661 print "This variable is already traced"
662 return
663 end
664 end
665
666 var trace_object: TraceObject
667
668 if breaker then
669 trace_object = new TraceObject(true)
670 else
671 trace_object = new TraceObject(false)
672 end
673
674 # We trace the current variable found for the current frame
675 trace_object.add_frame_variable(self.frame, variable_name)
676
677 var position_of_variable_in_arguments = get_position_of_variable_in_arguments(frame, variable_name)
678
679 # Start parsing the frames starting with the parent of the current one, until the highest
680 # When the variable traced is declared locally, the loop stops
681 for i in [1 .. frames.length-1] do
682
683 # If the variable was reported to be an argument of the previous frame
684 if position_of_variable_in_arguments != -1 then
685
686 var local_name = get_identifiers_in_current_instruction(get_function_arguments(frames[i].current_node.location.text))[position_of_variable_in_arguments]
687
688 position_of_variable_in_arguments = get_position_of_variable_in_arguments(frames[i], local_name)
689
690 trace_object.add_frame_variable(frames[i], local_name)
691 else
692 break
693 end
694 end
695
696 self.traces.add(trace_object)
697 end
698
699 # If the variable *variable_name* is an argument of the function being executed in the frame *frame*
700 # The function returns its position in the arguments
701 # Else, it returns -1
702 private fun get_position_of_variable_in_arguments(frame: Frame, variable_name: String): Int
703 do
704 var identifiers = get_identifiers_in_current_instruction(get_function_arguments(frame.mpropdef.location.text))
705 for i in [0 .. identifiers.length-1] do
706 # If the current traced variable is an argument of the current function, we trace its parent (at least)
707 if identifiers[i] == variable_name then return i
708 end
709 return -1
710 end
711
712 # Gets all the identifiers of an instruction (uses the rules of Nit as of Mar 05 2013)
713 #
714 fun get_identifiers_in_current_instruction(instruction: AbstractString): Array[String]
715 do
716 var result_array = new Array[String]
717 var instruction_buffer = new Buffer
718
719 var trigger_char_escape = false
720 var trigger_string_escape = false
721 var trigger_concat_in_string = false
722
723 for i in instruction do
724 if trigger_char_escape then
725 if i == '\'' then trigger_char_escape = false
726 else if trigger_string_escape then
727 if i == '{' then
728 trigger_concat_in_string = true
729 trigger_string_escape = false
730 else if i == '\"' then trigger_string_escape = false
731 else
732 if i.is_alphanumeric or i == '_' then
733 instruction_buffer.add(i)
734 else if i == '.' then
735 if instruction_buffer.is_numeric or (instruction_buffer[0] >= 'A' and instruction_buffer[0] <= 'Z') then
736 instruction_buffer.clear
737 else
738 result_array.push(instruction_buffer.to_s)
739 instruction_buffer.add(i)
740 end
741 else if i == '\'' then
742 trigger_char_escape = true
743 else if i == '\"' then
744 trigger_string_escape = true
745 else if i == '}' then
746 trigger_concat_in_string = false
747 trigger_string_escape = true
748 else
749 if instruction_buffer.length > 0 and not instruction_buffer.is_numeric and not (instruction_buffer[0] >= 'A' and instruction_buffer[0] <= 'Z') then result_array.push(instruction_buffer.to_s)
750 instruction_buffer.clear
751 end
752 end
753 end
754
755 if instruction_buffer.length > 0 and not instruction_buffer.is_numeric and not (instruction_buffer[0] >= 'A' and instruction_buffer[0] <= 'Z') then result_array.push(instruction_buffer.to_s)
756
757 return result_array
758 end
759
760 # Takes a function call or declaration and strips all but the arguments
761 #
762 fun get_function_arguments(function: AbstractString): String
763 do
764 var buf = new Buffer
765 var trigger_copy = false
766
767 for i in function do
768 if i == ')' then break
769 if trigger_copy then buf.add(i)
770 if i == '(' then trigger_copy = true
771 end
772
773 return buf.to_s
774 end
775
776 #######################################################################
777 ## Alias management functions ##
778 #######################################################################
779
780 # Adds a new alias to the tables
781 fun add_alias(var_represented: String, alias: String)
782 do
783 self.aliases[alias] = var_represented
784 end
785
786 # Gets the real name of a variable hidden by an alias
787 fun get_variable_name_by_alias(alias: String): nullable String
788 do
789 if self.aliases.keys.has(alias) then
790 return self.aliases[alias]
791 end
792
793 return null
794 end
795
796 # Gets the variable named by name, whether it is an alias or not
797 fun get_real_variable_name(name: String): String
798 do
799 var explode_string = name.split_with(".")
800 var final_string = new Buffer
801 for i in explode_string do
802 var alias_resolved = get_variable_name_by_alias(i)
803 if alias_resolved != null then
804 final_string.append(get_real_variable_name(alias_resolved))
805 else
806 final_string.append(i)
807 end
808 final_string.append(".")
809 end
810
811 return final_string.substring(0,final_string.length-1).to_s
812 end
813
814 #######################################################################
815 ## Print functions ##
816 #######################################################################
817
818 # Prints an object instance and its attributes if it has some
819 #
820 # If it is a primitive type, its value is directly printed
821 fun print_instance(instance: Instance)
822 do
823 print "Printing innards of a variable"
824
825 if instance isa MutableInstance then
826 var attributes = instance.attributes
827 print "Object : {instance}"
828
829 for current_attribute in attributes.keys do
830 print "Attribute : {current_attribute.to_s} \nValeur : {attributes[current_attribute].to_s}"
831 end
832 else
833 print "Found variable {instance}"
834 end
835
836 print "Stopping printing innards of a variable"
837 end
838
839 # Prints the attributes demanded in a SequenceRead
840 # Used recursively to print nested collections
841 fun print_nested_collection(instance: Instance, indexes: Array[Array[Int]], depth: Int, variable_name: String, depth_string: String)
842 do
843 var collection: nullable SequenceRead[Object] = null
844 var real_collection_length: nullable Int = null
845
846 if instance isa MutableInstance then
847 real_collection_length = get_collection_instance_real_length(instance)
848 collection = get_primary_collection(instance)
849 end
850
851 if collection != null and real_collection_length != null then
852 for i in indexes[depth] do
853 if i >= 0 and i < real_collection_length then
854 if depth == indexes.length-1 then
855 print "{variable_name}{depth_string}[{i}] = {collection[i]}"
856 else
857 var item_i = collection[i]
858
859 if item_i isa MutableInstance then
860 print_nested_collection(item_i, indexes, depth+1, variable_name, depth_string+"[{i}]")
861 else
862 print "The item at {variable_name}{depth_string}[{i}] is not a collection"
863 print item_i
864 end
865 end
866 else
867 print "Out of bounds exception : i = {i} and collection_length = {real_collection_length.to_s}"
868
869 if i < 0 then
870 continue
871 else if i >= real_collection_length then
872 break
873 end
874 end
875 end
876 else
877 if collection == null then
878 print "Cannot find {variable_name}{depth_string}"
879 else if real_collection_length != null then
880 print "Cannot find attribute length in {instance}"
881 else
882 print "Unknown error."
883 abort
884 end
885 end
886 end
887
888 #######################################################################
889 ## Variable Exploration functions ##
890 #######################################################################
891
892 # Seeks a variable from the current frame called 'variable_path', can introspect complex objects using function get_variable_in_mutable_instance
893 private fun seek_variable(variable_path: String, frame: Frame): nullable Instance
894 do
895 var full_variable = variable_path.split_with(".")
896
897 var full_variable_iterator = full_variable.iterator
898
899 var first_instance = get_variable_in_frame(full_variable_iterator.item, frame)
900
901 if first_instance == null then return null
902
903 if full_variable.length <= 1 then return first_instance
904
905 full_variable_iterator.next
906
907 if not (first_instance isa MutableInstance and full_variable_iterator.is_ok) then return null
908
909 return get_variable_in_mutable_instance(first_instance, full_variable_iterator)
910 end
911
912 # Gets a variable 'variable_name' contained in the frame 'frame'
913 private fun get_variable_in_frame(variable_name: String, frame: Frame): nullable Instance
914 do
915 if variable_name == "self" then
916 if frame.arguments.length >= 1 then return frame.arguments.first
917 end
918
919 var map_of_instances = frame.map
920
921 for key in map_of_instances.keys do
922 if key.to_s == variable_name then
923 return map_of_instances[key]
924 end
925 end
926
927 return null
928 end
929
930 # Gets an attribute 'attribute_name' contained in variable 'variable'
931 fun get_attribute_in_mutable_instance(variable: MutableInstance, attribute_name: String): nullable MAttribute
932 do
933 var map_of_attributes = variable.attributes
934
935 for key in map_of_attributes.keys do
936 if key.to_s.substring_from(1) == attribute_name then
937 return key
938 end
939 end
940
941 return null
942 end
943
944 # Recursive function, returns the variable described by 'total_chain'
945 fun get_variable_in_mutable_instance(variable: MutableInstance, iterator: Iterator[String]): nullable Instance
946 do
947 var attribute = get_attribute_in_mutable_instance(variable, iterator.item)
948
949 if attribute == null then return null
950
951 iterator.next
952
953 if iterator.is_ok then
954 var new_variable = variable.attributes[attribute]
955 if new_variable isa MutableInstance then
956 return get_variable_in_mutable_instance(new_variable, iterator)
957 else
958 return null
959 end
960 else
961 return variable.attributes[attribute]
962 end
963 end
964
965 #######################################################################
966 ## Array exploring functions ##
967 #######################################################################
968
969 # Gets the length of a collection
970 # Used by the debugger, else if we call Collection.length, it returns the capacity instead
971 fun get_collection_instance_real_length(collection: MutableInstance): nullable Int
972 do
973 var collection_length_attribute = get_attribute_in_mutable_instance(collection, "length")
974
975 var real_collection_length: nullable Int = null
976
977 if collection_length_attribute != null then
978 var primitive_length_instance = collection.attributes[collection_length_attribute]
979 if primitive_length_instance isa PrimitiveInstance[Int] then
980 return primitive_length_instance.val
981 end
982 end
983
984 return null
985 end
986
987 # Processes the indexes of a print array call
988 # Returns an array containing all the indexes demanded
989 fun process_index(index_string: String): nullable Array[Int]
990 do
991 var from_end_index = index_string.index_of('.')
992 var to_start_index = index_string.last_index_of('.')
993
994 if from_end_index != -1 and to_start_index != -1 then
995 var index_from_string = index_string.substring(0,from_end_index)
996 var index_to_string = index_string.substring_from(to_start_index+1)
997
998 if index_from_string.is_numeric and index_to_string.is_numeric then
999 var result_array = new Array[Int]
1000
1001 var index_from = index_from_string.to_i
1002 var index_to = index_to_string.to_i
1003
1004 for i in [index_from..index_to] do
1005 result_array.push(i)
1006 end
1007
1008 return result_array
1009 end
1010 else
1011 if index_string.is_numeric
1012 then
1013 var result_array = new Array[Int]
1014
1015 result_array.push(index_string.to_i)
1016
1017 return result_array
1018 else
1019 return null
1020 end
1021 end
1022
1023 return null
1024 end
1025
1026 # Gets a collection in a MutableInstance
1027 fun get_primary_collection(container: MutableInstance): nullable SequenceRead[Object]
1028 do
1029 var items_of_array = get_attribute_in_mutable_instance(container, "items")
1030 if items_of_array != null then
1031 var array = container.attributes[items_of_array]
1032
1033 if array isa PrimitiveInstance[Object] then
1034 var sequenceRead_final = array.val
1035 if sequenceRead_final isa SequenceRead[Object] then
1036 return sequenceRead_final
1037 end
1038 end
1039 end
1040
1041 return null
1042 end
1043
1044 # Removes the braces '[' ']' in a print array command
1045 # Returns an array containing their content
1046 fun remove_braces(braces: String): nullable Array[String]
1047 do
1048 var buffer = new Buffer
1049
1050 var result_array = new Array[String]
1051
1052 var number_of_opening_brackets = 0
1053 var number_of_closing_brackets = 0
1054
1055 var last_was_opening_bracket = false
1056
1057 for i in braces do
1058 if i == '[' then
1059 if last_was_opening_bracket then
1060 return null
1061 end
1062
1063 number_of_opening_brackets += 1
1064 last_was_opening_bracket = true
1065 else if i == ']' then
1066 if not last_was_opening_bracket then
1067 return null
1068 end
1069
1070 result_array.push(buffer.to_s)
1071 buffer.clear
1072 number_of_closing_brackets += 1
1073 last_was_opening_bracket = false
1074 else if i.is_numeric or i == '.' then
1075 buffer.append(i.to_s)
1076 else if not i == ' ' then
1077 return null
1078 end
1079 end
1080
1081 if number_of_opening_brackets != number_of_closing_brackets then
1082 return null
1083 end
1084
1085 return result_array
1086 end
1087
1088 #######################################################################
1089 ## Breakpoint placing functions ##
1090 #######################################################################
1091
1092 # Places a breakpoint on line 'line_to_break' for file 'file_to_break'
1093 fun place_breakpoint(breakpoint: Breakpoint)
1094 do
1095 if not self.breakpoints.keys.has(breakpoint.file) then
1096 self.breakpoints[breakpoint.file] = new HashSet[Breakpoint]
1097 end
1098 if find_breakpoint(breakpoint.file, breakpoint.line) == null then
1099 self.breakpoints[breakpoint.file].add(breakpoint)
1100 print "Breakpoint added on line {breakpoint.line} for file {breakpoint.file}"
1101 else
1102 print "Breakpoint already present on line {breakpoint.line} for file {breakpoint.file}"
1103 end
1104 end
1105
1106 #Places a breakpoint that will trigger once and be destroyed afterwards
1107 fun process_place_tbreak_fun(parts_of_command: Array[String])
1108 do
1109 var bp = get_breakpoint_from_command(parts_of_command)
1110 if bp != null
1111 then
1112 bp.set_max_breaks(1)
1113 place_breakpoint(bp)
1114 else
1115 list_commands
1116 end
1117 end
1118
1119 #######################################################################
1120 ## Breakpoint removing functions ##
1121 #######################################################################
1122
1123 # Removes a breakpoint on line 'line_to_break' for file 'file_to_break'
1124 fun remove_breakpoint(file_to_break: String, line_to_break: Int)
1125 do
1126 if self.breakpoints.keys.has(file_to_break) then
1127 var bp = find_breakpoint(file_to_break, line_to_break)
1128
1129 if bp != null then
1130 self.breakpoints[file_to_break].remove(bp)
1131 print "Breakpoint removed on line {line_to_break} for file {file_to_break}"
1132 return
1133 end
1134 end
1135
1136 print "No breakpoint existing on line {line_to_break} for file {file_to_break}"
1137 end
1138
1139 #######################################################################
1140 ## Breakpoint searching functions ##
1141 #######################################################################
1142
1143 # Finds a breakpoint for 'file' and 'line' in the class HashMap
1144 fun find_breakpoint(file: String, line: Int): nullable Breakpoint
1145 do
1146 if self.breakpoints.keys.has(file)
1147 then
1148 for i in self.breakpoints[file]
1149 do
1150 if i.line == line
1151 then
1152 return i
1153 end
1154 end
1155 end
1156
1157 return null
1158 end
1159
1160 #######################################################################
1161 ## Runtime modification functions ##
1162 #######################################################################
1163
1164 # Modifies the value of a variable contained in a frame
1165 fun modify_in_frame(variable: Instance, value: String)
1166 do
1167 var new_variable = get_variable_of_type_with_value(variable.mtype.to_s, value)
1168 if new_variable != null
1169 then
1170 var keys = frame.map.keys
1171 for key in keys
1172 do
1173 if frame.map[key] == variable
1174 then
1175 frame.map[key] = new_variable
1176 end
1177 end
1178 end
1179 end
1180
1181 # Modifies the value of a variable contained in a MutableInstance
1182 fun modify_argument_of_complex_type(papa: MutableInstance, attribute: MAttribute, value: String)
1183 do
1184 var final_variable = papa.attributes[attribute]
1185 var type_of_variable = final_variable.mtype.to_s
1186 var new_variable = get_variable_of_type_with_value(type_of_variable, value)
1187 if new_variable != null
1188 then
1189 papa.attributes[attribute] = new_variable
1190 end
1191 end
1192
1193 #######################################################################
1194 ## Variable generator functions ##
1195 #######################################################################
1196
1197 # Returns a new variable of the type 'type_of_variable' with a value of 'value'
1198 fun get_variable_of_type_with_value(type_of_variable: String, value: String): nullable Instance
1199 do
1200 if type_of_variable == "Int" then
1201 return get_int(value)
1202 else if type_of_variable == "Float" then
1203 return get_float(value)
1204 else if type_of_variable == "Bool" then
1205 return get_bool(value)
1206 else if type_of_variable == "Char" then
1207 return get_char(value)
1208 end
1209
1210 return null
1211 end
1212
1213 # Returns a new int instance with value 'value'
1214 fun get_int(value: String): nullable Instance
1215 do
1216 if value.is_numeric then
1217 return int_instance(value.to_i)
1218 else
1219 return null
1220 end
1221 end
1222
1223 # Returns a new float instance with value 'value'
1224 fun get_float(value:String): nullable Instance
1225 do
1226 if value.is_numeric then
1227 return float_instance(value.to_f)
1228 else
1229 return null
1230 end
1231 end
1232
1233 # Returns a new char instance with value 'value'
1234 fun get_char(value: String): nullable Instance
1235 do
1236 if value.length >= 1 then
1237 return char_instance(value[0])
1238 else
1239 return null
1240 end
1241 end
1242
1243 # Returns a new bool instance with value 'value'
1244 fun get_bool(value: String): nullable Instance
1245 do
1246 if value.to_lower == "true" then
1247 return self.true_instance
1248 else if value.to_lower == "false" then
1249 return self.false_instance
1250 else
1251 print "Invalid value, a boolean must be set at \"true\" or \"false\""
1252 return null
1253 end
1254 end
1255
1256 #######################################################################
1257 ## Command listing function ##
1258 #######################################################################
1259
1260 # Lists the commands available when using the debugger
1261 fun list_commands
1262 do
1263 print "\nCommand not recognized\n"
1264 print "Commands accepted : \n"
1265 print "[break/b] line : Adds a breakpoint on line *line_nb* of the current file\n"
1266 print "[break/b] file_name line_nb : Adds a breakpoint on line *line_nb* of file *file_name* \n"
1267 print "[p/print] variable : [p/print] * shows the status of all the variables\n"
1268 print "[p/print] variable[i] : Prints the value of the variable contained at position *i* in SequenceRead collection *variable*\n"
1269 print "[p/print] variable[i..j]: Prints the value of all the variables contained between positions *i* and *j* in SequenceRead collection *variable*\n"
1270 print "[p/print] stack: Prints a stack trace at current instruction\n"
1271 print "Note : The arrays can be multi-dimensional (Ex : variable[i..j][k] will print all the values at position *k* of all the SequenceRead collections contained between positions *i* and *j* in SequenceRead collection *variable*)\n"
1272 print "s : steps in on the current function\n"
1273 print "n : steps-over the current instruction\n"
1274 print "finish : steps out of the current function\n"
1275 print "variable as alias : Adds an alias called *alias* for the variable *variable*"
1276 print "An alias can reference another alias\n"
1277 print "variable = value : Sets the value of *variable* to *value*\n"
1278 print "[d/delete] line_nb : Removes a breakpoint on line *line_nb* of the current file \n"
1279 print "[d/delete] file_name line_nb : Removes a breakpoint on line *line_nb* of file *file_name* \n"
1280 print "trace variable_name [break/print] : Traces the uses of the variable you chose to trace by printing the statement it appears in or by breaking on each use."
1281 print "untrace variable_name : Removes the trace on the variable you chose to trace earlier in the program"
1282 print "kill : kills the current program (Exits with an error and stack trace)\n"
1283 end
1284
1285 end
1286
1287 # Traces the modifications of an object linked to a certain frame
1288 private class TraceObject
1289
1290 # Map of the local names bound to a frame
1291 var trace_map: HashMap[Frame, String]
1292 # Decides if breaking or printing statement when the variable is encountered
1293 var break_on_encounter: Bool
1294
1295 init(break_on_encounter: Bool)
1296 do
1297 trace_map = new HashMap[Frame, String]
1298 self.break_on_encounter = break_on_encounter
1299 end
1300
1301 # Adds the local alias for a variable and the frame bound to it
1302 fun add_frame_variable(frame: Frame, variable_name: String)
1303 do
1304 self.trace_map[frame] = variable_name
1305 end
1306
1307 # Checks if the prompted variable is traced in the specified frame
1308 fun is_variable_traced_in_frame(variable_name: String, frame: Frame): Bool
1309 do
1310 if self.trace_map.has_key(frame) then
1311 if self.trace_map[frame] == variable_name then
1312 return true
1313 end
1314 end
1315
1316 return false
1317 end
1318
1319 end
1320
1321 redef class ANode
1322
1323 # Breaks automatically when encountering an error
1324 # Permits the injunction of commands before crashing
1325 redef private fun fatal(v: NaiveInterpreter, message: String)
1326 do
1327 if v isa Debugger then
1328 print "An error was encountered, the program will stop now."
1329 self.debug(message)
1330 while v.process_debug_command(gets) do end
1331 end
1332
1333 super
1334 end
1335 end