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