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