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
20 intrude import naive_interpreter
22 intrude import semantize
::local_var_init
23 intrude import semantize
::scope
24 intrude import toolcontext
25 private import parser_util
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
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 m
.text
.search
("Warning") == null then had_error
= true
113 sys
.stderr
.write
("{m.to_color_string}\n")
123 var opt_debugger_mode
= new OptionBool("Launches the target program with the debugger attached to it", "-d")
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")
130 self.option_context
.add_option
(self.opt_debugger_mode
)
131 self.option_context
.add_option
(self.opt_debugger_autorun
)
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
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])
145 self.toolcontext
.info
("*** START INTERPRETING ***", 1)
147 var interpreter
= new Debugger(self, mainmodule
, arguments
)
149 interpreter
.start
(mainmodule
)
152 self.toolcontext
.info
("*** END INTERPRETING: {time1-time0} ***", 2)
155 fun run_debugger_autorun
(mainmodule
: MModule, arguments
: Array[String])
158 self.toolcontext
.info
("*** START INTERPRETING ***", 1)
160 var interpreter
= new Debugger(self, mainmodule
, arguments
)
161 interpreter
.autocontinue
= true
163 interpreter
.start
(mainmodule
)
166 self.toolcontext
.info
("*** END INTERPRETING: {time1-time0} ***", 2)
170 # Contains all the informations of a Breakpoint for the Debugger
176 # File concerned by the breakpoint
180 if not file
.has_suffix
(".nit") then file
+= ".nit"
184 # The class extending `NaiveInterpreter` by adding debugging methods
186 super NaiveInterpreter
188 # Keeps the frame count in memory to find when to stop
189 # and launch the command prompt after a step out call
190 var step_stack_count
= 1
192 # Triggers a step over an instruction in a nit program
193 var stop_after_step_over_trigger
= true
195 # Triggers a step out of an instruction
196 var stop_after_step_out_trigger
= false
198 # Triggers a step in a instruction (enters a function
199 # if the instruction is a function call)
200 var step_in_trigger
= false
202 # HashMap containing the breakpoints bound to a file
203 var breakpoints
= new HashMap[String, HashSet[Breakpoint]]
205 # Contains the current file
208 # Aliases hashmap (maps an alias to a variable name)
209 var aliases
= new HashMap[String, String]
211 # Set containing all the traced variables and their related frame
212 private var traces
= new HashSet[TraceObject]
214 # Map containing all the positions for the positions of the arguments traced
216 private var fun_call_arguments_positions
= new HashMap[Int, TraceObject]
218 # Triggers the remapping of a trace object in the local context after a function call
219 var aftermath
= false
221 # Used to prevent the case when the body of the function called is empty
222 # If it is not, then, the remapping won't be happening
223 var frame_count_aftermath
= 1
225 # Auto continues the execution until the end or until an error is encountered
226 var autocontinue
= false
228 #######################################################################
229 ## Execution of statement function ##
230 #######################################################################
232 # Main loop, every call to a debug command is done here
233 redef fun stmt
(n
: nullable AExpr)
235 if n
== null then return
237 var frame
= self.frame
238 var old
= frame
.current_node
239 frame
.current_node
= n
241 if sys
.stdin
.poll_in
then process_debug_command
(gets
)
243 if not self.autocontinue
then
244 if not n
isa ABlockExpr then
249 check_funcall_and_traced_args
(n
)
253 check_if_vars_are_traced
(n
)
258 frame
.current_node
= old
261 # 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.
262 # 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.
263 fun rt_send
(mproperty
: MMethod, args
: Array[Instance]): nullable Instance
265 var recv
= args
.first
266 var mtype
= recv
.mtype
267 var ret
= send_commons
(mproperty
, args
, mtype
)
268 if ret
!= null then return ret
269 var propdef
= mproperty
.lookup_first_definition
(self.mainmodule
, mtype
)
270 return self.rt_call
(propdef
, args
)
273 # Same as a regular call but for a runtime injected module
274 fun rt_call
(mpropdef
: MMethodDef, args
: Array[Instance]): nullable Instance
276 if self.modelbuilder
.toolcontext
.opt_discover_call_trace
.value
and not self.discover_call_trace
.has
(mpropdef
) then
277 self.discover_call_trace
.add mpropdef
278 self.debug
("Discovered {mpropdef}")
280 assert args
.length
== mpropdef
.msignature
.arity
+ 1 else debug
("Invalid arity for {mpropdef}. {args.length} arguments given.")
282 # Look for the AST node that implements the property
283 var mproperty
= mpropdef
.mproperty
284 if self.modelbuilder
.mpropdef2npropdef
.has_key
(mpropdef
) then
285 var npropdef
= self.modelbuilder
.mpropdef2npropdef
[mpropdef
]
286 self.parameter_check
(npropdef
, mpropdef
, args
)
287 if npropdef
isa AMethPropdef then
288 return npropdef
.rt_call
(self, mpropdef
, args
)
290 print
"Error, invalid propdef to call at runtime !"
293 else if mproperty
.is_root_init
then
294 var nclassdef
= self.modelbuilder
.mclassdef2nclassdef
[mpropdef
.mclassdef
]
295 self.parameter_check
(nclassdef
, mpropdef
, args
)
296 return nclassdef
.call
(self, mpropdef
, args
)
298 fatal
("Fatal Error: method {mpropdef} not found in the AST")
303 # Evaluates dynamically a snippet of Nit code
304 # `nit_code` : Nit code to be executed
305 fun eval
(nit_code
: String)
307 var local_toolctx
= modelbuilder
.toolcontext
308 local_toolctx
.dbg
= self
309 var e
= local_toolctx
.parse_something
(nit_code
)
310 if e
isa ABlockExpr then
311 nit_code
= "module rt_module\n" + nit_code
312 e
= local_toolctx
.parse_something
(nit_code
)
315 nit_code
= "module rt_module\nprint " + nit_code
316 e
= local_toolctx
.parse_something
(nit_code
)
318 if e
isa AModule then
319 local_toolctx
.had_error
= false
320 modelbuilder
.load_rt_module
(self.mainmodule
, e
, "rt_module")
321 local_toolctx
.run_phases
([e
])
322 if local_toolctx
.had_error
then
323 modelbuilder
.model
.try_remove_module
(e
.mmodule
.as(not null))
324 local_toolctx
.dbg
= null
329 self.mainmodule
= mmod
330 var sys_type
= mmod
.sys_type
331 if sys_type
== null then
332 print
"Fatal error, cannot find Class Sys !\nAborting"
335 var mobj
= new MutableInstance(sys_type
)
337 var initprop
= mmod
.try_get_primitive_method
("init", sys_type
.mclass
)
338 if initprop
!= null then
339 self.send
(initprop
, [mobj
])
341 var mainprop
= mmod
.try_get_primitive_method
("run", sys_type
.mclass
) or else
342 mmod
.try_get_primitive_method
("main", sys_type
.mclass
)
343 if mainprop
!= null then
344 self.rt_send
(mainprop
, [mobj
])
347 print
"Error while loading_rt_module"
350 print
"Error when parsing, e = {e.class_name}"
352 local_toolctx
.dbg
= null
355 # Encpasulates the behaviour for step over/out
356 private fun steps_fun_call
(n
: AExpr)
358 if self.stop_after_step_over_trigger
then
359 if self.frames
.length
<= self.step_stack_count
then
360 n
.debug
("Execute stmt {n.to_s}")
361 while read_cmd
do end
363 else if self.stop_after_step_out_trigger
then
364 if frames
.length
< self.step_stack_count
then
365 n
.debug
("Execute stmt {n.to_s}")
366 while read_cmd
do end
368 else if step_in_trigger
then
369 n
.debug
("Execute stmt {n.to_s}")
370 while read_cmd
do end
374 # Checks if a breakpoint is encountered, and launches the debugging prompt if true
375 private fun breakpoint_check
(n
: AExpr)
377 var currFileNameSplit
= self.frame
.current_node
.location
.file
.filename
.to_s
.split_with
("/")
379 self.curr_file
= currFileNameSplit
[currFileNameSplit
.length-1
]
381 var breakpoint
= find_breakpoint
(curr_file
, n
.location
.line_start
)
383 if breakpoints
.keys
.has
(curr_file
) and breakpoint
!= null then
384 n
.debug
("Execute stmt {n.to_s}")
385 while read_cmd
do end
389 # Check if a variable of current expression is traced
390 # Then prints and/or breaks for command prompt
391 private fun check_if_vars_are_traced
(n
: AExpr)
393 var identifiers_in_instruction
= get_identifiers_in_current_instruction
(n
.location
.text
)
395 for i
in identifiers_in_instruction
do
396 for j
in self.traces
do
397 if j
.is_variable_traced_in_frame
(i
, frame
) then
398 n
.debug
("Traced variable {i} used")
399 if j
.break_on_encounter
then while read_cmd
do end
406 # Function remapping all the traced objects to match their name in the local context
407 private fun remap
(n
: AExpr)
409 if self.aftermath
then
411 # Trace every argument variable pre-specified
412 if self.frame_count_aftermath
< frames
.length
and fun_call_arguments_positions
.length
> 0 then
414 var ids_in_fun_def
= get_identifiers_in_current_instruction
(get_function_arguments
(frame
.mpropdef
.location
.text
))
416 for i
in fun_call_arguments_positions
.keys
do
417 self.fun_call_arguments_positions
[i
].add_frame_variable
(frame
, ids_in_fun_def
[i
])
421 self.aftermath
= false
425 # If the current instruction is a function call
426 # We analyse its signature and the position of traced arguments if the call
427 # For future remapping when inside the function
428 private fun check_funcall_and_traced_args
(n
: AExpr) do
429 # If we have a function call, we need to see if any of the arguments is traced (including the caller)
430 # if it is, next time we face an instruction, we'll trace the local version on the traced variable in the next frame
431 if n
isa ACallExpr then
432 self.aftermath
= true
433 self.frame_count_aftermath
= frames
.length
434 fun_call_arguments_positions
.clear
435 var fun_arguments
= get_identifiers_in_current_instruction
(get_function_arguments
(n
.location
.text
))
437 for i
in self.traces
do
438 for j
in [0 .. fun_arguments
.length
- 1] do
439 if i
.is_variable_traced_in_frame
(fun_arguments
[j
],frame
) then
440 fun_call_arguments_positions
[j
] = i
447 #######################################################################
448 ## Processing commands functions ##
449 #######################################################################
454 return process_debug_command
(gets
)
457 # Takes a user command as a parameter
459 # Returns a boolean value, representing whether or not to
460 # continue reading commands from the console input
461 fun process_debug_command
(command
: String): Bool
464 if command
== "finish"
468 else if command
== "s"
472 else if command
== "n" then
475 else if command
== "help" then
478 # Opens a new NitIndex prompt on current model
479 else if command
== "nitx" then
480 new NitIndex.with_infos
(modelbuilder
, self.mainmodule
).prompt
482 else if command
== "bt" or command
== "backtrack" then
485 # Continues execution until the end
486 else if command
== "c" then
488 else if command
== "nit" then
491 var nit_buf
= new FlatBuffer
492 while not command
== ":q" do
493 nit_buf
.append
(command
)
500 else if command
== "quit" then
502 else if command
== "abort" then
506 var parts
= command
.split_with
(' ')
507 var cname
= parts
.first
508 # Shows the value of a variable in the current frame
509 if cname
== "p" or cname
== "print" then
511 # Places a breakpoint on line x of file y
512 else if cname
== "break" or cname
== "b" then
513 process_place_break_fun
(parts
)
514 # Removes a breakpoint on line x of file y
515 else if cname
== "d" or cname
== "delete" then
516 process_remove_break_fun
(parts
)
517 # Sets an alias for a variable
518 else if parts
.length
== 2 and parts
[1] == "as" then
520 # Modifies the value of a variable in the current frame
521 else if parts
.length
== 3 and parts
[1] == "=" then
522 process_mod_function
(parts
)
523 # Traces the modifications on a variable
524 else if cname
== "trace" then
525 process_trace_command
(parts
)
526 # Untraces the modifications on a variable
527 else if cname
== "untrace" then
528 process_untrace_command
(parts
)
536 # Produces help for the commands of the debugger
540 print
"-----------------------------------"
543 print
" * Modification: var_name = value (Warning: var_name must be primitive)"
544 print
" * Alias: var_name as alias"
547 print
" * Variables: p(rint) var_name (Use * to print all local variables)"
548 print
" * Collections: p(rint) var_name '[' start_index (.. end_index) ']'"
551 print
" * File/line: b(reak) file_name line_number"
552 print
" * Remove: d(elete) id"
555 print
" * Variable: trace var_name break/print"
556 print
" * Untrace variable: untrace var_name"
559 print
" * Next instruction (same-level): n"
560 print
" * Next instruction: s"
561 print
" * Finish current method: finish"
562 print
" * Continue until next breakpoint or end: c"
564 print
"General commands"
565 print
" * quit: Quits the debugger"
566 print
" * abort: Aborts the interpretation, prints the stack trace before leaving"
567 print
" * nitx: Ask questions to the model about its entities (classes, methods, etc.)"
568 print
" * nit: Inject dynamic code for interpretation"
572 #######################################################################
573 ## Processing specific command functions ##
574 #######################################################################
576 # Sets the flags to step-over an instruction in the current file
579 self.step_stack_count
= frames
.length
580 self.stop_after_step_over_trigger
= true
581 self.stop_after_step_out_trigger
= false
582 self.step_in_trigger
= false
586 #Sets the flags to step-out of a function
589 self.stop_after_step_over_trigger
= false
590 self.stop_after_step_out_trigger
= true
591 self.step_in_trigger
= false
592 self.step_stack_count
= frames
.length
596 # Sets the flags to step-in an instruction
599 self.step_in_trigger
= true
600 self.stop_after_step_over_trigger
= false
601 self.stop_after_step_out_trigger
= false
605 # Sets the flags to continue execution
606 fun continue_exec
: Bool
608 self.stop_after_step_over_trigger
= false
609 self.stop_after_step_out_trigger
= false
610 self.step_in_trigger
= false
614 fun bad_command
(cmd
: String) do
615 print
"Unrecognized command {cmd}. Use 'help' to show help."
618 # Prints the demanded variable in the command
620 # The name of the variable in in position 1 of the array 'parts_of_command'
621 fun print_command
(parts
: Array[String])
623 if parts
.length
!= 2 then
624 bad_command
(parts
.join
(" "))
627 if parts
[1] == "*" then
628 var map_of_instances
= frame
.map
630 var self_var
= seek_variable
("self", frame
)
631 print
"self: {self_var.to_s}"
633 for instance
in map_of_instances
.keys
do
634 print
"{instance.to_s}: {map_of_instances[instance].to_s}"
636 else if parts
[1].chars
.has
('[') and parts
[1].chars
.has
(']') then
637 process_array_command
(parts
)
639 var instance
= seek_variable
(get_real_variable_name
(parts
[1]), frame
)
643 print_instance
(instance
)
645 print
"Cannot find variable {parts[1]}"
650 # Process the input command to set an alias for a variable
651 fun process_alias
(parts
: Array[String]) do
652 if parts
.length
!= 3 then
653 bad_command
(parts
.join
(" "))
656 add_alias
(parts
.first
, parts
.last
)
659 # Processes the input string to know where to put a breakpoint
660 fun process_place_break_fun
(parts
: Array[String])
662 if parts
.length
!= 3 then
663 bad_command
(parts
.join
(" "))
666 var bp
= get_breakpoint_from_command
(parts
)
672 # Returns a breakpoint containing the informations stored in the command
673 fun get_breakpoint_from_command
(parts
: Array[String]): nullable Breakpoint
675 if parts
[1].is_numeric
then
676 return new Breakpoint(parts
[1].to_i
, curr_file
)
677 else if parts
.length
>= 3 and parts
[2].is_numeric
then
678 return new Breakpoint(parts
[2].to_i
, parts
[1])
684 # Processes the command of removing a breakpoint on specified line and file
685 fun process_remove_break_fun
(parts
: Array[String])
687 if parts
.length
!= 2 then
688 bad_command
(parts
.join
(" "))
691 if parts
[1].is_numeric
then
692 remove_breakpoint
(self.curr_file
, parts
[1].to_i
)
693 else if parts
.length
>= 3 and parts
[2].is_numeric
then
694 remove_breakpoint
(parts
[1], parts
[2].to_i
)
698 # Processes an array print command
699 fun process_array_command
(parts
: Array[String])
701 var index_of_first_brace
= parts
[1].chars
.index_of
('[')
702 var variable_name
= get_real_variable_name
(parts
[1].substring
(0,index_of_first_brace
))
703 var braces
= parts
[1].substring_from
(index_of_first_brace
)
705 var indexes
= remove_braces
(braces
)
707 var index_array
= new Array[Array[Int]]
709 if indexes
!= null then
710 for index
in indexes
do
711 var temp_indexes_array
= process_index
(index
)
712 if temp_indexes_array
!= null then
713 index_array
.push
(temp_indexes_array
)
714 #print index_array.last
719 var instance
= seek_variable
(variable_name
, frame
)
721 if instance
!= null then
722 print_nested_collection
(instance
, index_array
, 0, variable_name
, "")
724 print
"Cannot find variable {variable_name}"
728 # Processes the modification function to modify a variable dynamically
730 # Command of type variable = value
731 fun process_mod_function
(parts
: Array[String])
733 if parts
.length
!= 3 then
734 bad_command
(parts
.join
(" "))
738 p0
= get_real_variable_name
(p0
)
739 var parts_of_variable
= p0
.split_with
(".")
741 if parts_of_variable
.length
> 1 then
742 var last_part
= parts_of_variable
.pop
743 var first_part
= p0
.substring
(0,p0
.length
- last_part
.length
- 1)
744 var papa
= seek_variable
(first_part
, frame
)
746 if papa
!= null and papa
isa MutableInstance then
747 var attribute
= get_attribute_in_mutable_instance
(papa
, last_part
)
749 if attribute
!= null then
750 modify_argument_of_complex_type
(papa
, attribute
, parts
[2])
754 var target
= seek_variable
(parts_of_variable
[0], frame
)
755 if target
!= null then
756 modify_in_frame
(target
, parts
[2])
761 # Processes the untrace variable command
763 # Command pattern : "untrace variable"
764 fun process_untrace_command
(parts
: Array[String])
766 if parts
.length
!= 2 then
767 bad_command
(parts
.join
(" "))
770 var variable_name
= get_real_variable_name
(parts
[1])
771 if untrace_variable
(variable_name
) then
772 print
"Untraced variable {parts[1]}"
774 print
"{parts[1]} is not traced"
778 # Processes the trace variable command
780 # Command pattern : "trace variable [break/print]"
781 fun process_trace_command
(parts
: Array[String])
783 if parts
.length
!= 3 then
784 bad_command
(parts
.join
(" "))
787 var variable_name
= get_real_variable_name
(parts
[1])
790 if seek_variable
(variable_name
, frame
) == null then
791 print
"Cannot find a variable called {parts[1]}"
795 if parts
[2] == "break" then
801 trace_variable
(variable_name
, breaker
)
803 print
"Successfully tracing {parts[1]}"
806 #######################################################################
807 ## Trace Management functions ##
808 #######################################################################
810 # Effectively untraces the variable called *variable_name*
812 # Returns true if the variable exists, false otherwise
813 private fun untrace_variable
(variable_name
: String): Bool
815 var to_remove
: nullable TraceObject = null
816 for i
in self.traces
do
817 if i
.is_variable_traced_in_frame
(variable_name
, frame
) then
822 if to_remove
!= null then
823 self.traces
.remove
(to_remove
)
830 # Effectively traces the variable *variable_name* either in print or break mode depending on the value of breaker (break if true, print if false)
832 private fun trace_variable
(variable_name
: String, breaker
: Bool)
834 for i
in self.traces
do
835 if i
.is_variable_traced_in_frame
(variable_name
, frame
) then
836 print
"This variable is already traced"
841 var trace_object
: TraceObject
844 trace_object
= new TraceObject(true)
846 trace_object
= new TraceObject(false)
849 # We trace the current variable found for the current frame
850 trace_object
.add_frame_variable
(self.frame
, variable_name
)
852 var position_of_variable_in_arguments
= get_position_of_variable_in_arguments
(frame
, variable_name
)
854 # Start parsing the frames starting with the parent of the current one, until the highest
855 # When the variable traced is declared locally, the loop stops
856 for i
in [1 .. frames
.length-1
] do
858 # If the variable was reported to be an argument of the previous frame
859 if position_of_variable_in_arguments
!= -1 then
861 var local_name
= get_identifiers_in_current_instruction
(get_function_arguments
(frames
[i
].current_node
.location
.text
))[position_of_variable_in_arguments
]
863 position_of_variable_in_arguments
= get_position_of_variable_in_arguments
(frames
[i
], local_name
)
865 trace_object
.add_frame_variable
(frames
[i
], local_name
)
871 self.traces
.add
(trace_object
)
874 # If the variable *variable_name* is an argument of the function being executed in the frame *frame*
875 # The function returns its position in the arguments
876 # Else, it returns -1
877 private fun get_position_of_variable_in_arguments
(frame
: Frame, variable_name
: String): Int
879 var identifiers
= get_identifiers_in_current_instruction
(get_function_arguments
(frame
.mpropdef
.location
.text
))
880 for i
in [0 .. identifiers
.length-1
] do
881 # If the current traced variable is an argument of the current function, we trace its parent (at least)
882 if identifiers
[i
] == variable_name
then return i
887 # Gets all the identifiers of an instruction (uses the rules of Nit as of Mar 05 2013)
889 fun get_identifiers_in_current_instruction
(instruction
: Text): Array[String]
891 var result_array
= new Array[String]
892 var instruction_buffer
= new FlatBuffer
894 var trigger_char_escape
= false
895 var trigger_string_escape
= false
897 for i
in instruction
.chars
do
898 if trigger_char_escape
then
899 if i
== '\'' then trigger_char_escape = false
900 else if trigger_string_escape then
902 trigger_string_escape = false
903 else if i == '\
"' then trigger_string_escape = false
905 if i.is_alphanumeric or i == '_' then
906 instruction_buffer.add(i)
907 else if i == '.' then
908 if instruction_buffer.is_numeric or (instruction_buffer.chars[0] >= 'A' and instruction_buffer.chars[0] <= 'Z') then
909 instruction_buffer.clear
911 result_array.push(instruction_buffer.to_s)
912 instruction_buffer.add(i)
914 else if i == '\'' then
915 trigger_char_escape = true
916 else if i == '\"' then
917 trigger_string_escape = true
918 else if i == '}' then
919 trigger_string_escape = true
921 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)
922 instruction_buffer.clear
927 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)
932 # Takes a function call or declaration and strips all but the arguments
934 fun get_function_arguments(function: Text): String
936 var buf = new FlatBuffer
937 var trigger_copy = false
939 for i in function.chars do
940 if i == ')' then break
941 if trigger_copy then buf.add(i)
942 if i == '(' then trigger_copy = true
948 #######################################################################
949 ## Alias management functions ##
950 #######################################################################
952 # Adds a new alias to the tables
953 fun add_alias(var_represented: String, alias: String)
955 self.aliases[alias] = var_represented
958 # Gets the real name of a variable hidden by an alias
959 fun get_variable_name_by_alias(alias: String): nullable String
961 if self.aliases.keys.has(alias) then
962 return self.aliases[alias]
968 # Gets the variable named by name, whether it is an alias or not
969 fun get_real_variable_name(name: String): String
971 var explode_string = name.split_with(".")
972 var final_string = new FlatBuffer
973 for i in explode_string do
974 var alias_resolved = get_variable_name_by_alias(i)
975 if alias_resolved != null then
976 final_string.append(get_real_variable_name(alias_resolved))
978 final_string.append(i)
980 final_string.append(".")
983 return final_string.substring(0,final_string.length-1).to_s
986 #######################################################################
987 ## Print functions ##
988 #######################################################################
990 # Prints an object instance and its attributes if it has some
992 # If it is a primitive type, its value is directly printed
993 fun print_instance(instance: Instance)
995 if instance isa MutableInstance then
997 print "\ttype : {instance},"
1001 print instance.attributes.join(",\n\t"," : ")
1009 # Prints the attributes demanded in a SequenceRead
1010 # Used recursively to print nested collections
1011 fun print_nested_collection(instance: Instance, indexes: Array[Array[Int]], depth: Int, variable_name: String, depth_string: String)
1013 var collection: nullable SequenceRead[Object] = null
1014 var real_collection_length: nullable Int = null
1016 if instance isa MutableInstance then
1017 real_collection_length = get_collection_instance_real_length(instance)
1018 collection = get_primary_collection(instance)
1021 if collection != null and real_collection_length != null then
1022 for i in indexes[depth] do
1023 if i >= 0 and i < real_collection_length then
1024 if depth == indexes.length-1 then
1025 print "{variable_name}{depth_string}[{i}] = {collection[i]}"
1027 var item_i = collection[i]
1029 if item_i isa MutableInstance then
1030 print_nested_collection(item_i, indexes, depth+1, variable_name, depth_string+"[{i}]")
1032 print "The item at {variable_name}{depth_string}[{i}] is not a collection"
1037 print "Out of bounds exception : i = {i} and collection_length = {real_collection_length.to_s}"
1041 else if i >= real_collection_length then
1047 if collection == null then
1048 print "Cannot find {variable_name}{depth_string}"
1049 else if real_collection_length != null then
1050 print "Cannot find attribute length in {instance}"
1052 print "Unknown error."
1058 #######################################################################
1059 ## Variable Exploration functions ##
1060 #######################################################################
1062 # Seeks a variable from the current frame called 'variable_path
', can introspect complex objects using function get_variable_in_mutable_instance
1063 private fun seek_variable(variable_path: String, frame: Frame): nullable Instance
1065 var full_variable = variable_path.split_with(".")
1067 var full_variable_iterator = full_variable.iterator
1069 var first_instance = get_variable_in_frame(full_variable_iterator.item, frame)
1071 if first_instance == null then return null
1073 if full_variable.length <= 1 then return first_instance
1075 full_variable_iterator.next
1077 if not (first_instance isa MutableInstance and full_variable_iterator.is_ok) then return null
1079 return get_variable_in_mutable_instance(first_instance, full_variable_iterator)
1082 # Gets a variable 'variable_name
' contained in the frame 'frame
'
1083 private fun get_variable_in_frame(variable_name: String, frame: Frame): nullable Instance
1085 if variable_name == "self" then
1086 if frame.arguments.length >= 1 then return frame.arguments.first
1089 var map_of_instances = frame.map
1091 for key in map_of_instances.keys do
1092 if key.to_s == variable_name then
1093 return map_of_instances[key]
1100 # Gets an attribute 'attribute_name
' contained in variable 'variable
'
1101 fun get_attribute_in_mutable_instance(variable: MutableInstance, attribute_name: String): nullable MAttribute
1103 var map_of_attributes = variable.attributes
1105 for key in map_of_attributes.keys do
1106 if key.to_s.substring_from(1) == attribute_name then
1114 # Recursive function, returns the variable described by 'total_chain
'
1115 fun get_variable_in_mutable_instance(variable: MutableInstance, iterator: Iterator[String]): nullable Instance
1117 var attribute = get_attribute_in_mutable_instance(variable, iterator.item)
1119 if attribute == null then return null
1123 if iterator.is_ok then
1124 var new_variable = variable.attributes[attribute]
1125 if new_variable isa MutableInstance then
1126 return get_variable_in_mutable_instance(new_variable, iterator)
1131 return variable.attributes[attribute]
1135 #######################################################################
1136 ## Array exploring functions ##
1137 #######################################################################
1139 # Gets the length of a collection
1140 # Used by the debugger, else if we call Collection.length, it returns the capacity instead
1141 fun get_collection_instance_real_length(collection: MutableInstance): nullable Int
1143 var collection_length_attribute = get_attribute_in_mutable_instance(collection, "length")
1145 if collection_length_attribute != null then
1146 var primitive_length_instance = collection.attributes[collection_length_attribute]
1147 if primitive_length_instance isa PrimitiveInstance[Int] then
1148 return primitive_length_instance.val
1155 # Processes the indexes of a print array call
1156 # Returns an array containing all the indexes demanded
1157 fun process_index(index_string: String): nullable Array[Int]
1159 var from_end_index = index_string.chars.index_of('.')
1160 var to_start_index = index_string.chars.last_index_of('.')
1162 if from_end_index != -1 and to_start_index != -1 then
1163 var index_from_string = index_string.substring(0,from_end_index)
1164 var index_to_string = index_string.substring_from(to_start_index+1)
1166 if index_from_string.is_numeric and index_to_string.is_numeric then
1167 var result_array = new Array[Int]
1169 var index_from = index_from_string.to_i
1170 var index_to = index_to_string.to_i
1172 for i in [index_from..index_to] do
1173 result_array.push(i)
1179 if index_string.is_numeric
1181 var result_array = new Array[Int]
1183 result_array.push(index_string.to_i)
1194 # Gets a collection in a MutableInstance
1195 fun get_primary_collection(container: MutableInstance): nullable SequenceRead[Object]
1197 var items_of_array = get_attribute_in_mutable_instance(container, "items")
1198 if items_of_array != null then
1199 var array = container.attributes[items_of_array]
1201 if array isa PrimitiveInstance[Object] then
1202 var sequenceRead_final = array.val
1203 if sequenceRead_final isa SequenceRead[Object] then
1204 return sequenceRead_final
1212 # Removes the braces '[' ']' in a print array command
1213 # Returns an array containing their content
1214 fun remove_braces(braces: String): nullable Array[String]
1216 var buffer = new FlatBuffer
1218 var result_array = new Array[String]
1220 var number_of_opening_brackets = 0
1221 var number_of_closing_brackets = 0
1223 var last_was_opening_bracket = false
1225 for i in braces.chars do
1227 if last_was_opening_bracket then
1231 number_of_opening_brackets += 1
1232 last_was_opening_bracket = true
1233 else if i == ']' then
1234 if not last_was_opening_bracket then
1238 result_array.push(buffer.to_s)
1240 number_of_closing_brackets += 1
1241 last_was_opening_bracket = false
1242 else if i.is_numeric or i == '.' then
1243 buffer.append(i.to_s)
1244 else if not i == ' ' then
1249 if number_of_opening_brackets != number_of_closing_brackets then
1256 #######################################################################
1257 ## Breakpoint placing functions ##
1258 #######################################################################
1260 # Places a breakpoint on line 'line_to_break
' for file 'file_to_break
'
1261 fun place_breakpoint(breakpoint: Breakpoint)
1263 if not self.breakpoints.keys.has(breakpoint.file) then
1264 self.breakpoints[breakpoint.file] = new HashSet[Breakpoint]
1266 if find_breakpoint(breakpoint.file, breakpoint.line) == null then
1267 self.breakpoints[breakpoint.file].add(breakpoint)
1268 print "Breakpoint added on line {breakpoint.line} for file {breakpoint.file}"
1270 print "Breakpoint already present on line {breakpoint.line} for file {breakpoint.file}"
1274 #######################################################################
1275 ## Breakpoint removing functions ##
1276 #######################################################################
1278 # Removes a breakpoint on line 'line_to_break
' for file 'file_to_break
'
1279 fun remove_breakpoint(file_to_break: String, line_to_break: Int)
1281 if self.breakpoints.keys.has(file_to_break) then
1282 var bp = find_breakpoint(file_to_break, line_to_break)
1285 self.breakpoints[file_to_break].remove(bp)
1286 print "Breakpoint removed on line {line_to_break} for file {file_to_break}"
1291 print "No breakpoint existing on line {line_to_break} for file {file_to_break}"
1294 #######################################################################
1295 ## Breakpoint searching functions ##
1296 #######################################################################
1298 # Finds a breakpoint for 'file
' and 'line
' in the class HashMap
1299 fun find_breakpoint(file: String, line: Int): nullable Breakpoint
1301 if self.breakpoints.keys.has(file)
1303 for i in self.breakpoints[file]
1315 #######################################################################
1316 ## Runtime modification functions ##
1317 #######################################################################
1319 # Modifies the value of a variable contained in a frame
1320 fun modify_in_frame(variable: Instance, value: String)
1322 var new_variable = get_variable_of_type_with_value(variable.mtype.to_s, value)
1323 if new_variable != null
1325 var keys = frame.map.keys
1328 if frame.map[key] == variable
1330 frame.map[key] = new_variable
1336 # Modifies the value of a variable contained in a MutableInstance
1337 fun modify_argument_of_complex_type(papa: MutableInstance, attribute: MAttribute, value: String)
1339 var final_variable = papa.attributes[attribute]
1340 var type_of_variable = final_variable.mtype.to_s
1341 var new_variable = get_variable_of_type_with_value(type_of_variable, value)
1342 if new_variable != null
1344 papa.attributes[attribute] = new_variable
1348 #######################################################################
1349 ## Variable generator functions ##
1350 #######################################################################
1352 # Returns a new variable of the type 'type_of_variable
' with a value of 'value
'
1353 fun get_variable_of_type_with_value(type_of_variable: String, value: String): nullable Instance
1355 if type_of_variable == "Int" then
1356 return get_int(value)
1357 else if type_of_variable == "Float" then
1358 return get_float(value)
1359 else if type_of_variable == "Bool" then
1360 return get_bool(value)
1361 else if type_of_variable == "Char" then
1362 return get_char(value)
1368 # Returns a new int instance with value 'value
'
1369 fun get_int(value: String): nullable Instance
1371 if value.is_numeric then
1372 return int_instance(value.to_i)
1378 # Returns a new float instance with value 'value
'
1379 fun get_float(value:String): nullable Instance
1381 if value.is_numeric then
1382 return float_instance(value.to_f)
1388 # Returns a new char instance with value 'value
'
1389 fun get_char(value: String): nullable Instance
1391 if value.length >= 1 then
1392 return char_instance(value.chars[0])
1398 # Returns a new bool instance with value 'value
'
1399 fun get_bool(value: String): nullable Instance
1401 if value.to_lower == "true" then
1402 return self.true_instance
1403 else if value.to_lower == "false" then
1404 return self.false_instance
1406 print "Invalid value, a boolean must be set at \"true\" or \"false\""
1413 redef class AMethPropdef
1415 # Same as call except it will copy local variables of the parent frame to the frame defined in this call.
1416 # Not supposed to be used by anyone else than the Debugger.
1417 private fun rt_call(v: Debugger, mpropdef: MMethodDef, args: Array[Instance]): nullable Instance
1419 var f = new Frame(self, self.mpropdef.as(not null), args)
1420 var curr_instances = v.frame.map
1421 for i in curr_instances.keys do
1422 f.map[i] = curr_instances[i]
1424 call_commons(v,mpropdef,args,f)
1425 var currFra = v.frames.shift
1426 for i in curr_instances.keys do
1427 if currFra.map.keys.has(i) then
1428 curr_instances[i] = currFra.map[i]
1431 if v.returnmark == f then
1433 var res = v.escapevalue
1434 v.escapevalue = null
1442 # Traces the modifications of an object linked to a certain frame
1443 private class TraceObject
1445 # Map of the local names bound to a frame
1446 var trace_map = new HashMap[Frame, String]
1448 # Decides if breaking or printing statement when the variable is encountered
1449 var break_on_encounter: Bool
1451 # Adds the local alias for a variable and the frame bound to it
1452 fun add_frame_variable(frame: Frame, variable_name: String)
1454 self.trace_map[frame] = variable_name
1457 # Checks if the prompted variable is traced in the specified frame
1458 fun is_variable_traced_in_frame(variable_name: String, frame: Frame): Bool
1460 if self.trace_map.has_key(frame) then
1461 if self.trace_map[frame] == variable_name then
1473 # Breaks automatically when encountering an error
1474 # Permits the injunction of commands before crashing
1475 redef fun fatal(v: NaiveInterpreter, message: String)
1477 if v isa Debugger then
1478 print "An error was encountered, the program will stop now."
1480 while v.process_debug_command(gets) do end