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