1 # This file is part of NIT ( http://www.nitlanguage.org ).
3 # Copyright 2013 Lucas Bajolet <lucas.bajolet@gmail.com>
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
9 # http://www.apache.org/licenses/LICENSE-2.0
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.
17 # Debugging of a nit program using the NaiveInterpreter
21 intrude import naive_interpreter
23 intrude import local_var_init
25 intrude import toolcontext
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
32 for i
in [0 .. mmodules
.length
[ do
33 if mmodules
[i
] == m
then
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
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
59 prop
.mpropdefs
.remove_at
(index
)
66 redef class ScopeVisitor
68 redef init(toolcontext
)
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
81 redef class LocalVarInitVisitor
82 redef fun mark_is_unset
(node
: AExpr, variable
: nullable Variable)
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
)
98 redef class ToolContext
99 private var dbg
: nullable Debugger = null
101 private var had_error
: Bool = false
103 redef fun check_errors
108 if messages
.length
> 0 then
109 message_sorter
.sort
(messages
)
112 if "Warning".search_in
(m
.text
, 0) == null then had_error
= true
113 stderr
.write
("{m.to_color_string}\n")
122 var opt_debugger_mode
: OptionBool = new OptionBool("Launches the target program with the debugger attached to it", "-d")
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")
129 self.option_context
.add_option
(self.opt_debugger_mode
)
130 self.option_context
.add_option
(self.opt_debugger_autorun
)
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
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])
144 self.toolcontext
.info
("*** START INTERPRETING ***", 1)
146 var interpreter
= new Debugger(self, mainmodule
, arguments
)
148 init_naive_interpreter
(interpreter
, mainmodule
)
151 self.toolcontext
.info
("*** END INTERPRETING: {time1-time0} ***", 2)
154 fun run_debugger_autorun
(mainmodule
: MModule, arguments
: Array[String])
157 self.toolcontext
.info
("*** START INTERPRETING ***", 1)
159 var interpreter
= new Debugger(self, mainmodule
, arguments
)
160 interpreter
.autocontinue
= true
162 init_naive_interpreter
(interpreter
, mainmodule
)
165 self.toolcontext
.info
("*** END INTERPRETING: {time1-time0} ***", 2)
169 # The class extending `NaiveInterpreter` by adding debugging methods
171 super NaiveInterpreter
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
177 # Triggers a step over an instruction in a nit program
178 var stop_after_step_over_trigger
= true
180 # Triggers a step out of an instruction
181 var stop_after_step_out_trigger
= false
183 # Triggers a step in a instruction (enters a function
184 # if the instruction is a function call)
185 var step_in_trigger
= false
187 # HashMap containing the breakpoints bound to a file
188 var breakpoints
= new HashMap[String, HashSet[Breakpoint]]
190 # Contains the current file
193 # Aliases hashmap (maps an alias to a variable name)
194 var aliases
= new HashMap[String, String]
196 # Set containing all the traced variables and their related frame
197 private var traces
= new HashSet[TraceObject]
199 # Map containing all the positions for the positions of the arguments traced
201 private var fun_call_arguments_positions
= new HashMap[Int, TraceObject]
203 # Triggers the remapping of a trace object in the local context after a function call
204 var aftermath
= false
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
210 # Auto continues the execution until the end or until an error is encountered
211 var autocontinue
= false
213 #######################################################################
214 ## Execution of statement function ##
215 #######################################################################
217 # Main loop, every call to a debug command is done here
218 redef fun stmt
(n
: nullable AExpr)
220 if n
== null then return
222 var frame
= self.frame
223 var old
= frame
.current_node
224 frame
.current_node
= n
226 if not self.autocontinue
then
227 if not n
isa ABlockExpr then
232 check_funcall_and_traced_args
(n
)
236 check_if_vars_are_traced
(n
)
241 frame
.current_node
= old
244 # Does the same as an usual send, except it will modify the call chain on the first call when injecting code at Runtime using the debugger.
245 # Instead of creating a pristine Frame, it will copy the actual values of the frame, and re-inject them after execution in the current context.
246 fun rt_send
(mproperty
: MMethod, args
: Array[Instance]): nullable Instance
248 var recv
= args
.first
249 var mtype
= recv
.mtype
250 var ret
= send_commons
(mproperty
, args
, mtype
)
251 if ret
!= null then return ret
252 var propdef
= mproperty
.lookup_first_definition
(self.mainmodule
, mtype
)
253 return self.rt_call
(propdef
, args
)
256 # Same as a regular call but for a runtime injected module
258 fun rt_call
(mpropdef
: MMethodDef, args
: Array[Instance]): nullable Instance
260 args
= call_commons
(mpropdef
, args
)
261 return rt_call_without_varargs
(mpropdef
, args
)
264 # Common code to call and this function
266 # Call only executes the variadic part, this avoids
267 # double encapsulation of variadic parameters into an Array
268 fun rt_call_without_varargs
(mpropdef
: MMethodDef, args
: Array[Instance]): nullable Instance
270 if self.modelbuilder
.toolcontext
.opt_discover_call_trace
.value
and not self.discover_call_trace
.has
(mpropdef
) then
271 self.discover_call_trace
.add mpropdef
272 self.debug
("Discovered {mpropdef}")
274 if args
.length
< mpropdef
.msignature
.arity
+ 1 or args
.length
> mpropdef
.msignature
.arity
+ 1 then
275 fatal
("NOT YET IMPLEMENTED: Invalid arity for {mpropdef}. {args.length} arguments given.")
277 if args
.length
< mpropdef
.msignature
.arity
+ 1 then
278 fatal
("NOT YET IMPLEMENTED: default closures")
281 # Look for the AST node that implements the property
282 var mproperty
= mpropdef
.mproperty
283 if self.modelbuilder
.mpropdef2npropdef
.has_key
(mpropdef
) then
284 var npropdef
= self.modelbuilder
.mpropdef2npropdef
[mpropdef
]
285 self.parameter_check
(npropdef
, mpropdef
, args
)
286 if npropdef
isa AConcreteMethPropdef then
287 return npropdef
.rt_call
(self, mpropdef
, args
)
289 print
"Error, invalid propdef to call at runtime !"
292 else if mproperty
.name
== "init" then
293 var nclassdef
= self.modelbuilder
.mclassdef2nclassdef
[mpropdef
.mclassdef
]
294 self.parameter_check
(nclassdef
, mpropdef
, args
)
295 return nclassdef
.call
(self, mpropdef
, args
)
297 fatal
("Fatal Error: method {mpropdef} not found in the AST")
302 # Evaluates dynamically a snippet of Nit code
303 # `nit_code` : Nit code to be executed
304 fun eval
(nit_code
: String)
306 var local_toolctx
= modelbuilder
.toolcontext
307 local_toolctx
.dbg
= self
308 var e
= local_toolctx
.parse_something
(nit_code
)
310 nit_code
= "print " + nit_code
311 e
= local_toolctx
.parse_something
(nit_code
)
313 if e
isa AModule then
314 local_toolctx
.had_error
= false
315 modelbuilder
.load_rt_module
(self.mainmodule
, e
, "rt_module")
316 local_toolctx
.run_phases
([e
])
317 if local_toolctx
.had_error
then
318 modelbuilder
.model
.try_remove_module
(e
.mmodule
.as(not null))
319 local_toolctx
.dbg
= null
324 self.mainmodule
= mmod
325 var local_classdefs
= mmod
.mclassdefs
326 var sys_type
= mmod
.sys_type
327 if sys_type
== null then
328 print
"Fatal error, cannot find Class Sys !\nAborting"
331 var mobj
= new MutableInstance(sys_type
)
333 var initprop
= mmod
.try_get_primitive_method
("init", sys_type
.mclass
)
334 if initprop
!= null then
335 self.send
(initprop
, [mobj
])
337 self.check_init_instance
(mobj
)
338 var mainprop
= mmod
.try_get_primitive_method
("main", sys_type
.mclass
)
339 if mainprop
!= null then
340 self.rt_send
(mainprop
, [mobj
])
343 print
"Error while loading_rt_module"
346 print
"Error when parsing, e = {e.class_name}"
348 local_toolctx
.dbg
= null
351 # Encpasulates the behaviour for step over/out
352 private fun steps_fun_call
(n
: AExpr)
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
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
364 else if step_in_trigger
then
365 n
.debug
("Execute stmt {n.to_s}")
366 while read_cmd
do end
370 # Checks if a breakpoint is encountered, and launches the debugging prompt if true
371 private fun breakpoint_check
(n
: AExpr)
373 var currFileNameSplit
= self.frame
.current_node
.location
.file
.filename
.to_s
.split_with
("/")
375 self.curr_file
= currFileNameSplit
[currFileNameSplit
.length-1
]
377 var breakpoint
= find_breakpoint
(curr_file
, n
.location
.line_start
)
379 if breakpoints
.keys
.has
(curr_file
) and breakpoint
!= null then
383 if not breakpoint
.is_valid
385 remove_breakpoint
(curr_file
, n
.location
.line_start
)
388 n
.debug
("Execute stmt {n.to_s}")
389 while read_cmd
do end
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)
397 var identifiers_in_instruction
= get_identifiers_in_current_instruction
(n
.location
.text
)
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
411 # Function remapping all the traced objects to match their name in the local context
412 private fun remap
(n
: AExpr)
414 if self.aftermath
then
416 # Trace every argument variable pre-specified
417 if self.frame_count_aftermath
< frames
.length
and fun_call_arguments_positions
.length
> 0 then
419 var ids_in_fun_def
= get_identifiers_in_current_instruction
(get_function_arguments
(frame
.mpropdef
.location
.text
))
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
])
426 self.aftermath
= false
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
))
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
452 #######################################################################
453 ## Processing commands functions ##
454 #######################################################################
459 return process_debug_command
(gets
)
462 # Takes a user command as a parameter
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
469 if command
== "finish"
473 else if command
== "s"
477 else if command
== "n" then
479 # Opens a new NitIndex prompt on current model
480 else if command
== "nitx" then
481 new NitIndex.with_infos
(modelbuilder
, self.mainmodule
).prompt
483 # Continues execution until the end
484 else if command
== "c" then
486 else if command
== "nit" then
489 var nit_buf
= new Buffer
490 while not command
== ":q" do
491 nit_buf
.append
(command
)
498 else if command
== "quit" then
500 else if command
== "abort" then
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"
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)
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"
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
)
533 print
"Unknown command \"{command}\
""
539 #######################################################################
540 ## Processing specific command functions ##
541 #######################################################################
543 # Sets the flags to step-over an instruction in the current file
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
553 #Sets the flags to step-out of a function
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
563 # Sets the flags to step-in an instruction
566 self.step_in_trigger
= true
567 self.stop_after_step_over_trigger
= false
568 self.stop_after_step_out_trigger
= false
572 # Sets the flags to continue execution
573 fun continue_exec
: Bool
575 self.stop_after_step_over_trigger
= false
576 self.stop_after_step_out_trigger
= false
577 self.step_in_trigger
= false
581 # Prints the demanded variable in the command
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])
586 if parts_of_command
[1] == "*" then
587 var map_of_instances
= frame
.map
589 var keys
= map_of_instances
.iterator
591 print
"Variables collection : \n"
593 for instance
in map_of_instances
.keys
do
594 print
"Variable {instance.to_s}, Instance {map_of_instances[instance].to_s}"
597 print
"\nEnd of current instruction \n"
598 else if parts_of_command
[1] == "stack" then
599 print
self.stack_trace
600 else if parts_of_command
[1].has
('[') and parts_of_command
[1].has
(']') then
601 process_array_command
(parts_of_command
)
603 var instance
= seek_variable
(get_real_variable_name
(parts_of_command
[1]), frame
)
607 print_instance
(instance
)
609 print
"Cannot find variable {parts_of_command[1]}"
614 # Processes the input string to know where to put a breakpoint
615 fun process_place_break_fun
(parts_of_command
: Array[String])
617 var bp
= get_breakpoint_from_command
(parts_of_command
)
623 # Returns a breakpoint containing the informations stored in the command
624 fun get_breakpoint_from_command
(parts_of_command
: Array[String]): nullable Breakpoint
626 if parts_of_command
[1].is_numeric
then
627 return new Breakpoint(parts_of_command
[1].to_i
, curr_file
)
628 else if parts_of_command
.length
>= 3 and parts_of_command
[2].is_numeric
then
629 return new Breakpoint(parts_of_command
[2].to_i
, parts_of_command
[1])
635 # Processes the command of removing a breakpoint on specified line and file
636 fun process_remove_break_fun
(parts_of_command
: Array[String])
638 if parts_of_command
[1].is_numeric
then
639 remove_breakpoint
(self.curr_file
, parts_of_command
[1].to_i
)
640 else if parts_of_command
.length
>= 3 and parts_of_command
[2].is_numeric
then
641 remove_breakpoint
(parts_of_command
[1], parts_of_command
[2].to_i
)
645 # Processes an array print command
646 fun process_array_command
(parts_of_command
: Array[String])
648 var index_of_first_brace
= parts_of_command
[1].index_of
('[')
649 var variable_name
= get_real_variable_name
(parts_of_command
[1].substring
(0,index_of_first_brace
))
650 var braces
= parts_of_command
[1].substring_from
(index_of_first_brace
)
652 var indexes
= remove_braces
(braces
)
654 var index_array
= new Array[Array[Int]]
656 if indexes
!= null then
657 for index
in indexes
do
658 var temp_indexes_array
= process_index
(index
)
659 if temp_indexes_array
!= null then
660 index_array
.push
(temp_indexes_array
)
661 #print index_array.last
666 var instance
= seek_variable
(variable_name
, frame
)
668 if instance
!= null then
669 print_nested_collection
(instance
, index_array
, 0, variable_name
, "")
671 print
"Cannot find variable {variable_name}"
675 # Processes the modification function to modify a variable dynamically
677 # Command of type variable = value
678 fun process_mod_function
(parts_of_command
: Array[String])
680 parts_of_command
[0] = get_real_variable_name
(parts_of_command
[0])
681 var parts_of_variable
= parts_of_command
[0].split_with
(".")
683 if parts_of_variable
.length
> 1 then
684 var last_part
= parts_of_variable
.pop
685 var first_part
= parts_of_command
[0].substring
(0,parts_of_command
[0].length
- last_part
.length
- 1)
686 var papa
= seek_variable
(first_part
, frame
)
688 if papa
!= null and papa
isa MutableInstance then
689 var attribute
= get_attribute_in_mutable_instance
(papa
, last_part
)
691 if attribute
!= null then
692 modify_argument_of_complex_type
(papa
, attribute
, parts_of_command
[2])
696 var target
= seek_variable
(parts_of_variable
[0], frame
)
697 if target
!= null then
698 modify_in_frame
(target
, parts_of_command
[2])
703 # Processes the untrace variable command
705 # Command pattern : "untrace variable"
706 fun process_untrace_command
(parts_of_command
: Array[String])
708 var variable_name
= get_real_variable_name
(parts_of_command
[1])
709 if untrace_variable
(variable_name
) then
710 print
"Untraced variable {parts_of_command[1]}"
712 print
"{parts_of_command[1]} is not traced"
716 # Processes the trace variable command
718 # Command pattern : "trace variable [break/print]"
719 fun process_trace_command
(parts_of_command
: Array[String])
721 var variable_name
= get_real_variable_name
(parts_of_command
[1])
724 if seek_variable
(variable_name
, frame
) == null then
725 print
"Cannot find a variable called {parts_of_command[1]}"
729 if parts_of_command
.length
== 3 then
730 if parts_of_command
[2] == "break" then
739 trace_variable
(variable_name
, breaker
)
741 print
"Successfully tracing {parts_of_command[1]}"
744 #######################################################################
745 ## Trace Management functions ##
746 #######################################################################
748 # Effectively untraces the variable called *variable_name*
750 # Returns true if the variable exists, false otherwise
751 private fun untrace_variable
(variable_name
: String): Bool
753 var to_remove
: nullable TraceObject = null
754 for i
in self.traces
do
755 if i
.is_variable_traced_in_frame
(variable_name
, frame
) then
760 if to_remove
!= null then
761 self.traces
.remove
(to_remove
)
768 # Effectively traces the variable *variable_name* either in print or break mode depending on the value of breaker (break if true, print if false)
770 private fun trace_variable
(variable_name
: String, breaker
: Bool)
772 for i
in self.traces
do
773 if i
.is_variable_traced_in_frame
(variable_name
, frame
) then
774 print
"This variable is already traced"
779 var trace_object
: TraceObject
782 trace_object
= new TraceObject(true)
784 trace_object
= new TraceObject(false)
787 # We trace the current variable found for the current frame
788 trace_object
.add_frame_variable
(self.frame
, variable_name
)
790 var position_of_variable_in_arguments
= get_position_of_variable_in_arguments
(frame
, variable_name
)
792 # Start parsing the frames starting with the parent of the current one, until the highest
793 # When the variable traced is declared locally, the loop stops
794 for i
in [1 .. frames
.length-1
] do
796 # If the variable was reported to be an argument of the previous frame
797 if position_of_variable_in_arguments
!= -1 then
799 var local_name
= get_identifiers_in_current_instruction
(get_function_arguments
(frames
[i
].current_node
.location
.text
))[position_of_variable_in_arguments
]
801 position_of_variable_in_arguments
= get_position_of_variable_in_arguments
(frames
[i
], local_name
)
803 trace_object
.add_frame_variable
(frames
[i
], local_name
)
809 self.traces
.add
(trace_object
)
812 # If the variable *variable_name* is an argument of the function being executed in the frame *frame*
813 # The function returns its position in the arguments
814 # Else, it returns -1
815 private fun get_position_of_variable_in_arguments
(frame
: Frame, variable_name
: String): Int
817 var identifiers
= get_identifiers_in_current_instruction
(get_function_arguments
(frame
.mpropdef
.location
.text
))
818 for i
in [0 .. identifiers
.length-1
] do
819 # If the current traced variable is an argument of the current function, we trace its parent (at least)
820 if identifiers
[i
] == variable_name
then return i
825 # Gets all the identifiers of an instruction (uses the rules of Nit as of Mar 05 2013)
827 fun get_identifiers_in_current_instruction
(instruction
: AbstractString): Array[String]
829 var result_array
= new Array[String]
830 var instruction_buffer
= new Buffer
832 var trigger_char_escape
= false
833 var trigger_string_escape
= false
834 var trigger_concat_in_string
= false
836 for i
in instruction
do
837 if trigger_char_escape
then
838 if i
== '\'' then trigger_char_escape = false
839 else if trigger_string_escape then
841 trigger_concat_in_string = true
842 trigger_string_escape = false
843 else if i == '\
"' then trigger_string_escape = false
845 if i.is_alphanumeric or i == '_' then
846 instruction_buffer.add(i)
847 else if i == '.' then
848 if instruction_buffer.is_numeric or (instruction_buffer[0] >= 'A' and instruction_buffer[0] <= 'Z') then
849 instruction_buffer.clear
851 result_array.push(instruction_buffer.to_s)
852 instruction_buffer.add(i)
854 else if i == '\'' then
855 trigger_char_escape = true
856 else if i == '\"' then
857 trigger_string_escape = true
858 else if i == '}' then
859 trigger_concat_in_string = false
860 trigger_string_escape = true
862 if instruction_buffer.length > 0 and not instruction_buffer.is_numeric and not (instruction_buffer[0] >= 'A
' and instruction_buffer[0] <= 'Z
') then result_array.push(instruction_buffer.to_s)
863 instruction_buffer.clear
868 if instruction_buffer.length > 0 and not instruction_buffer.is_numeric and not (instruction_buffer[0] >= 'A
' and instruction_buffer[0] <= 'Z
') then result_array.push(instruction_buffer.to_s)
873 # Takes a function call or declaration and strips all but the arguments
875 fun get_function_arguments(function: AbstractString): String
878 var trigger_copy = false
881 if i == ')' then break
882 if trigger_copy then buf.add(i)
883 if i == '(' then trigger_copy = true
889 #######################################################################
890 ## Alias management functions ##
891 #######################################################################
893 # Adds a new alias to the tables
894 fun add_alias(var_represented: String, alias: String)
896 self.aliases[alias] = var_represented
899 # Gets the real name of a variable hidden by an alias
900 fun get_variable_name_by_alias(alias: String): nullable String
902 if self.aliases.keys.has(alias) then
903 return self.aliases[alias]
909 # Gets the variable named by name, whether it is an alias or not
910 fun get_real_variable_name(name: String): String
912 var explode_string = name.split_with(".")
913 var final_string = new Buffer
914 for i in explode_string do
915 var alias_resolved = get_variable_name_by_alias(i)
916 if alias_resolved != null then
917 final_string.append(get_real_variable_name(alias_resolved))
919 final_string.append(i)
921 final_string.append(".")
924 return final_string.substring(0,final_string.length-1).to_s
927 #######################################################################
928 ## Print functions ##
929 #######################################################################
931 # Prints an object instance and its attributes if it has some
933 # If it is a primitive type, its value is directly printed
934 fun print_instance(instance: Instance)
936 print "Printing innards of a variable"
938 if instance isa MutableInstance then
939 var attributes = instance.attributes
940 print "Object : {instance}"
942 for current_attribute in attributes.keys do
943 print "Attribute : {current_attribute.to_s} \nValeur : {attributes[current_attribute].to_s}"
946 print "Found variable {instance}"
949 print "Stopping printing innards of a variable"
952 # Prints the attributes demanded in a SequenceRead
953 # Used recursively to print nested collections
954 fun print_nested_collection(instance: Instance, indexes: Array[Array[Int]], depth: Int, variable_name: String, depth_string: String)
956 var collection: nullable SequenceRead[Object] = null
957 var real_collection_length: nullable Int = null
959 if instance isa MutableInstance then
960 real_collection_length = get_collection_instance_real_length(instance)
961 collection = get_primary_collection(instance)
964 if collection != null and real_collection_length != null then
965 for i in indexes[depth] do
966 if i >= 0 and i < real_collection_length then
967 if depth == indexes.length-1 then
968 print "{variable_name}{depth_string}[{i}] = {collection[i]}"
970 var item_i = collection[i]
972 if item_i isa MutableInstance then
973 print_nested_collection(item_i, indexes, depth+1, variable_name, depth_string+"[{i}]")
975 print "The item at {variable_name}{depth_string}[{i}] is not a collection"
980 print "Out of bounds exception : i = {i} and collection_length = {real_collection_length.to_s}"
984 else if i >= real_collection_length then
990 if collection == null then
991 print "Cannot find {variable_name}{depth_string}"
992 else if real_collection_length != null then
993 print "Cannot find attribute length in {instance}"
995 print "Unknown error."
1001 #######################################################################
1002 ## Variable Exploration functions ##
1003 #######################################################################
1005 # Seeks a variable from the current frame called 'variable_path
', can introspect complex objects using function get_variable_in_mutable_instance
1006 private fun seek_variable(variable_path: String, frame: Frame): nullable Instance
1008 var full_variable = variable_path.split_with(".")
1010 var full_variable_iterator = full_variable.iterator
1012 var first_instance = get_variable_in_frame(full_variable_iterator.item, frame)
1014 if first_instance == null then return null
1016 if full_variable.length <= 1 then return first_instance
1018 full_variable_iterator.next
1020 if not (first_instance isa MutableInstance and full_variable_iterator.is_ok) then return null
1022 return get_variable_in_mutable_instance(first_instance, full_variable_iterator)
1025 # Gets a variable 'variable_name
' contained in the frame 'frame
'
1026 private fun get_variable_in_frame(variable_name: String, frame: Frame): nullable Instance
1028 if variable_name == "self" then
1029 if frame.arguments.length >= 1 then return frame.arguments.first
1032 var map_of_instances = frame.map
1034 for key in map_of_instances.keys do
1035 if key.to_s == variable_name then
1036 return map_of_instances[key]
1043 # Gets an attribute 'attribute_name
' contained in variable 'variable
'
1044 fun get_attribute_in_mutable_instance(variable: MutableInstance, attribute_name: String): nullable MAttribute
1046 var map_of_attributes = variable.attributes
1048 for key in map_of_attributes.keys do
1049 if key.to_s.substring_from(1) == attribute_name then
1057 # Recursive function, returns the variable described by 'total_chain
'
1058 fun get_variable_in_mutable_instance(variable: MutableInstance, iterator: Iterator[String]): nullable Instance
1060 var attribute = get_attribute_in_mutable_instance(variable, iterator.item)
1062 if attribute == null then return null
1066 if iterator.is_ok then
1067 var new_variable = variable.attributes[attribute]
1068 if new_variable isa MutableInstance then
1069 return get_variable_in_mutable_instance(new_variable, iterator)
1074 return variable.attributes[attribute]
1078 #######################################################################
1079 ## Array exploring functions ##
1080 #######################################################################
1082 # Gets the length of a collection
1083 # Used by the debugger, else if we call Collection.length, it returns the capacity instead
1084 fun get_collection_instance_real_length(collection: MutableInstance): nullable Int
1086 var collection_length_attribute = get_attribute_in_mutable_instance(collection, "length")
1088 var real_collection_length: nullable Int = null
1090 if collection_length_attribute != null then
1091 var primitive_length_instance = collection.attributes[collection_length_attribute]
1092 if primitive_length_instance isa PrimitiveInstance[Int] then
1093 return primitive_length_instance.val
1100 # Processes the indexes of a print array call
1101 # Returns an array containing all the indexes demanded
1102 fun process_index(index_string: String): nullable Array[Int]
1104 var from_end_index = index_string.index_of('.')
1105 var to_start_index = index_string.last_index_of('.')
1107 if from_end_index != -1 and to_start_index != -1 then
1108 var index_from_string = index_string.substring(0,from_end_index)
1109 var index_to_string = index_string.substring_from(to_start_index+1)
1111 if index_from_string.is_numeric and index_to_string.is_numeric then
1112 var result_array = new Array[Int]
1114 var index_from = index_from_string.to_i
1115 var index_to = index_to_string.to_i
1117 for i in [index_from..index_to] do
1118 result_array.push(i)
1124 if index_string.is_numeric
1126 var result_array = new Array[Int]
1128 result_array.push(index_string.to_i)
1139 # Gets a collection in a MutableInstance
1140 fun get_primary_collection(container: MutableInstance): nullable SequenceRead[Object]
1142 var items_of_array = get_attribute_in_mutable_instance(container, "items")
1143 if items_of_array != null then
1144 var array = container.attributes[items_of_array]
1146 if array isa PrimitiveInstance[Object] then
1147 var sequenceRead_final = array.val
1148 if sequenceRead_final isa SequenceRead[Object] then
1149 return sequenceRead_final
1157 # Removes the braces '[' ']' in a print array command
1158 # Returns an array containing their content
1159 fun remove_braces(braces: String): nullable Array[String]
1161 var buffer = new Buffer
1163 var result_array = new Array[String]
1165 var number_of_opening_brackets = 0
1166 var number_of_closing_brackets = 0
1168 var last_was_opening_bracket = false
1172 if last_was_opening_bracket then
1176 number_of_opening_brackets += 1
1177 last_was_opening_bracket = true
1178 else if i == ']' then
1179 if not last_was_opening_bracket then
1183 result_array.push(buffer.to_s)
1185 number_of_closing_brackets += 1
1186 last_was_opening_bracket = false
1187 else if i.is_numeric or i == '.' then
1188 buffer.append(i.to_s)
1189 else if not i == ' ' then
1194 if number_of_opening_brackets != number_of_closing_brackets then
1201 #######################################################################
1202 ## Breakpoint placing functions ##
1203 #######################################################################
1205 # Places a breakpoint on line 'line_to_break
' for file 'file_to_break
'
1206 fun place_breakpoint(breakpoint: Breakpoint)
1208 if not self.breakpoints.keys.has(breakpoint.file) then
1209 self.breakpoints[breakpoint.file] = new HashSet[Breakpoint]
1211 if find_breakpoint(breakpoint.file, breakpoint.line) == null then
1212 self.breakpoints[breakpoint.file].add(breakpoint)
1213 print "Breakpoint added on line {breakpoint.line} for file {breakpoint.file}"
1215 print "Breakpoint already present on line {breakpoint.line} for file {breakpoint.file}"
1219 #Places a breakpoint that will trigger once and be destroyed afterwards
1220 fun process_place_tbreak_fun(parts_of_command: Array[String])
1222 var bp = get_breakpoint_from_command(parts_of_command)
1225 bp.set_max_breaks(1)
1226 place_breakpoint(bp)
1230 #######################################################################
1231 ## Breakpoint removing functions ##
1232 #######################################################################
1234 # Removes a breakpoint on line 'line_to_break
' for file 'file_to_break
'
1235 fun remove_breakpoint(file_to_break: String, line_to_break: Int)
1237 if self.breakpoints.keys.has(file_to_break) then
1238 var bp = find_breakpoint(file_to_break, line_to_break)
1241 self.breakpoints[file_to_break].remove(bp)
1242 print "Breakpoint removed on line {line_to_break} for file {file_to_break}"
1247 print "No breakpoint existing on line {line_to_break} for file {file_to_break}"
1250 #######################################################################
1251 ## Breakpoint searching functions ##
1252 #######################################################################
1254 # Finds a breakpoint for 'file
' and 'line
' in the class HashMap
1255 fun find_breakpoint(file: String, line: Int): nullable Breakpoint
1257 if self.breakpoints.keys.has(file)
1259 for i in self.breakpoints[file]
1271 #######################################################################
1272 ## Runtime modification functions ##
1273 #######################################################################
1275 # Modifies the value of a variable contained in a frame
1276 fun modify_in_frame(variable: Instance, value: String)
1278 var new_variable = get_variable_of_type_with_value(variable.mtype.to_s, value)
1279 if new_variable != null
1281 var keys = frame.map.keys
1284 if frame.map[key] == variable
1286 frame.map[key] = new_variable
1292 # Modifies the value of a variable contained in a MutableInstance
1293 fun modify_argument_of_complex_type(papa: MutableInstance, attribute: MAttribute, value: String)
1295 var final_variable = papa.attributes[attribute]
1296 var type_of_variable = final_variable.mtype.to_s
1297 var new_variable = get_variable_of_type_with_value(type_of_variable, value)
1298 if new_variable != null
1300 papa.attributes[attribute] = new_variable
1304 #######################################################################
1305 ## Variable generator functions ##
1306 #######################################################################
1308 # Returns a new variable of the type 'type_of_variable
' with a value of 'value
'
1309 fun get_variable_of_type_with_value(type_of_variable: String, value: String): nullable Instance
1311 if type_of_variable == "Int" then
1312 return get_int(value)
1313 else if type_of_variable == "Float" then
1314 return get_float(value)
1315 else if type_of_variable == "Bool" then
1316 return get_bool(value)
1317 else if type_of_variable == "Char" then
1318 return get_char(value)
1324 # Returns a new int instance with value 'value
'
1325 fun get_int(value: String): nullable Instance
1327 if value.is_numeric then
1328 return int_instance(value.to_i)
1334 # Returns a new float instance with value 'value
'
1335 fun get_float(value:String): nullable Instance
1337 if value.is_numeric then
1338 return float_instance(value.to_f)
1344 # Returns a new char instance with value 'value
'
1345 fun get_char(value: String): nullable Instance
1347 if value.length >= 1 then
1348 return char_instance(value[0])
1354 # Returns a new bool instance with value 'value
'
1355 fun get_bool(value: String): nullable Instance
1357 if value.to_lower == "true" then
1358 return self.true_instance
1359 else if value.to_lower == "false" then
1360 return self.false_instance
1362 print "Invalid value, a boolean must be set at \"true\" or \"false\""
1369 redef class AConcreteMethPropdef
1371 # Same as call except it will copy local variables of the parent frame to the frame defined in this call.
1372 # Not supposed to be used by anyone else than the Debugger.
1373 private fun rt_call(v: Debugger, mpropdef: MMethodDef, args: Array[Instance]): nullable Instance
1375 var f = new Frame(self, self.mpropdef.as(not null), args)
1376 var curr_instances = v.frame.map
1377 for i in curr_instances.keys do
1378 f.map[i] = curr_instances[i]
1380 call_commons(v,mpropdef,args,f)
1381 var currFra = v.frames.shift
1382 for i in curr_instances.keys do
1383 if currFra.map.keys.has(i) then
1384 curr_instances[i] = currFra.map[i]
1387 if v.returnmark == f then
1389 var res = v.escapevalue
1390 v.escapevalue = null
1398 # Traces the modifications of an object linked to a certain frame
1399 private class TraceObject
1401 # Map of the local names bound to a frame
1402 var trace_map: HashMap[Frame, String]
1403 # Decides if breaking or printing statement when the variable is encountered
1404 var break_on_encounter: Bool
1406 init(break_on_encounter: Bool)
1408 trace_map = new HashMap[Frame, String]
1409 self.break_on_encounter = break_on_encounter
1412 # Adds the local alias for a variable and the frame bound to it
1413 fun add_frame_variable(frame: Frame, variable_name: String)
1415 self.trace_map[frame] = variable_name
1418 # Checks if the prompted variable is traced in the specified frame
1419 fun is_variable_traced_in_frame(variable_name: String, frame: Frame): Bool
1421 if self.trace_map.has_key(frame) then
1422 if self.trace_map[frame] == variable_name then
1434 # Breaks automatically when encountering an error
1435 # Permits the injunction of commands before crashing
1436 redef private fun fatal(v: NaiveInterpreter, message: String)
1438 if v isa Debugger then
1439 print "An error was encountered, the program will stop now."
1441 while v.process_debug_command(gets) do end