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