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